Skip to content

The animation engine for agents: blazingly fast math and 3D videos with Manim's Python API, on a Rust GPU core.

Python

Set up native Cargo engine

apoogdk64939eb1f43f
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 3f048041..30e099e8 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -3,1216 +3,4547 @@
version = 4
[[package]]
-name = "adler2"
-version = "2.0.1"
+name = "ab_glyph"
+version = "0.2.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
+checksum = "01c0457472c38ea5bd1c3b5ada5e368271cb550be7a4ca4a0b4634e9913f6cc2"
+dependencies = [
+ "ab_glyph_rasterizer",
+ "owned_ttf_parser",
+]
[[package]]
-name = "allocator-api2"
-version = "0.2.21"
+name = "ab_glyph_rasterizer"
+version = "0.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
+checksum = "366ffbaa4442f4684d91e2cd7c5ea7c4ed8add41959a31447066e279e432b618"
[[package]]
-name = "android_system_properties"
-version = "0.1.5"
+name = "adler2"
+version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311"
-dependencies = [
- "libc",
-]
+checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
[[package]]
-name = "arrayref"
-version = "0.3.9"
+name = "ahash"
+version = "0.7.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb"
+checksum = "891477e0c6a8957309ee5c45a6368af3ae14bb510732d2684ffa19af310920f9"
+dependencies = [
+ "getrandom 0.2.17",
+ "once_cell",
+ "version_check",
+]
[[package]]
-name = "arrayvec"
-version = "0.7.6"
+name = "ahash"
+version = "0.8.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50"
+checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"
+dependencies = [
+ "cfg-if",
+ "getrandom 0.3.4",
+ "once_cell",
+ "version_check",
+ "zerocopy",
+]
[[package]]
-name = "ash"
-version = "0.38.0+1.3.281"
+name = "aho-corasick"
+version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0bb44936d800fea8f016d7f2311c6a4f97aebd5dc86f09906139ec848cf3a46f"
+checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
dependencies = [
- "libloading",
+ "memchr",
]
[[package]]
-name = "autocfg"
-version = "1.5.0"
+name = "allocator-api2"
+version = "0.2.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8"
+checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
[[package]]
-name = "base64"
-version = "0.22.1"
+name = "alsa"
+version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
+checksum = "812947049edcd670a82cd5c73c3661d2e58468577ba8489de58e1a73c04cbd5d"
+dependencies = [
+ "alsa-sys",
+ "bitflags 2.13.2",
+ "cfg-if",
+ "libc",
+]
[[package]]
-name = "bit-set"
-version = "0.8.0"
+name = "alsa-sys"
+version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3"
+checksum = "ad7569085a265dd3f607ebecce7458eaab2132a84393534c95b18dcbc3f31e04"
dependencies = [
- "bit-vec",
+ "libc",
+ "pkg-config",
]
[[package]]
-name = "bit-vec"
-version = "0.8.0"
+name = "android-activity"
+version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"
+checksum = "0f2a1bb052857d5dd49572219344a7332b31b76405648eabac5bc68978251bcd"
+dependencies = [
+ "android-properties",
+ "bitflags 2.13.2",
+ "cc",
+ "jni",
+ "libc",
+ "log",
+ "ndk",
+ "ndk-context",
+ "ndk-sys",
+ "num_enum",
+ "thiserror 2.0.20",
+]
[[package]]
-name = "bitflags"
-version = "2.11.0"
+name = "android-properties"
+version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "843867be96c8daad0d758b57df9392b6d8d271134fce549de6ce169ff98a92af"
+checksum = "fc7eb209b1518d6bb87b283c20095f5228ecda460da70b44f0802523dea6da04"
[[package]]
-name = "block"
+name = "android_system_properties"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0d8c1fef690941d3e7788d328517591fecc684c084084702d6ff1641e993699a"
+checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc"
+dependencies = [
+ "libc",
+]
[[package]]
-name = "bumpalo"
-version = "3.20.2"
+name = "anyhow"
+version = "1.0.104"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb"
+checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
[[package]]
-name = "bytemuck"
-version = "1.25.0"
+name = "approx"
+version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c8efb64bd706a16a1bdde310ae86b351e4d21550d98d056f22f8a7f7a2183fec"
+checksum = "cab112f0a86d568ea0e627cc1d6be74a1e9cd55214684db5561995f6dad897c6"
dependencies = [
- "bytemuck_derive",
+ "num-traits",
]
[[package]]
-name = "bytemuck_derive"
-version = "1.10.2"
+name = "ar_archive_writer"
+version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f9abbd1bc6865053c427f7198e6af43bfdedc55ab791faed4fbd361d789575ff"
+checksum = "73cd58deff2140a0a8eae87e417bd01db68a33e148aa93d1e8cd837e55e312b6"
dependencies = [
- "proc-macro2",
- "quote",
- "syn",
+ "object",
]
[[package]]
-name = "cfg-if"
-version = "1.0.4"
+name = "arrayref"
+version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
+checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb"
[[package]]
-name = "cfg_aliases"
-version = "0.2.1"
+name = "arrayvec"
+version = "0.7.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"
+checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56"
[[package]]
-name = "codespan-reporting"
-version = "0.12.0"
+name = "as-raw-xcb-connection"
+version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "fe6d2e5af09e8c8ad56c969f2157a3d4238cebc7c55f0a517728c38f7b200f81"
-dependencies = [
- "serde",
- "termcolor",
- "unicode-width",
-]
+checksum = "175571dd1d178ced59193a6fc02dde1b972eb0bc56c892cde9beeceac5bf0f6b"
[[package]]
-name = "core-foundation"
-version = "0.10.1"
+name = "ash"
+version = "0.38.0+1.3.281"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6"
+checksum = "0bb44936d800fea8f016d7f2311c6a4f97aebd5dc86f09906139ec848cf3a46f"
dependencies = [
- "core-foundation-sys",
- "libc",
+ "libloading",
]
[[package]]
-name = "core-foundation-sys"
-version = "0.8.7"
+name = "atomic-waker"
+version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
+checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
[[package]]
-name = "core-graphics-types"
-version = "0.2.0"
+name = "autocfg"
+version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb"
-dependencies = [
- "bitflags",
- "core-foundation",
- "libc",
-]
+checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
-name = "core_maths"
-version = "0.1.1"
+name = "az"
+version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30"
-dependencies = [
- "libm",
-]
+checksum = "be5eb007b7cacc6c660343e96f650fedf4b5a77512399eb952ca6642cf8d13f7"
[[package]]
-name = "crc32fast"
-version = "1.5.0"
+name = "base64"
+version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511"
-dependencies = [
- "cfg-if",
-]
+checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
[[package]]
-name = "crunchy"
-version = "0.2.4"
+name = "base64"
+version = "0.23.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
+checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
[[package]]
-name = "data-url"
-version = "0.3.2"
+name = "beef"
+version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376"
+checksum = "3a8241f3ebb85c056b509d4327ad0358fbbba6ffb340bf388f26350aeda225b1"
[[package]]
-name = "document-features"
-version = "0.2.12"
+name = "biblatex"
+version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61"
+checksum = "591eba69b7c085632e22ca03606f0bbea68d53bbe26c8962e2d549af20c6a561"
dependencies = [
- "litrs",
+ "paste",
+ "roman-numerals-rs",
+ "strum",
+ "unic-langid",
+ "unicode-normalization",
+ "unscanny",
]
[[package]]
-name = "equivalent"
-version = "1.0.2"
+name = "bincode"
+version = "1.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
+checksum = "b1f45e9417d87227c7a56d22e471c6206462cba514c7590c09aff4cf6d1ddcad"
+dependencies = [
+ "serde",
+]
[[package]]
-name = "euclid"
-version = "0.22.13"
+name = "bit-set"
+version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "df61bf483e837f88d5c2291dcf55c67be7e676b3a51acc48db3a7b163b91ed63"
+checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3"
dependencies = [
- "num-traits",
+ "bit-vec 0.8.0",
]
[[package]]
-name = "flate2"
-version = "1.1.9"
+name = "bit-set"
+version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c"
+checksum = "09ec2f926cc3060f09db9ebc5b52823d85268d24bb917e472c0c4bea35780a7d"
dependencies = [
- "crc32fast",
- "miniz_oxide",
+ "bit-vec 0.9.1",
]
[[package]]
-name = "float-cmp"
-version = "0.9.0"
+name = "bit-vec"
+version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4"
+checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"
[[package]]
-name = "float_next_after"
-version = "1.0.0"
+name = "bit-vec"
+version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8bf7cc16383c4b8d58b9905a8509f02926ce3058053c056376248d958c9df1e8"
+checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51"
[[package]]
-name = "foldhash"
-version = "0.1.5"
+name = "bitflags"
+version = "1.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
+checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
[[package]]
-name = "foldhash"
-version = "0.2.0"
+name = "bitflags"
+version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
+checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
+dependencies = [
+ "serde_core",
+]
[[package]]
-name = "fontconfig-parser"
-version = "0.5.8"
+name = "bitvec"
+version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bbc773e24e02d4ddd8395fd30dc147524273a83e54e0f312d986ea30de5f5646"
+checksum = "ddcec3d12c579d40898fe0a9a358a803c23e9c52ca3c425707f81c9436211837"
dependencies = [
- "roxmltree 0.20.0",
+ "funty",
+ "radium",
+ "tap",
+ "wyz",
]
[[package]]
-name = "fontdb"
-version = "0.23.0"
+name = "block-buffer"
+version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "457e789b3d1202543297a350643cf459f836cade38934e7a4cf6a39e7cde2905"
+checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"
dependencies = [
- "fontconfig-parser",
- "log",
- "memmap2",
- "slotmap",
- "tinyvec",
- "ttf-parser",
+ "hybrid-array",
]
[[package]]
-name = "foreign-types"
-version = "0.5.0"
+name = "block2"
+version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965"
+checksum = "2c132eebf10f5cad5289222520a4a058514204aed6d791f1cf4fe8088b82d15f"
dependencies = [
- "foreign-types-macros",
- "foreign-types-shared",
+ "objc2 0.5.2",
]
[[package]]
-name = "foreign-types-macros"
-version = "0.2.3"
+name = "block2"
+version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1a5c6c585bc94aaf2c7b51dd4c2ba22680844aba4c687be581871a6f518c5742"
+checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5"
dependencies = [
- "proc-macro2",
- "quote",
- "syn",
+ "objc2 0.6.4",
]
[[package]]
-name = "foreign-types-shared"
-version = "0.3.1"
+name = "bumpalo"
+version = "3.20.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b"
+checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
[[package]]
-name = "futures-core"
-version = "0.3.32"
+name = "by_address"
+version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d"
+checksum = "64fa3c856b712db6612c019f14756e64e4bcea13337a6b33b696333a9eaa2d06"
[[package]]
-name = "futures-task"
-version = "0.3.32"
+name = "bytecheck"
+version = "0.6.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393"
+checksum = "23cdc57ce23ac53c931e88a43d06d070a6fd142f2617be5855eb75efc9beb1c2"
+dependencies = [
+ "bytecheck_derive",
+ "ptr_meta",
+ "simdutf8",
+]
[[package]]
-name = "futures-util"
-version = "0.3.32"
+name = "bytecheck_derive"
+version = "0.6.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6"
+checksum = "3db406d29fbcd95542e92559bed4d8ad92636d1ca8b3b72ede10b4bcc010e659"
dependencies = [
- "futures-core",
- "futures-task",
- "pin-project-lite",
- "slab",
+ "proc-macro2",
+ "quote",
+ "syn 1.0.109",
]
[[package]]
-name = "gl_generator"
-version = "0.14.0"
+name = "bytemuck"
+version = "1.25.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1a95dfc23a2b4a9a2f5ab41d194f8bfda3cabec42af4e39f08c339eb2a0c124d"
+checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"
dependencies = [
- "khronos_api",
- "log",
- "xml-rs",
+ "bytemuck_derive",
]
[[package]]
-name = "glow"
-version = "0.16.0"
+name = "bytemuck_derive"
+version = "1.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c5e5ea60d70410161c8bf5da3fdfeaa1c72ed2c15f8bbb9d19fe3a4fad085f08"
+checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c"
dependencies = [
- "js-sys",
- "slotmap",
- "wasm-bindgen",
- "web-sys",
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
]
[[package]]
-name = "glutin_wgl_sys"
-version = "0.6.1"
+name = "byteorder-lite"
+version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2c4ee00b289aba7a9e5306d57c2d05499b2e5dc427f84ac708bd2c090212cf3e"
-dependencies = [
- "gl_generator",
-]
+checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"
[[package]]
-name = "gpu-allocator"
-version = "0.28.0"
+name = "bytes"
+version = "1.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "51255ea7cfaadb6c5f1528d43e92a82acb2b96c43365989a28b2d44ee38f8795"
-dependencies = [
- "ash",
- "hashbrown 0.16.1",
- "log",
- "presser",
- "thiserror",
- "windows",
-]
+checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
[[package]]
-name = "gpu-descriptor"
-version = "0.3.2"
+name = "calloop"
+version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b89c83349105e3732062a895becfc71a8f921bb71ecbbdd8ff99263e3b53a0ca"
+checksum = "b99da2f8558ca23c71f4fd15dc57c906239752dd27ff3c00a1d56b685b7cbfec"
dependencies = [
- "bitflags",
- "gpu-descriptor-types",
- "hashbrown 0.15.5",
+ "bitflags 2.13.2",
+ "log",
+ "polling",
+ "rustix 0.38.44",
+ "slab",
+ "thiserror 1.0.69",
]
[[package]]
-name = "gpu-descriptor-types"
-version = "0.2.0"
+name = "calloop-wayland-source"
+version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "fdf242682df893b86f33a73828fb09ca4b2d3bb6cc95249707fc684d27484b91"
+checksum = "95a66a987056935f7efce4ab5668920b5d0dac4a7c99991a67395f13702ddd20"
dependencies = [
- "bitflags",
+ "calloop",
+ "rustix 0.38.44",
+ "wayland-backend",
+ "wayland-client",
]
[[package]]
-name = "half"
-version = "2.7.1"
+name = "cc"
+version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b"
+checksum = "f360145194ee8e21db5ee7f3fcd4fe52210864c75c985dae33218202c8bbe040"
dependencies = [
- "cfg-if",
- "crunchy",
- "num-traits",
- "zerocopy",
+ "find-msvc-tools",
+ "jobserver",
+ "libc",
+ "shlex",
]
[[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"
+name = "cfg-if"
+version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
-dependencies = [
- "allocator-api2",
- "equivalent",
- "foldhash 0.2.0",
-]
+checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
[[package]]
-name = "heck"
-version = "0.5.0"
+name = "cfg_aliases"
+version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
+checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
[[package]]
-name = "hexf-parse"
-version = "0.2.1"
+name = "chinese-number"
+version = "0.7.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "dfa686283ad6dd069f105e5ab091b04c62850d3e4cf5d67debad1933f55023df"
+checksum = "3e964125508474a83c95eb935697abbeb446ff4e9d62c71ce880e3986d1c606b"
+dependencies = [
+ "chinese-variant",
+ "enum-ordinalize",
+ "num-bigint",
+ "num-traits",
+]
[[package]]
-name = "imagesize"
-version = "0.14.0"
+name = "chinese-variant"
+version = "1.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "09e54e57b4c48b40f7aec75635392b12b3421fa26fe8b4332e63138ed278459c"
+checksum = "0d1275808335c5583ea45a4141d631dafcb36b79fa8a5e10b00e356b6af3e08a"
[[package]]
-name = "indexmap"
-version = "2.13.0"
+name = "ciborium"
+version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7714e70437a7dc3ac8eb7e6f8df75fd8eb422675fc7678aff7364301092b1017"
+checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e"
dependencies = [
- "equivalent",
- "hashbrown 0.16.1",
+ "ciborium-io",
+ "ciborium-ll",
+ "serde",
]
[[package]]
-name = "jni-sys"
-version = "0.3.0"
+name = "ciborium-io"
+version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8eaf4bc02d17cbdd7ff4c7438cafcdf7fb9a4613313ad11b4f8fefe7d3fa0130"
+checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757"
[[package]]
-name = "js-sys"
-version = "0.3.87"
+name = "ciborium-ll"
+version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "93f0862381daaec758576dcc22eb7bbf4d7efd67328553f3b45a412a51a3fb21"
+checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9"
dependencies = [
- "once_cell",
- "wasm-bindgen",
+ "ciborium-io",
+ "half",
]
[[package]]
-name = "khronos-egl"
-version = "6.0.0"
+name = "citationberg"
+version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6aae1df220ece3c0ada96b8153459b67eebe9ae9212258bb0134ae60416fdf76"
+checksum = "756ff1e3d43a9ecc8183932fb4d9fd3971236f3ce4acb62fe51d1cd43297547d"
dependencies = [
- "libc",
- "libloading",
- "pkg-config",
+ "quick-xml 0.38.4",
+ "serde",
+ "serde_path_to_error",
]
[[package]]
-name = "khronos_api"
-version = "3.1.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc"
-
-[[package]]
-name = "kurbo"
-version = "0.13.0"
+name = "cobs"
+version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7564e90fe3c0d5771e1f0bc95322b21baaeaa0d9213fa6a0b61c99f8b17b3bfb"
+checksum = "0fa961b519f0b462e3a3b4a34b64d119eeaca1d59af726fe450bbba07a9fc0a1"
dependencies = [
- "arrayvec",
- "euclid",
- "smallvec",
+ "thiserror 2.0.20",
]
[[package]]
-name = "libc"
-version = "0.2.182"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6800badb6cb2082ffd7b6a67e6125bb39f18782f793520caee8cb8846be06112"
-
-[[package]]
-name = "libloading"
-version = "0.8.9"
+name = "codespan-reporting"
+version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55"
+checksum = "af491d569909a7e4dee0ad7db7f5341fef5c614d5b8ec8cf765732aba3cff681"
dependencies = [
- "cfg-if",
- "windows-link",
+ "serde",
+ "termcolor",
+ "unicode-width",
]
[[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.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "11d3d7f243d5c5a8b9bb5d6dd2b1602c0cb0b9db1621bafc7ed66e35ff9fe092"
-
-[[package]]
-name = "lock_api"
-version = "0.4.14"
+name = "codex"
+version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
+checksum = "0732ab1a27b4ea05e6f9f60a5122c9924dd5123defde0d8e907f58cf643d40e6"
dependencies = [
- "scopeguard",
+ "chinese-number",
]
[[package]]
-name = "log"
-version = "0.4.29"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
-
-[[package]]
-name = "lyon"
-version = "1.0.16"
+name = "color"
+version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "dbcb7d54d54c8937364c9d41902d066656817dce1e03a44e5533afebd1ef4352"
+checksum = "2ec7c5eb7a16992b1904d76c517d170ab353b0e0b3d5a0c81a8a0cd1037893cf"
dependencies = [
- "lyon_algorithms",
- "lyon_tessellation",
+ "bytemuck",
]
[[package]]
-name = "lyon_algorithms"
-version = "1.0.16"
+name = "color_quant"
+version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f4c0829e28c4f336396f250d850c3987e16ce6db057ffe047ce0dd54aab6b647"
-dependencies = [
- "lyon_path",
- "num-traits",
-]
+checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b"
[[package]]
-name = "lyon_geom"
-version = "1.0.18"
+name = "combine"
+version = "4.6.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e260b6de923e6e47adfedf6243013a7a874684165a6a277594ee3906021b2343"
+checksum = "cfc320937d09e6de266b31b9afb480f197d7a861be86be7cb2ea7e5d1bfffc5e"
dependencies = [
- "arrayvec",
- "euclid",
- "num-traits",
+ "bytes",
+ "memchr",
]
[[package]]
-name = "lyon_path"
-version = "1.0.16"
+name = "comemo"
+version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1aeca86bcfd632a15984ba029b539ffb811e0a70bf55e814ef8b0f54f506fdeb"
+checksum = "3c963350b2b08aa4b725d7802593245380ab53dacfedcaa971385fc33306c0d4"
dependencies = [
- "lyon_geom",
- "num-traits",
+ "comemo-macros",
+ "parking_lot",
+ "rustc-hash 2.1.3",
+ "siphasher",
+ "slab",
]
[[package]]
-name = "lyon_tessellation"
-version = "1.0.16"
+name = "comemo-macros"
+version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f3f586142e1280335b1bc89539f7c97dd80f08fc43e9ab1b74ef0a42b04aa353"
+checksum = "a3c400139ba1389ef9e20ad2d87cda68b437a66483aa0da616bdf2cea7413853"
dependencies = [
- "float_next_after",
- "lyon_path",
- "num-traits",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
]
[[package]]
-name = "malloc_buf"
-version = "0.0.6"
+name = "concurrent-queue"
+version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "62bb907fe88d54d8d9ce32a3cceab4218ed2f6b7d35617cafe9adf84e43919cb"
+checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973"
dependencies = [
- "libc",
+ "crossbeam-utils",
]
[[package]]
-name = "matrixmultiply"
-version = "0.3.10"
+name = "console_error_panic_hook"
+version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a06de3016e9fae57a36fd14dba131fccf49f74b40b7fbdb472f96e361ec71a08"
+checksum = "a06aeb73f470f66dcdbf7223caeebb85984942f22f1adb2a088cf9668146bbbc"
dependencies = [
- "autocfg",
- "rawpointer",
+ "cfg-if",
+ "wasm-bindgen",
]
[[package]]
-name = "memchr"
-version = "2.8.0"
+name = "const-oid"
+version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79"
+checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c"
[[package]]
-name = "memmap2"
-version = "0.9.10"
+name = "core-foundation"
+version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "714098028fe011992e1c3962653c96b2d578c4b4bce9036e15ff220319b1e0e3"
+checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f"
dependencies = [
+ "core-foundation-sys",
"libc",
]
[[package]]
-name = "metal"
-version = "0.33.0"
+name = "core-foundation-sys"
+version = "0.8.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
+
+[[package]]
+name = "core-graphics"
+version = "0.23.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c7047791b5bc903b8cd963014b355f71dc9864a9a0b727057676c1dcae5cbc15"
+checksum = "c07782be35f9e1140080c6b96f0d44b739e2278479f64e02fdab4e32dfd8b081"
dependencies = [
- "bitflags",
- "block",
+ "bitflags 1.3.2",
+ "core-foundation",
"core-graphics-types",
"foreign-types",
- "log",
- "objc",
- "paste",
+ "libc",
]
[[package]]
-name = "miniz_oxide"
-version = "0.8.9"
+name = "core-graphics-types"
+version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
+checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf"
dependencies = [
- "adler2",
- "simd-adler32",
+ "bitflags 1.3.2",
+ "core-foundation",
+ "libc",
]
[[package]]
-name = "naga"
-version = "28.0.0"
+name = "core_maths"
+version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "618f667225063219ddfc61251087db8a9aec3c3f0950c916b614e403486f1135"
+checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30"
dependencies = [
- "arrayvec",
- "bit-set",
- "bitflags",
- "cfg-if",
- "cfg_aliases",
- "codespan-reporting",
- "half",
- "hashbrown 0.16.1",
- "hexf-parse",
- "indexmap",
"libm",
- "log",
- "num-traits",
- "once_cell",
- "rustc-hash 1.1.0",
- "spirv",
- "thiserror",
- "unicode-ident",
]
[[package]]
-name = "ndarray"
-version = "0.17.2"
+name = "coreaudio-rs"
+version = "0.14.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "520080814a7a6b4a6e9070823bb24b4531daac8c4627e08ba5de8c5ef2f2752d"
+checksum = "7d5d7dca3ebcf65a035582c9ad4385371a9d9ee6537474d2a278f4e1e475bb58"
dependencies = [
- "matrixmultiply",
- "num-complex",
- "num-integer",
- "num-traits",
- "portable-atomic",
- "portable-atomic-util",
- "rawpointer",
+ "bitflags 2.13.2",
+ "libc",
+ "objc2-audio-toolbox",
+ "objc2-core-audio",
+ "objc2-core-audio-types",
+ "objc2-core-foundation",
]
[[package]]
-name = "ndk-sys"
-version = "0.6.0+11769913"
+name = "countme"
+version = "3.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873"
-dependencies = [
- "jni-sys",
-]
+checksum = "7704b5fdd17b18ae31c4c1da5a2e0305a2bf17b5249300a9ee9ed7b72114c636"
[[package]]
-name = "manimgx_engine"
-version = "0.1.0"
+name = "cpal"
+version = "0.18.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6f02e8d0327b42d3e2e4ab2119af397344eb9fc54a34bf0ddeaa1277af8681f1"
dependencies = [
- "bytemuck",
- "lyon",
- "metal",
- "numpy",
- "pollster",
- "pyo3",
- "usvg",
- "wgpu",
+ "alsa",
+ "block2 0.6.2",
+ "coreaudio-rs",
+ "dasp_sample",
+ "jni",
+ "js-sys",
+ "libc",
+ "mach2",
+ "ndk",
+ "ndk-context",
+ "num-derive",
+ "num-traits",
+ "objc2 0.6.4",
+ "objc2-audio-toolbox",
+ "objc2-avf-audio",
+ "objc2-core-audio",
+ "objc2-core-audio-types",
+ "objc2-core-foundation",
+ "objc2-foundation 0.3.2",
+ "web-sys",
+ "windows",
+ "windows-core",
]
[[package]]
-name = "num-complex"
-version = "0.4.6"
+name = "cpufeatures"
+version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495"
+checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"
dependencies = [
- "num-traits",
+ "libc",
]
[[package]]
-name = "num-integer"
-version = "0.1.46"
+name = "crc32fast"
+version = "1.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f"
+checksum = "01a7799fd6b852db0e61728dde9a204c423b44d689dbd432522543614b490e78"
dependencies = [
- "num-traits",
+ "cfg-if",
]
[[package]]
-name = "num-traits"
-version = "0.2.19"
+name = "crossbeam-deque"
+version = "0.8.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
+checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a"
dependencies = [
- "autocfg",
- "libm",
+ "crossbeam-epoch",
+ "crossbeam-utils",
]
[[package]]
-name = "numpy"
-version = "0.28.0"
+name = "crossbeam-epoch"
+version = "0.9.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "778da78c64ddc928ebf5ad9df5edf0789410ff3bdbf3619aed51cd789a6af1e2"
+checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d"
dependencies = [
- "libc",
- "ndarray",
- "num-complex",
- "num-integer",
- "num-traits",
- "pyo3",
- "pyo3-build-config",
- "rustc-hash 2.1.1",
+ "crossbeam-utils",
]
[[package]]
-name = "objc"
-version = "0.2.7"
+name = "crossbeam-utils"
+version = "0.8.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "915b1b472bc21c53464d6c8461c9d3af805ba1ef837e1cac254428f4a77177b1"
-dependencies = [
- "malloc_buf",
-]
+checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"
[[package]]
-name = "once_cell"
-version = "1.21.3"
+name = "crunchy"
+version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d"
+checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
[[package]]
-name = "ordered-float"
-version = "5.1.0"
+name = "crypto-common"
+version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7f4779c6901a562440c3786d08192c6fbda7c1c2060edd10006b05ee35d10f2d"
+checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
dependencies = [
- "num-traits",
+ "hybrid-array",
]
[[package]]
-name = "parking_lot"
-version = "0.12.5"
+name = "csv"
+version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
+checksum = "52cd9d68cf7efc6ddfaaee42e7288d3a99d613d4b50f76ce9827ae0c6e14f938"
dependencies = [
- "lock_api",
- "parking_lot_core",
+ "csv-core",
+ "itoa",
+ "ryu",
+ "serde_core",
]
[[package]]
-name = "parking_lot_core"
-version = "0.9.12"
+name = "csv-core"
+version = "0.1.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
+checksum = "704a3c26996a80471189265814dbc2c257598b96b8a7feae2d31ace646bb9782"
dependencies = [
- "cfg-if",
- "libc",
- "redox_syscall",
- "smallvec",
- "windows-link",
+ "memchr",
]
[[package]]
-name = "paste"
-version = "1.0.15"
+name = "cursor-icon"
+version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
+checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f"
[[package]]
-name = "pico-args"
-version = "0.5.0"
+name = "dasp_sample"
+version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5be167a7af36ee22fe3115051bc51f6e6c7054c9348e28deb4f49bd6f705a315"
+checksum = "0c87e182de0887fd5361989c677c4e8f5000cd9491d6d563161a8f3a5519fc7f"
[[package]]
-name = "pin-project-lite"
-version = "0.2.16"
+name = "data-url"
+version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b"
+checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376"
[[package]]
-name = "pkg-config"
-version = "0.3.32"
+name = "deranged"
+version = "0.5.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c"
+checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"
[[package]]
-name = "pollster"
-version = "0.4.0"
+name = "digest"
+version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2f3a9f18d041e6d0e102a0a46750538147e5e8992d3b4873aaafee2520b00ce3"
+checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
+dependencies = [
+ "block-buffer",
+ "const-oid",
+ "crypto-common",
+]
[[package]]
-name = "portable-atomic"
-version = "1.13.1"
+name = "dirs"
+version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49"
+checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e"
+dependencies = [
+ "dirs-sys",
+]
[[package]]
-name = "portable-atomic-util"
-version = "0.2.5"
+name = "dirs-sys"
+version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7a9db96d7fa8782dd8c15ce32ffe8680bbd1e978a43bf51a34d39483540495f5"
+checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab"
dependencies = [
- "portable-atomic",
+ "libc",
+ "option-ext",
+ "redox_users",
+ "windows-sys 0.61.2",
]
[[package]]
-name = "presser"
-version = "0.3.1"
+name = "dispatch"
+version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e8cf8e6a8aa66ce33f63993ffc4ea4271eb5b0530a9002db8455ea6050c77bfa"
+checksum = "bd0c93bb4b0c6d9b77f4435b0ae98c24d17f1c45b2ff844c6151a07256ca923b"
[[package]]
-name = "proc-macro2"
-version = "1.0.106"
+name = "dispatch2"
+version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
+checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38"
dependencies = [
- "unicode-ident",
+ "bitflags 2.13.2",
+ "objc2 0.6.4",
]
[[package]]
-name = "profiling"
-version = "1.0.17"
+name = "displaydoc"
+version = "0.2.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3eb8486b569e12e2c32ad3e204dbaba5e4b5b216e9367044f25f1dba42341773"
+checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+]
[[package]]
-name = "pyo3"
-version = "0.28.2"
+name = "dlib"
+version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "cf85e27e86080aafd5a22eae58a162e133a589551542b3e5cee4beb27e54f8e1"
+checksum = "ab8ecd87370524b461f8557c119c405552c396ed91fc0a8eec68679eab26f94a"
dependencies = [
- "libc",
- "once_cell",
- "portable-atomic",
- "pyo3-build-config",
- "pyo3-ffi",
- "pyo3-macros",
+ "libloading",
]
[[package]]
-name = "pyo3-build-config"
-version = "0.28.2"
+name = "document-features"
+version = "0.2.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8bf94ee265674bf76c09fa430b0e99c26e319c945d96ca0d5a8215f31bf81cf7"
+checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61"
dependencies = [
- "target-lexicon",
+ "litrs",
]
[[package]]
-name = "pyo3-ffi"
-version = "0.28.2"
+name = "downcast-rs"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2"
+
+[[package]]
+name = "dpi"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76"
+
+[[package]]
+name = "ecow"
+version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "491aa5fc66d8059dd44a75f4580a2962c1862a1c2945359db36f6c2818b748dc"
+checksum = "78e4f79b296fbaab6ce2e22d52cb4c7f010fe0ebe7a32e34fa25885fd797bd02"
dependencies = [
- "libc",
- "pyo3-build-config",
+ "serde",
]
[[package]]
-name = "pyo3-macros"
-version = "0.28.2"
+name = "either"
+version = "1.18.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34"
+
+[[package]]
+name = "ena"
+version = "0.14.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f5d671734e9d7a43449f8480f8b38115df67bef8d21f76837fa75ee7aaa5e52e"
+checksum = "eabffdaee24bd1bf95c5ef7cec31260444317e72ea56c4c91750e8b7ee58d5f1"
dependencies = [
- "proc-macro2",
- "pyo3-macros-backend",
- "quote",
- "syn",
+ "log",
]
[[package]]
-name = "pyo3-macros-backend"
-version = "0.28.2"
+name = "enum-ordinalize"
+version = "4.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "22faaa1ce6c430a1f71658760497291065e6450d7b5dc2bcf254d49f66ee700a"
+checksum = "89dd01549b09589510cf0647475075d12071456586d70f5c75c98ae2a5537677"
+dependencies = [
+ "enum-ordinalize-derive",
+]
+
+[[package]]
+name = "enum-ordinalize-derive"
+version = "4.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a65863d15a4ce2888bd2f0f543cc963d3879c3a022c8ee43f6141d479a3ac815"
dependencies = [
- "heck",
"proc-macro2",
- "pyo3-build-config",
"quote",
- "syn",
+ "syn 3.0.6",
]
[[package]]
-name = "quote"
-version = "1.0.44"
+name = "equivalent"
+version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "21b2ebcf727b7760c461f091f9f0f539b77b8e87f2fd88131e7f1b433b3cece4"
+checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
+
+[[package]]
+name = "errno"
+version = "0.3.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
- "proc-macro2",
+ "libc",
+ "windows-sys 0.61.2",
]
[[package]]
-name = "range-alloc"
-version = "0.1.4"
+name = "euclid"
+version = "0.22.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c3d6831663a5098ea164f89cff59c6284e95f4e3c76ce9848d4529f5ccca9bde"
+checksum = "f1a05365e3b1c6d1650318537c7460c6923f1abdd272ad6842baa2b509957a06"
+dependencies = [
+ "num-traits",
+]
[[package]]
-name = "raw-window-handle"
-version = "0.6.2"
+name = "fallible-iterator"
+version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539"
+checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649"
[[package]]
-name = "rawpointer"
-version = "0.2.1"
+name = "fancy-regex"
+version = "0.16.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "60a357793950651c4ed0f3f52338f53b2f809f32d83a07f72909fa13e4c6c1e3"
+checksum = "998b056554fbe42e03ae0e152895cd1a7e1002aec800fdc6635d20270260c46f"
+dependencies = [
+ "bit-set 0.8.0",
+ "regex-automata",
+ "regex-syntax",
+]
[[package]]
-name = "redox_syscall"
-version = "0.5.18"
+name = "fastrand"
+version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
+checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
+
+[[package]]
+name = "fdeflate"
+version = "0.3.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c"
dependencies = [
- "bitflags",
+ "simd-adler32",
]
[[package]]
-name = "renderdoc-sys"
-version = "1.1.0"
+name = "fearless_simd"
+version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832"
+checksum = "b97b65636e5b9ef369943878ac74335ba1c55c1cb6adbf1e2c293c624248d693"
[[package]]
-name = "roxmltree"
-version = "0.20.0"
+name = "fetch"
+version = "0.1.0"
+dependencies = [
+ "sha2",
+]
+
+[[package]]
+name = "ffmpeg"
+version = "9.0.2"
+dependencies = [
+ "cc",
+ "fetch",
+]
+
+[[package]]
+name = "find-msvc-tools"
+version = "0.1.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97"
+checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484"
[[package]]
-name = "roxmltree"
-version = "0.21.1"
+name = "flate2"
+version = "1.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f1964b10c76125c36f8afe190065a4bf9a87bf324842c05701330bba9f1cacbb"
+checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb"
dependencies = [
- "memchr",
+ "crc32fast",
+ "miniz_oxide 0.9.1",
+ "zlib-rs",
]
[[package]]
-name = "rustc-hash"
-version = "1.1.0"
+name = "float-cmp"
+version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2"
+checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4"
[[package]]
-name = "rustc-hash"
-version = "2.1.1"
+name = "fnv"
+version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d"
+checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
[[package]]
-name = "rustversion"
-version = "1.0.22"
+name = "foldhash"
+version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d"
+checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
[[package]]
-name = "rustybuzz"
-version = "0.20.1"
+name = "font-types"
+version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "fd3c7c96f8a08ee34eff8857b11b49b07d71d1c3f4e88f8a88d4c9e9f90b1702"
+checksum = "5b38ad915f6dadd993ced50848a8291a543bd41ca62bc10740d5e64e2ab4cfd7"
dependencies = [
- "bitflags",
"bytemuck",
- "core_maths",
- "log",
- "smallvec",
- "ttf-parser",
- "unicode-bidi-mirroring",
- "unicode-ccc",
- "unicode-properties",
- "unicode-script",
]
[[package]]
-name = "scopeguard"
-version = "1.2.0"
+name = "fontconfig-parser"
+version = "0.5.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
+checksum = "bbc773e24e02d4ddd8395fd30dc147524273a83e54e0f312d986ea30de5f5646"
+dependencies = [
+ "roxmltree 0.20.0",
+]
[[package]]
-name = "serde"
-version = "1.0.228"
+name = "fontdb"
+version = "0.23.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
+checksum = "457e789b3d1202543297a350643cf459f836cade38934e7a4cf6a39e7cde2905"
dependencies = [
- "serde_core",
- "serde_derive",
+ "fontconfig-parser",
+ "log",
+ "memmap2",
+ "slotmap",
+ "tinyvec",
+ "ttf-parser",
]
[[package]]
-name = "serde_core"
-version = "1.0.228"
+name = "foreign-types"
+version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
+checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965"
dependencies = [
- "serde_derive",
+ "foreign-types-macros",
+ "foreign-types-shared",
]
[[package]]
-name = "serde_derive"
-version = "1.0.228"
+name = "foreign-types-macros"
+version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
+checksum = "ea5190182e6915eb873ddbc16e23b711b6eb1f9c00a0d0a3a91b5f6228475225"
dependencies = [
"proc-macro2",
"quote",
- "syn",
+ "syn 3.0.6",
]
[[package]]
-name = "simd-adler32"
-version = "0.3.8"
+name = "foreign-types-shared"
+version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e320a6c5ad31d271ad523dcf3ad13e2767ad8b1cb8f047f75a8aeaf8da139da2"
+checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b"
[[package]]
-name = "simplecss"
-version = "0.2.2"
+name = "form_urlencoded"
+version = "1.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7a9c6883ca9c3c7c90e888de77b7a5c849c779d25d74a1269b0218b14e8b136c"
+checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
dependencies = [
- "log",
+ "percent-encoding",
]
[[package]]
-name = "siphasher"
-version = "1.0.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b2aa850e253778c88a04c3d7323b043aeda9d3e30d5971937c1855769763678e"
-
-[[package]]
-name = "slab"
-version = "0.4.12"
+name = "funty"
+version = "2.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
+checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c"
[[package]]
-name = "slotmap"
-version = "1.1.1"
+name = "futures-core"
+version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bdd58c3c93c3d278ca835519292445cb4b0d4dc59ccfdf7ceadaab3f8aeb4038"
-dependencies = [
- "version_check",
-]
+checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"
[[package]]
-name = "smallvec"
-version = "1.15.1"
+name = "futures-task"
+version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03"
+checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"
[[package]]
-name = "spirv"
-version = "0.3.0+sdk-1.3.268.0"
+name = "futures-util"
+version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "eda41003dc44290527a59b13432d4a0379379fa074b70174882adfbdfd917844"
+checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"
dependencies = [
- "bitflags",
+ "futures-core",
+ "futures-task",
+ "pin-project-lite",
+ "slab",
]
[[package]]
-name = "static_assertions"
+name = "gethostname"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
+checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8"
+dependencies = [
+ "rustix 1.1.5",
+ "windows-link",
+]
[[package]]
-name = "strict-num"
-version = "0.1.1"
+name = "getrandom"
+version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731"
+checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
dependencies = [
- "float-cmp",
+ "cfg-if",
+ "libc",
+ "wasi",
]
[[package]]
-name = "svgtypes"
-version = "0.16.1"
+name = "getrandom"
+version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "695b5790b3131dafa99b3bbfd25a216edb3d216dad9ca208d4657bfb8f2abc3d"
+checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
dependencies = [
- "kurbo",
- "siphasher",
+ "cfg-if",
+ "libc",
+ "r-efi 5.3.0",
+ "wasip2",
]
[[package]]
-name = "syn"
-version = "2.0.117"
+name = "getrandom"
+version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99"
+checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
dependencies = [
- "proc-macro2",
- "quote",
- "unicode-ident",
+ "cfg-if",
+ "libc",
+ "r-efi 6.0.0",
]
[[package]]
-name = "target-lexicon"
-version = "0.13.5"
+name = "gif"
+version = "0.14.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca"
+checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159"
+dependencies = [
+ "color_quant",
+ "weezl",
+]
[[package]]
-name = "termcolor"
-version = "1.4.1"
+name = "gimli"
+version = "0.32.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755"
+checksum = "e629b9b98ef3dd8afe6ca2bd0f89306cec16d43d907889945bc5d6687f2f13c7"
dependencies = [
- "winapi-util",
+ "fallible-iterator",
+ "indexmap",
+ "stable_deref_trait",
]
[[package]]
-name = "thiserror"
-version = "2.0.18"
+name = "gl_generator"
+version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4"
+checksum = "1a95dfc23a2b4a9a2f5ab41d194f8bfda3cabec42af4e39f08c339eb2a0c124d"
dependencies = [
- "thiserror-impl",
+ "khronos_api",
+ "log",
+ "xml-rs",
]
[[package]]
-name = "thiserror-impl"
-version = "2.0.18"
+name = "glidesort"
+version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn",
-]
+checksum = "f2e102e6eb644d3e0b186fc161e4460417880a0a0b87d235f2e5b8fb30f2e9e0"
[[package]]
-name = "tiny-skia-path"
-version = "0.12.0"
+name = "glifo"
+version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "edca365c3faccca67d06593c5980fa6c57687de727a03131735bb85f01fdeeb9"
+checksum = "d99fc21d493812643aae86d53b7bbd02f376434a90317e8a790bc209fdd6605e"
dependencies = [
- "arrayref",
"bytemuck",
- "strict-num",
+ "foldhash",
+ "hashbrown 0.17.1",
+ "log",
+ "peniko",
+ "png",
+ "skrifa",
+ "smallvec",
+ "vello_common 0.0.9",
]
[[package]]
-name = "tinyvec"
-version = "1.10.0"
+name = "glow"
+version = "0.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bfa5fdc3bce6191a1dbc8c02d5c8bffcf557bafa17c124c5264a458f1b0613fa"
+checksum = "29038e1c483364cc6bb3cf78feee1816002e127c331a1eec55a4d202b9e1adb5"
dependencies = [
- "tinyvec_macros",
+ "js-sys",
+ "slotmap",
+ "wasm-bindgen",
+ "web-sys",
]
[[package]]
-name = "tinyvec_macros"
-version = "0.1.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
-
-[[package]]
-name = "ttf-parser"
-version = "0.25.1"
+name = "glutin_wgl_sys"
+version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31"
+checksum = "2c4ee00b289aba7a9e5306d57c2d05499b2e5dc427f84ac708bd2c090212cf3e"
dependencies = [
- "core_maths",
+ "gl_generator",
]
[[package]]
-name = "unicode-bidi"
-version = "0.3.18"
+name = "gpu-allocator"
+version = "0.28.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "51255ea7cfaadb6c5f1528d43e92a82acb2b96c43365989a28b2d44ee38f8795"
+dependencies = [
+ "ash",
+ "hashbrown 0.16.1",
+ "log",
+ "presser",
+ "thiserror 2.0.20",
+ "windows",
+]
+
+[[package]]
+name = "guillotiere"
+version = "0.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6b17e70c989c36bad147b27a58d148c0741c51448aa5653436547323e524d0ab"
+dependencies = [
+ "euclid",
+]
+
+[[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.12.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"
+dependencies = [
+ "ahash 0.7.8",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.14.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
+
+[[package]]
+name = "hashbrown"
+version = "0.16.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
+dependencies = [
+ "allocator-api2",
+ "equivalent",
+ "foldhash",
+ "serde",
+ "serde_core",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.17.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
+dependencies = [
+ "foldhash",
+]
+
+[[package]]
+name = "hayagriva"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7b6c185c5c72546d50b25b70187f01ab9a1a2fa21c4db8691e2426fa5fce805c"
+dependencies = [
+ "biblatex",
+ "ciborium",
+ "citationberg",
+ "icu_collator",
+ "icu_locale",
+ "indexmap",
+ "paste",
+ "roman-numerals-rs",
+ "serde",
+ "serde_yaml",
+ "thiserror 2.0.20",
+ "unic-langid",
+ "unicode-segmentation",
+ "unscanny",
+ "url",
+]
+
+[[package]]
+name = "hayro"
+version = "0.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c4caa128ab87fd48ffb7490617cf93f77f606820dffbc9fd9ef6ab0ed077f56d"
+dependencies = [
+ "bytemuck",
+ "hayro-interpret",
+ "image",
+ "kurbo",
+ "pic-scale",
+ "vello_cpu",
+]
+
+[[package]]
+name = "hayro-ccitt"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
+
+[[package]]
+name = "hayro-cmap"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "24d285dc30731c8485de5fa732fbdf2b3affdf01e4da7c2135022ca6fa664bf6"
+dependencies = [
+ "hayro-postscript",
+]
+
+[[package]]
+name = "hayro-interpret"
+version = "0.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f2613d0406898995042d0794c4245b2f2fba1246490c8ac593769bba6551129d"
+dependencies = [
+ "bitflags 2.13.2",
+ "hayro-cmap",
+ "hayro-syntax",
+ "kurbo",
+ "moxcms",
+ "phf",
+ "rustc-hash 2.1.3",
+ "siphasher",
+ "skrifa",
+ "smallvec",
+ "yoke",
+]
+
+[[package]]
+name = "hayro-jbig2"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "69374b3668dd45aeb3d3145cda68f2c7b4f223aaa2511e67d076f1c7d741388d"
+dependencies = [
+ "fearless_simd",
+ "hayro-ccitt",
+]
+
+[[package]]
+name = "hayro-jpeg2000"
+version = "0.3.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c75ab947623ef4ccaa7acf0579edf7cbb5a73838e3839a7be73335e522f433a1"
+dependencies = [
+ "fearless_simd",
+]
+
+[[package]]
+name = "hayro-postscript"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "885c5ef0654933139a9b9546fc2c69e18d37f38aa2520f079092b1be18f1fcaa"
+
+[[package]]
+name = "hayro-svg"
+version = "0.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7434c89e920d84e077214a29e69b462a6518754610f732f1124af3948410cb8c"
+dependencies = [
+ "base64 0.22.1",
+ "hayro-interpret",
+ "image",
+ "kurbo",
+ "siphasher",
+ "xmlwriter",
+]
+
+[[package]]
+name = "hayro-syntax"
+version = "0.7.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0edeafd70aa2db743de8ede8637d07ec87db05efe69cde371d03f1b185fcef27"
+dependencies = [
+ "flate2",
+ "hayro-ccitt",
+ "hayro-jbig2",
+ "hayro-jpeg2000",
+ "memchr",
+ "rustc-hash 2.1.3",
+ "smallvec",
+ "zune-jpeg",
+]
+
+[[package]]
+name = "heck"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
+
+[[package]]
+name = "hermit-abi"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284"
+
+[[package]]
+name = "hybrid-array"
+version = "0.4.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17"
+dependencies = [
+ "typenum",
+]
+
+[[package]]
+name = "hypher"
+version = "0.1.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "45f2b4f6b5da34d400d4c112eadcc14512cc5d04307a8eee182586d9bebd7ce6"
+
+[[package]]
+name = "icu_collator"
+version = "2.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "08984ed58ac439ebf3e13d2cf26b0c46a60afcd21721c1d14087c0b240344dda"
+dependencies = [
+ "icu_collator_data",
+ "icu_collections",
+ "icu_locale_core",
+ "icu_locale_fallback",
+ "icu_normalizer",
+ "icu_properties",
+ "icu_provider",
+ "smallvec",
+ "utf16_iter",
+ "utf8_iter",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_collator_data"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f7d7e54efdddeb1208c08dd5d32b53a879ac00d2d3d051b2255fd26821d16368"
+
+[[package]]
+name = "icu_collections"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513"
+dependencies = [
+ "displaydoc",
+ "potential_utf",
+ "serde",
+ "utf8_iter",
+ "yoke",
+ "zerofrom",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_locale"
+version = "2.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "785f595c61ef57169a467eeed7b4b6936a66f6cacbb116a96ee86da983251bf4"
+dependencies = [
+ "icu_collections",
+ "icu_locale_core",
+ "icu_locale_data",
+ "icu_locale_fallback",
+ "icu_provider",
+ "tinystr",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_locale_core"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb"
+dependencies = [
+ "displaydoc",
+ "litemap",
+ "serde",
+ "tinystr",
+ "writeable",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_locale_data"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d37d91460e362a5cf58907cd7ce871411775ee6294e49a5cc8e6cec16dfa75ea"
+
+[[package]]
+name = "icu_locale_fallback"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "251af8e57c9400e3eb58242fe5b8b1152b2a64fdf4cf632f923c38ccee6f2fa9"
+dependencies = [
+ "icu_locale_core",
+ "icu_locale_fallback_data",
+ "icu_provider",
+ "potential_utf",
+ "tinystr",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_locale_fallback_data"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "decf2a22ec8fa68f1a0c1129a3f8583f8f8bc24e8b9ccbe98ead99f62a4dc3a8"
+
+[[package]]
+name = "icu_normalizer"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f"
+dependencies = [
+ "icu_collections",
+ "icu_normalizer_data",
+ "icu_properties",
+ "icu_provider",
+ "smallvec",
+ "utf16_iter",
+ "utf8_iter",
+ "write16",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_normalizer_data"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0"
+
+[[package]]
+name = "icu_properties"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148"
+dependencies = [
+ "displaydoc",
+ "icu_collections",
+ "icu_locale_core",
+ "icu_properties_data",
+ "icu_provider",
+ "serde",
+ "zerotrie",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_properties_data"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa"
+
+[[package]]
+name = "icu_provider"
+version = "2.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73"
+dependencies = [
+ "displaydoc",
+ "icu_locale_core",
+ "postcard",
+ "serde",
+ "stable_deref_trait",
+ "writeable",
+ "yoke",
+ "zerofrom",
+ "zerotrie",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_provider_blob"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5916b44fac319d3f58e4d8d805a627df19e27937b582cd99fcde3bb6b7ce1b0e"
+dependencies = [
+ "icu_provider",
+ "postcard",
+ "serde",
+ "writeable",
+ "zerotrie",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_segmenter"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "82d07aafccd67af15d02512a6adf5896fbc5ed00f2e99b471d2efa14016db3db"
+dependencies = [
+ "core_maths",
+ "icu_collections",
+ "icu_locale_fallback",
+ "icu_provider",
+ "icu_segmenter_data",
+ "potential_utf",
+ "serde",
+ "smallvec",
+ "utf8_iter",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_segmenter_data"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ae293c039020f9ec10710af98d29ce6aa2051486638b49c9a6409f3b4a9e98ad"
+
+[[package]]
+name = "id-arena"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
+dependencies = [
+ "rayon",
+]
+
+[[package]]
+name = "idna"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de"
+dependencies = [
+ "idna_adapter",
+ "smallvec",
+ "utf8_iter",
+]
+
+[[package]]
+name = "idna_adapter"
+version = "1.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714"
+dependencies = [
+ "icu_normalizer",
+ "icu_properties",
+]
+
+[[package]]
+name = "image"
+version = "0.25.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104"
+dependencies = [
+ "bytemuck",
+ "byteorder-lite",
+ "color_quant",
+ "gif",
+ "image-webp",
+ "moxcms",
+ "num-traits",
+ "png",
+ "zune-core",
+ "zune-jpeg",
+]
+
+[[package]]
+name = "image-webp"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3"
+dependencies = [
+ "byteorder-lite",
+ "quick-error",
+]
+
+[[package]]
+name = "imagesize"
+version = "0.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09e54e57b4c48b40f7aec75635392b12b3421fa26fe8b4332e63138ed278459c"
+
+[[package]]
+name = "indexmap"
+version = "2.14.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
+dependencies = [
+ "equivalent",
+ "hashbrown 0.17.1",
+ "rayon",
+ "serde",
+ "serde_core",
+]
+
+[[package]]
+name = "itoa"
+version = "1.0.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
+
+[[package]]
+name = "jni"
+version = "0.22.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498"
+dependencies = [
+ "cfg-if",
+ "combine",
+ "jni-macros",
+ "jni-sys 0.4.1",
+ "log",
+ "simd_cesu8",
+ "thiserror 2.0.20",
+ "walkdir",
+ "windows-link",
+]
+
+[[package]]
+name = "jni-macros"
+version = "0.22.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "rustc_version",
+ "simd_cesu8",
+ "syn 2.0.119",
+]
+
+[[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 = "jobserver"
+version = "0.1.35"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3"
+dependencies = [
+ "getrandom 0.4.3",
+ "libc",
+]
+
+[[package]]
+name = "js-sys"
+version = "0.3.105"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ce57d20d1ea864ce2ac172ab472d409214f4fd359f0b2a2775abdf522e2af99e"
+dependencies = [
+ "cfg-if",
+ "futures-util",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "kamadak-exif"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1130d80c7374efad55a117d715a3af9368f0fa7a2c54573afc15a188cd984837"
+dependencies = [
+ "mutate_once",
+]
+
+[[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 = "kurbo"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4b60dfc32f652b926df6192e55525b16d186c69d47876c3ead4da5cc9f8450e2"
+dependencies = [
+ "arrayvec",
+ "euclid",
+ "polycool",
+ "smallvec",
+]
+
+[[package]]
+name = "lazy_static"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
+
+[[package]]
+name = "leb128"
+version = "0.2.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c83bff1d572d6b9aeef67ddfc8448e4a3737909cb28e81f97c791b9018703e52"
+
+[[package]]
+name = "leb128fmt"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2"
+
+[[package]]
+name = "libc"
+version = "0.2.189"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
+
+[[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 = "libredox"
+version = "0.1.25"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d"
+dependencies = [
+ "bitflags 2.13.2",
+ "libc",
+ "plain",
+ "redox_syscall 0.9.4",
+]
+
+[[package]]
+name = "linebender_resource_handle"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"
+
+[[package]]
+name = "linked-hash-map"
+version = "0.5.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0717cef1bc8b636c6e1c1bbdefc09e6322da8a9321966e8928ef80d20f7f770f"
+
+[[package]]
+name = "linux-raw-sys"
+version = "0.4.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab"
+
+[[package]]
+name = "linux-raw-sys"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
+
+[[package]]
+name = "lipsum"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "636860251af8963cc40f6b4baadee105f02e21b28131d76eba8e40ce84ab8064"
+dependencies = [
+ "rand",
+ "rand_chacha",
+]
+
+[[package]]
+name = "litemap"
+version = "0.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae"
+dependencies = [
+ "serde_core",
+]
+
+[[package]]
+name = "litrs"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "11d3d7f243d5c5a8b9bb5d6dd2b1602c0cb0b9db1621bafc7ed66e35ff9fe092"
+
+[[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 = "logos"
+version = "0.14.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7251356ef8cb7aec833ddf598c6cb24d17b689d20b993f9d11a3d764e34e6458"
+dependencies = [
+ "logos-derive",
+]
+
+[[package]]
+name = "logos-codegen"
+version = "0.14.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "59f80069600c0d66734f5ff52cc42f2dabd6b29d205f333d61fd7832e9e9963f"
+dependencies = [
+ "beef",
+ "fnv",
+ "lazy_static",
+ "proc-macro2",
+ "quote",
+ "regex-syntax",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "logos-derive"
+version = "0.14.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "24fb722b06a9dc12adb0963ed585f19fc61dc5413e6a9be9422ef92c091e731d"
+dependencies = [
+ "logos-codegen",
+]
+
+[[package]]
+name = "mach2"
+version = "0.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dae608c151f68243f2b000364e1f7b186d9c29845f7d2d85bd31b9ad77ad552b"
+
+[[package]]
+name = "manimgx-engine"
+version = "0.1.0"
+dependencies = [
+ "ash",
+ "bincode",
+ "bytemuck",
+ "console_error_panic_hook",
+ "cpal",
+ "ffmpeg",
+ "js-sys",
+ "libc",
+ "memmap2",
+ "mitex",
+ "mitex-spec-gen",
+ "pollster",
+ "pyo3",
+ "rusty_aac",
+ "rustybuzz",
+ "ruzstd",
+ "serde",
+ "serde_json",
+ "ttf-parser",
+ "typst",
+ "typst-kit",
+ "typst-layout",
+ "unicode-bidi",
+ "unicode-segmentation",
+ "wasm-bindgen",
+ "wasm-bindgen-cli-support",
+ "wasm-bindgen-futures",
+ "web-sys",
+ "web-time",
+ "wgpu",
+ "winit",
+ "x264",
+ "xxhash-rust",
+ "zstd",
+]
+
+[[package]]
+name = "memchr"
+version = "2.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
+
+[[package]]
+name = "memmap2"
+version = "0.9.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d1219ed1b7f229ee7104d281dd01d6802fe28bb6e95d292942c4daacdeb798c0"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "memoffset"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a"
+dependencies = [
+ "autocfg",
+]
+
+[[package]]
+name = "miniz_oxide"
+version = "0.8.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
+dependencies = [
+ "adler2",
+ "simd-adler32",
+]
+
+[[package]]
+name = "miniz_oxide"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"
+dependencies = [
+ "adler2",
+ "simd-adler32",
+]
+
+[[package]]
+name = "mitex"
+version = "0.2.7"
+source = "git+https://github.com/mitex-rs/mitex?tag=0.2.7#51f7210e026ab05d037125247e92d4d023d8a80d"
+dependencies = [
+ "mitex-parser",
+ "mitex-spec-gen",
+ "rowan",
+]
+
+[[package]]
+name = "mitex-glob"
+version = "0.2.7"
+source = "git+https://github.com/mitex-rs/mitex?tag=0.2.7#51f7210e026ab05d037125247e92d4d023d8a80d"
+
+[[package]]
+name = "mitex-lexer"
+version = "0.2.7"
+source = "git+https://github.com/mitex-rs/mitex?tag=0.2.7#51f7210e026ab05d037125247e92d4d023d8a80d"
+dependencies = [
+ "ecow",
+ "ena",
+ "logos",
+ "mitex-spec",
+ "once_cell",
+ "rustc-hash 2.1.3",
+]
+
+[[package]]
+name = "mitex-parser"
+version = "0.2.7"
+source = "git+https://github.com/mitex-rs/mitex?tag=0.2.7#51f7210e026ab05d037125247e92d4d023d8a80d"
+dependencies = [
+ "mitex-glob",
+ "mitex-lexer",
+ "mitex-spec",
+ "rowan",
+]
+
+[[package]]
+name = "mitex-spec"
+version = "0.2.7"
+source = "git+https://github.com/mitex-rs/mitex?tag=0.2.7#51f7210e026ab05d037125247e92d4d023d8a80d"
+dependencies = [
+ "rkyv",
+ "rustc-hash 2.1.3",
+ "serde",
+ "serde_json",
+]
+
+[[package]]
+name = "mitex-spec-gen"
+version = "0.2.7"
+dependencies = [
+ "fetch",
+ "mitex-spec",
+ "serde_json",
+ "typst",
+ "typst-kit",
+ "typst-layout",
+]
+
+[[package]]
+name = "moxcms"
+version = "0.8.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b"
+dependencies = [
+ "num-traits",
+ "pxfm",
+]
+
+[[package]]
+name = "mutate_once"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "13d2233c9842d08cfe13f9eac96e207ca6a2ea10b80259ebe8ad0268be27d2af"
+
+[[package]]
+name = "naga"
+version = "30.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a616d2fb8c89516ac2723a581f69d6c18576046bed761bd6b305e5618e6ae130"
+dependencies = [
+ "arrayvec",
+ "bit-set 0.10.0",
+ "bitflags 2.13.2",
+ "cfg-if",
+ "cfg_aliases",
+ "codespan-reporting",
+ "half",
+ "hashbrown 0.17.1",
+ "indexmap",
+ "libm",
+ "log",
+ "naga-types",
+ "num-traits",
+ "once_cell",
+ "rustc-hash 1.1.0",
+ "spirv",
+ "thiserror 2.0.20",
+ "unicode-ident",
+]
+
+[[package]]
+name = "naga-types"
+version = "30.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "590afbf58a6f4f62873cd5cff4468061844bafa1cdf399cc954537c22d768d49"
+dependencies = [
+ "hashbrown 0.17.1",
+ "indexmap",
+ "rustc-hash 1.1.0",
+ "thiserror 2.0.20",
+]
+
+[[package]]
+name = "nasm"
+version = "3.2.0"
+dependencies = [
+ "cc",
+ "fetch",
+]
+
+[[package]]
+name = "ndk"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4"
+dependencies = [
+ "bitflags 2.13.2",
+ "jni-sys 0.3.1",
+ "log",
+ "ndk-sys",
+ "num_enum",
+ "raw-window-handle",
+ "thiserror 1.0.69",
+]
+
+[[package]]
+name = "ndk-context"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b"
+
+[[package]]
+name = "ndk-sys"
+version = "0.6.0+11769913"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873"
+dependencies = [
+ "jni-sys 0.3.1",
+]
+
+[[package]]
+name = "num-bigint"
+version = "0.4.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367"
+dependencies = [
+ "num-integer",
+ "num-traits",
+]
+
+[[package]]
+name = "num-conv"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"
+
+[[package]]
+name = "num-derive"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "num-integer"
+version = "0.1.47"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b"
+dependencies = [
+ "num-traits",
+]
+
+[[package]]
+name = "num-traits"
+version = "0.2.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
+dependencies = [
+ "autocfg",
+ "libm",
+]
+
+[[package]]
+name = "num_enum"
+version = "0.7.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26"
+dependencies = [
+ "num_enum_derive",
+ "rustversion",
+]
+
+[[package]]
+name = "num_enum_derive"
+version = "0.7.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8"
+dependencies = [
+ "proc-macro-crate",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "objc-sys"
+version = "0.3.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cdb91bdd390c7ce1a8607f35f3ca7151b65afc0ff5ff3b34fa350f7d7c7e4310"
+
+[[package]]
+name = "objc2"
+version = "0.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "46a785d4eeff09c14c487497c162e92766fbb3e4059a71840cecc03d9a50b804"
+dependencies = [
+ "objc-sys",
+ "objc2-encode",
+]
+
+[[package]]
+name = "objc2"
+version = "0.6.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3a12a8ed07aefc768292f076dc3ac8c48f3781c8f2d5851dd3d98950e8c5a89f"
+dependencies = [
+ "objc2-encode",
+]
+
+[[package]]
+name = "objc2-app-kit"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e4e89ad9e3d7d297152b17d39ed92cd50ca8063a89a9fa569046d41568891eff"
+dependencies = [
+ "bitflags 2.13.2",
+ "block2 0.5.1",
+ "libc",
+ "objc2 0.5.2",
+ "objc2-core-data",
+ "objc2-core-image",
+ "objc2-foundation 0.2.2",
+ "objc2-quartz-core 0.2.2",
+]
+
+[[package]]
+name = "objc2-audio-toolbox"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6948501a91121d6399b79abaa33a8aa4ea7857fe019f341b8c23ad6e81b79b08"
+dependencies = [
+ "bitflags 2.13.2",
+ "libc",
+ "objc2 0.6.4",
+ "objc2-core-audio",
+ "objc2-core-audio-types",
+ "objc2-core-foundation",
+ "objc2-foundation 0.3.2",
+]
+
+[[package]]
+name = "objc2-avf-audio"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "13a380031deed8e99db00065c45937da434ca987c034e13b87e4441f9e4090be"
+dependencies = [
+ "bitflags 2.13.2",
+ "objc2 0.6.4",
+ "objc2-foundation 0.3.2",
+]
+
+[[package]]
+name = "objc2-cloud-kit"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "74dd3b56391c7a0596a295029734d3c1c5e7e510a4cb30245f8221ccea96b009"
+dependencies = [
+ "bitflags 2.13.2",
+ "block2 0.5.1",
+ "objc2 0.5.2",
+ "objc2-core-location",
+ "objc2-foundation 0.2.2",
+]
+
+[[package]]
+name = "objc2-contacts"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a5ff520e9c33812fd374d8deecef01d4a840e7b41862d849513de77e44aa4889"
+dependencies = [
+ "block2 0.5.1",
+ "objc2 0.5.2",
+ "objc2-foundation 0.2.2",
+]
+
+[[package]]
+name = "objc2-core-audio"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e1eebcea8b0dbff5f7c8504f3107c68fc061a3eb44932051c8cf8a68d969c3b2"
+dependencies = [
+ "dispatch2",
+ "objc2 0.6.4",
+ "objc2-core-audio-types",
+ "objc2-core-foundation",
+ "objc2-foundation 0.3.2",
+]
+
+[[package]]
+name = "objc2-core-audio-types"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5a89f2ec274a0cf4a32642b2991e8b351a404d290da87bb6a9a9d8632490bd1c"
+dependencies = [
+ "bitflags 2.13.2",
+ "objc2 0.6.4",
+]
+
+[[package]]
+name = "objc2-core-data"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "617fbf49e071c178c0b24c080767db52958f716d9eabdf0890523aeae54773ef"
+dependencies = [
+ "bitflags 2.13.2",
+ "block2 0.5.1",
+ "objc2 0.5.2",
+ "objc2-foundation 0.2.2",
+]
+
+[[package]]
+name = "objc2-core-foundation"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"
+dependencies = [
+ "bitflags 2.13.2",
+ "block2 0.6.2",
+ "dispatch2",
+ "libc",
+ "objc2 0.6.4",
+]
+
+[[package]]
+name = "objc2-core-graphics"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807"
+dependencies = [
+ "dispatch2",
+ "objc2 0.6.4",
+ "objc2-core-foundation",
+ "objc2-io-surface",
+]
+
+[[package]]
+name = "objc2-core-image"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "55260963a527c99f1819c4f8e3b47fe04f9650694ef348ffd2227e8196d34c80"
+dependencies = [
+ "block2 0.5.1",
+ "objc2 0.5.2",
+ "objc2-foundation 0.2.2",
+ "objc2-metal 0.2.2",
+]
+
+[[package]]
+name = "objc2-core-location"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "000cfee34e683244f284252ee206a27953279d370e309649dc3ee317b37e5781"
+dependencies = [
+ "block2 0.5.1",
+ "objc2 0.5.2",
+ "objc2-contacts",
+ "objc2-foundation 0.2.2",
+]
+
+[[package]]
+name = "objc2-encode"
+version = "4.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33"
+
+[[package]]
+name = "objc2-foundation"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0ee638a5da3799329310ad4cfa62fbf045d5f56e3ef5ba4149e7452dcf89d5a8"
+dependencies = [
+ "bitflags 2.13.2",
+ "block2 0.5.1",
+ "dispatch",
+ "libc",
+ "objc2 0.5.2",
+]
+
+[[package]]
+name = "objc2-foundation"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"
+dependencies = [
+ "bitflags 2.13.2",
+ "block2 0.6.2",
+ "libc",
+ "objc2 0.6.4",
+ "objc2-core-foundation",
+]
+
+[[package]]
+name = "objc2-io-surface"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d"
+dependencies = [
+ "bitflags 2.13.2",
+ "objc2 0.6.4",
+ "objc2-core-foundation",
+]
+
+[[package]]
+name = "objc2-link-presentation"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a1a1ae721c5e35be65f01a03b6d2ac13a54cb4fa70d8a5da293d7b0020261398"
+dependencies = [
+ "block2 0.5.1",
+ "objc2 0.5.2",
+ "objc2-app-kit",
+ "objc2-foundation 0.2.2",
+]
+
+[[package]]
+name = "objc2-metal"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dd0cba1276f6023976a406a14ffa85e1fdd19df6b0f737b063b95f6c8c7aadd6"
+dependencies = [
+ "bitflags 2.13.2",
+ "block2 0.5.1",
+ "objc2 0.5.2",
+ "objc2-foundation 0.2.2",
+]
+
+[[package]]
+name = "objc2-metal"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a0125f776a10d00af4152d74616409f0d4a2053a6f57fa5b7d6aa2854ac04794"
+dependencies = [
+ "bitflags 2.13.2",
+ "block2 0.6.2",
+ "objc2 0.6.4",
+ "objc2-foundation 0.3.2",
+]
+
+[[package]]
+name = "objc2-quartz-core"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e42bee7bff906b14b167da2bac5efe6b6a07e6f7c0a21a7308d40c960242dc7a"
+dependencies = [
+ "bitflags 2.13.2",
+ "block2 0.5.1",
+ "objc2 0.5.2",
+ "objc2-foundation 0.2.2",
+ "objc2-metal 0.2.2",
+]
+
+[[package]]
+name = "objc2-quartz-core"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f"
+dependencies = [
+ "bitflags 2.13.2",
+ "objc2 0.6.4",
+ "objc2-core-foundation",
+ "objc2-core-graphics",
+ "objc2-foundation 0.3.2",
+ "objc2-metal 0.3.2",
+]
+
+[[package]]
+name = "objc2-symbols"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0a684efe3dec1b305badae1a28f6555f6ddd3bb2c2267896782858d5a78404dc"
+dependencies = [
+ "objc2 0.5.2",
+ "objc2-foundation 0.2.2",
+]
+
+[[package]]
+name = "objc2-ui-kit"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b8bb46798b20cd6b91cbd113524c490f1686f4c4e8f49502431415f3512e2b6f"
+dependencies = [
+ "bitflags 2.13.2",
+ "block2 0.5.1",
+ "objc2 0.5.2",
+ "objc2-cloud-kit",
+ "objc2-core-data",
+ "objc2-core-image",
+ "objc2-core-location",
+ "objc2-foundation 0.2.2",
+ "objc2-link-presentation",
+ "objc2-quartz-core 0.2.2",
+ "objc2-symbols",
+ "objc2-uniform-type-identifiers",
+ "objc2-user-notifications",
+]
+
+[[package]]
+name = "objc2-uniform-type-identifiers"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "44fa5f9748dbfe1ca6c0b79ad20725a11eca7c2218bceb4b005cb1be26273bfe"
+dependencies = [
+ "block2 0.5.1",
+ "objc2 0.5.2",
+ "objc2-foundation 0.2.2",
+]
+
+[[package]]
+name = "objc2-user-notifications"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "76cfcbf642358e8689af64cee815d139339f3ed8ad05103ed5eaf73db8d84cb3"
+dependencies = [
+ "bitflags 2.13.2",
+ "block2 0.5.1",
+ "objc2 0.5.2",
+ "objc2-core-location",
+ "objc2-foundation 0.2.2",
+]
+
+[[package]]
+name = "object"
+version = "0.39.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2e5a6c098c7a3b6547378093f5cc30bc54fd361ce711e05293a5cc589562739b"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "once_cell"
+version = "1.21.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
+
+[[package]]
+name = "option-ext"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"
+
+[[package]]
+name = "orbclient"
+version = "0.3.55"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5df339f526ea9a60e371768d50efc2f2508c7203290731565d1f7a6f71d21747"
+dependencies = [
+ "libc",
+ "libredox",
+]
+
+[[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 = "owned_ttf_parser"
+version = "0.25.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "36820e9051aca1014ddc75770aab4d68bc1e9e632f0f5627c4086bc216fb583b"
+dependencies = [
+ "ttf-parser",
+]
+
+[[package]]
+name = "palette"
+version = "0.7.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ddeed8580d347d2abf3dcf06a5f0b3dc020258338526b277847cd4248a70fc64"
+dependencies = [
+ "approx",
+ "libm",
+ "palette_derive",
+ "palette_math",
+]
+
+[[package]]
+name = "palette_derive"
+version = "0.7.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "88537020289b719d81be994ccf1bbf4990f477e2f69ee52fe3e45f43a02e56be"
+dependencies = [
+ "by_address",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "palette_math"
+version = "0.7.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6e6eb142958d64335fb0e345c5b9ead2ecd6fc438c307e9d7d3c4fd428dbaf12"
+dependencies = [
+ "libm",
+]
+
+[[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 0.5.18",
+ "smallvec",
+ "windows-link",
+]
+
+[[package]]
+name = "paste"
+version = "1.0.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
+
+[[package]]
+name = "peniko"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "839c8299360d2e998bdb106dc0a6cd71dcc5f4df51df1b620361bf50e283cca6"
+dependencies = [
+ "bytemuck",
+ "color",
+ "kurbo",
+ "linebender_resource_handle",
+ "smallvec",
+]
+
+[[package]]
+name = "percent-encoding"
+version = "2.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
+
+[[package]]
+name = "phf"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf"
+dependencies = [
+ "phf_macros",
+ "phf_shared",
+ "serde",
+]
+
+[[package]]
+name = "phf_generator"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737"
+dependencies = [
+ "fastrand",
+ "phf_shared",
+]
+
+[[package]]
+name = "phf_macros"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef"
+dependencies = [
+ "phf_generator",
+ "phf_shared",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "phf_shared"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266"
+dependencies = [
+ "siphasher",
+]
+
+[[package]]
+name = "pic-scale"
+version = "0.7.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6edb0ff645d35accaec252de081d55984a0d6c952cb1e5dc2b9afa7c78f07288"
+dependencies = [
+ "num-traits",
+ "pxfm",
+]
+
+[[package]]
+name = "pico-args"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5be167a7af36ee22fe3115051bc51f6e6c7054c9348e28deb4f49bd6f705a315"
+
+[[package]]
+name = "pin-project"
+version = "1.1.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924"
+dependencies = [
+ "pin-project-internal",
+]
+
+[[package]]
+name = "pin-project-internal"
+version = "1.1.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[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 = "plain"
+version = "0.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6"
+
+[[package]]
+name = "plist"
+version = "1.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2896bade328c13f7042a297ea5ac5b0951f6cf989dea5f32c2fd98da398195cb"
+dependencies = [
+ "base64 0.23.1",
+ "indexmap",
+ "quick-xml 0.42.0",
+ "serde",
+ "time",
+]
+
+[[package]]
+name = "png"
+version = "0.18.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61"
+dependencies = [
+ "bitflags 2.13.2",
+ "crc32fast",
+ "fdeflate",
+ "flate2",
+ "miniz_oxide 0.8.9",
+]
+
+[[package]]
+name = "polling"
+version = "3.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218"
+dependencies = [
+ "cfg-if",
+ "concurrent-queue",
+ "hermit-abi",
+ "pin-project-lite",
+ "rustix 1.1.5",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "pollster"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bc6355899e1c9462875b6757c79f3caa011a1fdae12bbb1a2e72dd1f234f8336"
+
+[[package]]
+name = "polycool"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "50596ddc09eb5ad5f75cacd40209568e66df71baf86e1499a0e99c4cff12a5a6"
+dependencies = [
+ "arrayvec",
+]
+
+[[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 = "postcard"
+version = "1.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6764c3b5dd454e283a30e6dfe78e9b31096d9e32036b5d1eaac7a6119ccb9a24"
+dependencies = [
+ "cobs",
+ "serde",
+]
+
+[[package]]
+name = "potential_utf"
+version = "0.1.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661"
+dependencies = [
+ "serde_core",
+ "writeable",
+ "zerovec",
+]
+
+[[package]]
+name = "powerfmt"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"
+
+[[package]]
+name = "ppv-lite86"
+version = "0.2.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
+dependencies = [
+ "zerocopy",
+]
+
+[[package]]
+name = "presser"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e8cf8e6a8aa66ce33f63993ffc4ea4271eb5b0530a9002db8455ea6050c77bfa"
+
+[[package]]
+name = "proc-macro-crate"
+version = "3.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f"
+dependencies = [
+ "toml_edit 0.25.15+spec-1.1.0",
+]
+
+[[package]]
+name = "proc-macro-hack"
+version = "0.5.20+deprecated"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dc375e1527247fe1a97d8b7156678dfe7c1af2fc075c9a4db3690ecd2a148068"
+
+[[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 = "psm"
+version = "0.1.32"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4dcd034599e63b970727f70d79e02d62390a4a84f7c6b827c27c46d5ac3fa622"
+dependencies = [
+ "ar_archive_writer",
+ "cc",
+]
+
+[[package]]
+name = "ptr_meta"
+version = "0.1.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0738ccf7ea06b608c10564b31debd4f5bc5e197fc8bfe088f68ae5ce81e7a4f1"
+dependencies = [
+ "ptr_meta_derive",
+]
+
+[[package]]
+name = "ptr_meta_derive"
+version = "0.1.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "16b845dbfca988fa33db069c0e230574d15a3088f147a87b64c7589eb662c9ac"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 1.0.109",
+]
+
+[[package]]
+name = "pxfm"
+version = "0.1.30"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"
+
+[[package]]
+name = "pyo3"
+version = "0.29.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4688ddedf473e32662b9b067670129a8afb8c18e351482c70d62ba4a88171e8b"
+dependencies = [
+ "libc",
+ "once_cell",
+ "portable-atomic",
+ "pyo3-build-config",
+ "pyo3-ffi",
+ "pyo3-macros",
+]
+
+[[package]]
+name = "pyo3-build-config"
+version = "0.29.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f41027e41b4bd03f6e60f9f417fe24a6341a6bb744edd62b6f709f2a52ea30e9"
+dependencies = [
+ "target-lexicon",
+]
+
+[[package]]
+name = "pyo3-ffi"
+version = "0.29.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e591a95526fead067432c3b3a33fc74770b87b1e04e73671090d9c2055a2b327"
+dependencies = [
+ "libc",
+ "pyo3-build-config",
+]
+
+[[package]]
+name = "pyo3-macros"
+version = "0.29.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "73225868fc1cd84eef2c3c230ddb91273bf1de46aeb8a4248da76d32a0924a1c"
+dependencies = [
+ "proc-macro2",
+ "pyo3-macros-backend",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "pyo3-macros-backend"
+version = "0.29.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "571575aa3749fa6216757dd47d2a3e7ef360f329a40f0666a9fbd14889024952"
+dependencies = [
+ "heck",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "quick-error"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"
+
+[[package]]
+name = "quick-xml"
+version = "0.38.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b66c2058c55a409d601666cffe35f04333cf1013010882cec174a7467cd4e21c"
+dependencies = [
+ "memchr",
+ "serde",
+]
+
+[[package]]
+name = "quick-xml"
+version = "0.41.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "quick-xml"
+version = "0.42.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.47"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "r-efi"
+version = "5.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
+
+[[package]]
+name = "r-efi"
+version = "6.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
+
+[[package]]
+name = "radium"
+version = "0.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09"
+
+[[package]]
+name = "rand"
+version = "0.8.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c"
+dependencies = [
+ "rand_core",
+]
+
+[[package]]
+name = "rand_chacha"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
+dependencies = [
+ "ppv-lite86",
+ "rand_core",
+]
+
+[[package]]
+name = "rand_core"
+version = "0.6.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
+
+[[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 = "raw-window-metal"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "40d213455a5f1dc59214213c7330e074ddf8114c9a42411eb890c767357ce135"
+dependencies = [
+ "objc2 0.6.4",
+ "objc2-core-foundation",
+ "objc2-foundation 0.3.2",
+ "objc2-quartz-core 0.3.2",
+]
+
+[[package]]
+name = "rayon"
+version = "1.12.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d"
+dependencies = [
+ "either",
+ "rayon-core",
+]
+
+[[package]]
+name = "rayon-core"
+version = "1.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91"
+dependencies = [
+ "crossbeam-deque",
+ "crossbeam-utils",
+]
+
+[[package]]
+name = "read-fonts"
+version = "0.39.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c4ed38b89c2c77ff968c524145ad65fb010f38af5c7a224b53b81d47ac2daa81"
+dependencies = [
+ "bytemuck",
+ "font-types",
+]
+
+[[package]]
+name = "redox_syscall"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa"
+dependencies = [
+ "bitflags 1.3.2",
+]
+
+[[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 = "redox_syscall"
+version = "0.9.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "737970939a87c6fa31e7acad13307bccbb017a073b695b6089a2c484f929e20e"
+dependencies = [
+ "bitflags 2.13.2",
+]
+
+[[package]]
+name = "redox_users"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "60dc65c0ff1a7ae1294b0c67b9f14baf70b644404010370171787bfac1038fc0"
+dependencies = [
+ "libredox",
+ "thiserror 2.0.20",
+]
+
+[[package]]
+name = "regex"
+version = "1.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"
+dependencies = [
+ "aho-corasick",
+ "memchr",
+ "regex-automata",
+ "regex-syntax",
+]
+
+[[package]]
+name = "regex-automata"
+version = "0.4.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
+dependencies = [
+ "aho-corasick",
+ "memchr",
+ "regex-syntax",
+]
+
+[[package]]
+name = "regex-syntax"
+version = "0.8.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
+
+[[package]]
+name = "rend"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "71fe3824f5629716b1589be05dacd749f6aa084c87e00e016714a8cdfccc997c"
+dependencies = [
+ "bytecheck",
+]
+
+[[package]]
+name = "renderdoc-sys"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832"
+
+[[package]]
+name = "rkyv"
+version = "0.7.46"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2297bf9c81a3f0dc96bc9521370b88f054168c29826a75e89c55ff196e7ed6a1"
+dependencies = [
+ "bitvec",
+ "bytecheck",
+ "bytes",
+ "hashbrown 0.12.3",
+ "ptr_meta",
+ "rend",
+ "rkyv_derive",
+ "seahash",
+ "tinyvec",
+ "uuid",
+]
+
+[[package]]
+name = "rkyv_derive"
+version = "0.7.46"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "84d7b42d4b8d06048d3ac8db0eb31bcb942cbeb709f0b5f2b2ebde398d3038f5"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 1.0.109",
+]
+
+[[package]]
+name = "roman-numerals-rs"
+version = "3.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c85cd47a33a4510b1424fe796498e174c6a9cf94e606460ef022a19f3e4ff85e"
+
+[[package]]
+name = "rowan"
+version = "0.15.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a2441aaccb50f4267d4f0f58b21e0138e96a449f361ed57a2673a83c9bca0772"
+dependencies = [
+ "countme",
+ "hashbrown 0.14.5",
+ "memoffset",
+ "rustc-hash 1.1.0",
+ "text-size",
+]
+
+[[package]]
+name = "roxmltree"
+version = "0.20.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97"
+
+[[package]]
+name = "roxmltree"
+version = "0.21.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f1964b10c76125c36f8afe190065a4bf9a87bf324842c05701330bba9f1cacbb"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "rust_decimal"
+version = "1.43.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7653272e75dcac41dc199fbea6f5797633994fafd339943c06c9af16bf29cd3a"
+dependencies = [
+ "arrayvec",
+ "num-traits",
+]
+
+[[package]]
+name = "rustc-demangle"
+version = "0.1.28"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b74b56ffa8bb2830709a538c2cbcae9aa062db0d2a42563bfb09bdaae44020eb"
+
+[[package]]
+name = "rustc-hash"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2"
+
+[[package]]
+name = "rustc-hash"
+version = "2.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
+
+[[package]]
+name = "rustc_version"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"
+dependencies = [
+ "semver",
+]
+
+[[package]]
+name = "rustix"
+version = "0.38.44"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154"
+dependencies = [
+ "bitflags 2.13.2",
+ "errno",
+ "libc",
+ "linux-raw-sys 0.4.15",
+ "windows-sys 0.59.0",
+]
+
+[[package]]
+name = "rustix"
+version = "1.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d"
+dependencies = [
+ "bitflags 2.13.2",
+ "errno",
+ "libc",
+ "linux-raw-sys 0.12.1",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "rustversion"
+version = "1.0.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
+
+[[package]]
+name = "rusty_aac"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b7ab980ffb66a559565d09dd6727ff2da7d2a39d2e8b6149e48af6908caa99b5"
+
+[[package]]
+name = "rustybuzz"
+version = "0.20.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fd3c7c96f8a08ee34eff8857b11b49b07d71d1c3f4e88f8a88d4c9e9f90b1702"
+dependencies = [
+ "bitflags 2.13.2",
+ "bytemuck",
+ "core_maths",
+ "log",
+ "smallvec",
+ "ttf-parser",
+ "unicode-bidi-mirroring",
+ "unicode-ccc",
+ "unicode-properties",
+ "unicode-script",
+]
+
+[[package]]
+name = "ruzstd"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a252f5e20f038fe7b4ea53e073e65398d652c864cc162fc77c56c2f13717b888"
+dependencies = [
+ "twox-hash",
+]
+
+[[package]]
+name = "ryu"
+version = "1.0.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
+
+[[package]]
+name = "same-file"
+version = "1.0.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
+dependencies = [
+ "winapi-util",
+]
+
+[[package]]
+name = "scoped-tls"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294"
+
+[[package]]
+name = "scopeguard"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
+
+[[package]]
+name = "sctk-adwaita"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6277f0217056f77f1d8f49f2950ac6c278c0d607c45f5ee99328d792ede24ec"
+dependencies = [
+ "ab_glyph",
+ "log",
+ "memmap2",
+ "smithay-client-toolkit",
+ "tiny-skia",
+]
+
+[[package]]
+name = "seahash"
+version = "4.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1c107b6f4780854c8b126e228ea8869f4d7b71260f962fefb57b996b8959ba6b"
+
+[[package]]
+name = "semver"
+version = "1.0.28"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
+
+[[package]]
+name = "serde"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
+dependencies = [
+ "serde_core",
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_core"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
+dependencies = [
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_derive"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+]
+
+[[package]]
+name = "serde_json"
+version = "1.0.151"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14"
+dependencies = [
+ "itoa",
+ "memchr",
+ "serde",
+ "serde_core",
+ "zmij",
+]
+
+[[package]]
+name = "serde_path_to_error"
+version = "0.1.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457"
+dependencies = [
+ "itoa",
+ "serde",
+ "serde_core",
+]
+
+[[package]]
+name = "serde_spanned"
+version = "0.6.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3"
+dependencies = [
+ "serde",
+]
+
+[[package]]
+name = "serde_yaml"
+version = "0.9.34+deprecated"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47"
+dependencies = [
+ "indexmap",
+ "itoa",
+ "ryu",
+ "serde",
+ "unsafe-libyaml",
+]
+
+[[package]]
+name = "sha2"
+version = "0.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4"
+dependencies = [
+ "cfg-if",
+ "cpufeatures",
+ "digest",
+]
+
+[[package]]
+name = "shlex"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
+
+[[package]]
+name = "simd-adler32"
+version = "0.3.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
+
+[[package]]
+name = "simd_cesu8"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520"
+dependencies = [
+ "rustc_version",
+ "simdutf8",
+]
+
+[[package]]
+name = "simdutf8"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e"
+
+[[package]]
+name = "simplecss"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7a9c6883ca9c3c7c90e888de77b7a5c849c779d25d74a1269b0218b14e8b136c"
+dependencies = [
+ "log",
+]
+
+[[package]]
+name = "siphasher"
+version = "1.0.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8ee5873ec9cce0195efcb7a4e9507a04cd49aec9c83d0389df45b1ef7ba2e649"
+
+[[package]]
+name = "skrifa"
+version = "0.42.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c34617370ae968efb7161bb2beb517d9084659aae19e24b89e3db25b46e4564"
+dependencies = [
+ "bytemuck",
+ "read-fonts",
+]
+
+[[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.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ba467056f1b547ed52077911161fc86985becbc60e8e1857c8a144dab0def891"
+
+[[package]]
+name = "smithay-client-toolkit"
+version = "0.19.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3457dea1f0eb631b4034d61d4d8c32074caa6cd1ab2d59f2327bd8461e2c0016"
+dependencies = [
+ "bitflags 2.13.2",
+ "calloop",
+ "calloop-wayland-source",
+ "cursor-icon",
+ "libc",
+ "log",
+ "memmap2",
+ "rustix 0.38.44",
+ "thiserror 1.0.69",
+ "wayland-backend",
+ "wayland-client",
+ "wayland-csd-frame",
+ "wayland-cursor",
+ "wayland-protocols",
+ "wayland-protocols-wlr",
+ "wayland-scanner",
+ "xkeysym",
+]
+
+[[package]]
+name = "smol_str"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dd538fb6910ac1099850255cf94a94df6551fbdd602454387d0adb2d1ca6dead"
+dependencies = [
+ "serde",
+]
+
+[[package]]
+name = "spin"
+version = "0.9.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e"
+
+[[package]]
+name = "spirv"
+version = "0.4.0+sdk-1.4.341.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d9571ea910ebd84c86af4b3ed27f9dbdc6ad06f17c5f96146b2b671e2976744f"
+dependencies = [
+ "bitflags 2.13.2",
+]
+
+[[package]]
+name = "stable_deref_trait"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
+
+[[package]]
+name = "stacker"
+version = "0.1.25"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "707f49d46706bacf8a2b00d51dace3f9de527c13eec3778f570c411f89e69967"
+dependencies = [
+ "cc",
+ "cfg-if",
+ "libc",
+ "psm",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "static_assertions"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
+
+[[package]]
+name = "strict-num"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731"
+dependencies = [
+ "float-cmp",
+]
+
+[[package]]
+name = "strum"
+version = "0.27.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "af23d6f6c1a224baef9d3f61e287d2761385a5b88fdab4eb4c6f11aeb54c4bcf"
+dependencies = [
+ "strum_macros",
+]
+
+[[package]]
+name = "strum_macros"
+version = "0.27.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7695ce3845ea4b33927c055a39dc438a45b059f7c1b3d91d38d10355fb8cbca7"
+dependencies = [
+ "heck",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "svgtypes"
+version = "0.16.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "695b5790b3131dafa99b3bbfd25a216edb3d216dad9ca208d4657bfb8f2abc3d"
+dependencies = [
+ "kurbo",
+ "siphasher",
+]
+
+[[package]]
+name = "syn"
+version = "1.0.109"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[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.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "synstructure"
+version = "0.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+]
+
+[[package]]
+name = "syntect"
+version = "5.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "656b45c05d95a5704399aeef6bd0ddec7b2b3531b7c9e900abbf7c4d2190c925"
+dependencies = [
+ "bincode",
+ "fancy-regex",
+ "flate2",
+ "fnv",
+ "once_cell",
+ "plist",
+ "regex-syntax",
+ "serde",
+ "serde_derive",
+ "serde_json",
+ "thiserror 2.0.20",
+ "walkdir",
+ "yaml-rust",
+]
+
+[[package]]
+name = "tap"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369"
+
+[[package]]
+name = "target-lexicon"
+version = "0.13.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca"
+
+[[package]]
+name = "termcolor"
+version = "1.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755"
+dependencies = [
+ "winapi-util",
+]
+
+[[package]]
+name = "text-size"
+version = "1.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f18aa187839b2bdb1ad2fa35ead8c4c2976b64e4363c386d45ac0f7ee85c9233"
+
+[[package]]
+name = "thin-vec"
+version = "0.2.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4568d7e143ec86d2021c338bae2afa88699e84b8e0af523626654fe6f03a1748"
+
+[[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.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f"
+dependencies = [
+ "thiserror-impl 2.0.20",
+]
+
+[[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.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+]
+
+[[package]]
+name = "time"
+version = "0.3.55"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134"
+dependencies = [
+ "deranged",
+ "num-conv",
+ "powerfmt",
+ "serde_core",
+ "time-core",
+ "time-macros",
+]
+
+[[package]]
+name = "time-core"
+version = "0.1.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109"
+
+[[package]]
+name = "time-macros"
+version = "0.2.32"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85"
+dependencies = [
+ "num-conv",
+ "time-core",
+]
+
+[[package]]
+name = "tiny-skia"
+version = "0.11.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "83d13394d44dae3207b52a326c0c85a8bf87f1541f23b0d143811088497b09ab"
+dependencies = [
+ "arrayref",
+ "arrayvec",
+ "bytemuck",
+ "cfg-if",
+ "log",
+ "tiny-skia-path 0.11.4",
+]
+
+[[package]]
+name = "tiny-skia-path"
+version = "0.11.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9c9e7fc0c2e86a30b117d0462aa261b72b7a99b7ebd7deb3a14ceda95c5bdc93"
+dependencies = [
+ "arrayref",
+ "bytemuck",
+ "strict-num",
+]
+
+[[package]]
+name = "tiny-skia-path"
+version = "0.12.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "edca365c3faccca67d06593c5980fa6c57687de727a03131735bb85f01fdeeb9"
+dependencies = [
+ "arrayref",
+ "bytemuck",
+ "strict-num",
+]
+
+[[package]]
+name = "tinystr"
+version = "0.8.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643"
+dependencies = [
+ "displaydoc",
+ "serde_core",
+ "zerovec",
+]
+
+[[package]]
+name = "tinyvec"
+version = "1.13.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"
+
+[[package]]
+name = "toml"
+version = "0.8.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362"
+dependencies = [
+ "serde",
+ "serde_spanned",
+ "toml_datetime 0.6.11",
+ "toml_edit 0.22.27",
+]
+
+[[package]]
+name = "toml_datetime"
+version = "0.6.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c"
+dependencies = [
+ "serde",
+]
+
+[[package]]
+name = "toml_datetime"
+version = "1.1.1+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7"
+dependencies = [
+ "serde_core",
+]
+
+[[package]]
+name = "toml_edit"
+version = "0.22.27"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a"
+dependencies = [
+ "indexmap",
+ "serde",
+ "serde_spanned",
+ "toml_datetime 0.6.11",
+ "toml_write",
+ "winnow 0.7.15",
+]
+
+[[package]]
+name = "toml_edit"
+version = "0.25.15+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1340ea94a5856333492c9064b02c778b191dd2c853778d9609debdcdfea3a614"
+dependencies = [
+ "indexmap",
+ "toml_datetime 1.1.1+spec-1.1.0",
+ "toml_parser",
+ "winnow 1.0.4",
+]
+
+[[package]]
+name = "toml_parser"
+version = "1.1.3+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56"
+dependencies = [
+ "winnow 1.0.4",
+]
+
+[[package]]
+name = "toml_write"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801"
+
+[[package]]
+name = "tracing"
+version = "0.1.44"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
+dependencies = [
+ "pin-project-lite",
+ "tracing-core",
+]
+
+[[package]]
+name = "tracing-core"
+version = "0.1.36"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
+
+[[package]]
+name = "ttf-parser"
+version = "0.25.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31"
+dependencies = [
+ "core_maths",
+]
+
+[[package]]
+name = "two-face"
+version = "0.4.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "39e51b6e60e545cfdae5a4639ff423818f52372211a8d9a3e892b4b0761f76b2"
+dependencies = [
+ "serde",
+ "serde_derive",
+ "syntect",
+]
+
+[[package]]
+name = "twox-hash"
+version = "2.1.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5283634e518fe9e82c7b20520bb4bc209009fd16c82077c802f8111ecbb0117a"
+
+[[package]]
+name = "typed-arena"
+version = "2.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6af6ae20167a9ece4bcb41af5b80f8a1f1df981f6391189ce00fd257af04126a"
+
+[[package]]
+name = "typenum"
+version = "1.20.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
+
+[[package]]
+name = "typst"
+version = "0.15.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d1cb79435d128de5d5443a058a983f6dcc16738760fa55ed703762bc278b1fd3"
+dependencies = [
+ "arrayvec",
+ "comemo",
+ "ecow",
+ "rustc-hash 2.1.3",
+ "typst-eval",
+ "typst-html",
+ "typst-layout",
+ "typst-library",
+ "typst-macros",
+ "typst-realize",
+ "typst-syntax",
+ "typst-timing",
+ "typst-utils",
+]
+
+[[package]]
+name = "typst-assets"
+version = "0.15.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bcee505dac6702dd1c5e65aa2e94a6179d19ee09e2e5637d7313db91765dc4e0"
+dependencies = [
+ "bitflags 2.13.2",
+]
+
+[[package]]
+name = "typst-eval"
+version = "0.15.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a8823e1822bd181d8bee47b05632d16bf3a0a8ab042e01d815826350d7ae16c3"
+dependencies = [
+ "comemo",
+ "ecow",
+ "indexmap",
+ "rustc-hash 2.1.3",
+ "stacker",
+ "toml",
+ "typst-library",
+ "typst-macros",
+ "typst-syntax",
+ "typst-timing",
+ "typst-utils",
+ "unicode-segmentation",
+]
+
+[[package]]
+name = "typst-html"
+version = "0.15.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f41bcfbe480b640c4447d8bf9bb59020da610f239aa032d53328651a03572c09"
+dependencies = [
+ "az",
+ "bumpalo",
+ "comemo",
+ "ecow",
+ "palette",
+ "rustc-hash 2.1.3",
+ "time",
+ "typst-assets",
+ "typst-library",
+ "typst-macros",
+ "typst-svg",
+ "typst-syntax",
+ "typst-timing",
+ "typst-utils",
+ "unicode-math-class",
+]
+
+[[package]]
+name = "typst-kit"
+version = "0.15.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "27ee52e27dfab0da5ac3d19e7e43a21fbc7ff83af9301119468bae89fa857a8b"
+dependencies = [
+ "dirs",
+ "ecow",
+ "fontdb",
+ "once_cell",
+ "parking_lot",
+ "rustc-hash 2.1.3",
+ "serde",
+ "serde_json",
+ "typst-assets",
+ "typst-library",
+ "typst-syntax",
+ "typst-timing",
+ "typst-utils",
+ "url",
+]
+
+[[package]]
+name = "typst-layout"
+version = "0.15.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1916c407baf8f8815e5d50030eed6d5ac6a0702d927b3c156e38db7a618499e2"
+dependencies = [
+ "az",
+ "bumpalo",
+ "codex",
+ "comemo",
+ "ecow",
+ "either",
+ "hypher",
+ "icu_properties",
+ "icu_provider",
+ "icu_provider_blob",
+ "icu_segmenter",
+ "kurbo",
+ "libm",
+ "memchr",
+ "rustc-hash 2.1.3",
+ "rustybuzz",
+ "smallvec",
+ "ttf-parser",
+ "typst-assets",
+ "typst-library",
+ "typst-macros",
+ "typst-syntax",
+ "typst-timing",
+ "typst-utils",
+ "unicode-bidi",
+ "unicode-math-class",
+ "unicode-script",
+ "unicode-segmentation",
+]
+
+[[package]]
+name = "typst-library"
+version = "0.15.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "12becd02464849f1507f3c4ef3f401a4d28d5938cc74b6acc6f1d703458bf393"
+dependencies = [
+ "arrayvec",
+ "az",
+ "bitflags 2.13.2",
+ "bumpalo",
+ "ciborium",
+ "codex",
+ "comemo",
+ "csv",
+ "ecow",
+ "either",
+ "flate2",
+ "fontdb",
+ "glidesort",
+ "hayagriva",
+ "hayro-syntax",
+ "icu_properties",
+ "image",
+ "indexmap",
+ "kamadak-exif",
+ "kurbo",
+ "libm",
+ "lipsum",
+ "memchr",
+ "moxcms",
+ "palette",
+ "percent-encoding",
+ "phf",
+ "png",
+ "rayon",
+ "regex",
+ "regex-syntax",
+ "roxmltree 0.21.1",
+ "rust_decimal",
+ "rustc-hash 2.1.3",
+ "rustybuzz",
+ "serde",
+ "serde_json",
+ "serde_yaml",
+ "siphasher",
+ "smallvec",
+ "syntect",
+ "time",
+ "toml",
+ "ttf-parser",
+ "two-face",
+ "typed-arena",
+ "typst-assets",
+ "typst-macros",
+ "typst-syntax",
+ "typst-timing",
+ "typst-utils",
+ "unicode-math-class",
+ "unicode-normalization",
+ "unicode-segmentation",
+ "unscanny",
+ "usvg",
+ "utf8_iter",
+ "wasmi",
+ "xmlwriter",
+]
+
+[[package]]
+name = "typst-macros"
+version = "0.15.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "033626e6fd43dc09170a9237c55a4dd308005fd751456a0c81b5864f822a97df"
+dependencies = [
+ "heck",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "typst-realize"
+version = "0.15.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a8f2eb73ab25add88cab03b26effabc657977fe850ff81556b28c6b137ff4bf1"
+dependencies = [
+ "arrayvec",
+ "bumpalo",
+ "comemo",
+ "ecow",
+ "regex",
+ "typst-html",
+ "typst-library",
+ "typst-macros",
+ "typst-syntax",
+ "typst-timing",
+ "typst-utils",
+]
+
+[[package]]
+name = "typst-svg"
+version = "0.15.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5df6dc785695aae085678bd6657aa04a1d26058a76ed042e738658078bca681e"
+dependencies = [
+ "base64 0.22.1",
+ "comemo",
+ "ecow",
+ "flate2",
+ "hayro",
+ "hayro-svg",
+ "image",
+ "indexmap",
+ "itoa",
+ "rustc-hash 2.1.3",
+ "ryu",
+ "ttf-parser",
+ "typst-assets",
+ "typst-layout",
+ "typst-library",
+ "typst-macros",
+ "typst-timing",
+ "typst-utils",
+ "xmlwriter",
+]
+
+[[package]]
+name = "typst-syntax"
+version = "0.15.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "92a20d79df5d10c7fb0b4f7c18e4b2671edfc21e5ed9ad9894e18cccefd1c70f"
+dependencies = [
+ "ecow",
+ "rustc-hash 2.1.3",
+ "serde",
+ "toml",
+ "typst-timing",
+ "typst-utils",
+ "unicode-ident",
+ "unicode-math-class",
+ "unicode-script",
+ "unicode-segmentation",
+ "unscanny",
+]
+
+[[package]]
+name = "typst-timing"
+version = "0.15.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ab6ee5110f671a23164c61caa85dbc476043d503103dedd36f16d93f970f3f59"
+dependencies = [
+ "parking_lot",
+ "serde",
+ "serde_json",
+]
+
+[[package]]
+name = "typst-utils"
+version = "0.15.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b33ad1675497b45ae9d960a16e95207c35c2c46330d1a6249a9a977670c8c160"
+dependencies = [
+ "libm",
+ "once_cell",
+ "portable-atomic",
+ "rayon",
+ "rustc-hash 2.1.3",
+ "semver",
+ "siphasher",
+ "smallvec",
+ "thin-vec",
+ "unicode-math-class",
+]
+
+[[package]]
+name = "unic-langid"
+version = "0.9.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a28ba52c9b05311f4f6e62d5d9d46f094bd6e84cb8df7b3ef952748d752a7d05"
+dependencies = [
+ "unic-langid-impl",
+ "unic-langid-macros",
+]
+
+[[package]]
+name = "unic-langid-impl"
+version = "0.9.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dce1bf08044d4b7a94028c93786f8566047edc11110595914de93362559bc658"
+dependencies = [
+ "serde",
+ "tinystr",
+]
+
+[[package]]
+name = "unic-langid-macros"
+version = "0.9.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d5957eb82e346d7add14182a3315a7e298f04e1ba4baac36f7f0dbfedba5fc25"
+dependencies = [
+ "proc-macro-hack",
+ "tinystr",
+ "unic-langid-impl",
+ "unic-langid-macros-impl",
+]
+
+[[package]]
+name = "unic-langid-macros-impl"
+version = "0.9.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a1249a628de3ad34b821ecb1001355bca3940bcb2f88558f1a8bd82e977f75b5"
+dependencies = [
+ "proc-macro-hack",
+ "quote",
+ "syn 2.0.119",
+ "unic-langid-impl",
+]
+
+[[package]]
+name = "unicode-bidi"
+version = "0.3.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5"
@@ -1230,9 +4561,24 @@ checksum = "ce61d488bcdc9bc8b5d1772c404828b17fc481c0a582b5581e95fb233aef503e"
[[package]]
name = "unicode-ident"
-version = "1.0.24"
+version = "1.0.26"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954"
+
+[[package]]
+name = "unicode-math-class"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7d246cf599d5fae3c8d56e04b20eb519adb89a8af8d0b0fbcded369aa3647d65"
+
+[[package]]
+name = "unicode-normalization"
+version = "0.1.25"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
+checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8"
+dependencies = [
+ "tinyvec",
+]
[[package]]
name = "unicode-properties"
@@ -1246,6 +4592,12 @@ version = "0.5.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "383ad40bb927465ec0ce7720e033cb4ca06912855fc35db31b5755d0de75b1ee"
+[[package]]
+name = "unicode-segmentation"
+version = "1.13.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"
+
[[package]]
name = "unicode-vo"
version = "0.1.0"
@@ -1258,13 +4610,38 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"
+[[package]]
+name = "unsafe-libyaml"
+version = "0.2.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861"
+
+[[package]]
+name = "unscanny"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e9df2af067a7953e9c3831320f35c1cc0600c30d44d9f7a12b01db1cd88d6b47"
+
+[[package]]
+name = "url"
+version = "2.5.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"
+dependencies = [
+ "form_urlencoded",
+ "idna",
+ "percent-encoding",
+ "serde",
+ "serde_derive",
+]
+
[[package]]
name = "usvg"
version = "0.47.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d46cf96c5f498d36b7a9693bc6a7075c0bb9303189d61b2249b0dc3d309c07de"
dependencies = [
- "base64",
+ "base64 0.22.1",
"data-url",
"flate2",
"fontdb",
@@ -1278,7 +4655,7 @@ dependencies = [
"siphasher",
"strict-num",
"svgtypes",
- "tiny-skia-path",
+ "tiny-skia-path 0.12.0",
"ttf-parser",
"unicode-bidi",
"unicode-script",
@@ -1286,6 +4663,75 @@ dependencies = [
"xmlwriter",
]
+[[package]]
+name = "utf16_iter"
+version = "1.0.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c8232dd3cdaed5356e0f716d285e4b40b932ac434100fe9b7e0e8e935b9e6246"
+
+[[package]]
+name = "utf8_iter"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
+
+[[package]]
+name = "uuid"
+version = "1.26.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2ef6dac1e96601b4fb3acccccff2139741fcb757cb9a36089bf5be91cfb285ce"
+dependencies = [
+ "js-sys",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "vello_common"
+version = "0.0.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3361bff7f7d82c0c496b92048db83846691f0e844cc28dee92b1c824291b55ee"
+dependencies = [
+ "bytemuck",
+ "fearless_simd",
+ "guillotiere",
+ "hashbrown 0.17.1",
+ "log",
+ "peniko",
+ "png",
+ "smallvec",
+ "thiserror 2.0.20",
+]
+
+[[package]]
+name = "vello_common"
+version = "0.0.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "19d672facaa2d697285a786cd9d44d614cd2ce54cdc022504bf339f8fff3b750"
+dependencies = [
+ "bytemuck",
+ "fearless_simd",
+ "guillotiere",
+ "hashbrown 0.17.1",
+ "log",
+ "peniko",
+ "png",
+ "smallvec",
+ "thiserror 2.0.20",
+]
+
+[[package]]
+name = "vello_cpu"
+version = "0.0.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6d8ded630e8316bb94a55881256506d1f3b9947b5f66db8a7d32ca7ba02decd0"
+dependencies = [
+ "bytemuck",
+ "glifo",
+ "hashbrown 0.17.1",
+ "png",
+ "vello_common 0.0.8",
+]
+
[[package]]
name = "version_check"
version = "0.9.5"
@@ -1293,87 +4739,349 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
[[package]]
-name = "wasm-bindgen"
-version = "0.2.110"
+name = "walkdir"
+version = "2.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"
+dependencies = [
+ "same-file",
+ "winapi-util",
+]
+
+[[package]]
+name = "walrus"
+version = "0.26.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "25b63a2bc6e4acb4cf69080068a531bad4530791098230e972ffcb64fd1dc266"
+dependencies = [
+ "anyhow",
+ "gimli",
+ "id-arena",
+ "leb128",
+ "log",
+ "rayon",
+ "walrus-macro",
+ "wasm-encoder",
+ "wasmparser 0.245.1",
+]
+
+[[package]]
+name = "walrus-macro"
+version = "0.26.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1a9b0525d7ea6e5f906aca581a172e5c91b4c595290dfa8ad4a2bc9ffef33b44"
+dependencies = [
+ "heck",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "wasi"
+version = "0.11.1+wasi-snapshot-preview1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
+
+[[package]]
+name = "wasip2"
+version = "1.0.4+wasi-0.2.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487"
+dependencies = [
+ "wit-bindgen",
+]
+
+[[package]]
+name = "wasm-bindgen"
+version = "0.2.128"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aecb87a33d3b0c5e3b7aa46336eaf486cffafbd281b195e4c8b80d50df2351bf"
+dependencies = [
+ "cfg-if",
+ "once_cell",
+ "rustversion",
+ "wasm-bindgen-macro",
+ "wasm-bindgen-shared",
+]
+
+[[package]]
+name = "wasm-bindgen-cli-support"
+version = "0.2.128"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e771daffd9404412ad1b20076ab5d0aa9f8c031e5d1734c362f720cf5538f8e3"
+dependencies = [
+ "anyhow",
+ "base64 0.22.1",
+ "leb128",
+ "log",
+ "rustc-demangle",
+ "serde",
+ "serde_json",
+ "walrus",
+ "wasm-bindgen-shared",
+ "wasmparser 0.245.1",
+]
+
+[[package]]
+name = "wasm-bindgen-futures"
+version = "0.4.78"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6ef4c5d3d2cdf5c54f4231181768f5510842e350db025faf1f7163b1030ed928"
+dependencies = [
+ "js-sys",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "wasm-bindgen-macro"
+version = "0.2.128"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a690d511e3c1a8b3a55e33511e3c2c00c78415cd23650f32b808627f5696b9ed"
+dependencies = [
+ "quote",
+ "wasm-bindgen-macro-support",
+]
+
+[[package]]
+name = "wasm-bindgen-macro-support"
+version = "0.2.128"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "411e4887f0071ef2d2164a9d5fdf2d20efbef78fccd3a78b0c10a1dc5295e48a"
+dependencies = [
+ "bumpalo",
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+ "wasm-bindgen-shared",
+]
+
+[[package]]
+name = "wasm-bindgen-shared"
+version = "0.2.128"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "81941cd78d0c92026c33e5e01312845a4cb1e9af3407f9134b100dd03144103e"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "wasm-encoder"
+version = "0.245.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f9dca005e69bf015e45577e415b9af8c67e8ee3c0e38b5b0add5aa92581ed5c"
+dependencies = [
+ "leb128fmt",
+ "wasmparser 0.245.1",
+]
+
+[[package]]
+name = "wasmi"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2300d0f78cba12f14e29e8dd157ea64050c0a688179aefdb2050105805594a0c"
+dependencies = [
+ "spin",
+ "wasmi_collections",
+ "wasmi_core",
+ "wasmi_ir",
+ "wasmparser 0.239.0",
+]
+
+[[package]]
+name = "wasmi_collections"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8a8c42a2a76148d43097b1d7cc2a5bf33d5c23bd4dd69015fc887e311767884"
+
+[[package]]
+name = "wasmi_core"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9013136083d988725953390bf668b64b7a218fabf26f8b913bbc59546b97ee27"
+dependencies = [
+ "libm",
+]
+
+[[package]]
+name = "wasmi_ir"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ba1fa003f79156f406d62ef0e1464dc03e11ace37170e9fa7524299a75ad8f68"
+dependencies = [
+ "wasmi_core",
+]
+
+[[package]]
+name = "wasmparser"
+version = "0.239.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8c9d90bb93e764f6beabf1d02028c70a2156a6583e63ac4218dd07ef733368b0"
+dependencies = [
+ "bitflags 2.13.2",
+]
+
+[[package]]
+name = "wasmparser"
+version = "0.245.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4f08c9adee0428b7bddf3890fc27e015ac4b761cc608c822667102b8bfd6995e"
+dependencies = [
+ "bitflags 2.13.2",
+ "hashbrown 0.16.1",
+ "indexmap",
+ "semver",
+ "serde",
+]
+
+[[package]]
+name = "wayland-backend"
+version = "0.3.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078"
+dependencies = [
+ "cc",
+ "downcast-rs",
+ "rustix 1.1.5",
+ "scoped-tls",
+ "smallvec",
+ "wayland-sys",
+]
+
+[[package]]
+name = "wayland-client"
+version = "0.31.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073"
+dependencies = [
+ "bitflags 2.13.2",
+ "rustix 1.1.5",
+ "wayland-backend",
+ "wayland-scanner",
+]
+
+[[package]]
+name = "wayland-csd-frame"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "625c5029dbd43d25e6aa9615e88b829a5cad13b2819c4ae129fdbb7c31ab4c7e"
+dependencies = [
+ "bitflags 2.13.2",
+ "cursor-icon",
+ "wayland-backend",
+]
+
+[[package]]
+name = "wayland-cursor"
+version = "0.31.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4a52d18780be9b1314328a3de5f930b73d2200112e3849ca6cb11822793fb34d"
+dependencies = [
+ "rustix 1.1.5",
+ "wayland-client",
+ "xcursor",
+]
+
+[[package]]
+name = "wayland-protocols"
+version = "0.32.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1de241cdc66a9d91bd84f097039eb140cdc6eec47e0cdbaf9d932a1dd6c35866"
+checksum = "23d0c813de3daa2ed6520af85a3bd49b0e722a3078506899aa9686fea58dc4b6"
dependencies = [
- "cfg-if",
- "once_cell",
- "rustversion",
- "wasm-bindgen-macro",
- "wasm-bindgen-shared",
+ "bitflags 2.13.2",
+ "wayland-backend",
+ "wayland-client",
+ "wayland-scanner",
]
[[package]]
-name = "wasm-bindgen-futures"
-version = "0.4.60"
+name = "wayland-protocols-plasma"
+version = "0.3.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a42e96ea38f49b191e08a1bab66c7ffdba24b06f9995b39a9dd60222e5b6f1da"
+checksum = "2b6d8cf1eb2c1c31ed1f5643c88a6e53538129d4af80030c8cabd1f9fa884d91"
dependencies = [
- "cfg-if",
- "futures-util",
- "js-sys",
- "once_cell",
- "wasm-bindgen",
- "web-sys",
+ "bitflags 2.13.2",
+ "wayland-backend",
+ "wayland-client",
+ "wayland-protocols",
+ "wayland-scanner",
]
[[package]]
-name = "wasm-bindgen-macro"
-version = "0.2.110"
+name = "wayland-protocols-wlr"
+version = "0.3.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e12fdf6649048f2e3de6d7d5ff3ced779cdedee0e0baffd7dff5cdfa3abc8a52"
+checksum = "eb04e52f7836d7c7976c78ca0250d61e33873c34156a2a1fc9474828ec268234"
dependencies = [
- "quote",
- "wasm-bindgen-macro-support",
+ "bitflags 2.13.2",
+ "wayland-backend",
+ "wayland-client",
+ "wayland-protocols",
+ "wayland-scanner",
]
[[package]]
-name = "wasm-bindgen-macro-support"
-version = "0.2.110"
+name = "wayland-scanner"
+version = "0.31.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0e63d1795c565ac3462334c1e396fd46dbf481c40f51f5072c310717bc4fb309"
+checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0"
dependencies = [
- "bumpalo",
"proc-macro2",
+ "quick-xml 0.41.0",
"quote",
- "syn",
- "wasm-bindgen-shared",
]
[[package]]
-name = "wasm-bindgen-shared"
-version = "0.2.110"
+name = "wayland-sys"
+version = "0.31.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e9f9cdac23a5ce71f6bf9f8824898a501e511892791ea2a0c6b8568c68b9cb53"
+checksum = "d8eab23fefc9e41f8e841df4a9c707e8a8c4ed26e944ef69297184de2785e3be"
dependencies = [
- "unicode-ident",
+ "dlib",
+ "log",
+ "once_cell",
+ "pkg-config",
]
[[package]]
name = "web-sys"
-version = "0.3.87"
+version = "0.3.105"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9fbddc4a036f00ec4f18c83445bd3115cb306a91da554919a099d9222fe4a7f8"
+dependencies = [
+ "js-sys",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "web-time"
+version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f2c7c5718134e770ee62af3b6b4a84518ec10101aad610c024b64d6ff29bb1ff"
+checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb"
dependencies = [
"js-sys",
"wasm-bindgen",
]
+[[package]]
+name = "weezl"
+version = "0.1.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88"
+
[[package]]
name = "wgpu"
-version = "28.0.0"
+version = "30.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f9cb534d5ffd109c7d1135f34cdae29e60eab94855a625dcfe1705f8bc7ad79f"
+checksum = "527ccdf43dd5b2e8676eed9984ce00e2bbb0a1b85b70c1969dcb6cd2eb55ab9e"
dependencies = [
"arrayvec",
- "bitflags",
+ "bitflags 2.13.2",
"bytemuck",
"cfg-if",
"cfg_aliases",
"document-features",
- "hashbrown 0.16.1",
+ "hashbrown 0.17.1",
"js-sys",
"log",
"naga",
@@ -1393,21 +5101,22 @@ dependencies = [
[[package]]
name = "wgpu-core"
-version = "28.0.0"
+version = "30.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8bb4c8b5db5f00e56f1f08869d870a0dff7c8bc7ebc01091fec140b0cf0211a9"
+checksum = "14c018fce9b6270aa203c2fdd56f3cce996713534bd757e4ea58c8560b121f14"
dependencies = [
"arrayvec",
- "bit-set",
- "bit-vec",
- "bitflags",
+ "bit-set 0.10.0",
+ "bit-vec 0.9.1",
+ "bitflags 2.13.2",
"bytemuck",
"cfg_aliases",
"document-features",
- "hashbrown 0.16.1",
+ "hashbrown 0.17.1",
"indexmap",
"log",
"naga",
+ "naga-types",
"once_cell",
"parking_lot",
"portable-atomic",
@@ -1415,71 +5124,75 @@ dependencies = [
"raw-window-handle",
"rustc-hash 1.1.0",
"smallvec",
- "thiserror",
+ "thiserror 2.0.20",
"wgpu-core-deps-apple",
"wgpu-core-deps-emscripten",
"wgpu-core-deps-windows-linux-android",
"wgpu-hal",
+ "wgpu-naga-bridge",
"wgpu-types",
]
[[package]]
name = "wgpu-core-deps-apple"
-version = "28.0.0"
+version = "30.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "87b7b696b918f337c486bf93142454080a32a37832ba8a31e4f48221890047da"
+checksum = "061f3d319a40d39d00b1ecc2c33b89fe21d4e6fe01859df3500a3a8ecccd6b68"
dependencies = [
"wgpu-hal",
]
[[package]]
name = "wgpu-core-deps-emscripten"
-version = "28.0.0"
+version = "30.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "34b251c331f84feac147de3c4aa3aa45112622a95dd7ee1b74384fa0458dbd79"
+checksum = "d98b86cf4abf524a902dd35f18ca6a3f08fc2ae9847c8f10b48e30491b1f0b86"
dependencies = [
"wgpu-hal",
]
[[package]]
name = "wgpu-core-deps-windows-linux-android"
-version = "28.0.0"
+version = "30.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "68ca976e72b2c9964eb243e281f6ce7f14a514e409920920dcda12ae40febaae"
+checksum = "7586165fd5f6d881cb9ce4bb71f40d6caab2c0f1837e3fc1d9788a197fb6004f"
dependencies = [
"wgpu-hal",
]
[[package]]
name = "wgpu-hal"
-version = "28.0.0"
+version = "30.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "293080d77fdd14d6b08a67c5487dfddbf874534bb7921526db56a7b75d7e3bef"
+checksum = "b6b7fb58561a792bc237628ba0792e332de418fefe145f13b5ed8201e6d52f58"
dependencies = [
"android_system_properties",
"arrayvec",
"ash",
- "bit-set",
- "bitflags",
- "block",
+ "bit-set 0.10.0",
+ "bitflags 2.13.2",
+ "block2 0.6.2",
"bytemuck",
"cfg-if",
"cfg_aliases",
- "core-graphics-types",
"glow",
"glutin_wgl_sys",
"gpu-allocator",
- "gpu-descriptor",
- "hashbrown 0.16.1",
+ "hashbrown 0.17.1",
"js-sys",
"khronos-egl",
"libc",
"libloading",
"log",
- "metal",
"naga",
+ "naga-types",
"ndk-sys",
- "objc",
+ "objc2 0.6.4",
+ "objc2-core-foundation",
+ "objc2-core-graphics",
+ "objc2-foundation 0.3.2",
+ "objc2-metal 0.3.2",
+ "objc2-quartz-core 0.3.2",
"once_cell",
"ordered-float",
"parking_lot",
@@ -1488,26 +5201,44 @@ dependencies = [
"profiling",
"range-alloc",
"raw-window-handle",
+ "raw-window-metal",
"renderdoc-sys",
"smallvec",
- "thiserror",
+ "static_assertions",
+ "thiserror 2.0.20",
"wasm-bindgen",
+ "wayland-sys",
"web-sys",
+ "wgpu-naga-bridge",
"wgpu-types",
"windows",
"windows-core",
+ "windows-result",
+]
+
+[[package]]
+name = "wgpu-naga-bridge"
+version = "30.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d2f62e73117bb7a62bfd9c5a5841438a823f6566c6442a808ee269d2d055c081"
+dependencies = [
+ "naga",
+ "wgpu-types",
]
[[package]]
name = "wgpu-types"
-version = "28.0.0"
+version = "30.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e18308757e594ed2cd27dddbb16a139c42a683819d32a2e0b1b0167552f5840c"
+checksum = "99dad6f1fbdbbdb4c278a6508b059d44688f5cebddf78d005a46a31340269286"
dependencies = [
- "bitflags",
+ "bitflags 2.13.2",
"bytemuck",
"js-sys",
"log",
+ "naga-types",
+ "raw-window-handle",
+ "static_assertions",
"web-sys",
]
@@ -1517,7 +5248,7 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
- "windows-sys",
+ "windows-sys 0.61.2",
]
[[package]]
@@ -1573,7 +5304,7 @@ checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"
dependencies = [
"proc-macro2",
"quote",
- "syn",
+ "syn 2.0.119",
]
[[package]]
@@ -1584,7 +5315,7 @@ checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"
dependencies = [
"proc-macro2",
"quote",
- "syn",
+ "syn 2.0.119",
]
[[package]]
@@ -1621,6 +5352,24 @@ dependencies = [
"windows-link",
]
+[[package]]
+name = "windows-sys"
+version = "0.52.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
+dependencies = [
+ "windows-targets",
+]
+
+[[package]]
+name = "windows-sys"
+version = "0.59.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
+dependencies = [
+ "windows-targets",
+]
+
[[package]]
name = "windows-sys"
version = "0.61.2"
@@ -1630,6 +5379,22 @@ 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-threading"
version = "0.2.1"
@@ -1639,11 +5404,222 @@ dependencies = [
"windows-link",
]
+[[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 = "winit"
+version = "0.30.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a6755fa58a9f8350bd1e472d4c3fcc25f824ec358933bba33306d0b63df5978d"
+dependencies = [
+ "ahash 0.8.12",
+ "android-activity",
+ "atomic-waker",
+ "bitflags 2.13.2",
+ "block2 0.5.1",
+ "bytemuck",
+ "calloop",
+ "cfg_aliases",
+ "concurrent-queue",
+ "core-foundation",
+ "core-graphics",
+ "cursor-icon",
+ "dpi",
+ "js-sys",
+ "libc",
+ "memmap2",
+ "ndk",
+ "objc2 0.5.2",
+ "objc2-app-kit",
+ "objc2-foundation 0.2.2",
+ "objc2-ui-kit",
+ "orbclient",
+ "percent-encoding",
+ "pin-project",
+ "raw-window-handle",
+ "redox_syscall 0.4.1",
+ "rustix 0.38.44",
+ "sctk-adwaita",
+ "smithay-client-toolkit",
+ "smol_str",
+ "tracing",
+ "unicode-segmentation",
+ "wasm-bindgen",
+ "wasm-bindgen-futures",
+ "wayland-backend",
+ "wayland-client",
+ "wayland-protocols",
+ "wayland-protocols-plasma",
+ "web-sys",
+ "web-time",
+ "windows-sys 0.52.0",
+ "x11-dl",
+ "x11rb",
+ "xkbcommon-dl",
+]
+
+[[package]]
+name = "winnow"
+version = "0.7.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "winnow"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "wit-bindgen"
+version = "0.57.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"
+
+[[package]]
+name = "write16"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d1890f4022759daae28ed4fe62859b1236caebfc61ede2f63ed4e695f3f6d936"
+
+[[package]]
+name = "writeable"
+version = "0.6.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc"
+
+[[package]]
+name = "wyz"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "05f360fc0b24296329c78fda852a1e9ae82de9cf7b27dae4b7f62f118f77b9ed"
+dependencies = [
+ "tap",
+]
+
+[[package]]
+name = "x11-dl"
+version = "2.21.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "38735924fedd5314a6e548792904ed8c6de6636285cb9fec04d5b1db85c1516f"
+dependencies = [
+ "libc",
+ "once_cell",
+ "pkg-config",
+]
+
+[[package]]
+name = "x11rb"
+version = "0.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9993aa5be5a26815fe2c3eacfc1fde061fc1a1f094bf1ad2a18bf9c495dd7414"
+dependencies = [
+ "as-raw-xcb-connection",
+ "gethostname",
+ "libc",
+ "libloading",
+ "once_cell",
+ "rustix 1.1.5",
+ "x11rb-protocol",
+]
+
+[[package]]
+name = "x11rb-protocol"
+version = "0.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd"
+
+[[package]]
+name = "x264"
+version = "0.165.3223"
+dependencies = [
+ "cc",
+ "fetch",
+ "nasm",
+]
+
+[[package]]
+name = "xcursor"
+version = "0.3.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "163b33ed8786455e2fa5d72f554057ce3f3182425434f756cd39c99839d88e23"
+
+[[package]]
+name = "xkbcommon-dl"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d039de8032a9a8856a6be89cea3e5d12fdd82306ab7c94d74e6deab2460651c5"
+dependencies = [
+ "bitflags 2.13.2",
+ "dlib",
+ "log",
+ "once_cell",
+ "xkeysym",
+]
+
+[[package]]
+name = "xkeysym"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56"
+
[[package]]
name = "xml-rs"
-version = "0.8.28"
+version = "0.8.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3ae8337f8a065cfc972643663ea4279e04e7256de865aa66fe25cec5fb912d3f"
+checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7"
[[package]]
name = "xmlwriter"
@@ -1651,22 +5627,173 @@ version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9"
+[[package]]
+name = "xxhash-rust"
+version = "0.8.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "550a2b930b62486a393c52d5c3b84bff264b28aa437ed64694d31e93b1757af7"
+
+[[package]]
+name = "yaml-rust"
+version = "0.4.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "56c1936c4cc7a1c9ab21a1ebb602eb942ba868cbd44a99cb7cdc5892335e1c85"
+dependencies = [
+ "linked-hash-map",
+]
+
+[[package]]
+name = "yoke"
+version = "0.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5"
+dependencies = [
+ "stable_deref_trait",
+ "yoke-derive",
+ "zerofrom",
+]
+
+[[package]]
+name = "yoke-derive"
+version = "0.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "33811428bee40dbceb6d545e95754741d17a6aef9a4849f0fd62e2ba4f412a78"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+ "synstructure",
+]
+
[[package]]
name = "zerocopy"
-version = "0.8.39"
+version = "0.8.57"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "db6d35d663eadb6c932438e763b262fe1a70987f9ae936e60158176d710cae4a"
+checksum = "d35102a9f36d089ccae9e4c6802bc118be4487b80aaffc0ab4e0cf5ce92d2873"
dependencies = [
"zerocopy-derive",
]
[[package]]
name = "zerocopy-derive"
-version = "0.8.39"
+version = "0.8.57"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "146c01f5ab44258da43cf276c74a2763db2ff3969c9c652c3f2de07041d0b2bc"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "zerofrom"
+version = "0.1.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272"
+dependencies = [
+ "zerofrom-derive",
+]
+
+[[package]]
+name = "zerofrom-derive"
+version = "0.1.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+ "synstructure",
+]
+
+[[package]]
+name = "zerotrie"
+version = "0.2.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f"
+dependencies = [
+ "displaydoc",
+ "litemap",
+ "serde_core",
+ "yoke",
+ "zerofrom",
+ "zerovec",
+]
+
+[[package]]
+name = "zerovec"
+version = "0.11.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8"
+dependencies = [
+ "serde",
+ "yoke",
+ "zerofrom",
+ "zerovec-derive",
+]
+
+[[package]]
+name = "zerovec-derive"
+version = "0.11.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4122cd3169e94605190e77839c9a40d40ed048d305bfdc146e7df40ab0f3e517"
+checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da"
dependencies = [
"proc-macro2",
"quote",
- "syn",
+ "syn 3.0.6",
+]
+
+[[package]]
+name = "zlib-rs"
+version = "0.6.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112"
+
+[[package]]
+name = "zmij"
+version = "1.0.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
+
+[[package]]
+name = "zstd"
+version = "0.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bf06bd8162af0734b344780deb55b42a2429ae430870d13fcc12f238e880fe6e"
+dependencies = [
+ "zstd-safe",
+]
+
+[[package]]
+name = "zstd-safe"
+version = "8.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ae42c0555055784c70058d19ba8e275528e8a99a706684868ace5da4e716a4ab"
+dependencies = [
+ "zstd-sys",
+]
+
+[[package]]
+name = "zstd-sys"
+version = "2.1.0+zstd.1.5.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0ef0a8027ec3ee71300ab3bcbcd0393f434aa72b91ca6d635a39941deae8eea0"
+dependencies = [
+ "cc",
+ "pkg-config",
+]
+
+[[package]]
+name = "zune-core"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b"
+
+[[package]]
+name = "zune-jpeg"
+version = "0.5.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296"
+dependencies = [
+ "zune-core",
]
diff --git a/rust/Cargo.toml b/rust/Cargo.toml
index 945195af..6ae8c106 100644
--- a/rust/Cargo.toml
+++ b/rust/Cargo.toml
@@ -1,22 +1,21 @@
-[package]
-name = "manimgx_engine"
-version = "0.1.0"
-edition = "2024"
-
-[lib]
-name = "engine"
-crate-type = ["cdylib"]
-
-[dependencies]
-pyo3 = { version = "0.28", features = ["extension-module"] }
-lyon = "1.0"
-usvg = "0.47"
-wgpu = "28"
-bytemuck = { version = "1", features = ["derive"] }
-numpy = "0.28"
-pollster = "0.4"
-[target.'cfg(target_os = "macos")'.dependencies]
-metal = "0.33"
+# The engine's crates, each a folder here: the engine (engine/, built into the manimgx package by
+# maturin), and the ones it is built with from others' sources, which their build scripts fetch
+# (fetch/): x264, NASM, FFmpeg with libopus, and mitex's Typst package. Cargo runs here
+# (`cargo test`, `cargo clippy`); it builds into target/.
+[workspace]
+resolver = "3"
+members = ["*"]
+exclude = ["target"]
[profile.dev]
opt-level = 2
+
+[profile.release]
+opt-level = 3
+lto = "thin"
+codegen-units = 1
+
+# mitex's own spec crate reads a prebuilt spec from a git submodule (made before 0.2.7's
+# commands) or runs whatever `typst` is on the PATH; ours is made from mitex's package
+[patch."https://github.com/mitex-rs/mitex"]
+mitex-spec-gen = { path = "mitex-spec-gen" }
diff --git a/rust/bridge/Cargo.toml b/rust/bridge/Cargo.toml
deleted file mode 100644
index 9ed96dca..00000000
--- a/rust/bridge/Cargo.toml
+++ /dev/null
@@ -1,20 +0,0 @@
-[workspace]
-resolver = "2"
-members = [
- "crates/manimgx-core",
- "crates/manimgx-encode",
- "crates/manimgx-render",
- "crates/manimgx-metal",
- "crates/manimgx-py",
-]
-default-members = [
- "crates/manimgx-core",
- "crates/manimgx-encode",
- "crates/manimgx-render",
- "crates/manimgx-metal",
-]
-
-[workspace.dependencies]
-glam = "0.29"
-bytemuck = { version = "1", features = ["derive"] }
-log = "0.4"
diff --git a/rust/bridge/crates/manimgx-core/Cargo.toml b/rust/bridge/crates/manimgx-core/Cargo.toml
deleted file mode 100644
index 1da7358f..00000000
--- a/rust/bridge/crates/manimgx-core/Cargo.toml
+++ /dev/null
@@ -1,9 +0,0 @@
-[package]
-name = "manimgx-core"
-version = "0.1.0"
-edition = "2021"
-
-[dependencies]
-glam = { workspace = true }
-bytemuck = { workspace = true }
-log = { workspace = true }
diff --git a/rust/bridge/crates/manimgx-core/src/animation/easing.rs b/rust/bridge/crates/manimgx-core/src/animation/easing.rs
deleted file mode 100644
index 99da2374..00000000
--- a/rust/bridge/crates/manimgx-core/src/animation/easing.rs
+++ /dev/null
@@ -1,61 +0,0 @@
-use std::f32::consts::PI;
-
-#[derive(Clone, Copy, Debug)]
-pub enum EasingFunction {
- Linear,
- EaseIn,
- EaseOut,
- EaseInOut,
- EaseInQuad,
- EaseOutQuad,
- EaseInOutQuad,
- EaseInCubic,
- EaseOutCubic,
- EaseInOutCubic,
-}
-
-impl EasingFunction {
- pub fn parse(s: &str) -> Self {
- match s {
- "linear" => Self::Linear,
- "ease_in" => Self::EaseIn,
- "ease_out" => Self::EaseOut,
- "ease_in_out" => Self::EaseInOut,
- "ease_in_quad" => Self::EaseInQuad,
- "ease_out_quad" => Self::EaseOutQuad,
- "ease_in_out_quad" => Self::EaseInOutQuad,
- "ease_in_cubic" => Self::EaseInCubic,
- "ease_out_cubic" => Self::EaseOutCubic,
- "ease_in_out_cubic" => Self::EaseInOutCubic,
- _ => Self::Linear,
- }
- }
-
- pub fn evaluate(&self, t: f32) -> f32 {
- let t = t.clamp(0.0, 1.0);
- match self {
- Self::Linear => t,
- Self::EaseIn => 1.0 - ((t * PI / 2.0).cos()),
- Self::EaseOut => (t * PI / 2.0).sin(),
- Self::EaseInOut => -(((t * PI).cos() - 1.0) / 2.0),
- Self::EaseInQuad => t * t,
- Self::EaseOutQuad => 1.0 - (1.0 - t) * (1.0 - t),
- Self::EaseInOutQuad => {
- if t < 0.5 {
- 2.0 * t * t
- } else {
- 1.0 - (-2.0 * t + 2.0).powi(2) / 2.0
- }
- }
- Self::EaseInCubic => t * t * t,
- Self::EaseOutCubic => 1.0 - (1.0 - t).powi(3),
- Self::EaseInOutCubic => {
- if t < 0.5 {
- 4.0 * t * t * t
- } else {
- 1.0 - (-2.0 * t + 2.0).powi(3) / 2.0
- }
- }
- }
- }
-}
diff --git a/rust/bridge/crates/manimgx-core/src/animation/keyframe.rs b/rust/bridge/crates/manimgx-core/src/animation/keyframe.rs
deleted file mode 100644
index 29c83368..00000000
--- a/rust/bridge/crates/manimgx-core/src/animation/keyframe.rs
+++ /dev/null
@@ -1,26 +0,0 @@
-use crate::animation::easing::EasingFunction;
-use crate::scene::ObjectId;
-use glam::Vec3;
-
-/// Sentinel object ID used for camera keyframes (not associated with any scene object).
-pub const CAMERA_OBJECT_ID: ObjectId = usize::MAX;
-
-#[derive(Clone, Copy, Debug)]
-pub enum AnimatedProperty {
- Translation(Vec3),
- Rotation(Vec3),
- Scale(Vec3),
- Color(Vec3),
- Opacity(f32),
- CameraPosition(Vec3),
- CameraLookAt(Vec3),
-}
-
-#[derive(Clone, Copy, Debug)]
-pub struct Keyframe {
- pub object_id: ObjectId,
- pub property: AnimatedProperty,
- pub start_time: f32,
- pub duration: f32,
- pub easing: EasingFunction,
-}
diff --git a/rust/bridge/crates/manimgx-core/src/animation/mod.rs b/rust/bridge/crates/manimgx-core/src/animation/mod.rs
deleted file mode 100644
index d8d28a43..00000000
--- a/rust/bridge/crates/manimgx-core/src/animation/mod.rs
+++ /dev/null
@@ -1,3 +0,0 @@
-pub mod easing;
-pub mod keyframe;
-pub mod timeline;
diff --git a/rust/bridge/crates/manimgx-core/src/animation/timeline.rs b/rust/bridge/crates/manimgx-core/src/animation/timeline.rs
deleted file mode 100644
index 8ee4f9b2..00000000
--- a/rust/bridge/crates/manimgx-core/src/animation/timeline.rs
+++ /dev/null
@@ -1,116 +0,0 @@
-use crate::animation::keyframe::{AnimatedProperty, Keyframe, CAMERA_OBJECT_ID};
-use crate::scene::Scene;
-
-pub struct Timeline {
- pub keyframes: Vec<Keyframe>,
- pub cursor: f32,
-}
-
-impl Timeline {
- pub fn new() -> Self {
- Self {
- keyframes: Vec::new(),
- cursor: 0.0,
- }
- }
-
- pub fn add_keyframe(&mut self, keyframe: Keyframe) {
- self.keyframes.push(keyframe);
- }
-
- pub fn advance_cursor(&mut self, seconds: f32) {
- self.cursor += seconds;
- }
-
- pub fn total_duration(&self) -> f32 {
- let keyframe_end = self
- .keyframes
- .iter()
- .map(|kf| kf.start_time + kf.duration)
- .fold(0.0_f32, f32::max);
- keyframe_end.max(self.cursor)
- }
-
- /// Evaluate the scene at a specific time, applying all active animations.
- ///
- /// Sequential animations on the same property chain correctly:
- /// each keyframe lerps from the CURRENT value (which may already be
- /// modified by an earlier completed keyframe) to its target.
- pub fn evaluate(&self, scene: &mut Scene, time: f32) {
- // First reset everything to base state
- scene.reset_to_base();
-
- // Apply keyframes in order — each lerps from current value, not base.
- // This lets sequential animations chain: if keyframe A moved pos to X
- // and keyframe B moves pos to Y, B lerps from X (not from base).
- for kf in &self.keyframes {
- // Skip keyframes that haven't started yet
- if time < kf.start_time {
- continue;
- }
-
- // Completed or zero-duration keyframes snap to target (skip easing math)
- let end_time = kf.start_time + kf.duration;
- let eased_t = if kf.duration <= 0.0 || time >= end_time {
- 1.0
- } else {
- let local_t = (time - kf.start_time) / kf.duration;
- kf.easing.evaluate(local_t)
- };
-
- // Camera keyframes use the sentinel ID
- if kf.object_id == CAMERA_OBJECT_ID {
- match &kf.property {
- AnimatedProperty::CameraPosition(target) => {
- let current = scene.camera.camera.position;
- scene.camera.camera.position = current + ((*target - current) * eased_t);
- }
- AnimatedProperty::CameraLookAt(target) => {
- let current = scene.camera.camera.look_at;
- scene.camera.camera.look_at = current + ((*target - current) * eased_t);
- }
- _ => {} // Other properties don't apply to camera
- }
- continue;
- }
-
- // ObjectId == Vec index (objects are never removed, IDs are sequential)
- if let Some(obj) = scene.objects.get_mut(kf.object_id) {
- match &kf.property {
- AnimatedProperty::Translation(target) => {
- let current = obj.transform.translation;
- obj.transform.translation = current + ((*target - current) * eased_t);
- }
- AnimatedProperty::Rotation(target) => {
- let current = obj.transform.rotation;
- obj.transform.rotation = current + ((*target - current) * eased_t);
- }
- AnimatedProperty::Scale(target) => {
- let current = obj.transform.scale;
- obj.transform.scale = current + ((*target - current) * eased_t);
- }
- AnimatedProperty::Color(target) => {
- // RGB only — don't touch color[3] (alpha is controlled by opacity)
- let cr = obj.material.color[0];
- let cg = obj.material.color[1];
- let cb = obj.material.color[2];
- obj.material.color[0] = cr + (target.x - cr) * eased_t;
- obj.material.color[1] = cg + (target.y - cg) * eased_t;
- obj.material.color[2] = cb + (target.z - cb) * eased_t;
- }
- AnimatedProperty::Opacity(target) => {
- let current = obj.material.opacity;
- obj.material.opacity = current + (target - current) * eased_t;
- }
- _ => {} // Camera properties handled above
- }
- }
- }
- }
-}
-
-impl Default for Timeline {
- fn default() -> Self {
- Self::new()
- }
-}
diff --git a/rust/bridge/crates/manimgx-core/src/camera.rs b/rust/bridge/crates/manimgx-core/src/camera.rs
deleted file mode 100644
index 676bf11a..00000000
--- a/rust/bridge/crates/manimgx-core/src/camera.rs
+++ /dev/null
@@ -1,225 +0,0 @@
-use glam::{Mat4, Vec3};
-
-/// View transform — position, look_at, up. Shared by all projection types.
-#[derive(Clone, Copy, Debug)]
-pub struct Camera {
- pub position: Vec3,
- pub look_at: Vec3,
- pub up: Vec3,
-}
-
-impl Default for Camera {
- fn default() -> Self {
- Self {
- position: Vec3::new(3.0, 2.0, 5.0),
- look_at: Vec3::ZERO,
- up: Vec3::Y,
- }
- }
-}
-
-impl Camera {
- pub fn view_matrix(&self) -> Mat4 {
- Mat4::look_at_rh(self.position, self.look_at, self.up)
- }
-}
-
-/// Projection type — each variant stores its own parameters and computes its own matrix.
-#[derive(Clone, Copy, Debug)]
-pub enum Projection {
- /// Standard perspective projection.
- Perspective { fov: f32, near: f32, far: f32 },
- /// Parallel projection with oblique rays (cabinet/cavalier).
- /// `alpha` — angle of oblique rays in degrees.
- /// `l` — foreshortening ratio (0.5 = cabinet, 1.0 = cavalier).
- /// `height` — visible vertical range in world units. Width = height * aspect_ratio.
- Oblique {
- alpha: f32,
- l: f32,
- height: f32,
- near: f32,
- far: f32,
- },
-}
-
-impl Projection {
- /// Returns the pure projection matrix (no oblique shear).
- pub fn projection_matrix(&self, _aspect_ratio: f32) -> Mat4 {
- match self {
- Projection::Perspective { fov, near, far } => {
- Mat4::perspective_rh(fov.to_radians(), _aspect_ratio, *near, *far)
- }
- Projection::Oblique {
- height, near, far, ..
- } => {
- let width = height * _aspect_ratio;
- let half_w = width / 2.0;
- let half_h = height / 2.0;
- Mat4::orthographic_rh(-half_w, half_w, -half_h, half_h, *near, *far)
- }
- }
- }
-
- /// Returns the oblique shear matrix (identity for non-oblique projections).
- /// This shear must be applied in world space (before the view transform)
- /// so that objects at z=0 are unaffected.
- pub fn world_shear_matrix(&self) -> Mat4 {
- match self {
- Projection::Perspective { .. } => Mat4::IDENTITY,
- Projection::Oblique { alpha, l, .. } => {
- let alpha_rad = alpha.to_radians();
- let shear_x = l * alpha_rad.cos();
- let shear_y = l * alpha_rad.sin();
- Mat4::from_cols_array(&[
- 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, shear_x, shear_y, 1.0, 0.0, 0.0, 0.0,
- 0.0, 1.0,
- ])
- }
- }
- }
-}
-
-impl Default for Projection {
- fn default() -> Self {
- Projection::Perspective {
- fov: 45.0,
- near: 0.1,
- far: 100.0,
- }
- }
-}
-
-/// Composes Camera (view) + Projection into a single rig.
-/// Stored in Scene, consumed by renderer.
-#[derive(Clone, Copy, Debug, Default)]
-pub struct CameraRig {
- pub camera: Camera,
- pub projection: Projection,
-}
-
-impl CameraRig {
- pub fn view_projection_matrix(&self, aspect_ratio: f32) -> Mat4 {
- // Oblique shear is applied in world space (before view transform)
- // so that 2D objects at z=0 are unaffected by the shear.
- // Pipeline: projection * view * shear * world_pos
- let proj = self.projection.projection_matrix(aspect_ratio);
- let view = self.camera.view_matrix();
- let shear = self.projection.world_shear_matrix();
- proj * view * shear
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn camera_view_matrix_look_at() {
- let camera = Camera {
- position: Vec3::new(0.0, 0.0, 5.0),
- look_at: Vec3::ZERO,
- up: Vec3::Y,
- };
- let view = camera.view_matrix();
- let expected = Mat4::look_at_rh(Vec3::new(0.0, 0.0, 5.0), Vec3::ZERO, Vec3::Y);
- assert_eq!(view, expected);
- }
-
- #[test]
- fn perspective_projection_matches_glam() {
- let proj = Projection::Perspective {
- fov: 45.0,
- near: 0.1,
- far: 100.0,
- };
- let aspect = 16.0 / 9.0;
- let mat = proj.projection_matrix(aspect);
- let expected = Mat4::perspective_rh(45.0_f32.to_radians(), aspect, 0.1, 100.0);
- assert_eq!(mat, expected);
- }
-
- #[test]
- fn oblique_cavalier_vs_cabinet() {
- let cavalier = Projection::Oblique {
- alpha: 45.0,
- l: 1.0,
- height: 10.0,
- near: 0.1,
- far: 100.0,
- };
- let cabinet = Projection::Oblique {
- alpha: 45.0,
- l: 0.5,
- height: 10.0,
- near: 0.1,
- far: 100.0,
- };
-
- // Cavalier has stronger shear than cabinet (l=1.0 vs l=0.5)
- let cav_shear = cavalier.world_shear_matrix();
- let cab_shear = cabinet.world_shear_matrix();
- assert_ne!(cav_shear, Mat4::IDENTITY);
- assert_ne!(cab_shear, Mat4::IDENTITY);
- assert_ne!(cav_shear, cab_shear);
- }
-
- #[test]
- fn oblique_different_angles() {
- let alpha0 = Projection::Oblique {
- alpha: 0.0,
- l: 0.5,
- height: 10.0,
- near: 0.1,
- far: 100.0,
- };
- let alpha45 = Projection::Oblique {
- alpha: 45.0,
- l: 0.5,
- height: 10.0,
- near: 0.1,
- far: 100.0,
- };
- let shear0 = alpha0.world_shear_matrix();
- let shear45 = alpha45.world_shear_matrix();
- assert_ne!(shear0, shear45);
- }
-
- #[test]
- fn oblique_2d_objects_unaffected_by_shear() {
- // Objects at z=0 should not be displaced by oblique shear
- let proj = Projection::Oblique {
- alpha: 45.0,
- l: 0.5,
- height: 8.0,
- near: 0.1,
- far: 100.0,
- };
- let shear = proj.world_shear_matrix();
- let point_at_z0 = glam::Vec4::new(3.0, 2.0, 0.0, 1.0);
- let result = shear * point_at_z0;
- assert_eq!(result.x, 3.0);
- assert_eq!(result.y, 2.0);
- assert_eq!(result.z, 0.0);
- }
-
- #[test]
- fn camera_rig_perspective_view_projection() {
- // For perspective (no shear), view_projection = projection * view
- let rig = CameraRig {
- camera: Camera {
- position: Vec3::new(3.0, 2.0, 5.0),
- look_at: Vec3::ZERO,
- up: Vec3::Y,
- },
- projection: Projection::Perspective {
- fov: 60.0,
- near: 0.5,
- far: 200.0,
- },
- };
- let aspect = 16.0 / 9.0;
- let vp = rig.view_projection_matrix(aspect);
- let expected = rig.projection.projection_matrix(aspect) * rig.camera.view_matrix();
- assert_eq!(vp, expected);
- }
-}
diff --git a/rust/bridge/crates/manimgx-core/src/color.rs b/rust/bridge/crates/manimgx-core/src/color.rs
deleted file mode 100644
index 5aef7d4d..00000000
--- a/rust/bridge/crates/manimgx-core/src/color.rs
+++ /dev/null
@@ -1,9 +0,0 @@
-/// Convert an sRGB component [0,1] to linear space.
-#[inline]
-pub fn srgb_to_linear(c: f32) -> f32 {
- if c <= 0.04045 {
- c / 12.92
- } else {
- ((c + 0.055) / 1.055).powf(2.4)
- }
-}
diff --git a/rust/bridge/crates/manimgx-core/src/encoder.rs b/rust/bridge/crates/manimgx-core/src/encoder.rs
deleted file mode 100644
index 5561e713..00000000
--- a/rust/bridge/crates/manimgx-core/src/encoder.rs
+++ /dev/null
@@ -1,150 +0,0 @@
-use std::io::Write;
-use std::process::{Child, Command, Stdio};
-
-#[derive(Debug, Clone, Copy)]
-pub enum FfmpegCodec {
- H264VideoToolbox,
- H264Vaapi,
-}
-
-pub struct FfmpegEncoder {
- child: Child,
- expected_frame_size: usize,
-}
-
-impl FfmpegEncoder {
- pub fn with_pixel_format(
- output_path: &str,
- width: u32,
- height: u32,
- fps: u32,
- codec: FfmpegCodec,
- crf: u32,
- pixel_format: &str,
- ) -> Self {
- let expected_frame_size = match pixel_format {
- "nv12" => (width * height * 3 / 2) as usize,
- _ => (width * height * 4) as usize,
- };
-
- let mut args = vec![
- "-y".to_string(),
- "-f".to_string(),
- "rawvideo".to_string(),
- "-pixel_format".to_string(),
- pixel_format.to_string(),
- "-video_size".to_string(),
- format!("{}x{}", width, height),
- "-framerate".to_string(),
- fps.to_string(),
- ];
-
- // NV12: signal BT.709 color space to ffmpeg input
- if pixel_format == "nv12" {
- args.extend([
- "-color_primaries".to_string(),
- "bt709".to_string(),
- "-color_trc".to_string(),
- "bt709".to_string(),
- "-colorspace".to_string(),
- "bt709".to_string(),
- ]);
- }
-
- // VAAPI needs -vaapi_device before -i
- if matches!(codec, FfmpegCodec::H264Vaapi) {
- args.extend([
- "-vaapi_device".to_string(), "/dev/dri/renderD128".to_string(),
- ]);
- }
-
- args.extend(["-i".to_string(), "-".to_string()]);
-
- match codec {
- FfmpegCodec::H264VideoToolbox => {
- args.extend([
- "-c:v".to_string(),
- "h264_videotoolbox".to_string(),
- ]);
- // NV12 is already YUV420 semi-planar — no swscale needed
- if pixel_format != "nv12" {
- args.extend(["-pix_fmt".to_string(), "yuv420p".to_string()]);
- }
- args.extend([
- "-q:v".to_string(),
- "65".to_string(),
- "-allow_sw".to_string(),
- "0".to_string(),
- ]);
- }
- FfmpegCodec::H264Vaapi => {
- args.extend([
- "-c:v".to_string(), "h264_vaapi".to_string(),
- ]);
- if pixel_format != "nv12" {
- args.extend(["-vf".to_string(), "format=nv12,hwupload".to_string()]);
- } else {
- args.extend(["-vf".to_string(), "hwupload".to_string()]);
- }
- args.extend([
- "-qp".to_string(), crf.to_string(),
- ]);
- }
- }
-
- args.push(output_path.to_string());
-
- let child = Command::new("ffmpeg")
- .args(&args)
- .stdin(Stdio::piped())
- .stdout(Stdio::null())
- .stderr(Stdio::null())
- .spawn()
- .expect(
- "Failed to start ffmpeg. Please ensure ffmpeg is installed and available in PATH.\n\
- Install with: brew install ffmpeg (macOS) or apt install ffmpeg (Linux)",
- );
-
- log::info!(
- "ffmpeg encoder started ({:?}): {}x{} @ {} fps -> {}",
- codec,
- width,
- height,
- fps,
- output_path
- );
-
- Self {
- child,
- expected_frame_size,
- }
- }
-
- pub fn write_frame(&mut self, pixels: &[u8]) {
- assert_eq!(
- pixels.len(),
- self.expected_frame_size,
- "Frame size mismatch: expected {} bytes, got {}",
- self.expected_frame_size,
- pixels.len()
- );
-
- if let Some(stdin) = self.child.stdin.as_mut() {
- stdin
- .write_all(pixels)
- .expect("Failed to write frame to ffmpeg");
- }
- }
-
- pub fn finish(mut self) {
- // Close stdin to signal EOF to ffmpeg
- drop(self.child.stdin.take());
- let status = self.child.wait().expect("Failed to wait for ffmpeg");
- if !status.success() {
- log::error!("ffmpeg exited with status: {}", status);
- } else {
- log::info!("ffmpeg encoding completed successfully");
- }
- }
-}
-
diff --git a/rust/bridge/crates/manimgx-core/src/geometry/mod.rs b/rust/bridge/crates/manimgx-core/src/geometry/mod.rs
deleted file mode 100644
index db559df2..00000000
--- a/rust/bridge/crates/manimgx-core/src/geometry/mod.rs
+++ /dev/null
@@ -1,7 +0,0 @@
-pub mod three_d;
-pub mod two_d;
-
-// Re-exports for existing consumers
-pub use three_d::bezier;
-pub use three_d::mesh;
-pub use three_d::primitives;
diff --git a/rust/bridge/crates/manimgx-core/src/geometry/three_d/bezier.rs b/rust/bridge/crates/manimgx-core/src/geometry/three_d/bezier.rs
deleted file mode 100644
index 1499ca5d..00000000
--- a/rust/bridge/crates/manimgx-core/src/geometry/three_d/bezier.rs
+++ /dev/null
@@ -1,80 +0,0 @@
-use crate::vertex::Vertex;
-use glam::Vec3;
-
-pub struct BezierCurve;
-
-impl BezierCurve {
- /// De Casteljau evaluation of a cubic Bezier at parameter t
- fn evaluate(points: &[Vec3; 4], t: f32) -> Vec3 {
- let p01 = points[0].lerp(points[1], t);
- let p12 = points[1].lerp(points[2], t);
- let p23 = points[2].lerp(points[3], t);
- let p012 = p01.lerp(p12, t);
- let p123 = p12.lerp(p23, t);
- p012.lerp(p123, t)
- }
-
- /// Tangent of a cubic Bezier at parameter t
- fn tangent(points: &[Vec3; 4], t: f32) -> Vec3 {
- let p01 = points[0].lerp(points[1], t);
- let p12 = points[1].lerp(points[2], t);
- let p23 = points[2].lerp(points[3], t);
- let p012 = p01.lerp(p12, t);
- let p123 = p12.lerp(p23, t);
- (p123 - p012).normalize_or_zero()
- }
-
- /// Tessellate a cubic Bezier into a tube mesh
- pub fn generate_tube(
- control_points: &[[f32; 3]; 4],
- color: [f32; 4],
- width: f32,
- segments: u32,
- radial_segments: u32,
- ) -> (Vec<Vertex>, Vec<u32>) {
- let points = [
- Vec3::from_array(control_points[0]),
- Vec3::from_array(control_points[1]),
- Vec3::from_array(control_points[2]),
- Vec3::from_array(control_points[3]),
- ];
-
- let radius = width / 2.0;
- let mut vertices = Vec::new();
- let mut indices = Vec::new();
-
- for i in 0..=segments {
- let t = i as f32 / segments as f32;
- let center = Self::evaluate(&points, t);
- let forward = Self::tangent(&points, t);
-
- // Build a frame around the curve
- let up = if forward.dot(Vec3::Y).abs() > 0.99 {
- Vec3::Z
- } else {
- Vec3::Y
- };
- let right = forward.cross(up).normalize();
- let actual_up = right.cross(forward).normalize();
-
- for j in 0..=radial_segments {
- let angle = j as f32 * 2.0 * std::f32::consts::PI / radial_segments as f32;
- let normal = right * angle.cos() + actual_up * angle.sin();
- let pos = center + normal * radius;
- vertices.push(Vertex::new(pos.to_array(), normal.to_array(), color));
- }
- }
-
- for i in 0..segments {
- for j in 0..radial_segments {
- let current = i * (radial_segments + 1) + j;
- let next = current + radial_segments + 1;
- indices.extend_from_slice(&[current, next, current + 1]);
- indices.extend_from_slice(&[current + 1, next, next + 1]);
- }
- }
-
- (vertices, indices)
- }
-
-}
diff --git a/rust/bridge/crates/manimgx-core/src/geometry/three_d/mesh.rs b/rust/bridge/crates/manimgx-core/src/geometry/three_d/mesh.rs
deleted file mode 100644
index 43595eed..00000000
--- a/rust/bridge/crates/manimgx-core/src/geometry/three_d/mesh.rs
+++ /dev/null
@@ -1,56 +0,0 @@
-use crate::vertex::Vertex;
-
-pub struct SurfaceMesh;
-
-impl SurfaceMesh {
- /// Generate a mesh from a function f(x, z) -> y
- /// over the domain [x_min, x_max] x [z_min, z_max]
- pub fn from_function<F>(
- f: F,
- x_range: [f32; 2],
- z_range: [f32; 2],
- resolution: u32,
- color: [f32; 4],
- ) -> (Vec<Vertex>, Vec<u32>)
- where
- F: Fn(f32, f32) -> f32,
- {
- let n_verts = ((resolution + 1) * (resolution + 1)) as usize;
- let n_indices = (resolution * resolution * 6) as usize;
- let mut vertices = Vec::with_capacity(n_verts);
- let mut indices = Vec::with_capacity(n_indices);
-
- let dx = (x_range[1] - x_range[0]) / resolution as f32;
- let dz = (z_range[1] - z_range[0]) / resolution as f32;
-
- for zi in 0..=resolution {
- for xi in 0..=resolution {
- let x = x_range[0] + xi as f32 * dx;
- let z = z_range[0] + zi as f32 * dz;
- let y = f(x, z);
-
- // Approximate normal via central differences
- let eps = 0.001;
- let dydx = (f(x + eps, z) - f(x - eps, z)) / (2.0 * eps);
- let dydz = (f(x, z + eps) - f(x, z - eps)) / (2.0 * eps);
- let normal = [-dydx, 1.0, -dydz];
- let len =
- (normal[0] * normal[0] + normal[1] * normal[1] + normal[2] * normal[2]).sqrt();
- let normal = [normal[0] / len, normal[1] / len, normal[2] / len];
-
- vertices.push(Vertex::new([x, y, z], normal, color));
- }
- }
-
- for zi in 0..resolution {
- for xi in 0..resolution {
- let current = zi * (resolution + 1) + xi;
- let next_row = current + resolution + 1;
- indices.extend_from_slice(&[current, next_row, current + 1]);
- indices.extend_from_slice(&[current + 1, next_row, next_row + 1]);
- }
- }
-
- (vertices, indices)
- }
-}
diff --git a/rust/bridge/crates/manimgx-core/src/geometry/three_d/mod.rs b/rust/bridge/crates/manimgx-core/src/geometry/three_d/mod.rs
deleted file mode 100644
index e8ba253f..00000000
--- a/rust/bridge/crates/manimgx-core/src/geometry/three_d/mod.rs
+++ /dev/null
@@ -1,3 +0,0 @@
-pub mod bezier;
-pub mod mesh;
-pub mod primitives;
diff --git a/rust/bridge/crates/manimgx-core/src/geometry/three_d/primitives.rs b/rust/bridge/crates/manimgx-core/src/geometry/three_d/primitives.rs
deleted file mode 100644
index 2adcd45f..00000000
--- a/rust/bridge/crates/manimgx-core/src/geometry/three_d/primitives.rs
+++ /dev/null
@@ -1,273 +0,0 @@
-use crate::vertex::Vertex;
-use std::f32::consts::PI;
-
-pub struct Cube;
-pub struct Box3D;
-pub struct Sphere;
-pub struct Cylinder;
-pub struct Plane;
-pub struct ParametricSurface;
-
-impl Cube {
- pub fn generate(size: f32, color: [f32; 4]) -> (Vec<Vertex>, Vec<u32>) {
- let h = size / 2.0;
-
- #[rustfmt::skip]
- let face_data: &[([f32; 3], [[f32; 3]; 4])] = &[
- // normal, 4 corner positions
- ([0.0, 0.0, 1.0], [[-h, -h, h], [h, -h, h], [h, h, h], [-h, h, h]]), // front
- ([0.0, 0.0, -1.0], [[h, -h, -h], [-h, -h, -h], [-h, h, -h], [h, h, -h]]), // back
- ([0.0, 1.0, 0.0], [[-h, h, h], [h, h, h], [h, h, -h], [-h, h, -h]]), // top
- ([0.0, -1.0, 0.0], [[-h, -h, -h], [h, -h, -h], [h, -h, h], [-h, -h, h]]), // bottom
- ([1.0, 0.0, 0.0], [[h, -h, h], [h, -h, -h], [h, h, -h], [h, h, h]]), // right
- ([-1.0, 0.0, 0.0], [[-h, -h, -h], [-h, -h, h], [-h, h, h], [-h, h, -h]]), // left
- ];
-
- let mut vertices = Vec::with_capacity(24);
- let mut indices = Vec::with_capacity(36);
-
- for (normal, positions) in face_data {
- let base = vertices.len() as u32;
- for pos in positions {
- vertices.push(Vertex::new(*pos, *normal, color));
- }
- indices.extend_from_slice(&[base, base + 1, base + 2, base, base + 2, base + 3]);
- }
-
- (vertices, indices)
- }
-}
-
-impl Box3D {
- /// Generate a rectangular prism (box) with independent width, height, depth.
- /// Width = X axis, Height = Y axis, Depth = Z axis.
- pub fn generate(width: f32, height: f32, depth: f32, color: [f32; 4]) -> (Vec<Vertex>, Vec<u32>) {
- let hw = width / 2.0;
- let hh = height / 2.0;
- let hd = depth / 2.0;
-
- #[rustfmt::skip]
- let face_data: &[([f32; 3], [[f32; 3]; 4])] = &[
- ([0.0, 0.0, 1.0], [[-hw, -hh, hd], [hw, -hh, hd], [hw, hh, hd], [-hw, hh, hd]]), // front
- ([0.0, 0.0, -1.0], [[hw, -hh, -hd], [-hw, -hh, -hd], [-hw, hh, -hd], [hw, hh, -hd]]), // back
- ([0.0, 1.0, 0.0], [[-hw, hh, hd], [hw, hh, hd], [hw, hh, -hd], [-hw, hh, -hd]]), // top
- ([0.0, -1.0, 0.0], [[-hw, -hh, -hd], [hw, -hh, -hd], [hw, -hh, hd], [-hw, -hh, hd]]), // bottom
- ([1.0, 0.0, 0.0], [[hw, -hh, hd], [hw, -hh, -hd], [hw, hh, -hd], [hw, hh, hd]]), // right
- ([-1.0, 0.0, 0.0], [[-hw, -hh, -hd], [-hw, -hh, hd], [-hw, hh, hd], [-hw, hh, -hd]]), // left
- ];
-
- let mut vertices = Vec::with_capacity(24);
- let mut indices = Vec::with_capacity(36);
-
- for (normal, positions) in face_data {
- let base = vertices.len() as u32;
- for pos in positions {
- vertices.push(Vertex::new(*pos, *normal, color));
- }
- indices.extend_from_slice(&[base, base + 1, base + 2, base, base + 2, base + 3]);
- }
-
- (vertices, indices)
- }
-}
-
-impl Sphere {
- pub fn generate(
- radius: f32,
- color: [f32; 4],
- segments: u32,
- rings: u32,
- ) -> (Vec<Vertex>, Vec<u32>) {
- let mut vertices = Vec::new();
- let mut indices = Vec::new();
-
- for ring in 0..=rings {
- let theta = ring as f32 * PI / rings as f32;
- let sin_theta = theta.sin();
- let cos_theta = theta.cos();
-
- for seg in 0..=segments {
- let phi = seg as f32 * 2.0 * PI / segments as f32;
- let sin_phi = phi.sin();
- let cos_phi = phi.cos();
-
- let x = sin_theta * cos_phi;
- let y = cos_theta;
- let z = sin_theta * sin_phi;
-
- vertices.push(Vertex::new(
- [x * radius, y * radius, z * radius],
- [x, y, z],
- color,
- ));
- }
- }
-
- for ring in 0..rings {
- for seg in 0..segments {
- let current = ring * (segments + 1) + seg;
- let next = current + segments + 1;
-
- indices.extend_from_slice(&[current, next, current + 1]);
- indices.extend_from_slice(&[current + 1, next, next + 1]);
- }
- }
-
- (vertices, indices)
- }
-}
-
-impl Cylinder {
- pub fn generate(
- radius: f32,
- height: f32,
- color: [f32; 4],
- segments: u32,
- ) -> (Vec<Vertex>, Vec<u32>) {
- let mut vertices = Vec::new();
- let mut indices = Vec::new();
- let half_h = height / 2.0;
-
- // Side vertices
- for i in 0..=segments {
- let angle = i as f32 * 2.0 * PI / segments as f32;
- let x = angle.cos() * radius;
- let z = angle.sin() * radius;
- let nx = angle.cos();
- let nz = angle.sin();
-
- vertices.push(Vertex::new([x, -half_h, z], [nx, 0.0, nz], color));
- vertices.push(Vertex::new([x, half_h, z], [nx, 0.0, nz], color));
- }
-
- // Side indices
- for i in 0..segments {
- let base = i * 2;
- indices.extend_from_slice(&[base, base + 1, base + 2]);
- indices.extend_from_slice(&[base + 2, base + 1, base + 3]);
- }
-
- // Top cap
- let top_center = vertices.len() as u32;
- vertices.push(Vertex::new([0.0, half_h, 0.0], [0.0, 1.0, 0.0], color));
- for i in 0..=segments {
- let angle = i as f32 * 2.0 * PI / segments as f32;
- let x = angle.cos() * radius;
- let z = angle.sin() * radius;
- vertices.push(Vertex::new([x, half_h, z], [0.0, 1.0, 0.0], color));
- }
- for i in 0..segments {
- indices.extend_from_slice(&[top_center, top_center + 1 + i, top_center + 2 + i]);
- }
-
- // Bottom cap
- let bot_center = vertices.len() as u32;
- vertices.push(Vertex::new([0.0, -half_h, 0.0], [0.0, -1.0, 0.0], color));
- for i in 0..=segments {
- let angle = i as f32 * 2.0 * PI / segments as f32;
- let x = angle.cos() * radius;
- let z = angle.sin() * radius;
- vertices.push(Vertex::new([x, -half_h, z], [0.0, -1.0, 0.0], color));
- }
- for i in 0..segments {
- indices.extend_from_slice(&[bot_center, bot_center + 2 + i, bot_center + 1 + i]);
- }
-
- (vertices, indices)
- }
-}
-
-impl Plane {
- pub fn generate(width: f32, depth: f32, color: [f32; 4]) -> (Vec<Vertex>, Vec<u32>) {
- let hw = width / 2.0;
- let hd = depth / 2.0;
- let up = [0.0, 1.0, 0.0];
-
- let vertices = vec![
- Vertex::new([-hw, 0.0, -hd], up, color),
- Vertex::new([hw, 0.0, -hd], up, color),
- Vertex::new([hw, 0.0, hd], up, color),
- Vertex::new([-hw, 0.0, hd], up, color),
- ];
- let indices = vec![0, 2, 1, 0, 3, 2];
-
- (vertices, indices)
- }
-}
-
-impl ParametricSurface {
- /// Generate a parametric surface from pre-computed point grid.
- /// `points` is a row-major grid of [x, y, z] positions, with dimensions `u_steps × v_steps`.
- /// Normals are computed from cross products of partial derivatives.
- pub fn generate(
- points: &[[f32; 3]],
- u_steps: u32,
- v_steps: u32,
- color: [f32; 4],
- ) -> (Vec<Vertex>, Vec<u32>) {
- let mut vertices = Vec::with_capacity((u_steps * v_steps) as usize);
- let mut indices = Vec::new();
-
- // Build vertices with computed normals
- for vi in 0..v_steps {
- for ui in 0..u_steps {
- let idx = (vi * u_steps + ui) as usize;
- let p = points[idx];
-
- // Compute normal via finite differences
- let du = if ui + 1 < u_steps {
- let next = points[idx + 1];
- [next[0] - p[0], next[1] - p[1], next[2] - p[2]]
- } else if ui > 0 {
- let prev = points[idx - 1];
- [p[0] - prev[0], p[1] - prev[1], p[2] - prev[2]]
- } else {
- [1.0, 0.0, 0.0]
- };
-
- let dv = if vi + 1 < v_steps {
- let next = points[(idx + u_steps as usize).min(points.len() - 1)];
- [next[0] - p[0], next[1] - p[1], next[2] - p[2]]
- } else if vi > 0 {
- let prev = points[idx.saturating_sub(u_steps as usize)];
- [p[0] - prev[0], p[1] - prev[1], p[2] - prev[2]]
- } else {
- [0.0, 0.0, 1.0]
- };
-
- // Cross product du × dv
- let normal = [
- du[1] * dv[2] - du[2] * dv[1],
- du[2] * dv[0] - du[0] * dv[2],
- du[0] * dv[1] - du[1] * dv[0],
- ];
- let len = (normal[0] * normal[0] + normal[1] * normal[1] + normal[2] * normal[2])
- .sqrt()
- .max(1e-6);
- let normal = [normal[0] / len, normal[1] / len, normal[2] / len];
-
- vertices.push(Vertex::new(p, normal, color));
- }
- }
-
- // Build triangle indices
- for vi in 0..(v_steps - 1) {
- for ui in 0..(u_steps - 1) {
- let tl = vi * u_steps + ui;
- let tr = tl + 1;
- let bl = tl + u_steps;
- let br = bl + 1;
-
- indices.push(tl);
- indices.push(bl);
- indices.push(tr);
-
- indices.push(tr);
- indices.push(bl);
- indices.push(br);
- }
- }
-
- (vertices, indices)
- }
-}
diff --git a/rust/bridge/crates/manimgx-core/src/geometry/two_d/axes.rs b/rust/bridge/crates/manimgx-core/src/geometry/two_d/axes.rs
deleted file mode 100644
index b2c71a76..00000000
--- a/rust/bridge/crates/manimgx-core/src/geometry/two_d/axes.rs
+++ /dev/null
@@ -1,215 +0,0 @@
-use crate::vertex::Vertex;
-
-pub struct NumberLine;
-pub struct Axes2D;
-pub struct Grid;
-
-const NORMAL_2D: [f32; 3] = [0.0, 0.0, 1.0];
-
-impl NumberLine {
- /// Generate a horizontal number line with tick marks.
- /// `range` = [min, max], line along x-axis at y=0.
- pub fn generate(
- range: [f32; 2],
- color: [f32; 4],
- line_width: f32,
- tick_spacing: f32,
- tick_height: f32,
- tick_width: f32,
- ) -> (Vec<Vertex>, Vec<u32>) {
- let mut vertices = Vec::new();
- let mut indices = Vec::new();
-
- // Main horizontal line
- let half_w = line_width / 2.0;
- let base = vertices.len() as u32;
- vertices.push(Vertex::new([range[0], -half_w, 0.0], NORMAL_2D, color));
- vertices.push(Vertex::new([range[0], half_w, 0.0], NORMAL_2D, color));
- vertices.push(Vertex::new([range[1], half_w, 0.0], NORMAL_2D, color));
- vertices.push(Vertex::new([range[1], -half_w, 0.0], NORMAL_2D, color));
- indices.extend_from_slice(&[base, base + 1, base + 2, base, base + 2, base + 3]);
-
- // Tick marks
- if tick_spacing > 0.0 {
- let half_th = tick_height / 2.0;
- let half_tw = tick_width / 2.0;
-
- // Start from the first tick position >= range[0]
- let start_tick = (range[0] / tick_spacing).ceil() as i32;
- let end_tick = (range[1] / tick_spacing).floor() as i32;
-
- for i in start_tick..=end_tick {
- let x = i as f32 * tick_spacing;
- let base = vertices.len() as u32;
- vertices.push(Vertex::new([x - half_tw, -half_th, 0.0], NORMAL_2D, color));
- vertices.push(Vertex::new([x + half_tw, -half_th, 0.0], NORMAL_2D, color));
- vertices.push(Vertex::new([x + half_tw, half_th, 0.0], NORMAL_2D, color));
- vertices.push(Vertex::new([x - half_tw, half_th, 0.0], NORMAL_2D, color));
- indices.extend_from_slice(&[base, base + 1, base + 2, base, base + 2, base + 3]);
- }
- }
-
- (vertices, indices)
- }
-}
-
-impl Axes2D {
- /// Generate X and Y axes with optional arrow tips.
- #[allow(clippy::too_many_arguments)]
- pub fn generate(
- x_range: [f32; 2],
- y_range: [f32; 2],
- color: [f32; 4],
- line_width: f32,
- tick_spacing: f32,
- tick_height: f32,
- tick_width: f32,
- include_arrows: bool,
- ) -> (Vec<Vertex>, Vec<u32>) {
- let mut vertices = Vec::new();
- let mut indices = Vec::new();
-
- // X-axis: horizontal line
- let half_w = line_width / 2.0;
- let base = vertices.len() as u32;
- vertices.push(Vertex::new([x_range[0], -half_w, 0.0], NORMAL_2D, color));
- vertices.push(Vertex::new([x_range[0], half_w, 0.0], NORMAL_2D, color));
- vertices.push(Vertex::new([x_range[1], half_w, 0.0], NORMAL_2D, color));
- vertices.push(Vertex::new([x_range[1], -half_w, 0.0], NORMAL_2D, color));
- indices.extend_from_slice(&[base, base + 1, base + 2, base, base + 2, base + 3]);
-
- // Y-axis: vertical line
- let base = vertices.len() as u32;
- vertices.push(Vertex::new([-half_w, y_range[0], 0.0], NORMAL_2D, color));
- vertices.push(Vertex::new([half_w, y_range[0], 0.0], NORMAL_2D, color));
- vertices.push(Vertex::new([half_w, y_range[1], 0.0], NORMAL_2D, color));
- vertices.push(Vertex::new([-half_w, y_range[1], 0.0], NORMAL_2D, color));
- indices.extend_from_slice(&[base, base + 1, base + 2, base, base + 2, base + 3]);
-
- // X-axis tick marks
- if tick_spacing > 0.0 {
- let half_th = tick_height / 2.0;
- let half_tw = tick_width / 2.0;
-
- let start = (x_range[0] / tick_spacing).ceil() as i32;
- let end = (x_range[1] / tick_spacing).floor() as i32;
- for i in start..=end {
- if i == 0 {
- continue;
- } // skip origin
- let x = i as f32 * tick_spacing;
- let base = vertices.len() as u32;
- vertices.push(Vertex::new([x - half_tw, -half_th, 0.0], NORMAL_2D, color));
- vertices.push(Vertex::new([x + half_tw, -half_th, 0.0], NORMAL_2D, color));
- vertices.push(Vertex::new([x + half_tw, half_th, 0.0], NORMAL_2D, color));
- vertices.push(Vertex::new([x - half_tw, half_th, 0.0], NORMAL_2D, color));
- indices.extend_from_slice(&[base, base + 1, base + 2, base, base + 2, base + 3]);
- }
-
- // Y-axis tick marks
- let start = (y_range[0] / tick_spacing).ceil() as i32;
- let end = (y_range[1] / tick_spacing).floor() as i32;
- for i in start..=end {
- if i == 0 {
- continue;
- }
- let y = i as f32 * tick_spacing;
- let base = vertices.len() as u32;
- vertices.push(Vertex::new([-half_th, y - half_tw, 0.0], NORMAL_2D, color));
- vertices.push(Vertex::new([half_th, y - half_tw, 0.0], NORMAL_2D, color));
- vertices.push(Vertex::new([half_th, y + half_tw, 0.0], NORMAL_2D, color));
- vertices.push(Vertex::new([-half_th, y + half_tw, 0.0], NORMAL_2D, color));
- indices.extend_from_slice(&[base, base + 1, base + 2, base, base + 2, base + 3]);
- }
- }
-
- // Arrow tips
- if include_arrows {
- let arrow_len = tick_height * 1.5;
- let arrow_half_w = tick_height * 0.8;
-
- // X-axis arrow (pointing right)
- let base = vertices.len() as u32;
- vertices.push(Vertex::new(
- [x_range[1], -arrow_half_w, 0.0],
- NORMAL_2D,
- color,
- ));
- vertices.push(Vertex::new(
- [x_range[1], arrow_half_w, 0.0],
- NORMAL_2D,
- color,
- ));
- vertices.push(Vertex::new(
- [x_range[1] + arrow_len, 0.0, 0.0],
- NORMAL_2D,
- color,
- ));
- indices.extend_from_slice(&[base, base + 1, base + 2]);
-
- // Y-axis arrow (pointing up)
- let base = vertices.len() as u32;
- vertices.push(Vertex::new(
- [-arrow_half_w, y_range[1], 0.0],
- NORMAL_2D,
- color,
- ));
- vertices.push(Vertex::new(
- [arrow_half_w, y_range[1], 0.0],
- NORMAL_2D,
- color,
- ));
- vertices.push(Vertex::new(
- [0.0, y_range[1] + arrow_len, 0.0],
- NORMAL_2D,
- color,
- ));
- indices.extend_from_slice(&[base, base + 1, base + 2]);
- }
-
- (vertices, indices)
- }
-}
-
-impl Grid {
- /// Generate a background grid of lines in the XY plane.
- pub fn generate(
- x_range: [f32; 2],
- y_range: [f32; 2],
- spacing: f32,
- color: [f32; 4],
- line_width: f32,
- ) -> (Vec<Vertex>, Vec<u32>) {
- let mut vertices = Vec::new();
- let mut indices = Vec::new();
- let half_w = line_width / 2.0;
-
- // Vertical lines
- let start_x = (x_range[0] / spacing).ceil() as i32;
- let end_x = (x_range[1] / spacing).floor() as i32;
- for i in start_x..=end_x {
- let x = i as f32 * spacing;
- let base = vertices.len() as u32;
- vertices.push(Vertex::new([x - half_w, y_range[0], 0.0], NORMAL_2D, color));
- vertices.push(Vertex::new([x + half_w, y_range[0], 0.0], NORMAL_2D, color));
- vertices.push(Vertex::new([x + half_w, y_range[1], 0.0], NORMAL_2D, color));
- vertices.push(Vertex::new([x - half_w, y_range[1], 0.0], NORMAL_2D, color));
- indices.extend_from_slice(&[base, base + 1, base + 2, base, base + 2, base + 3]);
- }
-
- // Horizontal lines
- let start_y = (y_range[0] / spacing).ceil() as i32;
- let end_y = (y_range[1] / spacing).floor() as i32;
- for i in start_y..=end_y {
- let y = i as f32 * spacing;
- let base = vertices.len() as u32;
- vertices.push(Vertex::new([x_range[0], y - half_w, 0.0], NORMAL_2D, color));
- vertices.push(Vertex::new([x_range[1], y - half_w, 0.0], NORMAL_2D, color));
- vertices.push(Vertex::new([x_range[1], y + half_w, 0.0], NORMAL_2D, color));
- vertices.push(Vertex::new([x_range[0], y + half_w, 0.0], NORMAL_2D, color));
- indices.extend_from_slice(&[base, base + 1, base + 2, base, base + 2, base + 3]);
- }
-
- (vertices, indices)
- }
-}
diff --git a/rust/bridge/crates/manimgx-core/src/geometry/two_d/function_plot.rs b/rust/bridge/crates/manimgx-core/src/geometry/two_d/function_plot.rs
deleted file mode 100644
index eab9fdfe..00000000
--- a/rust/bridge/crates/manimgx-core/src/geometry/two_d/function_plot.rs
+++ /dev/null
@@ -1,64 +0,0 @@
-use crate::vertex::Vertex;
-
-pub struct FunctionPlot;
-
-const NORMAL_2D: [f32; 3] = [0.0, 0.0, 1.0];
-
-impl FunctionPlot {
- /// Generate a line strip as a quad strip from pre-sampled [x, y] points.
- pub fn from_points(
- points: &[[f32; 2]],
- color: [f32; 4],
- width: f32,
- ) -> (Vec<Vertex>, Vec<u32>) {
- let mut vertices = Vec::new();
- let mut indices = Vec::new();
-
- if points.len() < 2 {
- return (vertices, indices);
- }
-
- let half_w = width / 2.0;
-
- for i in 0..points.len() {
- // Compute tangent direction for this point
- let tangent = if i == 0 {
- let dx = points[1][0] - points[0][0];
- let dy = points[1][1] - points[0][1];
- [dx, dy]
- } else if i == points.len() - 1 {
- let dx = points[i][0] - points[i - 1][0];
- let dy = points[i][1] - points[i - 1][1];
- [dx, dy]
- } else {
- let dx = points[i + 1][0] - points[i - 1][0];
- let dy = points[i + 1][1] - points[i - 1][1];
- [dx, dy]
- };
-
- let len = (tangent[0] * tangent[0] + tangent[1] * tangent[1])
- .sqrt()
- .max(1e-6);
- // Normal perpendicular to tangent
- let nx = -tangent[1] / len * half_w;
- let ny = tangent[0] / len * half_w;
-
- let p = points[i];
- vertices.push(Vertex::new([p[0] - nx, p[1] - ny, 0.0], NORMAL_2D, color));
- vertices.push(Vertex::new([p[0] + nx, p[1] + ny, 0.0], NORMAL_2D, color));
- }
-
- for i in 0..(points.len() - 1) as u32 {
- let base = i * 2;
- indices.push(base);
- indices.push(base + 1);
- indices.push(base + 2);
-
- indices.push(base + 2);
- indices.push(base + 1);
- indices.push(base + 3);
- }
-
- (vertices, indices)
- }
-}
diff --git a/rust/bridge/crates/manimgx-core/src/geometry/two_d/mod.rs b/rust/bridge/crates/manimgx-core/src/geometry/two_d/mod.rs
deleted file mode 100644
index 9b2aad00..00000000
--- a/rust/bridge/crates/manimgx-core/src/geometry/two_d/mod.rs
+++ /dev/null
@@ -1,4 +0,0 @@
-pub mod axes;
-pub mod function_plot;
-pub mod polygon;
-pub mod shapes;
diff --git a/rust/bridge/crates/manimgx-core/src/geometry/two_d/polygon.rs b/rust/bridge/crates/manimgx-core/src/geometry/two_d/polygon.rs
deleted file mode 100644
index 455822d7..00000000
--- a/rust/bridge/crates/manimgx-core/src/geometry/two_d/polygon.rs
+++ /dev/null
@@ -1,269 +0,0 @@
-use crate::vertex::Vertex;
-use std::f32::consts::PI;
-
-pub struct RegularPolygon;
-pub struct Polygram;
-pub struct Triangle;
-
-const NORMAL_2D: [f32; 3] = [0.0, 0.0, 1.0];
-
-impl RegularPolygon {
- /// Generate a regular polygon with `sides` sides, centered at origin in the XY plane.
- /// Fill is a triangle fan, stroke is a quad strip around the perimeter.
- pub fn generate(
- sides: u32,
- radius: f32,
- fill_color: [f32; 4],
- stroke_color: [f32; 4],
- stroke_width: f32,
- ) -> (Vec<Vertex>, Vec<u32>) {
- let mut vertices = Vec::new();
- let mut indices = Vec::new();
-
- // Compute corner positions
- let corners: Vec<[f32; 2]> = (0..sides)
- .map(|i| {
- let angle = (i as f32) * 2.0 * PI / sides as f32 - PI / 2.0;
- [angle.cos() * radius, angle.sin() * radius]
- })
- .collect();
-
- // Fill: triangle fan from center
- let center_idx = vertices.len() as u32;
- vertices.push(Vertex::new([0.0, 0.0, 0.0], NORMAL_2D, fill_color));
-
- for corner in &corners {
- vertices.push(Vertex::new(
- [corner[0], corner[1], 0.0],
- NORMAL_2D,
- fill_color,
- ));
- }
-
- for i in 0..sides {
- indices.push(center_idx);
- indices.push(center_idx + 1 + i);
- indices.push(center_idx + 1 + (i + 1) % sides);
- }
-
- // Stroke: quad strip around perimeter
- if stroke_width > 0.0 {
- let half_w = stroke_width / 2.0;
- let stroke_base = vertices.len() as u32;
-
- for i in 0..sides {
- let curr = corners[i as usize];
- let next = corners[((i + 1) % sides) as usize];
-
- // Direction along edge
- let dx = next[0] - curr[0];
- let dy = next[1] - curr[1];
- let len = (dx * dx + dy * dy).sqrt();
- // Outward normal (perpendicular)
- let nx = -dy / len;
- let ny = dx / len;
-
- // Inner and outer vertices for this corner
- let inner = [curr[0] - nx * half_w, curr[1] - ny * half_w];
- let outer = [curr[0] + nx * half_w, curr[1] + ny * half_w];
-
- vertices.push(Vertex::new(
- [inner[0], inner[1], 0.0],
- NORMAL_2D,
- stroke_color,
- ));
- vertices.push(Vertex::new(
- [outer[0], outer[1], 0.0],
- NORMAL_2D,
- stroke_color,
- ));
- }
-
- for i in 0..sides {
- let base = stroke_base + i * 2;
- let next_base = stroke_base + ((i + 1) % sides) * 2;
- // Two triangles forming a quad between this edge and next
- indices.push(base);
- indices.push(base + 1);
- indices.push(next_base);
-
- indices.push(next_base);
- indices.push(base + 1);
- indices.push(next_base + 1);
- }
- }
-
- (vertices, indices)
- }
-}
-
-impl Polygram {
- /// Generate a star polygon {points/step}.
- /// `points` = number of outer vertices, `step` = connect every `step`-th vertex.
- pub fn generate(
- points: u32,
- step: u32,
- outer_radius: f32,
- fill_color: [f32; 4],
- stroke_color: [f32; 4],
- stroke_width: f32,
- ) -> (Vec<Vertex>, Vec<u32>) {
- let mut vertices = Vec::new();
- let mut indices = Vec::new();
-
- // Compute inner radius using the star polygon formula
- let inner_radius =
- outer_radius * (PI / points as f32).cos() / (PI * step as f32 / points as f32).cos();
-
- // Generate alternating outer/inner vertices
- let total = points * 2;
- let star_pts: Vec<[f32; 2]> = (0..total)
- .map(|i| {
- let angle = (i as f32) * PI / points as f32 - PI / 2.0;
- let r = if i % 2 == 0 {
- outer_radius
- } else {
- inner_radius
- };
- [angle.cos() * r, angle.sin() * r]
- })
- .collect();
-
- // Fill: triangle fan from center
- let center_idx = vertices.len() as u32;
- vertices.push(Vertex::new([0.0, 0.0, 0.0], NORMAL_2D, fill_color));
-
- for pt in &star_pts {
- vertices.push(Vertex::new([pt[0], pt[1], 0.0], NORMAL_2D, fill_color));
- }
-
- for i in 0..total {
- indices.push(center_idx);
- indices.push(center_idx + 1 + i);
- indices.push(center_idx + 1 + (i + 1) % total);
- }
-
- // Stroke: quad strip around perimeter
- if stroke_width > 0.0 {
- let half_w = stroke_width / 2.0;
- let stroke_base = vertices.len() as u32;
-
- for i in 0..total {
- let curr = star_pts[i as usize];
- let next = star_pts[((i + 1) % total) as usize];
-
- let dx = next[0] - curr[0];
- let dy = next[1] - curr[1];
- let len = (dx * dx + dy * dy).sqrt().max(1e-6);
- let nx = -dy / len;
- let ny = dx / len;
-
- let inner = [curr[0] - nx * half_w, curr[1] - ny * half_w];
- let outer = [curr[0] + nx * half_w, curr[1] + ny * half_w];
-
- vertices.push(Vertex::new(
- [inner[0], inner[1], 0.0],
- NORMAL_2D,
- stroke_color,
- ));
- vertices.push(Vertex::new(
- [outer[0], outer[1], 0.0],
- NORMAL_2D,
- stroke_color,
- ));
- }
-
- for i in 0..total {
- let base = stroke_base + i * 2;
- let next_base = stroke_base + ((i + 1) % total) * 2;
- indices.push(base);
- indices.push(base + 1);
- indices.push(next_base);
-
- indices.push(next_base);
- indices.push(base + 1);
- indices.push(next_base + 1);
- }
- }
-
- (vertices, indices)
- }
-}
-
-impl Triangle {
- /// Generate an equilateral triangle with circumradius `radius`.
- pub fn equilateral(
- radius: f32,
- fill_color: [f32; 4],
- stroke_color: [f32; 4],
- stroke_width: f32,
- ) -> (Vec<Vertex>, Vec<u32>) {
- RegularPolygon::generate(3, radius, fill_color, stroke_color, stroke_width)
- }
-
- /// Generate a triangle from three arbitrary XY vertices.
- pub fn from_vertices(
- v0: [f32; 2],
- v1: [f32; 2],
- v2: [f32; 2],
- fill_color: [f32; 4],
- stroke_color: [f32; 4],
- stroke_width: f32,
- ) -> (Vec<Vertex>, Vec<u32>) {
- let mut vertices = Vec::new();
- let mut indices = Vec::new();
-
- let corners = [v0, v1, v2];
-
- // Fill: single triangle
- for c in &corners {
- vertices.push(Vertex::new([c[0], c[1], 0.0], NORMAL_2D, fill_color));
- }
- indices.extend_from_slice(&[0, 1, 2]);
-
- // Stroke: quad strip around perimeter
- if stroke_width > 0.0 {
- let half_w = stroke_width / 2.0;
- let stroke_base = vertices.len() as u32;
-
- for i in 0..3u32 {
- let curr = corners[i as usize];
- let next = corners[((i + 1) % 3) as usize];
-
- let dx = next[0] - curr[0];
- let dy = next[1] - curr[1];
- let len = (dx * dx + dy * dy).sqrt().max(1e-6);
- let nx = -dy / len;
- let ny = dx / len;
-
- let inner = [curr[0] - nx * half_w, curr[1] - ny * half_w];
- let outer = [curr[0] + nx * half_w, curr[1] + ny * half_w];
-
- vertices.push(Vertex::new(
- [inner[0], inner[1], 0.0],
- NORMAL_2D,
- stroke_color,
- ));
- vertices.push(Vertex::new(
- [outer[0], outer[1], 0.0],
- NORMAL_2D,
- stroke_color,
- ));
- }
-
- for i in 0..3u32 {
- let base = stroke_base + i * 2;
- let next_base = stroke_base + ((i + 1) % 3) * 2;
- indices.push(base);
- indices.push(base + 1);
- indices.push(next_base);
-
- indices.push(next_base);
- indices.push(base + 1);
- indices.push(next_base + 1);
- }
- }
-
- (vertices, indices)
- }
-}
diff --git a/rust/bridge/crates/manimgx-core/src/geometry/two_d/shapes.rs b/rust/bridge/crates/manimgx-core/src/geometry/two_d/shapes.rs
deleted file mode 100644
index cf58cec2..00000000
--- a/rust/bridge/crates/manimgx-core/src/geometry/two_d/shapes.rs
+++ /dev/null
@@ -1,704 +0,0 @@
-use crate::vertex::Vertex;
-use std::f32::consts::PI;
-
-pub struct Circle;
-pub struct Rectangle;
-pub struct Line;
-pub struct Arc;
-pub struct Arrow;
-pub struct Dot;
-pub struct CurvedArrow;
-pub struct DashedLine;
-pub struct Brace;
-pub struct FilledRegion;
-pub struct RiemannRects;
-
-const NORMAL_2D: [f32; 3] = [0.0, 0.0, 1.0];
-
-impl Circle {
- /// Generate a filled circle with optional stroke.
- pub fn generate(
- radius: f32,
- fill_color: [f32; 4],
- stroke_color: [f32; 4],
- stroke_width: f32,
- segments: u32,
- ) -> (Vec<Vertex>, Vec<u32>) {
- // Circle is just a high-segment regular polygon
- super::polygon::RegularPolygon::generate(
- segments,
- radius,
- fill_color,
- stroke_color,
- stroke_width,
- )
- }
-}
-
-impl Rectangle {
- /// Generate a filled rectangle centered at origin in XY plane.
- pub fn generate(
- width: f32,
- height: f32,
- fill_color: [f32; 4],
- stroke_color: [f32; 4],
- stroke_width: f32,
- ) -> (Vec<Vertex>, Vec<u32>) {
- let hw = width / 2.0;
- let hh = height / 2.0;
- let mut vertices = Vec::new();
- let mut indices = Vec::new();
-
- // Fill: two triangles
- vertices.push(Vertex::new([-hw, -hh, 0.0], NORMAL_2D, fill_color));
- vertices.push(Vertex::new([hw, -hh, 0.0], NORMAL_2D, fill_color));
- vertices.push(Vertex::new([hw, hh, 0.0], NORMAL_2D, fill_color));
- vertices.push(Vertex::new([-hw, hh, 0.0], NORMAL_2D, fill_color));
- indices.extend_from_slice(&[0, 1, 2, 0, 2, 3]);
-
- // Stroke: quad strip around perimeter
- if stroke_width > 0.0 {
- let half_w = stroke_width / 2.0;
- let corners: [[f32; 2]; 4] = [[-hw, -hh], [hw, -hh], [hw, hh], [-hw, hh]];
-
- let stroke_base = vertices.len() as u32;
-
- for i in 0..4u32 {
- let curr = corners[i as usize];
- let next = corners[((i + 1) % 4) as usize];
-
- let dx = next[0] - curr[0];
- let dy = next[1] - curr[1];
- let len = (dx * dx + dy * dy).sqrt().max(1e-6);
- let nx = -dy / len;
- let ny = dx / len;
-
- let inner = [curr[0] - nx * half_w, curr[1] - ny * half_w];
- let outer = [curr[0] + nx * half_w, curr[1] + ny * half_w];
-
- vertices.push(Vertex::new(
- [inner[0], inner[1], 0.0],
- NORMAL_2D,
- stroke_color,
- ));
- vertices.push(Vertex::new(
- [outer[0], outer[1], 0.0],
- NORMAL_2D,
- stroke_color,
- ));
- }
-
- for i in 0..4u32 {
- let base = stroke_base + i * 2;
- let next_base = stroke_base + ((i + 1) % 4) * 2;
- indices.push(base);
- indices.push(base + 1);
- indices.push(next_base);
-
- indices.push(next_base);
- indices.push(base + 1);
- indices.push(next_base + 1);
- }
- }
-
- (vertices, indices)
- }
-}
-
-impl Line {
- /// Generate a line (quad) between two XY points.
- pub fn generate(
- start: [f32; 2],
- end: [f32; 2],
- color: [f32; 4],
- width: f32,
- ) -> (Vec<Vertex>, Vec<u32>) {
- let dx = end[0] - start[0];
- let dy = end[1] - start[1];
- let len = (dx * dx + dy * dy).sqrt().max(1e-6);
- let nx = -dy / len * width / 2.0;
- let ny = dx / len * width / 2.0;
-
- let vertices = vec![
- Vertex::new([start[0] - nx, start[1] - ny, 0.0], NORMAL_2D, color),
- Vertex::new([start[0] + nx, start[1] + ny, 0.0], NORMAL_2D, color),
- Vertex::new([end[0] + nx, end[1] + ny, 0.0], NORMAL_2D, color),
- Vertex::new([end[0] - nx, end[1] - ny, 0.0], NORMAL_2D, color),
- ];
- let indices = vec![0, 1, 2, 0, 2, 3];
-
- (vertices, indices)
- }
-}
-
-impl Arc {
- /// Generate an arc (partial circle outline) as a quad strip.
- pub fn generate(
- radius: f32,
- start_angle: f32,
- end_angle: f32,
- color: [f32; 4],
- width: f32,
- segments: u32,
- ) -> (Vec<Vertex>, Vec<u32>) {
- let mut vertices = Vec::new();
- let mut indices = Vec::new();
- let half_w = width / 2.0;
-
- let angle_span = end_angle - start_angle;
-
- for i in 0..=segments {
- let t = i as f32 / segments as f32;
- let angle = start_angle + t * angle_span;
- let cos_a = angle.cos();
- let sin_a = angle.sin();
-
- // Inner and outer points
- let inner_r = radius - half_w;
- let outer_r = radius + half_w;
-
- vertices.push(Vertex::new(
- [cos_a * inner_r, sin_a * inner_r, 0.0],
- NORMAL_2D,
- color,
- ));
- vertices.push(Vertex::new(
- [cos_a * outer_r, sin_a * outer_r, 0.0],
- NORMAL_2D,
- color,
- ));
- }
-
- for i in 0..segments {
- let base = i * 2;
- indices.push(base);
- indices.push(base + 1);
- indices.push(base + 2);
-
- indices.push(base + 2);
- indices.push(base + 1);
- indices.push(base + 3);
- }
-
- (vertices, indices)
- }
-}
-
-impl Arrow {
- /// Generate an arrow from start to end with a triangular head.
- pub fn generate(
- start: [f32; 2],
- end: [f32; 2],
- color: [f32; 4],
- width: f32,
- head_length: f32,
- head_width: f32,
- ) -> (Vec<Vertex>, Vec<u32>) {
- let dx = end[0] - start[0];
- let dy = end[1] - start[1];
- let len = (dx * dx + dy * dy).sqrt().max(1e-6);
- let ux = dx / len;
- let uy = dy / len;
-
- // The shaft ends where the arrowhead begins
- let shaft_end = [end[0] - ux * head_length, end[1] - uy * head_length];
-
- // Shaft (line quad)
- let nx = -uy * width / 2.0;
- let ny = ux * width / 2.0;
-
- let mut vertices = vec![
- Vertex::new([start[0] - nx, start[1] - ny, 0.0], NORMAL_2D, color),
- Vertex::new([start[0] + nx, start[1] + ny, 0.0], NORMAL_2D, color),
- Vertex::new(
- [shaft_end[0] + nx, shaft_end[1] + ny, 0.0],
- NORMAL_2D,
- color,
- ),
- Vertex::new(
- [shaft_end[0] - nx, shaft_end[1] - ny, 0.0],
- NORMAL_2D,
- color,
- ),
- ];
- let mut indices = vec![0, 1, 2, 0, 2, 3];
-
- // Arrowhead (triangle)
- let head_nx = -uy * head_width / 2.0;
- let head_ny = ux * head_width / 2.0;
-
- let head_base = vertices.len() as u32;
- vertices.push(Vertex::new(
- [shaft_end[0] - head_nx, shaft_end[1] - head_ny, 0.0],
- NORMAL_2D,
- color,
- ));
- vertices.push(Vertex::new(
- [shaft_end[0] + head_nx, shaft_end[1] + head_ny, 0.0],
- NORMAL_2D,
- color,
- ));
- vertices.push(Vertex::new([end[0], end[1], 0.0], NORMAL_2D, color));
-
- indices.push(head_base);
- indices.push(head_base + 1);
- indices.push(head_base + 2);
-
- (vertices, indices)
- }
-}
-
-impl Dot {
- /// Generate a small filled circle (dot) at a position.
- pub fn generate(
- position: [f32; 2],
- radius: f32,
- color: [f32; 4],
- segments: u32,
- ) -> (Vec<Vertex>, Vec<u32>) {
- let mut vertices = Vec::new();
- let mut indices = Vec::new();
-
- // Center vertex
- let center_idx = 0u32;
- vertices.push(Vertex::new(
- [position[0], position[1], 0.0],
- NORMAL_2D,
- color,
- ));
-
- // Perimeter vertices
- for i in 0..segments {
- let angle = (i as f32) * 2.0 * PI / segments as f32;
- vertices.push(Vertex::new(
- [
- position[0] + angle.cos() * radius,
- position[1] + angle.sin() * radius,
- 0.0,
- ],
- NORMAL_2D,
- color,
- ));
- }
-
- for i in 0..segments {
- indices.push(center_idx);
- indices.push(1 + i);
- indices.push(1 + (i + 1) % segments);
- }
-
- (vertices, indices)
- }
-}
-
-impl CurvedArrow {
- /// Generate an arc with an arrowhead at the end.
- pub fn generate(
- radius: f32,
- start_angle: f32,
- end_angle: f32,
- color: [f32; 4],
- width: f32,
- head_length: f32,
- head_width: f32,
- segments: u32,
- ) -> (Vec<Vertex>, Vec<u32>) {
- let mut vertices = Vec::new();
- let mut indices = Vec::new();
- let half_w = width / 2.0;
-
- // Shorten the arc to make room for the arrowhead
- let angle_span = end_angle - start_angle;
- let head_angle = head_length / radius;
- let arc_end = end_angle - head_angle;
-
- // Arc body (quad strip)
- let arc_span = arc_end - start_angle;
- for i in 0..=segments {
- let t = i as f32 / segments as f32;
- let angle = start_angle + t * arc_span;
- let cos_a = angle.cos();
- let sin_a = angle.sin();
-
- let inner_r = radius - half_w;
- let outer_r = radius + half_w;
-
- vertices.push(Vertex::new(
- [cos_a * inner_r, sin_a * inner_r, 0.0],
- NORMAL_2D,
- color,
- ));
- vertices.push(Vertex::new(
- [cos_a * outer_r, sin_a * outer_r, 0.0],
- NORMAL_2D,
- color,
- ));
- }
-
- for i in 0..segments {
- let base = i * 2;
- indices.push(base);
- indices.push(base + 1);
- indices.push(base + 2);
- indices.push(base + 2);
- indices.push(base + 1);
- indices.push(base + 3);
- }
-
- // Arrowhead triangle at arc_end
- let head_base_idx = vertices.len() as u32;
- let cos_end = arc_end.cos();
- let sin_end = arc_end.sin();
-
- // Tangent direction at arc_end (perpendicular to radius, in the direction of angle increase)
- let sign = if angle_span >= 0.0 { 1.0 } else { -1.0 };
- let tx = -sin_end * sign;
- let ty = cos_end * sign;
-
- // Normal to arc at this point (radial direction)
- let nx = cos_end;
- let ny = sin_end;
-
- // Head base points (perpendicular to tangent)
- let half_hw = head_width / 2.0;
- let base_x = cos_end * radius;
- let base_y = sin_end * radius;
-
- vertices.push(Vertex::new(
- [base_x - nx * half_hw, base_y - ny * half_hw, 0.0],
- NORMAL_2D,
- color,
- ));
- vertices.push(Vertex::new(
- [base_x + nx * half_hw, base_y + ny * half_hw, 0.0],
- NORMAL_2D,
- color,
- ));
-
- // Tip point
- let tip_x = base_x + tx * head_length;
- let tip_y = base_y + ty * head_length;
- vertices.push(Vertex::new([tip_x, tip_y, 0.0], NORMAL_2D, color));
-
- indices.push(head_base_idx);
- indices.push(head_base_idx + 1);
- indices.push(head_base_idx + 2);
-
- (vertices, indices)
- }
-}
-
-impl DashedLine {
- /// Generate a dashed line between two points.
- pub fn generate(
- start: [f32; 2],
- end: [f32; 2],
- color: [f32; 4],
- width: f32,
- dash_length: f32,
- gap_length: f32,
- ) -> (Vec<Vertex>, Vec<u32>) {
- let dx = end[0] - start[0];
- let dy = end[1] - start[1];
- let total_len = (dx * dx + dy * dy).sqrt().max(1e-6);
- let ux = dx / total_len;
- let uy = dy / total_len;
- let nx = -uy * width / 2.0;
- let ny = ux * width / 2.0;
-
- let mut vertices = Vec::new();
- let mut indices = Vec::new();
-
- let pattern_len = dash_length + gap_length;
- let mut dist = 0.0;
-
- while dist < total_len {
- let d_end = (dist + dash_length).min(total_len);
- let sx = start[0] + ux * dist;
- let sy = start[1] + uy * dist;
- let ex = start[0] + ux * d_end;
- let ey = start[1] + uy * d_end;
-
- let base = vertices.len() as u32;
- vertices.push(Vertex::new([sx - nx, sy - ny, 0.0], NORMAL_2D, color));
- vertices.push(Vertex::new([sx + nx, sy + ny, 0.0], NORMAL_2D, color));
- vertices.push(Vertex::new([ex + nx, ey + ny, 0.0], NORMAL_2D, color));
- vertices.push(Vertex::new([ex - nx, ey - ny, 0.0], NORMAL_2D, color));
-
- indices.push(base);
- indices.push(base + 1);
- indices.push(base + 2);
- indices.push(base);
- indices.push(base + 2);
- indices.push(base + 3);
-
- dist += pattern_len;
- }
-
- (vertices, indices)
- }
-}
-
-impl Brace {
- /// Generate a curly brace shape in 2D. The brace spans from `start` to `end`
- /// with the curl pointing in the direction of the normal.
- pub fn generate(
- start: [f32; 2],
- end: [f32; 2],
- color: [f32; 4],
- width: f32,
- curl_size: f32,
- segments: u32,
- ) -> (Vec<Vertex>, Vec<u32>) {
- let dx = end[0] - start[0];
- let dy = end[1] - start[1];
- let len = (dx * dx + dy * dy).sqrt().max(1e-6);
- let ux = dx / len;
- let uy = dy / len;
- // Normal pointing outward (perpendicular)
- let nx = -uy;
- let ny = ux;
-
- // Build the brace as a series of quad segments following a parametric path
- // The brace has 4 arcs: start curl, first half, second half, end curl
- let total_segs = segments.max(16);
- let mut path_points = Vec::with_capacity(total_segs as usize + 1);
-
- for i in 0..=total_segs {
- let t = i as f32 / total_segs as f32;
-
- // Parametric brace: smooth curve from start to end with curl at middle
- let along = start[0] + dx * t;
- let along_y = start[1] + dy * t;
-
- // Curl function: peaks at t=0.5, zero at t=0 and t=1
- // Use sin^2 for smooth bump, with a sharper peak at the midpoint
- let curl = if t < 0.5 {
- let s = t * 2.0;
- curl_size * (s * PI).sin()
- } else {
- let s = (t - 0.5) * 2.0;
- curl_size * ((1.0 - s) * PI).sin()
- };
-
- // Add small hooks at the tips
- let hook = if t < 0.05 {
- curl_size * 0.3 * ((t / 0.05) * PI * 0.5).sin()
- } else if t > 0.95 {
- curl_size * 0.3 * (((1.0 - t) / 0.05) * PI * 0.5).sin()
- } else {
- 0.0
- };
-
- let px = along + nx * (curl + hook);
- let py = along_y + ny * (curl + hook);
- path_points.push([px, py]);
- }
-
- // Convert path to quad strip
- let mut vertices = Vec::new();
- let mut indices = Vec::new();
- let half_w = width / 2.0;
-
- for i in 0..path_points.len() {
- let p = path_points[i];
-
- // Compute tangent direction
- let tangent = if i == 0 {
- let next = path_points[1];
- [next[0] - p[0], next[1] - p[1]]
- } else if i == path_points.len() - 1 {
- let prev = path_points[i - 1];
- [p[0] - prev[0], p[1] - prev[1]]
- } else {
- let prev = path_points[i - 1];
- let next = path_points[i + 1];
- [next[0] - prev[0], next[1] - prev[1]]
- };
-
- let tlen = (tangent[0] * tangent[0] + tangent[1] * tangent[1])
- .sqrt()
- .max(1e-6);
- let tnx = -tangent[1] / tlen * half_w;
- let tny = tangent[0] / tlen * half_w;
-
- vertices.push(Vertex::new(
- [p[0] - tnx, p[1] - tny, 0.0],
- NORMAL_2D,
- color,
- ));
- vertices.push(Vertex::new(
- [p[0] + tnx, p[1] + tny, 0.0],
- NORMAL_2D,
- color,
- ));
- }
-
- for i in 0..(path_points.len() as u32 - 1) {
- let base = i * 2;
- indices.push(base);
- indices.push(base + 1);
- indices.push(base + 2);
- indices.push(base + 2);
- indices.push(base + 1);
- indices.push(base + 3);
- }
-
- // Add the midpoint tip triangle
- let mid_idx = total_segs / 2;
- let mid_point = path_points[mid_idx as usize];
- let tip_base = vertices.len() as u32;
- let tip_offset = curl_size * 0.4;
- vertices.push(Vertex::new(
- [mid_point[0] + nx * tip_offset - ux * width, mid_point[1] + ny * tip_offset - uy * width, 0.0],
- NORMAL_2D,
- color,
- ));
- vertices.push(Vertex::new(
- [mid_point[0] + nx * tip_offset + ux * width, mid_point[1] + ny * tip_offset + uy * width, 0.0],
- NORMAL_2D,
- color,
- ));
- vertices.push(Vertex::new(
- [mid_point[0] + nx * (tip_offset + curl_size * 0.3), mid_point[1] + ny * (tip_offset + curl_size * 0.3), 0.0],
- NORMAL_2D,
- color,
- ));
- indices.push(tip_base);
- indices.push(tip_base + 1);
- indices.push(tip_base + 2);
-
- (vertices, indices)
- }
-}
-
-impl FilledRegion {
- /// Generate a filled region between a curve (given as points) and the x-axis (y=baseline).
- pub fn generate(
- points: &[[f32; 2]],
- baseline: f32,
- color: [f32; 4],
- ) -> (Vec<Vertex>, Vec<u32>) {
- let mut vertices = Vec::new();
- let mut indices = Vec::new();
-
- if points.len() < 2 {
- return (vertices, indices);
- }
-
- // For each point, create a vertex pair: one at the curve, one at the baseline
- for &p in points {
- vertices.push(Vertex::new([p[0], p[1], 0.0], NORMAL_2D, color));
- vertices.push(Vertex::new([p[0], baseline, 0.0], NORMAL_2D, color));
- }
-
- // Create quads between adjacent point pairs
- for i in 0..(points.len() as u32 - 1) {
- let base = i * 2;
- // Triangle 1: curve[i], baseline[i], curve[i+1]
- indices.push(base);
- indices.push(base + 1);
- indices.push(base + 2);
- // Triangle 2: curve[i+1], baseline[i], baseline[i+1]
- indices.push(base + 2);
- indices.push(base + 1);
- indices.push(base + 3);
- }
-
- (vertices, indices)
- }
-}
-
-impl RiemannRects {
- /// Generate Riemann sum rectangles for a function sampled at points.
- /// Each rectangle spans from baseline to y_value at the sampled x position.
- pub fn generate(
- x_positions: &[f32],
- y_values: &[f32],
- dx: f32,
- baseline: f32,
- fill_color: [f32; 4],
- stroke_color: [f32; 4],
- stroke_width: f32,
- ) -> (Vec<Vertex>, Vec<u32>) {
- let mut vertices = Vec::new();
- let mut indices = Vec::new();
-
- let half_dx = dx / 2.0;
-
- for (&x, &y) in x_positions.iter().zip(y_values.iter()) {
- let base = vertices.len() as u32;
-
- // Rectangle fill (2 triangles)
- let left = x - half_dx;
- let right = x + half_dx;
- let bot = baseline;
- let top = y;
-
- vertices.push(Vertex::new([left, bot, 0.0], NORMAL_2D, fill_color));
- vertices.push(Vertex::new([right, bot, 0.0], NORMAL_2D, fill_color));
- vertices.push(Vertex::new([right, top, 0.0], NORMAL_2D, fill_color));
- vertices.push(Vertex::new([left, top, 0.0], NORMAL_2D, fill_color));
-
- indices.push(base);
- indices.push(base + 1);
- indices.push(base + 2);
- indices.push(base);
- indices.push(base + 2);
- indices.push(base + 3);
-
- // Stroke outline
- if stroke_width > 0.0 {
- let hw = stroke_width / 2.0;
- let corners: [[f32; 2]; 4] = [
- [left, bot],
- [right, bot],
- [right, top],
- [left, top],
- ];
-
- for edge in 0..4u32 {
- let curr = corners[edge as usize];
- let next = corners[((edge + 1) % 4) as usize];
-
- let edx = next[0] - curr[0];
- let edy = next[1] - curr[1];
- let elen = (edx * edx + edy * edy).sqrt().max(1e-6);
- let enx = -edy / elen * hw;
- let eny = edx / elen * hw;
-
- let sb = vertices.len() as u32;
- vertices.push(Vertex::new(
- [curr[0] - enx, curr[1] - eny, 0.0],
- NORMAL_2D,
- stroke_color,
- ));
- vertices.push(Vertex::new(
- [curr[0] + enx, curr[1] + eny, 0.0],
- NORMAL_2D,
- stroke_color,
- ));
- vertices.push(Vertex::new(
- [next[0] + enx, next[1] + eny, 0.0],
- NORMAL_2D,
- stroke_color,
- ));
- vertices.push(Vertex::new(
- [next[0] - enx, next[1] - eny, 0.0],
- NORMAL_2D,
- stroke_color,
- ));
-
- indices.push(sb);
- indices.push(sb + 1);
- indices.push(sb + 2);
- indices.push(sb);
- indices.push(sb + 2);
- indices.push(sb + 3);
- }
- }
- }
-
- (vertices, indices)
- }
-}
diff --git a/rust/bridge/crates/manimgx-core/src/lib.rs b/rust/bridge/crates/manimgx-core/src/lib.rs
deleted file mode 100644
index 06e0bd9e..00000000
--- a/rust/bridge/crates/manimgx-core/src/lib.rs
+++ /dev/null
@@ -1,12 +0,0 @@
-pub mod animation;
-pub mod camera;
-pub mod color;
-pub mod encoder;
-pub mod geometry;
-pub mod material;
-pub mod mp4_muxer;
-pub mod scene;
-pub mod timeline_eval;
-pub mod transform;
-pub mod uniform;
-pub mod vertex;
diff --git a/rust/bridge/crates/manimgx-core/src/material.rs b/rust/bridge/crates/manimgx-core/src/material.rs
deleted file mode 100644
index 4857f516..00000000
--- a/rust/bridge/crates/manimgx-core/src/material.rs
+++ /dev/null
@@ -1,94 +0,0 @@
-#[derive(Clone, Copy, Debug)]
-pub struct Material {
- pub color: [f32; 4],
- pub fill_color: [f32; 4],
- pub stroke_color: [f32; 4],
- pub stroke_width: f32,
- pub fill_opacity: f32,
- pub opacity: f32,
- pub use_vertex_colors: bool,
-}
-
-impl Default for Material {
- fn default() -> Self {
- Self {
- color: [1.0, 1.0, 1.0, 1.0],
- fill_color: [1.0, 1.0, 1.0, 1.0],
- stroke_color: [1.0, 1.0, 1.0, 1.0],
- stroke_width: 0.0,
- fill_opacity: 1.0,
- opacity: 1.0,
- use_vertex_colors: false,
- }
- }
-}
-
-impl Material {
- pub fn new(r: f32, g: f32, b: f32) -> Self {
- Self {
- color: [r, g, b, 1.0],
- fill_color: [r, g, b, 1.0],
- stroke_color: [r, g, b, 1.0],
- stroke_width: 0.0,
- fill_opacity: 1.0,
- opacity: 1.0,
- use_vertex_colors: false,
- }
- }
-
- pub fn with_alpha(r: f32, g: f32, b: f32, a: f32) -> Self {
- Self {
- color: [r, g, b, a],
- fill_color: [r, g, b, a],
- stroke_color: [r, g, b, a],
- stroke_width: 0.0,
- fill_opacity: a,
- opacity: 1.0,
- use_vertex_colors: false,
- }
- }
-
- pub fn for_2d_shape(
- fill_color: [f32; 4],
- stroke_color: [f32; 4],
- stroke_width: f32,
- fill_opacity: f32,
- ) -> Self {
- Self {
- color: fill_color,
- fill_color,
- stroke_color,
- stroke_width,
- fill_opacity,
- opacity: 1.0,
- use_vertex_colors: true,
- }
- }
-
- pub fn lerp(&self, other: &Material, t: f32) -> Material {
- Material {
- color: [
- self.color[0] + (other.color[0] - self.color[0]) * t,
- self.color[1] + (other.color[1] - self.color[1]) * t,
- self.color[2] + (other.color[2] - self.color[2]) * t,
- self.color[3] + (other.color[3] - self.color[3]) * t,
- ],
- fill_color: [
- self.fill_color[0] + (other.fill_color[0] - self.fill_color[0]) * t,
- self.fill_color[1] + (other.fill_color[1] - self.fill_color[1]) * t,
- self.fill_color[2] + (other.fill_color[2] - self.fill_color[2]) * t,
- self.fill_color[3] + (other.fill_color[3] - self.fill_color[3]) * t,
- ],
- stroke_color: [
- self.stroke_color[0] + (other.stroke_color[0] - self.stroke_color[0]) * t,
- self.stroke_color[1] + (other.stroke_color[1] - self.stroke_color[1]) * t,
- self.stroke_color[2] + (other.stroke_color[2] - self.stroke_color[2]) * t,
- self.stroke_color[3] + (other.stroke_color[3] - self.stroke_color[3]) * t,
- ],
- stroke_width: self.stroke_width + (other.stroke_width - self.stroke_width) * t,
- fill_opacity: self.fill_opacity + (other.fill_opacity - self.fill_opacity) * t,
- opacity: self.opacity + (other.opacity - self.opacity) * t,
- use_vertex_colors: other.use_vertex_colors,
- }
- }
-}
diff --git a/rust/bridge/crates/manimgx-core/src/mp4_muxer.rs b/rust/bridge/crates/manimgx-core/src/mp4_muxer.rs
deleted file mode 100644
index c70d0785..00000000
--- a/rust/bridge/crates/manimgx-core/src/mp4_muxer.rs
+++ /dev/null
@@ -1,1007 +0,0 @@
-//! MP4 muxer for single-track H.264 video.
-//!
-//! Pure Rust, zero external dependencies. Accepts Annex B H.264 NAL units,
-//! converts to AVCC format, writes ISO 14496-12 compliant MP4.
-//!
-//! Three muxing strategies:
-//! - **Ram** — buffer all mdat in memory, write faststart MP4 at finish
-//! - **Disk** — stream mdat to temp file, assemble faststart MP4 at finish
-//! - **Fmp4** — fragmented MP4, stream directly to output file
-
-use std::fs::File;
-use std::io::{self, BufWriter, Write};
-
-// ── Public types ──────────────────────────────────────────────────
-
-#[derive(Clone, Copy, Debug, PartialEq)]
-pub enum MuxerStrategy {
- Ram,
- Disk,
- Fmp4,
-}
-
-// ── Internal storage ──────────────────────────────────────────────
-
-enum MdatStorage {
- Ram(Vec<u8>),
- Disk {
- writer: BufWriter<File>,
- temp_path: String,
- data_size: u64,
- },
- Fmp4 {
- writer: BufWriter<File>,
- sequence_number: u32,
- fragment_samples: Vec<SampleInfo>,
- fragment_mdat: Vec<u8>,
- base_decode_time: i64,
- flushed_init: bool,
- },
-}
-
-// ── Mp4Muxer ─────────────────────────────────────────────────────
-
-pub struct Mp4Muxer {
- path: String,
- width: u32,
- height: u32,
- timescale: u32,
-
- sps: Vec<u8>,
- pps: Vec<u8>,
-
- samples: Vec<SampleInfo>, // Ram/Disk only
- has_b_frames: bool,
-
- avcc_buf: Vec<u8>,
- storage: MdatStorage,
-}
-
-struct SampleInfo {
- size: u32,
- is_keyframe: bool,
- dts: i64,
- cts_offset: i32,
-}
-
-impl Mp4Muxer {
- pub fn new(
- path: &str,
- width: u32,
- height: u32,
- fps: f64,
- strategy: MuxerStrategy,
- ) -> io::Result<Self> {
- let storage = match strategy {
- MuxerStrategy::Ram => MdatStorage::Ram(Vec::with_capacity(4 * 1024 * 1024)),
- MuxerStrategy::Disk => {
- let temp_path = format!("{}.tmp", path);
- let file = File::create(&temp_path)?;
- MdatStorage::Disk {
- writer: BufWriter::with_capacity(256 * 1024, file),
- temp_path,
- data_size: 0,
- }
- }
- MuxerStrategy::Fmp4 => {
- let file = File::create(path)?;
- MdatStorage::Fmp4 {
- writer: BufWriter::with_capacity(256 * 1024, file),
- sequence_number: 1,
- fragment_samples: Vec::new(),
- fragment_mdat: Vec::with_capacity(1024 * 1024),
- base_decode_time: 0,
- flushed_init: false,
- }
- }
- };
-
- Ok(Self {
- path: path.to_string(),
- width,
- height,
- timescale: fps.round() as u32,
- sps: Vec::new(),
- pps: Vec::new(),
- samples: Vec::new(),
- has_b_frames: false,
- avcc_buf: Vec::with_capacity(128 * 1024),
- storage,
- })
- }
-
- /// Write a video frame from pre-split NAL units (no start codes).
- pub fn write_video_nals(
- &mut self,
- pts_secs: f64,
- dts_secs: f64,
- nals: &[&[u8]],
- is_keyframe: bool,
- ) -> io::Result<()> {
- let ts = self.timescale as f64;
- let pts_ticks = (pts_secs * ts).round() as i64;
- let dts_ticks = (dts_secs * ts).round() as i64;
- let cts_offset = (pts_ticks - dts_ticks) as i32;
-
- if cts_offset != 0 {
- self.has_b_frames = true;
- }
-
- // Build AVCC data into avcc_buf, filtering SPS/PPS/SEI/AUD/filler
- self.avcc_buf.clear();
- for nal in nals {
- if nal.is_empty() {
- continue;
- }
- let nal_type = nal[0] & 0x1F;
- match nal_type {
- 7 => {
- if self.sps.is_empty() {
- self.sps = nal.to_vec();
- }
- continue;
- }
- 8 => {
- if self.pps.is_empty() {
- self.pps = nal.to_vec();
- }
- continue;
- }
- 6 | 9 | 12 => continue,
- _ => {}
- }
- self.avcc_buf
- .extend_from_slice(&(nal.len() as u32).to_be_bytes());
- self.avcc_buf.extend_from_slice(nal);
- }
-
- if self.avcc_buf.is_empty() {
- return Ok(());
- }
-
- let sample = SampleInfo {
- size: self.avcc_buf.len() as u32,
- is_keyframe,
- dts: dts_ticks,
- cts_offset,
- };
-
- let mut avcc_data = std::mem::take(&mut self.avcc_buf);
- self.append_sample_data(&avcc_data, sample)?;
- avcc_data.clear();
- self.avcc_buf = avcc_data;
-
- Ok(())
- }
-
- /// Dispatch sample data to the active storage backend.
- fn append_sample_data(&mut self, data: &[u8], sample: SampleInfo) -> io::Result<()> {
- match &mut self.storage {
- MdatStorage::Ram(vec) => {
- vec.extend_from_slice(data);
- self.samples.push(sample);
- }
- MdatStorage::Disk {
- writer, data_size, ..
- } => {
- writer.write_all(data)?;
- *data_size += data.len() as u64;
- self.samples.push(sample);
- }
- MdatStorage::Fmp4 {
- writer,
- sequence_number,
- fragment_samples,
- fragment_mdat,
- base_decode_time,
- flushed_init,
- } => {
- // Write init segment on first sample with SPS/PPS available
- if !*flushed_init && !self.sps.is_empty() && !self.pps.is_empty() {
- let ftyp = build_fmp4_ftyp();
- let init_moov = build_fmp4_init_moov(
- self.width,
- self.height,
- self.timescale,
- &self.sps,
- &self.pps,
- );
- writer.write_all(&ftyp)?;
- writer.write_all(&init_moov)?;
- *flushed_init = true;
- }
-
- // Flush previous fragment on keyframe boundary
- if sample.is_keyframe && !fragment_samples.is_empty() {
- flush_fragment(
- writer,
- sequence_number,
- fragment_samples,
- fragment_mdat,
- *base_decode_time,
- )?;
- // Advance base_decode_time to the DTS of this new keyframe
- *base_decode_time = sample.dts;
- }
-
- // Set initial base_decode_time from first sample
- if fragment_samples.is_empty() && *base_decode_time == 0 {
- *base_decode_time = sample.dts;
- }
-
- fragment_mdat.extend_from_slice(data);
- fragment_samples.push(sample);
- }
- }
- Ok(())
- }
-
- /// Finalize the MP4 file.
- pub fn finish(mut self) -> io::Result<()> {
- assert!(!self.sps.is_empty(), "No SPS found in H.264 stream");
- assert!(!self.pps.is_empty(), "No PPS found in H.264 stream");
-
- // Move storage out to avoid borrow conflicts with self.build_moov()
- let storage = std::mem::replace(
- &mut self.storage,
- MdatStorage::Ram(Vec::new()),
- );
-
- match storage {
- MdatStorage::Ram(mdat_body) => {
- let ftyp = build_ftyp();
- let ftyp_size = ftyp.len() as u64;
- let data_size = mdat_body.len() as u64;
- let mdat_hdr_size = mdat_header_size(data_size);
- let n_samples = self.samples.len();
-
- // Two-pass moov build with co64 auto-detection
- let moov_pass1 = self.build_moov(0, false);
- let stco_moov_size = moov_pass1.len() as u64;
- let base_stco = ftyp_size + stco_moov_size + mdat_hdr_size;
-
- let total_data: u64 = self.samples.iter().map(|s| s.size as u64).sum();
- let moov = if base_stco + total_data > u32::MAX as u64 {
- let co64_moov_size = stco_moov_size + (4 * n_samples) as u64;
- let base = ftyp_size + co64_moov_size + mdat_hdr_size;
- let m = self.build_moov(base, true);
- debug_assert_eq!(m.len() as u64, co64_moov_size);
- m
- } else {
- let m = self.build_moov(base_stco, false);
- debug_assert_eq!(m.len() as u64, stco_moov_size);
- m
- };
-
- let mdat_header = build_mdat_header(data_size);
-
- let file = File::create(&self.path)?;
- let mut writer = BufWriter::new(file);
- writer.write_all(&ftyp)?;
- writer.write_all(&moov)?;
- writer.write_all(&mdat_header)?;
- writer.write_all(&mdat_body)?;
- writer.flush()?;
- }
- MdatStorage::Disk {
- writer: mut disk_writer,
- temp_path,
- data_size,
- } => {
- disk_writer.flush()?;
- drop(disk_writer);
-
- let ftyp = build_ftyp();
- let ftyp_size = ftyp.len() as u64;
- let mdat_hdr_size = mdat_header_size(data_size);
- let n_samples = self.samples.len();
-
- // Two-pass moov build with co64 auto-detection
- let moov_pass1 = self.build_moov(0, false);
- let stco_moov_size = moov_pass1.len() as u64;
- let base_stco = ftyp_size + stco_moov_size + mdat_hdr_size;
-
- let total_data: u64 = self.samples.iter().map(|s| s.size as u64).sum();
- let moov = if base_stco + total_data > u32::MAX as u64 {
- let co64_moov_size = stco_moov_size + (4 * n_samples) as u64;
- let base = ftyp_size + co64_moov_size + mdat_hdr_size;
- let m = self.build_moov(base, true);
- debug_assert_eq!(m.len() as u64, co64_moov_size);
- m
- } else {
- let m = self.build_moov(base_stco, false);
- debug_assert_eq!(m.len() as u64, stco_moov_size);
- m
- };
-
- let mdat_header = build_mdat_header(data_size);
-
- // Write final file: ftyp + moov + mdat_header + copy temp data
- let file = File::create(&self.path)?;
- let mut out = BufWriter::with_capacity(256 * 1024, file);
- out.write_all(&ftyp)?;
- out.write_all(&moov)?;
- out.write_all(&mdat_header)?;
-
- let mut src = io::BufReader::with_capacity(256 * 1024, File::open(&temp_path)?);
- io::copy(&mut src, &mut out)?;
- out.flush()?;
- drop(src);
-
- let _ = std::fs::remove_file(&temp_path);
- }
- MdatStorage::Fmp4 {
- mut writer,
- mut sequence_number,
- mut fragment_samples,
- mut fragment_mdat,
- base_decode_time,
- ..
- } => {
- // Flush remaining fragment (last GOP)
- if !fragment_samples.is_empty() {
- flush_fragment(
- &mut writer,
- &mut sequence_number,
- &mut fragment_samples,
- &mut fragment_mdat,
- base_decode_time,
- )?;
- }
- writer.flush()?;
- }
- }
-
- Ok(())
- }
-
- // ── moov construction ──────────────────────────────────────────────
-
- fn build_moov(&self, base_offset: u64, use_co64: bool) -> Vec<u8> {
- let duration = self.samples.len() as u32;
- let mvhd = self.build_mvhd(duration);
- let trak = self.build_trak(duration, base_offset, use_co64);
- mp4_box(b"moov", &[&mvhd, &trak])
- }
-
- fn build_mvhd(&self, duration: u32) -> Vec<u8> {
- let mut c = Vec::with_capacity(96);
- c.extend_from_slice(&0u32.to_be_bytes()); // creation_time
- c.extend_from_slice(&0u32.to_be_bytes()); // modification_time
- c.extend_from_slice(&self.timescale.to_be_bytes());
- c.extend_from_slice(&duration.to_be_bytes());
- c.extend_from_slice(&0x0001_0000u32.to_be_bytes()); // rate 1.0
- c.extend_from_slice(&0x0100u16.to_be_bytes()); // volume 1.0
- c.extend_from_slice(&[0u8; 10]); // reserved
- c.extend_from_slice(&IDENTITY_MATRIX);
- c.extend_from_slice(&[0u8; 24]); // pre_defined
- c.extend_from_slice(&2u32.to_be_bytes()); // next_track_ID
- full_box(b"mvhd", 0, 0, &c)
- }
-
- fn build_trak(&self, duration: u32, base_offset: u64, use_co64: bool) -> Vec<u8> {
- let tkhd = self.build_tkhd(duration);
- let mdia = self.build_mdia(duration, base_offset, use_co64);
- mp4_box(b"trak", &[&tkhd, &mdia])
- }
-
- fn build_tkhd(&self, duration: u32) -> Vec<u8> {
- let mut c = Vec::with_capacity(80);
- c.extend_from_slice(&0u32.to_be_bytes()); // creation_time
- c.extend_from_slice(&0u32.to_be_bytes()); // modification_time
- c.extend_from_slice(&1u32.to_be_bytes()); // track_ID
- c.extend_from_slice(&0u32.to_be_bytes()); // reserved
- c.extend_from_slice(&duration.to_be_bytes());
- c.extend_from_slice(&[0u8; 8]); // reserved
- c.extend_from_slice(&0u16.to_be_bytes()); // layer
- c.extend_from_slice(&0u16.to_be_bytes()); // alternate_group
- c.extend_from_slice(&0u16.to_be_bytes()); // volume (0 for video)
- c.extend_from_slice(&0u16.to_be_bytes()); // reserved
- c.extend_from_slice(&IDENTITY_MATRIX);
- c.extend_from_slice(&(self.width << 16).to_be_bytes()); // width 16.16
- c.extend_from_slice(&(self.height << 16).to_be_bytes()); // height 16.16
- full_box(b"tkhd", 0, 3, &c) // flags = track_enabled | track_in_movie
- }
-
- fn build_mdia(&self, duration: u32, base_offset: u64, use_co64: bool) -> Vec<u8> {
- let mdhd = self.build_mdhd(duration);
- let hdlr = build_hdlr();
- let minf = self.build_minf(base_offset, use_co64);
- mp4_box(b"mdia", &[&mdhd, &hdlr, &minf])
- }
-
- fn build_mdhd(&self, duration: u32) -> Vec<u8> {
- let mut c = Vec::with_capacity(20);
- c.extend_from_slice(&0u32.to_be_bytes()); // creation_time
- c.extend_from_slice(&0u32.to_be_bytes()); // modification_time
- c.extend_from_slice(&self.timescale.to_be_bytes());
- c.extend_from_slice(&duration.to_be_bytes());
- c.extend_from_slice(&0x55C4u16.to_be_bytes()); // language "und"
- c.extend_from_slice(&0u16.to_be_bytes()); // pre_defined
- full_box(b"mdhd", 0, 0, &c)
- }
-
- fn build_minf(&self, base_offset: u64, use_co64: bool) -> Vec<u8> {
- let vmhd = build_vmhd();
- let dinf = build_dinf();
- let stbl = self.build_stbl(base_offset, use_co64);
- mp4_box(b"minf", &[&vmhd, &dinf, &stbl])
- }
-
- fn build_stbl(&self, base_offset: u64, use_co64: bool) -> Vec<u8> {
- let stsd = self.build_stsd();
- let stts = self.build_stts();
- let stss = self.build_stss();
- let stsz = self.build_stsz();
- let stsc = build_stsc();
- let chunk_offsets = self.build_chunk_offsets(base_offset, use_co64);
-
- let mut children: Vec<&[u8]> = vec![&stsd, &stts, &stss, &stsz, &stsc, &chunk_offsets];
-
- let ctts;
- if self.has_b_frames {
- ctts = self.build_ctts();
- children.push(&ctts);
- }
-
- mp4_box(b"stbl", &children)
- }
-
- fn build_stsd(&self) -> Vec<u8> {
- let avcc_box = self.build_avcc();
- let avc1 = self.build_avc1(&avcc_box);
- let mut c = Vec::with_capacity(4 + avc1.len());
- c.extend_from_slice(&1u32.to_be_bytes()); // entry_count
- c.extend_from_slice(&avc1);
- full_box(b"stsd", 0, 0, &c)
- }
-
- fn build_avc1(&self, avcc_box: &[u8]) -> Vec<u8> {
- let mut c = Vec::with_capacity(78 + avcc_box.len());
- c.extend_from_slice(&[0u8; 6]); // reserved
- c.extend_from_slice(&1u16.to_be_bytes()); // data_reference_index
- c.extend_from_slice(&[0u8; 2]); // pre_defined
- c.extend_from_slice(&[0u8; 2]); // reserved
- c.extend_from_slice(&[0u8; 12]); // pre_defined
- c.extend_from_slice(&(self.width as u16).to_be_bytes());
- c.extend_from_slice(&(self.height as u16).to_be_bytes());
- c.extend_from_slice(&0x0048_0000u32.to_be_bytes()); // horiz 72 dpi
- c.extend_from_slice(&0x0048_0000u32.to_be_bytes()); // vert 72 dpi
- c.extend_from_slice(&0u32.to_be_bytes()); // reserved
- c.extend_from_slice(&1u16.to_be_bytes()); // frame_count
- c.extend_from_slice(&[0u8; 32]); // compressorname
- c.extend_from_slice(&0x0018u16.to_be_bytes()); // depth
- c.extend_from_slice(&0xFFFFu16.to_be_bytes()); // pre_defined = -1
- c.extend_from_slice(avcc_box);
- mp4_box(b"avc1", &[&c])
- }
-
- fn build_avcc(&self) -> Vec<u8> {
- let sps = &self.sps;
- let pps = &self.pps;
- let mut c = Vec::with_capacity(11 + sps.len() + pps.len());
- c.push(1); // configurationVersion
- c.push(sps[1]); // AVCProfileIndication
- c.push(sps[2]); // profile_compatibility
- c.push(sps[3]); // AVCLevelIndication
- c.push(0xFF); // lengthSizeMinusOne = 3
- c.push(0xE1); // numOfSPS = 1
- c.extend_from_slice(&(sps.len() as u16).to_be_bytes());
- c.extend_from_slice(sps);
- c.push(1); // numOfPPS
- c.extend_from_slice(&(pps.len() as u16).to_be_bytes());
- c.extend_from_slice(pps);
- mp4_box(b"avcC", &[&c])
- }
-
- fn build_stts(&self) -> Vec<u8> {
- let mut entries: Vec<(u32, u32)> = Vec::new();
- for i in 0..self.samples.len() {
- let delta = if i + 1 < self.samples.len() {
- (self.samples[i + 1].dts - self.samples[i].dts) as u32
- } else if let Some(last) = entries.last() {
- last.1
- } else {
- 1
- };
- if let Some(last) = entries.last_mut() {
- if last.1 == delta {
- last.0 += 1;
- continue;
- }
- }
- entries.push((1, delta));
- }
- let mut c = Vec::with_capacity(4 + entries.len() * 8);
- c.extend_from_slice(&(entries.len() as u32).to_be_bytes());
- for &(count, delta) in &entries {
- c.extend_from_slice(&count.to_be_bytes());
- c.extend_from_slice(&delta.to_be_bytes());
- }
- full_box(b"stts", 0, 0, &c)
- }
-
- fn build_stss(&self) -> Vec<u8> {
- let keyframes: Vec<u32> = self
- .samples
- .iter()
- .enumerate()
- .filter(|(_, s)| s.is_keyframe)
- .map(|(i, _)| (i + 1) as u32) // 1-based
- .collect();
- let mut c = Vec::with_capacity(4 + keyframes.len() * 4);
- c.extend_from_slice(&(keyframes.len() as u32).to_be_bytes());
- for &k in &keyframes {
- c.extend_from_slice(&k.to_be_bytes());
- }
- full_box(b"stss", 0, 0, &c)
- }
-
- fn build_stsz(&self) -> Vec<u8> {
- let n = self.samples.len() as u32;
- let mut c = Vec::with_capacity(8 + self.samples.len() * 4);
- c.extend_from_slice(&0u32.to_be_bytes()); // sample_size = 0 (variable)
- c.extend_from_slice(&n.to_be_bytes());
- for s in &self.samples {
- c.extend_from_slice(&s.size.to_be_bytes());
- }
- full_box(b"stsz", 0, 0, &c)
- }
-
- fn build_chunk_offsets(&self, base_offset: u64, use_co64: bool) -> Vec<u8> {
- if use_co64 {
- self.build_co64(base_offset)
- } else {
- self.build_stco(base_offset)
- }
- }
-
- fn build_stco(&self, base_offset: u64) -> Vec<u8> {
- let n = self.samples.len() as u32;
- let mut c = Vec::with_capacity(4 + self.samples.len() * 4);
- c.extend_from_slice(&n.to_be_bytes());
- let mut offset = base_offset;
- for s in &self.samples {
- debug_assert!(
- offset <= u32::MAX as u64,
- "Chunk offset {} exceeds u32 — should have used co64",
- offset,
- );
- c.extend_from_slice(&(offset as u32).to_be_bytes());
- offset += s.size as u64;
- }
- full_box(b"stco", 0, 0, &c)
- }
-
- fn build_co64(&self, base_offset: u64) -> Vec<u8> {
- let n = self.samples.len() as u32;
- let mut c = Vec::with_capacity(4 + self.samples.len() * 8);
- c.extend_from_slice(&n.to_be_bytes());
- let mut offset = base_offset;
- for s in &self.samples {
- c.extend_from_slice(&offset.to_be_bytes());
- offset += s.size as u64;
- }
- full_box(b"co64", 0, 0, &c)
- }
-
- fn build_ctts(&self) -> Vec<u8> {
- let mut entries: Vec<(u32, i32)> = Vec::new();
- for s in &self.samples {
- if let Some(last) = entries.last_mut() {
- if last.1 == s.cts_offset {
- last.0 += 1;
- continue;
- }
- }
- entries.push((1, s.cts_offset));
- }
- let mut c = Vec::with_capacity(4 + entries.len() * 8);
- c.extend_from_slice(&(entries.len() as u32).to_be_bytes());
- for &(count, offset) in &entries {
- c.extend_from_slice(&count.to_be_bytes());
- c.extend_from_slice(&offset.to_be_bytes());
- }
- full_box(b"ctts", 1, 0, &c) // version 1 for signed offsets
- }
-}
-
-// ── Standalone box builders (regular MP4) ─────────────────────────
-
-fn build_ftyp() -> Vec<u8> {
- let mut c = Vec::with_capacity(24);
- c.extend_from_slice(b"isom"); // major_brand
- c.extend_from_slice(&512u32.to_be_bytes()); // minor_version
- c.extend_from_slice(b"isom");
- c.extend_from_slice(b"iso2");
- c.extend_from_slice(b"avc1");
- c.extend_from_slice(b"mp41");
- mp4_box(b"ftyp", &[&c])
-}
-
-fn build_hdlr() -> Vec<u8> {
- let mut c = Vec::with_capacity(33);
- c.extend_from_slice(&0u32.to_be_bytes()); // pre_defined
- c.extend_from_slice(b"vide"); // handler_type
- c.extend_from_slice(&[0u8; 12]); // reserved
- c.extend_from_slice(b"VideoHandler\0"); // name (null-terminated)
- full_box(b"hdlr", 0, 0, &c)
-}
-
-fn build_vmhd() -> Vec<u8> {
- let mut c = Vec::with_capacity(8);
- c.extend_from_slice(&0u16.to_be_bytes()); // graphicsmode
- c.extend_from_slice(&[0u8; 6]); // opcolor
- full_box(b"vmhd", 0, 1, &c) // flags = 1 per spec
-}
-
-fn build_dinf() -> Vec<u8> {
- let url = full_box(b"url ", 0, 1, &[]); // self-contained
- let mut dref_c = Vec::with_capacity(4 + url.len());
- dref_c.extend_from_slice(&1u32.to_be_bytes()); // entry_count
- dref_c.extend_from_slice(&url);
- let dref = full_box(b"dref", 0, 0, &dref_c);
- mp4_box(b"dinf", &[&dref])
-}
-
-fn build_stsc() -> Vec<u8> {
- let mut c = Vec::with_capacity(16);
- c.extend_from_slice(&1u32.to_be_bytes()); // entry_count
- c.extend_from_slice(&1u32.to_be_bytes()); // first_chunk
- c.extend_from_slice(&1u32.to_be_bytes()); // samples_per_chunk
- c.extend_from_slice(&1u32.to_be_bytes()); // sample_description_index
- full_box(b"stsc", 0, 0, &c)
-}
-
-fn build_mdat_header(data_size: u64) -> Vec<u8> {
- let total = 8 + data_size;
- if total <= u32::MAX as u64 {
- let mut h = Vec::with_capacity(8);
- h.extend_from_slice(&(total as u32).to_be_bytes());
- h.extend_from_slice(b"mdat");
- h
- } else {
- let mut h = Vec::with_capacity(16);
- h.extend_from_slice(&1u32.to_be_bytes()); // extended size marker
- h.extend_from_slice(b"mdat");
- h.extend_from_slice(&(16 + data_size).to_be_bytes());
- h
- }
-}
-
-fn mdat_header_size(data_size: u64) -> u64 {
- if 8 + data_size > u32::MAX as u64 {
- 16
- } else {
- 8
- }
-}
-
-// ── Fragmented MP4 box builders ───────────────────────────────────
-
-fn build_fmp4_ftyp() -> Vec<u8> {
- let mut c = Vec::with_capacity(24);
- c.extend_from_slice(b"isom"); // major_brand
- c.extend_from_slice(&512u32.to_be_bytes()); // minor_version
- c.extend_from_slice(b"isom");
- c.extend_from_slice(b"iso6");
- c.extend_from_slice(b"msdh");
- c.extend_from_slice(b"msix");
- mp4_box(b"ftyp", &[&c])
-}
-
-fn build_fmp4_init_moov(
- width: u32,
- height: u32,
- timescale: u32,
- sps: &[u8],
- pps: &[u8],
-) -> Vec<u8> {
- let mvhd = {
- let mut c = Vec::with_capacity(96);
- c.extend_from_slice(&0u32.to_be_bytes()); // creation_time
- c.extend_from_slice(&0u32.to_be_bytes()); // modification_time
- c.extend_from_slice(&timescale.to_be_bytes());
- c.extend_from_slice(&0u32.to_be_bytes()); // duration = 0 (fragmented)
- c.extend_from_slice(&0x0001_0000u32.to_be_bytes()); // rate 1.0
- c.extend_from_slice(&0x0100u16.to_be_bytes()); // volume 1.0
- c.extend_from_slice(&[0u8; 10]); // reserved
- c.extend_from_slice(&IDENTITY_MATRIX);
- c.extend_from_slice(&[0u8; 24]); // pre_defined
- c.extend_from_slice(&2u32.to_be_bytes()); // next_track_ID
- full_box(b"mvhd", 0, 0, &c)
- };
-
- let tkhd = {
- let mut c = Vec::with_capacity(80);
- c.extend_from_slice(&0u32.to_be_bytes()); // creation_time
- c.extend_from_slice(&0u32.to_be_bytes()); // modification_time
- c.extend_from_slice(&1u32.to_be_bytes()); // track_ID
- c.extend_from_slice(&0u32.to_be_bytes()); // reserved
- c.extend_from_slice(&0u32.to_be_bytes()); // duration = 0
- c.extend_from_slice(&[0u8; 8]); // reserved
- c.extend_from_slice(&0u16.to_be_bytes()); // layer
- c.extend_from_slice(&0u16.to_be_bytes()); // alternate_group
- c.extend_from_slice(&0u16.to_be_bytes()); // volume
- c.extend_from_slice(&0u16.to_be_bytes()); // reserved
- c.extend_from_slice(&IDENTITY_MATRIX);
- c.extend_from_slice(&(width << 16).to_be_bytes());
- c.extend_from_slice(&(height << 16).to_be_bytes());
- full_box(b"tkhd", 0, 3, &c)
- };
-
- let mdhd = {
- let mut c = Vec::with_capacity(20);
- c.extend_from_slice(&0u32.to_be_bytes()); // creation_time
- c.extend_from_slice(&0u32.to_be_bytes()); // modification_time
- c.extend_from_slice(&timescale.to_be_bytes());
- c.extend_from_slice(&0u32.to_be_bytes()); // duration = 0
- c.extend_from_slice(&0x55C4u16.to_be_bytes()); // language "und"
- c.extend_from_slice(&0u16.to_be_bytes());
- full_box(b"mdhd", 0, 0, &c)
- };
-
- let hdlr = build_hdlr();
-
- // avcC box
- let avcc = {
- let mut c = Vec::with_capacity(11 + sps.len() + pps.len());
- c.push(1);
- c.push(sps[1]);
- c.push(sps[2]);
- c.push(sps[3]);
- c.push(0xFF);
- c.push(0xE1);
- c.extend_from_slice(&(sps.len() as u16).to_be_bytes());
- c.extend_from_slice(sps);
- c.push(1);
- c.extend_from_slice(&(pps.len() as u16).to_be_bytes());
- c.extend_from_slice(pps);
- mp4_box(b"avcC", &[&c])
- };
-
- // avc1 sample entry
- let avc1 = {
- let mut c = Vec::with_capacity(78 + avcc.len());
- c.extend_from_slice(&[0u8; 6]);
- c.extend_from_slice(&1u16.to_be_bytes());
- c.extend_from_slice(&[0u8; 2]);
- c.extend_from_slice(&[0u8; 2]);
- c.extend_from_slice(&[0u8; 12]);
- c.extend_from_slice(&(width as u16).to_be_bytes());
- c.extend_from_slice(&(height as u16).to_be_bytes());
- c.extend_from_slice(&0x0048_0000u32.to_be_bytes());
- c.extend_from_slice(&0x0048_0000u32.to_be_bytes());
- c.extend_from_slice(&0u32.to_be_bytes());
- c.extend_from_slice(&1u16.to_be_bytes());
- c.extend_from_slice(&[0u8; 32]);
- c.extend_from_slice(&0x0018u16.to_be_bytes());
- c.extend_from_slice(&0xFFFFu16.to_be_bytes());
- c.extend_from_slice(&avcc);
- mp4_box(b"avc1", &[&c])
- };
-
- let stsd = {
- let mut c = Vec::with_capacity(4 + avc1.len());
- c.extend_from_slice(&1u32.to_be_bytes());
- c.extend_from_slice(&avc1);
- full_box(b"stsd", 0, 0, &c)
- };
-
- // Empty sample tables (required by spec for fmp4 init segment)
- let stts = full_box(b"stts", 0, 0, &0u32.to_be_bytes());
- let stsz = {
- let mut c = Vec::with_capacity(8);
- c.extend_from_slice(&0u32.to_be_bytes()); // sample_size
- c.extend_from_slice(&0u32.to_be_bytes()); // sample_count
- full_box(b"stsz", 0, 0, &c)
- };
- let stsc = full_box(b"stsc", 0, 0, &0u32.to_be_bytes());
- let stco = full_box(b"stco", 0, 0, &0u32.to_be_bytes());
-
- let stbl = mp4_box(b"stbl", &[&stsd, &stts, &stsz, &stsc, &stco]);
-
- let vmhd = build_vmhd();
- let dinf = build_dinf();
- let minf = mp4_box(b"minf", &[&vmhd, &dinf, &stbl]);
- let mdia = mp4_box(b"mdia", &[&mdhd, &hdlr, &minf]);
- let trak = mp4_box(b"trak", &[&tkhd, &mdia]);
-
- // mvex with trex
- let trex = {
- let mut c = Vec::with_capacity(20);
- c.extend_from_slice(&1u32.to_be_bytes()); // track_ID
- c.extend_from_slice(&1u32.to_be_bytes()); // default_sample_description_index
- c.extend_from_slice(&0u32.to_be_bytes()); // default_sample_duration
- c.extend_from_slice(&0u32.to_be_bytes()); // default_sample_size
- c.extend_from_slice(&0u32.to_be_bytes()); // default_sample_flags
- full_box(b"trex", 0, 0, &c)
- };
- let mvex = mp4_box(b"mvex", &[&trex]);
-
- mp4_box(b"moov", &[&mvhd, &trak, &mvex])
-}
-
-/// Flush a fragment (moof + mdat pair) to the writer.
-fn flush_fragment(
- writer: &mut BufWriter<File>,
- sequence_number: &mut u32,
- fragment_samples: &mut Vec<SampleInfo>,
- fragment_mdat: &mut Vec<u8>,
- base_decode_time: i64,
-) -> io::Result<()> {
- if fragment_samples.is_empty() {
- return Ok(());
- }
-
- // Build moof with placeholder data_offset, measure size, rebuild with correct offset
- let moof_size = compute_moof_size(fragment_samples.len());
- let mdat_hdr = 8u32; // fragment mdat is always small enough for 4-byte size
- let data_offset = (moof_size + mdat_hdr) as i32;
-
- let moof = build_moof(
- *sequence_number,
- base_decode_time,
- fragment_samples,
- data_offset,
- );
- debug_assert_eq!(moof.len(), moof_size as usize);
-
- // mdat box
- let mdat_total = 8 + fragment_mdat.len();
- let mut mdat = Vec::with_capacity(mdat_total);
- mdat.extend_from_slice(&(mdat_total as u32).to_be_bytes());
- mdat.extend_from_slice(b"mdat");
- mdat.extend_from_slice(fragment_mdat);
-
- writer.write_all(&moof)?;
- writer.write_all(&mdat)?;
-
- *sequence_number += 1;
- fragment_samples.clear();
- fragment_mdat.clear();
-
- Ok(())
-}
-
-/// Compute moof box size deterministically from sample count.
-/// moof = 8 (box hdr) + mfhd(16) + traf(8 + tfhd(16) + tfdt(20) + trun(12 + 16*n))
-fn compute_moof_size(n_samples: usize) -> u32 {
- let mfhd = 16u32; // full_box(12) + seq_num(4)
- let tfhd = 16u32; // full_box(12) + track_id(4)
- let tfdt = 20u32; // full_box(12) + base_decode_time(8) [version 1]
- // trun: full_box(12) + sample_count(4) + data_offset(4) + per-sample(16) * n
- let trun = 12 + 4 + 4 + (16 * n_samples as u32);
- let traf = 8 + tfhd + tfdt + trun;
- 8 + mfhd + traf
-}
-
-fn build_moof(
- seq_num: u32,
- base_decode_time: i64,
- samples: &[SampleInfo],
- data_offset: i32,
-) -> Vec<u8> {
- let mfhd = build_mfhd(seq_num);
- let traf = build_traf(base_decode_time, samples, data_offset);
- mp4_box(b"moof", &[&mfhd, &traf])
-}
-
-fn build_mfhd(seq_num: u32) -> Vec<u8> {
- full_box(b"mfhd", 0, 0, &seq_num.to_be_bytes())
-}
-
-fn build_traf(
- base_decode_time: i64,
- samples: &[SampleInfo],
- data_offset: i32,
-) -> Vec<u8> {
- let tfhd = build_tfhd();
- let tfdt = build_tfdt(base_decode_time);
- let trun = build_trun(samples, data_offset);
- mp4_box(b"traf", &[&tfhd, &tfdt, &trun])
-}
-
-fn build_tfhd() -> Vec<u8> {
- // flags = 0x020000 (default-base-is-moof)
- let mut c = Vec::with_capacity(4);
- c.extend_from_slice(&1u32.to_be_bytes()); // track_ID
- full_box(b"tfhd", 0, 0x020000, &c)
-}
-
-fn build_tfdt(base_decode_time: i64) -> Vec<u8> {
- // version 1: 64-bit decode time
- full_box(b"tfdt", 1, 0, &(base_decode_time as u64).to_be_bytes())
-}
-
-fn build_trun(samples: &[SampleInfo], data_offset: i32) -> Vec<u8> {
- // flags: data-offset-present(0x1) | sample-duration-present(0x100)
- // | sample-size-present(0x200) | sample-flags-present(0x400)
- // | sample-composition-time-offsets-present(0x800)
- let flags: u32 = 0x1 | 0x100 | 0x200 | 0x400 | 0x800;
-
- let n = samples.len();
- let mut c = Vec::with_capacity(4 + 4 + n * 16);
- c.extend_from_slice(&(n as u32).to_be_bytes()); // sample_count
- c.extend_from_slice(&data_offset.to_be_bytes()); // data_offset
-
- for i in 0..n {
- // sample_duration: delta to next sample's DTS
- let duration = if i + 1 < n {
- (samples[i + 1].dts - samples[i].dts) as u32
- } else if i > 0 {
- (samples[i].dts - samples[i - 1].dts) as u32
- } else {
- 1
- };
- c.extend_from_slice(&duration.to_be_bytes());
-
- // sample_size
- c.extend_from_slice(&samples[i].size.to_be_bytes());
-
- // sample_flags: bit 16 set = non-sync (non-keyframe), bit 25 = depends_on_other
- let sample_flags: u32 = if samples[i].is_keyframe {
- 0x02000000 // sample_depends_on = 2 (does not depend on others)
- } else {
- 0x01010000 // sample_depends_on = 1 (depends) | sample_is_non_sync = 1
- };
- c.extend_from_slice(&sample_flags.to_be_bytes());
-
- // sample_composition_time_offset (signed, version 1 trun would be needed
- // but we use version 0 with unsigned — works for non-negative offsets,
- // use version 1 for signed)
- c.extend_from_slice(&samples[i].cts_offset.to_be_bytes());
- }
-
- // version 1 for signed composition time offsets
- full_box(b"trun", 1, flags, &c)
-}
-
-// ── Identity matrix (3x3, 16.16 / 2.30 fixed-point) ───────────────
-
-const IDENTITY_MATRIX: [u8; 36] = {
- let mut m = [0u8; 36];
- // a = 1.0 (16.16) at bytes 0..4
- m[0] = 0x00;
- m[1] = 0x01;
- m[2] = 0x00;
- m[3] = 0x00;
- // d = 1.0 (16.16) at bytes 16..20
- m[16] = 0x00;
- m[17] = 0x01;
- m[18] = 0x00;
- m[19] = 0x00;
- // w = 1.0 (2.30) at bytes 32..36
- m[32] = 0x40;
- m[33] = 0x00;
- m[34] = 0x00;
- m[35] = 0x00;
- m
-};
-
-// ── Box construction helpers ───────────────────────────────────────
-
-fn mp4_box(box_type: &[u8; 4], parts: &[&[u8]]) -> Vec<u8> {
- let payload_len: usize = parts.iter().map(|p| p.len()).sum();
- let total = 8 + payload_len;
- let mut buf = Vec::with_capacity(total);
- buf.extend_from_slice(&(total as u32).to_be_bytes());
- buf.extend_from_slice(box_type);
- for part in parts {
- buf.extend_from_slice(part);
- }
- buf
-}
-
-fn full_box(box_type: &[u8; 4], version: u8, flags: u32, content: &[u8]) -> Vec<u8> {
- let total = 12 + content.len();
- let mut buf = Vec::with_capacity(total);
- buf.extend_from_slice(&(total as u32).to_be_bytes());
- buf.extend_from_slice(box_type);
- buf.push(version);
- let flag_bytes = flags.to_be_bytes();
- buf.extend_from_slice(&flag_bytes[1..4]);
- buf.extend_from_slice(content);
- buf
-}
-
diff --git a/rust/bridge/crates/manimgx-core/src/scene.rs b/rust/bridge/crates/manimgx-core/src/scene.rs
deleted file mode 100644
index 1832b763..00000000
--- a/rust/bridge/crates/manimgx-core/src/scene.rs
+++ /dev/null
@@ -1,149 +0,0 @@
-use crate::camera::CameraRig;
-use crate::material::Material;
-use crate::transform::Transform;
-use crate::vertex::Vertex;
-
-pub type ObjectId = usize;
-
-/// RGBA bitmap data for textured objects (e.g. rendered text).
-#[derive(Clone, Debug)]
-pub struct TextureData {
- pub rgba: Vec<u8>,
- pub width: u32,
- pub height: u32,
-}
-
-#[derive(Clone, Copy, Debug, Default)]
-pub enum RenderHint {
- #[default]
- Default,
- FlatUnlit,
- /// Textured quad (e.g. text bitmap). Uses text.wgsl with texture sampling.
- Textured,
-}
-
-#[derive(Clone, Debug)]
-pub struct SceneObject {
- pub id: ObjectId,
- pub vertices: Vec<Vertex>,
- pub indices: Vec<u32>,
- pub transform: Transform,
- pub base_transform: Transform,
- pub material: Material,
- pub base_material: Material,
- pub render_hint: RenderHint,
- /// Optional texture data for Textured render hint (uploaded once, not per frame).
- pub texture_data: Option<TextureData>,
-}
-
-pub struct Scene {
- pub width: u32,
- pub height: u32,
- pub fps: u32,
- pub background: [f32; 4],
- pub camera: CameraRig,
- pub base_camera: CameraRig,
- pub objects: Vec<SceneObject>,
- next_id: ObjectId,
-}
-
-impl Scene {
- pub fn new(width: u32, height: u32, fps: u32, background: [f32; 3]) -> Self {
- Self {
- width,
- height,
- fps,
- background: [background[0], background[1], background[2], 1.0],
- camera: CameraRig::default(),
- base_camera: CameraRig::default(),
- objects: Vec::new(),
- next_id: 0,
- }
- }
-
- pub fn set_camera(&mut self, camera: CameraRig) {
- self.camera = camera.clone();
- self.base_camera = camera;
- }
-
- pub fn add_object_with_hint(
- &mut self,
- vertices: Vec<Vertex>,
- indices: Vec<u32>,
- material: Material,
- render_hint: RenderHint,
- position: [f32; 3],
- ) -> ObjectId {
- let id = self.next_id;
- self.next_id += 1;
- let transform = Transform {
- translation: glam::Vec3::new(position[0], position[1], position[2]),
- ..Transform::default()
- };
- self.objects.push(SceneObject {
- id,
- vertices,
- indices,
- transform: transform.clone(),
- base_transform: transform,
- material: material.clone(),
- base_material: material,
- render_hint,
- texture_data: None,
- });
- id
- }
-
- /// Add a textured object (e.g. text bitmap) with texture data attached.
- pub fn add_textured_object(
- &mut self,
- vertices: Vec<Vertex>,
- indices: Vec<u32>,
- material: Material,
- position: [f32; 3],
- texture: TextureData,
- ) -> ObjectId {
- let id = self.next_id;
- self.next_id += 1;
- let transform = Transform {
- translation: glam::Vec3::new(position[0], position[1], position[2]),
- ..Transform::default()
- };
- self.objects.push(SceneObject {
- id,
- vertices,
- indices,
- transform: transform.clone(),
- base_transform: transform,
- material: material.clone(),
- base_material: material,
- render_hint: RenderHint::Textured,
- texture_data: Some(texture),
- });
- id
- }
-
- pub fn set_transform(&mut self, id: ObjectId, transform: Transform) {
- if let Some(obj) = self.objects.get_mut(id) {
- obj.transform = transform;
- }
- }
-
- pub fn set_material(&mut self, id: ObjectId, material: Material) {
- if let Some(obj) = self.objects.get_mut(id) {
- obj.material = material;
- }
- }
-
- pub fn reset_to_base(&mut self) {
- self.camera = self.base_camera.clone();
- for obj in &mut self.objects {
- obj.transform = obj.base_transform.clone();
- obj.material = obj.base_material.clone();
- }
- }
-
- pub fn aspect_ratio(&self) -> f32 {
- self.width as f32 / self.height as f32
- }
-}
diff --git a/rust/bridge/crates/manimgx-core/src/timeline_eval.rs b/rust/bridge/crates/manimgx-core/src/timeline_eval.rs
deleted file mode 100644
index 64f6705b..00000000
--- a/rust/bridge/crates/manimgx-core/src/timeline_eval.rs
+++ /dev/null
@@ -1,14 +0,0 @@
-use crate::scene::Scene;
-
-/// Trait for timeline evaluation — allows renderer to drive frame evaluation
-/// without depending on manimgx-core's Timeline directly.
-pub trait TimelineEval {
- fn evaluate(&self, scene: &mut Scene, time: f32);
-}
-
-/// Adapter: wraps manimgx_core::animation::timeline::Timeline
-impl TimelineEval for crate::animation::timeline::Timeline {
- fn evaluate(&self, scene: &mut Scene, time: f32) {
- self.evaluate(scene, time);
- }
-}
diff --git a/rust/bridge/crates/manimgx-core/src/transform.rs b/rust/bridge/crates/manimgx-core/src/transform.rs
deleted file mode 100644
index dc2f28c3..00000000
--- a/rust/bridge/crates/manimgx-core/src/transform.rs
+++ /dev/null
@@ -1,46 +0,0 @@
-use glam::{Mat4, Quat, Vec3};
-
-#[derive(Clone, Copy, Debug)]
-pub struct Transform {
- pub translation: Vec3,
- pub rotation: Vec3,
- pub scale: Vec3,
-}
-
-impl Default for Transform {
- fn default() -> Self {
- Self {
- translation: Vec3::ZERO,
- rotation: Vec3::ZERO,
- scale: Vec3::ONE,
- }
- }
-}
-
-impl Transform {
- pub fn to_matrix(&self) -> Mat4 {
- // Fast path: skip quaternion for zero rotation (common for 2D objects)
- if self.rotation == Vec3::ZERO {
- return Mat4::from_scale_rotation_translation(
- self.scale,
- Quat::IDENTITY,
- self.translation,
- );
- }
- let rotation_quat = Quat::from_euler(
- glam::EulerRot::YXZ,
- self.rotation.y.to_radians(),
- self.rotation.x.to_radians(),
- self.rotation.z.to_radians(),
- );
- Mat4::from_scale_rotation_translation(self.scale, rotation_quat, self.translation)
- }
-
- pub fn lerp(&self, other: &Transform, t: f32) -> Transform {
- Transform {
- translation: self.translation.lerp(other.translation, t),
- rotation: self.rotation.lerp(other.rotation, t),
- scale: self.scale.lerp(other.scale, t),
- }
- }
-}
diff --git a/rust/bridge/crates/manimgx-core/src/uniform.rs b/rust/bridge/crates/manimgx-core/src/uniform.rs
deleted file mode 100644
index 4979fade..00000000
--- a/rust/bridge/crates/manimgx-core/src/uniform.rs
+++ /dev/null
@@ -1,17 +0,0 @@
-/// GPU uniform buffer types shared across render backends.
-/// Layout must match WGSL and MSL shader struct definitions exactly.
-
-#[repr(C)]
-#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
-pub struct CameraUniform {
- pub view_proj: [[f32; 4]; 4],
-}
-
-#[repr(C)]
-#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
-pub struct ObjectUniform {
- pub model: [[f32; 4]; 4],
- pub material_color: [f32; 4],
- pub use_vertex_colors: u32,
- pub _pad: [u32; 3],
-}
diff --git a/rust/bridge/crates/manimgx-core/src/vertex.rs b/rust/bridge/crates/manimgx-core/src/vertex.rs
deleted file mode 100644
index 3a6d08b1..00000000
--- a/rust/bridge/crates/manimgx-core/src/vertex.rs
+++ /dev/null
@@ -1,19 +0,0 @@
-use bytemuck::{Pod, Zeroable};
-
-#[repr(C)]
-#[derive(Clone, Copy, Debug, Pod, Zeroable)]
-pub struct Vertex {
- pub position: [f32; 3],
- pub normal: [f32; 3],
- pub color: [f32; 4],
-}
-
-impl Vertex {
- pub fn new(position: [f32; 3], normal: [f32; 3], color: [f32; 4]) -> Self {
- Self {
- position,
- normal,
- color,
- }
- }
-}
diff --git a/rust/bridge/crates/manimgx-encode/Cargo.toml b/rust/bridge/crates/manimgx-encode/Cargo.toml
deleted file mode 100644
index d66b7497..00000000
--- a/rust/bridge/crates/manimgx-encode/Cargo.toml
+++ /dev/null
@@ -1,13 +0,0 @@
-[package]
-name = "manimgx-encode"
-version = "0.1.0"
-edition = "2021"
-build = "build.rs"
-
-[dependencies]
-manimgx-core = { path = "../manimgx-core" }
-log = { workspace = true }
-
-[build-dependencies]
-pkg-config = "0.3"
-bindgen = { version = "0.70", default-features = false, features = ["runtime"] }
diff --git a/rust/bridge/crates/manimgx-encode/src/lib.rs b/rust/bridge/crates/manimgx-encode/src/lib.rs
deleted file mode 100644
index f80ad3b3..00000000
--- a/rust/bridge/crates/manimgx-encode/src/lib.rs
+++ /dev/null
@@ -1,2 +0,0 @@
-mod x264;
-pub use x264::{X264FrameMsg, X264Writer};
diff --git a/rust/bridge/crates/manimgx-encode/src/x264.rs b/rust/bridge/crates/manimgx-encode/src/x264.rs
deleted file mode 100644
index e99af877..00000000
--- a/rust/bridge/crates/manimgx-encode/src/x264.rs
+++ /dev/null
@@ -1,298 +0,0 @@
-#[allow(non_upper_case_globals, non_camel_case_types, non_snake_case, dead_code)]
-mod bindings {
- include!(concat!(env!("OUT_DIR"), "/x264_bindings.rs"));
-}
-use bindings::*;
-
-use std::sync::mpsc::{channel, Sender};
-use std::thread::{self, JoinHandle};
-
-/// Message sent from the render loop to the encoder thread.
-pub enum X264FrameMsg {
- /// A new frame: pointer into a pool NV12 buffer.
- Frame {
- ptr: *const u8,
- len: usize,
- pts: i64,
- buf_idx: usize,
- },
- /// Duplicate frame: re-encode from the scratch buffer.
- Dup { pts: i64 },
- /// Flush delayed frames and shut down.
- Flush,
-}
-
-// SAFETY: ptr points to a pinned buffer (MTLBuffer or Vec<u8>) in shared storage.
-// The buffer remains valid until the encoder thread sends buf_idx back
-// via release_tx, at which point the pool reclaims it. The main thread
-// only reuses pool buffers after they are released.
-unsafe impl Send for X264FrameMsg {}
-
-/// In-process x264 encoder. Spawns an encoder thread that receives NV12
-/// frames via an unbounded channel and muxes directly to MP4.
-pub struct X264Writer {
- sender: Sender<X264FrameMsg>,
- handle: Option<JoinHandle<()>>,
-}
-
-impl X264Writer {
- pub fn new(
- output: &str,
- width: u32,
- height: u32,
- fps: u32,
- preset: &str,
- crf: u32,
- release_tx: Sender<usize>,
- muxer: &str,
- ) -> Self {
- use manimgx_core::mp4_muxer::MuxerStrategy;
- let strategy = match muxer {
- "ram" => MuxerStrategy::Ram,
- "fmp4" => MuxerStrategy::Fmp4,
- _ => MuxerStrategy::Disk,
- };
-
- let output_owned = output.to_string();
- let width_i = width as i32;
- let height_i = height as i32;
- let fps_i = fps as i32;
- let crf_f = crf as f32;
- let preset_owned = preset.to_string();
-
- // Unbounded channel: elastic pool provides backpressure instead
- let (sender, receiver) = channel::<X264FrameMsg>();
-
- let handle = thread::spawn(move || {
- unsafe {
- encoder_thread_main(
- &receiver,
- &output_owned,
- width_i,
- height_i,
- fps_i,
- crf_f,
- &preset_owned,
- &release_tx,
- strategy,
- );
- }
- });
-
- Self {
- sender,
- handle: Some(handle),
- }
- }
-
- /// Send a frame to the encoder thread (zero-copy from pool buffer).
- pub fn send(&self, msg: X264FrameMsg) {
- self.sender.send(msg).expect("x264 encoder thread died");
- }
-
- /// Flush encoder, join thread. MP4 is finalized in the encoder thread.
- pub fn finish(mut self) {
- let _ = self.sender.send(X264FrameMsg::Flush);
- if let Some(handle) = self.handle.take() {
- handle.join().expect("x264 encoder thread panicked");
- }
- }
-}
-
-/// Encoder thread main loop. Runs entirely on a dedicated thread.
-///
-/// SAFETY: All x264 FFI calls happen here. x264 copies input plane data
-/// internally via plane_copy at the start of x264_encoder_encode, so the
-/// pool buffer is safe to release after the call returns. No zerolatency
-/// tune needed — frame-level threading is safe with the elastic pool.
-unsafe fn encoder_thread_main(
- receiver: &std::sync::mpsc::Receiver<X264FrameMsg>,
- output_path: &str,
- width: i32,
- height: i32,
- fps: i32,
- crf: f32,
- preset: &str,
- release_tx: &Sender<usize>,
- muxer_strategy: manimgx_core::mp4_muxer::MuxerStrategy,
-) {
- // 1. Configure x264 params (no tune — frame-level threading for speed)
- let mut param: x264_param_t = std::mem::zeroed();
-
- let preset_cstr = std::ffi::CString::new(preset).unwrap();
- let ret = x264_param_default_preset(
- &mut param,
- preset_cstr.as_ptr(),
- std::ptr::null(),
- );
- assert!(ret == 0, "x264_param_default_preset failed");
-
- param.i_width = width;
- param.i_height = height;
- param.i_csp = X264_CSP_NV12 as i32;
- param.i_fps_num = fps as u32;
- param.i_fps_den = 1;
- param.i_timebase_num = 1;
- param.i_timebase_den = fps as u32;
- param.b_repeat_headers = 1;
- param.b_annexb = 1;
- param.rc.f_rf_constant = crf;
- param.vui.i_sar_width = 1;
- param.vui.i_sar_height = 1;
- param.i_log_level = X264_LOG_NONE;
-
- let profile_cstr = c"high";
- let ret = x264_param_apply_profile(&mut param, profile_cstr.as_ptr());
- assert!(ret == 0, "x264_param_apply_profile failed");
-
- // 2. Open encoder
- // x264_encoder_open is a version-mangled macro; use the actual symbol
- let encoder = x264_encoder_open_165(&mut param);
- assert!(!encoder.is_null(), "x264_encoder_open failed");
-
- // 3. Init MP4 muxer
- use manimgx_core::mp4_muxer::Mp4Muxer;
- let mut muxer = Mp4Muxer::new(output_path, width as u32, height as u32, fps as f64, muxer_strategy)
- .expect("Failed to create MP4 muxer");
- // 4. Allocate dup scratch buffer (W*H*3/2 bytes for NV12)
- let nv12_size = (width * height * 3 / 2) as usize;
- let mut dup_scratch = vec![0u8; nv12_size];
-
- // 5. Init picture struct once
- let mut pic: x264_picture_t = std::mem::zeroed();
- x264_picture_init(&mut pic);
- pic.img.i_csp = X264_CSP_NV12 as i32;
- pic.img.i_plane = 2;
- // Strides: Y plane = width, UV plane = width (interleaved U/V)
- pic.img.i_stride[0] = width;
- pic.img.i_stride[1] = width;
-
- let mut pic_out: x264_picture_t = std::mem::zeroed();
-
- // Helper: pass raw NAL slices directly to muxer (zero Annex B roundtrip)
- macro_rules! mux_nals {
- ($frame_size:expr, $pp_nal:expr, $i_nal:expr, $pic_out:expr) => {
- if $frame_size > 0 {
- let is_keyframe = $pic_out.b_keyframe != 0;
-
- // Build slice of raw NAL payloads, stripping Annex B start codes
- let mut nal_slices: Vec<&[u8]> = Vec::with_capacity($i_nal as usize);
- for i in 0..$i_nal as isize {
- let nal = &*$pp_nal.offset(i);
- let data = std::slice::from_raw_parts(nal.p_payload, nal.i_payload as usize);
- // x264 NALs include Annex B start code; strip to get raw NAL unit
- let raw = if data.len() > 4
- && data[0] == 0 && data[1] == 0 && data[2] == 0 && data[3] == 1
- {
- &data[4..]
- } else if data.len() > 3
- && data[0] == 0 && data[1] == 0 && data[2] == 1
- {
- &data[3..]
- } else {
- data
- };
- nal_slices.push(raw);
- }
-
- let pts_secs = $pic_out.i_pts as f64 / fps as f64;
- let dts_secs = $pic_out.i_dts as f64 / fps as f64;
- muxer.write_video_nals(pts_secs, dts_secs, &nal_slices, is_keyframe)
- .expect("Failed to write frame to MP4 muxer");
- }
- };
- }
-
- // 6. Encode loop
- loop {
- let msg = match receiver.recv() {
- Ok(msg) => msg,
- Err(_) => break, // channel closed
- };
-
- match msg {
- X264FrameMsg::Frame { ptr, len, pts, buf_idx } => {
- debug_assert_eq!(len, nv12_size);
-
- // Set plane pointers into the pool buffer
- pic.img.plane[0] = ptr as *mut u8;
- pic.img.plane[1] = ptr.add((width * height) as usize) as *mut u8;
- pic.i_pts = pts;
-
- let mut pp_nal: *mut x264_nal_t = std::ptr::null_mut();
- let mut i_nal: i32 = 0;
-
- let frame_size = x264_encoder_encode(
- encoder,
- &mut pp_nal,
- &mut i_nal,
- &mut pic,
- &mut pic_out,
- );
- assert!(frame_size >= 0, "x264_encoder_encode failed");
-
- // Memcpy NV12 data to dup scratch BEFORE releasing buffer
- // (so we have a copy for potential Dup frames)
- std::ptr::copy_nonoverlapping(ptr, dup_scratch.as_mut_ptr(), nv12_size);
-
- // Release pool buffer back to the main thread
- let _ = release_tx.send(buf_idx);
-
- mux_nals!(frame_size, pp_nal, i_nal, pic_out);
- }
-
- X264FrameMsg::Dup { pts } => {
- // Encode from the dup scratch buffer (not from pool buffer)
- pic.img.plane[0] = dup_scratch.as_ptr() as *mut u8;
- pic.img.plane[1] = dup_scratch.as_ptr().add((width * height) as usize) as *mut u8;
- pic.i_pts = pts;
-
- let mut pp_nal: *mut x264_nal_t = std::ptr::null_mut();
- let mut i_nal: i32 = 0;
-
- let frame_size = x264_encoder_encode(
- encoder,
- &mut pp_nal,
- &mut i_nal,
- &mut pic,
- &mut pic_out,
- );
- assert!(frame_size >= 0, "x264_encoder_encode (dup) failed");
-
- mux_nals!(frame_size, pp_nal, i_nal, pic_out);
- }
-
- X264FrameMsg::Flush => {
- // Drain delayed frames
- loop {
- let delayed = x264_encoder_delayed_frames(encoder);
- if delayed == 0 {
- break;
- }
-
- let mut pp_nal: *mut x264_nal_t = std::ptr::null_mut();
- let mut i_nal: i32 = 0;
-
- let frame_size = x264_encoder_encode(
- encoder,
- &mut pp_nal,
- &mut i_nal,
- std::ptr::null_mut(),
- &mut pic_out,
- );
- if frame_size < 0 {
- break;
- }
-
- mux_nals!(frame_size, pp_nal, i_nal, pic_out);
- }
-
- x264_encoder_close(encoder);
- break;
- }
- }
- }
-
- // Finalize MP4 (writes moov atom, applies fast-start)
- muxer.finish().expect("Failed to finalize MP4 file");
-}
diff --git a/rust/bridge/crates/manimgx-metal/Cargo.toml b/rust/bridge/crates/manimgx-metal/Cargo.toml
deleted file mode 100644
index 1607f777..00000000
--- a/rust/bridge/crates/manimgx-metal/Cargo.toml
+++ /dev/null
@@ -1,21 +0,0 @@
-[package]
-name = "manimgx-metal"
-version = "0.1.0"
-edition = "2021"
-
-[dependencies]
-log = { workspace = true }
-
-[target.'cfg(target_os = "macos")'.dependencies]
-manimgx-core = { path = "../manimgx-core" }
-manimgx-encode = { path = "../manimgx-encode" }
-metal = "0.31"
-objc = "0.2"
-bytemuck = { workspace = true }
-glam = { workspace = true }
-
-[features]
-time_profile = []
-
-[lints.rust]
-unexpected_cfgs = { level = "warn", check-cfg = ['cfg(feature, values("time_profile", "cargo-clippy"))'] }
diff --git a/rust/bridge/crates/manimgx-metal/src/backend.rs b/rust/bridge/crates/manimgx-metal/src/backend.rs
deleted file mode 100644
index 068d6399..00000000
--- a/rust/bridge/crates/manimgx-metal/src/backend.rs
+++ /dev/null
@@ -1,1008 +0,0 @@
-use std::collections::HashMap;
-use std::ffi::c_void;
-use std::sync::Arc;
-
-use manimgx_core::color::srgb_to_linear;
-use manimgx_core::scene::{ObjectId, RenderHint, Scene, TextureData};
-use manimgx_core::uniform::CameraUniform;
-use manimgx_core::vertex::Vertex;
-use metal::foreign_types::{ForeignType, ForeignTypeRef};
-use metal::*;
-use objc::runtime::Object;
-#[allow(unused_imports)]
-use objc::{sel, sel_impl};
-
-// ── Cached GPU resources ──
-
-struct CachedMetalBuffers {
- vertex_buffer: Buffer,
- index_buffer: Buffer,
- index_count: u32,
-}
-
-struct CachedMetalTexture {
- texture: Texture,
-}
-
-// ── Per-frame slot for N-buffering ──
-//
-// Two backing modes:
-// Buffer: MTLBuffer (shared) backs output_texture. After GPU completes,
-// buffer.contents() is a direct pointer to BGRA pixels → pipe to ffmpeg.
-// IOSurface: IOSurface (shared) backs output_texture. Same memory is wrapped
-// by a CVPixelBuffer → fed directly to VideoToolbox. Zero readback.
-
-enum SlotBacking {
- /// CPU-readable MTLBuffer backing store for ffmpeg encoding path.
- Buffer(Buffer),
- /// IOSurface + CVPixelBuffer for VideoToolbox encoding path.
- IOSurface {
- surface: crate::metal_encoder::IOSurfaceRef,
- cv_pixel_buffer: crate::metal_encoder::CVPixelBufferRef,
- },
-}
-
-impl Drop for SlotBacking {
- fn drop(&mut self) {
- if let SlotBacking::IOSurface { surface, cv_pixel_buffer } = self {
- unsafe {
- crate::metal_encoder::CVPixelBufferRelease(*cv_pixel_buffer);
- crate::metal_encoder::CFRelease(*surface as crate::metal_encoder::CFTypeRef);
- }
- }
- // Buffer variant: metal crate's Drop handles it
- }
-}
-
-struct FrameSlot {
- backing: SlotBacking,
- output_texture: Texture, // buffer-backed or IOSurface-backed texture (resolve/render target)
- msaa_texture: Option<Texture>, // private mode, sample_count>1
- depth_texture: Texture, // private mode
- camera_buffer: Buffer, // shared mode, per-slot
- object_buffer: Buffer, // shared mode, per-slot
- pending_cmd_buffer: Option<*mut c_void>, // retained raw MTLCommandBuffer pointer
- /// Signaled by encoding thread after it finishes reading pixels from
- /// pixel_buffer.contents(). Main thread waits on this before reusing the slot.
- pub encoding_done: Arc<EncodingSignal>,
-}
-
-unsafe impl Send for FrameSlot {}
-
-/// Condition-variable-based signal for encoding thread → main thread synchronization.
-/// Replaces AtomicBool spin loop to avoid burning a CPU core.
-pub struct EncodingSignal {
- done: std::sync::Mutex<bool>,
- cvar: std::sync::Condvar,
-}
-
-impl EncodingSignal {
- pub fn new(initial: bool) -> Self {
- Self {
- done: std::sync::Mutex::new(initial),
- cvar: std::sync::Condvar::new(),
- }
- }
-
- /// Mark as done and wake the waiting thread.
- pub fn signal_done(&self) {
- let mut done = self.done.lock().unwrap();
- *done = true;
- self.cvar.notify_one();
- }
-
- /// Wait until done, then return.
- pub fn wait_done(&self) {
- let mut done = self.done.lock().unwrap();
- while !*done {
- done = self.cvar.wait(done).unwrap();
- }
- }
-
- /// Reset to not-done (called before handing slot to encoding thread).
- pub fn reset(&self) {
- let mut done = self.done.lock().unwrap();
- *done = false;
- }
-}
-
-
-// ── Shader compilation ──
-
-/// Replace `#include "types.h"` with actual types content for runtime MSL compilation.
-fn prepare_shader(types_src: &str, shader_src: &str) -> String {
- shader_src.replace("#include \"types.h\"", types_src)
-}
-
-// ── MetalBackend ──
-
-pub struct MetalBackend {
- device: Device,
- queue: CommandQueue,
-
- default_pipeline: RenderPipelineState,
- flat_no_cull_pipeline: RenderPipelineState,
- textured_pipeline: RenderPipelineState,
-
- depth_stencil_state: DepthStencilState,
- sampler_state: SamplerState,
-
- frame_slots: Vec<FrameSlot>,
-
- buffer_cache: HashMap<ObjectId, CachedMetalBuffers>,
- texture_cache: HashMap<ObjectId, CachedMetalTexture>,
-
- width: u32,
- height: u32,
- pixel_size: usize,
-
- // NV12 compute conversion (optional, only when pix_fmt="nv12")
- nv12_pipeline: Option<ComputePipelineState>,
- nv12_buffers: Vec<Buffer>, // one per frame slot, W*H*3/2 bytes
- nv12_dims_buffer: Option<Buffer>, // constant [u32; 2] = [width, height]
- nv12_size: usize,
-}
-
-impl MetalBackend {
- /// Query the default Metal device for supported MSAA sample counts.
- /// Returns an error string if `sample_count` is not supported.
- pub fn validate_sample_count(sample_count: u32) -> Result<(), String> {
- let device = Device::system_default().ok_or("No Metal device found")?;
- if !device.supports_texture_sample_count(sample_count as u64) {
- let supported: Vec<u32> = [1, 2, 4, 8, 16]
- .iter()
- .copied()
- .filter(|&c| device.supports_texture_sample_count(c as u64))
- .collect();
- return Err(format!(
- "Metal device '{}' does not support msaa={}. Supported values: {:?}.",
- device.name(), sample_count, supported
- ));
- }
- Ok(())
- }
-
- pub fn new(width: u32, height: u32, sample_count: u32, n_buffers: u32, pix_fmt: &str) -> Self {
- let device = Device::system_default().expect("No Metal device found");
- let queue = device.new_command_queue();
-
- let use_nv12 = pix_fmt == "nv12";
- log::info!("Metal native backend: {} ({}x{}, MSAA={}, pix_fmt={})", device.name(), width, height, sample_count, pix_fmt);
-
- let pixel_format = MTLPixelFormat::BGRA8Unorm_sRGB;
- let bytes_per_row = (width * 4) as u64;
- let pixel_size = (width * height * 4) as usize;
-
- // Compile MSL shaders
- let types_src = include_str!("../../../shaders/metal/types.h");
- let opts = CompileOptions::new();
-
- let default_lib = device
- .new_library_with_source(&prepare_shader(types_src, include_str!("../../../shaders/metal/default.metal")), &opts)
- .unwrap_or_else(|e| panic!("default.metal compilation failed:\n{}", e));
- let flat_color_lib = device
- .new_library_with_source(&prepare_shader(types_src, include_str!("../../../shaders/metal/flat_color.metal")), &opts)
- .unwrap_or_else(|e| panic!("flat_color.metal compilation failed:\n{}", e));
- let text_lib = device
- .new_library_with_source(&prepare_shader(types_src, include_str!("../../../shaders/metal/text.metal")), &opts)
- .unwrap_or_else(|e| panic!("text.metal compilation failed:\n{}", e));
-
- // Vertex descriptor (shared across all pipelines)
- let vertex_desc = Self::create_vertex_descriptor();
-
- // Create 5 pipelines
- let default_pipeline = Self::create_pipeline(
- &device, &default_lib, vertex_desc, pixel_format, sample_count,
- );
- let flat_no_cull_pipeline = Self::create_pipeline(
- &device, &flat_color_lib, vertex_desc, pixel_format, sample_count,
- );
- let textured_pipeline = Self::create_pipeline(
- &device, &text_lib, vertex_desc, pixel_format, sample_count,
- );
-
- // Depth stencil state
- let depth_desc = DepthStencilDescriptor::new();
- depth_desc.set_depth_compare_function(MTLCompareFunction::Less);
- depth_desc.set_depth_write_enabled(true);
- let depth_stencil_state = device.new_depth_stencil_state(&depth_desc);
-
- // Sampler for text textures
- let sampler_desc = SamplerDescriptor::new();
- sampler_desc.set_address_mode_s(MTLSamplerAddressMode::ClampToEdge);
- sampler_desc.set_address_mode_t(MTLSamplerAddressMode::ClampToEdge);
- sampler_desc.set_mag_filter(MTLSamplerMinMagFilter::Linear);
- sampler_desc.set_min_filter(MTLSamplerMinMagFilter::Linear);
- let sampler_state = device.new_sampler(&sampler_desc);
-
- // NV12 compute pipeline (optional)
- let nv12_size = (width * height * 3 / 2) as usize;
- let (nv12_pipeline, nv12_dims_buffer) = if use_nv12 {
- assert!(width.is_multiple_of(2) && height.is_multiple_of(2), "NV12 requires even width and height");
- let nv12_src = include_str!("../../../shaders/metal/bgra_to_nv12.metal");
- let nv12_lib = device
- .new_library_with_source(nv12_src, &opts)
- .unwrap_or_else(|e| panic!("bgra_to_nv12.metal compilation failed:\n{}", e));
- let nv12_fn = nv12_lib.get_function("bgra_to_nv12", None)
- .expect("bgra_to_nv12 function not found");
- let pipeline = device.new_compute_pipeline_state_with_function(&nv12_fn)
- .unwrap_or_else(|e| panic!("Failed to create NV12 compute pipeline: {}", e));
-
- let dims: [u32; 2] = [width, height];
- let dims_buf = device.new_buffer_with_data(
- dims.as_ptr() as *const c_void,
- std::mem::size_of::<[u32; 2]>() as u64,
- MTLResourceOptions::StorageModeShared,
- );
-
- (Some(pipeline), Some(dims_buf))
- } else {
- (None, None)
- };
-
- // Create N frame slots with buffer-backed textures
- let n = n_buffers.max(1) as usize;
- let max_objects: usize = 512;
- let uniform_buf_size = (max_objects * 256) as u64;
-
- let mut nv12_buffers = Vec::new();
-
- let frame_slots: Vec<FrameSlot> = (0..n)
- .map(|_| {
- // Zero-copy pixel readback: create MTLBuffer, then create MTLTexture
- // backed by that buffer. GPU writes into the texture → pixels land in
- // the buffer's memory. After completion, buffer.contents() is a direct
- // pointer to the pixel data.
- let pixel_buffer = device.new_buffer(
- pixel_size as u64,
- MTLResourceOptions::StorageModeShared,
- );
-
- let tex_desc = TextureDescriptor::new();
- tex_desc.set_pixel_format(pixel_format);
- tex_desc.set_width(width as u64);
- tex_desc.set_height(height as u64);
- tex_desc.set_texture_type(MTLTextureType::D2);
- tex_desc.set_storage_mode(MTLStorageMode::Shared);
- tex_desc.set_usage(MTLTextureUsage::RenderTarget);
-
- let output_texture = pixel_buffer.new_texture_with_descriptor(
- &tex_desc,
- 0, // offset
- bytes_per_row, // bytesPerRow
- );
-
- // NV12 output buffer per slot
- if use_nv12 {
- nv12_buffers.push(device.new_buffer(
- nv12_size as u64,
- MTLResourceOptions::StorageModeShared,
- ));
- }
-
- let msaa_texture = if sample_count > 1 {
- Some(Self::create_msaa_texture(&device, width, height, pixel_format, sample_count))
- } else {
- None
- };
-
- let depth_texture = Self::create_depth_texture(&device, width, height, sample_count);
-
- let camera_buffer = device.new_buffer(
- std::mem::size_of::<CameraUniform>() as u64,
- MTLResourceOptions::StorageModeShared,
- );
-
- let object_buffer = device.new_buffer(
- uniform_buf_size,
- MTLResourceOptions::StorageModeShared,
- );
-
- FrameSlot {
- backing: SlotBacking::Buffer(pixel_buffer),
- output_texture,
- msaa_texture,
- depth_texture,
- camera_buffer,
- object_buffer,
- pending_cmd_buffer: None,
- encoding_done: Arc::new(EncodingSignal::new(true)), // initially "done" (no work pending)
- }
- })
- .collect();
-
- Self {
- device,
- queue,
- default_pipeline,
- flat_no_cull_pipeline,
- textured_pipeline,
- depth_stencil_state,
- sampler_state,
- frame_slots,
- buffer_cache: HashMap::new(),
- texture_cache: HashMap::new(),
- width,
- height,
- pixel_size,
- nv12_pipeline,
- nv12_buffers,
- nv12_dims_buffer,
- nv12_size,
- }
- }
-
- pub fn pixel_size(&self) -> usize {
- self.pixel_size
- }
-
- /// Create a MetalBackend with IOSurface-backed frame slots for VideoToolbox encoding.
- /// Each slot gets its own IOSurface + CVPixelBuffer. No pixel readback needed.
- pub fn new_metal_encoder(width: u32, height: u32, sample_count: u32, n_buffers: u32) -> Self {
- let device = Device::system_default().expect("No Metal device found");
- let queue = device.new_command_queue();
-
- log::info!("Metal native backend (VT encoder): {} ({}x{}, MSAA={})", device.name(), width, height, sample_count);
-
- let pixel_format = MTLPixelFormat::BGRA8Unorm_sRGB;
-
- // Compile MSL shaders
- let types_src = include_str!("../../../shaders/metal/types.h");
- let opts = CompileOptions::new();
-
- let default_lib = device
- .new_library_with_source(&prepare_shader(types_src, include_str!("../../../shaders/metal/default.metal")), &opts)
- .unwrap_or_else(|e| panic!("default.metal compilation failed:\n{}", e));
- let flat_color_lib = device
- .new_library_with_source(&prepare_shader(types_src, include_str!("../../../shaders/metal/flat_color.metal")), &opts)
- .unwrap_or_else(|e| panic!("flat_color.metal compilation failed:\n{}", e));
- let text_lib = device
- .new_library_with_source(&prepare_shader(types_src, include_str!("../../../shaders/metal/text.metal")), &opts)
- .unwrap_or_else(|e| panic!("text.metal compilation failed:\n{}", e));
-
- let vertex_desc = Self::create_vertex_descriptor();
-
- let default_pipeline = Self::create_pipeline(&device, &default_lib, vertex_desc, pixel_format, sample_count);
- let flat_no_cull_pipeline = Self::create_pipeline(&device, &flat_color_lib, vertex_desc, pixel_format, sample_count);
- let textured_pipeline = Self::create_pipeline(&device, &text_lib, vertex_desc, pixel_format, sample_count);
-
- let depth_desc = DepthStencilDescriptor::new();
- depth_desc.set_depth_compare_function(MTLCompareFunction::Less);
- depth_desc.set_depth_write_enabled(true);
- let depth_stencil_state = device.new_depth_stencil_state(&depth_desc);
-
- let sampler_desc = SamplerDescriptor::new();
- sampler_desc.set_address_mode_s(MTLSamplerAddressMode::ClampToEdge);
- sampler_desc.set_address_mode_t(MTLSamplerAddressMode::ClampToEdge);
- sampler_desc.set_mag_filter(MTLSamplerMinMagFilter::Linear);
- sampler_desc.set_min_filter(MTLSamplerMinMagFilter::Linear);
- let sampler_state = device.new_sampler(&sampler_desc);
-
- let n = n_buffers.max(1) as usize;
- let max_objects: usize = 512;
- let uniform_buf_size = (max_objects * 256) as u64;
-
- let frame_slots: Vec<FrameSlot> = (0..n)
- .map(|_| {
- // Create IOSurface → IOSurface-backed MTLTexture → CVPixelBuffer
- let surface = crate::metal_encoder::create_iosurface(width, height);
- let cv_pixel_buffer = crate::metal_encoder::create_cv_pixel_buffer(surface, width, height);
-
- // Create MTLTextureDescriptor for IOSurface-backed texture
- let tex_desc = TextureDescriptor::new();
- tex_desc.set_pixel_format(pixel_format);
- tex_desc.set_width(width as u64);
- tex_desc.set_height(height as u64);
- tex_desc.set_texture_type(MTLTextureType::D2);
- tex_desc.set_storage_mode(MTLStorageMode::Shared);
- tex_desc.set_usage(MTLTextureUsage::RenderTarget);
-
- // Create Metal texture backed by IOSurface via objc runtime
- let output_texture = unsafe {
- let raw_texture: *mut Object = objc::msg_send![
- device.as_ptr() as *mut Object,
- newTextureWithDescriptor: tex_desc.as_ptr() as *mut Object
- iosurface: surface as *mut Object
- plane: 0usize
- ];
- assert!(!raw_texture.is_null(), "Failed to create IOSurface-backed Metal texture");
- Texture::from_ptr(raw_texture as *mut MTLTexture)
- };
-
- let msaa_texture = if sample_count > 1 {
- Some(Self::create_msaa_texture(&device, width, height, pixel_format, sample_count))
- } else {
- None
- };
-
- let depth_texture = Self::create_depth_texture(&device, width, height, sample_count);
-
- let camera_buffer = device.new_buffer(
- std::mem::size_of::<CameraUniform>() as u64,
- MTLResourceOptions::StorageModeShared,
- );
-
- let object_buffer = device.new_buffer(
- uniform_buf_size,
- MTLResourceOptions::StorageModeShared,
- );
-
- FrameSlot {
- backing: SlotBacking::IOSurface { surface, cv_pixel_buffer },
- output_texture,
- msaa_texture,
- depth_texture,
- camera_buffer,
- object_buffer,
- pending_cmd_buffer: None,
- encoding_done: Arc::new(EncodingSignal::new(true)),
- }
- })
- .collect();
-
- Self {
- device,
- queue,
- default_pipeline,
- flat_no_cull_pipeline,
- textured_pipeline,
- depth_stencil_state,
- sampler_state,
- frame_slots,
- buffer_cache: HashMap::new(),
- texture_cache: HashMap::new(),
- width,
- height,
- pixel_size: 0, // not used for IOSurface path
- nv12_pipeline: None,
- nv12_buffers: Vec::new(),
- nv12_dims_buffer: None,
- nv12_size: 0,
- }
- }
-
- // ── Texture creation helpers ──
-
- fn create_msaa_texture(device: &Device, width: u32, height: u32, format: MTLPixelFormat, sample_count: u32) -> Texture {
- let desc = TextureDescriptor::new();
- desc.set_pixel_format(format);
- desc.set_width(width as u64);
- desc.set_height(height as u64);
- desc.set_sample_count(sample_count as u64);
- desc.set_texture_type(MTLTextureType::D2Multisample);
- desc.set_storage_mode(MTLStorageMode::Private);
- desc.set_usage(MTLTextureUsage::RenderTarget);
- device.new_texture(&desc)
- }
-
- fn create_depth_texture(device: &Device, width: u32, height: u32, sample_count: u32) -> Texture {
- let desc = TextureDescriptor::new();
- desc.set_pixel_format(MTLPixelFormat::Depth32Float);
- desc.set_width(width as u64);
- desc.set_height(height as u64);
- desc.set_storage_mode(MTLStorageMode::Private);
- desc.set_usage(MTLTextureUsage::RenderTarget);
- if sample_count > 1 {
- desc.set_sample_count(sample_count as u64);
- desc.set_texture_type(MTLTextureType::D2Multisample);
- } else {
- desc.set_texture_type(MTLTextureType::D2);
- }
- device.new_texture(&desc)
- }
-
- // ── Pipeline creation ──
-
- fn create_vertex_descriptor() -> &'static VertexDescriptorRef {
- let desc = VertexDescriptor::new();
-
- // attribute(0): position — float3 at offset 0
- let attr0 = desc.attributes().object_at(0).unwrap();
- attr0.set_format(MTLVertexFormat::Float3);
- attr0.set_offset(0);
- attr0.set_buffer_index(0);
-
- // attribute(1): normal — float3 at offset 12
- let attr1 = desc.attributes().object_at(1).unwrap();
- attr1.set_format(MTLVertexFormat::Float3);
- attr1.set_offset(12);
- attr1.set_buffer_index(0);
-
- // attribute(2): color — float4 at offset 24
- let attr2 = desc.attributes().object_at(2).unwrap();
- attr2.set_format(MTLVertexFormat::Float4);
- attr2.set_offset(24);
- attr2.set_buffer_index(0);
-
- // layout(0): stride=40, per-vertex
- let layout0 = desc.layouts().object_at(0).unwrap();
- layout0.set_stride(40);
- layout0.set_step_function(MTLVertexStepFunction::PerVertex);
-
- desc
- }
-
- fn create_pipeline(
- device: &Device,
- library: &Library,
- vertex_desc: &VertexDescriptorRef,
- color_format: MTLPixelFormat,
- sample_count: u32,
- ) -> RenderPipelineState {
- let vertex_fn = library.get_function("vs_main", None)
- .expect("vs_main function not found in MSL library");
- let fragment_fn = library.get_function("fs_main", None)
- .expect("fs_main function not found in MSL library");
-
- let pipe_desc = RenderPipelineDescriptor::new();
- pipe_desc.set_vertex_function(Some(&vertex_fn));
- pipe_desc.set_fragment_function(Some(&fragment_fn));
- pipe_desc.set_vertex_descriptor(Some(vertex_desc));
- pipe_desc.set_sample_count(sample_count as u64);
- pipe_desc.set_depth_attachment_pixel_format(MTLPixelFormat::Depth32Float);
-
- // Color attachment with alpha blending (matches wgpu's ALPHA_BLENDING)
- let color_att = pipe_desc.color_attachments().object_at(0).unwrap();
- color_att.set_pixel_format(color_format);
- color_att.set_blending_enabled(true);
- color_att.set_source_rgb_blend_factor(MTLBlendFactor::SourceAlpha);
- color_att.set_destination_rgb_blend_factor(MTLBlendFactor::OneMinusSourceAlpha);
- color_att.set_source_alpha_blend_factor(MTLBlendFactor::SourceAlpha);
- color_att.set_destination_alpha_blend_factor(MTLBlendFactor::OneMinusSourceAlpha);
- color_att.set_rgb_blend_operation(MTLBlendOperation::Add);
- color_att.set_alpha_blend_operation(MTLBlendOperation::Add);
-
- device.new_render_pipeline_state(&pipe_desc)
- .unwrap_or_else(|e| panic!("Failed to create Metal render pipeline: {}", e))
- }
-
- // ── Buffer caching ──
-
- fn get_or_cache_buffers(&mut self, obj_id: ObjectId, vertices: &[Vertex], indices: &[u32]) -> &CachedMetalBuffers {
- self.buffer_cache.entry(obj_id).or_insert_with(|| {
- let vertex_data = bytemuck::cast_slice::<Vertex, u8>(vertices);
- let index_data = bytemuck::cast_slice::<u32, u8>(indices);
-
- let vertex_buffer = self.device.new_buffer_with_data(
- vertex_data.as_ptr() as *const c_void,
- vertex_data.len() as u64,
- MTLResourceOptions::StorageModeShared,
- );
- let index_buffer = self.device.new_buffer_with_data(
- index_data.as_ptr() as *const c_void,
- index_data.len() as u64,
- MTLResourceOptions::StorageModeShared,
- );
-
- CachedMetalBuffers {
- vertex_buffer,
- index_buffer,
- index_count: indices.len() as u32,
- }
- })
- }
-
- fn get_or_cache_texture(&mut self, obj_id: ObjectId, texture_data: &TextureData) -> &CachedMetalTexture {
- self.texture_cache.entry(obj_id).or_insert_with(|| {
- let desc = TextureDescriptor::new();
- desc.set_pixel_format(MTLPixelFormat::RGBA8Unorm_sRGB);
- desc.set_width(texture_data.width as u64);
- desc.set_height(texture_data.height as u64);
- desc.set_storage_mode(MTLStorageMode::Shared);
- desc.set_usage(MTLTextureUsage::ShaderRead);
- desc.set_texture_type(MTLTextureType::D2);
-
- let texture = self.device.new_texture(&desc);
-
- let region = MTLRegion::new_2d(0, 0, texture_data.width as u64, texture_data.height as u64);
- texture.replace_region(
- region,
- 0, // mipmap level
- texture_data.rgba.as_ptr() as *const c_void,
- (4 * texture_data.width) as u64, // bytes per row
- );
-
- CachedMetalTexture { texture }
- })
- }
-
- // ── Render a single frame into a slot ──
-
- /// Build clear color from scene background (sRGB → linear for sRGB framebuffer).
- pub fn clear_color(scene: &Scene) -> MTLClearColor {
- MTLClearColor {
- red: srgb_to_linear(scene.background[0]) as f64,
- green: srgb_to_linear(scene.background[1]) as f64,
- blue: srgb_to_linear(scene.background[2]) as f64,
- alpha: scene.background[3] as f64,
- }
- }
-
- /// Get the encoding_done signal for a slot (used by render_loop for synchronization).
- pub fn slot_encoding_done(&self, slot_idx: usize) -> &Arc<EncodingSignal> {
- &self.frame_slots[slot_idx].encoding_done
- }
-
- /// Wait until the encoding thread has finished reading from this slot's pixel buffer.
- /// Must be called before submitting new GPU work to this slot.
- pub fn wait_encoding_done(&self, slot_idx: usize) {
- self.frame_slots[slot_idx].encoding_done.wait_done();
- }
-
- /// Encode and submit a render pass for one frame. Does NOT wait for completion.
- /// NV12 compute writes to self.nv12_buffers[slot_idx] (per-slot buffer).
- pub fn submit_frame(
- &mut self,
- scene: &Scene,
- cam_bytes: &[u8],
- uniform_staging: &[u8],
- total_uniform_bytes: usize,
- draw_cmds: &[(usize, usize)],
- clear_color: MTLClearColor,
- slot_idx: usize,
- ) {
- self.submit_frame_impl(scene, cam_bytes, uniform_staging, total_uniform_bytes, draw_cmds, clear_color, slot_idx, None);
- }
-
- /// Like submit_frame, but NV12 compute writes to an external pool buffer instead.
- pub fn submit_frame_nv12(
- &mut self,
- scene: &Scene,
- cam_bytes: &[u8],
- uniform_staging: &[u8],
- total_uniform_bytes: usize,
- draw_cmds: &[(usize, usize)],
- clear_color: MTLClearColor,
- slot_idx: usize,
- nv12_target: &Buffer,
- ) {
- self.submit_frame_impl(scene, cam_bytes, uniform_staging, total_uniform_bytes, draw_cmds, clear_color, slot_idx, Some(nv12_target));
- }
-
- fn submit_frame_impl(
- &mut self,
- scene: &Scene,
- cam_bytes: &[u8],
- uniform_staging: &[u8],
- total_uniform_bytes: usize,
- draw_cmds: &[(usize, usize)], // (obj_idx, uniform_slot)
- clear_color: MTLClearColor,
- slot_idx: usize,
- nv12_override: Option<&Buffer>,
- ) {
- let slot = &self.frame_slots[slot_idx];
-
- // Write camera uniform via direct memcpy
- unsafe {
- let dst = slot.camera_buffer.contents() as *mut u8;
- std::ptr::copy_nonoverlapping(cam_bytes.as_ptr(), dst, cam_bytes.len());
- }
-
- // Write object uniforms
- if total_uniform_bytes > 0 {
- unsafe {
- let dst = slot.object_buffer.contents() as *mut u8;
- std::ptr::copy_nonoverlapping(
- uniform_staging.as_ptr(),
- dst,
- total_uniform_bytes,
- );
- }
- }
-
- // Pre-cache textures (must happen before encoding)
- for &(obj_idx, _) in draw_cmds {
- let obj = &scene.objects[obj_idx];
- if let RenderHint::Textured = &obj.render_hint {
- if let Some(ref tex_data) = obj.texture_data {
- self.get_or_cache_texture(obj.id, tex_data);
- }
- }
- }
-
- // Pre-cache geometry
- for &(obj_idx, _) in draw_cmds {
- let obj = &scene.objects[obj_idx];
- self.get_or_cache_buffers(obj.id, &obj.vertices, &obj.indices);
- }
-
- let cmd_buf = self.queue.new_command_buffer();
-
- // Configure render pass descriptor
- let pass_desc = RenderPassDescriptor::new();
-
- // Color attachment
- let color_att = pass_desc.color_attachments().object_at(0).unwrap();
- if let Some(ref msaa_tex) = self.frame_slots[slot_idx].msaa_texture {
- color_att.set_texture(Some(msaa_tex));
- color_att.set_resolve_texture(Some(&self.frame_slots[slot_idx].output_texture));
- color_att.set_store_action(MTLStoreAction::MultisampleResolve);
- } else {
- color_att.set_texture(Some(&self.frame_slots[slot_idx].output_texture));
- color_att.set_store_action(MTLStoreAction::Store);
- }
- color_att.set_load_action(MTLLoadAction::Clear);
- color_att.set_clear_color(clear_color);
-
- // Depth attachment
- let depth_att = pass_desc.depth_attachment().unwrap();
- depth_att.set_texture(Some(&self.frame_slots[slot_idx].depth_texture));
- depth_att.set_load_action(MTLLoadAction::Clear);
- depth_att.set_clear_depth(1.0);
- depth_att.set_store_action(MTLStoreAction::DontCare);
-
- let encoder = cmd_buf.new_render_command_encoder(pass_desc);
-
- // Set viewport
- encoder.set_viewport(MTLViewport {
- originX: 0.0,
- originY: 0.0,
- width: self.width as f64,
- height: self.height as f64,
- znear: 0.0,
- zfar: 1.0,
- });
-
- // Set depth stencil state
- encoder.set_depth_stencil_state(&self.depth_stencil_state);
-
- // Set front face winding (CCW, matching wgpu)
- encoder.set_front_facing_winding(MTLWinding::CounterClockwise);
-
- // Draw each object
- let slot = &self.frame_slots[slot_idx];
- let uniform_alignment: usize = 256;
-
- for &(obj_idx, uniform_slot) in draw_cmds {
- let obj = &scene.objects[obj_idx];
- let is_textured = matches!(&obj.render_hint, RenderHint::Textured);
-
- // Select pipeline and cull mode based on render hint
- let (pipeline, cull_mode) = match &obj.render_hint {
- RenderHint::Default => (&self.default_pipeline, MTLCullMode::None),
- RenderHint::FlatUnlit => (&self.flat_no_cull_pipeline, MTLCullMode::None),
- RenderHint::Textured => (&self.textured_pipeline, MTLCullMode::None),
- };
-
- encoder.set_render_pipeline_state(pipeline);
- encoder.set_cull_mode(cull_mode);
-
- let cached = self.buffer_cache.get(&obj.id).unwrap();
- let obj_offset = (uniform_slot * uniform_alignment) as u64;
-
- // Buffer index 0: vertex data
- encoder.set_vertex_buffer(0, Some(&cached.vertex_buffer), 0);
- // Buffer index 1: camera uniform (vertex shader only)
- encoder.set_vertex_buffer(1, Some(&slot.camera_buffer), 0);
- // Buffer index 2: object uniform (vertex AND fragment)
- encoder.set_vertex_buffer(2, Some(&slot.object_buffer), obj_offset);
- encoder.set_fragment_buffer(2, Some(&slot.object_buffer), obj_offset);
-
- // Texture binding for text objects
- if is_textured {
- if let Some(tex_cached) = self.texture_cache.get(&obj.id) {
- encoder.set_fragment_texture(0, Some(&tex_cached.texture));
- encoder.set_fragment_sampler_state(0, Some(&self.sampler_state));
- }
- }
-
- // Draw indexed primitives
- encoder.draw_indexed_primitives(
- MTLPrimitiveType::Triangle,
- cached.index_count as u64,
- MTLIndexType::UInt32,
- &cached.index_buffer,
- 0,
- );
- }
-
- encoder.end_encoding();
-
- // NV12 compute pass: convert BGRA → NV12 on the same command buffer
- if let Some(ref nv12_pipeline) = self.nv12_pipeline {
- let pixel_buf = match &self.frame_slots[slot_idx].backing {
- SlotBacking::Buffer(buf) => buf,
- _ => panic!("NV12 compute requires Buffer-backed slot"),
- };
- let nv12_buf = nv12_override.unwrap_or(&self.nv12_buffers[slot_idx]);
- let dims_buf = self.nv12_dims_buffer.as_ref().unwrap();
-
- let compute_enc = cmd_buf.new_compute_command_encoder();
- compute_enc.set_compute_pipeline_state(nv12_pipeline);
- compute_enc.set_buffer(0, Some(pixel_buf), 0);
- compute_enc.set_buffer(1, Some(nv12_buf), 0);
- compute_enc.set_buffer(2, Some(dims_buf), 0);
-
- // Each thread processes a 4×2 pixel block, threadgroup is 8×8 threads (32×16 pixels)
- let threadgroup_size = MTLSize::new(8, 8, 1);
- let grid_w = (self.width as u64).div_ceil(4); // ceil(width / 4)
- let grid_h = (self.height as u64).div_ceil(2); // ceil(height / 2)
- compute_enc.dispatch_thread_groups(
- MTLSize::new(
- grid_w.div_ceil(8), // ceil(grid_w / threadgroup_w)
- grid_h.div_ceil(8), // ceil(grid_h / threadgroup_h)
- 1,
- ),
- threadgroup_size,
- );
- compute_enc.end_encoding();
- }
-
- cmd_buf.commit();
-
- // Retain the command buffer so we can wait on it later
- let raw_ptr = cmd_buf.as_ptr() as *mut c_void;
- unsafe {
- let _: *mut Object = objc::msg_send![raw_ptr as *mut Object, retain];
- }
- self.frame_slots[slot_idx].pending_cmd_buffer = Some(raw_ptr);
- }
-
- /// Wait for a slot's command buffer to complete, then return a direct pointer
- /// to the pixel data in the buffer-backed texture's MTLBuffer.
- ///
- /// ZERO COPY: The returned pointer points directly into the MTLBuffer's shared
- /// memory. The GPU wrote pixels there during the render pass resolve. No getBytes,
- /// no staging buffer, no memcpy. The pointer is valid until the next GPU submission
- /// to this slot.
- ///
- /// The caller MUST call `mark_encoding_start` before passing this pointer to
- /// the encoding thread, and the encoding thread MUST set `encoding_done` when
- /// finished reading. The main thread will spin on `wait_encoding_done` before
- /// reusing this slot.
- pub fn drain_slot(&mut self, slot_idx: usize) -> *const u8 {
- let slot = &mut self.frame_slots[slot_idx];
-
- if let Some(raw_ptr) = slot.pending_cmd_buffer.take() {
- unsafe {
- // Wait for GPU completion
- let _: () = objc::msg_send![raw_ptr as *mut Object, waitUntilCompleted];
- // Release the retained command buffer
- let _: () = objc::msg_send![raw_ptr as *mut Object, release];
- }
- }
-
- // Return direct pointer to pixel data in the buffer-backed texture's backing store
- match &slot.backing {
- SlotBacking::Buffer(buf) => buf.contents() as *const u8,
- SlotBacking::IOSurface { .. } => panic!("drain_slot called on IOSurface-backed slot; use drain_slot_metal"),
- }
- }
-
- /// Wait for GPU completion on an IOSurface-backed slot. No pixel readback —
- /// the IOSurface already has the data for VideoToolbox to read.
- pub fn drain_slot_metal(&mut self, slot_idx: usize) {
- let slot = &mut self.frame_slots[slot_idx];
-
- if let Some(raw_ptr) = slot.pending_cmd_buffer.take() {
- unsafe {
- let _: () = objc::msg_send![raw_ptr as *mut Object, waitUntilCompleted];
- let _: () = objc::msg_send![raw_ptr as *mut Object, release];
- }
- }
- }
-
- /// Wait for GPU completion on an IOSurface-backed slot and return GPU timing.
- /// Used by the profiling render loop.
- pub fn drain_slot_metal_timed(&mut self, slot_idx: usize) -> f64 {
- let slot = &mut self.frame_slots[slot_idx];
- let mut gpu_duration = 0.0;
-
- if let Some(raw_ptr) = slot.pending_cmd_buffer.take() {
- unsafe {
- let _: () = objc::msg_send![raw_ptr as *mut Object, waitUntilCompleted];
-
- let gpu_start: f64 = objc::msg_send![raw_ptr as *mut Object, GPUStartTime];
- let gpu_end: f64 = objc::msg_send![raw_ptr as *mut Object, GPUEndTime];
- if gpu_end > gpu_start {
- gpu_duration = gpu_end - gpu_start;
- }
-
- let _: () = objc::msg_send![raw_ptr as *mut Object, release];
- }
- }
-
- gpu_duration
- }
-
- /// Get the CVPixelBuffer for a slot (IOSurface-backed slots only).
- pub fn slot_cv_pixel_buffer(&self, slot_idx: usize) -> crate::metal_encoder::CVPixelBufferRef {
- match &self.frame_slots[slot_idx].backing {
- SlotBacking::IOSurface { cv_pixel_buffer, .. } => *cv_pixel_buffer,
- SlotBacking::Buffer(_) => panic!("slot_cv_pixel_buffer called on Buffer-backed slot"),
- }
- }
-
- /// Mark that the encoding thread is about to start reading from this slot's pixel buffer.
- pub fn mark_encoding_start(&self, slot_idx: usize) {
- self.frame_slots[slot_idx].encoding_done.reset();
- }
-
- /// Wait for a slot's command buffer to complete, then return a direct pointer
- /// to the pixel data AND the GPU execution time in seconds.
- ///
- /// Same as `drain_slot` but reads `MTLCommandBuffer.GPUStartTime/GPUEndTime`
- /// before releasing the command buffer. Used by the profiling render loop.
- pub fn drain_slot_timed(&mut self, slot_idx: usize) -> (*const u8, f64) {
- let slot = &mut self.frame_slots[slot_idx];
- let mut gpu_duration = 0.0;
-
- if let Some(raw_ptr) = slot.pending_cmd_buffer.take() {
- unsafe {
- let _: () = objc::msg_send![raw_ptr as *mut Object, waitUntilCompleted];
-
- // Read GPU timing from completed command buffer
- let gpu_start: f64 = objc::msg_send![raw_ptr as *mut Object, GPUStartTime];
- let gpu_end: f64 = objc::msg_send![raw_ptr as *mut Object, GPUEndTime];
- if gpu_end > gpu_start {
- gpu_duration = gpu_end - gpu_start;
- }
-
- let _: () = objc::msg_send![raw_ptr as *mut Object, release];
- }
- }
-
- match &slot.backing {
- SlotBacking::Buffer(buf) => (buf.contents() as *const u8, gpu_duration),
- SlotBacking::IOSurface { .. } => panic!("drain_slot_timed called on IOSurface-backed slot"),
- }
- }
-
- /// Wait for GPU completion, then return pointer to the NV12 buffer for this slot.
- pub fn drain_slot_nv12(&mut self, slot_idx: usize) -> *const u8 {
- let slot = &mut self.frame_slots[slot_idx];
-
- if let Some(raw_ptr) = slot.pending_cmd_buffer.take() {
- unsafe {
- let _: () = objc::msg_send![raw_ptr as *mut Object, waitUntilCompleted];
- let _: () = objc::msg_send![raw_ptr as *mut Object, release];
- }
- }
-
- self.nv12_buffers[slot_idx].contents() as *const u8
- }
-
- /// Wait for GPU completion, return NV12 buffer pointer + GPU timing.
- pub fn drain_slot_nv12_timed(&mut self, slot_idx: usize) -> (*const u8, f64) {
- let slot = &mut self.frame_slots[slot_idx];
- let mut gpu_duration = 0.0;
-
- if let Some(raw_ptr) = slot.pending_cmd_buffer.take() {
- unsafe {
- let _: () = objc::msg_send![raw_ptr as *mut Object, waitUntilCompleted];
-
- let gpu_start: f64 = objc::msg_send![raw_ptr as *mut Object, GPUStartTime];
- let gpu_end: f64 = objc::msg_send![raw_ptr as *mut Object, GPUEndTime];
- if gpu_end > gpu_start {
- gpu_duration = gpu_end - gpu_start;
- }
-
- let _: () = objc::msg_send![raw_ptr as *mut Object, release];
- }
- }
-
- (self.nv12_buffers[slot_idx].contents() as *const u8, gpu_duration)
- }
-
- /// NV12 frame size in bytes (W*H*3/2). Zero if NV12 not enabled.
- pub fn nv12_size(&self) -> usize {
- self.nv12_size
- }
-
- /// Whether NV12 compute conversion is enabled.
- pub fn has_nv12(&self) -> bool {
- self.nv12_pipeline.is_some()
- }
-
- /// Create standalone NV12 MTLBuffers for the elastic pool (not tied to frame slots).
- pub fn create_nv12_buffers(&self, count: usize) -> Vec<Buffer> {
- (0..count).map(|_| {
- self.device.new_buffer(self.nv12_size as u64, MTLResourceOptions::StorageModeShared)
- }).collect()
- }
-
- /// Number of frame slots.
- pub fn n_slots(&self) -> usize {
- self.frame_slots.len()
- }
-}
diff --git a/rust/bridge/crates/manimgx-metal/src/lib.rs b/rust/bridge/crates/manimgx-metal/src/lib.rs
deleted file mode 100644
index 07c7c8d6..00000000
--- a/rust/bridge/crates/manimgx-metal/src/lib.rs
+++ /dev/null
@@ -1,19 +0,0 @@
-#![cfg(target_os = "macos")]
-
-mod backend;
-pub(crate) mod metal_encoder;
-
-#[cfg(not(feature = "time_profile"))]
-mod render_loop_x264;
-#[cfg(feature = "time_profile")]
-#[path = "render_loop_x264_profile.rs"]
-mod render_loop_x264;
-#[cfg(not(feature = "time_profile"))]
-mod render_loop_metal;
-#[cfg(feature = "time_profile")]
-#[path = "render_loop_metal_profile.rs"]
-mod render_loop_metal;
-
-pub use backend::MetalBackend;
-pub use render_loop_metal::render_video_metal;
-pub use render_loop_x264::render_video_x264;
diff --git a/rust/bridge/crates/manimgx-metal/src/render_loop_metal.rs b/rust/bridge/crates/manimgx-metal/src/render_loop_metal.rs
deleted file mode 100644
index 88edfe3b..00000000
--- a/rust/bridge/crates/manimgx-metal/src/render_loop_metal.rs
+++ /dev/null
@@ -1,217 +0,0 @@
-use manimgx_core::scene::Scene;
-use manimgx_core::timeline_eval::TimelineEval;
-
-use manimgx_core::uniform::{CameraUniform, ObjectUniform};
-use crate::backend::MetalBackend;
-use crate::metal_encoder::MetalEncoder;
-
-/// Render a video using the native Metal backend with VideoToolbox encoding.
-///
-/// Zero-copy path: GPU renders into IOSurface-backed textures, VideoToolbox
-/// reads the same IOSurface memory for hardware H.264 encoding. No pixel
-/// readback, no ffmpeg, no CPU copies.
-pub fn render_video_metal(
- scene: &mut Scene,
- timeline: &dyn TimelineEval,
- output: &str,
- total_frames: u32,
- fps: u32,
- sample_count: u32,
- n_buffers: u32,
- check_cancelled: &dyn Fn() -> bool,
-) {
- if total_frames == 0 {
- return;
- }
-
- let width = scene.width;
- let height = scene.height;
- let n = n_buffers.max(1) as usize;
-
- // Create Metal backend with IOSurface-backed frame slots
- let mut backend = MetalBackend::new_metal_encoder(width, height, sample_count, n_buffers);
-
- // Create VideoToolbox encoder
- let mut encoder = MetalEncoder::new(output, width, height, fps);
-
- // Uniform staging
- let uniform_alignment: usize = 256;
- let max_objects = scene.objects.len().max(1);
- let uniform_size = std::mem::size_of::<ObjectUniform>();
- let cam_size = std::mem::size_of::<CameraUniform>();
- let mut uniform_staging = vec![0u8; max_objects * uniform_alignment];
-
- // Frame dedup state
- let mut prev_cam_bytes = vec![0u8; cam_size];
- let mut prev_uniform_bytes = vec![0u8; uniform_staging.len()];
- let mut prev_draw_count: usize = 0;
- let mut first_frame = true;
- let mut dup_count = 0u32;
- let mut render_count = 0usize;
-
- // Track last rendered slot for dup frame re-encoding
- let mut last_rendered_slot: usize = 0;
-
- // N-buffering: pending slot queue
- let mut pending: std::collections::VecDeque<usize> = std::collections::VecDeque::new();
-
- let clear_color = MetalBackend::clear_color(scene);
- let render_start = std::time::Instant::now();
- let mut last_progress = std::time::Instant::now();
-
- let mut draw_cmds: Vec<(usize, usize)> = Vec::with_capacity(scene.objects.len());
-
- for frame_idx in 0..total_frames {
- // Progress bar
- print_progress(frame_idx, total_frames, &render_start, &mut last_progress);
- if check_cancelled() { eprintln!("\n Render interrupted at frame {}/{}", frame_idx, total_frames); break; }
-
- let time = frame_idx as f32 / fps as f32;
- timeline.evaluate(scene, time);
-
- // Build camera uniform
- let view_proj = scene.camera.view_projection_matrix(scene.aspect_ratio());
- let cam_uniform = CameraUniform {
- view_proj: view_proj.to_cols_array_2d(),
- };
- let cam_bytes = bytemuck::bytes_of(&cam_uniform);
-
- // Build draw commands + object uniforms
- draw_cmds.clear();
- for (obj_idx, obj) in scene.objects.iter().enumerate() {
- if obj.material.opacity <= 0.0 {
- continue;
- }
- let slot = draw_cmds.len();
- let byte_offset = slot * uniform_alignment;
-
- if byte_offset + uniform_size > uniform_staging.len() {
- let new_len = (byte_offset + uniform_size).next_power_of_two();
- uniform_staging.resize(new_len, 0);
- prev_uniform_bytes.resize(new_len, 0);
- }
-
- let mut material_color = obj.material.color;
- material_color[3] = obj.material.color[3] * obj.material.opacity;
-
- let uniform = ObjectUniform {
- model: obj.transform.to_matrix().to_cols_array_2d(),
- material_color,
- use_vertex_colors: if obj.material.use_vertex_colors { 1 } else { 0 },
- _pad: [0; 3],
- };
- uniform_staging[byte_offset..byte_offset + uniform_size]
- .copy_from_slice(bytemuck::bytes_of(&uniform));
- draw_cmds.push((obj_idx, slot));
- }
-
- let total_uniform_bytes = draw_cmds.len() * uniform_alignment;
-
- // Frame deduplication
- let is_dup = !first_frame
- && draw_cmds.len() == prev_draw_count
- && cam_bytes == &prev_cam_bytes[..]
- && (total_uniform_bytes == 0
- || uniform_staging[..total_uniform_bytes]
- == prev_uniform_bytes[..total_uniform_bytes]);
-
- if is_dup {
- // Drain any pending GPU slots before encoding dup
- while let Some(drain_idx) = pending.pop_front() {
- backend.drain_slot_metal(drain_idx);
- encoder.encode_frame(backend.slot_cv_pixel_buffer(drain_idx));
- last_rendered_slot = drain_idx;
- }
- // Re-encode from last rendered slot's IOSurface (still has the data)
- encoder.encode_frame(backend.slot_cv_pixel_buffer(last_rendered_slot));
- dup_count += 1;
- continue;
- }
-
- let slot_idx = render_count % n;
-
- // Drain oldest pending slot if all slots are in use
- if pending.len() >= n {
- let drain_idx = pending.pop_front().unwrap();
- backend.drain_slot_metal(drain_idx);
- encoder.encode_frame(backend.slot_cv_pixel_buffer(drain_idx));
- last_rendered_slot = drain_idx;
- }
-
- // Submit this frame's render work
- backend.submit_frame(
- scene,
- cam_bytes,
- &uniform_staging,
- total_uniform_bytes,
- &draw_cmds,
- clear_color,
- slot_idx,
- );
- pending.push_back(slot_idx);
-
- // Update dedup state
- prev_cam_bytes.copy_from_slice(cam_bytes);
- if total_uniform_bytes > 0 {
- prev_uniform_bytes[..total_uniform_bytes]
- .copy_from_slice(&uniform_staging[..total_uniform_bytes]);
- }
- prev_draw_count = draw_cmds.len();
- first_frame = false;
- render_count += 1;
- }
-
- // Drain remaining pending slots
- while let Some(drain_idx) = pending.pop_front() {
- backend.drain_slot_metal(drain_idx);
- encoder.encode_frame(backend.slot_cv_pixel_buffer(drain_idx));
- }
-
- encoder.finish();
-
- eprintln!();
- let rendered = total_frames - dup_count;
- eprintln!(
- " frames: {} rendered, {} duplicates skipped ({:.0}%)",
- rendered,
- dup_count,
- dup_count as f64 / total_frames as f64 * 100.0,
- );
-}
-
-fn print_progress(
- frame_idx: u32,
- total_frames: u32,
- render_start: &std::time::Instant,
- last_progress: &mut std::time::Instant,
-) {
- if last_progress.elapsed().as_millis() >= 250 || frame_idx == total_frames - 1 {
- let done = frame_idx + 1;
- let elapsed = render_start.elapsed().as_secs_f64();
- let pct = done as f64 / total_frames as f64;
- let fps_now = if elapsed > 0.0 {
- done as f64 / elapsed
- } else {
- 0.0
- };
- let eta = if pct > 0.0 {
- elapsed / pct - elapsed
- } else {
- 0.0
- };
- let bar_width = 30;
- let filled = (pct * bar_width as f64) as usize;
- let bar: String = "█".repeat(filled) + &"░".repeat(bar_width - filled);
- eprint!(
- "\r [{}] {:>3.0}% | {}/{} | {:.1}s | ~{:.1}s left | {:.0} fps\x1b[K",
- bar,
- pct * 100.0,
- done,
- total_frames,
- elapsed,
- eta,
- fps_now,
- );
- *last_progress = std::time::Instant::now();
- }
-}
diff --git a/rust/bridge/crates/manimgx-py/Cargo.toml b/rust/bridge/crates/manimgx-py/Cargo.toml
deleted file mode 100644
index c4612abb..00000000
--- a/rust/bridge/crates/manimgx-py/Cargo.toml
+++ /dev/null
@@ -1,19 +0,0 @@
-[package]
-name = "manimgx-py"
-version = "0.1.0"
-edition = "2021"
-
-[lib]
-name = "manimgx"
-crate-type = ["cdylib"]
-
-[dependencies]
-manimgx-core = { path = "../manimgx-core" }
-manimgx-render = { path = "../manimgx-render" }
-manimgx-metal = { path = "../manimgx-metal" }
-pyo3 = { version = "0.28", features = ["extension-module"] }
-glam = { workspace = true }
-log = { workspace = true }
-
-[features]
-time_profile = ["manimgx-render/time_profile", "manimgx-metal/time_profile"]
diff --git a/rust/bridge/crates/manimgx-py/src/lib.rs b/rust/bridge/crates/manimgx-py/src/lib.rs
deleted file mode 100644
index 95e7bc6d..00000000
--- a/rust/bridge/crates/manimgx-py/src/lib.rs
+++ /dev/null
@@ -1,46 +0,0 @@
-use pyo3::prelude::*;
-
-mod py_camera;
-mod py_objects;
-mod py_scene;
-
-#[pymodule]
-fn manimgx(m: &Bound<'_, PyModule>) -> PyResult<()> {
- // Scene
- m.add_class::<py_scene::PyScene>()?;
- // Cameras
- m.add_class::<py_camera::PyPerspectiveCamera>()?;
- m.add_class::<py_camera::PyObliqueCamera>()?;
- // 3D primitives
- m.add_class::<py_objects::PyCube>()?;
- m.add_class::<py_objects::PyBox3D>()?;
- m.add_class::<py_objects::PySphere>()?;
- m.add_class::<py_objects::PyCylinder>()?;
- m.add_class::<py_objects::PyPlane>()?;
- m.add_class::<py_objects::PyBezierCurve>()?;
- m.add_class::<py_objects::PyParametricSurface>()?;
- // 2D primitives
- m.add_class::<py_objects::PyPolygon>()?;
- m.add_class::<py_objects::PyPolygram>()?;
- m.add_class::<py_objects::PyTriangle>()?;
- m.add_class::<py_objects::PyCircle>()?;
- m.add_class::<py_objects::PyRectangle>()?;
- m.add_class::<py_objects::PyLine>()?;
- m.add_class::<py_objects::PyArc>()?;
- m.add_class::<py_objects::PyArrow>()?;
- m.add_class::<py_objects::PyDot>()?;
- // 2D graph primitives
- m.add_class::<py_objects::PyNumberLine>()?;
- m.add_class::<py_objects::PyAxes>()?;
- m.add_class::<py_objects::PyGrid>()?;
- m.add_class::<py_objects::PyFunctionPlot>()?;
- // New 2D primitives
- m.add_class::<py_objects::PyCurvedArrow>()?;
- m.add_class::<py_objects::PyDashedLine>()?;
- m.add_class::<py_objects::PyBrace>()?;
- m.add_class::<py_objects::PyFilledRegion>()?;
- m.add_class::<py_objects::PyRiemannRects>()?;
- // Text
- m.add_class::<py_objects::PyText>()?;
- Ok(())
-}
diff --git a/rust/bridge/crates/manimgx-py/src/py_camera.rs b/rust/bridge/crates/manimgx-py/src/py_camera.rs
deleted file mode 100644
index 22ec829c..00000000
--- a/rust/bridge/crates/manimgx-py/src/py_camera.rs
+++ /dev/null
@@ -1,65 +0,0 @@
-use manimgx_core::camera::{Camera, CameraRig, Projection};
-use glam::Vec3;
-use pyo3::prelude::*;
-
-#[pyclass(name = "PerspectiveCamera", from_py_object)]
-#[derive(Clone)]
-pub struct PyPerspectiveCamera {
- pub inner: CameraRig,
-}
-
-#[pymethods]
-impl PyPerspectiveCamera {
- #[new]
- #[pyo3(signature = (fov=45.0, position=vec![3.0, 2.0, 5.0], look_at=vec![0.0, 0.0, 0.0], near=0.1, far=100.0))]
- fn new(fov: f32, position: Vec<f32>, look_at: Vec<f32>, near: f32, far: f32) -> Self {
- Self {
- inner: CameraRig {
- camera: Camera {
- position: Vec3::new(position[0], position[1], position[2]),
- look_at: Vec3::new(look_at[0], look_at[1], look_at[2]),
- up: Vec3::Y,
- },
- projection: Projection::Perspective { fov, near, far },
- },
- }
- }
-}
-
-#[pyclass(name = "ObliqueCamera", from_py_object)]
-#[derive(Clone)]
-pub struct PyObliqueCamera {
- pub inner: CameraRig,
-}
-
-#[pymethods]
-impl PyObliqueCamera {
- #[new]
- #[pyo3(signature = (alpha=210.0, l=0.5, position=vec![0.0, 0.0, 10.0], look_at=vec![0.0, 0.0, 0.0], height=8.0, near=0.1, far=100.0))]
- fn new(
- alpha: f32,
- l: f32,
- position: Vec<f32>,
- look_at: Vec<f32>,
- height: f32,
- near: f32,
- far: f32,
- ) -> Self {
- Self {
- inner: CameraRig {
- camera: Camera {
- position: Vec3::new(position[0], position[1], position[2]),
- look_at: Vec3::new(look_at[0], look_at[1], look_at[2]),
- up: Vec3::Y,
- },
- projection: Projection::Oblique {
- alpha,
- l,
- height,
- near,
- far,
- },
- },
- }
- }
-}
diff --git a/rust/bridge/crates/manimgx-py/src/py_scene.rs b/rust/bridge/crates/manimgx-py/src/py_scene.rs
deleted file mode 100644
index 64089fec..00000000
--- a/rust/bridge/crates/manimgx-py/src/py_scene.rs
+++ /dev/null
@@ -1,548 +0,0 @@
-use manimgx_core::animation::easing::EasingFunction;
-use manimgx_core::animation::keyframe::{AnimatedProperty, Keyframe, CAMERA_OBJECT_ID};
-use manimgx_core::animation::timeline::Timeline;
-use manimgx_core::scene::{ObjectId, Scene};
-use manimgx_core::encoder::{FfmpegCodec, FfmpegEncoder};
-use manimgx_render::renderer::{EncoderBackend, FfmpegWriter, Renderer};
-use glam::Vec3;
-use pyo3::prelude::*;
-use std::collections::HashMap;
-
-use crate::py_camera::{PyObliqueCamera, PyPerspectiveCamera};
-use crate::py_objects;
-
-#[pyclass(name = "Scene")]
-pub struct PyScene {
- scene: Scene,
- timeline: Timeline,
- sample_count: u32,
- uuid_map: HashMap<u64, ObjectId>,
-}
-
-#[pymethods]
-impl PyScene {
- #[new]
- #[pyo3(signature = (width=1920, height=1080, fps=60, background=vec![0.0, 0.0, 0.0], msaa=4))]
- fn new(width: u32, height: u32, fps: u32, background: Vec<f32>, msaa: u32) -> Self {
- Self {
- scene: Scene::new(
- width,
- height,
- fps,
- [background[0], background[1], background[2]],
- ),
- timeline: Timeline::new(),
- sample_count: msaa,
- uuid_map: HashMap::new(),
- }
- }
-
- fn set_camera(&mut self, camera: &Bound<'_, PyAny>) -> PyResult<()> {
- let rig = if let Ok(cam) = camera.extract::<PyPerspectiveCamera>() {
- cam.inner
- } else if let Ok(cam) = camera.extract::<PyObliqueCamera>() {
- cam.inner
- } else {
- return Err(PyErr::new::<pyo3::exceptions::PyTypeError, _>(
- "Unsupported camera type. Use PerspectiveCamera or ObliqueCamera.",
- ));
- };
- self.scene.set_camera(rig);
- Ok(())
- }
-
- /// Add an object to the scene at the current cursor time with opacity=1 (visible).
- fn add(&mut self, obj: &Bound<'_, PyAny>) -> PyResult<()> {
- let data = py_objects::extract_data(obj)?;
- let uuid = data.uuid;
-
- if self.uuid_map.contains_key(&uuid) {
- return Ok(()); // already added
- }
-
- let object_id = if let Some(texture) = data.texture_data {
- self.scene.add_textured_object(
- data.vertices,
- data.indices,
- data.material,
- data.position,
- texture,
- )
- } else {
- self.scene.add_object_with_hint(
- data.vertices,
- data.indices,
- data.material,
- data.render_hint,
- data.position,
- )
- };
- self.uuid_map.insert(uuid, object_id);
- Ok(())
- }
-
- /// Auto-add an object with opacity=0 (hidden), returning its ObjectId.
- fn auto_add_hidden(&mut self, obj: &Bound<'_, PyAny>) -> PyResult<ObjectId> {
- let data = py_objects::extract_data(obj)?;
- let uuid = data.uuid;
-
- let mut mat = data.material;
- mat.opacity = 0.0;
-
- let object_id = if let Some(texture) = data.texture_data {
- self.scene.add_textured_object(
- data.vertices,
- data.indices,
- mat,
- data.position,
- texture,
- )
- } else {
- self.scene.add_object_with_hint(
- data.vertices,
- data.indices,
- mat,
- data.render_hint,
- data.position,
- )
- };
- self.uuid_map.insert(uuid, object_id);
- Ok(object_id)
- }
-
- #[pyo3(signature = (obj, translation=None, rotation=None, scale=None, color=None, opacity=None, duration=1.0, easing="linear".to_string()))]
- #[allow(clippy::too_many_arguments)]
- fn animate(
- &mut self,
- obj: &Bound<'_, PyAny>,
- translation: Option<Vec<f32>>,
- rotation: Option<Vec<f32>>,
- scale: Option<Vec<f32>>,
- color: Option<Vec<f32>>,
- opacity: Option<f32>,
- duration: f32,
- easing: String,
- ) -> PyResult<()> {
- let uuid = py_objects::get_uuid(obj)?;
-
- // If not yet in scene, auto-add with opacity=0
- let object_id = if let Some(&id) = self.uuid_map.get(&uuid) {
- id
- } else {
- self.auto_add_hidden(obj)?
- };
-
- let easing_fn = EasingFunction::parse(&easing);
- let start_time = self.timeline.cursor;
-
- if let Some(t) = translation {
- self.timeline.add_keyframe(Keyframe {
- object_id,
- property: AnimatedProperty::Translation(Vec3::new(t[0], t[1], t[2])),
- start_time,
- duration,
- easing: easing_fn.clone(),
- });
- }
-
- if let Some(r) = rotation {
- self.timeline.add_keyframe(Keyframe {
- object_id,
- property: AnimatedProperty::Rotation(Vec3::new(r[0], r[1], r[2])),
- start_time,
- duration,
- easing: easing_fn.clone(),
- });
- }
-
- if let Some(s) = scale {
- self.timeline.add_keyframe(Keyframe {
- object_id,
- property: AnimatedProperty::Scale(Vec3::new(s[0], s[1], s[2])),
- start_time,
- duration,
- easing: easing_fn.clone(),
- });
- }
-
- if let Some(c) = color {
- self.timeline.add_keyframe(Keyframe {
- object_id,
- property: AnimatedProperty::Color(Vec3::new(c[0], c[1], c[2])),
- start_time,
- duration,
- easing: easing_fn.clone(),
- });
- }
-
- if let Some(o) = opacity {
- self.timeline.add_keyframe(Keyframe {
- object_id,
- property: AnimatedProperty::Opacity(o),
- start_time,
- duration,
- easing: easing_fn,
- });
- }
-
- Ok(())
- }
-
- /// Remove an object from the scene (zero-duration opacity→0 at cursor).
- fn remove(&mut self, obj: &Bound<'_, PyAny>) -> PyResult<()> {
- let uuid = py_objects::get_uuid(obj)?;
- let object_id = match self.uuid_map.get(&uuid) {
- Some(&id) => id,
- None => return Ok(()), // not in scene, nothing to do
- };
-
- self.timeline.add_keyframe(Keyframe {
- object_id,
- property: AnimatedProperty::Opacity(0.0),
- start_time: self.timeline.cursor,
- duration: 0.0,
- easing: EasingFunction::Linear,
- });
-
- Ok(())
- }
-
- /// Animate camera position and/or look_at target over time.
- #[pyo3(signature = (position=None, look_at=None, duration=1.0, easing="linear".to_string()))]
- fn animate_camera(
- &mut self,
- position: Option<Vec<f32>>,
- look_at: Option<Vec<f32>>,
- duration: f32,
- easing: String,
- ) {
- let easing_fn = EasingFunction::parse(&easing);
- let start_time = self.timeline.cursor;
-
- if let Some(p) = position {
- self.timeline.add_keyframe(Keyframe {
- object_id: CAMERA_OBJECT_ID,
- property: AnimatedProperty::CameraPosition(Vec3::new(p[0], p[1], p[2])),
- start_time,
- duration,
- easing: easing_fn.clone(),
- });
- }
-
- if let Some(la) = look_at {
- self.timeline.add_keyframe(Keyframe {
- object_id: CAMERA_OBJECT_ID,
- property: AnimatedProperty::CameraLookAt(Vec3::new(la[0], la[1], la[2])),
- start_time,
- duration,
- easing: easing_fn,
- });
- }
- }
-
- fn wait(&mut self, seconds: f32) {
- self.timeline.advance_cursor(seconds);
- }
-
- fn get_cursor(&self) -> f32 {
- self.timeline.cursor
- }
-
- fn set_cursor(&mut self, time: f32) {
- self.timeline.cursor = time;
- }
-
- #[pyo3(signature = (output, encoder="cpu".to_string(), n_buffers=2, preset="medium".to_string(), crf=18, backend="wgpu".to_string(), pix_fmt="nv12".to_string(), muxer="fmp4".to_string()))]
- fn render(
- &mut self,
- py: Python<'_>,
- output: String,
- encoder: String,
- n_buffers: u32,
- preset: String,
- crf: u32,
- backend: String,
- pix_fmt: String,
- muxer: String,
- ) -> PyResult<()> {
- let path = Self::output_path(&output);
- let check_cancelled = || py.check_signals().is_err();
-
- if backend == "metal_native" {
- #[cfg(target_os = "macos")]
- {
- manimgx_metal::MetalBackend::validate_sample_count(self.sample_count)
- .map_err(|e| PyErr::new::<pyo3::exceptions::PyValueError, _>(e))?;
- return self.render_metal_native(&path, &encoder, n_buffers, &preset, crf, &muxer, &check_cancelled);
- }
- #[cfg(not(target_os = "macos"))]
- {
- return Err(PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(
- "backend='metal_native' is only available on macOS",
- ));
- }
- }
-
- if !matches!(self.sample_count, 1 | 4) {
- return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(
- format!(
- "wgpu backend only supports msaa=1 or msaa=4. Use backend='metal_native' for msaa={}.",
- self.sample_count
- ),
- ));
- }
-
- let enc_backend = Self::parse_encoder(&encoder)?;
- self.render_inner(&path, enc_backend, n_buffers, &preset, crf, &pix_fmt, &muxer, &check_cancelled);
- Ok(())
- }
-
- fn render_png(&mut self, output: String) -> PyResult<()> {
- if !matches!(self.sample_count, 1 | 4) {
- return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(
- format!(
- "wgpu backend only supports msaa=1 or msaa=4. Use backend='metal_native' for msaa={}.",
- self.sample_count
- ),
- ));
- }
- let path = Self::output_path(&output);
- let renderer = Renderer::new(self.sample_count);
- self.timeline.evaluate(&mut self.scene, 0.0);
- renderer.render_to_png(&self.scene, &path);
- Ok(())
- }
-}
-
-impl PyScene {
- /// Render using the native Metal backend (bypasses wgpu entirely).
- #[cfg(target_os = "macos")]
- fn render_metal_native(
- &mut self,
- output: &str,
- encoder: &str,
- n_buffers: u32,
- preset: &str,
- crf: u32,
- muxer: &str,
- check_cancelled: &dyn Fn() -> bool,
- ) -> PyResult<()> {
- let total_duration = self.timeline.total_duration();
- if total_duration <= 0.0 {
- // Fall back to wgpu for single-frame PNG
- let renderer = Renderer::new(self.sample_count);
- self.timeline.evaluate(&mut self.scene, 0.0);
- renderer.render_to_png(&self.scene, output);
- return Ok(());
- }
-
- let fps = self.scene.fps;
- let total_frames = (total_duration * fps as f32).ceil() as u32;
-
- let start = std::time::Instant::now();
-
- match encoder {
- "metal" => {
- eprintln!(
- "Rendering {} frames ({:.1}s @ {} fps) [backend: metal_native, encoder: metal (IOSurface, zero readback), n_buffers: {}]...",
- total_frames, total_duration, fps, n_buffers,
- );
- manimgx_metal::render_video_metal(
- &mut self.scene,
- &self.timeline,
- output,
- total_frames,
- fps,
- self.sample_count,
- n_buffers,
- check_cancelled,
- );
- }
- "cpu" => {
- eprintln!(
- "Rendering {} frames ({:.1}s @ {} fps) [backend: metal_native, encoder: cpu (in-process x264), n_buffers: {}, preset: {}, crf: {}, muxer: {}]...",
- total_frames, total_duration, fps, n_buffers, preset, crf, muxer,
- );
- manimgx_metal::render_video_x264(
- &mut self.scene,
- &self.timeline,
- output,
- total_frames,
- fps,
- self.sample_count,
- n_buffers,
- &preset,
- crf,
- muxer,
- check_cancelled,
- );
- }
- _ => {
- return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(
- "Unknown encoder '{}' for metal_native backend. Choose from: 'cpu', 'metal'",
- encoder
- )));
- }
- }
-
- let elapsed = start.elapsed();
- let fps_actual = total_frames as f64 / elapsed.as_secs_f64();
- eprintln!(
- "Saved: {} ({:.2}s, {:.0} fps)",
- output,
- elapsed.as_secs_f64(),
- fps_actual,
- );
-
- Ok(())
- }
-
- /// Always place output files under `<repo_root>/output/`, creating it if needed.
- fn output_path(filename: &str) -> String {
- let p = std::path::Path::new(filename);
- let name = p.file_name().unwrap_or(p.as_os_str());
- // CARGO_MANIFEST_DIR points to crates/manimgx-py at compile time; go up two levels for repo root
- let repo_root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
- .parent()
- .unwrap()
- .parent()
- .unwrap();
- let dir = repo_root.join("output");
- std::fs::create_dir_all(&dir).expect("Failed to create output/ directory");
- dir.join(name).to_string_lossy().into_owned()
- }
-
- fn parse_encoder(encoder: &str) -> PyResult<EncoderBackend> {
- match encoder {
- "cpu" => Ok(EncoderBackend::X264),
- "hw" => {
- #[cfg(target_os = "macos")]
- {
- Ok(EncoderBackend::Ffmpeg(FfmpegCodec::H264VideoToolbox))
- }
- #[cfg(not(target_os = "macos"))]
- {
- Ok(EncoderBackend::Ffmpeg(FfmpegCodec::H264Vaapi))
- }
- }
- _ => Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(
- "Unknown encoder '{}'. Choose from: 'cpu', 'hw'",
- encoder
- ))),
- }
- }
-
- fn render_inner(
- &mut self,
- output: &str,
- backend: EncoderBackend,
- n_buffers: u32,
- preset: &str,
- crf: u32,
- pix_fmt: &str,
- muxer: &str,
- check_cancelled: &dyn Fn() -> bool,
- ) {
- let total_duration = self.timeline.total_duration();
- if total_duration <= 0.0 {
- let renderer = Renderer::new(self.sample_count);
- self.timeline.evaluate(&mut self.scene, 0.0);
- renderer.render_to_png(&self.scene, output);
- return;
- }
-
- let fps = self.scene.fps;
- let total_frames = (total_duration * fps as f32).ceil() as u32;
- let use_nv12 = pix_fmt == "nv12";
-
- match &backend {
- EncoderBackend::Ffmpeg(FfmpegCodec::H264VideoToolbox) => {
- eprintln!(
- "Rendering {} frames ({:.1}s @ {} fps) [backend: wgpu, encoder: hw (VideoToolbox via ffmpeg), n_buffers: {}, pix_fmt: {}]...",
- total_frames, total_duration, fps, n_buffers, pix_fmt,
- );
- }
- EncoderBackend::Ffmpeg(FfmpegCodec::H264Vaapi) => {
- eprintln!(
- "Rendering {} frames ({:.1}s @ {} fps) [backend: wgpu, encoder: hw (VAAPI via ffmpeg), n_buffers: {}, pix_fmt: {}]...",
- total_frames, total_duration, fps, n_buffers, pix_fmt,
- );
- }
- EncoderBackend::X264 => {
- eprintln!(
- "Rendering {} frames ({:.1}s @ {} fps) [backend: wgpu, encoder: cpu (in-process x264), n_buffers: {}, preset: {}, crf: {}, muxer: {}]...",
- total_frames, total_duration, fps, n_buffers, preset, crf, muxer,
- );
- }
- }
-
- let start = std::time::Instant::now();
- let w = self.scene.width;
- let h = self.scene.height;
-
- // Validate NV12 dimension requirements
- if use_nv12 {
- assert!(
- w % 4 == 0 && h % 2 == 0,
- "NV12 requires width%4==0 and height%2==0, got {}x{}",
- w,
- h
- );
- }
-
- match backend {
- EncoderBackend::Ffmpeg(codec) => {
- let renderer = Renderer::new(self.sample_count);
- let effective_fmt = if use_nv12 { "nv12" } else { "rgba" };
- let pixel_size = if use_nv12 {
- (w * h * 3 / 2) as usize
- } else {
- (w * h * 4) as usize
- };
- let encoder = FfmpegEncoder::with_pixel_format(
- output, w, h, fps, codec, crf, effective_fmt,
- );
- let mut writer = FfmpegWriter::new(encoder, pixel_size);
- renderer.render_video(
- &mut self.scene,
- &self.timeline,
- &mut writer,
- total_frames,
- fps,
- n_buffers,
- use_nv12,
- check_cancelled,
- );
- }
- EncoderBackend::X264 => {
- assert!(
- w % 4 == 0 && h % 2 == 0,
- "NV12 requires width%4==0 and height%2==0, got {}x{}",
- w, h,
- );
- let renderer = Renderer::new(self.sample_count);
- renderer.render_video_x264(
- &mut self.scene,
- &self.timeline,
- output,
- total_frames,
- fps,
- n_buffers,
- preset,
- crf,
- muxer,
- check_cancelled,
- );
- }
- }
-
- let elapsed = start.elapsed();
- let fps_actual = total_frames as f64 / elapsed.as_secs_f64();
- eprintln!(
- "Saved: {} ({:.2}s, {:.0} fps)",
- output,
- elapsed.as_secs_f64(),
- fps_actual,
- );
- }
-}
diff --git a/rust/bridge/crates/manimgx-render/Cargo.toml b/rust/bridge/crates/manimgx-render/Cargo.toml
deleted file mode 100644
index 3787a396..00000000
--- a/rust/bridge/crates/manimgx-render/Cargo.toml
+++ /dev/null
@@ -1,17 +0,0 @@
-[package]
-name = "manimgx-render"
-version = "0.1.0"
-edition = "2021"
-
-[dependencies]
-manimgx-core = { path = "../manimgx-core" }
-manimgx-encode = { path = "../manimgx-encode" }
-wgpu = "24"
-bytemuck = { workspace = true }
-glam = { workspace = true }
-log = { workspace = true }
-image = { version = "0.25", default-features = false, features = ["png"], optional = true }
-
-[features]
-time_profile = []
-png_debug = ["image"]
diff --git a/rust/bridge/crates/manimgx-render/src/gpu.rs b/rust/bridge/crates/manimgx-render/src/gpu.rs
deleted file mode 100644
index 0fc8ae07..00000000
--- a/rust/bridge/crates/manimgx-render/src/gpu.rs
+++ /dev/null
@@ -1,67 +0,0 @@
-use std::pin::pin;
-use std::task::{Context, Poll, Waker};
-
-pub struct GpuContext {
- pub device: wgpu::Device,
- pub queue: wgpu::Queue,
-}
-
-/// Poll a future that is expected to resolve synchronously (wgpu native).
-fn block_on<F: std::future::Future>(future: F) -> F::Output {
- let waker = Waker::noop();
- let mut cx = Context::from_waker(&waker);
- let mut future = pin!(future);
- match future.as_mut().poll(&mut cx) {
- Poll::Ready(v) => v,
- Poll::Pending => unreachable!("wgpu futures resolve synchronously on native"),
- }
-}
-
-impl Default for GpuContext {
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl GpuContext {
- pub fn new() -> Self {
- Self::with_features(wgpu::Features::empty())
- }
-
- pub fn with_features(features: wgpu::Features) -> Self {
- block_on(Self::init(features))
- }
-
- async fn init(features: wgpu::Features) -> Self {
- let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor {
- backends: wgpu::Backends::all(),
- ..Default::default()
- });
-
- let adapter = instance
- .request_adapter(&wgpu::RequestAdapterOptions {
- power_preference: wgpu::PowerPreference::HighPerformance,
- compatible_surface: None,
- force_fallback_adapter: false,
- })
- .await
- .expect("Failed to find a suitable GPU adapter. Ensure you have a GPU with Vulkan/Metal/DX12 support.");
-
- let (device, queue) = adapter
- .request_device(
- &wgpu::DeviceDescriptor {
- label: Some("manimgx-device"),
- required_features: features,
- required_limits: wgpu::Limits::default(),
- ..Default::default()
- },
- None,
- )
- .await
- .expect("Failed to create GPU device");
-
- log::info!("GPU initialized: {:?}", adapter.get_info().name);
-
- Self { device, queue }
- }
-}
diff --git a/rust/bridge/crates/manimgx-render/src/lib.rs b/rust/bridge/crates/manimgx-render/src/lib.rs
deleted file mode 100644
index 67d710e8..00000000
--- a/rust/bridge/crates/manimgx-render/src/lib.rs
+++ /dev/null
@@ -1,7 +0,0 @@
-pub mod gpu;
-pub mod pipeline;
-#[cfg(not(feature = "time_profile"))]
-pub mod renderer;
-#[cfg(feature = "time_profile")]
-#[path = "renderer_profile.rs"]
-pub mod renderer;
diff --git a/rust/bridge/crates/manimgx-render/src/pipeline.rs b/rust/bridge/crates/manimgx-render/src/pipeline.rs
deleted file mode 100644
index 813e6fbb..00000000
--- a/rust/bridge/crates/manimgx-render/src/pipeline.rs
+++ /dev/null
@@ -1,232 +0,0 @@
-use manimgx_core::vertex::Vertex;
-use wgpu;
-
-pub struct RenderPipelines {
- pub default: wgpu::RenderPipeline,
- pub flat_no_cull: wgpu::RenderPipeline,
- pub textured: wgpu::RenderPipeline,
- pub camera_bind_group_layout: wgpu::BindGroupLayout,
- pub model_bind_group_layout: wgpu::BindGroupLayout,
- pub texture_bind_group_layout: wgpu::BindGroupLayout,
-}
-
-impl RenderPipelines {
- pub fn new(
- device: &wgpu::Device,
- color_format: wgpu::TextureFormat,
- sample_count: u32,
- ) -> Self {
- let camera_bind_group_layout =
- device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
- label: Some("camera_bind_group_layout"),
- entries: &[wgpu::BindGroupLayoutEntry {
- binding: 0,
- visibility: wgpu::ShaderStages::VERTEX,
- ty: wgpu::BindingType::Buffer {
- ty: wgpu::BufferBindingType::Uniform,
- has_dynamic_offset: false,
- min_binding_size: None,
- },
- count: None,
- }],
- });
-
- let model_bind_group_layout =
- device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
- label: Some("model_bind_group_layout"),
- entries: &[wgpu::BindGroupLayoutEntry {
- binding: 0,
- visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
- ty: wgpu::BindingType::Buffer {
- ty: wgpu::BufferBindingType::Uniform,
- has_dynamic_offset: true,
- min_binding_size: None,
- },
- count: None,
- }],
- });
-
- let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
- label: Some("render_pipeline_layout"),
- bind_group_layouts: &[&camera_bind_group_layout, &model_bind_group_layout],
- push_constant_ranges: &[],
- });
-
- let vertex_buffer_layout = wgpu::VertexBufferLayout {
- array_stride: std::mem::size_of::<Vertex>() as wgpu::BufferAddress,
- step_mode: wgpu::VertexStepMode::Vertex,
- attributes: &[
- // position
- wgpu::VertexAttribute {
- offset: 0,
- shader_location: 0,
- format: wgpu::VertexFormat::Float32x3,
- },
- // normal
- wgpu::VertexAttribute {
- offset: 12,
- shader_location: 1,
- format: wgpu::VertexFormat::Float32x3,
- },
- // color
- wgpu::VertexAttribute {
- offset: 24,
- shader_location: 2,
- format: wgpu::VertexFormat::Float32x4,
- },
- ],
- };
-
- let default_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
- label: Some("default_shader"),
- source: wgpu::ShaderSource::Wgsl(include_str!("../../../shaders/default.wgsl").into()),
- });
-
- let flat_color_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
- label: Some("flat_color_shader"),
- source: wgpu::ShaderSource::Wgsl(
- include_str!("../../../shaders/flat_color.wgsl").into(),
- ),
- });
-
- let default = Self::create_pipeline(
- device,
- &pipeline_layout,
- &default_shader,
- &vertex_buffer_layout,
- color_format,
- wgpu::PrimitiveTopology::TriangleList,
- None,
- sample_count,
- );
-
- let flat_no_cull = Self::create_pipeline(
- device,
- &pipeline_layout,
- &flat_color_shader,
- &vertex_buffer_layout,
- color_format,
- wgpu::PrimitiveTopology::TriangleList,
- None,
- sample_count,
- );
-
- // --- Textured pipeline (for text rendering) ---
-
- let texture_bind_group_layout =
- device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
- label: Some("texture_bind_group_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,
- },
- ],
- });
-
- let textured_pipeline_layout =
- device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
- label: Some("textured_pipeline_layout"),
- bind_group_layouts: &[
- &camera_bind_group_layout,
- &model_bind_group_layout,
- &texture_bind_group_layout,
- ],
- push_constant_ranges: &[],
- });
-
- let text_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
- label: Some("text_shader"),
- source: wgpu::ShaderSource::Wgsl(include_str!("../../../shaders/text.wgsl").into()),
- });
-
- // Textured pipeline uses the same Vertex layout (UV packed into normal.xy)
- let textured = Self::create_pipeline(
- device,
- &textured_pipeline_layout,
- &text_shader,
- &vertex_buffer_layout,
- color_format,
- wgpu::PrimitiveTopology::TriangleList,
- None, // no culling for 2D text quads at z=0
- sample_count,
- );
-
- Self {
- default,
- flat_no_cull,
- textured,
- camera_bind_group_layout,
- model_bind_group_layout,
- texture_bind_group_layout,
- }
- }
-
- #[allow(clippy::too_many_arguments)]
- fn create_pipeline(
- device: &wgpu::Device,
- layout: &wgpu::PipelineLayout,
- shader: &wgpu::ShaderModule,
- vertex_buffer_layout: &wgpu::VertexBufferLayout,
- color_format: wgpu::TextureFormat,
- topology: wgpu::PrimitiveTopology,
- cull_mode: Option<wgpu::Face>,
- sample_count: u32,
- ) -> wgpu::RenderPipeline {
- device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
- label: Some("render_pipeline"),
- layout: Some(layout),
- vertex: wgpu::VertexState {
- module: shader,
- entry_point: Some("vs_main"),
- buffers: std::slice::from_ref(vertex_buffer_layout),
- compilation_options: Default::default(),
- },
- fragment: Some(wgpu::FragmentState {
- module: shader,
- entry_point: Some("fs_main"),
- targets: &[Some(wgpu::ColorTargetState {
- format: color_format,
- blend: Some(wgpu::BlendState::ALPHA_BLENDING),
- write_mask: wgpu::ColorWrites::ALL,
- })],
- compilation_options: Default::default(),
- }),
- primitive: wgpu::PrimitiveState {
- topology,
- strip_index_format: None,
- front_face: wgpu::FrontFace::Ccw,
- cull_mode,
- unclipped_depth: false,
- polygon_mode: wgpu::PolygonMode::Fill,
- conservative: false,
- },
- depth_stencil: Some(wgpu::DepthStencilState {
- format: wgpu::TextureFormat::Depth32Float,
- depth_write_enabled: true,
- depth_compare: wgpu::CompareFunction::Less,
- stencil: wgpu::StencilState::default(),
- bias: wgpu::DepthBiasState::default(),
- }),
- multisample: wgpu::MultisampleState {
- count: sample_count,
- mask: !0,
- alpha_to_coverage_enabled: false,
- },
- multiview: None,
- cache: None,
- })
- }
-}
diff --git a/rust/bridge/crates/manimgx-render/src/renderer.rs b/rust/bridge/crates/manimgx-render/src/renderer.rs
deleted file mode 100644
index 463fb1e3..00000000
--- a/rust/bridge/crates/manimgx-render/src/renderer.rs
+++ /dev/null
@@ -1,1460 +0,0 @@
-use std::collections::HashMap;
-
-use manimgx_core::color::srgb_to_linear;
-use manimgx_core::scene::{ObjectId, RenderHint, Scene};
-use manimgx_core::uniform::{CameraUniform, ObjectUniform};
-use manimgx_core::vertex::Vertex;
-use bytemuck;
-use wgpu::util::DeviceExt;
-
-use manimgx_core::encoder::FfmpegCodec;
-use crate::gpu::GpuContext;
-use crate::pipeline::RenderPipelines;
-
-
-/// Which encoder backend to use for video output.
-pub enum EncoderBackend {
- /// GPU → staging → CPU readback → ffmpeg pipe (h264_videotoolbox or h264_vaapi)
- Ffmpeg(FfmpegCodec),
- /// GPU → NV12 compute → staging → CPU readback → in-process x264 FFI (no subprocess)
- X264,
-}
-
-/// Cached GPU buffers for a scene object (geometry never changes).
-struct CachedObjectBuffers {
- vertex_buffer: wgpu::Buffer,
- index_buffer: wgpu::Buffer,
- index_count: u32,
-}
-
-/// Cached GPU texture resources for a textured object (uploaded once).
-struct CachedTextureBindGroup {
- _texture: wgpu::Texture,
- _view: wgpu::TextureView,
- _sampler: wgpu::Sampler,
- bind_group: wgpu::BindGroup,
-}
-
-/// Draw command for one object in one frame.
-struct DrawCmd {
- obj_idx: usize,
- uniform_slot: usize,
-}
-
-/// Pre-allocated GPU resources for rendering.
-struct FrameResources {
- /// MSAA render target (only when sample_count > 1). Kept alive for msaa_view / nv12 bind group.
- _msaa_texture: Option<wgpu::Texture>,
- msaa_view: Option<wgpu::TextureView>,
- /// Output texture (sample_count=1) — copied to staging for readback.
- /// When MSAA is on, this is the resolve target. When off, this is the render target.
- output_texture: wgpu::Texture,
- output_view: wgpu::TextureView,
- _depth_texture: wgpu::Texture,
- depth_view: wgpu::TextureView,
- staging_buffer: wgpu::Buffer,
- padded_bytes_per_row: u32,
- unpadded_bytes_per_row: u32,
- pixel_size: usize,
- width: u32,
- height: u32,
- camera_buffer: wgpu::Buffer,
- camera_bind_group: wgpu::BindGroup,
- object_uniform_buffer: wgpu::Buffer,
- object_bind_group: wgpu::BindGroup,
- uniform_alignment: usize,
- /// CPU staging for object uniforms: max_objects * alignment bytes
- uniform_staging: Vec<u8>,
- rows_contiguous: bool,
- // NV12 compute conversion resources
- /// Kept alive to back nv12_bind_group
- _nv12_view: Option<wgpu::TextureView>,
- nv12_storage_buffer: Option<wgpu::Buffer>,
- nv12_staging_buffer: Option<wgpu::Buffer>,
- nv12_bind_group: Option<wgpu::BindGroup>,
- nv12_size: usize,
-}
-
-impl FrameResources {
- #[allow(clippy::too_many_arguments)]
- fn new(
- device: &wgpu::Device,
- width: u32,
- height: u32,
- color_format: wgpu::TextureFormat,
- camera_bgl: &wgpu::BindGroupLayout,
- object_bgl: &wgpu::BindGroupLayout,
- num_objects: usize,
- sample_count: u32,
- use_nv12: bool,
- nv12_bgl: Option<&wgpu::BindGroupLayout>,
- ) -> Self {
- // Non-sRGB view format for NV12 compute shader (keeps gamma-encoded values)
- let non_srgb_format = match color_format {
- wgpu::TextureFormat::Rgba8UnormSrgb => wgpu::TextureFormat::Rgba8Unorm,
- wgpu::TextureFormat::Bgra8UnormSrgb => wgpu::TextureFormat::Bgra8Unorm,
- other => other,
- };
-
- // MSAA render target (only when sample_count > 1)
- // Hardware MSAA resolve is essentially free (dedicated fixed-function silicon on tile flush).
- // The NV12 compute shader always reads the resolved 1x output_texture, not the MSAA texture.
- let (msaa_texture, msaa_view) = if sample_count > 1 {
- let tex = device.create_texture(&wgpu::TextureDescriptor {
- label: Some("msaa_texture"),
- size: wgpu::Extent3d {
- width,
- height,
- depth_or_array_layers: 1,
- },
- mip_level_count: 1,
- sample_count,
- dimension: wgpu::TextureDimension::D2,
- format: color_format,
- usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
- view_formats: &[],
- });
- let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
- (Some(tex), Some(view))
- } else {
- (None, None)
- };
-
- // Output texture (1x) — resolve target when MSAA, or direct render target.
- // NV12 compute shader reads from this after hardware MSAA resolve.
- let mut output_usage =
- wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC;
- let mut output_view_formats: Vec<wgpu::TextureFormat> = vec![];
- if use_nv12 {
- output_usage |= wgpu::TextureUsages::TEXTURE_BINDING;
- output_view_formats.push(non_srgb_format);
- }
- let output_texture = device.create_texture(&wgpu::TextureDescriptor {
- label: Some("output_texture"),
- size: wgpu::Extent3d {
- width,
- height,
- depth_or_array_layers: 1,
- },
- mip_level_count: 1,
- sample_count: 1,
- dimension: wgpu::TextureDimension::D2,
- format: color_format,
- usage: output_usage,
- view_formats: &output_view_formats,
- });
- let output_view = output_texture.create_view(&wgpu::TextureViewDescriptor::default());
-
- // Depth buffer (must match sample_count)
- let depth_texture = device.create_texture(&wgpu::TextureDescriptor {
- label: Some("depth_texture"),
- size: wgpu::Extent3d {
- width,
- height,
- depth_or_array_layers: 1,
- },
- mip_level_count: 1,
- sample_count,
- dimension: wgpu::TextureDimension::D2,
- format: wgpu::TextureFormat::Depth32Float,
- usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
- view_formats: &[],
- });
- let depth_view = depth_texture.create_view(&wgpu::TextureViewDescriptor::default());
-
- let bytes_per_pixel = 4u32;
- let unpadded_bytes_per_row = width * bytes_per_pixel;
- let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
- let padded_bytes_per_row = unpadded_bytes_per_row.div_ceil(align) * align;
- let rows_contiguous = padded_bytes_per_row == unpadded_bytes_per_row;
- let pixel_size = (width * height * bytes_per_pixel) as usize;
- let staging_size = (padded_bytes_per_row * height) as u64;
-
- let staging_buffer = device.create_buffer(&wgpu::BufferDescriptor {
- label: Some("staging"),
- size: staging_size,
- usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
- mapped_at_creation: false,
- });
-
- let cam_size = std::mem::size_of::<CameraUniform>() as u64;
- let camera_buffer = device.create_buffer(&wgpu::BufferDescriptor {
- label: Some("camera"),
- size: cam_size,
- usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
- mapped_at_creation: false,
- });
- let camera_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
- label: Some("camera_bg"),
- layout: camera_bgl,
- entries: &[wgpu::BindGroupEntry {
- binding: 0,
- resource: camera_buffer.as_entire_binding(),
- }],
- });
-
- let uniform_alignment = device.limits().min_uniform_buffer_offset_alignment as usize;
- let max_objects = num_objects.max(1);
- let buffer_size = (max_objects * uniform_alignment) as u64;
-
- let object_uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
- label: Some("object_uniform_buffer"),
- size: buffer_size,
- usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
- mapped_at_creation: false,
- });
-
- let uniform_size = std::mem::size_of::<ObjectUniform>() as u64;
- let object_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
- label: Some("object_bind_group"),
- layout: object_bgl,
- entries: &[wgpu::BindGroupEntry {
- binding: 0,
- resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
- buffer: &object_uniform_buffer,
- offset: 0,
- size: Some(std::num::NonZero::new(uniform_size).unwrap()),
- }),
- }],
- });
-
- let uniform_staging = vec![0u8; max_objects * uniform_alignment];
-
- // NV12 compute conversion resources
- let nv12_size = (width * height * 3 / 2) as usize;
- let (nv12_view, nv12_storage_buffer, nv12_staging_buffer, nv12_bind_group) = if use_nv12 {
- let bgl = nv12_bgl.expect("NV12 bind group layout required when use_nv12=true");
-
- // Non-sRGB view of the resolved 1x output_texture.
- // Hardware MSAA resolve writes here; compute shader reads raw gamma-encoded bytes.
- let nv12_view = output_texture.create_view(&wgpu::TextureViewDescriptor {
- format: Some(non_srgb_format),
- ..Default::default()
- });
-
- let storage_buf = device.create_buffer(&wgpu::BufferDescriptor {
- label: Some("nv12_storage"),
- size: nv12_size as u64,
- usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
- mapped_at_creation: false,
- });
-
- let staging_buf = device.create_buffer(&wgpu::BufferDescriptor {
- label: Some("nv12_staging"),
- size: nv12_size as u64,
- usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
- mapped_at_creation: false,
- });
-
- let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
- label: Some("nv12_bg"),
- layout: bgl,
- entries: &[
- wgpu::BindGroupEntry {
- binding: 0,
- resource: wgpu::BindingResource::TextureView(&nv12_view),
- },
- wgpu::BindGroupEntry {
- binding: 1,
- resource: storage_buf.as_entire_binding(),
- },
- ],
- });
-
- (
- Some(nv12_view),
- Some(storage_buf),
- Some(staging_buf),
- Some(bind_group),
- )
- } else {
- (None, None, None, None)
- };
-
- Self {
- _msaa_texture: msaa_texture,
- msaa_view,
- output_texture,
- output_view,
- _depth_texture: depth_texture,
- depth_view,
- staging_buffer,
- padded_bytes_per_row,
- unpadded_bytes_per_row,
- pixel_size,
- width,
- height,
- camera_buffer,
- camera_bind_group,
- object_uniform_buffer,
- object_bind_group,
- uniform_alignment,
- uniform_staging,
- rows_contiguous,
- _nv12_view: nv12_view,
- nv12_storage_buffer,
- nv12_staging_buffer,
- nv12_bind_group,
- nv12_size,
- }
- }
-
- /// Read pixels from the mapped staging buffer into a pre-allocated buffer.
- fn read_pixels_into(&self, dst: &mut Vec<u8>) {
- let data = self.staging_buffer.slice(..).get_mapped_range();
-
- if self.rows_contiguous {
- dst.clear();
- dst.extend_from_slice(&data[..self.pixel_size]);
- } else {
- dst.clear();
- dst.reserve(self.pixel_size);
- for row in 0..self.height {
- let start = (row * self.padded_bytes_per_row) as usize;
- let end = start + self.unpadded_bytes_per_row as usize;
- dst.extend_from_slice(&data[start..end]);
- }
- }
-
- drop(data);
- self.staging_buffer.unmap();
- }
-
- /// Read NV12 data from the mapped NV12 staging buffer (no row padding).
- fn read_nv12_into(&self, dst: &mut Vec<u8>) {
- let buf = self.nv12_staging_buffer.as_ref().unwrap();
- let data = buf.slice(..).get_mapped_range();
- dst.clear();
- dst.extend_from_slice(&data[..self.nv12_size]);
- drop(data);
- buf.unmap();
- }
-
- /// Read NV12 data from the mapped NV12 staging buffer into a pre-existing slice.
- fn read_nv12_into_slice(&self, dst: &mut [u8]) {
- let buf = self.nv12_staging_buffer.as_ref().unwrap();
- let data = buf.slice(..).get_mapped_range();
- dst[..self.nv12_size].copy_from_slice(&data[..self.nv12_size]);
- drop(data);
- buf.unmap();
- }
-}
-
-pub struct Renderer {
- pub gpu: GpuContext,
- pub pipelines: RenderPipelines,
- pub color_format: wgpu::TextureFormat,
- pub sample_count: u32,
- nv12_pipeline: wgpu::ComputePipeline,
- nv12_bind_group_layout: wgpu::BindGroupLayout,
-}
-
-/// Trait abstracting different frame encoding backends for the unified render loop.
-pub trait FrameWriter {
- /// Write a rendered frame's pixel data to the encoder.
- fn write_frame(&mut self, pixels: &[u8]);
- /// Handle a duplicate frame (same scene state as previous).
- fn write_duplicate(&mut self);
- /// Finalize the writer (flush, join threads, etc).
- fn finish(&mut self);
-}
-
-/// Frame writer for ffmpeg-based encoding with a background writer thread and buffer pool.
-pub struct FfmpegWriter {
- tx: Option<std::sync::mpsc::SyncSender<Option<Vec<u8>>>>,
- pool_rx: std::sync::mpsc::Receiver<Vec<u8>>,
- writer_handle: Option<std::thread::JoinHandle<()>>,
-}
-
-impl FfmpegWriter {
- pub fn new(encoder: manimgx_core::encoder::FfmpegEncoder, pixel_size: usize) -> Self {
- let pool_size = 4;
- let (tx, rx) = std::sync::mpsc::sync_channel::<Option<Vec<u8>>>(2);
- let (pool_tx, pool_rx) = std::sync::mpsc::sync_channel::<Vec<u8>>(pool_size);
-
- for _ in 0..pool_size {
- pool_tx.send(vec![0u8; pixel_size]).unwrap();
- }
-
- let handle = std::thread::spawn(move || {
- let mut encoder = encoder;
- let mut last_written = vec![0u8; pixel_size];
- while let Ok(data) = rx.recv() {
- match data {
- Some(pixels) => {
- encoder.write_frame(&pixels);
- last_written.copy_from_slice(&pixels);
- let _ = pool_tx.send(pixels);
- }
- None => {
- encoder.write_frame(&last_written);
- }
- }
- }
- encoder.finish();
- });
-
- Self {
- tx: Some(tx),
- pool_rx,
- writer_handle: Some(handle),
- }
- }
-}
-
-impl FrameWriter for FfmpegWriter {
- fn write_frame(&mut self, pixels: &[u8]) {
- let mut buf = self.pool_rx.recv().unwrap();
- buf[..pixels.len()].copy_from_slice(pixels);
- self.tx.as_ref().unwrap().send(Some(buf)).unwrap();
- }
-
- fn write_duplicate(&mut self) {
- self.tx.as_ref().unwrap().send(None).unwrap();
- }
-
- fn finish(&mut self) {
- self.tx.take();
- if let Some(handle) = self.writer_handle.take() {
- handle.join().unwrap();
- }
- }
-}
-
-impl Renderer {
- pub fn new(sample_count: u32) -> Self {
- Self::new_with_format(sample_count, wgpu::TextureFormat::Rgba8UnormSrgb)
- }
-
- pub fn new_with_format(sample_count: u32, color_format: wgpu::TextureFormat) -> Self {
- let gpu = GpuContext::new();
- let pipelines = RenderPipelines::new(&gpu.device, color_format, sample_count);
-
- // NV12 compute pipeline — always reads the resolved 1x output_texture (non-MSAA).
- // Hardware MSAA resolve is free; manual resolve in compute shader is 10x slower.
- let nv12_shader_src = include_str!("../../../shaders/nv12_convert.wgsl");
- let nv12_shader = gpu
- .device
- .create_shader_module(wgpu::ShaderModuleDescriptor {
- label: Some("nv12_convert_shader"),
- source: wgpu::ShaderSource::Wgsl(nv12_shader_src.into()),
- });
-
- let nv12_bind_group_layout =
- gpu.device
- .create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
- label: Some("nv12_bgl"),
- entries: &[
- wgpu::BindGroupLayoutEntry {
- binding: 0,
- visibility: wgpu::ShaderStages::COMPUTE,
- ty: wgpu::BindingType::Texture {
- sample_type: wgpu::TextureSampleType::Float { filterable: false },
- view_dimension: wgpu::TextureViewDimension::D2,
- multisampled: false,
- },
- count: None,
- },
- wgpu::BindGroupLayoutEntry {
- binding: 1,
- visibility: wgpu::ShaderStages::COMPUTE,
- ty: wgpu::BindingType::Buffer {
- ty: wgpu::BufferBindingType::Storage { read_only: false },
- has_dynamic_offset: false,
- min_binding_size: None,
- },
- count: None,
- },
- ],
- });
-
- let nv12_pipeline_layout =
- gpu.device
- .create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
- label: Some("nv12_pipeline_layout"),
- bind_group_layouts: &[&nv12_bind_group_layout],
- push_constant_ranges: &[],
- });
-
- let nv12_pipeline =
- gpu.device
- .create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
- label: Some("nv12_pipeline"),
- layout: Some(&nv12_pipeline_layout),
- module: &nv12_shader,
- entry_point: Some("nv12_convert"),
- compilation_options: Default::default(),
- cache: None,
- });
-
- Self {
- gpu,
- pipelines,
- color_format,
- sample_count,
- nv12_pipeline,
- nv12_bind_group_layout,
- }
- }
-
- /// Get or create cached vertex/index buffers for an object.
- fn get_or_cache_buffers<'a>(
- &self,
- obj_id: ObjectId,
- vertices: &[Vertex],
- indices: &[u32],
- cache: &'a mut HashMap<ObjectId, CachedObjectBuffers>,
- ) -> &'a CachedObjectBuffers {
- cache.entry(obj_id).or_insert_with(|| {
- let vertex_buffer =
- self.gpu
- .device
- .create_buffer_init(&wgpu::util::BufferInitDescriptor {
- label: Some("cached_vertex_buffer"),
- contents: bytemuck::cast_slice(vertices),
- usage: wgpu::BufferUsages::VERTEX,
- });
- let index_buffer =
- self.gpu
- .device
- .create_buffer_init(&wgpu::util::BufferInitDescriptor {
- label: Some("cached_index_buffer"),
- contents: bytemuck::cast_slice(indices),
- usage: wgpu::BufferUsages::INDEX,
- });
- CachedObjectBuffers {
- vertex_buffer,
- index_buffer,
- index_count: indices.len() as u32,
- }
- })
- }
-
- /// Get or create cached texture bind group for a textured object (uploaded once).
- fn get_or_cache_texture<'a>(
- &self,
- obj_id: ObjectId,
- texture_data: &manimgx_core::scene::TextureData,
- cache: &'a mut HashMap<ObjectId, CachedTextureBindGroup>,
- ) -> &'a CachedTextureBindGroup {
- cache.entry(obj_id).or_insert_with(|| {
- let size = wgpu::Extent3d {
- width: texture_data.width,
- height: texture_data.height,
- depth_or_array_layers: 1,
- };
- let texture = self.gpu.device.create_texture(&wgpu::TextureDescriptor {
- label: Some("text_texture"),
- size,
- mip_level_count: 1,
- sample_count: 1,
- dimension: wgpu::TextureDimension::D2,
- format: wgpu::TextureFormat::Rgba8UnormSrgb,
- usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
- view_formats: &[],
- });
- self.gpu.queue.write_texture(
- wgpu::TexelCopyTextureInfo {
- texture: &texture,
- mip_level: 0,
- origin: wgpu::Origin3d::ZERO,
- aspect: wgpu::TextureAspect::All,
- },
- &texture_data.rgba,
- wgpu::TexelCopyBufferLayout {
- offset: 0,
- bytes_per_row: Some(4 * texture_data.width),
- rows_per_image: Some(texture_data.height),
- },
- size,
- );
- let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
- let sampler = self.gpu.device.create_sampler(&wgpu::SamplerDescriptor {
- label: Some("text_sampler"),
- address_mode_u: wgpu::AddressMode::ClampToEdge,
- address_mode_v: wgpu::AddressMode::ClampToEdge,
- mag_filter: wgpu::FilterMode::Linear,
- min_filter: wgpu::FilterMode::Linear,
- ..Default::default()
- });
- let bind_group =
- self.gpu
- .device
- .create_bind_group(&wgpu::BindGroupDescriptor {
- label: Some("text_texture_bg"),
- layout: &self.pipelines.texture_bind_group_layout,
- entries: &[
- wgpu::BindGroupEntry {
- binding: 0,
- resource: wgpu::BindingResource::TextureView(&view),
- },
- wgpu::BindGroupEntry {
- binding: 1,
- resource: wgpu::BindingResource::Sampler(&sampler),
- },
- ],
- });
- CachedTextureBindGroup {
- _texture: texture,
- _view: view,
- _sampler: sampler,
- bind_group,
- }
- })
- }
-
- fn wait_for_gpu(&self) {
- self.gpu.device.poll(wgpu::Maintain::Wait);
- }
-
- /// Encode a render pass into a command encoder.
- /// `output_view` is the resolve target (or direct render target if no MSAA).
- #[allow(clippy::too_many_arguments)]
- fn encode_render_pass(
- &self,
- cmd_encoder: &mut wgpu::CommandEncoder,
- res: &FrameResources,
- output_view: &wgpu::TextureView,
- draw_cmds: &[DrawCmd],
- scene: &Scene,
- object_cache: &mut HashMap<ObjectId, CachedObjectBuffers>,
- texture_cache: &mut HashMap<ObjectId, CachedTextureBindGroup>,
- clear_color: wgpu::Color,
- ) {
- let alignment = res.uniform_alignment;
-
- // Pre-cache textures for textured objects (must happen outside render pass borrow)
- for cmd in draw_cmds {
- let obj = &scene.objects[cmd.obj_idx];
- if let RenderHint::Textured = &obj.render_hint {
- if let Some(ref tex_data) = obj.texture_data {
- self.get_or_cache_texture(obj.id, tex_data, texture_cache);
- }
- }
- }
-
- // Always do hardware MSAA resolve — it's essentially free (dedicated fixed-function silicon).
- // NV12 compute shader reads the resolved 1x output_texture afterwards.
- let mut rp = cmd_encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
- label: None,
- color_attachments: &[Some(wgpu::RenderPassColorAttachment {
- view: res.msaa_view.as_ref().unwrap_or(output_view),
- resolve_target: res.msaa_view.as_ref().map(|_| output_view),
- ops: wgpu::Operations {
- load: wgpu::LoadOp::Clear(clear_color),
- store: wgpu::StoreOp::Store,
- },
- })],
- depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
- view: &res.depth_view,
- depth_ops: Some(wgpu::Operations {
- load: wgpu::LoadOp::Clear(1.0),
- store: wgpu::StoreOp::Store,
- }),
- stencil_ops: None,
- }),
- timestamp_writes: None,
- occlusion_query_set: None,
- });
-
- rp.set_bind_group(0, &res.camera_bind_group, &[]);
-
- for cmd in draw_cmds {
- let obj = &scene.objects[cmd.obj_idx];
- let is_textured = matches!(&obj.render_hint, RenderHint::Textured);
- let pipeline = match &obj.render_hint {
- RenderHint::Default => &self.pipelines.default,
- RenderHint::FlatUnlit => &self.pipelines.flat_no_cull,
- RenderHint::Textured => &self.pipelines.textured,
- };
- rp.set_pipeline(pipeline);
- let dynamic_offset = (cmd.uniform_slot * alignment) as u32;
- rp.set_bind_group(1, &res.object_bind_group, &[dynamic_offset]);
-
- if is_textured {
- if let Some(tex_cached) = texture_cache.get(&obj.id) {
- rp.set_bind_group(2, &tex_cached.bind_group, &[]);
- }
- }
-
- let cached =
- self.get_or_cache_buffers(obj.id, &obj.vertices, &obj.indices, object_cache);
- rp.set_vertex_buffer(0, cached.vertex_buffer.slice(..));
- rp.set_index_buffer(cached.index_buffer.slice(..), wgpu::IndexFormat::Uint32);
- rp.draw_indexed(0..cached.index_count, 0, 0..1);
- }
- }
-
- /// Encode render pass, copy to staging, submit, wait, readback into dst.
- fn render_and_readback(
- &self,
- res: &mut FrameResources,
- draw_cmds: &[DrawCmd],
- scene: &Scene,
- object_cache: &mut HashMap<ObjectId, CachedObjectBuffers>,
- texture_cache: &mut HashMap<ObjectId, CachedTextureBindGroup>,
- clear_color: wgpu::Color,
- dst: &mut Vec<u8>,
- ) {
- let mut cmd_encoder =
- self.gpu
- .device
- .create_command_encoder(&wgpu::CommandEncoderDescriptor {
- label: Some("frame_encoder"),
- });
-
- self.encode_render_pass(
- &mut cmd_encoder,
- res,
- &res.output_view,
- draw_cmds,
- scene,
- object_cache,
- texture_cache,
- clear_color,
- );
-
- cmd_encoder.copy_texture_to_buffer(
- wgpu::TexelCopyTextureInfo {
- texture: &res.output_texture,
- mip_level: 0,
- origin: wgpu::Origin3d::ZERO,
- aspect: wgpu::TextureAspect::All,
- },
- wgpu::TexelCopyBufferInfo {
- buffer: &res.staging_buffer,
- layout: wgpu::TexelCopyBufferLayout {
- offset: 0,
- bytes_per_row: Some(res.padded_bytes_per_row),
- rows_per_image: Some(res.height),
- },
- },
- wgpu::Extent3d {
- width: res.width,
- height: res.height,
- depth_or_array_layers: 1,
- },
- );
-
- self.gpu.queue.submit(std::iter::once(cmd_encoder.finish()));
- res.staging_buffer
- .slice(..)
- .map_async(wgpu::MapMode::Read, |_| {});
- self.wait_for_gpu();
- res.read_pixels_into(dst);
- }
-
- /// Print progress bar to stderr.
- fn print_progress(
- frame_idx: u32,
- total_frames: u32,
- render_start: &std::time::Instant,
- last_progress: &mut std::time::Instant,
- ) {
- if last_progress.elapsed().as_millis() >= 250 || frame_idx == total_frames - 1 {
- let done = frame_idx + 1;
- let elapsed = render_start.elapsed().as_secs_f64();
- let pct = done as f64 / total_frames as f64;
- let fps_now = if elapsed > 0.0 {
- done as f64 / elapsed
- } else {
- 0.0
- };
- let eta = if pct > 0.0 {
- elapsed / pct - elapsed
- } else {
- 0.0
- };
- let bar_width = 30;
- let filled = (pct * bar_width as f64) as usize;
- let bar: String = "█".repeat(filled) + &"░".repeat(bar_width - filled);
- eprint!(
- "\r [{}] {:>3.0}% | {}/{} | {:.1}s | ~{:.1}s left | {:.0} fps\x1b[K",
- bar,
- pct * 100.0,
- done,
- total_frames,
- elapsed,
- eta,
- fps_now,
- );
- *last_progress = std::time::Instant::now();
- }
- }
-
- /// Unified render loop with N-buffering and frame deduplication.
- ///
- /// With `n_buffers=1`: current synchronous behavior (render, readback, repeat).
- /// With `n_buffers=2+`: GPU render of frame K overlaps with staging readback of frame K-1.
- pub fn render_video<W: FrameWriter>(
- &self,
- scene: &mut Scene,
- timeline: &dyn manimgx_core::timeline_eval::TimelineEval,
- writer: &mut W,
- total_frames: u32,
- fps: u32,
- n_buffers: u32,
- use_nv12: bool,
- check_cancelled: &dyn Fn() -> bool,
- ) {
- if total_frames == 0 {
- return;
- }
-
- let effective_buffers = n_buffers.max(1) as usize;
-
- let nv12_bgl = if use_nv12 {
- Some(&self.nv12_bind_group_layout)
- } else {
- None
- };
-
- let resources: Vec<FrameResources> = (0..effective_buffers)
- .map(|_| {
- FrameResources::new(
- &self.gpu.device,
- scene.width,
- scene.height,
- self.color_format,
- &self.pipelines.camera_bind_group_layout,
- &self.pipelines.model_bind_group_layout,
- scene.objects.len(),
- self.sample_count,
- use_nv12,
- nv12_bgl,
- )
- })
- .collect();
- let mut object_cache: HashMap<ObjectId, CachedObjectBuffers> = HashMap::with_capacity(scene.objects.len());
- let mut texture_cache: HashMap<ObjectId, CachedTextureBindGroup> = HashMap::new();
-
- let alignment = resources[0].uniform_alignment;
- let uniform_size = std::mem::size_of::<ObjectUniform>();
- let cam_size = std::mem::size_of::<CameraUniform>();
- let pixel_size = if use_nv12 {
- resources[0].nv12_size
- } else {
- resources[0].pixel_size
- };
-
- let clear_color = wgpu::Color {
- r: srgb_to_linear(scene.background[0]) as f64,
- g: srgb_to_linear(scene.background[1]) as f64,
- b: srgb_to_linear(scene.background[2]) as f64,
- a: scene.background[3] as f64,
- };
-
- // CPU staging for uniform building and dedup comparison (shared across buffers)
- let mut uniform_staging = vec![0u8; resources[0].uniform_staging.len()];
- let mut prev_cam_bytes = vec![0u8; cam_size];
- let mut prev_uniform_bytes = vec![0u8; uniform_staging.len()];
- let mut prev_draw_count: usize = 0;
- let mut first_frame = true;
- let mut dup_count = 0u32;
- let mut render_count = 0usize;
- let mut pixel_buf = vec![0u8; pixel_size];
-
- // Pending readback queue: buffer indices with submitted but not-yet-read staging data
- let mut pending: std::collections::VecDeque<usize> = std::collections::VecDeque::new();
-
- // Pre-allocate draw command buffer (reused each frame)
- let mut draw_cmds: Vec<DrawCmd> = Vec::with_capacity(scene.objects.len());
-
- let render_start = std::time::Instant::now();
- let mut last_progress = std::time::Instant::now();
-
- for frame_idx in 0..total_frames {
- Self::print_progress(frame_idx, total_frames, &render_start, &mut last_progress);
- if check_cancelled() { eprintln!("\n Render interrupted at frame {}/{}", frame_idx, total_frames); break; }
-
- let time = frame_idx as f32 / fps as f32;
- timeline.evaluate(scene, time);
-
- let view_proj = scene.camera.view_projection_matrix(scene.aspect_ratio());
- let cam_uniform = CameraUniform {
- view_proj: view_proj.to_cols_array_2d(),
- };
- let cam_bytes = bytemuck::bytes_of(&cam_uniform);
-
- // Build draw commands + object uniforms into shared staging buffer
- draw_cmds.clear();
- for (obj_idx, obj) in scene.objects.iter().enumerate() {
- if obj.material.opacity <= 0.0 {
- continue;
- }
- let slot = draw_cmds.len();
- let byte_offset = slot * alignment;
- let mut material_color = obj.material.color;
- material_color[3] = obj.material.color[3] * obj.material.opacity;
- let uniform = ObjectUniform {
- model: obj.transform.to_matrix().to_cols_array_2d(),
- material_color,
- use_vertex_colors: if obj.material.use_vertex_colors { 1 } else { 0 },
- _pad: [0; 3],
- };
- uniform_staging[byte_offset..byte_offset + uniform_size]
- .copy_from_slice(bytemuck::bytes_of(&uniform));
- draw_cmds.push(DrawCmd {
- obj_idx,
- uniform_slot: slot,
- });
- }
-
- let total_uniform_bytes = draw_cmds.len() * alignment;
-
- // Frame deduplication: skip GPU render when scene state is unchanged
- let is_dup = !first_frame
- && draw_cmds.len() == prev_draw_count
- && cam_bytes == &prev_cam_bytes[..]
- && (total_uniform_bytes == 0
- || uniform_staging[..total_uniform_bytes]
- == prev_uniform_bytes[..total_uniform_bytes]);
-
- if is_dup {
- writer.write_duplicate();
- dup_count += 1;
- continue;
- }
-
- let buf_idx = render_count % effective_buffers;
-
- {
- // Staging readback path with N-buffering
- // Drain oldest pending readback if all buffers are in use
- if pending.len() >= effective_buffers {
- let drain_idx = pending.pop_front().unwrap();
- self.wait_for_gpu();
- if use_nv12 {
- resources[drain_idx].read_nv12_into(&mut pixel_buf);
- } else {
- resources[drain_idx].read_pixels_into(&mut pixel_buf);
- }
- writer.write_frame(&pixel_buf);
- }
-
- let res = &resources[buf_idx];
- self.gpu
- .queue
- .write_buffer(&res.camera_buffer, 0, cam_bytes);
- if total_uniform_bytes > 0 {
- self.gpu.queue.write_buffer(
- &res.object_uniform_buffer,
- 0,
- &uniform_staging[..total_uniform_bytes],
- );
- }
-
- // Encode render pass + copy to staging + submit (don't wait yet)
- let mut cmd_encoder =
- self.gpu
- .device
- .create_command_encoder(&wgpu::CommandEncoderDescriptor {
- label: Some("frame_encoder"),
- });
- self.encode_render_pass(
- &mut cmd_encoder,
- res,
- &res.output_view,
- &draw_cmds,
- scene,
- &mut object_cache,
- &mut texture_cache,
- clear_color,
- );
-
- if use_nv12 {
- // Compute pass: MSAA resolve + NV12 conversion
- {
- let mut cpass = cmd_encoder.begin_compute_pass(
- &wgpu::ComputePassDescriptor {
- label: Some("nv12_convert"),
- timestamp_writes: None,
- },
- );
- cpass.set_pipeline(&self.nv12_pipeline);
- cpass.set_bind_group(0, res.nv12_bind_group.as_ref().unwrap(), &[]);
- cpass.dispatch_workgroups(
- res.width.div_ceil(32),
- res.height.div_ceil(16),
- 1,
- );
- }
- // Copy storage → staging
- let nv12_sz = res.nv12_size as u64;
- cmd_encoder.copy_buffer_to_buffer(
- res.nv12_storage_buffer.as_ref().unwrap(),
- 0,
- res.nv12_staging_buffer.as_ref().unwrap(),
- 0,
- nv12_sz,
- );
- self.gpu.queue.submit(std::iter::once(cmd_encoder.finish()));
- res.nv12_staging_buffer
- .as_ref()
- .unwrap()
- .slice(..)
- .map_async(wgpu::MapMode::Read, |_| {});
- } else {
- cmd_encoder.copy_texture_to_buffer(
- wgpu::TexelCopyTextureInfo {
- texture: &res.output_texture,
- mip_level: 0,
- origin: wgpu::Origin3d::ZERO,
- aspect: wgpu::TextureAspect::All,
- },
- wgpu::TexelCopyBufferInfo {
- buffer: &res.staging_buffer,
- layout: wgpu::TexelCopyBufferLayout {
- offset: 0,
- bytes_per_row: Some(res.padded_bytes_per_row),
- rows_per_image: Some(res.height),
- },
- },
- wgpu::Extent3d {
- width: res.width,
- height: res.height,
- depth_or_array_layers: 1,
- },
- );
- self.gpu.queue.submit(std::iter::once(cmd_encoder.finish()));
- // Issue map_async immediately — overlap GPU work with CPU readback of previous frames
- res.staging_buffer
- .slice(..)
- .map_async(wgpu::MapMode::Read, |_| {});
- }
- pending.push_back(buf_idx);
- }
-
- // Update dedup state
- prev_cam_bytes.copy_from_slice(cam_bytes);
- if total_uniform_bytes > 0 {
- prev_uniform_bytes[..total_uniform_bytes]
- .copy_from_slice(&uniform_staging[..total_uniform_bytes]);
- }
- prev_draw_count = draw_cmds.len();
- first_frame = false;
- render_count += 1;
- }
-
- // Drain remaining pending readbacks
- while let Some(drain_idx) = pending.pop_front() {
- self.wait_for_gpu();
- if use_nv12 {
- resources[drain_idx].read_nv12_into(&mut pixel_buf);
- } else {
- resources[drain_idx].read_pixels_into(&mut pixel_buf);
- }
- writer.write_frame(&pixel_buf);
- }
-
- writer.finish();
-
- eprintln!();
- let rendered = total_frames - dup_count;
- eprintln!(
- " frames: {} rendered, {} duplicates skipped ({:.0}%)",
- rendered,
- dup_count,
- dup_count as f64 / total_frames as f64 * 100.0,
- );
- }
-
- /// Render video using in-process x264 encoding with CPU-side NV12 buffer pool.
- ///
- /// GPU renders → NV12 compute → staging readback → pool Vec<u8> → x264 encoder thread.
- /// No ffmpeg subprocess. Pool buffers are pinned (never reallocated) so raw pointers
- /// sent to the encoder thread remain valid.
- #[allow(clippy::too_many_arguments)]
- pub fn render_video_x264(
- &self,
- scene: &mut Scene,
- timeline: &dyn manimgx_core::timeline_eval::TimelineEval,
- output: &str,
- total_frames: u32,
- fps: u32,
- n_buffers: u32,
- preset: &str,
- crf: u32,
- muxer: &str,
- check_cancelled: &dyn Fn() -> bool,
- ) {
- use manimgx_encode::{X264FrameMsg, X264Writer};
- use std::collections::VecDeque;
- use std::sync::mpsc;
-
- if total_frames == 0 {
- return;
- }
-
- let n = n_buffers.max(1) as usize;
- let w = scene.width;
- let h = scene.height;
- let nv12_size = (w * h * 3 / 2) as usize;
-
- let nv12_bgl = Some(&self.nv12_bind_group_layout);
-
- let resources: Vec<FrameResources> = (0..n)
- .map(|_| {
- FrameResources::new(
- &self.gpu.device,
- w,
- h,
- self.color_format,
- &self.pipelines.camera_bind_group_layout,
- &self.pipelines.model_bind_group_layout,
- scene.objects.len(),
- self.sample_count,
- true,
- nv12_bgl,
- )
- })
- .collect();
- let mut object_cache: HashMap<ObjectId, CachedObjectBuffers> = HashMap::with_capacity(scene.objects.len());
- let mut texture_cache: HashMap<ObjectId, CachedTextureBindGroup> = HashMap::new();
-
- let alignment = resources[0].uniform_alignment;
- let uniform_size = std::mem::size_of::<ObjectUniform>();
- let cam_size = std::mem::size_of::<CameraUniform>();
-
- // CPU-side NV12 buffer pool (elastic, decoupled from GPU slots)
- let pool_count = 8usize;
- let (release_tx, release_rx) = mpsc::channel::<usize>();
- let mut pool_buffers: Vec<Vec<u8>> = (0..pool_count).map(|_| vec![0u8; nv12_size]).collect();
- let mut pool_available: VecDeque<usize> = (0..pool_count).collect();
-
- // In-process x264 encoder (spawns encoder thread)
- let writer = X264Writer::new(output, w, h, fps, preset, crf, release_tx, muxer);
-
- let clear_color = wgpu::Color {
- r: srgb_to_linear(scene.background[0]) as f64,
- g: srgb_to_linear(scene.background[1]) as f64,
- b: srgb_to_linear(scene.background[2]) as f64,
- a: scene.background[3] as f64,
- };
-
- // CPU staging for uniform building and dedup comparison
- let mut uniform_staging = vec![0u8; resources[0].uniform_staging.len()];
- let mut prev_cam_bytes = vec![0u8; cam_size];
- let mut prev_uniform_bytes = vec![0u8; uniform_staging.len()];
- let mut prev_draw_count: usize = 0;
- let mut first_frame = true;
- let mut dup_count = 0u32;
- let mut render_count = 0usize;
-
- // N-buffering: pending queue tracks (gpu_slot_idx, pool_buf_idx)
- let mut pending: VecDeque<(usize, usize)> = VecDeque::new();
-
- // Pre-allocate draw command buffer (reused each frame)
- let mut draw_cmds: Vec<DrawCmd> = Vec::with_capacity(scene.objects.len());
-
- let render_start = std::time::Instant::now();
- let mut last_progress = std::time::Instant::now();
-
- // Helper: acquire a pool buffer index
- let acquire_pool = |available: &mut VecDeque<usize>, rx: &mpsc::Receiver<usize>| -> usize {
- // Drain all released buffers (non-blocking)
- while let Ok(idx) = rx.try_recv() {
- available.push_back(idx);
- }
- if let Some(idx) = available.pop_front() {
- return idx;
- }
- // Pool exhausted — block until encoder releases one
- rx.recv().expect("x264 encoder thread died")
- };
-
- for frame_idx in 0..total_frames {
- Self::print_progress(frame_idx, total_frames, &render_start, &mut last_progress);
- if check_cancelled() {
- eprintln!("\n Render interrupted at frame {}/{}", frame_idx, total_frames);
- break;
- }
-
- let time = frame_idx as f32 / fps as f32;
- timeline.evaluate(scene, time);
-
- let view_proj = scene.camera.view_projection_matrix(scene.aspect_ratio());
- let cam_uniform = CameraUniform {
- view_proj: view_proj.to_cols_array_2d(),
- };
- let cam_bytes = bytemuck::bytes_of(&cam_uniform);
-
- // Build draw commands + object uniforms
- draw_cmds.clear();
- for (obj_idx, obj) in scene.objects.iter().enumerate() {
- if obj.material.opacity <= 0.0 {
- continue;
- }
- let slot = draw_cmds.len();
- let byte_offset = slot * alignment;
- let mut material_color = obj.material.color;
- material_color[3] = obj.material.color[3] * obj.material.opacity;
- let uniform = ObjectUniform {
- model: obj.transform.to_matrix().to_cols_array_2d(),
- material_color,
- use_vertex_colors: if obj.material.use_vertex_colors { 1 } else { 0 },
- _pad: [0; 3],
- };
- uniform_staging[byte_offset..byte_offset + uniform_size]
- .copy_from_slice(bytemuck::bytes_of(&uniform));
- draw_cmds.push(DrawCmd {
- obj_idx,
- uniform_slot: slot,
- });
- }
-
- let total_uniform_bytes = draw_cmds.len() * alignment;
-
- // Frame deduplication
- let is_dup = !first_frame
- && draw_cmds.len() == prev_draw_count
- && cam_bytes == &prev_cam_bytes[..]
- && (total_uniform_bytes == 0
- || uniform_staging[..total_uniform_bytes]
- == prev_uniform_bytes[..total_uniform_bytes]);
-
- if is_dup {
- // Drain ALL pending GPU slots before encoding dup
- while let Some((drain_slot, drain_buf)) = pending.pop_front() {
- self.wait_for_gpu();
- resources[drain_slot].read_nv12_into_slice(&mut pool_buffers[drain_buf]);
-
- writer.send(X264FrameMsg::Frame {
- ptr: pool_buffers[drain_buf].as_ptr(),
- len: nv12_size,
- pts: (frame_idx as i64) - (pending.len() as i64) - 1,
- buf_idx: drain_buf,
- });
- }
-
- writer.send(X264FrameMsg::Dup {
- pts: frame_idx as i64,
- });
- dup_count += 1;
- continue;
- }
-
- let slot_idx = render_count % n;
-
- // Drain oldest pending slot if all GPU slots are in use
- if pending.len() >= n {
- let (drain_slot, drain_buf) = pending.pop_front().unwrap();
- self.wait_for_gpu();
- resources[drain_slot].read_nv12_into_slice(&mut pool_buffers[drain_buf]);
-
- writer.send(X264FrameMsg::Frame {
- ptr: pool_buffers[drain_buf].as_ptr(),
- len: nv12_size,
- pts: (frame_idx as i64) - (n as i64),
- buf_idx: drain_buf,
- });
- }
-
- // Acquire a pool buffer for NV12 output
- let buf_idx = acquire_pool(&mut pool_available, &release_rx);
-
- // Write uniforms to GPU
- let res = &resources[slot_idx];
- self.gpu
- .queue
- .write_buffer(&res.camera_buffer, 0, cam_bytes);
- if total_uniform_bytes > 0 {
- self.gpu.queue.write_buffer(
- &res.object_uniform_buffer,
- 0,
- &uniform_staging[..total_uniform_bytes],
- );
- }
-
- // Encode render pass + NV12 compute + staging copy + submit
- let mut cmd_encoder =
- self.gpu
- .device
- .create_command_encoder(&wgpu::CommandEncoderDescriptor {
- label: Some("x264_frame"),
- });
- self.encode_render_pass(
- &mut cmd_encoder,
- res,
- &res.output_view,
- &draw_cmds,
- scene,
- &mut object_cache,
- &mut texture_cache,
- clear_color,
- );
-
- // NV12 compute pass
- {
- let mut cpass = cmd_encoder.begin_compute_pass(
- &wgpu::ComputePassDescriptor {
- label: Some("nv12_convert"),
- timestamp_writes: None,
- },
- );
- cpass.set_pipeline(&self.nv12_pipeline);
- cpass.set_bind_group(0, res.nv12_bind_group.as_ref().unwrap(), &[]);
- cpass.dispatch_workgroups(
- res.width.div_ceil(32),
- res.height.div_ceil(16),
- 1,
- );
- }
- // Copy storage → staging
- let nv12_sz = res.nv12_size as u64;
- cmd_encoder.copy_buffer_to_buffer(
- res.nv12_storage_buffer.as_ref().unwrap(),
- 0,
- res.nv12_staging_buffer.as_ref().unwrap(),
- 0,
- nv12_sz,
- );
- self.gpu.queue.submit(std::iter::once(cmd_encoder.finish()));
- res.nv12_staging_buffer
- .as_ref()
- .unwrap()
- .slice(..)
- .map_async(wgpu::MapMode::Read, |_| {});
-
- pending.push_back((slot_idx, buf_idx));
-
- // Update dedup state
- prev_cam_bytes.copy_from_slice(cam_bytes);
- if total_uniform_bytes > 0 {
- prev_uniform_bytes[..total_uniform_bytes]
- .copy_from_slice(&uniform_staging[..total_uniform_bytes]);
- }
- prev_draw_count = draw_cmds.len();
- first_frame = false;
- render_count += 1;
- }
-
- // Drain remaining pending slots
- let remaining = pending.len();
- let mut drain_count = 0;
- while let Some((drain_slot, drain_buf)) = pending.pop_front() {
- self.wait_for_gpu();
- resources[drain_slot].read_nv12_into_slice(&mut pool_buffers[drain_buf]);
-
- writer.send(X264FrameMsg::Frame {
- ptr: pool_buffers[drain_buf].as_ptr(),
- len: nv12_size,
- pts: (total_frames as i64) - (remaining as i64) + (drain_count as i64),
- buf_idx: drain_buf,
- });
- drain_count += 1;
- }
-
- // Flush encoder, join thread, finalize MP4
- writer.finish();
-
- eprintln!();
- let rendered = total_frames - dup_count;
- eprintln!(
- " frames: {} rendered, {} duplicates skipped ({:.0}%)",
- rendered,
- dup_count,
- dup_count as f64 / total_frames as f64 * 100.0,
- );
- }
-
- /// Render a single frame, returning RGBA pixel data (used for PNG export).
- pub fn render_frame(&self, scene: &Scene) -> Vec<u8> {
- let mut res = FrameResources::new(
- &self.gpu.device,
- scene.width,
- scene.height,
- self.color_format,
- &self.pipelines.camera_bind_group_layout,
- &self.pipelines.model_bind_group_layout,
- scene.objects.len(),
- self.sample_count,
- false,
- None,
- );
- let mut object_cache: HashMap<ObjectId, CachedObjectBuffers> = HashMap::with_capacity(scene.objects.len());
- let mut texture_cache: HashMap<ObjectId, CachedTextureBindGroup> = HashMap::new();
-
- // Camera
- let view_proj = scene.camera.view_projection_matrix(scene.aspect_ratio());
- let camera_uniform = CameraUniform {
- view_proj: view_proj.to_cols_array_2d(),
- };
- self.gpu.queue.write_buffer(
- &res.camera_buffer,
- 0,
- bytemuck::cast_slice(&[camera_uniform]),
- );
-
- // Object uniforms
- let alignment = res.uniform_alignment;
- let uniform_size = std::mem::size_of::<ObjectUniform>();
- let mut draw_cmds: Vec<DrawCmd> = Vec::with_capacity(scene.objects.len());
-
- for (obj_idx, obj) in scene.objects.iter().enumerate() {
- if obj.material.opacity <= 0.0 {
- continue;
- }
- let slot = draw_cmds.len();
- let offset = slot * alignment;
- let mut material_color = obj.material.color;
- material_color[3] = obj.material.color[3] * obj.material.opacity;
- let uniform = ObjectUniform {
- model: obj.transform.to_matrix().to_cols_array_2d(),
- material_color,
- use_vertex_colors: if obj.material.use_vertex_colors { 1 } else { 0 },
- _pad: [0; 3],
- };
- res.uniform_staging[offset..offset + uniform_size]
- .copy_from_slice(bytemuck::bytes_of(&uniform));
- draw_cmds.push(DrawCmd {
- obj_idx,
- uniform_slot: slot,
- });
- }
-
- if !draw_cmds.is_empty() {
- let total_bytes = draw_cmds.len() * alignment;
- self.gpu.queue.write_buffer(
- &res.object_uniform_buffer,
- 0,
- &res.uniform_staging[..total_bytes],
- );
- }
-
- let clear_color = wgpu::Color {
- r: srgb_to_linear(scene.background[0]) as f64,
- g: srgb_to_linear(scene.background[1]) as f64,
- b: srgb_to_linear(scene.background[2]) as f64,
- a: scene.background[3] as f64,
- };
-
- let mut pixels = Vec::with_capacity(res.pixel_size);
- self.render_and_readback(
- &mut res,
- &draw_cmds,
- scene,
- &mut object_cache,
- &mut texture_cache,
- clear_color,
- &mut pixels,
- );
- pixels
- }
-
- /// Render a single frame and save as PNG (requires `png_debug` feature).
- #[cfg(feature = "png_debug")]
- pub fn render_to_png(&self, scene: &Scene, path: &str) {
- let pixels = self.render_frame(scene);
- let img = image::RgbaImage::from_raw(scene.width, scene.height, pixels)
- .expect("Invalid image data");
- img.save(path).expect("Failed to save PNG");
- log::info!("Saved PNG: {}", path);
- }
-
- /// Stub when `png_debug` is not enabled — panics with a clear message.
- #[cfg(not(feature = "png_debug"))]
- pub fn render_to_png(&self, _scene: &Scene, _path: &str) {
- panic!("render_to_png requires the `png_debug` feature on manimgx-render");
- }
-}
diff --git a/rust/bridge/shaders/default.wgsl b/rust/bridge/shaders/default.wgsl
deleted file mode 100644
index 310e11c4..00000000
--- a/rust/bridge/shaders/default.wgsl
+++ /dev/null
@@ -1,56 +0,0 @@
-struct CameraUniform {
- view_proj: mat4x4<f32>,
-};
-
-struct ObjectUniform {
- model: mat4x4<f32>,
- material_color: vec4<f32>,
- use_vertex_colors: u32,
-};
-
-@group(0) @binding(0) var<uniform> camera: CameraUniform;
-@group(1) @binding(0) var<uniform> object: ObjectUniform;
-
-struct VertexInput {
- @location(0) position: vec3<f32>,
- @location(1) normal: vec3<f32>,
- @location(2) color: vec4<f32>,
-};
-
-struct VertexOutput {
- @builtin(position) clip_position: vec4<f32>,
- @location(0) world_normal: vec3<f32>,
- @location(1) color: vec4<f32>,
-};
-
-@vertex
-fn vs_main(in: VertexInput) -> VertexOutput {
- var out: VertexOutput;
- let world_pos = object.model * vec4<f32>(in.position, 1.0);
- out.clip_position = camera.view_proj * world_pos;
- // Transform normal (ignoring non-uniform scale for simplicity)
- out.world_normal = (object.model * vec4<f32>(in.normal, 0.0)).xyz;
- out.color = in.color;
- return out;
-}
-
-@fragment
-fn fs_main(@builtin(front_facing) front_facing: bool, in: VertexOutput) -> @location(0) vec4<f32> {
- let light_dir = normalize(vec3<f32>(0.5, 1.0, 0.3));
- var normal = normalize(in.world_normal);
- if (!front_facing) {
- normal = -normal;
- }
- let ndotl = max(dot(normal, light_dir), 0.0);
- let ambient = 0.3;
- let diffuse = ndotl * 0.7;
- let lighting = ambient + diffuse;
-
- var base_color: vec4<f32>;
- if (object.use_vertex_colors > 0u) {
- base_color = in.color * object.material_color;
- } else {
- base_color = object.material_color;
- }
- return vec4<f32>(base_color.rgb * lighting, base_color.a);
-}
diff --git a/rust/bridge/shaders/metal/default.metal b/rust/bridge/shaders/metal/default.metal
deleted file mode 100644
index 056bfe9c..00000000
--- a/rust/bridge/shaders/metal/default.metal
+++ /dev/null
@@ -1,47 +0,0 @@
-// 3D lit shading — port of default.wgsl.
-// Diffuse + ambient lighting, double-sided via [[front_facing]].
-
-#include "types.h"
-
-struct VertexOut {
- float4 position [[position]];
- float3 world_normal;
- float4 color;
-};
-
-vertex VertexOut vs_main(
- VertexIn in [[stage_in]],
- constant CameraUniform& camera [[buffer(1)]],
- constant ObjectUniform& object [[buffer(2)]]
-) {
- VertexOut out;
- float4 world_pos = object.model * float4(in.position, 1.0);
- out.position = camera.view_proj * world_pos;
- out.world_normal = (object.model * float4(in.normal, 0.0)).xyz;
- out.color = in.color;
- return out;
-}
-
-fragment float4 fs_main(
- VertexOut in [[stage_in]],
- bool front_facing [[front_facing]],
- constant ObjectUniform& object [[buffer(2)]]
-) {
- float3 light_dir = normalize(float3(0.5, 1.0, 0.3));
- float3 normal = normalize(in.world_normal);
- if (!front_facing) {
- normal = -normal;
- }
- float ndotl = max(dot(normal, light_dir), 0.0);
- float ambient = 0.3;
- float diffuse = ndotl * 0.7;
- float lighting = ambient + diffuse;
-
- float4 base_color;
- if (object.use_vertex_colors > 0u) {
- base_color = in.color * object.material_color;
- } else {
- base_color = object.material_color;
- }
- return float4(base_color.rgb * lighting, base_color.a);
-}
diff --git a/rust/engine/Cargo.toml b/rust/engine/Cargo.toml
new file mode 100644
index 00000000..6003766d
--- /dev/null
+++ b/rust/engine/Cargo.toml
@@ -0,0 +1,92 @@
+[package]
+name = "manimgx-engine"
+version = "0.1.0"
+edition = "2024"
+authors = ["Sina Atalay <[email protected]>", "Abdullah Geduk <[email protected]>"]
+license = "MIT"
+publish = false
+description = "manimgx's engine: typesets with Typst, draws blends of shapes on the GPU and encodes them to MP4."
+
+[lib]
+name = "_engine"
+crate-type = ["cdylib"]
+
+# One engine, three builds. Native (the Python extension): everything, the player in a window
+# too. In Pyodide (the pyemscripten wheel): the Python extension without the GPU (typesetting,
+# content keys, sound read, the take a scene records). In the browser (wasm32-unknown-unknown):
+# the player on a page's canvas, drawing with WebGPU.
+[features]
+default = ["python", "render", "export", "typeset", "window"]
+python = ["dep:pyo3", "dep:ffmpeg", "dep:wasm-bindgen-cli-support", "dep:zstd"]
+render = ["dep:wgpu", "dep:ash", "dep:libc"]
+export = ["render", "dep:rusty_aac", "dep:x264"]
+typeset = ["dep:typst", "dep:typst-kit", "dep:typst-layout", "dep:ttf-parser", "dep:unicode-segmentation", "dep:mitex", "dep:mitex-spec-gen", "dep:bincode", "dep:memmap2"]
+# the player (src/player.rs): takes played on a clock, with a face and a sound, on any screen
+player = ["render", "dep:ruzstd", "dep:serde", "dep:serde_json", "dep:rustybuzz", "dep:ttf-parser", "dep:unicode-bidi", "dep:unicode-segmentation", "dep:web-time"]
+window = ["python", "typeset", "player", "dep:winit", "dep:cpal"]
+web = ["player", "dep:wasm-bindgen", "dep:wasm-bindgen-futures", "dep:js-sys", "dep:web-sys", "dep:console_error_panic_hook"]
+
+[dependencies]
+bytemuck = { version = "1.25", features = ["derive", "extern_crate_alloc", "min_const_generics"] }
+xxhash-rust = { version = "0.8.19", features = ["xxh3"] } # content keys: what names an upload
+pyo3 = { version = "0.29.2", features = ["abi3-py313", "extension-module"], optional = true }
+wgpu = { version = "30.0.1", optional = true }
+# the typesetter: Typst as a library, its layout read directly (see src/typeset.rs)
+typst = { version = "0.15.1", optional = true }
+typst-kit = { version = "0.15.1", default-features = false, features = ["embedded-fonts", "scan-fonts"], optional = true }
+typst-layout = { version = "0.15.1", optional = true }
+ttf-parser = { version = "0.25.1", optional = true } # glyph outlines and ligature carets, from the fonts Typst loaded
+unicode-segmentation = { version = "1.12", optional = true } # graphemes: the characters a ligature's colors divide
+bincode = { version = "1.3", optional = true } # the system fonts' scan, cached on disk
+memmap2 = { version = "0.9", optional = true } # system fonts mapped, not read whole (a CJK font is 60 MB)
+rusty_aac = { version = "0.5.0", optional = true } # sound out: AAC-LC in pure Rust (src/aac.rs)
+# sound in: the common audio files decoded by FFmpeg, built from its source (src/audio.rs)
+ffmpeg = { path = "../ffmpeg", optional = true }
+# LaTeX → Typst, natively; its command spec is made from mitex's package, which Typst reads
+# from the engine (../mitex-spec-gen, patched in at the workspace's root)
+mitex = { git = "https://github.com/mitex-rs/mitex", tag = "0.2.7", optional = true }
+mitex-spec-gen = { path = "../mitex-spec-gen", optional = true }
+# the H.264 encoder: x264 built from its source (fetched), with NASM from its source
+x264 = { path = "../x264", optional = true }
+# a take's arrays compressed (src/pack.rs), and decompressed in the browser in pure Rust
+zstd = { version = "0.14", default-features = false, optional = true }
+ruzstd = { version = "0.9", optional = true }
+# the player's face set in lines, shaped as Typst shapes them (src/text.rs), each line's runs in
+# reading order; its notes read; its clock the same in a window and a page
+rustybuzz = { version = "0.20.1", optional = true }
+unicode-bidi = { version = "0.3.18", optional = true }
+serde = { version = "1.0.229", features = ["derive"], optional = true }
+serde_json = { version = "1.0.151", optional = true }
+web-time = { version = "1.1", optional = true }
+# the player's bindings in the browser; its JS is made by the same version of wasm-bindgen (build.rs)
+wasm-bindgen = { version = "=0.2.128", optional = true }
+wasm-bindgen-futures = { version = "0.4", optional = true }
+js-sys = { version = "0.3", optional = true }
+web-sys = { version = "0.3", features = ["HtmlCanvasElement", "AudioContext", "AudioContextState", "BaseAudioContext", "AudioBuffer", "AudioBufferSourceNode", "AudioScheduledSourceNode", "AudioNode", "AudioParam", "GainNode", "AudioDestinationNode"], optional = true }
+console_error_panic_hook = { version = "0.1", optional = true }
+
+[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
+pollster = "1.0.1" # a GPU brought up by blocking on it
+winit = { version = "0.30.13", optional = true } # the window `manimgx preview` plays in
+
+# the window's sound: the system's own audio (CoreAudio, WASAPI); on Linux it would link ALSA
+[target.'cfg(not(any(target_os = "linux", target_arch = "wasm32")))'.dependencies]
+cpal = { version = "0.18.2", optional = true }
+
+# Mesa's lavapipe, which a Linux wheel bundles, loaded where no GPU driver is (src/lavapipe.rs):
+# its Vulkan entry points through ash (wgpu-hal's), and the engine's own folder through dladdr
+[target.'cfg(target_os = "linux")'.dependencies]
+ash = { version = "0.38", optional = true }
+libc = { version = "0.2", optional = true }
+
+[dev-dependencies]
+zstd = { version = "0.14", default-features = false }
+ruzstd = "0.9"
+
+[build-dependencies]
+wasm-bindgen-cli-support = { version = "=0.2.128", optional = true }
+
+[lints.clippy]
+correctness = { level = "deny", priority = -1 }
+suspicious = { level = "warn", priority = -1 }
+perf = { level = "warn", priority = -1 }
diff --git a/rust/engine/build.rs b/rust/engine/build.rs
new file mode 100644
index 00000000..1b8ff814
--- /dev/null
+++ b/rust/engine/build.rs
@@ -0,0 +1,67 @@
+//! The Python extension's build. Pyodide's (the browser's wheel) carries the player for a page —
+//! this crate for wasm32-unknown-unknown with its `web` feature, the same player as a window's,
+//! drawing with WebGPU — built beside it (`_engine.web()`), which manimgx's element in the browser
+//! plays films with. x264 is built by its own crate (`../x264`).
+
+#[cfg(feature = "python")]
+use std::path::{Path, PathBuf};
+
+fn main() {
+ println!("cargo::rustc-check-cfg=cfg(web_player)");
+ #[cfg(feature = "python")]
+ web_player();
+}
+
+/// The player for a page, as the browser loads it: `engine.js` and `engine_bg.wasm`
+/// (wasm-bindgen's JS and module), built for Pyodide's extension by a cargo of its own (a target
+/// directory of its own, in the workspace's) whenever this crate's sources change, into OUT_DIR,
+/// where the extension takes them in (`cfg(web_player)`). Without the wasm32-unknown-unknown
+/// target, a warning: the extension builds without it, and the page says what it misses. A native
+/// extension carries none: its films are played in a window (`window`).
+#[cfg(feature = "python")]
+fn web_player() {
+ if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("emscripten") {
+ return;
+ }
+ let crate_dir = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap());
+ println!("cargo:rerun-if-changed={}", crate_dir.join("src").display());
+ // the workspace's target directory: its root is this crate's parent (rust/), in a clone and in
+ // the source distribution alike
+ let target = std::env::var_os("CARGO_TARGET_DIR")
+ .map_or_else(|| crate_dir.join("../target"), PathBuf::from)
+ .join("web-player");
+ let built = std::process::Command::new(std::env::var("CARGO").unwrap())
+ .args(["build", "--lib", "--release", "--target", "wasm32-unknown-unknown", "--no-default-features", "--features", "web"])
+ .arg("--target-dir")
+ .arg(&target)
+ .current_dir(&crate_dir)
+ // this build's own flags are for the extension's target (Pyodide's link arguments)
+ .env_remove("RUSTFLAGS")
+ .env_remove("CARGO_ENCODED_RUSTFLAGS")
+ .env_remove("CARGO_BUILD_TARGET")
+ .status();
+ let module = target.join("wasm32-unknown-unknown/release/_engine.wasm");
+ if !built.is_ok_and(|s| s.success()) || !module.exists() {
+ println!("cargo:warning=the player for a page (manimgx in the browser) was not built: `rustup target add wasm32-unknown-unknown`");
+ return;
+ }
+ match bindgen(&module, Path::new(&std::env::var("OUT_DIR").unwrap())) {
+ Ok(()) => println!("cargo:rustc-cfg=web_player"),
+ Err(error) => println!("cargo:warning=the player's JS was not made: {error}"),
+ }
+}
+
+#[cfg(feature = "python")]
+fn bindgen(module: &Path, out: &Path) -> Result<(), String> {
+ wasm_bindgen_cli_support::Bindgen::new()
+ .input_path(module)
+ .out_name("engine")
+ .web(true)
+ .map_err(|e| e.to_string())?
+ .typescript(false)
+ .omit_default_module_path(true)
+ .remove_name_section(true)
+ .remove_producers_section(true)
+ .generate(out)
+ .map_err(|e| e.to_string())
+}
diff --git a/rust/engine/src/lib.rs b/rust/engine/src/lib.rs
new file mode 100644
index 00000000..3b67ed62
--- /dev/null
+++ b/rust/engine/src/lib.rs
@@ -0,0 +1,65 @@
+//! manimgx's engine: draws blends of shapes on the GPU (`render`) and typesets with Typst
+//! (`typeset`).
+//!
+//! It is Python's extension module (`python`), which also reads sound (`audio`): natively with
+//! the GPU, a film's video encoded by x264, its sound as AAC (`export`); in Pyodide without it,
+//! a scene's frames recorded as a take (`take`: its arrays coded against the ones they
+//! replace, `pack`). A take is played by the player (`player`: a projector of takes, `project`,
+//! on a clock, with a face, `chrome`, and a sound, `speaker`), the same on two screens: a window
+//! on this machine (`window`) and, the engine compiled to WebAssembly, a page's canvas (`web`).
+
+#[cfg(feature = "export")]
+mod aac;
+#[cfg(feature = "python")]
+mod audio;
+#[cfg(feature = "player")]
+mod chrome;
+#[cfg(feature = "export")]
+mod encode;
+mod environment;
+#[cfg(feature = "export")]
+mod export;
+#[cfg(feature = "export")]
+mod mp4;
+mod pack;
+#[cfg(feature = "player")]
+mod player;
+#[cfg(feature = "player")]
+mod project;
+#[cfg(feature = "python")]
+mod python;
+#[cfg(feature = "player")]
+mod speaker;
+#[cfg(feature = "render")]
+mod render;
+mod take;
+#[cfg(feature = "player")]
+mod text;
+#[cfg(feature = "typeset")]
+mod typeset;
+#[cfg(feature = "web")]
+mod web;
+#[cfg(feature = "window")]
+mod window;
+
+/// The content key of some bytes, taken as one stream: xxh3, 64 bits, never 0 (reserved). What
+/// names an upload, so that equal content is uploaded once.
+pub fn digest<'a>(parts: impl IntoIterator<Item = &'a [u8]>) -> u64 {
+ let mut hasher = xxhash_rust::xxh3::Xxh3::new();
+ for part in parts {
+ hasher.update(part);
+ }
+ hasher.digest().max(1)
+}
+
+/// A camera's view, drawn into a texture that later views sample by its key: (key, width,
+/// height, view, records).
+pub(crate) type CameraView = (u64, u32, u32, Vec<u8>, Vec<u8>);
+
+/// Bytes as the items they hold (`what` names them in the error).
+pub(crate) fn read<T: bytemuck::Pod>(bytes: &[u8], what: &str) -> Result<Vec<T>, String> {
+ if !bytes.len().is_multiple_of(size_of::<T>()) {
+ return Err(format!("{what}: {} bytes is not a whole number of items", bytes.len()));
+ }
+ Ok(bytemuck::pod_collect_to_vec(bytes))
+}
diff --git a/rust/src/camera.rs b/rust/src/camera.rs
deleted file mode 100644
index 9938803d..00000000
--- a/rust/src/camera.rs
+++ /dev/null
@@ -1,52 +0,0 @@
-use numpy::PyArray1;
-use pyo3::prelude::*;
-
-#[pyclass]
-pub struct Camera {
- #[pyo3(get, set)]
- pub frame_height: f32,
- #[pyo3(get, set)]
- pub background: (u8, u8, u8),
- pub position: [f32; 3],
- pub quaternion: [f32; 4],
- #[pyo3(get, set)]
- pub projection: u8, // 0 = orthographic (default), 1 = perspective
- #[pyo3(get, set)]
- pub fov: f32, // field of view in degrees, default 45.0, used when projection=1
-}
-
-#[pymethods]
-impl Camera {
- #[new]
- #[pyo3(signature = (*, frame_height=8.0, background=(0, 0, 0), projection=0, fov=45.0))]
- fn new(frame_height: f32, background: (u8, u8, u8), projection: u8, fov: f32) -> Self {
- Camera {
- frame_height,
- background,
- position: [0.0, 0.0, 0.0],
- quaternion: [0.0, 0.0, 0.0, 1.0],
- projection,
- fov,
- }
- }
-
- #[getter]
- fn position<'py>(&self, py: Python<'py>) -> Bound<'py, PyArray1<f32>> {
- PyArray1::from_slice(py, &self.position)
- }
-
- #[setter]
- fn set_position(&mut self, value: Vec<f32>) {
- self.position.copy_from_slice(&value[..3]);
- }
-
- #[getter]
- fn quaternion<'py>(&self, py: Python<'py>) -> Bound<'py, PyArray1<f32>> {
- PyArray1::from_slice(py, &self.quaternion)
- }
-
- #[setter]
- fn set_quaternion(&mut self, value: Vec<f32>) {
- self.quaternion.copy_from_slice(&value[..4]);
- }
-}
diff --git a/rust/src/common.rs b/rust/src/common.rs
deleted file mode 100644
index 97dc2420..00000000
--- a/rust/src/common.rs
+++ /dev/null
@@ -1,387 +0,0 @@
-use bytemuck::{Pod, Zeroable};
-use std::io::{BufWriter, Read as IoRead, Write};
-use std::process::{Child, Command, Stdio};
-
-use crate::render_context::{
- CLIP_THRESHOLD, OPACITY, POSITION_X, ROTATION_X, SCALE_X, SHADING, STRIDE, TINT_R,
-};
-use crate::tessellation::{Mesh, SubMesh};
-
-pub const MSAA_SAMPLES: u32 = 4;
-pub const PIPELINE_DEPTH: usize = 5;
-
-/// Configuration passed from Renderer.render() to the platform renderer.
-pub struct RenderConfig {
- pub total_duration: f32,
- pub fps: u32,
- pub output_path: std::path::PathBuf,
- pub output_width: u32,
- pub output_height: u32,
-}
-
-#[repr(C)]
-#[derive(Copy, Clone, Pod, Zeroable)]
-pub struct Vertex {
- pub position: [f32; 3],
- pub normal: [f32; 3],
- pub uv: [f32; 2], // uv.x = arc-length progress, uv.y = 0.0 (reserved)
- pub color: [f32; 4], // per-vertex RGBA color
-}
-
-#[repr(C)]
-#[derive(Copy, Clone, Pod, Zeroable)]
-pub struct DrawUniforms {
- pub clip_threshold: f32,
- pub opacity: f32,
- pub shading: f32,
- pub _pad0: f32,
- pub position: [f32; 4],
- pub scale: [f32; 4],
- pub rotation: [f32; 4],
- pub tint: [f32; 4],
-}
-
-#[repr(C)]
-#[derive(Copy, Clone, Pod, Zeroable)]
-pub struct CameraUniforms {
- pub view_projection: [[f32; 4]; 4],
-}
-
-pub fn orthographic_projection(width: u32, height: u32, frame_height: f32) -> [[f32; 4]; 4] {
- let aspect = width as f32 / height as f32;
- let frame_width = frame_height * aspect;
- let sx = 2.0 / frame_width;
- let sy = 2.0 / frame_height;
- let near = -100.0;
- let far = 100.0;
- let sz = 1.0 / (far - near);
- let tz = -near / (far - near);
- [
- [sx, 0.0, 0.0, 0.0],
- [0.0, sy, 0.0, 0.0],
- [0.0, 0.0, sz, 0.0],
- [0.0, 0.0, tz, 1.0],
- ]
-}
-
-pub fn perspective_projection(
- width: u32,
- height: u32,
- fov_y_deg: f32,
- near: f32,
- far: f32,
-) -> [[f32; 4]; 4] {
- let aspect = width as f32 / height as f32;
- let fov_y = fov_y_deg * std::f32::consts::PI / 180.0;
- let f = 1.0 / (fov_y / 2.0).tan();
- let nf = 1.0 / (near - far);
- [
- [f / aspect, 0.0, 0.0, 0.0],
- [0.0, f, 0.0, 0.0],
- [0.0, 0.0, far * nf, -1.0],
- [0.0, 0.0, near * far * nf, 0.0],
- ]
-}
-
-fn quat_to_rotation_matrix(q: [f32; 4]) -> [[f32; 4]; 4] {
- let [x, y, z, w] = q;
- let x2 = x + x;
- let y2 = y + y;
- let z2 = z + z;
- let xx = x * x2;
- let xy = x * y2;
- let xz = x * z2;
- let yy = y * y2;
- let yz = y * z2;
- let zz = z * z2;
- let wx = w * x2;
- let wy = w * y2;
- let wz = w * z2;
- [
- [1.0 - (yy + zz), xy + wz, xz - wy, 0.0],
- [xy - wz, 1.0 - (xx + zz), yz + wx, 0.0],
- [xz + wy, yz - wx, 1.0 - (xx + yy), 0.0],
- [0.0, 0.0, 0.0, 1.0],
- ]
-}
-
-fn mat4_mul(a: [[f32; 4]; 4], b: [[f32; 4]; 4]) -> [[f32; 4]; 4] {
- let mut out = [[0.0f32; 4]; 4];
- for i in 0..4 {
- for j in 0..4 {
- out[i][j] =
- a[i][0] * b[0][j] + a[i][1] * b[1][j] + a[i][2] * b[2][j] + a[i][3] * b[3][j];
- }
- }
- out
-}
-
-pub fn build_view_projection(
- width: u32,
- height: u32,
- frame_height: f32,
- position: [f32; 3],
- rotation: [f32; 4],
- projection: u8,
- fov: f32,
-) -> [[f32; 4]; 4] {
- let proj = if projection == 1 {
- perspective_projection(width, height, fov, 0.1, 200.0)
- } else {
- orthographic_projection(width, height, frame_height)
- };
-
- // Build view matrix: inverse of camera transform
- // View = inverse(Translation * Rotation) = inverse(Rotation) * inverse(Translation)
- // Conjugate the quaternion (negate x,y,z) for inverse rotation
- let inv_rot = [-rotation[0], -rotation[1], -rotation[2], rotation[3]];
- let rot_mat = quat_to_rotation_matrix(inv_rot);
-
- // Apply translation of -position through the inverse rotation
- let tx = -position[0];
- let ty = -position[1];
- let tz = -position[2];
- // Rotated translation
- let rtx = rot_mat[0][0] * tx + rot_mat[0][1] * ty + rot_mat[0][2] * tz;
- let rty = rot_mat[1][0] * tx + rot_mat[1][1] * ty + rot_mat[1][2] * tz;
- let rtz = rot_mat[2][0] * tx + rot_mat[2][1] * ty + rot_mat[2][2] * tz;
-
- let view = [
- [rot_mat[0][0], rot_mat[0][1], rot_mat[0][2], 0.0],
- [rot_mat[1][0], rot_mat[1][1], rot_mat[1][2], 0.0],
- [rot_mat[2][0], rot_mat[2][1], rot_mat[2][2], 0.0],
- [rtx, rty, rtz, 1.0],
- ];
-
- mat4_mul(view, proj)
-}
-
-#[repr(C)]
-#[derive(Copy, Clone, Pod, Zeroable)]
-pub struct TexturedVertex {
- pub position: [f32; 3],
- pub uv: [f32; 2],
-}
-
-pub fn build_textured_vertices(geo: &Mesh) -> Vec<TexturedVertex> {
- geo.texture_positions
- .chunks_exact(3)
- .zip(geo.texture_uvs.chunks_exact(2))
- .map(|(pos, uv)| TexturedVertex {
- position: [pos[0], pos[1], pos[2]],
- uv: [uv[0], uv[1]],
- })
- .collect()
-}
-
-pub fn build_vertices(submesh: &SubMesh) -> Vec<Vertex> {
- let has_per_vertex = !submesh.colors.is_empty();
- submesh
- .positions
- .chunks_exact(3)
- .zip(submesh.normals.chunks_exact(3))
- .zip(&submesh.progress)
- .enumerate()
- .map(|(i, ((pos, nor), &progress))| {
- let color = if has_per_vertex {
- let base = i * 4;
- [
- submesh.colors[base],
- submesh.colors[base + 1],
- submesh.colors[base + 2],
- submesh.colors[base + 3],
- ]
- } else {
- submesh.color
- };
- Vertex {
- position: [pos[0], pos[1], pos[2]],
- normal: [nor[0], nor[1], nor[2]],
- uv: [progress, 0.0],
- color,
- }
- })
- .collect()
-}
-
-pub fn build_draw_uniforms(state: &[f32], mobject_id: u32) -> DrawUniforms {
- let base = mobject_id as usize * STRIDE;
- DrawUniforms {
- clip_threshold: state[base + CLIP_THRESHOLD],
- opacity: state[base + OPACITY],
- shading: state[base + SHADING],
- _pad0: 0.0,
- position: [
- state[base + POSITION_X],
- state[base + POSITION_X + 1],
- state[base + POSITION_X + 2],
- 0.0,
- ],
- scale: [
- state[base + SCALE_X],
- state[base + SCALE_X + 1],
- state[base + SCALE_X + 2],
- 0.0,
- ],
- rotation: [
- state[base + ROTATION_X],
- state[base + ROTATION_X + 1],
- state[base + ROTATION_X + 2],
- state[base + ROTATION_X + 3],
- ],
- tint: [
- state[base + TINT_R],
- state[base + TINT_R + 1],
- state[base + TINT_R + 2],
- 0.0,
- ],
- }
-}
-
-pub struct FfmpegPipeline {
- pub frame_tx: std::sync::mpsc::Sender<Vec<u8>>,
- pub buf_pool_rx: std::sync::mpsc::Receiver<Vec<u8>>,
- writer_handle: Option<std::thread::JoinHandle<Result<(), String>>>,
- stderr_handle: Option<std::thread::JoinHandle<String>>,
- child: Child,
-}
-
-impl FfmpegPipeline {
- pub fn spawn(
- width: u32,
- height: u32,
- fps: u32,
- output_path: &str,
- frame_size: usize,
- output_width: u32,
- output_height: u32,
- ) -> Result<Self, String> {
- if let Some(parent) = std::path::Path::new(output_path).parent()
- && !parent.as_os_str().is_empty()
- {
- std::fs::create_dir_all(parent)
- .map_err(|e| format!("Failed to create output directory: {e}"))?;
- }
-
- let is_image_sequence = output_path.ends_with(".png") || output_path.ends_with(".jpg");
- let pixel_format = if is_image_sequence { "rgba" } else { "nv12" };
- let video_size = format!("{width}x{height}");
- let fps_str = fps.to_string();
-
- let mut args: Vec<&str> = vec![
- "-y",
- "-f",
- "rawvideo",
- "-pixel_format",
- pixel_format,
- "-video_size",
- &video_size,
- "-framerate",
- &fps_str,
- "-thread_queue_size",
- "64",
- "-i",
- "pipe:0",
- ];
- if !is_image_sequence {
- args.extend([
- "-c:v",
- "libx264",
- "-preset",
- "ultrafast",
- "-crf",
- "23",
- "-threads",
- "0",
- "-flags",
- "+bitexact",
- "-fflags",
- "+bitexact",
- ]);
- }
- let scale_str;
- if output_width != width || output_height != height {
- scale_str = format!("scale={output_width}:{output_height}:flags=area");
- args.extend(["-vf", &scale_str]);
- }
- args.push(output_path);
-
- let mut child = Command::new("ffmpeg")
- .args(&args)
- .stdin(Stdio::piped())
- .stdout(Stdio::null())
- .stderr(Stdio::piped())
- .spawn()
- .map_err(|e| format!("Failed to spawn ffmpeg: {e}"))?;
-
- let stdin = child.stdin.take().ok_or("Failed to open ffmpeg stdin")?;
- let stderr = child.stderr.take();
-
- let stderr_handle = std::thread::spawn(move || {
- let Some(stderr) = stderr else {
- return String::new();
- };
- let mut buf = String::new();
- std::io::BufReader::new(stderr)
- .read_to_string(&mut buf)
- .ok();
- buf
- });
-
- let (frame_tx, frame_rx) = std::sync::mpsc::channel::<Vec<u8>>();
- let (buf_return_tx, buf_pool_rx) = std::sync::mpsc::channel::<Vec<u8>>();
- for _ in 0..PIPELINE_DEPTH + 1 {
- buf_return_tx.send(vec![0u8; frame_size]).unwrap();
- }
-
- let writer_handle = std::thread::spawn(move || -> Result<(), String> {
- let mut writer = BufWriter::with_capacity(frame_size * 2, stdin);
- while let Ok(frame) = frame_rx.recv() {
- writer
- .write_all(&frame)
- .map_err(|e| format!("Pipe write error: {e}"))?;
- let _ = buf_return_tx.send(frame);
- }
- writer
- .flush()
- .map_err(|e| format!("Pipe flush error: {e}"))?;
- Ok(())
- });
-
- Ok(FfmpegPipeline {
- frame_tx,
- buf_pool_rx,
- writer_handle: Some(writer_handle),
- stderr_handle: Some(stderr_handle),
- child,
- })
- }
-
- pub fn finish(mut self) -> Result<(), String> {
- drop(self.frame_tx);
- let writer_result = self
- .writer_handle
- .take()
- .unwrap()
- .join()
- .map_err(|_| "Writer thread panicked".to_string())?;
-
- let status = self
- .child
- .wait()
- .map_err(|e| format!("ffmpeg wait error: {e}"))?;
- let stderr_output = self
- .stderr_handle
- .take()
- .unwrap()
- .join()
- .unwrap_or_default();
-
- writer_result?;
- if !status.success() {
- return Err(format!("ffmpeg failed (exit {status}): {stderr_output}"));
- }
-
- Ok(())
- }
-}
diff --git a/rust/src/lib.rs b/rust/src/lib.rs
deleted file mode 100644
index ca8b8c1c..00000000
--- a/rust/src/lib.rs
+++ /dev/null
@@ -1,32 +0,0 @@
-use pyo3::prelude::*;
-
-mod camera;
-mod common;
-#[cfg(target_os = "macos")]
-mod metal_renderer;
-mod render_context;
-mod renderer;
-mod scene_node;
-mod tessellation;
-
-#[pymodule]
-fn engine(m: &Bound<'_, PyModule>) -> PyResult<()> {
- m.add_function(wrap_pyfunction!(tessellation::tessellate_svg, m)?)?;
- m.add_function(wrap_pyfunction!(tessellation::tessellate, m)?)?;
- m.add_function(wrap_pyfunction!(tessellation::build_surface, m)?)?;
- m.add_function(wrap_pyfunction!(tessellation::build_textured_quad, m)?)?;
- m.add_class::<tessellation::Material>()?;
- m.add_class::<tessellation::Surface>()?;
- m.add_class::<tessellation::Mesh>()?;
- m.add_class::<tessellation::Texture>()?;
- m.add_class::<tessellation::TessellationResult>()?;
- m.add_class::<tessellation::SvgGlyphData>()?;
- m.add_class::<camera::Camera>()?;
- m.add_class::<scene_node::Object3D>()?;
- m.add_class::<render_context::Renderer>()?;
- m.add_class::<render_context::FillRule>()?;
- m.add_class::<render_context::Shading>()?;
- m.add_class::<render_context::Side>()?;
- m.add_class::<render_context::PathCommand>()?;
- Ok(())
-}
diff --git a/rust/src/metal_renderer.rs b/rust/src/metal_renderer.rs
deleted file mode 100644
index 54a81256..00000000
--- a/rust/src/metal_renderer.rs
+++ /dev/null
@@ -1,884 +0,0 @@
-use metal::*;
-use pyo3::prelude::*;
-use std::collections::VecDeque;
-use std::ffi::c_void;
-
-use crate::common::*;
-use crate::render_context::{ACTIVE, FRAME_INDEX, OPACITY, POSITION_X, SIDE, STRIDE, Z_INDEX};
-use crate::tessellation::{Mesh, Texture as TexData};
-
-struct MetalGpuMesh {
- vertex_buffer: Buffer,
- index_buffer: Buffer,
- index_count: u64,
- mobject_id: u32,
- mesh_index: usize,
- cached_generation: u32,
-}
-
-struct MetalGpuTexturedMesh {
- vertex_buffer: Buffer,
- index_buffer: Buffer,
- index_count: u64,
- textures: Vec<Texture>,
- sampler_state: SamplerState,
- mobject_id: u32,
- frame_count: u32,
-}
-
-#[pyclass]
-pub struct MetalRenderer {
- device: Device,
- queue: CommandQueue,
- pipeline: RenderPipelineState,
- ds_state: DepthStencilState,
- msaa_texture: Texture,
- depth_texture: Texture,
- // NV12 compute conversion (for video output)
- nv12_pipeline: ComputePipelineState,
- nv12_buffers: [Buffer; PIPELINE_DEPTH],
- nv12_frame_size: u64,
- // RGBA resolve (for image sequence output — avoids NV12 chroma subsampling)
- resolve_texture: Texture,
- rgba_buffers: [Buffer; PIPELINE_DEPTH],
- rgba_frame_size: u64,
- // Shared state
- camera_uniforms: CameraUniforms,
- width: u32,
- height: u32,
- gpu_meshes: Vec<MetalGpuMesh>,
- // Textured pipeline
- textured_pipeline: RenderPipelineState,
- gpu_textured_meshes: Vec<MetalGpuTexturedMesh>,
- num_mobjects: u32,
- background_color: [f32; 4],
- warmup_done: bool,
-}
-
-#[pymethods]
-impl MetalRenderer {
- #[new]
- pub fn new(width: u32, height: u32) -> PyResult<Self> {
- let device = Device::system_default()
- .ok_or_else(|| pyo3::exceptions::PyRuntimeError::new_err("No Metal device found"))?;
-
- let queue = device.new_command_queue();
-
- let shader_source = include_str!("shaders/main.metal");
- let options = CompileOptions::new();
- let library = device
- .new_library_with_source(shader_source, &options)
- .map_err(|e| {
- pyo3::exceptions::PyRuntimeError::new_err(format!("MSL compile error: {e}"))
- })?;
-
- let vertex_fn = library.get_function("vs_main", None).map_err(|e| {
- pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to get vertex function: {e}"))
- })?;
-
- let fragment_fn = library.get_function("fs_main", None).map_err(|e| {
- pyo3::exceptions::PyRuntimeError::new_err(format!(
- "Failed to get fragment function: {e}"
- ))
- })?;
-
- // Vertex descriptor: position (float3) + normal (float3) + uv (float2) + color (float4) at buffer index 2
- // Morph target: position (float3) + normal (float3) + uv (float2) + color (float4) at buffer index 3
- // (indices 0 and 1 are used for DrawUniforms and CameraUniforms via set_vertex_bytes)
- let vertex_desc = VertexDescriptor::new();
-
- let attr0 = vertex_desc.attributes().object_at(0).unwrap();
- attr0.set_format(MTLVertexFormat::Float3);
- attr0.set_offset(0);
- attr0.set_buffer_index(2);
-
- let attr1 = vertex_desc.attributes().object_at(1).unwrap();
- attr1.set_format(MTLVertexFormat::Float3);
- attr1.set_offset(12);
- attr1.set_buffer_index(2);
-
- let attr2 = vertex_desc.attributes().object_at(2).unwrap();
- attr2.set_format(MTLVertexFormat::Float2);
- attr2.set_offset(24);
- attr2.set_buffer_index(2);
-
- let attr3 = vertex_desc.attributes().object_at(3).unwrap();
- attr3.set_format(MTLVertexFormat::Float4);
- attr3.set_offset(32);
- attr3.set_buffer_index(2);
-
- let layout = vertex_desc.layouts().object_at(2).unwrap();
- layout.set_stride(std::mem::size_of::<Vertex>() as u64);
- layout.set_step_function(MTLVertexStepFunction::PerVertex);
- layout.set_step_rate(1);
-
- let pipeline_desc = RenderPipelineDescriptor::new();
- pipeline_desc.set_vertex_function(Some(&vertex_fn));
- pipeline_desc.set_fragment_function(Some(&fragment_fn));
- pipeline_desc.set_vertex_descriptor(Some(vertex_desc));
- pipeline_desc.set_sample_count(MSAA_SAMPLES as u64);
- pipeline_desc.set_depth_attachment_pixel_format(MTLPixelFormat::Depth32Float);
-
- let color_att = pipeline_desc.color_attachments().object_at(0).unwrap();
- color_att.set_pixel_format(MTLPixelFormat::RGBA8Unorm);
- color_att.set_blending_enabled(true);
- color_att.set_rgb_blend_operation(MTLBlendOperation::Add);
- color_att.set_alpha_blend_operation(MTLBlendOperation::Add);
- color_att.set_source_rgb_blend_factor(MTLBlendFactor::SourceAlpha);
- color_att.set_destination_rgb_blend_factor(MTLBlendFactor::OneMinusSourceAlpha);
- color_att.set_source_alpha_blend_factor(MTLBlendFactor::One);
- color_att.set_destination_alpha_blend_factor(MTLBlendFactor::OneMinusSourceAlpha);
-
- let pipeline = device
- .new_render_pipeline_state(&pipeline_desc)
- .map_err(|e| {
- pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to create pipeline: {e}"))
- })?;
-
- // Textured pipeline
- let tex_shader_source = include_str!("shaders/textured.metal");
- let tex_library = device
- .new_library_with_source(tex_shader_source, &options)
- .map_err(|e| {
- pyo3::exceptions::PyRuntimeError::new_err(format!(
- "Textured MSL compile error: {e}"
- ))
- })?;
-
- let tex_vertex_fn = tex_library.get_function("vs_textured", None).map_err(|e| {
- pyo3::exceptions::PyRuntimeError::new_err(format!(
- "Failed to get textured vertex function: {e}"
- ))
- })?;
-
- let tex_fragment_fn = tex_library.get_function("fs_textured", None).map_err(|e| {
- pyo3::exceptions::PyRuntimeError::new_err(format!(
- "Failed to get textured fragment function: {e}"
- ))
- })?;
-
- // Vertex descriptor: position (float3) + uv (float2) at buffer index 30
- let tex_vertex_desc = VertexDescriptor::new();
-
- let tex_attr0 = tex_vertex_desc.attributes().object_at(0).unwrap();
- tex_attr0.set_format(MTLVertexFormat::Float3);
- tex_attr0.set_offset(0);
- tex_attr0.set_buffer_index(2);
-
- let tex_attr1 = tex_vertex_desc.attributes().object_at(1).unwrap();
- tex_attr1.set_format(MTLVertexFormat::Float2);
- tex_attr1.set_offset(12);
- tex_attr1.set_buffer_index(2);
-
- let tex_layout = tex_vertex_desc.layouts().object_at(2).unwrap();
- tex_layout.set_stride(std::mem::size_of::<TexturedVertex>() as u64);
- tex_layout.set_step_function(MTLVertexStepFunction::PerVertex);
- tex_layout.set_step_rate(1);
-
- let tex_pipeline_desc = RenderPipelineDescriptor::new();
- tex_pipeline_desc.set_vertex_function(Some(&tex_vertex_fn));
- tex_pipeline_desc.set_fragment_function(Some(&tex_fragment_fn));
- tex_pipeline_desc.set_vertex_descriptor(Some(tex_vertex_desc));
- tex_pipeline_desc.set_sample_count(MSAA_SAMPLES as u64);
- tex_pipeline_desc.set_depth_attachment_pixel_format(MTLPixelFormat::Depth32Float);
-
- let tex_color_att = tex_pipeline_desc.color_attachments().object_at(0).unwrap();
- tex_color_att.set_pixel_format(MTLPixelFormat::RGBA8Unorm);
- tex_color_att.set_blending_enabled(true);
- tex_color_att.set_rgb_blend_operation(MTLBlendOperation::Add);
- tex_color_att.set_alpha_blend_operation(MTLBlendOperation::Add);
- tex_color_att.set_source_rgb_blend_factor(MTLBlendFactor::SourceAlpha);
- tex_color_att.set_destination_rgb_blend_factor(MTLBlendFactor::OneMinusSourceAlpha);
- tex_color_att.set_source_alpha_blend_factor(MTLBlendFactor::One);
- tex_color_att.set_destination_alpha_blend_factor(MTLBlendFactor::OneMinusSourceAlpha);
-
- let textured_pipeline = device
- .new_render_pipeline_state(&tex_pipeline_desc)
- .map_err(|e| {
- pyo3::exceptions::PyRuntimeError::new_err(format!(
- "Failed to create textured pipeline: {e}"
- ))
- })?;
-
- // Depth-stencil state: depth LessEqual, write enabled
- let ds_desc = DepthStencilDescriptor::new();
- ds_desc.set_depth_compare_function(MTLCompareFunction::LessEqual);
- ds_desc.set_depth_write_enabled(true);
- let ds_state = device.new_depth_stencil_state(&ds_desc);
-
- // MSAA texture — ShaderRead lets NV12 compute read samples directly
- let msaa_desc = TextureDescriptor::new();
- msaa_desc.set_texture_type(MTLTextureType::D2Multisample);
- msaa_desc.set_pixel_format(MTLPixelFormat::RGBA8Unorm);
- msaa_desc.set_width(width as u64);
- msaa_desc.set_height(height as u64);
- msaa_desc.set_sample_count(MSAA_SAMPLES as u64);
- msaa_desc.set_storage_mode(MTLStorageMode::Private);
- msaa_desc.set_usage(MTLTextureUsage::RenderTarget | MTLTextureUsage::ShaderRead);
- let msaa_texture = device.new_texture(&msaa_desc);
-
- // Depth texture (MSAA)
- let depth_tex_desc = TextureDescriptor::new();
- depth_tex_desc.set_texture_type(MTLTextureType::D2Multisample);
- depth_tex_desc.set_pixel_format(MTLPixelFormat::Depth32Float);
- depth_tex_desc.set_width(width as u64);
- depth_tex_desc.set_height(height as u64);
- depth_tex_desc.set_sample_count(MSAA_SAMPLES as u64);
- depth_tex_desc.set_storage_mode(MTLStorageMode::Private);
- depth_tex_desc.set_usage(MTLTextureUsage::RenderTarget);
- let depth_texture = device.new_texture(&depth_tex_desc);
-
- // NV12 compute pipeline
- let nv12_source = include_str!("shaders/nv12_convert.metal");
- let nv12_library = device
- .new_library_with_source(nv12_source, &options)
- .map_err(|e| {
- pyo3::exceptions::PyRuntimeError::new_err(format!("NV12 MSL compile error: {e}"))
- })?;
-
- let nv12_fn = nv12_library
- .get_function("nv12_convert", None)
- .map_err(|e| {
- pyo3::exceptions::PyRuntimeError::new_err(format!(
- "Failed to get nv12_convert function: {e}"
- ))
- })?;
-
- let nv12_pipeline = device
- .new_compute_pipeline_state_with_function(&nv12_fn)
- .map_err(|e| {
- pyo3::exceptions::PyRuntimeError::new_err(format!(
- "Failed to create NV12 compute pipeline: {e}"
- ))
- })?;
-
- // NV12 output buffers (shared, zero-copy readback)
- let nv12_frame_size = (width as u64 * height as u64 * 3) / 2;
- let nv12_buffers: [Buffer; PIPELINE_DEPTH] = std::array::from_fn(|_| {
- device.new_buffer(nv12_frame_size, MTLResourceOptions::StorageModeShared)
- });
-
- // RGBA resolve texture + staging buffers (for image sequence output)
- let resolve_desc = TextureDescriptor::new();
- resolve_desc.set_texture_type(MTLTextureType::D2);
- resolve_desc.set_pixel_format(MTLPixelFormat::RGBA8Unorm);
- resolve_desc.set_width(width as u64);
- resolve_desc.set_height(height as u64);
- resolve_desc.set_storage_mode(MTLStorageMode::Private);
- resolve_desc.set_usage(MTLTextureUsage::RenderTarget);
- let resolve_texture = device.new_texture(&resolve_desc);
-
- let rgba_frame_size = width as u64 * height as u64 * 4;
- let rgba_buffers: [Buffer; PIPELINE_DEPTH] = std::array::from_fn(|_| {
- device.new_buffer(rgba_frame_size, MTLResourceOptions::StorageModeShared)
- });
-
- // Initialize with defaults — will be overwritten on first frame
- let camera_uniforms = CameraUniforms {
- view_projection: orthographic_projection(width, height, 8.0),
- };
- let background_color = [0.0, 0.0, 0.0, 1.0];
-
- Ok(MetalRenderer {
- device,
- queue,
- pipeline,
- ds_state,
- msaa_texture,
- depth_texture,
- nv12_pipeline,
- nv12_buffers,
- nv12_frame_size,
- resolve_texture,
- rgba_buffers,
- rgba_frame_size,
- camera_uniforms,
- width,
- height,
- gpu_meshes: Vec::new(),
- textured_pipeline,
- gpu_textured_meshes: Vec::new(),
- num_mobjects: 0,
- background_color,
- warmup_done: false,
- })
- }
-}
-
-impl MetalRenderer {
- pub(crate) fn upload_meshes(
- &mut self,
- meshes: Vec<Mesh>,
- textures: &[Option<TexData>],
- mobject_ids: Vec<u32>,
- num_mobjects: u32,
- ) {
- self.gpu_meshes.clear();
- self.gpu_textured_meshes.clear();
- self.num_mobjects = num_mobjects;
-
- for (geo_idx, (geo, &mobject_id)) in meshes.iter().zip(mobject_ids.iter()).enumerate() {
- if let Some(tex) = textures.get(geo_idx).and_then(|t| t.as_ref()) {
- // Textured mesh path
- let vertices = build_textured_vertices(geo);
- let vertex_data = bytemuck::cast_slice::<TexturedVertex, u8>(&vertices);
- let index_data = bytemuck::cast_slice::<u32, u8>(&geo.texture_indices);
-
- let vertex_buffer = self.device.new_buffer_with_data(
- vertex_data.as_ptr() as *const c_void,
- vertex_data.len() as u64,
- MTLResourceOptions::StorageModeShared,
- );
-
- let index_buffer = self.device.new_buffer_with_data(
- index_data.as_ptr() as *const c_void,
- index_data.len() as u64,
- MTLResourceOptions::StorageModeShared,
- );
-
- // Create a GPU texture for each frame
- let mut textures = Vec::with_capacity(tex.frames.len());
- for frame_data in &tex.frames {
- let tex_desc = TextureDescriptor::new();
- tex_desc.set_texture_type(MTLTextureType::D2);
- tex_desc.set_pixel_format(MTLPixelFormat::RGBA8Unorm);
- tex_desc.set_width(tex.width as u64);
- tex_desc.set_height(tex.height as u64);
- tex_desc.set_storage_mode(MTLStorageMode::Shared);
- tex_desc.set_usage(MTLTextureUsage::ShaderRead);
- let gpu_tex = self.device.new_texture(&tex_desc);
-
- let region = MTLRegion {
- origin: MTLOrigin { x: 0, y: 0, z: 0 },
- size: MTLSize {
- width: tex.width as u64,
- height: tex.height as u64,
- depth: 1,
- },
- };
- let bytes_per_row = tex.width as u64 * 4;
- gpu_tex.replace_region(
- region,
- 0,
- frame_data.as_ptr() as *const c_void,
- bytes_per_row,
- );
- textures.push(gpu_tex);
- }
-
- // Create sampler
- let sampler_desc = SamplerDescriptor::new();
- sampler_desc.set_min_filter(MTLSamplerMinMagFilter::Linear);
- sampler_desc.set_mag_filter(MTLSamplerMinMagFilter::Linear);
- sampler_desc.set_address_mode_s(MTLSamplerAddressMode::ClampToEdge);
- sampler_desc.set_address_mode_t(MTLSamplerAddressMode::ClampToEdge);
- let sampler_state = self.device.new_sampler(&sampler_desc);
-
- self.gpu_textured_meshes.push(MetalGpuTexturedMesh {
- vertex_buffer,
- index_buffer,
- index_count: geo.texture_indices.len() as u64,
- textures,
- sampler_state,
- mobject_id,
- frame_count: tex.frames.len() as u32,
- });
- continue;
- }
-
- // Solid mesh path
- for submesh in geo.submeshes.iter() {
- if submesh.indices.is_empty() {
- continue;
- }
-
- let vertices = build_vertices(submesh);
- let vertex_data = bytemuck::cast_slice::<Vertex, u8>(&vertices);
- let index_data = bytemuck::cast_slice::<u32, u8>(&submesh.indices);
-
- let vertex_buffer = self.device.new_buffer_with_data(
- vertex_data.as_ptr() as *const c_void,
- vertex_data.len() as u64,
- MTLResourceOptions::StorageModeShared,
- );
-
- let index_buffer = self.device.new_buffer_with_data(
- index_data.as_ptr() as *const c_void,
- index_data.len() as u64,
- MTLResourceOptions::StorageModeShared,
- );
-
- self.gpu_meshes.push(MetalGpuMesh {
- vertex_buffer,
- index_buffer,
- index_count: submesh.indices.len() as u64,
- mobject_id,
- mesh_index: mobject_id as usize,
- cached_generation: 0,
- });
- }
- }
- }
-}
-
-impl MetalRenderer {
- pub(crate) fn render_all_frames(
- &mut self,
- py: Python<'_>,
- evaluate_frame: &Py<PyAny>,
- surface_refs: &[Py<crate::tessellation::Surface>],
- object3d_refs: &[Py<crate::scene_node::Object3D>],
- camera_ref: &Py<crate::camera::Camera>,
- cfg: RenderConfig,
- ) -> PyResult<()> {
- self.render_loop(
- py,
- evaluate_frame,
- surface_refs,
- object3d_refs,
- camera_ref,
- &cfg,
- )
- .map_err(pyo3::exceptions::PyRuntimeError::new_err)
- }
-
- fn sync_dirty_surfaces(
- &mut self,
- py: Python<'_>,
- surface_refs: &[Py<crate::tessellation::Surface>],
- ) {
- for gpu_mesh in &mut self.gpu_meshes {
- let surface = surface_refs[gpu_mesh.mesh_index].borrow(py);
- if surface.generation != gpu_mesh.cached_generation {
- let geo = surface.mesh.borrow(py);
- // Find a non-empty submesh to re-upload
- for submesh in &geo.submeshes {
- if !submesh.indices.is_empty() {
- let vertices = build_vertices(submesh);
- let vertex_data = bytemuck::cast_slice::<Vertex, u8>(&vertices);
- let index_data = bytemuck::cast_slice::<u32, u8>(&submesh.indices);
-
- gpu_mesh.vertex_buffer = self.device.new_buffer_with_data(
- vertex_data.as_ptr() as *const c_void,
- vertex_data.len() as u64,
- MTLResourceOptions::StorageModeShared,
- );
- gpu_mesh.index_buffer = self.device.new_buffer_with_data(
- index_data.as_ptr() as *const c_void,
- index_data.len() as u64,
- MTLResourceOptions::StorageModeShared,
- );
- gpu_mesh.index_count = submesh.indices.len() as u64;
- break;
- }
- }
- gpu_mesh.cached_generation = surface.generation;
- }
- }
- }
-
- fn encode_render_pass(
- &self,
- cmd_buf: &CommandBufferRef,
- state: &[f32],
- is_image_sequence: bool,
- ) {
- let pass_desc = RenderPassDescriptor::new();
- let color_att = pass_desc.color_attachments().object_at(0).unwrap();
- color_att.set_texture(Some(&self.msaa_texture));
- color_att.set_load_action(MTLLoadAction::Clear);
- if is_image_sequence {
- // Resolve MSAA → non-MSAA texture (avoids NV12 chroma subsampling)
- color_att.set_resolve_texture(Some(&self.resolve_texture));
- color_att.set_store_action(MTLStoreAction::MultisampleResolve);
- } else {
- // Store MSAA samples for NV12 compute kernel to read directly
- color_att.set_store_action(MTLStoreAction::Store);
- }
- color_att.set_clear_color(MTLClearColor::new(
- self.background_color[0] as f64,
- self.background_color[1] as f64,
- self.background_color[2] as f64,
- self.background_color[3] as f64,
- ));
-
- let depth_att = pass_desc.depth_attachment().unwrap();
- depth_att.set_texture(Some(&self.depth_texture));
- depth_att.set_load_action(MTLLoadAction::Clear);
- depth_att.set_store_action(MTLStoreAction::DontCare);
- depth_att.set_clear_depth(1.0);
-
- let encoder = cmd_buf.new_render_command_encoder(pass_desc);
- encoder.set_render_pipeline_state(&self.pipeline);
- encoder.set_depth_stencil_state(&self.ds_state);
-
- encoder.set_vertex_bytes(
- 1,
- std::mem::size_of::<CameraUniforms>() as u64,
- &self.camera_uniforms as *const CameraUniforms as *const c_void,
- );
-
- // Classify meshes into opaque and transparent buckets
- let mut opaque_indices: Vec<usize> = Vec::new();
- let mut transparent_indices: Vec<usize> = Vec::new();
- for (i, gpu_mesh) in self.gpu_meshes.iter().enumerate() {
- let base = gpu_mesh.mobject_id as usize * STRIDE;
- if state[base + ACTIVE] == 0.0 || state[base + OPACITY] <= 0.0 {
- continue;
- }
- let opacity = state[base + OPACITY];
- if opacity >= 1.0 {
- opaque_indices.push(i);
- } else {
- transparent_indices.push(i);
- }
- }
-
- // Sort opaque by z_index ascending
- opaque_indices.sort_by(|&a, &b| {
- let za = state[self.gpu_meshes[a].mobject_id as usize * STRIDE + Z_INDEX];
- let zb = state[self.gpu_meshes[b].mobject_id as usize * STRIDE + Z_INDEX];
- za.partial_cmp(&zb).unwrap_or(std::cmp::Ordering::Equal)
- });
- // Sort transparent by z_index ascending, then position_z descending (back-to-front)
- transparent_indices.sort_by(|&a, &b| {
- let ba = self.gpu_meshes[a].mobject_id as usize * STRIDE;
- let bb = self.gpu_meshes[b].mobject_id as usize * STRIDE;
- let za = state[ba + Z_INDEX];
- let zb = state[bb + Z_INDEX];
- match za.partial_cmp(&zb).unwrap_or(std::cmp::Ordering::Equal) {
- std::cmp::Ordering::Equal => {
- let pza = state[ba + POSITION_X + 2];
- let pzb = state[bb + POSITION_X + 2];
- // Descending position_z (back-to-front)
- pzb.partial_cmp(&pza).unwrap_or(std::cmp::Ordering::Equal)
- }
- ord => ord,
- }
- });
-
- // Pass 1: Opaque meshes, Pass 2: Transparent meshes
- for &idx in opaque_indices.iter().chain(transparent_indices.iter()) {
- let gpu_mesh = &self.gpu_meshes[idx];
- let base = gpu_mesh.mobject_id as usize * STRIDE;
-
- let side = state[base + SIDE] as u32;
- let cull_mode = match side {
- 1 => MTLCullMode::Front,
- 2 => MTLCullMode::None,
- _ => MTLCullMode::Back,
- };
- encoder.set_cull_mode(cull_mode);
-
- let uniforms = build_draw_uniforms(state, gpu_mesh.mobject_id);
-
- encoder.set_vertex_bytes(
- 0,
- std::mem::size_of::<DrawUniforms>() as u64,
- &uniforms as *const DrawUniforms as *const c_void,
- );
- encoder.set_fragment_bytes(
- 0,
- std::mem::size_of::<DrawUniforms>() as u64,
- &uniforms as *const DrawUniforms as *const c_void,
- );
-
- encoder.set_vertex_buffer(2, Some(&gpu_mesh.vertex_buffer), 0);
-
- encoder.draw_indexed_primitives(
- MTLPrimitiveType::Triangle,
- gpu_mesh.index_count,
- MTLIndexType::UInt32,
- &gpu_mesh.index_buffer,
- 0,
- );
- }
-
- // Draw textured meshes
- if !self.gpu_textured_meshes.is_empty() {
- encoder.set_render_pipeline_state(&self.textured_pipeline);
- encoder.set_depth_stencil_state(&self.ds_state);
-
- encoder.set_vertex_bytes(
- 1,
- std::mem::size_of::<CameraUniforms>() as u64,
- &self.camera_uniforms as *const CameraUniforms as *const c_void,
- );
-
- for gpu_mesh in &self.gpu_textured_meshes {
- // Skip inactive or fully transparent meshes
- let base = gpu_mesh.mobject_id as usize * STRIDE;
- if state[base + ACTIVE] == 0.0 || state[base + OPACITY] <= 0.0 {
- continue;
- }
-
- let uniforms = build_draw_uniforms(state, gpu_mesh.mobject_id);
-
- encoder.set_vertex_bytes(
- 0,
- std::mem::size_of::<DrawUniforms>() as u64,
- &uniforms as *const DrawUniforms as *const c_void,
- );
- encoder.set_fragment_bytes(
- 0,
- std::mem::size_of::<DrawUniforms>() as u64,
- &uniforms as *const DrawUniforms as *const c_void,
- );
-
- // Select frame
- let base = gpu_mesh.mobject_id as usize * STRIDE;
- let frame_idx = if gpu_mesh.frame_count > 1 && base + FRAME_INDEX < state.len() {
- (state[base + FRAME_INDEX] as usize) % gpu_mesh.frame_count as usize
- } else {
- 0
- };
-
- encoder.set_vertex_buffer(2, Some(&gpu_mesh.vertex_buffer), 0);
- encoder.set_fragment_texture(0, Some(&gpu_mesh.textures[frame_idx]));
- encoder.set_fragment_sampler_state(0, Some(&gpu_mesh.sampler_state));
-
- encoder.draw_indexed_primitives(
- MTLPrimitiveType::Triangle,
- gpu_mesh.index_count,
- MTLIndexType::UInt32,
- &gpu_mesh.index_buffer,
- 0,
- );
- }
- }
-
- encoder.end_encoding();
- }
-
- fn encode_nv12_pass(&self, cmd_buf: &CommandBufferRef, slot: usize) {
- let compute_encoder = cmd_buf.new_compute_command_encoder();
- compute_encoder.set_compute_pipeline_state(&self.nv12_pipeline);
- compute_encoder.set_texture(0, Some(&self.msaa_texture));
- compute_encoder.set_buffer(0, Some(&self.nv12_buffers[slot]), 0);
-
- let threads_per_group = MTLSize {
- width: 16,
- height: 16,
- depth: 1,
- };
- let num_groups = MTLSize {
- width: (self.width as u64 / 4).div_ceil(16),
- height: (self.height as u64 / 2).div_ceil(16),
- depth: 1,
- };
- compute_encoder.dispatch_thread_groups(num_groups, threads_per_group);
- compute_encoder.end_encoding();
- }
-
- fn nv12_readback(&self, slot: usize, out: &mut [u8]) {
- let ptr = self.nv12_buffers[slot].contents() as *const u8;
- unsafe {
- std::ptr::copy_nonoverlapping(ptr, out.as_mut_ptr(), out.len());
- }
- }
-
- fn encode_rgba_blit(&self, cmd_buf: &CommandBufferRef, slot: usize) {
- let blit = cmd_buf.new_blit_command_encoder();
- let bytes_per_row = self.width as u64 * 4;
- blit.copy_from_texture_to_buffer(
- &self.resolve_texture,
- 0,
- 0,
- MTLOrigin { x: 0, y: 0, z: 0 },
- MTLSize {
- width: self.width as u64,
- height: self.height as u64,
- depth: 1,
- },
- &self.rgba_buffers[slot],
- 0,
- bytes_per_row,
- bytes_per_row * self.height as u64,
- MTLBlitOption::empty(),
- );
- blit.end_encoding();
- }
-
- fn rgba_readback(&self, slot: usize, out: &mut [u8]) {
- let ptr = self.rgba_buffers[slot].contents() as *const u8;
- unsafe {
- std::ptr::copy_nonoverlapping(ptr, out.as_mut_ptr(), out.len());
- }
- }
-
- /// Force Metal to compile shaders, avoiding lazy compilation stutter on frame 0.
- fn warmup(&mut self) {
- if self.warmup_done {
- return;
- }
-
- let cmd = self.queue.new_command_buffer();
-
- let pass = RenderPassDescriptor::new();
- let att = pass.color_attachments().object_at(0).unwrap();
- att.set_texture(Some(&self.msaa_texture));
- att.set_load_action(MTLLoadAction::Clear);
- att.set_store_action(MTLStoreAction::Store);
- att.set_clear_color(MTLClearColor::new(0.0, 0.0, 0.0, 1.0));
-
- let depth_att = pass.depth_attachment().unwrap();
- depth_att.set_texture(Some(&self.depth_texture));
- depth_att.set_load_action(MTLLoadAction::Clear);
- depth_att.set_store_action(MTLStoreAction::DontCare);
- depth_att.set_clear_depth(1.0);
-
- let enc = cmd.new_render_command_encoder(pass);
- enc.set_render_pipeline_state(&self.pipeline);
- enc.set_depth_stencil_state(&self.ds_state);
- // Also warm up textured pipeline
- enc.set_render_pipeline_state(&self.textured_pipeline);
- enc.end_encoding();
-
- let compute = cmd.new_compute_command_encoder();
- compute.set_compute_pipeline_state(&self.nv12_pipeline);
- compute.set_texture(0, Some(&self.msaa_texture));
- compute.set_buffer(0, Some(&self.nv12_buffers[0]), 0);
- compute.dispatch_thread_groups(
- MTLSize {
- width: 1,
- height: 1,
- depth: 1,
- },
- MTLSize {
- width: 16,
- height: 16,
- depth: 1,
- },
- );
- compute.end_encoding();
-
- cmd.commit();
- cmd.wait_until_completed();
- self.warmup_done = true;
- }
-
- fn render_loop(
- &mut self,
- py: Python<'_>,
- evaluate_frame: &Py<PyAny>,
- surface_refs: &[Py<crate::tessellation::Surface>],
- object3d_refs: &[Py<crate::scene_node::Object3D>],
- camera_ref: &Py<crate::camera::Camera>,
- cfg: &RenderConfig,
- ) -> Result<(), String> {
- let total_frames = ((cfg.total_duration * cfg.fps as f32) as u32).max(1);
- let fps = cfg.fps;
- let output_path = cfg.output_path.to_str().unwrap();
- let output_width = cfg.output_width;
- let output_height = cfg.output_height;
- let is_image_sequence = output_path.ends_with(".png") || output_path.ends_with(".jpg");
-
- let frame_size = if is_image_sequence {
- self.rgba_frame_size as usize
- } else {
- self.nv12_frame_size as usize
- };
- let fps_f32 = fps as f32;
-
- // Spawn ffmpeg concurrently with Metal warmup
- let (w, h, fps_u32, fsz) = (self.width, self.height, fps, frame_size);
- let (ow, oh) = (output_width, output_height);
- let path = output_path.to_string();
- let ffmpeg_handle =
- std::thread::spawn(move || FfmpegPipeline::spawn(w, h, fps_u32, &path, fsz, ow, oh));
-
- self.warmup();
-
- let pipeline = ffmpeg_handle
- .join()
- .map_err(|_| "ffmpeg spawn thread panicked".to_string())??;
-
- let mut pending: VecDeque<(usize, CommandBuffer)> = VecDeque::new();
- let mut state: Vec<f32> = Vec::new();
-
- for frame_idx in 0..total_frames {
- let t = frame_idx as f32 / fps_f32;
- let slot = frame_idx as usize % PIPELINE_DEPTH;
-
- if pending.len() == PIPELINE_DEPTH {
- let (old_slot, old_cmd) = pending.pop_front().unwrap();
- old_cmd.wait_until_completed();
-
- let mut pixels = pipeline
- .buf_pool_rx
- .recv()
- .map_err(|_| "Buffer pool closed".to_string())?;
- if is_image_sequence {
- self.rgba_readback(old_slot, &mut pixels);
- } else {
- self.nv12_readback(old_slot, &mut pixels);
- }
- pipeline
- .frame_tx
- .send(pixels)
- .map_err(|e| format!("Channel send error: {e}"))?;
- }
-
- // Evaluate scene state for this frame, then snapshot to state buffer.
- evaluate_frame
- .call1(py, (t,))
- .map_err(|e| format!("evaluate_frame error: {e}"))?;
- crate::render_context::snapshot_surfaces(py, surface_refs, object3d_refs, &mut state);
- self.sync_dirty_surfaces(py, surface_refs);
-
- // Read camera state per-frame
- {
- let cam = camera_ref.borrow(py);
- self.camera_uniforms = CameraUniforms {
- view_projection: build_view_projection(
- self.width,
- self.height,
- cam.frame_height,
- cam.position,
- cam.quaternion,
- cam.projection,
- cam.fov,
- ),
- };
- self.background_color = [
- cam.background.0 as f32 / 255.0,
- cam.background.1 as f32 / 255.0,
- cam.background.2 as f32 / 255.0,
- 1.0,
- ];
- }
-
- let cmd_buf = self.queue.new_command_buffer();
- self.encode_render_pass(cmd_buf, &state, is_image_sequence);
- if is_image_sequence {
- self.encode_rgba_blit(cmd_buf, slot);
- } else {
- self.encode_nv12_pass(cmd_buf, slot);
- }
-
- let owned = cmd_buf.to_owned();
- cmd_buf.commit();
- pending.push_back((slot, owned));
- }
-
- while let Some((old_slot, old_cmd)) = pending.pop_front() {
- old_cmd.wait_until_completed();
-
- let mut pixels = pipeline
- .buf_pool_rx
- .recv()
- .map_err(|_| "Buffer pool closed".to_string())?;
- if is_image_sequence {
- self.rgba_readback(old_slot, &mut pixels);
- } else {
- self.nv12_readback(old_slot, &mut pixels);
- }
- pipeline
- .frame_tx
- .send(pixels)
- .map_err(|e| format!("Channel send error: {e}"))?;
- }
-
- pipeline.finish()
- }
-}
diff --git a/rust/src/render_context.rs b/rust/src/render_context.rs
deleted file mode 100644
index 44ec1cec..00000000
--- a/rust/src/render_context.rs
+++ /dev/null
@@ -1,271 +0,0 @@
-use pyo3::prelude::*;
-
-use crate::scene_node::{Object3D, is_node_chain_active};
-use crate::tessellation::{Mesh, Surface, Texture};
-
-pub const STRIDE: usize = 21;
-
-// Property indices for building DrawUniforms from mesh fields.
-pub const CLIP_THRESHOLD: usize = 0;
-pub const OPACITY: usize = 1;
-pub const POSITION_X: usize = 2;
-pub const SCALE_X: usize = 5;
-pub const ROTATION_X: usize = 8;
-pub const TINT_R: usize = 12;
-// offset 15 is reserved (_pad0 in DrawUniforms)
-pub const FRAME_INDEX: usize = 16;
-pub const ACTIVE: usize = 17;
-pub const Z_INDEX: usize = 18;
-pub const SHADING: usize = 19;
-pub const SIDE: usize = 20;
-
-// ── Renderer ─────────────────────────────────────────────────────────
-
-#[pyclass]
-pub struct Renderer {
- /// Cloned mesh data — used for initial GPU upload.
- pub meshes: Vec<Mesh>,
- /// Cloned texture data (parallel to meshes). None = solid mesh.
- pub textures: Vec<Option<Texture>>,
- /// Python-side Surface references — used to read per-frame property updates.
- surface_refs: Vec<Py<Surface>>,
- /// Parallel Object3D references — one per Surface, for reading transforms.
- object3d_refs: Vec<Py<Object3D>>,
- /// Camera — set via set_camera(), read per-frame during render.
- camera: Option<Py<crate::camera::Camera>>,
-}
-
-#[pymethods]
-impl Renderer {
- #[new]
- pub fn new() -> Self {
- Renderer {
- meshes: Vec::new(),
- textures: Vec::new(),
- surface_refs: Vec::new(),
- object3d_refs: Vec::new(),
- camera: None,
- }
- }
-
- pub fn set_camera(&mut self, camera: Py<crate::camera::Camera>) {
- self.camera = Some(camera);
- }
-
- pub fn add(&mut self, py: Python<'_>, object3d: &Bound<'_, Object3D>) {
- let node = object3d.borrow();
- for surface_ref in &node.surfaces {
- let surface = surface_ref.borrow(py);
- // Clone mesh data for GPU upload.
- let mesh = surface.mesh.borrow(py);
- self.meshes.push(mesh.clone());
- // Clone texture from material if present.
- let mat = surface.material.borrow(py);
- let texture = mat.texture.as_ref().map(|t| t.borrow(py).clone());
- self.textures.push(texture);
- // Keep references to Surface and its Object3D for per-frame state reads.
- self.surface_refs.push(surface_ref.clone_ref(py));
- self.object3d_refs.push(object3d.as_unbound().clone_ref(py));
- }
- }
-
- #[pyo3(signature = (*, evaluate_frame, total_duration, output, width=1920, height=1080, fps=60, supersample=1))]
- #[allow(clippy::too_many_arguments)]
- pub fn render(
- &mut self,
- py: Python<'_>,
- evaluate_frame: Py<PyAny>,
- total_duration: f32,
- output: std::path::PathBuf,
- width: u32,
- height: u32,
- fps: u32,
- supersample: u32,
- ) -> PyResult<()> {
- let camera = self.camera.as_ref().ok_or_else(|| {
- pyo3::exceptions::PyRuntimeError::new_err(
- "No camera set. Call set_camera() before render().",
- )
- })?;
-
- let render_width = width * supersample;
- let render_height = height * supersample;
-
- let num_instances = self.meshes.len() as u32;
- let ids: Vec<u32> = (0..num_instances).collect();
-
- let cfg = crate::common::RenderConfig {
- total_duration,
- fps,
- output_path: output,
- output_width: width,
- output_height: height,
- };
-
- #[cfg(target_os = "macos")]
- {
- let mut r = crate::metal_renderer::MetalRenderer::new(render_width, render_height)?;
- r.upload_meshes(self.meshes.clone(), &self.textures, ids, num_instances);
- r.render_all_frames(
- py,
- &evaluate_frame,
- &self.surface_refs,
- &self.object3d_refs,
- camera,
- cfg,
- )
- }
- #[cfg(not(target_os = "macos"))]
- {
- let mut r = crate::renderer::GpuRenderer::new(render_width, render_height)?;
- r.upload_meshes(self.meshes.clone(), &self.textures, ids, num_instances);
- r.render_all_frames(
- py,
- &evaluate_frame,
- &self.surface_refs,
- &self.object3d_refs,
- camera,
- cfg,
- )
- }
- }
-}
-
-/// Snapshot current Surface fields into a flat state buffer.
-/// Reads transforms from the parallel Object3D refs (absolute coordinates).
-/// No parent-child composition — transforms are already absolute.
-pub fn snapshot_surfaces(
- py: Python<'_>,
- surface_refs: &[Py<Surface>],
- object3d_refs: &[Py<Object3D>],
- state: &mut Vec<f32>,
-) {
- let n = surface_refs.len();
- state.resize(n * STRIDE, 0.0);
-
- for (i, (surface_ref, node_ref)) in surface_refs.iter().zip(object3d_refs.iter()).enumerate() {
- let surface = surface_ref.borrow(py);
- let node = node_ref.borrow(py);
- let b = i * STRIDE;
-
- // Read absolute transforms from Object3D
- let node_active = is_node_chain_active(py, &node);
-
- // Write transforms directly (already absolute)
- state[b + POSITION_X] = node.position[0];
- state[b + POSITION_X + 1] = node.position[1];
- state[b + POSITION_X + 2] = node.position[2];
- state[b + SCALE_X] = node.scale[0];
- state[b + SCALE_X + 1] = node.scale[1];
- state[b + SCALE_X + 2] = node.scale[2];
- state[b + ROTATION_X] = node.quaternion[0];
- state[b + ROTATION_X + 1] = node.quaternion[1];
- state[b + ROTATION_X + 2] = node.quaternion[2];
- state[b + ROTATION_X + 3] = node.quaternion[3];
-
- // Cascading visibility: Surface active AND all ancestor nodes active
- let effective_active = surface.active && node_active;
- state[b + ACTIVE] = if effective_active { 1.0 } else { 0.0 };
- state[b + OPACITY] = if effective_active {
- surface.material.borrow(py).opacity
- } else {
- 0.0
- };
-
- state[b + Z_INDEX] = surface.z_index;
- state[b + CLIP_THRESHOLD] = surface.clip_threshold;
-
- let mat = surface.material.borrow(py);
- let c = mat.color;
- state[b + TINT_R] = c.0 as f32 / 255.0;
- state[b + TINT_R + 1] = c.1 as f32 / 255.0;
- state[b + TINT_R + 2] = c.2 as f32 / 255.0;
- state[b + SHADING] = mat.shading.value as f32;
- state[b + SIDE] = mat.side.value as f32;
- state[b + FRAME_INDEX] = 0.0;
- }
-}
-
-// ── Constants ────────────────────────────────────────────────────────
-
-#[pyclass(frozen, eq, hash, from_py_object)]
-#[derive(Clone, Copy, PartialEq, Eq, Hash)]
-pub struct FillRule {
- pub(crate) value: u8,
-}
-
-#[allow(non_snake_case)]
-#[pymethods]
-impl FillRule {
- #[classattr]
- fn NON_ZERO() -> FillRule {
- FillRule { value: 0 }
- }
- #[classattr]
- fn EVEN_ODD() -> FillRule {
- FillRule { value: 1 }
- }
-}
-
-#[pyclass(frozen, eq, hash, from_py_object)]
-#[derive(Clone, Copy, PartialEq, Eq, Hash)]
-pub struct Shading {
- pub(crate) value: u8,
-}
-
-#[allow(non_snake_case)]
-#[pymethods]
-impl Shading {
- #[classattr]
- fn UNLIT() -> Shading {
- Shading { value: 0 }
- }
- #[classattr]
- fn FLAT() -> Shading {
- Shading { value: 1 }
- }
- #[classattr]
- fn SMOOTH() -> Shading {
- Shading { value: 2 }
- }
-}
-
-#[pyclass(frozen, eq, hash, from_py_object)]
-#[derive(Clone, Copy, PartialEq, Eq, Hash)]
-pub struct Side {
- pub(crate) value: u8,
-}
-
-#[allow(non_snake_case)]
-#[pymethods]
-impl Side {
- #[classattr]
- fn FRONT() -> Side {
- Side { value: 0 }
- }
- #[classattr]
- fn BACK() -> Side {
- Side { value: 1 }
- }
- #[classattr]
- fn BOTH() -> Side {
- Side { value: 2 }
- }
-}
-
-#[pyclass(frozen)]
-pub struct PathCommand;
-
-#[pymethods]
-impl PathCommand {
- #[classattr]
- const MOVE_TO: u8 = 0;
- #[classattr]
- const LINE_TO: u8 = 1;
- #[classattr]
- const CUBIC_TO: u8 = 2;
- #[classattr]
- const QUAD_TO: u8 = 3;
- #[classattr]
- const CLOSE: u8 = 4;
-}
diff --git a/rust/src/renderer.rs b/rust/src/renderer.rs
deleted file mode 100644
index 0e71a73e..00000000
--- a/rust/src/renderer.rs
+++ /dev/null
@@ -1,1019 +0,0 @@
-use pyo3::prelude::*;
-use wgpu::util::DeviceExt;
-
-use crate::common::*;
-use crate::render_context::{ACTIVE, FRAME_INDEX, OPACITY, POSITION_X, SIDE, STRIDE, Z_INDEX};
-use crate::tessellation::{Mesh, Texture};
-
-#[allow(dead_code)]
-struct GpuMesh {
- vertex_buffer: wgpu::Buffer,
- index_buffer: wgpu::Buffer,
- draw_uniform_buffer: wgpu::Buffer,
- draw_bind_group: wgpu::BindGroup,
- index_count: u32,
- mobject_id: u32,
-}
-
-#[allow(dead_code)]
-struct GpuTexturedMesh {
- vertex_buffer: wgpu::Buffer,
- index_buffer: wgpu::Buffer,
- draw_uniform_buffer: wgpu::Buffer,
- draw_bind_group: wgpu::BindGroup,
- texture_bind_groups: Vec<wgpu::BindGroup>,
- index_count: u32,
- mobject_id: u32,
- frame_count: u32,
-}
-
-#[pyclass]
-#[allow(dead_code)]
-pub struct GpuRenderer {
- device: wgpu::Device,
- queue: wgpu::Queue,
- pipeline_cull_back: wgpu::RenderPipeline,
- pipeline_cull_front: wgpu::RenderPipeline,
- pipeline_cull_none: wgpu::RenderPipeline,
- msaa_texture: wgpu::Texture,
- depth_texture: wgpu::Texture,
- // NV12 compute conversion
- nv12_compute_pipeline: wgpu::ComputePipeline,
- nv12_bind_groups: [wgpu::BindGroup; PIPELINE_DEPTH],
- nv12_storage_buffers: [wgpu::Buffer; PIPELINE_DEPTH],
- nv12_staging_buffers: [wgpu::Buffer; PIPELINE_DEPTH],
- nv12_frame_size: u64,
- // Shared state
- camera_buffer: wgpu::Buffer,
- camera_bind_group: wgpu::BindGroup,
- draw_bind_group_layout: wgpu::BindGroupLayout,
- // Textured pipeline
- textured_pipeline: wgpu::RenderPipeline,
- texture_bind_group_layout: wgpu::BindGroupLayout,
- gpu_textured_meshes: Vec<GpuTexturedMesh>,
- width: u32,
- height: u32,
- gpu_meshes: Vec<GpuMesh>,
- num_mobjects: u32,
- background_color: [f32; 4],
-}
-
-#[pymethods]
-impl GpuRenderer {
- #[new]
- pub fn new(width: u32, height: u32) -> PyResult<Self> {
- let background_color = [0.0f32, 0.0, 0.0, 1.0];
- 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| {
- pyo3::exceptions::PyRuntimeError::new_err(format!("No GPU adapter found: {e}"))
- })?;
-
- let (device, queue) =
- pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor::default()))
- .map_err(|e| {
- pyo3::exceptions::PyRuntimeError::new_err(format!(
- "Failed to create device: {e}"
- ))
- })?;
-
- let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
- label: None,
- source: wgpu::ShaderSource::Wgsl(include_str!("shaders/main.wgsl").into()),
- });
-
- let draw_bind_group_layout =
- device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
- label: None,
- entries: &[wgpu::BindGroupLayoutEntry {
- binding: 0,
- visibility: wgpu::ShaderStages::VERTEX | wgpu::ShaderStages::FRAGMENT,
- ty: wgpu::BindingType::Buffer {
- ty: wgpu::BufferBindingType::Uniform,
- has_dynamic_offset: false,
- min_binding_size: None,
- },
- count: None,
- }],
- });
-
- let camera_bind_group_layout =
- device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
- label: None,
- entries: &[wgpu::BindGroupLayoutEntry {
- binding: 0,
- visibility: wgpu::ShaderStages::VERTEX,
- ty: wgpu::BindingType::Buffer {
- ty: wgpu::BufferBindingType::Uniform,
- has_dynamic_offset: false,
- min_binding_size: None,
- },
- count: None,
- }],
- });
-
- let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
- label: None,
- bind_group_layouts: &[&draw_bind_group_layout, &camera_bind_group_layout],
- immediate_size: 0,
- });
-
- let vertex_buffer_layouts = [
- // Primary vertex buffer (slot 0)
- wgpu::VertexBufferLayout {
- array_stride: std::mem::size_of::<Vertex>() as u64,
- step_mode: wgpu::VertexStepMode::Vertex,
- attributes: &[
- wgpu::VertexAttribute {
- format: wgpu::VertexFormat::Float32x3,
- offset: 0,
- shader_location: 0,
- },
- wgpu::VertexAttribute {
- format: wgpu::VertexFormat::Float32x3,
- offset: 12,
- shader_location: 1,
- },
- wgpu::VertexAttribute {
- format: wgpu::VertexFormat::Float32x2,
- offset: 24,
- shader_location: 2,
- },
- wgpu::VertexAttribute {
- format: wgpu::VertexFormat::Float32x4,
- offset: 32,
- shader_location: 3,
- },
- ],
- },
- ];
-
- let depth_format = wgpu::TextureFormat::Depth32Float;
-
- let create_pipeline = |cull_mode: Option<wgpu::Face>| {
- device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
- label: None,
- layout: Some(&pipeline_layout),
- vertex: wgpu::VertexState {
- module: &shader,
- entry_point: Some("vs_main"),
- buffers: &vertex_buffer_layouts,
- compilation_options: Default::default(),
- },
- fragment: Some(wgpu::FragmentState {
- module: &shader,
- entry_point: Some("fs_main"),
- targets: &[Some(wgpu::ColorTargetState {
- format: wgpu::TextureFormat::Rgba8Unorm,
- blend: Some(wgpu::BlendState::ALPHA_BLENDING),
- write_mask: wgpu::ColorWrites::ALL,
- })],
- compilation_options: Default::default(),
- }),
- primitive: wgpu::PrimitiveState {
- topology: wgpu::PrimitiveTopology::TriangleList,
- front_face: wgpu::FrontFace::Ccw,
- cull_mode,
- ..Default::default()
- },
- depth_stencil: Some(wgpu::DepthStencilState {
- format: depth_format,
- depth_write_enabled: true,
- depth_compare: wgpu::CompareFunction::LessEqual,
- stencil: wgpu::StencilState::default(),
- bias: wgpu::DepthBiasState::default(),
- }),
- multisample: wgpu::MultisampleState {
- count: MSAA_SAMPLES,
- mask: !0,
- alpha_to_coverage_enabled: false,
- },
- multiview_mask: None,
- cache: None,
- })
- };
-
- let pipeline_cull_back = create_pipeline(Some(wgpu::Face::Back));
- let pipeline_cull_front = create_pipeline(Some(wgpu::Face::Front));
- let pipeline_cull_none = create_pipeline(None);
-
- // Textured pipeline
- let textured_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
- label: None,
- source: wgpu::ShaderSource::Wgsl(include_str!("shaders/textured.wgsl").into()),
- });
-
- let texture_bind_group_layout =
- device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
- label: None,
- 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,
- },
- ],
- });
-
- let textured_pipeline_layout =
- device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
- label: None,
- bind_group_layouts: &[
- &draw_bind_group_layout,
- &camera_bind_group_layout,
- &texture_bind_group_layout,
- ],
- immediate_size: 0,
- });
-
- let textured_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
- label: None,
- layout: Some(&textured_pipeline_layout),
- vertex: wgpu::VertexState {
- module: &textured_shader,
- entry_point: Some("vs_main"),
- buffers: &[wgpu::VertexBufferLayout {
- array_stride: std::mem::size_of::<TexturedVertex>() as u64,
- step_mode: wgpu::VertexStepMode::Vertex,
- attributes: &[
- wgpu::VertexAttribute {
- format: wgpu::VertexFormat::Float32x3,
- offset: 0,
- shader_location: 0,
- },
- wgpu::VertexAttribute {
- format: wgpu::VertexFormat::Float32x2,
- offset: 12,
- shader_location: 1,
- },
- ],
- }],
- compilation_options: Default::default(),
- },
- fragment: Some(wgpu::FragmentState {
- module: &textured_shader,
- entry_point: Some("fs_main"),
- targets: &[Some(wgpu::ColorTargetState {
- format: wgpu::TextureFormat::Rgba8Unorm,
- blend: Some(wgpu::BlendState::ALPHA_BLENDING),
- write_mask: wgpu::ColorWrites::ALL,
- })],
- compilation_options: Default::default(),
- }),
- primitive: wgpu::PrimitiveState {
- topology: wgpu::PrimitiveTopology::TriangleList,
- front_face: wgpu::FrontFace::Ccw,
- cull_mode: None,
- ..Default::default()
- },
- depth_stencil: Some(wgpu::DepthStencilState {
- format: depth_format,
- depth_write_enabled: true,
- depth_compare: wgpu::CompareFunction::LessEqual,
- stencil: wgpu::StencilState::default(),
- bias: wgpu::DepthBiasState::default(),
- }),
- multisample: wgpu::MultisampleState {
- count: MSAA_SAMPLES,
- mask: !0,
- alpha_to_coverage_enabled: false,
- },
- multiview_mask: None,
- cache: None,
- });
-
- // MSAA texture — TEXTURE_BINDING lets the NV12 compute shader read samples directly
- let msaa_texture = device.create_texture(&wgpu::TextureDescriptor {
- label: None,
- size: wgpu::Extent3d {
- width,
- height,
- depth_or_array_layers: 1,
- },
- mip_level_count: 1,
- sample_count: MSAA_SAMPLES,
- dimension: wgpu::TextureDimension::D2,
- format: wgpu::TextureFormat::Rgba8Unorm,
- usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
- view_formats: &[],
- });
-
- // Depth texture (MSAA)
- let depth_texture = device.create_texture(&wgpu::TextureDescriptor {
- label: None,
- size: wgpu::Extent3d {
- width,
- height,
- depth_or_array_layers: 1,
- },
- mip_level_count: 1,
- sample_count: MSAA_SAMPLES,
- dimension: wgpu::TextureDimension::D2,
- format: depth_format,
- usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
- view_formats: &[],
- });
-
- // NV12 compute pipeline
- let nv12_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
- label: None,
- source: wgpu::ShaderSource::Wgsl(include_str!("shaders/nv12_convert.wgsl").into()),
- });
-
- let nv12_bind_group_layout =
- device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
- label: None,
- entries: &[
- wgpu::BindGroupLayoutEntry {
- binding: 0,
- visibility: wgpu::ShaderStages::COMPUTE,
- ty: wgpu::BindingType::Texture {
- sample_type: wgpu::TextureSampleType::Float { filterable: false },
- view_dimension: wgpu::TextureViewDimension::D2,
- multisampled: true,
- },
- count: None,
- },
- wgpu::BindGroupLayoutEntry {
- binding: 1,
- visibility: wgpu::ShaderStages::COMPUTE,
- ty: wgpu::BindingType::Buffer {
- ty: wgpu::BufferBindingType::Storage { read_only: false },
- has_dynamic_offset: false,
- min_binding_size: None,
- },
- count: None,
- },
- ],
- });
-
- let nv12_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
- label: None,
- bind_group_layouts: &[&nv12_bind_group_layout],
- immediate_size: 0,
- });
-
- let nv12_compute_pipeline =
- device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
- label: None,
- layout: Some(&nv12_pipeline_layout),
- module: &nv12_shader,
- entry_point: Some("nv12_convert"),
- compilation_options: Default::default(),
- cache: None,
- });
-
- let nv12_frame_size = (width as u64 * height as u64 * 3) / 2;
-
- let nv12_storage_buffers = std::array::from_fn(|_| {
- device.create_buffer(&wgpu::BufferDescriptor {
- label: None,
- size: nv12_frame_size,
- usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
- mapped_at_creation: false,
- })
- });
-
- let nv12_staging_buffers = std::array::from_fn(|_| {
- device.create_buffer(&wgpu::BufferDescriptor {
- label: None,
- size: nv12_frame_size,
- usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
- mapped_at_creation: false,
- })
- });
-
- let msaa_view = msaa_texture.create_view(&Default::default());
-
- let nv12_bind_groups = std::array::from_fn(|i| {
- device.create_bind_group(&wgpu::BindGroupDescriptor {
- label: None,
- layout: &nv12_bind_group_layout,
- entries: &[
- wgpu::BindGroupEntry {
- binding: 0,
- resource: wgpu::BindingResource::TextureView(&msaa_view),
- },
- wgpu::BindGroupEntry {
- binding: 1,
- resource: nv12_storage_buffers[i].as_entire_binding(),
- },
- ],
- })
- });
-
- let camera_uniforms = CameraUniforms {
- view_projection: orthographic_projection(width, height, 8.0),
- };
- let camera_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
- label: None,
- contents: bytemuck::bytes_of(&camera_uniforms),
- usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
- });
-
- let camera_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
- label: None,
- layout: &camera_bind_group_layout,
- entries: &[wgpu::BindGroupEntry {
- binding: 0,
- resource: camera_buffer.as_entire_binding(),
- }],
- });
-
- Ok(GpuRenderer {
- device,
- queue,
- pipeline_cull_back,
- pipeline_cull_front,
- pipeline_cull_none,
- msaa_texture,
- depth_texture,
- nv12_compute_pipeline,
- nv12_bind_groups,
- nv12_storage_buffers,
- nv12_staging_buffers,
- nv12_frame_size,
- camera_buffer,
- camera_bind_group,
- draw_bind_group_layout,
- textured_pipeline,
- texture_bind_group_layout,
- gpu_textured_meshes: Vec::new(),
- width,
- height,
- gpu_meshes: Vec::new(),
- num_mobjects: 0,
- background_color,
- })
- }
-}
-
-#[cfg_attr(target_os = "macos", allow(dead_code))]
-impl GpuRenderer {
- pub(crate) fn upload_meshes(
- &mut self,
- meshes: Vec<Mesh>,
- textures: &[Option<Texture>],
- mobject_ids: Vec<u32>,
- num_mobjects: u32,
- ) {
- self.gpu_meshes.clear();
- self.gpu_textured_meshes.clear();
- self.num_mobjects = num_mobjects;
-
- for (geo_idx, (geo, &mobject_id)) in meshes.iter().zip(mobject_ids.iter()).enumerate() {
- if let Some(tex) = textures.get(geo_idx).and_then(|t| t.as_ref()) {
- // Textured mesh path
- let vertices = build_textured_vertices(geo);
- let vertex_buffer =
- self.device
- .create_buffer_init(&wgpu::util::BufferInitDescriptor {
- label: None,
- contents: bytemuck::cast_slice(&vertices),
- usage: wgpu::BufferUsages::VERTEX,
- });
-
- let index_buffer =
- self.device
- .create_buffer_init(&wgpu::util::BufferInitDescriptor {
- label: None,
- contents: bytemuck::cast_slice(&geo.texture_indices),
- usage: wgpu::BufferUsages::INDEX,
- });
-
- let draw_uniform_buffer =
- self.device
- .create_buffer_init(&wgpu::util::BufferInitDescriptor {
- label: None,
- contents: bytemuck::bytes_of(&DrawUniforms {
- clip_threshold: 1.0,
- opacity: 1.0,
- shading: 0.0,
- _pad0: 0.0,
- position: [0.0, 0.0, 0.0, 0.0],
- scale: [1.0, 1.0, 1.0, 0.0],
- rotation: [0.0, 0.0, 0.0, 1.0],
- tint: [0.0, 0.0, 0.0, 0.0],
- }),
- usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
- });
-
- let draw_bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
- label: None,
- layout: &self.draw_bind_group_layout,
- entries: &[wgpu::BindGroupEntry {
- binding: 0,
- resource: draw_uniform_buffer.as_entire_binding(),
- }],
- });
-
- // Create sampler (shared across frames)
- let sampler = self.device.create_sampler(&wgpu::SamplerDescriptor {
- mag_filter: wgpu::FilterMode::Linear,
- min_filter: wgpu::FilterMode::Linear,
- address_mode_u: wgpu::AddressMode::ClampToEdge,
- address_mode_v: wgpu::AddressMode::ClampToEdge,
- ..Default::default()
- });
-
- // Create a GPU texture + bind group per frame
- let mut texture_bind_groups = Vec::with_capacity(tex.frames.len());
- let tex_size = wgpu::Extent3d {
- width: tex.width,
- height: tex.height,
- depth_or_array_layers: 1,
- };
-
- for frame_data in &tex.frames {
- let gpu_texture = self.device.create_texture(&wgpu::TextureDescriptor {
- label: None,
- size: tex_size,
- mip_level_count: 1,
- sample_count: 1,
- dimension: wgpu::TextureDimension::D2,
- format: wgpu::TextureFormat::Rgba8Unorm,
- usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
- view_formats: &[],
- });
-
- self.queue.write_texture(
- wgpu::TexelCopyTextureInfo {
- texture: &gpu_texture,
- mip_level: 0,
- origin: wgpu::Origin3d::ZERO,
- aspect: wgpu::TextureAspect::All,
- },
- frame_data,
- wgpu::TexelCopyBufferLayout {
- offset: 0,
- bytes_per_row: Some(tex.width * 4),
- rows_per_image: None,
- },
- tex_size,
- );
-
- let tex_view = gpu_texture.create_view(&Default::default());
- let bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
- label: None,
- layout: &self.texture_bind_group_layout,
- entries: &[
- wgpu::BindGroupEntry {
- binding: 0,
- resource: wgpu::BindingResource::TextureView(&tex_view),
- },
- wgpu::BindGroupEntry {
- binding: 1,
- resource: wgpu::BindingResource::Sampler(&sampler),
- },
- ],
- });
- texture_bind_groups.push(bind_group);
- }
-
- self.gpu_textured_meshes.push(GpuTexturedMesh {
- vertex_buffer,
- index_buffer,
- draw_uniform_buffer,
- draw_bind_group,
- texture_bind_groups,
- index_count: geo.texture_indices.len() as u32,
- mobject_id,
- frame_count: tex.frames.len() as u32,
- });
- continue;
- }
-
- // Solid mesh path
- for submesh in geo.submeshes.iter() {
- if submesh.indices.is_empty() {
- continue;
- }
-
- let vertices = build_vertices(submesh);
- let vertex_buffer =
- self.device
- .create_buffer_init(&wgpu::util::BufferInitDescriptor {
- label: None,
- contents: bytemuck::cast_slice(&vertices),
- usage: wgpu::BufferUsages::VERTEX,
- });
-
- let index_buffer =
- self.device
- .create_buffer_init(&wgpu::util::BufferInitDescriptor {
- label: None,
- contents: bytemuck::cast_slice(&submesh.indices),
- usage: wgpu::BufferUsages::INDEX,
- });
-
- let draw_uniform_buffer =
- self.device
- .create_buffer_init(&wgpu::util::BufferInitDescriptor {
- label: None,
- contents: bytemuck::bytes_of(&DrawUniforms {
- clip_threshold: 1.0,
- opacity: 1.0,
- shading: 0.0,
- _pad0: 0.0,
- position: [0.0, 0.0, 0.0, 0.0],
- scale: [1.0, 1.0, 1.0, 0.0],
- rotation: [0.0, 0.0, 0.0, 1.0],
- tint: [0.0, 0.0, 0.0, 0.0],
- }),
- usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
- });
-
- let draw_bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
- label: None,
- layout: &self.draw_bind_group_layout,
- entries: &[wgpu::BindGroupEntry {
- binding: 0,
- resource: draw_uniform_buffer.as_entire_binding(),
- }],
- });
-
- self.gpu_meshes.push(GpuMesh {
- vertex_buffer,
- index_buffer,
- draw_uniform_buffer,
- draw_bind_group,
- index_count: submesh.indices.len() as u32,
- mobject_id,
- });
- }
- }
- }
-}
-
-#[cfg_attr(target_os = "macos", allow(dead_code))]
-impl GpuRenderer {
- pub(crate) fn render_all_frames(
- &mut self,
- py: Python<'_>,
- evaluate_frame: &Py<PyAny>,
- surface_refs: &[Py<crate::tessellation::Surface>],
- object3d_refs: &[Py<crate::scene_node::Object3D>],
- camera_ref: &Py<crate::camera::Camera>,
- cfg: RenderConfig,
- ) -> PyResult<()> {
- self.render_loop(
- py,
- evaluate_frame,
- surface_refs,
- object3d_refs,
- camera_ref,
- &cfg,
- )
- .map_err(pyo3::exceptions::PyRuntimeError::new_err)
- }
-
- fn update_camera_state(&mut self, py: Python<'_>, camera_ref: &Py<crate::camera::Camera>) {
- let cam = camera_ref.borrow(py);
- let camera_uniforms = CameraUniforms {
- view_projection: build_view_projection(
- self.width,
- self.height,
- cam.frame_height,
- cam.position,
- cam.quaternion,
- cam.projection,
- cam.fov,
- ),
- };
- self.queue
- .write_buffer(&self.camera_buffer, 0, bytemuck::bytes_of(&camera_uniforms));
- self.background_color = [
- cam.background.0 as f32 / 255.0,
- cam.background.1 as f32 / 255.0,
- cam.background.2 as f32 / 255.0,
- 1.0,
- ];
- }
-
- fn encode_render_pass(&self, encoder: &mut wgpu::CommandEncoder, state: &[f32]) {
- let msaa_view = self.msaa_texture.create_view(&Default::default());
- let depth_view = self.depth_texture.create_view(&Default::default());
-
- // Classify meshes into opaque and transparent buckets
- let mut opaque_indices: Vec<usize> = Vec::new();
- let mut transparent_indices: Vec<usize> = Vec::new();
- for (i, gpu_mesh) in self.gpu_meshes.iter().enumerate() {
- let base = gpu_mesh.mobject_id as usize * STRIDE;
- if state[base + ACTIVE] == 0.0 || state[base + OPACITY] <= 0.0 {
- continue;
- }
- let opacity = state[base + OPACITY];
- if opacity >= 1.0 {
- opaque_indices.push(i);
- } else {
- transparent_indices.push(i);
- }
- }
-
- // Sort opaque by z_index ascending
- opaque_indices.sort_by(|&a, &b| {
- let za = state[self.gpu_meshes[a].mobject_id as usize * STRIDE + Z_INDEX];
- let zb = state[self.gpu_meshes[b].mobject_id as usize * STRIDE + Z_INDEX];
- za.partial_cmp(&zb).unwrap_or(std::cmp::Ordering::Equal)
- });
- // Sort transparent by z_index ascending, then position_z descending (back-to-front)
- transparent_indices.sort_by(|&a, &b| {
- let ba = self.gpu_meshes[a].mobject_id as usize * STRIDE;
- let bb = self.gpu_meshes[b].mobject_id as usize * STRIDE;
- let za = state[ba + Z_INDEX];
- let zb = state[bb + Z_INDEX];
- match za.partial_cmp(&zb).unwrap_or(std::cmp::Ordering::Equal) {
- std::cmp::Ordering::Equal => {
- let pza = state[ba + POSITION_X + 2];
- let pzb = state[bb + POSITION_X + 2];
- // Descending position_z (back-to-front)
- pzb.partial_cmp(&pza).unwrap_or(std::cmp::Ordering::Equal)
- }
- ord => ord,
- }
- });
-
- // Write uniforms for all active meshes (before beginning render pass)
- for &idx in opaque_indices.iter().chain(transparent_indices.iter()) {
- let gpu_mesh = &self.gpu_meshes[idx];
- let uniforms = build_draw_uniforms(state, gpu_mesh.mobject_id);
- self.queue.write_buffer(
- &gpu_mesh.draw_uniform_buffer,
- 0,
- bytemuck::bytes_of(&uniforms),
- );
- }
-
- {
- let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
- label: None,
- color_attachments: &[Some(wgpu::RenderPassColorAttachment {
- view: &msaa_view,
- resolve_target: None,
- ops: wgpu::Operations {
- load: wgpu::LoadOp::Clear(wgpu::Color {
- r: self.background_color[0] as f64,
- g: self.background_color[1] as f64,
- b: self.background_color[2] as f64,
- a: self.background_color[3] as f64,
- }),
- store: wgpu::StoreOp::Store,
- },
- depth_slice: None,
- })],
- depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
- view: &depth_view,
- depth_ops: Some(wgpu::Operations {
- load: wgpu::LoadOp::Clear(1.0),
- store: wgpu::StoreOp::Store,
- }),
- stencil_ops: None,
- }),
- ..Default::default()
- });
-
- rpass.set_bind_group(1, &self.camera_bind_group, &[]);
-
- // Pass 1: Opaque meshes, Pass 2: Transparent meshes
- for &idx in opaque_indices.iter().chain(transparent_indices.iter()) {
- let gpu_mesh = &self.gpu_meshes[idx];
- let base = gpu_mesh.mobject_id as usize * STRIDE;
-
- let side = state[base + SIDE] as u32;
- let pipeline = match side {
- 1 => &self.pipeline_cull_front,
- 2 => &self.pipeline_cull_none,
- _ => &self.pipeline_cull_back,
- };
- rpass.set_pipeline(pipeline);
-
- rpass.set_bind_group(0, &gpu_mesh.draw_bind_group, &[]);
- rpass.set_bind_group(1, &self.camera_bind_group, &[]);
- rpass.set_vertex_buffer(0, gpu_mesh.vertex_buffer.slice(..));
- rpass.set_index_buffer(gpu_mesh.index_buffer.slice(..), wgpu::IndexFormat::Uint32);
- rpass.draw_indexed(0..gpu_mesh.index_count, 0, 0..1);
- }
-
- // Draw textured meshes
- if !self.gpu_textured_meshes.is_empty() {
- rpass.set_pipeline(&self.textured_pipeline);
- rpass.set_bind_group(1, &self.camera_bind_group, &[]);
-
- for gpu_mesh in &self.gpu_textured_meshes {
- // Skip inactive or fully transparent meshes
- let base = gpu_mesh.mobject_id as usize * STRIDE;
- if state[base + ACTIVE] == 0.0 || state[base + OPACITY] <= 0.0 {
- continue;
- }
-
- let uniforms = build_draw_uniforms(state, gpu_mesh.mobject_id);
-
- self.queue.write_buffer(
- &gpu_mesh.draw_uniform_buffer,
- 0,
- bytemuck::bytes_of(&uniforms),
- );
-
- // Select frame
- let base = gpu_mesh.mobject_id as usize * STRIDE;
- let frame_idx = if gpu_mesh.frame_count > 1 && base + FRAME_INDEX < state.len()
- {
- (state[base + FRAME_INDEX] as usize) % gpu_mesh.frame_count as usize
- } else {
- 0
- };
-
- rpass.set_bind_group(0, &gpu_mesh.draw_bind_group, &[]);
- rpass.set_bind_group(2, &gpu_mesh.texture_bind_groups[frame_idx], &[]);
- rpass.set_vertex_buffer(0, gpu_mesh.vertex_buffer.slice(..));
- rpass.set_index_buffer(
- gpu_mesh.index_buffer.slice(..),
- wgpu::IndexFormat::Uint32,
- );
- rpass.draw_indexed(0..gpu_mesh.index_count, 0, 0..1);
- }
- }
- }
- }
-
- /// Render + NV12 compute + copy to staging. Returns SubmissionIndex for waiting.
- fn submit_frame(&self, state: &[f32], slot: usize) -> wgpu::SubmissionIndex {
- let mut encoder = self
- .device
- .create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
-
- self.encode_render_pass(&mut encoder, state);
-
- {
- let mut cpass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
- label: None,
- ..Default::default()
- });
- cpass.set_pipeline(&self.nv12_compute_pipeline);
- cpass.set_bind_group(0, &self.nv12_bind_groups[slot], &[]);
-
- let dispatch_x = (self.width / 4).div_ceil(8);
- let dispatch_y = (self.height / 2).div_ceil(8);
- cpass.dispatch_workgroups(dispatch_x, dispatch_y, 1);
- }
-
- encoder.copy_buffer_to_buffer(
- &self.nv12_storage_buffers[slot],
- 0,
- &self.nv12_staging_buffers[slot],
- 0,
- self.nv12_frame_size,
- );
-
- self.queue.submit(Some(encoder.finish()))
- }
-
- fn nv12_readback(&self, slot: usize, out: &mut [u8]) {
- let data = self.nv12_staging_buffers[slot].slice(..).get_mapped_range();
- out.copy_from_slice(&data[..out.len()]);
- drop(data);
- }
-
- fn render_loop(
- &mut self,
- py: Python<'_>,
- evaluate_frame: &Py<PyAny>,
- surface_refs: &[Py<crate::tessellation::Surface>],
- object3d_refs: &[Py<crate::scene_node::Object3D>],
- camera_ref: &Py<crate::camera::Camera>,
- cfg: &RenderConfig,
- ) -> Result<(), String> {
- let total_frames = ((cfg.total_duration * cfg.fps as f32) as u32).max(1);
- let fps = cfg.fps;
- let output_path = cfg.output_path.to_str().unwrap();
- let output_width = cfg.output_width;
- let output_height = cfg.output_height;
-
- let nv12_size = self.nv12_frame_size as usize;
- let fps_f32 = fps as f32;
-
- let pipeline = FfmpegPipeline::spawn(
- self.width,
- self.height,
- fps,
- output_path,
- nv12_size,
- output_width,
- output_height,
- )?;
-
- let initial = total_frames.min(PIPELINE_DEPTH as u32 - 1);
- let mut pending: std::collections::VecDeque<(usize, wgpu::SubmissionIndex)> =
- std::collections::VecDeque::new();
- let mut state: Vec<f32> = Vec::new();
-
- // Pre-fill pipeline slots
- for i in 0..initial {
- let t = i as f32 / fps_f32;
- let slot = i as usize % PIPELINE_DEPTH;
- evaluate_frame
- .call1(py, (t,))
- .map_err(|e| format!("evaluate_frame error: {e}"))?;
- crate::render_context::snapshot_surfaces(py, surface_refs, object3d_refs, &mut state);
- self.update_camera_state(py, camera_ref);
- let idx = self.submit_frame(&state, slot);
- pending.push_back((slot, idx));
- }
-
- if let Some((oldest_slot, oldest_idx)) = pending.front() {
- self.device
- .poll(wgpu::PollType::Wait {
- submission_index: Some(oldest_idx.clone()),
- timeout: None,
- })
- .unwrap();
- self.nv12_staging_buffers[*oldest_slot]
- .slice(..)
- .map_async(wgpu::MapMode::Read, |_| {});
- }
-
- // Submit new frame, then wait for oldest, readback, map next-oldest
- for frame_idx in initial..total_frames {
- let t = frame_idx as f32 / fps_f32;
- let slot = frame_idx as usize % PIPELINE_DEPTH;
-
- evaluate_frame
- .call1(py, (t,))
- .map_err(|e| format!("evaluate_frame error: {e}"))?;
- crate::render_context::snapshot_surfaces(py, surface_refs, object3d_refs, &mut state);
- self.update_camera_state(py, camera_ref);
- let new_idx = self.submit_frame(&state, slot);
-
- let (old_slot, old_idx) = pending.pop_front().unwrap();
- self.device
- .poll(wgpu::PollType::Wait {
- submission_index: Some(old_idx),
- timeout: None,
- })
- .unwrap();
-
- let mut pixels = pipeline
- .buf_pool_rx
- .recv()
- .map_err(|_| "Buffer pool closed".to_string())?;
- self.nv12_readback(old_slot, &mut pixels);
- self.nv12_staging_buffers[old_slot].unmap();
- pipeline
- .frame_tx
- .send(pixels)
- .map_err(|e| format!("Channel send error: {e}"))?;
-
- pending.push_back((slot, new_idx));
-
- if let Some((next_oldest_slot, _)) = pending.front() {
- self.nv12_staging_buffers[*next_oldest_slot]
- .slice(..)
- .map_async(wgpu::MapMode::Read, |_| {});
- }
- }
-
- // Drain remaining
- while let Some((old_slot, old_idx)) = pending.pop_front() {
- self.device
- .poll(wgpu::PollType::Wait {
- submission_index: Some(old_idx),
- timeout: None,
- })
- .unwrap();
-
- let mut pixels = pipeline
- .buf_pool_rx
- .recv()
- .map_err(|_| "Buffer pool closed".to_string())?;
- self.nv12_readback(old_slot, &mut pixels);
- self.nv12_staging_buffers[old_slot].unmap();
- pipeline
- .frame_tx
- .send(pixels)
- .map_err(|e| format!("Channel send error: {e}"))?;
-
- if let Some((next_slot, _)) = pending.front() {
- self.nv12_staging_buffers[*next_slot]
- .slice(..)
- .map_async(wgpu::MapMode::Read, |_| {});
- }
- }
-
- pipeline.finish()
- }
-}
diff --git a/rust/src/scene_node.rs b/rust/src/scene_node.rs
deleted file mode 100644
index 96372cbb..00000000
--- a/rust/src/scene_node.rs
+++ /dev/null
@@ -1,218 +0,0 @@
-use numpy::PyArray1;
-use pyo3::prelude::*;
-
-use crate::tessellation::Surface;
-
-// ── Quaternion helpers ──────────────────────────────────────────────────
-
-pub fn quat_mul(a: [f32; 4], b: [f32; 4]) -> [f32; 4] {
- let [ax, ay, az, aw] = a;
- let [bx, by, bz, bw] = b;
- [
- aw * bx + ax * bw + ay * bz - az * by,
- aw * by - ax * bz + ay * bw + az * bx,
- aw * bz + ax * by - ay * bx + az * bw,
- aw * bw - ax * bx - ay * by - az * bz,
- ]
-}
-
-pub fn quat_rotate_vec3(q: [f32; 4], v: [f32; 3]) -> [f32; 3] {
- let [qx, qy, qz, qw] = q;
- let [vx, vy, vz] = v;
- let tx = 2.0 * (qy * vz - qz * vy);
- let ty = 2.0 * (qz * vx - qx * vz);
- let tz = 2.0 * (qx * vy - qy * vx);
- [
- vx + qw * tx + (qy * tz - qz * ty),
- vy + qw * ty + (qz * tx - qx * tz),
- vz + qw * tz + (qx * ty - qy * tx),
- ]
-}
-
-// ── Object3D ───────────────────────────────────────────────────────────
-
-#[pyclass]
-pub struct Object3D {
- pub position: [f32; 3],
- pub scale: [f32; 3],
- pub quaternion: [f32; 4],
- pub(crate) parent: Option<Py<Object3D>>,
- pub(crate) children: Vec<Py<Object3D>>,
- pub(crate) surfaces: Vec<Py<Surface>>,
- #[pyo3(get, set)]
- pub active: bool,
-}
-
-#[pymethods]
-impl Object3D {
- #[new]
- #[pyo3(signature = (*surfaces))]
- fn new(surfaces: Vec<Py<Surface>>) -> Self {
- Object3D {
- position: [0.0, 0.0, 0.0],
- scale: [1.0, 1.0, 1.0],
- quaternion: [0.0, 0.0, 0.0, 1.0],
- parent: None,
- children: Vec::new(),
- surfaces,
- active: true,
- }
- }
-
- #[getter]
- fn surfaces(&self, py: Python<'_>) -> Vec<Py<Surface>> {
- self.surfaces.iter().map(|s| s.clone_ref(py)).collect()
- }
-
- // ── Transform getters/setters ───────────────────────────────────
-
- #[getter]
- fn position<'py>(&self, py: Python<'py>) -> Bound<'py, PyArray1<f32>> {
- PyArray1::from_slice(py, &self.position)
- }
-
- #[setter]
- fn set_position(&mut self, value: Vec<f32>) {
- self.position.copy_from_slice(&value[..3]);
- }
-
- #[getter]
- fn scale<'py>(&self, py: Python<'py>) -> Bound<'py, PyArray1<f32>> {
- PyArray1::from_slice(py, &self.scale)
- }
-
- #[setter]
- fn set_scale(&mut self, value: Vec<f32>) {
- self.scale.copy_from_slice(&value[..3]);
- }
-
- #[getter]
- fn quaternion<'py>(&self, py: Python<'py>) -> Bound<'py, PyArray1<f32>> {
- PyArray1::from_slice(py, &self.quaternion)
- }
-
- #[setter]
- fn set_quaternion(&mut self, value: Vec<f32>) {
- self.quaternion.copy_from_slice(&value[..4]);
- }
-
- // ── Parent (manages children lists) ─────────────────────────────
-
- #[getter]
- fn parent(&self, py: Python<'_>) -> Option<Py<Object3D>> {
- self.parent.as_ref().map(|p| p.clone_ref(py))
- }
-
- #[setter]
- fn set_parent(slf: &Bound<'_, Self>, value: Option<Py<Object3D>>) {
- let py = slf.py();
-
- // Remove from old parent's children
- {
- let this = slf.borrow();
- if let Some(ref old_parent_ref) = this.parent {
- let mut old_parent = old_parent_ref.borrow_mut(py);
- old_parent.children.retain(|c| !c.is(slf));
- }
- }
-
- // Add to new parent's children
- if let Some(ref new_parent_ref) = value {
- let mut new_parent = new_parent_ref.borrow_mut(py);
- new_parent.children.push(slf.clone().unbind());
- }
-
- // Set parent reference
- slf.borrow_mut().parent = value;
- }
-
- // ── Group transforms (propagate to all descendants) ─────────────
-
- fn shift(&mut self, py: Python<'_>, offset: Vec<f32>) {
- let off = [offset[0], offset[1], offset[2]];
- self.shift_recursive(py, off);
- }
-
- #[pyo3(signature = (quaternion, about=None))]
- fn rotate(&mut self, py: Python<'_>, quaternion: Vec<f32>, about: Option<Vec<f32>>) {
- let q = [quaternion[0], quaternion[1], quaternion[2], quaternion[3]];
- let pivot = about.map(|a| [a[0], a[1], a[2]]).unwrap_or(self.position);
- self.rotate_recursive(py, q, pivot);
- }
-
- #[pyo3(signature = (factor, about=None))]
- fn apply_scale(&mut self, py: Python<'_>, factor: Vec<f32>, about: Option<Vec<f32>>) {
- let f = [factor[0], factor[1], factor[2]];
- let pivot = about.map(|a| [a[0], a[1], a[2]]).unwrap_or(self.position);
- self.scale_recursive(py, f, pivot);
- }
-}
-
-// ── Recursive helpers (not exposed to Python) ───────────────────────────
-
-impl Object3D {
- fn shift_recursive(&mut self, py: Python<'_>, offset: [f32; 3]) {
- self.position[0] += offset[0];
- self.position[1] += offset[1];
- self.position[2] += offset[2];
- for child_ref in &self.children {
- child_ref.borrow_mut(py).shift_recursive(py, offset);
- }
- }
-
- fn rotate_recursive(&mut self, py: Python<'_>, q: [f32; 4], pivot: [f32; 3]) {
- // Rotate position around pivot
- let rel = [
- self.position[0] - pivot[0],
- self.position[1] - pivot[1],
- self.position[2] - pivot[2],
- ];
- let rotated = quat_rotate_vec3(q, rel);
- self.position = [
- pivot[0] + rotated[0],
- pivot[1] + rotated[1],
- pivot[2] + rotated[2],
- ];
- // Compose rotation
- self.quaternion = quat_mul(q, self.quaternion);
- for child_ref in &self.children {
- child_ref.borrow_mut(py).rotate_recursive(py, q, pivot);
- }
- }
-
- fn scale_recursive(&mut self, py: Python<'_>, factor: [f32; 3], pivot: [f32; 3]) {
- // Scale position relative to pivot
- self.position = [
- pivot[0] + factor[0] * (self.position[0] - pivot[0]),
- pivot[1] + factor[1] * (self.position[1] - pivot[1]),
- pivot[2] + factor[2] * (self.position[2] - pivot[2]),
- ];
- // Compose scale
- self.scale = [
- self.scale[0] * factor[0],
- self.scale[1] * factor[1],
- self.scale[2] * factor[2],
- ];
- for child_ref in &self.children {
- child_ref.borrow_mut(py).scale_recursive(py, factor, pivot);
- }
- }
-}
-
-/// Walk up the parent chain checking active flags.
-pub fn is_node_chain_active(py: Python<'_>, node: &Object3D) -> bool {
- if !node.active {
- return false;
- }
- let mut current = node.parent.as_ref().map(|p| p.clone_ref(py));
- loop {
- let Some(node_ref) = current else { break };
- let n = node_ref.borrow(py);
- if !n.active {
- return false;
- }
- current = n.parent.as_ref().map(|p| p.clone_ref(py));
- drop(n);
- }
- true
-}
diff --git a/rust/src/shaders/main.metal b/rust/src/shaders/main.metal
deleted file mode 100644
index 44c7fc01..00000000
--- a/rust/src/shaders/main.metal
+++ /dev/null
@@ -1,78 +0,0 @@
-#include <metal_stdlib>
-using namespace metal;
-
-struct CameraUniforms {
- float4x4 view_projection;
-};
-
-struct DrawUniforms {
- float clip_threshold;
- float opacity;
- float shading;
- float _pad0;
- float4 position;
- float4 scale;
- float4 rotation;
- float4 tint;
-};
-
-struct VertexInput {
- float3 position [[attribute(0)]];
- float3 normal [[attribute(1)]];
- float2 uv [[attribute(2)]];
- float4 color [[attribute(3)]];
-};
-
-struct VertexOutput {
- float4 clip_position [[position]];
- float2 uv;
- float4 color;
- float3 world_normal;
-};
-
-float3 quat_rotate(float4 q, float3 v) {
- float3 t = 2.0 * cross(q.xyz, v);
- return v + q.w * t + cross(q.xyz, t);
-}
-
-vertex VertexOutput vs_main(
- VertexInput in [[stage_in]],
- constant DrawUniforms& draw [[buffer(0)]],
- constant CameraUniforms& camera [[buffer(1)]]
-) {
- VertexOutput out;
- float4 q = normalize(draw.rotation);
- float3 scaled = in.position * draw.scale.xyz;
- float3 rotated = quat_rotate(q, scaled);
- float3 world_pos = rotated + draw.position.xyz;
- out.clip_position = camera.view_projection * float4(world_pos, 1.0);
- out.uv = in.uv;
- float3 base_rgb = draw.tint.rgb;
- out.color = float4(base_rgb, in.color.a * draw.opacity);
- // Transform normal: inverse-transpose for non-uniform scale = rotate(n / scale)
- out.world_normal = normalize(quat_rotate(q, in.normal / draw.scale.xyz));
- return out;
-}
-
-fragment float4 fs_main(
- VertexOutput in [[stage_in]],
- constant DrawUniforms& draw [[buffer(0)]]
-) {
- if (in.uv.x > draw.clip_threshold) {
- discard_fragment();
- }
- if (draw.shading < 0.5) {
- // Unlit: no lighting applied
- return in.color;
- }
- // Flat (shading >= 0.5 && < 1.5) and Smooth (shading >= 1.5) both use Phong
- float3 n = normalize(in.world_normal);
- float3 light_dir = normalize(float3(0.2, 0.3, 1.0));
- float ambient = 0.35;
- float diffuse = max(dot(n, light_dir), 0.0) * 0.55;
- float3 view_dir = float3(0.0, 0.0, 1.0);
- float3 half_vec = normalize(light_dir + view_dir);
- float spec = pow(max(dot(n, half_vec), 0.0), 32.0) * 0.15;
- float brightness = ambient + diffuse + spec;
- return float4(in.color.rgb * brightness, in.color.a);
-}
diff --git a/rust/src/shaders/main.wgsl b/rust/src/shaders/main.wgsl
deleted file mode 100644
index 6b2a28c5..00000000
--- a/rust/src/shaders/main.wgsl
+++ /dev/null
@@ -1,73 +0,0 @@
-struct CameraUniforms {
- view_projection: mat4x4<f32>,
-};
-
-struct DrawUniforms {
- clip_threshold: f32,
- opacity: f32,
- shading: f32,
- _pad0: f32,
- position: vec4<f32>,
- scale: vec4<f32>,
- rotation: vec4<f32>,
- tint: vec4<f32>,
-};
-
-@group(0) @binding(0) var<uniform> draw: DrawUniforms;
-@group(1) @binding(0) var<uniform> camera: CameraUniforms;
-
-struct VertexInput {
- @location(0) position: vec3<f32>,
- @location(1) normal: vec3<f32>,
- @location(2) uv: vec2<f32>,
- @location(3) color: vec4<f32>,
-};
-
-struct VertexOutput {
- @builtin(position) clip_position: vec4<f32>,
- @location(0) uv: vec2<f32>,
- @location(1) color: vec4<f32>,
- @location(2) world_normal: vec3<f32>,
-};
-
-fn quat_rotate(q: vec4<f32>, v: vec3<f32>) -> vec3<f32> {
- let t = 2.0 * cross(q.xyz, v);
- return v + q.w * t + cross(q.xyz, t);
-}
-
-@vertex
-fn vs_main(in: VertexInput) -> VertexOutput {
- var out: VertexOutput;
- let q = normalize(draw.rotation);
- let scaled = in.position * draw.scale.xyz;
- let rotated = quat_rotate(q, scaled);
- let world_pos = rotated + draw.position.xyz;
- out.clip_position = camera.view_projection * vec4<f32>(world_pos, 1.0);
- out.uv = in.uv;
- let base_rgb = draw.tint.rgb;
- out.color = vec4<f32>(base_rgb, in.color.a * draw.opacity);
- // Transform normal: inverse-transpose for non-uniform scale = rotate(n / scale)
- out.world_normal = normalize(quat_rotate(q, in.normal / draw.scale.xyz));
- return out;
-}
-
-@fragment
-fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
- if (in.uv.x > draw.clip_threshold) {
- discard;
- }
- if (draw.shading < 0.5) {
- // Unlit: no lighting applied
- return in.color;
- }
- // Flat (shading >= 0.5 && < 1.5) and Smooth (shading >= 1.5) both use Phong
- let n = normalize(in.world_normal);
- let light_dir = normalize(vec3<f32>(0.2, 0.3, 1.0));
- let ambient = 0.35;
- let diffuse = max(dot(n, light_dir), 0.0) * 0.55;
- let view_dir = vec3<f32>(0.0, 0.0, 1.0);
- let half_vec = normalize(light_dir + view_dir);
- let spec = pow(max(dot(n, half_vec), 0.0), 32.0) * 0.15;
- let brightness = ambient + diffuse + spec;
- return vec4<f32>(in.color.rgb * brightness, in.color.a);
-}
diff --git a/rust/src/shaders/nv12_convert.metal b/rust/src/shaders/nv12_convert.metal
deleted file mode 100644
index 642e1188..00000000
--- a/rust/src/shaders/nv12_convert.metal
+++ /dev/null
@@ -1,78 +0,0 @@
-// RGBA -> NV12 compute kernel (BT.601 limited range)
-//
-// Reads directly from the MSAA texture, manually resolving (averaging) all
-// samples per pixel — no intermediate RGBA resolve texture needed.
-//
-// Each thread handles a 4x2 pixel block: 8 MSAA resolves, 2 packed Y u32 writes,
-// 1 packed UV u32 write, zero branching.
-// Workgroup: (16,16), dispatched as (ceil(w/64), ceil(h/32)) groups.
-
-#include <metal_stdlib>
-using namespace metal;
-
-inline float4 resolve_pixel(texture2d_ms<float, access::read> src, uint x, uint y) {
- uint ns = src.get_num_samples();
- float4 acc = float4(0.0f);
- for (uint s = 0; s < ns; s++) {
- acc += src.read(uint2(x, y), s);
- }
- return acc / float(ns);
-}
-
-inline uint pack_y4(float4 a, float4 b, float4 c, float4 d) {
- uint ya = uint(clamp(16.0f + 65.481f * a.r + 128.553f * a.g + 24.966f * a.b, 16.0f, 235.0f));
- uint yb = uint(clamp(16.0f + 65.481f * b.r + 128.553f * b.g + 24.966f * b.b, 16.0f, 235.0f));
- uint yc = uint(clamp(16.0f + 65.481f * c.r + 128.553f * c.g + 24.966f * c.b, 16.0f, 235.0f));
- uint yd = uint(clamp(16.0f + 65.481f * d.r + 128.553f * d.g + 24.966f * d.b, 16.0f, 235.0f));
- return ya | (yb << 8) | (yc << 16) | (yd << 24);
-}
-
-inline uint pack_uv2(float4 avg_l, float4 avg_r) {
- uint u0 = uint(clamp(128.0f - 37.797f * avg_l.r - 74.203f * avg_l.g + 112.0f * avg_l.b, 16.0f, 240.0f));
- uint v0 = uint(clamp(128.0f + 112.0f * avg_l.r - 93.786f * avg_l.g - 18.214f * avg_l.b, 16.0f, 240.0f));
- uint u1 = uint(clamp(128.0f - 37.797f * avg_r.r - 74.203f * avg_r.g + 112.0f * avg_r.b, 16.0f, 240.0f));
- uint v1 = uint(clamp(128.0f + 112.0f * avg_r.r - 93.786f * avg_r.g - 18.214f * avg_r.b, 16.0f, 240.0f));
- return u0 | (v0 << 8) | (u1 << 16) | (v1 << 24);
-}
-
-kernel void nv12_convert(
- texture2d_ms<float, access::read> src [[texture(0)]],
- device uint32_t* dst [[buffer(0)]],
- uint2 gid [[thread_position_in_grid]]
-) {
- uint w = src.get_width();
- uint h = src.get_height();
-
- uint px = gid.x * 4;
- uint py = gid.y * 2;
-
- if (px >= w || py >= h) {
- return;
- }
-
- uint py1 = min(py + 1, h - 1);
-
- float4 r0c0 = resolve_pixel(src, px, py );
- float4 r0c1 = resolve_pixel(src, px + 1, py );
- float4 r0c2 = resolve_pixel(src, px + 2, py );
- float4 r0c3 = resolve_pixel(src, px + 3, py );
- float4 r1c0 = resolve_pixel(src, px, py1);
- float4 r1c1 = resolve_pixel(src, px + 1, py1);
- float4 r1c2 = resolve_pixel(src, px + 2, py1);
- float4 r1c3 = resolve_pixel(src, px + 3, py1);
-
- uint y_stride = w / 4;
-
- // Y plane — row 0 (always in bounds)
- dst[py * y_stride + gid.x] = pack_y4(r0c0, r0c1, r0c2, r0c3);
-
- // Y plane — row 1 (guard for odd-height images)
- if (py + 1 < h) {
- dst[(py + 1) * y_stride + gid.x] = pack_y4(r1c0, r1c1, r1c2, r1c3);
- }
-
- // UV plane — always written, no branch
- float4 avg_l = (r0c0 + r0c1 + r1c0 + r1c1) * 0.25f;
- float4 avg_r = (r0c2 + r0c3 + r1c2 + r1c3) * 0.25f;
- dst[w * h / 4 + gid.y * y_stride + gid.x] = pack_uv2(avg_l, avg_r);
-}
diff --git a/rust/src/shaders/nv12_convert.wgsl b/rust/src/shaders/nv12_convert.wgsl
deleted file mode 100644
index d46e8a01..00000000
--- a/rust/src/shaders/nv12_convert.wgsl
+++ /dev/null
@@ -1,77 +0,0 @@
-// RGBA -> NV12 compute shader (BT.601 limited range)
-//
-// Reads directly from the MSAA texture, manually resolving (averaging) all
-// samples per pixel — no intermediate RGBA resolve texture needed.
-//
-// Each thread handles a 4x2 pixel block: 8 MSAA resolves, 2 packed Y u32 writes,
-// 1 packed UV u32 write, zero branching.
-// Workgroup: (8,8) -> 32x16 pixels per workgroup.
-
-@group(0) @binding(0) var src: texture_multisampled_2d<f32>;
-@group(0) @binding(1) var<storage, read_write> dst: array<u32>;
-
-fn resolve_msaa(x: u32, y: u32) -> vec4<f32> {
- let ns = textureNumSamples(src);
- var acc = vec4<f32>(0.0);
- for (var s = 0i; s < i32(ns); s++) {
- acc += textureLoad(src, vec2<i32>(i32(x), i32(y)), s);
- }
- return acc / f32(ns);
-}
-
-fn pack_y4(a: vec4<f32>, b: vec4<f32>, c: vec4<f32>, d: vec4<f32>) -> u32 {
- let ya = u32(clamp(16.0 + 65.481 * a.r + 128.553 * a.g + 24.966 * a.b, 16.0, 235.0));
- let yb = u32(clamp(16.0 + 65.481 * b.r + 128.553 * b.g + 24.966 * b.b, 16.0, 235.0));
- let yc = u32(clamp(16.0 + 65.481 * c.r + 128.553 * c.g + 24.966 * c.b, 16.0, 235.0));
- let yd = u32(clamp(16.0 + 65.481 * d.r + 128.553 * d.g + 24.966 * d.b, 16.0, 235.0));
- return ya | (yb << 8u) | (yc << 16u) | (yd << 24u);
-}
-
-fn pack_uv2(avg_l: vec4<f32>, avg_r: vec4<f32>) -> u32 {
- let u0 = u32(clamp(128.0 - 37.797 * avg_l.r - 74.203 * avg_l.g + 112.0 * avg_l.b, 16.0, 240.0));
- let v0 = u32(clamp(128.0 + 112.0 * avg_l.r - 93.786 * avg_l.g - 18.214 * avg_l.b, 16.0, 240.0));
- let u1 = u32(clamp(128.0 - 37.797 * avg_r.r - 74.203 * avg_r.g + 112.0 * avg_r.b, 16.0, 240.0));
- let v1 = u32(clamp(128.0 + 112.0 * avg_r.r - 93.786 * avg_r.g - 18.214 * avg_r.b, 16.0, 240.0));
- return u0 | (v0 << 8u) | (u1 << 16u) | (v1 << 24u);
-}
-
-@compute @workgroup_size(8, 8)
-fn nv12_convert(@builtin(global_invocation_id) gid: vec3<u32>) {
- let dims = textureDimensions(src);
- let w = dims.x;
- let h = dims.y;
-
- let px = gid.x * 4u;
- let py = gid.y * 2u;
-
- if px >= w || py >= h {
- return;
- }
-
- let py1 = min(py + 1u, h - 1u);
-
- let r0c0 = resolve_msaa(px, py );
- let r0c1 = resolve_msaa(px + 1u, py );
- let r0c2 = resolve_msaa(px + 2u, py );
- let r0c3 = resolve_msaa(px + 3u, py );
- let r1c0 = resolve_msaa(px, py1);
- let r1c1 = resolve_msaa(px + 1u, py1);
- let r1c2 = resolve_msaa(px + 2u, py1);
- let r1c3 = resolve_msaa(px + 3u, py1);
-
- let y_stride = w / 4u;
-
- // Y plane — row 0 (always in bounds)
- dst[py * y_stride + gid.x] = pack_y4(r0c0, r0c1, r0c2, r0c3);
-
- // Y plane — row 1 (guard for odd-height images)
- if py + 1u < h {
- dst[(py + 1u) * y_stride + gid.x] = pack_y4(r1c0, r1c1, r1c2, r1c3);
- }
-
- // UV plane — always written, no branch
- let avg_l = (r0c0 + r0c1 + r1c0 + r1c1) * 0.25;
- let avg_r = (r0c2 + r0c3 + r1c2 + r1c3) * 0.25;
- let uv_base = w * h / 4u;
- dst[uv_base + gid.y * y_stride + gid.x] = pack_uv2(avg_l, avg_r);
-}
diff --git a/rust/src/shaders/textured.metal b/rust/src/shaders/textured.metal
deleted file mode 100644
index b67f3e07..00000000
--- a/rust/src/shaders/textured.metal
+++ /dev/null
@@ -1,59 +0,0 @@
-#include <metal_stdlib>
-using namespace metal;
-
-struct CameraUniforms {
- float4x4 view_projection;
-};
-
-struct DrawUniforms {
- float4 color;
- float clip_threshold;
- float opacity;
- float shading;
- float _pad0;
- float4 position;
- float4 scale;
- float4 rotation;
- float4 tint;
-};
-
-struct VertexInput {
- float3 position [[attribute(0)]];
- float2 uv [[attribute(1)]];
-};
-
-struct VertexOutput {
- float4 clip_position [[position]];
- float2 uv;
- float opacity;
-};
-
-float3 quat_rotate_tex(float4 q, float3 v) {
- float3 t = 2.0 * cross(q.xyz, v);
- return v + q.w * t + cross(q.xyz, t);
-}
-
-vertex VertexOutput vs_textured(
- VertexInput in [[stage_in]],
- constant DrawUniforms& draw [[buffer(0)]],
- constant CameraUniforms& camera [[buffer(1)]]
-) {
- VertexOutput out;
- float4 q = normalize(draw.rotation);
- float3 scaled = in.position * draw.scale.xyz;
- float3 rotated = quat_rotate_tex(q, scaled);
- float3 world_pos = rotated + draw.position.xyz;
- out.clip_position = camera.view_projection * float4(world_pos, 1.0);
- out.uv = in.uv;
- out.opacity = draw.color.a * draw.opacity;
- return out;
-}
-
-fragment float4 fs_textured(
- VertexOutput in [[stage_in]],
- texture2d<float> tex [[texture(0)]],
- sampler tex_sampler [[sampler(0)]]
-) {
- float4 tex_color = tex.sample(tex_sampler, in.uv);
- return float4(tex_color.rgb, tex_color.a * in.opacity);
-}
diff --git a/rust/src/shaders/textured.wgsl b/rust/src/shaders/textured.wgsl
deleted file mode 100644
index 7f2731da..00000000
--- a/rust/src/shaders/textured.wgsl
+++ /dev/null
@@ -1,55 +0,0 @@
-struct CameraUniforms {
- view_projection: mat4x4<f32>,
-};
-
-struct DrawUniforms {
- color: vec4<f32>,
- clip_threshold: f32,
- opacity: f32,
- shading: f32,
- _pad0: f32,
- position: vec4<f32>,
- scale: vec4<f32>,
- rotation: vec4<f32>,
- tint: vec4<f32>,
-};
-
-@group(0) @binding(0) var<uniform> draw: DrawUniforms;
-@group(1) @binding(0) var<uniform> camera: CameraUniforms;
-@group(2) @binding(0) var tex: texture_2d<f32>;
-@group(2) @binding(1) var tex_sampler: sampler;
-
-struct VertexInput {
- @location(0) position: vec3<f32>,
- @location(1) uv: vec2<f32>,
-};
-
-struct VertexOutput {
- @builtin(position) clip_position: vec4<f32>,
- @location(0) uv: vec2<f32>,
- @location(1) opacity: f32,
-};
-
-fn quat_rotate(q: vec4<f32>, v: vec3<f32>) -> vec3<f32> {
- let t = 2.0 * cross(q.xyz, v);
- return v + q.w * t + cross(q.xyz, t);
-}
-
-@vertex
-fn vs_main(in: VertexInput) -> VertexOutput {
- var out: VertexOutput;
- let q = normalize(draw.rotation);
- let scaled = in.position * draw.scale.xyz;
- let rotated = quat_rotate(q, scaled);
- let world_pos = rotated + draw.position.xyz;
- out.clip_position = camera.view_projection * vec4<f32>(world_pos, 1.0);
- out.uv = in.uv;
- out.opacity = draw.color.a * draw.opacity;
- return out;
-}
-
-@fragment
-fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
- let tex_color = textureSample(tex, tex_sampler, in.uv);
- return vec4<f32>(tex_color.rgb, tex_color.a * in.opacity);
-}
diff --git a/rust/src/tessellation.rs b/rust/src/tessellation.rs
deleted file mode 100644
index ab00ecce..00000000
--- a/rust/src/tessellation.rs
+++ /dev/null
@@ -1,1534 +0,0 @@
-use lyon::math::point;
-use lyon::path::Path as LyonPath;
-use lyon::tessellation::*;
-use pyo3::prelude::*;
-
-use crate::render_context::{FillRule as PyFillRule, Shading, Side};
-
-#[pyclass(skip_from_py_object)]
-#[derive(Clone)]
-pub struct SubMesh {
- /// Flat vertex positions [x0, y0, z0, x1, y1, z1, ...], f32
- #[pyo3(get)]
- pub positions: Vec<f32>,
- /// Flat vertex normals [nx0, ny0, nz0, nx1, ny1, nz1, ...], f32
- #[pyo3(get)]
- pub normals: Vec<f32>,
- /// Per-vertex progress (arc-length fraction 0..1), f32
- #[pyo3(get, set)]
- pub progress: Vec<f32>,
- /// RGBA color [r, g, b, a] normalized 0..1
- #[pyo3(get)]
- pub color: [f32; 4],
- /// Triangle indices, u32
- #[pyo3(get)]
- pub indices: Vec<u32>,
- /// 0 = fill, 1 = stroke
- #[pyo3(get)]
- pub kind: u32,
- /// Index of the SVG path this submesh was tessellated from
- #[pyo3(get)]
- pub path_index: u32,
- /// Per-vertex RGBA colors, flat [r0,g0,b0,a0, r1,g1,b1,a1, ...].
- /// When empty, `color` is used as a uniform fallback for every vertex.
- #[pyo3(get)]
- pub colors: Vec<f32>,
- /// Whether this submesh should be lit (1.0) or unlit (0.0)
- pub use_lighting: f32,
-}
-
-struct PathData {
- lyon_path: LyonPath,
- color: [f32; 4],
- arc_length: f32,
-}
-
-// ── Mesh ─────────────────────────────────────────────────────────────
-
-/// Immutable vertex/index data produced by tessellation.
-#[pyclass(from_py_object)]
-#[derive(Clone)]
-pub struct Mesh {
- #[pyo3(get)]
- pub submeshes: Vec<SubMesh>,
- /// Per-path arc lengths (one entry per SVG path that produced a submesh)
- #[pyo3(get)]
- pub arc_lengths: Vec<f32>,
- /// Bounding box after normalization [min_x, min_y, min_z, max_x, max_y, max_z]
- #[pyo3(get)]
- pub bounds: [f32; 6],
-
- // Texture quad geometry — separate from SubMesh pipeline.
- // Populated by build_textured_quad (pixel data lives in Texture).
- /// Flat vertex positions for the textured quad [x0,y0,z0, x1,y1,z1, ...]
- pub texture_positions: Vec<f32>,
- /// Flat UV coordinates [u0,v0, u1,v1, ...]
- pub texture_uvs: Vec<f32>,
- /// Triangle indices for the textured quad
- pub texture_indices: Vec<u32>,
-}
-
-#[pymethods]
-impl Mesh {
- #[staticmethod]
- fn empty() -> Self {
- Mesh {
- submeshes: Vec::new(),
- arc_lengths: Vec::new(),
- bounds: [0.0; 6],
- texture_positions: Vec::new(),
- texture_uvs: Vec::new(),
- texture_indices: Vec::new(),
- }
- }
-
- #[getter]
- fn submesh_count(&self) -> usize {
- self.submeshes.len()
- }
-
- fn get_submesh_kind(&self, index: usize) -> u32 {
- self.submeshes[index].kind
- }
-
- fn get_submesh_progress(&self, index: usize) -> Vec<f32> {
- self.submeshes[index].progress.clone()
- }
-
- fn get_submesh_path_index(&self, index: usize) -> u32 {
- self.submeshes[index].path_index
- }
-
- fn set_submesh_progress(&mut self, index: usize, progress: Vec<f32>) {
- self.submeshes[index].progress = progress;
- }
-}
-
-// ── TessellationResult ──────────────────────────────────────────────
-
-/// Result of tessellation: separate fill and stroke meshes.
-#[pyclass]
-pub struct TessellationResult {
- #[pyo3(get)]
- pub fill_mesh: Option<Py<Mesh>>,
- #[pyo3(get)]
- pub stroke_mesh: Option<Py<Mesh>>,
- /// Per-path arc lengths for coordinating draw progress across fill+stroke
- pub arc_lengths: Vec<f32>,
-}
-
-#[pymethods]
-impl TessellationResult {}
-
-// ── Texture ──────────────────────────────────────────────────────────
-
-/// Opaque handle to GPU texture data (pixel frames).
-#[pyclass(from_py_object)]
-#[derive(Clone)]
-pub struct Texture {
- pub frames: Vec<Vec<u8>>,
- pub width: u32,
- pub height: u32,
-}
-
-// ── Material ─────────────────────────────────────────────────────────
-
-/// Surface appearance properties. Stored on Surface and read per-frame
-/// by the snapshot/render pipeline.
-#[pyclass]
-pub struct Material {
- #[pyo3(get, set)]
- pub color: (u8, u8, u8),
- #[pyo3(get, set)]
- pub opacity: f32,
- #[pyo3(get, set)]
- pub shading: Shading,
- #[pyo3(get, set)]
- pub metallic: f32,
- #[pyo3(get, set)]
- pub roughness: f32,
- #[pyo3(get, set)]
- pub emissive: (u8, u8, u8),
- #[pyo3(get, set)]
- pub side: Side,
- pub(crate) texture: Option<Py<Texture>>,
-}
-
-#[pymethods]
-impl Material {
- #[new]
- #[pyo3(signature = (*, color=(255, 255, 255), opacity=1.0, shading=None, side=None, texture=None, metallic=0.0, roughness=0.5, emissive=(0, 0, 0)))]
- #[allow(clippy::too_many_arguments)]
- fn new(
- color: (u8, u8, u8),
- opacity: f32,
- shading: Option<Shading>,
- side: Option<Side>,
- texture: Option<Py<Texture>>,
- metallic: f32,
- roughness: f32,
- emissive: (u8, u8, u8),
- ) -> Self {
- Material {
- color,
- opacity,
- shading: shading.unwrap_or(Shading { value: 0 }),
- side: side.unwrap_or(Side { value: 0 }),
- texture,
- metallic,
- roughness,
- emissive,
- }
- }
-
- #[getter]
- fn texture(&self, py: Python<'_>) -> Option<Py<Texture>> {
- self.texture.as_ref().map(|t| t.clone_ref(py))
- }
-
- #[setter]
- fn set_texture(&mut self, value: Option<Py<Texture>>) {
- self.texture = value;
- }
-}
-
-// ── Surface ──────────────────────────────────────────────────────────
-
-/// Geometry + appearance — **what to draw**.
-///
-/// Pairs a Mesh with a Material. Carries no transform of its own.
-/// Attach to an Object3D (which controls *where* it is drawn).
-/// Swapping the `mesh` reference triggers a GPU re-upload via the
-/// generation counter.
-#[pyclass]
-pub struct Surface {
- pub(crate) mesh: Py<Mesh>,
- pub(crate) material: Py<Material>,
- #[pyo3(get, set)]
- pub active: bool,
- #[pyo3(get, set)]
- pub z_index: f32,
- /// Internal: the fragment shader discards pixels where u > clip_threshold.
- /// Always 1.0 (fully active). Progressive reveal will be reimplemented
- /// without leaking GPU concerns into the public API.
- pub clip_threshold: f32,
- /// Incremented when mesh is swapped. Renderer uses this to detect
- /// when vertex buffers need re-upload.
- pub generation: u32,
-}
-
-#[pymethods]
-impl Surface {
- #[new]
- fn new(mesh: Py<Mesh>, material: Py<Material>) -> Self {
- Surface {
- mesh,
- material,
- active: true,
- z_index: 0.0,
- clip_threshold: 1.0,
- generation: 0,
- }
- }
-
- #[getter]
- fn mesh(&self, py: Python<'_>) -> Py<Mesh> {
- self.mesh.clone_ref(py)
- }
-
- #[setter]
- fn set_mesh(&mut self, m: Py<Mesh>) {
- self.mesh = m;
- self.generation += 1;
- }
-
- #[getter]
- fn material(&self, py: Python<'_>) -> Py<Material> {
- self.material.clone_ref(py)
- }
-
- #[setter]
- fn set_material(&mut self, mat: Py<Material>) {
- self.material = mat;
- }
-}
-
-// ── SVG Glyph Data ──────────────────────────────────────────────────
-
-/// Per-glyph tessellation result from SVG. Each SVG path produces one glyph.
-#[pyclass]
-pub struct SvgGlyphData {
- #[pyo3(get)]
- pub fill_mesh: Option<Py<Mesh>>,
- #[pyo3(get)]
- pub stroke_mesh: Option<Py<Mesh>>,
- #[pyo3(get)]
- pub color: (u8, u8, u8),
-}
-
-/// Tracks which submesh indices belong to which glyph during SVG tessellation.
-struct SvgGlyphRange {
- fill_start: usize,
- fill_count: usize,
- stroke_path_index: Option<usize>, // index into path_data for auto-stroke
- color: [f32; 4],
-}
-
-/// Tessellate an SVG document into per-glyph meshes.
-/// Each SVG path becomes a separate SvgGlyphData with its own fill and stroke meshes.
-#[pyfunction]
-pub fn tessellate_svg(py: Python<'_>, svg_bytes: &[u8]) -> PyResult<Vec<SvgGlyphData>> {
- let options = usvg::Options::default();
- let tree = usvg::Tree::from_data(svg_bytes, &options)
- .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("SVG parse error: {e}")))?;
-
- let mut fills: Vec<SubMesh> = Vec::new();
- let mut path_data: Vec<PathData> = Vec::new();
- let mut glyph_ranges: Vec<SvgGlyphRange> = Vec::new();
- walk_group_tracked(tree.root(), &mut fills, &mut path_data, &mut glyph_ranges);
-
- // Auto-stroke width from combined fill bbox height
- let bbox_height = if fills.is_empty() {
- 1.0
- } else {
- let (_, min_y, _, _, max_y, _) = compute_bbox(&fills);
- let h = max_y - min_y;
- if h > 1e-9 { h } else { 1.0 }
- };
- let auto_sw = bbox_height * 0.008;
-
- // Generate auto-strokes (one per glyph that has path_data)
- let mut auto_strokes: Vec<Option<SubMesh>> = vec![None; glyph_ranges.len()];
- for (gi, range) in glyph_ranges.iter().enumerate() {
- if let Some(pdi) = range.stroke_path_index
- && let Some(mut sm) = tessellate_stroke(&path_data[pdi], auto_sw)
- {
- sm.path_index = pdi as u32;
- auto_strokes[gi] = Some(sm);
- }
- }
-
- // Compute combined bbox from fills + auto_strokes without cloning
- let mut combined_bbox = compute_bbox(&fills);
- for sm in auto_strokes.iter().flatten() {
- combined_bbox = extend_bbox(combined_bbox, sm);
- }
- if combined_bbox.0 == f32::MAX {
- combined_bbox = (0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
- }
-
- // Normalize everything against the shared bbox (in place)
- normalize_submeshes_with_ref(&mut fills, combined_bbox);
- for sm in auto_strokes.iter_mut().flatten() {
- normalize_submeshes_with_ref(std::slice::from_mut(sm), combined_bbox);
- }
-
- // Compute bounds from all normalized submeshes without cloning
- let mut norm_bbox = compute_bbox(&fills);
- for sm in auto_strokes.iter().flatten() {
- norm_bbox = extend_bbox(norm_bbox, sm);
- }
- let bounds = if norm_bbox.0 != f32::MAX {
- bbox_to_bounds(norm_bbox)
- } else {
- [0.0; 6]
- };
-
- // Build per-glyph Mesh objects
- let make_mesh = |submeshes: Vec<SubMesh>, arc_lens: Vec<f32>| -> Mesh {
- Mesh {
- submeshes,
- arc_lengths: arc_lens,
- bounds, // shared bounds for all glyphs
- texture_positions: Vec::new(),
- texture_uvs: Vec::new(),
- texture_indices: Vec::new(),
- }
- };
-
- let mut result: Vec<SvgGlyphData> = Vec::new();
- for (gi, range) in glyph_ranges.iter().enumerate() {
- let glyph_fills: Vec<SubMesh> =
- fills[range.fill_start..range.fill_start + range.fill_count].to_vec();
- let glyph_arc_lengths: Vec<f32> = glyph_fills
- .iter()
- .filter_map(|sm| {
- path_data
- .get(sm.path_index as usize)
- .map(|pd| pd.arc_length)
- })
- .collect();
-
- let fill_mesh = if glyph_fills.is_empty() {
- None
- } else {
- Some(Py::new(
- py,
- make_mesh(glyph_fills, glyph_arc_lengths.clone()),
- )?)
- };
-
- let stroke_mesh = if let Some(stroke_sm) = auto_strokes[gi].take() {
- Some(Py::new(py, make_mesh(vec![stroke_sm], glyph_arc_lengths))?)
- } else {
- None
- };
-
- let c = range.color;
- let color = (
- (c[0] * 255.0).round() as u8,
- (c[1] * 255.0).round() as u8,
- (c[2] * 255.0).round() as u8,
- );
-
- result.push(SvgGlyphData {
- fill_mesh,
- stroke_mesh,
- color,
- });
- }
-
- Ok(result)
-}
-
-fn walk_group_tracked(
- group: &usvg::Group,
- fills: &mut Vec<SubMesh>,
- path_data: &mut Vec<PathData>,
- glyph_ranges: &mut Vec<SvgGlyphRange>,
-) {
- for child in group.children() {
- match child {
- usvg::Node::Group(g) => walk_group_tracked(g, fills, path_data, glyph_ranges),
- usvg::Node::Path(path) => {
- let fill_start = fills.len();
- let pd_start = path_data.len();
-
- // Use existing tessellate_usvg_path to populate fills and path_data
- tessellate_usvg_path(path, fills, path_data);
-
- let fill_count = fills.len() - fill_start;
- let stroke_path_index = if path_data.len() > pd_start {
- Some(pd_start)
- } else {
- None
- };
-
- // Extract color from the fill submesh or use white default
- let color = if fill_count > 0 {
- fills[fill_start].color
- } else {
- [1.0, 1.0, 1.0, 1.0]
- };
-
- if fill_count > 0 || stroke_path_index.is_some() {
- glyph_ranges.push(SvgGlyphRange {
- fill_start,
- fill_count,
- stroke_path_index,
- color,
- });
- }
- }
- _ => {} // Skip Image, Text
- }
- }
-}
-
-fn tessellate_usvg_path(
- path: &usvg::Path,
- fills: &mut Vec<SubMesh>,
- path_data: &mut Vec<PathData>,
-) {
- let (segments, total_length) = collect_segments_with_length(path.data(), path.abs_transform());
- let (lyon_path, arc_length) = build_lyon_path_from_segments(&segments, total_length);
-
- // Handle fill
- if let Some(fill) = path.fill()
- && let Some(color) = extract_fill_color(fill)
- {
- let fill_rule = match fill.rule() {
- usvg::FillRule::NonZero => FillRule::NonZero,
- usvg::FillRule::EvenOdd => FillRule::EvenOdd,
- };
-
- let options = FillOptions::default().with_fill_rule(fill_rule);
-
- // Vertex type: [x, y, progress]
- let mut geometry: VertexBuffers<[f32; 3], u32> = VertexBuffers::new();
- let mut tessellator = FillTessellator::new();
-
- let result = tessellator.tessellate_path(
- &lyon_path,
- &options,
- &mut BuffersBuilder::new(&mut geometry, |mut vertex: FillVertex| {
- let pos = vertex.position();
- let progress = vertex.interpolated_attributes()[0];
- [pos.x, pos.y, progress]
- }),
- );
-
- if let Ok(()) = result
- && !geometry.indices.is_empty()
- {
- // Assign chord-closure progress: each fill vertex gets the minimum
- // clip_threshold at which it falls inside the chord-closed partial
- // path, matching manim CE's pointwise_become_partial fill.
- let boundary = sample_boundary_points(&segments, total_length);
- assign_fill_chord_progress(&mut geometry.vertices, &boundary);
-
- let num_verts = geometry.vertices.len();
- let positions: Vec<f32> = geometry
- .vertices
- .iter()
- .flat_map(|v| [v[0], v[1], 0.0])
- .collect();
- let normals: Vec<f32> = [0.0, 0.0, 1.0].repeat(num_verts);
- let progress: Vec<f32> = geometry.vertices.iter().map(|v| v[2]).collect();
- let pi = path_data.len() as u32;
-
- fills.push(SubMesh {
- positions,
- normals,
- progress,
- color,
- indices: geometry.indices,
- kind: 0,
- path_index: pi,
- colors: Vec::new(),
- use_lighting: 0.0,
- });
-
- // Store path for auto-stroke tessellation
- path_data.push(PathData {
- lyon_path: lyon_path.clone(),
- color,
- arc_length,
- });
- }
- }
-
- // Handle explicit SVG stroke (e.g. from Typst text stroke settings).
- // These are treated as fills (kind=0) so they render with fill_opacity
- // and aren't hidden when stroke_opacity is set to 0.
- if let Some(stroke) = path.stroke()
- && let Some(color) = extract_stroke_color(stroke)
- {
- let line_cap = match stroke.linecap() {
- usvg::LineCap::Butt => LineCap::Butt,
- usvg::LineCap::Round => LineCap::Round,
- usvg::LineCap::Square => LineCap::Square,
- };
- let line_join = match stroke.linejoin() {
- usvg::LineJoin::Miter | usvg::LineJoin::MiterClip => LineJoin::Miter,
- usvg::LineJoin::Round => LineJoin::Round,
- usvg::LineJoin::Bevel => LineJoin::Bevel,
- };
- let width = stroke.width().get();
-
- let options = StrokeOptions::default()
- .with_line_width(width)
- .with_line_cap(line_cap)
- .with_line_join(line_join)
- .with_miter_limit(stroke.miterlimit().get());
-
- let mut geometry: VertexBuffers<[f32; 3], u32> = VertexBuffers::new();
- let mut tessellator = StrokeTessellator::new();
-
- let result = tessellator.tessellate_path(
- &lyon_path,
- &options,
- &mut BuffersBuilder::new(&mut geometry, |mut vertex: StrokeVertex| {
- let pos = vertex.position();
- let progress = vertex.interpolated_attributes()[0];
- [pos.x, pos.y, progress]
- }),
- );
-
- if let Ok(()) = result
- && !geometry.indices.is_empty()
- {
- let num_verts = geometry.vertices.len();
- let positions: Vec<f32> = geometry
- .vertices
- .iter()
- .flat_map(|v| [v[0], v[1], 0.0])
- .collect();
- let normals: Vec<f32> = [0.0, 0.0, 1.0].repeat(num_verts);
- let progress: Vec<f32> = geometry.vertices.iter().map(|v| v[2]).collect();
- let pi = if path_data.is_empty() {
- 0
- } else {
- path_data.len() as u32 - 1
- };
-
- fills.push(SubMesh {
- positions,
- normals,
- progress,
- color,
- indices: geometry.indices,
- kind: 0, // Treat as fill so it's not affected by stroke_opacity
- path_index: pi,
- colors: Vec::new(),
- use_lighting: 0.0,
- });
- }
- }
-}
-
-type BBox = (f32, f32, f32, f32, f32, f32);
-
-const EMPTY_BBOX: BBox = (f32::MAX, f32::MAX, f32::MAX, f32::MIN, f32::MIN, f32::MIN);
-
-fn compute_bbox(submeshes: &[SubMesh]) -> BBox {
- let mut bb = EMPTY_BBOX;
- for sm in submeshes {
- bb = extend_bbox(bb, sm);
- }
- bb
-}
-
-/// Extend a bounding box with a single submesh's positions.
-fn extend_bbox(bb: BBox, sm: &SubMesh) -> BBox {
- let (mut min_x, mut min_y, mut min_z, mut max_x, mut max_y, mut max_z) = bb;
- for i in (0..sm.positions.len()).step_by(3) {
- let x = sm.positions[i];
- let y = sm.positions[i + 1];
- let z = sm.positions[i + 2];
- min_x = min_x.min(x);
- min_y = min_y.min(y);
- min_z = min_z.min(z);
- max_x = max_x.max(x);
- max_y = max_y.max(y);
- max_z = max_z.max(z);
- }
- (min_x, min_y, min_z, max_x, max_y, max_z)
-}
-
-/// Merge two bounding boxes into the smallest box containing both.
-fn merge_bboxes(a: BBox, b: BBox) -> BBox {
- (
- a.0.min(b.0),
- a.1.min(b.1),
- a.2.min(b.2),
- a.3.max(b.3),
- a.4.max(b.4),
- a.5.max(b.5),
- )
-}
-
-fn bbox_to_bounds(bb: BBox) -> [f32; 6] {
- let (min_x, min_y, min_z, max_x, max_y, max_z) = bb;
- [min_x, min_y, min_z, max_x, max_y, max_z]
-}
-
-/// Stroke with miter joins (sharp corners) for explicit user-requested strokes.
-fn tessellate_stroke_miter(pd: &PathData, stroke_width: f32) -> Option<SubMesh> {
- let options = StrokeOptions::default()
- .with_line_width(stroke_width)
- .with_line_cap(LineCap::Butt)
- .with_line_join(LineJoin::Miter)
- .with_miter_limit(4.0)
- .with_tolerance(0.005);
-
- let mut geometry: VertexBuffers<[f32; 3], u32> = VertexBuffers::new();
- let mut tessellator = StrokeTessellator::new();
-
- let result = tessellator.tessellate_path(
- &pd.lyon_path,
- &options,
- &mut BuffersBuilder::new(&mut geometry, |mut vertex: StrokeVertex| {
- let pos = vertex.position();
- let progress = vertex.interpolated_attributes()[0];
- [pos.x, pos.y, progress]
- }),
- );
-
- if let Ok(()) = result
- && !geometry.indices.is_empty()
- {
- let num_verts = geometry.vertices.len();
- let positions: Vec<f32> = geometry
- .vertices
- .iter()
- .flat_map(|v| [v[0], v[1], 0.0])
- .collect();
- let normals: Vec<f32> = [0.0, 0.0, 1.0].repeat(num_verts);
- let progress: Vec<f32> = geometry.vertices.iter().map(|v| v[2]).collect();
-
- Some(SubMesh {
- positions,
- normals,
- progress,
- color: pd.color,
- indices: geometry.indices,
- kind: 1,
- path_index: 0,
- colors: Vec::new(),
- use_lighting: 0.0,
- })
- } else {
- None
- }
-}
-
-/// Stroke with round joins/caps for auto-stroke outlines.
-fn tessellate_stroke(pd: &PathData, stroke_width: f32) -> Option<SubMesh> {
- let options = StrokeOptions::default()
- .with_line_width(stroke_width)
- .with_line_cap(LineCap::Round)
- .with_line_join(LineJoin::Round)
- .with_tolerance(0.005);
-
- let mut geometry: VertexBuffers<[f32; 3], u32> = VertexBuffers::new();
- let mut tessellator = StrokeTessellator::new();
-
- let result = tessellator.tessellate_path(
- &pd.lyon_path,
- &options,
- &mut BuffersBuilder::new(&mut geometry, |mut vertex: StrokeVertex| {
- let pos = vertex.position();
- let progress = vertex.interpolated_attributes()[0];
- [pos.x, pos.y, progress]
- }),
- );
-
- if let Ok(()) = result
- && !geometry.indices.is_empty()
- {
- let num_verts = geometry.vertices.len();
- let positions: Vec<f32> = geometry
- .vertices
- .iter()
- .flat_map(|v| [v[0], v[1], 0.0])
- .collect();
- let normals: Vec<f32> = [0.0, 0.0, 1.0].repeat(num_verts);
- let progress: Vec<f32> = geometry.vertices.iter().map(|v| v[2]).collect();
-
- Some(SubMesh {
- positions,
- normals,
- progress,
- color: pd.color,
- indices: geometry.indices,
- kind: 1,
- path_index: 0, // Set by caller
- colors: Vec::new(),
- use_lighting: 0.0,
- })
- } else {
- None
- }
-}
-
-fn extract_fill_color(fill: &usvg::Fill) -> Option<[f32; 4]> {
- match fill.paint() {
- usvg::Paint::Color(c) => {
- let opacity = fill.opacity().get();
- Some([
- c.red as f32 / 255.0,
- c.green as f32 / 255.0,
- c.blue as f32 / 255.0,
- opacity,
- ])
- }
- _ => None, // Skip gradients, patterns for now
- }
-}
-
-fn extract_stroke_color(stroke: &usvg::Stroke) -> Option<[f32; 4]> {
- match stroke.paint() {
- usvg::Paint::Color(c) => {
- let opacity = stroke.opacity().get();
- Some([
- c.red as f32 / 255.0,
- c.green as f32 / 255.0,
- c.blue as f32 / 255.0,
- opacity,
- ])
- }
- _ => None,
- }
-}
-
-/// Build a lyon Path from pre-collected path segments with arc-length progress.
-fn build_lyon_path_from_segments(
- segments: &[(PathSeg, f32)],
- total_length: f32,
-) -> (LyonPath, f32) {
- let mut builder = LyonPath::builder_with_attributes(1);
- let progress = |cum: f32| -> f32 {
- if total_length > 0.0 {
- cum / total_length
- } else {
- 0.0
- }
- };
-
- let mut has_open_path = false;
- for (seg, cum) in segments {
- let p = progress(*cum);
- match seg {
- PathSeg::MoveTo(x, y) => {
- if has_open_path {
- builder.end(false);
- }
- builder.begin(point(*x, *y), &[p]);
- has_open_path = true;
- }
- PathSeg::LineTo(x, y) => {
- builder.line_to(point(*x, *y), &[p]);
- }
- PathSeg::CubicTo(c1x, c1y, c2x, c2y, ex, ey) => {
- builder.cubic_bezier_to(
- point(*c1x, *c1y),
- point(*c2x, *c2y),
- point(*ex, *ey),
- &[p],
- );
- }
- PathSeg::QuadTo(cx, cy, ex, ey) => {
- builder.quadratic_bezier_to(point(*cx, *cy), point(*ex, *ey), &[p]);
- }
- PathSeg::Close => {
- builder.end(true);
- has_open_path = false;
- }
- }
- }
-
- if has_open_path {
- builder.end(false);
- }
-
- (builder.build(), total_length)
-}
-
-enum PathSeg {
- MoveTo(f32, f32),
- LineTo(f32, f32),
- CubicTo(f32, f32, f32, f32, f32, f32),
- QuadTo(f32, f32, f32, f32),
- Close,
-}
-
-fn collect_segments_with_length(
- data: &usvg::tiny_skia_path::Path,
- transform: usvg::Transform,
-) -> (Vec<(PathSeg, f32)>, f32) {
- let mut segments: Vec<(PathSeg, f32)> = Vec::new();
- let mut cumulative = 0.0f32;
- let mut last: Option<(f32, f32)> = None;
-
- for seg in data.segments() {
- match seg {
- usvg::tiny_skia_path::PathSegment::MoveTo(pt) => {
- let (x, y) = apply_transform(pt.x, pt.y, transform);
- // MoveTo adds no arc length; store cumulative before the move.
- segments.push((PathSeg::MoveTo(x, y), cumulative));
- last = Some((x, y));
- }
- usvg::tiny_skia_path::PathSegment::LineTo(pt) => {
- let (x, y) = apply_transform(pt.x, pt.y, transform);
- if let Some((lx, ly)) = last {
- let dx = x - lx;
- let dy = y - ly;
- cumulative += (dx * dx + dy * dy).sqrt();
- }
- segments.push((PathSeg::LineTo(x, y), cumulative));
- last = Some((x, y));
- }
- usvg::tiny_skia_path::PathSegment::CubicTo(pt1, pt2, pt3) => {
- let (c1x, c1y) = apply_transform(pt1.x, pt1.y, transform);
- let (c2x, c2y) = apply_transform(pt2.x, pt2.y, transform);
- let (ex, ey) = apply_transform(pt3.x, pt3.y, transform);
- if let Some((lx, ly)) = last {
- cumulative += cubic_arc_length(lx, ly, c1x, c1y, c2x, c2y, ex, ey);
- }
- segments.push((PathSeg::CubicTo(c1x, c1y, c2x, c2y, ex, ey), cumulative));
- last = Some((ex, ey));
- }
- usvg::tiny_skia_path::PathSegment::QuadTo(pt1, pt2) => {
- let (cx, cy) = apply_transform(pt1.x, pt1.y, transform);
- let (ex, ey) = apply_transform(pt2.x, pt2.y, transform);
- if let Some((lx, ly)) = last {
- cumulative += quad_arc_length(lx, ly, cx, cy, ex, ey);
- }
- segments.push((PathSeg::QuadTo(cx, cy, ex, ey), cumulative));
- last = Some((ex, ey));
- }
- usvg::tiny_skia_path::PathSegment::Close => {
- segments.push((PathSeg::Close, cumulative));
- last = None;
- }
- }
- }
-
- (segments, cumulative)
-}
-
-fn apply_transform(x: f32, y: f32, t: usvg::Transform) -> (f32, f32) {
- let tx = t.sx * x + t.kx * y + t.tx;
- let ty = t.ky * x + t.sy * y + t.ty;
- (tx, ty)
-}
-
-/// Approximate cubic bezier arc length using recursive subdivision.
-#[allow(clippy::too_many_arguments)]
-fn cubic_arc_length(
- x0: f32,
- y0: f32,
- c1x: f32,
- c1y: f32,
- c2x: f32,
- c2y: f32,
- x3: f32,
- y3: f32,
-) -> f32 {
- cubic_arc_length_recursive(x0, y0, c1x, c1y, c2x, c2y, x3, y3, 0)
-}
-
-#[allow(clippy::too_many_arguments)]
-fn cubic_arc_length_recursive(
- x0: f32,
- y0: f32,
- c1x: f32,
- c1y: f32,
- c2x: f32,
- c2y: f32,
- x3: f32,
- y3: f32,
- depth: u32,
-) -> f32 {
- // Chord length
- let dx = x3 - x0;
- let dy = y3 - y0;
- let chord = (dx * dx + dy * dy).sqrt();
-
- // Control polygon length
- let d1x = c1x - x0;
- let d1y = c1y - y0;
- let d2x = c2x - c1x;
- let d2y = c2y - c1y;
- let d3x = x3 - c2x;
- let d3y = y3 - c2y;
- let poly = (d1x * d1x + d1y * d1y).sqrt()
- + (d2x * d2x + d2y * d2y).sqrt()
- + (d3x * d3x + d3y * d3y).sqrt();
-
- if depth > 8 || (poly - chord).abs() < 0.01 {
- return (chord + poly) / 2.0;
- }
-
- // De Casteljau split at t=0.5
- let m01x = (x0 + c1x) / 2.0;
- let m01y = (y0 + c1y) / 2.0;
- let m12x = (c1x + c2x) / 2.0;
- let m12y = (c1y + c2y) / 2.0;
- let m23x = (c2x + x3) / 2.0;
- let m23y = (c2y + y3) / 2.0;
- let m012x = (m01x + m12x) / 2.0;
- let m012y = (m01y + m12y) / 2.0;
- let m123x = (m12x + m23x) / 2.0;
- let m123y = (m12y + m23y) / 2.0;
- let mx = (m012x + m123x) / 2.0;
- let my = (m012y + m123y) / 2.0;
-
- cubic_arc_length_recursive(x0, y0, m01x, m01y, m012x, m012y, mx, my, depth + 1)
- + cubic_arc_length_recursive(mx, my, m123x, m123y, m23x, m23y, x3, y3, depth + 1)
-}
-
-/// Approximate quadratic bezier arc length.
-fn quad_arc_length(x0: f32, y0: f32, cx: f32, cy: f32, x2: f32, y2: f32) -> f32 {
- // Elevate to cubic
- let c1x = x0 + 2.0 / 3.0 * (cx - x0);
- let c1y = y0 + 2.0 / 3.0 * (cy - y0);
- let c2x = x2 + 2.0 / 3.0 * (cx - x2);
- let c2y = y2 + 2.0 / 3.0 * (cy - y2);
- cubic_arc_length(x0, y0, c1x, c1y, c2x, c2y, x2, y2)
-}
-
-/// Sample boundary points from path segments for chord-closure progress.
-/// Returns a dense set of (x, y, progress) points along the path.
-fn sample_boundary_points(segments: &[(PathSeg, f32)], total_length: f32) -> Vec<(f32, f32, f32)> {
- let progress = |cum: f32| -> f32 {
- if total_length > 0.0 {
- cum / total_length
- } else {
- 0.0
- }
- };
-
- let mut points = Vec::new();
- let mut last: Option<(f32, f32)> = None;
- let samples_per_segment = 16;
-
- for (seg, cum) in segments {
- match seg {
- PathSeg::MoveTo(x, y) => {
- points.push((*x, *y, progress(*cum)));
- last = Some((*x, *y));
- }
- PathSeg::LineTo(x, y) => {
- if let Some((lx, ly)) = last {
- let prev_cum = *cum - ((x - lx).powi(2) + (y - ly).powi(2)).sqrt();
- for i in 1..=samples_per_segment {
- let t = i as f32 / samples_per_segment as f32;
- let px = lx + t * (x - lx);
- let py = ly + t * (y - ly);
- let p = progress(prev_cum + t * (*cum - prev_cum));
- points.push((px, py, p));
- }
- }
- last = Some((*x, *y));
- }
- PathSeg::CubicTo(c1x, c1y, c2x, c2y, ex, ey) => {
- if let Some((lx, ly)) = last {
- let seg_len = cubic_arc_length(lx, ly, *c1x, *c1y, *c2x, *c2y, *ex, *ey);
- let prev_cum = *cum - seg_len;
- for i in 1..=samples_per_segment {
- let t = i as f32 / samples_per_segment as f32;
- let mt = 1.0 - t;
- let px = mt.powi(3) * lx
- + 3.0 * mt * mt * t * c1x
- + 3.0 * mt * t * t * c2x
- + t.powi(3) * ex;
- let py = mt.powi(3) * ly
- + 3.0 * mt * mt * t * c1y
- + 3.0 * mt * t * t * c2y
- + t.powi(3) * ey;
- let p = progress(prev_cum + t * seg_len);
- points.push((px, py, p));
- }
- }
- last = Some((*ex, *ey));
- }
- PathSeg::QuadTo(cx, cy, ex, ey) => {
- if let Some((lx, ly)) = last {
- let seg_len = quad_arc_length(lx, ly, *cx, *cy, *ex, *ey);
- let prev_cum = *cum - seg_len;
- for i in 1..=samples_per_segment {
- let t = i as f32 / samples_per_segment as f32;
- let mt = 1.0 - t;
- let px = mt * mt * lx + 2.0 * mt * t * cx + t * t * ex;
- let py = mt * mt * ly + 2.0 * mt * t * cy + t * t * ey;
- let p = progress(prev_cum + t * seg_len);
- points.push((px, py, p));
- }
- }
- last = Some((*ex, *ey));
- }
- PathSeg::Close => {
- last = None;
- }
- }
- }
-
- points
-}
-
-/// Ray-casting point-in-polygon test for the partial polygon:
-/// boundary[0], boundary[1], ..., boundary[k] with an implicit closing
-/// edge from boundary[k] back to boundary[0].
-fn point_in_partial_polygon(vx: f32, vy: f32, boundary: &[(f32, f32, f32)], k: usize) -> bool {
- let mut inside = false;
- let mut j = k;
- for i in 0..=k {
- let (xi, yi) = (boundary[i].0, boundary[i].1);
- let (xj, yj) = (boundary[j].0, boundary[j].1);
- if ((yi > vy) != (yj > vy)) && (vx < (xj - xi) * (vy - yi) / (yj - yi) + xi) {
- inside = !inside;
- }
- j = i;
- }
- inside
-}
-
-/// Compute the minimum progress α at which (vx, vy) is inside the
-/// chord-closed partial path: arc[0→α] + chord(P(α)→P(0)).
-/// This matches manim CE's `pointwise_become_partial` + fill behaviour
-/// where the enclosed area grows as the path is progressively revealed.
-fn chord_closure_progress(vx: f32, vy: f32, boundary: &[(f32, f32, f32)]) -> f32 {
- let n = boundary.len();
- if n < 3 {
- return 1.0;
- }
- for k in 2..n {
- if point_in_partial_polygon(vx, vy, boundary, k) {
- return boundary[k].2;
- }
- }
- 1.0
-}
-
-/// Assign chord-closure progress to all fill vertices.
-/// For each vertex, finds the minimum clip_threshold at which it would be
-/// inside the polygon formed by the partial arc + closing chord. This
-/// replaces the nearest-boundary-point algorithm to match manim CE's
-/// partial-path fill behaviour.
-fn assign_fill_chord_progress(vertices: &mut [[f32; 3]], boundary: &[(f32, f32, f32)]) {
- // Compute the maximum distance any vertex has from its nearest boundary
- // point. This lets us distinguish boundary vertices from interior ones.
- // Lyon sometimes tessellates shapes with only boundary vertices (e.g.
- // circles), in which case chord-closure ray casting is unreliable
- // because the test point sits exactly on a polygon edge.
- let mut max_boundary_dist = 0.0_f32;
- for v in vertices.iter() {
- let (vx, vy) = (v[0], v[1]);
- let mut best_d2 = f32::MAX;
- for &(bx, by, _) in boundary {
- let d2 = (vx - bx) * (vx - bx) + (vy - by) * (vy - by);
- if d2 < best_d2 {
- best_d2 = d2;
- }
- }
- let d = best_d2.sqrt();
- if d > max_boundary_dist {
- max_boundary_dist = d;
- }
- }
-
- // Threshold: vertices closer than 1% of max depth are "on the boundary".
- let boundary_eps = max_boundary_dist * 0.01;
-
- for v in vertices.iter_mut() {
- let (vx, vy) = (v[0], v[1]);
-
- // Find nearest boundary point and distance.
- let mut best_dist_sq = f32::MAX;
- let mut best_progress = v[2];
- for &(bx, by, bp) in boundary {
- let d2 = (vx - bx) * (vx - bx) + (vy - by) * (vy - by);
- if d2 < best_dist_sq {
- best_dist_sq = d2;
- best_progress = bp;
- }
- }
-
- if best_dist_sq.sqrt() <= boundary_eps {
- // Vertex is on/near the boundary: use arc-length progress.
- v[2] = best_progress;
- } else {
- // Interior vertex: use chord-closure progress.
- v[2] = chord_closure_progress(vx, vy, boundary);
- }
- }
-}
-
-/// Collect path segments with arc-length from flat command arrays.
-fn collect_segments_from_commands(
- command_types: &[u8],
- command_data: &[f32],
-) -> (Vec<(PathSeg, f32)>, f32) {
- let mut segments: Vec<(PathSeg, f32)> = Vec::new();
- let mut cumulative = 0.0f32;
- let mut last: Option<(f32, f32)> = None;
- let mut di = 0; // data index
-
- for &cmd in command_types {
- match cmd {
- 0 => {
- // MoveTo(x, y)
- let x = command_data[di];
- let y = command_data[di + 1];
- di += 2;
- segments.push((PathSeg::MoveTo(x, y), cumulative));
- last = Some((x, y));
- }
- 1 => {
- // LineTo(x, y)
- let x = command_data[di];
- let y = command_data[di + 1];
- di += 2;
- if let Some((lx, ly)) = last {
- let dx = x - lx;
- let dy = y - ly;
- cumulative += (dx * dx + dy * dy).sqrt();
- }
- segments.push((PathSeg::LineTo(x, y), cumulative));
- last = Some((x, y));
- }
- 2 => {
- // CubicTo(c1x, c1y, c2x, c2y, ex, ey)
- let c1x = command_data[di];
- let c1y = command_data[di + 1];
- let c2x = command_data[di + 2];
- let c2y = command_data[di + 3];
- let ex = command_data[di + 4];
- let ey = command_data[di + 5];
- di += 6;
- if let Some((lx, ly)) = last {
- cumulative += cubic_arc_length(lx, ly, c1x, c1y, c2x, c2y, ex, ey);
- }
- segments.push((PathSeg::CubicTo(c1x, c1y, c2x, c2y, ex, ey), cumulative));
- last = Some((ex, ey));
- }
- 3 => {
- // QuadTo(cx, cy, ex, ey)
- let cx = command_data[di];
- let cy = command_data[di + 1];
- let ex = command_data[di + 2];
- let ey = command_data[di + 3];
- di += 4;
- if let Some((lx, ly)) = last {
- cumulative += quad_arc_length(lx, ly, cx, cy, ex, ey);
- }
- segments.push((PathSeg::QuadTo(cx, cy, ex, ey), cumulative));
- last = Some((ex, ey));
- }
- 4 => {
- // Close
- segments.push((PathSeg::Close, cumulative));
- last = None;
- }
- _ => {}
- }
- }
-
- (segments, cumulative)
-}
-
-/// Tessellate path commands into separate fill and stroke geometries.
-///
-/// Handles tessellation resolution scaling, reference bounds, and auto-stroke
-/// logic internally. Color/opacity are not passed here; they live on Material.
-///
-/// * `stroke_width` – when > 0, generate an explicit stroke. When 0,
-/// a thin auto-stroke outline is generated. Negative suppresses all strokes.
-#[pyfunction]
-#[pyo3(signature = (command_types, command_data, *, fill_rule=None, stroke_width=0.0))]
-pub fn tessellate(
- py: Python<'_>,
- command_types: Vec<u8>,
- command_data: Vec<f32>,
- fill_rule: Option<PyFillRule>,
- stroke_width: f32,
-) -> PyResult<TessellationResult> {
- let color = [1.0, 1.0, 1.0, 1.0];
-
- // Decide auto-stroke: when no explicit stroke width is given.
- // Negative stroke_width explicitly suppresses all strokes (fill only).
- let auto_stroke = stroke_width == 0.0;
-
- let (segments, total_length) = collect_segments_from_commands(&command_types, &command_data);
- let (lyon_path, arc_length) = build_lyon_path_from_segments(&segments, total_length);
-
- let lr = if fill_rule.map_or(0, |r| r.value) == 1 {
- FillRule::EvenOdd
- } else {
- FillRule::NonZero
- };
- // Use tight tolerance for sub-pixel curve approximation at 1080p.
- let options = FillOptions::default()
- .with_fill_rule(lr)
- .with_tolerance(0.005);
-
- let mut fills: Vec<SubMesh> = Vec::new();
- let mut path_data: Vec<PathData> = Vec::new();
-
- // Tessellate fill
- let mut geometry: VertexBuffers<[f32; 3], u32> = VertexBuffers::new();
- let mut tessellator = FillTessellator::new();
-
- let result = tessellator.tessellate_path(
- &lyon_path,
- &options,
- &mut BuffersBuilder::new(&mut geometry, |mut vertex: FillVertex| {
- let pos = vertex.position();
- let progress = vertex.interpolated_attributes()[0];
- [pos.x, pos.y, progress]
- }),
- );
-
- if let Ok(()) = result
- && !geometry.indices.is_empty()
- {
- // Always populate path_data (needed for stroke generation)
- path_data.push(PathData {
- lyon_path,
- color,
- arc_length,
- });
-
- // Always create fill submesh (visibility controlled by Material.opacity)
- let boundary = sample_boundary_points(&segments, total_length);
- assign_fill_chord_progress(&mut geometry.vertices, &boundary);
-
- let num_verts = geometry.vertices.len();
- let positions: Vec<f32> = geometry
- .vertices
- .iter()
- .flat_map(|v| [v[0], v[1], 0.0])
- .collect();
- let normals: Vec<f32> = [0.0, 0.0, 1.0].repeat(num_verts);
- let progress: Vec<f32> = geometry.vertices.iter().map(|v| v[2]).collect();
-
- fills.push(SubMesh {
- positions,
- normals,
- progress,
- color,
- indices: geometry.indices,
- kind: 0,
- path_index: 0,
- colors: Vec::new(),
- use_lighting: 0.0,
- });
- }
-
- // Stroke generation
- let mut strokes: Vec<SubMesh> = Vec::new();
- if stroke_width > 0.0 {
- // Explicit stroke with user-specified width (color comes from Material)
- for (i, pd) in path_data.iter().enumerate() {
- if let Some(mut sm) = tessellate_stroke_miter(pd, stroke_width) {
- sm.color = color;
- sm.path_index = i as u32;
- strokes.push(sm);
- }
- }
- } else if auto_stroke {
- // Auto-stroke: thin outline proportional to bounding box height
- let bbox_height = if fills.is_empty() {
- 1.0
- } else {
- let (_, min_y, _, _, max_y, _) = compute_bbox(&fills);
- let h = max_y - min_y;
- if h > 1e-9 { h } else { 1.0 }
- };
- let auto_sw = bbox_height * 0.008;
-
- for (i, pd) in path_data.iter().enumerate() {
- if let Some(mut stroke_sm) = tessellate_stroke(pd, auto_sw) {
- stroke_sm.path_index = i as u32;
- strokes.push(stroke_sm);
- }
- }
- }
-
- let arc_lengths: Vec<f32> = path_data.iter().map(|pd| pd.arc_length).collect();
-
- // Flip Y axis: PlanarPath uses math convention (Y-up at start angle -π/2),
- // negating Y makes shapes match Manim CE's visual orientation.
- fn flip_y(submeshes: &mut [SubMesh]) {
- for sm in submeshes.iter_mut() {
- for i in (1..sm.positions.len()).step_by(3) {
- sm.positions[i] = -sm.positions[i];
- }
- }
- }
- flip_y(&mut fills);
- flip_y(&mut strokes);
-
- // Compute bounds from all submeshes in path-space coordinates (post Y-flip)
- // without cloning.
- let bounds = {
- let bb = merge_bboxes(compute_bbox(&fills), compute_bbox(&strokes));
- if bb.0 != f32::MAX {
- bbox_to_bounds(bb)
- } else {
- [0.0; 6]
- }
- };
-
- let make_empty_geo = || Mesh {
- submeshes: Vec::new(),
- arc_lengths: Vec::new(),
- bounds,
- texture_positions: Vec::new(),
- texture_uvs: Vec::new(),
- texture_indices: Vec::new(),
- };
-
- let fill_geo = if fills.is_empty() {
- None
- } else {
- let mut geo = make_empty_geo();
- geo.submeshes = fills;
- geo.arc_lengths = arc_lengths.clone();
- Some(Py::new(py, geo)?)
- };
-
- let stroke_geo = if strokes.is_empty() {
- None
- } else {
- let mut geo = make_empty_geo();
- geo.submeshes = strokes;
- geo.arc_lengths = arc_lengths.clone();
- Some(Py::new(py, geo)?)
- };
-
- Ok(TessellationResult {
- fill_mesh: fill_geo,
- stroke_mesh: stroke_geo,
- arc_lengths,
- })
-}
-
-/// Center and scale submeshes using the given reference bounding box.
-fn normalize_submeshes_with_ref(
- submeshes: &mut [SubMesh],
- ref_bbox: (f32, f32, f32, f32, f32, f32),
-) {
- if submeshes.is_empty() {
- return;
- }
-
- let (min_x, min_y, min_z, max_x, max_y, max_z) = ref_bbox;
- let cx = (min_x + max_x) / 2.0;
- let cy = (min_y + max_y) / 2.0;
- let cz = (min_z + max_z) / 2.0;
- let height = max_y - min_y;
- let scale = if height > 1e-9 { 1.0 / height } else { 1.0 };
-
- // Center and scale, flip Y (SVG Y is down, manim Y is up)
- for sm in submeshes.iter_mut() {
- for i in (0..sm.positions.len()).step_by(3) {
- sm.positions[i] = (sm.positions[i] - cx) * scale;
- sm.positions[i + 1] = -(sm.positions[i + 1] - cy) * scale;
- sm.positions[i + 2] = (sm.positions[i + 2] - cz) * scale;
- }
- }
-}
-
-/// Center submeshes at origin and scale so the max extent = 1.0 (no Y flip).
-fn normalize_submeshes_3d(submeshes: &mut [SubMesh]) {
- if submeshes.is_empty() {
- return;
- }
-
- let (min_x, min_y, min_z, max_x, max_y, max_z) = compute_bbox(submeshes);
- let cx = (min_x + max_x) / 2.0;
- let cy = (min_y + max_y) / 2.0;
- let cz = (min_z + max_z) / 2.0;
- let extent = (max_x - min_x).max(max_y - min_y).max(max_z - min_z);
- let scale = if extent > 1e-9 { 1.0 / extent } else { 1.0 };
-
- for sm in submeshes.iter_mut() {
- for i in (0..sm.positions.len()).step_by(3) {
- sm.positions[i] = (sm.positions[i] - cx) * scale;
- sm.positions[i + 1] = (sm.positions[i + 1] - cy) * scale;
- sm.positions[i + 2] = (sm.positions[i + 2] - cz) * scale;
- }
- }
-}
-
-/// Build a mesh from pre-computed 3D vertex data (positions, normals, indices).
-#[pyfunction]
-#[pyo3(signature = (positions, normals, indices, *, color=[255, 255, 255], opacity=1.0))]
-pub fn build_surface(
- positions: Vec<f32>,
- normals: Vec<f32>,
- indices: Vec<u32>,
- color: [u8; 3],
- opacity: f32,
-) -> PyResult<Mesh> {
- let num_verts = positions.len() / 3;
- let color = [
- color[0] as f32 / 255.0,
- color[1] as f32 / 255.0,
- color[2] as f32 / 255.0,
- opacity,
- ];
-
- let progress = vec![0.0; num_verts];
-
- let mut submeshes = vec![SubMesh {
- positions,
- normals,
- progress,
- color,
- indices,
- kind: 0,
- path_index: 0,
- colors: Vec::new(),
- use_lighting: 1.0,
- }];
-
- normalize_submeshes_3d(&mut submeshes);
-
- let bounds = if submeshes.is_empty() {
- [0.0; 6]
- } else {
- let (min_x, min_y, min_z, max_x, max_y, max_z) = compute_bbox(&submeshes);
- [min_x, min_y, min_z, max_x, max_y, max_z]
- };
-
- Ok(Mesh {
- submeshes,
- arc_lengths: Vec::new(),
- bounds,
- texture_positions: Vec::new(),
- texture_uvs: Vec::new(),
- texture_indices: Vec::new(),
- })
-}
-
-/// Build a textured quad mesh + texture from RGBA pixel data.
-///
-/// * `frames` – one or more RGBA blobs (one per animation frame).
-/// * `width` / `height` – pixel dimensions (same for every frame).
-///
-/// Returns `(Mesh, Texture)`. The quad spans [-0.5, 0.5] in both X and Y
-/// with Z = 0. Actual world size is controlled via Object3D.scale.
-#[pyfunction]
-#[pyo3(signature = (frames, width, height))]
-pub fn build_textured_quad(
- py: Python<'_>,
- frames: Vec<Vec<u8>>,
- width: u32,
- height: u32,
-) -> PyResult<(Py<Mesh>, Py<Texture>)> {
- let expected = (width * height * 4) as usize;
- for (i, frame) in frames.iter().enumerate() {
- if frame.len() != expected {
- return Err(pyo3::exceptions::PyValueError::new_err(format!(
- "Frame {i} has {} bytes, expected {expected} ({}x{}x4)",
- frame.len(),
- width,
- height
- )));
- }
- }
-
- // Unit quad: 4 vertices, 6 indices
- #[rustfmt::skip]
- let texture_positions = vec![
- -0.5, -0.5, 0.0,
- 0.5, -0.5, 0.0,
- 0.5, 0.5, 0.0,
- -0.5, 0.5, 0.0,
- ];
- #[rustfmt::skip]
- let texture_uvs = vec![
- 0.0, 0.0,
- 1.0, 0.0,
- 1.0, 1.0,
- 0.0, 1.0,
- ];
- let texture_indices = vec![0, 1, 2, 0, 2, 3];
-
- let mesh = Py::new(
- py,
- Mesh {
- submeshes: Vec::new(),
- arc_lengths: Vec::new(),
- bounds: [-0.5, -0.5, 0.0, 0.5, 0.5, 0.0],
- texture_positions,
- texture_uvs,
- texture_indices,
- },
- )?;
-
- let texture = Py::new(
- py,
- Texture {
- frames,
- width,
- height,
- },
- )?;
-
- Ok((mesh, texture))
-}