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/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/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..f957ce49 --- /dev/null +++ b/crates/bake/src/cage/high_poly_reach.rs @@ -0,0 +1,103 @@ +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.chunks_exact(3).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.chunks_exact(3) { + 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..e6d66d07 --- /dev/null +++ b/crates/bake/src/test/high_poly_reach.rs @@ -0,0 +1,222 @@ +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.chunks_exact_mut(3) { + 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/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..abfccaac 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( { diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index 36b5f856..3fe26e04 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -395,6 +395,11 @@ pub struct Project { /// it, so parts the file leaves unnamed get the same name (from it) as on import. #[serde(default, skip_serializing_if = "String::is_empty")] pub mesh_file: String, + /// Where the mesh file was imported from (the project's "3D mesh path"). Reimport mesh reads + /// it again from there, so edits made to the file since are picked up. Empty when unknown + /// (built-in meshes, web imports, projects saved before it was kept). + #[serde(default, skip_serializing_if = "String::is_empty")] + pub mesh_path: String, pub normal_format: NormalFormat, pub texture_sets: Vec, pub layers: BTreeMap, @@ -412,6 +417,7 @@ impl Project { name: name.into(), mesh: mesh.into(), mesh_file: String::new(), + mesh_path: String::new(), normal_format: NormalFormat::OpenGl, texture_sets: Vec::new(), layers: BTreeMap::new(), diff --git a/crates/engine/src/bake/bake_cage_inputs.rs b/crates/engine/src/bake/bake_cage_inputs.rs new file mode 100644 index 00000000..ab559beb --- /dev/null +++ b/crates/engine/src/bake/bake_cage_inputs.rs @@ -0,0 +1,45 @@ +use super::MergedHigh; +use std::sync::Arc; +use texturecraft_bake::{BakeError, BakePaintMap, BakeRequest, CageShell, HighPoly, HighPolyReach}; +use texturecraft_core::BakeSettings; +use texturecraft_geom::{Bvh, Mesh}; + +/// What a texture set's bake reads to place its transfer rays, owned so a worker thread can use it +#[derive(Clone, Debug)] +pub struct BakeCageInputs { + pub(super) mesh: Arc, + pub(super) bvh: Arc, + pub(super) material: usize, + pub(super) settings: BakeSettings, + pub(super) high: MergedHigh, + pub(super) cage: Option>, + pub(super) skew: Option>, + pub(super) cage_paint: Option>, +} + +impl BakeCageInputs { + /// The cage the 3D view draws: the bake's ray origins at each triangle corner + pub fn cage_shell(&self) -> Result { + CageShell::new(&self.request()) + } + + /// Where each high-poly vertex sits relative to the bake's transfer rays + pub fn high_poly_reach(&self) -> Result { + HighPolyReach::new(&self.request()) + } + + fn request(&self) -> BakeRequest<'_> { + BakeRequest { + low_base_color: &[], + mesh: &self.mesh, + bvh: &self.bvh, + material: self.material, + settings: &self.settings, + high: Some(HighPoly { file_ids: &self.high.file_ids, mesh: &self.high.mesh, bvh: &self.high.bvh, base_color: &self.high.base_color }), + cage: self.cage.as_deref(), + skew: self.skew.as_deref(), + cage_paint: self.cage_paint.as_deref(), + tiles: (1, 1), + } + } +} diff --git a/crates/engine/src/bake/bake_meshes.rs b/crates/engine/src/bake/bake_meshes.rs index 260002db..da0e4a97 100644 --- a/crates/engine/src/bake/bake_meshes.rs +++ b/crates/engine/src/bake/bake_meshes.rs @@ -14,6 +14,11 @@ pub struct BakeMeshes { } impl BakeMeshes { + /// Every high poly appended into one mesh, as bakes see it + pub fn merged_high(&self) -> Option<&MergedHigh> { + self.merged.as_ref() + } + pub(crate) fn rebuild(&mut self) { self.merged = (!self.high.is_empty()).then(|| { let (mut mesh, mut base_color, mut file_ids) = (Mesh::default(), Vec::new(), Vec::new()); diff --git a/crates/engine/src/bake/high_poly_missed.rs b/crates/engine/src/bake/high_poly_missed.rs new file mode 100644 index 00000000..21de6c05 --- /dev/null +++ b/crates/engine/src/bake/high_poly_missed.rs @@ -0,0 +1,23 @@ +use rayon::prelude::*; +use texturecraft_bake::HighPolyReach; + +/// Per high-poly vertex: 1.0 if its owning set's bake misses it, otherwise 0.0 +/// Distances are each set's (max frontal, max rear); filtered or unavailable sets leave their vertices unmarked +/// `vertex_count` is the validated high-poly mesh's vertex count +pub fn high_poly_missed(reach: &[Option], distances: &[(f32, f32)], only_set: Option, vertex_count: usize) -> Vec { + // Ownership is already assigned by HighPolyReach; other sets must not color the vertex + let sets: Vec<(&HighPolyReach, f32, f32)> = reach + .iter() + .zip(distances) + .enumerate() + .filter(|(texture_set, _)| only_set.is_none_or(|only| only == *texture_set)) + .filter_map(|(_, (reach, &(max_frontal, max_rear)))| Some((reach.as_ref()?, max_frontal, max_rear))) + .collect(); + (0..vertex_count) + .into_par_iter() + .map(|vertex| { + let missed = sets.iter().find_map(|(reach, max_frontal, max_rear)| reach.missed(vertex, *max_frontal, *max_rear)); + f32::from(u8::from(missed.unwrap_or(false))) + }) + .collect() +} diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs index e5982f18..b65d6ac8 100644 --- a/crates/engine/src/bake/mesh_map_command.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -8,6 +8,7 @@ use std::collections::BTreeMap; use std::sync::{Arc, OnceLock}; use texturecraft_core::BakePaintTarget; +use super::{BakeCageInputs, MergedHigh}; use crate::{BakeMesh, BakeTask}; use serde_json::{Value, json}; use texturecraft_bake::tracing::Tracer; @@ -15,6 +16,7 @@ use texturecraft_bake::{BakeOutput, BakePaintMap, MAX_RAYS, Progress}; use texturecraft_core::{ BackfaceMode, BakeAntialiasing, BakeResolution, BakeSettings, BakedMap, CurvatureMethod, PositionMode, RayDistribution, RaySettings, SelfOcclusion, }; +use texturecraft_geom::Mesh; use crate::commands::{CommandSpec, always, bad, boolp, f32p, strp, u64p}; use crate::{EngineError, Result, Session, cmd}; @@ -90,8 +92,8 @@ fn parse_mesh(file_name: &str, bytes: Vec) -> Result { } impl Session { - pub fn bake_task(&self, ts: usize) -> Result { - let set = self.doc.project.texture_set(ts)?; + pub fn bake_task(&self, texture_set: usize) -> Result { + let set = self.doc.project.texture_set(texture_set)?; if !set.has_enabled_bake_tiles() { return Err(EngineError::Other(format!("texture set {} has no UV tiles selected for baking", set.name))); } @@ -112,31 +114,22 @@ impl Session { } else { Arc::new(Vec::new()) }; - let high = if set.bake.high_poly.use_low_as_high { None } else { self.bake_meshes.merged.clone() }; - let cage = if high.is_some() && set.bake.cage.kind == texturecraft_core::CageType::CustomFile { - Some(self.bake_meshes.cage.as_ref().ok_or_else(|| EngineError::Other("Custom File requires a cage mesh".into()))?.mesh.clone()) - } else { - None - }; - let painted = |target| high.as_ref().and(self.doc.bake_paint.get(&(ts, target))).map(|map| super::layout::paint_for_bake(map, set)).transpose(); - let skew = painted(BakePaintTarget::Skew)?; - let cage_paint = painted(BakePaintTarget::Cage)?; + + let high = self.bake_high(texture_set)?; + let cage = self.bake_cage(texture_set, high.is_some())?; + let skew = self.bake_paint(texture_set, high.is_some(), BakePaintTarget::Skew)?; + let cage_paint = self.bake_paint(texture_set, high.is_some(), BakePaintTarget::Cage)?; + let grid = set.tile_grid(); let tiles = grid.map_or((1, 1), |grid| (grid.cols, grid.rows)); let excluded_tiles: Vec<_> = set.uv_tiles.iter().filter(|tile| set.bake_excluded_tiles.contains(tile)).filter_map(|tile| grid?.block(*tile)).collect(); - let previous_maps = if excluded_tiles.is_empty() { Default::default() } else { self.doc.baked.get(&ts).cloned().unwrap_or_default() }; + let previous_maps = if excluded_tiles.is_empty() { Default::default() } else { self.doc.baked.get(&texture_set).cloned().unwrap_or_default() }; + let tracer = GPU_TRACER.get().cloned(); Ok(BakeTask { low_base_color, - ts, - mesh: match grid.filter(|_| !set.tile_resolutions.is_empty()) { - Some(grid) => { - let mut mesh = (*self.source).clone(); - mesh.map_material_uvs(set.material, |uv| texturecraft_geom::glam::Vec2::from_array(grid.to_atlas(uv.to_array()))); - Arc::new(mesh) - } - None => self.mesh.clone(), - }, + ts: texture_set, + mesh: self.bake_mesh(texture_set)?, bvh: self.bvh.clone(), material: set.material, settings: set.bake.clone(), @@ -151,6 +144,61 @@ impl Session { }) } + /// What texture set `texture_set`'s bake reads to place its transfer rays; `None` when the set bakes without a high poly or misses its cage file + pub fn bake_cage_inputs(&self, texture_set: usize) -> Result> { + let set = self.doc.project.texture_set(texture_set)?; + let Some(high) = self.bake_high(texture_set)? else { return Ok(None) }; + let Ok(cage) = self.bake_cage(texture_set, true) else { return Ok(None) }; + + Ok(Some(BakeCageInputs { + mesh: self.bake_mesh(texture_set)?, + bvh: self.bvh.clone(), + material: set.material, + settings: set.bake.clone(), + high, + cage, + skew: self.bake_paint(texture_set, true, BakePaintTarget::Skew)?, + cage_paint: self.bake_paint(texture_set, true, BakePaintTarget::Cage)?, + })) + } + + /// The merged high polys texture set `texture_set` bakes from, unless it bakes from the low poly + fn bake_high(&self, texture_set: usize) -> Result> { + let set = self.doc.project.texture_set(texture_set)?; + Ok(if set.bake.high_poly.use_low_as_high { None } else { self.bake_meshes.merged.clone() }) + } + + /// Texture set `texture_set`'s cage mesh when it bakes from a high poly with a Custom File cage + fn bake_cage(&self, texture_set: usize, has_high: bool) -> Result>> { + let set = self.doc.project.texture_set(texture_set)?; + if !has_high || set.bake.cage.kind != texturecraft_core::CageType::CustomFile { + return Ok(None); + } + + let cage = self.bake_meshes.cage.as_ref().ok_or_else(|| EngineError::Other("Custom File requires a cage mesh".into()))?; + Ok(Some(cage.mesh.clone())) + } + + /// Texture set `texture_set`'s painted skew or cage map, used only when it bakes from a high poly + fn bake_paint(&self, texture_set: usize, has_high: bool, target: BakePaintTarget) -> Result>> { + let set = self.doc.project.texture_set(texture_set)?; + let paint = self.doc.bake_paint.get(&(texture_set, target)).filter(|_| has_high); + paint.map(|map| super::layout::paint_for_bake(map, set)).transpose() + } + + /// The low poly texture set `texture_set` bakes: UV tiles of mixed resolutions move into its atlas + fn bake_mesh(&self, texture_set: usize) -> Result> { + let set = self.doc.project.texture_set(texture_set)?; + Ok(match set.tile_grid().filter(|_| !set.tile_resolutions.is_empty()) { + Some(grid) => { + let mut mesh = (*self.source).clone(); + mesh.map_material_uvs(set.material, |uv| texturecraft_geom::glam::Vec2::from_array(grid.to_atlas(uv.to_array()))); + Arc::new(mesh) + } + None => self.mesh.clone(), + }) + } + /// Store a finished bake as one undo step pub fn apply_bake(&mut self, texture_set: usize, output: BakeOutput) -> Result<()> { let tracer = output.tracer.clone(); diff --git a/crates/engine/src/bake/mod.rs b/crates/engine/src/bake/mod.rs index 213e1ff6..fa3403df 100644 --- a/crates/engine/src/bake/mod.rs +++ b/crates/engine/src/bake/mod.rs @@ -1,8 +1,10 @@ //! Baking tasks, commands, settings helpers, and the mesh-map baking API +mod bake_cage_inputs; mod bake_mesh; mod bake_meshes; mod bake_task; +mod high_poly_missed; mod layout; mod merged_high; mod mesh_map_command; @@ -11,9 +13,11 @@ mod paint_command; mod preserve_tiles; mod tile_command; +pub use bake_cage_inputs::BakeCageInputs; pub use bake_mesh::BakeMesh; pub use bake_meshes::BakeMeshes; pub use bake_task::BakeTask; +pub use high_poly_missed::high_poly_missed; pub use merged_high::MergedHigh; pub use mesh_map_command::{install_gpu_tracer, meshes_json, settings_params}; pub use model_patch::settings_patch; diff --git a/crates/engine/src/color_selection_cmds.rs b/crates/engine/src/color_selection_cmds.rs new file mode 100644 index 00000000..2b9f9eaf --- /dev/null +++ b/crates/engine/src/color_selection_cmds.rs @@ -0,0 +1,160 @@ +//! Color selection effects: the ID colors they select, picked from the ID mesh map + +use serde_json::{Value, json}; +use texturecraft_core::{BakedMap, EffectKind, LayerId}; +use texturecraft_geom::glam::Vec2; +use texturecraft_geom::surface_at; + +use crate::commands::{CommandSpec, bad, f32p, has_layer}; +use crate::mask_cmds::effect_id; +use crate::tool_cmds::viewport_of; +use crate::{Result, Session, cmd}; + +/// Most colors one color selection holds; an ID map rarely has more distinct parts +const MAX_SELECTED_COLORS: usize = 256; + +pub fn specs() -> Vec { + vec![cmd!( + "effect.colorSelection.pick", + "Pick ID color", + [], + None, + "{effect?: a color selection (default: the selected effect), x?, y?: viewport pixels, viewport?: [w,h] | uv?: [u,v] texture set atlas UV (the 2D view), index?: replace this color instead of adding one} → {color: [r,g,b] as the ID map stores it, index} — samples the ID mesh map under the point", + has_layer, + pick + )] +} + +/// Applies `effect.set`'s `colors` and `tolerance` params to a color selection +pub(crate) fn apply_params(params: &Value, colors: &mut Vec<[f32; 3]>, tolerance: &mut f32) -> Result<()> { + if let Some(list) = params.get("colors") { + *colors = colors_param(list)?; + } + if let Some(value) = f32p(params, "tolerance") { + *tolerance = value.clamp(0.0, 1.0); + } + Ok(()) +} + +/// A non-empty `[[r, g, b], ...]` list of finite values, clamped to 0..1 +fn colors_param(list: &Value) -> Result> { + const CMD: &str = "effect.set"; + let items = list.as_array().ok_or_else(|| bad(CMD, "`colors` must be a list of [r, g, b]"))?; + if items.is_empty() || items.len() > MAX_SELECTED_COLORS { + return Err(bad(CMD, format!("`colors` needs 1 to {MAX_SELECTED_COLORS} colors"))); + } + + items + .iter() + .map(|item| match finite_numbers::<3>(item) { + Some(color) => Ok(color.map(|value| value.clamp(0.0, 1.0) as f32)), + _ => Err(bad(CMD, "each color must be [r, g, b] with finite numbers")), + }) + .collect() +} + +/// Samples the ID map under a viewport point or at a UV and adds the color to a color selection +fn pick(session: &mut Session, params: &Value) -> Result { + const CMD: &str = "effect.colorSelection.pick"; + let effect = effect_id(session, params, CMD)?; + let (owner, color_count) = match session.doc.project.effect(effect) { + Some((owner, found)) => match &found.kind { + EffectKind::ColorSelection { colors, .. } => (owner, colors.len()), + other => return Err(bad(CMD, format!("{} is not a color selection", other.name()))), + }, + None => return Err(bad(CMD, format!("no effect {}", effect.0))), + }; + + let index = params + .get("index") + .filter(|index| !index.is_null()) + .map(|index| index.as_u64().ok_or_else(|| bad(CMD, "`index` must be a non-negative integer"))) + .transpose()?; + let index = match index { + Some(index) => Some(usize::try_from(index).ok().filter(|index| *index < color_count).ok_or_else(|| bad(CMD, format!("no color {index} to replace")))?), + None if color_count >= MAX_SELECTED_COLORS => return Err(bad(CMD, format!("a color selection holds at most {MAX_SELECTED_COLORS} colors"))), + None => None, + }; + + let color = id_color_at(session, params, owner)?; + session.edit("Pick ID color", |session| { + let edited = session.doc.project.effect_mut(effect).ok_or_else(|| bad(CMD, format!("no effect {}", effect.0)))?; + if let EffectKind::ColorSelection { colors, .. } = &mut edited.kind { + match index.and_then(|index| colors.get_mut(index)) { + Some(slot) => *slot = color, + None => colors.push(color), + } + } + Ok(()) + })?; + Ok(json!({ "color": color, "index": index.unwrap_or(color_count) })) +} + +/// The ID map color of the texel a color selection on `owner` reads at the picked point +fn id_color_at(session: &Session, params: &Value, owner: LayerId) -> Result<[f32; 3]> { + const CMD: &str = "effect.colorSelection.pick"; + let (set_index, _, _) = session.doc.project.locate(owner).ok_or_else(|| bad(CMD, "the effect's layer is not in a texture set"))?; + let set = session.doc.project.texture_set(set_index)?; + let baked = session.baked(set_index).filter(|baked| baked.maps.contains_key(&BakedMap::Id)); + let Some(baked) = baked else { + return Err(bad(CMD, format!("texture set \"{}\" has no ID map: bake one, or set one with textureSet.meshMap.set", set.name))); + }; + + let uv = match params.get("uv") { + Some(uv) => uv_param(uv)?, + None => { + let (Some(x), Some(y)) = (f32p(params, "x"), f32p(params, "y")) else { + return Err(bad(CMD, "give `x` and `y` (viewport pixels) or `uv`")); + }; + + let (uv, material) = visible_surface(session, Vec2::new(x, y), viewport_of(session, params)) + .ok_or_else(|| bad(CMD, "nothing under that point: pick on the mesh"))?; + if material != set.material { + return Err(bad(CMD, "that surface belongs to another texture set")); + } + uv + } + }; + + // The same texel the mask evaluates, so a picked color always selects where it was picked + let size = set.size(); + let texel = [uv.x * size.0 as f32, uv.y * size.1 as f32]; + if !texel.iter().zip([size.0, size.1]).all(|(position, extent)| (0.0..extent as f32).contains(position)) { + return Err(bad(CMD, "that point is outside the texture set's UV space")); + } + baked.sample_working(BakedMap::Id, texel[0] as u32, texel[1] as u32, size, &set.block_scales()).ok_or_else(|| bad(CMD, "no ID color there")) +} + +/// The UV and mesh material under viewport pixel `screen`; hidden texture sets don't stop the ray +fn visible_surface(session: &Session, screen: Vec2, viewport: Vec2) -> Option<(Vec2, usize)> { + let viewport = viewport.max(Vec2::ONE); + let device = Vec2::new(screen.x / viewport.x * 2.0 - 1.0, 1.0 - screen.y / viewport.y * 2.0); + let ray = session.camera.ray(device, viewport.x / viewport.y); + let sets = &session.doc.project.texture_sets; + let visible = |triangle: u32| { + let material = session.mesh.material_of(triangle as usize).unwrap_or(0); + sets.iter().find(|set| set.material == material).is_none_or(|set| set.visible) + }; + + let hit = session.bvh.closest_filtered(ray.origin, ray.dir, f32::MAX, &visible)?; + let surface = surface_at(&session.mesh, hit.tri, hit.u, hit.v)?; + Some((surface.uv, session.mesh.material_of(hit.tri as usize).unwrap_or(0))) +} + +/// A `[u, v]` param of finite numbers +fn uv_param(uv: &Value) -> Result { + match finite_numbers::<2>(uv) { + Some([u, v]) => Ok(Vec2::new(u as f32, v as f32)), + _ => Err(bad("effect.colorSelection.pick", "`uv` must be [u, v] with finite numbers")), + } +} + +/// Validate the shape before reading components, without allocating for oversized input +fn finite_numbers(list: &Value) -> Option<[f64; N]> { + let items: &[Value; N] = list.as_array()?.as_slice().try_into().ok()?; + let mut numbers = [0.0; N]; + for (number, item) in numbers.iter_mut().zip(items) { + *number = item.as_f64().filter(|value| value.is_finite())?; + } + Some(numbers) +} diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 9f0d126b..d9a31b39 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -56,6 +56,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(crate::layer_ops::specs()); v.extend(crate::instance_cmds::specs()); v.extend(crate::mask_cmds::specs()); + v.extend(crate::color_selection_cmds::specs()); v.extend(crate::effect_clipboard::specs()); v.extend(crate::tool_cmds::specs()); v.extend(crate::brush_preset_cmds::specs()); @@ -65,6 +66,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(crate::quick_mask::specs()); v.extend(crate::set_cmds::specs()); v.extend(crate::meshmap_cmds::specs()); + v.extend(crate::meshmap_import_cmds::specs()); v.extend(crate::uv_tile_cmds::specs()); v.extend(crate::template_cmds::specs()); v.extend(crate::project_cmds::specs()); diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index f2b95e03..ae2f00b5 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -331,6 +331,11 @@ mod native { strp(p, key).filter(|s| !s.trim().is_empty()).ok_or_else(|| bad(cmd, format!("`{key}` is required"))) } + /// `path` made absolute (as given when that fails), for [`Project::mesh_path`]. + pub fn absolute(path: &str) -> String { + std::path::absolute(Path::new(path)).map_or_else(|_| path.to_string(), |p| p.display().to_string()) + } + /// Mesh file `path` with the files it references next to it folded in (a `.gltf`'s buffers /// and images, a loose USD layer's textures), ready to import and store in the project. pub fn read_mesh(cmd: &str, path: &str) -> Result { @@ -349,6 +354,7 @@ mod native { } else { let f = read_mesh("file.open", path)?; let mut s = Session::from_mesh_bytes(&f.name, &f.bytes, 2048, &stem_of(path))?; + s.doc.project.mesh_path = absolute(path); s.log.extend(f.warnings); Ok(s) } @@ -367,8 +373,10 @@ mod native { } #[cfg(not(target_arch = "wasm32"))] -pub use native::{open_path, read_mesh}; +pub use native::{absolute, open_path, read_mesh}; +/// `file.new {mesh, name?, resolution?, uvTiles?, template?}`: a new project from the mesh file `mesh`, +/// remembering its path for Reimport mesh. #[cfg(not(target_arch = "wasm32"))] fn new_from_mesh(s: &mut Session, p: &Value) -> Result { let path = native::path_param(p, "mesh", "file.new")?; @@ -377,6 +385,7 @@ fn new_from_mesh(s: &mut Session, p: &Value) -> Result { let res = u64p(p, "resolution").or(template.as_ref().map(|t| u64::from(t.resolution))).unwrap_or(2048); let name = strp(p, "name").map(str::to_string).unwrap_or_else(|| stem_of(path)); let mut next = Session::from_mesh_bytes_tiled(&f.name, &f.bytes, u32::try_from(res).unwrap_or(0), &name, crate::commands::boolp(p, "uvTiles"))?; + next.doc.project.mesh_path = native::absolute(path); next.log.extend(f.warnings); if let Some(t) = &template { next.apply_template(t); @@ -414,14 +423,28 @@ fn save_copy(s: &mut Session, p: &Value) -> Result { native::save_to(s, &path, false) } +/// `file.reimportMesh {path?, preserveStrokes?}`: reimport from `path`, or from the project's own +/// copy of the mesh when there is none. A path given is remembered as the project's mesh path. +/// The remembered path is never read implicitly (a project file could point it anywhere on the +/// host); callers that may read host files pass [`Session::remembered_mesh_path`] as `path`. #[cfg(not(target_arch = "wasm32"))] fn reimport(s: &mut Session, p: &Value) -> Result { - let file = strp(p, "path").map(|path| native::read_mesh("file.reimportMesh", path)).transpose()?; - s.reimport_mesh(file, crate::commands::boolp(p, "preserveStrokes").unwrap_or(false)) + let path = strp(p, "path"); + let file = path.map(|path| native::read_mesh("file.reimportMesh", path)).transpose()?; + let reply = s.reimport_mesh(file, crate::commands::boolp(p, "preserveStrokes").unwrap_or(false))?; + if let Some(path) = path { + s.doc.project.mesh_path = native::absolute(path); + } + Ok(reply) } #[cfg(not(target_arch = "wasm32"))] impl Session { + /// The file the mesh was imported from, when it is still there: what Reimport mesh reads again. + pub fn remembered_mesh_path(&self) -> Option<&str> { + Some(self.doc.project.mesh_path.as_str()).filter(|m| !m.is_empty() && std::path::Path::new(m).is_file()) + } + /// Replace the mesh with `file` (or re-read the project's own copy) and keep the project: /// texture sets map by material index. Nothing changes unless the new mesh fits the project. /// With `preserve_strokes`, painted pixels follow the surface where the UVs changed. Replies @@ -449,6 +472,7 @@ impl Session { next.log.extend(warnings); next.path = self.path.clone(); next.modified = true; + next.project_id = self.project_id; let preserved = preserve_strokes.then(|| crate::preserve::preserve_strokes(self, &mut next)); self.switch_to(next); Ok(preserved.map_or(Value::Null, |n| json!({ "preserved": n }))) @@ -611,14 +635,57 @@ fn close(s: &mut Session, _: &Value) -> Result { mod tests { use super::*; + /// Reimport mesh reads the mesh file again from where it was imported, so a change saved to + /// the file since shows up (it used to re-read the project's own copy and change nothing). + #[test] + fn reimport_picks_up_changes_saved_to_the_mesh_file() { + let dir = std::env::temp_dir().join(format!("tc_reimport_disk_{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("tri.obj"); + let obj = |z: f32| { + format!( + "v -1 -1 {z} +v 1 -1 0 +v 1 1 0 +vt 0 0 +vt 1 0 +vt 1 1 +f 1/1 2/2 3/3 +" + ) + }; + std::fs::write(&file, obj(0.0)).unwrap(); + let path = file.display().to_string(); + let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + crate::execute(&mut s, "file.new", &json!({"mesh": path, "resolution": 128})).unwrap(); + let low = |s: &Session| s.mesh.positions.iter().map(|p| p.z.abs()).fold(0.0_f32, f32::max); + assert_eq!(low(&s), 0.0); + // Edit the file, save the project, reopen it, then reimport with no path. + std::fs::write(&file, obj(0.5)).unwrap(); + let mut reopened = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); + assert_eq!(low(&reopened), 0.0, "the project still holds the old copy"); + // A command without a path never reads the remembered host path (automation allows it). + crate::execute(&mut reopened, "file.reimportMesh", &Value::Null).unwrap(); + assert_eq!(low(&reopened), 0.0, "no path: the project's own copy"); + let remembered = reopened.remembered_mesh_path().map(str::to_string).expect("the imported file is remembered"); + crate::execute(&mut reopened, "file.reimportMesh", &json!({ "path": remembered })).unwrap(); + assert!(low(&reopened) > 0.0, "the edited file must be read again"); + // The file gone: nothing is remembered, so the UI asks for one. + std::fs::remove_file(&file).unwrap(); + assert!(reopened.remembered_mesh_path().is_none()); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn reimporting_a_saved_project_marks_it_modified() { let obj = b"v -1 -1 0\nv 1 -1 0\nv 1 1 0\nvt 0 0\nvt 1 0\nvt 1 1\nf 1/1 2/2 3/3\n"; let original = Session::from_mesh_bytes("mesh.obj", obj, 128, "mesh").unwrap(); let mut saved = Session::from_project_bytes(&original.to_project_bytes().unwrap()).unwrap(); assert!(!saved.modified); + let project = saved.project_id; crate::execute(&mut saved, "file.reimportMesh", &Value::Null).unwrap(); assert!(saved.modified, "reimport must trigger the unsaved-changes prompt"); + assert_eq!(saved.project_id, project, "a reimport stays the same project"); } #[test] diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index b4ce8443..160aab90 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -42,6 +42,10 @@ fn effect_json(session: &Session, effect: &Effect, content: bool) -> Value { match &effect.kind { EffectKind::Generator(generator) => out["generator"] = generator_json(generator), EffectKind::Levels(levels) => out["levels"] = json!([levels.in_low, levels.in_high, levels.gamma, levels.out_low, levels.out_high]), + EffectKind::ColorSelection { colors, tolerance } => { + out["colors"] = json!(colors); + out["tolerance"] = json!(tolerance); + } EffectKind::Path(paths) => { out["paths"] = json!( paths.iter().map(|path| json!({ "points": path.points.len(), "uv": path.uv, "closed": path.closed, "fill": path.fill })).collect::>() diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 8c2a03d1..40ebd7bc 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -11,6 +11,7 @@ pub mod bake; pub mod brush_preset_cmds; pub mod camera_cmds; +pub mod color_selection_cmds; pub mod commands; pub mod decal_cmds; pub mod effect_clipboard; @@ -30,6 +31,8 @@ mod material_preview_pixel; pub mod materials; pub mod materialx_cmds; pub mod meshmap_cmds; +mod meshmap_file_name; +pub mod meshmap_import_cmds; mod orb_camera; pub mod orb_preview; pub mod painting; @@ -51,6 +54,7 @@ pub mod template_cmds; pub mod text_cmds; pub mod tool_cmds; mod triangle_partition; +mod uv_stroke_state; pub mod uv_tile_cmds; pub mod view_cmds; diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index d8091c06..4c286955 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -94,7 +94,7 @@ pub fn specs() -> Vec { "Edit effect", [], None, - "{effect, visible?, blend?, opacity?, name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place), level?, softness?, noise?, noiseScale?, offset?, invert?, mode?, sizes?, value?, anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, filter parameters (see effect.add.filter)}", + "{effect, visible?, blend?, opacity?, name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place), level?, softness?, noise?, noiseScale?, offset?, invert?, mode?, sizes?, value?, anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, colors?: [[r,g,b], ...] (a color selection's ID colors), filter parameters (see effect.add.filter)}", has_layer, set ), @@ -522,7 +522,8 @@ fn set(session: &mut Session, params: &Value) -> Result { *source = Source::Uniform([value.clamp(0.0, 1.0); 3]); } } - EffectKind::ColorSelection { tolerance, .. } | EffectKind::Compare { tolerance, .. } => { + EffectKind::ColorSelection { colors, tolerance } => crate::color_selection_cmds::apply_params(params, colors, tolerance)?, + EffectKind::Compare { tolerance, .. } => { if let Some(value) = f32p(params, "tolerance") { *tolerance = value.clamp(0.0, 1.0); } diff --git a/crates/engine/src/meshmap_cmds.rs b/crates/engine/src/meshmap_cmds.rs index 0fbe1f5b..4524b361 100644 --- a/crates/engine/src/meshmap_cmds.rs +++ b/crates/engine/src/meshmap_cmds.rs @@ -38,55 +38,91 @@ fn set(s: &mut Session, p: &Value) -> Result { let ts = ts_param(s, p, CMD)?; let map = map_param(p, CMD)?; let name = strp(p, "image").ok_or_else(|| bad(CMD, "`image` (an image resource name) is required"))?; - let img = s.images.get(name).cloned().ok_or_else(|| bad(CMD, format!("no image resource `{name}`")))?; - let set = s.doc.project.texture_set(ts)?.clone(); - let tiles = set.tile_grid().map(|grid| tile_images(&s.images, name, &set.uv_tiles).map(|imgs| (grid, imgs))).transpose()?; - // Every mesh map of a set shares one size: the other maps', or what a bake would make (a - // block of the bake resolution per tile of the atlas). - let (cols, rows) = tiles.as_ref().map_or((1, 1), |(g, _)| (g.cols, g.rows)); - let (res, height) = match s.doc.baked.get(&ts).filter(|b| !b.maps.is_empty()) { - Some(b) => (b.resolution, b.maps.keys().next().map_or(b.resolution, |m| b.height(*m))), - None => { - let (width, height) = set.bake.common.output_size(); - (width.saturating_mul(cols), height.saturating_mul(rows)) - } + let image = s.images.get(name).cloned().ok_or_else(|| bad(CMD, format!("no image resource `{name}`")))?; + let texture_set = s.doc.project.texture_set(ts)?; + let images = match texture_set.tile_grid() { + Some(_) => tile_images(&s.images, CMD, name, &texture_set.uv_tiles)?, + None => BTreeMap::from([(FIRST_TILE, image)]), }; - if res == 0 || height == 0 || u64::from(res) * u64::from(height) > texturecraft_bake::MAX_TEXELS || (tiles.is_none() && res > MAX_RESOLUTION) { - return Err(bad(CMD, format!("mesh map size {res} × {height} is too large or empty"))); - } - let directx = map == BakedMap::Normal && s.doc.project.normal_format == NormalFormat::DirectX; - let data = match &tiles { - None => resample(map.components(), (res, height), directx, |u, v| img.sample(u, v)), - // An atlas texel reads the image of the tile its mesh UV falls in. - Some((grid, imgs)) => resample(map.components(), (res, height), directx, |u, v| { - let uv = grid.from_atlas([u, v]); - udim_at(uv).and_then(|t| imgs.get(&t)).map_or([0.0; 4], |img| img.sample(uv[0] - uv[0].floor(), uv[1] - uv[1].floor())) - }), - }; - s.edit("Use image as mesh map", |s| { - let entry = s.doc.baked.entry(ts).or_default(); - entry.resolution = res; - entry.maps.insert(map, Arc::new(data)); - s.doc.project.texture_set_mut(ts)?.baked.insert(map); - Ok(()) - })?; - Ok(json!({ "map": map.id(), "resolution": res })) + + let resolution = s.edit("Use image as mesh map", |s| use_images(s, CMD, ts, map, &images))?; + Ok(json!({ "map": map.id(), "resolution": resolution })) } -/// The image of every UV tile of a set: `name` with its tile number (`ao.1001.png`) swapped for -/// each tile's. -fn tile_images(images: &ImageStore, name: &str, tiles: &[u32]) -> Result>> { - const CMD: &str = "textureSet.meshMap.set"; - let at = udim_in(name).ok_or_else(|| bad(CMD, format!("`{name}` names no UV tile: a UV-tiled set takes one image per tile, named like ao.1001.png")))?; +/// The tile number a set without UV tiles keys its one image by +pub(crate) const FIRST_TILE: u32 = *UDIM_RANGE.start(); + +/// Use `images` (by UV tile; one at [`FIRST_TILE`] without UV tiles) as mesh map `map` of set `ts` in the caller's edit; returns its width +pub(crate) fn use_images(s: &mut Session, cmd: &str, ts: usize, map: BakedMap, images: &BTreeMap>) -> Result { + let texture_set = s.doc.project.texture_set(ts)?; + let grid = texture_set.tile_grid(); + if let Some(tile) = texture_set.uv_tiles.iter().find(|tile| grid.is_some() && !images.contains_key(tile)) { + return Err(bad(cmd, format!("no image for UV tile {tile}"))); + } + + let (width, height) = image_map_size(s, cmd, ts)?; + + let flip_green = map == BakedMap::Normal && s.doc.project.normal_format == NormalFormat::DirectX; + let data = match (grid, images.values().next()) { + (_, None) => return Err(bad(cmd, "no image to use")), + (None, Some(image)) => resample(map.components(), (width, height), flip_green, |u, v| image.sample(u, v)), + // An atlas texel reads the image of the tile its mesh UV falls in + (Some(grid), Some(_)) => resample(map.components(), (width, height), flip_green, |u, v| { + let uv = grid.from_atlas([u, v]); + udim_at(uv).and_then(|tile| images.get(&tile)).map_or([0.0; 4], |image| image.sample(uv[0] - uv[0].floor(), uv[1] - uv[1].floor())) + }), + }; + + let entry = s.doc.baked.entry(ts).or_default(); + entry.resolution = width; + entry.maps.insert(map, Arc::new(data)); + s.doc.project.texture_set_mut(ts)?.baked.insert(map); + Ok(width) +} + +/// Dimensions shared by imported mesh maps, checked before allocating the resampled pixels +pub(crate) fn image_map_size(s: &Session, cmd: &str, ts: usize) -> Result<(u32, u32)> { + let texture_set = s.doc.project.texture_set(ts)?; + let grid = texture_set.tile_grid(); + + // Every mesh map of a set shares one size: the other maps', or a bake's (a bake-size block per atlas tile) + let (columns, rows) = grid.map_or((1, 1), |grid| (grid.cols, grid.rows)); + let (width, height) = match s.doc.baked.get(&ts).filter(|baked| !baked.maps.is_empty()) { + Some(baked) => (baked.resolution, baked.maps.keys().next().map_or(baked.resolution, |other| baked.height(*other))), + None => { + let (width, height) = texture_set.bake.common.output_size(); + (width.saturating_mul(columns), height.saturating_mul(rows)) + } + }; + let empty = width == 0 || height == 0; + let too_many_texels = u64::from(width) * u64::from(height) > texturecraft_bake::MAX_TEXELS; + let too_wide = grid.is_none() && width > MAX_RESOLUTION; + if empty || too_many_texels || too_wide { + return Err(bad(cmd, format!("mesh map size {width} × {height} is too large or empty"))); + } + + Ok((width, height)) +} + +/// The image of every UV tile of a set: `name` with its tile number (`ao.1001.png`) swapped for each tile's +fn tile_images(images: &ImageStore, cmd: &str, name: &str, tiles: &[u32]) -> Result>> { + let tile_at = + udim_in(name).ok_or_else(|| bad(cmd, format!("`{name}` names no UV tile: a UV-tiled set takes one image per tile, named like ao.1001.png")))?; + let (before_tile, after_tile) = (name.get(..tile_at).unwrap_or_default(), name.get(tile_at + 4..).unwrap_or_default()); tiles .iter() - .map(|&t| { - let tile_name = format!("{}{t}{}", name.get(..at).unwrap_or_default(), name.get(at + 4..).unwrap_or_default()); - images.get(&tile_name).cloned().map(|img| (t, img)).ok_or_else(|| bad(CMD, format!("no image `{tile_name}` for UV tile {t}"))) + .map(|&tile| { + let tile_name = format!("{before_tile}{tile}{after_tile}"); + images.get(&tile_name).cloned().map(|image| (tile, image)).ok_or_else(|| bad(cmd, format!("no image `{tile_name}` for UV tile {tile}"))) }) .collect() } +/// The UV tile number in a file name (`Body_ao.1002.png` → 1002) +pub(crate) fn tile_number(file_name: &str) -> Option { + udim_in(file_name).and_then(|at| file_name.get(at..at + 4)).and_then(|digits| digits.parse().ok()) +} + /// Where the last UDIM tile number (four digits alone, in [`UDIM_RANGE`]) in `name` starts. fn udim_in(name: &str) -> Option { let b = name.as_bytes(); diff --git a/crates/engine/src/meshmap_file_name.rs b/crates/engine/src/meshmap_file_name.rs new file mode 100644 index 00000000..fde32d5e --- /dev/null +++ b/crates/engine/src/meshmap_file_name.rs @@ -0,0 +1,159 @@ +//! Which texture set and mesh map a baked map file is for, by file name (`Body_ao.1001.png` = Body's ambient occlusion) + +use std::path::Path; + +use texturecraft_core::{BakedMap, UDIM_RANGE}; + +/// Mesh maps named by two words anywhere in the file name; they win over the one-word names +const TWO_WORD_NAMES: &[(&str, &[&str], BakedMap)] = &[ + ("world", &["normal", "normals"], BakedMap::WorldNormal), + ("bent", &["normal", "normals"], BakedMap::BentNormal), + ("ambient", &["occlusion"], BakedMap::AmbientOcclusion), +]; + +/// Mesh maps named by one word, including the two-word names written as one +const ONE_WORD_NAMES: &[(&str, BakedMap)] = &[ + ("worldnormal", BakedMap::WorldNormal), + ("worldnormals", BakedMap::WorldNormal), + ("bentnormal", BakedMap::BentNormal), + ("bentnormals", BakedMap::BentNormal), + ("ambientocclusion", BakedMap::AmbientOcclusion), + ("normal", BakedMap::Normal), + ("normals", BakedMap::Normal), + ("nrm", BakedMap::Normal), + ("occlusion", BakedMap::AmbientOcclusion), + ("ao", BakedMap::AmbientOcclusion), + ("curvature", BakedMap::Curvature), + ("curv", BakedMap::Curvature), + ("id", BakedMap::Id), + ("position", BakedMap::Position), + ("pos", BakedMap::Position), + ("thickness", BakedMap::Thickness), + ("height", BakedMap::Height), + ("displacement", BakedMap::Height), + ("opacity", BakedMap::Opacity), + ("alpha", BakedMap::Opacity), +]; + +fn is_separator(c: char) -> bool { + matches!(c, '_' | '-' | '.' | ' ') +} + +/// The lowercase file name without its folder and extension +fn lowercase_stem(path: &str) -> String { + Path::new(path).file_stem().and_then(|stem| stem.to_str()).unwrap_or_default().to_lowercase() +} + +/// What follows `set_name` at the start of a lowercase stem, when a separator follows it +fn after_set_name<'a>(stem: &'a str, set_name: &str) -> Option<&'a str> { + if set_name.is_empty() { + return None; + } + + stem.strip_prefix(&set_name.to_lowercase()).filter(|rest| rest.starts_with(is_separator)) +} + +/// The mesh map a file holds, from the words of its name after `set_name`; the last recognised word wins +pub(crate) fn baked_map_from_file_name(path: &str, set_name: &str) -> Option { + let stem = lowercase_stem(path); + let rest = after_set_name(&stem, set_name).unwrap_or(&stem); + let is_tile_number = |word: &str| word.len() == 4 && word.parse::().is_ok_and(|number| UDIM_RANGE.contains(&number)); + let words: Vec<&str> = rest.split(is_separator).filter(|word| !word.is_empty() && !is_tile_number(word)).collect(); + + let has = |name: &str| words.contains(&name); + TWO_WORD_NAMES + .iter() + .find(|(first, seconds, _)| has(first) && seconds.iter().any(|second| has(second))) + .map(|(_, _, map)| *map) + .or_else(|| words.iter().rev().find_map(|word| ONE_WORD_NAMES.iter().find(|(name, _)| name == word).map(|(_, map)| *map))) +} + +/// The set a file is for: the longest set name its name starts with before a separator (any name with one set) +pub(crate) fn texture_set_from_file_name(path: &str, set_names: &[&str]) -> Option { + if set_names.len() == 1 { + return Some(0); + } + + let stem = lowercase_stem(path); + set_names.iter().enumerate().filter(|(_, name)| after_set_name(&stem, name).is_some()).max_by_key(|(_, name)| name.chars().count()).map(|(ts, _)| ts) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn each_word_names_its_map() { + let cases = [ + ("Body_normal.png", BakedMap::Normal), + ("Body_normals.png", BakedMap::Normal), + ("Body_nrm.png", BakedMap::Normal), + ("Body_world_normal.png", BakedMap::WorldNormal), + ("Body_normals_world.png", BakedMap::WorldNormal), + ("Body_WorldNormal.png", BakedMap::WorldNormal), + ("Body_bent_normals.png", BakedMap::BentNormal), + ("Body-ambient-occlusion.png", BakedMap::AmbientOcclusion), + ("Body_AmbientOcclusion.png", BakedMap::AmbientOcclusion), + ("Body_occlusion.png", BakedMap::AmbientOcclusion), + ("Body AO.png", BakedMap::AmbientOcclusion), + ("Body_curvature.png", BakedMap::Curvature), + ("Body_curv.png", BakedMap::Curvature), + ("Body_ID.png", BakedMap::Id), + ("Body_position.png", BakedMap::Position), + ("Body_pos.png", BakedMap::Position), + ("Body_thickness.png", BakedMap::Thickness), + ("Body_height.png", BakedMap::Height), + ("Body_displacement.png", BakedMap::Height), + ("Body_opacity.png", BakedMap::Opacity), + ("Body_alpha.png", BakedMap::Opacity), + ]; + for (file, map) in cases { + assert_eq!(baked_map_from_file_name(file, "Body"), Some(map), "{file}"); + } + } + + #[test] + fn tile_numbers_and_folders_are_ignored() { + assert_eq!(baked_map_from_file_name("/bakes/Body_ao.1001.png", "Body"), Some(BakedMap::AmbientOcclusion)); + assert_eq!(baked_map_from_file_name("Body_normal_1002.tga", "Body"), Some(BakedMap::Normal)); + assert_eq!(texture_set_from_file_name("/bakes/Body_ao.1001.png", &["Head", "Body"]), Some(1)); + } + + #[test] + fn unknown_words_match_no_map() { + assert_eq!(baked_map_from_file_name("Body_diffuse.png", "Body"), None); + assert_eq!(baked_map_from_file_name("Body_1001.png", "Body"), None); + assert_eq!(baked_map_from_file_name("ambient.png", "Body"), None); + assert_eq!(baked_map_from_file_name("", "Body"), None); + } + + #[test] + fn the_set_name_is_not_read_as_a_map() { + assert_eq!(baked_map_from_file_name("World_normal.png", "World"), Some(BakedMap::Normal)); + assert_eq!(baked_map_from_file_name("ID_diffuse.png", "ID"), None); + assert_eq!(baked_map_from_file_name("Body_ao.png", ""), Some(BakedMap::AmbientOcclusion)); + } + + #[test] + fn the_longest_set_name_wins() { + let sets = ["Body", "Body_Upper", "Head"]; + assert_eq!(texture_set_from_file_name("Body_Upper_ao.png", &sets), Some(1)); + assert_eq!(texture_set_from_file_name("body_ao.png", &sets), Some(0)); + assert_eq!(texture_set_from_file_name("HEAD-normal.png", &sets), Some(2)); + } + + #[test] + fn a_set_name_must_end_at_a_separator() { + let sets = ["Body", "Head"]; + assert_eq!(texture_set_from_file_name("Bodywork_ao.png", &sets), None); + assert_eq!(texture_set_from_file_name("Arm_ao.png", &sets), None); + assert_eq!(texture_set_from_file_name("Body.png", &sets), None); + } + + #[test] + fn one_set_takes_every_file() { + assert_eq!(texture_set_from_file_name("ao.png", &["Body"]), Some(0)); + assert_eq!(texture_set_from_file_name("Head_ao.png", &["Body"]), Some(0)); + assert_eq!(texture_set_from_file_name("ao.png", &[]), None); + } +} diff --git a/crates/engine/src/meshmap_import_cmds.rs b/crates/engine/src/meshmap_import_cmds.rs new file mode 100644 index 00000000..20913de2 --- /dev/null +++ b/crates/engine/src/meshmap_import_cmds.rs @@ -0,0 +1,162 @@ +//! Import mesh maps baked in another app: many files at once, each to the set and slot its file name names + +use std::collections::BTreeMap; +use std::path::Path; + +use serde_json::{Value, json}; +use texturecraft_core::BakedMap; + +use crate::commands::{CommandSpec, always, bad, strp}; +use crate::meshmap_cmds::{FIRST_TILE, image_map_size, tile_number, use_images}; +use crate::meshmap_file_name::{baked_map_from_file_name, texture_set_from_file_name}; +use crate::resource_cmds::read_image_file; +use crate::{Result, Session, cmd}; + +const CMD: &str = "textureSet.meshMap.import"; + +/// Most files one import takes: every mesh map of dozens of sets, each split over a few UV tiles +const MAX_FILES: usize = 512; + +/// Bound retained file bytes, decoded RGBA floats and resampled maps together, before allocating pixels +const MAX_TOTAL_BYTES: u64 = 2 << 30; + +pub fn specs() -> Vec { + vec![cmd!( + "textureSet.meshMap.import", + "Import baked maps", + [], + None, + "{files: [{path, map?: mesh map id}]} → {assigned: [{path, ts, map}], unmatched: [path]} — each image file becomes the mesh map its name names (`Body_ao.png`, `Body_world_normal.png`; or `map`) of the texture set its name starts with (any name when there is one set), read as by textureSet.meshMap.set. A UV-tiled set takes one file per tile, named with the tile number (`Body_ao.1001.png`, `Body_ao.1002.png`). Left out and listed in `unmatched`: files matching no set or map, a second file for one slot or tile, files of a UV-tiled set without one of its tile numbers, and every file of a map missing a tile. One undo step (none when nothing matches); at most 512 files and 2 GiB of file bytes, decoded images and mesh maps; desktop only", + always, + import + )] +} + +fn import(s: &mut Session, p: &Value) -> Result { + import_with_budget(s, p, MAX_TOTAL_BYTES) +} + +fn import_with_budget(s: &mut Session, p: &Value, max_bytes: u64) -> Result { + let files = p.get("files").and_then(Value::as_array).ok_or_else(|| bad(CMD, "`files` (a list of {path, map?}) is required"))?; + if files.len() > MAX_FILES { + return Err(bad(CMD, format!("at most {MAX_FILES} files at once"))); + } + + let set_names: Vec<&str> = s.doc.project.texture_sets.iter().map(|set| set.name.as_str()).collect(); + let mut slots: BTreeMap<(usize, BakedMap), BTreeMap> = BTreeMap::new(); + let mut unmatched = Vec::new(); + for file in files { + let path = strp(file, "path").ok_or_else(|| bad(CMD, "every file needs a `path`"))?; + let given_map = match file.get("map") { + None | Some(Value::Null) => None, + Some(Value::String(id)) => Some(BakedMap::parse(id).ok_or_else(|| bad(CMD, format!("unknown mesh map `{id}`")))?), + Some(_) => return Err(bad(CMD, "`map` must be a mesh map id string")), + }; + + match slot_of(s, &set_names, path, given_map) { + Some((slot, tile)) if !slots.get(&slot).is_some_and(|tiles| tiles.contains_key(&tile)) => { + slots.entry(slot).or_default().insert(tile, path); + } + _ => unmatched.push(path), + } + } + + // A UV-tiled map needs a file for every tile of its set + slots.retain(|(ts, _), tiles| { + let complete = + s.doc.project.texture_sets.get(*ts).is_some_and(|set| set.tile_grid().is_none() || set.uv_tiles.iter().all(|tile| tiles.contains_key(tile))); + if !complete { + unmatched.extend(tiles.values()); + } + complete + }); + if slots.is_empty() { + return Ok(json!({ "assigned": [], "unmatched": unmatched })); + } + + let result = s.edit("Import baked maps", |s| { + let mut assigned = Vec::new(); + let mut remaining_bytes = max_bytes; + for ((ts, map), tiles) in &slots { + let (width, height) = image_map_size(s, CMD, *ts)?; + let map_bytes = u64::from(width) * u64::from(height) * map.components() as u64 * size_of::() as u64; + reserve_bytes(&mut remaining_bytes, map_bytes)?; + + let mut images = BTreeMap::new(); + for (tile, path) in tiles { + let bytes = read_image_file(CMD, path, remaining_bytes)?; + reserve_bytes(&mut remaining_bytes, bytes.len() as u64)?; + + let bytes_per_texel = size_of::<[f32; 4]>() as u64; + let name = s.add_image_resource(path, bytes, remaining_bytes / bytes_per_texel)?; + let image = s.images.get(&name).ok_or_else(|| bad(CMD, format!("no decoded image `{name}`")))?; + reserve_bytes(&mut remaining_bytes, u64::from(image.width) * u64::from(image.height) * bytes_per_texel)?; + images.insert(*tile, image.clone()); + assigned.push(json!({"path": path, "ts": ts, "map": map.id()})); + } + use_images(s, CMD, *ts, *map, &images)?; + } + Ok(assigned) + }); + // A failed edit leaves the document as it was; forget the images it decoded + if result.is_err() { + s.sync_images(); + } + + Ok(json!({ "assigned": result?, "unmatched": unmatched })) +} + +fn reserve_bytes(remaining_bytes: &mut u64, bytes: u64) -> Result<()> { + *remaining_bytes = remaining_bytes.checked_sub(bytes).ok_or_else(|| bad(CMD, "the files, decoded images and mesh maps exceed the import memory budget"))?; + Ok(()) +} + +/// The texture set and mesh map a file is for, and its UV tile ([`FIRST_TILE`] on a set without UV tiles) +fn slot_of(s: &Session, set_names: &[&str], path: &str, given_map: Option) -> Option<((usize, BakedMap), u32)> { + let ts = texture_set_from_file_name(path, set_names)?; + let map = given_map.or_else(|| baked_map_from_file_name(path, set_names.get(ts).copied().unwrap_or_default()))?; + let texture_set = s.doc.project.texture_sets.get(ts)?; + let tile = match texture_set.tile_grid() { + Some(_) => tile_number(Path::new(path).file_name()?.to_str()?).filter(|tile| texture_set.uv_tiles.contains(tile))?, + None => FIRST_TILE, + }; + Some(((ts, map), tile)) +} + +#[cfg(test)] +mod tests { + use super::*; + use texturecraft_core::BakeResolution; + + #[test] + fn import_budget_counts_decoded_images_and_resampled_maps() { + let dir = std::env::temp_dir().join(format!("texturecraft-import-budget-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let paths = [dir.join("ao.png"), dir.join("height.png")]; + for path in &paths { + image::RgbaImage::from_pixel(16, 16, image::Rgba([128, 128, 128, 255])).save(path).unwrap(); + } + let file_bytes: u64 = paths.iter().map(|path| std::fs::metadata(path).unwrap().len()).sum(); + let decoded_bytes = 2 * 16 * 16 * 16; + let map_bytes = 2 * 16 * 16 * 4; + let required_bytes = file_bytes + decoded_bytes + map_bytes; + let params = json!({"files": paths.map(|path| json!({"path": path}))}); + let mut session = Session::new_project("budget", texturecraft_geom::primitives::cube(2.0), "builtin:cube", None, 128).unwrap(); + session.doc.project.texture_sets[0].bake.common.resolution = BakeResolution::R16; + let revision = session.revision; + + for budget in [file_bytes, file_bytes + decoded_bytes, required_bytes - 1] { + let result = import_with_budget(&mut session, ¶ms, budget); + assert!(result.is_err(), "budget {budget} must cover decoded pixels and mesh maps: {result:?}"); + assert!(session.doc.resources.is_empty() && session.images.is_empty()); + assert!(session.doc.baked.values().all(|baked| baked.maps.is_empty())); + assert_eq!(session.revision, revision); + assert!(!session.modified); + assert!(session.undo_label().is_none()); + } + + let result = import_with_budget(&mut session, ¶ms, required_bytes).unwrap(); + assert_eq!(result["assigned"].as_array().unwrap().len(), 2); + std::fs::remove_dir_all(dir).unwrap(); + } +} diff --git a/crates/engine/src/painting.rs b/crates/engine/src/painting.rs index afc67a28..27377af1 100644 --- a/crates/engine/src/painting.rs +++ b/crates/engine/src/painting.rs @@ -12,8 +12,18 @@ use texturecraft_paint::{ }; use crate::session::{ActiveStroke, CloneFrom, Session, StackTarget, Tool}; +use crate::uv_stroke_state::UvStrokeState; use crate::{EngineError, Result}; +/// Shortest distance between 2D view stamps, so a stamp with no radius (a pen at zero pressure) can't stall a stroke. +const MIN_UV_STAMP_STEP: f32 = 1e-5; + +/// 2D view stamps rasterized together, bounding the memory of one batch. +const UV_STAMP_BATCH: usize = 4096; + +/// Covers a UV diagonal at the minimum step (about 142k stamps), including light pen pressure, while bounding hostile coordinates +const MAX_UV_STAMPS_PER_SAMPLE: usize = 150_000; + impl Session { /// Camera visibility for a stroke at `viewport` (cached until the camera, size or mesh change). fn eye_depth(&mut self, viewport: Vec2) -> std::sync::Arc { @@ -234,7 +244,7 @@ impl Session { stroke, canvas, depth, - uv: uv_mode.then_some((None, 0.0)), + uv: uv_mode.then(UvStrokeState::default), camera: self.camera, viewport, values, @@ -317,40 +327,49 @@ impl Session { /// Add a 2D view sample (texture coordinates). Brush size is relative to the UV square. pub fn continue_stroke_uv(&mut self, uv: Vec2, pressure: f32) { - let Some(st) = self.stroke.as_mut() else { return }; - let Some((last, carry)) = st.uv.as_mut() else { return }; - let Some(cache) = self.caches.get_mut(st.ts) else { return }; - let b = &st.stroke.settings; - let p = pressure.clamp(0.0, 1.0); - let radius = b.size * 2.0 * if p < 1.0 { b.min_size + (1.0 - b.min_size) * p } else { 1.0 }; - let step = (b.spacing * 2.0 * radius).max(1e-5); - let mut points = Vec::new(); - match *last { - None => points.push(uv), - Some(prev) => { - let seg = uv - prev; - let len = seg.length(); - let mut t = step - *carry; - while t <= len && points.len() < 4096 { - points.push(prev + seg * (t / len.max(1e-9))); - t += step; - } - *carry = len - (t - step); - } - } - // Follow path: turn the stamp with the stroke direction (y up on screen, v grows down). - let angle = match *last { - Some(prev) if b.follow_path && uv != prev => b.angle + (prev.y - uv.y).atan2(uv.x - prev.x).to_degrees() - 90.0, - _ => b.angle, + let Some(active) = self.stroke.as_mut() else { return }; + let Some(progress) = active.uv.as_mut() else { return }; + let Some(cache) = self.caches.get_mut(active.ts) else { return }; + + let settings = &active.stroke.settings; + let pressure = pressure.clamp(0.0, 1.0); + let size_scale = if pressure < 1.0 { settings.min_size + (1.0 - settings.min_size) * pressure } else { 1.0 }; + let radius = settings.size * 2.0 * size_scale; + let step = (settings.spacing * 2.0 * radius).max(MIN_UV_STAMP_STEP); + + // Follow path: turn the stamp with the stroke direction (y up on screen, v grows down) + let angle = match progress.last { + Some(previous) if settings.follow_path && uv != previous => settings.angle + (previous.y - uv.y).atan2(uv.x - previous.x).to_degrees() - 90.0, + _ => settings.angle, }; - *last = Some(uv); - let n0 = st.stroke.stamps.len() as u32; - let stamps: Vec = points - .iter() - .enumerate() - .map(|(i, c)| texturecraft_paint::UvStamp { center: *c, radius, angle, flow: b.flow, hardness: b.hardness, seed: n0 + i as u32 }) - .collect(); - texturecraft_paint::rasterize_uv(&mut st.canvas, &cache.gbuf, Self::shape(&self.images, b), &stamps); + + // The first sample is one stamp; a later one stamps every `step` along the segment from the previous + let (start, segment, mut distance) = match progress.last.replace(uv) { + None => (uv, Vec2::ZERO, 0.0), + // Pressure can shrink the step below the carry from the preceding sample + Some(previous) => (previous, uv - previous, (step - progress.carry).max(0.0)), + }; + let length = segment.length(); + let shape = Self::shape(&self.images, settings); + let mut batch = Vec::new(); + let mut stamped = 0; + while distance <= length && stamped < MAX_UV_STAMPS_PER_SAMPLE { + let batch_size = UV_STAMP_BATCH.min(MAX_UV_STAMPS_PER_SAMPLE - stamped); + batch.clear(); + while distance <= length && batch.len() < batch_size { + let center = start + segment * (distance / length.max(f32::MIN_POSITIVE)); + let seed = progress.stamps.wrapping_add((stamped + batch.len()) as u32); + batch.push(texturecraft_paint::UvStamp { center, radius, angle, flow: settings.flow, hardness: settings.hardness, seed }); + distance += step; + } + + stamped += batch.len(); + texturecraft_paint::rasterize_uv(&mut active.canvas, &cache.gbuf, shape, &batch); + } + + // At most one step, so a segment cut off at the stamp limit can't push the next one's stamps backwards + progress.carry = (length - (distance - step)).min(step); + progress.stamps = progress.stamps.wrapping_add(stamped as u32); self.stroke_painted(); } diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index 87f6d50f..86e7c9b8 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -36,12 +36,18 @@ pub(crate) fn decoded(d: texturecraft_formats::DecodedImage) -> Arc { } impl Session { - /// Add an image resource from bytes (one undo step); returns its unique, sanitized name. + /// Add an image resource from bytes (one undo step); returns its unique, sanitized name pub fn import_resource_bytes(&mut self, file_name: &str, bytes: Vec) -> Result { + self.edit("Import resource", |s| s.add_image_resource(file_name, bytes, u64::MAX)) + } + + /// Add an image within a decoded texel budget, inside the caller's edit + pub(crate) fn add_image_resource(&mut self, file_name: &str, bytes: Vec, max_texels: u64) -> Result { if bytes.len() > MAX_BYTES { return Err(EngineError::Other(format!("{file_name} is larger than {} MB", MAX_BYTES >> 20))); } - let image = texturecraft_formats::decode_image(&bytes).map_err(|e| EngineError::Other(format!("{file_name}: {e}")))?; + + let image = texturecraft_formats::decode_image_within(&bytes, max_texels).map_err(|e| EngineError::Other(format!("{file_name}: {e}")))?; let leaf = std::path::Path::new(file_name).file_name().and_then(|n| n.to_str()).unwrap_or("image"); let base = texturecraft_formats::sanitize_resource_name(leaf); let mut name = base.clone(); @@ -50,11 +56,8 @@ impl Session { name = format!("{n}_{base}"); n += 1; } - let key = name.clone(); - self.edit("Import resource", |s| { - s.doc.resources.insert(key, Arc::new(bytes)); - Ok(()) - })?; + + self.doc.resources.insert(name.clone(), Arc::new(bytes)); self.images.insert(name.clone(), decoded(image)); Ok(name) } @@ -98,15 +101,44 @@ fn list(s: &Session) -> Value { #[cfg(not(target_arch = "wasm32"))] fn import(s: &mut Session, p: &Value) -> Result { let path = strp(p, "path").ok_or_else(|| bad("resource.import", "`path` is required"))?; - let meta = std::fs::metadata(path).map_err(|e| bad("resource.import", format!("cannot read {path}: {e}")))?; - if meta.len() > MAX_BYTES as u64 { - return Err(bad("resource.import", format!("{path} is too large"))); - } - let bytes = std::fs::read(path).map_err(|e| bad("resource.import", format!("cannot read {path}: {e}")))?; + let bytes = read_image_file("resource.import", path, MAX_BYTES as u64)?; let name = s.import_resource_bytes(path, bytes)?; Ok(json!({ "name": name })) } +/// Read a regular image file within both the per-file cap and the caller's remaining byte budget +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn read_image_file(cmd: &str, path: &str, max_bytes: u64) -> Result> { + use std::io::Read; + + let max_bytes = max_bytes.min(MAX_BYTES as u64); + let read_error = |error| bad(cmd, format!("cannot read {path}: {error}")); + let too_large = || bad(cmd, format!("{path} is too large (limit {max_bytes} bytes)")); + let metadata = std::fs::metadata(path).map_err(read_error)?; + // Pipes can block on open, and devices may never reach EOF + if !metadata.is_file() { + return Err(bad(cmd, format!("{path} is not a regular file"))); + } + if metadata.len() > max_bytes { + return Err(too_large()); + } + + // Bound the read even if the file grows after the metadata check + let file = std::fs::File::open(path).map_err(read_error)?; + let mut bytes = Vec::with_capacity(metadata.len() as usize); + file.take(max_bytes + 1).read_to_end(&mut bytes).map_err(read_error)?; + if bytes.len() as u64 > max_bytes { + return Err(too_large()); + } + + Ok(bytes) +} + +#[cfg(target_arch = "wasm32")] +pub(crate) fn read_image_file(cmd: &str, _: &str, _: u64) -> Result> { + Err(bad(cmd, "file paths are not available in the browser")) +} + #[cfg(target_arch = "wasm32")] fn import(_: &mut Session, _: &Value) -> Result { Err(EngineError::Other("file paths are not available in the browser; use File > Import resources".into())) @@ -165,3 +197,24 @@ fn add_image_fill(s: &mut Session, p: &Value) -> Result { })?; Ok(json!({ "layer": id.0 })) } + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tests { + use super::*; + + #[test] + fn file_reads_obey_the_remaining_byte_budget() { + let path = std::env::temp_dir().join(format!("texturecraft-read-image-{}.png", std::process::id())); + std::fs::write(&path, b"1234").unwrap(); + let name = path.to_str().unwrap(); + assert!(read_image_file("test", name, 3).unwrap_err().to_string().contains("too large")); + assert_eq!(read_image_file("test", name, 4).unwrap(), b"1234"); + std::fs::remove_file(path).unwrap(); + } + + #[cfg(unix)] + #[test] + fn devices_are_rejected_before_reading() { + assert!(read_image_file("test", "/dev/null", 16).unwrap_err().to_string().contains("not a regular file")); + } +} diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index c6b7c469..298f7f61 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -295,8 +295,8 @@ pub(crate) struct ActiveStroke { pub canvas: StrokeCanvas, /// Camera visibility for 3D strokes (None for strokes in the 2D view). pub depth: Option>, - /// 2D view strokes: last UV point and the distance carried to the next stamp. - pub uv: Option<(Option, f32)>, + /// 2D view strokes: where the stroke is between samples. + pub uv: Option, pub camera: OrbitCamera, pub viewport: Vec2, pub values: BTreeMap, @@ -318,6 +318,9 @@ pub struct Session { pub mesh: Arc, /// Unique per loaded mesh and UV layout (GPU caches compare it). pub mesh_id: u64, + /// Unique per open project: a mesh reimport or UV layout change keeps it, and opening, closing + /// or creating a project replaces it. + pub project_id: u64, /// The mesh with its own UVs (`mesh` maps UV-tiled sets into their atlas). pub(crate) source: Arc, pub bvh: Arc, @@ -384,6 +387,7 @@ impl Session { Ok(Session { doc, mesh_id: next_mesh_id(), + project_id: next_mesh_id(), source, mesh, bvh: Arc::new(bvh), diff --git a/crates/engine/src/uv_stroke_state.rs b/crates/engine/src/uv_stroke_state.rs new file mode 100644 index 00000000..5ce5ae2f --- /dev/null +++ b/crates/engine/src/uv_stroke_state.rs @@ -0,0 +1,14 @@ +//! Where a stroke in the 2D view is between pointer samples. + +use texturecraft_geom::glam::Vec2; + +/// A 2D view stroke's progress: its last point, the distance carried to the next stamp and the stamps so far. +#[derive(Clone, Copy, Debug, Default)] +pub(crate) struct UvStrokeState { + /// The last sample's texture coordinates (None before the first sample). + pub last: Option, + /// Distance from the last stamp to the last sample, at most one stamp step. + pub carry: f32, + /// Stamps so far: the next stamp's seed, so noise alphas don't repeat from sample to sample. + pub stamps: u32, +} diff --git a/crates/engine/tests/bake.rs b/crates/engine/tests/it/bake.rs similarity index 100% rename from crates/engine/tests/bake.rs rename to crates/engine/tests/it/bake.rs diff --git a/crates/engine/tests/bake_resolution.rs b/crates/engine/tests/it/bake_resolution.rs similarity index 100% rename from crates/engine/tests/bake_resolution.rs rename to crates/engine/tests/it/bake_resolution.rs diff --git a/crates/engine/tests/bake_settings.rs b/crates/engine/tests/it/bake_settings.rs similarity index 100% rename from crates/engine/tests/bake_settings.rs rename to crates/engine/tests/it/bake_settings.rs diff --git a/crates/engine/tests/bake_tiles.rs b/crates/engine/tests/it/bake_tiles.rs similarity index 100% rename from crates/engine/tests/bake_tiles.rs rename to crates/engine/tests/it/bake_tiles.rs diff --git a/crates/engine/tests/it/color_selection.rs b/crates/engine/tests/it/color_selection.rs new file mode 100644 index 00000000..bdb984b5 --- /dev/null +++ b/crates/engine/tests/it/color_selection.rs @@ -0,0 +1,309 @@ +//! Color selection effects: editing their ID colors and picking them from the ID mesh map + +use serde_json::{Value, json}; +use texturecraft_engine::core::{EffectKind, LayerId}; +use texturecraft_engine::geom::glam::Vec2; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +const TOP_LEFT_ID: [u8; 3] = [200, 30, 10]; +const TOP_RIGHT_ID: [u8; 3] = [10, 200, 30]; +const BOTTOM_ID: [u8; 3] = [30, 10, 200]; +const NO_PART: [f32; 3] = [0.0, 0.0, 0.0]; + +fn session() -> Session { + let mut session = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 256).unwrap(); + session.viewport = Vec2::new(400.0, 400.0); + session.camera.yaw = 0.0; + session.camera.pitch = 0.0; + session.update(); + session +} + +/// An 8×8 ID map: two parts on the top half, one on the bottom half +fn id_map_png() -> Vec { + let image = image::RgbaImage::from_fn(8, 8, |x, y| { + let [red, green, blue] = match (x < 4, y < 4) { + (true, true) => TOP_LEFT_ID, + (false, true) => TOP_RIGHT_ID, + _ => BOTTOM_ID, + }; + image::Rgba([red, green, blue, 255]) + }); + let mut bytes = Vec::new(); + image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + bytes +} + +fn stored(id: [u8; 3]) -> [f32; 3] { + id.map(|channel| channel as f32 / 255.0) +} + +fn assert_close(actual: [f32; 3], expected: [f32; 3]) { + assert!(actual.iter().zip(expected).all(|(channel, wanted)| (channel - wanted).abs() < 1e-3), "{actual:?} vs {expected:?}"); +} + +/// A fill layer masked by a color selection that selects no part yet: (layer, effect) +fn masked_layer(session: &mut Session, with_id_map: bool) -> (LayerId, LayerId) { + if with_id_map { + let image = session.import_resource_bytes("id.png", id_map_png()).unwrap(); + execute(session, "textureSet.meshMap.set", &json!({"map": "id", "image": image})).unwrap(); + } + + let layer = LayerId(execute(session, "layer.add.fill", &json!({"color": [0.9, 0.1, 0.1]})).unwrap()["layer"].as_u64().unwrap()); + execute(session, "mask.add.colorSelection", &json!({"color": NO_PART, "tolerance": 0.05})).unwrap(); + let effect = session.doc.project.layer(layer).unwrap().mask.as_ref().unwrap().effects[0].id; + (layer, effect) +} + +fn colors(session: &Session, effect: LayerId) -> Vec<[f32; 3]> { + match &session.doc.project.effect(effect).unwrap().1.kind { + EffectKind::ColorSelection { colors, .. } => colors.clone(), + other => panic!("not a color selection: {other:?}"), + } +} + +#[test] +fn a_color_picked_on_the_mesh_is_selected_where_it_was_picked() { + let mut session = session(); + let (layer, effect) = masked_layer(&mut session, true); + let center = Vec2::new(200.0, 200.0); + let hit = session.pick(center, session.viewport).unwrap(); + let (width, height) = session.caches[0].size; + let texel = ((hit.uv.x * width as f32) as u32, (hit.uv.y * height as f32) as u32); + assert_eq!(session.mask_at(layer, &[texel]).unwrap(), vec![0.0], "nothing selected before the pick"); + + let picked = execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "x": center.x, "y": center.y})).unwrap(); + + assert_eq!(picked["index"], json!(1)); + assert_eq!(colors(&session, effect).len(), 2); + assert_eq!(session.mask_at(layer, &[texel]).unwrap(), vec![1.0]); + execute(&mut session, "edit.undo", &Value::Null).unwrap(); + assert_eq!(colors(&session, effect), vec![NO_PART], "one undo step"); +} + +#[test] +fn a_uv_pick_adds_the_color_there_or_replaces_one() { + let mut session = session(); + let (_, effect) = masked_layer(&mut session, true); + + execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": [0.25, 0.25]})).unwrap(); + assert_close(colors(&session, effect)[1], stored(TOP_LEFT_ID)); + + let replaced = execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": [0.75, 0.75], "index": 0})).unwrap(); + assert_eq!(replaced["index"], json!(0)); + let picked = colors(&session, effect); + assert_eq!(picked.len(), 2); + assert_close(picked[0], stored(BOTTOM_ID)); + execute(&mut session, "edit.undo", &Value::Null).unwrap(); + assert_eq!(colors(&session, effect)[0], NO_PART, "one undo step"); +} + +#[test] +fn the_colors_param_replaces_the_list_in_one_undo_step() { + let mut session = session(); + let (_, effect) = masked_layer(&mut session, false); + let edited = [stored(TOP_LEFT_ID), stored(TOP_RIGHT_ID)]; + + execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": edited, "tolerance": 0.2})).unwrap(); + assert_eq!(colors(&session, effect), edited.to_vec()); + let Some((_, found)) = session.doc.project.effect(effect) else { panic!("effect gone") }; + assert!(matches!(found.kind, EffectKind::ColorSelection { tolerance, .. } if tolerance == 0.2)); + + execute(&mut session, "edit.undo", &Value::Null).unwrap(); + assert_eq!(colors(&session, effect), vec![NO_PART]); +} + +#[test] +fn bad_colors_are_refused_and_change_nothing() { + let mut session = session(); + let (_, effect) = masked_layer(&mut session, false); + let refused = [json!([]), json!([[0.5, 0.5]]), json!([[0.5, "x", 0.5]]), json!([[0.5, null, 0.5]]), json!("red")]; + + for colors_param in &refused { + assert!(execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": colors_param})).is_err(), "{colors_param}"); + } + assert_eq!(colors(&session, effect), vec![NO_PART]); + execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": [[1e300, 0.5, 0.5]]})).unwrap(); + assert_eq!(colors(&session, effect), vec![[1.0, 0.5, 0.5]], "out-of-range values clamp to 0..1"); +} + +#[test] +fn picking_explains_what_is_missing() { + let mut session = session(); + let (layer, effect) = masked_layer(&mut session, false); + let pick = |session: &mut Session, params: Value| execute(session, "effect.colorSelection.pick", ¶ms).unwrap_err().to_string(); + + assert!(pick(&mut session, json!({"effect": effect.0, "uv": [0.5, 0.5]})).contains("no ID map")); + let image = session.import_resource_bytes("id.png", id_map_png()).unwrap(); + execute(&mut session, "textureSet.meshMap.set", &json!({"map": "id", "image": image})).unwrap(); + assert!(pick(&mut session, json!({"effect": effect.0, "x": 1, "y": 1})).contains("nothing under that point")); + assert!(pick(&mut session, json!({"effect": effect.0, "uv": [1.5, 0.5]})).contains("outside")); + assert!(pick(&mut session, json!({"effect": effect.0, "uv": [0.5, 0.5], "index": 7})).contains("no color 7")); + assert!(pick(&mut session, json!({"effect": effect.0})).contains("`x` and `y`")); + + let fill = execute(&mut session, "effect.add.fill", &json!({"layer": layer.0})).unwrap()["effect"].as_u64().unwrap(); + assert!(pick(&mut session, json!({"effect": fill, "uv": [0.5, 0.5]})).contains("not a color selection")); + assert_eq!(colors(&session, effect), vec![NO_PART]); +} + +#[test] +fn hostile_params_never_crash_the_color_selection_commands() { + let mut session = session(); + let (_, effect) = masked_layer(&mut session, true); + let hostile = [ + json!({"effect": effect.0, "x": f32::MAX, "y": -1e30, "viewport": [0, 0]}), + json!({"effect": effect.0, "uv": [f64::MAX, -1e300], "index": u64::MAX}), + json!({"effect": effect.0, "uv": [0.5], "colors": [[f64::MAX, -f64::MAX, 0.0]]}), + json!({"effect": effect.0, "uv": "x", "colors": {"r": 1}}), + json!({"effect": u64::MAX, "uv": [0.5, 0.5]}), + ]; + + for params in &hostile { + let _ = execute(&mut session, "effect.colorSelection.pick", params); + let _ = execute(&mut session, "effect.set", params); + session.update(); + } +} + +#[test] +fn a_hidden_texture_set_does_not_block_a_pick_behind_it() { + let mut session = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 256).unwrap(); + session.viewport = Vec2::new(400.0, 400.0); + session.update(); + let set_named = |name: &str| session.doc.project.texture_sets.iter().position(|set| set.name == name).unwrap(); + let (base, ball) = (set_named("Base"), set_named("Ball")); + execute(&mut session, "textureSet.select", &json!({"ts": base})).unwrap(); + let (_, effect) = masked_layer(&mut session, true); + let pick_at = |session: &mut Session, y: f32| execute(session, "effect.colorSelection.pick", &json!({"effect": effect.0, "x": 200, "y": y})); + let ball_in_front = |session: &Session, y: f32| { + session.pick(Vec2::new(200.0, y), session.viewport).is_some_and(|hit| session.texture_set_of_material(hit.material) == Some(ball)) + }; + + // Down the middle until a pixel where the hidden ball covers the base: the pick reads the base + execute(&mut session, "textureSet.visible", &json!({"ts": ball, "visible": false})).unwrap(); + let mut covered = None; + for y in (200..400).map(|y| y as f32) { + if ball_in_front(&session, y) && pick_at(&mut session, y).is_ok() { + covered = Some(y); + break; + } + } + let y = covered.expect("a pixel where the ball covers the base"); + assert_eq!(colors(&session, effect).len(), 2); + + execute(&mut session, "textureSet.visible", &json!({"ts": ball, "visible": true})).unwrap(); + assert!(pick_at(&mut session, y).unwrap_err().to_string().contains("another texture set"), "a shown ball still blocks it"); +} + +#[test] +fn malformed_replacement_indices_are_rejected_without_editing() { + let mut session = session(); + let (_, effect) = masked_layer(&mut session, true); + let history = session.history_labels(); + + for index in [json!(-1), json!(0.4), json!("0"), json!(true), json!([])] { + let result = execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": [0.25, 0.25], "index": index})); + assert!(result.is_err(), "invalid index {index} was accepted: {result:?}"); + assert_eq!(colors(&session, effect), vec![NO_PART]); + assert_eq!(session.history_labels(), history); + } +} + +#[test] +fn the_color_limit_rejects_additions_but_allows_replacement() { + let mut session = session(); + let (_, effect) = masked_layer(&mut session, true); + let full = vec![NO_PART; 256]; + execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": full})).unwrap(); + let history = session.history_labels(); + let project = session.doc.project.clone(); + + for params in [json!({"effect": effect.0, "uv": [0.25, 0.25]}), json!({"effect": effect.0, "uv": [0.25, 0.25], "index": 256})] { + assert!(execute(&mut session, "effect.colorSelection.pick", ¶ms).is_err()); + assert_eq!(colors(&session, effect), full); + assert_eq!(session.history_labels(), history); + } + assert!(execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": vec![NO_PART; 257], "name": "Invalid edit"})).is_err()); + assert_eq!(session.history_labels(), history); + assert_eq!(session.doc.project, project, "invalid colors also roll back edits to other fields"); + + execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": [0.25, 0.25], "index": 255})).unwrap(); + assert_eq!(colors(&session, effect).len(), 256); + assert_close(colors(&session, effect)[255], stored(TOP_LEFT_ID)); +} + +#[test] +fn inspect_exposes_the_selected_colors_and_tolerance() { + let mut session = session(); + let (layer, effect) = masked_layer(&mut session, true); + execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": [0.25, 0.25]})).unwrap(); + execute(&mut session, "effect.set", &json!({"effect": effect.0, "tolerance": 0.25})).unwrap(); + + let inspected = execute(&mut session, "project.inspect", &Value::Null).unwrap(); + let layer = inspected["layers"].as_array().unwrap().iter().find(|found| found["id"] == layer.0).unwrap(); + let found = &layer["mask"]["effects"][0]; + assert_eq!(found["colors"], json!(colors(&session, effect))); + assert_eq!(found["tolerance"], json!(0.25)); +} + +#[test] +fn picks_use_the_working_texel_on_a_smaller_uv_tile() { + let mut session = Session::new_project("UV tiles", primitives::udim_plane(), "builtin:udim_plane", None, 256).unwrap(); + for tile in [1001, 1002] { + session.import_resource_bytes(&format!("id.{tile}.png"), id_map_png()).unwrap(); + } + execute(&mut session, "textureSet.meshMap.set", &json!({"map": "id", "image": "id.1001.png"})).unwrap(); + let (layer, effect) = masked_layer(&mut session, false); + execute(&mut session, "textureSet.tile.resolution", &json!({"tile": 1002, "resolution": 128})).unwrap(); + execute(&mut session, "effect.set", &json!({"effect": effect.0, "tolerance": 0.0})).unwrap(); + let size = session.doc.project.texture_sets[0].size(); + let uv = [0.625, 0.25]; + let texel = ((uv[0] * size.0 as f32) as u32, (uv[1] * size.1 as f32) as u32); + assert_eq!(session.mask_at(layer, &[texel]).unwrap(), vec![0.0]); + + execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": uv})).unwrap(); + assert_eq!(session.mask_at(layer, &[texel]).unwrap(), vec![1.0]); + let before = colors(&session, effect); + let result = execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": [0.9, 0.8]})); + assert!(result.unwrap_err().to_string().contains("no ID color"), "unused tile space has no sample"); + assert_eq!(colors(&session, effect), before); +} + +#[test] +#[ignore = "release benchmark; run with --ignored --nocapture --test-threads=1"] +fn benchmark_color_selection_edits() { + use std::time::{Duration, Instant}; + + const SAMPLES: u32 = 10; + for resolution in [256, 1024] { + let started = Instant::now(); + let mut session = Session::new_project("benchmark", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, resolution).unwrap(); + let (_, effect) = masked_layer(&mut session, true); + session.update(); + let construction = started.elapsed(); + + for count in [1, 256] { + execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": vec![NO_PART; count]})).unwrap(); + session.update(); + let params = json!({"effect": effect.0, "uv": [0.25, 0.25], "index": count - 1}); + let (mut command_time, mut composite_time) = (Duration::ZERO, Duration::ZERO); + for _ in 0..SAMPLES { + let started = Instant::now(); + execute(&mut session, "effect.colorSelection.pick", ¶ms).unwrap(); + command_time += started.elapsed(); + let started = Instant::now(); + session.update(); + composite_time += started.elapsed(); + execute(&mut session, "edit.undo", &Value::Null).unwrap(); + session.update(); + } + println!( + "{resolution}x{resolution}, {count} colors, {SAMPLES} samples: construction {construction:.3?}; pick {:.3?}; composite {:.3?}; session memory {} bytes", + command_time / SAMPLES, + composite_time / SAMPLES, + session.memory().total() + ); + } + } +} diff --git a/crates/engine/tests/content_effects.rs b/crates/engine/tests/it/content_effects.rs similarity index 100% rename from crates/engine/tests/content_effects.rs rename to crates/engine/tests/it/content_effects.rs diff --git a/crates/engine/tests/export_colour_space.rs b/crates/engine/tests/it/export_colour_space.rs similarity index 100% rename from crates/engine/tests/export_colour_space.rs rename to crates/engine/tests/it/export_colour_space.rs diff --git a/crates/engine/tests/filter_swap.rs b/crates/engine/tests/it/filter_swap.rs similarity index 100% rename from crates/engine/tests/filter_swap.rs rename to crates/engine/tests/it/filter_swap.rs diff --git a/crates/engine/tests/filters.rs b/crates/engine/tests/it/filters.rs similarity index 100% rename from crates/engine/tests/filters.rs rename to crates/engine/tests/it/filters.rs diff --git a/crates/engine/tests/it/high_poly_missed.rs b/crates/engine/tests/it/high_poly_missed.rs new file mode 100644 index 00000000..c5b132fa --- /dev/null +++ b/crates/engine/tests/it/high_poly_missed.rs @@ -0,0 +1,57 @@ +use texturecraft_engine::bake::{HighPolyReach, RayStart, VertexReach, high_poly_missed}; +use texturecraft_engine::geom::glam::Vec3; + +fn vertex(height: f32) -> Option { + Some(VertexReach { + low_position: Vec3::ZERO, + start: RayStart::Distance { up: Vec3::Y, scale: 1.0 }, + high_position: Vec3::new(0.0, height, 0.0), + high_facing: Vec3::Y, + name_matches: true, + }) +} + +fn reach(vertices: Vec>) -> Option { + Some(HighPolyReach { vertices, cage_units: 1.0, ignore_backface: false }) +} + +fn sets() -> Vec> { + vec![None, reach(vec![vertex(0.5), vertex(-0.25), None, None, None]), reach(vec![None, None, vertex(0.5), vertex(-0.25), None])] +} + +const DISTANCES: [(f32, f32); 3] = [(9.0, 9.0), (0.25, 0.25), (0.5, 0.125)]; + +#[test] +fn each_owning_set_uses_its_own_frontal_and_rear_distances() { + let reaches = sets(); + assert_eq!(high_poly_missed(&reaches, &DISTANCES, None, 6), vec![1.0, 0.0, 0.0, 1.0, 0.0, 0.0]); + let expanded = [(9.0, 9.0), (0.5, 0.25), (0.5, 0.25)]; + assert_eq!(high_poly_missed(&reaches, &expanded, None, 6), vec![0.0; 6]); +} + +#[test] +fn selected_set_filter_leaves_other_sets_unmarked() { + let reaches = sets(); + assert_eq!(high_poly_missed(&reaches, &DISTANCES, Some(1), 6), vec![1.0, 0.0, 0.0, 0.0, 0.0, 0.0]); + assert_eq!(high_poly_missed(&reaches, &DISTANCES, Some(2), 6), vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0]); + for only_set in [0, reaches.len(), usize::MAX] { + assert_eq!(high_poly_missed(&reaches, &DISTANCES, Some(only_set), 6), vec![0.0; 6]); + } +} + +#[test] +fn missing_reach_or_distances_leave_vertices_unmarked() { + assert_eq!(high_poly_missed(&[], &DISTANCES, None, 6), vec![0.0; 6]); + assert_eq!(high_poly_missed(&sets(), &[], None, 6), vec![0.0; 6]); + assert_eq!(high_poly_missed(&sets(), &DISTANCES[..2], None, 6), vec![1.0, 0.0, 0.0, 0.0, 0.0, 0.0]); + assert_eq!(high_poly_missed(&sets(), &DISTANCES, None, 1), vec![1.0]); + assert!(high_poly_missed(&sets(), &DISTANCES, None, 0).is_empty()); +} + +#[test] +fn a_reached_vertex_is_not_overridden_by_a_later_set() { + let reaches = [reach(vec![vertex(0.5)]), reach(vec![vertex(0.5)])]; + let distances = [(0.5, 0.0), (0.25, 0.0)]; + assert_eq!(high_poly_missed(&reaches, &distances, None, 1), vec![0.0]); + assert_eq!(high_poly_missed(&reaches, &distances, Some(1), 1), vec![1.0]); +} diff --git a/crates/engine/tests/instances.rs b/crates/engine/tests/it/instances.rs similarity index 100% rename from crates/engine/tests/instances.rs rename to crates/engine/tests/it/instances.rs diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs new file mode 100644 index 00000000..7f13db57 --- /dev/null +++ b/crates/engine/tests/it/main.rs @@ -0,0 +1,27 @@ +//! One integration-test executable avoids linking the same dependencies for every feature. +//! Keep feature tests in their own modules; the standalone session.rs target remains available. + +mod bake; +mod bake_resolution; +mod bake_settings; +mod bake_tiles; +mod color_selection; +mod content_effects; +mod export_colour_space; +mod filter_swap; +mod filters; +mod high_poly_missed; +mod instances; +mod materialcraft_link; +mod materialx; +mod materialx_import; +mod meshmap_import; +mod painter_gaps; +mod path_tool; +mod perf; +mod polygon_fill; +mod project_recovery; +mod sample; +mod tools; +mod udim; +mod uv_strokes; diff --git a/crates/engine/tests/materialcraft_link.rs b/crates/engine/tests/it/materialcraft_link.rs similarity index 100% rename from crates/engine/tests/materialcraft_link.rs rename to crates/engine/tests/it/materialcraft_link.rs diff --git a/crates/engine/tests/materialx.rs b/crates/engine/tests/it/materialx.rs similarity index 100% rename from crates/engine/tests/materialx.rs rename to crates/engine/tests/it/materialx.rs diff --git a/crates/engine/tests/materialx_import.rs b/crates/engine/tests/it/materialx_import.rs similarity index 100% rename from crates/engine/tests/materialx_import.rs rename to crates/engine/tests/it/materialx_import.rs diff --git a/crates/engine/tests/it/meshmap_import.rs b/crates/engine/tests/it/meshmap_import.rs new file mode 100644 index 00000000..33dc2ec8 --- /dev/null +++ b/crates/engine/tests/it/meshmap_import.rs @@ -0,0 +1,298 @@ +//! Importing baked map files at once: each lands in the texture set and mesh map its name names + +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; +use texturecraft_engine::core::BakedMap; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +/// The material ball: texture sets "Ball" and "Base" +fn session() -> Session { + Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap() +} + +/// A folder of 4×4 gray PNGs named `files`, each with its own gray level +fn bake_folder(test: &str, files: &[&str]) -> PathBuf { + let dir = std::env::temp_dir().join(format!("texturecraft-meshmap-import-{test}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + for (index, file) in files.iter().enumerate() { + let gray = u8::try_from(20 + 20 * index).unwrap_or(u8::MAX); + image::RgbaImage::from_pixel(4, 4, image::Rgba([gray, gray, gray, 255])).save(dir.join(file)).unwrap(); + } + dir +} + +fn import(s: &mut Session, dir: &Path, files: &[(&str, Option<&str>)]) -> Value { + let files: Vec = files + .iter() + .map(|(file, map)| { + let path = dir.join(file).display().to_string(); + match map { + Some(map) => json!({"path": path, "map": map}), + None => json!({"path": path}), + } + }) + .collect(); + execute(s, "textureSet.meshMap.import", &json!({ "files": files })).unwrap() +} + +fn file_names(list: &Value) -> Vec { + list.as_array() + .unwrap() + .iter() + .map(|entry| entry.as_str().unwrap_or_else(|| entry["path"].as_str().unwrap())) + .map(|path| path.rsplit(['/', '\\']).next().unwrap().to_string()) + .collect() +} + +fn has_map(s: &Session, ts: usize, map: BakedMap) -> bool { + s.doc.baked.get(&ts).is_some_and(|baked| baked.maps.contains_key(&map)) && s.doc.project.texture_sets[ts].baked.contains(&map) +} + +#[test] +fn files_go_to_the_set_and_map_their_names_name() { + let files = ["Ball_normal.png", "Ball_world_normal.png", "base-AO.png", "Base_curvature.png", "Ball_diffuse.png", "Head_ao.png", "Base_id.png"]; + let dir = bake_folder("sets", &files); + let mut s = session(); + let label_before = s.undo_label().map(str::to_string); + + let result = import(&mut s, &dir, &files.map(|file| (file, None))); + + let assigned = &result["assigned"]; + assert_eq!(file_names(assigned).len(), 5, "{result}"); + for (ts, map) in [(0, BakedMap::Normal), (0, BakedMap::WorldNormal), (1, BakedMap::AmbientOcclusion), (1, BakedMap::Curvature), (1, BakedMap::Id)] { + assert!(has_map(&s, ts, map), "set {ts} lacks {}", map.id()); + assert!(assigned.as_array().unwrap().iter().any(|entry| entry["ts"] == ts && entry["map"] == map.id()), "{result}"); + } + assert_eq!(file_names(&result["unmatched"]), ["Ball_diffuse.png", "Head_ao.png"]); + assert_eq!(s.undo_label(), Some("Import baked maps")); + + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(s.undo_label().map(str::to_string), label_before, "one undo step"); + assert!(s.doc.baked.values().all(|baked| baked.maps.is_empty()), "undo removes every imported map"); + assert!(s.doc.resources.is_empty(), "undo removes the imported image resources"); + std::fs::remove_dir_all(dir).ok(); +} + +#[test] +fn a_given_map_overrides_the_name() { + let dir = bake_folder("override", &["Ball_bake3.png", "Base_normal.png"]); + let mut s = session(); + + let result = import(&mut s, &dir, &[("Ball_bake3.png", Some("thickness")), ("Base_normal.png", Some("height"))]); + + assert_eq!(file_names(&result["assigned"]).len(), 2, "{result}"); + assert!(has_map(&s, 0, BakedMap::Thickness)); + assert!(has_map(&s, 1, BakedMap::Height)); + assert!(!has_map(&s, 1, BakedMap::Normal)); + std::fs::remove_dir_all(dir).ok(); +} + +#[test] +fn a_second_file_for_one_slot_is_left_out() { + let dir = bake_folder("twice", &["Ball_ao.png", "Ball_occlusion.png"]); + let mut s = session(); + + let result = import(&mut s, &dir, &[("Ball_ao.png", None), ("Ball_occlusion.png", None)]); + + assert_eq!(file_names(&result["assigned"]), ["Ball_ao.png"]); + assert_eq!(file_names(&result["unmatched"]), ["Ball_occlusion.png"]); + assert_eq!(s.doc.resources.len(), 1, "the left-out file is not imported"); + std::fs::remove_dir_all(dir).ok(); +} + +#[test] +fn an_undecodable_file_imports_nothing() { + let dir = bake_folder("undecodable", &["Ball_ao.png"]); + std::fs::write(dir.join("Base_ao.png"), b"not an image").unwrap(); + let mut s = session(); + let label_before = s.undo_label().map(str::to_string); + let files = json!({"files": [{"path": dir.join("Ball_ao.png").display().to_string()}, {"path": dir.join("Base_ao.png").display().to_string()}]}); + + let error = execute(&mut s, "textureSet.meshMap.import", &files).unwrap_err().to_string(); + + assert!(error.contains("Base_ao.png"), "{error}"); + assert!(s.doc.baked.values().all(|baked| baked.maps.is_empty())); + assert!(s.doc.resources.is_empty() && s.images.is_empty()); + assert_eq!(s.undo_label().map(str::to_string), label_before); + std::fs::remove_dir_all(dir).ok(); +} + +/// The UV tile plane: one texture set "Plane" on tiles 1001 and 1002 +fn tiled_session() -> Session { + Session::new_project("t", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap() +} + +#[test] +fn a_uv_tiled_set_takes_one_file_per_tile_however_each_is_written() { + let files = ["Plane_ao.1001.png", "plane-AO-1002.png"]; + let dir = bake_folder("tiles", &files); + let mut s = tiled_session(); + + let result = import(&mut s, &dir, &files.map(|file| (file, None))); + + assert_eq!(file_names(&result["assigned"]).len(), 2, "{result}"); + let baked = &s.doc.baked[&0]; + let ao = &baked.maps[&BakedMap::AmbientOcclusion]; + let width = baked.resolution as usize; + let middle_row = ao.len() / width / 2 * width; + assert!(ao[middle_row + width / 4] < ao[middle_row + 3 * width / 4], "each tile reads its own file"); + std::fs::remove_dir_all(dir).ok(); +} + +#[test] +fn tiled_files_without_their_tiles_are_left_out_alone() { + let files = ["Plane_ao.1001.png", "Plane_ao.1002.png", "Plane_normal.png", "Plane_curvature.1001.png", "Plane_id.1005.png"]; + let dir = bake_folder("partial-tiles", &files); + let mut s = tiled_session(); + + let result = import(&mut s, &dir, &files.map(|file| (file, None))); + + assert_eq!(file_names(&result["assigned"]), ["Plane_ao.1001.png", "Plane_ao.1002.png"]); + assert_eq!(file_names(&result["unmatched"]), ["Plane_normal.png", "Plane_id.1005.png", "Plane_curvature.1001.png"]); + assert!(has_map(&s, 0, BakedMap::AmbientOcclusion)); + assert_eq!(s.doc.resources.len(), 2, "left-out files are not imported"); + std::fs::remove_dir_all(dir).ok(); +} + +#[test] +fn nothing_matched_makes_no_undo_step() { + let dir = bake_folder("none", &["Head_ao.png", "Ball_diffuse.png"]); + let mut s = session(); + let label_before = s.undo_label().map(str::to_string); + + let result = import(&mut s, &dir, &[("Head_ao.png", None), ("Ball_diffuse.png", None)]); + + assert_eq!(file_names(&result["assigned"]), Vec::::new()); + assert_eq!(file_names(&result["unmatched"]).len(), 2); + assert_eq!(s.undo_label().map(str::to_string), label_before); + assert!(!s.modified); + std::fs::remove_dir_all(dir).ok(); +} + +#[test] +fn an_invalid_map_override_does_not_fall_back_to_the_file_name() { + let dir = bake_folder("invalid-map", &["Ball_ao.png"]); + let mut session = session(); + for map in [json!(true), json!(42), json!([]), json!({}), json!("unknown")] { + let params = json!({"files": [{"path": dir.join("Ball_ao.png"), "map": map}]}); + let result = execute(&mut session, "textureSet.meshMap.import", ¶ms); + assert!(result.is_err(), "invalid map {map} must be rejected: {result:?}"); + assert!(session.doc.resources.is_empty()); + assert!(!session.modified); + } + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +#[ignore = "release benchmark; run with --ignored --nocapture --test-threads=1"] +fn benchmark_baked_map_import() { + use std::time::Instant; + use texturecraft_engine::core::BakeResolution; + + let dir = std::env::temp_dir().join(format!("texturecraft-import-benchmark-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + for (size, tiled) in [(1024, false), (2048, false), (1024, true)] { + let mut files = Vec::new(); + let mut encoded_bytes = 0; + for map in ["normal", "ao", "curvature"] { + for tile in 1001..=if tiled { 1002 } else { 1001 } { + let path = dir.join(format!("mesh_{map}.{tile}.png")); + image::RgbaImage::from_fn(size, size, |x, y| { + let value = (x.wrapping_mul(73) ^ y.wrapping_mul(151) ^ tile) as u8; + image::Rgba([value, value.wrapping_add(37), 255, 255]) + }) + .save(&path) + .unwrap(); + encoded_bytes += std::fs::metadata(&path).unwrap().len(); + files.push(json!({"path": path})); + } + } + let params = json!({"files": files}); + let mut milliseconds = Vec::new(); + for iteration in 0..6 { + let mesh = if tiled { primitives::udim_plane() } else { primitives::cube(2.0) }; + let mut session = Session::new_project("benchmark", mesh, "builtin:cube", None, 128).unwrap(); + session.doc.project.texture_sets[0].bake.common.resolution = BakeResolution::from_pixels(size).unwrap(); + let started = Instant::now(); + let result = execute(&mut session, "textureSet.meshMap.import", ¶ms).unwrap(); + let elapsed = started.elapsed().as_secs_f64() * 1000.0; + assert_eq!(result["assigned"].as_array().unwrap().len(), files.len()); + assert_eq!(session.doc.baked[&0].maps.len(), 3); + if iteration > 0 { + milliseconds.push(elapsed); + } + } + milliseconds.sort_by(f64::total_cmp); + eprintln!( + "import size={size} tiles={} files={} encoded_bytes={encoded_bytes} median_ms={:.3} min_ms={:.3} max_ms={:.3}", + if tiled { 2 } else { 1 }, + files.len(), + milliseconds[2], + milliseconds[0], + milliseconds[4] + ); + } + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn tiled_import_uses_new_images_when_resource_names_collide() { + let files = ["Plane_ao.1001.png", "Plane_ao.1002.png"]; + let dir = bake_folder("collisions", &files); + let mut session = tiled_session(); + let old_bytes = std::fs::read(dir.join(files[0])).unwrap(); + for name in files { + session.import_resource_bytes(name, old_bytes.clone()).unwrap(); + } + let revision_before = session.revision; + + import(&mut session, &dir, &files.map(|file| (file, None))); + + let baked = &session.doc.baked[&0]; + let ao = &baked.maps[&BakedMap::AmbientOcclusion]; + let width = baked.resolution as usize; + let row = ao.len() / width / 2 * width; + assert!((ao[row + width / 4] - 20.0 / 255.0).abs() < 1e-5); + assert!((ao[row + 3 * width / 4] - 40.0 / 255.0).abs() < 1e-5); + assert_eq!(session.revision, revision_before + 1); + assert_eq!(session.doc.resources.len(), 4); + + session.undo().unwrap(); + assert_eq!(session.doc.resources.len(), 2); + assert_eq!(session.images.len(), 2); + session.redo().unwrap(); + assert_eq!(session.images.len(), 4); + assert!(has_map(&session, 0, BakedMap::AmbientOcclusion)); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn too_many_files_are_rejected_before_reading_any() { + let mut session = session(); + let files = vec![json!({"path": "Ball_ao.png"}); 513]; + let error = execute(&mut session, "textureSet.meshMap.import", &json!({"files": files})).unwrap_err().to_string(); + assert!(error.contains("at most 512 files"), "{error}"); + assert!(session.doc.resources.is_empty()); + assert!(!session.modified); +} + +#[test] +fn tga_maps_survive_undo_redo_and_project_reload() { + let dir = bake_folder("tga", &["Ball_normal.tga", "Base_ao.png"]); + let mut session = session(); + let result = import(&mut session, &dir, &[("Ball_normal.tga", None), ("Base_ao.png", None)]); + assert_eq!(result["assigned"].as_array().unwrap().len(), 2); + assert!(has_map(&session, 0, BakedMap::Normal)); + let image = session.images["Ball_normal.tga"].clone(); + + session.undo().unwrap(); + assert!(session.images.is_empty()); + session.redo().unwrap(); + assert_eq!(session.images["Ball_normal.tga"].rgba, image.rgba); + let reloaded = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + assert_eq!(reloaded.images["Ball_normal.tga"].rgba, image.rgba); + assert_eq!(reloaded.doc.baked, session.doc.baked); + std::fs::remove_dir_all(dir).unwrap(); +} diff --git a/crates/engine/tests/painter_gaps.rs b/crates/engine/tests/it/painter_gaps.rs similarity index 100% rename from crates/engine/tests/painter_gaps.rs rename to crates/engine/tests/it/painter_gaps.rs diff --git a/crates/engine/tests/path_tool.rs b/crates/engine/tests/it/path_tool.rs similarity index 100% rename from crates/engine/tests/path_tool.rs rename to crates/engine/tests/it/path_tool.rs diff --git a/crates/engine/tests/perf.rs b/crates/engine/tests/it/perf.rs similarity index 100% rename from crates/engine/tests/perf.rs rename to crates/engine/tests/it/perf.rs diff --git a/crates/engine/tests/polygon_fill.rs b/crates/engine/tests/it/polygon_fill.rs similarity index 100% rename from crates/engine/tests/polygon_fill.rs rename to crates/engine/tests/it/polygon_fill.rs diff --git a/crates/engine/tests/project_recovery.rs b/crates/engine/tests/it/project_recovery.rs similarity index 100% rename from crates/engine/tests/project_recovery.rs rename to crates/engine/tests/it/project_recovery.rs diff --git a/crates/engine/tests/sample.rs b/crates/engine/tests/it/sample.rs similarity index 100% rename from crates/engine/tests/sample.rs rename to crates/engine/tests/it/sample.rs diff --git a/crates/engine/tests/tools.rs b/crates/engine/tests/it/tools.rs similarity index 100% rename from crates/engine/tests/tools.rs rename to crates/engine/tests/it/tools.rs diff --git a/crates/engine/tests/udim.rs b/crates/engine/tests/it/udim.rs similarity index 100% rename from crates/engine/tests/udim.rs rename to crates/engine/tests/it/udim.rs diff --git a/crates/engine/tests/it/uv_strokes.rs b/crates/engine/tests/it/uv_strokes.rs new file mode 100644 index 00000000..18a33fda --- /dev/null +++ b/crates/engine/tests/it/uv_strokes.rs @@ -0,0 +1,105 @@ +//! Stamping along 2D view strokes: long segments, the carry between samples and per-stamp seeds + +use serde_json::json; +use texturecraft_engine::core::Channel; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +/// Texture size: 1e-4 UV is 0.0256 texels +const RESOLUTION: u32 = 256; + +/// A sphere project painting red with `brush` settings (the UI's 0–100 scales) +fn red_brush_session(brush: serde_json::Value) -> Session { + let mut session = Session::new_project("UV strokes", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, RESOLUTION).unwrap(); + execute(&mut session, "tool.paint", &serde_json::Value::Null).unwrap(); + execute(&mut session, "tool.material", &json!({"channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap(); + execute(&mut session, "tool.brush", &brush).unwrap(); + session +} + +/// The composite base color at texel (`x`, `y`) +fn color_at(session: &Session, x: u32, y: u32) -> [f32; 3] { + session.caches[0].composite.value(Channel::BaseColor, x, y) +} + +/// Whether the composite base color at (`u`, `v`) is the painted red +fn red_at(session: &Session, u: f32, v: f32) -> bool { + let color = color_at(session, (u * RESOLUTION as f32) as u32, (v * RESOLUTION as f32) as u32); + color[0] > 0.85 && color[1] < 0.15 +} + +#[test] +fn a_segment_longer_than_one_stamp_batch_paints_to_its_end() { + // 1e-4 UV between stamps: 0.9 UV is 9000 stamps, past the 4096 of one batch + let mut session = red_brush_session(json!({"size": 1.0, "spacing": 1.0, "hardness": 90})); + + execute(&mut session, "tool.strokeUv", &json!({"points": [[0.05, 0.5], [0.95, 0.5]]})).unwrap(); + + for u in [0.1, 0.5, 0.9] { + assert!(red_at(&session, u, 0.5), "painted at u = {u}"); + } +} + +#[test] +fn a_segment_cut_at_the_stamp_limit_does_not_stamp_the_next_one_backwards() { + // 1e-4 UV between stamps: the 20.5 UV first segment needs 205k stamps and is cut off before reaching the texture + let mut session = red_brush_session(json!({"size": 1.0, "spacing": 1.0, "hardness": 90})); + + execute(&mut session, "tool.strokeUv", &json!({"points": [[-20.0, 0.5], [0.5, 0.5], [0.6, 0.5]]})).unwrap(); + + assert!(red_at(&session, 0.55, 0.5), "the last segment is painted"); + assert!(!red_at(&session, 0.3, 0.5), "nothing is stamped behind the last segment's start"); +} + +#[test] +fn each_sample_of_a_stroke_stamps_new_noise() { + // A 32 texel radius at full spacing: one stamp per sample, each centred on a texel at u = 0.25 and 0.5 + let mut session = red_brush_session(json!({"size": 25.0, "spacing": 100.0, "alpha": "cloud"})); + + execute(&mut session, "tool.strokeUv", &json!({"points": [[0.25, 0.5], [0.5, 0.5]]})).unwrap(); + + let patch = |centre_x: u32| -> Vec<[f32; 3]> { + (centre_x - 16..centre_x + 16).flat_map(|x| (112..144).map(move |y| (x, y))).map(|(x, y)| color_at(&session, x, y)).collect() + }; + let first_stamp = patch(64); + assert!(first_stamp.iter().any(|color| color[0] > 0.5 && color[1] < 0.5), "the first stamp painted"); + assert_ne!(first_stamp, patch(128), "the second sample's stamp has its own noise"); +} + +#[test] +fn a_hostile_segment_stays_bounded() { + // The finest brush the settings allow: 2e-5 UV between stamps + let mut session = red_brush_session(json!({"size": 0.2, "spacing": 1.0})); + + let result = execute(&mut session, "tool.strokeUv", &json!({"points": [[0.0, 0.0], [1e9, 1e9]]})); + + assert!(result.is_ok(), "{result:?}"); +} + +#[test] +fn a_light_pressure_diagonal_reaches_the_far_corner() { + let mut session = red_brush_session(json!({"size": 0.2, "minSize": 0.0, "spacing": 1.0, "hardness": 90})); + + // Half pressure reaches the minimum stamp step: a diagonal needs about 142k stamps + session.begin_stroke_uv([0.0, 0.0].into(), 0.5).unwrap(); + session.continue_stroke_uv([1.0, 1.0].into(), 0.5); + session.end_stroke().unwrap(); + session.update(); + + assert!(red_at(&session, 0.5, 0.5), "the diagonal paints through its midpoint"); + assert!(red_at(&session, 0.97, 0.97), "the diagonal reaches the far corner"); +} + +#[test] +fn decreasing_pressure_does_not_stamp_behind_a_turn() { + let mut session = red_brush_session(json!({"size": 10.0, "minSize": 0.0, "spacing": 100.0, "hardness": 90})); + + session.begin_stroke_uv([0.25, 0.5].into(), 1.0).unwrap(); + session.continue_stroke_uv([0.33, 0.5].into(), 1.0); + session.continue_stroke_uv([0.33, 0.6].into(), 0.1); + session.end_stroke().unwrap(); + session.update(); + + assert!(red_at(&session, 0.33, 0.55), "the new segment is painted"); + assert!(!red_at(&session, 0.33, 0.45), "a smaller step must not stamp behind the turn"); +} diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index aa6722a6..22a17cd5 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -206,6 +206,19 @@ fn polygon_fill_boxes_survive_hostile_params() { } } +/// A small project still gets the production bake defaults; only panic_hunt overrides them. +#[test] +fn new_project_keeps_full_resolution_bake_defaults() { + let s = session(); + assert!(!s.doc.project.texture_sets.is_empty()); + for texture_set in &s.doc.project.texture_sets { + assert_eq!(texture_set.resolution, 256); + assert_eq!(texture_set.bake, texturecraft_engine::core::BakeSettings::default()); + assert_eq!(texture_set.bake.common.output_size(), (2048, 2048)); + assert_eq!(texture_set.bake.maps.ao.parameters.rays.rays, 64); + } +} + /// Every command must return Ok or Err — never panic — for hostile params. #[test] fn panic_hunt() { @@ -223,6 +236,11 @@ fn panic_hunt() { } for p in &hostile { let mut s = session(); + // Match the 256px fixture: otherwise empty/irrelevant bake.run params perform + // repeated 2048px default bakes. Keep every input, ray count and fresh session. + for texture_set in &mut s.doc.project.texture_sets { + texture_set.bake.common.resolution = texturecraft_engine::core::BakeResolution::R256; + } let _ = execute(&mut s, spec.id, p); s.update(); } diff --git a/crates/formats/src/image_res.rs b/crates/formats/src/image_res.rs index 49e1e014..85590d9d 100644 --- a/crates/formats/src/image_res.rs +++ b/crates/formats/src/image_res.rs @@ -21,20 +21,27 @@ pub fn decode_image(bytes: &[u8]) -> Result { /// [`decode_image`] for an image of at most `max_texels` (width × height), checked from the /// header, before any pixel is decoded or allocated. pub fn decode_image_within(bytes: &[u8], max_texels: u64) -> Result { - let reader = + let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().map_err(|e| FormatError::Malformed { kind: "image", msg: e.to_string() })?; - let (w, h) = reader.into_dimensions().map_err(|e| FormatError::Malformed { kind: "image", msg: e.to_string() })?; - if w == 0 || h == 0 || w > MAX_IMAGE_SIZE || h > MAX_IMAGE_SIZE { - return Err(FormatError::TooLarge(format!("image is {w}x{h} (limit {MAX_IMAGE_SIZE})"))); + + // TGA has no magic signature; its decoder validates the header when no format was recognized + let format = reader.format().unwrap_or(image::ImageFormat::Tga); + reader.set_format(format); + + let (width, height) = reader.into_dimensions().map_err(|e| FormatError::Malformed { kind: "image", msg: e.to_string() })?; + if width == 0 || height == 0 || width > MAX_IMAGE_SIZE || height > MAX_IMAGE_SIZE { + return Err(FormatError::TooLarge(format!("image is {width}x{height} (limit {MAX_IMAGE_SIZE})"))); } - if u64::from(w) * u64::from(h) > max_texels { - return Err(FormatError::TooLarge(format!("image is {w}x{h}, more than {max_texels} texels"))); + if u64::from(width) * u64::from(height) > max_texels { + return Err(FormatError::TooLarge(format!("image is {width}x{height}, more than {max_texels} texels"))); } - let img = crate::guard("image", || image::load_from_memory(bytes).map_err(|e| FormatError::Malformed { kind: "image", msg: e.to_string() }))?; - let srgb = !matches!(img, image::DynamicImage::ImageRgb32F(_) | image::DynamicImage::ImageRgba32F(_)); - let f = img.into_rgba32f(); - let (width, height) = f.dimensions(); - let rgba = f.pixels().map(|p| p.0).collect(); + + let image = + crate::guard("image", || image::load_from_memory_with_format(bytes, format).map_err(|e| FormatError::Malformed { kind: "image", msg: e.to_string() }))?; + let srgb = !matches!(image, image::DynamicImage::ImageRgb32F(_) | image::DynamicImage::ImageRgba32F(_)); + let float_image = image.into_rgba32f(); + let (width, height) = float_image.dimensions(); + let rgba = float_image.pixels().map(|pixel| pixel.0).collect(); Ok(DecodedImage { width, height, rgba, srgb }) } @@ -69,6 +76,19 @@ mod tests { assert!(coverage_png(2, 2, &[0], [255; 3]).is_err()); } + #[test] + fn tga_without_a_magic_signature_decodes_within_the_texel_budget() { + let mut bytes = Vec::new(); + image::RgbaImage::from_pixel(4, 4, image::Rgba([128, 51, 255, 255])).write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Tga).unwrap(); + let image = decode_image_within(&bytes, 16).unwrap(); + assert_eq!((image.width, image.height), (4, 4)); + assert!((image.rgba[0][1] - 0.2).abs() < 1e-6); + assert!(image.srgb); + let header = &bytes[..18]; + assert!(matches!(decode_image_within(header, 15), Err(FormatError::TooLarge(_)))); + assert!(decode_image(header).is_err()); + } + #[test] fn decoding_within_a_texel_limit_refuses_big_images_from_the_header() { let png = { diff --git a/crates/geom/src/mesh.rs b/crates/geom/src/mesh.rs index 95d66b4e..917f5838 100644 --- a/crates/geom/src/mesh.rs +++ b/crates/geom/src/mesh.rs @@ -4,6 +4,9 @@ use glam::{Vec2, Vec3, Vec4}; use crate::{GeomError, Result}; +/// An edge by the bits of its two end positions, the lower one first +type EdgePositions = ([u32; 3], [u32; 3]); + /// A contiguous index range drawn with one material. #[derive(Clone, Debug, PartialEq)] pub struct SubMesh { @@ -107,6 +110,47 @@ impl Mesh { .collect() } + /// Edges where the UV layout splits: two triangles meet there in 3D but not in UV space, per material in `0..materials.len().max(1)` + pub fn uv_seam_edges(&self) -> Vec> { + // Signed zero denotes the same position on either side of an imported seam + let bits = |position: Vec3| position.to_array().map(|coordinate| if coordinate == 0.0 { 0 } else { coordinate.to_bits() }); + let mut seams = vec![Vec::new(); self.materials.len().max(1)]; + // Match across materials before grouping the lines for texture-set visibility + let mut sides: std::collections::HashMap> = std::collections::HashMap::new(); + for material in 0..seams.len() { + for triangle in self.triangles_of(material) { + let Some(corners) = self.indices.get(triangle * 3..triangle * 3 + 3) else { continue }; + + for (from, to) in [(corners[0], corners[1]), (corners[1], corners[2]), (corners[2], corners[0])] { + let (Some(from_position), Some(to_position)) = (self.positions.get(from as usize), self.positions.get(to as usize)) else { continue }; + + let (from_bits, to_bits) = (bits(*from_position), bits(*to_position)); + let (edge, pair) = if from_bits <= to_bits { ((from_bits, to_bits), (from, to)) } else { ((to_bits, from_bits), (to, from)) }; + sides.entry(edge).or_default().push((pair.0, pair.1, material)); + } + } + } + + let uv = |index: u32| self.uvs.get(index as usize).copied(); + for pairs in sides.into_values() { + let Some(&(first_from, first_to, _)) = pairs.first() else { continue }; + + if pairs.iter().any(|&(from, to, _)| (uv(from), uv(to)) != (uv(first_from), uv(first_to))) { + for (from, to, material) in pairs { + if let Some(edges) = seams.get_mut(material) { + edges.push((from.min(to), from.max(to))); + } + } + } + } + for edges in &mut seams { + edges.sort_unstable(); + edges.dedup(); + } + + seams + } + /// Material of triangle `t`. pub fn material_of(&self, t: usize) -> Option { let idx = (t * 3) as u32; @@ -433,6 +477,55 @@ mod tests { assert_eq!(crate::primitives::plane(1.0, 2).wire_edges()[0].len(), 12, "a 2×2 grid of quads has 12 edges"); } + #[test] + fn uv_seams_are_where_the_uv_layout_splits() { + let mesh = quad(); + assert_eq!(mesh.uv_seam_edges(), vec![Vec::<(u32, u32)>::new()], "one UV island has no seam"); + + // Vertex 4 copies vertex 0's position with another UV: the diagonal (0, 2) / (4, 2) is cut + let mut seam = mesh.clone(); + seam.positions.push(seam.positions[0]); + seam.normals.push(seam.normals[0]); + seam.tangents.push(seam.tangents[0]); + seam.uvs.push(Vec2::new(0.9, 0.9)); + seam.indices[3] = 4; + assert_eq!(seam.uv_seam_edges(), vec![vec![(0, 2), (2, 4)]]); + + // The same split with the same UV is a hard edge, not a seam + let mut hard = seam.clone(); + hard.uvs[4] = hard.uvs[0]; + assert_eq!(hard.uv_seam_edges(), vec![Vec::<(u32, u32)>::new()]); + } + + #[test] + fn uv_seams_join_positions_with_opposite_signed_zero() { + let mut mesh = quad(); + mesh.positions.push(Vec3::new(-0.0, 0.0, 0.0)); + mesh.normals.push(mesh.normals[0]); + mesh.tangents.push(mesh.tangents[0]); + mesh.uvs.push(Vec2::new(0.9, 0.9)); + mesh.indices[3] = 4; + assert_eq!(mesh.positions[0], mesh.positions[4]); + assert_eq!(mesh.uv_seam_edges(), vec![vec![(0, 2), (2, 4)]]); + } + + #[test] + fn uv_seams_between_materials_belong_to_both_materials() { + let mut mesh = quad(); + mesh.positions.push(mesh.positions[0]); + mesh.normals.push(mesh.normals[0]); + mesh.tangents.push(mesh.tangents[0]); + mesh.uvs.push(Vec2::new(0.9, 0.9)); + mesh.indices[3] = 4; + mesh.materials.push("second".into()); + mesh.submeshes[0].count = 3; + mesh.submeshes.push(SubMesh { name: "second".into(), material: 1, start: 3, count: 3 }); + + assert_eq!(mesh.uv_seam_edges(), vec![vec![(0, 2)], vec![(2, 4)]]); + mesh.uvs[4] = mesh.uvs[0]; + assert_eq!(mesh.uv_seam_edges(), vec![Vec::<(u32, u32)>::new(); 2], "a material boundary alone is not a UV seam"); + } + #[test] fn validate_catches_bad_indices() { let mut m = quad(); diff --git a/crates/render/src/bake_visualization.rs b/crates/render/src/bake_visualization.rs new file mode 100644 index 00000000..8dbc4927 --- /dev/null +++ b/crates/render/src/bake_visualization.rs @@ -0,0 +1,12 @@ +//! What bake mode's 3D view draws while a bake is set up: the high poly, the cage, the UV seams and the low poly + +/// Which parts of the bake setup the 3D view draws +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct BakeVisualization { + pub high_poly: bool, + pub cage: bool, + pub uv_seams: bool, + pub low_poly: bool, + /// Draw the cage, seams and low poly of only this texture set + pub only_set: Option, +} diff --git a/crates/render/src/cage_gpu.rs b/crates/render/src/cage_gpu.rs new file mode 100644 index 00000000..3ed4f13f --- /dev/null +++ b/crates/render/src/cage_gpu.rs @@ -0,0 +1,9 @@ +/// One texture set's cage on the GPU: three corners per triangle and the wireframe's corner pairs +pub(crate) struct CageGpu { + /// Identifies the corners' order and the edges: a new distance with the same topology only rewrites `corners` + pub(crate) topology: u64, + pub(crate) corners: wgpu::Buffer, + pub(crate) corner_count: u32, + pub(crate) edges: wgpu::Buffer, + pub(crate) edge_index_count: u32, +} diff --git a/crates/render/src/high_poly_gpu.rs b/crates/render/src/high_poly_gpu.rs new file mode 100644 index 00000000..97da6861 --- /dev/null +++ b/crates/render/src/high_poly_gpu.rs @@ -0,0 +1,11 @@ +/// The high poly bake mode draws over the low poly +pub(crate) struct HighPolyGpu { + /// Which mesh the buffers hold + pub(crate) id: u64, + pub(crate) vertices: wgpu::Buffer, + pub(crate) vertex_count: usize, + pub(crate) indices: wgpu::Buffer, + pub(crate) index_count: u32, + /// One value per vertex: 1 where the bake's rays miss it (drawn red), 0 where they reach it + pub(crate) missed: wgpu::Buffer, +} diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index c5ca2221..bb0967c7 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -13,12 +13,15 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +pub mod bake_visualization; +mod cage_gpu; pub mod displace; #[cfg(not(target_arch = "wasm32"))] pub mod gpu_bake; pub mod gpu_trace; #[cfg(not(target_arch = "wasm32"))] pub mod headless; +mod high_poly_gpu; pub mod ibl; pub mod mesh_maps; pub mod readback; @@ -26,7 +29,9 @@ pub mod renderer; pub mod set_highlight; mod subdivide; pub mod trace; +mod uv_seam_gpu; +pub use bake_visualization::BakeVisualization; pub use renderer::{COLOR_FORMAT, Frame, MSAA, Renderer, Shade, ViewKind, aux_size, uv_view_scale}; pub use set_highlight::SetHighlight; pub use wgpu; diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index 4ce9dac3..ad2bc2bf 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -30,10 +30,14 @@ use texturecraft_geom::glam::{Mat4, Vec3}; use texturecraft_geom::{Mesh, OrbitCamera}; use texturecraft_texel::TILE; +use crate::bake_visualization::BakeVisualization; +use crate::cage_gpu::CageGpu; use crate::gpu_trace::{Checked, checked}; +use crate::high_poly_gpu::HighPolyGpu; use crate::ibl; use crate::set_highlight::SetHighlight; use crate::subdivide::{self, Vertex}; +use crate::uv_seam_gpu::UvSeamGpu; pub const MSAA: u32 = 4; pub const COLOR_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm; @@ -173,6 +177,8 @@ pub struct Shade { /// Move the surface by the height channel (3D view): a dense copy of the mesh, displaced in /// the vertex shader at the height-to-normal strength. pub displacement: bool, + /// Bake mode's high poly, cage and UV seams over the 3D view + pub bake: Option, } /// The viewport's subsurface scattering approximation: the diffuse lighting wraps around the @@ -259,6 +265,7 @@ impl Default for Shade { sss_blur: None, refraction: false, displacement: false, + bake: None, } } } @@ -530,6 +537,11 @@ pub struct Renderer { wire3d_pipeline: wgpu::RenderPipeline, /// The highlighted set's mesh edges, wider and in the highlight color highlight_pipeline: wgpu::RenderPipeline, + /// Bake mode: the high poly, the cage's faces and wireframe, the low poly's UV seams + bake_high_pipeline: wgpu::RenderPipeline, + cage_pipeline: wgpu::RenderPipeline, + cage_wire_pipeline: wgpu::RenderPipeline, + uv_seam_pipeline: wgpu::RenderPipeline, bg_pipeline: wgpu::RenderPipeline, blit_pipeline: wgpu::RenderPipeline, post_pipeline: wgpu::RenderPipeline, @@ -563,6 +575,10 @@ pub struct Renderer { /// accumulation. content_rev: u64, mesh: Option, + bake_high: Option, + /// Each texture set's cage, by set index + cages: Vec>, + uv_seams: Option, sets: Vec, /// Viewport texture resolution: display textures at 1/2^shift of each set's size (at least /// as reduced as the device's texture limit needs). @@ -808,20 +824,31 @@ fn halton(mut i: u32, base: u32) -> f32 { const CLEAR: wgpu::LoadOp = wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT); +/// Depth bias of the shadow map, per unit of surface slope: keeps lit surfaces from shadowing themselves +const SHADOW_SLOPE_BIAS: f32 = 1.5; + +/// Anisotropic filtering of the texture sets' sampler +const MAX_ANISOTROPY: u16 = 8; + +/// Size of the environment texture before the first environment loads +const PLACEHOLDER_ENV_SIZE: [u32; 2] = [512, 256]; + impl Renderer { /// `target_format`: the format of the pass [`Renderer::blit`] draws into. pub fn new(device: &wgpu::Device, queue: &wgpu::Queue, target_format: wgpu::TextureFormat) -> Renderer { let shader = |label: &str, source: &str| { device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some(label), source: wgpu::ShaderSource::Wgsl(source.into()) }) }; - let module = shader("tc_mesh", concat!(include_str!("shaders/displace.wgsl"), include_str!("shaders/mesh.wgsl"))); + let module = + shader("tc_mesh", concat!(include_str!("shaders/displace.wgsl"), include_str!("shaders/mesh.wgsl"), "\n", include_str!("shaders/bake_view.wgsl"))); let util_module = shader("tc_util", include_str!("shaders/util.wgsl")); let post_module = shader("tc_post", concat!(include_str!("shaders/util.wgsl"), include_str!("shaders/post.wgsl"), include_str!("shaders/fx.wgsl"))); let shadow_module = shader("tc_shadow", concat!(include_str!("shaders/displace.wgsl"), include_str!("shaders/shadow.wgsl"))); - let bgl = |label: &str, entries: &[wgpu::BindGroupLayoutEntry]| { + + let bind_group_layout = |label: &str, entries: &[wgpu::BindGroupLayoutEntry]| { device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some(label), entries }) }; - let globals_bgl = bgl( + let globals_bind_group_layout = bind_group_layout( "tc_globals", &[ uniform_entry(0), @@ -838,44 +865,47 @@ impl Renderer { fragment_entry(4, wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Comparison)), ], ); - // The display textures, the aux texture, the sampler. + // The display textures, the aux texture, the sampler let textures = DisplayKind::ALL.len() as u32 + 1; - // Displacement reads the height (and the sampler) in the vertex shader. - let height = DisplayKind::ALL.iter().position(|k| *k == DisplayKind::Height).unwrap_or(0) as u32; + // Displacement reads the height (and the sampler) in the vertex shader + let height = DisplayKind::ALL.iter().position(|kind| *kind == DisplayKind::Height).unwrap_or(0) as u32; let set_entries: Vec<_> = (0..textures) .map(tex_entry) .chain(std::iter::once(sampler_entry(textures))) - .map(|mut e| { - if e.binding == height || e.binding == textures { - e.visibility |= wgpu::ShaderStages::VERTEX; + .map(|mut entry| { + if entry.binding == height || entry.binding == textures { + entry.visibility |= wgpu::ShaderStages::VERTEX; } - e + entry }) .collect(); - let set_bgl = bgl("tc_set", &set_entries); - let refr_bgl = bgl("tc_refr", &[tex_entry(0)]); - let blit_bgl = bgl("tc_blit", &[tex_entry(0), sampler_entry(1), uniform_entry(2)]); - let mip_bgl = bgl("tc_mip", &[tex_entry(0), sampler_entry(1)]); - let fx_bgl = bgl("tc_fx", &[tex_entry(0), sampler_entry(1), uniform_entry(3), tex_entry(4), tex_entry(5), tex_entry(6)]); - let shadow_bgl = bgl("tc_shadow", &[uniform_entry(0)]); - let pl = |label: &str, groups: &[Option<&wgpu::BindGroupLayout>]| { + let set_bind_group_layout = bind_group_layout("tc_set", &set_entries); + let refraction_bind_group_layout = bind_group_layout("tc_refr", &[tex_entry(0)]); + let blit_bind_group_layout = bind_group_layout("tc_blit", &[tex_entry(0), sampler_entry(1), uniform_entry(2)]); + let mip_bind_group_layout = bind_group_layout("tc_mip", &[tex_entry(0), sampler_entry(1)]); + let effect_bind_group_layout = + bind_group_layout("tc_fx", &[tex_entry(0), sampler_entry(1), uniform_entry(3), tex_entry(4), tex_entry(5), tex_entry(6)]); + let shadow_bind_group_layout = bind_group_layout("tc_shadow", &[uniform_entry(0)]); + + let pipeline_layout = |label: &str, groups: &[Option<&wgpu::BindGroupLayout>]| { device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some(label), bind_group_layouts: groups, immediate_size: 0 }) }; - let layout = pl("tc_uv", &[Some(&globals_bgl), Some(&set_bgl)]); - let mesh_layout = pl("tc_mesh", &[Some(&globals_bgl), Some(&set_bgl), Some(&refr_bgl)]); - let bg_layout = pl("tc_bg", &[Some(&globals_bgl)]); - let blit_layout = pl("tc_blit", &[Some(&blit_bgl)]); - let fx_layout = pl("tc_fx", &[Some(&fx_bgl)]); - let shadow_layout = pl("tc_shadow", &[Some(&shadow_bgl), Some(&set_bgl)]); - let vb = [Some(wgpu::VertexBufferLayout { + let layout = pipeline_layout("tc_uv", &[Some(&globals_bind_group_layout), Some(&set_bind_group_layout)]); + let mesh_layout = pipeline_layout("tc_mesh", &[Some(&globals_bind_group_layout), Some(&set_bind_group_layout), Some(&refraction_bind_group_layout)]); + let background_layout = pipeline_layout("tc_bg", &[Some(&globals_bind_group_layout)]); + let blit_layout = pipeline_layout("tc_blit", &[Some(&blit_bind_group_layout)]); + let effect_layout = pipeline_layout("tc_fx", &[Some(&effect_bind_group_layout)]); + let shadow_layout = pipeline_layout("tc_shadow", &[Some(&shadow_bind_group_layout), Some(&set_bind_group_layout)]); + + let vertex_layout = [Some(wgpu::VertexBufferLayout { array_stride: std::mem::size_of::() as u64, step_mode: wgpu::VertexStepMode::Vertex, attributes: &wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x3, 2 => Float32x4, 3 => Float32x2], })]; - // shortcut: the RGBA8 fallback clips highlights above 1 and bands in the darks; encode - // (e.g. RGBM) if WebGL2 without float color buffers turns out to matter. + + // shortcut: the RGBA8 fallback clips highlights above 1 and bands in the darks; encode (e.g. RGBM) if WebGL2 without float color buffers turns out to matter let hdr_format = if hdr_renderable(device) { HDR_FORMAT } else { COLOR_FORMAT }; - let hdr = |fs, blend| Some((fs, hdr_format, blend)); + let hdr_target = |fragment_entry_point, blend| Some((fragment_entry_point, hdr_format, blend)); let always = || Some(depth_state(false, wgpu::CompareFunction::Always)); let mesh_pipeline = pipeline( device, @@ -883,8 +913,8 @@ impl Renderer { &mesh_layout, &module, "vs_mesh", - &vb, - hdr("fs_mesh", None), + &vertex_layout, + hdr_target("fs_mesh", None), MSAA, Some(depth_state(true, wgpu::CompareFunction::Less)), ); @@ -894,31 +924,103 @@ impl Renderer { &mesh_layout, &module, "vs_mesh", - &vb, - hdr("fs_opaque", None), + &vertex_layout, + hdr_target("fs_opaque", None), MSAA, Some(depth_state(true, wgpu::CompareFunction::Less)), ); - let uv_pipeline = pipeline(device, "tc_uv", &layout, &module, "vs_uv", &vb, hdr("fs_uv", None), MSAA, always()); + let uv_pipeline = pipeline(device, "tc_uv", &layout, &module, "vs_uv", &vertex_layout, hdr_target("fs_uv", None), MSAA, always()); let blend = Some(wgpu::BlendState::ALPHA_BLENDING); - let wire_pipeline = pipeline(device, "tc_wire", &layout, &module, "vs_uv", &vb, hdr("fs_wire", blend), MSAA, always()); + let wire_pipeline = pipeline(device, "tc_wire", &layout, &module, "vs_uv", &vertex_layout, hdr_target("fs_wire", blend), MSAA, always()); let wire3d_depth = Some(depth_state(false, wgpu::CompareFunction::LessEqual)); - let wire3d_pipeline = pipeline(device, "tc_wire3d", &layout, &module, "vs_wire3d", &vb, hdr("fs_wire3d", blend), MSAA, wire3d_depth.clone()); - let highlight_pipeline = - pipeline(device, "tc_highlight", &layout, &module, "vs_wire_highlight", &vb, hdr("fs_wire_highlight", blend), MSAA, wire3d_depth); - let bg_pipeline = pipeline(device, "tc_bg", &bg_layout, &module, "vs_bg", &[], hdr("fs_bg", None), MSAA, always()); + let wire3d_pipeline = + pipeline(device, "tc_wire3d", &layout, &module, "vs_wire3d", &vertex_layout, hdr_target("fs_wire3d", blend), MSAA, wire3d_depth.clone()); + let highlight_pipeline = pipeline( + device, + "tc_highlight", + &layout, + &module, + "vs_wire_highlight", + &vertex_layout, + hdr_target("fs_wire_highlight", blend), + MSAA, + wire3d_depth.clone(), + ); + + let [mesh_vertex_layout] = vertex_layout.clone(); + let high_layout = [ + mesh_vertex_layout, + Some(wgpu::VertexBufferLayout { + array_stride: std::mem::size_of::() as u64, + step_mode: wgpu::VertexStepMode::Vertex, + attributes: &wgpu::vertex_attr_array![4 => Float32], + }), + ]; + let bake_high_pipeline = pipeline( + device, + "tc_bake_high", + &background_layout, + &module, + "vs_bake_high", + &high_layout, + hdr_target("fs_bake_high", None), + MSAA, + Some(depth_state(true, wgpu::CompareFunction::Less)), + ); + let corner_layout = [Some(wgpu::VertexBufferLayout { + array_stride: std::mem::size_of::<[f32; 3]>() as u64, + step_mode: wgpu::VertexStepMode::Vertex, + attributes: &wgpu::vertex_attr_array![0 => Float32x3], + })]; + let cage_pipeline = pipeline( + device, + "tc_cage", + &background_layout, + &module, + "vs_bake_cage", + &corner_layout, + hdr_target("fs_bake_cage", blend), + MSAA, + wire3d_depth.clone(), + ); + let cage_wire_pipeline = pipeline( + device, + "tc_cage_wire", + &background_layout, + &module, + "vs_bake_cage_wire", + &corner_layout, + hdr_target("fs_wire_bake_cage", blend), + MSAA, + wire3d_depth.clone(), + ); + let uv_seam_pipeline = + pipeline(device, "tc_uv_seam", &layout, &module, "vs_wire3d", &vertex_layout, hdr_target("fs_wire_uv_seam", blend), MSAA, wire3d_depth.clone()); + let bg_pipeline = pipeline(device, "tc_bg", &background_layout, &module, "vs_bg", &[], hdr_target("fs_bg", None), MSAA, always()); let blit_pipeline = pipeline(device, "tc_blit", &blit_layout, &util_module, "vs_blit", &[], Some(("fs_blit", target_format, None)), 1, None); - let post_pipeline = pipeline(device, "tc_post", &fx_layout, &post_module, "vs_full", &[], Some(("fs_post", COLOR_FORMAT, None)), 1, None); - let bloom_pipelines = [("fs_bloom_pre", None), ("fs_bloom_down", None), ("fs_bloom_up", Some(ADDITIVE))] - .map(|(fs, blend)| pipeline(device, "tc_bloom", &fx_layout, &post_module, "vs_full", &[], hdr(fs, blend), 1, None)); - let gbuf_pipeline = - pipeline(device, "tc_gbuf", &mesh_layout, &module, "vs_mesh", &vb, hdr("fs_gbuf", None), 1, Some(depth_state(true, wgpu::CompareFunction::Less))); - let sss_pipelines = ["fs_sss_h", "fs_sss_v"].map(|fs| pipeline(device, "tc_sss", &fx_layout, &post_module, "vs_full", &[], hdr(fs, None), 1, None)); - let dof_pipeline = pipeline(device, "tc_dof", &fx_layout, &post_module, "vs_full", &[], hdr("fs_dof", None), 1, None); + let post_pipeline = pipeline(device, "tc_post", &effect_layout, &post_module, "vs_full", &[], Some(("fs_post", COLOR_FORMAT, None)), 1, None); + let bloom_pipelines = [("fs_bloom_pre", None), ("fs_bloom_down", None), ("fs_bloom_up", Some(ADDITIVE))].map(|(fragment_entry_point, blend)| { + pipeline(device, "tc_bloom", &effect_layout, &post_module, "vs_full", &[], hdr_target(fragment_entry_point, blend), 1, None) + }); + let gbuffer_pipeline = pipeline( + device, + "tc_gbuf", + &mesh_layout, + &module, + "vs_mesh", + &vertex_layout, + hdr_target("fs_gbuf", None), + 1, + Some(depth_state(true, wgpu::CompareFunction::Less)), + ); + let sss_pipelines = ["fs_sss_h", "fs_sss_v"].map(|fragment_entry_point| { + pipeline(device, "tc_sss", &effect_layout, &post_module, "vs_full", &[], hdr_target(fragment_entry_point, None), 1, None) + }); + let dof_pipeline = pipeline(device, "tc_dof", &effect_layout, &post_module, "vs_full", &[], hdr_target("fs_dof", None), 1, None); let dof_target = Some(wgpu::ColorTargetState { format: hdr_format, blend: None, write_mask: wgpu::ColorWrites::ALL }); let dof_gather_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { label: Some("tc_dof_gather"), - layout: Some(&fx_layout), + layout: Some(&effect_layout), vertex: wgpu::VertexState { module: &post_module, entry_point: Some("vs_full"), buffers: &[], compilation_options: Default::default() }, primitive: wgpu::PrimitiveState::default(), depth_stencil: None, @@ -932,20 +1034,23 @@ impl Renderer { multiview_mask: None, cache: None, }); + let shadow_depth = wgpu::DepthStencilState { - bias: wgpu::DepthBiasState { constant: 0, slope_scale: 1.5, clamp: 0.0 }, + bias: wgpu::DepthBiasState { constant: 0, slope_scale: SHADOW_SLOPE_BIAS, clamp: 0.0 }, ..depth_state(true, wgpu::CompareFunction::Less) }; - let shadow_pipeline = pipeline(device, "tc_shadow", &shadow_layout, &shadow_module, "vs_shadow", &vb, None, 1, Some(shadow_depth)); - // accum = hdr * k + accum * (1 - k) with k = 1 / (sample + 1): a running average. + let shadow_pipeline = pipeline(device, "tc_shadow", &shadow_layout, &shadow_module, "vs_shadow", &vertex_layout, None, 1, Some(shadow_depth)); + + // accum = hdr_target * k + accum * (1 - k) with k = 1 / (sample + 1): a running average let average = wgpu::BlendComponent { src_factor: wgpu::BlendFactor::Constant, dst_factor: wgpu::BlendFactor::OneMinusConstant, operation: wgpu::BlendOperation::Add, }; - let accum_layout = pl("tc_accum", &[Some(&mip_bgl)]); + let accum_layout = pipeline_layout("tc_accum", &[Some(&mip_bind_group_layout)]); let accum_blend = Some(wgpu::BlendState { color: average, alpha: average }); - let accum_pipeline = pipeline(device, "tc_accum", &accum_layout, &util_module, "vs_full", &[], hdr("fs_copy", accum_blend), 1, None); + let accum_pipeline = pipeline(device, "tc_accum", &accum_layout, &util_module, "vs_full", &[], hdr_target("fs_copy", accum_blend), 1, None); + let sampler = device.create_sampler(&wgpu::SamplerDescriptor { label: Some("tc_tex"), address_mode_u: wgpu::AddressMode::ClampToEdge, @@ -953,7 +1058,7 @@ impl Renderer { mag_filter: wgpu::FilterMode::Linear, min_filter: wgpu::FilterMode::Linear, mipmap_filter: wgpu::MipmapFilterMode::Linear, - anisotropy_clamp: 8, + anisotropy_clamp: MAX_ANISOTROPY, ..Default::default() }); let env_sampler = device.create_sampler(&wgpu::SamplerDescriptor { @@ -972,7 +1077,8 @@ impl Renderer { compare: Some(wgpu::CompareFunction::LessEqual), ..Default::default() }); - let shadow_buf = device.create_buffer(&wgpu::BufferDescriptor { + + let shadow_buffer = device.create_buffer(&wgpu::BufferDescriptor { label: Some("tc_shadow"), size: std::mem::size_of::<[[f32; 4]; 5]>() as u64, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, @@ -986,39 +1092,45 @@ impl Renderer { vp: Mat4::IDENTITY, bg: device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("tc_shadow"), - layout: &shadow_bgl, - entries: &[wgpu::BindGroupEntry { binding: 0, resource: shadow_buf.as_entire_binding() }], + layout: &shadow_bind_group_layout, + entries: &[wgpu::BindGroupEntry { binding: 0, resource: shadow_buffer.as_entire_binding() }], }), - buf: shadow_buf, + buf: shadow_buffer, }; + let black = Tex::new(device, "tc_black", 1, 1, COLOR_FORMAT, 1).view; - let refr_black = device.create_bind_group(&wgpu::BindGroupDescriptor { + let refraction_black = device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("tc_refr_black"), - layout: &refr_bgl, + layout: &refraction_bind_group_layout, entries: &[wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&black) }], }); - let env = Tex::new(device, "tc_env", 512, 256, wgpu::TextureFormat::Rgba16Float, ENV_LEVELS); - let mut r = Renderer { + let env = Tex::new(device, "tc_env", PLACEHOLDER_ENV_SIZE[0], PLACEHOLDER_ENV_SIZE[1], wgpu::TextureFormat::Rgba16Float, ENV_LEVELS); + + let mut renderer = Renderer { target_format, hdr_format, - globals_bgl, - set_bgl, - blit_bgl, - mip_bgl, - fx_bgl, - refr_bgl, - refr_black, + globals_bgl: globals_bind_group_layout, + set_bgl: set_bind_group_layout, + blit_bgl: blit_bind_group_layout, + mip_bgl: mip_bind_group_layout, + fx_bgl: effect_bind_group_layout, + refr_bgl: refraction_bind_group_layout, + refr_black: refraction_black, mesh_pipeline, opaque_pipeline, uv_pipeline, wire_pipeline, wire3d_pipeline, highlight_pipeline, + bake_high_pipeline, + cage_pipeline, + cage_wire_pipeline, + uv_seam_pipeline, bg_pipeline, blit_pipeline, post_pipeline, bloom_pipelines, - gbuf_pipeline, + gbuf_pipeline: gbuffer_pipeline, sss_pipelines, dof_gather_pipeline, dof_pipeline, @@ -1038,13 +1150,16 @@ impl Renderer { sh: [[0.0; 4]; 9], content_rev: 0, mesh: None, + bake_high: None, + cages: Vec::new(), + uv_seams: None, sets: Vec::new(), display_shift: 0, material_sets: Vec::new(), views: HashMap::new(), }; - r.set_environment(device, queue, "Studio Soft", None); - r + renderer.set_environment(device, queue, "Studio Soft", None); + renderer } pub fn environment_name(&self) -> &str { @@ -1124,6 +1239,94 @@ impl Renderer { self.content_rev += 1; } + /// Upload the high poly when `id` changes; remove it on `None` or when its buffers exceed the device limit + pub fn set_bake_high(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, mesh: Option<&Mesh>, id: u64) -> Result<(), String> { + if self.bake_high.as_ref().map(|high| high.id) == mesh.map(|_| id) { + return Ok(()); + } + + self.bake_high = None; + self.content_rev += 1; + let Some(mesh) = mesh else { return Ok(()) }; + + // Imported high polys can outgrow a viewport buffer even when the CPU baker accepts them + let limit = device.limits().max_buffer_size; + let buffers = [ + (mesh.positions.len(), std::mem::size_of::()), + (mesh.indices.len(), std::mem::size_of::()), + (mesh.positions.len(), std::mem::size_of::()), + ]; + if mesh.indices.len() > u32::MAX as usize || buffers.iter().any(|&(count, stride)| count.checked_mul(stride).is_none_or(|bytes| bytes as u64 > limit)) { + return Err(format!("High-poly visualization exceeds the GPU buffer limit ({limit} bytes). Use a smaller preview mesh or hide the high poly.")); + } + + self.bake_high = Some(HighPolyGpu { + id, + vertices: upload_buffer(device, queue, "tc_bake_high_vb", bytemuck::cast_slice(&subdivide::vertices(mesh)), wgpu::BufferUsages::VERTEX), + vertex_count: mesh.positions.len(), + indices: upload_buffer(device, queue, "tc_bake_high_ib", bytemuck::cast_slice(&mesh.indices), wgpu::BufferUsages::INDEX), + index_count: mesh.indices.len() as u32, + missed: upload_buffer(device, queue, "tc_bake_high_missed", bytemuck::cast_slice(&vec![0f32; mesh.positions.len()]), wgpu::BufferUsages::VERTEX), + }); + Ok(()) + } + + /// Which vertices of high poly `id` the bake's rays miss (1) or reach (0); ignored for another mesh or vertex count + pub fn set_bake_high_missed(&mut self, queue: &wgpu::Queue, id: u64, missed: &[f32]) { + let Some(high) = self.bake_high.as_ref().filter(|high| high.id == id && high.vertex_count == missed.len()) else { return }; + + queue.write_buffer(&high.missed, 0, bytemuck::cast_slice(missed)); + self.content_rev += 1; + } + + /// Texture set `texture_set`'s cage: `corners` three per triangle and `edges` as corner pairs; `None` removes it. The same `topology` as before only rewrites the corners + pub fn set_bake_cage(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, texture_set: usize, cage: Option<(&[Vec3], &[[u32; 2]])>, topology: u64) { + if self.cages.len() <= texture_set { + self.cages.resize_with(texture_set + 1, || None); + } + let Some(slot) = self.cages.get_mut(texture_set) else { return }; + + match (cage, slot.as_mut()) { + (None, _) => *slot = None, + (Some((corners, _)), Some(gpu)) if gpu.topology == topology && gpu.corner_count as usize == corners.len() => { + queue.write_buffer(&gpu.corners, 0, bytemuck::cast_slice(corners)); + } + (Some((corners, edges)), _) => { + *slot = Some(CageGpu { + topology, + corners: upload_buffer(device, queue, "tc_cage_vb", bytemuck::cast_slice(corners), wgpu::BufferUsages::VERTEX), + corner_count: corners.len() as u32, + edges: upload_buffer(device, queue, "tc_cage_ib", bytemuck::cast_slice(edges), wgpu::BufferUsages::INDEX), + edge_index_count: (edges.len() * 2) as u32, + }); + } + } + self.content_rev += 1; + } + + /// Forget the cages of texture sets from `count` on (sets that were removed) + pub fn truncate_bake_cages(&mut self, count: usize) { + if self.cages.len() > count { + self.cages.truncate(count); + self.content_rev += 1; + } + } + + /// The low poly's UV seams as vertex pairs per material ([`Mesh::uv_seam_edges`]) for mesh `mesh_id` + pub fn set_uv_seams(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, mesh_id: u64, seams: &[Vec<(u32, u32)>]) { + let mut line_indices: Vec = Vec::new(); + let mut line_draws = Vec::new(); + for (material, edges) in seams.iter().enumerate() { + let start = line_indices.len() as u32; + line_indices.extend(edges.iter().flat_map(|&(from, to)| [from, to])); + line_draws.push((start, line_indices.len() as u32 - start, material)); + } + + let lines = upload_buffer(device, queue, "tc_uv_seams", bytemuck::cast_slice(&line_indices), wgpu::BufferUsages::INDEX); + self.uv_seams = Some(UvSeamGpu { mesh_id, lines, line_draws }); + self.content_rev += 1; + } + /// Build the mesh's dense copy for displacement (once per mesh). fn ensure_dense(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) { let Some(m) = self.mesh.as_mut() else { return }; @@ -1889,30 +2092,30 @@ impl Renderer { self.draw_scene(encoder, v, resolve, globals_bg, frame, pipe, wire, highlight, refr); } - /// One scene pass: background, then the mesh with `pipe`, the wireframe with `wire` and one set's highlighted edges with `highlight` + /// One scene pass: background, then the mesh with `mesh_pipeline`, the wireframe with `wire` and one set's highlighted edges with `highlight` #[allow(clippy::too_many_arguments)] fn draw_scene( &self, encoder: &mut wgpu::CommandEncoder, - v: &ViewTargets, + targets: &ViewTargets, resolve: &wgpu::TextureView, - globals_bg: &wgpu::BindGroup, + globals_bind_group: &wgpu::BindGroup, frame: &Frame, - pipe: &wgpu::RenderPipeline, + mesh_pipeline: &wgpu::RenderPipeline, wire: Option<&wgpu::RenderPipeline>, highlight: Option<(&wgpu::RenderPipeline, usize)>, - refr: &wgpu::BindGroup, + refraction_source: &wgpu::BindGroup, ) { let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: Some("tc_view"), color_attachments: &[Some(wgpu::RenderPassColorAttachment { - view: &v.msaa, + view: &targets.msaa, resolve_target: Some(resolve), depth_slice: None, ops: wgpu::Operations { load: CLEAR, store: wgpu::StoreOp::Discard }, })], depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { - view: &v.depth, + view: &targets.depth, depth_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Clear(1.0), store: wgpu::StoreOp::Discard }), stencil_ops: None, }), @@ -1920,33 +2123,87 @@ impl Renderer { occlusion_query_set: None, multiview_mask: None, }); - pass.set_bind_group(0, globals_bg, &[]); + pass.set_bind_group(0, globals_bind_group, &[]); pass.set_pipeline(&self.bg_pipeline); pass.draw(0..3, 0..1); - let Some(m) = &self.mesh else { return }; - let uv_ts = match frame.kind { + let Some(mesh) = &self.mesh else { return }; + + let uv_set = match frame.kind { ViewKind::Scene => None, ViewKind::Uv { ts, .. } => Some(ts), }; - pass.set_bind_group(2, refr, &[]); - let geo = self.geometry(m, frame); + pass.set_bind_group(2, refraction_source, &[]); + let geometry = self.geometry(mesh, frame); + let bake = frame.shade.bake.filter(|_| uv_set.is_none()); + let low_poly_shown = bake.is_none_or(|bake| bake.low_poly); + let low_poly_set = bake.and_then(|bake| bake.only_set).or(uv_set); + let (highlight, highlight_set) = highlight.filter(|(_, set)| low_poly_shown && low_poly_set.is_none_or(|only| only == *set)).unzip(); + // The wireframe and the highlight draw the mesh's own edges (displaced in the vertex shader too) - let (highlight, highlight_set) = highlight.unzip(); let passes = [ - (Some(pipe), &geo.vb, &geo.ib, &geo.draws, uv_ts, 1), - (wire, &m.geo.vb, &m.lines, &m.line_draws, uv_ts, 1), - (highlight, &m.geo.vb, &m.lines, &m.line_draws, highlight_set, HIGHLIGHT_SHIFTS), + (low_poly_shown.then_some(mesh_pipeline), &geometry.vb, &geometry.ib, &geometry.draws, low_poly_set, 1), + (wire.filter(|_| low_poly_shown), &mesh.geo.vb, &mesh.lines, &mesh.line_draws, low_poly_set, 1), + (highlight, &mesh.geo.vb, &mesh.lines, &mesh.line_draws, highlight_set, HIGHLIGHT_SHIFTS), ]; - for (pipe, vb, ib, ranges, only, instances) in passes { - let Some(pipe) = pipe else { continue }; - pass.set_pipeline(pipe); - pass.set_vertex_buffer(0, vb.slice(..)); - pass.set_index_buffer(ib.slice(..), wgpu::IndexFormat::Uint32); - for (range, set) in self.drawable(ranges, &frame.visible, only) { + for (pipeline, vertices, indices, ranges, only_set, instances) in passes { + let Some(pipeline) = pipeline else { continue }; + + pass.set_pipeline(pipeline); + pass.set_vertex_buffer(0, vertices.slice(..)); + pass.set_index_buffer(indices.slice(..), wgpu::IndexFormat::Uint32); + for (range, set) in self.drawable(ranges, &frame.visible, only_set) { pass.set_bind_group(1, &set.bind_group, &[]); pass.draw_indexed(range, 0, 0..instances); } } + + if let Some(bake) = bake { + self.draw_bake(&mut pass, mesh, frame, bake); + } + } + + /// Bake mode's high poly, UV seams and cages over the low poly `low_poly` + fn draw_bake(&self, pass: &mut wgpu::RenderPass<'_>, low_poly: &MeshGpu, frame: &Frame, bake: BakeVisualization) { + if bake.high_poly + && let Some(high) = &self.bake_high + { + pass.set_pipeline(&self.bake_high_pipeline); + pass.set_vertex_buffer(0, high.vertices.slice(..)); + pass.set_vertex_buffer(1, high.missed.slice(..)); + pass.set_index_buffer(high.indices.slice(..), wgpu::IndexFormat::Uint32); + pass.draw_indexed(0..high.index_count, 0, 0..1); + } + + if bake.uv_seams + && let Some(seams) = self.uv_seams.as_ref().filter(|seams| seams.mesh_id == low_poly.id) + { + pass.set_pipeline(&self.uv_seam_pipeline); + pass.set_vertex_buffer(0, low_poly.geo.vb.slice(..)); + pass.set_index_buffer(seams.lines.slice(..), wgpu::IndexFormat::Uint32); + for (range, set) in self.drawable(&seams.line_draws, &frame.visible, bake.only_set) { + pass.set_bind_group(1, &set.bind_group, &[]); + pass.draw_indexed(range, 0, 0..1); + } + } + + if !bake.cage { + return; + } + + let shown = |texture_set: usize| bake.only_set.is_none_or(|only| only == texture_set) && frame.visible.get(texture_set).copied().unwrap_or(true); + let cages = || self.cages.iter().enumerate().filter(move |(texture_set, _)| shown(*texture_set)).filter_map(|(_, cage)| cage.as_ref()); + // The translucent faces first, then the wireframe over them + pass.set_pipeline(&self.cage_pipeline); + for cage in cages() { + pass.set_vertex_buffer(0, cage.corners.slice(..)); + pass.draw(0..cage.corner_count, 0..1); + } + pass.set_pipeline(&self.cage_wire_pipeline); + for cage in cages() { + pass.set_vertex_buffer(0, cage.corners.slice(..)); + pass.set_index_buffer(cage.edges.slice(..), wgpu::IndexFormat::Uint32); + pass.draw_indexed(0..cage.edge_index_count, 0, 0..1); + } } /// Draw view `id` into the current pass at `rect` (target pixels: x, y, w, h). diff --git a/crates/render/src/shaders/bake_view.wgsl b/crates/render/src/shaders/bake_view.wgsl new file mode 100644 index 00000000..1985f980 --- /dev/null +++ b/crates/render/src/shaders/bake_view.wgsl @@ -0,0 +1,88 @@ +// Bake mode's 3D view: the high poly, the cage around the low poly and the UV seams + +struct BakeViewOut { + @builtin(position) clip: vec4, + @location(0) world_position: vec3, + @location(1) normal: vec3, + // 1 where the bake's rays miss the high poly, 0 where they reach it + @location(2) missed: f32, +}; + +const HIGH_POLY_COLOR: vec3 = vec3(0.10, 0.36, 0.56); +const MISSED_COLOR: vec3 = vec3(0.80, 0.01, 0.01); +const CAGE_COLOR: vec3 = vec3(0.55, 0.42, 0.26); +const CAGE_OPACITY: f32 = 0.16; +const CAGE_WIRE_COLOR: vec4 = vec4(0.75, 0.62, 0.42, 0.7); +const UV_SEAM_COLOR: vec4 = vec4(0.20, 0.85, 0.30, 1.0); + +// Brightness of surfaces seen edge-on; facing the camera adds the rest +const HEADLIGHT_AMBIENT: f32 = 0.3; + +// Fractions of the way to the camera each vertex moves, so near-coincident surfaces and lines draw in a fixed order +const HIGH_POLY_PULL_TOWARD_EYE: f32 = 0.001; +const CAGE_WIRE_PULL_TOWARD_EYE: f32 = 0.002; + +// Lit from the camera: surfaces facing it are brightest +fn headlight(color: vec3, normal: vec3, world_position: vec3) -> vec3 { + let facing = abs(dot(normal, normalize(g.eye.xyz - world_position))); + return color * (HEADLIGHT_AMBIENT + (1.0 - HEADLIGHT_AMBIENT) * facing); +} + +fn pulled_toward_eye(world_position: vec3, fraction: f32) -> vec4 { + return g.view_proj * vec4(world_position + (g.eye.xyz - world_position) * fraction, 1.0); +} + +// Pulled slightly toward the camera: where the high poly nearly touches the low poly it shows instead of flickering with it +@vertex +fn vs_bake_high(@location(0) position: vec3, @location(1) normal: vec3, @location(4) missed: f32) -> BakeViewOut { + var out: BakeViewOut; + out.clip = pulled_toward_eye(position, HIGH_POLY_PULL_TOWARD_EYE); + out.world_position = position; + out.normal = normal; + out.missed = missed; + return out; +} + +@fragment +fn fs_bake_high(surface: BakeViewOut) -> @location(0) vec4 { + let color = mix(HIGH_POLY_COLOR, MISSED_COLOR, surface.missed); + return vec4(headlight(color, normalize(surface.normal), surface.world_position), 1.0); +} + +@vertex +fn vs_bake_cage(@location(0) position: vec3) -> BakeViewOut { + var out: BakeViewOut; + out.clip = g.view_proj * vec4(position, 1.0); + out.world_position = position; + out.normal = vec3(0.0, 1.0, 0.0); + out.missed = 0.0; + return out; +} + +// The cage's own faces: their normal comes from the screen-space change of the position +@fragment +fn fs_bake_cage(surface: BakeViewOut) -> @location(0) vec4 { + let face_normal = normalize(cross(dpdx(surface.world_position), dpdy(surface.world_position))); + return vec4(headlight(CAGE_COLOR, face_normal, surface.world_position), CAGE_OPACITY); +} + +// Pulled toward the camera like the 3D wireframe, so the lines win against the cage's faces +@vertex +fn vs_bake_cage_wire(@location(0) position: vec3) -> BakeViewOut { + var out: BakeViewOut; + out.clip = pulled_toward_eye(position, CAGE_WIRE_PULL_TOWARD_EYE); + out.world_position = position; + out.normal = vec3(0.0, 1.0, 0.0); + out.missed = 0.0; + return out; +} + +@fragment +fn fs_wire_bake_cage(surface: BakeViewOut) -> @location(0) vec4 { + return CAGE_WIRE_COLOR; +} + +@fragment +fn fs_wire_uv_seam(surface: VOut) -> @location(0) vec4 { + return UV_SEAM_COLOR; +} diff --git a/crates/render/src/uv_seam_gpu.rs b/crates/render/src/uv_seam_gpu.rs new file mode 100644 index 00000000..0ac80dc9 --- /dev/null +++ b/crates/render/src/uv_seam_gpu.rs @@ -0,0 +1,8 @@ +/// The low poly's UV seams as a line list over its vertex buffer +pub(crate) struct UvSeamGpu { + /// The low-poly mesh the lines belong to + pub(crate) mesh_id: u64, + pub(crate) lines: wgpu::Buffer, + /// (first index, count, material) per material + pub(crate) line_draws: Vec<(u32, u32, usize)>, +} diff --git a/crates/render/tests/headless.rs b/crates/render/tests/headless.rs index 864c70c3..84a6e0e2 100644 --- a/crates/render/tests/headless.rs +++ b/crates/render/tests/headless.rs @@ -1,8 +1,9 @@ use texturecraft_compose::{DisplayKind, ImageRes}; +use texturecraft_geom::glam::Vec3; use texturecraft_geom::{OrbitCamera, primitives}; use texturecraft_render::headless::Headless; use texturecraft_render::renderer::TAA_SAMPLES; -use texturecraft_render::{Frame, Shade, ViewKind}; +use texturecraft_render::{BakeVisualization, Frame, Shade, ViewKind}; /// The UI's key light (`viewport::shade`). const LIGHT: [f32; 4] = [0.5, 0.8, 0.4, 2.5]; @@ -42,14 +43,18 @@ impl Img { } } +/// The id `setup` uploads the material ball under +const MESH_ID: u64 = 1; + /// A headless renderer with the material ball framed in a 480×360 view (None without a GPU). fn setup() -> Option<(Headless, Frame)> { let Ok(mut h) = Headless::new() else { eprintln!("skipping: no GPU adapter"); return None; }; + eprintln!("headless adapter: {:?}", h.device.adapter_info()); let mesh = primitives::material_ball(); - h.renderer.set_mesh(&h.device, &h.queue, &mesh, 1); + h.renderer.set_mesh(&h.device, &h.queue, &mesh, MESH_ID); h.renderer.set_texture_sets(&h.device, &h.queue, &[((256, 256), 0), ((256, 256), 1)], 2); let mut cam = OrbitCamera { yaw: 0.6, pitch: 0.25, ..OrbitCamera::default() }; let (lo, hi) = mesh.bounds(); @@ -220,6 +225,122 @@ fn wireframe_3d_overlays_the_mesh() { assert_eq!(a.at(5, 5), b.at(5, 5), "the background stays clean"); } +#[test] +fn bake_visualization_draws_the_high_poly_and_the_cage() { + // A high poly inside the material ball, a cage around it, and how far a color must lead the others to count as that color + const HIGH_POLY_RADIUS_PER_SIZE: f32 = 0.3; + const CAGE_SCALE: f32 = 2.5; + const HIGH_POLY_ID: u64 = 7; + const CAGE_TOPOLOGY: u64 = 1; + const CAGE_EDGES: [[u32; 2]; 2] = [[0, 1], [1, 2]]; + const COLOR_LEAD: i32 = 30; + + let Some((mut h, frame)) = setup() else { return }; + let ball = primitives::material_ball(); + let (low_min, low_max) = ball.bounds(); + let ball_center = (low_min + low_max) * 0.5; + let mut high = primitives::sphere((low_max - low_min).max_element() * HIGH_POLY_RADIUS_PER_SIZE, 32, 16); + for position in &mut high.positions { + *position += ball_center; + } + h.renderer.set_bake_high(&h.device, &h.queue, Some(&high), HIGH_POLY_ID).unwrap(); + let corners: Vec = high.indices.iter().map(|index| (high.positions[*index as usize] - ball_center) * CAGE_SCALE + ball_center).collect(); + h.renderer.set_bake_cage(&h.device, &h.queue, 0, Some((&corners, &CAGE_EDGES)), CAGE_TOPOLOGY); + let bake = BakeVisualization { high_poly: false, cage: false, uv_seams: false, low_poly: true, only_set: None }; + let center = (frame.size[0] / 2, frame.size[1] / 2); + + let only = |h: &mut Headless, parts: BakeVisualization, name: &str| render(h, &shaded(&frame, |s| s.bake = Some(parts)), name); + let low_only = only(&mut h, bake, "bake_low_only"); + let hidden = only(&mut h, BakeVisualization { low_poly: false, ..bake }, "bake_low_hidden"); + let high_poly = only(&mut h, BakeVisualization { low_poly: false, high_poly: true, ..bake }, "bake_high_poly"); + let caged = only(&mut h, BakeVisualization { cage: true, ..bake }, "bake_cage"); + assert_same(&low_only, &render(&mut h, &frame, "bake_off"), "every part off draws only the low poly"); + let background = render(&mut h, &Frame { visible: vec![false, false], ..frame.clone() }, "bake_background"); + assert_same(&hidden, &background, "without the low poly only the background is left"); + let [red, green, blue] = high_poly.at(center.0, center.1).map(i32::from); + assert!(blue > red + COLOR_LEAD && blue > green, "the high poly inside the low poly draws blue: {:?}", [red, green, blue]); + let ([low_red, low_green, low_blue], [caged_red, caged_green, caged_blue]) = (low_only.at(center.0, center.1), caged.at(center.0, center.1)); + assert!( + caged_blue < low_blue && caged_red >= caged_blue && caged_green >= caged_blue, + "the cage tints the ball tan: {:?} → {:?}", + [low_red, low_green, low_blue], + [caged_red, caged_green, caged_blue] + ); + + // Vertices the bake's rays miss turn red + h.renderer.set_bake_high_missed(&h.queue, HIGH_POLY_ID, &vec![1.0; high.positions.len()]); + let missed = only(&mut h, BakeVisualization { low_poly: false, high_poly: true, ..bake }, "bake_high_missed"); + let [red, green, blue] = missed.at(center.0, center.1).map(i32::from); + assert!(red > blue + COLOR_LEAD && red > green + COLOR_LEAD, "missed vertices draw red: {:?}", [red, green, blue]); + + // Show for selected texture set only: the other set's low poly and the cage of set 0 drop out + let first_set = only(&mut h, BakeVisualization { cage: true, only_set: Some(0), ..bake }, "bake_only_first_set"); + let second_set = only(&mut h, BakeVisualization { cage: true, only_set: Some(1), ..bake }, "bake_only_second_set"); + assert_ne!(first_set.px, caged.px, "the second set's low poly is left out"); + assert_ne!(second_set.px, caged.px, "the first set's low poly and cage are left out"); + assert_ne!(first_set.px, second_set.px); + + // UV seams draw over the low poly + h.renderer.set_uv_seams(&h.device, &h.queue, MESH_ID, &ball.uv_seam_edges()); + let seams = only(&mut h, BakeVisualization { uv_seams: true, ..bake }, "bake_uv_seams"); + assert_ne!(seams.px, low_only.px, "the seams show"); + + // A new distance with the same topology only moves the corners + let grown: Vec = corners.iter().map(|corner| (*corner - ball_center) * 2.0 + ball_center).collect(); + h.renderer.set_bake_cage(&h.device, &h.queue, 0, Some((&grown, &CAGE_EDGES)), CAGE_TOPOLOGY); + let bigger = only(&mut h, BakeVisualization { cage: true, ..bake }, "bake_cage_grown"); + assert_ne!(caged.px, bigger.px, "the cage grew"); +} + +#[test] +fn oversized_bake_high_poly_leaves_the_view_renderable() { + let Some((mut headless, frame)) = setup() else { return }; + + let high = primitives::sphere(0.5, 16, 8); + headless.renderer.set_bake_high(&headless.device, &headless.queue, Some(&high), 1).unwrap(); + let limit = headless.device.limits().max_buffer_size; + // The viewport vertex contains position, normal, tangent and UV: twelve f32 values + let vertex_count = limit as usize / (12 * std::mem::size_of::()) + 1; + let oversized = texturecraft_geom::Mesh { positions: vec![Vec3::ZERO; vertex_count], ..Default::default() }; + let error = headless.renderer.set_bake_high(&headless.device, &headless.queue, Some(&oversized), 2).unwrap_err(); + assert!(error.contains("GPU buffer limit"), "{error}"); + + headless.renderer.set_bake_high_missed(&headless.queue, 2, &[]); + let bake = BakeVisualization { high_poly: true, cage: false, uv_seams: false, low_poly: false, only_set: None }; + let cleared = render(&mut headless, &shaded(&frame, |shade| shade.bake = Some(bake)), "bake_oversized_cleared"); + let background = render(&mut headless, &Frame { visible: vec![false, false], ..frame.clone() }, "bake_oversized_background"); + assert_same(&cleared, &background, "an oversized replacement must not leave the previous high poly visible"); + headless.renderer.set_bake_high(&headless.device, &headless.queue, Some(&high), 3).unwrap(); + let recovered = render(&mut headless, &shaded(&frame, |shade| shade.bake = Some(bake)), "bake_oversized_recovered"); + assert_ne!(recovered.px, background.px, "a later valid high poly still draws"); +} + +#[test] +fn bake_low_poly_visibility_also_filters_its_wireframe() { + let Some((mut headless, frame)) = setup() else { return }; + + let bake = BakeVisualization { high_poly: false, cage: false, uv_seams: false, low_poly: false, only_set: None }; + let hidden = shaded(&frame, |shade| { + shade.bake = Some(bake); + shade.wireframe_3d = true; + shade.highlight = Some(texturecraft_render::SetHighlight { set: 0, color: [1.0, 0.5, 0.0] }); + }); + let background = render(&mut headless, &Frame { visible: vec![false, false], ..frame.clone() }, "bake_wire_background"); + let hidden_wire = render(&mut headless, &hidden, "bake_wire_hidden"); + assert_same(&hidden_wire, &background, "hiding the project mesh also hides its wireframe and highlight"); + + for texture_set in [0, 1] { + let selected = shaded(&hidden, |shade| { + shade.bake = Some(BakeVisualization { low_poly: true, only_set: Some(texture_set), ..bake }); + shade.highlight = Some(texturecraft_render::SetHighlight { set: 1 - texture_set, color: [1.0, 0.5, 0.0] }); + }); + let expected = Frame { visible: vec![texture_set == 0, texture_set == 1], ..selected.clone() }; + let actual = render(&mut headless, &selected, &format!("bake_wire_selected_{texture_set}")); + let expected = render(&mut headless, &expected, &format!("bake_wire_expected_{texture_set}")); + assert_same(&actual, &expected, "the wireframe and highlight respect the selected texture set"); + } +} + #[test] fn ortho_background_matches_perspective() { let Some((mut h, frame)) = setup() else { return }; diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 7887bf26..fdc45c70 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -15,6 +15,8 @@ eframe = { workspace = true, features = ["default_fonts", "wgpu", "persistence"] egui = { workspace = true } craft-ui = { workspace = true } craft-window = { workspace = true } +craft-keymap = { workspace = true } +craft-quit = { workspace = true } egui-phosphor = { version = "0.14", features = ["regular", "fill"] } serde = { workspace = true } serde_json = { workspace = true } @@ -22,7 +24,6 @@ rayon = { workspace = true } log = { workspace = true } base64 = "0.22" image = { workspace = true } -rfd = { workspace = true } zip = { workspace = true } # The OS UI language for the first run (MIT OR Apache-2.0; the browser asks `navigator.language`). @@ -30,6 +31,10 @@ zip = { workspace = true } sys-locale = "0.3" # Floating panels open as OS windows. craft-ui = { workspace = true, features = ["native-windows"] } +# Help > Check for Updates and the check at start (updates_ui.rs). +craft-update = { workspace = true } +# Native file dialogs (file_dialogs.rs); the browser build has none. +craft-dialogs = { workspace = true } # build.rs: the interface faces lose their Private Use Area, where the icon font draws (the # versions craft-libs' craft-fonts-build subsets with). @@ -39,6 +44,7 @@ skrifa = { version = "0.48", default-features = false, features = ["std"] } # Browser file I/O (web_files.rs): async pickers and Blob downloads. [target.'cfg(target_arch = "wasm32")'.dependencies] +rfd = { workspace = true } wasm-bindgen = "0.2" wasm-bindgen-futures = "0.4" js-sys = "0.3" diff --git a/crates/ui-egui/src/bake_mode/bake_visualization_panel.rs b/crates/ui-egui/src/bake_mode/bake_visualization_panel.rs new file mode 100644 index 00000000..42da4393 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/bake_visualization_panel.rs @@ -0,0 +1,61 @@ +use egui::collapsing_header::CollapsingState; +use egui::{Rect, Ui, vec2}; +use egui_phosphor::regular as icon; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::theme::Tokens; +use crate::widgets::{icon_button_without_tooltip, section_chevron}; + +/// The panel's width and its gap from the 3D view's top-left corner +const PANEL_WIDTH: f32 = 280.0; +const PANEL_MARGIN: f32 = 12.0; + +/// Size of the panel's eye buttons +const EYE_BUTTON_SIZE: f32 = 22.0; + +/// The Baking Visualization panel in the top-left corner of bake mode's 3D view `view` +pub(crate) fn bake_visualization_panel(app: &mut TextureCraftApp, ui: &Ui, view: Rect) { + let toggles = &mut app.ui.bake_visualization; + egui::Area::new(ui.scope_id().with("bake_visualization_panel")).fixed_pos(view.left_top() + vec2(PANEL_MARGIN, PANEL_MARGIN)).constrain_to(view).show( + ui.ctx(), + |ui| { + ui.set_width(PANEL_WIDTH); + let mut collapsing_state = CollapsingState::load_with_default_open(ui.ctx(), ui.make_persistent_id("bake_visualization_open"), true); + let header = eye_row(ui, &mut toggles.on, tr("Baking Visualization"), Some(collapsing_state.is_open())); + if header.clicked() { + collapsing_state.toggle(ui); + } + + collapsing_state.show_body_unindented(ui, |ui| { + ui.add_enabled_ui(toggles.on, |ui| { + ui.checkbox(&mut toggles.selected_set_only, tr("Show for Selected Texture Set Only")); + eye_row(ui, &mut toggles.high_poly, tr("High Definition Mesh (HP)"), None); + eye_row(ui, &mut toggles.cage, tr("Cage"), None); + eye_row(ui, &mut toggles.uv_seams, tr("UV Seams"), None); + eye_row(ui, &mut toggles.low_poly, tr("Project Mesh (LP)"), None); + }); + }); + }, + ); +} + +/// A row with `label`, a chevron when `open` is given, and an eye button on the right that switches `shown`; returns the label's response +fn eye_row(ui: &mut Ui, shown: &mut bool, label: &str, open: Option) -> egui::Response { + let tokens = Tokens::get(ui.ctx()); + ui.horizontal(|ui| { + ui.set_min_height(EYE_BUTTON_SIZE); + let text = match open { + Some(is_open) => egui::RichText::new(format!("{} {label}", section_chevron(ui, is_open).text())), + None => egui::RichText::new(label), + }; + let response = ui.add(egui::Label::new(text.color(tokens.text_strong)).selectable(false).sense(egui::Sense::click())); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if icon_button_without_tooltip(ui, if *shown { icon::EYE } else { icon::EYE_SLASH }, label, false, EYE_BUTTON_SIZE).clicked() { + *shown = !*shown; + } + }); + response + }) + .inner +} diff --git a/crates/ui-egui/src/bake_mode/bake_visualization_toggles.rs b/crates/ui-egui/src/bake_mode/bake_visualization_toggles.rs new file mode 100644 index 00000000..0603c523 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/bake_visualization_toggles.rs @@ -0,0 +1,34 @@ +use serde::{Deserialize, Serialize}; +use texturecraft_render::BakeVisualization; + +/// The Baking Visualization panel's switches in bake mode's 3D view +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct BakeVisualizationToggles { + /// The panel's eye: the whole visualization on or off + pub on: bool, + pub selected_set_only: bool, + pub high_poly: bool, + pub cage: bool, + pub uv_seams: bool, + pub low_poly: bool, +} + +impl Default for BakeVisualizationToggles { + fn default() -> Self { + Self { on: true, selected_set_only: false, high_poly: true, cage: true, uv_seams: false, low_poly: true } + } +} + +impl BakeVisualizationToggles { + /// What the renderer draws with these switches while texture set `selected_set` is selected + pub fn visualization(&self, selected_set: usize) -> Option { + self.on.then_some(BakeVisualization { + high_poly: self.high_poly, + cage: self.cage, + uv_seams: self.uv_seams, + low_poly: self.low_poly, + only_set: self.selected_set_only.then_some(selected_set), + }) + } +} diff --git a/crates/ui-egui/src/bake_mode/mod.rs b/crates/ui-egui/src/bake_mode/mod.rs index 3a308a4a..70dd4225 100644 --- a/crates/ui-egui/src/bake_mode/mod.rs +++ b/crates/ui-egui/src/bake_mode/mod.rs @@ -1,9 +1,13 @@ //! Bake Mode presentation; persisted settings live in core and edits use engine commands mod bake_paint_brush; +mod bake_visualization_panel; +mod bake_visualization_toggles; mod breadcrumb; mod common_settings; pub use bake_paint_brush::BakePaintBrush; +pub(crate) use bake_visualization_panel::bake_visualization_panel; +pub use bake_visualization_toggles::BakeVisualizationToggles; mod controls; mod map_settings; mod mesh_map_bakers; diff --git a/crates/ui-egui/src/bake_scene.rs b/crates/ui-egui/src/bake_scene.rs new file mode 100644 index 00000000..1a30780e --- /dev/null +++ b/crates/ui-egui/src/bake_scene.rs @@ -0,0 +1,11 @@ +//! Keeps the GPU's copy of bake mode's visualization (high poly, cages, UV seams) in step with the session + +mod bake_scene_link; +mod cage_link; +mod cage_shell_key; +mod cage_upload; +mod reach_link; +mod shared_handle; + +pub use bake_scene_link::BakeSceneLink; +pub use cage_upload::CageUpload; diff --git a/crates/ui-egui/src/bake_scene/bake_scene_link.rs b/crates/ui-egui/src/bake_scene/bake_scene_link.rs new file mode 100644 index 00000000..b9cecaa9 --- /dev/null +++ b/crates/ui-egui/src/bake_scene/bake_scene_link.rs @@ -0,0 +1,239 @@ +use std::sync::Arc; + +use texturecraft_engine::Session; +use texturecraft_engine::geom::Mesh; +use texturecraft_render::BakeVisualization; + +use super::CageUpload; +use super::cage_link::CageLink; +use super::cage_shell_key::CageShellKey; +use super::reach_link::ReachLink; +use super::shared_handle::SharedHandle; +use crate::gpu::SceneSync; + +/// What the GPU has of bake mode's visualization: the high poly, each set's cage and the UV seams +#[derive(Default)] +pub struct BakeSceneLink { + /// The high poly sent to the GPU and the id it was sent under (each new high poly gets the next one) + high: SharedHandle, + high_id: u64, + /// Whether the GPU has the high poly (a lost frame sends it again under the same id) + high_sent: bool, + cages: Vec>, + /// How many texture sets' cages the GPU was last told to keep + sent_cage_count: Option, + /// The low-poly mesh whose seams are uploaded + seams_mesh_id: Option, + next_topology: u64, + reach: ReachLink, +} + +impl BakeSceneLink { + /// Send everything again (the GPU lost what it was sent); the cage shells and the reach worked out on the CPU stay + pub fn resend(&mut self) { + self.high_sent = false; + self.sent_cage_count = None; + self.seams_mesh_id = None; + for link in self.cages.iter_mut().flatten() { + link.max_frontal = f32::NAN; + } + self.reach.resend(); + } + + /// Whether something is still being worked out off the UI thread + pub fn busy(&self) -> bool { + self.reach.busy() + } + + /// Add to `out` what the GPU needs to draw `visualization` this frame + pub fn sync(&mut self, session: &Session, visualization: Option, out: &mut SceneSync) { + self.reach.poll(); + + let Some(visualization) = visualization else { return }; + + if visualization.high_poly { + let high = session.bake_meshes.merged_high().map(|high| high.mesh.clone()); + let handle = SharedHandle::of(high.as_ref()); + if handle != self.high { + self.high = handle; + self.high_id += 1; + self.high_sent = false; + } + if !self.high_sent { + out.bake_high = Some((high, self.high_id)); + self.high_sent = true; + } + self.reach.sync(session, self.high_id, visualization.only_set, out); + } + + if visualization.uv_seams && self.seams_mesh_id != Some(session.mesh_id) { + self.seams_mesh_id = Some(session.mesh_id); + out.uv_seams = Some((session.mesh_id, session.mesh.uv_seam_edges())); + } + + if visualization.cage { + self.sync_cages(session, out); + } + } + + /// Rebuild the cages whose inputs changed and move the corners of those whose distance changed + fn sync_cages(&mut self, session: &Session, out: &mut SceneSync) { + let set_count = session.doc.project.texture_sets.len(); + if self.sent_cage_count != Some(set_count) { + out.bake_cage_count = Some(set_count); + self.sent_cage_count = Some(set_count); + } + self.cages.truncate(set_count); + self.cages.resize_with(set_count, || None); + + for (texture_set, link) in self.cages.iter_mut().enumerate() { + let (Some(key), Some(set)) = (CageShellKey::of(session, texture_set), session.doc.project.texture_sets.get(texture_set)) else { continue }; + + let max_frontal = set.bake.cage.max_frontal; + match link { + Some(link) if link.key == key => { + if link.max_frontal == max_frontal { + continue; + } + link.max_frontal = max_frontal; + } + _ => { + self.next_topology += 1; + let shell = session.bake_cage_inputs(texture_set).ok().flatten().and_then(|inputs| inputs.cage_shell().ok()).map(Arc::new); + *link = Some(CageLink { key, shell, topology: self.next_topology, max_frontal }); + } + } + + let Some(link) = link.as_ref() else { continue }; + + let upload = link.shell.as_ref().map(|shell| CageUpload { corners: shell.corners(max_frontal), shell: shell.clone() }); + out.bake_cages.push((texture_set, upload, link.topology)); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + const EVERYTHING: BakeVisualization = BakeVisualization { high_poly: true, cage: true, uv_seams: true, low_poly: true, only_set: None }; + + /// How long a test waits for the reach worker: frames, and the pause between them + const WAIT_FRAMES: usize = 2000; + const WAIT_FRAME_PAUSE: std::time::Duration = std::time::Duration::from_millis(5); + + /// The sample project with a high poly a little outside its low poly + fn session() -> Session { + const HIGH_POLY_OFFSET: f32 = 0.02; + + let mut session = texturecraft_engine::sample_session(128, 128).unwrap(); + let low = session.mesh.clone(); + let mut obj = String::new(); + for (position, normal) in low.positions.iter().zip(&low.normals) { + let raised = *position + *normal * HIGH_POLY_OFFSET; + obj += &format!("v {} {} {}\n", raised.x, raised.y, raised.z); + } + for corners in low.indices.chunks(3) { + obj += &format!("f {} {} {}\n", corners[0] + 1, corners[1] + 1, corners[2] + 1); + } + session.add_high_poly_bytes("high.obj", obj.into_bytes()).unwrap(); + session + } + + fn sync(link: &mut BakeSceneLink, session: &Session, visualization: BakeVisualization) -> SceneSync { + let mut out = SceneSync::default(); + link.sync(session, Some(visualization), &mut out); + out + } + + /// Sync until the reach worked out on the worker thread colors the high poly; the share of vertices drawn red + fn red_share(link: &mut BakeSceneLink, session: &Session, visualization: BakeVisualization) -> f32 { + for _ in 0..WAIT_FRAMES { + if let Some((_, missed)) = sync(link, session, visualization).bake_high_missed { + return missed.iter().sum::() / missed.len().max(1) as f32; + } + std::thread::sleep(WAIT_FRAME_PAUSE); + } + panic!("the reach never arrived"); + } + + fn set_distances(session: &mut Session, max_frontal: f32) { + texturecraft_engine::execute(session, "bake.settings", &json!({"ts": "all", "maxFrontal": max_frontal})).unwrap(); + } + + #[test] + fn a_new_distance_moves_the_corners_and_new_settings_rebuild_the_cage() { + let (mut session, mut link) = (session(), BakeSceneLink::default()); + let first = sync(&mut link, &session, EVERYTHING); + assert!(first.bake_high.is_some() && first.uv_seams.is_some() && first.bake_cage_count == Some(session.doc.project.texture_sets.len())); + let (_, Some(cage), topology) = first.bake_cages.first().unwrap() else { panic!("set 0 has a cage") }; + + let unchanged = sync(&mut link, &session, EVERYTHING); + assert!(unchanged.bake_high.is_none() && unchanged.bake_cages.is_empty() && unchanged.uv_seams.is_none(), "nothing changed, nothing is sent"); + + set_distances(&mut session, 0.03); + let moved = sync(&mut link, &session, EVERYTHING); + let (_, Some(moved_cage), moved_topology) = moved.bake_cages.first().unwrap() else { panic!("set 0 has a cage") }; + assert_eq!(moved_topology, topology, "a distance only moves the corners"); + assert_ne!(moved_cage.corners, cage.corners); + + texturecraft_engine::execute(&mut session, "bake.settings", &json!({"ts": "all", "averageNormals": false})).unwrap(); + let rebuilt = sync(&mut link, &session, EVERYTHING); + assert_ne!(rebuilt.bake_cages.first().unwrap().2, *topology, "new settings rebuild the cage"); + // The rebuilt cage starts a new reach: let it finish so the last check sees only what the resend starts + red_share(&mut link, &session, EVERYTHING); + + link.resend(); + let resent = sync(&mut link, &session, EVERYTHING); + assert!(resent.bake_high.is_some() && resent.uv_seams.is_some() && resent.bake_cage_count.is_some(), "a lost frame sends everything again"); + assert_eq!(resent.bake_cages.len(), rebuilt.bake_cages.len()); + assert_eq!(resent.bake_cages.first().unwrap().2, rebuilt.bake_cages.first().unwrap().2, "the cages are not rebuilt for a lost frame"); + assert_eq!(resent.bake_high.unwrap().1, first.bake_high.unwrap().1, "the high poly goes again under the same id"); + assert!(!link.busy(), "a lost frame doesn't work out the reach again"); + } + + #[test] + fn a_reach_finishes_while_nothing_is_drawn() { + let session = session(); + let no_high_poly = BakeVisualization { high_poly: false, ..EVERYTHING }; + for hidden in [None, Some(no_high_poly)] { + let mut link = BakeSceneLink::default(); + sync(&mut link, &session, EVERYTHING); + assert!(link.busy(), "the first frame starts working out the reach"); + + let finished = (0..WAIT_FRAMES).any(|_| { + std::thread::sleep(WAIT_FRAME_PAUSE); + link.sync(&session, hidden, &mut SceneSync::default()); + !link.busy() + }); + assert!(finished, "the view stops redrawing for a reach once it is done: {hidden:?}"); + } + } + + #[test] + fn the_red_follows_the_distances_and_the_selected_set() { + let (mut session, mut link) = (session(), BakeSceneLink::default()); + set_distances(&mut session, 0.0); + let at_zero = red_share(&mut link, &session, EVERYTHING); + assert!(at_zero > 0.5, "at frontal 0 the high poly outside the low poly is red: {at_zero}"); + + set_distances(&mut session, 0.05); + let covered = red_share(&mut link, &session, EVERYTHING); + assert!(covered < at_zero / 10.0, "a cage past the high poly reaches it: {covered}"); + + set_distances(&mut session, 0.0); + let by_name = |session: &mut Session, low_suffix: &str| { + for set in &mut session.doc.project.texture_sets { + set.bake.high_poly.match_mode = texturecraft_engine::core::MeshMatchMode::ByMeshName; + set.bake.high_poly.low_suffix = low_suffix.into(); + } + }; + by_name(&mut session, "_no_such_suffix"); + let by_name_red = red_share(&mut link, &session, EVERYTHING); + assert!(by_name_red > 0.5, "matching by name and other suffixes works out the reach again: {by_name_red}"); + + let no_set = BakeVisualization { only_set: Some(session.doc.project.texture_sets.len()), ..EVERYTHING }; + assert_eq!(red_share(&mut link, &session, no_set), 0.0, "sets left out by the filter color nothing"); + } +} diff --git a/crates/ui-egui/src/bake_scene/cage_link.rs b/crates/ui-egui/src/bake_scene/cage_link.rs new file mode 100644 index 00000000..855d9619 --- /dev/null +++ b/crates/ui-egui/src/bake_scene/cage_link.rs @@ -0,0 +1,16 @@ +use std::sync::Arc; + +use texturecraft_engine::bake::CageShell; + +use super::cage_shell_key::CageShellKey; + +/// A texture set's cage as the GPU has it +pub(super) struct CageLink { + pub(super) key: CageShellKey, + /// `None`: the set bakes without a high poly or its cage can't be built + pub(super) shell: Option>, + /// The renderer's name for the shell's corner order and edges + pub(super) topology: u64, + /// The max frontal distance the GPU's corners are at + pub(super) max_frontal: f32, +} diff --git a/crates/ui-egui/src/bake_scene/cage_shell_key.rs b/crates/ui-egui/src/bake_scene/cage_shell_key.rs new file mode 100644 index 00000000..44e17eca --- /dev/null +++ b/crates/ui-egui/src/bake_scene/cage_shell_key.rs @@ -0,0 +1,47 @@ +use std::collections::BTreeMap; + +use texturecraft_engine::Session; +use texturecraft_engine::bake::BakePaintMap; +use texturecraft_engine::core::{BakePaintTarget, CageType, SkewSettings}; +use texturecraft_engine::geom::Mesh; + +use super::shared_handle::SharedHandle; + +/// Everything a texture set's cage shell is built from except the distances, which only move its corners +#[derive(Clone, Debug, PartialEq)] +pub(super) struct CageShellKey { + mesh_id: u64, + high: SharedHandle, + cage_file: SharedHandle, + material: usize, + uv_tiles: Vec, + tile_resolutions: BTreeMap, + cage_kind: CageType, + relative_to_bounding_box: bool, + average_normals: bool, + use_low_as_high: bool, + skew: SkewSettings, + /// The painted skew and cage maps + paint: [SharedHandle; 2], +} + +impl CageShellKey { + pub(super) fn of(session: &Session, texture_set: usize) -> Option { + let set = session.doc.project.texture_sets.get(texture_set)?; + let paint = |target| SharedHandle::of(session.doc.bake_paint.get(&(texture_set, target))); + Some(CageShellKey { + mesh_id: session.mesh_id, + high: SharedHandle::of(session.bake_meshes.merged_high().map(|high| &high.mesh)), + cage_file: SharedHandle::of(session.bake_meshes.cage.as_ref().map(|cage| &cage.mesh)), + material: set.material, + uv_tiles: set.uv_tiles.clone(), + tile_resolutions: set.tile_resolutions.clone(), + cage_kind: set.bake.cage.kind, + relative_to_bounding_box: set.bake.cage.relative_to_bounding_box, + average_normals: set.bake.cage.average_normals, + use_low_as_high: set.bake.high_poly.use_low_as_high, + skew: set.bake.skew, + paint: [paint(BakePaintTarget::Skew), paint(BakePaintTarget::Cage)], + }) + } +} diff --git a/crates/ui-egui/src/bake_scene/cage_upload.rs b/crates/ui-egui/src/bake_scene/cage_upload.rs new file mode 100644 index 00000000..81951645 --- /dev/null +++ b/crates/ui-egui/src/bake_scene/cage_upload.rs @@ -0,0 +1,10 @@ +use std::sync::Arc; + +use texturecraft_engine::bake::CageShell; +use texturecraft_engine::geom::glam::Vec3; + +/// A texture set's cage for the GPU: its corners at the current distance and the shell they come from +pub struct CageUpload { + pub corners: Vec, + pub shell: Arc, +} diff --git a/crates/ui-egui/src/bake_scene/reach_link.rs b/crates/ui-egui/src/bake_scene/reach_link.rs new file mode 100644 index 00000000..c8a181f5 --- /dev/null +++ b/crates/ui-egui/src/bake_scene/reach_link.rs @@ -0,0 +1,140 @@ +use std::sync::mpsc::{Receiver, TryRecvError}; + +use texturecraft_engine::Session; +use texturecraft_engine::bake::{HighPolyReach, high_poly_missed}; +use texturecraft_engine::core::HighPolySettings; + +use super::cage_shell_key::CageShellKey; +use crate::gpu::SceneSync; + +/// Each set's (max frontal, max rear) and the selected-set filter +type ShownDistances = (Vec<(f32, f32)>, Option); + +/// The red on the high poly: each texture set's ray reach, worked out on a worker thread, and the distances the GPU's colors show +#[derive(Default)] +pub(super) struct ReachLink { + /// Each set's ray inputs and high-poly settings (backfaces, name matching), and the id of the high poly, the reach was started for + keys: Vec>, + high_id: u64, + job: Option>>>, + reach: Vec>, + /// Each set's (max frontal, max rear) and the selected-set filter the GPU's colors are for + shown: Option, +} + +impl ReachLink { + /// Whether a reach is being worked out (the view must keep drawing to pick it up) + pub(super) fn busy(&self) -> bool { + self.job.is_some() + } + + /// Send the colors again (the GPU lost what it was sent); the reach itself stays + pub(super) fn resend(&mut self) { + self.shown = None; + } + + /// Pick up the reach once the worker finishes; runs every frame, even when nothing is drawn, so `busy` clears + pub(super) fn poll(&mut self) { + let Some(job) = &self.job else { return }; + + match job.try_recv() { + Ok(reach) => { + self.reach = reach; + self.shown = None; + self.job = None; + } + Err(TryRecvError::Disconnected) => self.job = None, + Err(TryRecvError::Empty) => {} + } + } + + /// Start a new reach when the high poly (sent under `high_id`) or a set's inputs changed, and color the high poly when the reach or the distances changed + pub(super) fn sync(&mut self, session: &Session, high_id: u64, only_set: Option, out: &mut SceneSync) { + // Coalesce paint edits while a worker runs; after polling it, the next job captures the latest inputs + if self.job.is_some() { + return; + } + + let set_count = session.doc.project.texture_sets.len(); + let keys: Vec> = session + .doc + .project + .texture_sets + .iter() + .enumerate() + .map(|(texture_set, set)| Some((CageShellKey::of(session, texture_set)?, set.bake.high_poly.clone()))) + .collect(); + if keys != self.keys || high_id != self.high_id { + let inputs: Vec<_> = (0..set_count).map(|texture_set| session.bake_cage_inputs(texture_set).ok().flatten()).collect(); + self.job = Some(crate::spawn_worker("texturecraft-bake-reach", move || { + inputs.iter().map(|inputs| inputs.as_ref().and_then(|inputs| inputs.high_poly_reach().ok())).collect() + })); + (self.keys, self.high_id) = (keys, high_id); + } + + // Colors wait for the reach being worked out: the old ones stay until it arrives + if self.job.is_some() { + return; + } + + let distances: Vec<(f32, f32)> = session.doc.project.texture_sets.iter().map(|set| (set.bake.cage.max_frontal, set.bake.cage.max_rear)).collect(); + let shown = (distances, only_set); + if self.shown.as_ref() == Some(&shown) { + return; + } + + let Some(vertex_count) = session.bake_meshes.merged_high().map(|high| high.mesh.positions.len()) else { return }; + + out.bake_high_missed = Some((self.high_id, high_poly_missed(&self.reach, &shown.0, only_set, vertex_count))); + self.shown = Some(shown); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::{Arc, mpsc}; + use std::time::Duration; + use texturecraft_engine::bake::BakePaintMap; + use texturecraft_engine::core::BakePaintTarget; + use texturecraft_engine::geom::primitives; + + #[test] + fn input_changes_wait_for_the_running_reach_then_use_the_latest_inputs() { + let mut session = Session::new_project("Reach", primitives::plane(1.0, 1), "plane", None, 128).unwrap(); + session.add_high_poly_bytes("high.obj", b"v 0 0.1 0\nv 0.1 0.1 0\nv 0 0.1 0.1\nf 1 2 3\n".to_vec()).unwrap(); + let (sender, receiver) = mpsc::channel(); + let mut link = ReachLink { job: Some(receiver), ..Default::default() }; + + // Hold the original job open while paint and mesh inputs change + for amount in [0.25, 0.5, 0.75] { + session.doc.bake_paint.insert((0, BakePaintTarget::Cage), Arc::new(BakePaintMap::constant(amount))); + let mut out = SceneSync::default(); + link.sync(&session, 2, None, &mut out); + assert!(out.bake_high_missed.is_none()); + } + assert!(sender.send(Vec::new()).is_ok(), "input changes must keep the running job's receiver"); + link.poll(); + + // The finished job is stale: a new job must capture the latest settings before sending colors + session.doc.project.texture_sets[0].bake.high_poly.use_low_as_high = true; + let mut out = SceneSync::default(); + link.sync(&session, 2, None, &mut out); + assert!(link.busy()); + assert!(out.bake_high_missed.is_none()); + + for _ in 0..2000 { + link.poll(); + if !link.busy() { + break; + } + std::thread::sleep(Duration::from_millis(5)); + } + assert!(!link.busy(), "the latest reach must finish"); + link.sync(&session, 2, None, &mut out); + let (high_id, missed) = out.bake_high_missed.unwrap(); + assert_eq!(high_id, 2); + assert_eq!(missed, vec![0.0; session.bake_meshes.merged_high().unwrap().mesh.positions.len()]); + assert!(link.reach[0].is_none(), "the latest setting bakes without a high poly"); + } +} diff --git a/crates/ui-egui/src/bake_scene/shared_handle.rs b/crates/ui-egui/src/bake_scene/shared_handle.rs new file mode 100644 index 00000000..15ceb1d8 --- /dev/null +++ b/crates/ui-egui/src/bake_scene/shared_handle.rs @@ -0,0 +1,32 @@ +use std::sync::{Arc, Weak}; + +/// Which shared value a key refers to, without keeping the value alive; the held `Weak` keeps its address from being reused, so a new value never passes for it +#[derive(Debug)] +pub(super) struct SharedHandle(Option>); + +impl SharedHandle { + pub(super) fn of(value: Option<&Arc>) -> SharedHandle { + SharedHandle(value.map(Arc::downgrade)) + } +} + +impl Clone for SharedHandle { + fn clone(&self) -> Self { + SharedHandle(self.0.clone()) + } +} + +impl Default for SharedHandle { + fn default() -> Self { + SharedHandle(None) + } +} + +impl PartialEq for SharedHandle { + fn eq(&self, other: &Self) -> bool { + match (&self.0, &other.0) { + (Some(this), Some(other)) => Weak::ptr_eq(this, other), + (this, other) => this.is_none() && other.is_none(), + } + } +} diff --git a/crates/ui-egui/src/color_selection_editor.rs b/crates/ui-egui/src/color_selection_editor.rs new file mode 100644 index 00000000..482bc227 --- /dev/null +++ b/crates/ui-egui/src/color_selection_editor.rs @@ -0,0 +1,104 @@ +//! Properties of a color selection effect: tolerance and the ID colors it selects + +use egui::{Color32, RichText, Sense, Stroke, Ui, vec2}; +use egui_phosphor::regular as ic; +use serde_json::json; +use texturecraft_engine::core::{BakedMap, LayerId}; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::id_color_pick::IdColorPick; +use crate::theme::Tokens; +use crate::widgets::{icon_button, slider_edit}; + +/// Width of one R, G or B readout, so the columns line up from row to row (fits "G: 255") +const READOUT_WIDTH: f32 = 50.0; + +/// Height of a color row's swatch and readouts, as tall as the app's other swatches +const ROW_HEIGHT: f32 = 18.0; + +const SWATCH_WIDTH: f32 = 36.0; + +const ROW_BUTTON_SIZE: f32 = 20.0; + +/// Tolerance, a Colors list with a pick mode, and one row per ID color (swatch, re-pick, R/G/B, remove) +pub fn color_selection_properties(app: &mut TextureCraftApp, ui: &mut Ui, effect: LayerId, colors: &[[f32; 3]], tolerance: f32) { + let tokens = Tokens::get(ui.ctx()); + let mut edited_tolerance = tolerance; + if let Some(merge) = slider_edit(ui, tr("Tolerance"), &mut edited_tolerance, 0.0..=1.0, 2) { + app.run("effect.set", json!({"effect": effect.0, "tolerance": edited_tolerance, "merge": merge})); + } + + let set_index = app.session.doc.project.locate(effect_owner(app, effect)).map_or(app.session.ts(), |(set_index, _, _)| set_index); + let has_id_map = app.session.baked(set_index).is_some_and(|baked| baked.maps.contains_key(&BakedMap::Id)); + if !has_id_map { + ui.label(RichText::new(format!("{} {}", ic::WARNING, tr("Bake an ID map (F8) to pick colors from the mesh."))).color(tokens.warning)); + } + + let picking = app.picking_id_color.filter(|pick| pick.effect == effect); + ui.group(|ui| { + ui.horizontal(|ui| { + ui.label(tr("Colors")); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let adding = picking.is_some_and(|pick| pick.index.is_none()); + let button = egui::Button::new(format!("{} {}", ic::EYEDROPPER, tr("Pick color"))).selected(adding); + if ui.add_enabled(has_id_map, button).clicked() { + toggle_pick(app, effect, None, adding); + } + }); + }); + + for (index, color) in colors.iter().enumerate() { + ui.horizontal(|ui| { + id_swatch(ui, *color); + let repicking = picking.is_some_and(|pick| pick.index == Some(index)); + let repick = ui.add_enabled_ui(has_id_map, |ui| icon_button(ui, ic::EYEDROPPER, tr("Pick color"), repicking, ROW_BUTTON_SIZE)).inner; + if repick.clicked() { + toggle_pick(app, effect, Some(index), repicking); + } + + for (channel, value) in ["R", "G", "B"].iter().zip(display_bytes(*color)) { + ui.allocate_ui_with_layout(vec2(READOUT_WIDTH, ROW_HEIGHT), egui::Layout::left_to_right(egui::Align::Center), |ui| { + ui.set_min_width(READOUT_WIDTH); + ui.label(format!("{channel}: {value}")); + }); + } + + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let remove = ui.add_enabled_ui(colors.len() > 1, |ui| icon_button(ui, ic::MINUS, tr("Remove"), false, ROW_BUTTON_SIZE)).inner; + if remove.clicked() { + // Removing a row changes the indices of pending replacements + IdColorPick::end(app); + let remaining: Vec<[f32; 3]> = colors.iter().enumerate().filter(|(kept, _)| *kept != index).map(|(_, kept)| *kept).collect(); + app.run("effect.set", json!({"effect": effect.0, "colors": remaining})); + } + }); + }); + } + }); +} + +/// The layer whose mask holds `effect` +fn effect_owner(app: &TextureCraftApp, effect: LayerId) -> LayerId { + app.session.doc.project.effect(effect).map_or(effect, |(owner, _)| owner) +} + +fn toggle_pick(app: &mut TextureCraftApp, effect: LayerId, index: Option, running: bool) { + if running { + IdColorPick::end(app); + } else { + IdColorPick::start(app, effect, index); + } +} + +/// An ID color as the ID map view draws it: the stored value, unconverted, in 0–255 +fn display_bytes(color: [f32; 3]) -> [u8; 3] { + color.map(|value| (value.clamp(0.0, 1.0) * 255.0).round() as u8) +} + +fn id_swatch(ui: &mut Ui, color: [f32; 3]) { + let tokens = Tokens::get(ui.ctx()); + let [red, green, blue] = display_bytes(color); + let (rect, _) = ui.allocate_exact_size(vec2(SWATCH_WIDTH, ROW_HEIGHT), Sense::hover()); + ui.painter().rect(rect, f32::from(tokens.radius), Color32::from_rgb(red, green, blue), Stroke::new(1.0, tokens.field_border), egui::StrokeKind::Inside); +} diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 364d16e8..612186fa 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -2112,6 +2112,7 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: tool_properties(app, ui); } EffectKind::Filter(filter) => filter_properties(app, ui, id, filter), + EffectKind::ColorSelection { colors, tolerance } => crate::color_selection_editor::color_selection_properties(app, ui, eid, colors, *tolerance), other => { ui.label(RichText::new(tr(other.name())).color(tk.text_dim)); } diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index 789ddc51..0dcbdaa2 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -388,6 +388,17 @@ fn style(ui: &Ui, t: &Tokens) -> DockStyle { s } +/// Whether a modal layer or update dialog holds the input, so the panels, floating ones included, +/// do not take it. +pub(crate) fn input_blocked(app: &TextureCraftApp, context: &egui::Context) -> bool { + let modal = context.memory(|memory| memory.top_modal_layer()).is_some(); + #[cfg(not(target_arch = "wasm32"))] + let modal = modal || crate::updates_ui::blocks_input(app); + #[cfg(target_arch = "wasm32")] + let _ = app; + modal +} + /// Draw the dock (viewport and panels) into `ui`. pub fn show(app: &mut TextureCraftApp, ui: &mut Ui) { for panel in Panel::ALL { @@ -400,7 +411,7 @@ pub fn show(app: &mut TextureCraftApp, ui: &mut Ui) { let tokens = Tokens::get(&context); let style = style(ui, &tokens); let layout = app.ui.dock.workspace.layout.clone(); - let mut area = DockArea::new(area_id()).input_blocked(context.memory(|memory| memory.top_modal_layer()).is_some()); + let mut area = DockArea::new(area_id()).input_blocked(input_blocked(app, &context)); if let Some(panel) = app.ui.dock.raise.take() { area = area.raise_panel(panel); } diff --git a/crates/ui-egui/src/export_templates.rs b/crates/ui-egui/src/export_templates.rs index fe2fc5e4..5d5ddafc 100644 --- a/crates/ui-egui/src/export_templates.rs +++ b/crates/ui-egui/src/export_templates.rs @@ -341,11 +341,14 @@ pub fn import(app: &mut TextureCraftApp, preset: &ExportPreset) { #[cfg(not(target_arch = "wasm32"))] fn import_file(app: &mut TextureCraftApp, _ctx: &egui::Context) { - let Some(path) = rfd::FileDialog::new().add_filter(tr("Export template"), &["json"]).pick_file() else { return }; - match texturecraft_engine::formats::load_preset(&path) { - Ok(p) => import(app, &p), - Err(e) => app.toast(trf("Couldn't import {name}: {error}", &[("name", &path.display()), ("error", &e)]), true), - } + use crate::file_dialogs::{Bound, FileDialog}; + app.ask_file(FileDialog::open().filter(tr("Export template"), &["json"]), Bound::App, |app, paths| { + let Some(path) = paths.first() else { return }; + match texturecraft_engine::formats::load_preset(path) { + Ok(p) => import(app, &p), + Err(e) => app.toast(trf("Couldn't import {name}: {error}", &[("name", &path.display()), ("error", &e)]), true), + } + }); } #[cfg(target_arch = "wasm32")] @@ -356,26 +359,43 @@ fn import_file(_app: &mut TextureCraftApp, ctx: &egui::Context) { fn export_file(app: &mut TextureCraftApp) { let Some(p) = selected(app) else { return }; let name = format!("{}.json", sanitize_file_stem(&p.name)); - let saved = texturecraft_engine::formats::preset_to_json(&p).map_err(|e| e.to_string()).and_then(|json| write_json(&name, &json)); - match saved { - Ok(Some(to)) => app.toast(trf("Exported template \"{name}\" to {path}", &[("name", &p.name), ("path", &to)]), false), - Ok(None) => {} - Err(e) => app.toast(trf("Couldn't export the template: {error}", &[("error", &e)]), true), - } + let json = match texturecraft_engine::formats::preset_to_json(&p) { + Ok(json) => json, + Err(e) => { + export_failed(app, &e); + return; + } + }; + write_json(app, p.name, name, json); } -/// Save `json` with the native dialog (Ok(None): cancelled). +fn export_failed(app: &mut TextureCraftApp, error: &dyn std::fmt::Display) { + app.toast(trf("Couldn't export the template: {error}", &[("error", error)]), true); +} + +fn exported(app: &mut TextureCraftApp, name: &str, to: &str) { + app.toast(trf("Exported template \"{name}\" to {path}", &[("name", &name), ("path", &to)]), false); +} + +/// Asks where to save `json` with the native dialog. #[cfg(not(target_arch = "wasm32"))] -fn write_json(name: &str, json: &str) -> Result, String> { - let Some(path) = rfd::FileDialog::new().add_filter(tr("Export template"), &["json"]).set_file_name(name).save_file() else { return Ok(None) }; - std::fs::write(&path, json).map_err(|e| e.to_string())?; - Ok(Some(path.display().to_string())) +fn write_json(app: &mut TextureCraftApp, preset: String, name: String, json: String) { + use crate::file_dialogs::{Bound, FileDialog}; + app.ask_file(FileDialog::save().filter(tr("Export template"), &["json"]).file_name(name), Bound::App, move |app, paths| { + let Some(path) = paths.first() else { return }; + match std::fs::write(path, &json) { + Ok(()) => exported(app, &preset, &path.display().to_string()), + Err(e) => export_failed(app, &e), + } + }); } #[cfg(target_arch = "wasm32")] -fn write_json(name: &str, json: &str) -> Result, String> { - crate::web_files::download(name, json.as_bytes())?; - Ok(Some(name.to_string())) +fn write_json(app: &mut TextureCraftApp, preset: String, name: String, json: String) { + match crate::web_files::download(&name, json.as_bytes()) { + Ok(()) => exported(app, &preset, &name), + Err(e) => export_failed(app, &e), + } } /// Read the user's templates: the library folder on the desktop, the app storage on the web. diff --git a/crates/ui-egui/src/file_dialogs.rs b/crates/ui-egui/src/file_dialogs.rs new file mode 100644 index 00000000..3c9df8c0 --- /dev/null +++ b/crates/ui-egui/src/file_dialogs.rs @@ -0,0 +1,111 @@ +//! Native file dialogs that never block the frame (craft-dialogs). +//! +//! An action that needs a path calls [`TextureCraftApp::ask_file`] and returns. The dialog shows at +//! the end of the frame, and the continuation runs with the answer on a later frame. The browser +//! build has no native dialogs (`web_files.rs`). + +use std::panic::Location; +use std::path::PathBuf; +use std::sync::Arc; + +pub use craft_dialogs::{Answer, FileDialog, Override, Request}; + +use crate::TextureCraftApp; +use crate::i18n::{tr, trf}; + +/// Whether an answer still needs the project that was open when the dialog was asked for. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Bound { + /// The continuation reads or changes the open project, and does not run on another one. + Project, + /// The continuation does not depend on the open project. + App, +} + +/// What runs with the answer. The list is empty when nothing was chosen. +type Then = Box)>; + +/// Which dialog was asked for, for which project and by which code. Asking again with all three +/// the same brings the open panel to the front instead of queuing a second one. +#[derive(Clone, Debug, PartialEq)] +struct AskKey { + request: Request, + project: Option, + origin: &'static Location<'static>, +} + +/// A dialog's continuation. +pub struct Asked { + key: AskKey, + then: Then, +} + +/// The app's dialogs and the requests not yet answered. +pub struct FileDialogs { + dialogs: craft_dialogs::Dialogs, + asked: Vec, +} + +impl FileDialogs { + /// The dialogs of the app whose context is `ctx`: an answer wakes its event loop. + pub fn new(ctx: egui::Context) -> FileDialogs { + FileDialogs { dialogs: craft_dialogs::Dialogs::new(Arc::new(move || ctx.request_repaint())), asked: Vec::new() } + } + + /// Answers every request with `answer_with` instead of a native dialog (tests). + pub fn set_override(&mut self, answer_with: Option) { + self.dialogs.set_override(answer_with); + } + + /// Requests that have not been answered yet. + pub fn pending(&self) -> usize { + self.asked.len() + } + + /// Shows the next dialog asked for. Call at the end of every frame with the window. + pub fn show_pending(&mut self, frame: &eframe::Frame) { + self.dialogs.show_pending(Some(frame)); + } +} + +impl TextureCraftApp { + /// Queues `dialog`. `then` runs on a later frame with the chosen paths, or with none after + /// Cancel, after a dialog that could not be shown, and when `bound` is [`Bound::Project`] and + /// another project has been opened since. Returns false, and drops `then`, when the same dialog + /// is already showing or waiting. + #[track_caller] + pub(crate) fn ask_file(&mut self, dialog: FileDialog, bound: Bound, then: impl FnOnce(&mut TextureCraftApp, Vec) + 'static) -> bool { + let project = (bound == Bound::Project).then_some(self.session.project_id); + let key = AskKey { request: Request::File(dialog.clone()), project, origin: Location::caller() }; + if self.file_dialogs.asked.contains(&key) { + self.file_dialogs.dialogs.raise(); + return false; + } + self.file_dialogs.asked.push(key.clone()); + self.file_dialogs.dialogs.ask(dialog, Asked { key, then: Box::new(then) }); + true + } + + /// Runs the continuations of the dialogs that have answered. + pub(crate) fn run_file_dialog_answers(&mut self) { + for (asked, answer) in self.file_dialogs.dialogs.take_answers() { + let Asked { key, then } = asked; + if let Some(i) = self.file_dialogs.asked.iter().position(|k| *k == key) { + self.file_dialogs.asked.remove(i); + } + let paths = match answer { + Answer::Paths(paths) => paths, + Answer::Unavailable(why) => { + self.toast(trf("The file dialog couldn't be shown: {error}", &[("error", &why)]), true); + Vec::new() + } + Answer::Cancelled | Answer::Message(_) => Vec::new(), + }; + let moved_on = key.project.is_some_and(|project| project != self.session.project_id); + if moved_on && !paths.is_empty() { + self.toast(tr("The project changed while the dialog was open, so nothing was done"), true); + } + then(self, if moved_on { Vec::new() } else { paths }); + } + } +} diff --git a/crates/ui-egui/src/gpu.rs b/crates/ui-egui/src/gpu.rs index c6695b34..acdac551 100644 --- a/crates/ui-egui/src/gpu.rs +++ b/crates/ui-egui/src/gpu.rs @@ -11,7 +11,9 @@ use texturecraft_engine::Session; use texturecraft_engine::compose::{DisplayKind, ImageRes, tile_bytes}; use texturecraft_engine::core::BakedMap; use texturecraft_engine::geom::Mesh; -use texturecraft_render::{Frame, Renderer, wgpu}; +use texturecraft_render::{BakeVisualization, Frame, Renderer, wgpu}; + +use crate::bake_scene::{BakeSceneLink, CageUpload}; /// Content shown through the aux texture. #[derive(Clone, Copy, Debug, PartialEq)] @@ -25,6 +27,9 @@ pub enum AuxView { /// A texture set's texels across and down, and its mesh material. pub type SetLayout = ((u32, u32), usize); +/// The low poly's UV seam edges (vertex pairs) per material +pub type UvSeamEdges = Vec>; + /// What the renderer must catch up with before drawing. #[derive(Default)] pub struct SceneSync { @@ -36,6 +41,16 @@ pub struct SceneSync { pub env: Option<(String, Option>)>, pub tiles: Vec<(usize, DisplayKind, u32, u32, Vec)>, pub aux: Vec<(usize, u32, Vec)>, + /// Bake mode's high poly (`None` removes it) and the id it is sent under + pub bake_high: Option<(Option>, u64)>, + /// Which vertices of the high poly (by its id) the bake's rays miss (1) or reach (0) + pub bake_high_missed: Option<(u64, Vec)>, + /// Changed cages: texture set, the cage or `None` to remove it, its topology + pub bake_cages: Vec<(usize, Option, u64)>, + /// Texture sets left after some were removed: their cages go too + pub bake_cage_count: Option, + /// The low poly's UV seams per material, for mesh id + pub uv_seams: Option<(u64, UvSeamEdges)>, } /// Lives in egui's callback resources. @@ -78,6 +93,7 @@ pub struct GpuLink { pub adapter: String, /// Most tiles waiting to be composited since compositing last caught up (progress). composite_total: usize, + bake_scene: BakeSceneLink, } /// Compositing time per frame: a full recomposite of a large texture set spreads over frames. @@ -124,6 +140,7 @@ pub fn init(rs: &egui_wgpu::RenderState, ctx: &egui::Context) -> GpuLink { aux: BTreeMap::new(), adapter: format!("{} ({:?})", info.name, info.backend), composite_total: 0, + bake_scene: BakeSceneLink::default(), } } @@ -133,132 +150,158 @@ impl GpuLink { std::mem::take(&mut *self.reports.lock().unwrap_or_else(PoisonError::into_inner)) } - /// Collect everything the GPU needs this frame (runs the compositor first). + /// Whether bake mode's visualization is still being worked out off the UI thread + pub fn bake_busy(&self) -> bool { + self.bake_scene.busy() + } + /// Compositing progress (0..1) while tiles wait to be composited. pub fn composite_progress(&self, s: &Session) -> Option { let pending = s.pending_tiles(); (pending > 0 && self.composite_total > 0).then(|| 1.0 - pending as f32 / self.composite_total as f32) } - /// `spent_ms`: time this frame already took before the sync. - pub fn sync(&mut self, s: &mut Session, aux_map: Option, shift: u32, spent_ms: f64) -> SceneSync { - let start = crate::now_ms(); + /// Collect everything the GPU needs this frame, running the compositor first: `bake` is what bake mode's 3D view draws besides the low poly, `spent_ms` the time this frame already took + pub fn sync(&mut self, session: &mut Session, aux_map: Option, bake: Option, shift: u32, spent_ms: f64) -> SceneSync { + let start_ms = crate::now_ms(); let mut queued = 0usize; - let left = |queued: usize| FRAME_BUDGET_MS - spent_ms - (crate::now_ms() - start) - queued as f64 * UPLOAD_MS_PER_TILE; - let pending = s.pending_tiles(); + let time_left_ms = |queued: usize| FRAME_BUDGET_MS - spent_ms - (crate::now_ms() - start_ms) - queued as f64 * UPLOAD_MS_PER_TILE; + let pending = session.pending_tiles(); self.composite_total = if pending == 0 { 0 } else { self.composite_total.max(pending) }; - s.update_for(COMPOSITE_BUDGET_MS.min(left(0)).max(MIN_SLICE_MS), crate::now_ms); + session.update_for(COMPOSITE_BUDGET_MS.min(time_left_ms(0)).max(MIN_SLICE_MS), crate::now_ms); + let mut out = SceneSync::default(); if self.lost.swap(false, Ordering::AcqRel) { self.mesh_id = 0; self.sets.clear(); self.env = Default::default(); + self.bake_scene.resend(); self.reset.store(true, Ordering::Release); } - if self.mesh_id != s.mesh_id { - out.mesh = Some((s.mesh.clone(), s.mesh_id)); - self.mesh_id = s.mesh_id; + + if self.mesh_id != session.mesh_id { + out.mesh = Some((session.mesh.clone(), session.mesh_id)); + self.mesh_id = session.mesh_id; self.aux.clear(); } - let sets: Vec = s.doc.project.texture_sets.iter().map(|t| (t.size(), t.material)).collect(); + + let sets: Vec = session.doc.project.texture_sets.iter().map(|texture_set| (texture_set.size(), texture_set.material)).collect(); if sets != self.sets || shift != self.shift || out.mesh.is_some() { - out.sets = Some((sets.clone(), s.mesh.materials.len().max(1), shift)); + out.sets = Some((sets.clone(), session.mesh.materials.len().max(1), shift)); self.sets = sets; self.shift = shift; } - let d = &s.doc.project.display; - let image = d.environment_resource().and_then(|n| s.images.get(n)); - let ptr = image.map_or(0, |i| Arc::as_ptr(i) as usize); - if self.env.0 != d.environment || self.env.1 != ptr { - self.env = (d.environment.clone(), ptr); - out.env = Some((d.environment.clone(), image.cloned())); + + let display = &session.doc.project.display; + let image = display.environment_resource().and_then(|name| session.images.get(name)); + let image_identity = image.map_or(0, |image| Arc::as_ptr(image) as usize); + if self.env.0 != display.environment || self.env.1 != image_identity { + self.env = (display.environment.clone(), image_identity); + out.env = Some((display.environment.clone(), image.cloned())); } + if self.reset.swap(false, Ordering::AcqRel) { - for c in &mut s.caches { - c.upload.extend(texturecraft_engine::compose::all_tiles(c.size.0, c.size.1)); + for cache in &mut session.caches { + cache.upload.extend(texturecraft_engine::compose::all_tiles(cache.size.0, cache.size.1)); } self.aux.clear(); } - for ts in 0..s.caches.len() { - let tiles = s.take_uploads(ts); + + for texture_set in 0..session.caches.len() { + let tiles = session.take_uploads(texture_set); if tiles.is_empty() { continue; } + let mut done = 0; - if let Some(cache) = s.caches.get(ts) { + if let Some(cache) = session.caches.get(texture_set) { let empty = Default::default(); - let baked = s.doc.baked.get(&ts).unwrap_or(&empty); - let comp = &cache.composite; - // In chunks while the frame has time (at least one chunk); the rest waits. + let baked = session.doc.baked.get(&texture_set).unwrap_or(&empty); + let composite = &cache.composite; + // In chunks while the frame has time (at least one chunk); the rest waits for chunk in tiles.chunks(UPLOAD_CHUNK) { let bytes: Vec<_> = chunk .par_iter() - .flat_map_iter(|&(tx, ty)| DisplayKind::ALL.into_iter().map(move |k| (k, tx, ty))) - .map(|(k, tx, ty)| (ts, k, tx, ty, tile_bytes(comp, baked, k, tx, ty))) + .flat_map_iter(|&(tile_x, tile_y)| DisplayKind::ALL.into_iter().map(move |kind| (kind, tile_x, tile_y))) + .map(|(kind, tile_x, tile_y)| (texture_set, kind, tile_x, tile_y, tile_bytes(composite, baked, kind, tile_x, tile_y))) .collect(); queued += bytes.len(); out.tiles.extend(bytes); done += chunk.len(); - if left(queued) < MIN_SLICE_MS { + if time_left_ms(queued) < MIN_SLICE_MS { break; } } } - if let (Some(rest), Some(cache)) = (tiles.get(done..), s.caches.get_mut(ts)) { + if let (Some(rest), Some(cache)) = (tiles.get(done..), session.caches.get_mut(texture_set)) { cache.upload.extend(rest.iter().copied()); } } + match aux_map { - Some(AuxView::MeshMap(m)) => { - for ts in 0..s.caches.len() { - let rev = s.doc.baked.get(&ts).and_then(|b| b.maps.get(&m)).map(|d| Arc::as_ptr(d) as u64).unwrap_or(0); - let key = (format!("{m:?}"), rev); - if self.aux.get(&ts) == Some(&key) { + Some(AuxView::MeshMap(map)) => { + for texture_set in 0..session.caches.len() { + let revision = session.doc.baked.get(&texture_set).and_then(|baked| baked.maps.get(&map)).map(|data| Arc::as_ptr(data) as u64).unwrap_or(0); + let key = (format!("{map:?}"), revision); + if self.aux.get(&texture_set) == Some(&key) { continue; } - let Some(cache) = s.caches.get(ts) else { continue }; + let Some(cache) = session.caches.get(texture_set) else { continue }; - let res = texturecraft_render::aux_size(cache.size); + let resolution = texturecraft_render::aux_size(cache.size); out.aux.push(( - ts, - res, - texturecraft_render::mesh_maps::mesh_map_rgba(s.doc.baked.get(&ts), m, res, cache.size, &cache.composite.block_scales), + texture_set, + resolution, + texturecraft_render::mesh_maps::mesh_map_rgba( + session.doc.baked.get(&texture_set), + map, + resolution, + cache.size, + &cache.composite.block_scales, + ), )); - self.aux.insert(ts, key); + self.aux.insert(texture_set, key); } } Some(AuxView::Mask(id)) => { - if let Some((ts, _, _)) = s.doc.project.locate(id) { - let key = (format!("mask{}", id.0), s.revision); - if self.aux.get(&ts) != Some(&key) && !s.stroke_active() { - let res = s.caches.get(ts).map_or(1024, |c| texturecraft_render::aux_size(c.size)); - if let Some(rgba) = s.mask_view_rgba(id, res) { - out.aux.push((ts, res, rgba)); + if let Some((texture_set, _, _)) = session.doc.project.locate(id) { + let key = (format!("mask{}", id.0), session.revision); + if self.aux.get(&texture_set) != Some(&key) && !session.stroke_active() { + let resolution = + session.caches.get(texture_set).map_or(MASK_VIEW_FALLBACK_RESOLUTION, |cache| texturecraft_render::aux_size(cache.size)); + if let Some(rgba) = session.mask_view_rgba(id, resolution) { + out.aux.push((texture_set, resolution, rgba)); } - self.aux.insert(ts, key); + self.aux.insert(texture_set, key); } } } Some(AuxView::QuickMask) => { - for ts in 0..s.caches.len() { - let Some(cache) = s.caches.get(ts) else { continue }; - let key = (format!("quickmask{}", s.quick_mask.revision), cache.revision); - if self.aux.get(&ts) == Some(&key) { + for texture_set in 0..session.caches.len() { + let Some(cache) = session.caches.get(texture_set) else { continue }; + + let key = (format!("quickmask{}", session.quick_mask.revision), cache.revision); + if self.aux.get(&texture_set) == Some(&key) { continue; } - let res = texturecraft_render::aux_size(cache.size); - if let Some(rgba) = s.quick_mask_rgba(ts, res) { - out.aux.push((ts, res, rgba)); + let resolution = texturecraft_render::aux_size(cache.size); + if let Some(rgba) = session.quick_mask_rgba(texture_set, resolution) { + out.aux.push((texture_set, resolution, rgba)); } - self.aux.insert(ts, key); + self.aux.insert(texture_set, key); } } None => {} } + + self.bake_scene.sync(session, bake, &mut out); out } } +/// Mask view resolution for a texture set without a composite cache +const MASK_VIEW_FALLBACK_RESOLUTION: u32 = 1024; + /// Paint callback for one view. pub struct ViewCallback { pub frame: Frame, @@ -295,39 +338,64 @@ impl CallbackTrait for ViewCallback { if let Some((mesh, id)) = &sync.mesh { gpu.renderer.set_mesh(device, queue, mesh, *id); } - if let Some((sets, mats, shift)) = &sync.sets { + if let Some((sets, material_count, shift)) = &sync.sets { gpu.renderer.set_display_shift(*shift); - let reset = gpu.renderer.set_texture_sets(device, queue, sets, *mats); + let reset = gpu.renderer.set_texture_sets(device, queue, sets, *material_count); if !reset.is_empty() { gpu.reset.store(true, Ordering::Release); } } - for (ts, k, tx, ty, bytes) in &sync.tiles { - gpu.renderer.upload_tile(device, queue, *ts, *k, *tx, *ty, bytes); + for (texture_set, kind, tile_x, tile_y, bytes) in &sync.tiles { + gpu.renderer.upload_tile(device, queue, *texture_set, *kind, *tile_x, *tile_y, bytes); } - for (ts, size, bytes) in &sync.aux { - gpu.renderer.upload_aux(device, queue, *ts, *size, bytes); + for (texture_set, size, bytes) in &sync.aux { + gpu.renderer.upload_aux(device, queue, *texture_set, *size, bytes); + } + if let Some((high, id)) = &sync.bake_high + && let Err(error) = gpu.renderer.set_bake_high(device, queue, high.as_deref(), *id) + { + let mut reports = gpu.reports.lock().unwrap_or_else(PoisonError::into_inner); + if reports.errors.len() < MAX_GPU_ERRORS && !reports.errors.contains(&error) { + reports.errors.push(error); + } + gpu.ctx.request_repaint(); + } + if let Some((id, missed)) = &sync.bake_high_missed { + gpu.renderer.set_bake_high_missed(queue, *id, missed); + } + if let Some(count) = sync.bake_cage_count { + gpu.renderer.truncate_bake_cages(count); + } + for (texture_set, cage, topology) in &sync.bake_cages { + let cage = cage.as_ref().map(|upload| (upload.corners.as_slice(), upload.shell.edges.as_slice())); + gpu.renderer.set_bake_cage(device, queue, *texture_set, cage, *topology); + } + if let Some((mesh_id, seams)) = &sync.uv_seams { + gpu.renderer.set_uv_seams(device, queue, *mesh_id, seams); } } - // Also installs (or rejects) full-size textures WebGPU answered for since last frame. + + // Also installs (or rejects) full-size textures WebGPU answered for since last frame gpu.renderer.prepare(device, queue, encoder, &self.frame); let failed = gpu.renderer.take_memory_failures(); if !failed.is_empty() { - let mut r = gpu.reports.lock().unwrap_or_else(PoisonError::into_inner); - for ts in failed { - if !r.memory.contains(&ts) { - r.memory.push(ts); + let mut reports = gpu.reports.lock().unwrap_or_else(PoisonError::into_inner); + for texture_set in failed { + if !reports.memory.contains(&texture_set) { + reports.memory.push(texture_set); } } - // This frame's report drain already ran: the next frame shows the toast. + // This frame's report drain already ran: the next frame shows the toast gpu.ctx.request_repaint(); } if gpu.renderer.awaiting_gpu() { gpu.ctx.request_repaint(); } - let ppp = screen.pixels_per_point; - let r = self.rect; - gpu.renderer.set_blit_rect(queue, self.frame.view_id, [r.min.x * ppp, r.min.y * ppp, r.width() * ppp, r.height() * ppp], screen.size_in_pixels); + + let pixels_per_point = screen.pixels_per_point; + let rect = self.rect; + let blit_rect = [rect.min.x * pixels_per_point, rect.min.y * pixels_per_point, rect.width() * pixels_per_point, rect.height() * pixels_per_point]; + gpu.renderer.set_blit_rect(queue, self.frame.view_id, blit_rect, screen.size_in_pixels); Vec::new() } diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 80105c00..7ccc1d84 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -134,13 +134,15 @@ pub fn os_language() -> &'static str { locale.map_or("en", |l| language_for_locale(&l)) } +/// Tests that switch the global UI language, or draw the UI under it, run one at a time. +#[cfg(test)] +pub(crate) static TEST_LANGUAGE: std::sync::Mutex<()> = std::sync::Mutex::new(()); + #[cfg(test)] mod tests { + use super::TEST_LANGUAGE as LANGUAGE; use super::*; - /// Tests that switch the global UI language run one at a time. - static LANGUAGE: std::sync::Mutex<()> = std::sync::Mutex::new(()); - /// Every key the UI looks up: `tr("…")` / `trf("…"` literals in the sources, plus the /// static catalogs whose labels are translated where they are shown. fn keys() -> Vec { diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index e651a035..12019c44 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -86,6 +86,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Axis", "المحور"), ("Back to painting", "العودة إلى الرسم"), ("Backface culling", "استبعاد الوجوه الخلفية"), + ("Bake an ID map (F8) to pick colors from the mesh.", "اخبز خريطة المعرّفات ID (F8) لالتقاط الألوان من الشبكة."), ("Bake Mesh Maps", "خبز خرائط المجسم"), ("Bake mesh maps", "خبز خرائط المجسم"), ( @@ -121,6 +122,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in: {mesh}", "مدمج: {mesh}"), ("Cage: {name}", "القفص (Cage): {name}"), ("Camera", "الكاميرا"), + ("Colors", "الألوان"), ("Go to camera 1", "الانتقال إلى الكاميرا 1"), ("Go to camera 2", "الانتقال إلى الكاميرا 2"), ("Go to camera 3", "الانتقال إلى الكاميرا 3"), @@ -138,6 +140,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Channel", "القناة"), ("Channel source: uniform value, procedural, image or anchor", "مصدر القناة: قيمة موحدة، إجرائي، صورة أو نقطة ارتكاز"), ("Channels", "القنوات"), + ("Check for Updates...", "التحقق من وجود تحديثات..."), ("Checker", "رقعة شطرنج"), ("Clamp", "تقييد القيم"), ("Clear", "مسح"), @@ -553,6 +556,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Overlay", "تراكب (Overlay)"), ("Overlay opacity", "عتامة التراكب"), ("PBR - Metallic Roughness (TextureCraft)", "PBR - خشونة ومعدنية (TextureCraft)"), + ("Pick color", "التقاط لون"), ("PNG image", "صورة PNG"), ("Padding", "الحشو (Padding)"), ("Paint", "رسم"), @@ -1037,6 +1041,17 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "إزالة تجاوز الدقة"), ("Texture set resolution", "دقة مجموعة الخامات"), ("UV tile {tile} resolution", "دقة بلاطة UV {tile}"), + ("Advanced settings", "إعدادات متقدمة"), + ("Import baked maps", "استيراد خرائط مخبوزة"), + ("Name each file after its texture set, like Body_normal.png", "سمِّ كل ملف باسم مجموعة الخامات الخاصة به، مثل Body_normal.png"), + ("Add...", "إضافة..."), + ("Baked maps imported: {count}", "الخرائط المخبوزة المستوردة: {count}"), + ("Not imported: {files}", "لم يتم استيرادها: {files}"), + ("Baking Visualization", "تصور الخبز"), + ("Show for Selected Texture Set Only", "العرض لمجموعة الخامات المحددة فقط"), + ("High Definition Mesh (HP)", "المجسم عالي الدقة (HP)"), + ("UV Seams", "فواصل UV"), + ("Project Mesh (LP)", "مجسم الإسقاط (LP)"), ("Edges", "الحواف"), ("Cavities", "التجاويف"), ("Edges and cavities", "الحواف والتجاويف"), @@ -1066,4 +1081,6 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Visible polygons only", "المضلعات المرئية فقط"), ("\"{layer}\" can't be filled: select a paint layer or a layer's mask", "\"{layer}\" لا يمكن تعبئتها: حدد طبقة رسم أو قناع طبقة"), + ("The file dialog couldn't be shown: {error}", "تعذر عرض نافذة الملفات: {error}"), + ("The project changed while the dialog was open, so nothing was done", "تغيّر المشروع أثناء فتح النافذة، لذا لم يُنفَّذ أي إجراء"), ]; diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 52bf1393..dde41825 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -89,6 +89,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Axis", "Achse"), ("Back to painting", "Zurück zum Malen"), ("Backface culling", "Rückseiten-Culling"), + ("Bake an ID map (F8) to pick colors from the mesh.", "Backe eine ID-Map (F8), um Farben vom Mesh aufzunehmen."), ("Bake Mesh Maps", "Mesh-Maps backen"), ("Bake mesh maps", "Mesh-Maps backen"), ("Bake mesh maps (F8) for curvature, AO and thickness based generators.", "Mesh-Maps backen (F8) für Generatoren auf Basis von Krümmung, AO und Dicke."), @@ -121,6 +122,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in: {mesh}", "Integriert: {mesh}"), ("Cage: {name}", "Cage: {name}"), ("Camera", "Kamera"), + ("Colors", "Farben"), ("Go to camera 1", "Zu Kamera 1 wechseln"), ("Go to camera 2", "Zu Kamera 2 wechseln"), ("Go to camera 3", "Zu Kamera 3 wechseln"), @@ -138,6 +140,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Channel", "Kanal"), ("Channel source: uniform value, procedural, image or anchor", "Kanalquelle: einheitlicher Wert, prozedural, Bild oder Anker"), ("Channels", "Kanäle"), + ("Check for Updates...", "Nach Updates suchen..."), ("Checker", "Schachbrett"), ("Clamp", "Begrenzen"), ("Clear", "Leeren"), @@ -586,6 +589,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Overlay", "Ineinanderkopieren"), ("Overlay opacity", "Überlagerungsdeckkraft"), ("PBR - Metallic Roughness (TextureCraft)", "PBR - Metallisch/Rauheit (TextureCraft)"), + ("Pick color", "Farbe aufnehmen"), ("PNG image", "PNG-Bild"), ("Padding", "Padding"), ("Paint", "Malen"), @@ -1080,6 +1084,17 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Auflösungsüberschreibung entfernen"), ("Texture set resolution", "Auflösung des Textursets"), ("UV tile {tile} resolution", "Auflösung der UV-Kachel {tile}"), + ("Advanced settings", "Erweiterte Einstellungen"), + ("Import baked maps", "Gebackene Maps importieren"), + ("Name each file after its texture set, like Body_normal.png", "Benennen Sie jede Datei nach ihrem Texturset, z. B. Body_normal.png"), + ("Add...", "Hinzufügen..."), + ("Baked maps imported: {count}", "Gebackene Maps importiert: {count}"), + ("Not imported: {files}", "Nicht importiert: {files}"), + ("Baking Visualization", "Bake-Visualisierung"), + ("Show for Selected Texture Set Only", "Nur für das ausgewählte Texturset anzeigen"), + ("High Definition Mesh (HP)", "High-Poly-Mesh (HP)"), + ("UV Seams", "UV-Nähte"), + ("Project Mesh (LP)", "Projektions-Mesh (LP)"), ("Edges", "Kanten"), ("Cavities", "Vertiefungen"), ("Edges and cavities", "Kanten und Vertiefungen"), @@ -1112,4 +1127,9 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Visible polygons only", "Nur sichtbare Polygone"), ("\"{layer}\" can't be filled: select a paint layer or a layer's mask", "\"{layer}\" kann nicht gefüllt werden: Wähle eine Malebene oder eine Ebenenmaske"), + ("The file dialog couldn't be shown: {error}", "Der Dateidialog konnte nicht angezeigt werden: {error}"), + ( + "The project changed while the dialog was open, so nothing was done", + "Das Projekt hat sich geändert, während der Dialog geöffnet war, daher wurde nichts ausgeführt", + ), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 8065a348..22f63bc9 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -86,6 +86,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Axis", "Eje"), ("Back to painting", "Volver a pintar"), ("Backface culling", "Descarte de caras traseras"), + ("Bake an ID map (F8) to pick colors from the mesh.", "Hornea un mapa de ID (F8) para tomar colores de la malla."), ("Bake Mesh Maps", "Hornear mapas de malla"), ("Bake mesh maps", "Hornear mapas de malla"), ( @@ -121,6 +122,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in: {mesh}", "Integrada: {mesh}"), ("Cage: {name}", "Jaula: {name}"), ("Camera", "Cámara"), + ("Colors", "Colores"), ("Go to camera 1", "Ir a la cámara 1"), ("Go to camera 2", "Ir a la cámara 2"), ("Go to camera 3", "Ir a la cámara 3"), @@ -138,6 +140,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Channel", "Canal"), ("Channel source: uniform value, procedural, image or anchor", "Origen del canal: valor uniforme, procedural, imagen o anclaje"), ("Channels", "Canales"), + ("Check for Updates...", "Buscar actualizaciones..."), ("Checker", "Damero"), ("Clamp", "Limitar"), ("Clear", "Borrar"), @@ -577,6 +580,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Overlay", "Superponer"), ("Overlay opacity", "Opacidad de superposición"), ("PBR - Metallic Roughness (TextureCraft)", "PBR - Metálico Rugosidad (TextureCraft)"), + ("Pick color", "Tomar color"), ("PNG image", "Imagen PNG"), ("Padding", "Margen"), ("Paint", "Pintar"), @@ -1065,6 +1069,17 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Quitar resolución personalizada"), ("Texture set resolution", "Resolución del conjunto de texturas"), ("UV tile {tile} resolution", "Resolución del mosaico UV {tile}"), + ("Advanced settings", "Ajustes avanzados"), + ("Import baked maps", "Importar mapas horneados"), + ("Name each file after its texture set, like Body_normal.png", "Nombra cada archivo según su conjunto de texturas, p. ej. Body_normal.png"), + ("Add...", "Añadir..."), + ("Baked maps imported: {count}", "Mapas horneados importados: {count}"), + ("Not imported: {files}", "Sin importar: {files}"), + ("Baking Visualization", "Visualización del horneado"), + ("Show for Selected Texture Set Only", "Mostrar solo para el conjunto de texturas seleccionado"), + ("High Definition Mesh (HP)", "Malla de alta resolución (HP)"), + ("UV Seams", "Costuras UV"), + ("Project Mesh (LP)", "Malla de proyección (LP)"), ("Edges", "Bordes"), ("Cavities", "Cavidades"), ("Edges and cavities", "Bordes y cavidades"), @@ -1100,4 +1115,9 @@ pub const TABLE: &[(&str, &str)] = &[ "\"{layer}\" can't be filled: select a paint layer or a layer's mask", "\"{layer}\" no se puede rellenar: selecciona una capa de pintura o una máscara de capa", ), + ("The file dialog couldn't be shown: {error}", "No se pudo mostrar el cuadro de diálogo de archivos: {error}"), + ( + "The project changed while the dialog was open, so nothing was done", + "El proyecto cambió mientras el cuadro de diálogo estaba abierto, así que no se hizo nada", + ), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index b8c882f0..bb25ed8e 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -92,6 +92,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Axis", "Axe"), ("Back to painting", "Retour à la peinture"), ("Backface culling", "Élimination des faces arrière"), + ("Bake an ID map (F8) to pick colors from the mesh.", "Précalculez une carte d'ID (F8) pour prélever des couleurs sur le maillage."), ("Bake Mesh Maps", "Précalculer les cartes de maillage"), ("Bake mesh maps", "Précalculer les cartes de maillage"), ( @@ -127,6 +128,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in: {mesh}", "Intégré : {mesh}"), ("Cage: {name}", "Cage : {name}"), ("Camera", "Caméra"), + ("Colors", "Couleurs"), ("Go to camera 1", "Aller à la caméra 1"), ("Go to camera 2", "Aller à la caméra 2"), ("Go to camera 3", "Aller à la caméra 3"), @@ -144,6 +146,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Channel", "Canal"), ("Channel source: uniform value, procedural, image or anchor", "Source du canal : valeur uniforme, procédural, image ou ancrage"), ("Channels", "Canaux"), + ("Check for Updates...", "Rechercher des mises à jour..."), ("Checker", "Damier"), ("Clamp", "Limiter"), ("Clear", "Effacer"), @@ -592,6 +595,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Overlay", "Incrustation"), ("Overlay opacity", "Opacité de superposition"), ("PBR - Metallic Roughness (TextureCraft)", "PBR - Métallique Rugosité (TextureCraft)"), + ("Pick color", "Prélever une couleur"), ("PNG image", "Image PNG"), ("Padding", "Marge"), ("Paint", "Peinture"), @@ -1089,6 +1093,17 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Supprimer la résolution personnalisée"), ("Texture set resolution", "Résolution de l'ensemble de textures"), ("UV tile {tile} resolution", "Résolution de la tuile UV {tile}"), + ("Advanced settings", "Paramètres avancés"), + ("Import baked maps", "Importer des cartes précalculées"), + ("Name each file after its texture set, like Body_normal.png", "Nommez chaque fichier d'après son ensemble de textures, par ex. Body_normal.png"), + ("Add...", "Ajouter..."), + ("Baked maps imported: {count}", "Cartes précalculées importées : {count}"), + ("Not imported: {files}", "Non importés : {files}"), + ("Baking Visualization", "Visualisation du baking"), + ("Show for Selected Texture Set Only", "Afficher uniquement pour l'ensemble de textures sélectionné"), + ("High Definition Mesh (HP)", "Maillage haute définition (HP)"), + ("UV Seams", "Coutures UV"), + ("Project Mesh (LP)", "Maillage de projection (LP)"), ("Edges", "Arêtes"), ("Cavities", "Cavités"), ("Edges and cavities", "Arêtes et cavités"), @@ -1124,4 +1139,9 @@ pub const TABLE: &[(&str, &str)] = &[ "\"{layer}\" can't be filled: select a paint layer or a layer's mask", "« {layer} » ne peut pas être rempli : sélectionnez un calque de peinture ou un masque de calque", ), + ("The file dialog couldn't be shown: {error}", "Impossible d'afficher la boîte de dialogue de fichiers : {error}"), + ( + "The project changed while the dialog was open, so nothing was done", + "Le projet a changé pendant que la boîte de dialogue était ouverte ; rien n'a été fait", + ), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index c6cfdaf5..a260de48 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -89,6 +89,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Axis", "Asse"), ("Back to painting", "Torna alla pittura"), ("Backface culling", "Culling facce posteriori"), + ("Bake an ID map (F8) to pick colors from the mesh.", "Esegui il bake di una mappa ID (F8) per prelevare i colori dalla mesh."), ("Bake Mesh Maps", "Bake mappe mesh"), ("Bake mesh maps", "Bake mappe mesh"), ( @@ -124,6 +125,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in: {mesh}", "Integrata: {mesh}"), ("Cage: {name}", "Gabbia: {name}"), ("Camera", "Camera"), + ("Colors", "Colori"), ("Go to camera 1", "Vai alla camera 1"), ("Go to camera 2", "Vai alla camera 2"), ("Go to camera 3", "Vai alla camera 3"), @@ -141,6 +143,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Channel", "Canale"), ("Channel source: uniform value, procedural, image or anchor", "Sorgente del canale: valore uniforme, procedurale, immagine o ancoraggio"), ("Channels", "Canali"), + ("Check for Updates...", "Controlla aggiornamenti..."), ("Checker", "Scacchiera"), ("Clamp", "Limita"), ("Clear", "Cancella"), @@ -583,6 +586,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Overlay", "Sovrapponi"), ("Overlay opacity", "Opacità sovrapposizione"), ("PBR - Metallic Roughness (TextureCraft)", "PBR - Metallico Rugosità (TextureCraft)"), + ("Pick color", "Preleva colore"), ("PNG image", "Immagine PNG"), ("Padding", "Padding"), ("Paint", "Pittura"), @@ -1074,6 +1078,17 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Rimuovi risoluzione personalizzata"), ("Texture set resolution", "Risoluzione del set di texture"), ("UV tile {tile} resolution", "Risoluzione del tile UV {tile}"), + ("Advanced settings", "Impostazioni avanzate"), + ("Import baked maps", "Importa mappe bake"), + ("Name each file after its texture set, like Body_normal.png", "Dai a ogni file il nome del suo set di texture, ad es. Body_normal.png"), + ("Add...", "Aggiungi..."), + ("Baked maps imported: {count}", "Mappe bake importate: {count}"), + ("Not imported: {files}", "Non importati: {files}"), + ("Baking Visualization", "Visualizzazione del baking"), + ("Show for Selected Texture Set Only", "Mostra solo per il set di texture selezionato"), + ("High Definition Mesh (HP)", "Mesh ad alta risoluzione (HP)"), + ("UV Seams", "Cuciture UV"), + ("Project Mesh (LP)", "Mesh di proiezione (LP)"), ("Edges", "Bordi"), ("Cavities", "Cavità"), ("Edges and cavities", "Bordi e cavità"), @@ -1109,4 +1124,9 @@ pub const TABLE: &[(&str, &str)] = &[ "\"{layer}\" can't be filled: select a paint layer or a layer's mask", "\"{layer}\" non può essere riempito: seleziona un livello di pittura o una maschera di livello", ), + ("The file dialog couldn't be shown: {error}", "Impossibile mostrare la finestra di dialogo dei file: {error}"), + ( + "The project changed while the dialog was open, so nothing was done", + "Il progetto è cambiato mentre la finestra di dialogo era aperta, quindi non è stato fatto nulla", + ), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index bcecd8df..5538ba67 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -92,6 +92,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Axis", "軸"), ("Back to painting", "ペイントに戻る"), ("Backface culling", "背面カリング"), + ("Bake an ID map (F8) to pick colors from the mesh.", "メッシュから色を拾うには ID マップをベイクしてください (F8)。"), ("Bake Mesh Maps", "メッシュマップのベイク"), ("Bake mesh maps", "メッシュマップをベイク"), ( @@ -127,6 +128,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in: {mesh}", "組み込み: {mesh}"), ("Cage: {name}", "ケージ: {name}"), ("Camera", "カメラ"), + ("Colors", "カラー"), ("Go to camera 1", "カメラ 1 に移動"), ("Go to camera 2", "カメラ 2 に移動"), ("Go to camera 3", "カメラ 3 に移動"), @@ -144,6 +146,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Channel", "チャンネル"), ("Channel source: uniform value, procedural, image or anchor", "チャンネルのソース: 均一値、プロシージャル、画像、アンカー"), ("Channels", "チャンネル"), + ("Check for Updates...", "アップデートを確認..."), ("Checker", "チェッカー"), ("Clamp", "クランプ"), ("Clear", "クリア"), @@ -571,6 +574,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Overlay", "オーバーレイ"), ("Overlay opacity", "オーバーレイの不透明度"), ("PBR - Metallic Roughness (TextureCraft)", "PBR - メタリック/ラフネス (TextureCraft)"), + ("Pick color", "色を拾う"), ("PNG image", "PNG画像"), ("Padding", "パディング"), ("Paint", "ペイント"), @@ -1059,6 +1063,17 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "解像度の上書きを解除"), ("Texture set resolution", "テクスチャセットの解像度"), ("UV tile {tile} resolution", "UVタイル {tile} の解像度"), + ("Advanced settings", "詳細設定"), + ("Import baked maps", "ベイク済みマップを読み込む"), + ("Name each file after its texture set, like Body_normal.png", "各ファイル名をテクスチャセット名で始めてください(例: Body_normal.png)"), + ("Add...", "追加..."), + ("Baked maps imported: {count}", "読み込んだベイク済みマップ: {count}"), + ("Not imported: {files}", "読み込まれなかったファイル: {files}"), + ("Baking Visualization", "ベイクの可視化"), + ("Show for Selected Texture Set Only", "選択したテクスチャセットのみ表示"), + ("High Definition Mesh (HP)", "ハイポリメッシュ (HP)"), + ("UV Seams", "UVシーム"), + ("Project Mesh (LP)", "投影メッシュ (LP)"), ("Edges", "エッジ"), ("Cavities", "くぼみ"), ("Edges and cavities", "エッジとくぼみ"), @@ -1094,4 +1109,6 @@ pub const TABLE: &[(&str, &str)] = &[ "\"{layer}\" can't be filled: select a paint layer or a layer's mask", "「{layer}」は塗りつぶせません: ペイントレイヤーまたはレイヤーマスクを選択してください", ), + ("The file dialog couldn't be shown: {error}", "ファイルダイアログを表示できませんでした: {error}"), + ("The project changed while the dialog was open, so nothing was done", "ダイアログを開いている間にプロジェクトが変更されたため、何も実行されませんでした"), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 6a310a1a..754a7b10 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -89,6 +89,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Axis", "축"), ("Back to painting", "페인팅으로 돌아가기"), ("Backface culling", "후면 컬링"), + ("Bake an ID map (F8) to pick colors from the mesh.", "메시에서 색을 고르려면 ID 맵을 베이크하세요 (F8)."), ("Bake Mesh Maps", "메시 맵 베이크"), ("Bake mesh maps", "메시 맵 베이크"), ("Bake mesh maps (F8) for curvature, AO and thickness based generators.", "곡률, AO, 두께 기반 제너레이터를 사용하려면 메시 맵을 베이크하세요 (F8)."), @@ -121,6 +122,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in: {mesh}", "기본 제공: {mesh}"), ("Cage: {name}", "케이지: {name}"), ("Camera", "카메라"), + ("Colors", "색상"), ("Go to camera 1", "카메라 1 보기"), ("Go to camera 2", "카메라 2 보기"), ("Go to camera 3", "카메라 3 보기"), @@ -138,6 +140,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Channel", "채널"), ("Channel source: uniform value, procedural, image or anchor", "채널 소스: 균일 값, 프로시저럴, 이미지 또는 앵커"), ("Channels", "채널"), + ("Check for Updates...", "업데이트 확인..."), ("Checker", "체커"), ("Clamp", "클램프"), ("Clear", "지우기"), @@ -562,6 +565,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Overlay", "오버레이"), ("Overlay opacity", "오버레이 불투명도"), ("PBR - Metallic Roughness (TextureCraft)", "PBR - 메탈릭 러프니스 (TextureCraft)"), + ("Pick color", "색 고르기"), ("PNG image", "PNG 이미지"), ("Padding", "패딩"), ("Paint", "페인트"), @@ -1047,6 +1051,17 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "해상도 재정의 제거"), ("Texture set resolution", "텍스처 세트 해상도"), ("UV tile {tile} resolution", "UV 타일 {tile} 해상도"), + ("Advanced settings", "고급 설정"), + ("Import baked maps", "베이크된 맵 가져오기"), + ("Name each file after its texture set, like Body_normal.png", "각 파일 이름을 텍스처 세트 이름으로 시작하세요(예: Body_normal.png)"), + ("Add...", "추가..."), + ("Baked maps imported: {count}", "가져온 베이크된 맵: {count}"), + ("Not imported: {files}", "가져오지 않음: {files}"), + ("Baking Visualization", "베이크 시각화"), + ("Show for Selected Texture Set Only", "선택한 텍스처 세트만 표시"), + ("High Definition Mesh (HP)", "하이 폴리 메시 (HP)"), + ("UV Seams", "UV 심"), + ("Project Mesh (LP)", "투영 메시 (LP)"), ("Edges", "가장자리"), ("Cavities", "오목한 부분"), ("Edges and cavities", "가장자리와 오목한 부분"), @@ -1079,4 +1094,6 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Visible polygons only", "보이는 폴리곤만"), ("\"{layer}\" can't be filled: select a paint layer or a layer's mask", "\"{layer}\"은(는) 채울 수 없습니다: 페인트 레이어나 레이어 마스크를 선택하세요"), + ("The file dialog couldn't be shown: {error}", "파일 대화 상자를 표시할 수 없습니다: {error}"), + ("The project changed while the dialog was open, so nothing was done", "대화 상자가 열려 있는 동안 프로젝트가 변경되어 아무 작업도 수행하지 않았습니다"), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index ddee5e62..e5d9a6e9 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -89,6 +89,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Axis", "Eixo"), ("Back to painting", "Voltar à pintura"), ("Backface culling", "Descarte de faces traseiras"), + ("Bake an ID map (F8) to pick colors from the mesh.", "Faça o bake de um mapa de ID (F8) para coletar cores da malha."), ("Bake Mesh Maps", "Bake de mapas de malha"), ("Bake mesh maps", "Fazer bake dos mapas de malha"), ( @@ -124,6 +125,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in: {mesh}", "Embutida: {mesh}"), ("Cage: {name}", "Cage: {name}"), ("Camera", "Câmera"), + ("Colors", "Cores"), ("Go to camera 1", "Ir para a câmera 1"), ("Go to camera 2", "Ir para a câmera 2"), ("Go to camera 3", "Ir para a câmera 3"), @@ -141,6 +143,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Channel", "Canal"), ("Channel source: uniform value, procedural, image or anchor", "Origem do canal: valor uniforme, procedural, imagem ou âncora"), ("Channels", "Canais"), + ("Check for Updates...", "Verificar atualizações..."), ("Checker", "Xadrez"), ("Clamp", "Limitar"), ("Clear", "Limpar"), @@ -574,6 +577,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Overlay", "Sobrepor"), ("Overlay opacity", "Opacidade da sobreposição"), ("PBR - Metallic Roughness (TextureCraft)", "PBR - Metálico Rugosidade (TextureCraft)"), + ("Pick color", "Coletar cor"), ("PNG image", "Imagem PNG"), ("Padding", "Margem"), ("Paint", "Pintura"), @@ -1062,6 +1066,17 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Remover resolução personalizada"), ("Texture set resolution", "Resolução do conjunto de texturas"), ("UV tile {tile} resolution", "Resolução do tile UV {tile}"), + ("Advanced settings", "Configurações avançadas"), + ("Import baked maps", "Importar mapas com bake"), + ("Name each file after its texture set, like Body_normal.png", "Nomeie cada arquivo com o nome do seu conjunto de texturas, como Body_normal.png"), + ("Add...", "Adicionar..."), + ("Baked maps imported: {count}", "Mapas com bake importados: {count}"), + ("Not imported: {files}", "Não importados: {files}"), + ("Baking Visualization", "Visualização do bake"), + ("Show for Selected Texture Set Only", "Mostrar apenas para o conjunto de texturas selecionado"), + ("High Definition Mesh (HP)", "Malha de alta resolução (HP)"), + ("UV Seams", "Costuras UV"), + ("Project Mesh (LP)", "Malha de projeção (LP)"), ("Edges", "Bordas"), ("Cavities", "Cavidades"), ("Edges and cavities", "Bordas e cavidades"), @@ -1097,4 +1112,6 @@ pub const TABLE: &[(&str, &str)] = &[ "\"{layer}\" can't be filled: select a paint layer or a layer's mask", "\"{layer}\" não pode ser preenchida: selecione uma camada de pintura ou uma máscara de camada", ), + ("The file dialog couldn't be shown: {error}", "Não foi possível mostrar a caixa de diálogo de arquivos: {error}"), + ("The project changed while the dialog was open, so nothing was done", "O projeto mudou enquanto a caixa de diálogo estava aberta, então nada foi feito"), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index fc76f759..023ceb72 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -80,6 +80,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Axis", "轴"), ("Back to painting", "返回绘画"), ("Backface culling", "背面剔除"), + ("Bake an ID map (F8) to pick colors from the mesh.", "烘焙 ID 贴图(F8)以从网格上拾取颜色。"), ("Bake Mesh Maps", "烘焙网格贴图"), ("Bake mesh maps", "烘焙网格贴图"), ("Bake mesh maps (F8) for curvature, AO and thickness based generators.", "烘焙网格贴图(F8)以用于基于曲率、AO 和厚度的生成器。"), @@ -112,6 +113,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in: {mesh}", "内置:{mesh}"), ("Cage: {name}", "笼体:{name}"), ("Camera", "相机"), + ("Colors", "颜色"), ("Go to camera 1", "转到相机 1"), ("Go to camera 2", "转到相机 2"), ("Go to camera 3", "转到相机 3"), @@ -129,6 +131,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Channel", "通道"), ("Channel source: uniform value, procedural, image or anchor", "通道来源:统一值、程序纹理、图像或锚点"), ("Channels", "通道"), + ("Check for Updates...", "检查更新..."), ("Checker", "棋盘格"), ("Clamp", "钳制"), ("Clear", "清除"), @@ -526,6 +529,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Overlay", "叠加"), ("Overlay opacity", "叠加层不透明度"), ("PBR - Metallic Roughness (TextureCraft)", "PBR - 金属度/粗糙度(TextureCraft)"), + ("Pick color", "拾取颜色"), ("PNG image", "PNG 图像"), ("Padding", "扩边"), ("Paint", "绘画"), @@ -1005,6 +1009,17 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "移除分辨率覆盖"), ("Texture set resolution", "纹理集分辨率"), ("UV tile {tile} resolution", "UV 图块 {tile} 的分辨率"), + ("Advanced settings", "高级设置"), + ("Import baked maps", "导入已烘焙贴图"), + ("Name each file after its texture set, like Body_normal.png", "以纹理集名称为每个文件命名,例如 Body_normal.png"), + ("Add...", "添加..."), + ("Baked maps imported: {count}", "已导入的烘焙贴图:{count}"), + ("Not imported: {files}", "未导入:{files}"), + ("Baking Visualization", "烘焙可视化"), + ("Show for Selected Texture Set Only", "仅显示所选纹理集"), + ("High Definition Mesh (HP)", "高模网格 (HP)"), + ("UV Seams", "UV 接缝"), + ("Project Mesh (LP)", "投射网格 (LP)"), ("Edges", "边缘"), ("Cavities", "凹陷"), ("Edges and cavities", "边缘和凹陷"), @@ -1028,4 +1043,6 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Visible polygons only", "仅可见多边形"), ("\"{layer}\" can't be filled: select a paint layer or a layer's mask", "“{layer}”无法填充:请选择绘画图层或图层遮罩"), + ("The file dialog couldn't be shown: {error}", "无法显示文件对话框:{error}"), + ("The project changed while the dialog was open, so nothing was done", "对话框打开期间项目已更改,因此未执行任何操作"), ]; diff --git a/crates/ui-egui/src/id_color_pick.rs b/crates/ui-egui/src/id_color_pick.rs new file mode 100644 index 00000000..c4e99a65 --- /dev/null +++ b/crates/ui-egui/src/id_color_pick.rs @@ -0,0 +1,92 @@ +//! Pick mode of a color selection: the next click in the 3D or 2D view adds the ID color under it + +use serde_json::{Value, json}; +use texturecraft_engine::core::{BakedMap, LayerId}; +use texturecraft_engine::{StackTarget, ViewMode}; + +use crate::TextureCraftApp; +use crate::state::Mode; + +/// Height in points of the eyedropper drawn as the pointer while picking +const EYEDROPPER_SIZE: f32 = 20.0; + +/// A color selection waiting for a click, and the view to return to once it comes +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct IdColorPick { + pub effect: LayerId, + /// The color the click replaces; None adds one + pub index: Option, + previous_view: ViewMode, +} + +impl IdColorPick { + /// Waits for a click that picks into `effect`, showing the ID map meanwhile + pub fn start(app: &mut TextureCraftApp, effect: LayerId, index: Option) { + let previous_view = match app.picking_id_color.take() { + Some(running) => running.previous_view, + None => app.session.view, + }; + + app.properties_popup = None; + app.picking_id_color = Some(IdColorPick { effect, index, previous_view }); + app.run("viewport.view", json!({"mode": format!("map:{}", BakedMap::Id.id())})); + } + + /// Leaves pick mode, returning to the earlier view unless the user chose another meanwhile + pub fn end(app: &mut TextureCraftApp) { + let Some(pick) = app.picking_id_color.take() else { return }; + + if app.session.view == ViewMode::MeshMap(BakedMap::Id) { + app.run("viewport.view", view_params(pick.previous_view)); + } + } + + /// Picks at `point` (`x`/`y`/`viewport` or `uv` params) and leaves pick mode + pub fn pick_at(app: &mut TextureCraftApp, point: Value) { + let Some(pick) = app.picking_id_color else { return }; + + let mut params = json!({"effect": pick.effect.0, "index": pick.index}); + if let (Some(target), Some(source)) = (params.as_object_mut(), point.as_object()) { + target.extend(source.clone()); + } + + app.run("effect.colorSelection.pick", params); + IdColorPick::end(app); + } + + /// An eyedropper in place of the pointer while it is over `rect`, its tip on the hotspot + pub fn draw_cursor(ui: &egui::Ui, rect: egui::Rect) { + let Some(pointer) = ui.ctx().pointer_hover_pos().filter(|pointer| rect.contains(*pointer)) else { return }; + + ui.ctx().set_cursor_icon(egui::CursorIcon::None); + + // The glyph's tip is its bottom-left corner; a dark outline keeps it readable on any ID color + let painter = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::unique("id_color_pick_cursor"))); + let font = egui::FontId::proportional(EYEDROPPER_SIZE); + let glyph = egui_phosphor::regular::EYEDROPPER; + for offset in [egui::vec2(-1.0, 0.0), egui::vec2(1.0, 0.0), egui::vec2(0.0, -1.0), egui::vec2(0.0, 1.0)] { + painter.text(pointer + offset, egui::Align2::LEFT_BOTTOM, glyph, font.clone(), egui::Color32::from_black_alpha(220)); + } + painter.text(pointer, egui::Align2::LEFT_BOTTOM, glyph, font, egui::Color32::WHITE); + } + + /// Ends pick mode once its effect is no longer selected or painting mode is left + pub fn end_when_stale(app: &mut TextureCraftApp) { + let Some(pick) = app.picking_id_color else { return }; + + if app.session.target != StackTarget::Effect(pick.effect) || app.ui.mode != Mode::Painting { + IdColorPick::end(app); + } + } +} + +/// The `viewport.view` params that show `view` +fn view_params(view: ViewMode) -> Value { + match view { + ViewMode::Material => json!({"mode": "material"}), + ViewMode::Channel(channel) => json!({"mode": channel.id()}), + ViewMode::MeshMap(map) => json!({"mode": format!("map:{}", map.id())}), + ViewMode::UvChecker => json!({"mode": "uvChecker"}), + ViewMode::Mask(layer) => json!({"mode": "mask", "layer": layer.0}), + } +} diff --git a/crates/ui-egui/src/keymap.rs b/crates/ui-egui/src/keymap.rs index 32b61242..6129dbc7 100644 --- a/crates/ui-egui/src/keymap.rs +++ b/crates/ui-egui/src/keymap.rs @@ -4,12 +4,14 @@ use std::collections::BTreeMap; +use craft_keymap::egui::Dispatcher; +use craft_keymap::{Active, Bindable, Chord, CommandRef, ConflictKind, KeyInput, Layout, Lookup, Mods, Overrides, Platform, Scope, Scopes}; use egui::{Event, Id, Key, KeyboardShortcut, Modifiers, RichText, vec2}; use egui_phosphor::regular as ic; use crate::TextureCraftApp; use crate::i18n::{tr, trf}; -use crate::menus::{CATALOG, parse_shortcut}; +use crate::menus::CATALOG; use crate::theme::Tokens; use crate::widgets::{icon_button, section}; @@ -64,7 +66,18 @@ pub fn tip(keymap: &Keymap, label: &str, id: &str) -> String { } } -/// "Ctrl+Shift+E" notation (the inverse of `menus::parse_shortcut`). +/// craft-keymap's text of a shortcut: "Ctrl" here is the command modifier (Cmd on macOS), which the +/// crate writes "Cmd". +fn crate_text(text: &str) -> String { + text.split('+').map(|part| if part == "Ctrl" { "Cmd" } else { part }).collect::>().join("+") +} + +/// Read "Ctrl+Shift+E" notation. +pub fn parse(text: &str) -> Option { + Chord::parse(&crate_text(text)).ok() +} + +/// "Ctrl+Shift+E" notation (the inverse of [`parse`]). pub fn format_shortcut(sc: &KeyboardShortcut) -> String { let m = sc.modifiers; let mut s = String::new(); @@ -81,27 +94,118 @@ pub fn format_shortcut(sc: &KeyboardShortcut) -> String { s } -fn modifier_count(m: Modifiers) -> u8 { - u8::from(m.command || m.ctrl || m.mac_cmd) + u8::from(m.shift) + u8::from(m.alt) +/// Every bound shortcut as egui's shortcut type. +fn active(keymap: &Keymap) -> Vec { + bindings().iter().filter_map(|b| Some(parse(shortcut(keymap, b)?)?.to_egui_shortcut())).collect() } -/// Every bound shortcut with its item id, most modifiers first: egui ignores extra Shift and -/// Alt when matching, so Shift+C has to be tried before C. -pub fn active(keymap: &Keymap) -> Vec<(&'static str, KeyboardShortcut)> { - let mut v: Vec<(&'static str, KeyboardShortcut)> = bindings().iter().filter_map(|b| Some((b.id, parse_shortcut(shortcut(keymap, b)?)?))).collect(); - v.sort_by_key(|(_, sc)| std::cmp::Reverse(modifier_count(sc.modifiers))); - v +/// The catalog as craft-keymap sees it, in `bindings()` order: the first one listed wins a shared +/// shortcut. +fn catalog() -> Vec { + bindings() + .iter() + .map(|b| { + let item = Bindable::new(b.id, b.label, Scope::app()); + match b.default.and_then(parse) { + Some(chord) => item.with_default(craft_keymap::Binding::new(chord)), + None => item, + } + }) + .collect() } -/// Each binding's parsed shortcut, in `bindings()` order. -pub fn resolve(keymap: &Keymap) -> Vec> { - bindings().iter().map(|b| shortcut(keymap, b).and_then(parse_shortcut)).collect() +/// craft-keymap's text of a stored shortcut. A symbol that needs Shift is looked up without it, so +/// "Shift+Colon" is ":". +fn override_text(text: &str) -> String { + match parse(text) { + Some(chord) => Layout::new().resolve(&KeyInput::new(chord.mods).with_typed(chord.key)).unwrap_or(chord).to_string(), + None => crate_text(text), + } } -/// Another binding with the same shortcut as binding `i`. -pub fn conflict(resolved: &[Option], i: usize) -> Option { - let sc = resolved.get(i).copied().flatten()?; - resolved.iter().enumerate().position(|(j, o)| j != i && *o == Some(sc)) +/// The stored shortcuts as craft-keymap overrides ("" = no shortcut). +fn overrides(keymap: &Keymap) -> Overrides { + let mut out = Overrides::new(); + for (id, text) in keymap { + let texts = if text.is_empty() { Vec::new() } else { vec![override_text(text)] }; + // Only an overlong id or text is refused, and neither can be a shortcut. + let _ = out.insert(id.clone(), texts); + } + out +} + +/// The keymap with `keymap`'s shortcuts for `platform`. +fn resolved(keymap: &Keymap, platform: Platform) -> craft_keymap::Keymap { + craft_keymap::Keymap::new(catalog(), Scopes::new(), platform).with_overrides(overrides(keymap)) +} + +/// The resolved keymap and the dispatcher that runs it against each frame's keys. +pub struct Bindings { + stored: Keymap, + map: craft_keymap::Keymap, + dispatcher: Dispatcher, +} + +impl Default for Bindings { + fn default() -> Bindings { + let stored = Keymap::new(); + let map = resolved(&stored, Platform::current()); + // Held keys repeat their command. Copy, Cut and Paste events count as Ctrl+C, X and V. + Bindings { stored, map, dispatcher: Dispatcher::new().with_repeat(true).with_clipboard_events(true) } + } +} + +impl Bindings { + /// Follows the stored shortcuts and the platform; a no-op while neither changed. + pub(crate) fn sync(&mut self, keymap: &Keymap, platform: Platform) { + if self.stored != *keymap || self.map.platform() != platform { + self.stored = keymap.clone(); + self.map = resolved(keymap, platform); + } + } + + /// The ids of the commands this frame's key presses run, in press order. The presses are + /// removed from the input. + pub(crate) fn dispatch(&mut self, input: &mut egui::InputState) -> Vec { + self.dispatcher.dispatch(input, &self.map, &Active::NONE).into_iter().map(|hit| hit.command.id).collect() + } + + /// The id of the command a key press outside the main window runs. The press is matched as + /// the main window's presses are. + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn command_of(&self, press: &Event) -> Option { + let input = KeyInput::from_egui(press, self.map.platform())?; + self.dispatcher.layout().candidates(&input).into_iter().find_map(|chord| match self.map.lookup(&chord, false, &Active::NONE) { + Lookup::Run(command) => Some(command.id), + Lookup::Cycle(commands) => commands.into_iter().next().map(|command| command.id), + _ => None, + }) + } + + /// The shortcut a press records: the chord it runs, keeping the held Ctrl and Cmd as they are. + fn recorded(&self, press: &Event, key: Key, modifiers: Modifiers, platform: Platform) -> KeyboardShortcut { + let chord = KeyInput::from_egui(press, platform).and_then(|input| self.dispatcher.layout().resolve(&input)); + match chord { + Some(chord) => KeyboardShortcut::new(Modifiers { shift: chord.mods.shift, ..modifiers }, chord.to_egui_shortcut().logical_key), + None => KeyboardShortcut::new(modifiers, key), + } + } + + /// Whether a Shift-only Cut or Paste, read as Shift+Delete or Shift+Insert, runs nothing. + pub(crate) fn shift_clipboard_is_free(&self, event: &Event) -> bool { + let key = match event { + Event::Cut => craft_keymap::Key::Delete, + Event::Paste(_) => craft_keymap::Key::Insert, + _ => return false, + }; + matches!(self.map.lookup(&Chord::new(Mods::SHIFT, key), false, &Active::NONE), Lookup::None) + } + + /// Another binding on the same shortcut as `b`. + fn conflict(&self, b: &Binding) -> Option<&'static Binding> { + let clash = self.map.conflicts_with(&CommandRef::new(b.id)).into_iter().find(|c| c.kind == ConflictKind::Clash)?; + bindings().iter().find(|x| x.id == clash.b.0.id) + } } /// Bind `b` to `value` ("" = no shortcut); the default is stored as no override. @@ -127,7 +231,6 @@ pub fn sync_captured(keymap: &Keymap) { let clipboard = [Key::C, Key::V, Key::X]; let keys: Vec = active(keymap) .into_iter() - .map(|(_, sc)| sc) .filter(|sc| { let fkey = sc.logical_key.name().strip_prefix('F').is_some_and(|n| n.parse::().is_ok()); (sc.modifiers.command || sc.modifiers.alt || fkey) && !(sc.modifiers.command && !sc.modifiers.shift && clipboard.contains(&sc.logical_key)) @@ -151,10 +254,11 @@ pub fn capturing(ctx: &egui::Context) -> bool { } /// The first key press this frame as a shortcut. -fn pressed(ctx: &egui::Context) -> Option { +fn pressed(ctx: &egui::Context, bindings: &Bindings) -> Option { + let platform = craft_keymap::egui::platform(ctx); ctx.input(|i| { i.events.iter().find_map(|e| match e { - Event::Key { key, pressed: true, modifiers, .. } => Some(KeyboardShortcut::new(*modifiers, *key)), + Event::Key { key, pressed: true, modifiers, .. } => Some(bindings.recorded(e, *key, *modifiers, platform)), _ => None, }) }) @@ -169,7 +273,7 @@ pub fn window(app: &mut TextureCraftApp, ctx: &egui::Context) { let capture_id = Id::unique(CAPTURE); let filter_id = Id::unique("keymap_filter"); let mut capture: Option = ctx.data(|d| d.get_temp(capture_id)); - if let (Some(i), Some(sc)) = (capture, pressed(ctx)) { + if let (Some(i), Some(sc)) = (capture, pressed(ctx, &app.bindings)) { if (sc.logical_key != Key::Escape || !sc.modifiers.is_none()) && let Some(b) = bindings().get(i) { @@ -177,10 +281,10 @@ pub fn window(app: &mut TextureCraftApp, ctx: &egui::Context) { } capture = None; } + app.bindings.sync(&app.ui.keymap, craft_keymap::egui::platform(ctx)); let mut filter: String = ctx.data(|d| d.get_temp(filter_id)).unwrap_or_default(); let mut open = true; crate::windows::window("keyboard_shortcuts", tr("Keyboard shortcuts"), &mut open).default_width(480.0).show(ctx, |ui| { - let resolved = resolve(&app.ui.keymap); ui.horizontal(|ui| { ui.label(RichText::new(ic::MAGNIFYING_GLASS).color(tk.text_dim)); ui.add(egui::TextEdit::singleline(&mut filter).hint_text(tr("Search commands or keys")).desired_width(300.0)); @@ -190,7 +294,7 @@ pub fn window(app: &mut TextureCraftApp, ctx: &egui::Context) { } }); }); - let clashes = (0..resolved.len()).filter(|i| conflict(&resolved, *i).is_some()).count(); + let clashes = bindings().iter().filter(|b| app.bindings.conflict(b).is_some()).count(); if clashes > 0 { ui.label( RichText::new(format!("{} {}", ic::WARNING, trf("{n} items share a shortcut; the first one listed wins.", &[("n", &clashes)]))) @@ -220,7 +324,7 @@ pub fn window(app: &mut TextureCraftApp, ctx: &egui::Context) { } let bound = current.is_some(); ui.horizontal(|ui| { - if let Some(other) = conflict(&resolved, i).and_then(|j| bindings().get(j)) { + if let Some(other) = app.bindings.conflict(b) { ui.label(RichText::new(ic::WARNING).color(tk.danger)) .on_hover_text(trf("Also bound to {item} ({menu})", &[("item", &tr(other.label)), ("menu", &tr(other.group))])); } @@ -300,48 +404,154 @@ mod tests { fn shortcuts_round_trip_through_parse_and_format() { for b in bindings() { if let Some(s) = b.default { - let sc = parse_shortcut(s).unwrap_or_else(|| panic!("{} has an unparsable shortcut {s}", b.id)); - assert_eq!(format_shortcut(&sc), s); + let chord = parse(s).unwrap_or_else(|| panic!("{} has an unparsable shortcut {s}", b.id)); + assert_eq!(format_shortcut(&chord.to_egui_shortcut()), s); } } for s in ["Ctrl+Shift+Alt+F12", "Alt+OpenBracket", "Shift+Delete", "Ctrl+9"] { - assert_eq!(parse_shortcut(s).map(|sc| format_shortcut(&sc)).as_deref(), Some(s)); + assert_eq!(parse(s).map(|chord| format_shortcut(&chord.to_egui_shortcut())).as_deref(), Some(s)); } - assert!(parse_shortcut("Ctrl+").is_none() && parse_shortcut("Ctrl+NoSuchKey").is_none()); + assert!(parse("Ctrl+").is_none() && parse("Ctrl+NoSuchKey").is_none()); + } + + fn bindings_for(keymap: &Keymap) -> Bindings { + let mut out = Bindings::default(); + out.sync(keymap, Platform::Windows); + out + } + + fn binding(id: &str) -> &'static Binding { + bindings().iter().find(|b| b.id == id).unwrap() } #[test] fn default_shortcuts_do_not_conflict() { - let resolved = resolve(&Keymap::new()); - for (i, b) in bindings().iter().enumerate() { - assert!(conflict(&resolved, i).is_none(), "{} shares its default shortcut", b.id); + let resolved = bindings_for(&Keymap::new()); + for b in bindings() { + assert!(resolved.conflict(b).is_none(), "{} shares its default shortcut", b.id); } } #[test] fn rebinding_detects_conflicts_and_resets() { - let all = bindings(); - let save = all.iter().position(|b| b.id == "file.save").unwrap(); - let undo = all.iter().position(|b| b.id == "edit.undo").unwrap(); + let (save, undo) = (binding("file.save"), binding("edit.undo")); let mut keymap = Keymap::new(); - rebind(&mut keymap, &all[save], "Ctrl+Z"); - let resolved = resolve(&keymap); - assert_eq!(conflict(&resolved, save), Some(undo)); - assert_eq!(conflict(&resolved, undo), Some(save)); + rebind(&mut keymap, save, "Ctrl+Z"); + let resolved = bindings_for(&keymap); + assert_eq!(resolved.conflict(save).map(|b| b.id), Some("edit.undo")); + assert_eq!(resolved.conflict(undo).map(|b| b.id), Some("file.save")); assert_eq!(shortcut_of(&keymap, "file.save"), Some("Ctrl+Z")); // Unbinding clears the conflict; binding back to the default drops the override. - rebind(&mut keymap, &all[save], ""); + rebind(&mut keymap, save, ""); assert_eq!(shortcut_of(&keymap, "file.save"), None); - assert!(conflict(&resolve(&keymap), undo).is_none()); - rebind(&mut keymap, &all[save], "Ctrl+S"); + assert!(bindings_for(&keymap).conflict(undo).is_none()); + rebind(&mut keymap, save, "Ctrl+S"); assert!(keymap.is_empty()); } + fn press(key: Key, modifiers: Modifiers) -> Event { + Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers } + } + + fn press_at(key: Key, physical: Key, modifiers: Modifiers) -> Event { + Event::Key { key, physical_key: Some(physical), pressed: true, repeat: false, modifiers } + } + + fn dispatched(bindings: &mut Bindings, events: Vec, modifiers: Modifiers) -> Vec { + let mut input = egui::InputState::default(); + input.modifiers = modifiers; + input.events = events; + bindings.dispatch(&mut input) + } + #[test] - fn specific_shortcuts_are_tried_first() { - let active = active(&Keymap::new()); - let pos = |id: &str| active.iter().position(|(x, _)| *x == id).unwrap(); - assert!(pos("viewport.previousChannel") < pos("viewport.nextChannel")); - assert!(pos("file.saveAs") < pos("file.save")); + fn a_stored_shortcut_on_a_shifted_symbol_runs_on_that_press() { + for (stored, key, physical, modifiers) in [ + ("Shift+Colon", Key::Colon, Key::Semicolon, Modifiers::SHIFT), + ("Shift+Exclamationmark", Key::Exclamationmark, Key::Num1, Modifiers::SHIFT), + ("Shift+Questionmark", Key::Questionmark, Key::Slash, Modifiers::SHIFT), + ("Ctrl+Shift+Plus", Key::Plus, Key::Equals, Modifiers::COMMAND | Modifiers::SHIFT), + ] { + let mut keymap = Keymap::new(); + keymap.insert("file.save".into(), stored.into()); + let mut resolved = bindings_for(&keymap); + assert_eq!(dispatched(&mut resolved, vec![press_at(key, physical, modifiers)], modifiers), ["file.save"], "{stored}"); + assert_eq!(resolved.command_of(&press_at(key, physical, modifiers)).as_deref(), Some("file.save"), "{stored} in a floating panel"); + } + } + + #[test] + fn a_recorded_shifted_symbol_is_the_chord_it_runs() { + let resolved = bindings_for(&Keymap::new()); + let recorded = |key, physical, modifiers| format_shortcut(&resolved.recorded(&press_at(key, physical, modifiers), key, modifiers, Platform::Windows)); + assert_eq!(recorded(Key::Colon, Key::Semicolon, Modifiers::SHIFT), "Colon"); + // The layout needs Shift for this slash; the key at that position is not a symbol. + assert_eq!(recorded(Key::Slash, Key::Num7, Modifiers::SHIFT), "Slash"); + assert_eq!(recorded(Key::E, Key::E, Modifiers::COMMAND | Modifiers::SHIFT), "Ctrl+Shift+E"); + } + + #[test] + fn a_floating_panel_matches_presses_as_the_main_window_does() { + let mut keymap = Keymap::new(); + keymap.insert("file.save".into(), "Equals".into()); + let resolved = bindings_for(&keymap); + assert_eq!(resolved.command_of(&press(Key::Plus, Modifiers::NONE)).as_deref(), Some("file.save"), "+ stands for ="); + } + + #[test] + fn a_floating_panel_leaves_a_bound_shift_insert_to_its_binding() { + let paste = || Event::Paste("text".into()); + let free = bindings_for(&Keymap::new()); + let event = crate::menus::forwarded_press(&free, paste(), Modifiers::SHIFT); + assert_eq!(free.command_of(&event).as_deref(), Some("layer.paste")); + let mut keymap = Keymap::new(); + keymap.insert("file.save".into(), "Shift+Insert".into()); + keymap.insert("file.saveAs".into(), "Shift+Delete".into()); + let bound = bindings_for(&keymap); + let event = crate::menus::forwarded_press(&bound, paste(), Modifiers::SHIFT); + assert_eq!(bound.command_of(&event).as_deref(), Some("file.save")); + let event = crate::menus::forwarded_press(&bound, Event::Cut, Modifiers::SHIFT); + assert_eq!(bound.command_of(&event).as_deref(), Some("file.saveAs")); + } + + #[test] + fn a_press_runs_the_command_bound_to_exactly_that_chord() { + let resolved = bindings_for(&Keymap::new()); + let run = |mods: Modifiers, key: Key| resolved.command_of(&press(key, mods)); + assert_eq!(run(Modifiers::COMMAND, Key::S).as_deref(), Some("file.save")); + assert_eq!(run(Modifiers::COMMAND | Modifiers::SHIFT, Key::S).as_deref(), Some("file.saveAs")); + assert_eq!(run(Modifiers::SHIFT, Key::C).as_deref(), Some("viewport.previousChannel")); + assert_eq!(run(Modifiers::NONE, Key::C).as_deref(), Some("viewport.nextChannel")); + assert_eq!(run(Modifiers::ALT, Key::C), None, "Alt+C is not bound"); + assert_eq!(run(Modifiers::SHIFT, Key::M), None, "Shift+M is not bound"); + } + + #[test] + fn a_stored_shortcut_replaces_the_default_and_an_empty_one_unbinds() { + let mut keymap = Keymap::new(); + keymap.insert("file.save".into(), "F5".into()); + keymap.insert("edit.undo".into(), String::new()); + let resolved = bindings_for(&keymap); + assert_eq!(resolved.command_of(&press(Key::F5, Modifiers::NONE)).as_deref(), Some("file.save")); + assert_eq!(resolved.command_of(&press(Key::S, Modifiers::COMMAND)), None); + assert_eq!(resolved.command_of(&press(Key::Z, Modifiers::COMMAND)), None); + } + + #[test] + fn ctrl_in_the_notation_is_the_command_key_on_macos() { + let mut resolved = Bindings::default(); + resolved.sync(&Keymap::new(), Platform::Mac); + let cmd = Modifiers { mac_cmd: true, command: true, ..Modifiers::NONE }; + assert_eq!(resolved.command_of(&press(Key::S, cmd)).as_deref(), Some("file.save")); + assert_eq!(resolved.command_of(&press(Key::S, Modifiers::CTRL)), None, "the Control key is another key"); + } + + #[test] + fn the_first_item_listed_wins_a_shared_shortcut() { + let mut keymap = Keymap::new(); + keymap.insert("file.save".into(), "Ctrl+Z".into()); + let resolved = bindings_for(&keymap); + let first = bindings().iter().find(|b| matches!(b.id, "file.save" | "edit.undo")).unwrap().id; + assert_eq!(resolved.command_of(&press(Key::Z, Modifiers::COMMAND)).as_deref(), Some(first)); } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 00bc0524..77c0aa19 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -8,18 +8,24 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] pub mod bake_mode; +mod bake_scene; +mod color_selection_editor; pub mod control; pub mod dock; pub mod docking; pub mod export_templates; +#[cfg(not(target_arch = "wasm32"))] +pub mod file_dialogs; mod filter_slot; pub mod fonts; pub mod gpu; pub mod i18n; +pub mod id_color_pick; pub mod keymap; mod mask_preview_image; mod material_preview_image; pub mod menus; +pub mod new_project_advanced; mod orb_shape; pub mod parity; mod preview_image; @@ -38,6 +44,10 @@ pub mod theme; pub mod thumbs; pub mod titlebar; pub mod toolbar; +pub mod ui_state_store; +#[cfg(not(target_arch = "wasm32"))] +pub(crate) mod updates_ui; +pub mod uv_paint_point; pub mod viewport; pub mod web_files; pub mod widgets; @@ -54,6 +64,14 @@ use texturecraft_engine::bake::Progress; pub use control::ControlRequest; pub use state::UiState; +/// The app as the updater knows it: its releases, and the icon and color of its update prompt. +#[cfg(not(target_arch = "wasm32"))] +pub const UPDATE_APP: craft_update::App = craft_update::App { + icon_png: Some(include_bytes!("../../../assets/app-icon/hicolor/128x128/apps/ai.storyteller.texturecraft.png")), + accent: Some([0xc2, 0x67, 0x2b]), + ..craft_update::App::new("texturecraft", "TextureCraft", "3D texture painting", "storytold/texturecraft") +}; + /// A texture set resize running on a worker thread (`Session::resize_task`). pub struct ResizeJob { pub progress: Arc, @@ -91,6 +109,8 @@ pub struct TextureCraftApp { /// A smooth move to a saved camera in progress. camera_glide: Option, pub ui: UiState, + /// Where `ui` is saved between runs + ui_store: ui_state_store::UiStateStore, pub gpu: Option, pub control: Option>, pub toasts: Vec, @@ -115,10 +135,14 @@ pub struct TextureCraftApp { pub profiler: profile::Profiler, /// Where the last 3D stroke ended (viewport pixels), for Shift+click straight lines. pub last_paint_point: Option, + /// The last finished 2D stroke's endpoint, scoped to its mesh and texture set for Shift+click lines + pub last_paint_uv: Option, /// The decal layer the next click in the 3D view places. pub placing_decal: Option, /// The Properties popup a right click in a view opens. pub properties_popup: Option, + /// The color selection the next click in the 3D or 2D view picks an ID color for + pub picking_id_color: Option, /// The wgpu state (screenshots read the renderer's targets). pub render_state: Option, /// CJK fallback fonts for the UI language. @@ -135,26 +159,46 @@ pub struct TextureCraftApp { styled: Option<(theme::Brightness, theme::Accent)>, /// Whether the window had focus last frame. focused: bool, + /// The update check and prompt (desktop only). + #[cfg(not(target_arch = "wasm32"))] + pub(crate) updates_rt: updates_ui::Runtime, + /// Native file dialogs and their continuations (desktop only). + #[cfg(not(target_arch = "wasm32"))] + pub file_dialogs: file_dialogs::FileDialogs, + /// The unsaved-changes dialog's Save is waiting on the Save dialog's answer. + #[cfg(not(target_arch = "wasm32"))] + pub(crate) saving_for_prompt: bool, + /// That Save dialog saved the project; the prompt goes on at its next frame. + #[cfg(not(target_arch = "wasm32"))] + pub(crate) prompt_saved: bool, + /// The resolved keymap and its key dispatcher. + pub(crate) bindings: keymap::Bindings, } impl TextureCraftApp { + /// The app around `session`, with the saved UI state (or defaults in the OS language) and the GPU viewport. pub fn new(cc: &eframe::CreationContext<'_>, session: Session) -> TextureCraftApp { theme::install(&cc.egui_ctx); - // Bakes cast their rays on a GPU device of their own (created on the first bake). + + // Bakes cast their rays on a GPU device of their own (created on the first bake) #[cfg(not(target_arch = "wasm32"))] texturecraft_engine::bake::install_gpu_tracer(Arc::new(texturecraft_render::gpu_bake::GpuBaker::new())); - let gpu = cc.wgpu_render_state.as_ref().map(|rs| gpu::init(rs, &cc.egui_ctx)); - // The first run speaks the OS (or browser) language. - let ui = cc.storage.and_then(|s| eframe::get_value::(s, "ui")).unwrap_or_else(|| { + let gpu = cc.wgpu_render_state.as_ref().map(|render_state| gpu::init(render_state, &cc.egui_ctx)); + + // The first run speaks the OS (or browser) language + let mut ui_store = ui_state_store::UiStateStore::new(ui_state_store::FILE.get().cloned()); + let ui = ui_store.load(cc.storage).unwrap_or_else(|| { let mut ui = UiState::default(); ui.prefs.language = i18n::os_language().into(); ui }); let next_autosave = ui.prefs.autosave_minutes as f64 * 60.0; + let mut app = TextureCraftApp { camera_glide: None, session, ui, + ui_store, gpu, control: None, toasts: Vec::new(), @@ -171,8 +215,10 @@ impl TextureCraftApp { brushes: None, render: render_mode::RenderView::default(), last_paint_point: None, + last_paint_uv: None, placing_decal: None, properties_popup: None, + picking_id_color: None, render_state: cc.wgpu_render_state.clone(), fonts: fonts::UiFonts::default(), banner: None, @@ -181,22 +227,36 @@ impl TextureCraftApp { next_autosave, styled: None, focused: true, + #[cfg(not(target_arch = "wasm32"))] + updates_rt: updates_ui::Runtime::default(), + #[cfg(not(target_arch = "wasm32"))] + file_dialogs: file_dialogs::FileDialogs::new(cc.egui_ctx.clone()), + #[cfg(not(target_arch = "wasm32"))] + saving_for_prompt: false, + #[cfg(not(target_arch = "wasm32"))] + prompt_saved: false, + bindings: keymap::Bindings::default(), }; app.ui.rename = None; app.ui.windows.new_project = false; i18n::set_language(&app.ui.prefs.language); + app.report_ui_storage_warning(); export_templates::load_library(&mut app, cc.storage); + #[cfg(not(target_arch = "wasm32"))] { - // The first window of the process fixes it; a new folder applies on restart. + // The first window of the process fixes it; a new folder applies on restart let _ = DATA_FOLDER.set(data_folder(&app.ui.prefs.data_folder)); - // An export folder still at the default follows the data folder. + + // An export folder still at the default follows the data folder if app.ui.export.dir == data_folder("").join("export").display().to_string() { app.ui.export.dir = user_dir("export").display().to_string(); } + let skipped = app.session.load_templates(user_dir("templates")); - app.session.log.extend(skipped.into_iter().map(|w| format!("Project template skipped: {w}"))); + app.session.log.extend(skipped.into_iter().map(|warning| format!("Project template skipped: {warning}"))); } + app } @@ -219,6 +279,13 @@ impl TextureCraftApp { } } + fn report_ui_storage_warning(&mut self) { + if let Some(warning) = self.ui_store.take_warning() { + self.session.log.push(warning.clone()); + self.toast_sticky(warning); + } + } + pub fn toast(&mut self, text: impl Into, error: bool) { self.toasts.push(Toast { text: text.into(), error, until: self.last_time + if error { 6.0 } else { 3.0 } }); } @@ -486,7 +553,8 @@ impl eframe::App for TextureCraftApp { } fn save(&mut self, storage: &mut dyn eframe::Storage) { - eframe::set_value(storage, "ui", &self.ui); + self.ui_store.save(&self.ui, storage); + self.report_ui_storage_warning(); export_templates::save_library(self, storage); } @@ -505,6 +573,8 @@ impl eframe::App for TextureCraftApp { } self.step_camera_glide(ctx); control::poll(self, ctx); + #[cfg(not(target_arch = "wasm32"))] + self.run_file_dialog_answers(); web_files::poll(self); let dropped = ctx.input(|i| i.raw.dropped_files.clone()); for f in &dropped { @@ -532,6 +602,9 @@ impl eframe::App for TextureCraftApp { web_files::sync_unsaved(self); } self.fonts.update(ctx, i18n::current().code, self.ui.windows.settings); + #[cfg(not(target_arch = "wasm32"))] + updates_ui::tick(self, ctx); + self.bindings.sync(&self.ui.keymap, craft_keymap::egui::platform(ctx)); menus::shortcuts(self, ctx); // A stored path being edited repaints its sublayer as its points, brush or material change. if let Err(e) = self.session.path_live() { @@ -541,9 +614,12 @@ impl eframe::App for TextureCraftApp { profile::drive(self, ctx); self.toasts.retain(|t| t.until > now); self.profiler.logic_ms = (now_ms() - t0) as f32; + // Last, so it sees every close request this frame's work made. + windows::close_request(self, ctx); } - fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) { + #[cfg_attr(target_arch = "wasm32", allow(unused_variables))] + fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { let ctx = ui.ctx().clone(); let t0 = now_ms(); if !self.ui.hide_ui { @@ -559,10 +635,14 @@ impl eframe::App for TextureCraftApp { let hide = self.ui.hide_ui; let tk = theme::Tokens::get(&ctx); // The dock keeps the cards' gutter from the bars and rails around it. - let frame = if hide { egui::Frame::NONE.fill(tk.viewport) } else { egui::Frame::NONE.fill(tk.chrome).inner_margin(theme::GUTTER) }; - egui::CentralPanel::default().frame(frame).show(ui, |ui| if hide { viewport::central(self, ui) } else { docking::show(self, ui) }); + let panel_frame = if hide { egui::Frame::NONE.fill(tk.viewport) } else { egui::Frame::NONE.fill(tk.chrome).inner_margin(theme::GUTTER) }; + egui::CentralPanel::default().frame(panel_frame).show(ui, |ui| if hide { viewport::central(self, ui) } else { docking::show(self, ui) }); windows::show(self, &ctx); + #[cfg(not(target_arch = "wasm32"))] + updates_ui::show(self, &ctx); toasts(self, &ctx); + #[cfg(not(target_arch = "wasm32"))] + self.file_dialogs.show_pending(frame); let end = now_ms(); let dt = (end - t0) as f32; self.ui_ms = if self.ui_ms == 0.0 { dt } else { self.ui_ms * 0.9 + dt * 0.1 }; diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 3f645eeb..df5be69c 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -2,7 +2,7 @@ //! texture-painting workflow, with stable ids; an item is live when the engine (or the shell, for `ui.*` ids) implements //! its id. The same catalog drives `docs/parity.md`. -use egui::{Key, KeyboardShortcut, Modifiers}; +use egui::{Key, Modifiers}; use serde_json::{Value, json}; use crate::TextureCraftApp; @@ -100,6 +100,8 @@ pub const CATALOG: &[Item] = &[ it("Help", "Report a bug...", "ui.help.bug", None), sep("Help"), it("Help", "Show log...", "ui.view.log", None), + #[cfg(not(target_arch = "wasm32"))] + it("Help", "Check for Updates...", "ui.help.checkForUpdates", None), it("Help", "About TextureCraft...", "ui.about", None), ]; @@ -165,6 +167,8 @@ pub fn invoke(app: &mut TextureCraftApp, ctx: &egui::Context, id: &str) { "ui.layout.2d" => app.ui.layout = ViewLayout::Only2D, "ui.help.shortcuts" => app.ui.windows.shortcuts = true, "ui.about" => app.ui.windows.about = true, + #[cfg(not(target_arch = "wasm32"))] + "ui.help.checkForUpdates" => crate::updates_ui::request_check(app, ctx), "ui.help.discord" => ctx.open_url(egui::OpenUrl::new_tab("https://discord.gg/artcraft")), "ui.help.website" => ctx.open_url(egui::OpenUrl::new_tab("https://getartcraft.com/apps/texturecraft")), "ui.help.docs" => ctx.open_url(egui::OpenUrl::new_tab("https://github.com/storytold/texturecraft#readme")), @@ -178,21 +182,6 @@ pub fn invoke(app: &mut TextureCraftApp, ctx: &egui::Context, id: &str) { } } -/// Parse "Ctrl+Shift+E" style shortcuts. -pub fn parse_shortcut(s: &str) -> Option { - let mut mods = Modifiers::NONE; - let mut key = None; - for part in s.split('+') { - match part { - "Ctrl" | "Cmd" => mods |= Modifiers::COMMAND, - "Shift" => mods |= Modifiers::SHIFT, - "Alt" => mods |= Modifiers::ALT, - k => key = Key::from_name(k), - } - } - key.map(|k| KeyboardShortcut::new(mods, k)) -} - /// The menus, then the mode label at the right of `ui` (the strip `titlebar::show` lays out). pub fn menu_bar(app: &mut TextureCraftApp, ui: &mut egui::Ui) { let tk = Tokens::get(ui.ctx()); @@ -279,18 +268,35 @@ fn menu_item(app: &mut TextureCraftApp, ctx: &egui::Context, ui: &mut egui::Ui, /// Keys pressed in a floating panel's own OS window run the shortcuts the main window's keys do. #[cfg(not(target_arch = "wasm32"))] pub fn forwarded_shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context, events: Vec, held: Modifiers) { - if crate::keymap::capturing(ctx) { + if crate::keymap::capturing(ctx) || crate::updates_ui::blocks_input(app) { return; } - let active = crate::keymap::active(&app.ui.keymap); + app.bindings.sync(&app.ui.keymap, craft_keymap::egui::platform(ctx)); for event in events { - let event = clipboard_key(&event, held).unwrap_or(event); - let egui::Event::Key { key, pressed: true, repeat: false, modifiers, .. } = event else { continue }; - let Some((id, _)) = active.iter().find(|(_, sc)| sc.logical_key == key && modifiers.matches_logically(sc.modifiers)) else { continue }; - invoke(app, ctx, effect_command(app, id)); + let event = forwarded_press(&app.bindings, event, held); + if !matches!(event, egui::Event::Key { pressed: true, repeat: false, .. }) { + continue; + } + let Some(id) = app.bindings.command_of(&event) else { continue }; + invoke(app, ctx, effect_command(app, &id)); } } +/// The press a floating panel's event stands for. Cut and Paste with Shift alone are Shift+Delete +/// and Shift+Insert when something is bound to them, and clipboard shortcuts otherwise. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn forwarded_press(bindings: &crate::keymap::Bindings, event: egui::Event, held: Modifiers) -> egui::Event { + let shift_key = match event { + egui::Event::Cut => Some(Key::Delete), + egui::Event::Paste(_) => Some(Key::Insert), + _ => None, + }; + if let Some(key) = shift_key.filter(|_| shift_only(held) && !bindings.shift_clipboard_is_free(&event)) { + return egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: held }; + } + clipboard_key(&event, held).unwrap_or(event) +} + /// Layer shortcuts act on the selected effect instead of its layer (copy, cut, duplicate, /// remove), and paste a copied effect onto the selection. fn effect_command<'a>(app: &TextureCraftApp, id: &'a str) -> &'a str { @@ -310,25 +316,35 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { if crate::keymap::capturing(ctx) || (ctx.memory(|memory| memory.focused().is_some()) && ctx.egui_wants_keyboard_input()) { return; } - - ctx.input_mut(|input| { - let keys: Vec<_> = input.events.iter().filter_map(|event| clipboard_key(event, input.modifiers)).collect(); - input.events.extend(keys); - }); - - if !ctx.input(|input| input.events.iter().any(|event| matches!(event, egui::Event::Key { pressed: true, .. }))) { + #[cfg(not(target_arch = "wasm32"))] + if crate::updates_ui::blocks_input(app) { return; } + // The dispatcher reads Copy, Cut and Paste as their chords. A pasted image is Ctrl+V here, and + // Shift+Delete and Shift+Insert (Cut and Paste on Windows) are Ctrl+X and Ctrl+V unless + // something is bound to them. + ctx.input_mut(|input| { + let held = input.modifiers; + let aliases: Vec<_> = input + .events + .iter() + .filter(|event| matches!(event, egui::Event::PasteImage(_)) || (shift_only(held) && app.bindings.shift_clipboard_is_free(event))) + .filter_map(|event| clipboard_key(event, held)) + .collect(); + input.events.extend(aliases); + }); + // Escape closes an open popup first, before the Properties popup or the stroke let popup_open = egui::Popup::is_any_open(ctx); - let active_shortcuts = crate::keymap::active(&app.ui.keymap); - let mut commands_to_invoke: Vec<&str> = Vec::new(); - ctx.input_mut(|input| { - for (id, shortcut) in &active_shortcuts { - if input.consume_shortcut(shortcut) { - commands_to_invoke.push(*id); + let commands_to_invoke = ctx.input_mut(|input| { + // egui's label selection copies on these events at the end of the frame + let copies: Vec<_> = input.events.iter().filter(|event| matches!(event, egui::Event::Copy | egui::Event::Cut)).cloned().collect(); + let commands = app.bindings.dispatch(input); + for copy in copies { + if !input.events.contains(©) { + input.events.push(copy); } } @@ -343,15 +359,18 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { if !popup_open && app.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { app.properties_popup = None; + } else if !popup_open && app.picking_id_color.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { + crate::id_color_pick::IdColorPick::end(app); } else if app.ui.mode == Mode::Painting && !popup_open && input.consume_key(Modifiers::NONE, Key::Escape) { app.session.cancel_stroke(); app.session.tool.path.points.clear(); app.session.tool.path.editing = None; } + commands }); - for id in commands_to_invoke { - if matches!(id, "layer.copy" | "layer.cut") + for id in &commands_to_invoke { + if matches!(id.as_str(), "layer.copy" | "layer.cut") && let Some(layer) = app.session.selected_layer().and_then(|layer| app.session.doc.project.layers.get(&layer)) { // Ctrl+V reaches the app only while the system clipboard holds text or an image @@ -371,5 +390,11 @@ fn clipboard_key(event: &egui::Event, held: Modifiers) -> Option { egui::Event::Paste(_) | egui::Event::PasteImage(_) => Key::V, _ => return None, }; - Some(egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: held | Modifiers::COMMAND }) + let modifiers = if shift_only(held) { Modifiers::COMMAND } else { held | Modifiers::COMMAND }; + Some(egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }) +} + +/// Shift alone is held: a clipboard event that came from Shift+Delete or Shift+Insert. +fn shift_only(held: Modifiers) -> bool { + held.shift && !(held.command || held.ctrl || held.mac_cmd || held.alt) } diff --git a/crates/ui-egui/src/new_project_advanced.rs b/crates/ui-egui/src/new_project_advanced.rs new file mode 100644 index 00000000..3247fc8e --- /dev/null +++ b/crates/ui-egui/src/new_project_advanced.rs @@ -0,0 +1,163 @@ +//! New project ▸ Advanced settings: the normal map format, and baked map files imported at creation + +use std::collections::BTreeSet; + +use egui::{RichText, Sense, Ui, vec2}; +use serde_json::{Value, json}; +use texturecraft_engine::core::NormalFormat; + +use crate::TextureCraftApp; +use crate::i18n::{tr, trf}; +use crate::state::NewProject; +use crate::theme::{Tokens, caption}; +use crate::widgets::{section, section_chevron}; +use crate::windows::file_dialogs_available; + +/// Labels of every New project form row, so Basic and Advanced share one label column +const FORM_LABELS: [&str; 6] = ["3D mesh", "Project template", "Document resolution", "UV tiles (UDIM)", "Name", "Normal map format"]; + +/// Each normal map format with its command id and label +const NORMAL_FORMATS: [(NormalFormat, &str, &str); 2] = [(NormalFormat::OpenGl, "openGl", "OpenGL"), (NormalFormat::DirectX, "directX", "DirectX")]; + +/// Width of the dialog's dropdowns +pub(crate) const COMBO_WIDTH: f32 = 200.0; + +/// Width of the Add... and Clear buttons +const FILE_BUTTON_WIDTH: f32 = 96.0; + +/// Tallest the list of added files grows before it scrolls +const FILE_LIST_HEIGHT: f32 = 160.0; + +/// Width of the widest form label, for the label column of every form grid in the dialog +pub(crate) fn form_label_width(ui: &Ui) -> f32 { + let font = egui::TextStyle::Body.resolve(ui.style()); + FORM_LABELS.iter().map(|label| ui.painter().layout_no_wrap(tr(label).to_string(), font.clone(), egui::Color32::WHITE).size().x).fold(0.0, f32::max) +} + +/// The collapsible Advanced settings section (closed until opened) +pub(crate) fn advanced_settings(app: &mut TextureCraftApp, ui: &mut Ui) { + let id = ui.make_persistent_id("np_advanced"); + let mut state = egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, false); + let header = ui + .horizontal(|ui| { + ui.add(egui::Label::new(section_chevron(ui, state.is_open())).selectable(false)); + ui.add(egui::Label::new(caption(tr("Advanced settings"))).selectable(false)); + }) + .response + .interact(Sense::click()); + if header.clicked() { + state.toggle(ui); + } + + state.show_body_unindented(ui, |ui| { + egui::Grid::new("np_advanced_grid").num_columns(2).spacing(vec2(12.0, 8.0)).min_col_width(form_label_width(ui)).show(ui, |ui| { + ui.label(tr("Normal map format")); + normal_format_combo(app, ui); + ui.end_row(); + }); + if file_dialogs_available() { + ui.add_space(4.0); + section(ui, "np_baked_maps", tr("Import baked maps"), false, |ui| { + if baked_maps(&mut app.ui.new_project, ui) { + ask_baked_map_files(app); + } + }); + } + }); +} + +fn normal_format_combo(app: &mut TextureCraftApp, ui: &mut Ui) { + let new_project = &mut app.ui.new_project; + let template_format = app.session.template(&new_project.template).map(|template| template.normal_format).unwrap_or_default(); + let current = new_project.normal_format.unwrap_or(template_format); + let current_label = NORMAL_FORMATS.iter().find(|(format, _, _)| *format == current).map_or("", |(_, _, label)| label); + egui::ComboBox::from_id_salt("np_normal_format").width(COMBO_WIDTH).selected_text(current_label).show_ui(ui, |ui| { + for (format, _, label) in NORMAL_FORMATS { + if ui.selectable_label(format == current, label).clicked() { + new_project.normal_format = Some(format); + } + } + }); +} + +/// The baked map list and its buttons; true when Add was clicked. +fn baked_maps(new_project: &mut NewProject, ui: &mut Ui) -> bool { + let tokens = Tokens::get(ui.ctx()); + let mut add = false; + ui.horizontal(|ui| { + let buttons_width = 2.0 * FILE_BUTTON_WIDTH + ui.spacing().item_spacing.x; + let hint_width = (ui.available_width() - buttons_width - ui.spacing().item_spacing.x).max(0.0); + ui.allocate_ui_with_layout(vec2(hint_width, 0.0), egui::Layout::left_to_right(egui::Align::Center), |ui| { + ui.set_min_width(hint_width); + ui.add(egui::Label::new(RichText::new(tr("Name each file after its texture set, like Body_normal.png")).color(tokens.text_dim)).wrap()); + }); + if ui.add(egui::Button::new(tr("Add...")).min_size(vec2(FILE_BUTTON_WIDTH, 0.0))).clicked() { + add = true; + } + if ui.add_enabled(!new_project.baked_maps.is_empty(), egui::Button::new(tr("Clear")).min_size(vec2(FILE_BUTTON_WIDTH, 0.0))).clicked() { + new_project.baked_maps.clear(); + } + }); + if new_project.baked_maps.is_empty() { + return add; + } + + ui.add_space(4.0); + egui::ScrollArea::vertical().max_height(FILE_LIST_HEIGHT).auto_shrink([false, true]).show(ui, |ui| { + for path in &new_project.baked_maps { + ui.add(egui::Label::new(file_name(path)).truncate()).on_hover_text(path.as_str()); + } + }); + add +} + +/// List picked baked map files (files already listed are skipped) +pub fn add_baked_map_files(new_project: &mut NewProject, paths: Vec) { + for path in paths { + if !new_project.baked_maps.contains(&path) { + new_project.baked_maps.push(path); + } + } +} + +/// After creation: set the normal format, import the listed baked maps (one undo step), toast the outcome; a failed import keeps the list +pub(crate) fn apply_after_create(app: &mut TextureCraftApp, new_project: &NewProject) { + let chosen_format = new_project.normal_format.filter(|format| *format != app.session.doc.project.normal_format); + if let Some((_, id, _)) = chosen_format.and_then(|chosen| NORMAL_FORMATS.iter().find(|(format, _, _)| *format == chosen)) { + app.run("textureSet.settings", json!({ "normalFormat": id })); + } + if new_project.baked_maps.is_empty() { + return; + } + + let files: Vec = new_project.baked_maps.iter().map(|path| json!({ "path": path })).collect(); + let Some(result) = app.run("textureSet.meshMap.import", json!({ "files": files })) else { + return; + }; + + let assigned = result["assigned"].as_array().into_iter().flatten(); + let maps: BTreeSet<(u64, &str)> = assigned.filter_map(|entry| Some((entry["ts"].as_u64()?, entry["map"].as_str()?))).collect(); + let not_imported: Vec = result["unmatched"].as_array().into_iter().flatten().filter_map(Value::as_str).map(file_name).collect(); + let mut text = trf("Baked maps imported: {count}", &[("count", &maps.len())]); + if !not_imported.is_empty() { + text.push('\n'); + text.push_str(&trf("Not imported: {files}", &[("files", ¬_imported.join(", "))])); + } + app.toast(text, !not_imported.is_empty()); + app.ui.new_project.baked_maps.clear(); +} + +fn file_name(path: &str) -> String { + std::path::Path::new(path).file_name().map_or_else(|| path.to_string(), |name| name.to_string_lossy().into_owned()) +} + +#[cfg(not(target_arch = "wasm32"))] +fn ask_baked_map_files(app: &mut TextureCraftApp) { + use crate::file_dialogs::{Bound, FileDialog}; + app.ask_file(FileDialog::open_many().filter(tr("Images"), crate::web_files::IMAGE_EXTS), Bound::App, |app, files| { + add_baked_map_files(&mut app.ui.new_project, files.into_iter().map(|path| path.display().to_string()).collect()); + }); +} + +#[cfg(target_arch = "wasm32")] +fn ask_baked_map_files(_app: &mut TextureCraftApp) {} diff --git a/crates/ui-egui/src/render_mode.rs b/crates/ui-egui/src/render_mode.rs index 8228f51a..80248a32 100644 --- a/crates/ui-egui/src/render_mode.rs +++ b/crates/ui-egui/src/render_mode.rs @@ -611,11 +611,14 @@ fn save(app: &mut TextureCraftApp) { let name = format!("{}_render.png", texturecraft_engine::formats::export::sanitize_file_stem(&app.session.doc.project.name)); #[cfg(not(target_arch = "wasm32"))] { - let Some(path) = rfd::FileDialog::new().add_filter(tr("PNG image"), &["png"]).set_file_name(name).save_file() else { return }; - match std::fs::write(&path, png) { - Ok(()) => app.toast(trf("Saved {path}", &[("path", &path.display())]), false), - Err(e) => app.toast(trf("Couldn't save the render: {error}", &[("error", &e)]), true), - } + use crate::file_dialogs::{Bound, FileDialog}; + app.ask_file(FileDialog::save().filter(tr("PNG image"), &["png"]).file_name(name), Bound::App, move |app, paths| { + let Some(path) = paths.first() else { return }; + match std::fs::write(path, &png) { + Ok(()) => app.toast(trf("Saved {path}", &[("path", &path.display())]), false), + Err(e) => app.toast(trf("Couldn't save the render: {error}", &[("error", &e)]), true), + } + }); } #[cfg(target_arch = "wasm32")] match crate::web_files::download(&name, &png) { diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 0a9f6033..3b25125f 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -1,7 +1,7 @@ //! UI state (serde, so the control channel can read and drive it). use serde::{Deserialize, Serialize}; -use texturecraft_engine::core::{BakedMap, Channel}; +use texturecraft_engine::core::{BakedMap, Channel, NormalFormat}; use crate::docking::Dock; use crate::keymap::Keymap; @@ -151,6 +151,12 @@ pub struct NewProject { /// Name typed to save the current project's settings as a template. #[serde(skip)] pub template_name: String, + /// Normal map format of the project and its imported normal maps; None keeps the template's + #[serde(default)] + pub normal_format: Option, + /// Baked map files to import at creation, matched to sets and mesh maps by name (desktop only) + #[serde(skip)] + pub baked_maps: Vec, } fn default_template() -> String { @@ -167,6 +173,8 @@ impl Default for NewProject { uv_tiles: None, template: default_template(), template_name: String::new(), + normal_format: None, + baked_maps: Vec::new(), } } } @@ -296,6 +304,9 @@ pub struct UiState { /// The brush that paints the skew correction map in the 2D view of bake mode. #[serde(default)] pub bake_paint_brush: crate::bake_mode::BakePaintBrush, + /// What bake mode's 3D view draws besides the low poly (the Baking Visualization panel) + #[serde(default)] + pub bake_visualization: crate::bake_mode::BakeVisualizationToggles, } impl UiState { @@ -365,6 +376,7 @@ impl Default for UiState { recent: Vec::new(), keymap: Keymap::new(), bake_paint_brush: crate::bake_mode::BakePaintBrush::default(), + bake_visualization: crate::bake_mode::BakeVisualizationToggles::default(), } } } @@ -429,35 +441,13 @@ mod tests { } } - /// The app's own settings store: eframe keeps `UiState` as RON text under a key - #[derive(Default)] - struct MemoryStorage(std::collections::HashMap); - - impl eframe::Storage for MemoryStorage { - fn get_string(&self, key: &str) -> Option { - self.0.get(key).cloned() - } - - fn set_string(&mut self, key: &str, value: String) { - self.0.insert(key.to_string(), value); - } - - fn remove_string(&mut self, key: &str) { - self.0.remove(key); - } - - fn flush(&mut self) {} - } - #[test] fn the_bake_layout_survives_a_restart_whichever_mode_was_open() { for mode in [Mode::Painting, Mode::Baking] { let mut ui = UiState { mode, ..UiState::default() }; ui.sync_mode_dock(); - let mut storage = MemoryStorage::default(); - eframe::set_value(&mut storage, "ui", &ui); - let mut restarted: UiState = eframe::get_value(&storage, "ui").unwrap(); + let mut restarted = crate::ui_state_store::tests::restart(&ui); restarted.sync_mode_dock(); let bake_dock = if mode == Mode::Baking { &restarted.dock } else { &restarted.inactive_mode_dock }; assert_eq!(*bake_dock, Dock::for_baking(), "{mode:?}"); diff --git a/crates/ui-egui/src/ui_state_store.rs b/crates/ui-egui/src/ui_state_store.rs new file mode 100644 index 00000000..dcce58df --- /dev/null +++ b/crates/ui-egui/src/ui_state_store.rs @@ -0,0 +1,618 @@ +//! The UI state kept between runs as JSON: `ui.json` beside eframe's settings on the desktop, a key of eframe's storage on the web + +use std::path::{Path, PathBuf}; +use std::sync::OnceLock; + +use crate::UiState; + +/// eframe storage key of the UI state as JSON, where there is no file +const STORAGE_KEY: &str = "ui.json"; + +/// Name of the UI state in eframe's storage, before the extension, for the copies of unreadable states kept there +const STORAGE_STEM: &str = "ui"; + +/// eframe storage key under which earlier builds kept the UI state, as RON +const RON_STORAGE_KEY: &str = "ui"; + +/// Maximum encoded UI state size for both reads and writes; typical states are a few kilobytes +const MAX_FILE_BYTES: u64 = 16 * 1024 * 1024; + +/// Copies of unreadable saved states kept before saving stops +const MAX_UNREADABLE_COPIES: u32 = 10; + +/// The desktop's `ui.json`, set by the app before its window opens; unset, the state stays in eframe's storage +pub static FILE: OnceLock = OnceLock::new(); + +/// Where the UI state is saved, holding a saved state this build could not fully read until it is kept beside it +#[derive(Default)] +pub struct UiStateStore { + file: Option, + /// A saved state this build could not fully read and its file extension, kept by the next save + unreadable: Option<(Vec, &'static str)>, + /// A saved state could not be read or kept, so it is left as it is + frozen: bool, + warning: Option, + last_warning: Option, +} + +impl UiStateStore { + /// The store at `file`, or in eframe's storage without one + pub fn new(file: Option) -> Self { + UiStateStore { file, ..Self::default() } + } + + /// The saved UI state, else the one an earlier build saved; a state not fully read is kept for the next save + pub fn load(&mut self, storage: Option<&dyn eframe::Storage>) -> Option { + let saved = match &self.file { + Some(file) => match read_bytes(file) { + Ok(bytes) => Some(bytes), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => None, + Err(error) => { + self.frozen = true; + self.warn(&format!( + "Settings could not be read: {error}. Saving is disabled for this session. Back up the settings, check access and restart." + )); + return None; + } + }, + None => storage.and_then(|storage| storage.get_string(STORAGE_KEY)).map(String::into_bytes), + }; + let Some(bytes) = saved else { return self.load_ron(storage?) }; + + if bytes.len() as u64 > MAX_FILE_BYTES { + self.frozen = true; + self.warn("Settings exceed the 16 MiB limit. Saving is disabled for this session. Back up the settings and reduce their size before restarting."); + return None; + } + + let ui = serde_json::from_slice::(&bytes).ok(); + if !ui.as_ref().is_some_and(fully_read) { + self.unreadable = Some((bytes, "json")); + } + ui + } + + /// Preserve the original RON when decoding loses either dock, even if other settings load + fn load_ron(&mut self, storage: &dyn eframe::Storage) -> Option { + let text = storage.get_string(RON_STORAGE_KEY)?; + let ui = eframe::get_value::(storage, RON_STORAGE_KEY); + if !ui.as_ref().is_some_and(fully_read) { + self.unreadable = Some((text.into_bytes(), "ron")); + } + ui + } + + /// Save `ui` as JSON once an unreadable saved state is kept, and drop the RON copy of earlier builds + pub fn save(&mut self, ui: &UiState, storage: &mut dyn eframe::Storage) { + if self.frozen { + return; + } + + let json = match serde_json::to_string_pretty(ui) { + Ok(json) => json, + Err(error) => { + self.warn(&format!("Settings could not be encoded: {error}. The previous settings have been kept.")); + return; + } + }; + if json.len() as u64 > MAX_FILE_BYTES { + self.warn("Settings were not saved because they exceed the 16 MiB limit. Reduce their size and try again. The previous settings have been kept."); + return; + } + + // JSON turns non-finite numbers into null; a dock can also silently fall back during decoding + if !serde_json::from_str::(&json).as_ref().is_ok_and(fully_read) { + self.warn( + "Settings were not saved because they would not read back. Reset invalid view settings and try again. The previous settings have been kept.", + ); + return; + } + + if let Some((bytes, extension)) = self.unreadable.take() + && !self.keep_unreadable(&bytes, extension, storage) + { + self.frozen = true; + self.warn("The previous settings could not be backed up. Saving is disabled for this session. Check free space and access, move existing unreadable backups to a safe place, then restart."); + return; + } + + let saved = match &self.file { + Some(file) => write_file(file, json.as_bytes()), + None => write_storage(storage, STORAGE_KEY, json), + }; + if saved { + storage.remove_string(RON_STORAGE_KEY); + self.warning = None; + self.last_warning = None; + } else { + self.warn("Settings could not be saved. Check free space and write access, or browser storage permissions and quota. The previous settings have been kept; saving will be retried."); + } + } + + /// A new storage warning for the app to show once, until saving succeeds again + pub fn take_warning(&mut self) -> Option { + self.warning.take() + } + + fn warn(&mut self, detail: &str) { + let location = self.file.as_ref().map_or_else(|| "browser/app storage".to_owned(), |file| file.display().to_string()); + let warning = format!("UI settings ({location}): {detail}"); + if self.last_warning.as_ref() != Some(&warning) { + log::warn!("{warning}"); + self.warning = Some(warning.clone()); + self.last_warning = Some(warning); + } + } + + /// Keep a saved state this build could not fully read under the first free copy name, beside the file or in storage + fn keep_unreadable(&self, bytes: &[u8], extension: &str, storage: &mut dyn eframe::Storage) -> bool { + match &self.file { + Some(file) => keep_file_copy(file, bytes, extension), + None => { + let free = (1..=MAX_UNREADABLE_COPIES).map(|n| unreadable_name(STORAGE_STEM, n, extension)).find(|key| storage.get_string(key).is_none()); + let Some(key) = free else { return false }; + + write_storage(storage, &key, String::from_utf8_lossy(bytes).into_owned()) + } + } + } +} + +/// The UI state saved in `file`, if it reads +pub fn read(file: &Path) -> Option { + serde_json::from_slice(&read_bytes(file).ok()?).ok() +} + +/// eframe's browser storage reports write failures only through logging, so verify before discarding old settings +fn write_storage(storage: &mut dyn eframe::Storage, key: &str, text: String) -> bool { + storage.set_string(key, text.clone()); + storage.get_string(key).as_deref() == Some(text.as_str()) +} + +#[cfg(not(target_arch = "wasm32"))] +fn read_bytes(file: &Path) -> std::io::Result> { + use std::io::Read as _; + + let input = std::fs::File::open(file)?; + let too_large = || std::io::Error::new(std::io::ErrorKind::InvalidData, "UI settings exceed the 16 MiB limit"); + if input.metadata()?.len() > MAX_FILE_BYTES { + return Err(too_large()); + } + + // Bound the read itself in case the file grows after its metadata was checked + let mut bytes = Vec::new(); + input.take(MAX_FILE_BYTES + 1).read_to_end(&mut bytes)?; + if bytes.len() as u64 > MAX_FILE_BYTES { + return Err(too_large()); + } + + Ok(bytes) +} + +#[cfg(target_arch = "wasm32")] +fn read_bytes(_file: &Path) -> std::io::Result> { + Err(std::io::Error::new(std::io::ErrorKind::Unsupported, "UI settings use browser storage")) +} + +/// Whether both docks were read rather than replaced by a default +fn fully_read(ui: &UiState) -> bool { + !ui.dock.replaced_unreadable() && !ui.inactive_mode_dock.replaced_unreadable() +} + +/// The `n`th copy name of an unreadable state: `.unreadable.`, then `.unreadable-N.` +fn unreadable_name(stem: &str, n: u32, extension: &str) -> String { + if n == 1 { format!("{stem}.unreadable.{extension}") } else { format!("{stem}.unreadable-{n}.{extension}") } +} + +#[cfg(not(target_arch = "wasm32"))] +fn write_file(file: &Path, bytes: &[u8]) -> bool { + if let Some(folder) = file.parent() { + let _ = std::fs::create_dir_all(folder); + } + + texturecraft_engine::formats::write_atomic(file, bytes).is_ok() +} + +#[cfg(target_arch = "wasm32")] +fn write_file(_file: &Path, _bytes: &[u8]) -> bool { + false +} + +/// Copy `bytes` beside `file` under the first free copy name +#[cfg(not(target_arch = "wasm32"))] +fn keep_file_copy(file: &Path, bytes: &[u8], extension: &str) -> bool { + use std::io::Write as _; + + let stem = file.file_stem().map(|stem| stem.to_string_lossy().into_owned()).unwrap_or_default(); + for n in 1..=MAX_UNREADABLE_COPIES { + let copy_file = file.with_file_name(unreadable_name(&stem, n, extension)); + match std::fs::OpenOptions::new().write(true).create_new(true).open(copy_file) { + Ok(mut copy) => return copy.write_all(bytes).is_ok(), + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {} + Err(_) => return false, + } + } + false +} + +#[cfg(target_arch = "wasm32")] +fn keep_file_copy(_file: &Path, _bytes: &[u8], _extension: &str) -> bool { + false +} + +#[cfg(test)] +mod memory_storage; + +#[cfg(test)] +pub(crate) mod tests { + use super::memory_storage::MemoryStorage; + use super::*; + use crate::docking::{Dock, Panel, default_workspace, permissions}; + use craft_ui::docking::{Action, Placement}; + + /// Save `ui` and load it back, as closing and reopening the app does + pub(crate) fn restart(ui: &UiState) -> UiState { + let mut storage = MemoryStorage::default(); + UiStateStore::default().save(ui, &mut storage); + UiStateStore::default().load(Some(&storage)).unwrap_or_else(|| panic!("the saved state loads: {:?}", storage.values)) + } + + /// An empty folder of its own for one test + fn test_folder(name: &str) -> PathBuf { + let folder = std::env::temp_dir().join(format!("texturecraft-ui-store-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&folder); + std::fs::create_dir_all(&folder).unwrap(); + folder + } + + /// The painting default with Layers moved into a tab beside Assets and Properties floating + fn moved_panels() -> Dock { + let mut workspace = default_workspace(); + let actions = [ + Action::Move { panel: Panel::Layers, anchor: Panel::Assets, placement: Placement::Tab { before: None } }, + Action::Float { panel: Panel::Properties, rect: [900.0, 120.0, 320.0, 400.0] }, + ]; + workspace.apply_all(actions, permissions).unwrap(); + + let dock = Dock::from_value(serde_json::to_value(&workspace).unwrap()); + assert!(!dock.replaced_unreadable(), "the moved layout is valid"); + dock + } + + #[test] + fn panel_layouts_survive_a_restart_in_the_file_and_in_storage() { + let folder = test_folder("layouts"); + for dock in [Dock::default(), moved_panels()] { + let ui = UiState { dock, split_ratio: 0.3, ..UiState::default() }; + for file in [None, Some(folder.join("ui.json"))] { + let mut storage = MemoryStorage::default(); + UiStateStore::new(file.clone()).save(&ui, &mut storage); + + let restarted = UiStateStore::new(file.clone()).load(Some(&storage)).unwrap(); + assert!(fully_read(&restarted), "{file:?}"); + assert_eq!(restarted, ui, "{file:?}"); + } + } + std::fs::remove_dir_all(&folder).unwrap(); + } + + #[test] + fn the_state_an_earlier_build_saved_loads_and_its_copy_goes_on_the_next_save() { + let mut storage = MemoryStorage::default(); + let earlier = UiState { split_ratio: 0.3, ..UiState::default() }; + eframe::set_value(&mut storage, RON_STORAGE_KEY, &earlier); + + let mut store = UiStateStore::default(); + let loaded = store.load(Some(&storage)).expect("the earlier state loads"); + assert_eq!(loaded.split_ratio, 0.3); + + store.save(&loaded, &mut storage); + assert!(!storage.values.contains_key(RON_STORAGE_KEY)); + assert_eq!(UiStateStore::default().load(Some(&storage)).unwrap(), loaded); + } + + #[test] + fn an_unreadable_layout_loads_the_default_and_is_kept_beside_the_file() { + let folder = test_folder("unreadable"); + let file = folder.join("ui.json"); + let ui = UiState { dock: moved_panels(), split_ratio: 0.3, ..UiState::default() }; + let mut storage = MemoryStorage::default(); + UiStateStore::new(Some(file.clone())).save(&ui, &mut storage); + let saved = std::fs::read_to_string(&file).unwrap(); + assert!(saved.contains("\"Assets\"") && saved.contains("\"version\": 2"), "{saved}"); + + let unreadable = [ + // A panel this build does not know + saved.replacen("\"Assets\"", "\"Bogus\"", 1), + // A layout from a newer format + saved.replacen("\"version\": 2", "\"version\": 99", 1), + // Not a saved state + "not json".to_owned(), + ]; + for (n, text) in unreadable.iter().enumerate() { + std::fs::write(&file, text).unwrap(); + let mut store = UiStateStore::new(Some(file.clone())); + let loaded = store.load(Some(&storage)); + if let Some(loaded) = &loaded { + assert_eq!(loaded.dock, Dock::default(), "{text}"); + assert_eq!(loaded.split_ratio, 0.3, "{text}"); + } + + store.save(&loaded.unwrap_or_default(), &mut storage); + let copy = unreadable_name("ui", n as u32 + 1, "json"); + assert_eq!(std::fs::read_to_string(folder.join(copy)).unwrap(), *text); + assert_ne!(std::fs::read_to_string(&file).unwrap(), *text, "the next save replaces it once kept"); + } + std::fs::remove_dir_all(&folder).unwrap(); + } + + #[test] + fn an_unreadable_state_that_cannot_be_kept_is_not_saved_over() { + let folder = test_folder("frozen"); + let file = folder.join("ui.json"); + for n in 1..=MAX_UNREADABLE_COPIES { + std::fs::write(folder.join(unreadable_name("ui", n, "json")), "").unwrap(); + } + std::fs::write(&file, "not json").unwrap(); + + let mut store = UiStateStore::new(Some(file.clone())); + let mut storage = MemoryStorage::default(); + assert!(store.load(Some(&storage)).is_none()); + store.save(&UiState::default(), &mut storage); + store.save(&UiState::default(), &mut storage); + assert_eq!(std::fs::read_to_string(&file).unwrap(), "not json"); + std::fs::remove_dir_all(&folder).unwrap(); + } + + #[test] + fn a_file_too_large_to_read_is_not_saved_over() { + let folder = test_folder("too-large"); + let file = folder.join("ui.json"); + std::fs::write(&file, vec![b' '; MAX_FILE_BYTES as usize + 1]).unwrap(); + + let mut store = UiStateStore::new(Some(file.clone())); + let mut storage = MemoryStorage::default(); + assert!(store.load(Some(&storage)).is_none()); + store.save(&UiState::default(), &mut storage); + assert_eq!(std::fs::metadata(&file).unwrap().len(), MAX_FILE_BYTES + 1); + std::fs::remove_dir_all(&folder).unwrap(); + } + + #[test] + fn unreadable_layouts_in_storage_are_each_kept_under_a_key_of_their_own() { + let mut storage = MemoryStorage::default(); + UiStateStore::default().save(&UiState { dock: moved_panels(), ..UiState::default() }, &mut storage); + let saved = storage.values[STORAGE_KEY].clone(); + + for (n, panel) in [(1, "\"Bogus\""), (2, "\"Other\"")] { + let unreadable = saved.replacen("\"Assets\"", panel, 1); + storage.values.insert(STORAGE_KEY.to_owned(), unreadable.clone()); + + let mut store = UiStateStore::default(); + let loaded = store.load(Some(&storage)).unwrap(); + assert_eq!(loaded.dock, Dock::default()); + store.save(&loaded, &mut storage); + assert_eq!(storage.values[&unreadable_name(STORAGE_STEM, n, "json")], unreadable); + assert_eq!(UiStateStore::default().load(Some(&storage)).unwrap(), loaded); + } + assert_eq!(storage.values[&unreadable_name(STORAGE_STEM, 1, "json")], saved.replacen("\"Assets\"", "\"Bogus\"", 1), "the first copy stays"); + } + + #[test] + fn an_earlier_state_that_does_not_parse_is_kept_before_its_entry_goes() { + let folder = test_folder("ron"); + for file in [None, Some(folder.join("ui.json"))] { + let mut storage = MemoryStorage::default(); + storage.values.insert(RON_STORAGE_KEY.to_owned(), "(not ron".to_owned()); + + let mut store = UiStateStore::new(file.clone()); + assert!(store.load(Some(&storage)).is_none()); + store.save(&UiState::default(), &mut storage); + let copy = match &file { + Some(_) => std::fs::read_to_string(folder.join(unreadable_name("ui", 1, "ron"))).unwrap(), + None => storage.values[&unreadable_name(STORAGE_STEM, 1, "ron")].clone(), + }; + assert_eq!(copy, "(not ron", "{file:?}"); + assert!(!storage.values.contains_key(RON_STORAGE_KEY), "{file:?}"); + } + std::fs::remove_dir_all(&folder).unwrap(); + } + + #[test] + fn a_file_that_exists_but_cannot_be_read_is_not_saved_over() { + let folder = test_folder("read-error"); + let file = folder.join("ui.json"); + // A folder in the file's place fails to read with an error other than not found + std::fs::create_dir_all(&file).unwrap(); + let mut storage = MemoryStorage::default(); + eframe::set_value(&mut storage, RON_STORAGE_KEY, &UiState::default()); + + let mut store = UiStateStore::new(Some(file.clone())); + assert!(store.load(Some(&storage)).is_none(), "the earlier state is not loaded in its place"); + store.save(&UiState::default(), &mut storage); + assert!(file.is_dir()); + assert!(storage.values.contains_key(RON_STORAGE_KEY)); + std::fs::remove_dir_all(&folder).unwrap(); + } + + #[test] + fn a_state_that_would_not_read_back_is_not_saved() { + let mut storage = MemoryStorage::default(); + let mut store = UiStateStore::default(); + store.save(&UiState { split_ratio: 0.3, ..UiState::default() }, &mut storage); + let saved = storage.values[STORAGE_KEY].clone(); + + store.save(&UiState { uv_pan: [f32::NAN, 0.0], ..UiState::default() }, &mut storage); + assert_eq!(storage.values[STORAGE_KEY], saved); + } + + #[test] + fn rejected_storage_backup_preserves_the_unreadable_original() { + let mut storage = MemoryStorage::default(); + storage.values.insert(STORAGE_KEY.into(), "not json".into()); + storage.rejected_key = Some("ui.unreadable.json"); + let mut store = UiStateStore::default(); + assert!(store.load(Some(&storage)).is_none()); + + store.save(&UiState::default(), &mut storage); + store.save(&UiState::default(), &mut storage); + assert_eq!(storage.values[STORAGE_KEY], "not json"); + } + + #[test] + fn rejected_storage_save_keeps_legacy_ron() { + let mut storage = MemoryStorage::default(); + let ui = UiState::default(); + eframe::set_value(&mut storage, RON_STORAGE_KEY, &ui); + let original = storage.values[RON_STORAGE_KEY].clone(); + storage.rejected_key = Some(STORAGE_KEY); + let mut store = UiStateStore::default(); + let loaded = store.load(Some(&storage)).unwrap(); + + store.save(&loaded, &mut storage); + assert_eq!(storage.values.get(RON_STORAGE_KEY), Some(&original)); + assert!(!storage.values.contains_key(STORAGE_KEY)); + } + + #[test] + fn parsed_legacy_ron_keeps_the_raw_custom_layout() { + let folder = test_folder("legacy-layout"); + for file in [None, Some(folder.join("ui.json"))] { + let mut storage = MemoryStorage::default(); + // Recorded with the legacy eframe RON writer: Assets closed, Display floating, twenty recent projects + let original = include_str!("../tests/fixture/ui_state_before_json.ron").to_owned(); + storage.values.insert(RON_STORAGE_KEY.into(), original.clone()); + assert!(original.contains("panels:[Display]") && original.contains("960.0")); + let mut store = UiStateStore::new(file.clone()); + let loaded = store.load(Some(&storage)).unwrap(); + assert!(loaded.dock.replaced_unreadable()); + assert_eq!(loaded.split_ratio, 0.3); + + store.save(&loaded, &mut storage); + let backup = match &file { + Some(_) => std::fs::read_to_string(folder.join("ui.unreadable.ron")).ok(), + None => storage.values.get("ui.unreadable.ron").cloned(), + }; + assert_eq!(backup, Some(original), "{file:?}"); + } + std::fs::remove_dir_all(folder).unwrap(); + } + + #[test] + fn a_save_larger_than_the_read_limit_preserves_the_previous_state() { + let folder = test_folder("oversized-save"); + let file = folder.join("ui.json"); + let mut storage = MemoryStorage::default(); + let mut store = UiStateStore::new(Some(file.clone())); + store.save(&UiState::default(), &mut storage); + let previous = std::fs::read(&file).unwrap(); + let ui = UiState { shelf_filter: "x".repeat(MAX_FILE_BYTES as usize), ..UiState::default() }; + + store.save(&ui, &mut storage); + assert!(std::fs::read(&file).unwrap() == previous); + std::fs::remove_dir_all(folder).unwrap(); + } + + #[test] + fn customized_painting_and_baking_docks_survive_each_active_mode() { + let folder = test_folder("both-modes"); + for mode in [crate::state::Mode::Painting, crate::state::Mode::Baking, crate::state::Mode::Rendering] { + let mut ui = UiState { dock: moved_panels(), ..UiState::default() }; + ui.inactive_mode_dock.close(Panel::MeshMapBakers); + ui.mode = mode; + ui.sync_mode_dock(); + for file in [None, Some(folder.join("ui.json"))] { + let mut storage = MemoryStorage::default(); + UiStateStore::new(file.clone()).save(&ui, &mut storage); + let mut loaded = UiStateStore::new(file).load(Some(&storage)).unwrap(); + loaded.sync_mode_dock(); + assert_eq!(loaded, ui, "{mode:?}"); + loaded.mode = crate::state::Mode::Painting; + loaded.sync_mode_dock(); + assert_eq!(loaded.dock, moved_panels()); + loaded.mode = crate::state::Mode::Baking; + loaded.sync_mode_dock(); + assert!(!loaded.dock.is_open(Panel::MeshMapBakers)); + } + } + std::fs::remove_dir_all(folder).unwrap(); + } + + #[test] + fn failed_saves_report_once_and_retry_after_access_is_restored() { + let mut storage = MemoryStorage::default(); + storage.rejected_key = Some(STORAGE_KEY); + let mut store = UiStateStore::default(); + store.save(&UiState::default(), &mut storage); + assert!(store.take_warning().unwrap().contains("could not be saved")); + store.save(&UiState::default(), &mut storage); + assert!(store.take_warning().is_none()); + + storage.rejected_key = None; + store.save(&UiState::default(), &mut storage); + assert!(store.load(Some(&storage)).is_some()); + storage.rejected_key = Some(STORAGE_KEY); + store.save(&UiState { split_ratio: 0.3, ..UiState::default() }, &mut storage); + assert!(store.take_warning().is_some(), "a new failure after recovery is reported"); + } + + #[test] + fn failed_file_saves_keep_legacy_settings_and_report_the_path() { + let folder = test_folder("write-error"); + let file = folder.join("ui.json"); + let mut storage = MemoryStorage::default(); + eframe::set_value(&mut storage, RON_STORAGE_KEY, &UiState::default()); + let original = storage.values[RON_STORAGE_KEY].clone(); + let mut store = UiStateStore::new(Some(file.clone())); + let loaded = store.load(Some(&storage)).unwrap(); + std::fs::create_dir(&file).unwrap(); + + store.save(&loaded, &mut storage); + assert_eq!(storage.values[RON_STORAGE_KEY], original); + assert!(store.take_warning().unwrap().contains(&file.display().to_string())); + std::fs::remove_dir(&file).unwrap(); + store.save(&loaded, &mut storage); + assert!(read(&file).is_some()); + assert!(!storage.values.contains_key(RON_STORAGE_KEY)); + std::fs::remove_dir_all(folder).unwrap(); + } + + #[test] + fn non_finite_legacy_pan_leaves_the_original_ron_for_the_next_restart() { + let folder = test_folder("nonfinite-ron"); + for file in [None, Some(folder.join("ui.json"))] { + let mut storage = MemoryStorage::default(); + eframe::set_value(&mut storage, RON_STORAGE_KEY, &UiState { uv_pan: [f32::NAN, 1.0], ..UiState::default() }); + let original = storage.values[RON_STORAGE_KEY].clone(); + let mut store = UiStateStore::new(file.clone()); + let loaded = store.load(Some(&storage)).unwrap(); + assert!(loaded.uv_pan[0].is_nan()); + + store.save(&loaded, &mut storage); + assert_eq!(storage.values[RON_STORAGE_KEY], original); + assert!(store.take_warning().is_some()); + assert!(!storage.values.contains_key(STORAGE_KEY)); + assert!(!file.as_ref().is_some_and(|file| file.exists())); + let restarted = UiStateStore::new(file).load(Some(&storage)).unwrap(); + assert!(restarted.uv_pan[0].is_nan()); + } + std::fs::remove_dir_all(folder).unwrap(); + } + + #[test] + fn an_unreadable_inactive_dock_is_backed_up_before_mode_sync() { + let mut storage = MemoryStorage::default(); + let mut saved = serde_json::to_value(UiState::default()).unwrap(); + saved["inactive_mode_dock"]["version"] = 99.into(); + let original = saved.to_string(); + storage.values.insert(STORAGE_KEY.into(), original.clone()); + let mut store = UiStateStore::default(); + let mut loaded = store.load(Some(&storage)).unwrap(); + assert!(loaded.inactive_mode_dock.replaced_unreadable()); + loaded.sync_mode_dock(); + assert!(!loaded.inactive_mode_dock.replaced_unreadable()); + + store.save(&loaded, &mut storage); + assert_eq!(storage.values["ui.unreadable.json"], original); + } +} diff --git a/crates/ui-egui/src/ui_state_store/memory_storage.rs b/crates/ui-egui/src/ui_state_store/memory_storage.rs new file mode 100644 index 00000000..794fc996 --- /dev/null +++ b/crates/ui-egui/src/ui_state_store/memory_storage.rs @@ -0,0 +1,24 @@ +/// eframe's storage held in memory +#[derive(Default)] +pub(crate) struct MemoryStorage { + pub(crate) values: std::collections::HashMap, + pub(crate) rejected_key: Option<&'static str>, +} + +impl eframe::Storage for MemoryStorage { + fn get_string(&self, key: &str) -> Option { + self.values.get(key).cloned() + } + + fn set_string(&mut self, key: &str, value: String) { + if self.rejected_key != Some(key) { + self.values.insert(key.to_owned(), value); + } + } + + fn remove_string(&mut self, key: &str) { + self.values.remove(key); + } + + fn flush(&mut self) {} +} diff --git a/crates/ui-egui/src/updates_ui.rs b/crates/ui-egui/src/updates_ui.rs new file mode 100644 index 00000000..fa1e6c4b --- /dev/null +++ b/crates/ui-egui/src/updates_ui.rs @@ -0,0 +1,325 @@ +//! Software updates on the desktop: the check at start, Help > Check for Updates and the update +//! prompt. An update that is ready starts its install helper when the app is dropped at exit. + +use craft_update::updater::{Action, Status, Updater}; +use craft_update::{CheckResultDialog, CheckResultResponse}; + +use crate::TextureCraftApp; + +pub(crate) struct Runtime { + updater: Updater, + /// The desktop app turns the check at start on; tests leave it off. + startup_check: bool, + check_requested: bool, +} + +impl Default for Runtime { + fn default() -> Self { + Self { updater: Updater::new(&crate::UPDATE_APP, env!("CARGO_PKG_VERSION")), startup_check: false, check_requested: false } + } +} + +impl TextureCraftApp { + /// Whether the app asks for a newer release when it starts (off until the desktop app turns it on). + pub fn set_startup_update_check(&mut self, on: bool) { + self.updates_rt.startup_check = on; + } +} + +/// Help > Check for Updates: the next frame starts a check that reports its outcome. +pub(crate) fn request_check(app: &mut TextureCraftApp, ctx: &egui::Context) { + app.updates_rt.check_requested = true; + ctx.request_repaint(); +} + +/// The update prompt and the modal result window hold the keyboard while they are open, so keys +/// do not act on the project behind them. +pub(crate) fn blocks_input(app: &TextureCraftApp) -> bool { + holds_keyboard(app.updates_rt.updater.status(), app.updates_rt.updater.prompt_open()) +} + +/// The prompt is modal, and the result window is modal for every status but [`Status::Updated`], +/// a notice that leaves the app usable behind it. +fn holds_keyboard(status: &Status, prompt_open: bool) -> bool { + prompt_open || !matches!(status, Status::Idle | Status::Updated(_)) +} + +pub(crate) fn tick(app: &mut TextureCraftApp, ctx: &egui::Context) { + let rt = &mut app.updates_rt; + if std::mem::take(&mut rt.check_requested) { + rt.updater.check_now(ctx); + } else if rt.startup_check { + rt.updater.check_at_start(ctx); + } + rt.updater.tick(ctx); +} + +/// Whether the result window shows: for every status but idle (a requested check, and the first +/// start after an update, which reports that it installed or why it failed), and never over the +/// update prompt. +fn result_window_shows(status: &Status, prompt_open: bool) -> bool { + !prompt_open && !matches!(status, Status::Idle) +} + +/// Whether an update may install and close the app: the project has no unsaved changes and no +/// stroke, bake or resize is running. +fn safe_to_close(app: &TextureCraftApp) -> bool { + !app.session.modified && !app.session.stroke_active() && app.bake.is_none() && app.resize.is_none() +} + +pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { + let safe = safe_to_close(app); + match app.updates_rt.updater.show_if(ctx, safe) { + Action::OpenUrl(url) => ctx.open_url(egui::OpenUrl::new_tab(url)), + Action::Close => ctx.send_viewport_cmd(egui::ViewportCommand::Close), + Action::None => {} + } + let rt = &mut app.updates_rt; + if result_window_shows(rt.updater.status(), rt.updater.prompt_open()) { + match CheckResultDialog::new(&crate::UPDATE_APP, env!("CARGO_PKG_VERSION")).show(ctx, rt.updater.status()) { + CheckResultResponse::None => {} + CheckResultResponse::Close => rt.updater.dismiss_status(), + CheckResultResponse::CheckAgain => rt.check_requested = true, + CheckResultResponse::RestartToUpdate => rt.updater.restart_to_update(), + } + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + use std::sync::mpsc::{Receiver, channel}; + + use craft_update::updater::CheckSource; + use craft_update::{Arch, Asset, Os, PackageKind, Paths, Platform, Release, pick_asset}; + use egui_kittest::Harness; + use egui_kittest::kittest::Queryable as _; + use serde_json::json; + use texturecraft_engine::Tool; + use texturecraft_engine::bake::Progress; + use texturecraft_engine::geom::glam::Vec2; + + use super::*; + use crate::state::Mode; + + /// Stands in for GitHub: each check sends one message and finds nothing newer. + fn source() -> (CheckSource, Receiver<()>) { + let (sent, asked) = channel(); + let ask: CheckSource = Arc::new(move || { + let _ = sent.send(()); + Ok(None) + }); + (ask, asked) + } + + /// The harness draws the UI, and the i18n tests switch the process-wide language to ones + /// its fonts cannot draw. + fn language() -> std::sync::MutexGuard<'static, ()> { + crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner) + } + + /// The app with an updater that asks `ask` and keeps its records out of the user's folders. + fn harness(modified: bool, test: &str, ask: CheckSource) -> Harness<'static, TextureCraftApp> { + let root = std::env::temp_dir().join(format!("texturecraft-updates-{}-{test}", std::process::id())); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + session.modified = modified; + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().updates_rt.updater = + Updater::new(&crate::UPDATE_APP, "0.0.1").with_source(ask).with_paths(Paths::under(&root)).with_pins_path(root.join("pins.json")); + h.state_mut().ui.windows.start = false; + h.run_steps(2); + h + } + + fn offer(h: &mut Harness<'static, TextureCraftApp>) { + let release = Release { + tag: "v99.0.0".into(), + version: craft_update::parse_version("99.0.0"), + name: "TextureCraft 99.0.0".into(), + html_url: "https://github.com/storytold/texturecraft/releases/tag/v99.0.0".into(), + ..Default::default() + }; + h.state_mut().updates_rt.updater.offer(release); + h.run_steps(2); + } + + #[test] + fn default_runtime_is_idle() { + let rt = Runtime::default(); + assert!(!rt.startup_check); + assert!(!rt.check_requested); + assert!(!rt.updater.prompt_open()); + assert_eq!(rt.updater.status(), &Status::Idle); + } + + #[test] + fn the_menu_item_runs_a_check_that_reports_its_outcome() { + let _language = language(); + let (ask, asked) = source(); + let mut h = harness(false, "menu", ask); + let ctx = h.ctx.clone(); + crate::menus::invoke(h.state_mut(), &ctx, "ui.help.checkForUpdates"); + h.step(); + let status = h.state().updates_rt.updater.status().clone(); + assert!(matches!(status, Status::Checking | Status::UpToDate), "{status:?}"); + // Dropping the app drops the only sender left when no check started, so this cannot hang. + drop(h); + assert!(asked.recv().is_ok(), "the check asked for the latest release"); + } + + #[test] + fn the_check_at_start_runs_only_when_the_desktop_app_turns_it_on() { + let _language = language(); + for on in [false, true] { + let (ask, asked) = source(); + let mut h = harness(false, if on { "start-on" } else { "start-off" }, ask); + h.state_mut().set_startup_update_check(on); + h.step(); + drop(h); + assert_eq!(asked.recv().is_ok(), on, "startup check {on}"); + } + } + + #[test] + fn an_offered_update_shows_the_prompt_and_later_closes_it() { + let _language = language(); + let (ask, _asked) = source(); + let mut h = harness(false, "prompt", ask); + offer(&mut h); + assert!(h.state().updates_rt.updater.prompt_open()); + h.get_by_label("LATER").click(); + h.run_steps(2); + assert!(!h.state().updates_rt.updater.prompt_open()); + } + + #[test] + fn keys_do_not_reach_the_project_behind_the_prompt() { + let _language = language(); + let (ask, _asked) = source(); + let mut h = harness(false, "keys", ask); + assert_eq!(h.state().ui.mode, Mode::Painting); + offer(&mut h); + assert!(crate::docking::input_blocked(h.state(), &h.ctx), "floating panels stop taking input"); + h.key_press(egui::Key::F8); + h.step(); + assert_eq!(h.state().ui.mode, Mode::Painting, "the prompt holds the keyboard"); + h.get_by_label("LATER").click(); + h.run_steps(2); + assert!(!crate::docking::input_blocked(h.state(), &h.ctx)); + h.key_press(egui::Key::F8); + h.step(); + assert_eq!(h.state().ui.mode, Mode::Baking, "the key works once the prompt is closed"); + } + + #[test] + fn the_path_tools_keys_do_not_reach_the_path_behind_the_prompt() { + let _language = language(); + let (ask, _asked) = source(); + let mut h = harness(false, "path-keys", ask); + let state = h.state_mut(); + state.session.tool.tool = Tool::Path; + texturecraft_engine::execute(&mut state.session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]]})).unwrap(); + h.run_steps(2); + let points = |h: &Harness<'static, TextureCraftApp>| h.state().session.tool.path.points.len(); + assert_eq!(points(&h), 2); + offer(&mut h); + h.key_press(egui::Key::Backspace); + h.step(); + assert_eq!(points(&h), 2, "the prompt holds the keyboard"); + h.get_by_label("LATER").click(); + h.run_steps(2); + h.key_press(egui::Key::Backspace); + h.step(); + assert_eq!(points(&h), 1, "the key works once the prompt is closed"); + } + + #[test] + fn the_result_window_holds_the_keyboard_unless_it_is_the_updated_notice() { + let modal = [ + Status::Checking, + Status::UpToDate, + Status::Failed("offline".into()), + Status::Installing, + Status::Ready, + Status::Managed, + Status::InstallFailed("locked".into()), + ]; + for status in &modal { + assert!(holds_keyboard(status, false), "{status:?}"); + } + assert!(!holds_keyboard(&Status::Idle, false)); + assert!(!holds_keyboard(&Status::Updated("99.0.0".into()), false)); + assert!(holds_keyboard(&Status::Idle, true), "the prompt is modal"); + } + + #[test] + fn unsaved_changes_and_running_work_hold_an_update_back() { + let _language = language(); + let (ask, _asked) = source(); + let mut h = harness(false, "safe-to-close", ask); + assert!(safe_to_close(h.state())); + + h.state_mut().session.modified = true; + assert!(!safe_to_close(h.state()), "unsaved changes"); + h.state_mut().session.modified = false; + + h.state_mut().bake = Some(crate::BakeJob { queue: Vec::new(), current: None, total: 0 }); + assert!(!safe_to_close(h.state()), "a bake"); + h.state_mut().bake = None; + + h.state_mut().resize = Some(crate::ResizeJob { progress: Arc::new(Progress::new()), rx: channel().1 }); + assert!(!safe_to_close(h.state()), "a resize"); + h.state_mut().resize = None; + + let session = &mut h.state_mut().session; + texturecraft_engine::execute(session, "layer.add.paint", &serde_json::Value::Null).unwrap(); + session.modified = false; + session.begin_stroke_uv(Vec2::new(0.5, 0.5), 1.0).unwrap(); + assert!(!safe_to_close(h.state()), "a stroke"); + h.state_mut().session.cancel_stroke(); + assert!(safe_to_close(h.state())); + } + + #[test] + fn result_window_shows_every_status_but_idle() { + let shown = [ + Status::Checking, + Status::UpToDate, + Status::Failed("offline".into()), + Status::Installing, + Status::Ready, + Status::Managed, + Status::Updated("99.0.0".into()), + Status::InstallFailed("locked".into()), + ]; + for status in &shown { + assert!(result_window_shows(status, false), "{status:?} shows"); + assert!(!result_window_shows(status, true), "{status:?} waits for the prompt"); + } + assert!(!result_window_shows(&Status::Idle, false)); + } + + #[test] + fn the_update_app_finds_the_assets_a_release_publishes() { + let names = [ + "texturecraft-0.4.0-macos-universal.dmg", + "texturecraft-0.4.0-windows-x64.msi", + "texturecraft-0.4.0-windows-x64-portable.zip", + "texturecraft-0.4.0-linux-x86_64.AppImage", + "texturecraft-0.4.0-linux-x86_64.tar.gz", + "texturecraft-cli-0.4.0-macos-universal.zip", + "texturecraft-web-0.4.0.zip", + ]; + let assets = names.iter().map(|name| Asset { name: (*name).into(), size: 1, url: String::new(), sha256: None }).collect(); + let release = Release { assets, ..Default::default() }; + let stems = [crate::UPDATE_APP.id]; + let picked = |os, arch, kind| pick_asset(&release, &stems, Platform { os, arch }, &[kind]).map(|(asset, _)| asset.name.clone()); + assert_eq!(picked(Os::MacOs, Arch::Arm64, PackageKind::Dmg).as_deref(), Some(names[0])); + assert_eq!(picked(Os::Windows, Arch::X64, PackageKind::Msi).as_deref(), Some(names[1])); + assert_eq!(picked(Os::Windows, Arch::X64, PackageKind::PortableZip).as_deref(), Some(names[2])); + assert_eq!(picked(Os::Linux, Arch::X64, PackageKind::AppImage).as_deref(), Some(names[3])); + assert_eq!(picked(Os::Linux, Arch::X64, PackageKind::TarGz).as_deref(), Some(names[4])); + assert_eq!(crate::UPDATE_APP.bundle_id(), "ai.storyteller.texturecraft"); + assert_eq!(crate::UPDATE_APP.repo, "storytold/texturecraft"); + } +} diff --git a/crates/ui-egui/src/uv_paint_point.rs b/crates/ui-egui/src/uv_paint_point.rs new file mode 100644 index 00000000..5ff1cafb --- /dev/null +++ b/crates/ui-egui/src/uv_paint_point.rs @@ -0,0 +1,21 @@ +//! A finished stroke's endpoint in one mesh's UV layout + +use texturecraft_engine::{Session, geom::glam::Vec2}; + +/// A line anchor scoped to its project, UV layout and texture set +#[derive(Clone, Copy, Debug)] +pub struct UvPaintPoint { + mesh_id: u64, + texture_set: usize, + uv: Vec2, +} + +impl UvPaintPoint { + pub(crate) fn new(session: &Session, uv: Vec2) -> Self { + Self { mesh_id: session.mesh_id, texture_set: session.ts(), uv } + } + + pub(crate) fn uv_for(self, session: &Session) -> Option { + (self.mesh_id == session.mesh_id && self.texture_set == session.ts()).then_some(self.uv) + } +} diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 517377b1..e864a5b2 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -51,9 +51,10 @@ pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) { crate::toolbar::paint_bar(app, ui); } + crate::id_color_pick::IdColorPick::end_when_stale(app); let tokens = Tokens::get(ui.ctx()); let aux_view = match app.session.view { - _ if mode == crate::state::Mode::Painting && app.session.quick_mask.editing => Some(crate::gpu::AuxView::QuickMask), + _ if mode == crate::state::Mode::Painting && app.session.quick_mask.editing && app.picking_id_color.is_none() => Some(crate::gpu::AuxView::QuickMask), ViewMode::MeshMap(map) => Some(crate::gpu::AuxView::MeshMap(map)), ViewMode::Mask(id) => Some(crate::gpu::AuxView::Mask(id)), _ => None, @@ -165,6 +166,18 @@ const UV_VIEW_MAX_ZOOM: f32 = 40.0; /// UV zoom change per point of mouse wheel, as a fraction of the zoom const UV_WHEEL_ZOOM_PER_POINT: f32 = 0.002; +/// Dash length of the straight-line preview, in points +const RUBBER_BAND_DASH: f32 = 6.0; + +/// Gap between the straight-line preview's dashes, in points +const RUBBER_BAND_GAP: f32 = 4.0; + +/// Opacity of the UV tile outlines in the 2D view +const UV_TILE_OUTLINE_ALPHA: u8 = 40; + +/// Smallest skew brush circle in the 2D view, in points, so a tiny brush stays visible +const BAKE_PAINT_CURSOR_MIN_RADIUS: f32 = 2.0; + /// The 2D view's width when the split divider is at `divider_x` fn uv_view_width(full: Rect, divider_x: f32) -> f32 { (full.right() - divider_x - SPLIT_LINE_HALF_WIDTH).max(1.0) @@ -205,7 +218,7 @@ fn split_divider_grab(ui: &Ui, full: Rect, divider_x: f32) { fn shade(app: &TextureCraftApp) -> Shade { let (view_mode, channel) = match app.session.view { - _ if app.ui.mode == crate::state::Mode::Painting && app.session.quick_mask.editing => (2, 0), + _ if app.ui.mode == crate::state::Mode::Painting && app.session.quick_mask.editing && app.picking_id_color.is_none() => (2, 0), ViewMode::Material => (0, 0), ViewMode::Channel(selected_channel) => (1, selected_channel.index() as u32), ViewMode::MeshMap(_) | ViewMode::Mask(_) => (2, 0), @@ -297,31 +310,45 @@ fn frame_size_in_pixels(ui: &Ui, rect: Rect) -> [u32; 2] { [pixels(rect.left(), rect.right()), pixels(rect.top(), rect.bottom())] } -fn add_callback(app: &mut TextureCraftApp, ui: &Ui, rect: Rect, frame: Frame, sync: &mut PendingSync) { - let tk = Tokens::get(ui.ctx()); +fn add_callback(app: &mut TextureCraftApp, ui: &Ui, rect: Rect, mut frame: Frame, sync: &mut PendingSync) { + let tokens = Tokens::get(ui.ctx()); + let bake = bake_visualization(app); + frame.shade.bake = bake.filter(|_| frame.kind == ViewKind::Scene); let scene = match (sync.0.take(), app.gpu.as_mut()) { - (Some(aux), Some(g)) => { - let t0 = crate::now_ms(); - let scene = g.sync(&mut app.session, aux, u32::from(app.ui.prefs.viewport_texture.min(2)), f64::from(app.profiler.logic_ms)); - let reports = g.take_reports(); - app.profiler.sync_ms += (crate::now_ms() - t0) as f32; + (Some(aux), Some(gpu_link)) => { + let sync_start_ms = crate::now_ms(); + let scene = gpu_link.sync(&mut app.session, aux, bake, u32::from(app.ui.prefs.viewport_texture.min(2)), f64::from(app.profiler.logic_ms)); + let reports = gpu_link.take_reports(); + app.profiler.sync_ms += (crate::now_ms() - sync_start_ms) as f32; gpu_report_toasts(app, reports); - // Display tiles left for later frames (the frame budget ran out). - if app.session.caches.iter().any(|c| !c.upload.is_empty()) { + + // Display tiles left for later frames (the frame budget ran out), or the bake visualization still being worked out + if app.session.caches.iter().any(|cache| !cache.upload.is_empty()) || app.gpu.as_ref().is_some_and(crate::gpu::GpuLink::bake_busy) { ui.ctx().request_repaint(); } Some(scene) } _ => None, }; + let Some(gpu) = &app.gpu else { - ui.painter().text(rect.center(), egui::Align2::CENTER_CENTER, tr("No GPU renderer available"), egui::FontId::proportional(14.0), tk.viewport_text); + ui.painter().text( + rect.center(), + egui::Align2::CENTER_CENTER, + tr("No GPU renderer available"), + egui::FontId::proportional(NO_GPU_TEXT_SIZE), + tokens.viewport_text, + ); return; }; - let cb = ViewCallback { frame, sync: Mutex::new(scene), rect, lost: gpu.lost.clone() }; - ui.painter().add(eframe::egui_wgpu::Callback::new_paint_callback(rect, cb)); + + let callback = ViewCallback { frame, sync: Mutex::new(scene), rect, lost: gpu.lost.clone() }; + ui.painter().add(eframe::egui_wgpu::Callback::new_paint_callback(rect, callback)); } +/// Text size of the notice a view shows without a GPU renderer +const NO_GPU_TEXT_SIZE: f32 = 14.0; + /// Width of the camera and view pickers centred at the top of a view const VIEW_HEADER_WIDTH: f32 = 300.0; @@ -560,8 +587,29 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin crate::properties_popup::open_on_right_click(app, ui, &response, rect, s_held || v_held); let popup = app.properties_popup.is_some(); + // A pending ID color pick takes the next click instead of the brush + let picking_id_color = app.picking_id_color.is_some(); + if picking_id_color { + crate::id_color_pick::IdColorPick::draw_cursor(ui, rect); + if !alt + && response.clicked_by(PointerButton::Primary) + && let Some(position) = response.interact_pointer_pos() + { + let (pixel, viewport) = (local(position), app.session.viewport); + crate::id_color_pick::IdColorPick::pick_at(app, json!({"x": pixel.x, "y": pixel.y, "viewport": [viewport.x, viewport.y]})); + } + } + // The selected decal's frame and handles: drag to move, scale or turn it - let decal_drag = !alt && !s_held && !v_held && !focus_pick && !popup && placing.is_none() && touch.is_none() && decal_input(app, ui, &response, rect); + let decal_drag = !alt + && !s_held + && !v_held + && !focus_pick + && !popup + && placing.is_none() + && !picking_id_color + && touch.is_none() + && decal_input(app, ui, &response, rect); // Painting let painting = app.ui.mode == crate::state::Mode::Painting @@ -572,6 +620,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin && !v_held && !focus_pick && placing.is_none() + && !picking_id_color && touch.is_none() && !decal_drag; let path_tool = app.session.tool.tool == Tool::Path; @@ -642,6 +691,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin && !navigating && response.hovered() && brush_tool(app.session.tool.tool) + && app.picking_id_color.is_none() && let Some(hover_pos) = if adjusting { ui.input(|input| input.pointer.press_origin()) } else { response.hover_pos() } && let Some(hit) = app.session.pick(local(hover_pos), app.session.viewport) { @@ -668,19 +718,32 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin stencil_overlay(app, ui, rect); decal_overlay(app, ui, rect); brush_readout(app, ui, &response, adjusting); - if app.session.quick_mask.editing { + if app.session.quick_mask.editing && app.picking_id_color.is_none() { ui.painter_at(rect).text( - rect.left_top() + vec2(12.0, 40.0), + rect.left_top() + QUICK_MASK_NOTICE_OFFSET, egui::Align2::LEFT_TOP, tr("Editing quick mask: paint where painting is allowed (U to finish)"), - egui::FontId::proportional(12.0), - Color32::from_rgb(0xe8, 0x6a, 0x6a), + egui::FontId::proportional(QUICK_MASK_NOTICE_TEXT_SIZE), + QUICK_MASK_NOTICE_COLOR, ); } + if app.ui.mode == crate::state::Mode::Baking { + crate::bake_mode::bake_visualization_panel(app, ui, rect); + } view_header(app, ui, rect, "v3d"); axis_gizmo(ui, rect, app, false); } +/// Where the quick-mask editing notice sits from the 3D view's top-left corner, its text size and its warning red +const QUICK_MASK_NOTICE_OFFSET: egui::Vec2 = vec2(12.0, 40.0); +const QUICK_MASK_NOTICE_TEXT_SIZE: f32 = 12.0; +const QUICK_MASK_NOTICE_COLOR: Color32 = Color32::from_rgb(0xe8, 0x6a, 0x6a); + +/// What bake mode's 3D view draws besides the low poly (nothing in the other modes) +fn bake_visualization(app: &TextureCraftApp) -> Option { + (app.ui.mode == crate::state::Mode::Baking).then(|| app.ui.bake_visualization.visualization(app.session.ts())).flatten() +} + /// What a drag on the selected decal's frame does. #[derive(Clone, Copy, Debug, PartialEq)] enum DecalGrab { @@ -915,6 +978,10 @@ const HANDLE_GRAB: f32 = 8.0; /// Path tool keys: Enter applies the path, Backspace removes its last point (Esc, handled with /// the global shortcuts, cancels it). fn path_keys(app: &mut TextureCraftApp, ui: &Ui) { + #[cfg(not(target_arch = "wasm32"))] + if crate::updates_ui::blocks_input(app) { + return; + } if app.ui.mode != crate::state::Mode::Painting || app.session.tool.tool != Tool::Path || app.session.tool.path.points.is_empty() @@ -1008,11 +1075,43 @@ fn path_overlay(app: &TextureCraftApp, ui: &Ui, rect: Rect, resp: &egui::Respons } } -/// Dashed preview of a straight segment. +/// Dashed preview of a straight segment, clipped to `rect` so an end far off screen adds no dashes. fn rubber_band(ui: &Ui, rect: Rect, from: Pos2, to: Pos2) { - let p = ui.painter_at(rect); - p.add(egui::Shape::dashed_line(&[from, to], Stroke::new(2.5, Color32::from_black_alpha(120)), 6.0, 4.0)); - p.add(egui::Shape::dashed_line(&[from, to], Stroke::new(1.0, Color32::from_white_alpha(200)), 6.0, 4.0)); + let Some(visible) = visible_dashes(rect, from, to) else { return }; + let painter = ui.painter_at(rect); + for stroke in [Stroke::new(2.5, Color32::from_black_alpha(120)), Stroke::new(1.0, Color32::from_white_alpha(200))] { + painter.add(egui::Shape::dashed_line(&visible, stroke, RUBBER_BAND_DASH, RUBBER_BAND_GAP)); + } +} + +/// The part of `from`→`to` inside `rect`, its start moved back to a whole dash period so the dashes keep their place. +fn visible_dashes(rect: Rect, from: Pos2, to: Pos2) -> Option<[Pos2; 2]> { + let direction = to - from; + let length = direction.length(); + if length == 0.0 { + return rect.contains(from).then_some([from, to]); + } + + // Clip the segment's parameter range against each axis's slab + let (mut enter, mut exit) = (0.0_f32, 1.0_f32); + for (delta, origin, low, high) in [(direction.x, from.x, rect.left(), rect.right()), (direction.y, from.y, rect.top(), rect.bottom())] { + if delta == 0.0 { + if origin < low || origin > high { + return None; + } + continue; + } + let (at_low, at_high) = ((low - origin) / delta, (high - origin) / delta); + enter = enter.max(at_low.min(at_high)); + exit = exit.min(at_low.max(at_high)); + } + if enter > exit { + return None; + } + + let period = RUBBER_BAND_DASH + RUBBER_BAND_GAP; + let start = (enter * length / period).floor() * period / length; + Some([from + direction * start, from + direction * exit]) } /// Polygon fill in a view: a click fills one target, a drag fills its box live (one undo step); returns the box to draw over the view image @@ -1218,11 +1317,12 @@ fn pen_pressure(ui: &Ui) -> f32 { } } +/// The 2D (UV) view: navigation, painting in texture coordinates and the overlays drawn over the texture. fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut PendingSync) { let tokens = Tokens::get(ui.ctx()); let response = ui.interact(rect, ui.scope_id().with("view2d"), Sense::click_and_drag()); let size = rect.size(); - let alt = ui.input(|input| input.modifiers.alt); + let (alt, shift) = ui.input(|input| (input.modifiers.alt, input.modifiers.shift)); let adjusting = brush_drag(app, ui, &response); // Pan with a middle drag or Alt+left drag, zoom with the wheel about the cursor @@ -1281,8 +1381,21 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin crate::properties_popup::open_on_right_click(app, ui, &response, rect, v_held); + // A pending ID color pick takes the next click instead of the brush + let picking_id_color = app.picking_id_color.is_some(); + if picking_id_color { + crate::id_color_pick::IdColorPick::draw_cursor(ui, rect); + if !alt + && response.clicked_by(PointerButton::Primary) + && let Some(position) = response.interact_pointer_pos() + { + let uv = to_uv(position); + crate::id_color_pick::IdColorPick::pick_at(app, json!({"uv": [uv.x, uv.y]})); + } + } + // Painting in UV space - let painting = app.ui.mode == crate::state::Mode::Painting && app.properties_popup.is_none() && !alt && !adjusting && !v_held; + let painting = app.ui.mode == crate::state::Mode::Painting && app.properties_popup.is_none() && !alt && !adjusting && !v_held && !picking_id_color; let mut fill_box = None; if painting && path_tool { path_input(app, ui, &response, true, |_, pointer| Some(to_uv(pointer).extend(0.0)), show); @@ -1295,29 +1408,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin |session, corner, opposite| session.drag_polygon_fill_box_uv(to_uv(corner), to_uv(opposite)), ); } else if painting { - let pressure = pen_pressure(ui); - if response.drag_started_by(PointerButton::Primary) || response.clicked_by(PointerButton::Primary) { - if let Some(pointer) = response.interact_pointer_pos() - && let Err(error) = app.session.begin_stroke_uv(to_uv(pointer), pressure) - { - app.toast(error.to_string(), true); - } - if response.clicked_by(PointerButton::Primary) - && let Err(error) = app.session.end_stroke() - { - app.toast(error.to_string(), true); - } - } else if response.dragged_by(PointerButton::Primary) - && app.session.stroke_active() - && let Some(pointer) = response.interact_pointer_pos() - { - app.session.continue_stroke_uv(to_uv(pointer), pressure); - } - if response.drag_stopped_by(PointerButton::Primary) - && let Err(error) = app.session.end_stroke() - { - app.toast(error.to_string(), true); - } + paint_2d_input(app, ui, &response, shift, &to_uv); } if response.double_clicked() && !(painting && path_tool) { app.ui.uv_zoom = 1.0; @@ -1339,7 +1430,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin // The UV tile outlines (numbered for UDIM sets) and the path being edited let painter = ui.painter_at(rect); let set = app.session.doc.project.texture_sets.get(ts); - let outline = |tile: Rect| painter.rect_stroke(tile, 0.0, Stroke::new(1.0, Color32::from_white_alpha(40)), egui::StrokeKind::Outside); + let outline = |tile: Rect| painter.rect_stroke(tile, 0.0, Stroke::new(1.0, Color32::from_white_alpha(UV_TILE_OUTLINE_ALPHA)), egui::StrokeKind::Outside); match set.and_then(|texture_set| Some((texture_set, texture_set.tile_grid()?))) { Some((texture_set, grid)) => { for (udim, (block_x, block_y)) in texture_set.uv_tiles.iter().filter_map(|udim| Some((*udim, grid.block(*udim)?))) { @@ -1365,10 +1456,21 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin path_overlay(app, ui, rect, &response, true, show); } + // Shift: preview the straight line Shift+click paints from the last stroke + if painting + && shift + && !path_tool + && brush_tool(app.session.tool.tool) + && let Some(from) = app.last_paint_uv.and_then(|point| point.uv_for(&app.session)) + && let Some(hover) = response.hover_pos() + { + rubber_band(ui, rect, to_screen(from.x, from.y), hover); + } + if app.ui.mode == crate::state::Mode::Baking { bake_paint_overlay(app, ui, &painter, to_screen(0.0, 1.0), to_screen(1.0, 0.0)); if bake_paint_on && let Some(hover) = response.hover_pos() { - let radius = (to_screen(app.ui.bake_paint_brush.radius, 0.0).x - to_screen(0.0, 0.0).x).abs().max(2.0); + let radius = (to_screen(app.ui.bake_paint_brush.radius, 0.0).x - to_screen(0.0, 0.0).x).abs().max(BAKE_PAINT_CURSOR_MIN_RADIUS); painter.circle_stroke(hover, radius, Stroke::new(1.0, Color32::from_white_alpha(200))); } } @@ -1380,6 +1482,47 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin ui.painter().text(rect.right_bottom() + vec2(-10.0, -10.0), egui::Align2::RIGHT_BOTTOM, name, egui::FontId::proportional(11.0), tokens.viewport_text); } +/// Paint in the 2D view: a press starts a stroke, a drag continues it, Shift+click draws a line from the last stroke. +fn paint_2d_input(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response, shift: bool, to_uv: &dyn Fn(egui::Pos2) -> Vec2) { + let pressure = pen_pressure(ui); + + // Where the stroke under way is; it becomes the line start only when the stroke finishes + let stroke_end = ui.scope_id().with("paint_2d_stroke_end"); + + if response.drag_started_by(PointerButton::Primary) || response.clicked_by(PointerButton::Primary) { + let line_start = app.last_paint_uv.filter(|_| shift).and_then(|point| point.uv_for(&app.session)); + if let Some(pointer) = response.interact_pointer_pos() { + let uv = to_uv(pointer); + match app.session.begin_stroke_uv(line_start.unwrap_or(uv), pressure) { + Ok(()) => { + if line_start.is_some() { + app.session.continue_stroke_uv(uv, pressure); + } + ui.data_mut(|data| data.insert_temp(stroke_end, crate::uv_paint_point::UvPaintPoint::new(&app.session, uv))); + } + Err(error) => app.toast(error.to_string(), true), + } + } + } else if response.dragged_by(PointerButton::Primary) + && app.session.stroke_active() + && let Some(pointer) = response.interact_pointer_pos() + { + let uv = to_uv(pointer); + app.session.continue_stroke_uv(uv, pressure); + ui.data_mut(|data| data.insert_temp(stroke_end, crate::uv_paint_point::UvPaintPoint::new(&app.session, uv))); + } + + // Escape cancels the stroke and ends the drag without a primary release, so a cancelled stroke never gets here + if response.clicked_by(PointerButton::Primary) || response.drag_stopped_by(PointerButton::Primary) { + let finishing = app.session.stroke_active(); + match app.session.end_stroke() { + Ok(()) if finishing => app.last_paint_uv = ui.data(|data| data.get_temp(stroke_end)), + Ok(()) => {} + Err(error) => app.toast(error.to_string(), true), + } + } +} + /// Paint the skew map under the pointer in the 2D view (a click is one dab, a drag a stroke). fn bake_paint_input(app: &mut TextureCraftApp, ui: &Ui, resp: &egui::Response, to_uv: &dyn Fn(egui::Pos2) -> Vec2) { let last = ui.scope_id().with(("bake_paint_last", app.session.ts(), app.ui.bake_paint_brush.target as u8)); @@ -1431,3 +1574,34 @@ fn bake_paint_overlay(app: &TextureCraftApp, ui: &Ui, painter: &egui::Painter, t }; painter.image(tex.id(), Rect::from_two_pos(top_left, bottom_right), Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); } + +#[cfg(test)] +mod tests { + use super::*; + + const VIEW: Rect = Rect::from_min_max(pos2(0.0, 0.0), pos2(100.0, 100.0)); + const DASH_PERIOD: f32 = RUBBER_BAND_DASH + RUBBER_BAND_GAP; + + #[test] + fn a_far_start_is_clipped_to_the_view_on_a_whole_dash_period() { + let far_start = pos2(-10_003.0, 50.0); + + let [start, end] = visible_dashes(VIEW, far_start, pos2(50.0, 50.0)).unwrap(); + + assert!(start.x <= VIEW.left() && start.x > VIEW.left() - DASH_PERIOD, "starts at the view's edge: {start:?}"); + let periods = (start.x - far_start.x) / DASH_PERIOD; + assert!((periods - periods.round()).abs() < 1e-3, "a whole number of dash periods from the real start: {periods}"); + assert_eq!(end, pos2(50.0, 50.0)); + } + + #[test] + fn a_segment_inside_the_view_is_kept_whole() { + assert_eq!(visible_dashes(VIEW, pos2(10.0, 20.0), pos2(90.0, 80.0)), Some([pos2(10.0, 20.0), pos2(90.0, 80.0)])); + } + + #[test] + fn a_segment_outside_the_view_draws_nothing() { + assert_eq!(visible_dashes(VIEW, pos2(-50.0, -10.0), pos2(150.0, -10.0)), None); + assert_eq!(visible_dashes(VIEW, pos2(-50.0, 120.0), pos2(120.0, 300.0)), None); + } +} diff --git a/crates/ui-egui/src/web_files.rs b/crates/ui-egui/src/web_files.rs index 6ebe87ec..759d5576 100644 --- a/crates/ui-egui/src/web_files.rs +++ b/crates/ui-egui/src/web_files.rs @@ -77,28 +77,33 @@ pub fn poll(app: &mut TextureCraftApp) { } } -/// Bake mode: add high-definition meshes (or load the cage) with the native file dialog; in -/// the browser they arrive on a later frame. +/// Bake mode: add high-definition meshes (or load the cage) with the native file dialog. The +/// meshes load on a later frame, when the dialog answers. #[cfg(not(target_arch = "wasm32"))] pub fn import_bake_mesh(app: &mut TextureCraftApp, _ctx: &egui::Context, cage: bool) { - let dialog = rfd::FileDialog::new().add_filter(tr("Meshes"), &MESH_EXTENSIONS); - let paths = if cage { dialog.pick_file().into_iter().collect() } else { dialog.pick_files().unwrap_or_default() }; - for p in paths { - let cmd = if cage { "bake.cage.set" } else { "bake.highPoly.add" }; - app.run(cmd, serde_json::json!({ "path": p.display().to_string() })); - } + use crate::file_dialogs::{Bound, FileDialog}; + let dialog = if cage { FileDialog::open() } else { FileDialog::open_many() }; + app.ask_file(dialog.filter(tr("Meshes"), &MESH_EXTENSIONS), Bound::Project, move |app, paths| { + for p in paths { + let cmd = if cage { "bake.cage.set" } else { "bake.highPoly.add" }; + app.run(cmd, serde_json::json!({ "path": p.display().to_string() })); + } + }); } /// Display settings › Import HDR: pick an equirect `.hdr`/`.exr`, import it as a resource and -/// light the scene with it (in the browser the file arrives on a later frame). +/// light the scene with it, on a later frame when the dialog answers. #[cfg(not(target_arch = "wasm32"))] pub fn import_environment(app: &mut TextureCraftApp, _ctx: &egui::Context) { - let Some(p) = rfd::FileDialog::new().add_filter(tr("HDR environments"), ENV_EXTS).pick_file() else { return }; - if let Some(r) = app.run("resource.import", serde_json::json!({ "path": p.display().to_string() })) - && let Some(name) = r.get("name").and_then(|n| n.as_str()) - { - use_environment(app, name); - } + use crate::file_dialogs::{Bound, FileDialog}; + app.ask_file(FileDialog::open().filter(tr("HDR environments"), ENV_EXTS), Bound::Project, |app, paths| { + let Some(p) = paths.first() else { return }; + if let Some(r) = app.run("resource.import", serde_json::json!({ "path": p.display().to_string() })) + && let Some(name) = r.get("name").and_then(|n| n.as_str()) + { + use_environment(app, name); + } + }); } /// Make image resource `name` the environment. diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 0c35d957..15bc9646 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -9,8 +9,11 @@ use texturecraft_engine::geom::primitives::BUILTINS; use texturecraft_render::ibl::ENVIRONMENTS; use crate::TextureCraftApp; +#[cfg(not(target_arch = "wasm32"))] +use crate::file_dialogs::{Bound, FileDialog}; use crate::i18n::LANGUAGES; use crate::i18n::{tr, trf}; +use crate::new_project_advanced::COMBO_WIDTH; use crate::state::Mode; use crate::theme::{Accent, Brightness, Tokens, caption}; use crate::widgets::{color_swatch, combo, icon_button, primary_button, slider, slider_edit}; @@ -36,16 +39,40 @@ pub(crate) fn ask_to_save(app: &mut TextureCraftApp, then: crate::state::Unsaved app.session.modified } +/// The close decision, once per frame in `logic` (which also runs while the window is minimized): +/// a close with unsaved changes waits on the dialog, in a window brought back so it can be +/// answered. A close nothing holds open quits through the platform's own path (craft-quit). +pub(crate) fn close_request(app: &mut TextureCraftApp, ctx: &egui::Context) { + let closing = ctx.input(|i| i.viewport().close_requested()); + // A stroke still open at the close, or released in this frame, is a change to ask about. + if closing + && app.session.stroke_active() + && let Err(error) = app.session.end_stroke() + { + app.toast(error.to_string(), true); + } + if closing && ask_to_save(app, crate::state::Unsaved::Quit) { + ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); + if ctx.input(|i| i.viewport().minimized == Some(true)) { + ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(false)); + ctx.send_viewport_cmd(egui::ViewportCommand::Focus); + } + } + craft_quit::on_close_request(ctx); +} + /// Quitting, opening or closing a project with unsaved changes asks whether to save them first /// (in the browser, Save downloads the project). fn unsaved(app: &mut TextureCraftApp, ctx: &egui::Context) { use crate::state::Unsaved; - if ctx.input(|i| i.viewport().close_requested()) && ask_to_save(app, Unsaved::Quit) { - ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); - } let Some(pending) = app.ui.windows.unsaved.clone() else { return }; + #[cfg(not(target_arch = "wasm32"))] + let (waiting_for_save, saved_by_dialog) = (app.saving_for_prompt, std::mem::take(&mut app.prompt_saved)); + #[cfg(target_arch = "wasm32")] + let (waiting_for_save, saved_by_dialog) = (false, false); + let mut open = true; let mut save_first = None; let mut cancel = false; @@ -61,33 +88,46 @@ fn unsaved(app: &mut TextureCraftApp, ctx: &egui::Context) { // One row keeps the window to its contents; a bare right-to-left layout fills the screen height ui.horizontal(|ui| { - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui.add(primary_button(ui, tr("Save"))).clicked() { - save_first = Some(true); - } - if ui.button(tr("Don't save")).clicked() { - save_first = Some(false); - } - if ui.button(tr("Cancel")).clicked() { - cancel = true; - } + // The answers wait while the Save dialog is open + ui.add_enabled_ui(!waiting_for_save, |ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.add(primary_button(ui, tr("Save"))).clicked() { + save_first = Some(true); + } + if ui.button(tr("Don't save")).clicked() { + save_first = Some(false); + } + if ui.button(tr("Cancel")).clicked() { + cancel = true; + } + }); }); }); }); if !open || cancel { app.ui.windows.unsaved = None; + #[cfg(not(target_arch = "wasm32"))] + { + app.saving_for_prompt = false; + } } match save_first { Some(true) => { + // An untitled project is saved from a dialog that answers on a later frame + #[cfg(not(target_arch = "wasm32"))] + { + app.saving_for_prompt = app.session.path.is_none(); + } file_action(app, ctx, "file.save"); } // Going ahead anyway: the changes are let go Some(false) => app.session.modified = false, + None if saved_by_dialog => {} None => return, } - // A cancelled or failed save keeps the project and this dialog open + // A canceled or failed save keeps the project and this dialog open if app.session.modified { return; } @@ -388,24 +428,28 @@ fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) { if !app.ui.windows.new_project { return; } + let mut open = true; let mut create = false; dialog("new_project", tr("New project"), &mut open).show(ctx, |ui| { ui.label(caption(tr("Basic settings"))); - egui::Grid::new("np").num_columns(2).spacing(vec2(12.0, 8.0)).show(ui, |ui| { + egui::Grid::new("np").num_columns(2).spacing(vec2(12.0, 8.0)).min_col_width(crate::new_project_advanced::form_label_width(ui)).show(ui, |ui| { ui.label(tr("3D mesh")); ui.horizontal(|ui| { let label = app.ui.new_project.file.clone().unwrap_or_else(|| { BUILTINS .iter() .find(|(id, _)| *id == app.ui.new_project.mesh) - .map(|(_, l)| trf("Built-in: {mesh}", &[("mesh", &tr(l))])) + .map(|(_, builtin_label)| trf("Built-in: {mesh}", &[("mesh", &tr(builtin_label))])) .unwrap_or_default() }); - egui::ComboBox::from_id_salt("np_mesh").width(200.0).selected_text(label).show_ui(ui, |ui| { - for (id, l) in BUILTINS { + egui::ComboBox::from_id_salt("np_mesh").width(COMBO_WIDTH).selected_text(label).show_ui(ui, |ui| { + for (id, builtin_label) in BUILTINS { if ui - .selectable_label(app.ui.new_project.mesh == id && app.ui.new_project.file.is_none(), trf("Built-in: {mesh}", &[("mesh", &tr(l))])) + .selectable_label( + app.ui.new_project.mesh == id && app.ui.new_project.file.is_none(), + trf("Built-in: {mesh}", &[("mesh", &tr(builtin_label))]), + ) .clicked() { app.ui.new_project.mesh = id.to_string(); @@ -413,22 +457,20 @@ fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) { } } }); - if file_dialogs_available() - && ui.button(tr("Select...")).clicked() - && let Some(p) = pick_mesh_file() - { - app.ui.new_project.file = Some(p); + if file_dialogs_available() && ui.button(tr("Select...")).clicked() { + ask_mesh_file(app); } }); ui.end_row(); ui.label(tr("Project template")); - let np = &mut app.ui.new_project; - egui::ComboBox::from_id_salt("np_template").width(200.0).selected_text(np.template.clone()).show_ui(ui, |ui| { - let user = app.session.templates.list.iter(); - for t in texturecraft_engine::template_cmds::builtin_templates().iter().chain(user) { - if ui.selectable_label(t.name == np.template, &t.name).clicked() { - np.template = t.name.clone(); - np.resolution = t.resolution; + let new_project = &mut app.ui.new_project; + egui::ComboBox::from_id_salt("np_template").width(COMBO_WIDTH).selected_text(new_project.template.clone()).show_ui(ui, |ui| { + let user_templates = app.session.templates.list.iter(); + for template in texturecraft_engine::template_cmds::builtin_templates().iter().chain(user_templates) { + if ui.selectable_label(template.name == new_project.template, &template.name).clicked() { + new_project.template = template.name.clone(); + new_project.resolution = template.resolution; + new_project.normal_format = None; } } }); @@ -447,20 +489,20 @@ fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.end_row(); ui.label(tr("Document resolution")); egui::ComboBox::from_id_salt("np_res").selected_text(format!("{0} x {0}", app.ui.new_project.resolution)).show_ui(ui, |ui| { - for r in [512u32, 1024, 2048, 4096] { - ui.selectable_value(&mut app.ui.new_project.resolution, r, format!("{r} x {r}")); + for size in [512u32, 1024, 2048, 4096] { + ui.selectable_value(&mut app.ui.new_project.resolution, size, format!("{size} x {size}")); } }); ui.end_row(); ui.label(tr("UV tiles (UDIM)")); - let tiles_label = |m: Option| match m { + let tiles_label = |tiles: Option| match tiles { None => tr("Automatic (from the mesh UVs)"), Some(true) => tr("On"), Some(false) => tr("Off"), }; egui::ComboBox::from_id_salt("np_tiles").selected_text(tiles_label(app.ui.new_project.uv_tiles)).show_ui(ui, |ui| { - for m in [None, Some(true), Some(false)] { - ui.selectable_value(&mut app.ui.new_project.uv_tiles, m, tiles_label(m)); + for tiles in [None, Some(true), Some(false)] { + ui.selectable_value(&mut app.ui.new_project.uv_tiles, tiles, tiles_label(tiles)); } }); ui.end_row(); @@ -469,6 +511,8 @@ fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.end_row(); }); ui.add_space(8.0); + crate::new_project_advanced::advanced_settings(app, ui); + ui.add_space(8.0); ui.horizontal(|ui| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { if ui.add(primary_button(ui, tr("Create"))).clicked() { @@ -481,15 +525,16 @@ fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) { }); }); if create { - let np = app.ui.new_project.clone(); - let (cmd, mesh) = match &np.file { + let new_project = app.ui.new_project.clone(); + let (command, mesh) = match &new_project.file { Some(path) => ("file.new", path.clone()), - None => ("project.new", np.mesh.clone()), + None => ("project.new", new_project.mesh.clone()), }; - let r = app.run(cmd, json!({"mesh": mesh, "resolution": np.resolution, "name": np.name, "uvTiles": np.uv_tiles, "template": np.template})).map(|_| ()); - if r.is_some() { + let params = json!({"mesh": mesh, "resolution": new_project.resolution, "name": new_project.name, "uvTiles": new_project.uv_tiles, "template": new_project.template}); + if app.run(command, params).is_some() { app.ui.windows.new_project = false; app.ui.mode = Mode::Painting; + crate::new_project_advanced::apply_after_create(app, &new_project); } } if !open { @@ -502,6 +547,8 @@ fn settings(app: &mut TextureCraftApp, ctx: &egui::Context) { let mut open = app.ui.windows.settings; // A language whose script no font draws is listed by its English name and disabled. let drawable = LANGUAGES.each_ref().map(|l| crate::fonts::Script::of_language(l.code).is_none_or(|s| app.fonts.covers(s))); + #[cfg(not(target_arch = "wasm32"))] + let mut pick_data_folder = false; window("settings", tr("Settings"), &mut open).default_width(360.0).show(ctx, |ui| { let p = &mut app.ui.prefs; // Every section is a two-column form: labels on the left, controls aligned beside them. @@ -596,10 +643,8 @@ fn settings(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.horizontal(|ui| { let default = crate::data_folder("").display().to_string(); ui.add(egui::TextEdit::singleline(&mut p.data_folder).hint_text(default).desired_width(260.0)); - if ui.button("...").clicked() - && let Some(d) = rfd::FileDialog::new().set_directory(crate::data_folder(&p.data_folder)).pick_folder() - { - p.data_folder = d.display().to_string(); + if ui.button("...").clicked() { + pick_data_folder = true; } }); ui.end_row(); @@ -624,6 +669,14 @@ fn settings(app: &mut TextureCraftApp, ctx: &egui::Context) { } }); app.ui.windows.settings = open; + #[cfg(not(target_arch = "wasm32"))] + if pick_data_folder { + app.ask_file(FileDialog::folder().directory(crate::data_folder(&app.ui.prefs.data_folder)), Bound::App, |app, paths| { + if let Some(d) = paths.first() { + app.ui.prefs.data_folder = d.display().to_string(); + } + }); + } } /// Browser File › Export Mesh: pick the download format @@ -693,14 +746,17 @@ pub fn file_dialogs_available() -> bool { } #[cfg(not(target_arch = "wasm32"))] -fn pick_mesh_file() -> Option { - rfd::FileDialog::new().add_filter(tr("3D meshes"), &texturecraft_engine::formats::mesh_import::MESH_EXTENSIONS).pick_file().map(|p| p.display().to_string()) +fn ask_mesh_file(app: &mut TextureCraftApp) { + let dialog = FileDialog::open().filter(tr("3D meshes"), &texturecraft_engine::formats::mesh_import::MESH_EXTENSIONS); + app.ask_file(dialog, Bound::App, |app, paths| { + if let Some(p) = paths.first() { + app.ui.new_project.file = Some(p.display().to_string()); + } + }); } #[cfg(target_arch = "wasm32")] -fn pick_mesh_file() -> Option { - None -} +fn ask_mesh_file(_app: &mut TextureCraftApp) {} /// Remember a project path in File ▸ Recent projects. pub fn remember(app: &mut TextureCraftApp, path: &str) { @@ -713,28 +769,29 @@ pub fn remember(app: &mut TextureCraftApp, path: &str) { #[cfg(not(target_arch = "wasm32"))] pub fn layout_file(app: &mut TextureCraftApp, save: bool) { let dir = crate::user_dir("layouts"); - let dialog = rfd::FileDialog::new().add_filter(tr("UI layout"), &["json"]).set_directory(&dir); - let result = if save { - let Some(path) = dialog.set_file_name("layout.json").save_file() else { return }; - let layout = crate::UiState { recent: Vec::new(), ..app.ui.clone() }; - std::fs::create_dir_all(&dir) - .map_err(|e| e.to_string()) - .and_then(|_| serde_json::to_vec_pretty(&layout).map_err(|e| e.to_string())) - .and_then(|bytes| std::fs::write(&path, bytes).map_err(|e| e.to_string())) - .map(|_| trf("Saved UI layout {path}", &[("path", &path.display())])) - } else { - let Some(path) = dialog.pick_file() else { return }; - std::fs::read(&path).map_err(|e| e.to_string()).and_then(|bytes| serde_json::from_slice::(&bytes).map_err(|e| e.to_string())).map( - |layout| { - app.ui.adopt_layout(layout); - trf("Loaded UI layout {path}", &[("path", &path.display())]) - }, - ) - }; - match result { - Ok(msg) => app.toast(msg, false), - Err(e) => app.toast(trf("UI layout: {error}", &[("error", &e)]), true), - } + let dialog = if save { FileDialog::save().file_name("layout.json") } else { FileDialog::open() }; + app.ask_file(dialog.filter(tr("UI layout"), &["json"]).directory(dir.clone()), Bound::App, move |app, paths| { + let Some(path) = paths.first() else { return }; + let result = if save { + let layout = crate::UiState { recent: Vec::new(), ..app.ui.clone() }; + std::fs::create_dir_all(&dir) + .map_err(|e| e.to_string()) + .and_then(|_| serde_json::to_vec_pretty(&layout).map_err(|e| e.to_string())) + .and_then(|bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())) + .map(|_| trf("Saved UI layout {path}", &[("path", &path.display())])) + } else { + std::fs::read(path).map_err(|e| e.to_string()).and_then(|bytes| serde_json::from_slice::(&bytes).map_err(|e| e.to_string())).map( + |layout| { + app.ui.adopt_layout(layout); + trf("Loaded UI layout {path}", &[("path", &path.display())]) + }, + ) + }; + match result { + Ok(msg) => app.toast(msg, false), + Err(e) => app.toast(trf("UI layout: {error}", &[("error", &e)]), true), + } + }); } /// The browser has no file paths; layouts persist with the rest of the UI state. @@ -748,10 +805,11 @@ pub fn layout_file(app: &mut TextureCraftApp, _save: bool) { pub fn file_action(app: &mut TextureCraftApp, _ctx: &egui::Context, id: &str) -> bool { match id { "file.open" => { - let pick = rfd::FileDialog::new().add_filter(tr("TextureCraft project or mesh"), crate::web_files::OPEN_EXTS).pick_file(); - if let Some(p) = pick { - open_path(app, &p.display().to_string()); - } + app.ask_file(FileDialog::open().filter(tr("TextureCraft project or mesh"), crate::web_files::OPEN_EXTS), Bound::App, |app, paths| { + if let Some(p) = paths.first() { + open_path(app, &p.display().to_string()); + } + }); true } "file.save" if app.session.path.is_some() => { @@ -761,83 +819,126 @@ pub fn file_action(app: &mut TextureCraftApp, _ctx: &egui::Context, id: &str) -> } true } - "file.save" | "file.saveAs" | "file.saveCopy" => { - let name = crate::web_files::project_file_name(app); - if let Some(p) = - rfd::FileDialog::new().add_filter(tr("TextureCraft project"), &[texturecraft_engine::core::PROJECT_EXT]).set_file_name(name).save_file() - { - let path = p.display().to_string(); - let cmd = if id == "file.saveCopy" { "file.saveCopy" } else { "file.saveAs" }; - if app.run(cmd, json!({"path": path})).is_some() { - remember(app, &path); - app.toast(trf("Saved {path}", &[("path", &path)]), false); - } - } + "file.save" | "file.saveAs" => { + ask_save_project(app, "file.saveAs"); + true + } + "file.saveCopy" => { + ask_save_project(app, "file.saveCopy"); true } "material.load" => { - for p in rfd::FileDialog::new().add_filter(tr("Materials"), crate::web_files::MATERIAL_EXTS).pick_files().unwrap_or_default() { - app.run("material.load", json!({"path": p.display().to_string()})); - } + app.ask_file(FileDialog::open_many().filter(tr("Materials"), crate::web_files::MATERIAL_EXTS), Bound::Project, |app, paths| { + for p in paths { + app.run("material.load", json!({"path": p.display().to_string()})); + } + }); true } "file.importResources" | "resource.import" => { - let picks = rfd::FileDialog::new().add_filter(tr("Images"), crate::web_files::IMAGE_EXTS).pick_files(); - for p in picks.unwrap_or_default() { - if let Some(r) = app.run("resource.import", json!({"path": p.display().to_string()})) { - let name = r.get("name").and_then(|n| n.as_str()).unwrap_or_default().to_string(); - app.toast(trf("Imported {name}", &[("name", &name)]), false); + app.ask_file(FileDialog::open_many().filter(tr("Images"), crate::web_files::IMAGE_EXTS), Bound::Project, |app, paths| { + if paths.is_empty() { + return; } - } - app.ui.dock.focus(crate::docking::Panel::Assets); + for p in paths { + if let Some(r) = app.run("resource.import", json!({"path": p.display().to_string()})) { + let name = r.get("name").and_then(|n| n.as_str()).unwrap_or_default().to_string(); + app.toast(trf("Imported {name}", &[("name", &name)]), false); + } + } + app.ui.dock.focus(crate::docking::Panel::Assets); + }); true } "file.importMaterialX" => { - if let Some(p) = rfd::FileDialog::new().add_filter(tr("MaterialX materials"), &["mtlx"]).pick_file() - && let Some(r) = app.run("file.importMaterialX", json!({"path": p.display().to_string()})) - { - let name = r.get("material").and_then(|n| n.as_str()).unwrap_or_default().to_string(); - for w in r.get("warnings").and_then(|w| w.as_array()).into_iter().flatten().filter_map(|w| w.as_str()) { - app.session.log.push(format!("MaterialX {name}: {w}")); + app.ask_file(FileDialog::open().filter(tr("MaterialX materials"), &["mtlx"]), Bound::Project, |app, paths| { + if let Some(p) = paths.first() + && let Some(r) = app.run("file.importMaterialX", json!({"path": p.display().to_string()})) + { + let name = r.get("material").and_then(|n| n.as_str()).unwrap_or_default().to_string(); + for w in r.get("warnings").and_then(|w| w.as_array()).into_iter().flatten().filter_map(|w| w.as_str()) { + app.session.log.push(format!("MaterialX {name}: {w}")); + } + app.toast(trf("Imported {name}", &[("name", &name)]), false); + app.ui.dock.focus(crate::docking::Panel::Layers); } - app.toast(trf("Imported {name}", &[("name", &name)]), false); - app.ui.dock.focus(crate::docking::Panel::Layers); - } + }); true } "file.exportMesh" => { let name = format!("{}.obj", texturecraft_engine::formats::export::sanitize_file_stem(&app.session.doc.project.name)); - if let Some(p) = rfd::FileDialog::new() - .add_filter(tr("Wavefront OBJ with MTL, textures alongside"), &["obj"]) - .add_filter(tr("glTF binary with textures"), &["glb"]) - .add_filter(tr("USDZ with textures"), &["usdz"]) - .add_filter(tr("USD text, textures alongside"), &["usda"]) - .add_filter(tr("USD binary, textures alongside"), &["usdc"]) - .set_file_name(name) - .save_file() - && let Some(r) = app.run("file.exportMesh", json!({"path": p.display().to_string()})) - { - let p = r.get("path").and_then(|p| p.as_str()).unwrap_or_default().to_string(); - app.toast(trf("Exported mesh to {path}", &[("path", &p)]), false); - } + let dialog = FileDialog::save() + .filter(tr("Wavefront OBJ with MTL, textures alongside"), &["obj"]) + .filter(tr("glTF binary with textures"), &["glb"]) + .filter(tr("USDZ with textures"), &["usdz"]) + .filter(tr("USD text, textures alongside"), &["usda"]) + .filter(tr("USD binary, textures alongside"), &["usdc"]) + .file_name(name); + app.ask_file(dialog, Bound::Project, |app, paths| { + if let Some(p) = paths.first() + && let Some(r) = app.run("file.exportMesh", json!({"path": p.display().to_string()})) + { + let p = r.get("path").and_then(|p| p.as_str()).unwrap_or_default().to_string(); + app.toast(trf("Exported mesh to {path}", &[("path", &p)]), false); + } + }); true } "file.reimportMesh" => { - // Painted strokes follow the surface when the new mesh's UVs differ. - let path = match app.session.mesh_source { - Some(_) => None, - None => match rfd::FileDialog::new().add_filter(tr("3D meshes"), &texturecraft_engine::formats::mesh_import::MESH_EXTENSIONS).pick_file() { - Some(p) => Some(p.display().to_string()), - None => return true, - }, - }; - app.run("file.reimportMesh", json!({"path": path, "preserveStrokes": true})); + // The file the mesh came from is read again from disk; ask only when it's gone. + if let Some(path) = app.session.remembered_mesh_path().map(str::to_string) { + reimport_mesh(app, path); + return true; + } + let dialog = FileDialog::open().filter(tr("3D meshes"), &texturecraft_engine::formats::mesh_import::MESH_EXTENSIONS); + app.ask_file(dialog, Bound::Project, |app, paths| { + if let Some(p) = paths.first() { + reimport_mesh(app, p.display().to_string()); + } + }); true } _ => false, } } +/// Asks where to save the project and runs `cmd` with the answer. Each caller is its own dialog +/// request, so Save As and Save a Copy queue separately. +#[cfg(not(target_arch = "wasm32"))] +#[track_caller] +fn ask_save_project(app: &mut TextureCraftApp, cmd: &'static str) { + let name = crate::web_files::project_file_name(app); + let dialog = FileDialog::save().filter(tr("TextureCraft project"), &[texturecraft_engine::core::PROJECT_EXT]).file_name(name); + // Save a Copy leaves the project unsaved, so it never answers the unsaved-changes prompt. + let for_prompt = app.saving_for_prompt && cmd == "file.saveAs"; + let asked = app.ask_file(dialog, Bound::Project, move |app, paths| { + let mut saved = false; + if let Some(p) = paths.first() { + let path = p.display().to_string(); + saved = app.run(cmd, json!({"path": path})).is_some(); + if saved { + remember(app, &path); + app.toast(trf("Saved {path}", &[("path", &path)]), false); + } + } + // The answer ends the wait. A canceled or failed save leaves the prompt open for an answer. + if for_prompt { + app.saving_for_prompt = false; + app.prompt_saved = saved && !app.session.modified; + } + }); + // A Save As already on its way answers for itself: the prompt's buttons stay usable. + if for_prompt && !asked { + app.saving_for_prompt = false; + } +} + +/// Reimport the mesh; painted strokes follow the surface when the new mesh's UVs differ. +#[cfg(not(target_arch = "wasm32"))] +fn reimport_mesh(app: &mut TextureCraftApp, path: String) { + app.run("file.reimportMesh", json!({"path": path, "preserveStrokes": true})); +} + /// Open a project or mesh by path (menus, Recent projects, drag and drop). #[cfg(not(target_arch = "wasm32"))] pub fn open_path(app: &mut TextureCraftApp, path: &str) { @@ -925,10 +1026,12 @@ fn export_settings_tab(app: &mut TextureCraftApp, ui: &mut Ui, presets: &[textur ui.label(tr("Output directory")); ui.horizontal(|ui| { ui.add(egui::TextEdit::singleline(&mut app.ui.export.dir).desired_width(360.0)); - if ui.button("...").clicked() - && let Some(d) = rfd::FileDialog::new().set_directory(&app.ui.export.dir).pick_folder() - { - app.ui.export.dir = d.display().to_string(); + if ui.button("...").clicked() { + app.ask_file(FileDialog::folder().directory(app.ui.export.dir.clone()), Bound::App, |app, paths| { + if let Some(d) = paths.first() { + app.ui.export.dir = d.display().to_string(); + } + }); } }); ui.end_row(); @@ -1109,3 +1212,95 @@ pub fn export(app: &mut TextureCraftApp, ctx: &egui::Context) { app.ui.windows.export = false; } } + +#[cfg(test)] +mod tests { + use egui_kittest::Harness; + use egui_kittest::kittest::{NodeT as _, Queryable as _}; + + use super::*; + use crate::state::Unsaved; + + fn harness() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut h = Harness::builder().with_size(vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.run_steps(2); + h + } + + #[test] + fn a_canceled_save_dialog_does_not_answer_the_prompt() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut h = harness(); + let app = h.state_mut(); + app.file_dialogs.set_override(Some(Box::new(|_| crate::file_dialogs::Answer::Cancelled))); + app.ui.windows.unsaved = Some(Unsaved::Quit); + // Saved elsewhere, by a script, while the dialog was open. + app.session.modified = false; + app.saving_for_prompt = true; + ask_save_project(app, "file.saveAs"); + h.run_steps(3); + assert_eq!(h.state().ui.windows.unsaved, Some(Unsaved::Quit), "the prompt still waits for an answer"); + } + + #[test] + fn the_prompts_buttons_wait_for_its_save_dialog() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut h = harness(); + let app = h.state_mut(); + app.ui.windows.unsaved = Some(Unsaved::Quit); + app.session.modified = true; + h.run_steps(2); + for label in ["Save", "Don't save", "Cancel"] { + assert!(!h.get_by_label(label).accesskit_node().is_disabled(), "{label} answers while no dialog is open"); + } + h.state_mut().saving_for_prompt = true; + h.run_steps(2); + for label in ["Save", "Don't save", "Cancel"] { + assert!(h.get_by_label(label).accesskit_node().is_disabled(), "{label} waits for the Save dialog"); + } + } + + #[test] + fn a_save_a_copy_answer_does_not_end_the_prompts_wait() { + let mut h = harness(); + let app = h.state_mut(); + app.file_dialogs.set_override(Some(Box::new(|_| crate::file_dialogs::Answer::Cancelled))); + app.saving_for_prompt = true; + ask_save_project(app, "file.saveCopy"); + h.run_steps(3); + assert!(h.state().saving_for_prompt, "only the prompt's own Save As ends the wait"); + } + + #[test] + fn a_save_as_already_on_its_way_ends_the_prompts_wait() { + let mut h = harness(); + let app = h.state_mut(); + // One call site, as File › Save As and the prompt's Save share one. + for waiting in [false, true] { + app.saving_for_prompt = waiting; + ask_save_project(app, "file.saveAs"); + } + assert_eq!(app.file_dialogs.pending(), 1); + assert!(!app.saving_for_prompt, "the prompt's buttons work again"); + } + + /// A change that lands after the Save dialog saved (a bake finishing that frame) keeps the + /// question open with buttons that still answer. + #[test] + fn a_change_after_the_dialog_saved_leaves_the_prompt_usable() { + // The harness keeps the process-wide language at English while this asserts on labels. + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut h = harness(); + let app = h.state_mut(); + app.ui.windows.unsaved = Some(Unsaved::Quit); + app.session.modified = true; + app.prompt_saved = true; + h.run_steps(2); + assert_eq!(h.state().ui.windows.unsaved, Some(Unsaved::Quit), "the project has unsaved changes again"); + assert!(!h.state().saving_for_prompt); + h.get_by_label("Cancel").click(); + h.run_steps(2); + assert!(h.state().ui.windows.unsaved.is_none()); + } +} diff --git a/crates/ui-egui/tests/fixture/ui_state_before_json.ron b/crates/ui-egui/tests/fixture/ui_state_before_json.ron new file mode 100644 index 00000000..db17d424 --- /dev/null +++ b/crates/ui-egui/tests/fixture/ui_state_before_json.ron @@ -0,0 +1 @@ +(mode:Painting,layout:Split,split_ratio:0.3,dock:(version:2,layout:(root:Some(Split(axis:Horizontal,size:Ratio(0.78),first:Tabs(panels:[Viewport],active:0),second:Split(axis:Vertical,size:Ratio(0.125),first:Tabs(panels:[TextureSetList],active:0),second:Split(axis:Vertical,size:Ratio(0.57),first:Tabs(panels:[Layers,TextureSetSettings],active:0),second:Tabs(panels:[Properties],active:0))))),floating:[(id:387041999283132987,panels:[Display],active:0,rect:(960.0,90.0,300.0,380.0))]),hidden:[(Shader,(floating:Some((960.0,140.0,300.0,380.0)),anchor:None,placement:Tab(before:None),size:None,stack:None,sibling:[],group:None)),(History,(floating:Some((960.0,190.0,300.0,380.0)),anchor:None,placement:Tab(before:None),size:None,stack:None,sibling:[],group:None)),(Log,(floating:Some((960.0,240.0,300.0,380.0)),anchor:None,placement:Tab(before:None),size:None,stack:None,sibling:[],group:None)),(BakeMaps,(floating:None,anchor:Some(TextureSetList),placement:Tab(before:None),size:None,stack:None,sibling:[],group:None)),(BakeSettings,(floating:None,anchor:Some(TextureSetList),placement:Tab(before:None),size:None,stack:None,sibling:[],group:None)),(MeshMapBakers,(floating:None,anchor:Some(TextureSetList),placement:Tab(before:None),size:None,stack:None,sibling:[],group:None)),(Assets,(floating:None,anchor:Some(Viewport),placement:Split(Left),size:Some(Ratio(0.115)),stack:None,sibling:[Viewport,TextureSetList,Layers,TextureSetSettings,Properties],group:None))],saved:None,locked:false),inactive_mode_dock:(version:2,layout:(root:Some(Split(axis:Horizontal,size:FixedFirst(536.0),first:Split(axis:Vertical,size:FixedSecond(160.0),first:Split(axis:Horizontal,size:FixedFirst(200.0),first:Split(axis:Vertical,size:Ratio(0.4),first:Tabs(panels:[TextureSetList],active:0),second:Tabs(panels:[MeshMapBakers],active:0)),second:Tabs(panels:[BakeSettings,BakeMaps],active:0)),second:Tabs(panels:[Log],active:0)),second:Tabs(panels:[Viewport],active:0))),floating:[]),hidden:[(Display,(floating:Some((960.0,90.0,300.0,380.0)),anchor:None,placement:Tab(before:None),size:None,stack:None,sibling:[],group:None)),(Shader,(floating:Some((960.0,140.0,300.0,380.0)),anchor:None,placement:Tab(before:None),size:None,stack:None,sibling:[],group:None)),(History,(floating:Some((960.0,190.0,300.0,380.0)),anchor:None,placement:Tab(before:None),size:None,stack:None,sibling:[],group:None)),(Assets,(floating:None,anchor:Some(Viewport),placement:Split(Left),size:Some(Ratio(0.115)),stack:None,sibling:[Viewport,TextureSetList,Layers,TextureSetSettings,Properties],group:None)),(Layers,(floating:None,anchor:Some(TextureSetSettings),placement:Tab(before:Some(TextureSetSettings)),size:None,stack:None,sibling:[],group:None)),(TextureSetSettings,(floating:None,anchor:Some(Layers),placement:Tab(before:None),size:None,stack:None,sibling:[],group:None)),(Properties,(floating:None,anchor:Some(Layers),placement:Split(Bottom),size:Some(Ratio(0.57)),stack:None,sibling:[Layers,TextureSetSettings],group:None))],saved:None,locked:false),dock_is_baking:false,bake_layout_version:1,selected_baked_map:None,hide_ui:false,windows:(export:false,new_project:false,about:false,shortcuts:false,settings:false,export_mesh:false),uv_zoom:1.0,uv_pan:(0.0,0.0),layer_channel:BaseColor,shelf_filter:"",shelf_tab:0,props_tab:Brush,text:(text:"",font:"",style:""),rename:None,new_project:(mesh:"material_ball",resolution:2048,name:"Untitled",file:None,uv_tiles:None,template:"PBR - Metallic Roughness"),uv_wireframe:true,wireframe_3d:false,render:(max_samples:256,bounces:6,denoise:true,cpu:false),prefs:(ui_scale:1.0,autosave_minutes:10,language:"en",viewport_texture:0,brightness:mediumDark,accent:copper,system_title_bar:false,start_window:true,data_folder:""),export:(dir:"/example/export",preset:"Document channels + Normal + AO",format:"",bit_depth:0,padding:"infinite",dilation:16,size:0,normal_format:"",color_space:"",skip:[],tab:0),recent:["/example/project-0.tcraft","/example/project-1.tcraft","/example/project-2.tcraft","/example/project-3.tcraft","/example/project-4.tcraft","/example/project-5.tcraft","/example/project-6.tcraft","/example/project-7.tcraft","/example/project-8.tcraft","/example/project-9.tcraft","/example/project-10.tcraft","/example/project-11.tcraft","/example/project-12.tcraft","/example/project-13.tcraft","/example/project-14.tcraft","/example/project-15.tcraft","/example/project-16.tcraft","/example/project-17.tcraft","/example/project-18.tcraft","/example/project-19.tcraft"],keymap:{},bake_paint_brush:(on:false,target:Skew,radius:0.03,value:1.0,hardness:0.5)) diff --git a/crates/ui-egui/tests/bake_mode.rs b/crates/ui-egui/tests/it/bake_mode.rs similarity index 100% rename from crates/ui-egui/tests/bake_mode.rs rename to crates/ui-egui/tests/it/bake_mode.rs diff --git a/crates/ui-egui/tests/brush_drag.rs b/crates/ui-egui/tests/it/brush_drag.rs similarity index 100% rename from crates/ui-egui/tests/brush_drag.rs rename to crates/ui-egui/tests/it/brush_drag.rs diff --git a/crates/ui-egui/tests/close_unsaved.rs b/crates/ui-egui/tests/it/close_unsaved.rs similarity index 84% rename from crates/ui-egui/tests/close_unsaved.rs rename to crates/ui-egui/tests/it/close_unsaved.rs index a0c5481d..47996530 100644 --- a/crates/ui-egui/tests/close_unsaved.rs +++ b/crates/ui-egui/tests/it/close_unsaved.rs @@ -56,10 +56,25 @@ fn cancel_keeps_the_app_open() { fn closing_without_changes_does_not_ask() { let mut h = harness(false); request_close(&mut h); - assert!(!sent(&h, &ViewportCommand::CancelClose)); + // macOS keeps the window for `-[NSApplication terminate:]` to close; elsewhere it closes now. + assert_eq!(sent(&h, &ViewportCommand::CancelClose), cfg!(target_os = "macos")); assert!(h.state().ui.windows.unsaved.is_none()); } +/// `ui` does not run while the window is minimized, so the close decision is made in `logic`. +#[test] +fn closing_a_minimized_window_with_changes_brings_it_back_to_ask() { + let mut h = harness(true); + let root = h.input_mut().viewports.entry(ViewportId::ROOT).or_default(); + root.minimized = Some(true); + root.events.push(ViewportEvent::Close); + h.step(); + assert!(sent(&h, &ViewportCommand::CancelClose), "the close waits for an answer"); + assert!(sent(&h, &ViewportCommand::Minimized(false)), "the window comes back"); + assert!(sent(&h, &ViewportCommand::Focus)); + assert_eq!(h.state().ui.windows.unsaved, Some(Unsaved::Quit)); +} + /// A project picked or dropped in the browser arrives as bytes; it waits on the same dialog. #[test] fn a_dropped_project_waits_on_the_dialog() { diff --git a/crates/ui-egui/tests/color_picker.rs b/crates/ui-egui/tests/it/color_picker.rs similarity index 100% rename from crates/ui-egui/tests/color_picker.rs rename to crates/ui-egui/tests/it/color_picker.rs diff --git a/crates/ui-egui/tests/it/color_selection_editor.rs b/crates/ui-egui/tests/it/color_selection_editor.rs new file mode 100644 index 00000000..81c34868 --- /dev/null +++ b/crates/ui-egui/tests/it/color_selection_editor.rs @@ -0,0 +1,269 @@ +//! The color selection editor in Properties: one row per ID color, remove, and the pick mode + +use egui::{Event, Modifiers, PointerButton, Pos2}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::{Value, json}; +use texturecraft_engine::core::{BakedMap, EffectKind, LayerId}; +use texturecraft_engine::{StackTarget, ViewMode, execute}; +use texturecraft_ui_egui::TextureCraftApp; + +const FIRST: [f32; 3] = [200.0 / 255.0, 0.0, 0.0]; +const SECOND: [f32; 3] = [10.0 / 255.0, 1.0, 0.0]; +const THIRD: [f32; 3] = [30.0 / 255.0, 0.0, 1.0]; +const ID_PART: [u8; 3] = [90, 160, 220]; + +/// An ID map of one color, as a PNG +fn id_map_png() -> Vec { + let [red, green, blue] = ID_PART; + let image = image::RgbaImage::from_pixel(4, 4, image::Rgba([red, green, blue, 255])); + let mut bytes = Vec::new(); + image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + bytes +} + +/// A selected color selection of three colors on a fill layer's mask +fn color_selection_session(with_id_map: bool) -> (texturecraft_engine::Session, LayerId) { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + if with_id_map { + let image = session.import_resource_bytes("id.png", id_map_png()).unwrap(); + execute(&mut session, "textureSet.meshMap.set", &json!({"map": "id", "image": image})).unwrap(); + } else { + // The sample bakes an ID map with the others + execute(&mut session, "textureSet.meshMap.clear", &json!({"map": "id"})).unwrap(); + } + + let layer = LayerId(execute(&mut session, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap()); + execute(&mut session, "mask.add.colorSelection", &Value::Null).unwrap(); + let effect = session.doc.project.layer(layer).unwrap().mask.as_ref().unwrap().effects[0].id; + execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": [FIRST, SECOND, THIRD]})).unwrap(); + session.target = StackTarget::Effect(effect); + (session, effect) +} + +fn app_with_color_selection(with_id_map: bool) -> (Harness<'static, TextureCraftApp>, LayerId) { + let (session, effect) = color_selection_session(with_id_map); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.run_steps(4); + (harness, effect) +} + +fn colors(harness: &Harness<'_, TextureCraftApp>, effect: LayerId) -> Vec<[f32; 3]> { + match &harness.state().session.doc.project.effect(effect).unwrap().1.kind { + EffectKind::ColorSelection { colors, .. } => colors.clone(), + other => panic!("not a color selection: {other:?}"), + } +} + +fn click_at(harness: &mut Harness<'_, TextureCraftApp>, position: Pos2) { + harness.event(Event::PointerMoved(position)); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: position, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: position, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(3); +} + +/// Whether the last frame drew the eyedropper glyph with its tip at `pointer` +fn eyedropper_at(harness: &Harness<'_, TextureCraftApp>, pointer: Pos2) -> bool { + harness.output().shapes.iter().any(|clipped| match &clipped.shape { + egui::Shape::Text(text) => text.galley.text() == egui_phosphor::regular::EYEDROPPER && (text.pos.x - pointer.x).abs() < 1.0, + _ => false, + }) +} + +fn pick_color_label() -> String { + format!("{} Pick color", egui_phosphor::regular::EYEDROPPER) +} + +#[test] +fn each_color_gets_a_row_and_remove_sends_the_list_without_it() { + let (mut harness, effect) = app_with_color_selection(false); + for readout in ["R: 200", "R: 10", "R: 30"] { + assert!(harness.query_by_label(readout).is_some(), "{readout} row"); + } + + let second_row = harness.get_by_label("R: 10").rect().center().y; + let remove = harness + .query_all_by_label("Remove") + .find(|button| (button.rect().center().y - second_row).abs() < 8.0) + .expect("the second row's remove button") + .rect() + .center(); + click_at(&mut harness, remove); + + assert_eq!(colors(&harness, effect), vec![FIRST, THIRD]); +} + +#[test] +fn pick_mode_shows_the_id_map_and_a_click_on_the_mesh_adds_its_color() { + let (mut harness, effect) = app_with_color_selection(true); + harness.get_by_label(&pick_color_label()).click(); + harness.run_steps(3); + assert!(harness.state().picking_id_color.is_some_and(|pick| pick.effect == effect && pick.index.is_none())); + assert_eq!(harness.state().session.view, ViewMode::MeshMap(BakedMap::Id)); + + let center = harness.state().viewport_rect.center(); + harness.event(Event::PointerMoved(center)); + harness.run_steps(2); + assert!(eyedropper_at(&harness, center), "the pointer is an eyedropper"); + + click_at(&mut harness, center); + + let picked = colors(&harness, effect); + assert_eq!(picked.len(), 4, "the click adds a row"); + assert_eq!(picked[3], ID_PART.map(|channel| channel as f32 / 255.0)); + assert!(harness.state().picking_id_color.is_none(), "one click ends pick mode"); + assert_eq!(harness.state().session.view, ViewMode::Material, "the earlier view comes back"); +} + +#[test] +fn without_an_id_map_picking_is_off_and_a_warning_says_why() { + let (mut harness, _) = app_with_color_selection(false); + let warning = format!("{} Bake an ID map (F8) to pick colors from the mesh.", egui_phosphor::regular::WARNING); + assert!(harness.query_by_label(&warning).is_some()); + + harness.get_by_label(&pick_color_label()).click(); + harness.run_steps(3); + assert!(harness.state().picking_id_color.is_none()); +} + +fn row_button(harness: &Harness<'_, TextureCraftApp>, readout: &str, label: &str) -> Pos2 { + let row_y = harness.get_by_label(readout).rect().center().y; + harness.query_all_by_label(label).find(|button| (button.rect().center().y - row_y).abs() < 8.0).unwrap().rect().center() +} + +#[test] +fn removing_a_row_cancels_a_pending_replacement() { + let (mut harness, effect) = app_with_color_selection(true); + let repick = row_button(&harness, "R: 10", "Pick color"); + click_at(&mut harness, repick); + assert_eq!(harness.state().picking_id_color.unwrap().index, Some(1)); + + let remove = row_button(&harness, "R: 200", "Remove"); + click_at(&mut harness, remove); + + assert_eq!(colors(&harness, effect), vec![SECOND, THIRD]); + assert!(harness.state().picking_id_color.is_none(), "removing a row must not leave a replacement targeting a different color"); + assert_eq!(harness.state().session.view, ViewMode::Material); +} + +#[test] +fn escape_cancels_the_pick_without_editing_colors() { + let (mut harness, effect) = app_with_color_selection(true); + harness.get_by_label(&pick_color_label()).click(); + harness.run_steps(3); + let history = harness.state().session.history_labels(); + + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + + assert!(harness.state().picking_id_color.is_none()); + assert_eq!(harness.state().session.view, ViewMode::Material); + assert_eq!(colors(&harness, effect), vec![FIRST, SECOND, THIRD]); + assert_eq!(harness.state().session.history_labels(), history); +} + +#[test] +fn picking_from_the_popup_closes_it_before_the_viewport_click() { + use texturecraft_ui_egui::properties_popup::{self, PropertiesPopup}; + + let (mut harness, effect) = app_with_color_selection(true); + let bounds = harness.state().viewport_rect; + harness.state_mut().properties_popup = Some(PropertiesPopup::Open { at: bounds.center() - egui::vec2(100.0, 100.0), bounds }); + harness.run_steps(4); + let popup = harness.ctx.memory(|memory| memory.area_rect(properties_popup::area_id())).unwrap(); + let pick = harness.query_all_by_label(&pick_color_label()).find(|button| popup.contains_rect(button.rect())).unwrap().rect().center(); + click_at(&mut harness, pick); + + assert!(harness.state().picking_id_color.is_some()); + let center = harness.state().viewport_rect.center(); + assert!(popup.contains(center), "pick a point the popup would otherwise cover"); + click_at(&mut harness, center); + assert_eq!(colors(&harness, effect).len(), 4, "the next viewport click must pick, even under the former popup"); + assert_eq!(harness.state().properties_popup, None); +} + +#[test] +fn a_2d_pick_replaces_the_chosen_row_and_undo_restores_it() { + use texturecraft_ui_egui::state::ViewLayout; + + let (mut harness, effect) = app_with_color_selection(true); + harness.state_mut().ui.layout = ViewLayout::Only3D; + harness.run_steps(3); + let center = harness.state().viewport_rect.center(); + harness.state_mut().ui.layout = ViewLayout::Only2D; + harness.run_steps(3); + let repick = row_button(&harness, "R: 10", "Pick color"); + click_at(&mut harness, repick); + click_at(&mut harness, center); + + assert_eq!(colors(&harness, effect), vec![FIRST, ID_PART.map(|channel| channel as f32 / 255.0), THIRD]); + assert_eq!(harness.state().session.view, ViewMode::Material); + assert!(!harness.state().session.stroke_active()); + harness.state_mut().session.undo().unwrap(); + assert_eq!(colors(&harness, effect), vec![FIRST, SECOND, THIRD]); +} + +#[test] +fn deselection_cancels_picking_and_preserves_a_view_chosen_meanwhile() { + let (mut harness, effect) = app_with_color_selection(true); + harness.get_by_label(&pick_color_label()).click(); + harness.run_steps(3); + execute(&mut harness.state_mut().session, "viewport.view", &json!({"mode": "uvChecker"})).unwrap(); + harness.state_mut().session.target = StackTarget::Content; + harness.run_steps(3); + + assert!(harness.state().picking_id_color.is_none()); + assert_eq!(harness.state().session.view, ViewMode::UvChecker); + assert_eq!(colors(&harness, effect), vec![FIRST, SECOND, THIRD]); +} + +#[test] +#[ignore = "requires a GPU adapter; set TC_UI_SNAPSHOTS to save the rendered views"] +fn color_selection_snapshots_and_quick_mask_pick() { + let (session, _) = color_selection_session(true); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|context| { + let mut app = TextureCraftApp::new(context, session); + app.ui.layout = texturecraft_ui_egui::state::ViewLayout::Only3D; + app + }); + let adapter = harness.state().render_state.as_ref().unwrap().adapter.get_info(); + eprintln!("Offscreen adapter: {adapter:?}"); + + let save = |harness: &mut Harness<'_, TextureCraftApp>, name: &str| { + harness.run_steps(8); + let image = harness.render().unwrap(); + if let Some(directory) = std::env::var_os("TC_UI_SNAPSHOTS") { + let path = std::path::Path::new(&directory).join(format!("{name}.png")); + image.save(&path).unwrap(); + eprintln!("wrote {}", path.display()); + } + image + }; + + save(&mut harness, "color-selection-editor"); + harness.get_by_label(&pick_color_label()).click(); + let center = harness.state().viewport_rect.center(); + harness.hover_at(center + egui::vec2(80.0, 0.0)); + let expected = save(&mut harness, "color-selection-picking"); + execute(&mut harness.state_mut().session, "viewport.quickMask.edit", &json!({"editing": true})).unwrap(); + let with_quick_mask = save(&mut harness, "color-selection-picking-quick-mask"); + assert_eq!( + with_quick_mask.get_pixel(center.x as u32, center.y as u32), + expected.get_pixel(center.x as u32, center.y as u32), + "picking must display the ID map while quick-mask editing is enabled" + ); + + click_at(&mut harness, center); + assert!(harness.state().session.quick_mask.editing, "picking preserves quick-mask editing"); + save(&mut harness, "color-selection-quick-mask-restored"); + execute(&mut harness.state_mut().session, "viewport.quickMask.edit", &json!({"editing": false})).unwrap(); + harness.state_mut().ui.layout = texturecraft_ui_egui::state::ViewLayout::Only2D; + harness.get_by_label(&pick_color_label()).click(); + save(&mut harness, "color-selection-picking-2d"); + click_at(&mut harness, center); + assert!(harness.state().picking_id_color.is_none()); + execute(&mut harness.state_mut().session, "textureSet.meshMap.clear", &json!({"map": "id"})).unwrap(); + save(&mut harness, "color-selection-no-id-map"); +} diff --git a/crates/ui-egui/tests/curvature_generator.rs b/crates/ui-egui/tests/it/curvature_generator.rs similarity index 100% rename from crates/ui-egui/tests/curvature_generator.rs rename to crates/ui-egui/tests/it/curvature_generator.rs diff --git a/crates/ui-egui/tests/effect_rows.rs b/crates/ui-egui/tests/it/effect_rows.rs similarity index 100% rename from crates/ui-egui/tests/effect_rows.rs rename to crates/ui-egui/tests/it/effect_rows.rs diff --git a/crates/ui-egui/tests/effect_sliders.rs b/crates/ui-egui/tests/it/effect_sliders.rs similarity index 100% rename from crates/ui-egui/tests/effect_sliders.rs rename to crates/ui-egui/tests/it/effect_sliders.rs diff --git a/crates/ui-egui/tests/it/file_dialogs.rs b/crates/ui-egui/tests/it/file_dialogs.rs new file mode 100644 index 00000000..5c13c6d8 --- /dev/null +++ b/crates/ui-egui/tests/it/file_dialogs.rs @@ -0,0 +1,265 @@ +//! Native file dialogs answer on a later frame; the tests answer them without a window. + +use std::path::{Path, PathBuf}; + +use egui::{ViewportCommand, ViewportEvent, ViewportId}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::Session; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::file_dialogs::{Answer, Request}; +use texturecraft_ui_egui::state::Unsaved; + +fn harness(modified: bool) -> Harness<'static, TextureCraftApp> { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + session.modified = modified; + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.run_steps(4); + h +} + +fn answer(h: &mut Harness<'_, TextureCraftApp>, answer_with: impl FnMut(&Request) -> Answer + 'static) { + h.state_mut().file_dialogs.set_override(Some(Box::new(answer_with))); +} + +fn invoke(h: &mut Harness<'_, TextureCraftApp>, id: &str) { + let ctx = h.ctx.clone(); + texturecraft_ui_egui::menus::invoke(h.state_mut(), &ctx, id); +} + +/// A path in a new temporary folder. +fn temp_file(test: &str, name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("texturecraft-file-dialogs-{test}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + dir.join(name) +} + +fn project_named(name: &str, file: &PathBuf) { + let session = Session::new_project(name, texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); + std::fs::write(file, session.to_project_bytes().unwrap()).unwrap(); +} + +#[test] +fn open_returns_at_once_and_the_answer_opens_the_project_later() { + let file = temp_file("open", "picked.tcraft"); + project_named("Picked", &file); + let mut h = harness(false); + let path = file.clone(); + answer(&mut h, move |_| Answer::Paths(vec![path.clone()])); + invoke(&mut h, "file.open"); + assert_ne!(h.state().session.doc.project.name, "Picked", "the menu click does not wait for the dialog"); + h.run_steps(3); + assert_eq!(h.state().session.doc.project.name, "Picked"); + assert_eq!(h.state().ui.recent.first().map(String::as_str), Some(file.display().to_string().as_str())); +} + +#[test] +fn a_canceled_dialog_changes_nothing() { + let mut h = harness(false); + let name = h.state().session.doc.project.name.clone(); + answer(&mut h, |_| Answer::Cancelled); + invoke(&mut h, "file.open"); + h.run_steps(3); + assert_eq!(h.state().session.doc.project.name, name); + assert!(h.state().toasts.is_empty()); + assert_eq!(h.state().file_dialogs.pending(), 0); +} + +#[test] +fn a_dialog_that_cannot_show_is_reported() { + let mut h = harness(false); + answer(&mut h, |_| Answer::Unavailable("no portal".into())); + invoke(&mut h, "file.open"); + h.run_steps(3); + assert!(h.state().toasts.iter().any(|t| t.error && t.text.contains("no portal"))); +} + +#[test] +fn choosing_the_same_menu_item_twice_asks_once() { + let mut h = harness(false); + let asked = std::rc::Rc::new(std::cell::Cell::new(0)); + let count = asked.clone(); + answer(&mut h, move |_| { + count.set(count.get() + 1); + Answer::Cancelled + }); + invoke(&mut h, "file.open"); + invoke(&mut h, "file.open"); + assert_eq!(h.state().file_dialogs.pending(), 1); + h.run_steps(3); + assert_eq!(asked.get(), 1); +} + +#[test] +fn save_as_and_save_a_copy_are_separate_requests() { + let mut h = harness(false); + answer(&mut h, |_| Answer::Cancelled); + invoke(&mut h, "file.saveAs"); + invoke(&mut h, "file.saveCopy"); + assert_eq!(h.state().file_dialogs.pending(), 2, "the second one does not take the first one's place"); +} + +#[test] +fn save_as_offers_the_project_format_and_a_name() { + let mut h = harness(false); + let seen = std::rc::Rc::new(std::cell::RefCell::new(None)); + let store = seen.clone(); + answer(&mut h, move |request| { + *store.borrow_mut() = Some(request.clone()); + Answer::Cancelled + }); + invoke(&mut h, "file.saveAs"); + h.run_steps(3); + let Some(Request::File(dialog)) = seen.borrow().clone() else { panic!("no file dialog was asked for") }; + assert_eq!(dialog.filters.first().map(|f| f.extensions.clone()), Some(vec![texturecraft_engine::core::PROJECT_EXT.to_string()])); + assert!(dialog.file_name.is_some_and(|name| name.ends_with(texturecraft_engine::core::PROJECT_EXT))); +} + +#[test] +fn a_save_answer_for_a_replaced_project_saves_nothing() { + let file = temp_file("replaced", "kept.tcraft"); + let mut h = harness(true); + let path = file.clone(); + answer(&mut h, move |_| Answer::Paths(vec![path.clone()])); + invoke(&mut h, "file.saveAs"); + h.state_mut().session.project_id += 1; + h.run_steps(3); + assert!(!file.exists(), "the answer belonged to the project that was open when it was asked"); + assert!(h.state().toasts.iter().any(|t| t.error)); + assert!(h.state().session.modified); +} + +const PROJECT_CHANGED: &str = "The project changed while the dialog was open"; + +/// A project-bound dialog asked by `ask`, answered after another project was opened. +fn answered_after_the_project_changed(ask: impl FnOnce(&mut Harness<'_, TextureCraftApp>), file: &Path) -> Harness<'static, TextureCraftApp> { + let mut h = harness(false); + h.state_mut().session.doc.project.mesh_path.clear(); + let path = file.to_path_buf(); + answer(&mut h, move |_| Answer::Paths(vec![path.clone()])); + ask(&mut h); + h.state_mut().session.project_id += 1; + h.run_steps(3); + h +} + +#[test] +fn every_project_dialog_does_nothing_for_a_replaced_project() { + let file = temp_file("replaced-actions", "chosen.obj"); + for id in ["material.load", "resource.import", "file.importMaterialX", "file.exportMesh", "file.reimportMesh"] { + let h = answered_after_the_project_changed(|h| invoke(h, id), &file); + assert!(h.state().toasts.iter().any(|t| t.error && t.text.starts_with(PROJECT_CHANGED)), "{id}"); + assert!(!file.exists(), "{id} wrote nothing"); + } + let bake = answered_after_the_project_changed( + |h| { + let ctx = h.ctx.clone(); + texturecraft_ui_egui::web_files::import_bake_mesh(h.state_mut(), &ctx, false); + }, + &file, + ); + assert!(bake.state().toasts.iter().any(|t| t.error && t.text.starts_with(PROJECT_CHANGED)), "bake meshes"); + let hdr = answered_after_the_project_changed( + |h| { + let ctx = h.ctx.clone(); + texturecraft_ui_egui::web_files::import_environment(h.state_mut(), &ctx); + }, + &file, + ); + assert!(hdr.state().toasts.iter().any(|t| t.error && t.text.starts_with(PROJECT_CHANGED)), "Import HDR"); +} + +#[test] +fn reimport_reads_the_remembered_file_without_asking() { + let file = temp_file("reimport", "mesh.obj"); + std::fs::write(&file, "").unwrap(); + let mut h = harness(false); + h.state_mut().session.doc.project.mesh_path = file.display().to_string(); + answer(&mut h, |_| Answer::Cancelled); + invoke(&mut h, "file.reimportMesh"); + assert_eq!(h.state().file_dialogs.pending(), 0, "the file is still there, so no dialog was asked for"); +} + +#[test] +fn a_mesh_change_keeps_the_answer_for_the_same_project() { + let file = temp_file("mesh-change", "kept.tcraft"); + let mut h = harness(true); + let path = file.clone(); + answer(&mut h, move |_| Answer::Paths(vec![path.clone()])); + invoke(&mut h, "file.saveAs"); + h.state_mut().session.mesh_id += 1; + h.run_steps(3); + assert!(file.exists(), "a reimport or a UV layout change is still the same project"); +} + +fn request_close(h: &mut Harness<'_, TextureCraftApp>) { + h.input_mut().viewports.entry(ViewportId::ROOT).or_default().events.push(ViewportEvent::Close); + h.step(); + h.input_mut().viewports.entry(ViewportId::ROOT).or_default().events.clear(); + h.run_steps(2); +} + +/// A root viewport command sent during `frames` steps. +fn sends(h: &mut Harness<'_, TextureCraftApp>, frames: usize, cmd: &ViewportCommand) -> bool { + (0..frames).any(|_| { + h.step(); + h.output().viewport_output.get(&ViewportId::ROOT).is_some_and(|v| v.commands.contains(cmd)) + }) +} + +fn untitled_with_prompt(h: &mut Harness<'_, TextureCraftApp>) { + h.state_mut().session.path = None; + request_close(h); + assert_eq!(h.state().ui.windows.unsaved, Some(Unsaved::Quit), "the dialog is open"); +} + +#[test] +fn closing_during_a_stroke_finishes_it_and_asks() { + let mut h = harness(false); + h.state_mut().session.begin_stroke_uv(texturecraft_engine::geom::glam::Vec2::splat(0.5), 1.0).unwrap(); + assert!(!h.state().session.modified, "the stroke is not finished yet"); + request_close(&mut h); + assert!(!h.state().session.stroke_active()); + assert!(h.state().session.modified); + assert_eq!(h.state().ui.windows.unsaved, Some(Unsaved::Quit)); +} + +#[test] +fn save_in_the_prompt_goes_on_once_the_dialog_has_saved() { + let file = temp_file("prompt-save", "saved.tcraft"); + let mut h = harness(true); + untitled_with_prompt(&mut h); + let path = file.clone(); + answer(&mut h, move |_| Answer::Paths(vec![path.clone()])); + h.get_by_label("Save").click(); + assert!(sends(&mut h, 5, &ViewportCommand::Close), "the close goes on after the save"); + assert!(file.exists()); + assert!(!h.state().session.modified); + assert!(h.state().ui.windows.unsaved.is_none()); +} + +#[test] +fn canceling_the_save_dialog_keeps_the_prompt_and_its_buttons() { + let mut h = harness(true); + untitled_with_prompt(&mut h); + answer(&mut h, |_| Answer::Cancelled); + h.get_by_label("Save").click(); + assert!(!sends(&mut h, 5, &ViewportCommand::Close)); + assert_eq!(h.state().ui.windows.unsaved, Some(Unsaved::Quit), "the question is still open"); + assert!(h.state().session.modified); + h.get_by_label("Cancel").click(); + h.run_steps(2); + assert!(h.state().ui.windows.unsaved.is_none(), "Cancel answers again after the Save dialog closed"); +} + +#[test] +fn a_save_elsewhere_does_not_answer_the_prompt() { + let file = temp_file("prompt-other", "other.tcraft"); + let mut h = harness(true); + untitled_with_prompt(&mut h); + let path = file.display().to_string(); + h.state_mut().run("file.saveAs", serde_json::json!({ "path": path })); + assert!(!h.state().session.modified); + assert!(!sends(&mut h, 3, &ViewportCommand::Close), "only the prompt's own Save goes on"); + assert_eq!(h.state().ui.windows.unsaved, Some(Unsaved::Quit)); +} diff --git a/crates/ui-egui/tests/fill_channel_image.rs b/crates/ui-egui/tests/it/fill_channel_image.rs similarity index 100% rename from crates/ui-egui/tests/fill_channel_image.rs rename to crates/ui-egui/tests/it/fill_channel_image.rs diff --git a/crates/ui-egui/tests/fill_projection_section.rs b/crates/ui-egui/tests/it/fill_projection_section.rs similarity index 100% rename from crates/ui-egui/tests/fill_projection_section.rs rename to crates/ui-egui/tests/it/fill_projection_section.rs diff --git a/crates/ui-egui/tests/filter_picker.rs b/crates/ui-egui/tests/it/filter_picker.rs similarity index 100% rename from crates/ui-egui/tests/filter_picker.rs rename to crates/ui-egui/tests/it/filter_picker.rs diff --git a/crates/ui-egui/tests/history_panel.rs b/crates/ui-egui/tests/it/history_panel.rs similarity index 100% rename from crates/ui-egui/tests/history_panel.rs rename to crates/ui-egui/tests/it/history_panel.rs diff --git a/crates/ui-egui/tests/layer_clipboard.rs b/crates/ui-egui/tests/it/layer_clipboard.rs similarity index 72% rename from crates/ui-egui/tests/layer_clipboard.rs rename to crates/ui-egui/tests/it/layer_clipboard.rs index 36c20ff9..efcf40c0 100644 --- a/crates/ui-egui/tests/layer_clipboard.rs +++ b/crates/ui-egui/tests/it/layer_clipboard.rs @@ -31,6 +31,34 @@ fn ctrl_x_cuts_the_clicked_layer() { assert!(h.state().session.clipboard.is_some(), "and keeps it on the layer clipboard"); } +/// Windows reports Shift+Delete and Shift+Insert as Cut and Paste with Shift held. +#[test] +fn shift_delete_cuts_and_shift_insert_pastes() { + let (mut h, layer) = harness(); + let before = count(&h); + h.event_modifiers(egui::Event::Cut, egui::Modifiers::SHIFT); + h.run_steps(3); + assert!(!h.state().session.doc.project.layers.contains_key(&layer), "Shift+Delete cuts the layer"); + h.event_modifiers(egui::Event::Paste("Layer".into()), egui::Modifiers::SHIFT); + h.run_steps(3); + assert_eq!(count(&h), before, "Shift+Insert pastes it back"); +} + +#[test] +fn a_binding_on_shift_insert_runs_instead_of_the_paste() { + let (mut h, _) = harness(); + let before = count(&h); + h.event(egui::Event::Copy); + h.run_steps(3); + assert!(h.state().session.clipboard.is_some(), "there is something to paste"); + h.state_mut().ui.keymap.insert("ui.layout.3d".into(), "Shift+Insert".into()); + h.run_steps(2); + h.event_modifiers(egui::Event::Paste("Layer".into()), egui::Modifiers::SHIFT); + h.run_steps(3); + assert_eq!(h.state().ui.layout, texturecraft_ui_egui::state::ViewLayout::Only3D, "the shortcut ran"); + assert_eq!(count(&h), before, "and nothing was pasted"); +} + #[test] fn ctrl_c_then_ctrl_v_pastes_a_copy() { let (mut h, _) = harness(); diff --git a/crates/ui-egui/tests/layer_rename.rs b/crates/ui-egui/tests/it/layer_rename.rs similarity index 100% rename from crates/ui-egui/tests/layer_rename.rs rename to crates/ui-egui/tests/it/layer_rename.rs diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs new file mode 100644 index 00000000..26b1ef10 --- /dev/null +++ b/crates/ui-egui/tests/it/main.rs @@ -0,0 +1,31 @@ +//! One integration-test executable avoids linking the same dependencies for every feature. +//! Keep feature tests in their own modules; the standalone ui_snapshots.rs target remains available. + +mod bake_mode; +mod brush_drag; +mod close_unsaved; +mod color_picker; +mod color_selection_editor; +mod curvature_generator; +mod effect_rows; +mod effect_sliders; +mod file_dialogs; +mod fill_channel_image; +mod fill_projection_section; +mod filter_picker; +mod history_panel; +mod layer_clipboard; +mod layer_rename; +mod new_project_baked_maps; +mod path_list; +mod pen_pressure; +mod polygon_fill; +mod properties_popup; +mod shelf_drop; +mod shelf_hover_preview; +mod shift_lines_2d; +mod shortcut_keys; +mod skew_paint; +mod split_divider; +mod start_window; +mod toolbar; diff --git a/crates/ui-egui/tests/it/new_project_baked_maps.rs b/crates/ui-egui/tests/it/new_project_baked_maps.rs new file mode 100644 index 00000000..39a7c813 --- /dev/null +++ b/crates/ui-egui/tests/it/new_project_baked_maps.rs @@ -0,0 +1,153 @@ +//! New project ▸ Import baked maps: added files are listed, Clear empties the list, Create imports them + +use std::path::PathBuf; + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::core::{BakedMap, NormalFormat}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::new_project_advanced::add_baked_map_files; + +fn harness() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.windows.new_project = true; + h.state_mut().ui.new_project.resolution = 256; + h.run_steps(3); + h.get_by_label("Advanced settings").click(); + h.run_steps(3); + h.get_by_label("Import baked maps").click(); + h.run_steps(3); + h +} + +/// 4×4 PNGs named `files` in a fresh folder, as their full paths; green 0.2 shows which way a normal map was read +fn bake_files(test: &str, files: &[&str]) -> Vec { + let dir = std::env::temp_dir().join(format!("texturecraft-np-baked-maps-{test}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + files + .iter() + .map(|file| { + let path: PathBuf = dir.join(file); + image::RgbaImage::from_pixel(4, 4, image::Rgba([128, 51, 255, 255])).save(&path).unwrap(); + path.display().to_string() + }) + .collect() +} + +#[test] +fn added_files_are_listed_once_and_clear_empties_the_list() { + let mut h = harness(); + let paths = bake_files("list", &["Ball_normal.png", "Base_ao.png", "Ball_notes.png"]); + + add_baked_map_files(&mut h.state_mut().ui.new_project, paths.clone()); + add_baked_map_files(&mut h.state_mut().ui.new_project, paths); + h.run_steps(3); + + assert_eq!(h.state().ui.new_project.baked_maps.len(), 3, "each file once"); + for file in ["Ball_normal.png", "Base_ao.png", "Ball_notes.png"] { + h.get_by_label(file); + } + + h.get_by_label("Clear").click(); + h.run_steps(3); + assert!(h.state().ui.new_project.baked_maps.is_empty()); + assert!(h.query_by_label("Ball_normal.png").is_none()); +} + +#[test] +fn create_imports_the_listed_maps_in_the_chosen_normal_format() { + let mut h = harness(); + let paths = bake_files("create", &["Ball_normal.png", "Base_ao.png", "Ball_notes.png"]); + add_baked_map_files(&mut h.state_mut().ui.new_project, paths); + h.state_mut().ui.new_project.normal_format = Some(NormalFormat::DirectX); + h.run_steps(3); + + h.get_by_label("Create").click(); + h.run_steps(3); + + let state = h.state(); + assert!(!state.ui.windows.new_project, "the dialog closes"); + let project = &state.session.doc.project; + assert_eq!(project.normal_format, NormalFormat::DirectX); + let baked = |ts: usize, map: BakedMap| state.session.doc.baked.get(&ts).is_some_and(|baked| baked.maps.contains_key(&map)); + assert!(baked(0, BakedMap::Normal) && baked(1, BakedMap::AmbientOcclusion)); + let normal_green = state.session.doc.baked[&0].maps[&BakedMap::Normal][1]; + assert!(normal_green > 0.75, "the normal map is read as DirectX (green flipped): {normal_green}"); + assert_eq!(state.session.doc.resources.len(), 2, "the file naming no map is not imported"); + let toast = &state.toasts.last().unwrap().text; + assert!(toast.contains("Baked maps imported: 2") && toast.contains("Ball_notes.png"), "{toast}"); + assert!(state.ui.new_project.baked_maps.is_empty(), "the next new project starts with no files"); + assert_eq!(state.session.undo_label(), Some("Import baked maps")); +} + +#[test] +fn a_failed_import_keeps_the_file_list_and_created_project() { + let mut h = harness(); + let paths = bake_files("failure", &["Ball_normal.png", "Base_ao.png"]); + std::fs::write(&paths[1], b"not an image").unwrap(); + add_baked_map_files(&mut h.state_mut().ui.new_project, paths.clone()); + h.state_mut().ui.new_project.name = "Import failure".to_string(); + h.run_steps(3); + + h.get_by_label("Create").click(); + h.run_steps(3); + + let app = h.state(); + assert!(!app.ui.windows.new_project); + assert_eq!(app.session.doc.project.name, "Import failure"); + assert_eq!(app.ui.new_project.baked_maps, paths); + assert!(app.session.doc.resources.is_empty() && app.session.images.is_empty()); + assert!(app.session.doc.baked.values().all(|baked| baked.maps.is_empty())); + let toast = app.toasts.last().unwrap(); + assert!(toast.error && toast.text.contains("Base_ao.png"), "{}", toast.text); +} + +#[test] +#[ignore = "offscreen GPU snapshots; set TC_UI_SNAPSHOTS to an output directory"] +fn new_project_baked_maps_snapshots() { + let output_dir = PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); + std::fs::create_dir_all(&output_dir).unwrap(); + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|cc| { + let adapter = cc.wgpu_render_state.as_ref().unwrap().adapter.get_info(); + eprintln!("snapshot adapter: {adapter:?}"); + TextureCraftApp::new(cc, session) + }); + h.state_mut().ui.windows.new_project = true; + h.state_mut().ui.new_project.resolution = 256; + h.run_steps(6); + h.get_by_label("Advanced settings").click(); + h.run_steps(6); + h.get_by_label("Import baked maps").click(); + h.run_steps(6); + let paths = bake_files("snapshots", &["Ball_normal.png", "Base_ao.png", "Ball_notes.png"]); + add_baked_map_files(&mut h.state_mut().ui.new_project, paths); + h.state_mut().ui.new_project.normal_format = Some(NormalFormat::DirectX); + h.run_steps(6); + h.render().unwrap().save(output_dir.join("new-project-baked-maps.png")).unwrap(); + h.set_size(egui::vec2(1024.0, 768.0)); + h.run_steps(6); + h.render().unwrap().save(output_dir.join("new-project-baked-maps-small.png")).unwrap(); + h.set_size(egui::vec2(1600.0, 960.0)); + h.run_steps(6); + h.get_by_label("Create").click(); + h.run_steps(3); + assert!(h.state().session.doc.baked[&0].maps.contains_key(&BakedMap::Normal)); + h.render().unwrap().save(output_dir.join("new-project-imported.png")).unwrap(); +} + +#[test] +fn normal_format_preview_uses_the_same_template_lookup_as_creation() { + let mut h = harness(); + h.state_mut().session.templates.dir = None; + h.state_mut().run("textureSet.settings", serde_json::json!({"normalFormat": "directX"})).unwrap(); + h.state_mut().run("project.template.save", serde_json::json!({"name": "Custom DirectX"})).unwrap(); + h.state_mut().ui.new_project.template = "custom directx".to_string(); + h.run_steps(3); + + h.get_by_value("DirectX"); + h.get_by_label("Create").click(); + h.run_steps(3); + assert_eq!(h.state().session.doc.project.normal_format, NormalFormat::DirectX); +} diff --git a/crates/ui-egui/tests/path_list.rs b/crates/ui-egui/tests/it/path_list.rs similarity index 100% rename from crates/ui-egui/tests/path_list.rs rename to crates/ui-egui/tests/it/path_list.rs diff --git a/crates/ui-egui/tests/pen_pressure.rs b/crates/ui-egui/tests/it/pen_pressure.rs similarity index 100% rename from crates/ui-egui/tests/pen_pressure.rs rename to crates/ui-egui/tests/it/pen_pressure.rs diff --git a/crates/ui-egui/tests/polygon_fill.rs b/crates/ui-egui/tests/it/polygon_fill.rs similarity index 100% rename from crates/ui-egui/tests/polygon_fill.rs rename to crates/ui-egui/tests/it/polygon_fill.rs diff --git a/crates/ui-egui/tests/properties_popup.rs b/crates/ui-egui/tests/it/properties_popup.rs similarity index 100% rename from crates/ui-egui/tests/properties_popup.rs rename to crates/ui-egui/tests/it/properties_popup.rs diff --git a/crates/ui-egui/tests/shelf_drop.rs b/crates/ui-egui/tests/it/shelf_drop.rs similarity index 100% rename from crates/ui-egui/tests/shelf_drop.rs rename to crates/ui-egui/tests/it/shelf_drop.rs diff --git a/crates/ui-egui/tests/shelf_hover_preview.rs b/crates/ui-egui/tests/it/shelf_hover_preview.rs similarity index 100% rename from crates/ui-egui/tests/shelf_hover_preview.rs rename to crates/ui-egui/tests/it/shelf_hover_preview.rs diff --git a/crates/ui-egui/tests/it/shift_lines_2d.rs b/crates/ui-egui/tests/it/shift_lines_2d.rs new file mode 100644 index 00000000..a6e6175d --- /dev/null +++ b/crates/ui-egui/tests/it/shift_lines_2d.rs @@ -0,0 +1,247 @@ +//! Shift+click in the 2D view paints a straight line from where the last stroke ended, as in the 3D view + +use egui::{Event, Modifiers, PointerButton, Pos2, pos2}; +use egui_kittest::Harness; +use serde_json::json; +use texturecraft_engine::core::Channel; +use texturecraft_engine::geom::glam::Vec2; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::state::ViewLayout; + +/// The first click, on the sample's texture in the 2D view +const FIRST_CLICK: Pos2 = pos2(700.0, 420.0); + +/// The Shift+click, on the texture of both of the sample's texture sets +const SECOND_CLICK: Pos2 = pos2(900.0, 520.0); + +/// Start of a drag cancelled with Escape, well away from the line between the two clicks +const CANCELLED_DRAG_FROM: Pos2 = pos2(760.0, 700.0); + +/// End of the cancelled drag +const CANCELLED_DRAG_TO: Pos2 = pos2(820.0, 700.0); + +/// Alpha a texel needs to count as painted +const PAINTED_ALPHA: f32 = 0.05; + +/// How far beside the line the unpainted check looks, in brush radii +const BESIDE_LINE_IN_RADII: f32 = 3.0; + +/// The sample project with only the 2D view, at 1600 x 960 +fn uv_view_app() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.layout = ViewLayout::Only2D; + harness.run_steps(4); + harness +} + +/// A primary click at `pos`, with Shift held when `shift` is set +fn click(harness: &mut Harness<'_, TextureCraftApp>, pos: Pos2, shift: bool) { + let modifiers = if shift { Modifiers::SHIFT } else { Modifiers::NONE }; + harness.event(Event::ModifiersChanged(modifiers)); + harness.hover_at(pos); + harness.run_steps(1); + harness.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed: true, modifiers }); + harness.run_steps(1); + harness.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed: false, modifiers }); + harness.run_steps(2); + harness.event(Event::ModifiersChanged(Modifiers::NONE)); + harness.run_steps(1); +} + +/// Press at `from`, drag to `to`, press Escape and release: the stroke is cancelled +fn cancelled_drag(harness: &mut Harness<'_, TextureCraftApp>, from: Pos2, to: Pos2) { + harness.hover_at(from); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(1); + harness.hover_at(to); + harness.run_steps(2); + harness.key_press(egui::Key::Escape); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); + assert!(!harness.state().session.stroke_active(), "Escape cancelled the stroke"); +} + +/// The selected layer's base color alpha, row by row, with the texture width +fn alpha(harness: &Harness<'_, TextureCraftApp>) -> (Vec, u32) { + let session = &harness.state().session; + let (width, height) = session.doc.project.texture_sets[session.ts()].size(); + let layer = session.selected_layer().expect("a selected layer"); + let Some(image) = session.doc.pixels.layer(layer, Channel::BaseColor) else { return (vec![0.0; (width * height) as usize], width) }; + let texels = (0..height).flat_map(|y| (0..width).map(move |x| (x, y))); + (texels.map(|(x, y)| image.get(x, y)[3] as f32 / 65535.0).collect(), width) +} + +/// Alpha added between two snapshots +fn added(before: &[f32], after: &[f32]) -> Vec { + after.iter().zip(before).map(|(after, before)| (after - before).max(0.0)).collect() +} + +/// The alpha-weighted centre of `paint`, in texels +fn centre(paint: &[f32], width: u32) -> Vec2 { + let (sum, total) = paint.iter().enumerate().fold((Vec2::ZERO, 0.0), |(sum, total), (index, value)| { + let texel = Vec2::new((index as u32 % width) as f32, (index as u32 / width) as f32); + (sum + texel * *value, total + value) + }); + assert!(total > 0.0, "something was painted"); + sum / total +} + +/// Whether `paint` holds visible alpha at `texel` +fn painted_at(paint: &[f32], width: u32, texel: Vec2) -> bool { + let index = texel.y.round() as usize * width as usize + texel.x.round() as usize; + paint[index] > PAINTED_ALPHA +} + +/// The brush radius in texels: a 2D view stamp's radius is twice the brush size in UV units +fn brush_radius_in_texels(harness: &Harness<'_, TextureCraftApp>, width: u32) -> f32 { + harness.state().session.tool.brush.size * 2.0 * width as f32 +} + +/// Click, run `between` (zoom or pan), Shift+click; assert one straight stroke joins both dabs +fn assert_shift_click_draws_a_line(between: impl FnOnce(&mut Harness<'_, TextureCraftApp>)) { + let mut harness = uv_view_app(); + let (blank, width) = alpha(&harness); + click(&mut harness, FIRST_CLICK, false); + let (first_dab, _) = alpha(&harness); + let start = centre(&added(&blank, &first_dab), width); + + between(&mut harness); + harness.run_steps(2); + let steps_before = harness.state().session.history_labels().len(); + click(&mut harness, SECOND_CLICK, true); + assert_eq!(harness.state().session.history_labels().len(), steps_before + 1, "the line is one undo step"); + let (with_line, _) = alpha(&harness); + let line = added(&first_dab, &with_line); + + // A plain click at the same point finds where the line should end + harness.state_mut().session.undo().unwrap(); + click(&mut harness, SECOND_CLICK, false); + let (with_dab, _) = alpha(&harness); + let end = centre(&added(&first_dab, &with_dab), width); + + let middle = (start + end) * 0.5; + let across = (end - start).perp().normalize() * brush_radius_in_texels(&harness, width) * BESIDE_LINE_IN_RADII; + assert!(painted_at(&line, width, middle), "the line passes halfway between {start} and {end}"); + assert!(!painted_at(&line, width, middle + across), "nothing is painted beside the line"); +} + +#[test] +fn shift_click_paints_a_straight_line_from_the_last_stroke() { + assert_shift_click_draws_a_line(|_| {}); +} + +#[test] +fn the_line_joins_the_same_texture_points_after_zoom_and_pan() { + assert_shift_click_draws_a_line(|harness| { + let ui_state = &mut harness.state_mut().ui; + ui_state.uv_zoom *= 1.5; + ui_state.uv_pan = [0.2, -0.1]; + }); +} + +/// Shift+click at the second point; assert it painted the same dot a plain click there paints +fn assert_shift_click_paints_only_a_dot(harness: &mut Harness<'_, TextureCraftApp>) { + let (before, _) = alpha(harness); + click(harness, SECOND_CLICK, true); + let (after_shift_click, _) = alpha(harness); + let shift_click_alpha: f32 = added(&before, &after_shift_click).iter().sum(); + + harness.state_mut().session.undo().unwrap(); + click(harness, SECOND_CLICK, false); + let (after_click, _) = alpha(harness); + let click_alpha: f32 = added(&before, &after_click).iter().sum(); + + assert!(click_alpha > 1.0, "the plain click painted: {click_alpha}"); + assert!((shift_click_alpha - click_alpha).abs() < click_alpha * 0.01, "Shift+click paints only a dot: {shift_click_alpha} vs {click_alpha}"); +} + +#[test] +fn shift_click_without_a_previous_stroke_paints_a_dot() { + assert_shift_click_paints_only_a_dot(&mut uv_view_app()); +} + +#[test] +fn a_line_does_not_start_from_a_point_on_another_texture_set() { + let mut harness = uv_view_app(); + click(&mut harness, FIRST_CLICK, false); + + harness.state_mut().run("textureSet.select", json!({"ts": 1})); + harness.run_steps(2); + + assert_shift_click_paints_only_a_dot(&mut harness); +} + +#[test] +fn a_stroke_cancelled_with_escape_leaves_the_line_start_where_it_was() { + assert_shift_click_draws_a_line(|harness| cancelled_drag(harness, CANCELLED_DRAG_FROM, CANCELLED_DRAG_TO)); +} + +#[test] +fn a_new_project_does_not_reuse_the_previous_projects_line_start() { + let mut harness = uv_view_app(); + click(&mut harness, FIRST_CLICK, false); + harness.state_mut().run("project.new", json!({"mesh": "sphere", "resolution": 256})).unwrap(); + harness.run_steps(2); + + assert_shift_click_paints_only_a_dot(&mut harness); +} + +#[test] +fn a_project_opened_through_control_does_not_reuse_the_line_start() { + let mut harness = uv_view_app(); + click(&mut harness, FIRST_CLICK, false); + let context = harness.ctx.clone(); + let result = texturecraft_ui_egui::control::handle( + harness.state_mut(), + &context, + "command.run", + &json!({"id": "project.new", "params": {"mesh": "sphere", "resolution": 256}}), + ); + assert_eq!(result["ok"], true); + harness.run_steps(2); + + assert_shift_click_paints_only_a_dot(&mut harness); +} + +#[test] +#[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"] +fn shift_line_snapshots() { + let output_dir = std::path::PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS to the output directory")); + std::fs::create_dir_all(&output_dir).unwrap(); + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|context| { + let adapter = &context.wgpu_render_state.as_ref().expect("wgpu render state").adapter; + eprintln!("Shift-line snapshot adapter: {:?}", adapter.get_info()); + TextureCraftApp::new(context, session) + }); + harness.state_mut().ui.layout = ViewLayout::Only2D; + harness.run_steps(4); + click(&mut harness, FIRST_CLICK, false); + + let save = |harness: &mut Harness<'_, TextureCraftApp>, name: &str| { + harness.run_steps(4); + let path = output_dir.join(format!("{name}.png")); + harness.render().unwrap().save(&path).unwrap(); + eprintln!("wrote {}", path.display()); + }; + + harness.event(Event::ModifiersChanged(Modifiers::SHIFT)); + harness.hover_at(SECOND_CLICK); + save(&mut harness, "shift-line-preview"); + click(&mut harness, SECOND_CLICK, true); + save(&mut harness, "shift-line-painted"); + + harness.state_mut().ui.uv_zoom = 1.5; + harness.state_mut().ui.uv_pan = [0.2, -0.1]; + harness.event(Event::ModifiersChanged(Modifiers::SHIFT)); + harness.hover_at(FIRST_CLICK); + save(&mut harness, "shift-line-zoom-pan-preview"); + + harness.state_mut().run("project.new", json!({"mesh": "sphere", "resolution": 256})).unwrap(); + save(&mut harness, "shift-line-new-project"); + harness.event(Event::ModifiersChanged(Modifiers::NONE)); + assert_shift_click_paints_only_a_dot(&mut harness); +} diff --git a/crates/ui-egui/tests/it/shortcut_keys.rs b/crates/ui-egui/tests/it/shortcut_keys.rs new file mode 100644 index 00000000..bffac25b --- /dev/null +++ b/crates/ui-egui/tests/it/shortcut_keys.rs @@ -0,0 +1,106 @@ +//! Key presses run the commands bound to exactly that chord. + +use egui::{Event, Key, Modifiers, OutputCommand, PointerButton}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable as _; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::Panel; +use texturecraft_ui_egui::state::ViewLayout; + +fn harness() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.run_steps(4); + h +} + +fn press(key: Key, modifiers: Modifiers, repeat: bool) -> Event { + Event::Key { key, physical_key: None, pressed: true, repeat, modifiers } +} + +fn hidden(h: &Harness<'_, TextureCraftApp>) -> bool { + h.state().ui.hide_ui +} + +#[test] +fn a_bound_key_runs_its_command() { + let mut h = harness(); + h.event(press(Key::Tab, Modifiers::NONE, false)); + h.run_steps(2); + assert!(hidden(&h), "Tab hides the UI"); +} + +#[test] +fn extra_shift_or_alt_does_not_run_a_plain_key_shortcut() { + let mut h = harness(); + h.event(press(Key::Tab, Modifiers::SHIFT, false)); + h.event(press(Key::Tab, Modifiers::ALT, false)); + h.run_steps(2); + assert!(!hidden(&h)); +} + +#[test] +fn a_held_key_runs_its_command_again() { + let mut h = harness(); + // Tab also moves egui's keyboard focus, and a focused text field stops the second press. + h.state_mut().ui.keymap.insert("ui.hideUi".into(), "F7".into()); + h.run_steps(2); + h.event(press(Key::F7, Modifiers::NONE, false)); + h.run_steps(2); + assert!(hidden(&h)); + h.event(press(Key::F7, Modifiers::NONE, true)); + h.run_steps(2); + assert!(!hidden(&h), "the repeat toggled it back"); +} + +#[test] +fn a_shortcut_stored_in_the_settings_replaces_the_default() { + let mut h = harness(); + assert_ne!(h.state().ui.layout, ViewLayout::Only3D); + h.state_mut().ui.keymap.insert("ui.layout.3d".into(), "Ctrl+Shift+H".into()); + h.run_steps(2); + h.event(press(Key::F2, Modifiers::NONE, false)); + h.run_steps(2); + assert_ne!(h.state().ui.layout, ViewLayout::Only3D, "the default no longer runs it"); + h.event(press(Key::H, Modifiers::COMMAND | Modifiers::SHIFT, false)); + h.run_steps(2); + assert_eq!(h.state().ui.layout, ViewLayout::Only3D); +} + +#[test] +fn copy_with_label_text_selected_puts_that_text_on_the_clipboard() { + let mut h = harness(); + h.state_mut().session.log.push("a line to copy".into()); + h.state_mut().ui.dock.focus(Panel::Log); + h.run_steps(4); + let line = h.get_all_by_label("a line to copy").next().unwrap().rect(); + let (from, to) = (line.left_center() + egui::vec2(1.0, 0.0), line.right_center()); + h.hover_at(from); + h.step(); + h.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.step(); + h.hover_at(to); + h.step(); + h.event(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(2); + h.event(Event::Copy); + h.step(); + let last_copied = h.output().platform_output.commands.iter().rev().find_map(|c| match c { + OutputCommand::CopyText(text) => Some(text.clone()), + _ => None, + }); + assert_eq!(last_copied.as_deref(), Some("a line to copy"), "the selected text is the last text copied"); +} + +#[test] +fn a_pasted_image_counts_as_the_paste_shortcut() { + let mut h = harness(); + let before = h.state().session.doc.project.layers.len(); + h.event(Event::Copy); + h.run_steps(3); + assert!(h.state().session.clipboard.is_some()); + let image = std::sync::Arc::new(egui::ColorImage::filled([1, 1], egui::Color32::WHITE)); + h.event(Event::PasteImage(image)); + h.run_steps(3); + assert!(h.state().session.doc.project.layers.len() > before, "the paste ran layer.paste"); +} diff --git a/crates/ui-egui/tests/skew_paint.rs b/crates/ui-egui/tests/it/skew_paint.rs similarity index 100% rename from crates/ui-egui/tests/skew_paint.rs rename to crates/ui-egui/tests/it/skew_paint.rs diff --git a/crates/ui-egui/tests/split_divider.rs b/crates/ui-egui/tests/it/split_divider.rs similarity index 94% rename from crates/ui-egui/tests/split_divider.rs rename to crates/ui-egui/tests/it/split_divider.rs index d5af8c8f..e0a487fc 100644 --- a/crates/ui-egui/tests/split_divider.rs +++ b/crates/ui-egui/tests/it/split_divider.rs @@ -5,6 +5,7 @@ use egui_kittest::Harness; use texturecraft_engine::core::Channel; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::state::UiState; +use texturecraft_ui_egui::ui_state_store::UiStateStore; /// Narrowest a split view may get, as in `viewport.rs` const MIN_VIEW_WIDTH: f32 = 16.0; @@ -144,16 +145,15 @@ fn the_divider_position_survives_a_restart_and_old_saved_states_load_centred() { let mut storage = MemoryStorage::default(); let mut ui_state = UiState::default(); ui_state.split_ratio = 0.3; - eframe::set_value(&mut storage, "ui", &ui_state); - let restored = eframe::get_value::(&storage, "ui").expect("saved state loads"); + UiStateStore::default().save(&ui_state, &mut storage); + let restored = UiStateStore::default().load(Some(&storage)).expect("saved state loads"); assert_eq!(restored.split_ratio, 0.3); // A state saved before the divider existed has no ratio - let saved = storage.0.get("ui").cloned().unwrap(); - let without_ratio = saved.replace("split_ratio:0.3,", ""); - assert_ne!(without_ratio, saved, "the saved state names the ratio: {saved}"); - storage.0.insert("ui".to_owned(), without_ratio); - let restored = eframe::get_value::(&storage, "ui").expect("an older saved state loads"); + let mut saved: serde_json::Value = serde_json::from_str(&storage.0["ui.json"]).unwrap(); + assert!(saved.as_object_mut().unwrap().remove("split_ratio").is_some(), "the saved state names the ratio: {saved}"); + storage.0.insert("ui.json".to_owned(), saved.to_string()); + let restored = UiStateStore::default().load(Some(&storage)).expect("an older saved state loads"); assert_eq!(restored.split_ratio, 0.5); } diff --git a/crates/ui-egui/tests/start_window.rs b/crates/ui-egui/tests/it/start_window.rs similarity index 100% rename from crates/ui-egui/tests/start_window.rs rename to crates/ui-egui/tests/it/start_window.rs diff --git a/crates/ui-egui/tests/toolbar.rs b/crates/ui-egui/tests/it/toolbar.rs similarity index 100% rename from crates/ui-egui/tests/toolbar.rs rename to crates/ui-egui/tests/it/toolbar.rs diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index ccaa2e84..fe90dda3 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -77,7 +77,7 @@ fn window_snapshots() { save(&mut harness, &output_dir, "bake-settings"); harness.state_mut().session.add_high_poly_bytes("High Poly.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); save(&mut harness, &output_dir, "bake-settings-high-poly"); - harness.get_by_label("Cage").scroll_to_me(); + harness.get_by_role_and_label(egui::Role::ComboBox, "Cage Type").scroll_to_me(); save(&mut harness, &output_dir, "bake-settings-cage-skew"); harness.get_by_label("Edge Contrast").scroll_to_me(); save(&mut harness, &output_dir, "bake-settings-skew"); diff --git a/crates/ui-egui/tests/ui_state_persistence.rs b/crates/ui-egui/tests/ui_state_persistence.rs new file mode 100644 index 00000000..a2008864 --- /dev/null +++ b/crates/ui-egui/tests/ui_state_persistence.rs @@ -0,0 +1,106 @@ +//! App save/restart coverage, including offscreen rendering when explicitly requested + +use eframe::App as _; +use egui_kittest::Harness; +use texturecraft_ui_egui::{TextureCraftApp, docking::Panel, state::Mode}; + +#[path = "../src/ui_state_store/memory_storage.rs"] +mod memory_storage; +use memory_storage::MemoryStorage; + +fn app(storage: &MemoryStorage, render: bool) -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + // Existing viewport controls lack accessible names; these tests check persistence and rendering + let builder = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_accessibility_check(false); + let builder = if render { builder.wgpu() } else { builder }; + builder.build_eframe(|context| { + let mut creation = eframe::CreationContext::_new_kittest(context.egui_ctx.clone()); + creation.storage = Some(storage); + creation.wgpu_render_state = context.wgpu_render_state.clone(); + TextureCraftApp::new(&creation, session) + }) +} + +fn customize(harness: &mut Harness<'_, TextureCraftApp>) { + harness.state_mut().ui.dock.close(Panel::Assets); + harness.state_mut().ui.split_ratio = 0.35; + harness.state_mut().ui.mode = Mode::Baking; + harness.run_steps(3); + harness.state_mut().ui.dock.close(Panel::MeshMapBakers); + harness.state_mut().ui.mode = Mode::Painting; + harness.run_steps(3); +} + +#[test] +fn app_save_restores_both_customized_modes() { + let mut storage = MemoryStorage::default(); + let mut original = app(&storage, false); + customize(&mut original); + original.state_mut().save(&mut storage); + let mut restarted = app(&storage, false); + restarted.run_steps(3); + assert_eq!(restarted.state().ui.dock, original.state().ui.dock); + assert_eq!(restarted.state().ui.split_ratio, 0.35); + + for harness in [&mut original, &mut restarted] { + harness.state_mut().ui.mode = Mode::Baking; + harness.run_steps(3); + } + assert_eq!(restarted.state().ui.dock, original.state().ui.dock); + assert!(!restarted.state().ui.dock.is_open(Panel::MeshMapBakers)); +} + +#[test] +fn failed_backups_show_one_persistent_warning_and_keep_the_original() { + let mut storage = MemoryStorage::default(); + storage.values.insert("ui.json".into(), "not json".into()); + for index in 1..=10 { + let key = if index == 1 { "ui.unreadable.json".into() } else { format!("ui.unreadable-{index}.json") }; + storage.values.insert(key, "previous backup".into()); + } + let mut harness = app(&storage, false); + harness.state_mut().save(&mut storage); + harness.state_mut().save(&mut storage); + assert_eq!(storage.values["ui.json"], "not json"); + let warnings = &harness.state().toasts; + assert_eq!(warnings.len(), 1); + assert!(warnings[0].error && warnings[0].until.is_infinite()); + assert!(warnings[0].text.contains("Saving is disabled")); + assert!(harness.state().session.log.iter().any(|line| line == &warnings[0].text)); +} + +#[test] +#[ignore = "requires an offscreen GPU and TC_UI_SNAPSHOTS"] +fn customized_layout_restart_snapshots() { + let output = std::path::PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); + std::fs::create_dir_all(&output).unwrap(); + let file = output.join("restart-ui.json"); + let _ = std::fs::remove_file(&file); + texturecraft_ui_egui::ui_state_store::FILE.set(file).unwrap(); + let mut storage = MemoryStorage::default(); + let mut original = app(&storage, true); + eprintln!("Rendering adapter: {}", original.state().gpu.as_ref().unwrap().adapter); + customize(&mut original); + original.state_mut().save(&mut storage); + let mut restarted = app(&storage, true); + eprintln!("Restart rendering adapter: {}", restarted.state().gpu.as_ref().unwrap().adapter); + + for (mode, name) in [(Mode::Painting, "painting"), (Mode::Baking, "baking")] { + for (harness, suffix) in [(&mut original, "before"), (&mut restarted, "after")] { + harness.state_mut().ui.mode = mode; + harness.run_steps(8); + harness.render().unwrap().save(output.join(format!("restart-{name}-{suffix}.png"))).unwrap(); + } + assert_eq!(restarted.state().ui.dock, original.state().ui.dock); + assert_eq!(restarted.state().ui.split_ratio, original.state().ui.split_ratio); + } + + let file = texturecraft_ui_egui::ui_state_store::FILE.get().unwrap(); + std::fs::remove_file(file).unwrap(); + std::fs::create_dir(file).unwrap(); + let mut unreadable = app(&storage, true); + assert!(unreadable.state().toasts.iter().any(|toast| toast.text.contains("Saving is disabled"))); + unreadable.run_steps(8); + unreadable.render().unwrap().save(output.join("settings-read-warning.png")).unwrap(); + std::fs::remove_dir(file).unwrap(); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index b071e91d..0c2c9a1b 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -162,8 +162,8 @@ print(call("command.run", {"id": "layer.add.fill", "params": {"color": [0.8, 0.1 File › Save. Through `command_run`, every `file.*` command but `file.close` and `file.removeUnused` (and -`file.reimportMesh` without a `path`) is refused, and so is any command given a `path` or `dir` (`resource.import`, -`material.save`, `material.load`, …), in both modes: use the workspace tools below. `resource.text` +`file.reimportMesh` without a `path`) is refused, and so is any command given a `path` or `dir`, at the top level or in +a `files` entry (`resource.import`, `material.save`, `material.load`, `textureSet.meshMap.import`, …), in both modes: use the workspace tools below. `resource.text` takes a font family, not a path: it reads only the system's font folders. | Tool | Params | Notes | @@ -179,7 +179,7 @@ takes a font family, not a path: it reads only the system's font folders. | `mesh_reimport` | `{path?, preserveStrokes?}` | Reimport the mesh from a file, or (no path) from the project's own copy; bridge mode supports only the latter | | `mesh_export` | `{path, format?}` | The mesh as obj, glb, usda, usdc or usdz below the write root (obj: its .mtl and textures, usda / usdc: textures next to it) → `{path, textures?}` | | `bake_mesh_add` | `{path, cage?}` | Add a high-definition mesh for baking, or set the cage → `{name, meshes}` | -| `resource_import` | `{path}` | Image resource (png, jpg, tga, tif, bmp, webp, exr, hdr) → its name, for `layer.add.image` / `tool.stencil`, or as a mesh map instead of baking it: `textureSet.meshMap.set {ts?, map, image}` (`textureSet.meshMap.clear {ts?, map}` empties the slot) | +| `resource_import` | `{path}` | Image resource (png, jpg, tga, tif, bmp, webp, exr, hdr) → its name, for `layer.add.image` / `tool.stencil`, or as a mesh map instead of baking it: `textureSet.meshMap.set {ts?, map, image}` (`textureSet.meshMap.clear {ts?, map}` empties the slot); call it once per baked map file (the desktop app's `textureSet.meshMap.import`, which takes host paths, is refused through `command_run`) | | `material_save` | `{path, layer?, name?}` | A layer or folder as a `.tcmat` smart material below the write root | | `material_load` | `{path}` | Add a `.tcmat` smart material, a MaterialCraft `.mcmat` material or a `.mcraft` package above the selection | | `textures_export` | `{dir, preset?, ts?, format?, padding?, size?}` | Writes files below the write root | diff --git a/docs/parity.md b/docs/parity.md index 652b84a9..75f6fd30 100644 --- a/docs/parity.md +++ b/docs/parity.md @@ -2,7 +2,7 @@ Generated by `TC_UPDATE_PARITY=1 cargo test -p texturecraft-ui-egui parity`. Each row is a menu item of the target menu layout with TextureCraft's command id; **live** means the id is implemented. Feature parity beyond menus is tracked in [`ROADMAP.md`](../ROADMAP.md). -**58 of 58 menu items live (100%).** +**59 of 59 menu items live (100%).** ## File @@ -90,5 +90,6 @@ Generated by `TC_UPDATE_PARITY=1 cargo test -p texturecraft-ui-egui parity`. Eac | ArtCraft website... | `ui.help.website` | | live | | Report a bug... | `ui.help.bug` | | live | | Show log... | `ui.view.log` | | live | +| Check for Updates... | `ui.help.checkForUpdates` | | live | | About TextureCraft... | `ui.about` | | live | diff --git a/docs/testing-ci.md b/docs/testing-ci.md new file mode 100644 index 00000000..7db9ae07 --- /dev/null +++ b/docs/testing-ci.md @@ -0,0 +1,24 @@ +# Integration tests and CI + +The engine and UI integration tests share one `it` executable per crate. This +avoids compiling and linking the same crate dependencies into a separate +executable for every feature. Feature modules keep their own helpers and tests. +When adding a file under `tests/it/`, register it with `mod name;` in that +folder's `main.rs` so Cargo runs it. + +Run a feature module with a test-name filter, for example: + +```sh +cargo test -p texturecraft-engine --test it bake:: +``` + +The standalone engine `session` target and UI `ui_snapshots` target remain +available for the commands in `AGENTS.md`. Existing ignore attributes are +unchanged. Tests in the shared executable can run concurrently across modules; +keep temporary paths unique and avoid changing process-wide state. + +CI continues to use the shared gate workflow and `cargo xtask ci` on Ubuntu and +Windows: formatting, Clippy, workspace tests (including doctests), layering and +isolated per-package WebAssembly checks. The caller disables the shared +workflow's optional tool installation because this gate uses `cargo test` and +does not use nextest.