Merge upstream/main into fix/217-generator-offset

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vangel76andClaude Opus 5.5 committed 2026-11-09 23:26:53 +01:00
commit 254ee16b04
155 files changed
+8607 -782

No files matched your search

+2
View File
@@ -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
Generated
+547 -15
View File
@@ -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"
+12 -2
View File
@@ -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]
+1
View File
@@ -32,6 +32,7 @@
<img alt="MCP server for agents" src="https://img.shields.io/badge/agents-MCP%20server-555555?style=flat-square">
<img alt="License: MIT OR Apache-2.0" src="https://img.shields.io/badge/license-MIT%20OR%20Apache--2.0-555555?style=flat-square">
<br>
<a href="https://sonarcloud.io/project/overview?id=storytold_texturecraft"><img alt="Scanned by SonarCloud" src="https://img.shields.io/badge/Scanned_by-SonarCloud-4b9fd5?style=flat-square&logo=sonarqubecloud&logoColor=white"></a>
<a href="https://coderabbit.ai"><img alt="Reviewed by CodeRabbit" src="https://img.shields.io/coderabbit/prs/github/storytold/texturecraft?style=flat-square&label=Reviewed%20by%20CodeRabbit&logo=coderabbit"></a>
</p>
+6
View File
@@ -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"
+66 -23
View File
@@ -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::<std::collections::HashMap<String, String>>(&s).ok());
kv.and_then(|kv| ron::from_str::<UiState>(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::<std::collections::HashMap<String, String>>(&text).ok());
entries.and_then(|entries| ron::from_str::<UiState>(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<u16>) -> 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::<Vec<_>>()) {
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)));
}
}
+26 -9
View File
@@ -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]
+15
View File
@@ -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;
+65
View File
@@ -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<Vec3>,
pub starts: Vec<RayStart>,
/// 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<CageShell, BakeError> {
let ray_frame = RayFrame::new(request, MeshExtent::of(request.mesh)?)?;
let (frame, mesh) = (&ray_frame, request.mesh);
let triangles: Vec<usize> = mesh.triangles_of(request.material).collect();
let (positions, starts): (Vec<Vec3>, Vec<RayStart>) = 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<Vec3> {
let frontal = max_frontal * self.cage_units;
self.positions.par_iter().zip(&self.starts).map(|(position, start)| start.origin(*position, frontal)).collect()
}
}
+103
View File
@@ -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<Option<VertexReach>>,
/// 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<HighPolyReach, BakeError> {
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<bool> {
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<u32> {
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<Vec3> {
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
}
+63
View File
@@ -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<Vec3>,
cage: Option<&'a Mesh>,
skew: Option<PreparedSkew<'a>>,
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<RayFrame<'a>, 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)) }
}
}
+20
View File
@@ -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,
}
}
}
+28
View File
@@ -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)
}
}
+4
View File
@@ -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;
+3
View File
@@ -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;
+21 -65
View File
@@ -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<Source<'a>>,
cage: Option<&'a Mesh>,
skew: Option<PreparedSkew<'a>>,
cage_paint: Option<&'a crate::BakePaintMap>,
ray_normals: Vec<Vec3>,
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<BakeContext<'a>, 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,
+28 -19
View File
@@ -3,34 +3,43 @@ use std::ops::{Add, Mul};
use texturecraft_geom::glam::Vec3;
use texturecraft_geom::{Mesh, Surface};
pub(super) fn interpolate<T: Copy + Mul<f32, Output = T> + Add<Output = T>>(mesh: &Mesh, v: &[T], tri: u32, [b1, b2]: [f32; 2]) -> Option<T> {
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<T: Copy + Mul<f32, Output = T> + Add<Output = T>>(mesh: &Mesh, values: &[T], triangle: u32, barycentric: [f32; 2]) -> Option<T> {
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<u32>, Vec<Vec3>, Vec<Vec3>) {
let q = diag * 1e-5;
let mut ids: HashMap<[i64; 3], u32> = HashMap::new();
let (mut pos, mut nrm) = (Vec::new(), Vec::<Vec3>::new());
let weld: Vec<u32> = 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<u32>, Vec<Vec3>, Vec<Vec3>) {
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::<Vec3>::new());
let welded_indices: Vec<u32> = 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 {
+13
View File
@@ -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<Source<'a>>) {
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,
+8
View File
@@ -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<u32>, Vec<u32>) {
let (low, high) = Source::of_request(request);
(low.key, high.map(|high| high.key).unwrap_or_default())
}
+35
View File
@@ -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<MeshExtent, BakeError> {
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
}
}
+103
View File
@@ -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<usize> = 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));
}
+222
View File
@@ -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<bool>) {
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::<f32>() / 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);
}
+51
View File
@@ -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}"
);
}
}
}
+9
View File
@@ -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(
{
+6
View File
@@ -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<TextureSet>,
pub layers: BTreeMap<LayerId, Layer>,
@@ -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(),
@@ -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<Mesh>,
pub(super) bvh: Arc<Bvh>,
pub(super) material: usize,
pub(super) settings: BakeSettings,
pub(super) high: MergedHigh,
pub(super) cage: Option<Arc<Mesh>>,
pub(super) skew: Option<Arc<BakePaintMap>>,
pub(super) cage_paint: Option<Arc<BakePaintMap>>,
}
impl BakeCageInputs {
/// The cage the 3D view draws: the bake's ray origins at each triangle corner
pub fn cage_shell(&self) -> Result<CageShell, BakeError> {
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, BakeError> {
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),
}
}
}
+5
View File
@@ -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());
@@ -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<HighPolyReach>], distances: &[(f32, f32)], only_set: Option<usize>, vertex_count: usize) -> Vec<f32> {
// 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()
}
+69 -21
View File
@@ -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<u8>) -> Result<BakeMesh> {
}
impl Session {
pub fn bake_task(&self, ts: usize) -> Result<BakeTask> {
let set = self.doc.project.texture_set(ts)?;
pub fn bake_task(&self, texture_set: usize) -> Result<BakeTask> {
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<Option<BakeCageInputs>> {
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<Option<MergedHigh>> {
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<Option<Arc<Mesh>>> {
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<Option<Arc<BakePaintMap>>> {
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<Arc<Mesh>> {
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();
+4
View File
@@ -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;
+160
View File
@@ -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<CommandSpec> {
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<Vec<[f32; 3]>> {
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<Value> {
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<Vec2> {
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<const N: usize>(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)
}
+2
View File
@@ -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());
+70 -3
View File
@@ -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<texturecraft_formats::MeshFile> {
@@ -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<Value> {
let path = native::path_param(p, "mesh", "file.new")?;
@@ -377,6 +385,7 @@ fn new_from_mesh(s: &mut Session, p: &Value) -> Result<Value> {
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<Value> {
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<Value> {
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<Value> {
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]
+4
View File
@@ -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::<Vec<_>>()
+4
View File
@@ -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;
+3 -2
View File
@@ -94,7 +94,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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<Value> {
*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);
}
+76 -40
View File
@@ -38,55 +38,91 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
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<BTreeMap<u32, Arc<ImageRes>>> {
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<u32, Arc<ImageRes>>) -> Result<u32> {
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<BTreeMap<u32, Arc<ImageRes>>> {
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<u32> {
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<usize> {
let b = name.as_bytes();
+159
View File
@@ -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<BakedMap> {
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::<u32>().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<usize> {
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);
}
}
+162
View File
@@ -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<CommandSpec> {
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<Value> {
import_with_budget(s, p, MAX_TOTAL_BYTES)
}
fn import_with_budget(s: &mut Session, p: &Value, max_bytes: u64) -> Result<Value> {
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<u32, &str>> = 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::<f32>() 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<BakedMap>) -> 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, &params, 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, &params, required_bytes).unwrap();
assert_eq!(result["assigned"].as_array().unwrap().len(), 2);
std::fs::remove_dir_all(dir).unwrap();
}
}
+53 -34
View File
@@ -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<EyeDepth> {
@@ -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<texturecraft_paint::UvStamp> = 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();
}
+65 -12
View File
@@ -36,12 +36,18 @@ pub(crate) fn decoded(d: texturecraft_formats::DecodedImage) -> Arc<ImageRes> {
}
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<u8>) -> Result<String> {
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<u8>, max_texels: u64) -> Result<String> {
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<Value> {
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<Vec<u8>> {
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<Vec<u8>> {
Err(bad(cmd, "file paths are not available in the browser"))
}
#[cfg(target_arch = "wasm32")]
fn import(_: &mut Session, _: &Value) -> Result<Value> {
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<Value> {
})?;
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"));
}
}
+6 -2
View File
@@ -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<Arc<EyeDepth>>,
/// 2D view strokes: last UV point and the distance carried to the next stamp.
pub uv: Option<(Option<Vec2>, f32)>,
/// 2D view strokes: where the stroke is between samples.
pub uv: Option<crate::uv_stroke_state::UvStrokeState>,
pub camera: OrbitCamera,
pub viewport: Vec2,
pub values: BTreeMap<Channel, [f32; 3]>,
@@ -318,6 +318,9 @@ pub struct Session {
pub mesh: Arc<Mesh>,
/// 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<Mesh>,
pub bvh: Arc<Bvh>,
@@ -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),
+14
View File
@@ -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<Vec2>,
/// 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,
}
File renamed without changes.
File renamed without changes.
File renamed without changes.
+309
View File
@@ -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<u8> {
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", &params).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", &params).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", &params).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()
);
}
}
}
File renamed without changes.
File renamed without changes.
@@ -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<VertexReach> {
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<VertexReach>>) -> Option<HighPolyReach> {
Some(HighPolyReach { vertices, cage_units: 1.0, ignore_backface: false })
}
fn sets() -> Vec<Option<HighPolyReach>> {
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]);
}
File renamed without changes.
+27
View File
@@ -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;
File renamed without changes.
+298
View File
@@ -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<Value> = 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<String> {
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::<String>::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", &params);
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", &params).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();
}
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
+105
View File
@@ -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");
}
+18
View File
@@ -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();
}
+31 -11
View File
@@ -21,20 +21,27 @@ pub fn decode_image(bytes: &[u8]) -> Result<DecodedImage> {
/// [`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<DecodedImage> {
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 = {
+93
View File
@@ -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<Vec<(u32, u32)>> {
// 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<EdgePositions, Vec<(u32, u32, usize)>> = 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<usize> {
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();
+12
View File
@@ -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<usize>,
}
+9
View File
@@ -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,
}
+11
View File
@@ -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,
}
+5
View File
@@ -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;
+348 -91
View File
@@ -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<BakeVisualization>,
}
/// 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<MeshGpu>,
bake_high: Option<HighPolyGpu>,
/// Each texture set's cage, by set index
cages: Vec<Option<CageGpu>>,
uv_seams: Option<UvSeamGpu>,
sets: Vec<SetGpu>,
/// 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::Color> = 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::<Vertex>() 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::<f32>() 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::<Vertex>()),
(mesh.indices.len(), std::mem::size_of::<u32>()),
(mesh.positions.len(), std::mem::size_of::<f32>()),
];
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<u32> = 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).
+88
View File
@@ -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<f32>,
@location(0) world_position: vec3<f32>,
@location(1) normal: vec3<f32>,
// 1 where the bake's rays miss the high poly, 0 where they reach it
@location(2) missed: f32,
};
const HIGH_POLY_COLOR: vec3<f32> = vec3<f32>(0.10, 0.36, 0.56);
const MISSED_COLOR: vec3<f32> = vec3<f32>(0.80, 0.01, 0.01);
const CAGE_COLOR: vec3<f32> = vec3<f32>(0.55, 0.42, 0.26);
const CAGE_OPACITY: f32 = 0.16;
const CAGE_WIRE_COLOR: vec4<f32> = vec4<f32>(0.75, 0.62, 0.42, 0.7);
const UV_SEAM_COLOR: vec4<f32> = vec4<f32>(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<f32>, normal: vec3<f32>, world_position: vec3<f32>) -> vec3<f32> {
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<f32>, fraction: f32) -> vec4<f32> {
return g.view_proj * vec4<f32>(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<f32>, @location(1) normal: vec3<f32>, @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<f32> {
let color = mix(HIGH_POLY_COLOR, MISSED_COLOR, surface.missed);
return vec4<f32>(headlight(color, normalize(surface.normal), surface.world_position), 1.0);
}
@vertex
fn vs_bake_cage(@location(0) position: vec3<f32>) -> BakeViewOut {
var out: BakeViewOut;
out.clip = g.view_proj * vec4<f32>(position, 1.0);
out.world_position = position;
out.normal = vec3<f32>(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<f32> {
let face_normal = normalize(cross(dpdx(surface.world_position), dpdy(surface.world_position)));
return vec4<f32>(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<f32>) -> BakeViewOut {
var out: BakeViewOut;
out.clip = pulled_toward_eye(position, CAGE_WIRE_PULL_TOWARD_EYE);
out.world_position = position;
out.normal = vec3<f32>(0.0, 1.0, 0.0);
out.missed = 0.0;
return out;
}
@fragment
fn fs_wire_bake_cage(surface: BakeViewOut) -> @location(0) vec4<f32> {
return CAGE_WIRE_COLOR;
}
@fragment
fn fs_wire_uv_seam(surface: VOut) -> @location(0) vec4<f32> {
return UV_SEAM_COLOR;
}
+8
View File
@@ -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)>,
}
+123 -2
View File
@@ -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<Vec3> = 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<Vec3> = 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::<f32>()) + 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 };
+7 -1
View File
@@ -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"
@@ -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<bool>) -> 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
}
@@ -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<BakeVisualization> {
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),
})
}
}
+4
View File
@@ -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;
+11
View File
@@ -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;
@@ -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<Mesh>,
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<Option<CageLink>>,
/// How many texture sets' cages the GPU was last told to keep
sent_cage_count: Option<usize>,
/// The low-poly mesh whose seams are uploaded
seams_mesh_id: Option<u64>,
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<BakeVisualization>, 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::<f32>() / 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");
}
}
@@ -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<Arc<CageShell>>,
/// 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,
}
@@ -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<Mesh>,
cage_file: SharedHandle<Mesh>,
material: usize,
uv_tiles: Vec<u32>,
tile_resolutions: BTreeMap<u32, u32>,
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<BakePaintMap>; 2],
}
impl CageShellKey {
pub(super) fn of(session: &Session, texture_set: usize) -> Option<CageShellKey> {
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)],
})
}
}
@@ -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<Vec3>,
pub shell: Arc<CageShell>,
}
+140
View File
@@ -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<usize>);
/// 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<Option<(CageShellKey, HighPolySettings)>>,
high_id: u64,
job: Option<Receiver<Vec<Option<HighPolyReach>>>>,
reach: Vec<Option<HighPolyReach>>,
/// Each set's (max frontal, max rear) and the selected-set filter the GPU's colors are for
shown: Option<ShownDistances>,
}
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<usize>, 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<Option<(CageShellKey, HighPolySettings)>> = 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");
}
}
@@ -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<T>(Option<Weak<T>>);
impl<T> SharedHandle<T> {
pub(super) fn of(value: Option<&Arc<T>>) -> SharedHandle<T> {
SharedHandle(value.map(Arc::downgrade))
}
}
impl<T> Clone for SharedHandle<T> {
fn clone(&self) -> Self {
SharedHandle(self.0.clone())
}
}
impl<T> Default for SharedHandle<T> {
fn default() -> Self {
SharedHandle(None)
}
}
impl<T> PartialEq for SharedHandle<T> {
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(),
}
}
}
@@ -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<usize>, 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);
}
+1
View File
@@ -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));
}
+12 -1
View File
@@ -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);
}
+39 -19
View File
@@ -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<Option<String>, 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<Option<String>, 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.
+111
View File
@@ -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<dyn FnOnce(&mut TextureCraftApp, Vec<PathBuf>)>;
/// 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<u64>,
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>,
asked: Vec<AskKey>,
}
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<Override>) {
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<PathBuf>) + '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 });
}
}
}
+140 -72
View File
@@ -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<Vec<(u32, u32)>>;
/// 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<Arc<ImageRes>>)>,
pub tiles: Vec<(usize, DisplayKind, u32, u32, Vec<u8>)>,
pub aux: Vec<(usize, u32, Vec<u8>)>,
/// Bake mode's high poly (`None` removes it) and the id it is sent under
pub bake_high: Option<(Option<Arc<Mesh>>, 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<f32>)>,
/// Changed cages: texture set, the cage or `None` to remove it, its topology
pub bake_cages: Vec<(usize, Option<CageUpload>, u64)>,
/// Texture sets left after some were removed: their cages go too
pub bake_cage_count: Option<usize>,
/// 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<f32> {
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<AuxView>, 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<AuxView>, bake: Option<BakeVisualization>, 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<SetLayout> = s.doc.project.texture_sets.iter().map(|t| (t.size(), t.material)).collect();
let sets: Vec<SetLayout> = 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()
}
+5 -3
View File
@@ -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<String> {
+17
View File
@@ -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", "تغيّر المشروع أثناء فتح النافذة، لذا لم يُنفَّذ أي إجراء"),
];
+20
View File
@@ -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",
),
];
+20
View File
@@ -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",
),
];
Loaded 100 of 155 files, more files were not shown because too many files have changed in this diff. Show more