Skip to content

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

Add a wgpu renderer and offscreen render CLI for native avatars

shinshin8687fa6166d719
diff --git a/native/Cargo.lock b/native/Cargo.lock
index 671c1ee..2149747 100644
--- a/native/Cargo.lock
+++ b/native/Cargo.lock
@@ -8,6 +8,15 @@ version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
+[[package]]
+name = "android_system_properties"
+version = "0.1.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc"
+dependencies = [
+ "libc",
+]
+
[[package]]
name = "anyhow"
version = "1.0.104"
@@ -23,18 +32,136 @@ dependencies = [
"derive_arbitrary",
]
+[[package]]
+name = "arrayvec"
+version = "0.7.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56"
+
+[[package]]
+name = "ash"
+version = "0.38.0+1.3.281"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0bb44936d800fea8f016d7f2311c6a4f97aebd5dc86f09906139ec848cf3a46f"
+dependencies = [
+ "libloading",
+]
+
+[[package]]
+name = "autocfg"
+version = "1.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
+
+[[package]]
+name = "bit-set"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3"
+dependencies = [
+ "bit-vec",
+]
+
+[[package]]
+name = "bit-vec"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"
+
[[package]]
name = "bitflags"
version = "1.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
+[[package]]
+name = "bitflags"
+version = "2.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
+
+[[package]]
+name = "block"
+version = "0.1.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0d8c1fef690941d3e7788d328517591fecc684c084084702d6ff1641e993699a"
+
+[[package]]
+name = "bumpalo"
+version = "3.20.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
+
+[[package]]
+name = "bytemuck"
+version = "1.25.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"
+dependencies = [
+ "bytemuck_derive",
+]
+
+[[package]]
+name = "bytemuck_derive"
+version = "1.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.9",
+]
+
[[package]]
name = "cfg-if"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
+[[package]]
+name = "cfg_aliases"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
+
+[[package]]
+name = "codespan-reporting"
+version = "0.12.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fe6d2e5af09e8c8ad56c969f2157a3d4238cebc7c55f0a517728c38f7b200f81"
+dependencies = [
+ "serde",
+ "termcolor",
+ "unicode-width",
+]
+
+[[package]]
+name = "core-foundation"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6"
+dependencies = [
+ "core-foundation-sys",
+ "libc",
+]
+
+[[package]]
+name = "core-foundation-sys"
+version = "0.8.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
+
+[[package]]
+name = "core-graphics-types"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb"
+dependencies = [
+ "bitflags 2.13.2",
+ "core-foundation",
+ "libc",
+]
+
[[package]]
name = "crc32fast"
version = "1.5.3"
@@ -50,6 +177,12 @@ version = "0.8.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"
+[[package]]
+name = "crunchy"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
+
[[package]]
name = "derive_arbitrary"
version = "1.5.0"
@@ -58,7 +191,16 @@ checksum = "1b034bd7d5f032402a2479444dcc6f74e36a03f31854d41680fb240ef682a1ac"
dependencies = [
"proc-macro2",
"quote",
- "syn",
+ "syn 3.0.9",
+]
+
+[[package]]
+name = "document-features"
+version = "0.2.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61"
+dependencies = [
+ "litrs",
]
[[package]]
@@ -87,12 +229,194 @@ dependencies = [
"zlib-rs",
]
+[[package]]
+name = "foldhash"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
+
+[[package]]
+name = "foldhash"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
+
+[[package]]
+name = "foreign-types"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965"
+dependencies = [
+ "foreign-types-macros",
+ "foreign-types-shared",
+]
+
+[[package]]
+name = "foreign-types-macros"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ea5190182e6915eb873ddbc16e23b711b6eb1f9c00a0d0a3a91b5f6228475225"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.9",
+]
+
+[[package]]
+name = "foreign-types-shared"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b"
+
+[[package]]
+name = "futures-core"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"
+
+[[package]]
+name = "futures-task"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"
+
+[[package]]
+name = "futures-util"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"
+dependencies = [
+ "futures-core",
+ "futures-task",
+ "pin-project-lite",
+ "slab",
+]
+
+[[package]]
+name = "gl_generator"
+version = "0.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1a95dfc23a2b4a9a2f5ab41d194f8bfda3cabec42af4e39f08c339eb2a0c124d"
+dependencies = [
+ "khronos_api",
+ "log",
+ "xml-rs",
+]
+
+[[package]]
+name = "glow"
+version = "0.16.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c5e5ea60d70410161c8bf5da3fdfeaa1c72ed2c15f8bbb9d19fe3a4fad085f08"
+dependencies = [
+ "js-sys",
+ "slotmap",
+ "wasm-bindgen",
+ "web-sys",
+]
+
+[[package]]
+name = "glutin_wgl_sys"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2c4ee00b289aba7a9e5306d57c2d05499b2e5dc427f84ac708bd2c090212cf3e"
+dependencies = [
+ "gl_generator",
+]
+
+[[package]]
+name = "gpu-alloc"
+version = "0.6.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "45cf04b2726f02df5508c6de726acdc90cdf97ac771a9a0ffd8ba10a6e696bf9"
+dependencies = [
+ "bitflags 2.13.2",
+ "gpu-alloc-types",
+]
+
+[[package]]
+name = "gpu-alloc-types"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b2bbed164dd10ed526c2e4fe3e721ca4a71c61730e5aafac6844b417b3227058"
+dependencies = [
+ "bitflags 2.13.2",
+]
+
+[[package]]
+name = "gpu-allocator"
+version = "0.27.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c151a2a5ef800297b4e79efa4f4bec035c5f51d5ae587287c9b952bdf734cacd"
+dependencies = [
+ "log",
+ "presser",
+ "thiserror 1.0.69",
+ "windows",
+]
+
+[[package]]
+name = "gpu-descriptor"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b89c83349105e3732062a895becfc71a8f921bb71ecbbdd8ff99263e3b53a0ca"
+dependencies = [
+ "bitflags 2.13.2",
+ "gpu-descriptor-types",
+ "hashbrown 0.15.5",
+]
+
+[[package]]
+name = "gpu-descriptor-types"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fdf242682df893b86f33a73828fb09ca4b2d3bb6cc95249707fc684d27484b91"
+dependencies = [
+ "bitflags 2.13.2",
+]
+
+[[package]]
+name = "half"
+version = "2.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b"
+dependencies = [
+ "cfg-if",
+ "crunchy",
+ "num-traits",
+ "zerocopy",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.15.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"
+dependencies = [
+ "foldhash 0.1.5",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.16.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
+dependencies = [
+ "foldhash 0.2.0",
+]
+
[[package]]
name = "hashbrown"
version = "0.17.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
+[[package]]
+name = "hexf-parse"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dfa686283ad6dd069f105e5ab091b04c62850d3e4cf5d67debad1933f55023df"
+
[[package]]
name = "indexmap"
version = "2.14.2"
@@ -100,7 +424,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
dependencies = [
"equivalent",
- "hashbrown",
+ "hashbrown 0.17.1",
]
[[package]]
@@ -109,6 +433,114 @@ version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
+[[package]]
+name = "jni-sys"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258"
+dependencies = [
+ "jni-sys 0.4.1",
+]
+
+[[package]]
+name = "jni-sys"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2"
+dependencies = [
+ "jni-sys-macros",
+]
+
+[[package]]
+name = "jni-sys-macros"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264"
+dependencies = [
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "js-sys"
+version = "0.3.106"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5"
+dependencies = [
+ "cfg-if",
+ "futures-util",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "khronos-egl"
+version = "6.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6aae1df220ece3c0ada96b8153459b67eebe9ae9212258bb0134ae60416fdf76"
+dependencies = [
+ "libc",
+ "libloading",
+ "pkg-config",
+]
+
+[[package]]
+name = "khronos_api"
+version = "3.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc"
+
+[[package]]
+name = "libc"
+version = "0.2.191"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
+
+[[package]]
+name = "libloading"
+version = "0.8.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55"
+dependencies = [
+ "cfg-if",
+ "windows-link",
+]
+
+[[package]]
+name = "libm"
+version = "0.2.16"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
+
+[[package]]
+name = "litrs"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4744e383959f0db86ede514b809b1c53251889093803c05267acc7d4e7030d70"
+
+[[package]]
+name = "lock_api"
+version = "0.4.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
+dependencies = [
+ "scopeguard",
+]
+
+[[package]]
+name = "log"
+version = "0.4.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
+
+[[package]]
+name = "malloc_buf"
+version = "0.0.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "62bb907fe88d54d8d9ce32a3cceab4218ed2f6b7d35617cafe9adf84e43919cb"
+dependencies = [
+ "libc",
+]
+
[[package]]
name = "memchr"
version = "2.8.3"
@@ -134,7 +566,29 @@ version = "0.1.0"
name = "mesh-avatar-wgpu"
version = "0.1.0"
dependencies = [
+ "anyhow",
+ "bytemuck",
"mesh-avatar-core",
+ "png",
+ "pollster",
+ "serde",
+ "serde_json",
+ "wgpu",
+]
+
+[[package]]
+name = "metal"
+version = "0.32.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "00c15a6f673ff72ddcc22394663290f870fb224c1bfce55734a75c414150e605"
+dependencies = [
+ "bitflags 2.13.2",
+ "block",
+ "core-graphics-types",
+ "foreign-types",
+ "log",
+ "objc",
+ "paste",
]
[[package]]
@@ -158,38 +612,226 @@ dependencies = [
]
[[package]]
-name = "png"
-version = "0.17.16"
+name = "naga"
+version = "27.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526"
+checksum = "066cf25f0e8b11ee0df221219010f213ad429855f57c494f995590c861a9a7d8"
dependencies = [
- "bitflags",
- "crc32fast",
- "fdeflate",
- "flate2",
- "miniz_oxide 0.8.9",
+ "arrayvec",
+ "bit-set",
+ "bitflags 2.13.2",
+ "cfg-if",
+ "cfg_aliases",
+ "codespan-reporting",
+ "half",
+ "hashbrown 0.16.1",
+ "hexf-parse",
+ "indexmap",
+ "libm",
+ "log",
+ "num-traits",
+ "once_cell",
+ "rustc-hash",
+ "spirv",
+ "thiserror 2.0.21",
+ "unicode-ident",
]
[[package]]
-name = "proc-macro2"
-version = "1.0.107"
+name = "ndk-sys"
+version = "0.6.0+11769913"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
+checksum = "ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873"
dependencies = [
- "unicode-ident",
+ "jni-sys 0.3.1",
]
[[package]]
-name = "quote"
-version = "1.0.47"
+name = "num-traits"
+version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
- "proc-macro2",
+ "autocfg",
+ "libm",
]
[[package]]
-name = "serde"
+name = "objc"
+version = "0.2.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "915b1b472bc21c53464d6c8461c9d3af805ba1ef837e1cac254428f4a77177b1"
+dependencies = [
+ "malloc_buf",
+]
+
+[[package]]
+name = "once_cell"
+version = "1.21.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
+
+[[package]]
+name = "ordered-float"
+version = "5.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8c7c9e0d9b23589f26070720bac724174bfec1083e82f7854cdd0267518343c0"
+dependencies = [
+ "num-traits",
+]
+
+[[package]]
+name = "parking_lot"
+version = "0.12.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
+dependencies = [
+ "lock_api",
+ "parking_lot_core",
+]
+
+[[package]]
+name = "parking_lot_core"
+version = "0.9.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "redox_syscall",
+ "smallvec",
+ "windows-link",
+]
+
+[[package]]
+name = "paste"
+version = "1.0.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
+
+[[package]]
+name = "pin-project-lite"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
+
+[[package]]
+name = "pkg-config"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
+
+[[package]]
+name = "png"
+version = "0.17.16"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526"
+dependencies = [
+ "bitflags 1.3.2",
+ "crc32fast",
+ "fdeflate",
+ "flate2",
+ "miniz_oxide 0.8.9",
+]
+
+[[package]]
+name = "pollster"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2f3a9f18d041e6d0e102a0a46750538147e5e8992d3b4873aaafee2520b00ce3"
+
+[[package]]
+name = "portable-atomic"
+version = "1.15.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85"
+
+[[package]]
+name = "portable-atomic-util"
+version = "0.2.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715"
+dependencies = [
+ "portable-atomic",
+]
+
+[[package]]
+name = "presser"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e8cf8e6a8aa66ce33f63993ffc4ea4271eb5b0530a9002db8455ea6050c77bfa"
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.107"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "profiling"
+version = "1.0.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5"
+
+[[package]]
+name = "quote"
+version = "1.0.47"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "range-alloc"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ca45419789ae5a7899559e9512e58ca889e41f04f1f2445e9f4b290ceccd1d08"
+
+[[package]]
+name = "raw-window-handle"
+version = "0.6.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539"
+
+[[package]]
+name = "redox_syscall"
+version = "0.5.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
+dependencies = [
+ "bitflags 2.13.2",
+]
+
+[[package]]
+name = "renderdoc-sys"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832"
+
+[[package]]
+name = "rustc-hash"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2"
+
+[[package]]
+name = "rustversion"
+version = "1.0.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
+
+[[package]]
+name = "scopeguard"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
+
+[[package]]
+name = "serde"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
@@ -215,7 +857,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
- "syn",
+ "syn 3.0.9",
]
[[package]]
@@ -237,6 +879,53 @@ version = "0.3.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
+[[package]]
+name = "slab"
+version = "0.4.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
+
+[[package]]
+name = "slotmap"
+version = "1.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bdd58c3c93c3d278ca835519292445cb4b0d4dc59ccfdf7ceadaab3f8aeb4038"
+dependencies = [
+ "version_check",
+]
+
+[[package]]
+name = "smallvec"
+version = "1.16.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8"
+
+[[package]]
+name = "spirv"
+version = "0.3.0+sdk-1.3.268.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "eda41003dc44290527a59b13432d4a0379379fa074b70174882adfbdfd917844"
+dependencies = [
+ "bitflags 2.13.2",
+]
+
+[[package]]
+name = "static_assertions"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
+
+[[package]]
+name = "syn"
+version = "2.0.119"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
[[package]]
name = "syn"
version = "3.0.9"
@@ -248,12 +937,477 @@ dependencies = [
"unicode-ident",
]
+[[package]]
+name = "termcolor"
+version = "1.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755"
+dependencies = [
+ "winapi-util",
+]
+
+[[package]]
+name = "thiserror"
+version = "1.0.69"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"
+dependencies = [
+ "thiserror-impl 1.0.69",
+]
+
+[[package]]
+name = "thiserror"
+version = "2.0.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"
+dependencies = [
+ "thiserror-impl 2.0.21",
+]
+
+[[package]]
+name = "thiserror-impl"
+version = "1.0.69"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "thiserror-impl"
+version = "2.0.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.9",
+]
+
+[[package]]
+name = "tokio"
+version = "1.54.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3"
+dependencies = [
+ "pin-project-lite",
+]
+
[[package]]
name = "unicode-ident"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
+[[package]]
+name = "unicode-width"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"
+
+[[package]]
+name = "version_check"
+version = "0.9.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
+
+[[package]]
+name = "wasm-bindgen"
+version = "0.2.129"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409"
+dependencies = [
+ "cfg-if",
+ "once_cell",
+ "rustversion",
+ "wasm-bindgen-macro",
+ "wasm-bindgen-shared",
+]
+
+[[package]]
+name = "wasm-bindgen-futures"
+version = "0.4.79"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e"
+dependencies = [
+ "js-sys",
+ "tokio",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "wasm-bindgen-macro"
+version = "0.2.129"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535"
+dependencies = [
+ "quote",
+ "wasm-bindgen-macro-support",
+]
+
+[[package]]
+name = "wasm-bindgen-macro-support"
+version = "0.2.129"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7"
+dependencies = [
+ "bumpalo",
+ "proc-macro2",
+ "quote",
+ "syn 3.0.9",
+ "wasm-bindgen-shared",
+]
+
+[[package]]
+name = "wasm-bindgen-shared"
+version = "0.2.129"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "web-sys"
+version = "0.3.106"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4"
+dependencies = [
+ "js-sys",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "wgpu"
+version = "27.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bfe68bac7cde125de7a731c3400723cadaaf1703795ad3f4805f187459cd7a77"
+dependencies = [
+ "arrayvec",
+ "bitflags 2.13.2",
+ "cfg-if",
+ "cfg_aliases",
+ "document-features",
+ "hashbrown 0.16.1",
+ "js-sys",
+ "log",
+ "naga",
+ "parking_lot",
+ "portable-atomic",
+ "profiling",
+ "raw-window-handle",
+ "smallvec",
+ "static_assertions",
+ "wasm-bindgen",
+ "wasm-bindgen-futures",
+ "web-sys",
+ "wgpu-core",
+ "wgpu-hal",
+ "wgpu-types",
+]
+
+[[package]]
+name = "wgpu-core"
+version = "27.0.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "27a75de515543b1897b26119f93731b385a19aea165a1ec5f0e3acecc229cae7"
+dependencies = [
+ "arrayvec",
+ "bit-set",
+ "bit-vec",
+ "bitflags 2.13.2",
+ "bytemuck",
+ "cfg_aliases",
+ "document-features",
+ "hashbrown 0.16.1",
+ "indexmap",
+ "log",
+ "naga",
+ "once_cell",
+ "parking_lot",
+ "portable-atomic",
+ "profiling",
+ "raw-window-handle",
+ "rustc-hash",
+ "smallvec",
+ "thiserror 2.0.21",
+ "wgpu-core-deps-apple",
+ "wgpu-core-deps-emscripten",
+ "wgpu-core-deps-windows-linux-android",
+ "wgpu-hal",
+ "wgpu-types",
+]
+
+[[package]]
+name = "wgpu-core-deps-apple"
+version = "27.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0772ae958e9be0c729561d5e3fd9a19679bcdfb945b8b1a1969d9bfe8056d233"
+dependencies = [
+ "wgpu-hal",
+]
+
+[[package]]
+name = "wgpu-core-deps-emscripten"
+version = "27.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b06ac3444a95b0813ecfd81ddb2774b66220b264b3e2031152a4a29fda4da6b5"
+dependencies = [
+ "wgpu-hal",
+]
+
+[[package]]
+name = "wgpu-core-deps-windows-linux-android"
+version = "27.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "71197027d61a71748e4120f05a9242b2ad142e3c01f8c1b47707945a879a03c3"
+dependencies = [
+ "wgpu-hal",
+]
+
+[[package]]
+name = "wgpu-hal"
+version = "27.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5b21cb61c57ee198bc4aff71aeadff4cbb80b927beb912506af9c780d64313ce"
+dependencies = [
+ "android_system_properties",
+ "arrayvec",
+ "ash",
+ "bit-set",
+ "bitflags 2.13.2",
+ "block",
+ "bytemuck",
+ "cfg-if",
+ "cfg_aliases",
+ "core-graphics-types",
+ "glow",
+ "glutin_wgl_sys",
+ "gpu-alloc",
+ "gpu-allocator",
+ "gpu-descriptor",
+ "hashbrown 0.16.1",
+ "js-sys",
+ "khronos-egl",
+ "libc",
+ "libloading",
+ "log",
+ "metal",
+ "naga",
+ "ndk-sys",
+ "objc",
+ "once_cell",
+ "ordered-float",
+ "parking_lot",
+ "portable-atomic",
+ "portable-atomic-util",
+ "profiling",
+ "range-alloc",
+ "raw-window-handle",
+ "renderdoc-sys",
+ "smallvec",
+ "thiserror 2.0.21",
+ "wasm-bindgen",
+ "web-sys",
+ "wgpu-types",
+ "windows",
+ "windows-core",
+]
+
+[[package]]
+name = "wgpu-types"
+version = "27.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "afdcf84c395990db737f2dd91628706cb31e86d72e53482320d368e52b5da5eb"
+dependencies = [
+ "bitflags 2.13.2",
+ "bytemuck",
+ "js-sys",
+ "log",
+ "thiserror 2.0.21",
+ "web-sys",
+]
+
+[[package]]
+name = "winapi-util"
+version = "0.1.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
+dependencies = [
+ "windows-sys",
+]
+
+[[package]]
+name = "windows"
+version = "0.58.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dd04d41d93c4992d421894c18c8b43496aa748dd4c081bac0dc93eb0489272b6"
+dependencies = [
+ "windows-core",
+ "windows-targets",
+]
+
+[[package]]
+name = "windows-core"
+version = "0.58.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6ba6d44ec8c2591c134257ce647b7ea6b20335bf6379a27dac5f1641fcf59f99"
+dependencies = [
+ "windows-implement",
+ "windows-interface",
+ "windows-result",
+ "windows-strings",
+ "windows-targets",
+]
+
+[[package]]
+name = "windows-implement"
+version = "0.58.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2bbd5b46c938e506ecbce286b6628a02171d56153ba733b6c741fc627ec9579b"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "windows-interface"
+version = "0.58.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "053c4c462dc91d3b1504c6fe5a726dd15e216ba718e84a0e46a88fbe5ded3515"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "windows-link"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
+
+[[package]]
+name = "windows-result"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1d1043d8214f791817bab27572aaa8af63732e11bf84aa21a45a78d6c317ae0e"
+dependencies = [
+ "windows-targets",
+]
+
+[[package]]
+name = "windows-strings"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4cd9b125c486025df0eabcb585e62173c6c9eddcec5d117d3b6e8c30e2ee4d10"
+dependencies = [
+ "windows-result",
+ "windows-targets",
+]
+
+[[package]]
+name = "windows-sys"
+version = "0.61.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
+dependencies = [
+ "windows-link",
+]
+
+[[package]]
+name = "windows-targets"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
+dependencies = [
+ "windows_aarch64_gnullvm",
+ "windows_aarch64_msvc",
+ "windows_i686_gnu",
+ "windows_i686_gnullvm",
+ "windows_i686_msvc",
+ "windows_x86_64_gnu",
+ "windows_x86_64_gnullvm",
+ "windows_x86_64_msvc",
+]
+
+[[package]]
+name = "windows_aarch64_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
+
+[[package]]
+name = "windows_aarch64_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
+
+[[package]]
+name = "windows_i686_gnu"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
+
+[[package]]
+name = "windows_i686_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
+
+[[package]]
+name = "windows_i686_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
+
+[[package]]
+name = "windows_x86_64_gnu"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
+
+[[package]]
+name = "windows_x86_64_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
+
+[[package]]
+name = "windows_x86_64_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
+
+[[package]]
+name = "xml-rs"
+version = "0.8.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7"
+
+[[package]]
+name = "zerocopy"
+version = "0.8.63"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8"
+dependencies = [
+ "zerocopy-derive",
+]
+
+[[package]]
+name = "zerocopy-derive"
+version = "0.8.63"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
[[package]]
name = "zip"
version = "2.6.1"
diff --git a/native/Cargo.toml b/native/Cargo.toml
index ae40e51..d93a952 100644
--- a/native/Cargo.toml
+++ b/native/Cargo.toml
@@ -15,3 +15,6 @@ serde = { version = "1", features = ["derive"] }
serde_json = { version = "1", features = ["float_roundtrip"] }
png = "0.17"
zip = { version = "2", default-features = false }
+wgpu = "27"
+pollster = "0.4"
+bytemuck = { version = "1", features = ["derive"] }
diff --git a/native/conformance/compare-pixels.mjs b/native/conformance/compare-pixels.mjs
new file mode 100644
index 0000000..7d08f45
--- /dev/null
+++ b/native/conformance/compare-pixels.mjs
@@ -0,0 +1,171 @@
+// Local-only Chromium/WebGL and wgpu comparison. Outputs stay under native/target/.
+import { readFile, writeFile, mkdir } from 'node:fs/promises';
+import { execFile, execFileSync } from 'node:child_process';
+import { promisify } from 'node:util';
+import { fileURLToPath } from 'node:url';
+import { resolve, relative } from 'node:path';
+import { createServer } from 'vite';
+import { chromium } from '@playwright/test';
+import { PNG } from 'pngjs';
+
+const root = fileURLToPath(new URL('../../', import.meta.url));
+const noAA = process.argv.includes('--no-aa');
+const metal = process.argv.includes('--metal');
+const dpr = process.argv.includes('--dpr=2') ? 2 : 1;
+const out = resolve(root, `native/target/pixel-comparison${metal ? '-metal' : ''}${noAA ? '-no-aa' : ''}${dpr === 2 ? '-dpr2' : ''}`);
+const project = resolve(root, 'samples/miko-qipao');
+const baselineOnly = process.argv.includes('--baseline-only');
+const allPoses = [
+ { name: 'rest', parameters: {} },
+ { name: 'half-eyes', parameters: { eyeLOpen: 0.5, eyeROpen: 0.5 } },
+ { name: 'closed-eyes', parameters: { eyeLOpen: 0, eyeROpen: 0, eyeSmile: 1 } },
+ { name: 'mouth-a', parameters: { mouthOpen: 0.8 } },
+ { name: 'mouth-i', parameters: { mouthOpen: 0.8, mouthForm: -1 } },
+ { name: 'gaze-blush', parameters: { gazeX: 1, gazeY: -0.7, blush: 1 } },
+ { name: 'turn-left', parameters: { angleX: -30, angleY: 10, angleZ: -15, bodyAngleZ: 8, breath: 1 } },
+ { name: 'turn-right', parameters: { angleX: 30, angleY: -10, angleZ: 15 } },
+ { name: 'sad', parameters: {}, expression: 'sad', seconds: 1 },
+ { name: 'painted-mouth-lids', parameters: { eyeLOpen: 0.2, eyeROpen: 0.5, eyeSmile: 0.9, mouthOpen: 0.9, mouthForm: 0.7, blush: 1 }, noSprites: true },
+ { name: 'cover-wide', parameters: { gazeX: -1, mouthOpen: 0.75, mouthForm: 0.7 }, size: [640, 360], fit: 'cover', padTop: 0.1, padSide: 0.12 },
+ { name: 'contain-odd', parameters: { angleX: 20, angleZ: -10 }, size: [333, 501], padTop: 0.1, padSide: 0.1 },
+];
+const poses = dpr === 2 ? allPoses.filter(p => ['rest', 'cover-wide', 'contain-odd'].includes(p.name))
+ .map(p => ({ ...p, size: (p.size ?? [512, 640]).map(v => Math.ceil(v / dpr) * dpr) })) : allPoses;
+const run = promisify(execFile);
+
+function metrics(a, b) {
+ let rawMax = 0, rawSum = 0, rawOver = 0, pmMax = 0, pmSum = 0, pmOver = 0, alphaMax = 0;
+ const diff = new PNG({ width: a.width, height: a.height });
+ for (let i = 0; i < a.data.length; i += 4) {
+ let pixelRaw = 0, pixelPm = 0;
+ for (let c = 0; c < 4; c++) {
+ const raw = Math.abs(a.data[i + c] - b.data[i + c]);
+ const pm = c === 3 ? raw : Math.abs(a.data[i + c] * a.data[i + 3] / 255 - b.data[i + c] * b.data[i + 3] / 255);
+ rawMax = Math.max(rawMax, raw); rawSum += raw; pmMax = Math.max(pmMax, pm); pmSum += pm;
+ pixelRaw = Math.max(pixelRaw, raw); pixelPm = Math.max(pixelPm, pm);
+ if (c < 3) diff.data[i + c] = Math.min(255, Math.round(pm * 8));
+ }
+ alphaMax = Math.max(alphaMax, Math.abs(a.data[i + 3] - b.data[i + 3]));
+ rawOver += pixelRaw > 8 ? 1 : 0; pmOver += pixelPm > 8 ? 1 : 0;
+ diff.data[i + 3] = 255;
+ }
+ const pixels = a.width * a.height;
+ return { raw: { max: rawMax, mean: rawSum / a.data.length, percentOver8: rawOver / pixels * 100 },
+ premultiplied: { max: pmMax, mean: pmSum / a.data.length, percentOver8: pmOver / pixels * 100 }, alphaMax, diff };
+}
+
+async function main() {
+ await mkdir(out, { recursive: true });
+ const rig = JSON.parse(await readFile(resolve(project, 'rig.json'), 'utf8'));
+ const metadata = JSON.parse(await readFile(resolve(project, 'built/layers.json'), 'utf8'));
+ const sprites = JSON.parse(await readFile(resolve(project, 'built/sprites/sprites.json'), 'utf8'));
+ const assets = {};
+ for (const name of ['layers.json', 'base.png', 'hairmask.png', ...Object.keys(metadata.layers).map(name => `${name}.png`),
+ 'sprites/sprites.json', ...Object.keys(sprites.layers).map(name => `sprites/${name}.png`)]) {
+ const mime = name.endsWith('.png') ? 'image/png' : 'application/json';
+ assets[name] = `data:${mime};base64,${(await readFile(resolve(project, 'built', name))).toString('base64')}`;
+ }
+ const server = await createServer({ root, configFile: false, publicDir: false, appType: 'custom', cacheDir: 'node_modules/.vite-native-pixels',
+ optimizeDeps: { noDiscovery: true, entries: [] }, logLevel: 'error',
+ plugins: [{ name: 'native-pixel-page', configureServer(server) {
+ server.middlewares.use((req, res, next) => {
+ if (req.url !== '/__native_compare__') return next();
+ res.setHeader('Content-Type', 'text/html'); res.end('<!doctype html><body style="margin:0"><canvas id="avatar"></canvas>');
+ });
+ } }], server: { host: '127.0.0.1', port: 0, hmr: false, watch: null, preTransformRequests: false } });
+ let browser;
+ try {
+ await server.listen();
+ const origin = `http://127.0.0.1:${server.httpServer.address().port}`;
+ browser = await chromium.launch(metal ? { args: ['--use-angle=metal'] } : {});
+ const page = await browser.newPage({ viewport: { width: 1024, height: 1024 }, deviceScaleFactor: dpr });
+ const errors = []; page.on('pageerror', error => errors.push(error.message));
+ await page.route('**/*', route => new URL(route.request().url()).origin === origin ? route.continue() : route.abort());
+ await page.goto(`${origin}/__native_compare__`);
+ const baseline = await page.evaluate(async ({ rig, assets, poses, noAA, dpr }) => {
+ const { createMeshAvatar, PARAMS } = await import('/packages/runtime/src/index.ts');
+ const { seededRandom } = await import('/tools/motion-scenarios.mjs');
+ const canvas = document.getElementById('avatar'), results = [];
+ if (noAA) canvas.getContext('webgl2', { premultipliedAlpha: true, antialias: false, alpha: true, preserveDrawingBuffer: true });
+ const defaults = Object.fromEntries(PARAMS.map(p => [p.id, p.def]));
+ for (const pose of poses) {
+ Math.random = seededRandom(0);
+ const size = pose.size ?? [512, 640]; canvas.style.width = `${size[0] / dpr}px`; canvas.style.height = `${size[1] / dpr}px`;
+ const images = { ...assets }; if (pose.noSprites) delete images['sprites/sprites.json'];
+ const avatar = await createMeshAvatar(canvas, { rig, assets: images, manual: true, fit: pose.fit ?? 'contain',
+ padTop: pose.padTop ?? rig.view.padTop, padSide: pose.padSide ?? rig.view.padSide });
+ avatar.setAutoIdle(false); avatar.setAutoMotion(false); avatar.setParameters({ ...defaults, ...pose.parameters });
+ if (pose.expression) avatar.setExpression(pose.expression);
+ avatar.advance(0); if (pose.seconds) avatar.advance(pose.seconds, 60);
+ const gl = canvas.getContext('webgl2'), ext = gl.getExtension('WEBGL_debug_renderer_info');
+ results.push({ name: pose.name, image: canvas.toDataURL(), samples: gl.getParameter(gl.SAMPLES),
+ renderer: ext ? gl.getParameter(ext.UNMASKED_RENDERER_WEBGL) : gl.getParameter(gl.RENDERER) });
+ avatar.destroy();
+ }
+ return results;
+ }, { rig, assets, poses, noAA, dpr });
+ if (errors.length) throw new Error(errors.join('\n'));
+ for (const item of baseline) await writeFile(resolve(out, `${item.name}-js.png`), Buffer.from(item.image.split(',')[1], 'base64'));
+ await writeFile(resolve(out, 'baseline.json'), JSON.stringify(baseline.map(({ image: _image, ...info }) => info), null, 2) + '\n');
+ console.log(`Saved ${baseline.length} Chromium baseline images`);
+ if (baselineOnly) return;
+ execFileSync('cargo', ['build', '-p', 'mesh-avatar-wgpu', '--bin', 'mesh-avatar-render'], { cwd: resolve(root, 'native'), stdio: 'inherit' });
+ const reports = [], gallery = [];
+ let nativeRenderer;
+ for (const [i, pose] of poses.entries()) {
+ const posePath = resolve(out, `${pose.name}-params.json`), nativePath = resolve(out, `${pose.name}-native.png`);
+ await writeFile(posePath, JSON.stringify(pose.parameters) + '\n');
+ const size = pose.size ?? [512, 640];
+ const args = [project, '--pose', posePath, '--seconds', String(pose.seconds ?? 0), '--size', size.join('x'),
+ '--samples', String(baseline[i].samples || 1), '-o', nativePath];
+ if (pose.fit) args.push('--fit', pose.fit);
+ if (pose.padTop !== undefined) args.push('--pad-top', String(pose.padTop));
+ if (pose.padSide !== undefined) args.push('--pad-side', String(pose.padSide));
+ if (pose.expression) args.push('--expression', pose.expression);
+ if (pose.noSprites) args.push('--no-sprites');
+ const { stderr } = await run(resolve(root, 'native/target/debug/mesh-avatar-render'), args, { cwd: root });
+ process.stderr.write(stderr);
+ nativeRenderer ??= stderr.split('\n').find(line => line.startsWith('GPU:'));
+ const nativeBytes = await readFile(nativePath);
+ const a = PNG.sync.read(Buffer.from(baseline[i].image.split(',')[1], 'base64')), b = PNG.sync.read(nativeBytes);
+ if (a.width !== b.width || a.height !== b.height) throw new Error(`Image size mismatch: ${pose.name}`);
+ const { diff, ...stats } = metrics(a, b), diffBytes = PNG.sync.write(diff);
+ await writeFile(resolve(out, `${pose.name}-diff.png`), diffBytes);
+ reports.push({ name: pose.name, size, samples: baseline[i].samples, ...stats });
+ gallery.push({ name: pose.name, images: [baseline[i].image, `data:image/png;base64,${nativeBytes.toString('base64')}`, `data:image/png;base64,${diffBytes.toString('base64')}`] });
+ console.log(`${pose.name}: raw max ${stats.raw.max}, mean ${stats.raw.mean.toFixed(4)}, >8 ${stats.raw.percentOver8.toFixed(3)}%; premult max ${stats.premultiplied.max.toFixed(2)}, mean ${stats.premultiplied.mean.toFixed(4)}, >8 ${stats.premultiplied.percentOver8.toFixed(3)}%`);
+ }
+ const sheets = await page.evaluate(async gallery => {
+ const sheets = [];
+ for (const [index, row] of gallery.entries()) {
+ const sheet = document.createElement('canvas'); sheet.width = 1536; sheet.height = 680;
+ const ctx = sheet.getContext('2d'); ctx.fillStyle = '#dedfe5'; ctx.fillRect(0, 0, sheet.width, sheet.height);
+ for (const [i, url] of row.images.entries()) {
+ const image = new Image(); image.src = url; await image.decode();
+ const scale = Math.min(512 / image.width, 640 / image.height);
+ ctx.drawImage(image, i * 512 + (512 - image.width * scale) / 2, 40, image.width * scale, image.height * scale);
+ ctx.fillStyle = '#171b23'; ctx.font = '18px sans-serif'; ctx.fillText(`${row.name}: ${['Chromium', 'wgpu', 'premult diff x8'][i]}`, i * 512 + 12, 27);
+ }
+ sheets.push({ name: `${row.name}-comparison.png`, url: sheet.toDataURL() });
+ if (index === 0) {
+ const image = new Image(); image.src = row.images[1]; await image.decode();
+ const crop = document.createElement('canvas'); crop.width = 900; crop.height = 700;
+ const c = crop.getContext('2d'); c.fillStyle = '#dedfe5'; c.fillRect(0, 0, 900, 700);
+ c.drawImage(image, image.width * 0.26, image.height * 0.18, image.width * 0.48, image.height * 0.34, 0, 0, 900, 700);
+ sheets.push({ name: 'rest-native-face.png', url: crop.toDataURL() });
+ }
+ }
+ return sheets;
+ }, gallery);
+ for (const sheet of sheets) await writeFile(resolve(out, sheet.name), Buffer.from(sheet.url.split(',')[1], 'base64'));
+ await writeFile(resolve(out, 'report.json'), JSON.stringify({ threshold: 8, diffGain: 8, dpr, chromiumRenderer: baseline[0].renderer, nativeRenderer, poses: reports }, null, 2) + '\n');
+ const lines = ['# Pixel comparison', '', `Chromium: ${baseline[0].renderer}`, ``, `Native: ${nativeRenderer}`, '', `Device pixel ratio: ${dpr}. Comparisons use equal physical image sizes.`, '',
+ 'RGBA values are 0–255. Transparent pixels can magnify straight RGB differences; premultiplied statistics measure their visible contribution. Diff images amplify premultiplied RGB differences by 8.', '',
+ '| Pose | Raw max | Raw mean | Raw pixels >8 | Premult max | Premult mean | Premult pixels >8 |',
+ '|---|---:|---:|---:|---:|---:|---:|',
+ ...reports.map(r => `| [${r.name}](${r.name}-comparison.png) | ${r.raw.max} | ${r.raw.mean.toFixed(4)} | ${r.raw.percentOver8.toFixed(3)}% | ${r.premultiplied.max.toFixed(2)} | ${r.premultiplied.mean.toFixed(4)} | ${r.premultiplied.percentOver8.toFixed(3)}% |`), ''];
+ await writeFile(resolve(out, 'report.md'), lines.join('\n'));
+ console.log(`Comparison images and report: ${relative(root, out)}/`);
+ } finally { await browser?.close(); await server.close(); }
+}
+main().catch(error => { console.error(error); process.exitCode = 1; });
diff --git a/native/conformance/dump.mjs b/native/conformance/dump.mjs
index 7dffe6e..c71dd3f 100644
--- a/native/conformance/dump.mjs
+++ b/native/conformance/dump.mjs
@@ -6,6 +6,9 @@ import { fileURLToPath } from 'node:url';
import { PNG } from 'pngjs';
import { dumpDeformation } from './deformation.mjs';
import { dumpMotion } from './motion.mjs';
+import { execFileSync } from 'node:child_process';
+
+execFileSync(process.execPath, ['--experimental-strip-types', fileURLToPath(new URL('./sync-motion-data.mjs', import.meta.url)), '--check'], { stdio: 'inherit' });
// Match the runtime's bundler-style extensionless lighting imports in plain Node.
const hooks = registerHooks({ resolve(specifier, context, next) {
diff --git a/native/conformance/sync-motion-data.mjs b/native/conformance/sync-motion-data.mjs
index dfb4f50..4153fcb 100644
--- a/native/conformance/sync-motion-data.mjs
+++ b/native/conformance/sync-motion-data.mjs
@@ -1,9 +1,16 @@
// Authored keyframes and expression targets shared with the JS runtime.
-import { writeFile } from 'node:fs/promises';
+import { readFile, writeFile } from 'node:fs/promises';
import { MOTIONS, IDLE_MOTIONS, ADDITIVE } from '../../packages/runtime/src/engine/motions.js';
import { EXPRESSIONS } from '../../packages/runtime/src/engine/motion.js';
const motions = Object.entries({ ...MOTIONS, ...IDLE_MOTIONS }).map(([id, motion]) => ({
id, ...motion, idle: motion.idle ?? false, tracks: Object.entries(motion.tracks),
}));
-await writeFile(new URL('../crates/mesh-avatar-core/src/engine/motions.json', import.meta.url),
- JSON.stringify({ motions, additive: [...ADDITIVE], expressions: EXPRESSIONS }, null, 2) + '\n');
+const path = new URL('../crates/mesh-avatar-core/src/engine/motions.json', import.meta.url);
+const expected = JSON.stringify({ motions, additive: [...ADDITIVE], expressions: EXPRESSIONS }, null, 2) + '\n';
+if (process.argv.includes('--check')) {
+ const actual = await readFile(path, 'utf8');
+ if (actual !== expected) {
+ console.error('Embedded motion data differs from the JS runtime. Run node --experimental-strip-types native/conformance/sync-motion-data.mjs');
+ process.exitCode = 1;
+ }
+} else await writeFile(path, expected);
diff --git a/native/crates/mesh-avatar-wgpu/Cargo.toml b/native/crates/mesh-avatar-wgpu/Cargo.toml
index fab5168..31d3304 100644
--- a/native/crates/mesh-avatar-wgpu/Cargo.toml
+++ b/native/crates/mesh-avatar-wgpu/Cargo.toml
@@ -7,3 +7,10 @@ publish.workspace = true
[dependencies]
mesh-avatar-core.workspace = true
+wgpu.workspace = true
+pollster.workspace = true
+bytemuck.workspace = true
+png.workspace = true
+anyhow.workspace = true
+serde.workspace = true
+serde_json.workspace = true
diff --git a/native/crates/mesh-avatar-wgpu/src/avatar.wgsl b/native/crates/mesh-avatar-wgpu/src/avatar.wgsl
new file mode 100644
index 0000000..9bd2ce4
--- /dev/null
+++ b/native/crates/mesh-avatar-wgpu/src/avatar.wgsl
@@ -0,0 +1,105 @@
+struct Uniforms {
+ scale_offset: vec4f,
+ rect: vec4f,
+ flags: vec4f,
+ eye_box: array<vec4f, 2>,
+ eye_top: array<vec4f, 12>,
+ eye_bot: array<vec4f, 12>,
+ eyes: array<vec4f, 2>,
+ mouth: vec4f,
+ mouth_state: vec4f,
+ cheeks: vec4f,
+};
+@group(0) @binding(0) var<uniform> u: Uniforms;
+@group(1) @binding(0) var image: texture_2d<f32>;
+@group(1) @binding(1) var image_sampler: sampler;
+struct VertexOutput { @builtin(position) position: vec4f, @location(0) uv: vec2f };
+@vertex fn vs(@location(0) position: vec2f, @location(1) uv: vec2f) -> VertexOutput {
+ var out: VertexOutput;
+ out.position = vec4f(position * u.scale_offset.xy + u.scale_offset.zw, 0.0, 1.0);
+ out.uv = uv;
+ return out;
+}
+fn curve(e: u32, top: bool, value: f32) -> f32 {
+ let f = clamp(value, 0.0, 1.0) * 23.0;
+ let i = min(u32(floor(f)), 22u);
+ let t = f - f32(i);
+ let k = e * 24u + i;
+ if top { return mix(u.eye_top[k / 4u][k % 4u], u.eye_top[(k + 1u) / 4u][(k + 1u) % 4u], t); }
+ return mix(u.eye_bot[k / 4u][k % 4u], u.eye_bot[(k + 1u) / 4u][(k + 1u) % 4u], t);
+}
+fn eye_lids_raw(e: u32, input: f32) -> vec2f {
+ let value = clamp(input, 0.0, 1.0);
+ let state = u.eyes[e];
+ let top = curve(e, true, value);
+ let bot = curve(e, false, value);
+ let b = 1.0 - state.x;
+ let hump = 4.0 * value * (1.0 - value);
+ let height = curve(e, false, 0.5) - curve(e, true, 0.5);
+ let arc = mix(u.eye_top[e * 6u].x, u.eye_top[e * 6u + 5u].w, value) - 0.3 * height * hump;
+ let closed = max(top, bot + 1.0 + (arc - bot - 1.0) * state.y);
+ return vec2f((closed - top) * max(b, -0.07), select(0.0, (closed - bot) * b * state.y, b > 0.0));
+}
+fn eye_lids(e: u32, value: f32, top: f32, bot: f32) -> vec2f {
+ let box = u.eye_box[e];
+ let du = 5.0 / (box.y - box.x);
+ let raw = eye_lids_raw(e, value);
+ let d = (eye_lids_raw(e, value - 2.0 * du) + 2.0 * eye_lids_raw(e, value - du) + 3.0 * raw
+ + 2.0 * eye_lids_raw(e, value + du) + eye_lids_raw(e, value + 2.0 * du)) / 9.0;
+ return vec2f(top + max(d.x, raw.x), bot + min(d.y, raw.y));
+}
+fn tex_at(p: vec2f) -> vec4f { return textureSample(image, image_sampler, (p - u.rect.xy) / u.rect.zw); }
+fn eye_ball(e: u32, p: vec2f) -> vec4f {
+ let box = u.eye_box[e];
+ let state = u.eyes[e];
+ let value = clamp((p.x - box.x) / (box.y - box.x), 0.0, 1.0);
+ let top = curve(e, true, value);
+ let bot = curve(e, false, value);
+ let lids = eye_lids(e, value, top, bot);
+ let v = clamp((p.y - top) / max(bot - top, 1.0), 0.0, 1.0);
+ let w = sqrt(4.0 * value * (1.0 - value)) * sqrt(4.0 * v * (1.0 - v));
+ let c = tex_at(p - state.zw * w);
+ return c * smoothstep(lids.x - 1.0, lids.x + 0.5, p.y) * (1.0 - smoothstep(lids.y - 0.9, lids.y + 0.6, p.y));
+}
+fn painted_mouth(p: vec2f, base: vec4f) -> vec4f {
+ let open = u.mouth_state.x;
+ if open < 0.01 { return base; }
+ let d = vec2f(cos(u.mouth.z), sin(u.mouth.z));
+ let n = vec2f(-d.y, d.x);
+ let r = p - u.mouth.xy;
+ let s = dot(r, d) / u.mouth.w;
+ let t = dot(r, n);
+ let form = u.mouth_state.y;
+ let wf = mix(0.78, 0.46, clamp(form * 0.5 + 0.5, 0.0, 1.0));
+ let k = 1.0 - (s / wf) * (s / wf);
+ if k <= 0.0 { return base; }
+ let line = u.mouth_state.z * (1.0 - s * s);
+ let hk = pow(k, mix(0.55, 0.85, clamp(form, 0.0, 1.0)));
+ let height = mix(20.0, 26.0, clamp(form, 0.0, 1.0));
+ let up = line - 0.6 - open * 2.5 * hk;
+ let lo = line + open * height * hk;
+ let cov = smoothstep(-0.7, 0.7, t - up) * smoothstep(-0.7, 0.7, lo - t);
+ if cov <= 0.0 { return base; }
+ let tv = clamp((t - up) / max(lo - up, 1.0), 0.0, 1.0);
+ var col = mix(vec3f(0.24, 0.05, 0.08), vec3f(0.48, 0.15, 0.19), tv);
+ let tongue = smoothstep(0.5, 0.78, tv) * (1.0 - smoothstep(0.45, 0.8, abs(s) / wf));
+ col = mix(col, vec3f(0.86, 0.44, 0.47), tongue * 0.9);
+ let teeth = (1.0 - smoothstep(0.12, 0.22, tv)) * smoothstep(0.25, 0.45, open) * (1.0 - smoothstep(0.55, 0.85, abs(s) / wf));
+ col = mix(col, vec3f(0.99, 0.96, 0.94), teeth);
+ let rim = 1.0 - smoothstep(0.6, 1.8, lo - t);
+ col = mix(col, vec3f(0.36, 0.09, 0.11), rim * 0.85);
+ return vec4f(mix(base.rgb, col, cov), 1.0);
+}
+@fragment fn fs(in: VertexOutput) -> @location(0) vec4f {
+ let p = u.rect.xy + in.uv * u.rect.zw;
+ var c: vec4f;
+ if u.flags.x == 1.0 {
+ c = painted_mouth(p, tex_at(p));
+ let a = (p - u.cheeks.xy) / vec2f(48.0, 22.0);
+ let b = (p - u.cheeks.zw) / vec2f(40.0, 20.0);
+ let blush = exp(-dot(a, a)) + exp(-dot(b, b));
+ c = vec4f(mix(c.rgb, c.rgb * vec3f(1.0, 0.62, 0.64), clamp(blush * u.flags.z * 0.55, 0.0, 1.0) * c.a), c.a);
+ } else if u.flags.x >= 2.0 { c = eye_ball(u32(u.flags.x) - 2u, p); }
+ else { c = tex_at(p); }
+ return c * u.flags.y;
+}
diff --git a/native/crates/mesh-avatar-wgpu/src/bin/mesh-avatar-render.rs b/native/crates/mesh-avatar-wgpu/src/bin/mesh-avatar-render.rs
new file mode 100644
index 0000000..90faee6
--- /dev/null
+++ b/native/crates/mesh-avatar-wgpu/src/bin/mesh-avatar-render.rs
@@ -0,0 +1,153 @@
+use anyhow::{bail, ensure, Context, Result};
+use mesh_avatar_core::{
+ engine::{random::SeededRandom, rig::PARAMS},
+ format::AvatarPackage,
+ Avatar, AvatarOptions,
+};
+use mesh_avatar_wgpu::{headless_device, wgpu, Fit, Renderer, ViewOptions};
+use std::{collections::BTreeMap, env, fs, path::PathBuf};
+
+struct Args {
+ avatar: PathBuf,
+ output: PathBuf,
+ pose: Option<PathBuf>,
+ seconds: f64,
+ size: [u32; 2],
+ fit: Fit,
+ pad_top: Option<f64>,
+ pad_side: Option<f64>,
+ samples: u32,
+ seed: u32,
+ no_sprites: bool,
+ expression: Option<String>,
+}
+fn usage() -> &'static str {
+ "Usage: mesh-avatar-render <avatar> [--pose params.json] [--seconds N] [--size WxH] -o out.png\nOptions: --fit contain|cover --pad-top N --pad-side N --samples 1|4 --seed N --no-sprites --expression NAME"
+}
+fn parse() -> Result<Option<Args>> {
+ let mut args = env::args().skip(1);
+ let Some(first) = args.next() else {
+ bail!("{}", usage());
+ };
+ if matches!(first.as_str(), "--help" | "-h") {
+ println!("{}", usage());
+ return Ok(None);
+ }
+ let mut out = Args {
+ avatar: first.into(),
+ output: PathBuf::new(),
+ pose: None,
+ seconds: 0.0,
+ size: [512, 640],
+ fit: Fit::Contain,
+ pad_top: None,
+ pad_side: None,
+ samples: 4,
+ seed: 0,
+ no_sprites: false,
+ expression: None,
+ };
+ while let Some(flag) = args.next() {
+ if flag == "--no-sprites" {
+ out.no_sprites = true;
+ continue;
+ }
+ let value = args
+ .next()
+ .with_context(|| format!("{flag}: missing value"))?;
+ match flag.as_str() {
+ "-o" | "--output" => out.output = value.into(),
+ "--pose" => out.pose = Some(value.into()),
+ "--seconds" => out.seconds = value.parse()?,
+ "--size" => {
+ let (w, h) = value.split_once('x').context("size must be WxH")?;
+ out.size = [w.parse()?, h.parse()?];
+ }
+ "--fit" => {
+ out.fit = match value.as_str() {
+ "contain" => Fit::Contain,
+ "cover" => Fit::Cover,
+ _ => bail!("fit must be contain or cover"),
+ }
+ }
+ "--pad-top" => out.pad_top = Some(value.parse()?),
+ "--pad-side" => out.pad_side = Some(value.parse()?),
+ "--samples" => out.samples = value.parse()?,
+ "--seed" => out.seed = value.parse()?,
+ "--expression" => out.expression = Some(value),
+ _ => bail!("unknown option: {flag}\n{}", usage()),
+ }
+ }
+ ensure!(!out.output.as_os_str().is_empty(), "-o is required");
+ ensure!(
+ out.seconds.is_finite() && out.seconds >= 0.0,
+ "seconds must be finite and non-negative"
+ );
+ Ok(Some(out))
+}
+fn run(args: Args) -> Result<()> {
+ let mut package = AvatarPackage::open(&args.avatar)?;
+ if args.no_sprites {
+ package.sprites = None;
+ }
+ let view = ViewOptions {
+ image_size: [package.rig.image.width, package.rig.image.height],
+ pad_top: args.pad_top.unwrap_or(package.rig.view.pad_top),
+ pad_side: args.pad_side.unwrap_or(package.rig.view.pad_side),
+ fit: args.fit,
+ };
+ view.transform(args.size)?;
+ let mut avatar = Avatar::with_rng(
+ package,
+ AvatarOptions::default(),
+ Box::new(SeededRandom::new(args.seed)),
+ )?;
+ if let Some(path) = args.pose {
+ let values: BTreeMap<String, f64> =
+ serde_json::from_slice(&fs::read(path)?).context("invalid pose parameter object")?;
+ let mut parameters: BTreeMap<String, f64> = PARAMS
+ .iter()
+ .map(|p| (p.id.to_owned(), p.default))
+ .collect();
+ parameters.extend(values);
+ avatar.set_parameters(parameters);
+ avatar.set_auto_idle(false);
+ avatar.set_auto_motion(false);
+ }
+ if let Some(expression) = args.expression {
+ avatar.set_expression(&expression);
+ }
+ let mut frame = avatar.tick(0.0);
+ // Mirror advance(seconds, 60): a whole number of fixed simulation steps.
+ for _ in 0..(args.seconds * 60.0).round() as usize {
+ frame = avatar.tick(1.0 / 60.0);
+ }
+ let (device, queue, info) = pollster::block_on(headless_device())?;
+ eprintln!(
+ "GPU: {} ({:?}), {}x{}, {} samples",
+ info.name, info.backend, args.size[0], args.size[1], args.samples
+ );
+ let mut renderer = Renderer::new(
+ &device,
+ &queue,
+ wgpu::TextureFormat::Rgba8Unorm,
+ args.samples,
+ avatar.textures(),
+ )?;
+ let rgba = renderer.render_rgba(&frame, args.size, &view)?;
+ if let Some(parent) = args.output.parent().filter(|p| !p.as_os_str().is_empty()) {
+ fs::create_dir_all(parent)?;
+ }
+ let mut encoder =
+ png::Encoder::new(fs::File::create(&args.output)?, args.size[0], args.size[1]);
+ encoder.set_color(png::ColorType::Rgba);
+ encoder.set_depth(png::BitDepth::Eight);
+ encoder.write_header()?.write_image_data(&rgba)?;
+ Ok(())
+}
+fn main() {
+ if let Err(error) = parse().and_then(|args| args.map(run).transpose()) {
+ eprintln!("mesh-avatar-render: {error:#}");
+ std::process::exit(1);
+ }
+}
diff --git a/native/crates/mesh-avatar-wgpu/src/lib.rs b/native/crates/mesh-avatar-wgpu/src/lib.rs
index bf7c711..1cf1f6d 100644
--- a/native/crates/mesh-avatar-wgpu/src/lib.rs
+++ b/native/crates/mesh-avatar-wgpu/src/lib.rs
@@ -1,3 +1,750 @@
-//! GPU rendering support for mesh avatars.
-//!
-//! The renderer is not implemented yet.
+//! Premultiplied-alpha rendering into caller-owned wgpu texture views.
+use anyhow::{ensure, Context, Result};
+use bytemuck::{Pod, Zeroable};
+use mesh_avatar_core::{format::Texture, DrawLayer, FaceUniforms, Frame};
+use serde::{Deserialize, Serialize};
+use std::{collections::BTreeMap, sync::mpsc, time::Duration};
+pub use wgpu;
+use wgpu::util::DeviceExt;
+
+#[derive(Debug, Clone, Copy, Default, Deserialize, Serialize)]
+#[serde(rename_all = "lowercase")]
+pub enum Fit {
+ #[default]
+ Contain,
+ Cover,
+}
+#[derive(Debug, Clone, Copy)]
+pub struct ViewOptions {
+ pub image_size: [u32; 2],
+ pub pad_top: f64,
+ pub pad_side: f64,
+ pub fit: Fit,
+}
+impl ViewOptions {
+ /// Target sizes are physical pixels; no device-pixel-ratio value is needed.
+ pub fn transform(&self, size: [u32; 2]) -> Result<[f32; 4]> {
+ ensure!(
+ self.image_size.iter().chain(size.iter()).all(|&v| v > 0),
+ "image and target dimensions must be positive"
+ );
+ ensure!(
+ self.pad_top.is_finite()
+ && self.pad_top > -1.0
+ && self.pad_side.is_finite()
+ && self.pad_side > -0.5,
+ "invalid viewport margins"
+ );
+ let [iw, ih] = self.image_size.map(f64::from);
+ let [w, h] = size.map(f64::from);
+ let sx = w / (iw * (1.0 + 2.0 * self.pad_side));
+ let sy = h / (ih * (1.0 + self.pad_top));
+ let scale = match self.fit {
+ Fit::Contain => sx.min(sy),
+ Fit::Cover => sx.max(sy),
+ };
+ let ox = (w - iw * scale) / 2.0;
+ let oy = (h - ih * scale)
+ / match self.fit {
+ Fit::Contain => 1.0,
+ Fit::Cover => 2.0,
+ };
+ Ok([
+ 2.0 * scale / w,
+ -2.0 * scale / h,
+ -1.0 + 2.0 * ox / w,
+ 1.0 - 2.0 * oy / h,
+ ]
+ .map(|v| v as f32))
+ }
+}
+#[repr(C, align(16))]
+#[derive(Clone, Copy, Pod, Zeroable)]
+struct Uniforms {
+ scale_offset: [f32; 4],
+ rect: [f32; 4],
+ flags: [f32; 4],
+ eye_box: [[f32; 4]; 2],
+ eye_top: [[f32; 4]; 12],
+ eye_bot: [[f32; 4]; 12],
+ eyes: [[f32; 4]; 2],
+ mouth: [f32; 4],
+ mouth_state: [f32; 4],
+ cheeks: [f32; 4],
+}
+impl Uniforms {
+ fn new(transform: [f32; 4], layer: &DrawLayer, state: &FaceUniforms) -> Self {
+ Self {
+ scale_offset: transform,
+ rect: layer.rect.map(|v| v as f32),
+ flags: [
+ layer
+ .eye_ball
+ .map_or(if layer.face { 1.0 } else { 0.0 }, |e| 2.0 + e as f32),
+ layer.alpha as f32,
+ state.cheek,
+ 0.0,
+ ],
+ eye_box: state.eye_box,
+ eye_top: std::array::from_fn(|i| {
+ std::array::from_fn(|j| state.eye_top[(i * 4 + j) / 24][(i * 4 + j) % 24])
+ }),
+ eye_bot: std::array::from_fn(|i| {
+ std::array::from_fn(|j| state.eye_bot[(i * 4 + j) / 24][(i * 4 + j) % 24])
+ }),
+ eyes: [
+ state.eyes[..4].try_into().unwrap(),
+ state.eyes[4..].try_into().unwrap(),
+ ],
+ mouth: state.mouth,
+ mouth_state: state.mouth_state,
+ cheeks: state.cheeks,
+ }
+ }
+}
+struct LayerBuffers {
+ positions: wgpu::Buffer,
+ uvs: wgpu::Buffer,
+ indices: wgpu::Buffer,
+ uniform: wgpu::Buffer,
+ bind_group: wgpu::BindGroup,
+ vertex_len: usize,
+ index_len: u32,
+}
+struct Multisample {
+ size: [u32; 2],
+ view: wgpu::TextureView,
+}
+
+pub struct Renderer {
+ device: wgpu::Device,
+ queue: wgpu::Queue,
+ format: wgpu::TextureFormat,
+ sample_count: u32,
+ pipeline: wgpu::RenderPipeline,
+ uniform_layout: wgpu::BindGroupLayout,
+ textures: BTreeMap<String, wgpu::BindGroup>,
+ layers: BTreeMap<String, LayerBuffers>,
+ multisample: Option<Multisample>,
+}
+fn texture_layout(device: &wgpu::Device) -> wgpu::BindGroupLayout {
+ device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
+ label: Some("avatar texture layout"),
+ entries: &[
+ wgpu::BindGroupLayoutEntry {
+ binding: 0,
+ visibility: wgpu::ShaderStages::FRAGMENT,
+ ty: wgpu::BindingType::Texture {
+ sample_type: wgpu::TextureSampleType::Float { filterable: true },
+ view_dimension: wgpu::TextureViewDimension::D2,
+ multisampled: false,
+ },
+ count: None,
+ },
+ wgpu::BindGroupLayoutEntry {
+ binding: 1,
+ visibility: wgpu::ShaderStages::FRAGMENT,
+ ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
+ count: None,
+ },
+ ],
+ })
+}
+fn texture_group(
+ device: &wgpu::Device,
+ layout: &wgpu::BindGroupLayout,
+ view: &wgpu::TextureView,
+ sampler: &wgpu::Sampler,
+) -> wgpu::BindGroup {
+ device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("avatar texture"),
+ layout,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: wgpu::BindingResource::TextureView(view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::Sampler(sampler),
+ },
+ ],
+ })
+}
+fn color_attachment<'a>(
+ view: &'a wgpu::TextureView,
+ resolve_target: Option<&'a wgpu::TextureView>,
+) -> wgpu::RenderPassColorAttachment<'a> {
+ wgpu::RenderPassColorAttachment {
+ view,
+ resolve_target,
+ depth_slice: None,
+ ops: wgpu::Operations {
+ load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
+ store: wgpu::StoreOp::Store,
+ },
+ }
+}
+impl Renderer {
+ /// Match WebGL's gamma-encoded arithmetic with an Unorm target, such as
+ /// Rgba8Unorm or Bgra8Unorm. A swapchain may supply a compatible non-sRGB view.
+ pub fn new(
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ format: wgpu::TextureFormat,
+ sample_count: u32,
+ images: &BTreeMap<String, Texture>,
+ ) -> Result<Self> {
+ ensure!(matches!(sample_count, 1 | 4), "sample count must be 1 or 4");
+ ensure!(
+ !format.is_srgb(),
+ "use a non-sRGB texture view to match WebGL blending"
+ );
+ let uniform_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
+ label: Some("avatar uniform layout"),
+ entries: &[wgpu::BindGroupLayoutEntry {
+ binding: 0,
+ visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
+ ty: wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Uniform,
+ has_dynamic_offset: false,
+ min_binding_size: wgpu::BufferSize::new(std::mem::size_of::<Uniforms>() as u64),
+ },
+ count: None,
+ }],
+ });
+ let texture_layout = texture_layout(device);
+ let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
+ label: Some("avatar pipeline layout"),
+ bind_group_layouts: &[&uniform_layout, &texture_layout],
+ push_constant_ranges: &[],
+ });
+ let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
+ label: Some("avatar shader"),
+ source: wgpu::ShaderSource::Wgsl(include_str!("avatar.wgsl").into()),
+ });
+ let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
+ label: Some("avatar pipeline"),
+ layout: Some(&layout),
+ vertex: wgpu::VertexState {
+ module: &shader,
+ entry_point: Some("vs"),
+ compilation_options: Default::default(),
+ buffers: &[
+ wgpu::VertexBufferLayout {
+ array_stride: 8,
+ step_mode: wgpu::VertexStepMode::Vertex,
+ attributes: &wgpu::vertex_attr_array![0=>Float32x2],
+ },
+ wgpu::VertexBufferLayout {
+ array_stride: 8,
+ step_mode: wgpu::VertexStepMode::Vertex,
+ attributes: &wgpu::vertex_attr_array![1=>Float32x2],
+ },
+ ],
+ },
+ fragment: Some(wgpu::FragmentState {
+ module: &shader,
+ entry_point: Some("fs"),
+ compilation_options: Default::default(),
+ targets: &[Some(wgpu::ColorTargetState {
+ format,
+ blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
+ write_mask: wgpu::ColorWrites::ALL,
+ })],
+ }),
+ primitive: wgpu::PrimitiveState::default(),
+ depth_stencil: None,
+ multisample: wgpu::MultisampleState {
+ count: sample_count,
+ ..Default::default()
+ },
+ multiview: None,
+ cache: None,
+ });
+ let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
+ label: Some("avatar linear mip sampler"),
+ mag_filter: wgpu::FilterMode::Linear,
+ min_filter: wgpu::FilterMode::Linear,
+ mipmap_filter: wgpu::FilterMode::Linear,
+ ..Default::default()
+ });
+ let mip_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
+ label: Some("avatar mipmap shader"),
+ source: wgpu::ShaderSource::Wgsl(include_str!("mipmap.wgsl").into()),
+ });
+ let mip_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
+ label: Some("mipmap layout"),
+ bind_group_layouts: &[&texture_layout],
+ push_constant_ranges: &[],
+ });
+ let mip_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
+ label: Some("mipmap pipeline"),
+ layout: Some(&mip_layout),
+ vertex: wgpu::VertexState {
+ module: &mip_shader,
+ entry_point: Some("vs"),
+ compilation_options: Default::default(),
+ buffers: &[],
+ },
+ fragment: Some(wgpu::FragmentState {
+ module: &mip_shader,
+ entry_point: Some("fs"),
+ compilation_options: Default::default(),
+ targets: &[Some(wgpu::ColorTargetState {
+ format: wgpu::TextureFormat::Rgba8Unorm,
+ blend: None,
+ write_mask: wgpu::ColorWrites::ALL,
+ })],
+ }),
+ primitive: Default::default(),
+ depth_stencil: None,
+ multisample: Default::default(),
+ multiview: None,
+ cache: None,
+ });
+ let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("avatar mipmaps"),
+ });
+ let mut textures = BTreeMap::new();
+ for (name, image) in images {
+ ensure!(
+ image.width > 0
+ && image.height > 0
+ && image.width <= device.limits().max_texture_dimension_2d
+ && image.height <= device.limits().max_texture_dimension_2d,
+ "texture {name}: invalid dimensions"
+ );
+ ensure!(
+ image.rgba.len() as u64 == u64::from(image.width) * u64::from(image.height) * 4,
+ "texture {name}: invalid RGBA length"
+ );
+ let levels = 32 - image.width.max(image.height).leading_zeros();
+ let texture = device.create_texture(&wgpu::TextureDescriptor {
+ label: Some(name),
+ size: wgpu::Extent3d {
+ width: image.width,
+ height: image.height,
+ depth_or_array_layers: 1,
+ },
+ mip_level_count: levels,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format: wgpu::TextureFormat::Rgba8Unorm,
+ usage: wgpu::TextureUsages::TEXTURE_BINDING
+ | wgpu::TextureUsages::COPY_DST
+ | wgpu::TextureUsages::RENDER_ATTACHMENT,
+ view_formats: &[],
+ });
+ queue.write_texture(
+ wgpu::TexelCopyTextureInfo {
+ texture: &texture,
+ mip_level: 0,
+ origin: Default::default(),
+ aspect: wgpu::TextureAspect::All,
+ },
+ &image.premultiplied_rgba(),
+ wgpu::TexelCopyBufferLayout {
+ offset: 0,
+ bytes_per_row: Some(image.width * 4),
+ rows_per_image: Some(image.height),
+ },
+ texture.size(),
+ );
+ for level in 1..levels {
+ let previous = texture.create_view(&wgpu::TextureViewDescriptor {
+ base_mip_level: level - 1,
+ mip_level_count: Some(1),
+ ..Default::default()
+ });
+ let target = texture.create_view(&wgpu::TextureViewDescriptor {
+ base_mip_level: level,
+ mip_level_count: Some(1),
+ ..Default::default()
+ });
+ let bind = texture_group(device, &texture_layout, &previous, &sampler);
+ let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
+ label: Some("generate avatar mip"),
+ color_attachments: &[Some(color_attachment(&target, None))],
+ depth_stencil_attachment: None,
+ timestamp_writes: None,
+ occlusion_query_set: None,
+ });
+ pass.set_pipeline(&mip_pipeline);
+ pass.set_bind_group(0, &bind, &[]);
+ pass.draw(0..3, 0..1);
+ }
+ textures.insert(
+ name.clone(),
+ texture_group(
+ device,
+ &texture_layout,
+ &texture.create_view(&Default::default()),
+ &sampler,
+ ),
+ );
+ }
+ queue.submit([encoder.finish()]);
+ Ok(Self {
+ device: device.clone(),
+ queue: queue.clone(),
+ format,
+ sample_count,
+ pipeline,
+ uniform_layout,
+ textures,
+ layers: BTreeMap::new(),
+ multisample: None,
+ })
+ }
+ /// Encode a transparent frame into the supplied single-sample texture view.
+ /// The view's format must match the format passed to new().
+ /// Submit the encoder before rendering another frame with this renderer.
+ pub fn render(
+ &mut self,
+ encoder: &mut wgpu::CommandEncoder,
+ target: &wgpu::TextureView,
+ size: [u32; 2],
+ frame: &Frame,
+ view: &ViewOptions,
+ ) -> Result<()> {
+ let transform = view.transform(size)?;
+ ensure!(
+ size.iter()
+ .all(|&v| v <= self.device.limits().max_texture_dimension_2d),
+ "target exceeds GPU texture limits"
+ );
+ for layer in &frame.layers {
+ if layer.indices.is_empty() {
+ continue;
+ }
+ ensure!(
+ self.textures.contains_key(&layer.texture),
+ "missing GPU texture: {}",
+ layer.texture
+ );
+ ensure!(
+ layer.positions.len() == layer.uvs.len()
+ && layer.positions.len().is_multiple_of(2)
+ && layer
+ .indices
+ .iter()
+ .all(|&i| (i as usize) < layer.positions.len() / 2),
+ "invalid mesh: {}",
+ layer.name
+ );
+ if !self.layers.get(&layer.name).is_some_and(|old| {
+ old.vertex_len == layer.positions.len()
+ && old.index_len as usize == layer.indices.len()
+ }) {
+ let buffer = |label, bytes: &[u8], usage| {
+ self.device
+ .create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some(label),
+ contents: bytes,
+ usage,
+ })
+ };
+ let uniform = self.device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("avatar uniforms"),
+ size: std::mem::size_of::<Uniforms>() as u64,
+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ });
+ let bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("avatar uniforms"),
+ layout: &self.uniform_layout,
+ entries: &[wgpu::BindGroupEntry {
+ binding: 0,
+ resource: uniform.as_entire_binding(),
+ }],
+ });
+ self.layers.insert(
+ layer.name.clone(),
+ LayerBuffers {
+ positions: buffer(
+ "avatar positions",
+ bytemuck::cast_slice(&layer.positions),
+ wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
+ ),
+ uvs: buffer(
+ "avatar UVs",
+ bytemuck::cast_slice(&layer.uvs),
+ wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
+ ),
+ indices: buffer(
+ "avatar indices",
+ bytemuck::cast_slice(&layer.indices),
+ wgpu::BufferUsages::INDEX | wgpu::BufferUsages::COPY_DST,
+ ),
+ uniform,
+ bind_group,
+ vertex_len: layer.positions.len(),
+ index_len: layer.indices.len() as u32,
+ },
+ );
+ }
+ let gpu = &self.layers[&layer.name];
+ self.queue
+ .write_buffer(&gpu.positions, 0, bytemuck::cast_slice(&layer.positions));
+ self.queue
+ .write_buffer(&gpu.uvs, 0, bytemuck::cast_slice(&layer.uvs));
+ self.queue
+ .write_buffer(&gpu.indices, 0, bytemuck::cast_slice(&layer.indices));
+ self.queue.write_buffer(
+ &gpu.uniform,
+ 0,
+ bytemuck::bytes_of(&Uniforms::new(transform, layer, &frame.uniforms)),
+ );
+ }
+ if self.sample_count > 1 && !self.multisample.as_ref().is_some_and(|m| m.size == size) {
+ let texture = self.device.create_texture(&wgpu::TextureDescriptor {
+ label: Some("avatar multisample target"),
+ size: wgpu::Extent3d {
+ width: size[0],
+ height: size[1],
+ depth_or_array_layers: 1,
+ },
+ mip_level_count: 1,
+ sample_count: self.sample_count,
+ dimension: wgpu::TextureDimension::D2,
+ format: self.format,
+ usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
+ view_formats: &[],
+ });
+ self.multisample = Some(Multisample {
+ size,
+ view: texture.create_view(&Default::default()),
+ });
+ }
+ let attachment = if let Some(msaa) = &self.multisample {
+ color_attachment(&msaa.view, Some(target))
+ } else {
+ color_attachment(target, None)
+ };
+ let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
+ label: Some("avatar frame"),
+ color_attachments: &[Some(attachment)],
+ depth_stencil_attachment: None,
+ timestamp_writes: None,
+ occlusion_query_set: None,
+ });
+ pass.set_pipeline(&self.pipeline);
+ for layer in &frame.layers {
+ if layer.indices.is_empty() {
+ continue;
+ }
+ let gpu = &self.layers[&layer.name];
+ pass.set_bind_group(0, &gpu.bind_group, &[]);
+ pass.set_bind_group(1, &self.textures[&layer.texture], &[]);
+ pass.set_vertex_buffer(0, gpu.positions.slice(..));
+ pass.set_vertex_buffer(1, gpu.uvs.slice(..));
+ pass.set_index_buffer(gpu.indices.slice(..), wgpu::IndexFormat::Uint32);
+ pass.draw_indexed(0..gpu.index_len, 0, 0..1);
+ }
+ Ok(())
+ }
+ /// Render and read back straight RGBA, suitable for a PNG encoder.
+ pub fn render_rgba(
+ &mut self,
+ frame: &Frame,
+ size: [u32; 2],
+ view: &ViewOptions,
+ ) -> Result<Vec<u8>> {
+ ensure!(
+ self.format == wgpu::TextureFormat::Rgba8Unorm,
+ "RGBA readback requires Rgba8Unorm"
+ );
+ view.transform(size)?;
+ ensure!(
+ size.iter()
+ .all(|&v| v <= self.device.limits().max_texture_dimension_2d),
+ "target exceeds GPU texture limits"
+ );
+ let texture = self.device.create_texture(&wgpu::TextureDescriptor {
+ label: Some("avatar offscreen target"),
+ size: wgpu::Extent3d {
+ width: size[0],
+ height: size[1],
+ depth_or_array_layers: 1,
+ },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format: self.format,
+ usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
+ view_formats: &[],
+ });
+ let stride = (size[0] * 4).div_ceil(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT)
+ * wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
+ let buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("avatar readback"),
+ size: u64::from(stride) * u64::from(size[1]),
+ usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ });
+ let mut encoder = self.device.create_command_encoder(&Default::default());
+ self.render(
+ &mut encoder,
+ &texture.create_view(&Default::default()),
+ size,
+ frame,
+ view,
+ )?;
+ encoder.copy_texture_to_buffer(
+ texture.as_image_copy(),
+ wgpu::TexelCopyBufferInfo {
+ buffer: &buffer,
+ layout: wgpu::TexelCopyBufferLayout {
+ offset: 0,
+ bytes_per_row: Some(stride),
+ rows_per_image: Some(size[1]),
+ },
+ },
+ texture.size(),
+ );
+ let submission = self.queue.submit([encoder.finish()]);
+ let (send, receive) = mpsc::sync_channel(1);
+ buffer
+ .slice(..)
+ .map_async(wgpu::MapMode::Read, move |result| {
+ let _ = send.send(result);
+ });
+ self.device.poll(wgpu::PollType::Wait {
+ submission_index: Some(submission),
+ timeout: Some(Duration::from_secs(30)),
+ })?;
+ receive
+ .recv_timeout(Duration::from_secs(30))
+ .context("GPU readback timed out")??;
+ 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) {
+ for p in row[..(size[0] * 4) as usize].as_chunks::<4>().0 {
+ let alpha = u32::from(p[3]);
+ let unpremultiply = |value: u8| {
+ (u32::from(value) * 255 + alpha / 2)
+ .checked_div(alpha)
+ .unwrap_or(0)
+ .min(255) as u8
+ };
+ out.extend([
+ unpremultiply(p[0]),
+ unpremultiply(p[1]),
+ unpremultiply(p[2]),
+ p[3],
+ ]);
+ }
+ }
+ drop(bytes);
+ buffer.unmap();
+ Ok(out)
+ }
+}
+
+pub async fn headless_device() -> Result<(wgpu::Device, wgpu::Queue, wgpu::AdapterInfo)> {
+ let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor::default());
+ let adapter = instance
+ .request_adapter(&wgpu::RequestAdapterOptions {
+ power_preference: wgpu::PowerPreference::HighPerformance,
+ compatible_surface: None,
+ force_fallback_adapter: false,
+ })
+ .await
+ .context("no compatible GPU adapter")?;
+ let info = adapter.get_info();
+ let (device, queue) = adapter
+ .request_device(&wgpu::DeviceDescriptor {
+ label: Some("mesh avatar"),
+ ..Default::default()
+ })
+ .await?;
+ Ok((device, queue, info))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ #[test]
+ fn gpu_transparency_and_dynamic_mesh_updates() {
+ let Ok((device, queue, _)) = pollster::block_on(headless_device()) else {
+ eprintln!("GPU adapter unavailable; skipping GPU readback check.");
+ return;
+ };
+ let images = BTreeMap::from([(
+ "quad.png".into(),
+ Texture {
+ width: 2,
+ height: 2,
+ rgba: [200, 100, 50, 128].repeat(4),
+ },
+ )]);
+ let mut renderer =
+ Renderer::new(&device, &queue, wgpu::TextureFormat::Rgba8Unorm, 1, &images).unwrap();
+ let mut frame = Frame {
+ layers: vec![DrawLayer {
+ name: "quad".into(),
+ texture: "quad.png".into(),
+ rect: [1.0, 1.0, 2.0, 2.0],
+ positions: vec![1.0, 1.0, 3.0, 1.0, 1.0, 3.0, 3.0, 3.0],
+ uvs: vec![0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0],
+ indices: vec![0, 1, 2, 1, 3, 2],
+ alpha: 1.0,
+ face: false,
+ eye_ball: None,
+ }],
+ uniforms: FaceUniforms {
+ angles: [0.0; 3],
+ eye_box: [[0.0; 4]; 2],
+ eye_top: [[0.0; 24]; 2],
+ eye_bot: [[0.0; 24]; 2],
+ eyes: [0.0; 8],
+ mouth: [0.0; 4],
+ mouth_state: [0.0; 4],
+ cheeks: [0.0; 4],
+ cheek: 0.0,
+ },
+ motion_events: vec![],
+ };
+ let view = ViewOptions {
+ image_size: [4, 4],
+ pad_top: 0.0,
+ pad_side: 0.0,
+ fit: Fit::Contain,
+ };
+ let first = renderer.render_rgba(&frame, [8, 8], &view).unwrap();
+ assert_eq!(&first[..4], &[0, 0, 0, 0]);
+ let center = (4 * 8 + 4) * 4;
+ for (actual, expected) in first[center..center + 4].iter().zip([200_u8, 100, 50, 128]) {
+ assert!(actual.abs_diff(expected) <= 1);
+ }
+ for position in frame.layers[0].positions.as_chunks_mut::<2>().0 {
+ position[0] += 1.0;
+ }
+ let second = renderer.render_rgba(&frame, [8, 8], &view).unwrap();
+ assert_eq!(&second[(3 * 8 + 2) * 4..(3 * 8 + 2) * 4 + 4], &[0, 0, 0, 0]);
+ assert_eq!(second[(3 * 8 + 6) * 4 + 3], 128);
+ }
+ #[test]
+ fn contain_bottom_anchor_and_centered_cover_match_js() {
+ let mut view = ViewOptions {
+ image_size: [1000, 1000],
+ pad_top: 0.0,
+ pad_side: 0.0,
+ fit: Fit::Contain,
+ };
+ assert_eq!(
+ view.transform([1000, 500]).unwrap(),
+ [0.001, -0.002, -0.5, 1.0]
+ );
+ view.fit = Fit::Cover;
+ assert_eq!(
+ view.transform([1000, 500]).unwrap(),
+ [0.002, -0.004, -1.0, 2.0]
+ );
+ assert!(view.transform([0, 500]).is_err());
+ view.pad_side = -0.5;
+ assert!(view.transform([1000, 500]).is_err());
+ assert_eq!(std::mem::size_of::<Uniforms>(), 544);
+ }
+}
diff --git a/native/crates/mesh-avatar-wgpu/src/mipmap.wgsl b/native/crates/mesh-avatar-wgpu/src/mipmap.wgsl
new file mode 100644
index 0000000..d70014e
--- /dev/null
+++ b/native/crates/mesh-avatar-wgpu/src/mipmap.wgsl
@@ -0,0 +1,13 @@
+@group(0) @binding(0) var image: texture_2d<f32>;
+@group(0) @binding(1) var image_sampler: sampler;
+struct VertexOutput { @builtin(position) position: vec4f, @location(0) uv: vec2f };
+@vertex fn vs(@builtin(vertex_index) index: u32) -> VertexOutput {
+ let p = array<vec2f,3>(vec2f(-1.0,-1.0),vec2f(3.0,-1.0),vec2f(-1.0,3.0))[index];
+ var out: VertexOutput;
+ out.position = vec4f(p,0.0,1.0);
+ out.uv = vec2f((p.x + 1.0) * 0.5, (1.0 - p.y) * 0.5);
+ return out;
+}
+@fragment fn fs(in: VertexOutput) -> @location(0) vec4f {
+ return textureSampleLevel(image,image_sampler,in.uv,0.0);
+}