diff --git a/.cargo/config.toml b/.cargo/config.toml index 5592118f..acb86eae 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -1,2 +1,7 @@ [alias] xtask = "run -p xtask --" + +# An explicit level for dependencies: Cargo drops the profile's default debug level from crates only build scripts and +# macros use, and then clippy and test each build their own copy of them. +[profile.dev.package."*"] +debug = "line-tables-only" diff --git a/.github/nightly-signing-policy.json b/.github/nightly-signing-policy.json new file mode 100644 index 00000000..92288670 --- /dev/null +++ b/.github/nightly-signing-policy.json @@ -0,0 +1,110 @@ +{ + "schema": "craft-nightly-release-policy/v3", + "repository": "storytold/texturecraft", + "repository_id": 1419654881, + "producer_workflow_id": null, + "producer_workflow_path": ".github/workflows/nightly.yml", + "producer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea", + "producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea", + "signer_workflow_path": ".github/workflows/nightly-sign.yml", + "signer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea", + "release_branch": "release", + "manual_actors": [ + "bflatastic", + "dylanmtaylor", + "echelon", + "FredApps", + "skylartaylor" + ], + "max_age_seconds": 86400, + "candidate_policy": { + "schema": "craft-nightly-candidate-policy/v3", + "epoch": "texturecraft-nightly-20261124", + "repository": "storytold/texturecraft", + "branch": "main", + "required_workflows": [ + { + "workflow_id": 384666426, + "workflow_path": ".github/workflows/ci.yml", + "jobs": [ + { + "name": "gate / gate (ubuntu-24.04)", + "app_id": 15368, + "applicability": "required" + }, + { + "name": "gate / gate (windows-latest)", + "app_id": 15368, + "applicability": "required" + } + ] + } + ], + "sonar": { + "organization": "storytold", + "project": "storytold_texturecraft", + "app_id": 12526, + "check_name": "SonarCloud Code Analysis", + "details_url": "https://sonarcloud.io/dashboard?id=storytold_texturecraft&branch=main", + "issue_types": [ + "VULNERABILITY" + ], + "accepted_conditions": [], + "required_conditions": [ + { + "metric": "new_security_rating", + "comparator": "GT", + "error_threshold": "1" + }, + { + "metric": "new_reliability_rating", + "comparator": "GT", + "error_threshold": "1" + }, + { + "metric": "new_maintainability_rating", + "comparator": "GT", + "error_threshold": "1" + }, + { + "metric": "new_coverage", + "comparator": "LT", + "error_threshold": "80" + }, + { + "metric": "new_duplicated_lines_density", + "comparator": "GT", + "error_threshold": "3" + }, + { + "metric": "new_security_hotspots_reviewed", + "comparator": "LT", + "error_threshold": "100" + } + ], + "debt": [] + } + }, + "max_artifact_bytes": 2147483648, + "automatic_signer_actors": [], + "platforms": { + "windows-x86_64": { + "unsigned_artifact_name": "nightly-unsigned-windows-x86_64", + "trust": { + "publisher_subject": "CN=Learning Machines Inc, O=Learning Machines Inc, L=Atlanta, S=Georgia, C=US" + } + }, + "linux-x86_64": { + "unsigned_artifact_name": "nightly-unsigned-linux-x86_64", + "trust": { + "fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED" + } + }, + "macos-aarch64": { + "unsigned_artifact_name": "nightly-unsigned-macos-aarch64", + "trust": { + "apple_team_id": "DJ6XS33FX8" + } + } + } +} diff --git a/.github/workflows/nightly-macos.yml b/.github/workflows/nightly-macos.yml new file mode 100644 index 00000000..75134544 --- /dev/null +++ b/.github/workflows/nightly-macos.yml @@ -0,0 +1,91 @@ +name: Nightly macOS build + +# Builds the unsigned Apple-silicon TextureCraft Nightly (packaging/macos/nightly.sh) on a hosted +# macOS runner and checks the archive as the Launcher unpacks it, ending with the bundle's version +# query (packaging/macos/nightly-verify.sh --expect unsigned). No secrets and no environment: the real +# Nightly is signed and notarized by the shared release-ref signer (craft-common-actions), which calls +# packaging/macos/nightly-sign.sh. +on: + # macOS minutes are shared with release builds: pull requests run this only with the `full-ci` + # label, never by changed paths. `labeled` so adding it starts a run. + pull_request: + types: [opened, synchronize, reopened, labeled] + workflow_dispatch: + +permissions: + contents: read + +# A newer push to a labelled PR cancels its older run. Any event that will not build (no `full-ci` +# label, or another label added) gets a group of its own, so it never cancels a real build. +concurrency: + group: nightly-macos-${{ github.event_name == 'pull_request' && contains(github.event.pull_request.labels.*.name, 'full-ci') && (github.event.action != 'labeled' || github.event.label.name == 'full-ci') && github.ref || github.run_id }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + build: + name: Nightly .app (aarch64, unsigned) + if: >- + github.event_name == 'workflow_dispatch' || + (contains(github.event.pull_request.labels.*.name, 'full-ci') && + (github.event.action != 'labeled' || github.event.label.name == 'full-ci')) + runs-on: macos-15 + timeout-minutes: 90 + env: + CARGO_TERM_COLOR: always + CARGO_INCREMENTAL: 0 + RUST_BACKTRACE: 1 + steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + # The release's pin (release.yml craft-fonts-ref), so the bundle's notices match a shipped build. + - name: Check out craft-fonts + uses: storytold/craft-common-actions/actions/checkout-craft-fonts@605d58766e8f536564da8fc81d3676ac86816dea + with: + ref: aced4137c022f1f587624d48e81ec77e1914a9cc + - uses: storytold/craft-common-actions/actions/checkout-craft-i18n@605d58766e8f536564da8fc81d3676ac86816dea + - id: rust + uses: storytold/craft-common-actions/actions/rust-channel@605d58766e8f536564da8fc81d3676ac86816dea + with: + targets: aarch64-apple-darwin + - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + with: + toolchain: ${{ steps.rust.outputs.toolchain }} + targets: ${{ steps.rust.outputs.targets }} + components: ${{ steps.rust.outputs.components }} + # A version of the prepared Nightly form for this commit; the real one comes from the feed's + # identity job. Only nightly.sh's input checks read it. + - name: Prepare a Nightly identity for this commit + run: | + set -euo pipefail + base="$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["version"].split("-")[0])')" + sha="$(git rev-parse HEAD)" + date="$(date -u +%Y-%m-%d)" + { + echo "TEXTURECRAFT_BUILD_SHA=$sha" + echo "TEXTURECRAFT_BUILD_DATE=$date" + echo "TEXTURECRAFT_VERSION=$base-nightly.${date//-/}.$GITHUB_RUN_NUMBER.$GITHUB_RUN_ATTEMPT.g${sha:0:12}" + } >>"$GITHUB_ENV" + - name: Build the unsigned Nightly bundle + env: + TEXTURECRAFT_BUILD_CHANNEL: nightly-v1 + CARGO_TARGET_DIR: ${{ runner.temp }}/nightly-targets + DIST: ${{ runner.temp }}/nightly-dist + CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts + CRAFT_FONTS_REQUIRED: "1" + run: bash packaging/macos/nightly.sh --arch aarch64 + - name: Check the archive and the bundle's version + run: bash packaging/macos/nightly-verify.sh --expect unsigned --input "$RUNNER_TEMP/nightly-dist/texturecraft-$TEXTURECRAFT_VERSION-macos-aarch64-nightly.zip" + # Keeps the verified unsigned zip briefly for keyless signer tests and hand testing. Unsigned only. + - name: Keep the unsigned archive + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: texturecraft-nightly-macos-aarch64-unsigned + path: ${{ runner.temp }}/nightly-dist/texturecraft-${{ env.TEXTURECRAFT_VERSION }}-macos-aarch64-nightly.zip + if-no-files-found: error + retention-days: 7 + compression-level: 0 diff --git a/.github/workflows/nightly-sign.yml b/.github/workflows/nightly-sign.yml new file mode 100644 index 00000000..d07db551 --- /dev/null +++ b/.github/workflows/nightly-sign.yml @@ -0,0 +1,42 @@ +name: TextureCraft release-ref nightly signer + +# Enabled for supervised manual dispatch on release. Main/release contents must match. +# A reusable callee does not change context; this must be a real top-level release dispatch. +on: + workflow_dispatch: + inputs: + producer_run_id: + description: Exact untrusted producer Actions run ID + required: true + type: string + producer_run_attempt: + description: Exact untrusted producer Actions run attempt + required: true + type: string + +permissions: {} + +concurrency: + group: texturecraft-nightly-release + cancel-in-progress: false + +jobs: + release: + # Actual context guards: official repository, manual dispatch, real release branch. + if: >- + github.repository == 'storytold/texturecraft' && + github.event_name == 'workflow_dispatch' && + github.ref == 'refs/heads/release' && github.ref_type == 'branch' + permissions: + contents: write + actions: read + checks: read + attestations: write + id-token: write + uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@605d58766e8f536564da8fc81d3676ac86816dea + with: + tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea + producer_run_id: ${{ inputs.producer_run_id }} + producer_run_attempt: ${{ inputs.producer_run_attempt }} + # No secrets: inherit or raw platform values in this caller. Only the isolated native + # callee job may bind the existing release environment and export keys in its signing step. diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml new file mode 100644 index 00000000..5345fe9a --- /dev/null +++ b/.github/workflows/nightly.yml @@ -0,0 +1,34 @@ +name: TextureCraft unsigned nightly + +# Enabled for supervised manual runs by the reviewed manual actor only; no schedule yet. +# A later explicit opt-in may add a cadence (and turn on nightly-dispatch.yml with it). +on: + workflow_dispatch: + +permissions: + contents: read + +jobs: + unsigned: + # Actual context guards only; no inherited/platform secrets. + if: >- + github.repository == 'storytold/texturecraft' && + github.ref == 'refs/heads/main' && github.ref_type == 'branch' && + (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch') + # Maximum for the reusable workflow. Its compiler narrows to contents/actions read; + # no OIDC, attestation write, release environment or platform secrets in compilation. + permissions: + contents: read + actions: read + attestations: write + id-token: write + uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea + with: + tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea + app-name: texturecraft + manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]' + craft-fonts-ref: aced4137c022f1f587624d48e81ec77e1914a9cc + # One producer run builds every listed platform for one all-or-nothing release. The pin is the + # craft-common-actions main commit that merged #339 (bounded lineage compares), on top of the + # Linux/macOS signer (#342). + platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]' diff --git a/.github/workflows/packaging-lint.yml b/.github/workflows/packaging-lint.yml index f54b0538..feb8675d 100644 --- a/.github/workflows/packaging-lint.yml +++ b/.github/workflows/packaging-lint.yml @@ -21,3 +21,7 @@ jobs: lint: # 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/packaging-lint.yml@main + with: + # Runs the Nightly synthetic suites, the launcher tests and `bash -n` here, so the checks + # that need no compiler are part of CI rather than a local step. + extra-checks-script: packaging/nightly-checks.sh diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 23727788..c8c04b32 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -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/.gitignore b/.gitignore index 0996cb2f..14362878 100644 --- a/.gitignore +++ b/.gitignore @@ -7,5 +7,11 @@ target/ /log /secrets /temp +# The shared nightly workflow checks these out into the workspace; `nightly_init` refuses a dirty tree. +/.nightly-tools +/.nightly-input /craft-fonts +/craft-i18n +__pycache__/ +*.pyc *.tcraft.tmp diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 500328aa..a895078e 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -15,6 +15,7 @@ licensed and keep their license file next to them. | `assets/app-icon/texturecraft.icns` | App icon (engraved zebra), macOS (16-1024 px) | Project owner (ArtCraft team) | Original artwork drawn in ArtCraft for TextureCraft, rendered by `packaging/icons.sh` | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | | `assets/app-icon/hicolor/{16x16,24x24,32x32,48x48,64x64,128x128,256x256,512x512}/apps/ai.storyteller.texturecraft.png` | App icon (engraved zebra), hicolor theme PNGs | Project owner (ArtCraft team) | Original artwork drawn in ArtCraft for TextureCraft, rendered by `packaging/icons.sh` | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | | `assets/app-icon/hicolor/scalable/apps/ai.storyteller.texturecraft.svg` | App icon (engraved zebra), hicolor scalable (copy of `texturecraft-small.svg`) | Project owner (ArtCraft team) | Original artwork drawn in ArtCraft for TextureCraft, vectorised with craftrules `vectorize_tile.py` | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | +| `assets/app-icon/texturecraft-nightly{,-1024}.png`, `assets/app-icon/texturecraft-nightly.{icns,ico}`, `assets/app-icon/nightly/{16,24,32,48,64,128,256,512}.png` | Nightly app icons (engraved zebra on deep copper) | Project owner (ArtCraft team) | Project-owned stable icon renders, with the background recolored by `packaging/nightly-icons.py` ([provenance and hashes](assets/app-icon/nightly-provenance.json)) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | | `assets/app-icon/LICENSE.txt`, `assets/app-icon/README.md` | App icon licence and notes | TextureCraft contributors | original | MIT OR Apache-2.0 | | `docs/images/texturecraft-workspace.png` | README screenshot: the TextureCraft workspace (a 1970s portable TV in aged cream plastic with a crayon doodle) | TextureCraft contributors | original screenshot of TextureCraft | MIT OR Apache-2.0 | | `docs/images/texturecraft-bake.png` | README screenshot: bake mode | TextureCraft contributors | original screenshot of TextureCraft | MIT OR Apache-2.0 | @@ -23,6 +24,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 +42,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..d82d26f7 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", @@ -1432,6 +1603,7 @@ dependencies = [ "raw-window-handle", "serde", "web-time", + "webbrowser", "windows-sys 0.61.2", "winit", ] @@ -1753,6 +1925,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 +2046,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 +2123,7 @@ dependencies = [ "js-sys", "libc", "r-efi 6.0.0", + "rand_core", "wasm-bindgen", ] @@ -1931,6 +2137,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 +2189,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 +2397,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 +2638,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 +2736,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 +2940,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 +3000,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 +3097,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 +3260,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 +3391,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 +3427,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 +3480,7 @@ checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807" dependencies = [ "bitflags 2.13.2", "dispatch2", + "libc", "objc2 0.6.5", "objc2-core-foundation", "objc2-io-surface", @@ -3148,6 +3510,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 +3922,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 +4192,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 +4339,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 +4784,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 +5030,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 +5053,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 +5090,7 @@ dependencies = [ "craft-update", "eframe", "egui", + "egui_kittest", "image", "log", "rfd", @@ -4687,6 +5174,7 @@ name = "texturecraft-engine" version = "0.6.1" dependencies = [ "chrono", + "craft-usd", "epaint_default_fonts", "image", "processkit", @@ -4714,6 +5202,7 @@ version = "0.6.1" dependencies = [ "base64 0.22.1", "bytemuck", + "cap-std", "craft-cms", "craft-image-codecs", "craft-materialx", @@ -4729,7 +5218,6 @@ dependencies = [ "gltf", "half", "image", - "lz4_flex", "png", "quick-xml 0.41.0", "rayon", @@ -4807,7 +5295,9 @@ dependencies = [ "craft-quit", "craft-ui", "craft-update", + "craft-usd", "craft-window", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c376774f15ae7cd3b06a7ac664f01a8645af4b83)", "eframe", "egui", "egui-phosphor", @@ -4816,6 +5306,7 @@ dependencies = [ "js-sys", "log", "pollster 0.4.0", + "raw-window-handle", "rayon", "rfd", "serde", @@ -4828,6 +5319,10 @@ dependencies = [ "wasm-bindgen", "wasm-bindgen-futures", "web-sys", + "winsafe", + "x11rb", + "xcap", + "zbus 5.19.0", "zip", ] @@ -5082,7 +5577,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8765b90061cba6c22b5831f675da109ae5561588290f9fa2317adab2714d5a6" dependencies = [ "memchr", - "nom", + "nom 8.0.0", "petgraph", ] @@ -5195,6 +5690,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 +5787,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 +5977,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 +5997,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d8eab23fefc9e41f8e841df4a9c707e8a8c4ed26e944ef69297184de2785e3be" dependencies = [ "dlib", + "libc", "log", + "memoffset", "once_cell", "pkg-config", ] @@ -5496,6 +6024,22 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "webbrowser" +version = "1.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73e91ccd4698f2647d6137e8eb17a3f1dcfd63810be9029fb2398f507279b95b" +dependencies = [ + "jni", + "log", + "ndk-context", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "url", + "web-sys", +] + [[package]] name = "webpki-root-certs" version = "1.0.11" @@ -5694,6 +6238,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 +6738,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 +6872,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 +6943,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 +6966,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" @@ -6455,9 +7100,9 @@ dependencies = [ [[package]] name = "zip" -version = "9.8.1" +version = "9.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9534624d547e3f516ecde0ed9a70d37788f01d340efcfdd03bf3ea8e163c1d0" +checksum = "2d8dbe089cf6b0448b78f5fc50139ab5aaa40d08ac07cdc1baf2c13add35fcce" dependencies = [ "constant_time_eq", "crc32fast", @@ -6497,6 +7142,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/ROADMAP.md b/ROADMAP.md index 759dfde7..cb114376 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -63,7 +63,7 @@ Why alpha. Mouse/keyboard tasks verified 3D/2D painting, undo/redo, material dra and generator editing, UV rectangle fill, UI baking, native saving and texture export. Separate command checks covered high-to-low transfer, UDIM sizes/packing and scene/material exports. The interface is recognizably close in its painting, bake and export workspaces, but still lacks -mask-thumbnail effect menus, several fill controls and a MaterialX export option. +mask-thumbnail effect menus and several fill controls. Generator depth is limited, bake equivalence is open, and hardware/performance coverage is incomplete. There were **96 open issues** on the review date; these include requests and older reports, not 96 reproduced defects. The published @@ -118,7 +118,7 @@ menu entries. Feature rows overlap and are not an additional additive score. | Baking | ~60% | TBD | All ten maps completed through the UI on CPU at 256 px and through commands on GPU at 128 px. Separate high/low normal/height transfer produced varying maps; cross-app pixel equivalence, larger assets and resolution-stable wear remain unproven | | Viewport, shading and rendering | ~70% | TBD | PBR/IBL, extra shading lobes, 3D/2D views, displacement and CPU/GPU path-tracing paths. Matching material/display behavior, larger scenes and hardware ray tracing remain open | | Color management | ~35% | TBD | Linear/sRGB handling, fixed export spaces and profile metadata; display model has Linear/ACES-filmic tone mapping. Configurable OCIO project/display workflows are absent | -| Texture and scene export | ~75% | TBD | Current PNG/UDIM/USD/GLB/MaterialX checks passed within scope. Output-package layout/content may be reworked; package contracts and consumers need separate validation. MaterialX UI output, complex materials and larger UDIM assets remain incomplete | +| Texture and scene export | ~75% | TBD | Current PNG/UDIM/USD/GLB/MaterialX checks passed within scope. Output-package layout/content may be reworked; package contracts and consumers need separate validation. MaterialX export covers OpenPBR only (no standard_surface); complex materials and larger UDIM assets remain incomplete | | Read-only `.spp` compatibility | 0% | TBD after feasibility study | Planned; no reader, version matrix or import-fidelity corpus. `.tcraft` remains the save format | | Workspace, panels and preferences | ~65% | TBD | Current views/layouts checked; narrow labels truncate. Incoming ArtCraft UI refactoring/shared components can change these surfaces; task, shortcut, accessibility and layout/preferences persistence checks must be repeated | | Automation | ~80% | TBD | Command inspection and scripted editing/export work; UI, CLI and MCP surfaces share engine commands. This review exercised the control channel and CLI, not every MCP/tool path | @@ -135,7 +135,7 @@ the legacy promise must not be carried forward automatically. The [UI gap inventory](docs/ui-parity.md#missing-controls-and-workflows) records reproduction routes and acceptance checks: mask context/save/export actions; independent U/V tiling, -filtering/wrap, physical-size and warp/per-tile projections; MaterialX UI output; +filtering/wrap, physical-size and warp/per-tile projections; and configurable color-management settings. Generator depth and narrow-layout readability are tracked as partial areas. Direct hardness/angle controls and polygon/UV rectangle fill already exist; older reports must not turn them into fresh missing-feature claims. diff --git a/apps/texturecraft-cli/build.rs b/apps/texturecraft-cli/build.rs index 37e0bd12..d58a4323 100644 --- a/apps/texturecraft-cli/build.rs +++ b/apps/texturecraft-cli/build.rs @@ -1,2 +1,71 @@ -// The same build provenance and Windows icon/VERSIONINFO as the app; see that file. -include!("../texturecraft/build.rs"); +// Provenance for the headless CLI: the same commit and date variables as the app, and (Windows +// only) its own icon and VERSIONINFO into `texturecraft-cli.exe`. +// +// This is deliberately not an `include!` of the app's build script: that one resolves a `#[path]` +// submodule and reads the Nightly channel, neither of which a CLI build has any use for, and a +// module path inside an included script is resolved from the included file, not from here. + +use std::process::Command; + +const ICON: &str = "../../assets/app-icon/texturecraft.ico"; + +fn main() { + println!("cargo:rerun-if-changed=build.rs"); + println!("cargo:rerun-if-changed={ICON}"); + for var in ["TEXTURECRAFT_BUILD_SHA", "TEXTURECRAFT_BUILD_DATE", "TEXTURECRAFT_REQUIRE_WINRES", "SOURCE_DATE_EPOCH"] { + println!("cargo:rerun-if-env-changed={var}"); + } + println!("cargo:rustc-env=TEXTURECRAFT_BUILD_SHA={}", env_or("TEXTURECRAFT_BUILD_SHA", git_sha)); + println!("cargo:rustc-env=TEXTURECRAFT_BUILD_DATE={}", env_or("TEXTURECRAFT_BUILD_DATE", today)); + + if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") { + windows_resources(); + } +} + +fn env_or(var: &str, fallback: fn() -> Option) -> String { + std::env::var(var).ok().map(|v| v.trim().to_owned()).filter(|v| !v.is_empty()).or_else(fallback).unwrap_or_default() +} + +fn git_sha() -> Option { + let out = Command::new("git").args(["rev-parse", "HEAD"]).output().ok().filter(|o| o.status.success())?; + let sha = String::from_utf8(out.stdout).ok()?.trim().to_owned(); + (sha.len() >= 7 && sha.bytes().all(|b| b.is_ascii_hexdigit())).then_some(sha) +} + +/// UTC date of `SOURCE_DATE_EPOCH`, or of now. +fn today() -> Option { + let secs = match std::env::var("SOURCE_DATE_EPOCH") { + Ok(v) => v.trim().parse::().ok()?, + Err(_) => std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).ok()?.as_secs(), + }; + // Days since 1970-01-01 to a civil date (Howard Hinnant's algorithm, proleptic Gregorian). + let z = i64::try_from(secs / 86_400).ok()? + 719_468; + let era = z.div_euclid(146_097); + let doe = z.rem_euclid(146_097); + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let day = doy - (153 * mp + 2) / 5 + 1; + let month = if mp < 10 { mp + 3 } else { mp - 9 }; + let year = yoe + era * 400 + i64::from(month <= 2); + Some(format!("{year:04}-{month:02}-{day:02}")) +} + +fn windows_resources() { + let mut res = winresource::WindowsResource::new(); + res.set_icon(ICON) + .set("ProductName", "TextureCraft") + .set("FileDescription", "TextureCraft command-line tool") + .set("CompanyName", "Learning Machines LLC") + .set("LegalCopyright", "Copyright (c) the TextureCraft contributors. MIT OR Apache-2.0.") + .set("OriginalFilename", "texturecraft-cli.exe") + .set("InternalName", "texturecraft-cli"); + if let Err(e) = res.compile() { + if std::env::var_os("TEXTURECRAFT_REQUIRE_WINRES").is_some() { + println!("cargo::error=embedding Windows resources into texturecraft-cli.exe failed: {e}"); + } else { + println!("cargo:warning=texturecraft-cli.exe built without icon/version resources: {e}"); + } + } +} diff --git a/apps/texturecraft-cli/src/main.rs b/apps/texturecraft-cli/src/main.rs index f15dc209..c38b323a 100644 --- a/apps/texturecraft-cli/src/main.rs +++ b/apps/texturecraft-cli/src/main.rs @@ -120,8 +120,18 @@ fn version() -> String { } } +/// The desktop app's Nightly launch options. The CLI never takes them: a Nightly install ships the +/// GUI only, and a script that passes them to the CLI has the wrong program. +fn is_launch_profile_flag(arg: &str) -> bool { + arg == "--launch-profile" || arg == "--profile-root" || arg.starts_with("--launch-profile=") || arg.starts_with("--profile-root=") +} + fn main() { let args: Vec = std::env::args().skip(1).collect(); + if let Some(flag) = args.iter().find(|arg| is_launch_profile_flag(arg.as_str())) { + eprintln!("texturecraft-cli: `{flag}` is a TextureCraft desktop launch option, not a CLI argument"); + std::process::exit(2); + } let code = match args.first().map(String::as_str) { None => { eprint!("{USAGE}"); 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..7f5ee538 100644 --- a/apps/texturecraft/Cargo.toml +++ b/apps/texturecraft/Cargo.toml @@ -15,7 +15,7 @@ texturecraft-engine = { workspace = true } texturecraft-ui-egui = { workspace = true } # The control channel's token, framing and connection limits (shared with `texturecraft-cli serve`). texturecraft-automation = { workspace = true } -eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "wayland", "x11", "persistence"] } +eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "wayland", "x11", "persistence", "links"] } egui = { workspace = true } image = { workspace = true } craft-image-codecs = { workspace = true } @@ -30,7 +30,8 @@ ron = "0.12" # borderless (src/window_frame.rs; winsafe is MIT, User32 only). [target.'cfg(windows)'.dependencies] winit = { version = "0.30", default-features = false } -winsafe = { version = "0.0.29", default-features = false, features = ["user"] } +# `shell` carries SetCurrentProcessExplicitAppUserModelID, the Nightly taskbar identity (src/process_identity.rs). +winsafe = { version = "0.0.29", default-features = false, features = ["user", "shell"] } # The update helper is a copy of this program (`main`). craft-update = { workspace = true } @@ -38,5 +39,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/build.rs b/apps/texturecraft/build.rs index c77d91bd..9f712207 100644 --- a/apps/texturecraft/build.rs +++ b/apps/texturecraft/build.rs @@ -2,31 +2,78 @@ // // Shared by `texturecraft` and `texturecraft-cli` (whose build.rs `include!`s this file). // +// - Sets `TEXTURECRAFT_VERSION` for `env!`: the prepared Nightly feed identity when +// `TEXTURECRAFT_BUILD_CHANNEL=nightly-v1`, else the workspace package version. A Nightly build +// without a well-formed `TEXTURECRAFT_VERSION` fails rather than falling back to the Cargo +// version, so an archive can never carry the wrong identity. // - Always sets `TEXTURECRAFT_BUILD_SHA` (full git commit) and `TEXTURECRAFT_BUILD_DATE` // (`YYYY-MM-DD`, UTC) for `env!`. They come from the same-named environment variables (CI and // packaging/env.sh set them), else from `git` and the clock (`SOURCE_DATE_EPOCH` wins for // reproducible builds); either is an empty string when unknown, so source tarballs, wasm and // offline builds still compile. Without the env vars the commit is read when this script runs, // so a local build can show a stale commit; release builds always set the variable. -// - Windows targets only: embeds assets/app-icon/texturecraft.ico and VERSIONINFO into the exe. +// - Windows targets only: embeds the flavor's `assets/app-icon/*.ico` and VERSIONINFO into the exe. // A missing resource compiler is a warning, so a cross-compile still links, unless // `TEXTURECRAFT_REQUIRE_WINRES=1` (set by packaging/windows/package.ps1) makes it an error. -use std::process::Command; +#[path = "src/build_channel.rs"] +mod build_channel; -const ICON: &str = "../../assets/app-icon/texturecraft.ico"; +use std::process::Command; fn main() { println!("cargo:rerun-if-changed=build.rs"); - println!("cargo:rerun-if-changed={ICON}"); - for var in ["TEXTURECRAFT_BUILD_SHA", "TEXTURECRAFT_BUILD_DATE", "TEXTURECRAFT_REQUIRE_WINRES", "SOURCE_DATE_EPOCH"] { + println!("cargo:rerun-if-changed=src/build_channel.rs"); + for icon in [build_channel::windows_icon_path(false), build_channel::windows_icon_path(true)] { + println!("cargo:rerun-if-changed={icon}"); + } + for var in [ + "TEXTURECRAFT_BUILD_SHA", + "TEXTURECRAFT_BUILD_DATE", + "TEXTURECRAFT_BUILD_CHANNEL", + "TEXTURECRAFT_VERSION", + "TEXTURECRAFT_OVERRIDE_VERSION", + "TEXTURECRAFT_REQUIRE_WINRES", + "SOURCE_DATE_EPOCH", + ] { println!("cargo:rerun-if-env-changed={var}"); } + println!("cargo:rustc-check-cfg=cfg(texturecraft_nightly_v1)"); + let nightly = match std::env::var("TEXTURECRAFT_BUILD_CHANNEL").as_deref() { + Ok("nightly-v1") => { + println!("cargo:rustc-cfg=texturecraft_nightly_v1"); + true + } + // An empty value (an unset CI input) means the default stable build. + Ok("stable" | "") | Err(std::env::VarError::NotPresent) => false, + _ => { + eprintln!("unsupported TEXTURECRAFT_BUILD_CHANNEL (expected stable or nightly-v1)"); + std::process::exit(1); + } + }; + // `TEXTURECRAFT_VERSION` is the feed identity the workflow exports; the packaging scripts + // (packaging/env.sh, nightly-common.sh, linux/package.sh) spell the same value + // `TEXTURECRAFT_OVERRIDE_VERSION`, so both name the version the binary reports. + let requested = ["TEXTURECRAFT_VERSION", "TEXTURECRAFT_OVERRIDE_VERSION"] + .into_iter() + .find_map(|name| std::env::var(name).ok().map(|value| value.trim().to_owned()).filter(|value| !value.is_empty())); + let built_version = if nightly { + match requested { + Some(version) if build_channel::is_nightly_version(&version) => version, + _ => { + eprintln!("nightly-v1 requires an explicit prepared feed identity in TEXTURECRAFT_VERSION"); + std::process::exit(1); + } + } + } else { + std::env::var("CARGO_PKG_VERSION").unwrap_or_default() + }; + println!("cargo:rustc-env=TEXTURECRAFT_VERSION={built_version}"); println!("cargo:rustc-env=TEXTURECRAFT_BUILD_SHA={}", env_or("TEXTURECRAFT_BUILD_SHA", git_sha)); println!("cargo:rustc-env=TEXTURECRAFT_BUILD_DATE={}", env_or("TEXTURECRAFT_BUILD_DATE", today)); if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") { - windows_resources(); + windows_resources(nightly, &built_version); } } @@ -59,17 +106,27 @@ fn today() -> Option { Some(format!("{year:04}-{month:02}-{day:02}")) } -fn windows_resources() { +fn windows_resources(nightly: bool, built_version: &str) { let name = std::env::var("CARGO_PKG_NAME").unwrap_or_else(|_| "texturecraft".into()); - let description = if name.ends_with("-cli") { "TextureCraft command-line tool" } else { "TextureCraft 3D texture painter" }; + let description = if name.ends_with("-cli") { + if nightly { "TextureCraft Nightly command-line tool" } else { "TextureCraft command-line tool" } + } else if nightly { + "TextureCraft Nightly 3D texture painter" + } else { + "TextureCraft 3D texture painter" + }; let mut res = winresource::WindowsResource::new(); - res.set_icon(ICON) - .set("ProductName", "TextureCraft") + res.set_icon(build_channel::windows_icon_path(nightly)) + .set("ProductName", if nightly { "TextureCraft Nightly" } else { "TextureCraft" }) .set("FileDescription", description) .set("CompanyName", "Learning Machines LLC") .set("LegalCopyright", "Copyright (c) the TextureCraft contributors. MIT OR Apache-2.0.") .set("OriginalFilename", &format!("{name}.exe")) .set("InternalName", &name); + if nightly { + // The Launcher checks the PE ProductVersion against the exact feed identity, not FileVersion. + res.set("ProductVersion", built_version); + } if let Err(e) = res.compile() { if std::env::var_os("TEXTURECRAFT_REQUIRE_WINRES").is_some() { println!("cargo::error=embedding Windows resources into {name}.exe failed: {e}"); diff --git a/apps/texturecraft/src/build_channel.rs b/apps/texturecraft/src/build_channel.rs new file mode 100644 index 00000000..ebfc4a2a --- /dev/null +++ b/apps/texturecraft/src/build_channel.rs @@ -0,0 +1,62 @@ +//! The build-time nightly identity shared by the build script and its pure regression tests. +//! +//! `build.rs` includes this file (`#[path = "src/build_channel.rs"]`) and the app compiles it for +//! the same checks, so the icon and the version shape cannot drift apart between them. + +/// `X.Y.Z-nightly.YYYYMMDD...g`, the Launcher's immutable feed identity. +pub fn is_nightly_version(version: &str) -> bool { + let Some((base, suffix)) = version.split_once("-nightly.") else { return false }; + let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()); + let base: Vec<_> = base.split('.').collect(); + let parts: Vec<_> = suffix.split('.').collect(); + base.len() == 3 + && base.iter().all(|s| digits(s)) + && parts.len() == 4 + && parts[0].len() == 8 + && digits(parts[0]) + && digits(parts[1]) + && digits(parts[2]) + && parts[3].strip_prefix('g').is_some_and(|sha| sha.len() == 12 && sha.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))) +} + +/// The Windows icon embedded in the executable: the nightly art only in a nightly build. +pub fn windows_icon_path(nightly: bool) -> &'static str { + if nightly { "../../assets/app-icon/texturecraft-nightly.ico" } else { "../../assets/app-icon/texturecraft.ico" } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn windows_resource_uses_the_flavor_specific_icon_without_changing_stable() { + assert_eq!(windows_icon_path(false), "../../assets/app-icon/texturecraft.ico"); + assert_eq!(windows_icon_path(true), "../../assets/app-icon/texturecraft-nightly.ico"); + } + + #[test] + fn explicit_feed_identity_is_required_for_a_nightly_build() { + assert!(is_nightly_version("0.23.1-nightly.20261120.17.1.gabcdef012345")); + for invalid in [ + "", + "0.23.1", + "0.23.1-nightly", + "0.23.1-nightly.20261120", + "0.23.1-nightly.20261120.17.1.gABCDEF012345", + "0.23.1-nightly.20261120.17.1.gabcdef012345\n", + ] { + assert!(!is_nightly_version(invalid), "{invalid:?}"); + } + } + + #[test] + fn version_cannot_inject_a_path_or_an_extra_build_directive() { + for invalid in [ + "../0.23.1-nightly.20261120.1.1.gabcdef012345", + "0.23.1-nightly.20261120.1.1.gabcdef012345/other", + "0.23.1-nightly.20261120.1.1.gabcdef012345\ncargo:rustc-cfg=other", + ] { + assert!(!is_nightly_version(invalid)); + } + } +} diff --git a/apps/texturecraft/src/build_flavor.rs b/apps/texturecraft/src/build_flavor.rs new file mode 100644 index 00000000..294f1e19 --- /dev/null +++ b/apps/texturecraft/src/build_flavor.rs @@ -0,0 +1,94 @@ +//! The build-time channel, which is distinct from a launch selector: no runtime environment can +//! promote a stable build into the Nightly one. + +use crate::launch_profile::Profile; +use std::ffi::OsString; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BuildFlavor { + Stable, + NightlyV1, +} + +/// `TEXTURECRAFT_BUILD_CHANNEL=nightly-v1` at compile time (`build.rs`). +pub const COMPILED: BuildFlavor = if cfg!(texturecraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable }; + +/// The version this binary was built as: the prepared feed identity in a nightly build, else the +/// workspace version (`build.rs` bakes it so both flavors read it the same way). +pub const BUILT_VERSION: &str = env!("TEXTURECRAFT_VERSION"); + +/// A nightly build starts only with its profile, and a stable build only without one. +pub fn require_profile(flavor: BuildFlavor, profile: &Profile) -> Result<(), String> { + match (flavor, profile.is_nightly()) { + (BuildFlavor::NightlyV1, false) => Err("Open TextureCraft Nightly from ArtCraft Launcher".into()), + (BuildFlavor::Stable, true) => Err("This is a stable TextureCraft build; nightly-v1 requires the nightly build".into()), + _ => Ok(()), + } +} + +/// A refused nightly start explains itself in a native dialog: a release Windows build has no +/// console, and a Dock launch on macOS has none either. +pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool { + desktop_session && flavor == BuildFlavor::NightlyV1 +} + +/// `--version` or `-V` alone; a file called `--version` after `--` is never a query. +pub fn version_query(args: &[OsString]) -> bool { + matches!(args, [arg] if arg == "--version" || arg == "-V") +} + +/// The line `--version` prints: ` (nightly-v1)` in a nightly build, exactly as the +/// Launcher and the release smoke test read it. +pub fn version(flavor: BuildFlavor) -> String { + match flavor { + BuildFlavor::Stable => format!("TextureCraft {BUILT_VERSION}"), + BuildFlavor::NightlyV1 => format!("TextureCraft {BUILT_VERSION} (nightly-v1)"), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_a_nightly_desktop_refusal_requests_a_native_dialog() { + assert!(needs_native_error(BuildFlavor::NightlyV1, true)); + assert!(!needs_native_error(BuildFlavor::NightlyV1, false)); + assert!(!needs_native_error(BuildFlavor::Stable, true)); + assert!(!needs_native_error(BuildFlavor::Stable, false)); + } + + #[test] + fn nightly_build_without_a_profile_is_refused_before_startup() { + let started = std::cell::Cell::new(false); + let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true)); + assert!(result.unwrap_err().contains("ArtCraft Launcher")); + assert!(!started.get()); + } + + #[test] + fn stable_and_nightly_flavors_accept_only_their_own_profile() { + let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root")); + assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok()); + assert!(require_profile(BuildFlavor::Stable, &nightly).is_err()); + assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok()); + } + + #[test] + fn the_nightly_version_line_is_exact_and_says_its_channel() { + let nightly = version(BuildFlavor::NightlyV1); + assert!(nightly.starts_with("TextureCraft "), "{nightly}"); + assert!(nightly.ends_with(" (nightly-v1)"), "{nightly}"); + assert_eq!(nightly, format!("TextureCraft {} (nightly-v1)", BUILT_VERSION)); + assert_eq!(version(BuildFlavor::Stable), format!("TextureCraft {BUILT_VERSION}")); + } + + #[test] + fn only_a_bare_version_flag_is_a_query() { + assert!(version_query(&["--version".into()])); + assert!(version_query(&["-V".into()])); + assert!(!version_query(&["--".into(), "--version".into()])); + assert!(!version_query(&["--version".into(), "--version".into()])); + assert!(!version_query(&[])); + } +} 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/launch_profile.rs b/apps/texturecraft/src/launch_profile.rs new file mode 100644 index 00000000..84f5061f --- /dev/null +++ b/apps/texturecraft/src/launch_profile.rs @@ -0,0 +1,217 @@ +//! The Launcher's nightly-v1 bootstrap, selected before logging, updates, fonts or saved state. +//! Stable launches keep their arguments and directory policy unchanged, and no environment is +//! mutated: the profile is a value this process reads, not a variable it exports. + +use std::ffi::OsString; +use std::path::{Component, Path, PathBuf}; +use std::sync::OnceLock; + +pub const VERSION: &str = "nightly-v1"; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Profile { + Stable, + NightlyV1(PathBuf), +} + +impl Profile { + pub fn is_nightly(&self) -> bool { + matches!(self, Self::NightlyV1(_)) + } + + pub fn root(&self) -> Option<&Path> { + match self { + Self::Stable => None, + Self::NightlyV1(root) => Some(root), + } + } +} + +#[derive(Debug, PartialEq, Eq)] +pub struct Launch { + pub profile: Profile, + pub args: Vec, +} + +static PROFILE: OnceLock = OnceLock::new(); + +pub fn current() -> &'static Profile { + PROFILE.get().unwrap_or(&Profile::Stable) +} + +pub fn install(profile: Profile) -> Result<(), String> { + PROFILE.set(profile).map_err(|_| "the launch profile was already selected".into()) +} + +/// Recognize only the agreed literal selector/root pair before `--`. Everything after it is a +/// file, even when it looks like a profile flag. No filesystem or startup hook runs here. +pub fn parse(args: Vec) -> Result { + let mut selector = None; + let mut root = None; + let mut other = Vec::new(); + let mut files = Vec::new(); + let mut iter = args.iter(); + let mut delimiter = false; + while let Some(arg) = iter.next() { + if arg == "--" { + delimiter = true; + files.extend(iter.cloned()); + break; + } + if arg == "--launch-profile" || arg == "--profile-root" { + let slot = if arg == "--launch-profile" { &mut selector } else { &mut root }; + if slot.is_some() { + return Err("the profile selector and root must each occur exactly once".into()); + } + let value = iter.next().filter(|v| !v.is_empty()).ok_or("the profile selector/root needs a value")?; + if value.to_string_lossy().starts_with("--") { + return Err("the profile selector/root needs a value".into()); + } + *slot = Some(value.clone()); + } else if arg.to_string_lossy().starts_with("--launch-profile=") || arg.to_string_lossy().starts_with("--profile-root=") { + return Err("the nightly protocol requires separate literal selector/root argument tokens".into()); + } else { + other.push(arg.clone()); + } + } + match (selector, root) { + (None, None) => Ok(Launch { profile: Profile::Stable, args }), + (Some(version), Some(root)) if version == VERSION => { + if !delimiter || !other.is_empty() { + return Err("nightly-v1 accepts only its selector/root followed by -- and file names".into()); + } + let root = PathBuf::from(root); + if !root.is_absolute() || root.components().any(|c| matches!(c, Component::ParentDir)) { + return Err("the nightly profile root must be absolute and contain no parent traversal".into()); + } + Ok(Launch { profile: Profile::NightlyV1(root), args: std::iter::once(OsString::from("--")).chain(files).collect() }) + } + (Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".into()), + _ => Err("--launch-profile and --profile-root must be supplied together".into()), + } +} + +/// The Launcher's version check: the selector/root pair followed by exactly `--version` (or `-V`), +/// answered like a plain version query. Only [`parse`]'s lexical checks apply; the root is never +/// validated or touched, and `-- --version` stays a file name. +pub fn version_query(args: &[OsString]) -> bool { + let Some((last, pair)) = args.split_last() else { return false }; + if last != "--version" && last != "-V" { + return false; + } + let lexical = pair.iter().cloned().chain(std::iter::once(OsString::from("--"))).collect(); + matches!(parse(lexical), Ok(Launch { profile: Profile::NightlyV1(_), args }) if args.len() == 1) +} + +/// Validation finishes before the caller's first startup effect. Stable never calls the nightly +/// root validator, so its old directory resolution stays unchanged. +pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result) -> Result { + if let Profile::NightlyV1(root) = &launch.profile { + launch.profile = Profile::NightlyV1(validate(root)?); + } + Ok(launch) +} + +/// Resolve the selected private root before the caller's first startup effect. +pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option, exe: Option<&Path>) -> Result { + crate::profile_root::validate(root, env, exe, crate::profile_root::ensure_writable) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::cell::Cell; + + fn args(values: &[&str]) -> Vec { + values.iter().map(OsString::from).collect() + } + + fn absolute() -> &'static str { + if cfg!(windows) { r"C:\NightlyData\profiles\texturecraft" } else { "/nightly-data/profiles/texturecraft" } + } + + fn nightly() -> Vec { + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"]) + } + + #[test] + fn stable_arguments_and_directory_policy_are_unchanged() { + for argv in [args(&[]), args(&["model.glb"]), args(&["--gpu", "nvidia"]), args(&["--", "--launch-profile", "model.glb"])] { + let launch = prepare(parse(argv.clone()).unwrap(), |_| panic!("stable must never validate a nightly root")).unwrap(); + assert_eq!(launch, Launch { profile: Profile::Stable, args: argv }); + } + } + + #[test] + fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() { + let mut argv = nightly(); + argv.extend(args(&["--profile-root", "model with spaces.glb"])); + let launch = parse(argv).unwrap(); + assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute()))); + assert_eq!(launch.args, args(&["--", "--profile-root", "model with spaces.glb"])); + } + + #[test] + fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() { + for argv in [ + args(&["--launch-profile", VERSION]), + args(&["--profile-root", absolute()]), + args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]), + args(&["--launch-profile", VERSION, "--launch-profile", VERSION, "--profile-root", absolute(), "--"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--profile-root", absolute(), "--"]), + args(&["--launch-profile", VERSION, "--profile-root", "relative", "--"]), + args(&["--launch-profile", VERSION, "--profile-root", "", "--"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--gpu", "nvidia", "--"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute()]), + args(&["--launch-profile=nightly-v1", "--profile-root", absolute(), "--"]), + args(&["--launch-profile", VERSION, "--profile-root=/nightly-data/profiles/texturecraft", "--"]), + ] { + assert!(parse(argv.clone()).is_err(), "{argv:?}"); + } + } + + #[test] + fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() { + let pair = &["--launch-profile", VERSION, "--profile-root", absolute()]; + let reversed = &["--profile-root", absolute(), "--launch-profile", VERSION]; + for flag in ["--version", "-V"] { + for form in [pair, reversed] { + let mut argv = args(form); + argv.push(flag.into()); + assert!(version_query(&argv), "{argv:?}"); + } + } + for argv in [ + args(&["--version"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--version"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--gpu", "nvidia", "--version"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--version"]), + args(&["--version", "--launch-profile", VERSION, "--profile-root", absolute()]), + args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--version"]), + args(&["--launch-profile", VERSION, "--profile-root", "relative", "--version"]), + args(&["--launch-profile", VERSION, "--version"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--help"]), + ] { + assert!(!version_query(&argv), "{argv:?}"); + } + // Outside the query the strict protocol still refuses the version flag. + assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err()); + } + + #[test] + fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() { + let reached = Cell::new(false); + let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".into())).map(|_| reached.set(true)); + assert!(result.is_err()); + assert!(!reached.get()); + } + + #[test] + fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() { + let checked = PathBuf::from(absolute()).join("checked"); + let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap(); + assert_eq!(launch.profile.root(), Some(checked.as_path())); + assert!(launch.profile.is_nightly()); + } +} diff --git a/apps/texturecraft/src/main.rs b/apps/texturecraft/src/main.rs index ec60c58c..349b9275 100644 --- a/apps/texturecraft/src/main.rs +++ b/apps/texturecraft/src/main.rs @@ -5,11 +5,22 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#[cfg(test)] +mod build_channel; +mod build_flavor; mod control_server; mod gpu; +mod launch_profile; +mod nightly_session; +mod process_identity; +mod profile_root; mod window_frame; +use std::ffi::OsString; + +use launch_profile::Profile; use texturecraft_engine::Session; +use texturecraft_ui_egui::os_window::{self, LaunchIdentity}; use texturecraft_ui_egui::titlebar::TitleBar; use texturecraft_ui_egui::ui_state_store; use texturecraft_ui_egui::{TextureCraftApp, UiState}; @@ -17,14 +28,25 @@ use texturecraft_ui_egui::{TextureCraftApp, UiState}; /// The app name eframe keeps the settings under (`eframe::storage_dir`). const APP_NAME: &str = "TextureCraft"; +/// The data folder Dylan's #801 packaging lets a Stable wrapper set. A Nightly launch never reads +/// it: its profile arrives as the Launcher's literal selector/root pair, and nothing else. +const DATA_DIR_ENV: &str = "TEXTURECRAFT_DATA_DIR"; + /// The window's size when it opens, in points. const DEFAULT_SIZE: [f32; 2] = [1600.0, 960.0]; /// The smallest size the window can be resized to, in points. const MIN_SIZE: [f32; 2] = [960.0, 600.0]; const ICON_PNG: &[u8] = include_bytes!("../../../assets/app-icon/hicolor/256x256/apps/ai.storyteller.texturecraft.png"); +/// The Nightly window icon: the same artwork on the deeper background the package icon uses. +const NIGHTLY_ICON_PNG: &[u8] = include_bytes!("../../../assets/app-icon/texturecraft-nightly.png"); +/// The version line: a Nightly build names its exact feed identity and channel, and every other +/// build keeps the workspace version with the commit and date it was built from. fn version() -> String { + if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 { + return build_flavor::version(build_flavor::COMPILED); + } let sha = env!("TEXTURECRAFT_BUILD_SHA"); let short = sha.get(..7).unwrap_or(sha); let date = env!("TEXTURECRAFT_BUILD_DATE"); @@ -44,15 +66,23 @@ struct Args { power_pref: Option, } -fn parse_args() -> Result, String> { - parse_args_from(std::env::args().skip(1)) -} - fn parse_args_from>(it: I) -> Result, String> { let mut args = Args { file: None, control: None, empty: false, gpu: None, power_pref: None }; let mut it = it.into_iter(); + // Everything after `--` is a file, even when it looks like an option: the Launcher's nightly + // protocol passes the selected file that way (and a file may be called `--version`). + let mut after_delimiter = false; while let Some(a) = it.next() { + if after_delimiter { + // A Launcher hand-off may carry more than one file. Opening the first one beats a + // silent exit on a Windows build, which has no console to show the refusal on. + if args.file.is_none() { + args.file = Some(a); + } + continue; + } match a.as_str() { + "--" => after_delimiter = true, "--version" | "-V" => { println!("{}", version()); return Ok(None); @@ -119,7 +149,8 @@ fn initial_session(args: &Args) -> Session { } fn icon() -> Option { - let img = craft_image_codecs::decode(ICON_PNG).ok()?; + let png = if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 { NIGHTLY_ICON_PNG } else { ICON_PNG }; + let img = craft_image_codecs::decode(png).ok()?; Some(egui::IconData { rgba: img.to_rgba8(), width: img.width(), height: img.height() }) } @@ -134,13 +165,39 @@ fn set_taskbar_icon(w: &winit::window::Window) { } } +/// Directory for saved settings, UI state, and error logs: a Nightly launch's validated profile, +/// else `TEXTURECRAFT_DATA_DIR` (when non-empty, as a Stable package wrapper sets it), else +/// eframe's own folder for this app. +fn storage_dir() -> Option { + settings_folder( + launch_profile::current().root(), + std::env::var_os(DATA_DIR_ENV).filter(|v| !v.is_empty()).map(std::path::PathBuf::from), + eframe::storage_dir(APP_NAME), + ) +} + +/// The settings folder, in the order a launch decides it: a Nightly profile, a Stable wrapper's +/// `TEXTURECRAFT_DATA_DIR`, else eframe's own folder for this app. +/// +/// The last one is passed in rather than left to eframe. With `with_app_id` set (the Linux window +/// class the Stable entry needs), eframe derives its folder from the app id, so Stable's `app.ron` +/// — window state and the user's export presets — would move to `ai.storyteller.texturecraft` while +/// `ui.json` and `errors.log` stayed behind. `persistence_path` therefore names the file explicitly. +fn settings_folder( + profile: Option<&std::path::Path>, + wrapper_dir: Option, + legacy: Option, +) -> Option { + profile.map(std::path::Path::to_path_buf).or(wrapper_dir).or(legacy) +} + /// Preferences needed before opening the initial project or window, with legacy storage fallback. fn saved_prefs(ui_file: Option<&std::path::Path>, persistence_path: Option<&std::path::Path>) -> texturecraft_ui_egui::state::Prefs { if let Some(ui) = ui_file.and_then(ui_state_store::read) { return ui.prefs; } - let file = persistence_path.map(std::path::Path::to_path_buf).or_else(|| eframe::storage_dir(APP_NAME).map(|folder| folder.join("app.ron"))); + let file = persistence_path.map(std::path::Path::to_path_buf).or_else(|| storage_dir().map(|folder| folder.join("app.ron"))); let saved = file.and_then(|file| std::fs::read_to_string(file).ok()); let entries = saved.and_then(|text| ron::from_str::>(&text).ok()); entries.and_then(|entries| ron::from_str::(entries.get("ui")?).ok()).map(|ui| ui.prefs).unwrap_or_default() @@ -151,6 +208,10 @@ fn saved_prefs(ui_file: Option<&std::path::Path>, persistence_path: Option<&std: struct Shell { app: TextureCraftApp, window_frame: Option, + /// Runs once when the window closes. On macOS that is the only place a clean quit is handled: + /// Cmd+Q ends the process inside AppKit's terminate, after eframe's `on_exit` and before + /// `eframe::run_native` returns, so the Nightly session record is finished here, not there. + exit_hook: Option>, #[cfg(target_os = "macos")] movable: Option, } @@ -164,12 +225,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) { @@ -181,6 +244,12 @@ impl eframe::App for Shell { #[cfg(target_os = "macos")] texturecraft_ui_egui::titlebar::sync_native(&self.app.title_bar, ui, frame, &mut self.movable); } + + fn on_exit(&mut self) { + if let Some(hook) = self.exit_hook.take() { + hook(); + } + } } /// A script driving the app gets no network check and no update prompt over its window. @@ -188,13 +257,97 @@ fn checks_for_updates_at_start(control: Option) -> bool { control.is_none() } +/// The AppUserModelID a Nightly window is grouped under, set before any native window exists. +fn initialize_nightly_process_identity() -> Result<(), process_identity::IdentityError> { + process_identity::initialize(build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1, os_window::id_for(LaunchIdentity::NightlyV1)) +} + +/// A refused Nightly start explains itself in a dialog where there is a desktop to show one. +fn report_launch_profile_error(error: &str) { + eprintln!("texturecraft: {error}"); + let desktop_session = cfg!(windows) + || cfg!(target_os = "macos") + || (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty()))); + if build_flavor::needs_native_error(build_flavor::COMPILED, desktop_session) { + if let Err(error) = initialize_nightly_process_identity() { + eprintln!("texturecraft: {error}"); + return; + } + #[cfg(any(windows, target_os = "linux", target_os = "macos"))] + let _ = rfd::MessageDialog::new() + .set_title(os_window::name_for(LaunchIdentity::NightlyV1)) + .set_description(error) + .set_level(rfd::MessageLevel::Error) + .set_buttons(rfd::MessageButtons::Ok) + .show(); + } +} + +/// Select the immutable launch profile before any startup service or side effect, and answer the +/// Launcher's version queries before root validation, logging, IPC or a window. `None` means the +/// launch is already answered and the process returns. +fn prepare_launch() -> Option> { + let argv: Vec = std::env::args_os().skip(1).collect(); + // Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root + // --version`: both are answered here, with nothing but standard output written. + if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv)) { + use std::io::Write as _; + let _ = writeln!(std::io::stdout(), "{}", build_flavor::version(build_flavor::COMPILED)); + return None; + } + let early = launch_profile::parse(argv) + .and_then(|launch| { + build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?; + initialize_nightly_process_identity().map_err(|error| error.to_string())?; + Ok(launch) + }) + .and_then(|launch| { + launch_profile::prepare(launch, |root| launch_profile::validate_root(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref())) + }) + .unwrap_or_else(|error| { + report_launch_profile_error(&error); + std::process::exit(2) + }); + let identity = if early.profile.is_nightly() { LaunchIdentity::NightlyV1 } else { LaunchIdentity::Stable }; + if let Err(error) = launch_profile::install(early.profile).and_then(|()| os_window::select_identity(identity)) { + report_launch_profile_error(&error); + std::process::exit(2); + } + if let Profile::NightlyV1(root) = launch_profile::current() { + // Every data folder follows the profile before the first one is used. + texturecraft_ui_egui::set_data_root(root.clone()); + texturecraft_ui_egui::os_window::set_display_version(build_flavor::BUILT_VERSION.to_owned()); + } + Some(early.args) +} + +/// The launch arguments as text. A Nightly protocol argument is a path the app opens, so a value +/// that is not valid Unicode is refused rather than silently replaced. +fn launch_arguments(arguments: Vec) -> Result, String> { + arguments.into_iter().map(|value| value.into_string().map_err(|_| "an argument is not valid Unicode".to_string())).collect() +} + fn main() { - // Windows: the update helper is a copy of this program started with `--finish-update` + // Windows: the update helper is a copy of this program started with `--finish-update`. A + // Nightly install is updated by ArtCraft Launcher, so it never installs an update itself. #[cfg(windows)] - if let Some(result) = craft_update::self_update::finish(&texturecraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::>()) { + if build_flavor::COMPILED == build_flavor::BuildFlavor::Stable + && let Some(result) = craft_update::self_update::finish(&texturecraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::>()) + { std::process::exit(i32::from(result.is_err())); } - let args = match parse_args() { + + // Windows: the eyedropper's pointer keeper (screen_pick) is a copy of this program started with + // its own argument. It reads no user state and is started without the profile tokens, so it + // runs before the launch protocol would refuse it. + #[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 Some(arguments) = prepare_launch() else { return }; + let nightly = launch_profile::current().is_nightly(); + let args = match launch_arguments(arguments).and_then(parse_args_from) { Ok(Some(a)) => a, Ok(None) => return, Err(e) => { @@ -202,6 +355,12 @@ fn main() { std::process::exit(2); } }; + // The control server is a stable-install service: a Nightly window is driven by the Launcher, + // and its token file would sit in the shared temp folder rather than its private profile. + if nightly && args.control.is_some() { + eprintln!("texturecraft: TextureCraft Nightly cannot start a control server (--control); use the stable app or texturecraft-cli"); + std::process::exit(2); + } // Errors before the window opens speak the system's language; the app then applies the saved one texturecraft_ui_egui::i18n::set_language(texturecraft_ui_egui::i18n::os_language()); @@ -212,11 +371,13 @@ fn main() { previous_hook(info); })); - // Scripted runs use temporary files so they cannot overwrite saved settings - let persistence_path = + // Scripted runs use temporary files so they cannot overwrite saved settings. Otherwise eframe + // is told the file explicitly, so `with_app_id` cannot move Stable's `app.ron` out of the + // folder `storage_dir` keeps `ui.json` and `errors.log` in (see `settings_folder`). + let no_prefs_path = std::env::var_os("TEXTURECRAFT_NO_PREFS").map(|_| std::env::temp_dir().join(format!("texturecraft-noprefs-{}.ron", std::process::id()))); - let ui_file = - persistence_path.as_ref().map(|path| path.with_extension("json")).or_else(|| eframe::storage_dir(APP_NAME).map(|folder| folder.join("ui.json"))); + let persistence_path = no_prefs_path.clone().or_else(|| storage_dir().map(|dir| dir.join("app.ron"))); + let ui_file = no_prefs_path.as_ref().map(|path| path.with_extension("json")).or_else(|| storage_dir().map(|folder| folder.join("ui.json"))); if let Some(file) = &ui_file { let _ = ui_state_store::FILE.set(file.clone()); } @@ -227,7 +388,11 @@ fn main() { prefs.apply_resource_limits(); let session = initial_session(&args); let title_bar = TitleBar::decide(prefs.system_title_bar); - let mut viewport = egui::ViewportBuilder::default().with_title(APP_NAME).with_inner_size(DEFAULT_SIZE).with_min_inner_size(MIN_SIZE); + let mut viewport = egui::ViewportBuilder::default() + .with_app_id(os_window::app_id()) + .with_title(os_window::name()) + .with_inner_size(DEFAULT_SIZE) + .with_min_inner_size(MIN_SIZE); if let Some(i) = icon() { viewport = viewport.with_icon(i); } @@ -238,8 +403,34 @@ fn main() { std::process::exit(2); } let control = args.control; + // The Nightly session record: one owner per profile, an unclean exit reported by the next + // start, and no document name, path or diagnostic payload collected. + let (nightly_session, session_health_warning) = match nightly_session::Session::begin_with_health( + launch_profile::current().root(), + build_flavor::BUILT_VERSION, + Some(env!("TEXTURECRAFT_BUILD_SHA")), + ) { + Ok(state) => state, + Err(error) => { + log::warn!("Nightly session health is unavailable: {error}"); + (None, true) + } + }; + let previous_nightly_unclean = nightly_session.as_ref().is_some_and(nightly_session::Session::previous_unclean); + // Set once a window has posted the interruption notice; until then the record must survive. + let unclean_notice_shown = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let notice_shown_in_window = unclean_notice_shown.clone(); + let nightly_session: nightly_session::Shared = std::sync::Arc::new(std::sync::Mutex::new(nightly_session)); + // The exit hook is the controlled return on macOS, where every quit ends the process inside + // AppKit's terminate and `run_native` never returns. Elsewhere the return path below finishes. + let finish_at_exit = { + let shared = nightly_session.clone(); + let shown = unclean_notice_shown.clone(); + move || nightly_session::finish_once(&shared, shown.load(std::sync::atomic::Ordering::Relaxed)) + }; + let window_name = os_window::name(); let result = eframe::run_native( - APP_NAME, + window_name, options, Box::new(move |cc| { #[cfg(windows)] @@ -249,7 +440,7 @@ fn main() { // winit's Quit ends the process without asking; this menu's asks like the close button #[cfg(target_os = "macos")] - if let Err(e) = craft_menu::mac::install_app_menu(&cc.egui_ctx, APP_NAME) { + if let Err(e) = craft_menu::mac::install_app_menu(&cc.egui_ctx, window_name) { log::warn!("the app menu could not be installed: {e}"); } let window_frame = window_frame::service(cc, matches!(title_bar, TitleBar::App(_))); @@ -259,14 +450,27 @@ fn main() { if let Some(port) = control { app.control = Some(control_server::start(port, cc.egui_ctx.clone())); } + if previous_nightly_unclean || session_health_warning { + use texturecraft_ui_egui::i18n::tr; + app.banner = Some(if previous_nightly_unclean { + tr("The previous TextureCraft Nightly session did not finish normally. No diagnostics have been sent.") + } else { + tr("TextureCraft Nightly could not record session health in its profile; abnormal-exit detection is unavailable.") + }); + notice_shown_in_window.store(previous_nightly_unclean, std::sync::atomic::Ordering::Relaxed); + } Ok(Box::new(Shell { app, window_frame, + exit_hook: Some(Box::new(finish_at_exit)), #[cfg(target_os = "macos")] movable: None, })) }), ); + // A controlled return, including a handled startup error. On macOS a window already finished in + // its exit hook, so this is then a no-op. + nightly_session::finish_once(&nightly_session, unclean_notice_shown.load(std::sync::atomic::Ordering::Relaxed)); if let Err(e) = result { fatal(&e.to_string(), true); std::process::exit(1); @@ -275,7 +479,7 @@ fn main() { /// The file startup errors and crashes are appended to, beside the saved settings. fn error_log() -> Option { - eframe::storage_dir(APP_NAME).map(|d| d.join("errors.log")) + storage_dir().map(|d| d.join("errors.log")) } /// Append a line with the time (Unix seconds) and the app version; true when it was written. @@ -296,7 +500,7 @@ fn fatal(msg: &str, dialog: bool) { let saved = log.map(|f| format!("\n\n{}", trf("Details saved to {file}", &[("file", &f.display())]))).unwrap_or_default(); rfd::MessageDialog::new() .set_level(rfd::MessageLevel::Error) - .set_title(APP_NAME) + .set_title(os_window::name()) .set_description(format!("{}\n\n{msg}{saved}", tr("TextureCraft had to close:"))) .set_buttons(rfd::MessageButtons::Ok) .show(); @@ -322,16 +526,52 @@ mod tests { } #[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))); + fn stable_settings_stay_in_the_folder_eframe_used_before_the_app_id() { + let legacy = std::path::PathBuf::from("/legacy/TextureCraft"); + // Stable, no wrapper folder: the folder eframe picked for `APP_NAME` before `with_app_id` + // existed, so `app.ron` (window state and the export presets stored in it) does not move. + let folder = settings_folder(None, None, Some(legacy.clone())).expect("a legacy folder"); + assert_eq!(folder.join("app.ron"), legacy.join("app.ron")); + // A Stable wrapper's data folder still wins, which is what #801's packaging expects. + let wrapper = std::path::PathBuf::from("/wrapper/data"); + assert_eq!(settings_folder(None, Some(wrapper.clone()), Some(legacy.clone())), Some(wrapper.clone())); + // A Nightly profile wins over both, so no Stable folder is ever read. + assert_eq!(settings_folder(Some(std::path::Path::new("/profile")), Some(wrapper), Some(legacy)), Some(std::path::PathBuf::from("/profile"))); + // Nothing resolvable: there is no folder to fall back to and eframe keeps its own default. + assert_eq!(settings_folder(None, None, None), None); + // The app's wiring: with no profile and no wrapper folder, `app.ron` sits beside `ui.json` + // in eframe's folder for `APP_NAME`, not in the folder of the app id `with_app_id` sets. + if std::env::var_os(DATA_DIR_ENV).is_none() + && !launch_profile::current().is_nightly() + && let Some(stable) = eframe::storage_dir(APP_NAME) + { + assert_eq!(storage_dir(), Some(stable.clone())); + assert_eq!(storage_dir().map(|dir| dir.join("app.ron")), Some(stable.join("app.ron"))); + } } #[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); + fn a_file_after_the_delimiter_is_a_file_even_when_it_looks_like_an_option() { + let args = parse_args_from(["--".to_string(), "--version".to_string()]).unwrap().unwrap(); + assert_eq!(args.file.as_deref(), Some("--version")); + let args = parse_args_from(["--".to_string(), "--launch-profile".to_string()]).unwrap().unwrap(); + assert_eq!(args.file.as_deref(), Some("--launch-profile")); + // Options before the delimiter still parse as options. + let args = parse_args_from(["--gpu".to_string(), "nvidia".to_string(), "--".to_string(), "a.glb".to_string()]).unwrap().unwrap(); + assert_eq!((args.gpu.as_deref(), args.file.as_deref()), (Some("nvidia"), Some("a.glb"))); + // One window opens one project: extra files after the delimiter are ignored, in that order. + let args = parse_args_from(["--".to_string(), "a.glb".to_string(), "b.glb".to_string()]).unwrap().unwrap(); + assert_eq!(args.file.as_deref(), Some("a.glb")); + } + + #[test] + fn launch_arguments_refuse_a_name_that_is_not_unicode() { + assert_eq!(launch_arguments(vec![OsString::from("--version")]).unwrap(), vec!["--version".to_string()]); + #[cfg(unix)] + { + use std::os::unix::ffi::OsStringExt as _; + assert!(launch_arguments(vec![OsString::from_vec(vec![b'a', 0xff, b'b'])]).is_err()); + } } #[test] @@ -388,4 +628,56 @@ 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, + exit_hook: 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/apps/texturecraft/src/nightly_session.rs b/apps/texturecraft/src/nightly_session.rs new file mode 100644 index 00000000..a1f2dee5 --- /dev/null +++ b/apps/texturecraft/src/nightly_session.rs @@ -0,0 +1,277 @@ +//! App-private Nightly session health, not telemetry and not a Launcher protocol. +//! +//! A live owner holds a separate persistent lease; a secondary launch never rewrites its record. +//! Dropping the guard does not clear the marker; only the app's controlled return path does. + +use std::fs::File; +use std::io::{self, Read}; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex, PoisonError}; + +const RECORD: &str = "nightly-session.json"; +const LEASE: &str = "nightly-session.lock"; +const MAX_METADATA_BYTES: usize = 256; + +pub struct Session { + _lease: File, + path: PathBuf, + own_record: Vec, + previous_unclean: bool, +} + +fn regular_or_missing(path: &Path) -> io::Result { + match std::fs::symlink_metadata(path) { + Ok(metadata) if metadata.file_type().is_file() && !metadata.file_type().is_symlink() => Ok(true), + Ok(_) => Err(io::Error::other("Nightly session state must be a regular file, not an alias or directory")), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false), + Err(error) => Err(error), + } +} + +/// Write `bytes` to `path` without ever following a link at the destination: the temporary file is +/// created exclusively beside it and renamed over the name, which replaces a link rather than +/// writing through it (the engine's `write_atomic` deliberately resolves the target instead). +fn write_no_follow(path: &Path, bytes: &[u8]) -> io::Result<()> { + let parent = path.parent().ok_or_else(|| io::Error::other("the Nightly record has no folder"))?; + let name = path.file_name().and_then(|name| name.to_str()).ok_or_else(|| io::Error::other("the Nightly record name is not Unicode"))?; + let temporary = parent.join(format!(".{name}.{}.tmp", std::process::id())); + let mut options = std::fs::OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt as _; + options.mode(0o600); + } + let staged = write_staged(&mut options, &temporary, bytes).and_then(|()| std::fs::rename(&temporary, path)); + if let Err(error) = staged { + let _ = std::fs::remove_file(&temporary); + return Err(error); + } + // The rename is durable only once its folder is synced (no-op where the platform has no handle). + #[cfg(unix)] + if let Ok(folder) = File::open(parent) { + let _ = folder.sync_all(); + } + Ok(()) +} + +/// Write the whole file and flush it to the device before it may replace the destination. +fn write_staged(options: &mut std::fs::OpenOptions, temporary: &Path, bytes: &[u8]) -> io::Result<()> { + use std::io::Write as _; + let mut file = options.open(temporary)?; + file.write_all(bytes)?; + file.sync_all() +} + +/// The owner's session, shared by the app's exit hook (macOS) and the code after the event loop. +/// On macOS every quit ends the process inside AppKit's terminate, after eframe's `on_exit` and +/// before `eframe::run_native` could return, so the exit hook finishes it there; the return path +/// still runs for a start that created no window. +pub type Shared = Arc>>; + +/// The controlled return ([`Session::finish`]) by whichever path comes first; later calls do nothing. +pub fn finish_once(shared: &Shared, unclean_notice_shown: bool) { + let watch = shared.lock().unwrap_or_else(PoisonError::into_inner).take(); + if let Some(watch) = watch + && let Err(error) = watch.finish(unclean_notice_shown) + { + log::warn!("Nightly session state was left intact: {error}"); + } +} + +impl Session { + /// The warning belongs to this window: a busy secondary has no health-record coverage, while + /// Stable and a lease-owning Nightly window preserve their existing result. + pub fn begin_with_health(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result<(Option, bool)> { + let watch = Self::begin(root, version, commit)?; + let unavailable = root.is_some() && watch.is_none(); + Ok((watch, unavailable)) + } + + /// `None` is Stable or another owner of this profile. Neither case touches the record. + /// The supplied root must already be the validated private Nightly profile. + pub fn begin(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result> { + let Some(root) = root else { return Ok(None) }; + if version.is_empty() || version.len() > MAX_METADATA_BYTES || commit.is_some_and(|value| value.len() > MAX_METADATA_BYTES) { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "Nightly session provenance is missing or too large")); + } + let lease_path = root.join(LEASE); + regular_or_missing(&lease_path)?; + let lease = std::fs::OpenOptions::new().read(true).write(true).create(true).truncate(false).open(lease_path)?; + match lease.try_lock() { + Ok(()) => {} + Err(std::fs::TryLockError::WouldBlock) => return Ok(None), + Err(std::fs::TryLockError::Error(error)) => return Err(error), + } + let path = root.join(RECORD); + let previous_unclean = regular_or_missing(&path)?; + let own_record = serde_json::to_vec(&serde_json::json!({ + "schema_version": 1, + "channel": "nightly-v1", + "version": version, + "commit": commit.filter(|value| !value.is_empty()), + }))?; + write_no_follow(&path, &own_record)?; + Ok(Some(Self { _lease: lease, path, own_record, previous_unclean })) + } + + pub fn previous_unclean(&self) -> bool { + self.previous_unclean + } + + /// Controlled return. If an earlier session's interruption was detected but no window showed it + /// yet, the record is left for the next owner to report; otherwise this is [`Self::complete`]. + pub fn finish(self, unclean_notice_shown: bool) -> io::Result<()> { + if self.previous_unclean && !unclean_notice_shown { + return Ok(()); + } + self.complete() + } + + /// A handled startup error is a controlled return too. An unwind, abort, forced exit or killed + /// process never calls this method. + pub fn complete(self) -> io::Result<()> { + if !regular_or_missing(&self.path)? { + return Ok(()); + } + let mut current = Vec::new(); + File::open(&self.path)?.take(self.own_record.len() as u64 + 1).read_to_end(&mut current)?; + if current != self.own_record { + return Err(io::Error::other("Nightly session state changed; leaving it intact")); + } + std::fs::remove_file(&self.path) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicU64, Ordering}; + + struct Fixture(PathBuf); + impl Fixture { + fn new() -> Self { + static NEXT: AtomicU64 = AtomicU64::new(0); + loop { + let path = std::env::temp_dir().join(format!("texturecraft-nightly-session-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); + match std::fs::create_dir(&path) { + Ok(()) => return Self(path), + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(error) => panic!("cannot create owned fixture: {error}"), + } + } + } + } + impl Drop for Fixture { + fn drop(&mut self) { + std::fs::remove_dir_all(&self.0).unwrap(); + } + } + + #[test] + fn busy_secondary_reports_unavailable_without_replacing_the_owner_record() { + let fixture = Fixture::new(); + let (stable, warning) = Session::begin_with_health(None, "stable", None).unwrap(); + assert!(stable.is_none() && !warning); + let (first, warning) = Session::begin_with_health(Some(&fixture.0), "nightly", Some("owned-commit")).unwrap(); + assert!(!warning); + let first = first.unwrap(); + let record = std::fs::read(fixture.0.join(RECORD)).unwrap(); + let (secondary, warning) = Session::begin_with_health(Some(&fixture.0), "secondary", None).unwrap(); + assert!(secondary.is_none() && warning, "a secondary window cannot claim recorded exit/crash coverage"); + assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record); + first.complete().unwrap(); + assert!(!fixture.0.join(RECORD).exists()); + } + + #[test] + fn controlled_completion_is_clean_but_an_unfinished_owner_is_reported_next_time() { + let fixture = Fixture::new(); + let first = Session::begin(Some(&fixture.0), "first", Some("recorded-commit")).unwrap().unwrap(); + assert!(!first.previous_unclean()); + let own = std::fs::read(fixture.0.join(RECORD)).unwrap(); + assert!(Session::begin(Some(&fixture.0), "secondary", None).unwrap().is_none()); + assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), own, "a busy secondary must not replace the owner's record"); + first.complete().unwrap(); + assert!(!fixture.0.join(RECORD).exists()); + let unfinished = Session::begin(Some(&fixture.0), "second", None).unwrap().unwrap(); + assert!(!unfinished.previous_unclean()); + drop(unfinished); // Unwind/abnormal-path ownership release, not a controlled completion. + let next = Session::begin(Some(&fixture.0), "third", None).unwrap().unwrap(); + assert!(next.previous_unclean()); + next.complete().unwrap(); + assert!(!fixture.0.join(RECORD).exists()); + } + + #[test] + fn an_interruption_no_window_showed_survives_a_handled_startup_failure() { + let fixture = Fixture::new(); + drop(Session::begin(Some(&fixture.0), "crashed", None).unwrap().unwrap()); + let failed = Session::begin(Some(&fixture.0), "gpu-failed", None).unwrap().unwrap(); + assert!(failed.previous_unclean()); + failed.finish(false).unwrap(); + // The next start still sees the interruption and shows it. + let retry = Session::begin(Some(&fixture.0), "next", None).unwrap().unwrap(); + assert!(retry.previous_unclean()); + retry.finish(true).unwrap(); + assert!(!fixture.0.join(RECORD).exists(), "a session that showed the notice clears its record"); + let clean = Session::begin(Some(&fixture.0), "clean", None).unwrap().unwrap(); + assert!(!clean.previous_unclean()); + clean.finish(false).unwrap(); + assert!(!fixture.0.join(RECORD).exists()); + } + + #[test] + fn the_exit_hook_and_the_return_path_finish_the_session_once() { + let fixture = Fixture::new(); + let shared: Shared = Arc::new(Mutex::new(Session::begin(Some(&fixture.0), "quitting", None).unwrap())); + // The exit hook (macOS quit: the only path that runs there). + finish_once(&shared, false); + assert!(!fixture.0.join(RECORD).exists(), "a quit that ran the exit hook is a clean exit"); + // Elsewhere the return path runs too, by then possibly after a successor took the profile. + let successor = Session::begin(Some(&fixture.0), "successor", None).unwrap().unwrap(); + assert!(!successor.previous_unclean()); + let record = std::fs::read(fixture.0.join(RECORD)).unwrap(); + finish_once(&shared, false); + assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record, "the second finish must not touch a successor's record"); + successor.complete().unwrap(); + } + + #[test] + fn cleanup_never_removes_an_unknown_changed_record() { + let fixture = Fixture::new(); + let watch = Session::begin(Some(&fixture.0), "nightly", None).unwrap().unwrap(); + std::fs::write(fixture.0.join(RECORD), b"replacement owned by someone else").unwrap(); + assert!(watch.complete().is_err()); + assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), b"replacement owned by someone else"); + } + + #[test] + fn provenance_is_bounded_and_never_collects_documents_paths_or_diagnostics() { + let fixture = Fixture::new(); + assert!(Session::begin(Some(&fixture.0), &"x".repeat(MAX_METADATA_BYTES + 1), None).is_err()); + assert_eq!(std::fs::read_dir(&fixture.0).unwrap().count(), 0); + assert!(Session::begin(None, "", None).unwrap().is_none(), "stable has no session-health side effects"); + let watch = Session::begin(Some(&fixture.0), "nightly", None).unwrap().unwrap(); + let data: serde_json::Value = serde_json::from_slice(&std::fs::read(fixture.0.join(RECORD)).unwrap()).unwrap(); + let fields = data.as_object().unwrap().keys().map(String::as_str).collect::>(); + assert_eq!(fields, ["schema_version", "channel", "version", "commit"].into_iter().collect()); + assert!(data["commit"].is_null(), "missing provenance must not be invented"); + watch.complete().unwrap(); + } + + #[test] + #[cfg(unix)] + fn reserved_state_aliases_do_not_modify_external_files() { + let fixture = Fixture::new(); + let external = fixture.0.join("stable-document"); + std::fs::write(&external, b"stable bytes").unwrap(); + for name in [LEASE, RECORD] { + let alias = fixture.0.join(name); + std::os::unix::fs::symlink(&external, &alias).unwrap(); + assert!(Session::begin(Some(&fixture.0), "nightly", None).is_err()); + assert_eq!(std::fs::read(&external).unwrap(), b"stable bytes"); + std::fs::remove_file(alias).unwrap(); + } + } +} diff --git a/apps/texturecraft/src/process_identity.rs b/apps/texturecraft/src/process_identity.rs new file mode 100644 index 00000000..f9ef611e --- /dev/null +++ b/apps/texturecraft/src/process_identity.rs @@ -0,0 +1,78 @@ +//! Set the immutable Nightly Windows identity before any native window or COM service. +//! Stable deliberately leaves its implicit shortcut/path identity unchanged, so MSI shortcut +//! matching keeps working. + +use std::fmt; +use std::sync::OnceLock; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct IdentityError(pub String); + +impl fmt::Display for IdentityError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} + +impl std::error::Error for IdentityError {} + +/// The AppUserModelID the taskbar groups the Nightly window under, distinct from Stable's. +pub fn initialize(nightly: bool, app_id: &str) -> Result<(), IdentityError> { + configure(nightly && cfg!(windows), app_id, |id| { + static RESULT: OnceLock> = OnceLock::new(); + RESULT + .get_or_init(|| { + #[cfg(windows)] + { + winsafe::SetCurrentProcessExplicitAppUserModelID(id).map_err(|error| format!("cannot set the nightly Windows identity: {error}"))?; + let actual = winsafe::GetCurrentProcessExplicitAppUserModelID() + .map_err(|error| format!("cannot read back the nightly Windows identity: {error}"))?; + if actual != id { + return Err("the native Windows identity did not match the selected nightly channel".into()); + } + Ok(()) + } + #[cfg(not(windows))] + { + let _ = id; + Ok(()) + } + }) + .clone() + }) + .map_err(IdentityError) +} + +fn configure(explicit_nightly: bool, app_id: &str, set: impl FnOnce(&str) -> Result<(), String>) -> Result<(), String> { + if explicit_nightly { set(app_id) } else { Ok(()) } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn stable_does_not_call_the_explicit_identity_api() { + configure(false, "nightly-id", |_| panic!("stable identity must remain implicit")).unwrap(); + } + + #[test] + fn nightly_applies_the_supplied_identity_once() { + let calls = std::cell::Cell::new(0); + configure(true, "nightly-id", |id| { + assert_eq!(id, "nightly-id"); + calls.set(calls.get() + 1); + Ok(()) + }) + .unwrap(); + assert_eq!(calls.get(), 1); + } + + #[test] + fn native_identity_failure_is_returned_instead_of_starting_a_window() { + let started = std::cell::Cell::new(false); + let result = configure(true, "nightly-id", |_| Err("native identity refused".into())).map(|()| started.set(true)); + assert_eq!(result.unwrap_err(), "native identity refused"); + assert!(!started.get()); + } +} diff --git a/apps/texturecraft/src/profile_root.rs b/apps/texturecraft/src/profile_root.rs new file mode 100644 index 00000000..71265909 --- /dev/null +++ b/apps/texturecraft/src/profile_root.rs @@ -0,0 +1,489 @@ +//! App-owned nightly profile fences; no stable fallback, migration or process environment changes. +//! +//! A Nightly profile has to hold *all* of its user state: eframe's `app.ron`/`ui.json`, the error +//! log, session logs, autosave copies, smart materials, layouts, templates, brush and export +//! presets. Anything that resolves to a stable folder would read and prune Stable's files, so the +//! root is refused when it overlaps one of them, when an entry inside it is an alias that leaves it, +//! or when it is not writable. + +use std::ffi::OsString; +use std::path::{Component, Path, PathBuf}; + +/// The folder names the launch checks use for this app in each platform's location. +const BRAND: &str = "TextureCraft"; +/// The bundle identifier of the stable package (macOS library folders, the Linux Flatpak). +const STABLE_ID: &str = "ai.storyteller.texturecraft"; +/// The package id of the Nightly Flatpak bundle (`packaging/linux/flatpak-bundle.sh`). Inside that +/// sandbox `FLATPAK_ID` is always set, so this exact id is the one a Nightly native launch accepts. +const NIGHTLY_ID: &str = "ai.storyteller.texturecraft.nightly"; +/// eframe lowercases its folder name on Linux (`file_storage.rs`), so Stable's real settings folder +/// is `$XDG_DATA_HOME/texturecraft`, not the capitalised `TextureCraft` the app is called. +const LINUX_STORAGE_BRAND: &str = "texturecraft"; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Platform { + Windows, + Linux, + Mac, +} + +impl Platform { + fn current() -> Result { + match std::env::consts::OS { + "windows" => Ok(Self::Windows), + "linux" => Ok(Self::Linux), + "macos" => Ok(Self::Mac), + _ => Err("nightly-v1 is not defined for this operating system".into()), + } + } + + fn ignores_case(self) -> bool { + self != Self::Linux + } +} + +fn absolute(path: PathBuf, label: &str) -> Result { + if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) { + return Err(format!("{label} must be absolute and contain no parent traversal")); + } + Ok(path) +} + +fn required_base(env: &impl Fn(&str) -> Option, key: &str) -> Result { + let value = env(key).filter(|v| !v.is_empty()).ok_or_else(|| format!("cannot establish the stable {key} boundary"))?; + absolute(PathBuf::from(value), key) +} + +fn xdg_base(env: &impl Fn(&str) -> Option, key: &str, fallback: &str) -> Result { + match env(key).filter(|v| !v.is_empty()) { + Some(value) => absolute(PathBuf::from(value), key), + None => Ok(required_base(env, "HOME")?.join(fallback)), + } +} + +/// Resolve existing ancestors before creating anything. A dangling link or an inaccessible ancestor +/// is not a missing directory that may be replaced or followed later. +fn canonical_future(path: &Path) -> Result { + let mut parent = path; + let mut missing = Vec::new(); + loop { + match std::fs::symlink_metadata(parent) { + Ok(_) => break, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + missing.push(parent.file_name().ok_or("the profile root has no existing ancestor")?.to_os_string()); + parent = parent.parent().ok_or("the profile root has no existing ancestor")?; + } + Err(error) => return Err(format!("cannot inspect the profile boundary: {error}")), + } + } + let mut resolved = std::fs::canonicalize(parent).map_err(|e| format!("cannot resolve the profile boundary: {e}"))?; + for part in missing.into_iter().rev() { + resolved.push(part); + } + Ok(resolved) +} + +/// Whether one path is the other or contains it (in either direction), compared component by +/// component and folded the way the platform's filesystem folds names. `TextureCraft2` is not +/// inside `TextureCraft`. +fn overlaps(a: &Path, b: &Path, platform: Platform) -> bool { + let parts = |p: &Path| { + p.components() + .map(|c| { + let value = c.as_os_str().to_string_lossy().into_owned(); + if platform.ignores_case() { value.to_lowercase() } else { value } + }) + .collect::>() + }; + let (a, b) = (parts(a), parts(b)); + a.starts_with(&b) || b.starts_with(&a) +} + +/// The running install: never let the profile live inside it (it would be replaced or removed by +/// the next update). +fn installation_boundary(platform: Platform, exe: &Path) -> Result { + let parent = exe.parent().ok_or("cannot establish the installation boundary")?; + if platform == Platform::Mac { + // A profile in Resources is still inside the versioned bundle, not beside MacOS. + if let Some(bundle) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))) { + return Ok(bundle.to_path_buf()); + } + } + Ok(parent.to_path_buf()) +} + +/// The default data folder, `Documents/TextureCraft`, as the app's own resolver builds it +/// (`crate::data_folder("")`): `USERPROFILE` on Windows and `HOME` elsewhere, then `Documents`. +fn default_data_folder(platform: Platform, env: &impl Fn(&str) -> Option) -> Result { + let home = match platform { + Platform::Windows => required_base(env, "USERPROFILE")?, + _ => required_base(env, "HOME")?, + }; + Ok(home.join("Documents").join(BRAND)) +} + +fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option, exe: &Path) -> Result, String> { + let mut roots = match platform { + Platform::Windows => { + // eframe's settings folder (`%APPDATA%\TextureCraft`), its local counterpart, and the MSI's + // per-machine and any per-user install folders. A custom install folder is covered by the + // executable's own folder below. + let mut roots = ["APPDATA", "LOCALAPPDATA"].into_iter().map(|key| required_base(env, key).map(|p| p.join(BRAND))).collect::, _>>()?; + roots.push(required_base(env, "LOCALAPPDATA")?.join("Programs").join("ArtCraft").join(BRAND)); + for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] { + if let Some(base) = env(key).filter(|v| !v.is_empty()) { + roots.push(absolute(PathBuf::from(base), key)?.join(BRAND)); + } + } + roots + } + Platform::Linux => { + // The four XDG roots carry eframe's settings, caches and state under the app's name. + let mut roots = + [("XDG_CONFIG_HOME", ".config"), ("XDG_DATA_HOME", ".local/share"), ("XDG_CACHE_HOME", ".cache"), ("XDG_STATE_HOME", ".local/state")] + .into_iter() + .map(|(key, fallback)| xdg_base(env, key, fallback).map(|p| p.join(BRAND))) + .collect::, _>>()?; + // eframe's own folder for this app on Linux, which is what holds Stable's `app.ron`, + // `ui.json` and `errors.log`: it folds the name, so it is the lowercase one. + roots.push(xdg_base(env, "XDG_DATA_HOME", ".local/share")?.join(LINUX_STORAGE_BRAND)); + roots.extend(["/usr/bin/texturecraft", "/usr/local/bin/texturecraft", "/opt/texturecraft"].map(PathBuf::from)); + // The stable Flatpak keeps its own per-app data folder. + roots.push(required_base(env, "HOME")?.join(format!(".var/app/{STABLE_ID}"))); + roots + } + Platform::Mac => { + let home = required_base(env, "HOME")?; + let library = home.join("Library"); + vec![ + library.join("Application Support").join(BRAND), + library.join("Caches").join(BRAND), + library.join("Caches").join(STABLE_ID), + library.join("Preferences").join(BRAND), + library.join("Preferences").join(format!("{STABLE_ID}.plist")), + library.join("Saved Application State").join(format!("{STABLE_ID}.savedState")), + home.join("Applications").join(format!("{BRAND}.app")), + PathBuf::from("/Applications").join(format!("{BRAND}.app")), + ] + } + }; + // The user's own documents folder is Stable's default data folder on every platform; a profile + // there would share autosaves, smart materials and presets with it. + roots.push(default_data_folder(platform, env)?); + roots.push(installation_boundary(platform, exe)?); + roots.into_iter().map(|p| canonical_future(&p)).collect() +} + +/// An entry inside the profile must resolve inside it, so a link planted there cannot point +/// Nightly's writes at another app's files. +fn private_subdirectory(root: &Path, name: impl AsRef, label: &str) -> Result { + let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?; + let child = canonical_future(&chosen.join(name))?; + if child == chosen || !child.starts_with(&chosen) { + return Err(format!("the nightly {label} must stay inside its selected profile")); + } + Ok(child) +} + +/// Every existing entry directly in the profile (autosave, logs, library and so on) must resolve +/// inside it. +fn entries_stay_inside(root: &Path) -> Result<(), String> { + let entries = match std::fs::read_dir(root) { + Ok(entries) => entries, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()), + Err(error) => return Err(format!("cannot inspect the nightly profile: {error}")), + }; + for entry in entries { + let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?; + private_subdirectory(root, entry.file_name(), "profile entry")?; + } + Ok(()) +} + +/// The app's writable probe: create a file exclusively in the profile and remove it again. +pub fn ensure_writable(dir: &Path) -> std::io::Result<()> { + let probe = dir.join("exclusive-write-probe"); + let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?; + drop(file); + std::fs::remove_file(probe) +} + +/// Refuse a stable folder, the running install or an alias, create a missing root with owner-only +/// access where the platform has it, and return the resolved root to use. +pub fn validate( + root: &Path, + env: impl Fn(&str) -> Option, + exe: Option<&Path>, + writable: impl FnOnce(&Path) -> std::io::Result<()>, +) -> Result { + validate_for(Platform::current()?, root, env, exe, writable) +} + +fn validate_for( + platform: Platform, + root: &Path, + env: impl Fn(&str) -> Option, + exe: Option<&Path>, + writable: impl FnOnce(&Path) -> std::io::Result<()>, +) -> Result { + absolute(root.to_path_buf(), "the nightly profile root")?; + // A native package must not carry another app's Flatpak namespace, and the Nightly bundle must + // be able to start inside its own sandbox, where the runtime always sets `FLATPAK_ID`. Its + // `~/.var/app/` sandbox is separate from stable's, so only other ids are refused. + if platform != Platform::Windows + && let Some(id) = env("FLATPAK_ID").filter(|v| !v.is_empty()) + && id != NIGHTLY_ID + { + return Err("nightly-v1 only runs inside its own Flatpak; launch through the native Launcher or the Nightly bundle".into()); + } + let chosen = canonical_future(root)?; + let exe = absolute(exe.ok_or("cannot establish the installation boundary")?.to_path_buf(), "the executable")?; + let forbidden = forbidden_roots(platform, &env, &exe)?; + if forbidden.iter().any(|stable| overlaps(&chosen, stable, platform)) { + return Err("the nightly root must not overlap stable data or an installation".into()); + } + // Existing aliases under the profile must not redirect any of its folders elsewhere. + entries_stay_inside(&chosen)?; + let mut create = std::fs::DirBuilder::new(); + create.recursive(true); + #[cfg(unix)] + { + use std::os::unix::fs::DirBuilderExt as _; + create.mode(0o700); + } + create.create(&chosen).map_err(|e| format!("cannot create the nightly profile: {e}"))?; + let confirmed = std::fs::canonicalize(&chosen).map_err(|e| format!("cannot resolve the created nightly profile: {e}"))?; + if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) { + return Err("the nightly profile changed while it was being validated".into()); + } + entries_stay_inside(&confirmed)?; + writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?; + Ok(confirmed) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::BTreeMap; + use std::sync::atomic::{AtomicU64, Ordering}; + + struct Fixture { + root: PathBuf, + env: BTreeMap, + exe: PathBuf, + } + + impl Fixture { + fn new() -> Self { + static NEXT: AtomicU64 = AtomicU64::new(0); + let root = loop { + let candidate = + std::env::temp_dir().join(format!("texturecraft-profile-policy-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); + match std::fs::create_dir(&candidate) { + Ok(()) => break std::fs::canonicalize(candidate).unwrap(), + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(error) => panic!("cannot create owned fixture: {error}"), + } + }; + let home = root.join("home"); + let exe = root.join("install/texturecraft"); + std::fs::create_dir_all(&home).unwrap(); + std::fs::create_dir_all(exe.parent().unwrap()).unwrap(); + std::fs::write(&exe, b"fixture executable, never run").unwrap(); + let env = [("HOME", home.clone()), ("USERPROFILE", home), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))] + .into_iter() + .map(|(key, value)| (key.into(), value.into_os_string())) + .collect(); + Self { root, env, exe } + } + + fn get(&self, key: &str) -> Option { + self.env.get(key).cloned() + } + + fn check(&self, platform: Platform, root: &Path) -> Result { + validate_for(platform, root, |key| self.get(key), Some(&self.exe), ensure_writable) + } + + fn home(&self) -> PathBuf { + PathBuf::from(self.get("HOME").unwrap()) + } + + fn profile(&self, name: &str) -> PathBuf { + self.root.join("profiles").join(name) + } + } + + impl Drop for Fixture { + fn drop(&mut self) { + // Only the directory this fixture created is owned for removal. + std::fs::remove_dir_all(&self.root).unwrap(); + } + } + + #[test] + fn a_fresh_private_profile_is_created_and_returned_resolved() { + let fixture = Fixture::new(); + let profile = fixture.profile("nightly"); + for platform in [Platform::Windows, Platform::Linux, Platform::Mac] { + assert_eq!(fixture.check(platform, &profile).unwrap(), profile); + assert!(profile.is_dir()); + std::fs::remove_dir_all(&profile).ok(); + } + } + + #[test] + fn every_stable_data_folder_of_each_platform_is_refused_before_any_probe() { + let fixture = Fixture::new(); + let home = fixture.home(); + let candidates: Vec<(Platform, PathBuf)> = vec![ + (Platform::Windows, PathBuf::from(fixture.get("APPDATA").unwrap()).join(BRAND)), + (Platform::Windows, PathBuf::from(fixture.get("LOCALAPPDATA").unwrap()).join(BRAND)), + (Platform::Windows, PathBuf::from(fixture.get("LOCALAPPDATA").unwrap()).join("Programs/ArtCraft").join(BRAND)), + (Platform::Windows, home.join("Documents").join(BRAND)), + (Platform::Linux, home.join(".config").join(BRAND)), + (Platform::Linux, home.join(".local/share").join(BRAND)), + (Platform::Linux, home.join(".local/share").join(LINUX_STORAGE_BRAND)), + (Platform::Linux, home.join(".cache").join(BRAND)), + (Platform::Linux, home.join(".local/state").join(BRAND)), + (Platform::Linux, home.join("Documents").join(BRAND)), + (Platform::Linux, PathBuf::from("/usr/bin/texturecraft")), + (Platform::Linux, PathBuf::from("/opt/texturecraft")), + (Platform::Linux, home.join(format!(".var/app/{STABLE_ID}"))), + (Platform::Mac, home.join("Library/Application Support").join(BRAND)), + (Platform::Mac, home.join("Library/Caches").join(BRAND)), + (Platform::Mac, home.join("Library/Preferences").join(format!("{STABLE_ID}.plist"))), + (Platform::Mac, home.join("Library/Saved Application State").join(format!("{STABLE_ID}.savedState"))), + (Platform::Mac, home.join("Documents").join(BRAND)), + (Platform::Mac, PathBuf::from(format!("/Applications/{BRAND}.app"))), + ]; + for (platform, stable) in candidates { + for candidate in [stable.clone(), stable.join("nested nightly")] { + let probed = std::cell::Cell::new(false); + let result = validate_for( + platform, + &candidate, + |key| fixture.get(key), + Some(&fixture.exe), + |_| { + probed.set(true); + Ok(()) + }, + ); + assert!(result.is_err(), "{platform:?} accepted {}", candidate.display()); + assert!(!probed.get(), "a refused root must not be probed: {}", candidate.display()); + } + } + } + + #[test] + fn the_running_install_is_fenced_on_every_platform() { + let fixture = Fixture::new(); + for platform in [Platform::Windows, Platform::Linux, Platform::Mac] { + let inside = fixture.exe.parent().unwrap().join("profile"); + assert!(fixture.check(platform, &inside).is_err(), "{platform:?} let the profile inside the install"); + } + } + + #[test] + fn lookalike_names_are_not_overlaps_but_case_folding_is() { + let fixture = Fixture::new(); + let documents = fixture.home().join("Documents"); + assert!(fixture.check(Platform::Linux, &documents.join("TextureCraft2")).is_ok(), "a neighbor with a suffix is a different folder"); + assert!(fixture.check(Platform::Linux, &documents.join("texturecraft")).is_ok(), "Linux folds names exactly"); + for platform in [Platform::Windows, Platform::Mac] { + assert!(fixture.check(platform, &documents.join("texturecraft")).is_err(), "{platform:?} must fold case"); + } + } + + #[test] + fn relative_parent_traversal_and_empty_roots_are_refused() { + let fixture = Fixture::new(); + for root in [PathBuf::from("relative/profile"), PathBuf::from("/nightly/../stable"), PathBuf::from("")] { + assert!(fixture.check(Platform::Linux, &root).is_err(), "{}", root.display()); + } + } + + #[test] + fn only_the_nightly_flatpak_may_start_with_its_own_id() { + let fixture = Fixture::new(); + let profile = fixture.profile("flatpak"); + assert!(fixture.check(Platform::Linux, &profile).is_ok()); + std::fs::remove_dir_all(&profile).ok(); + let check_with = |id: &str, candidate: &Path| { + let id = OsString::from(id); + validate_for( + Platform::Linux, + candidate, + |key| if key == "FLATPAK_ID" { Some(id.clone()) } else { fixture.get(key) }, + Some(&fixture.exe), + ensure_writable, + ) + }; + // Stable's id, its window id and an unrelated app's id are all refusals. + for id in [STABLE_ID, "ai.storyteller.texturecraft.nightly-v1", "org.example.other"] { + assert!(check_with(id, &profile).is_err(), "{id} was accepted"); + } + // The Nightly bundle's own id is the sandbox the Nightly package runs in: accepted, with the + // profile its wrapper names inside it (`${XDG_DATA_HOME}/TextureCraft-Nightly`). + let sandbox = fixture.home().join(format!(".var/app/{NIGHTLY_ID}")); + let sandboxed = sandbox.join(".local/share/TextureCraft-Nightly"); + assert_eq!(check_with(NIGHTLY_ID, &sandboxed).expect("the Nightly Flatpak may start"), sandboxed); + std::fs::remove_dir_all(&sandbox).ok(); + } + + #[test] + #[cfg(unix)] + fn an_entry_that_leaves_the_profile_is_refused() { + let fixture = Fixture::new(); + let profile = fixture.profile("aliased"); + let outside = fixture.root.join("somewhere else"); + std::fs::create_dir_all(&profile).unwrap(); + std::fs::create_dir_all(&outside).unwrap(); + std::os::unix::fs::symlink(&outside, profile.join("autosave")).unwrap(); + assert!(fixture.check(Platform::Linux, &profile).is_err(), "a link out of the profile must be refused"); + // A dangling link is not a missing folder that may be created. + std::fs::remove_file(profile.join("autosave")).unwrap(); + std::os::unix::fs::symlink(profile.join("missing"), profile.join("logs")).unwrap(); + assert!(fixture.check(Platform::Linux, &profile).is_err()); + std::fs::remove_file(profile.join("logs")).unwrap(); + // A plain folder inside it is fine. + std::fs::create_dir(profile.join("autosave")).unwrap(); + assert!(fixture.check(Platform::Linux, &profile).is_ok()); + } + + #[test] + fn a_failed_write_probe_never_falls_back_to_stable() { + let fixture = Fixture::new(); + let profile = fixture.profile("read only"); + let reached = std::cell::Cell::new(false); + let result = validate_for( + Platform::Linux, + &profile, + |key| fixture.get(key), + Some(&fixture.exe), + |_| { + reached.set(true); + Err(std::io::Error::other("read-only filesystem")) + }, + ); + assert!(result.is_err()); + assert!(reached.get()); + assert!(result.unwrap_err().contains("not writable")); + // The app must not then use the stable folder: it simply refuses to start. + assert!(fixture.check(Platform::Linux, &fixture.home().join("Documents").join(BRAND)).is_err()); + } + + #[test] + #[cfg(unix)] + fn a_profile_whose_existing_ancestor_is_a_link_resolves_before_the_fence() { + let fixture = Fixture::new(); + let real = fixture.root.join("real profiles"); + std::fs::create_dir_all(&real).unwrap(); + let link = fixture.root.join("linked"); + std::os::unix::fs::symlink(&real, &link).unwrap(); + // A link to a private folder is fine, and the resolved root is what the app uses. + let resolved = fixture.check(Platform::Linux, &link.join("nightly")).unwrap(); + assert_eq!(resolved, real.join("nightly")); + } +} diff --git a/assets/app-icon/README.md b/assets/app-icon/README.md index 07351074..38a8538c 100644 --- a/assets/app-icon/README.md +++ b/assets/app-icon/README.md @@ -57,3 +57,23 @@ pillow and potracer): OPT=0.4 DP=1 python3 vectorize_tile.py source.png '#c2672b' 2048 2 texturecraft.svg OPT=1.0 DP=0 python3 vectorize_tile.py source.png '#c2672b' 1024 4 texturecraft-small.svg ``` + +## Nightly icon + +The Nightly build ships the same engraving on a deeper copper field (`#643418`): the background +contribution of each pixel is replaced and the ink, paper and alpha padding are left exactly as +they are. No badge, crescent or letter is added, so the two icons differ only in the field. + +| File | What | +|---|---| +| `texturecraft-nightly.png` | 256 px window icon (`apps/texturecraft/src/main.rs`) | +| `texturecraft-nightly-1024.png` | full tile, 1024 px (docs) | +| `texturecraft-nightly.icns` | macOS icon set, the stable `.icns`'s own PNG slots recoloured | +| `texturecraft-nightly.ico` | Windows icon, the stable `.ico`'s own frames (16 to 256 px) recoloured | +| `nightly/.png` | per-size renders for the Nightly package and the title bar's icon in a Nightly window (16 to 512 px). Kept out of `hicolor/`, which Stable's Linux and FreeBSD packagers copy whole | +| `nightly-provenance.json` | the inputs, the palette, the transform and the SHA-256 of every output | + +`packaging/nightly-icons.py` derives all of them from the committed stable renders (no upscale, no +resvg, no Pillow): run it after `packaging/icons.sh` changes a stable file, and +`python3 packaging/nightly-icons.py --check` (part of `packaging/nightly-tests.py`) fails when a +committed Nightly file has drifted. diff --git a/assets/app-icon/nightly-provenance.json b/assets/app-icon/nightly-provenance.json new file mode 100644 index 00000000..b9c4fc52 --- /dev/null +++ b/assets/app-icon/nightly-provenance.json @@ -0,0 +1,81 @@ +{ + "title": "TextureCraft nightly deep-background icons", + "license": "MIT OR Apache-2.0", + "generator": "packaging/nightly-icons.py", + "generator_sha256": "745786e3bfbecf29077df1e4a64ed717953694038f95533d2d37507c520b791c", + "inputs": [ + { + "path": "assets/app-icon/texturecraft.icns", + "sha256": "eb5e1b19679aa9a23531219d92922e37edbdc3e2046454b8f6c64423f471b57b" + }, + { + "path": "assets/app-icon/texturecraft.ico", + "sha256": "9c3366e4af9f2c0772e00193c348feba834d407fc8b826d4276a8fcb4cc01dcb" + }, + { + "path": "assets/app-icon/texturecraft-1024.png", + "sha256": "8451f91be8c1bc9c2e1a594e193ae5d1793d2d12f26a8bc64d2bd83fe4b789e4" + }, + { + "path": "assets/app-icon/hicolor/16x16/apps/ai.storyteller.texturecraft.png", + "sha256": "79ee309754be54b56052ab05fff87a2427bbc38bb057c96094f8f070ee13ca1d" + }, + { + "path": "assets/app-icon/hicolor/24x24/apps/ai.storyteller.texturecraft.png", + "sha256": "f8f89220ce68be236d63edfd94d4fef2aad2aa9840a50e430f874649a9816171" + }, + { + "path": "assets/app-icon/hicolor/32x32/apps/ai.storyteller.texturecraft.png", + "sha256": "ff8578ffc95f5123bb2e4a00636080f02adf259334ecb0ac9f952fac3378ddb2" + }, + { + "path": "assets/app-icon/hicolor/48x48/apps/ai.storyteller.texturecraft.png", + "sha256": "f7f19ffbd8904ff462bc6d785b865153112025bbdeb868bc0f136e39c7d725e1" + }, + { + "path": "assets/app-icon/hicolor/64x64/apps/ai.storyteller.texturecraft.png", + "sha256": "39d17421579ace5dbe4705fb0a52cd6002d433ded7ba0ee2fdeb5d6d7cd16c8c" + }, + { + "path": "assets/app-icon/hicolor/128x128/apps/ai.storyteller.texturecraft.png", + "sha256": "ac629a038a215a13d86172286142502b6efd17618869652050f291d9745346d2" + }, + { + "path": "assets/app-icon/hicolor/256x256/apps/ai.storyteller.texturecraft.png", + "sha256": "757f858b26897cb0e9f0c8cd43db9ade9664dd6199bd190d1af406839769c71f" + }, + { + "path": "assets/app-icon/hicolor/512x512/apps/ai.storyteller.texturecraft.png", + "sha256": "705513dc82aa908f962b9a466743b42e53b0f586752d2d69a5b6596b8ff928f0" + } + ], + "method": { + "kind": "derivative of the project-owned stable renders; no badge, crescent or letter", + "original_palette": { + "ink": "#0b0b0c", + "paper": "#efe9dc", + "background": "#c2672b" + }, + "nightly_background": "#643418", + "transform": "Fit each pixel as the tile background plus one engraved foreground (ink or paper) and replace only the background contribution; keep alpha, padding and foreground detail. Each frame comes from the stable master of its own size: the .icns and .ico PNG frames are recoloured in place, and the per-size PNGs (in nightly/) and the 1024 master are recoloured from their own renders. No upscaling." + }, + "outputs": { + "assets/app-icon/texturecraft-nightly.icns": "e21e2c90f7402e6289038ad7db896a14780766e07f33d9cb68cbe0d423efe66d", + "assets/app-icon/texturecraft-nightly.ico": "b0dc8817a3b07f0eb8175241c1fdc1ce21ffb8d5a54e6b03979ba2f73e62d47e", + "assets/app-icon/nightly/16.png": "657c7a39547828b0eaafe4b78df28771bb953afdb62440d0c001c695ff586e76", + "assets/app-icon/nightly/24.png": "b4c263436402faa93276b77614291107f6b44309ccfe329b71c3562c1f382c11", + "assets/app-icon/nightly/32.png": "cefb99a330d103f32a07d07e49542da2231897224a3dfe479e9c9d4a53a0a17b", + "assets/app-icon/nightly/48.png": "126316a058f4a225fbea7e1c0e49dc3d27941e2a91a7f033f35b84bc6d646f22", + "assets/app-icon/nightly/64.png": "d471a4bd691fca348603571bfe9c05357120e492566e31c7b2c936361a4a2510", + "assets/app-icon/nightly/128.png": "b36b07739b98b7884ce308641407725bb499adfefd87a4286c3aa117abdb57d5", + "assets/app-icon/nightly/256.png": "82c417bbcafd9b90929b117b7f80f403e631a77a327ee868bc9e8ca7a44c7fe2", + "assets/app-icon/nightly/512.png": "de756e67f16076a08cb5c2726d1a63181a0a8b61c73ff3df0cf49e065f1c8bc2", + "assets/app-icon/texturecraft-nightly-1024.png": "509ebc6130db6c10c380bc4ee2280a6b1810eea5dc03293b86a575c1ef120736", + "assets/app-icon/texturecraft-nightly.png": "82c417bbcafd9b90929b117b7f80f403e631a77a327ee868bc9e8ca7a44c7fe2" + }, + "ico_frames": [ + "the stable .ico's own frames (16, 20, 24, 32, 40, 48, 64, 128, 256)" + ], + "icns_slots": "the stable .icns's own PNG slots (icp4 through ic10)", + "validation": "Byte comparison against the committed assets (packaging/nightly-archive-tests.py and the icon check in packaging/nightly-tests.py); native Explorer/Finder rendering is not exercised here. The per-size PNGs are kept out of hicolor/ because Stable's Linux and FreeBSD packages copy that theme tree whole." +} diff --git a/assets/app-icon/nightly/128.png b/assets/app-icon/nightly/128.png new file mode 100644 index 00000000..c220657a Binary files /dev/null and b/assets/app-icon/nightly/128.png differ diff --git a/assets/app-icon/nightly/16.png b/assets/app-icon/nightly/16.png new file mode 100644 index 00000000..39ae3282 Binary files /dev/null and b/assets/app-icon/nightly/16.png differ diff --git a/assets/app-icon/nightly/24.png b/assets/app-icon/nightly/24.png new file mode 100644 index 00000000..6e15fead Binary files /dev/null and b/assets/app-icon/nightly/24.png differ diff --git a/assets/app-icon/nightly/256.png b/assets/app-icon/nightly/256.png new file mode 100644 index 00000000..3ca334c3 Binary files /dev/null and b/assets/app-icon/nightly/256.png differ diff --git a/assets/app-icon/nightly/32.png b/assets/app-icon/nightly/32.png new file mode 100644 index 00000000..aa3c8526 Binary files /dev/null and b/assets/app-icon/nightly/32.png differ diff --git a/assets/app-icon/nightly/48.png b/assets/app-icon/nightly/48.png new file mode 100644 index 00000000..db1aeaeb Binary files /dev/null and b/assets/app-icon/nightly/48.png differ diff --git a/assets/app-icon/nightly/512.png b/assets/app-icon/nightly/512.png new file mode 100644 index 00000000..f62c465e Binary files /dev/null and b/assets/app-icon/nightly/512.png differ diff --git a/assets/app-icon/nightly/64.png b/assets/app-icon/nightly/64.png new file mode 100644 index 00000000..a85b8233 Binary files /dev/null and b/assets/app-icon/nightly/64.png differ diff --git a/assets/app-icon/texturecraft-nightly-1024.png b/assets/app-icon/texturecraft-nightly-1024.png new file mode 100644 index 00000000..d43e9fbc Binary files /dev/null and b/assets/app-icon/texturecraft-nightly-1024.png differ diff --git a/assets/app-icon/texturecraft-nightly.icns b/assets/app-icon/texturecraft-nightly.icns new file mode 100644 index 00000000..9d96db5f Binary files /dev/null and b/assets/app-icon/texturecraft-nightly.icns differ diff --git a/assets/app-icon/texturecraft-nightly.ico b/assets/app-icon/texturecraft-nightly.ico new file mode 100644 index 00000000..9d1f3eb3 Binary files /dev/null and b/assets/app-icon/texturecraft-nightly.ico differ diff --git a/assets/app-icon/texturecraft-nightly.png b/assets/app-icon/texturecraft-nightly.png new file mode 100644 index 00000000..3ca334c3 Binary files /dev/null and b/assets/app-icon/texturecraft-nightly.png differ 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/bake_passes.rs b/crates/bake/src/bake_passes.rs new file mode 100644 index 00000000..eb7d5846 --- /dev/null +++ b/crates/bake/src/bake_passes.rs @@ -0,0 +1,72 @@ +use crate::cage::RayFrame; +use crate::map::BakeContext; +use crate::tracing::{CpuTracer, Tracer}; +use crate::{BakeError, BakeOutput, BakeRequest, MeshExtent, Progress}; +use std::sync::atomic::Ordering::Relaxed; +use texturecraft_core::{BakeSettings, BakedMap}; + +/// Map passes over one immutable request share the fitted cage and prepared skew. +pub struct BakePasses<'a> { + request: BakeRequest<'a>, + frame: Option<(MeshExtent, RayFrame<'a>)>, +} + +impl<'a> BakePasses<'a> { + pub fn new(request: BakeRequest<'a>) -> Self { + Self { request, frame: None } + } + + /// Bake one selected map, including the CPU fallback used by a normal bake. + pub fn bake_map( + &mut self, + map: BakedMap, + progress: &Progress, + excluded_tiles: &[(u32, u32)], + tracer: Option<&dyn Tracer>, + ) -> Result { + let mut settings = self.request.settings.clone(); + settings.maps.select([map]); + self.run(&settings, progress, excluded_tiles, tracer, super::STRIP_TEXELS) + } + + pub(super) fn run( + &mut self, + settings: &BakeSettings, + progress: &Progress, + excluded_tiles: &[(u32, u32)], + tracer: Option<&dyn Tracer>, + strip_texels: usize, + ) -> Result { + if progress.cancel.load(Relaxed) { + return Err(BakeError::Cancelled); + } + + let request = BakeRequest { settings, ..self.request }; + super::validate(&request)?; + if excluded_tiles.iter().any(|(column, row)| *column >= request.tiles.0 || *row >= request.tiles.1) { + return Err(BakeError::Invalid("excluded UV tile lies outside the bake atlas".into())); + } + + // Validate each pass separately so earlier maps can finish before a later map fails + let (extent, frame) = match &mut self.frame { + Some(geometry) => geometry, + None => { + let extent = MeshExtent::of(request.mesh)?; + self.frame.insert((extent, RayFrame::new(&self.request, extent)?)) + } + }; + let context = BakeContext::with_frame(&request, *extent, frame); + let bake = |tracer: &dyn Tracer| super::bake_prepared(&request, &context, progress, strip_texels, tracer, excluded_tiles); + match tracer { + Some(tracer) => match bake(tracer) { + Err(BakeError::Tracer(error)) => { + let mut output = bake(&CpuTracer)?; + output.tracer = format!("CPU ({} unavailable: {error})", tracer.name()); + Ok(output) + } + result => result, + }, + None => bake(&CpuTracer), + } + } +} diff --git a/crates/bake/src/cage.rs b/crates/bake/src/cage.rs index d2c7d7f3..d2c8a592 100644 --- a/crates/bake/src/cage.rs +++ b/crates/bake/src/cage.rs @@ -1,7 +1,9 @@ //! Where the bake's transfer rays start, shared by the bake and the cage the 3D view draws mod cage_shell; +mod fitted_cage; mod high_poly_reach; +mod name_keys; mod ray_frame; mod ray_start; mod vertex_reach; @@ -9,6 +11,7 @@ mod vertex_reach; #[cfg(test)] pub(crate) use cage_shell::CORNERS; pub use cage_shell::CageShell; +pub(crate) use fitted_cage::FittedCage; pub use high_poly_reach::HighPolyReach; pub(crate) use ray_frame::RayFrame; pub use ray_start::RayStart; diff --git a/crates/bake/src/cage/fitted_cage.rs b/crates/bake/src/cage/fitted_cage.rs new file mode 100644 index 00000000..079d94b0 --- /dev/null +++ b/crates/bake/src/cage/fitted_cage.rs @@ -0,0 +1,231 @@ +use super::name_keys::NameKeys; +use crate::map::interpolate; +use crate::{BakeRequest, HighPoly, MeshExtent}; +use rayon::prelude::*; +use std::borrow::Cow; +use std::collections::{HashMap, VecDeque}; +use texturecraft_geom::Mesh; +use texturecraft_geom::glam::Vec3; + +/// How much farther than the high poly the cage reaches, as a fraction of the fitted distance: the fit reads both meshes at their vertices only. Tuned with [`MARGIN_PER_DIAGONAL`] on two production meshes: the tightest pair whose rays miss no more texels than the default distances do +const MARGIN_PER_DISTANCE: f32 = 0.5; + +/// The least the cage reaches each way, as a fraction of the mesh diagonal, so a high poly lying on the low poly is still inside +const MARGIN_PER_DIAGONAL: f32 = 4e-3; + +/// How many times farther than the nearest high-poly point a low-poly vertex's ray may find the high poly: beyond it (a surface more than about 75 degrees off the ray) the ray has left the vertex's own part +const MAX_RAY_PER_NEAREST_DISTANCE: f32 = 4.0; + +/// Bound temporary high-vertex projections while giving Rayon thousands of independent queries per batch +const PROJECTION_BATCH_VERTICES: usize = 8192; + +/// The automatic cage: how far the transfer rays start in front of each low-poly vertex and how far they run behind it, fitted to the high poly +pub(crate) struct FittedCage { + /// (front, rear) in world units per low-poly vertex; `None` on parts no high poly is near + distances: Vec>, +} + +impl FittedCage { + /// Fit the cage of `request`'s low poly around `high` along `ray_normals` (where parts welded back to back cancelled a vertex's normal out, along its own): each low-poly vertex reaches the high poly straight in front of or behind it, and each high-poly vertex pushes the corners of its nearest low-poly triangle out (or in) to its height. Vertices neither finds take their neighbours' distances; a part the high poly reaches nowhere gets none + pub(crate) fn new(request: &BakeRequest, high: HighPoly, welded_indices: &[u32], ray_normals: &[Vec3], extent: MeshExtent) -> FittedCage { + let low = request.mesh; + let keys = NameKeys::of(request, high); + let welded_indices = welded_within_groups(welded_indices, &keys.low_vertices); + let welded = |vertex: usize| welded_indices.get(vertex).copied().unwrap_or(0) as usize; + let welded_count = welded_indices.iter().max().map_or(0, |last| *last as usize + 1); + + let fitting_normals = fitting_normals(low, ray_normals); + let mut reach: Vec> = vec![None; welded_count]; + let mut widen = |vertex: usize, height: f32| { + if let Some(distances) = reach.get_mut(welded(vertex)) { + let (front, rear) = distances.unwrap_or((0.0, 0.0)); + *distances = Some((front.max(height), rear.max(-height))); + } + }; + + for (vertex, height) in heights_at_low_vertices(low, high, &fitting_normals, &keys, extent.diagonal).into_iter().enumerate() { + if let Some(height) = height { + widen(vertex, height); + } + } + let mut projected = Vec::new(); + for (batch, positions) in high.mesh.positions.chunks(PROJECTION_BATCH_VERTICES).enumerate() { + let first = batch * PROJECTION_BATCH_VERTICES; + positions + .par_iter() + .enumerate() + .map(|(index, &position)| project_high_vertex(request, &fitting_normals, &keys, first + index, position)) + .collect_into_vec(&mut projected); + + for (triangle, height) in projected.drain(..).flatten() { + for corner in low.tri(triangle).into_iter().flatten() { + widen(corner, height); + } + } + } + drop(projected); + + spread_to_neighbours(&mut reach, low.indices.as_chunks::<3>().0.iter().map(|corners| corners.map(|corner| welded(corner as usize)))); + + let floor = MARGIN_PER_DIAGONAL * extent.diagonal; + let padded = |distance: f32| distance * (1.0 + MARGIN_PER_DISTANCE) + floor; + let distances = + (0..low.positions.len()).map(|vertex| reach.get(welded(vertex)).copied().flatten().map(|(front, rear)| (padded(front), padded(rear)))).collect(); + + FittedCage { distances } + } + + /// The (front, rear) distances at `barycentric` of triangle `triangle` of the low poly `low` the cage was fitted to; `None` where the high poly reaches no corner + pub(crate) fn distances(&self, low: &Mesh, triangle: u32, barycentric: [f32; 2]) -> Option<(f32, f32)> { + let corners = low.tri(triangle as usize)?; + let [first, second, third] = [0, 1, 2].map(|corner| self.distances.get(corners[corner]).copied().flatten()); + let ((first_front, first_rear), (second_front, second_rear), (third_front, third_rear)) = (first?, second?, third?); + let [second_weight, third_weight] = barycentric; + let first_weight = 1.0 - second_weight - third_weight; + + Some(( + first_front * first_weight + second_front * second_weight + third_front * third_weight, + first_rear * first_weight + second_rear * second_weight + third_rear * third_weight, + )) + } +} + +/// `welded_indices` with the vertices of different mesh-name groups (`vertex_keys`, empty when names don't matter) kept apart, so a group's distances come only from its own high poly and never spread into another group +fn welded_within_groups<'a>(welded_indices: &'a [u32], vertex_keys: &[u32]) -> Cow<'a, [u32]> { + if vertex_keys.is_empty() { + return Cow::Borrowed(welded_indices); + } + + let mut indices: HashMap<(u32, Option), u32> = HashMap::new(); + welded_indices + .iter() + .enumerate() + .map(|(vertex, &welded)| { + let next = indices.len() as u32; + *indices.entry((welded, vertex_keys.get(vertex).copied())).or_insert(next) + }) + .collect() +} + +/// `ray_normals`, except where parts welded back to back cancelled a vertex's normal out: there, the vertex's own normal, the direction its transfer rays fall back to +fn fitting_normals<'a>(low: &Mesh, ray_normals: &'a [Vec3]) -> Cow<'a, [Vec3]> { + if !ray_normals.contains(&Vec3::ZERO) { + return Cow::Borrowed(ray_normals); + } + + ray_normals + .iter() + .enumerate() + .map(|(vertex, &welded_normal)| { + if welded_normal != Vec3::ZERO { + return welded_normal; + } + + low.normals.get(vertex).and_then(|normal| normal.try_normalize()).unwrap_or(welded_normal) + }) + .collect() +} + +/// Per low-poly vertex, how far along its ray normal the high-poly surface in front of it (positive) or behind it (negative) is. A ray that only finds a surface much farther than the nearest high-poly point (within `max_distance`) found another part, so the vertex takes that nearest point's height instead +fn heights_at_low_vertices(low: &Mesh, high: HighPoly, ray_normals: &[Vec3], keys: &NameKeys, max_distance: f32) -> Vec> { + low.positions + .par_iter() + .zip(ray_normals) + .enumerate() + .map(|(vertex, (&position, &up))| { + let low_key = keys.low_vertices.get(vertex); + let rays_reach = |triangle: u32| NameKeys::matches(low_key, keys.high_triangles.get(triangle as usize)); + let nearest = high.bvh.nearest(position, max_distance, &rays_reach)?; + let nearest_position = interpolate(high.mesh, &high.mesh.positions, nearest.tri, [nearest.u, nearest.v])?; + let ray_limit = nearest.t * MAX_RAY_PER_NEAREST_DISTANCE + MARGIN_PER_DIAGONAL * max_distance; + let distance = |direction: Vec3| high.bvh.closest_filtered(position, direction, ray_limit, &rays_reach).map(|hit| hit.t); + + Some(match (distance(up), distance(-up)) { + (Some(front), Some(rear)) if front <= rear => front, + (Some(front), None) => front, + (_, Some(rear)) => -rear, + (None, None) => (nearest_position - position).dot(up), + }) + }) + .collect() +} + +/// The nearest matching low-poly triangle and signed height of one high-poly vertex +fn project_high_vertex(request: &BakeRequest, ray_normals: &[Vec3], keys: &NameKeys, vertex: usize, position: Vec3) -> Option<(usize, f32)> { + let low = request.mesh; + let high_key = keys.high_vertices.get(vertex); + let rays_reach = |triangle: u32| NameKeys::matches(keys.low_triangles.get(triangle as usize), high_key); + let nearest = request.bvh.nearest(position, f32::INFINITY, &rays_reach)?; + let barycentric = [nearest.u, nearest.v]; + let low_position = interpolate(low, &low.positions, nearest.tri, barycentric)?; + let up = interpolate(low, ray_normals, nearest.tri, barycentric)?.try_normalize()?; + + Some((nearest.tri as usize, (position - low_position).dot(up))) +} + +/// Give each vertex without distances the largest of its nearest fitted neighbours', walking outward along the edges of `triangles` +fn spread_to_neighbours(reach: &mut [Option<(f32, f32)>], triangles: impl Iterator) { + // Only unfitted vertices adjacent to a fitted region can gain distances + if reach.iter().all(Option::is_some) || reach.iter().all(Option::is_none) { + return; + } + + let mut neighbours = vec![Vec::new(); reach.len()]; + for corners in triangles { + for (corner, next) in [(0, 1), (1, 2), (2, 0)] { + if let (true, Some(list)) = (corners[next] < reach.len(), neighbours.get_mut(corners[corner])) { + list.push(corners[next]); + } + if let (true, Some(list)) = (corners[corner] < reach.len(), neighbours.get_mut(corners[next])) { + list.push(corners[corner]); + } + } + } + + // Propagate distances from the preceding breadth-first layer + let mut steps: Vec> = reach.iter().map(|distances| distances.map(|_| 0)).collect(); + let mut queue: VecDeque = (0..reach.len()).filter(|vertex| reach[*vertex].is_some()).collect(); + while let Some(vertex) = queue.pop_front() { + let (Some((front, rear)), Some(step)) = (reach[vertex], steps[vertex]) else { continue }; + + for &neighbour in &neighbours[vertex] { + match steps[neighbour] { + None => { + steps[neighbour] = Some(step + 1); + reach[neighbour] = Some((front, rear)); + queue.push_back(neighbour); + } + Some(neighbour_step) if neighbour_step == step + 1 => { + let (neighbour_front, neighbour_rear) = reach[neighbour].unwrap_or((0.0, 0.0)); + reach[neighbour] = Some((neighbour_front.max(front), neighbour_rear.max(rear))); + } + Some(_) => {} + } + } + } +} + +#[cfg(test)] +mod tests { + use super::{spread_to_neighbours, welded_within_groups}; + + #[test] + fn coincident_vertices_of_different_name_groups_are_not_welded() { + // The coincident pairs span different mesh-name groups + assert_eq!(welded_within_groups(&[0, 0, 1, 1], &[5, 7, 7, 5]).as_ref(), [0, 1, 2, 3]); + assert_eq!(welded_within_groups(&[0, 0, 1, 1], &[5, 5, 7, 7]).as_ref(), [0, 0, 1, 1], "same group: still welded"); + assert_eq!(welded_within_groups(&[0, 0, 1], &[]).as_ref(), [0, 0, 1], "without name matching nothing changes"); + } + + #[test] + fn unfitted_vertices_take_the_largest_distances_of_their_nearest_fitted_neighbours() { + // A strip of triangles 0-1-2, 1-2-3, 2-3-4: vertices 0 and 4 are fitted + let mut reach = vec![Some((1.0, 0.5)), None, None, None, Some((3.0, 0.25))]; + + spread_to_neighbours(&mut reach, [[0, 1, 2], [1, 2, 3], [2, 3, 4]].into_iter()); + + assert_eq!(reach[1], Some((1.0, 0.5)), "one step from vertex 0 only"); + assert_eq!(reach[3], Some((3.0, 0.25)), "one step from vertex 4 only"); + assert_eq!(reach[2], Some((3.0, 0.5)), "one step from both: the larger of each"); + } +} diff --git a/crates/bake/src/cage/high_poly_reach.rs b/crates/bake/src/cage/high_poly_reach.rs index 2f461343..b227ca06 100644 --- a/crates/bake/src/cage/high_poly_reach.rs +++ b/crates/bake/src/cage/high_poly_reach.rs @@ -75,7 +75,7 @@ impl HighPolyReach { } /// Each vertex's mesh-name key, from the first triangle that uses it -fn vertex_keys(mesh: &Mesh, triangle_keys: &[u32]) -> Vec { +pub(super) fn vertex_keys(mesh: &Mesh, triangle_keys: &[u32]) -> Vec { let mut keys = vec![ANY; mesh.positions.len()]; for (corners, &triangle_key) in mesh.indices.as_chunks::<3>().0.iter().zip(triangle_keys) { for &corner in corners { diff --git a/crates/bake/src/cage/name_keys.rs b/crates/bake/src/cage/name_keys.rs new file mode 100644 index 00000000..077cd826 --- /dev/null +++ b/crates/bake/src/cage/name_keys.rs @@ -0,0 +1,38 @@ +use super::high_poly_reach::vertex_keys; +use crate::map::transfer_keys; +use crate::tracing::ANY; +use crate::{BakeRequest, HighPoly}; +use texturecraft_core::MeshMatchMode; + +/// The mesh-name keys of a bake's low and high poly, per triangle and per vertex; all empty when every ray may hit every part +#[derive(Default)] +pub(super) struct NameKeys { + pub(super) low_triangles: Vec, + pub(super) low_vertices: Vec, + pub(super) high_triangles: Vec, + pub(super) high_vertices: Vec, +} + +impl NameKeys { + /// The keys `request` bakes with against `high`: filled only when it matches by mesh name + pub(super) fn of(request: &BakeRequest, high: HighPoly) -> NameKeys { + match request.settings.high_poly.match_mode { + MeshMatchMode::Always => NameKeys::default(), + MeshMatchMode::ByMeshName => { + let (low_triangles, high_triangles) = transfer_keys(request); + NameKeys { + low_vertices: vertex_keys(request.mesh, &low_triangles), + high_vertices: vertex_keys(high.mesh, &high_triangles), + low_triangles, + high_triangles, + } + } + } + } + + /// Whether a ray from the low-poly part keyed `low_key` may hit the high-poly part keyed `high_key`; a missing key is a part any ray may hit + pub(super) fn matches(low_key: Option<&u32>, high_key: Option<&u32>) -> bool { + let low_key = low_key.copied().unwrap_or(ANY); + low_key == ANY || low_key == high_key.copied().unwrap_or(ANY) + } +} diff --git a/crates/bake/src/cage/ray_frame.rs b/crates/bake/src/cage/ray_frame.rs index e8692cf2..590e52e1 100644 --- a/crates/bake/src/cage/ray_frame.rs +++ b/crates/bake/src/cage/ray_frame.rs @@ -1,4 +1,4 @@ -use super::RayStart; +use super::{FittedCage, RayStart}; use crate::MeshExtent; use crate::map::{interpolate, welded}; use crate::skew::PreparedSkew; @@ -7,11 +7,12 @@ use texturecraft_core::CageType; use texturecraft_geom::glam::Vec3; use texturecraft_geom::{Mesh, Surface}; -/// What decides where transfer rays start: the cage mesh or the averaged normals, skew and painted cage amount +/// What decides where transfer rays start: the cage mesh, the automatic cage's fitted distances, or the averaged normals, skew and painted cage amount pub(crate) struct RayFrame<'a> { mesh: &'a Mesh, ray_normals: Vec, cage: Option<&'a Mesh>, + fitted: Option, skew: Option>, cage_paint: Option<&'a BakePaintMap>, /// Cage-file offsets this short count as none: the ray starts from the distance-based cage instead @@ -23,18 +24,24 @@ pub(crate) struct RayFrame<'a> { impl<'a> RayFrame<'a> { pub(crate) fn new(request: &BakeRequest<'a>, extent: MeshExtent) -> Result, BakeError> { let settings = request.settings; - let ray_normals = match settings.cage.average_normals && request.high.is_some() { + + // The automatic cage is one closed shell, so its rays always follow the averaged normals + let automatic_high = request.high.filter(|_| settings.cage.kind == CageType::Automatic); + let (ray_normals, fitted) = match (settings.cage.average_normals || automatic_high.is_some()) && request.high.is_some() { true => { let (welded_indices, _, normals) = welded(request.mesh, extent.diagonal); - welded_indices.iter().map(|index| normals.get(*index as usize).copied().unwrap_or(Vec3::Y)).collect() + let ray_normals: Vec = welded_indices.iter().map(|index| normals.get(*index as usize).copied().unwrap_or(Vec3::Y)).collect(); + let fitted = automatic_high.map(|high| FittedCage::new(request, high, &welded_indices, &ray_normals, extent)); + (ray_normals, fitted) } - false => Vec::new(), + false => (Vec::new(), None), }; Ok(RayFrame { mesh: request.mesh, ray_normals, cage: if settings.cage.kind == CageType::CustomFile { request.cage } else { None }, + fitted, skew: request.skew.map(|skew_map| PreparedSkew::new(skew_map, request.mesh, extent.scale, settings.skew)).transpose()?, cage_paint: request.cage_paint, ray_epsilon: extent.ray_epsilon(), @@ -54,6 +61,11 @@ impl<'a> RayFrame<'a> { } let averaged_normal = interpolate(self.mesh, &self.ray_normals, surface.tri, barycentric).and_then(Vec3::try_normalize).unwrap_or(surface.nrm); + let fitted_distances = self.fitted.as_ref().and_then(|fitted| fitted.distances(self.mesh, surface.tri, barycentric)); + if let Some((front, rear)) = fitted_distances { + return RayStart::Fitted { up: averaged_normal, front, rear }; + } + let up = match &self.skew { Some(skew) => skew.correct(self.mesh, surface, averaged_normal), None => averaged_normal, diff --git a/crates/bake/src/cage/ray_start.rs b/crates/bake/src/cage/ray_start.rs index c0c3923a..8c21bb9b 100644 --- a/crates/bake/src/cage/ray_start.rs +++ b/crates/bake/src/cage/ray_start.rs @@ -7,6 +7,8 @@ pub enum RayStart { CageMesh(Vec3), /// Out along `up` by the frontal distance times `scale` (the painted cage amount) Distance { up: Vec3, scale: f32 }, + /// Out along `up` by `front` world units and reaching `rear` past the low-poly point: the automatic cage's own distances + Fitted { up: Vec3, front: f32, rear: f32 }, } impl RayStart { @@ -15,6 +17,16 @@ impl RayStart { match *self { RayStart::CageMesh(offset) => position - offset, RayStart::Distance { up, scale } => position + up * frontal * scale, + RayStart::Fitted { up, front, .. } => position + up * front, + } + } + + /// The ray's direction, how far it runs to the low-poly point and how far past it, at `frontal` and `rear` world units of the distance settings + pub fn span(&self, frontal: f32, rear: f32) -> (Vec3, f32, f32) { + match *self { + RayStart::CageMesh(offset) => (offset.normalize_or_zero(), offset.length(), rear), + RayStart::Distance { up, scale } => (-up, frontal * scale, rear), + RayStart::Fitted { up, front, rear: fitted_rear } => (-up, front, fitted_rear), } } } diff --git a/crates/bake/src/cage/vertex_reach.rs b/crates/bake/src/cage/vertex_reach.rs index 34adea92..2c6df8e8 100644 --- a/crates/bake/src/cage/vertex_reach.rs +++ b/crates/bake/src/cage/vertex_reach.rs @@ -17,10 +17,7 @@ impl VertexReach { /// Whether the ray misses the vertex (or may not hit its part) at `frontal` and `rear` world units of cage distance; with `ignore_backface` it also misses a vertex whose triangles face away from the ray pub fn missed(&self, frontal: f32, rear: f32, ignore_backface: bool) -> bool { let origin = self.start.origin(self.low_position, frontal); - let (direction, front) = match self.start { - RayStart::CageMesh(offset) => (offset.normalize_or_zero(), offset.length()), - RayStart::Distance { up, scale } => (-up, frontal * scale), - }; + let (direction, front, rear) = self.start.span(frontal, rear); let along_ray = (self.high_position - origin).dot(direction); !self.name_matches || !(0.0..=front + rear).contains(&along_ray) || (ignore_backface && self.high_facing.dot(direction) > 0.0) diff --git a/crates/bake/src/lib.rs b/crates/bake/src/lib.rs index 1d99ab36..5c8c3ba8 100644 --- a/crates/bake/src/lib.rs +++ b/crates/bake/src/lib.rs @@ -5,6 +5,7 @@ mod bake_error; mod bake_output; +mod bake_passes; mod bake_request; mod cage; mod high_poly; @@ -14,6 +15,7 @@ mod progress; pub use bake_error::BakeError; pub use bake_output::BakeOutput; +pub use bake_passes::BakePasses; pub use bake_request::BakeRequest; pub use cage::{CageShell, HighPolyReach, RayStart, VertexReach}; pub use high_poly::HighPoly; @@ -149,7 +151,7 @@ fn alloc(count: usize, value: T) -> Result, BakeError> { } pub fn bake(request: &BakeRequest, progress: &Progress) -> Result { - bake_in_strips(request, progress, STRIP_TEXELS, &CpuTracer, &[]) + bake_tiles(request, progress, &[], None) } /// Retry on the CPU if the supplied tracer fails @@ -159,19 +161,12 @@ pub fn bake_on(request: &BakeRequest, progress: &Progress, tracer: &dyn Tracer) /// Excluded atlas blocks produce no samples; their geometry still participates in ray tracing pub fn bake_tiles(request: &BakeRequest, progress: &Progress, excluded_tiles: &[(u32, u32)], tracer: Option<&dyn Tracer>) -> Result { - let tracer = tracer.unwrap_or(&CpuTracer); - match bake_in_strips(request, progress, STRIP_TEXELS, tracer, excluded_tiles) { - Err(BakeError::Tracer(error)) => { - let mut output = bake_in_strips(request, progress, STRIP_TEXELS, &CpuTracer, excluded_tiles)?; - output.tracer = format!("CPU ({} unavailable: {error})", tracer.name()); - Ok(output) - } - result => result, - } + BakePasses::new(*request).run(request.settings, progress, excluded_tiles, tracer, STRIP_TEXELS) } type OutRow<'a> = Vec<&'a mut [f32]>; +#[cfg(test)] fn bake_in_strips( request: &BakeRequest, progress: &Progress, @@ -179,9 +174,19 @@ fn bake_in_strips( tracer: &dyn Tracer, excluded_tiles: &[(u32, u32)], ) -> Result { - validate(request)?; - if excluded_tiles.iter().any(|(column, row)| *column >= request.tiles.0 || *row >= request.tiles.1) { - return Err(BakeError::Invalid("excluded UV tile lies outside the bake atlas".into())); + BakePasses::new(*request).run(request.settings, progress, excluded_tiles, Some(tracer), strip_texels) +} + +fn bake_prepared( + request: &BakeRequest, + context: &map::BakeContext, + progress: &Progress, + strip_texels: usize, + tracer: &dyn Tracer, + excluded_tiles: &[(u32, u32)], +) -> Result { + if progress.cancel.load(Relaxed) { + return Err(BakeError::Cancelled); } let settings = request.settings; @@ -189,7 +194,6 @@ fn bake_in_strips( let tile_size = (tile_width as usize, tile_height as usize); let samples_per_axis = settings.common.antialiasing.samples_per_axis() as usize; let (width, height) = (tile_size.0 * request.tiles.0 as usize, tile_size.1 * request.tiles.1 as usize); - let context = map::BakeContext::new(request)?; let tracer = if context.casts_rays() { tracer } else { &CpuTracer }; let meshes = context.trace_meshes(); let mut scene = tracer.scene(&meshes)?; @@ -259,9 +263,10 @@ fn bake_in_strips( if progress.cancel.load(Relaxed) { return Err(BakeError::Cancelled); } + // Global sample indices keep noise unchanged across strip and batch sizes bake_rows( - &context, + context, &maps, request.mesh, &gbuffer, @@ -313,6 +318,7 @@ fn bake_in_strips( if progress.cancel.load(Relaxed) { return Err(BakeError::Cancelled); } + progress.done.store(10_000, Relaxed); Ok(BakeOutput { resolution: width as u32, height: height as u32, maps: output, tracer: tracer.name() }) } @@ -349,6 +355,7 @@ fn bake_rows( .collect() }) .collect(); + let row_offsets: Vec = samples_by_row .iter() .scan(0, |sample_count, row| { @@ -362,11 +369,12 @@ fn bake_rows( true => { let (rays, frontal_distances): (Vec, Vec) = samples().map(|sample| context.transfer_ray(&sample.surface, sample.bary)).unzip(); let hits = scene.closest(1, &rays, context.ignore_transfer_backface())?; - hits.into_par_iter().zip(frontal_distances).map(|(hit, front)| context.transfer(hit, front)).collect() + hits.into_par_iter().zip(&rays).zip(frontal_distances).map(|((hit, ray), front)| context.transfer(hit, front, ray.max_distance)).collect() } false => Vec::new(), }; let transfer = |sample_index: usize| transfers.get(sample_index).and_then(Option::as_ref); + let curvature = match context.traces_curvature() { true => { let items: Vec<(&Surface, Option<&map::Transfer>)> = samples_by_row @@ -379,6 +387,7 @@ fn bake_rows( } false => Vec::new(), }; + let queries: Vec = match context.ao.is_some() || context.bent.is_some() || context.thickness.is_some() { true => samples_by_row .par_iter() @@ -388,6 +397,7 @@ fn bake_rows( .collect(), false => Vec::new(), }; + // Share occlusion results when the bent-normal ray settings match let separate_bent_pass = context.bent.filter(|_| context.bent != context.ao); let passes: Vec = [context.ao, separate_bent_pass, context.thickness].into_iter().flatten().collect(); diff --git a/crates/bake/src/map/bake_context.rs b/crates/bake/src/map/bake_context.rs index bbeb623e..156d392f 100644 --- a/crates/bake/src/map/bake_context.rs +++ b/crates/bake/src/map/bake_context.rs @@ -1,7 +1,7 @@ use super::curvature::Curvature; use super::sampling::{pack, splitmix64, tangent_normal}; use super::{position_projection::PositionProjection, source::Source, traced::Traced, transfer::Transfer}; -use crate::cage::{RayFrame, RayStart}; +use crate::cage::RayFrame; use crate::tracing::{ANY, Hemisphere, Query, Ray, RayKind, RayScene, TraceMesh}; use crate::{BakeError, BakeRequest, MeshExtent}; use rayon::prelude::*; @@ -12,10 +12,13 @@ use texturecraft_geom::{Hit, Surface, surface_at}; const CURVATURE_CHUNK: usize = 1 << 15; +/// Height relative to the rays divides by the ray's length; this keeps a zero-length ray from dividing by zero +const SHORTEST_RAY: f32 = 1e-20; + pub(crate) struct BakeContext<'a> { low: Source<'a>, high: Option>, - ray_frame: RayFrame<'a>, + ray_frame: &'a RayFrame<'a>, settings: &'a BakeSettings, frontal: f32, rear: f32, @@ -28,11 +31,9 @@ pub(crate) struct BakeContext<'a> { } impl<'a> BakeContext<'a> { - pub(crate) fn new(request: &BakeRequest<'a>) -> Result, BakeError> { + pub(crate) fn with_frame(request: &BakeRequest<'a>, extent: MeshExtent, ray_frame: &'a RayFrame<'a>) -> Self { let settings = request.settings; - let extent = MeshExtent::of(request.mesh)?; let (low, high) = Source::of_request(request); - let ray_frame = RayFrame::new(request, extent)?; let (mesh_scale, ray_epsilon) = (extent.scale, extent.ray_epsilon()); let pass = |map: BakedMap, ray_settings: &RaySettings, kind: RayKind| { let half_angle_radians = (ray_settings.spread.clamp(0.0, 180.0) * 0.5).to_radians(); @@ -74,7 +75,7 @@ impl<'a> BakeContext<'a> { } let cage_units = ray_frame.cage_units; - Ok(BakeContext { + BakeContext { low, high, ray_frame, @@ -87,7 +88,7 @@ impl<'a> BakeContext<'a> { ao, bent, thickness, - }) + } } pub(crate) fn ignore_transfer_backface(&self) -> bool { @@ -109,21 +110,19 @@ impl<'a> BakeContext<'a> { pub(crate) fn transfer_ray(&self, surface: &Surface, barycentric: [f32; 2]) -> (Ray, f32) { let start = self.ray_frame.start(surface, barycentric); let origin = start.origin(surface.pos, self.frontal); - let (direction, front) = match start { - RayStart::CageMesh(offset) => (offset.normalize(), offset.length()), - RayStart::Distance { up, scale } => (-up, self.frontal * scale), - }; + let (direction, front, rear) = start.span(self.frontal, self.rear); let key = match self.settings.high_poly.match_mode { MeshMatchMode::Always => ANY, MeshMatchMode::ByMeshName => self.low.key.get(surface.tri as usize).copied().unwrap_or(ANY), }; - (Ray { origin, direction, max_distance: front + self.rear, key }, front) + (Ray { origin, direction, max_distance: front + rear, key }, front) } - pub(crate) fn transfer(&self, hit: Option, front: f32) -> Option { + /// What the transfer ray that ran `front` to the low poly and `ray_length` in all brought back from the high poly + pub(crate) fn transfer(&self, hit: Option, front: f32, ray_length: f32) -> Option { let (high, hit) = (self.high.as_ref()?, hit?); let surface = surface_at(high.mesh, hit.tri, hit.u, hit.v)?; - Some(Transfer { surface, bary: [hit.u, hit.v], t: hit.t, front }) + Some(Transfer { surface, bary: [hit.u, hit.v], t: hit.t, front, ray_length }) } pub(crate) fn query(&self, transfer: Option<&Transfer>, low_surface: &Surface, seed: u64) -> Query { @@ -245,7 +244,7 @@ impl<'a> BakeContext<'a> { let relative_to_rays = self.settings.maps.height.parameters.normalization == texturecraft_core::HeightNormalization::RelativeToRayDistances; [transfer.map_or(if relative_to_rays { 0.5 } else { 0.0 }, |hit| { let height = hit.front - hit.t; - if relative_to_rays { (0.5 + height / (hit.front + self.rear).max(1e-20)).clamp(0.0, 1.0) } else { height } + if relative_to_rays { (0.5 + height / hit.ray_length.max(SHORTEST_RAY)).clamp(0.0, 1.0) } else { height } }); 3] } BakedMap::Opacity if missed => [0.0; 3], diff --git a/crates/bake/src/map/transfer.rs b/crates/bake/src/map/transfer.rs index c1200053..46c67f28 100644 --- a/crates/bake/src/map/transfer.rs +++ b/crates/bake/src/map/transfer.rs @@ -5,4 +5,6 @@ pub(crate) struct Transfer { pub(super) bary: [f32; 2], pub(super) t: f32, pub(super) front: f32, + /// The whole ray, from the cage to its rear end + pub(super) ray_length: f32, } diff --git a/crates/bake/src/test/cage_shell.rs b/crates/bake/src/test/cage_shell.rs index 40edd3b8..a437c089 100644 --- a/crates/bake/src/test/cage_shell.rs +++ b/crates/bake/src/test/cage_shell.rs @@ -17,7 +17,9 @@ fn painted_map() -> BakePaintMap { fn assert_cage_matches_the_ray_origins(request: &BakeRequest) { let shell = CageShell::new(request).unwrap(); let corners = shell.corners(request.settings.cage.max_frontal); - let context = BakeContext::new(request).unwrap(); + let extent = crate::MeshExtent::of(request.mesh).unwrap(); + let frame = crate::cage::RayFrame::new(request, extent).unwrap(); + let context = BakeContext::with_frame(request, extent, &frame); let triangles: Vec = request.mesh.triangles_of(request.material).collect(); assert_eq!(corners.len(), triangles.len() * 3); @@ -60,6 +62,12 @@ fn the_cage_corners_are_the_bake_ray_origins() { face_normals }; assert_cage_matches_the_ray_origins(&request(&face_normals)); + let automatic = { + let mut automatic = bake_settings.clone(); + automatic.cage.kind = CageType::Automatic; + automatic + }; + assert_cage_matches_the_ray_origins(&request(&automatic)); } #[test] diff --git a/crates/bake/src/test/fitted_cage.rs b/crates/bake/src/test/fitted_cage.rs new file mode 100644 index 00000000..3cfec7a5 --- /dev/null +++ b/crates/bake/src/test/fitted_cage.rs @@ -0,0 +1,250 @@ +use super::{covered_values, settings, transfer}; +use crate::{BakeRequest, CageShell, HighPoly, HighPolyReach}; +use texturecraft_core::{BakeSettings, BakedMap, CageType, MeshMatchMode}; +use texturecraft_geom::glam::Vec3; +use texturecraft_geom::{Bvh, Mesh, primitives}; + +/// A distance setting far larger than any fitted distance in these tests, to tell the two apart +const UNFITTED_DISTANCE: f32 = 0.5; + +/// Settings baking `maps` with the automatic cage, and distance settings no fitted cage comes near +fn automatic(maps: &[BakedMap]) -> BakeSettings { + let mut bake_settings = settings(32, maps); + bake_settings.cage.kind = CageType::Automatic; + bake_settings.cage.relative_to_bounding_box = false; + (bake_settings.cage.max_frontal, bake_settings.cage.max_rear) = (UNFITTED_DISTANCE, UNFITTED_DISTANCE); + bake_settings +} + +/// How far each corner of the automatic cage of the flat `low` around `high` rises above it, with the corner's low-poly position +fn cage_heights(low: &Mesh, high: &Mesh, bake_settings: &BakeSettings) -> Vec<(Vec3, f32)> { + let (low_bvh, high_bvh) = (Bvh::new(low), Bvh::new(high)); + let request = BakeRequest { + low_base_color: &[], + mesh: low, + bvh: &low_bvh, + material: 0, + settings: bake_settings, + high: Some(HighPoly { file_ids: &[], mesh: high, bvh: &high_bvh, base_color: &[] }), + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }; + let shell = CageShell::new(&request).unwrap(); + let corners = shell.corners(bake_settings.cage.max_frontal); + shell.positions.iter().zip(corners).map(|(position, corner)| (*position, corner.y - position.y)).collect() +} + +/// Every submesh on the first material, so the cage shell of material 0 covers all the parts +fn one_material(mesh: &mut Mesh) { + mesh.materials.truncate(1); + for submesh in &mut mesh.submeshes { + submesh.material = 0; + } +} + +#[test] +fn the_automatic_cage_reaches_a_high_poly_the_default_distances_miss() { + let low = primitives::cube(1.0); + let high = primitives::sphere(0.8, 32, 16); + let opacity_of = |bake_settings: &BakeSettings| -> Vec { + let output = transfer(&low, &high, None, bake_settings).unwrap(); + covered_values(&low, &output, BakedMap::Opacity).into_iter().map(|(_, opacity)| opacity).collect() + }; + + let distance_based = opacity_of(&settings(32, &[BakedMap::Opacity])); + assert!(distance_based.contains(&0.0), "the sphere is beyond the default distances at the middle of each face"); + + let mut bake_settings = settings(32, &[BakedMap::Opacity]); + bake_settings.cage.kind = CageType::Automatic; + let fitted = opacity_of(&bake_settings); + assert!(fitted.iter().all(|opacity| *opacity == 1.0), "every ray of the automatic cage finds the sphere"); + + // The triangles at the sphere's poles have no area, so a pole vertex has no side to face the ray with + bake_settings.high_poly.ignore_backface = false; + let (low_bvh, high_bvh) = (Bvh::new(&low), Bvh::new(&high)); + let request = BakeRequest { + low_base_color: &[], + mesh: &low, + bvh: &low_bvh, + material: 0, + settings: &bake_settings, + high: Some(HighPoly { file_ids: &[], mesh: &high, bvh: &high_bvh, base_color: &[] }), + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }; + let reach = HighPolyReach::new(&request).unwrap(); + for vertex in 0..high.positions.len() { + assert_eq!(reach.missed(vertex, 0.0, 0.0), Some(false), "high-poly vertex {vertex} is inside the cage whatever the distance settings"); + } +} + +#[test] +fn the_automatic_cage_stays_low_where_the_high_poly_is_low() { + const LOW_HEIGHT: f32 = 0.01; + const RAISED_HEIGHT: f32 = 0.2; + const RAISED_FROM_X: f32 = 0.25; + + let low = primitives::plane(1.0, 8); + let mut high = primitives::plane(1.0, 40); + for position in &mut high.positions { + position.y = if position.x > RAISED_FROM_X { RAISED_HEIGHT } else { LOW_HEIGHT }; + } + + let heights = cage_heights(&low, &high, &automatic(&[BakedMap::Normal])); + + for (position, height) in heights { + if position.x < 0.0 { + assert!((LOW_HEIGHT..RAISED_HEIGHT / 2.0).contains(&height), "the cage at {position} hugs the low part: {height}"); + } else if position.x > RAISED_FROM_X + 0.125 { + assert!((RAISED_HEIGHT..RAISED_HEIGHT * 2.0).contains(&height), "the cage at {position} clears the raised part: {height}"); + } + } +} + +#[test] +fn a_ray_that_only_finds_a_far_surface_takes_the_nearest_surface_height_instead() { + const PATCH_HEIGHT: f32 = 0.02; + const CEILING_HEIGHT: f32 = 1.0; + + // A low-plane vertex beside the patch's edge: the patch is its nearest high poly, the ceiling is straight above it + const BESIDE_PATCH: Vec3 = Vec3::new(0.125, 0.0, 0.0); + + // Far enough that the ceiling's own corners are nearest to the low plane's border, not to the vertex tested + const CEILING_REACH: f32 = 1000.0; + + // The ceiling starts just past the patch's edge (x = 0), the patch covers the low plane's other half + const CEILING_FROM_X: f32 = 0.05; + const PATCH_SIZE: f32 = 0.5; + const SAME_POSITION: f32 = 1e-4; + + let low = primitives::plane(1.0, 8); + let mut high = primitives::plane(PATCH_SIZE, 1); + for position in &mut high.positions { + *position = Vec3::new(position.x - PATCH_SIZE / 2.0, PATCH_HEIGHT, position.z); + } + let ceiling = Mesh::from_parts( + vec![ + Vec3::new(CEILING_FROM_X, CEILING_HEIGHT, -CEILING_REACH), + Vec3::new(CEILING_FROM_X, CEILING_HEIGHT, CEILING_REACH), + Vec3::new(CEILING_REACH, CEILING_HEIGHT, 0.0), + ], + None, + vec![Default::default(); 3], + vec![0, 1, 2], + "ceiling", + ) + .unwrap(); + high.append(&ceiling); + + let heights = cage_heights(&low, &high, &automatic(&[BakedMap::Normal])); + + let (_, height) = heights.iter().find(|(position, _)| position.distance(BESIDE_PATCH) < SAME_POSITION).unwrap(); + assert!(*height < CEILING_HEIGHT / 2.0, "the cage beside the patch stays near the patch, not the ceiling: {height}"); +} + +#[test] +fn a_part_no_high_poly_part_matches_keeps_the_distance_settings() { + let mut low = primitives::plane(1.0, 2); + let mut high = primitives::plane(1.0, 2); + low.submeshes[0].name = "panel_low".into(); + high.submeshes[0].name = "door_high".into(); + let mut bake_settings = automatic(&[BakedMap::Normal]); + bake_settings.high_poly.match_mode = MeshMatchMode::ByMeshName; + + let heights = cage_heights(&low, &high, &bake_settings); + + assert!(heights.iter().all(|(_, height)| *height == UNFITTED_DISTANCE)); +} + +#[test] +fn a_part_meeting_another_part_takes_its_distances_from_its_own_high_poly_only() { + const LOW_HEIGHT: f32 = 0.01; + const RAISED_HEIGHT: f32 = 0.3; + + // Two low parts sharing the edge x = 0, under a low and a raised high-poly part matched by name + let part = |name: &str, side: f32, height: f32, subdivisions: usize| { + let mut part = primitives::plane(1.0, subdivisions); + for position in &mut part.positions { + *position += Vec3::new(side * 0.5, height, 0.0); + } + part.submeshes[0].name = name.into(); + part + }; + let mut low = part("left_low", -1.0, 0.0, 4); + low.append(&part("right_low", 1.0, 0.0, 4)); + let mut high = part("left_high", -1.0, LOW_HEIGHT, 8); + high.append(&part("right_high", 1.0, RAISED_HEIGHT, 8)); + for mesh in [&mut low, &mut high] { + one_material(mesh); + } + let mut bake_settings = automatic(&[BakedMap::Normal]); + bake_settings.high_poly.match_mode = MeshMatchMode::ByMeshName; + + let heights = cage_heights(&low, &high, &bake_settings); + + // The left part's triangles come first, three corners each + let left_corners = low.submeshes[0].count as usize; + for (position, height) in &heights[..left_corners] { + assert!(*height < RAISED_HEIGHT / 2.0, "the left part's cage at {position} stays near the left high poly: {height}"); + } +} + +#[test] +fn parts_back_to_back_fit_their_cages_along_their_own_normals() { + const SHEET_DISTANCE: f32 = 0.2; + + // A plane facing up and the same plane facing down, each facing its own high-poly sheet: welded, their normals cancel out + let named = |mut mesh: Mesh, name: &str| { + mesh.submeshes[0].name = name.into(); + mesh + }; + let facing_down = |mut mesh: Mesh| { + for normal in &mut mesh.normals { + *normal = -*normal; + } + for triangle in mesh.indices.as_chunks_mut::<3>().0 { + triangle.swap(1, 2); + } + mesh + }; + let sheet = |height: f32| { + let mut sheet = primitives::plane(1.0, 8); + for position in &mut sheet.positions { + position.y = height; + } + sheet + }; + let mut low = named(primitives::plane(1.0, 4), "front_low"); + low.append(&named(facing_down(primitives::plane(1.0, 4)), "back_low")); + let mut high = named(sheet(SHEET_DISTANCE), "front_high"); + high.append(&named(facing_down(sheet(-SHEET_DISTANCE)), "back_high")); + for mesh in [&mut low, &mut high] { + one_material(mesh); + } + + for match_mode in [MeshMatchMode::Always, MeshMatchMode::ByMeshName] { + let mut bake_settings = automatic(&[BakedMap::Normal]); + bake_settings.high_poly.match_mode = match_mode; + + let heights = cage_heights(&low, &high, &bake_settings); + + // The front part's triangles come first, three corners each + let front_corners = low.submeshes[0].count as usize; + for (position, height) in &heights[..front_corners] { + assert!( + (SHEET_DISTANCE..UNFITTED_DISTANCE).contains(height), + "{match_mode:?}: the front part's cage at {position} reaches the sheet above it, fitted: {height}" + ); + } + for (position, height) in &heights[front_corners..] { + assert!( + (-UNFITTED_DISTANCE..=-SHEET_DISTANCE).contains(height), + "{match_mode:?}: the back part's cage at {position} reaches the sheet below it, fitted: {height}" + ); + } + } +} diff --git a/crates/bake/src/test/high_poly_reach.rs b/crates/bake/src/test/high_poly_reach.rs index 8a4f83c4..b001737b 100644 --- a/crates/bake/src/test/high_poly_reach.rs +++ b/crates/bake/src/test/high_poly_reach.rs @@ -69,7 +69,9 @@ fn a_vertex_is_missed_exactly_when_the_bake_ray_misses_it() { tiles: (1, 1), }; let reach = HighPolyReach::new(&request).unwrap(); - let context = BakeContext::new(&request).unwrap(); + let extent = crate::MeshExtent::of(request.mesh).unwrap(); + let frame = crate::cage::RayFrame::new(&request, extent).unwrap(); + let context = BakeContext::with_frame(&request, extent, &frame); for (vertex, vertex_reach) in reach.vertices.iter().enumerate() { let (vertex_reach, missed) = (vertex_reach.unwrap(), reach.missed(vertex, max_frontal, max_rear).unwrap()); @@ -94,6 +96,7 @@ fn a_vertex_is_missed_exactly_when_the_bake_ray_misses_it() { } } } + assert!(checked[0] > 100 && checked[1] > 100, "both reached and missed vertices were compared: {checked:?}"); } @@ -173,11 +176,14 @@ fn matching_by_mesh_name_misses_the_parts_with_another_name() { tiles: (1, 1), }; let reach = HighPolyReach::new(&request).unwrap(); - let context = BakeContext::new(&request).unwrap(); + let extent = crate::MeshExtent::of(request.mesh).unwrap(); + let frame = crate::cage::RayFrame::new(&request, extent).unwrap(); + let context = BakeContext::with_frame(&request, extent, &frame); let (_, high_keys) = transfer_keys(&request); for (vertex, vertex_reach) in reach.vertices.iter().enumerate() { let (vertex_reach, missed) = (vertex_reach.unwrap(), reach.missed(vertex, 0.02, 0.01).unwrap()); + // On the line where the two parts meet, a ray reaches either part's triangles if vertex_reach.high_position.x.abs() < BOUNDARY { continue; diff --git a/crates/bake/src/tests.rs b/crates/bake/src/tests.rs index dab94f80..7d94031e 100644 --- a/crates/bake/src/tests.rs +++ b/crates/bake/src/tests.rs @@ -20,6 +20,9 @@ mod bent_normal_space; #[path = "test/cage_shell.rs"] mod cage_shell; +#[path = "test/fitted_cage.rs"] +mod fitted_cage; + #[path = "test/high_poly_reach.rs"] mod high_poly_reach; @@ -1056,24 +1059,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..dd440224 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.sources().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/curvature_sizes.rs b/crates/compose/src/curvature_sizes.rs index 0b7138bc..4660ca45 100644 --- a/crates/compose/src/curvature_sizes.rs +++ b/crates/compose/src/curvature_sizes.rs @@ -4,13 +4,16 @@ use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex, Weak}; use rayon::prelude::*; -use texturecraft_core::{BakedMap, BlockScales, CurvatureDetail}; +use texturecraft_core::{BakedMap, BlockScales}; use texturecraft_texel::dilate::{DilationMap, NONE}; use crate::curvature_size_level::{CurvatureSizeLevel, DEVIATION_SCALE}; use crate::eval::{BLUR_BOX_PASSES, Inputs, blur}; -/// The curvature map padded past its UV islands and blurred at each size of [`CurvatureDetail::SIZES`] after the first. +/// The blur radius of each level in texels at 2K: the detail sizes of [`texturecraft_core::CurvatureDetail::SIZES`] after the first, then wider ones the wear generators' edges smoothness reaches +pub const LEVEL_RADII: [f32; 8] = [1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0, 128.0]; + +/// The curvature map padded past its UV islands and blurred at each radius of [`LEVEL_RADII`] pub struct CurvatureSizes { /// One per blurred size, built once a generator gives that size a weight above 0. pub levels: Vec>>, @@ -31,7 +34,11 @@ const CACHE_MAPS: usize = 16; impl CurvatureSizes { /// The sizes of the texture set `inp` composites, holding at least those `needed` marks (one flag per blurred size); None without a baked curvature map or a needed size. pub fn of(inp: &Inputs, needed: &[bool]) -> Option> { - let curvature = inp.baked.maps.get(&BakedMap::Curvature)?; + CurvatureSizes::of_map(inp, inp.baked.maps.get(&BakedMap::Curvature)?, needed) + } + + /// The sizes of `curvature`, a map in the baked curvature map's layout (the baked map or one derived from it) + pub fn of_map(inp: &Inputs, curvature: &Arc>, needed: &[bool]) -> Option> { let (width, height) = (inp.baked.resolution, inp.baked.height(BakedMap::Curvature)); if !needed.contains(&true) || width == 0 || height == 0 { return None; @@ -70,14 +77,14 @@ impl CurvatureSizes { padding.src.par_iter().map(|&source| if source == NONE { 0.0 } else { curvature.get(source as usize).copied().unwrap_or(0.5) - 0.5 }).collect(); let (block_width, block_height) = (block.0.max(1).min(width), block.1.max(1).min(height)); - let levels = CurvatureDetail::SIZES + let levels = LEVEL_RADII .iter() - .skip(1) .enumerate() .map(|(level, size)| { if let Some(existing) = built.and_then(|sizes| sizes.levels.get(level)).and_then(Option::clone) { return Some(existing); } + if !needed.get(level).copied().unwrap_or(false) { return None; } @@ -85,6 +92,7 @@ impl CurvatureSizes { // Sizes are texels at 2K; a blur this wide holds nothing finer than half its radius, so it is stored that much coarser let radius = (size * block_width as f32 / 2048.0).round().max(1.0) as u32; let mut step = (radius / 2).max(1).next_power_of_two(); + // A coarse cell must not average curvature from different UV tiles while !block_width.is_multiple_of(step) || !block_height.is_multiple_of(step) { step /= 2; @@ -247,6 +255,8 @@ fn coarsen(data: &[f32], (width, height): (u32, u32), step: u32, block: (u32, u3 #[cfg(test)] mod tests { + use texturecraft_core::CurvatureDetail; + use super::*; #[test] @@ -473,4 +483,9 @@ mod tests { } } } + + #[test] + fn the_first_levels_are_the_detail_sizes() { + assert_eq!(LEVEL_RADII[..CurvatureDetail::BLURRED_SIZES], CurvatureDetail::SIZES[1..]); + } } 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/dripping_rust.rs b/crates/compose/src/dripping_rust.rs new file mode 100644 index 00000000..c08bc90b --- /dev/null +++ b/crates/compose/src/dripping_rust.rs @@ -0,0 +1,316 @@ +//! The Dripping Rust generator: rust grown from the occlusion, broken up by grunge, then run down the mesh in drips; built once per layout and settings + +use std::sync::Arc; + +use rayon::prelude::*; +use texturecraft_core::{BakedMap, DrippingRustParameters, GeneratorKind, WearParameters}; +use texturecraft_geom::{NO_TRI, TrianglePartition}; + +use crate::eval::{Inputs, texel_coords}; +use crate::field_cache::FieldCache; +use crate::histogram_scan::histogram_scan; +use crate::wear; +use crate::working_field::{REFERENCE_TILE_TEXELS, blur_blocks, box_radius}; + +/// The rust before any grunge: `RUST_FLOOR + RUST_GAIN * max(RUST_OCCLUSION − occlusion, 0)^RUST_POWER` (fitted to the reference) +const RUST_FLOOR: f32 = 0.315; +const RUST_GAIN: f32 = 3.19; +const RUST_OCCLUSION: f32 = 0.849; +const RUST_POWER: f32 = 2.38; + +/// How much grunge breaks the rust up: the spread of the reference's noise (measured); the pattern itself is inferred +const GRUNGE_SPREAD: f32 = 0.19; + +/// Blur sizes at Spreading Smoothness 1 and Drips Smoothness 1, as gaussian sigmas in texels of a 2K UV tile (fitted) +const SPREADING_SIGMA_2K: f32 = 47.0; +const DRIPS_SIGMA_2K: f32 = 11.5; + +/// How far a drip runs at Drips Intensity 1, in texels of a 2K UV tile, and how it fades along its length: `1 − DRIP_FADE · along^DRIP_FADE_POWER` (fitted) +const DRIP_LENGTH_2K: f32 = 90.86; +const DRIP_FADE: f32 = 0.898; +const DRIP_FADE_POWER: f32 = 0.671; + +/// Coverage below which a blurred texel has nothing to average +const MIN_COVERAGE: f32 = 1e-3; + +static CACHE: FieldCache = FieldCache::new(); + +/// The rust before its spreading and contrast at every working texel of `inp` (0 outside the islands) +pub(crate) fn rust_field(inp: &Inputs, geometry: u64, rust: &DrippingRustParameters, seed: u32) -> Arc> { + let settings = vec![ + rust.spreading_smoothness.to_bits(), + rust.drips_intensity.to_bits(), + rust.drips_smoothness.to_bits(), + rust.drips_samples, + u32::from(rust.axis), + seed, + ]; + CACHE.get_or_build(inp, geometry, &[BakedMap::AmbientOcclusion], settings, |block| build(inp, rust, seed, block)) +} + +/// The value at a working texel: the rust spread and contrasted +pub(crate) fn rust_value(rust: &DrippingRustParameters, field: f32) -> f32 { + histogram_scan(field, rust.spreading, rust.contrast) +} + +fn build(inp: &Inputs, rust: &DrippingRustParameters, seed: u32, block: (u32, u32)) -> Vec { + let gbuf = inp.gbuf; + let (width, height) = (gbuf.width, gbuf.height); + let cover: Vec = (0..width * height).map(|texel| if gbuf.covered(texel as usize) { 1.0 } else { 0.0 }).collect(); + let tile_texels = |x: u32, y: u32| block.0 as f32 * inp.block_scales.at(x, y); + + // The rust from the occlusion, broken up by the Dirt generator's grunge + let grunge = WearParameters::defaults(GeneratorKind::Dirt); + let rust_at = |texel: u32| { + let (x, y) = (texel % width, texel / width); + let occlusion = inp.baked.sample_working(BakedMap::AmbientOcclusion, x, y, (width, height), &inp.block_scales).map_or(1.0, |value| value[0]); + let base = RUST_FLOOR + RUST_GAIN * (RUST_OCCLUSION - occlusion).max(0.0).powf(RUST_POWER); + let noise = grunge.map_or(0.0, |grunge| wear::grunge(GeneratorKind::Dirt, &grunge, seed, &texel_coords(inp, x, y))); + base + GRUNGE_SPREAD * noise + }; + let mut field: Vec = (0..width * height).into_par_iter().map(|texel| if gbuf.covered(texel as usize) { rust_at(texel) } else { 0.0 }).collect(); + + let radius_at = |sigma_2k: f32, smoothness: f32| move |x: u32, y: u32| box_radius(smoothness * sigma_2k * tile_texels(x, y) / REFERENCE_TILE_TEXELS); + blur_over_cover(&mut field, &cover, (width, height), block, radius_at(SPREADING_SIGMA_2K, rust.spreading_smoothness)); + let mut field = drips(inp, rust, field, (width, height), &tile_texels); + blur_over_cover(&mut field, &cover, (width, height), block, radius_at(DRIPS_SIGMA_2K, rust.drips_smoothness)); + field.iter_mut().zip(&cover).for_each(|(value, covered)| *value = if *covered > 0.0 { value.clamp(0.0, 1.0) } else { 0.0 }); + field +} + +/// `values` blurred within each UV tile block by the radius `radius_at` gives, weighted by `cover` so the empty space around the islands doesn't bleed in +fn blur_over_cover(values: &mut [f32], cover: &[f32], size: (u32, u32), block: (u32, u32), radius_at: impl Fn(u32, u32) -> usize + Copy) { + let has_blur = (0..size.1).step_by(block.1 as usize).any(|top| (0..size.0).step_by(block.0 as usize).any(|left| radius_at(left, top) > 0)); + if !has_blur { + return; + } + + let mut sums: Vec = values.iter().zip(cover).map(|(value, covered)| value * covered).collect(); + let mut weights = cover.to_vec(); + blur_blocks(&mut sums, size, block, radius_at); + blur_blocks(&mut weights, size, block, radius_at); + values.par_iter_mut().zip(sums.par_iter().zip(weights.par_iter())).zip(cover.par_iter()).for_each(|((value, (sum, weight)), covered)| { + if *covered > 0.0 && *weight > MIN_COVERAGE { + *value = sum / weight; + } + }); +} + +/// Each texel takes the most rust found uphill along the drip axis, fading with how far up it lies +fn drips( + inp: &Inputs, + rust: &DrippingRustParameters, + field: Vec, + (width, height): (u32, u32), + tile_texels: &(impl Fn(u32, u32) -> f32 + Sync), +) -> Vec { + let gbuf = inp.gbuf; + if rust.drips_samples == 0 || rust.drips_intensity <= 0.0 { + return field; + } + + let axis = usize::from(rust.axis.min(2)); + let (low, high) = inp.bounds; + let low = low.to_array()[axis]; + let extent = (high.to_array()[axis] - low).max(f32::EPSILON); + let material = inp.project.texture_set(inp.ts).map_or(0, |set| set.material); + let islands = TrianglePartition::uv_islands(inp.mesh, material); + let surface: Vec<(u32, f32)> = (0..width * height) + .into_par_iter() + .map(|texel| { + let triangle = gbuf.tri.get(texel as usize).copied().unwrap_or(NO_TRI); + let Some(island) = islands.index_of(triangle) else { return (NO_TRI, 0.0) }; + + gbuf.surface(inp.mesh, texel as usize).map_or((NO_TRI, 0.0), |surface| (island as u32, (surface.pos.to_array()[axis] - low) / extent)) + }) + .collect(); + drop(islands); + + let index_at = |x: i64, y: i64| -> Option { + if x < 0 || y < 0 || x >= i64::from(width) || y >= i64::from(height) { + return None; + } + + Some((y * i64::from(width) + x) as usize) + }; + let samples = rust.drips_samples; + let taps: Vec<_> = (1..=samples) + .map(|step| { + let fraction = step as f32 / samples as f32; + (fraction, 1.0 - DRIP_FADE * fraction.powf(DRIP_FADE_POWER)) + }) + .collect(); + + (0..width * height) + .into_par_iter() + .map(|texel| { + let (column, row) = (texel % width, texel / width); + let (x, y) = (i64::from(column), i64::from(row)); + let here = field.get(texel as usize).copied().unwrap_or(0.0); + let Some(&(island, axis_here)) = surface.get(texel as usize).filter(|(island, _)| *island != NO_TRI) else { return here }; + let axis_at = |x, y| { + let (other_island, value) = *surface.get(index_at(x, y)?)?; + (other_island == island).then_some(value) + }; + + let (dx, dy) = (slope(axis_at(x - 1, y), axis_here, axis_at(x + 1, y)), slope(axis_at(x, y - 1), axis_here, axis_at(x, y + 1))); + let length = (dx * dx + dy * dy).sqrt(); + if !length.is_finite() || length <= f32::EPSILON { + return here; + } + + let reach = rust.drips_intensity * DRIP_LENGTH_2K * tile_texels(column, row) / REFERENCE_TILE_TEXELS; + let mut most = here; + let mut current = (x, y); + 'ray: for &(fraction, fade) in &taps { + let distance = reach * fraction; + let sample = ((x as f32 + distance * dx / length).round() as i64, (y as f32 + distance * dy / length).round() as i64); + + // A sparse tap must still have continuous coverage along the ray + while current != sample { + current = next_ray_texel((x, y), current, sample, (dx, dy)); + if axis_at(current.0, current.1).is_none() { + break 'ray; + } + } + + // A tap beyond a ridge contributes only if it is higher than the receiving texel + if axis_at(sample.0, sample.1).is_some_and(|value| value >= axis_here) + && let Some(value) = index_at(sample.0, sample.1).and_then(|index| field.get(index)) + { + most = most.max(*value * fade); + } + } + most + }) + .collect() +} + +/// Finite difference within one UV island, one-sided at its edge +fn slope(before: Option, here: f32, after: Option) -> f32 { + match (before, after) { + (Some(before), Some(after)) => (after - before) * 0.5, + (None, Some(after)) => after - here, + (Some(before), None) => here - before, + (None, None) => 0.0, + } +} + +/// Advance across the next texel boundary on a ray from a texel centre toward its next tap +fn next_ray_texel(origin: (i64, i64), (x, y): (i64, i64), (target_x, target_y): (i64, i64), (dx, dy): (f32, f32)) -> (i64, i64) { + let step_x = (target_x - x).signum(); + let step_y = (target_y - y).signum(); + if step_x == 0 || step_y == 0 { + return (x + step_x, y + step_y); + } + + // Compare crossing distances without dividing by either component + let crossing_x = ((x - origin.0).abs() as f32 + 0.5) * dy.abs(); + let crossing_y = ((y - origin.1).abs() as f32 + 0.5) * dx.abs(); + (x + step_x * i64::from(crossing_x <= crossing_y), y + step_y * i64::from(crossing_y <= crossing_x)) +} + +#[cfg(test)] +mod tests { + use texturecraft_core::{Project, TextureSet}; + use texturecraft_geom::{UvGBuffer, primitives}; + + use super::*; + use crate::{BakedMaps, PixelStore}; + + const RES: u32 = 256; + + #[test] + fn a_drip_takes_no_rust_from_past_a_ridge_lower_on_the_axis() { + // A strip rising gently to a ridge at its middle, then falling steeply + let mut mesh = primitives::plane(2.0, 64); + for position in &mut mesh.positions { + position.y = if position.z <= 0.0 { 1.0 + position.z } else { 1.0 - 8.0 * position.z }; + } + let gbuf = UvGBuffer::new(&mesh, 0, RES, RES); + let mut project = Project::new("t", "strip"); + project.texture_sets.push(TextureSet::new("A", 0, RES)); + let (pixels, baked, images) = (PixelStore::default(), BakedMaps::default(), Default::default()); + let inputs = Inputs { + project: &project, + ts: 0, + mesh: &mesh, + gbuf: &gbuf, + pixels: &pixels, + baked: &baked, + block_scales: project.texture_sets[0].block_scales(), + preview: None, + images: &images, + bounds: mesh.bounds(), + }; + + // Rust only on the steep side, all lower than the gentle side's texel just below the ridge + let rusted = |surface: &texturecraft_geom::Surface| surface.pos.z > 0.01; + let field: Vec = (0..RES * RES).map(|texel| gbuf.surface(&mesh, texel as usize).filter(rusted).map_or(0.0, |_| 1.0)).collect(); + let rust = DrippingRustParameters { drips_intensity: 1.0, drips_samples: DrippingRustParameters::MAX_SAMPLES, axis: 1, ..Default::default() }; + let dripped = drips(&inputs, &rust, field, (RES, RES), &|_, _| RES as f32); + + let below_ridge = (0..RES * RES) + .find(|texel| { + gbuf.surface(&mesh, *texel as usize).is_some_and(|surface| (surface.pos.z + 0.04).abs() < 1.0 / RES as f32 && surface.pos.x.abs() < 0.1) + }) + .expect("a texel just below the ridge"); + assert_eq!(dripped[below_ridge as usize], 0.0); + } + + #[test] + fn a_runoff_streak_requires_a_continuous_uv_surface() { + const GAP_HALF_WIDTH: f32 = 1.0 / 64.0; + let mut mesh = primitives::plane(2.0, 128); + let connected_indices = mesh.indices.clone(); + let (triangles, _) = connected_indices.as_chunks::<3>(); + let separated_indices: Vec<_> = triangles + .iter() + .filter(|triangle| { + triangle.iter().all(|&corner| mesh.positions[corner as usize].z <= -GAP_HALF_WIDTH) + || triangle.iter().all(|&corner| mesh.positions[corner as usize].z >= GAP_HALF_WIDTH) + }) + .flatten() + .copied() + .collect(); + for position in &mut mesh.positions { + position.y = position.z; + } + let mut project = Project::new("Runoff", "Plane"); + project.texture_sets.push(TextureSet::new("UV islands", 0, RES)); + let (pixels, baked, images) = (PixelStore::default(), BakedMaps::default(), Default::default()); + let index = |row| (row * RES + RES / 2) as usize; + + for (connected, indices) in [(true, connected_indices), (false, separated_indices)] { + mesh.indices = indices; + mesh.submeshes[0].count = mesh.indices.len() as u32; + let gbuf = UvGBuffer::new(&mesh, 0, RES, RES); + let inputs = Inputs { + project: &project, + ts: 0, + mesh: &mesh, + gbuf: &gbuf, + pixels: &pixels, + baked: &baked, + block_scales: project.texture_sets[0].block_scales(), + preview: None, + images: &images, + bounds: mesh.bounds(), + }; + let field: Vec = + (0..RES * RES).map(|texel| f32::from(gbuf.surface(&mesh, texel as usize).is_some_and(|surface| surface.pos.z > GAP_HALF_WIDTH))).collect(); + assert!(gbuf.covered(index(124))); + assert_eq!(gbuf.covered(index(128)), connected); + assert_eq!(field[index(124)], 0.0); + assert_eq!(field[index(131)], 1.0); + + for samples in [1, DrippingRustParameters::MAX_SAMPLES] { + let rust = DrippingRustParameters { drips_intensity: 1.0, drips_samples: samples, axis: 1, ..Default::default() }; + + let dripped = drips(&inputs, &rust, field.clone(), (RES, RES), &|_, _| RES as f32); + + assert_eq!(dripped[index(124)] > 0.0, connected, "a streak with {samples} taps requires a continuous covered surface"); + } + } + } +} 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..52184129 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -2,34 +2,77 @@ //! 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; -use std::collections::{BTreeMap, HashMap}; +use std::collections::{BTreeMap, HashMap, HashSet}; 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, GeneratorGlobal, GeneratorKind, + GrayscaleConversionParameters, HeightMask, HeightToNormal, HighpassSpace, ImageInput, KindControls, Layer, LayerId, LayerKind, Mask, MaskBackground, + MaskOutline, Mirror, NormalFormat, PreparedColorMatch, PreparedGradient, Project, Projection, RepeatMode, Sampling, SectionParameters, ShapeCrop, Source, + SourceColorMode, SourceSlopeBlur, SourceWarp, StylizedShading, TargetColorMode, TextureSet, TileGrid, TileTransform, WarpSourceMode, WearParameters, + 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::curvature_sizes::{CurvatureSizes, LEVEL_RADII}; +use crate::dripping_rust; +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::generator_maps::GeneratorMaps; 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::micro_detail::AnchorHeights; +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::sections; +use crate::shape_distance::distance_filter; +use crate::slope_texel::slope_texel; +use crate::store::{BakedMaps, ImageRes, ImageStore, PixelStore, decode}; +use crate::texture_layer; +use crate::three_d_distance; +use crate::uv_border_distance; +use crate::warp_texel::{Input, MIN_READ_WEIGHT, Sample, warp_texel}; +use crate::wear; +use crate::wear_inputs::WearInputs; +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; + +/// Narrowest extent of the mesh's bounds a position is normalised across +const MIN_BOUNDS_EXTENT: f32 = 1e-6; + /// 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 +103,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 +111,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 +133,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 +175,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 +273,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,19 +292,51 @@ 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>, preview: bool, - /// The curvature detail sizes a generator with detail reads. - curvature_sizes: Option>, + /// The detail sizes and micro details a generator reads + maps: GeneratorMaps, /// 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 +352,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 +360,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 +473,91 @@ 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.applied_global().blur > 0.0 || generator.resolution.can_reduce() || sections::generator_blur_sigma(generator) > 0.0 => + { + let section_blur = sections::generator_blur_sigma(generator); + let section_reach = if section_blur > 0.0 { texels(section_blur) } else { 0.0 }; + let reach = texels(generator.applied_global().blur_radius()) + section_reach + generator.resolution.largest_cell(res) as f32; + Some((index, reach, 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 +576,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 +608,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 +692,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 +711,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 +808,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 +1262,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 +1284,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 +1292,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 +1306,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 +1318,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 +1372,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 +1458,19 @@ 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, visible_only: bool, 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 visible_only && !inp.project.layers.get(id).is_some_and(|layer| layer.visible) { + continue; + } + + 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), visible_only, out); } } } @@ -616,36 +1483,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 +1540,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))) { @@ -706,82 +1668,139 @@ fn filter_region( _ => None, }; let components = match job { - Job::Mask(_) if generator.is_some() => 2, + Job::Mask(_) if generator.is_some() => GENERATOR_STAGE_COMPONENTS, Job::Mask(_) => 1, 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; + let mut generator_maps = GeneratorMaps::default(); 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 mut mask_stack = mask_plan(inputs, id, layer_mask, tile_x, tile_y, Some(below), place); - generator_sizes = mask_stack.effects.get(index).and_then(|effect| effect.curvature_sizes.clone()); + generator_maps = mask_stack.effects.get(index).map(|effect| effect.maps.clone()).unwrap_or_default(); mask_stack.effects.truncate(index); mask_stack.start = start; 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_maps)); + let texture = generator.and_then(|(generator, _)| texel.generator_texture(generator)).unwrap_or(0.0); + [texel.mask(mask_stack), ramp, texture, 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 +1808,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 +1835,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,11 +1944,45 @@ 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() }) } -/// The mask over a region after a generator at its own resolution and blur: `stack` is (stack below, generator ramp) per texel, sizes in texels per side. +/// Where working texel (`x`, `y`) of `inp` is, for pattern evaluation (as [`Texel::coords`] sees it outside a fill copy) +pub(crate) fn texel_coords(inp: &Inputs, x: u32, y: u32) -> Coords { + let gbuf = inp.gbuf; + let mut coords = match gbuf.surface(inp.mesh, (y * gbuf.width + x) as usize) { + Some(surface) => { + let (center, radius) = mesh_frame(inp.bounds); + Coords { uv: surface.uv, pos: (surface.pos - center) / radius, nrm: surface.nrm } + } + None => Coords { uv: Vec2::new((x as f32 + 0.5) / gbuf.width as f32, (y as f32 + 0.5) / gbuf.height as f32), pos: Vec3::ZERO, nrm: Vec3::Y }, + }; + + // UV-tiled sets: projections see the mesh's own UVs (patterns repeat per tile) + if let Ok(set) = inp.project.texture_set(inp.ts) + && let Some(grid) = set.tile_grid() + { + coords.uv = Vec2::from(set.from_atlas(&grid, coords.uv.to_array())); + } + coords +} + +/// What a generator's texture or custom grunge reads with nothing in its slot +const EMPTY_IMAGE_SLOT: Source = Source::Uniform([0.0; 3]); + +/// The step Safe Rotation turns a Grayscale Conversion image by, so it keeps tiling seamlessly +const QUARTER_TURN_DEGREES: f32 = 90.0; + +/// Values per texel of a generator stage's region: the stack below, the generator's ramp and its texture's gray +const GENERATOR_STAGE_COMPONENTS: usize = 3; + +/// The mask over a region after a generator at its own resolution and blur: `stack` is (stack below, generator ramp, texture gray) per texel, sizes in texels per side fn generator_region( generator: &Generator, blend: BlendMode, @@ -877,7 +1993,7 @@ fn generator_region( (uv_tile, texture_set): (u32, u32), ) -> Vec { let (columns, rows) = (width as usize, height as usize); - let mut ramps: Vec = stack.par_chunks(2).map(|texel| texel.get(1).copied().unwrap_or(0.0)).collect(); + let mut ramps: Vec = stack.par_chunks(GENERATOR_STAGE_COMPONENTS).map(|texel| texel.get(1).copied().unwrap_or(0.0)).collect(); // Coarser than the UV tile: averaged over cells, then the blur around them let cell = generator.resolution.cell(uv_tile, texture_set) as usize; @@ -885,22 +2001,24 @@ fn generator_region( ramps = resampled_by_cells(&ramps, cover, (region_x as usize, region_y as usize, columns, rows), cell); } - let blur_radius = generator.global.blur_radius_at(uv_tile).round() as usize; - if blur_radius > 0 { - let mut weights = cover.to_vec(); - blur(&mut weights, columns, rows, blur_radius); - 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 { - *ramp = sum / weight; - } + // The section controls act on the signal before the global blur, their own blur first + if let Some(section) = generator.section_controls() { + blur_over_cover(&mut ramps, cover, (columns, rows), sections::blur_radius_at(generator.kind, §ion, uv_tile)); + ramps.par_iter_mut().for_each(|signal| *signal = sections::adjusted(generator.kind, §ion, *signal)); + } + + // The texture blends over the adjusted signal, before the global blur + if let Some(texture) = generator.texture_in_use() { + ramps.par_iter_mut().zip(stack.par_chunks(GENERATOR_STAGE_COMPONENTS)).for_each(|(signal, texel)| { + *signal = texture_layer::blended_over(texture, *signal, texel.get(2).copied().unwrap_or(0.0)); }); } + blur_over_cover(&mut ramps, cover, (columns, rows), generator.applied_global().blur_radius_at(uv_tile).round() as usize); + // Finished and blended over the stack below, like the generator effect itself stack - .par_chunks(2) + .par_chunks(GENERATOR_STAGE_COMPONENTS) .zip(ramps.par_iter()) .map(|(texel, ramp)| { let below = texel.first().copied().unwrap_or(0.0); @@ -910,6 +2028,23 @@ fn generator_region( .collect() } +/// `values` blurred by three box passes of `radius`, weighted by `cover` so uncovered texels don't bleed in +fn blur_over_cover(values: &mut [f32], cover: &[f32], (columns, rows): (usize, usize), radius: usize) { + if radius == 0 { + return; + } + + let mut weights = cover.to_vec(); + blur(&mut weights, columns, rows, radius); + let mut sums: Vec = values.iter().zip(cover).map(|(value, covered)| value * covered).collect(); + blur(&mut sums, columns, rows, radius); + values.par_iter_mut().zip(sums.par_iter().zip(weights.par_iter())).for_each(|(value, (sum, weight))| { + if *weight > MIN_READ_WEIGHT { + *value = sum / weight; + } + }); +} + /// `values` averaged over `cell` × `cell` texel cells on the mesh (`cover`), read back bilinearly between cell centers. fn resampled_by_cells(values: &[f32], cover: &[f32], (region_x, region_y, width, height): (usize, usize, usize, usize), cell: usize) -> Vec { // Cells are aligned to absolute texel positions, so a texel's cell is the same in every region @@ -934,7 +2069,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,19 +2099,193 @@ 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 (the light controls invert their shading themselves) fn finish_generator(generator: &Generator, ramp: f32) -> f32 { - let value = generator.global.apply(ramp); - let value = if generator.invert { 1.0 - value } else { value }; + let value = generator.applied_global().apply(ramp); + let value = if generator.invert && generator.light.is_none() { 1.0 - value } else { value }; let offset = if generator.offset.is_finite() { generator.offset } else { 0.0 }; (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 +2307,20 @@ 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 mut inputs = EvaluationInputs::new(inputs, &projectors); + prepare_generators(&mut inputs, None); + 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,45 +2328,289 @@ 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(), false, &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 }; + let field_mask = + |id, place: DrawPlacement| layer_mask(inp.project, id).filter(|mask| mask.enabled || (place.instance == 0 && inp.sampled_disabled_mask == Some(id))); - 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, place)| { + let mask_margin = below_margin; + let effects = field_mask(id, place).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 = field_mask(id, place).filter(|mask| 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 } -/// 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]) { +/// 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: &EvaluationInputs, layers: &[LayerId]) { let visible = layers.iter().filter(|id| inp.project.layers.get(id).is_some_and(|layer| layer.visible)); let masks = visible.filter_map(|id| layer_mask(inp.project, *id)).filter(|mask| mask.enabled); prepare_mask_curvature_sizes(inp, masks); } -/// Build the curvature detail sizes the visible generators of `masks` read, once, before tiles composite in parallel. -fn prepare_mask_curvature_sizes<'a>(inp: &Inputs, masks: impl Iterator) { - let mut needed = [false; CurvatureDetail::BLURRED_SIZES]; +/// Retain up to this many bytes of whole-map fields while planning tiles +const EVALUATION_FIELD_BYTES: usize = 256 << 20; + +/// Generators whose fitted signal depends on a precomputed whole-atlas field +fn whole_map_generator(kind: GeneratorKind) -> bool { + matches!(kind, GeneratorKind::UvBorderDistance | GeneratorKind::DrippingRust | GeneratorKind::UvRandomColor | GeneratorKind::UvChecker) +} + +/// A requested mask beneath a hidden folder probes the visible stack before that folder +fn requested_mask_stop(inp: &EvaluationInputs, id: LayerId) -> LayerId { + let mut stop = id; + let mut current = id; + for _ in 0..texturecraft_core::project::MAX_DEPTH { + let Some((_, Some(parent), _)) = inp.project.locate(current) else { break }; + if inp.project.layers.get(&parent).is_some_and(|layer| !layer.visible) { + stop = parent; + } + current = parent; + } + stop +} + +/// Prepare whole-map fields and build Micro Height maps from bottom to top +fn prepare_generators(inp: &mut EvaluationInputs, requested_mask: Option) { + let Ok(set) = inp.project.texture_set(inp.ts) else { return }; + let requested_stop = requested_mask.map(|id| requested_mask_stop(inp, id)); + let mut order = Vec::new(); + draw_order(inp, &set.stack, 0, ContentsOffset::NONE.into(), true, &mut order); + + let mut anchors_below = HashMap::new(); + let mut first_readers = HashMap::new(); + let mut generators_by_anchor = HashMap::<_, BTreeMap<_, _>>::new(); + let mut considered_fields = HashSet::new(); + let mut retained_fields = HashSet::new(); + let field_bytes = (inp.gbuf.width as usize).saturating_mul(inp.gbuf.height as usize).saturating_mul(size_of::()); + let mut retained_bytes = 0usize; + + for (index, &(id, place)) in order.iter().enumerate() { + let visible = inp.project.layers.get(&id).is_some_and(|layer| layer.visible); + let draw = (id, place.instance); + let masks = visible + .then_some((draw, id)) + .into_iter() + .chain(requested_mask.filter(|_| requested_stop == Some(id) && place.instance == 0 && !visible).map(|reader| ((reader, 0), reader))); + for (reader_draw, reader) in masks { + // Clone and smudge explicitly sample disabled masks + let requested = reader_draw.1 == 0 && requested_mask == Some(reader); + let effects = layer_mask(inp.project, reader).filter(|mask| mask.enabled || requested).into_iter().flat_map(|mask| &mask.effects); + for effect in effects.filter(|effect| effect.visible) { + let EffectKind::Generator(generator) = &effect.kind else { continue }; + + if let Some(anchor) = micro_height_anchor(generator) + && let Some(anchor_index) = anchors_below.get(&anchor) + { + inp.anchor_readers.insert((reader_draw, anchor), *anchor_index); + first_readers.entry((anchor, *anchor_index)).or_insert(draw); + generators_by_anchor.entry((anchor, *anchor_index)).or_default().insert(effect.id, generator); + } + + if whole_map_generator(generator.kind) + && retained_bytes.saturating_add(field_bytes) <= EVALUATION_FIELD_BYTES + && considered_fields.insert(effect.id) + { + let maps = GeneratorMaps::of(inp, generator, &curvature_sizes_in_use(generator), None, || inp.field_identity()); + if let Some(field) = &maps.field + && retained_fields.insert(Arc::as_ptr(field)) + { + retained_bytes += field_bytes; + } + inp.whole_maps.insert(effect.id, maps); + } + } + } + + if visible { + let mask_effects = layer_mask(inp.project, id).filter(|mask| mask.enabled).into_iter().flat_map(|mask| &mask.effects); + let content_effects = inp.project.content_layer(id).filter(|layer| !layer.is_group()).into_iter().flat_map(|layer| &layer.content_effects); + for effect in content_effects.chain(mask_effects).filter(|effect| effect.visible && matches!(effect.kind, EffectKind::Anchor)) { + anchors_below.insert(effect.id, index); + } + } + } + + if inp.is_session_stack() { + inp.projectors.micro_heights.retain_readers(inp.ts, &first_readers.keys().copied().collect::>()); + } + + if first_readers.is_empty() { + return; + } + + let mut readers: Vec<_> = first_readers.into_iter().collect(); + readers.sort_unstable_by_key(|((anchor, index), _)| (*index, *anchor)); + let stack = (inp.is_session_stack() && inp.preview.is_none()) + .then(|| StackKey::new(inp.project, inp.pixels, inp.baked, inp.images, inp.ts, &set.stack).map(Arc::new)) + .flatten(); + + for ((anchor, index), draw) in readers { + let build = || anchor_heights(inp, draw, anchor); + let heights = match &stack { + Some(stack) => inp.projectors.micro_heights.get_or_build(inp, (anchor, index), stack, build), + None => Arc::new(build()), + }; + if let Some(generators) = generators_by_anchor.remove(&(anchor, index)) { + for (id, generator) in generators { + let maps = GeneratorMaps::of(inp, generator, &curvature_sizes_in_use(generator), Some(heights.clone()), || inp.field_identity()); + inp.anchor_maps.insert((id, index), maps); + } + } + } +} + +fn micro_height_anchor(generator: &Generator) -> Option { + let micro = generator.micro_in_use().filter(|micro| micro.height)?; + match µ.height_source { + Some(Source::Anchor { anchor, .. }) => Some(*anchor), + _ => None, + } +} + +/// Anchor point `anchor`'s height over the whole texture set as layer `reader` reads it, in the working atlas's layout +fn anchor_heights(inp: &EvaluationInputs, reader: (LayerId, usize), anchor: LayerId) -> AnchorHeights { + let (width, height) = (inp.gbuf.width, inp.gbuf.height); + let channels = evaluation_channels(inp, vec![Channel::Height]); + let fields = evaluation_fields(inp, &channels, &all_tiles(width, height)); + let width_usize = width as usize; + let tile_side = TILE as usize; + let mut data = vec![0.0f32; width_usize * height as usize]; + + // Each tile row writes its own atlas rows + data.par_chunks_mut(width_usize.max(1) * tile_side).enumerate().for_each(|(tile_y, rows)| { + for tile_x in 0..width.div_ceil(TILE) { + let nodes = below_plan(inp, reader, &channels, (tile_x, tile_y as u32), Some(&fields), true); + let preview = inp.preview.and_then(|preview| preview.alpha.tile(tile_x, tile_y as u32)); + for (x, y, offset) in tile_texels(inp.gbuf, tile_x, tile_y as u32) { + let mut texel = Texel::new(inp, x, y, offset, stroke_at(preview, offset)); + texel.anchors_below(&nodes, reader); + if let Some(destination) = rows.get_mut((y as usize % tile_side) * width_usize + x as usize) { + *destination = texel.anchored(anchor, Channel::Height)[0]; + } + } + } + }); + AnchorHeights::new(data, (width, height), inp.block_scales.clone()) +} + +/// The blurred curvature levels `generator` reads: its wear's smoothing, else its detail sizes (a replaced curvature input reads none) +fn curvature_sizes_in_use(generator: &Generator) -> [bool; LEVEL_RADII.len()] { + if generator.inputs.contains_key(&BakedMap::Curvature) { + return [false; LEVEL_RADII.len()]; + } + + if let Some(wear) = wear_parameters(generator) { + return wear::levels_in_use(generator.kind, &wear); + } + + let detail = generator.detail_in_use().as_ref().map(CurvatureDetail::blurred_sizes_in_use).unwrap_or_default(); + std::array::from_fn(|level| detail.get(level).copied().unwrap_or(false)) +} + +/// The wear controls `generator` computes with: its own, Fiber Glass Edge Wear's defaults when it has none (it has no earlier model), else None +fn wear_parameters(generator: &Generator) -> Option { + generator.wear.or_else(|| WearParameters::defaults(generator.kind).filter(|_| generator.kind == GeneratorKind::FiberGlassEdgeWear)) +} + +/// Build the curvature detail sizes the visible generators of `masks` read, once, before tiles composite in parallel +fn prepare_mask_curvature_sizes<'a>(inp: &EvaluationInputs, masks: impl Iterator) { + let mut needed = [false; LEVEL_RADII.len()]; for effect in masks.flat_map(|mask| &mask.effects).filter(|effect| effect.visible) { - if let EffectKind::Generator(Generator { detail: Some(detail), .. }) = &effect.kind { - for (slot, in_use) in needed.iter_mut().zip(detail.blurred_sizes_in_use()) { + if let EffectKind::Generator(generator) = &effect.kind { + if micro_height_anchor(generator).is_some() || inp.whole_maps.contains_key(&effect.id) { + continue; + } + + if generator.micro_in_use().is_some() || whole_map_generator(generator.kind) { + GeneratorMaps::of(inp, generator, &curvature_sizes_in_use(generator), None, || inp.field_identity()); + continue; + } + + for (slot, in_use) in needed.iter_mut().zip(curvature_sizes_in_use(generator)) { *slot |= in_use; } } @@ -1059,15 +2619,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 +2636,15 @@ 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, + place: DrawPlacement, + id: LayerId, +) -> Vec> { effects .iter() .filter(|effect| effect.visible) @@ -1084,19 +2653,58 @@ fn effect_plans<'a>(inp: &Inputs<'a>, effects: &'a [Effect], tile_x: u32, tile_y Some(channel) => (inp.pixels.layer(effect.id, channel), PaintTarget::Layer(effect.id)), None => (inp.pixels.masks.get(&effect.id), PaintTarget::Mask(effect.id)), }; - let curvature_sizes = match &effect.kind { - EffectKind::Generator(Generator { detail: Some(detail), .. }) => CurvatureSizes::of(inp, &detail.blurred_sizes_in_use()), + let maps = match &effect.kind { + EffectKind::Generator(generator) => { + let maps = micro_height_anchor(generator) + .and_then(|anchor| inp.anchor_readers.get(&((id, place.instance), anchor))) + .and_then(|index| inp.anchor_maps.get(&(effect.id, *index))) + .or_else(|| inp.whole_maps.get(&effect.id)); + maps.cloned().unwrap_or_else(|| GeneratorMaps::of(inp, generator, &curvature_sizes_in_use(generator), None, || inp.field_identity())) + } + _ => GeneratorMaps::default(), + }; + 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, (!place.offset.is_none()).then(|| place.offset.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, + maps, 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 +2725,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 +2734,57 @@ 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> { - if !mask.enabled { - return None; - } - +/// 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) -> MaskPlan<'a> { 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, id); + 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)) + }; + 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 +2792,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).filter(|mask| mask.enabled).map(|mask| mask_plan(inp, id, mask, 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 +2832,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, id) } 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 +2926,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 +2958,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 +3004,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 +3045,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 +3102,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 +3314,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 +3424,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 +3450,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 +3469,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]], @@ -1510,26 +3518,84 @@ impl<'a, 'b> Texel<'a, 'b> { if needs_gray { [lum(value); 3] } else { value } } - fn generator_ramp(&mut self, generator: &Generator, curvature_sizes: Option<&CurvatureSizes>) -> f32 { + /// The generator's ramp at this texel, before its global blur, balance, contrast and invert (on the section controls, before those too). + fn generator_ramp(&mut self, generator: &Generator, maps: &GeneratorMaps) -> f32 { + if let Some(wear) = wear_parameters(generator) { + return self.wear_ramp(generator, &wear, maps); + } + + if let Some(light) = &generator.light { + let normal = + self.generator_input_color(generator, BakedMap::WorldNormal).map_or_else(|| self.coords().nrm, |encoded| Vec3::from(encoded) * 2.0 - 1.0); + let position = Vec3::from(self.position_input(generator)); + return sections::light_value(light, normal, position, generator.invert); + } + + if let Some(section) = generator.section_controls() { + return self.section_signal(generator, §ion, maps); + } + + // The kinds with only their own controls: resolved once per plan, not per texel + let resolved; + let controls = match maps.controls.as_deref() { + Some(controls) => Some(controls), + None => { + resolved = generator.kind_controls(); + resolved.as_ref() + } + }; + match controls { + Some(KindControls::Distance(distance)) => { + let position = self.uniform_position_input(generator); + return three_d_distance::distance_value(distance, position); + } + Some(KindControls::LinearGradient(gradient)) => { + let position = self.uniform_position_input(generator); + return three_d_distance::linear_gradient_value(gradient, position); + } + Some(KindControls::BorderDistance(border)) => return uv_border_distance::border_value(border, self.field_value(maps)), + Some(KindControls::Grayscale(grayscale)) => return self.grayscale_conversion(grayscale), + Some(KindControls::DrippingRust(rust)) => return dripping_rust::rust_value(rust, self.field_value(maps)), + Some(KindControls::UvRandomColor(_) | KindControls::UvChecker(_)) => return self.field_value(maps), + None => {} + } + let coords = self.coords(); - let micro = generator.micro.map_or(0.0, |micro| self.micro_detail(generator.kind, micro)); + let earlier_micro = generator.earlier_micro().map_or(0.0, |(anchor, amount)| self.earlier_micro_detail(generator.kind, anchor, amount)); + + // Micro details saved on the earlier model add to its curvature and occlusion inputs too let signal = match (generator.kind, &generator.detail) { (GeneratorKind::Curvature | GeneratorKind::EdgeWear, Some(detail)) => { // Detail sizes are blurred copies of the mesh map, so a replaced curvature input reads at its own size only - let sizes = if generator.inputs.contains_key(&BakedMap::Curvature) { None } else { curvature_sizes }; - let curvature = self.generator_input(generator, BakedMap::Curvature); - self.curvature_detail(detail, sizes, curvature, micro) + let sizes = if generator.inputs.contains_key(&BakedMap::Curvature) { None } else { maps.sizes.as_deref() }; + let curvature = self.curvature_input(generator, maps); + self.curvature_detail(detail, sizes, curvature, earlier_micro) } - (GeneratorKind::EdgeWear, None) => (self.generator_input(generator, BakedMap::Curvature).unwrap_or(0.5) - 0.5) * 2.0, - (GeneratorKind::Curvature, None) => self.generator_input(generator, BakedMap::Curvature).unwrap_or(0.5), - (GeneratorKind::Dirt, _) => 1.0 - self.generator_input(generator, BakedMap::AmbientOcclusion).unwrap_or(1.0), - (GeneratorKind::AmbientOcclusion, _) => self.generator_input(generator, BakedMap::AmbientOcclusion).unwrap_or(1.0), + (GeneratorKind::EdgeWear, None) | (GeneratorKind::FiberGlassEdgeWear, _) => (self.curvature_input(generator, maps).unwrap_or(0.5) - 0.5) * 2.0, + (GeneratorKind::Curvature, None) => self.curvature_input(generator, maps).unwrap_or(0.5), + (GeneratorKind::Dirt, _) => 1.0 - self.occlusion_input(generator, maps).unwrap_or(1.0), + (GeneratorKind::AmbientOcclusion, _) => self.occlusion_input(generator, maps).unwrap_or(1.0), (GeneratorKind::ThinAreas, _) => 1.0 - self.generator_input(generator, BakedMap::Thickness).unwrap_or(1.0), (GeneratorKind::Position, _) => coords.pos.dot(Vec3::from(generator.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, (GeneratorKind::Direction, _) => coords.nrm.dot(Vec3::from(generator.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, + // World Space Normals and 3D Distance always compute with their own controls: these arms only keep the match whole + (GeneratorKind::WorldSpaceNormals, _) => coords.nrm.y * 0.5 + 0.5, + ( + GeneratorKind::ThreeDDistance + | GeneratorKind::ThreeDLinearGradient + | GeneratorKind::UvBorderDistance + | GeneratorKind::GrayscaleConversion + | GeneratorKind::DrippingRust + | GeneratorKind::UvRandomColor + | GeneratorKind::UvChecker, + _, + ) => 0.0, + }; + let signal = if matches!(generator.kind, GeneratorKind::Curvature | GeneratorKind::EdgeWear) && generator.detail.is_some() { + signal + } else { + signal + earlier_micro }; - let signal = - if matches!(generator.kind, GeneratorKind::Curvature | GeneratorKind::EdgeWear) && generator.detail.is_some() { signal } else { signal + micro }; let signal = if generator.noise_amount > 0.0 { let noise = world_noise(coords.pos, generator.noise_scale, generator.seed); if let (GeneratorKind::Curvature | GeneratorKind::EdgeWear, Some(detail)) = (generator.kind, &generator.detail) { @@ -1550,41 +3616,242 @@ impl<'a, 'b> Texel<'a, 'b> { ramp * ramp * (3.0 - 2.0 * ramp) } - /// How a generator's micro detail moves its signal at this texel: the anchor's height (0 where - /// the anchor is not evaluated yet) as an edge where raised and a cavity where recessed. - fn micro_detail(&self, kind: GeneratorKind, micro: MicroDetail) -> f32 { - let height = self.anchor_value(micro.anchor, Channel::Height, ChannelKind::Signed)[0]; - let amount = if micro.amount.is_finite() { micro.amount.clamp(0.0, 1.0) } else { 0.0 }; - let response = height.clamp(-1.0, 1.0) * amount; - match kind { - GeneratorKind::Curvature | GeneratorKind::EdgeWear => response, + /// The signal a generator on its section controls adjusts at this texel: the axes of its map, its curvature or its occlusion + fn section_signal(&mut self, generator: &Generator, section: &SectionParameters, maps: &GeneratorMaps) -> f32 { + match generator.kind { + GeneratorKind::Curvature => { + let detail = generator.detail_in_use().unwrap_or_default(); + let sizes = if generator.inputs.contains_key(&BakedMap::Curvature) { None } else { maps.sizes.as_deref() }; + let curvature = self.curvature_input(generator, maps); + self.curvature_detail(&detail, sizes, curvature, 0.0) + } + GeneratorKind::AmbientOcclusion => self.occlusion_input(generator, maps).unwrap_or(1.0), + GeneratorKind::Position => { + let position = self.position_input(generator); + sections::axes_signal(position, §ion.axes) + } + GeneratorKind::WorldSpaceNormals => { + let normal = self.generator_input_color(generator, BakedMap::WorldNormal).unwrap_or_else(|| (self.coords().nrm * 0.5 + 0.5).to_array()); + sections::axes_signal(normal, §ion.axes) + } - // Dirt gathers in dents; dents are occluded - GeneratorKind::Dirt => -response, - GeneratorKind::AmbientOcclusion => response, - GeneratorKind::ThinAreas | GeneratorKind::Position | GeneratorKind::Direction => 0.0, + // Other kinds use their own evaluator + GeneratorKind::EdgeWear + | GeneratorKind::Dirt + | GeneratorKind::ThinAreas + | GeneratorKind::Direction + | GeneratorKind::FiberGlassEdgeWear + | GeneratorKind::ThreeDDistance + | GeneratorKind::ThreeDLinearGradient + | GeneratorKind::UvBorderDistance + | GeneratorKind::GrayscaleConversion + | GeneratorKind::DrippingRust + | GeneratorKind::UvRandomColor + | GeneratorKind::UvChecker => 0.0, } } - /// The generator's value at this texel: its ramp finished by balance, contrast, invert and offset (its blur and resolution need neighbours: see [`generator_region`]). - fn generator(&mut self, generator: &Generator, curvature_sizes: Option<&CurvatureSizes>) -> f32 { - let ramp = self.generator_ramp(generator, curvature_sizes); - finish_generator(generator, ramp) + /// The image in `generator`'s Position input, else this texel's position across the mesh's bounds: the baked Position map is not read, its normalisation is a bake setting + fn position_input(&mut self, generator: &Generator) -> [f32; 3] { + match generator.inputs.get(&BakedMap::Position) { + Some(source) => self.source(source, &Projection::default(), Sampling::default(), ChannelKind::NormalMap), + None => self.bounds_position().to_array(), + } + } + + /// A generator's whole-map field at this texel (0 without one) + fn field_value(&self, maps: &GeneratorMaps) -> f32 { + let texel = (self.y * self.inp.gbuf.width + self.x) as usize; + maps.field.as_ref().and_then(|field| field.get(texel)).copied().unwrap_or(0.0) + } + + /// The Grayscale Conversion generator at this texel: its image tiled and turned about the UV square's centre, made gray, balanced and contrasted + fn grayscale_conversion(&mut self, grayscale: &GrayscaleConversionParameters) -> f32 { + let degrees = if grayscale.safe_rotation { (grayscale.rotation / QUARTER_TURN_DEGREES).round() * QUARTER_TURN_DEGREES } else { grayscale.rotation }; + let (sin, cos) = degrees.to_radians().sin_cos(); + let centred = self.coords().uv - Vec2::splat(0.5); + let at = Vec2::new(centred.x * cos - centred.y * sin, centred.x * sin + centred.y * cos) * grayscale.tile + Vec2::splat(0.5); + let rgb = match grayscale.source.as_ref().unwrap_or(&EMPTY_IMAGE_SLOT) { + Source::Image { name, .. } => self.inp.images.get(name).map_or([0.0; 3], |image| { + let [red, green, blue, _] = image.sample(at.x, at.y); + [red, green, blue] + }), + other => self.source(other, &Projection::default(), Sampling::default(), ChannelKind::NormalMap), + }; + let gray = grayscale.grayscale.gray(rgb).clamp(0.0, 1.0); + GeneratorGlobal { balance: grayscale.balance, contrast: grayscale.contrast, ..GeneratorGlobal::default() }.apply(gray) + } + + /// The image in `generator`'s Position input, else this texel's position across the mesh's bounds scaled evenly: the longest side spans 0..1, the others centred on 0.5 + fn uniform_position_input(&mut self, generator: &Generator) -> Vec3 { + if let Some(source) = generator.inputs.get(&BakedMap::Position) { + return Vec3::from(self.source(source, &Projection::default(), Sampling::default(), ChannelKind::NormalMap)); + } + + let (low, high) = self.inp.bounds; + let longest = (high - low).max_element().max(MIN_BOUNDS_EXTENT); + self.world().map_or(Vec3::splat(0.5), |position| (position - (low + high) * 0.5) / longest + Vec3::splat(0.5)) + } + + /// This texel's world position across the mesh's bounds, 0..1 on each axis (0 where uncovered) + fn bounds_position(&self) -> Vec3 { + let (low, high) = self.inp.bounds; + self.world().map_or(Vec3::ZERO, |position| ((position - low) / (high - low).max(Vec3::splat(MIN_BOUNDS_EXTENT))).clamp(Vec3::ZERO, Vec3::ONE)) + } + + /// A wear generator's value at this texel from its curvature, occlusion and grunge, before its global adjustments and invert + fn wear_ramp(&mut self, generator: &Generator, wear: &WearParameters, maps: &GeneratorMaps) -> f32 { + let curvature = self.curvature_input(generator, maps).map_or(0.0, |curvature| curvature - 0.5); + + // Blurred levels are copies of the mesh map, so a replaced curvature input is read at its own size only + let sizes = if generator.inputs.contains_key(&BakedMap::Curvature) { None } else { maps.sizes.as_deref() }; + let blurred_curvature = self.blurred_curvature(wear::blur_sigma(generator.kind, wear), sizes, curvature); + + let occlusion = self.occlusion_input(generator, maps).unwrap_or(1.0); + let grunge = if wear.custom_grunge { + // An image not loaded yet reads mid gray, which leaves the wear as without grunge + let gray = self.slot_color(generator, generator.grunge.as_ref(), &wear::custom_grunge_placement(wear)).map_or(0.5, lum); + wear::custom_grunge(generator.kind, gray) + } else { + wear::grunge(generator.kind, wear, generator.seed, &self.coords()) + }; + wear::wear_value(generator.kind, wear, &WearInputs { curvature, blurred_curvature, occlusion, grunge }) + } + + /// The curvature deviation at this texel blurred to `sigma` (texels at 2K) between the two built levels around it; `curvature` without them + fn blurred_curvature(&self, sigma: f32, curvature_sizes: Option<&CurvatureSizes>, curvature: f32) -> f32 { + let Some((sizes, (baked_x, baked_y))) = curvature_sizes.zip(self.baked_curvature_texel()) else { return curvature }; + + let level = |index: usize| sizes.levels.get(index).and_then(Option::as_deref).map(|level| level.sample(baked_x, baked_y)); + let (narrower, wider, weight) = wear::levels_around(sigma); + let narrower = narrower.map_or(Some(curvature), level); + match (narrower, level(wider)) { + (Some(narrower), Some(wider)) => narrower + (wider - narrower) * weight, + _ => curvature, + } + } + + /// The baked curvature map's texel under this texel (None outside the baked layout) + fn baked_curvature_texel(&self) -> Option<(u32, u32)> { + let working_size = (self.res, self.inp.gbuf.height); + let texel_uv = [(self.x as f32 + 0.5) / working_size.0.max(1) as f32, (self.y as f32 + 0.5) / working_size.1.max(1) as f32]; + let baked_uv = self.inp.block_scales.bake_uv(texel_uv, working_size)?; + let baked_size = (self.inp.baked.resolution, self.inp.baked.height(BakedMap::Curvature)); + Some(((baked_uv[0] * baked_size.0 as f32) as u32, (baked_uv[1] * baked_size.1 as f32) as u32)) + } + + /// The generator's value at this texel: its ramp finished by balance, contrast, invert and offset (its blur and resolution need neighbours: see [`generator_region`]) + fn generator(&mut self, generator: &Generator, maps: &GeneratorMaps) -> f32 { + let ramp = self.generator_ramp(generator, maps); + let adjusted = generator.section_controls().map_or(ramp, |section| sections::adjusted(generator.kind, §ion, ramp)); + + // An image still loading reads black, as it does where blur or resolution compute the generator over a region + let textured = match generator.texture_in_use() { + Some(texture) => texture_layer::blended_over(texture, adjusted, self.generator_texture(generator).unwrap_or(0.0)), + None => adjusted, + }; + + finish_generator(generator, textured) + } + + /// The gray of the generator's texture at this texel (None when it blends no texture) + fn generator_texture(&mut self, generator: &Generator) -> Option { + let texture = generator.texture_in_use()?; + let rgb = self.slot_color(generator, texture.source.as_ref(), &texture_layer::texture_placement(texture))?; + Some(texture_layer::texture_gray(texture, rgb)) + } + + /// The color of a generator's image slot holding `source` (None: empty, read as black) at this texel, read where `placement` puts it (None when its image isn't loaded) + fn slot_color(&mut self, generator: &Generator, source: Option<&Source>, placement: &texture_layer::SlotPlacement) -> Option<[f32; 3]> { + match source.unwrap_or(&EMPTY_IMAGE_SLOT) { + Source::Image { name, .. } => { + let image = self.inp.images.get(name)?.clone(); + let read = |coordinates: Vec2| { + let [red, green, blue, _] = image.sample(coordinates.x, coordinates.y); + Vec3::new(red, green, blue) + }; + let color = match placement.triplanar_contrast { + Some(contrast) => { + let normal = self + .generator_input_color(generator, BakedMap::WorldNormal) + .map_or_else(|| self.coords().nrm, |encoded| Vec3::from(encoded) * 2.0 - 1.0); + let weights = texture_layer::triplanar_weights(contrast, normal); + let coordinates = texture_layer::triplanar_coordinates(placement, self.bounds_position()); + weights.iter().zip(coordinates).fold(Vec3::ZERO, |sum, (weight, at)| sum + read(at) * *weight) + } + None => read(texture_layer::uv_coordinates(placement, self.coords().uv)), + }; + Some(color.to_array()) + } + + // A value or an anchor reads the same wherever it is projected + other => Some(self.source(other, &Projection::default(), Sampling::default(), ChannelKind::NormalMap)), + } + } + + /// How a micro detail saved before Micro Details moves an earlier-model generator's signal at this texel: anchor point `anchor`'s height times `amount` (0 where the anchor is not evaluated yet), an edge where raised and a cavity where recessed + fn earlier_micro_detail(&self, kind: GeneratorKind, anchor: LayerId, amount: f32) -> f32 { + let response = self.anchor_value(anchor, Channel::Height, ChannelKind::Signed)[0].clamp(-1.0, 1.0) * amount; + match kind { + GeneratorKind::Curvature | GeneratorKind::EdgeWear | GeneratorKind::AmbientOcclusion => response, + + // Dirt gathers in dents + GeneratorKind::Dirt => -response, + + // Kinds the micro detail never moved, or without an earlier model + GeneratorKind::FiberGlassEdgeWear + | GeneratorKind::ThinAreas + | GeneratorKind::Position + | GeneratorKind::Direction + | GeneratorKind::WorldSpaceNormals + | GeneratorKind::ThreeDDistance + | GeneratorKind::ThreeDLinearGradient + | GeneratorKind::UvBorderDistance + | GeneratorKind::GrayscaleConversion + | GeneratorKind::DrippingRust + | GeneratorKind::UvRandomColor + | GeneratorKind::UvChecker => 0.0, + } + } + + /// The generator's curvature input at this texel with what its micro details add + fn curvature_input(&mut self, generator: &Generator, maps: &GeneratorMaps) -> Option { + let curvature = self.generator_input(generator, BakedMap::Curvature)?; + let working_size = (self.res, self.inp.gbuf.height); + let micro = maps.micro_curvature.as_ref().and_then(|micro| micro.term.at((self.x, self.y), working_size, &self.inp.block_scales)); + Some(curvature + micro.unwrap_or(0.0)) + } + + /// The generator's occlusion input at this texel, darkened by its micro details + fn occlusion_input(&mut self, generator: &Generator, maps: &GeneratorMaps) -> Option { + let occlusion = self.generator_input(generator, BakedMap::AmbientOcclusion)?; + let working_size = (self.res, self.inp.gbuf.height); + let micro = maps.micro_occlusion.as_ref().and_then(|micro| micro.at((self.x, self.y), working_size, &self.inp.block_scales)); + Some(occlusion * micro.unwrap_or(1.0)) } /// 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), } } - /// The curvature of `detail`'s mode at this texel from `curvature` (None: nothing to read), with its blurred detail sizes when given. - fn curvature_detail(&self, detail: &CurvatureDetail, curvature_sizes: Option<&CurvatureSizes>, curvature: Option, micro: f32) -> f32 { + /// Generator input `map` at this texel as three channels (an encoded normal or position): what replaces the mesh map, else the mesh map (None when not baked) + fn generator_input_color(&mut self, generator: &Generator, map: BakedMap) -> Option<[f32; 3]> { + match generator.inputs.get(&map) { + Some(source) => Some(self.source(source, &Projection::default(), Sampling::default(), ChannelKind::NormalMap)), + None => self.baked_color(map), + } + } + + /// The curvature of `detail`'s mode at this texel from `curvature` (None: nothing to read), with its blurred detail sizes when given and an earlier micro detail's term (see [`Texel::earlier_micro_detail`]) as an edge where positive and a cavity where negative + fn curvature_detail(&self, detail: &CurvatureDetail, curvature_sizes: Option<&CurvatureSizes>, curvature: Option, earlier_micro: f32) -> f32 { let combine = |edges: f32, cavities: f32| { - let edges = 1.0 - (1.0 - edges) * (1.0 - micro.max(0.0)); - let cavities = 1.0 - (1.0 - cavities) * (1.0 + micro.min(0.0)); + let edges = 1.0 - (1.0 - edges) * (1.0 - earlier_micro.max(0.0)); + let cavities = 1.0 - (1.0 - cavities) * (1.0 + earlier_micro.min(0.0)); match detail.mode { CurvatureMode::Edges => edges, CurvatureMode::Cavities => cavities, @@ -1593,15 +3860,10 @@ impl<'a, 'b> Texel<'a, 'b> { } }; - // Without baked curvature, only painted micro height supplies edges or cavities + // Without curvature to read only an earlier micro detail supplies edges or cavities let Some(curvature) = curvature else { return combine(0.0, 0.0) }; + let Some((baked_x, baked_y)) = self.baked_curvature_texel() else { return combine(0.0, 0.0) }; - let working_size = (self.res, self.inp.gbuf.height); - let texel_uv = [(self.x as f32 + 0.5) / working_size.0.max(1) as f32, (self.y as f32 + 0.5) / working_size.1.max(1) as f32]; - let Some(baked_uv) = self.inp.block_scales.bake_uv(texel_uv, working_size) else { return combine(0.0, 0.0) }; - - let baked_size = (self.inp.baked.resolution, self.inp.baked.height(BakedMap::Curvature)); - let (baked_x, baked_y) = ((baked_uv[0] * baked_size.0 as f32) as u32, (baked_uv[1] * baked_size.1 as f32) as u32); let blurred = |index: usize| { curvature_sizes.and_then(|sizes| sizes.levels.get(index)).and_then(Option::as_deref).map_or(0.0, |level| level.sample(baked_x, baked_y)) }; @@ -1629,7 +3891,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 +3924,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 +3937,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()); + let generated = self.generator(generator, &effect.maps); 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 +3991,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 +4135,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 +4148,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 +4159,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 +4213,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 +4276,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 +4323,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,13 +4461,51 @@ 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 mut inputs = EvaluationInputs::new(inputs, &projectors); + composite_evaluation_tiles(&mut 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 mut inputs = EvaluationInputs::new(inputs, projectors).of_the_session_stack(); + composite_evaluation_tiles(&mut inputs, out, tiles, below); +} + +fn composite_evaluation_tiles(inp: &mut 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; } + if !tiles.is_empty() { + prepare_generators(inp, None); + } + let split = below.as_deref_mut().and_then(|b| b.prepare(inp)); // Avoid caching tiles that would immediately evict each other @@ -2047,7 +4518,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 +4558,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 +4570,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 +4580,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 +4597,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(), false, &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 +4632,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 +4664,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 +4683,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 +4691,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 +4721,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 +4737,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 +4782,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 +4809,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 +4940,18 @@ 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 = &mut 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_generators(inputs, Some(id)); 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 +4974,26 @@ 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 = &mut 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_generators(inputs, Some(id)); 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 +5012,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 +5033,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 +5087,20 @@ 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 = &mut EvaluationInputs::new(inputs, &projectors); let mask = layer_mask(inputs.project, id)?; - let channels = inputs.project.texture_set(inputs.ts).ok()?.channel_list(); + inputs.sampled_disabled_mask = (!mask.enabled).then_some(id); + let mut channels = inputs.project.texture_set(inputs.ts).ok()?.channel_list(); + if !mask.enabled { + channels = compared_channels(mask.effects.iter().filter(|effect| effect.visible && effect.kind.reads_stack()), channels); + } + + let channels = evaluation_channels(inputs, channels); + prepare_generators(inputs, Some(id)); 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 +5123,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 = &mut 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 +5143,14 @@ pub fn mask_at(inputs: &Inputs, id: LayerId, texels: &[(u32, u32)]) -> Option