diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cb4ec50b..7bef15d1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -25,6 +25,8 @@ jobs: craft-fonts-ref: aced4137c022f1f587624d48e81ec77e1914a9cc os: '["ubuntu-24.04","windows-latest"]' toolchain: "1.96.0" + # xtask ci runs cargo test (including doctests), not cargo nextest. + tools: "" packages: >- libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev libgl1-mesa-dev libgtk-3-dev diff --git a/.github/workflows/freebsd.yml b/.github/workflows/freebsd.yml index 9f64bbdd..442b9fd7 100644 --- a/.github/workflows/freebsd.yml +++ b/.github/workflows/freebsd.yml @@ -33,4 +33,9 @@ jobs: uses: storytold/craft-common-actions/.github/workflows/freebsd.yml@main with: craft-fonts-ref: aced4137c022f1f587624d48e81ec77e1914a9cc + # The VM's software Vulkan driver crashes (SIGSEGV) when several tests set up a device at + # once (photocraft serializes its GPU tests for the same reason), so tests run one at a + # time. The whole workspace is tested in one command: excluding packages would change + # feature unification and build winit without its X11/Wayland backends. + cargo-test-extra-args: "-- --test-threads=1" run-package-check: true diff --git a/Cargo.lock b/Cargo.lock index 7a9453c3..384c4457 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -412,6 +412,12 @@ version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + [[package]] name = "bit-set" version = "0.10.0" @@ -448,6 +454,15 @@ dependencies = [ "serde_core", ] +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + [[package]] name = "block2" version = "0.5.1" @@ -691,6 +706,16 @@ dependencies = [ "libc", ] +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "core-foundation-sys" version = "0.8.7" @@ -704,7 +729,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c07782be35f9e1140080c6b96f0d44b739e2278479f64e02fdab4e32dfd8b081" dependencies = [ "bitflags 1.3.2", - "core-foundation", + "core-foundation 0.9.4", "core-graphics-types", "foreign-types", "libc", @@ -717,19 +742,41 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf" dependencies = [ "bitflags 1.3.2", - "core-foundation", + "core-foundation 0.9.4", "libc", ] +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "craft-dialogs" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" +dependencies = [ + "block2 0.6.2", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "raw-window-handle", + "rfd", +] + [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242" +source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242" +source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" dependencies = [ "fixed_decimal", "icu_decimal", @@ -749,10 +796,44 @@ dependencies = [ "writeable", ] +[[package]] +name = "craft-keymap" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" +dependencies = [ + "egui", + "serde", + "serde_json", +] + +[[package]] +name = "craft-menu" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" +dependencies = [ + "craft-keymap", + "craft-quit", + "egui", + "muda", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", +] + +[[package]] +name = "craft-quit" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" +dependencies = [ + "dispatch2", + "egui", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", +] + [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242" +source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" dependencies = [ "craft-fonts-build", "craft-i18n", @@ -770,10 +851,36 @@ dependencies = [ "web-sys", ] +[[package]] +name = "craft-update" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" +dependencies = [ + "chrono", + "dunce", + "egui", + "flate2", + "getrandom 0.3.4", + "image", + "log", + "plist", + "semver", + "serde", + "serde_json", + "sha2", + "tar", + "tempfile", + "ureq", + "verifysign", + "winreg", + "winsafe", + "zip", +] + [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242" +source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" dependencies = [ "egui", "objc2 0.6.5", @@ -790,6 +897,15 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "crossbeam-channel" +version = "0.5.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" +dependencies = [ + "crossbeam-utils", +] + [[package]] name = "crossbeam-deque" version = "0.8.8" @@ -821,6 +937,16 @@ version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + [[package]] name = "cursor-icon" version = "1.2.0" @@ -861,6 +987,22 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + [[package]] name = "dispatch" version = "0.2.0" @@ -920,6 +1062,12 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76" +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + [[package]] name = "dyn-clone" version = "1.0.20" @@ -1171,7 +1319,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.60.2", ] [[package]] @@ -1252,6 +1400,16 @@ version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b97b65636e5b9ef369943878ac74335ba1c55c1cb6adbf1e2c293c624248d693" +[[package]] +name = "filetime" +version = "0.2.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759" +dependencies = [ + "cfg-if", + "libc", +] + [[package]] name = "find-msvc-tools" version = "0.1.14" @@ -1447,6 +1605,16 @@ dependencies = [ "slab", ] +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + [[package]] name = "gethostname" version = "1.1.0" @@ -1457,6 +1625,17 @@ dependencies = [ "windows-link", ] +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + [[package]] name = "getrandom" version = "0.3.4" @@ -1728,6 +1907,22 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + [[package]] name = "iana-time-zone" version = "0.1.65" @@ -2103,6 +2298,16 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "keyboard-types" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fbe853b403ae61a04233030ae8a79d94975281ed9770a1f9e246732b534b28d" +dependencies = [ + "bitflags 2.13.2", + "serde", +] + [[package]] name = "khronos-egl" version = "6.0.0" @@ -2322,6 +2527,24 @@ dependencies = [ "pxfm", ] +[[package]] +name = "muda" +version = "0.21.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4340e89c178916e62879c5c36b7f699019369be413e496178a6983ce91b8bc03" +dependencies = [ + "crossbeam-channel", + "dpi", + "keyboard-types", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "png", + "thiserror 2.0.21", + "windows-sys 0.60.2", +] + [[package]] name = "naga" version = "30.0.1" @@ -2427,6 +2650,12 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + [[package]] name = "num-traits" version = "0.2.19" @@ -2776,6 +3005,12 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "openssl-probe" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" + [[package]] name = "orbclient" version = "0.3.55" @@ -2812,7 +3047,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.60.2", ] [[package]] @@ -2978,6 +3213,19 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" +[[package]] +name = "plist" +version = "1.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "327a4cb2ad49dc48adfdc9da89e22c64d488b508c67a044d71ba729e4521a285" +dependencies = [ + "base64 0.23.1", + "indexmap", + "quick-xml 0.42.0", + "serde", + "time", +] + [[package]] name = "png" version = "0.18.1" @@ -3062,6 +3310,12 @@ dependencies = [ "zerovec", ] +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + [[package]] name = "presser" version = "0.3.1" @@ -3136,6 +3390,15 @@ dependencies = [ "memchr", ] +[[package]] +name = "quick-xml" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b" +dependencies = [ + "memchr", +] + [[package]] name = "quote" version = "1.0.47" @@ -3320,6 +3583,20 @@ dependencies = [ "windows-sys 0.61.2", ] +[[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.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + [[package]] name = "rmcp" version = "3.5.1" @@ -3414,7 +3691,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.12.1", - "windows-sys 0.52.0", + "windows-sys 0.60.2", ] [[package]] @@ -3427,6 +3704,80 @@ dependencies = [ "rustix 1.1.5", ] +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-native-certs" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-platform-verifier" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" +dependencies = [ + "core-foundation 0.10.1", + "core-foundation-sys", + "jni", + "log", + "once_cell", + "rustls", + "rustls-native-certs", + "rustls-platform-verifier-android", + "rustls-webpki", + "security-framework", + "security-framework-sys", + "webpki-root-certs", + "windows-sys 0.60.2", +] + +[[package]] +name = "rustls-platform-verifier-android" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" + +[[package]] +name = "rustls-webpki" +version = "0.103.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + [[package]] name = "rustversion" version = "1.0.23" @@ -3442,6 +3793,15 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "schannel" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "schemars" version = "1.2.3" @@ -3480,6 +3840,29 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags 2.13.2", + "core-foundation 0.10.1", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "self_cell" version = "1.3.0" @@ -3491,6 +3874,10 @@ name = "semver" version = "1.0.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" +dependencies = [ + "serde", + "serde_core", +] [[package]] name = "send_wrapper" @@ -3572,6 +3959,17 @@ dependencies = [ "serde_core", ] +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + [[package]] name = "shlex" version = "2.0.1" @@ -3743,6 +4141,12 @@ 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 = "syn" version = "2.0.119" @@ -3788,6 +4192,16 @@ dependencies = [ "web-sys", ] +[[package]] +name = "tar" +version = "0.4.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840" +dependencies = [ + "filetime", + "libc", +] + [[package]] name = "tempfile" version = "3.27.0" @@ -3795,10 +4209,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.3.4", + "getrandom 0.4.3", "once_cell", "rustix 1.1.5", - "windows-sys 0.52.0", + "windows-sys 0.60.2", ] [[package]] @@ -3814,6 +4228,8 @@ dependencies = [ name = "texturecraft" version = "0.3.1" dependencies = [ + "craft-menu", + "craft-update", "eframe", "egui", "image", @@ -3925,7 +4341,7 @@ dependencies = [ "half", "image", "lz4_flex", - "quick-xml", + "quick-xml 0.41.0", "rayon", "serde", "serde_json", @@ -3992,7 +4408,11 @@ name = "texturecraft-ui-egui" version = "0.3.1" dependencies = [ "base64 0.22.1", + "craft-dialogs", + "craft-keymap", + "craft-quit", "craft-ui", + "craft-update", "craft-window", "eframe", "egui", @@ -4084,6 +4504,36 @@ dependencies = [ "zune-jpeg", ] +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + [[package]] name = "tinystr" version = "0.8.5" @@ -4266,6 +4716,12 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c" +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + [[package]] name = "uds_windows" version = "1.2.1" @@ -4313,6 +4769,41 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "ureq" +version = "3.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7be76686bdf7198002062423ca0d8cf9b75a27c8e1de804513b97e97b555d9d" +dependencies = [ + "base64 0.23.1", + "flate2", + "log", + "percent-encoding", + "rustls", + "rustls-pki-types", + "rustls-platform-verifier", + "ureq-proto", + "utf8-zero", +] + +[[package]] +name = "ureq-proto" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622dce33c252115466d83f63e9744a18f12b4406aae51a01c15ad8fcf1185eb3" +dependencies = [ + "base64 0.23.1", + "http", + "httparse", + "log", +] + [[package]] name = "urlencoding" version = "2.1.3" @@ -4328,6 +4819,12 @@ dependencies = [ "utf_types", ] +[[package]] +name = "utf8-zero" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e" + [[package]] name = "utf8_iter" version = "1.1.0" @@ -4382,6 +4879,16 @@ dependencies = [ "vello_common", ] +[[package]] +name = "verifysign" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6efd25aadc22c756a9012267fae0b130278d335d6ceb512ec02ce82029b5ca9" +dependencies = [ + "core-foundation 0.10.1", + "windows-sys 0.61.2", +] + [[package]] name = "version_check" version = "0.9.5" @@ -4562,7 +5069,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0" dependencies = [ "proc-macro2", - "quick-xml", + "quick-xml 0.41.0", "quote", ] @@ -4598,6 +5105,15 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "webpki-root-certs" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e49d0e65abc00c142e8f9428da991da9f1a250c39be97459901eb12b9b49f62a" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "weezl" version = "0.1.12" @@ -4793,7 +5309,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.52.0", + "windows-sys 0.60.2", ] [[package]] @@ -5096,7 +5612,7 @@ dependencies = [ "calloop", "cfg_aliases", "concurrent-queue", - "core-foundation", + "core-foundation 0.9.4", "core-graphics", "cursor-icon", "dpi", @@ -5141,6 +5657,16 @@ dependencies = [ "memchr", ] +[[package]] +name = "winreg" +version = "0.55.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb5a765337c50e9ec252c2069be9bf91c7df47afb103b642ba3a53bf8101be97" +dependencies = [ + "cfg-if", + "windows-sys 0.59.0", +] + [[package]] name = "winresource" version = "0.1.34" @@ -5457,6 +5983,12 @@ dependencies = [ "synstructure", ] +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + [[package]] name = "zerotrie" version = "0.2.5" diff --git a/Cargo.toml b/Cargo.toml index 02b5a6dc..73a090c8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -63,9 +63,19 @@ getrandom = "0.3" rustix = { version = "1", default-features = false, features = ["std", "fs", "process"] } # Shared Craft egui components (widget palette, icon buttons, panel docking): storytold/craft-libs, # MIT OR Apache-2.0, pinned to one rev. -craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242", features = ["serde"] } +craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["serde"] } # Who draws the window frame, and the app-drawn strip as the title bar (crates/ui-egui/src/titlebar.rs). -craft-window = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242", features = ["egui"] } +craft-window = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["egui"] } +# Release checks, the update prompt and the update helper (crates/ui-egui/src/updates_ui.rs). +craft-update = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["egui"] } +# File dialogs that never block the frame (crates/ui-egui/src/file_dialogs.rs). +craft-dialogs = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" } +# Shortcut chords, lookup and dispatch (crates/ui-egui/src/keymap.rs). +craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["egui"] } +# Quitting the macOS way instead of closing the window (crates/ui-egui/src/windows.rs). +craft-quit = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["egui"] } +# The macOS app menu whose Quit asks about unsaved changes (apps/texturecraft/src/main.rs). +craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" } # egui 0.37 and winit: the suite's forks (storytold/egui, storytold/winit), as craft-libs pins them. [patch.crates-io] diff --git a/README.md b/README.md index 80f807b6..69cd720c 100644 --- a/README.md +++ b/README.md @@ -32,6 +32,7 @@ MCP server for agents License: MIT OR Apache-2.0
+ Scanned by SonarCloud Reviewed by CodeRabbit

diff --git a/apps/texturecraft/Cargo.toml b/apps/texturecraft/Cargo.toml index 2f80d416..b4a1d57c 100644 --- a/apps/texturecraft/Cargo.toml +++ b/apps/texturecraft/Cargo.toml @@ -30,6 +30,12 @@ ron = "0.12" [target.'cfg(windows)'.dependencies] winit = { version = "0.30", default-features = false } winsafe = { version = "0.0.29", default-features = false, features = ["user"] } +# The update helper is a copy of this program (`main`). +craft-update = { workspace = true } + +# Quit (Cmd+Q) asks about unsaved changes (src/main.rs); winit's own Quit does not. +[target.'cfg(target_os = "macos")'.dependencies] +craft-menu = { workspace = true } [build-dependencies] winresource = "0.1" diff --git a/apps/texturecraft/src/main.rs b/apps/texturecraft/src/main.rs index 377b2e52..4965c438 100644 --- a/apps/texturecraft/src/main.rs +++ b/apps/texturecraft/src/main.rs @@ -11,11 +11,17 @@ mod window_frame; use texturecraft_engine::Session; use texturecraft_ui_egui::titlebar::TitleBar; +use texturecraft_ui_egui::ui_state_store; use texturecraft_ui_egui::{TextureCraftApp, UiState}; /// The app name eframe keeps the settings under (`eframe::storage_dir`). const APP_NAME: &str = "TextureCraft"; +/// The window's size when it opens, in points. +const DEFAULT_SIZE: [f32; 2] = [1600.0, 960.0]; +/// The smallest size the window can be resized to, in points. +const MIN_SIZE: [f32; 2] = [960.0, 600.0]; + const ICON_PNG: &[u8] = include_bytes!("../../../assets/app-icon/hicolor/256x256/apps/ai.storyteller.texturecraft.png"); fn version() -> String { @@ -115,13 +121,16 @@ fn set_taskbar_icon(w: &winit::window::Window) { } } -/// Settings › Interface › System title bar, read from the saved settings before the window opens -/// (eframe hands the app its storage only afterwards). Missing or unreadable: off. -fn saved_system_title_bar(persistence_path: Option<&std::path::Path>) -> bool { - let file = persistence_path.map(std::path::Path::to_path_buf).or_else(|| eframe::storage_dir(APP_NAME).map(|d| d.join("app.ron"))); - let saved = file.and_then(|f| std::fs::read_to_string(f).ok()); - let kv = saved.and_then(|s| ron::from_str::>(&s).ok()); - kv.and_then(|kv| ron::from_str::(kv.get("ui")?).ok()).is_some_and(|ui| ui.prefs.system_title_bar) +/// Settings › Interface › System title bar, read before the window opens from `ui.json`, else as earlier builds saved it; missing or unreadable: off +fn saved_system_title_bar(ui_file: Option<&std::path::Path>, persistence_path: Option<&std::path::Path>) -> bool { + if let Some(ui) = ui_file.and_then(ui_state_store::read) { + return ui.prefs.system_title_bar; + } + + let file = persistence_path.map(std::path::Path::to_path_buf).or_else(|| eframe::storage_dir(APP_NAME).map(|folder| folder.join("app.ron"))); + let saved = file.and_then(|file| std::fs::read_to_string(file).ok()); + let entries = saved.and_then(|text| ron::from_str::>(&text).ok()); + entries.and_then(|entries| ron::from_str::(entries.get("ui")?).ok()).is_some_and(|ui| ui.prefs.system_title_bar) } /// The app with the window chrome that needs the native window: the Windows borderless guard, and @@ -161,7 +170,17 @@ impl eframe::App for Shell { } } +/// A script driving the app gets no network check and no update prompt over its window. +fn checks_for_updates_at_start(control: Option) -> bool { + control.is_none() +} + fn main() { + // Windows: the update helper is a copy of this program started with `--finish-update`. + #[cfg(windows)] + if let Some(result) = craft_update::self_update::finish(&texturecraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::>()) { + std::process::exit(i32::from(result.is_err())); + } let args = match parse_args() { Ok(Some(a)) => a, Ok(None) => return, @@ -170,21 +189,25 @@ fn main() { std::process::exit(2); } }; - // Errors before the window opens speak the system's language; the app then applies the saved one. + // Errors before the window opens speak the system's language; the app then applies the saved one texturecraft_ui_egui::i18n::set_language(texturecraft_ui_egui::i18n::os_language()); let prev = std::panic::take_hook(); std::panic::set_hook(Box::new(move |info| { - // A message box needs the main thread on macOS; other threads' panics are only logged. + // A message box needs the main thread on macOS; other threads' panics are only logged fatal(&format!("internal error: {info}"), std::thread::current().name() == Some("main")); prev(info); })); let session = initial_session(&args); - // Scripted runs (agents, films, tests) set TEXTURECRAFT_NO_PREFS so they neither read nor - // overwrite the user's saved UI layout and settings: state goes to a throwaway folder. + // Scripted runs (agents, films, tests) set TEXTURECRAFT_NO_PREFS to keep the user's saved settings untouched: state goes to throwaway files let persistence_path = std::env::var_os("TEXTURECRAFT_NO_PREFS").map(|_| std::env::temp_dir().join(format!("texturecraft-noprefs-{}.ron", std::process::id()))); - let title_bar = TitleBar::decide(saved_system_title_bar(persistence_path.as_deref())); - let mut viewport = egui::ViewportBuilder::default().with_title(APP_NAME).with_inner_size([1600.0, 960.0]).with_min_inner_size([960.0, 600.0]); + let ui_file = + persistence_path.as_ref().map(|path| path.with_extension("json")).or_else(|| eframe::storage_dir(APP_NAME).map(|folder| folder.join("ui.json"))); + if let Some(file) = &ui_file { + let _ = ui_state_store::FILE.set(file.clone()); + } + let title_bar = TitleBar::decide(saved_system_title_bar(ui_file.as_deref(), persistence_path.as_deref())); + let mut viewport = egui::ViewportBuilder::default().with_title(APP_NAME).with_inner_size(DEFAULT_SIZE).with_min_inner_size(MIN_SIZE); if let Some(i) = icon() { viewport = viewport.with_icon(i); } @@ -195,7 +218,7 @@ fn main() { std::process::exit(2); } let control = args.control; - // The start window offers new, open and recent projects, unless a file was given or a script drives the app. + // The start window offers new, open and recent projects, unless a file was given or a script drives the app let start = args.file.is_none() && control.is_none(); let r = eframe::run_native( APP_NAME, @@ -205,10 +228,16 @@ fn main() { if let Some(w) = cc.winit_window() { set_taskbar_icon(w); } + // winit's Quit ends the process without asking; this menu's asks like the close button. + #[cfg(target_os = "macos")] + if let Err(e) = craft_menu::mac::install_app_menu(&cc.egui_ctx, APP_NAME) { + log::warn!("the app menu could not be installed: {e}"); + } let window_frame = window_frame::service(cc, matches!(title_bar, TitleBar::App(_))); let mut app = TextureCraftApp::new(cc, session); app.title_bar = title_bar; app.ui.windows.start = start && app.ui.prefs.start_window; + app.set_startup_update_check(checks_for_updates_at_start(control)); if let Some(port) = control { app.control = Some(control_server::start(port, cc.egui_ctx.clone())); } @@ -274,6 +303,12 @@ mod tests { assert_eq!(args.gpu.as_deref(), Some("3080")); } + #[test] + fn only_a_run_without_a_control_port_checks_for_updates_at_start() { + assert!(checks_for_updates_at_start(None)); + assert!(!checks_for_updates_at_start(Some(9000))); + } + #[test] fn rejects_missing_or_invalid_gpu_args() { assert!(parse_args_from(["--gpu".to_string()]).is_err()); @@ -296,19 +331,27 @@ mod tests { } #[test] - fn the_system_title_bar_setting_is_read_from_eframes_settings_file() { - let path = std::env::temp_dir().join(format!("texturecraft-titlebar-test-{}.ron", std::process::id())); + fn the_system_title_bar_setting_is_read_from_ui_json_else_as_earlier_builds_saved_it() { + let ron_path = std::env::temp_dir().join(format!("texturecraft-titlebar-test-{}.ron", std::process::id())); + let json_path = ron_path.with_extension("json"); for on in [false, true] { let mut ui = UiState::default(); ui.prefs.system_title_bar = on; - // Written as eframe writes it: a pretty RON map of RON strings. + // Written as eframe writes it: a pretty RON map of RON strings let kv = std::collections::HashMap::from([("ui".to_string(), ron::to_string(&ui).unwrap())]); - std::fs::write(&path, ron::Options::default().to_string_pretty(&kv, Default::default()).unwrap()).unwrap(); - assert_eq!(saved_system_title_bar(Some(&path)), on); + std::fs::write(&ron_path, ron::Options::default().to_string_pretty(&kv, Default::default()).unwrap()).unwrap(); + assert_eq!(saved_system_title_bar(None, Some(&ron_path)), on); + + ui.prefs.system_title_bar = !on; + std::fs::write(&json_path, serde_json::to_vec(&ui).unwrap()).unwrap(); + assert_eq!(saved_system_title_bar(Some(&json_path), Some(&ron_path)), !on, "ui.json comes first"); } - std::fs::write(&path, "not ron").unwrap(); - assert!(!saved_system_title_bar(Some(&path))); - std::fs::remove_file(&path).unwrap(); - assert!(!saved_system_title_bar(Some(&path))); + + std::fs::write(&json_path, "not json").unwrap(); + std::fs::write(&ron_path, "not ron").unwrap(); + assert!(!saved_system_title_bar(Some(&json_path), Some(&ron_path))); + std::fs::remove_file(&json_path).unwrap(); + std::fs::remove_file(&ron_path).unwrap(); + assert!(!saved_system_title_bar(Some(&json_path), Some(&ron_path))); } } diff --git a/crates/automation/src/security.rs b/crates/automation/src/security.rs index 0f5e6ab5..63c12b0e 100644 --- a/crates/automation/src/security.rs +++ b/crates/automation/src/security.rs @@ -178,8 +178,11 @@ pub struct ConnectionLimiter(Arc); pub struct Permit(Arc); impl ConnectionLimiter { - pub fn try_acquire(&self, max: usize) -> Option { - self.0.fetch_update(Ordering::AcqRel, Ordering::Acquire, |n| (n < max).then_some(n + 1)).ok().map(|_| Permit(self.0.clone())) + pub fn try_acquire(&self, max_connections: usize) -> Option { + self.0 + .try_update(Ordering::AcqRel, Ordering::Acquire, |connections| (connections < max_connections).then_some(connections + 1)) + .ok() + .map(|_| Permit(self.0.clone())) } } @@ -328,10 +331,12 @@ mod tests { #[test] fn limiter_releases() { - let l = ConnectionLimiter::default(); - let p = l.try_acquire(1).unwrap(); - assert!(l.try_acquire(1).is_none()); - drop(p); - assert!(l.try_acquire(1).is_some()); + let limiter = ConnectionLimiter::default(); + + let permit = limiter.try_acquire(1).unwrap(); + assert!(limiter.try_acquire(1).is_none()); + + drop(permit); + assert!(limiter.try_acquire(1).is_some()); } } diff --git a/crates/automation/src/workspace.rs b/crates/automation/src/workspace.rs index 2015c090..1061db2d 100644 --- a/crates/automation/src/workspace.rs +++ b/crates/automation/src/workspace.rs @@ -127,20 +127,20 @@ fn file_error(op: &str, path: &str, e: std::io::Error) -> AutomationError { AutomationError::Io(format!("{op} `{path}` failed: {e}")) } -/// Engine commands that take host paths (`file.open`, `file.exportTextures`, `resource.import`, -/// `material.save`, …) would bypass the workspace: automation clients use the workspace-scoped -/// methods instead. Any command given a `path` or `dir` is refused, and every `file.*` command -/// but `file.close` and `file.removeUnused` (`file.save` even without `path`: a headless session's path is -/// workspace-relative, not a host path; `file.reimportMesh` without `path` re-reads the -/// embedded mesh). +/// Host keys a command reads or writes a file through, at the top level or in each `files` entry +const HOST_PATH_KEYS: [&str; 2] = ["path", "dir"]; + +/// Refuses engine commands that would reach host paths around the workspace roots, so clients use the workspace tools pub fn authorize_command(id: &str, params: &Value) -> Result<(), AutomationError> { - let has_path = ["path", "dir"].iter().any(|k| params.get(k).is_some_and(|v| !v.is_null())); - let ok = match id { + let has_path = names_host_path(params) || params.get("files").and_then(Value::as_array).is_some_and(|files| files.iter().any(names_host_path)); + + // `file.save` is refused even without a path: a headless session's path is workspace-relative, not a host path + let allowed = match id { "file.close" | "file.removeUnused" => true, "file.reimportMesh" => !has_path, _ => !id.starts_with("file.") && !has_path, }; - if ok { + if allowed { Ok(()) } else { Err(bad(format!( @@ -149,6 +149,11 @@ pub fn authorize_command(id: &str, params: &Value) -> Result<(), AutomationError } } +/// Whether `params` names a host path or folder at its own top level +fn names_host_path(params: &Value) -> bool { + HOST_PATH_KEYS.iter().any(|key| params.get(key).is_some_and(|value| !value.is_null())) +} + #[cfg(test)] mod tests { use super::*; @@ -243,6 +248,18 @@ mod tests { assert!(authorize_command("layer.add.fill", &json!({"color": "#ff0000", "path": null})).is_ok()); } + #[test] + fn nested_file_paths_are_denied() { + let outside_file = json!({"files": [{"path": "/etc/x_ao.png", "map": "ao"}]}); + assert!(authorize_command("textureSet.meshMap.import", &outside_file).is_err()); + + let one_of_many = json!({"files": [{"map": "ao"}, {"path": "/etc/x_ao.png"}]}); + assert!(authorize_command("textureSet.meshMap.import", &one_of_many).is_err()); + + let no_paths = json!({"files": [{"map": "ao"}, {"path": null}]}); + assert!(authorize_command("textureSet.meshMap.import", &no_paths).is_ok()); + } + /// Every registry command documenting a host path must be classified (fails when a new /// path-taking command is added without an automation policy). #[test] diff --git a/crates/bake/src/cage.rs b/crates/bake/src/cage.rs new file mode 100644 index 00000000..d2c7d7f3 --- /dev/null +++ b/crates/bake/src/cage.rs @@ -0,0 +1,15 @@ +//! Where the bake's transfer rays start, shared by the bake and the cage the 3D view draws + +mod cage_shell; +mod high_poly_reach; +mod ray_frame; +mod ray_start; +mod vertex_reach; + +#[cfg(test)] +pub(crate) use cage_shell::CORNERS; +pub use cage_shell::CageShell; +pub use high_poly_reach::HighPolyReach; +pub(crate) use ray_frame::RayFrame; +pub use ray_start::RayStart; +pub use vertex_reach::VertexReach; diff --git a/crates/bake/src/cage/cage_shell.rs b/crates/bake/src/cage/cage_shell.rs new file mode 100644 index 00000000..e1664219 --- /dev/null +++ b/crates/bake/src/cage/cage_shell.rs @@ -0,0 +1,65 @@ +use super::{RayFrame, RayStart}; +use crate::{BakeError, BakeRequest, MeshExtent}; +use rayon::prelude::*; +use std::collections::{HashMap, HashSet}; +use texturecraft_geom::glam::Vec3; +use texturecraft_geom::surface_at; + +/// Barycentric coordinates of a triangle's three corners +pub(crate) const CORNERS: [[f32; 2]; 3] = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]; + +/// The cage of one texture set as the bake sees it: where its transfer rays start at each corner of the set's triangles +#[derive(Clone, Debug, Default)] +pub struct CageShell { + /// Low-poly position of each triangle corner, three per triangle + pub positions: Vec, + pub starts: Vec, + /// Corner pairs along the low poly's polygon edges, for the wireframe + pub edges: Vec<[u32; 2]>, + /// World units per unit of the max frontal distance setting + pub cage_units: f32, +} + +impl CageShell { + /// The cage of `request`'s texture set, from the same ray starts the bake uses + pub fn new(request: &BakeRequest) -> Result { + let ray_frame = RayFrame::new(request, MeshExtent::of(request.mesh)?)?; + let (frame, mesh) = (&ray_frame, request.mesh); + let triangles: Vec = mesh.triangles_of(request.material).collect(); + let (positions, starts): (Vec, Vec) = triangles + .par_iter() + .flat_map_iter(|&triangle| { + CORNERS.into_iter().map(move |barycentric| match surface_at(mesh, triangle as u32, barycentric[0], barycentric[1]) { + Some(surface) => (surface.pos, frame.start(&surface, barycentric)), + None => (Vec3::ZERO, RayStart::Distance { up: Vec3::ZERO, scale: 0.0 }), + }) + }) + .unzip(); + + let wire_edges: HashSet<(u32, u32)> = mesh.wire_edges().into_iter().nth(request.material).unwrap_or_default().into_iter().collect(); + let mut edge_corners = HashMap::new(); + for (triangle_index, &triangle) in triangles.iter().enumerate() { + let Some(vertices) = mesh.tri(triangle) else { continue }; + + for corner in 0..3 { + let next = (corner + 1) % 3; + let (from, to) = (vertices[corner] as u32, vertices[next] as u32); + let key = (from.min(to), from.max(to)); + if wire_edges.contains(&key) { + let first_corner = (triangle_index * 3) as u32; + edge_corners.entry(key).or_insert([first_corner + corner as u32, first_corner + next as u32]); + } + } + } + let mut edges: Vec<[u32; 2]> = edge_corners.into_values().collect(); + edges.sort_unstable(); + + Ok(CageShell { positions, starts, edges, cage_units: ray_frame.cage_units }) + } + + /// Each corner's cage position at `max_frontal`, the setting before relative-to-bounding-box scaling + pub fn corners(&self, max_frontal: f32) -> Vec { + let frontal = max_frontal * self.cage_units; + self.positions.par_iter().zip(&self.starts).map(|(position, start)| start.origin(*position, frontal)).collect() + } +} diff --git a/crates/bake/src/cage/high_poly_reach.rs b/crates/bake/src/cage/high_poly_reach.rs new file mode 100644 index 00000000..2f461343 --- /dev/null +++ b/crates/bake/src/cage/high_poly_reach.rs @@ -0,0 +1,105 @@ +use super::{RayFrame, VertexReach}; +use crate::map::transfer_keys; +use crate::tracing::ANY; +use crate::{BakeError, BakeRequest, MeshExtent}; +use rayon::prelude::*; +use texturecraft_core::MeshMatchMode; +use texturecraft_geom::glam::Vec3; +use texturecraft_geom::{Mesh, surface_at}; + +/// Where each high-poly vertex sits relative to the transfer rays of one texture set, to show which parts its bake misses +#[derive(Clone, Debug, Default)] +pub struct HighPolyReach { + /// Per high-poly vertex; `None` where another texture set's low poly is nearer or the request has no high poly + pub vertices: Vec>, + /// World units per unit of the cage distance settings + pub cage_units: f32, + pub ignore_backface: bool, +} + +impl HighPolyReach { + /// The reach of `request`'s transfer rays at the high-poly vertices whose nearest low-poly point is on this set, from the same ray starts the bake uses there + pub fn new(request: &BakeRequest) -> Result { + let Some(high) = request.high else { return Ok(HighPolyReach::default()) }; + + let frame = RayFrame::new(request, MeshExtent::of(request.mesh)?)?; + let mut in_set = vec![false; request.mesh.triangle_count()]; + for triangle in request.mesh.triangles_of(request.material) { + if let Some(flag) = in_set.get_mut(triangle) { + *flag = true; + } + } + + let winding_normals = winding_normals(high.mesh); + let (low_keys, high_vertex_keys) = match request.settings.high_poly.match_mode { + MeshMatchMode::Always => (Vec::new(), Vec::new()), + MeshMatchMode::ByMeshName => { + let (low_keys, high_keys) = transfer_keys(request); + (low_keys, vertex_keys(high.mesh, &high_keys)) + } + }; + let key = |keys: &[u32], index: usize| keys.get(index).copied().unwrap_or(ANY); + let frame = &frame; + let vertices = high + .mesh + .positions + .par_iter() + .zip(&winding_normals) + .enumerate() + .map(|(vertex, (&high_position, &high_facing))| { + let nearest = request.bvh.nearest(high_position, f32::INFINITY, &|_| true)?; + if !in_set.get(nearest.tri as usize).copied().unwrap_or(false) { + return None; + } + + let surface = surface_at(request.mesh, nearest.tri, nearest.u, nearest.v)?; + let ray_key = key(&low_keys, nearest.tri as usize); + Some(VertexReach { + low_position: surface.pos, + start: frame.start(&surface, [nearest.u, nearest.v]), + high_position, + high_facing, + name_matches: ray_key == ANY || key(&high_vertex_keys, vertex) == ray_key, + }) + }) + .collect(); + + Ok(HighPolyReach { vertices, cage_units: frame.cage_units, ignore_backface: request.settings.high_poly.ignore_backface }) + } + + /// Whether the transfer rays miss high-poly vertex `vertex` at the `max_frontal` and `max_rear` settings; `None` when the vertex isn't this set's + pub fn missed(&self, vertex: usize, max_frontal: f32, max_rear: f32) -> Option { + let reach = self.vertices.get(vertex).copied().flatten()?; + Some(reach.missed(max_frontal * self.cage_units, max_rear * self.cage_units, self.ignore_backface)) + } +} + +/// Each vertex's mesh-name key, from the first triangle that uses it +fn vertex_keys(mesh: &Mesh, triangle_keys: &[u32]) -> Vec { + let mut keys = vec![ANY; mesh.positions.len()]; + for (corners, &triangle_key) in mesh.indices.as_chunks::<3>().0.iter().zip(triangle_keys) { + for &corner in corners { + if let Some(key) = keys.get_mut(corner as usize).filter(|key| **key == ANY) { + *key = triangle_key; + } + } + } + + keys +} + +/// Each vertex's sum of its triangles' winding normals, weighted by area: the side the bake's backface test sees as the front +fn winding_normals(mesh: &Mesh) -> Vec { + let mut normals = vec![Vec3::ZERO; mesh.positions.len()]; + for corners in mesh.indices.as_chunks::<3>().0 { + let position = |corner: u32| mesh.positions.get(corner as usize).copied().unwrap_or(Vec3::ZERO); + let winding_normal = (position(corners[1]) - position(corners[0])).cross(position(corners[2]) - position(corners[0])); + for &corner in corners { + if let Some(normal) = normals.get_mut(corner as usize) { + *normal += winding_normal; + } + } + } + + normals +} diff --git a/crates/bake/src/cage/ray_frame.rs b/crates/bake/src/cage/ray_frame.rs new file mode 100644 index 00000000..e8692cf2 --- /dev/null +++ b/crates/bake/src/cage/ray_frame.rs @@ -0,0 +1,63 @@ +use super::RayStart; +use crate::MeshExtent; +use crate::map::{interpolate, welded}; +use crate::skew::PreparedSkew; +use crate::{BakeError, BakePaintMap, BakeRequest}; +use texturecraft_core::CageType; +use texturecraft_geom::glam::Vec3; +use texturecraft_geom::{Mesh, Surface}; + +/// What decides where transfer rays start: the cage mesh or the averaged normals, skew and painted cage amount +pub(crate) struct RayFrame<'a> { + mesh: &'a Mesh, + ray_normals: Vec, + cage: Option<&'a Mesh>, + skew: Option>, + cage_paint: Option<&'a BakePaintMap>, + /// Cage-file offsets this short count as none: the ray starts from the distance-based cage instead + ray_epsilon: f32, + /// World units per unit of the cage distance settings + pub(crate) cage_units: f32, +} + +impl<'a> RayFrame<'a> { + pub(crate) fn new(request: &BakeRequest<'a>, extent: MeshExtent) -> Result, BakeError> { + let settings = request.settings; + let ray_normals = match settings.cage.average_normals && request.high.is_some() { + true => { + let (welded_indices, _, normals) = welded(request.mesh, extent.diagonal); + welded_indices.iter().map(|index| normals.get(*index as usize).copied().unwrap_or(Vec3::Y)).collect() + } + false => Vec::new(), + }; + + Ok(RayFrame { + mesh: request.mesh, + ray_normals, + cage: if settings.cage.kind == CageType::CustomFile { request.cage } else { None }, + skew: request.skew.map(|skew_map| PreparedSkew::new(skew_map, request.mesh, extent.scale, settings.skew)).transpose()?, + cage_paint: request.cage_paint, + ray_epsilon: extent.ray_epsilon(), + cage_units: if settings.cage.relative_to_bounding_box { extent.scale } else { 1.0 }, + }) + } + + /// Where the transfer ray of the low-poly point `surface` at `barycentric` starts + pub(crate) fn start(&self, surface: &Surface, barycentric: [f32; 2]) -> RayStart { + let cage_offset = self + .cage + .and_then(|cage_mesh| interpolate(cage_mesh, &cage_mesh.positions, surface.tri, barycentric)) + .map(|cage_position| surface.pos - cage_position) + .filter(|offset| offset.length() > self.ray_epsilon); + if let Some(offset) = cage_offset { + return RayStart::CageMesh(offset); + } + + let averaged_normal = interpolate(self.mesh, &self.ray_normals, surface.tri, barycentric).and_then(Vec3::try_normalize).unwrap_or(surface.nrm); + let up = match &self.skew { + Some(skew) => skew.correct(self.mesh, surface, averaged_normal), + None => averaged_normal, + }; + RayStart::Distance { up, scale: self.cage_paint.map_or(1.0, |map| map.sample(surface.uv)) } + } +} diff --git a/crates/bake/src/cage/ray_start.rs b/crates/bake/src/cage/ray_start.rs new file mode 100644 index 00000000..c0c3923a --- /dev/null +++ b/crates/bake/src/cage/ray_start.rs @@ -0,0 +1,20 @@ +use texturecraft_geom::glam::Vec3; + +/// Where the bake's transfer ray for one low-poly point starts +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum RayStart { + /// On the cage mesh: the offset from the cage to the low-poly point + CageMesh(Vec3), + /// Out along `up` by the frontal distance times `scale` (the painted cage amount) + Distance { up: Vec3, scale: f32 }, +} + +impl RayStart { + /// The ray origin for the low-poly point `position` at `frontal` world units of max frontal distance + pub fn origin(&self, position: Vec3, frontal: f32) -> Vec3 { + match *self { + RayStart::CageMesh(offset) => position - offset, + RayStart::Distance { up, scale } => position + up * frontal * scale, + } + } +} diff --git a/crates/bake/src/cage/vertex_reach.rs b/crates/bake/src/cage/vertex_reach.rs new file mode 100644 index 00000000..34adea92 --- /dev/null +++ b/crates/bake/src/cage/vertex_reach.rs @@ -0,0 +1,28 @@ +use super::RayStart; +use texturecraft_geom::glam::Vec3; + +/// One high-poly vertex seen from the transfer ray through its nearest low-poly point +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct VertexReach { + pub low_position: Vec3, + pub start: RayStart, + pub high_position: Vec3, + /// The side the high poly's triangles face at the vertex, by their winding (not normalized) + pub high_facing: Vec3, + /// Whether the bake lets this low-poly point's ray hit the vertex's part (always, unless matching by mesh name) + pub name_matches: bool, +} + +impl VertexReach { + /// Whether the ray misses the vertex (or may not hit its part) at `frontal` and `rear` world units of cage distance; with `ignore_backface` it also misses a vertex whose triangles face away from the ray + pub fn missed(&self, frontal: f32, rear: f32, ignore_backface: bool) -> bool { + let origin = self.start.origin(self.low_position, frontal); + let (direction, front) = match self.start { + RayStart::CageMesh(offset) => (offset.normalize_or_zero(), offset.length()), + RayStart::Distance { up, scale } => (-up, frontal * scale), + }; + let along_ray = (self.high_position - origin).dot(direction); + + !self.name_matches || !(0.0..=front + rear).contains(&along_ray) || (ignore_backface && self.high_facing.dot(direction) > 0.0) + } +} diff --git a/crates/bake/src/lib.rs b/crates/bake/src/lib.rs index a8b087bc..eb8a61de 100644 --- a/crates/bake/src/lib.rs +++ b/crates/bake/src/lib.rs @@ -6,13 +6,17 @@ mod bake_error; mod bake_output; mod bake_request; +mod cage; mod high_poly; +mod mesh_extent; mod progress; pub use bake_error::BakeError; pub use bake_output::BakeOutput; pub use bake_request::BakeRequest; +pub use cage::{CageShell, HighPolyReach, RayStart, VertexReach}; pub use high_poly::HighPoly; +pub(crate) use mesh_extent::MeshExtent; pub use progress::Progress; mod map; diff --git a/crates/bake/src/map.rs b/crates/bake/src/map.rs index 384d9d02..c9c30fd6 100644 --- a/crates/bake/src/map.rs +++ b/crates/bake/src/map.rs @@ -15,10 +15,13 @@ mod source; mod texel_grid; mod traced; mod transfer; +mod transfer_keys; pub(crate) use bake_context::BakeContext; pub(crate) use normal_curvature::curvature_from_normal; pub(crate) use sample::Sample; +pub(crate) use sampling::{interpolate, welded}; pub(crate) use texel_grid::TexelGrid; pub(crate) use traced::Traced; pub(crate) use transfer::Transfer; +pub(crate) use transfer_keys::transfer_keys; diff --git a/crates/bake/src/map/bake_context.rs b/crates/bake/src/map/bake_context.rs index 21fed094..f3e35df6 100644 --- a/crates/bake/src/map/bake_context.rs +++ b/crates/bake/src/map/bake_context.rs @@ -1,28 +1,22 @@ use super::curvature::Curvature; -use super::sampling::{interpolate, pack, splitmix64, tangent_normal, welded}; +use super::sampling::{pack, splitmix64, tangent_normal}; use super::{position_projection::PositionProjection, source::Source, traced::Traced, transfer::Transfer}; -use crate::skew::PreparedSkew; +use crate::cage::{RayFrame, RayStart}; use crate::tracing::{ANY, Hemisphere, Query, Ray, RayKind, RayScene, TraceMesh}; -use crate::{BakeError, BakeRequest}; +use crate::{BakeError, BakeRequest, MeshExtent}; use rayon::prelude::*; -use std::collections::HashMap; use texturecraft_core::{ - AmbientOcclusionAttenuation, BackfaceMode, BakeSettings, BakedMap, CageType, CurvatureMethod, MeshMatchMode, RayDistribution, RaySettings, SelfOcclusion, + AmbientOcclusionAttenuation, BackfaceMode, BakeSettings, BakedMap, CurvatureMethod, MeshMatchMode, RayDistribution, RaySettings, SelfOcclusion, }; -use texturecraft_geom::glam::Vec3; -use texturecraft_geom::{Hit, Mesh, Surface, surface_at}; +use texturecraft_geom::{Hit, Surface, surface_at}; const CURVATURE_CHUNK: usize = 1 << 15; pub(crate) struct BakeContext<'a> { low: Source<'a>, high: Option>, - cage: Option<&'a Mesh>, - skew: Option>, - cage_paint: Option<&'a crate::BakePaintMap>, - ray_normals: Vec, + ray_frame: RayFrame<'a>, settings: &'a BakeSettings, - eps: f32, frontal: f32, rear: f32, position: PositionProjection, @@ -36,36 +30,10 @@ pub(crate) struct BakeContext<'a> { impl<'a> BakeContext<'a> { pub(crate) fn new(request: &BakeRequest<'a>) -> Result, BakeError> { let settings = request.settings; - let (bounds_min, bounds_max) = request.mesh.bounds(); - let mesh_diagonal = (bounds_max - bounds_min).length().max(1e-6); - if !mesh_diagonal.is_finite() { - return Err(BakeError::Invalid("mesh bounds are too large".into())); - } - - let mesh_scale = (bounds_max - bounds_min).max_element().max(1e-6); - let mut name_keys = HashMap::new(); - let low = Source::new(request.mesh, request.bvh, request.low_base_color, &[], &settings.high_poly.low_suffix, &settings.high_poly, &mut name_keys); - let high = request.high.map(|high_mesh| { - Source::new( - high_mesh.mesh, - high_mesh.bvh, - high_mesh.base_color, - high_mesh.file_ids, - &settings.high_poly.high_suffix, - &settings.high_poly, - &mut name_keys, - ) - }); - let ray_normals = match settings.cage.average_normals && high.is_some() { - true => { - let (welded_indices, _, normals) = welded(request.mesh, mesh_diagonal); - welded_indices.iter().map(|index| normals.get(*index as usize).copied().unwrap_or(Vec3::Y)).collect() - } - false => Vec::new(), - }; - - let skew = request.skew.map(|skew_map| PreparedSkew::new(skew_map, request.mesh, mesh_scale, settings.skew)).transpose()?; - let ray_epsilon = 1e-6 * mesh_diagonal; + let extent = MeshExtent::of(request.mesh)?; + let (low, high) = Source::of_request(request); + let ray_frame = RayFrame::new(request, extent)?; + let (mesh_scale, ray_epsilon) = (extent.scale, extent.ray_epsilon()); let pass = |map: BakedMap, ray_settings: &RaySettings, kind: RayKind| { let half_angle_radians = (ray_settings.spread.clamp(0.0, 180.0) * 0.5).to_radians(); let units = if ray_settings.relative_to_bounding_box { mesh_scale } else { 1.0 }; @@ -91,27 +59,26 @@ impl<'a> BakeContext<'a> { pass.ignore_backface = parameters.ignore_backface; pass.same_key = parameters.self_occlusion == SelfOcclusion::SameMeshName; pass.attenuation = parameters.attenuation; - pass.ground_height = parameters.ground_plane.enabled.then_some(bounds_min.y - parameters.ground_plane.offset); + pass.ground_height = parameters.ground_plane.enabled.then_some(extent.bounds_min.y - parameters.ground_plane.offset); } + let mut bent = pass(BakedMap::BentNormal, &settings.maps.bent_normal.parameters.rays, RayKind::Occlusion); if let Some(pass) = &mut bent { pass.ignore_backface = settings.maps.bent_normal.parameters.ignore_backface; pass.same_key = settings.maps.bent_normal.parameters.self_occlusion == SelfOcclusion::SameMeshName; } + let mut thickness = pass(BakedMap::Thickness, &settings.maps.thickness.parameters.rays, RayKind::Thickness); if let Some(pass) = &mut thickness { pass.same_key = settings.maps.thickness.parameters.self_occlusion == SelfOcclusion::SameMeshName; } - let cage_units = if settings.cage.relative_to_bounding_box { mesh_scale } else { 1.0 }; + + let cage_units = ray_frame.cage_units; Ok(BakeContext { low, high, - cage: if settings.cage.kind == CageType::CustomFile { request.cage } else { None }, - skew, - cage_paint: request.cage_paint, - ray_normals, + ray_frame, settings, - eps: ray_epsilon, frontal: settings.cage.max_frontal * cage_units, rear: settings.cage.max_rear * cage_units, position: PositionProjection::new(request.mesh, request.material, settings.maps.position.parameters), @@ -140,22 +107,11 @@ impl<'a> BakeContext<'a> { } pub(crate) fn transfer_ray(&self, surface: &Surface, barycentric: [f32; 2]) -> (Ray, f32) { - let averaged_normal = interpolate(self.low.mesh, &self.ray_normals, surface.tri, barycentric).and_then(Vec3::try_normalize).unwrap_or(surface.nrm); - let cage = self - .cage - .and_then(|cage_mesh| interpolate(cage_mesh, &cage_mesh.positions, surface.tri, barycentric)) - .map(|cage_position| surface.pos - cage_position) - .filter(|offset| offset.length() > self.eps); - let cage_scale = self.cage_paint.map_or(1.0, |map| map.sample(surface.uv)); - let (origin, direction, front) = match cage { - Some(offset) => (surface.pos - offset, offset.normalize(), offset.length()), - None => { - let up = match &self.skew { - Some(skew) => skew.correct(self.low.mesh, surface, averaged_normal), - None => averaged_normal, - }; - (surface.pos + up * self.frontal * cage_scale, -up, self.frontal * cage_scale) - } + let start = self.ray_frame.start(surface, barycentric); + let origin = start.origin(surface.pos, self.frontal); + let (direction, front) = match start { + RayStart::CageMesh(offset) => (offset.normalize(), offset.length()), + RayStart::Distance { up, scale } => (-up, self.frontal * scale), }; let key = match self.settings.high_poly.match_mode { MeshMatchMode::Always => ANY, diff --git a/crates/bake/src/map/sampling.rs b/crates/bake/src/map/sampling.rs index d19e4afa..5f2d2677 100644 --- a/crates/bake/src/map/sampling.rs +++ b/crates/bake/src/map/sampling.rs @@ -3,34 +3,43 @@ use std::ops::{Add, Mul}; use texturecraft_geom::glam::Vec3; use texturecraft_geom::{Mesh, Surface}; -pub(super) fn interpolate + Add>(mesh: &Mesh, v: &[T], tri: u32, [b1, b2]: [f32; 2]) -> Option { - let [a, b, c] = mesh.tri(tri as usize)?; - Some(*v.get(a)? * (1.0 - b1 - b2) + *v.get(b)? * b1 + *v.get(c)? * b2) +/// `values` (one per vertex) at `barycentric` in triangle `triangle` +pub(crate) fn interpolate + Add>(mesh: &Mesh, values: &[T], triangle: u32, barycentric: [f32; 2]) -> Option { + let [first, second, third] = mesh.tri(triangle as usize)?; + let [second_weight, third_weight] = barycentric; + + Some(*values.get(first)? * (1.0 - second_weight - third_weight) + *values.get(second)? * second_weight + *values.get(third)? * third_weight) } -pub(super) fn welded(mesh: &Mesh, diag: f32) -> (Vec, Vec, Vec) { - let q = diag * 1e-5; - let mut ids: HashMap<[i64; 3], u32> = HashMap::new(); - let (mut pos, mut nrm) = (Vec::new(), Vec::::new()); - let weld: Vec = mesh +/// Vertices closer than this fraction of the mesh diagonal count as one when welding +const WELD_TOLERANCE_PER_DIAGONAL: f32 = 1e-5; + +/// Vertices that share a position merged: each vertex's welded index, the welded positions and their averaged normals +pub(crate) fn welded(mesh: &Mesh, diagonal: f32) -> (Vec, Vec, Vec) { + let tolerance = diagonal * WELD_TOLERANCE_PER_DIAGONAL; + let mut welded_index_of_cell: HashMap<[i64; 3], u32> = HashMap::new(); + let (mut positions, mut normal_sums) = (Vec::new(), Vec::::new()); + + let welded_indices: Vec = mesh .positions .iter() .zip(&mesh.normals) - .map(|(p, n)| { - let key = [p.x, p.y, p.z].map(|c| (c / q).round() as i64); - let id = *ids.entry(key).or_insert_with(|| { - pos.push(*p); - nrm.push(Vec3::ZERO); - (pos.len() - 1) as u32 + .map(|(position, normal)| { + let cell = [position.x, position.y, position.z].map(|coordinate| (coordinate / tolerance).round() as i64); + let welded_index = *welded_index_of_cell.entry(cell).or_insert_with(|| { + positions.push(*position); + normal_sums.push(Vec3::ZERO); + (positions.len() - 1) as u32 }); - if let Some(acc) = nrm.get_mut(id as usize) { - *acc += *n; + if let Some(normal_sum) = normal_sums.get_mut(welded_index as usize) { + *normal_sum += *normal; } - id + welded_index }) .collect(); - let nrm = nrm.into_iter().map(|n| n.try_normalize().unwrap_or(Vec3::ZERO)).collect(); - (weld, pos, nrm) + + let normals = normal_sums.into_iter().map(|normal_sum| normal_sum.try_normalize().unwrap_or(Vec3::ZERO)).collect(); + (welded_indices, positions, normals) } pub(super) fn splitmix64(x: u64) -> u64 { diff --git a/crates/bake/src/map/source.rs b/crates/bake/src/map/source.rs index 0e1f9164..ad057b11 100644 --- a/crates/bake/src/map/source.rs +++ b/crates/bake/src/map/source.rs @@ -1,4 +1,5 @@ use super::sampling::{generated_hue, interpolate, splitmix64}; +use crate::BakeRequest; use crate::tracing::{ANY, TraceMesh}; use std::collections::HashMap; use std::sync::Arc; @@ -21,6 +22,18 @@ pub(super) struct Source<'a> { } impl<'a> Source<'a> { + /// `request`'s low and high poly, their mesh names keyed from one shared table so the bake can match a low-poly part to its high-poly part + pub(super) fn of_request(request: &BakeRequest<'a>) -> (Source<'a>, Option>) { + let settings = &request.settings.high_poly; + let mut name_keys = HashMap::new(); + let low = Source::new(request.mesh, request.bvh, request.low_base_color, &[], &settings.low_suffix, settings, &mut name_keys); + let high = request.high.map(|high_mesh| { + Source::new(high_mesh.mesh, high_mesh.bvh, high_mesh.base_color, high_mesh.file_ids, &settings.high_suffix, settings, &mut name_keys) + }); + + (low, high) + } + pub(super) fn new( mesh: &'a Mesh, bvh: &'a Bvh, diff --git a/crates/bake/src/map/transfer_keys.rs b/crates/bake/src/map/transfer_keys.rs new file mode 100644 index 00000000..69e9b12a --- /dev/null +++ b/crates/bake/src/map/transfer_keys.rs @@ -0,0 +1,8 @@ +use super::source::Source; +use crate::BakeRequest; + +/// The bake's mesh-name key of each low-poly and each high-poly triangle: with By Mesh Name a transfer ray from a low-poly triangle only hits high-poly triangles with its key +pub(crate) fn transfer_keys(request: &BakeRequest) -> (Vec, Vec) { + let (low, high) = Source::of_request(request); + (low.key, high.map(|high| high.key).unwrap_or_default()) +} diff --git a/crates/bake/src/mesh_extent.rs b/crates/bake/src/mesh_extent.rs new file mode 100644 index 00000000..3c6fa48d --- /dev/null +++ b/crates/bake/src/mesh_extent.rs @@ -0,0 +1,35 @@ +use crate::BakeError; +use texturecraft_geom::Mesh; +use texturecraft_geom::glam::Vec3; + +/// Smallest size a mesh is treated as having, so a flat or empty mesh still gives finite distances +const MIN_MESH_SIZE: f32 = 1e-6; + +/// How far a ray starts past the surface it leaves, as a fraction of the mesh diagonal +const RAY_EPSILON_PER_DIAGONAL: f32 = 1e-6; + +/// The low-poly mesh's size, which scales the bake's relative distances +#[derive(Clone, Copy, Debug)] +pub(crate) struct MeshExtent { + pub(crate) bounds_min: Vec3, + pub(crate) diagonal: f32, + /// The bounding box's largest side + pub(crate) scale: f32, +} + +impl MeshExtent { + pub(crate) fn of(mesh: &Mesh) -> Result { + let (bounds_min, bounds_max) = mesh.bounds(); + let diagonal = (bounds_max - bounds_min).length().max(MIN_MESH_SIZE); + if !diagonal.is_finite() { + return Err(BakeError::Invalid("mesh bounds are too large".into())); + } + + Ok(MeshExtent { bounds_min, diagonal, scale: (bounds_max - bounds_min).max_element().max(MIN_MESH_SIZE) }) + } + + /// How far a ray starts past the surface it leaves, in world units + pub(crate) fn ray_epsilon(&self) -> f32 { + RAY_EPSILON_PER_DIAGONAL * self.diagonal + } +} diff --git a/crates/bake/src/test/cage_shell.rs b/crates/bake/src/test/cage_shell.rs new file mode 100644 index 00000000..2d114b06 --- /dev/null +++ b/crates/bake/src/test/cage_shell.rs @@ -0,0 +1,103 @@ +use super::settings; +use crate::cage::CORNERS; +use crate::map::BakeContext; +use crate::{BakePaintMap, BakeRequest, CageShell, HighPoly}; +use texturecraft_core::{BakedMap, CageType}; +use texturecraft_geom::glam::{Vec2, Vec3}; +use texturecraft_geom::{Bvh, Mesh, primitives, surface_at}; + +/// A painted map whose values vary over the UV square +fn painted_map() -> BakePaintMap { + let mut map = BakePaintMap::constant(0.25).resized(32, 32).unwrap(); + map.paint(&[Vec2::new(0.2, 0.3), Vec2::new(0.7, 0.6)], 0.3, 1.0, 0.5, 1.0).unwrap(); + map +} + +/// Every corner of `request`'s cage equals the origin of the bake's transfer ray at that corner, bit for bit +fn assert_cage_matches_the_ray_origins(request: &BakeRequest) { + let shell = CageShell::new(request).unwrap(); + let corners = shell.corners(request.settings.cage.max_frontal); + let context = BakeContext::new(request).unwrap(); + let triangles: Vec = request.mesh.triangles_of(request.material).collect(); + assert_eq!(corners.len(), triangles.len() * 3); + + for (corner_index, corner) in corners.iter().enumerate() { + let barycentric = CORNERS[corner_index % 3]; + let surface = surface_at(request.mesh, triangles[corner_index / 3] as u32, barycentric[0], barycentric[1]).unwrap(); + let (ray, _) = context.transfer_ray(&surface, barycentric); + assert_eq!(*corner, ray.origin, "corner {corner_index}"); + } +} + +#[test] +fn the_cage_corners_are_the_bake_ray_origins() { + let low = primitives::cube(1.0); + let high_mesh = primitives::sphere(0.8, 16, 8); + let (low_bvh, high_bvh) = (Bvh::new(&low), Bvh::new(&high_mesh)); + let high = HighPoly { file_ids: &[], mesh: &high_mesh, bvh: &high_bvh, base_color: &[] }; + let (skew, cage_paint) = (painted_map(), painted_map()); + let mut bake_settings = settings(16, &[BakedMap::Normal]); + bake_settings.cage.max_frontal = 0.03; + bake_settings.skew.edge_protection = true; + let request = |settings| BakeRequest { + low_base_color: &[], + mesh: &low, + bvh: &low_bvh, + material: 0, + settings, + high: Some(high), + cage: None, + skew: Some(&skew), + cage_paint: Some(&cage_paint), + tiles: (1, 1), + }; + + assert_cage_matches_the_ray_origins(&request(&bake_settings)); + let face_normals = { + let mut face_normals = bake_settings.clone(); + face_normals.cage.average_normals = false; + face_normals.cage.relative_to_bounding_box = false; + face_normals + }; + assert_cage_matches_the_ray_origins(&request(&face_normals)); +} + +#[test] +fn the_cage_follows_the_frontal_distance_and_a_cage_mesh() { + let low = primitives::cube(1.0); + let low_bvh = Bvh::new(&low); + let high = HighPoly { file_ids: &[], mesh: &low, bvh: &low_bvh, base_color: &[] }; + let mut bake_settings = settings(16, &[BakedMap::Normal]); + bake_settings.cage.relative_to_bounding_box = false; + let request = BakeRequest { + low_base_color: &[], + mesh: &low, + bvh: &low_bvh, + material: 0, + settings: &bake_settings, + high: Some(high), + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }; + let shell = CageShell::new(&request).unwrap(); + let distance_from_the_cube = |max_frontal: f32| shell.corners(max_frontal).iter().map(|corner| corner.abs().max_element() - 0.5).fold(0.0, f32::max); + + assert!(distance_from_the_cube(0.0).abs() < 1e-6, "at frontal 0 the cage is the low poly"); + // Averaged normals point diagonally at the corners, so a corner moves out by at least half the distance along each axis + assert!(distance_from_the_cube(0.2) > 0.1 && distance_from_the_cube(0.2) <= 0.2 + 1e-6, "the cage grows with the frontal distance"); + assert_eq!(shell.edges.len(), low.wire_edges()[0].len(), "one wireframe line per polygon edge"); + + let cage_mesh = Mesh { positions: low.positions.iter().map(|position| *position * 1.5).collect(), ..low.clone() }; + let custom_settings = { + let mut custom_settings = bake_settings.clone(); + custom_settings.cage.kind = CageType::CustomFile; + custom_settings + }; + let custom = BakeRequest { settings: &custom_settings, cage: Some(&cage_mesh), ..request }; + assert_cage_matches_the_ray_origins(&custom); + let corners = CageShell::new(&custom).unwrap().corners(0.0); + assert!(corners.iter().all(|corner| (corner.abs().max_element() - 0.75).abs() < 1e-6), "the cage mesh is drawn as it is"); + assert!(corners.iter().all(|corner| corner.is_finite() && *corner != Vec3::ZERO)); +} diff --git a/crates/bake/src/test/high_poly_reach.rs b/crates/bake/src/test/high_poly_reach.rs new file mode 100644 index 00000000..8a4f83c4 --- /dev/null +++ b/crates/bake/src/test/high_poly_reach.rs @@ -0,0 +1,223 @@ +use super::settings; +use crate::map::{BakeContext, transfer_keys}; +use crate::tracing::ANY; +use crate::{BakeRequest, HighPoly, HighPolyReach, RayStart}; +use texturecraft_core::{BakedMap, MeshMatchMode}; +use texturecraft_geom::glam::Vec3; +use texturecraft_geom::{Bvh, Mesh, primitives, surface_at}; + +/// Ray distances closer than this to the end of the ray's range are left out: rounding decides them +const BOUNDARY: f32 = 1e-4; + +/// How close the ray's hit must be to the vertex to count as reaching it +const HIT_TOLERANCE: f32 = 1e-4; + +/// A bumpy plane over the flat low poly, with the triangles right of `FLIPPED_FROM_X` wound the other way +fn bumpy_high_poly() -> (Mesh, Vec) { + const FLIPPED_FROM_X: f32 = 0.2; + + let mut mesh = primitives::plane(1.0, 40); + for position in &mut mesh.positions { + position.y = 0.04 * (position.x * 9.0).sin() * (position.z * 7.0).cos() + 0.005; + } + + let mut flipped = vec![false; mesh.positions.len()]; + let mut unflipped = vec![false; mesh.positions.len()]; + for corners in mesh.indices.as_chunks_mut::<3>().0 { + let center_x = corners.iter().map(|&corner| mesh.positions[corner as usize].x).sum::() / 3.0; + if center_x > FLIPPED_FROM_X { + corners.swap(1, 2); + } + for &corner in corners.iter() { + if center_x > FLIPPED_FROM_X { flipped[corner as usize] = true } else { unflipped[corner as usize] = true } + } + } + + // Vertices on the border face both ways: neither answer is right for them + let mixed = flipped.iter().zip(&unflipped).map(|(flipped, unflipped)| *flipped && *unflipped).collect(); + (mesh, mixed) +} + +#[test] +fn a_vertex_is_missed_exactly_when_the_bake_ray_misses_it() { + let low = primitives::plane(1.0, 8); + let (high_mesh, mixed) = bumpy_high_poly(); + let (low_bvh, high_bvh) = (Bvh::new(&low), Bvh::new(&high_mesh)); + let high = HighPoly { file_ids: &[], mesh: &high_mesh, bvh: &high_bvh, base_color: &[] }; + let back_facing = |triangle: u32, direction: Vec3| { + let [a, b, c] = high_mesh.tri(triangle as usize).unwrap().map(|corner| high_mesh.positions[corner]); + (b - a).cross(c - a).dot(direction) > 0.0 + }; + let mut checked = [0usize; 2]; + + for ignore_backface in [false, true] { + for (max_frontal, max_rear) in [(0.0, 0.01), (0.02, 0.0), (0.02, 0.01), (0.05, 0.05)] { + let mut bake_settings = settings(16, &[BakedMap::Normal]); + bake_settings.cage.relative_to_bounding_box = false; + bake_settings.high_poly.ignore_backface = ignore_backface; + (bake_settings.cage.max_frontal, bake_settings.cage.max_rear) = (max_frontal, max_rear); + let request = BakeRequest { + low_base_color: &[], + mesh: &low, + bvh: &low_bvh, + material: 0, + settings: &bake_settings, + high: Some(high), + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }; + let reach = HighPolyReach::new(&request).unwrap(); + let context = BakeContext::new(&request).unwrap(); + + for (vertex, vertex_reach) in reach.vertices.iter().enumerate() { + let (vertex_reach, missed) = (vertex_reach.unwrap(), reach.missed(vertex, max_frontal, max_rear).unwrap()); + let RayStart::Distance { scale, .. } = vertex_reach.start else { panic!("a distance-based cage") }; + let height = vertex_reach.high_position.y - vertex_reach.low_position.y; + let near_the_range_end = [max_frontal * scale, -max_rear].iter().any(|end| (height - end).abs() < BOUNDARY); + if near_the_range_end || mixed[vertex] { + continue; + } + + let nearest = low_bvh.nearest(vertex_reach.high_position, f32::INFINITY, &|_| true).unwrap(); + let surface = surface_at(&low, nearest.tri, nearest.u, nearest.v).unwrap(); + let (ray, _) = context.transfer_ray(&surface, [nearest.u, nearest.v]); + let hit = high_bvh + .closest_filtered(ray.origin, ray.direction, ray.max_distance, &|triangle| !(ignore_backface && back_facing(triangle, ray.direction))); + let reaches_the_vertex = hit.is_some_and(|hit| (ray.origin + ray.direction * hit.t - vertex_reach.high_position).length() < HIT_TOLERANCE); + assert_eq!( + missed, !reaches_the_vertex, + "vertex {vertex}, ignore backface {ignore_backface}, frontal {max_frontal}, rear {max_rear}: height {height}" + ); + checked[usize::from(missed)] += 1; + } + } + } + assert!(checked[0] > 100 && checked[1] > 100, "both reached and missed vertices were compared: {checked:?}"); +} + +#[test] +fn a_vertex_belongs_to_the_texture_set_whose_low_poly_is_nearest() { + let mut low = primitives::plane(1.0, 4); + let mut right = primitives::plane(1.0, 4); + for position in &mut right.positions { + position.x += 2.0; + } + low.append(&right); + assert_eq!(low.materials.len(), 2, "each plane is its own texture set"); + let mut high_mesh = primitives::plane(3.0, 30); + for position in &mut high_mesh.positions { + position.x += 1.0; + position.y = 0.3; + } + let (low_bvh, high_bvh) = (Bvh::new(&low), Bvh::new(&high_mesh)); + let bake_settings = settings(16, &[BakedMap::Normal]); + let request = |material| BakeRequest { + low_base_color: &[], + mesh: &low, + bvh: &low_bvh, + material, + settings: &bake_settings, + high: Some(HighPoly { file_ids: &[], mesh: &high_mesh, bvh: &high_bvh, base_color: &[] }), + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }; + let (left, right) = (HighPolyReach::new(&request(0)).unwrap(), HighPolyReach::new(&request(1)).unwrap()); + + for (vertex, position) in high_mesh.positions.iter().enumerate() { + let owners = (left.vertices[vertex].is_some(), right.vertices[vertex].is_some()); + assert!(owners != (true, true), "vertex {vertex} belongs to one set at most"); + if position.x < 0.9 { + assert_eq!(owners, (true, false), "vertex {vertex} at {position} is over the left set"); + } else if position.x > 1.1 { + assert_eq!(owners, (false, true), "vertex {vertex} at {position} is over the right set"); + } + } +} + +#[test] +fn matching_by_mesh_name_misses_the_parts_with_another_name() { + const HEIGHT_INSIDE_THE_CAGE: f32 = 0.01; + + let mut low = primitives::plane(1.0, 8); + low.submeshes[0].name = "part_low".into(); + let mut high_mesh = primitives::plane(0.5, 10); + let mut other_part = primitives::plane(0.5, 10); + for (mesh, center_x) in [(&mut high_mesh, -0.25), (&mut other_part, 0.25)] { + for position in &mut mesh.positions { + position.x += center_x; + position.y = HEIGHT_INSIDE_THE_CAGE; + } + } + high_mesh.append(&other_part); + high_mesh.submeshes[0].name = "part_high".into(); + high_mesh.submeshes[1].name = "other_high".into(); + let (low_bvh, high_bvh) = (Bvh::new(&low), Bvh::new(&high_mesh)); + let mut bake_settings = settings(16, &[BakedMap::Normal]); + bake_settings.cage.relative_to_bounding_box = false; + bake_settings.cage.max_frontal = 0.02; + bake_settings.high_poly.match_mode = MeshMatchMode::ByMeshName; + let request = BakeRequest { + low_base_color: &[], + mesh: &low, + bvh: &low_bvh, + material: 0, + settings: &bake_settings, + high: Some(HighPoly { file_ids: &[], mesh: &high_mesh, bvh: &high_bvh, base_color: &[] }), + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }; + let reach = HighPolyReach::new(&request).unwrap(); + let context = BakeContext::new(&request).unwrap(); + let (_, high_keys) = transfer_keys(&request); + + for (vertex, vertex_reach) in reach.vertices.iter().enumerate() { + let (vertex_reach, missed) = (vertex_reach.unwrap(), reach.missed(vertex, 0.02, 0.01).unwrap()); + // On the line where the two parts meet, a ray reaches either part's triangles + if vertex_reach.high_position.x.abs() < BOUNDARY { + continue; + } + + let nearest = low_bvh.nearest(vertex_reach.high_position, f32::INFINITY, &|_| true).unwrap(); + let surface = surface_at(&low, nearest.tri, nearest.u, nearest.v).unwrap(); + let (ray, _) = context.transfer_ray(&surface, [nearest.u, nearest.v]); + let same_name = |triangle: u32| ray.key == ANY || high_keys.get(triangle as usize) == Some(&ray.key); + let hit = high_bvh.closest_filtered(ray.origin, ray.direction, ray.max_distance, &same_name); + let reaches_the_vertex = hit.is_some_and(|hit| (ray.origin + ray.direction * hit.t - vertex_reach.high_position).length() < HIT_TOLERANCE); + assert_eq!(missed, !reaches_the_vertex, "vertex {vertex} at {}", vertex_reach.high_position); + assert_eq!( + missed, + vertex >= high_mesh.positions.len() - other_part.positions.len(), + "only the part named like the low poly is reached: vertex {vertex}" + ); + } +} + +#[test] +fn without_a_high_poly_no_vertex_has_a_reach() { + let low = primitives::plane(1.0, 4); + let low_bvh = Bvh::new(&low); + let bake_settings = settings(16, &[BakedMap::Normal]); + let request = BakeRequest { + low_base_color: &[], + mesh: &low, + bvh: &low_bvh, + material: 0, + settings: &bake_settings, + high: None, + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }; + + let reach = HighPolyReach::new(&request).unwrap(); + assert!(reach.vertices.is_empty()); + // Any cage distances: there is no vertex to miss + assert_eq!(reach.missed(0, 0.02, 0.01), None); +} diff --git a/crates/bake/src/test/setting.rs b/crates/bake/src/test/setting.rs index b490655d..668338a7 100644 --- a/crates/bake/src/test/setting.rs +++ b/crates/bake/src/test/setting.rs @@ -41,13 +41,18 @@ fn matching_skips_a_closer_unrelated_high_mesh_and_backfaces() { parameters.cage.relative_to_bounding_box = false; parameters.maps.height.parameters.normalization = HeightNormalization::Manual; let height = |parameters: &BakeSettings, high: &Mesh| transfer(&low, high, None, parameters).unwrap().maps[&BakedMap::Height][128]; + assert!((height(¶meters, &high) - 0.54).abs() < 1e-5); + parameters.high_poly.match_mode = MeshMatchMode::ByMeshName; assert!((height(¶meters, &high) - 0.52).abs() < 1e-5); - for triangle in high.indices.chunks_exact_mut(3) { + + for triangle in high.indices.as_chunks_mut::<3>().0 { triangle.swap(1, 2); } + assert_eq!(height(¶meters, &high), 0.5); + parameters.high_poly.ignore_backface = false; assert!((height(¶meters, &high) - 0.52).abs() < 1e-5); } @@ -159,12 +164,14 @@ fn position_axis_and_material_bounds_change_only_the_requested_space() { mesh.append(&distant); let mut parameters = settings(16, &[BakedMap::Position]); parameters.maps.position.parameters.axis = PositionAxis::X; + let global = run(&mesh, ¶meters).unwrap(); parameters.maps.position.parameters.scale = PositionNormalizationScale::PerMaterial; let local = run(&mesh, ¶meters).unwrap(); + assert!(global.maps[&BakedMap::Position].iter().all(|value| *value < 0.2)); assert!(local.maps[&BakedMap::Position].iter().any(|value| *value > 0.9)); - assert!(local.maps[&BakedMap::Position].chunks_exact(3).all(|pixel| pixel[0] == pixel[1] && pixel[1] == pixel[2])); + assert!(local.maps[&BakedMap::Position].as_chunks::<3>().0.iter().all(|pixel| pixel[0] == pixel[1] && pixel[1] == pixel[2])); } #[test] diff --git a/crates/bake/src/test/vertex_reach.rs b/crates/bake/src/test/vertex_reach.rs new file mode 100644 index 00000000..7675e8dc --- /dev/null +++ b/crates/bake/src/test/vertex_reach.rs @@ -0,0 +1,51 @@ +use crate::{RayStart, VertexReach}; +use texturecraft_geom::glam::Vec3; + +/// Cage distances in world units; every case's ray runs down the Y axis from 0.5 to -0.25 +const FRONTAL: f32 = 0.5; +const REAR: f32 = 0.25; + +/// A frontal distance a cage-mesh start must ignore: its ray starts on the cage +const IGNORED_FRONTAL: f32 = 9.0; + +/// How far past an end of the ray's range a vertex counts as outside it +const PAST_THE_END: f32 = 1e-3; + +/// A vertex at `height` above the low-poly point at the origin, its triangles facing `facing` +fn vertex(start: RayStart, height: f32, facing: Vec3, name_matches: bool) -> VertexReach { + VertexReach { low_position: Vec3::ZERO, start, high_position: Vec3::new(0.0, height, 0.0), high_facing: facing, name_matches } +} + +#[test] +fn a_vertex_is_missed_outside_the_ray_range_on_another_part_or_facing_away() { + // A painted cage amount of 2 doubles the frontal distance + let starts = [ + (RayStart::Distance { up: Vec3::Y, scale: 1.0 }, FRONTAL), + (RayStart::Distance { up: Vec3::Y, scale: 2.0 }, FRONTAL / 2.0), + (RayStart::CageMesh(Vec3::new(0.0, -FRONTAL, 0.0)), IGNORED_FRONTAL), + ]; + let (top, bottom) = (FRONTAL, -REAR); + // Height, facing, name matches, ignore backface: missed + let cases = [ + (top, Vec3::Y, true, false, false), + (bottom, Vec3::Y, true, false, false), + (0.0, Vec3::Y, true, false, false), + (top + PAST_THE_END, Vec3::Y, true, false, true), + (bottom - PAST_THE_END, Vec3::Y, true, false, true), + (0.0, Vec3::Y, false, false, true), + (0.0, Vec3::NEG_Y, true, false, false), + (0.0, Vec3::NEG_Y, true, true, true), + (0.0, Vec3::Y, true, true, false), + ]; + + for (start, frontal) in starts { + for (height, facing, name_matches, ignore_backface, missed) in cases { + let reach = vertex(start, height, facing, name_matches); + assert_eq!( + reach.missed(frontal, REAR, ignore_backface), + missed, + "{start:?} at height {height}, facing {facing}, name matches {name_matches}, ignore backface {ignore_backface}" + ); + } + } +} diff --git a/crates/bake/src/tests.rs b/crates/bake/src/tests.rs index 26c8665c..0c313462 100644 --- a/crates/bake/src/tests.rs +++ b/crates/bake/src/tests.rs @@ -14,6 +14,12 @@ use texturecraft_geom::primitives; use super::*; +#[path = "test/cage_shell.rs"] +mod cage_shell; + +#[path = "test/high_poly_reach.rs"] +mod high_poly_reach; + #[path = "test/setting.rs"] mod setting; @@ -23,6 +29,9 @@ mod normal_map_curvature; #[path = "test/tile_selection.rs"] mod tile_selection; +#[path = "test/vertex_reach.rs"] +mod vertex_reach; + fn settings(resolution: u32, maps: &[BakedMap]) -> BakeSettings { with_rays( { @@ -91,18 +100,20 @@ fn open_quad_is_unoccluded() { #[test] fn inside_of_a_closed_box_is_occluded() { - let mut m = primitives::cube(2.0); - for t in m.indices.chunks_exact_mut(3) { - t.swap(1, 2); + let mut mesh = primitives::cube(2.0); + for triangle in mesh.indices.as_chunks_mut::<3>().0 { + triangle.swap(1, 2); } - for n in &mut m.normals { - *n = -*n; + for normal in &mut mesh.normals { + *normal = -*normal; } - m.compute_tangents(); - let s = with_rays(settings(64, &[BakedMap::AmbientOcclusion]), 64, 4.0); - let out = run(&m, &s).unwrap(); - let ao = mean(covered_values(&m, &out, BakedMap::AmbientOcclusion).into_iter().map(|v| v.1)); - assert!(ao < 0.3, "{ao}"); + mesh.compute_tangents(); + let parameters = with_rays(settings(64, &[BakedMap::AmbientOcclusion]), 64, 4.0); + + let output = run(&mesh, ¶meters).unwrap(); + + let mean_occlusion = mean(covered_values(&mesh, &output, BakedMap::AmbientOcclusion).into_iter().map(|v| v.1)); + assert!(mean_occlusion < 0.3, "{mean_occlusion}"); } #[test] diff --git a/crates/compose/src/curvature_size_level.rs b/crates/compose/src/curvature_size_level.rs new file mode 100644 index 00000000..fcd25492 --- /dev/null +++ b/crates/compose/src/curvature_size_level.rs @@ -0,0 +1,50 @@ +/// Deviations of ±0.5 (curvature − 0.5) stored as 16-bit integers. +pub const DEVIATION_SCALE: f32 = i16::MAX as f32 * 2.0; + +/// Curvature blurred at one detail size: deviations from flat, stored `step` times coarser than the map. +pub struct CurvatureSizeLevel { + pub step: u32, + pub width: u32, + pub height: u32, + /// UV tile dimensions in stored texels; interpolation must stay inside one tile + pub block: (u32, u32), + pub deviation: Vec, +} + +impl CurvatureSizeLevel { + /// The deviation at map texel `(x, y)`, interpolated within its UV tile + pub fn sample(&self, x: u32, y: u32) -> f32 { + if self.width == 0 || self.height == 0 { + return 0.0; + } + + let step = self.step.max(1); + let axis = |texel: u32, block: u32, length: u32| { + let block = block.max(1); + let first = if block >= length { 0 } else { (texel / block.saturating_mul(step) * block).min(length - 1) }; + let last = first.saturating_add(block - 1).min(length - 1); + let position = ((texel as f32 + 0.5) / step as f32 - 0.5).clamp(first as f32, last as f32); + let lower = position.floor() as u32; + (lower, (lower + 1).min(last), position - lower as f32) + }; + let (x0, x1, blend_x) = axis(x, self.block.0, self.width); + let (y0, y1, blend_y) = axis(y, self.block.1, self.height); + let stored = |x: u32, y: u32| self.deviation.get((y * self.width + x) as usize).map_or(0.0, |value| f32::from(*value) / DEVIATION_SCALE); + let top = stored(x0, y0) + (stored(x1, y0) - stored(x0, y0)) * blend_x; + let bottom = stored(x0, y1) + (stored(x1, y1) - stored(x0, y1)) * blend_x; + top + (bottom - top) * blend_y + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn samples_blend_the_stored_texels() { + let level = CurvatureSizeLevel { step: 2, width: 2, height: 1, block: (2, 1), deviation: vec![0, (0.25 * DEVIATION_SCALE) as i16] }; + assert!(level.sample(0, 0).abs() < 1e-4, "the first stored texel covers map texels 0 and 1"); + assert!((level.sample(3, 0) - 0.25).abs() < 1e-3); + assert!(level.sample(2, 0) > 0.0 && level.sample(2, 0) < 0.25, "between stored texels the value blends"); + } +} diff --git a/crates/compose/src/curvature_sizes.rs b/crates/compose/src/curvature_sizes.rs new file mode 100644 index 00000000..d04e7f62 --- /dev/null +++ b/crates/compose/src/curvature_sizes.rs @@ -0,0 +1,447 @@ +//! The baked curvature map at the detail sizes of curvature generators, built once per map and layout. + +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex, Weak}; + +use rayon::prelude::*; +use texturecraft_core::{BakedMap, BlockScales, CurvatureDetail}; +use texturecraft_texel::dilate::{DilationMap, NONE}; + +use crate::curvature_size_level::{CurvatureSizeLevel, DEVIATION_SCALE}; +use crate::eval::{BLUR_BOX_PASSES, Inputs, blur}; + +/// The curvature map padded past its UV islands and blurred at each size of [`CurvatureDetail::SIZES`] after the first. +pub struct CurvatureSizes { + /// One per blurred size, built once a generator gives that size a weight above 0. + pub levels: Vec>>, +} + +/// The bake map size, its UV tile block and the working texture size a cache entry was built for. +type CacheKey = ((u32, u32), (u32, u32), (u32, u32)); + +/// Built sizes by the curvature data they come from, their layout and the tiles' scales. +type CacheEntry = (Weak>, CacheKey, BlockScales, Arc); + +static CACHE: Mutex> = Mutex::new(Vec::new()); + +// Undo snapshots keep old maps alive; their derived levels must not grow with the history +const CACHE_BYTES: usize = 256 << 20; +const CACHE_MAPS: usize = 16; + +impl CurvatureSizes { + /// The sizes of the texture set `inp` composites, holding at least those `needed` marks (one flag per blurred size); None without a baked curvature map or a needed size. + pub fn of(inp: &Inputs, needed: &[bool]) -> Option> { + let curvature = inp.baked.maps.get(&BakedMap::Curvature)?; + let (width, height) = (inp.baked.resolution, inp.baked.height(BakedMap::Curvature)); + if !needed.contains(&true) || width == 0 || height == 0 { + return None; + } + + let grid = inp.project.texture_set(inp.ts).ok().and_then(|set| set.tile_grid()); + let block = grid.map_or((width, height), |grid| (width / grid.cols.max(1), height / grid.rows.max(1))); + let key = ((width, height), block, (inp.gbuf.width, inp.gbuf.height)); + let built = cached(curvature, key, &inp.block_scales); + if let Some(sizes) = built.as_ref().filter(|sizes| sizes.holds(needed)) { + return Some(sizes.clone()); + } + + // Built without the cache locked: the build runs parallel work, and a thread waiting on it may composite a tile that asks the cache again + let covered = covered_texels(inp, (width, height)); + let sizes = CurvatureSizes::build(curvature, (width, height), &covered, block, needed, built.as_deref()); + Some(store(curvature, key, &inp.block_scales, sizes)) + } + + /// Whether every size `needed` marks is built. + fn holds(&self, needed: &[bool]) -> bool { + needed.iter().zip(&self.levels).all(|(needs, level)| !needs || level.is_some()) + } + + /// Pad and blur each UV tile at the requested sizes, reusing levels already in `built` + fn build( + curvature: &[f32], + (width, height): (u32, u32), + covered: &[bool], + block: (u32, u32), + needed: &[bool], + built: Option<&CurvatureSizes>, + ) -> CurvatureSizes { + let padding = DilationMap::in_rectangular_blocks(covered, width, height, None, block); + let deviation: Vec = + padding.src.par_iter().map(|&source| if source == NONE { 0.0 } else { curvature.get(source as usize).copied().unwrap_or(0.5) - 0.5 }).collect(); + let (block_width, block_height) = (block.0.max(1).min(width), block.1.max(1).min(height)); + + let levels = CurvatureDetail::SIZES + .iter() + .skip(1) + .enumerate() + .map(|(level, size)| { + if let Some(existing) = built.and_then(|sizes| sizes.levels.get(level)).and_then(Option::clone) { + return Some(existing); + } + if !needed.get(level).copied().unwrap_or(false) { + return None; + } + + // Sizes are texels at 2K; a blur this wide holds nothing finer than half its radius, so it is stored that much coarser + let radius = (size * block_width as f32 / 2048.0).round().max(1.0) as u32; + let mut step = (radius / 2).max(1).next_power_of_two(); + // A coarse cell must not average curvature from different UV tiles + while !block_width.is_multiple_of(step) || !block_height.is_multiple_of(step) { + step /= 2; + } + + let mut blurred = deviation.clone(); + for block_y in (0..height).step_by(block_height as usize) { + for block_x in (0..width).step_by(block_width as usize) { + let region = (block_x, block_y, block_width.min(width - block_x), block_height.min(height - block_y)); + blur_block(&mut blurred, width, region, radius); + } + } + Some(Arc::new(coarsen(&blurred, (width, height), step, (block_width, block_height)))) + }) + .collect(); + CurvatureSizes { levels } + } +} + +/// The cached sizes of `curvature` for layout `key` and tile `scales`, if any +fn cached(curvature: &Arc>, key: CacheKey, scales: &BlockScales) -> Option> { + let mut cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + cache.retain(|(source, ..)| source.strong_count() > 0); + let index = cache.iter().position(|entry| is_entry_for(entry, curvature, key, scales))?; + let entry = cache.remove(index); + let sizes = entry.3.clone(); + cache.push(entry); + Some(sizes) +} + +/// Cache `sizes`, merging any levels another thread stored meanwhile +fn store(curvature: &Arc>, key: CacheKey, scales: &BlockScales, sizes: CurvatureSizes) -> Arc { + let mut cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let sizes = if let Some((.., cached_sizes)) = cache.iter().find(|entry| is_entry_for(entry, curvature, key, scales)) { + let levels = cached_sizes.levels.iter().zip(sizes.levels).map(|(cached, built)| cached.clone().or(built)).collect(); + CurvatureSizes { levels } + } else { + sizes + }; + + // One layout per curvature map, with the most recently used map at the end + cache.retain(|(source, ..)| source.strong_count() > 0 && !std::ptr::eq(source.as_ptr(), Arc::as_ptr(curvature))); + let sizes = Arc::new(sizes); + cache.push((Arc::downgrade(curvature), key, scales.clone(), sizes.clone())); + trim_cache(&mut cache, CACHE_BYTES); + sizes +} + +/// Evict the least recently used maps, retaining the newest even if it alone exceeds the budget +fn trim_cache(cache: &mut Vec, budget: usize) { + // Keeping the newest prevents a large atlas from rebuilding its levels for every tile + let mut bytes = 0usize; + let mut keep = 0; + for (.., sizes) in cache.iter().rev() { + let size = sizes.levels.iter().flatten().map(|level| level.deviation.len().saturating_mul(size_of::())).fold(0usize, usize::saturating_add); + bytes = bytes.saturating_add(size); + if keep > 0 && (bytes > budget || keep == CACHE_MAPS) { + break; + } + keep += 1; + } + cache.drain(..cache.len() - keep); +} + +/// Whether cache `entry` holds the sizes of `curvature` for layout `key` and tile `scales`. +fn is_entry_for((source, cached_key, cached_scales, _): &CacheEntry, curvature: &Arc>, key: CacheKey, scales: &BlockScales) -> bool { + source.upgrade().is_some_and(|data| Arc::ptr_eq(&data, curvature)) && *cached_key == key && cached_scales == scales +} + +/// The bake atlas texels (`width × height`) overlapped by covered working texels of `inp` +fn covered_texels(inp: &Inputs, (width, height): (u32, u32)) -> Vec { + let working_size = (inp.gbuf.width, inp.gbuf.height); + if working_size == (width, height) && inp.block_scales == BlockScales::default() { + return (0..width * height).into_par_iter().map(|texel| inp.gbuf.covered(texel as usize)).collect(); + } + + let covered: Vec = (0..width * height).map(|_| AtomicBool::new(false)).collect(); + (0..working_size.0 * working_size.1).into_par_iter().filter(|texel| inp.gbuf.covered(*texel as usize)).for_each(|texel| { + let (x, y) = (texel % working_size.0, texel / working_size.0); + let uv = [(x as f32 + 0.5) / working_size.0 as f32, (y as f32 + 0.5) / working_size.1 as f32]; + if let Some(baked_uv) = inp.block_scales.bake_uv(uv, working_size) { + // A lower-resolution working texel covers a whole rectangle in the bake, not just its center + let scale = inp.block_scales.at(x, y); + let footprint = |center: f32, baked: u32, working: u32| { + let half_width = 0.5 * baked as f32 / (working as f32 * scale); + let center = center * baked as f32; + ((center - half_width).floor().max(0.0) as u32)..((center + half_width).ceil() as u32).min(baked) + }; + let columns = footprint(baked_uv[0], width, working_size.0); + for baked_y in footprint(baked_uv[1], height, working_size.1) { + for baked_x in columns.clone() { + if let Some(slot) = covered.get((baked_y * width + baked_x) as usize) { + slot.store(true, Ordering::Relaxed); + } + } + } + } + }); + covered.into_iter().map(AtomicBool::into_inner).collect() +} + +/// Blur the `(left, top, region_width, region_height)` block of `data` (`width` texels per row) in place, reading nothing outside it. +fn blur_block(data: &mut [f32], width: u32, (left, top, region_width, region_height): (u32, u32, u32, u32), radius: u32) { + let rows = top..top + region_height; + let mut block: Vec = + rows.flat_map(|y| (left..left + region_width).map(move |x| (y * width + x) as usize)).map(|index| data.get(index).copied().unwrap_or(0.0)).collect(); + blur(&mut block, region_width as usize, region_height as usize, radius as usize); + + // The blur reads zero past the block's edges; dividing by the share of its window inside the block keeps the edges at full strength + let column_weights = window_inside(region_width as usize, radius as usize); + let row_weights = window_inside(region_height as usize, radius as usize); + for (values, row_weight) in block.chunks_mut(region_width as usize).zip(&row_weights) { + for (value, column_weight) in values.iter_mut().zip(&column_weights) { + *value /= row_weight * column_weight; + } + } + + for (row, values) in block.chunks(region_width as usize).enumerate() { + let start = ((top + row as u32) * width + left) as usize; + if let Some(target) = data.get_mut(start..start + values.len()) { + target.copy_from_slice(values); + } + } +} + +/// The share of the [`blur`] window at each texel of a line `length` long that falls inside it: 1 from three radii in. +fn window_inside(length: usize, radius: usize) -> Vec { + let window = (2 * radius + 1) as f64; + let mut weights = vec![1.0f64; length]; + for _ in 0..BLUR_BOX_PASSES { + let running_totals: Vec = std::iter::once(0.0) + .chain(weights.iter().scan(0.0, |total, weight| { + *total += weight; + Some(*total) + })) + .collect(); + let total_at = |end: usize| running_totals.get(end.min(length)).copied().unwrap_or(0.0); + weights = (0..length).map(|texel| (total_at(texel + radius + 1) - total_at(texel.saturating_sub(radius))) / window).collect(); + } + weights.into_iter().map(|weight| weight as f32).collect() +} + +/// `data` averaged over `step × step` squares, clipping the last cells to the map +fn coarsen(data: &[f32], (width, height): (u32, u32), step: u32, block: (u32, u32)) -> CurvatureSizeLevel { + let (coarse_width, coarse_height) = (width.div_ceil(step), height.div_ceil(step)); + let deviation = (0..coarse_width * coarse_height) + .into_par_iter() + .map(|cell| { + let (cell_x, cell_y) = (cell % coarse_width, cell / coarse_width); + let columns = cell_x * step..((cell_x + 1) * step).min(width); + let rows = cell_y * step..((cell_y + 1) * step).min(height); + let count = (columns.len() * rows.len()).max(1) as f32; + let texels = rows.flat_map(|y| columns.clone().map(move |x| (y * width + x) as usize)); + let mean = texels.map(|index| data.get(index).copied().unwrap_or(0.0)).sum::() / count; + (mean * DEVIATION_SCALE).round().clamp(i16::MIN as f32, i16::MAX as f32) as i16 + }) + .collect(); + CurvatureSizeLevel { step, width: coarse_width, height: coarse_height, block: (block.0.div_ceil(step), block.1.div_ceil(step)), deviation } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn coarse_sizes_do_not_blend_between_uv_tiles() { + let (width, height) = (512, 512); + let block = (256, 256); + let curvature: Vec = (0..width * height).map(|texel| if (texel % width) / block.0 == (texel / width) / block.1 { 0.8 } else { 0.2 }).collect(); + let covered = vec![true; curvature.len()]; + let sizes = CurvatureSizes::build(&curvature, (width, height), &covered, block, &[true; CurvatureDetail::BLURRED_SIZES], None); + + for level in sizes.levels.iter().flatten() { + for (x, y) in [(255, 128), (256, 128), (128, 255), (128, 256), (255, 255), (256, 256)] { + let expected = curvature[(y * width + x) as usize] - 0.5; + assert!((level.sample(x, y) - expected).abs() < 0.001, "step {} at ({x}, {y}): {} instead of {expected}", level.step, level.sample(x, y)); + } + } + } + + #[test] + fn coverage_preserves_bake_texels_above_the_working_resolution() { + use texturecraft_core::{Project, TextureSet}; + use texturecraft_geom::{UvGBuffer, primitives}; + + let mesh = primitives::plane(2.0, 1); + let mut project = Project::new("Coverage", "builtin:plane"); + project.texture_sets.push(TextureSet::new("Plane", 0, 64)); + let gbuf = UvGBuffer::new(&mesh, 0, 64, 64); + let pixels = Default::default(); + let images = Default::default(); + let baked = Default::default(); + let inputs = Inputs { + project: &project, + ts: 0, + mesh: &mesh, + gbuf: &gbuf, + pixels: &pixels, + baked: &baked, + block_scales: BlockScales::default(), + preview: None, + images: &images, + bounds: mesh.bounds(), + }; + + for size in [(32, 32), (64, 64), (128, 128), (128, 32)] { + let coverage = covered_texels(&inputs, size); + assert!(coverage.iter().all(|covered| *covered), "the plane covers the entire {size:?} bake, including between working texel centers"); + } + } + + #[test] + fn coverage_expands_scaled_tiles_without_crossing_block_borders() { + use texturecraft_core::{Project, TextureSet}; + use texturecraft_geom::{NO_TRI, UvGBuffer, primitives}; + + let mesh = primitives::plane(2.0, 1); + let mut project = Project::new("Tile coverage", "builtin:plane"); + let mut set = TextureSet::new("Tiles", 0, 64); + set.uv_tiles = vec![1001, 1002, 1003]; + set.tile_resolutions.insert(1002, 32); + let scales = set.block_scales(); + project.texture_sets.push(set); + let mut gbuf = UvGBuffer::new(&mesh, 0, 192, 64); + for (index, triangle) in gbuf.tri.iter_mut().enumerate() { + if !(64..96).contains(&(index % 192)) || index / 192 >= 32 { + *triangle = NO_TRI; + } + } + let pixels = Default::default(); + let images = Default::default(); + let baked = Default::default(); + let inputs = Inputs { + project: &project, + ts: 0, + mesh: &mesh, + gbuf: &gbuf, + pixels: &pixels, + baked: &baked, + block_scales: scales, + preview: None, + images: &images, + bounds: mesh.bounds(), + }; + + let covered = covered_texels(&inputs, (384, 128)); + for (index, covered) in covered.iter().enumerate() { + assert_eq!(*covered, (128..256).contains(&(index % 384)), "bake texel ({}, {})", index % 384, index / 384); + } + } + + #[test] + fn unused_maps_are_evicted_even_while_undo_keeps_the_sources_alive() { + let sources: Vec<_> = (0..=CACHE_MAPS).map(|_| Arc::new(vec![0.5; 16])).collect(); + let scales = BlockScales::default(); + let key = ((4, 4), (4, 4), (4, 4)); + let sizes = store(&sources[0], key, &scales, CurvatureSizes { levels: Vec::new() }); + let first = Arc::downgrade(&sizes); + drop(sizes); + for source in sources.iter().skip(1) { + store(source, key, &scales, CurvatureSizes { levels: Vec::new() }); + } + + assert!(first.upgrade().is_none(), "undo history may retain the bake, but not an unlimited number of derived maps"); + } + + #[test] + fn cache_budget_evicts_old_levels_but_keeps_one_large_map() { + let source = Arc::new(vec![0.5]); + let key = ((1, 1), (1, 1), (1, 1)); + let entry = || { + let level = CurvatureSizeLevel { step: 1, width: 4, height: 1, block: (4, 1), deviation: vec![0; 4] }; + let sizes = CurvatureSizes { levels: vec![Some(Arc::new(level))] }; + (Arc::downgrade(&source), key, BlockScales::default(), Arc::new(sizes)) + }; + let mut cache = vec![entry(), entry(), entry()]; + let oldest = Arc::downgrade(&cache[0].3); + let newest = cache[2].3.clone(); + + trim_cache(&mut cache, 16); + assert_eq!(cache.len(), 2); + assert!(oldest.upgrade().is_none()); + trim_cache(&mut cache, 1); + assert_eq!(cache.len(), 1, "the active map must not rebuild once per composite tile"); + assert!(Arc::ptr_eq(&cache[0].3, &newest)); + } + + #[test] + fn padding_keeps_an_island_border_from_reading_flat() { + let map_size: u32 = 64; + let left_half = |texel: u32| texel % map_size < map_size / 2; + let curvature: Vec = (0..map_size * map_size).map(|texel| if left_half(texel) { 1.0 } else { 0.0 }).collect(); + let covered: Vec = (0..map_size * map_size).map(left_half).collect(); + let shape = (map_size, map_size); + let sizes = CurvatureSizes::build(&curvature, shape, &covered, shape, &[true; CurvatureDetail::BLURRED_SIZES], None); + + // The last covered column, halfway down + let (border_x, border_y) = (map_size / 2 - 1, map_size / 2); + for level in sizes.levels.iter().flatten() { + assert!((level.sample(border_x, border_y) - 0.5).abs() < 0.01, "the border keeps the island's curvature, not the empty texels beside it"); + } + } + + #[test] + fn uniform_curvature_keeps_its_strength_at_block_borders() { + let (map_width, map_height): (u32, u32) = (256, 256); + // Curvature 0.8 reads 0.3 above the neutral 0.5 at every size + const CURVATURE: f32 = 0.8; + let expected = CURVATURE - 0.5; + let curvature = vec![CURVATURE; (map_width * map_height) as usize]; + let covered = vec![true; curvature.len()]; + let block = (map_width / 2, map_height); + let sizes = CurvatureSizes::build(&curvature, (map_width, map_height), &covered, block, &[true; CurvatureDetail::BLURRED_SIZES], None); + + // The map's corner, then the last texel of the left block and the first of the right one, halfway down + let border_texels = [(0, 0), (block.0 - 1, map_height / 2), (block.0, map_height / 2)]; + for level in sizes.levels.iter().flatten() { + for (x, y) in border_texels { + assert!((level.sample(x, y) - expected).abs() < 0.01, "texel ({x}, {y}) reads {} instead of the uniform {expected}", level.sample(x, y)); + } + } + } + + #[test] + fn a_new_layout_replaces_the_sizes_of_the_old_one() { + let curvature = Arc::new(vec![0.5; 16]); + let scales = BlockScales::default(); + let entries_for_curvature = || { + let cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + cache.iter().filter(|(source, ..)| std::ptr::eq(source.as_ptr(), Arc::as_ptr(&curvature))).count() + }; + + store(&curvature, ((4, 4), (4, 4), (4, 4)), &scales, CurvatureSizes { levels: Vec::new() }); + store(&curvature, ((4, 4), (2, 2), (8, 8)), &scales, CurvatureSizes { levels: Vec::new() }); + assert_eq!(entries_for_curvature(), 1, "only the latest layout of a curvature map stays cached"); + } + + #[test] + fn sizes_built_on_demand_match_a_full_build() { + let map_size: u32 = 64; + let curvature: Vec = + (0..map_size * map_size).map(|texel| 0.5 + 0.4 * ((texel % map_size) as f32 * 0.3).sin() * ((texel / map_size) as f32 * 0.2).cos()).collect(); + let covered = vec![true; (map_size * map_size) as usize]; + let shape = (map_size, map_size); + let all = vec![true; CurvatureDetail::BLURRED_SIZES]; + let full = CurvatureSizes::build(&curvature, shape, &covered, shape, &all, None); + + let even: Vec = (0..all.len()).map(|level| level % 2 == 0).collect(); + let partial = CurvatureSizes::build(&curvature, shape, &covered, shape, &even, None); + assert!(partial.levels.iter().zip(&even).all(|(level, needed)| level.is_some() == *needed), "only the needed sizes are built"); + + let completed = CurvatureSizes::build(&curvature, shape, &covered, shape, &all, Some(&partial)); + for ((built, expected), earlier) in completed.levels.iter().zip(&full.levels).zip(&partial.levels) { + assert_eq!(built.as_ref().map(|level| &level.deviation), expected.as_ref().map(|level| &level.deviation), "the same values either way"); + if let (Some(built), Some(earlier)) = (built, earlier) { + assert!(Arc::ptr_eq(built, earlier), "sizes already built are kept, not rebuilt"); + } + } + } +} diff --git a/crates/compose/src/display.rs b/crates/compose/src/display.rs index ba4b675e..5ebb667b 100644 --- a/crates/compose/src/display.rs +++ b/crates/compose/src/display.rs @@ -93,20 +93,21 @@ fn u8_of(v: u16) -> u8 { (v >> 8) as u8 } -/// Tile bytes (`TILE × TILE`, row-major) for `kind` from the composite, or None when the tile is -/// absent in every source (the GPU texture keeps its cleared default). -pub fn tile_bytes(comp: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u32, ty: u32) -> Vec { - let bpt = kind.bytes_per_texel(); - let mut out = vec![0u8; TILE_AREA * bpt]; - let lut = srgb_lut(); - let get = |c: Channel| comp.channels.get(&c).and_then(|img| img.tile(tx, ty)); - let res = comp.resolution; +/// Tile bytes (`TILE × TILE`, row-major) for `kind`, using channel defaults for absent source tiles. +pub fn tile_bytes(composite: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u32, ty: u32) -> Vec { + let bytes_per_texel = kind.bytes_per_texel(); + let mut out = vec![0u8; TILE_AREA * bytes_per_texel]; + let srgb = srgb_lut(); + let get = |c: Channel| composite.channels.get(&c).and_then(|img| img.tile(tx, ty)); + let resolution = composite.resolution; let default16 = |c: Channel| texturecraft_texel::to_u16(c.default_value()[0]); - // A scalar channel's texel `i` as 8 bits (its default where the set lacks it). + + // A scalar channel's texel `i` as 8 bits (its default where the set lacks it) let scalar8 = |c: Channel| { let (t, d) = (get(c), default16(c)); move |i: usize| u8_of(t.and_then(|t| t.get(i).copied()).unwrap_or(d)) }; + match kind { DisplayKind::BaseColor | DisplayKind::Emissive | DisplayKind::Sheen => { let (c, alpha) = match kind { @@ -117,81 +118,87 @@ pub fn tile_bytes(comp: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u3 let (src, alpha) = (get(c), scalar8(alpha)); let d = c.default_value().map(|v| (texturecraft_texel::linear_to_srgb(v) * 255.0 + 0.5) as u8); for i in 0..TILE_AREA { - let px = &mut out[i * 4..i * 4 + 4]; + let pixel = &mut out[i * 4..i * 4 + 4]; match src { Some(s) => { for k in 0..3 { - px[k] = lut[(s.get(i * 3 + k).copied().unwrap_or(0) >> 4) as usize]; + pixel[k] = srgb[(s.get(i * 3 + k).copied().unwrap_or(0) >> 4) as usize]; } } - None => px[..3].copy_from_slice(&d), + None => pixel[..3].copy_from_slice(&d), } - px[3] = alpha(i); + pixel[3] = alpha(i); } } DisplayKind::Lobes => { let lanes = [Channel::CoatWeight, Channel::CoatRoughness, Channel::AnisotropyLevel, Channel::AnisotropyAngle].map(scalar8); - for (i, px) in out.chunks_exact_mut(4).enumerate() { - for (d, lane) in px.iter_mut().zip(&lanes) { + for (i, pixel) in out.as_chunks_mut::<4>().0.iter_mut().enumerate() { + for (d, lane) in pixel.iter_mut().zip(&lanes) { *d = lane(i); } } } DisplayKind::Extra => { let (n, transmission) = (get(Channel::CoatNormal), scalar8(Channel::Transmission)); - // Signed 8-bit around 128 so the flat normal packs exactly. - let snorm = |v: u16| (128.0 + 127.0 * (v as f32 / 65535.0 * 2.0 - 1.0)).round().clamp(0.0, 255.0) as u8; - // A TILE never straddles two atlas blocks. - let scale = (-32.0 * comp.block_scales.at(tx * TILE, ty * TILE).log2()).round().clamp(0.0, 255.0) as u8; - for (i, px) in out.chunks_exact_mut(4).enumerate() { - for (k, d) in px.iter_mut().take(2).enumerate() { - *d = n.and_then(|t| t.get(i * 3 + k)).map_or(128, |v| snorm(*v)); + + // Signed 8-bit around 128 so the flat normal packs exactly + let pack_signed_normal = |v: u16| (128.0 + 127.0 * (v as f32 / 65535.0 * 2.0 - 1.0)).round().clamp(0.0, 255.0) as u8; + + // A TILE never straddles two atlas blocks + let scale = (-32.0 * composite.block_scales.at(tx * TILE, ty * TILE).log2()).round().clamp(0.0, 255.0) as u8; + for (i, pixel) in out.as_chunks_mut::<4>().0.iter_mut().enumerate() { + for (k, d) in pixel.iter_mut().take(2).enumerate() { + *d = n.and_then(|t| t.get(i * 3 + k)).map_or(128, |v| pack_signed_normal(*v)); } - px[2] = transmission(i); - px[3] = scale; + pixel[2] = transmission(i); + pixel[3] = scale; } } DisplayKind::Orm => { let (ao, m, s) = (get(Channel::AmbientOcclusion), get(Channel::Metallic), get(Channel::SpecularLevel)); - // Specular/glossiness sets: the viewport shades roughness = 1 − glossiness. - let gloss = comp.channels.contains_key(&Channel::Glossiness); + + // Specular/glossiness sets: the viewport shades roughness = 1 − glossiness + let gloss = composite.channels.contains_key(&Channel::Glossiness); let (r, r_default) = if gloss { (get(Channel::Glossiness), default16(Channel::Glossiness)) } else { (get(Channel::Roughness), default16(Channel::Roughness)) }; for i in 0..TILE_AREA { let (x, y) = (tx * TILE + (i as u32 % TILE), ty * TILE + (i as u32 / TILE)); - let baked_ao = baked.sample_working(BakedMap::AmbientOcclusion, x, y, (res, comp.height), &comp.block_scales).map_or(1.0, |value| value[0]); + let baked_ao = baked + .sample_working(BakedMap::AmbientOcclusion, x, y, (resolution, composite.height), &composite.block_scales) + .map_or(1.0, |value| value[0]); let ch_ao = ao.and_then(|a| a.get(i)).map(|v| *v as f32 / 65535.0).unwrap_or(1.0); - let px = &mut out[i * 4..i * 4 + 4]; - px[0] = ((baked_ao * ch_ao).clamp(0.0, 1.0) * 255.0 + 0.5) as u8; + let pixel = &mut out[i * 4..i * 4 + 4]; + pixel[0] = ((baked_ao * ch_ao).clamp(0.0, 1.0) * 255.0 + 0.5) as u8; let v = r.and_then(|t| t.get(i).copied()).unwrap_or(r_default); - px[1] = u8_of(if gloss { 65535 - v } else { v }); - px[2] = u8_of(m.and_then(|t| t.get(i).copied()).unwrap_or(0)); - px[3] = u8_of(s.and_then(|t| t.get(i).copied()).unwrap_or(default16(Channel::SpecularLevel))); + pixel[1] = u8_of(if gloss { 65535 - v } else { v }); + pixel[2] = u8_of(m.and_then(|t| t.get(i).copied()).unwrap_or(0)); + pixel[3] = u8_of(s.and_then(|t| t.get(i).copied()).unwrap_or(default16(Channel::SpecularLevel))); } } DisplayKind::Normal => { - let (n, sheen_rough) = (get(Channel::Normal), scalar8(Channel::SheenRoughness)); + let (n, sheen_roughness) = (get(Channel::Normal), scalar8(Channel::SheenRoughness)); for i in 0..TILE_AREA { - let px = &mut out[i * 4..i * 4 + 4]; - // The baked normal is the base the painted normal details sit on (as in export). + let pixel = &mut out[i * 4..i * 4 + 4]; + + // The baked normal is the base the painted normal details sit on (as in export) let (x, y) = (tx * TILE + (i as u32 % TILE), ty * TILE + (i as u32 / TILE)); - let base = baked.sample_working(BakedMap::Normal, x, y, (res, comp.height), &comp.block_scales); + let base = baked.sample_working(BakedMap::Normal, x, y, (resolution, composite.height), &composite.block_scales); match (n, base) { (Some(t), None) => { - for (k, d) in px.iter_mut().take(3).enumerate() { + for (k, d) in pixel.iter_mut().take(3).enumerate() { *d = u8_of(t.get(i * 3 + k).copied().unwrap_or(0)); } } (detail, Some(base)) => { let detail = detail.map_or([0.5, 0.5, 1.0], |t| [0, 1, 2].map(|k| t.get(i * 3 + k).map_or(0.0, |v| *v as f32 / 65535.0))); let v = texturecraft_core::blend::rnm(base, detail); - for (d, v) in px.iter_mut().zip(v) { + for (d, v) in pixel.iter_mut().zip(v) { *d = (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; } } - (None, None) => px[..3].copy_from_slice(&[128, 128, 255]), + (None, None) => pixel[..3].copy_from_slice(&[128, 128, 255]), } - px[3] = sheen_rough(i); + pixel[3] = sheen_roughness(i); } } DisplayKind::Height => { @@ -206,6 +213,7 @@ pub fn tile_bytes(comp: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u3 } } } + out } diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index c2287a4b..d3ae712e 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -2,19 +2,24 @@ //! tile by tile in parallel. This is the reference implementation (the oracle) for the viewport //! and for export. +pub(crate) mod thumbnail; + use std::borrow::Cow; use std::collections::{BTreeMap, HashMap}; +use std::sync::Arc; use rayon::prelude::*; use texturecraft_core::{ - BakedMap, BlendMode, BlockScales, Channel, ChannelKind, CompareOp, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId, - LayerKind, Mask, MaskBackground, NormalFormat, Project, Projection, Source, TextureSet, TileGrid, blend1, blend3, lum, mix3, per_unit, + BakedMap, BlendMode, BlockScales, Channel, ChannelKind, CompareOp, CurvatureDetail, CurvatureMode, Effect, EffectKind, Fill, Filter, Generator, + GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Mask, MaskBackground, NormalFormat, Project, Projection, Source, TextureSet, TileGrid, blend1, + blend3, lum, mix3, per_unit, }; use texturecraft_geom::glam::{Vec2, Vec3}; use texturecraft_geom::{Mesh, NO_TRI, UvGBuffer}; use texturecraft_texel::{DilationMap, TILE, TILE_AREA, TileImage, from_u16, noise, to_u16, to_u16_signed}; use crate::below::{Band, BelowCache, Level}; +use crate::curvature_sizes::CurvatureSizes; use crate::pattern::{Coords, decal_uv, image_samples, procedural, world_noise}; use crate::store::{BakedMaps, ImageStore, PixelStore, decode}; @@ -204,6 +209,8 @@ struct EffectPlan<'a> { opacity: f32, data: Option>, preview: bool, + /// The curvature detail sizes a generator with detail reads. + curvature_sizes: Option>, } struct MaskPlan<'a> { @@ -304,6 +311,12 @@ fn direction(angle: f32) -> [f32; 2] { [cs, -sn] } +/// Gain on the curvature map's own deviation from flat (±0.5 reaches black and white). +const MAP_GAIN: f32 = 2.0; + +/// Gain per texel of a detail size: blurring spreads an edge over about twice its radius, so wider sizes need proportionally more to reach full strength. +const GAIN_PER_DETAIL_TEXEL: f32 = 2.0 * std::f32::consts::SQRT_2; + /// Samples along a directional or slope blur at most (beyond, samples spread out). const LINE_SAMPLES: i32 = 24; @@ -421,17 +434,20 @@ fn gather(op: Op, orig: &[f32], cover: &[f32], comps: usize, (x0, y0, w, h): (u3 /// the region it is computed in, so tiles composited in any grouping agree exactly. const FIX: f64 = (1u64 << 24) as f64; -/// Three running-sum box blurs (≈ Gaussian) of a `w × h` image along rows then along columns. -/// Rows (and columns, transposed) blur in parallel. -fn blur(data: &mut [f32], w: usize, h: usize, r: usize) { - let fix = |v: &f32| if v.is_finite() { (f64::from(v.clamp(-1e6, 1e6)) * FIX).round() as i64 } else { 0 }; - let mut v: Vec = data.par_iter().map(fix).collect(); - blur_rows(&mut v, w, r); - let mut t = transpose(&v, w, h); - blur_rows(&mut t, h, r); - data.par_iter_mut().zip(transpose(&t, h, w)).for_each(|(d, s)| *d = (s as f64 / FIX) as f32); +/// Three running-sum box blurs (≈ Gaussian) of a `width × height` image along its rows, then its columns, each in parallel. +pub(crate) fn blur(data: &mut [f32], width: usize, height: usize, radius: usize) { + let to_fixed = |value: &f32| if value.is_finite() { (f64::from(value.clamp(-1e6, 1e6)) * FIX).round() as i64 } else { 0 }; + let mut fixed: Vec = data.par_iter().map(to_fixed).collect(); + blur_rows(&mut fixed, width, radius); + + let mut columns = transpose(&fixed, width, height); + blur_rows(&mut columns, height, radius); + data.par_iter_mut().zip(transpose(&columns, height, width)).for_each(|(target, blurred)| *target = (blurred as f64 / FIX) as f32); } +/// The box blurs `blur` runs along each axis +pub(crate) const BLUR_BOX_PASSES: usize = 3; + /// Three box blurs of radius `r` along every row (`w` long) of `data`. fn blur_rows(data: &mut [i64], w: usize, r: usize) { if w == 0 { @@ -439,7 +455,7 @@ fn blur_rows(data: &mut [i64], w: usize, r: usize) { } data.par_chunks_mut(w).for_each(|row| { let mut tmp = vec![0i64; row.len()]; - for _ in 0..3 { + for _ in 0..BLUR_BOX_PASSES { box_line(row, &mut tmp, r); row.copy_from_slice(&tmp); } @@ -760,28 +776,53 @@ fn fields_of(inp: &Inputs, channels: &[Channel], list: &[LayerId], tiles: &[(u32 if tiles.is_empty() || inp.gbuf.width == 0 { return out; } - let res = inp.gbuf.width; + + let working_width = inp.gbuf.width; let mut order = Vec::new(); draw_order(inp.project, list, 0, &mut order); + prepare_curvature_sizes(inp, &order); + for id in order { let Some(layer) = inp.project.content_layer(id) else { continue }; - if let Some(m) = layer_mask(inp.project, id).filter(|m| m.enabled && neighbourhood(&m.effects, res).is_some()) - && let Some(f) = field(inp, channels, &out, id, Job::Mask(m), tiles) + + if let Some(mask) = layer_mask(inp.project, id).filter(|mask| mask.enabled && neighbourhood(&mask.effects, working_width).is_some()) + && let Some(filtered) = field(inp, channels, &out, id, Job::Mask(mask), tiles) { - out.insert(FieldKey::Mask(id), f); + out.insert(FieldKey::Mask(id), filtered); } - if layer.is_group() || neighbourhood(&layer.content_effects, res).is_none() { + + if layer.is_group() || neighbourhood(&layer.content_effects, working_width).is_none() { continue; } - for ch in channels.iter().filter(|c| layer.channels.contains_key(c)) { - if let Some(f) = field(inp, channels, &out, id, Job::Content(*ch), tiles) { - out.insert(FieldKey::Content(id, *ch), f); + for channel in channels.iter().filter(|channel| layer.channels.contains_key(channel)) { + if let Some(filtered) = field(inp, channels, &out, id, Job::Content(*channel), tiles) { + out.insert(FieldKey::Content(id, *channel), filtered); } } } out } +/// Build the curvature detail sizes every visible generator of `layers` reads, once, before tiles composite in parallel. +fn prepare_curvature_sizes(inp: &Inputs, layers: &[LayerId]) { + let visible = layers.iter().filter(|id| inp.project.layers.get(id).is_some_and(|layer| layer.visible)); + let masks = visible.filter_map(|id| layer_mask(inp.project, *id)).filter(|mask| mask.enabled); + prepare_mask_curvature_sizes(inp, masks); +} + +/// Build the curvature detail sizes the visible generators of `masks` read, once, before tiles composite in parallel. +fn prepare_mask_curvature_sizes<'a>(inp: &Inputs, masks: impl Iterator) { + let mut needed = [false; CurvatureDetail::BLURRED_SIZES]; + for effect in masks.flat_map(|mask| &mask.effects).filter(|effect| effect.visible) { + if let EffectKind::Generator(Generator { detail: Some(detail), .. }) = &effect.kind { + for (slot, in_use) in needed.iter_mut().zip(detail.blurred_sizes_in_use()) { + *slot |= in_use; + } + } + } + CurvatureSizes::of(inp, &needed); +} + struct Node<'a> { id: LayerId, content: Content<'a>, @@ -799,21 +840,26 @@ struct Node<'a> { /// Plans of the visible effects of a stack: mask effects (`channel` None) or the content /// effects of one channel (paint effects then read that channel's pixels). -fn effect_plans<'a>(inp: &Inputs<'a>, effects: &'a [Effect], tx: u32, ty: u32, channel: Option) -> Vec> { +fn effect_plans<'a>(inp: &Inputs<'a>, effects: &'a [Effect], tile_x: u32, tile_y: u32, channel: Option) -> Vec> { effects .iter() - .filter(|e| e.visible) - .map(|e| { - let (img, target) = match channel { - Some(c) => (inp.pixels.layer(e.id, c), PaintTarget::Layer(e.id)), - None => (inp.pixels.masks.get(&e.id), PaintTarget::Mask(e.id)), + .filter(|effect| effect.visible) + .map(|effect| { + let (image, target) = match channel { + Some(channel) => (inp.pixels.layer(effect.id, channel), PaintTarget::Layer(effect.id)), + None => (inp.pixels.masks.get(&effect.id), PaintTarget::Mask(effect.id)), + }; + let curvature_sizes = match &effect.kind { + EffectKind::Generator(Generator { detail: Some(detail), .. }) => CurvatureSizes::of(inp, &detail.blurred_sizes_in_use()), + _ => None, }; EffectPlan { - kind: &e.kind, - blend: e.blend, - opacity: e.opacity, - data: if e.kind.painted() { tile_of(inp, img, tx, ty, channel) } else { None }, + kind: &effect.kind, + blend: effect.blend, + opacity: effect.opacity, + data: if effect.kind.painted() { tile_of(inp, image, tile_x, tile_y, channel) } else { None }, preview: previews(inp, target), + curvature_sizes, } }) .collect() @@ -1129,131 +1175,183 @@ impl<'a, 'b> Texel<'a, 'b> { w * image.map_or(1.0, |img| img.sample(c.uv.x, c.uv.y)[3].clamp(0.0, 1.0)) } - fn source(&mut self, s: &Source, proj: &Projection, kind: ChannelKind) -> [f32; 3] { - match s { - Source::Uniform(v) => *v, + /// The value `source` gives this texel through `projection`, read as a channel of `kind` + fn source(&mut self, source: &Source, projection: &Projection, kind: ChannelKind) -> [f32; 3] { + match source { + Source::Uniform(value) => *value, Source::Procedural { pattern, low, high } => { - let (c, proj, _) = self.projected(proj); - let t = procedural(pattern, proj, &c); - mix3(*low, *high, t) + let (coords, projection, _) = self.projected(projection); + let amount = procedural(pattern, projection, &coords); + mix3(*low, *high, amount) } Source::Image { name, normal_format } => { - let Some(img) = self.inp.images.get(name) else { return [0.5; 3] }; - let (c, proj, _) = self.projected(proj); - let mut acc = [0.0f32; 4]; - for (uv, w) in image_samples(proj, &c).into_iter().filter(|(_, w)| *w > 0.0) { - let s = img.sample(uv.x, uv.y); - for k in 0..4 { - acc[k] += s[k] * w; + let Some(image) = self.inp.images.get(name) else { return [0.5; 3] }; + + let (coords, projection, _) = self.projected(projection); + let mut sum = [0.0f32; 4]; + for (uv, weight) in image_samples(projection, &coords).into_iter().filter(|(_, weight)| *weight > 0.0) { + for (total, value) in sum.iter_mut().zip(image.sample(uv.x, uv.y)) { + *total += value * weight; } } + + let rgb = [sum[0], sum[1], sum[2]]; match kind { - ChannelKind::Color if img.srgb => [acc[0], acc[1], acc[2]].map(texturecraft_texel::srgb_to_linear), - // Normal channels are OpenGL (+Y up the image): a DirectX image's green flips. - ChannelKind::NormalMap if *normal_format == NormalFormat::DirectX => [acc[0], 1.0 - acc[1], acc[2]], - ChannelKind::Color | ChannelKind::NormalMap => [acc[0], acc[1], acc[2]], - ChannelKind::Scalar => [acc[0]; 3], - ChannelKind::Signed => [acc[0] * 2.0 - 1.0; 3], + ChannelKind::Color if image.srgb => rgb.map(texturecraft_texel::srgb_to_linear), + // Normal channels are OpenGL (+Y up the image): a DirectX image's green flips + ChannelKind::NormalMap if *normal_format == NormalFormat::DirectX => [rgb[0], 1.0 - rgb[1], rgb[2]], + ChannelKind::Color | ChannelKind::NormalMap => rgb, + // A one-value channel or mask reads the image's gray, so a color image works as a mask + ChannelKind::Scalar => [lum(rgb); 3], + ChannelKind::Signed => [lum(rgb) * 2.0 - 1.0; 3], } } Source::Anchor { anchor, channel } => { - // An anchor not evaluated yet (above this layer, hidden) reads the channel default. - let v = self.anchors.iter().rev().find(|(id, _)| id == anchor).and_then(|(_, acc)| acc.get(channel.index()).copied()); - let v = v.unwrap_or_else(|| channel.default_value()); + // An anchor not evaluated yet (above this layer, hidden) reads the channel default + let anchored = self.anchors.iter().rev().find(|(id, _)| id == anchor).and_then(|(_, values)| values.get(channel.index()).copied()); + let value = anchored.unwrap_or_else(|| channel.default_value()); let gray = matches!(channel.kind(), ChannelKind::Color | ChannelKind::NormalMap) && matches!(kind, ChannelKind::Scalar | ChannelKind::Signed); - if gray { [lum(v); 3] } else { v } + if gray { [lum(value); 3] } else { value } } } } - fn generator(&mut self, g: &Generator) -> f32 { - let c = self.coords(); - let s = match g.kind { - GeneratorKind::EdgeWear => (self.baked(BakedMap::Curvature).unwrap_or(0.5) - 0.5) * 2.0, - GeneratorKind::Curvature => self.baked(BakedMap::Curvature).unwrap_or(0.5), - GeneratorKind::Dirt => 1.0 - self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0), - GeneratorKind::AmbientOcclusion => self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0), - GeneratorKind::ThinAreas => 1.0 - self.baked(BakedMap::Thickness).unwrap_or(1.0), - GeneratorKind::Position => c.pos.dot(Vec3::from(g.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, - GeneratorKind::Direction => c.nrm.dot(Vec3::from(g.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, + fn generator(&mut self, generator: &Generator, curvature_sizes: Option<&CurvatureSizes>) -> f32 { + let coords = self.coords(); + let signal = match (generator.kind, &generator.detail) { + (GeneratorKind::Curvature | GeneratorKind::EdgeWear, Some(detail)) => self.curvature_detail(detail, curvature_sizes), + (GeneratorKind::EdgeWear, None) => (self.baked(BakedMap::Curvature).unwrap_or(0.5) - 0.5) * 2.0, + (GeneratorKind::Curvature, None) => self.baked(BakedMap::Curvature).unwrap_or(0.5), + (GeneratorKind::Dirt, _) => 1.0 - self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0), + (GeneratorKind::AmbientOcclusion, _) => self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0), + (GeneratorKind::ThinAreas, _) => 1.0 - self.baked(BakedMap::Thickness).unwrap_or(1.0), + (GeneratorKind::Position, _) => coords.pos.dot(Vec3::from(generator.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, + (GeneratorKind::Direction, _) => coords.nrm.dot(Vec3::from(generator.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, }; - let s = if g.noise_amount > 0.0 { s + (world_noise(c.pos, g.noise_scale, g.seed) - 0.5) * g.noise_amount } else { s }; - let th = 1.0 - g.level.clamp(0.0, 1.0); - let soft = g.softness.max(1e-3); - let t = ((s - (th - soft)) / (2.0 * soft)).clamp(0.0, 1.0); - let v = t * t * (3.0 - 2.0 * t); - if g.invert { 1.0 - v } else { v } + let signal = if generator.noise_amount > 0.0 { + let noise = world_noise(coords.pos, generator.noise_scale, generator.seed); + if let (GeneratorKind::Curvature | GeneratorKind::EdgeWear, Some(detail)) = (generator.kind, &generator.detail) { + // Break up curvature without inventing edges or cavities on a flat surface + let neutral = if detail.mode == CurvatureMode::Raw { 0.5 } else { 0.0 }; + neutral + (signal - neutral) * (1.0 - noise * generator.noise_amount).max(0.0) + } else { + signal + (noise - 0.5) * generator.noise_amount + } + } else { + signal + }; + + // A smooth step from black to white over 2 × softness around 1 − level + let threshold = 1.0 - generator.level.clamp(0.0, 1.0); + let softness = generator.softness.max(1e-3); + let ramp = ((signal - (threshold - softness)) / (2.0 * softness)).clamp(0.0, 1.0); + let value = ramp * ramp * (3.0 - 2.0 * ramp); + if generator.invert { 1.0 - value } else { value } } - fn mask(&mut self, m: &MaskPlan) -> f32 { - let mut v = m.background; - let mut skip = 0; - if let Some((k, field)) = m.start - && let Some(f) = field.get(self.x, self.y).and_then(|d| d.first().copied()) - { - v = f; - skip = k + 1; + /// The curvature of `detail`'s mode at this texel: each detail size's edges and cavities, weighted and combined like a screen blend. + fn curvature_detail(&self, detail: &CurvatureDetail, curvature_sizes: Option<&CurvatureSizes>) -> f32 { + let combine = |edges: f32, cavities: f32| match detail.mode { + CurvatureMode::Edges => edges, + CurvatureMode::Cavities => cavities, + CurvatureMode::Both => 1.0 - (1.0 - edges) * (1.0 - cavities), + CurvatureMode::Raw => 0.5 + 0.5 * (edges - cavities), + }; + + // Without curvature to read the texel is flat: no edges or cavities + let Some(curvature) = self.baked(BakedMap::Curvature) else { return combine(0.0, 0.0) }; + + let working_size = (self.res, self.inp.gbuf.height); + let texel_uv = [(self.x as f32 + 0.5) / working_size.0.max(1) as f32, (self.y as f32 + 0.5) / working_size.1.max(1) as f32]; + let Some(baked_uv) = self.inp.block_scales.bake_uv(texel_uv, working_size) else { return combine(0.0, 0.0) }; + + let baked_size = (self.inp.baked.resolution, self.inp.baked.height(BakedMap::Curvature)); + let (baked_x, baked_y) = ((baked_uv[0] * baked_size.0 as f32) as u32, (baked_uv[1] * baked_size.1 as f32) as u32); + let blurred = |index: usize| { + curvature_sizes.and_then(|sizes| sizes.levels.get(index)).and_then(Option::as_deref).map_or(0.0, |level| level.sample(baked_x, baked_y)) + }; + let (mut edges, mut cavities) = (0.0f32, 0.0f32); + for (index, (size, weight)) in CurvatureDetail::SIZES.iter().zip(detail.weights).enumerate() { + let deviation = if index == 0 { curvature - 0.5 } else { blurred(index - 1) }; + + let response = deviation * if *size == 0.0 { MAP_GAIN } else { GAIN_PER_DETAIL_TEXEL * size }; + let weight = weight.clamp(0.0, 1.0); + edges = 1.0 - (1.0 - edges) * (1.0 - weight * response.clamp(0.0, 1.0)); + cavities = 1.0 - (1.0 - cavities) * (1.0 - weight * (-response).clamp(0.0, 1.0)); } - for e in m.effects.iter().skip(skip) { - let o = e.opacity.clamp(0.0, 1.0); - match e.kind { + + combine(edges, cavities) + } + + fn mask(&mut self, plan: &MaskPlan) -> f32 { + let mut value = plan.background; + let mut skip = 0; + if let Some((filtered_index, field)) = plan.start + && let Some(filtered) = field.get(self.x, self.y).and_then(|texel| texel.first().copied()) + { + value = filtered; + skip = filtered_index + 1; + } + + for effect in plan.effects.iter().skip(skip) { + let opacity = effect.opacity.clamp(0.0, 1.0); + match effect.kind { EffectKind::Paint | EffectKind::Path(_) => { - let (mut pv, mut cov) = match e.data.as_deref() { - Some(d) => (from_u16(d.get(self.o * 2).copied().unwrap_or(0)), from_u16(d.get(self.o * 2 + 1).copied().unwrap_or(0))), + let (mut painted, mut cov) = match effect.data.as_deref() { + Some(data) => (from_u16(data.get(self.o * 2).copied().unwrap_or(0)), from_u16(data.get(self.o * 2 + 1).copied().unwrap_or(0))), None => (0.0, 0.0), }; - if e.preview - && let Some(p) = self.inp.preview + if effect.preview + && let Some(preview) = self.inp.preview { - let a = (self.stroke * p.opacity).clamp(0.0, 1.0); - if p.erase { - pv *= 1.0 - a; - cov *= 1.0 - a; + let stroke = (self.stroke * preview.opacity).clamp(0.0, 1.0); + if preview.erase { + painted *= 1.0 - stroke; + cov *= 1.0 - stroke; } else { - pv = p.mask_value * a + pv * (1.0 - a); - cov = a + cov * (1.0 - a); + painted = preview.mask_value * stroke + painted * (1.0 - stroke); + cov = stroke + cov * (1.0 - stroke); } } if cov > 0.0 { - let val = pv / cov.max(1e-5); - v += (blend1(e.blend, v, val) - v) * cov * o; + let layer_value = painted / cov.max(1e-5); + value += (blend1(effect.blend, value, layer_value) - value) * cov * opacity; } } EffectKind::Fill { source, projection } => { - let val = self.source(source, projection, ChannelKind::Scalar)[0]; - v += (blend1(e.blend, v, val) - v) * o * self.cover(std::iter::once(source), projection); + let fill = self.source(source, projection, ChannelKind::Scalar)[0]; + value += (blend1(effect.blend, value, fill) - value) * opacity * self.cover(std::iter::once(source), projection); } - EffectKind::Generator(g) => { - let val = self.generator(g); - v += (blend1(e.blend, v, val) - v) * o; + EffectKind::Generator(generator) => { + let generated = self.generator(generator, effect.curvature_sizes.as_deref()); + value += (blend1(effect.blend, value, generated) - value) * opacity; } - EffectKind::Levels(l) => v += (l.apply(v) - v) * o, - EffectKind::Filter(f) => { - // A mask is gray (HSL only changes its lightness); neighbourhood filters come - // precomputed through `MaskPlan::start`. - let val = f.point(ChannelKind::Scalar, [v; 3]).map_or(v, |x| x[0]); - v += (val - v) * o; + EffectKind::Levels(levels) => value += (levels.apply(value) - value) * opacity, + EffectKind::Filter(filter) => { + // A mask is gray (HSL only changes its lightness); neighbourhood filters come precomputed through `MaskPlan::start` + let filtered = filter.point(ChannelKind::Scalar, [value; 3]).map_or(value, |gray| gray[0]); + value += (filtered - value) * opacity; } EffectKind::ColorSelection { colors, tolerance } => { let id = self.baked_color(BakedMap::Id); - let hit = id.is_some_and(|c| colors.iter().any(|k| (k[0] - c[0]).abs().max((k[1] - c[1]).abs()).max((k[2] - c[2]).abs()) <= *tolerance)); - let val = if hit { 1.0 } else { 0.0 }; - v += (blend1(e.blend, v, val) - v) * o; + let within = |picked: &[f32; 3], color: [f32; 3]| (0..3).all(|component| (picked[component] - color[component]).abs() <= *tolerance); + let selected = if id.is_some_and(|color| colors.iter().any(|picked| within(picked, color))) { 1.0 } else { 0.0 }; + value += (blend1(effect.blend, value, selected) - value) * opacity; } - EffectKind::Compare { op, value, tolerance } => { + EffectKind::Compare { op, value: compared, tolerance } => { let pass = match op { - CompareOp::LesserThan => v < *value, - CompareOp::GreaterThan => v > *value, - CompareOp::WithinTolerance => (v - value).abs() <= *tolerance, + CompareOp::LesserThan => value < *compared, + CompareOp::GreaterThan => value > *compared, + CompareOp::WithinTolerance => (value - compared).abs() <= *tolerance, }; - let val = if pass { 1.0 } else { 0.0 }; - v += (val - v) * o; + let result = if pass { 1.0 } else { 0.0 }; + value += (result - value) * opacity; } - // Content-only effects. + // Content-only effects EffectKind::Material(_) | EffectKind::Anchor => {} } } - v.clamp(0.0, 1.0) + value.clamp(0.0, 1.0) } /// Composite `nodes` over `acc`, recording anchors. Returns true when it reached the `stop` @@ -1898,6 +1996,10 @@ pub fn mask_image(inputs: &Inputs, id: LayerId, size: u32) -> Option> { let channels = inputs.project.texture_set(inputs.ts).map(|set| set.channel_list()).unwrap_or_default(); let (width, height) = (inputs.gbuf.width, inputs.gbuf.height); let coordinates = all_tiles(width, height); + + // A hidden layer's mask is left out of the stack's preparation + prepare_mask_curvature_sizes(inputs, std::iter::once(mask)); + let fields = neighbourhood_fields(inputs, &channels, &coordinates); let tiles: HashMap<(u32, u32), Vec> = coordinates .par_iter() @@ -1951,6 +2053,10 @@ pub fn mask_at(inputs: &Inputs, id: LayerId, texels: &[(u32, u32)]) -> Option