diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a9e5501a..cb4ec50b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -22,7 +22,7 @@ jobs: uses: storytold/craft-common-actions/.github/workflows/gate.yml@main with: # Same craft-fonts commit as release.yml. - craft-fonts-ref: 3d9ab3a132ed0eff457e424226a435a901da30d3 + craft-fonts-ref: aced4137c022f1f587624d48e81ec77e1914a9cc os: '["ubuntu-24.04","windows-latest"]' toolchain: "1.96.0" packages: >- diff --git a/.github/workflows/freebsd.yml b/.github/workflows/freebsd.yml index ae8422b6..9f64bbdd 100644 --- a/.github/workflows/freebsd.yml +++ b/.github/workflows/freebsd.yml @@ -32,5 +32,5 @@ jobs: # Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos. uses: storytold/craft-common-actions/.github/workflows/freebsd.yml@main with: - craft-fonts-ref: 3d9ab3a132ed0eff457e424226a435a901da30d3 + craft-fonts-ref: aced4137c022f1f587624d48e81ec77e1914a9cc run-package-check: true diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index c7dcab7a..3ed14bca 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -25,7 +25,7 @@ jobs: with: app-name: texturecraft app-title: "TextureCraft" - craft-fonts-ref: 3d9ab3a132ed0eff457e424226a435a901da30d3 + craft-fonts-ref: aced4137c022f1f587624d48e81ec77e1914a9cc web-craft-fonts: true version: ${{ inputs.version }} secrets: diff --git a/AGENTS.md b/AGENTS.md index 8f0bfb97..ad435dac 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -130,7 +130,10 @@ panic. The shared standard is `../craftrules/standards/never-crash.md`. `docs/control-protocol.md`, and never depend on MaterialCraft's crates; talk to it through `materialcraft-cli`. 9. **Verify UI changes visually.** Launch with `--control ` and call `ui.screenshot` (whole - window) or `viewport.screenshot`; look at the PNG. + window) or `viewport.screenshot`; look at the PNG. Without a visible screen (a locked machine, + CI), render the whole window offscreen: + `TC_UI_SNAPSHOTS= cargo test -p texturecraft-ui-egui --release --test ui_snapshots -- --ignored` + (add `CRAFT_FONTS_DIR=` to see the release fonts). ## 4. Picking work diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 20d91dd6..5d607a5c 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -16,13 +16,13 @@ licensed and keep their license file next to them. | `assets/app-icon/hicolor/{16x16,24x24,32x32,48x48,64x64,128x128,256x256,512x512}/apps/ai.storyteller.texturecraft.png` | App icon (engraved zebra), hicolor theme PNGs | Project owner (ArtCraft team) | Original artwork drawn in ArtCraft for TextureCraft, rendered by `packaging/icons.sh` | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | | `assets/app-icon/hicolor/scalable/apps/ai.storyteller.texturecraft.svg` | App icon (engraved zebra), hicolor scalable (copy of `texturecraft-small.svg`) | Project owner (ArtCraft team) | Original artwork drawn in ArtCraft for TextureCraft, vectorised with craftrules `vectorize_tile.py` | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | | `assets/app-icon/LICENSE.txt`, `assets/app-icon/README.md` | App icon licence and notes | TextureCraft contributors | original | MIT OR Apache-2.0 | -| `docs/images/texturecraft-workspace.png` | README screenshot: the TextureCraft workspace (material ball in chipped paint, grime and a gold stripe) | TextureCraft contributors | original screenshot of TextureCraft | MIT OR Apache-2.0 | +| `docs/images/texturecraft-workspace.png` | README screenshot: the TextureCraft workspace (a 1970s portable TV in aged cream plastic with a crayon doodle) | TextureCraft contributors | original screenshot of TextureCraft | MIT OR Apache-2.0 | | `docs/images/texturecraft-bake.png` | README screenshot: bake mode | TextureCraft contributors | original screenshot of TextureCraft | MIT OR Apache-2.0 | | `docs/images/texturecraft-export.png` | README screenshot: the Export textures dialog | TextureCraft contributors | original screenshot of TextureCraft | MIT OR Apache-2.0 | | `docs/images/texturecraft-rendering.png` | README screenshot: Rendering mode, path traced on the GPU | TextureCraft contributors | original screenshot of TextureCraft | MIT OR Apache-2.0 | | `docs/images/texturecraft-light.png` | README screenshot: the light brightness level with the blue accent | TextureCraft contributors | original screenshot of TextureCraft | MIT OR Apache-2.0 | -| `docs/images/texturecraft-materials.png` | README render: car paint, velvet and brushed steel on the material ball (`texturecraft-cli render --samples 256`, three renders side by side) | TextureCraft contributors | original render | MIT OR Apache-2.0 | -| `docs/images/texturecraft-crate.png` | README render: the built-in crate with chipped paint on wood, rusted iron and tarnished brass smart materials (`texturecraft-cli render --samples 512`, cropped) | TextureCraft contributors | original render by TextureCraft | MIT OR Apache-2.0 | +| `docs/images/texturecraft-lantern.png` | README render: a storm lantern (original procedural mesh of lathes and swept wires, eight texture sets) in chipped red enamel, rust, soot, tarnished brass and glass with an emissive flame (`texturecraft-cli render --camera Hero --samples 2048`, 1200×900) | TextureCraft contributors | original model and render by TextureCraft | MIT OR Apache-2.0 | +| `docs/images/texturecraft-camera.png` | README render: a rangefinder camera (original procedural mesh) in black enamel worn to brass, leatherette, chrome and coated glass; the lens distance scale is an original image drawn in code (`texturecraft-cli render --camera Hero --samples 2048`, 1200×900) | TextureCraft contributors | original model and render by TextureCraft | MIT OR Apache-2.0 | | `docs/brand/artcraft-*.svg`, `docs/brand/artcraft-*.png` | ArtCraft logo and mark | ArtCraft Team | storytold/craftrules `assets/brand/` | ArtCraft brand terms, not open source ([`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt)) | ## Third-party assets compiled into the binary @@ -32,10 +32,11 @@ These come from Rust crate dependencies (not files in this repository) and keep | Asset | Used for | Author | Source | License | |---|---|---|---|---| | Phosphor Icons (regular), via the `egui-phosphor` crate (vendored in `vendor/egui-phosphor` for egui 0.37) | Every UI icon (tools, layers, panels) | Phosphor Icons (Helena Zhang, Tobias Fried) | https://phosphoricons.com, https://github.com/amPerl/egui-phosphor | MIT (icons); crate MIT OR Apache-2.0 | -| egui default fonts (Ubuntu-Light, Hack, Noto Emoji, emoji-icon-font), via `epaint_default_fonts` | UI text | Canonical / Source Foundry / Google / Jessie Jung | https://github.com/emilk/egui | Ubuntu Font Licence 1.0, MIT + Bitstream Vera License, OFL 1.1, MIT | -| Only in builds made with `CRAFT_FONTS_DIR`: BIZ UDPGothic Regular (desktop and web) and Noto Sans CJK SC Regular (desktop), from storytold/craft-fonts (`crates/ui-egui/build.rs`) | Japanese and Chinese UI text | The BIZ UDGothic Project Authors (Morisawa Inc.); The Noto Project Authors | https://github.com/storytold/craft-fonts (pinned sources in its `fonts/manifest.txt` and `ATTRIBUTION.md`) | OFL 1.1 | +| egui default fonts (Ubuntu-Light, Hack, Noto Emoji, emoji-icon-font), via `epaint_default_fonts` | UI text; Ubuntu Light and Hack also as the built-in fonts for text alphas and decals | Canonical / Source Foundry / Google / Jessie Jung | https://github.com/emilk/egui | Ubuntu Font Licence 1.0, MIT + Bitstream Vera License, OFL 1.1, MIT | +| Only in builds made with `CRAFT_FONTS_DIR`: Inter Regular and SemiBold (desktop and web), from storytold/craft-fonts' Latin catalog (`crates/ui-egui/build.rs`) | Interface text | The Inter Project Authors | https://github.com/storytold/craft-fonts (pinned sources in its `fonts/latin-manifest.txt` and `ATTRIBUTION.md`) | OFL 1.1 | +| Only in builds made with `CRAFT_FONTS_DIR`: BIZ UDPGothic Regular (desktop and web), Noto Sans CJK SC Regular (desktop) and Noto Sans Arabic Regular (desktop and web), from storytold/craft-fonts (`crates/ui-egui/build.rs`) | Japanese, Chinese and Arabic UI text | The BIZ UDGothic Project Authors (Morisawa Inc.); The Noto Project Authors | https://github.com/storytold/craft-fonts (pinned sources in its `fonts/manifest.txt` and `ATTRIBUTION.md`) | OFL 1.1 | -Without craft-fonts, Chinese, Japanese and Korean UI text uses the operating system's fonts at run +Without craft-fonts, Chinese, Japanese, Korean and Arabic UI text uses the operating system's fonts at run time (nothing is bundled); see [docs/localization-parity.md](docs/localization-parity.md). ## Procedural content (no asset files) diff --git a/Cargo.lock b/Cargo.lock index f1230397..b62ad4e7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -178,15 +178,6 @@ dependencies = [ "libc", ] -[[package]] -name = "arbitrary" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed" -dependencies = [ - "derive_arbitrary", -] - [[package]] name = "arboard" version = "3.6.1" @@ -572,7 +563,7 @@ dependencies = [ "maybe-owned", "rustix 1.1.5", "rustix-linux-procfs", - "windows-sys 0.61.2", + "windows-sys 0.60.2", "winx", ] @@ -773,12 +764,23 @@ dependencies = [ "objc2-app-kit 0.3.2", "objc2-foundation 0.3.2", "serde", - "skrifa", + "skrifa 0.44.0", "wasm-bindgen", "wasm-bindgen-futures", "web-sys", ] +[[package]] +name = "craft-window" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242" +dependencies = [ + "egui", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "wayland-client", +] + [[package]] name = "crc32fast" version = "1.5.2" @@ -859,17 +861,6 @@ dependencies = [ "syn 3.0.9", ] -[[package]] -name = "derive_arbitrary" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b034bd7d5f032402a2479444dcc6f74e36a03f31854d41680fb240ef682a1ac" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.9", -] - [[package]] name = "dispatch" version = "0.2.0" @@ -1065,6 +1056,23 @@ dependencies = [ "winit", ] +[[package]] +name = "egui_kittest" +version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +dependencies = [ + "eframe", + "egui", + "egui-wgpu", + "image", + "kittest", + "log", + "pollster 1.0.1", + "serde", + "toml", + "wgpu", +] + [[package]] name = "either" version = "1.19.0" @@ -1136,7 +1144,7 @@ dependencies = [ "profiling", "self_cell", "serde", - "skrifa", + "skrifa 0.44.0", "smallvec", "unicode-bidi", "unicode-general-category", @@ -1163,7 +1171,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -1292,9 +1300,9 @@ checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" [[package]] name = "font-types" -version = "0.12.6" +version = "0.12.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c92d9081c7ab3bd83ef1eecdfad090f3d966e3ce74106779664114cfe1a6274" +checksum = "835ae9d781464a79026cde387f9cbc650c9a4909d7cf7e658b127e3c35d2f35d" dependencies = [ "bytemuck", "serde", @@ -1510,7 +1518,7 @@ dependencies = [ "hashbrown 0.17.1", "log", "peniko", - "skrifa", + "skrifa 0.44.0", "smallvec", "vello_common", ] @@ -1675,7 +1683,7 @@ checksum = "c03d949a14aa089bbb282f7dd76a498a7f684428e4257202efc119ec010376f9" dependencies = [ "bitflags 2.13.2", "bytemuck", - "read-fonts", + "read-fonts 0.41.0", "smallvec", ] @@ -2112,6 +2120,16 @@ version = "3.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc" +[[package]] +name = "kittest" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bb81a721ba76aa095b7f45deb180504f786904e56ca4b8e141f66eb89a78b75" +dependencies = [ + "accesskit", + "accesskit_consumer", +] + [[package]] name = "kurbo" version = "0.13.1" @@ -2372,6 +2390,18 @@ dependencies = [ "jni-sys 0.3.1", ] +[[package]] +name = "nix" +version = "0.31.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" +dependencies = [ + "bitflags 2.13.2", + "cfg-if", + "cfg_aliases", + "libc", +] + [[package]] name = "nohash-hasher" version = "0.2.0" @@ -2782,7 +2812,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -3191,6 +3221,19 @@ dependencies = [ "once_cell", ] +[[package]] +name = "read-fonts" +version = "0.45.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4edc8db0d972de88e53a085b1f01fb3fbdae7bb0cb7a0ce2b2f8285a412fe3ef" +dependencies = [ + "bytemuck", + "foldhash 0.2.0", + "font-types", + "once_cell", + "yoke", +] + [[package]] name = "reborrow" version = "0.5.5" @@ -3371,7 +3414,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.12.1", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -3573,6 +3616,18 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" +[[package]] +name = "skera" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "531045338e36ad05b9652912a47ba38a935d0eaa0293c3e33d8112cfa414c14b" +dependencies = [ + "hashbrown 0.17.1", + "skrifa 0.48.0", + "thiserror 2.0.21", + "write-fonts", +] + [[package]] name = "skrifa" version = "0.44.0" @@ -3580,7 +3635,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68" dependencies = [ "bytemuck", - "read-fonts", + "read-fonts 0.41.0", +] + +[[package]] +name = "skrifa" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5213b4825bac3587046330052d61bfac7bd3bd0d203c758d7c2ef726fcea034" +dependencies = [ + "bytemuck", + "read-fonts 0.45.1", ] [[package]] @@ -3648,7 +3713,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -3730,10 +3795,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.4.3", + "getrandom 0.3.4", "once_cell", "rustix 1.1.5", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -3747,21 +3812,25 @@ dependencies = [ [[package]] name = "texturecraft" -version = "0.1.0" +version = "0.2.0" dependencies = [ "eframe", "egui", "image", "log", + "ron", "serde_json", + "texturecraft-automation", "texturecraft-engine", "texturecraft-ui-egui", + "winit", "winresource", + "winsafe", ] [[package]] name = "texturecraft-automation" -version = "0.1.0" +version = "0.2.0" dependencies = [ "base64 0.22.1", "cap-std", @@ -3769,6 +3838,7 @@ dependencies = [ "image", "rayon", "rmcp", + "rustix 1.1.5", "schemars", "serde", "serde_json", @@ -3781,7 +3851,7 @@ dependencies = [ [[package]] name = "texturecraft-bake" -version = "0.1.0" +version = "0.2.0" dependencies = [ "rayon", "texturecraft-core", @@ -3792,7 +3862,7 @@ dependencies = [ [[package]] name = "texturecraft-cli" -version = "0.1.0" +version = "0.2.0" dependencies = [ "image", "serde_json", @@ -3804,7 +3874,7 @@ dependencies = [ [[package]] name = "texturecraft-compose" -version = "0.1.0" +version = "0.2.0" dependencies = [ "half", "rayon", @@ -3815,7 +3885,7 @@ dependencies = [ [[package]] name = "texturecraft-core" -version = "0.1.0" +version = "0.2.0" dependencies = [ "serde", "serde_json", @@ -3824,8 +3894,9 @@ dependencies = [ [[package]] name = "texturecraft-engine" -version = "0.1.0" +version = "0.2.0" dependencies = [ + "epaint_default_fonts", "image", "rayon", "serde", @@ -3843,7 +3914,7 @@ dependencies = [ [[package]] name = "texturecraft-formats" -version = "0.1.0" +version = "0.2.0" dependencies = [ "base64 0.22.1", "exr", @@ -3867,7 +3938,7 @@ dependencies = [ [[package]] name = "texturecraft-geom" -version = "0.1.0" +version = "0.2.0" dependencies = [ "glam 0.30.10", "mikktspace", @@ -3878,10 +3949,13 @@ dependencies = [ [[package]] name = "texturecraft-paint" -version = "0.1.0" +version = "0.2.0" dependencies = [ + "epaint_default_fonts", + "harfrust", "rayon", "serde", + "skrifa 0.44.0", "texturecraft-compose", "texturecraft-core", "texturecraft-geom", @@ -3890,11 +3964,12 @@ dependencies = [ [[package]] name = "texturecraft-render" -version = "0.1.0" +version = "0.2.0" dependencies = [ "bytemuck", "half", "image", + "log", "pollster 0.4.0", "rayon", "texturecraft-bake", @@ -3902,22 +3977,25 @@ dependencies = [ "texturecraft-core", "texturecraft-geom", "texturecraft-texel", + "wasm-bindgen-futures", "wgpu", ] [[package]] name = "texturecraft-texel" -version = "0.1.0" +version = "0.2.0" [[package]] name = "texturecraft-ui-egui" -version = "0.1.0" +version = "0.2.0" dependencies = [ "base64 0.22.1", "craft-ui", + "craft-window", "eframe", "egui", "egui-phosphor", + "egui_kittest", "image", "js-sys", "log", @@ -3925,6 +4003,8 @@ dependencies = [ "rfd", "serde", "serde_json", + "skera", + "skrifa 0.48.0", "sys-locale", "texturecraft-engine", "texturecraft-render", @@ -3936,7 +4016,7 @@ dependencies = [ [[package]] name = "texturecraft-web" -version = "0.1.0" +version = "0.2.0" dependencies = [ "eframe", "js-sys", @@ -4172,6 +4252,12 @@ dependencies = [ "rustc-hash 2.1.3", ] +[[package]] +name = "typed-path" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54ec2755506471f54baf5e4bb5499d8e510cc1caf271270e778a736bd2d7336c" + [[package]] name = "typeid" version = "1.0.3" @@ -4186,7 +4272,7 @@ checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" dependencies = [ "memoffset", "tempfile", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -4705,7 +4791,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -5063,6 +5149,12 @@ dependencies = [ "version_check", ] +[[package]] +name = "winsafe" +version = "0.0.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ef0ffc427f045c0cc9ebffd6f4f91153dcd2a1547b5c3c29ee3f541e16e95c6" + [[package]] name = "winx" version = "0.36.4" @@ -5097,6 +5189,17 @@ dependencies = [ "wayland-protocols-wlr", ] +[[package]] +name = "write-fonts" +version = "0.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55716cfa7e8bcdb90289e07dfac478ccb2e3ec0f9a604fe682c7a03a7984d705" +dependencies = [ + "font-types", + "log", + "read-fonts 0.45.1", +] + [[package]] name = "write16" version = "1.0.0" @@ -5177,7 +5280,7 @@ checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7" [[package]] name = "xtask" -version = "0.1.0" +version = "0.2.0" dependencies = [ "serde_json", ] @@ -5391,18 +5494,16 @@ dependencies = [ [[package]] name = "zip" -version = "2.4.2" +version = "9.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fabe6324e908f85a1c52063ce7aa26b68dcb7eb6dbc83a2d148403c9bc3eba50" +checksum = "6e04976da629d3b04204ba8105b396a193af8ad2583b2c79bfb3ab8af580a11e" dependencies = [ - "arbitrary", "crc32fast", - "crossbeam-utils", - "displaydoc", "flate2", "indexmap", "memchr", - "thiserror 2.0.21", + "nix", + "typed-path", "zopfli", ] diff --git a/Cargo.toml b/Cargo.toml index 826e8ae7..b9dfc9aa 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,7 +5,7 @@ exclude = ["vendor"] default-members = ["crates/core", "crates/texel", "crates/geom", "crates/compose", "crates/bake", "crates/formats", "crates/paint", "crates/engine", "crates/render", "crates/automation", "crates/ui-egui", "apps/texturecraft", "apps/texturecraft-cli", "xtask"] [workspace.package] -version = "0.1.0" +version = "0.2.0" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" @@ -32,6 +32,11 @@ serde_json = "1" glam = { version = "0.30", features = ["serde", "bytemuck"] } bytemuck = { version = "1", features = ["derive"] } rayon = "1" +# Text alphas: shaping and glyph outlines, the versions egui's text layout already builds. +harfrust = "0.12" +skrifa = { version = "0.44", default-features = false, features = ["std"] } +# The UI's built-in fonts (Ubuntu Light, Hack): text alphas fall back to them without system fonts. +epaint_default_fonts = "0.37" log = "0.4" image = { version = "0.25", default-features = false, features = ["png", "jpeg", "tga", "tiff", "exr", "hdr", "bmp", "webp"] } half = "2" @@ -40,7 +45,7 @@ eframe = { version = "0.37", default-features = false } egui = "0.37" wgpu = "30" rfd = "0.17" -zip = { version = "2", default-features = false, features = ["deflate"] } +zip = { version = "9", default-features = false, features = ["deflate"] } gltf = { version = "1.4", default-features = false, features = ["import", "utils", "names", "KHR_materials_emissive_strength"] } tobj = { version = "4", default-features = false } flate2 = "1" @@ -54,9 +59,13 @@ schemars = "1" base64 = "0.22" cap-std = "4" getrandom = "0.3" +# Opening the control token file without following symlinks, and the effective uid (Unix). +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"] } +# 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"] } # egui 0.37 and winit: the suite's forks (storytold/egui, storytold/winit), as craft-libs pins them. [patch.crates-io] @@ -69,6 +78,7 @@ egui-winit = { git = "https://github.com/storytold/egui.git", rev = "6d518fc7996 egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } eframe = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } +egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" } # egui-phosphor has no release for egui 0.37 (vendor/egui-phosphor/VENDORED.md). egui-phosphor = { path = "vendor/egui-phosphor" } diff --git a/NOTICE b/NOTICE index d2ace09a..a6c9da4b 100644 --- a/NOTICE +++ b/NOTICE @@ -21,6 +21,7 @@ Every other bundled asset is original to TextureCraft (generated in code or draw project). Builds made with craft-fonts (CRAFT_FONTS_DIR; all official releases) also embed the fonts listed -in https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md (BIZ UDPGothic on desktop and -web, Noto Sans CJK SC on desktop), under the SIL Open Font License 1.1. Their licence texts ship +in https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md (Inter +and BIZ UDPGothic on desktop and web, Noto Sans CJK SC on desktop), under the SIL Open Font License +1.1. Their licence texts ship with the package as OFL-.txt. diff --git a/README.md b/README.md index ae9050c3..087fb53f 100644 --- a/README.md +++ b/README.md @@ -48,7 +48,7 @@

- The TextureCraft workspace: the material library on the left; the 3D viewport and the 2D UV view of a material ball in chipped red paint with grime and a hand-painted gold stripe, on a rusted iron base; and the texture set list, layer stack and brush properties on the right + The TextureCraft workspace: the material library on the left; the 3D viewport and the 2D UV view of a 1970s portable TV in aged cream plastic with a hand-drawn crayon flower; and the texture set list, the layer stack with its Crayon doodle and Wear and dirt folders, and the fill layer properties on the right
The workspace: asset shelf, 3D viewport, 2D UV view, texture sets, layer stack and properties

@@ -73,7 +73,7 @@ @@ -95,18 +95,19 @@ ## Made in TextureCraft -Both pieces below were textured with TextureCraft's procedural materials and smart materials (no -textures or models from anywhere else) and path traced on the GPU by `texturecraft-cli render`. +Two original props, modelled procedurally by contributors, textured layer by layer with TextureCraft's +own materials, masks and mesh-map generators (no textures or models from anywhere else) and path +traced on the GPU by `texturecraft-cli render`.
- Bake mode: the texture sets and mesh map bakers on the left, the common bake parameters below them, and the Bake selected textures button under the viewport + Bake mode on the portable TV: its seven texture sets and the mesh map bakers on the left, the common bake parameters below them, and the Bake selected textures button under the viewport

Bake mesh maps: ambient occlusion, curvature, thickness and more, ray traced on the GPU

@@ -83,11 +83,11 @@
- Rendering mode: the material ball path traced on the GPU at 256 samples with denoising, the gold stripe catching the studio light, and the render settings in a card over the viewport + Rendering mode: the portable TV path traced on the GPU at 256 samples with denoising, the curved screen catching the studio light, and the render settings in a card over the viewport

Rendering mode (F10): your textures path traced on the GPU, with a denoiser

- TextureCraft in the light brightness level with the blue accent: the same panels as rounded cards on a light background around the dark 3D viewport + TextureCraft in the light brightness level with the blue accent: the same panels as tiles on a light background around the dark 3D viewport

Light theme: four brightness levels and seven accent colours

- A path-traced crate: teal paint chipping off wooden planks, a rusted iron lid and a tarnished brass handle -

Crate: chipped paint on wood, rusted iron and tarnished brass smart materials, one per texture set

+ A path-traced storm lantern on a dark stage: red enamel chipped to bare steel on the edges, rust and grime in the seams, a cream pinstripe, a tarnished brass burner and knob, rusty guard wires and a glowing flame behind the glass globe +

Storm lantern: chipped enamel, rust, soot and a lit flame over eight texture sets

- Three path-traced material balls: glossy red car paint with a clear coat, purple velvet with sheen, and brushed steel with anisotropic highlights -

Shading lobes: car paint (clear coat), velvet (sheen) and brushed steel (anisotropy)

+ A path-traced vintage rangefinder camera: black enamel worn through to brass along the edges and corners of the top plate, cognac leatherette, knurled chrome dials, a black lens barrel with an engraved distance scale and a coated front element +

Rangefinder camera: black paint brassing, leatherette, chrome and coated glass

@@ -155,10 +156,10 @@ cd apps/texturecraft-web && trunk serve # web build cargo xtask ci # fmt, clippy, tests, layering, wasm ``` -You need Rust 1.95 or newer. The app opens with a baked sample project; **File ▸ New project** starts +You need Rust 1.95 or newer. The app opens with a baked sample project and a start window (new project, open, recent projects); **File ▸ New project** starts from a built-in mesh, a project template or your own mesh file (UVs are generated if it has none). -Japanese, Chinese and Korean interface text uses the fonts of +Japanese, Chinese, Korean and Arabic interface text uses the fonts of [storytold/craft-fonts](https://github.com/storytold/craft-fonts) where it has them, an optional build input (releases always use it): `CRAFT_FONTS_DIR="$PWD/../craft-fonts" cargo run --release -p texturecraft` (an absolute path). Without it, the desktop app uses the installed system fonts. @@ -188,7 +189,7 @@ area, the remaining work and what's next. to end, weighted by how much of the day each area carries: importing meshes, texture sets and UDIM tiles, the layer stack with masks, effects and smart materials, every painting tool, baking, the PBR viewport and Rendering mode, export presets and templates, and the full menu set. The interface -speaks English, French, German, Spanish, Portuguese, Italian, Japanese, Chinese and Korean; +speaks English, French, German, Spanish, Portuguese, Italian, Japanese, Chinese, Korean and Arabic; [localization-parity.md](docs/localization-parity.md) has the details. The scores are self-assessed from our code against public documentation. @@ -265,13 +266,20 @@ stand on its own. |:-:|---|---|---|---| | | **PhotoCraft** | Image editing: layers, masks, type and real PSD files | [GitHub](https://github.com/storytold/photocraft) | [Website](https://getartcraft.com/apps/photocraft) | | | **VectorCraft** | Vector illustration | [GitHub](https://github.com/storytold/vectorcraft) | [Website](https://getartcraft.com/apps/vectorcraft) | -| | **TextureCraft** | **3D texture painting · you are here** | [GitHub](https://github.com/storytold/texturecraft) | [Website](https://getartcraft.com/apps/texturecraft) | | | **FilmCraft** | Video editing, color and sound | [GitHub](https://github.com/storytold/filmcraft) | [Website](https://getartcraft.com/apps/filmcraft) | | | **LightCraft** | Photo library and raw development | [GitHub](https://github.com/storytold/lightcraft) | [Website](https://getartcraft.com/apps/lightcraft) | | | **PdfCraft** | Reading, organizing and protecting PDFs | [GitHub](https://github.com/storytold/pdfcraft) | [Website](https://getartcraft.com/apps/pdfcraft) | | | **EffectCraft** | Motion graphics and visual effects | [GitHub](https://github.com/storytold/effectcraft) | [Website](https://getartcraft.com/apps/effectcraft) | | | **DesignCraft** | Page layout and publishing | [GitHub](https://github.com/storytold/designcraft) | [Website](https://getartcraft.com/apps/designcraft) | +| | **FigCraft** | Interface design and prototyping | [GitHub](https://github.com/storytold/figcraft) | [Website](https://getartcraft.com/apps/figcraft) | +| | **WordCraft** | Word processing and documents | [GitHub](https://github.com/storytold/wordcraft) | [Website](https://getartcraft.com/apps/wordcraft) | +| | **SoundCraft** | Audio recording and editing | [GitHub](https://github.com/storytold/soundcraft) | [Website](https://getartcraft.com/apps/soundcraft) | +| | **DeckCraft** | Presentations and slide decks | [GitHub](https://github.com/storytold/deckcraft) | [Website](https://getartcraft.com/apps/deckcraft) | +| | **CADCraft** | Computer-aided design | [GitHub](https://github.com/storytold/cadcraft) | [Website](https://getartcraft.com/apps/cadcraft) | | | **GridCraft** | Spreadsheets and data | [GitHub](https://github.com/storytold/gridcraft) | [Website](https://getartcraft.com/apps/gridcraft) | +| | **TextureCraft** | 3D texture painting | [GitHub](https://github.com/storytold/texturecraft) | [Website](https://getartcraft.com/apps/texturecraft) | +| | **Craft Anything** | See how any software works, then build your own | [GitHub](https://github.com/storytold/craft-anything) | [Website](https://getartcraft.com/apps/craft-anything) | +| | **SolidCraft** | Parametric 3D CAD by Tangency Labs (community app) | [GitHub](https://github.com/tangency-labs/solidcraft) | | And [**ArtCraft**](https://getartcraft.com/) itself, our AI image and video studio for artists who want real control. diff --git a/ROADMAP.md b/ROADMAP.md index 48ca576c..25e398f2 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -4,25 +4,25 @@ TextureCraft aims for 1:1 parity with Adobe Substance 3D Painter's texturing wor performance, a smaller footprint, every feature drivable by agents (MCP, CLI, control channel), and builds for Windows, macOS, Linux, FreeBSD and the web. -## Honest parity estimate (2026-11-01) +## Honest parity estimate (2026-11-02) Weighted by how much of a professional's daily work each area carries. "Done" counts what works end to end today (engine + UI + automation + tests), not what is planned. | Area | Weight | Done | What works | Main gaps | |---|---:|---:|---|---| -| Project and files | 8 | 95% | New project from glTF/GLB, FBX (binary and ASCII, 6.x and 7.x), COLLADA, **USD (usda, usdc, usdz)**, **Alembic (Ogawa)**, OBJ, PLY, STL or built-in meshes (auto-unwrap when UVs are missing; a `.gltf`'s buffers and images and a loose USD layer's textures are read from its folder and kept in the project), **project templates** (built-in and saved from a project), `.tcraft` open/save/save as/save a copy, autosave, recent files, drag and drop, reimport mesh **with strokes preserved on the surface**, image resources, remove unused resources, OBJ, textured GLB and **USD** mesh export, browser open/save/download | HDF5 Alembic; Alembic animation (first sample only) | -| Texture sets | 6 | 95% | One set per material, **UDIM / UV tiles** (auto-detected or switched on later with resampling, **a resolution per tile**, one texture per tile at its own size, `$udim` export), list with visibility, sizes 128–8192 with resampling, add/remove channels (19 channel types incl. coat, sheen, anisotropy and scattering), height strength, normal format | Filter radii and height slopes of a tile smaller than its atlas block follow the block | -| Layer stack | 16 | 96% | Paint, fill, folder and **instance** layers; 32 per-channel blend modes and opacities; white/black/painted masks with **mask with height**; generator, fill, levels, invert/threshold, color selection, compare, blur, sharpen and HSL effects on masks and layer content; anchor points; smart masks; mask view (Alt+click); duplicate, group, drag to reorder, rename, color tags, copy/cut/paste (also as instance) across sets, flatten, instantiate across sets, save layers as smart materials; **27 library filters** (adjustments, blur/sharpen/high pass, bevel, glow, edge detect, warps, mosaic, baked lighting, material finishes); **geometry masks** (a layer on chosen mesh parts) | A few niche filters of the reference app's catalog | -| Painting tools | 14 | 88% | Paint, eraser, projection with image stencils, polygon fill, **path** and **lasso fill**, smudge, clone, color picker, quick mask, Shift+click lines with preview, 2D view painting; size, flow, stroke opacity, spacing, hardness, angle, follow path, jitters, alignment, angle fade, backface culling, lazy mouse, X/Y/Z mirror and **radial symmetry**, pen pressure, procedural and image alphas, **particle brush** | Pen tilt (not exposed by the windowing layer) | -| Materials and assets | 8 | 89% | **MaterialCraft materials** (`.mcmat`, sent to the shelf from MaterialCraft) as fill layers whose graph inputs and presets stay editable, re-cooked at the set's resolution with its baked mesh maps; 48 procedural materials (incl. car paint, velvet, brushed steel, skin, wax), 21 smart materials, 18 smart masks, **67 procedural brush alphas**, 22 procedurals, 6 environments plus imported HDR/EXR panoramas, image resources, a user smart material library, a tabbed shelf with search and **drag and drop** onto layers and the viewport | A smaller bundled library than the reference app's | +| Project and files | 8 | 95% | New project from glTF/GLB, FBX (binary and ASCII, 6.x and 7.x), COLLADA, **USD (usda, usdc, usdz)**, **Alembic (Ogawa)**, OBJ, PLY, STL or built-in meshes (auto-unwrap when UVs are missing; a `.gltf`'s buffers and images and a loose USD layer's textures are read from its folder and kept in the project), **project templates** (built-in and saved from a project), `.tcraft` open/save/save as/save a copy, autosave, **asks to save unsaved changes** before quitting or replacing the project (in the browser too, and before the tab closes), recent files, drag and drop, reimport mesh **with strokes preserved on the surface**, image resources, remove unused resources, OBJ, textured GLB and **USD** mesh export, browser open/save/download | HDF5 Alembic; Alembic animation (first sample only) | +| Texture sets | 6 | 95% | One set per material, **UDIM / UV tiles** (auto-detected or switched on later with resampling, **a resolution per tile**, one texture per tile at its own size, `$udim` export), list with visibility (show or hide all, invert, **focus** on one set), sizes 128–8192 with resampling, add/remove channels (19 channel types incl. coat, sheen, anisotropy and scattering), height strength, normal format | Filter radii and height slopes of a tile smaller than its atlas block follow the block | +| Layer stack | 16 | 97% | Paint, fill, folder and **instance** layers; 32 per-channel blend modes and opacities; white/black/painted masks with **mask with height**; generator, fill, levels (with a histogram of its input), invert/threshold, color selection, compare, blur, sharpen and HSL effects on masks and layer content; anchor points; smart masks; mask view (Alt+click); Alt+click a material channel to keep it alone; duplicate, group, drag to reorder, rename, color tags, copy/cut/paste (also as instance) across sets, flatten, instantiate across sets, save layers as smart materials; **30 library filters** (adjustments incl. histogram scan, range and shift, blur/sharpen/high pass, bevel, glow, edge detect, warps, mosaic, baked lighting, material finishes); **geometry masks** (a layer on chosen mesh parts) | A few niche filters of the reference app's catalog | +| Painting tools | 14 | 90% | Paint, eraser, projection with image stencils, polygon fill, **path** and **lasso fill**, smudge, clone, color picker, quick mask, Shift+click lines with preview, 2D view painting; size, flow, stroke opacity, spacing, hardness, angle, follow path, jitters, alignment, angle fade, backface culling, lazy mouse, X/Y/Z mirror and **radial symmetry**, pen pressure, procedural and image alphas, **text** in any installed font (as an alpha or a decal), **particle brush** | Pen tilt (not exposed by the windowing layer) | +| Materials and assets | 8 | 92% | **MaterialCraft materials** (`.mcmat`, sent to the shelf from MaterialCraft) as fill layers whose graph inputs and presets stay editable, re-cooked at the set's resolution with its baked mesh maps; 63 procedural materials (incl. car paint, velvet, brushed steel, skin, wax, ice, snow, bark), 21 smart materials, 18 smart masks, **67 procedural brush alphas**, **18 brush presets** plus user presets, 23 procedurals, 6 environments plus imported HDR/EXR panoramas, image resources, a user smart material library, a tabbed shelf with search and **drag and drop** onto layers and the viewport | A smaller bundled library than the reference app's | | Baking | 10 | 100% | AO, curvature (also from the normal map), thickness, world normal, position, ID, normal, height, **bent normals, opacity, color map and world-space direction**; **high-poly meshes**, cage, frontal/rear distances, average normals, **match by mesh name**; per-texture-set selection, common and per-map parameters, progress and cancel; high-poly base color textures embedded or in files beside a `.gltf`, FBX or USD layer | — | -| Viewport and display | 12 | 95% | PBR with image-based lighting, 6 procedural environments or imported HDR/EXR panoramas with exposure, rotation, blur, opacity, ACES/linear tone mapping, HDR pipeline with bloom, vignette, sharpen and grain, key-light shadows, 4× MSAA plus idle temporal accumulation, channel / mesh-map / mask / UV checker views, 3D and 2D wireframes, brush cursor, axis gizmos, subsurface scattering blur, **depth of field**, saved cameras and cameras from glTF, FBX, COLLADA and USD files, displacement (also in shadows and the path tracers), **path-traced Rendering mode** (F10, on the GPU or the CPU) with environment importance sampling and an edge-aware **denoiser** | Hardware ray tracing | +| Viewport and display | 12 | 95% | PBR with image-based lighting, 6 procedural environments or imported HDR/EXR panoramas with exposure, rotation, blur, opacity, ACES/linear tone mapping, HDR pipeline with bloom, vignette, sharpen and grain, key-light shadows, 4× MSAA plus idle temporal accumulation, the baked normal map under the painted normal, channel / mesh-map / mask / UV checker views, 3D and 2D wireframes of the mesh's own polygons, brush cursor, axis gizmos, subsurface scattering blur, **depth of field**, saved cameras and cameras from glTF, FBX, COLLADA and USD files, displacement (also in shadows and the path tracers), **path-traced Rendering mode** (F10, on the GPU or the CPU) with environment importance sampling and an edge-aware **denoiser** | Hardware ray tracing | | Shader | 6 | 100% | Metallic/roughness and specular/glossiness PBR, **clear coat, sheen, anisotropy and subsurface scattering** (viewport and path tracer), height-to-normal, painted normals, parallax occlusion, emissive, opacity (dithered), AO intensity | — | -| Export | 8 | 92% | 10 presets (incl. Godot 4 and **OpenPBR** with every shading lobe) plus **user output templates** (per-channel packing, converted maps, JSON import/export), PNG/JPEG/TGA/TIFF/BMP/WEBP/EXR/HDR, 8/16/32-bit, padding modes, size override, OpenGL/DirectX normals, `$udim` tiles, OBJ, textured GLB (with clearcoat/sheen) and USD (with clear coat) mesh export, zip download in the browser | Sheen and anisotropy in USD (UsdPreviewSurface has no inputs for them; GLB and OpenPBR maps carry them) | -| UI and UX | 8 | 95% | Painter-style layout with **dockable, tabbed, floating panels**, menus, tool shelf, tool bar, asset shelf, texture set list, layer stack with context menu, properties, display/shader/history/log panels, export dialog, new project dialog, bake mode, rendering mode, settings (interface scale, autosave, viewport texture resolution), saved UI layouts, **shortcut editor** with conflict detection, tooltips with shortcuts; all menu items live ([docs/parity.md](docs/parity.md)); **9 UI languages** with CJK fonts ([docs/localization-parity.md](docs/localization-parity.md)); closed panels reopen where they were; frame-budgeted compositing and uploads keep 8K sets responsive | Native-speaker review of the translations | -| Platforms | 4 | 75% | Windows, macOS (universal, signed and notarized), Linux (AppImage, deb, rpm, tar.gz, Flatpak), FreeBSD and web release workflows | First real release run; web build polish | -| **Total** | **100** | **≈ 93%** | | | +| Export | 8 | 92% | 10 presets (incl. Godot 4 and **OpenPBR** with every shading lobe) plus **user output templates** (per-channel packing, converted maps, JSON import/export), PNG/JPEG/TGA/TIFF/BMP/WEBP/EXR/HDR, 8/16/32-bit, padding modes, size override, OpenGL/DirectX normals, **colour space** of the colour maps (sRGB, Linear Rec.709, ACEScg, ACES2065-1; data maps never converted), `$udim` tiles, **MaterialX** (`file.exportTextures` with `materialX`: a `.mtlx` OpenPBR material per set, `` aware), OBJ, textured GLB (with clearcoat/sheen) and USD (with clear coat) mesh export, zip download in the browser | Sheen and anisotropy in USD (UsdPreviewSurface has no inputs for them; GLB and OpenPBR maps carry them) | +| UI and UX | 8 | 96% | Painter-style layout with **dockable, tabbed, floating panels**, menus, tool shelf, tool bar, asset shelf, texture set list, layer stack with context menu, properties, display/shader/history/log panels, export dialog, new project dialog, bake mode, rendering mode, settings (interface scale, autosave, viewport texture resolution, system title bar), **own title bar** with the app icon and window buttons (Windows, GNOME; integrated with the macOS traffic lights), saved UI layouts, a **start window** (new, open, recent projects), **shortcut editor** with conflict detection, tooltips with shortcuts, a compact color picker (saturation/value square, hue strip, copyable RGB); all menu items live ([docs/parity.md](docs/parity.md)); **10 UI languages** with CJK and Arabic fonts ([docs/localization-parity.md](docs/localization-parity.md)); closed panels reopen where they were; frame-budgeted compositing and uploads keep 8K sets responsive | Native-speaker review of the translations | +| Platforms | 4 | 76% | Windows, macOS (universal, signed and notarized), Linux (AppImage, deb, rpm, tar.gz, Flatpak), FreeBSD and web release workflows | First real release run; web build polish | +| **Total** | **100** | **≈ 94%** | | | Beyond the reference app: every command is available to agents through MCP, the CLI and the app's control channel (MCP workspace tools cover every file action: projects, meshes, high polys and diff --git a/apps/texturecraft-cli/src/main.rs b/apps/texturecraft-cli/src/main.rs index 21b7235b..8cc7f230 100644 --- a/apps/texturecraft-cli/src/main.rs +++ b/apps/texturecraft-cli/src/main.rs @@ -29,16 +29,19 @@ USAGE: Bake mesh maps for every texture set (a project is saved in place without -o). texturecraft-cli export [--preset ] [--format ] [--padding ] [--size ] Export textures (default preset: Document channels + Normal + AO). - texturecraft-cli render [--size x] [--view 3d|2d] [--yaw ] [--pitch ] - [--samples ] [--bounces ] [--cpu] - Render the viewport to PNG (needs a GPU or software adapter); --samples path traces it - instead (Rendering mode), on the GPU when it has compute shaders, else (or with --cpu) on - the CPU. + texturecraft-cli render [--size x] [--view 3d|2d] [--camera ] [--yaw ] + [--pitch ] [--samples ] [--bounces ] [--cpu] + Render the viewport to PNG (needs a GPU or software adapter); --camera looks through a + camera saved in the project (camera.add); --samples path traces it instead (Rendering + mode), on the GPU when it has compute shaders, else (or with --cpu) on the CPU. texturecraft-cli new > [--resolution ] [--sample] - New project; --sample bakes and applies a smart material to every texture set. + New project; --sample bakes and applies a smart material to every texture set. The + sample's mesh maps are baked at the resolution up to 1024 px (most of the file's size), + so a 2048 sample project is as large as a 1024 one. texturecraft-cli mcp [--bridge ] [--token ] [--read-root ] [--write-root ] MCP server on stdio: headless (file access only below the roots), or bridged to - `texturecraft --control `. + `texturecraft --control `. --automation-read-root / --automation-write-root are + the same as --read-root / --write-root (mcp and serve). texturecraft-cli serve [--port ] [--read-root ] [--write-root ] JSON lines ({\"id\",\"method\",\"params\"}) on stdio, or on 127.0.0.1: with a token. @@ -55,10 +58,10 @@ const SUBCOMMANDS: &[(&str, &[&str], &[&str])] = &[ ("batch", &[], &[]), ("bake", &["-o", "--resolution", "--maps"], &[]), ("export", &["--preset", "--format", "--padding", "--size"], &[]), - ("render", &["--size", "--view", "--yaw", "--pitch", "--samples", "--bounces"], &["--cpu"]), + ("render", &["--size", "--view", "--camera", "--yaw", "--pitch", "--samples", "--bounces"], &["--cpu"]), ("new", &["--resolution"], &["--sample"]), - ("mcp", &["--bridge", "--token", "--read-root", "--write-root"], &[]), - ("serve", &["--port", "--read-root", "--write-root"], &[]), + ("mcp", &["--bridge", "--token", "--read-root", "--write-root", "--automation-read-root", "--automation-write-root"], &[]), + ("serve", &["--port", "--read-root", "--write-root", "--automation-read-root", "--automation-write-root"], &[]), ]; struct Args { @@ -336,6 +339,9 @@ fn render(a: &Args) -> R { cpu: a.has("--cpu"), }; let mut h = open(input, None)?; + if let Some(name) = a.get("--camera") { + h.command_run("camera.select", json!({ "name": name })).map_err(s)?; + } let t0 = std::time::Instant::now(); let r = h.render_png(&o).map_err(s)?; let secs = t0.elapsed().as_secs_f64(); @@ -364,7 +370,9 @@ fn new(a: &Args) -> R { } fn workspace(a: &Args) -> Result { - let (r, w) = (a.get("--read-root").map(Path::new), a.get("--write-root").map(Path::new)); + // `--automation-*-root` is the spelling the other crafting apps use. + let root = |k: &str| a.get(&format!("--automation-{k}")).or_else(|| a.get(&format!("--{k}"))).map(Path::new); + let (r, w) = (root("read-root"), root("write-root")); if r.is_none() && w.is_none() { return Ok(Filesystem::Denied); } @@ -393,13 +401,16 @@ fn serve(a: &Args) -> R { match a.get("--port") { None => rpc::serve_lines(&h, std::io::stdin().lock(), std::io::stdout().lock()).map_err(s), Some(p) => { - let port = port_of(p)?; - let (token, file) = server_token(port).map_err(s)?; - rpc::serve_tcp(port, h, token, |addr| match file { + // Bind first: a port in use must not replace its server's token file, and port 0's + // token file is named after the port actually picked. + let listener = rpc::bind_tcp(port_of(p)?).map_err(s)?; + let addr = listener.local_addr().map_err(s)?; + let (token, file) = server_token(addr.port()).map_err(s)?; + match file { Some(f) => eprintln!("texturecraft-cli: serving on {addr}; token in {}", f.display()), None => eprintln!("texturecraft-cli: serving on {addr}; token from TEXTURECRAFT_CONTROL_TOKEN"), - }) - .map_err(s) + } + rpc::serve_listener(listener, h, token).map_err(s) } } } diff --git a/apps/texturecraft-cli/tests/cli.rs b/apps/texturecraft-cli/tests/cli.rs index 2a0b3dce..7232e2b7 100644 --- a/apps/texturecraft-cli/tests/cli.rs +++ b/apps/texturecraft-cli/tests/cli.rs @@ -97,6 +97,24 @@ fn info_on_a_mesh_reports_uvs() { let _ = std::fs::remove_dir_all(&d); } +#[test] +fn serve_takes_the_automation_root_spelling_too() { + use std::io::Write as _; + let d = tmp("automation-root"); + let mut child = Command::new(env!("CARGO_BIN_EXE_texturecraft-cli")) + .args(["serve", "--automation-write-root", p(&d)]) + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .spawn() + .unwrap(); + child.stdin.take().unwrap().write_all(b"{\"id\":1,\"method\":\"project.save\",\"params\":{\"path\":\"a.tcraft\"}}\n").unwrap(); + let out = child.wait_with_output().unwrap(); + let reply: Value = serde_json::from_slice(&out.stdout).unwrap(); + assert_eq!(reply["ok"], true, "{reply}"); + assert!(d.join("a.tcraft").is_file()); + let _ = std::fs::remove_dir_all(&d); +} + #[test] fn render_writes_a_png() { let d = tmp("render"); @@ -128,6 +146,12 @@ fn path_traced_render_needs_no_gpu() { let lum = |x, y| img.get_pixel(x, y).0.iter().map(|v| *v as u32).sum::(); assert!(lum(48, 28) > lum(1, 1) + 60); } + // --camera looks through a camera saved in the project; an unknown name is an error. + let proj = d.join("cams.tcraft"); + ok(&["run", "builtin:cube", "camera.set", r#"{"yaw": 80, "distance": 9}"#, "-o", p(&proj)]); + ok(&["run", p(&proj), "camera.add", r#"{"name": "Side"}"#, "-o", p(&proj)]); + ok(&["render", p(&proj), p(&out), "--size", "48x32", "--camera", "Side", "--samples", "2", "--cpu"]); + assert_eq!(cli(&["render", p(&proj), p(&out), "--camera", "Nope", "--samples", "2", "--cpu"]).status.code(), Some(1)); assert_eq!(cli(&["render", "builtin:cube", p(&out), "--samples", "0"]).status.code(), Some(1)); assert_eq!(cli(&["render", "builtin:cube", p(&out), "--samples", "4", "--view", "2d"]).status.code(), Some(1)); let _ = std::fs::remove_dir_all(&d); diff --git a/apps/texturecraft-web/Cargo.toml b/apps/texturecraft-web/Cargo.toml index b2d47259..e5512768 100644 --- a/apps/texturecraft-web/Cargo.toml +++ b/apps/texturecraft-web/Cargo.toml @@ -24,4 +24,4 @@ eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", " wasm-bindgen = "0.2" wasm-bindgen-futures = "0.4" js-sys = "0.3" -web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlCanvasElement", "Location", "KeyboardEvent", "EventTarget", "AddEventListenerOptions"] } +web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlCanvasElement", "Location", "KeyboardEvent", "BeforeUnloadEvent", "EventTarget", "AddEventListenerOptions"] } diff --git a/apps/texturecraft-web/src/web.rs b/apps/texturecraft-web/src/web.rs index 96bbc70c..bc1372a5 100644 --- a/apps/texturecraft-web/src/web.rs +++ b/apps/texturecraft-web/src/web.rs @@ -1,5 +1,6 @@ //! The eframe web runner: canvas lookup, backend selection, the loading screen's startup steps, -//! browser shortcuts the app takes over, and startup errors shown in the page. +//! browser shortcuts the app takes over, the unsaved-changes guard on close, and startup errors +//! shown in the page. use texturecraft_engine::Session; use texturecraft_ui_egui::TextureCraftApp; @@ -14,6 +15,7 @@ const PROGRESS_ID: &str = "texturecraft_progress"; pub fn start() { eframe::WebLogger::init(log::LevelFilter::Info).ok(); capture_app_shortcuts(); + guard_unsaved_changes(); wasm_bindgen_futures::spawn_local(async { let Some(document) = web_sys::window().and_then(|w| w.document()) else { log::error!("no document"); @@ -54,6 +56,7 @@ async fn run(canvas: web_sys::HtmlCanvasElement) -> Result<(), String> { options, Box::new(|cc| { let mut app = TextureCraftApp::new(cc, session); + app.ui.windows.start = app.ui.prefs.start_window; if let Some(rs) = &cc.wgpu_render_state { let backend = rs.adapter.get_info().backend; log::info!("TextureCraft: wgpu backend {backend:?}"); @@ -117,6 +120,23 @@ fn capture_app_shortcuts() { on_key.forget(); } +/// Closing or reloading the tab with unsaved changes makes the browser ask first (it shows its +/// own message; pages can't word it). +fn guard_unsaved_changes() { + let Some(window) = web_sys::window() else { return }; + let on_unload = Closure::::new(|e: web_sys::BeforeUnloadEvent| { + if texturecraft_ui_egui::web_files::unsaved() { + e.prevent_default(); + // Browsers that predate `preventDefault` here read the return value. + e.set_return_value("unsaved"); + } + }); + if let Err(e) = window.add_event_listener_with_callback("beforeunload", on_unload.as_ref().unchecked_ref()) { + log::warn!("couldn't guard unsaved changes on close: {e:?}"); + } + on_unload.forget(); +} + /// The baked sample project, or an empty material ball if that fails. Texture and bake sizes are /// kept small: the web build composites and bakes on one thread (bake 256 took ~12 s to start on a /// fast desktop CPU, 128 ~7.5 s). diff --git a/apps/texturecraft/Cargo.toml b/apps/texturecraft/Cargo.toml index 66964286..581b2eb0 100644 --- a/apps/texturecraft/Cargo.toml +++ b/apps/texturecraft/Cargo.toml @@ -13,11 +13,21 @@ workspace = true [dependencies] texturecraft-engine = { workspace = true } texturecraft-ui-egui = { workspace = true } +# The control channel's token, framing and connection limits (shared with `texturecraft-cli serve`). +texturecraft-automation = { workspace = true } eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "wayland", "x11", "persistence"] } egui = { workspace = true } image = { workspace = true } serde_json = { workspace = true } log = { workspace = true } +# Reads the saved System title bar setting before the window opens (eframe's settings format). +ron = "0.12" + +# The window's big (taskbar) icon, and the guard that keeps the app-drawn title bar's window +# borderless (src/window_frame.rs; winsafe is MIT, User32 only). +[target.'cfg(windows)'.dependencies] +winit = { version = "0.30", default-features = false } +winsafe = { version = "0.0.29", default-features = false, features = ["user"] } [build-dependencies] winresource = "0.1" diff --git a/apps/texturecraft/src/control_server.rs b/apps/texturecraft/src/control_server.rs index f7ee3b2a..b502fe55 100644 --- a/apps/texturecraft/src/control_server.rs +++ b/apps/texturecraft/src/control_server.rs @@ -1,42 +1,26 @@ //! Loopback JSON-lines control server (`--control `): one request per line, //! `{"id", "method", "params"}`, one reply per line. The first request must be //! `{"method":"auth","params":{"token":"…"}}` with the token from `TEXTURECRAFT_CONTROL_TOKEN` -//! or, when that is unset, the token written to `/texturecraft-control-.token`. +//! or, when that is unset, the token written (owner-only) to +//! `/texturecraft-control-.token`. Token handling, request framing and connection +//! limits are shared with `texturecraft-cli serve` (`texturecraft_automation::security`). -use std::io::{BufRead, BufReader, Read, Write}; +use std::io::{BufReader, Write}; use std::net::{TcpListener, TcpStream}; use std::sync::mpsc::{Receiver, Sender, channel}; use std::time::Duration; use serde_json::{Value, json}; +use texturecraft_automation::security::{ + AUTH_TIMEOUT, AuthDeadline, ConnectionLimiter, LineRead, MAX_CONNECTIONS, read_bounded_line, server_token, token_matches, +}; use texturecraft_ui_egui::ControlRequest; -/// Requests larger than this are rejected (screenshots go the other way). -const MAX_REQUEST: u64 = 8 << 20; - -fn token(port: u16) -> String { - if let Ok(t) = std::env::var("TEXTURECRAFT_CONTROL_TOKEN") - && t.len() >= 16 - { - return t; - } - use std::hash::{BuildHasher, Hasher}; - let mut out = String::new(); - for i in 0..4u64 { - let mut h = std::collections::hash_map::RandomState::new().build_hasher(); - h.write_u64(i ^ u64::from(std::process::id())); - h.write_u128(std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0)); - out.push_str(&format!("{:016x}", h.finish())); - } - let path = std::env::temp_dir().join(format!("texturecraft-control-{port}.token")); - if let Err(e) = std::fs::write(&path, &out) { - eprintln!("texturecraft: could not write the control token to {}: {e}", path.display()); - } else { - eprintln!("texturecraft: control token written to {}", path.display()); - } - out -} +/// How long an authenticated connection may stay idle. +const IDLE_TIMEOUT: Duration = Duration::from_secs(600); +/// Listen on `127.0.0.1:port` and return the requests for the UI thread to answer +/// ([`ControlRequest::reply`]). Bind or token failures are printed and leave the channel empty. pub fn start(port: u16, ctx: egui::Context) -> Receiver { let (tx, rx) = channel::(); let listener = match TcpListener::bind(("127.0.0.1", port)) { @@ -46,35 +30,65 @@ pub fn start(port: u16, ctx: egui::Context) -> Receiver { return rx; } }; - let token = token(port); - eprintln!("texturecraft: control server listening on 127.0.0.1:{port}"); - std::thread::spawn(move || { - for stream in listener.incoming().flatten() { - let (tx, ctx, token) = (tx.clone(), ctx.clone(), token.clone()); - std::thread::spawn(move || serve(stream, &token, tx, ctx)); + // After binding, so an app that cannot listen never replaces another server's token. + let token = match server_token(port) { + Ok((token, Some(path))) => { + eprintln!("texturecraft: control token written to {}", path.display()); + token } - }); + Ok((token, None)) => token, + Err(e) => { + eprintln!("texturecraft: control server disabled: {e}"); + return rx; + } + }; + eprintln!("texturecraft: control server listening on 127.0.0.1:{port}"); + std::thread::spawn(move || accept(listener, &token, &tx, &ctx)); rx } -fn serve(stream: TcpStream, token: &str, tx: Sender, ctx: egui::Context) { - let _ = stream.set_read_timeout(Some(Duration::from_secs(600))); - let Ok(read) = stream.try_clone() else { return }; - let mut reader = BufReader::new(read.take(u64::MAX)); - let mut out = stream; - let mut authed = false; - loop { - let mut line = String::new(); - let n = match reader.by_ref().take(MAX_REQUEST).read_line(&mut line) { - Ok(n) => n, - Err(_) => break, +/// Serve connections from `listener` (at most [`MAX_CONNECTIONS`] at once). +fn accept(listener: TcpListener, token: &str, tx: &Sender, ctx: &egui::Context) { + let limiter = ConnectionLimiter::default(); + for stream in listener.incoming() { + let Ok(mut stream) = stream else { continue }; + let Some(permit) = limiter.try_acquire(MAX_CONNECTIONS) else { + let _ = writeln!(stream, "{}", json!({"id": null, "ok": false, "error": "too many connections"})); + continue; }; - if n == 0 { - break; - } - if !line.ends_with('\n') && n as u64 >= MAX_REQUEST { - let _ = writeln!(out, "{}", json!({"id": null, "ok": false, "error": "request too large"})); - break; + let (tx, ctx, token) = (tx.clone(), ctx.clone(), token.to_string()); + std::thread::spawn(move || { + let _permit = permit; + serve(stream, &token, &tx, &ctx); + }); + } +} + +/// Send `reply` with the request's `id`; false when the client is gone. +fn reply(out: &mut TcpStream, id: Value, mut reply: Value) -> bool { + if let Some(o) = reply.as_object_mut() { + o.insert("id".into(), id); + } + writeln!(out, "{reply}").is_ok() && out.flush().is_ok() +} + +/// One connection: `auth` first (within [`AUTH_TIMEOUT`], one attempt), then requests +/// forwarded to the UI thread one at a time until the client disconnects or idles out. +fn serve(stream: TcpStream, token: &str, tx: &Sender, ctx: &egui::Context) { + let Ok(mut deadline) = AuthDeadline::start(&stream, AUTH_TIMEOUT).map(Some) else { return }; + let _ = stream.set_read_timeout(Some(IDLE_TIMEOUT)); + let Ok(read) = stream.try_clone() else { return }; + let mut reader = BufReader::new(read); + let mut out = stream; + let mut line = String::new(); + loop { + match read_bounded_line(&mut reader, &mut line) { + Ok(LineRead::Line) => {} + Ok(LineRead::TooLong) => { + reply(&mut out, Value::Null, json!({"ok": false, "error": "request too large"})); + return; + } + Ok(LineRead::Eof) | Err(_) => return, } if line.trim().is_empty() { continue; @@ -82,33 +96,133 @@ fn serve(stream: TcpStream, token: &str, tx: Sender, ctx: egui:: let msg: Value = match serde_json::from_str(&line) { Ok(v) => v, Err(e) => { - let _ = writeln!(out, "{}", json!({"id": null, "ok": false, "error": format!("bad JSON: {e}")})); + let sent = reply(&mut out, Value::Null, json!({"ok": false, "error": format!("bad JSON: {e}")})); + // Before `auth` a malformed line is the one refused attempt, as on `serve --port`. + if !sent || deadline.is_some() { + return; + } continue; } }; let id = msg.get("id").cloned().unwrap_or(Value::Null); let method = msg.get("method").and_then(Value::as_str).unwrap_or("").to_string(); let params = msg.get("params").cloned().unwrap_or(json!({})); - let mut reply = if !authed { - let ok = method == "auth" && params.get("token").and_then(Value::as_str) == Some(token); - authed = ok; - if ok { json!({"ok": true}) } else { json!({"ok": false, "error": "authenticate first: {\"method\":\"auth\",\"params\":{\"token\":…}}"}) } - } else { - let (req, rrx) = ControlRequest::new(method, params); - if tx.send(req).is_err() { - break; + if deadline.is_some() { + let supplied = params.get("token").and_then(Value::as_str).unwrap_or_default(); + if method != "auth" || !token_matches(token, supplied) { + // One attempt per connection, as on `texturecraft-cli serve`. + reply(&mut out, id, json!({"ok": false, "error": "authenticate first: {\"method\":\"auth\",\"params\":{\"token\":…}}"})); + return; } - ctx.request_repaint(); - rrx.recv_timeout(Duration::from_secs(120)).unwrap_or_else(|_| json!({"ok": false, "error": "timeout"})) - }; - if let Some(o) = reply.as_object_mut() { - o.insert("id".into(), id); + drop(deadline.take()); + if !reply(&mut out, id, json!({"ok": true})) { + return; + } + continue; } - if writeln!(out, "{reply}").is_err() || out.flush().is_err() || !authed { - if !authed { - continue; - } - break; + let (req, rrx) = ControlRequest::new(method, params); + if tx.send(req).is_err() { + return; + } + ctx.request_repaint(); + let answer = rrx.recv_timeout(Duration::from_secs(120)).unwrap_or_else(|_| json!({"ok": false, "error": "timeout"})); + if !reply(&mut out, id, answer) { + return; } } } + +#[cfg(test)] +mod tests { + use std::io::BufRead; + + use super::*; + + const TOKEN: &str = "0123456789abcdef0123456789abcdef"; + + /// A server on a free port whose app side answers every request with its method name. + fn server() -> std::net::SocketAddr { + let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let addr = listener.local_addr().unwrap(); + let (tx, rx) = channel::(); + std::thread::spawn(move || accept(listener, TOKEN, &tx, &egui::Context::default())); + std::thread::spawn(move || { + for r in rx { + let _ = r.reply.send(json!({"ok": true, "result": r.method})); + } + }); + addr + } + + fn connect(addr: std::net::SocketAddr) -> (TcpStream, BufReader) { + let s = TcpStream::connect(addr).unwrap(); + s.set_read_timeout(Some(Duration::from_secs(20))).unwrap(); + let r = BufReader::new(s.try_clone().unwrap()); + (s, r) + } + + fn call(w: &mut TcpStream, r: &mut BufReader, line: &str) -> Option { + writeln!(w, "{line}").ok()?; + let mut reply = String::new(); + (r.read_line(&mut reply).ok()? > 0).then(|| serde_json::from_str(&reply).unwrap()) + } + + #[test] + fn requests_need_the_token() { + let addr = server(); + // Anything before `auth` is refused and the connection closed. + let (mut w, mut r) = connect(addr); + let denied = call(&mut w, &mut r, r#"{"id":1,"method":"command.run","params":{"id":"file.open"}}"#).unwrap(); + assert_eq!(denied["ok"], false); + assert_eq!(denied["id"], 1); + assert!(call(&mut w, &mut r, r#"{"id":2,"method":"ping"}"#).is_none(), "closed after a refused request"); + // A wrong token is refused and gets no second try. + let (mut w, mut r) = connect(addr); + let wrong = format!(r#"{{"id":1,"method":"auth","params":{{"token":"{}x"}}}}"#, &TOKEN[1..]); + assert_eq!(call(&mut w, &mut r, &wrong).unwrap()["ok"], false); + let right = format!(r#"{{"id":2,"method":"auth","params":{{"token":"{TOKEN}"}}}}"#); + assert!(call(&mut w, &mut r, &right).is_none()); + // So is a malformed first line: no further lines before `auth`. + let (mut w, mut r) = connect(addr); + assert_eq!(call(&mut w, &mut r, "not json").unwrap()["ok"], false); + assert!(call(&mut w, &mut r, &right).is_none(), "closed after malformed JSON before auth"); + // The right token unlocks the connection. + let (mut w, mut r) = connect(addr); + let ok = call(&mut w, &mut r, &right).unwrap(); + assert_eq!((ok["ok"].clone(), ok["id"].clone()), (json!(true), json!(2))); + let pong = call(&mut w, &mut r, r#"{"id":3,"method":"ping"}"#).unwrap(); + assert_eq!((pong["result"].clone(), pong["id"].clone()), (json!("ping"), json!(3))); + assert_eq!(call(&mut w, &mut r, "not json").unwrap()["ok"], false); + assert_eq!(call(&mut w, &mut r, r#"{"id":4,"method":"ping"}"#).unwrap()["id"], 4, "bad JSON keeps an authenticated connection"); + } + + #[test] + fn connections_are_limited_and_idle_ones_time_out() { + let addr = server(); + let idle: Vec<_> = (0..MAX_CONNECTIONS).map(|_| connect(addr)).collect(); + // Let the server take every idle connection before the one over the limit. + std::thread::sleep(Duration::from_millis(300)); + // Read without writing: the server closes at once, and unread input would reset the + // connection before its reply arrives. + let (_, mut r) = connect(addr); + let mut full = String::new(); + r.read_line(&mut full).unwrap(); + assert_eq!(serde_json::from_str::(&full).unwrap()["error"], "too many connections"); + // Unauthenticated connections are closed after AUTH_TIMEOUT, which frees their slots. + for (_, mut r) in idle { + let mut rest = String::new(); + assert_eq!(r.read_line(&mut rest).unwrap(), 0); + } + // A slot frees once its thread has ended, which can trail the client's EOF a little. + let right = format!(r#"{{"id":1,"method":"auth","params":{{"token":"{TOKEN}"}}}}"#); + let authed = (0..50).any(|_| { + let (mut w, mut r) = connect(addr); + let ok = call(&mut w, &mut r, &right).is_some_and(|v| v["ok"] == true); + if !ok { + std::thread::sleep(Duration::from_millis(100)); + } + ok + }); + assert!(authed, "slots are freed after the auth deadline"); + } +} diff --git a/apps/texturecraft/src/gpu.rs b/apps/texturecraft/src/gpu.rs new file mode 100644 index 00000000..4d48a2ff --- /dev/null +++ b/apps/texturecraft/src/gpu.rs @@ -0,0 +1,272 @@ +//! Graphics adapter selection and multi-GPU configuration (#49). +//! +//! On machines with multiple GPUs (e.g. hybrid laptops or dual-GPU desktops with Intel/AMD iGPU and +//! NVIDIA/AMD dGPU), TextureCraft must allow users to select which graphics processor renders the +//! 3D viewport, and default to the high-performance discrete GPU for real-time PBR shading. +//! +//! Selection priority: +//! 1. Window surface support: adapters that cannot present to the surface are ranked last. +//! 2. Explicit filter: `--gpu ` CLI option or `WGPU_ADAPTER_NAME` environment variable (case-insensitive substring). +//! 3. Hardware before software: physical GPUs before software/CPU rasterizers (llvmpipe, lavapipe, WARP). +//! 4. Power preference: [`wgpu::PowerPreference::HighPerformance`] (default for 3D painting) prefers discrete GPUs, +//! [`wgpu::PowerPreference::LowPower`] prefers integrated GPUs, and [`wgpu::PowerPreference::None`] preserves system order. +//! 5. Backend preference: native backends (Vulkan, Metal, DX12) before OpenGL. + +use std::sync::Arc; + +use eframe::NativeOptions; +use eframe::egui_wgpu::WgpuSetup; +use eframe::wgpu::{self, Backend, DeviceType, PowerPreference}; + +/// Environment variable for choosing an adapter by name or substring. +pub const ADAPTER_NAME_ENV: &str = "WGPU_ADAPTER_NAME"; + +/// Environment variable for power preference (`high`, `low`, `none`). +pub const POWER_PREF_ENV: &str = "WGPU_POWER_PREF"; + +/// Parses a power preference string from CLI or environment variable. +pub fn parse_power_preference(s: &str) -> Result { + match s.trim().to_ascii_lowercase().as_str() { + "high" | "highperformance" | "high-performance" => Ok(PowerPreference::HighPerformance), + "low" | "lowpower" | "low-power" => Ok(PowerPreference::LowPower), + "none" | "default" => Ok(PowerPreference::None), + other => Err(format!("invalid power preference `{other}`: expected `high`, `low`, or `none`")), + } +} + +/// A graphics adapter candidate inspected during adapter selection. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Candidate { + pub name: String, + pub vendor: u32, + pub device: u32, + pub device_type: DeviceType, + pub backend: Backend, + pub surface_supported: bool, +} + +impl Candidate { + pub fn new(adapter: &wgpu::Adapter, surface: Option<&wgpu::Surface<'_>>) -> Self { + let info = adapter.get_info(); + Self { + name: info.name, + vendor: info.vendor, + device: info.device, + device_type: info.device_type, + backend: info.backend, + surface_supported: surface.is_none_or(|s| adapter.is_surface_supported(s)), + } + } + + /// Whether this candidate matches the given search filter (by name or backend). + pub fn matches_filter(&self, filter: &str) -> bool { + let filter_lower = filter.to_ascii_lowercase(); + self.name.to_ascii_lowercase().contains(&filter_lower) || format!("{:?}", self.backend).to_ascii_lowercase().contains(&filter_lower) + } + + /// Whether this is a CPU or software rasterizer. + pub fn is_software(&self) -> bool { + self.device_type == DeviceType::Cpu + || self.name.to_ascii_lowercase().contains("llvmpipe") + || self.name.to_ascii_lowercase().contains("lavapipe") + || self.name.to_ascii_lowercase().contains("warp") + } +} + +/// Chooses the best adapter index from the candidates based on filter, power preference, and surface support. +pub fn pick_adapter_index(candidates: &[Candidate], named_filter: Option<&str>, power: PowerPreference) -> Option { + if candidates.is_empty() { + return None; + } + + candidates + .iter() + .enumerate() + .min_by_key(|(orig_idx, c)| { + // Surface support is required; unsupported adapters rank last. + let surface_penalty = !c.surface_supported; + + // Explicit named filter (e.g. --gpu nvidia, WGPU_ADAPTER_NAME=3080). + let name_penalty = match named_filter { + Some(filter) => !c.matches_filter(filter), + None => false, + }; + + // Hardware GPUs before software/CPU rasterizers. + let software_penalty = c.is_software(); + + // Native backends before OpenGL (except when preserving system order). + let backend_rank = match (power, c.backend) { + (PowerPreference::None, _) => 0, + (_, Backend::Vulkan | Backend::Metal | Backend::Dx12) => 0, + (_, Backend::Gl) => 1, + _ => 2, + }; + + // Power preference ranking. + let power_rank = match power { + PowerPreference::HighPerformance => match c.device_type { + DeviceType::DiscreteGpu => 0, + DeviceType::IntegratedGpu => 1, + DeviceType::Other => 2, + DeviceType::VirtualGpu => 3, + DeviceType::Cpu => 4, + }, + PowerPreference::LowPower => match c.device_type { + DeviceType::IntegratedGpu => 0, + DeviceType::DiscreteGpu => 1, + DeviceType::Other => 2, + DeviceType::VirtualGpu => 3, + DeviceType::Cpu => 4, + }, + PowerPreference::None => match c.device_type { + DeviceType::Cpu => 1, + _ => 0, + }, + }; + + (surface_penalty, name_penalty, software_penalty, power_rank, backend_rank, *orig_idx) + }) + .map(|(idx, _)| idx) +} + +/// Configures `options` with adapter selection honoring `--gpu`, `WGPU_ADAPTER_NAME`, and `WGPU_POWER_PREF`. +pub fn configure(options: &mut NativeOptions, cli_gpu: Option, cli_power: Option) -> Result<(), String> { + let effective_filter = cli_gpu.or_else(|| std::env::var(ADAPTER_NAME_ENV).ok()); + let effective_power = match cli_power { + Some(p) => p, + None => match std::env::var(POWER_PREF_ENV) { + Ok(val) => parse_power_preference(&val)?, + Err(_) => PowerPreference::HighPerformance, + }, + }; + + if let WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup { + create.power_preference = effective_power; + + let filter = effective_filter.clone(); + create.native_adapter_selector = Some(Arc::new(move |adapters, surface| { + let candidates: Vec = adapters.iter().map(|a| Candidate::new(a, surface)).collect(); + + for (idx, c) in candidates.iter().enumerate() { + log::info!("graphics adapter #{idx}: {} ({:?}, {:?}, surface supported: {})", c.name, c.device_type, c.backend, c.surface_supported); + } + + let chosen_idx = pick_adapter_index(&candidates, filter.as_deref(), effective_power) + .ok_or_else(|| "no graphics adapter found that can present to the window".to_string())?; + + let chosen = &candidates[chosen_idx]; + if !chosen.surface_supported { + return Err("no graphics adapter found that can present to the window".to_string()); + } + + if let Some(ref f) = filter + && !chosen.matches_filter(f) + { + log::warn!("no graphics adapter matched filter `{f}`; fell back to {}", chosen.name); + } + + log::info!("selected graphics adapter: {} ({:?}, {:?})", chosen.name, chosen.device_type, chosen.backend); + + adapters.get(chosen_idx).cloned().ok_or_else(|| "selected adapter index out of range".to_string()) + })); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn dummy_candidate(name: &str, device_type: DeviceType, backend: Backend, surface_supported: bool) -> Candidate { + Candidate { name: name.to_string(), vendor: 0, device: 0, device_type, backend, surface_supported } + } + + #[test] + fn parses_power_preferences_correctly() { + assert_eq!(parse_power_preference("high").unwrap(), PowerPreference::HighPerformance); + assert_eq!(parse_power_preference("high-performance").unwrap(), PowerPreference::HighPerformance); + assert_eq!(parse_power_preference("low").unwrap(), PowerPreference::LowPower); + assert_eq!(parse_power_preference("low-power").unwrap(), PowerPreference::LowPower); + assert_eq!(parse_power_preference("none").unwrap(), PowerPreference::None); + assert_eq!(parse_power_preference("default").unwrap(), PowerPreference::None); + assert!(parse_power_preference("invalid").is_err()); + } + + #[test] + fn high_performance_default_prefers_discrete_gpu() { + let candidates = vec![ + dummy_candidate("AMD Radeon 660M", DeviceType::IntegratedGpu, Backend::Vulkan, true), + dummy_candidate("NVIDIA GeForce RTX 2050", DeviceType::DiscreteGpu, Backend::Vulkan, true), + ]; + + let selected = pick_adapter_index(&candidates, None, PowerPreference::HighPerformance); + assert_eq!(selected, Some(1)); + } + + #[test] + fn low_power_prefers_integrated_gpu() { + let candidates = vec![ + dummy_candidate("AMD Radeon 660M", DeviceType::IntegratedGpu, Backend::Vulkan, true), + dummy_candidate("NVIDIA GeForce RTX 2050", DeviceType::DiscreteGpu, Backend::Vulkan, true), + ]; + + let selected = pick_adapter_index(&candidates, None, PowerPreference::LowPower); + assert_eq!(selected, Some(0)); + } + + #[test] + fn none_power_preference_preserves_enumerated_order() { + let candidates = vec![ + dummy_candidate("GPU A (GL)", DeviceType::DiscreteGpu, Backend::Gl, true), + dummy_candidate("GPU B (Vulkan)", DeviceType::DiscreteGpu, Backend::Vulkan, true), + ]; + + let selected = pick_adapter_index(&candidates, None, PowerPreference::None); + assert_eq!(selected, Some(0)); + } + + #[test] + fn named_filter_selects_specific_gpu() { + let candidates = vec![ + dummy_candidate("Intel(R) UHD Graphics 770", DeviceType::IntegratedGpu, Backend::Vulkan, true), + dummy_candidate("NVIDIA GeForce RTX 3080", DeviceType::DiscreteGpu, Backend::Vulkan, true), + dummy_candidate("AMD Radeon RX 7900 XTX", DeviceType::DiscreteGpu, Backend::Vulkan, true), + ]; + + // Match by "3080" + let selected = pick_adapter_index(&candidates, Some("3080"), PowerPreference::HighPerformance); + assert_eq!(selected, Some(1)); + + // Match by "intel" + let selected_intel = pick_adapter_index(&candidates, Some("intel"), PowerPreference::HighPerformance); + assert_eq!(selected_intel, Some(0)); + + // Match by "7900" + let selected_amd = pick_adapter_index(&candidates, Some("7900"), PowerPreference::HighPerformance); + assert_eq!(selected_amd, Some(2)); + } + + #[test] + fn unsupported_surface_is_ranked_last() { + let candidates = vec![ + dummy_candidate("NVIDIA GeForce RTX 3080", DeviceType::DiscreteGpu, Backend::Vulkan, false), + dummy_candidate("Intel(R) UHD Graphics 770", DeviceType::IntegratedGpu, Backend::Vulkan, true), + ]; + + // Even with HighPerformance, RTX 3080 cannot present to the surface, so Intel is chosen. + let selected = pick_adapter_index(&candidates, None, PowerPreference::HighPerformance); + assert_eq!(selected, Some(1)); + } + + #[test] + fn hardware_gpu_preferred_over_software() { + let candidates = vec![ + dummy_candidate("llvmpipe (LLVM 18.1.8, 256 bits)", DeviceType::Cpu, Backend::Vulkan, true), + dummy_candidate("Intel(R) UHD Graphics 620", DeviceType::IntegratedGpu, Backend::Vulkan, true), + ]; + + let selected = pick_adapter_index(&candidates, None, PowerPreference::HighPerformance); + assert_eq!(selected, Some(1)); + } +} diff --git a/apps/texturecraft/src/main.rs b/apps/texturecraft/src/main.rs index 7e6bedb4..42b56ba4 100644 --- a/apps/texturecraft/src/main.rs +++ b/apps/texturecraft/src/main.rs @@ -6,9 +6,15 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] mod control_server; +mod gpu; +mod window_frame; use texturecraft_engine::Session; -use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::titlebar::TitleBar; +use texturecraft_ui_egui::{TextureCraftApp, UiState}; + +/// The app name eframe keeps the settings under (`eframe::storage_dir`). +const APP_NAME: &str = "TextureCraft"; const ICON_PNG: &[u8] = include_bytes!("../../../assets/app-icon/hicolor/256x256/apps/ai.storyteller.texturecraft.png"); @@ -27,11 +33,17 @@ struct Args { file: Option, control: Option, empty: bool, + gpu: Option, + power_pref: Option, } fn parse_args() -> Result, String> { - let mut args = Args { file: None, control: None, empty: false }; - let mut it = std::env::args().skip(1); + parse_args_from(std::env::args().skip(1)) +} + +fn parse_args_from>(it: I) -> Result, String> { + let mut args = Args { file: None, control: None, empty: false, gpu: None, power_pref: None }; + let mut it = it.into_iter(); while let Some(a) = it.next() { match a.as_str() { "--version" | "-V" => { @@ -39,13 +51,24 @@ fn parse_args() -> Result, String> { return Ok(None); } "--help" | "-h" => { - println!("{}\n\nUsage: texturecraft [project.tcraft | mesh file] [--control ] [--empty]", version()); + println!( + "{}\n\nUsage: texturecraft [project.tcraft | mesh file] [--control ] [--gpu ] [--power-pref ] [--empty]", + version() + ); return Ok(None); } "--control" => { let p = it.next().ok_or("--control needs a port")?; args.control = Some(p.parse().map_err(|_| format!("invalid port `{p}`"))?); } + "--gpu" => { + let g = it.next().ok_or("--gpu needs a GPU name or pattern")?; + args.gpu = Some(g); + } + "--power-pref" => { + let p = it.next().ok_or("--power-pref needs high, low, or none")?; + args.power_pref = Some(gpu::parse_power_preference(&p)?); + } "--empty" => args.empty = true, f if !f.starts_with('-') => args.file = Some(f.to_string()), other => return Err(format!("unknown option `{other}`")), @@ -81,6 +104,63 @@ fn icon() -> Option { Some(egui::IconData { rgba: img.into_raw(), width: w, height: h }) } +/// Windows shows a window's big icon (`ICON_BIG`) in the taskbar and Alt+Tab; eframe sets only the +/// small one, so the taskbar would show a generic icon. Set the big one too. +#[cfg(windows)] +fn set_taskbar_icon(w: &winit::window::Window) { + use winit::platform::windows::WindowExtWindows as _; + // An icon that can't be made leaves the generic one: nothing else depends on it. + if let Some(i) = icon().and_then(|i| winit::window::Icon::from_rgba(i.rgba, i.width, i.height).ok()) { + w.set_taskbar_icon(Some(i)); + } +} + +/// Settings › Interface › System title bar, read from the saved settings before the window opens +/// (eframe hands the app its storage only afterwards). Missing or unreadable: off. +fn saved_system_title_bar(persistence_path: Option<&std::path::Path>) -> bool { + let file = persistence_path.map(std::path::Path::to_path_buf).or_else(|| eframe::storage_dir(APP_NAME).map(|d| d.join("app.ron"))); + let saved = file.and_then(|f| std::fs::read_to_string(f).ok()); + let kv = saved.and_then(|s| ron::from_str::>(&s).ok()); + kv.and_then(|kv| ron::from_str::(kv.get("ui")?).ok()).is_some_and(|ui| ui.prefs.system_title_bar) +} + +/// The app with the window chrome that needs the native window: the Windows borderless guard, and +/// on macOS the traffic lights and AppKit's `movable` flag. +struct Shell { + app: TextureCraftApp, + window_frame: Option, + #[cfg(target_os = "macos")] + movable: Option, +} + +impl eframe::App for Shell { + fn auto_save_interval(&self) -> std::time::Duration { + self.app.auto_save_interval() + } + + fn save(&mut self, storage: &mut dyn eframe::Storage) { + self.app.save(storage); + } + + fn raw_input_hook(&mut self, _ctx: &egui::Context, _raw: &mut egui::RawInput) { + // winit gives the window its caption back when it changes the window's flags (maximize, + // restore, …): take it off again before the frame is laid out. + if let Some(guard) = self.window_frame.as_mut() { + guard(); + } + } + + fn logic(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) { + self.app.logic(ctx, frame); + } + + fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { + self.app.ui(ui, frame); + #[cfg(target_os = "macos")] + texturecraft_ui_egui::titlebar::sync_native(&self.app.title_bar, ui, frame, &mut self.movable); + } +} + fn main() { let args = match parse_args() { Ok(Some(a)) => a, @@ -96,25 +176,45 @@ fn main() { prev(info); })); let session = initial_session(&args); - let mut viewport = egui::ViewportBuilder::default().with_title("TextureCraft").with_inner_size([1600.0, 960.0]).with_min_inner_size([960.0, 600.0]); - if let Some(i) = icon() { - viewport = viewport.with_icon(i); - } // 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. let persistence_path = std::env::var_os("TEXTURECRAFT_NO_PREFS").map(|_| std::env::temp_dir().join(format!("texturecraft-noprefs-{}.ron", std::process::id()))); - let options = eframe::NativeOptions { viewport, renderer: eframe::Renderer::Wgpu, persistence_path, ..Default::default() }; + 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]); + if let Some(i) = icon() { + viewport = viewport.with_icon(i); + } + let viewport = title_bar.viewport(viewport); + let mut options = eframe::NativeOptions { viewport, renderer: eframe::Renderer::Wgpu, persistence_path, ..Default::default() }; + if let Err(e) = gpu::configure(&mut options, args.gpu, args.power_pref) { + eprintln!("texturecraft: {e}"); + 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. + let start = args.file.is_none() && control.is_none(); let r = eframe::run_native( - "TextureCraft", + APP_NAME, options, Box::new(move |cc| { + #[cfg(windows)] + if let Some(w) = cc.winit_window() { + set_taskbar_icon(w); + } + 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; if let Some(port) = control { app.control = Some(control_server::start(port, cc.egui_ctx.clone())); } - Ok(Box::new(app)) + Ok(Box::new(Shell { + app, + window_frame, + #[cfg(target_os = "macos")] + movable: None, + })) }), ); if let Err(e) = r { @@ -122,3 +222,46 @@ fn main() { std::process::exit(1); } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_gpu_and_power_preference_args() { + let args = parse_args_from(["--gpu".to_string(), "nvidia".to_string()]).unwrap().unwrap(); + assert_eq!(args.gpu.as_deref(), Some("nvidia")); + assert_eq!(args.power_pref, None); + + let args = parse_args_from(["--power-pref".to_string(), "high".to_string()]).unwrap().unwrap(); + assert_eq!(args.power_pref, Some(eframe::wgpu::PowerPreference::HighPerformance)); + + let args = parse_args_from(["--power-pref".to_string(), "low".to_string(), "--gpu".to_string(), "3080".to_string()]).unwrap().unwrap(); + assert_eq!(args.power_pref, Some(eframe::wgpu::PowerPreference::LowPower)); + assert_eq!(args.gpu.as_deref(), Some("3080")); + } + + #[test] + fn rejects_missing_or_invalid_gpu_args() { + assert!(parse_args_from(["--gpu".to_string()]).is_err()); + assert!(parse_args_from(["--power-pref".to_string()]).is_err()); + assert!(parse_args_from(["--power-pref".to_string(), "unrecognized".to_string()]).is_err()); + } + + #[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())); + 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. + 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(&path, "not ron").unwrap(); + assert!(!saved_system_title_bar(Some(&path))); + std::fs::remove_file(&path).unwrap(); + assert!(!saved_system_title_bar(Some(&path))); + } +} diff --git a/apps/texturecraft/src/window_frame.rs b/apps/texturecraft/src/window_frame.rs new file mode 100644 index 00000000..c45b4fd0 --- /dev/null +++ b/apps/texturecraft/src/window_frame.rs @@ -0,0 +1,351 @@ +//! Keeps the app-drawn title bar's undecorated window truly borderless on Windows (ported from +//! VectorCraft's `apps/vectorcraft/src/window_frame.rs`). +//! +//! winit 0.30 gives an undecorated window the `WS_CAPTION | WS_BORDER` styles and hides the +//! non-client area by spreading the client rect over it (`WM_NCCALCSIZE`). On some systems the +//! desktop compositor still reserves that frame for the window surface: the content is drawn +//! offset by the caption and border while the pointer keeps the un-offset client coordinates, so +//! it no longer points at what is drawn under it (rust-windowing/winit#2419). [`service`] strips +//! the two styles and has Windows recalculate the frame; winit puts them back whenever it changes +//! the window flags (maximize, restore, …), so the returned guard runs every frame. +//! +//! Windows sizes a maximize by the frame its styles describe, so a window maximized while its +//! caption is gone is sized without one: its rect covers the whole monitor, taskbar included, and +//! the shell reads a caption-less window covering its monitor as a full-screen app. With the +//! taskbar on the top or a side edge, the strip between the window's edge and the client area that +//! winit pins to the work area is drawn as a classic title bar. The guard therefore also moves a +//! parked maximize's rect back inside the work area on every edge, plus its own frame, clear of the +//! taskbar wherever it is, and repaints the window. +//! +//! An auto-hidden taskbar reserves no work area, so that move leaves a maximize covering the whole +//! monitor, and the taskbar would not show when the pointer reaches its edge. On each edge with an +//! auto-hidden taskbar the guard stops the window one pixel short of the monitor instead. + +/// Run once per frame; a no-op once the window is borderless. +pub type WindowFrameFn = Box; + +pub use platform::service; + +#[cfg(windows)] +mod platform { + use eframe::wgpu::rwh::{HasWindowHandle, RawWindowHandle}; + use winsafe::prelude::Handle; + use winsafe::{AtomStr, HWND, HwndPlace, POINT, SIZE, co}; + + /// A guard that keeps the window borderless each frame, or `None` when the system draws the + /// title bar (the window is decorated) or the window's handle can't be found. + pub fn service(cc: &eframe::CreationContext<'_>, app_frame: bool) -> Option { + if !app_frame { + return None; + } + let target = match cc.window_handle().ok()?.as_raw() { + RawWindowHandle::Win32(h) => h.hwnd.get(), + _ => return None, + }; + let hwnd = find_window(target)?; + reapply(&hwnd); + Some(Box::new(move || reapply(&hwnd))) + } + + /// One pass of the per-frame guard: the styles winit put back come off again, and a parked + /// maximize stays clear of the taskbar. + fn reapply(hwnd: &HWND) { + strip(hwnd); + keep_clear_of_the_taskbar(hwnd); + } + + /// The top-level window with the given raw handle: `EnumWindows` hands out real `HWND`s, so + /// this needs no `unsafe` to wrap a raw one. + fn find_window(target: isize) -> Option { + let mut found = None; + let _ = winsafe::EnumWindows(|hwnd| { + if hwnd.ptr() as isize == target { + found = Some(hwnd); + false + } else { + true + } + }); + found + } + + /// Removes `WS_CAPTION` (which includes `WS_BORDER`) and has Windows recalculate the frame; + /// the sizing border stays, so edge resizing and snapping keep working. + fn strip(hwnd: &HWND) { + let style = hwnd.style(); + let without = style & !(co::WS::CAPTION | co::WS::BORDER); + if without.raw() == style.raw() { + return; + } + hwnd.set_style(without); + let _ = hwnd.SetWindowPos( + HwndPlace::None, + POINT::new(), + SIZE::new(), + co::SWP::FRAMECHANGED | co::SWP::NOCOPYBITS | co::SWP::NOMOVE | co::SWP::NOSIZE | co::SWP::NOZORDER | co::SWP::NOACTIVATE, + ); + } + + /// [`super::clamped_rect`] for this frame's window: move a maximized window whose rect runs + /// under a taskbar on any edge back inside the work area plus its frame, and repaint it. A + /// maximized window that covers its whole monitor instead stops one pixel short of each edge + /// with an auto-hidden taskbar ([`super::short_of_autohide_taskbars`]). No-op otherwise. + fn keep_clear_of_the_taskbar(hwnd: &HWND) { + if !hwnd.IsZoomed() { + return; + } + let (Ok(r), Ok(mi)) = (hwnd.GetWindowRect(), hwnd.MonitorFromWindow(co::MONITOR::DEFAULTTONEAREST).GetMonitorInfo()) else { + return; + }; + let (m, w) = (mi.rcMonitor, mi.rcWork); + let (rect, monitor, work) = ((r.left, r.top, r.right, r.bottom), (m.left, m.top, m.right, m.bottom), (w.left, w.top, w.right, w.bottom)); + // The taskbars are looked up (a few `FindWindowEx` calls) only while the window covers its + // whole monitor, which it no longer does once trimmed. + let Some((left, top, right, bottom)) = super::clamped_rect(rect, monitor, work) + .or_else(|| super::covers(rect, monitor).then(|| super::short_of_autohide_taskbars(rect, monitor, work, &taskbar_edges(monitor))).flatten()) + else { + return; + }; + let (Some(width), Some(height)) = (right.checked_sub(left), bottom.checked_sub(top)) else { + return; + }; + // The frame moves while winit keeps the client rect on the work area: `NOCOPYBITS` and the + // invalidation have the whole window drawn again instead of the old frame's pixels being + // copied into the title bar. + let _ = hwnd.SetWindowPos( + HwndPlace::None, + POINT { x: left, y: top }, + SIZE { cx: width, cy: height }, + co::SWP::FRAMECHANGED | co::SWP::NOCOPYBITS | co::SWP::NOZORDER | co::SWP::NOACTIVATE, + ); + let _ = hwnd.InvalidateRect(None, false); + } + + /// The edges of `monitor` that have a taskbar, shown or auto-hidden: the primary monitor's + /// `Shell_TrayWnd` window and the other monitors' `Shell_SecondaryTrayWnd` windows. + fn taskbar_edges(monitor: super::Rect) -> Vec { + let mut edges = Vec::new(); + for class in ["Shell_TrayWnd", "Shell_SecondaryTrayWnd"] { + let mut after: Option = None; + // A monitor has at most one taskbar; the bound ends the walk if the shell keeps + // returning windows. + for _ in 0..64 { + let Ok(Some(tray)) = HWND::NULL.FindWindowEx(after.as_ref(), AtomStr::from_str(class), None) else { + break; + }; + if let Ok(r) = tray.GetWindowRect() { + edges.extend(super::taskbar_edge((r.left, r.top, r.right, r.bottom), monitor)); + } + after = Some(tray); + } + } + edges + } +} + +#[cfg(not(windows))] +mod platform { + pub fn service(_cc: &eframe::CreationContext<'_>, _app_frame: bool) -> Option { + None + } +} + +/// How far a parked maximize reaches past a monitor or work-area edge: the resize border (about +/// 8 pt at 100 %, more with DPI). Past that, a maximized window's rect is not parked but being +/// dragged or snapped, and is left alone. +const FRAME: i32 = 32; + +/// A rect in desktop coordinates: `(left, top, right, bottom)`, right and bottom exclusive. +#[cfg_attr(not(windows), allow(dead_code))] +type Rect = (i32, i32, i32, i32); + +/// The rect to move a maximize to so it stays inside the work area on every edge, plus the resize +/// border it was parked with, or `None` when it already does or `rect` is not parked at its +/// maximize place. `monitor` is the monitor's full rect and `work` its work area (the monitor less +/// the taskbar). The border is read from the edges that have no taskbar, and every edge must sit +/// that far outside either the monitor (where Windows puts a caption-less maximize) or the work +/// area (where the guard puts it), so a rect it already moved is left alone. Platform-neutral so +/// it is tested everywhere. +#[cfg_attr(not(windows), allow(dead_code))] +fn clamped_rect(rect: Rect, monitor: Rect, work: Rect) -> Option { + let (l, t, r, b) = rect; + let (ml, mt, mr, mb) = monitor; + let (wl, wt, wr, wb) = work; + if ml >= mr || mt >= mb || wl < ml || wt < mt || wr > mr || wb > mb || wl >= wr || wt >= wb { + return None; + } + // On an edge with a taskbar, the offsets from the monitor and from the work area can both + // look like a border, so only the edges without one are read. + let border = [ + (ml == wl).then(|| ml.checked_sub(l)).flatten(), + (mt == wt).then(|| mt.checked_sub(t)).flatten(), + (mr == wr).then(|| r.checked_sub(mr)).flatten(), + (mb == wb).then(|| b.checked_sub(mb)).flatten(), + ] + .into_iter() + .flatten() + .filter(|n| (0..=FRAME).contains(n)) + .min()?; + let parked = |monitor: Option, work: Option| monitor == Some(border) || work == Some(border); + if !parked(ml.checked_sub(l), wl.checked_sub(l)) + || !parked(mt.checked_sub(t), wt.checked_sub(t)) + || !parked(r.checked_sub(mr), r.checked_sub(wr)) + || !parked(b.checked_sub(mb), b.checked_sub(wb)) + { + return None; + } + let corrected = (wl.checked_sub(border)?, wt.checked_sub(border)?, wr.checked_add(border)?, wb.checked_add(border)?); + (corrected != rect).then_some(corrected) +} + +/// A monitor edge. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[cfg_attr(not(windows), allow(dead_code))] +enum Edge { + Left, + Top, + Right, + Bottom, +} + +/// Whether `rect` reaches every edge of `monitor`, which the shell treats as a full-screen app. +#[cfg_attr(not(windows), allow(dead_code))] +fn covers(rect: Rect, monitor: Rect) -> bool { + rect.0 <= monitor.0 && rect.1 <= monitor.1 && rect.2 >= monitor.2 && rect.3 >= monitor.3 +} + +/// The edge of `monitor` that a taskbar with the rect `taskbar` sits on: the edge nearest the +/// taskbar's center, or `None` when the taskbar does not overlap the monitor. An auto-hidden +/// taskbar is parked mostly past its edge with a sliver left on the monitor, so its center can lie +/// outside the monitor. +#[cfg_attr(not(windows), allow(dead_code))] +fn taskbar_edge(taskbar: Rect, monitor: Rect) -> Option { + let (tl, tt, tr, tb) = (i64::from(taskbar.0), i64::from(taskbar.1), i64::from(taskbar.2), i64::from(taskbar.3)); + let (ml, mt, mr, mb) = (i64::from(monitor.0), i64::from(monitor.1), i64::from(monitor.2), i64::from(monitor.3)); + if tl >= tr || tt >= tb || ml >= mr || mt >= mb || tr <= ml || tl >= mr || tb <= mt || tt >= mb { + return None; + } + // The center and the distances are doubled, so nothing is rounded. + let (cx, cy) = (tl + tr, tt + tb); + [(Edge::Left, cx - 2 * ml), (Edge::Top, cy - 2 * mt), (Edge::Right, 2 * mr - cx), (Edge::Bottom, 2 * mb - cy)] + .into_iter() + .min_by_key(|&(_, distance)| distance) + .map(|(edge, _)| edge) +} + +/// A maximize that covers its monitor, trimmed to stop one pixel short of the monitor on each of +/// the `taskbars` edges where the work area reaches the monitor's edge (the taskbar there is +/// auto-hidden). `None` when `rect` does not cover the monitor or nothing is trimmed. +#[cfg_attr(not(windows), allow(dead_code))] +fn short_of_autohide_taskbars(rect: Rect, monitor: Rect, work: Rect, taskbars: &[Edge]) -> Option { + if !covers(rect, monitor) { + return None; + } + let (mut l, mut t, mut r, mut b) = rect; + for edge in taskbars { + match edge { + Edge::Left if work.0 == monitor.0 => l = monitor.0.checked_add(1)?, + Edge::Top if work.1 == monitor.1 => t = monitor.1.checked_add(1)?, + Edge::Right if work.2 == monitor.2 => r = monitor.2.checked_sub(1)?, + Edge::Bottom if work.3 == monitor.3 => b = monitor.3.checked_sub(1)?, + _ => {} + } + } + let trimmed = (l, t, r, b); + (l < r && t < b && trimmed != rect).then_some(trimmed) +} + +#[cfg(test)] +mod tests { + use super::{Edge, clamped_rect, short_of_autohide_taskbars, taskbar_edge}; + + #[test] + fn a_maximize_covering_the_taskbar_is_trimmed_to_the_work_area() { + // 1920 × 1080 with a 34 px taskbar: a caption-less maximize covers the whole monitor, + // taskbar included. Trimmed so the rect ends at the work area plus the frame the window + // was parked with. + let monitor = (0, 0, 1920, 1080); + let work = (0, 0, 1920, 1046); + assert_eq!(clamped_rect((-7, -7, 1927, 1087), monitor, work), Some((-7, -7, 1927, 1046 + 7))); + } + + #[test] + fn a_maximize_already_clear_of_the_taskbar_is_left_alone() { + // What Windows sizes a framed maximize to: the work area plus the frame. + assert_eq!(clamped_rect((-8, -8, 1928, 1054), (0, 0, 1920, 1080), (0, 0, 1920, 1046)), None); + } + + #[test] + fn a_maximize_stays_clear_of_a_taskbar_on_any_edge() { + // A taskbar on the top or a side edge: the rect moves inside the work area there and + // keeps its frame on the other edges. Once moved, it is left alone. + let monitor = (0, 0, 1920, 1080); + let rect = (-8, -8, 1928, 1088); + for (work, expected) in [ + ((0, 0, 1920, 1046), (-8, -8, 1928, 1054)), + ((0, 48, 1920, 1080), (-8, 40, 1928, 1088)), + ((0, 2, 1920, 1080), (-8, -6, 1928, 1088)), + ((0, 0, 1920, 1078), (-8, -8, 1928, 1086)), + ((48, 0, 1920, 1080), (40, -8, 1928, 1088)), + ((0, 0, 1872, 1080), (-8, -8, 1880, 1088)), + ] { + assert_eq!(clamped_rect(rect, monitor, work), Some(expected), "work area {work:?}"); + assert_eq!(clamped_rect(expected, monitor, work), None, "already moved, work area {work:?}"); + } + } + + #[test] + fn a_top_taskbar_is_cleared_on_any_monitor_and_at_any_frame_size() { + // A monitor above and left of the primary one, at frame sizes up to the limit. + let monitor = (-1920, -1080, 0, 0); + let work = (-1920, -1032, 0, 0); + for border in [0, 8, 16, 32] { + let rect = (-1920 - border, -1080 - border, border, border); + let expected = (-1920 - border, -1032 - border, border, border); + assert_eq!(clamped_rect(rect, monitor, work), Some(expected), "border {border}"); + assert_eq!(clamped_rect(expected, monitor, work), None, "border {border}"); + } + } + + #[test] + fn a_maximize_without_a_reserved_taskbar_or_being_dragged_is_left_alone() { + let monitor = (0, 0, 1920, 1080); + assert_eq!(clamped_rect((-8, -8, 1928, 1088), monitor, monitor), None); + let work = (0, 0, 1920, 1046); + assert_eq!(clamped_rect((100, 200, 1100, 900), monitor, work), None, "moved"); + assert_eq!(clamped_rect((-500, -7, 1427, 1087), monitor, work), None, "resized"); + let work = (0, 48, 1920, 1080); + assert_eq!(clamped_rect((-500, -8, 1428, 1088), monitor, work), None, "resized under a top taskbar"); + assert_eq!(clamped_rect((0, 48, 960, 1080), monitor, work), None, "snapped to half the screen"); + } + + #[test] + fn a_maximize_stops_a_pixel_short_of_an_auto_hidden_taskbar_edge() { + // An auto-hidden taskbar reserves no work area, so the work area is the whole monitor. + let monitor = (0, 0, 1920, 1080); + let rect = (-8, -8, 1928, 1088); + for (edge, expected) in + [(Edge::Bottom, (-8, -8, 1928, 1079)), (Edge::Top, (-8, 1, 1928, 1088)), (Edge::Left, (1, -8, 1928, 1088)), (Edge::Right, (-8, -8, 1919, 1088))] + { + assert_eq!(short_of_autohide_taskbars(rect, monitor, monitor, &[edge]), Some(expected), "{edge:?}"); + assert_eq!(short_of_autohide_taskbars(expected, monitor, monitor, &[edge]), None, "already trimmed, {edge:?}"); + assert_eq!(clamped_rect(expected, monitor, monitor), None, "left alone on the next frame, {edge:?}"); + } + assert_eq!(short_of_autohide_taskbars(rect, monitor, monitor, &[]), None, "no taskbar"); + // A taskbar that reserves its work area is moved clear of by `clamped_rect` instead. + assert_eq!(short_of_autohide_taskbars(rect, monitor, (0, 0, 1920, 1032), &[Edge::Bottom]), None, "shown taskbar"); + assert_eq!(short_of_autohide_taskbars((0, 0, 960, 1080), monitor, monitor, &[Edge::Bottom]), None, "half-screen"); + } + + #[test] + fn a_taskbar_sits_on_the_monitor_edge_nearest_its_center() { + let monitor = (0, 0, 1920, 1080); + assert_eq!(taskbar_edge((0, 1032, 1920, 1080), monitor), Some(Edge::Bottom), "shown"); + assert_eq!(taskbar_edge((0, 1078, 1920, 1126), monitor), Some(Edge::Bottom), "auto-hidden"); + assert_eq!(taskbar_edge((0, -46, 1920, 2), monitor), Some(Edge::Top)); + assert_eq!(taskbar_edge((-60, 0, 2, 1080), monitor), Some(Edge::Left)); + assert_eq!(taskbar_edge((1918, 0, 1980, 1080), monitor), Some(Edge::Right)); + assert_eq!(taskbar_edge((1920, 1032, 3840, 1080), monitor), None, "other monitor"); + assert!(taskbar_edge((i32::MIN, i32::MIN, i32::MAX, i32::MAX), monitor).is_some(), "no overflow"); + } +} diff --git a/assets/app-icon/README.md b/assets/app-icon/README.md index 2130c6d0..07351074 100644 --- a/assets/app-icon/README.md +++ b/assets/app-icon/README.md @@ -30,7 +30,7 @@ artwork. Licence: see `LICENSE.txt`. | `texturecraft-1024.png` | full tile, 1024 px | docs, store listings | | `texturecraft.icns` | macOS icon set, 16 to 1024 px | `packaging/macos/package.sh` (`CFBundleIconFile`) | | `texturecraft.ico` | Windows icon, 16 to 256 px | `apps/texturecraft/build.rs` (embedded in the `.exe`), the MSI (`packaging/windows/package.ps1`) | -| `hicolor//apps/ai.storyteller.texturecraft.png` | Linux theme icons, 16 to 512 px; the 256 one is also the runtime window icon (`apps/texturecraft/src/main.rs`) and the README icon | `packaging/linux/ai.storyteller.texturecraft.desktop` | +| `hicolor//apps/ai.storyteller.texturecraft.png` | Linux theme icons, 16 to 512 px; the 256 one is also the runtime window and taskbar icon (`apps/texturecraft/src/main.rs`) and the README icon, and the 16 to 64 px ones the icon at the left of the title bar (`crates/ui-egui/src/titlebar.rs`) | `packaging/linux/ai.storyteller.texturecraft.desktop` | | `hicolor/scalable/apps/ai.storyteller.texturecraft.svg` | Linux scalable icon | as above | ## How it reaches each OS @@ -38,8 +38,8 @@ artwork. Licence: see `LICENSE.txt`. - **macOS:** the app sets the Dock / app-switcher icon at runtime (`ViewportBuilder::with_icon`); the `.app` from `packaging/macos/package.sh` carries `texturecraft.icns`. - **Windows:** `build.rs` embeds `texturecraft.ico` and VERSIONINFO with `winresource` (taskbar, Start - menu, Explorer, Alt-Tab); the runtime icon covers the title bar, and the MSI uses the same `.ico` - for its shortcuts. + menu, Explorer, Alt-Tab); the runtime icon covers the window and taskbar, and the MSI uses the + same `.ico` for its shortcuts. - **Linux and FreeBSD:** the packages install `packaging/linux/ai.storyteller.texturecraft.desktop` to `share/applications/` and `hicolor/` to `share/icons/`; the AppImage and Flatpak carry the same files. diff --git a/crates/automation/Cargo.toml b/crates/automation/Cargo.toml index 5b1d59d5..a0c3c0ad 100644 --- a/crates/automation/Cargo.toml +++ b/crates/automation/Cargo.toml @@ -24,5 +24,8 @@ base64 = { workspace = true } cap-std = { workspace = true } getrandom = { workspace = true } +[target.'cfg(unix)'.dependencies] +rustix = { workspace = true } + [dev-dependencies] rmcp = { workspace = true, features = ["client"] } diff --git a/crates/automation/src/render.rs b/crates/automation/src/render.rs index e98ccbf9..4621d6a0 100644 --- a/crates/automation/src/render.rs +++ b/crates/automation/src/render.rs @@ -77,7 +77,7 @@ impl Gpu { _ => None, }; if let Some(rgba) = aux { - h.renderer.upload_aux(&h.queue, ts, res, &rgba); + h.renderer.upload_aux(&h.device, &h.queue, ts, res, &rgba); } } } diff --git a/crates/automation/src/rpc.rs b/crates/automation/src/rpc.rs index f8922412..d159bc80 100644 --- a/crates/automation/src/rpc.rs +++ b/crates/automation/src/rpc.rs @@ -20,7 +20,9 @@ use serde_json::{Value, json}; use crate::budgets::json_text; use crate::headless::RenderOptions; -use crate::security::{ConnectionLimiter, LineRead, MAX_BATCH_STEPS, MAX_CONNECTIONS, MAX_REQUEST_BYTES, read_bounded_line, token_matches}; +use crate::security::{ + AUTH_TIMEOUT, AuthDeadline, ConnectionLimiter, LineRead, MAX_BATCH_STEPS, MAX_CONNECTIONS, MAX_REQUEST_BYTES, read_bounded_line, token_matches, +}; use crate::{AutomationError, Headless, bad}; pub const METHODS: &[&str] = &[ @@ -170,6 +172,7 @@ fn serve_connection(h: &Mutex, stream: std::net::TcpStream, token: &st let mut w = stream; let mut line = String::new(); let mut authed = false; + let mut deadline = Some(AuthDeadline::start(&w, AUTH_TIMEOUT)?); loop { match read_bounded_line(&mut r, &mut line)? { LineRead::Eof => return Ok(()), @@ -188,15 +191,26 @@ fn serve_connection(h: &Mutex, stream: std::net::TcpStream, token: &st if !authed { return write_reply(&mut w, &json!({"id": id, "ok": false, "error": "authenticate first: {\"method\":\"auth\",\"params\":{\"token\":…}}"})); } + drop(deadline.take()); write_reply(&mut w, &json!({"id": id, "ok": true}))?; } } +/// Listen on `127.0.0.1:port` (0 picks a port). +pub fn bind_tcp(port: u16) -> Result { + TcpListener::bind(("127.0.0.1", port)).map_err(|e| AutomationError::Io(format!("cannot listen on 127.0.0.1:{port}: {e}"))) +} + /// Serve authenticated JSON lines on `127.0.0.1:port` (0 picks a port) with one shared /// session. `ready` gets the bound address. pub fn serve_tcp(port: u16, h: Arc>, token: String, ready: impl FnOnce(std::net::SocketAddr)) -> Result<(), AutomationError> { - let listener = TcpListener::bind(("127.0.0.1", port)).map_err(|e| AutomationError::Io(format!("cannot listen on 127.0.0.1:{port}: {e}")))?; + let listener = bind_tcp(port)?; ready(listener.local_addr().map_err(|e| AutomationError::Io(e.to_string()))?); + serve_listener(listener, h, token) +} + +/// Serve authenticated JSON lines on a bound listener (see [`bind_tcp`]) with one shared session. +pub fn serve_listener(listener: TcpListener, h: Arc>, token: String) -> Result<(), AutomationError> { let limiter = ConnectionLimiter::default(); let token = Arc::new(token); for stream in listener.incoming() { diff --git a/crates/automation/src/security.rs b/crates/automation/src/security.rs index c781dfb3..0f5e6ab5 100644 --- a/crates/automation/src/security.rs +++ b/crates/automation/src/security.rs @@ -1,10 +1,13 @@ //! Tokens and bounded framing for the loopback JSON-lines transports (the app's control channel //! and `texturecraft-cli serve` share the token conventions). -use std::io::BufRead; -use std::path::PathBuf; +use std::io::{BufRead, Read, Write}; +use std::net::{Shutdown, TcpStream}; +use std::path::{Path, PathBuf}; use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::mpsc::{RecvTimeoutError, Sender, channel}; +use std::time::Duration; use crate::{AutomationError, bad}; @@ -14,6 +17,10 @@ pub const TOKEN_ENV: &str = "TEXTURECRAFT_CONTROL_TOKEN"; pub const MAX_REQUEST_BYTES: usize = 8 << 20; /// Simultaneous TCP connections served by `serve --port`. pub const MAX_CONNECTIONS: usize = 16; +/// Largest token file read (a token is at most 1024 characters, plus whitespace). +const MAX_TOKEN_FILE_BYTES: u64 = 4096; +/// Time a TCP client has to authenticate before its connection is closed. +pub const AUTH_TIMEOUT: Duration = Duration::from_secs(10); /// Steps in one `command_batch`. pub const MAX_BATCH_STEPS: usize = 256; @@ -44,7 +51,7 @@ pub fn client_token(port: u16, supplied: Option) -> Result t, None => { let path = token_file(port); - std::fs::read_to_string(&path) + read_token_file(&path) .map_err(|e| bad(format!("no control token: set {TOKEN_ENV} or start the app with `--control {port}` so it writes {} ({e})", path.display())))? } }; @@ -54,7 +61,8 @@ pub fn client_token(port: u16, supplied: Option) -> Result Result<(String, Option), AutomationError> { if let Ok(t) = std::env::var(TOKEN_ENV) { validate_token(t.trim())?; @@ -62,13 +70,60 @@ pub fn server_token(port: u16) -> Result<(String, Option), AutomationEr } let token = generate_token()?; let path = token_file(port); + write_token_file(&path, &token).map_err(|e| { + AutomationError::Io(format!("cannot write the control token to {} ({e}); set {TOKEN_ENV} to a token of your own instead", path.display())) + })?; + Ok((token, Some(path))) +} + +/// Write `token` to a new file at `path`, readable by the owner only on Unix. Whatever was at +/// `path` is removed first and the file is created exclusively (`O_EXCL`, which never follows +/// a symlink), so a file or link planted in a shared temp folder can neither keep its +/// permissions nor redirect the write; one that cannot be removed (another user's, in a sticky +/// `/tmp`) fails the call. +fn write_token_file(path: &Path, token: &str) -> std::io::Result<()> { + match std::fs::remove_file(path) { + Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(e), + _ => {} + } let mut o = std::fs::OpenOptions::new(); - o.write(true).create(true).truncate(true); + o.write(true).create_new(true); #[cfg(unix)] std::os::unix::fs::OpenOptionsExt::mode(&mut o, 0o600); - let res = o.open(&path).and_then(|mut f| std::io::Write::write_all(&mut f, token.as_bytes())); - res.map_err(|e| AutomationError::Io(format!("cannot write the control token to {}: {e}", path.display())))?; - Ok((token, Some(path))) + let mut f = o.open(path)?; + f.write_all(token.as_bytes())?; + f.sync_all() +} + +/// Read a token file written by [`write_token_file`]. On Unix the file must be a regular file +/// (not a symlink, FIFO or device) owned by this user with no group or other permissions, so a +/// file another user planted is never trusted and a link can't make a client send one of its +/// own secrets as the token. +fn read_token_file(path: &Path) -> std::io::Result { + #[cfg(unix)] + let file = { + use rustix::fs::{Mode, OFlags}; + use std::os::unix::fs::MetadataExt; + let flags = OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC; + let file = std::fs::File::from(rustix::fs::open(path, flags, Mode::empty())?); + let meta = file.metadata()?; + let refuse = |why: &str| Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, format!("refusing the token file: {why}"))); + if !meta.is_file() { + return refuse("not a regular file"); + } + if meta.uid() != rustix::process::geteuid().as_raw() { + return refuse("owned by another user"); + } + if meta.mode() & 0o077 != 0 { + return refuse("readable or writable by other users"); + } + file + }; + #[cfg(not(unix))] + let file = std::fs::File::open(path)?; + let mut out = String::new(); + file.take(MAX_TOKEN_FILE_BYTES).read_to_string(&mut out)?; + Ok(out) } /// Compare equal-length tokens without an early exit. @@ -134,6 +189,27 @@ impl Drop for Permit { } } +/// Closes a connection that has not authenticated in time, so idle or trickling clients can't +/// hold the few connection slots. Drop it once the client is authenticated (or gone). +pub struct AuthDeadline { + _cancel: Sender<()>, +} + +impl AuthDeadline { + /// Shut `stream` down after `timeout` unless the returned deadline is dropped first. + pub fn start(stream: &TcpStream, timeout: Duration) -> std::io::Result { + let stream = stream.try_clone()?; + let (tx, rx) = channel::<()>(); + std::thread::spawn(move || { + // Dropping the deadline disconnects the channel and ends this thread at once. + if let Err(RecvTimeoutError::Timeout) = rx.recv_timeout(timeout) { + let _ = stream.shutdown(Shutdown::Both); + } + }); + Ok(AuthDeadline { _cancel: tx }) + } +} + #[cfg(test)] mod tests { use super::*; @@ -149,6 +225,76 @@ mod tests { assert!(client_token(1, Some(format!(" {a}\n"))).is_ok()); } + fn scratch(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("tc-token-{}-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + #[test] + fn token_files_round_trip_and_replace_old_ones() { + let dir = scratch("round-trip"); + let path = dir.join("t.token"); + write_token_file(&path, "first-token-0123456789").unwrap(); + assert_eq!(read_token_file(&path).unwrap(), "first-token-0123456789"); + write_token_file(&path, "second-token-0123456789").unwrap(); + assert_eq!(read_token_file(&path).unwrap(), "second-token-0123456789"); + let _ = std::fs::remove_dir_all(dir); + } + + #[cfg(unix)] + #[test] + fn token_files_are_owner_only_even_over_an_open_file() { + use std::os::unix::fs::PermissionsExt; + let dir = scratch("perms"); + let path = dir.join("t.token"); + std::fs::write(&path, "old").unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o666)).unwrap(); + write_token_file(&path, "fresh-token-0123456789").unwrap(); + assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600); + let _ = std::fs::remove_dir_all(dir); + } + + #[cfg(unix)] + #[test] + fn token_files_never_write_through_a_symlink() { + let dir = scratch("symlink-write"); + let (path, victim) = (dir.join("t.token"), dir.join("victim")); + std::fs::write(&victim, "keep me").unwrap(); + std::os::unix::fs::symlink(&victim, &path).unwrap(); + write_token_file(&path, "fresh-token-0123456789").unwrap(); + assert_eq!(std::fs::read_to_string(&victim).unwrap(), "keep me"); + assert!(!std::fs::symlink_metadata(&path).unwrap().file_type().is_symlink()); + let _ = std::fs::remove_dir_all(dir); + } + + #[cfg(unix)] + #[test] + fn unsafe_token_files_are_refused() { + use std::os::unix::fs::PermissionsExt; + let dir = scratch("refuse"); + // Readable by others: another user may have planted or read it. + let open = dir.join("open.token"); + std::fs::write(&open, "planted-token-0123456789").unwrap(); + std::fs::set_permissions(&open, std::fs::Permissions::from_mode(0o644)).unwrap(); + assert!(read_token_file(&open).is_err()); + // A symlink, even to an owner-only file: a client must not send that file as its token. + let secret = dir.join("secret"); + write_token_file(&secret, "private-0123456789abcdef").unwrap(); + let link = dir.join("link.token"); + std::os::unix::fs::symlink(&secret, &link).unwrap(); + assert!(read_token_file(&link).is_err()); + // A FIFO is refused without blocking on open or read. + let fifo = dir.join("fifo.token"); + if std::process::Command::new("mkfifo").arg(&fifo).status().is_ok_and(|s| s.success()) { + assert!(read_token_file(&fifo).is_err()); + } + // A directory is not a token. + assert!(read_token_file(&dir).is_err()); + let _ = std::fs::remove_dir_all(dir); + } + #[test] fn oversized_lines_are_skipped() { let input = format!("{}\n{{\"ok\":1}}\n", "x".repeat(MAX_REQUEST_BYTES + 10)); @@ -160,6 +306,26 @@ mod tests { assert!(matches!(read_bounded_line(&mut r, &mut line).unwrap(), LineRead::Eof)); } + #[test] + fn auth_deadline_closes_idle_connections_only() { + let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let addr = listener.local_addr().unwrap(); + let idle = TcpStream::connect(addr).unwrap(); + let (server_idle, _) = listener.accept().unwrap(); + let _deadline = AuthDeadline::start(&server_idle, Duration::from_millis(200)).unwrap(); + let mut buf = [0u8; 1]; + idle.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + assert_eq!(std::io::Read::read(&mut &idle, &mut buf).unwrap(), 0, "closed by the deadline"); + + let kept = TcpStream::connect(addr).unwrap(); + let (server_kept, _) = listener.accept().unwrap(); + drop(AuthDeadline::start(&server_kept, Duration::from_millis(200)).unwrap()); + std::thread::sleep(Duration::from_millis(400)); + (&server_kept).write_all(b"x").unwrap(); + kept.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + assert_eq!(std::io::Read::read(&mut &kept, &mut buf).unwrap(), 1, "a met deadline leaves the connection open"); + } + #[test] fn limiter_releases() { let l = ConnectionLimiter::default(); diff --git a/crates/compose/src/display.rs b/crates/compose/src/display.rs index f82af292..96294c4a 100644 --- a/crates/compose/src/display.rs +++ b/crates/compose/src/display.rs @@ -169,13 +169,23 @@ pub fn tile_bytes(comp: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u3 let (n, sheen_rough) = (get(Channel::Normal), scalar8(Channel::SheenRoughness)); for i in 0..TILE_AREA { let px = &mut out[i * 4..i * 4 + 4]; - match n { - Some(t) => { + // The baked normal is the base the painted normal details sit on (as in export). + let (x, y) = (tx * TILE + (i as u32 % TILE), ty * TILE + (i as u32 / TILE)); + let base = baked.sample(BakedMap::Normal, x, y, res); + match (n, base) { + (Some(t), None) => { for (k, d) in px.iter_mut().take(3).enumerate() { *d = u8_of(t.get(i * 3 + k).copied().unwrap_or(0)); } } - None => px[..3].copy_from_slice(&[128, 128, 255]), + (detail, Some(base)) => { + let detail = detail.map_or([0.5, 0.5, 1.0], |t| [0, 1, 2].map(|k| t.get(i * 3 + k).map_or(0.0, |v| *v as f32 / 65535.0))); + let v = texturecraft_core::blend::rnm(base, detail); + for (d, v) in px.iter_mut().zip(v) { + *d = (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; + } + } + (None, None) => px[..3].copy_from_slice(&[128, 128, 255]), } px[3] = sheen_rough(i); } @@ -231,6 +241,23 @@ mod tests { assert_eq!(half::f16::from_le_bytes([h[2], h[3]]).to_f32(), half::f16::from_f32(0.04).to_f32(), "default F0"); } + #[test] + fn the_baked_normal_is_the_base_of_the_shown_normal() { + // A baked normal tilted to +X (packed), 64² like the set. + let tilted = [0.8f32, 0.5, 0.9]; + let baked = BakedMaps { resolution: 64, maps: [(BakedMap::Normal, std::sync::Arc::new(tilted.repeat(64 * 64)))].into_iter().collect() }; + let shown = |comp: &Composite| tile_bytes(comp, &baked, DisplayKind::Normal, 0, 0)[..3].to_vec(); + let pack = |v: [f32; 3]| v.map(|x| (x * 255.0 + 0.5) as u8).to_vec(); + // No normal channel: the baked normal as it is. + assert_eq!(shown(&Composite::new(&[], 64)), pack(tilted)); + // A flat painted normal leaves it; a painted detail is re-oriented onto it. + let mut comp = Composite::new(&[Channel::Normal], 64); + comp.channels.get_mut(&Channel::Normal).unwrap().set(0, 0, &[to_u16(0.5), to_u16(0.5), to_u16(1.0)]); + assert!(shown(&comp).iter().zip(pack(tilted)).all(|(a, b)| (*a as i32 - b as i32).abs() <= 1), "{:?}", shown(&comp)); + comp.channels.get_mut(&Channel::Normal).unwrap().set(0, 0, &[to_u16(0.5), to_u16(0.8), to_u16(0.9)]); + assert_eq!(shown(&comp), pack(texturecraft_core::blend::rnm(tilted, [0.5, 0.8, 0.9]))); + } + #[test] fn glossiness_shows_as_roughness_and_specular_rides_in_height() { let mut comp = Composite::new(&[Channel::Glossiness, Channel::Specular], 64); diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index f9f7e183..e4404588 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -1846,6 +1846,101 @@ pub fn mask_image(inp: &Inputs, id: LayerId, size: u32) -> Option> { Some(out) } +/// Tiles [`effect_histogram`] samples at most (a million texels). +const HISTOGRAM_TILES: usize = 256; + +/// The tiles [`effect_histogram`] reads: an even sample of at most [`HISTOGRAM_TILES`], which +/// keeps the cost flat up to 8K. The stride is odd: a power of two would divide the row length +/// and sample the same few columns. +fn histogram_tiles(width: u32, height: u32) -> Vec<(u32, u32)> { + let all = all_tiles(width, height); + let stride = all.len().div_ceil(HISTOGRAM_TILES).max(1) | 1; + all.into_iter().step_by(stride).collect() +} + +/// Histogram (`bins` buckets over 0..1) of the values entering effect `effect`: its layer's mask +/// below it, or (a content effect) the layer's `channel` below it where the layer has content, +/// color components pooled and signed values mapped to 0..1. Over the texels the mesh covers +/// (in an even sample of tiles on large sets); None for an unknown effect. +pub fn effect_histogram(inp: &Inputs, effect: LayerId, channel: Channel, bins: usize) -> Option> { + let (owner, _) = inp.project.effect(effect)?; + let bins = bins.max(1); + // Evaluate the layer forced visible, its mask enabled, cut just below the effect. + let mut cut = inp.project.clone(); + let l = cut.layers.get_mut(&owner)?; + l.visible = true; + let in_mask = match l.mask.as_mut().and_then(|m| m.effects.iter().position(|e| e.id == effect).map(|k| (m, k))) { + Some((m, k)) => { + m.enabled = true; + m.effects.truncate(k); + true + } + None => { + let k = l.content_effects.iter().position(|e| e.id == effect)?; + l.content_effects.truncate(k); + false + } + }; + let cut_inp = Inputs { project: &cut, preview: None, ..*inp }; + let channels = cut.texture_set(inp.ts).map(|t| t.channel_list()).unwrap_or_default(); + let tiles = histogram_tiles(inp.gbuf.width, inp.gbuf.height); + // A field covers the bounding box of the tiles it is built for, which for a scattered sample + // is the whole set: with a neighbourhood filter below, each tile gets its own. + let probe = neighbourhood_fields(&cut_inp, &channels, tiles.get(..1).unwrap_or_default()); + let shared = probe.is_empty().then_some(probe); + let bin = |v: f32| ((v.clamp(0.0, 1.0) * bins as f32) as usize).min(bins - 1); + let hist = tiles + .par_iter() + .map(|&(tx, ty)| { + let own; + let fields = match &shared { + Some(f) => f, + None => { + own = neighbourhood_fields(&cut_inp, &channels, &[(tx, ty)]); + &own + } + }; + let mut h = vec![0u32; bins]; + // The mask is planned on its own: a layer with nothing drawn plans no node. + let mask = if in_mask { layer_mask(&cut, owner).and_then(|m| mask_plan(&cut_inp, owner, m, tx, ty, Some(fields))) } else { None }; + let nodes = if in_mask { Vec::new() } else { plan(&cut_inp, &[owner], &channels, tx, ty, 0, Some(fields)) }; + let content = nodes.first().and_then(|n| n.chans.iter().find(|c| Channel::ALL.get(c.ch) == Some(&channel)).map(|c| (n, c))); + if mask.is_none() && content.is_none() { + return h; + } + let full = anchor_plan(&cut_inp, owner, &channels, tx, ty, Some(fields)); + for (x, y, o) in tile_texels(inp.gbuf, tx, ty) { + let mut tex = Texel::new(&cut_inp, x, y, o, 0.0); + if !full.is_empty() { + tex.anchors_below(&full, owner); + } + if let Some(m) = &mask { + if let Some(b) = h.get_mut(bin(tex.mask(m))) { + *b += 1; + } + } else if let Some((n, c)) = content + && let Some((v, _)) = tex.content(&n.content, c) + { + // As levels reads them (`per_unit`); normal maps pass through levels unchanged. + let (vals, signed) = match c.kind { + ChannelKind::Color => (&v[..], false), + ChannelKind::Scalar => (&v[..1], false), + ChannelKind::Signed => (&v[..1], true), + ChannelKind::NormalMap => (&v[..0], false), + }; + for x in vals { + if let Some(b) = h.get_mut(bin(if signed { x * 0.5 + 0.5 } else { *x })) { + *b += 1; + } + } + } + } + h + }) + .reduce(|| vec![0u32; bins], |a, b| a.iter().zip(&b).map(|(x, y)| x.saturating_add(*y)).collect()); + Some(hist) +} + /// One flattened tile of one channel: (channel, tile, premultiplied value + coverage data). pub type FlatTile = (Channel, (u32, u32), Vec); @@ -1962,6 +2057,17 @@ mod tests { (0..3).all(|i| (a[i] - b[i]).abs() < 2e-4) } + #[test] + fn histogram_samples_spread_over_every_column() { + assert_eq!(histogram_tiles(1024, 1024), all_tiles(1024, 1024), "small sets are read whole"); + for size in [2048, 4096, 8192] { + let tiles = histogram_tiles(size, size); + let columns: std::collections::BTreeSet = tiles.iter().map(|t| t.0).collect(); + assert!(tiles.len() <= HISTOGRAM_TILES, "{size}: {} tiles", tiles.len()); + assert!(columns.len() as u32 >= size / TILE / 2, "{size}: only {} columns", columns.len()); + } + } + #[test] fn empty_stack_gives_channel_defaults() { let f = fixture(); @@ -2180,6 +2286,13 @@ soft {soft:?}" assert_eq!(Filter::Grayscale.point(ChannelKind::Scalar, [0.3; 3]), Some([0.3; 3])); assert_eq!(Filter::NormalInvert.point(ChannelKind::NormalMap, [0.5, 0.25, 1.0]), Some([0.5, 0.75, 1.0])); assert_eq!(Filter::NormalInvert.point(ChannelKind::Color, [0.5, 0.25, 1.0]), Some([0.5, 0.25, 1.0])); + // Replace color: near colors shift (keeping their offset), far ones and scalars stay. + let rc = Filter::ReplaceColor { from: [0.8, 0.1, 0.1], to: [0.1, 0.1, 0.8], tolerance: 0.1, softness: 0.1 }; + assert!(close(rc.point(ChannelKind::Color, [0.85, 0.1, 0.1]).unwrap(), [0.15, 0.1, 0.8])); + assert!(close(rc.point(ChannelKind::Color, [0.1, 0.8, 0.1]).unwrap(), [0.1, 0.8, 0.1])); + let half = rc.point(ChannelKind::Color, [0.8, 0.1 + 0.15 * 3f32.sqrt(), 0.1]).unwrap(); + assert!((half[2] - 0.45).abs() < 0.02, "halfway through the softness: {half:?}"); + assert_eq!(rc.point(ChannelKind::Scalar, [0.8; 3]), Some([0.8; 3])); } #[test] diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 5435acdb..5e34945c 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -16,7 +16,7 @@ pub mod store; pub use below::{BelowCache, StackKey}; pub use display::{DisplayKind, tile_bytes}; pub use eval::{ - Composite, Inputs, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, covered_tiles, flatten_layer, mask_image, - pad_tiles, + Composite, Inputs, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, covered_tiles, effect_histogram, flatten_layer, + mask_image, pad_tiles, }; pub use store::{BakedMaps, ImageRes, ImageStore, PixelStore}; diff --git a/crates/compose/src/pattern.rs b/crates/compose/src/pattern.rs index e03685b7..9ca2a3da 100644 --- a/crates/compose/src/pattern.rs +++ b/crates/compose/src/pattern.rs @@ -67,17 +67,22 @@ fn raw(kind: ProceduralKind, p: Vec3, seed: u32) -> f32 { let d = f.x.min(1.0 - f.x).min(f.y.min(1.0 - f.y)); smoothstep(0.015, 0.035, d) * (0.9 + 0.1 * noise::cell_hash(c.x as i32, c.y as i32, 0, seed)) } - ProceduralKind::Weave => { - // Plain weave: in each cell the thread on top alternates (warp along X, weft along Y); - // the top thread shows its round cross-section, bulging mid-span. + ProceduralKind::Weave | ProceduralKind::Twill => { + // Warp along X, weft along Y: in each cell the thread on top shows its round + // cross-section, bulging mid-span. A plain weave alternates every cell; a 2/2 twill + // floats over two cells and steps one cell per row, so the floats line up in diagonal + // ribs, the weft darker than the warp. let c = (p * 2.0).floor(); let f = p * 2.0 - c; let pi = std::f32::consts::PI; - let warp_on_top = (c.x as i32 + c.y as i32).rem_euclid(2) == 0; + let twill = kind == ProceduralKind::Twill; + let (period, warp_cells) = if twill { (4, 2) } else { (2, 1) }; + let warp_on_top = (c.x as i32).wrapping_add(c.y as i32).rem_euclid(period) < warp_cells; let (across, along) = if warp_on_top { (f.y, f.x) } else { (f.x, f.y) }; let thread = (pi * across).sin().max(0.0).sqrt() * (0.8 + 0.2 * (pi * along).sin()); + let tone = if twill && !warp_on_top { 0.55 } else { 1.0 }; let fiber = noise::value([p.x * 40.0, p.y * 40.0, p.z], seed); - (thread * (0.88 + 0.12 * fiber)).clamp(0.0, 1.0) + (thread * tone * (0.88 + 0.12 * fiber)).clamp(0.0, 1.0) } ProceduralKind::Leather => { let w = noise::perlin((p * 0.7).to_array(), seed ^ 0x2D) - 0.5; @@ -351,6 +356,21 @@ mod tests { assert!(decal_uv(&Decal { size: [f32::NAN; 2], ..d }, Vec3::ZERO, z).is_none()); } + #[test] + fn twill_floats_run_in_diagonal_ribs() { + // The value at the centre of cell (x, y); cells are half a unit. + let at = |k, x: i32, y: i32| raw(k, Vec3::new(x as f32 * 0.5 + 0.25, y as f32 * 0.5 + 0.25, 0.0), 3); + for y in 1..8 { + let warp: Vec = (0..8).map(|x| at(ProceduralKind::Twill, x, y) > 0.7).collect(); + assert_eq!(warp.iter().filter(|w| **w).count(), 4, "row {y}: half the floats are warp"); + for x in 0..7 { + assert_eq!(warp[x as usize], at(ProceduralKind::Twill, x + 1, y - 1) > 0.7, "the rib continues diagonally at ({x}, {y})"); + } + } + // A plain weave shows every top thread alike. + assert!((0..8).all(|x| at(ProceduralKind::Weave, x, 0) > 0.7)); + } + #[test] fn every_pattern_varies() { for k in ProceduralKind::ALL { diff --git a/crates/core/src/blend.rs b/crates/core/src/blend.rs index e43fd4b8..5f165cdb 100644 --- a/crates/core/src/blend.rs +++ b/crates/core/src/blend.rs @@ -313,8 +313,9 @@ fn pack(n: [f32; 3]) -> [f32; 3] { n.map(|v| v / len * 0.5 + 0.5) } -/// Reoriented normal mapping (Barré-Brisebois & Hill): `detail` re-oriented onto `base`. -fn rnm(base: [f32; 3], detail: [f32; 3]) -> [f32; 3] { +/// Reoriented normal mapping (Barré-Brisebois & Hill): `detail` re-oriented onto `base` (both +/// packed into 0..1, as is the result). +pub fn rnm(base: [f32; 3], detail: [f32; 3]) -> [f32; 3] { let t = unpack(base); let t = [t[0], t[1], t[2] + 1.0]; let u = unpack(detail); diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index c524321a..21e62eca 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -228,6 +228,8 @@ pub enum ProceduralKind { Tiles, /// Plain fabric weave. Weave, + /// 2/2 twill: diagonal ribs, the warp brighter than the weft (denim, carbon fiber). + Twill, /// Leather grain: pebbled cells with creases. Leather, /// Hammered metal dimples. @@ -249,7 +251,7 @@ pub enum ProceduralKind { } impl ProceduralKind { - pub const ALL: [ProceduralKind; 22] = [ + pub const ALL: [ProceduralKind; 23] = [ ProceduralKind::Clouds, ProceduralKind::Perlin, ProceduralKind::Noise, @@ -263,6 +265,7 @@ impl ProceduralKind { ProceduralKind::Bricks, ProceduralKind::Tiles, ProceduralKind::Weave, + ProceduralKind::Twill, ProceduralKind::Leather, ProceduralKind::Hammered, ProceduralKind::Brushed, @@ -288,6 +291,7 @@ impl ProceduralKind { ProceduralKind::Bricks => "Bricks", ProceduralKind::Tiles => "Tiles", ProceduralKind::Weave => "Fabric weave", + ProceduralKind::Twill => "Twill weave", ProceduralKind::Leather => "Leather grain", ProceduralKind::Hammered => "Hammered", ProceduralKind::Brushed => "Brushed lines", @@ -584,6 +588,21 @@ pub enum Filter { min: f32, max: f32, }, + /// A ramp slid through the values: those above `position` go towards white, those below + /// towards black, over a width `contrast` (0..1) narrows to a hard step. + HistogramScan { + position: f32, + contrast: f32, + }, + /// The values squeezed towards `position`: `range` 1 keeps them, 0 sets them all to it. + HistogramRange { + range: f32, + position: f32, + }, + /// The values offset by `offset` (−1..1), wrapping around past white and black. + HistogramShift { + offset: f32, + }, /// Shift each texel's lookup along a noise vector field: `intensity` in texels at 2K, /// `scale` noise features per UV unit. Warp { @@ -647,6 +666,14 @@ pub enum Filter { ambient: f32, occlusion: f32, }, + /// Colors near `from` (within `tolerance`, fading out over `softness`, as RGB distance + /// 0..1) shifted by `to − from`, so their shading and texture stay (linear RGB). + ReplaceColor { + from: [f32; 3], + to: [f32; 3], + tolerance: f32, + softness: f32, + }, } /// Push `x` (0..1) towards 1 (`amount` > 0) or 0 (`amount` < 0); `amount` in −1..1. @@ -783,6 +810,24 @@ impl Filter { let (lo, hi) = (min.min(*max), min.max(*max)); per_unit(kind, v, |x| x.max(lo).min(hi)) } + // Full contrast is a threshold: the position itself goes to white. + Filter::HistogramScan { position, contrast } if *contrast >= 1.0 => per_unit(kind, v, |x| if x >= *position { 1.0 } else { 0.0 }), + Filter::HistogramScan { position, contrast } => { + let width = (1.0 - contrast.clamp(0.0, 1.0)).max(1e-3); + per_unit(kind, v, |x| unit((x - position) / width + 0.5)) + } + Filter::HistogramRange { range, position } => per_unit(kind, v, |x| unit(position + (x - position) * range)), + Filter::HistogramShift { offset } => per_unit(kind, v, |x| { + // Wrapped by hand: `rem_euclid` would also send white (1 + 0) to black. + let y = unit(x) + offset.clamp(-1.0, 1.0); + unit(if y > 1.0 { + y - 1.0 + } else if y < 0.0 { + y + 1.0 + } else { + y + }) + }), Filter::Grayscale => match kind { ChannelKind::Color => [lum(v); 3], _ => v, @@ -791,6 +836,22 @@ impl Filter { ChannelKind::NormalMap => [v[0], 1.0 - v[1], v[2]], _ => v, }, + Filter::ReplaceColor { from, to, tolerance, softness } => match kind { + ChannelKind::Color => { + let d = ((v[0] - from[0]).powi(2) + (v[1] - from[1]).powi(2) + (v[2] - from[2]).powi(2)).sqrt() / 3f32.sqrt(); + let (t, s) = (tolerance.clamp(0.0, 1.0), softness.clamp(0.0, 1.0)); + let w = if d <= t { + 1.0 + } else if d >= t + s { + 0.0 + } else { + let x = 1.0 - (d - t) / s.max(1e-6); + x * x * (3.0 - 2.0 * x) + }; + std::array::from_fn(|k| unit(v[k] + (to[k] - from[k]) * w)) + } + _ => v, + }, Filter::Blur { .. } | Filter::Sharpen { .. } | Filter::Warp { .. } @@ -818,6 +879,9 @@ impl Filter { Filter::GradientMap { .. } => "Gradient Map", Filter::Posterize { .. } => "Posterize", Filter::Clamp { .. } => "Clamp", + Filter::HistogramScan { .. } => "Histogram Scan", + Filter::HistogramRange { .. } => "Histogram Range", + Filter::HistogramShift { .. } => "Histogram Shift", Filter::Warp { .. } => "Warp", Filter::DirectionalBlur { .. } => "Blur Directional", Filter::SlopeBlur { .. } => "Slope Blur", @@ -830,6 +894,7 @@ impl Filter { Filter::Mosaic { .. } => "Mosaic", Filter::Glow { .. } => "Glow", Filter::BakedLighting { .. } => "Baked Lighting", + Filter::ReplaceColor { .. } => "Replace Color", } } @@ -992,6 +1057,17 @@ mod tests { assert_eq!(Filter::GradientMap { colors: vec![] }.point(c, [0.3; 3]), None, "an empty gradient changes nothing"); assert!(close(Filter::Posterize { levels: 2.0 }.point(c, [0.2, 0.6, 0.9]).unwrap(), [0.0, 1.0, 1.0])); assert!(close(Filter::Clamp { min: 0.8, max: 0.3 }.point(c, [0.1, 0.5, 0.9]).unwrap(), [0.3, 0.5, 0.8]), "swapped bounds never panic"); + let scan = |position, contrast| Filter::HistogramScan { position, contrast }.point(c, [0.2, 0.5, 0.9]).unwrap(); + assert!(close(scan(0.5, 0.0), [0.2, 0.5, 0.9]), "a full-width ramp at the middle keeps the values"); + assert!(close(scan(0.4, 1.0), [0.0, 1.0, 1.0]), "full contrast is a step at the position"); + assert!(close(scan(0.5, 1.0), [0.0, 1.0, 1.0]), "the position itself goes to white"); + assert!(close(scan(0.7, 0.5), [0.0, 0.1, 0.9])); + let range = |range, position| Filter::HistogramRange { range, position }.point(c, [0.2, 0.5, 0.9]).unwrap(); + assert!(close(range(1.0, 0.3), [0.2, 0.5, 0.9]) && close(range(0.0, 0.3), [0.3; 3])); + assert!(close(range(0.5, 0.5), [0.35, 0.5, 0.7])); + let shift = |offset| Filter::HistogramShift { offset }.point(c, [0.0, 0.5, 1.0]).unwrap(); + assert!(close(shift(0.0), [0.0, 0.5, 1.0]), "no offset keeps white white"); + assert!(close(shift(0.25), [0.25, 0.75, 0.25]) && close(shift(-0.25), [0.75, 0.25, 0.75])); let cb = Filter::ColorBalance { shadows: [0.2, 0.0, 0.0], midtones: [0.0; 3], highlights: [0.0, 0.0, 0.2] }; assert!(cb.point(c, [0.05; 3]).unwrap()[0] > 0.2 && cb.point(c, [0.95; 3]).unwrap()[2] > 0.99); assert!(close(Filter::Invert.point(ChannelKind::Signed, [0.5; 3]).unwrap(), [-0.5; 3])); diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index f4b50a66..2a8dbf58 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -254,7 +254,8 @@ impl Default for BakeSettings { ao: RaySettings::default(), ao_ignore_backface: false, ao_self_occlusion: SelfOcclusion::Always, - thickness: RaySettings::default(), + // Thickness is hit distance / max distance: long rays turn thin parts almost black. + thickness: RaySettings { max_distance: 0.1, ..RaySettings::default() }, bent_normal: RaySettings::default(), curvature_strength: 1.0, curvature_from_normal: false, @@ -592,6 +593,9 @@ impl Default for Camera { } } +/// Built-in environments, in menu order. +pub const ENVIRONMENTS: [&str; 6] = ["Studio Soft", "Studio Contrast", "Overcast", "Sunset", "Warehouse", "Night"]; + /// Prefix of [`DisplaySettings::environment`] naming an image resource. pub const ENV_RESOURCE_PREFIX: &str = "resource:"; @@ -637,6 +641,10 @@ pub struct Project { pub name: String, /// Path of the mesh inside the project file (or a built-in primitive id `builtin:`). pub mesh: String, + /// File name the mesh was imported from (`quad.gltf`). The stored mesh is read again under + /// 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, pub normal_format: NormalFormat, pub texture_sets: Vec, pub layers: BTreeMap, @@ -653,6 +661,7 @@ impl Project { format_version: FORMAT_VERSION, name: name.into(), mesh: mesh.into(), + mesh_file: String::new(), normal_format: NormalFormat::OpenGl, texture_sets: Vec::new(), layers: BTreeMap::new(), diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index ac357ccc..2500d9ed 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -17,6 +17,7 @@ texturecraft-paint = { workspace = true } texturecraft-bake = { workspace = true } texturecraft-formats = { workspace = true } rayon = { workspace = true } +epaint_default_fonts = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } thiserror = { workspace = true } diff --git a/crates/engine/src/brush_preset_cmds.rs b/crates/engine/src/brush_preset_cmds.rs new file mode 100644 index 00000000..0ebfa070 --- /dev/null +++ b/crates/engine/src/brush_preset_cmds.rs @@ -0,0 +1,85 @@ +//! Brush presets: the built-in ones, and the user's own saved as `.tcbrush` files (the brush +//! settings as JSON). Applying or loading one changes the stroke and keeps the brush's size. + +use serde_json::{Value, json}; +use texturecraft_paint::BrushSettings; +use texturecraft_paint::presets::{PRESETS, find_preset, with_stroke_of}; + +use crate::commands::{CommandSpec, always, bad, strp}; +use crate::tool_cmds::brush_json; +use crate::{Result, Session, cmd}; + +/// File extension of a saved brush preset. +pub const BRUSH_EXT: &str = "tcbrush"; +/// Largest preset file read. +#[cfg(not(target_arch = "wasm32"))] +const MAX_BYTES: u64 = 1 << 20; + +pub fn specs() -> Vec { + vec![ + cmd!("brush.preset.list", "List brush presets", [], None, "{} — the built-in presets: id, label, category", always, |_, _| Ok(list())), + cmd!( + "brush.preset.apply", + "Apply brush preset", + [], + None, + "{preset: id or label (brush.preset.list)} — sets the stroke (alpha, spacing, flow, hardness, jitters…), keeps the size", + always, + apply + ), + cmd!("brush.preset.save", "Save brush preset", [], None, "{path} — the current brush as a .tcbrush file", always, save), + cmd!("brush.preset.load", "Load brush preset", [], None, "{path} — a .tcbrush file's stroke on the brush, keeping the size", always, load), + ] +} + +fn list() -> Value { + json!(PRESETS.iter().map(|p| json!({"id": p.id, "label": p.label, "category": p.category})).collect::>()) +} + +fn apply(s: &mut Session, p: &Value) -> Result { + let name = strp(p, "preset").ok_or_else(|| bad("brush.preset.apply", "`preset` is required"))?; + let preset = find_preset(name).ok_or_else(|| bad("brush.preset.apply", format!("unknown brush preset `{name}` (see brush.preset.list)")))?; + set(s, preset.applied(&s.tool.brush)) +} + +fn set(s: &mut Session, brush: BrushSettings) -> Result { + s.tool.brush = brush; + s.revision = s.revision.wrapping_add(1); + Ok(brush_json(s)) +} + +#[cfg(not(target_arch = "wasm32"))] +fn save(s: &mut Session, p: &Value) -> Result { + let path = strp(p, "path").ok_or_else(|| bad("brush.preset.save", "`path` is required"))?; + let bytes = serde_json::to_vec_pretty(&s.tool.brush).map_err(|e| bad("brush.preset.save", e.to_string()))?; + std::fs::write(path, bytes).map_err(|e| bad("brush.preset.save", format!("cannot write {path}: {e}")))?; + Ok(json!({ "path": path })) +} + +#[cfg(not(target_arch = "wasm32"))] +fn load(s: &mut Session, p: &Value) -> Result { + use std::io::Read as _; + let cmd = "brush.preset.load"; + let path = strp(p, "path").ok_or_else(|| bad(cmd, "`path` is required"))?; + let mut bytes = Vec::new(); + std::fs::File::open(path).and_then(|f| f.take(MAX_BYTES + 1).read_to_end(&mut bytes)).map_err(|e| bad(cmd, format!("cannot read {path}: {e}")))?; + if bytes.len() as u64 > MAX_BYTES { + return Err(bad(cmd, format!("{path} is too large for a brush preset"))); + } + let mut from: BrushSettings = serde_json::from_slice(&bytes).map_err(|e| bad(cmd, format!("{path} is not a brush preset: {e}")))?; + // An image alpha belongs to the project that saved it. + if from.alpha_image.as_ref().is_some_and(|n| !s.images.contains_key(n)) { + from.alpha_image = None; + } + set(s, with_stroke_of(&s.tool.brush, &from)) +} + +#[cfg(target_arch = "wasm32")] +fn save(_: &mut Session, _: &Value) -> Result { + Err(bad("brush.preset.save", "file paths are not available in the browser")) +} + +#[cfg(target_arch = "wasm32")] +fn load(_: &mut Session, _: &Value) -> Result { + Err(bad("brush.preset.load", "file paths are not available in the browser")) +} diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 830f50c7..a1c83944 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -56,12 +56,15 @@ 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::effect_clipboard::specs()); v.extend(crate::tool_cmds::specs()); + v.extend(crate::brush_preset_cmds::specs()); v.extend(crate::path_tool::specs()); v.extend(crate::view_cmds::specs()); v.extend(crate::camera_cmds::specs()); v.extend(crate::quick_mask::specs()); v.extend(crate::set_cmds::specs()); + v.extend(crate::meshmap_cmds::specs()); v.extend(crate::uv_tile_cmds::specs()); v.extend(crate::template_cmds::specs()); v.extend(crate::project_cmds::specs()); @@ -74,6 +77,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(crate::smart_masks::specs()); v.extend(crate::filter_lib::specs()); v.extend(crate::decal_cmds::specs()); + v.extend(crate::text_cmds::specs()); v }) } diff --git a/crates/engine/src/decal_cmds.rs b/crates/engine/src/decal_cmds.rs index 5c1c4ab0..1221a8c9 100644 --- a/crates/engine/src/decal_cmds.rs +++ b/crates/engine/src/decal_cmds.rs @@ -16,7 +16,7 @@ pub fn specs() -> Vec { "Add decal", [], None, - "{image: resource name, x?, y?: viewport pixels (default: the view center), viewport?: [w,h] | position?: [x,y,z], normal?: [x,y,z], size?: height | [w,h] (world units; default a quarter of the mesh), rotation?: degrees, depth?, name?} — a fill layer projecting the image from a frame placed on the surface", + "{image: resource name, x?, y?: viewport pixels (default: the view center), viewport?: [w,h] | position?: [x,y,z], normal?: [x,y,z], up?: [x,y,z] (the image's up; default the view's up, or the view direction when that is along the normal), size?: height | [w,h] (world units; default a quarter of the mesh), rotation?: degrees, depth?, name?} — a fill layer projecting the image from a frame placed on the surface; seen from the front, the image reads the right way round", always, add ), @@ -25,7 +25,7 @@ pub fn specs() -> Vec { "Edit decal", [], None, - "{layer?, x?, y?, viewport? | position?, normal? (re-place it), size?: height | [w,h], rotation?: degrees, offset?: [right, up] (world units from where it was placed), depth?, image?, merge?: true continues the previous Edit decal undo step (drags)}", + "{layer?, x?, y?, viewport? | position?, normal? (re-place it), up?: [x,y,z], size?: height | [w,h], rotation?: degrees, offset?: [right, up] (world units from where it was placed), depth?, image?, merge?: true continues the previous Edit decal undo step (drags)}", has_layer, set ), @@ -81,9 +81,16 @@ fn size_param(p: &Value, aspect: f32, diag: f32) -> Option<[f32; 2]> { size.iter().all(|x| x.is_finite()).then(|| size.map(|x| x.clamp(diag * 1e-4, diag * 10.0))) } -/// The camera's up direction (decals are placed upright on screen). -fn screen_up(s: &Session) -> Vec3 { - s.camera.view().inverse().transform_vector3(Vec3::Y) +/// The decal's up direction: `up` when given, else the camera's (decals are placed upright on +/// screen), or where the camera looks when that is along `normal` (a top face seen from the +/// front: its far edge is up, as on a table). +fn decal_up(s: &Session, cmd: &str, p: &Value, normal: Vec3) -> Result { + if p.get("up").is_some() { + return vec3(p, "up").filter(|u| u.cross(normal).length_squared() > 1e-8).ok_or_else(|| bad(cmd, "`up` must be [x, y, z], not along the normal")); + } + let to_world = s.camera.view().inverse(); + let up = to_world.transform_vector3(Vec3::Y); + Ok(if up.normalize_or_zero().cross(normal).length_squared() > 1e-4 { up } else { to_world.transform_vector3(Vec3::NEG_Z) }) } fn add(s: &mut Session, p: &Value) -> Result { @@ -97,7 +104,7 @@ fn add(s: &mut Session, p: &Value) -> Result { let decal = Decal { center: center.to_array(), normal: normal.to_array(), - up: screen_up(s).to_array(), + up: decal_up(s, cmd, p, normal)?.to_array(), size, rotation: f32p(p, "rotation").unwrap_or(0.0).rem_euclid(360.0), offset: [0.0; 2], @@ -132,6 +139,9 @@ fn set(s: &mut Session, p: &Value) -> Result { if let Some((center, normal)) = placement(s, cmd, p, true)? { (d.center, d.normal, d.offset) = (center.to_array(), normal.to_array(), [0.0; 2]); } + if p.get("up").is_some() { + d.up = decal_up(s, cmd, p, Vec3::from(d.normal))?.to_array(); + } if let Some(size) = size_param(p, d.size[0] / d.size[1].max(1e-6), diag) { d.size = size; } diff --git a/crates/engine/src/effect_clipboard.rs b/crates/engine/src/effect_clipboard.rs new file mode 100644 index 00000000..8132c9ca --- /dev/null +++ b/crates/engine/src/effect_clipboard.rs @@ -0,0 +1,124 @@ +//! Copy and paste effects between layers, masks and texture sets. The clipboard is the layer +//! clipboard: it holds a layer or an effect. + +use serde_json::{Value, json}; +use texturecraft_core::{EffectKind, LayerId, Mask, MaskBackground, Source}; + +use crate::commands::{CommandSpec, bad, has_layer, layer_param, strp}; +use crate::layer_ops::{empty_texel, fit}; +use crate::mask_cmds::{anchor_source, content_target, effect_id}; +use crate::session::StackTarget; +use crate::{EngineError, Result, Session, cmd}; + +pub fn specs() -> Vec { + vec![ + cmd!("effect.copy", "Copy effect", [], None, "{effect?: the selected effect}", has_layer, copy), + cmd!("effect.cut", "Cut effect", [], None, "{effect?: the selected effect}", has_layer, cut), + cmd!( + "effect.paste", + "Paste effect", + [], + None, + "{layer?, target?: mask|content (default: the selection's stack)} → {effect} — above the selected effect, or on top of the stack", + can_paste, + paste + ), + ] +} + +/// The copied effect, if the clipboard holds one. +fn clipboard_effect(s: &Session) -> Option { + s.clipboard.as_ref().and_then(|(doc, id)| doc.project.effect(*id).map(|_| *id)) +} + +fn can_paste(s: &Session) -> std::result::Result<(), String> { + match clipboard_effect(s) { + Some(_) if s.selected_layer().is_some() => Ok(()), + Some(_) => Err("select a layer to paste the effect on".into()), + None => Err("the clipboard holds no effect".into()), + } +} + +fn copy(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "effect.copy"; + let eid = effect_id(s, p, CMD)?; + if s.doc.project.effect(eid).is_none() { + return Err(bad(CMD, format!("no effect {}", eid.0))); + } + s.clipboard = Some((s.doc.clone(), eid)); + Ok(json!({ "copied": eid.0 })) +} + +fn cut(s: &mut Session, p: &Value) -> Result { + let eid = copy(s, p)?["copied"].clone(); + crate::execute(s, "effect.remove", &json!({ "effect": eid }))?; + Ok(json!({ "cut": eid })) +} + +fn paste(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "effect.paste"; + let (src, eid) = s.clipboard.clone().ok_or_else(|| bad(CMD, "the clipboard holds no effect"))?; + let effect = src.project.effect(eid).map(|(_, e)| e.clone()).ok_or_else(|| bad(CMD, "the clipboard holds no effect"))?; + let layer = layer_param(s, CMD, p)?; + // The selected effect's stack, or the content or mask the selection targets. + let selected = match s.target { + StackTarget::Effect(x) if s.selected_layer() == Some(layer) => Some(x), + _ => None, + }; + let in_content = |s: &Session, x: LayerId| { + s.doc.project.effect(x).and_then(|(o, _)| s.doc.project.layers.get(&o)).is_some_and(|l| l.content_effects.iter().any(|e| e.id == x)) + }; + let asked = strp(p, "target").is_some(); + let content = match selected { + _ if asked => content_target(p, CMD)?, + Some(x) => in_content(s, x), + None => s.target == StackTarget::Content && s.selected_layer() == Some(layer), + }; + // Effects that fit one stack only go there, unless another was asked for. + let content = match effect.kind.content_only() { + Some(only) if only != content && asked => { + return Err(bad(CMD, format!("{} effects go on the {}", effect.kind.name(), if only { "layer content" } else { "mask" }))); + } + Some(only) => only, + None => content, + }; + // An instance's content and (unless it has its own) mask belong to its source. + let owner = if content { s.doc.project.content_layer(layer).map_or(layer, |l| l.id) } else { s.doc.project.mask_owner(layer) }; + let owner_layer = s.doc.project.layer(owner)?; + if content && owner_layer.is_group() { + return Err(EngineError::Other(format!("\"{}\" is a folder: content effects go on paint and fill layers", owner_layer.name))); + } + // A fill reading an anchor point needs one below its new layer. + if let EffectKind::Fill { source: Source::Anchor { anchor, channel }, .. } = &effect.kind { + anchor_source(s, CMD, owner, *anchor, *channel)?; + } + let (ts, _, _) = s.doc.project.locate(owner).ok_or_else(|| bad(CMD, "the layer is not in a stack"))?; + let (size, channels) = s.doc.project.texture_set(ts).map(|t| (t.size(), t.channel_list()))?; + let new = s.edit("Paste effect", |s| { + let new = s.doc.project.alloc_id(); + let l = s.doc.project.layer_mut(owner)?; + let list = if content { + &mut l.content_effects + } else { + let bg = if matches!(effect.kind, EffectKind::Generator(_) | EffectKind::Fill { .. }) { MaskBackground::Black } else { MaskBackground::White }; + &mut l.mask.get_or_insert_with(|| Mask::new(bg)).effects + }; + let at = selected.and_then(|x| list.iter().position(|e| e.id == x)).map_or(list.len(), |i| i + 1); + list.insert(at, texturecraft_core::Effect { id: new, ..effect.clone() }); + // Painted pixels come along, resampled to the set's size (a mask's paint stays a mask's). + if let Some(img) = src.pixels.masks.get(&eid).filter(|_| !content) { + s.doc.pixels.masks.insert(new, fit(img, size, &[0, 0])); + } + for c in channels.iter().copied().filter(|_| content) { + if let Some(img) = src.pixels.layer(eid, c) { + s.doc.pixels.layers.insert((new, c), fit(img, size, &empty_texel(c))); + } + } + if let Some((lts, _, _)) = s.doc.project.locate(layer) { + s.selected.insert(lts, layer); + } + s.target = StackTarget::Effect(new); + Ok(new) + })?; + Ok(json!({ "effect": new.0 })) +} diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 32ae6b49..8f808ec3 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -4,7 +4,7 @@ use serde_json::{Value, json}; #[cfg(not(target_arch = "wasm32"))] use texturecraft_core::PROJECT_EXT; -use texturecraft_core::{NormalFormat, TextureSet}; +use texturecraft_core::{NormalFormat, Project, TextureSet}; use texturecraft_formats::{ExportInput, ExportOptions, ExportedFile, FileFormat, Padding, ProjectFile}; use texturecraft_geom::{Mesh, primitives}; @@ -42,7 +42,7 @@ pub fn specs() -> Vec { "Export textures", ["File"], None, - "{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|\"all\", format?: png|jpg|tga|tif|exr|..., bitDepth?, padding?: none|dilation|dilationDefault|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX}", + "{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|\"all\", format?: png|jpg|tga|tif|exr|..., bitDepth?, padding?: none|dilation|dilationDefault|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1), materialX?: bool (also write a .mtlx OpenPBR material per texture set; needs the \"OpenPBR (separate maps)\" preset)}", always, export_textures ), @@ -60,7 +60,7 @@ pub fn specs() -> Vec { "List export outputs", [], None, - "{preset?: name or preset object, ts?, format?, bitDepth?, size?} → [{ts, map, file, format, bitDepth, warnings}]", + "{preset?: name or preset object, ts?, format?, bitDepth?, size?, colorSpace?} → [{ts, map, file, format, bitDepth, warnings}]", always, plan ), @@ -79,6 +79,18 @@ fn stem_of(name: &str) -> String { std::path::Path::new(name).file_stem().and_then(|e| e.to_str()).unwrap_or("Untitled").to_string() } +/// The leaf of an imported mesh file's name (kept in [`Project::mesh_file`]). +fn leaf_of(name: &str) -> String { + std::path::Path::new(name).file_name().and_then(|e| e.to_str()).unwrap_or_default().to_string() +} + +/// Read the project's stored mesh `bytes` (extension `ext`) under the name it was imported +/// with, so its unnamed parts keep their names (and the geometry masks that use them). +fn read_stored_mesh(project: &Project, ext: &str, bytes: &[u8]) -> Result { + let stem = std::path::Path::new(&project.mesh_file).file_stem().and_then(|s| s.to_str()).filter(|s| !s.is_empty()).unwrap_or("mesh"); + texturecraft_formats::import_mesh_bytes(&format!("{stem}.{ext}"), bytes).map_err(fe) +} + impl Session { /// The working mesh as Wavefront OBJ (with its own UVs, UDIM tiles included). pub fn mesh_obj_bytes(&self) -> Vec { @@ -122,6 +134,7 @@ impl Session { let imported = texturecraft_formats::import_mesh_bytes(file_name, bytes).map_err(fe)?; let ext = ext_of(file_name); let mut s = Session::new_project_tiled(name, imported.mesh, &format!("mesh.{ext}"), Some((ext, bytes.to_vec())), resolution, uv_tiles)?; + s.doc.project.mesh_file = leaf_of(file_name); s.doc.project.cameras = imported.cameras; s.log.extend(imported.report.warnings.iter().cloned()); s.log.push(format!( @@ -143,7 +156,7 @@ impl Session { pub fn from_project_file(pf: ProjectFile) -> Result { let mesh = match (&pf.mesh, pf.project.mesh.strip_prefix("builtin:")) { (_, Some(id)) => primitives::builtin(id).ok_or_else(|| EngineError::Other(format!("unknown built-in mesh `{id}`")))?, - (Some((ext, bytes)), None) => texturecraft_formats::import_mesh_bytes(&format!("mesh.{ext}"), bytes).map_err(fe)?.mesh, + (Some((ext, bytes)), None) => read_stored_mesh(&pf.project, ext, bytes)?.mesh, (None, None) => return Err(EngineError::Other("the project has no mesh".into())), }; check_materials(&pf.project, &mesh)?; @@ -256,6 +269,12 @@ pub fn export_options(s: &Session, p: &Value, cmd: &str) -> Result return Err(bad(cmd, format!("unknown normal format `{other}`"))), None => None, }; + if let Some(name) = strp(p, "colorSpace") { + o.color_space = Some( + texturecraft_texel::ColorSpace::from_name(name) + .ok_or_else(|| bad(cmd, format!("unknown colorSpace `{name}` (sRGB, Linear Rec.709, ACEScg or ACES2065-1)")))?, + ); + } Ok(o) } @@ -384,14 +403,14 @@ impl Session { /// With `preserve_strokes`, painted pixels follow the surface where the UVs changed. Replies /// like `file.reimportMesh`: `{preserved?}`. pub fn reimport_mesh(&mut self, file: Option, preserve_strokes: bool) -> Result { - let (mesh, source, warnings) = match file { + let (mesh, source, warnings, mesh_file) = match file { Some(f) => { let m = texturecraft_formats::import_mesh_bytes(&f.name, &f.bytes).map_err(fe)?.mesh; - (m, Some((ext_of(&f.name), f.bytes)), f.warnings) + (m, Some((ext_of(&f.name), f.bytes)), f.warnings, leaf_of(&f.name)) } None => match &self.mesh_source { Some((ext, bytes)) => { - (texturecraft_formats::import_mesh_bytes(&format!("mesh.{ext}"), bytes).map_err(fe)?.mesh, self.mesh_source.clone(), Vec::new()) + (read_stored_mesh(&self.doc.project, ext, bytes)?.mesh, self.mesh_source.clone(), Vec::new(), self.doc.project.mesh_file.clone()) } None => return Err(bad("file.reimportMesh", "built-in meshes can't be reimported; give `path`")), }, @@ -400,6 +419,7 @@ impl Session { let mut doc = self.doc.clone(); if let Some((ext, _)) = &source { doc.project.mesh = format!("mesh.{ext}"); + doc.project.mesh_file = mesh_file; } let mut next = Session::new(doc, mesh, source)?; next.log.extend(warnings); @@ -417,12 +437,66 @@ fn export_textures(s: &mut Session, p: &Value) -> Result { let sets = sets_param(s, p, "file.exportTextures")?; std::fs::create_dir_all(&dir).map_err(|e| bad("file.exportTextures", format!("cannot create {dir}: {e}")))?; let files = s.export_files(&sets, &opts)?; - let warnings: Vec = files.iter().flat_map(|f| f.warnings.iter().cloned()).collect(); - let written = texturecraft_formats::write_files(&files, std::path::Path::new(&dir)).map_err(fe)?; + let mut warnings: Vec = files.iter().flat_map(|f| f.warnings.iter().cloned()).collect(); + let mut written = texturecraft_formats::write_files(&files, std::path::Path::new(&dir)).map_err(fe)?; + if p.get("materialX").and_then(Value::as_bool).unwrap_or(false) { + written.extend(write_materialx(s, &sets, &opts, std::path::Path::new(&dir), &mut warnings)?); + } s.log.push(format!("Exported {} textures to {dir}", written.len())); Ok(json!({ "files": written.iter().map(|p| p.display().to_string()).collect::>(), "warnings": warnings })) } +/// One `_.mtlx` per texture set, next to the textures `opts` just wrote: the +/// OpenPBR inputs those textures feed (see `texturecraft_formats::materialx`). UDIM sets name +/// their files with the `` token. Sets with no recognised map, or whose name gives the +/// same file name as an earlier set's, are skipped with a warning. +#[cfg(not(target_arch = "wasm32"))] +fn write_materialx(s: &Session, sets: &[usize], opts: &ExportOptions, dir: &std::path::Path, warnings: &mut Vec) -> Result> { + use texturecraft_formats::materialx::{self, Texture}; + let mesh_name = stem_of(s.doc.project.mesh.trim_start_matches("builtin:")); + if opts.normal_format == Some(NormalFormat::DirectX) { + warnings.push("MaterialX: the normalmap node reads OpenGL (+Y) normals; this export wrote DirectX normals, so flip the green channel".into()); + } + if opts.color_space == Some(texturecraft_texel::ColorSpace::Aces2065) { + warnings.push("MaterialX: version 1.39 has no ACES2065-1 colour space; the colour maps are tagged lin_ap0_scene, its name in later versions, which older readers may not know".into()); + } + let mut out = Vec::new(); + let mut stems = std::collections::HashSet::new(); + for &ts in sets { + let set = s.doc.project.texture_set(ts).map_err(|e| EngineError::Other(e.to_string()))?; + let mut textures: Vec = Vec::new(); + for f in texturecraft_formats::list_outputs(&s.doc.project, ts, &mesh_name, opts).map_err(fe)? { + let Some(input) = opts.preset.maps.get(f.map).and_then(|m| materialx::input_of_template(&m.file)) else { continue }; + // The first tile stands for all of them: 1001 -> . + let file = match f.tile { + Some(t) => f.name.replacen(&format!(".{t}."), "..", 1), + None => f.name.clone(), + }; + let colorspace = materialx::colorspace_name(opts.space_for(f.format)); + if !textures.iter().any(|t| t.input == input) { + textures.push(Texture { input: input.to_owned(), file, colorspace }); + } + } + if textures.is_empty() { + warnings.push(format!("MaterialX: texture set \"{}\" has no OpenPBR maps; use the \"OpenPBR (separate maps)\" preset", set.name)); + continue; + } + let stem = texturecraft_formats::export::sanitize_file_stem(&format!("{mesh_name}_{}", set.name)); + // Case-insensitive: Windows and macOS file systems are. + if !stems.insert(stem.to_ascii_lowercase()) { + warnings.push(format!( + "MaterialX: texture set \"{}\" exports as \"{stem}\" like an earlier set, so its .mtlx was not written; rename one of them", + set.name + )); + continue; + } + let path = dir.join(format!("{stem}.mtlx")); + texturecraft_formats::write_atomic(&path, materialx::write(&format!("{mesh_name}_{}", set.name), &textures, None).as_bytes()).map_err(fe)?; + out.push(path); + } + Ok(out) +} + #[cfg(not(target_arch = "wasm32"))] fn export_mesh(s: &mut Session, p: &Value) -> Result { let path = native::path_param(p, "path", "file.exportMesh")?; @@ -555,4 +629,49 @@ mod tests { } let _ = std::fs::remove_dir_all(&dir); } + + #[test] + fn unnamed_parts_keep_their_names_and_masks_through_save_and_reopen() { + // A GLB quad whose mesh and node have no name: its one part is named after the file. + let mut bin: Vec = [-1.0f32, -1.0, 0.0, 1.0, -1.0, 0.0, 1.0, 1.0, 0.0, -1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0] + .iter() + .flat_map(|f| f.to_le_bytes()) + .chain([0u16, 1, 2, 0, 2, 3].iter().flat_map(|i| i.to_le_bytes())) + .collect(); + bin.resize(92, 0); + let mut gltf = json!({ + "asset": {"version": "2.0"}, "buffers": [{"byteLength": 92}], + "bufferViews": [{"buffer": 0, "byteOffset": 0, "byteLength": 48}, {"buffer": 0, "byteOffset": 48, "byteLength": 32}, {"buffer": 0, "byteOffset": 80, "byteLength": 12}], + "accessors": [{"bufferView": 0, "componentType": 5126, "count": 4, "type": "VEC3", "min": [-1, -1, 0], "max": [1, 1, 0]}, + {"bufferView": 1, "componentType": 5126, "count": 4, "type": "VEC2"}, {"bufferView": 2, "componentType": 5123, "count": 6, "type": "SCALAR"}], + "meshes": [{"primitives": [{"attributes": {"POSITION": 0, "TEXCOORD_0": 1}, "indices": 2}]}], + "nodes": [{"mesh": 0}], "scenes": [{"nodes": [0]}], "scene": 0 + }) + .to_string() + .into_bytes(); + gltf.resize(gltf.len().div_ceil(4) * 4, b' '); + let mut glb = b"glTF".to_vec(); + glb.extend(2u32.to_le_bytes()); + glb.extend(((12 + 8 + gltf.len() + 8 + bin.len()) as u32).to_le_bytes()); + glb.extend((gltf.len() as u32).to_le_bytes()); + glb.extend(b"JSON"); + glb.extend(gltf); + glb.extend((bin.len() as u32).to_le_bytes()); + glb.extend(b"BIN\0"); + glb.extend(bin); + let mut s = Session::from_mesh_bytes("dir/quad.glb", &glb, 128, "quad").unwrap(); + let parts = |s: &mut Session| crate::execute(s, "textureSet.parts", &Value::Null).unwrap(); + assert_eq!(parts(&mut s), json!(["quad"])); + crate::execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.0, 0.0]})).unwrap(); + crate::execute(&mut s, "layer.set", &json!({"geometryMask": ["quad"]})).unwrap(); + let mut back = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); + assert_eq!(parts(&mut back), json!(["quad"]), "the reopened mesh names its part as the import did"); + crate::execute(&mut back, "file.reimportMesh", &Value::Null).unwrap(); + assert_eq!(parts(&mut back), json!(["quad"]), "and so does a reimport of the stored mesh"); + // Projects saved before the file name was kept read the mesh as before. + let mut old = back.project_file(); + old.project.mesh_file.clear(); + let mut old = Session::from_project_bytes(&texturecraft_formats::save_project_bytes(&old).unwrap()).unwrap(); + assert_eq!(parts(&mut old), json!(["mesh"])); + } } diff --git a/crates/engine/src/filter_lib.rs b/crates/engine/src/filter_lib.rs index 327655f4..f3168c9d 100644 --- a/crates/engine/src/filter_lib.rs +++ b/crates/engine/src/filter_lib.rs @@ -31,12 +31,16 @@ pub const FILTERS: &[FilterDef] = &[ def("gradientMap", "Gradient Map", "Adjustments", true), def("posterize", "Posterize", "Adjustments", true), def("clamp", "Clamp", "Adjustments", true), + def("histogramScan", "Histogram Scan", "Adjustments", true), + def("histogramRange", "Histogram Range", "Adjustments", true), + def("histogramShift", "Histogram Shift", "Adjustments", true), def("invert", "Invert", "Adjustments", true), def("threshold", "Threshold", "Adjustments", true), def("grayscale", "Grayscale", "Adjustments", false), def("edgeDetect", "Edge Detect", "Adjustments", true), def("normalInvert", "Normal Invert", "Adjustments", false), def("bakedLighting", "Baked Lighting", "Adjustments", false), + def("replaceColor", "Replace Color", "Adjustments", false), def("blur", "Blur", "Blur and sharpen", true), def("blurDirectional", "Blur Directional", "Blur and sharpen", true), def("slopeBlur", "Slope Blur", "Blur and sharpen", true), @@ -95,6 +99,9 @@ pub fn build(id: &str, p: &Value) -> Result { "gradientMap" => Filter::GradientMap { colors: vec![[0.02, 0.02, 0.04], [0.45, 0.16, 0.05], [1.0, 0.85, 0.55]] }, "posterize" => Filter::Posterize { levels: 4.0 }, "clamp" => Filter::Clamp { min: 0.2, max: 0.8 }, + "histogramScan" => Filter::HistogramScan { position: 0.5, contrast: 0.5 }, + "histogramRange" => Filter::HistogramRange { range: 0.5, position: 0.5 }, + "histogramShift" => Filter::HistogramShift { offset: 0.25 }, "warp" => Filter::Warp { intensity: 16.0, scale: 4.0, seed: 1 }, "blurDirectional" => Filter::DirectionalBlur { radius: 16.0, angle: 0.0 }, "slopeBlur" => Filter::SlopeBlur { radius: 16.0, scale: 4.0, seed: 1 }, @@ -106,6 +113,7 @@ pub fn build(id: &str, p: &Value) -> Result { "bevel" => Filter::Bevel { width: 16.0 }, "mosaic" => Filter::Mosaic { size: 32.0 }, "glow" => Filter::Glow { radius: 16.0, amount: 1.0 }, + "replaceColor" => Filter::ReplaceColor { from: [0.5, 0.05, 0.05], to: [0.05, 0.15, 0.5], tolerance: 0.2, softness: 0.15 }, "bakedLighting" => Filter::BakedLighting { azimuth: 45.0, elevation: 45.0, light: 0.8, ambient: 0.4, occlusion: 1.0 }, "levels" => { let mut l = Levels::default(); @@ -149,6 +157,9 @@ pub fn scalar_params(f: &Filter) -> Vec<(&'static str, &'static str, f32, f32, f } Filter::Posterize { levels } => vec![("levels", "Steps", *levels, 2.0, 64.0)], Filter::Clamp { min, max } => vec![("min", "Minimum", *min, 0.0, 1.0), ("max", "Maximum", *max, 0.0, 1.0)], + Filter::HistogramScan { position, contrast } => vec![("position", "Position", *position, 0.0, 1.0), ("contrast", "Contrast", *contrast, 0.0, 1.0)], + Filter::HistogramRange { range, position } => vec![("range", "Range", *range, 0.0, 1.0), ("position", "Position", *position, 0.0, 1.0)], + Filter::HistogramShift { offset } => vec![("offset", "Offset", *offset, -1.0, 1.0)], Filter::Warp { intensity, scale, seed } => { vec![ ("intensity", "Intensity (texels at 2K)", *intensity, 0.0, 128.0), @@ -188,6 +199,9 @@ pub fn scalar_params(f: &Filter) -> Vec<(&'static str, &'static str, f32, f32, f ("ambient", "Ambient", *ambient, 0.0, 2.0), ("occlusion", "Ambient occlusion", *occlusion, 0.0, 1.0), ], + Filter::ReplaceColor { tolerance, softness, .. } => { + vec![("tolerance", "Tolerance", *tolerance, 0.0, 1.0), ("softness", "Softness", *softness, 0.0, 1.0)] + } Filter::Invert | Filter::ColorBalance { .. } | Filter::GradientMap { .. } | Filter::Grayscale | Filter::NormalInvert => Vec::new(), } } @@ -245,6 +259,15 @@ pub(crate) fn apply(p: &Value, f: &mut Filter, cmd: &str) -> Result<()> { set(min, "min", 0.0, 1.0); set(max, "max", 0.0, 1.0); } + Filter::HistogramScan { position, contrast } => { + set(position, "position", 0.0, 1.0); + set(contrast, "contrast", 0.0, 1.0); + } + Filter::HistogramRange { range, position } => { + set(range, "range", 0.0, 1.0); + set(position, "position", 0.0, 1.0); + } + Filter::HistogramShift { offset } => set(offset, "offset", -1.0, 1.0), Filter::Warp { intensity, scale, seed: s } => { set(intensity, "intensity", 0.0, 256.0); set(scale, "scale", 0.01, 1000.0); @@ -266,6 +289,16 @@ pub(crate) fn apply(p: &Value, f: &mut Filter, cmd: &str) -> Result<()> { set(radius, "radius", 0.0, 256.0); set(amount, "amount", 0.0, 10.0); } + Filter::ReplaceColor { from, to, tolerance, softness } => { + for (key, slot) in [("from", from), ("to", to)] { + if p.get(key).is_some() { + let v = color_param(p, key).ok_or_else(|| bad(cmd, format!("`{key}` must be a color ([r, g, b] linear or \"#rrggbb\")")))?; + *slot = v.map(|x| x.clamp(0.0, 1.0)); + } + } + set(tolerance, "tolerance", 0.0, 1.0); + set(softness, "softness", 0.0, 1.0); + } Filter::BakedLighting { azimuth, elevation, light, ambient, occlusion } => { if let Some(v) = f32p(p, "azimuth") { *azimuth = v.rem_euclid(360.0); diff --git a/crates/engine/src/instance_cmds.rs b/crates/engine/src/instance_cmds.rs index 255a69c3..a9307883 100644 --- a/crates/engine/src/instance_cmds.rs +++ b/crates/engine/src/instance_cmds.rs @@ -69,6 +69,7 @@ fn instance(s: &mut Session, p: &Value) -> Result { fn can_paste_instance(s: &Session) -> std::result::Result<(), String> { match &s.clipboard { Some((_, id)) if s.doc.project.locate(*id).is_some() => Ok(()), + Some((doc, id)) if doc.project.effect(*id).is_some() => Err("the clipboard holds an effect (effect.paste)".into()), Some(_) => Err("the copied layer is no longer in the project (paste it instead)".into()), None => Err("the layer clipboard is empty".into()), } diff --git a/crates/engine/src/layer_cmds.rs b/crates/engine/src/layer_cmds.rs index e7831f12..e7575baf 100644 --- a/crates/engine/src/layer_cmds.rs +++ b/crates/engine/src/layer_cmds.rs @@ -25,7 +25,7 @@ pub fn specs() -> Vec { "Set fill source", [], None, - "{layer? | effect?: content fill effect id, channel, color?|value?|procedural?: kind, scale?, seed?, contrast?, balance?, invert?, low?, high?|image?|anchor?: anchor effect id, anchorChannel?, enabled?}", + "{layer? | effect?: content fill effect id, channel, color?|value?|procedural?: kind, scale?, seed?, contrast?, balance?, invert?, low?, high?|image?|anchor?: anchor effect id, anchorChannel?, enabled?, solo?: true (this channel on, every other one off)}", has_layer, fill_set ), @@ -303,7 +303,9 @@ fn fill_mut(s: &mut Session, target: FillTarget) -> Result<&mut Fill> { fn fill_set(s: &mut Session, p: &Value) -> Result { let target = fill_target(s, p, "layer.fill.set")?; let ch = channel_param("layer.fill.set", p, "channel")?.ok_or_else(|| bad("layer.fill.set", "`channel` is required"))?; - let enabled = boolp(p, "enabled"); + // `solo`: this channel on, every other one off. + let solo = boolp(p, "solo") == Some(true); + let enabled = if solo { Some(true) } else { boolp(p, "enabled") }; let source = if let Some(kind) = strp(p, "procedural") { let kind = ProceduralKind::parse(kind).ok_or_else(|| bad("layer.fill.set", format!("unknown procedural `{kind}`")))?; let mut pr = Procedural::new(kind); @@ -336,7 +338,7 @@ fn fill_set(s: &mut Session, p: &Value) -> Result { } else if enabled.is_some() { None } else { - return Err(bad("layer.fill.set", "give `color`, `value`, `procedural`, `image`, `anchor` or `enabled`")); + return Err(bad("layer.fill.set", "give `color`, `value`, `procedural`, `image`, `anchor`, `enabled` or `solo`")); }; s.edit("Set fill", |s| { let f = fill_mut(s, target)?; @@ -348,6 +350,9 @@ fn fill_set(s: &mut Session, p: &Value) -> Result { FillTarget::Effect(_) => { let src = source.unwrap_or_else(|| f.source(ch)); f.sources.insert(ch, src); + if solo { + f.sources.retain(|c, _| *c == ch); + } } FillTarget::Layer(id) => { if let Some(src) = source { @@ -359,6 +364,9 @@ fn fill_set(s: &mut Session, p: &Value) -> Result { } else { l.channels.entry(ch).or_default(); } + if solo { + l.channels.retain(|c, _| *c == ch); + } } } Ok(()) diff --git a/crates/engine/src/layer_ops.rs b/crates/engine/src/layer_ops.rs index 8291409e..9493009b 100644 --- a/crates/engine/src/layer_ops.rs +++ b/crates/engine/src/layer_ops.rs @@ -36,7 +36,11 @@ pub fn specs() -> Vec { } fn can_paste(s: &Session) -> std::result::Result<(), String> { - if s.clipboard.is_some() { Ok(()) } else { Err("the layer clipboard is empty".into()) } + match &s.clipboard { + Some((doc, id)) if doc.project.layers.contains_key(id) => Ok(()), + Some(_) => Err("the clipboard holds an effect (effect.paste)".into()), + None => Err("the layer clipboard is empty".into()), + } } /// Encoded "nothing painted" texel for a channel image (value 0, coverage 0). @@ -47,7 +51,7 @@ pub(crate) fn empty_texel(c: Channel) -> Vec { v } -fn fit(img: &TileImage, (w, h): (u32, u32), empty: &[u16]) -> TileImage { +pub(crate) fn fit(img: &TileImage, (w, h): (u32, u32), empty: &[u16]) -> TileImage { if (img.width(), img.height()) == (w, h) { img.clone() } else { img.resampled(w, h, empty) } } @@ -194,21 +198,8 @@ impl Session { /// Layer `id` of texture set `ts` alone (content times mask) as premultiplied tiles per /// channel over the set's covered tiles. None for folders or a set not ready. pub(crate) fn flatten(&self, ts: usize, id: LayerId) -> Option> { - let cache = self.caches.get(ts)?; - let tiles: Vec<(u32, u32)> = cache.covered_tiles.iter().copied().collect(); - let empty = Default::default(); - let inputs = texturecraft_compose::Inputs { - project: &self.doc.project, - ts, - mesh: &self.mesh, - gbuf: &cache.gbuf, - pixels: &self.doc.pixels, - baked: self.doc.baked.get(&ts).unwrap_or(&empty), - preview: None, - images: &self.images, - bounds: self.mesh.bounds(), - }; - texturecraft_compose::flatten_layer(&inputs, id, &tiles) + let tiles: Vec<(u32, u32)> = self.caches.get(ts)?.covered_tiles.iter().copied().collect(); + self.with_inputs(ts, |inp| texturecraft_compose::flatten_layer(inp, id, &tiles)) } } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 434eaaaf..b3f32688 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -9,9 +9,11 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] pub mod bake_cmds; +pub mod brush_preset_cmds; pub mod camera_cmds; pub mod commands; pub mod decal_cmds; +pub mod effect_clipboard; pub mod file_cmds; pub mod filter_lib; pub mod inspect; @@ -22,6 +24,7 @@ pub mod link_cmds; pub mod mask_cmds; pub mod material_lib; pub mod materials; +pub mod meshmap_cmds; pub mod painting; pub mod path_tool; // Mesh reimport reads files: native only. @@ -36,6 +39,7 @@ pub mod session; pub mod set_cmds; pub mod smart_masks; pub mod template_cmds; +pub mod text_cmds; pub mod tool_cmds; pub mod uv_tile_cmds; pub mod view_cmds; diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 9122b158..784755c2 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -3,10 +3,10 @@ use serde_json::{Value, json}; use texturecraft_core::{ BlendMode, Channel, CompareOp, Effect, EffectKind, Filter, Generator, GeneratorKind, LayerId, Levels, Mask, MaskBackground, Procedural, ProceduralKind, - Source, + Project, Source, }; -use crate::commands::{CommandSpec, bad, blend_param, boolp, channel_param, color_param, f32p, has_layer, layer_param, strp, u64p}; +use crate::commands::{CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, f32p, has_layer, layer_param, strp, u64p}; use crate::layer_cmds::projection_from; use crate::session::StackTarget; use crate::{EngineError, Result, Session, cmd}; @@ -67,7 +67,7 @@ pub fn specs() -> Vec { "Add filter", ["Layers", "Effects"], None, - "{layer?, target?: mask|content, name?, filter?: id from filter.list (invert, threshold, blur, sharpen, hsl, levels, contrastLuminosity, colorBalance, gradientMap, posterize, clamp, warp, blurDirectional, slopeBlur, matFinishGrind|Raw|Sanded|Hammered), level?, radius?, amount?, hue?: turns -1..1, saturation?, lightness?, contrast?, luminosity?, shadows?|midtones?|highlights?: [r,g,b] -1..1, colors?: [[r,g,b]|\"#rrggbb\", ...], levels?, min?, max?, intensity?, scale?, seed?, angle?} — material finishes go on the content", + "{layer?, target?: mask|content, name?, filter?: id from filter.list (invert, threshold, blur, sharpen, hsl, levels, contrastLuminosity, colorBalance, gradientMap, posterize, clamp, histogramScan|Range|Shift, warp, blurDirectional, slopeBlur, matFinishGrind|Raw|Sanded|Hammered), level?, radius?, amount?, hue?: turns -1..1, saturation?, lightness?, contrast?, luminosity?, shadows?|midtones?|highlights?: [r,g,b] -1..1, colors?: [[r,g,b]|\"#rrggbb\", ...], levels?, min?, max?, position?, range?, offset?, intensity?, scale?, seed?, angle?} — material finishes go on the content", has_layer, add_filter ), @@ -98,7 +98,26 @@ pub fn specs() -> Vec { has_layer, set ), - cmd!("effect.remove", "Remove effect", [], None, "{effect}", has_layer, remove_effect), + cmd!("effect.remove", "Remove effect", [], None, "{effect?: the selected effect}", has_layer, remove_effect), + cmd!( + "effect.duplicate", + "Duplicate effect", + [], + None, + "{effect?: the selected effect} → {effect} (the copy, just above it, pixels included)", + has_layer, + duplicate_effect + ), + cmd!("effect.move", "Move effect", [], None, "{effect, index: position in its stack, 0 = bottom (applied first)}", has_layer, move_effect), + cmd!( + "effect.histogram", + "Effect input histogram", + [], + None, + "{effect, channel?: for content effects (default: the layer's first channel), bins?: 2..256 (64)} → {target: mask|content, channel?, bins: [count per bucket over 0..1]}", + always, + histogram + ), ] } @@ -200,7 +219,7 @@ fn remove(s: &mut Session, p: &Value) -> Result { /// Whether `effect.add.*` targets the layer content (`target: "content"`) or its mask (the /// default). -fn content_target(p: &Value, cmd: &str) -> Result { +pub(crate) fn content_target(p: &Value, cmd: &str) -> Result { match strp(p, "target") { None | Some("mask") => Ok(false), Some("content") => Ok(true), @@ -369,12 +388,33 @@ fn add_compare(s: &mut Session, p: &Value) -> Result { push_effect(s, p, kind, BlendMode::Normal) } -fn effect_id(p: &Value, cmd: &str) -> Result { - u64p(p, "effect").map(LayerId).ok_or_else(|| bad(cmd, "`effect` id is required")) +/// The `effect` param, or the selected effect. +pub(crate) fn effect_id(s: &Session, p: &Value, cmd: &str) -> Result { + match (u64p(p, "effect"), s.target) { + (Some(e), _) => Ok(LayerId(e)), + (None, StackTarget::Effect(e)) => Ok(e), + (None, _) => Err(bad(cmd, "`effect` is required (no effect is selected)")), + } +} + +/// The distribution of the values entering an effect (what a levels effect remaps). +fn histogram(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "effect.histogram"; + let eid = effect_id(s, p, CMD)?; + let (owner, _) = s.doc.project.effect(eid).ok_or_else(|| bad(CMD, format!("no effect {}", eid.0)))?; + let l = s.doc.project.layer(owner)?; + let content = l.content_effects.iter().any(|e| e.id == eid); + let channel = match channel_param(CMD, p, "channel")? { + Some(c) => c, + None => l.channels.keys().next().copied().unwrap_or(Channel::BaseColor), + }; + let bins = u64p(p, "bins").unwrap_or(64).clamp(2, 256) as usize; + let counts = s.effect_histogram(eid, channel, bins).ok_or_else(|| bad(CMD, "the texture set is not ready"))?; + Ok(if content { json!({"target": "content", "channel": channel.id(), "bins": counts}) } else { json!({"target": "mask", "bins": counts}) }) } fn set(s: &mut Session, p: &Value) -> Result { - let eid = effect_id(p, "effect.set")?; + let eid = effect_id(s, p, "effect.set")?; let blend = blend_param("effect.set", p, "blend")?; // A fill reading an anchor: `anchor` picks the anchor point, `anchorChannel` alone // re-targets the current one. @@ -431,8 +471,60 @@ fn set(s: &mut Session, p: &Value) -> Result { Ok(Value::Null) } +/// The stack (a mask's or a layer's content effects) holding effect `eid`, and its position there. +fn stack_of(project: &mut Project, eid: LayerId) -> Option<(&mut Vec, usize)> { + project.layers.values_mut().find_map(|l| { + l.mask.iter_mut().map(|m| &mut m.effects).chain(std::iter::once(&mut l.content_effects)).find_map(|list| { + let i = list.iter().position(|e| e.id == eid)?; + Some((list, i)) + }) + }) +} + +fn duplicate_effect(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "effect.duplicate"; + let eid = effect_id(s, p, CMD)?; + let new = s.edit("Duplicate effect", |s| { + let new = s.doc.project.alloc_id(); + let (list, i) = stack_of(&mut s.doc.project, eid).ok_or_else(|| bad(CMD, format!("no effect {}", eid.0)))?; + let mut e = list.get(i).cloned().ok_or_else(|| bad(CMD, format!("no effect {}", eid.0)))?; + e.id = new; + e.name = format!("{} copy", e.name); + list.insert(i + 1, e); + // Painted effects keep their pixels (copy-on-write tiles: cheap). + let px = &mut s.doc.pixels; + if let Some(img) = px.masks.get(&eid).cloned() { + px.masks.insert(new, img); + } + for c in Channel::ALL { + if let Some(img) = px.layer(eid, c).cloned() { + px.layers.insert((new, c), img); + } + } + Ok(new) + })?; + if s.target == StackTarget::Effect(eid) { + s.target = StackTarget::Effect(new); + } + Ok(json!({ "effect": new.0 })) +} + +fn move_effect(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "effect.move"; + let eid = effect_id(s, p, CMD)?; + let index = u64p(p, "index").ok_or_else(|| bad(CMD, "`index` is required"))?; + s.edit("Move effect", |s| { + let (list, i) = stack_of(&mut s.doc.project, eid).ok_or_else(|| bad(CMD, format!("no effect {}", eid.0)))?; + let e = list.remove(i); + let to = usize::try_from(index).unwrap_or(usize::MAX).min(list.len()); + list.insert(to, e); + Ok(()) + })?; + Ok(Value::Null) +} + fn remove_effect(s: &mut Session, p: &Value) -> Result { - let eid = effect_id(p, "effect.remove")?; + let eid = effect_id(s, p, "effect.remove")?; s.edit("Remove effect", |s| { let content = match s.doc.project.effect(eid) { Some((owner, _)) => s.doc.project.layer(owner)?.content_effects.iter().any(|e| e.id == eid), diff --git a/crates/engine/src/materials.rs b/crates/engine/src/materials.rs index 11b63aa3..12479401 100644 --- a/crates/engine/src/materials.rs +++ b/crates/engine/src/materials.rs @@ -65,6 +65,9 @@ pub const MATERIALS: &[SmartMaterial] = &[ m("chrome", "Chrome", METAL, [0.55, 0.556, 0.554], 1.0, 0.05), m("titanium", "Titanium", METAL, [0.542, 0.497, 0.449], 1.0, 0.32), m("nickel", "Nickel", METAL, [0.66, 0.609, 0.526], 1.0, 0.25), + m("platinum", "Platinum", METAL, [0.673, 0.637, 0.585], 1.0, 0.2), + m("zinc", "Zinc", METAL, [0.664, 0.824, 0.85], 1.0, 0.38), + m("cobalt", "Cobalt", METAL, [0.662, 0.655, 0.634], 1.0, 0.3), m("galvanized", "Steel Galvanized", METAL, [0.69, 0.71, 0.72], 1.0, 0.4), m("rust", "Rust", METAL, [0.3, 0.1, 0.03], 0.0, 0.85), // Woods. @@ -73,6 +76,7 @@ pub const MATERIALS: &[SmartMaterial] = &[ m("wood_walnut", "Walnut", WOOD, [0.12, 0.06, 0.03], 0.0, 0.5), m("wood_pine", "Pine", WOOD, [0.52, 0.33, 0.16], 0.0, 0.65), m("plywood", "Plywood", WOOD, [0.55, 0.38, 0.21], 0.0, 0.75), + m("bark", "Bark", WOOD, [0.14, 0.1, 0.07], 0.0, 0.9), m("wood_painted", "Wood Painted", WOOD, [0.61, 0.59, 0.54], 0.0, 0.48), // Stone, masonry and earth. m("concrete", "Concrete", STONE, [0.27, 0.26, 0.25], 0.0, 0.9), @@ -86,6 +90,8 @@ pub const MATERIALS: &[SmartMaterial] = &[ m("slate", "Slate", STONE, [0.11, 0.115, 0.13], 0.0, 0.72), m("sandstone", "Sandstone", STONE, [0.52, 0.38, 0.23], 0.0, 0.9), m("terrazzo", "Terrazzo", STONE, [0.7, 0.69, 0.66], 0.0, 0.3), + m("sand", "Sand", STONE, [0.52, 0.41, 0.26], 0.0, 0.95), + m("mud", "Mud", STONE, [0.12, 0.08, 0.05], 0.0, 0.6), // Plastics, rubber, composites. m("plastic_glossy", "Plastic Glossy", PLASTIC, [0.8, 0.12, 0.08], 0.0, 0.16), m("plastic_matte", "Plastic Matte", PLASTIC, [0.18, 0.18, 0.19], 0.0, 0.6), @@ -102,12 +108,15 @@ pub const MATERIALS: &[SmartMaterial] = &[ m("ceramic", "Ceramic White", GLASS, [0.8, 0.8, 0.78], 0.0, 0.08), m("glass", "Glass Clear", GLASS, [0.88, 0.9, 0.9], 0.0, 0.03), m("glass_frosted", "Glass Frosted", GLASS, [0.84, 0.88, 0.88], 0.0, 0.45), + m("ice", "Ice", GLASS, [0.72, 0.82, 0.88], 0.0, 0.12), m("car_paint", "Car Paint", PLASTIC, [0.45, 0.025, 0.03], 0.0, 0.4), // Organic. m("skin", "Skin", ORGANIC, [0.56, 0.35, 0.27], 0.0, 0.5), m("wax", "Candle Wax", ORGANIC, [0.8, 0.72, 0.55], 0.0, 0.35), m("cork", "Cork", ORGANIC, [0.36, 0.21, 0.1], 0.0, 0.85), m("paper", "Paper", ORGANIC, [0.82, 0.81, 0.77], 0.0, 0.92), + m("snow", "Snow", ORGANIC, [0.85, 0.87, 0.9], 0.0, 0.6), + m("bone", "Bone", ORGANIC, [0.7, 0.63, 0.5], 0.0, 0.55), // Smart materials. sm("steel_painted_worn", "Steel Painted Worn", METAL, [0.42, 0.06, 0.04], 0.2, 0.45), sm("steel_painted_rust", "Steel Painted Rust Leaks", METAL, [0.62, 0.62, 0.6], 0.1, 0.5), @@ -232,10 +241,11 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result> { let clouds_rough = |seed: u32| gray(P::Clouds, 6.0, seed, r * 0.85, (r * 1.2).min(1.0)); match m.id { // ---- Metals ------------------------------------------------------------------------- - "steel" | "steel_dark" | "iron" | "copper" | "brass" | "bronze" | "gold_polished" | "silver" | "aluminium" | "chrome" | "nickel" => { - plain_metal(b, clouds_rough(7)) - } + "steel" | "steel_dark" | "iron" | "copper" | "brass" | "bronze" | "gold_polished" | "silver" | "aluminium" | "chrome" | "nickel" | "platinum" + | "cobalt" => plain_metal(b, clouds_rough(7)), "steel_stainless" | "aluminium_brushed" | "titanium" => plain_metal(b, gray(P::Brushed, 3.0, 3, r * 0.75, r * 1.25)), + // Zinc plate: large crystalline spangles. + "zinc" => one(b, metal(pat(P::Voronoi, 6.0, 21, 1.0, m.base.map(|v| v * 0.8), m.base), gray(P::Voronoi, 6.0, 21, r * 1.5, r * 0.6))), // Brushing lines run along X; the highlights stretch across them (a quarter turn). "steel_brushed_aniso" => one( b, @@ -275,6 +285,19 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result> { } // Stone chips in a pale binder, polished flat. "terrazzo" => one(b, dielectric(pat(P::Voronoi, 18.0, 9, 1.0, [0.55, 0.55, 0.53], [0.85, 0.84, 0.8]), gray(P::Voronoi, 18.0, 9, 0.34, 0.26))), + // Fine grains in soft wind ripples. + "sand" => one( + b, + plus(dielectric(pat(P::Noise, 12.0, 27, 1.0, [0.42, 0.32, 0.19], [0.6, 0.48, 0.31]), u(0.95)), height(gray(P::Perlin, 4.0, 27, -0.012, 0.0))), + ), + // Glossy wet patches over rougher, drier mud. + "mud" => one( + b, + plus( + dielectric(pat(P::Clouds, 3.0, 29, 1.0, [0.05, 0.035, 0.02], [0.17, 0.12, 0.075]), gray(P::Grunge, 3.0, 29, 0.85, 0.2)), + height(gray(P::Clouds, 3.0, 29, -0.03, 0.0)), + ), + ), "cork" => { one(b, plus(dielectric(pat(P::Noise, 6.0, 17, 1.0, [0.25, 0.14, 0.06], [0.45, 0.28, 0.13]), u(0.85)), height(gray(P::Pores, 20.0, 17, -0.01, 0.0)))) } @@ -310,6 +333,11 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result> { ), ), "plywood" => one(b, dielectric(pat(P::Wood, 1.2, 15, 0.6, [0.42, 0.27, 0.13], [0.66, 0.47, 0.27]), gray(P::Wood, 1.2, 15, 0.8, 0.7))), + // Dark, deep furrows between gray-brown ridges. + "bark" => one( + b, + plus(dielectric(pat(P::Streaks, 8.0, 25, 1.4, [0.13, 0.105, 0.08], [0.03, 0.022, 0.015]), u(0.9)), height(gray(P::Streaks, 8.0, 25, 0.0, -0.06))), + ), "wood_painted" => one( b, plus( @@ -357,15 +385,21 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result> { "plastic_glossy" | "plastic_matte" | "ceramic" => one(b, dielectric(rgb(m.base), clouds_rough(9))), "plastic_textured" => one(b, plus(dielectric(rgb(m.base), gray(P::Leather, 40.0, 5, 0.66, 0.5)), height(gray(P::Leather, 40.0, 5, -0.01, 0.0)))), "rubber" => one(b, dielectric(pat(P::Noise, 0.5, 3, 1.0, [0.025; 3], [0.035; 3]), gray(P::Noise, 0.5, 3, 0.84, 0.94))), - "carbon_fiber" => { - one(b, plus(dielectric(pat(P::Weave, 24.0, 1, 1.0, [0.01, 0.01, 0.012], [0.06, 0.06, 0.065]), u(r)), height(gray(P::Weave, 24.0, 1, 0.0, 0.006)))) - } + // Twill-woven tows under a clear coat: the warp catches the light, the weft stays dark. + "carbon_fiber" => one( + b, + plus( + dielectric(pat(P::Twill, 12.0, 1, 1.0, [0.004, 0.004, 0.005], [0.08, 0.08, 0.085]), gray(P::Twill, 12.0, 1, 0.5, 0.28)), + [(CoatWeight, u(1.0)), (CoatRoughness, u(r * 0.2)), (Height, gray(P::Twill, 12.0, 1, 0.0, 0.002))], + ), + ), // ---- Fabric and leather ------------------------------------------------------------- "fabric" => { one(b, plus(dielectric(pat(P::Weave, 18.0, 2, 1.0, [0.27, 0.29, 0.34], [0.6, 0.62, 0.7]), u(r)), height(gray(P::Weave, 18.0, 2, -0.01, 0.0)))) } + // Indigo twill: diagonal ribs. "denim" => { - one(b, plus(dielectric(pat(P::Weave, 22.0, 5, 1.0, [0.02, 0.03, 0.08], [0.12, 0.16, 0.3]), u(r)), height(gray(P::Weave, 22.0, 5, -0.01, 0.0)))) + one(b, plus(dielectric(pat(P::Twill, 22.0, 5, 1.0, [0.015, 0.025, 0.07], [0.15, 0.2, 0.38]), u(r)), height(gray(P::Twill, 22.0, 5, -0.01, 0.0)))) } "leather" => one( b, @@ -384,8 +418,9 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result> { "velvet" => one( b, plus( - dielectric(pat(P::Weave, 30.0, 3, 1.0, [0.07, 0.008, 0.05], m.base), u(r)), - [(SheenWeight, u(1.0)), (SheenColor, rgb([0.95, 0.55, 0.85])), (SheenRoughness, u(0.35)), (Height, gray(P::Weave, 30.0, 3, -0.004, 0.0))], + // A pile, not a weave: soft crushed patches under a bright sheen. + dielectric(pat(P::Clouds, 3.0, 3, 1.0, [0.06, 0.006, 0.045], m.base), u(r)), + [(SheenWeight, u(1.0)), (SheenColor, rgb([0.95, 0.55, 0.85])), (SheenRoughness, u(0.35)), (Height, gray(P::Noise, 1.0, 3, -0.002, 0.0))], ), ), // ---- Coated and translucent --------------------------------------------------------- @@ -406,6 +441,27 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result> { "wax" => one(b, plus(dielectric(pat(P::Clouds, 2.0, 11, 1.0, [0.74, 0.66, 0.5], m.base), clouds_rough(11)), [(ScatterWeight, u(1.0))])), // ---- Glass (the Transmission channel; the base color tints the light going through) ---- "glass" => one(b, plus(dielectric(rgb(m.base), u(r)), [(Transmission, u(1.0))])), + // Clear with cloudy patches of trapped air. + "ice" => one( + b, + plus(dielectric(pat(P::Clouds, 4.0, 31, 1.0, m.base, [0.84, 0.88, 0.9]), clouds_rough(31)), [(Transmission, gray(P::Clouds, 4.0, 31, 0.9, 0.5))]), + ), + // Bright, rough and slightly translucent. + "snow" => one( + b, + plus( + dielectric(pat(P::Clouds, 4.0, 33, 1.0, [0.8, 0.82, 0.86], [0.88, 0.89, 0.9]), gray(P::Noise, 1.0, 33, 0.5, 0.7)), + [(ScatterWeight, u(0.5)), (Height, gray(P::Perlin, 3.0, 33, -0.02, 0.0))], + ), + ), + // Porous, ivory to tan, with a little light under the surface. + "bone" => one( + b, + plus( + dielectric(pat(P::Clouds, 5.0, 35, 1.0, [0.58, 0.5, 0.37], m.base), clouds_rough(35)), + [(ScatterWeight, u(0.3)), (Height, gray(P::Pores, 16.0, 35, -0.006, 0.0))], + ), + ), "glass_frosted" => one(b, plus(dielectric(rgb(m.base), gray(P::Noise, 1.0, 2, 0.4, 0.5)), [(Transmission, u(1.0))])), // ---- Smart materials ---------------------------------------------------------------- "steel_painted_worn" => { diff --git a/crates/engine/src/meshmap_cmds.rs b/crates/engine/src/meshmap_cmds.rs new file mode 100644 index 00000000..1a42a362 --- /dev/null +++ b/crates/engine/src/meshmap_cmds.rs @@ -0,0 +1,98 @@ +//! Mesh map slots of the Texture Set Settings: use an image resource as a mesh map (baked in +//! another app, or edited by hand) instead of baking it, or clear a slot. + +use std::sync::Arc; + +use rayon::prelude::*; +use serde_json::{Value, json}; +use texturecraft_compose::ImageRes; +use texturecraft_core::{BakedMap, MAX_RESOLUTION, NormalFormat}; + +use crate::commands::{CommandSpec, always, bad, strp}; +use crate::set_cmds::ts_param; +use crate::{Result, Session, cmd}; + +pub fn specs() -> Vec { + vec![ + cmd!( + "textureSet.meshMap.set", + "Use image as mesh map", + [], + None, + "{ts?, map: mesh map id (normal_base, ambient_occlusion, curvature, id, height…), image: resource name} → {map, resolution} — resampled to the size of the set's other mesh maps (or its bake size); a normal map is read in the project's normal format", + always, + set + ), + cmd!("textureSet.meshMap.clear", "Clear mesh map", [], None, "{ts?, map}", always, clear), + ] +} + +fn map_param(p: &Value, cmd: &str) -> Result { + let id = strp(p, "map").ok_or_else(|| bad(cmd, "`map` is required"))?; + BakedMap::parse(id).ok_or_else(|| bad(cmd, format!("unknown mesh map `{id}`"))) +} + +fn set(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "textureSet.meshMap.set"; + 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)?; + // shortcut: one image spans the whole set; UV-tiled sets would need one image per tile. + if !set.uv_tiles.is_empty() { + return Err(bad(CMD, format!("\"{}\" has UV tiles: mesh maps from images need a set without them", set.name))); + } + // Every mesh map of a set shares one size: the other maps', or what a bake would make. + let res = s.doc.baked.get(&ts).filter(|b| !b.maps.is_empty()).map_or(set.bake.resolution, |b| b.resolution); + if !(1..=MAX_RESOLUTION).contains(&res) { + return Err(bad(CMD, format!("mesh map size {res} is not in 1..={MAX_RESOLUTION}"))); + } + let directx = map == BakedMap::Normal && s.doc.project.normal_format == NormalFormat::DirectX; + let data = resample(&img, map.components(), res, directx); + 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 })) +} + +/// `img` as `res` × `res` texels of `comps` values each, as stored in the file (mesh maps hold +/// data, not colors, so nothing is linearized); `flip_green` reads a DirectX normal map. +fn resample(img: &ImageRes, comps: usize, res: u32, flip_green: bool) -> Vec { + let n = res as usize; + let mut out = vec![0.0; n * n * comps]; + out.par_chunks_mut(n * comps).enumerate().for_each(|(y, row)| { + let v = (y as f32 + 0.5) / res as f32; + for (x, texel) in row.chunks_exact_mut(comps).enumerate() { + let mut c = img.sample((x as f32 + 0.5) / res as f32, v); + if flip_green { + c[1] = 1.0 - c[1]; + } + for (o, c) in texel.iter_mut().zip(c) { + *o = c; + } + } + }); + out +} + +fn clear(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "textureSet.meshMap.clear"; + let ts = ts_param(s, p, CMD)?; + let map = map_param(p, CMD)?; + if !s.doc.baked.get(&ts).is_some_and(|b| b.maps.contains_key(&map)) { + return Err(bad(CMD, format!("texture set {ts} has no {} map", map.label()))); + } + s.edit("Clear mesh map", |s| { + if let Some(b) = s.doc.baked.get_mut(&ts) { + b.maps.remove(&map); + } + s.doc.project.texture_set_mut(ts)?.baked.remove(&map); + Ok(()) + })?; + Ok(Value::Null) +} diff --git a/crates/engine/src/painting.rs b/crates/engine/src/painting.rs index 741fac6c..623d0751 100644 --- a/crates/engine/src/painting.rs +++ b/crates/engine/src/painting.rs @@ -57,7 +57,10 @@ impl Session { let content = self.doc.project.layer(owner)?.content_effects.iter().any(|x| x.id == e); Ok(if content { PaintTarget::Layer(e) } else { PaintTarget::Mask(e) }) } - _ => Err(EngineError::Other("the selected effect is not a paint effect".into())), + // A filter (or another effect) is selected, e.g. just added from the shelf: paint + // what lies beneath it, so the new paint goes through it. + Some((owner, _)) => self.paint_target_below(owner, e), + None => Err(EngineError::Other("the selected effect is not a paint effect".into())), }, StackTarget::Mask => { let eid = self.doc.project.alloc_id(); @@ -72,6 +75,36 @@ impl Session { } } + /// What a stroke paints while non-paint effect `effect` of layer `owner` is selected: the + /// nearest paint effect below it in the same stack, else the paint layer's own pixels (for + /// content) or a new paint effect inserted just below it (for a mask). + fn paint_target_below(&mut self, owner: LayerId, effect: LayerId) -> Result { + let eid = self.doc.project.alloc_id(); + let layer = self.doc.project.layer_mut(owner)?; + let below = |effects: &[Effect], at: usize| effects.get(..at).and_then(|b| b.iter().rev().find(|x| matches!(x.kind, EffectKind::Paint))).map(|x| x.id); + if let Some(at) = layer.content_effects.iter().position(|x| x.id == effect) { + if let Some(id) = below(&layer.content_effects, at) { + return Ok(PaintTarget::Layer(id)); + } + return if matches!(layer.kind, LayerKind::Paint) { + Ok(PaintTarget::Layer(owner)) + } else { + Err(EngineError::Other(format!( + "\"{}\" is a {} layer: paint on a paint layer or on its mask (a filter changes what lies below it)", + layer.name, + layer.kind.name() + ))) + }; + } + let mask = layer.mask.as_mut().ok_or_else(|| EngineError::Other("the selected effect is not a paint effect".into()))?; + let at = mask.effects.iter().position(|x| x.id == effect).ok_or_else(|| EngineError::Other("the selected effect is not a paint effect".into()))?; + if let Some(id) = below(&mask.effects, at) { + return Ok(PaintTarget::Mask(id)); + } + mask.effects.insert(at, Effect::new(eid, EffectKind::Paint)); + Ok(PaintTarget::Mask(eid)) + } + fn stroke_values(&self, target: PaintTarget) -> BTreeMap { let ts = self.ts(); let Ok(set) = self.doc.project.texture_set(ts) else { return BTreeMap::new() }; @@ -483,13 +516,18 @@ impl Session { FillMode::Triangle => [tri].into_iter().collect(), FillMode::Mesh => m.triangles_of(material).map(|t| t as u32).collect(), FillMode::UvIsland => { - // Triangles sharing vertex indices form a UV island (seams split vertices). - let mut by_vertex: BTreeMap> = BTreeMap::new(); + // Triangles sharing an edge in UV space form a UV island: imported meshes often + // split vertices along hard edges (or per face) where the UVs run on, so shared + // vertex indices alone break an island into its polygons. + let corner = |i: usize| m.uvs.get(i).map(|uv| [(uv.x * 1e5).round() as i64, (uv.y * 1e5).round() as i64]); + let edges = |t: usize| match m.tri(t).map(|v| v.map(corner)) { + Some([Some(a), Some(b), Some(c)]) => [(a, b), (b, c), (c, a)].map(|(p, q)| (p.min(q), p.max(q))).to_vec(), + _ => Vec::new(), + }; + let mut by_edge: BTreeMap<_, Vec> = BTreeMap::new(); for t in m.triangles_of(material) { - if let Some(v) = m.tri(t) { - for i in v { - by_vertex.entry(i).or_default().push(t as u32); - } + for e in edges(t) { + by_edge.entry(e).or_default().push(t as u32); } } let mut seen = BTreeSet::new(); @@ -498,12 +536,10 @@ impl Session { if !seen.insert(t) { continue; } - if let Some(v) = m.tri(t as usize) { - for i in v { - for n in by_vertex.get(&i).map(Vec::as_slice).unwrap_or(&[]) { - if !seen.contains(n) { - stack.push(*n); - } + for e in edges(t as usize) { + for n in by_edge.get(&e).map(Vec::as_slice).unwrap_or(&[]) { + if !seen.contains(n) { + stack.push(*n); } } } @@ -573,3 +609,34 @@ fn with_commit_source( let carried = st.canvas.pickup.as_ref().map(|p| &p.values); f(CommitSource { alpha: &st.canvas.alpha, tiles, opacity: st.stroke.settings.opacity, erase: st.erase, per_texel, carried }) } + +#[cfg(test)] +mod tests { + use texturecraft_geom::glam::{Vec2, Vec3}; + use texturecraft_geom::mesh::Mesh; + use texturecraft_geom::primitives; + + use crate::session::{FillMode, Session}; + + #[test] + fn uv_island_fill_follows_uvs_across_split_vertices() { + // Two copies of a plane, each triangle with its own three vertices (as hard edges or + // per-face imports leave a mesh), the second copy apart in UV space. + let plane = primitives::plane(2.0, 4); + let (mut positions, mut uvs) = (Vec::::new(), Vec::::new()); + for shift in [0.0, 0.5] { + for i in plane.indices.iter().map(|i| *i as usize) { + positions.push(plane.positions[i] + Vec3::Y * shift); + uvs.push(plane.uvs[i] * 0.5 + shift); + } + } + let indices = (0..positions.len() as u32).collect(); + let mesh = Mesh::from_parts(positions, None, uvs, indices, "m").unwrap(); + let n = plane.triangle_count(); + assert_eq!(mesh.vertex_count(), 6 * n, "no vertex is shared"); + let mut s = Session::new_project("t", mesh, "test", None, 128).unwrap(); + s.tool.fill_mode = FillMode::UvIsland; + assert_eq!(s.fill_set(0, 0).len(), n, "the whole first island"); + assert_eq!(s.fill_set(n as u32, 0).len(), n, "only the second island"); + } +} diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index fa239848..9b5acfa5 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -333,7 +333,7 @@ pub struct Session { /// Viewport size (pixels) used by scripted strokes. pub viewport: Vec2, pub(crate) stroke: Option, - /// Layer clipboard: a document snapshot and the copied layer. + /// Layer clipboard: a document snapshot and the copied layer (or effect). pub clipboard: Option<(Document, LayerId)>, /// Decoded image resources (rebuilt from `doc.resources` by `Session::sync_images`). pub images: texturecraft_compose::ImageStore, @@ -601,6 +601,10 @@ impl Session { pub fn redo_label(&self) -> Option<&str> { self.redo.last().map(|(l, _)| l.as_str()) } + /// The undone steps, the next one to redo first. + pub fn redo_labels(&self) -> Vec { + self.redo.iter().rev().map(|(l, _)| l.clone()).collect() + } pub fn history_labels(&self) -> Vec { self.undo.iter().map(|(l, _)| l.clone()).collect() } @@ -629,6 +633,14 @@ impl Session { self.modified = true; self.revision = self.revision.wrapping_add(1); self.invalidate_changed(other); + // An undone add or duplicate takes the selected effect away: select the stack it was in. + if let StackTarget::Effect(e) = self.target + && self.doc.project.effect(e).is_none() + { + let p = &other.project; + let content = p.effect(e).and_then(|(owner, _)| p.layers.get(&owner)).is_some_and(|l| l.content_effects.iter().any(|x| x.id == e)); + self.target = if content { StackTarget::Content } else { StackTarget::Mask }; + } } // ----------------------------------------------------------------------------------------- @@ -773,12 +785,12 @@ impl Session { self.caches.get_mut(ts).map(|c| std::mem::take(&mut c.upload).into_iter().collect()).unwrap_or_default() } - /// Grayscale RGBA8 of layer `id`'s mask at `size²` for the mask view (None without a mask). - pub fn mask_view_rgba(&self, id: LayerId, size: u32) -> Option> { - let (ts, _, _) = self.doc.project.locate(id)?; + /// `f` on the compositor inputs of texture set `ts` (without a live stroke; None for a set + /// not ready). + pub(crate) fn with_inputs(&self, ts: usize, f: impl FnOnce(&texturecraft_compose::Inputs) -> Option) -> Option { let cache = self.caches.get(ts)?; let empty = BakedMaps::default(); - let inputs = texturecraft_compose::Inputs { + f(&texturecraft_compose::Inputs { project: &self.doc.project, ts, mesh: &self.mesh, @@ -788,11 +800,24 @@ impl Session { preview: None, images: &self.images, bounds: self.mesh.bounds(), - }; - let gray = texturecraft_compose::mask_image(&inputs, id, size)?; + }) + } + + /// Grayscale RGBA8 of layer `id`'s mask at `size²` for the mask view (None without a mask). + pub fn mask_view_rgba(&self, id: LayerId, size: u32) -> Option> { + let (ts, _, _) = self.doc.project.locate(id)?; + let gray = self.with_inputs(ts, |inp| texturecraft_compose::mask_image(inp, id, size))?; Some(gray.iter().flat_map(|g| [*g, *g, *g, 255]).collect()) } + /// Histogram (`bins` buckets over 0..1) of the values entering effect `effect`: its layer's + /// mask, or for a content effect the layer's `channel` (None for an unknown effect). + pub fn effect_histogram(&self, effect: LayerId, channel: Channel, bins: usize) -> Option> { + let (owner, _) = self.doc.project.effect(effect)?; + let (ts, _, _) = self.doc.project.locate(owner)?; + self.with_inputs(ts, |inp| texturecraft_compose::effect_histogram(inp, effect, channel, bins)) + } + pub fn baked(&self, ts: usize) -> Option<&BakedMaps> { self.doc.baked.get(&ts) } diff --git a/crates/engine/src/set_cmds.rs b/crates/engine/src/set_cmds.rs index d311b65d..c793f443 100644 --- a/crates/engine/src/set_cmds.rs +++ b/crates/engine/src/set_cmds.rs @@ -28,6 +28,15 @@ pub fn specs() -> Vec { cmd!("textureSet.channel.add", "Add channel", [], None, "{ts?, channel}", always, |s, p| channel(s, p, true)), cmd!("textureSet.channel.remove", "Remove channel", [], None, "{ts?, channel}", always, |s, p| channel(s, p, false)), cmd!("textureSet.visible", "Toggle texture set visibility", [], None, "{ts?, visible?}", always, visible), + cmd!( + "textureSet.visibility", + "Show or hide texture sets", + [], + None, + "{mode: showAll|hideAll|invert|solo, ts?} → {visible: [bool per set]}; solo shows only `ts` (the active set), or every set again when it already was the only one", + always, + visibility + ), cmd!("textureSet.rename", "Rename texture set", [], None, "{ts?, name}", always, rename), cmd!("textureSet.settings", "Texture set settings", [], None, "{ts?, description?, heightStrength?, normalFormat?: openGl|directX}", always, settings), cmd!( @@ -214,6 +223,25 @@ fn visible(s: &mut Session, p: &Value) -> Result { Ok(json!({ "visible": v })) } +fn visibility(s: &mut Session, p: &Value) -> Result { + let cmd = "textureSet.visibility"; + let ts = ts_param(s, p, cmd)?; + let mode = strp(p, "mode").filter(|m| ["showAll", "hideAll", "invert", "solo"].contains(m)); + let mode = mode.ok_or_else(|| bad(cmd, "`mode` must be showAll, hideAll, invert or solo"))?; + let sets = &mut s.doc.project.texture_sets; + let solo = sets.iter().enumerate().all(|(i, t)| t.visible == (i == ts)); + for (i, t) in sets.iter_mut().enumerate() { + t.visible = match mode { + "showAll" => true, + "hideAll" => false, + "invert" => !t.visible, + _ => solo || i == ts, + }; + } + s.revision = s.revision.wrapping_add(1); + Ok(json!({ "visible": s.doc.project.texture_sets.iter().map(|t| t.visible).collect::>() })) +} + fn rename(s: &mut Session, p: &Value) -> Result { let ts = ts_param(s, p, "textureSet.rename")?; let name = strp(p, "name") @@ -251,3 +279,22 @@ fn settings(s: &mut Session, p: &Value) -> Result { })?; Ok(Value::Null) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn visibility_shows_hides_inverts_and_solos() { + // The material ball has two texture sets. + let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + let mut run = |p: Value| crate::execute(&mut s, "textureSet.visibility", &p).map(|r| r["visible"].clone()); + assert_eq!(run(json!({"mode": "hideAll"})).unwrap(), json!([false, false])); + assert_eq!(run(json!({"mode": "solo", "ts": 1})).unwrap(), json!([false, true])); + assert_eq!(run(json!({"mode": "solo", "ts": 1})).unwrap(), json!([true, true]), "solo again shows every set"); + assert_eq!(run(json!({"mode": "solo", "ts": 0})).unwrap(), json!([true, false])); + assert_eq!(run(json!({"mode": "invert"})).unwrap(), json!([false, true])); + assert_eq!(run(json!({"mode": "showAll"})).unwrap(), json!([true, true])); + assert!(run(json!({"mode": "sideways"})).is_err() && run(json!({"mode": "solo", "ts": 9})).is_err()); + } +} diff --git a/crates/engine/src/text_cmds.rs b/crates/engine/src/text_cmds.rs new file mode 100644 index 00000000..fbc4705b --- /dev/null +++ b/crates/engine/src/text_cmds.rs @@ -0,0 +1,108 @@ +//! Text: an image resource drawn from text in an installed font (or a built-in one), to stamp +//! with the brush as its alpha or to place as a decal. + +use serde_json::{Value, json}; +use texturecraft_paint::text::render_text; + +use crate::commands::{CommandSpec, always, bad, color_param, f32p, strp}; +use crate::{Result, Session, cmd}; + +pub fn specs() -> Vec { + vec![ + cmd!("text.fonts", "List fonts", [], None, "{} — the installed font families with their styles, and the built-in ones", always, |_, _| Ok(fonts())), + cmd!( + "resource.text", + "Add text", + [], + None, + "{text (lines split at \\n), font?: family (text.fonts; default a common sans-serif), style?: e.g. Bold (default Regular), size?: 8..1024 texels per em (default 256), color?: [r,g,b] linear or \"#rrggbb\" (default white), name?} — draws the text as an image resource with an alpha (white for tool.brush {alpha: {image}}, colored for layer.add.decal)", + always, + add_text + ), + ] +} + +/// Fonts bundled with the app (egui's), used when nothing is installed or in the browser. +const BUILT_IN: [(&str, &[u8]); 2] = [("Ubuntu Light", epaint_default_fonts::UBUNTU_LIGHT), ("Hack", epaint_default_fonts::HACK_REGULAR)]; +/// Families tried, in order, when no font is asked for. +const DEFAULT_FAMILIES: [&str; 6] = ["Arial", "Segoe UI", "Helvetica", "Liberation Sans", "DejaVu Sans", "Noto Sans"]; +/// Largest font file read. +#[cfg(not(target_arch = "wasm32"))] +const MAX_FONT_BYTES: u64 = 128 << 20; + +#[cfg(not(target_arch = "wasm32"))] +fn installed() -> &'static [texturecraft_formats::fonts::FontFace] { + static FONTS: std::sync::OnceLock> = std::sync::OnceLock::new(); + FONTS.get_or_init(texturecraft_formats::fonts::system_fonts) +} + +fn fonts() -> Value { + #[cfg(not(target_arch = "wasm32"))] + let families = { + let mut out: Vec<(String, Vec)> = Vec::new(); + for f in installed() { + match out.last_mut() { + Some((family, styles)) if *family == f.family => styles.push(f.style.clone()), + _ => out.push((f.family.clone(), vec![f.style.clone()])), + } + } + out + }; + #[cfg(target_arch = "wasm32")] + let families: Vec<(String, Vec)> = Vec::new(); + json!({ + "installed": families.into_iter().map(|(family, styles)| json!({"family": family, "styles": styles})).collect::>(), + "builtIn": BUILT_IN.map(|(name, _)| name), + }) +} + +/// The bytes and face index of `family` in `style` (a regular face when the style is missing), +/// or the first default family installed, else the built-in font. +fn font_bytes(family: Option<&str>, style: Option<&str>) -> Result<(std::borrow::Cow<'static, [u8]>, u32)> { + let is = |a: &str, b: &str| a.eq_ignore_ascii_case(b); + if let Some((_, bytes)) = BUILT_IN.iter().find(|(name, _)| family.is_some_and(|f| is(f, name))) { + return Ok((std::borrow::Cow::Borrowed(bytes), 0)); + } + #[cfg(not(target_arch = "wasm32"))] + { + let faces = installed(); + let pick = |family: &str| { + let of: Vec<_> = faces.iter().filter(|f| is(&f.family, family)).collect(); + let regular = ["Regular", "Normal", "Book", "Roman"]; + let found = style.and_then(|s| of.iter().find(|f| is(&f.style, s))); + found.or_else(|| of.iter().find(|f| regular.iter().any(|r| is(&f.style, r)))).or(of.first()).copied() + }; + let face = match family { + Some(f) => Some(pick(f).ok_or_else(|| bad("resource.text", format!("no font family `{f}` (see text.fonts)")))?), + None => DEFAULT_FAMILIES.iter().find_map(|f| pick(f)), + }; + if let Some(face) = face { + let size = std::fs::metadata(&face.path).map(|m| m.len()).unwrap_or(u64::MAX); + if size > MAX_FONT_BYTES { + return Err(bad("resource.text", format!("{} is too large", face.path.display()))); + } + let bytes = std::fs::read(&face.path).map_err(|e| bad("resource.text", format!("cannot read {}: {e}", face.path.display())))?; + return Ok((std::borrow::Cow::Owned(bytes), face.index)); + } + } + #[cfg(target_arch = "wasm32")] + let _ = style; + match family { + Some(f) => Err(bad("resource.text", format!("no font family `{f}` (see text.fonts)"))), + None => Ok((std::borrow::Cow::Borrowed(BUILT_IN[0].1), 0)), + } +} + +fn add_text(s: &mut Session, p: &Value) -> Result { + let cmd = "resource.text"; + let text = strp(p, "text").ok_or_else(|| bad(cmd, "`text` is required"))?; + let (font, index) = font_bytes(strp(p, "font"), strp(p, "style"))?; + let size = f32p(p, "size").unwrap_or(256.0).clamp(8.0, 1024.0); + let img = render_text(&font, index, text, size).map_err(|e| bad(cmd, e))?; + let rgb = color_param(p, "color").unwrap_or([1.0; 3]).map(|c| (texturecraft_texel::linear_to_srgb(c.clamp(0.0, 1.0)) * 255.0).round() as u8); + let png = texturecraft_formats::coverage_png(img.width, img.height, &img.coverage, rgb).map_err(|e| bad(cmd, e.to_string()))?; + // The resource is named after the text (its first line, shortened) unless a name is given. + let label: String = strp(p, "name").unwrap_or_else(|| text.lines().next().unwrap_or_default()).chars().take(32).collect(); + let name = s.import_resource_bytes(&format!("Text {}.png", label.trim()), png)?; + Ok(json!({ "name": name, "width": img.width, "height": img.height })) +} diff --git a/crates/engine/src/tool_cmds.rs b/crates/engine/src/tool_cmds.rs index 465726f2..7fa5fdab 100644 --- a/crates/engine/src/tool_cmds.rs +++ b/crates/engine/src/tool_cmds.rs @@ -42,7 +42,15 @@ pub fn specs() -> Vec { "procedural": BrushAlpha::ALL.map(BrushAlpha::label), "library": alphas::library().iter().map(|a| json!({"id": a.id, "label": a.label, "category": a.category})).collect::>(), }))), - cmd!("tool.material", "Tool material", [], None, "{channel, color?|value?, enabled?} or {maskValue?: 0..1}", always, material), + cmd!( + "tool.material", + "Tool material", + [], + None, + "{channel, color?|value?, enabled?, solo?: true (paint this channel only)} or {maskValue?: 0..1}", + always, + material + ), cmd!( "tool.stencil", "Projection stencil", @@ -232,6 +240,9 @@ fn material(s: &mut Session, p: &Value) -> Result { } None => {} } + if boolp(p, "solo") == Some(true) { + s.tool.enabled = std::iter::once(c).collect(); + } } s.revision = s.revision.wrapping_add(1); Ok(json!({ diff --git a/crates/engine/src/view_cmds.rs b/crates/engine/src/view_cmds.rs index b157dc90..b39c876d 100644 --- a/crates/engine/src/view_cmds.rs +++ b/crates/engine/src/view_cmds.rs @@ -1,10 +1,11 @@ //! Edit, viewport and display commands. use serde_json::{Value, json}; +use texturecraft_core::project::ENVIRONMENTS; use texturecraft_core::{BakedMap, Channel, ToneMapping}; use texturecraft_geom::glam::Vec3; -use crate::commands::{CommandSpec, always, bad, boolp, can_redo, can_undo, color_param, f32p, strp}; +use crate::commands::{CommandSpec, always, bad, boolp, can_redo, can_undo, color_param, f32p, strp, u64p}; use crate::session::ViewMode; use crate::{Result, Session, cmd}; @@ -34,14 +35,51 @@ pub fn specs() -> Vec { pub(crate) fn edit_specs() -> Vec { vec![ - cmd!("edit.undo", "Undo", ["Edit"], Some("Ctrl+Z"), "{}", can_undo, |s, _| Ok(json!({ "undone": s.undo()? }))), - cmd!("edit.redo", "Redo", ["Edit"], Some("Ctrl+Y"), "{}", can_redo, |s, _| Ok(json!({ "redone": s.redo()? }))), - cmd!("edit.history", "History", [], None, "{}", always, |s, _| Ok( - json!({ "undo": s.history_labels(), "redo": s.redo.iter().rev().map(|(l, _)| l.clone()).collect::>() }) + cmd!( + "edit.undo", + "Undo", + ["Edit"], + Some("Ctrl+Z"), + "{steps?: 1 (as many as there are)} → {undone: the last step undone, steps}", + can_undo, + |s, p| { + let (last, n) = repeat(s, p, Session::undo)?; + Ok(json!({ "undone": last, "steps": n })) + } + ), + cmd!( + "edit.redo", + "Redo", + ["Edit"], + Some("Ctrl+Y"), + "{steps?: 1 (as many as there are)} → {redone: the last step redone, steps}", + can_redo, + |s, p| { + let (last, n) = repeat(s, p, Session::redo)?; + Ok(json!({ "redone": last, "steps": n })) + } + ), + cmd!("edit.history", "History", [], None, "{} → {undo: steps, oldest first, redo: undone steps, next first}", always, |s, _| Ok( + json!({ "undo": s.history_labels(), "redo": s.redo_labels() }) )), ] } +/// Run `step` (undo or redo) `steps` times (default 1) or until the history runs out: the last +/// step's label and how many ran (the History panel jumps to a step this way). +fn repeat(s: &mut Session, p: &Value, step: fn(&mut Session) -> Result) -> Result<(String, u64)> { + let steps = u64p(p, "steps").unwrap_or(1).max(1); + let mut last = step(s)?; + let mut n = 1; + while n < steps + && let Ok(l) = step(s) + { + last = l; + n += 1; + } + Ok((last, n)) +} + fn frame(s: &mut Session, _: &Value) -> Result { let (lo, hi) = s.mesh.bounds(); s.camera.frame(lo, hi); @@ -164,6 +202,9 @@ fn display(s: &mut Session, p: &Value) -> Result { { return Err(bad("display.set", format!("no image resource `{name}` (import it with resource.import)"))); } + if let Some(e) = env.as_deref().filter(|e| !e.starts_with(texturecraft_core::project::ENV_RESOURCE_PREFIX) && !ENVIRONMENTS.contains(e)) { + return Err(bad("display.set", format!("unknown environment `{e}`: one of {}, or resource:", ENVIRONMENTS.join(", ")))); + } let d = &mut s.doc.project.display; if let Some(e) = env { d.environment = e; @@ -234,6 +275,10 @@ mod tests { fn hdr_resources_become_the_environment() { let mut s = Session::new_project("t", texturecraft_geom::primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 128).unwrap(); assert!(execute(&mut s, "display.set", &json!({"environment": "resource:sky.hdr"})).is_err(), "unknown resources are rejected"); + let e = execute(&mut s, "display.set", &json!({"environment": "nonexistent"})).unwrap_err().to_string(); + assert!(e.contains("Studio Soft"), "unknown environments are rejected with the valid names: {e}"); + assert_eq!(s.doc.project.display.environment, "Studio Soft"); + execute(&mut s, "display.set", &json!({"environment": "Night"})).unwrap(); let img = image::Rgb32FImage::from_fn(64, 32, |_, y| image::Rgb([if y < 8 { 40.0 } else { 0.5 }; 3])); let mut hdr = Vec::new(); image::DynamicImage::ImageRgb32F(img).write_to(&mut std::io::Cursor::new(&mut hdr), image::ImageFormat::Hdr).unwrap(); diff --git a/crates/engine/tests/bake.rs b/crates/engine/tests/bake.rs index e209094f..41940f54 100644 --- a/crates/engine/tests/bake.rs +++ b/crates/engine/tests/bake.rs @@ -143,7 +143,7 @@ fn per_map_ray_settings_round_trip() { let b = s.doc.project.texture_sets[0].bake.clone(); assert_eq!(b.ao, RaySettings { rays: 48, max_distance: 0.5, spread: 90.0, distribution: RayDistribution::Uniform }); assert!(b.ao_ignore_backface && b.ao_self_occlusion == SelfOcclusion::SameMeshName); - assert_eq!((b.thickness.rays, b.thickness.spread, b.thickness.max_distance), (12, 45.0, 0.25)); + assert_eq!((b.thickness.rays, b.thickness.spread, b.thickness.max_distance), (12, 45.0, 0.1)); assert_eq!((b.bent_normal.rays, b.bent_normal.max_distance, b.bent_normal.spread), (6, 0.1, 180.0)); assert_eq!((b.curvature_radius, b.position_mode, b.direction_mode), (3, PositionMode::BoundingSphere, DirectionMode::Positive)); assert_eq!(r[0]["settings"]["ao"]["selfOcclusion"], "sameMeshName"); diff --git a/crates/engine/tests/content_effects.rs b/crates/engine/tests/content_effects.rs index 74011e9e..e6c75e1e 100644 --- a/crates/engine/tests/content_effects.rs +++ b/crates/engine/tests/content_effects.rs @@ -1,7 +1,7 @@ //! Content effects, HSL and anchor points through engine commands. use serde_json::{Value, json}; -use texturecraft_engine::core::{Channel, LayerId}; +use texturecraft_engine::core::{Channel, EffectKind, LayerId}; use texturecraft_engine::geom::primitives; use texturecraft_engine::{Session, StackTarget, execute}; @@ -111,3 +111,137 @@ fn painting_into_a_content_paint_effect() { assert!(s.doc.pixels.layer(LayerId(e), Channel::Roughness).is_none()); assert!(center(&mut s, Channel::Roughness)[0] > 0.85); } + +#[test] +fn effects_move_within_their_stack_and_duplicate_with_their_pixels() { + let mut s = session(); + let layer = id(execute(&mut s, "layer.add.fill", &json!({"roughness": 0.3})).unwrap(), "layer"); + let paint = id(execute(&mut s, "effect.add.paint", &json!({"target": "content"})).unwrap(), "effect"); + execute(&mut s, "tool.material", &json!({"channel": "roughness", "value": 0.9})).unwrap(); + execute(&mut s, "tool.brush", &json!({"size": 20, "hardness": 90})).unwrap(); + execute(&mut s, "tool.stroke", &json!({"points": [[180, 200], [220, 200]]})).unwrap(); + let fill = id(execute(&mut s, "effect.add.fill", &json!({"target": "content", "roughness": 0.2})).unwrap(), "effect"); + let order = |s: &Session| s.doc.project.layer(LayerId(layer)).unwrap().content_effects.iter().map(|e| e.id.0).collect::>(); + assert!(close(center(&mut s, Channel::Roughness), [0.2; 3]), "the fill covers the paint"); + // To the bottom, the paint shows again; an index past the end means the top. + execute(&mut s, "effect.move", &json!({"effect": fill, "index": 0})).unwrap(); + assert_eq!(order(&s), [fill, paint]); + assert!(center(&mut s, Channel::Roughness)[0] > 0.85, "{:?}", center(&mut s, Channel::Roughness)); + execute(&mut s, "effect.move", &json!({"effect": fill, "index": 99})).unwrap(); + assert_eq!(order(&s), [paint, fill]); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(order(&s), [fill, paint]); + assert!(execute(&mut s, "effect.move", &json!({"effect": fill})).is_err(), "index is required"); + assert!(execute(&mut s, "effect.move", &json!({"effect": 999_999, "index": 0})).is_err()); + // A duplicate sits just above its original with the painted pixels, and takes the selection. + execute(&mut s, "layer.select", &json!({"layer": layer, "target": paint})).unwrap(); + let copy = id(execute(&mut s, "effect.duplicate", &json!({"effect": paint})).unwrap(), "effect"); + assert_eq!(order(&s), [fill, paint, copy]); + assert_eq!(s.target, StackTarget::Effect(LayerId(copy))); + assert!(s.doc.project.effect(LayerId(copy)).unwrap().1.name.ends_with(" copy")); + // Undoing it leaves no missing effect selected, but the stack it was in. + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(s.target, StackTarget::Content); + execute(&mut s, "edit.redo", &Value::Null).unwrap(); + execute(&mut s, "effect.remove", &json!({"effect": paint})).unwrap(); + assert!(center(&mut s, Channel::Roughness)[0] > 0.85, "the copy keeps the strokes"); + assert!(execute(&mut s, "effect.duplicate", &json!({"effect": 999_999})).is_err()); + // Mask effects move within the mask. + execute(&mut s, "mask.add.black", &Value::Null).unwrap(); + let a = id(execute(&mut s, "effect.add.fill", &json!({"target": "mask", "value": 0.3})).unwrap(), "effect"); + let b = id(execute(&mut s, "effect.add.levels", &json!({"target": "mask"})).unwrap(), "effect"); + execute(&mut s, "effect.move", &json!({"effect": b, "index": 0})).unwrap(); + let mask: Vec = s.doc.project.layer(LayerId(layer)).unwrap().mask.as_ref().unwrap().effects.iter().map(|e| e.id.0).collect(); + assert_eq!(mask, [b, a]); +} + +#[test] +fn effects_copy_and_paste_between_layers_and_stacks() { + let mut s = session(); + let low = id(execute(&mut s, "layer.add.fill", &json!({"roughness": 0.3})).unwrap(), "layer"); + let paint = id(execute(&mut s, "effect.add.paint", &json!({"target": "content"})).unwrap(), "effect"); + execute(&mut s, "tool.material", &json!({"channel": "roughness", "value": 0.9})).unwrap(); + execute(&mut s, "tool.brush", &json!({"size": 20, "hardness": 90})).unwrap(); + execute(&mut s, "tool.stroke", &json!({"points": [[180, 200], [220, 200]]})).unwrap(); + assert_eq!(execute(&mut s, "effect.copy", &Value::Null).unwrap(), json!({"copied": paint}), "the selected effect"); + assert!(execute(&mut s, "layer.paste", &Value::Null).is_err(), "the clipboard holds an effect, not a layer"); + // Onto the content of a fill above that covers the first: its strokes come along. + let high = id(execute(&mut s, "layer.add.fill", &json!({"roughness": 0.3})).unwrap(), "layer"); + let pasted = id(execute(&mut s, "effect.paste", &Value::Null).unwrap(), "effect"); + assert_eq!(s.target, StackTarget::Effect(LayerId(pasted))); + assert!(s.doc.pixels.layer(LayerId(pasted), Channel::Roughness).is_some()); + execute(&mut s, "effect.remove", &json!({"effect": paint})).unwrap(); + assert!(center(&mut s, Channel::Roughness)[0] > 0.85, "{:?}", center(&mut s, Channel::Roughness)); + // Above the selected effect. + let inv = id(execute(&mut s, "effect.add.filter", &json!({"target": "content", "filter": "invert"})).unwrap(), "effect"); + execute(&mut s, "effect.copy", &json!({"effect": inv})).unwrap(); + execute(&mut s, "layer.select", &json!({"layer": high, "target": pasted})).unwrap(); + let again = id(execute(&mut s, "effect.paste", &Value::Null).unwrap(), "effect"); + let order: Vec = s.doc.project.layer(LayerId(high)).unwrap().content_effects.iter().map(|e| e.id.0).collect(); + assert_eq!(order, [pasted, again, inv]); + // A generator goes on a mask (made for it) even with the content selected; asking for the + // content is an error. Cut removes the original. + execute(&mut s, "layer.select", &json!({"layer": high})).unwrap(); + let generator = id(execute(&mut s, "effect.add.generator", &Value::Null).unwrap(), "effect"); + execute(&mut s, "effect.cut", &json!({"effect": generator})).unwrap(); + assert!(s.doc.project.effect(LayerId(generator)).is_none()); + execute(&mut s, "layer.select", &json!({"layer": low})).unwrap(); + assert!(execute(&mut s, "effect.paste", &json!({"target": "content"})).is_err()); + execute(&mut s, "effect.paste", &Value::Null).unwrap(); + let mask = &s.doc.project.layer(LayerId(low)).unwrap().mask; + assert!(mask.as_ref().is_some_and(|m| m.effects.iter().any(|e| matches!(e.kind, EffectKind::Generator(_))))); + // A fill reading an anchor point needs one below its new layer. + execute(&mut s, "layer.select", &json!({"layer": low})).unwrap(); + let anchor = id(execute(&mut s, "effect.add.anchor", &Value::Null).unwrap(), "effect"); + execute(&mut s, "layer.select", &json!({"layer": high})).unwrap(); + let reader = id(execute(&mut s, "effect.add.fill", &json!({"target": "mask", "anchor": anchor})).unwrap(), "effect"); + execute(&mut s, "effect.copy", &json!({"effect": reader})).unwrap(); + execute(&mut s, "layer.select", &json!({"layer": low})).unwrap(); + assert!(execute(&mut s, "effect.paste", &Value::Null).is_err(), "the anchor is on the layer itself"); +} + +#[test] +fn histogram_counts_what_an_effect_reads() { + let mut s = session(); + let hist = |s: &mut Session, p: Value| { + let r = execute(s, "effect.histogram", &p).unwrap(); + let bins: Vec = r["bins"].as_array().unwrap().iter().map(|b| b.as_u64().unwrap()).collect(); + (r["target"].as_str().unwrap().to_string(), bins) + }; + // Only the bucket holding the value is filled. + let one = |bins: &[u64], k: usize| bins.iter().enumerate().all(|(i, b)| (*b > 0) == (i == k)); + execute(&mut s, "layer.add.fill", &json!({"color": [0.25, 0.25, 0.25], "roughness": 0.75})).unwrap(); + let lv = id(execute(&mut s, "effect.add.levels", &json!({"target": "content", "inLow": 0.5})).unwrap(), "effect"); + execute(&mut s, "effect.add.filter", &json!({"target": "content", "filter": "invert"})).unwrap(); + let (target, bins) = hist(&mut s, json!({"effect": lv, "channel": "roughness", "bins": 4})); + assert_eq!(target, "content"); + assert!(one(&bins, 3), "roughness 0.75: {bins:?}"); + // The effect itself and those above it are left out; the default channel is the first. + let (_, bins) = hist(&mut s, json!({"effect": lv, "bins": 4})); + assert!(one(&bins, 1), "base color 0.25, components pooled: {bins:?}"); + assert_eq!(bins.iter().sum::() % 3, 0); + // A mask's levels reads the mask below it. + execute(&mut s, "mask.add.black", &Value::Null).unwrap(); + execute(&mut s, "effect.add.fill", &json!({"target": "mask", "value": 0.3})).unwrap(); + let ml = id(execute(&mut s, "effect.add.levels", &json!({"target": "mask"})).unwrap(), "effect"); + let (target, bins) = hist(&mut s, json!({"effect": ml, "bins": 4})); + assert_eq!(target, "mask"); + assert!(one(&bins, 1), "mask 0.3: {bins:?}"); + assert_eq!(hist(&mut s, json!({"effect": ml})).1.len(), 64); + // Below a blur, every tile builds its own neighbourhood field; the texels counted stay the same. + let texels: u64 = bins.iter().sum(); + execute(&mut s, "effect.remove", &json!({"effect": ml})).unwrap(); + execute(&mut s, "effect.add.filter", &json!({"target": "mask", "filter": "blur", "radius": 4})).unwrap(); + let ml = id(execute(&mut s, "effect.add.levels", &json!({"target": "mask"})).unwrap(), "effect"); + let (_, blurred) = hist(&mut s, json!({"effect": ml, "bins": 4})); + assert_eq!(blurred.iter().sum::(), texels); + assert_eq!(blurred.iter().enumerate().max_by_key(|(_, b)| **b).map(|(i, _)| i), Some(1), "{blurred:?}"); + // A paint layer with nothing painted yet still has its mask. + execute(&mut s, "layer.add.paint", &Value::Null).unwrap(); + execute(&mut s, "mask.add.black", &Value::Null).unwrap(); + execute(&mut s, "effect.add.fill", &json!({"target": "mask", "value": 0.6})).unwrap(); + let pl = id(execute(&mut s, "effect.add.levels", &json!({"target": "mask"})).unwrap(), "effect"); + assert!(one(&hist(&mut s, json!({"effect": pl, "bins": 4})).1, 2), "an empty paint layer's mask"); + assert!(execute(&mut s, "effect.histogram", &json!({"effect": 999_999})).is_err()); + assert!(execute(&mut s, "effect.histogram", &json!({"effect": lv, "channel": "nope"})).is_err()); +} diff --git a/crates/engine/tests/export_colour_space.rs b/crates/engine/tests/export_colour_space.rs new file mode 100644 index 00000000..d1985ec8 --- /dev/null +++ b/crates/engine/tests/export_colour_space.rs @@ -0,0 +1,57 @@ +//! `file.exportTextures` / `export.plan` with `colorSpace`. + +use serde_json::{Value, json}; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::texel::ColorSpace; +use texturecraft_engine::{Session, execute}; + +fn session() -> Session { + let mut s = Session::new_project("t", primitives::builtin("plane").unwrap(), "builtin:plane", None, 128).unwrap(); + execute(&mut s, "layer.add.fill", &json!({ "color": [0.8, 0.2, 0.1] })).unwrap(); + s +} + +fn export(s: &mut Session, tag: &str, extra: Value) -> (Value, std::path::PathBuf) { + let dir = std::env::temp_dir().join(format!("tc_export_cs_{tag}_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut p = json!({ "dir": dir.display().to_string(), "preset": "glTF PBR Metal Roughness", "format": "exr", "bitDepth": 32, "padding": "infinite" }); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + (execute(s, "file.exportTextures", &p).unwrap(), dir) +} + +fn first_pixel(path: &std::path::Path) -> [f32; 3] { + let img = image::open(path).unwrap().to_rgb32f(); + // The plane's UV layout covers the whole image; read its middle. + let px = img.get_pixel(img.width() / 2, img.height() / 2); + [px[0], px[1], px[2]] +} + +#[test] +fn colour_maps_are_written_in_the_chosen_space() { + let mut s = session(); + let (plain, dir_plain) = export(&mut s, "plain", json!({})); + let (aces, dir_aces) = export(&mut s, "aces", json!({ "colorSpace": "ACEScg" })); + let base = + |r: &Value| std::path::PathBuf::from(r["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap()).find(|f| f.contains("BaseColor")).unwrap()); + let (a, b) = (first_pixel(&base(&plain)), first_pixel(&base(&aces))); + let want = ColorSpace::AcesCg.from_linear_rec709(a); + assert!((0..3).all(|k| (b[k] - want[k]).abs() < 1e-3), "{b:?} vs {want:?}"); + assert!((0..3).any(|k| (a[k] - b[k]).abs() > 0.01), "the colour actually changed: {a:?} vs {b:?}"); + for d in [dir_plain, dir_aces] { + let _ = std::fs::remove_dir_all(d); + } +} + +#[test] +fn the_plan_reports_the_space_and_clamping_and_bad_names_are_errors() { + let mut s = session(); + let plan = execute(&mut s, "export.plan", &json!({ "preset": "glTF PBR Metal Roughness", "colorSpace": "ACEScg" })).unwrap(); + assert!(plan.as_array().unwrap().iter().any(|f| f["warnings"].as_array().is_some_and(|w| !w.is_empty())), "8-bit ACEScg warns: {plan}"); + let float = execute(&mut s, "export.plan", &json!({ "preset": "glTF PBR Metal Roughness", "colorSpace": "ACEScg", "format": "exr" })).unwrap(); + assert!(float.as_array().unwrap().iter().all(|f| f["warnings"].as_array().is_some_and(Vec::is_empty)), "{float}"); + for bad in ["Display P3", "", "Rec.2020"] { + assert!(execute(&mut s, "export.plan", &json!({ "preset": "glTF PBR Metal Roughness", "colorSpace": bad })).is_err(), "{bad:?}"); + } +} diff --git a/crates/engine/tests/filters.rs b/crates/engine/tests/filters.rs new file mode 100644 index 00000000..12e4e3cd --- /dev/null +++ b/crates/engine/tests/filters.rs @@ -0,0 +1,111 @@ +//! Painting while a filter is selected (it is selected right after the shelf adds it): the +//! stroke paints what lies beneath the filter, so the new paint goes through it. + +use serde_json::{Value, json}; +use texturecraft_engine::core::{Channel, EffectKind, LayerId}; +use texturecraft_engine::geom::glam::Vec2; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, StackTarget, execute}; + +const RES: f32 = 256.0; + +fn session() -> Session { + let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 256).unwrap(); + s.viewport = Vec2::new(400.0, 400.0); + s.camera.yaw = 0.0; + s.camera.pitch = 0.0; + s.update(); + s +} + +/// Base color of the composite under a viewport point. +fn color_at(s: &mut Session, x: f32, y: f32) -> [f32; 3] { + s.update(); + let hit = s.pick(Vec2::new(x, y), s.viewport).unwrap(); + s.caches[0].composite.value(Channel::BaseColor, (hit.uv.x * RES) as u32, (hit.uv.y * RES) as u32) +} + +fn brush(s: &mut Session, color: [f32; 3]) { + execute(s, "tool.paint", &Value::Null).unwrap(); + execute(s, "tool.material", &json!({"channel": "baseColor", "color": color})).unwrap(); + execute(s, "tool.brush", &json!({"size": 20, "hardness": 90})).unwrap(); +} + +fn dab(s: &mut Session) -> Result { + execute(s, "tool.stroke", &json!({"points": [[200, 200]]})).map_err(|e| e.to_string()) +} + +fn add_filter(s: &mut Session, filter: &str, target: &str) -> LayerId { + execute(s, "effect.add.filter", &json!({"filter": filter, "target": target})).unwrap(); + let StackTarget::Effect(e) = s.target else { panic!("adding a filter selects it: {:?}", s.target) }; + e +} + +fn kinds(effects: &[texturecraft_engine::core::Effect]) -> Vec<&'static str> { + effects.iter().map(|e| if matches!(e.kind, EffectKind::Paint) { "paint" } else { "other" }).collect() +} + +#[test] +fn a_selected_content_filter_paints_its_paint_layer_through_it() { + let mut s = session(); + let layer = s.selected_layer().unwrap(); + add_filter(&mut s, "invert", "content"); + brush(&mut s, [1.0, 0.0, 0.0]); + dab(&mut s).expect("painting with the filter selected works"); + let v = color_at(&mut s, 200.0, 200.0); + assert!(v[0] < 0.15 && v[1] > 0.85 && v[2] > 0.85, "red paint shows inverted (cyan): {v:?}"); + assert!(s.doc.pixels.layers.keys().any(|(id, _)| *id == layer), "the paint landed in the layer's own pixels"); + // One undo step removes the stroke and leaves the filter. + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert!(!s.doc.pixels.layers.iter().any(|((id, _), img)| *id == layer && img.allocated_count() > 0)); + assert_eq!(s.doc.project.layer(layer).unwrap().content_effects.len(), 1); +} + +#[test] +fn a_selected_content_filter_paints_the_paint_effect_below_it() { + let mut s = session(); + let layer = s.selected_layer().unwrap(); + execute(&mut s, "effect.add.paint", &json!({"target": "content"})).unwrap(); + let StackTarget::Effect(paint) = s.target else { panic!("{:?}", s.target) }; + add_filter(&mut s, "invert", "content"); + brush(&mut s, [1.0, 0.0, 0.0]); + dab(&mut s).unwrap(); + assert!(s.doc.pixels.layers.iter().any(|((id, _), img)| *id == paint && img.allocated_count() > 0), "painted into the paint effect"); + assert!(!s.doc.pixels.layers.iter().any(|((id, _), img)| *id == layer && img.allocated_count() > 0), "not into the layer below it"); + let v = color_at(&mut s, 200.0, 200.0); + assert!(v[0] < 0.15 && v[1] > 0.85, "through the filter: {v:?}"); +} + +#[test] +fn a_selected_filter_on_a_fill_layer_explains_why_it_cannot_paint() { + let mut s = session(); + execute(&mut s, "layer.add.fill", &json!({"color": [0.2, 0.4, 0.8]})).unwrap(); + add_filter(&mut s, "invert", "content"); + brush(&mut s, [1.0, 0.0, 0.0]); + let e = dab(&mut s).unwrap_err(); + assert!(e.contains("fill layer"), "{e}"); +} + +#[test] +fn a_selected_mask_filter_paints_a_mask_paint_effect_below_it() { + let mut s = session(); + execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.0, 0.0]})).unwrap(); + let layer = s.selected_layer().unwrap(); + execute(&mut s, "mask.add.black", &Value::Null).unwrap(); + add_filter(&mut s, "invert", "mask"); + let mask = |s: &Session| s.doc.project.layer(layer).unwrap().mask.clone().unwrap().effects; + assert_eq!(kinds(&mask(&s)), ["other"]); + // Black mask, inverted: the red fill shows everywhere. + assert!(color_at(&mut s, 200.0, 200.0)[0] > 0.85); + brush(&mut s, [1.0, 1.0, 1.0]); + s.tool.mask_value = 1.0; + dab(&mut s).expect("painting the mask with its filter selected works"); + assert_eq!(kinds(&mask(&s)), ["paint", "other"], "a paint effect was inserted below the filter"); + // White paint goes through the invert: the fill disappears where it was painted only. + let painted = color_at(&mut s, 200.0, 200.0); + let elsewhere = color_at(&mut s, 120.0, 200.0); + assert!(painted[0] < 0.6 && elsewhere[0] > 0.85, "painted {painted:?}, elsewhere {elsewhere:?}"); + // The next stroke reuses that paint effect. + dab(&mut s).unwrap(); + assert_eq!(kinds(&mask(&s)), ["paint", "other"]); +} diff --git a/crates/engine/tests/materialx.rs b/crates/engine/tests/materialx.rs new file mode 100644 index 00000000..35ba658a --- /dev/null +++ b/crates/engine/tests/materialx.rs @@ -0,0 +1,127 @@ +//! `file.exportTextures` with `materialX: true`: a `.mtlx` OpenPBR material next to the textures. + +use serde_json::{Value, json}; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +const OPENPBR: &str = "OpenPBR (separate maps)"; + +/// A scratch folder that is removed when it goes out of scope, so a failing test leaves nothing behind. +struct Scratch(std::path::PathBuf); + +impl std::ops::Deref for Scratch { + type Target = std::path::Path; + fn deref(&self) -> &std::path::Path { + &self.0 + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn temp(tag: &str) -> Scratch { + let dir = std::env::temp_dir().join(format!("tc_mtlx_{tag}_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + Scratch(dir) +} + +fn export(s: &mut Session, dir: &std::path::Path, preset: &str, mtlx: bool) -> Value { + execute(s, "file.exportTextures", &json!({"dir": dir.display().to_string(), "preset": preset, "materialX": mtlx})).unwrap() +} + +fn files(r: &Value) -> Vec { + r["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap().to_string()).collect() +} + +#[test] +fn writes_a_material_that_names_the_exported_textures() { + let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + let dir = temp("ball"); + let r = export(&mut s, &dir, OPENPBR, true); + let all = files(&r); + let mtlx: Vec<&String> = all.iter().filter(|f| f.ends_with(".mtlx")).collect(); + assert_eq!(mtlx.len(), s.set_count(), "one material per texture set: {all:?}"); + for path in mtlx { + let set = path.rsplit(['/', '\\']).next().unwrap().trim_end_matches(".mtlx").to_string(); + let text = std::fs::read_to_string(path).unwrap(); + assert!(text.contains("= 3, "base colour, roughness and normal at least: {text}"); + assert!(text.contains("name=\"base_color\"") && text.contains("name=\"geometry_normal\""), "{text}"); + } +} + +#[test] +fn off_by_default_and_warns_without_openpbr_maps() { + let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + let dir = temp("off"); + assert!(!files(&export(&mut s, &dir, OPENPBR, false)).iter().any(|f| f.ends_with(".mtlx"))); + let dir = temp("other"); + let r = export(&mut s, &dir, "Document channels + Normal + AO", true); + assert!(!files(&r).iter().any(|f| f.ends_with(".mtlx"))); + assert!(r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("OpenPBR")), "{r}"); +} + +#[test] +fn float_colour_maps_are_tagged_linear() { + let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + let dir = temp("exr"); + let r = execute(&mut s, "file.exportTextures", &json!({"dir": dir.display().to_string(), "preset": OPENPBR, "format": "exr", "materialX": true})).unwrap(); + let mtlx = files(&r).into_iter().find(|f| f.ends_with(".mtlx")).unwrap(); + let text = std::fs::read_to_string(mtlx).unwrap(); + assert!(text.contains("_base_color.exr\" colorspace=\"lin_rec709\"") && !text.contains("srgb_texture"), "{text}"); +} + +#[test] +fn colour_maps_are_tagged_with_the_export_colour_space() { + let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + for (space, tag, warns) in [("ACEScg", "acescg", false), ("ACES2065-1", "lin_ap0_scene", true), ("sRGB", "srgb_texture", false)] { + let dir = temp(tag); + let r = execute( + &mut s, + "file.exportTextures", + &json!({"dir": dir.display().to_string(), "preset": OPENPBR, "format": "exr", "colorSpace": space, "materialX": true}), + ) + .unwrap(); + let mtlx = files(&r).into_iter().find(|f| f.ends_with(".mtlx")).unwrap(); + let text = std::fs::read_to_string(mtlx).unwrap(); + assert!(text.contains(&format!("_base_color.exr\" colorspace=\"{tag}\"")), "{space}: {text}"); + let warned = r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("ACES2065-1")); + assert_eq!(warned, warns, "{space}: {r}"); + } +} + +#[test] +fn sets_with_the_same_file_name_warn_instead_of_overwriting() { + let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + assert!(s.set_count() >= 2); + execute(&mut s, "textureSet.rename", &json!({"ts": 0, "name": "a b"})).unwrap(); + execute(&mut s, "textureSet.rename", &json!({"ts": 1, "name": "A_B"})).unwrap(); + let dir = temp("clash"); + let r = execute(&mut s, "file.exportTextures", &json!({"dir": dir.display().to_string(), "preset": OPENPBR, "ts": "all", "materialX": true})).unwrap(); + assert_eq!(files(&r).iter().filter(|f| f.ends_with(".mtlx")).count(), s.set_count() - 1, "{r}"); + assert!(r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("\"A_B\"")), "{r}"); +} + +#[test] +fn udim_sets_use_the_udim_token() { + let mut s = Session::new_project("t", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap(); + let dir = temp("udim"); + let r = export(&mut s, &dir, OPENPBR, true); + let all = files(&r); + let mtlx = all.iter().find(|f| f.ends_with(".mtlx")).unwrap_or_else(|| panic!("no .mtlx in {all:?}")); + let text = std::fs::read_to_string(mtlx).unwrap(); + assert!(text.contains(".<UDIM>.png"), "{text}"); + assert!(!text.contains(".1001.") && !text.contains(".1002."), "{text}"); + assert!(all.iter().any(|f| f.ends_with(".1001.png")) && all.iter().any(|f| f.ends_with(".1002.png"))); +} diff --git a/crates/engine/tests/painter_gaps.rs b/crates/engine/tests/painter_gaps.rs index 960cf344..f6fbfdc2 100644 --- a/crates/engine/tests/painter_gaps.rs +++ b/crates/engine/tests/painter_gaps.rs @@ -1,6 +1,6 @@ //! The filter library, geometry decals, cloning from the selected layer, placing saved smart -//! materials, anchors inside a content stack and instances across texture set resolutions, -//! through engine commands. +//! materials, anchors inside a content stack, instances across texture set resolutions and mesh +//! maps from images, through engine commands. use serde_json::{Value, json}; use texturecraft_engine::core::{Channel, EffectKind, Filter, LayerId, LayerKind, Projection}; @@ -67,6 +67,7 @@ fn filter_library_adds_every_filter_and_edits_its_parameters() { "mosaic", "glow", "bakedLighting", + "replaceColor", ] { assert!(ids.contains(&want), "{want} missing from {ids:?}"); } @@ -151,6 +152,19 @@ fn geometry_masks_limit_layers_to_mesh_parts() { assert!(texel(&mut s, 0.1, 0.9) && texel(&mut s, 0.6, 0.4)); } +#[test] +fn solo_keeps_one_material_channel() { + let mut s = session(); + let r = execute(&mut s, "tool.material", &json!({"channel": "roughness", "solo": true})).unwrap(); + assert_eq!(r["enabled"], json!(["roughness"]), "the brush paints roughness only"); + let fill = id(execute(&mut s, "layer.add.fill", &Value::Null).unwrap(), "layer"); + assert!(s.doc.project.layer(fill).unwrap().channels.len() > 1); + execute(&mut s, "layer.fill.set", &json!({"channel": "metallic", "solo": true})).unwrap(); + assert_eq!(s.doc.project.layer(fill).unwrap().channels.keys().copied().collect::>(), [Channel::Metallic]); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert!(s.doc.project.layer(fill).unwrap().channels.len() > 1, "one undo step"); +} + #[test] fn decals_project_an_image_from_a_frame_placed_on_the_surface() { let mut s = session(); @@ -187,6 +201,26 @@ fn decals_project_an_image_from_a_frame_placed_on_the_surface() { assert!(!red(at(&mut s, Channel::BaseColor, 170.0, 180.0))); } +#[test] +fn a_decal_takes_its_up_from_the_params_or_a_rule_that_never_degenerates() { + let mut s = session(); + let name = s.import_resource_bytes("logo.png", png(8, 4, |x, _| if x < 4 { [255, 0, 0, 255] } else { [0, 0, 255, 255] })).unwrap(); + let top = json!({"image": name, "position": [0.0, 1.0, 0.0], "normal": [0.0, 1.0, 0.0]}); + let up = |r: &Value| [0, 1, 2].map(|i| r["decal"]["up"][i].as_f64().unwrap() as f32); + let mut with_up = top.clone(); + with_up["up"] = json!([0.0, 0.0, -1.0]); + assert_eq!(up(&execute(&mut s, "layer.add.decal", &with_up).unwrap()), [0.0, 0.0, -1.0]); + with_up["up"] = json!([0.0, 2.0, 0.0]); + assert!(execute(&mut s, "layer.add.decal", &with_up).is_err(), "an up along the normal is refused"); + // A level camera's up is the top face's normal: the decal's up is where the camera looks. + execute(&mut s, "camera.set", &json!({"yaw": 90.0, "pitch": 0.0})).unwrap(); + let forward = s.camera.view().inverse().transform_vector3(texturecraft_engine::geom::glam::Vec3::NEG_Z); + let u = up(&execute(&mut s, "layer.add.decal", &top).unwrap()); + assert!((texturecraft_engine::geom::glam::Vec3::from(u) - forward).length() < 1e-4, "{u:?} vs {forward}"); + let r = execute(&mut s, "layer.decal.set", &json!({"up": [1.0, 0.0, 0.0]})).unwrap(); + assert_eq!(up(&r), [1.0, 0.0, 0.0]); +} + #[test] fn clone_copies_the_selected_layer_alone_when_asked() { let mut s = session(); @@ -341,3 +375,37 @@ fn geometry_mask_tool_toggles_the_clicked_part() { assert_eq!(s.doc.project.layer(layer).unwrap().geometry_mask, Some(vec!["Lid".to_string()])); assert!(execute(&mut s, "tool.click", &json!({"x": 1, "y": 1})).is_err(), "nothing under the point"); } + +#[test] +fn images_fill_mesh_map_slots() { + use texturecraft_engine::core::BakedMap; + let mut s = session(); + // Dark on the left, light on the right. + let ao = s.import_resource_bytes("ao.png", png(8, 8, |x, _| if x < 4 { [64, 64, 64, 255] } else { [192, 192, 192, 255] })).unwrap(); + let r = execute(&mut s, "textureSet.meshMap.set", &json!({"map": "ambient_occlusion", "image": ao})).unwrap(); + let res = s.doc.project.texture_sets[0].bake.resolution; + assert_eq!(r, json!({"map": "ambient_occlusion", "resolution": res})); + assert!(s.doc.project.texture_sets[0].baked.contains(&BakedMap::AmbientOcclusion)); + let sample = |s: &Session, m: BakedMap, x: u32| s.baked(0).unwrap().sample(m, x, 50, 100).unwrap(); + assert!((sample(&s, BakedMap::AmbientOcclusion, 10)[0] - 64.0 / 255.0).abs() < 1e-3, "raw file values, not linearized"); + assert!((sample(&s, BakedMap::AmbientOcclusion, 90)[0] - 192.0 / 255.0).abs() < 1e-3); + // A normal map is read in the project's normal format (DirectX: green flipped). + execute(&mut s, "textureSet.settings", &json!({"normalFormat": "directX"})).unwrap(); + let n = s.import_resource_bytes("n.png", png(2, 2, |_, _| [128, 64, 255, 255])).unwrap(); + execute(&mut s, "textureSet.meshMap.set", &json!({"map": "normal", "image": n})).unwrap(); + let v = sample(&s, BakedMap::Normal, 50); + assert!((v[1] - (1.0 - 64.0 / 255.0)).abs() < 1e-3 && (v[2] - 1.0).abs() < 1e-3, "{v:?}"); + // Clearing empties the slot (one undo step); bad params are errors. + execute(&mut s, "textureSet.meshMap.clear", &json!({"map": "ambient_occlusion"})).unwrap(); + assert!(s.baked(0).unwrap().sample(BakedMap::AmbientOcclusion, 0, 0, 100).is_none()); + assert!(!s.doc.project.texture_sets[0].baked.contains(&BakedMap::AmbientOcclusion)); + assert!(execute(&mut s, "textureSet.meshMap.clear", &json!({"map": "ambient_occlusion"})).is_err(), "already empty"); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert!(s.doc.project.texture_sets[0].baked.contains(&BakedMap::AmbientOcclusion)); + assert!(execute(&mut s, "textureSet.meshMap.set", &json!({"map": "nope", "image": ao})).is_err()); + assert!(execute(&mut s, "textureSet.meshMap.set", &json!({"map": "curvature", "image": "missing.png"})).is_err()); + assert!(execute(&mut s, "textureSet.meshMap.set", &json!({"map": "curvature"})).is_err()); + // The maps are saved with the project. + let back = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); + assert_eq!(back.doc.baked, s.doc.baked); +} diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 45ae667d..02be7a8d 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -54,6 +54,45 @@ fn layers_masks_materials_and_bake() { assert_eq!(s.doc.project.walk(0).len(), 1, "back to the initial paint layer"); } +#[test] +fn layer_rename_and_undo() { + let mut s = session(); + let layer_id = s.selected_layer().unwrap(); + let orig_name = s.doc.project.layer(layer_id).unwrap().name.clone(); + execute(&mut s, "layer.rename", &json!({"name": "Custom Paint"})).unwrap(); + assert_eq!(s.doc.project.layer(layer_id).unwrap().name, "Custom Paint"); + + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(s.doc.project.layer(layer_id).unwrap().name, orig_name); + + execute(&mut s, "edit.redo", &Value::Null).unwrap(); + assert_eq!(s.doc.project.layer(layer_id).unwrap().name, "Custom Paint"); +} + +#[test] +fn undo_and_redo_jump_several_steps() { + let mut s = session(); + let layer = s.selected_layer().unwrap(); + let name = |s: &Session| s.doc.project.layer(layer).unwrap().name.clone(); + let first = name(&s); + for n in ["A", "B", "C"] { + execute(&mut s, "layer.rename", &json!({"name": n})).unwrap(); + } + let base = s.history_labels().len() - 3; + // Two back to "A": the undone steps wait to be redone, next first. + assert_eq!(execute(&mut s, "edit.undo", &json!({"steps": 2})).unwrap(), json!({"undone": "Rename layer", "steps": 2})); + assert_eq!(name(&s), "A"); + assert_eq!(s.redo_labels().len(), 2); + assert_eq!(execute(&mut s, "edit.history", &Value::Null).unwrap()["redo"].as_array().unwrap().len(), 2); + // Forward past the end stops at "C"; back past the start stops at the first state. + assert_eq!(execute(&mut s, "edit.redo", &json!({"steps": 99})).unwrap()["steps"], 2); + assert_eq!(name(&s), "C"); + let r = execute(&mut s, "edit.undo", &json!({"steps": 1_000_000})).unwrap(); + assert_eq!(r["steps"].as_u64().unwrap() as usize, base + 3); + assert_eq!(name(&s), first); + assert!(execute(&mut s, "edit.undo", &json!({"steps": 2})).is_err(), "nothing left to undo"); +} + #[test] fn polygon_fill_and_color_picker() { let mut s = session(); @@ -150,6 +189,55 @@ fn image_resources_fill_layers_and_round_trip() { assert!(s.import_resource_bytes("bad.png", vec![1, 2, 3]).is_err()); } +#[test] +fn brush_presets_apply_save_and_load() { + let mut s = session(); + let list = execute(&mut s, "brush.preset.list", &Value::Null).unwrap(); + assert!(list.as_array().unwrap().len() >= 12); + execute(&mut s, "tool.brush", &json!({"size": 30})).unwrap(); + let b = execute(&mut s, "brush.preset.apply", &json!({"preset": "Scratches"})).unwrap(); + assert_eq!((b["alpha"]["library"].as_str(), b["followPath"].as_bool()), (Some("scratches"), Some(true))); + assert!((b["size"].as_f64().unwrap() - 30.0).abs() < 1e-3, "presets keep the size"); + assert!(execute(&mut s, "tool.stroke", &json!({"points": [[160, 200], [240, 200]]})).unwrap()["stamps"].as_u64().unwrap() > 0); + // Saved and loaded back onto another brush, the stroke returns and the size stays. + let path = std::env::temp_dir().join(format!("tc-brush-{}.tcbrush", std::process::id())); + let path = path.to_str().unwrap(); + execute(&mut s, "brush.preset.save", &json!({"path": path})).unwrap(); + execute(&mut s, "brush.preset.apply", &json!({"preset": "basic_soft"})).unwrap(); + execute(&mut s, "tool.brush", &json!({"size": 10})).unwrap(); + let b = execute(&mut s, "brush.preset.load", &json!({"path": path})).unwrap(); + assert_eq!(b["alpha"]["library"], "scratches"); + assert!((b["size"].as_f64().unwrap() - 10.0).abs() < 1e-3); + std::fs::write(path, b"{}").unwrap(); + assert!(execute(&mut s, "brush.preset.load", &json!({"path": path})).is_err()); + let _ = std::fs::remove_file(path); + for bad in [json!({}), json!({"preset": "nope"})] { + assert!(execute(&mut s, "brush.preset.apply", &bad).is_err()); + } +} + +#[test] +fn text_becomes_a_brush_alpha_and_a_decal() { + let mut s = session(); + let fonts = execute(&mut s, "text.fonts", &Value::Null).unwrap(); + assert_eq!(fonts["builtIn"][0], "Ubuntu Light"); + let r = execute(&mut s, "resource.text", &json!({"text": "TEXT\nCRAFT", "font": "ubuntu light", "size": 64})).unwrap(); + let name = r["name"].as_str().unwrap().to_string(); + assert_eq!(name, "Text_TEXT.png"); + assert!(r["width"].as_u64().unwrap() > r["height"].as_u64().unwrap() / 2, "two short lines"); + // White with the glyphs in alpha. + let img = s.images[&name].clone(); + assert!(img.rgba.iter().any(|t| t[3] > 0.99) && img.rgba.iter().any(|t| t[3] == 0.0) && img.rgba.iter().all(|t| t[0] == 1.0)); + // As the brush alpha it paints (keeping its proportions), and it places as a decal. + execute(&mut s, "tool.material", &json!({"channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap(); + execute(&mut s, "tool.brush", &json!({"size": 40, "alpha": {"image": name}})).unwrap(); + assert!(execute(&mut s, "tool.click", &json!({"x": 200, "y": 200})).is_ok()); + assert!(execute(&mut s, "layer.add.decal", &json!({"image": name})).unwrap()["layer"].as_u64().is_some()); + for bad in [json!({}), json!({"text": " "}), json!({"text": "x", "font": "No Such Font"})] { + assert!(execute(&mut s, "resource.text", &bad).is_err(), "{bad}"); + } +} + #[test] fn projection_tool_paints_the_stencil_colors() { let mut s = session(); diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index d5ff31c6..e4010f20 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -20,7 +20,7 @@ use serde::{Deserialize, Serialize}; use texturecraft_compose::{BakedMaps, Composite}; use texturecraft_core::{AoMixing, BakedMap, Channel, ChannelKind, NormalFormat, NormalMixing, Project, TextureSet}; use texturecraft_geom::glam::Vec3; -use texturecraft_texel::{DilationMap, linear_to_srgb}; +use texturecraft_texel::{ColorSpace, DilationMap, linear_to_srgb}; use crate::{FormatError, MAX_IMAGE_SIZE, Result}; @@ -41,7 +41,7 @@ pub const FILE_TOKENS: [(&str, &str); 6] = [ ("$textureSet", "Texture set name"), ("$project", "Project name"), ("$channel", "Channel or map id"), - ("$colorSpace", "sRGB or linear"), + ("$colorSpace", "Colour maps: sRGB, linear, ACEScg or ACES2065-1; data maps: linear"), ("$udim", "UV tile number (1001 for sets without UV tiles)"), ]; @@ -323,11 +323,31 @@ pub struct ExportOptions { /// UV-tiled sets: one image of the whole tile atlas per map instead of a file per tile /// (for formats without UDIM support, with the mesh's UVs in atlas space). pub atlas: bool, + /// The colour space of the colour maps (data maps are never converted); None writes sRGB + /// into 8/16-bit files and linear Rec.709 into float files (EXR, HDR). + #[serde(skip)] + pub color_space: Option, +} + +impl ExportOptions { + /// The colour space colour maps are written in when `format` is used. + pub fn space_for(&self, format: FileFormat) -> ColorSpace { + self.color_space.unwrap_or(if format.is_float() { ColorSpace::LinearRec709 } else { ColorSpace::Srgb }) + } } impl ExportOptions { pub fn new(preset: ExportPreset) -> ExportOptions { - ExportOptions { preset, format_override: None, bit_depth_override: None, padding: Padding::Infinite, size: None, normal_format: None, atlas: false } + ExportOptions { + preset, + format_override: None, + bit_depth_override: None, + padding: Padding::Infinite, + size: None, + normal_format: None, + atlas: false, + color_space: None, + } } } @@ -462,7 +482,14 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export } let format = opts.format_override.unwrap_or(map.format); let bit_depth = format.depth(opts.bit_depth_override.unwrap_or(map.bit_depth)); - let color_space = if is_color(map) && !format.is_float() { "sRGB" } else { "linear" }; + let space = opts.space_for(format); + let color_space = match (is_color(map), space) { + (false, _) | (true, ColorSpace::LinearRec709) => "linear", + (true, ColorSpace::Srgb) => "sRGB", + (true, other) => other.name(), + }; + // Integer files clamp to 0-1, which wide-gamut linear colour can leave. + let clamps = is_color(map) && !format.is_float() && matches!(space, ColorSpace::AcesCg | ColorSpace::Aces2065); // One file per UV tile: names without `$udim` get it appended. let template = if tiles.iter().any(Option::is_some) && !map.file.contains("$udim") { format!("{}.$udim", map.file) } else { map.file.clone() }; for &tile in &tiles { @@ -477,6 +504,13 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export let ext = format.extension(); let mut name = format!("{stem}.{ext}"); let mut warnings = Vec::new(); + if clamps { + warnings.push(format!( + "{} colours outside 0-1 are clamped in {} files; use EXR or HDR to keep them", + space.name(), + format.extension().to_uppercase() + )); + } // Case-insensitive: Windows and macOS file systems are. let mut k = 2; while used.contains(&name.to_ascii_lowercase()) { @@ -697,8 +731,23 @@ pub fn render_maps(input: &ExportInput, opts: &ExportOptions) -> Result = lay.iter().map(|(d, _)| *d != Dest::A && is_color(map) && !p.format.is_float()).collect(); + // Colour maps leave linear Rec.709 for the chosen space. sRGB in integer files is + // encoded by `encode`; every other case is converted here (float sRGB included). + let space = opts.space_for(p.format); + let rgb = lay.len() >= 3 && lay.iter().take(3).map(|(d, _)| *d).eq([Dest::R, Dest::G, Dest::B]); + let mut data = data; let mut warnings = p.warnings; + let convert = is_color(map) && (space != ColorSpace::Srgb || p.format.is_float()) && space != ColorSpace::LinearRec709; + if convert && rgb { + data.par_chunks_mut(n).for_each(|px| { + if let [r, g, b, ..] = px { + [*r, *g, *b] = space.from_linear_rec709([*r, *g, *b]); + } + }); + } else if convert { + warnings.push(format!("\"{}\" packs colour into one channel (L), so it is written in linear Rec.709, not {}", p.name, space.name())); + } + let srgb: Vec = lay.iter().map(|(d, _)| *d != Dest::A && is_color(map) && !p.format.is_float() && space == ColorSpace::Srgb).collect(); let bytes = encode(p.format, p.bit_depth, size, n, &data, &srgb, &mut warnings)?; Ok(ExportedFile { name: p.name, bytes, width: size.0, height: size.1, warnings }) }) diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index c8c53407..c4966585 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -509,3 +509,91 @@ fn lobe_channels_export_as_document_maps_and_gltf_extension_maps() { let plain = Fx::new(&default_channels()).render_preset("glTF PBR Metal Roughness"); assert!(!plain.iter().any(|f| f.name.contains("Clearcoat") || f.name.contains("Sheen")), "sets without the lobes export no extension maps"); } + +#[test] +fn colour_space_converts_colour_maps_only() { + let fx = Fx::new(&default_channels()); + let preset = builtin_preset("glTF PBR Metal Roughness").unwrap(); + let want_at = |space: ColorSpace, x, y| space.from_linear_rec709(fx.comp.value(Channel::BaseColor, x, y)); + // ACEScg in a float EXR: the base colour is the converted triple, above-1 values aside. + let mut exr = ExportOptions::new(preset.clone()); + exr.format_override = Some(FileFormat::Exr); + exr.bit_depth_override = Some(32); + exr.color_space = Some(ColorSpace::AcesCg); + let files = fx.render(&exr); + let img = decode(find(&files, "_BaseColor.exr")).to_rgb32f(); + for (x, y) in [(0, 0), (10, 40), (63, 63)] { + let (px, want) = (img.get_pixel(x, y), want_at(ColorSpace::AcesCg, x, y)); + assert!((0..3).all(|k| (px[k] - want[k]).abs() < 1e-4), "({x},{y}) {px:?} vs {want:?}"); + } + // Data maps are never converted: roughness and metalness (packed in the ORM map) are as before. + let default_files = + fx.render(&ExportOptions { format_override: Some(FileFormat::Exr), bit_depth_override: Some(32), ..ExportOptions::new(preset.clone()) }); + assert_eq!(find(&files, "OcclusionRoughnessMetallic").bytes, find(&default_files, "OcclusionRoughnessMetallic").bytes); + assert_eq!(find(&files, "_Normal").bytes, find(&default_files, "_Normal").bytes); + assert_ne!(find(&files, "_BaseColor").bytes, find(&default_files, "_BaseColor").bytes); + + // Linear Rec.709 in an 8-bit PNG: the values are written without the sRGB curve. + let mut lin = ExportOptions::new(preset.clone()); + lin.color_space = Some(ColorSpace::LinearRec709); + let png = decode(find(&fx.render(&lin), "_BaseColor.png")); + let v = fx.comp.value(Channel::BaseColor, 10, 40); + for k in 0..3 { + assert!((png.get_pixel(10, 40)[k] as f32 - v[k] * 255.0).abs() <= 1.0, "[{k}]"); + } + // The default is unchanged: sRGB for integer files (None and explicit sRGB agree). + let default_png = fx.render(&ExportOptions::new(preset.clone())); + let mut srgb = ExportOptions::new(preset.clone()); + srgb.color_space = Some(ColorSpace::Srgb); + assert_eq!(find(&default_png, "_BaseColor.png").bytes, find(&fx.render(&srgb), "_BaseColor.png").bytes); + // An explicit sRGB in a float file is encoded once, not twice. + let mut float_srgb = ExportOptions::new(preset); + float_srgb.format_override = Some(FileFormat::Exr); + float_srgb.bit_depth_override = Some(32); + float_srgb.color_space = Some(ColorSpace::Srgb); + let px = *decode(find(&fx.render(&float_srgb), "_BaseColor.exr")).to_rgb32f().get_pixel(10, 40); + assert!((px[0] - linear_to_srgb(v[0])).abs() < 1e-4, "{px:?}"); +} + +#[test] +fn colour_space_names_the_files_and_warns_when_integer_files_clamp() { + let fx = Fx::new(&default_channels()); + let named = ExportPreset { + name: "named".into(), + maps: vec![MapSpec { + file: "$textureSet_$channel_$colorSpace".into(), + format: FileFormat::Png, + bit_depth: 8, + channels: vec![ + (Dest::R, SourceRef::Channel { channel: Channel::BaseColor, component: 0 }), + (Dest::G, SourceRef::Channel { channel: Channel::BaseColor, component: 1 }), + (Dest::B, SourceRef::Channel { channel: Channel::BaseColor, component: 2 }), + ], + }], + }; + let plan = |space: Option, format: Option| { + let opts = ExportOptions { color_space: space, format_override: format, ..ExportOptions::new(named.clone()) }; + list_outputs(&fx.project, 0, "sphere", &opts).unwrap().remove(0) + }; + assert!(plan(None, None).name.ends_with("_sRGB.png") && plan(None, Some(FileFormat::Exr)).name.ends_with("_linear.exr"), "defaults keep their names"); + assert!(plan(Some(ColorSpace::LinearRec709), None).name.ends_with("_linear.png")); + let aces = plan(Some(ColorSpace::AcesCg), None); + assert!(aces.name.ends_with("_ACEScg.png"), "{}", aces.name); + assert!(aces.warnings.iter().any(|w| w.contains("clamped")), "{:?}", aces.warnings); + assert!(plan(Some(ColorSpace::AcesCg), Some(FileFormat::Exr)).warnings.is_empty(), "float files keep the values"); + assert!(plan(None, None).warnings.is_empty() && plan(Some(ColorSpace::LinearRec709), None).warnings.is_empty()); + // The planned names are the rendered names. + let opts = ExportOptions { color_space: Some(ColorSpace::Aces2065), ..ExportOptions::new(named) }; + let names: Vec = fx.render(&opts).into_iter().map(|f| f.name).collect(); + assert_eq!(names, list_outputs(&fx.project, 0, "sphere", &opts).unwrap().into_iter().map(|p| p.name).collect::>()); + assert!(names[0].ends_with("_ACES2065-1.png"), "{names:?}"); +} + +#[test] +fn colour_packed_into_one_channel_warns_instead_of_converting_silently() { + let fx = Fx::new(&default_channels()); + let preset = ExportPreset { name: "l".into(), maps: vec![gray_map("$textureSet_red", SourceRef::Channel { channel: Channel::BaseColor, component: 0 })] }; + let opts = |space| ExportOptions { color_space: space, format_override: Some(FileFormat::Exr), ..ExportOptions::new(preset.clone()) }; + assert!(fx.render(&opts(Some(ColorSpace::AcesCg)))[0].warnings.iter().any(|w| w.contains("ACEScg"))); + assert!(fx.render(&opts(None))[0].warnings.is_empty(), "linear Rec.709 needs no conversion"); +} diff --git a/crates/formats/src/fonts.rs b/crates/formats/src/fonts.rs new file mode 100644 index 00000000..b047ba49 --- /dev/null +++ b/crates/formats/src/fonts.rs @@ -0,0 +1,197 @@ +//! Installed fonts, for text alphas: the faces (family and style) of every TrueType or OpenType +//! file (and collection) in the system's font folders, read from each file's `name` table only, +//! so listing hundreds of fonts stays quick. Native only; the browser has no font folders. + +use std::io::{Read, Seek, SeekFrom}; +use std::path::{Path, PathBuf}; + +/// One face of an installed font file. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub struct FontFace { + pub family: String, + pub style: String, + pub path: PathBuf, + /// Face index in a collection (`.ttc`), else 0. + pub index: u32, +} + +/// Files and faces visited at most (a font folder is never this large, a wrong one may be). +const MAX_FILES: usize = 20_000; +const MAX_FACES_PER_FILE: u32 = 64; +const MAX_NAME_TABLE: u32 = 1 << 20; + +/// The installed fonts' faces, sorted by family then style. +pub fn system_fonts() -> Vec { + let mut files = Vec::new(); + for dir in font_dirs() { + collect(&dir, 0, &mut files); + } + let mut faces: Vec = files.iter().flat_map(|p| faces_of(p).unwrap_or_default()).collect(); + faces.sort(); + faces.dedup_by(|a, b| a.family == b.family && a.style == b.style); + faces +} + +fn font_dirs() -> Vec { + let home = std::env::var_os("HOME").map(PathBuf::from); + if cfg!(windows) { + let mut v = vec![PathBuf::from(std::env::var_os("WINDIR").unwrap_or_else(|| "C:\\Windows".into())).join("Fonts")]; + v.extend(std::env::var_os("LOCALAPPDATA").map(|d| PathBuf::from(d).join("Microsoft\\Windows\\Fonts"))); + v + } else if cfg!(target_os = "macos") { + let mut v = vec![PathBuf::from("/System/Library/Fonts"), PathBuf::from("/Library/Fonts")]; + v.extend(home.map(|h| h.join("Library/Fonts"))); + v + } else { + let mut v = vec![PathBuf::from("/usr/share/fonts"), PathBuf::from("/usr/local/share/fonts")]; + v.extend(home.iter().flat_map(|h| [h.join(".local/share/fonts"), h.join(".fonts")])); + v + } +} + +/// Font files under `dir` (a few levels deep). +fn collect(dir: &Path, depth: usize, out: &mut Vec) { + let Ok(entries) = std::fs::read_dir(dir) else { return }; + for e in entries.flatten() { + if out.len() >= MAX_FILES { + return; + } + let path = e.path(); + match e.file_type() { + Ok(t) if t.is_dir() && depth < 4 => collect(&path, depth + 1, out), + Ok(t) if t.is_file() => { + let ext = path.extension().and_then(|x| x.to_str()).unwrap_or_default().to_ascii_lowercase(); + if matches!(ext.as_str(), "ttf" | "otf" | "ttc" | "otc") { + out.push(path); + } + } + _ => {} + } + } +} + +/// The faces of the font file at `path` (each face of a collection). +pub fn faces_of(path: &Path) -> std::io::Result> { + let mut f = std::fs::File::open(path)?; + let mut at = |offset: u64, len: usize| -> std::io::Result> { + f.seek(SeekFrom::Start(offset))?; + let mut buf = vec![0; len]; + f.read_exact(&mut buf)?; + Ok(buf) + }; + let head = at(0, 12)?; + let offsets: Vec = if head.get(..4) == Some(b"ttcf") { + let n = u32_at(&head, 8).unwrap_or(0).min(MAX_FACES_PER_FILE); + let table = at(12, 4 * n as usize)?; + (0..n as usize).filter_map(|i| u32_at(&table, 4 * i)).map(u64::from).collect() + } else { + vec![0] + }; + let mut faces = Vec::new(); + for (index, offset) in offsets.into_iter().enumerate() { + let dir = at(offset, 12)?; + let tables = at(offset + 12, 16 * usize::from(u16_at(&dir, 4).unwrap_or(0)))?; + let Some(rec) = tables.chunks_exact(16).find(|r| r.get(..4) == Some(b"name")) else { continue }; + let (Some(off), Some(len)) = (u32_at(rec, 8), u32_at(rec, 12)) else { continue }; + let names = at(u64::from(off), len.min(MAX_NAME_TABLE) as usize)?; + let name = |ids: [u16; 2]| ids.iter().find_map(|id| name_string(&names, *id)); + if let Some(family) = name([16, 1]) { + let style = name([17, 2]).unwrap_or_else(|| "Regular".into()); + faces.push(FontFace { family, style, path: path.to_path_buf(), index: index as u32 }); + } + } + Ok(faces) +} + +fn u16_at(b: &[u8], o: usize) -> Option { + Some(u16::from_be_bytes(b.get(o..o.checked_add(2)?)?.try_into().ok()?)) +} + +fn u32_at(b: &[u8], o: usize) -> Option { + Some(u32::from_be_bytes(b.get(o..o.checked_add(4)?)?.try_into().ok()?)) +} + +/// Name `id` of a `name` table, in English when it has several languages: Windows and Unicode +/// records are UTF-16BE, Macintosh ones single-byte (read as Latin-1). +fn name_string(t: &[u8], id: u16) -> Option { + let (count, base) = (usize::from(u16_at(t, 2)?), usize::from(u16_at(t, 4)?)); + let mut best: Option<(u8, String)> = None; + for r in (0..count).filter_map(|i| t.get(6 + 12 * i..18 + 12 * i)) { + let (platform, language, name_id) = (u16_at(r, 0)?, u16_at(r, 4)?, u16_at(r, 6)?); + let (len, off) = (usize::from(u16_at(r, 8)?), usize::from(u16_at(r, 10)?)); + let Some(bytes) = t.get(base + off..base + off + len) else { continue }; + if name_id != id { + continue; + } + let (rank, s) = match platform { + 3 | 0 => { + let s = String::from_utf16_lossy(&bytes.chunks_exact(2).map(|c| u16::from_be_bytes([c[0], c[1]])).collect::>()); + (if language == 0x409 { 0 } else { 1 }, s) + } + 1 => (if language == 0 { 2 } else { 3 }, bytes.iter().map(|b| char::from(*b)).collect()), + _ => continue, + }; + let s = s.trim().to_string(); + if !s.is_empty() && best.as_ref().is_none_or(|(r, _)| rank < *r) { + best = Some((rank, s)); + } + } + best.map(|(_, s)| s) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A `name` table with the given (platform, language, name id, bytes) records. + fn name_table(records: &[(u16, u16, u16, Vec)]) -> Vec { + let base = 6 + 12 * records.len(); + let mut t: Vec = [0u16, records.len() as u16, base as u16].iter().flat_map(|v| v.to_be_bytes()).collect(); + let mut strings: Vec = Vec::new(); + for (platform, language, id, bytes) in records { + for v in [*platform, 1, *language, *id, bytes.len() as u16, strings.len() as u16] { + t.extend(v.to_be_bytes()); + } + strings.extend(bytes); + } + t.extend(strings); + t + } + + fn utf16(s: &str) -> Vec { + s.encode_utf16().flat_map(u16::to_be_bytes).collect() + } + + #[test] + fn names_prefer_english_windows_records() { + let t = + name_table(&[(1, 0, 1, b"Mac Name".to_vec()), (3, 0x407, 1, utf16("Deutsch")), (3, 0x409, 1, utf16("Plain Sans")), (3, 0x409, 2, utf16("Bold"))]); + assert_eq!(name_string(&t, 1).as_deref(), Some("Plain Sans")); + assert_eq!(name_string(&t, 2).as_deref(), Some("Bold")); + assert_eq!(name_string(&t, 16), None); + // Truncated or hostile tables give nothing rather than panicking. + for n in 0..t.len() { + let _ = name_string(&t[..n], 1); + } + assert_eq!(name_string(&[0xff; 64], 1), None); + } + + #[test] + fn faces_of_a_file_and_garbage() { + let dir = std::env::temp_dir().join(format!("tc-fonts-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("font.ttf"); + // A font file with only a name table: offset table, one table record, the table. + let names = name_table(&[(3, 0x409, 1, utf16("Plain Sans")), (3, 0x409, 2, utf16("Italic"))]); + let mut file: Vec = [0x0001_0000u32.to_be_bytes().to_vec(), 1u16.to_be_bytes().to_vec(), vec![0; 6]].concat(); + file.extend(b"name"); + file.extend([0u32, 28, names.len() as u32].iter().flat_map(|v| v.to_be_bytes())); + file.extend(&names); + std::fs::write(&path, &file).unwrap(); + let faces = faces_of(&path).unwrap(); + assert_eq!((faces[0].family.as_str(), faces[0].style.as_str(), faces[0].index), ("Plain Sans", "Italic", 0)); + std::fs::write(&path, b"garbage").unwrap(); + assert!(faces_of(&path).is_err() || faces_of(&path).unwrap().is_empty()); + let _ = std::fs::remove_dir_all(dir); + } +} diff --git a/crates/formats/src/image_res.rs b/crates/formats/src/image_res.rs index 9d1a7654..9b67aaf8 100644 --- a/crates/formats/src/image_res.rs +++ b/crates/formats/src/image_res.rs @@ -29,6 +29,17 @@ pub fn decode_image(bytes: &[u8]) -> Result { Ok(DecodedImage { width, height, rgba, srgb }) } +/// PNG bytes of an `rgb` (sRGB) image whose alpha is `coverage` (`width × height`, top row first): +/// drawn text as an image resource. +pub fn coverage_png(width: u32, height: u32, coverage: &[u8], rgb: [u8; 3]) -> Result> { + let rgba: Vec = coverage.iter().flat_map(|a| [rgb[0], rgb[1], rgb[2], *a]).collect(); + let img = image::RgbaImage::from_raw(width, height, rgba) + .ok_or_else(|| FormatError::Invalid(format!("{} coverage values for {width}x{height}", coverage.len())))?; + let mut png = Vec::new(); + img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).map_err(|e| FormatError::Invalid(e.to_string()))?; + Ok(png) +} + #[cfg(test)] mod tests { use super::*; @@ -44,5 +55,8 @@ mod tests { assert!((d.rgba[1][0] - 60.0 / 255.0).abs() < 1e-3); assert!(decode_image(b"not an image").is_err()); assert!(decode_image(&png[..png.len() / 2]).is_err()); + let text = decode_image(&coverage_png(2, 1, &[0, 255], [255; 3]).unwrap()).unwrap(); + assert_eq!(text.rgba, vec![[1.0, 1.0, 1.0, 0.0], [1.0; 4]]); + assert!(coverage_png(2, 2, &[0], [255; 3]).is_err()); } } diff --git a/crates/formats/src/lib.rs b/crates/formats/src/lib.rs index 5d30acdf..0fd12ff4 100644 --- a/crates/formats/src/lib.rs +++ b/crates/formats/src/lib.rs @@ -12,11 +12,13 @@ //! - [`export`]: texture export from a texture set's composite through [`ExportPreset`]s (file //! name templates, channel packing, virtual maps such as the final normal, padding, resizing) //! to PNG, JPEG, TGA, TIFF, BMP, WebP, EXR and HDR bytes. +//! - [`materialx`]: a MaterialX (`.mtlx`) OpenPBR document for an exported texture set. //! - [`mcmat`]: MaterialCraft portable materials (`.mcmat`) and mesh maps as 16-bit PNGs for //! MaterialCraft graph inputs. //! - [`presets`]: the built-in export presets and JSON (de)serialization of user presets. //! - [`project_file`]: the `.tcraft` project zip (project JSON, sparse lossless pixel tiles, //! baked maps, the original mesh and a thumbnail). +//! - `fonts`: the installed fonts' families and styles (native only), for text alphas. //! //! Every reader takes untrusted bytes and returns an error, never panics. Byte-based functions //! work everywhere (including the web build); path-based ones are native only. @@ -24,7 +26,10 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] pub mod export; +#[cfg(not(target_arch = "wasm32"))] +pub mod fonts; pub mod image_res; +pub mod materialx; pub mod mcmat; pub mod mesh_export; pub mod mesh_import; @@ -34,7 +39,7 @@ pub mod project_file; pub use export::{ Dest, ExportInput, ExportOptions, ExportPreset, ExportedFile, FileFormat, MapSpec, Padding, PlannedFile, SourceRef, VirtualMap, list_outputs, render_maps, }; -pub use image_res::{DecodedImage, decode_image}; +pub use image_res::{DecodedImage, coverage_png, decode_image}; pub use mesh_export::{GlbTextures, UsdExport, UsdFormat, glb_bytes, glb_export_options, obj_bytes, usd_bytes, usd_export_options}; pub use mesh_import::{HighPolyMesh, ImportedMesh, MeshFile, MeshReport, import_high_poly_bytes, import_mesh_bytes, self_contained_mesh}; #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/formats/src/materialx.rs b/crates/formats/src/materialx.rs new file mode 100644 index 00000000..e7440328 --- /dev/null +++ b/crates/formats/src/materialx.rs @@ -0,0 +1,299 @@ +//! MaterialX documents for exported texture sets, written from the ASWF MaterialX specification +//! (version 1.39) and the OpenPBR Surface specification. Pure Rust: no MaterialX library is +//! linked, and nothing is read from any other application. +//! +//! [`write`] takes a material's name and the texture files an export produced, each tagged with +//! the OpenPBR input it feeds, and gives the text of a `.mtlx` file: an `open_pbr_surface` shader +//! whose inputs read `tiledimage` nodes, wrapped in a `surfacematerial`. The inputs are the ones +//! the built-in "OpenPBR (separate maps)" export preset writes ([`INPUTS`]); `height` becomes a +//! `displacement` shader on the material and `geometry_normal` goes through a `normalmap` node +//! (OpenGL, +Y up, which is what that node expects). +//! +//! Colour textures (base, fuzz and emission colour) are tagged with the colour space they were +//! exported in ([`colorspace_name`]); every data map is left untagged (linear). UDIM sets write the `` filename token MaterialX defines. +//! Texture file names are relative to the document. + +use std::collections::HashSet; +use std::fmt::Write as _; + +use texturecraft_texel::ColorSpace; + +/// How an OpenPBR input is typed in the document. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + /// `color3` from an sRGB texture. + Color, + /// `float` from a linear texture. + Float, + /// `vector3` through a `normalmap` node. + Normal, + /// `float` driving a `displacement` shader. + Height, +} + +/// The OpenPBR inputs the export writes, in document order. Names are the file-name suffixes of +/// the built-in OpenPBR preset's maps (`$mesh_$textureSet_`). +pub const INPUTS: &[(&str, Kind)] = &[ + ("base_color", Kind::Color), + ("base_metalness", Kind::Float), + ("specular_roughness", Kind::Float), + ("specular_roughness_anisotropy", Kind::Float), + ("coat_weight", Kind::Float), + ("coat_roughness", Kind::Float), + ("fuzz_weight", Kind::Float), + ("fuzz_color", Kind::Color), + ("fuzz_roughness", Kind::Float), + ("transmission_weight", Kind::Float), + ("subsurface_weight", Kind::Float), + ("emission_color", Kind::Color), + ("geometry_opacity", Kind::Float), + ("geometry_normal", Kind::Normal), + ("height", Kind::Height), +]; + +/// The file-name prefix of the built-in OpenPBR preset's maps. +const PREFIX: &str = "$mesh_$textureSet_"; + +/// One exported texture: the OpenPBR input it feeds and the file (relative to the `.mtlx`). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Texture { + pub input: String, + pub file: String, + /// The MaterialX colour space of the file's values (`srgb_texture`, `lin_rec709`, ...); + /// used for colour inputs only, data maps are always linear. + pub colorspace: &'static str, +} + +/// The MaterialX colour space of colour maps written in `space`. MaterialX 1.39 defines no +/// ACES2065-1 (AP0) space: it gets `lin_ap0_scene`, its name in later versions of the +/// specification, which 1.39 readers may not know. +pub fn colorspace_name(space: ColorSpace) -> &'static str { + match space { + ColorSpace::Srgb => "srgb_texture", + ColorSpace::LinearRec709 => "lin_rec709", + ColorSpace::AcesCg => "acescg", + ColorSpace::Aces2065 => "lin_ap0_scene", + } +} + +/// The OpenPBR input a preset map's file template feeds (`$mesh_$textureSet_base_color` → +/// `base_color`), or None for templates this module has no place for. +pub fn input_of_template(template: &str) -> Option<&'static str> { + let suffix = template.strip_prefix(PREFIX)?; + INPUTS.iter().find(|(n, _)| *n == suffix).map(|(n, _)| *n) +} + +fn kind_of(input: &str) -> Option { + INPUTS.iter().find(|(n, _)| *n == input).map(|(_, k)| *k) +} + +/// A MaterialX name: letters, digits and underscores, not starting with a digit. +pub fn node_name(s: &str) -> String { + let mut out: String = s.chars().map(|c| if c.is_ascii_alphanumeric() || c == '_' { c } else { '_' }).collect(); + if out.is_empty() || out.starts_with(|c: char| c.is_ascii_digit()) { + out.insert(0, '_'); + } + out +} + +fn esc(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + for c in s.chars() { + match c { + '&' => out.push_str("&"), + '<' => out.push_str("<"), + '>' => out.push_str(">"), + '"' => out.push_str("""), + '\'' => out.push_str("'"), + c if c.is_control() => out.push(' '), + c => out.push(c), + } + } + out +} + +fn image_name(input: &str) -> String { + format!("image_{}", node_name(input)) +} + +/// The text of a MaterialX document for `name` with the given textures. `physical_size_cm` goes +/// into the material's `doc` attribute. Inputs this module has no place for are skipped, and so +/// are repeats of one input (the first wins). +pub fn write(name: &str, textures: &[Texture], physical_size_cm: Option<[f32; 2]>) -> String { + let base = node_name(name); + let mut seen = HashSet::new(); + let tex: Vec<(&Texture, Kind)> = textures.iter().filter_map(|t| kind_of(&t.input).map(|k| (t, k))).filter(|(t, _)| seen.insert(t.input.as_str())).collect(); + let has = |i: &str| tex.iter().any(|(t, _)| t.input == i); + let mut x = String::new(); + let _ = writeln!(x, ""); + let _ = writeln!(x, ""); + + let shader = format!("OPBR_{base}"); + let _ = writeln!(x, " ", esc(&shader)); + for (t, kind) in &tex { + let (ty, node) = match kind { + Kind::Color => ("color3", image_name(&t.input)), + Kind::Float => ("float", image_name(&t.input)), + Kind::Normal => ("vector3", "normalmap".to_owned()), + Kind::Height => continue, + }; + let _ = writeln!(x, " ", t.input); + } + if has("emission_color") { + let _ = writeln!(x, " "); + } + let _ = writeln!(x, " "); + + for (t, kind) in &tex { + let (ty, space) = match kind { + Kind::Color => ("color3", Some(t.colorspace)), + Kind::Normal => ("vector3", None), + Kind::Float | Kind::Height => ("float", None), + }; + let node = image_name(&t.input); + let _ = writeln!(x, " "); + match space { + Some(space) => { + let _ = writeln!(x, " ", esc(&t.file)); + } + None => { + let _ = writeln!(x, " ", esc(&t.file)); + } + } + let _ = writeln!(x, " "); + } + if has("geometry_normal") { + let _ = writeln!(x, " "); + let _ = writeln!(x, " ", image_name("geometry_normal")); + let _ = writeln!(x, " "); + } + if has("height") { + let _ = writeln!(x, " "); + let _ = writeln!(x, " ", image_name("height")); + let _ = writeln!(x, " "); + let _ = writeln!(x, " "); + } + + let doc = match physical_size_cm { + Some([w, h]) if w.is_finite() && h.is_finite() => format!(" doc=\"Tiles every {w} x {h} cm\""), + _ => String::new(), + }; + let _ = writeln!(x, " ", esc(&base)); + let _ = writeln!(x, " ", esc(&shader)); + if has("height") { + let _ = writeln!(x, " "); + } + let _ = writeln!(x, " "); + let _ = writeln!(x, ""); + x +} + +#[cfg(test)] +mod tests { + use super::*; + + fn tex(input: &str, file: &str) -> Texture { + Texture { input: input.into(), file: file.into(), colorspace: "srgb_texture" } + } + + /// Every start tag is closed or self-closed, in order: enough to catch a malformed writer. + fn balanced(xml: &str) -> bool { + let mut stack: Vec = Vec::new(); + let mut rest = xml; + while let Some(i) = rest.find('<') { + let Some(j) = rest.get(i..).and_then(|r| r.find('>')) else { return false }; + let Some(tag) = rest.get(i + 1..i + j) else { return false }; + rest = rest.get(i + j + 1..).unwrap_or(""); + if tag.starts_with('?') || tag.starts_with('!') { + continue; + } + if let Some(name) = tag.strip_prefix('/') { + if stack.pop().as_deref() != Some(name.trim()) { + return false; + } + } else if !tag.ends_with('/') { + stack.push(tag.split_whitespace().next().unwrap_or("").to_owned()); + } + } + stack.is_empty() + } + + #[test] + fn a_full_material_maps_every_input() { + let t: Vec = INPUTS.iter().map(|(n, _)| tex(n, &format!("stone_{n}.png"))).collect(); + let x = write("Stone", &t, Some([100.0, 50.0])); + assert!(balanced(&x), "{x}"); + for want in [ + "", + "name=\"base_color\" type=\"color3\" nodename=\"image_base_color\"", + "name=\"base_metalness\" type=\"float\" nodename=\"image_base_metalness\"", + "name=\"specular_roughness\" type=\"float\" nodename=\"image_specular_roughness\"", + "name=\"coat_weight\" type=\"float\" nodename=\"image_coat_weight\"", + "name=\"fuzz_color\" type=\"color3\" nodename=\"image_fuzz_color\"", + "name=\"transmission_weight\" type=\"float\"", + "name=\"subsurface_weight\" type=\"float\"", + "name=\"geometry_opacity\" type=\"float\" nodename=\"image_geometry_opacity\"", + "name=\"geometry_normal\" type=\"vector3\" nodename=\"normalmap\"", + "name=\"emission_color\" type=\"color3\" nodename=\"image_emission_color\"", + "name=\"emission_luminance\" type=\"float\" value=\"1\"", + "value=\"stone_base_color.png\" colorspace=\"srgb_texture\"", + "value=\"stone_emission_color.png\" colorspace=\"srgb_texture\"", + "", + "", + "name=\"displacementshader\"", + "", + ] { + assert!(x.contains(want), "missing {want}\n{x}"); + } + // Data textures carry no colour space, and height is not an OpenPBR input. + assert!(x.contains("value=\"stone_specular_roughness.png\" />")); + assert!(!x.contains("name=\"height\"")); + } + + #[test] + fn only_what_is_there_is_written() { + let x = write("m", &[tex("specular_roughness", "r.png")], None); + assert!(balanced(&x)); + assert!(!x.contains("base_color") && !x.contains("normalmap") && !x.contains("displacement") && !x.contains("emission_luminance")); + assert!(x.contains("")); + let none = write("m", &[], None); + assert!(balanced(&none) && none.contains(""), "{x}"); + } + + #[test] + fn unknown_and_repeated_inputs_are_skipped() { + let x = write("m", &[tex("ambient_occlusion", "ao.png"), tex("base_color", "a.png"), tex("base_color", "b.png")], None); + assert!(!x.contains("ao.png") && x.contains("a.png") && !x.contains("b.png")); + } + + #[test] + fn templates_map_to_inputs() { + assert_eq!(input_of_template("$mesh_$textureSet_base_color"), Some("base_color")); + assert_eq!(input_of_template("$mesh_$textureSet_height"), Some("height")); + assert_eq!(input_of_template("$mesh_$textureSet_orm"), None); + assert_eq!(input_of_template("base_color"), None); + for (n, _) in INPUTS { + assert_eq!(input_of_template(&format!("{PREFIX}{n}")), Some(*n)); + } + } + + #[test] + fn udim_tokens_and_hostile_names_are_escaped() { + assert_eq!(node_name("Rough Stone #2"), "Rough_Stone__2"); + assert_eq!(node_name("9lives"), "_9lives"); + assert_eq!(node_name(""), "_"); + let x = write("a&\"c", &[tex("base_color", "x\"&<'>..png")], Some([f32::NAN, 1.0])); + assert!(balanced(&x.replace("<UDIM>", "UDIM")), "{x}"); + assert!(x.contains("value=\"x"&<'>.<UDIM>.png\"")); + assert!(!x.contains("doc="), "a non-finite size is left out"); + assert!(x.contains("OPBR_a_b___c")); + } +} diff --git a/crates/formats/src/mesh_export/usd.rs b/crates/formats/src/mesh_export/usd.rs index 1232373f..1e14039e 100644 --- a/crates/formats/src/mesh_export/usd.rs +++ b/crates/formats/src/mesh_export/usd.rs @@ -83,6 +83,7 @@ pub fn usd_export_options() -> ExportOptions { #[derive(Clone, Debug, PartialEq)] pub(crate) enum UsdValue { Token(String), + Str(String), Int(i32), Double(f64), Asset(String), @@ -277,7 +278,8 @@ fn material(path: &str, id: &str, files: &[(usize, String)]) -> UsdPrim { let mut st = UsdPrim::new("st", "Shader"); st.attrs = vec![ UsdAttr::new("info:id", "token", Some(UsdValue::Token("UsdPrimvarReader_float2".into()))).uniform(), - UsdAttr::new("inputs:varname", "token", Some(UsdValue::Token("st".into()))), + // A string, not a token: usdchecker's ARKit profile refuses a token here. + UsdAttr::new("inputs:varname", "string", Some(UsdValue::Str("st".into()))), UsdAttr::new("outputs:result", "float2", None), ]; mat.children.push(st); @@ -355,7 +357,7 @@ fn usda_value(s: &mut String, v: &UsdValue) { s.push(']'); }; match v { - UsdValue::Token(t) => { + UsdValue::Token(t) | UsdValue::Str(t) => { let _ = write!(s, "\"{t}\""); } UsdValue::Int(i) => { diff --git a/crates/formats/src/mesh_export/usdc.rs b/crates/formats/src/mesh_export/usdc.rs index 3bb987ea..35900e28 100644 --- a/crates/formats/src/mesh_export/usdc.rs +++ b/crates/formats/src/mesh_export/usdc.rs @@ -57,6 +57,18 @@ impl Writer { i } + /// Index of `s` in the string table (which holds token indices). + fn string(&mut self, s: &str) -> u32 { + let t = self.token(s); + match self.strings.iter().position(|x| *x == t) { + Some(i) => i as u32, + None => { + self.strings.push(t); + (self.strings.len() - 1) as u32 + } + } + } + fn add_path(&mut self, parent: usize, parent_text: &str, name: &str, prop: bool) -> (usize, String) { let text = match (prop, parent_text) { (true, _) => format!("{parent_text}.{name}"), @@ -127,6 +139,7 @@ impl Writer { Ok(match v { UsdValue::Token(t) => rep(ty::TOKEN, codec::IS_INLINED, u64::from(self.token(t))), UsdValue::Asset(a) => rep(ty::ASSET_PATH, codec::IS_INLINED, u64::from(self.token(a))), + UsdValue::Str(s) => rep(ty::STRING, codec::IS_INLINED, u64::from(self.string(s))), UsdValue::Int(i) => rep(ty::INT, codec::IS_INLINED, u64::from(*i as u32)), UsdValue::Double(d) => { let at = self.offset(); diff --git a/crates/formats/src/mesh_import/fbx.rs b/crates/formats/src/mesh_import/fbx.rs index 43fea71e..d7dd46fc 100644 --- a/crates/formats/src/mesh_import/fbx.rs +++ b/crates/formats/src/mesh_import/fbx.rs @@ -445,7 +445,7 @@ pub(crate) fn read(bytes: &[u8]) -> Result { if zip.len() > MAX_ZIP_ENTRIES { return Err(FormatError::TooLarge(format!("the FBX package has more than {MAX_ZIP_ENTRIES} entries"))); } - let name = zip.file_names().filter(|n| super::extension(n) == "fbx").min_by_key(|n| zip.index_for_name(n)).map(str::to_string); + let name = zip.file_names().flatten().filter(|n| super::extension(n) == "fbx").min_by_key(|n| zip.index_for_name(n)).map(Cow::into_owned); let name = name.ok_or_else(|| malformed(KIND, "the package contains no FBX file"))?; let fbx = zip_entry(&mut zip, &name, MAX_MESH_FILE_BYTES) .ok_or_else(|| FormatError::TooLarge("the packaged FBX is unreadable or larger than 2 GiB".into()))?; diff --git a/crates/formats/src/mesh_import/mod.rs b/crates/formats/src/mesh_import/mod.rs index 521cab30..361d7837 100644 --- a/crates/formats/src/mesh_import/mod.rs +++ b/crates/formats/src/mesh_import/mod.rs @@ -20,8 +20,8 @@ mod stl; pub(crate) mod tests; pub(crate) mod usd; -use std::collections::HashMap; use std::collections::hash_map::Entry; +use std::collections::{HashMap, HashSet}; use texturecraft_geom::glam::{Mat4, Vec2, Vec3, Vec4}; use texturecraft_geom::unwrap::{all_triangles_degenerate, auto_unwrap, weld_ids}; @@ -134,6 +134,8 @@ pub(crate) struct RawMesh { pub cameras: Vec, /// Materials whose base color is not plain white (glTF). pub base_colors: Vec, + /// Vertex pairs (smaller first) that [`RawMesh::polygon`] added to split polygons. + pub diagonals: HashSet<(u32, u32)>, } /// A material's base color as a file gives it: the linear factor and the encoded texture. @@ -159,6 +161,19 @@ impl RawMesh { pub fn triangle_count(&self) -> usize { self.groups.iter().map(|(_, _, g)| g.len() / 3).sum() } + + /// Fan-triangulate polygon `corners` (vertex indices) into `material`'s triangles in `part`, + /// remembering the diagonals so wireframes can show the polygon. + pub fn polygon(&mut self, material: &str, part: &str, corners: &[u32]) { + let Some((&first, rest)) = corners.split_first() else { return }; + let group = self.group(material, part); + for w in rest.windows(2) { + group.extend_from_slice(&[first, w[0], w[1]]); + } + for &v in rest.iter().skip(1).take(rest.len().saturating_sub(2)) { + self.diagonals.insert((first.min(v), first.max(v))); + } + } } /// One polygon corner of a scene format (FBX, COLLADA), already in world space. @@ -213,11 +228,7 @@ impl PolygonSink { }; self.polygon.push(id); } - let group = self.raw.group(material, &self.part); - let (first, rest) = self.polygon.split_first().unwrap_or((&0, &[])); - for w in rest.windows(2) { - group.extend_from_slice(&[*first, w[0], w[1]]); - } + self.raw.polygon(material, &self.part, &self.polygon); Ok(()) } @@ -365,7 +376,7 @@ fn read(file_name: &str, bytes: &[u8]) -> Result { /// Positions, submeshes (materials contiguous), normals and colors of a raw mesh, validated; /// plus its warnings and UVs (the mesh's UVs and tangents are left empty). fn geometry(raw: RawMesh) -> Result<(Mesh, Vec, Option>)> { - let RawMesh { positions, normals, uvs, colors, groups, warnings, .. } = raw; + let RawMesh { positions, normals, uvs, colors, groups, warnings, diagonals, .. } = raw; check_vertices(positions.len())?; check_triangles(0, groups.iter().map(|(_, _, g)| g.len() / 3).sum())?; let mut mesh = Mesh { positions, ..Mesh::default() }; @@ -390,6 +401,10 @@ fn geometry(raw: RawMesh) -> Result<(Mesh, Vec, Option>)> { if mesh.indices.is_empty() { return Err(FormatError::Invalid("the file contains no triangles".into())); } + if !diagonals.is_empty() { + let diagonal = |a: u32, b: u32| diagonals.contains(&(a.min(b), a.max(b))); + mesh.diagonals = mesh.indices.chunks_exact(3).map(|t| (0..3).map(|i| u8::from(diagonal(t[i], t[(i + 1) % 3])) << i).sum()).collect(); + } if let Some(bad) = mesh.indices.iter().find(|i| **i as usize >= mesh.positions.len()) { return Err(FormatError::Invalid(format!("vertex index {bad} out of range ({} vertices)", mesh.positions.len()))); } diff --git a/crates/formats/src/mesh_import/obj.rs b/crates/formats/src/mesh_import/obj.rs index ce259a5a..4cf36661 100644 --- a/crates/formats/src/mesh_import/obj.rs +++ b/crates/formats/src/mesh_import/obj.rs @@ -27,7 +27,8 @@ fn read_inner(bytes: &[u8]) -> Result { } let library: String = names.iter().map(|n| format!("newmtl {n}\n")).collect(); let source = format!("mtllib texturecraft-usemtl.mtl\n{text}"); - let opts = tobj::LoadOptions { single_index: true, triangulate: true, ignore_points: true, ignore_lines: true }; + // Polygons stay whole so the wireframe can show them; `RawMesh::polygon` triangulates. + let opts = tobj::LoadOptions { single_index: true, triangulate: false, ignore_points: true, ignore_lines: true }; let (models, materials) = tobj::load_obj_buf(&mut source.as_bytes(), &opts, |_| tobj::load_mtl_buf(&mut library.as_bytes())).map_err(|e| malformed(KIND, e))?; let materials = materials.unwrap_or_default(); @@ -39,7 +40,9 @@ fn read_inner(bytes: &[u8]) -> Result { let m = &model.mesh; let n = m.positions.len() / 3; check_vertices(raw.positions.len().saturating_add(n))?; - check_triangles(raw.triangle_count(), m.indices.len() / 3)?; + // Corners per face; without arities every face is a triangle. + let arities: Vec = if m.face_arities.is_empty() { vec![3; m.indices.len() / 3] } else { m.face_arities.iter().map(|a| *a as usize).collect() }; + check_triangles(raw.triangle_count(), arities.iter().map(|a| a.saturating_sub(2)).sum())?; let base = raw.positions.len() as u32; raw.positions.extend(m.positions.chunks_exact(3).map(|p| Vec3::new(p[0], p[1], p[2]))); if m.normals.len() == n * 3 { @@ -67,12 +70,18 @@ fn read_inner(bytes: &[u8]) -> Result { Some(id) => materials.get(id).map(|mat| mat.name.clone()).filter(|s| !s.is_empty()).unwrap_or_else(|| format!("Material_{id}")), None => "Default".to_string(), }; - let group = raw.group(&name, &model.name); - for &i in m.indices.get(..m.indices.len() / 3 * 3).unwrap_or_default() { - if i as usize >= n { - return Err(malformed(KIND, format!("face index {i} out of range"))); + if let Some(i) = m.indices.iter().find(|i| **i as usize >= n) { + return Err(malformed(KIND, format!("face index {i} out of range"))); + } + let (mut rest, mut corners) = (m.indices.as_slice(), Vec::new()); + for arity in arities { + let Some((face, tail)) = rest.split_at_checked(arity) else { break }; + rest = tail; + corners.clear(); + corners.extend(face.iter().map(|i| base + i)); + if arity >= 3 { + raw.polygon(&name, &model.name, &corners); } - group.push(base + i); } } if partial_uvs && models.iter().any(|m| !m.mesh.texcoords.is_empty()) { diff --git a/crates/formats/src/mesh_import/ply.rs b/crates/formats/src/mesh_import/ply.rs index 1452aa41..0a72b28e 100644 --- a/crates/formats/src/mesh_import/ply.rs +++ b/crates/formats/src/mesh_import/ply.rs @@ -117,7 +117,6 @@ pub(crate) fn read(bytes: &[u8]) -> Result { let mut body = Body { data: bytes.get(body_start..).unwrap_or_default(), pos: 0, enc }; let mut raw = RawMesh::default(); let (mut normals, mut uvs, mut colors) = (Vec::new(), Vec::new(), Vec::new()); - let mut faces: Vec = Vec::new(); let mut nverts = 0usize; for el in &elements { // Every item takes at least one byte, so the count can never exceed what is left. @@ -169,10 +168,8 @@ pub(crate) fn read(bytes: &[u8]) -> Result { } } if face_list == Some(k) && poly.len() >= 3 { - check_triangles(faces.len() / 3, poly.len() - 2)?; - for i in 1..poly.len() - 1 { - faces.extend_from_slice(&[poly[0], poly[i], poly[i + 1]]); - } + check_triangles(raw.triangle_count(), poly.len() - 2)?; + raw.polygon("Default", "", &poly); } } } @@ -202,7 +199,6 @@ pub(crate) fn read(bytes: &[u8]) -> Result { raw.normals = (normals.len() == n).then_some(normals); raw.uvs = (uvs.len() == n).then_some(uvs); raw.colors = (colors.len() == n).then_some(colors); - raw.groups.push(("Default".into(), String::new(), faces)); Ok(raw) } diff --git a/crates/formats/src/mesh_import/tests.rs b/crates/formats/src/mesh_import/tests.rs index a21e5d4a..752fa61b 100644 --- a/crates/formats/src/mesh_import/tests.rs +++ b/crates/formats/src/mesh_import/tests.rs @@ -235,6 +235,22 @@ fn obj_without_uvs_or_normals_is_completed() { assert!(n0.len() > 1 && n0.iter().all(|n| (*n - n0[0]).length() < 1e-5)); } +#[test] +fn polygons_keep_their_edges_for_the_wireframe() { + // An OBJ quad and pentagon (with UVs, so no unwrap splits them), a triangle, and a PLY quad. + let obj = "v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nv 2 0 0\nv 3 0 0\nv 3 1 0\nv 2.5 2 0\nv 2 1 0\nvt 0 0\n\ + f 1/1 2/1 3/1 4/1\nf 5/1 6/1 7/1 8/1 9/1\nf 1/1 2/1 5/1\n"; + let m = import_mesh_bytes("p.obj", obj.as_bytes()).unwrap().mesh; + assert_eq!(m.triangle_count(), 2 + 3 + 1); + assert_eq!(m.wire_edges()[0].len(), 4 + 5 + 2, "the triangle adds edges 1-5 and 2-5"); + let ply = import_mesh_bytes("a.ply", ply_ascii().as_bytes()).unwrap().mesh; + assert_eq!(ply.wire_edges()[0].len(), 4); + // Triangles alone keep every edge. + let tris = import_mesh_bytes("t.obj", b"v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 0 0\nf 1/1 2/1 3/1\nf 1/1 3/1 4/1\n").unwrap().mesh; + assert!(tris.diagonals.is_empty()); + assert_eq!(tris.wire_edges()[0].len(), 5); +} + fn ply_ascii() -> String { "ply\nformat ascii 1.0\ncomment test\nelement vertex 4\nproperty float x\nproperty float y\nproperty float z\nproperty float s\nproperty float t\n\ element face 1\nproperty list uchar int vertex_indices\nend_header\n\ diff --git a/crates/formats/src/mesh_import/usd/mod.rs b/crates/formats/src/mesh_import/usd/mod.rs index fc1544bb..e7f9d0fe 100644 --- a/crates/formats/src/mesh_import/usd/mod.rs +++ b/crates/formats/src/mesh_import/usd/mod.rs @@ -228,8 +228,8 @@ fn read_usdz(bytes: &[u8]) -> Result<(Layer, Package<'_>)> { if zip.len() > MAX_ZIP_ENTRIES { return Err(FormatError::TooLarge(format!("the usdz package has more than {MAX_ZIP_ENTRIES} entries"))); } - let name = zip.file_names().filter(|n| matches!(super::extension(n).as_str(), "usda" | "usdc" | "usd")).min_by_key(|n| zip.index_for_name(n)); - let name = name.ok_or_else(|| malformed(KIND, "the usdz package contains no USD layer"))?.to_string(); + let name = zip.file_names().flatten().filter(|n| matches!(super::extension(n).as_str(), "usda" | "usdc" | "usd")).min_by_key(|n| zip.index_for_name(n)); + let name = name.ok_or_else(|| malformed(KIND, "the usdz package contains no USD layer"))?.into_owned(); let dir = name.rsplit_once('/').map_or("", |(d, _)| d).to_string(); let mut package = Package { zip, dir }; let data = package.read(&name, MAX_MESH_FILE_BYTES).ok_or_else(|| FormatError::TooLarge("the usdz layer is unreadable or larger than 2 GiB".into()))?; diff --git a/crates/formats/src/mesh_import/usd/tests.rs b/crates/formats/src/mesh_import/usd/tests.rs index 6cfd0a07..1797093b 100644 --- a/crates/formats/src/mesh_import/usd/tests.rs +++ b/crates/formats/src/mesh_import/usd/tests.rs @@ -344,19 +344,27 @@ fn usda_usdc_and_usdz_round_trip_with_textures() { && !text.contains("Red_Clearcoat"), "a coat exports with its roughness; no coat (black) drops both" ); - round_trip(&m, UsdFormat::Usdc, "usdc", &textures); + // The primvar reader's varname is a string (usdchecker --arkit refuses a token), in both encodings. + assert!(text.contains("string inputs:varname = \"st\""), "{text}"); + let usdc = round_trip(&m, UsdFormat::Usdc, "usdc", &textures); + let layer = super::usdc::read(&usdc, &mut super::Budget::new()).unwrap(); + let varnames: Vec<&super::Prop> = layer.prims.iter().filter_map(|p| p.props.get("inputs:varname")).collect(); + assert!(!varnames.is_empty()); + for v in varnames { + assert_eq!((v.type_name.as_str(), v.value.clone()), ("string", Some(super::Val::Tok(vec!["st".into()])))); + } let usdz = round_trip(&m, UsdFormat::Usdz, "usdz", &textures); let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&usdz)).unwrap(); - let names: Vec = zip.file_names().map(str::to_string).collect(); + let names: Vec = zip.file_names().map(|n| n.unwrap().into_owned()).collect(); assert_eq!(names.first().map(String::as_str), Some("Test_scene.usdc")); assert_eq!(names.len(), 1 + 7, "the layer and every non-black texture"); for i in 0..zip.len() { let mut f = zip.by_index(i).unwrap(); assert_eq!(f.compression(), zip::CompressionMethod::Stored); - assert_eq!(f.data_start() % 64, 0, "usdz entries are 64-byte aligned"); + assert_eq!(f.data_start().unwrap() % 64, 0, "usdz entries are 64-byte aligned"); let mut data = Vec::new(); f.read_to_end(&mut data).unwrap(); - if f.name().ends_with(".png") { + if f.name().unwrap().ends_with(".png") { assert!(image::load_from_memory(&data).is_ok()); } } diff --git a/crates/formats/src/project_file/mod.rs b/crates/formats/src/project_file/mod.rs index bd8bd228..a0d6cb3b 100644 --- a/crates/formats/src/project_file/mod.rs +++ b/crates/formats/src/project_file/mod.rs @@ -333,7 +333,7 @@ fn load(reader: R) -> Result { }; for i in 0..zip.len() { let mut f = zip.by_index(i).map_err(zip_err)?; - let name = f.name().to_string(); + let name = f.name().map_err(zip_err)?.into_owned(); let size_of = |id: LayerId| texture_set_of(&pf.project, id).and_then(|ts| pf.project.texture_sets.get(ts)).map(|t| t.size()); if name == "thumbnail.png" { pf.thumbnail = Some(read_all(&mut f, MAX_THUMBNAIL, &mut budget, &name)?); diff --git a/crates/geom/src/mesh.rs b/crates/geom/src/mesh.rs index 2ba804b2..95d66b4e 100644 --- a/crates/geom/src/mesh.rs +++ b/crates/geom/src/mesh.rs @@ -40,6 +40,9 @@ pub struct Mesh { /// Index ranges per material and part (node / object); `name` is the part name. pub submeshes: Vec, pub materials: Vec, + /// Per triangle, bit `i` set when edge `i` (corner `i` to corner `i + 1`) is a diagonal the + /// importer added to split a polygon, which wireframes leave out. Empty: every edge is real. + pub diagonals: Vec, } /// Hard cap on mesh size accepted from files (triangles). @@ -74,6 +77,36 @@ impl Mesh { Some([i[0] as usize, i[1] as usize, i[2] as usize]) } + /// The edges wireframes draw: each vertex pair once (smaller index first), leaving out + /// polygon diagonals ([`Mesh::diagonals`]) unless only one triangle has the edge (a UV seam + /// split it from its twin), per material in `0..materials.len().max(1)`. + pub fn wire_edges(&self) -> Vec> { + (0..self.materials.len().max(1)) + .map(|m| { + // Edge → (real in some triangle, triangles using it), in first-seen order. + let mut edges: Vec<((u32, u32), bool, u8)> = Vec::new(); + let mut at: std::collections::HashMap<(u32, u32), usize> = std::collections::HashMap::new(); + for t in self.triangles_of(m) { + let Some(v) = self.indices.get(t * 3..t * 3 + 3) else { continue }; + let hidden = self.diagonals.get(t).copied().unwrap_or(0); + for (i, (a, b)) in [(v[0], v[1]), (v[1], v[2]), (v[2], v[0])].into_iter().enumerate() { + let key = (a.min(b), a.max(b)); + let real = hidden >> i & 1 == 0; + let e = *at.entry(key).or_insert_with(|| { + edges.push((key, false, 0)); + edges.len() - 1 + }); + if let Some((_, r, n)) = edges.get_mut(e) { + *r |= real; + *n = n.saturating_add(1); + } + } + } + edges.into_iter().filter(|(_, real, n)| *real || *n == 1).map(|(k, ..)| k).collect() + }) + .collect() + } + /// Material of triangle `t`. pub fn material_of(&self, t: usize) -> Option { let idx = (t * 3) as u32; @@ -270,6 +303,10 @@ impl Mesh { self.colors.resize(base as usize, Vec4::ONE); self.colors.extend(other.colors.iter().copied().chain(std::iter::repeat(Vec4::ONE)).take(other.positions.len())); } + if !(self.diagonals.is_empty() && other.diagonals.is_empty()) { + self.diagonals.resize(ibase as usize / 3, 0); + self.diagonals.extend(other.diagonals.iter().copied().chain(std::iter::repeat(0)).take(other.triangle_count())); + } self.indices.extend(other.indices.iter().map(|i| i + base)); self.materials.extend(other.materials.iter().cloned()); self.submeshes.extend(other.submeshes.iter().map(|s| SubMesh { @@ -302,6 +339,7 @@ impl Mesh { colors: Vec::new(), submeshes: vec![SubMesh { name: material.into(), material: 0, start: 0, count }], materials: vec![material.into()], + diagonals: Vec::new(), }; if m.normals.len() != m.positions.len() { m.compute_normals(); @@ -377,6 +415,24 @@ mod tests { assert_eq!(m.triangles_of(0).collect::>(), vec![0, 1]); } + #[test] + fn wire_edges_leave_out_polygon_diagonals() { + let mut m = quad(); + assert_eq!(m.wire_edges(), vec![vec![(0, 1), (1, 2), (0, 2), (2, 3), (0, 3)]], "triangles show every edge"); + // Edge 2 of (0, 1, 2) and edge 0 of (0, 2, 3) split the quad. + m.diagonals = vec![0b100, 0b001]; + assert_eq!(m.wire_edges(), vec![vec![(0, 1), (1, 2), (2, 3), (0, 3)]]); + // A diagonal whose twin a seam split off (vertex 4 copies vertex 0) stays. + let mut seam = m.clone(); + seam.indices[3] = 4; + assert_eq!(seam.wire_edges()[0].len(), 6); + // Appending keeps each side's diagonals on its own triangles. + let mut a = Mesh::from_parts(m.positions.clone(), None, m.uvs.clone(), vec![0, 1, 2], "A").unwrap(); + a.append(&m); + assert_eq!(a.diagonals, vec![0, 0b100, 0b001]); + assert_eq!(crate::primitives::plane(1.0, 2).wire_edges()[0].len(), 12, "a 2×2 grid of quads has 12 edges"); + } + #[test] fn validate_catches_bad_indices() { let mut m = quad(); diff --git a/crates/geom/src/primitives.rs b/crates/geom/src/primitives.rs index 7f07270c..6403faed 100644 --- a/crates/geom/src/primitives.rs +++ b/crates/geom/src/primitives.rs @@ -30,6 +30,8 @@ struct Builder { n: Vec, uv: Vec, idx: Vec, + /// Per triangle: its [`Mesh::diagonals`] bits. + diag: Vec, } impl Builder { @@ -55,6 +57,8 @@ impl Builder { let a = base + i * w + j; let (b, c, d) = (a + 1, a + w, a + w + 1); self.idx.extend_from_slice(&[a, c, d, a, d, b]); + // Edge d-a of the first triangle and a-d of the second split the quad. + self.diag.extend_from_slice(&[0b100, 0b001]); } } } @@ -70,6 +74,7 @@ impl Builder { colors: Vec::new(), submeshes: vec![SubMesh { name: material.into(), material: 0, start: 0, count }], materials: vec![material.into()], + diagonals: self.diag, }; m.compute_tangents(); m @@ -203,6 +208,7 @@ fn disk_into(b: &mut Builder, center: Vec3, radius: f32, up: bool, segs: usize, } else { b.idx.extend_from_slice(&[c, a, bb]); } + b.diag.push(0); } } diff --git a/crates/paint/Cargo.toml b/crates/paint/Cargo.toml index 6cc99089..0b4bb7af 100644 --- a/crates/paint/Cargo.toml +++ b/crates/paint/Cargo.toml @@ -14,4 +14,9 @@ texturecraft-texel = { workspace = true } texturecraft-geom = { workspace = true } texturecraft-compose = { workspace = true } rayon = { workspace = true } +harfrust = { workspace = true } +skrifa = { workspace = true } serde = { workspace = true } + +[dev-dependencies] +epaint_default_fonts = { workspace = true } diff --git a/crates/paint/src/brush.rs b/crates/paint/src/brush.rs index 626f0fb7..7bcd4334 100644 --- a/crates/paint/src/brush.rs +++ b/crates/paint/src/brush.rs @@ -112,12 +112,15 @@ impl Shape<'_> { } } -/// An image as a brush alpha: luminance × alpha over the stamp square (−1..1, y up), 0 outside. +/// An image as a brush alpha: luminance × alpha, its longer side across the stamp square (−1..1, +/// y up) so it keeps its proportions (a line of text stays a line), 0 outside. pub fn image_alpha(img: &ImageRes, lx: f32, ly: f32) -> f32 { - if !(lx.abs() <= 1.0 && ly.abs() <= 1.0) { + let aspect = img.width as f32 / img.height.max(1) as f32; + let (x, y) = if aspect >= 1.0 { (lx, ly * aspect) } else { (lx / aspect.max(1e-6), ly) }; + if !(x.abs() <= 1.0 && y.abs() <= 1.0) { return 0.0; } - let [r, g, b, a] = img.sample(lx * 0.5 + 0.5, 0.5 - ly * 0.5); + let [r, g, b, a] = img.sample(x * 0.5 + 0.5, 0.5 - y * 0.5); ((0.2126 * r + 0.7152 * g + 0.0722 * b) * a).clamp(0.0, 1.0) } diff --git a/crates/paint/src/lib.rs b/crates/paint/src/lib.rs index fa689f5c..c34415ed 100644 --- a/crates/paint/src/lib.rs +++ b/crates/paint/src/lib.rs @@ -6,7 +6,8 @@ //! see ([`EyeDepth`]); [`commit`] blends the finished stroke into layer pixels. Clone and smudge //! strokes carry channel values ([`pickup`]) instead of painting the tool's material. //! [`path`] samples the Path tool's curves and lasso coverage; [`particles`] runs the particle -//! brush; [`alphas`] is the built-in library of procedural brush alphas. +//! brush; [`alphas`] is the built-in library of procedural brush alphas and [`presets`] the built-in +//! brush presets; [`text`] draws text for text alphas and decals. #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] @@ -16,8 +17,10 @@ pub mod commit; pub mod particles; pub mod path; pub mod pickup; +pub mod presets; pub mod raster; pub mod stroke; +pub mod text; pub mod visibility; pub use brush::{Alignment, BrushAlpha, BrushSettings, Particles, Shape, Symmetry, image_alpha}; diff --git a/crates/paint/src/presets.rs b/crates/paint/src/presets.rs new file mode 100644 index 00000000..72f537e6 --- /dev/null +++ b/crates/paint/src/presets.rs @@ -0,0 +1,203 @@ +//! Built-in brush presets: how a brush strokes (shape, spacing, flow, hardness, jitters, path +//! following, particles). Applying one keeps the brush's size, alignment, culling, symmetry and +//! lazy mouse, so a preset changes the stroke, not the setup. + +use crate::brush::{BrushAlpha, BrushSettings}; + +/// A named stroke recipe on top of the default stroke. +pub struct BrushPreset { + pub id: &'static str, + pub label: &'static str, + pub category: &'static str, + recipe: fn(&mut BrushSettings), +} + +impl BrushPreset { + /// `brush` with this preset's stroke. + pub fn applied(&self, brush: &BrushSettings) -> BrushSettings { + let mut b = with_stroke_of(brush, &BrushSettings::default()); + (self.recipe)(&mut b); + b.sanitized() + } +} + +/// `brush` with the stroke of `from` (shape, flow, opacity, spacing, hardness, angle, path +/// following, jitters and particles): what a preset sets. +pub fn with_stroke_of(brush: &BrushSettings, from: &BrushSettings) -> BrushSettings { + BrushSettings { + flow: from.flow, + opacity: from.opacity, + spacing: from.spacing, + hardness: from.hardness, + angle: from.angle, + follow_path: from.follow_path, + jitter_size: from.jitter_size, + jitter_angle: from.jitter_angle, + jitter_flow: from.jitter_flow, + jitter_position: from.jitter_position, + alpha: from.alpha, + alpha_image: from.alpha_image.clone(), + alpha_library: from.alpha_library.clone(), + particles: from.particles, + ..brush.clone() + } + .sanitized() +} + +/// A preset by id or label (case, spaces, `_` and `-` ignored). +pub fn find_preset(name: &str) -> Option<&'static BrushPreset> { + let n = |x: &str| x.to_ascii_lowercase().replace([' ', '_', '-'], ""); + PRESETS.iter().find(|p| n(p.id) == n(name) || n(p.label) == n(name)) +} + +const BASIC: &str = "Basic"; +const GRUNGE: &str = "Wear and grunge"; +const DETAIL: &str = "Details"; + +fn library(b: &mut BrushSettings, id: &str) { + b.alpha_library = Some(id.to_string()); +} + +/// Every built-in preset, in shelf order. +pub const PRESETS: [BrushPreset; 18] = [ + BrushPreset { id: "basic_hard", label: "Basic hard", category: BASIC, recipe: |b| b.hardness = 0.95 }, + BrushPreset { id: "basic_soft", label: "Basic soft", category: BASIC, recipe: |b| (b.hardness, b.flow) = (0.0, 0.6) }, + BrushPreset { id: "airbrush", label: "Airbrush", category: BASIC, recipe: |b| (b.hardness, b.flow, b.spacing) = (0.0, 0.12, 0.04) }, + BrushPreset { id: "square", label: "Square", category: BASIC, recipe: |b| (b.alpha, b.hardness, b.follow_path) = (BrushAlpha::Square, 0.9, true) }, + BrushPreset { id: "dots", label: "Dots", category: BASIC, recipe: |b| (b.hardness, b.spacing) = (0.9, 1.6) }, + BrushPreset { + id: "dry_brush", + label: "Dry brush", + category: GRUNGE, + recipe: |b| (b.alpha, b.follow_path, b.spacing, b.flow) = (BrushAlpha::Streaks, true, 0.04, 0.5), + }, + BrushPreset { + id: "chalk", + label: "Chalk", + category: GRUNGE, + recipe: |b| { + library(b, "sponge"); + (b.jitter_angle, b.spacing, b.flow) = (1.0, 0.15, 0.7); + }, + }, + BrushPreset { + id: "spray", + label: "Spray", + category: GRUNGE, + recipe: |b| (b.alpha, b.jitter_angle, b.jitter_size, b.spacing) = (BrushAlpha::Spray, 1.0, 0.3, 0.3), + }, + BrushPreset { + id: "grunge", + label: "Grunge", + category: GRUNGE, + recipe: |b| (b.alpha, b.jitter_angle, b.jitter_size, b.spacing) = (BrushAlpha::Grunge, 1.0, 0.4, 0.4), + }, + BrushPreset { + id: "splatter", + label: "Splatter", + category: GRUNGE, + recipe: |b| { + library(b, "splatter"); + (b.jitter_angle, b.jitter_size, b.jitter_position, b.spacing) = (1.0, 0.5, 1.5, 1.2); + }, + }, + BrushPreset { + id: "scratches", + label: "Scratches", + category: GRUNGE, + recipe: |b| { + library(b, "scratches"); + (b.follow_path, b.jitter_angle, b.spacing) = (true, 0.1, 0.5); + }, + }, + BrushPreset { + id: "chips", + label: "Chips", + category: GRUNGE, + recipe: |b| { + library(b, "chips"); + (b.jitter_angle, b.jitter_size, b.jitter_position, b.spacing) = (1.0, 0.5, 1.0, 0.8); + }, + }, + BrushPreset { + id: "cracks", + label: "Cracks", + category: GRUNGE, + recipe: |b| { + library(b, "cracks"); + (b.jitter_angle, b.spacing) = (1.0, 0.9); + }, + }, + BrushPreset { + id: "drips", + label: "Drips", + category: GRUNGE, + recipe: |b| { + (b.hardness, b.flow) = (0.7, 0.6); + b.particles.enabled = true; + }, + }, + BrushPreset { + id: "stars", + label: "Stars", + category: DETAIL, + recipe: |b| { + library(b, "star_5"); + (b.jitter_size, b.jitter_angle, b.jitter_position, b.spacing) = (0.6, 1.0, 2.0, 1.5); + }, + }, + BrushPreset { + id: "stitches", + label: "Stitches", + category: DETAIL, + recipe: |b| { + library(b, "stitches"); + (b.follow_path, b.spacing) = (true, 0.9); + }, + }, + BrushPreset { + id: "rivets", + label: "Rivets", + category: DETAIL, + recipe: |b| { + library(b, "rivet"); + b.spacing = 2.0; + }, + }, + BrushPreset { + id: "fur", + label: "Fur", + category: DETAIL, + recipe: |b| { + library(b, "fur"); + (b.follow_path, b.jitter_angle, b.spacing) = (true, 0.15, 0.3); + }, + }, +]; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn presets_are_unique_valid_and_keep_the_setup() { + let mut ids: Vec<&str> = PRESETS.iter().map(|p| p.id).collect(); + ids.sort_unstable(); + ids.dedup(); + assert_eq!(ids.len(), PRESETS.len()); + let mine = + BrushSettings { size: 0.1, lazy: 12.0, backface_culling: false, jitter_size: 1.0, alpha_image: Some("x.png".into()), ..BrushSettings::default() }; + for p in &PRESETS { + let b = p.applied(&mine); + assert_eq!(b, b.sanitized(), "{}", p.id); + assert_eq!((b.size, b.lazy, b.backface_culling, b.alpha_image.as_deref()), (0.1, 12.0, false, None), "{}", p.id); + if let Some(id) = &b.alpha_library { + assert!(crate::alphas::find(id).is_some(), "{}: library alpha {id}", p.id); + } + assert_eq!(find_preset(p.label).map(|f| f.id), Some(p.id)); + } + assert_eq!(find_preset("basic hard").map(|p| p.id), Some("basic_hard")); + assert!(find_preset("nope").is_none()); + assert_eq!(PRESETS[0].applied(&mine).jitter_size, 0.0, "jitters reset"); + } +} diff --git a/crates/paint/src/text.rs b/crates/paint/src/text.rs new file mode 100644 index 00000000..15d9cf26 --- /dev/null +++ b/crates/paint/src/text.rs @@ -0,0 +1,254 @@ +//! Text as a coverage image, for brush alphas and decals: each line shaped with harfrust +//! (kerning, ligatures, joined scripts), drawn from the font's outlines (skrifa) and filled with +//! a non-zero scanline rasterizer, lines centered. + +use harfrust::{FontRef, ShapeOptions, ShaperData, UnicodeBuffer}; +use skrifa::MetadataProvider; +use skrifa::instance::{LocationRef, Size}; +use skrifa::outline::{DrawSettings, OutlinePen}; + +/// Longest text drawn (characters). +pub const MAX_TEXT_CHARS: usize = 1000; +/// Largest side of a text image (texels); bigger layouts are drawn smaller to fit. +pub const MAX_TEXT_SIDE: u32 = 4096; +/// Vertical samples per texel row. +const SUBROWS: usize = 4; + +/// A shaped glyph: its id and pen position (font units). +type Placed = (u32, f32, f32); + +/// Coverage 0..=255 per texel, rows top to bottom. +#[derive(Clone, Debug, PartialEq)] +pub struct TextImage { + pub width: u32, + pub height: u32, + pub coverage: Vec, +} + +/// Draw `text` (one or more lines) with face `index` of `font` at `px` texels per em, cropped to +/// the ink with a margin of a tenth of an em. +pub fn render_text(font: &[u8], index: u32, text: &str, px: f32) -> Result { + let text = text.trim_end(); + if text.trim().is_empty() { + return Err("the text is empty".into()); + } + if text.chars().count() > MAX_TEXT_CHARS { + return Err(format!("the text is longer than {MAX_TEXT_CHARS} characters")); + } + let font = FontRef::from_index(font, index).map_err(|e| format!("not a usable font: {e}"))?; + // Layout in font units; `scale` turns them into texels. + let m = font.metrics(Size::unscaled(), LocationRef::default()); + let upem = f32::from(m.units_per_em.max(1)); + let line = (m.ascent - m.descent + m.leading).max(upem * 0.5); + let data = ShaperData::new(&font); + let shaper = data.shaper(&font).build(); + let mut lines: Vec<(f32, Vec)> = Vec::new(); + for t in text.lines() { + let mut buffer = UnicodeBuffer::new(); + buffer.push_str(t); + buffer.guess_segment_properties(); + let shaped = shaper.shape(buffer, ShapeOptions::new()); + let mut x = 0.0; + let mut glyphs = Vec::new(); + for (info, pos) in shaped.glyph_infos().iter().zip(shaped.glyph_positions()) { + glyphs.push((info.glyph_id, x + pos.x_offset as f32, pos.y_offset as f32)); + x += pos.x_advance as f32; + } + lines.push((x, glyphs)); + } + let widest = lines.iter().map(|(w, _)| *w).fold(0.0, f32::max); + let px = px.clamp(4.0, 1024.0); + // Outlines in texels (y down) at the shaped positions, lines centered on the widest. + let outlines = font.outline_glyphs(); + let mut pen = Edges { scale: px / upem, ..Edges::default() }; + for (row, (line_width, glyphs)) in lines.iter().enumerate() { + let left = (widest - line_width) * 0.5; + for &(id, x, y) in glyphs { + let Some(glyph) = outlines.get(skrifa::GlyphId::new(id)) else { continue }; + pen.origin = ((left + x) * pen.scale, (line * row as f32 - y) * pen.scale); + // A glyph that can't be drawn is left out rather than failing the text. + let _ = glyph.draw(DrawSettings::unhinted(Size::unscaled(), LocationRef::default()), &mut pen); + pen.close(); + } + } + // The image is the ink's bounds plus the margin (accents and descenders never clip), scaled + // down when that is too large. + let points = || pen.edges.iter().flat_map(|e| [(e[0], e[1]), (e[2], e[3])]); + let lo = points().fold((f32::MAX, f32::MAX), |a, p| (a.0.min(p.0), a.1.min(p.1))); + let hi = points().fold((f32::MIN, f32::MIN), |a, p| (a.0.max(p.0), a.1.max(p.1))); + if pen.edges.is_empty() || !(lo.0.is_finite() && hi.0.is_finite() && lo.1.is_finite() && hi.1.is_finite()) { + return Err("the font draws nothing for this text".into()); + } + let margin = px * 0.1; + let (w, h) = (hi.0 - lo.0 + 2.0 * margin, hi.1 - lo.1 + 2.0 * margin); + let fit = (MAX_TEXT_SIDE as f32 / w.max(h)).min(1.0); + let edges: Vec<[f32; 4]> = pen + .edges + .iter() + .map(|e| [(e[0] - lo.0 + margin) * fit, (e[1] - lo.1 + margin) * fit, (e[2] - lo.0 + margin) * fit, (e[3] - lo.1 + margin) * fit]) + .collect(); + let (width, height) = ((w * fit).ceil().max(1.0) as u32, (h * fit).ceil().max(1.0) as u32); + Ok(TextImage { width, height, coverage: fill(&edges, width as usize, height as usize) }) +} + +/// Line segments (texel space, y down) collected from glyph outlines: font units times `scale` +/// from `origin`, curves flattened. +#[derive(Default)] +struct Edges { + scale: f32, + origin: (f32, f32), + start: (f32, f32), + at: (f32, f32), + edges: Vec<[f32; 4]>, +} + +impl Edges { + fn map(&self, x: f32, y: f32) -> (f32, f32) { + (self.origin.0 + x * self.scale, self.origin.1 - y * self.scale) + } + + fn segment(&mut self, to: (f32, f32)) { + if to != self.at { + self.edges.push([self.at.0, self.at.1, to.0, to.1]); + } + self.at = to; + } + + /// Flatten a curve given as a point function of t in 0..1, finer for longer curves. + fn curve(&mut self, control_length: f32, point: impl Fn(f32) -> (f32, f32)) { + let steps = (control_length.sqrt() * 2.0).clamp(2.0, 64.0) as usize; + for i in 1..=steps { + self.segment(point(i as f32 / steps as f32)); + } + } +} + +fn dist(a: (f32, f32), b: (f32, f32)) -> f32 { + (a.0 - b.0).hypot(a.1 - b.1) +} + +impl OutlinePen for Edges { + fn move_to(&mut self, x: f32, y: f32) { + self.close(); + self.start = self.map(x, y); + self.at = self.start; + } + + fn line_to(&mut self, x: f32, y: f32) { + let p = self.map(x, y); + self.segment(p); + } + + fn quad_to(&mut self, cx0: f32, cy0: f32, x: f32, y: f32) { + let (p0, c, p) = (self.at, self.map(cx0, cy0), self.map(x, y)); + self.curve(dist(p0, c) + dist(c, p), |t| { + let s = 1.0 - t; + (s * s * p0.0 + 2.0 * s * t * c.0 + t * t * p.0, s * s * p0.1 + 2.0 * s * t * c.1 + t * t * p.1) + }); + } + + fn curve_to(&mut self, cx0: f32, cy0: f32, cx1: f32, cy1: f32, x: f32, y: f32) { + let (p0, c0, c1, p) = (self.at, self.map(cx0, cy0), self.map(cx1, cy1), self.map(x, y)); + self.curve(dist(p0, c0) + dist(c0, c1) + dist(c1, p), |t| { + let s = 1.0 - t; + let (a, b, c, d) = (s * s * s, 3.0 * s * s * t, 3.0 * s * t * t, t * t * t); + (a * p0.0 + b * c0.0 + c * c1.0 + d * p.0, a * p0.1 + b * c0.1 + c * c1.1 + d * p.1) + }); + } + + fn close(&mut self) { + self.segment(self.start); + } +} + +/// Non-zero winding coverage of closed `edges` over a `w × h` grid: [`SUBROWS`] scanlines per +/// row, each span's ends spread over the texels they cross. +fn fill(edges: &[[f32; 4]], w: usize, h: usize) -> Vec { + let mut acc = vec![0f32; w * h]; + // Edges by their top, and the ones the current scanline may cross. + let mut sorted: Vec<[f32; 4]> = edges.iter().copied().filter(|e| e[1] != e[3]).collect(); + sorted.sort_by(|a, b| a[1].min(a[3]).total_cmp(&b[1].min(b[3]))); + let (mut next, mut active) = (0, Vec::new()); + let mut crossings: Vec<(f32, i32)> = Vec::new(); + for row in 0..h { + for sub in 0..SUBROWS { + let y = row as f32 + (sub as f32 + 0.5) / SUBROWS as f32; + while let Some(e) = sorted.get(next).filter(|e| e[1].min(e[3]) <= y) { + active.push(*e); + next += 1; + } + active.retain(|e| e[1].max(e[3]) > y); + crossings.clear(); + for &[x0, y0, x1, y1] in &active { + if (y0 <= y) != (y1 <= y) { + crossings.push((x0 + (y - y0) / (y1 - y0) * (x1 - x0), if y1 > y0 { 1 } else { -1 })); + } + } + crossings.sort_by(|a, b| a.0.total_cmp(&b.0)); + let mut winding = 0; + for pair in crossings.windows(2) { + winding += pair[0].1; + if winding != 0 { + span(&mut acc[row * w..(row + 1) * w], pair[0].0, pair[1].0); + } + } + } + } + acc.iter().map(|c| (c / SUBROWS as f32 * 255.0).round().clamp(0.0, 255.0) as u8).collect() +} + +/// Add the covered length of `x0..x1` to each texel of `row`. +fn span(row: &mut [f32], x0: f32, x1: f32) { + let (x0, x1) = (x0.clamp(0.0, row.len() as f32), x1.clamp(0.0, row.len() as f32)); + if x1 <= x0 { + return; + } + for (i, c) in row.iter_mut().enumerate().take(x1.ceil() as usize).skip(x0.floor() as usize) { + *c += (x1.min(i as f32 + 1.0) - x0.max(i as f32)).max(0.0); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn spans_spread_partial_texels() { + let mut row = [0.0; 4]; + span(&mut row, 0.5, 2.25); + assert_eq!(row, [0.5, 1.0, 0.25, 0.0]); + // A square drawn either way round fills the same texels. + let square = |cw: bool| { + let p = [(1.0, 1.0), (3.0, 1.0), (3.0, 3.0), (1.0, 3.0)]; + let p: Vec<_> = if cw { p.to_vec() } else { p.iter().rev().copied().collect() }; + (0..4).map(|i| [p[i].0, p[i].1, p[(i + 1) % 4].0, p[(i + 1) % 4].1]).collect::>() + }; + let a = fill(&square(true), 4, 4); + assert_eq!(a, fill(&square(false), 4, 4)); + assert_eq!((a[5], a[0], a[3 * 4 + 3]), (255, 0, 0), "inside full, outside empty"); + } + + #[test] + fn text_is_laid_out_and_filled() { + let font = epaint_default_fonts::UBUNTU_LIGHT; + let one = render_text(font, 0, "H", 64.0).unwrap(); + let two = render_text(font, 0, "HH", 64.0).unwrap(); + let lines = render_text(font, 0, "H\nH", 64.0).unwrap(); + assert!(two.width > one.width && two.height == one.height); + assert!(lines.height > one.height && lines.width == one.width, "lines stack"); + let ink = |t: &TextImage| t.coverage.iter().map(|c| u32::from(*c)).sum::(); + assert!(ink(&two) > ink(&one) * 19 / 10 && ink(&two) < ink(&one) * 21 / 10, "two H, twice the ink"); + assert!(one.coverage.contains(&255) && one.coverage.contains(&0)); + // The margin stays clear; huge sizes are drawn to fit. + assert!(one.coverage[..one.width as usize].iter().all(|c| *c == 0)); + let big = render_text(font, 0, &"W".repeat(400), 1024.0).unwrap(); + assert!(big.width <= MAX_TEXT_SIDE && big.height >= 1); + } + + #[test] + fn bad_input_is_an_error() { + assert!(render_text(b"not a font", 0, "Hi", 64.0).is_err()); + assert!(render_text(b"", 0, " ", 64.0).is_err()); + assert!(render_text(b"", 0, &"x".repeat(MAX_TEXT_CHARS + 1), 64.0).is_err()); + } +} diff --git a/crates/render/Cargo.toml b/crates/render/Cargo.toml index 95b91c29..080f12ba 100644 --- a/crates/render/Cargo.toml +++ b/crates/render/Cargo.toml @@ -17,10 +17,15 @@ texturecraft-bake = { workspace = true } wgpu = { workspace = true } bytemuck = { workspace = true } half = { workspace = true } +log = { workspace = true } rayon = { workspace = true } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] pollster = "0.4" +# The browser's WebGPU resolves error scopes later: their results are awaited on the page. +[target.'cfg(target_arch = "wasm32")'.dependencies] +wasm-bindgen-futures = "0.4" + [dev-dependencies] image = { workspace = true } diff --git a/crates/render/src/displace.rs b/crates/render/src/displace.rs index 287898c7..f2e2b19a 100644 --- a/crates/render/src/displace.rs +++ b/crates/render/src/displace.rs @@ -72,6 +72,7 @@ pub fn displaced(mesh: &Mesh, sets: &[TraceSet]) -> Option { }, indices, materials: mesh.materials.clone(), + diagonals: Vec::new(), }) } diff --git a/crates/render/src/gpu_trace.rs b/crates/render/src/gpu_trace.rs index 4ea0f472..775fc026 100644 --- a/crates/render/src/gpu_trace.rs +++ b/crates/render/src/gpu_trace.rs @@ -140,6 +140,54 @@ pub(crate) fn scoped(device: &wgpu::Device, what: &str, f: impl FnOnce() -> T } } +/// What [`checked`] knows right after the call. +pub(crate) enum Checked { + /// wgpu answered at once (native backends, WebGL): the value, or what went wrong. + Done(Result), + /// The browser's WebGPU answers later: the value, possibly invalid, and where the answer + /// arrives (`None` for success). Don't use the value until it arrives. (Native backends + /// never answer late; the renderer's tests build this variant by hand.) + #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))] + Later(T, std::sync::mpsc::Receiver>), +} + +/// [`scoped`] for work whose errors may arrive later: never takes an unanswered scope as success. +pub(crate) fn checked(device: &wgpu::Device, what: &str, f: impl FnOnce() -> T) -> Checked { + let oom = device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); + let invalid = device.push_error_scope(wgpu::ErrorFilter::Validation); + let out = f(); + let (invalid, oom) = (invalid.pop(), oom.pop()); + let what = what.to_string(); + let mut answer = Box::pin(async move { + let invalid = invalid.await; + let oom = oom.await; + // An allocation that ran out of memory also makes later calls on it invalid: the + // out-of-memory error is the cause. + oom.or(invalid).map(|e| format!("{what}: {e}")) + }); + #[cfg(not(target_arch = "wasm32"))] + { + Checked::Done(match pollster::block_on(answer.as_mut()) { + Some(e) => Err(e), + None => Ok(out), + }) + } + #[cfg(target_arch = "wasm32")] + { + match answer.as_mut().poll(&mut Context::from_waker(Waker::noop())) { + Poll::Ready(Some(e)) => Checked::Done(Err(e)), + Poll::Ready(None) => Checked::Done(Ok(out)), + Poll::Pending => { + let (tx, rx) = std::sync::mpsc::channel(); + wasm_bindgen_futures::spawn_local(async move { + let _ = tx.send(answer.await); + }); + Checked::Later(out, rx) + } + } + } +} + pub(crate) fn entry(binding: u32, ty: wgpu::BindingType) -> wgpu::BindGroupLayoutEntry { wgpu::BindGroupLayoutEntry { binding, visibility: wgpu::ShaderStages::COMPUTE, ty, count: None } } @@ -439,7 +487,8 @@ impl GpuTracer { let mut info: Vec<[f32; 3]> = sets .iter() .map(|s| { - let dims = s.first().map_or((1, 1), |t| (t.width(), t.height())); + // The set's size is its largest texture's; any kind may still be a 1×1 placeholder. + let dims = s.iter().fold((1, 1), |(w, h), t| (t.width().max(w), t.height().max(h))); let small = s.iter().enumerate().filter(|(_, t)| (t.width(), t.height()) != dims).fold(0u32, |m, (k, _)| m | 1 << k); [dims.0 as f32, dims.1 as f32, small as f32] }) @@ -821,6 +870,43 @@ mod tests { } } + #[test] + fn gpu_reads_full_size_channels_beside_placeholders() { + // Base color stays at its default (a 1×1 placeholder texture) while roughness varies + // across the surface (a full-size texture): the tracer must still read every texel of it. + use Channel::*; + let Some((mut h, mut t)) = gpu() else { return }; + let mut composite = Composite::new(&[Roughness, Metallic], 64); + for y in 0..64 { + for x in 0..64 { + let rough = if x < 32 { 0.05 } else { 0.9 }; + composite.channels.get_mut(&Roughness).unwrap().set(x, y, &[texturecraft_texel::to_u16(rough)]); + composite.channels.get_mut(&Metallic).unwrap().set(x, y, &[texturecraft_texel::to_u16(1.0)]); + } + } + h.renderer.set_texture_sets(&h.device, &h.queue, &[((64, 64), 0)], 1); + for (tx, ty) in all_tiles(64, 64) { + for k in DisplayKind::ALL { + h.renderer.upload_tile(&h.device, &h.queue, 0, k, tx, ty, &tile_bytes(&composite, &BakedMaps::default(), k, tx, ty)); + } + } + let sizes: Vec = h.renderer.display_textures()[0].iter().map(|t| t.width()).collect(); + assert_eq!(sizes[0], 1, "base color stays a placeholder"); + assert_eq!(sizes[1], 64, "roughness and metallic are full size"); + let mesh = Arc::new(primitives::sphere(1.0, 32, 16)); + let bvh = Arc::new(Bvh::new(&mesh)); + let env = crate::ibl::environment("Studio Contrast", 256); + let scene = TraceScene::new(mesh, bvh, vec![TraceSet { material: 0, composite, height_strength: 0.0 }], Arc::new(env), 0.0); + let d = TraceDisplay { exposure: 1.0, aces: true, env_opacity: 0.5, denoise: false }; + let settings = TraceSettings { bounces: 4 }; + let (_, _, gpu) = t.render(&h.device, &h.queue, &h.renderer, &scene, &camera(), &settings, &d, [48, 36], 1024).unwrap(); + let mut cpu = Tracer::new(48, 36); + for _ in 0..1024 { + cpu.pass(&scene, &camera(), &settings); + } + assert_region_means_match("varying roughness, default base color", &gpu, &cpu.rgba8(&d), 48, 36, 3.0); + } + /// Mean luminance of each 6×6 block of two RGBA8 renders agrees within `tol` 8-bit levels. fn assert_region_means_match(name: &str, a: &[u8], b: &[u8], w: usize, h: usize, tol: f32) { let lum = |img: &[u8], x: usize, y: usize| { diff --git a/crates/render/src/ibl.rs b/crates/render/src/ibl.rs index d4c9fc8b..5c6b59db 100644 --- a/crates/render/src/ibl.rs +++ b/crates/render/src/ibl.rs @@ -18,8 +18,7 @@ pub struct EnvImage { pub data: Vec<[f32; 3]>, } -/// Built-in environments, in menu order. -pub const ENVIRONMENTS: [&str; 6] = ["Studio Soft", "Studio Contrast", "Overcast", "Sunset", "Warehouse", "Night"]; +pub use texturecraft_core::project::ENVIRONMENTS; pub fn dir_of(u: f32, v: f32) -> Vec3 { let (theta, phi) = (v * PI, u * TAU); diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index 5fd4ac14..ea4757d5 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -30,6 +30,7 @@ use texturecraft_geom::glam::{Mat4, Vec3}; use texturecraft_geom::{Mesh, OrbitCamera}; use texturecraft_texel::TILE; +use crate::gpu_trace::{Checked, checked}; use crate::ibl; use crate::subdivide::{self, Vertex}; @@ -327,10 +328,67 @@ struct SetGpu { /// Display textures hold the set at `size >> shift`: halved until they fit the device. shift: u32, /// The display textures in [`DisplayKind::ALL`] order, then the aux (mesh map) texture. - /// [`lazy`] kinds stay 1×1 until a tile with a non-default value arrives. + /// Each starts as a 1×1 neutral placeholder and gets its full size with the first tile (or + /// aux image) that holds something else, so a mesh with many materials costs no GPU memory + /// until its sets are painted. tex: Vec, bind_group: wgpu::BindGroup, mips_dirty: Vec, + /// Textures whose full-size allocation failed (out of GPU memory): they keep their + /// placeholder until the set is re-created, instead of retrying on every tile. + failed: Vec, + /// Full-size textures the browser's WebGPU has not yet confirmed: tiles go into them while + /// the placeholder stays bound (see [`Renderer::resolve_pending`]). + pending: Vec>, +} + +/// A full-size texture waiting for WebGPU's verdict on its allocation. +struct PendingTex { + tex: Tex, + /// `None` for success, else what went wrong. (A mutex: the renderer is shared with the + /// paint callback, so it must be `Sync`.) + answer: std::sync::Mutex>>, +} + +/// Swap `tex` in for slot `slot` of `set` (bound at once; its mips are rebuilt). +fn install(set: &mut SetGpu, slot: usize, tex: Tex, device: &wgpu::Device, layout: &wgpu::BindGroupLayout, sampler: &wgpu::Sampler) { + if let Some(s) = set.tex.get_mut(slot) { + *s = tex; + } + set.bind_group = set_bind_group(device, layout, sampler, &set.tex); + if let Some(d) = set.mips_dirty.get_mut(slot) { + *d = true; + } +} + +/// Give slot `slot` of `set` (texture set `ts`) the full-size texture `checked` allocated: +/// installed when wgpu accepted it, kept pending while WebGPU has not answered, or (out of GPU +/// memory) left as the placeholder with the failure recorded. False when there is nothing to +/// write into. +fn grow( + set: &mut SetGpu, + ts: usize, + slot: usize, + checked: Checked, + ctx: (&wgpu::Device, &wgpu::BindGroupLayout, &wgpu::Sampler), + failures: &mut Vec, +) -> bool { + match checked { + Checked::Done(Ok(full)) => install(set, slot, full, ctx.0, ctx.1, ctx.2), + Checked::Done(Err(e)) => { + if let Some(f) = set.failed.get_mut(slot) { + *f = true; + } + memory_failed(failures, ts, &e); + return false; + } + Checked::Later(tex, answer) => { + if let Some(p) = set.pending.get_mut(slot) { + *p = Some(PendingTex { tex, answer: std::sync::Mutex::new(answer) }); + } + } + } + true } /// Vertex and index buffers with their draws (first index, count, material). @@ -477,6 +535,9 @@ pub struct Renderer { black: wgpu::TextureView, /// [`DisplayKind::default_texel`] in [`DisplayKind::ALL`] order. default_texels: Vec>, + /// Texture sets whose display textures could not be allocated (out of GPU memory) since + /// [`Renderer::take_memory_failures`]. + memory_failures: Vec, accum_pipeline: wgpu::RenderPipeline, env: Tex, env_name: String, @@ -530,11 +591,8 @@ pub(crate) fn display_format(k: DisplayKind) -> wgpu::TextureFormat { } } -/// Textures of the optional lobe channels: most sets never use them, so they cost no memory or -/// bandwidth (a 1×1 neutral texture) until painted. -fn lazy(k: DisplayKind) -> bool { - matches!(k, DisplayKind::Lobes | DisplayKind::Sheen | DisplayKind::Extra) -} +/// Texel of the aux texture before a mesh map or mask is shown. +const AUX_NEUTRAL: [u8; 4] = [128, 128, 128, 255]; /// A `w × h` texture filled with `texel`. fn neutral_tex(device: &wgpu::Device, queue: &wgpu::Queue, (w, h): (u32, u32), format: wgpu::TextureFormat, mips: u32, texel: &[u8]) -> Tex { @@ -557,6 +615,14 @@ fn neutral_tex(device: &wgpu::Device, queue: &wgpu::Queue, (w, h): (u32, u32), f t } +/// Record that texture set `ts` could not get a display texture (`error` says which). +fn memory_failed(failures: &mut Vec, ts: usize, error: &str) { + log::warn!("cannot allocate the display texture of {error}"); + if !failures.contains(&ts) { + failures.push(ts); + } +} + /// Bytes per write when filling a texture with one texel. const NEUTRAL_BAND_BYTES: usize = 8 << 20; @@ -946,6 +1012,7 @@ impl Renderer { shadow, black, default_texels: DisplayKind::ALL.map(DisplayKind::default_texel).to_vec(), + memory_failures: Vec::new(), env, env_name: String::new(), sh: [[0.0; 4]; 9], @@ -1018,21 +1085,12 @@ impl Renderer { let vb = mk("tc_vb", bytemuck::cast_slice(&verts), wgpu::BufferUsages::VERTEX); let ib = mk("tc_ib", &idx_bytes, wgpu::BufferUsages::INDEX); let draws: Vec<(u32, u32, usize)> = mesh.submeshes.iter().map(|s| (s.start, s.count, s.material)).collect(); - // UV edges (each shared edge once) per material, for the 2D view wireframe. + // Mesh edges per material (polygons, not their triangles), for the wireframes. let mut line_idx: Vec = Vec::new(); let mut line_draws = Vec::new(); - for m in 0..mesh.materials.len().max(1) { + for (m, edges) in mesh.wire_edges().into_iter().enumerate() { let start = line_idx.len() as u32; - let mut seen = std::collections::HashSet::new(); - for t in mesh.triangles_of(m) { - let Some(v) = mesh.tri(t) else { continue }; - for (a, b) in [(v[0], v[1]), (v[1], v[2]), (v[2], v[0])] { - let key = (a.min(b), a.max(b)); - if seen.insert(key) { - line_idx.extend_from_slice(&[key.0 as u32, key.1 as u32]); - } - } - } + line_idx.extend(edges.into_iter().flat_map(|(a, b)| [a, b])); line_draws.push((start, line_idx.len() as u32 - start, m)); } let lines = mk("tc_lines", bytemuck::cast_slice(&line_idx), wgpu::BufferUsages::INDEX); @@ -1077,20 +1135,13 @@ impl Renderer { if self.sets.get(i).is_some_and(|s| s.size == size && s.shift == shift) { continue; } - let dims = display_dims(size, shift); - let mut tex: Vec = DisplayKind::ALL - .iter() - .zip(&self.default_texels) - .map(|(k, texel)| { - let (d, mips) = if lazy(*k) { ((1, 1), 1) } else { (dims, mip_count(dims.0.max(dims.1))) }; - neutral_tex(device, queue, d, display_format(*k), mips, texel) - }) - .collect(); - let aux = aux_size(size); - tex.push(neutral_tex(device, queue, (aux, aux), wgpu::TextureFormat::Rgba8Unorm, mip_count(aux), &[128, 128, 128, 255])); + // Placeholders only: full-size textures come with the first non-neutral upload. + let mut tex: Vec = + DisplayKind::ALL.iter().zip(&self.default_texels).map(|(k, texel)| neutral_tex(device, queue, (1, 1), display_format(*k), 1, texel)).collect(); + tex.push(neutral_tex(device, queue, (1, 1), wgpu::TextureFormat::Rgba8Unorm, 1, &AUX_NEUTRAL)); let bind_group = set_bind_group(device, &self.set_bgl, &self.sampler, &tex); let n = tex.len(); - let gpu = SetGpu { size, shift, tex, bind_group, mips_dirty: vec![true; n] }; + let gpu = SetGpu { size, shift, tex, bind_group, mips_dirty: vec![true; n], failed: vec![false; n], pending: (0..n).map(|_| None).collect() }; if i < self.sets.len() { self.sets[i] = gpu; } else { @@ -1119,18 +1170,24 @@ impl Renderer { return; } let dims = display_dims(set.size, set.shift); - if t.texture.width() < dims.0 { - // A lazy placeholder: neutral tiles change nothing, the first real one allocates it. - if bytes.chunks_exact(texel.len()).all(|px| px == texel.as_slice()) { + let awaiting = set.pending.get(ki).is_some_and(Option::is_some); + if !awaiting && (t.texture.width() < dims.0 || t.texture.height() < dims.1) { + // A placeholder: neutral tiles change nothing, the first real one allocates it. + if set.failed.get(ki).copied().unwrap_or(true) || bytes.chunks_exact(texel.len()).all(|px| px == texel.as_slice()) { return; } - let full = neutral_tex(device, queue, dims, display_format(kind), mip_count(dims.0.max(dims.1)), texel); - if let Some(slot) = set.tex.get_mut(ki) { - *slot = full; + let what = format!("texture set {} ({kind:?}, {}×{})", ts + 1, dims.0, dims.1); + let full = checked(device, &what, || neutral_tex(device, queue, dims, display_format(kind), mip_count(dims.0.max(dims.1)), texel)); + if !grow(set, ts, ki, full, (device, &self.set_bgl, &self.sampler), &mut self.memory_failures) { + return; } - set.bind_group = set_bind_group(device, &self.set_bgl, &self.sampler, &set.tex); } - let Some(t) = set.tex.get(ki) else { return }; + // While WebGPU has not confirmed the full-size texture, tiles go into it (its errors, if + // it is invalid, are dropped with these scopes) and the placeholder stays bound. + let pending = set.pending.get(ki).and_then(Option::as_ref).map(|p| &p.tex); + let Some(t) = pending.or(set.tex.get(ki)) else { return }; + let oom = pending.is_some().then(|| device.push_error_scope(wgpu::ErrorFilter::OutOfMemory)); + let invalid = pending.is_some().then(|| device.push_error_scope(wgpu::ErrorFilter::Validation)); // Downscaled sets take every `step`-th texel of the tile. let (step, n) = (1usize << set.shift.min(6), TILE >> set.shift.min(6)); let small: Vec; @@ -1152,33 +1209,96 @@ impl Renderer { wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(n * bpt), rows_per_image: Some(n) }, wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 }, ); + // Innermost scope first. + drop(invalid); + drop(oom); self.content_rev += 1; if let Some(d) = set.mips_dirty.get_mut(ki) { *d = true; } } - /// Upload the aux (mesh map / debug) texture of a set: RGBA8, `size × size`. - pub fn upload_aux(&mut self, queue: &wgpu::Queue, ts: usize, size: u32, rgba: &[u8]) { + /// Upload the aux (mesh map / debug) texture of a set: RGBA8, `size × size` with `size` from + /// [`aux_size`]. The first upload allocates it. + pub fn upload_aux(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, ts: usize, size: u32, rgba: &[u8]) { let Some(set) = self.sets.get_mut(ts) else { return }; + let want = aux_size(set.size); + let ai = set.tex.len().saturating_sub(1); let Some(t) = set.tex.last() else { return }; - let (w, h) = (t.texture.width(), t.texture.height()); - if size != w || rgba.len() < (w * h * 4) as usize { + if size != want || rgba.len() < (size as usize) * (size as usize) * 4 { return; } + let awaiting = set.pending.get(ai).is_some_and(Option::is_some); + if !awaiting && t.texture.width() != size { + if set.failed.get(ai).copied().unwrap_or(true) { + return; + } + let what = format!("texture set {} (mesh map view, {size}×{size})", ts + 1); + let full = checked(device, &what, || neutral_tex(device, queue, (size, size), wgpu::TextureFormat::Rgba8Unorm, mip_count(size), &AUX_NEUTRAL)); + if !grow(set, ts, ai, full, (device, &self.set_bgl, &self.sampler), &mut self.memory_failures) { + return; + } + } + let pending = set.pending.get(ai).and_then(Option::as_ref).map(|p| &p.tex); + let Some(t) = pending.or(set.tex.last()) else { return }; + let (w, h) = (t.texture.width(), t.texture.height()); + let oom = pending.is_some().then(|| device.push_error_scope(wgpu::ErrorFilter::OutOfMemory)); + let invalid = pending.is_some().then(|| device.push_error_scope(wgpu::ErrorFilter::Validation)); queue.write_texture( wgpu::TexelCopyTextureInfo { texture: &t.texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, rgba, wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(w * 4), rows_per_image: Some(h) }, wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 }, ); + drop(invalid); + drop(oom); self.content_rev += 1; if let Some(d) = set.mips_dirty.last_mut() { *d = true; } } - /// Size of the aux texture of a set. + /// Texture sets whose display textures could not be allocated since the last call (out of + /// GPU memory: they show neutral values where they could not be allocated). + pub fn take_memory_failures(&mut self) -> Vec { + std::mem::take(&mut self.memory_failures) + } + + /// Whether a full-size texture still waits for WebGPU's verdict: keep drawing frames, since + /// [`Renderer::prepare`] installs it (or reports the failure) once the answer is in. + pub fn awaiting_gpu(&self) -> bool { + self.sets.iter().any(|s| s.pending.iter().any(Option::is_some)) + } + + /// Install the pending full-size textures WebGPU accepted; drop the ones it rejected (their + /// placeholder stays and the failure is reported). + fn resolve_pending(&mut self, device: &wgpu::Device) { + for (ts, set) in self.sets.iter_mut().enumerate() { + for slot in 0..set.pending.len() { + let poll = |p: &PendingTex| p.answer.lock().unwrap_or_else(std::sync::PoisonError::into_inner).try_recv(); + let verdict = match set.pending.get(slot).and_then(Option::as_ref).map(poll) { + None | Some(Err(std::sync::mpsc::TryRecvError::Empty)) => continue, + Some(Ok(v)) => v, + Some(Err(std::sync::mpsc::TryRecvError::Disconnected)) => Some(format!("texture set {}: the GPU never answered", ts + 1)), + }; + let Some(p) = set.pending.get_mut(slot).and_then(Option::take) else { continue }; + match verdict { + None => { + install(set, slot, p.tex, device, &self.set_bgl, &self.sampler); + self.content_rev += 1; + } + Some(e) => { + if let Some(f) = set.failed.get_mut(slot) { + *f = true; + } + memory_failed(&mut self.memory_failures, ts, &e); + } + } + } + } + } + + /// Size of the aux texture of a set (1 until a mesh map or mask was shown). pub fn aux_size(&self, ts: usize) -> Option { self.sets.get(ts).and_then(|s| s.tex.last()).map(|t| t.texture.width()) } @@ -1499,6 +1619,7 @@ impl Renderer { /// `shade.taa` that repeats the previous one adds a jittered sample to the average instead, /// and renders nothing once [`TAA_SAMPLES`] are in. pub fn prepare(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, encoder: &mut wgpu::CommandEncoder, frame: &Frame) { + self.resolve_pending(device); self.generate_mips(device, encoder); let rev = self.content_rev; let sample = match self.views.get(&frame.view_id) { @@ -1593,7 +1714,7 @@ impl Renderer { b: [fx(s.vignette), fx(s.sharpen), fx(s.grain), BLOOM_THRESHOLD], c: dof_c, d: sss_d, - e: [flag(cam.ortho), 0.0, 0.0, 0.0], + e: [flag(cam.ortho), sample as f32, 0.0, 0.0], }; let Some(v) = self.targets(device, frame.view_id, frame.size, bloom, fx_on, refraction) else { return }; queue.write_buffer(&v.globals, 0, bytemuck::bytes_of(&raw)); @@ -1841,3 +1962,76 @@ impl Renderer { self.views.remove(&id); } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::headless::Headless; + + /// A headless renderer with one 256² texture set, and the base color slot's full-size + /// texture handed over as WebGPU would: allocated, with its verdict still to come. + fn awaiting() -> Option<(Headless, std::sync::mpsc::Sender>)> { + let Ok(mut h) = Headless::new() else { + eprintln!("skipping: no GPU adapter"); + return None; + }; + h.renderer.set_texture_sets(&h.device, &h.queue, &[((256, 256), 0)], 1); + let (tx, rx) = std::sync::mpsc::channel(); + let full = neutral_tex(&h.device, &h.queue, (256, 256), display_format(DisplayKind::BaseColor), mip_count(256), &[0, 0, 0, 255]); + let r = &mut h.renderer; + let set = r.sets.get_mut(0).unwrap(); + assert!(grow(set, 0, 0, Checked::Later(full, rx), (&h.device, &r.set_bgl, &r.sampler), &mut r.memory_failures)); + Some((h, tx)) + } + + fn base_width(h: &Headless) -> u32 { + h.renderer.display_textures()[0][0].width() + } + + fn prepare(h: &mut Headless) { + let mut enc = h.device.create_command_encoder(&Default::default()); + h.renderer.resolve_pending(&h.device); + h.renderer.generate_mips(&h.device, &mut enc); + h.queue.submit([enc.finish()]); + } + + #[test] + fn a_late_texture_stays_unbound_until_accepted() { + let Some((mut h, tx)) = awaiting() else { return }; + assert!(h.renderer.awaiting_gpu()); + // Tiles go into the pending texture; the placeholder stays bound and nothing is retried. + h.renderer.upload_tile(&h.device, &h.queue, 0, DisplayKind::BaseColor, 0, 0, &[200, 30, 30, 255].repeat(64 * 64)); + prepare(&mut h); + assert_eq!(base_width(&h), 1, "no verdict yet: the placeholder stays bound"); + assert!(h.renderer.awaiting_gpu()); + tx.send(None).unwrap(); + prepare(&mut h); + assert_eq!(base_width(&h), 256, "accepted: installed"); + assert!(!h.renderer.awaiting_gpu()); + assert!(h.renderer.take_memory_failures().is_empty()); + } + + #[test] + fn a_late_rejection_keeps_the_placeholder_and_is_reported() { + let Some((mut h, tx)) = awaiting() else { return }; + tx.send(Some("texture set 1 (BaseColor, 256×256): Out of Memory".into())).unwrap(); + prepare(&mut h); + assert_eq!(base_width(&h), 1); + assert!(!h.renderer.awaiting_gpu()); + assert_eq!(h.renderer.take_memory_failures(), vec![0]); + // The failed kind is not allocated again by later tiles. + h.renderer.upload_tile(&h.device, &h.queue, 0, DisplayKind::BaseColor, 1, 0, &[200, 30, 30, 255].repeat(64 * 64)); + prepare(&mut h); + assert_eq!(base_width(&h), 1); + assert!(!h.renderer.awaiting_gpu()); + } + + #[test] + fn a_verdict_that_never_comes_counts_as_a_failure() { + let Some((mut h, tx)) = awaiting() else { return }; + drop(tx); + prepare(&mut h); + assert_eq!(base_width(&h), 1); + assert_eq!(h.renderer.take_memory_failures(), vec![0]); + } +} diff --git a/crates/render/src/shaders/fx.wgsl b/crates/render/src/shaders/fx.wgsl index cdd3963c..333664ce 100644 --- a/crates/render/src/shaders/fx.wgsl +++ b/crates/render/src/shaders/fx.wgsl @@ -22,7 +22,8 @@ fn texel_at(t: texture_2d, p: vec2) -> vec4 { // ---- Subsurface scattering: a separable bilateral blur (Jimenez et al., "Separable Subsurface // Scattering", 2015) of the scattering diffuse light, a Gaussian per color channel as wide as -// its mean free path, cut off across depth discontinuities. +// its mean free path. A tap across a depth discontinuity (or off the mesh) takes the centre's +// light instead, so no tap drops out of the sum as it crosses a silhouette. const SSS_TAPS: i32 = 8; @@ -41,17 +42,22 @@ fn sss_blur(p: vec2, dir: vec2) -> vec4 { let stride = dir * (smax * 3.0 / f32(SSS_TAPS)); let depth_range = 3.0 * max(post.d.x, max(post.d.y, post.d.z)); let inv = 1.0 / (2.0 * sigma * sigma + vec3(1e-4)); + // Wide blurs space their taps pixels apart: shifting them per pixel (interleaved gradient + // noise) and per accumulated frame turns what would show as copies of edges into fine grain. + let ign = fract(52.9829189 * fract(dot(p, vec2(0.06711056, 0.00583715)))); + let jitter = fract(ign + post.e.y * 0.618034) - 0.5; var sum = c.rgb; var wsum = vec3(1.0); for (var k = -SSS_TAPS; k <= SSS_TAPS; k++) { if (k == 0) { continue; } - let t = texel_at(src, p + stride * f32(k)); - let x = f32(k) * smax * 3.0 / f32(SSS_TAPS); + let o = f32(k) + jitter; + let t = texel_at(src, p + stride * o); + let x = o * smax * 3.0 / f32(SSS_TAPS); let wd = select(0.0, max(1.0 - abs(t.a - c.a) / depth_range, 0.0), t.a > 0.0); - let w = exp(-x * x * inv) * wd; - sum += t.rgb * w; + let w = exp(-x * x * inv); + sum += mix(c.rgb, t.rgb, wd) * w; wsum += w; } return vec4(sum / wsum, c.a); diff --git a/crates/render/src/shaders/mesh.wgsl b/crates/render/src/shaders/mesh.wgsl index ec6bcdce..6ef69758 100644 --- a/crates/render/src/shaders/mesh.wgsl +++ b/crates/render/src/shaders/mesh.wgsl @@ -4,7 +4,7 @@ // in compose/src/display.rs), the G-buffer of the depth of field and subsurface blur passes, the // 2D UV view, // the background, debug views and the 3D wireframe. Output is scene-linear HDR, premultiplied by -// alpha = scene coverage over the flat studio backdrop; exposure, tone mapping and sRGB encoding +// alpha = scene coverage over the studio backdrop; exposure, tone mapping and sRGB encoding // happen in the post pass (post.wgsl). WebGPU/WebGL2-safe (fragment passes only). struct Globals { diff --git a/crates/render/src/shaders/post.wgsl b/crates/render/src/shaders/post.wgsl index 53a64e59..6eb30868 100644 --- a/crates/render/src/shaders/post.wgsl +++ b/crates/render/src/shaders/post.wgsl @@ -1,5 +1,5 @@ // Viewport post processing, appended to util.wgsl (uses `src`, `src_samp`, `vs_full`): the -// resolved scene (linear HDR, premultiplied by scene coverage) → flat studio backdrop, exposure, +// resolved scene (linear HDR, premultiplied by scene coverage) → studio backdrop, exposure, // tone mapping, optional bloom / sharpen / vignette / grain, sRGB encoding. struct Post { @@ -7,7 +7,7 @@ struct Post { b: vec4, // x vignette, y sharpen, z grain, w bloom threshold c: vec4, // depth of field (fx.wgsl): x circle of confusion at infinity (pixels), y focus depth, z largest circle radius (pixels), w accumulation sample d: vec4, // subsurface blur (fx.wgsl): xyz mean free path per channel (world units), w pixels per world unit at depth 1 - e: vec4, // x orthographic camera (1: pixels per world unit don't fall off with depth), yzw - + e: vec4, // x orthographic camera (1: pixels per world unit don't fall off with depth), y accumulation sample, zw - }; @group(0) @binding(3) var post: Post; @@ -34,10 +34,12 @@ fn tonemap(hdr: vec3) -> vec3 { return min(x, vec3(1.0)); } -// The flat studio gray behind the scene, with a gentle falloff so the stage doesn't look like a hole. +// The studio backdrop behind the scene: the interface's cool slate (#30343b at the top to #1b1e23 +// at the bottom, faintly tinted so colors still read true), a little darker in the corners so the +// stage doesn't look like a hole. fn backdrop(uv: vec2) -> vec3 { - let r = length(uv * 2.0 - 1.0) * 0.35; - return vec3(0.0232 * (1.06 - r * r)); + let d = uv * 2.0 - 1.0; + return mix(vec3(0.0295, 0.0343, 0.0437), vec3(0.0110, 0.0130, 0.0168), uv.y) * (1.0 - 0.09 * dot(d, d)); } // Display-linear color of one pixel (scene over backdrop), without bloom. diff --git a/crates/render/src/shaders/trace_post.wgsl b/crates/render/src/shaders/trace_post.wgsl index d4ddc05b..0c0871d8 100644 --- a/crates/render/src/shaders/trace_post.wgsl +++ b/crates/render/src/shaders/trace_post.wgsl @@ -104,9 +104,10 @@ fn denoise_step(@builtin(global_invocation_id) id: vec3) { } } +// The viewport's studio backdrop (matches post.wgsl). fn backdrop(uv: vec2) -> vec3 { - let r = length(uv * 2.0 - 1.0) * 0.35; - return vec3(0.0232 * (1.06 - r * r)); + let d = uv * 2.0 - 1.0; + return mix(vec3(0.0295, 0.0343, 0.0437), vec3(0.0110, 0.0130, 0.0168), uv.y) * (1.0 - 0.09 * dot(d, d)); } fn tonemap(hdr: vec3) -> vec3 { diff --git a/crates/render/src/trace.rs b/crates/render/src/trace.rs index 22e64d06..1a592a49 100644 --- a/crates/render/src/trace.rs +++ b/crates/render/src/trace.rs @@ -441,10 +441,10 @@ impl Tracer { } } -/// The viewport's flat studio gray with a gentle falloff (matches the post pass). +/// The viewport's studio backdrop: a cool slate, lighter at the top (matches the post pass). fn backdrop(uv: Vec2) -> Vec3 { - let r = (uv * 2.0 - Vec2::ONE).length() * 0.35; - Vec3::splat(0.0232 * (1.06 - r * r)) + let d = uv * 2.0 - Vec2::ONE; + Vec3::new(0.0295, 0.0343, 0.0437).lerp(Vec3::new(0.0110, 0.0130, 0.0168), uv.y) * (1.0 - 0.09 * d.length_squared()) } fn tonemap(hdr: Vec3, d: &TraceDisplay) -> Vec3 { diff --git a/crates/render/tests/headless.rs b/crates/render/tests/headless.rs index 8ef1b897..864c70c3 100644 --- a/crates/render/tests/headless.rs +++ b/crates/render/tests/headless.rs @@ -734,3 +734,47 @@ fn refraction_shows_the_scene_behind_transmissive_surfaces() { let frosted = render(&mut h, &refr, "refr_frosted_checker"); assert!(detail(&frosted, &ball) < detail(&clear, &ball), "frosted glass blurs the scene behind"); } + +/// Kinds in [`DisplayKind::ALL`] order with each set's display texture widths, then the aux width. +fn widths(h: &Headless) -> Vec> { + h.renderer.display_textures().iter().map(|s| s.iter().map(|t| t.width()).collect()).collect() +} + +#[test] +fn texture_sets_take_no_gpu_memory_until_painted() { + // A mesh with many materials (one texture set each) must not reserve full-size textures + // for every set up front: that ran a 4 GB GPU out of memory, and wgpu's handler aborted. + let Some((mut h, _)) = setup() else { return }; + let sets: Vec<((u32, u32), usize)> = (0..40).map(|m| ((2048, 2048), m)).collect(); + h.renderer.set_texture_sets(&h.device, &h.queue, &sets, 40); + assert!(widths(&h).iter().flatten().all(|w| *w == 1), "every display texture starts as a 1×1 placeholder"); + assert!((0..40).all(|ts| h.renderer.aux_size(ts) == Some(1)), "so does every aux texture"); + // A neutral tile changes nothing; the first painted one allocates that kind alone. + let kind = DisplayKind::BaseColor; + let neutral = kind.default_texel().repeat(64 * 64); + h.renderer.upload_tile(&h.device, &h.queue, 3, kind, 0, 0, &neutral); + assert_eq!(widths(&h)[3][0], 1); + h.renderer.upload_tile(&h.device, &h.queue, 3, kind, 0, 0, &[200, 30, 30, 255].repeat(64 * 64)); + let w = widths(&h); + assert_eq!(w[3][0], 2048, "the painted kind is full size"); + assert!(w[3][1..].iter().all(|w| *w == 1) && w[2].iter().all(|w| *w == 1), "nothing else was allocated"); + // The aux texture is allocated by its first upload, at the set's aux size only. + h.renderer.upload_aux(&h.device, &h.queue, 3, 512, &[0; 512 * 512 * 4]); + assert_eq!(h.renderer.aux_size(3), Some(1), "a wrong aux size is ignored"); + h.renderer.upload_aux(&h.device, &h.queue, 3, 2048, &[90; 2048 * 2048 * 4]); + assert_eq!(h.renderer.aux_size(3), Some(2048)); + assert!(h.renderer.take_memory_failures().is_empty()); +} + +#[test] +fn painted_placeholders_render_like_full_textures() { + // A set painted in one kind renders that paint whether the other kinds are placeholders. + let Some((mut h, frame)) = setup() else { return }; + let before = render(&mut h, &frame, "placeholders"); + fill(&mut h, &[0, 1], DisplayKind::BaseColor, &[220, 40, 40, 255]); + let red = render(&mut h, &frame, "painted_base_color"); + let (w, hgt) = (frame.size[0], frame.size[1]); + let [r0, g0, _] = before.at(w / 2, hgt / 2); + let [r1, g1, _] = red.at(w / 2, hgt / 2); + assert!(r1 > r0 && g1 < g0, "the painted base color shows: {:?} → {:?}", before.at(w / 2, hgt / 2), red.at(w / 2, hgt / 2)); +} diff --git a/crates/texel/src/colorspace.rs b/crates/texel/src/colorspace.rs new file mode 100644 index 00000000..a685cba5 --- /dev/null +++ b/crates/texel/src/colorspace.rs @@ -0,0 +1,217 @@ +//! Built-in colour spaces as plain maths: sRGB, linear Rec.709, ACEScg and ACES2065-1. +//! +//! The conversion matrices are derived at first use from the published primaries and white points +//! (ITU-R BT.709, ACES S-2014-004 for AP1, SMPTE ST 2065-1 for AP0) with Bradford chromatic +//! adaptation, so nothing is copied from a colour-management library. TextureCraft's colour +//! channels are linear Rec.709 internally; this module converts them for export. +//! +//! Only colour is converted. Data (normal, height, roughness...) has no colour space and never +//! goes through here. + +use std::sync::OnceLock; + +use crate::linear_to_srgb; + +/// The colour space of exported colour images. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub enum ColorSpace { + /// sRGB-encoded (display-referred, 0–1), Rec.709 primaries. + #[default] + Srgb, + /// Scene-linear Rec.709 / sRGB primaries, D65. + LinearRec709, + /// Scene-linear ACES AP1 primaries. + AcesCg, + /// Scene-linear ACES AP0 primaries (the archival interchange space). + Aces2065, +} + +impl ColorSpace { + pub const ALL: [ColorSpace; 4] = [ColorSpace::Srgb, ColorSpace::LinearRec709, ColorSpace::AcesCg, ColorSpace::Aces2065]; + + pub fn name(self) -> &'static str { + match self { + ColorSpace::Srgb => "sRGB", + ColorSpace::LinearRec709 => "Linear Rec.709", + ColorSpace::AcesCg => "ACEScg", + ColorSpace::Aces2065 => "ACES2065-1", + } + } + + /// A space by name, ignoring case, spaces and punctuation ("linear rec709", "ap1", "srgb_texture"). + pub fn from_name(name: &str) -> Option { + let key: String = name.chars().filter(|c| c.is_ascii_alphanumeric()).collect::().to_ascii_lowercase(); + Some(match key.as_str() { + "srgb" | "srgbtexture" => ColorSpace::Srgb, + "linearrec709" | "linearsrgb" | "linear" | "rec709" => ColorSpace::LinearRec709, + "acescg" | "ap1" => ColorSpace::AcesCg, + "aces20651" | "aces2065" | "ap0" | "aces" => ColorSpace::Aces2065, + _ => return None, + }) + } + + /// Whether values are scene-linear light. + pub fn is_linear(self) -> bool { + self != ColorSpace::Srgb + } + + fn primaries(self) -> Primaries { + match self { + ColorSpace::Srgb | ColorSpace::LinearRec709 => REC709, + ColorSpace::AcesCg => AP1, + ColorSpace::Aces2065 => AP0, + } + } + + /// Linear Rec.709 `rgb` as values in this space: the primaries are converted, and sRGB + /// also gets its transfer curve (clamped to 0–1). Linear spaces keep values outside 0–1. + /// Non-finite input becomes 0. + pub fn from_linear_rec709(self, rgb: [f32; 3]) -> [f32; 3] { + let rgb = rgb.map(|v| if v.is_finite() { v } else { 0.0 }); + let out = match matrix_to(self) { + Some(m) => [0, 1, 2].map(|i| m[i][0] * rgb[0] + m[i][1] * rgb[1] + m[i][2] * rgb[2]), + None => rgb, + }; + if self == ColorSpace::Srgb { out.map(linear_to_srgb) } else { out } + } +} + +type M3 = [[f64; 3]; 3]; + +#[derive(Clone, Copy)] +struct Primaries { + r: [f64; 2], + g: [f64; 2], + b: [f64; 2], + white: [f64; 2], +} + +const D65: [f64; 2] = [0.3127, 0.3290]; +const D60_ACES: [f64; 2] = [0.32168, 0.33767]; +const REC709: Primaries = Primaries { r: [0.640, 0.330], g: [0.300, 0.600], b: [0.150, 0.060], white: D65 }; +const AP1: Primaries = Primaries { r: [0.713, 0.293], g: [0.165, 0.830], b: [0.128, 0.044], white: D60_ACES }; +const AP0: Primaries = Primaries { r: [0.7347, 0.2653], g: [0.0, 1.0], b: [0.0001, -0.0770], white: D60_ACES }; + +const BRADFORD: M3 = [[0.8951, 0.2664, -0.1614], [-0.7502, 1.7135, 0.0367], [0.0389, -0.0685, 1.0296]]; + +fn mul(a: &M3, b: &M3) -> M3 { + let mut o = [[0.0; 3]; 3]; + for (i, row) in o.iter_mut().enumerate() { + for (j, v) in row.iter_mut().enumerate() { + *v = (0..3).map(|k| a[i][k] * b[k][j]).sum(); + } + } + o +} + +fn apply(m: &M3, v: [f64; 3]) -> [f64; 3] { + [0, 1, 2].map(|i| m[i][0] * v[0] + m[i][1] * v[1] + m[i][2] * v[2]) +} + +fn inverse(m: &M3) -> Option { + let c = |r: usize, c: usize| { + let (r1, r2) = ((r + 1) % 3, (r + 2) % 3); + let (c1, c2) = ((c + 1) % 3, (c + 2) % 3); + m[r1][c1] * m[r2][c2] - m[r1][c2] * m[r2][c1] + }; + let det = m[0][0] * c(0, 0) + m[0][1] * c(0, 1) + m[0][2] * c(0, 2); + if det.abs() < 1e-12 || !det.is_finite() { + return None; + } + let mut o = [[0.0; 3]; 3]; + for (i, row) in o.iter_mut().enumerate() { + for (j, v) in row.iter_mut().enumerate() { + *v = c(j, i) / det; + } + } + Some(o) +} + +fn xy_to_xyz(xy: [f64; 2]) -> [f64; 3] { + [xy[0] / xy[1], 1.0, (1.0 - xy[0] - xy[1]) / xy[1]] +} + +/// RGB (linear) to XYZ for a set of primaries, scaled so white maps to the white point. +fn rgb_to_xyz(p: &Primaries) -> Option { + let (r, g, b) = (xy_to_xyz(p.r), xy_to_xyz(p.g), xy_to_xyz(p.b)); + let cols = [[r[0], g[0], b[0]], [r[1], g[1], b[1]], [r[2], g[2], b[2]]]; + let s = apply(&inverse(&cols)?, xy_to_xyz(p.white)); + Some([[r[0] * s[0], g[0] * s[1], b[0] * s[2]], [r[1] * s[0], g[1] * s[1], b[1] * s[2]], [r[2] * s[0], g[2] * s[1], b[2] * s[2]]]) +} + +/// Bradford chromatic adaptation from one white point to another. +fn adapt(from: [f64; 2], to: [f64; 2]) -> Option { + let (cs, cd) = (apply(&BRADFORD, xy_to_xyz(from)), apply(&BRADFORD, xy_to_xyz(to))); + let scale = [[cd[0] / cs[0], 0.0, 0.0], [0.0, cd[1] / cs[1], 0.0], [0.0, 0.0, cd[2] / cs[2]]]; + Some(mul(&inverse(&BRADFORD)?, &mul(&scale, &BRADFORD))) +} + +/// The matrix from linear Rec.709 to the linear primaries of `to` (cached). +fn matrix_to(to: ColorSpace) -> Option<[[f32; 3]; 3]> { + static CACHE: OnceLock<[Option<[[f32; 3]; 3]>; 4]> = OnceLock::new(); + let table = CACHE.get_or_init(|| { + ColorSpace::ALL.map(|s| { + let (from, to) = (REC709, s.primaries()); + let m = mul(&inverse(&rgb_to_xyz(&to)?)?, &mul(&adapt(from.white, to.white)?, &rgb_to_xyz(&from)?)); + Some(m.map(|r| r.map(|v| v as f32))) + }) + }); + let i = ColorSpace::ALL.iter().position(|s| *s == to)?; + table.get(i).copied().flatten() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::srgb_to_linear; + + fn close(a: [f32; 3], b: [f32; 3], tol: f32) -> bool { + a.iter().zip(b).all(|(x, y)| (x - y).abs() <= tol) + } + + #[test] + fn white_stays_white_in_every_linear_space() { + for s in [ColorSpace::LinearRec709, ColorSpace::AcesCg, ColorSpace::Aces2065] { + assert!(close(s.from_linear_rec709([1.0; 3]), [1.0; 3], 1e-4), "{s:?}"); + } + assert!(close(ColorSpace::Srgb.from_linear_rec709([1.0; 3]), [1.0; 3], 1e-5)); + } + + #[test] + fn rec709_primaries_in_acescg_match_published_values() { + // Rec.709 red in ACEScg (AP1, D60): the widely published 0.6131 0.0702 0.0206. + assert!(close(ColorSpace::AcesCg.from_linear_rec709([1.0, 0.0, 0.0]), [0.6131, 0.0702, 0.0206], 2e-3)); + // And in ACES2065-1 (AP0): 0.4397 0.0897 0.0175. + assert!(close(ColorSpace::Aces2065.from_linear_rec709([1.0, 0.0, 0.0]), [0.4397, 0.0897, 0.0175], 2e-3)); + } + + #[test] + fn grey_stays_neutral_and_srgb_is_the_transfer_curve() { + for s in ColorSpace::ALL { + let o = s.from_linear_rec709([0.18; 3]); + assert!(close(o, [o[0]; 3], 1e-4), "{s:?} {o:?}"); + } + assert!(close(ColorSpace::Srgb.from_linear_rec709([0.5; 3]), [linear_to_srgb(0.5); 3], 1e-6)); + assert!((srgb_to_linear(ColorSpace::Srgb.from_linear_rec709([0.25; 3])[0]) - 0.25).abs() < 1e-5); + assert_eq!(ColorSpace::LinearRec709.from_linear_rec709([0.3, 2.0, -1.0]), [0.3, 2.0, -1.0], "linear Rec.709 is the identity, values above 1 kept"); + } + + #[test] + fn hostile_values_stay_finite() { + for s in ColorSpace::ALL { + assert!(s.from_linear_rec709([f32::NAN, f32::INFINITY, f32::NEG_INFINITY]).iter().all(|v| v.is_finite()), "{s:?}"); + } + } + + #[test] + fn names_round_trip_and_aliases_work() { + for s in ColorSpace::ALL { + assert_eq!(ColorSpace::from_name(s.name()), Some(s)); + } + assert_eq!(ColorSpace::from_name("srgb_texture"), Some(ColorSpace::Srgb)); + assert_eq!(ColorSpace::from_name("AP1"), Some(ColorSpace::AcesCg)); + assert_eq!(ColorSpace::from_name("linear"), Some(ColorSpace::LinearRec709)); + assert_eq!(ColorSpace::from_name("nope"), None); + assert!(!ColorSpace::Srgb.is_linear() && ColorSpace::AcesCg.is_linear()); + } +} diff --git a/crates/texel/src/lib.rs b/crates/texel/src/lib.rs index 329ffaa4..982ca101 100644 --- a/crates/texel/src/lib.rs +++ b/crates/texel/src/lib.rs @@ -6,10 +6,12 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +pub mod colorspace; pub mod dilate; pub mod noise; pub mod tile; +pub use colorspace::ColorSpace; pub use dilate::DilationMap; pub use tile::{TILE, TILE_AREA, TileData, TileImage, from_u16, from_u16_signed, to_u16, to_u16_signed}; diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 735139ce..7887bf26 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -14,6 +14,7 @@ texturecraft-render = { workspace = true } eframe = { workspace = true, features = ["default_fonts", "wgpu", "persistence"] } egui = { workspace = true } craft-ui = { workspace = true } +craft-window = { workspace = true } egui-phosphor = { version = "0.14", features = ["regular", "fill"] } serde = { workspace = true } serde_json = { workspace = true } @@ -30,6 +31,12 @@ sys-locale = "0.3" # Floating panels open as OS windows. craft-ui = { workspace = true, features = ["native-windows"] } +# build.rs: the interface faces lose their Private Use Area, where the icon font draws (the +# versions craft-libs' craft-fonts-build subsets with). +[build-dependencies] +skera = "0.8" +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] wasm-bindgen = "0.2" @@ -40,3 +47,6 @@ web-sys = { version = "0.3", features = ["Window", "Document", "HtmlElement", "H # winit needs a window system on Linux, so the crate's own tests build with X11. [target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies] eframe = { workspace = true, features = ["x11"] } +# Offscreen pictures of the whole window (tests/ui_snapshots.rs). +egui_kittest = { version = "0.37", features = ["wgpu", "eframe"] } +image = { workspace = true } diff --git a/crates/ui-egui/build.rs b/crates/ui-egui/build.rs index 229bcc8f..86168323 100644 --- a/crates/ui-egui/build.rs +++ b/crates/ui-egui/build.rs @@ -1,21 +1,33 @@ -//! Embeds the optional craft-fonts CJK UI fonts (storytold/craft-fonts) when `CRAFT_FONTS_DIR` -//! points at a checkout; without it `CRAFT_FONTS` is empty and the UI uses system fonts. The -//! recipe follows craft-fonts' `docs/integration.md`; no font file is committed here. +//! Embeds the optional craft-fonts UI fonts (storytold/craft-fonts) when `CRAFT_FONTS_DIR` points +//! at a checkout: Inter for the interface (from its Latin catalog) and the CJK and Arabic +//! faces; without it `CRAFT_FONTS` is empty and the UI uses egui's and the system's fonts. The +//! recipe follows craft-fonts' `docs/integration.md`; no font file is committed here. The Latin +//! faces are embedded without their Private Use Area ([`without_private_use`]). use std::fmt::Write as _; use std::path::PathBuf; -/// The UI faces TextureCraft embeds (family, style): one sans font per script. -const UI_FONTS: &[(&str, &str)] = &[("BIZ UDPGothic", "Regular"), ("Noto Sans CJK SC", "Regular")]; -/// The web build has a download budget: only the Japanese UI font (~4.5 MB). -const WEB_FONTS: &[(&str, &str)] = &[("BIZ UDPGothic", "Regular")]; +/// The UI faces TextureCraft embeds (family, style) per manifest: desktop, then web (the web build +/// has a download budget: of the CJK faces only the Japanese one, ~4.5 MB). +const MANIFESTS: &[(&str, Faces, Faces)] = &[ + ("fonts/manifest.txt", &[("BIZ UDPGothic", "Regular"), ("Noto Sans CJK SC", "Regular"), ARABIC], &[("BIZ UDPGothic", "Regular"), ARABIC]), + // The interface font, regular and semibold (0.8 MB). + (LATIN_MANIFEST, LATIN, LATIN), +]; +/// The Arabic face (0.8 MB, so the web build has it too). +const ARABIC: (&str, &str) = ("Noto Sans Arabic", "Regular"); +/// Newer than the core catalog: a checkout without it keeps the default interface font. +const LATIN_MANIFEST: &str = "fonts/latin-manifest.txt"; +const LATIN: Faces = &[("Inter", "Regular"), ("Inter", "SemiBold")]; +/// (family, style) pairs of a manifest. +type Faces = &'static [(&'static str, &'static str)]; fn main() { println!("cargo::rerun-if-env-changed=CRAFT_FONTS_DIR"); println!("cargo::rerun-if-env-changed=CRAFT_FONTS_REQUIRED"); let mut src = String::from("pub static CRAFT_FONTS: &[CraftFont] = &[\n"); if let Some(dir) = std::env::var_os("CRAFT_FONTS_DIR").map(PathBuf::from) { - match craft_fonts(&dir) { + match MANIFESTS.iter().map(|(rel, desktop, web)| craft_fonts(&dir, rel, desktop, web)).collect::>() { Ok(entries) => src.push_str(&entries), Err(e) if std::env::var_os("CRAFT_FONTS_REQUIRED").is_some() => { println!("cargo::error=CRAFT_FONTS_DIR={}: {e}", dir.display()); @@ -30,13 +42,16 @@ fn main() { } } -/// One `CraftFont { .. }` initialiser per wanted manifest line. -fn craft_fonts(dir: &std::path::Path) -> Result { - let manifest = dir.join("fonts/manifest.txt"); +/// One `CraftFont { .. }` initialiser per wanted line of manifest `rel`. +fn craft_fonts(dir: &std::path::Path, rel: &str, desktop: &[(&str, &str)], web: &[(&str, &str)]) -> Result { + let manifest = dir.join(rel); println!("cargo::rerun-if-changed={}", manifest.display()); + if rel == LATIN_MANIFEST && !manifest.exists() { + return Ok(String::new()); + } let text = std::fs::read_to_string(&manifest).map_err(|e| format!("{}: {e}", manifest.display()))?; let wasm = std::env::var("CARGO_CFG_TARGET_ARCH").is_ok_and(|a| a == "wasm32"); - let wanted = if wasm { WEB_FONTS } else { UI_FONTS }; + let wanted = if wasm { web } else { desktop }; let mut out = String::new(); for line in text.lines().map(str::trim).filter(|l| !l.is_empty() && !l.starts_with('#')) { let f: Vec<&str> = line.split(" | ").map(str::trim).collect(); @@ -46,8 +61,14 @@ fn craft_fonts(dir: &std::path::Path) -> Result { if !wanted.contains(&(*family, *style)) { continue; } - let path = dir.join(file).canonicalize().map_err(|e| format!("{file}: {e}"))?; + let mut path = dir.join(file).canonicalize().map_err(|e| format!("{file}: {e}"))?; println!("cargo::rerun-if-changed={}", path.display()); + if rel == LATIN_MANIFEST { + let bytes = std::fs::read(&path).map_err(|e| format!("{file}: {e}"))?; + let out = PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default()).join(path.file_name().unwrap_or_default()); + std::fs::write(&out, without_private_use(&bytes).map_err(|e| format!("{file}: {e}"))?).map_err(|e| format!("{}: {e}", out.display()))?; + path = out; + } let scripts: Vec = scripts.split(',').map(|s| format!("{:?}", s.trim())).collect(); let _ = writeln!( out, @@ -58,3 +79,33 @@ fn craft_fonts(dir: &std::path::Path) -> Result { } Ok(out) } + +/// `font` without the characters of the Private Use Area (U+E000–U+F8FF): the icon font (Phosphor) +/// draws there, and Inter, ahead of it in the fallback list, has alternates of its own there that +/// would show instead of the icons. Everything else (layout features, hinting) is kept, as +/// craft-libs' `craft-fonts-build` subsets. +fn without_private_use(font: &[u8]) -> Result, String> { + use skera::{Plan, SubsetFlags, subset_font}; + use skrifa::raw::collections::IntSet; + use skrifa::raw::types::NameId; + use skrifa::{FontRef, GlyphId, MetadataProvider, Tag}; + let font = FontRef::new(font).map_err(|e| e.to_string())?; + let mut unicodes = IntSet::::empty(); + unicodes.extend(font.charmap().mappings().map(|(c, _)| c).filter(|c| !(0xE000..=0xF8FF).contains(c))); + let mut name_ids = IntSet::::empty(); + name_ids.insert_range(NameId::new(0)..=NameId::new(6)); + let mut languages = IntSet::::empty(); + languages.insert(0x0409); + let plan = Plan::new( + &IntSet::::empty(), + &unicodes, + &font, + SubsetFlags::default(), + &IntSet::::empty(), + &IntSet::::all(), + &IntSet::::all(), + &name_ids, + &languages, + ); + subset_font(&font, &plan).map_err(|e| e.to_string()) +} diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 83ab93a6..167b9754 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -5,7 +5,7 @@ //! - `command.run {id, params?}`: run an engine command (programmatic: never opens a dialog). //! - `command.list {filter?}`: every command with params docs and enabled state. //! - `session.inspect`: project, texture sets, layer stack, tool, camera, display, history. -//! - `ui.inspect`: the UI state (panels, windows, mode, layout, viewport rect). +//! - `ui.inspect`: the UI state (panels, windows, mode, layout, viewport rect, who draws the title bar). //! - `ui.menu.list`: the menu catalog with ids, shortcuts and whether each is live. //! - `ui.menu.invoke {id}`: behave like a menu click (may open a window). //! - `ui.set {...}`: merge fields into the UI state (e.g. `{"layout":"Only3D"}`). @@ -108,6 +108,7 @@ pub fn handle(app: &mut TextureCraftApp, ctx: &egui::Context, method: &str, p: & "viewport": [r.min.x, r.min.y, r.width(), r.height()], "fps": app.fps, "uiMs": app.ui_ms, + "titleBar": app.title_bar.name(), "baking": app.bake_progress(), "toasts": app.toasts.iter().map(|t| json!({"text": t.text, "error": t.error})).collect::>(), })) diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 73ff540d..0bf4c63e 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -5,7 +5,8 @@ use egui::{Color32, Rect, RichText, Sense, Stroke, Ui, pos2, vec2}; use egui_phosphor::regular as ic; use serde_json::{Value, json}; use texturecraft_engine::core::{ - BakedMap, BlendMode, Channel, Decal, EffectKind, Fill, Filter, GeneratorKind, Layer, LayerId, LayerKind, LinkParam, MaterialLink, ProceduralKind, Source, + BakedMap, BlendMode, Channel, Decal, Effect, EffectKind, Fill, Filter, GeneratorKind, Layer, LayerId, LayerKind, LinkParam, MaterialLink, ProceduralKind, + Source, }; use texturecraft_engine::filter_lib::{FILTERS, scalar_params}; use texturecraft_engine::paint::{BrushAlpha, alphas}; @@ -16,7 +17,7 @@ use crate::i18n::{n_, tr, trf}; use crate::shelf::{Asset, ShelfDrag}; use crate::state::PropsTab; use crate::theme::{Tokens, caption}; -use crate::widgets::{chip, color_swatch, combo, dnd_release, elided, icon_button, section, slider}; +use crate::widgets::{chip, color_swatch, combo, dnd_release, elided, histogram, icon_button, section, slider, slider_edit}; const TAG_COLORS: [Color32; 8] = [ Color32::from_rgb(0xc0, 0x40, 0x40), @@ -47,6 +48,23 @@ pub(crate) fn texture_set_list(app: &mut TextureCraftApp, ui: &mut Ui) { }) .collect(); let active = app.session.ts(); + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 4.0; + ui.menu_button(RichText::new(ic::EYE).size(14.0), |ui| { + for (label, mode) in [(tr("Show all"), "showAll"), (tr("Hide all"), "hideAll"), (tr("Invert show/hide"), "invert")] { + if ui.button(label).clicked() { + app.run("textureSet.visibility", json!({ "mode": mode })); + ui.close(); + } + } + }) + .response + .on_hover_text(tr("Show or hide texture sets")); + let solo = sets.iter().enumerate().all(|(i, s)| s.2 == (i == active)); + if icon_button(ui, ic::FRAME_CORNERS, tr("Focus: show only the active texture set"), solo && sets.len() > 1, 22.0).clicked() { + app.run("textureSet.visibility", json!({ "mode": "solo" })); + } + }); egui::ScrollArea::vertical().id_salt("ts_scroll").show(ui, |ui| { for (i, (name, size, visible)) in sets.into_iter().enumerate() { let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click()); @@ -95,17 +113,35 @@ pub(crate) fn texture_set_list(app: &mut TextureCraftApp, ui: &mut Ui) { // --------------------------------------------------------------------------------------------- // Layers +/// The add-mask commands, for the selected layer or (`row`) the layer whose mask slot was clicked. +fn add_mask_menu(app: &mut TextureCraftApp, ui: &mut Ui, row: Option) { + let enabled = row.is_some() || app.session.selected_layer().is_some(); + for (label, id) in + [(tr("Add white mask"), "mask.add.white"), (tr("Add black mask"), "mask.add.black"), (tr("Add mask with color selection"), "mask.add.colorSelection")] + { + if ui.add_enabled(enabled, egui::Button::new(label)).clicked() { + if let Some(layer) = row { + app.run("layer.select", json!({ "layer": layer })); + } + app.run(id, Value::Null); + ui.close(); + } + } +} + pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) { let tk = Tokens::get(ui.ctx()); // Wraps in a narrow column instead of widening the rows below past the panel. ui.horizontal_wrapped(|ui| { + // The menu buttons as compact as the icon buttons beside them. + ui.spacing_mut().button_padding.x = 4.0; + ui.spacing_mut().item_spacing.x = 4.0; let chans = app.session.doc.project.texture_set(app.session.ts()).map(|t| t.channel_list()).unwrap_or_default(); egui::ComboBox::from_id_salt("layer_channel").width(86.0).selected_text(tr(app.ui.layer_channel.label())).show_ui(ui, |ui| { for c in chans { ui.selectable_value(&mut app.ui.layer_channel, c, tr(c.label())); } }); - let has = app.session.selected_layer().is_some(); let selected = app.session.selected_layer().and_then(|id| app.session.doc.project.layers.get(&id)).cloned(); ui.menu_button(RichText::new(ic::MAGIC_WAND).size(14.0), |ui| match &selected { Some(l) => effect_menu(app, ui, l), @@ -115,20 +151,7 @@ pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) { }) .response .on_hover_text(tr("Add effect")); - ui.menu_button(RichText::new(ic::SELECTION_BACKGROUND).size(14.0), |ui| { - for (label, id) in [ - (tr("Add white mask"), "mask.add.white"), - (tr("Add black mask"), "mask.add.black"), - (tr("Add mask with color selection"), "mask.add.colorSelection"), - ] { - if ui.add_enabled(has, egui::Button::new(label)).clicked() { - app.run(id, Value::Null); - ui.close(); - } - } - }) - .response - .on_hover_text(tr("Add mask")); + ui.menu_button(RichText::new(ic::SELECTION_BACKGROUND).size(14.0), |ui| add_mask_menu(app, ui, None)).response.on_hover_text(tr("Add mask")); if icon_button(ui, ic::PAINT_BRUSH, tr("Add paint layer"), false, 22.0).clicked() { app.run("layer.add.paint", Value::Null); } @@ -233,11 +256,11 @@ fn layer_tree(app: &mut TextureCraftApp, ui: &mut Ui, id: LayerId, depth: usize) let Some(layer) = app.session.doc.project.layers.get(&id).cloned() else { return }; layer_row(app, ui, &layer, depth); for e in layer.content_effects.iter().rev() { - effect_row(app, ui, &layer, e.id, &e.name, e.visible, depth + 1, ic::SPHERE); + effect_row(app, ui, &layer, &layer.content_effects, e, depth + 1, ic::SPHERE); } if let Some(m) = &layer.mask { for e in m.effects.iter().rev() { - effect_row(app, ui, &layer, e.id, &e.name, e.visible, depth + 1, ic::MAGIC_WAND); + effect_row(app, ui, &layer, &m.effects, e, depth + 1, ic::MAGIC_WAND); } } if let LayerKind::Group { children, collapsed } = &layer.kind @@ -255,6 +278,7 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize let selected = app.session.selected_layer() == Some(layer.id); let h = 38.0; let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), h), Sense::click_and_drag()); + resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, selected, &layer.name)); let p = ui.painter().clone(); let bg = if selected && app.session.target == StackTarget::Content { tk.row_selected @@ -371,7 +395,13 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize p.rect_stroke(mask_rect.expand(2.0), 1.0, Stroke::new(1.5, tk.warning), egui::StrokeKind::Outside); } } else { - p.rect_stroke(mask_rect, 1.0, Stroke::new(1.0, tk.field_border), egui::StrokeKind::Inside); + // The empty slot adds a mask to this layer. + let slot = ui.interact(mask_rect, ui.scope_id().with(("mask_slot", layer.id.0)), Sense::click()).on_hover_text(tr("Add mask")); + p.rect_stroke(mask_rect, 1.0, Stroke::new(1.0, if slot.hovered() { tk.accent } else { tk.field_border }), egui::StrokeKind::Inside); + if slot.hovered() { + p.text(mask_rect.center(), egui::Align2::CENTER_CENTER, ic::PLUS, egui::FontId::proportional(12.0), tk.text); + } + egui::Popup::menu(&slot).show(|ui| add_mask_menu(app, ui, Some(layer.id.0))); } // Name (or rename editor). let name_rect = Rect::from_min_max(pos2(x, rect.top() + 4.0), pos2(mask_rect.left() - 4.0, rect.bottom() - 4.0)); @@ -379,12 +409,22 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize if renaming { let mut child = ui.new_child(egui::UiBuilder::new().max_rect(name_rect).layout(egui::Layout::left_to_right(egui::Align::Center))); if let Some((_, buf)) = app.ui.rename.as_mut() { - let r = child.add(egui::TextEdit::singleline(buf).desired_width(name_rect.width())); - r.request_focus(); - if r.lost_focus() { - let name = buf.clone(); + // Escape reaches us instead of just unfocusing the field, so it can cancel. + let filter = egui::EventFilter { horizontal_arrows: true, vertical_arrows: true, escape: true, ..Default::default() }; + let r = child.add(egui::TextEdit::singleline(buf).desired_width(name_rect.width()).event_filter(filter)); + if ui.input(|i| i.key_pressed(egui::Key::Escape)) { app.ui.rename = None; - app.run("layer.rename", json!({"layer": layer.id.0, "name": name})); + } else if r.lost_focus() { + // Enter or a click elsewhere. + let name = buf.trim().to_string(); + app.ui.rename = None; + if !name.is_empty() && name != layer.name { + app.run("layer.rename", json!({"layer": layer.id.0, "name": name})); + } + } else if !r.has_focus() { + // Only until the field has focus: requesting it every frame kept it from ever + // losing focus, which trapped the editor open and blocked every shortcut. + r.request_focus(); } } } else { @@ -422,8 +462,10 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize }); let mut op = (b.opacity * 100.0).round(); let mut child = ui.new_child(egui::UiBuilder::new().max_rect(op_rect).layout(egui::Layout::right_to_left(egui::Align::Center))); - // As tall as its slot in the row (the style's fields are taller). + // As tall as its slot in the row (the style's fields are taller), in the row's small print. child.spacing_mut().interact_size.y = op_rect.height(); + child.spacing_mut().button_padding = vec2(4.0, 0.0); + child.style_mut().override_text_style = Some(egui::TextStyle::Small); let r = child.add(egui::DragValue::new(&mut op).range(0.0..=100.0).speed(0.5).max_decimals(0)); if r.changed() { app.run("layer.blend", json!({"layer": layer.id.0, "channel": ch.id(), "opacity": op / 100.0})); @@ -432,13 +474,13 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize p.text(blend_rect.right_center(), egui::Align2::RIGHT_CENTER, tr("off"), egui::FontId::proportional(11.0), tk.text_dim); } // Interaction: select, rename, drag & drop, context menu. - if resp.clicked() && !eye_resp.clicked() { + if resp.clicked() && !eye_resp.clicked() && !renaming { app.run("layer.select", json!({"layer": layer.id.0})); } - if resp.double_clicked() { + if resp.double_clicked() && !eye_resp.clicked() && !renaming { app.ui.rename = Some((layer.id.0, layer.name.clone())); } - if resp.drag_started() { + if resp.drag_started() && !renaming { resp.dnd_set_drag_payload(layer.id.0); } // Drops: a layer or a shelf material lands above this row (inside a folder when dropped on @@ -481,12 +523,16 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize resp.context_menu(|ui| layer_context_menu(app, ui, layer)); } -/// One effect of a layer's content (`glyph` sphere) or mask (`glyph` wand) stack. -#[allow(clippy::too_many_arguments)] -fn effect_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: LayerId, name: &str, visible: bool, depth: usize, glyph: &str) { +/// The drag-and-drop payload of an effect row (the effect id). +struct EffectDrag(u64); + +/// Effect `e` of `stack`, a layer's content (`glyph` sphere) or mask (`glyph` wand) effects. +fn effect_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, stack: &[Effect], e: &Effect, depth: usize, glyph: &str) { let tk = Tokens::get(ui.ctx()); + let (eid, visible) = (e.id, e.visible); let selected = app.session.selected_layer() == Some(layer.id) && app.session.target == StackTarget::Effect(eid); - let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click()); + let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click_and_drag()); + resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, selected, &e.name)); let p = ui.painter().clone(); p.rect_filled( rect.shrink2(vec2(0.0, 1.0)), @@ -507,16 +553,55 @@ fn effect_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: LayerI let er = ui.interact(eye, ui.scope_id().with(("eff_eye", eid.0)), Sense::click()).on_hover_text(tr("Enable or disable the effect")); p.text(eye.center(), egui::Align2::CENTER_CENTER, if visible { ic::EYE } else { ic::EYE_SLASH }, egui::FontId::proportional(12.0), tk.text_dim); p.text(pos2(x0 + 22.0, rect.center().y), egui::Align2::LEFT_CENTER, glyph, egui::FontId::proportional(11.0), tk.text_dim); - p.text(pos2(x0 + 38.0, rect.center().y), egui::Align2::LEFT_CENTER, name, egui::FontId::proportional(11.5), tk.text); + p.text(pos2(x0 + 38.0, rect.center().y), egui::Align2::LEFT_CENTER, &e.name, egui::FontId::proportional(11.5), tk.text); if er.clicked() { app.run("effect.set", json!({"effect": eid.0, "visible": !visible})); } else if resp.clicked() { app.run("layer.select", json!({"layer": layer.id.0, "target": eid.0})); } + // Drag to reorder within the stack: a drop lands above this row, or below it from its lower half. + if resp.drag_started() { + resp.dnd_set_drag_payload(EffectDrag(eid.0)); + } + let pos = |id: u64| stack.iter().position(|x| x.id.0 == id); + let below = ui.input(|i| i.pointer.hover_pos()).is_some_and(|p| p.y > rect.center().y); + if resp.dnd_hover_payload::().is_some_and(|src| src.0 != eid.0 && pos(src.0).is_some()) { + let y = if below { rect.bottom() } else { rect.top() }; + p.line_segment([pos2(rect.left(), y), pos2(rect.right(), y)], Stroke::new(2.0, tk.accent)); + } + if let Some(src) = dnd_release::(&resp) + && let (Some(from), Some(to)) = (pos(src.0), pos(eid.0)) + && from != to + { + // Rows list the stack top first, so above this row is the next index up. + let index = match (from < to, below) { + (true, false) | (false, true) => to, + (true, true) => to - 1, + (false, false) => to + 1, + }; + app.run("effect.move", json!({"effect": src.0, "index": index})); + } resp.context_menu(|ui| { - if ui.button(tr("Remove effect")).clicked() { - app.run("effect.remove", json!({"effect": eid.0})); - ui.close(); + let keymap = app.ui.keymap.clone(); + let paste = crate::menus::enabled(app, "effect.paste"); + // The clipboard items show the layer clipboard's shortcuts, which act on a selected effect. + for (label, id, keys, enabled) in [ + (tr("Copy effect"), "effect.copy", Some("layer.copy"), true), + (tr("Cut effect"), "effect.cut", Some("layer.cut"), true), + (tr("Paste effect"), "effect.paste", Some("layer.paste"), paste), + (tr("Duplicate effect"), "effect.duplicate", None, true), + (tr("Remove effect"), "effect.remove", None, true), + ] { + let mut b = egui::Button::new(label); + if let Some(sc) = keys.and_then(|k| crate::keymap::shortcut_of(&keymap, k)) { + b = b.shortcut_text(sc); + } + if ui.add_enabled(enabled, b).clicked() { + // Selected first: a paste lands above it, a duplicate takes the selection. + app.run("layer.select", json!({"layer": layer.id.0, "target": eid.0})); + app.run(id, json!({"effect": eid.0})); + ui.close(); + } } }); } @@ -609,7 +694,9 @@ fn layer_context_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { ui.separator(); run(app, ui, tr("Cut layer(s)"), "layer.cut", json!({"layer": lid}), true); run(app, ui, tr("Copy layer(s)"), "layer.copy", json!({"layer": lid}), true); - run(app, ui, tr("Paste layer(s)"), "layer.paste", json!({}), app.session.clipboard.is_some()); + let (paste_layer, paste_effect) = (crate::menus::enabled(app, "layer.paste"), crate::menus::enabled(app, "effect.paste")); + run(app, ui, tr("Paste layer(s)"), "layer.paste", json!({}), paste_layer); + run(app, ui, tr("Paste effect"), "effect.paste", json!({}), paste_effect); let paste_instance = crate::menus::enabled(app, "layer.pasteInstance"); run(app, ui, tr("Paste as instance"), "layer.pasteInstance", json!({}), paste_instance); run(app, ui, tr("Duplicate layer(s)"), "layer.duplicate", json!({"layer": lid}), true); @@ -721,10 +808,10 @@ pub(crate) fn texture_set_settings(app: &mut TextureCraftApp, ui: &mut Ui) { } }); }); - let baked = app.session.doc.baked.get(&ts); + let images: Vec = app.session.doc.resources.keys().cloned().collect(); for m in BakedMap::ALL { - let present = baked.is_some_and(|b| b.maps.contains_key(&m)); - ui.horizontal(|ui| { + let present = app.session.doc.baked.get(&ts).is_some_and(|b| b.maps.contains_key(&m)); + let row = ui.horizontal(|ui| { let (r, _) = ui.allocate_exact_size(vec2(26.0, 26.0), Sense::hover()); ui.painter().rect_filled(r, 2.0, if present { mesh_map_color(m) } else { tk.button }); ui.vertical(|ui| { @@ -735,7 +822,36 @@ pub(crate) fn texture_set_settings(app: &mut TextureCraftApp, ui: &mut Ui) { .color(tk.text_dim), ); }); + // An image resource instead of a bake, or no map. + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.menu_button(RichText::new(ic::DOTS_THREE).size(13.0), |ui| { + ui.label(caption(tr("Images"))); + for name in &images { + if ui.button(name).clicked() { + app.run("textureSet.meshMap.set", json!({"ts": ts, "map": m.id(), "image": name})); + ui.close(); + } + } + if ui.button(tr("Import...")).clicked() { + crate::menus::invoke(app, ui.ctx(), "resource.import"); + ui.close(); + } + ui.separator(); + if ui.add_enabled(present, egui::Button::new(tr("Clear"))).clicked() { + app.run("textureSet.meshMap.clear", json!({"ts": ts, "map": m.id()})); + ui.close(); + } + }); + }); }); + // A shelf image dropped on the row becomes this mesh map. + let resp = row.response.interact(Sense::hover()).on_hover_text(tr("Drop an image from the Assets panel here to use it as this mesh map")); + if resp.dnd_hover_payload::().is_some_and(|d| matches!(d.asset, Asset::Texture(_))) { + ui.painter().rect_stroke(resp.rect.shrink(1.0), 3.0, Stroke::new(2.0, tk.accent), egui::StrokeKind::Inside); + } + if let Some(Asset::Texture(name)) = dnd_release::(&resp).map(|d| d.asset.clone()) { + app.run("textureSet.meshMap.set", json!({"ts": ts, "map": m.id(), "image": name})); + } } }); } @@ -829,10 +945,10 @@ fn height_mask_section(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { } ui.add_enabled_ui(hm.enabled, |ui| { let (mut contrast, mut offset) = (hm.contrast, hm.offset); - if slider(ui, tr("Contrast"), &mut contrast, 0.0..=16.0, 2).drag_stopped() { + if slider_edit(ui, tr("Contrast"), &mut contrast, 0.0..=16.0, 2) { app.run("layer.set", json!({"layer": id, "heightMask": {"contrast": contrast}})); } - if slider(ui, tr("Height offset"), &mut offset, -1.0..=1.0, 2).drag_stopped() { + if slider_edit(ui, tr("Height offset"), &mut offset, -1.0..=1.0, 2) { app.run("layer.set", json!({"layer": id, "heightMask": {"offset": offset}})); } }); @@ -986,6 +1102,8 @@ fn path_section(app: &mut TextureCraftApp, ui: &mut Ui) { fn brush_section(app: &mut TextureCraftApp, ui: &mut Ui) { let b = &mut app.session.tool.brush; ui.label(caption(tr("Brush"))); + let hint = tr("Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle."); + ui.label(RichText::new(hint).size(10.5).color(Tokens::get(ui.ctx()).text_dim)); section(ui, "sec_size", tr("Size"), true, |ui| { let mut size = b.size / 0.25 * 100.0; if slider(ui, tr("Size"), &mut size, 0.05..=100.0, 1).changed() { @@ -1091,7 +1209,8 @@ fn alpha_tile(ui: &mut Ui, on: bool, label: &str, paint: impl FnOnce(&egui::Pain p.rect_stroke(rect, 3.0, Stroke::new(1.0, tk.accent), egui::StrokeKind::Inside); } paint(p, Rect::from_center_size(rect.center() - vec2(0.0, 7.0), vec2(40.0, 40.0))); - p.text(rect.center_bottom() - vec2(0.0, 6.0), egui::Align2::CENTER_CENTER, label, egui::FontId::proportional(9.5), tk.viewport_text); + let name = elided(p, label, 9.5, tk.viewport_text, rect.width() - 4.0); + p.galley(rect.center_bottom() - vec2(name.size().x * 0.5, 6.0 + name.size().y * 0.5), name, tk.viewport_text); resp.on_hover_text(label) } @@ -1140,8 +1259,67 @@ fn alpha_section(app: &mut TextureCraftApp, ui: &mut Ui) { } ui.label(RichText::new(tr("More in Assets > Alphas: click one, or drag it here")).size(10.0).color(tk.text_dim)); crate::shelf::drop_target(app, ui, &zone.response, crate::shelf::DropZone::Brush); + section(ui, "sec_text", tr("Text"), true, |ui| text_section(app, ui)); } +/// Text drawn in a font, as the brush alpha or a decal (`resource.text`). +fn text_section(app: &mut TextureCraftApp, ui: &mut Ui) { + if app.ui.text.fonts.is_empty() + && let Some(f) = app.run("text.fonts", Value::Null) + { + let installed = f["installed"].as_array().into_iter().flatten().map(|v| { + let styles = v["styles"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect(); + (v["family"].as_str().unwrap_or_default().to_string(), styles) + }); + let built_in = f["builtIn"].as_array().into_iter().flatten().filter_map(Value::as_str).map(|n| (n.to_string(), Vec::new())); + app.ui.text.fonts = installed.chain(built_in).collect(); + } + // A decal shows the text in the tool's base color; an alpha must stay white. + let color = app.session.tool.values.get(&Channel::BaseColor).copied().unwrap_or([1.0; 3]); + let t = &mut app.ui.text; + ui.add(egui::TextEdit::multiline(&mut t.text).desired_rows(2).desired_width(f32::INFINITY).hint_text(tr("Text"))); + let shown = if t.font.is_empty() { tr("Default").to_string() } else { t.font.clone() }; + combo(ui, tr("Font"), shown, |ui| { + if ui.selectable_label(t.font.is_empty(), tr("Default")).clicked() { + (t.font, t.style) = (String::new(), String::new()); + } + for (family, _) in &t.fonts { + if ui.selectable_label(t.font == *family, family).clicked() { + (t.font, t.style) = (family.clone(), String::new()); + } + } + }); + let styles = t.fonts.iter().find(|(f, _)| *f == t.font).map(|(_, s)| s.clone()).unwrap_or_default(); + if styles.len() > 1 { + let shown = if t.style.is_empty() { tr("Default").to_string() } else { t.style.clone() }; + combo(ui, tr("Style"), shown, |ui| { + for s in styles { + ui.selectable_value(&mut t.style, s.clone(), s); + } + }); + } + let mut params = json!({"text": t.text, "font": (!t.font.is_empty()).then_some(&t.font), "style": (!t.style.is_empty()).then_some(&t.style)}); + let ready = !t.text.trim().is_empty(); + ui.horizontal_wrapped(|ui| { + let alpha = ui.add_enabled(ready, egui::Button::new(tr("Use as brush alpha"))).clicked(); + let decal = ui.add_enabled(ready, egui::Button::new(tr("Place as decal"))).clicked(); + if decal { + params["color"] = json!(color); + } + if (alpha || decal) + && let Some(name) = app.run("resource.text", params).and_then(|r| r["name"].as_str().map(str::to_string)) + { + match alpha { + true => app.run("tool.brush", json!({"alpha": {"image": name}})), + false => app.run("layer.add.decal", json!({"image": name})), + }; + } + }); +} + +/// Tooltip of the material channel chips. +pub(crate) const SOLO_HINT: &str = "Click: turn this channel on or off. Alt+click: this channel only"; + fn material_section(app: &mut TextureCraftApp, ui: &mut Ui) { let tk = Tokens::get(ui.ctx()); ui.label(caption(tr("Material"))); @@ -1149,8 +1327,9 @@ fn material_section(app: &mut TextureCraftApp, ui: &mut Ui) { ui.horizontal_wrapped(|ui| { for c in &chans { let on = app.session.tool.enabled.contains(c); - if chip(ui, tr(c.short()), on).clicked() { - app.run("tool.material", json!({"channel": c.id(), "enabled": !on})); + if chip(ui, tr(c.short()), on).on_hover_text(tr(SOLO_HINT)).clicked() { + let solo = ui.input(|i| i.modifiers.alt); + app.run("tool.material", json!({"channel": c.id(), "enabled": solo || !on, "solo": solo})); } } }); @@ -1370,8 +1549,9 @@ fn fill_editor(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Value ui.horizontal_wrapped(|ui| { for c in &chans { let enabled = on.contains(c); - if chip(ui, tr(c.short()), enabled).clicked() { - app.run("layer.fill.set", with(base, json!({"channel": c.id(), "enabled": !enabled}))); + if chip(ui, tr(c.short()), enabled).on_hover_text(tr(SOLO_HINT)).clicked() { + let solo = ui.input(|i| i.modifiers.alt); + app.run("layer.fill.set", with(base, json!({"channel": c.id(), "enabled": solo || !enabled, "solo": solo}))); } } }); @@ -1410,7 +1590,7 @@ fn projection_editor(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: Projection::Cylindrical { scale, .. } => (*scale, "cylindrical"), Projection::Decal(_) => return, }; - if slider(ui, tr("Scale / tiling"), &mut scale, 0.01..=20.0, 2).drag_stopped() { + if slider_edit(ui, tr("Scale / tiling"), &mut scale, 0.01..=20.0, 2) { app.run("layer.fill.projection", with(base, json!({"projection": proj_id, "scale": scale}))); } } @@ -1437,7 +1617,7 @@ fn decal_editor(app: &mut TextureCraftApp, ui: &mut Ui, d: &Decal, layer: LayerI ]; let mut done = false; for ((label, range), x) in rows.into_iter().zip(v.iter_mut()) { - done |= slider(ui, label, x, range, 3).drag_stopped(); + done |= slider_edit(ui, label, x, range, 3); } if done { app.run("layer.decal.set", json!({"layer": layer.0, "size": [v[0], v[1]], "rotation": v[2], "offset": [v[3], v[4]], "depth": v[5]})); @@ -1514,11 +1694,11 @@ fn fill_channel(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Valu ); let mut s = pattern.scale; let mut con = pattern.contrast; - let r1 = slider(ui, tr("Pattern scale"), &mut s, 0.1..=100.0, 1); - let r2 = slider(ui, tr("Contrast"), &mut con, 0.0..=8.0, 2); + let r1 = slider_edit(ui, tr("Pattern scale"), &mut s, 0.1..=100.0, 1); + let r2 = slider_edit(ui, tr("Contrast"), &mut con, 0.0..=8.0, 2); let mut seed = pattern.seed as f32; - let r3 = slider(ui, tr("Seed"), &mut seed, 0.0..=999.0, 0); - if r1.drag_stopped() || r2.drag_stopped() || r3.drag_stopped() { + let r3 = slider_edit(ui, tr("Seed"), &mut seed, 0.0..=999.0, 0); + if r1 || r2 || r3 { app.run( "layer.fill.set", set(json!({"procedural": pattern.kind.label(), "scale": s, "contrast": con, "seed": seed as u64, "low": low, "high": high})), @@ -1567,7 +1747,7 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: }); }); let mut op = e.opacity; - if slider(ui, tr("Opacity"), &mut op, 0.0..=1.0, 2).drag_stopped() { + if slider_edit(ui, tr("Opacity"), &mut op, 0.0..=1.0, 2) { app.run("effect.set", json!({"effect": id, "opacity": op})); } ui.separator(); @@ -1584,13 +1764,13 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: } }); let (mut level, mut soft, mut noise, mut ns) = (g.level, g.softness, g.noise_amount, g.noise_scale); - let r1 = slider(ui, tr("Level"), &mut level, 0.0..=1.0, 2); - let r2 = slider(ui, tr("Softness"), &mut soft, 0.0..=1.0, 2); - let r3 = slider(ui, tr("Noise amount"), &mut noise, 0.0..=2.0, 2); - let r4 = slider(ui, tr("Noise scale"), &mut ns, 0.1..=64.0, 1); + let r1 = slider_edit(ui, tr("Level"), &mut level, 0.0..=1.0, 2); + let r2 = slider_edit(ui, tr("Softness"), &mut soft, 0.0..=1.0, 2); + let r3 = slider_edit(ui, tr("Noise amount"), &mut noise, 0.0..=2.0, 2); + let r4 = slider_edit(ui, tr("Noise scale"), &mut ns, 0.1..=64.0, 1); let mut inv = g.invert; let r5 = ui.checkbox(&mut inv, tr("Invert")); - if r1.drag_stopped() || r2.drag_stopped() || r3.drag_stopped() || r4.drag_stopped() || r5.changed() { + if r1 || r2 || r3 || r4 || r5.changed() { app.run("effect.set", json!({"effect": id, "level": level, "softness": soft, "noise": noise, "noiseScale": ns, "invert": inv})); } if !app.session.doc.baked.contains_key(&app.session.ts()) { @@ -1601,12 +1781,13 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: } EffectKind::Levels(l) => { ui.label(caption(tr("Levels"))); + levels_histogram(app, ui, layer, eid, (l.in_low, l.in_high)); let mut v = [l.in_low, l.in_high, l.gamma, l.out_low, l.out_high]; let labels = [tr("Input low"), tr("Input high"), tr("Gamma"), tr("Output low"), tr("Output high")]; let mut done = false; for (i, label) in labels.iter().enumerate() { let range = if i == 2 { 0.1..=5.0 } else { 0.0..=1.0 }; - done |= slider(ui, label, &mut v[i], range, 2).drag_stopped(); + done |= slider_edit(ui, label, &mut v[i], range, 2); } if done { app.run("effect.set", json!({"effect": id, "inLow": v[0], "inHigh": v[1], "gamma": v[2], "outLow": v[3], "outHigh": v[4]})); @@ -1634,7 +1815,7 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: match source { Source::Uniform(v) => { let mut x = v[0]; - if slider(ui, tr("Value"), &mut x, 0.0..=1.0, 2).drag_stopped() { + if slider_edit(ui, tr("Value"), &mut x, 0.0..=1.0, 2) { app.run("effect.set", json!({"effect": id, "value": x})); } } @@ -1683,6 +1864,38 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: } } +/// The histogram of what levels effect `eid` of `layer` remaps (its mask, or a content channel +/// picked here), with the input range marked. Recomputed after a document change once no +/// pointer button is held, so dragging a slider keeps the last one. +fn levels_histogram(app: &TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: LayerId, range: (f32, f32)) { + let mut channel = layer.channels.keys().next().copied().unwrap_or(Channel::BaseColor); + if layer.content_effects.iter().any(|e| e.id == eid) { + let pick = egui::Id::unique(("levels_channel", eid.0)); + let chans: Vec = layer.channels.keys().copied().filter(|c| c.kind() != texturecraft_engine::core::ChannelKind::NormalMap).collect(); + channel = ui.data(|d| d.get_temp(pick)).filter(|c| chans.contains(c)).or(chans.first().copied()).unwrap_or(channel); + combo(ui, tr("Channel"), tr(channel.label()), |ui| { + for c in chans { + if ui.selectable_label(c == channel, tr(c.label())).clicked() { + ui.data_mut(|d| d.insert_temp(pick, c)); + } + } + }); + } + let key = egui::Id::unique(("levels_histogram", eid.0, channel)); + let rev = app.session.revision; + let counts = match ui.data(|d| d.get_temp::<(u64, std::sync::Arc>)>(key)) { + Some((r, h)) if r == rev || ui.input(|i| i.pointer.any_down()) => Some(h), + _ => app.session.effect_histogram(eid, channel, 64).map(|h| { + let h = std::sync::Arc::new(h); + ui.data_mut(|d| d.insert_temp(key, (rev, h.clone()))); + h + }), + }; + if let Some(counts) = counts { + histogram(ui, &counts, range); + } +} + /// The parameters of filter effect `id`. fn filter_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, f: &Filter) { let tk = Tokens::get(ui.ctx()); @@ -1694,7 +1907,7 @@ fn filter_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, f: &Filter ui.label(caption(tr(f.label()))); if let Filter::Hsl { hue, .. } = f { let mut h = hue * 360.0; - if slider(ui, tr("Hue shift (degrees)"), &mut h, -180.0..=180.0, 0).drag_stopped() { + if slider_edit(ui, tr("Hue shift (degrees)"), &mut h, -180.0..=180.0, 0) { set(app, "hue", json!(h / 360.0)); } } @@ -1706,7 +1919,7 @@ fn filter_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, f: &Filter } else { 2 }; - if slider(ui, tr(label), &mut v, lo..=hi, decimals).drag_stopped() { + if slider_edit(ui, tr(label), &mut v, lo..=hi, decimals) { set(app, key, json!(v)); } } @@ -1718,13 +1931,25 @@ fn filter_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, f: &Filter let mut v = *rgb; let mut done = false; for (x, name) in v.iter_mut().zip([tr("Cyan / red"), tr("Magenta / green"), tr("Yellow / blue")]) { - done |= slider(ui, name, x, -1.0..=1.0, 2).drag_stopped(); + done |= slider_edit(ui, name, x, -1.0..=1.0, 2); } if done { set(app, key, json!(v)); } } } + Filter::ReplaceColor { from, to, .. } => { + for (key, label, rgb) in [("from", tr("Color to replace"), from), ("to", tr("Replacement color"), to)] { + let mut v = *rgb; + ui.horizontal(|ui| { + if color_swatch(ui, &format!("replace_{key}_{id}"), &mut v, 36.0) { + set(app, key, json!(v)); + } + ui.label(label); + }); + } + ui.label(RichText::new(tr("Colors near the first shift towards the second, keeping their shading.")).size(10.5).color(tk.text_dim)); + } Filter::GradientMap { colors } => { let mut c = colors.clone(); let mut changed = false; diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index 37e109fd..ed23f88a 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -280,10 +280,10 @@ fn area_id() -> Id { } /// The dock look: every panel group is a card on the window's frame colour, its tab strip -/// without hard lines, the shown tab a pill, uppercase captions. +/// without hard lines, the shown tab a pill. fn style(ui: &Ui, t: &Tokens) -> DockStyle { let mut s = DockStyle::from_ui(ui); - s.gap = 6.0; + s.gap = f32::from(crate::theme::GUTTER); // Smallest panel extent a divider drag leaves. s.min_pane = 60.0; s.background = t.panel; @@ -295,7 +295,7 @@ fn style(ui: &Ui, t: &Tokens) -> DockStyle { s.accent = t.accent; s.floating_background = t.panel; s.floating_stroke = egui::Stroke::new(1.0, t.button_border); - s.font = egui::FontId::proportional(10.5); + s.font = egui::FontId::proportional(12.5); s.min_tab_width = 54.0; s.tab_height = 30.0; // Panels arrange in a split tree around the viewport; floating title bars only move windows. @@ -375,7 +375,7 @@ impl DockContent for Panels<'_> { } fn label(&mut self, _ui: &Ui, _panel: &Panel, logical: &str, font: &egui::FontId, color: egui::Color32) -> egui::WidgetText { - RichText::new(logical.to_uppercase()).font(font.clone()).strong().color(color).into() + RichText::new(logical).font(font.clone()).color(color).into() } fn permissions(&self, panel: &Panel) -> Permissions { diff --git a/crates/ui-egui/src/fonts.rs b/crates/ui-egui/src/fonts.rs index 514f4554..b31b423a 100644 --- a/crates/ui-egui/src/fonts.rs +++ b/crates/ui-egui/src/fonts.rs @@ -1,15 +1,17 @@ -//! CJK fallback fonts for the UI. egui's default fonts have no Japanese, Chinese or Korean -//! glyphs, so translated UIs (and CJK layer or file names) need more fonts. They come from: +//! CJK and Arabic fallback fonts for the UI. egui's default fonts have no Japanese, Chinese, +//! Korean or Arabic glyphs, so translated UIs (and such layer or file names) need more fonts. +//! They come from: //! //! 1. craft-fonts, embedded at build time when `CRAFT_FONTS_DIR` points at a checkout (optional; //! see `build.rs` and storytold/craft-fonts' `docs/integration.md`); -//! 2. on desktop, the operating system's CJK fonts (Windows, macOS, Linux and BSD paths). +//! 2. on desktop, the operating system's fonts (Windows, macOS, Linux and BSD paths). //! -//! Fonts load lazily: one script when the UI language needs it, all three while the language -//! picker shows every language's own name. They are appended after the app's fonts, so Latin -//! text and row heights keep the default font; the current language's script goes first, so -//! shared Han characters take that language's glyph forms. In the browser only craft-fonts -//! can supply them (without it, a CJK language shows its English name in the picker). +//! Fonts load lazily: one script when the UI language needs it, all of them while the language +//! picker shows every language's own name. They are appended after the app's fonts +//! (`theme::font_definitions`), so Latin text and row heights keep the interface font; the current language's script goes first, so +//! shared Han characters take that language's glyph forms. egui shapes Arabic and orders +//! right-to-left runs itself. In the browser only craft-fonts can supply them (without it, the +//! language shows its English name in the picker). use std::sync::Arc; @@ -35,10 +37,11 @@ pub enum Script { Japanese, Chinese, Korean, + Arabic, } impl Script { - pub const ALL: [Script; 3] = [Script::Japanese, Script::Chinese, Script::Korean]; + pub const ALL: [Script; 4] = [Script::Japanese, Script::Chinese, Script::Korean, Script::Arabic]; /// The script a UI language needs beyond Latin. pub fn of_language(code: &str) -> Option