diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 23727788..6a6f238d 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -27,7 +27,7 @@ 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/release.yml@main with: - dry-run: ${{ github.event_name == 'schedule' }} + nightly: ${{ github.event_name == 'schedule' }} app-name: texturecraft app-title: "TextureCraft" craft-fonts-ref: aced4137c022f1f587624d48e81ec77e1914a9cc @@ -49,3 +49,4 @@ jobs: AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }} AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }} LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }} + ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }} diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 500328aa..a136498a 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -23,6 +23,7 @@ licensed and keep their license file next to them. | `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-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 | +| `assets/hdr/studio_small_09_512.hdr` | Studio Small 09: a small photo studio with octaboxes on a white infinity cyc, equirect HDR reduced to 512×256 (2×2 box filter, Radiance RLE); lights the Properties panel's material orbs | Sergej Majboroda (Poly Haven) | [Poly Haven release](https://polyhaven.com/a/studio_small_09), [1K Radiance HDR](https://dl.polyhaven.org/file/ph-assets/HDRIs/hdr/1k/studio_small_09_1k.hdr) (MD5 `d5d7eb9d26d341d6aa4d11c1a54fd97c`) | [CC0 1.0 Universal](https://creativecommons.org/publicdomain/zero/1.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)) | | `crates/formats/src/mesh_import/usd/fixtures/crafted-references.usdc` | Synthetic USDC class/reference/time-sample acceptance fixture | ArtCraft Team and craft-libs contributors | [Pinned generator and provenance](crates/formats/src/mesh_import/usd/fixtures/README.md) | MIT (`crates/formats/src/mesh_import/usd/fixtures/LICENSE-MIT`) | @@ -40,6 +41,17 @@ These come from Rust crate dependencies (not files in this repository) and keep 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). +## Native eyedropper dependencies + +| Crate | Use | Upstream | License | +|---|---|---|---| +| `raw-window-handle` | Identify native application windows | https://github.com/rust-windowing/raw-window-handle | MIT OR Apache-2.0 OR Zlib | +| `winsafe` | Windows pointer and event handling | https://github.com/rodrigocfd/winsafe | MIT | +| `xcap` | Windows screen pixel capture | https://github.com/nashaofu/xcap | Apache-2.0 | +| `widestring` | Windows string handling through `xcap` | https://github.com/VoidStarKat/widestring-rs | MIT OR Apache-2.0 | +| `x11rb` | X11 pointer and pixel capture | https://github.com/psychon/x11rb | MIT OR Apache-2.0 | +| `zbus` | Wayland desktop color-picker portal | https://github.com/z-galaxy/zbus | MIT | + ## Procedural content (no asset files) Built-in environments (`crates/render/src/ibl.rs`), smart materials and procedurals diff --git a/Cargo.lock b/Cargo.lock index a06f2619..84a1a752 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -80,7 +80,7 @@ dependencies = [ "futures-lite", "futures-util", "serde", - "zbus", + "zbus 5.19.0", ] [[package]] @@ -132,6 +132,15 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + [[package]] name = "alloc-no-stdlib" version = "3.0.0" @@ -193,6 +202,22 @@ dependencies = [ "libc", ] +[[package]] +name = "annotate-snippets" +version = "0.11.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "710e8eae58854cdc1790fcb56cca04d712a17be849eeb81da2a724bf4bae2bc4" +dependencies = [ + "anstyle", + "unicode-width", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + [[package]] name = "arboard" version = "3.6.1" @@ -235,6 +260,22 @@ dependencies = [ "libloading", ] +[[package]] +name = "ashpd" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ba377f1fb1e3972907220f1f8e7c0a45164580905c981d872c1fb90d921cbcc" +dependencies = [ + "bitflags 2.13.2", + "futures-channel", + "futures-util", + "getrandom 0.4.3", + "pipewire", + "serde", + "serde_repr", + "zbus 6.3.0", +] + [[package]] name = "async-broadcast" version = "0.7.2" @@ -391,7 +432,7 @@ dependencies = [ "enumflags2", "serde", "static_assertions", - "zbus", + "zbus 5.19.0", "zbus-lockstep", "zbus-lockstep-macros", "zbus_names", @@ -406,7 +447,7 @@ checksum = "2230e48787ed3eb4088996eab66a32ca20c0b67bbd4fd6cdfe79f04f1f04c9fc" dependencies = [ "atspi-common", "serde", - "zbus", + "zbus 5.19.0", ] [[package]] @@ -433,6 +474,25 @@ version = "0.23.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" +[[package]] +name = "bindgen" +version = "0.72.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895" +dependencies = [ + "annotate-snippets", + "bitflags 2.13.2", + "cexpr", + "clang-sys", + "itertools 0.13.0", + "proc-macro2", + "quote", + "regex", + "rustc-hash 2.1.3", + "shlex 1.3.0", + "syn 2.0.119", +] + [[package]] name = "bit-set" version = "0.10.0" @@ -628,7 +688,26 @@ dependencies = [ "find-msvc-tools", "jobserver", "libc", - "shlex", + "shlex 2.0.1", +] + +[[package]] +name = "cexpr" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766" +dependencies = [ + "nom 7.1.3", +] + +[[package]] +name = "cfg-expr" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edd44d82755fb9210fb10d9daf8dd7e522da0efe1d5f263cffc5db07725663ff" +dependencies = [ + "smallvec", + "target-lexicon", ] [[package]] @@ -652,6 +731,17 @@ dependencies = [ "libc", ] +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "rand_core", +] + [[package]] name = "chrono" version = "0.4.45" @@ -666,6 +756,17 @@ dependencies = [ "windows-link", ] +[[package]] +name = "clang-sys" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a" +dependencies = [ + "glob", + "libc", + "libloading", +] + [[package]] name = "clipboard-win" version = "5.4.1" @@ -738,6 +839,12 @@ dependencies = [ "rustversion", ] +[[package]] +name = "cookie-factory" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9885fa71e26b8ab7855e2ec7cae6e9b380edff76cd052e07c683a0319d51b3a2" + [[package]] name = "core-foundation" version = "0.9.4" @@ -803,6 +910,15 @@ dependencies = [ "libc", ] +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + [[package]] name = "craft-cms" version = "0.1.0" @@ -1307,6 +1423,61 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76" +[[package]] +name = "drm" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80bc8c5c6c2941f70a55c15f8d9f00f9710ebda3ffda98075f996a0e6c92756f" +dependencies = [ + "bitflags 2.13.2", + "bytemuck", + "drm-ffi", + "drm-fourcc", + "libc", + "rustix 0.38.44", +] + +[[package]] +name = "drm" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a41816e58f47f49acfd956651055ddcf137c4882c2098c30c448817af21183a" +dependencies = [ + "bitflags 2.13.2", + "bytemuck", + "bytemuck_derive", + "drm-ffi", + "drm-fourcc", + "libc", + "rustix 1.1.5", +] + +[[package]] +name = "drm-ffi" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51a91c9b32ac4e8105dec255e849e0d66e27d7c34d184364fb93e469db08f690" +dependencies = [ + "drm-sys", + "rustix 1.1.5", +] + +[[package]] +name = "drm-fourcc" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0aafbcdb8afc29c1a7ee5fbe53b5d62f4565b35a042a662ca9fecd0b54dae6f4" + +[[package]] +name = "drm-sys" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ecc8e1361066d91f5ffccff060a3c3be9c3ecde15be2959c1937595f7a82a9f8" +dependencies = [ + "libc", + "linux-raw-sys 0.9.4", +] + [[package]] name = "dunce" version = "1.0.5" @@ -1376,7 +1547,7 @@ dependencies = [ "bitflags 2.13.2", "emath", "epaint", - "itertools", + "itertools 0.15.0", "log", "nohash-hasher", "profiling", @@ -1753,6 +1924,15 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + [[package]] name = "fs-set-times" version = "0.20.3" @@ -1865,6 +2045,30 @@ dependencies = [ "slab", ] +[[package]] +name = "gbm" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce852e998d3ca5e4a97014fb31c940dc5ef344ec7d364984525fd11e8a547e6a" +dependencies = [ + "bitflags 2.13.2", + "drm 0.14.1", + "drm-fourcc", + "gbm-sys", + "libc", + "wayland-backend", + "wayland-server", +] + +[[package]] +name = "gbm-sys" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c13a5f2acc785d8fb6bf6b7ab6bfb0ef5dad4f4d97e8e70bb8e470722312f76f" +dependencies = [ + "libc", +] + [[package]] name = "generic-array" version = "0.14.7" @@ -1918,6 +2122,7 @@ dependencies = [ "js-sys", "libc", "r-efi 6.0.0", + "rand_core", "wasm-bindgen", ] @@ -1931,6 +2136,15 @@ dependencies = [ "weezl", ] +[[package]] +name = "gl" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a94edab108827d67608095e269cf862e60d920f144a5026d3dbcfd8b877fb404" +dependencies = [ + "gl_generator", +] + [[package]] name = "gl_generator" version = "0.14.0" @@ -1974,6 +2188,12 @@ dependencies = [ "vello_common", ] +[[package]] +name = "glob" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" + [[package]] name = "glow" version = "0.17.0" @@ -2176,6 +2396,12 @@ dependencies = [ "fearless_simd", ] +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + [[package]] name = "hermit-abi" version = "0.5.3" @@ -2411,6 +2637,27 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + [[package]] name = "image" version = "0.25.10" @@ -2488,6 +2735,15 @@ version = "2.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" +[[package]] +name = "itertools" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" +dependencies = [ + "either", +] + [[package]] name = "itertools" version = "0.15.0" @@ -2683,6 +2939,54 @@ dependencies = [ "redox_syscall 0.9.4", ] +[[package]] +name = "libspa" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "882f7427e7989dcc9d388b7f05c4630390a1d7696f9ffa469cd4a7a48f0b4c40" +dependencies = [ + "bitflags 2.13.2", + "cc", + "cookie-factory", + "libc", + "libspa-sys", + "nom 8.0.0", + "rustix 1.1.5", + "system-deps", +] + +[[package]] +name = "libspa-sys" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b6e17bdaf63ed0d5e4144022624032b41fd9733112e8c74ac26fc9bf1291924" +dependencies = [ + "bindgen", + "cc", + "system-deps", +] + +[[package]] +name = "libwayshot-xcap" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea8a46e4d016ef464e386e4970f5415fe0939c2d63abe0c2f539c05ef88c5fe5" +dependencies = [ + "drm 0.15.0", + "gbm", + "gl", + "image", + "khronos-egl", + "memmap2", + "rustix 1.1.5", + "thiserror 2.0.21", + "tracing", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-protocols-wlr", +] + [[package]] name = "linebender_resource_handle" version = "0.1.1" @@ -2695,6 +2999,12 @@ version = "0.4.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" +[[package]] +name = "linux-raw-sys" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd945864f07fe9f5371a27ad7b52a172b4b499999f1d97574c9fa68373937e12" + [[package]] name = "linux-raw-sys" version = "0.12.1" @@ -2786,6 +3096,12 @@ dependencies = [ "glam 0.15.2", ] +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + [[package]] name = "miniz_oxide" version = "0.8.9" @@ -2943,6 +3259,16 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451" +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + [[package]] name = "nom" version = "8.0.0" @@ -3064,6 +3390,18 @@ dependencies = [ "objc2-foundation 0.3.2", ] +[[package]] +name = "objc2-av-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "478ae33fcac9df0a18db8302387c666b8ef08a3e2d62b510ca4fc278a384b6c0" +dependencies = [ + "objc2 0.6.5", + "objc2-core-graphics", + "objc2-core-media", + "objc2-foundation 0.3.2", +] + [[package]] name = "objc2-cloud-kit" version = "0.2.2" @@ -3088,6 +3426,28 @@ dependencies = [ "objc2-foundation 0.2.2", ] +[[package]] +name = "objc2-core-audio" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1eebcea8b0dbff5f7c8504f3107c68fc061a3eb44932051c8cf8a68d969c3b2" +dependencies = [ + "dispatch2", + "objc2 0.6.5", + "objc2-core-audio-types", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-core-audio-types" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a89f2ec274a0cf4a32642b2991e8b351a404d290da87bb6a9a9d8632490bd1c" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", +] + [[package]] name = "objc2-core-data" version = "0.2.2" @@ -3119,6 +3479,7 @@ checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807" dependencies = [ "bitflags 2.13.2", "dispatch2", + "libc", "objc2 0.6.5", "objc2-core-foundation", "objc2-io-surface", @@ -3148,6 +3509,34 @@ dependencies = [ "objc2-foundation 0.2.2", ] +[[package]] +name = "objc2-core-media" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05ec576860167a15dd9fce7fbee7512beb4e31f532159d3482d1f9c6caedf31d" +dependencies = [ + "bitflags 2.13.2", + "dispatch2", + "objc2 0.6.5", + "objc2-core-audio", + "objc2-core-audio-types", + "objc2-core-foundation", + "objc2-core-video", +] + +[[package]] +name = "objc2-core-video" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d425caf1df73233f29fd8a5c3e5edbc30d2d4307870f802d18f00d83dc5141a6" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-io-surface", +] + [[package]] name = "objc2-encode" version = "4.1.0" @@ -3532,6 +3921,31 @@ dependencies = [ "futures-io", ] +[[package]] +name = "pipewire" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bde71084c4e25959d68f1ea54daa75e5ecdb338e5caf0b5510143b79baa32d5c" +dependencies = [ + "bitflags 2.13.2", + "libc", + "libspa", + "libspa-sys", + "pipewire-sys", + "rustix 1.1.5", +] + +[[package]] +name = "pipewire-sys" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ce653f53e63e5b93853218092ee9a8906a5d082c92f3f1db26316955dd63ce0" +dependencies = [ + "bindgen", + "libspa-sys", + "system-deps", +] + [[package]] name = "pkg-config" version = "0.3.34" @@ -3777,6 +4191,23 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "rand" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + [[package]] name = "range-alloc" version = "0.1.5" @@ -3907,6 +4338,35 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "regex" +version = "1.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" + [[package]] name = "renderdoc-sys" version = "1.1.0" @@ -4323,10 +4783,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" dependencies = [ "cfg-if", - "cpufeatures", + "cpufeatures 0.2.17", "digest", ] +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + [[package]] name = "shlex" version = "2.0.1" @@ -4563,6 +5029,19 @@ dependencies = [ "windows", ] +[[package]] +name = "system-deps" +version = "7.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "396a35feb67335377e0251fcbc1092fc85c484bd4e3a7a54319399da127796e7" +dependencies = [ + "cfg-expr", + "heck", + "pkg-config", + "toml", + "version-compare", +] + [[package]] name = "tar" version = "0.4.46" @@ -4573,6 +5052,12 @@ dependencies = [ "libc", ] +[[package]] +name = "target-lexicon" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca" + [[package]] name = "tempfile" version = "3.27.0" @@ -4604,6 +5089,7 @@ dependencies = [ "craft-update", "eframe", "egui", + "egui_kittest", "image", "log", "rfd", @@ -4729,7 +5215,6 @@ dependencies = [ "gltf", "half", "image", - "lz4_flex", "png", "quick-xml 0.41.0", "rayon", @@ -4816,6 +5301,7 @@ dependencies = [ "js-sys", "log", "pollster 0.4.0", + "raw-window-handle", "rayon", "rfd", "serde", @@ -4828,6 +5314,10 @@ dependencies = [ "wasm-bindgen", "wasm-bindgen-futures", "web-sys", + "winsafe", + "x11rb", + "xcap", + "zbus 5.19.0", "zip", ] @@ -5082,7 +5572,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8765b90061cba6c22b5831f675da109ae5561588290f9fa2317adab2714d5a6" dependencies = [ "memchr", - "nom", + "nom 8.0.0", "petgraph", ] @@ -5195,6 +5685,18 @@ dependencies = [ "log", ] +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + [[package]] name = "urlencoding" version = "2.1.3" @@ -5280,6 +5782,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "version-compare" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03c2856837ef78f57382f06b2b8563a2f512f7185d732608fd9176cb3b8edf0e" + [[package]] name = "version_check" version = "0.9.5" @@ -5464,6 +5972,19 @@ dependencies = [ "quote", ] +[[package]] +name = "wayland-server" +version = "0.31.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0dde9c29be0f723a573977de51ee455bf3dfa03652730a74f9dd3b337e374d75" +dependencies = [ + "bitflags 2.13.2", + "downcast-rs", + "rustix 1.1.5", + "wayland-backend", + "wayland-scanner", +] + [[package]] name = "wayland-sys" version = "0.31.11" @@ -5471,7 +5992,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d8eab23fefc9e41f8e841df4a9c707e8a8c4ed26e944ef69297184de2785e3be" dependencies = [ "dlib", + "libc", "log", + "memoffset", "once_cell", "pkg-config", ] @@ -5694,6 +6217,12 @@ dependencies = [ "web-sys", ] +[[package]] +name = "widestring" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72069c3113ab32ab29e5584db3c6ec55d416895e60715417b5b883a357c3e471" + [[package]] name = "winapi" version = "0.3.9" @@ -6188,6 +6717,49 @@ version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd" +[[package]] +name = "xcap" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e833d39f662982a09608f2550fd4036725f98d78738e40fa7206a26258b06384" +dependencies = [ + "ashpd", + "dispatch2", + "image", + "libwayshot-xcap", + "log", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-av-foundation", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-core-media", + "objc2-core-video", + "objc2-foundation 0.3.2", + "percent-encoding", + "pipewire", + "pollster 1.0.1", + "rand", + "scopeguard", + "serde", + "thiserror 2.0.21", + "url", + "widestring", + "windows", + "xcb", +] + +[[package]] +name = "xcb" +version = "1.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6c2ad15e0e922856ee89afe862b8992334bbe7953adad56cd1199358cb30566" +dependencies = [ + "bitflags 2.13.2", + "libc", + "quick-xml 0.41.0", +] + [[package]] name = "xcursor" version = "0.3.11" @@ -6279,11 +6851,38 @@ dependencies = [ "uuid", "windows-sys 0.61.2", "winnow", - "zbus_macros", + "zbus_macros 5.19.0", "zbus_names", "zvariant", ] +[[package]] +name = "zbus" +version = "6.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b4aae740b23927ceabed962431abab2cdefb9f7f885e5bbab062da09bf580e4" +dependencies = [ + "async-trait", + "bitflags 2.13.2", + "endi", + "futures-core", + "hex", + "libc", + "ordered-stream", + "rustix 1.1.5", + "serde", + "serde_repr", + "socket2", + "uds_windows", + "uuid", + "windows-sys 0.61.2", + "winnow", + "zbus_macros 6.3.0", + "zbus_utils", + "zcheapstr", + "zruntime", +] + [[package]] name = "zbus-lockstep" version = "0.5.2" @@ -6323,6 +6922,18 @@ dependencies = [ "zvariant_utils", ] +[[package]] +name = "zbus_macros" +version = "6.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37c9dd4beaf145c16fcb2902862f50da86e54aed13dd368ddf64a1d17e6b8529" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "zbus_utils", +] + [[package]] name = "zbus_names" version = "4.3.4" @@ -6334,6 +6945,19 @@ dependencies = [ "zvariant", ] +[[package]] +name = "zbus_utils" +version = "6.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af55e52da295311b368c45bcae221f020e28e97a2420360170ce389218e76ec7" +dependencies = [ + "proc-macro2", + "quote", + "serde", + "syn 3.0.9", + "winnow", +] + [[package]] name = "zbus_xml" version = "5.2.1" @@ -6497,6 +7121,19 @@ dependencies = [ "simd-adler32", ] +[[package]] +name = "zruntime" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6a55d4f521760475a30f7b96779508fe8c40dc834478709454dd1d5f0ebc72" +dependencies = [ + "futures-core", + "futures-io", + "rustix 1.1.5", + "socket2", + "windows-sys 0.61.2", +] + [[package]] name = "zune-core" version = "0.5.3" diff --git a/Cargo.toml b/Cargo.toml index e4f86a12..de6fc98d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,8 +8,6 @@ default-members = ["crates/core", "crates/texel", "crates/geom", "crates/compose version = "0.6.1" edition = "2024" license = "MIT OR Apache-2.0" -rust-version = "1.95" -repository = "https://github.com/storytold/texturecraft" [workspace.dependencies] craft-usd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3" } @@ -53,10 +51,8 @@ rfd = "0.17" zip = { version = "9", default-features = false, features = ["deflate"] } gltf = { version = "1.4", default-features = false, features = ["import", "utils", "names", "KHR_materials_emissive_strength"] } flate2 = "1" -lz4_flex = { version = "0.11", default-features = false, features = ["safe-decode", "safe-encode"] } quick-xml = "0.41" mikktspace = { version = "0.3", default-features = false, features = ["glam"] } -proptest = "1" rmcp = { version = "3.5", default-features = false, features = ["server", "macros", "transport-io"] } tokio = { version = "1", features = ["rt-multi-thread", "macros", "io-std", "sync", "net", "io-util", "time"] } schemars = "1" diff --git a/NOTICE b/NOTICE index a6c9da4b..25d962ff 100644 --- a/NOTICE +++ b/NOTICE @@ -12,6 +12,18 @@ Third-party material This product bundles third-party material under its own licenses, listed below. The per-file list (author, source, license) is in ATTRIBUTION.md. +Studio Small 09 HDR environment (assets/hdr/studio_small_09_512.hdr), +by Sergej Majboroda (Poly Haven) — CC0-1.0. +Source: https://polyhaven.com/a/studio_small_09 (1K HDR, reduced to 512x256). + +Native eyedropper components: +- raw-window-handle — MIT OR Apache-2.0 OR Zlib. Copyright (c) 2019, 2020 Osspial. +- winsafe — MIT. Copyright (c) 2019-present, Rodrigo Cesar de Freitas Dias. +- xcap — Apache-2.0. +- widestring (through xcap on Windows) — MIT OR Apache-2.0. +- x11rb — MIT OR Apache-2.0. Copyright 2019 x11rb contributors. +- zbus — MIT. Copyright (c) 2024 Zeeshan Ali Khan and zbus contributors. + Phosphor Icons (compiled in through the egui-phosphor crate) — MIT. egui default fonts (compiled in through the epaint_default_fonts crate): Ubuntu-Light — Ubuntu Font Licence 1.0; Hack — MIT and Bitstream Vera License; Noto Emoji — SIL Open Font License 1.1; diff --git a/apps/texturecraft-cli/tests/cli.rs b/apps/texturecraft-cli/tests/cli.rs index 4cb6a5aa..ce209c3e 100644 --- a/apps/texturecraft-cli/tests/cli.rs +++ b/apps/texturecraft-cli/tests/cli.rs @@ -16,17 +16,6 @@ fn cli_binary_path(runner_path: Option) -> OsString { runner_path.unwrap_or_else(|| env!("CARGO_BIN_EXE_texturecraft-cli").into()) } -#[test] -fn cli_binary_prefers_relocated_runner_path() { - let relocated = OsString::from("relocated archive/texturecraft-cli"); - assert_eq!(cli_binary_path(Some(relocated.clone())), relocated); -} - -#[test] -fn cli_binary_defaults_to_cargo_path() { - assert_eq!(cli_binary_path(None), OsString::from(env!("CARGO_BIN_EXE_texturecraft-cli"))); -} - fn cli(args: &[&str]) -> Output { Command::new(cli_binary()).args(args).output().unwrap() } diff --git a/apps/texturecraft-web/Cargo.toml b/apps/texturecraft-web/Cargo.toml index e5512768..bb5c79a6 100644 --- a/apps/texturecraft-web/Cargo.toml +++ b/apps/texturecraft-web/Cargo.toml @@ -13,12 +13,11 @@ workspace = true name = "texturecraft-web" path = "src/main.rs" -[dependencies] +[target.'cfg(target_arch = "wasm32")'.dependencies] texturecraft-engine = { workspace = true } texturecraft-ui-egui = { workspace = true } log = { workspace = true } -[target.'cfg(target_arch = "wasm32")'.dependencies] # `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback. eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "persistence"] } wasm-bindgen = "0.2" diff --git a/apps/texturecraft-web/src/main.rs b/apps/texturecraft-web/src/main.rs index cd4045c4..742cb5a8 100644 --- a/apps/texturecraft-web/src/main.rs +++ b/apps/texturecraft-web/src/main.rs @@ -1,6 +1,6 @@ //! TextureCraft in the browser. //! -//! Runs the same [`texturecraft_ui_egui::TextureCraftApp`] as the desktop app through eframe's web +//! Runs the same `TextureCraftApp` as the desktop app through eframe's web //! runner (wgpu: WebGPU where available, WebGL2 otherwise). Build with `trunk build --release` //! from this directory (`packaging/web/package.sh` zips the result). //! diff --git a/apps/texturecraft/Cargo.toml b/apps/texturecraft/Cargo.toml index e3fb936a..cab8493e 100644 --- a/apps/texturecraft/Cargo.toml +++ b/apps/texturecraft/Cargo.toml @@ -38,5 +38,9 @@ craft-update = { workspace = true } [target.'cfg(target_os = "macos")'.dependencies] craft-menu = { workspace = true } +[dev-dependencies] +# The pointer-hold test drives the windowed app's frames (src/main.rs) +egui_kittest = { version = "0.37", features = ["eframe"] } + [build-dependencies] winresource = "0.1" diff --git a/apps/texturecraft/src/control_server.rs b/apps/texturecraft/src/control_server.rs index b502fe55..cf0a6df4 100644 --- a/apps/texturecraft/src/control_server.rs +++ b/apps/texturecraft/src/control_server.rs @@ -134,7 +134,7 @@ fn serve(stream: TcpStream, token: &str, tx: &Sender, ctx: &egui #[cfg(test)] mod tests { - use std::io::BufRead; + use std::io::{BufRead, Read}; use super::*; @@ -196,33 +196,28 @@ mod tests { assert_eq!(call(&mut w, &mut r, r#"{"id":4,"method":"ping"}"#).unwrap()["id"], 4, "bad JSON keeps an authenticated connection"); } + fn assert_reply(reader: &mut BufReader, expected: Value) -> std::io::Result<()> { + let expected = format!("{expected}\n"); + let mut received = vec![0; expected.len()]; + reader.read_exact(&mut received)?; + assert_eq!(received, expected.as_bytes(), "unexpected control server reply"); + Ok(()) + } + #[test] - fn connections_are_limited_and_idle_ones_time_out() { + fn authenticated_connections_hold_server_slots() -> std::io::Result<()> { 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"); + let mut held = Vec::with_capacity(MAX_CONNECTIONS); + for _ in 0..MAX_CONNECTIONS { + let (mut writer, mut reader) = connect(addr); + writeln!(writer, "{right}")?; + // The reply confirms that this connection is holding a slot. + assert_reply(&mut reader, json!({"ok": true, "id": 1}))?; + held.push((writer, reader)); + } + + let (_writer, mut reader) = connect(addr); + assert_reply(&mut reader, json!({"id": null, "ok": false, "error": "too many connections"})) } } diff --git a/apps/texturecraft/src/main.rs b/apps/texturecraft/src/main.rs index ec60c58c..7787e1cf 100644 --- a/apps/texturecraft/src/main.rs +++ b/apps/texturecraft/src/main.rs @@ -164,12 +164,14 @@ impl eframe::App for Shell { 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. + fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) { + // Restore the frameless style after winit changes the window flags if let Some(guard) = self.window_frame.as_mut() { guard(); } + + // The app's own hook: a drag holding the pointer reads its moves from it + self.app.raw_input_hook(ctx, raw); } fn logic(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) { @@ -194,6 +196,13 @@ fn main() { if let Some(result) = craft_update::self_update::finish(&texturecraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::>()) { std::process::exit(i32::from(result.is_err())); } + + // Windows: the eyedropper's pointer keeper (screen_pick) is a copy of this program started with its own argument + #[cfg(windows)] + if std::env::args_os().nth(1).is_some_and(|arg| arg == texturecraft_ui_egui::screen_pick::KEEPER_ARG) { + std::process::exit(texturecraft_ui_egui::screen_pick::keep_pointer()); + } + let args = match parse_args() { Ok(Some(a)) => a, Ok(None) => return, @@ -321,19 +330,6 @@ mod tests { assert_eq!(args.gpu.as_deref(), Some("3080")); } - #[test] - fn only_a_run_without_a_control_port_checks_for_updates_at_start() { - assert!(checks_for_updates_at_start(None)); - assert!(!checks_for_updates_at_start(Some(9000))); - } - - #[test] - fn bundled_app_icon_decodes_to_rgba() { - let icon = icon().unwrap(); - assert!(icon.width > 0 && icon.height > 0); - assert_eq!(icon.rgba.len(), (icon.width * icon.height * 4) as usize); - } - #[test] fn rejects_missing_or_invalid_gpu_args() { assert!(parse_args_from(["--gpu".to_string()]).is_err()); @@ -388,4 +384,55 @@ mod tests { std::fs::remove_file(&ron_path).unwrap(); assert_eq!(saved_prefs(Some(&json_path), Some(&ron_path)), texturecraft_ui_egui::state::Prefs::default()); } + + /// How far the test's drag moves the mouse in one frame, in points + const DRAG_STEP: egui::Vec2 = egui::vec2(80.0, 0.0); + + /// Points within which a put-back lands on the press point (the system rounds it to whole pixels) + const PUT_BACK_REACH: f32 = 1.0; + + /// One frame of the window: the system's events go through the window's raw input hook, as eframe sends them; returns what the app asked of the window + fn window_frame(harness: &mut egui_kittest::Harness<'static, Shell>, events: Vec) -> Vec { + let ctx = harness.ctx.clone(); + let mut raw = harness.input_mut().clone(); + raw.events.extend(events); + eframe::App::raw_input_hook(harness.state_mut(), &ctx, &mut raw); + *harness.input_mut() = raw; + harness.step(); + harness.output().viewport_output.get(&egui::ViewportId::ROOT).map(|viewport| viewport.commands.clone()).unwrap_or_default() + } + + /// Holding the fill's preview square in the window holds the system's pointer: put back to the press point every frame, or locked where the system locks it + #[test] + fn the_window_holds_the_pointer_while_the_preview_square_is_held() { + let session = Session::new_project("Hold", texturecraft_engine::geom::primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 128).unwrap(); + let builder = egui_kittest::Harness::builder().with_size(egui::vec2(DEFAULT_SIZE[0], DEFAULT_SIZE[1])); + let mut harness = builder.build_eframe(|cc| Shell { + app: TextureCraftApp::new(cc, session), + window_frame: None, + #[cfg(target_os = "macos")] + movable: None, + }); + harness.run_steps(4); + let layer = harness.state_mut().app.run("layer.add.fill", serde_json::json!({})).unwrap()["layer"].clone(); + harness.state_mut().app.run("layer.fill.projection", serde_json::json!({"layer": layer, "projection": "triplanar"})).unwrap(); + harness.run_steps(2); + + let pad = egui_kittest::kittest::Queryable::get_by_label(&harness, "Move on model").rect().center(); + let press = egui::Event::PointerButton { pos: pad, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }; + let pressed = window_frame(&mut harness, vec![egui::Event::PointerMoved(pad), press]); + let locked = pressed.contains(&egui::ViewportCommand::CursorGrab(egui::CursorGrab::Locked)); + + // A locked pointer stays still and the system reports only its raw motion + let mut moves = vec![egui::Event::MouseMoved(DRAG_STEP)]; + if !locked { + moves.push(egui::Event::PointerMoved(pad + DRAG_STEP)); + } + let moved = window_frame(&mut harness, moves); + let put_back = moved.iter().any(|command| matches!(command, egui::ViewportCommand::CursorPosition(to) if to.distance(pad) <= PUT_BACK_REACH)); + + assert!(locked || put_back, "the window puts the pointer back where the press began, so it never leaves: {moved:?}"); + let seen = harness.ctx.input(|input| input.pointer.latest_pos()); + assert!(seen.is_some_and(|seen| seen.distance(pad + DRAG_STEP) <= PUT_BACK_REACH), "the app reads the whole move: {seen:?}"); + } } diff --git a/assets/hdr/studio_small_09_512.hdr b/assets/hdr/studio_small_09_512.hdr new file mode 100644 index 00000000..3a3f4f35 Binary files /dev/null and b/assets/hdr/studio_small_09_512.hdr differ diff --git a/crates/automation/src/render.rs b/crates/automation/src/render.rs index 8e809021..c12ce621 100644 --- a/crates/automation/src/render.rs +++ b/crates/automation/src/render.rs @@ -228,14 +228,6 @@ mod tests { out } - #[test] - fn the_unlit_switch_decides_whether_a_channel_view_is_lit() { - let mut s = texturecraft_engine::sample_session(128, 64).unwrap(); - assert!(!shade(&s).solo_lit, "channel views are flat by default"); - execute(&mut s, "display.set", &json!({"soloUnlit": false})).unwrap(); - assert!(shade(&s).solo_lit); - } - #[test] fn renders_with_an_imported_hdr_environment() { let mesh = texturecraft_engine::geom::primitives::material_ball(); @@ -284,8 +276,10 @@ mod tests { let mut mesh = texturecraft_engine::geom::primitives::plane(2.0, 1); mesh.append(&texturecraft_engine::geom::primitives::plane(2.0, 1)); let mut session = Session::new_project("Test", mesh, "two-planes", None, 128).unwrap(); + assert_eq!(session.caches.len(), 2); - session.images.insert("red".into(), Arc::new(ImageRes { width: 1, height: 1, rgba: vec![[1.0, 0.0, 0.0, 1.0]], srgb: true })); + + session.images.insert("red".into(), Arc::new(ImageRes::new(1, 1, vec![[1.0, 0.0, 0.0, 1.0]], true))); execute(&mut session, "viewport.view", &json!({"mode": "image", "image": "red"})).unwrap(); let camera = session.camera; let uv = |ts| ViewKind::Uv { ts, zoom: 1.0, pan: [0.0, 0.0], rotation: 0.0 }; @@ -302,6 +296,7 @@ mod tests { assert!(first.as_chunks::<4>().0.iter().any(|pixel| pixel[0] > 200 && pixel[1] < 20)); let (_, _, second) = gpu.render(&mut session, uv(1), [128, 128], camera).unwrap(); + assert!(second.as_chunks::<4>().0.iter().any(|pixel| pixel[0] > 200 && pixel[1] < 20)); assert_eq!(gpu.h.renderer.aux_size(1), Some(128)); } diff --git a/crates/automation/tests/perf.rs b/crates/automation/tests/perf.rs index 8b49f36f..ef73dc98 100644 --- a/crates/automation/tests/perf.rs +++ b/crates/automation/tests/perf.rs @@ -141,18 +141,6 @@ fn sample_for_project_bake(resolution: u32) -> Headless { backend } -#[test] -fn project_bake_uses_documented_ray_count() { - let backend = sample_for_project_bake(256); - - for texture_set in 0..backend.session.set_count() { - let task = backend.session.bake_task(texture_set).unwrap(); - assert_eq!(task.settings.maps.ao.parameters.rays.rays, 32); - assert_eq!(task.settings.maps.thickness.parameters.rays.rays, 32); - assert_eq!(task.settings.maps.bent_normal.parameters.rays.rays, 32); - } -} - /// The whole-project bake at benchmark settings (1024², 32 rays, AA 1), then 2048². #[test] #[ignore] diff --git a/crates/bake/src/tests.rs b/crates/bake/src/tests.rs index dab94f80..eaa64cf2 100644 --- a/crates/bake/src/tests.rs +++ b/crates/bake/src/tests.rs @@ -1056,24 +1056,6 @@ fn occlusion_falls_off_linearly_to_the_max_distance() { assert!((ambient_occlusion - 0.5).abs() < 0.01, "{ambient_occlusion}"); } -#[test] -fn secondary_ray_defaults_preserve_per_map_distances() { - let parameters = BakeSettings::default(); - let expected_rays = RaySettings { - rays: 64, - min_distance: 0.00001, - max_distance: 1.0, - relative_to_bounding_box: true, - spread: 180.0, - distribution: RayDistribution::Cosine, - }; - - assert_eq!(parameters.maps.ao.parameters.rays, expected_rays); - assert_eq!(parameters.maps.ao.parameters.attenuation, texturecraft_core::AmbientOcclusionAttenuation::Linear); - assert_eq!(parameters.maps.bent_normal.parameters.rays, expected_rays); - assert_eq!(parameters.maps.thickness.parameters.rays, RaySettings { max_distance: 0.1, ..expected_rays }); -} - #[test] fn bent_normals_and_thickness_have_their_own_rays() { let m = floor_and_wall(false); diff --git a/crates/compose/src/axis_frame.rs b/crates/compose/src/axis_frame.rs new file mode 100644 index 00000000..80f465fe --- /dev/null +++ b/crates/compose/src/axis_frame.rs @@ -0,0 +1,162 @@ +//! The frame an axis planar projection projects from: moving one on the model places it as that frame, so its images land where they did + +use texturecraft_core::{Decal, Projection, Projector, Source}; +use texturecraft_geom::glam::{EulerRot, Mat3, Vec3}; + +use crate::frame_placement::culling_folds; +use crate::pattern::{DEPTH_FADE_START, frame_uv_from_corner, mesh_frame, nonzero_stretch, projector_stretch}; + +/// Place an axis planar on a mesh within `bounds` while keeping its sampling and culling. +/// See [`culling_folds`] for when culling prevents placement. +pub fn placed_from_axis(proj: &Projection, bounds: (Vec3, Vec3)) -> Option { + let Projection::Planar { scale, axis, offset, uv, projector, placed: None } = proj else { return None }; + + if !culling_folds(projector) { + return None; + } + + let frame = axis_frame(*scale, *axis, Vec3::from(*offset), projector, bounds)?; + + // The frame carries rotation and scale while the projected rectangle keeps axis coverage + let projector = Projector { rotation: [0.0; 3], scale: [1.0; 3], ignore_image_alpha: true, ..*projector }; + + // An axis planar turns its image round the top left, a frame round its centre + let uv = frame_uv_from_corner(uv); + Some(Projection::Planar { scale: *scale, axis: *axis, offset: *offset, uv, projector, placed: Some(frame) }) +} + +/// Whether placing an axis planar that reads `sources` would move a pattern: a procedural reads an axis planar's plane but a placed frame's uv, so such a planar keeps its axis +pub fn placing_moves_pattern<'a>(mut sources: impl Iterator) -> bool { + sources.any(|source| matches!(source, Source::Procedural { .. })) +} + +/// The frame of an axis planar projection: its image's 0..1 square on the plane through the mesh, turned and sized by `projector` +pub fn axis_frame(scale: f32, axis: u8, offset: Vec3, projector: &Projector, bounds: (Vec3, Vec3)) -> Option { + let (center, radius) = mesh_frame(bounds); + let [x, y, z] = projector.rotation.map(f32::to_radians); + let turn = Mat3::from_euler(EulerRot::ZYX, z, y, x); + let stretch = projector_stretch(projector); + let scale = nonzero_stretch(scale); + + // Where the image's centre sits, then its across, up and out directions with the stretch along each + let origin = center + turn * (stretch * -offset / scale) * radius; + let (across, up, out) = match axis { + 0 => (Vec3::Z, Vec3::Y, Vec3::NEG_X), + 1 => (Vec3::X, Vec3::NEG_Z, Vec3::Y), + _ => (Vec3::X, Vec3::Y, Vec3::Z), + }; + let side = |direction: Vec3| 2.0 * radius * direction.abs().dot(stretch) / scale; + + // A negative stretch or scale turns that side over + let flip = |direction: Vec3| direction * side(direction).signum(); + let (across, up) = (flip(across), flip(up)); + let size = [side(across).abs(), side(up).abs()]; + let out = turn * across.cross(up).normalize_or(out); + + // Deep enough never to crop the mesh by depth: the fade starts at three quarters of it + let reach = (radius + (origin - center).length()) / DEPTH_FADE_START * DEPTH_SPARE; + let frame = Decal { + center: origin.to_array(), + normal: out.to_array(), + up: (turn * up).to_array(), + size, + rotation: 0.0, + offset: [0.0; 2], + depth: reach, + symmetry: None, + flip: [false; 2], + }; + (origin.is_finite() && size.iter().all(|side| side.is_finite() && *side > 0.0) && reach.is_finite()).then_some(frame) +} + +/// Extra reach past the farthest mesh point +const DEPTH_SPARE: f32 = 1.01; + +#[cfg(test)] +mod tests { + use texturecraft_core::{Backface, ShapeCrop, UvTransform}; + use texturecraft_geom::glam::Vec2; + + use super::*; + use crate::pattern::{Coords, image_samples}; + use crate::projector_cover::{framed_cover, projector_cover}; + + /// Points spread through the box `lo`..`hi` with varied normals + fn points(lo: Vec3, hi: Vec3) -> Vec<(Vec3, Vec3)> { + (0..64) + .map(|i| { + let spread = |salt: u32| ((i * 37 + salt * 11) % 64) as f32 / 63.0; + let position = lo + (hi - lo) * Vec3::new(spread(1), spread(2), spread(3)); + let normal = Vec3::new(spread(4) - 0.4, spread(5) - 0.3, spread(6) - 0.2).normalize_or(Vec3::Z); + (position, normal) + }) + .collect() + } + + #[test] + fn a_placed_axis_planar_reads_images_where_it_did() { + let (lo, hi) = (Vec3::new(-1.0, -0.5, -2.0), Vec3::new(3.0, 1.5, 0.5)); + let center = (lo + hi) * 0.5; + let radius = (hi - lo).length() * 0.5; + for axis in 0..3 { + for (rotation, stretch) in [([0.0; 3], [1.0; 3]), ([20.0, -35.0, 50.0], [1.5, 0.7, 2.0])] { + for crop in [ShapeCrop::ExtendsOutside, ShapeCrop::Cropped] { + let projector = Projector { rotation, scale: stretch, crop, ..Projector::default() }; + let uv = UvTransform { tiling: [2.0, 3.0], rotation: 30.0, offset: [0.1, -0.2] }; + let axis_planar = Projection::Planar { scale: 1.7, axis, offset: [0.3, -0.4, 0.2], uv, projector, placed: None }; + let placed = placed_from_axis(&axis_planar, (lo, hi)).expect("an axis planar has a frame"); + for (position, normal) in points(lo, hi) { + let coords = Coords { uv: Vec2::ZERO, pos: (position - center) / radius, nrm: normal }; + let (before, _) = image_samples(&axis_planar, &coords)[0]; + let (uv_after, cover) = framed_cover(&placed, position, normal, center).expect("a placed frame covers"); + let (after, _) = image_samples(&placed, &Coords { uv: uv_after, ..coords })[0]; + + assert!(before.distance(after) < 1e-3, "axis {axis} {rotation:?}: {before} became {after}"); + assert!((projector_cover(&axis_planar, &coords) - cover).abs() < 1e-3, "axis {axis} {crop:?}: cover changed at {position}"); + } + } + } + } + } + + #[test] + fn a_placed_axis_planar_keeps_what_backface_culling_hides() { + let (lo, hi) = (Vec3::new(-1.0, -0.5, -2.0), Vec3::new(3.0, 1.5, 0.5)); + let center = (lo + hi) * 0.5; + let radius = (hi - lo).length() * 0.5; + let backface = Backface { on: true, angle: 60.0, hardness: 1.0 }; + + // An oblique normal exposes tilted and reversed culling under stretch + let halfway = (center, Vec3::new(1.0, 0.0, 1.0).normalize()); + + for stretch in [[4.0, 1.0, 1.0], [1.5, -1.5, 1.5], [1.7; 3]] { + let projector = Projector { scale: stretch, backface, ..Projector::default() }; + let axis_planar = Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv: UvTransform::default(), projector, placed: None }; + let Some(placed) = placed_from_axis(&axis_planar, (lo, hi)) else { + assert!(!culling_folds(&projector), "{stretch:?}: only a stretch culling cannot keep stays unplaced"); + continue; + }; + + for (position, normal) in points(lo, hi).into_iter().chain([halfway]) { + let coords = Coords { uv: Vec2::ZERO, pos: (position - center) / radius, nrm: normal }; + let (_, cover) = framed_cover(&placed, position, normal, center).expect("a placed frame covers"); + assert!((projector_cover(&axis_planar, &coords) - cover).abs() < 1e-3, "{stretch:?}: culling changed at {normal}"); + } + } + + let even = Projector { scale: [1.7; 3], backface, ..Projector::default() }; + let axis_planar = Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv: UvTransform::default(), projector: even, placed: None }; + assert!(placed_from_axis(&axis_planar, (lo, hi)).is_some(), "an even stretch is still placed"); + } + + #[test] + fn only_axis_planars_are_placed() { + let bounds = (Vec3::NEG_ONE, Vec3::ONE); + + assert!(placed_from_axis(&Projection::default(), bounds).is_none()); + + let frame = axis_frame(1.0, 2, Vec3::ZERO, &Projector::default(), bounds).expect("a frame"); + assert!(placed_from_axis(&Projection::decal(frame), bounds).is_none()); + assert!(axis_frame(f32::NAN, 2, Vec3::ZERO, &Projector::default(), bounds).is_none()); + } +} diff --git a/crates/compose/src/below.rs b/crates/compose/src/below.rs index 4a2187ed..cdca3b83 100644 --- a/crates/compose/src/below.rs +++ b/crates/compose/src/below.rs @@ -7,13 +7,15 @@ //! identical to a full evaluation. use std::collections::{BTreeSet, HashMap, VecDeque}; -use std::sync::Arc; +use std::hash::{DefaultHasher, Hash, Hasher}; +use std::sync::{Arc, Weak}; use texturecraft_core::project::MAX_DEPTH; -use texturecraft_core::{BakedMap, Channel, EffectKind, Layer, LayerId, LayerKind, Project, Source, TextureSet}; +use texturecraft_core::{BakedMap, Channel, EffectKind, Filter, Layer, LayerId, LayerKind, Project, Source, TextureSet}; +use texturecraft_geom::Mesh; use texturecraft_texel::TileImage; -use crate::eval::{Inputs, PaintTarget}; +use crate::eval::{Inputs, PaintTarget, lights_material}; use crate::held_fields::HeldFields; use crate::image_identity::ImageIdentity; use crate::store::{BakedMaps, ImageStore, PixelStore}; @@ -25,6 +27,8 @@ pub const BELOW_BUDGET: usize = 256 << 20; /// See the module docs. One per texture set. #[derive(Debug)] pub struct BelowCache { + mesh: Weak, + borrowed_mesh_key: Option, hot: Option, key: Option, /// Tiles with the stamp of their last use. @@ -52,6 +56,8 @@ pub struct BelowCache { impl Default for BelowCache { fn default() -> Self { BelowCache { + mesh: Weak::new(), + borrowed_mesh_key: None, hot: None, key: None, tiles: HashMap::new(), @@ -98,6 +104,8 @@ pub struct StackKey { pixels: Vec<(LayerId, Option, Shared)>, baked: (u32, Vec<(BakedMap, usize)>), images: Vec<(String, ImageIdentity)>, + /// The viewport environment, its rotation (bits) and its image when it is an imported one, where Baked Lighting Environment lights with them + environment: Option<(String, u32, Option)>, } impl StackKey { @@ -142,18 +150,23 @@ impl StackKey { let mut referenced_images = BTreeSet::new(); if !images.is_empty() { - let mut record_image_reference = |source: &Source| { - referenced_images.extend(source.images().into_iter().filter_map(|name| images.get_key_value(name)).map(|(name, _)| name)); + let mut record_image_name = |name: &str| { + if let Some((name, _)) = images.get_key_value(name) { + referenced_images.insert(name); + } }; for layer in render_tree.iter().filter_map(|id| project.layers.get(id)) { if let LayerKind::Fill(fill) = &layer.kind { - fill.sources.values().for_each(&mut record_image_reference); + fill.sources.values().flat_map(Source::images).for_each(&mut record_image_name); } for effect in layer.mask.iter().flat_map(|mask| &mask.effects).chain(&layer.content_effects) { + // A filter's image inputs, also one its mode leaves unread: that only empties the cache more often + effect.inputs.values().flat_map(Source::images).for_each(&mut record_image_name); match &effect.kind { - EffectKind::Fill { source, .. } => record_image_reference(source), - EffectKind::Material(fill) => fill.sources.values().for_each(&mut record_image_reference), - EffectKind::Generator(generator) => generator.inputs.values().for_each(&mut record_image_reference), + EffectKind::Fill { source, .. } => source.images().into_iter().for_each(&mut record_image_name), + EffectKind::Material(fill) => fill.sources.values().flat_map(Source::images).for_each(&mut record_image_name), + EffectKind::Generator(generator) => generator.inputs.values().flat_map(Source::images).for_each(&mut record_image_name), + EffectKind::ColorSelection(selection) => selection.id_map.iter().for_each(|name| record_image_name(name)), _ => {} } } @@ -163,6 +176,16 @@ impl StackKey { let image_identities = referenced_images.into_iter().filter_map(|name| images.get(name).map(|image| (name.clone(), ImageIdentity::new(image)))).collect(); + let lit = render_tree + .iter() + .filter_map(|id| project.layers.get(id)) + .flat_map(|layer| layer.content_effects.iter()) + .any(|effect| matches!(effect.kind, EffectKind::Filter(Filter::EnvironmentLighting { .. }))); + let environment = lit.then(|| { + let image = project.display.environment_resource().and_then(|name| images.get(name)).map(ImageIdentity::new); + (project.display.environment.clone(), project.display.env_rotation.to_bits(), image) + }); + Some(StackKey { set, roots, @@ -170,6 +193,7 @@ impl StackKey { pixels: pixel_handles, baked: (baked.resolution, baked.maps.iter().map(|(map, data)| (*map, Arc::as_ptr(data) as usize)).collect()), images: image_identities, + environment, }) } } @@ -179,12 +203,20 @@ impl StackKey { /// changed (same set, roots, layers, baked maps and images; the same images by id, channel /// and size). None when anything else differs: the caller recomposites everything. pub fn changed_tiles(&self, other: &StackKey) -> Option> { - if self.set != other.set || self.roots != other.roots || self.layers != other.layers || self.baked != other.baked || self.images != other.images { + if self.set != other.set + || self.roots != other.roots + || self.layers != other.layers + || self.baked != other.baked + || self.images != other.images + || self.environment != other.environment + { return None; } + if self.pixels.len() != other.pixels.len() { return None; } + let size = self.set.size(); let mut changed = BTreeSet::new(); for ((left_id, left_channel, left_image), (right_id, right_channel, right_image)) in self.pixels.iter().zip(&other.pixels) { @@ -199,6 +231,7 @@ impl StackKey { if !same_shape || (left_image.width(), left_image.height()) != size { return None; } + if left_image.same_tiles(right_image) { continue; } @@ -260,6 +293,48 @@ fn render_view(l: &Layer) -> Layer { } impl BelowCache { + pub(crate) fn bind_mesh(&mut self, mesh: &Arc) { + if !std::ptr::eq(self.mesh.as_ptr(), mesh.as_ref()) { + self.clear(); + self.borrowed_mesh_key = None; + self.mesh = Arc::downgrade(mesh); + } + } + + pub(crate) fn bind_borrowed_mesh(&mut self, mesh: &Mesh) { + if std::ptr::eq(self.mesh.as_ptr(), mesh) { + return; + } + + // A borrow alone cannot distinguish in-place edits or reuse of the same address + let mut key = DefaultHasher::new(); + for attribute in [&mesh.positions, &mesh.normals] { + attribute.len().hash(&mut key); + for value in attribute { + value.to_array().map(f32::to_bits).hash(&mut key); + } + } + mesh.tangents.len().hash(&mut key); + for value in &mesh.tangents { + value.to_array().map(f32::to_bits).hash(&mut key); + } + mesh.uvs.len().hash(&mut key); + for value in &mesh.uvs { + value.to_array().map(f32::to_bits).hash(&mut key); + } + mesh.indices.hash(&mut key); + for part in &mesh.submeshes { + (&part.name, part.start, part.count, part.material).hash(&mut key); + } + + let key = key.finish(); + if self.borrowed_mesh_key != Some(key) { + self.clear(); + self.mesh = Weak::new(); + self.borrowed_mesh_key = Some(key); + } + } + /// Cache the stack around `hot` from now on (a different layer empties the cache). pub fn set_hot(&mut self, hot: Option) { if self.hot != hot { @@ -363,8 +438,17 @@ impl BelowCache { let project = inp.project; let set = project.texture_set(inp.ts).ok()?; - // Anchor readers depend on the stack below them - if project.render_tree(&set.stack).iter().any(|id| project.layers.get(id).is_some_and(Layer::reads_anchor)) { + // Replaying cached colors would reuse the material below a lighting or validation effect + if project + .render_tree(&set.stack) + .iter() + .filter_map(|id| project.layers.get(id)) + .any(|layer| layer.reads_stack() || layer.content_effects.iter().any(|effect| effect.visible && lights_material(&effect.kind))) + { + if self.key.is_some() { + self.clear(); + } + return None; } diff --git a/crates/compose/src/distance_envelope.rs b/crates/compose/src/distance_envelope.rs new file mode 100644 index 00000000..d78ea341 --- /dev/null +++ b/crates/compose/src/distance_envelope.rs @@ -0,0 +1,64 @@ +//! The lower envelope of parabolas that turns a line of squared distances into each place's squared distance to the nearest feature + +/// The lower envelope of the parabolas over a line of squared distances, which gives each place's squared distance to the nearest feature along it and the line before +#[derive(Default)] +pub(crate) struct DistanceEnvelope { + /// The parabolas still lowest somewhere: their vertex and where their stretch begins + parabolas: Vec<(usize, f64)>, + /// The line as it was + heights: Vec, +} + +impl DistanceEnvelope { + /// Replace `line` with each place's squared distance to the nearest feature + pub(crate) fn lower(&mut self, line: &mut [f32]) { + self.heights.clear(); + self.heights.extend_from_slice(line); + self.parabolas.clear(); + let heights = &self.heights; + + // In f64, where squared places and their sums stay exact past 4096 texels and a wide line cannot overflow a 32-bit usize + let lifted = |at: usize| f64::from(heights.get(at).copied().unwrap_or(f32::MAX)) + at as f64 * at as f64; + for at in 0..heights.len() { + let mut start = f64::NEG_INFINITY; + while let Some(&(vertex, from)) = self.parabolas.last() { + let crossing = (lifted(at) - lifted(vertex)) / (2.0 * (at - vertex) as f64); + if crossing <= from { + self.parabolas.pop(); + } else { + start = crossing; + break; + } + } + self.parabolas.push((at, start)); + } + + let mut current = 0; + for (at, out) in line.iter_mut().enumerate() { + while self.parabolas.get(current + 1).is_some_and(|(_, from)| *from < at as f64) { + current += 1; + } + if let Some(&(vertex, _)) = self.parabolas.get(current) { + *out = (at as f32 - vertex as f32).powi(2) + heights.get(vertex).copied().unwrap_or(f32::MAX); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Past 4096 texels a squared place is no longer exact in f32: two close features at the end of a wide line still each read 0 + #[test] + fn close_features_far_along_a_wide_line_stay_exact() { + const FAR: f32 = 4.0e8; + let mut line = vec![FAR; 10_000]; + line[9_950] = 1.0; + line[9_951] = 0.0; + + DistanceEnvelope::default().lower(&mut line); + + assert_eq!(line[9_949..9_954], [2.0, 1.0, 0.0, 1.0, 4.0]); + } +} diff --git a/crates/compose/src/effect_histogram.rs b/crates/compose/src/effect_histogram.rs new file mode 100644 index 00000000..83f948d6 --- /dev/null +++ b/crates/compose/src/effect_histogram.rs @@ -0,0 +1,95 @@ +//! The distribution of the values entering an effect, as the levels editor draws it + +use texturecraft_core::lum; + +/// Bucket counts over 0..1 of the values entering an effect, pooled and per part of a colour +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct EffectHistogram { + /// Every value, a colour's three components pooled + pub all: Vec, + /// Red, green and blue on their own; empty for a one-value channel or a mask + pub components: Vec>, + /// Each colour's luminance; a one-value channel's or a mask's values (the same as `all`) + pub luminance: Vec, +} + +impl EffectHistogram { + /// `bins` empty buckets (at least one), with per-component buckets when it counts colours + pub fn new(bins: usize, color: bool) -> EffectHistogram { + let bins = bins.max(1); + EffectHistogram { all: vec![0; bins], components: if color { vec![vec![0; bins]; 3] } else { Vec::new() }, luminance: vec![0; bins] } + } + + /// Counts one value of a one-value channel or a mask + pub fn add_value(&mut self, value: f32) { + bump(&mut self.all, value); + bump(&mut self.luminance, value); + } + + /// Counts one colour: each component pooled and on its own, and its luminance + pub fn add_color(&mut self, color: [f32; 3]) { + for (index, component) in color.into_iter().enumerate() { + bump(&mut self.all, component); + if let Some(counts) = self.components.get_mut(index) { + bump(counts, component); + } + } + bump(&mut self.luminance, lum(color)); + } + + /// Both histograms' counts together (they have the same buckets) + pub fn merged(mut self, other: &EffectHistogram) -> EffectHistogram { + add_counts(&mut self.all, &other.all); + for (counts, more) in self.components.iter_mut().zip(&other.components) { + add_counts(counts, more); + } + add_counts(&mut self.luminance, &other.luminance); + self + } +} + +/// One more count in the bucket of `value` (clamped to 0..1) +fn bump(counts: &mut [u32], value: f32) { + let bins = counts.len(); + let index = ((value.clamp(0.0, 1.0) * bins as f32) as usize).min(bins.saturating_sub(1)); + if let Some(count) = counts.get_mut(index) { + *count = count.saturating_add(1); + } +} + +fn add_counts(counts: &mut [u32], more: &[u32]) { + for (count, extra) in counts.iter_mut().zip(more) { + *count = count.saturating_add(*extra); + } +} + +#[cfg(test)] +mod tests { + use super::EffectHistogram; + + #[test] + fn a_colour_counts_each_component_pooled_and_alone_and_its_luminance() { + let mut histogram = EffectHistogram::new(4, true); + + histogram.add_color([1.0, 0.0, 0.3]); + let merged = histogram.clone().merged(&histogram); + + assert_eq!(histogram.all, vec![1, 1, 0, 1]); + assert_eq!(histogram.components, vec![vec![0, 0, 0, 1], vec![1, 0, 0, 0], vec![0, 1, 0, 0]]); + assert_eq!(histogram.luminance, vec![0, 1, 0, 0], "luminance 0.33 lands in the second bucket"); + assert_eq!(merged.all, vec![2, 2, 0, 2]); + assert_eq!(merged.components.first(), Some(&vec![0, 0, 0, 2])); + } + + #[test] + fn a_value_has_no_components() { + let mut histogram = EffectHistogram::new(2, false); + + histogram.add_value(f32::NAN); + histogram.add_value(0.9); + + assert_eq!(histogram.all, vec![1, 1]); + assert_eq!(histogram.luminance, histogram.all); + assert!(histogram.components.is_empty()); + } +} diff --git a/crates/compose/src/environment_sh.rs b/crates/compose/src/environment_sh.rs new file mode 100644 index 00000000..e236d306 --- /dev/null +++ b/crates/compose/src/environment_sh.rs @@ -0,0 +1,217 @@ +//! The viewport environment's diffuse light as spherical harmonics, worked out once per environment, and Baked Lighting Environment's shading with it + +use std::sync::{Arc, Mutex, Weak}; + +use texturecraft_core::project::DisplaySettings; +use texturecraft_core::{Channel, DIELECTRIC_REFLECTANCE, finite_unit, mix3}; +use texturecraft_geom::glam::Vec3; + +use crate::environment_sky::{VIEWPORT_WIDTH, dir_of, environment_linear, radiance, sh_basis, sh9_averaged}; +use crate::store::{ImageRes, ImageStore}; + +/// The diffuse light of the viewport environment and the turn the viewport gives it +#[derive(Clone, Copy)] +pub struct EnvironmentSh { + coefficients: [[f32; 3]; 9], + /// The viewport's environment rotation (radians) + rotation: f32, +} + +/// The last coefficients, keyed by a built-in name or the identity of an imported image +type CacheEntry = (String, Option>, [[f32; 3]; 9]); + +static CACHE: Mutex> = Mutex::new(None); + +impl EnvironmentSh { + /// The diffuse light of the environment `display` shows (an imported image from `images`), worked out once per environment + pub fn of(display: &DisplaySettings, images: &ImageStore) -> EnvironmentSh { + let image = display.environment_resource().and_then(|name| images.get(name)); + let same = |entry: &CacheEntry| match (&entry.1, &image) { + (Some(identity), Some(image)) => std::ptr::eq(identity.as_ptr(), Arc::as_ptr(image)), + (None, None) => entry.0 == display.environment, + _ => false, + }; + let rotation = display.env_rotation.to_radians(); + + let cached = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).as_ref().filter(|entry| same(entry)).map(|entry| entry.2); + if let Some(coefficients) = cached { + return EnvironmentSh { coefficients, rotation }; + } + + // Average outside the lock so a Rayon worker can take another tile that needs the cache + let coefficients = match image { + Some(image) => image_sh(image), + None => built_in_sh(&display.environment), + }; + *CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = Some((display.environment.clone(), image.map(Arc::downgrade), coefficients)); + EnvironmentSh { coefficients, rotation } + } + + /// The diffuse light reaching a surface facing world direction `normal` with the environment turned `horizontal` and tilted `vertical` (radians) past the viewport's turn + pub fn irradiance(&self, normal: Vec3, horizontal: f32, vertical: f32) -> Vec3 { + let (sin_tilt, cos_tilt) = vertical.sin_cos(); + let tilted = Vec3::new(normal.x, cos_tilt * normal.y - sin_tilt * normal.z, sin_tilt * normal.y + cos_tilt * normal.z); + + // Turned as the viewport turns its environment + let (sin_turn, cos_turn) = (self.rotation + horizontal).sin_cos(); + let direction = Vec3::new(cos_turn * tilted.x - sin_turn * tilted.z, tilted.y, sin_turn * tilted.x + cos_turn * tilted.z); + let light = sh_basis(direction).iter().zip(&self.coefficients).fold(Vec3::ZERO, |sum, (basis, coefficient)| sum + Vec3::from(*coefficient) * *basis); + light.max(Vec3::ZERO) + } + + /// Baked Lighting Environment's lit base color: linear `albedo`, its metal read from `channels` (straight values by [`Channel::index`]), in `light` (the environment's diffuse light at the surface, exposure applied), darkened by ambient occlusion `ao` by `[diffuse, specular]` occlusion. The viewer looks straight at the surface, so what it reflects is the light around the normal + pub fn shade(albedo: [f32; 3], light: Vec3, ao: f32, [diffuse_occlusion, specular_occlusion]: [f32; 2], channels: &[[f32; 3]]) -> [f32; 3] { + let ao = if ao.is_finite() { ao.clamp(0.0, 1.0) } else { 1.0 }; + let metal = finite_unit(channels.get(Channel::Metallic.index()).map_or(0.0, |m| m[0])); + let f0 = mix3([DIELECTRIC_REFLECTANCE; 3], albedo, metal); + let diffuse = 1.0 + (ao - 1.0) * finite_unit(diffuse_occlusion); + let specular = 1.0 + (ao - 1.0) * finite_unit(specular_occlusion); + let incoming = light.to_array(); + std::array::from_fn(|k| finite_unit(albedo[k] * (1.0 - metal) * incoming[k] * diffuse + f0[k] * incoming[k] * specular)) + } +} + +/// The coefficients of built-in environment `name` as the viewport works them out: drawn at its width, then averaged +fn built_in_sh(name: &str) -> [[f32; 3]; 9] { + let (width, height) = (VIEWPORT_WIDTH, VIEWPORT_WIDTH / 2); + sh9_averaged(width, height, |x, y| radiance(name, dir_of((x as f32 + 0.5) / width as f32, (y as f32 + 0.5) / height as f32))) +} + +/// The coefficients of an imported equirect image, every texel averaged in as the viewport does +fn image_sh(image: &ImageRes) -> [[f32; 3]; 9] { + let linear = |v: f32| environment_linear(v, image.srgb); + sh9_averaged(image.width, image.height, |x, y| { + let texel = image.rgba.get((y as usize) * image.width as usize + x as usize).copied().unwrap_or([0.0; 4]); + Vec3::new(linear(texel[0]), linear(texel[1]), linear(texel[2])) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A uniform environment lights every direction alike, whatever the turn; brighter skies light more + #[test] + fn a_uniform_image_lights_every_way_alike() { + for (width, height) in [(1, 1), (32, 16)] { + let image = ImageRes::new(width, height, vec![[0.5, 0.5, 0.5, 1.0]; (width * height) as usize], false); + let sh = EnvironmentSh { coefficients: image_sh(&image), rotation: 1.0 }; + + for normal in [Vec3::Y, Vec3::X, Vec3::NEG_Y, Vec3::new(0.6, 0.0, 0.8)] { + let light = sh.irradiance(normal, 0.3, 0.7); + assert!((light - Vec3::splat(0.5)).abs().max_element() < 0.02, "{width}x{height} {normal}: {light}"); + } + } + } + + /// The studio's key light is up and to one side: a surface facing up gets more light than one facing down, and turning the environment moves the light around + #[test] + fn a_built_in_lights_by_where_the_surface_faces_and_turns() { + let display = DisplaySettings { environment: "Studio Soft".into(), ..DisplaySettings::default() }; + let sh = EnvironmentSh::of(&display, &ImageStore::default()); + assert!(sh.irradiance(Vec3::Y, 0.0, 0.0).element_sum() > 2.0 * sh.irradiance(Vec3::NEG_Y, 0.0, 0.0).element_sum()); + let side = Vec3::new(0.7, 0.0, 0.7).normalize(); + let (here, turned) = (sh.irradiance(side, 0.0, 0.0), sh.irradiance(side, std::f32::consts::PI, 0.0)); + assert!((here - turned).abs().max_element() > 0.05, "{here} vs {turned}"); + let night = EnvironmentSh::of(&DisplaySettings { environment: "Night".into(), ..DisplaySettings::default() }, &ImageStore::default()); + assert!(night.irradiance(Vec3::Y, 0.0, 0.0).element_sum() < sh.irradiance(Vec3::Y, 0.0, 0.0).element_sum(), "the cache follows the environment"); + } + + #[test] + fn replacing_an_imported_environment_releases_its_image() { + let display = DisplaySettings { environment: "resource:lighting".into(), ..DisplaySettings::default() }; + + for color in [[1.0, 0.0, 0.0, 1.0], [0.0, 1.0, 0.0, 1.0]] { + let image = Arc::new(ImageRes::new(32, 16, vec![color; 32 * 16], false)); + let image_identity = Arc::downgrade(&image); + let images = ImageStore::from([("lighting".into(), image)]); + + let lighting = EnvironmentSh::of(&display, &images); + drop(images); + let irradiance = lighting.irradiance(Vec3::Y, 0.0, 0.0); + + assert!(irradiance.distance(Vec3::new(color[0], color[1], color[2])) < 0.02); + assert!(image_identity.upgrade().is_none(), "lighting should release the decoded image with its store"); + } + } + + /// Tiles on the thread pool that ask for a new light finish: the light is worked out with the cache unlocked, so a worker that steals another tile while it waits for its share of the averaging never waits for its own lock + #[test] + fn tiles_asking_for_a_new_light_on_the_thread_pool_finish() { + use rayon::prelude::*; + + const WORKERS: usize = 8; + const TILES: usize = 1024; + + // One tile in so many asks for the light; the rest finish at once, so their workers are free to steal the averaging's work + const LIT_EVERY: usize = 128; + const ROUNDS: usize = 20; + const PATIENCE: std::time::Duration = std::time::Duration::from_secs(60); + + let (done, finished) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let Ok(pool) = rayon::ThreadPoolBuilder::new().num_threads(WORKERS).build() else { return }; + pool.install(|| { + for round in 0..ROUNDS { + // Each round shows another environment, so its first tile misses the cache + let environment = if round % 2 == 0 { "Sunset" } else { "Night" }; + let display = DisplaySettings { environment: environment.into(), ..DisplaySettings::default() }; + (0..TILES).into_par_iter().filter(|tile| tile % LIT_EVERY == 0).for_each(|_| { + EnvironmentSh::of(&display, &ImageStore::default()); + }); + } + }); + let _ = done.send(()); + }); + assert!(finished.recv_timeout(PATIENCE).is_ok(), "the tiles deadlocked on the cache"); + } + + /// Diffuse occlusion darkens non-metals by the ambient occlusion; metals take their light from the reflections, which only specular occlusion darkens + #[test] + fn occlusion_darkens_the_diffuse_and_the_reflections_apart() { + let mut channels: Vec<[f32; 3]> = Channel::ALL.iter().map(|c| c.default_value()).collect(); + let light = Vec3::splat(1.0); + let dielectric = |occlusion| EnvironmentSh::shade([0.5; 3], light, 0.2, occlusion, &channels)[0]; + assert!(dielectric([1.0, 0.0]) < dielectric([0.0, 0.0]) * 0.5); + channels[Channel::Metallic.index()] = [1.0; 3]; + let metal = |occlusion| EnvironmentSh::shade([0.5; 3], light, 0.2, occlusion, &channels)[0]; + assert_eq!(metal([1.0, 0.0]), metal([0.0, 0.0])); + assert!(metal([0.0, 1.0]) < metal([0.0, 0.0]) * 0.5); + } + + /// The coefficients of `radiance` read at every place of a fine grid, the integral the averaged ones must match + fn fine_sh(width: u32, radiance: impl Fn(Vec3) -> Vec3) -> [[f32; 3]; 9] { + let height = width / 2; + crate::environment_sky::sh9(width, height, |x, y| radiance(dir_of((x as f32 + 0.5) / width as f32, (y as f32 + 0.5) / height as f32))) + } + + /// Sunset's sun is smaller than a texel of a coarse grid: averaging the viewport's drawing keeps its light, as the viewport does + #[test] + fn a_small_sun_lights_as_the_viewport_shows_it() { + let display = DisplaySettings { environment: "Sunset".into(), ..DisplaySettings::default() }; + + let baked = EnvironmentSh::of(&display, &ImageStore::default()).coefficients; + let fine = fine_sh(1024, |direction| radiance("Sunset", direction)); + + for (baked, fine) in baked.iter().zip(&fine) { + for (baked, fine) in baked.iter().zip(fine) { + assert!((baked - fine).abs() < 0.02, "{baked} vs {fine}"); + } + } + } + + /// An imported image's small bright patch counts though it falls between the texels a coarse read would take + #[test] + fn a_small_bright_patch_of_an_image_counts() { + const BRIGHT: f32 = 500.0; + let (width, height) = (1024u32, 512u32); + let patch = |x: u32, y: u32| (97..101).contains(&x) && (193..197).contains(&y); + let rgba = (0..width * height).map(|i| if patch(i % width, i / width) { [BRIGHT, BRIGHT, BRIGHT, 1.0] } else { [0.0, 0.0, 0.0, 1.0] }).collect(); + let image = ImageRes::new(width, height, rgba, false); + + let averaged = image_sh(&image)[0][0]; + let exact = crate::environment_sky::sh9(width, height, |x, y| if patch(x, y) { Vec3::splat(BRIGHT) } else { Vec3::ZERO })[0][0]; + + assert!(exact > 0.01 && (averaged - exact).abs() < exact * 0.05, "{averaged} vs {exact}"); + } +} diff --git a/crates/compose/src/environment_sky.rs b/crates/compose/src/environment_sky.rs new file mode 100644 index 00000000..a8ab62b8 --- /dev/null +++ b/crates/compose/src/environment_sky.rs @@ -0,0 +1,174 @@ +//! The built-in environments (drawn in code, no image assets) and their diffuse light as spherical harmonics, for the viewport and Baked Lighting Environment + +use std::f32::consts::{PI, TAU}; + +use rayon::prelude::*; +use texturecraft_geom::glam::{Vec2, Vec3}; + +use crate::soft_box::SoftBox; + +/// The width the viewport draws a built-in environment at (half as tall) +pub const VIEWPORT_WIDTH: u32 = 512; + +/// The width an environment is box-averaged down to before its diffuse light is worked out: averaging keeps a sun smaller than a texel +const SH_WIDTH: u32 = 128; + +/// The brightest radiance the viewport keeps of an imported environment (it stores half floats) +const HALF_FLOAT_MAX: f32 = 65_000.0; + +/// The irradiance convolution factor of each SH band (the cosine lobe's π, 2π/3 and π/4), one per coefficient +const COSINE_LOBE_BANDS: [f32; 9] = [PI, 2.0 * PI / 3.0, 2.0 * PI / 3.0, 2.0 * PI / 3.0, PI / 4.0, PI / 4.0, PI / 4.0, PI / 4.0, PI / 4.0]; + +/// The linear radiance of a component `v` of an imported environment's texel (sRGB-encoded when `srgb`): not a number is 0, capped at the half-float range, sRGB at 1 +pub fn environment_linear(v: f32, srgb: bool) -> f32 { + let v = if v.is_finite() { v.clamp(0.0, HALF_FLOAT_MAX) } else { 0.0 }; + if srgb { texturecraft_texel::srgb_to_linear(v.min(1.0)) } else { v } +} + +/// The direction at equirect place `u = φ / 2π`, `v = θ / π`: `(sin θ cos φ, cos θ, sin θ sin φ)`, row 0 straight up +pub fn dir_of(u: f32, v: f32) -> Vec3 { + let (theta, phi) = (v * PI, u * TAU); + Vec3::new(theta.sin() * phi.cos(), theta.cos(), theta.sin() * phi.sin()) +} + +/// The equirect place of direction `d` +pub fn uv_of(d: Vec3) -> Vec2 { + let phi = d.z.atan2(d.x); + Vec2::new((phi / TAU).rem_euclid(1.0), d.y.clamp(-1.0, 1.0).acos() / PI) +} + +/// Smoothstep of `t` over 0..1 +pub(crate) fn smooth(t: f32) -> f32 { + let t = t.clamp(0.0, 1.0); + t * t * (3.0 - 2.0 * t) +} + +/// How fast a sky turns from its horizon to its zenith and to its ground (powers of the height; under 1 turns early) +const ZENITH_FALLOFF: f32 = 0.6; +const GROUND_FALLOFF: f32 = 0.25; + +/// A sky blending `horizon` up to `zenith` and down to `ground` +fn sky(d: Vec3, zenith: Vec3, horizon: Vec3, ground: Vec3) -> Vec3 { + if d.y >= 0.0 { horizon.lerp(zenith, d.y.powf(ZENITH_FALLOFF)) } else { horizon.lerp(ground, (-d.y).powf(GROUND_FALLOFF)) } +} + +/// The Sunset sun's disc: the cosine of its edge from the centre, the width of its soft rim, and its brightness +const SUN_EDGE_COS: f32 = 0.9985; +const SUN_EDGE_WIDTH: f32 = 0.0012; +const SUN_RADIANCE: f32 = 120.0; + +/// The light a built-in environment `name` sends from direction `d` (unknown names give the default studio) +pub fn radiance(name: &str, d: Vec3) -> Vec3 { + if name == "Sunset" { + let base = sky(d, Vec3::new(0.15, 0.25, 0.55), Vec3::new(1.4, 0.65, 0.3), Vec3::new(0.08, 0.06, 0.05)); + let sun_dir = dir_of(0.12, 0.47); + let sun = smooth((d.dot(sun_dir) - SUN_EDGE_COS) / SUN_EDGE_WIDTH) * SUN_RADIANCE; + return base + Vec3::new(1.0, 0.6, 0.3) * sun; + } + + let (azimuth, elevation) = SoftBox::angles(d); + match name { + "Studio Contrast" => { + let base = sky(d, Vec3::splat(0.04), Vec3::splat(0.03), Vec3::splat(0.01)); + base + SoftBox { azimuth: 35.0, elevation: 30.0, half_width: 22.0, half_height: 18.0, color: Vec3::new(14.0, 13.2, 12.0) }.eval(azimuth, elevation) + + SoftBox { azimuth: -150.0, elevation: 40.0, half_width: 6.0, half_height: 30.0, color: Vec3::new(4.0, 4.4, 5.0) }.eval(azimuth, elevation) + } + "Overcast" => { + let base = sky(d, Vec3::new(1.2, 1.25, 1.35), Vec3::new(0.95, 0.95, 0.95), Vec3::new(0.18, 0.2, 0.15)); + base + SoftBox { azimuth: 60.0, elevation: 55.0, half_width: 40.0, half_height: 25.0, color: Vec3::splat(0.6) }.eval(azimuth, elevation) + } + "Warehouse" => { + let mut c = sky(d, Vec3::splat(0.25), Vec3::splat(0.18), Vec3::splat(0.06)); + for k in 0..6 { + c += SoftBox { azimuth: -150.0 + k as f32 * 60.0, elevation: 50.0, half_width: 6.0, half_height: 3.0, color: Vec3::new(9.0, 8.5, 7.5) } + .eval(azimuth, elevation); + } + c + SoftBox { azimuth: 90.0, elevation: 5.0, half_width: 30.0, half_height: 12.0, color: Vec3::new(1.6, 1.8, 2.2) }.eval(azimuth, elevation) + } + "Night" => { + let base = sky(d, Vec3::new(0.01, 0.015, 0.04), Vec3::new(0.03, 0.03, 0.06), Vec3::splat(0.005)); + base + SoftBox { azimuth: 20.0, elevation: 15.0, half_width: 10.0, half_height: 10.0, color: Vec3::new(0.4, 1.6, 4.0) }.eval(azimuth, elevation) + + SoftBox { azimuth: -110.0, elevation: 10.0, half_width: 12.0, half_height: 8.0, color: Vec3::new(4.0, 0.8, 1.6) }.eval(azimuth, elevation) + } + + // "Studio Soft" (default) + _ => { + let base = sky(d, Vec3::new(0.5, 0.52, 0.56), Vec3::new(0.32, 0.32, 0.33), Vec3::new(0.08, 0.075, 0.07)); + base + SoftBox { azimuth: 40.0, elevation: 35.0, half_width: 28.0, half_height: 20.0, color: Vec3::new(5.5, 5.2, 4.8) }.eval(azimuth, elevation) + + SoftBox { azimuth: -125.0, elevation: 20.0, half_width: 35.0, half_height: 22.0, color: Vec3::new(1.1, 1.25, 1.5) }.eval(azimuth, elevation) + + SoftBox { azimuth: 175.0, elevation: 55.0, half_width: 8.0, half_height: 25.0, color: Vec3::new(3.0, 3.0, 3.0) }.eval(azimuth, elevation) + } + } +} + +/// The 9 real spherical-harmonics basis functions at unit direction `d` (the standard band 0..2 constants) +pub fn sh_basis(d: Vec3) -> [f32; 9] { + let (x, y, z) = (d.x, d.y, d.z); + [ + 0.282_095, + 0.488_603 * y, + 0.488_603 * z, + 0.488_603 * x, + 1.092_548 * x * y, + 1.092_548 * y * z, + 0.315_392 * (3.0 * z * z - 1.0), + 1.092_548 * x * z, + 0.546_274 * (x * x - y * y), + ] +} + +/// Diffuse irradiance as 9 SH coefficients of the equirect image `width` x `height` whose texels `radiance` gives (already convolved with the cosine lobe and divided by π, so `Σ c·Y(n)` times albedo is the diffuse radiance) +pub fn sh9(width: u32, height: u32, radiance: impl Fn(u32, u32) -> Vec3) -> [[f32; 3]; 9] { + let (w, h) = (width.max(1), height.max(1)); + + // Sample each large texel across its angular footprint so a constant sky lights all directions + const MIN_COLUMNS: u32 = 32; + const MIN_ROWS: u32 = 16; + let samples_x = MIN_COLUMNS.div_ceil(w); + let samples_y = MIN_ROWS.div_ceil(h); + let (w, h) = (w * samples_x, h * samples_y); + let mut sums = [Vec3::ZERO; 9]; + for y in 0..h { + let theta = PI * (y as f32 + 0.5) / h as f32; + let solid_angle = (TAU / w as f32) * (PI / h as f32) * theta.sin(); + for x in 0..w { + let direction = dir_of((x as f32 + 0.5) / w as f32, (y as f32 + 0.5) / h as f32); + + // No firefly clamp: the projection integrates, so a bright sun lights diffuse fully + let weighted = radiance(x / samples_x, y / samples_y) * solid_angle; + for (sum, basis) in sums.iter_mut().zip(sh_basis(direction)) { + *sum += weighted * basis; + } + } + } + std::array::from_fn(|k| (sums[k] * COSINE_LOBE_BANDS[k] / PI).to_array()) +} + +/// [`sh9`] of the equirect image `width` x `height` whose texels `radiance` gives, box-halved while wider than [`SH_WIDTH`] (an odd last row or column is dropped, as the viewport drops it) +pub fn sh9_averaged(width: u32, height: u32, radiance: impl Fn(u32, u32) -> Vec3 + Sync) -> [[f32; 3]; 9] { + if width <= SH_WIDTH { + return sh9(width, height, radiance); + } + + let mut image = half(width, height, radiance); + while image.0 > SH_WIDTH { + let (w, h, data) = ℑ + image = half(*w, *h, |x, y| data.get((y * w + x) as usize).copied().unwrap_or(Vec3::ZERO)); + } + let (w, h, data) = image; + sh9(w, h, |x, y| data.get((y * w + x) as usize).copied().unwrap_or(Vec3::ZERO)) +} + +/// The equirect image `width` x `height` whose texels `texel` gives, box-downsampled by 2 (wrapping around, clamped at the poles): its width, height and texels +pub fn half(width: u32, height: u32, texel: impl Fn(u32, u32) -> Vec3 + Sync) -> (u32, u32, Vec) { + let (w, h) = ((width / 2).max(1), (height / 2).max(1)); + let get = |x: u32, y: u32| texel(x % width.max(1), y.min(height.saturating_sub(1))); + let mut data = vec![Vec3::ZERO; (w * h) as usize]; + data.par_chunks_mut(w as usize).enumerate().for_each(|(y, row)| { + for (x, texel) in row.iter_mut().enumerate() { + let (sx, sy) = (x as u32 * 2, y as u32 * 2); + *texel = (get(sx, sy) + get(sx + 1, sy) + get(sx, sy + 1) + get(sx + 1, sy + 1)) * 0.25; + } + }); + (w, h, data) +} diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 8bb323e9..3097e768 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -2,6 +2,8 @@ //! tile by tile in parallel. This is the reference implementation (the oracle) for the viewport //! and for export. +mod draw_placement; +mod evaluation_inputs; pub(crate) mod thumbnail; use std::borrow::Cow; @@ -10,26 +12,54 @@ use std::sync::Arc; use rayon::prelude::*; use texturecraft_core::{ - BakedMap, BlendMode, BlockScales, Channel, ChannelKind, CompareOp, CurvatureDetail, CurvatureMode, Effect, EffectKind, Fill, Filter, Generator, - GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Mask, MaskBackground, MicroDetail, NormalFormat, Project, Projection, Source, TextureSet, TileGrid, - blend1, blend3, lum, mix3, per_unit, + AnisotropicKuwahara, BakedMap, Bevel, BevelSmooth, BlendMode, BlockScales, Channel, ChannelKind, ColorMatch, CompareSource, ContentsOffset, + CurvatureDetail, CurvatureMode, Effect, EffectKind, FLAT_CURVATURE, Fill, Filter, Filtering, Generator, GeneratorKind, HeightMask, HeightToNormal, + HighpassSpace, ImageInput, Layer, LayerId, LayerKind, Mask, MaskBackground, MaskOutline, MicroDetail, Mirror, NormalFormat, PreparedColorMatch, + PreparedGradient, Project, Projection, RepeatMode, Sampling, ShapeCrop, Source, SourceColorMode, SourceSlopeBlur, SourceWarp, StylizedShading, + TargetColorMode, TextureSet, TileGrid, TileTransform, WarpSourceMode, blend1, blend3, lum, mix3, per_unit, posterize, udim_at, }; use texturecraft_geom::glam::{Vec2, Vec3}; -use texturecraft_geom::{Mesh, NO_TRI, UvGBuffer}; +use texturecraft_geom::{Mesh, NO_TRI, Surface, UvGBuffer}; use texturecraft_texel::{DilationMap, TILE, TILE_AREA, TileImage, from_u16, noise, to_u16, to_u16_signed}; +use crate::ProjectorDepthCache; use crate::below::{Band, BelowCache, Level, StackKey}; use crate::curvature_sizes::CurvatureSizes; +use crate::effect_histogram::EffectHistogram; +use crate::environment_sh::EnvironmentSh; +use crate::fill_copies::FillCopies; +use crate::fill_copy::FillCopy; +use crate::fill_depth::FillDepth; +use crate::fill_place::FillPlace; use crate::held_fields::HeldFields; -use crate::pattern::{Coords, decal_uv_symmetric, image_samples, pattern_pixels, procedural_in, world_noise}; +use crate::mask_gray::MaskGray; +use crate::pattern::{Coords, image_samples, mesh_frame, pattern_pixels, placement, procedural_in, world_noise}; use crate::pattern_context::PatternContext; -use crate::store::{BakedMaps, ImageStore, PixelStore, decode}; +use crate::projector_cover::{framed_cover, projector_cover, projector_covers_all}; +use crate::shape_distance::distance_filter; +use crate::slope_texel::slope_texel; +use crate::store::{BakedMaps, ImageRes, ImageStore, PixelStore, decode}; +use crate::warp_texel::{Input, MIN_READ_WEIGHT, Sample, warp_texel}; +use draw_placement::DrawPlacement; +use evaluation_inputs::EvaluationInputs; const NCH: usize = Channel::ALL.len(); +/// Coverage past which a symmetric fill's remaining copies would not show under the ones above +const COVERED: f32 = 0.9999; + +/// Largest projected step as a share of the image's longer side for non-UV projections +const SEAM_JUMP_SHARE: f32 = 0.25; + /// Stack values being composited, per channel. type Acc = [[f32; 3]; NCH]; +/// How tall a baked height of 1 stands, as a fraction of a UV tile, when Baked Lighting Stylized tilts normals by its slope +const HEIGHT_RELIEF: f32 = 1.0 / 32.0; + +/// The Height Intensity of Baked Lighting Environment that tilts the normals as Baked Lighting Stylized's Height to Normal Intensity 1 does (its default) +const ENVIRONMENT_HEIGHT_UNIT: f32 = 4.0; + /// What a live stroke paints into. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum PaintTarget { @@ -60,6 +90,7 @@ impl Stencil { if c.w <= 1e-6 { return None; } + let (dx, dy) = (c.x / c.w - self.center[0], c.y / c.w - self.center[1]); let (sn, cs) = (-self.rotation).sin_cos(); let lx = (dx * cs - dy * sn) / self.half[0].max(1e-6); @@ -67,6 +98,7 @@ impl Stencil { if !self.tile && (lx.abs() > 1.0 || ly.abs() > 1.0) { return None; } + let s = self.image.sample(lx * 0.5 + 0.5, 0.5 - ly * 0.5); let rgb = if self.image.srgb { [s[0], s[1], s[2]].map(texturecraft_texel::srgb_to_linear) } else { [s[0], s[1], s[2]] }; Some((rgb, s[3].clamp(0.0, 1.0))) @@ -88,8 +120,8 @@ pub struct StrokePreview { pub erase: bool, /// Values painted per channel (layer targets). pub values: BTreeMap, - /// Gray value painted into a mask. - pub mask_value: f32, + /// Gray painted into a mask + pub mask_gray: MaskGray, /// Projection tool: base color (and alpha) come from a screen-pinned image. pub stencil: Option, /// Clone and smudge: straight values per channel carried by the stroke (replace `values`). @@ -130,6 +162,23 @@ impl Inputs<'_> { fn tile_res_at(&self, x: u32, y: u32) -> u32 { ((self.tile_res() as f32 * self.block_scales.at(x, y)).round() as u32).max(1) } + + /// Mesh UV units per atlas texel along each axis, within the tile containing `(x, y)`. + fn mesh_uv_step(&self, x: u32, y: u32) -> Vec2 { + let atlas_step = Vec2::new(self.gbuf.width.max(1) as f32, self.gbuf.height.max(1) as f32).recip(); + let Ok(set) = self.project.texture_set(self.ts) else { return atlas_step }; + let Some(grid) = set.tile_grid() else { return atlas_step }; + + let grid_step = atlas_step * Vec2::new(grid.cols as f32, grid.rows as f32); + if set.tile_resolutions.is_empty() { + return grid_step; + } + + // Locate the atlas cell before undoing the tile scale + let atlas_uv = Vec2::new(x as f32 + 0.5, y as f32 + 0.5) * atlas_step; + let tile_scale = udim_at(grid.from_atlas(atlas_uv.to_array())).map_or(1.0, |tile| set.tile_scale(tile)); + grid_step / tile_scale + } } /// The composited channels of one texture set. @@ -211,8 +260,18 @@ struct ChanPlan<'a> { } enum Content<'a> { - Paint { preview: bool }, - Fill(&'a Fill), + Paint { + preview: bool, + }, + /// A fill (with the Scale and Rotation of the folders around it laid on) + Fill { + fill: &'a Fill, + projection: Option>, + /// Its projector's depth map when it culls by depth + depth: Option>, + /// Whether it covers every texel (see [`covers_every_texel`]), so no texel asks + covers_all: bool, + }, Group(Vec>), } @@ -220,6 +279,8 @@ struct EffectPlan<'a> { /// The effect id (an anchor point records under it). id: LayerId, kind: &'a EffectKind, + /// The source projection after applying an enclosing folder's transform + projection: Option, blend: BlendMode, opacity: f32, data: Option>, @@ -228,11 +289,41 @@ struct EffectPlan<'a> { curvature_sizes: Option>, /// A filtered mask stage retained because an anchor above it records that stage. filtered_mask: Option<&'a Field>, + /// The projector's depth map of a fill or material effect that culls by depth + depth: Option>, + /// Whether a fill or material effect covers every texel (see [`covers_every_texel`]), so no texel asks + covers_all: bool, + /// The viewport environment's light, for Baked Lighting Environment + environment: Option, + /// Baked Lighting Stylized's settings worked out once for every texel it shades + stylized: Option, + /// The source a point filter's image input reads (Grayscale Conversion's Custom Input) + input: Option, + /// Custom stops shared across tile plans and channels + gradient: Option>, +} + +impl EffectPlan<'_> { + fn point(&self, filter: &Filter, kind: ChannelKind, value: [f32; 3]) -> Option<[f32; 3]> { + match &self.gradient { + Some(gradient) => gradient.point(kind, value), + None => filter.point(kind, value), + } + } + + fn ramp_at(&self, filter: &Filter, position: f32) -> Option<[f32; 3]> { + match &self.gradient { + Some(gradient) => gradient.at(position), + None => filter.ramp_at(position), + } + } } struct MaskPlan<'a> { background: f32, effects: Vec>, + /// The layer's own content in the channels its compare effects read (planned only when one reads the stack) + layer: Option<(Content<'a>, Vec>)>, /// A neighbourhood filter (blur, sharpen) precomputed over the region: continue the stack /// after effect `.0` starting from the field's value. start: Option<(usize, &'a Field)>, @@ -248,7 +339,7 @@ pub struct Field { comps: usize, data: Vec, /// Intermediate mask stages needed by anchors, owned by this drawn layer's final field. - anchor_stages: Vec<(LayerId, Field)>, + anchor_stages: Vec<(usize, Field)>, } impl Field { @@ -256,49 +347,110 @@ impl Field { if x < self.x0 || y < self.y0 || x >= self.x0 + self.w || y >= self.y0 + self.h { return None; } + let i = ((y - self.y0) * self.w + (x - self.x0)) as usize * self.comps; self.data.get(i..i + self.comps) } } +/// A layer's mask or content channel field, filtered under the folders' Scale and Rotation (as bits) its traversal lays on its fills #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum FieldKey { - Mask(LayerId), - Content(LayerId, Channel), + Mask(LayerId, [u32; 2]), + Content(LayerId, Channel, [u32; 2]), + InstanceMask(LayerId, [u32; 2], usize), + InstanceContent(LayerId, Channel, [u32; 2], usize), +} + +impl FieldKey { + fn in_instance(self, instance: usize) -> Self { + match self { + Self::Mask(id, offset) if instance != 0 => Self::InstanceMask(id, offset, instance), + Self::Content(id, channel, offset) if instance != 0 => Self::InstanceContent(id, channel, offset, instance), + key => key, + } + } + + fn field(self, fields: &Fields, instance: usize) -> Option<&Field> { + if instance != 0 + && let Some(field) = fields.get(&self.in_instance(instance)) + { + return Some(field); + } + + fields.get(&self) + } + + /// The key of layer `id`'s mask field under the folders' offset `around` + pub fn mask(id: LayerId, around: ContentsOffset) -> FieldKey { + FieldKey::Mask(id, [around.scale.to_bits(), around.rotation.to_bits()]) + } + + /// The key of layer `id`'s `channel` content field under the folders' offset `around` + pub fn content(id: LayerId, channel: Channel, around: ContentsOffset) -> FieldKey { + FieldKey::Content(id, channel, [around.scale.to_bits(), around.rotation.to_bits()]) + } } pub type Fields = HashMap; -/// How a neighbourhood filter reads around a texel. +/// How a neighbourhood filter reads around a texel #[derive(Clone, Copy)] enum Op { - /// Box blurs (≈ Gaussian), sharpening by the amount when given. + /// Box blurs (≈ Gaussian), sharpening by the amount when given Blur(Option), - /// The value minus its box blur, around the channel's mid value. - HighPass, - /// Values ramped down towards their shape's edge, from the box blur. + /// The value minus its box blur, around the channel's mid value: colors in `space`, the coverage too when `alpha` + HighPass { space: HighpassSpace, alpha: bool }, + /// Values ramped down towards their shape's edge, from the box blur Bevel, - /// The value plus its box blur times the amount. + /// The value plus its box blur times the amount Glow(f32), - /// The value at the center of its cell (`r` texels across). - Mosaic, - /// Average along a direction (unit vector in texels). + /// The value at the center of its cell (`r` texels across); the texel's own coverage kept unless `alpha` + Mosaic { alpha: bool }, + /// Stair-stepped edges blended across (FXAA); the texel's own coverage kept unless `alpha` + Fxaa { alpha: bool }, + /// The mean of the calmest sector of an ellipse along the local direction (see [`kuwahara_texel`]) + Kuwahara(AnisotropicKuwahara), + /// Average along a direction (unit vector in texels) Line([f32; 2]), - /// Read at an offset given by a noise vector field, or by noise along a direction. + /// Read at an offset given by a noise vector field, or by noise along a direction Warp { scale: f32, seed: u32, dir: Option<[f32; 2]> }, - /// Gradient magnitude from central differences. + /// Gradient magnitude from central differences Edge, - /// Average downhill along a noise height field. + /// Average downhill along a noise height field Slope { scale: f32, seed: u32 }, + /// Box blurs, then the effect's own point filter on the blurred value (a gradient's Blur Intensity) + PreBlur, + /// A halo from the box blur of the shapes, laid around (or inside) them + Halo, + /// The shapes moved by `offset` (whole texels), box blurred and laid under them + Shadow { offset: [i32; 2] }, + /// Each UV tile's texels read from where `mirror` sends them in their tile (`block` texels across the set's atlas blocks) + Mirror { mirror: Mirror, block: u32 }, + /// Each UV tile's texels read from where `transform` sends them (its `affine`, worked out once), repeating round the tile or empty past it + Transform { transform: TileTransform, affine: ([[f32; 2]; 2], [f32; 2]), block: u32 }, + /// A band along the edge of the shapes past a threshold, from the box blur of the shapes + Outline(MaskOutline), + /// Drawn from the distance to the shapes' edge (see [`distance_filter`]) + Distance, + /// Read from where a warp's source sends each texel (see [`warp_texel`]) + SourceWarp(SourceWarp), + /// The values downhill of each texel along a source's slope, blended (see [`slope_texel`]) + SourceSlopeBlur(SourceSlopeBlur), + /// The normal of the slopes of the layer's Height (see [`height_to_normal_texel`]) + HeightToNormal(HeightToNormal), + /// Colors moved from a source color to a target color; the source the whole set's mean in Source Color Mode Average (see [`color_match`]) + ColorMatch(ColorMatch), } -/// The last neighbourhood filter of an effect stack (see [`neighbourhood_filters`]). +/// The last neighbourhood filter of an effect stack (see [`neighbourhood_filters`]) fn neighbourhood(effects: &[Effect], res: u32) -> Option<(usize, f32, Op)> { - neighbourhood_filters(effects, res).last() + neighbourhood_filters(effects, res, None).last() } -/// Below this a coverage weight counts as no coverage at all. -const MIN_COVERAGE_WEIGHT: f32 = 1e-6; +/// Below this squared length an unpacked baked normal is no direction (an unbaked texel) +const MIN_NORMAL_LENGTH_SQUARED: f32 = 1e-6; + /// Filter sizes are texels at this many texels per side (2K), scaled to the resolution they run at. const FILTER_SIZE_RESOLUTION: f32 = 2048.0; /// The smallest radius a filter runs at, in texels. @@ -308,35 +460,86 @@ const SHARPEN_RADIUS: f32 = 1.5; const MIN_SHARPEN_RADIUS: f32 = 0.75; /// The neighbourhood filters of an effect stack, bottom → top: index among the visible effects, radius in texels (`res` texels per UV tile across) and what it does. -fn neighbourhood_filters(effects: &[Effect], res: u32) -> impl Iterator + '_ { +fn neighbourhood_filters(effects: &[Effect], res: u32, channel: Option) -> impl Iterator + '_ { let texels = move |size: f32| (size * res as f32 / FILTER_SIZE_RESOLUTION).max(MIN_FILTER_RADIUS); - effects.iter().filter(|effect| effect.visible).enumerate().filter_map(move |(index, effect)| match &effect.kind { - EffectKind::Filter(Filter::Blur { radius }) if *radius > 0.0 => Some((index, texels(*radius), Op::Blur(None))), - EffectKind::Filter(Filter::Sharpen { amount }) => { - Some((index, (SHARPEN_RADIUS * res as f32 / FILTER_SIZE_RESOLUTION).max(MIN_SHARPEN_RADIUS), Op::Blur(Some(*amount)))) - } - EffectKind::Filter(Filter::DirectionalBlur { radius, angle }) if *radius > 0.0 => Some((index, texels(*radius), Op::Line(direction(*angle)))), - EffectKind::Filter(Filter::Warp { intensity, scale, seed }) if *intensity > 0.0 => { - Some((index, texels(*intensity), Op::Warp { scale: *scale, seed: *seed, dir: None })) - } - EffectKind::Filter(Filter::DirectionalWarp { intensity, angle, scale, seed }) if *intensity > 0.0 => { - Some((index, texels(*intensity), Op::Warp { scale: *scale, seed: *seed, dir: Some(direction(*angle)) })) - } - EffectKind::Filter(Filter::HighPass { radius }) => Some((index, texels(*radius), Op::HighPass)), - EffectKind::Filter(Filter::EdgeDetect { width }) => Some((index, texels(*width), Op::Edge)), - // Three box passes ramp an edge over about twice their radius - EffectKind::Filter(Filter::Bevel { width }) => Some((index, texels(*width * 0.5), Op::Bevel)), - EffectKind::Filter(Filter::Glow { radius, amount }) => Some((index, texels(*radius), Op::Glow(*amount))), - EffectKind::Filter(Filter::Mosaic { size }) => Some((index, texels(*size), Op::Mosaic)), - // Independent of `res`, so every caller agrees on which effects are stages; the reach covers the cells, then the blur around them - EffectKind::Generator(generator) if generator.global.blur > 0.0 || generator.resolution.can_reduce() => { - Some((index, texels(generator.global.blur_radius()) + generator.resolution.largest_cell(res) as f32, Op::Blur(None))) - } - EffectKind::Filter(Filter::SlopeBlur { radius, scale, seed }) if *radius > 0.0 => { - Some((index, texels(*radius), Op::Slope { scale: *scale, seed: *seed })) - } - _ => None, - }) + effects + .iter() + .filter(|effect| effect.visible) + .enumerate() + .filter(move |(_, effect)| channel.is_none_or(|channel| effect.blend_of(Some(channel)).mode != BlendMode::Disable)) + .filter_map(move |(index, effect)| match &effect.kind { + EffectKind::Filter(Filter::Blur { radius, .. }) if *radius > 0.0 => Some((index, texels(*radius), Op::Blur(None))), + EffectKind::Filter(Filter::Sharpen { amount }) => { + Some((index, (SHARPEN_RADIUS * res as f32 / FILTER_SIZE_RESOLUTION).max(MIN_SHARPEN_RADIUS), Op::Blur(Some(*amount)))) + } + EffectKind::Filter(Filter::DirectionalBlur { radius, angle }) if *radius > 0.0 => Some((index, texels(*radius), Op::Line(direction(*angle)))), + EffectKind::Filter(Filter::Warp { intensity, scale, seed, divider }) if *intensity > 0.0 => { + Some((index, texels(divided(*intensity, *divider)), Op::Warp { scale: *scale, seed: *seed, dir: None })) + } + EffectKind::Filter(Filter::DirectionalWarp { intensity, angle, scale, seed, divider }) if *intensity > 0.0 => { + Some((index, texels(divided(*intensity, *divider)), Op::Warp { scale: *scale, seed: *seed, dir: Some(direction(*angle)) })) + } + EffectKind::Filter(Filter::SourceWarp(warp)) if warp.move_texels(res) > 0.0 => Some((index, warp.reach(res).max(0.5), Op::SourceWarp(*warp))), + EffectKind::Filter(Filter::SourceSlopeBlur(slope)) if slope.move_texels(res) > 0.0 => { + Some((index, slope.reach(res).max(0.5), Op::SourceSlopeBlur(*slope))) + } + EffectKind::Filter(Filter::HighPass { radius, space, alpha }) => Some((index, texels(*radius), Op::HighPass { space: *space, alpha: *alpha })), + EffectKind::Filter(Filter::EdgeDetect { width }) => Some((index, texels(*width), Op::Edge)), + // Three box passes ramp an edge over about twice their radius + EffectKind::Filter(Filter::Bevel { width, .. }) => Some((index, texels(*width * 0.5), Op::Bevel)), + EffectKind::Filter(Filter::Glow { radius, amount }) => Some((index, texels(*radius), Op::Glow(*amount))), + EffectKind::Filter(Filter::Mosaic { size, alpha }) => Some((index, texels(*size), Op::Mosaic { alpha: *alpha })), + EffectKind::Filter(Filter::Fxaa { alpha }) => Some((index, FXAA_SEARCH as f32 + 1.0, Op::Fxaa { alpha: *alpha })), + // Both the direction search and the ellipse can reach twice the radius + EffectKind::Filter(Filter::AnisotropicKuwahara(kuwahara)) if kuwahara.radius > 0.0 => { + Some((index, texels(kuwahara.radius.min(AnisotropicKuwahara::MAX_RADIUS)) * (2.0 + kuwahara.tensor_reach()) + 1.0, Op::Kuwahara(*kuwahara))) + } + + // The slopes come from the heights right around a texel + EffectKind::Filter(Filter::HeightToNormal(filter)) if channel.is_none_or(|channel| channel == Channel::Normal) => { + Some((index, 1.0, Op::HeightToNormal(*filter))) + } + + // Average reads the mean color of the whole set; the other modes read the texel alone + EffectKind::Filter(Filter::ColorMatch(matcher)) if channel.is_none_or(|channel| channel.kind() == ChannelKind::Color) => { + Some((index, if matcher.source_mode == SourceColorMode::Average { WHOLE_SET } else { 1.0 }, Op::ColorMatch(*matcher))) + } + + // Use reference-resolution reach so all callers classify the same filters as stages + EffectKind::Generator(generator) if generator.global.blur > 0.0 || generator.resolution.can_reduce() => { + Some((index, texels(generator.global.blur_radius()) + generator.resolution.largest_cell(res) as f32, Op::Blur(None))) + } + + // A mirror reads anywhere in its UV tile + EffectKind::Filter(Filter::Mirror(mirror)) => Some((index, res as f32, Op::Mirror { mirror: *mirror, block: res })), + // A transform reads anywhere in its UV tile; one that changes nothing is skipped + EffectKind::Filter(Filter::Transform(transform)) if !transform.is_identity() => { + Some((index, res as f32, Op::Transform { transform: *transform, affine: transform.affine(), block: res })) + } + + // Three box passes reach the band's width + EffectKind::Filter(Filter::MaskOutline(outline)) => { + Some((index, (outline.width * res as f32 / BLUR_BOX_PASSES as f32).max(MIN_FILTER_RADIUS), Op::Outline(*outline))) + } + + // Three box passes' reach covers the distance and its smoothing + EffectKind::Filter(filter @ (Filter::DistanceBevel(_) | Filter::BevelSmooth(_) | Filter::DirectionalDistance(_))) => { + Some((index, distance_reach(filter, res) / BLUR_BOX_PASSES as f32 + 1.0, Op::Distance)) + } + EffectKind::Filter(Filter::HaloGlow { width, .. }) => Some((index, texels(width.abs() * Filter::HALO_REACH), Op::Halo)), + EffectKind::Filter(Filter::DropShadow { angle, distance, size, .. }) => { + // Cast away from the light: `distance` of a UV tile, against the light's direction + let [dx, dy] = direction(*angle); + let reach = distance.clamp(-Filter::SHADOW_DISTANCE_MAX, Filter::SHADOW_DISTANCE_MAX) * res as f32; + let offset = [(-dx * reach).round() as i32, (-dy * reach).round() as i32]; + Some((index, texels(size * Filter::HALO_REACH), Op::Shadow { offset })) + } + EffectKind::Filter(Filter::GradientMap { input, debug: false, .. }) if input.blur > 0.0 => Some((index, texels(input.blur), Op::PreBlur)), + EffectKind::Filter(Filter::SlopeBlur { radius, scale, seed, divider }) if *radius > 0.0 => { + Some((index, texels(divided(*radius, *divider)), Op::Slope { scale: *scale, seed: *seed })) + } + _ => None, + }) } /// Whether any mask or content effect in a texture set reads neighbouring texels. Includes @@ -355,9 +558,27 @@ pub fn stack_reads_neighbours(project: &Project, texture_set_index: usize) -> bo }) } +/// A neighbourhood radius that reaches the whole set ([`filter_extent`] caps it at the set's longest side) +const WHOLE_SET: f32 = 65_536.0; + +/// How many texels around a texel distance filter `filter` reads at `res` texels across a UV tile: its reach and its smoothing's three box passes +fn distance_reach(filter: &Filter, res: u32) -> f32 { + match filter { + Filter::DistanceBevel(bevel) => bevel.reach(res) + BLUR_BOX_PASSES as f32 * bevel.smoothing_texels(res), + Filter::BevelSmooth(smooth) => smooth.reach(res) + BLUR_BOX_PASSES as f32 * smooth.smoothing_texels(res), + Filter::DirectionalDistance(trail) => trail.reach(res), + _ => 0.0, + } +} + +/// `size` over its intensity divider (a divider of 0 from a hostile file counts as 1) +fn divided(size: f32, divider: u16) -> f32 { + size / f32::from(divider.max(1)) +} + /// Unit texel-space vector of `angle` degrees. Texel rows run down: positive angles turn /// counterclockwise on screen. -fn direction(angle: f32) -> [f32; 2] { +pub(crate) fn direction(angle: f32) -> [f32; 2] { let (sn, cs) = angle.to_radians().sin_cos(); [cs, -sn] } @@ -369,36 +590,83 @@ const MAP_GAIN: f32 = 2.0; const GAIN_PER_DETAIL_TEXEL: f32 = 2.0 * std::f32::consts::SQRT_2; /// Samples along a directional or slope blur at most (beyond, samples spread out). -const LINE_SAMPLES: i32 = 24; +pub(crate) const LINE_SAMPLES: i32 = 24; /// Fractal noise over texel position `(x, y)` (`res` texels per UV unit, `scale` features per /// UV unit), shifted by `d` in noise space. -fn texel_noise(x: f32, y: f32, d: [f32; 2], res: u32, scale: f32, seed: u32) -> f32 { - let k = if scale.is_finite() { scale.clamp(0.01, 1000.0) } else { 1.0 } / res.max(1) as f32; - noise::fbm([x * k + d[0], y * k + d[1], 0.0], 3, seed, noise::perlin) +pub(crate) fn texel_noise(x: f32, y: f32, d: [f32; 2], res: u32, scale: f32, seed: u32) -> f32 { + let per_texel = if scale.is_finite() { scale.clamp(Filter::NOISE_SCALE_MIN, Filter::NOISE_SCALE_MAX) } else { 1.0 } / res.max(1) as f32; + noise::fbm([x * per_texel + d[0], y * per_texel + d[1], 0.0], 3, seed, noise::perlin) } -/// The neighbourhood filters that gather samples (directional and slope blur, warp) over a -/// field region `(x0, y0, w, h)` of premultiplied `orig` texels (`comps` each) and their -/// `cover`: bilinear samples weighted by coverage, so uncovered texels don't bleed in. -/// Positions are absolute texel coordinates, so a texel's result does not depend on the region. +/// Gain on a noise warp's value around mid gray: values a third away from it already move the whole radius, as the noise seldom strays further +const WARP_NOISE_GAIN: f32 = 3.0; + +/// Mixed into a noise warp's seed for its vertical move, so it differs from the horizontal one (any odd constant does) +const WARP_Y_SALT: u32 = 0x5BD1_E995; + +/// How far apart, in noise space, a slope blur measures its noise's slope +const SLOPE_NOISE_PROBE: f32 = 0.01; + +/// The neighbourhood filters that gather samples (directional and slope blur, warp) over a field region `(x0, y0, w, h)` of premultiplied `orig` texels (`comps` each) and their `cover`: bilinear samples weighted by coverage, so uncovered texels don't bleed in; positions are absolute texel coordinates, so a texel's result does not depend on the region #[allow(clippy::too_many_arguments)] -fn gather(op: Op, orig: &[f32], cover: &[f32], comps: usize, (x0, y0, w, h): (u32, u32, u32, u32), r: f32, res: u32, opacity: f32) -> Vec { +fn gather( + op: Op, + (orig, cover, grays): (&[f32], &[f32], &[f32]), + comps: usize, + (x0, y0, w, h): (u32, u32, u32, u32), + r: f32, + (res, block_size, tile_size): (u32, [u32; 2], [u32; 2]), + opacity: f32, +) -> Vec { let mut data = orig.to_vec(); - let (wu, hu) = (w as usize, h as usize); - // Bilinear sample at absolute texel position (fx, fy) into `acc` (components, then weight). + let (width, height) = (w as usize, h as usize); + let warp_directions = match op { + Op::SourceWarp(warp) => warp.angles().map(direction).collect::>(), + _ => Vec::new(), + }; + + // The filter's image input at absolute texel position (fx, fy), bilinear over the covered texels; None off them + let input = |fx: f32, fy: f32| -> Option { + if !(fx.is_finite() && fy.is_finite()) { + return None; + } + + let (bx, by) = (fx.floor(), fy.floor()); + let (tx, ty) = (fx - bx, fy - by); + let (mut sum, mut weight) = (0.0f32, 0.0f32); + for (dx, dy, k) in [(0, 0, (1.0 - tx) * (1.0 - ty)), (1, 0, tx * (1.0 - ty)), (0, 1, (1.0 - tx) * ty), (1, 1, tx * ty)] { + let (cx, cy) = (bx as i64 + dx - i64::from(x0), by as i64 + dy - i64::from(y0)); + if k <= 0.0 || cx < 0 || cy < 0 || cx >= width as i64 || cy >= height as i64 { + continue; + } + + let i = cy as usize * width + cx as usize; + if let (Some(covered), Some(gray)) = (cover.get(i), grays.get(i)) + && *covered > 0.0 + { + sum += gray * k; + weight += k; + } + } + (weight > MIN_READ_WEIGHT).then(|| sum / weight) + }; + + // Bilinear sample at absolute texel position (fx, fy) into `acc` (components, then weight) let sample = |fx: f32, fy: f32, acc: &mut [f32; 5]| { if !(fx.is_finite() && fy.is_finite()) { return; } + let (bx, by) = (fx.floor(), fy.floor()); let (tx, ty) = (fx - bx, fy - by); for (dx, dy, k) in [(0, 0, (1.0 - tx) * (1.0 - ty)), (1, 0, tx * (1.0 - ty)), (0, 1, (1.0 - tx) * ty), (1, 1, tx * ty)] { let (cx, cy) = (bx as i64 + dx - i64::from(x0), by as i64 + dy - i64::from(y0)); - if k <= 0.0 || cx < 0 || cy < 0 || cx >= wu as i64 || cy >= hu as i64 { + if k <= 0.0 || cx < 0 || cy < 0 || cx >= width as i64 || cy >= height as i64 { continue; } - let i = cy as usize * wu + cx as usize; + + let i = cy as usize * width + cx as usize; let (Some(c), Some(px)) = (cover.get(i), orig.get(i * comps..(i + 1) * comps)) else { continue }; for (a, v) in acc.iter_mut().zip(px) { *a += v * k; @@ -406,11 +674,13 @@ fn gather(op: Op, orig: &[f32], cover: &[f32], comps: usize, (x0, y0, w, h): (u3 acc[4] += c * k; } }; - data.par_chunks_mut((comps * wu).max(1)).enumerate().for_each(|(row, line)| { - for col in 0..wu { - if cover.get(row * wu + col).is_none_or(|c| *c <= 0.0) { + + data.par_chunks_mut((comps * width).max(1)).enumerate().for_each(|(row, line)| { + for col in 0..width { + if cover.get(row * width + col).is_none_or(|c| *c <= 0.0) { continue; } + let (x, y) = ((x0 as usize + col) as f32, (y0 as usize + row) as f32); let mut acc = [0.0f32; 5]; let n = (r.ceil() as i32).clamp(1, LINE_SAMPLES); @@ -423,53 +693,92 @@ fn gather(op: Op, orig: &[f32], cover: &[f32], comps: usize, (x0, y0, w, h): (u3 } } Op::Warp { scale, seed, dir } => { - let off = |salt: u32| ((texel_noise(x, y, [0.0; 2], res, scale, seed ^ salt) - 0.5) * 3.0).clamp(-1.0, 1.0) * r; + let noise_offset = |salt: u32| ((texel_noise(x, y, [0.0; 2], res, scale, seed ^ salt) - 0.5) * WARP_NOISE_GAIN).clamp(-1.0, 1.0) * r; match dir { Some(d) => { - let t = off(0); + let t = noise_offset(0); sample(x + d[0] * t, y + d[1] * t, &mut acc); } - None => sample(x + off(0), y + off(0x5BD1_E995), &mut acc), + None => sample(x + noise_offset(0), y + noise_offset(WARP_Y_SALT), &mut acc), } } Op::Edge => { - let center = orig.get((row * wu + col) * comps..(row * wu + col + 1) * comps).unwrap_or(&[]); + let center = orig.get((row * width + col) * comps..(row * width + col + 1) * comps).unwrap_or(&[]); let at = |dx: f32, dy: f32| { - let mut a = [0.0f32; 5]; - sample(x + dx, y + dy, &mut a); - a + let mut read = [0.0f32; 5]; + sample(x + dx, y + dy, &mut read); + read }; - let (l, rt, u, d) = (at(-r, 0.0), at(r, 0.0), at(0.0, -r), at(0.0, r)); - // A side outside the UV island reads the texel itself: seams are not edges. - let val = |a: &[f32; 5], k: usize| if a[4] > 1e-6 { a[k] / a[4] } else { center.get(k).copied().unwrap_or(0.0) }; - let mag = |k: usize| (val(&rt, k) - val(&l, k)).hypot(val(&d, k) - val(&u, k)).min(1.0); - // Content stays premultiplied by its own coverage; masks are one value. - let cov = if comps == 4 { center.get(3).copied().unwrap_or(0.0) } else { 1.0 }; - for (k, a) in acc.iter_mut().enumerate().take(comps.min(3)) { - *a = mag(k) * cov; + let (left, right, up, down) = (at(-r, 0.0), at(r, 0.0), at(0.0, -r), at(0.0, r)); + + // A side outside the UV island reads the texel itself: seams are not edges + let component = |read: &[f32; 5], k: usize| { + if read[4] > MIN_READ_WEIGHT { read[k] / read[4] } else { center.get(k).copied().unwrap_or(0.0) } + }; + let magnitude = |k: usize| (component(&right, k) - component(&left, k)).hypot(component(&down, k) - component(&up, k)).min(1.0); + + // Content stays premultiplied by its own coverage; masks are one value + let coverage = if comps == 4 { center.get(3).copied().unwrap_or(0.0) } else { 1.0 }; + for (k, slot) in acc.iter_mut().enumerate().take(comps.min(3)) { + *slot = magnitude(k) * coverage; } if comps == 4 { - acc[3] = cov; + acc[3] = coverage; } acc[4] = 1.0; } Op::Slope { scale, seed } => { - let e = 0.01; - let hgt = |dx: f32, dy: f32| texel_noise(x, y, [dx, dy], res, scale, seed); - // Downhill; a flat spot keeps its value. - let d = Vec2::new(hgt(-e, 0.0) - hgt(e, 0.0), hgt(0.0, -e) - hgt(0.0, e)).try_normalize().unwrap_or(Vec2::ZERO); + let noise_height = |dx: f32, dy: f32| texel_noise(x, y, [dx, dy], res, scale, seed); + let probe = SLOPE_NOISE_PROBE; + + // Downhill; a flat spot keeps its value + let downhill = Vec2::new(noise_height(-probe, 0.0) - noise_height(probe, 0.0), noise_height(0.0, -probe) - noise_height(0.0, probe)); + let d = downhill.try_normalize().unwrap_or(Vec2::ZERO); for s in 0..=n { let t = s as f32 * step; sample(x + d.x * t, y + d.y * t, &mut acc); } } - Op::Mosaic => { + Op::Mosaic { alpha } => { let center = |v: f32| ((v / r).floor() + 0.5) * r - 0.5; sample(center(x), center(y), &mut acc); + if !alpha { + keep_coverage(&mut acc, comps, orig.get((row * width + col) * comps + 3)); + } } - Op::Blur(_) | Op::HighPass | Op::Bevel | Op::Glow(_) => {} + Op::Fxaa { alpha } => { + let center = orig.get((row * width + col) * comps..(row * width + col + 1) * comps).unwrap_or(&[]); + fxaa_texel((x, y), comps, center, &mut acc, &sample); + if !alpha { + keep_coverage(&mut acc, comps, center.get(3)); + } + } + Op::Mirror { mirror, block } => { + mirror_texel(&mirror, (x, y), (block, res), comps, orig.get((row * width + col) * comps + comps - 1), &mut acc, &sample) + } + Op::Transform { transform, affine, block } => transform_texel(&transform, affine, (x, y), (block, res), &mut acc, &sample), + Op::SourceWarp(warp) => warp_texel((&warp, &warp_directions), (x, y), (res, comps), (block_size, tile_size), &mut acc, (&sample, &input)), + Op::SourceSlopeBlur(slope) => slope_texel(&slope, (x, y), (res, comps), (block_size, tile_size), &mut acc, (&sample, &input)), + Op::HeightToNormal(filter) => { + let center = orig.get((row * width + col) * comps..(row * width + col + 1) * comps).unwrap_or(&[]); + height_to_normal_texel(&filter, (x, y), (res, center), &mut acc, &input); + } + Op::Kuwahara(kuwahara) => { + let radius = (kuwahara.radius.min(AnisotropicKuwahara::MAX_RADIUS) * res as f32 / FILTER_SIZE_RESOLUTION).max(MIN_FILTER_RADIUS); + kuwahara_texel(&kuwahara, (x, y), (radius, comps), &mut acc, (&sample, &input)); + } + Op::ColorMatch(_) + | Op::Blur(_) + | Op::HighPass { .. } + | Op::Bevel + | Op::Glow(_) + | Op::PreBlur + | Op::Halo + | Op::Shadow { .. } + | Op::Outline(_) + | Op::Distance => {} } - if acc[4] > 1e-6 + if acc[4] > MIN_READ_WEIGHT && let Some(px) = line.get_mut(col * comps..(col + 1) * comps) { for (slot, a) in px.iter_mut().zip(acc) { @@ -481,6 +790,445 @@ fn gather(op: Op, orig: &[f32], cover: &[f32], comps: usize, (x0, y0, w, h): (u3 data } +/// The linear colors a filter input gives over the tile-aligned texel region, row by row +fn input_colors( + inputs: &EvaluationInputs, + source: &Source, + (draw, channels, below): ((LayerId, usize), &[Channel], &Fields), + (left, top, width, height): (u32, u32, u32, u32), +) -> Vec<[f32; 3]> { + if width == 0 || height == 0 { + return Vec::new(); + } + + let mut colors = vec![[0.0; 3]; (width * height) as usize]; + let horizontal_tiles = left / TILE..(left + width).div_ceil(TILE); + colors.par_chunks_mut((TILE * width) as usize).enumerate().for_each(|(band, colors)| { + let tile_y = top / TILE + band as u32; + let band_top = tile_y * TILE; + for tile_x in horizontal_tiles.clone() { + let anchors = if matches!(source, Source::Anchor { .. }) { anchor_plan(inputs, draw, channels, tile_x, tile_y, Some(below)) } else { Vec::new() }; + let preview_tile = inputs.preview.and_then(|preview| preview.alpha.tile(tile_x, tile_y)); + + for (x, y, offset) in tile_texels(inputs.gbuf, tile_x, tile_y) { + if x < left || x - left >= width { + continue; + } + + let index = ((y - band_top) * width + (x - left)) as usize; + let Some(pixel) = colors.get_mut(index) else { continue }; + let mut texel = Texel::new(inputs, x, y, offset, stroke_at(preview_tile, offset)); + if !anchors.is_empty() { + texel.anchors_below(&anchors, draw); + } + + *pixel = texel.source(source, &Projection::default(), Sampling::default(), ChannelKind::Color); + } + } + }); + + colors +} + +/// Color Match's per-texel source or target colors (None: one color for the whole region) +type MatchColors = Option>; + +/// Color Match over premultiplied `data` (`comps` values a texel): each covered color moved from its source (the region's mean or its Input color) to its target (Target Color or its Image Input color), mixed in by `opacity` +fn color_match(data: &mut [f32], comps: usize, matcher: &ColorMatch, (sources, targets): (&MatchColors, &MatchColors), opacity: f32) { + if comps != 4 || opacity <= 0.0 { + return; + } + + let source_color = if matcher.source_mode == SourceColorMode::Average { mean_region_color(data, matcher.target_color) } else { matcher.source_color }; + let source_pixels = if matcher.source_mode == SourceColorMode::Input { sources.as_deref() } else { None }; + let target_pixels = if matcher.target_mode == TargetColorMode::ImageInput { targets.as_deref() } else { None }; + + if source_pixels.is_none() && target_pixels.is_none() { + let prepared = PreparedColorMatch::new(*matcher, source_color, matcher.target_color); + match_pixels(data, opacity, |_, color| prepared.apply(color)); + } else { + match_pixels(data, opacity, |index, color| { + let source = source_pixels.and_then(|pixels| pixels.get(index)).copied().unwrap_or(source_color); + let target = target_pixels.and_then(|pixels| pixels.get(index)).copied().unwrap_or(matcher.target_color); + matcher.apply(color, source, target) + }); + } +} + +fn match_pixels(data: &mut [f32], opacity: f32, remap: impl Fn(usize, [f32; 3]) -> [f32; 3] + Sync) { + data.par_chunks_mut(4).enumerate().for_each(|(index, pixel)| { + let [red, green, blue, alpha] = *pixel else { return }; + if alpha <= 0.0 || !alpha.is_finite() { + return; + } + + let moved = remap(index, [red, green, blue].map(|component| component / alpha)); + for (slot, value) in pixel.iter_mut().zip(moved) { + *slot += (value * alpha - *slot) * opacity; + } + }); +} + +/// The mean of a premultiplied color region, or the fallback when no texel is covered +fn mean_region_color(data: &[f32], fallback: [f32; 3]) -> [f32; 3] { + // Premultiplication weights the color by coverage + let (color_sum, coverage_sum) = data + .par_chunks(4) + .fold( + || ([0.0f64; 3], 0.0f64), + |(mut colors, mut coverage), pixel| { + if let [red, green, blue, alpha] = *pixel + && alpha > 0.0 + && alpha.is_finite() + { + for (sum, component) in colors.iter_mut().zip([red, green, blue]) { + *sum += f64::from(component); + } + coverage += f64::from(alpha); + } + + (colors, coverage) + }, + ) + .reduce( + || ([0.0; 3], 0.0), + |(left, left_coverage), (right, right_coverage)| ([left[0] + right[0], left[1] + right[1], left[2] + right[2]], left_coverage + right_coverage), + ); + + if coverage_sum > 0.0 { color_sum.map(|component| (component / coverage_sum) as f32) } else { fallback } +} + +/// Height To Normal at texel `(x, y)` into `acc`: the 3×3 Sobel normal of the heights `height` reads, laid over normal `center` unless it overwrites it +fn height_to_normal_texel( + filter: &HeightToNormal, + (x, y): (f32, f32), + (res, center): (u32, &[f32]), + acc: &mut [f32; 5], + height: &dyn Fn(f32, f32) -> Option, +) { + let (Some(own), [red, green, blue, cov]) = (height(x, y), center) else { return }; + if *cov <= 0.0 { + return; + } + + let at = |dx: f32, dy: f32| height(x + dx, y + dy).unwrap_or(own); + + // Sobel gradients over the kernel's weight sum + let gx = (at(1.0, -1.0) + 2.0 * at(1.0, 0.0) + at(1.0, 1.0) - at(-1.0, -1.0) - 2.0 * at(-1.0, 0.0) - at(-1.0, 1.0)) / 8.0; + let gy = (at(-1.0, 1.0) + 2.0 * at(0.0, 1.0) + at(1.0, 1.0) - at(-1.0, -1.0) - 2.0 * at(0.0, -1.0) - at(1.0, -1.0)) / 8.0; + let made = filter.normal([gx, gy], res).map(|v| v * 0.5 + 0.5); + let packed = if filter.overwrite { made } else { texturecraft_core::blend::rnm([red, green, blue].map(|v| v / cov), made) }; + for (slot, value) in acc.iter_mut().zip(packed) { + *slot = value * cov; + } + acc[3] = *cov; + acc[4] = 1.0; +} + +/// Gathered sample `acc` (premultiplied, then weight) recoloured over the texel's own coverage `own` (content only; a sample with no coverage leaves it) +fn keep_coverage(acc: &mut [f32; 5], comps: usize, own: Option<&f32>) { + let Some(&own) = own.filter(|_| comps == 4) else { return }; + if acc[3] <= MIN_READ_WEIGHT { + acc[4] = 0.0; + return; + } + + let scale = own * acc[4] / acc[3]; + for component in acc.iter_mut().take(3) { + *component *= scale; + } + acc[3] = own * acc[4]; +} + +/// Sample rows (and columns) on each side of the middle Anisotropic Kuwahara reads its ellipse with at most +const KUWAHARA_STEPS: i32 = 6; + +/// Below this, a structure tensor has no direction +const MIN_TENSOR: f32 = 1e-12; + +/// How fast a Kuwahara sample's gaussian weight falls with its squared distance across the ellipse (e^-2 at the rim) +const KUWAHARA_FALLOFF: f32 = 2.0; + +/// A spread of one in a sector, in 8-bit steps: what Anisotropic Kuwahara's sector weights are measured in +const KUWAHARA_SPREAD_SCALE: f32 = 255.0; + +/// Anisotropic Kuwahara at texel `(x, y)` (`radius` texels, `comps` components) into `acc`: an ellipse along the gray's direction, its sectors' means weighed by their calm +fn kuwahara_texel( + kuwahara: &AnisotropicKuwahara, + (x, y): (f32, f32), + (radius, comps): (f32, usize), + acc: &mut [f32; 5], + (sample, input): (Sample<'_>, Input<'_>), +) { + // A straight value at an offset; None off the UV island + let read = |fx: f32, fy: f32| -> Option<[f32; 4]> { + let mut sum = [0.0f32; 5]; + sample(fx, fy, &mut sum); + (sum[4] > MIN_READ_WEIGHT).then(|| std::array::from_fn(|k| if k < comps.min(4) { sum[k] / sum[4] } else { 0.0 })) + }; + let gray = |fx: f32, fy: f32| if kuwahara.custom_input { input(fx, fy) } else { read(fx, fy).map(|px| fxaa_luma(&px[..comps.min(4)])) }; + + // Structure tensor: the gray's gradients over a 3×3 grid spread by Tensor Smoothness, the middle weighing most + let spread = kuwahara.tensor_reach() * radius; + let (mut xx, mut xy, mut yy) = (0.0f32, 0.0f32, 0.0f32); + for gy in -1i32..=1 { + for gx in -1i32..=1 { + let (px, py) = (x + gx as f32 * spread, y + gy as f32 * spread); + let own = gray(px, py); + let at = |dx: f32, dy: f32| gray(px + dx, py + dy).or(own); + let (Some(left), Some(right), Some(up), Some(down)) = (at(-1.0, 0.0), at(1.0, 0.0), at(0.0, -1.0), at(0.0, 1.0)) else { continue }; + + // Central differences over two texels + let (dx, dy) = ((right - left) * 0.5, (down - up) * 0.5); + + // A 1-2-1 binomial kernel in each direction: the middle 4, the sides 2, the corners 1 + let weight = (4 >> (gx.abs() + gy.abs())) as f32; + xx += weight * dx * dx; + xy += weight * dx * dy; + yy += weight * dy * dy; + } + } + let root = ((xx - yy).powi(2) + 4.0 * xy * xy).sqrt(); + let clear = if xx + yy > MIN_TENSOR { root / (xx + yy) } else { 0.0 }; + + // Strokes run across the steepest change; Anisotropy Angle turns the ellipse counterclockwise on screen + let along = 0.5 * (2.0 * xy).atan2(xx - yy) + std::f32::consts::FRAC_PI_2 - kuwahara.angle.to_radians(); + let (sin, cos) = if along.is_finite() { along.sin_cos() } else { (0.0, 1.0) }; + let (major, minor) = kuwahara.axes(radius, if clear.is_finite() { clear } else { 0.0 }); + + // Each sector's weighted sum, squared sum and weight + let mut sums = [[0.0f32; 5]; AnisotropicKuwahara::SECTORS]; + let mut squares = [0.0f32; AnisotropicKuwahara::SECTORS]; + let steps = (major.ceil() as i32).clamp(1, KUWAHARA_STEPS); + let exponent = kuwahara.sector_exponent(); + let colors = comps.min(3); + for j in -steps..=steps { + for i in -steps..=steps { + let (u, v) = (i as f32 / steps as f32, j as f32 / steps as f32); + let distance = u * u + v * v; + if distance > 1.0 { + continue; + } + + let (ox, oy) = (u * major, v * minor); + let Some(px) = read(x + ox * cos - oy * sin, y + ox * sin + oy * cos) else { continue }; + let falloff = (-KUWAHARA_FALLOFF * distance).exp(); + let heading = v.atan2(u); + for (k, (sum, square)) in sums.iter_mut().zip(&mut squares).enumerate() { + // The center contributes to every sector while other weights taper at sector boundaries + let facing = (heading - k as f32 * std::f32::consts::TAU / AnisotropicKuwahara::SECTORS as f32).cos(); + let weight = if distance <= 0.0 { + falloff + } else if facing > 0.0 { + falloff * facing.powf(exponent) + } else { + continue; + }; + + for (slot, value) in sum.iter_mut().zip(&px) { + *slot += weight * value; + } + sum[4] += weight; + *square += weight * px.iter().take(colors).map(|value| value * value).sum::(); + } + } + } + + // Weight low-variance sectors more and use logarithms to avoid overflow + let sharpness = kuwahara.sharpness_exponent(); + let logs: [Option; AnisotropicKuwahara::SECTORS] = std::array::from_fn(|sector| { + let (sum, square) = (sums.get(sector)?, squares.get(sector)?); + (sum[4] > MIN_READ_WEIGHT).then(|| { + let mean = sum.iter().take(colors).map(|value| (value / sum[4]).powi(2)).sum::(); + let spread = (square / sum[4] - mean).max(0.0).sqrt(); + -sharpness * (1.0 + KUWAHARA_SPREAD_SCALE * spread).ln() + }) + }); + let Some(top) = logs.iter().flatten().copied().reduce(f32::max) else { return }; + let mut total = [0.0f32; 5]; + for (sum, log) in sums.iter().zip(&logs) { + let Some(log) = log else { continue }; + let weight = (log - top).exp(); + for (slot, value) in total.iter_mut().zip(sum.iter().take(4)) { + *slot += weight * value / sum[4]; + } + total[4] += weight; + } + *acc = total; +} + +/// Texels an FXAA edge search walks each way along an edge at most +const FXAA_SEARCH: i32 = 8; + +/// The least luma contrast around a texel FXAA smooths +const FXAA_EDGE_MIN: f32 = 0.0312; + +/// The least luma contrast around a texel FXAA smooths, as a share of its brightest neighbour +const FXAA_EDGE_RELATIVE: f32 = 0.125; + +/// How much a lone texel (subpixel aliasing) is blended into its neighbours at most +const FXAA_SUBPIXEL: f32 = 0.75; + +/// Luma of premultiplied texel components (a mask's value) +fn fxaa_luma(px: &[f32]) -> f32 { + match px { + [value] => *value, + [r, g, b, ..] => lum([*r, *g, *b]), + _ => 0.0, + } +} + +/// FXAA (the public luma-edge method) at texel `(x, y)` with components `center` into `acc`: read across its edge by how near the edge's end is +fn fxaa_texel((x, y): (f32, f32), comps: usize, center: &[f32], acc: &mut [f32; 5], sample: &dyn Fn(f32, f32, &mut [f32; 5])) { + let own = fxaa_luma(center); + + // Luma at an offset from the texel; off the UV island the texel's own, so seams are not edges + let luma = |dx: f32, dy: f32| { + let mut read = [0.0f32; 5]; + sample(x + dx, y + dy, &mut read); + if read[4] <= MIN_READ_WEIGHT { + return own; + } + + let mut px = [0.0f32; 4]; + for (slot, v) in px.iter_mut().zip(&read).take(comps.min(4)) { + *slot = v / read[4]; + } + fxaa_luma(&px[..comps.min(4)]) + }; + let (n, s, w, e) = (luma(0.0, -1.0), luma(0.0, 1.0), luma(-1.0, 0.0), luma(1.0, 0.0)); + let (hi, lo) = (own.max(n).max(s).max(w).max(e), own.min(n).min(s).min(w).min(e)); + let range = hi - lo; + if !range.is_finite() || range < FXAA_EDGE_MIN.max(hi * FXAA_EDGE_RELATIVE) { + return; + } + + let (nw, ne, sw, se) = (luma(-1.0, -1.0), luma(1.0, -1.0), luma(-1.0, 1.0), luma(1.0, 1.0)); + + // An edge running across (values changing down the rows) or down (values changing along them) + let across = 2.0 * (n - 2.0 * own + s).abs() + (nw - 2.0 * w + sw).abs() + (ne - 2.0 * e + se).abs(); + let down = 2.0 * (w - 2.0 * own + e).abs() + (nw - 2.0 * n + ne).abs() + (sw - 2.0 * s + se).abs(); + let horizontal = across >= down; + let (before, after) = if horizontal { (n, s) } else { (w, e) }; + let (sign, side) = if (before - own).abs() >= (after - own).abs() { (-1.0, before) } else { (1.0, after) }; + let (perp, along) = if horizontal { ([0.0, sign], [1.0, 0.0]) } else { ([sign, 0.0], [0.0, 1.0]) }; + + // Walk the edge's midline both ways until its luma leaves the edge's + let edge = 0.5 * (own + side); + let enough = 0.25 * (side - own).abs(); + let walk = |way: f32| { + let mut end = (FXAA_SEARCH as f32, 0.0); + for step in 1..=FXAA_SEARCH { + let t = step as f32 * way; + let delta = luma(perp[0] * 0.5 + along[0] * t, perp[1] * 0.5 + along[1] * t) - edge; + end = (step as f32, delta); + if delta.abs() >= enough { + break; + } + } + end + }; + let ((back, back_delta), (ahead, ahead_delta)) = (walk(-1.0), walk(1.0)); + let (nearest, delta) = if back < ahead { (back, back_delta) } else { (ahead, ahead_delta) }; + let edge_blend = if (delta < 0.0) != (own < edge) { 0.5 - nearest / (back + ahead) } else { 0.0 }; + + // A texel unlike all its neighbours blends in by its own contrast (sides weigh twice the corners) + let average = (2.0 * (n + s + w + e) + nw + ne + sw + se) / 12.0; + let contrast = ((average - own).abs() / range).clamp(0.0, 1.0); + let eased = crate::organic::smoothstep(0.0, 1.0, contrast); + let blend = edge_blend.max(eased * eased * FXAA_SUBPIXEL); + if blend > 0.0 { + sample(x + perp[0] * blend, y + perp[1] * blend, acc); + } +} + +/// Mirror `mirror` at texel `(x, y)` into `acc`: the texel it reads in its UV tile (`res` texels from its `block`'s top left), or white on a debug axis +fn mirror_texel( + mirror: &Mirror, + (x, y): (f32, f32), + (block, res): (u32, u32), + comps: usize, + alpha: Option<&f32>, + acc: &mut [f32; 5], + sample: &dyn Fn(f32, f32, &mut [f32; 5]), +) { + let (block, size) = (block.max(1) as f32, res.max(1) as f32); + let (origin_x, origin_y) = ((x / block).floor() * block, (y / block).floor() * block); + let (local_x, local_y) = (x - origin_x, y - origin_y); + if local_x >= size || local_y >= size { + return; + } + + let uv = [(local_x + 0.5) / size, (local_y + 0.5) / size]; + let line = (Mirror::DEBUG_HALF_WIDTH * size / FILTER_SIZE_RESOLUTION).max(MIN_FILTER_RADIUS) / size; + if mirror.debug && mirror.on_axis(uv, line) { + // Content stays premultiplied by its own coverage; masks are one value + let cover = if comps == 4 { alpha.copied().unwrap_or(0.0) } else { 1.0 }; + for slot in acc.iter_mut().take(comps) { + *slot = cover; + } + acc[4] = 1.0; + return; + } + + let [u, v] = mirror.source(uv); + + // Whole texels, so an even mirror copies texels exactly + let at = |origin: f32, along: f32| origin + (along * size - 0.5).round().clamp(0.0, size - 1.0); + sample(at(origin_x, u), at(origin_y, v), acc); +} + +/// Transform `transform` (whose read is `affine`) at texel `(x, y)` into `acc`: bilinear between the four texels round where it reads in its UV tile (`res` texels from its `block`'s top left), each wrapped round the tile; where it does not repeat, a read past the tile counts as empty +fn transform_texel( + transform: &TileTransform, + (columns, shift): ([[f32; 2]; 2], [f32; 2]), + (x, y): (f32, f32), + (block, res): (u32, u32), + acc: &mut [f32; 5], + sample: &dyn Fn(f32, f32, &mut [f32; 5]), +) { + let (block, size) = (block.max(1) as f32, res.max(1) as f32); + let (origin_x, origin_y) = ((x / block).floor() * block, (y / block).floor() * block); + let (local_x, local_y) = (x - origin_x, y - origin_y); + if local_x >= size || local_y >= size { + return; + } + + let uv = [(local_x + 0.5) / size, (local_y + 0.5) / size]; + + // Texel space of the tile, centres at whole numbers + let at = [0, 1].map(|axis| (columns[0][axis] * uv[0] + columns[1][axis] * uv[1] + shift[axis]) * size - 0.5); + if !at.iter().all(|a| a.is_finite()) { + return; + } + + let (base_x, base_y) = (at[0].floor(), at[1].floor()); + let (tx, ty) = (at[0] - base_x, at[1] - base_y); + let repeat = transform.repeat == RepeatMode::HorizontallyAndVertically; + let mut total = [0.0f32; 5]; + for (dx, dy, k) in [(0.0, 0.0, (1.0 - tx) * (1.0 - ty)), (1.0, 0.0, tx * (1.0 - ty)), (0.0, 1.0, (1.0 - tx) * ty), (1.0, 1.0, tx * ty)] { + if k <= 0.0 { + continue; + } + + let (cx, cy) = (base_x + dx, base_y + dy); + let inside = (0.0..size).contains(&cx) && (0.0..size).contains(&cy); + if !repeat && !inside { + // Empty: no value, full weight + total[4] += k; + continue; + } + + // One whole texel: the sample's own weights, so this matches its bilinear read + let mut one = [0.0f32; 5]; + sample(origin_x + cx.rem_euclid(size), origin_y + cy.rem_euclid(size), &mut one); + for (slot, value) in total.iter_mut().zip(one) { + *slot += value * k; + } + } + *acc = total; +} + /// Fixed-point scale of the blur. Integer running sums make a texel's result independent of /// the region it is computed in, so tiles composited in any grouping agree exactly. const FIX: f64 = (1u64 << 24) as f64; @@ -496,15 +1244,19 @@ fn lines_per_task(length: usize) -> usize { /// Three running-sum box blurs (≈ Gaussian) of a `width × height` image along its rows, then its columns, each in parallel. pub(crate) fn blur(data: &mut [f32], width: usize, height: usize, radius: usize) { + blur_with_wrap(data, width, height, radius, (false, false)); +} + +fn blur_with_wrap(data: &mut [f32], width: usize, height: usize, radius: usize, wrap: (bool, bool)) { // Bound samples before fixed-point accumulation const MAX_INPUT_MAGNITUDE: f32 = 1e6; let to_fixed = |value: &f32| if value.is_finite() { (f64::from(value.clamp(-MAX_INPUT_MAGNITUDE, MAX_INPUT_MAGNITUDE)) * FIX).round() as i64 } else { 0 }; let mut fixed: Vec = data.par_iter().with_min_len(MIN_PARALLEL_TEXELS).map(to_fixed).collect(); - blur_rows(&mut fixed, width, radius); + blur_rows(&mut fixed, width, radius, wrap.0); let mut columns = transpose(&fixed, width, height); - blur_rows(&mut columns, height, radius); + blur_rows(&mut columns, height, radius, wrap.1); transpose_into(&columns, height, width, &mut fixed); data.par_iter_mut().with_min_len(MIN_PARALLEL_TEXELS).zip(fixed).for_each(|(target, blurred)| *target = (blurred as f64 / FIX) as f32); @@ -514,7 +1266,7 @@ pub(crate) fn blur(data: &mut [f32], width: usize, height: usize, radius: usize) pub(crate) const BLUR_BOX_PASSES: usize = 3; /// Three box blurs of radius `r` along every row (`w` long) of `data`. -fn blur_rows(data: &mut [i64], w: usize, r: usize) { +fn blur_rows(data: &mut [i64], w: usize, r: usize, wrap: bool) { if w == 0 { return; } @@ -522,7 +1274,11 @@ fn blur_rows(data: &mut [i64], w: usize, r: usize) { data.par_chunks_mut(w).with_min_len(lines_per_task(w)).for_each(|row| { let mut scratch = vec![0i64; row.len()]; for _ in 0..BLUR_BOX_PASSES { - box_line(row, &mut scratch, r); + if wrap { + box_line_wrapped(row, &mut scratch, r); + } else { + box_line(row, &mut scratch, r); + } row.copy_from_slice(&scratch); } }); @@ -532,7 +1288,7 @@ fn blur_rows(data: &mut [i64], w: usize, r: usize) { fn box_line(src: &[i64], dst: &mut [i64], r: usize) { let n = (2 * r + 1) as i64; - // Rounded division of a window sum. + // Round the signed window mean consistently across axes let avg = |acc: i64| (2 * acc + n).div_euclid(2 * n); let mut acc: i64 = src.iter().take(r + 1).sum(); for (i, d) in dst.iter_mut().enumerate() { @@ -544,6 +1300,29 @@ fn box_line(src: &[i64], dst: &mut [i64], r: usize) { } } +/// One periodic box pass, including full periods when the kernel is wider than the line. +fn box_line_wrapped(source: &[i64], output: &mut [i64], radius: usize) { + let period = source.len(); + let taps = 2 * radius + 1; + let mut outgoing = (period - radius % period) % period; + let mut incoming = (outgoing + taps % period) % period; + let mut total = if taps >= period { source.iter().sum::() * (taps / period) as i64 } else { 0 }; + total += source[outgoing..].iter().chain(source).take(taps % period).sum::(); + + for value in output { + *value = (2 * total + taps as i64).div_euclid(2 * taps as i64); + total += source[incoming] - source[outgoing]; + outgoing += 1; + incoming += 1; + if outgoing == period { + outgoing = 0; + } + if incoming == period { + incoming = 0; + } + } +} + /// `src` (`w × h`, row-major) transposed to `h × w`. fn transpose(src: &[i64], w: usize, h: usize) -> Vec { let mut out = vec![0i64; src.len()]; @@ -575,18 +1354,83 @@ fn stroke_at(preview: Option<&[u16]>, o: usize) -> f32 { preview.and_then(|t| t.get(o)).map(|v| from_u16(*v)).unwrap_or(0.0) } -/// The full stack of tile (tx, ty) when `layer` reads anchor points (empty otherwise): evaluated -/// up to the layer, it records the anchors below it. -fn anchor_plan<'a>(inp: &Inputs<'a>, id: LayerId, channels: &[Channel], tx: u32, ty: u32, fields: Option<&'a Fields>) -> Vec> { - match inp.project.texture_set(inp.ts) { - Ok(set) if reads_anchor(inp.project, id) => plan(inp, &set.stack, channels, tx, ty, 0, fields), - _ => Vec::new(), +/// Plan the stack below a draw when it reads anchors or the material under it +fn below_plan<'a>( + inp: &EvaluationInputs<'a>, + draw: (LayerId, usize), + channels: &[Channel], + (tile_x, tile_y): (u32, u32), + fields: Option<&'a Fields>, + lit: bool, +) -> Vec> { + if !lit && !reads_stack(inp.project, draw.0) { + return Vec::new(); } + + let Ok(set) = inp.project.texture_set(inp.ts) else { return Vec::new() }; + let compare_effects = layer_mask(inp.project, draw.0).into_iter().flat_map(|mask| mask.effects.iter()); + let planned = compared_channels(compare_effects, channels.to_vec()); + plan_in(inp, &set.stack, &planned, tile_x, tile_y, 0, fields, DrawPlacement::default(), Some(draw)) } -/// Whether layer `id` (its own mask, or the content it draws) reads an anchor point. -pub(crate) fn reads_anchor(p: &Project, id: LayerId) -> bool { - p.layers.get(&id).is_some_and(Layer::reads_anchor) || p.content_layer(id).is_some_and(Layer::reads_anchor) +/// Plan the stack below a draw for its anchor and Compare inputs +fn anchor_plan<'a>( + inp: &EvaluationInputs<'a>, + draw: (LayerId, usize), + channels: &[Channel], + tile_x: u32, + tile_y: u32, + fields: Option<&'a Fields>, +) -> Vec> { + below_plan(inp, draw, channels, (tile_x, tile_y), fields, false) +} + +/// `channels` with every channel the Compare effects among `effects` compare added once +fn compared_channels<'e>(effects: impl IntoIterator, mut channels: Vec) -> Vec { + for effect in effects { + if let EffectKind::Compare { channel, .. } = effect.kind + && !channels.contains(&channel) + { + channels.push(channel); + } + } + channels +} + +/// Include material channels that masks read even when the set no longer exports them. +fn evaluation_channels(inp: &Inputs, mut channels: Vec) -> Vec { + fn include_masks(project: &Project, layers: &[LayerId], depth: usize, channels: &mut Vec) { + if depth > texturecraft_core::project::MAX_DEPTH { + return; + } + + for &id in layers { + if let Some(mask) = layer_mask(project, id).filter(|mask| mask.enabled) { + for effect in mask.effects.iter().filter(|effect| effect.visible && effect.kind.reads_stack()) { + if let EffectKind::Compare { channel, .. } = effect.kind + && !channels.contains(&channel) + { + channels.push(channel); + } + } + } + + if let Some(layer) = project.content_layer(id).filter(|layer| !layer.children().is_empty()) { + include_masks(project, layer.children(), depth + 1, channels); + } + } + } + + if let Ok(set) = inp.project.texture_set(inp.ts) { + include_masks(inp.project, &set.stack, 0, &mut channels); + } + + channels +} + +/// Whether layer `id` (its own mask, or the content it draws) reads the stack below it: an anchor point, or a compare mask's layer sides +pub(crate) fn reads_stack(p: &Project, id: LayerId) -> bool { + p.layers.get(&id).is_some_and(Layer::reads_stack) || p.content_layer(id).is_some_and(Layer::reads_stack) } /// The mask layer `id` draws with: its own, or an instance source's. @@ -596,14 +1440,15 @@ fn layer_mask(p: &Project, id: LayerId) -> Option<&Mask> { /// Layers of `list` in drawing order (bottom → top, folder and instanced folder contents after /// their folder). -fn draw_order(p: &Project, list: &[LayerId], depth: usize, out: &mut Vec) { +fn draw_order(inp: &EvaluationInputs, list: &[LayerId], depth: usize, place: DrawPlacement, out: &mut Vec<(LayerId, DrawPlacement)>) { if depth > texturecraft_core::project::MAX_DEPTH { return; } + for id in list { - out.push(*id); - if let Some(l) = p.content_layer(*id) { - draw_order(p, l.children(), depth + 1, out); + out.push((*id, place)); + if let Some(layer) = inp.project.content_layer(*id).filter(|layer| !layer.children().is_empty()) { + draw_order(inp, layer.children(), depth + 1, place.children(inp, *id, layer), out); } } } @@ -616,36 +1461,51 @@ enum Job<'a> { } /// A layer's mask or content channel after every neighbourhood filter of its stack, over `tiles`. -fn field(inp: &Inputs, channels: &[Channel], below: &Fields, id: LayerId, job: Job, tiles: &[(u32, u32)]) -> Option { - let effects = match job { - Job::Mask(mask) => &mask.effects, - Job::Content(_) => &inp.project.content_layer(id)?.content_effects, +fn field( + inp: &EvaluationInputs, + channels: &[Channel], + below: &Fields, + (id, place): (LayerId, DrawPlacement), + job: Job, + tiles: &[(u32, u32)], + (reader_margin, reader_wrap): (u32, bool), +) -> Option { + let (effects, channel) = match job { + Job::Mask(mask) => (&mask.effects, None), + Job::Content(channel) => (&inp.project.content_layer(id)?.content_effects, Some(channel)), }; - let filters: Vec<(usize, f32, Op)> = neighbourhood_filters(effects, inp.tile_res()).collect(); - let longest_side = inp.gbuf.width.max(inp.gbuf.height); + let filters: Vec<(usize, f32, Op)> = neighbourhood_filters(effects, inp.tile_res(), channel).collect(); // Each filter's region also holds what every filter above it reads around the tiles - let mut margins: Vec = filters.iter().map(|&(_, radius, op)| filter_extent(radius, op, longest_side).1.div_ceil(TILE)).collect(); + let mut margins: Vec = filters.iter().map(|&(_, radius, op)| filter_extent(radius, op, inp).1.div_ceil(TILE)).collect(); for index in (0..margins.len().saturating_sub(1)).rev() { - margins[index] += margins[index + 1]; + margins[index] = margins[index].saturating_add(margins[index + 1]); + } + + // A wrapped dependency expands all lower stages across any crossed axis + let own_wraps: Vec = filters.iter().map(|filter| wraps(effects, filter.0)).collect(); + let mut wrapping = own_wraps.clone(); + for index in (0..wrapping.len().saturating_sub(1)).rev() { + wrapping[index] |= wrapping[index + 1]; } let mut previous: Option<(usize, Field)> = None; let mut anchor_stages = Vec::new(); - for (&filter, &margin) in filters.iter().zip(&margins) { - let region = region_around(inp, tiles, margin)?; + for (((&filter, &margin), &wrap), &own_wrap) in filters.iter().zip(&margins).zip(&wrapping).zip(&own_wraps) { + let region = region_around(inp, tiles, reader_margin.saturating_add(margin), reader_wrap || wrap)?; let start = previous.as_ref().map(|(index, field)| (*index, field)); - let filtered = filter_region(inp, channels, below, id, job, effects, filter, region, start)?; + let filtered = filter_region(inp, channels, below, (id, place), job, effects, filter, own_wrap, region, start)?; // Preserve only stages with anchors before the next filter overwrites their value - if let Some((previous_index, previous_field)) = previous.take() - && matches!(job, Job::Mask(_)) - { - let mut visible = effects.iter().filter(|effect| effect.visible).skip(previous_index); - let previous_effect = visible.next(); - let records_anchor = visible.take(filter.0 - previous_index - 1).any(|effect| matches!(effect.kind, EffectKind::Anchor)); - if records_anchor && let Some(previous_effect) = previous_effect { - anchor_stages.push((previous_effect.id, previous_field)); + if let Some((previous_index, previous_field)) = previous.take() { + let records_anchor = effects + .iter() + .filter(|effect| effect.visible) + .skip(previous_index + 1) + .take(filter.0 - previous_index - 1) + .any(|effect| matches!(effect.kind, EffectKind::Anchor)); + if records_anchor { + anchor_stages.push((previous_index, previous_field)); } } @@ -658,47 +1518,127 @@ fn field(inp: &Inputs, channels: &[Channel], below: &Fields, id: LayerId, job: J }) } -/// The tile-aligned texel region `(x0, y0, w, h)` around `tiles` plus `margin` tiles, clipped to the set. -fn region_around(inp: &Inputs, tiles: &[(u32, u32)], margin: u32) -> Option<(u32, u32, u32, u32)> { +/// The tile-aligned texel region `(x0, y0, w, h)` around `tiles` plus `margin` tiles, clipped to the set; with `wrap`, an axis the margin crosses an edge of spans the whole set (the filter reads the far side there) +fn region_around(inp: &Inputs, tiles: &[(u32, u32)], margin: u32, wrap: bool) -> Option<(u32, u32, u32, u32)> { let (first_x, first_y) = tiles.iter().fold((u32::MAX, u32::MAX), |(min_x, min_y), tile| (min_x.min(tile.0), min_y.min(tile.1))); let (last_x, last_y) = tiles.iter().fold((0, 0), |(max_x, max_y), tile| (max_x.max(tile.0), max_y.max(tile.1))); - let (x0, y0) = (first_x.saturating_sub(margin) * TILE, first_y.saturating_sub(margin) * TILE); - let (x1, y1) = (((last_x + 1 + margin) * TILE).min(inp.gbuf.width), ((last_y + 1 + margin) * TILE).min(inp.gbuf.height)); + let axis = |first: u32, last: u32, size: u32| { + let end = last.saturating_add(1).saturating_add(margin).saturating_mul(TILE); + if wrap && (first < margin || end > size) { + return (0, size); + } + + (first.saturating_sub(margin).saturating_mul(TILE), end.min(size)) + }; + let ((x0, x1), (y0, y1)) = (axis(first_x, last_x, inp.gbuf.width), axis(first_y, last_y, inp.gbuf.height)); let (w, h) = (x1.saturating_sub(x0), y1.saturating_sub(y0)); (w > 0 && h > 0).then_some((x0, y0, w, h)) } -/// A neighbourhood filter's radius in whole texels and how many texels around a texel it reads. -fn filter_extent(radius: f32, op: Op, longest_side: u32) -> (u32, u32) { +/// Whether the neighbourhood filter at `index` among the visible effects reads past the set's edges from the far side +fn wraps(effects: &[Effect], index: usize) -> bool { + matches!( + effects.iter().filter(|effect| effect.visible).nth(index).map(|effect| &effect.kind), + Some(EffectKind::Filter( + Filter::Blur { wrap: true, .. } + | Filter::Bevel { wrap: true, .. } + | Filter::DistanceBevel(Bevel { wrap: true, .. }) + | Filter::BevelSmooth(BevelSmooth { wrap: true, .. }) + )) + ) +} + +/// `data` (`w` × `h` texels of `comps` values) with `pad_x` and `pad_y` texels added around it, read from the opposite side +fn wrap_pad(data: &[f32], comps: usize, (w, h): (usize, usize), (pad_x, pad_y): (usize, usize)) -> Vec { + let (padded_w, padded_h) = (w + 2 * pad_x, h + 2 * pad_y); + let mut out = vec![0.0f32; padded_w * padded_h * comps]; + out.par_chunks_mut(padded_w * comps).enumerate().for_each(|(y, row)| { + let source_y = (y + h * pad_y.div_ceil(h.max(1)) - pad_y) % h.max(1); + for (x, pixel) in row.chunks_mut(comps).enumerate() { + let source_x = (x + w * pad_x.div_ceil(w.max(1)) - pad_x) % w.max(1); + let at = (source_y * w + source_x) * comps; + if let Some(source) = data.get(at..at + comps) { + pixel.copy_from_slice(source); + } + } + }); + out +} + +/// The `w` × `h` texels inside [`wrap_pad`]'s border +fn unpad(data: &[f32], comps: usize, (w, h): (usize, usize), (pad_x, pad_y): (usize, usize)) -> Vec { + let padded_w = w + 2 * pad_x; + (pad_y..pad_y + h).flat_map(|y| data.get((y * padded_w + pad_x) * comps..(y * padded_w + pad_x + w) * comps).unwrap_or_default()).copied().collect() +} + +/// A neighbourhood filter's radius in whole texels and how many texels around a texel it reads +fn filter_extent(radius: f32, op: Op, inputs: &Inputs) -> (u32, u32) { + let longest_side = inputs.gbuf.width.max(inputs.gbuf.height); // Clamped so a hostile radius can't overflow the region arithmetic let radius_texels = radius.round().clamp(1.0, longest_side as f32) as u32; // Three box passes reach three radii; the gathering filters one radius plus a bilinear texel let reach = if is_box_blur(op) { 3 * radius_texels } else { radius_texels + 1 }; - (radius_texels, reach) + + // A shadow also reads the shapes it was moved from + let moved = match op { + Op::Shadow { offset: [dx, dy] } => dx.unsigned_abs().max(dy.unsigned_abs()).min(longest_side), + _ => 0, + }; + + // Repeating a sampled source can read the opposite end of the output's UV tile + let tiled_source = match op { + Op::SourceWarp(warp) => Some(warp.source), + Op::SourceSlopeBlur(slope) => Some(slope.source), + _ => None, + }; + let source_reach = if tiled_source.is_some_and(|source| source.mode != WarpSourceMode::DefaultNoise && source.tiling_factor() != 1.0) { + inputs.tile_grid().map_or(longest_side, |_| inputs.tile_res()) + } else { + 0 + }; + + (radius_texels, (reach + moved).max(source_reach)) } -/// Whether neighbourhood filter `op` is computed from box blurs (the others gather samples). +/// Whether neighbourhood filter `op` is computed from box blurs (the others gather samples) fn is_box_blur(op: Op) -> bool { - matches!(op, Op::Blur(_) | Op::HighPass | Op::Bevel | Op::Glow(_)) + matches!(op, Op::Blur(_) | Op::HighPass { .. } | Op::Bevel | Op::Glow(_) | Op::PreBlur | Op::Halo | Op::Shadow { .. } | Op::Outline(_) | Op::Distance) } -/// The stack up to and including neighbourhood filter `filter` over texel `region`, continued from `start` (the filter below's field) when given. +/// The stack up to and including neighbourhood filter `filter` over texel `region`, continued from `start` (the filter below's field) when given; `wrap` when the filter reads past the set's edges from the far side #[allow(clippy::too_many_arguments)] fn filter_region( - inputs: &Inputs, + inputs: &EvaluationInputs, channels: &[Channel], below: &Fields, - id: LayerId, + (id, place): (LayerId, DrawPlacement), job: Job, effects: &[Effect], (index, radius, op): (usize, f32, Op), + wrap: bool, (region_x, region_y, width, height): (u32, u32, u32, u32), start: Option<(usize, &Field)>, ) -> Option { + let channel = match job { + Job::Mask(_) => None, + Job::Content(channel) => Some(channel), + }; + let filter_effect = effects.iter().filter(|effect| effect.visible).nth(index); - let opacity = filter_effect.map(|effect| effect.opacity.clamp(0.0, 1.0)).unwrap_or(1.0); - let (radius_texels, _) = filter_extent(radius, op, inputs.gbuf.width.max(inputs.gbuf.height)); + let filter = filter_effect.and_then(|effect| match &effect.kind { + EffectKind::Filter(filter) => Some(filter), + _ => None, + }); + let opacity = filter_effect.map(|effect| effect.applied_blend(channel).opacity.clamp(0.0, 1.0)).unwrap_or(1.0); + + // Height To Normal makes the Normal only (and reads the layer's Height as its gray); other channels pass + let heights = matches!(op, Op::HeightToNormal(_)) && channel == Some(Channel::Normal); + let opacity = if matches!(op, Op::HeightToNormal(_)) && !heights { 0.0 } else { opacity }; + + // Color Match moves colors only; other channels pass + let opacity = if matches!(op, Op::ColorMatch(_)) && channel.map(Channel::kind) != Some(ChannelKind::Color) { 0.0 } else { opacity }; + let (radius_texels, reach) = filter_extent(radius, op, inputs); // Generator stages keep their ramp beside the mask stack below let generator = match (job, filter_effect.map(|effect| (&effect.kind, effect.blend))) { @@ -711,21 +1651,44 @@ fn filter_region( Job::Content(_) => 4, }; - // Evaluate the stack up to the filter, tile by tile (content premultiplied by coverage) + // The gray the filter's image input reads (its first; the filters that read one have one) + let input = filter_effect.zip(filter).and_then(|(effect, filter)| { + // Color Match reads each input as linear color separately + if matches!(filter, Filter::ColorMatch(_)) { + return None; + } + + ImageInput::of(filter).first().map(|input| effect.input(input)) + }); + + let lit_prefix = + channel == Some(Channel::BaseColor) && effects.iter().filter(|effect| effect.visible).take(index).any(|effect| lights_material(&effect.kind)); + + // Evaluate the stack up to the filter, tile by tile (content premultiplied by coverage), and its image input let (region_right, region_bottom) = (region_x + width, region_y + height); - let region_tiles: Vec<(u32, u32)> = - (region_y / TILE..region_bottom.div_ceil(TILE)).flat_map(|y| (region_x / TILE..region_right.div_ceil(TILE)).map(move |x| (x, y))).collect(); - let parts: Vec> = region_tiles - .par_iter() - .map(|&(tile_x, tile_y)| { - let anchor_nodes = anchor_plan(inputs, id, channels, tile_x, tile_y, Some(below)); + let texel_count = width as usize * height as usize; + let mut stack_values = vec![0.0f32; texel_count * components]; + let mut cover = vec![0.0f32; texel_count]; + let band = TILE as usize * width as usize; + + let sample_band = |row: usize, (values, coverage): (&mut [f32], &mut [f32]), grays: &mut [f32]| { + let tile_y = region_y / TILE + row as u32; + for tile_x in region_x / TILE..region_right.div_ceil(TILE) { + let draw = (id, place.instance); + let lit_layer = + if lit_prefix { plan_node(inputs, id, channels, tile_x, tile_y, 0, Some(below), false, place, None).filter(|node| node.lights) } else { None }; + let anchor_nodes = below_plan(inputs, draw, channels, (tile_x, tile_y), Some(below), lit_layer.is_some()); let preview_tile = inputs.preview.and_then(|preview| preview.alpha.tile(tile_x, tile_y)); + let height_nodes = if heights { plan_in(inputs, &[id], &[Channel::Height], tile_x, tile_y, 0, Some(below), place, None) } else { Vec::new() }; let mut mask = None; let mut nodes = Vec::new(); let mut generator_sizes = None; match job { Job::Mask(layer_mask) => { - let Some(mut mask_stack) = mask_plan(inputs, id, layer_mask, tile_x, tile_y, None) else { return Vec::new() }; + // The layer's own filtered content, for a compare of it (this mask's field is not built yet) + let Some(mut mask_stack) = mask_plan(inputs, id, layer_mask, tile_x, tile_y, Some(below), place) else { + continue; + }; generator_sizes = mask_stack.effects.get(index).and_then(|effect| effect.curvature_sizes.clone()); mask_stack.effects.truncate(index); @@ -733,55 +1696,90 @@ fn filter_region( mask = Some(mask_stack); } Job::Content(channel) => { - nodes = plan(inputs, &[id], &[channel], tile_x, tile_y, 0, Some(below)); + nodes = plan_in(inputs, &[id], &[channel], tile_x, tile_y, 0, Some(below), place, None); if let Some(channel_plan) = nodes.first_mut().and_then(|node| node.chans.first_mut()) { channel_plan.effects.truncate(index); channel_plan.start = start; } } } - tile_texels(inputs.gbuf, tile_x, tile_y) - .map(|(x, y, offset)| { - let mut texel = Texel::new(inputs, x, y, offset, stroke_at(preview_tile, offset)); - if !anchor_nodes.is_empty() { - texel.anchors_below(&anchor_nodes, id); + for (x, y, offset) in tile_texels(inputs.gbuf, tile_x, tile_y) { + let mut texel = Texel::new(inputs, x, y, offset, stroke_at(preview_tile, offset)); + if !anchor_nodes.is_empty() { + texel.anchors_below(&anchor_nodes, (id, place.instance)); + } + + if let Some(layer) = &lit_layer { + texel.light(layer); + } + + let value = match (&mask, nodes.first()) { + (Some(mask_stack), _) => { + let ramp = generator.map_or(0.0, |(generator, _)| texel.generator_ramp(generator, generator_sizes.as_deref())); + [texel.mask(mask_stack), ramp, 0.0, 0.0] } + (None, Some(node)) => match node.chans.first().and_then(|channel_plan| texel.content(&node.content, channel_plan)) { + Some((color, coverage)) => [color[0] * coverage, color[1] * coverage, color[2] * coverage, coverage], + None => [0.0; 4], + }, + (None, None) => [0.0; 4], + }; + let offset_in_band = ((y % TILE) * width + (x - region_x)) as usize; + if let Some(gray) = grays.get_mut(offset_in_band) { + *gray = match height_nodes.first() { + // Coverage brings signed height down to zero at the layer's edge + Some(node) => { + let mut height = Texel::new(inputs, x, y, offset, stroke_at(preview_tile, offset)); + if !anchor_nodes.is_empty() { + height.anchors_below(&anchor_nodes, draw); + } - let value = match (&mask, nodes.first()) { - (Some(mask_stack), _) => { - let ramp = generator.map_or(0.0, |(generator, _)| texel.generator_ramp(generator, generator_sizes.as_deref())); - [texel.mask(mask_stack), ramp, 0.0, 0.0] + node.chans.first().and_then(|channel| height.content(&node.content, channel)).map_or(0.0, |(value, coverage)| value[0] * coverage) } - (None, Some(node)) => match node.chans.first().and_then(|channel_plan| texel.content(&node.content, channel_plan)) { - Some((color, coverage)) => [color[0] * coverage, color[1] * coverage, color[2] * coverage, coverage], - None => [0.0; 4], - }, - (None, None) => [0.0; 4], + None => input + .as_ref() + .map_or(1.0, |source| texel.source(source, &Projection::default(), Sampling::default(), ChannelKind::Scalar)[0]) + .clamp(0.0, 1.0), }; - (x, y, value) - }) - .collect() - }) - .collect(); + } - // Scatter into the region, a row of tiles at a time (the region is tile aligned) - let texel_count = (width * height) as usize; - let mut stack_values = vec![0.0f32; texel_count * components]; - let mut cover = vec![0.0f32; texel_count]; - let row_tiles = (region_right.div_ceil(TILE) - region_x / TILE).max(1) as usize; - let band = (TILE * width) as usize; - stack_values.par_chunks_mut(band * components).zip(cover.par_chunks_mut(band)).zip(parts.par_chunks(row_tiles)).for_each(|((stack_values, cover), row)| { - for &(x, y, value) in row.iter().flatten() { - let texel = (((y - region_y) % TILE) * width + (x - region_x)) as usize; - if let (Some(covered), Some(pixel)) = (cover.get_mut(texel), stack_values.get_mut(texel * components..(texel + 1) * components)) { - *covered = 1.0; - pixel.copy_from_slice(&value[..components]); + coverage[offset_in_band] = 1.0; + values[offset_in_band * components..(offset_in_band + 1) * components].copy_from_slice(&value[..components]); } } - }); + }; + let bands = stack_values.par_chunks_mut(band * components).zip(cover.par_chunks_mut(band)).enumerate(); + let mut grays = Vec::new(); + if heights || input.is_some() { + grays.resize(texel_count, 0.0); + bands.zip(grays.par_chunks_mut(band)).for_each(|((row, values), gray)| sample_band(row, values, gray)); + } else { + bands.for_each(|(row, values)| sample_band(row, values, &mut [])); + } - // Release tile scatter data before allocating filter buffers - drop(parts); + // Color Match is independent of UV tile scale and can transform its input in place + if let Op::ColorMatch(mut matcher) = op { + if let Some(effect) = filter_effect.filter(|_| opacity > 0.0) { + let read = |enabled: bool, input: ImageInput, uniform: &mut [f32; 3]| { + if !enabled { + return None; + } + + match effect.inputs.get(input.id) { + None => *uniform = [input.default; 3], + Some(Source::Uniform(color)) => *uniform = *color, + Some(source) => return Some(input_colors(inputs, source, ((id, place.instance), channels, below), (region_x, region_y, width, height))), + } + None + }; + let sources = read(matcher.source_mode == SourceColorMode::Input, ImageInput::SOURCE_INPUT, &mut matcher.source_color); + let targets = read(matcher.target_mode == TargetColorMode::ImageInput, ImageInput::TARGET_INPUT, &mut matcher.target_color); + color_match(&mut stack_values, components, &matcher, (&sources, &targets), opacity); + } + + unpremultiply(&mut stack_values, components); + return Some(Field { x0: region_x, y0: region_y, w: width, h: height, comps: components, data: stack_values, anchor_stages: Vec::new() }); + } // High pass centers on the channel's middle value (0 for signed channels like height) let middle = match job { @@ -789,7 +1787,26 @@ fn filter_region( _ => 0.5, }; + // Filter High Pass in its working space and preserve color when only coverage changes + let (space, highpass_alpha) = match (op, job) { + (Op::HighPass { space, alpha }, Job::Content(channel)) if components == 4 => { + (if channel.kind() == ChannelKind::Color { space } else { HighpassSpace::Working }, alpha) + } + _ => (HighpassSpace::Working, false), + }; + let covered = highpass_alpha.then(|| stack_values.clone()); + recode(&mut stack_values, components, |rgb| space.encode(rgb)); + + // A periodic box reads the original line directly on each pass + let wrap_axes = (wrap && region_x == 0 && width == inputs.gbuf.width, wrap && region_y == 0 && height == inputs.gbuf.height); + let pad_x = if matches!(op, Op::Distance) && wrap_axes.0 { reach.min(width) } else { 0 }; + let pad_y = if matches!(op, Op::Distance) && wrap_axes.1 { reach.min(height) } else { 0 }; + // A smaller UV tile has fewer texels per UV unit, so its filters reach fewer texels + let (block_size, tiled) = match inputs.tile_grid() { + Some(_) => ([inputs.tile_res(); 2], true), + None => ([inputs.gbuf.width, inputs.gbuf.height], false), + }; let filtered = |scale: f32| -> Vec { let tile_resolution = ((inputs.tile_res() as f32 * scale).round() as u32).max(1); if let Some((generator, blend)) = generator { @@ -797,47 +1814,91 @@ fn filter_region( return generator_region(generator, blend, opacity, &stack_values, &cover, (region_x, region_y, width, height), (tile_resolution, texture_set)); } - let scaled_radius = neighbourhood_filters(effects, tile_resolution) - .find(|filter| filter.0 == index) - .map_or(radius_texels, |filter| filter.1.round().clamp(1.0, radius_texels as f32) as u32); + let scaled = neighbourhood_filters(effects, tile_resolution, channel).find(|filter| filter.0 == index); + let scaled_radius = scaled.map_or(radius_texels, |filter| filter.1.round().clamp(1.0, radius_texels as f32) as u32); if !is_box_blur(op) { - return gather(op, &stack_values, &cover, components, (region_x, region_y, width, height), scaled_radius as f32, tile_resolution, opacity); + let tile_size = if tiled { [tile_resolution; 2] } else { block_size }; + return gather( + op, + (&stack_values, &cover, &grays), + components, + (region_x, region_y, width, height), + scaled_radius as f32, + (tile_resolution, block_size, tile_size), + opacity, + ); } - // Weighted so uncovered texels don't bleed in - let (columns, rows, blur_radius) = (width as usize, height as usize, scaled_radius as usize); - let mut weights = cover.clone(); - blur(&mut weights, columns, rows, blur_radius); - let mut filtered_values = stack_values.clone(); + // A distance transform needs samples from the opposite edge + let pad = (pad_x as usize, pad_y as usize); + let unpadded = (width as usize, height as usize); + let (stack_values, cover, grays) = if pad == (0, 0) { + (Cow::Borrowed(&stack_values), Cow::Borrowed(&cover), Cow::Borrowed(&grays)) + } else { + let padded = |values: &[f32], components: usize| Cow::Owned(wrap_pad(values, components, unpadded, pad)); + (padded(&stack_values, components), padded(&cover, 1), if grays.is_empty() { Cow::Borrowed(&grays) } else { padded(&grays, 1) }) + }; + let (columns, rows, blur_radius) = (unpadded.0 + 2 * pad.0, unpadded.1 + 2 * pad.1, scaled_radius as usize); + if let (Some((_, _, scaled_op @ (Op::Halo | Op::Shadow { .. }))), Some(filter)) = (scaled, filter) { + let kind = channel.map_or(ChannelKind::Scalar, Channel::kind); + let mut lit_values = stack_values.to_vec(); + halo(&mut lit_values, &cover, components, (columns, rows, blur_radius), (scaled_op, filter, kind), opacity); + return if pad == (0, 0) { lit_values } else { unpad(&lit_values, components, unpadded, pad) }; + } + + if let (Some((_, _, Op::Distance)), Some(filter)) = (scaled, filter) { + let mut distance_values = stack_values.to_vec(); + distance_filter(&mut distance_values, (&cover, &grays), components, (columns, rows), filter, tile_resolution, opacity); + return if pad == (0, 0) { distance_values } else { unpad(&distance_values, components, unpadded, pad) }; + } + + if let Some((_, _, Op::Outline(outline))) = scaled { + let mut outline_values = stack_values.to_vec(); + mask_outline(&mut outline_values, &cover, components, (columns, rows, blur_radius), &outline, opacity); + return if pad == (0, 0) { outline_values } else { unpad(&outline_values, components, unpadded, pad) }; + } + + // A pre-blur takes the blur whole; the effect's opacity mixes its mapped result below + let blurred_opacity = if matches!(op, Op::PreBlur) { 1.0 } else { opacity }; + let mut weights = cover.to_vec(); + blur_with_wrap(&mut weights, columns, rows, blur_radius, wrap_axes); + let mut filtered_values = stack_values.to_vec(); for component in 0..components { let mut sums: Vec = stack_values.par_chunks(components).map(|pixel| pixel.get(component).copied().unwrap_or(0.0)).collect(); - blur(&mut sums, columns, rows, blur_radius); + blur_with_wrap(&mut sums, columns, rows, blur_radius, wrap_axes); filtered_values.par_chunks_mut(components).zip(sums.par_iter()).zip(weights.par_iter()).for_each(|((pixel, sum), weight)| { // Content is premultiplied, so the middle value is too (coverage itself is kept) let coverage = if components == 4 { pixel.get(3).copied().unwrap_or(0.0) } else { 1.0 }; - if *weight > MIN_COVERAGE_WEIGHT + if *weight > MIN_READ_WEIGHT && let Some(slot) = pixel.get_mut(component) { let (original, blurred) = (*slot, sum / weight); let result = match op { Op::Blur(Some(amount)) => original + amount * (original - blurred), - Op::HighPass if component < 3 => original - blurred + middle * coverage, + Op::HighPass { .. } if component < 3 => original - blurred + middle * coverage, + Op::HighPass { alpha: true, .. } => (original - blurred + 0.5).clamp(0.0, 1.0), // Away from 0 by at most the value itself: 0 at the edge, full inside Op::Bevel if component < 3 => original.signum() * original.abs().min((2.0 * blurred * original.signum() - original.abs()).max(0.0)), Op::Glow(amount) if component < 3 => original + amount * blurred, - Op::HighPass | Op::Bevel | Op::Glow(_) => original, + Op::HighPass { .. } | Op::Bevel | Op::Glow(_) => original, _ => blurred, }; - *slot = original + (result - original) * opacity; + *slot = original + (result - original) * blurred_opacity; } }); } - filtered_values + if matches!(op, Op::PreBlur) + && let Some(filter) = filter + { + let kind = channel.map_or(ChannelKind::Scalar, Channel::kind); + map_blurred(&mut filtered_values, &stack_values, components, filter, inputs.gradient(filter).as_deref(), kind, opacity); + } + if pad == (0, 0) { filtered_values } else { unpad(&filtered_values, components, unpadded, pad) } }; // Each block keeps the result at its tile's scale (blocks are TILE aligned) - let scales = inputs.project.texture_set(inputs.ts).map(TextureSet::block_scales).unwrap_or_default(); + let scales = &inputs.block_scales; let mut levels: Vec = (region_y..region_bottom) .step_by(TILE as usize) .flat_map(|y| (region_x..region_right).step_by(TILE as usize).map(move |x| (x, y))) @@ -862,6 +1923,11 @@ fn filter_region( }); } + // Laid on the new coverage first, so the decode divides by the alpha the colours now carry + if let Some(before) = covered { + recover(&mut result, &before, middle); + } + recode(&mut result, field_components, |rgb| space.decode(rgb)); unpremultiply(&mut result, field_components); Some(Field { x0: region_x, y0: region_y, w: width, h: height, comps: field_components, data: result, anchor_stages: Vec::new() }) } @@ -892,7 +1958,7 @@ fn generator_region( let mut sums: Vec = ramps.iter().zip(cover).map(|(ramp, covered)| ramp * covered).collect(); blur(&mut sums, columns, rows, blur_radius); ramps.par_iter_mut().zip(sums.par_iter().zip(weights.par_iter())).for_each(|(ramp, (sum, weight))| { - if *weight > MIN_COVERAGE_WEIGHT { + if *weight > MIN_READ_WEIGHT { *ramp = sum / weight; } }); @@ -934,7 +2000,7 @@ fn resampled_by_cells(values: &[f32], cover: &[f32], (region_x, region_y, width, } } } - sums.into_iter().map(|(sum, weight)| (weight > MIN_COVERAGE_WEIGHT).then(|| sum / weight)) + sums.into_iter().map(|(sum, weight)| (weight > MIN_READ_WEIGHT).then(|| sum / weight)) }) .collect(); let average = |column: isize, row: isize| -> Option { @@ -964,12 +2030,12 @@ fn resampled_by_cells(values: &[f32], cover: &[f32], (region_x, region_y, width, Some(value) => (sum + value * corner_weight, weight + corner_weight), None => (sum, weight), }); - if weight > MIN_COVERAGE_WEIGHT { sum / weight } else { values.get(y * width + x).copied().unwrap_or(0.0) } + if weight > MIN_READ_WEIGHT { sum / weight } else { values.get(y * width + x).copied().unwrap_or(0.0) } }) .collect() } -/// A generator's (possibly blurred) ramp after balance, contrast, invert and offset. +/// A generator's (possibly blurred) ramp after balance, contrast, invert and offset fn finish_generator(generator: &Generator, ramp: f32) -> f32 { let value = generator.global.apply(ramp); let value = if generator.invert { 1.0 - value } else { value }; @@ -977,6 +2043,180 @@ fn finish_generator(generator: &Generator, ramp: f32) -> f32 { (value + offset).clamp(0.0, 1.0) } +/// Straight colours a colour space map must leave alone to be the identity +const IDENTITY_PROBE: [f32; 3] = [0.25, 0.5, 0.75]; + +/// Premultiplied content `data` (four components a texel) with each straight color mapped by `map` (nothing for masks or an identity space) +fn recode(data: &mut [f32], comps: usize, map: impl Fn([f32; 3]) -> [f32; 3] + Sync) { + if comps != 4 || map(IDENTITY_PROBE) == IDENTITY_PROBE { + return; + } + + data.par_chunks_mut(4).for_each(|pixel| { + if let [r, g, b, a] = pixel + && *a > MIN_READ_WEIGHT + { + let mapped = map([*r / *a, *g / *a, *b / *a]); + [*r, *g, *b] = mapped.map(|component| component * *a); + } + }); +} + +/// Premultiplied content `data` whose coverage a Highpass changed: its colors laid on the new coverage (mid gray where there was none, as `before`) +fn recover(data: &mut [f32], before: &[f32], mid: f32) { + data.par_chunks_mut(4).zip(before.par_chunks(4)).for_each(|(pixel, old)| { + let (Some(&own), Some(&new)) = (old.get(3), pixel.get(3)) else { return }; + let scale = if own > MIN_READ_WEIGHT { new / own } else { 0.0 }; + for component in pixel.iter_mut().take(3) { + *component = if own > MIN_READ_WEIGHT { *component * scale } else { mid * new }; + } + }); +} + +/// Below this cover a texel is empty and has no straight colour +pub(crate) const MIN_ALPHA: f32 = 1e-5; + +/// The blurred value a precise halo is solid from +const PRECISE_EDGE: f32 = 0.5; + +/// How soft a full spread leaves a halo: its least hardness +const HALO_SOFTEST: f32 = 0.01; + +/// The shapes' blurred share at their edge +const OUTLINE_EDGE_SHARE: f32 = 0.5; + +/// Lay halo glow or drop shadow `filter` (`op` its move) over premultiplied `data` in the tint of a channel of `kind`, mixed in by `opacity` +fn halo( + data: &mut [f32], + cover: &[f32], + comps: usize, + (width, height, radius): (usize, usize, usize), + (op, filter, kind): (Op, &Filter, ChannelKind), + opacity: f32, +) { + let (inner, precise, spread, strength, color, mask_white) = match *filter { + Filter::HaloGlow { on_mask, precise, width, spread, opacity, color } => (width < 0.0, precise, spread, opacity, color, on_mask), + Filter::DropShadow { spread, opacity, color, .. } => (false, false, spread, opacity, color, true), + _ => return, + }; + + // Rec. 709 luminance, unlike `lum`'s weights on purpose + let luminance = 0.2126 * color[0] + 0.7152 * color[1] + 0.0722 * color[2]; + let tint = match (comps, kind) { + (4, ChannelKind::Color) => color, + (4, _) => [luminance; 3], + _ if mask_white => [1.0; 3], + _ => [luminance; 3], + }; + + // The shapes: the content's coverage or the mask's value (the outside of them for an inner glow) + let shape = |texel: usize| { + let value = data.get(texel * comps + comps - 1).copied().unwrap_or(0.0); + let value = if value.is_finite() { value.clamp(0.0, 1.0) } else { 0.0 }; + if inner { 1.0 - value } else { value } + }; + let offset = match op { + Op::Shadow { offset } => offset, + _ => [0, 0], + }; + let moved = |texel: usize| -> Option { + let (x, y) = ((texel % width.max(1)) as i64 - i64::from(offset[0]), (texel / width.max(1)) as i64 - i64::from(offset[1])); + (x >= 0 && y >= 0 && (x as usize) < width && (y as usize) < height).then(|| y as usize * width + x as usize) + }; + let texels = width * height; + let mut weights: Vec = (0..texels).map(|texel| moved(texel).and_then(|from| cover.get(from).copied()).unwrap_or(0.0)).collect(); + let mut sums: Vec = (0..texels).map(|texel| moved(texel).map_or(0.0, |from| shape(from) * cover.get(from).copied().unwrap_or(0.0))).collect(); + blur(&mut weights, width, height, radius); + blur(&mut sums, width, height, radius); + + let hardness = (1.0 - spread.clamp(0.0, 1.0)).max(HALO_SOFTEST); + let strength = strength.clamp(0.0, 1.0); + data.par_chunks_mut(comps).zip(sums.par_iter().zip(weights.par_iter())).for_each(|(pixel, (sum, weight))| { + let blurred = if *weight > MIN_READ_WEIGHT { (sum / weight).clamp(0.0, 1.0) } else { 0.0 }; + let shaped = if precise { crate::organic::smoothstep(0.0, PRECISE_EDGE, blurred) } else { blurred }; + let glow = (shaped / hardness).min(1.0) * strength; + let cov = pixel.last().copied().unwrap_or(0.0).clamp(0.0, 1.0); + let mut before = [0.0f32; 4]; + for (was, value) in before.iter_mut().zip(pixel.iter()) { + *was = *value; + } + if inner { + // Inside the shapes, towards the tint (content premultiplied by its coverage) + let weight = if comps == 4 { glow } else { glow * cov }; + for (slot, tint) in pixel.iter_mut().zip(tint).take(comps.min(3)) { + let target = if comps == 4 { tint * cov } else { tint }; + *slot += (target - *slot) * weight; + } + } else { + // Under the shapes: it shows where they leave room + let under = glow * (1.0 - cov); + for (slot, tint) in pixel.iter_mut().zip(tint).take(comps.min(3)) { + *slot += tint * under; + } + if comps == 4 + && let Some(alpha) = pixel.get_mut(3) + { + *alpha += under; + } + } + for (slot, was) in pixel.iter_mut().zip(before) { + *slot = was + (*slot - was) * opacity; + } + }); +} + +/// Lay Mask Outline `outline` over premultiplied `data` (shapes of content from its luminance), mixed in by `opacity` +fn mask_outline(data: &mut [f32], cover: &[f32], comps: usize, (width, height, radius): (usize, usize, usize), outline: &MaskOutline, opacity: f32) { + let value = |pixel: &[f32]| match pixel { + [r, g, b, alpha] if *alpha > MIN_ALPHA => lum([r / alpha, g / alpha, b / alpha]), + [value] => *value, + _ => 0.0, + }; + let inside: Vec = data.par_chunks(comps).zip(cover.par_iter()).map(|(pixel, covered)| *covered > 0.0 && outline.inside(value(pixel))).collect(); + let fade_curve = outline.fade_curve(); + let mut weights = cover.to_vec(); + let mut sums: Vec = inside.par_iter().zip(cover.par_iter()).map(|(inside, covered)| if *inside { *covered } else { 0.0 }).collect(); + blur(&mut weights, width, height, radius); + blur(&mut sums, width, height, radius); + data.par_chunks_mut(comps).zip(inside.par_iter()).zip(sums.par_iter().zip(weights.par_iter())).for_each(|((pixel, inside), (sum, weight))| { + // The shapes' share around a texel is a half at their edge and none (outside) or all (inside) past the band + let share = if *weight > MIN_READ_WEIGHT { (sum / weight).clamp(0.0, 1.0) } else { 0.0 }; + let closeness = if *inside { (1.0 - share) / OUTLINE_EDGE_SHARE } else { share / OUTLINE_EDGE_SHARE }; + let band = outline.band(fade_curve, *inside, closeness); + + // Content is premultiplied by its coverage, which stays + let cov = if comps == 4 { pixel.get(3).copied().unwrap_or(0.0) } else { 1.0 }; + for slot in pixel.iter_mut().take(comps.min(3)) { + let before = if comps == 4 { if cov > MIN_ALPHA { *slot / cov } else { 0.0 } } else { *slot }; + let result = outline.apply(before, band); + *slot = (before + (result - before) * opacity) * cov; + } + }); +} + +/// Run point filter `filter` on blurred texels `data` (premultiplied content or masks) and mix the result over the unblurred `orig` by `opacity` +fn map_blurred(data: &mut [f32], orig: &[f32], comps: usize, filter: &Filter, gradient: Option<&PreparedGradient>, kind: ChannelKind, opacity: f32) { + let point = |value| match gradient { + Some(gradient) => gradient.point(kind, value), + None => filter.point(kind, value), + }; + let straight = |value: f32, cover: f32| if cover > MIN_ALPHA { value / cover } else { 0.0 }; + + data.par_chunks_mut(comps).zip(orig.par_chunks(comps)).for_each(|(pixel, original)| match (pixel, original) { + ([value], [before]) => { + let mapped = point([*value; 3]).map_or(*value, |gray| gray[0]); + *value = before + (mapped - before) * opacity; + } + ([r, g, b, cover], [r0, g0, b0, cover0]) => { + let before = [straight(*r0, *cover0), straight(*g0, *cover0), straight(*b0, *cover0)]; + let blurred = [straight(*r, *cover), straight(*g, *cover), straight(*b, *cover)]; + let mixed = mix3(before, point(blurred).unwrap_or(before), opacity); + [*r, *g, *b, *cover] = [mixed[0] * cover0, mixed[1] * cover0, mixed[2] * cover0, *cover0]; + } + _ => {} + }); +} + /// Clamp filtered masks to 0..1, and turn filtered content back into straight values. fn unpremultiply(data: &mut [f32], comps: usize) { // Avoid amplifying rounding error near transparent texels @@ -998,13 +2238,19 @@ fn unpremultiply(data: &mut [f32], comps: usize) { /// Precompute the neighbourhood-filtered masks and content channels of every layer that needs /// one, over `tiles` plus the filter's reach. Walks bottom → top so each field sees the fields /// (and anchors) below it. Cheap when no layer has a blur or sharpen. -pub fn neighbourhood_fields(inp: &Inputs, channels: &[Channel], tiles: &[(u32, u32)]) -> Fields { - let stack = inp.project.texture_set(inp.ts).map(|s| s.stack.as_slice()).unwrap_or_default(); - fields_of(inp, channels, stack, tiles) +pub fn neighbourhood_fields(inputs: &Inputs, channels: &[Channel], tiles: &[(u32, u32)]) -> Fields { + let projectors = ProjectorDepthCache::default(); + let inputs = EvaluationInputs::new(inputs, &projectors); + evaluation_fields(&inputs, &evaluation_channels(&inputs, channels.to_vec()), tiles) } -/// [`neighbourhood_fields`] of the layers drawn by `list` only. -fn fields_of(inp: &Inputs, channels: &[Channel], list: &[LayerId], tiles: &[(u32, u32)]) -> Fields { +fn evaluation_fields(inp: &EvaluationInputs, channels: &[Channel], tiles: &[(u32, u32)]) -> Fields { + let stack = inp.project.texture_set(inp.ts).map(|s| s.stack.as_slice()).unwrap_or_default(); + fields_of(inp, channels, (stack, ContentsOffset::NONE), tiles) +} + +/// [`neighbourhood_fields`] of the layers drawn by `list` only, held by folders whose Scale and Rotation make `around` +fn fields_of(inp: &EvaluationInputs, channels: &[Channel], (list, around): (&[LayerId], ContentsOffset), tiles: &[(u32, u32)]) -> Fields { let mut out = Fields::new(); if tiles.is_empty() || inp.gbuf.width == 0 { return out; @@ -1012,32 +2258,99 @@ fn fields_of(inp: &Inputs, channels: &[Channel], list: &[LayerId], tiles: &[(u32 let working_width = inp.gbuf.width; let mut order = Vec::new(); - draw_order(inp.project, list, 0, &mut order); - prepare_curvature_sizes(inp, &order); + draw_order(inp, list, 0, around.into(), &mut order); + let ids: Vec = order.iter().map(|(id, _)| *id).collect(); + prepare_curvature_sizes(inp, &ids); - for id in order { - let Some(layer) = inp.project.content_layer(id) else { continue }; - - if let Some(mask) = layer_mask(inp.project, id).filter(|mask| mask.enabled && neighbourhood(&mask.effects, working_width).is_some()) - && let Some(filtered) = field(inp, channels, &out, id, Job::Mask(mask), tiles) - { - out.insert(FieldKey::Mask(id), filtered); - } - - if layer.is_group() || neighbourhood(&layer.content_effects, working_width).is_none() { - continue; - } - - for channel in channels.iter().filter(|channel| layer.channels.contains_key(channel)) { - if let Some(filtered) = field(inp, channels, &out, id, Job::Content(*channel), tiles) { - out.insert(FieldKey::Content(id, *channel), filtered); + // Walk backwards to find the region each Compare needs below its position in the stack + let mut below_margin = (0u32, false); + let margins: Vec<_> = order + .iter() + .rev() + .map(|&(id, _)| { + let mask_margin = below_margin; + let effects = layer_mask(inp.project, id).filter(|mask| mask.enabled).map(|mask| mask.effects.as_slice()).unwrap_or_default(); + let first_reader = effects.iter().filter(|effect| effect.visible).position(|effect| effect.kind.reads_stack()); + if let Some(first_reader) = first_reader { + for (index, radius, op) in neighbourhood_filters(effects, inp.tile_res(), None).filter(|(index, _, _)| *index > first_reader) { + let reach = filter_extent(radius, op, inp).1; + below_margin.0 = below_margin.0.saturating_add(reach.div_ceil(TILE)); + below_margin.1 |= wraps(effects, index); + } } + + (mask_margin, below_margin) + }) + .collect(); + + for ((id, place), (mask_margin, content_margin)) in order.into_iter().zip(margins.into_iter().rev()) { + let Some(layer) = inp.project.content_layer(id) else { continue }; + let mask = layer_mask(inp.project, id).filter(|mask| mask.enabled && neighbourhood(&mask.effects, working_width).is_some()); + + // A mask comparing its own layer needs that layer's filtered content first + let compares_content = mask.is_some_and(|mask| mask.effects.iter().any(|effect| effect.visible && compares_this_layer(&effect.kind))); + if !compares_content { + insert_mask_field(inp, channels, &mut out, (id, place), mask, tiles, mask_margin); + } + + if !layer.is_group() && neighbourhood(&layer.content_effects, working_width).is_some() { + for channel in channels.iter().filter(|channel| layer.channels.contains_key(channel)) { + let mut key = FieldKey::content(id, *channel, place.offset); + if place.instance != 0 { + let reads_anchor = matches!(&layer.kind, LayerKind::Fill(fill) if fill.sources.get(channel).is_some_and(|source| source.reads_anchor(None))) + || layer + .content_effects + .iter() + .any(|effect| effect.visible && (effect.reads(None) || (*channel == Channel::BaseColor && lights_material(&effect.kind)))); + if reads_anchor { + key = key.in_instance(place.instance); + } + } + + if !out.contains_key(&key) + && let Some(filtered) = field(inp, channels, &out, (id, place), Job::Content(*channel), tiles, content_margin) + { + out.insert(key, filtered); + } + } + } + + if compares_content { + insert_mask_field(inp, channels, &mut out, (id, place), mask, tiles, mask_margin); } } out } +/// Store a filtered mask once per transform, or per draw when it reads the stack. +fn insert_mask_field( + inp: &EvaluationInputs, + channels: &[Channel], + fields: &mut Fields, + (id, place): (LayerId, DrawPlacement), + mask: Option<&Mask>, + tiles: &[(u32, u32)], + margin: (u32, bool), +) { + let Some(mask) = mask else { return }; + let mut key = FieldKey::mask(id, place.offset); + if place.instance != 0 && mask.effects.iter().any(|effect| effect.visible && (effect.kind.reads_stack() || effect.reads(None))) { + key = key.in_instance(place.instance); + } + + if !fields.contains_key(&key) + && let Some(filtered) = field(inp, channels, fields, (id, place), Job::Mask(mask), tiles, margin) + { + fields.insert(key, filtered); + } +} + +/// Whether a mask effect compares the layer's own content +fn compares_this_layer(kind: &EffectKind) -> bool { + matches!(kind, EffectKind::Compare { left, right, .. } if *left == CompareSource::ThisLayer || *right == CompareSource::ThisLayer) +} + /// Build the curvature detail sizes every visible generator of `layers` reads, once, before tiles composite in parallel. fn prepare_curvature_sizes(inp: &Inputs, layers: &[LayerId]) { let visible = layers.iter().filter(|id| inp.project.layers.get(id).is_some_and(|layer| layer.visible)); @@ -1059,15 +2372,16 @@ fn prepare_mask_curvature_sizes<'a>(inp: &Inputs, masks: impl Iterator { - id: LayerId, + draw: (LayerId, usize), content: Content<'a>, chans: Vec>, mask: Option>, - /// Visible anchor points of the layer: recorded after it is applied, or (`Some(k)`, an - /// anchor with visible effects above it) with its content cut after `k` visible effects. + /// Visible anchor points of the layer: recorded after it is applied, or (`Some(k)`, an anchor with visible effects above it) with its content cut after `k` visible effects anchors: Vec<(LayerId, Option)>, - /// The node or one of its children records an anchor. + /// The node or one of its children records an anchor has_anchor: bool, + /// Its base colour has an effect lit by the layer's material (see [`lights_material`]) + lights: bool, height_mask: HeightMask, /// Geometry mask: whether the layer shows on each mesh submesh (None: everywhere). parts: Option>, @@ -1075,7 +2389,14 @@ struct Node<'a> { /// Plans of the visible effects of a stack: mask effects (`channel` None) or the content /// effects of one channel (paint effects then read that channel's pixels). -fn effect_plans<'a>(inp: &Inputs<'a>, effects: &'a [Effect], tile_x: u32, tile_y: u32, channel: Option) -> Vec> { +fn effect_plans<'a>( + inp: &EvaluationInputs<'a>, + effects: &'a [Effect], + tile_x: u32, + tile_y: u32, + channel: Option, + around: ContentsOffset, +) -> Vec> { effects .iter() .filter(|effect| effect.visible) @@ -1088,15 +2409,48 @@ fn effect_plans<'a>(inp: &Inputs<'a>, effects: &'a [Effect], tile_x: u32, tile_y EffectKind::Generator(Generator { detail: Some(detail), .. }) => CurvatureSizes::of(inp, &detail.blurred_sizes_in_use()), _ => None, }; + let (depth, covers_all, projection) = match &effect.kind { + EffectKind::Fill { projection, sampling, .. } | EffectKind::Material(Fill { projection, sampling, .. }) => { + let (depth, covers_all) = fill_coverage(inp, projection, *sampling); + (depth, covers_all, (!around.is_none()).then(|| around.apply(projection))) + } + _ => (None, false, None), + }; + let environment = match &effect.kind { + EffectKind::Filter(Filter::EnvironmentLighting { .. }) + if channel == Some(Channel::BaseColor) && effect.applied_blend(channel).opacity > 0.0 => + { + Some(inp.environment()) + } + _ => None, + }; + let stylized = match &effect.kind { + EffectKind::Filter(filter @ Filter::BakedLighting { .. }) => filter.stylized_lighting().map(|(settings, light)| settings.shading(light)), + _ => None, + }; + let blend = effect.applied_blend(channel); EffectPlan { id: effect.id, kind: &effect.kind, - blend: effect.blend, - opacity: effect.opacity, + projection, + blend: blend.mode, + opacity: blend.opacity, data: if effect.kind.painted() { tile_of(inp, image, tile_x, tile_y, channel) } else { None }, preview: previews(inp, target), curvature_sizes, filtered_mask: None, + depth, + covers_all, + environment, + stylized, + input: match &effect.kind { + EffectKind::Filter(filter) if !filter.is_neighbourhood() => ImageInput::of(filter).first().map(|input| effect.input(input)), + _ => None, + }, + gradient: match &effect.kind { + EffectKind::Filter(filter) => inp.gradient(filter), + _ => None, + }, } }) .collect() @@ -1117,7 +2471,8 @@ fn tile_of<'a>(inp: &Inputs, img: Option<&'a TileImage>, tx: u32, ty: u32, chann if (img.width(), img.height()) == (w, h) { return img.tile(tx, ty).map(Cow::Borrowed); } - // Empty texels of signed channels hold a signed zero. + + // Empty texels of signed channels hold a signed zero let empty: Vec = match channel { Some(c) if c.kind() == ChannelKind::Signed => [vec![to_u16_signed(0.0); c.components()], vec![0]].concat(), _ => Vec::new(), @@ -1125,34 +2480,69 @@ fn tile_of<'a>(inp: &Inputs, img: Option<&'a TileImage>, tx: u32, ty: u32, chann img.resampled_tile(w, h, tx, ty, &empty).map(Cow::Owned) } -fn mask_plan<'a>(inp: &Inputs<'a>, id: LayerId, mask: &'a Mask, tx: u32, ty: u32, fields: Option<&'a Fields>) -> Option> { +/// The plan of layer `id`'s `mask` for tile (tx, ty), its fills under the Scale and Rotation `around` of the folders holding the layer +fn mask_plan<'a>( + inp: &EvaluationInputs<'a>, + id: LayerId, + mask: &'a Mask, + tx: u32, + ty: u32, + fields: Option<&'a Fields>, + place: DrawPlacement, +) -> Option> { if !mask.enabled { return None; } let background = if mask.background == MaskBackground::White { 1.0 } else { 0.0 }; - let mut effects = effect_plans(inp, &mask.effects, tx, ty, None); - let filtered = fields.and_then(|fields| fields.get(&FieldKey::Mask(id))); - for effect in &mut effects { - effect.filtered_mask = filtered.and_then(|field| field.anchor_stages.iter().find(|(id, _)| *id == effect.id).map(|(_, field)| field)); + let mut effects = effect_plans(inp, &mask.effects, tx, ty, None, place.offset); + let filtered = fields.and_then(|fields| FieldKey::mask(id, place.offset).field(fields, place.instance)); + for (index, effect) in effects.iter_mut().enumerate() { + effect.filtered_mask = filtered.and_then(|field| field.anchor_stages.iter().find(|(stage, _)| *stage == index).map(|(_, field)| field)); } let start = filtered.and_then(|field| neighbourhood(&mask.effects, inp.gbuf.width).map(|(index, _, _)| (index, field))); - Some(MaskPlan { background, effects, start }) + let compared = compared_channels(mask.effects.iter().filter(|effect| effect.visible && effect.kind.reads_stack()), Vec::new()); + + // A folder's own content is its children: its compare sides read the stack below it + let layer = if compared.is_empty() { + None + } else { + inp.project.content_layer(id).and_then(|l| plan_content(inp, id, l, &compared, tx, ty, 0, fields, false, place, None)) + }; + Some(MaskPlan { background, effects, layer, start }) } -fn plan<'a>(inp: &Inputs<'a>, list: &[LayerId], channels: &[Channel], tx: u32, ty: u32, depth: usize, fields: Option<&'a Fields>) -> Vec> { +/// The plans of sibling layers `list` (under the Scale and Rotation of the folders holding them) +fn plan<'a>(inp: &EvaluationInputs<'a>, list: &[LayerId], channels: &[Channel], tx: u32, ty: u32, depth: usize, fields: Option<&'a Fields>) -> Vec> { + let around = list.first().map_or(ContentsOffset::NONE, |id| inp.project.contents_around(*id)); + plan_in(inp, list, channels, tx, ty, depth, fields, around.into(), None) +} + +/// [`plan`] of sibling layers under `around`, with an optional marker for a stack probe +#[allow(clippy::too_many_arguments)] +fn plan_in<'a>( + inp: &EvaluationInputs<'a>, + list: &[LayerId], + channels: &[Channel], + tx: u32, + ty: u32, + depth: usize, + fields: Option<&'a Fields>, + place: DrawPlacement, + stop: Option<(LayerId, usize)>, +) -> Vec> { if depth > texturecraft_core::project::MAX_DEPTH { return Vec::new(); } - list.iter().filter_map(|id| plan_node(inp, *id, channels, tx, ty, depth, fields, true)).collect() + + list.iter().filter_map(|id| plan_node(inp, *id, channels, tx, ty, depth, fields, true, place, stop)).collect() } -/// The plan of layer `id` at `depth` (None where it draws nothing); a folder's children are -/// planned when `kids`. +/// The plan of layer `id` at `depth` (None where it draws nothing), its fills under the Scale and Rotation `around` of the folders holding it; a folder's children are planned when `kids` #[allow(clippy::too_many_arguments)] fn plan_node<'a>( - inp: &Inputs<'a>, + inp: &EvaluationInputs<'a>, id: LayerId, channels: &[Channel], tx: u32, @@ -1160,44 +2550,37 @@ fn plan_node<'a>( depth: usize, fields: Option<&'a Fields>, kids: bool, + place: DrawPlacement, + stop: Option<(LayerId, usize)>, ) -> Option> { let own: &'a Layer = inp.project.layers.get(&id)?; + // A stack probe stops here even when this layer draws nothing + if stop == Some((id, place.instance)) { + return Some(Node { + draw: (id, place.instance), + content: Content::Paint { preview: false }, + chans: Vec::new(), + mask: None, + anchors: Vec::new(), + has_anchor: false, + lights: false, + height_mask: HeightMask::default(), + parts: None, + }); + } + // Instances draw their source's content (a missing source draws nothing) let layer: &'a Layer = inp.project.content_layer(id)?; if !own.visible { return None; } - let paint = matches!(layer.kind, LayerKind::Paint); - let fx = !layer.is_group() && layer.content_effects.iter().any(|e| e.visible); - let fx_start = if fx { neighbourhood(&layer.content_effects, inp.gbuf.width).map(|n| n.0) } else { None }; - let chans = channels - .iter() - .filter_map(|c| { - let b = layer.blend(*c)?; - if b.mode == BlendMode::Disable || b.opacity <= 0.0 { - return None; - } - - let data = if paint { tile_of(inp, inp.pixels.layer(layer.id, *c), tx, ty, Some(*c)) } else { None }; - let effects = if fx { effect_plans(inp, &layer.content_effects, tx, ty, Some(*c)) } else { Vec::new() }; - let start = fx_start.zip(fields.and_then(|f| f.get(&FieldKey::Content(id, *c)))); - Some(ChanPlan { ch: c.index(), kind: c.kind(), comps: c.components(), blend: b.mode, opacity: b.opacity.clamp(0.0, 1.0), data, effects, start }) - }) - .collect::>(); - let content = match &layer.kind { - LayerKind::Paint => Content::Paint { preview: previews(inp, PaintTarget::Layer(layer.id)) }, - LayerKind::Fill(f) => Content::Fill(f), - LayerKind::Group { children, .. } => Content::Group(if kids { plan(inp, children, channels, tx, ty, depth + 1, fields) } else { Vec::new() }), - - // `content_layer` already followed instance links - LayerKind::Instance { .. } => return None, - }; - let mask = layer_mask(inp.project, id).and_then(|m| mask_plan(inp, id, m, tx, ty, fields)); + let (content, chans) = plan_content(inp, id, layer, channels, tx, ty, depth, fields, kids, place, stop)?; + let mask = layer_mask(inp.project, id).and_then(|m| mask_plan(inp, id, m, tx, ty, fields, place)); // Anchors in the mask record even where the layer draws nothing - let mask_anchor = mask.as_ref().is_some_and(|m| m.effects.iter().any(|e| matches!(e.kind, EffectKind::Anchor))); + let mask_anchor = mask.as_ref().is_some_and(|m| m.effects.iter().any(|e| matches!(*e.kind, EffectKind::Anchor))); // An empty paint layer still matters if its mask records an anchor if let Content::Paint { preview: false } = content @@ -1207,16 +2590,79 @@ fn plan_node<'a>( return None; } - if chans.is_empty() && !mask_anchor { + let probe_group = stop.is_some() && matches!(&content, Content::Group(children) if !children.is_empty()); + if chans.is_empty() && !mask_anchor && !probe_group { return None; } - let anchors = if fx { anchor_cuts(&layer.content_effects) } else { Vec::new() }; + let has_content_effects = !layer.is_group() && layer.content_effects.iter().any(|e| e.visible); + let anchors = if has_content_effects { anchor_cuts(&layer.content_effects) } else { Vec::new() }; let has_anchor = !anchors.is_empty() || mask_anchor || matches!(&content, Content::Group(nodes) if nodes.iter().any(|n| n.has_anchor)); + let base = Channel::BaseColor.index(); + let lights = chans.iter().any(|chan_plan| chan_plan.ch == base && chan_plan.effects.iter().any(|effect| lights_material(effect.kind))); // The geometry mask is the layer's own (an instance in another set has other parts) let parts = own.geometry_mask.as_ref().map(|names| inp.mesh.submeshes.iter().map(|s| names.contains(&s.name)).collect()); - Some(Node { id, content, chans, mask, anchors, has_anchor, height_mask: layer.height_mask, parts }) + Some(Node { draw: (id, place.instance), content, chans, mask, anchors, has_anchor, lights, height_mask: layer.height_mask, parts }) +} + +/// Whether a base colour effect reads the layer's other channels as its material: Baked Lighting Stylized's highlights, Environment Lighting, PBR Validate's metal +pub(crate) fn lights_material(kind: &EffectKind) -> bool { + match kind { + EffectKind::Filter(filter @ Filter::BakedLighting { .. }) => filter.stylized_lighting().is_some_and(|(stylized, _)| stylized.output.specular()), + EffectKind::Filter(Filter::EnvironmentLighting { .. } | Filter::PbrValidate(_)) => true, + _ => false, + } +} + +/// The content of `layer` (layer `id`'s own, or its instance source's; None for an unfollowed instance) and its plan per drawn channel of `channels`, its fills under the Scale and Rotation `around` of the folders holding `id`; a folder's children are planned when `kids` +#[allow(clippy::too_many_arguments)] +fn plan_content<'a>( + inp: &EvaluationInputs<'a>, + id: LayerId, + layer: &'a Layer, + channels: &[Channel], + tx: u32, + ty: u32, + depth: usize, + fields: Option<&'a Fields>, + kids: bool, + place: DrawPlacement, + stop: Option<(LayerId, usize)>, +) -> Option<(Content<'a>, Vec>)> { + let paint = matches!(layer.kind, LayerKind::Paint); + let has_content_effects = !layer.is_group() && layer.content_effects.iter().any(|e| e.visible); + let chans = channels + .iter() + .filter_map(|c| { + let b = layer.blend(*c)?; + if b.mode == BlendMode::Disable || b.opacity <= 0.0 { + return None; + } + + let data = if paint { tile_of(inp, inp.pixels.layer(layer.id, *c), tx, ty, Some(*c)) } else { None }; + let effects = if has_content_effects { effect_plans(inp, &layer.content_effects, tx, ty, Some(*c), place.offset) } else { Vec::new() }; + let start = fields + .and_then(|fields| FieldKey::content(id, *c, place.offset).field(fields, place.instance)) + .and_then(|field| neighbourhood_filters(&layer.content_effects, inp.tile_res(), Some(*c)).last().map(|(index, _, _)| (index, field))); + Some(ChanPlan { ch: c.index(), kind: c.kind(), comps: c.components(), blend: b.mode, opacity: b.opacity.clamp(0.0, 1.0), data, effects, start }) + }) + .collect::>(); + let content = match &layer.kind { + LayerKind::Paint => Content::Paint { preview: previews(inp, PaintTarget::Layer(layer.id)) }, + LayerKind::Fill(fill) => { + let (depth, covers_all) = fill_coverage(inp, &fill.projection, fill.sampling); + let projection = (!place.offset.is_none()).then(|| Box::new(place.offset.apply(&fill.projection))); + Content::Fill { fill, projection, depth, covers_all } + } + LayerKind::Group { children, .. } => { + Content::Group(if kids { plan_in(inp, children, channels, tx, ty, depth + 1, fields, place.children(inp, id, layer), stop) } else { Vec::new() }) + } + + // `content_layer` already followed instance links + LayerKind::Instance { .. } => return None, + }; + Some((content, chans)) } /// The visible anchor points of a content stack with where they cut it: after their index among @@ -1238,15 +2684,29 @@ struct LevelPlan<'a> { /// Plan the path to the hot layer for tile (tx, ty); the layers before the path are left out /// on tiles the cache holds (`warm`). -fn plan_levels<'a>(inp: &Inputs<'a>, levels: &[Level], channels: &[Channel], tx: u32, ty: u32, fields: &'a Fields, warm: bool) -> Vec> { +fn plan_levels<'a>(inp: &EvaluationInputs<'a>, levels: &[Level], channels: &[Channel], tx: u32, ty: u32, fields: &'a Fields, warm: bool) -> Vec> { let last = levels.len().saturating_sub(1); levels .iter() + .zip(level_offsets(inp.project, levels)) .enumerate() - .map(|(d, l)| LevelPlan { - below: if warm { Vec::new() } else { plan(inp, &l.below, channels, tx, ty, d, Some(fields)) }, - at: plan_node(inp, l.at, channels, tx, ty, d, Some(fields), d == last), - above: plan(inp, &l.above, channels, tx, ty, d, Some(fields)), + .map(|(d, (l, around))| LevelPlan { + below: if warm { Vec::new() } else { plan_in(inp, &l.below, channels, tx, ty, d, Some(fields), around.into(), None) }, + at: plan_node(inp, l.at, channels, tx, ty, d, Some(fields), d == last, around.into(), None), + above: plan_in(inp, &l.above, channels, tx, ty, d, Some(fields), around.into(), None), + }) + .collect() +} + +/// The Scale and Rotation the folders (instanced ones included) above each level of the path to the hot layer lay on its fills +fn level_offsets(p: &Project, levels: &[Level]) -> Vec { + let mut around = ContentsOffset::NONE; + levels + .iter() + .map(|level| { + let held = around; + around = around.then(p.content_layer(level.at).map_or(ContentsOffset::NONE, |layer| p.contents_offset(layer.id))); + held }) .collect() } @@ -1256,18 +2716,40 @@ fn blend_chan(c: &ChanPlan, mode: BlendMode, a: [f32; 3], b: [f32; 3]) -> [f32; if c.comps == 3 { blend3(mode, a, b) } else { [blend1(mode, a[0], b[0]); 3] } } -/// Lay value `p` with weight `a` over a straight value and coverage (premultiplied "over"). +/// Lay value `p` with weight `a` over a straight value and coverage (premultiplied "over") fn over(c: &ChanPlan, mode: BlendMode, v: [f32; 3], cov: f32, p: [f32; 3], a: f32) -> ([f32; 3], f32) { if a <= 0.0 { return (v, cov); } + let b = if cov > 0.0 { blend_chan(c, mode, v, p) } else { p }; let nc = a + cov * (1.0 - a); (mix3(v, b, a / nc.max(1e-5)), nc) } -/// The plain UV projection a decal's frame coordinates are sampled through. -const DECAL_UV: Projection = Projection::Uv { scale: [1.0, 1.0], rotation: 0.0, offset: [0.0, 0.0] }; +/// Whether a fill placed by `proj` repeats past its tile both ways, so no texel falls outside it (tri-planar never ends) +fn repeats_everywhere(proj: &Projection, sampling: Sampling) -> bool { + sampling.wrap.repeats() == (true, true) || matches!(proj, Projection::Triplanar { .. }) +} + +/// Whether a fill placed by `proj` covers every texel: it repeats, nothing crops or culls it and it is not framed on the surface +fn covers_every_texel(proj: &Projection, sampling: Sampling, depth: Option<&FillDepth>) -> bool { + let framed = matches!(proj, Projection::Planar { placed: Some(_), .. } | Projection::Warp { .. }); + let depth_culled = depth.is_some() && proj.depth_culling().is_some(); + !framed && !depth_culled && repeats_everywhere(proj, sampling) && projector_covers_all(proj) +} + +/// A fill's projector depth (None: not culled by depth) and whether it covers every texel +fn fill_coverage(inp: &EvaluationInputs, projection: &Projection, sampling: Sampling) -> (Option>, bool) { + let depth = inp.projector_depth(projection, sampling); + let covers_all = covers_every_texel(projection, sampling, depth.as_deref()); + (depth, covers_all) +} + +/// Whether a fill placed by `proj` is sampled once per copy of `sampling`'s symmetry +fn takes_symmetry(proj: &Projection, sampling: Sampling) -> bool { + sampling.symmetry.on && proj.takes_symmetry() +} /// Per-texel context. struct Texel<'a, 'b> { @@ -1280,11 +2762,17 @@ struct Texel<'a, 'b> { coords: Option, stroke: f32, /// `eval` stops when it reaches this layer. - stop: Option, + stop: Option<(LayerId, usize)>, /// Stack values recorded by the anchor points evaluated so far; true marks a mask anchor (gray, not channel values). anchors: Vec<(LayerId, Acc, bool)>, + /// The stack below the layer whose mask compares its channels (recorded by `eval` there, or where it stops) + below: Option, + /// The material Baked Lighting Stylized reads its highlights from: the stack with the layer it lights (its other channels) laid on + lit: Option, /// Where `eval` takes layer masks and content from. tape: Tape<'b>, + /// The copy of a symmetric fill being sampled: the surface point and normal it sees, and its image's flip + copy: Option<(usize, FillCopy)>, } /// What a layer contributes (its mask, its content value and coverage per channel): evaluated @@ -1315,9 +2803,12 @@ impl<'t> Tape<'t> { } } +/// Each channel's content (value and coverage) where the layer has one +type ChannelContents = [Option<([f32; 3], f32)>; NCH]; + impl<'a, 'b> Texel<'a, 'b> { fn new(inp: &'b Inputs<'a>, x: u32, y: u32, o: usize, stroke: f32) -> Self { - Texel { inp, x, y, o, res: inp.gbuf.width, coords: None, stroke, stop: None, anchors: Vec::new(), tape: Tape::Off } + Texel { inp, x, y, o, res: inp.gbuf.width, coords: None, stroke, stop: None, anchors: Vec::new(), below: None, lit: None, tape: Tape::Off, copy: None } } /// Run `f` with `tape` as this texel's tape. @@ -1369,29 +2860,208 @@ impl<'a, 'b> Texel<'a, 'b> { if let Some(c) = self.coords { return c; } + + #[cfg(test)] + tests::COORDS_LOOKUPS.with(|count| count.set(count.get() + 1)); + let g = self.inp.gbuf; - let i = (self.y * g.width + self.x) as usize; - let (lo, hi) = self.inp.bounds; - let center = (lo + hi) * 0.5; - let r = ((hi - lo).length() * 0.5).max(1e-4); - let mut c = match g.surface(self.inp.mesh, i) { - Some(s) => Coords { uv: s.uv, pos: (s.pos - center) / r, nrm: s.nrm }, - None => Coords { uv: Vec2::new((self.x as f32 + 0.5) / g.width as f32, (self.y as f32 + 0.5) / g.height as f32), pos: Vec3::ZERO, nrm: Vec3::Y }, + let c = match self.surface((self.y * g.width + self.x) as usize) { + Some(s) => self.coords_of(s), + None => self.tile_uv(Coords { + uv: Vec2::new((self.x as f32 + 0.5) / g.width as f32, (self.y as f32 + 0.5) / g.height as f32), + pos: Vec3::ZERO, + nrm: Vec3::Y, + }), }; - // UV-tiled sets: projections see the mesh's own UVs (patterns repeat per tile). + self.coords = Some(c); + c + } + + /// The coordinates projections see at surface `s`: its UV, and its position in mesh radii from the mesh's centre + #[inline(always)] + fn coords_of(&self, s: Surface) -> Coords { + let (center, radius) = mesh_frame(self.inp.bounds); + self.tile_uv(Coords { uv: s.uv, pos: (s.pos - center) / radius, nrm: s.nrm }) + } + + /// `c` with its UV moved out of the atlas on a UV-tiled set, so projections see the mesh's own UVs (patterns repeat per tile) + #[inline(always)] + fn tile_uv(&self, mut c: Coords) -> Coords { if let Ok(set) = self.inp.project.texture_set(self.inp.ts) && let Some(grid) = set.tile_grid() { c.uv = Vec2::from(set.from_atlas(&grid, c.uv.to_array())); } - self.coords = Some(c); c } - /// World position of this texel (None when uncovered). + /// The coordinates of texel (`x`, `y`) through `proj`, uncached (None when uncovered) + fn projected_at(&self, proj: &Projection, x: u32, y: u32) -> Option { + let g = self.inp.gbuf; + if x >= g.width || y >= g.height { + return None; + } + + let s = self.surface((y * g.width + x) as usize)?; + let c = self.coords_of(s); + if proj.frame().is_none() { + return Some(c); + } + + let (center, _) = mesh_frame(self.inp.bounds); + framed_cover(proj, s.pos, s.nrm, center).map(|(uv, _)| Coords { uv, ..c }) + } + + /// Image texels spanned by one surface texel in each projection plane. + fn footprints(&self, proj: &Projection, samples: &[(Vec2, f32); 3], image: &ImageRes) -> [f32; 3] { + let size = Vec2::new(image.width as f32, image.height as f32); + if matches!(proj, Projection::Uv { .. } | Projection::UvTile) { + // Use the current tile's affine mapping even where a neighbor wraps or is uncovered + let step = self.inp.mesh_uv_step(self.x, self.y); + let span = if let Projection::Uv { scale, rotation, .. } = proj { + let transform = placement(Vec2::from(*scale), *rotation, Vec2::ZERO); + let across = (transform(Vec2::new(step.x, 0.0)) * size).length(); + let down = (transform(Vec2::new(0.0, step.y)) * size).length(); + across.max(down) + } else { + (step * size).max_element() + }; + return [if span.is_finite() { span.max(1.0) } else { 1.0 }, 1.0, 1.0]; + } + + let mut out = [1.0f32; 3]; + let seam_limit = size.max_element() * SEAM_JUMP_SHARE; + for (dx, dy) in [(1, 0), (0, 1)] { + let Some(next) = self.projected_at(proj, self.x + dx, self.y + dy) else { continue }; + + for ((footprint, (uv, _)), (next_uv, _)) in out.iter_mut().zip(samples).zip(self.image_uvs(proj, &next)) { + let span = ((next_uv - *uv) * size).length(); + + // Projected neighbors can land on disconnected surfaces at a UV seam + if span.is_finite() && span < seam_limit { + *footprint = footprint.max(span); + } + } + } + out + } + + /// World position of this texel as the fill copy being sampled sees it (None when uncovered) fn world(&self) -> Option { + self.surface((self.y * self.inp.gbuf.width + self.x) as usize).map(|s| s.pos) + } + + /// The surface at G-buffer index `i`, as the fill copy being sampled sees it + #[inline(always)] + fn surface(&self, i: usize) -> Option { + let mut s = self.inp.gbuf.surface(self.inp.mesh, i)?; + if let Some((_, copy)) = self.copy { + s.pos = copy.point(s.pos); + s.nrm = copy.normal(s.nrm); + s.geo_nrm = copy.normal(s.geo_nrm); + } + Some(s) + } + + /// Where `proj` reads images at `coords`, turned over as the fill copy being sampled says + fn image_uvs(&self, proj: &Projection, coords: &Coords) -> [(Vec2, f32); 3] { + let samples = image_samples(proj, coords); + match self.copy { + Some((_, copy)) => samples.map(|(uv, weight)| (copy.uv(uv), weight)), + None => samples, + } + } + + /// A fill's value and coverage through `proj`, from `one` (which samples it once): with `sampling`'s symmetry on, every copy of the projection is sampled and the copies are laid over each other, the texel's own copy on top + fn symmetric(&mut self, proj: &Projection, sampling: Sampling, mut one: impl FnMut(&mut Self) -> ([f32; 3], f32)) -> ([f32; 3], f32) { + // Skip the world-space lookup when no symmetry copies are needed + if !takes_symmetry(proj, sampling) { + return one(self); + } + + self.symmetric_copies(sampling, one) + } + + /// [`Texel::symmetric`] with symmetry on: every copy sampled and laid over the others + fn symmetric_copies(&mut self, sampling: Sampling, mut one: impl FnMut(&mut Self) -> ([f32; 3], f32)) -> ([f32; 3], f32) { + let Some(world) = self.inp.gbuf.surface(self.inp.mesh, (self.y * self.inp.gbuf.width + self.x) as usize).map(|surface| surface.pos) else { + return one(self); + }; + + let (center, radius) = mesh_frame(self.inp.bounds); + let cached = self.coords.take(); + let mut value = [0.0f32; 3]; + let mut cover = 0.0f32; + let mut copies = FillCopies::new(&sampling.symmetry, world, center, radius); + while let Some((index, copy)) = copies.next_indexed() { + self.copy = Some((index, copy)); + self.coords = None; + let (copy_value, copy_cover) = one(self); + let weight = copy_cover.clamp(0.0, 1.0) * (1.0 - cover); + for (total, part) in value.iter_mut().zip(copy_value) { + *total += part * weight; + } + cover += weight; + if cover >= COVERED { + break; + } + } + self.copy = None; + self.coords = cached; + if cover <= 0.0 { + return ([0.0; 3], 0.0); + } + + (value.map(|v| v / cover), cover) + } + + /// The normal Baked Lighting Stylized lights: the mesh's (no `relief`), or (Mesh + Height + Normal) its [`Texel::detail_normal`] at `relief` + fn lit_normal(&mut self, relief: Option) -> [f32; 3] { + match relief { + Some(relief) => self.detail_normal(relief), + None => self.coords().nrm.to_array(), + } + } + + /// The baked world normal (the mesh's without one) tilted by the baked height's slope times `relief` + fn detail_normal(&mut self, relief: f32) -> [f32; 3] { + let mesh = self.coords().nrm; + let detail = self + .baked_color(BakedMap::WorldNormal) + .map(|packed| Vec3::from(packed) * 2.0 - Vec3::ONE) + .filter(|n| n.length_squared() > MIN_NORMAL_LENGTH_SQUARED); + let nrm = detail.map_or(mesh, Vec3::normalize); let i = (self.y * self.inp.gbuf.width + self.x) as usize; - self.inp.gbuf.surface(self.inp.mesh, i).map(|s| s.pos) + let (Some(surface), Some(slope)) = (self.surface(i), self.height_slope()) else { return nrm.to_array() }; + let tangent = surface.tangent.truncate(); + let bitangent = nrm.cross(tangent) * surface.tangent.w; + let tilted = nrm - (tangent * slope[0] + bitangent * slope[1]) * HEIGHT_RELIEF * relief; + tilted.try_normalize().unwrap_or(nrm).to_array() + } + + /// The baked height's change per UV unit along U and V at this texel (central differences); None without a height bake + fn height_slope(&self) -> Option<[f32; 2]> { + let (width, height) = (self.res, self.inp.gbuf.height); + let at = |x: u32, y: u32| self.inp.baked.sample_working(BakedMap::Height, x, y, (width, height), &self.inp.block_scales).map(|h| h[0]); + let (origin_x, origin_y, tile_width, tile_height) = if let Some(grid) = self.inp.tile_grid() { + let block = (width / grid.cols.max(1)).max(1); + let tile = ((block as f32 * self.inp.block_scales.at(self.x, self.y)).round() as u32).max(1); + (self.x / block * block, self.y / block * block, tile, tile) + } else { + (0, 0, width, height) + }; + + let last_x = origin_x.saturating_add(tile_width.saturating_sub(1)).min(width.saturating_sub(1)); + let last_y = origin_y.saturating_add(tile_height.saturating_sub(1)).min(height.saturating_sub(1)); + if self.x > last_x || self.y > last_y { + return None; + } + + let (left, right) = (self.x.saturating_sub(1).max(origin_x), (self.x + 1).min(last_x)); + let (up, down) = (self.y.saturating_sub(1).max(origin_y), (self.y + 1).min(last_y)); + let du = (at(right, self.y)? - at(left, self.y)?) / (right - left).max(1) as f32 * tile_width as f32; + let dv = (at(self.x, down)? - at(self.x, up)?) / (down - up).max(1) as f32 * tile_height as f32; + Some([du, dv]).filter(|slope| slope.iter().all(|s| s.is_finite())) } fn baked(&self, m: BakedMap) -> Option { @@ -1402,33 +3072,102 @@ impl<'a, 'b> Texel<'a, 'b> { self.inp.baked.sample_working(map, self.x, self.y, (self.res, self.inp.gbuf.height), &self.inp.block_scales) } - /// Where projection `proj` samples this texel: the texel's coordinates, or for a decal its - /// position in the decal's frame (then sampled as UVs) and the decal's coverage. - fn projected<'p>(&mut self, proj: &'p Projection) -> (Coords, &'p Projection, f32) { + /// This texel's ID color: from image resource `image` (nearest, as stored), or from the ID mesh map without one + fn id_color(&self, image: Option<&str>) -> Option<[f32; 3]> { + let Some(name) = image else { return self.baked_color(BakedMap::Id) }; + let image = self.inp.images.get(name)?; + let [red, green, blue, _] = + image.sample_nearest((self.x as f32 + 0.5) / self.res.max(1) as f32, (self.y as f32 + 0.5) / self.inp.gbuf.height.max(1) as f32); + Some([red, green, blue]) + } + + /// Where `proj` samples this texel: its coordinates, or for a projection from a frame on the surface (placed planar, warp) its place in the frame, and how much backface culling and the shape crop let through + fn projected(&mut self, proj: &Projection) -> (Coords, f32) { let c = self.coords(); - let (lo, hi) = self.inp.bounds; - let center = (lo + hi) * 0.5; - match proj { - Projection::Decal(d) => match self.world().and_then(|p| decal_uv_symmetric(d, p, c.nrm, center)) { - Some((uv, w)) => (Coords { uv, ..c }, &DECAL_UV, w), - None => (c, &DECAL_UV, 0.0), - }, - _ => (c, proj, 1.0), + if proj.frame().is_none() { + return (c, 1.0); + } + + let (center, _) = mesh_frame(self.inp.bounds); + + match self.world().and_then(|p| framed_cover(proj, p, c.nrm, center)) { + Some((uv, cover)) => (Coords { uv, ..c }, cover), + None => (c, 0.0), } } - /// How much a fill projected by `proj` covers this texel: 1, or for a decal its frame - /// coverage times the alpha of its first image source. - fn cover<'s>(&mut self, mut sources: impl Iterator, proj: &Projection) -> f32 { - if !matches!(proj, Projection::Decal(_)) { - return 1.0; + /// `place`'s fill at this texel in channel `ch`, every symmetric copy laid over each other when its symmetry is on + #[inline(always)] + fn fill_place_texel(&mut self, place: FillPlace, source: Option<&Source>, ch: Channel) -> ([f32; 3], f32) { + // Sample directly without symmetry to keep the common path free of the copy search + if takes_symmetry(place.projection, place.fill.sampling) { + self.symmetric(place.projection, place.fill.sampling, |texel| texel.fill_texel(place, source, ch)) + } else { + self.fill_texel(place, source, ch) } - let (c, _, w) = self.projected(proj); - let image = sources.find_map(|s| match s { + } + + /// `place`'s fill sampled once at this texel: its value in channel `ch` (`source`, else the channel's default) and its coverage + #[inline(always)] + fn fill_texel(&mut self, place: FillPlace, source: Option<&Source>, ch: Channel) -> ([f32; 3], f32) { + let FillPlace { fill, projection, depth, covers_all } = place; + let value = match source { + Some(source) => self.source(source, projection, fill.sampling, ch.kind()), + None => ch.default_value(), + }; + let cover = if covers_all { 1.0 } else { self.cover(fill.sources.values(), projection, fill.sampling, depth) }; + (value, cover) + } + + /// How much a fill projected by `proj` covers this texel: [`Texel::shape_cover`], then depth culling through the projector's `depth` map + fn cover<'s>(&mut self, sources: impl Iterator, proj: &Projection, sampling: Sampling, depth: Option<&FillDepth>) -> f32 { + #[cfg(test)] + tests::COVER_CALLS.with(|count| count.set(count.get() + 1)); + + let cover = self.shape_cover(sources, proj, sampling); + match depth.zip(proj.depth_culling()) { + Some((depth, culling)) if cover > 0.0 => { + let copy_index = self.copy.map_or(0, |(index, _)| index); + cover * self.world().map_or(1.0, |point| depth.cover(copy_index, point, culling.hardness)) + } + _ => cover, + } + } + + /// How much a fill projected by `proj` covers this texel: wrap, shape crop and backface culling, and a cropped framed projection's image alpha + fn shape_cover<'s>(&mut self, mut sources: impl Iterator, proj: &Projection, sampling: Sampling) -> f32 { + let (Projection::Planar { projector, placed: Some(_), .. } | Projection::Warp { projector, .. }) = proj else { + // Repeating with nothing cropped or culled, a fill covers every texel without looking up where the texel is + if repeats_everywhere(proj, sampling) && projector_covers_all(proj) { + return 1.0; + } + + let coords = self.coords(); + return self.tile_cover(proj, &coords, sampling) * projector_cover(proj, &coords); + }; + + let (coords, cover) = self.projected(proj); + if projector.crop == ShapeCrop::ExtendsOutside || projector.ignore_image_alpha { + return cover * self.tile_cover(proj, &coords, sampling); + } + + // Cropped to its shape, a framed projection takes the shape of its image too + let image = sources.find_map(|source| match source { Source::Image { name, .. } => self.inp.images.get(name), _ => None, }); - w * image.map_or(1.0, |img| img.sample(c.uv.x, c.uv.y)[3].clamp(0.0, 1.0)) + let samples = self.image_uvs(proj, &coords); + let [(uv, _), ..] = samples; + + // Use the image's sampling footprint so minified color and coverage agree + let alpha = image.map_or(1.0, |image| { + let [footprint, ..] = match sampling.filtering { + Filtering::BilinearHq => self.footprints(proj, &samples, image), + Filtering::BilinearSharp | Filtering::Nearest => [1.0; 3], + }; + image.sample_alpha(uv.x, uv.y, sampling, footprint).clamp(0.0, 1.0) + }); + cover * alpha * self.tile_cover(proj, &coords, sampling) } /// The stack value anchor point `anchor` recorded for `channel` (the channel default for an @@ -1443,8 +3182,20 @@ impl<'a, 'b> Texel<'a, 'b> { self.anchors.iter().rev().find(|(id, ..)| *id == anchor).is_some_and(|(_, _, mask)| *mask) } + /// 1 where a fill placed by `proj` at `coords` lands inside its 0..1 tile on every axis `sampling.wrap` does not repeat, else 0 + fn tile_cover(&self, proj: &Projection, coords: &Coords, sampling: Sampling) -> f32 { + if repeats_everywhere(proj, sampling) { + return 1.0; + } + + let (across, down) = sampling.wrap.repeats(); + let [(uv, _), ..] = self.image_uvs(proj, coords); + let inside = |t: f32, repeats: bool| repeats || (0.0..1.0).contains(&t); + if inside(uv.x, across) && inside(uv.y, down) { 1.0 } else { 0.0 } + } + /// The value `source` gives this texel through `projection`, read as a channel of `kind` - fn source(&mut self, source: &Source, projection: &Projection, kind: ChannelKind) -> [f32; 3] { + fn source(&mut self, source: &Source, projection: &Projection, sampling: Sampling, kind: ChannelKind) -> [f32; 3] { match source { Source::Uniform(value) => *value, @@ -1457,7 +3208,7 @@ impl<'a, 'b> Texel<'a, 'b> { texturecraft_core::gradient(ramp, lightness).unwrap_or_default() } Source::Procedural { pattern, low, high, ramp } => { - let (coords, projection, _) = self.projected(projection); + let (coords, _) = self.projected(projection); let pixels = if pattern.resolution.can_reduce() { let uv_tile = self.inp.tile_res_at(self.x, self.y); let texture_set = self.inp.project.texture_set(self.inp.ts).map_or(uv_tile, |set| set.resolution); @@ -1476,17 +3227,32 @@ impl<'a, 'b> Texel<'a, 'b> { Source::Image { name, normal_format } => { let Some(image) = self.inp.images.get(name) else { return [0.5; 3] }; - let (coords, projection, _) = self.projected(projection); - let mut sum = [0.0f32; 4]; - for (uv, weight) in image_samples(projection, &coords).into_iter().filter(|(_, weight)| *weight > 0.0) { - for (total, value) in sum.iter_mut().zip(image.sample(uv.x, uv.y)) { + let (coords, _) = self.projected(projection); + let samples = self.image_uvs(projection, &coords); + let footprints = match sampling.filtering { + Filtering::BilinearHq => self.footprints(projection, &samples, image), + Filtering::BilinearSharp | Filtering::Nearest => [1.0; 3], + }; + + // Blend projected planes in the same space when any of them reads a linear mip + let is_srgb_color = kind == ChannelKind::Color && image.srgb; + let planes = samples.into_iter().zip(footprints).filter(|((_, weight), _)| *weight > 0.0); + let blend_linear = is_srgb_color && planes.clone().any(|(_, footprint)| crate::store::uses_mips(footprint)); + let mut rgb = [0.0; 3]; + for ((uv, weight), footprint) in planes { + let sampled = if blend_linear { + image.sample_srgb_color(uv.x, uv.y, sampling, footprint) + } else { + image.sample_filtered(uv.x, uv.y, sampling, footprint) + }; + + for (total, value) in rgb.iter_mut().zip(sampled) { *total += value * weight; } } - let rgb = [sum[0], sum[1], sum[2]]; match kind { - ChannelKind::Color if image.srgb => rgb.map(texturecraft_texel::srgb_to_linear), + ChannelKind::Color if is_srgb_color && !blend_linear => rgb.map(texturecraft_texel::srgb_to_linear), // Normal channels are OpenGL (+Y up the image): a DirectX image's green flips ChannelKind::NormalMap if *normal_format == NormalFormat::DirectX => [rgb[0], 1.0 - rgb[1], rgb[2]], @@ -1575,7 +3341,8 @@ impl<'a, 'b> Texel<'a, 'b> { /// Generator input `map` at this texel: what replaces the mesh map in the generator's inputs, else the mesh map (None when not baked). fn generator_input(&mut self, generator: &Generator, map: BakedMap) -> Option { match generator.inputs.get(&map) { - Some(source) => Some(self.source(source, &Projection::default(), ChannelKind::Scalar)[0]), + // Keep legacy sampling for generator inputs without a sampling setting + Some(source) => Some(self.source(source, &Projection::default(), Sampling::SAVED_BEFORE, ChannelKind::Scalar)[0]), None => self.baked(map), } } @@ -1629,7 +3396,7 @@ impl<'a, 'b> Texel<'a, 'b> { } // Replay the prefix to record anchors skipped by the precomputed filter - if let Some(last) = plan.effects.iter().take(skip).rposition(|e| matches!(e.kind, EffectKind::Anchor)) { + if let Some(last) = plan.effects.iter().take(skip).rposition(|e| matches!(*e.kind, EffectKind::Anchor)) { self.mask_effects(plan, plan.background, 0, last + 1); } self.mask_effects(plan, value, skip, plan.effects.len()) @@ -1662,7 +3429,10 @@ impl<'a, 'b> Texel<'a, 'b> { coverage *= 1.0 - stroke; } else { // Clone and smudge show the values they carry instead of the mask gray - let deposited = preview.carried_mask.as_ref().map_or(preview.mask_value, |carried| from_u16(carried.get(self.x, self.y)[0])); + let deposited = preview.carried_mask.as_ref().map_or_else( + || preview.mask_gray.at(self.x, self.y, (self.inp.gbuf.width, self.inp.gbuf.height)), + |carried| from_u16(carried.get(self.x, self.y)[0]), + ); painted = deposited * stroke + painted * (1.0 - stroke); coverage = stroke + coverage * (1.0 - stroke); } @@ -1672,34 +3442,48 @@ impl<'a, 'b> Texel<'a, 'b> { value += (blend1(effect.blend, value, layer_value) - value) * coverage * opacity; } } - EffectKind::Fill { source, projection } => { - let fill = self.source(source, projection, ChannelKind::Scalar)[0]; - value += (blend1(effect.blend, value, fill) - value) * opacity * self.cover(std::iter::once(source), projection); + EffectKind::Fill { source, projection, sampling } => { + let projection = effect.projection.as_ref().unwrap_or(projection); + let once = |texel: &mut Self| { + let fill = texel.source(source, projection, *sampling, ChannelKind::Scalar); + let cover = if effect.covers_all { 1.0 } else { texel.cover(std::iter::once(source), projection, *sampling, effect.depth.as_deref()) }; + (fill, cover) + }; + + // Sampled directly without symmetry, as `Texel::fill_place_texel` is + let ([fill, ..], cover) = if takes_symmetry(projection, *sampling) { self.symmetric(projection, *sampling, once) } else { once(self) }; + value += (blend1(effect.blend, value, fill) - value) * opacity * cover; } EffectKind::Generator(generator) => { let generated = self.generator(generator, effect.curvature_sizes.as_deref()); value += (blend1(effect.blend, value, generated) - value) * opacity; } EffectKind::Levels(levels) => value += (levels.apply(value) - value) * opacity, + EffectKind::Filter(filter @ Filter::GradientMap { debug: true, .. }) => { + let ramp = effect.ramp_at(filter, self.coords().uv.x.rem_euclid(1.0)).map_or(value, lum); + value += (ramp - value) * opacity; + } + EffectKind::Filter(Filter::GrayscaleConversion(conversion)) => { + let read = match &effect.input { + Some(source) => self.source(source, &Projection::default(), Sampling::default(), ChannelKind::Color), + None => [value; 3], + }; + value += (conversion.gray(read, 1.0) - value) * opacity; + } EffectKind::Filter(filter) => { - // A mask is gray (HSL only changes its lightness); neighbourhood filters come precomputed through `MaskPlan::start` - let filtered = filter.point(ChannelKind::Scalar, [value; 3]).map_or(value, |gray| gray[0]); + // A gray mask uses HSL lightness and reads neighbourhoods from the prepared mask plan + let filtered = effect.point(filter, ChannelKind::Scalar, [value; 3]).map_or(value, |gray| gray[0]); value += (filtered - value) * opacity; } - EffectKind::ColorSelection { colors, tolerance } => { - let id = self.baked_color(BakedMap::Id); - let within = |picked: &[f32; 3], color: [f32; 3]| (0..3).all(|component| (picked[component] - color[component]).abs() <= *tolerance); - let selected = if id.is_some_and(|color| colors.iter().any(|picked| within(picked, color))) { 1.0 } else { 0.0 }; - value += (blend1(effect.blend, value, selected) - value) * opacity; + EffectKind::ColorSelection(selection) => { + let (selected, cover) = selection.value(self.id_color(selection.id_map.as_deref())); + value += (blend1(effect.blend, value, selected) - value) * opacity * cover; } - EffectKind::Compare { op, value: compared, tolerance } => { - let pass = match op { - CompareOp::LesserThan => value < *compared, - CompareOp::GreaterThan => value > *compared, - CompareOp::WithinTolerance => (value - compared).abs() <= *tolerance, - }; - let result = if pass { 1.0 } else { 0.0 }; - value += (result - value) * opacity; + EffectKind::Compare { op, value: constant, tolerance, left, right, channel, hardness } => { + let left = self.compare_side(*left, *channel, plan, value, *constant); + let right = self.compare_side(*right, *channel, plan, value, *constant); + let compared = op.mask(left, right, *tolerance, *hardness); + value += (blend1(effect.blend, value, compared) - value) * opacity; } // Every channel of a mask anchor reads the mask's gray @@ -1712,61 +3496,140 @@ impl<'a, 'b> Texel<'a, 'b> { value.clamp(0.0, 1.0) } - /// Composite `nodes` over `acc`, recording anchors. Returns true when it reached the `stop` - /// layer (`acc` then holds the stack below it). + /// What one side of a compare effect in mask `plan` reads at this texel (0..1): `mask` is the mask so far + fn compare_side(&mut self, side: CompareSource, channel: Channel, plan: &MaskPlan, mask: f32, constant: f32) -> f32 { + let stack_below = self.below; + let below = || stack_below.and_then(|acc| acc.get(channel.index()).copied()).unwrap_or_else(|| channel.default_value()); + let read = match side { + CompareSource::ThisMask => return mask, + CompareSource::Constant => return constant, + CompareSource::LayersBelow => below(), + CompareSource::ThisLayer => { + let own = plan.layer.as_ref().and_then(|(content, chans)| { + let chan_plan = chans.iter().find(|chan_plan| chan_plan.ch == channel.index())?; + self.content(content, chan_plan) + }); + + // Where the layer is empty (or thin) it shows the stack below it + let below = below(); + own.map_or(below, |(value, coverage)| mix3(below, value, coverage)) + } + }; + match channel.kind() { + ChannelKind::Color | ChannelKind::NormalMap => lum(read), + ChannelKind::Scalar => read[0], + ChannelKind::Signed => read[0] * 0.5 + 0.5, + } + } + + /// Composite `nodes` over `acc`, recording anchors; true when it reached the `stop` layer (`acc` then holds the stack below it) fn eval(&mut self, nodes: &[Node], acc: &mut Acc) -> bool { - for n in nodes { - if self.stop == Some(n.id) { + for node in nodes { + if self.stop == Some(node.draw) { + self.below = Some(*acc); return true; } - let m = self.tape_mask(n); - match &n.content { + if node.mask.as_ref().is_some_and(|mask| mask.layer.is_some()) { + self.below = Some(*acc); + } + let mask = self.tape_mask(node); + match &node.content { // Masked-out groups still run when they record anchors or hold the stop layer - Content::Group(children) if m > 0.0 || n.has_anchor || self.stop.is_some() => { + Content::Group(children) if mask > 0.0 || node.has_anchor || self.stop.is_some() => { let mut inner = *acc; if self.eval(children, &mut inner) { return true; } - if m > 0.0 { - mix_group(acc, &inner, &n.chans, m); + if mask > 0.0 { + mix_group(acc, &inner, &node.chans, mask); } } - Content::Fill(_) | Content::Paint { .. } if m > 0.0 => { - let before = if n.anchors.iter().any(|a| a.1.is_some()) { Some(*acc) } else { None }; - for c in &n.chans { - if let Some((v, cov)) = self.tape_content(&n.content, c) { - apply(acc, c, v, cov, m); + Content::Fill { .. } | Content::Paint { .. } if mask > 0.0 => { + let before = if node.anchors.iter().any(|(_, cut)| cut.is_some()) { Some(*acc) } else { None }; + + // A layer lit by its material evaluates its other channels first (see `Texel::lit_content`) + if node.lights { + self.lit_content(node, acc, mask); + } else { + self.lit = None; + for chan_plan in &node.chans { + if let Some((value, coverage)) = self.tape_content(&node.content, chan_plan) { + apply(acc, chan_plan, value, coverage, mask); + } } } - // Anchors inside the content stack read the stack cut at that point - for (a, cut) in &n.anchors { - let rec = match (cut, before) { - (Some(k), Some(mut b)) => { - for c in &n.chans { - if let Some((v, cov)) = self.content_to(&n.content, c, *k) { - apply(&mut b, c, v, cov, m); + // Anchors inside the content stack read the stack cut at that point, lit by the same material + for (anchor, cut) in &node.anchors { + let recorded = match (cut, before) { + (Some(cut), Some(mut cut_acc)) => { + for chan_plan in &node.chans { + if let Some((value, coverage)) = self.content_to(&node.content, chan_plan, *cut) { + apply(&mut cut_acc, chan_plan, value, coverage, mask); } } - b + cut_acc } _ => *acc, }; - self.anchors.push((*a, rec, false)); + self.anchors.push((*anchor, recorded, false)); } + self.lit = None; continue; } _ => {} } - for (a, _) in &n.anchors { - self.anchors.push((*a, *acc, false)); + for (anchor, _) in &node.anchors { + self.anchors.push((*anchor, *acc, false)); } } false } + /// Lay a layer lit by its material over `acc` under `mask`: its other channels go first, each evaluated once, and `self.lit` holds them over the stack below for its base colour's lighting + #[inline(never)] + fn lit_content(&mut self, node: &Node, acc: &mut Acc, mask: f32) { + let base = Channel::BaseColor.index(); + let (material, others) = self.material(node, *acc, mask); + self.lit = Some(material); + + for chan_plan in &node.chans { + let content = match others.get(chan_plan.ch) { + Some(other) if chan_plan.ch != base => *other, + _ => self.tape_content(&node.content, chan_plan), + }; + if let Some((value, coverage)) = content { + apply(acc, chan_plan, value, coverage, mask); + } + } + } + + /// Layer `node`'s other channels than its base colour laid over `below` under `mask`, and each one's content + fn material(&mut self, node: &Node, below: Acc, mask: f32) -> (Acc, ChannelContents) { + let base = Channel::BaseColor.index(); + let mut others = [None; NCH]; + let mut material = below; + for chan_plan in node.chans.iter().filter(|chan_plan| chan_plan.ch != base) { + let content = self.tape_content(&node.content, chan_plan); + if let Some((value, coverage)) = content { + apply(&mut material, chan_plan, value, coverage, mask); + } + if let Some(slot) = others.get_mut(chan_plan.ch) { + *slot = content; + } + } + (material, others) + } + + /// Light layer `node`'s base colour as the full render does, after [`Texel::anchors_below`] recorded the stack below it + fn light(&mut self, node: &Node) { + let below = self.below.unwrap_or_else(|| Channel::ALL.map(Channel::default_value)); + let mask = self.node_mask(node); + self.lit = Some(self.material(node, below, mask).0); + } + /// [`Texel::eval`] of the whole stack over `acc`, split along the path to the hot layer /// (`levels`, top level first). Cold (`warm` false) it evaluates everything, leaving in /// `accs` the stack before the path layer of each level and recording on `tape` the masks @@ -1777,8 +3640,8 @@ impl<'a, 'b> Texel<'a, 'b> { /// is identical. fn eval_split(&mut self, mut acc: Acc, levels: &[LevelPlan], accs: &mut [Acc], masks: &mut [f32], warm: bool, tape: &mut Tape<'b>) -> Acc { let last = levels.len().saturating_sub(1); - // Down the path: the deepest level the stack reaches (a folder masked out or not drawn - // here stops it). + + // A hidden or masked folder limits how far the evaluator descends let mut reach = last; for (d, lv) in levels.iter().enumerate() { if !warm { @@ -1790,6 +3653,7 @@ impl<'a, 'b> Texel<'a, 'b> { if d == last { break; } + let m = match &lv.at { Some(g) => self.taped(tape, |t| t.tape_mask(g)), None => 0.0, @@ -1800,16 +3664,19 @@ impl<'a, 'b> Texel<'a, 'b> { if m > 0.0 { continue; } + reach = d; break; } + let mut acc = accs.get(reach).copied().unwrap_or(acc); if reach == last && let Some(hot) = levels.get(last).and_then(|l| l.at.as_ref()) { self.eval(std::slice::from_ref(hot), &mut acc); } - // Back up: the layers after the path, then each folder's mix over the stack outside it. + + // Back up: the layers after the path, then each folder's mix over the stack outside it for d in (0..=reach).rev() { if let Some(lv) = levels.get(d) { self.taped(tape, |t| t.eval(&lv.above, &mut acc)); @@ -1851,59 +3718,62 @@ impl<'a, 'b> Texel<'a, 'b> { if tri == NO_TRI { return true; } + let first = tri.saturating_mul(3); let subs = &self.inp.mesh.submeshes; let holds = |k: usize| subs.get(k).is_some_and(|s| s.start <= first && first < s.start.saturating_add(s.count)); - // Submeshes are in index order; anything else is searched. + + // Submeshes are in index order; anything else is searched let k = subs.partition_point(|s| s.start <= first).checked_sub(1).filter(|k| holds(*k)).or_else(|| (0..subs.len()).find(|k| holds(*k))); k.and_then(|k| allowed.get(k).copied()).unwrap_or(true) } - /// Record the anchors of the stack below layer `id` (`full` is the planned stack), to - /// evaluate that layer on its own. - fn anchors_below(&mut self, full: &[Node], id: LayerId) { + /// Record the anchors of the stack below layer `id` (`full` is the planned stack), to evaluate that layer on its own + fn anchors_below(&mut self, full: &[Node], draw: (LayerId, usize)) { self.anchors.clear(); - self.stop = Some(id); + self.stop = Some(draw); let mut acc = Channel::ALL.map(Channel::default_value); self.eval(full, &mut acc); self.stop = None; } - /// Straight value and coverage of one channel of a paint or fill layer at this texel - /// (content effects and live stroke preview included). None where the layer is empty. + /// Straight value and coverage of one channel of a paint or fill layer at this texel (content effects and live stroke preview included); None where the layer is empty fn content(&mut self, content: &Content, c: &ChanPlan) -> Option<([f32; 3], f32)> { self.content_to(content, c, usize::MAX) } - /// [`Texel::content`] with only the first `end` visible content effects. - fn content_to(&mut self, content: &Content, c: &ChanPlan, end: usize) -> Option<([f32; 3], f32)> { - let start = c.start.filter(|(k, _)| *k < end); - let (mut v, mut cov, skip) = match start.and_then(|(k, f)| f.get(self.x, self.y).map(|d| (k, d))) { - Some((k, d)) => { - let px = |i: usize| d.get(i).copied().unwrap_or(0.0); - ([px(0), px(1), px(2)], px(3), k + 1) + /// [`Texel::content`] with only the first `end` visible content effects + fn content_to(&mut self, content: &Content, chan_plan: &ChanPlan, end: usize) -> Option<([f32; 3], f32)> { + let start = chan_plan.start.and_then(|(stage, field)| { + if stage < end { + Some((stage, field)) + } else { + field.anchor_stages.iter().rev().find(|(stage, _)| *stage < end).map(|(stage, field)| (*stage, field)) + } + }); + let (mut value, mut coverage, skip) = match start.and_then(|(stage, field)| field.get(self.x, self.y).map(|texel| (stage, texel))) { + Some((stage, texel)) => { + let component = |i: usize| texel.get(i).copied().unwrap_or(0.0); + ([component(0), component(1), component(2)], component(3), stage + 1) } None => { - let (v, cov) = match content { - Content::Fill(f) => { - let ch = Channel::ALL.get(c.ch).copied()?; - // A channel without a source fills with its default (no clone per texel). - let v = match f.sources.get(&ch) { - Some(s) => self.source(s, &f.projection, ch.kind()), - None => ch.default_value(), - }; - (v, self.cover(f.sources.values(), &f.projection)) + let (value, coverage) = match content { + Content::Fill { fill, projection, depth, covers_all } => { + let ch = Channel::ALL.get(chan_plan.ch).copied()?; + let source = fill.sources.get(&ch); + let projection = projection.as_deref().unwrap_or(&fill.projection); + self.fill_place_texel(FillPlace { fill, projection, depth: depth.as_deref(), covers_all: *covers_all }, source, ch) } - Content::Paint { preview } => self.painted(c.data.as_deref(), c, *preview), + Content::Paint { preview } => self.painted(chan_plan.data.as_deref(), chan_plan, *preview), Content::Group(_) => return None, }; - (v, cov, 0) + (value, coverage, 0) } }; - for e in c.effects.iter().take(end).skip(skip) { - (v, cov) = self.content_effect(e, c, v, cov); + for effect in chan_plan.effects.iter().take(end).skip(skip) { + (value, coverage) = self.content_effect(effect, chan_plan, value, coverage); } - (cov > 0.0).then_some((v, cov.min(1.0))) + (coverage > 0.0).then_some((value, coverage.min(1.0))) } /// Straight value and coverage of painted data of one channel (premultiplied values plus @@ -1911,7 +3781,8 @@ impl<'a, 'b> Texel<'a, 'b> { fn painted(&mut self, data: Option<&[u16]>, c: &ChanPlan, preview: bool) -> ([f32; 3], f32) { let pv = if preview { self.inp.preview } else { None }; let mut sa = pv.map(|p| (self.stroke * p.opacity).clamp(0.0, 1.0)).unwrap_or(0.0); - // Projection: the stencil's alpha shapes the stroke and its color is the base color. + + // Projection: the stencil's alpha shapes the stroke and its color is the base color let stencil = match pv.and_then(|p| p.stencil.as_ref()) { Some(st) if sa > 0.0 => { let s = self.world().and_then(|w| st.sample_world(w)); @@ -1957,42 +3828,109 @@ impl<'a, 'b> Texel<'a, 'b> { if cov <= 0.0 { return ([0.0; 3], 0.0); } + let inv = 1.0 / cov.max(1e-5); let v = if c.comps == 3 { val.map(|x| x * inv) } else { [val[0] * inv; 3] }; (v, cov.min(1.0)) } - /// Apply one content effect to a channel's straight value and coverage. - fn content_effect(&mut self, e: &EffectPlan, c: &ChanPlan, v: [f32; 3], cov: f32) -> ([f32; 3], f32) { - let o = e.opacity.clamp(0.0, 1.0); - match e.kind { + /// Apply one content effect to a channel's straight value and coverage + fn content_effect(&mut self, effect: &EffectPlan, chan_plan: &ChanPlan, value: [f32; 3], coverage: f32) -> ([f32; 3], f32) { + if effect.blend == BlendMode::Disable && effect.kind.blends() { + return (value, coverage); + } + + let opacity = effect.opacity.clamp(0.0, 1.0); + match effect.kind { EffectKind::Paint | EffectKind::Path(_) => { - let (p, pc) = self.painted(e.data.as_deref(), c, e.preview); - over(c, e.blend, v, cov, p, pc * o) + let (painted, painted_coverage) = self.painted(effect.data.as_deref(), chan_plan, effect.preview); + over(chan_plan, effect.blend, value, coverage, painted, painted_coverage * opacity) } - EffectKind::Material(f) => match Channel::ALL.get(c.ch).and_then(|ch| f.sources.get(ch).map(|s| (*ch, s))) { - Some((ch, s)) => { - let p = self.source(s, &f.projection, ch.kind()); - let w = o * self.cover(f.sources.values(), &f.projection); - over(c, e.blend, v, cov, p, w) + EffectKind::Material(fill) => match Channel::ALL.get(chan_plan.ch).and_then(|ch| fill.sources.get(ch).map(|source| (*ch, source))) { + Some((ch, source)) => { + let projection = effect.projection.as_ref().unwrap_or(&fill.projection); + let place = FillPlace { fill, projection, depth: effect.depth.as_deref(), covers_all: effect.covers_all }; + let (material_value, weight) = self.fill_place_texel(place, Some(source), ch); + over(chan_plan, effect.blend, value, coverage, material_value, weight * opacity) } - None => (v, cov), + None => (value, coverage), }, - EffectKind::Levels(l) => (mix3(v, per_unit(c.kind, v, |x| l.apply(x)), o), cov), - // Baked lighting reads the texel's normal and occlusion, and lights the base color only. - EffectKind::Filter(f @ Filter::BakedLighting { .. }) => match Channel::ALL.get(c.ch) { + EffectKind::Levels(levels) => match Channel::ALL.get(chan_plan.ch) { + Some(&channel) if levels.remaps(channel) => (mix3(value, per_unit(chan_plan.kind, value, |x| levels.apply(x)), opacity), coverage), + _ => (value, coverage), + }, + // Baked lighting reads the texel's normal and occlusion, and lights the base color only + EffectKind::Filter(filter @ Filter::BakedLighting { .. }) => match Channel::ALL.get(chan_plan.ch) { Some(Channel::BaseColor) => { - let nrm = self.coords().nrm.to_array(); - let k = f.baked_light(nrm, self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0)).unwrap_or(1.0); - (mix3(v, v.map(|x| (x * k).clamp(0.0, 1.0)), o), cov) + let ao = self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0); + let lit = match &effect.stylized { + Some(stylized) => { + let nrm = self.lit_normal(stylized.relief()); + let curvature = self.baked(BakedMap::Curvature).unwrap_or(FLAT_CURVATURE); + let material = self.lit.unwrap_or_else(|| Channel::ALL.map(Channel::default_value)); + stylized.shade(value, nrm, [ao, curvature], &material) + } + None => { + let factor = filter.baked_light(self.coords().nrm.to_array(), ao).unwrap_or(1.0); + value.map(|x| (x * factor).clamp(0.0, 1.0)) + } + }; + (mix3(value, lit, opacity), coverage) } - _ => (v, cov), + _ => (value, coverage), }, - // Neighbourhood filters come precomputed through `ChanPlan::start`. - EffectKind::Filter(f) => (f.point(c.kind, v).map_or(v, |out| mix3(v, out, o)), cov), - // Anchors are recorded by `eval`; mask-only effects leave content as it is. - EffectKind::Anchor | EffectKind::Fill { .. } | EffectKind::Generator(_) | EffectKind::ColorSelection { .. } | EffectKind::Compare { .. } => { - (v, cov) + // Environment lighting reads the texel's normal, occlusion and metal, and lights the base color only + EffectKind::Filter(Filter::EnvironmentLighting { horizontal, vertical, exposure, height_intensity, ambient_occlusion, specular_occlusion }) => { + match (Channel::ALL.get(chan_plan.ch), &effect.environment) { + (Some(Channel::BaseColor), Some(environment)) => { + let ao = self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0); + let nrm = Vec3::from(self.detail_normal(height_intensity / ENVIRONMENT_HEIGHT_UNIT)); + let light = environment.irradiance(nrm, horizontal.to_radians(), vertical.to_radians()) + * exposure.clamp(-Filter::ENVIRONMENT_EXPOSURE_STOPS, Filter::ENVIRONMENT_EXPOSURE_STOPS).exp2(); + let material = self.lit.unwrap_or_else(|| Channel::ALL.map(Channel::default_value)); + let lit = EnvironmentSh::shade(value, light, ao, [*ambient_occlusion, *specular_occlusion], &material); + (mix3(value, lit, opacity), coverage) + } + _ => (value, coverage), + } + } + + // PBR Validate checks the base color against the layer's metal and leaves the other channels as they are + EffectKind::Filter(Filter::PbrValidate(validate)) => match Channel::ALL.get(chan_plan.ch) { + Some(Channel::BaseColor) => { + let metal = self.lit.and_then(|material| material.get(Channel::Metallic.index()).map(|metal| metal[0])).unwrap_or(0.0); + (mix3(value, validate.check(value, metal), opacity), coverage) + } + _ => (value, coverage), + }, + // A gradient's debug view shows its ramp left to right across each UV tile + EffectKind::Filter(filter @ Filter::GradientMap { debug: true, .. }) => { + let ramp = effect + .ramp_at(filter, self.coords().uv.x.rem_euclid(1.0)) + .map(|color| if chan_plan.kind == ChannelKind::Color { color } else { [lum(color); 3] }); + (ramp.map_or(value, |ramp| mix3(value, ramp, opacity)), coverage) + } + + // Posterize with Apply to Alpha steps the content's coverage too + EffectKind::Filter(filter @ Filter::Posterize { levels, alpha: true }) => { + let stepped = coverage + (posterize(coverage, *levels) - coverage) * opacity; + (filter.point(chan_plan.kind, value).map_or(value, |out| mix3(value, out, opacity)), stepped) + } + + // Grayscale Conversion weighs the coverage as Alpha, or reads its Custom Input + EffectKind::Filter(Filter::GrayscaleConversion(conversion)) => { + let (custom_input, alpha) = match &effect.input { + Some(source) => (Some(self.source(source, &Projection::default(), Sampling::default(), ChannelKind::Color)), 1.0), + None => (None, coverage), + }; + (mix3(value, conversion.channel_value(chan_plan.kind, value, custom_input, alpha), opacity), coverage) + } + + // Neighbourhood filters come precomputed through `ChanPlan::start` + EffectKind::Filter(filter) => (effect.point(filter, chan_plan.kind, value).map_or(value, |out| mix3(value, out, opacity)), coverage), + // Anchors are recorded by `eval`; mask-only effects leave content as it is + EffectKind::Anchor | EffectKind::Fill { .. } | EffectKind::Generator(_) | EffectKind::ColorSelection(_) | EffectKind::Compare { .. } => { + (value, coverage) } } } @@ -2028,8 +3966,42 @@ pub fn composite_tiles(inp: &Inputs, out: &mut Composite, tiles: &[(u32, u32)]) pub const BLOCK: u32 = 16; /// [`composite_tiles`], serving everything but the hot layer from `below` where it can (and -/// filling it). Results are identical to [`composite_tiles`]. -pub fn composite_tiles_cached(inp: &Inputs, out: &mut Composite, tiles: &[(u32, u32)], mut below: Option<&mut BelowCache>) { +/// filling it). The borrowed mesh is fingerprinted once per batch. Callers with an owned mesh +/// can use [`composite_tiles_with_projectors`] for constant-time identity checks. +pub fn composite_tiles_cached(inputs: &Inputs, out: &mut Composite, tiles: &[(u32, u32)], mut below: Option<&mut BelowCache>) { + if let Some(cache) = below.as_deref_mut() { + cache.bind_borrowed_mesh(inputs.mesh); + } + + let projectors = ProjectorDepthCache::default(); + let inputs = EvaluationInputs::new(inputs, &projectors); + composite_evaluation_tiles(&inputs, out, tiles, below); +} + +/// Composite tile batches with a reusable cache for the mesh owned by the caller. +pub fn composite_tiles_with_projectors( + inputs: &Inputs, + mesh: &Arc, + projectors: &mut ProjectorDepthCache, + out: &mut Composite, + tiles: &[(u32, u32)], + mut below: Option<&mut BelowCache>, +) { + if !std::ptr::eq(inputs.mesh, mesh.as_ref()) { + composite_tiles_cached(inputs, out, tiles, None); + return; + } + + projectors.bind(mesh); + if let Some(cache) = below.as_deref_mut() { + cache.bind_mesh(mesh); + } + + let inputs = EvaluationInputs::new(inputs, projectors); + composite_evaluation_tiles(&inputs, out, tiles, below); +} + +fn composite_evaluation_tiles(inp: &EvaluationInputs, out: &mut Composite, tiles: &[(u32, u32)], mut below: Option<&mut BelowCache>) { let Ok(set) = inp.project.texture_set(inp.ts) else { return }; if (inp.gbuf.width, inp.gbuf.height) != (out.resolution, out.height) { return; @@ -2047,7 +4019,11 @@ pub fn composite_tiles_cached(inp: &Inputs, out: &mut Composite, tiles: &[(u32, blocks.entry((t.1 / BLOCK, t.0 / BLOCK)).or_default().push(*t); } - let channels = set.channel_list(); + let channels = evaluation_channels(inp, set.channel_list()); + if !blocks.is_empty() && channels.contains(&Channel::BaseColor) && uses_environment(inp.project, &set.stack, 0) { + inp.environment(); + } + let hot = split.as_deref().and_then(<[Level]>::last); // A stroke preview is absent from StackKey, so it disables field retention @@ -2083,7 +4059,7 @@ pub fn composite_tiles_cached(inp: &Inputs, out: &mut Composite, tiles: &[(u32, // Filter the current and following tiles as one run let planned_tiles: Vec<(u32, u32)> = block.iter().chain(&ahead).copied().collect(); let uncached_planned_tiles: Vec<(u32, u32)> = planned_tiles.iter().copied().filter(uncached).collect(); - let fields = Arc::new(block_fields(inp, &channels, &set.stack, hot, &uncached_planned_tiles, &planned_tiles)); + let fields = Arc::new(block_fields(inp, &channels, &set.stack, split.as_deref(), &uncached_planned_tiles, &planned_tiles)); let hot_tiles: std::collections::BTreeSet<(u32, u32)> = planned_tiles.iter().copied().collect(); let stack_tiles = if hot.is_some() && uncached_planned_tiles.len() < planned_tiles.len() { uncached_planned_tiles.into_iter().collect() @@ -2095,7 +4071,7 @@ pub fn composite_tiles_cached(inp: &Inputs, out: &mut Composite, tiles: &[(u32, } fields } - _ => Arc::new(block_fields(inp, &channels, &set.stack, hot, &fresh, block)), + _ => Arc::new(block_fields(inp, &channels, &set.stack, split.as_deref(), &fresh, block)), }; let quota = match below.as_deref() { @@ -2105,7 +4081,7 @@ pub fn composite_tiles_cached(inp: &Inputs, out: &mut Composite, tiles: &[(u32, }; let cached = below.as_deref().zip(split.as_deref()); - let records = composite_block(inp, &set.stack, out, block, cached, quota, &fields); + let records = composite_block(inp, (&set.stack, &channels), out, block, cached, quota, &fields); if let Some(b) = below.as_deref_mut() { for t in block { b.touch(*t); @@ -2122,12 +4098,34 @@ pub fn composite_tiles_cached(inp: &Inputs, out: &mut Composite, tiles: &[(u32, } } +/// Whether a visible layer in this draw needs the diffuse environment before parallel tile planning. +fn uses_environment(project: &Project, stack: &[LayerId], depth: usize) -> bool { + if depth > texturecraft_core::project::MAX_DEPTH { + return false; + } + + stack.iter().any(|id| { + let Some(own) = project.layers.get(id).filter(|layer| layer.visible) else { return false }; + let Some(layer) = project.content_layer(own.id) else { return false }; + if !layer.children().is_empty() { + return uses_environment(project, layer.children(), depth + 1); + } + + layer.blend(Channel::BaseColor).is_some_and(|blend| blend.opacity > 0.0 && blend.mode != BlendMode::Disable) + && layer.content_effects.iter().any(|effect| { + effect.visible + && matches!(effect.kind, EffectKind::Filter(Filter::EnvironmentLighting { .. })) + && effect.applied_blend(Some(Channel::BaseColor)).opacity > 0.0 + }) + }) +} + /// Whether a layer drawn by `stack` has a neighbourhood filter in its mask or content effects. -fn has_neighbourhood(inp: &Inputs, stack: &[LayerId]) -> bool { +fn has_neighbourhood(inp: &EvaluationInputs, stack: &[LayerId]) -> bool { let working_width = inp.gbuf.width; let mut order = Vec::new(); - draw_order(inp.project, stack, 0, &mut order); - order.into_iter().any(|id| { + draw_order(inp, stack, 0, DrawPlacement::default(), &mut order); + order.into_iter().any(|(id, _)| { let masked = layer_mask(inp.project, id).is_some_and(|mask| mask.enabled && neighbourhood(&mask.effects, working_width).is_some()); masked || inp.project.content_layer(id).is_some_and(|layer| !layer.is_group() && neighbourhood(&layer.content_effects, working_width).is_some()) }) @@ -2135,14 +4133,22 @@ fn has_neighbourhood(inp: &Inputs, stack: &[LayerId]) -> bool { /// The neighbourhood fields compositing `tiles` reads: those of every layer of `stack` over the tiles the cache lacks (`fresh`), /// and off the path to the `hot` layer only there; the hot layer's over all of `tiles`. -fn block_fields(inp: &Inputs, channels: &[Channel], stack: &[LayerId], hot: Option<&Level>, fresh: &[(u32, u32)], tiles: &[(u32, u32)]) -> Fields { +fn block_fields( + inp: &EvaluationInputs, + channels: &[Channel], + stack: &[LayerId], + split: Option<&[Level]>, + fresh: &[(u32, u32)], + tiles: &[(u32, u32)], +) -> Fields { + let hot = split.and_then(|levels| levels.last().zip(level_offsets(inp.project, levels).last().copied())); match hot { - Some(hot) if fresh.len() < tiles.len() => { - let mut fields = fields_of(inp, channels, stack, fresh); - fields.extend(fields_of(inp, channels, &[hot.at], tiles)); + Some((hot, around)) if fresh.len() < tiles.len() => { + let mut fields = fields_of(inp, channels, (stack, ContentsOffset::NONE), fresh); + fields.extend(fields_of(inp, channels, (&[hot.at], around), tiles)); fields } - _ => fields_of(inp, channels, stack, tiles), + _ => fields_of(inp, channels, (stack, ContentsOffset::NONE), tiles), } } @@ -2159,8 +4165,8 @@ type Joined = (Vec>>>, bool); /// Composite one block of tiles, split along the path to the hot layer when `below` holds it; /// returns what to cache (for at most `quota` tiles). fn composite_block( - inp: &Inputs, - stack: &[LayerId], + inp: &EvaluationInputs, + (stack, planned_channels): (&[LayerId], &[Channel]), out: &mut Composite, tiles: &[(u32, u32)], below: Option<(&BelowCache, &[Level])>, @@ -2178,7 +4184,7 @@ fn composite_block( let level_count = split.map_or(0, <[Level]>::len); let defaults: Acc = Channel::ALL.map(Channel::default_value); - // Tiles split into bands of rows, so a handful of tiles still keeps every thread busy. + // Tiles split into bands of rows, so a handful of tiles still keeps every thread busy let bands = TILE / BAND; let tasks: Vec<((u32, u32), u32)> = tiles.iter().flat_map(|t| (0..bands).map(move |b| (*t, b))).collect(); let mut results: Vec = tasks @@ -2186,8 +4192,8 @@ fn composite_block( .map(|&((tx, ty), band)| { let warm = cached((tx, ty)).and_then(|b| b.get(band as usize)); let record = warm.is_none() && recorded.contains(&(tx, ty)); - let levels = split.map(|l| plan_levels(inp, l, &channels, tx, ty, fields, warm.is_some())); - let nodes = if levels.is_none() { plan(inp, stack, &channels, tx, ty, 0, Some(fields)) } else { Vec::new() }; + let levels = split.map(|l| plan_levels(inp, l, planned_channels, tx, ty, fields, warm.is_some())); + let nodes = if levels.is_none() { plan(inp, stack, planned_channels, tx, ty, 0, Some(fields)) } else { Vec::new() }; let rows = (BAND * TILE) as usize; let mut level_values = vec![defaults; level_count]; let mut masks = vec![0.0f32; level_count]; @@ -2216,11 +4222,13 @@ fn composite_block( if y >= h { break; } + for lx in 0..TILE { let x = tx * TILE + lx; if x >= w { break; } + let gbuffer_index = (y * w + x) as usize; let tile_offset = (ly * TILE + lx) as usize; let band_offset = ((ly - band * BAND) * TILE + lx) as usize; @@ -2230,11 +4238,11 @@ fn composite_block( any = true; let mut texel = Texel::new(inp, x, y, tile_offset, stroke_at(preview_tile, tile_offset)); - // Reuse one anchor buffer per band. + // Reuse one anchor buffer per band texel.anchors = std::mem::take(&mut anchors); match &levels { Some(levels) => { - // The texel's stream starts with the stack at each level. + // The texel's stream starts with the stack at each level let start = match &mut tape { Tape::Record(t) => { t.resize(t.len() + slots, 0.0); @@ -2275,7 +4283,7 @@ fn composite_block( }) .collect(); - // Join the bands of each tile (in parallel; uncovered tiles are freed). + // Join the bands of each tile (in parallel; uncovered tiles are freed) let joined: Vec = results .par_chunks(bands as usize) .map(|parts| { @@ -2302,7 +4310,7 @@ fn composite_block( } } - // Tiles without covered texels cost nothing to composite: not worth caching. + // Tiles without covered texels cost nothing to composite: not worth caching if any && let Some(bands) = parts.iter_mut().map(|p| p.1.take()).collect::>>() { records.push(((tx, ty), bands)); } @@ -2433,15 +4441,17 @@ pub fn pad_tiles(out: &mut Composite, dmap: &DilationMap, tiles: &[(u32, u32)]) /// orientation of the exported maps), `gbuf.width × gbuf.height` of them; black outside the mesh /// Returns None without an enabled mask pub fn mask_texels(inputs: &Inputs, id: LayerId) -> Option> { + let projectors = ProjectorDepthCache::default(); + let inputs = &EvaluationInputs::new(inputs, &projectors); let mask = layer_mask(inputs.project, id).filter(|mask| mask.enabled)?; - let channels = inputs.project.texture_set(inputs.ts).map(|set| set.channel_list()).unwrap_or_default(); + let channels = evaluation_channels(inputs, inputs.project.texture_set(inputs.ts).map(|set| set.channel_list()).unwrap_or_default()); let (width, height) = (inputs.gbuf.width, inputs.gbuf.height); let coordinates = all_tiles(width, height); // A hidden layer's mask is left out of the stack's preparation prepare_mask_curvature_sizes(inputs, std::iter::once(mask)); - let fields = neighbourhood_fields(inputs, &channels, &coordinates); + let fields = evaluation_fields(inputs, &channels, &coordinates); let width_usize = width as usize; let tile_side = TILE as usize; let mut output = vec![0.0f32; width_usize * height as usize]; @@ -2464,17 +4474,25 @@ pub fn mask_texels(inputs: &Inputs, id: LayerId) -> Option> { /// The layer mask as a square grayscale image, using nearest texels and black outside the mesh /// Keep preview tiles at 8 bits instead of retaining the export's full float atlas -/// Returns None without an enabled mask +/// Returns None without an enabled mask or when the pixel count exceeds the supported range pub fn mask_image(inputs: &Inputs, id: LayerId, size: u32) -> Option> { + let size = size.max(1); + let pixel_count = usize::try_from(size.checked_mul(size)?).ok()?; + let projectors = ProjectorDepthCache::default(); + let inputs = &EvaluationInputs::new(inputs, &projectors); let mask = layer_mask(inputs.project, id).filter(|mask| mask.enabled)?; - let channels = inputs.project.texture_set(inputs.ts).map(|set| set.channel_list()).unwrap_or_default(); + let channels = evaluation_channels(inputs, inputs.project.texture_set(inputs.ts).map(|set| set.channel_list()).unwrap_or_default()); let (width, height) = (inputs.gbuf.width, inputs.gbuf.height); let coordinates = all_tiles(width, height); // A hidden layer's mask is left out of the stack's preparation prepare_mask_curvature_sizes(inputs, std::iter::once(mask)); - let fields = neighbourhood_fields(inputs, &channels, &coordinates); + let fields = evaluation_fields(inputs, &channels, &coordinates); + if size <= width.min(height) && (width != size || height != size) { + return Some(downsample_mask(inputs, id, mask, &channels, &fields, size)); + } + let width_usize = width as usize; let tile_side = TILE as usize; let mut atlas = vec![0u8; width_usize * height as usize]; @@ -2493,12 +4511,13 @@ pub fn mask_image(inputs: &Inputs, id: LayerId, size: u32) -> Option> { } }); - let size = size.max(1); if width == size && height == size { return Some(atlas); } - let mut output = vec![0u8; (size * size) as usize]; + let mut output = Vec::new(); + output.try_reserve_exact(pixel_count).ok()?; + output.resize(pixel_count, 0); for y in 0..size { for x in 0..size { let sample_x = (u64::from(x) * u64::from(width) / u64::from(size)) as u32; @@ -2513,6 +4532,49 @@ pub fn mask_image(inputs: &Inputs, id: LayerId, size: u32) -> Option> { Some(output) } +/// Sample a smaller mask image directly into disjoint output row groups +fn downsample_mask(inputs: &EvaluationInputs, id: LayerId, mask: &Mask, channels: &[Channel], fields: &Fields, size: u32) -> Vec { + let (width, height) = (inputs.gbuf.width, inputs.gbuf.height); + let source_at = |pixel, span| ((u64::from(pixel) * u64::from(span)) / u64::from(size)) as u32; + let first_output = |source, span| (u64::from(source) * u64::from(size)).div_ceil(u64::from(span)).min(u64::from(size)) as u32; + let mut output = vec![0; size as usize * size as usize]; + let mut destination = output.as_mut_slice(); + let mut bands = Vec::with_capacity(height.div_ceil(TILE) as usize); + + // Partition rows by the tile that contains each row's source texels + for tile_y in 0..height.div_ceil(TILE) { + let first_row = first_output(tile_y * TILE, height); + let past_row = first_output((tile_y + 1) * TILE, height); + if past_row > first_row { + let (rows, rest) = destination.split_at_mut((past_row - first_row) as usize * size as usize); + bands.push((tile_y, first_row, past_row, rows)); + destination = rest; + } + } + + bands.into_par_iter().for_each(|(tile_y, first_row, past_row, rows)| { + for tile_x in 0..width.div_ceil(TILE) { + let first_column = first_output(tile_x * TILE, width); + let past_column = first_output((tile_x + 1) * TILE, width); + if first_column == past_column { + continue; + } + + let offsets = (first_row..past_row).flat_map(|row| { + let y = source_at(row, height) % TILE; + (first_column..past_column).map(move |column| (y * TILE + source_at(column, width) % TILE) as usize) + }); + let texels = mask_tile(inputs, id, mask, channels, fields, (tile_x, tile_y), offsets); + let pixels = rows.chunks_exact_mut(size as usize).flat_map(|row| &mut row[first_column as usize..past_column as usize]); + for (pixel, (_, value)) in pixels.zip(texels) { + *pixel = (value * 255.0 + 0.5) as u8; + } + } + }); + + output +} + /// The layer mask as one-component values at the texture set's full resolution over `tiles` /// (uncovered texels read zero). Clone and smudge read it. Unlike [`mask_image`] it also reads a /// disabled mask; None when the layer has no mask. @@ -2524,11 +4586,13 @@ pub fn mask_values(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Option /// Evaluate requested tiles directly into the stroke's mask image. pub fn mask_values_into(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)], image: &mut TileImage) -> Option<()> { + let projectors = ProjectorDepthCache::default(); + let inputs = &EvaluationInputs::new(inputs, &projectors); let mask = layer_mask(inputs.project, id)?; - let channels = inputs.project.texture_set(inputs.ts).ok()?.channel_list(); + let channels = evaluation_channels(inputs, inputs.project.texture_set(inputs.ts).ok()?.channel_list()); prepare_mask_curvature_sizes(inputs, std::iter::once(mask)); - let fields = neighbourhood_fields(inputs, &channels, tiles); + let fields = evaluation_fields(inputs, &channels, tiles); let computed: Vec<((u32, u32), Vec)> = tiles .par_iter() .map(|&tile| { @@ -2551,6 +4615,8 @@ pub fn mask_values_into(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)], imag /// Mask values at texture-set coordinates, in request order; None without an enabled mask /// Uncovered and out-of-range texels read zero; neighbourhood filters also evaluate surrounding texels pub fn mask_at(inputs: &Inputs, id: LayerId, texels: &[(u32, u32)]) -> Option> { + let projectors = ProjectorDepthCache::default(); + let inputs = &EvaluationInputs::new(inputs, &projectors); let mask = layer_mask(inputs.project, id).filter(|mask| mask.enabled)?; let mut output = vec![0.0; texels.len()]; @@ -2569,13 +4635,13 @@ pub fn mask_at(inputs: &Inputs, id: LayerId, texels: &[(u32, u32)]) -> Option