commit 6e1613f73f97d2db41c789bd121b14561469e204 Author: meehl <12648828+meehl@users.noreply.github.com> Date: Thu Oct 16 17:00:59 2025 +0200 Initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b83d222 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/target/ diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..5a4f925 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,3999 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "ab_glyph" +version = "0.2.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e074464580a518d16a7126262fffaaa47af89d4099d4cb403f8ed938ba12ee7d" +dependencies = [ + "ab_glyph_rasterizer", + "owned_ttf_parser", +] + +[[package]] +name = "ab_glyph_rasterizer" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "366ffbaa4442f4684d91e2cd7c5ea7c4ed8add41959a31447066e279e432b618" + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "getrandom 0.3.3", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "aho-corasick" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916" +dependencies = [ + "memchr", +] + +[[package]] +name = "aligned-vec" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc890384c8602f339876ded803c97ad529f3842aba97f6392b3dba0dd171769b" +dependencies = [ + "equator", +] + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "android-activity" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef6978589202a00cd7e118380c448a08b6ed394c3a8df3a430d0898e3a42d046" +dependencies = [ + "android-properties", + "bitflags 2.9.4", + "cc", + "cesu8", + "jni", + "jni-sys", + "libc", + "log", + "ndk", + "ndk-context", + "ndk-sys", + "num_enum", + "thiserror 1.0.69", +] + +[[package]] +name = "android-properties" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc7eb209b1518d6bb87b283c20095f5228ecda460da70b44f0802523dea6da04" + +[[package]] +name = "android_system_properties" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" +dependencies = [ + "libc", +] + +[[package]] +name = "anstream" +version = "0.6.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ae563653d1938f79b1ab1b5e668c87c76a9930414574a6583a7b7e11a8e6192" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "862ed96ca487e809f1c8e5a8447f6ee2cf102f846893800b20cebdf541fc6bbd" + +[[package]] +name = "anstyle-parse" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7644824f0aa2c7b9384579234ef10eb7efb6a0deb83f9630a49594dd9c15c2" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e231f6134f61b71076a3eab506c379d4f36122f2af15a9ff04415ea4c3339e2" +dependencies = [ + "windows-sys 0.60.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e0633414522a32ffaac8ac6cc8f748e090c5717661fddeea04219e2344f5f2a" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.60.2", +] + +[[package]] +name = "anyhow" +version = "1.0.100" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a23eb6b1614318a8071c9b2521f36b424b2c83db5eb3a0fead4a6c0809af6e61" + +[[package]] +name = "arbitrary" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1" + +[[package]] +name = "arboard" +version = "3.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0348a1c054491f4bfe6ab86a7b6ab1e44e45d899005de92f58b3df180b36ddaf" +dependencies = [ + "clipboard-win", + "log", + "objc2 0.6.2", + "objc2-app-kit 0.3.1", + "objc2-foundation 0.3.1", + "parking_lot", + "percent-encoding", + "windows-sys 0.60.2", + "wl-clipboard-rs", + "x11rb", +] + +[[package]] +name = "arg_enum_proc_macro" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ae92a5119aa49cdbcf6b9f893fe4e1d98b04ccbf82ee0584ad948a44a734dea" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "arrayref" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb" + +[[package]] +name = "arrayvec" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" + +[[package]] +name = "as-raw-xcb-connection" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "175571dd1d178ced59193a6fc02dde1b972eb0bc56c892cde9beeceac5bf0f6b" + +[[package]] +name = "ash" +version = "0.38.0+1.3.281" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bb44936d800fea8f016d7f2311c6a4f97aebd5dc86f09906139ec848cf3a46f" +dependencies = [ + "libloading", +] + +[[package]] +name = "astc-decode" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d6058e6202e20b7fa445692ec4b77ca8eb02508091fcd479ea753d9f60e376b" + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" + +[[package]] +name = "av1-grain" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f3efb2ca85bc610acfa917b5aaa36f3fcbebed5b3182d7f877b02531c4b80c8" +dependencies = [ + "anyhow", + "arrayvec", + "log", + "nom", + "num-rational", + "v_frame", +] + +[[package]] +name = "avif-serialize" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47c8fbc0f831f4519fe8b810b6a7a91410ec83031b8233f730a0480029f6a23f" +dependencies = [ + "arrayvec", +] + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "bincode" +version = "1.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f45e9417d87227c7a56d22e471c6206462cba514c7590c09aff4cf6d1ddcad" +dependencies = [ + "serde", +] + +[[package]] +name = "bit-set" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3" +dependencies = [ + "bit-vec", +] + +[[package]] +name = "bit-vec" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bitflags" +version = "2.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2261d10cca569e4643e526d8dc2e62e433cc8aba21ab764233731f8d369bf394" + +[[package]] +name = "bitstream-io" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6099cdc01846bc367c4e7dd630dc5966dccf36b652fae7a74e17b640411a91b2" + +[[package]] +name = "block2" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c132eebf10f5cad5289222520a4a058514204aed6d791f1cf4fe8088b82d15f" +dependencies = [ + "objc2 0.5.2", +] + +[[package]] +name = "bstr" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "234113d19d0d7d613b40e86fb654acf958910802bcceab913a4f9e7cda03b1a4" +dependencies = [ + "memchr", + "serde", +] + +[[package]] +name = "built" +version = "0.7.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56ed6191a7e78c36abdb16ab65341eefd73d64d303fffccdbb00d51e4205967b" + +[[package]] +name = "bumpalo" +version = "3.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46c5e41b57b8bba42a04676d81cb89e9ee8e859a1a66f80a5a72e1cb76b34d43" + +[[package]] +name = "bytemuck" +version = "1.23.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3995eaeebcdf32f91f980d360f78732ddc061097ab4e39991ae7a6ace9194677" +dependencies = [ + "bytemuck_derive", +] + +[[package]] +name = "bytemuck_derive" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f154e572231cb6ba2bd1176980827e3d5dc04cc183a75dea38109fbdd672d29" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "byteorder-lite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" + +[[package]] +name = "bytes" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d71b6127be86fdcfddb610f7182ac57211d4b18a3e9c82eb2d17662f2227ad6a" + +[[package]] +name = "calloop" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b99da2f8558ca23c71f4fd15dc57c906239752dd27ff3c00a1d56b685b7cbfec" +dependencies = [ + "bitflags 2.9.4", + "log", + "polling", + "rustix 0.38.44", + "slab", + "thiserror 1.0.69", +] + +[[package]] +name = "calloop-wayland-source" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95a66a987056935f7efce4ab5668920b5d0dac4a7c99991a67395f13702ddd20" +dependencies = [ + "calloop", + "rustix 0.38.44", + "wayland-backend", + "wayland-client", +] + +[[package]] +name = "cc" +version = "1.2.38" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80f41ae168f955c12fb8960b057d70d0ca153fb83182b57d86380443527be7e9" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cesu8" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c" + +[[package]] +name = "cfg-expr" +version = "0.15.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d067ad48b8650848b989a59a86c6c36a995d02d2bf778d45c3c5d57bc2718f02" +dependencies = [ + "smallvec", + "target-lexicon", +] + +[[package]] +name = "cfg-if" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2fd1289c04a9ea8cb22300a459a72a385d7c73d3259e2ed7dcb2af674838cfa9" + +[[package]] +name = "cfg_aliases" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" + +[[package]] +name = "clap" +version = "4.5.48" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2134bb3ea021b78629caa971416385309e0131b351b25e01dc16fb54e1b5fae" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.5.48" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2ba64afa3c0a6df7fa517765e31314e983f51dda798ffba27b988194fb65dc9" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.5.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbfd7eae0b0f1a6e63d4b13c9c478de77c2eb546fba158ad50b4203dc24b9f9c" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "clap_lex" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b94f61472cee1439c0b966b47e3aca9ae07e45d070759512cd390ea2bebc6675" + +[[package]] +name = "clipboard-win" +version = "5.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bde03770d3df201d4fb868f2c9c59e66a3e4e2bd06692a0fe701e7103c7e84d4" +dependencies = [ + "error-code", +] + +[[package]] +name = "codespan-reporting" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe6d2e5af09e8c8ad56c969f2157a3d4238cebc7c55f0a517728c38f7b200f81" +dependencies = [ + "unicode-width", +] + +[[package]] +name = "colorchoice" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75" + +[[package]] +name = "combine" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba5a308b75df32fe02788e748662718f03fde005016435c444eea572398219fd" +dependencies = [ + "bytes", + "memchr", +] + +[[package]] +name = "concurrent-queue" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "core-graphics" +version = "0.23.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c07782be35f9e1140080c6b96f0d44b739e2278479f64e02fdab4e32dfd8b081" +dependencies = [ + "bitflags 1.3.2", + "core-foundation", + "core-graphics-types", + "foreign-types", + "libc", +] + +[[package]] +name = "core-graphics-types" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf" +dependencies = [ + "bitflags 1.3.2", + "core-foundation", + "libc", +] + +[[package]] +name = "core_maths" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30" +dependencies = [ + "libm", +] + +[[package]] +name = "crc32fast" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crossbeam-channel" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82b8f8f868b36967f9606790d1903570de9ceaf870a7bf9fbbd3016d636a2cb2" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-deque" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9dd111b7b7f7d55b72c0a6ae361660ee5853c9af73f70c3c2ef6858b950e2e51" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" + +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + +[[package]] +name = "cursor-icon" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f" + +[[package]] +name = "dds" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fe57b94813bbd438e2fb1df420ab1d875e54767001f96ab72eb3a8ac0a78302" +dependencies = [ + "astc-decode", + "bitflags 2.9.4", + "glam", + "rayon", + "resize", + "zerocopy", +] + +[[package]] +name = "directories" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16f5094c54661b38d03bd7e50df373292118db60b585c08a411c6d840017fe7d" +dependencies = [ + "dirs-sys", +] + +[[package]] +name = "dirs-sys" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" +dependencies = [ + "libc", + "option-ext", + "redox_users", + "windows-sys 0.61.0", +] + +[[package]] +name = "dispatch" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd0c93bb4b0c6d9b77f4435b0ae98c24d17f1c45b2ff844c6151a07256ca923b" + +[[package]] +name = "dispatch2" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89a09f22a6c6069a18470eb92d2298acf25463f14256d24778e1230d789a2aec" +dependencies = [ + "bitflags 2.9.4", + "objc2 0.6.2", +] + +[[package]] +name = "displaydoc" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "dlib" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330c60081dcc4c72131f8eb70510f1ac07223e5d4163db481a04a0befcffa412" +dependencies = [ + "libloading", +] + +[[package]] +name = "document-features" +version = "0.2.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95249b50c6c185bee49034bcb378a49dc2b5dff0be90ff6616d31d64febab05d" +dependencies = [ + "litrs", +] + +[[package]] +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 = "either" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" + +[[package]] +name = "env_logger" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cd405aab171cb85d6735e5c8d9db038c17d3ca007a4d2c25f337935c3d90580" +dependencies = [ + "humantime", + "is-terminal", + "log", + "regex", + "termcolor", +] + +[[package]] +name = "equator" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4711b213838dfee0117e3be6ac926007d7f433d7bbe33595975d4190cb07e6fc" +dependencies = [ + "equator-macro", +] + +[[package]] +name = "equator-macro" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44f23cf4b44bfce11a86ace86f8a73ffdec849c9fd00a386a53d278bd9e81fb3" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.0", +] + +[[package]] +name = "error-code" +version = "3.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dea2df4cf52843e0452895c455a1a2cfbb842a1e7329671acf418fdc53ed4c59" + +[[package]] +name = "euclid" +version = "0.22.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad9cdb4b747e485a12abb0e6566612956c7a1bafa3bdb8d682c5b6d403589e48" +dependencies = [ + "bytemuck", + "num-traits", +] + +[[package]] +name = "fast_image_resize" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bd1eda71e8af93f8b00e189404235d82f4de77ea4a0d182b44a7f03994d647c" +dependencies = [ + "bytemuck", + "cfg-if", + "document-features", + "image", + "num-traits", + "thiserror 2.0.16", +] + +[[package]] +name = "fastrand" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" + +[[package]] +name = "fdeflate" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" +dependencies = [ + "simd-adler32", +] + +[[package]] +name = "filetime" +version = "0.2.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc0505cd1b6fa6580283f6bdf70a73fcf4aba1184038c90902b92b3dd0df63ed" +dependencies = [ + "cfg-if", + "libc", + "libredox", + "windows-sys 0.60.2", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ced73b1dacfc750a6db6c0a0c3a3853c8b41997e2e2c563dc90804ae6867959" + +[[package]] +name = "fixedbitset" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80" + +[[package]] +name = "flate2" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a3d7db9596fecd151c5f638c0ee5d5bd487b6e0ea232e5dc96d5250f6f94b1d" +dependencies = [ + "crc32fast", + "miniz_oxide", +] + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "font-types" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "511e2c18a516c666d27867d2f9821f76e7d591f762e9fc41dd6cc5c90fe54b0b" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "fontique" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff3336bc0b87fe42305047263fa60d2eabd650d29cbe62fdeb2a66c7a0a595f9" +dependencies = [ + "bytemuck", + "hashbrown 0.15.5", + "icu_locale_core", + "linebender_resource_handle", + "memmap2", + "objc2 0.6.2", + "objc2-core-foundation", + "objc2-core-text", + "objc2-foundation 0.3.1", + "read-fonts", + "roxmltree", + "smallvec", + "windows", + "windows-core", + "yeslogic-fontconfig-sys", +] + +[[package]] +name = "foreign-types" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965" +dependencies = [ + "foreign-types-macros", + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-macros" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a5c6c585bc94aaf2c7b51dd4c2ba22680844aba4c687be581871a6f518c5742" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "foreign-types-shared" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" + +[[package]] +name = "gethostname" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc257fdb4038301ce4b9cd1b3b51704509692bb3ff716a410cbd07925d9dae55" +dependencies = [ + "rustix 1.1.2", + "windows-targets 0.52.6", +] + +[[package]] +name = "getrandom" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "335ff9f135e4384c8150d6f27c6daed433577f86b4750418338c01a1a2528592" +dependencies = [ + "cfg-if", + "libc", + "wasi 0.11.1+wasi-snapshot-preview1", +] + +[[package]] +name = "getrandom" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26145e563e54f2cadc477553f1ec5ee650b00862f0a58bcd12cbdc5f0ea2d2f4" +dependencies = [ + "cfg-if", + "libc", + "r-efi", + "wasi 0.14.7+wasi-0.2.4", +] + +[[package]] +name = "glam" +version = "0.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "151665d9be52f9bb40fc7966565d39666f2d1e69233571b71b87791c7e0528b3" + +[[package]] +name = "glob" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280" + +[[package]] +name = "gpu-alloc" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fbcd2dba93594b227a1f57ee09b8b9da8892c34d55aa332e034a228d0fe6a171" +dependencies = [ + "bitflags 2.9.4", + "gpu-alloc-types", +] + +[[package]] +name = "gpu-alloc-types" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98ff03b468aa837d70984d55f5d3f846f6ec31fe34bbb97c4f85219caeee1ca4" +dependencies = [ + "bitflags 2.9.4", +] + +[[package]] +name = "gpu-descriptor" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b89c83349105e3732062a895becfc71a8f921bb71ecbbdd8ff99263e3b53a0ca" +dependencies = [ + "bitflags 2.9.4", + "gpu-descriptor-types", + "hashbrown 0.15.5", +] + +[[package]] +name = "gpu-descriptor-types" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdf242682df893b86f33a73828fb09ca4b2d3bb6cc95249707fc684d27484b91" +dependencies = [ + "bitflags 2.9.4", +] + +[[package]] +name = "half" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "459196ed295495a68f7d7fe1d84f6c4b7ff0e21fe3017b2f283c6fac3ad803c9" +dependencies = [ + "cfg-if", + "crunchy", + "num-traits", +] + +[[package]] +name = "harfrust" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f3fd23d35c2d8bcf34a1f0e9ea8c0ad263f0c8a9a47108eee23aac76e71645a" +dependencies = [ + "bitflags 2.9.4", + "bytemuck", + "core_maths", + "read-fonts", + "smallvec", +] + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash 0.1.5", +] + +[[package]] +name = "hashbrown" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5419bdc4f6a9207fbeba6d11b604d481addf78ecd10c11ad51e76c2f6482748d" +dependencies = [ + "foldhash 0.2.0", +] + +[[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.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c" + +[[package]] +name = "hexf-parse" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa686283ad6dd069f105e5ab091b04c62850d3e4cf5d67debad1933f55023df" + +[[package]] +name = "http" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4a85d31aea989eead29a3aaf9e1115a180df8282431156e533de47660892565" +dependencies = [ + "bytes", + "fnv", + "itoa", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "humantime" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "135b12329e5e3ce057a9f972339ea52bc954fe1e9358ef27f95e89716fbc5424" + +[[package]] +name = "icu_locale_core" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0cde2700ccaed3872079a65fb1a78f6c0a36c91570f28755dda67bc8f7d9f00a" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", +] + +[[package]] +name = "image" +version = "0.25.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "529feb3e6769d234375c4cf1ee2ce713682b8e76538cb13f9fc23e1400a591e7" +dependencies = [ + "bytemuck", + "byteorder-lite", + "moxcms", + "num-traits", + "png", + "ravif", + "rayon", + "zune-core", + "zune-jpeg", +] + +[[package]] +name = "imgref" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c5cedc30da3a610cac6b4ba17597bdf7152cf974e8aab3afb3d54455e371c8" + +[[package]] +name = "indexmap" +version = "2.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b0f83760fb341a774ed326568e19f5a863af4a952def8c39f9ab92fd95b88e5" +dependencies = [ + "equivalent", + "hashbrown 0.16.0", +] + +[[package]] +name = "interpolate_name" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c34819042dc3d3971c46c2190835914dfbe0c3c13f61449b2997f4e9722dfa60" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "is-docker" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "928bae27f42bc99b60d9ac7334e3a21d10ad8f1835a4e12ec3ec0464765ed1b3" +dependencies = [ + "once_cell", +] + +[[package]] +name = "is-terminal" +version = "0.4.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e04d7f318608d35d4b61ddd75cbdaee86b023ebe2bd5a66ee0915f0bf93095a9" +dependencies = [ + "hermit-abi", + "libc", + "windows-sys 0.59.0", +] + +[[package]] +name = "is-wsl" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "173609498df190136aa7dea1a91db051746d339e18476eed5ca40521f02d7aa5" +dependencies = [ + "is-docker", + "once_cell", +] + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7943c866cc5cd64cbc25b2e01621d07fa8eb2a1a23160ee81ce38704e97b8ecf" + +[[package]] +name = "itertools" +version = "0.10.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473" +dependencies = [ + "either", +] + +[[package]] +name = "itertools" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba291022dbbd398a455acf126c1e341954079855bc60dfdda641363bd6922569" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c" + +[[package]] +name = "jni" +version = "0.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a87aa2bb7d2af34197c04845522473242e1aa17c12f4935d5856491a7fb8c97" +dependencies = [ + "cesu8", + "cfg-if", + "combine", + "jni-sys", + "log", + "thiserror 1.0.69", + "walkdir", + "windows-sys 0.45.0", +] + +[[package]] +name = "jni-sys" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8eaf4bc02d17cbdd7ff4c7438cafcdf7fb9a4613313ad11b4f8fefe7d3fa0130" + +[[package]] +name = "jobserver" +version = "0.1.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9afb3de4395d6b3e67a780b6de64b51c978ecf11cb9a462c66be7d4ca9039d33" +dependencies = [ + "getrandom 0.3.3", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "852f13bec5eba4ba9afbeb93fd7c13fe56147f055939ae21c43a29a0ecb2702e" +dependencies = [ + "once_cell", + "wasm-bindgen", +] + +[[package]] +name = "libc" +version = "0.2.176" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "58f929b4d672ea937a23a1ab494143d968337a5f47e56d0815df1e0890ddf174" + +[[package]] +name = "libfuzzer-sys" +version = "0.4.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5037190e1f70cbeef565bd267599242926f724d3b8a9f510fd7e0b540cfa4404" +dependencies = [ + "arbitrary", + "cc", +] + +[[package]] +name = "libloading" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" +dependencies = [ + "cfg-if", + "windows-link 0.2.0", +] + +[[package]] +name = "libm" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9fbbcab51052fe104eb5e5d351cf728d30a5be1fe14d9be8a3b097481fb97de" + +[[package]] +name = "libredox" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "416f7e718bdb06000964960ffa43b4335ad4012ae8b99060261aa4a8088d5ccb" +dependencies = [ + "bitflags 2.9.4", + "libc", + "redox_syscall 0.5.17", +] + +[[package]] +name = "linebender_resource_handle" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" + +[[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.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df1d3c3b53da64cf5760482273a98e575c651a67eec7f77df96b5b642de8f039" + +[[package]] +name = "litemap" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "241eaef5fd12c88705a01fc1066c48c4b36e0dd4377dcdc7ec3942cea7a69956" + +[[package]] +name = "litrs" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5e54036fe321fd421e10d732f155734c4e4afd610dd556d9a82833ab3ee0bed" + +[[package]] +name = "lock_api" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96936507f153605bddfcda068dd804796c84324ed2510809e5b2a624c81da765" +dependencies = [ + "autocfg", + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34080505efa8e45a4b816c349525ebe327ceaa8559756f0356cba97ef3bf7432" + +[[package]] +name = "loop9" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fae87c125b03c1d2c0150c90365d7d6bcc53fb73a9acaef207d2d065860f062" +dependencies = [ + "imgref", +] + +[[package]] +name = "lz4_flex" +version = "0.11.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08ab2867e3eeeca90e844d1940eab391c9dc5228783db2ed999acbc0a9ed375a" + +[[package]] +name = "maybe-rayon" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ea1f30cedd69f0a2954655f7188c6a834246d2bcf1e315e2ac40c4b24dc9519" +dependencies = [ + "cfg-if", + "rayon", +] + +[[package]] +name = "memchr" +version = "2.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a282da65faaf38286cf3be983213fcf1d2e2a58700e808f83f4ea9a4804bc0" + +[[package]] +name = "memmap2" +version = "0.9.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "843a98750cd611cc2965a8213b53b43e715f13c37a9e096c6408e69990961db7" +dependencies = [ + "libc", +] + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[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 = "mlua" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b3dd94c3c4dea0049b22296397040840a8f6b5b5229f438434ba82df402b42d" +dependencies = [ + "anyhow", + "bstr", + "either", + "mlua-sys", + "num-traits", + "parking_lot", + "rustc-hash 2.1.1", + "rustversion", +] + +[[package]] +name = "mlua-sys" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d4dc9cfc5a7698899802e97480617d9726f7da78c910db989d4d0fd4991d900" +dependencies = [ + "cc", + "cfg-if", + "pkg-config", +] + +[[package]] +name = "moxcms" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddd32fa8935aeadb8a8a6b6b351e40225570a37c43de67690383d87ef170cd08" +dependencies = [ + "num-traits", + "pxfm", +] + +[[package]] +name = "naga" +version = "27.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12b2e757b11b47345d44e7760e45458339bc490463d9548cd8651c53ae523153" +dependencies = [ + "arrayvec", + "bit-set", + "bitflags 2.9.4", + "cfg-if", + "cfg_aliases", + "codespan-reporting", + "half", + "hashbrown 0.16.0", + "hexf-parse", + "indexmap", + "libm", + "log", + "num-traits", + "once_cell", + "rustc-hash 1.1.0", + "spirv", + "thiserror 2.0.16", + "unicode-ident", +] + +[[package]] +name = "ndk" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4" +dependencies = [ + "bitflags 2.9.4", + "jni-sys", + "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", +] + +[[package]] +name = "new_debug_unreachable" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" + +[[package]] +name = "nohash-hasher" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451" + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "noop_proc_macro" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0676bb32a98c1a483ce53e500a81ad9c3d5b3f7c920c28c24e9cb0980d0b5bc8" + +[[package]] +name = "num-bigint" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5e44f723f1133c9deac646763579fdb3ac745e418f2a7af9cd0c431da1f20b9" +dependencies = [ + "num-integer", + "num-traits", +] + +[[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", +] + +[[package]] +name = "num-integer" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-rational" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" +dependencies = [ + "num-bigint", + "num-integer", + "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.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a973b4e44ce6cad84ce69d797acf9a044532e4184c4f267913d1b546a0727b7a" +dependencies = [ + "num_enum_derive", + "rustversion", +] + +[[package]] +name = "num_enum_derive" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77e878c846a8abae00dd069496dbe8751b16ac1c3d6bd2a7283a938e8228f90d" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn", +] + +[[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.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "561f357ba7f3a2a61563a186a163d0a3a5247e1089524a3981d49adb775078bc" +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.9.4", + "block2", + "libc", + "objc2 0.5.2", + "objc2-core-data", + "objc2-core-image", + "objc2-foundation 0.2.2", + "objc2-quartz-core", +] + +[[package]] +name = "objc2-app-kit" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6f29f568bec459b0ddff777cec4fe3fd8666d82d5a40ebd0ff7e66134f89bcc" +dependencies = [ + "bitflags 2.9.4", + "objc2 0.6.2", + "objc2-core-graphics", + "objc2-foundation 0.3.1", +] + +[[package]] +name = "objc2-cloud-kit" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74dd3b56391c7a0596a295029734d3c1c5e7e510a4cb30245f8221ccea96b009" +dependencies = [ + "bitflags 2.9.4", + "block2", + "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", + "objc2 0.5.2", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-core-data" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "617fbf49e071c178c0b24c080767db52958f716d9eabdf0890523aeae54773ef" +dependencies = [ + "bitflags 2.9.4", + "block2", + "objc2 0.5.2", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-core-foundation" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c10c2894a6fed806ade6027bcd50662746363a9589d3ec9d9bef30a4e4bc166" +dependencies = [ + "bitflags 2.9.4", + "dispatch2", + "objc2 0.6.2", +] + +[[package]] +name = "objc2-core-graphics" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "989c6c68c13021b5c2d6b71456ebb0f9dc78d752e86a98da7c716f4f9470f5a4" +dependencies = [ + "bitflags 2.9.4", + "dispatch2", + "objc2 0.6.2", + "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", + "objc2 0.5.2", + "objc2-foundation 0.2.2", + "objc2-metal", +] + +[[package]] +name = "objc2-core-location" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "000cfee34e683244f284252ee206a27953279d370e309649dc3ee317b37e5781" +dependencies = [ + "block2", + "objc2 0.5.2", + "objc2-contacts", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-core-text" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ba833d4a1cb1aac330f8c973fd92b6ff1858e4aef5cdd00a255eefb28022fb5" +dependencies = [ + "bitflags 2.9.4", + "objc2-core-foundation", +] + +[[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.9.4", + "block2", + "dispatch", + "libc", + "objc2 0.5.2", +] + +[[package]] +name = "objc2-foundation" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "900831247d2fe1a09a683278e5384cfb8c80c79fe6b166f9d14bfdde0ea1b03c" +dependencies = [ + "bitflags 2.9.4", + "objc2 0.6.2", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-io-surface" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7282e9ac92529fa3457ce90ebb15f4ecbc383e8338060960760fa2cf75420c3c" +dependencies = [ + "bitflags 2.9.4", + "objc2 0.6.2", + "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", + "objc2 0.5.2", + "objc2-app-kit 0.2.2", + "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.9.4", + "block2", + "objc2 0.5.2", + "objc2-foundation 0.2.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.9.4", + "block2", + "objc2 0.5.2", + "objc2-foundation 0.2.2", + "objc2-metal", +] + +[[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.9.4", + "block2", + "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", + "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", + "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.9.4", + "block2", + "objc2 0.5.2", + "objc2-core-location", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "once_cell" +version = "1.21.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4895175b425cb1f87721b59f0f286c2092bd4af812243672510e1ac53e2e0ad" + +[[package]] +name = "open" +version = "5.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2483562e62ea94312f3576a7aca397306df7990b8d89033e18766744377ef95" +dependencies = [ + "is-wsl", + "libc", + "pathdiff", +] + +[[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.48" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba0b26cec2e24f08ed8bb31519a9333140a6599b867dac464bb150bdb796fd43" +dependencies = [ + "libredox", +] + +[[package]] +name = "ordered-float" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2c1f9f56e534ac6a9b8a4600bdf0f530fb393b5f393e7b4d03489c3cf0c3f01" +dependencies = [ + "num-traits", +] + +[[package]] +name = "os_pipe" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db335f4760b14ead6290116f2427bf33a14d4f0617d49f78a246de10c1831224" +dependencies = [ + "libc", + "windows-sys 0.59.0", +] + +[[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 = "parking_lot" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70d58bf43669b5795d1576d0641cfb6fbb2057bf629506267a92807158584a13" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc838d2a56b5b1a6c25f55575dfc605fabb63bb2365f6c2353ef9159aa69e4a5" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall 0.5.17", + "smallvec", + "windows-targets 0.52.6", +] + +[[package]] +name = "parley" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26746861bb76dbc9bcd5ed1b0b55d2fedf291100961251702a031ab2abd2ce52" +dependencies = [ + "fontique", + "harfrust", + "hashbrown 0.15.5", + "linebender_resource_handle", + "skrifa", + "swash", +] + +[[package]] +name = "paste" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" + +[[package]] +name = "pathdiff" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df94ce210e5bc13cb6651479fa48d14f601d9858cfe0467f43ae157023b938d3" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "petgraph" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4c5cc86750666a3ed20bdaf5ca2a0344f9c67674cae0515bec2da16fbaa47db" +dependencies = [ + "fixedbitset", + "indexmap", +] + +[[package]] +name = "pin-project" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "677f1add503faace112b9f1373e43e9e054bfdd22ff1a63c1bc485eaec6a6a8a" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e918e4ff8c4549eb882f14b3a4bc8c8bc93de829416eacf579f1207a8fbf861" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b" + +[[package]] +name = "pkg-config" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c" + +[[package]] +name = "png" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97baced388464909d42d89643fe4361939af9b7ce7a31ee32a168f832a70f2a0" +dependencies = [ + "bitflags 2.9.4", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide", +] + +[[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.2", + "windows-sys 0.61.0", +] + +[[package]] +name = "pollster" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22686f4785f02a4fcc856d3b3bb19bf6c8160d103f7a99cc258bddd0251dc7f2" + +[[package]] +name = "portable-atomic" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f84267b20a16ea918e43c6a88433c2d54fa145c92a811b5b047ccbe153674483" + +[[package]] +name = "portable-atomic-util" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8a2f0d8d040d7848a709caf78912debcc3f33ee4b3cac47d73d1e1069e83507" +dependencies = [ + "portable-atomic", +] + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "proc-macro-crate" +version = "3.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "219cb19e96be00ab2e37d6e299658a0cfa83e52429179969b0f0121b4ac46983" +dependencies = [ + "toml_edit 0.23.6", +] + +[[package]] +name = "proc-macro2" +version = "1.0.101" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89ae43fd86e4158d6db51ad8e2b80f313af9cc74f5c0e03ccb87de09998732de" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "profiling" +version = "1.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eb8486b569e12e2c32ad3e204dbaba5e4b5b216e9367044f25f1dba42341773" +dependencies = [ + "profiling-procmacros", + "puffin", +] + +[[package]] +name = "profiling-procmacros" +version = "1.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52717f9a02b6965224f95ca2a81e2e0c5c43baacd28ca057577988930b6c3d5b" +dependencies = [ + "quote", + "syn", +] + +[[package]] +name = "puffin" +version = "0.19.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa9dae7b05c02ec1a6bc9bcf20d8bc64a7dcbf57934107902a872014899b741f" +dependencies = [ + "anyhow", + "bincode", + "byteorder", + "cfg-if", + "itertools 0.10.5", + "lz4_flex", + "once_cell", + "parking_lot", + "serde", +] + +[[package]] +name = "puffin_http" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "739a3c7f56604713b553d7addd7718c226e88d598979ae3450320800bd0e9810" +dependencies = [ + "anyhow", + "crossbeam-channel", + "log", + "parking_lot", + "puffin", +] + +[[package]] +name = "pxfm" +version = "0.1.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83f9b339b02259ada5c0f4a389b7fb472f933aa17ce176fd2ad98f28bb401fde" +dependencies = [ + "num-traits", +] + +[[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.37.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "331e97a1af0bf59823e6eadffe373d7b27f485be8748f71471c662c1f269b7fb" +dependencies = [ + "memchr", +] + +[[package]] +name = "quote" +version = "1.0.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d" +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 = "rand" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" +dependencies = [ + "libc", + "rand_chacha", + "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" +dependencies = [ + "getrandom 0.2.16", +] + +[[package]] +name = "rav1e" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd87ce80a7665b1cce111f8a16c1f3929f6547ce91ade6addf4ec86a8dda5ce9" +dependencies = [ + "arbitrary", + "arg_enum_proc_macro", + "arrayvec", + "av1-grain", + "bitstream-io", + "built", + "cfg-if", + "interpolate_name", + "itertools 0.12.1", + "libc", + "libfuzzer-sys", + "log", + "maybe-rayon", + "new_debug_unreachable", + "noop_proc_macro", + "num-derive", + "num-traits", + "once_cell", + "paste", + "profiling", + "rand", + "rand_chacha", + "simd_helpers", + "system-deps", + "thiserror 1.0.69", + "v_frame", + "wasm-bindgen", +] + +[[package]] +name = "ravif" +version = "0.11.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5825c26fddd16ab9f515930d49028a630efec172e903483c94796cfe31893e6b" +dependencies = [ + "avif-serialize", + "imgref", + "loop9", + "quick-error", + "rav1e", + "rayon", + "rgb", +] + +[[package]] +name = "raw-window-handle" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539" + +[[package]] +name = "rayon" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "368f01d005bf8fd9b1206fb6fa653e6c4a81ceb1466406b81792d87c5677a58f" +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.35.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6717cf23b488adf64b9d711329542ba34de147df262370221940dfabc2c91358" +dependencies = [ + "bytemuck", + "core_maths", + "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.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5407465600fb0548f1442edf71dd20683c6ed326200ace4b1ef0763521bb3b77" +dependencies = [ + "bitflags 2.9.4", +] + +[[package]] +name = "redox_users" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4e608c6638b9c18977b00b475ac1f28d14e84b27d8d42f70e0bf1e3dec127ac" +dependencies = [ + "getrandom 0.2.16", + "libredox", + "thiserror 2.0.16", +] + +[[package]] +name = "regex" +version = "1.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23d7fd106d8c02486a8d64e778353d1cffe08ce79ac2e82f540c86d0facf6912" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b9458fa0bfeeac22b5ca447c63aaf45f28439a709ccd244698632f9aa6394d6" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caf4aa5b0f434c91fe5c7f1ecb6a5ece2130b02ad2a590589dda5146df959001" + +[[package]] +name = "renderdoc-sys" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832" + +[[package]] +name = "resize" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87a103d0b47e783f4579149402f7499397ab25540c7a57b2f70487a5d2d20ef0" +dependencies = [ + "rayon", + "rgb", +] + +[[package]] +name = "rgb" +version = "0.8.52" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c6a884d2998352bb4daf0183589aec883f16a6da1f4dde84d8e2e9a5409a1ce" + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.16", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "roxmltree" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97" + +[[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.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d" + +[[package]] +name = "rustix" +version = "0.38.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" +dependencies = [ + "bitflags 2.9.4", + "errno", + "libc", + "linux-raw-sys 0.4.15", + "windows-sys 0.59.0", +] + +[[package]] +name = "rustix" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd15f8a2c5551a84d56efdc1cd049089e409ac19a3072d5037a17fd70719ff3e" +dependencies = [ + "bitflags 2.9.4", + "errno", + "libc", + "linux-raw-sys 0.11.0", + "windows-sys 0.61.0", +] + +[[package]] +name = "rustls" +version = "0.23.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd3c25631629d034ce7cd9940adc9d45762d46de2b0f57193c4443b92c6d4d40" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pemfile" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dce314e5fee3f39953d46bb63bb8a46d40c2f8fb7cc5a3b6cab2bde9721d6e50" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "rustls-pki-types" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "229a4a4c221013e7e1f1a043678c5cc39fe5171437c88fb47151a21e6f5b5c79" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8572f3c2cb9934231157b45499fc41e1f58c589fdfb81a844ba873265e80f8eb" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" + +[[package]] +name = "rusty-path-of-building" +version = "0.1.0" +dependencies = [ + "ahash", + "anyhow", + "arboard", + "bytemuck", + "clap", + "dds", + "directories", + "env_logger", + "euclid", + "fast_image_resize", + "flate2", + "glob", + "image", + "log", + "mlua", + "nohash-hasher", + "num-traits", + "open", + "ordered-float", + "parley", + "pollster", + "profiling", + "puffin_http", + "regex", + "swash", + "tar", + "ureq", + "wgpu", + "winit", + "zstd", +] + +[[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 = "serde" +version = "1.0.226" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0dca6411025b24b60bfa7ec1fe1f8e710ac09782dca409ee8237ba74b51295fd" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.226" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba2ba63999edb9dac981fb34b3e5c0d111a69b0924e253ed29d83f7c99e966a4" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.226" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8db53ae22f34573731bafa1db20f04027b2d25e02d8205921b569171699cdb33" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_spanned" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" +dependencies = [ + "serde", +] + +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + +[[package]] +name = "simd-adler32" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d66dc143e6b11c1eddc06d5c423cfc97062865baf299914ab64caa38182078fe" + +[[package]] +name = "simd_helpers" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95890f873bec569a0362c235787f3aca6e1e887302ba4840839bcc6459c42da6" +dependencies = [ + "quote", +] + +[[package]] +name = "skrifa" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c31071dedf532758ecf3fed987cdb4bd9509f900e026ab684b4ecb81ea49841" +dependencies = [ + "bytemuck", + "read-fonts", +] + +[[package]] +name = "slab" +version = "0.4.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a2ae44ef20feb57a68b23d846850f861394c2e02dc425a50098ae8c90267589" + +[[package]] +name = "smallvec" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" + +[[package]] +name = "smithay-client-toolkit" +version = "0.19.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3457dea1f0eb631b4034d61d4d8c32074caa6cd1ab2d59f2327bd8461e2c0016" +dependencies = [ + "bitflags 2.9.4", + "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 = "spirv" +version = "0.3.0+sdk-1.3.268.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eda41003dc44290527a59b13432d4a0379379fa074b70174882adfbdfd917844" +dependencies = [ + "bitflags 2.9.4", +] + +[[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" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "swash" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47846491253e976bdd07d0f9cc24b7daf24720d11309302ccbbc6e6b6e53550a" +dependencies = [ + "skrifa", + "yazi", + "zeno", +] + +[[package]] +name = "syn" +version = "2.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ede7c438028d4436d71104916910f5bb611972c5cfd7f89b8300a8186e6fada6" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "system-deps" +version = "6.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3e535eb8dded36d55ec13eddacd30dec501792ff23a0b1682c38601b8cf2349" +dependencies = [ + "cfg-expr", + "heck", + "pkg-config", + "toml", + "version-compare", +] + +[[package]] +name = "tar" +version = "0.4.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d863878d212c87a19c1a610eb53bb01fe12951c0501cf5a0d65f724914a667a" +dependencies = [ + "filetime", + "libc", + "xattr", +] + +[[package]] +name = "target-lexicon" +version = "0.12.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1" + +[[package]] +name = "tempfile" +version = "3.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d31c77bdf42a745371d260a26ca7163f1e0924b64afa0b688e61b5a9fa02f16" +dependencies = [ + "fastrand", + "getrandom 0.3.3", + "once_cell", + "rustix 1.1.2", + "windows-sys 0.61.0", +] + +[[package]] +name = "termcolor" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3467d614147380f2e4e374161426ff399c91084acd2363eaf549172b3d5e60c0" +dependencies = [ + "thiserror-impl 2.0.16", +] + +[[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", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c5e1be1c48b9172ee610da68fd9cd2770e7a4056cb3fc98710ee6906f0c7960" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[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", +] + +[[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 = "tinystr" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d4f6d1145dcb577acf783d4e601bc1d76a13337bb54e6233add580b07344c8b" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[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 = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32f1085dec27c2b6632b04c80b3bb1b4300d6495d1e129693bdda7d91e72eec1" +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", + "winnow", +] + +[[package]] +name = "toml_edit" +version = "0.23.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3effe7c0e86fdff4f69cdd2ccc1b96f933e24811c5441d44904e8683e27184b" +dependencies = [ + "indexmap", + "toml_datetime 0.7.2", + "toml_parser", + "winnow", +] + +[[package]] +name = "toml_parser" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cf893c33be71572e0e9aa6dd15e6677937abd686b066eac3f8cd3531688a627" +dependencies = [ + "winnow", +] + +[[package]] +name = "tracing" +version = "0.1.41" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "784e0ac535deb450455cbfa28a6f0df145ea1bb7ae51b821cf5e7927fdcfbdd0" +dependencies = [ + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9d12581f227e93f094d3af2ae690a574abb8a2b9b7a96e7cfe9647b2b617678" + +[[package]] +name = "tree_magic_mini" +version = "3.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f943391d896cdfe8eec03a04d7110332d445be7df856db382dd96a730667562c" +dependencies = [ + "memchr", + "nom", + "once_cell", + "petgraph", +] + +[[package]] +name = "ttf-parser" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" + +[[package]] +name = "unicode-ident" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f63a545481291138910575129486daeaf8ac54aee4387fe7906919f7830c7d9d" + +[[package]] +name = "unicode-segmentation" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6ccf251212114b54433ec949fd6a7841275f9ada20dddd2f29e9ceea4501493" + +[[package]] +name = "unicode-width" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a1a07cc7db3810833284e8d372ccdc6da29741639ecc70c9ec107df0fa6154c" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "ureq" +version = "3.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "99ba1025f18a4a3fc3e9b48c868e9beb4f24f4b4b1a325bada26bd4119f46537" +dependencies = [ + "base64", + "flate2", + "log", + "percent-encoding", + "rustls", + "rustls-pemfile", + "rustls-pki-types", + "ureq-proto", + "utf-8", + "webpki-roots", +] + +[[package]] +name = "ureq-proto" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60b4531c118335662134346048ddb0e54cc86bd7e81866757873055f0e38f5d2" +dependencies = [ + "base64", + "http", + "httparse", + "log", +] + +[[package]] +name = "utf-8" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "v_frame" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "666b7727c8875d6ab5db9533418d7c764233ac9c0cff1d469aec8fa127597be2" +dependencies = [ + "aligned-vec", + "num-traits", + "wasm-bindgen", +] + +[[package]] +name = "version-compare" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "852e951cb7832cb45cb1169900d19760cfa39b82bc0ea9c0e5a14ae88411c98b" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +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 = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasi" +version = "0.14.7+wasi-0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "883478de20367e224c0090af9cf5f9fa85bed63a95c1abf3afc5c083ebc06e8c" +dependencies = [ + "wasip2", +] + +[[package]] +name = "wasip2" +version = "1.0.1+wasi-0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0562428422c63773dad2c345a1882263bbf4d65cf3f42e90921f787ef5ad58e7" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.103" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab10a69fbd0a177f5f649ad4d8d3305499c42bab9aef2f7ff592d0ec8f833819" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-backend" +version = "0.2.103" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bb702423545a6007bbc368fde243ba47ca275e549c8a28617f56f6ba53b1d1c" +dependencies = [ + "bumpalo", + "log", + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.53" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0b221ff421256839509adbb55998214a70d829d3a28c69b4a6672e9d2a42f67" +dependencies = [ + "cfg-if", + "js-sys", + "once_cell", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.103" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc65f4f411d91494355917b605e1480033152658d71f722a90647f56a70c88a0" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.103" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ffc003a991398a8ee604a401e194b6b3a39677b3173d6e74495eb51b82e99a32" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-backend", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.103" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "293c37f4efa430ca14db3721dfbe48d8c33308096bd44d80ebaa775ab71ba1cf" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wayland-backend" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "673a33c33048a5ade91a6b139580fa174e19fb0d23f396dca9fa15f2e1e49b35" +dependencies = [ + "cc", + "downcast-rs", + "rustix 1.1.2", + "scoped-tls", + "smallvec", + "wayland-sys", +] + +[[package]] +name = "wayland-client" +version = "0.31.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c66a47e840dc20793f2264eb4b3e4ecb4b75d91c0dd4af04b456128e0bdd449d" +dependencies = [ + "bitflags 2.9.4", + "rustix 1.1.2", + "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.9.4", + "cursor-icon", + "wayland-backend", +] + +[[package]] +name = "wayland-cursor" +version = "0.31.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "447ccc440a881271b19e9989f75726d60faa09b95b0200a9b7eb5cc47c3eeb29" +dependencies = [ + "rustix 1.1.2", + "wayland-client", + "xcursor", +] + +[[package]] +name = "wayland-protocols" +version = "0.32.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "efa790ed75fbfd71283bd2521a1cfdc022aabcc28bdcff00851f9e4ae88d9901" +dependencies = [ + "bitflags 2.9.4", + "wayland-backend", + "wayland-client", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-plasma" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a07a14257c077ab3279987c4f8bb987851bf57081b93710381daea94f2c2c032" +dependencies = [ + "bitflags 2.9.4", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-wlr" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "efd94963ed43cf9938a090ca4f7da58eb55325ec8200c3848963e98dc25b78ec" +dependencies = [ + "bitflags 2.9.4", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-scanner" +version = "0.31.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54cb1e9dc49da91950bdfd8b848c49330536d9d1fb03d4bfec8cae50caa50ae3" +dependencies = [ + "proc-macro2", + "quick-xml", + "quote", +] + +[[package]] +name = "wayland-sys" +version = "0.31.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34949b42822155826b41db8e5d0c1be3a2bd296c747577a43a3e6daefc296142" +dependencies = [ + "dlib", + "log", + "once_cell", + "pkg-config", +] + +[[package]] +name = "web-sys" +version = "0.3.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fbe734895e869dc429d78c4b433f8d17d95f8d05317440b4fad5ab2d33e596dc" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-roots" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32b130c0d2d49f8b6889abc456e795e82525204f27c42cf767cf0d7734e089b8" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "wgpu" +version = "27.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfe68bac7cde125de7a731c3400723cadaaf1703795ad3f4805f187459cd7a77" +dependencies = [ + "arrayvec", + "bitflags 2.9.4", + "cfg-if", + "cfg_aliases", + "document-features", + "hashbrown 0.16.0", + "log", + "parking_lot", + "portable-atomic", + "profiling", + "raw-window-handle", + "smallvec", + "static_assertions", + "wgpu-core", + "wgpu-hal", + "wgpu-types", +] + +[[package]] +name = "wgpu-core" +version = "27.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3d654c0b6c6335edfca18c11bdaed964def641b8e9997d3a495a2ff4077c922" +dependencies = [ + "arrayvec", + "bit-set", + "bit-vec", + "bitflags 2.9.4", + "bytemuck", + "cfg_aliases", + "document-features", + "hashbrown 0.16.0", + "indexmap", + "log", + "naga", + "once_cell", + "parking_lot", + "portable-atomic", + "profiling", + "raw-window-handle", + "rustc-hash 1.1.0", + "smallvec", + "thiserror 2.0.16", + "wgpu-core-deps-windows-linux-android", + "wgpu-hal", + "wgpu-types", +] + +[[package]] +name = "wgpu-core-deps-windows-linux-android" +version = "27.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71197027d61a71748e4120f05a9242b2ad142e3c01f8c1b47707945a879a03c3" +dependencies = [ + "wgpu-hal", +] + +[[package]] +name = "wgpu-hal" +version = "27.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2618a2d6b8a5964ecc1ac32a5db56cb3b1e518725fcd773fd9a782e023453f2b" +dependencies = [ + "android_system_properties", + "arrayvec", + "ash", + "bitflags 2.9.4", + "bytemuck", + "cfg-if", + "cfg_aliases", + "gpu-alloc", + "gpu-descriptor", + "hashbrown 0.16.0", + "libc", + "libloading", + "log", + "naga", + "ordered-float", + "parking_lot", + "portable-atomic", + "portable-atomic-util", + "profiling", + "raw-window-handle", + "renderdoc-sys", + "smallvec", + "thiserror 2.0.16", + "wgpu-types", + "windows", +] + +[[package]] +name = "wgpu-types" +version = "27.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "afdcf84c395990db737f2dd91628706cb31e86d72e53482320d368e52b5da5eb" +dependencies = [ + "bitflags 2.9.4", + "bytemuck", + "js-sys", + "log", + "thiserror 2.0.16", + "web-sys", +] + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.0", +] + +[[package]] +name = "windows" +version = "0.58.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd04d41d93c4992d421894c18c8b43496aa748dd4c081bac0dc93eb0489272b6" +dependencies = [ + "windows-core", + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-core" +version = "0.58.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ba6d44ec8c2591c134257ce647b7ea6b20335bf6379a27dac5f1641fcf59f99" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-result", + "windows-strings", + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-implement" +version = "0.58.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bbd5b46c938e506ecbce286b6628a02171d56153ba733b6c741fc627ec9579b" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "windows-interface" +version = "0.58.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053c4c462dc91d3b1504c6fe5a726dd15e216ba718e84a0e46a88fbe5ded3515" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "windows-link" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e6ad25900d524eaabdbbb96d20b4311e1e7ae1699af4fb28c17ae66c80d798a" + +[[package]] +name = "windows-link" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "45e46c0661abb7180e7b9c281db115305d49ca1709ab8242adf09666d2173c65" + +[[package]] +name = "windows-result" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d1043d8214f791817bab27572aaa8af63732e11bf84aa21a45a78d6c317ae0e" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-strings" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cd9b125c486025df0eabcb585e62173c6c9eddcec5d117d3b6e8c30e2ee4d10" +dependencies = [ + "windows-result", + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0" +dependencies = [ + "windows-targets 0.42.2", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" +dependencies = [ + "windows-targets 0.53.3", +] + +[[package]] +name = "windows-sys" +version = "0.61.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e201184e40b2ede64bc2ea34968b28e33622acdbbf37104f0e4a33f7abe657aa" +dependencies = [ + "windows-link 0.2.0", +] + +[[package]] +name = "windows-targets" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071" +dependencies = [ + "windows_aarch64_gnullvm 0.42.2", + "windows_aarch64_msvc 0.42.2", + "windows_i686_gnu 0.42.2", + "windows_i686_msvc 0.42.2", + "windows_x86_64_gnu 0.42.2", + "windows_x86_64_gnullvm 0.42.2", + "windows_x86_64_msvc 0.42.2", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm 0.52.6", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + +[[package]] +name = "windows-targets" +version = "0.53.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5fe6031c4041849d7c496a8ded650796e7b6ecc19df1a431c1a363342e5dc91" +dependencies = [ + "windows-link 0.1.3", + "windows_aarch64_gnullvm 0.53.0", + "windows_aarch64_msvc 0.53.0", + "windows_i686_gnu 0.53.0", + "windows_i686_gnullvm 0.53.0", + "windows_i686_msvc 0.53.0", + "windows_x86_64_gnu 0.53.0", + "windows_x86_64_gnullvm 0.53.0", + "windows_x86_64_msvc 0.53.0", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8" + +[[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_gnullvm" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86b8d5f90ddd19cb4a147a5fa63ca848db3df085e25fee3cc10b39b6eebae764" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7651a1f62a11b8cbd5e0d42526e55f2c99886c77e007179efff86c2b137e66c" + +[[package]] +name = "windows_i686_gnu" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f" + +[[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_gnu" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1dc67659d35f387f5f6c479dc4e28f1d4bb90ddd1a5d3da2e5d97b42d6272c3" + +[[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_gnullvm" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ce6ccbdedbf6d6354471319e781c0dfef054c81fbc7cf83f338a4296c0cae11" + +[[package]] +name = "windows_i686_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_i686_msvc" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "581fee95406bb13382d2f65cd4a908ca7b1e4c2f1917f143ba16efe98a589b5d" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36" + +[[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_gnu" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e55b5ac9ea33f2fc1716d1742db15574fd6fc8dadc51caab1c16a3d3b4190ba" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3" + +[[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_gnullvm" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a6e035dd0599267ce1ee132e51c27dd29437f63325753051e71dd9e42406c57" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "271414315aff87387382ec3d271b52d7ae78726f5d44ac98b4f4030c91880486" + +[[package]] +name = "winit" +version = "0.30.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c66d4b9ed69c4009f6321f762d6e61ad8a2389cd431b97cb1e146812e9e6c732" +dependencies = [ + "ahash", + "android-activity", + "atomic-waker", + "bitflags 2.9.4", + "block2", + "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 0.2.2", + "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.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21a0236b59786fed61e2a80582dd500fe61f18b5dca67a4a067d0bc9039339cf" +dependencies = [ + "memchr", +] + +[[package]] +name = "wit-bindgen" +version = "0.46.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59" + +[[package]] +name = "wl-clipboard-rs" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e5ff8d0e60065f549fafd9d6cb626203ea64a798186c80d8e7df4f8af56baeb" +dependencies = [ + "libc", + "log", + "os_pipe", + "rustix 0.38.44", + "tempfile", + "thiserror 2.0.16", + "tree_magic_mini", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-protocols-wlr", +] + +[[package]] +name = "writeable" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea2f10b9bb0928dfb1b42b65e1f9e36f7f54dbdf08457afefb38afcdec4fa2bb" + +[[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.2", + "x11rb-protocol", +] + +[[package]] +name = "x11rb-protocol" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd" + +[[package]] +name = "xattr" +version = "1.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156" +dependencies = [ + "libc", + "rustix 1.1.2", +] + +[[package]] +name = "xcursor" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bec9e4a500ca8864c5b47b8b482a73d62e4237670e5b5f1d6b9e3cae50f28f2b" + +[[package]] +name = "xkbcommon-dl" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d039de8032a9a8856a6be89cea3e5d12fdd82306ab7c94d74e6deab2460651c5" +dependencies = [ + "bitflags 2.9.4", + "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 = "yazi" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e01738255b5a16e78bbb83e7fbba0a1e7dd506905cfc53f4622d89015a03fbb5" + +[[package]] +name = "yeslogic-fontconfig-sys" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "503a066b4c037c440169d995b869046827dbc71263f6e8f3be6d77d4f3229dbd" +dependencies = [ + "dlib", + "once_cell", + "pkg-config", +] + +[[package]] +name = "zeno" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6df3dc4292935e51816d896edcd52aa30bc297907c26167fec31e2b0c6a32524" + +[[package]] +name = "zerocopy" +version = "0.8.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0894878a5fa3edfd6da3f88c4805f4c8558e2b996227a3d864f47fe11e38282c" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88d2b8d9c68ad2b9e4340d7832716a4d21a22a1154777ad56ea55c51a9cf3831" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "zerofrom" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50cc42e0333e05660c3587f3bf9d0478688e15d870fab3346451ce7f8c9fbea5" + +[[package]] +name = "zeroize" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ced3678a2879b30306d323f4542626697a464a97c0a07c9aebf7ebca65cd4dde" + +[[package]] +name = "zerovec" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7aa2bd55086f1ab526693ecbe444205da57e25f4489879da80635a46d90e73b" +dependencies = [ + "zerofrom", +] + +[[package]] +name = "zstd" +version = "0.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a" +dependencies = [ + "zstd-safe", +] + +[[package]] +name = "zstd-safe" +version = "7.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f49c4d5f0abb602a93fb8736af2a4f4dd9512e36f7f570d66e65ff867ed3b9d" +dependencies = [ + "zstd-sys", +] + +[[package]] +name = "zstd-sys" +version = "2.0.16+zstd.1.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e19ebc2adc8f83e43039e79776e3fda8ca919132d68a1fed6a5faca2683748" +dependencies = [ + "cc", + "pkg-config", +] + +[[package]] +name = "zune-core" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f423a2c17029964870cfaabb1f13dfab7d092a62a29a89264f4d36990ca414a" + +[[package]] +name = "zune-jpeg" +version = "0.4.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29ce2c8a9384ad323cf564b67da86e21d3cfdff87908bc1223ed5c99bc792713" +dependencies = [ + "zune-core", +] diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..bade0e7 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,39 @@ +[package] +name = "rusty-path-of-building" +version = "0.1.0" +edition = "2024" + +[dependencies] +ahash = "0.8.12" +anyhow = "1.0" +arboard = { version = "3.6.1", default-features = false, features = ["wayland-data-control"] } +bytemuck = "1.23.2" +clap = { version = "4.5.46", features = ["derive"] } +dds = "0.1.0" +directories = "6.0.0" +env_logger = "0.10" +euclid = { version = "0.22.11", features = ["bytemuck"] } +fast_image_resize = { version = "5.3.0", features = ["image"] } +flate2 = "1.1.2" +glob = "0.3.3" +image = { version = "0.25.8", default-features = false, features = ["rayon", "jpeg", "png"] } +log = "0.4" +mlua = { version = "0.11.2", features = ["luajit", "anyhow"] } +nohash-hasher = "0.2.0" +num-traits = "0.2.19" +open = "5.3.2" +ordered-float = "5.0.0" +parley = "0.6.0" +pollster = "0.3" +profiling = "1.0" +puffin_http = { version = "0.16", optional = true } +regex = "1.11.2" +swash = "0.2.5" +tar = "0.4.44" +ureq = "3.1.2" +wgpu = { version = "27.0.1", default-features = false, features = ["std", "parking_lot", "vulkan", "wgsl"] } +winit = "0.30" +zstd = "0.13.3" + +[features] +profile-with-puffin = ["profiling/profile-with-puffin", "dep:puffin_http"] diff --git a/fonts/LiberationSans License.txt b/fonts/LiberationSans License.txt new file mode 100644 index 0000000..f2473f9 --- /dev/null +++ b/fonts/LiberationSans License.txt @@ -0,0 +1,46 @@ +Digitized data copyright (c) 2010 Google Corporation + with Reserved Font Arimo, Tinos and Cousine. +Copyright (c) 2012 Red Hat, Inc. + with Reserved Font Name Liberation. + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide development of collaborative font projects, to support the font creation efforts of academic and linguistic communities, and to provide a free and open framework in which fonts may be shared and improved in partnership with others. + +The OFL allows the licensed fonts to be used, studied, modified and redistributed freely as long as they are not sold by themselves. The fonts, including any derivative works, can be bundled, embedded, redistributed and/or sold with any software provided that any reserved names are not used by derivative works. The fonts and derivatives, however, cannot be released under any other type of license. The requirement for fonts to remain under this license does not apply to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright Holder(s) under this license and clearly marked as such. This may include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the copyright statement(s). + +"Original Version" refers to the collection of Font Software components as distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, or substituting -- in part or in whole -- any of the components of the Original Version, by changing formats or by porting the Font Software to a new environment. + +"Author" refers to any designer, engineer, programmer, technical writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to use, study, copy, merge, embed, modify, redistribute, and sell modified and unmodified copies of the Font Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any software, provided that each copy contains the above copyright notice and this license. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font Name(s) unless explicit written permission is granted by the corresponding Copyright Holder. This restriction only applies to the primary font name as presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font Software shall not be used to promote, endorse or advertise any Modified Version, except to acknowledge the contribution(s) of the Copyright Holder(s) and the Author(s) or with their explicit written permission. + +5) The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this license, and must not be distributed under any other license. The requirement for fonts to remain under this license does not apply to any document created using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE. \ No newline at end of file diff --git a/fonts/LiberationSans-Bold.ttf b/fonts/LiberationSans-Bold.ttf new file mode 100644 index 0000000..4581ebf Binary files /dev/null and b/fonts/LiberationSans-Bold.ttf differ diff --git a/fonts/LiberationSans-Regular.ttf b/fonts/LiberationSans-Regular.ttf new file mode 100644 index 0000000..626dd93 Binary files /dev/null and b/fonts/LiberationSans-Regular.ttf differ diff --git a/fonts/VeraMono License.txt b/fonts/VeraMono License.txt new file mode 100644 index 0000000..cf00835 --- /dev/null +++ b/fonts/VeraMono License.txt @@ -0,0 +1,123 @@ +Bitstream Vera Fonts Copyright + +The fonts have a generous copyright, allowing derivative works (as +long as "Bitstream" or "Vera" are not in the names), and full +redistribution (so long as they are not *sold* by themselves). They +can be be bundled, redistributed and sold with any software. + +The fonts are distributed under the following copyright: + +Copyright +========= + +Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream +Vera is a trademark of Bitstream, Inc. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of the fonts accompanying this license ("Fonts") and associated +documentation files (the "Font Software"), to reproduce and distribute +the Font Software, including without limitation the rights to use, +copy, merge, publish, distribute, and/or sell copies of the Font +Software, and to permit persons to whom the Font Software is furnished +to do so, subject to the following conditions: + +The above copyright and trademark notices and this permission notice +shall be included in all copies of one or more of the Font Software +typefaces. + +The Font Software may be modified, altered, or added to, and in +particular the designs of glyphs or characters in the Fonts may be +modified and additional glyphs or characters may be added to the +Fonts, only if the fonts are renamed to names not containing either +the words "Bitstream" or the word "Vera". + +This License becomes null and void to the extent applicable to Fonts +or Font Software that has been modified and is distributed under the +"Bitstream Vera" names. + +The Font Software may be sold as part of a larger software package but +no copy of one or more of the Font Software typefaces may be sold by +itself. + +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL +BITSTREAM OR THE GNOME FOUNDATION BE LIABLE FOR ANY CLAIM, DAMAGES OR +OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, +OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT +SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE. + +Except as contained in this notice, the names of Gnome, the Gnome +Foundation, and Bitstream Inc., shall not be used in advertising or +otherwise to promote the sale, use or other dealings in this Font +Software without prior written authorization from the Gnome Foundation +or Bitstream Inc., respectively. For further information, contact: +fonts at gnome dot org. + +Copyright FAQ +============= + + 1. I don't understand the resale restriction... What gives? + + Bitstream is giving away these fonts, but wishes to ensure its + competitors can't just drop the fonts as is into a font sale system + and sell them as is. It seems fair that if Bitstream can't make money + from the Bitstream Vera fonts, their competitors should not be able to + do so either. You can sell the fonts as part of any software package, + however. + + 2. I want to package these fonts separately for distribution and + sale as part of a larger software package or system. Can I do so? + + Yes. A RPM or Debian package is a "larger software package" to begin + with, and you aren't selling them independently by themselves. + See 1. above. + + 3. Are derivative works allowed? + Yes! + + 4. Can I change or add to the font(s)? + Yes, but you must change the name(s) of the font(s). + + 5. Under what terms are derivative works allowed? + + You must change the name(s) of the fonts. This is to ensure the + quality of the fonts, both to protect Bitstream and Gnome. We want to + ensure that if an application has opened a font specifically of these + names, it gets what it expects (though of course, using fontconfig, + substitutions could still could have occurred during font + opening). You must include the Bitstream copyright. Additional + copyrights can be added, as per copyright law. Happy Font Hacking! + + 6. If I have improvements for Bitstream Vera, is it possible they might get + adopted in future versions? + + Yes. The contract between the Gnome Foundation and Bitstream has + provisions for working with Bitstream to ensure quality additions to + the Bitstream Vera font family. Please contact us if you have such + additions. Note, that in general, we will want such additions for the + entire family, not just a single font, and that you'll have to keep + both Gnome and Jim Lyles, Vera's designer, happy! To make sense to add + glyphs to the font, they must be stylistically in keeping with Vera's + design. Vera cannot become a "ransom note" font. Jim Lyles will be + providing a document describing the design elements used in Vera, as a + guide and aid for people interested in contributing to Vera. + + 7. I want to sell a software package that uses these fonts: Can I do so? + + Sure. Bundle the fonts with your software and sell your software + with the fonts. That is the intent of the copyright. + + 8. If applications have built the names "Bitstream Vera" into them, + can I override this somehow to use fonts of my choosing? + + This depends on exact details of the software. Most open source + systems and software (e.g., Gnome, KDE, etc.) are now converting to + use fontconfig (see www.fontconfig.org) to handle font configuration, + selection and substitution; it has provisions for overriding font + names and subsituting alternatives. An example is provided by the + supplied local.conf file, which chooses the family Bitstream Vera for + "sans", "serif" and "monospace". Other software (e.g., the XFree86 + core server) has other mechanisms for font substitution. \ No newline at end of file diff --git a/fonts/VeraMono.ttf b/fonts/VeraMono.ttf new file mode 100644 index 0000000..139f0b4 Binary files /dev/null and b/fonts/VeraMono.ttf differ diff --git a/lua/libs/lzip/Makefile b/lua/libs/lzip/Makefile new file mode 100644 index 0000000..7182983 --- /dev/null +++ b/lua/libs/lzip/Makefile @@ -0,0 +1,80 @@ +T=lzip + +UNAME ?= $(shell uname) +DESTDIR ?= / +PKG_CONFIG ?= pkg-config +INSTALL ?= install +RM ?= rm +LUA_IMPL ?= luajit +CC ?= $(MAC_ENV) g++ + +LUA_VERSION = $(shell $(PKG_CONFIG) --print-provides --silence-errors $(LUA_IMPL)) +ifeq ($(LUA_VERSION),) +LUA_CMOD ?= /usr/lib/lua/5.1 +LUA_LMOD ?= /usr/share/lua/5.1 +LIBDIR ?= /usr/lib +LUA_INC ?= /usr/include +ZLIB_LIBS = -L/usr/lib -lz +else +LUA_CMOD ?= $(shell $(PKG_CONFIG) --variable INSTALL_CMOD $(LUA_IMPL)) +LUA_LMOD ?= $(shell $(PKG_CONFIG) --variable INSTALL_LMOD $(LUA_IMPL)) +LIBDIR ?= $(shell $(PKG_CONFIG) --variable libdir $(LUA_IMPL)) +LUA_INC ?= $(shell $(PKG_CONFIG) --variable includedir $(LUA_IMPL)) +LUA_LIBS = $(shell $(PKG_CONFIG) --libs $(LUA_IMPL)) +ZLIB_LIBS = $(shell $(PKG_CONFIG) --libs zlib) +endif + +ifeq ($(UNAME), Linux) +OS_FLAGS ?= -shared +endif +ifeq ($(UNAME), Darwin) +OS_FLAGS ?= -bundle -undefined dynamic_lookup +MAC_ENV ?= env MACOSX_DEPLOYMENT_TARGET='10.3' +endif + +ifneq ($(DEBUG),) +DBG = -ggdb +endif + +ifeq ($(DEV),) +WARN = -Wall -Wno-unused-value +else +WARN = -Wall -W -Waggregate-return -Wcast-align -Wmissing-prototypes -Wnested-externs -Wshadow -Wwrite-strings -pedantic +endif + +INCLUDES = -I$(LUA_INC) +DEFINES = +LIBS = $(ZLIB_LIBS) -lstdc++ + +COMMONFLAGS = -O2 -g -pipe -fPIC $(OS_FLAGS) $(DBG) +LF = $(LIBS) $(LDFLAGS) +CF = $(INCLUDES) $(DEFINES) $(COMMONFLAGS) $(WARN) -DPTHREADS $(CFLAGS) + +#SCR = src/lua/*.lua src/lua/cURL/*.lua src/lua/cURL/impl/*.lua +SRCS = src/*.cpp +OBJS = $(subst src/,,$(subst .c,.o,$(SRCS))) + +BIN = $(T).so +STATIC_LIB = $(T).a + +all: $(BIN) + +$(BIN): $(SRCS) + $(CC) $(CF) -o $@ $^ $(LF) + +$(OBJS): $(SRCS) + $(CC) $(CF) -c $^ $(LF) + +$(STATIC_LIB): $(OBJS) + ar rcs $@ $^ + +#install: all +# $(INSTALL) -d $(DESTDIR)$(LUA_CMOD) $(DESTDIR)$(LUA_LMOD)/cURL/impl +# $(INSTALL) $(BIN) $(DESTDIR)$(LUA_CMOD) +# $(INSTALL) src/lua/cURL.lua $(DESTDIR)$(LUA_LMOD) +# $(INSTALL) src/lua/cURL/safe.lua $(DESTDIR)$(LUA_LMOD)/cURL +# $(INSTALL) src/lua/cURL/utils.lua $(DESTDIR)$(LUA_LMOD)/cURL +# $(INSTALL) src/lua/cURL/impl/cURL.lua $(DESTDIR)$(LUA_LMOD)/cURL/impl + +clean: + $(RM) -f $(BIN) $(OBJS) $(STATIC_LIB) diff --git a/lua/libs/lzip/src/lzip.cpp b/lua/libs/lzip/src/lzip.cpp new file mode 100644 index 0000000..673aef0 --- /dev/null +++ b/lua/libs/lzip/src/lzip.cpp @@ -0,0 +1,735 @@ +#include +#include +#include + +#include "zlib.h" + +#ifdef _WIN32 +#define LZIP_EXPORT __declspec(dllexport) +#else +#define LZIP_EXPORT +#endif + +extern "C" { +#include "lua.h" +#include "lauxlib.h" +#include "lualib.h" +#include "luajit.h" +} + +typedef unsigned char byte; +typedef unsigned int dword; +typedef unsigned long lword; + +char* AllocString(char* st) +{ + if (st == NULL) { + return NULL; + } + + int aslen = strlen(st) + 1; + char* al = new char[aslen]; + strcpy(al, st); + return al; +} + +char* AllocStringLen(int len) +{ + char* al = new char[len+1]; + al[len] = 0; + return al; +} + +void FreeString(char* st) +{ + if (st) delete st; +} + +// ============= +// Configuration +// ============= + +static const int FS_INFLATE_BUFFER = 65536; + +// ========================== +// Zip File format structures +// ========================== + +#pragma pack(push, 1) + +struct zf_cdHeader_s { + int sig; // 0x02014b50 (50,4B,01,02) + short ver_made; + short ver_ext; + short flag; + short method; + short ftime; + short fdate; + int crc32; + lword szComp; + lword szUcomp; + short szName; + short szExtra; + short szComm; + short nDisk; + short attInt; + int attExt; + int hOffset; +}; + +struct zf_localHeader_s { + int sig; // 0x04034b50 (50,4B,03,04) + short ver_ext; + short flag; + short method; + short ftime; + short fdate; + int crc32; + lword szComp; + lword szUcomp; + short szName; + short szExtra; +}; + +struct zf_dataDesc_s { + int crc32; + lword szComp; + lword szUcomp; +}; + +struct zf_cdEnd_s { + int sig; // 0x06054b50 (50,4B,05,06) + short nDisk; + short stDisk; + short noeDisk; + short noeTotal; + int szTotal; + int cdOffset; + short szComm; +}; + +#pragma pack(pop) + +// ========================= +// Zip File format constants +// ========================= + +static const int ZF_MAXVER = 20; + +static const int ZF_GPBF_ENC = 0x0001; +static const int ZF_GPBF_DD = 0x0008; + +static const int ZF_METHOD_STORE = 0; +static const int ZF_METHOD_DEFLATE = 8; + +static const int ZF_SIG_CDHEADER = 0x02014B50; +static const int ZF_SIG_LOCALHEADER = 0x04034B50; +static const int ZF_SIG_CDEND = 0x06054B50; + +// =============== +// ZLib Alloc/Free +// =============== + +static void* ZF_Alloc(void* unused, dword num, dword size) +{ + return new byte[num*size]; +} + +static void ZF_Free(void* unused, void* ptr) +{ + delete (byte*)ptr; +} + +// ======= +// Classes +// ======= + +struct fs_fileInfo_s { + FILE* f; // Zip file + char* name; // Filename + int fo; // File offset + int szU; // Uncompressed size + int szC; // Compressed size, 0 if not compressed +}; + +// ================ +// fsInflator class +// ================ + +class fs_inflator_c { +public: + fs_inflator_c(fs_fileInfo_s* i); + ~fs_inflator_c(); + int Inflate(byte* buf, int len);// Inflate + +private: + int pC; // Read pointer + byte* ibuf; // Input buffer + int ibuflen; // Input buffer length + fs_fileInfo_s* i; // Info structure + z_stream* zst; // ZLib stream + + void FillInput();// Fill decompression input +}; + +fs_inflator_c::fs_inflator_c(fs_fileInfo_s* info) +{ + i = info; + + // Initialise stream + zst = new z_stream; + memset(zst, 0, sizeof(z_stream)); + zst->zalloc = ZF_Alloc; + zst->zfree = ZF_Free; + + // Initialise decompression input + pC = 0; + if (i->szC < FS_INFLATE_BUFFER) { + ibuflen = i->szC; + } else { + ibuflen = FS_INFLATE_BUFFER; + } + ibuf = new byte[ibuflen]; + FillInput(); + + // Start decompressor + inflateInit2(zst, -MAX_WBITS); +} + +fs_inflator_c::~fs_inflator_c() +{ + // Stop decompressor + inflateEnd(zst); + + // Release stream and input buffer + delete ibuf; + delete zst; +} + +void fs_inflator_c::FillInput() +{ + // Relocate any remaining input + int remin = zst->avail_in; + if (remin) { + memcpy(ibuf, zst->next_in, remin); + } + + // Get reading amount + int rdmax = ibuflen - remin; + int rd = i->szC - pC; + if (rd > rdmax) { + rd = rdmax; + } + + // Read into buffer + if (rd) { + fseek(i->f, i->fo + pC, SEEK_SET); + fread(ibuf + remin, rd, 1, i->f); + } + + // Update stream + zst->next_in = ibuf; + zst->avail_in+= rd; + pC+= rd; +} + +int fs_inflator_c::Inflate(byte* out, int len) +{ + // Prepare stream + zst->next_out = out; + zst->avail_out = len; + + while (1) { + // Decompress some data + int r = inflate(zst, Z_SYNC_FLUSH); + + switch (r) { + case Z_OK: + // Progress made, check if we're done + if (zst->avail_out == 0) { + return len; + } + break; + case Z_BUF_ERROR: + // No progress made, so give it more input + FillInput(); + break; + default: + // We got an error + case Z_STREAM_END: + // Reached the end of the stream + return len - zst->avail_out; + } + } +} + +// ============= +// fsFile class +// ============= + +enum vf_state_e { + VF_OPEN =0x01, // Open + VF_SEEK =0x04 // Seek enabled +}; + +class fs_file_c { +public: + fs_file_c(fs_fileInfo_s* i); + ~fs_file_c(); + void Seek(int pos, int mode); // Seek + int Read(byte* buf, int len); // Read data + int Length(); // Return the file length + int Tell(); // Return the read pointer + +private: + fs_fileInfo_s* i; // Info structure + int pU; // Read pointer + fs_inflator_c* inf; // Inflator +}; + +fs_file_c::fs_file_c(fs_fileInfo_s* info) +{ + i = info; + + // Create inflator + if (i->szC) { + inf = new fs_inflator_c(i); + } else { + inf = NULL; + } + + // Set position + pU = 0; +} + +fs_file_c::~fs_file_c() +{ + delete inf; +} + +void fs_file_c::Seek(int pos, int mode) +{ + int seekto; + + switch (mode) { + case SEEK_SET: + seekto = pos; + break; + case SEEK_CUR: + seekto = pU + pos; + break; + case SEEK_END: + seekto = i->szU - pos; + break; + default: + return; + } + + if (i->szC) { + int diff = seekto - pU; + if (diff > 0) { + // Seek forward + byte* sk = new byte[diff]; + Read(sk, diff); + delete[] sk; + } else if (diff < 0) { + // Restart reading + pU = 0; + // Recreate inflator + delete inf; + inf = new fs_inflator_c(i); + if (seekto) { + // Seek forward + byte* sk = new byte[seekto]; + Read(sk, seekto); + delete[] sk; + } + } + } else { + pU = seekto; + if (pU < 0) { + pU = 0; + } else if (pU > i->szU) { + pU = i->szU; + } + } +} + +int fs_file_c::Read(byte* out, int len) +{ + // Determine read length + int rp = len + pU; + if (rp > i->szU) len = i->szU - pU; + if (len == 0) { + return 0; + } + + if (i->szC) { + // Decompress + len = inf->Inflate(out, len); + } else { + // Raw read + fseek(i->f, i->fo + pU, SEEK_SET); + len = fread(out, 1, len, i->f); + } + + pU+= len; + return len; +} + +int fs_file_c::Length() +{ + return i->szU; +} + +int fs_file_c::Tell() +{ + return pU; +} + +// ============= +// zipFile class +// ============= + +class fs_zipFile_c { +public: + fs_zipFile_c(const char* zname); + ~fs_zipFile_c(); + + int numFiles; + fs_fileInfo_s** files; +private: + FILE* zf; // File handle + int filesSz; + + int GetSignature(); // Get next signature +}; + +int fs_zipFile_c::GetSignature() +{ + int sig = 0; + if (fread(&sig, 4, 1, zf) == 0) { + return 0; + } + fseek(zf, -4, SEEK_CUR); + return sig; +} + +fs_zipFile_c::fs_zipFile_c(const char* zname) +{ + numFiles = 0; + filesSz = 32; + files = new fs_fileInfo_s*[filesSz]; + + int sig; + + // Open and lock file + zf = fopen(zname, "rb"); + if (zf == NULL) { + return; + } + + // Check signature + sig = GetSignature(); + if (strncmp((char*)&sig, "Rar", 3) == 0) { + fclose(zf); + return; + } + + // Read local headers + while (sig == ZF_SIG_LOCALHEADER) { + zf_localHeader_s lh; + if (fread(&lh, sizeof(lh), 1, zf) == 0) { + fclose(zf); + return; + } + + if (lh.szName) { + // Read filename + char* fname = AllocStringLen(lh.szName); + fread(fname, lh.szName, 1, zf); + + // Add it in if it is a file + if (fname[lh.szName-1] != '/') { + // Fill in info + fs_fileInfo_s* fi = new fs_fileInfo_s; + fi->f = zf; + fi->name = fname; + fi->fo = ftell(zf) + lh.szExtra; + fi->szU = lh.szUcomp; + fi->szC = (lh.method == ZF_METHOD_DEFLATE)? lh.szComp : 0; + + // Record file + if (numFiles == filesSz) { + filesSz<<= 1; + files = (fs_fileInfo_s**)realloc(files, sizeof(fs_fileInfo_s*)*filesSz); + } + files[numFiles++] = fi; + } else { + FreeString(fname); + } + + // Skip the extra information and file data + fseek(zf, lh.szExtra + lh.szComp, SEEK_CUR); + } + + sig = GetSignature(); + } +} + +fs_zipFile_c::~fs_zipFile_c() +{ + fclose(zf); + for (int f = 0; f < numFiles; f++) { + delete files[f]->name; + delete files[f]; + } + delete files; +} + +// ============= +// Lua Interface +// ============= + +static int IsUserData(lua_State* L, int index, const char* metaName) +{ + if (lua_type(L, index) != LUA_TUSERDATA || lua_getmetatable(L, index) == 0) { + return 0; + } + lua_getfield(L, lua_upvalueindex(1), metaName); + int ret = lua_rawequal(L, -2, -1); + lua_pop(L, 2); + return ret; +} + +struct lzip_s { + fs_zipFile_c* zipFile; +}; +static lzip_s* GetZip(lua_State* L, const char* method, bool valid) +{ + if ( !IsUserData(L, 1, "zipMeta") ) { + luaL_error(L, "zip:%s() must be used on a zip handle", method); + } + lzip_s* lz = (lzip_s*)lua_touserdata(L, 1); + lua_remove(L, 1); + if (valid && lz->zipFile == NULL) { + luaL_error(L, "zip:%s(): zip handle is closed"); + } + return lz; +} + +struct lzipFile_s { + fs_file_c* file; +}; +static lzipFile_s* GetZipFile(lua_State* L, const char* method, bool valid) +{ + if ( !IsUserData(L, 1, "zipFileMeta") ) { + luaL_error(L, "zipFile:%s() must be used on a zip file handle", method); + } + lzipFile_s* lzf = (lzipFile_s*)lua_touserdata(L, 1); + lua_remove(L, 1); + if (valid && lzf->file == NULL) { + luaL_error(L, "zipFile:%s(): zip file handle is closed"); + } + return lzf; +} + +static int l_open(lua_State* L) +{ + int n = lua_gettop(L); + if (n < 1 || !lua_isstring(L, 1)) { + luaL_error(L, "Usage: lzip.open(fileName)"); + } + fs_zipFile_c* zipFile = new fs_zipFile_c(lua_tostring(L, 1)); + if (zipFile->numFiles == 0) { + delete zipFile; + return 0; + } + lzip_s* lz = (lzip_s*)lua_newuserdata(L, sizeof(lzip_s)); + lz->zipFile = zipFile; + lua_pushvalue(L, lua_upvalueindex(2)); + lua_setmetatable(L, -2); + return 1; +} + +static int l_zip_Close(lua_State* L) +{ + lzip_s* lz = GetZip(L, "Closea", false); + delete lz->zipFile; + lz->zipFile = NULL; + return 0; +} + +static int l_zip_GetNumFiles(lua_State* L) +{ + lzip_s* lz = GetZip(L, "GetNumFiles", true); + lua_pushinteger(L, lz->zipFile->numFiles); + return 1; +} + +static int l_zip_GetFileName(lua_State* L) +{ + lzip_s* lz = GetZip(L, "GetFileName", true); + int n = lua_gettop(L); + if (n < 1 || !lua_isnumber(L, 1)) { + luaL_error(L, "Usage: zip:GetFileName(index)"); + } + int index = lua_tointeger(L, 1); + if (index < 1 || index > lz->zipFile->numFiles) { + return 0; + } + lua_pushstring(L, lz->zipFile->files[index - 1]->name); + return 1; +} + +static int l_zip_GetFileSize(lua_State* L) +{ + lzip_s* lz = GetZip(L, "GetFileSize", true); + int n = lua_gettop(L); + if (n < 1 || !lua_isnumber(L, 1)) { + luaL_error(L, "Usage: zip:GetFileSize(index)"); + } + int index = lua_tointeger(L, 1); + if (index < 1 || index > lz->zipFile->numFiles) { + return 0; + } + lua_pushinteger(L, lz->zipFile->files[index - 1]->szU); + return 1; +} + +static int l_zip_OpenFile(lua_State* L) +{ + lzip_s* lz = GetZip(L, "OpenFile", true); + int n = lua_gettop(L); + if (n < 1 || !(lua_isnumber(L, 1) || lua_isstring(L, 1))) { + luaL_error(L, "Usage: zip:OpenFile(index) or zip:OpenFile(fileName)"); + } + fs_fileInfo_s* i = NULL; + if (lua_isnumber(L, 1)) { + int index = lua_tointeger(L, 1); + if (index < 1 || index > lz->zipFile->numFiles) { + luaL_error(L, "zip:OpenFile(): invalid index"); + } + i = lz->zipFile->files[index - 1]; + } else { + const char* name = lua_tostring(L, 1); + for (int index = 0; index < lz->zipFile->numFiles; index++) { + if ( !strcmp(name, lz->zipFile->files[index]->name) ) { + i = lz->zipFile->files[index]; + break; + } + } + if ( !i ) { + return 0; + } + } + fs_file_c* file = new fs_file_c(i); + lzipFile_s* lzf = (lzipFile_s*)lua_newuserdata(L, sizeof(lzipFile_s)); + lzf->file = file; + lua_pushvalue(L, lua_upvalueindex(2)); + lua_setmetatable(L, -2); + return 1; +} + +static int l_zipFile_Close(lua_State* L) +{ + lzipFile_s* lzf = GetZipFile(L, "Close", false); + delete lzf->file; + lzf->file = NULL; + return 0; +} + +static int l_zipFile_Read(lua_State* L) +{ + lzipFile_s* lzf = GetZipFile(L, "Read", true); + int n = lua_gettop(L); + if (n < 1) { + luaL_error(L, "Usage: zipFile:Read(count) or zipFile:read(\"*a\")"); + } + int count; + if (lua_isnumber(L, 1)) { + count = lua_tointeger(L, 1); + } else { + if ( !strcmp(lua_tostring(L, 1), "*a") ) { + count = lzf->file->Length() - lzf->file->Tell(); + } else { + luaL_error(L, "zipFile:Read(): unrecognised format: %s", lua_tostring(L, 1)); + } + } + if (count < 1) { + lua_pushstring(L, ""); + return 1; + } + byte* buf = new byte[count]; + lzf->file->Read(buf, count); + lua_pushlstring(L, (char*)buf, count); + return 1; +} + +static int l_zipFile_Length(lua_State* L) +{ + lzipFile_s* lzf = GetZipFile(L, "Read", true); + lua_pushinteger(L, lzf->file->Length()); + return 1; +} + +extern "C" LZIP_EXPORT int luaopen_lzip(lua_State* L) +{ + lua_settop(L, 0); + lua_newtable(L); // Library table + lua_newtable(L); // Zip metatable + lua_newtable(L); // Zip file metatable + + lua_pushvalue(L, 2); + lua_setfield(L, 1, "zipMeta"); + lua_pushvalue(L, 2); + lua_setfield(L, 2, "__index"); + + lua_pushvalue(L, 3); + lua_setfield(L, 1, "zipFileMeta"); + lua_pushvalue(L, 3); + lua_setfield(L, 3, "__index"); + + lua_pushvalue(L, 1); + lua_pushvalue(L, 2); + lua_pushcclosure(L, l_open, 2); + lua_setfield(L, 1, "open"); + + lua_pushvalue(L, 1); + lua_pushcclosure(L, l_zip_Close, 1); + lua_setfield(L, 2, "__gc"); + lua_pushvalue(L, 1); + lua_pushcclosure(L, l_zip_Close, 1); + lua_setfield(L, 2, "Close"); + lua_pushvalue(L, 1); + lua_pushcclosure(L, l_zip_GetNumFiles, 1); + lua_setfield(L, 2, "GetNumFiles"); + lua_pushvalue(L, 1); + lua_pushcclosure(L, l_zip_GetFileName, 1); + lua_setfield(L, 2, "GetFileName"); + lua_pushvalue(L, 1); + lua_pushcclosure(L, l_zip_GetFileSize, 1); + lua_setfield(L, 2, "GetFileSize"); + lua_pushvalue(L, 1); + lua_pushvalue(L, 3); + lua_pushcclosure(L, l_zip_OpenFile, 2); + lua_setfield(L, 2, "OpenFile"); + + lua_pushvalue(L, 1); + lua_pushcclosure(L, l_zipFile_Close, 1); + lua_setfield(L, 3, "__gc"); + lua_pushvalue(L, 1); + lua_pushcclosure(L, l_zipFile_Close, 1); + lua_setfield(L, 3, "Close"); + lua_pushvalue(L, 1); + lua_pushcclosure(L, l_zipFile_Read, 1); + lua_setfield(L, 3, "Read"); + lua_pushvalue(L, 1); + lua_pushcclosure(L, l_zipFile_Length, 1); + lua_setfield(L, 3, "Length"); + + // Pop metatables + lua_pop(L, 2); + + return 1; +} diff --git a/lua/poe1/UpdateCheck.lua b/lua/poe1/UpdateCheck.lua new file mode 100644 index 0000000..e678bc8 --- /dev/null +++ b/lua/poe1/UpdateCheck.lua @@ -0,0 +1,301 @@ +#@ +-- Path of Building +-- +-- Module: Update Check +-- Checks for updates +-- +local connectionProtocol, proxyURL = ... + +local xml = require("xml") +local sha1 = require("sha1") +local curl = require("lcurl.safe") +local lzip = require("lzip") + +local globalRetryLimit = 10 +local function downloadFileText(source, file) + for i = 1, 5 do + if i > 1 then + ConPrintf("Retrying... (%d of 5)", i) + end + local text = "" + local easy = curl.easy() + local escapedUrl = source..easy:escape(file) + easy:setopt_url(escapedUrl) + easy:setopt(curl.OPT_ACCEPT_ENCODING, "") + if connectionProtocol then + easy:setopt(curl.OPT_IPRESOLVE, connectionProtocol) + end + if proxyURL then + easy:setopt(curl.OPT_PROXY, proxyURL) + end + easy:setopt_writefunction(function(data) + text = text..data + return true + end) + local _, error = easy:perform() + easy:close() + if not error then + return text + end + ConPrintf("Download failed (%s)", error:msg()) + if globalRetryLimit == 0 or i == 5 then + return nil, error:msg() + end + globalRetryLimit = globalRetryLimit - 1 + end +end +local function downloadFile(source, file, outName) + for i = 1, 5 do + if i > 1 then + ConPrintf("Retrying... (%d of 5)", i) + end + local easy = curl.easy() + local escapedUrl = source..easy:escape(file) + easy:setopt_url(escapedUrl) + easy:setopt(curl.OPT_ACCEPT_ENCODING, "") + if connectionProtocol then + easy:setopt(curl.OPT_IPRESOLVE, connectionProtocol) + end + if proxyURL then + easy:setopt(curl.OPT_PROXY, proxyURL) + end + local file = io.open(outName, "wb+") + easy:setopt_writefunction(file) + local _, error = easy:perform() + easy:close() + file:close() + if not error then + return true + end + ConPrintf("Download failed (%s)", error:msg()) + if globalRetryLimit == 0 or i == 5 then + return nil, error:msg() + end + globalRetryLimit = globalRetryLimit - 1 + end + return true +end + +ConPrintf("Checking for update...") + +-- Use built-in helpers to obtain absolute paths without spawning a shell. +local scriptPath = (GetScriptPath and GetScriptPath()) or "." +local runtimePath = (GetRuntimePath and GetRuntimePath()) or scriptPath + +-- Load and process local manifest +local localVer +local localPlatform, localBranch +local localFiles = { } +local localManXML = xml.LoadXMLFile(scriptPath.."/manifest.xml") +local localSource +if localManXML and localManXML[1].elem == "PoBVersion" then + for _, node in ipairs(localManXML[1]) do + if type(node) == "table" then + if node.elem == "Version" then + localVer = node.attrib.number + localPlatform = node.attrib.platform + localBranch = node.attrib.branch + elseif node.elem == "Source" then + if node.attrib.part == "default" then + localSource = node.attrib.url + end + elseif node.elem == "File" then + local fullPath + node.attrib.name = node.attrib.name:gsub("{space}", " ") + fullPath = scriptPath .. "/" .. node.attrib.name + localFiles[node.attrib.name] = { sha1 = node.attrib.sha1, part = node.attrib.part, platform = node.attrib.platform, fullPath = fullPath } + end + end + end +end +if not localVer or not localSource or not localBranch or not next(localFiles) then + ConPrintf("Update check failed: invalid local manifest") + return nil, "Invalid local manifest" +end +localSource = localSource:gsub("{branch}", localBranch) + +-- Download and process remote manifest +local remoteVer +local remoteFiles = { } +local remoteSources = { } +local remoteManText, errMsg = downloadFileText(localSource, "manifest.xml") +if not remoteManText then + ConPrintf("Update check failed: couldn't download version manifest") + return nil, "Couldn't download version manifest.\nReason: "..errMsg.."\nCheck your internet connectivity.\nIf you are using a proxy, specify it in Options." +end +local remoteManXML = xml.ParseXML(remoteManText) +if remoteManXML and remoteManXML[1].elem == "PoBVersion" then + for _, node in ipairs(remoteManXML[1]) do + if type(node) == "table" then + if node.elem == "Version" then + remoteVer = node.attrib.number + elseif node.elem == "Source" then + if not remoteSources[node.attrib.part] then + remoteSources[node.attrib.part] = { } + end + remoteSources[node.attrib.part][node.attrib.platform or "any"] = node.attrib.url + elseif node.elem == "File" then + if not node.attrib.platform or node.attrib.platform == localPlatform then + local fullPath + fullPath = scriptPath .. "/" .. node.attrib.name + remoteFiles[node.attrib.name] = { sha1 = node.attrib.sha1, part = node.attrib.part, platform = node.attrib.platform, fullPath = fullPath } + end + end + end + end +end +if not remoteVer or not next(remoteSources) or not next(remoteFiles) then + ConPrintf("Update check failed: invalid remote manifest") + return nil, "Invalid remote manifest" +end + +-- Build lists of files to be updated or deleted +local updateFiles = { } +for name, data in pairs(remoteFiles) do + data.name = name + local sanitizedName = name:gsub("{space}", " ") + if (not localFiles[name] or localFiles[name].sha1 ~= data.sha1) and (not localFiles[sanitizedName] or localFiles[sanitizedName].sha1 ~= data.sha1) then + table.insert(updateFiles, data) + elseif localFiles[name] then + local file = io.open(localFiles[name].fullPath, "rb") + if not file then + ConPrintf("Warning: '%s' doesn't exist, it will be re-downloaded", data.name) + table.insert(updateFiles, data) + else + local content = file:read("*a") + file:close() + if data.sha1 ~= sha1(content) and data.sha1 ~= sha1(content:gsub("\n", "\r\n")) then + ConPrintf("Warning: Integrity check on '%s' failed, it will be replaced", data.name) + table.insert(updateFiles, data) + end + end + end +end +local deleteFiles = { } +for name, data in pairs(localFiles) do + data.name = name + local unSanitizedName = name:gsub(" ", "{space}") + if not remoteFiles[name] and not remoteFiles[unSanitizedName] then + table.insert(deleteFiles, data) + end +end + +if #updateFiles == 0 and #deleteFiles == 0 then + ConPrintf("No update available.") + return "none" +end + +MakeDir("Update") +ConPrintf("Downloading update...") + +-- Download changelog +downloadFile(localSource, "changelog.txt", scriptPath.."/changelog.txt") + +-- Download files that need updating +local failedFile = false +local zipFiles = { } +for index, data in ipairs(updateFiles) do + if UpdateProgress then + UpdateProgress("Downloading %d/%d", index, #updateFiles) + end + local partSources = remoteSources[data.part] + local source = partSources[localPlatform] or partSources["any"] + source = source:gsub("{branch}", localBranch) + local fileName = scriptPath.."/Update/"..data.name:gsub("[\\/]","{slash}") + data.updateFileName = fileName + local zipName = source:match("/([^/]+%.zip)$") + if zipName then + if not zipFiles[zipName] then + ConPrintf("Downloading %s...", zipName) + local zipFileName = scriptPath.."/Update/"..zipName + downloadFile(source, "", zipFileName) + zipFiles[zipName] = lzip.open(zipFileName) + end + local zip = zipFiles[zipName] + if zip then + local zippedFile = zip:OpenFile(data.name) + if zippedFile then + local file = io.open(fileName, "wb+") + file:write(zippedFile:Read("*a")) + file:close() + zippedFile:Close() + else + ConPrintf("Couldn't extract '%s' from '%s' (extract failed)", data.name, zipName) + end + else + ConPrintf("Couldn't extract '%s' from '%s' (zip open failed)", data.name, zipName) + end + else + local skipDownload + local file = io.open(fileName, "rb") + if file then + local content = file:read("*all") + if data.sha1 == sha1(content) or data.sha1 == sha1(content:gsub("\n", "\r\n")) then + ConPrintf("Using file from previous update attempt '%s'", fileName) + skipDownload = true + end + file:close() + end + if not skipDownload then + ConPrintf("Downloading %s... (%d of %d)", data.name, index, #updateFiles) + downloadFile(source, data.name, fileName) + end + end + local file = io.open(fileName, "rb") + if not file then + failedFile = true + else + local content = file:read("*all") + if data.sha1 ~= sha1(content) and data.sha1 ~= sha1(content:gsub("\n", "\r\n")) then + ConPrintf("Hash mismatch on '%s'", fileName) + failedFile = true + end + file:close() + end +end +for name, zip in pairs(zipFiles) do + zip:Close() + os.remove(scriptPath.."/Update/"..name) +end +if failedFile then + ConPrintf("Update failed: one or more files couldn't be downloaded") + return nil, "One or more files couldn't be downloaded.\nCheck your internet connectivity,\nor try again later." +end + +-- Create new manifest +localManXML = { elem = "PoBVersion" } +table.insert(localManXML, { elem = "Version", attrib = { number = remoteVer, platform = localPlatform, branch = localBranch } }) +for part, platforms in pairs(remoteSources) do + for platform, url in pairs(platforms) do + table.insert(localManXML, { elem = "Source", attrib = { part = part, platform = platform ~= "any" and platform, url = url } }) + end +end +for name, data in pairs(remoteFiles) do + table.insert(localManXML, { elem = "File", attrib = { name = data.name, sha1 = data.sha1, part = data.part, platform = data.platform } }) +end +xml.SaveXMLFile(localManXML, scriptPath.."/Update/manifest.xml") + +-- Build list of operations to apply the update +local updateMode = "normal" +local ops = { } +for _, data in pairs(updateFiles) do + -- Ensure that the destination path of this file exists + local dirStr = "" + for dir in data.fullPath:gmatch("([^/]*/)") do + dirStr = dirStr .. dir + MakeDir(dirStr) + end + table.insert(ops, 'move "'..data.updateFileName..'" "'..data.fullPath..'"') +end +for _, data in pairs(deleteFiles) do + table.insert(ops, 'delete "'..data.fullPath..'"') +end +table.insert(ops, 'move "'..scriptPath..'/Update/manifest.xml" "'..scriptPath..'/manifest.xml"') + +-- Write operations file +local opFile = io.open(scriptPath.."/Update/opFile.txt", "w+") +opFile:write(table.concat(ops, "\n")) +opFile:close() + +ConPrintf("Update is ready.") +return updateMode diff --git a/lua/poe1/manifest.xml b/lua/poe1/manifest.xml new file mode 100644 index 0000000..8fab7d4 --- /dev/null +++ b/lua/poe1/manifest.xml @@ -0,0 +1,843 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/lua/poe2/UpdateCheck.lua b/lua/poe2/UpdateCheck.lua new file mode 100644 index 0000000..e678bc8 --- /dev/null +++ b/lua/poe2/UpdateCheck.lua @@ -0,0 +1,301 @@ +#@ +-- Path of Building +-- +-- Module: Update Check +-- Checks for updates +-- +local connectionProtocol, proxyURL = ... + +local xml = require("xml") +local sha1 = require("sha1") +local curl = require("lcurl.safe") +local lzip = require("lzip") + +local globalRetryLimit = 10 +local function downloadFileText(source, file) + for i = 1, 5 do + if i > 1 then + ConPrintf("Retrying... (%d of 5)", i) + end + local text = "" + local easy = curl.easy() + local escapedUrl = source..easy:escape(file) + easy:setopt_url(escapedUrl) + easy:setopt(curl.OPT_ACCEPT_ENCODING, "") + if connectionProtocol then + easy:setopt(curl.OPT_IPRESOLVE, connectionProtocol) + end + if proxyURL then + easy:setopt(curl.OPT_PROXY, proxyURL) + end + easy:setopt_writefunction(function(data) + text = text..data + return true + end) + local _, error = easy:perform() + easy:close() + if not error then + return text + end + ConPrintf("Download failed (%s)", error:msg()) + if globalRetryLimit == 0 or i == 5 then + return nil, error:msg() + end + globalRetryLimit = globalRetryLimit - 1 + end +end +local function downloadFile(source, file, outName) + for i = 1, 5 do + if i > 1 then + ConPrintf("Retrying... (%d of 5)", i) + end + local easy = curl.easy() + local escapedUrl = source..easy:escape(file) + easy:setopt_url(escapedUrl) + easy:setopt(curl.OPT_ACCEPT_ENCODING, "") + if connectionProtocol then + easy:setopt(curl.OPT_IPRESOLVE, connectionProtocol) + end + if proxyURL then + easy:setopt(curl.OPT_PROXY, proxyURL) + end + local file = io.open(outName, "wb+") + easy:setopt_writefunction(file) + local _, error = easy:perform() + easy:close() + file:close() + if not error then + return true + end + ConPrintf("Download failed (%s)", error:msg()) + if globalRetryLimit == 0 or i == 5 then + return nil, error:msg() + end + globalRetryLimit = globalRetryLimit - 1 + end + return true +end + +ConPrintf("Checking for update...") + +-- Use built-in helpers to obtain absolute paths without spawning a shell. +local scriptPath = (GetScriptPath and GetScriptPath()) or "." +local runtimePath = (GetRuntimePath and GetRuntimePath()) or scriptPath + +-- Load and process local manifest +local localVer +local localPlatform, localBranch +local localFiles = { } +local localManXML = xml.LoadXMLFile(scriptPath.."/manifest.xml") +local localSource +if localManXML and localManXML[1].elem == "PoBVersion" then + for _, node in ipairs(localManXML[1]) do + if type(node) == "table" then + if node.elem == "Version" then + localVer = node.attrib.number + localPlatform = node.attrib.platform + localBranch = node.attrib.branch + elseif node.elem == "Source" then + if node.attrib.part == "default" then + localSource = node.attrib.url + end + elseif node.elem == "File" then + local fullPath + node.attrib.name = node.attrib.name:gsub("{space}", " ") + fullPath = scriptPath .. "/" .. node.attrib.name + localFiles[node.attrib.name] = { sha1 = node.attrib.sha1, part = node.attrib.part, platform = node.attrib.platform, fullPath = fullPath } + end + end + end +end +if not localVer or not localSource or not localBranch or not next(localFiles) then + ConPrintf("Update check failed: invalid local manifest") + return nil, "Invalid local manifest" +end +localSource = localSource:gsub("{branch}", localBranch) + +-- Download and process remote manifest +local remoteVer +local remoteFiles = { } +local remoteSources = { } +local remoteManText, errMsg = downloadFileText(localSource, "manifest.xml") +if not remoteManText then + ConPrintf("Update check failed: couldn't download version manifest") + return nil, "Couldn't download version manifest.\nReason: "..errMsg.."\nCheck your internet connectivity.\nIf you are using a proxy, specify it in Options." +end +local remoteManXML = xml.ParseXML(remoteManText) +if remoteManXML and remoteManXML[1].elem == "PoBVersion" then + for _, node in ipairs(remoteManXML[1]) do + if type(node) == "table" then + if node.elem == "Version" then + remoteVer = node.attrib.number + elseif node.elem == "Source" then + if not remoteSources[node.attrib.part] then + remoteSources[node.attrib.part] = { } + end + remoteSources[node.attrib.part][node.attrib.platform or "any"] = node.attrib.url + elseif node.elem == "File" then + if not node.attrib.platform or node.attrib.platform == localPlatform then + local fullPath + fullPath = scriptPath .. "/" .. node.attrib.name + remoteFiles[node.attrib.name] = { sha1 = node.attrib.sha1, part = node.attrib.part, platform = node.attrib.platform, fullPath = fullPath } + end + end + end + end +end +if not remoteVer or not next(remoteSources) or not next(remoteFiles) then + ConPrintf("Update check failed: invalid remote manifest") + return nil, "Invalid remote manifest" +end + +-- Build lists of files to be updated or deleted +local updateFiles = { } +for name, data in pairs(remoteFiles) do + data.name = name + local sanitizedName = name:gsub("{space}", " ") + if (not localFiles[name] or localFiles[name].sha1 ~= data.sha1) and (not localFiles[sanitizedName] or localFiles[sanitizedName].sha1 ~= data.sha1) then + table.insert(updateFiles, data) + elseif localFiles[name] then + local file = io.open(localFiles[name].fullPath, "rb") + if not file then + ConPrintf("Warning: '%s' doesn't exist, it will be re-downloaded", data.name) + table.insert(updateFiles, data) + else + local content = file:read("*a") + file:close() + if data.sha1 ~= sha1(content) and data.sha1 ~= sha1(content:gsub("\n", "\r\n")) then + ConPrintf("Warning: Integrity check on '%s' failed, it will be replaced", data.name) + table.insert(updateFiles, data) + end + end + end +end +local deleteFiles = { } +for name, data in pairs(localFiles) do + data.name = name + local unSanitizedName = name:gsub(" ", "{space}") + if not remoteFiles[name] and not remoteFiles[unSanitizedName] then + table.insert(deleteFiles, data) + end +end + +if #updateFiles == 0 and #deleteFiles == 0 then + ConPrintf("No update available.") + return "none" +end + +MakeDir("Update") +ConPrintf("Downloading update...") + +-- Download changelog +downloadFile(localSource, "changelog.txt", scriptPath.."/changelog.txt") + +-- Download files that need updating +local failedFile = false +local zipFiles = { } +for index, data in ipairs(updateFiles) do + if UpdateProgress then + UpdateProgress("Downloading %d/%d", index, #updateFiles) + end + local partSources = remoteSources[data.part] + local source = partSources[localPlatform] or partSources["any"] + source = source:gsub("{branch}", localBranch) + local fileName = scriptPath.."/Update/"..data.name:gsub("[\\/]","{slash}") + data.updateFileName = fileName + local zipName = source:match("/([^/]+%.zip)$") + if zipName then + if not zipFiles[zipName] then + ConPrintf("Downloading %s...", zipName) + local zipFileName = scriptPath.."/Update/"..zipName + downloadFile(source, "", zipFileName) + zipFiles[zipName] = lzip.open(zipFileName) + end + local zip = zipFiles[zipName] + if zip then + local zippedFile = zip:OpenFile(data.name) + if zippedFile then + local file = io.open(fileName, "wb+") + file:write(zippedFile:Read("*a")) + file:close() + zippedFile:Close() + else + ConPrintf("Couldn't extract '%s' from '%s' (extract failed)", data.name, zipName) + end + else + ConPrintf("Couldn't extract '%s' from '%s' (zip open failed)", data.name, zipName) + end + else + local skipDownload + local file = io.open(fileName, "rb") + if file then + local content = file:read("*all") + if data.sha1 == sha1(content) or data.sha1 == sha1(content:gsub("\n", "\r\n")) then + ConPrintf("Using file from previous update attempt '%s'", fileName) + skipDownload = true + end + file:close() + end + if not skipDownload then + ConPrintf("Downloading %s... (%d of %d)", data.name, index, #updateFiles) + downloadFile(source, data.name, fileName) + end + end + local file = io.open(fileName, "rb") + if not file then + failedFile = true + else + local content = file:read("*all") + if data.sha1 ~= sha1(content) and data.sha1 ~= sha1(content:gsub("\n", "\r\n")) then + ConPrintf("Hash mismatch on '%s'", fileName) + failedFile = true + end + file:close() + end +end +for name, zip in pairs(zipFiles) do + zip:Close() + os.remove(scriptPath.."/Update/"..name) +end +if failedFile then + ConPrintf("Update failed: one or more files couldn't be downloaded") + return nil, "One or more files couldn't be downloaded.\nCheck your internet connectivity,\nor try again later." +end + +-- Create new manifest +localManXML = { elem = "PoBVersion" } +table.insert(localManXML, { elem = "Version", attrib = { number = remoteVer, platform = localPlatform, branch = localBranch } }) +for part, platforms in pairs(remoteSources) do + for platform, url in pairs(platforms) do + table.insert(localManXML, { elem = "Source", attrib = { part = part, platform = platform ~= "any" and platform, url = url } }) + end +end +for name, data in pairs(remoteFiles) do + table.insert(localManXML, { elem = "File", attrib = { name = data.name, sha1 = data.sha1, part = data.part, platform = data.platform } }) +end +xml.SaveXMLFile(localManXML, scriptPath.."/Update/manifest.xml") + +-- Build list of operations to apply the update +local updateMode = "normal" +local ops = { } +for _, data in pairs(updateFiles) do + -- Ensure that the destination path of this file exists + local dirStr = "" + for dir in data.fullPath:gmatch("([^/]*/)") do + dirStr = dirStr .. dir + MakeDir(dirStr) + end + table.insert(ops, 'move "'..data.updateFileName..'" "'..data.fullPath..'"') +end +for _, data in pairs(deleteFiles) do + table.insert(ops, 'delete "'..data.fullPath..'"') +end +table.insert(ops, 'move "'..scriptPath..'/Update/manifest.xml" "'..scriptPath..'/manifest.xml"') + +-- Write operations file +local opFile = io.open(scriptPath.."/Update/opFile.txt", "w+") +opFile:write(table.concat(ops, "\n")) +opFile:close() + +ConPrintf("Update is ready.") +return updateMode diff --git a/lua/poe2/manifest.xml b/lua/poe2/manifest.xml new file mode 100644 index 0000000..622ba62 --- /dev/null +++ b/lua/poe2/manifest.xml @@ -0,0 +1,934 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/lua/update_manifest.py b/lua/update_manifest.py new file mode 100644 index 0000000..3b0d248 --- /dev/null +++ b/lua/update_manifest.py @@ -0,0 +1,83 @@ +import argparse +import hashlib +import urllib.request +import xml.etree.ElementTree as Et +from pathlib import Path + +# Downloads the official PoB manifest file and performs the following modifications: +# - set platform and branch +# - add a new 'default' source that points to this repo +# - rename old 'default' source to 'origin' +# - remove win32 libraries and executables +# - remove font files +# - use modified UpdateCheck.lua from this repo, which is compatible with unix paths and disables the 'basic' update mode + +repo = "meehl/RustyPathOfBuilding" + + +def is_font_file(name: str) -> bool: + return name.endswith(".tga") or name.endswith(".tgf") + + +def is_tar_file(name: str) -> bool: + return name.endswith(".tar") or name.endswith(".tgf") + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--game", choices=["poe1", "poe2"], required=True) + args = parser.parse_args() + + if args.game == "poe1": + origin_url = "https://raw.githubusercontent.com/PathOfBuildingCommunity/PathOfBuilding/master/manifest.xml" + else: + origin_url = "https://raw.githubusercontent.com/PathOfBuildingCommunity/PathOfBuilding-PoE2/master/manifest.xml" + + with urllib.request.urlopen(origin_url) as f: + manifest_root = Et.fromstring(f.read().decode("utf-8")) + + for child in list(manifest_root): + if child.tag == "Version": + child.set("branch", "master") + child.set("platform", "any") + elif child.tag == "Source": + if child.get("part") == "default": + child.set("part", "origin") + + if child.get("platform") is not None: + child.attrib.pop("platform") + elif child.tag == "File": + if child.get("part") == "default": + child.set("part", "origin") + + if ( + child.get("runtime") is not None + or is_font_file(child.get("name")) + or is_tar_file(child.get("name")) + ): + manifest_root.remove(child) + + if child.get("name") == "UpdateCheck.lua": + child.set("part", "default") + + path = Path(f"../manifest/{args.game}/UpdateCheck.lua") + data = path.read_bytes() + sha1 = hashlib.sha1(data).hexdigest() + child.set("sha1", sha1) + + default_source = Et.Element( + "Source", + { + "part": "default", + "url": f"https://raw.githubusercontent.com/{repo}/main/lua/{args.game}/", + }, + ) + manifest_root.insert(1, default_source) + + tree = Et.ElementTree(manifest_root) + Et.indent(tree, "\t") + tree.write(f"./{args.game}/manifest.xml") + + +if __name__ == "__main__": + main() diff --git a/src/api.rs b/src/api.rs new file mode 100644 index 0000000..6a7ae02 --- /dev/null +++ b/src/api.rs @@ -0,0 +1,396 @@ +use std::{ + fs, + io::{Read, Write, stdout}, + path::PathBuf, + time::{SystemTime, UNIX_EPOCH}, +}; + +use anyhow::anyhow; +use directories::UserDirs; +use flate2::{ + Compression, + read::{ZlibDecoder, ZlibEncoder}, +}; +use glob::glob; +use mlua::{ + Function, IntoLua, IntoLuaMulti, Lua, MultiValue, Result as LuaResult, String as LuaString, + Table, Value, Variadic, +}; + +use crate::{ + Game, + api::{image_handle::ImageHandle, rendering::PoBString, search_handle::SearchHandle}, + context::CONTEXT, + input::{str_as_keycode, str_as_mousebutton}, + util::{change_working_directory, get_executable_dir}, +}; + +mod image_handle; +mod rendering; +mod search_handle; + +/// Register functions that can be called from lua +pub fn register_globals(lua: &Lua) -> LuaResult<()> { + let globals = lua.globals(); + globals.set("SetMainObject", lua.create_function(set_main_object)?)?; + globals.set("SetCallback", lua.create_function(set_custom_callback)?)?; + globals.set("GetCallback", lua.create_function(get_custom_callback)?)?; + globals.set("GetUserPath", lua.create_function(get_user_path)?)?; + globals.set("GetScriptPath", lua.create_function(get_script_path)?)?; + globals.set("GetRuntimePath", lua.create_function(get_runtime_path)?)?; + globals.set("ConPrintf", lua.create_function(console_printf)?)?; + globals.set("ConExecute", lua.create_function(console_execute)?)?; + globals.set("ConClear", lua.create_function(console_clear)?)?; + globals.set("ConPrintTable", lua.create_function(console_print_table)?)?; + globals.set("PCall", lua.create_function(protected_call)?)?; + globals.set("GetTime", lua.create_function(get_time)?)?; + globals.set("MakeDir", lua.create_function(make_dir)?)?; + globals.set("StripEscapes", lua.create_function(strip_escapes)?)?; + globals.set("Inflate", lua.create_function(inflate)?)?; + globals.set("Deflate", lua.create_function(deflate)?)?; + globals.set("NewFileSearch", lua.create_function(new_search_handle)?)?; + globals.set("GetWorkDir", lua.create_function(get_work_dir)?)?; + globals.set("SetWorkDir", lua.create_function(set_work_dir)?)?; + globals.set("Copy", lua.create_function(copy)?)?; + globals.set("Paste", lua.create_function(paste)?)?; + globals.set("GetScreenSize", lua.create_function(get_screen_size)?)?; + globals.set("GetScreenScale", lua.create_function(get_screen_scale)?)?; + globals.set("GetCursorPos", lua.create_function(get_cursor_pos)?)?; + globals.set("IsKeyDown", lua.create_function(is_key_down)?)?; + globals.set("LoadModule", lua.create_function(load_module)?)?; + globals.set("PLoadModule", lua.create_function(protected_load_module)?)?; + globals.set("NewImageHandle", lua.create_function(new_image_handle)?)?; + globals.set("SetWindowTitle", lua.create_function(set_window_title)?)?; + globals.set("Restart", lua.create_function(restart)?)?; + globals.set("OpenURL", lua.create_function(open_url)?)?; + globals.set("RenderInit", lua.create_function(render_init)?)?; + + // NOTE: not used by PoB + let get_draw_layer = |_: &Lua, ()| -> LuaResult<()> { unimplemented!() }; + let set_blend_mode = |_: &Lua, ()| -> LuaResult<()> { unimplemented!() }; + let get_async_count = |_: &Lua, ()| -> LuaResult<()> { unimplemented!() }; + let set_cursor_pos = |_: &Lua, ()| -> LuaResult<()> { unimplemented!() }; + let show_cursor = |_: &Lua, ()| -> LuaResult<()> { unimplemented!() }; + let set_clear_color = |_: &Lua, ()| -> LuaResult<()> { unimplemented!() }; + globals.set("GetDrawLayer", lua.create_function(get_draw_layer)?)?; + globals.set("SetBlendMode", lua.create_function(set_blend_mode)?)?; + globals.set("GetAsyncCount", lua.create_function(get_async_count)?)?; + globals.set("SetCursorPos", lua.create_function(set_cursor_pos)?)?; + globals.set("ShowCursor", lua.create_function(show_cursor)?)?; + globals.set("SetClearColor", lua.create_function(set_clear_color)?)?; + + rendering::register_globals(lua)?; + + Ok(()) +} + +// During initialization, PoB calls `SetMainObject` with a callback table. +// Functions defined in this table are used to call back into Lua from Rust. +// Custom callback functions can be added with `SetCallback` and retrieved +// with `GetCallback`. +const CALLBACK_REGISTRY_NAME: &str = "uicallbacks"; + +pub fn get_callback(lua: &Lua, name: &str) -> LuaResult { + let callback_table: Table = lua.named_registry_value(CALLBACK_REGISTRY_NAME)?; + let callback_function: Value = callback_table.get(name)?; + if callback_function.is_function() { + // function defined through `SetCallback` + return Ok(callback_function.as_function().unwrap().clone()); + } else { + // look for function in `MainObject` + let main_object: Table = callback_table.get("MainObject")?; + let callback_function: Value = main_object.get(name)?; + if callback_function.is_function() { + // these functions expect `MainObject` as first argument so we bind it here + return callback_function.as_function().unwrap().bind(main_object); + } + } + Err(anyhow::anyhow!("Function '{}' not found", name).into()) +} + +fn set_main_object(l: &Lua, main_object: Table) -> LuaResult<()> { + let callback_table = l.create_table()?; + callback_table.set("MainObject", main_object)?; + l.set_named_registry_value(CALLBACK_REGISTRY_NAME, callback_table)?; + Ok(()) +} + +fn set_custom_callback(l: &Lua, (name, func): (String, Function)) -> LuaResult<()> { + let callback_table: Table = l.named_registry_value(CALLBACK_REGISTRY_NAME)?; + callback_table.set(name, func)?; + Ok(()) +} + +fn get_custom_callback(l: &Lua, name: String) -> LuaResult { + let callback_table: Table = l.named_registry_value(CALLBACK_REGISTRY_NAME)?; + let callback_function: Function = callback_table.get(name)?; + Ok(callback_function) +} + +fn get_user_path(_: &Lua, _: ()) -> LuaResult> { + let user_dirs = match UserDirs::new() { + Some(user_dirs) => user_dirs, + None => return Ok(Err(anyhow!("Failed to retrieve user's home directory"))), + }; + + match user_dirs.document_dir() { + Some(docs_dir) => Ok(Ok(docs_dir.canonicalize().unwrap())), + None => Ok(Err(anyhow!( + "Failed to retrieve user's documents directory" + ))), + } +} + +// parent directory of Launch.lua script +fn get_script_path(_: &Lua, _: ()) -> LuaResult { + Ok(Game::script_dir()) +} + +// parent directory of executable +fn get_runtime_path(_: &Lua, _: ()) -> LuaResult { + match get_executable_dir() { + Ok(exe_path) => Ok(exe_path), + Err(_) => Ok(PathBuf::new()), + } +} + +fn console_printf(l: &Lua, (fmt, args): (String, MultiValue)) -> LuaResult<()> { + // uses lua's builtin string.format function + let string_module: Table = l.globals().get("string")?; + let format_func: Function = string_module.get("format")?; + let formatted_string = format_func.call::((fmt, args))?; + println!("{formatted_string}"); + Ok(()) +} + +fn console_execute(_l: &Lua, _cmd: String) -> LuaResult<()> { + Ok(()) +} + +fn console_clear(_l: &Lua, _: ()) -> LuaResult<()> { + Ok(()) +} + +fn print_table(table: &Table, indent: usize, recursive: bool) -> LuaResult<()> { + let mut lock = stdout().lock(); + writeln!(lock, "{{")?; + for pair in table.pairs::() { + let inner_ind = indent + 2; + let (key, value) = pair?; + + if key.is_string() { + write!(lock, "{0:>1$}\"{2}\" = ", "", inner_ind, key.to_string()?,)?; + } else { + write!(lock, "{0:>1$}{2} = ", "", inner_ind, key.to_string()?,)?; + } + + if value.is_table() { + if recursive { + print_table(value.as_table().unwrap(), indent + 2, recursive)?; + } else { + writeln!(lock, "{}", value.to_string()?)?; + } + } else if value.is_string() { + writeln!(lock, "\"{}\"", value.to_string()?)?; + } else { + writeln!(lock, "{}", value.to_string()?)?; + } + } + writeln!(lock, "{0:>1$}}}", "", indent)?; + Ok(()) +} + +fn console_print_table(_l: &Lua, (table, no_recursive): (Table, Option)) -> LuaResult<()> { + print_table(&table, 0, !no_recursive.unwrap_or(true))?; + Ok(()) +} + +fn protected_call(l: &Lua, (func, args): (Function, MultiValue)) -> LuaResult { + match func.call::(args) { + // callers expect first return value to be Nil on success + Ok(return_values) => Ok(std::iter::once(Value::Nil).chain(return_values).collect()), + // otherwise it is set to error message. + Err(err) => Ok(err.to_string().into_lua_multi(l)?), + } +} + +fn get_time(_l: &Lua, _: ()) -> LuaResult { + Ok(SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_millis()) +} + +fn make_dir(l: &Lua, path: String) -> LuaResult { + match fs::create_dir_all(path) { + // callers expect first return value to be true on success + Ok(_) => Ok(Value::Boolean(true).into_lua_multi(l)?), + // otherwise it is set to Nil and second return value is set to error msg + Err(err) => Ok((Value::Nil, err.to_string()).into_lua_multi(l)?), + } +} + +fn strip_escapes(_: &Lua, text: String) -> LuaResult { + Ok(PoBString(&text).strip_escapes()) +} + +fn inflate(l: &Lua, compressed: LuaString) -> LuaResult { + let compressed_bytes = &compressed.as_bytes()[..]; + + // prevent decompression of input larger than 128MiB + if compressed_bytes.len() > (128 << 20) { + return Ok((Value::Nil, "Input larger than 128 MiB") + .into_lua_multi(l) + .unwrap()); + } + + let mut decoder = ZlibDecoder::new(compressed_bytes); + let mut decompressed = String::new(); + match decoder.read_to_string(&mut decompressed) { + Ok(_) => Ok(decompressed.into_lua_multi(l).unwrap()), + Err(e) => Ok((Value::Nil, e.to_string()).into_lua_multi(l).unwrap()), + } +} + +fn deflate(l: &Lua, uncompressed: LuaString) -> LuaResult { + let uncompressed_bytes = &uncompressed.as_bytes()[..]; + + // prevent compression of input larger than 128MiB + if uncompressed_bytes.len() > (128 << 20) { + return Ok((Value::Nil, "Input larger than 128 MiB") + .into_lua_multi(l) + .unwrap()); + } + + let mut encoder = ZlibEncoder::new(uncompressed_bytes, Compression::fast()); + let mut compressed = String::new(); + match encoder.read_to_string(&mut compressed) { + Ok(_) => Ok(compressed.into_lua_multi(l).unwrap()), + Err(e) => Ok((Value::Nil, e.to_string()).into_lua_multi(l).unwrap()), + } +} + +fn new_search_handle( + l: &Lua, + (pattern, find_directories): (String, Option), +) -> LuaResult { + if let Ok(paths) = glob(&pattern) { + let directories_only = find_directories.is_some_and(|x| x); + let mut handle = SearchHandle::new(paths, directories_only); + // try to get the first result + handle.next(); + // only return a handle if at least one file/directory is found + if handle.current.is_some() { + return handle.into_lua(l); + } + }; + Ok(Value::Nil) +} + +fn get_work_dir(_: &Lua, _: ()) -> LuaResult { + Ok(CONTEXT.with_borrow(|ctx| ctx.current_working_dir().to_path_buf())) +} + +// NOTE: unused +fn set_work_dir(_: &Lua, path: String) -> LuaResult<()> { + CONTEXT.with_borrow_mut(|ctx| ctx.set_current_working_dir(path.into())); + Ok(()) +} + +fn copy(_: &Lua, text: String) -> LuaResult<()> { + CONTEXT.with_borrow_mut(|ctx| { + ctx.clipboard + .set_text(text) + .map_err(|e| anyhow::anyhow!("{}", e)) + })?; + Ok(()) +} + +fn paste(_: &Lua, _: ()) -> LuaResult { + let text = CONTEXT.with_borrow_mut(|ctx| { + ctx.clipboard + .get_text() + .map_err(|e| anyhow::anyhow!("{}", e)) + })?; + Ok(text) +} + +// NOTE: needs to return physical size if this MR gets merged: +// https://github.com/PathOfBuildingCommunity/PathOfBuilding-PoE2/pull/1420 +fn get_screen_size(_: &Lua, _: ()) -> LuaResult<(u32, u32)> { + let size = CONTEXT.with_borrow(|ctx| ctx.screen_size_logical()); + Ok((size.width, size.height)) +} + +fn get_screen_scale(_: &Lua, _: ()) -> LuaResult { + Ok(CONTEXT.with_borrow(|ctx| ctx.pixels_per_point() as f32)) +} + +fn get_cursor_pos(_: &Lua, _: ()) -> LuaResult<(u32, u32)> { + let pos = CONTEXT.with_borrow(|ctx| ctx.mouse_pos_logical()); + Ok((pos.x as u32, pos.y as u32)) +} + +fn is_key_down(_: &Lua, key_name: String) -> LuaResult { + if let Some(code) = str_as_keycode(&key_name) { + Ok(CONTEXT.with_borrow(|ctx| ctx.input_state.key_pressed(code))) + } else if let Some(button) = str_as_mousebutton(&key_name) { + Ok(CONTEXT.with_borrow(|ctx| ctx.input_state.mouse_pressed(button))) + } else { + Ok(false) + } +} + +fn load_module(l: &Lua, (name, args): (String, MultiValue)) -> LuaResult { + let mut module_path = Game::script_dir().join(name); + if module_path.extension().is_none() { + module_path.set_extension("lua"); + } + + change_working_directory(Game::script_dir().as_path())?; + let result = l.load(module_path).call::(args); + CONTEXT.with_borrow(|ctx| change_working_directory(ctx.current_working_dir()))?; + result +} + +fn protected_load_module(l: &Lua, (name, args): (String, MultiValue)) -> LuaResult { + let mut module_path = Game::script_dir().join(name); + if module_path.extension().is_none() { + module_path.set_extension("lua"); + } + + change_working_directory(Game::script_dir().as_path())?; + let result = match l.load(module_path).call::(args) { + // on success, callers expect a Nil followed by return values + Ok(res) => Ok(std::iter::once(Value::Nil).chain(res).collect()), + // otherwise it is set to error message. + Err(err) => Ok(err.to_string().into_lua_multi(l)?), + }; + CONTEXT.with_borrow(|ctx| change_working_directory(ctx.current_working_dir()))?; + result +} + +fn new_image_handle(_: &Lua, _: ()) -> LuaResult { + Ok(ImageHandle::Unloaded) +} + +fn set_window_title(_: &Lua, title: String) -> LuaResult<()> { + CONTEXT.with_borrow(|ctx| ctx.set_window_title(&title)); + Ok(()) +} + +fn restart(_: &Lua, _: ()) -> LuaResult<()> { + CONTEXT.with_borrow_mut(|ctx| ctx.needs_restart = true); + Ok(()) +} + +fn open_url(l: &Lua, url: String) -> LuaResult { + match open::that(url) { + Ok(_) => Ok(().into_lua_multi(l)?), + Err(_) => Ok("Unable to open url!".into_lua_multi(l)?), + } +} + +fn render_init(_: &Lua, _features: Variadic) -> LuaResult<()> { + Ok(()) +} diff --git a/src/api/image_handle.rs b/src/api/image_handle.rs new file mode 100644 index 0000000..d3cde06 --- /dev/null +++ b/src/api/image_handle.rs @@ -0,0 +1,94 @@ +use mlua::{MultiValue, UserData}; + +use crate::{ + context::CONTEXT, + renderer::textures::{TextureHandle, TextureOptions}, +}; + +#[derive(Clone)] +pub enum ImageHandle { + Loaded(TextureHandle), + Unloaded, +} + +impl UserData for ImageHandle { + fn add_methods>(methods: &mut M) { + methods.add_method_mut( + "Load", + |_, this, (image_path, flags): (String, MultiValue)| { + let mut is_async = false; + let mut options = TextureOptions::LINEAR_REPEAT; + + for flag in flags.iter() { + if let Some(flag) = flag.as_string() { + match flag.to_string_lossy().as_str() { + "CLAMP" => options.wrap_mode = wgpu::AddressMode::ClampToEdge, + "NEAREST" => options.magnification = wgpu::FilterMode::Nearest, + "ASYNC" => is_async = true, + "MIPMAP" => options.generate_mipmaps = true, + _ => {} + } + } + } + + match this { + // replace image data if already allocated + ImageHandle::Loaded(texture_handle) => { + CONTEXT.with_borrow(|ctx| { + // in case of error, stay loaded with current texture + let _ = ctx.texture_manager.update_texture( + texture_handle.id(), + image_path, + options, + is_async, + ); + }); + } + // create new texture handle + ImageHandle::Unloaded => { + CONTEXT.with_borrow(|ctx| { + if let Ok(handle) = ctx + .texture_manager + .load_texture(image_path, options, is_async) + { + *this = ImageHandle::Loaded(handle); + } + }); + } + } + Ok(()) + }, + ); + + methods.add_method_mut("Unload", |_, this, ()| { + match this { + ImageHandle::Loaded(_) => { + // dropping the handle frees the texture + *this = ImageHandle::Unloaded; + } + ImageHandle::Unloaded => {} + } + Ok(()) + }); + + methods.add_method("IsValid", |_, this, ()| { + Ok(matches!(this, ImageHandle::Loaded(_))) + }); + + methods.add_method("IsLoading", |_, this, ()| match &this { + ImageHandle::Loaded(texture_handle) => { + let size = texture_handle.size(); + Ok(size[0] == 0) + } + ImageHandle::Unloaded => Ok(true), + }); + + methods.add_method("ImageSize", |_, this, ()| match &this { + ImageHandle::Loaded(texture_handle) => { + let size = texture_handle.size(); + Ok((size[0], size[1])) + } + ImageHandle::Unloaded => Ok((0, 0)), + }); + } +} diff --git a/src/api/rendering.rs b/src/api/rendering.rs new file mode 100644 index 0000000..32123fa --- /dev/null +++ b/src/api/rendering.rs @@ -0,0 +1,621 @@ +use crate::{ + api::image_handle::ImageHandle, + color::Srgba, + context::CONTEXT, + dpi::Uv, + fonts::{Alignment, LayoutJob}, + math::{Point, Quad, Rect, Size}, +}; +use core::ffi::{c_int, c_void}; +use mlua::{ + LightUserData, Lua, Result as LuaResult, UserDataRefMut, Value, + ffi::{self}, +}; +use regex::Regex; +use std::sync::LazyLock; + +pub fn register_globals(lua: &Lua) -> LuaResult<()> { + let globals = lua.globals(); + // rendering functions + // NOTE: unfortunately, mlua's conversion of function arguments adds a lot of + // overhead. this is very noticeable for the draw functions which can be called + // thousands of times per frame. C functions are used to get raw access to + // the lua stack without the overhead. + unsafe { globals.set("SetDrawColor", lua.create_c_function(set_draw_color)?)? }; + unsafe { globals.set("SetViewport", lua.create_c_function(set_viewport)?)? }; + unsafe { + globals.set("SetDrawLayer", lua.create_c_function(set_draw_layer)?)?; + } + unsafe { globals.set("DrawImage", lua.create_c_function(draw_image)?)? }; + unsafe { globals.set("DrawImageQuad", lua.create_c_function(draw_image_quad)?)? }; + unsafe { + globals.set("DrawString", lua.create_c_function(draw_string)?)?; + } + unsafe { + globals.set("DrawStringWidth", lua.create_c_function(get_string_width)?)?; + } + globals.set( + "DrawStringCursorIndex", + lua.create_function_mut(get_index_at_cur)?, + )?; + + // NOTE: mlua wraps UserData in a special way to maintain safety guarantees. + // This wrapper is not exposed by mlua, making it difficult to access the + // underlying user data from within C functions. + // This is a helper function that unwraps an ImageHandle and returns a pointer to it + // See: https://github.com/mlua-rs/mlua/discussions/545#discussioncomment-12530475 + let get_img_handle = lua.create_function(|_, mut ud: UserDataRefMut| { + let vec: *mut ImageHandle = &mut *ud; + Ok(Value::LightUserData(LightUserData(vec as *mut c_void))) + })?; + lua.set_named_registry_value("get_img_handle", get_img_handle)?; + Ok(()) +} + +macro_rules! str_from_stack { + ($s:ident, $i:expr) => { + unsafe { + let mut size = 0; + let data = ffi::luaL_checklstring($s, $i, &mut size); + let bytes = std::slice::from_raw_parts(data as *const u8, size); + std::str::from_utf8_unchecked(bytes) + } + }; +} + +macro_rules! f32_from_stack { + ($s:ident, $i:expr) => { + unsafe { ffi::luaL_checknumber($s, $i) } as f32 + }; +} + +macro_rules! i32_from_stack { + ($s:ident, $i:expr) => { + unsafe { ffi::luaL_checkinteger($s, $i) } as i32 + }; +} + +macro_rules! img_handle_from_stack { + ($s:ident, $i:expr) => { + unsafe { + match ffi::lua_type($s, $i) { + ffi::LUA_TNIL => None, + ffi::LUA_TUSERDATA => { + let img_handle = lua_toimghandle($s, $i); + if !img_handle.is_null() { + if let ImageHandle::Loaded(ref handle) = *img_handle { + Some(handle.id()) + } else { + None + } + } else { + None + } + } + t => panic!("Expected Nil or ImageHandle, got {:?}", t), + } + } + }; +} + +unsafe extern "C" fn lua_toimghandle(state: *mut ffi::lua_State, idx: c_int) -> *mut ImageHandle { + unsafe { + let idx = ffi::lua_absindex(state, idx); + ffi::lua_getfield(state, ffi::LUA_REGISTRYINDEX, c"get_img_handle".as_ptr()); + ffi::lua_pushvalue(state, idx); + let img_handle = match ffi::lua_pcall(state, 1, 1, 0) { + ffi::LUA_OK => ffi::lua_touserdata(state, -1) as *mut ImageHandle, + _ => std::ptr::null_mut(), + }; + ffi::lua_pop(state, 1); + img_handle + } +} + +unsafe extern "C-unwind" fn set_draw_color(state: *mut ffi::lua_State) -> c_int { + //profiling::scope!("set_draw_color"); + + let nargs = unsafe { ffi::lua_gettop(state) }; + match nargs { + // escape_code + 1 => { + let esc_str = str_from_stack!(state, -nargs); + let color = Srgba::from_escape_code(esc_str); + CONTEXT.with_borrow_mut(|ctx| ctx.set_draw_color(color)); + } + // rgb + 3 => { + let r = f32_from_stack!(state, -nargs); + let g = f32_from_stack!(state, -nargs + 1); + let b = f32_from_stack!(state, -nargs + 2); + let color = Srgba::new_f32(r, g, b, 1.0); + CONTEXT.with_borrow_mut(|ctx| ctx.set_draw_color(color)); + } + // rgba + 4 => { + let r = f32_from_stack!(state, -nargs); + let g = f32_from_stack!(state, -nargs + 1); + let b = f32_from_stack!(state, -nargs + 2); + let a = f32_from_stack!(state, -nargs + 3); + let color = Srgba::new_f32(r, g, b, a); + CONTEXT.with_borrow_mut(|ctx| ctx.set_draw_color(color)); + } + _ => panic!("Unexpected number of arguments"), + }; + + 0 +} + +unsafe extern "C-unwind" fn set_viewport(state: *mut ffi::lua_State) -> c_int { + //profiling::scope!("set_viewport"); + + let nargs = unsafe { ffi::lua_gettop(state) }; + match nargs { + 0 => CONTEXT.with_borrow_mut(|ctx| ctx.reset_viewport()), + 4 => { + let x = f32_from_stack!(state, -nargs); + let y = f32_from_stack!(state, -nargs + 1); + let w = f32_from_stack!(state, -nargs + 2); + let h = f32_from_stack!(state, -nargs + 3); + let rect = Rect::from_origin_and_size(Point::new(x, y), Size::new(w, h)); + CONTEXT.with_borrow_mut(|ctx| ctx.set_viewport(rect)); + } + _ => panic!("Unexpected number of arguments"), + }; + + 0 +} + +unsafe extern "C-unwind" fn set_draw_layer(state: *mut ffi::lua_State) -> c_int { + //profiling::scope!("set_draw_layer"); + + let nargs = unsafe { ffi::lua_gettop(state) }; + + match nargs { + 1 => { + let layer = i32_from_stack!(state, -nargs); + CONTEXT.with_borrow_mut(|ctx| ctx.set_draw_layer(layer, 0)); + } + 2 => { + let layer = match unsafe { ffi::lua_type(state, -nargs) } { + ffi::LUA_TNIL => None, + ffi::LUA_TNUMBER => { + let layer = i32_from_stack!(state, -nargs); + Some(layer) + } + t => panic!("Expected Nil or Number, got {:?}", t), + }; + let sublayer = i32_from_stack!(state, -nargs + 1); + if let Some(layer) = layer { + CONTEXT.with_borrow_mut(|ctx| ctx.set_draw_layer(layer, sublayer)); + } else { + CONTEXT.with_borrow_mut(|ctx| ctx.set_draw_sublayer(sublayer)); + } + } + _ => panic!("Unexpected number of arguments"), + }; + + 0 +} + +unsafe extern "C-unwind" fn draw_image(state: *mut ffi::lua_State) -> c_int { + //profiling::scope!("draw_image"); + + let nargs = unsafe { ffi::lua_gettop(state) }; + if !matches!(nargs, 5 | 6 | 7 | 9 | 10 | 11) { + panic!("Unexpected number of arguments"); + } + + #[allow(clippy::manual_range_patterns)] + let parse_uv = matches!(nargs, 9 | 10 | 11); + let parse_layer_idx = matches!(nargs, 6 | 7 | 10 | 11); + + let texture_id = img_handle_from_stack!(state, -nargs); + + // left, top, width, height + let x = f32_from_stack!(state, -nargs + 1); + let y = f32_from_stack!(state, -nargs + 2); + let w = f32_from_stack!(state, -nargs + 3); + let h = f32_from_stack!(state, -nargs + 4); + let rect = Rect::from_origin_and_size(Point::new(x, y), Size::new(w, h)); + + // u1, v1, u2, v2 + let mut i = 5; + let uv = if parse_uv { + let u1 = f32_from_stack!(state, -nargs + i); + let v1 = f32_from_stack!(state, -nargs + i + 1); + let u2 = f32_from_stack!(state, -nargs + i + 2); + let v2 = f32_from_stack!(state, -nargs + i + 3); + i += 4; + Rect::new(Point::new(u1, v1), Point::new(u2, v2)) + } else { + Rect::default_uv() + }; + + let layer_idx = if parse_layer_idx { + let layer_idx = i32_from_stack!(state, -nargs + i); + (layer_idx - 1) as u32 + } else { + 0 + }; + + CONTEXT.with_borrow_mut(|ctx| ctx.draw_rect(texture_id, rect, uv, layer_idx)); + + 0 +} + +unsafe extern "C-unwind" fn draw_image_quad(state: *mut ffi::lua_State) -> c_int { + //profiling::scope!("draw_image_quad", format!("args: {:?}", args)); + + let nargs = unsafe { ffi::lua_gettop(state) }; + if !matches!(nargs, 9 | 10 | 11 | 17 | 18 | 19) { + panic!("Unexpected number of arguments"); + } + + #[allow(clippy::manual_range_patterns)] + let parse_uv = matches!(nargs, 17 | 18 | 19); + let parse_layer_idx = matches!(nargs, 10 | 11 | 18 | 19); + + let texture_id = img_handle_from_stack!(state, -nargs); + + // x1, y1, x2, y2, ... + let x1 = f32_from_stack!(state, -nargs + 1); + let y1 = f32_from_stack!(state, -nargs + 2); + let x2 = f32_from_stack!(state, -nargs + 3); + let y2 = f32_from_stack!(state, -nargs + 4); + let x3 = f32_from_stack!(state, -nargs + 5); + let y3 = f32_from_stack!(state, -nargs + 6); + let x4 = f32_from_stack!(state, -nargs + 7); + let y4 = f32_from_stack!(state, -nargs + 8); + let quad = Quad::new( + Point::new(x1, y1), + Point::new(x2, y2), + Point::new(x3, y3), + Point::new(x4, y4), + ); + + // u1, v1, u2, v2, ... + let mut i = 9; + let uv = if parse_uv { + let u1 = f32_from_stack!(state, -nargs + i); + let v1 = f32_from_stack!(state, -nargs + i + 1); + let u2 = f32_from_stack!(state, -nargs + i + 2); + let v2 = f32_from_stack!(state, -nargs + i + 3); + let u3 = f32_from_stack!(state, -nargs + i + 4); + let v3 = f32_from_stack!(state, -nargs + i + 5); + let u4 = f32_from_stack!(state, -nargs + i + 6); + let v4 = f32_from_stack!(state, -nargs + i + 7); + i += 8; + Quad::new( + Point::new(u1, v1), + Point::new(u2, v2), + Point::new(u3, v3), + Point::new(u4, v4), + ) + } else { + Quad::default_uv() + }; + + let layer_idx = if parse_layer_idx { + let layer_idx = i32_from_stack!(state, -nargs + i); + (layer_idx - 1) as u32 + } else { + 0 + }; + + CONTEXT.with_borrow_mut(|ctx| ctx.draw_quad(texture_id, quad, uv, layer_idx)); + + 0 +} + +unsafe extern "C-unwind" fn draw_string(state: *mut ffi::lua_State) -> c_int { + //profiling::scope!("draw_string"); + + let nargs = unsafe { ffi::lua_gettop(state) }; + + let x = f32_from_stack!(state, -nargs); + let y = f32_from_stack!(state, -nargs + 1); + let alignment = str_from_stack!(state, -nargs + 2); + let line_height = i32_from_stack!(state, -nargs + 3); + let font_type = str_from_stack!(state, -nargs + 4); + let text = str_from_stack!(state, -nargs + 5); + + let alignment = match alignment.parse::() { + Ok(alignment) => alignment, + Err(_) => panic!("Invalid alignment"), + }; + let font_type = match font_type.parse::() { + Ok(font_type) => font_type, + Err(_) => panic!("Invalid font type"), + }; + + let mut position = Point::new(x, y); + let mut is_absolute_position = false; + CONTEXT.with_borrow_mut(|ctx| { + // the position needs to be adjusted for some alignments to match PoBs behavior + let screen_size = ctx.screen_size_logical(); + let halign = match alignment { + PoBTextAlignment::Left => Alignment::Min, + PoBTextAlignment::Center => { + position.x += screen_size.width as f32 / 2.0; + is_absolute_position = true; + Alignment::Center + } + PoBTextAlignment::Right => { + position.x = screen_size.width as f32 - position.x; + is_absolute_position = true; + Alignment::Max + } + PoBTextAlignment::CenterX => Alignment::Center, + PoBTextAlignment::RightX => Alignment::Max, + }; + + let current_draw_color = ctx.get_draw_color(); + let job = build_layout_job( + text, + current_draw_color, + font_type, + line_height, + Some(halign), + ); + + // NOTE: color escape codes modify the current draw color. + // set current draw color to color of last segment to match PoB's behavior + if let Some(last_segment) = job.segments.last() { + ctx.set_draw_color(last_segment.color); + } + + ctx.draw_text(position, job, is_absolute_position); + }); + + 0 +} + +unsafe extern "C-unwind" fn get_string_width(state: *mut ffi::lua_State) -> c_int { + //profiling::scope!("get_string_width"); + + let nargs = unsafe { ffi::lua_gettop(state) }; + + let line_height = i32_from_stack!(state, -nargs); + let font_type = str_from_stack!(state, -nargs + 1); + let text = str_from_stack!(state, -nargs + 2); + + let font_type = match font_type.parse::() { + Ok(font_type) => font_type, + Err(_) => panic!("Invalid font type"), + }; + + let job = build_layout_job(text, Srgba::WHITE, font_type, line_height, None); + let width = CONTEXT.with_borrow_mut(|ctx| ctx.get_text_width(job)); + + unsafe { ffi::lua_pushnumber(state, width as f64) }; + 1 +} + +fn get_index_at_cur( + _: &Lua, + (line_height, font_type, text, cur_x, cur_y): (i32, String, String, f32, f32), +) -> LuaResult { + //profiling::scope!("get_char_index_at_cur"); + + let font_type = font_type.parse::()?; + + let job = build_layout_job(&text, Srgba::WHITE, font_type, line_height, None); + let index = + CONTEXT.with_borrow_mut(|ctx| ctx.get_text_index_at_cursor(job, Point::new(cur_x, cur_y))); + + // convert to lua's 1-based indexing + Ok(index + 1) +} + +pub static ESCAPE_STR_REGEX: LazyLock = + LazyLock::new(|| Regex::new(r"\^(?[0-9])|\^[x|X](?[0-9A-Fa-f]{6})").unwrap()); + +fn build_layout_job<'a>( + text: &'a str, + current_color: Srgba, + font_type: PoBFontType, + line_height: i32, + alignment: Option, +) -> LayoutJob<'a> { + let mut font_weight = None; + let font_family = match font_type { + PoBFontType::Fixed => parley::GenericFamily::Monospace, + PoBFontType::Var => parley::GenericFamily::SansSerif, + PoBFontType::VarBold => { + font_weight = Some(700.0); + parley::GenericFamily::SansSerif + } + }; + + // TODO: check how PoB determines font size + let font_size = (line_height - 2).clamp(11, 32) as f32; + + let mut job = LayoutJob::new( + font_family, + font_size, + line_height as f32, + alignment, + font_weight, + ); + + for (color, segment) in PoBString(text).into_iter() { + job.append(segment, color.unwrap_or(current_color)); + } + + job +} + +// PoB strings can contain escape codes that affect the color of subsequent text +pub struct PoBString<'a>(pub &'a str); + +impl<'a> PoBString<'a> { + pub fn strip_escapes(&self) -> String { + ESCAPE_STR_REGEX.replace_all(self.0, "").to_string() + } +} + +type ColoredSegment<'a> = (Option, &'a str); + +impl<'a> IntoIterator for PoBString<'a> { + type Item = ColoredSegment<'a>; + type IntoIter = PoBStringSegmentIterator<'a>; + + fn into_iter(self) -> Self::IntoIter { + PoBStringSegmentIterator::new(self.0) + } +} + +// Iterates over colored segments +pub struct PoBStringSegmentIterator<'a> { + haystack: &'a str, + captures: std::iter::Peekable>, + is_first: bool, + is_done: bool, +} + +impl<'a> PoBStringSegmentIterator<'a> { + fn new(haystack: &'a str) -> Self { + let captures = ESCAPE_STR_REGEX.captures_iter(haystack).peekable(); + Self { + haystack, + captures, + is_first: true, + is_done: false, + } + } +} + +impl<'a> Iterator for PoBStringSegmentIterator<'a> { + type Item = ColoredSegment<'a>; + + fn next(&mut self) -> Option { + let is_first = core::mem::replace(&mut self.is_first, false); + + match self.captures.peek() { + Some(capture) => { + let code_start = capture.get(0).unwrap().start(); + let code_end = capture.get(0).unwrap().end(); + + // string didn't start with an escape code. + // return text up to first code without color. + if is_first && code_start > 0 { + return Some((None, &self.haystack[..code_start])); + } + + let escape_str = capture.get(0).unwrap().as_str(); + let color = Some(Srgba::from_escape_code(escape_str)); + + let _ = self.captures.next(); // pop current code to peek the next one + match self.captures.peek() { + Some(next_code) => { + // found another escape code. return text up the next code + let next_code_start = next_code.get(0).unwrap().start(); + Some((color, &self.haystack[code_end..next_code_start])) + } + None => { + // no additional escape codes found. return rest of string + self.is_done = true; + Some((color, &self.haystack[code_end..])) + } + } + } + None => { + if self.is_done { + None + } else { + // string doesn't contain any escape codes. + // return entire string without color + self.is_done = true; + Some((None, self.haystack)) + } + } + } + } +} + +// PoB's text alignment is weird +#[derive(Clone, Copy, Debug)] +enum PoBTextAlignment { + // left-aligned, x coordinate describes top-left corner + Left, + // centered in screen space, x coordinate describes offset of text center + // from screen center. positive values of x move text to right, negative to left. + Center, + // right-aligned in screen space, x coordinate describes distance from right edge + // of text to right edge of screen. positive values move text further to left. + Right, + // makes text centered around position, i.e. position.x = horizontal center of text + CenterX, + // makes text right-aligned to position, i.e. position.x = right edge of text + RightX, +} + +impl std::str::FromStr for PoBTextAlignment { + type Err = anyhow::Error; + + fn from_str(s: &str) -> Result { + match s { + "LEFT" => Ok(Self::Left), + "CENTER" => Ok(Self::Center), + "RIGHT" => Ok(Self::Right), + "CENTER_X" => Ok(Self::CenterX), + "RIGHT_X" => Ok(Self::RightX), + _ => Err(anyhow::anyhow!( + "'{}' is not a valid TextFontType variant", + s + )), + } + } +} + +#[derive(Clone, Copy, Debug)] +enum PoBFontType { + Fixed, + Var, + VarBold, +} + +impl std::str::FromStr for PoBFontType { + type Err = anyhow::Error; + + fn from_str(s: &str) -> Result { + match s { + "FIXED" => Ok(Self::Fixed), + "VAR" => Ok(Self::Var), + "VAR BOLD" => Ok(Self::VarBold), + _ => Err(anyhow::anyhow!( + "'{}' is not a valid TextFontType variant", + s + )), + } + } +} + +impl Srgba { + fn from_escape_code(escape_str: &str) -> Srgba { + if let Some(caps) = ESCAPE_STR_REGEX.captures(escape_str) { + if let Some(idx) = caps.name("idx") { + return match idx.as_str() { + "0" => Srgba::from_rgb(0, 0, 0), //black + "1" => Srgba::from_rgb(255, 0, 0), //red + "2" => Srgba::from_rgb(0, 255, 0), //green + "3" => Srgba::from_rgb(0, 0, 255), //blue + "4" => Srgba::from_rgb(255, 255, 0), //yellow + "5" => Srgba::from_rgb(255, 0, 255), //purple + "6" => Srgba::from_rgb(0, 255, 255), //aqua + "7" => Srgba::from_rgb(255, 255, 255), //white + "8" => Srgba::from_rgb(178, 178, 178), //gray + "9" => Srgba::from_rgb(102, 102, 102), //dark gray + _ => unreachable!(), + }; + } + if let Some(hex) = caps.name("hex") + && let Ok(hex_color) = Srgba::from_hex(hex.as_str()) + { + return hex_color; + } + } + Srgba::WHITE + } +} diff --git a/src/api/search_handle.rs b/src/api/search_handle.rs new file mode 100644 index 0000000..7a96164 --- /dev/null +++ b/src/api/search_handle.rs @@ -0,0 +1,69 @@ +use std::fs; +use std::path::{Path, PathBuf}; +use std::time::SystemTime; + +use glob::Paths; +use mlua::{IntoLua, UserData}; + +pub struct SearchHandle { + paths: Paths, + // only yield directories if true, otherwise only files + directories_only: bool, + pub current: Option, +} + +impl SearchHandle { + pub fn new(paths: Paths, directories_only: bool) -> Self { + Self { + paths, + directories_only, + current: None, + } + } + + // sets current to the next file/directory if it exists and doesn't cause errors, + // otherwise None + pub fn next(&mut self) { + self.current = self + .paths + .find(|candidate| { + candidate + .as_ref() + .is_ok_and(|c| c.is_dir() == self.directories_only) + }) + .transpose() + .ok() + .flatten(); + } +} + +impl UserData for SearchHandle { + fn add_methods>(methods: &mut M) { + methods.add_method_mut("NextFile", |_, this, ()| { + this.next(); + Ok(this.current.is_some()) + }); + methods.add_method_mut("GetFileName", |l, this, ()| { + Ok(this.current.as_ref().unwrap().file_name().into_lua(l)) + }); + methods.add_method("GetFileSize", |_, this, ()| match &this.current { + Some(path) => match fs::metadata(path) { + Ok(metadata) => Ok(metadata.len()), + Err(_) => Ok(0), + }, + None => Ok(0), + }); + methods.add_method("GetFileModifiedTime", |_, this, ()| match &this.current { + Some(path) => get_time_modified(path).map_or(Ok(0), Ok), + None => Ok(0), + }); + } +} + +fn get_time_modified>(path: P) -> anyhow::Result { + let metadata = fs::metadata(path)?; + let modified_time = metadata.modified()?; + let duration_since_epoch = modified_time.duration_since(SystemTime::UNIX_EPOCH)?; + let seconds_since_epoch = duration_since_epoch.as_secs(); + Ok(seconds_since_epoch) +} diff --git a/src/app.rs b/src/app.rs new file mode 100644 index 0000000..b932dbf --- /dev/null +++ b/src/app.rs @@ -0,0 +1,188 @@ +use std::sync::Arc; + +use anyhow::Result; +use winit::{ + application::ApplicationHandler, + dpi::PhysicalPosition, + event::*, + event_loop::ActiveEventLoop, + keyboard::{ModifiersState, PhysicalKey}, + window::Window, +}; + +use crate::{ + context::{CONTEXT, FrameOutput}, + gfx::GraphicsContext, + input::{keycode_as_str, mousebutton_as_str}, + lua::LuaInstance, +}; + +pub struct App { + gfx_context: Option, + lua_instance: LuaInstance, +} + +impl App { + pub fn new() -> Result { + let lua_instance = LuaInstance::new()?; + + Ok(Self { + gfx_context: None, + lua_instance, + }) + } + + fn frame(&mut self) -> FrameOutput { + // Handle restart requests + if CONTEXT.with_borrow(|ctx| ctx.needs_restart) { + match self.lua_instance.restart() { + Ok(_) => CONTEXT.with_borrow_mut(|ctx| ctx.needs_restart = false), + Err(e) => panic!("Error occused while restarting lua instance: {}", e), + } + }; + + self.lua_instance.handle_subscripts(); + + // Clear data from previous frame and prepare for new one + CONTEXT.with_borrow_mut(|ctx| ctx.begin_frame()); + + // Call back into lua and tell it to draw a frame + self.lua_instance.on_frame().unwrap(); + + // End frame and get outupts + CONTEXT.with_borrow_mut(|ctx| ctx.end_frame()) + } +} + +impl ApplicationHandler for App { + fn resumed(&mut self, event_loop: &ActiveEventLoop) { + let window = match event_loop.create_window(Window::default_attributes()) { + Ok(window) => Arc::new(window), + Err(err) => { + log::error!("{err}"); + event_loop.exit(); + return; + } + }; + + CONTEXT.with_borrow_mut(|ctx| ctx.set_window(Arc::clone(&window))); + + self.gfx_context = match pollster::block_on(GraphicsContext::new(window)) { + Ok(gfx) => Some(gfx), + Err(err) => { + log::error!("{err}"); + event_loop.exit(); + return; + } + } + } + + fn window_event( + &mut self, + event_loop: &ActiveEventLoop, + _window_id: winit::window::WindowId, + event: WindowEvent, + ) { + CONTEXT.with_borrow_mut(|ctx| ctx.on_window_event(&event)); + + match event { + WindowEvent::CloseRequested => { + self.lua_instance.on_exit().unwrap(); + event_loop.exit() + } + WindowEvent::Resized(size) => { + if let Some(ref mut gfx) = self.gfx_context { + gfx.resize(size.width, size.height); + CONTEXT.with_borrow_mut(|ctx| ctx.force_render = true) + } + } + WindowEvent::RedrawRequested => { + profiling::scope!("RedrawRequested"); + + let FrameOutput { render_job } = self.frame(); + + if let Some(ref mut gfx) = self.gfx_context { + match gfx.render(render_job) { + Ok(_) => {} + // Reconfigure the surface if it's lost or outdated + Err(wgpu::SurfaceError::Lost | wgpu::SurfaceError::Outdated) => { + let size = gfx.window.inner_size(); + gfx.resize(size.width, size.height); + CONTEXT.with_borrow_mut(|ctx| ctx.force_render = true) + } + Err(err) => { + log::error!("Unable to render: {err}"); + } + } + } + + profiling::finish_frame!(); + } + WindowEvent::KeyboardInput { + event: + KeyEvent { + physical_key: PhysicalKey::Code(code), + state, + text, + .. + }, + .. + } => { + // Only call OnChar if no modifier key except SHIFT is pressed. + // This prevents 'v' from getting inserted into a text field + // when 'CTRL + v' is used to paste. + if state.is_pressed() + && CONTEXT.with_borrow(|ctx| { + ctx.input_state + .modifiers() + .difference(ModifiersState::SHIFT) + .is_empty() + }) + && let Some(text) = text + { + self.lua_instance.on_char(&text).unwrap(); + } + + if let Some(key_string) = keycode_as_str(code) { + match state { + ElementState::Pressed => { + self.lua_instance.on_key_down(&key_string, false).unwrap(); + } + ElementState::Released => { + self.lua_instance.on_key_up(&key_string).unwrap(); + } + } + } + } + WindowEvent::MouseInput { state, button, .. } => { + if let Some(button_string) = mousebutton_as_str(button) { + match state { + ElementState::Pressed => { + let is_double_click = CONTEXT + .with_borrow_mut(|ctx| ctx.input_state.is_double_click(button)); + self.lua_instance + .on_key_down(&button_string, is_double_click) + .unwrap(); + } + ElementState::Released => { + self.lua_instance.on_key_up(&button_string).unwrap(); + } + } + } + } + WindowEvent::MouseWheel { delta, .. } => { + let vertical_scroll_amount = match delta { + MouseScrollDelta::LineDelta(_, y) => y as f64, + MouseScrollDelta::PixelDelta(PhysicalPosition { y, .. }) => y, + }; + + if vertical_scroll_amount > 0.0 { + self.lua_instance.on_key_up("WHEELUP").unwrap(); + } else if vertical_scroll_amount < 0.0 { + self.lua_instance.on_key_up("WHEELDOWN").unwrap(); + } + } + _ => {} + } + } +} diff --git a/src/args.rs b/src/args.rs new file mode 100644 index 0000000..77d45ee --- /dev/null +++ b/src/args.rs @@ -0,0 +1,41 @@ +use clap::Parser; +use clap::ValueEnum; +use directories::BaseDirs; +use std::path::PathBuf; + +#[derive(Parser, Debug)] +#[command(version, about, long_about = None)] +pub struct Args { + #[arg(value_enum)] + pub game: Game, + + pub build_path: Option, +} + +#[derive(Debug, Clone, ValueEnum)] +pub enum Game { + #[value(name = "poe1")] + Poe1, + #[value(name = "poe2")] + Poe2, +} + +static GAME_CONFIG: std::sync::OnceLock = std::sync::OnceLock::new(); + +impl Game { + pub fn init(game: Game) { + GAME_CONFIG.set(game).expect("Game should be uninitialized"); + } + + pub fn current() -> &'static Game { + GAME_CONFIG.get().expect("Game should be initialized") + } + + pub fn script_dir() -> PathBuf { + let directory_name = match Self::current() { + Game::Poe1 => "PathOfBuilding1", + Game::Poe2 => "PathOfBuilding2", + }; + BaseDirs::new().unwrap().data_dir().join(directory_name) + } +} diff --git a/src/color.rs b/src/color.rs new file mode 100644 index 0000000..a79dec8 --- /dev/null +++ b/src/color.rs @@ -0,0 +1,74 @@ +/// `sRGB` color with _unmultiplied alpha_. +#[repr(C)] +#[repr(align(4))] +#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq, bytemuck::Pod, bytemuck::Zeroable)] +pub struct Srgba(pub [u8; 4]); + +impl Srgba { + pub const WHITE: Self = Self::from_rgb(255, 255, 255); + pub const TRANSPARENT: Self = Self::new(0, 0, 0, 0); + + #[inline] + pub const fn new(r: u8, g: u8, b: u8, a: u8) -> Self { + Self([r, g, b, a]) + } + + #[inline] + pub const fn new_f32(r: f32, g: f32, b: f32, a: f32) -> Self { + Self([f32_to_u8(r), f32_to_u8(g), f32_to_u8(b), f32_to_u8(a)]) + } + + #[inline] + pub const fn from_rgb(r: u8, g: u8, b: u8) -> Self { + Self([r, g, b, 255]) + } + + #[inline] + pub fn from_hex>(hex: T) -> anyhow::Result { + let hex = hex.as_ref(); + let hex = hex.strip_prefix("#").unwrap_or(hex); + + match hex.len() { + // RGB shorthand form, e.g. #FC0 -> #FFCC00 + 3 => { + let [m, l] = u16::from_str_radix(hex, 16)?.to_be_bytes(); + let (r, g, b) = (m & 0x0F, (l & 0xF0) >> 4, l & 0x0F); + Ok(Self::from_rgb((r << 4) | r, (g << 4) | g, (b << 4) | b)) + } + // RGBA shorthand form, e.g. #FC0F -> #FFCC00FF + 4 => { + let [m, l] = u16::from_str_radix(hex, 16)?.to_be_bytes(); + let (r, g, b, a) = ((m & 0xF0) >> 4, m & 0xF, (l & 0xF0) >> 4, l & 0x0F); + Ok(Self::new( + (r << 4) | r, + (g << 4) | g, + (b << 4) | b, + (a << 4) | a, + )) + } + // RRGGBB + 6 => { + let [_, r, g, b] = u32::from_str_radix(hex, 16)?.to_be_bytes(); + Ok(Self::from_rgb(r, g, b)) + } + // RRGGBBAA + 8 => { + let [r, g, b, a] = u32::from_str_radix(hex, 16)?.to_be_bytes(); + Ok(Self::new(r, g, b, a)) + } + _ => Err(anyhow::anyhow!("Unexpected length of hex string")), + } + } +} + +impl From for image::Rgba { + fn from(value: Srgba) -> Self { + Self(value.0) + } +} + +/// f32 [0.0, 1.0] -> u8 [0, 255] +#[inline(always)] +const fn f32_to_u8(c: f32) -> u8 { + ((c * 255.0) + 0.5) as u8 +} diff --git a/src/context.rs b/src/context.rs new file mode 100644 index 0000000..c3d912b --- /dev/null +++ b/src/context.rs @@ -0,0 +1,249 @@ +use crate::{ + Game, + color::Srgba, + dpi::{ + ConvertToLogical, LogicalPoint, LogicalQuad, LogicalRect, LogicalSize, NormalizedQuad, + NormalizedRect, PhysicalRect, PhysicalSize, + }, + fonts::{Fonts, LayoutJob}, + input::InputState, + layers::Layers, + renderer::{ + mesh::ClippedMesh, + primitives::{QuadPrimitive, QuadTexture, RectPrimitive, RectTexture, TextPrimitive}, + tessellator::Tessellator, + textures::{TextureId, TexturesDelta, WrappedTextureManager}, + }, + util::{calculate_hash, change_working_directory}, +}; +use arboard::Clipboard; +use std::{ + cell::RefCell, + path::{Path, PathBuf}, + sync::Arc, +}; +use winit::{event::WindowEvent, window::Window}; + +// NOTE: This looks ugly but i haven't found a better way to do it yet. +// The C functions used for rendering need a way to access the context. +// They can't be defined as closures like all other lua callback functions +// and we can't change their arguments. The only way for them to access +// something outside their scope is to have some kind of static variable. +thread_local! { + pub static CONTEXT: RefCell = RefCell::new(Context::new()); +} + +pub struct Context { + window: Option>, + screen_size: PhysicalSize, + pixels_per_point: f32, + pub input_state: InputState, + pub clipboard: Clipboard, + pub texture_manager: WrappedTextureManager, + tessellator: Tessellator, + fonts: Fonts, + layers: Layers, + current_draw_color: Srgba, + previous_layers_hash: u64, + current_working_dir: PathBuf, + pub needs_restart: bool, + pub force_render: bool, +} + +impl Context { + pub fn new() -> Self { + Self { + window: None, + screen_size: PhysicalSize::new(0, 0), + pixels_per_point: 1.0, + input_state: InputState::default(), + clipboard: Clipboard::new().unwrap(), + texture_manager: WrappedTextureManager::new(), + tessellator: Tessellator::default(), + fonts: Fonts::new(), + layers: Layers::new(), + current_draw_color: Srgba::WHITE, + previous_layers_hash: 0, + current_working_dir: Game::script_dir().clone(), + needs_restart: false, + force_render: false, + } + } + + pub fn begin_frame(&mut self) { + profiling::scope!("begin_frame"); + + self.fonts.begin_frame(); + self.layers.reset(); + self.reset_viewport(); + } + + pub fn end_frame(&mut self) -> FrameOutput { + profiling::scope!("end_frame"); + + let font_atlas_size = self.fonts.font_atlas().size(); + if let Some(font_image_delta) = self.fonts.font_atlas_delta() { + self.texture_manager.update_font_texture(font_image_delta); + } + + let textures_delta = self.texture_manager.take_delta(); + + // Skip rendering this frame if identical to last one and no textures changed + let layers_hash = calculate_hash(&self.layers); + let elide_frame = layers_hash == self.previous_layers_hash && textures_delta.is_empty(); + + let render_job = if elide_frame && !self.force_render { + RenderJob::Skip + } else { + self.force_render = false; + self.previous_layers_hash = layers_hash; + + let primitives = self.layers.consume_layers(); + let meshes = self + .tessellator + .convert_clipped_primitives(primitives, font_atlas_size); + + RenderJob::Render { + meshes, + textures_delta, + } + }; + + FrameOutput { render_job } + } + + pub fn on_window_event(&mut self, event: &WindowEvent) { + match event { + WindowEvent::Resized(size) => { + self.screen_size = PhysicalSize::new(size.width, size.height); + } + WindowEvent::ScaleFactorChanged { scale_factor, .. } => { + self.pixels_per_point = *scale_factor as f32; + } + _ => {} + } + + self.input_state.on_window_event(event); + } + + pub fn screen_size_logical(&self) -> LogicalSize { + self.screen_size.to_logical(self.pixels_per_point) + } + + pub fn mouse_pos_logical(&self) -> LogicalPoint { + self.input_state + .mouse_pos() + .to_logical(self.pixels_per_point) + } + + pub fn pixels_per_point(&self) -> f32 { + self.pixels_per_point + } + + pub fn current_working_dir(&self) -> &Path { + &self.current_working_dir + } + + pub fn set_current_working_dir(&mut self, path: PathBuf) { + if change_working_directory(&path).is_ok() { + self.current_working_dir = path; + } + } + + pub fn set_window(&mut self, window: Arc) { + self.window = Some(window); + } + + pub fn set_window_title(&self, title: &str) { + if let Some(ref window) = self.window { + window.set_title(title); + } + } +} + +pub enum RenderJob { + Render { + meshes: Vec, + textures_delta: TexturesDelta, + }, + Skip, +} + +pub struct FrameOutput { + pub render_job: RenderJob, +} + +impl Context { + pub fn set_draw_layer(&mut self, layer: i32, sublayer: i32) { + self.layers.set_draw_layer(layer, sublayer); + } + + pub fn set_draw_sublayer(&mut self, sublayer: i32) { + self.layers.set_draw_sublayer(sublayer); + } + + pub fn set_viewport(&mut self, viewport: LogicalRect) { + self.layers.set_viewport(viewport); + } + + pub fn reset_viewport(&mut self) { + let viewport = PhysicalRect::from_size(self.screen_size); + self.layers + .set_viewport(viewport.to_logical(self.pixels_per_point)); + } + + pub fn set_draw_color(&mut self, color: Srgba) { + self.current_draw_color = color; + } + + pub fn get_draw_color(&self) -> Srgba { + self.current_draw_color + } + + pub fn draw_rect( + &mut self, + texture_id: Option, + rect: LogicalRect, + uv: NormalizedRect, + layer_idx: u32, + ) { + let texture = texture_id.map(|id| RectTexture::new(id, uv, layer_idx)); + let primitive = RectPrimitive::new(rect, self.current_draw_color, texture); + self.layers.add_rect(primitive); + } + + pub fn draw_quad( + &mut self, + texture_id: Option, + quad: LogicalQuad, + uv: NormalizedQuad, + layer_idx: u32, + ) { + let texture = texture_id.map(|id| QuadTexture::new(id, uv, layer_idx)); + let primitive = QuadPrimitive::new(quad, self.current_draw_color, texture); + self.layers.add_quad(primitive); + } + + pub fn draw_text( + &mut self, + position: LogicalPoint, + job: LayoutJob, + is_absolute_position: bool, + ) { + let layout = self.fonts.layout(job, self.pixels_per_point as f32); + let primitive = TextPrimitive::new(position, layout); + self.layers.add_text(primitive, is_absolute_position); + } + + /// Width of laid out text + pub fn get_text_width(&mut self, job: LayoutJob) -> i32 { + let layout = self.fonts.layout(job, self.pixels_per_point as f32); + layout.width() as i32 + } + + /// Text index based on where cursor is positioned within text + pub fn get_text_index_at_cursor(&mut self, job: LayoutJob, cursor: LogicalPoint) -> usize { + let layout = self.fonts.layout(job, self.pixels_per_point as f32); + layout.cursor_index(cursor) + } +} diff --git a/src/dpi.rs b/src/dpi.rs new file mode 100644 index 0000000..f528e99 --- /dev/null +++ b/src/dpi.rs @@ -0,0 +1,185 @@ +use crate::math::{Point, Quad, Rect, Size, Vector}; +use core::f32; +use num_traits::{Float, NumCast, ToPrimitive}; + +pub struct LogicalScreenSpace; +pub struct PhysicalScreenSpace; +pub struct Normalized; + +pub type LogicalPoint = Point; +pub type LogicalVector = Vector; +pub type LogicalSize = Size; +pub type LogicalRect = Rect; +pub type LogicalQuad = Quad; + +pub type PhysicalPoint = Point; +pub type PhysicalVector = Vector; +pub type PhysicalSize = Size; +pub type PhysicalRect = Rect; + +pub type NormalizedPoint = Point; +pub type NormalizedRect = Rect; +pub type NormalizedQuad = Quad; + +pub trait Normalize { + type Output; + fn normalize(&self, size: Size) -> Self::Output; +} + +impl Normalize for Point +where + T: Copy + std::ops::Div + ToPrimitive, +{ + type Output = Point; + + #[inline] + fn normalize(&self, size: Size) -> Self::Output { + Point::new( + F::from(self.x).unwrap() / F::from(size.width).unwrap(), + F::from(self.y).unwrap() / F::from(size.height).unwrap(), + ) + } +} + +impl Normalize for Rect +where + T: Copy + std::ops::Div + ToPrimitive, +{ + type Output = Rect; + + #[inline] + fn normalize(&self, size: Size) -> Self::Output { + Rect::new(self.min.normalize(size), self.max.normalize(size)) + } +} + +pub trait ConvertToLogical { + type Output; + fn to_logical(&self, scale_factor: F) -> Self::Output; +} + +pub trait ConvertToPhysical { + type Output; + fn to_physical(&self, scale_factor: F) -> Self::Output; +} + +#[inline] +pub fn validate_scale_factor(scale_factor: F) -> bool { + scale_factor.is_sign_positive() && scale_factor.is_normal() +} + +impl ConvertToLogical for PhysicalPoint +where + T: Copy + std::ops::Div + ToPrimitive, +{ + type Output = LogicalPoint; + + #[inline] + fn to_logical(&self, scale_factor: F) -> Self::Output { + assert!(validate_scale_factor(scale_factor)); + let x = F::from(self.x).unwrap() / scale_factor; + let y = F::from(self.y).unwrap() / scale_factor; + LogicalPoint::new(x, y).cast() + } +} + +impl ConvertToLogical for PhysicalSize +where + T: Copy + std::ops::Div + ToPrimitive, +{ + type Output = LogicalSize; + + #[inline] + fn to_logical(&self, scale_factor: F) -> Self::Output { + assert!(validate_scale_factor(scale_factor)); + let width = F::from(self.width).unwrap() / scale_factor; + let height = F::from(self.height).unwrap() / scale_factor; + LogicalSize::new(width, height).cast() + } +} + +impl ConvertToLogical for PhysicalRect +where + T: Copy + std::ops::Div + ToPrimitive, +{ + type Output = LogicalRect; + + #[inline] + fn to_logical(&self, scale_factor: F) -> Self::Output { + assert!(validate_scale_factor(scale_factor)); + let min = self.min.to_logical(scale_factor); + let max = self.max.to_logical(scale_factor); + LogicalRect::new(min, max) + } +} + +impl ConvertToPhysical for LogicalPoint +where + T: Copy + std::ops::Div + ToPrimitive, +{ + type Output = PhysicalPoint; + + #[inline] + fn to_physical(&self, scale_factor: F) -> Self::Output { + assert!(validate_scale_factor(scale_factor)); + let x = F::from(self.x).unwrap() * scale_factor; + let y = F::from(self.y).unwrap() * scale_factor; + PhysicalPoint::new(x, y).cast() + } +} + +impl ConvertToPhysical for LogicalRect +where + T: Copy + std::ops::Div + ToPrimitive, +{ + type Output = PhysicalRect; + + #[inline] + fn to_physical(&self, scale_factor: F) -> Self::Output { + assert!(validate_scale_factor(scale_factor)); + let min = self.min.to_physical(scale_factor); + let max = self.max.to_physical(scale_factor); + PhysicalRect::new(min, max) + } +} + +pub trait Uv { + fn default_uv() -> Self; + fn white_uv() -> Self; +} + +impl Uv for NormalizedPoint { + #[inline] + fn default_uv() -> Self { + Self::zero() + } + + #[inline] + fn white_uv() -> Self { + Self::zero() + } +} + +impl Uv for NormalizedRect { + #[inline] + fn default_uv() -> Self { + Self::from_size(Size::new(1.0, 1.0)) + } + + #[inline] + fn white_uv() -> Self { + Self::zero() + } +} + +impl Uv for NormalizedQuad { + #[inline] + fn default_uv() -> Self { + Self::from_size(Size::new(1.0, 1.0)) + } + + #[inline] + fn white_uv() -> Self { + Self::zero() + } +} diff --git a/src/fonts.rs b/src/fonts.rs new file mode 100644 index 0000000..5230cf7 --- /dev/null +++ b/src/fonts.rs @@ -0,0 +1,339 @@ +use crate::{ + color::Srgba, + dpi::LogicalVector, + fonts::{ + atlas::FontAtlas, glyph_key::SubpixelBin, layout::LayoutRow, rasterizer::GlyphRasterizer, + }, + renderer::image::ImageDelta, + util::calculate_hash, +}; +use ordered_float::OrderedFloat; +use parley::{ + FontContext, FontWeight, GenericFamily, LayoutContext, StyleProperty, TextStyle, fontique::Blob, +}; +use std::sync::Arc; + +pub use atlas::FontAtlasSize; +pub use layout::{Alignment, Layout, LayoutJob}; + +mod atlas; +mod glyph_key; +mod layout; +mod rasterizer; + +pub const BITSTREAM_VERA_SANS_MONO: &[u8] = include_bytes!("../fonts/VeraMono.ttf"); +pub const LIBERATION_SANS: &[u8] = include_bytes!("../fonts/LiberationSans-Regular.ttf"); +pub const LIBERATION_SANS_BOLD: &[u8] = include_bytes!("../fonts/LiberationSans-Bold.ttf"); + +pub struct FontData { + data: std::borrow::Cow<'static, [u8]>, +} + +impl FontData { + pub fn from_static(font_data: &'static [u8]) -> Self { + Self { + data: std::borrow::Cow::Borrowed(font_data), + } + } +} + +impl AsRef<[u8]> for FontData { + fn as_ref(&self) -> &[u8] { + self.data.as_ref() + } +} + +pub struct FontDefinition { + pub generic_families: Vec, + pub data: Arc, +} + +pub struct Fonts { + font_definitions: Vec, + font_context: FontContext, + layout_context: LayoutContext, + atlas: FontAtlas, + glyph_rasterizer: GlyphRasterizer, + layout_cache: LayoutCache, +} + +impl Fonts { + pub fn new() -> Self { + // add fonts used by PoB + let font_definitions = vec![ + FontDefinition { + generic_families: vec![GenericFamily::Monospace], + data: Arc::new(FontData::from_static(BITSTREAM_VERA_SANS_MONO)), + }, + FontDefinition { + generic_families: vec![GenericFamily::SansSerif], + data: Arc::new(FontData::from_static(LIBERATION_SANS)), + }, + FontDefinition { + generic_families: vec![GenericFamily::SansSerif], + data: Arc::new(FontData::from_static(LIBERATION_SANS_BOLD)), + }, + ]; + + let mut fonts = Self { + font_definitions, + font_context: FontContext::new(), + layout_context: LayoutContext::new(), + atlas: FontAtlas::new(1024), + glyph_rasterizer: GlyphRasterizer::new(), + layout_cache: LayoutCache::default(), + }; + + fonts.register_fonts(); + fonts.preload_common_characters(14.0); + fonts.preload_common_characters(16.0); + + fonts + } + + fn register_fonts(&mut self) { + for definition in &self.font_definitions { + let blob = Blob::new(Arc::new(definition.data.data.clone())); + let registered_fonts = self.font_context.collection.register_fonts(blob, None); + for generic_family in &definition.generic_families { + self.font_context + .collection + .append_generic_families(*generic_family, registered_fonts.iter().map(|f| f.0)); + } + } + } + + /// Needs to be called at beginning of each frame. + pub fn begin_frame(&mut self) { + // recreate atlas when it becomes too full or overflowed + if self.atlas.capacity() > 0.9 { + self.clear_atlas(); + } + self.layout_cache.flush(); + } + + /// Gets changes to the font atlas texture since last call. + pub fn font_atlas_delta(&mut self) -> Option { + self.atlas.take_delta() + } + + pub fn preload_common_characters(&mut self, font_size: f32) { + const ASCII_PRINTABLE_START: u8 = 32; + const ASCII_PRINTABLE_END: u8 = 126; + + let mut common_chars = + String::with_capacity((ASCII_PRINTABLE_END - ASCII_PRINTABLE_START + 1) as usize); + + for c in ASCII_PRINTABLE_START..=ASCII_PRINTABLE_END { + common_chars.push(c as char); + } + + self.preload_text(&common_chars, font_size, GenericFamily::Monospace, None); + self.preload_text(&common_chars, font_size, GenericFamily::SansSerif, None); + self.preload_text( + &common_chars, + font_size, + GenericFamily::SansSerif, + Some(FontWeight::BOLD), + ); + } + + fn preload_text( + &mut self, + text: &str, + font_size: f32, + generic_family: GenericFamily, + font_weight: Option, + ) { + profiling::scope!("preload_text"); + + let style = TextStyle { + font_stack: parley::FontStack::Single(parley::FontFamily::Generic(generic_family)), + font_weight: font_weight.unwrap_or(FontWeight::NORMAL), + font_size, + ..Default::default() + }; + let mut builder = + self.layout_context + .tree_builder(&mut self.font_context, 1.0, true, &style); + builder.push_text(text); + + let (mut layout, _) = builder.build(); + layout.break_all_lines(None); + + for line in layout.lines() { + for item in line.items() { + let parley::PositionedLayoutItem::GlyphRun(run) = item else { + continue; + }; + + for horizontal_offset in SubpixelBin::<4>::BIN_OFFSETS { + self.glyph_rasterizer + .rasterize_glyph_run( + &mut self.atlas, + &run, + LogicalVector::new(horizontal_offset, 0.0), + 1.0, + ) + .for_each(|_| {}); + } + } + } + } + + pub fn font_atlas(&self) -> &FontAtlas { + &self.atlas + } + + pub fn layout(&mut self, job: LayoutJob, pixels_per_point: f32) -> Arc { + let hash = calculate_hash(&(&job, OrderedFloat(pixels_per_point))); + + if let Some(cached_layout) = self.layout_cache.get(hash) { + return cached_layout; + } + + let default_style = TextStyle::default(); + let style = TextStyle { + font_stack: parley::FontStack::Single(parley::FontFamily::Generic(job.font_family)), + font_size: job.font_size.into(), + line_height: parley::LineHeight::Absolute(job.line_height.into()), + font_weight: job + .font_weight + .map(|w| parley::FontWeight::new(w.into())) + .unwrap_or(default_style.font_weight), + ..default_style + }; + + let mut builder = self.layout_context.tree_builder( + &mut self.font_context, + 1.0, + // TODO: quantize true or false? + true, + &style, + ); + + for segment in job.segments { + let brush_style = StyleProperty::Brush(segment.color); + builder.push_style_modification_span(&[brush_style]); + builder.push_text(segment.text); + builder.pop_style_span(); + } + + let (mut parley_layout, _) = builder.build(); + parley_layout.break_all_lines(None); + + // extra offset applied to each glyph to get position relative to layout origin + let mut glyph_offset = LogicalVector::new(0.0, 0.0); + if let Some(alignment) = job.alignment { + let alignment = match alignment { + Alignment::Min => parley::Alignment::Start, + Alignment::Center => { + glyph_offset.x += -parley_layout.full_width() * 0.5; + parley::Alignment::Center + } + Alignment::Max => { + glyph_offset.x += -parley_layout.full_width(); + parley::Alignment::End + } + }; + parley_layout.align(None, alignment, parley::AlignmentOptions::default()); + } + + let mut layout_rows = Vec::new(); + let mut num_of_vertices = 0; + let mut num_of_indices = 0; + + for line in parley_layout.lines() { + let mut layout_row = LayoutRow::default(); + + for item in line.items() { + let parley::PositionedLayoutItem::GlyphRun(run) = item else { + continue; + }; + + for rasterized_glyph in self.glyph_rasterizer.rasterize_glyph_run( + &mut self.atlas, + &run, + glyph_offset, + pixels_per_point, + ) { + let Some(glyph) = rasterized_glyph else { + continue; + }; + + layout_row.glyphs.push(glyph); + num_of_vertices += 4; + num_of_indices += 6; + } + } + + if !layout_row.glyphs.is_empty() { + layout_rows.push(layout_row); + } + } + + let layout = Arc::new(Layout { + job_hash: hash, + parley_layout, + rows: layout_rows, + num_of_vertices, + num_of_indices, + }); + + self.layout_cache.insert(hash, Arc::clone(&layout)); + + layout + } + + /// Clear atlas and invalidate caches depend on atlas state + fn clear_atlas(&mut self) { + self.atlas.clear(); + self.glyph_rasterizer.clear(); + self.layout_cache.clear(); + } +} + +struct CachedLayout { + generation: u32, + layout: Arc, +} + +#[derive(Default)] +struct LayoutCache { + current_generation: u32, + cache: nohash_hasher::IntMap, +} + +impl LayoutCache { + fn get(&mut self, hash: u64) -> Option> { + match self.cache.entry(hash) { + std::collections::hash_map::Entry::Occupied(entry) => { + let cached = entry.into_mut(); + cached.generation = self.current_generation; + Some(Arc::clone(&cached.layout)) + } + std::collections::hash_map::Entry::Vacant(_) => None, + } + } + + fn insert(&mut self, hash: u64, layout: Arc) { + self.cache.insert( + hash, + CachedLayout { + generation: self.current_generation, + layout, + }, + ); + } + + /// Removes unused layouts + pub fn flush(&mut self) { + self.cache + .retain(|_key, cached| cached.generation == self.current_generation); + self.current_generation = self.current_generation.wrapping_add(1); + } + + pub fn clear(&mut self) { + self.cache.clear(); + } +} diff --git a/src/fonts/atlas.rs b/src/fonts/atlas.rs new file mode 100644 index 0000000..337ad16 --- /dev/null +++ b/src/fonts/atlas.rs @@ -0,0 +1,137 @@ +use crate::{ + color::Srgba, + math::{Point, Rect, Size}, + renderer::{ + image::{ImageData, ImageDelta}, + textures::TextureOptions, + }, +}; +use image::{GenericImage, RgbaImage, SubImage, imageops}; + +pub struct FontAtlasSpace; +pub type FontAtlasPoint = Point; +pub type FontAtlasSize = Size; +pub type FontAtlasRect = Rect; + +pub struct FontAtlas { + // max width/height of atlas texture + max_texture_side: u32, + image: RgbaImage, + // position of next allocation + cursor: FontAtlasPoint, + current_row_height: u32, + // atlas has been altered and needs to be reuploaded to the GPU + // TODO: only mark changed region as dirty and perform partial texture update + dirty: bool, + // atlas has overflowed and needs to be recreated + overflowed: bool, +} + +impl FontAtlas { + pub fn new(max_texture_side: u32) -> Self { + // start out with maximum width and let height grow as needed + let width = max_texture_side; + let initial_height = 256; + + let mut atlas = Self { + max_texture_side, + image: RgbaImage::new(width, initial_height), + cursor: FontAtlasPoint::zero(), + current_row_height: 0, + dirty: false, + overflowed: false, + }; + + atlas.initialize(); + atlas + } + + fn initialize(&mut self) { + // Puts white pixel at (0, 0). + // NOTE: Rendering a solid color shape is done by setting the texture to + // the font atlas and sampling the white pixel at (0, 0). + let mut sub_image = self.allocate(FontAtlasSize::new(1, 1)); + sub_image.put_pixel(0, 0, Srgba::WHITE.into()); + } + + // TODO: use an actual bin packing algorithm for tighter packing + /// Returns a mutable view into the atlas of given size. + pub fn allocate(&mut self, size: FontAtlasSize) -> SubImage<&mut RgbaImage> { + const PADDING: u32 = 1; + + if self.cursor.x + size.width > self.image.width() { + self.cursor.x = 0; + self.cursor.y += self.current_row_height + PADDING; + self.current_row_height = 0; + } + + self.current_row_height = self.current_row_height.max(size.height); + + let required_atlas_height = self.cursor.y + self.current_row_height; + if required_atlas_height > self.max_texture_side { + log::warn!("font atlas overflowed!"); + // start overwriting old glyphs + self.cursor = Point::new(0, self.image.height() / 3); + // setting this flag causes atlas to be recreated next frame + self.overflowed = true; + } else if required_atlas_height > self.image().height() { + // increase height + let mut new_height = self.image.height(); + while new_height < required_atlas_height { + new_height *= 2; + } + self.image = extend_image_height(&self.image, new_height, Srgba::TRANSPARENT); + } + + let pos = self.cursor; + self.cursor.x += size.width + PADDING; + + self.dirty = true; + + self.image.sub_image(pos.x, pos.y, size.width, size.height) + } + + pub fn take_delta(&mut self) -> Option { + let dirty = std::mem::replace(&mut self.dirty, false); + if dirty { + Some(ImageDelta::new( + ImageData::from(self.image.clone()), + TextureOptions::LINEAR, + )) + } else { + None + } + } + + pub fn capacity(&self) -> f32 { + if self.overflowed { + 1.0 + } else { + (self.cursor.y + self.current_row_height) as f32 / self.max_texture_side as f32 + } + } + + pub fn clear(&mut self) { + self.image.fill(0); + self.cursor = FontAtlasPoint::zero(); + self.current_row_height = 0; + self.dirty = false; + self.overflowed = false; + self.initialize(); + } + + pub fn image(&self) -> &RgbaImage { + &self.image + } + + pub fn size(&self) -> FontAtlasSize { + FontAtlasSize::new(self.image.width(), self.image.height()) + } +} + +fn extend_image_height(image: &RgbaImage, new_height: u32, fill_color: Srgba) -> RgbaImage { + let width = image.width(); + let mut extended_image = RgbaImage::from_pixel(width, new_height, fill_color.into()); + imageops::overlay(&mut extended_image, image, 0, 0); + extended_image +} diff --git a/src/fonts/glyph_key.rs b/src/fonts/glyph_key.rs new file mode 100644 index 0000000..46bf36a --- /dev/null +++ b/src/fonts/glyph_key.rs @@ -0,0 +1,83 @@ +use ordered_float::OrderedFloat; +use parley::Glyph; + +use crate::{dpi::PhysicalPoint, fonts::rasterizer::StyleId}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct GlyphKey { + glyph_id: swash::GlyphId, + style_id: StyleId, + x_bin: SubpixelBin<4>, + pixels_per_point: OrderedFloat, +} + +impl GlyphKey { + pub fn from_glyph( + glyph: &Glyph, + style_id: StyleId, + pixels_per_point: f32, + ) -> (Self, PhysicalPoint) { + // Use subpixel binning for x coordinate + let (x, x_bin) = SubpixelBin::<4>::new(glyph.x * pixels_per_point); + // No binning for y coordinate, just rounding + let y = (glyph.y * pixels_per_point).round() as i32; + let glyph_pos = PhysicalPoint::new(x, y); + + ( + Self { + glyph_id: glyph.id as u16, + style_id, + x_bin, + pixels_per_point: OrderedFloat(pixels_per_point), + }, + glyph_pos, + ) + } + + pub fn get_fractional_offset(&self) -> swash::zeno::Vector { + swash::zeno::Vector::new(self.x_bin.as_float(), 0.0) + } +} + +/// Grouping of fractional offsets into discrete bins for cache optimization +/// Bins have size 1/N and are centered around (1/N) * i with i in {0, 1, 2, ...} +#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] +pub struct SubpixelBin(usize); + +impl SubpixelBin { + pub const BIN_OFFSETS: [f32; NUM_OF_BINS] = { + let mut out = [0.0; NUM_OF_BINS]; + let mut i = 0; + while i < NUM_OF_BINS { + out[i] = i as f32 * 1.0 / NUM_OF_BINS as f32; + i += 1; + } + out + }; + + pub fn new(position: f32) -> (i32, Self) { + let half_bin_width = 1.0 / (NUM_OF_BINS as f32 * 2.0); + let new_position = (position + half_bin_width).floor() as i32; + + let scaled_pos = ((position - position.floor()) * NUM_OF_BINS as f32).round() as usize; + let bin = scaled_pos.rem_euclid(NUM_OF_BINS); + + (new_position, Self(bin)) + } + + pub const fn as_float(&self) -> f32 { + self.0 as f32 / NUM_OF_BINS as f32 + } +} + +#[test] +fn test_subpixel_bins() { + assert_eq!(SubpixelBin::<4>::new(3.14), (3, SubpixelBin(1))); + assert_eq!(SubpixelBin::<4>::new(0.11), (0, SubpixelBin(0))); + assert_eq!(SubpixelBin::<4>::new(-0.8), (-1, SubpixelBin(1))); + assert_eq!(SubpixelBin::<2>::new(0.24), (0, SubpixelBin(0))); + assert_eq!(SubpixelBin::<2>::new(0.26), (0, SubpixelBin(1))); + assert_eq!(SubpixelBin::<2>::new(0.76), (1, SubpixelBin(0))); + assert_eq!(SubpixelBin::<2>::new(-0.76), (-1, SubpixelBin(0))); + assert_eq!(SubpixelBin::<2>::new(-0.25), (0, SubpixelBin(0))); +} diff --git a/src/fonts/layout.rs b/src/fonts/layout.rs new file mode 100644 index 0000000..952016b --- /dev/null +++ b/src/fonts/layout.rs @@ -0,0 +1,80 @@ +use crate::{color::Srgba, dpi::LogicalPoint, fonts::rasterizer::RasterizedGlyph}; +use ordered_float::OrderedFloat; +use parley::GenericFamily; + +#[derive(Copy, Clone, Debug, Hash)] +pub enum Alignment { + Min, + Center, + Max, +} + +#[derive(Clone, Debug, Hash)] +pub struct LayoutSegment<'s> { + pub text: &'s str, + pub color: Srgba, +} + +#[derive(Clone, Debug, Hash)] +pub struct LayoutJob<'s> { + pub segments: Vec>, + pub font_family: GenericFamily, + pub font_size: OrderedFloat, + pub line_height: OrderedFloat, + pub alignment: Option, + pub font_weight: Option>, +} + +impl<'s> LayoutJob<'s> { + pub fn new( + font_family: GenericFamily, + font_size: f32, + line_height: f32, + alignment: Option, + font_weight: Option, + ) -> Self { + Self { + segments: Vec::new(), + font_family, + font_size: font_size.into(), + line_height: line_height.into(), + alignment, + font_weight: font_weight.map(OrderedFloat), + } + } + + pub fn append(&mut self, text: &'s str, color: Srgba) { + self.segments.push(LayoutSegment { text, color }); + } +} + +#[derive(Default)] +pub struct LayoutRow { + pub glyphs: Vec, +} + +pub struct Layout { + pub job_hash: u64, + pub parley_layout: parley::Layout, + pub rows: Vec, + pub num_of_vertices: usize, + pub num_of_indices: usize, +} + +impl Layout { + pub fn width(&self) -> f32 { + self.parley_layout.full_width() + } + + /// Returns text index at cursor position + pub fn cursor_index(&self, cursor: LogicalPoint) -> usize { + let cursor = parley::Cursor::from_point(&self.parley_layout, cursor.x, cursor.y); + cursor.index() + } +} + +impl std::hash::Hash for Layout { + fn hash(&self, state: &mut H) { + self.job_hash.hash(state); + } +} diff --git a/src/fonts/rasterizer.rs b/src/fonts/rasterizer.rs new file mode 100644 index 0000000..93a09db --- /dev/null +++ b/src/fonts/rasterizer.rs @@ -0,0 +1,253 @@ +use crate::{ + color::Srgba, + dpi::{ + ConvertToLogical, LogicalRect, LogicalVector, PhysicalPoint, PhysicalRect, PhysicalVector, + }, + fonts::{ + atlas::{FontAtlas, FontAtlasRect}, + glyph_key::GlyphKey, + }, + math::{Point, Size}, +}; +use ahash::HashMap; +use image::GenericImage; +use ordered_float::OrderedFloat; +use parley::{FontData, GlyphRun}; +use std::borrow::Cow; + +type FontBlobId = u64; +type FontIndex = u32; +type SwashFontOffset = u32; +pub type StyleId = u32; + +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +struct StyleKey<'a> { + font_blob_id: FontBlobId, + font_size: OrderedFloat, + normalized_coords: Cow<'a, [i16]>, +} + +impl<'a> StyleKey<'a> { + fn new(font_blob_id: FontBlobId, font_size: f32, normalized_coords: &'a [i16]) -> Self { + Self { + font_blob_id, + font_size: font_size.into(), + normalized_coords: Cow::Borrowed(normalized_coords), + } + } + + fn to_static(&self) -> StyleKey<'static> { + StyleKey { + normalized_coords: self.normalized_coords.clone().into_owned().into(), + ..*self + } + } +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct CachedGlyph { + // absolute uv rect within font atlas + pub uv: FontAtlasRect, + // offset from top/left to baseline + pub baseline_offset: PhysicalVector, +} + +pub struct RasterizedGlyph { + // NOTE: this is relative to the layout origin + pub rect: LogicalRect, + pub uv: FontAtlasRect, + pub color: Srgba, +} + +impl RasterizedGlyph { + fn from_cached( + cached: CachedGlyph, + position: PhysicalPoint, + color: Srgba, + pixels_per_point: f32, + ) -> Self { + let glyph_rect = PhysicalRect::from_origin_and_size( + position + cached.baseline_offset, + cached.uv.cast_unit().cast().size(), + ); + + RasterizedGlyph { + rect: glyph_rect.to_logical(pixels_per_point), + uv: cached.uv, + color, + } + } +} + +pub struct GlyphRasterizer { + scale_context: swash::scale::ScaleContext, + swash_keys: HashMap<(FontBlobId, FontIndex), (SwashFontOffset, swash::CacheKey)>, + // Style properties (font, size, etc.) are the same for each glyph run and don't + // need to be part of each glyph key. Instead, associate each style with its own + // ID and include that in the glyph key. + style_ids: HashMap, StyleId>, + next_style_id: StyleId, + cached_glyphs: HashMap>, + // scratch image buffer used to write bitmap data into + scratch: swash::scale::image::Image, +} + +impl GlyphRasterizer { + pub fn new() -> Self { + Self { + scale_context: swash::scale::ScaleContext::new(), + swash_keys: Default::default(), + style_ids: Default::default(), + next_style_id: 0, + cached_glyphs: Default::default(), + scratch: Default::default(), + } + } + + pub fn clear(&mut self) { + self.swash_keys.clear(); + self.style_ids.clear(); + self.next_style_id = 0; + self.cached_glyphs.clear(); + } + + /// Gets a swash::FontRef from FontData + fn get_font_ref<'a>(&mut self, font: &'a FontData) -> swash::FontRef<'a> { + let font_blob_id = font.data.id(); + + let (swash_offset, swash_key) = *self + .swash_keys + .entry((font_blob_id, font.index)) + .or_insert_with(|| { + let font_ref = + swash::FontRef::from_index(font.data.data(), font.index as usize).unwrap(); + (font_ref.offset, font_ref.key) + }); + + swash::FontRef { + data: font.data.data(), + offset: swash_offset, + key: swash_key, + } + } + + fn get_style_id( + &mut self, + font_data: &FontData, + font_size: f32, + norm_coords: &[i16], + ) -> StyleId { + let style_key = StyleKey::new(font_data.data.id(), font_size, norm_coords); + match self.style_ids.get(&style_key) { + Some(key) => *key, + None => *self + .style_ids + .entry(style_key.to_static()) + .or_insert_with(|| { + let id = self.next_style_id; + self.next_style_id += 1; + id + }), + } + } + + /// Rasterizes glyph run and returns the placement and UV for each glyph. + /// Can return `None` if glyph doesn't take up any space (e.g. whitespace). + pub fn rasterize_glyph_run<'slf: 'run, 'run, 'atlas>( + &'slf mut self, + atlas: &'atlas mut FontAtlas, + glyph_run: &'run GlyphRun<'_, Srgba>, + // additional offset relative to layout origin + glyph_offset: LogicalVector, + pixels_per_point: f32, + ) -> impl Iterator> + use<'slf, 'run, 'atlas> { + let run = glyph_run.run(); + let color = glyph_run.style().brush; + let font_size = run.font_size() * pixels_per_point; + let normalized_coords = run.normalized_coords(); + + let font_ref = self.get_font_ref(run.font()); + let style_id = self.get_style_id(run.font(), font_size, normalized_coords); + + let mut scaler = self + .scale_context + .builder(font_ref) + .size(font_size) + .normalized_coords(normalized_coords) + .hint(true) + .build(); + + let image = &mut self.scratch; + let cached_glyphs = &mut self.cached_glyphs; + glyph_run.positioned_glyphs().map(move |mut glyph| { + glyph.x += glyph_offset.x; + glyph.y += glyph_offset.y; + + let (glyph_key, glyph_pos) = GlyphKey::from_glyph(&glyph, style_id, pixels_per_point); + + if let Some(cached_glyph) = cached_glyphs.get(&glyph_key) { + return cached_glyph.map(|cached| { + RasterizedGlyph::from_cached(cached, glyph_pos, color, pixels_per_point) + }); + } + + let fract_offset = glyph_key.get_fractional_offset(); + + image.clear(); + let did_render = swash::scale::Render::new(&[ + swash::scale::Source::ColorOutline(0), + swash::scale::Source::ColorBitmap(swash::scale::StrikeWith::BestFit), + swash::scale::Source::Outline, + ]) + .format(swash::zeno::Format::Alpha) + .offset(fract_offset) + .render_into(&mut scaler, glyph.id as u16, image); + + if !did_render || image.placement.width == 0 || image.placement.height == 0 { + cached_glyphs.insert(glyph_key, None); + return None; + }; + + let atlas_region = write_to_atlas(image, atlas); + + let cached_glyph = CachedGlyph { + uv: atlas_region, + baseline_offset: PhysicalVector::new(image.placement.left, -image.placement.top), + }; + cached_glyphs.insert(glyph_key, Some(cached_glyph)); + + Some(RasterizedGlyph::from_cached( + cached_glyph, + glyph_pos, + color, + pixels_per_point, + )) + }) + } +} + +/// Writes rasterized glyph to atlas and returns region it wrote into +fn write_to_atlas(image: &swash::scale::image::Image, atlas: &mut FontAtlas) -> FontAtlasRect { + let mut atlas_region = atlas.allocate(Size::new(image.placement.width, image.placement.height)); + + match image.content { + swash::scale::image::Content::Mask => { + let mut i = 0; + for y in 0..image.placement.height { + for x in 0..image.placement.width { + let a = image.data[i]; + // SAFETY: allocated atlas region and swash image have the same size + unsafe { + atlas_region.unsafe_put_pixel(x, y, Srgba::new(255, 255, 255, a).into()) + }; + i += 1; + } + } + } + _ => unreachable!(), + }; + + FontAtlasRect::from_origin_and_size( + Point::new(atlas_region.offsets().0, atlas_region.offsets().1), + Size::new(image.placement.width, image.placement.height), + ) +} diff --git a/src/gfx.rs b/src/gfx.rs new file mode 100644 index 0000000..4ff07e8 --- /dev/null +++ b/src/gfx.rs @@ -0,0 +1,257 @@ +use crate::{context::RenderJob, dpi::PhysicalSize, renderer::Renderer}; +use std::sync::Arc; +use wgpu::{Texture, TextureFormat, TextureView}; +use winit::window::Window; + +pub struct GraphicsContext { + surface: wgpu::Surface<'static>, + device: wgpu::Device, + queue: wgpu::Queue, + config: wgpu::SurfaceConfiguration, + is_surface_configured: bool, + renderer: Renderer, + blit_texture: wgpu::Texture, + blit_texture_view: wgpu::TextureView, + texture_blitter: wgpu::util::TextureBlitter, + pub window: Arc, +} + +impl GraphicsContext { + pub async fn new(window: Arc) -> anyhow::Result { + let size = window.inner_size(); + + let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor { + backends: wgpu::Backends::PRIMARY, + ..Default::default() + }); + + let surface = instance.create_surface(Arc::clone(&window)).unwrap(); + + let adapter = instance + .request_adapter(&wgpu::RequestAdapterOptions { + power_preference: wgpu::PowerPreference::default(), + compatible_surface: Some(&surface), + force_fallback_adapter: false, + }) + .await?; + + let required_features = wgpu::Features::TEXTURE_COMPRESSION_BC; + let required_limits = wgpu::Limits { + max_texture_array_layers: 512, + ..Default::default() + }; + + if !adapter.features().contains(required_features) { + anyhow::bail!( + "Unsupported features were requested: {}", + required_features - adapter.features() + ); + } + + let mut failed_limit = Vec::new(); + + required_limits.check_limits_with_fail_fn( + &adapter.limits(), + false, + |name, requested, allowed| { + failed_limit.push((name, requested, allowed)); + }, + ); + + if let Some((name, requested, allowed)) = failed_limit.pop() { + anyhow::bail!( + "Requested limit '{name}' value {requested} is better than allowed {allowed}!" + ) + } + + let (device, queue) = adapter + .request_device(&wgpu::DeviceDescriptor { + label: None, + required_features, + required_limits, + memory_hints: Default::default(), + trace: wgpu::Trace::Off, + experimental_features: Default::default(), + }) + .await?; + + let surface_caps = surface.get_capabilities(&adapter); + + // NOTE: PoB incorrectly performs mixing and blending in sRGB space. + // To get a similar visual outcome, we need to do the same. + // Select a non-sRGB format so that no automatic linear -> sRGB conversion + // is performed. + let surface_format = surface_caps + .formats + .iter() + .find(|f| !f.is_srgb()) + .copied() + .unwrap_or(surface_caps.formats[0]); + + let config = wgpu::SurfaceConfiguration { + usage: wgpu::TextureUsages::RENDER_ATTACHMENT, + format: surface_format, + width: size.width, + height: size.height, + //present_mode: surface_caps.present_modes[0], + present_mode: wgpu::PresentMode::Fifo, + alpha_mode: surface_caps.alpha_modes[0], + view_formats: vec![], + desired_maximum_frame_latency: 2, + }; + + let (blit_texture, blit_texture_view) = + create_blit_texture(&device, config.width, config.height, config.format); + + let texture_blitter = wgpu::util::TextureBlitter::new(&device, config.format); + + let renderer = Renderer::new(&device, config.format, None); + + Ok(Self { + surface, + device, + queue, + config, + is_surface_configured: false, + renderer, + blit_texture, + blit_texture_view, + texture_blitter, + window, + }) + } + + pub fn resize(&mut self, width: u32, height: u32) { + if width > 0 && height > 0 { + self.config.width = width; + self.config.height = height; + self.surface.configure(&self.device, &self.config); + self.is_surface_configured = true; + + (self.blit_texture, self.blit_texture_view) = + create_blit_texture(&self.device, width, height, self.config.format); + } + } + + pub fn render(&mut self, render_job: RenderJob) -> Result<(), wgpu::SurfaceError> { + profiling::scope!("render"); + + self.window.request_redraw(); + + if !self.is_surface_configured { + return Ok(()); + } + + let output = self.surface.get_current_texture()?; + let suboptimal = output.suboptimal; + + let surface_view = output + .texture + .create_view(&wgpu::TextureViewDescriptor::default()); + + let mut encoder = self + .device + .create_command_encoder(&wgpu::CommandEncoderDescriptor { + label: Some("Render Encoder"), + }); + + // If render_job is [`RenderJob::Skip`], skip rendering and just + // blit the texture of the previous frame onto the surface texture. + if let RenderJob::Render { + meshes, + textures_delta, + } = render_job + { + let screen_size = PhysicalSize::new(self.config.width, self.config.height); + let pixels_per_point = self.window.as_ref().scale_factor() as f32; + + // upload new textures + self.renderer + .update_textures(&self.device, &self.queue, &textures_delta); + + // upload vertex, index, and uniform buffers + self.renderer.update_buffers( + &self.device, + &self.queue, + &meshes, + screen_size, + pixels_per_point, + ); + + let rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &self.blit_texture_view, + resolve_target: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(wgpu::Color { + r: 0.0, + g: 0.0, + b: 0.0, + a: 1.0, + }), + store: wgpu::StoreOp::Store, + }, + depth_slice: None, + })], + depth_stencil_attachment: None, + timestamp_writes: None, + label: Some("main render pass"), + occlusion_query_set: None, + }); + + self.renderer.render( + &mut rpass.forget_lifetime(), + &meshes, + screen_size, + pixels_per_point, + ); + + self.renderer.free_textures(&textures_delta) + } + + { + profiling::scope!("blit"); + self.texture_blitter.copy( + &self.device, + &mut encoder, + &self.blit_texture_view, + &surface_view, + ); + } + + self.queue.submit(std::iter::once(encoder.finish())); + output.present(); + + if suboptimal { + Err(wgpu::SurfaceError::Outdated) + } else { + Ok(()) + } + } +} + +fn create_blit_texture( + device: &wgpu::Device, + width: u32, + height: u32, + format: TextureFormat, +) -> (Texture, TextureView) { + let blit_texture = device.create_texture(&wgpu::TextureDescriptor { + label: Some("Blit Texture"), + size: wgpu::Extent3d { + width, + height, + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING, + view_formats: &[], + }); + + let blit_texture_view = blit_texture.create_view(&wgpu::TextureViewDescriptor::default()); + + (blit_texture, blit_texture_view) +} diff --git a/src/input.rs b/src/input.rs new file mode 100644 index 0000000..fd2b1e9 --- /dev/null +++ b/src/input.rs @@ -0,0 +1,295 @@ +use crate::dpi::PhysicalPoint; +use ahash::{HashMap, HashSet}; +use std::time::{Duration, Instant}; +use winit::{ + event::{KeyEvent, MouseButton, WindowEvent}, + keyboard::{KeyCode, ModifiersState, PhysicalKey}, +}; + +#[derive(Default)] +pub struct InputState { + key_modifiers: ModifiersState, + keys_pressed: HashSet, + mouse_pressed: HashSet, + mouse_last_pressed: HashMap, + cursor_pos: PhysicalPoint, +} + +impl InputState { + pub fn key_pressed(&self, code: KeyCode) -> bool { + self.keys_pressed.contains(&code) + } + + pub fn mouse_pressed(&self, button: MouseButton) -> bool { + self.mouse_pressed.contains(&button) + } + + pub fn mouse_pos(&self) -> PhysicalPoint { + self.cursor_pos + } + + pub fn modifiers(&self) -> ModifiersState { + self.key_modifiers + } + + pub fn on_window_event(&mut self, event: &WindowEvent) { + match event { + WindowEvent::ModifiersChanged(modifiers) => { + self.key_modifiers = modifiers.state(); + } + WindowEvent::CursorMoved { position, .. } => { + self.cursor_pos = PhysicalPoint::new(position.x as f32, position.y as f32); + } + WindowEvent::KeyboardInput { + event: + KeyEvent { + physical_key: PhysicalKey::Code(code), + state, + .. + }, + .. + } => { + if state.is_pressed() { + self.keys_pressed.insert(*code); + } else { + self.keys_pressed.remove(code); + } + } + WindowEvent::MouseInput { state, button, .. } => { + if state.is_pressed() { + self.mouse_pressed.insert(*button); + } else { + self.mouse_pressed.remove(button); + } + } + _ => {} + } + } + + pub fn is_double_click(&mut self, button: MouseButton) -> bool { + let now = Instant::now(); + let last = self.mouse_last_pressed.entry(button); + + match last { + std::collections::hash_map::Entry::Occupied(mut occupied_entry) => { + let last = occupied_entry.insert(now); + now.duration_since(last) < Duration::from_millis(400) + } + std::collections::hash_map::Entry::Vacant(vacant_entry) => { + vacant_entry.insert(now); + false + } + } + } +} + +pub fn str_as_keycode(s: &str) -> Option { + Some(match s.to_uppercase().as_str() { + // Letters + "A" => KeyCode::KeyA, + "B" => KeyCode::KeyB, + "C" => KeyCode::KeyC, + "D" => KeyCode::KeyD, + "E" => KeyCode::KeyE, + "F" => KeyCode::KeyF, + "G" => KeyCode::KeyG, + "H" => KeyCode::KeyH, + "I" => KeyCode::KeyI, + "J" => KeyCode::KeyJ, + "K" => KeyCode::KeyK, + "L" => KeyCode::KeyL, + "M" => KeyCode::KeyM, + "N" => KeyCode::KeyN, + "O" => KeyCode::KeyO, + "P" => KeyCode::KeyP, + "Q" => KeyCode::KeyQ, + "R" => KeyCode::KeyR, + "S" => KeyCode::KeyS, + "T" => KeyCode::KeyT, + "U" => KeyCode::KeyU, + "V" => KeyCode::KeyV, + "W" => KeyCode::KeyW, + "X" => KeyCode::KeyX, + "Y" => KeyCode::KeyY, + "Z" => KeyCode::KeyZ, + + // Digits + "0" => KeyCode::Digit0, + "1" => KeyCode::Digit1, + "2" => KeyCode::Digit2, + "3" => KeyCode::Digit3, + "4" => KeyCode::Digit4, + "5" => KeyCode::Digit5, + "6" => KeyCode::Digit6, + "7" => KeyCode::Digit7, + "8" => KeyCode::Digit8, + "9" => KeyCode::Digit9, + + // Modifiers + "SHIFT" => KeyCode::ShiftLeft, + "CTRL" => KeyCode::ControlLeft, + "ALT" => KeyCode::AltLeft, + + // F Keys + "F1" => KeyCode::F1, + "F2" => KeyCode::F2, + "F3" => KeyCode::F3, + "F4" => KeyCode::F4, + "F5" => KeyCode::F5, + "F6" => KeyCode::F6, + "F7" => KeyCode::F7, + "F8" => KeyCode::F8, + "F9" => KeyCode::F9, + "F10" => KeyCode::F10, + "F11" => KeyCode::F11, + "F12" => KeyCode::F12, + + // Rest + " " => KeyCode::Space, + "BACK" => KeyCode::Backspace, + "TAB" => KeyCode::Tab, + "RETURN" => KeyCode::Enter, + "ESCAPE" => KeyCode::Escape, + "PAUSE" => KeyCode::Pause, + "PAGEUP" => KeyCode::PageUp, + "PAGEDOWN" => KeyCode::PageDown, + "END" => KeyCode::End, + "HOME" => KeyCode::Home, + "PRINTSCREEN" => KeyCode::PrintScreen, + "INSERT" => KeyCode::Insert, + "DELETE" => KeyCode::Delete, + "UP" => KeyCode::ArrowUp, + "DOWN" => KeyCode::ArrowDown, + "LEFT" => KeyCode::ArrowLeft, + "RIGHT" => KeyCode::ArrowRight, + "NUMLOCK" => KeyCode::NumLock, + "SCROLL" => KeyCode::ScrollLock, + + _ => return None, + }) +} + +pub fn keycode_as_str(code: KeyCode) -> Option { + Some( + match code { + // Letters + KeyCode::KeyA => "a", + KeyCode::KeyB => "b", + KeyCode::KeyC => "c", + KeyCode::KeyD => "d", + KeyCode::KeyE => "e", + KeyCode::KeyF => "f", + KeyCode::KeyG => "g", + KeyCode::KeyH => "h", + KeyCode::KeyI => "i", + KeyCode::KeyJ => "j", + KeyCode::KeyK => "k", + KeyCode::KeyL => "l", + KeyCode::KeyM => "m", + KeyCode::KeyN => "n", + KeyCode::KeyO => "o", + KeyCode::KeyP => "p", + KeyCode::KeyQ => "q", + KeyCode::KeyR => "r", + KeyCode::KeyS => "s", + KeyCode::KeyT => "t", + KeyCode::KeyU => "u", + KeyCode::KeyV => "v", + KeyCode::KeyW => "w", + KeyCode::KeyX => "x", + KeyCode::KeyY => "y", + KeyCode::KeyZ => "z", + + // Digits + KeyCode::Digit0 => "0", + KeyCode::Digit1 => "1", + KeyCode::Digit2 => "2", + KeyCode::Digit3 => "3", + KeyCode::Digit4 => "4", + KeyCode::Digit5 => "5", + KeyCode::Digit6 => "6", + KeyCode::Digit7 => "7", + KeyCode::Digit8 => "8", + KeyCode::Digit9 => "9", + + // Modifiers + KeyCode::ShiftLeft => "SHIFT", + KeyCode::ControlLeft => "CTRL", + KeyCode::AltLeft => "ALT", + + // F Keys + KeyCode::F1 => "F1", + KeyCode::F2 => "F2", + KeyCode::F3 => "F3", + KeyCode::F4 => "F4", + KeyCode::F5 => "F5", + KeyCode::F6 => "F6", + KeyCode::F7 => "F7", + KeyCode::F8 => "F8", + KeyCode::F9 => "F9", + KeyCode::F10 => "F10", + KeyCode::F11 => "F11", + KeyCode::F12 => "F12", + + // Rest + KeyCode::Space => " ", + KeyCode::Backspace => "BACK", + KeyCode::Tab => "TAB", + KeyCode::Enter => "RETURN", + KeyCode::Escape => "ESCAPE", + KeyCode::Pause => "PAUSE", + KeyCode::PageUp => "PAGEUP", + KeyCode::PageDown => "PAGEDOWN", + KeyCode::End => "END", + KeyCode::Home => "HOME", + KeyCode::PrintScreen => "PRINTSCREEN", + KeyCode::Insert => "INSERT", + KeyCode::Delete => "DELETE", + KeyCode::ArrowUp => "UP", + KeyCode::ArrowDown => "DOWN", + KeyCode::ArrowLeft => "LEFT", + KeyCode::ArrowRight => "RIGHT", + KeyCode::NumLock => "NUMLOCK", + KeyCode::ScrollLock => "SCROLL", + + KeyCode::Equal => "+", // This is what PoB does + KeyCode::Minus => "-", + KeyCode::Comma => ",", + KeyCode::Period => ".", + KeyCode::Slash => "/", + + KeyCode::NumpadAdd => "+", + KeyCode::NumpadSubtract => "-", + KeyCode::NumpadEnter => "RETURN", + KeyCode::Numpad0 => "0", + + _ => return None, + } + .to_string(), + ) +} + +pub fn str_as_mousebutton(s: &str) -> Option { + Some(match s.to_uppercase().as_str() { + "LEFTBUTTON" => MouseButton::Left, + "RIGHTBUTTON" => MouseButton::Right, + "MIDDLEBUTTON" => MouseButton::Middle, + "MOUSE4" => MouseButton::Back, + "MOUSE5" => MouseButton::Forward, + _ => return None, + }) +} + +pub fn mousebutton_as_str(button: MouseButton) -> Option { + Some( + match button { + MouseButton::Left => "LEFTBUTTON", + MouseButton::Right => "RIGHTBUTTON", + MouseButton::Middle => "MIDDLEBUTTON", + MouseButton::Back => "MOUSE4", + MouseButton::Forward => "MOUSE5", + _ => return None, + } + .to_string(), + ) +} diff --git a/src/installer.rs b/src/installer.rs new file mode 100644 index 0000000..edb5d29 --- /dev/null +++ b/src/installer.rs @@ -0,0 +1,135 @@ +use crate::args::Game; +use anyhow::bail; +use flate2::read::GzDecoder; +use std::{ + fs::{self}, + io::copy, + path::{Path, PathBuf}, +}; + +const REPO_NAME: &str = "meehl/RustyPathOfBuilding"; + +pub fn run_installer() -> anyhow::Result<()> { + let script_dir = Game::script_dir(); + + // run installer iff Launch.lua doesn't exist, meaning this is likely the first run + if script_dir.join("Launch.lua").exists() { + return Ok(()); + } + + download_path_of_building(script_dir.as_path())?; + replace_manifest(script_dir.as_path())?; + + Ok(()) +} + +/// Download latest release of Path of Building +fn download_path_of_building>(target_dir: P) -> anyhow::Result<()> { + log::info!("Downloading latest release of Path of Building..."); + + let repo = match Game::current() { + Game::Poe1 => "PathOfBuildingCommunity/PathOfBuilding", + Game::Poe2 => "PathOfBuildingCommunity/PathOfBuilding-PoE2", + }; + let url = format!( + "https://github.com/{}/archive/refs/heads/master.tar.gz", + repo + ); + + let response = ureq::get(url).call()?; + + let body_reader = response.into_body().into_reader(); + let gz_decoder = GzDecoder::new(body_reader); + let mut archive = tar::Archive::new(gz_decoder); + + for file in archive.entries()? { + let mut file = file?; + let file_path = file.path()?; + let components: Vec<_> = file_path.components().collect(); + + let target_path = match components.len() { + 0..=1 => None, + // put these into target_dir/ + 2 => { + let filename = components[1].as_os_str(); + if filename == "manifest.xml" + || filename == "help.txt" + || filename == "changelog.txt" + || filename == "LICENSE.md" + { + Some(target_dir.as_ref().join(filename)) + } else { + None + } + } + // put lua runtime files into target_dir/lua/ + 3.. => { + if components[1].as_os_str() == "src" + || (components[1].as_os_str() == "runtime" + && components[2].as_os_str() == "lua") + { + Some( + target_dir + .as_ref() + .join(components[2..].iter().collect::()), + ) + } else { + None + } + } + }; + + // create needed directories and extract + if let Some(target_path) = target_path { + if let Some(parent) = target_path.parent() { + fs::create_dir_all(parent)?; + } + file.unpack(&target_path)?; + } + } + + Ok(()) +} + +/// Replace manifest and UpdateCheck with RustyPathOfBuilding's modified versions +/// This is needed to make updating work without writing our own update system. +fn replace_manifest>(target_dir: P) -> anyhow::Result<()> { + log::info!("Replacing manifest..."); + + let game_path = match Game::current() { + Game::Poe1 => "lua/poe1", + Game::Poe2 => "lua/poe2", + }; + + // Download on overwrite files + download_file( + &format!( + "https://raw.githubusercontent.com/{REPO_NAME}/master/{}/{}", + game_path, "manifest.xml" + ), + target_dir.as_ref().join("manifest.xml"), + )?; + + download_file( + &format!( + "https://raw.githubusercontent.com/{REPO_NAME}/master/{}/{}", + game_path, "UpdateCheck.lua" + ), + target_dir.as_ref().join("UpdateCheck.lua"), + )?; + + Ok(()) +} + +fn download_file>(url: &str, file_path: P) -> anyhow::Result<()> { + let response = ureq::get(url).call()?; + + if response.status().is_success() { + let body = response.into_body(); + let mut file = fs::File::create(file_path)?; + copy(&mut body.into_reader(), &mut file)?; + Ok(()) + } else { + bail!("Unable to download: {}", url); + } +} diff --git a/src/layers.rs b/src/layers.rs new file mode 100644 index 0000000..3cc2eab --- /dev/null +++ b/src/layers.rs @@ -0,0 +1,102 @@ +use std::collections::BTreeMap; + +use crate::{ + dpi::LogicalRect, + math::Rect, + renderer::primitives::{ + ClippedPrimitive, DrawPrimitive, QuadPrimitive, RectPrimitive, TextPrimitive, + }, +}; + +/// Holds the draw primitives for each layer. +/// +/// Adding a primitive places it in currently set layer. Positions are interpreted as being relative to +/// the current viewport. They are translated into absolute positions (screen positions) and +/// clipped by the viewport. +pub struct Layers { + layers: BTreeMap<(i32, i32), Vec>, + current_layer: (i32, i32), + viewport: LogicalRect, +} + +impl Layers { + pub fn new() -> Self { + Self { + layers: Default::default(), + current_layer: (0, 0), + viewport: Rect::zero(), + } + } + + pub fn reset(&mut self) { + self.current_layer = (0, 0); + self.layers.clear(); + } + + /// Consume primitives and return an iterator over them in drawing order. + pub fn consume_layers(&mut self) -> impl Iterator { + let layers = std::mem::take(&mut self.layers); + layers.into_values().flatten() + } + + pub fn set_viewport(&mut self, viewport: LogicalRect) { + self.viewport = viewport; + } + + pub fn set_draw_layer(&mut self, layer: i32, sublayer: i32) { + self.current_layer = (layer, sublayer); + } + + pub fn set_draw_sublayer(&mut self, sublayer: i32) { + self.set_draw_layer(self.current_layer.0, sublayer); + } + + pub fn add_rect(&mut self, mut rect: RectPrimitive) { + rect.translate(self.viewport.min.to_vector()); + + let clipped_primitive = ClippedPrimitive { + clip_rect: self.viewport, + primitive: DrawPrimitive::Rect(rect), + }; + + self.push(clipped_primitive); + } + + pub fn add_quad(&mut self, mut quad: QuadPrimitive) { + quad.translate(self.viewport.min.to_vector()); + + let clipped_primitive = ClippedPrimitive { + clip_rect: self.viewport, + primitive: DrawPrimitive::Quad(quad), + }; + + self.push(clipped_primitive); + } + + pub fn add_text(&mut self, mut text: TextPrimitive, is_absolute_position: bool) { + if !is_absolute_position { + text.translate(self.viewport.min.to_vector()); + }; + + let clipped_primitive = ClippedPrimitive { + clip_rect: self.viewport, + primitive: DrawPrimitive::Text(text), + }; + + self.push(clipped_primitive); + } + + #[inline] + fn push(&mut self, clipped_primitive: ClippedPrimitive) { + self.layers + .entry(self.current_layer) + .or_default() + .push(clipped_primitive); + } +} + +impl std::hash::Hash for Layers { + fn hash(&self, state: &mut H) { + self.layers.hash(state); + } +} diff --git a/src/lua.rs b/src/lua.rs new file mode 100644 index 0000000..bfda4a9 --- /dev/null +++ b/src/lua.rs @@ -0,0 +1,157 @@ +use std::{cell::RefCell, rc::Rc}; + +use clap::Parser; +use mlua::{Lua, Result as LuaResult, Table}; + +use crate::{ + Game, + api::{self, get_callback}, + args::Args, + subscript::{NativeMultiValue, SubscriptManager, SubscriptResult, register_subscript_globals}, + util::{change_working_directory, get_executable_dir}, +}; + +pub struct LuaInstance { + lua: Lua, + subscript_manager: Rc>, +} + +impl LuaInstance { + pub fn new() -> anyhow::Result { + let subscript_manager = Rc::new(RefCell::new(SubscriptManager::new())); + + let lua = Self::create_lua_state()?; + register_subscript_globals(&lua, &subscript_manager)?; + + let instance = Self { + lua, + subscript_manager, + }; + + instance.init()?; + + Ok(instance) + } + + fn create_lua_state() -> LuaResult { + // SAFETY: use `unsafe_new` to allow loading of C modules + let lua = unsafe { Lua::unsafe_new() }; + + // expose build arg to lua + let args = Args::parse(); + let args_table = lua.create_sequence_from(std::iter::once(args.build_path))?; + lua.globals().set("arg", args_table)?; + + // add ./lua to package.path and package.cpath + Self::register_package_paths(&lua)?; + + // register callbacks + api::register_globals(&lua)?; + + Ok(lua) + } + + pub fn init(&self) -> LuaResult<()> { + let script_dir = Game::script_dir(); + change_working_directory(script_dir.as_path())?; + self.load(script_dir.join("Launch.lua")).exec()?; + self.on_init()?; + Ok(()) + } + + pub fn restart(&mut self) -> LuaResult<()> { + self.lua = Self::create_lua_state()?; + register_subscript_globals(&self.lua, &self.subscript_manager)?; + self.init()?; + + Ok(()) + } + + /// Run functions for subscripts and handle their completion/failure. + pub fn handle_subscripts(&self) { + let subscript_events = self.subscript_manager.borrow_mut().process(self); + + // Handle finished/errored subscripts. + for event in subscript_events { + match event { + SubscriptResult::SubscriptFinished { id, return_values } => { + self.on_sub_finished(id, return_values).unwrap(); + } + SubscriptResult::SubscriptError { id, error } => { + self.on_sub_error(id, &error).unwrap(); + } + } + } + } + + fn on_init(&self) -> LuaResult<()> { + let on_init = get_callback(&self.lua, "OnInit")?; + on_init.call::<()>(()) + } + + pub fn on_frame(&self) -> LuaResult<()> { + profiling::scope!("on_frame"); + + let on_frame = get_callback(&self.lua, "OnFrame")?; + on_frame.call::<()>(()) + } + + pub fn on_char(&self, ch: &str) -> LuaResult<()> { + let on_char = get_callback(&self.lua, "OnChar")?; + on_char.call::<()>(ch) + } + + pub fn on_key_down(&self, key: &str, is_double_click: bool) -> LuaResult<()> { + let on_key_down = get_callback(&self.lua, "OnKeyDown")?; + on_key_down.call::<()>((key, is_double_click)) + } + + pub fn on_key_up(&self, key: &str) -> LuaResult<()> { + let on_key_up = get_callback(&self.lua, "OnKeyUp")?; + on_key_up.call::<()>(key) + } + + pub fn on_sub_finished(&self, id: u64, return_values: NativeMultiValue) -> LuaResult<()> { + let on_sub_finished = get_callback(&self.lua, "OnSubFinished")?; + on_sub_finished.call::<()>((id, return_values)) + } + + pub fn on_sub_error(&self, id: u64, error: &str) -> LuaResult<()> { + let on_sub_error = get_callback(&self.lua, "OnSubError")?; + on_sub_error.call::<()>((id, error)) + } + + pub fn on_exit(&self) -> LuaResult<()> { + let on_exit = get_callback(&self.lua, "OnExit")?; + on_exit.call::<()>(()) + } + + pub fn register_package_paths(lua: &Lua) -> LuaResult<()> { + let script_dir = Game::script_dir(); + let package: Table = lua.globals().get("package")?; + let mut package_path: String = package.get("path")?; + package_path.push(';'); + package_path.push_str(script_dir.join("lua/?.lua").to_str().unwrap()); + package_path.push(';'); + package_path.push_str(script_dir.join("lua/?/init.lua").to_str().unwrap()); + package.set("path", package_path)?; + + let mut package_cpath: String = package.get("cpath")?; + let exe_dir = get_executable_dir()?; + package_cpath.push(';'); + #[cfg(target_os = "linux")] + package_cpath.push_str(exe_dir.join("lua/?.so").to_str().unwrap()); + #[cfg(target_os = "windows")] + package_cpath.push_str(exe_dir.join("lua/?.dll").to_str().unwrap()); + package.set("cpath", package_cpath)?; + + Ok(()) + } +} + +impl std::ops::Deref for LuaInstance { + type Target = Lua; + fn deref(&self) -> &Self::Target { + &self.lua + } +} diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..73e8987 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,49 @@ +use crate::app::App; +use crate::args::{Args, Game}; +use crate::installer::run_installer; +use clap::Parser; +use winit::event_loop::EventLoop; + +mod api; +mod app; +mod args; +mod color; +mod context; +mod dpi; +mod fonts; +mod gfx; +mod input; +mod installer; +mod layers; +mod lua; +mod math; +mod renderer; +mod subscript; +mod util; +mod worker_pool; + +fn main() -> anyhow::Result<()> { + profiling::register_thread!("Main Thread"); + env_logger::init(); + + #[cfg(feature = "profile-with-puffin")] + let _puffin_server = { + let server_addr = format!("127.0.0.1:{}", puffin_http::DEFAULT_PORT); + let server = puffin_http::Server::new(&server_addr).unwrap(); + eprintln!("Serving profiling data on {server_addr}. Run `puffin_viewer` to view it."); + profiling::puffin::set_scopes_on(true); + server + }; + + let args = Args::parse(); + Game::init(args.game); + + run_installer()?; + + let mut app = App::new()?; + + let event_loop = EventLoop::with_user_event().build()?; + event_loop.run_app(&mut app)?; + + Ok(()) +} diff --git a/src/math.rs b/src/math.rs new file mode 100644 index 0000000..0ba7ab9 --- /dev/null +++ b/src/math.rs @@ -0,0 +1,39 @@ +pub use euclid::Box2D as Rect; +pub use euclid::Point2D as Point; +pub use euclid::Size2D as Size; +pub use euclid::Vector2D as Vector; +pub use quad::Quad; + +mod quad; + +pub trait Corners { + fn top_left(&self) -> Point; + fn top_right(&self) -> Point; + fn bottom_left(&self) -> Point; + fn bottom_right(&self) -> Point; +} + +impl Corners for Rect +where + T: Copy, +{ + #[inline] + fn top_left(&self) -> Point { + self.min + } + + #[inline] + fn top_right(&self) -> Point { + Point::new(self.max.x, self.min.y) + } + + #[inline] + fn bottom_left(&self) -> Point { + Point::new(self.min.x, self.max.y) + } + + #[inline] + fn bottom_right(&self) -> Point { + self.max + } +} diff --git a/src/math/quad.rs b/src/math/quad.rs new file mode 100644 index 0000000..12d6434 --- /dev/null +++ b/src/math/quad.rs @@ -0,0 +1,123 @@ +use crate::math::{Point, Size, Vector}; +use bytemuck::{Pod, Zeroable}; +use euclid::num::Zero; +use std::fmt; +use std::hash::Hash; +use std::ops::Add; + +#[repr(C)] +pub struct Quad { + pub p0: Point, + pub p1: Point, + pub p2: Point, + pub p3: Point, +} + +impl Copy for Quad {} + +impl Clone for Quad { + fn clone(&self) -> Self { + Self { + p0: self.p0.clone(), + p1: self.p1.clone(), + p2: self.p2.clone(), + p3: self.p3.clone(), + } + } +} + +impl Eq for Quad where T: Eq {} + +impl PartialEq for Quad +where + T: PartialEq, +{ + fn eq(&self, other: &Self) -> bool { + self.p0 == other.p0 && self.p1 == other.p1 && self.p2 == other.p2 && self.p3 == other.p3 + } +} + +impl fmt::Debug for Quad { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_tuple("Quad") + .field(&self.p0) + .field(&self.p1) + .field(&self.p2) + .field(&self.p3) + .finish() + } +} + +impl Default for Quad { + fn default() -> Self { + Self::new( + Default::default(), + Default::default(), + Default::default(), + Default::default(), + ) + } +} + +impl Hash for Quad +where + T: Hash, +{ + fn hash(&self, state: &mut H) { + self.p0.hash(state); + self.p1.hash(state); + self.p2.hash(state); + self.p3.hash(state); + } +} + +// SAFETY: PhantomData in Point is zero-sized and repr(C) guarantees consistent layout +unsafe impl Zeroable for Quad {} +unsafe impl Pod for Quad {} + +impl Quad { + #[inline] + pub const fn new(p0: Point, p1: Point, p2: Point, p3: Point) -> Self { + Self { p0, p1, p2, p3 } + } +} + +impl Quad +where + T: Copy, +{ + /// Creates a `Quad` of the given size, at offset zero. + #[inline] + pub fn from_size(size: Size) -> Self + where + T: Zero, + { + Quad { + p0: Point::zero(), + p1: Point::new(size.width, Zero::zero()), + p2: Point::new(size.width, size.height), + p3: Point::new(Zero::zero(), size.height), + } + } +} + +impl Quad +where + T: Zero, +{ + /// Constructor, setting all points to zero. + pub fn zero() -> Self { + Quad::new(Point::zero(), Point::zero(), Point::zero(), Point::zero()) + } +} + +impl Quad +where + T: Copy + Add, +{ + /// Returns the same quad, translated by a vector. + #[inline] + pub fn translate(&self, by: Vector) -> Self { + Self::new(self.p0 + by, self.p1 + by, self.p2 + by, self.p3 + by) + } +} diff --git a/src/renderer.rs b/src/renderer.rs new file mode 100644 index 0000000..30d990a --- /dev/null +++ b/src/renderer.rs @@ -0,0 +1,635 @@ +use crate::{ + dpi::{ConvertToLogical, ConvertToPhysical, LogicalSize, PhysicalRect, PhysicalSize}, + math::Point, + renderer::{ + image::ImageData, + mesh::{ClippedMesh, Vertex}, + textures::{TextureId, TextureOptions, TexturesDelta}, + }, +}; +use ahash::HashMap; +use std::{borrow::Cow, num::NonZeroU64, ops::Range}; +use wgpu::util::DeviceExt; + +pub mod image; +pub mod mesh; +mod mipmap; +pub mod primitives; +pub mod tessellator; +pub mod textures; + +#[derive(Debug)] +struct Texture { + texture: wgpu::Texture, + bind_group: wgpu::BindGroup, +} + +#[repr(C)] +#[derive(Clone, Copy, Debug, PartialEq, bytemuck::Pod, bytemuck::Zeroable)] +struct Globals { + screen_size: LogicalSize, +} + +pub struct Renderer { + pipeline: wgpu::RenderPipeline, + + index_buffer: SlicedBuffer, + vertex_buffer: SlicedBuffer, + + globals_buffer: wgpu::Buffer, + previous_globals: Globals, + globals_bind_group: wgpu::BindGroup, + texture_bind_group_layout: wgpu::BindGroupLayout, + + textures: HashMap, + samplers: HashMap, +} + +impl Renderer { + pub fn new( + device: &wgpu::Device, + output_color_format: wgpu::TextureFormat, + output_depth_format: Option, + ) -> Self { + let shader_module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("main_shader_module"), + source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("renderer/main.wgsl"))), + }); + + let uniform_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("globals_uniform_buffer"), + contents: bytemuck::cast_slice(&[Globals { + screen_size: LogicalSize::zero(), + }]), + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + }); + + let globals_bind_group_layout = + device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("globals_uniform_bind_group_layout"), + entries: &[wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::VERTEX | wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Buffer { + has_dynamic_offset: false, + min_binding_size: NonZeroU64::new(std::mem::size_of::() as _), + ty: wgpu::BufferBindingType::Uniform, + }, + count: None, + }], + }); + + let globals_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("globals_uniform_bind_group"), + layout: &globals_bind_group_layout, + entries: &[wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { + buffer: &uniform_buffer, + offset: 0, + size: None, + }), + }], + }); + + 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 { + multisampled: false, + sample_type: wgpu::TextureSampleType::Float { filterable: true }, + view_dimension: wgpu::TextureViewDimension::D2Array, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 1, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), + count: None, + }, + ], + }); + + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("pipeline_layout"), + bind_group_layouts: &[&globals_bind_group_layout, &texture_bind_group_layout], + push_constant_ranges: &[], + }); + + let depth_stencil = output_depth_format.map(|format| wgpu::DepthStencilState { + format, + depth_write_enabled: false, + depth_compare: wgpu::CompareFunction::Always, + stencil: wgpu::StencilState::default(), + bias: wgpu::DepthBiasState::default(), + }); + + let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("render_pipeline"), + layout: Some(&pipeline_layout), + vertex: wgpu::VertexState { + entry_point: Some("vs_main"), + module: &shader_module, + buffers: &[wgpu::VertexBufferLayout { + // 4x f32, 2x u32 -> 6 * 4 bytes + array_stride: 6 * 4, + step_mode: wgpu::VertexStepMode::Vertex, + // 0: vec2 position + // 1: vec2 texture coordinates + // 2: uint color + // 3: uint layer_idx + attributes: &wgpu::vertex_attr_array![0 => Float32x2, 1 => Float32x2, 2 => Uint32, 3 => Uint32], + }], + compilation_options: wgpu::PipelineCompilationOptions::default() + }, + primitive: wgpu::PrimitiveState { + topology: wgpu::PrimitiveTopology::TriangleList, + unclipped_depth: false, + conservative: false, + cull_mode: None, + front_face: wgpu::FrontFace::default(), + polygon_mode: wgpu::PolygonMode::default(), + strip_index_format: None, + }, + depth_stencil, + multisample: wgpu::MultisampleState { + alpha_to_coverage_enabled: false, + count: 1, + mask: !0, + }, + fragment: Some(wgpu::FragmentState { + module: &shader_module, + entry_point: Some("fs_main"), + targets: &[Some(wgpu::ColorTargetState { + format: output_color_format, + blend: Some(wgpu::BlendState::ALPHA_BLENDING), + write_mask: wgpu::ColorWrites::ALL, + })], + compilation_options: wgpu::PipelineCompilationOptions::default() + }), + multiview: None, + cache: None, + }); + + let vertex_buffer = SlicedBuffer::new( + device, + wgpu::BufferUsages::VERTEX, + NonZeroU64::new(2048).expect("2048 is non-zero"), + NonZeroU64::new(std::mem::size_of::() as u64) + .expect("size of vertex is non-zero"), + ); + let index_buffer = SlicedBuffer::new( + device, + wgpu::BufferUsages::INDEX, + NonZeroU64::new(2048 * 3).expect("2048 * 3 is non-zero"), + NonZeroU64::new(std::mem::size_of::() as u64).expect("size of u32 is non-zero"), + ); + + Self { + pipeline, + vertex_buffer, + index_buffer, + globals_buffer: uniform_buffer, + previous_globals: Globals { + screen_size: LogicalSize::zero(), + }, + globals_bind_group, + texture_bind_group_layout, + textures: HashMap::default(), + samplers: HashMap::default(), + } + } + + pub fn render( + &self, + render_pass: &mut wgpu::RenderPass<'static>, + paint_jobs: &[ClippedMesh], + screen_size: PhysicalSize, + pixels_per_point: f32, + ) { + profiling::scope!("render"); + + let screen_rect = PhysicalRect::from_origin_and_size(Point::zero(), screen_size); + let mut index_buffer_slices = self.index_buffer.slices.iter(); + let mut vertex_buffer_slices = self.vertex_buffer.slices.iter(); + + render_pass.set_viewport( + 0.0, + 0.0, + screen_size.width as f32, + screen_size.height as f32, + 0.0, + 1.0, + ); + render_pass.set_pipeline(&self.pipeline); + render_pass.set_bind_group(0, &self.globals_bind_group, &[]); + + for ClippedMesh { clip_rect, mesh } in paint_jobs { + let phys_clip_rect = clip_rect.to_physical::(pixels_per_point).round(); + let scissor = phys_clip_rect + // NOTE: can't cast to u32 directly because negative values cause a panic + .cast::() + .intersection(&screen_rect.to_i32()) + .map(|s| s.to_u32()); + + let Some(scissor) = scissor else { + index_buffer_slices.next().unwrap(); + vertex_buffer_slices.next().unwrap(); + continue; + }; + + render_pass.set_scissor_rect( + scissor.min.x, + scissor.min.y, + scissor.width(), + scissor.height(), + ); + + let index_buffer_slice = index_buffer_slices.next().unwrap(); + let vertex_buffer_slice = vertex_buffer_slices.next().unwrap(); + + if let Some(Texture { bind_group, .. }) = self.textures.get(&mesh.texture_id) { + render_pass.set_bind_group(1, bind_group, &[]); + render_pass.set_index_buffer( + self.index_buffer + .buffer + .slice(index_buffer_slice.start as u64..index_buffer_slice.end as u64), + wgpu::IndexFormat::Uint32, + ); + render_pass.set_vertex_buffer( + 0, + self.vertex_buffer + .buffer + .slice(vertex_buffer_slice.start as u64..vertex_buffer_slice.end as u64), + ); + render_pass.draw_indexed(0..mesh.indices.len() as u32, 0, 0..1); + } else { + log::warn!("Missing texture: {:?}", mesh.texture_id); + } + } + + render_pass.set_scissor_rect(0, 0, screen_size.width, screen_size.height); + } + + /// Uploads texture data. + /// Needs to be called before [`Self::render`]. + pub fn update_textures( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + textures_delta: &TexturesDelta, + ) { + profiling::scope!("update_textures"); + + for (id, image_delta) in &textures_delta.update { + let ImageData { + format, + width, + height, + array_layers, + mipmap_count, + data_order, + ref bytes, + } = image_delta.image; + + let size = wgpu::Extent3d { + width, + height, + depth_or_array_layers: array_layers, + }; + + // only generate mipmaps for uncompressed images that don't already have mipmaps + let gen_mipmaps = image_delta.options.generate_mipmaps + && mipmap_count.get() == 1 + && !format.is_compressed(); + + let mip_level_count = if gen_mipmaps { + size.max_mips(wgpu::TextureDimension::D2) + } else { + mipmap_count.get() + }; + + let label_str = format!("texture_{id:?}"); + let label = Some(label_str.as_str()); + + let texture = create_texture_with_data( + device, + queue, + &wgpu::TextureDescriptor { + label, + size, + mip_level_count, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format, + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, + view_formats: &[format.add_srgb_suffix()], + }, + data_order.into(), + bytes, + gen_mipmaps, + ); + + if gen_mipmaps { + mipmap::generate_mipmap_chain(queue, &texture, bytes); + } + + let texture_view = texture.create_view(&wgpu::TextureViewDescriptor { + dimension: Some(wgpu::TextureViewDimension::D2Array), + ..Default::default() + }); + + let sampler = self + .samplers + .entry(image_delta.options) + .or_insert_with(|| create_sampler(image_delta.options, device)); + + let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label, + layout: &self.texture_bind_group_layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::TextureView(&texture_view), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::Sampler(sampler), + }, + ], + }); + + self.textures.insert( + *id, + Texture { + texture, + bind_group, + }, + ); + } + } + + pub fn free_textures(&mut self, textures_delta: &TexturesDelta) { + profiling::scope!("free_textures"); + + for id in &textures_delta.free { + if let Some(texture) = self.textures.remove(id) { + texture.texture.destroy(); + } + } + } + + /// Updates the vertex, index, and uniform buffers. + /// Needs to be called before [`Self::render`]. + pub fn update_buffers( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + paint_jobs: &[ClippedMesh], + screen_size: PhysicalSize, + pixels_per_point: f32, + ) { + profiling::scope!("update_buffers"); + + let uniform_buffer_content = Globals { + screen_size: screen_size.to_logical(pixels_per_point), + }; + + // update globals uniform buffer + if uniform_buffer_content != self.previous_globals { + queue.write_buffer( + &self.globals_buffer, + 0, + bytemuck::cast_slice(&[uniform_buffer_content]), + ); + self.previous_globals = uniform_buffer_content; + } + + // count how many vertices & indices need to be rendered + let (vertex_count, index_count) = { + paint_jobs.iter().fold((0, 0), |acc, clipped_mesh| { + ( + acc.0 + clipped_mesh.mesh.vertices.len(), + acc.1 + clipped_mesh.mesh.indices.len(), + ) + }) + }; + + // update index and vertex buffers + if index_count > 0 && vertex_count > 0 { + self.index_buffer.slices.clear(); + self.vertex_buffer.slices.clear(); + + let mut staging_index_buffer = self.index_buffer.create_staging_buffer( + device, + queue, + NonZeroU64::new(index_count as u64).expect("index_count > 0"), + ); + let mut staging_vertex_buffer = self.vertex_buffer.create_staging_buffer( + device, + queue, + NonZeroU64::new(vertex_count as u64).expect("vertex_count > 0"), + ); + + let mut index_offset = 0; + let mut vertex_offset = 0; + for ClippedMesh { mesh, .. } in paint_jobs { + { + let size = mesh.indices.len() * std::mem::size_of::(); + let slice = index_offset..(index_offset + size); + staging_index_buffer[slice.clone()] + .copy_from_slice(bytemuck::cast_slice(&mesh.indices)); + self.index_buffer.slices.push(slice); + index_offset += size; + } + { + let size = mesh.vertices.len() * std::mem::size_of::(); + let slice = vertex_offset..(vertex_offset + size); + staging_vertex_buffer[slice.clone()] + .copy_from_slice(bytemuck::cast_slice(&mesh.vertices)); + self.vertex_buffer.slices.push(slice); + vertex_offset += size; + } + } + } + } +} + +struct SlicedBuffer { + buffer: wgpu::Buffer, + slices: Vec>, + size: wgpu::BufferSize, + usage: wgpu::BufferUsages, + stride: NonZeroU64, +} + +impl SlicedBuffer { + fn new( + device: &wgpu::Device, + usage: wgpu::BufferUsages, + start_capacity: NonZeroU64, + stride: NonZeroU64, + ) -> Self { + let size = start_capacity.checked_mul(stride).unwrap(); + + let buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: None, + usage: usage | wgpu::BufferUsages::COPY_DST, + size: size.get(), + mapped_at_creation: false, + }); + + Self { + buffer, + slices: Vec::with_capacity(64), + size, + usage, + stride, + } + } + + fn create_staging_buffer( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + required_capacity: NonZeroU64, + ) -> wgpu::QueueWriteBufferView { + let required_size = required_capacity.checked_mul(self.stride).unwrap(); + + // resize buffer to required size + if self.size < required_size { + self.buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: None, + usage: self.usage | wgpu::BufferUsages::COPY_DST, + size: required_size.get(), + mapped_at_creation: false, + }); + self.size = required_size; + } + + let staging_buffer = queue.write_buffer_with(&self.buffer, 0, required_size); + let Some(staging_buffer) = staging_buffer else { + panic!("Failed to create staging buffer!"); + }; + staging_buffer + } +} + +fn create_sampler(options: TextureOptions, device: &wgpu::Device) -> wgpu::Sampler { + let TextureOptions { + magnification, + minification, + wrap_mode, + mipmap_mode, + .. + } = options; + device.create_sampler(&wgpu::SamplerDescriptor { + label: Some(&format!( + "sampler (mag: {magnification:?}, min {minification:?})" + )), + mag_filter: magnification, + min_filter: minification, + address_mode_u: wrap_mode, + address_mode_v: wrap_mode, + mipmap_filter: mipmap_mode, + ..Default::default() + }) +} + +/// Adapted from `wgpu::Device::create_texture_with_data`. +/// Doesn't upload any data for mip level > 0 if skip_mipmaps is true. +fn create_texture_with_data( + device: &wgpu::Device, + queue: &wgpu::Queue, + desc: &wgpu::TextureDescriptor<'_>, + order: wgpu::wgt::TextureDataOrder, + data: &[u8], + skip_mipmaps: bool, +) -> wgpu::Texture { + // Implicitly add the COPY_DST usage + let mut desc = desc.to_owned(); + desc.usage |= wgpu::TextureUsages::COPY_DST; + let texture = device.create_texture(&desc); + + // Will return None only if it's a combined depth-stencil format + // If so, default to 4, validation will fail later anyway since the depth or stencil + // aspect needs to be written to individually + let block_size = desc.format.block_copy_size(None).unwrap_or(4); + let (block_width, block_height) = desc.format.block_dimensions(); + let layer_iterations = desc.array_layer_count(); + + let outer_iteration; + let inner_iteration; + match order { + wgpu::wgt::TextureDataOrder::LayerMajor => { + outer_iteration = layer_iterations; + inner_iteration = desc.mip_level_count; + } + wgpu::wgt::TextureDataOrder::MipMajor => { + outer_iteration = desc.mip_level_count; + inner_iteration = layer_iterations; + } + } + + let mut binary_offset = 0; + for outer in 0..outer_iteration { + for inner in 0..inner_iteration { + let (layer, mip) = match order { + wgpu::wgt::TextureDataOrder::LayerMajor => (outer, inner), + wgpu::wgt::TextureDataOrder::MipMajor => (inner, outer), + }; + + let mut mip_size = desc.mip_level_size(mip).unwrap(); + // copying layers separately + if desc.dimension != wgpu::wgt::TextureDimension::D3 { + mip_size.depth_or_array_layers = 1; + } + + // When uploading mips of compressed textures and the mip is supposed to be + // a size that isn't a multiple of the block size, the mip needs to be uploaded + // as its "physical size" which is the size rounded up to the nearest block size. + let mip_physical = mip_size.physical_size(desc.format); + + // All these calculations are performed on the physical size as that's the + // data that exists in the buffer. + let width_blocks = mip_physical.width / block_width; + let height_blocks = mip_physical.height / block_height; + + let bytes_per_row = width_blocks * block_size; + let data_size = bytes_per_row * height_blocks * mip_size.depth_or_array_layers; + + let end_offset = binary_offset + data_size as usize; + + if mip == 0 || !skip_mipmaps { + queue.write_texture( + wgpu::TexelCopyTextureInfo { + texture: &texture, + mip_level: mip, + origin: wgpu::Origin3d { + x: 0, + y: 0, + z: layer, + }, + aspect: wgpu::wgt::TextureAspect::All, + }, + &data[binary_offset..end_offset], + wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(bytes_per_row), + rows_per_image: Some(height_blocks), + }, + mip_physical, + ); + } + + binary_offset = end_offset; + } + } + + texture +} diff --git a/src/renderer/image.rs b/src/renderer/image.rs new file mode 100644 index 0000000..ef34287 --- /dev/null +++ b/src/renderer/image.rs @@ -0,0 +1,171 @@ +use crate::{color::Srgba, renderer::textures::TextureOptions}; +use image::{DynamicImage, RgbaImage}; +use std::{io::Read, num::NonZeroU32, path::Path}; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ImageDelta { + pub image: ImageData, + pub options: TextureOptions, +} + +impl ImageDelta { + pub fn new>(image: I, options: TextureOptions) -> Self { + Self { + image: image.into(), + options, + } + } +} + +/// Order in which data is laid out. +/// Doesn't matter for data with a single layer and no mipmaps. +#[derive(Clone, Copy, Default, Debug, PartialEq, Eq, Hash)] +pub enum DataOrder { + /// Data is laid out as: `[Layer0Mip0, Layer0Mip1, Layer0Mip2, Layer1Mip0, Layer1Mip1, ...]` + /// Used by dds files. + #[default] + LayerMajor, + /// Data is laid out as: `[Layer0Mip0, Layer1Mip0, Layer2Mip0, Layer0Mip1, Layer1Mip1, ...]` + /// Used by ktx and ktx2 files. + #[allow(dead_code)] + MipMajor, +} + +impl From for wgpu::wgt::TextureDataOrder { + fn from(value: DataOrder) -> Self { + match value { + DataOrder::LayerMajor => Self::LayerMajor, + DataOrder::MipMajor => Self::MipMajor, + } + } +} + +#[derive(Clone, PartialEq, Eq)] +pub struct ImageData { + pub format: wgpu::TextureFormat, + pub width: u32, + pub height: u32, + pub array_layers: u32, + pub mipmap_count: NonZeroU32, + pub data_order: DataOrder, + pub bytes: Vec, +} + +impl ImageData { + pub fn from_solid_color(dimensions: [usize; 2], color: Srgba) -> Self { + let width = dimensions[0] as u32; + let height = dimensions[1] as u32; + Self { + format: wgpu::TextureFormat::Rgba8Unorm, + width, + height, + array_layers: 1, + mipmap_count: NonZeroU32::new(1).expect("1 is non-zero"), + data_order: Default::default(), + bytes: RgbaImage::from_pixel(width, height, color.0.into()).into_raw(), + } + } +} + +impl From for ImageData { + fn from(image: DynamicImage) -> Self { + Self { + format: wgpu::TextureFormat::Rgba8Unorm, + width: image.width(), + height: image.height(), + array_layers: 1, + mipmap_count: NonZeroU32::new(1).expect("1 is non-zero"), + data_order: Default::default(), + bytes: image.to_rgba8().into_raw(), + } + } +} + +impl From for ImageData { + fn from(image: RgbaImage) -> Self { + Self { + format: wgpu::TextureFormat::Rgba8Unorm, + width: image.width(), + height: image.height(), + array_layers: 1, + mipmap_count: NonZeroU32::new(1).expect("1 is non-zero"), + data_order: Default::default(), + bytes: image.into_raw(), + } + } +} + +impl std::fmt::Debug for ImageData { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("ImageData") + .field("format", &self.format) + .field("width", &self.width) + .field("height", &self.height) + .field("array_layers", &self.array_layers) + .field("mipmap_count", &self.mipmap_count) + .finish() + } +} + +// TODO: clean this up +pub fn load_image_file>(path: P) -> anyhow::Result { + // PoB2 assumes a case insensitive filesystem is used. This can lead to some + // files not being found on case sensitive systems. + // As a workaround, try using a lower-cased path if the original path doesn't + // exist. + let path = if path.as_ref().exists() { + path.as_ref().to_owned() + } else { + let mut path = path.as_ref().to_owned(); + let lowercase_filename = path.file_name().unwrap().to_ascii_lowercase(); + path.set_file_name(lowercase_filename); + path + }; + + // special handling for compressed dds files + if path.extension().and_then(|s| s.to_str()) == Some("zst") + && path + .file_stem() + .and_then(|s| s.to_str()) + .map(|s| s.ends_with(".dds")) + .unwrap_or(false) + { + let f = std::fs::File::open(&path)?; + let file_len = f.metadata().ok().map(|m| m.len()); + let mut zstd_decoder = zstd::Decoder::new(f)?; + + let parse_option = dds::header::ParseOptions::new_permissive(file_len); + let header = dds::header::Header::read(&mut zstd_decoder, &parse_option)?; + let dxgi_format = dds::Format::from_header(&header)?; + // zstd_decoder will now be at start of pixel data + let non_data_len = dds::header::Header::MAGIC.len() + header.byte_len(); + let data_len = file_len.and_then(|l| (l as usize).checked_sub(non_data_len)); + let mut pixel_data = Vec::with_capacity(data_len.unwrap_or(0)); + zstd_decoder.read_to_end(&mut pixel_data)?; + + let format = match dxgi_format { + dds::Format::BC1_UNORM => wgpu::TextureFormat::Bc1RgbaUnorm, + dds::Format::BC2_UNORM => wgpu::TextureFormat::Bc2RgbaUnorm, + dds::Format::BC3_UNORM => wgpu::TextureFormat::Bc3RgbaUnorm, + dds::Format::BC7_UNORM => wgpu::TextureFormat::Bc7RgbaUnorm, + dds::Format::R8G8B8A8_UNORM => wgpu::TextureFormat::Rgba8Unorm, + _ => anyhow::bail!("Unsupported dxgi format"), + }; + + let image_data = ImageData { + format, + width: header.width(), + height: header.height(), + array_layers: header.array_size(), + mipmap_count: header.mipmap_count(), + data_order: DataOrder::LayerMajor, + bytes: pixel_data, + }; + + return Ok(image_data); + } + + // let image crate deal with other file types + let image = image::ImageReader::open(&path)?.decode()?; + Ok(image.into()) +} diff --git a/src/renderer/main.wgsl b/src/renderer/main.wgsl new file mode 100644 index 0000000..21a8e93 --- /dev/null +++ b/src/renderer/main.wgsl @@ -0,0 +1,62 @@ +// Vertex shader bindings +struct VertexOutput { + @location(0) tex_coord: vec2, + @location(1) color: vec4, // linear + @location(2) layer_idx: u32, + @builtin(position) position: vec4, +}; + +struct Globals { + screen_size: vec2, +}; + +@group(0) @binding(0) var r_globals: Globals; + +// [u8; 4] as u32 -> [f32; 4] +fn unpack_color(color: u32) -> vec4 { + return vec4( + f32(color & 255u), + f32((color >> 8u) & 255u), + f32((color >> 16u) & 255u), + f32((color >> 24u) & 255u), + ) / 255.0; +} + +fn position_from_screen(screen_pos: vec2) -> vec4 { + return vec4( + 2.0 * screen_pos.x / r_globals.screen_size.x - 1.0, + 1.0 - 2.0 * screen_pos.y / r_globals.screen_size.y, + 0.0, + 1.0, + ); +} + +@vertex +fn vs_main( + @location(0) a_pos: vec2, + @location(1) a_tex_coord: vec2, + @location(2) a_color: u32, // non-linear + @location(3) a_layer_idx: u32, +) -> VertexOutput { + var out: VertexOutput; + out.tex_coord = a_tex_coord; + out.layer_idx = a_layer_idx; + out.color = unpack_color(a_color); + out.position = position_from_screen(a_pos); + return out; +} + +@group(1) @binding(0) var r_tex_color: texture_2d_array; +@group(1) @binding(1) var r_tex_sampler: sampler; + +@fragment +fn fs_main(in: VertexOutput) -> @location(0) vec4 { + // NOTE: PoB incorrectly performs mixing and blending in sRGB space. + // To get a similar visual result, we need to do the same. + // Vertex colors, texture samples, and the output color are all in sRGB. + // Texture formats and output surface formats are selected such that no automatic + // conversion between linear <-> sRGB is performed. + let tex_color = textureSample(r_tex_color, r_tex_sampler, in.tex_coord, in.layer_idx); + var out_color = in.color * tex_color; + return out_color; +} diff --git a/src/renderer/mesh.rs b/src/renderer/mesh.rs new file mode 100644 index 0000000..bf3ee98 --- /dev/null +++ b/src/renderer/mesh.rs @@ -0,0 +1,119 @@ +use crate::{ + color::Srgba, + dpi::{ + LogicalPoint, LogicalQuad, LogicalRect, NormalizedPoint, NormalizedQuad, NormalizedRect, + }, + math::Corners, + renderer::textures::TextureId, +}; + +#[repr(C)] +#[derive(Clone, Copy, Debug, Default, PartialEq, bytemuck::Pod, bytemuck::Zeroable)] +pub struct Vertex { + pub pos: LogicalPoint, + pub uv: NormalizedPoint, + pub color: Srgba, + // TODO: layer_idx is the same for all vertices. use a uniform buffer + // and bind it along with the texture. move into Mesh or make part of + // TextureId (change into tuple) + pub layer_idx: u32, +} + +#[derive(Clone, Debug, Default)] +pub struct Mesh { + pub vertices: Vec, + pub indices: Vec, + pub texture_id: TextureId, +} + +impl Mesh { + #[inline] + pub fn add_rect( + &mut self, + rect: LogicalRect, + uv: NormalizedRect, + color: Srgba, + layer_idx: u32, + ) { + let i = self.vertices.len() as u32; + self.indices + .extend_from_slice(&[i, i + 1, i + 3, i + 1, i + 2, i + 3]); + + self.vertices.extend_from_slice(&[ + Vertex { + pos: rect.top_left(), + uv: uv.top_left(), + color, + layer_idx, + }, + Vertex { + pos: rect.top_right(), + uv: uv.top_right(), + color, + layer_idx, + }, + Vertex { + pos: rect.bottom_right(), + uv: uv.bottom_right(), + color, + layer_idx, + }, + Vertex { + pos: rect.bottom_left(), + uv: uv.bottom_left(), + color, + layer_idx, + }, + ]); + } + + #[inline] + pub fn add_quad( + &mut self, + quad: LogicalQuad, + uv: NormalizedQuad, + color: Srgba, + layer_idx: u32, + ) { + let i = self.vertices.len() as u32; + self.indices + .extend_from_slice(&[i, i + 1, i + 3, i + 1, i + 2, i + 3]); + + self.vertices.extend_from_slice(&[ + Vertex { + pos: quad.p0, + uv: uv.p0, + color, + layer_idx, + }, + Vertex { + pos: quad.p1, + uv: uv.p1, + color, + layer_idx, + }, + Vertex { + pos: quad.p2, + uv: uv.p2, + color, + layer_idx, + }, + Vertex { + pos: quad.p3, + uv: uv.p3, + color, + layer_idx, + }, + ]); + } + + pub fn is_empty(&self) -> bool { + self.vertices.is_empty() && self.indices.is_empty() + } +} + +pub struct ClippedMesh { + // Only parts of the mesh that intersect with this will be rendered + pub clip_rect: LogicalRect, + pub mesh: Mesh, +} diff --git a/src/renderer/mipmap.rs b/src/renderer/mipmap.rs new file mode 100644 index 0000000..e317e40 --- /dev/null +++ b/src/renderer/mipmap.rs @@ -0,0 +1,99 @@ +/// Generate entire mipmap chain for all layers starting from mip level 0 image data. +/// Assumes data to contain one mip level 0 image for each layer in RGBA format. +pub fn generate_mipmap_chain(queue: &wgpu::Queue, texture: &wgpu::Texture, data: &[u8]) { + assert!(!texture.format().is_compressed()); + assert!(texture.format().components() == 4); + + let size = texture.size(); + let block_size = texture.format().block_copy_size(None).unwrap_or(4); + let data_size = (size.width * size.height * block_size) as usize; + + let srgb_mapper = fast_image_resize::create_srgb_mapper(); + + let mut data_offset = 0; + for layer in 0..texture.depth_or_array_layers() { + let bytes = data[data_offset..data_size].to_owned(); + let mut src_image = fast_image_resize::images::Image::from_vec_u8( + size.width, + size.height, + bytes, + fast_image_resize::PixelType::U8x4, + ) + .unwrap(); + + for mip in 1..texture.mip_level_count() { + let mut target_size = size.mip_level_size(mip, wgpu::TextureDimension::D2); + target_size.depth_or_array_layers = 1; // copying layers separately + + // intermediate buffer that stores linear source image data in a higher + // bit depth to avoid loss of information + let mut linear_src_image = fast_image_resize::images::Image::new( + src_image.width(), + src_image.height(), + fast_image_resize::PixelType::U16x4, + ); + + // convert from sRGB space into linear space + // resizing needs to be performed in linear space to get the correct visual result + srgb_mapper + .forward_map(&src_image, &mut linear_src_image) + .unwrap(); + + let mut dst_image = fast_image_resize::images::Image::new( + target_size.width, + target_size.height, + fast_image_resize::PixelType::U8x4, + ); + + let mut linear_dst_image = fast_image_resize::images::Image::new( + dst_image.width(), + dst_image.height(), + fast_image_resize::PixelType::U16x4, + ); + + let mut resizer = fast_image_resize::Resizer::new(); + resizer + .resize( + &linear_src_image, + &mut linear_dst_image, + Some(&fast_image_resize::ResizeOptions { + algorithm: fast_image_resize::ResizeAlg::Convolution( + fast_image_resize::FilterType::Bilinear, + ), + cropping: fast_image_resize::SrcCropping::None, + mul_div_alpha: true, + }), + ) + .unwrap(); + + // texture needs to be in sRGB, so map back from resized linear image + srgb_mapper + .backward_map(&linear_dst_image, &mut dst_image) + .unwrap(); + + queue.write_texture( + wgpu::TexelCopyTextureInfo { + texture, + mip_level: mip, + origin: wgpu::Origin3d { + x: 0, + y: 0, + z: layer, + }, + aspect: wgpu::wgt::TextureAspect::All, + }, + dst_image.buffer(), + wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(block_size * target_size.width), + rows_per_image: None, + }, + target_size, + ); + + src_image = dst_image; + } + + data_offset += data_size; + } +} diff --git a/src/renderer/primitives.rs b/src/renderer/primitives.rs new file mode 100644 index 0000000..1a69f01 --- /dev/null +++ b/src/renderer/primitives.rs @@ -0,0 +1,192 @@ +use crate::{ + color::Srgba, + dpi::{LogicalPoint, LogicalQuad, LogicalRect, LogicalVector, NormalizedQuad, NormalizedRect}, + fonts::Layout, + math::Point, + renderer::textures::TextureId, +}; +use ordered_float::OrderedFloat; +use std::{ + hash::{Hash, Hasher}, + sync::Arc, +}; + +#[derive(Clone)] +pub struct ClippedPrimitive { + pub clip_rect: LogicalRect, + pub primitive: DrawPrimitive, +} + +impl Hash for ClippedPrimitive { + fn hash(&self, state: &mut H) { + hash_pos(&self.clip_rect.min, state); + hash_pos(&self.clip_rect.max, state); + self.primitive.hash(state); + } +} + +#[derive(Clone, Hash)] +pub enum DrawPrimitive { + Rect(RectPrimitive), + Quad(QuadPrimitive), + Text(TextPrimitive), +} + +impl DrawPrimitive { + pub fn texture_id(&self) -> TextureId { + match self { + DrawPrimitive::Rect(rect_primitive) => rect_primitive + .texture + .map_or_else(TextureId::default, |tex| tex.texture_id), + DrawPrimitive::Quad(quad_primitive) => quad_primitive + .texture + .map_or_else(TextureId::default, |tex| tex.texture_id), + _ => TextureId::default(), + } + } +} + +#[derive(Clone, Copy)] +pub struct RectPrimitive { + pub rect: LogicalRect, + pub color: Srgba, + pub texture: Option, +} + +impl RectPrimitive { + pub fn new(rect: LogicalRect, color: Srgba, texture: Option) -> Self { + Self { + rect, + color, + texture, + } + } + + pub fn translate(&mut self, direction: LogicalVector) { + self.rect = self.rect.translate(direction); + } +} + +impl Hash for RectPrimitive { + fn hash(&self, state: &mut H) { + hash_pos(&self.rect.min, state); + hash_pos(&self.rect.max, state); + self.color.hash(state); + self.texture.hash(state); + } +} + +#[derive(Clone, Copy)] +pub struct RectTexture { + pub texture_id: TextureId, + pub uv: NormalizedRect, + pub layer_idx: u32, +} + +impl RectTexture { + pub fn new(texture_id: TextureId, uv: NormalizedRect, layer_idx: u32) -> Self { + Self { + texture_id, + uv, + layer_idx, + } + } +} + +impl Hash for RectTexture { + fn hash(&self, state: &mut H) { + self.texture_id.hash(state); + hash_pos(&self.uv.min, state); + hash_pos(&self.uv.max, state); + self.layer_idx.hash(state); + } +} + +#[derive(Clone, Copy)] +pub struct QuadPrimitive { + pub quad: LogicalQuad, + pub color: Srgba, + pub texture: Option, +} + +impl QuadPrimitive { + pub fn new(quad: LogicalQuad, color: Srgba, texture: Option) -> Self { + Self { + quad, + color, + texture, + } + } + + pub fn translate(&mut self, direction: LogicalVector) { + self.quad = self.quad.translate(direction); + } +} + +impl Hash for QuadPrimitive { + fn hash(&self, state: &mut H) { + hash_pos(&self.quad.p0, state); + hash_pos(&self.quad.p1, state); + hash_pos(&self.quad.p2, state); + hash_pos(&self.quad.p3, state); + self.color.hash(state); + self.texture.hash(state); + } +} + +#[derive(Clone, Copy)] +pub struct QuadTexture { + pub texture_id: TextureId, + pub uv: NormalizedQuad, + pub layer_idx: u32, +} + +impl QuadTexture { + pub fn new(texture_id: TextureId, uv: NormalizedQuad, layer_idx: u32) -> Self { + Self { + texture_id, + uv, + layer_idx, + } + } +} + +impl Hash for QuadTexture { + fn hash(&self, state: &mut H) { + self.texture_id.hash(state); + hash_pos(&self.uv.p0, state); + hash_pos(&self.uv.p1, state); + hash_pos(&self.uv.p2, state); + hash_pos(&self.uv.p3, state); + self.layer_idx.hash(state); + } +} + +#[derive(Clone)] +pub struct TextPrimitive { + pub pos: LogicalPoint, + pub layout: Arc, +} + +impl TextPrimitive { + pub fn new(pos: LogicalPoint, layout: Arc) -> Self { + Self { pos, layout } + } + + #[inline(always)] + pub fn translate(&mut self, direction: LogicalVector) { + self.pos += direction; + } +} + +impl Hash for TextPrimitive { + fn hash(&self, state: &mut H) { + hash_pos(&self.pos, state); + self.layout.hash(state); + } +} + +fn hash_pos(pos: &Point, state: &mut H) { + OrderedFloat(pos.x).hash(state); + OrderedFloat(pos.x).hash(state); +} diff --git a/src/renderer/tessellator.rs b/src/renderer/tessellator.rs new file mode 100644 index 0000000..5ce5a88 --- /dev/null +++ b/src/renderer/tessellator.rs @@ -0,0 +1,161 @@ +use crate::{ + dpi::{Normalize, NormalizedQuad, NormalizedRect, Uv}, + fonts::FontAtlasSize, + renderer::{ + mesh::{ClippedMesh, Mesh}, + primitives::{ + ClippedPrimitive, DrawPrimitive, QuadPrimitive, QuadTexture, RectPrimitive, + RectTexture, TextPrimitive, + }, + textures::TextureId, + }, +}; + +/// Converts [`DrawPrimitive`]s into [`Mesh`]es. +#[derive(Default)] +pub struct Tessellator { + last_clipped_meshes_size: usize, +} + +impl Tessellator { + pub fn convert_clipped_primitives( + &mut self, + clipped_primitives: impl Iterator, + font_atlas_size: FontAtlasSize, + ) -> Vec { + profiling::scope!("convert_primitives"); + + let mut clipped_meshes = Vec::with_capacity(self.last_clipped_meshes_size); + + for clipped_primitive in clipped_primitives { + self.convert_clipped_primitive(clipped_primitive, font_atlas_size, &mut clipped_meshes); + } + + self.last_clipped_meshes_size = clipped_meshes.len(); + clipped_meshes + } + + pub fn convert_clipped_primitive( + &mut self, + clipped_primitive: ClippedPrimitive, + font_atlas_size: FontAtlasSize, + out_clipped_meshes: &mut Vec, + ) { + let ClippedPrimitive { + clip_rect, + primitive, + } = clipped_primitive; + + if clip_rect.is_empty() { + return; + } + + let start_new_mesh = match out_clipped_meshes.last() { + None => true, + Some(last_clipped_mesh) => { + // append to previous mesh if clip_rect and texture_id match. + // otherwise, start a new mesh. + !(last_clipped_mesh.clip_rect == clip_rect + && last_clipped_mesh.mesh.texture_id == primitive.texture_id()) + } + }; + + if start_new_mesh { + out_clipped_meshes.push(ClippedMesh { + clip_rect, + mesh: Mesh::default(), + }); + } + + let last_clipped_mesh = out_clipped_meshes.last_mut().unwrap(); + + match primitive { + DrawPrimitive::Rect(rect_primitive) => { + self.convert_rect_primitive(rect_primitive, &mut last_clipped_mesh.mesh) + } + DrawPrimitive::Quad(quad_primitive) => { + self.convert_quad_primitive(quad_primitive, &mut last_clipped_mesh.mesh) + } + DrawPrimitive::Text(text_primitive) => self.convert_text_primitive( + text_primitive, + font_atlas_size, + &mut last_clipped_mesh.mesh, + ), + } + + // This can be empty if a new mesh was started but the conversion from a text primitive + // didn't add any vertices. Our renderer doesn't support empty meshes so remove it + if last_clipped_mesh.mesh.is_empty() { + out_clipped_meshes.pop(); + } + } + + fn convert_rect_primitive(&self, rect_primitive: RectPrimitive, out: &mut Mesh) { + let RectPrimitive { + rect, + color, + texture, + } = rect_primitive; + + let (texture_id, uv, layer_idx) = match texture { + Some(RectTexture { + texture_id, + uv, + layer_idx, + }) => (texture_id, uv, layer_idx), + None => (TextureId::default(), NormalizedRect::white_uv(), 0), + }; + + out.add_rect(rect, uv, color, layer_idx); + out.texture_id = texture_id; + } + + fn convert_quad_primitive(&self, quad_primitive: QuadPrimitive, out: &mut Mesh) { + let QuadPrimitive { + quad, + color, + texture, + } = quad_primitive; + + let (texture_id, uv, layer_idx) = match texture { + Some(QuadTexture { + texture_id, + uv, + layer_idx, + }) => (texture_id, uv, layer_idx), + None => (TextureId::default(), NormalizedQuad::white_uv(), 0), + }; + + out.add_quad(quad, uv, color, layer_idx); + out.texture_id = texture_id; + } + + fn convert_text_primitive( + &self, + text_primitive: TextPrimitive, + font_atlas_size: FontAtlasSize, + out: &mut Mesh, + ) { + let TextPrimitive { + pos: layout_pos, + layout, + } = text_primitive; + + if layout.rows.is_empty() { + return; + } + + out.vertices.reserve(layout.num_of_vertices); + out.indices.reserve(layout.num_of_indices); + + // TODO: align to pixel grid? + + for row in &layout.rows { + for glyph in &row.glyphs { + let rect = glyph.rect.translate(layout_pos.to_vector()); + let normalized_uv = glyph.uv.normalize(font_atlas_size); + out.add_rect(rect, normalized_uv, glyph.color, 0); + } + } + } +} diff --git a/src/renderer/textures.rs b/src/renderer/textures.rs new file mode 100644 index 0000000..fc572e2 --- /dev/null +++ b/src/renderer/textures.rs @@ -0,0 +1,329 @@ +use std::{ + collections::hash_map::Entry, + path::Path, + sync::{Arc, RwLock}, +}; + +use ahash::HashMap; +use anyhow::bail; + +use crate::{ + color::Srgba, + renderer::image::{ImageData, ImageDelta, load_image_file}, + worker_pool::WorkerPool, +}; + +pub type TextureId = u64; + +pub struct TextureHandle { + tex_mngr: Arc>, + id: TextureId, +} + +impl TextureHandle { + pub fn new(tex_mngr: Arc>, id: TextureId) -> Self { + Self { tex_mngr, id } + } + + pub fn id(&self) -> TextureId { + self.id + } + + pub fn size(&self) -> [usize; 2] { + self.tex_mngr + .read() + .unwrap() + .get_meta_data(self.id) + .map_or([0, 0], |tex| tex.size) + } +} + +impl Drop for TextureHandle { + fn drop(&mut self) { + self.tex_mngr.write().unwrap().free(self.id); + } +} + +impl Clone for TextureHandle { + fn clone(&self) -> Self { + self.tex_mngr.write().unwrap().retain(self.id); + Self { + tex_mngr: Arc::clone(&self.tex_mngr), + id: self.id, + } + } +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct TexturesDelta { + pub update: Vec<(TextureId, ImageDelta)>, + pub free: Vec, +} + +impl TexturesDelta { + pub fn is_empty(&self) -> bool { + self.update.is_empty() && self.free.is_empty() + } +} + +/// Metadata about an allocated texture. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct TextureMetaData { + pub name: String, + pub size: [usize; 2], + /// Texture is freed when this reaches zero + retain_count: usize, + pub options: TextureOptions, +} + +#[derive(Default)] +pub struct TextureManager { + next_id: u64, + meta_data: HashMap, + delta: TexturesDelta, +} + +impl TextureManager { + /// Allocates a new Texture. + pub fn alloc(&mut self, name: String, image: ImageData, options: TextureOptions) -> TextureId { + let id = self.next_id; + self.next_id += 1; + + self.meta_data.entry(id).or_insert_with(|| TextureMetaData { + name, + size: [image.width as usize, image.height as usize], + retain_count: 1, + options, + }); + + self.delta + .update + .push((id, ImageDelta::new(image, options))); + + id + } + + /// Reserves a new TextureId for later assignment. + pub fn reserve(&mut self, name: String, options: TextureOptions) -> TextureId { + let id = self.next_id; + self.next_id += 1; + + self.meta_data.entry(id).or_insert_with(|| TextureMetaData { + name, + size: [0, 0], + retain_count: 1, + options, + }); + + id + } + + /// Assigns a new image to an existing texture. + pub fn set(&mut self, id: TextureId, delta: ImageDelta) { + if let Some(meta_data) = self.meta_data.get_mut(&id) { + meta_data.size = [delta.image.width as usize, delta.image.height as usize]; + // discard all old enqueued deltas + self.delta.update.retain(|(x, _)| x != &id); + self.delta.update.push((id, delta)); + } else { + debug_assert!(false, "Tried setting texture {id:?} which is not allocated"); + } + } + + /// Frees an existing texture. + pub fn free(&mut self, id: TextureId) { + if let Entry::Occupied(mut entry) = self.meta_data.entry(id) { + let meta = entry.get_mut(); + meta.retain_count -= 1; + if meta.retain_count == 0 { + entry.remove(); + self.delta.free.push(id); + } + } else { + debug_assert!(false, "Tried freeing texture {id:?} which is not allocated"); + } + } + + /// Increase the retain-count of the given texture. + /// + /// [`Self::free`] must be called an additional time for each time [`Self::retain`] is called, + pub fn retain(&mut self, id: TextureId) { + if let Some(meta) = self.meta_data.get_mut(&id) { + meta.retain_count += 1; + } else { + debug_assert!( + false, + "Tried retaining texture {id:?} which is not allocated", + ); + } + } + + /// Get metadata about a specific texture. + pub fn get_meta_data(&self, id: TextureId) -> Option<&TextureMetaData> { + self.meta_data.get(&id) + } + + /// Take and reset changes since last frame. + pub fn take_delta(&mut self) -> TexturesDelta { + std::mem::take(&mut self.delta) + } +} + +pub struct WrappedTextureManager { + manager: Arc>, + worker_pool: WorkerPool, +} + +impl WrappedTextureManager { + pub fn new() -> Self { + let manager = Arc::new(RwLock::new(TextureManager::default())); + + // allocate default texture (id: 0) for font atlas + manager.write().unwrap().alloc( + "font_atlas_texture".into(), + ImageData::from_solid_color([0, 0], Srgba::TRANSPARENT), + TextureOptions::default(), + ); + + Self { + manager, + worker_pool: WorkerPool::new(4), + } + } + + #[inline] + pub fn update_font_texture(&self, delta: ImageDelta) { + self.manager + .write() + .unwrap() + .set(TextureId::default(), delta); + } + + #[inline] + pub fn take_delta(&self) -> TexturesDelta { + self.manager.write().unwrap().take_delta() + } + + pub fn load_texture( + &self, + image_path: String, + options: TextureOptions, + is_async: bool, + ) -> anyhow::Result { + let manager = Arc::clone(&self.manager); + + let handle = if is_async { + let id = manager + .write() + .unwrap() + .reserve(image_path.clone(), options); + + // load image in background worker + let mngr_clone = Arc::clone(&manager); + self.worker_pool + .execute(move || match load_image_file(Path::new(&image_path)) { + Ok(image) => { + mngr_clone + .write() + .unwrap() + .set(id, ImageDelta::new(image, options)); + } + Err(e) => log::warn!("Unable to load image fron {}: {}", &image_path, e), + }); + + TextureHandle::new(manager, id) + } else { + match load_image_file(Path::new(&image_path)) { + Ok(image) => { + let id = manager.write().unwrap().alloc(image_path, image, options); + TextureHandle::new(manager, id) + } + Err(e) => { + log::warn!("Unable to load image fron {}: {}", &image_path, e); + bail!(e); + } + } + }; + + Ok(handle) + } + + pub fn update_texture( + &self, + texture_id: TextureId, + image_path: String, + options: TextureOptions, + is_async: bool, + ) -> anyhow::Result<()> { + if is_async { + let mngr_clone = Arc::clone(&self.manager); + self.worker_pool + .execute(move || match load_image_file(Path::new(&image_path)) { + Ok(image) => { + mngr_clone + .write() + .unwrap() + .set(texture_id, ImageDelta::new(image, options)); + } + Err(e) => log::warn!("Unable to load image fron {}: {}", &image_path, e), + }); + } else { + match load_image_file(Path::new(&image_path)) { + Ok(image) => { + self.manager + .write() + .unwrap() + .set(texture_id, ImageDelta::new(image, options)); + } + Err(e) => { + log::warn!("Unable to load image fron {}: {}", &image_path, e); + bail!(e); + } + } + } + + Ok(()) + } +} + +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub struct TextureOptions { + pub magnification: wgpu::FilterMode, + pub minification: wgpu::FilterMode, + pub wrap_mode: wgpu::AddressMode, + pub mipmap_mode: wgpu::FilterMode, + pub generate_mipmaps: bool, +} + +impl TextureOptions { + pub const LINEAR_REPEAT: Self = Self { + magnification: wgpu::FilterMode::Linear, + minification: wgpu::FilterMode::Linear, + wrap_mode: wgpu::AddressMode::Repeat, + mipmap_mode: wgpu::FilterMode::Linear, + generate_mipmaps: false, + }; + + pub const LINEAR: Self = Self { + magnification: wgpu::FilterMode::Linear, + minification: wgpu::FilterMode::Linear, + wrap_mode: wgpu::AddressMode::ClampToEdge, + mipmap_mode: wgpu::FilterMode::Linear, + generate_mipmaps: false, + }; +} + +impl Default for TextureOptions { + fn default() -> Self { + Self::LINEAR + } +} + +impl std::hash::Hash for TextureOptions { + fn hash(&self, state: &mut H) { + self.magnification.hash(state); + self.minification.hash(state); + self.wrap_mode.hash(state); + self.mipmap_mode.hash(state); + } +} diff --git a/src/subscript.rs b/src/subscript.rs new file mode 100644 index 0000000..b212af8 --- /dev/null +++ b/src/subscript.rs @@ -0,0 +1,358 @@ +use std::cell::RefCell; +use std::rc::Rc; +use std::sync::mpsc::{Receiver, Sender, TryRecvError}; +use std::{collections::VecDeque, sync::mpsc::channel, thread::JoinHandle}; + +use anyhow::{Result, anyhow}; +use mlua::{Function, IntoLuaMulti, Lua, Value}; +use mlua::{Integer, MultiValue, Number, Result as LuaResult}; + +use crate::api::get_callback; +use crate::lua::LuaInstance; + +#[derive(Debug)] +pub enum SubscriptResult { + SubscriptFinished { + id: u64, + return_values: NativeMultiValue, + }, + SubscriptError { + id: u64, + error: String, + }, +} + +pub struct SubscriptManager { + current_id: u64, + scripts: Vec, +} + +impl SubscriptManager { + pub fn new() -> Self { + Self { + current_id: 0, + scripts: Vec::new(), + } + } + + pub fn push( + &mut self, + script_text: String, + blocking_calls: Vec, + nonblocking_calls: Vec, + arguments: NativeMultiValue, + ) -> u64 { + let id = self.current_id; + self.current_id += 1; + + let subscript = Subscript::new( + id, + script_text, + blocking_calls, + nonblocking_calls, + arguments, + ); + self.scripts.push(subscript); + id + } + + pub fn process(&mut self, lua: &LuaInstance) -> Vec { + let mut results = vec![]; + + self.scripts.retain_mut(|subscript| { + subscript.handle_calls(lua); + + if let Some(event) = subscript.try_join() { + results.push(event); + // subscript has finished or errored, remove it + false + } else { + // subscript has not finished yet, keep it + true + } + }); + + results + } +} + +enum SubscriptCall { + Blocking { + function_name: String, + arguments: NativeMultiValue, + // used to send return values of function back to thread + return_values_sender: Sender>, + }, + NonBlocking { + function_name: String, + arguments: NativeMultiValue, + }, +} + +pub struct Subscript { + id: u64, + handle: Option>>, + receiver: Receiver, +} + +// Subscripts are lua scripts that are executed in their own instance on a separate thread. +// +// When a subscript needs to call a function defined in the main instance, a `SubscriptCall` message is send over a channel. At the beginning of each frame, the main thread checks for messages and executes the requested function with the provided arguments on behalf of the subscript. +// For `BlockingCall`, the main thread sends the return values of the function back to the subscript which is waiting on them. +// For `NonBlockingCall`, the subscript doesn't wait on any return values and keeps executing the script after sending the message. +// Subscripts are required to explicitly specify the names of all (non)-blocking function calls that appear in the script. +impl Subscript { + pub fn new( + id: u64, + script_text: String, + blocking_calls: Vec, + nonblocking_calls: Vec, + arguments: NativeMultiValue, + ) -> Self { + let (tx, rx) = channel(); + + let handle = std::thread::spawn(move || { + profiling::register_thread!(format!("Subscript {} Thread", id)); + + // unsafe required to load C modules (curl) + let lua = unsafe { Lua::unsafe_new() }; + + // add ./lua to package.path and package.cpath + LuaInstance::register_package_paths(&lua)?; + + for function_name in blocking_calls { + let thread_tx = tx.clone(); + lua.globals().set( + function_name.clone(), + lua.create_function(move |_, args: MultiValue| { + let (tx_return, rx_return) = channel(); + thread_tx + .send(SubscriptCall::Blocking { + function_name: function_name.clone(), + arguments: args.try_into()?, + return_values_sender: tx_return, + }) + .unwrap(); + // this blocks until we receive return values + let return_values = rx_return.recv().map_err(|e| anyhow!("{}", e))??; + Ok(return_values) + })?, + )?; + } + + for function_name in nonblocking_calls { + let thread_tx = tx.clone(); + lua.globals().set( + function_name.clone(), + lua.create_function(move |_, args: MultiValue| { + thread_tx + .send(SubscriptCall::NonBlocking { + function_name: function_name.clone(), + arguments: args.try_into()?, + }) + .map_err(|e| anyhow!("{}", e))?; + Ok(()) + })?, + )?; + } + + let result = lua.load(script_text).call::(arguments)?; + result.try_into() + }); + + Self { + id, + handle: Some(handle), + receiver: rx, + } + } + + fn handle_calls(&mut self, lua: &Lua) { + match self.receiver.try_recv() { + Ok(SubscriptCall::Blocking { + function_name, + arguments, + return_values_sender, + }) => { + let func: Result = get_callback(lua, "OnSubCall"); + match func { + Ok(func) => { + match func.call::((function_name, arguments)) { + Ok(return_values) => { + // send return values back to thread + let _ = return_values_sender.send(return_values.try_into()); + } + // function returned error, forward it to thread + Err(err) => { + let _ = return_values_sender.send(Err(err.into())); + } + } + } + // function not found + Err(err) => { + let _ = return_values_sender.send(Err(err.into())); + } + } + } + Ok(SubscriptCall::NonBlocking { + function_name, + arguments, + }) => { + let func: Result = get_callback(lua, "OnSubCall"); + if let Ok(func) = func { + // we can ignore return values for non-blocking calls + let _ = func.call::<()>((function_name, arguments)); + } + } + // ignore disconnects. potential errors are handled during thread join + Err(TryRecvError::Disconnected) => {} + // no outstanding calls from thread + Err(TryRecvError::Empty) => {} + } + } + + fn try_join(&mut self) -> Option { + if self + .handle + .as_ref() + .map(|h| h.is_finished()) + .unwrap_or(false) + { + let event = match self.handle.take().unwrap().join() { + Ok(Ok(return_values)) => SubscriptResult::SubscriptFinished { + id: self.id, + return_values, + }, + Ok(Err(err)) => SubscriptResult::SubscriptError { + id: self.id, + error: err.to_string(), + }, + // the thread panicked + Err(_) => SubscriptResult::SubscriptError { + id: self.id, + error: String::from("Subscript thread panicked!"), + }, + }; + Some(event) + } else { + None + } + } +} + +pub fn register_subscript_globals( + lua: &Lua, + subscripts: &Rc>, +) -> LuaResult<()> { + let globals = lua.globals(); + + // ssID = LaunchSubScript("", "", ""[, ...]) + let subscripts_clone = Rc::clone(subscripts); + let launch_sub_script = move |_: &Lua, + (script_text, func_list, sub_list, args): ( + String, + String, + String, + MultiValue, + )| { + let blocking_calls = func_list + .split(',') + .map(|s| s.trim()) + .filter(|&s| !s.is_empty()) + .map(String::from) + .collect(); + + let nonblocking_calls = sub_list + .split(',') + .map(|s| s.trim()) + .filter(|&s| !s.is_empty()) + .map(String::from) + .collect(); + + let arguments = args.try_into()?; + let subscript_id = subscripts_clone.borrow_mut().push( + script_text, + blocking_calls, + nonblocking_calls, + arguments, + ); + Ok(subscript_id) + }; + + let subscripts_clone = Rc::clone(subscripts); + let is_subscript_running = move |_: &Lua, subscript_id: u64| { + Ok(subscripts_clone + .borrow() + .scripts + .iter() + .any(|ss| ss.id == subscript_id)) + }; + + let abort_subscript = |_: &Lua, _subscript_id: u64| -> LuaResult<()> { unimplemented!() }; + + globals.set( + "LaunchSubScript", + lua.create_function_mut(launch_sub_script)?, + )?; + globals.set( + "IsSubScriptRunning", + lua.create_function(is_subscript_running)?, + )?; + globals.set("IsSubScriptRunning", lua.create_function(abort_subscript)?)?; + Ok(()) +} + +// used to move arguments and return values between lua instances +// some lua values are associated with their instance and using them with another +// instance is not allowed. +#[derive(Debug)] +pub struct NativeMultiValue(VecDeque); + +#[derive(Debug)] +pub enum NativeValue { + Nil, + Number(Number), + Integer(Integer), + Boolean(bool), + // Lua strings may not be valid UTF-8, so store Vec instead + String(Vec), +} + +impl TryFrom for NativeMultiValue { + type Error = anyhow::Error; + + fn try_from(values: MultiValue) -> Result { + let native = values + .iter() + .map(|v| match v.type_name() { + "nil" => Ok(NativeValue::Nil), + "boolean" => Ok(NativeValue::Boolean(v.as_boolean().unwrap())), + "number" => Ok(NativeValue::Number(v.as_number().unwrap())), + "integer" => Ok(NativeValue::Integer(v.as_integer().unwrap())), + "string" => Ok(NativeValue::String( + v.as_string().unwrap().as_bytes().to_vec(), + )), + _ => Err(anyhow!("Unsupported value type")), + }) + .collect::, _>>()?; + + Ok(NativeMultiValue(native)) + } +} + +impl IntoLuaMulti for NativeMultiValue { + fn into_lua_multi(self, lua: &Lua) -> mlua::Result { + let values = self + .0 + .iter() + .map(|v| match v { + NativeValue::Nil => Ok(Value::Nil), + NativeValue::Boolean(b) => Ok(Value::Boolean(*b)), + NativeValue::Number(n) => Ok(Value::Number(*n)), + NativeValue::Integer(n) => Ok(Value::Integer(*n)), + NativeValue::String(s) => lua.create_string(s).map(Value::String), + }) + .collect::, _>>()?; + Ok(MultiValue::from_vec(values)) + } +} diff --git a/src/util.rs b/src/util.rs new file mode 100644 index 0000000..0a469e2 --- /dev/null +++ b/src/util.rs @@ -0,0 +1,29 @@ +use std::{ + env, + hash::{Hash, Hasher}, + path::{Path, PathBuf}, +}; + +use ahash::AHasher; + +pub fn get_executable_dir() -> anyhow::Result { + let exe_path = env::current_exe()?; + let exe_parent_dir = exe_path.parent().unwrap().canonicalize()?; + Ok(exe_parent_dir) +} + +pub fn change_working_directory>(path: P) -> anyhow::Result<()> { + env::set_current_dir(path.as_ref()).map_err(|e| { + anyhow::anyhow!( + "Failed to change working directory {:?}: {}", + path.as_ref(), + e + ) + }) +} + +pub fn calculate_hash(t: &T) -> u64 { + let mut state = AHasher::default(); + t.hash(&mut state); + state.finish() +} diff --git a/src/worker_pool.rs b/src/worker_pool.rs new file mode 100644 index 0000000..e0edc34 --- /dev/null +++ b/src/worker_pool.rs @@ -0,0 +1,76 @@ +use std::{ + sync::{Arc, Mutex, mpsc}, + thread, +}; + +type Job = Box; + +pub struct WorkerPool { + workers: Vec, + sender: Option>, +} + +impl WorkerPool { + pub fn new(size: usize) -> Self { + assert!(size > 0); + + let (tx, rx) = mpsc::channel(); + let rx = Arc::new(Mutex::new(rx)); + + let mut workers = Vec::with_capacity(size); + + for id in 0..size { + workers.push(Worker::new(id, rx.clone())); + } + + Self { + workers, + sender: Some(tx), + } + } + + pub fn execute(&self, f: F) + where + F: FnOnce() + Send + 'static, + { + let job = Box::new(f); + self.sender.as_ref().unwrap().send(job).unwrap(); + } +} + +impl Drop for WorkerPool { + fn drop(&mut self) { + drop(self.sender.take()); + + for worker in &mut self.workers { + if let Some(thread) = worker.thread.take() { + thread.join().unwrap(); + } + } + } +} + +struct Worker { + _id: usize, + thread: Option>, +} + +impl Worker { + fn new(id: usize, receiver: Arc>>) -> Self { + let thread = thread::spawn(move || { + loop { + let message = receiver.lock().unwrap().recv(); + + match message { + Ok(job) => job(), + Err(_) => break, + } + } + }); + + Self { + _id: id, + thread: Some(thread), + } + } +}