mirror of
https://github.com/storytold/texturecraft.git
synced 2026-11-30 10:03:56 +01:00
Merge remote-tracking branch 'origin/main' into fix/852-autosave-notice
# Conflicts: # crates/ui-egui/src/lib.rs
This commit is contained in:
commit
458ac8ce5b
367 files changed
+28980
-4644
No files matched your search
@@ -4,10 +4,10 @@
|
||||
"repository_id": 1419654881,
|
||||
"producer_workflow_id": 429738073,
|
||||
"producer_workflow_path": ".github/workflows/nightly.yml",
|
||||
"producer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
|
||||
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
|
||||
"producer_tooling_revision": "main",
|
||||
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main",
|
||||
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
|
||||
"signer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
|
||||
"signer_tooling_revision": "main",
|
||||
"release_branch": "nightly-signer",
|
||||
"manual_actors": [
|
||||
"bflatastic",
|
||||
@@ -100,7 +100,15 @@
|
||||
"unsigned_artifact_name": "nightly-unsigned-linux-x86_64",
|
||||
"trust": {
|
||||
"fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"
|
||||
}
|
||||
},
|
||||
"package_formats": [
|
||||
"appimage",
|
||||
"arch",
|
||||
"deb",
|
||||
"flatpak",
|
||||
"oci",
|
||||
"rpm"
|
||||
]
|
||||
},
|
||||
"macos-aarch64": {
|
||||
"unsigned_artifact_name": "nightly-unsigned-macos-aarch64",
|
||||
|
||||
@@ -36,7 +36,7 @@ jobs:
|
||||
RUST_BACKTRACE: 1
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
@@ -44,12 +44,12 @@ jobs:
|
||||
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
|
||||
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@main
|
||||
with:
|
||||
ref: aced4137c022f1f587624d48e81ec77e1914a9cc
|
||||
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@605d58766e8f536564da8fc81d3676ac86816dea
|
||||
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@main
|
||||
- id: rust
|
||||
uses: storytold/craft-common-actions/actions/rust-channel@605d58766e8f536564da8fc81d3676ac86816dea
|
||||
uses: storytold/craft-common-actions/actions/rust-channel@main
|
||||
with:
|
||||
targets: aarch64-apple-darwin
|
||||
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
|
||||
|
||||
@@ -34,12 +34,26 @@ jobs:
|
||||
checks: read
|
||||
attestations: write
|
||||
id-token: write
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@main
|
||||
with:
|
||||
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
|
||||
tooling-revision: main
|
||||
app-name: texturecraft
|
||||
producer_run_id: ${{ inputs.producer_run_id }}
|
||||
producer_run_attempt: ${{ inputs.producer_run_attempt }}
|
||||
secrets:
|
||||
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
|
||||
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
|
||||
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
|
||||
APPLE_ID: ${{ secrets.APPLE_ID }}
|
||||
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
|
||||
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
|
||||
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
|
||||
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
|
||||
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
|
||||
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
|
||||
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
|
||||
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
|
||||
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
|
||||
# No secrets: inherit or raw platform values in this caller. Only the isolated native
|
||||
# callee job may bind the release environment and export its keys; that environment must
|
||||
# admit nightly-signer alongside release before the first dispatch.
|
||||
@@ -22,9 +22,9 @@ jobs:
|
||||
actions: read
|
||||
attestations: write
|
||||
id-token: write
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main
|
||||
with:
|
||||
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
|
||||
tooling-revision: main
|
||||
app-name: texturecraft
|
||||
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
|
||||
craft-fonts-ref: aced4137c022f1f587624d48e81ec77e1914a9cc
|
||||
@@ -32,3 +32,4 @@ jobs:
|
||||
# craft-common-actions main commit that merged the exact-analysis admission (#371, after #370,
|
||||
# #369 and #364).
|
||||
platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'
|
||||
linux-package-formats: '["deb","rpm","appimage","flatpak","oci","arch"]'
|
||||
@@ -25,3 +25,21 @@ jobs:
|
||||
# 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
|
||||
|
||||
freebsd-layout:
|
||||
# The FreeBSD package layout, with stub binaries standing in for the build: RFC-0018 rule 1.9
|
||||
# puts texturecraft-cli's man pages and its bash, zsh and fish completions in it.
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: FreeBSD package layout (dry run)
|
||||
run: |
|
||||
CARGO_TARGET_DIR="$RUNNER_TEMP/texturecraft-target" bash packaging/freebsd/package.sh --dry-run
|
||||
listing="$(tar -tzf "$RUNNER_TEMP"/texturecraft-target/freebsd-package/texturecraft-*-freebsd-x86_64.tar.gz)"
|
||||
for f in man/man1/texturecraft-cli.1 share/bash-completion/completions/texturecraft-cli \
|
||||
share/zsh/site-functions/_texturecraft-cli share/fish/vendor_completions.d/texturecraft-cli.fish; do
|
||||
grep -q "/$f$" <<<"$listing" || { echo "::error::$f is missing from the FreeBSD package"; exit 1; }
|
||||
done
|
||||
@@ -63,7 +63,7 @@ The key words MUST, MUST NOT, SHOULD, SHOULD NOT and MAY are used as in RFC 2119
|
||||
## This repository
|
||||
<!-- craft-agents:end -->
|
||||
|
||||
TextureCraft is an open-source, native 3D texture painter in Rust: a native egui/eframe app on wgpu, a headless CLI and MCP server, and the same app in the browser (trunk, wasm-bindgen). The project extension is `.tcraft`. Crates are `texturecraft-*`; the product name is written TextureCraft. MaterialCraft's `.mcmat` portable materials are read here through the shared `craft-mcmat` format crate (craft-libs), with the app's own checks in `formats::mcmat`; each app keeps its own models and policy. Start with `docs/architecture.md`, `docs/control-protocol.md`, `ROADMAP.md` and `docs/parity.md`.
|
||||
TextureCraft is an open-source, native 3D texture painter in Rust: a native egui/eframe app on wgpu, a headless CLI and MCP server, and the same app in the browser (trunk, wasm-bindgen). The project extension is `.tcraft`. Crates are `texturecraft-*`; the product name is written TextureCraft. MaterialCraft's `.mcmat` portable materials are read here through the shared `craft-mcmat` format crate (craft-libs), with the app's own checks in `formats::mcmat`; each app keeps its own models and policy. Start with `docs/architecture.md`, `docs/control-protocol.md`, `ROADMAP.md` and `docs/parity.md`. `docs/parity.md` carries the [RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md) Headless column: `yes` only when the id is an engine command (`texturecraft_engine::find`), which `texturecraft-cli` and the MCP server reach. A `ui.*` id is live in the desktop app only and gets a `no`/`partial` mark with a `window`, `os` or `engine-gap` reach in `HEADLESS` (`crates/ui-egui/src/parity.rs`). Never write `yes` there. Regenerate with `TC_UPDATE_PARITY=1 cargo test -p texturecraft-ui-egui parity`.
|
||||
|
||||
### Layout
|
||||
```text
|
||||
|
||||
@@ -28,6 +28,10 @@ licensed and keep their license file next to them.
|
||||
| `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`) |
|
||||
| `apps/texturecraft/src/xwayland_pen.rs` | Pen on Wayland opens the window through Xwayland: pen detection, the Xwayland decision and the X11 library check (adapted, reduced to the pen decision) | PhotoCraft contributors | storytold/photocraft `830316b775f1f6734498ac6e39fd1298955ff93f`: [`apps/photocraft/src/tablet.rs`](https://github.com/storytold/photocraft/blob/830316b775f1f6734498ac6e39fd1298955ff93f/apps/photocraft/src/tablet.rs), [`apps/photocraft/src/linux_libs.rs`](https://github.com/storytold/photocraft/blob/830316b775f1f6734498ac6e39fd1298955ff93f/apps/photocraft/src/linux_libs.rs) | MIT OR Apache-2.0 |
|
||||
|
||||
Native autosave recovery uses `same-file` to compare file identities. Copyright (c) 2017 Andrew Gallant.
|
||||
The crate is available under Unlicense OR MIT. [Upstream source and licences](https://github.com/BurntSushi/same-file)
|
||||
|
||||
## Third-party assets compiled into the binary
|
||||
|
||||
@@ -52,6 +56,8 @@ time (nothing is bundled); see [docs/localization-parity.md](docs/localization-p
|
||||
| `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 |
|
||||
| `x11rb-protocol` | X11 setup and Xauthority for the Linux pen startup probe | https://github.com/psychon/x11rb | MIT OR Apache-2.0 |
|
||||
| `rustix` | Linux socket and hostname APIs for the X11 setup probe | https://github.com/bytecodealliance/rustix | Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT |
|
||||
| `zbus` | Wayland desktop color-picker portal | https://github.com/z-galaxy/zbus | MIT |
|
||||
|
||||
## Procedural content (no asset files)
|
||||
|
||||
Generated
+160
-17
@@ -212,12 +212,56 @@ dependencies = [
|
||||
"unicode-width",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anstream"
|
||||
version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d"
|
||||
dependencies = [
|
||||
"anstyle",
|
||||
"anstyle-parse",
|
||||
"anstyle-query",
|
||||
"anstyle-wincon",
|
||||
"colorchoice",
|
||||
"is_terminal_polyfill",
|
||||
"utf8parse",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anstyle"
|
||||
version = "1.0.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
|
||||
|
||||
[[package]]
|
||||
name = "anstyle-parse"
|
||||
version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e"
|
||||
dependencies = [
|
||||
"utf8parse",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anstyle-query"
|
||||
version = "1.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
|
||||
dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anstyle-wincon"
|
||||
version = "3.0.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
|
||||
dependencies = [
|
||||
"anstyle",
|
||||
"once_cell_polyfill",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "arboard"
|
||||
version = "3.6.1"
|
||||
@@ -672,7 +716,7 @@ dependencies = [
|
||||
"maybe-owned",
|
||||
"rustix 1.1.6",
|
||||
"rustix-linux-procfs",
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.61.2",
|
||||
"winx",
|
||||
]
|
||||
|
||||
@@ -776,6 +820,65 @@ dependencies = [
|
||||
"libloading",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap"
|
||||
version = "4.6.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946"
|
||||
dependencies = [
|
||||
"clap_builder",
|
||||
"clap_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap_builder"
|
||||
version = "4.6.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d"
|
||||
dependencies = [
|
||||
"anstream",
|
||||
"anstyle",
|
||||
"clap_lex",
|
||||
"strsim",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap_complete"
|
||||
version = "4.6.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6a35200383f20018d41c14d1ab19c1727c697f544492143f7d93aa39f0187848"
|
||||
dependencies = [
|
||||
"clap",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap_derive"
|
||||
version = "4.6.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0"
|
||||
dependencies = [
|
||||
"heck",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap_lex"
|
||||
version = "1.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79"
|
||||
|
||||
[[package]]
|
||||
name = "clap_mangen"
|
||||
version = "0.2.33"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7e30ffc187e2e3aeafcd1c6e2aa416e29739454c0ccaa419226d5ecd181f2d78"
|
||||
dependencies = [
|
||||
"clap",
|
||||
"roff",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clipboard-win"
|
||||
version = "5.4.1"
|
||||
@@ -820,6 +923,12 @@ version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b"
|
||||
|
||||
[[package]]
|
||||
name = "colorchoice"
|
||||
version = "1.0.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
|
||||
|
||||
[[package]]
|
||||
name = "combine"
|
||||
version = "4.6.8"
|
||||
@@ -1740,7 +1849,7 @@ dependencies = [
|
||||
"libc",
|
||||
"option-ext",
|
||||
"redox_users",
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2141,7 +2250,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2339,7 +2448,7 @@ checksum = "94e7099f6313ecacbe1256e8ff9d617b75d1bcb16a6fddef94866d225a01a14a"
|
||||
dependencies = [
|
||||
"io-lifetimes 2.0.4",
|
||||
"rustix 1.1.6",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3237,6 +3346,12 @@ version = "2.12.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0"
|
||||
|
||||
[[package]]
|
||||
name = "is_terminal_polyfill"
|
||||
version = "1.70.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
|
||||
|
||||
[[package]]
|
||||
name = "itertools"
|
||||
version = "0.13.0"
|
||||
@@ -3674,7 +3789,7 @@ dependencies = [
|
||||
"objc2-foundation 0.3.2",
|
||||
"png",
|
||||
"thiserror 2.0.21",
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4343,6 +4458,12 @@ version = "1.21.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
|
||||
|
||||
[[package]]
|
||||
name = "once_cell_polyfill"
|
||||
version = "1.70.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
|
||||
|
||||
[[package]]
|
||||
name = "openssl-probe"
|
||||
version = "0.2.2"
|
||||
@@ -4391,7 +4512,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5138,6 +5259,12 @@ dependencies = [
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "roff"
|
||||
version = "1.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "323c417e1d9665a65b263ec744ba09030cfb277e9daa0b018a4ab62e57bc8189"
|
||||
|
||||
[[package]]
|
||||
name = "ron"
|
||||
version = "0.12.2"
|
||||
@@ -5192,7 +5319,7 @@ dependencies = [
|
||||
"errno",
|
||||
"libc",
|
||||
"linux-raw-sys 0.4.15",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5205,7 +5332,7 @@ dependencies = [
|
||||
"errno",
|
||||
"libc",
|
||||
"linux-raw-sys 0.12.1",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5272,7 +5399,7 @@ dependencies = [
|
||||
"security-framework",
|
||||
"security-framework-sys",
|
||||
"webpki-root-certs",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5650,7 +5777,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5800,10 +5927,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
|
||||
dependencies = [
|
||||
"fastrand",
|
||||
"getrandom 0.3.4",
|
||||
"getrandom 0.4.3",
|
||||
"once_cell",
|
||||
"rustix 1.1.6",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5819,6 +5946,7 @@ dependencies = [
|
||||
name = "texturecraft"
|
||||
version = "0.6.1"
|
||||
dependencies = [
|
||||
"craft-host",
|
||||
"craft-image-codecs",
|
||||
"craft-menu",
|
||||
"craft-update",
|
||||
@@ -5829,6 +5957,7 @@ dependencies = [
|
||||
"log",
|
||||
"rfd",
|
||||
"ron",
|
||||
"rustix 1.1.6",
|
||||
"serde_json",
|
||||
"texturecraft-automation",
|
||||
"texturecraft-engine",
|
||||
@@ -5836,6 +5965,7 @@ dependencies = [
|
||||
"winit",
|
||||
"winresource",
|
||||
"winsafe",
|
||||
"x11rb-protocol",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5852,6 +5982,7 @@ dependencies = [
|
||||
"schemars",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
"texturecraft-engine",
|
||||
"texturecraft-formats",
|
||||
"texturecraft-render",
|
||||
@@ -5875,10 +6006,14 @@ dependencies = [
|
||||
name = "texturecraft-cli"
|
||||
version = "0.6.1"
|
||||
dependencies = [
|
||||
"clap",
|
||||
"clap_complete",
|
||||
"clap_mangen",
|
||||
"image",
|
||||
"serde_json",
|
||||
"texturecraft-automation",
|
||||
"texturecraft-engine",
|
||||
"thiserror 2.0.21",
|
||||
"tokio",
|
||||
"winresource",
|
||||
]
|
||||
@@ -5952,7 +6087,6 @@ dependencies = [
|
||||
"half",
|
||||
"image",
|
||||
"png",
|
||||
"quick-xml 0.41.0",
|
||||
"rayon",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -5984,6 +6118,7 @@ dependencies = [
|
||||
"harfrust 0.12.0",
|
||||
"rayon",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"skrifa 0.44.0",
|
||||
"texturecraft-compose",
|
||||
"texturecraft-core",
|
||||
@@ -6038,6 +6173,7 @@ dependencies = [
|
||||
"egui",
|
||||
"egui-phosphor",
|
||||
"egui_kittest",
|
||||
"flate2",
|
||||
"image",
|
||||
"js-sys",
|
||||
"log",
|
||||
@@ -6045,6 +6181,7 @@ dependencies = [
|
||||
"raw-window-handle",
|
||||
"rayon",
|
||||
"rfd",
|
||||
"same-file",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"skera",
|
||||
@@ -6382,7 +6519,7 @@ checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e"
|
||||
dependencies = [
|
||||
"memoffset",
|
||||
"tempfile",
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6517,6 +6654,12 @@ dependencies = [
|
||||
"utf_types",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "utf8parse"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
|
||||
|
||||
[[package]]
|
||||
name = "utf_types"
|
||||
version = "1.0.0"
|
||||
@@ -7072,7 +7215,7 @@ version = "0.1.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
|
||||
dependencies = [
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -7459,7 +7602,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3f3fd376f71958b862e7afb20cfe5a22830e1963462f3a17f49d82a6c1d1f42d"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -7866,7 +8009,7 @@ dependencies = [
|
||||
"memchr",
|
||||
"nix",
|
||||
"typed-path",
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.61.2",
|
||||
"zeroize",
|
||||
"zopfli",
|
||||
]
|
||||
|
||||
+19
-2
@@ -26,6 +26,10 @@ texturecraft-ui-egui = { path = "crates/ui-egui" }
|
||||
|
||||
# external
|
||||
thiserror = "2"
|
||||
# The command line of texturecraft-cli (RFC-0018); the generators are dev-dependencies, for the man pages and completions.
|
||||
clap = { version = "4", features = ["derive", "string", "env"] }
|
||||
clap_complete = "4"
|
||||
clap_mangen = "0.2"
|
||||
chrono = { version = "0.4", default-features = false, features = ["now", "wasmbind"] }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
@@ -51,7 +55,6 @@ 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"
|
||||
quick-xml = "0.41"
|
||||
mikktspace = { version = "0.3", default-features = false, features = ["glam"] }
|
||||
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"] }
|
||||
@@ -135,12 +138,26 @@ codegen-units = 16
|
||||
|
||||
[profile.wasm-release]
|
||||
inherits = "release"
|
||||
opt-level = "s"
|
||||
# "z" over "s": the browser build must stay under the 24 MiB gate in packaging/web/package.sh.
|
||||
# Measured on main 7c8dd1ae: 30,812,862 bytes with "s", 26,654,524 bytes with the levels below.
|
||||
opt-level = "z"
|
||||
lto = "fat"
|
||||
codegen-units = 1
|
||||
strip = "debuginfo"
|
||||
|
||||
[profile.wasm-release.package."*"]
|
||||
opt-level = "z"
|
||||
|
||||
# Kept at "s": these rely on inlining, and at "z" they come out larger, not smaller.
|
||||
[profile.wasm-release.package.fearless_simd]
|
||||
opt-level = "s"
|
||||
[profile.wasm-release.package.vello_cpu]
|
||||
opt-level = "s"
|
||||
[profile.wasm-release.package.vello_common]
|
||||
opt-level = "s"
|
||||
[profile.wasm-release.package.craft-image-codecs]
|
||||
opt-level = "s"
|
||||
[profile.wasm-release.package.texturecraft-core]
|
||||
opt-level = "s"
|
||||
|
||||
[profile.wasm-release.package.texturecraft-texel]
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 ArtCraft Team and the TextureCraft contributors
|
||||
Copyright (c) 2026 ArtCraft Team and the PhotoCraft contributors (adapted Linux pen and display probing code)
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
|
||||
@@ -12,10 +12,23 @@ 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.
|
||||
|
||||
PhotoCraft Linux pen and display probing code, adapted in apps/texturecraft/src/xwayland_pen.rs
|
||||
from storytold/photocraft at 830316b775f1f6734498ac6e39fd1298955ff93f.
|
||||
Copyright (c) 2026 ArtCraft Team and the PhotoCraft contributors.
|
||||
Licensed under the MIT License or the Apache License, Version 2.0, at your option
|
||||
(LICENSE-MIT, LICENSE-APACHE).
|
||||
|
||||
Linux X11 setup probe components:
|
||||
- rustix — Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT.
|
||||
- x11rb-protocol — MIT OR Apache-2.0. Copyright 2019 x11rb contributors.
|
||||
|
||||
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 autosave file identity checks use same-file (Unlicense OR MIT).
|
||||
Copyright (c) 2017 Andrew Gallant.
|
||||
|
||||
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.
|
||||
|
||||
+2
-2
@@ -82,7 +82,7 @@ The evidence column includes the November 16 scores for comparison.
|
||||
| UI/UX fidelity | ~75% | 20 | TBD | Layer targeting, the workspace, Bake Mode and export dialogs changed. Live task, layout, shortcut and accessibility checks remain. November 16 estimate ~65% |
|
||||
| File formats / interchange | ~70% | 10 | TBD | Shared import/export codecs, rebuilt UV persistence and linked `.mcmat` v3 have landed. Project/output contracts, `.spp` and destination-tool coverage remain open. November 16 estimate ~60% |
|
||||
| Hardware (GPU, pen, displays) | ~50% | 8 | TBD | One Windows GPU exercised; pen tilt, pressure across platforms and display coverage remain incomplete. November 16 estimate ~50% |
|
||||
| Localization | ~35% | 4 | TBD | Ten picker languages in source; optional shared catalogs/fonts and native-language review need current measurement. November 16 estimate ~35% |
|
||||
| Localization | ~35% | 4 | TBD | Eleven picker languages in source; optional shared catalogs/fonts and native-language review need current measurement. November 16 estimate ~35% |
|
||||
| Performance | ~45% | 10 | TBD | Main added dirty-region uploads, cheaper undo snapshots and faster glTF lookups. Establish response-time and memory budgets with representative large projects. November 16 estimate ~40% |
|
||||
| Stability | ~60% | 10 | TBD | The live baseline covered small save/reopen and undo/redo. Rebuilt UV layouts gained persistence checks. Recovery, large projects and long sessions remain open. November 16 estimate ~55% |
|
||||
| Platforms | ~70% | 3 | TBD | Desktop and web build paths exist. Nightly packaging and supervised signing workflows landed for Windows, Linux and macOS. Install, update and hardware checks remain. November 16 estimate ~65% |
|
||||
@@ -151,7 +151,7 @@ signed release installation remain outside the November 25 test evidence.
|
||||
|
||||
## Languages
|
||||
|
||||
The [picker](crates/ui-egui/src/i18n.rs) contains ten languages. Shared catalogs are optional at
|
||||
The [picker](crates/ui-egui/src/i18n.rs) contains eleven languages. Shared catalogs are optional at
|
||||
build time; missing entries fall back to English, and builds without catalogs offer English only.
|
||||
The older [coverage table](docs/localization-parity.md) predates catalog migration, so its “100%”
|
||||
rows are not a current measurement. The November 16 live audit ran an English build without external catalogs.
|
||||
|
||||
@@ -6,6 +6,14 @@ edition.workspace = true
|
||||
license.workspace = true
|
||||
build = "build.rs"
|
||||
|
||||
[lib]
|
||||
name = "texturecraft_cli"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "texturecraft-cli"
|
||||
path = "src/main.rs"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
@@ -14,9 +22,13 @@ texturecraft-automation = { workspace = true }
|
||||
texturecraft-engine = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
clap = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
image = { workspace = true }
|
||||
clap_complete = { workspace = true }
|
||||
clap_mangen = { workspace = true }
|
||||
|
||||
[build-dependencies]
|
||||
winresource = "0.1"
|
||||
@@ -0,0 +1,42 @@
|
||||
//! Writes texturecraft-cli's shell completions ([`clap_complete`]: bash, zsh, fish, elvish,
|
||||
//! PowerShell) and man pages ([`clap_mangen`]: `texturecraft-cli.1` and one per subcommand, such as
|
||||
//! `texturecraft-cli-info.1`) into a directory. The Linux and FreeBSD packages ship them
|
||||
//! (`packaging/linux/package.sh`, `packaging/freebsd/package.sh`):
|
||||
//!
|
||||
//! ```sh
|
||||
//! cargo run -p texturecraft-cli --example man-and-completions -- <out-dir>
|
||||
//! ```
|
||||
|
||||
use std::path::Path;
|
||||
use std::process::ExitCode;
|
||||
|
||||
use clap::ValueEnum;
|
||||
use clap_complete::Shell;
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let mut args = std::env::args_os().skip(1);
|
||||
let (Some(dir), None) = (args.next(), args.next()) else {
|
||||
eprintln!("usage: man-and-completions <out-dir>");
|
||||
return ExitCode::from(2);
|
||||
};
|
||||
let dir = Path::new(&dir);
|
||||
match generate(dir) {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
Err(e) => {
|
||||
eprintln!("error: {}: {e}", dir.display());
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Also run by `tests/it/man_and_completions.rs`.
|
||||
pub(crate) fn generate(dir: &Path) -> std::io::Result<()> {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
let mut cmd = texturecraft_cli::command();
|
||||
for &shell in Shell::value_variants() {
|
||||
clap_complete::generate_to(shell, &mut cmd, "texturecraft-cli", dir)?;
|
||||
}
|
||||
// A fresh command: `clap_complete::generate_to` built `cmd`, adding the `help` subcommand,
|
||||
// which `clap_mangen` would otherwise give pages of its own (`texturecraft-cli-help-convert.1`).
|
||||
clap_mangen::generate_to(texturecraft_cli::command(), dir)
|
||||
}
|
||||
@@ -0,0 +1,422 @@
|
||||
//! The command line as clap derive types. Values arrive typed, so the commands never validate a
|
||||
//! string; what clap can't say alone is a [`UsageError`], printed and exited like clap's own.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::str::FromStr;
|
||||
|
||||
use clap::error::ErrorKind;
|
||||
use clap::{Args, FromArgMatches, Parser, Subcommand};
|
||||
use serde_json::Value;
|
||||
|
||||
/// The end of `--help` of every command.
|
||||
const EXIT_STATUS: &str = "Exit status:\n 0 success\n 1 a command failed\n 2 usage error\n\nA process ended by a signal exits 128 + the signal number (130 for Ctrl-C), as in the shell.";
|
||||
|
||||
const INPUTS: &str = "An <INPUT> is a .tcraft project, a mesh file (.glb .gltf .fbx .dae .usd .usda .usdc .usdz .abc .obj .ply .stl) or builtin:<id> (material_ball, sphere, cube, rounded_cube, cylinder, torus, plane, crate, udim_plane). See docs/control-protocol.md.";
|
||||
|
||||
/// Headless TextureCraft
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(name = "texturecraft-cli", propagate_version = true, arg_required_else_help = true, after_help = EXIT_STATUS)]
|
||||
pub(crate) struct Cli {
|
||||
#[command(subcommand)]
|
||||
pub(crate) command: Command,
|
||||
}
|
||||
|
||||
#[derive(Subcommand, Debug)]
|
||||
pub(crate) enum Command {
|
||||
/// Texture sets, layers, triangles, materials and the UV report, as JSON
|
||||
#[command(after_help = INPUTS)]
|
||||
Info(InfoArgs),
|
||||
/// List the engine commands (id, label, params)
|
||||
Commands(CommandsArgs),
|
||||
/// Run one command and print its JSON result; -o saves the project
|
||||
#[command(after_help = INPUTS)]
|
||||
Run(RunArgs),
|
||||
/// Run a script of commands
|
||||
///
|
||||
/// The script is JSON: [{"id", "params"}, ...] or {"open": <input>, "steps": [...], "save": <out.tcraft>}.
|
||||
Batch(BatchArgs),
|
||||
/// Bake mesh maps for every texture set
|
||||
///
|
||||
/// A project is saved in place without -o, which needs --in-place; a mesh needs -o.
|
||||
#[command(after_help = INPUTS)]
|
||||
Bake(BakeArgs),
|
||||
/// Export textures (default preset: Document channels + Normal + AO (No Alpha))
|
||||
#[command(after_help = INPUTS)]
|
||||
Export(ExportArgs),
|
||||
/// Render the viewport to PNG (needs a GPU or software adapter)
|
||||
///
|
||||
/// --camera looks through a camera saved in the project (camera.add); --samples path traces it
|
||||
/// instead (Rendering mode), on the GPU when it has compute shaders, else (or with --cpu) on
|
||||
/// the CPU (no GPU needed).
|
||||
#[command(after_help = INPUTS)]
|
||||
Render(RenderArgs),
|
||||
/// A new project from a mesh or a built-in mesh
|
||||
///
|
||||
/// --sample bakes and applies a smart material to every texture set. The sample's mesh maps are
|
||||
/// baked at the resolution up to 1024 px (most of the file's size), so a 2048 sample project is
|
||||
/// as large as a 1024 one.
|
||||
#[command(after_help = INPUTS)]
|
||||
New(NewArgs),
|
||||
/// MCP server on stdio: headless, or bridged to `texturecraft --control <port>`
|
||||
///
|
||||
/// Headless, file access is only below the roots.
|
||||
Mcp(McpArgs),
|
||||
/// JSON lines ({"id","method","params"}) on stdio, or on 127.0.0.1:<port> with a token
|
||||
Serve(ServeArgs),
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub(crate) struct InfoArgs {
|
||||
#[arg(value_name = "INPUT")]
|
||||
pub(crate) input: PathBuf,
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub(crate) struct CommandsArgs {
|
||||
/// Only the commands whose id or label contains this text
|
||||
#[arg(long, value_name = "TEXT")]
|
||||
pub(crate) filter: Option<String>,
|
||||
/// Print the list as JSON instead of a table
|
||||
#[arg(long)]
|
||||
pub(crate) json: bool,
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub(crate) struct RunArgs {
|
||||
#[arg(value_name = "INPUT")]
|
||||
pub(crate) input: PathBuf,
|
||||
#[arg(value_name = "COMMAND-ID")]
|
||||
pub(crate) id: String,
|
||||
/// The command's parameters, as JSON
|
||||
#[arg(value_name = "PARAMS-JSON", value_parser = json_value)]
|
||||
pub(crate) params: Option<Value>,
|
||||
/// Save the project here
|
||||
#[arg(short = 'o', long = "output", value_name = "OUT.TCRAFT")]
|
||||
pub(crate) output: Option<PathBuf>,
|
||||
/// Allow -o to replace the project it opened
|
||||
#[arg(long, requires = "output")]
|
||||
pub(crate) in_place: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, thiserror::Error)]
|
||||
#[error("params are not JSON: {0}")]
|
||||
pub(crate) struct NotJson(String);
|
||||
|
||||
fn json_value(s: &str) -> Result<Value, NotJson> {
|
||||
serde_json::from_str(s).map_err(|e| NotJson(e.to_string()))
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub(crate) struct BatchArgs {
|
||||
#[arg(value_name = "SCRIPT.JSON")]
|
||||
pub(crate) script: PathBuf,
|
||||
/// Allow `save` to replace the project `open` named
|
||||
#[arg(long)]
|
||||
pub(crate) in_place: bool,
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub(crate) struct BakeArgs {
|
||||
#[arg(value_name = "INPUT")]
|
||||
pub(crate) input: PathBuf,
|
||||
/// Save the baked project here
|
||||
#[arg(short = 'o', long = "output", value_name = "OUT.TCRAFT")]
|
||||
pub(crate) output: Option<PathBuf>,
|
||||
/// Bake at this size
|
||||
#[arg(long, value_name = "PX", value_parser = positive)]
|
||||
pub(crate) resolution: Option<u32>,
|
||||
/// Only these maps (ids, comma separated)
|
||||
#[arg(long, value_name = "ID,ID,...", value_delimiter = ',')]
|
||||
pub(crate) maps: Vec<String>,
|
||||
/// Save over the project it opened (without -o), or allow -o to replace it
|
||||
#[arg(long)]
|
||||
pub(crate) in_place: bool,
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub(crate) struct ExportArgs {
|
||||
#[arg(value_name = "INPUT")]
|
||||
pub(crate) input: PathBuf,
|
||||
#[arg(value_name = "DIR")]
|
||||
pub(crate) dir: PathBuf,
|
||||
/// An export preset by name
|
||||
#[arg(long, value_name = "NAME")]
|
||||
pub(crate) preset: Option<String>,
|
||||
/// File format (an extension)
|
||||
#[arg(long, value_name = "EXT")]
|
||||
pub(crate) format: Option<String>,
|
||||
/// Padding mode
|
||||
#[arg(long, value_name = "MODE")]
|
||||
pub(crate) padding: Option<String>,
|
||||
/// Texture size
|
||||
#[arg(long, value_name = "PX", value_parser = positive)]
|
||||
pub(crate) size: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub(crate) struct RenderArgs {
|
||||
#[arg(value_name = "INPUT")]
|
||||
pub(crate) input: PathBuf,
|
||||
#[arg(value_name = "OUT.PNG")]
|
||||
pub(crate) output: PathBuf,
|
||||
/// Image size
|
||||
#[arg(long, value_name = "WxH")]
|
||||
pub(crate) size: Option<Dimensions>,
|
||||
/// The viewport: 3D, or the UV view of the active texture set
|
||||
#[arg(long, value_name = "VIEW", value_parser = ["3d", "2d", "uv"])]
|
||||
pub(crate) view: Option<String>,
|
||||
/// Look through a camera saved in the project
|
||||
#[arg(long, value_name = "NAME")]
|
||||
pub(crate) camera: Option<String>,
|
||||
/// Camera yaw in degrees
|
||||
#[arg(long, value_name = "DEG", allow_negative_numbers = true, value_parser = finite)]
|
||||
pub(crate) yaw: Option<f32>,
|
||||
/// Camera pitch in degrees
|
||||
#[arg(long, value_name = "DEG", allow_negative_numbers = true, value_parser = finite)]
|
||||
pub(crate) pitch: Option<f32>,
|
||||
/// Path trace with this many samples per pixel
|
||||
#[arg(long, value_name = "N", value_parser = positive)]
|
||||
pub(crate) samples: Option<u32>,
|
||||
/// Light bounces of the path tracer
|
||||
#[arg(long, value_name = "N", requires = "samples")]
|
||||
pub(crate) bounces: Option<u32>,
|
||||
/// Path trace on the CPU
|
||||
#[arg(long, requires = "samples")]
|
||||
pub(crate) cpu: bool,
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub(crate) struct NewArgs {
|
||||
#[arg(value_name = "INPUT")]
|
||||
pub(crate) input: PathBuf,
|
||||
#[arg(value_name = "OUT.TCRAFT")]
|
||||
pub(crate) output: PathBuf,
|
||||
/// Texture size
|
||||
#[arg(long, value_name = "PX", value_parser = positive)]
|
||||
pub(crate) resolution: Option<u32>,
|
||||
/// Bake and apply a smart material to every texture set
|
||||
#[arg(long)]
|
||||
pub(crate) sample: bool,
|
||||
}
|
||||
|
||||
/// The folders a server may read from and write to; with neither, it has no file access.
|
||||
#[derive(Args, Debug, Default)]
|
||||
pub(crate) struct RootArgs {
|
||||
/// Serve file access below this folder (alias --automation-read-root)
|
||||
#[arg(long, alias = "automation-read-root", value_name = "DIR")]
|
||||
pub(crate) read_root: Option<PathBuf>,
|
||||
/// Allow writes below this folder (alias --automation-write-root)
|
||||
#[arg(long, alias = "automation-write-root", value_name = "DIR")]
|
||||
pub(crate) write_root: Option<PathBuf>,
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub(crate) struct McpArgs {
|
||||
/// Bridge to a running app's control port instead of a headless session
|
||||
#[arg(long, value_name = "PORT", value_parser = port)]
|
||||
pub(crate) bridge: Option<u16>,
|
||||
/// The app's control token (TEXTURECRAFT_CONTROL_TOKEN; else the file the app wrote)
|
||||
#[arg(long, value_name = "TOKEN", env = "TEXTURECRAFT_CONTROL_TOKEN", hide_env_values = true)]
|
||||
pub(crate) token: Option<String>,
|
||||
#[command(flatten)]
|
||||
pub(crate) roots: RootArgs,
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub(crate) struct ServeArgs {
|
||||
/// Listen on 127.0.0.1:<PORT> with a token, instead of stdio
|
||||
#[arg(long, value_name = "PORT", value_parser = port)]
|
||||
pub(crate) port: Option<u16>,
|
||||
#[command(flatten)]
|
||||
pub(crate) roots: RootArgs,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, thiserror::Error)]
|
||||
#[error("`{0}` is not a number of pixels above zero")]
|
||||
pub(crate) struct NotPositive(String);
|
||||
|
||||
fn positive(s: &str) -> Result<u32, NotPositive> {
|
||||
s.parse::<u32>().ok().filter(|n| *n > 0).ok_or_else(|| NotPositive(s.to_string()))
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, thiserror::Error)]
|
||||
#[error("`{0}` is not a finite number")]
|
||||
pub(crate) struct NotFinite(String);
|
||||
|
||||
fn finite(s: &str) -> Result<f32, NotFinite> {
|
||||
s.parse::<f32>().ok().filter(|n| n.is_finite()).ok_or_else(|| NotFinite(s.to_string()))
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, thiserror::Error)]
|
||||
#[error("`{0}` is not a loopback port (1-65535)")]
|
||||
pub(crate) struct BadPort(String);
|
||||
|
||||
/// A port, as `7878`, `127.0.0.1:7878` or `localhost:7878`.
|
||||
fn port(s: &str) -> Result<u16, BadPort> {
|
||||
let digits = s.strip_prefix("127.0.0.1:").or_else(|| s.strip_prefix("localhost:")).unwrap_or(s);
|
||||
digits.parse::<u16>().ok().filter(|p| *p != 0).ok_or_else(|| BadPort(s.to_string()))
|
||||
}
|
||||
|
||||
/// `--size` of `render`: WIDTHxHEIGHT.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(crate) struct Dimensions {
|
||||
pub(crate) width: u32,
|
||||
pub(crate) height: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, thiserror::Error)]
|
||||
#[error("`{0}` is not <W>x<H>, e.g. 1280x800")]
|
||||
pub(crate) struct BadDimensions(String);
|
||||
|
||||
impl FromStr for Dimensions {
|
||||
type Err = BadDimensions;
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, BadDimensions> {
|
||||
let (width, height) = s.split_once(['x', 'X']).ok_or_else(|| BadDimensions(s.to_string()))?;
|
||||
match (positive(width), positive(height)) {
|
||||
(Ok(width), Ok(height)) => Ok(Dimensions { width, height }),
|
||||
_ => Err(BadDimensions(s.to_string())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A mistake in the command line that clap can't see by itself.
|
||||
#[derive(Debug, PartialEq, thiserror::Error)]
|
||||
pub(crate) enum UsageError {
|
||||
#[error("{output} {} is the {input}, which it would replace: choose another file{}", path.display(), if *in_place_helps { ", or pass --in-place" } else { "" })]
|
||||
WouldReplace { output: &'static str, input: &'static str, path: PathBuf, in_place_helps: bool },
|
||||
#[error("--in-place is for an output that is the INPUT, and this is another file")]
|
||||
InPlaceNotUsed,
|
||||
#[error("a mesh is not saved in place: give -o <out.tcraft> to save the baked project")]
|
||||
BakeNeedsOutput,
|
||||
#[error("saving over {} needs --in-place (or give -o <out.tcraft>)", path.display())]
|
||||
BakeInPlace { path: PathBuf },
|
||||
#[error("{flag} is for a headless server, and --bridge connects to an app")]
|
||||
RootsWithBridge { flag: &'static str },
|
||||
#[error("--token is for --bridge, and this is a headless server")]
|
||||
TokenNeedsBridge,
|
||||
#[error("mcp needs --read-root and --write-root (or their --automation-*-root aliases)")]
|
||||
McpNeedsRoots,
|
||||
}
|
||||
|
||||
impl UsageError {
|
||||
/// The clap error, printed with the usage and exited with 2 like clap's own.
|
||||
pub(crate) fn into_clap(self, subcommand: &str) -> clap::Error {
|
||||
let mut command = crate::command();
|
||||
// Built, so a subcommand's usage names the program: `texturecraft-cli run`.
|
||||
command.build();
|
||||
let mut command = command.find_subcommand_mut(subcommand).map_or_else(crate::command, std::mem::take);
|
||||
command.error(ErrorKind::ArgumentConflict, self.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether two paths name the same existing file, through links and `.` and `..`.
|
||||
fn same_file(a: &Path, b: &Path) -> bool {
|
||||
matches!((std::fs::canonicalize(a), std::fs::canonicalize(b)), (Ok(a), Ok(b)) if a == b)
|
||||
}
|
||||
|
||||
/// Whether `path` is a .tcraft project.
|
||||
pub(crate) fn is_project(path: &Path) -> bool {
|
||||
path.extension().is_some_and(|e| e.eq_ignore_ascii_case(texturecraft_engine::core::PROJECT_EXT))
|
||||
}
|
||||
|
||||
/// The path `Headless::save` writes: it appends `.tcraft` when the extension is missing.
|
||||
fn project_save_path(path: &Path) -> PathBuf {
|
||||
if is_project(path) {
|
||||
path.to_owned()
|
||||
} else {
|
||||
let mut raw = path.as_os_str().to_os_string();
|
||||
raw.push(".");
|
||||
raw.push(texturecraft_engine::core::PROJECT_EXT);
|
||||
PathBuf::from(raw)
|
||||
}
|
||||
}
|
||||
|
||||
fn would_replace(output: &'static str, input: &'static str, to: &Path, from: &Path, in_place_helps: bool) -> Result<(), UsageError> {
|
||||
if same_file(to, from) { Err(UsageError::WouldReplace { output, input, path: to.to_owned(), in_place_helps }) } else { Ok(()) }
|
||||
}
|
||||
|
||||
fn would_replace_project(output: &'static str, input: &'static str, to: &Path, from: &Path, in_place_helps: bool) -> Result<(), UsageError> {
|
||||
would_replace(output, input, &project_save_path(to), from, in_place_helps)
|
||||
}
|
||||
|
||||
fn same_project(output: &Path, input: &Path) -> bool {
|
||||
same_file(&project_save_path(output), input)
|
||||
}
|
||||
|
||||
/// If a batch script's `save` would replace `open`, it needs `--in-place`. An unreadable or
|
||||
/// malformed script is left to the command, which reports that as a failure (exit 1).
|
||||
fn batch_would_replace(a: &BatchArgs) -> Result<(), UsageError> {
|
||||
let Ok(text) = std::fs::read_to_string(&a.script) else {
|
||||
return Ok(());
|
||||
};
|
||||
let Ok(script) = serde_json::from_str::<Value>(&text) else {
|
||||
return Ok(());
|
||||
};
|
||||
let field = |name: &str| script.get(name).and_then(Value::as_str);
|
||||
let Some(output) = field("save") else {
|
||||
return Ok(());
|
||||
};
|
||||
let input = field("open").unwrap_or("builtin:material_ball");
|
||||
if input.starts_with("builtin:") {
|
||||
return if a.in_place { Err(UsageError::InPlaceNotUsed) } else { Ok(()) };
|
||||
}
|
||||
let input = Path::new(input);
|
||||
let output = Path::new(output);
|
||||
match (same_project(output, input), a.in_place) {
|
||||
(true, false) => Err(UsageError::WouldReplace { output: "save", input: "open", path: project_save_path(output), in_place_helps: true }),
|
||||
(false, true) => Err(UsageError::InPlaceNotUsed),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
impl Command {
|
||||
/// What clap can't check: the files a command would replace, and flags for another mode.
|
||||
fn check(&self) -> Result<(), (&'static str, UsageError)> {
|
||||
match self {
|
||||
Command::Run(a) => match (&a.output, a.in_place) {
|
||||
(Some(out), false) => would_replace_project("-o", "INPUT", out, &a.input, true).map_err(|e| ("run", e)),
|
||||
(Some(out), true) if !same_project(out, &a.input) => Err(("run", UsageError::InPlaceNotUsed)),
|
||||
_ => Ok(()),
|
||||
},
|
||||
Command::Bake(a) => match (&a.output, a.in_place) {
|
||||
(None, false) if is_project(&a.input) => Err(("bake", UsageError::BakeInPlace { path: a.input.clone() })),
|
||||
(None, _) if !is_project(&a.input) => Err(("bake", UsageError::BakeNeedsOutput)),
|
||||
(Some(out), false) => would_replace_project("-o", "INPUT", out, &a.input, true).map_err(|e| ("bake", e)),
|
||||
(Some(out), true) if !same_project(out, &a.input) => Err(("bake", UsageError::InPlaceNotUsed)),
|
||||
_ => Ok(()),
|
||||
},
|
||||
Command::Render(a) => would_replace("OUT.PNG", "INPUT", &a.output, &a.input, false).map_err(|e| ("render", e)),
|
||||
Command::New(a) => would_replace_project("OUT.TCRAFT", "INPUT", &a.output, &a.input, false).map_err(|e| ("new", e)),
|
||||
Command::Batch(a) => batch_would_replace(a).map_err(|e| ("batch", e)),
|
||||
Command::Mcp(a) if a.bridge.is_some() => match (&a.roots.read_root, &a.roots.write_root) {
|
||||
(Some(_), _) => Err(("mcp", UsageError::RootsWithBridge { flag: "--read-root" })),
|
||||
(_, Some(_)) => Err(("mcp", UsageError::RootsWithBridge { flag: "--write-root" })),
|
||||
_ => Ok(()),
|
||||
},
|
||||
Command::Mcp(a) if a.bridge.is_none() => match (&a.roots.read_root, &a.roots.write_root) {
|
||||
(Some(_), Some(_)) => Ok(()),
|
||||
_ => Err(("mcp", UsageError::McpNeedsRoots)),
|
||||
},
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses the arguments (without the program name). Help and the version come back as errors too,
|
||||
/// which print to stdout and exit 0.
|
||||
pub(crate) fn parse(args: &[OsString]) -> Result<Cli, clap::Error> {
|
||||
let matches = crate::command().try_get_matches_from(std::iter::once(OsString::from("texturecraft-cli")).chain(args.iter().cloned()))?;
|
||||
let cli = Cli::from_arg_matches(&matches)?;
|
||||
// An inherited TEXTURECRAFT_CONTROL_TOKEN must not force --bridge: the variable is how a
|
||||
// client authenticates when --bridge is already set. Only an explicit --token flag requires it.
|
||||
let token_flag_without_bridge = matches
|
||||
.subcommand_matches("mcp")
|
||||
.is_some_and(|mcp| mcp.value_source("token") == Some(clap::parser::ValueSource::CommandLine) && mcp.get_one::<u16>("bridge").is_none());
|
||||
if token_flag_without_bridge {
|
||||
return Err(UsageError::TokenNeedsBridge.into_clap("mcp"));
|
||||
}
|
||||
cli.command.check().map_err(|(sub, e)| e.into_clap(sub))?;
|
||||
Ok(cli)
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use texturecraft_automation::AutomationError;
|
||||
|
||||
/// Why a subcommand failed: printed as `error: {e}`, exit 1.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub(crate) enum CliError {
|
||||
#[error(transparent)]
|
||||
Automation(#[from] AutomationError),
|
||||
/// The engine's commands take paths as JSON text, which holds only Unicode.
|
||||
#[error("{}: the path is not valid Unicode", .0.display())]
|
||||
NotUnicode(PathBuf),
|
||||
#[error("unknown built-in mesh `{0}`")]
|
||||
UnknownBuiltin(String),
|
||||
#[error("cannot read {}: {message}", path.display())]
|
||||
Read { path: PathBuf, message: String },
|
||||
#[error("cannot write {}: {source}", path.display())]
|
||||
Write { path: PathBuf, source: std::io::Error },
|
||||
#[error("{} is not JSON: {source}", path.display())]
|
||||
Script { path: PathBuf, source: serde_json::Error },
|
||||
#[error("the script must be a list of steps or {{\"steps\": [...]}}")]
|
||||
ScriptShape,
|
||||
#[error("the script's `{0}` field must be a string")]
|
||||
ScriptField(&'static str),
|
||||
#[error("step {index} (`{id}`) failed: {message}")]
|
||||
BatchStopped { index: String, id: String, message: String },
|
||||
#[error("{} is already a project", .0.display())]
|
||||
AlreadyProject(PathBuf),
|
||||
#[error("{0}")]
|
||||
Serve(std::io::Error),
|
||||
}
|
||||
|
||||
/// A path as the text the engine's commands take.
|
||||
pub(crate) fn unicode(path: &Path) -> Result<&str, CliError> {
|
||||
path.to_str().ok_or_else(|| CliError::NotUnicode(path.to_owned()))
|
||||
}
|
||||
@@ -0,0 +1,342 @@
|
||||
//! Headless TextureCraft command line: inspect, script, bake, export and render projects, and
|
||||
//! serve agents over MCP or JSON lines. Never opens a window. `run` is the whole program, so it can
|
||||
//! be tested in-process as well as through the binary; `texturecraft-cli --help` lists the
|
||||
//! subcommands. The conventions are RFC-0018's: exit 0, 1 (a command failed) or 2 (a usage error),
|
||||
//! results on stdout, `error: <message>` on stderr.
|
||||
#![forbid(unsafe_code)]
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
mod args;
|
||||
mod error;
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use clap::CommandFactory;
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_automation::security::{client_token, server_token};
|
||||
use texturecraft_automation::{AuthorizedWorkspace, BridgeClient, Filesystem, Headless, RenderOptions, TexturecraftMcp, rpc};
|
||||
use texturecraft_engine::formats::{MeshReport, import_mesh, import_mesh_bytes, mesh_report};
|
||||
|
||||
use args::{
|
||||
BakeArgs, BatchArgs, Cli, Command, CommandsArgs, ExportArgs, InfoArgs, McpArgs, NewArgs, RenderArgs, RootArgs, RunArgs, ServeArgs, is_project, parse,
|
||||
};
|
||||
use error::{CliError, unicode};
|
||||
|
||||
/// Writes a line. A closed pipe (`texturecraft-cli info x | head`) is not worth an error: the rest
|
||||
/// of the output is dropped.
|
||||
macro_rules! outln {
|
||||
($to:expr, $($arg:tt)*) => {
|
||||
drop(writeln!($to, $($arg)*))
|
||||
};
|
||||
}
|
||||
|
||||
/// The version `--version` prints after the program's name: `<version> (<commit> <date>)`.
|
||||
fn version() -> String {
|
||||
let sha = env!("TEXTURECRAFT_BUILD_SHA");
|
||||
let short = sha.get(..7).unwrap_or(sha);
|
||||
let date = env!("TEXTURECRAFT_BUILD_DATE");
|
||||
match (short.is_empty(), date.is_empty()) {
|
||||
(true, true) => texturecraft_engine::VERSION.to_string(),
|
||||
(true, false) => format!("{} ({date})", texturecraft_engine::VERSION),
|
||||
_ => format!("{} ({short} {date})", texturecraft_engine::VERSION),
|
||||
}
|
||||
}
|
||||
|
||||
/// The command line's clap definition.
|
||||
pub fn command() -> clap::Command {
|
||||
Cli::command().version(version())
|
||||
}
|
||||
|
||||
/// 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 launch_profile_argument(args: &[OsString]) -> Option<String> {
|
||||
args.iter()
|
||||
.map(|arg| arg.to_string_lossy().into_owned())
|
||||
.find(|arg| ["--launch-profile", "--profile-root"].iter().any(|flag| arg == flag || arg.starts_with(&format!("{flag}="))))
|
||||
}
|
||||
|
||||
/// Run the CLI on its arguments (without the program name), writing results to `out` and
|
||||
/// diagnostics to `err`. Returns the process exit code: 0 on success, 1 on failure, 2 for a usage
|
||||
/// error. Help and the version go to `out`, exit 0. `mcp` and `serve` speak on the process's own
|
||||
/// stdin and stdout.
|
||||
pub fn run<I, T>(args: I, out: &mut dyn Write, err: &mut dyn Write) -> i32
|
||||
where
|
||||
I: IntoIterator<Item = T>,
|
||||
T: Into<OsString>,
|
||||
{
|
||||
let args: Vec<OsString> = args.into_iter().map(Into::into).collect();
|
||||
if let Some(flag) = launch_profile_argument(&args) {
|
||||
outln!(err, "error: `{flag}` is a TextureCraft desktop launch option, not a CLI argument");
|
||||
return 2;
|
||||
}
|
||||
// Help and the version (`help`, `-h`, `<subcommand> --help`, `-V`) come back as errors too.
|
||||
let cli = match parse(&args) {
|
||||
Ok(cli) => cli,
|
||||
Err(e) => {
|
||||
let to: &mut dyn Write = if e.use_stderr() { err } else { out };
|
||||
let _ = write!(to, "{}", e.render());
|
||||
return e.exit_code();
|
||||
}
|
||||
};
|
||||
match dispatch(cli.command, out, err) {
|
||||
Ok(()) => 0,
|
||||
Err(e) => {
|
||||
outln!(err, "error: {e}");
|
||||
1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn dispatch(command: Command, out: &mut dyn Write, err: &mut dyn Write) -> Result<(), CliError> {
|
||||
match command {
|
||||
Command::Info(a) => info(&a, out),
|
||||
Command::Commands(a) => commands(&a, out),
|
||||
Command::Run(a) => run_command(&a, out, err),
|
||||
Command::Batch(a) => batch(&a, out, err),
|
||||
Command::Bake(a) => bake(&a, out, err),
|
||||
Command::Export(a) => export(&a, out, err),
|
||||
Command::Render(a) => render(&a, err),
|
||||
Command::New(a) => new(&a, err),
|
||||
Command::Mcp(a) => mcp(&a),
|
||||
Command::Serve(a) => serve(&a, err),
|
||||
}
|
||||
}
|
||||
|
||||
fn print(out: &mut dyn Write, v: &Value) {
|
||||
outln!(out, "{}", serde_json::to_string_pretty(v).unwrap_or_else(|e| format!("{{\"error\": \"{e}\"}}")));
|
||||
}
|
||||
|
||||
/// A trusted local session on `input`: a project, a mesh file or `builtin:<id>`.
|
||||
fn open(input: &Path, resolution: Option<u32>) -> Result<Headless, CliError> {
|
||||
let mut h = Headless::new(Headless::default_session()?, Filesystem::TrustedLocal);
|
||||
match input.to_str().and_then(|text| text.strip_prefix("builtin:")) {
|
||||
Some(id) => h.command_run("project.new", json!({"mesh": id, "resolution": resolution.unwrap_or(1024), "name": id})).map(|_| ())?,
|
||||
None if is_project(input) => h.open(unicode(input)?).map(|_| ())?,
|
||||
None => h.import_mesh(unicode(input)?, resolution, None).map(|_| ())?,
|
||||
}
|
||||
Ok(h)
|
||||
}
|
||||
|
||||
fn save(h: &mut Headless, out: &Path, err: &mut dyn Write) -> Result<(), CliError> {
|
||||
let r = h.save(Some(unicode(out)?))?;
|
||||
outln!(err, "saved {}", r["path"].as_str().unwrap_or_default());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn report_json(r: &MeshReport) -> Value {
|
||||
json!({
|
||||
"triangles": r.triangles, "vertices": r.vertices, "materials": r.materials, "uvsGenerated": r.uvs_generated,
|
||||
"uvOutOfRange": r.uv_out_of_range, "overlapRatio": r.overlap_ratio, "zeroAreaUvTriangles": r.zero_area_uv_triangles, "warnings": r.warnings,
|
||||
})
|
||||
}
|
||||
|
||||
fn info(a: &InfoArgs, out: &mut dyn Write) -> Result<(), CliError> {
|
||||
let file = unicode(&a.input)?;
|
||||
if let Some(id) = file.strip_prefix("builtin:") {
|
||||
let m = texturecraft_engine::geom::primitives::builtin(id).ok_or_else(|| CliError::UnknownBuiltin(id.to_string()))?;
|
||||
let report = mesh_report(&m);
|
||||
print(
|
||||
out,
|
||||
&json!({
|
||||
"file": file, "kind": "mesh", "triangles": m.triangle_count(), "vertices": m.vertex_count(),
|
||||
"materials": m.materials, "textureSets": m.materials, "uv": report_json(&report),
|
||||
}),
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
if !is_project(&a.input) {
|
||||
let m = import_mesh(&a.input).map_err(|e| CliError::Read { path: a.input.clone(), message: e.to_string() })?;
|
||||
print(
|
||||
out,
|
||||
&json!({
|
||||
"file": file, "kind": "mesh", "triangles": m.mesh.triangle_count(), "vertices": m.mesh.vertex_count(),
|
||||
"materials": m.mesh.materials, "textureSets": m.mesh.materials, "uv": report_json(&m.report),
|
||||
}),
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
let h = open(&a.input, None)?;
|
||||
let mut v = h.inspect();
|
||||
v["file"] = json!(file);
|
||||
v["kind"] = json!("project");
|
||||
// The embedded mesh is re-imported for its UV report (built-in meshes have none).
|
||||
v["uv"] = match &h.session.mesh_source {
|
||||
Some((ext, bytes)) => {
|
||||
let m = import_mesh_bytes(&format!("mesh.{ext}"), bytes).map_err(|e| CliError::Read { path: a.input.clone(), message: e.to_string() })?;
|
||||
report_json(&m.report)
|
||||
}
|
||||
None => Value::Null,
|
||||
};
|
||||
print(out, &v);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn commands(a: &CommandsArgs, out: &mut dyn Write) -> Result<(), CliError> {
|
||||
let h = open(Path::new("builtin:cube"), Some(128))?;
|
||||
let list = h.command_list(a.filter.as_deref());
|
||||
if a.json {
|
||||
print(out, &list);
|
||||
return Ok(());
|
||||
}
|
||||
for c in list.as_array().into_iter().flatten() {
|
||||
let f = |k: &str| c.get(k).and_then(Value::as_str).unwrap_or_default().to_string();
|
||||
outln!(out, "{:<28} {:<36} {}", f("id"), f("label"), f("params"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn run_command(a: &RunArgs, out: &mut dyn Write, err: &mut dyn Write) -> Result<(), CliError> {
|
||||
let mut h = open(&a.input, None)?;
|
||||
print(out, &h.command_run(&a.id, a.params.clone().unwrap_or_else(|| json!({})))?);
|
||||
match &a.output {
|
||||
Some(path) => save(&mut h, path, err),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
fn batch(a: &BatchArgs, out: &mut dyn Write, err: &mut dyn Write) -> Result<(), CliError> {
|
||||
let text = std::fs::read_to_string(&a.script).map_err(|e| CliError::Read { path: a.script.clone(), message: e.to_string() })?;
|
||||
let script: Value = serde_json::from_str(&text).map_err(|source| CliError::Script { path: a.script.clone(), source })?;
|
||||
let steps = script.as_array().or_else(|| script.get("steps").and_then(Value::as_array)).ok_or(CliError::ScriptShape)?;
|
||||
let path_field = |field: &'static str| -> Result<Option<&str>, CliError> {
|
||||
match script.get(field) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(Value::String(path)) => Ok(Some(path.as_str())),
|
||||
Some(_) => Err(CliError::ScriptField(field)),
|
||||
}
|
||||
};
|
||||
let input = path_field("open")?.unwrap_or("builtin:material_ball");
|
||||
let output = path_field("save")?;
|
||||
|
||||
let mut h = open(Path::new(input), None)?;
|
||||
let reply = h.batch(steps);
|
||||
print(out, &reply);
|
||||
if let Some(failure) = reply.get("failed").filter(|failure| !failure.is_null()) {
|
||||
return Err(CliError::BatchStopped {
|
||||
index: failure["index"].to_string(),
|
||||
id: failure["id"].as_str().unwrap_or_default().to_string(),
|
||||
message: failure["error"].as_str().unwrap_or_default().to_string(),
|
||||
});
|
||||
}
|
||||
match output {
|
||||
Some(path) => save(&mut h, Path::new(path), err),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
fn bake(a: &BakeArgs, out: &mut dyn Write, err: &mut dyn Write) -> Result<(), CliError> {
|
||||
// `check` has seen to it: a project without -o is saved in place (--in-place), a mesh has -o.
|
||||
let target = a.output.as_deref().unwrap_or(&a.input);
|
||||
let mut p = json!({"ts": "all"});
|
||||
if let Some(r) = a.resolution {
|
||||
p["resolution"] = json!(r);
|
||||
}
|
||||
if !a.maps.is_empty() {
|
||||
p["maps"] = json!(a.maps.iter().map(|m| m.trim()).filter(|m| !m.is_empty()).collect::<Vec<_>>());
|
||||
}
|
||||
let mut h = open(&a.input, None)?;
|
||||
h.command_run("bake.run", p)?;
|
||||
save(&mut h, target, err)?;
|
||||
print(out, &h.inspect()["textureSets"]);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn export(a: &ExportArgs, out: &mut dyn Write, err: &mut dyn Write) -> Result<(), CliError> {
|
||||
let mut p = json!({"dir": unicode(&a.dir)?});
|
||||
for (key, value) in [("preset", &a.preset), ("format", &a.format), ("padding", &a.padding)] {
|
||||
if let Some(v) = value {
|
||||
p[key] = json!(v);
|
||||
}
|
||||
}
|
||||
if let Some(v) = a.size {
|
||||
p["size"] = json!(v);
|
||||
}
|
||||
let mut h = open(&a.input, None)?;
|
||||
let r = h.export(&p)?;
|
||||
for w in r["warnings"].as_array().into_iter().flatten() {
|
||||
outln!(err, "warning: {}", w.as_str().unwrap_or_default());
|
||||
}
|
||||
for f in r["files"].as_array().into_iter().flatten() {
|
||||
outln!(out, "{}", f.as_str().unwrap_or_default());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn render(a: &RenderArgs, err: &mut dyn Write) -> Result<(), CliError> {
|
||||
let options = RenderOptions {
|
||||
view: a.view.clone(),
|
||||
width: a.size.map(|s| s.width),
|
||||
height: a.size.map(|s| s.height),
|
||||
yaw: a.yaw,
|
||||
pitch: a.pitch,
|
||||
samples: a.samples,
|
||||
bounces: a.bounces,
|
||||
cpu: a.cpu,
|
||||
};
|
||||
let mut h = open(&a.input, None)?;
|
||||
if let Some(name) = &a.camera {
|
||||
h.command_run("camera.select", json!({ "name": name }))?;
|
||||
}
|
||||
let t0 = std::time::Instant::now();
|
||||
let r = h.render_png(&options)?;
|
||||
let secs = t0.elapsed().as_secs_f64();
|
||||
std::fs::write(&a.output, &r.png).map_err(|source| CliError::Write { path: a.output.clone(), source })?;
|
||||
outln!(err, "wrote {} ({}x{}, {}, {secs:.2} s)", a.output.display(), r.width, r.height, r.by);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn new(a: &NewArgs, err: &mut dyn Write) -> Result<(), CliError> {
|
||||
if is_project(&a.input) {
|
||||
return Err(CliError::AlreadyProject(a.input.clone()));
|
||||
}
|
||||
let mut h = open(&a.input, a.resolution)?;
|
||||
if a.sample {
|
||||
let bake_res = h.session.doc.project.texture_sets.first().map_or(1024, |t| t.resolution.min(1024));
|
||||
h.command_run("bake.run", json!({"ts": "all", "resolution": bake_res}))?;
|
||||
for ts in 0..h.session.set_count() {
|
||||
h.command_run("textureSet.select", json!({"ts": ts}))?;
|
||||
h.command_run("material.apply", json!({"material": "steel_painted_worn"}))?;
|
||||
}
|
||||
h.command_run("textureSet.select", json!({"ts": 0}))?;
|
||||
}
|
||||
save(&mut h, &a.output, err)
|
||||
}
|
||||
|
||||
/// File access for servers: none without roots, else only below them
|
||||
fn workspace(roots: &RootArgs) -> Result<Filesystem, CliError> {
|
||||
if roots.read_root.is_none() && roots.write_root.is_none() {
|
||||
return Ok(Filesystem::Denied);
|
||||
}
|
||||
Ok(Filesystem::Workspace(AuthorizedWorkspace::new(roots.read_root.as_deref(), roots.write_root.as_deref())?))
|
||||
}
|
||||
|
||||
fn mcp(a: &McpArgs) -> Result<(), CliError> {
|
||||
let server = match a.bridge {
|
||||
Some(port) => TexturecraftMcp::bridge(BridgeClient::new(port, client_token(port, a.token.clone())?)),
|
||||
None => TexturecraftMcp::headless(Headless::new(Headless::default_session()?, workspace(&a.roots)?)),
|
||||
};
|
||||
let rt = tokio::runtime::Builder::new_multi_thread().enable_all().build().map_err(CliError::Serve)?;
|
||||
rt.block_on(server.serve_stdio()).map_err(|e| CliError::Automation(texturecraft_automation::AutomationError::Other(e.to_string())))
|
||||
}
|
||||
|
||||
fn serve(a: &ServeArgs, err: &mut dyn Write) -> Result<(), CliError> {
|
||||
let h = Arc::new(Mutex::new(Headless::new(Headless::default_session()?, workspace(&a.roots)?)));
|
||||
match a.port {
|
||||
None => rpc::serve_lines(&h, std::io::stdin().lock(), std::io::stdout().lock()).map_err(CliError::Serve)?,
|
||||
Some(port) => {
|
||||
// Bind first: a port in use must not replace its server's token file.
|
||||
let listener = rpc::bind_tcp(port)?;
|
||||
let addr = listener.local_addr().map_err(CliError::Serve)?;
|
||||
let (token, file) = server_token(addr.port())?;
|
||||
match file {
|
||||
Some(f) => outln!(err, "texturecraft-cli: serving on {addr}; token in {}", f.display()),
|
||||
None => outln!(err, "texturecraft-cli: serving on {addr}; token from TEXTURECRAFT_CONTROL_TOKEN"),
|
||||
}
|
||||
rpc::serve_listener(listener, h, token)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,452 +1,8 @@
|
||||
//! Headless TextureCraft command line: inspect, script, bake, export and render projects, and
|
||||
//! serve agents over MCP or JSON lines. Never opens a window.
|
||||
//! Headless TextureCraft command line. Never opens a window. See the library crate for the commands.
|
||||
#![forbid(unsafe_code)]
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
use std::path::Path;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_automation::security::{client_token, server_token};
|
||||
use texturecraft_automation::{AuthorizedWorkspace, BridgeClient, Filesystem, Headless, RenderOptions, TexturecraftMcp, rpc};
|
||||
use texturecraft_engine::core::PROJECT_EXT;
|
||||
use texturecraft_engine::formats::{MeshReport, import_mesh, import_mesh_bytes, mesh_report};
|
||||
|
||||
const USAGE: &str = "\
|
||||
texturecraft-cli: headless TextureCraft
|
||||
|
||||
USAGE:
|
||||
texturecraft-cli --version
|
||||
texturecraft-cli info <project.tcraft | mesh file | builtin:<id>>
|
||||
Texture sets, layers, triangles, materials and the UV report, as JSON.
|
||||
texturecraft-cli commands [--filter <text>]
|
||||
List the engine commands (id, label, params).
|
||||
texturecraft-cli run <input> <command-id> [params-json] [-o <out.tcraft>]
|
||||
Run one command and print its JSON result; -o saves the project.
|
||||
texturecraft-cli batch <script.json>
|
||||
Run [{\"id\", \"params\"}, ...] or {\"open\": <input>, \"steps\": [...], \"save\": <out.tcraft>}.
|
||||
texturecraft-cli bake <input> [-o <out.tcraft>] [--resolution <px>] [--maps <id,id,...>]
|
||||
Bake mesh maps for every texture set (a project is saved in place without -o).
|
||||
texturecraft-cli export <input> <dir> [--preset <name>] [--format <ext>] [--padding <mode>] [--size <px>]
|
||||
Export textures (default preset: Document channels + Normal + AO (No Alpha)).
|
||||
texturecraft-cli render <input> <out.png> [--size <W>x<H>] [--view 3d|2d] [--camera <name>] [--yaw <deg>]
|
||||
[--pitch <deg>] [--samples <n>] [--bounces <n>] [--cpu]
|
||||
Render the viewport to PNG (needs a GPU or software adapter); --camera looks through a
|
||||
camera saved in the project (camera.add); --samples path traces it instead (Rendering
|
||||
mode), on the GPU when it has compute shaders, else (or with --cpu) on the CPU.
|
||||
texturecraft-cli new <mesh file | builtin:<id>> <out.tcraft> [--resolution <px>] [--sample]
|
||||
New project; --sample bakes and applies a smart material to every texture set. The
|
||||
sample's mesh maps are baked at the resolution up to 1024 px (most of the file's size),
|
||||
so a 2048 sample project is as large as a 1024 one.
|
||||
texturecraft-cli mcp [--bridge <port>] [--token <token>] [--read-root <dir>] [--write-root <dir>]
|
||||
MCP server on stdio: headless (file access only below the roots), or bridged to
|
||||
`texturecraft --control <port>`. --automation-read-root / --automation-write-root are
|
||||
the same as --read-root / --write-root (mcp and serve).
|
||||
texturecraft-cli serve [--port <port>] [--read-root <dir>] [--write-root <dir>]
|
||||
JSON lines ({\"id\",\"method\",\"params\"}) on stdio, or on 127.0.0.1:<port> with a token.
|
||||
|
||||
<input> is a .tcraft project, a mesh file (.glb .gltf .fbx .dae .usd .usda .usdc .usdz .abc .obj .ply .stl)
|
||||
or builtin:<id> (material_ball, sphere, cube, rounded_cube, cylinder, torus, plane, crate, udim_plane).
|
||||
See docs/control-protocol.md.
|
||||
";
|
||||
|
||||
/// (name, flags taking a value, bare flags)
|
||||
const SUBCOMMANDS: &[(&str, &[&str], &[&str])] = &[
|
||||
("info", &[], &[]),
|
||||
("commands", &["--filter"], &[]),
|
||||
("run", &["-o"], &[]),
|
||||
("batch", &[], &[]),
|
||||
("bake", &["-o", "--resolution", "--maps"], &[]),
|
||||
("export", &["--preset", "--format", "--padding", "--size"], &[]),
|
||||
("render", &["--size", "--view", "--camera", "--yaw", "--pitch", "--samples", "--bounces"], &["--cpu"]),
|
||||
("new", &["--resolution"], &["--sample"]),
|
||||
("mcp", &["--bridge", "--token", "--read-root", "--write-root", "--automation-read-root", "--automation-write-root"], &[]),
|
||||
("serve", &["--port", "--read-root", "--write-root", "--automation-read-root", "--automation-write-root"], &[]),
|
||||
];
|
||||
|
||||
struct Args {
|
||||
pos: Vec<String>,
|
||||
flags: Vec<(String, Option<String>)>,
|
||||
}
|
||||
|
||||
impl Args {
|
||||
fn get(&self, k: &str) -> Option<&str> {
|
||||
self.flags.iter().rev().find(|(f, _)| f == k).and_then(|(_, v)| v.as_deref())
|
||||
}
|
||||
fn has(&self, k: &str) -> bool {
|
||||
self.flags.iter().any(|(f, _)| f == k)
|
||||
}
|
||||
fn num<T: std::str::FromStr>(&self, k: &str) -> Result<Option<T>, String> {
|
||||
self.get(k).map(|v| v.parse().map_err(|_| format!("{k}: `{v}` is not a valid number"))).transpose()
|
||||
}
|
||||
fn pos(&self, n: usize, what: &str) -> Result<&str, String> {
|
||||
self.pos.get(n).map(String::as_str).ok_or_else(|| format!("missing {what}"))
|
||||
}
|
||||
}
|
||||
|
||||
fn parse(values: &[&str], bare: &[&str], args: &[String]) -> Result<Args, String> {
|
||||
let mut a = Args { pos: Vec::new(), flags: Vec::new() };
|
||||
let mut it = args.iter();
|
||||
while let Some(s) = it.next() {
|
||||
let (k, inline) = match s.split_once('=') {
|
||||
Some((k, v)) if k.starts_with("--") => (k, Some(v.to_string())),
|
||||
_ => (s.as_str(), None),
|
||||
};
|
||||
if values.contains(&k) {
|
||||
let v = match inline {
|
||||
Some(v) => v,
|
||||
None => it.next().ok_or_else(|| format!("{k} needs a value"))?.clone(),
|
||||
};
|
||||
a.flags.push((k.to_string(), Some(v)));
|
||||
} else if bare.contains(&k) && inline.is_none() {
|
||||
a.flags.push((k.to_string(), None));
|
||||
} else if k.starts_with('-') && k.len() > 1 && k.parse::<f64>().is_err() {
|
||||
return Err(format!("unknown option `{s}`"));
|
||||
} else {
|
||||
a.pos.push(s.clone());
|
||||
}
|
||||
}
|
||||
Ok(a)
|
||||
}
|
||||
|
||||
fn version() -> String {
|
||||
let sha = env!("TEXTURECRAFT_BUILD_SHA");
|
||||
let short = sha.get(..7).unwrap_or(sha);
|
||||
let date = env!("TEXTURECRAFT_BUILD_DATE");
|
||||
match (short.is_empty(), date.is_empty()) {
|
||||
(true, true) => format!("TextureCraft {}", texturecraft_engine::VERSION),
|
||||
(true, false) => format!("TextureCraft {} ({date})", texturecraft_engine::VERSION),
|
||||
_ => format!("TextureCraft {} ({short} {date})", texturecraft_engine::VERSION),
|
||||
}
|
||||
}
|
||||
|
||||
/// 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<String> = 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}");
|
||||
2
|
||||
}
|
||||
Some("--version" | "-V" | "version") => {
|
||||
println!("{}", version());
|
||||
0
|
||||
}
|
||||
Some("--help" | "-h" | "help") => {
|
||||
print!("{USAGE}");
|
||||
0
|
||||
}
|
||||
Some(cmd) => match SUBCOMMANDS.iter().find(|(n, _, _)| *n == cmd) {
|
||||
None => {
|
||||
eprintln!("texturecraft-cli: unknown command `{cmd}`\n\n{USAGE}");
|
||||
2
|
||||
}
|
||||
Some(_) if args.iter().any(|a| a == "--help" || a == "-h") => {
|
||||
print!("{USAGE}");
|
||||
0
|
||||
}
|
||||
Some((name, values, bare)) => match parse(values, bare, args.get(1..).unwrap_or_default()) {
|
||||
Err(e) => {
|
||||
eprintln!("texturecraft-cli {name}: {e}\n\n{USAGE}");
|
||||
2
|
||||
}
|
||||
Ok(a) => match dispatch(name, &a) {
|
||||
Ok(()) => 0,
|
||||
Err(e) => {
|
||||
eprintln!("texturecraft-cli {name}: error: {e}");
|
||||
1
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
// `args_os`, not `args`: a non-Unicode argument must reach clap, not panic before anything is printed.
|
||||
let code = texturecraft_cli::run(std::env::args_os().skip(1), &mut std::io::stdout(), &mut std::io::stderr());
|
||||
std::process::exit(code);
|
||||
}
|
||||
|
||||
type R = Result<(), String>;
|
||||
|
||||
fn dispatch(name: &str, a: &Args) -> R {
|
||||
match name {
|
||||
"info" => info(a),
|
||||
"commands" => commands(a),
|
||||
"run" => run(a),
|
||||
"batch" => batch(a),
|
||||
"bake" => bake(a),
|
||||
"export" => export(a),
|
||||
"render" => render(a),
|
||||
"new" => new(a),
|
||||
"mcp" => mcp(a),
|
||||
"serve" => serve(a),
|
||||
other => Err(format!("unknown command `{other}`")),
|
||||
}
|
||||
}
|
||||
|
||||
fn s(e: impl std::fmt::Display) -> String {
|
||||
e.to_string()
|
||||
}
|
||||
|
||||
fn print_json(v: &Value) -> R {
|
||||
println!("{}", serde_json::to_string_pretty(v).map_err(s)?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn is_project(path: &str) -> bool {
|
||||
Path::new(path).extension().is_some_and(|e| e.eq_ignore_ascii_case(PROJECT_EXT))
|
||||
}
|
||||
|
||||
/// A trusted local session on `input`: a project, a mesh file or `builtin:<id>`.
|
||||
fn open(input: &str, resolution: Option<u32>) -> Result<Headless, String> {
|
||||
let mut h = Headless::new(Headless::default_session().map_err(s)?, Filesystem::TrustedLocal);
|
||||
match input.strip_prefix("builtin:") {
|
||||
Some(id) => h.command_run("project.new", json!({"mesh": id, "resolution": resolution.unwrap_or(1024), "name": id})).map(|_| ()),
|
||||
None if is_project(input) => h.open(input).map(|_| ()),
|
||||
None => h.import_mesh(input, resolution, None).map(|_| ()),
|
||||
}
|
||||
.map_err(s)?;
|
||||
Ok(h)
|
||||
}
|
||||
|
||||
fn save(h: &mut Headless, out: &str) -> R {
|
||||
let r = h.save(Some(out)).map_err(s)?;
|
||||
eprintln!("saved {}", r["path"].as_str().unwrap_or_default());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn report_json(r: &MeshReport) -> Value {
|
||||
json!({
|
||||
"triangles": r.triangles, "vertices": r.vertices, "materials": r.materials, "uvsGenerated": r.uvs_generated,
|
||||
"uvOutOfRange": r.uv_out_of_range, "overlapRatio": r.overlap_ratio, "zeroAreaUvTriangles": r.zero_area_uv_triangles, "warnings": r.warnings,
|
||||
})
|
||||
}
|
||||
|
||||
fn info(a: &Args) -> R {
|
||||
let file = a.pos(0, "<file>")?;
|
||||
if let Some(id) = file.strip_prefix("builtin:") {
|
||||
let m = texturecraft_engine::geom::primitives::builtin(id).ok_or_else(|| format!("unknown built-in mesh `{id}`"))?;
|
||||
let report = mesh_report(&m);
|
||||
return print_json(&json!({
|
||||
"file": file, "kind": "mesh", "triangles": m.triangle_count(), "vertices": m.vertex_count(),
|
||||
"materials": m.materials, "textureSets": m.materials, "uv": report_json(&report),
|
||||
}));
|
||||
}
|
||||
if !is_project(file) {
|
||||
let m = import_mesh(Path::new(file)).map_err(|e| format!("cannot read {file}: {e}"))?;
|
||||
return print_json(&json!({
|
||||
"file": file, "kind": "mesh", "triangles": m.mesh.triangle_count(), "vertices": m.mesh.vertex_count(),
|
||||
"materials": m.mesh.materials, "textureSets": m.mesh.materials, "uv": report_json(&m.report),
|
||||
}));
|
||||
}
|
||||
let h = open(file, None)?;
|
||||
let mut v = h.inspect();
|
||||
v["file"] = json!(file);
|
||||
v["kind"] = json!("project");
|
||||
// The embedded mesh is re-imported for its UV report (built-in meshes have none).
|
||||
v["uv"] = match &h.session.mesh_source {
|
||||
Some((ext, bytes)) => import_mesh_bytes(&format!("mesh.{ext}"), bytes).map(|m| report_json(&m.report)).map_err(s)?,
|
||||
None => Value::Null,
|
||||
};
|
||||
print_json(&v)
|
||||
}
|
||||
|
||||
fn commands(a: &Args) -> R {
|
||||
let h = open("builtin:cube", Some(128))?;
|
||||
for c in h.command_list(a.get("--filter")).as_array().into_iter().flatten() {
|
||||
let f = |k: &str| c.get(k).and_then(Value::as_str).unwrap_or_default().to_string();
|
||||
println!("{:<28} {:<36} {}", f("id"), f("label"), f("params"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn run(a: &Args) -> R {
|
||||
let (input, id) = (a.pos(0, "<input>")?, a.pos(1, "<command-id>")?);
|
||||
let params: Value = match a.pos.get(2) {
|
||||
Some(j) => serde_json::from_str(j).map_err(|e| format!("params are not JSON: {e}"))?,
|
||||
None => json!({}),
|
||||
};
|
||||
let mut h = open(input, None)?;
|
||||
print_json(&h.command_run(id, params).map_err(s)?)?;
|
||||
match a.get("-o") {
|
||||
Some(out) => save(&mut h, out),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
fn batch(args: &Args) -> R {
|
||||
let path = args.pos(0, "<script.json>")?;
|
||||
let script: Value = {
|
||||
let script_text = std::fs::read_to_string(path).map_err(|err| format!("cannot read {path}: {err}"))?;
|
||||
serde_json::from_str(&script_text).map_err(|err| format!("{path} is not JSON: {err}"))?
|
||||
};
|
||||
|
||||
let steps =
|
||||
script.as_array().or_else(|| script.get("steps").and_then(Value::as_array)).ok_or("the script must be a list of steps or {\"steps\": [...]}")?;
|
||||
let path_field = |field: &str| -> Result<Option<&str>, String> {
|
||||
match script.get(field) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(Value::String(path)) => Ok(Some(path.as_str())),
|
||||
Some(_) => Err(format!("the script's `{field}` field must be a string")),
|
||||
}
|
||||
};
|
||||
let input = path_field("open")?.unwrap_or("builtin:material_ball");
|
||||
let output = path_field("save")?;
|
||||
|
||||
let mut headless = open(input, None)?;
|
||||
let reply = headless.batch(steps);
|
||||
print_json(&reply)?;
|
||||
if let Some(failure) = reply.get("failed").filter(|failure| !failure.is_null()) {
|
||||
return Err(format!(
|
||||
"step {} (`{}`) failed: {}",
|
||||
failure["index"],
|
||||
failure["id"].as_str().unwrap_or_default(),
|
||||
failure["error"].as_str().unwrap_or_default()
|
||||
));
|
||||
}
|
||||
|
||||
match output {
|
||||
Some(output_path) => save(&mut headless, output_path),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
fn bake(a: &Args) -> R {
|
||||
let input = a.pos(0, "<input>")?;
|
||||
let out = a.get("-o").or(is_project(input).then_some(input)).ok_or("give -o <out.tcraft> to save the baked project")?;
|
||||
let mut p = json!({"ts": "all"});
|
||||
if let Some(r) = a.num::<u32>("--resolution")? {
|
||||
p["resolution"] = json!(r);
|
||||
}
|
||||
if let Some(m) = a.get("--maps") {
|
||||
p["maps"] = json!(m.split(',').map(str::trim).filter(|m| !m.is_empty()).collect::<Vec<_>>());
|
||||
}
|
||||
let mut h = open(input, None)?;
|
||||
h.command_run("bake.run", p).map_err(s)?;
|
||||
save(&mut h, out)?;
|
||||
print_json(&h.inspect()["textureSets"])
|
||||
}
|
||||
|
||||
fn export(a: &Args) -> R {
|
||||
let (input, dir) = (a.pos(0, "<input>")?, a.pos(1, "<dir>")?);
|
||||
let mut p = json!({"dir": dir});
|
||||
for k in ["preset", "format", "padding"] {
|
||||
if let Some(v) = a.get(&format!("--{k}")) {
|
||||
p[k] = json!(v);
|
||||
}
|
||||
}
|
||||
if let Some(v) = a.num::<u32>("--size")? {
|
||||
p["size"] = json!(v);
|
||||
}
|
||||
let mut h = open(input, None)?;
|
||||
let r = h.export(&p).map_err(s)?;
|
||||
for w in r["warnings"].as_array().into_iter().flatten() {
|
||||
eprintln!("warning: {}", w.as_str().unwrap_or_default());
|
||||
}
|
||||
for f in r["files"].as_array().into_iter().flatten() {
|
||||
println!("{}", f.as_str().unwrap_or_default());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn render(a: &Args) -> R {
|
||||
let (input, out) = (a.pos(0, "<input>")?, a.pos(1, "<out.png>")?);
|
||||
let (width, height) = match a.get("--size") {
|
||||
Some(sz) => {
|
||||
let (w, h) = sz.split_once(['x', 'X']).ok_or("--size must be <W>x<H>, e.g. 1280x800")?;
|
||||
(Some(w.parse().map_err(|_| "bad --size width")?), Some(h.parse().map_err(|_| "bad --size height")?))
|
||||
}
|
||||
None => (None, None),
|
||||
};
|
||||
let o = RenderOptions {
|
||||
view: a.get("--view").map(str::to_string),
|
||||
width,
|
||||
height,
|
||||
yaw: a.num("--yaw")?,
|
||||
pitch: a.num("--pitch")?,
|
||||
samples: a.num("--samples")?,
|
||||
bounces: a.num("--bounces")?,
|
||||
cpu: a.has("--cpu"),
|
||||
};
|
||||
let mut h = open(input, None)?;
|
||||
if let Some(name) = a.get("--camera") {
|
||||
h.command_run("camera.select", json!({ "name": name })).map_err(s)?;
|
||||
}
|
||||
let t0 = std::time::Instant::now();
|
||||
let r = h.render_png(&o).map_err(s)?;
|
||||
let secs = t0.elapsed().as_secs_f64();
|
||||
std::fs::write(out, &r.png).map_err(|e| format!("cannot write {out}: {e}"))?;
|
||||
eprintln!("wrote {out} ({}x{}, {}, {secs:.2} s)", r.width, r.height, r.by);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn new(a: &Args) -> R {
|
||||
let (input, out) = (a.pos(0, "<mesh | builtin:id>")?, a.pos(1, "<out.tcraft>")?);
|
||||
if is_project(input) {
|
||||
return Err(format!("{input} is already a project"));
|
||||
}
|
||||
let res = a.num::<u32>("--resolution")?;
|
||||
let mut h = open(input, res)?;
|
||||
if a.has("--sample") {
|
||||
let bake_res = h.session.doc.project.texture_sets.first().map_or(1024, |t| t.resolution.min(1024));
|
||||
h.command_run("bake.run", json!({"ts": "all", "resolution": bake_res})).map_err(s)?;
|
||||
for ts in 0..h.session.set_count() {
|
||||
h.command_run("textureSet.select", json!({"ts": ts})).map_err(s)?;
|
||||
h.command_run("material.apply", json!({"material": "steel_painted_worn"})).map_err(s)?;
|
||||
}
|
||||
h.command_run("textureSet.select", json!({"ts": 0})).map_err(s)?;
|
||||
}
|
||||
save(&mut h, out)
|
||||
}
|
||||
|
||||
fn workspace(a: &Args) -> Result<Filesystem, String> {
|
||||
// `--automation-*-root` is the spelling the other crafting apps use.
|
||||
let root = |k: &str| a.get(&format!("--automation-{k}")).or_else(|| a.get(&format!("--{k}"))).map(Path::new);
|
||||
let (r, w) = (root("read-root"), root("write-root"));
|
||||
if r.is_none() && w.is_none() {
|
||||
return Ok(Filesystem::Denied);
|
||||
}
|
||||
Ok(Filesystem::Workspace(AuthorizedWorkspace::new(r, w).map_err(s)?))
|
||||
}
|
||||
|
||||
fn port_of(v: &str) -> Result<u16, String> {
|
||||
let p = v.strip_prefix("127.0.0.1:").or_else(|| v.strip_prefix("localhost:")).unwrap_or(v);
|
||||
p.parse::<u16>().ok().filter(|p| *p != 0).ok_or_else(|| format!("`{v}` is not a loopback port (1-65535)"))
|
||||
}
|
||||
|
||||
fn mcp(a: &Args) -> R {
|
||||
let server = match a.get("--bridge") {
|
||||
Some(b) => {
|
||||
let port = port_of(b)?;
|
||||
TexturecraftMcp::bridge(BridgeClient::new(port, client_token(port, a.get("--token").map(str::to_string)).map_err(s)?))
|
||||
}
|
||||
None => TexturecraftMcp::headless(Headless::new(Headless::default_session().map_err(s)?, workspace(a)?)),
|
||||
};
|
||||
let rt = tokio::runtime::Builder::new_multi_thread().enable_all().build().map_err(s)?;
|
||||
rt.block_on(server.serve_stdio()).map_err(s)
|
||||
}
|
||||
|
||||
fn serve(a: &Args) -> R {
|
||||
let h = Arc::new(Mutex::new(Headless::new(Headless::default_session().map_err(s)?, workspace(a)?)));
|
||||
match a.get("--port") {
|
||||
None => rpc::serve_lines(&h, std::io::stdin().lock(), std::io::stdout().lock()).map_err(s),
|
||||
Some(p) => {
|
||||
// Bind first: a port in use must not replace its server's token file, and port 0's
|
||||
// token file is named after the port actually picked.
|
||||
let listener = rpc::bind_tcp(port_of(p)?).map_err(s)?;
|
||||
let addr = listener.local_addr().map_err(s)?;
|
||||
let (token, file) = server_token(addr.port()).map_err(s)?;
|
||||
match file {
|
||||
Some(f) => eprintln!("texturecraft-cli: serving on {addr}; token in {}", f.display()),
|
||||
None => eprintln!("texturecraft-cli: serving on {addr}; token from TEXTURECRAFT_CONTROL_TOKEN"),
|
||||
}
|
||||
rpc::serve_listener(listener, h, token).map_err(s)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -44,9 +44,9 @@ fn p(path: &Path) -> &str {
|
||||
#[test]
|
||||
fn version_and_usage_errors() {
|
||||
let v = ok(&["--version"]);
|
||||
assert!(v.starts_with("TextureCraft "), "{v}");
|
||||
assert!(v.starts_with("texturecraft-cli "), "{v}");
|
||||
assert_eq!(v.lines().count(), 1);
|
||||
assert!(ok(&["--help"]).contains("texturecraft-cli mcp"));
|
||||
assert!(ok(&["--help"]).contains("Usage: texturecraft-cli <COMMAND>"));
|
||||
assert_eq!(cli(&[]).status.code(), Some(2));
|
||||
assert_eq!(cli(&["frobnicate"]).status.code(), Some(2));
|
||||
assert_eq!(cli(&["info", "--bogus"]).status.code(), Some(2));
|
||||
@@ -54,8 +54,8 @@ fn version_and_usage_errors() {
|
||||
assert_eq!(o.status.code(), Some(1));
|
||||
assert!(String::from_utf8_lossy(&o.stderr).contains("error"));
|
||||
assert_eq!(cli(&["run", "builtin:nope", "layer.add.fill"]).status.code(), Some(1));
|
||||
assert_eq!(cli(&["run", "builtin:cube", "layer.add.fill", "{not json"]).status.code(), Some(1));
|
||||
assert_eq!(cli(&["render", "builtin:cube", "x.png", "--size", "big"]).status.code(), Some(1));
|
||||
assert_eq!(cli(&["run", "builtin:cube", "layer.add.fill", "{not json"]).status.code(), Some(2));
|
||||
assert_eq!(cli(&["render", "builtin:cube", "x.png", "--size", "big"]).status.code(), Some(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -73,7 +73,7 @@ fn new_info_run_bake_export_batch() {
|
||||
assert!(r["layer"].is_u64(), "{r}");
|
||||
assert_eq!(json(&["info", p(&b)])["layers"][0]["kind"], "fill");
|
||||
|
||||
ok(&["bake", p(&b), "--resolution", "128", "--maps", "ambientOcclusion,curvature"]);
|
||||
ok(&["bake", p(&b), "--resolution", "128", "--maps", "ambientOcclusion,curvature", "--in-place"]);
|
||||
let maps = json(&["info", p(&b)])["textureSets"][0]["baked"]["maps"].clone();
|
||||
assert_eq!(maps.as_array().unwrap().len(), 2, "{maps}");
|
||||
|
||||
@@ -184,6 +184,34 @@ fn render_writes_a_png() {
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
/// Without a GPU, the viewport render's error says what still works, and that does work. A backend
|
||||
/// this platform lacks stands in for a machine without a GPU: the CLI's wgpu instance reads
|
||||
/// `WGPU_BACKEND`.
|
||||
#[test]
|
||||
fn render_without_a_gpu_points_to_path_tracing() {
|
||||
let d = tmp("no-gpu");
|
||||
let out = d.join("cube.png");
|
||||
let absent = if cfg!(target_os = "macos") { "dx12" } else { "metal" };
|
||||
let render = |extra: &[&str]| {
|
||||
Command::new(cli_binary())
|
||||
.env("WGPU_BACKEND", absent)
|
||||
.env_remove("WGPU_ADAPTER_NAME")
|
||||
.env_remove("WGPU_POWER_PREF")
|
||||
.args(["render", "builtin:cube", p(&out), "--size", "64x64"])
|
||||
.args(extra)
|
||||
.output()
|
||||
.unwrap()
|
||||
};
|
||||
let o = render(&[]);
|
||||
let err = String::from_utf8_lossy(&o.stderr);
|
||||
assert_eq!(o.status.code(), Some(1), "{err}");
|
||||
assert!(err.contains("cannot render") && err.contains("path tracing (`samples`) needs no GPU"), "{err}");
|
||||
let o = render(&["--samples", "2"]);
|
||||
assert!(o.status.success(), "{}", String::from_utf8_lossy(&o.stderr));
|
||||
assert_eq!(image::open(&out).unwrap().width(), 64);
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_traced_render_needs_no_gpu() {
|
||||
let d = tmp("trace");
|
||||
@@ -202,10 +230,10 @@ fn path_traced_render_needs_no_gpu() {
|
||||
// --camera looks through a camera saved in the project; an unknown name is an error.
|
||||
let proj = d.join("cams.tcraft");
|
||||
ok(&["run", "builtin:cube", "camera.set", r#"{"yaw": 80, "distance": 9}"#, "-o", p(&proj)]);
|
||||
ok(&["run", p(&proj), "camera.add", r#"{"name": "Side"}"#, "-o", p(&proj)]);
|
||||
ok(&["run", p(&proj), "camera.add", r#"{"name": "Side"}"#, "-o", p(&proj), "--in-place"]);
|
||||
ok(&["render", p(&proj), p(&out), "--size", "48x32", "--camera", "Side", "--samples", "2", "--cpu"]);
|
||||
assert_eq!(cli(&["render", p(&proj), p(&out), "--camera", "Nope", "--samples", "2", "--cpu"]).status.code(), Some(1));
|
||||
assert_eq!(cli(&["render", "builtin:cube", p(&out), "--samples", "0"]).status.code(), Some(1));
|
||||
assert_eq!(cli(&["render", "builtin:cube", p(&out), "--samples", "0"]).status.code(), Some(2));
|
||||
assert_eq!(cli(&["render", "builtin:cube", p(&out), "--samples", "4", "--view", "2d"]).status.code(), Some(1));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
//! RFC-0018 rule 2.7: help, versions, usage errors with exit 2 on stderr, and nothing written
|
||||
//! before the arguments are checked.
|
||||
|
||||
use std::ffi::OsString;
|
||||
|
||||
use crate::{argv, invoke, project, workdir};
|
||||
|
||||
const SUBCOMMANDS: [&str; 10] = ["info", "commands", "run", "batch", "bake", "export", "render", "new", "mcp", "serve"];
|
||||
|
||||
/// The shortest valid command line of each subcommand.
|
||||
fn minimal(sub: &str) -> Vec<&str> {
|
||||
match sub {
|
||||
"info" => vec!["info", "builtin:cube"],
|
||||
"run" => vec!["run", "builtin:cube", "layer.add.fill"],
|
||||
"batch" => vec!["batch", "s.json"],
|
||||
"bake" => vec!["bake", "builtin:cube", "-o", "o.tcraft"],
|
||||
"export" => vec!["export", "builtin:cube", "dir"],
|
||||
"render" => vec!["render", "builtin:cube", "o.png"],
|
||||
"new" => vec!["new", "builtin:cube", "o.tcraft"],
|
||||
other => vec![other],
|
||||
}
|
||||
}
|
||||
|
||||
fn usage_error(args: &[&str]) -> String {
|
||||
let got = invoke(args.iter().copied());
|
||||
assert_eq!(got.code, 2, "{args:?}: {}", got.err);
|
||||
assert_eq!(got.out, "", "{args:?} wrote to stdout");
|
||||
assert!(got.err.starts_with("error: "), "{args:?}: {}", got.err);
|
||||
got.err
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn help_and_the_version_go_to_stdout_with_exit_0() {
|
||||
for args in [&["--help"][..], &["-h"], &["help"], &["--version"], &["-V"]] {
|
||||
let got = invoke(args.iter().copied());
|
||||
assert_eq!((got.code, got.err.as_str()), (0, ""), "{args:?}");
|
||||
assert!(got.out.contains("texturecraft-cli"), "{args:?}: {}", got.out);
|
||||
}
|
||||
let help = invoke(["--help"]).out;
|
||||
assert!(help.contains("Exit status:") && help.contains("128 + the signal number"), "{help}");
|
||||
for sub in SUBCOMMANDS {
|
||||
for flag in ["--help", "-h"] {
|
||||
let got = invoke([sub, flag]);
|
||||
assert_eq!((got.code, got.err.as_str()), (0, ""), "{sub} {flag}");
|
||||
assert!(got.out.contains(&format!("Usage: texturecraft-cli {sub}")), "{sub}: {}", got.out);
|
||||
}
|
||||
assert_eq!(invoke(["help", sub]).out, invoke([sub, "--help"]).out, "{sub}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_subcommand_takes_the_version_and_there_is_no_version_subcommand() {
|
||||
let top = invoke(["--version"]).out;
|
||||
let want = top.strip_prefix("texturecraft-cli ").unwrap().trim_end().to_string();
|
||||
assert!(want.starts_with(texturecraft_engine::VERSION), "{want}");
|
||||
for sub in SUBCOMMANDS {
|
||||
for flag in ["--version", "-V"] {
|
||||
let got = invoke([sub, flag]);
|
||||
assert_eq!((got.code, got.out.as_str(), got.err.as_str()), (0, format!("texturecraft-cli-{sub} {want}\n").as_str(), ""), "{sub} {flag}");
|
||||
}
|
||||
}
|
||||
usage_error(&["version"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_arguments_is_a_usage_error_that_prints_the_help_on_stderr() {
|
||||
let got = invoke(Vec::<OsString>::new());
|
||||
assert_eq!((got.code, got.out.as_str()), (2, ""));
|
||||
assert!(got.err.contains("Usage: texturecraft-cli <COMMAND>"), "{}", got.err);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_flag_or_subcommand_is_refused_by_every_subcommand() {
|
||||
for sub in SUBCOMMANDS {
|
||||
let mut args = minimal(sub);
|
||||
args.push("--fromat");
|
||||
let message = usage_error(&args);
|
||||
assert!(message.contains("--fromat"), "{sub}: {message}");
|
||||
}
|
||||
usage_error(&["rendre"]);
|
||||
usage_error(&["--fromat"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_flag_given_twice_is_refused() {
|
||||
usage_error(&["new", "builtin:cube", "o.tcraft", "--resolution", "8", "--resolution", "9"]);
|
||||
usage_error(&["bake", "builtin:cube", "-o", "a.tcraft", "-o", "b.tcraft"]);
|
||||
usage_error(&["render", "builtin:cube", "o.png", "--samples", "2", "--cpu", "--cpu"]);
|
||||
usage_error(&["mcp", "--read-root", "a", "--automation-read-root", "b"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_values_conflicts_and_missing_arguments_are_refused_before_any_file_is_written() {
|
||||
let dir = workdir("refused");
|
||||
let out = dir.join("never");
|
||||
let o = out.to_str().unwrap();
|
||||
let project_file = dir.join("p.tcraft");
|
||||
let p = project_file.to_str().unwrap();
|
||||
for (args, expect) in [
|
||||
(vec!["new", "builtin:cube", o, "--resolution", "0"], "--resolution"),
|
||||
(vec!["new", "builtin:cube", o, "--resolution", "big"], "--resolution"),
|
||||
(vec!["bake", "builtin:cube", "-o", o, "--resolution", "-1"], "-1"),
|
||||
(vec!["bake", "builtin:cube"], "give -o"),
|
||||
(vec!["bake", p], "--in-place"),
|
||||
(vec!["bake", "builtin:cube", "--in-place"], "-o"),
|
||||
(vec!["export", "builtin:cube", o, "--size", "0"], "--size"),
|
||||
(vec!["export", "builtin:cube"], "required"),
|
||||
(vec!["run", "builtin:cube", "layer.add.fill", "{not json"], "not JSON"),
|
||||
(vec!["run", "builtin:cube", "layer.add.fill", "{}", "--in-place"], "--output"),
|
||||
(vec!["render", "builtin:cube", o, "--size", "big"], "<W>x<H>"),
|
||||
(vec!["render", "builtin:cube", o, "--size", "0x5"], "<W>x<H>"),
|
||||
(vec!["render", "builtin:cube", o, "--view", "4d"], "--view"),
|
||||
(vec!["render", "builtin:cube", o, "--yaw", "NaN"], "--yaw"),
|
||||
(vec!["render", "builtin:cube", o, "--samples", "0"], "--samples"),
|
||||
(vec!["render", "builtin:cube", o, "--cpu"], "--samples"),
|
||||
(vec!["render", "builtin:cube", o, "--bounces", "3"], "--samples"),
|
||||
(vec!["mcp", "--token", "abcdefghijklmnop"], "--bridge"),
|
||||
(vec!["mcp", "--bridge", "9878", "--read-root", o], "headless server"),
|
||||
(vec!["mcp", "--bridge", "99999"], "--bridge"),
|
||||
(vec!["mcp", "--bridge", "0"], "--bridge"),
|
||||
(vec!["serve", "--port", "http"], "--port"),
|
||||
] {
|
||||
let message = usage_error(&args);
|
||||
assert!(message.contains(expect), "{args:?}: {message}");
|
||||
}
|
||||
assert!(!out.exists());
|
||||
assert!(std::fs::read_dir(&dir).unwrap().next().is_none());
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loopback_ports_take_the_host_prefix_and_a_dashed_name_follows_a_double_dash() {
|
||||
// `--bridge 127.0.0.1:PORT` and `localhost:PORT` are still ports: the failure is the missing token.
|
||||
for bridge in ["127.0.0.1:9", "localhost:9"] {
|
||||
let got = invoke(["mcp", "--bridge", bridge, "--token", "short"]);
|
||||
assert_eq!(got.code, 1, "{bridge}: {}", got.err);
|
||||
}
|
||||
let got = invoke(["info", "--", "-odd.tcraft"]);
|
||||
assert_eq!(got.code, 1);
|
||||
assert!(got.err.contains("-odd.tcraft"), "{}", got.err);
|
||||
usage_error(&["render", "builtin:cube", "o.png", "--camera", "--cpu"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn info_and_commands_print_what_a_program_reads() {
|
||||
let got = invoke(["info", "builtin:cube"]);
|
||||
assert_eq!((got.code, got.err.as_str()), (0, ""));
|
||||
assert_eq!(serde_json::from_str::<serde_json::Value>(&got.out).unwrap()["kind"], "mesh");
|
||||
let table = invoke(["commands", "--filter", "layer.add"]);
|
||||
assert_eq!((table.code, table.err.as_str()), (0, ""));
|
||||
assert!(table.out.lines().all(|l| l.starts_with("layer.add") || l.trim().is_empty()) && !table.out.is_empty(), "{}", table.out);
|
||||
let json = invoke(["commands", "--filter", "layer.add", "--json"]);
|
||||
assert_eq!(json.code, 0);
|
||||
let list: serde_json::Value = serde_json::from_str(&json.out).unwrap();
|
||||
assert!(list.as_array().is_some_and(|l| !l.is_empty()), "{}", json.out);
|
||||
let got = invoke(["info", "builtin:bogus"]);
|
||||
assert_eq!((got.code, got.out.as_str()), (1, ""));
|
||||
assert!(got.err.starts_with("error: unknown built-in mesh `bogus`"), "{}", got.err);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_run_bake_and_export_through_files() {
|
||||
let dir = workdir("files");
|
||||
let a = project(&dir, "a.tcraft");
|
||||
let b = dir.join("b.tcraft");
|
||||
let got = invoke(argv(&[&"run", &a, &"layer.add.fill", &r#"{"color":[1,0,0]}"#, &"-o", &b]));
|
||||
assert_eq!(got.code, 0, "{}", got.err);
|
||||
assert!(got.err.starts_with("saved "), "{}", got.err);
|
||||
assert!(b.is_file());
|
||||
let got = invoke(argv(&[&"bake", &b, &"--resolution", &"128", &"--maps", &"ambientOcclusion", &"--in-place"]));
|
||||
assert_eq!(got.code, 0, "{}", got.err);
|
||||
let textures = dir.join("tex");
|
||||
let got = invoke(argv(&[&"export", &b, &textures, &"--preset", &"glTF PBR Metal Roughness", &"--size", &"128"]));
|
||||
assert_eq!(got.code, 0, "{}", got.err);
|
||||
assert!(got.out.lines().count() >= 3, "{}", got.out);
|
||||
let got = invoke(argv(&[&"new", &"builtin:cube", &a]));
|
||||
assert_eq!(got.code, 0, "{}", got.err);
|
||||
let got = invoke(argv(&[&"new", &a, &dir.join("again.tcraft")]));
|
||||
assert_eq!((got.code, got.out.as_str()), (1, ""));
|
||||
assert!(got.err.contains("is already a project"), "{}", got.err);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_output_that_would_replace_an_input_is_refused_without_in_place() {
|
||||
let dir = workdir("replace");
|
||||
let source = project(&dir, "a.tcraft");
|
||||
let a = source.to_str().unwrap();
|
||||
let before = std::fs::read(&source).unwrap();
|
||||
let again = dir.join(".").join("a.tcraft");
|
||||
let again = again.to_str().unwrap();
|
||||
for args in [
|
||||
vec!["run", a, "layer.add.fill", "{}", "-o", a],
|
||||
vec!["run", a, "layer.add.fill", "{}", "-o", again],
|
||||
vec!["bake", a, "-o", a],
|
||||
vec!["bake", a],
|
||||
vec!["render", a, again],
|
||||
vec!["new", a, a],
|
||||
] {
|
||||
let message = usage_error(&args);
|
||||
assert!(message.contains("--in-place") || message.contains("would replace"), "{args:?}: {message}");
|
||||
}
|
||||
assert_eq!(std::fs::read(&source).unwrap(), before, "a refused command changes nothing");
|
||||
// `--in-place` lets only a project be replaced, and only by itself.
|
||||
let got = invoke(["run", a, "layer.add.fill", "{}", "-o", a, "--in-place"]);
|
||||
assert_eq!(got.code, 0, "{}", got.err);
|
||||
let got = invoke(["bake", a, "--in-place", "--resolution", "128", "--maps", "ambientOcclusion"]);
|
||||
assert_eq!(got.code, 0, "{}", got.err);
|
||||
let elsewhere = dir.join("b.tcraft");
|
||||
assert!(usage_error(&["run", a, "layer.add.fill", "{}", "-o", elsewhere.to_str().unwrap(), "--in-place"]).contains("--in-place"));
|
||||
assert!(usage_error(&["bake", a, "-o", elsewhere.to_str().unwrap(), "--in-place"]).contains("--in-place"));
|
||||
assert!(!elsewhere.exists());
|
||||
// Headless::save appends .tcraft, so `-o scene` would replace scene.tcraft.
|
||||
let unsuffixed = dir.join("a");
|
||||
let unsuffixed = unsuffixed.to_str().unwrap();
|
||||
let after_in_place = std::fs::read(&source).unwrap();
|
||||
let message = usage_error(&["run", a, "layer.add.fill", "{}", "-o", unsuffixed]);
|
||||
assert!(message.contains("would replace") || message.contains("--in-place"), "{message}");
|
||||
assert_eq!(std::fs::read(&source).unwrap(), after_in_place, "an unsuffixed -o changes nothing");
|
||||
let got = invoke(["run", a, "layer.add.fill", "{}", "-o", unsuffixed, "--in-place"]);
|
||||
assert_eq!(got.code, 0, "{}", got.err);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_runs_a_script_and_a_failing_step_fails_the_command() {
|
||||
let dir = workdir("batch");
|
||||
let good = dir.join("good.json");
|
||||
std::fs::write(&good, r#"[{"id": "layer.add.paint", "params": {"name": "Scripted"}}]"#).unwrap();
|
||||
let got = invoke(argv(&[&"batch", &good]));
|
||||
assert_eq!((got.code, got.err.as_str()), (0, ""), "{}", got.out);
|
||||
let bad = dir.join("bad.json");
|
||||
std::fs::write(&bad, r#"[{"id": "layer.add.paint"}, {"id": "no.such.command"}]"#).unwrap();
|
||||
let got = invoke(argv(&[&"batch", &bad]));
|
||||
assert_eq!(got.code, 1);
|
||||
assert!(got.err.starts_with("error: step 1 (`no.such.command`) failed: "), "{}", got.err);
|
||||
for (body, expect) in [("[", "is not JSON"), ("{}", "list of steps"), (r#"{"steps": [], "open": false}"#, "`open` field must be a string")] {
|
||||
let script = dir.join("odd.json");
|
||||
std::fs::write(&script, body).unwrap();
|
||||
let got = invoke(argv(&[&"batch", &script]));
|
||||
assert_eq!(got.code, 1, "{body}");
|
||||
assert!(got.err.contains(expect), "{body}: {}", got.err);
|
||||
}
|
||||
let got = invoke(argv(&[&"batch", &dir.join("missing.json")]));
|
||||
assert_eq!(got.code, 1);
|
||||
assert!(got.err.contains("missing.json"), "{}", got.err);
|
||||
// A script that saves over the project it opened needs --in-place, and must not have run.
|
||||
let opened = project(&dir, "opened.tcraft");
|
||||
let before = std::fs::read(&opened).unwrap();
|
||||
let overwrite = dir.join("overwrite.json");
|
||||
std::fs::write(
|
||||
&overwrite,
|
||||
serde_json::json!({
|
||||
"open": opened,
|
||||
"save": opened,
|
||||
"steps": [{"id": "layer.add.paint", "params": {"name": "Batch"}}]
|
||||
})
|
||||
.to_string(),
|
||||
)
|
||||
.unwrap();
|
||||
let message = usage_error(&["batch", overwrite.to_str().unwrap()]);
|
||||
assert!(message.contains("--in-place") || message.contains("would replace"), "{message}");
|
||||
assert_eq!(std::fs::read(&opened).unwrap(), before);
|
||||
let got = invoke(argv(&[&"batch", &overwrite, &"--in-place"]));
|
||||
assert_eq!(got.code, 0, "{}", got.err);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_command_exits_1_with_the_message_on_stderr() {
|
||||
let got = invoke(["run", "builtin:cube", "no.such.command"]);
|
||||
assert_eq!((got.code, got.out.as_str()), (1, ""));
|
||||
assert!(got.err.starts_with("error: "), "{}", got.err);
|
||||
let got = invoke(["info", "missing.tcraft"]);
|
||||
assert_eq!(got.code, 1);
|
||||
assert!(got.err.starts_with("error: ") && got.err.contains("missing.tcraft"), "{}", got.err);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_desktop_launch_options_are_refused_before_any_subcommand() {
|
||||
for args in
|
||||
[vec!["--launch-profile", "nightly-v1", "--version"], vec!["--profile-root=/tmp/p", "--version"], vec!["info", "builtin:cube", "--launch-profile=x"]]
|
||||
{
|
||||
let message = usage_error(&args);
|
||||
assert!(message.contains("desktop launch option"), "{args:?}: {message}");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_path_that_is_not_valid_unicode_is_named_in_the_error() {
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
let dir = workdir("non-unicode");
|
||||
// The engine's commands take their paths as JSON text: the command says so and names the file.
|
||||
let input = dir.join(OsString::from_vec(b"in-\xff.tcraft".to_vec()));
|
||||
let got = invoke(argv(&[&"info", &input]));
|
||||
assert_eq!(got.code, 1);
|
||||
assert!(got.err.contains("the path is not valid Unicode") && got.err.contains("in-"), "{}", got.err);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_closed_stdout_is_not_an_error() {
|
||||
struct Closed;
|
||||
impl std::io::Write for Closed {
|
||||
fn write(&mut self, _: &[u8]) -> std::io::Result<usize> {
|
||||
Err(std::io::ErrorKind::BrokenPipe.into())
|
||||
}
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
let mut err = Vec::new();
|
||||
assert_eq!(texturecraft_cli::run(["commands"], &mut Closed, &mut err), 0);
|
||||
assert_eq!(texturecraft_cli::run(["--help"], &mut Closed, &mut err), 0);
|
||||
assert!(err.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn headless_mcp_requires_both_roots() {
|
||||
for args in [
|
||||
vec!["mcp"],
|
||||
vec!["mcp", "--read-root", "."],
|
||||
vec!["mcp", "--write-root", "."],
|
||||
vec!["mcp", "--automation-read-root", "."],
|
||||
vec!["mcp", "--automation-write-root", "."],
|
||||
] {
|
||||
let message = usage_error(&args);
|
||||
assert!(message.contains("--read-root") && message.contains("--write-root"), "{args:?}: {message}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
//! Integration tests, built as one test binary: each file is a module. They call `run` in-process,
|
||||
//! except where a test needs the real binary (a protocol on stdio, the environment).
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
mod cli;
|
||||
mod man_and_completions;
|
||||
mod protocol;
|
||||
|
||||
use std::ffi::{OsStr, OsString};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// What `run` returned and wrote.
|
||||
pub struct Outcome {
|
||||
pub code: i32,
|
||||
pub out: String,
|
||||
pub err: String,
|
||||
}
|
||||
|
||||
pub fn invoke<I, T>(args: I) -> Outcome
|
||||
where
|
||||
I: IntoIterator<Item = T>,
|
||||
T: Into<OsString>,
|
||||
{
|
||||
let (mut out, mut err) = (Vec::new(), Vec::new());
|
||||
let code = texturecraft_cli::run(args, &mut out, &mut err);
|
||||
Outcome { code, out: String::from_utf8_lossy(&out).into_owned(), err: String::from_utf8_lossy(&err).into_owned() }
|
||||
}
|
||||
|
||||
/// A new, empty folder for one test.
|
||||
pub fn workdir(name: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("texturecraft-cli-{}-{name}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
/// A small project made by `new`.
|
||||
pub fn project(dir: &Path, name: &str) -> PathBuf {
|
||||
let path = dir.join(name);
|
||||
let made = invoke(argv(&[&"new", &"builtin:cube", &path, &"--resolution", &"128"]));
|
||||
assert_eq!(made.code, 0, "{}", made.err);
|
||||
path
|
||||
}
|
||||
|
||||
/// An argument vector from parts of different types (strings, paths).
|
||||
pub fn argv(parts: &[&dyn AsRef<OsStr>]) -> Vec<OsString> {
|
||||
parts.iter().map(|p| p.as_ref().to_os_string()).collect()
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
//! The clap definition is consistent, and every shell's completions and every man page
|
||||
//! (`examples/man-and-completions.rs`) can be generated from it.
|
||||
|
||||
use clap::ValueEnum;
|
||||
use clap_complete::Shell;
|
||||
|
||||
// The example itself, so the test writes the files exactly as the packages get them.
|
||||
#[allow(dead_code)]
|
||||
#[path = "../../examples/man-and-completions.rs"]
|
||||
mod example;
|
||||
|
||||
#[test]
|
||||
fn command_is_consistent() {
|
||||
texturecraft_cli::command().debug_assert();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completions_generate_for_every_shell() {
|
||||
for &shell in Shell::value_variants() {
|
||||
let mut out = Vec::new();
|
||||
clap_complete::generate(shell, &mut texturecraft_cli::command(), "texturecraft-cli", &mut out);
|
||||
assert!(!out.is_empty(), "{shell}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn man_pages_render_for_the_command_and_every_subcommand() {
|
||||
let cmd = texturecraft_cli::command();
|
||||
for page in std::iter::once(&cmd).chain(cmd.get_subcommands()) {
|
||||
let mut out = Vec::new();
|
||||
clap_mangen::Man::new(page.clone()).render(&mut out).unwrap();
|
||||
assert!(!out.is_empty(), "{}", page.get_name());
|
||||
}
|
||||
}
|
||||
|
||||
/// The example writes the five completion files under the names `packaging/linux/package.sh` and
|
||||
/// `packaging/freebsd/package.sh` install, `texturecraft-cli.1` and a page per subcommand, and no
|
||||
/// pages for the `help` subcommand.
|
||||
#[test]
|
||||
fn the_example_writes_the_files_the_packages_install() {
|
||||
let dir = std::env::temp_dir().join(format!("mc-cli-{}-man-and-completions", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
example::generate(&dir).unwrap();
|
||||
|
||||
let mut written: Vec<String> = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name().into_string().unwrap()).collect();
|
||||
written.sort();
|
||||
let completions = ["texturecraft-cli.bash", "_texturecraft-cli", "texturecraft-cli.fish", "texturecraft-cli.elv", "_texturecraft-cli.ps1"];
|
||||
let subcommands = ["info", "commands", "run", "batch", "bake", "export", "render", "new", "mcp", "serve"];
|
||||
let mut expected: Vec<String> = completions.map(String::from).into();
|
||||
expected.push("texturecraft-cli.1".into());
|
||||
expected.extend(subcommands.iter().map(|s| format!("texturecraft-cli-{s}.1")));
|
||||
expected.sort();
|
||||
assert_eq!(written, expected);
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
//! The subcommands that talk over a stream (`mcp` and `serve` on stdio, through the real binary,
|
||||
//! which owns stdin and stdout) and the environment variable of the control token.
|
||||
|
||||
use std::io::Write;
|
||||
use std::net::TcpListener;
|
||||
use std::process::{Command, Output, Stdio};
|
||||
|
||||
fn binary() -> Command {
|
||||
let mut command = Command::new(env!("CARGO_BIN_EXE_texturecraft-cli"));
|
||||
command.env("TEXTURECRAFT_NO_PREFS", "1").env_remove("TEXTURECRAFT_CONTROL_TOKEN");
|
||||
command
|
||||
}
|
||||
|
||||
/// A port nothing listens on, with no token file.
|
||||
fn free_port() -> String {
|
||||
TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port().to_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serve_writes_nothing_but_json_lines_to_stdout() {
|
||||
let mut child = binary().arg("serve").stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
|
||||
let mut stdin = child.stdin.take().unwrap();
|
||||
writeln!(stdin, r#"{{"id":1,"method":"ping","params":{{}}}}"#).unwrap();
|
||||
writeln!(stdin, "not json").unwrap();
|
||||
drop(stdin);
|
||||
let output = child.wait_with_output().unwrap();
|
||||
assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));
|
||||
assert!(output.stderr.is_empty(), "{}", String::from_utf8_lossy(&output.stderr));
|
||||
let lines: Vec<_> = String::from_utf8(output.stdout).unwrap().lines().map(str::to_string).collect();
|
||||
assert_eq!(lines.len(), 2, "{lines:?}");
|
||||
for line in &lines {
|
||||
assert!(serde_json::from_str::<serde_json::Value>(line).unwrap().get("ok").is_some(), "{line}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serve_ends_quietly_and_mcp_reports_it_when_stdin_is_closed() {
|
||||
let output = binary().arg("serve").stdin(Stdio::null()).output().unwrap();
|
||||
assert_eq!((output.status.code(), output.stdout.is_empty(), output.stderr.is_empty()), (Some(0), true, true));
|
||||
// An MCP client must open with `initialize`; end of input before it is a failed start.
|
||||
let dir = std::env::temp_dir().join(format!("tc-mcp-stdio-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let output = binary().args(["mcp", "--read-root", dir.to_str().unwrap(), "--write-root", dir.to_str().unwrap()]).stdin(Stdio::null()).output().unwrap();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
assert_eq!((output.status.code(), output.stdout.is_empty()), (Some(1), true));
|
||||
assert!(String::from_utf8_lossy(&output.stderr).starts_with("error: MCP start: "), "{}", String::from_utf8_lossy(&output.stderr));
|
||||
}
|
||||
|
||||
fn bridge(token_flag: Option<&str>, env: Option<&str>) -> Output {
|
||||
let port = free_port();
|
||||
let mut command = binary();
|
||||
command.args(["mcp", "--bridge", &port]);
|
||||
if let Some(token) = token_flag {
|
||||
command.args(["--token", token]);
|
||||
}
|
||||
if let Some(token) = env {
|
||||
command.env("TEXTURECRAFT_CONTROL_TOKEN", token);
|
||||
}
|
||||
command.stdin(Stdio::null()).output().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_control_token_variable_is_a_fallback_the_flag_wins_and_an_empty_one_is_unset() {
|
||||
let secret = "env-token-0123456789-secret";
|
||||
// Empty or blank counts as unset: the error says to set one, as when there is none.
|
||||
for blank in ["", " "] {
|
||||
let output = bridge(None, Some(blank));
|
||||
let err = String::from_utf8_lossy(&output.stderr);
|
||||
assert_eq!(output.status.code(), Some(1), "{err}");
|
||||
assert!(err.contains("no control token: set TEXTURECRAFT_CONTROL_TOKEN"), "{err}");
|
||||
}
|
||||
// The variable is used when there is no flag: a good token gets as far as connecting.
|
||||
let err = String::from_utf8_lossy(&bridge(None, Some(secret)).stderr).into_owned();
|
||||
assert!(!err.contains("16 to 1024") && !err.contains(secret), "{err}");
|
||||
// The flag wins over a good variable: its bad value is what is reported, without echoing either.
|
||||
let err = String::from_utf8_lossy(&bridge(Some("short"), Some(secret)).stderr).into_owned();
|
||||
assert!(err.contains("control token must be 16 to 1024"), "{err}");
|
||||
assert!(!err.contains(secret) && !err.contains("short\n"), "{err}");
|
||||
// A bad value in the variable is refused too, and its value stays out of the message.
|
||||
let err = String::from_utf8_lossy(&bridge(None, Some("bad token")).stderr).into_owned();
|
||||
assert!(err.contains("control token must be 16 to 1024") && !err.contains("bad token"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn help_lists_the_variable_but_never_its_value() {
|
||||
let output = binary().args(["mcp", "--help"]).env("TEXTURECRAFT_CONTROL_TOKEN", "do-not-print-this-0123456789").output().unwrap();
|
||||
let help = String::from_utf8_lossy(&output.stdout);
|
||||
assert!(help.contains("TEXTURECRAFT_CONTROL_TOKEN") && !help.contains("do-not-print-this"), "{help}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_variable_alone_grants_no_file_access() {
|
||||
// The token variable is for authentication only: a headless server with no roots still refuses files.
|
||||
let mut child =
|
||||
binary().arg("serve").env("TEXTURECRAFT_CONTROL_TOKEN", "env-token-0123456789-secret").stdin(Stdio::piped()).stdout(Stdio::piped()).spawn().unwrap();
|
||||
let mut stdin = child.stdin.take().unwrap();
|
||||
writeln!(stdin, r#"{{"id":1,"method":"project.save","params":{{"path":"never.tcraft"}}}}"#).unwrap();
|
||||
drop(stdin);
|
||||
let output = child.wait_with_output().unwrap();
|
||||
let reply: serde_json::Value = serde_json::from_str(String::from_utf8(output.stdout).unwrap().lines().next().unwrap()).unwrap();
|
||||
assert_eq!(reply["ok"], false, "{reply}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_token_in_the_environment_does_not_require_bridge() {
|
||||
// Headless MCP must parse even when TEXTURECRAFT_CONTROL_TOKEN is set; only --token on the
|
||||
// command line requires --bridge.
|
||||
let output = binary().args(["mcp", "--fromat"]).env("TEXTURECRAFT_CONTROL_TOKEN", "env-token-0123456789-secret").output().unwrap();
|
||||
let err = String::from_utf8_lossy(&output.stderr);
|
||||
assert_eq!(output.status.code(), Some(2), "{err}");
|
||||
assert!(err.contains("--fromat"), "{err}");
|
||||
assert!(!err.contains("--bridge") && !err.contains("--token is for"), "{err}");
|
||||
|
||||
let output = binary().args(["mcp", "--token", "flag-token-0123456789"]).output().unwrap();
|
||||
let err = String::from_utf8_lossy(&output.stderr);
|
||||
assert_eq!(output.status.code(), Some(2), "{err}");
|
||||
assert!(err.contains("--token") && err.contains("--bridge"), "{err}");
|
||||
}
|
||||
@@ -18,8 +18,9 @@ texturecraft-engine = { workspace = true }
|
||||
texturecraft-ui-egui = { workspace = true }
|
||||
log = { workspace = true }
|
||||
|
||||
# `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback.
|
||||
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "persistence"] }
|
||||
# `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback. No `default_fonts`: the UI takes egui's faces
|
||||
# from craft-ui's deflated copies (the wasm is under a download budget).
|
||||
eframe = { workspace = true, features = ["wgpu", "accesskit", "persistence"] }
|
||||
wasm-bindgen = "0.2"
|
||||
wasm-bindgen-futures = "0.4"
|
||||
js-sys = "0.3"
|
||||
|
||||
@@ -23,6 +23,8 @@ serde_json = { workspace = true }
|
||||
log = { workspace = true }
|
||||
# The message box for errors that end the app (a Windows release build has no console).
|
||||
rfd = { workspace = true }
|
||||
# Pass the selected window backend to the title bar and UI runtime
|
||||
craft-host = { workspace = true }
|
||||
# Reads the saved System title bar setting before the window opens (eframe's settings format).
|
||||
ron = "0.12"
|
||||
|
||||
@@ -35,6 +37,12 @@ winsafe = { version = "0.0.29", default-features = false, features = ["user", "s
|
||||
# The update helper is a copy of this program (`main`).
|
||||
craft-update = { workspace = true }
|
||||
|
||||
# X11 setup probing and event loop selection for Wayland pen support
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
rustix = { workspace = true, features = ["net", "system"] }
|
||||
winit = { version = "0.30", default-features = false, features = ["x11"] }
|
||||
x11rb-protocol = "0.13"
|
||||
|
||||
# Quit (Cmd+Q) asks about unsaved changes (src/main.rs); winit's own Quit does not.
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
craft-menu = { workspace = true }
|
||||
|
||||
@@ -15,6 +15,8 @@ mod nightly_session;
|
||||
mod process_identity;
|
||||
mod profile_root;
|
||||
mod window_frame;
|
||||
#[cfg(target_os = "linux")]
|
||||
mod xwayland_pen;
|
||||
|
||||
use std::ffi::OsString;
|
||||
|
||||
@@ -334,8 +336,7 @@ fn launch_arguments(arguments: Vec<OsString>) -> Result<Vec<String>, String> {
|
||||
}
|
||||
|
||||
fn main() {
|
||||
// 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.
|
||||
// Stable handles --finish-update on Windows while the launcher updates Nightly
|
||||
#[cfg(windows)]
|
||||
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::<Vec<_>>())
|
||||
@@ -343,15 +344,16 @@ fn main() {
|
||||
std::process::exit(i32::from(result.is_err()));
|
||||
}
|
||||
|
||||
// Windows: the eyedropper's pointer keeper (screen_pick) is a copy of this program started with
|
||||
// its own argument. It reads no user state and is started without the profile tokens, so it
|
||||
// runs before the launch protocol would refuse it.
|
||||
// Dispatch the Windows pointer keeper before launch validation because it has no profile tokens
|
||||
#[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 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,
|
||||
@@ -361,8 +363,8 @@ 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.
|
||||
|
||||
// Keep the control token out of the shared temp folder for a private Nightly 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);
|
||||
@@ -377,9 +379,8 @@ fn main() {
|
||||
previous_hook(info);
|
||||
}));
|
||||
|
||||
// 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`).
|
||||
// Scripted runs use temporary files to protect saved settings
|
||||
// An explicit eframe path keeps app.ron with ui.json and errors.log despite the app ID
|
||||
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 persistence_path = no_prefs_path.clone().or_else(|| storage_dir().map(|dir| dir.join("app.ron")));
|
||||
@@ -393,8 +394,16 @@ fn main() {
|
||||
prefs.apply_work_threads();
|
||||
prefs.apply_resource_limits();
|
||||
let session = initial_session(&args);
|
||||
let frame_decision = TitleBar::decide(prefs.system_title_bar);
|
||||
|
||||
// Xwayland can forward pen input as pointer events on Wayland desktops
|
||||
#[cfg(target_os = "linux")]
|
||||
let use_xwayland_for_pen = xwayland_pen::opens_through_xwayland();
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
let use_xwayland_for_pen = false;
|
||||
let backend = if use_xwayland_for_pen { craft_host::target::Backend::X11 } else { craft_host::target::Backend::from_env() };
|
||||
let frame_decision = TitleBar::decide(prefs.system_title_bar, backend);
|
||||
let title_bar = TitleBar::of(&frame_decision.frame);
|
||||
|
||||
let mut viewport = egui::ViewportBuilder::default()
|
||||
.with_app_id(os_window::app_id())
|
||||
.with_title(os_window::name())
|
||||
@@ -403,15 +412,32 @@ fn main() {
|
||||
if let Some(i) = icon() {
|
||||
viewport = viewport.with_icon(i);
|
||||
}
|
||||
|
||||
let viewport = texturecraft_ui_egui::titlebar::viewport(&frame_decision, viewport);
|
||||
let mut options = eframe::NativeOptions { viewport, renderer: eframe::Renderer::Wgpu, persistence_path, ..Default::default() };
|
||||
#[cfg(target_os = "linux")]
|
||||
if use_xwayland_for_pen {
|
||||
use winit::platform::x11::EventLoopBuilderExtX11 as _;
|
||||
|
||||
options.event_loop_builder = Some(Box::new(|builder| {
|
||||
builder.with_x11();
|
||||
}));
|
||||
let notice = texturecraft_ui_egui::i18n::trf(
|
||||
"Opening the window through Xwayland for pen input. Set {variable}=1 to keep Wayland.",
|
||||
&[("variable", &xwayland_pen::NATIVE_WAYLAND_VARIABLE)],
|
||||
);
|
||||
eprintln!("texturecraft: {notice}");
|
||||
}
|
||||
|
||||
if let Err(e) = gpu::configure(&mut options, args.gpu, args.power_pref) {
|
||||
fatal(&e.to_string(), true);
|
||||
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.
|
||||
|
||||
// Nightly records one owner per profile so the next launch can report an unclean exit
|
||||
// The record carries no document name, path or diagnostics
|
||||
let (nightly_session, session_health_warning) = match nightly_session::Session::begin_with_health(
|
||||
launch_profile::current().root(),
|
||||
build_flavor::BUILT_VERSION,
|
||||
@@ -424,12 +450,13 @@ fn main() {
|
||||
}
|
||||
};
|
||||
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.
|
||||
|
||||
// Keep the record until a window has posted the interruption notice
|
||||
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.
|
||||
|
||||
// AppKit terminates the process without returning from run_native, so macOS needs the exit hook
|
||||
let finish_at_exit = {
|
||||
let shared = nightly_session.clone();
|
||||
let shown = unclean_notice_shown.clone();
|
||||
@@ -450,7 +477,8 @@ fn main() {
|
||||
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}");
|
||||
}
|
||||
texturecraft_ui_egui::framework::install(&cc.egui_ctx, frame_decision)?;
|
||||
|
||||
texturecraft_ui_egui::framework::install(&cc.egui_ctx, frame_decision, backend)?;
|
||||
let frame_guard = window_frame::service(cc, matches!(title_bar, TitleBar::App(_)));
|
||||
let mut app = TextureCraftApp::new(cc, session);
|
||||
app.title_bar = title_bar;
|
||||
@@ -470,8 +498,8 @@ fn main() {
|
||||
Ok(Box::new(Shell { app, window_frame: frame_guard, exit_hook: Some(Box::new(finish_at_exit)) }))
|
||||
}),
|
||||
);
|
||||
// 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.
|
||||
|
||||
// Close the session record on controlled return, including handled startup errors
|
||||
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);
|
||||
|
||||
@@ -178,13 +178,21 @@ fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option<OsString>,
|
||||
/// Nightly's writes at another app's files.
|
||||
fn private_subdirectory(root: &Path, name: impl AsRef<Path>, label: &str) -> Result<PathBuf, String> {
|
||||
let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?;
|
||||
let child = canonical_future(&chosen.join(name))?;
|
||||
let entry = chosen.join(name);
|
||||
let metadata = std::fs::symlink_metadata(&entry).map_err(|e| format!("cannot inspect the nightly {label}: {e}"))?;
|
||||
if !metadata.is_dir() {
|
||||
return Err(format!("the nightly {label} must be a directory inside its selected profile"));
|
||||
}
|
||||
let child = canonical_future(&entry)?;
|
||||
if child == chosen || !child.starts_with(&chosen) {
|
||||
return Err(format!("the nightly {label} must stay inside its selected profile"));
|
||||
}
|
||||
Ok(child)
|
||||
}
|
||||
|
||||
/// Known folder-only entries directly inside a Nightly profile.
|
||||
const PROFILE_FOLDERS: [&str; 10] = ["autosave", "logs", "cache", "library", "layouts", "templates", "brushes", "export", "export-presets", "Samples"];
|
||||
|
||||
/// 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> {
|
||||
@@ -195,11 +203,56 @@ fn entries_stay_inside(root: &Path) -> Result<(), String> {
|
||||
};
|
||||
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")?;
|
||||
let path = entry.path();
|
||||
let metadata = std::fs::symlink_metadata(&path).map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
|
||||
// Settings and session state are ordinary files, not directories. Keep the existing
|
||||
// directory-boundary check for folders (including the known folder-only entries).
|
||||
let folder_only = PROFILE_FOLDERS.iter().any(|name| entry.file_name().eq_ignore_ascii_case(name));
|
||||
if metadata.is_file() && !folder_only {
|
||||
private_regular_file(&path, &metadata)?;
|
||||
} else {
|
||||
private_subdirectory(root, entry.file_name(), "profile entry")?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Persisted files must have their own ordinary file identity, not an alias to other data.
|
||||
fn private_regular_file(path: &Path, metadata: &std::fs::Metadata) -> Result<(), String> {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::MetadataExt as _;
|
||||
if metadata.nlink() != 1 {
|
||||
return Err("the nightly profile file must not be shared".into());
|
||||
}
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use winsafe::{HFILE, co};
|
||||
let (file, _) = HFILE::CreateFile(
|
||||
path.to_str().ok_or("the nightly profile file path is not textual")?,
|
||||
co::GENERIC::default(),
|
||||
Some(co::FILE_SHARE::READ | co::FILE_SHARE::WRITE | co::FILE_SHARE::DELETE),
|
||||
None,
|
||||
co::DISPOSITION::OPEN_EXISTING,
|
||||
co::FILE_ATTRIBUTE::NORMAL,
|
||||
Some(co::FILE_FLAG::OPEN_REPARSE_POINT),
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let info = file.GetFileInformationByHandle().map_err(|e| e.to_string())?;
|
||||
if info.dwFileAttributes.has(co::FILE_ATTRIBUTE::REPARSE_POINT | co::FILE_ATTRIBUTE::DIRECTORY) {
|
||||
return Err("the nightly profile file must not be an alias or directory".into());
|
||||
}
|
||||
if info.nNumberOfLinks != 1 {
|
||||
return Err("the nightly profile file must not be shared".into());
|
||||
}
|
||||
}
|
||||
let _ = (path, metadata);
|
||||
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");
|
||||
@@ -474,6 +527,31 @@ mod tests {
|
||||
assert!(fixture.check(Platform::Linux, &fixture.home().join("Documents").join(BRAND)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_profile_reopens_after_saving_settings_and_session_state() {
|
||||
let fixture = Fixture::new();
|
||||
for platform in [Platform::Mac, Platform::Linux, Platform::Windows] {
|
||||
let private = fixture.root.join(format!("nightly-reopen-{platform:?}"));
|
||||
assert_eq!(fixture.check(platform, &private).unwrap(), private);
|
||||
for name in ["app.ron", "ui.json", "errors.log", "nightly-session.lock", "nightly-session.json"] {
|
||||
std::fs::write(private.join(name), b"saved profile data").unwrap();
|
||||
}
|
||||
for name in PROFILE_FOLDERS {
|
||||
std::fs::create_dir(private.join(name)).unwrap();
|
||||
}
|
||||
assert_eq!(fixture.check(platform, &private).unwrap(), private);
|
||||
assert_eq!(std::fs::read(private.join("app.ron")).unwrap(), b"saved profile data");
|
||||
for name in PROFILE_FOLDERS {
|
||||
let path = private.join(name);
|
||||
std::fs::remove_dir(&path).unwrap();
|
||||
std::fs::write(&path, b"not a directory").unwrap();
|
||||
assert!(fixture.check(platform, &private).is_err(), "{name} must stay a directory");
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
std::fs::create_dir(&path).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn a_profile_whose_existing_ancestor_is_a_link_resolves_before_the_fence() {
|
||||
|
||||
@@ -0,0 +1,264 @@
|
||||
//! A pen on a Wayland desktop opens the window through Xwayland (#816).
|
||||
//!
|
||||
//! Copyright (c) 2026 ArtCraft Team and the PhotoCraft contributors for the adapted code.
|
||||
//! Licensed under the MIT License or the Apache License, Version 2.0, at your option.
|
||||
//!
|
||||
//! Wayland compositors give a pen only to clients that bind the tablet protocol (`zwp_tablet_v2`),
|
||||
//! which winit 0.30 doesn't (and binding it on winit's connection needs `unsafe`, which this app
|
||||
//! forbids). Some compositors (KWin) then send the window nothing from the pen: no cursor, no
|
||||
//! painting. Xwayland binds the protocol and serves the pen as an X11 pointer, so with a pen
|
||||
//! attached the window opens there. `TEXTURECRAFT_NATIVE_WAYLAND=1` keeps native Wayland.
|
||||
//!
|
||||
//! Adapted from PhotoCraft (storytold/photocraft `830316b7`, MIT OR Apache-2.0):
|
||||
//! `apps/photocraft/src/tablet.rs` (`display_session`, `pen_needs_xwayland`, `has_pen`, `bit_set`)
|
||||
//! and `apps/photocraft/src/linux_libs.rs` (`session_from_env`, `ldconfig_has`, the library
|
||||
//! search), reduced to the pen decision. See the repository's NOTICE for the port.
|
||||
|
||||
use std::io::{Read as _, Write as _};
|
||||
use std::os::unix::net::UnixStream;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use x11rb_protocol::connect::Connect;
|
||||
use x11rb_protocol::xauth::{Family, get_auth};
|
||||
|
||||
/// Set (and not `0`) to keep native Wayland with a pen attached
|
||||
pub(super) const NATIVE_WAYLAND_VARIABLE: &str = "TEXTURECRAFT_NATIVE_WAYLAND";
|
||||
|
||||
/// `BTN_TOOL_PEN` (linux/input-event-codes.h): the key a tablet's stylus, a pen display's or a
|
||||
/// pen-enabled touchscreen's pen reports
|
||||
const BTN_TOOL_PEN: u32 = 0x140;
|
||||
|
||||
/// `ABS_X` and `ABS_Y` (linux/input-event-codes.h): the absolute axes every pen reports
|
||||
const ABS_X: u32 = 0x00;
|
||||
const ABS_Y: u32 = 0x01;
|
||||
|
||||
/// What winit 0.30 loads at run time for an X11 window: Xlib, Xlib-xcb, xcb, Xcursor, XInput2 and
|
||||
/// xkbcommon with its X11 part
|
||||
const X11_LIBRARIES: &[&str] =
|
||||
&["libX11.so.6", "libX11-xcb.so.1", "libxcb.so.1", "libXcursor.so.1", "libXi.so.6", "libxkbcommon.so.0", "libxkbcommon-x11.so.0"];
|
||||
|
||||
// Give local Xwayland time to answer while bounding the wait before falling back to Wayland
|
||||
const X11_SETUP_TIMEOUT: Duration = Duration::from_secs(1);
|
||||
|
||||
/// Whether the window opens through Xwayland: a pen is attached on a Wayland desktop and Xwayland
|
||||
/// has the required libraries and accepts an X11 client setup.
|
||||
pub fn opens_through_xwayland() -> bool {
|
||||
let var = |name: &str| std::env::var(name).ok();
|
||||
let pen = || std::fs::read_to_string("/proc/bus/input/devices").is_ok_and(|devices| has_pen(&devices));
|
||||
pen_needs_xwayland(var, pen, |display| x11_libraries_available() && x_server_accepts_setup(display))
|
||||
}
|
||||
|
||||
/// [`opens_through_xwayland`]'s decision. winit picks Wayland when `WAYLAND_DISPLAY` or
|
||||
/// `WAYLAND_SOCKET` is set; Xwayland needs `DISPLAY`. The system probes run only on Wayland.
|
||||
fn pen_needs_xwayland(var: impl Fn(&str) -> Option<String>, pen: impl FnOnce() -> bool, xwayland_ready: impl FnOnce(&str) -> bool) -> bool {
|
||||
let set = |name: &str| var(name).is_some_and(|value| !value.is_empty());
|
||||
let wayland = set("WAYLAND_DISPLAY") || set("WAYLAND_SOCKET");
|
||||
let keeps_wayland = var(NATIVE_WAYLAND_VARIABLE).is_some_and(|value| !value.is_empty() && value != "0");
|
||||
wayland && !keeps_wayland && var("DISPLAY").filter(|display| !display.is_empty()).is_some_and(|display| pen() && xwayland_ready(&display))
|
||||
}
|
||||
|
||||
/// winit commits to its forced backend, so require an accepted X11 setup before forcing X11.
|
||||
fn x_server_accepts_setup(display: &str) -> bool {
|
||||
let Some((display_number, screen)) = local_display(display) else {
|
||||
return false;
|
||||
};
|
||||
|
||||
let Some(socket) = connect_local_x_server(display_number) else {
|
||||
return false;
|
||||
};
|
||||
|
||||
let hostname = rustix::system::uname();
|
||||
let auth_hostname = std::env::var_os("XAUTHLOCALHOSTNAME");
|
||||
let auth_address = auth_hostname.as_ref().map_or(hostname.nodename().to_bytes(), |name| name.as_encoded_bytes());
|
||||
let (auth_name, auth_data) = get_auth(Family::LOCAL, auth_address, display_number).ok().flatten().unwrap_or_default();
|
||||
let (setup, request) = Connect::with_authorization(auth_name, auth_data);
|
||||
exchange_x11_setup(socket, setup, &request, screen)
|
||||
}
|
||||
|
||||
/// Parse the display and screen of a local X server such as `:0`, `:0.0` or `unix:0`.
|
||||
fn local_display(display: &str) -> Option<(u16, usize)> {
|
||||
let local = display.strip_prefix(':').or_else(|| display.strip_prefix("unix:"))?;
|
||||
let (display_number, screen) = local.split_once('.').unwrap_or((local, "0"));
|
||||
Some((display_number.parse().ok()?, screen.parse().ok()?))
|
||||
}
|
||||
|
||||
fn connect_local_x_server(display_number: u16) -> Option<UnixStream> {
|
||||
use rustix::net::{AddressFamily, SocketAddrUnix, SocketFlags, SocketType, connect, socket_with};
|
||||
|
||||
let path = format!("/tmp/.X11-unix/X{display_number}");
|
||||
|
||||
// Try the abstract socket first, as Xlib does on Linux
|
||||
[SocketAddrUnix::new_abstract_name(path.as_bytes()), SocketAddrUnix::new(&path)].into_iter().find_map(|address| {
|
||||
let address = address.ok()?;
|
||||
|
||||
// A full Unix socket backlog must not block app startup
|
||||
let socket = UnixStream::from(socket_with(AddressFamily::UNIX, SocketType::STREAM, SocketFlags::NONBLOCK | SocketFlags::CLOEXEC, None).ok()?);
|
||||
connect(&socket, &address).ok()?;
|
||||
socket.set_nonblocking(false).ok()?;
|
||||
Some(socket)
|
||||
})
|
||||
}
|
||||
|
||||
fn exchange_x11_setup(mut socket: UnixStream, mut setup: Connect, request: &[u8], screen: usize) -> bool {
|
||||
let start = Instant::now();
|
||||
if socket.set_write_timeout(Some(X11_SETUP_TIMEOUT)).is_err() || socket.write_all(request).is_err() {
|
||||
return false;
|
||||
}
|
||||
|
||||
while !setup.buffer().is_empty() {
|
||||
let remaining = X11_SETUP_TIMEOUT.saturating_sub(start.elapsed());
|
||||
if remaining.is_zero() || socket.set_read_timeout(Some(remaining)).is_err() {
|
||||
return false;
|
||||
}
|
||||
|
||||
let Ok(received) = socket.read(setup.buffer()) else {
|
||||
return false;
|
||||
};
|
||||
|
||||
if received == 0 {
|
||||
return false;
|
||||
}
|
||||
|
||||
if setup.advance(received) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
setup.into_setup().is_ok_and(|reply| screen < reply.roots.len())
|
||||
}
|
||||
|
||||
/// Is a pen among the input devices `/proc/bus/input/devices` lists? A pen's `B: KEY=` bitmap has
|
||||
/// `BTN_TOOL_PEN` and its `B: ABS=` bitmap has `ABS_X` and `ABS_Y`, as libinput asks of a tablet
|
||||
/// tool. The key alone isn't enough: a virtual keyboard made with uinput claims every key code.
|
||||
fn has_pen(devices: &str) -> bool {
|
||||
devices.split("\n\n").any(|device| {
|
||||
let bitmap = |name: &str| device.lines().find_map(|line| line.strip_prefix(name));
|
||||
bitmap("B: KEY=").is_some_and(|keys| bit_set(keys, BTN_TOOL_PEN)) && bitmap("B: ABS=").is_some_and(|axes| bit_set(axes, ABS_X) && bit_set(axes, ABS_Y))
|
||||
})
|
||||
}
|
||||
|
||||
/// Bit `bit` of a `/proc/bus/input/devices` bitmap: hex words of the kernel's `long`, most
|
||||
/// significant first. Short or malformed bitmaps have no bits set.
|
||||
fn bit_set(bitmap: &str, bit: u32) -> bool {
|
||||
let word_bits = usize::BITS;
|
||||
let word = usize::try_from(bit / word_bits).unwrap_or(usize::MAX);
|
||||
bitmap.split_whitespace().rev().nth(word).and_then(|hex| u64::from_str_radix(hex, 16).ok()).is_some_and(|value| (value >> (bit % word_bits)) & 1 == 1)
|
||||
}
|
||||
|
||||
/// Are the libraries an X11 window needs installed? The linker cache (`ldconfig -p`) or the usual
|
||||
/// library directories must list each; one that can't be found counts as missing.
|
||||
fn x11_libraries_available() -> bool {
|
||||
let cache = linker_cache();
|
||||
let dirs = library_dirs(std::env::var("LD_LIBRARY_PATH").ok().as_deref());
|
||||
X11_LIBRARIES.iter().all(|soname| cache.as_deref().is_some_and(|cache| ldconfig_has(cache, soname)) || dirs.iter().any(|dir| dir.join(soname).exists()))
|
||||
}
|
||||
|
||||
/// `ldconfig -p` in English (it is parsed), from where distributions put it
|
||||
fn linker_cache() -> Option<String> {
|
||||
["/sbin/ldconfig", "/usr/sbin/ldconfig", "ldconfig"].into_iter().find_map(|command| {
|
||||
let output = std::process::Command::new(command).arg("-p").env("LC_ALL", "C").output().ok()?;
|
||||
output.status.success().then(|| String::from_utf8_lossy(&output.stdout).into_owned())
|
||||
})
|
||||
}
|
||||
|
||||
/// Does an `ldconfig -p` listing have `soname` for this build's architecture? Lines look like
|
||||
/// `\tlibXi.so.6 (libc6,x86-64) => /lib/x86_64-linux-gnu/libXi.so.6`.
|
||||
fn ldconfig_has(cache: &str, soname: &str) -> bool {
|
||||
let architecture = if cfg!(target_arch = "x86_64") {
|
||||
Some("x86-64")
|
||||
} else if cfg!(target_arch = "aarch64") {
|
||||
Some("AArch64")
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
cache.lines().any(|line| {
|
||||
let Some((name, rest)) = line.trim_start().split_once(' ') else {
|
||||
return false;
|
||||
};
|
||||
|
||||
let flags = rest.split_once('(').and_then(|(_, after)| after.split_once(')')).map_or("", |(flags, _)| flags);
|
||||
name == soname && architecture.is_none_or(|tag| flags.split(',').any(|flag| flag.trim() == tag))
|
||||
})
|
||||
}
|
||||
|
||||
/// `LD_LIBRARY_PATH`, then the usual system and Flatpak library directories
|
||||
fn library_dirs(ld_library_path: Option<&str>) -> Vec<PathBuf> {
|
||||
let triplet = if cfg!(target_arch = "aarch64") { "aarch64-linux-gnu" } else { "x86_64-linux-gnu" };
|
||||
let mut dirs: Vec<PathBuf> = ld_library_path.into_iter().flat_map(|value| value.split(':')).filter(|dir| !dir.is_empty()).map(PathBuf::from).collect();
|
||||
dirs.extend(["/app/lib", "/usr/local/lib", "/usr/lib64", "/lib64", "/usr/lib", "/lib"].map(PathBuf::from));
|
||||
dirs.extend([Path::new("/usr/lib").join(triplet), Path::new("/lib").join(triplet)]);
|
||||
dirs
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
// Capabilities from /proc/bus/input/devices for a touchpad and a Wacom pen
|
||||
const TOUCHPAD: &str = "N: Name=\"SYNA2B33:00 06CB:CE26 Touchpad\"\nB: KEY=e520 10000 0 0 0 0\nB: ABS=2e0800000000003\n";
|
||||
const PEN: &str = "N: Name=\"Wacom Intuos Pro M Pen\"\nB: KEY=1c03 0 0 0 0 0\nB: ABS=1000f000003\n";
|
||||
|
||||
// The uinput keyboard claims the pen key but reports no axes
|
||||
const VIRTUAL_KEYBOARD: &str = "N: Name=\"RustDesk UInput Keyboard\"\nB: EV=20013\nB: KEY=ffffffffff 0 7ffffff000301ff 1000f7fffffff 7fe001fffff000f 7ffffffffffffff ffffffff0003fdff 7fff8fff00ff03ff 1ffffffffffff07 ffffffffffffffff ffffffffffefffff fffffffffffffffe\n";
|
||||
|
||||
#[test]
|
||||
fn a_pen_is_a_device_with_the_pen_key_and_absolute_axes() {
|
||||
assert!(has_pen(&format!("{TOUCHPAD}\n{PEN}")));
|
||||
assert!(!has_pen(TOUCHPAD), "a touchpad is no pen");
|
||||
assert!(!has_pen(&format!("{VIRTUAL_KEYBOARD}\n{TOUCHPAD}")), "a keyboard claiming the pen key has no pen axes");
|
||||
assert!(!has_pen("B: KEY=zz 0 0 0 0 0\nB: ABS=3\n"), "a malformed bitmap is no pen");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pen_on_wayland_opens_the_window_through_xwayland() {
|
||||
fn env(pairs: &'static [(&'static str, &'static str)]) -> impl Fn(&str) -> Option<String> {
|
||||
move |name: &str| pairs.iter().find(|(key, _)| *key == name).map(|(_, value)| value.to_string())
|
||||
}
|
||||
const WAYLAND: &[(&str, &str)] = &[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0")];
|
||||
|
||||
assert!(pen_needs_xwayland(env(WAYLAND), || true, |display| display == ":0"));
|
||||
assert!(!pen_needs_xwayland(env(WAYLAND), || false, |_| true), "no pen");
|
||||
assert!(!pen_needs_xwayland(env(WAYLAND), || true, |_| false), "Xwayland can't run the window");
|
||||
assert!(!pen_needs_xwayland(env(&[("WAYLAND_DISPLAY", "wayland-0")]), || true, |_| true), "no Xwayland");
|
||||
assert!(!pen_needs_xwayland(env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0"), (NATIVE_WAYLAND_VARIABLE, "1")]), || true, |_| true), "kept");
|
||||
assert!(pen_needs_xwayland(env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0"), (NATIVE_WAYLAND_VARIABLE, "0")]), || true, |_| true));
|
||||
assert!(!pen_needs_xwayland(env(&[("DISPLAY", ":0")]), || panic!("probed off Wayland"), |_| panic!("probed off Wayland")), "X11 already has the pen");
|
||||
assert_eq!([":1.2", "unix:0", "remote:0", ":0.bad"].map(local_display), [Some((1, 2)), Some((0, 0)), None, None]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pen_keeps_wayland_when_the_x_server_rejects_setup() -> std::io::Result<()> {
|
||||
use x11rb_protocol::protocol::xproto::{Screen, Setup, SetupFailed};
|
||||
use x11rb_protocol::x11_utils::Serialize as _;
|
||||
|
||||
const REPLY_HEADER_BYTES: usize = 8;
|
||||
const BYTES_PER_X11_WORD: usize = 4;
|
||||
let reason = b"Setup denied".to_vec();
|
||||
let rejected = SetupFailed { protocol_major_version: 11, length: (reason.len() / BYTES_PER_X11_WORD) as u16, reason, ..Default::default() };
|
||||
let mut accepted = Setup { status: 1, protocol_major_version: 11, roots: vec![Screen::default()], ..Default::default() };
|
||||
accepted.length = ((accepted.serialize().len() - REPLY_HEADER_BYTES) / BYTES_PER_X11_WORD) as u16;
|
||||
|
||||
for (reply, screen, selects_xwayland) in [(rejected.serialize(), 0, false), (accepted.serialize(), 1, false), (accepted.serialize(), 0, true)] {
|
||||
let (client, mut server) = UnixStream::pair()?;
|
||||
server.write_all(&reply)?;
|
||||
let (setup, request) = Connect::with_authorization(Vec::new(), Vec::new());
|
||||
let var = |name: &str| match name {
|
||||
"WAYLAND_DISPLAY" => Some("wayland-0".into()),
|
||||
"DISPLAY" => Some(format!(":0.{screen}")),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
let xwayland = pen_needs_xwayland(
|
||||
var,
|
||||
|| true,
|
||||
|display| local_display(display).is_some_and(|(_, screen)| exchange_x11_setup(client, setup, &request, screen)),
|
||||
);
|
||||
|
||||
assert_eq!(xwayland, selects_xwayland);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -28,4 +28,5 @@ getrandom = { workspace = true }
|
||||
rustix = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
rmcp = { workspace = true, features = ["client"] }
|
||||
@@ -289,25 +289,50 @@ impl Headless {
|
||||
}
|
||||
|
||||
/// Export textures to `dir` (`file.exportTextures` params: preset, ts, format, padding, size…).
|
||||
pub fn export(&mut self, p: &Value) -> Result<Value, AutomationError> {
|
||||
pub fn export(&mut self, params: &Value) -> Result<Value, AutomationError> {
|
||||
use texturecraft_engine::shader_parameters::{shader_parameters_param, shader_parameters_sidecar};
|
||||
|
||||
self.require_project()?;
|
||||
let dir = p.get("dir").and_then(Value::as_str).filter(|d| !d.is_empty()).ok_or_else(|| bad("`dir` is required"))?;
|
||||
let opts = file_cmds::export_options(&self.session, p, "textures.export")?;
|
||||
let n = self.session.set_count();
|
||||
let sets: Vec<usize> = match p.get("ts") {
|
||||
None | Some(Value::Null) => (0..n).collect(),
|
||||
Some(Value::String(a)) if a == "all" => (0..n).collect(),
|
||||
Some(v) => vec![v.as_u64().and_then(|t| usize::try_from(t).ok()).filter(|t| *t < n).ok_or_else(|| bad(format!("invalid `ts` {v}")))?],
|
||||
let dir = params.get("dir").and_then(Value::as_str).filter(|dir| !dir.is_empty()).ok_or_else(|| bad("`dir` is required"))?;
|
||||
let options = file_cmds::export_options(&self.session, params, "textures.export")?;
|
||||
let set_count = self.session.set_count();
|
||||
let sets: Vec<usize> = match params.get("ts") {
|
||||
None | Some(Value::Null) => (0..set_count).collect(),
|
||||
Some(Value::String(selection)) if selection == "all" => (0..set_count).collect(),
|
||||
Some(value) => vec![
|
||||
value
|
||||
.as_u64()
|
||||
.and_then(|index| usize::try_from(index).ok())
|
||||
.filter(|index| *index < set_count)
|
||||
.ok_or_else(|| bad(format!("invalid `ts` {value}")))?,
|
||||
],
|
||||
};
|
||||
let files = self.session.export_files(&sets, &opts)?;
|
||||
let shader_sets = shader_parameters_param(&self.session.doc.project, params, &sets, "textures.export")?;
|
||||
|
||||
let files = self.session.export_files(&sets, &options)?;
|
||||
let sidecar = shader_sets.map(|sets| shader_parameters_sidecar(&self.session.doc.project, &sets, &files));
|
||||
self.create_dir_all(dir)?;
|
||||
let mut written = Vec::new();
|
||||
for f in &files {
|
||||
let path = join(dir, &f.name);
|
||||
self.write(&path, &f.bytes)?;
|
||||
let mut warnings = Vec::new();
|
||||
for file in files {
|
||||
let path = join(dir, &file.name);
|
||||
self.write(&path, &file.bytes)?;
|
||||
written.push(path);
|
||||
warnings.extend(file.warnings);
|
||||
}
|
||||
let warnings: Vec<&String> = files.iter().flat_map(|f| &f.warnings).collect();
|
||||
|
||||
if let Some(sidecar) = sidecar {
|
||||
let result = sidecar.and_then(|file| {
|
||||
let path = join(dir, &file.name);
|
||||
self.write(&path, &file.bytes).map_err(|error| error.to_string())?;
|
||||
Ok(path)
|
||||
});
|
||||
match result {
|
||||
Ok(path) => written.push(path),
|
||||
Err(error) => warnings.push(format!("The shader settings file was not written: {error}")),
|
||||
}
|
||||
}
|
||||
|
||||
Ok(json!({ "files": written, "warnings": warnings }))
|
||||
}
|
||||
|
||||
@@ -376,7 +401,7 @@ impl Headless {
|
||||
|
||||
let gpu = match self.gpu.get_or_insert_with(Gpu::new) {
|
||||
Ok(g) => g,
|
||||
Err(e) => return Err(AutomationError::Other(format!("cannot render: {e}"))),
|
||||
Err(e) => return Err(AutomationError::Other(format!("cannot render: {e}; path tracing (`samples`) needs no GPU"))),
|
||||
};
|
||||
|
||||
// Last-resort guard: wgpu panics on device errors; drop the device and report instead
|
||||
|
||||
@@ -6,6 +6,7 @@ use std::sync::{Arc, Weak};
|
||||
|
||||
use rayon::prelude::*;
|
||||
use texturecraft_engine::compose::{DisplayKind, ImageRes, all_tiles, tile_bytes};
|
||||
use texturecraft_engine::core::AoMixing;
|
||||
use texturecraft_engine::{Session, ViewMode};
|
||||
use texturecraft_render::displace::trace_geometry;
|
||||
use texturecraft_render::gpu_trace::GpuTracer;
|
||||
@@ -67,6 +68,7 @@ impl Gpu {
|
||||
let empty = Default::default();
|
||||
let baked = session.doc.baked.get(&set_index).unwrap_or(&empty);
|
||||
let composite = &cache.composite;
|
||||
let ao_mixing = session.doc.project.texture_sets.get(set_index).map_or(AoMixing::Multiply, |set| set.ao_mixing);
|
||||
|
||||
// Limit live converted pixels while retaining parallel conversion within each batch
|
||||
const UPLOAD_TILES_PER_BATCH: usize = 64;
|
||||
@@ -74,7 +76,7 @@ impl Gpu {
|
||||
let bytes: Vec<_> = batch
|
||||
.par_iter()
|
||||
.flat_map_iter(|&(tile_x, tile_y)| DisplayKind::ALL.into_iter().map(move |kind| (kind, tile_x, tile_y)))
|
||||
.map(|(kind, tile_x, tile_y)| (kind, tile_x, tile_y, tile_bytes(composite, baked, kind, tile_x, tile_y)))
|
||||
.map(|(kind, tile_x, tile_y)| (kind, tile_x, tile_y, tile_bytes(composite, baked, ao_mixing, kind, tile_x, tile_y)))
|
||||
.collect();
|
||||
for (kind, tile_x, tile_y, pixels) in bytes {
|
||||
headless.renderer.upload_tile(&headless.device, &headless.queue, set_index, kind, tile_x, tile_y, &pixels);
|
||||
@@ -162,7 +164,14 @@ fn trace_inputs(s: &mut Session) -> (TraceScene, TraceDisplay) {
|
||||
.texture_sets
|
||||
.iter()
|
||||
.zip(&s.caches)
|
||||
.map(|(ts, c)| TraceSet { material: ts.material, composite: c.composite.clone(), height_strength: ts.atlas_height_strength() })
|
||||
.map(|(ts, c)| TraceSet {
|
||||
material: ts.material,
|
||||
composite: c.composite.clone(),
|
||||
height_strength: ts.atlas_height_strength(),
|
||||
height_y_factor: ts.atlas_height_y_factor(),
|
||||
height_in_normal: ts.height_in_normal(),
|
||||
height_to_normal: ts.height_to_normal,
|
||||
})
|
||||
.collect();
|
||||
let d = &s.doc.project.display;
|
||||
let env_image = d.environment_resource().and_then(|n| s.images.get(n));
|
||||
@@ -197,10 +206,15 @@ pub fn shade(s: &Session) -> Shade {
|
||||
ViewMode::UvChecker => (3, 0),
|
||||
ViewMode::NormalHeightMesh => (4, 0),
|
||||
};
|
||||
let active_set = s.doc.project.texture_sets.get(s.ts());
|
||||
Shade {
|
||||
height_strength: s.doc.project.texture_sets.get(s.ts()).map(|t| t.atlas_height_strength()).unwrap_or(1.0),
|
||||
height_strength: active_set.map_or(1.0, |t| t.atlas_height_strength()),
|
||||
height_y_factor: active_set.map_or(1.0, |t| t.atlas_height_y_factor()),
|
||||
height_in_normal: active_set.is_none_or(|t| t.height_in_normal()),
|
||||
height_to_normal: active_set.map_or_else(Default::default, |t| t.height_to_normal),
|
||||
view_mode,
|
||||
channel,
|
||||
|
||||
// Only the 2D view uses this default
|
||||
wireframe: true,
|
||||
..Shade::from_project(&s.doc.project)
|
||||
|
||||
@@ -89,6 +89,7 @@ impl Headless {
|
||||
if steps.len() > MAX_BATCH_STEPS {
|
||||
return Err(bad(format!("at most {MAX_BATCH_STEPS} steps per batch")));
|
||||
}
|
||||
|
||||
Ok(self.batch(steps))
|
||||
}
|
||||
"project.open" => self.open(required(p, "path")?),
|
||||
@@ -123,8 +124,9 @@ impl Headless {
|
||||
}
|
||||
}
|
||||
|
||||
/// Answer one request line. A panic inside a command becomes an error reply (edits run on a
|
||||
/// snapshot, so the session stays consistent).
|
||||
/// Answer one request line. A panic inside a command becomes an error reply. `Session::edit`
|
||||
/// rolls the document back on unwind, but work outside it (scripted strokes) and other session
|
||||
/// state, such as the selection or tool, is not rolled back.
|
||||
pub fn respond(h: &Mutex<Headless>, line: &str) -> Value {
|
||||
let req: Value = match serde_json::from_str(line) {
|
||||
Ok(v) => v,
|
||||
|
||||
@@ -45,9 +45,16 @@ pub fn generate_token() -> Result<String, AutomationError> {
|
||||
Ok(bytes.iter().map(|b| format!("{b:02x}")).collect())
|
||||
}
|
||||
|
||||
/// `TEXTURECRAFT_CONTROL_TOKEN`; an empty (or blank) variable counts as unset, as for every other
|
||||
/// variable of the command line (RFC-0018 rule 1.7).
|
||||
fn env_token() -> Option<String> {
|
||||
std::env::var(TOKEN_ENV).ok().filter(|t| !t.trim().is_empty())
|
||||
}
|
||||
|
||||
/// Token for a client of `port`: explicit, else `TEXTURECRAFT_CONTROL_TOKEN`, else the token file.
|
||||
/// A blank value counts as not given.
|
||||
pub fn client_token(port: u16, supplied: Option<String>) -> Result<String, AutomationError> {
|
||||
let token = match supplied.or_else(|| std::env::var(TOKEN_ENV).ok()) {
|
||||
let token = match supplied.filter(|t| !t.trim().is_empty()).or_else(env_token) {
|
||||
Some(t) => t,
|
||||
None => {
|
||||
let path = token_file(port);
|
||||
@@ -64,7 +71,7 @@ pub fn client_token(port: u16, supplied: Option<String>) -> Result<String, Autom
|
||||
/// [`token_file`] (owner-only on Unix). Returns the token and where it was written. Call it
|
||||
/// once the port is bound, so a server that cannot listen never replaces another's token.
|
||||
pub fn server_token(port: u16) -> Result<(String, Option<PathBuf>), AutomationError> {
|
||||
if let Ok(t) = std::env::var(TOKEN_ENV) {
|
||||
if let Some(t) = env_token() {
|
||||
validate_token(t.trim())?;
|
||||
return Ok((t.trim().to_string(), None));
|
||||
}
|
||||
@@ -228,6 +235,25 @@ mod tests {
|
||||
assert!(client_token(1, Some(format!(" {a}\n"))).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_blank_token_counts_as_not_given() {
|
||||
// No token anywhere (the port has no token file): the error says what to set, not that a
|
||||
// blank token is invalid. A non-blank inherited TOKEN_ENV can still satisfy the client
|
||||
// after a blank supplied value, so do not unwrap_err() first.
|
||||
match client_token(1, Some(" ".into())) {
|
||||
Err(error) => {
|
||||
if std::env::var_os(TOKEN_ENV).is_none() {
|
||||
let message = error.to_string();
|
||||
assert!(message.contains("no control token"), "{message}");
|
||||
}
|
||||
}
|
||||
Ok(_) => {
|
||||
let inherited = std::env::var(TOKEN_ENV).unwrap_or_default();
|
||||
assert!(!inherited.trim().is_empty(), "a blank token was accepted with no inherited value");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn scratch(name: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("tc-token-{}-{name}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
|
||||
@@ -177,6 +177,9 @@ pub struct ExportParams {
|
||||
/// Settings for individual maps in the selected template.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub maps: Option<Vec<ExportMapParams>>,
|
||||
/// Write shader settings for the exported sets (true) or the specified texture set indexes.
|
||||
#[serde(default, rename = "shaderParameters", skip_serializing_if = "Option::is_none")]
|
||||
pub shader_parameters: Option<Value>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
|
||||
@@ -335,8 +338,9 @@ impl TexturecraftMcp {
|
||||
match &*self.backend {
|
||||
Backend::Headless(h) => {
|
||||
let (h, m) = (h.clone(), method.to_string());
|
||||
// A panicking command poisons the lock, but edits run on a document snapshot
|
||||
// (`Session::edit`), so the session stays consistent: keep serving.
|
||||
// A panicking command poisons the lock: keep serving. `Session::edit` rolls the
|
||||
// document back on unwind, but work outside it (scripted strokes) and other
|
||||
// session state, such as the selection or tool, is not rolled back.
|
||||
tokio::task::spawn_blocking(move || h.lock().unwrap_or_else(PoisonError::into_inner).handle(&m, &p))
|
||||
.await
|
||||
.unwrap_or_else(|_| Err(AutomationError::Other(format!("internal error in `{method}`"))))
|
||||
|
||||
@@ -19,4 +19,7 @@ pub struct ExportMapParams {
|
||||
/// Override dithering for this map's 8-bit outputs.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub dithering: Option<bool>,
|
||||
/// Side length in pixels for this map, overriding the export size.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub size: Option<u32>,
|
||||
}
|
||||
@@ -132,6 +132,13 @@ const HOST_PATH_KEYS: [&str; 2] = ["path", "dir"];
|
||||
|
||||
/// Refuses engine commands that would reach host paths around the workspace roots, so clients use the workspace tools
|
||||
pub fn authorize_command(id: &str, params: &Value) -> Result<(), AutomationError> {
|
||||
// The Resources Updater reads the files a project names, which may lie outside the read root
|
||||
if matches!(id, "resource.status" | "resource.update" | "resource.relink") {
|
||||
return Err(bad(format!(
|
||||
"`{id}` reads the image files the project names on this machine, so it is disabled for automation; re-import changed files with resource_import"
|
||||
)));
|
||||
}
|
||||
|
||||
let has_path = names_host_path(params) || params.get("files").and_then(Value::as_array).is_some_and(|files| files.iter().any(names_host_path));
|
||||
|
||||
// `file.save` is refused even without a path: a headless session's path is workspace-relative, not a host path
|
||||
@@ -245,6 +252,10 @@ mod tests {
|
||||
assert!(authorize_command("file.reimportMesh", &json!({"path": "/etc/x.obj"})).is_err());
|
||||
assert!(authorize_command("file.reimportMesh", &json!({})).is_ok());
|
||||
assert!(authorize_command("file.close", &json!({})).is_ok());
|
||||
for id in ["resource.status", "resource.update", "resource.relink"] {
|
||||
let error = authorize_command(id, &json!({})).unwrap_err().to_string();
|
||||
assert!(error.contains("reads the image files"), "{id}: {error}");
|
||||
}
|
||||
assert!(authorize_command("layer.add.fill", &json!({"color": "#ff0000", "path": null})).is_ok());
|
||||
}
|
||||
|
||||
|
||||
@@ -88,14 +88,15 @@ async fn inspect(c: &Conn) -> Value {
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn textures_export_accepts_per_map_settings() {
|
||||
let dir = tmp("map-options");
|
||||
let (client, server) = connect(workspace(&dir)).await;
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let dir = temp.path();
|
||||
let (client, server) = connect(workspace(dir)).await;
|
||||
|
||||
let result = tool(
|
||||
&client,
|
||||
"textures_export",
|
||||
json!({"dir": "textures", "preset": "glTF PBR Metal Roughness", "maps": [
|
||||
{"map": 0, "format": "pgm", "bitDepth": 16},
|
||||
{"map": 0, "format": "pgm", "bitDepth": 16, "size": 256},
|
||||
{"map": 1, "enabled": false}
|
||||
]}),
|
||||
)
|
||||
@@ -104,9 +105,42 @@ async fn textures_export_accepts_per_map_settings() {
|
||||
let files = result["files"].as_array().unwrap();
|
||||
assert_eq!(files.len(), 2, "{result}");
|
||||
let graymap = files.iter().filter_map(Value::as_str).find(|path| path.ends_with(".pgm")).unwrap();
|
||||
assert!(std::fs::read(dir.join(graymap)).unwrap().starts_with(b"P5\n128 128\n65535\n"));
|
||||
assert!(std::fs::read(dir.join(graymap)).unwrap().starts_with(b"P5\n256 256\n65535\n"));
|
||||
let inherited = files.iter().filter_map(Value::as_str).find(|path| path.ends_with(".png")).unwrap();
|
||||
assert_eq!(image::image_dimensions(dir.join(inherited)).unwrap(), (128, 128));
|
||||
|
||||
shutdown(client, server).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn textures_export_reports_the_shader_sidecar_and_write_failures() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let dir = temp.path();
|
||||
let (client, server) = connect(workspace(dir)).await;
|
||||
let params = json!({"dir": "textures", "shaderParameters": [0]});
|
||||
|
||||
let result = tool(&client, "textures_export", params.clone()).await;
|
||||
|
||||
let files = result["files"].as_array().unwrap();
|
||||
let sidecar = files.iter().filter_map(Value::as_str).find(|name| name.ends_with("_shaders.json")).expect("shader settings file");
|
||||
let path = dir.join(sidecar);
|
||||
let settings: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
|
||||
assert_eq!(settings["shaders"][0]["textureSets"].as_array().unwrap().len(), 1);
|
||||
assert!(settings["shaders"][0]["model"].is_string());
|
||||
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
std::fs::create_dir(&path).unwrap();
|
||||
let result = tool(&client, "textures_export", params).await;
|
||||
|
||||
assert!(result["warnings"].as_array().unwrap().iter().any(|warning| warning.as_str().is_some_and(|text| text.contains("shader settings file"))));
|
||||
assert!(result["files"].as_array().unwrap().iter().any(|file| file.as_str().is_some_and(|name| name.ends_with(".png"))));
|
||||
|
||||
let error = tool_err(&client, "textures_export", json!({"dir": "invalid", "shaderParameters": [99]})).await;
|
||||
|
||||
assert!(error.contains("shaderParameters"));
|
||||
assert!(!dir.join("invalid").exists());
|
||||
|
||||
shutdown(client, server).await;
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
fn top(s: &Value) -> &Value {
|
||||
|
||||
@@ -57,9 +57,10 @@ fn display_all(session: &mut Session) -> usize {
|
||||
let tiles = session.take_uploads(texture_set);
|
||||
let baked = session.baked(texture_set).cloned().unwrap_or_default();
|
||||
let composite = &session.caches[texture_set].composite;
|
||||
let ao_mixing = session.doc.project.texture_sets[texture_set].ao_mixing;
|
||||
bytes += tiles
|
||||
.par_iter()
|
||||
.flat_map_iter(|&(tile_x, tile_y)| DisplayKind::ALL.map(|kind| tile_bytes(composite, &baked, kind, tile_x, tile_y).len()))
|
||||
.flat_map_iter(|&(tile_x, tile_y)| DisplayKind::ALL.map(|kind| tile_bytes(composite, &baked, ao_mixing, kind, tile_x, tile_y).len()))
|
||||
.sum::<usize>();
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use crate::cage::RayFrame;
|
||||
use crate::map::BakeContext;
|
||||
use crate::tracing::{CpuTracer, Tracer};
|
||||
use crate::{BakeError, BakeOutput, BakeRequest, MeshExtent, Progress};
|
||||
use crate::{BakeError, BakeOutput, BakeRequest, MeshExtent, Progress, RegionBake};
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
use texturecraft_core::{BakeSettings, BakedMap};
|
||||
|
||||
@@ -23,10 +23,22 @@ impl<'a> BakePasses<'a> {
|
||||
progress: &Progress,
|
||||
excluded_tiles: &[(u32, u32)],
|
||||
tracer: Option<&dyn Tracer>,
|
||||
) -> Result<BakeOutput, BakeError> {
|
||||
self.bake_map_in(map, progress, excluded_tiles, None, tracer)
|
||||
}
|
||||
|
||||
/// [`BakePasses::bake_map`] sampling only `region`'s texels, as [`crate::bake_tiles_in`] does
|
||||
pub fn bake_map_in(
|
||||
&mut self,
|
||||
map: BakedMap,
|
||||
progress: &Progress,
|
||||
excluded_tiles: &[(u32, u32)],
|
||||
region: Option<RegionBake>,
|
||||
tracer: Option<&dyn Tracer>,
|
||||
) -> Result<BakeOutput, BakeError> {
|
||||
let mut settings = self.request.settings.clone();
|
||||
settings.maps.select([map]);
|
||||
self.run(&settings, progress, excluded_tiles, tracer, super::STRIP_TEXELS)
|
||||
self.run(&settings, progress, excluded_tiles, region, tracer, super::STRIP_TEXELS)
|
||||
}
|
||||
|
||||
pub(super) fn run(
|
||||
@@ -34,6 +46,7 @@ impl<'a> BakePasses<'a> {
|
||||
settings: &BakeSettings,
|
||||
progress: &Progress,
|
||||
excluded_tiles: &[(u32, u32)],
|
||||
region: Option<RegionBake>,
|
||||
tracer: Option<&dyn Tracer>,
|
||||
strip_texels: usize,
|
||||
) -> Result<BakeOutput, BakeError> {
|
||||
@@ -56,7 +69,7 @@ impl<'a> BakePasses<'a> {
|
||||
}
|
||||
};
|
||||
let context = BakeContext::with_frame(&request, *extent, frame);
|
||||
let bake = |tracer: &dyn Tracer| super::bake_prepared(&request, &context, progress, strip_texels, tracer, excluded_tiles);
|
||||
let bake = |tracer: &dyn Tracer| super::bake_prepared(&request, &context, progress, strip_texels, tracer, excluded_tiles, region);
|
||||
match tracer {
|
||||
Some(tracer) => match bake(tracer) {
|
||||
Err(BakeError::Tracer(error)) => {
|
||||
|
||||
+55
-6
@@ -12,6 +12,8 @@ mod high_poly;
|
||||
mod mesh_extent;
|
||||
mod name_pair;
|
||||
mod progress;
|
||||
mod region_bake;
|
||||
mod texel_box;
|
||||
|
||||
pub use bake_error::BakeError;
|
||||
pub use bake_output::BakeOutput;
|
||||
@@ -22,6 +24,8 @@ pub use high_poly::HighPoly;
|
||||
pub(crate) use mesh_extent::MeshExtent;
|
||||
pub use name_pair::NamePair;
|
||||
pub use progress::Progress;
|
||||
pub use region_bake::{RegionBake, region_keeps_pixels};
|
||||
pub use texel_box::TexelBox;
|
||||
|
||||
mod map;
|
||||
mod skew;
|
||||
@@ -50,6 +54,8 @@ const STRIP_TEXELS: usize = 1 << 24;
|
||||
const BATCH: usize = 1 << 18;
|
||||
// Curvature batches stay small so progress and cancellation remain responsive
|
||||
const CURVATURE_BATCH: usize = 1 << 15;
|
||||
/// Smallest mesh extent the maps are normalized by, so a flat mesh never divides by zero
|
||||
const MIN_MESH_EXTENT: f32 = 1e-6;
|
||||
|
||||
fn validate(request: &BakeRequest) -> Result<(), BakeError> {
|
||||
let settings = request.settings;
|
||||
@@ -161,7 +167,18 @@ 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<BakeOutput, BakeError> {
|
||||
BakePasses::new(*request).run(request.settings, progress, excluded_tiles, tracer, STRIP_TEXELS)
|
||||
bake_tiles_in(request, progress, excluded_tiles, None, tracer)
|
||||
}
|
||||
|
||||
/// [`bake_tiles`] sampling only `region`'s texels and padding a whole map; equal to a whole bake for [`region_keeps_pixels`] maps
|
||||
pub fn bake_tiles_in(
|
||||
request: &BakeRequest,
|
||||
progress: &Progress,
|
||||
excluded_tiles: &[(u32, u32)],
|
||||
region: Option<RegionBake>,
|
||||
tracer: Option<&dyn Tracer>,
|
||||
) -> Result<BakeOutput, BakeError> {
|
||||
BakePasses::new(*request).run(request.settings, progress, excluded_tiles, region, tracer, STRIP_TEXELS)
|
||||
}
|
||||
|
||||
type OutRow<'a> = Vec<&'a mut [f32]>;
|
||||
@@ -173,8 +190,9 @@ fn bake_in_strips(
|
||||
strip_texels: usize,
|
||||
tracer: &dyn Tracer,
|
||||
excluded_tiles: &[(u32, u32)],
|
||||
region: Option<RegionBake>,
|
||||
) -> Result<BakeOutput, BakeError> {
|
||||
BakePasses::new(*request).run(request.settings, progress, excluded_tiles, Some(tracer), strip_texels)
|
||||
BakePasses::new(*request).run(request.settings, progress, excluded_tiles, region, Some(tracer), strip_texels)
|
||||
}
|
||||
|
||||
fn bake_prepared(
|
||||
@@ -184,6 +202,7 @@ fn bake_prepared(
|
||||
strip_texels: usize,
|
||||
tracer: &dyn Tracer,
|
||||
excluded_tiles: &[(u32, u32)],
|
||||
region: Option<RegionBake>,
|
||||
) -> Result<BakeOutput, BakeError> {
|
||||
if progress.cancel.load(Relaxed) {
|
||||
return Err(BakeError::Cancelled);
|
||||
@@ -211,7 +230,7 @@ fn bake_prepared(
|
||||
let mut padding_map = None;
|
||||
let total_rows = height.max(1) as u64;
|
||||
let mut rows_done = 0u64;
|
||||
let strip_error = || BakeError::Invalid("strip output of range".into());
|
||||
let strip_error = || BakeError::Invalid("strip output out of range".into());
|
||||
|
||||
let (sample_width, sample_height) = (width * samples_per_axis, height * samples_per_axis);
|
||||
let rows_per_strip = (strip_texels / (sample_width * samples_per_axis)).max(1).min(height);
|
||||
@@ -250,6 +269,16 @@ fn bake_prepared(
|
||||
}
|
||||
});
|
||||
|
||||
// Coverage stays the whole map's, so padding matches a whole bake; only the region is sampled
|
||||
if let Some(region) = region {
|
||||
for (row_index, row) in gbuffer.tri.chunks_mut(sample_width).enumerate() {
|
||||
let y = (sample_start_y + row_index) / samples_per_axis;
|
||||
for outside in region.texels.outside_row(y, samples_per_axis, row.len()) {
|
||||
row.get_mut(outside).unwrap_or_default().fill(NO_TRI);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut output_rows: Vec<OutRow> = (0..rows).map(|_| Vec::with_capacity(maps.len())).collect();
|
||||
for (map, data) in maps.iter().zip(buffers.iter_mut()) {
|
||||
let component_count = map.components();
|
||||
@@ -258,6 +287,7 @@ fn bake_prepared(
|
||||
row.push(chunk);
|
||||
}
|
||||
}
|
||||
|
||||
let mut bake_strip = || {
|
||||
for (batch_index, batch) in output_rows.chunks_mut(rows_per_batch).enumerate() {
|
||||
if progress.cancel.load(Relaxed) {
|
||||
@@ -276,10 +306,11 @@ fn bake_prepared(
|
||||
(width, samples_per_axis, sample_start_y * sample_width),
|
||||
)?;
|
||||
rows_done += batch.len() as u64;
|
||||
progress.done.store((rows_done.saturating_mul(10_000) / total_rows).min(10_000) as u32, Relaxed);
|
||||
progress.done.store((rows_done.saturating_mul(u64::from(Progress::DONE)) / total_rows).min(u64::from(Progress::DONE)) as u32, Relaxed);
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
|
||||
if strip_start + rows < height || (settings.common.dilation == 0 && !settings.common.apply_diffusion) {
|
||||
bake_strip()?;
|
||||
} else {
|
||||
@@ -291,6 +322,22 @@ fn bake_prepared(
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(region) = region {
|
||||
for (map, pixels) in maps.iter().zip(buffers.iter_mut()) {
|
||||
let previous = region.previous.get(map).filter(|previous| previous.len() == pixels.len());
|
||||
let previous = previous.ok_or_else(|| BakeError::Invalid(format!("no whole {} map of this size to bake a region of", map.id())))?;
|
||||
let components = map.components();
|
||||
let row_len = (width * components).max(1);
|
||||
for (y, (row, kept)) in pixels.chunks_exact_mut(row_len).zip(previous.chunks_exact(row_len)).enumerate() {
|
||||
for outside in region.texels.outside_row(y, components, row_len) {
|
||||
if let (Some(row), Some(kept)) = (row.get_mut(outside.clone()), kept.get(outside)) {
|
||||
row.copy_from_slice(kept);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut output: BTreeMap<BakedMap, Vec<f32>> = maps.into_iter().zip(buffers).collect();
|
||||
if from_normal {
|
||||
let world_normal =
|
||||
@@ -306,7 +353,8 @@ fn bake_prepared(
|
||||
}
|
||||
|
||||
let (bounds_min, bounds_max) = request.mesh.bounds();
|
||||
map::normalize(&mut output, &covered, width, tile_size, settings, (bounds_max - bounds_min).max_element().max(1e-6));
|
||||
map::normalize(&mut output, &covered, width, tile_size, settings, (bounds_max - bounds_min).max_element().max(MIN_MESH_EXTENT));
|
||||
|
||||
if let Some(padding_map) = padding_map {
|
||||
for (map, data) in output.iter_mut() {
|
||||
padding_map.apply(data, map.components());
|
||||
@@ -315,11 +363,12 @@ fn bake_prepared(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if progress.cancel.load(Relaxed) {
|
||||
return Err(BakeError::Cancelled);
|
||||
}
|
||||
|
||||
progress.done.store(10_000, Relaxed);
|
||||
progress.done.store(Progress::DONE, Relaxed);
|
||||
Ok(BakeOutput { resolution: width as u32, height: height as u32, maps: output, tracer: tracer.name() })
|
||||
}
|
||||
|
||||
|
||||
@@ -8,12 +8,15 @@ pub struct Progress {
|
||||
}
|
||||
|
||||
impl Progress {
|
||||
/// The basis points of a finished bake
|
||||
pub const DONE: u32 = 10_000;
|
||||
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
pub fn fraction(&self) -> f32 {
|
||||
self.done.load(Relaxed).min(10_000) as f32 / 10_000.0
|
||||
self.done.load(Relaxed).min(Self::DONE) as f32 / Self::DONE as f32
|
||||
}
|
||||
|
||||
pub fn cancel(&self) {
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
use texturecraft_core::BakedMap;
|
||||
|
||||
use crate::TexelBox;
|
||||
|
||||
/// A bake that samples only `texels` and takes every other texel from `previous`, a whole bake of the same size
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct RegionBake<'a> {
|
||||
pub texels: TexelBox,
|
||||
pub previous: &'a BTreeMap<BakedMap, Arc<Vec<f32>>>,
|
||||
}
|
||||
|
||||
/// Whether a region bake gives `map` a whole bake's pixels: not for maps scaled by their whole range or read from neighbours
|
||||
pub fn region_keeps_pixels(map: BakedMap) -> bool {
|
||||
!matches!(map, BakedMap::Curvature | BakedMap::Height | BakedMap::Thickness)
|
||||
}
|
||||
@@ -28,11 +28,13 @@ fn excluded_tiles_match_across_strips_antialiasing_and_cpu_fallback() {
|
||||
cage_paint: None,
|
||||
tiles: (2, 1),
|
||||
};
|
||||
|
||||
let full = bake(&request, &Progress::new()).unwrap();
|
||||
for excluded in [[(0, 0)], [(1, 0)]] {
|
||||
let partial = bake_tiles(&request, &Progress::new(), &excluded, None).unwrap();
|
||||
let strips = bake_in_strips(&request, &Progress::new(), 512, &CpuTracer, &excluded).unwrap();
|
||||
let strips = bake_in_strips(&request, &Progress::new(), 512, &CpuTracer, &excluded, None).unwrap();
|
||||
let fallback = bake_tiles(&request, &Progress::new(), &excluded, Some(&Broken)).unwrap();
|
||||
|
||||
assert_eq!(strips.maps, partial.maps);
|
||||
assert_eq!(fallback.maps, partial.maps);
|
||||
assert!(fallback.tracer.contains("Broken unavailable"));
|
||||
|
||||
+14
-12
@@ -365,9 +365,9 @@ fn two_runs_are_identical_and_sized() {
|
||||
|
||||
#[test]
|
||||
fn strips_match_a_single_pass() {
|
||||
let m = primitives::material_ball();
|
||||
let bvh = Bvh::new(&m);
|
||||
let s = with_rays(
|
||||
let mesh = primitives::material_ball();
|
||||
let bvh = Bvh::new(&mesh);
|
||||
let bake_settings = with_rays(
|
||||
{
|
||||
let mut base = settings(64, &[]);
|
||||
base.common = CommonBakeSettings { antialiasing: BakeAntialiasing::Subsampling2x2, ..base.common };
|
||||
@@ -377,24 +377,26 @@ fn strips_match_a_single_pass() {
|
||||
4,
|
||||
0.25,
|
||||
);
|
||||
let req = BakeRequest {
|
||||
let request = BakeRequest {
|
||||
low_base_color: &[],
|
||||
mesh: &m,
|
||||
mesh: &mesh,
|
||||
bvh: &bvh,
|
||||
material: 0,
|
||||
settings: &s,
|
||||
settings: &bake_settings,
|
||||
high: None,
|
||||
cage: None,
|
||||
skew: None,
|
||||
cage_paint: None,
|
||||
tiles: (1, 1),
|
||||
};
|
||||
let whole = bake(&req, &Progress::new()).unwrap();
|
||||
let strips = bake_in_strips(&req, &Progress::new(), 128 * 2, &CpuTracer, &[]).unwrap();
|
||||
for (map, a) in &whole.maps {
|
||||
let b = &strips.maps[map];
|
||||
let off = a.iter().zip(b).filter(|(a, b)| (*a - *b).abs() > 1e-3).count();
|
||||
assert!(off * 200 < a.len(), "{map:?}: {off} of {} differ", a.len());
|
||||
|
||||
let whole = bake(&request, &Progress::new()).unwrap();
|
||||
let strips = bake_in_strips(&request, &Progress::new(), 128 * 2, &CpuTracer, &[], None).unwrap();
|
||||
|
||||
for (map, whole_pixels) in &whole.maps {
|
||||
let strip_pixels = &strips.maps[map];
|
||||
let differences = whole_pixels.iter().zip(strip_pixels).filter(|(whole, strip)| (*whole - *strip).abs() > 1e-3).count();
|
||||
assert!(differences * 200 < whole_pixels.len(), "{map:?}: {differences} of {} differ", whole_pixels.len());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
use std::ops::Range;
|
||||
|
||||
/// A rectangle of output texels, from `min` (inclusive) to `max` (exclusive), in atlas pixels
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct TexelBox {
|
||||
pub min: (u32, u32),
|
||||
pub max: (u32, u32),
|
||||
}
|
||||
|
||||
impl TexelBox {
|
||||
/// Whether texel (`x`, `y`) lies inside the box
|
||||
pub fn contains(&self, x: usize, y: usize) -> bool {
|
||||
(self.min.0 as usize..self.max.0 as usize).contains(&x) && (self.min.1 as usize..self.max.1 as usize).contains(&y)
|
||||
}
|
||||
|
||||
/// The items of texel row `y` outside the box, in a row of `len` items with `scale` items per texel: those before the box and those after it
|
||||
pub fn outside_row(&self, y: usize, scale: usize, len: usize) -> [Range<usize>; 2] {
|
||||
let (start, end) = match (self.min.1 as usize..self.max.1 as usize).contains(&y) {
|
||||
true => ((self.min.0 as usize * scale).min(len), (self.max.0 as usize * scale).min(len)),
|
||||
false => (len, len),
|
||||
};
|
||||
[0..start, end.max(start)..len]
|
||||
}
|
||||
|
||||
/// The box grown by `texels` on every side, kept inside a `width` x `height` image
|
||||
pub fn grown(&self, texels: u32, width: u32, height: u32) -> TexelBox {
|
||||
TexelBox {
|
||||
min: (self.min.0.saturating_sub(texels), self.min.1.saturating_sub(texels)),
|
||||
max: (self.max.0.saturating_add(texels).min(width), self.max.1.saturating_add(texels).min(height)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_items_outside_a_row_are_the_ones_contains_leaves_out() {
|
||||
let (width, scale) = (6, 2);
|
||||
let boxes = [
|
||||
TexelBox { min: (1, 1), max: (4, 3) },
|
||||
TexelBox { min: (0, 0), max: (6, 4) },
|
||||
TexelBox { min: (3, 1), max: (9, 2) },
|
||||
TexelBox { min: (4, 1), max: (2, 3) },
|
||||
];
|
||||
for texels in boxes {
|
||||
for y in 0..4 {
|
||||
let outside = texels.outside_row(y, scale, width * scale);
|
||||
for item in 0..width * scale {
|
||||
let is_outside = outside.iter().any(|range| range.contains(&item));
|
||||
assert_eq!(is_outside, !texels.contains(item / scale, y), "{texels:?} row {y} item {item}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
//! What a channel's storage format keeps of a composited value
|
||||
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use texturecraft_core::{ChannelFormat, lum};
|
||||
use texturecraft_texel::{linear_to_srgb, srgb_to_linear};
|
||||
|
||||
/// What `value` keeps in `format`: 8-bit = 256 steps (sRGB8 gamma-spaced), L = grey, others = the tiles' 16 bits; `signed` = stored offset into 0..1
|
||||
pub(crate) fn stored(format: ChannelFormat, signed: bool, mut value: [f32; 3], components: usize) -> [f32; 3] {
|
||||
if format.is_grey() && components == 3 {
|
||||
value = [lum(value); 3];
|
||||
}
|
||||
value.map(|component| stored_value(format, signed, component))
|
||||
}
|
||||
|
||||
fn stored_value(format: ChannelFormat, signed: bool, component: f32) -> f32 {
|
||||
let value = if signed { component * 0.5 + 0.5 } else { component };
|
||||
let unit = |unit_value: f32| if signed { unit_value * 2.0 - 1.0 } else { unit_value };
|
||||
let step = |unit_value: f32| (unit_value.clamp(0.0, 1.0) * 255.0).round();
|
||||
match format {
|
||||
ChannelFormat::Rgb8 | ChannelFormat::L8 => unit(step(value) / 255.0),
|
||||
ChannelFormat::Srgb8 => unit(srgb8_linear().get(step(linear_to_srgb(value.clamp(0.0, 1.0))) as usize).copied().unwrap_or(0.0)),
|
||||
ChannelFormat::L16 | ChannelFormat::Rgb16 | ChannelFormat::L16F | ChannelFormat::Rgb16F | ChannelFormat::L32F | ChannelFormat::Rgb32F => component,
|
||||
}
|
||||
}
|
||||
|
||||
/// The linear value of each 8-bit sRGB step, so storing a colour decodes no sRGB per texel
|
||||
fn srgb8_linear() -> &'static [f32; 256] {
|
||||
static LINEAR: OnceLock<[f32; 256]> = OnceLock::new();
|
||||
LINEAR.get_or_init(|| std::array::from_fn(|step| srgb_to_linear(step as f32 / 255.0)))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn eight_bit_formats_keep_256_steps_and_sixteen_bit_ones_everything() {
|
||||
let x = 0.3_f32 + 1.0 / 1024.0;
|
||||
let eight = stored(ChannelFormat::L8, false, [x; 3], 1)[0];
|
||||
|
||||
assert!((eight * 255.0 - (eight * 255.0).round()).abs() < 1e-4, "on a 1/255 step");
|
||||
assert!((eight - x).abs() > 1e-4 && (eight - x).abs() <= 0.5 / 255.0 + 1e-6);
|
||||
assert_eq!(stored(ChannelFormat::L16, false, [x; 3], 1)[0], x);
|
||||
assert_eq!(stored(ChannelFormat::Rgb32F, true, [-x; 3], 1)[0], -x);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn srgb8_keeps_more_of_the_darks_than_rgb8() {
|
||||
let dark = 0.002_f32;
|
||||
let srgb = stored(ChannelFormat::Srgb8, false, [dark; 3], 3)[0];
|
||||
let linear = stored(ChannelFormat::Rgb8, false, [dark; 3], 3)[0];
|
||||
|
||||
assert!((srgb - dark).abs() < (linear - dark).abs());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn srgb8_keeps_the_same_steps_as_decoding_each_one() {
|
||||
for value in (0..=1000).map(|step| step as f32 / 1000.0) {
|
||||
let decoded = srgb_to_linear((linear_to_srgb(value) * 255.0).round() / 255.0);
|
||||
|
||||
assert_eq!(stored(ChannelFormat::Srgb8, false, [value; 3], 3)[0], decoded, "at {value}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grey_formats_turn_colours_grey_and_signed_values_keep_their_sign() {
|
||||
let grey = stored(ChannelFormat::L16, false, [1.0, 0.0, 0.0], 3);
|
||||
|
||||
assert!(grey[0] == grey[1] && grey[1] == grey[2] && grey[0] > 0.0 && grey[0] < 1.0);
|
||||
assert_eq!(stored(ChannelFormat::Rgb16, false, [1.0, 0.0, 0.0], 3), [1.0, 0.0, 0.0]);
|
||||
|
||||
let low = stored(ChannelFormat::L8, true, [-0.5; 3], 1)[0];
|
||||
assert!(low < -0.49 && low > -0.51);
|
||||
}
|
||||
}
|
||||
@@ -25,7 +25,7 @@
|
||||
//! the extra lobes off, so the renderer can keep Lobes and Sheen as 1×1 placeholders until a
|
||||
//! tile with a non-default value arrives.
|
||||
|
||||
use texturecraft_core::{BakedMap, Channel};
|
||||
use texturecraft_core::{AoMixing, BakedMap, Channel};
|
||||
use texturecraft_texel::{TILE, TILE_AREA, srgb_lut};
|
||||
|
||||
use crate::eval::Composite;
|
||||
@@ -93,7 +93,7 @@ impl DisplayKind {
|
||||
|
||||
/// The texel of a set that has none of this texture's channels (the GPU clear value).
|
||||
pub fn default_texel(self) -> Vec<u8> {
|
||||
let mut px = tile_bytes(&Composite::new(&[], TILE), &BakedMaps::default(), self, 0, 0);
|
||||
let mut px = tile_bytes(&Composite::new(&[], TILE), &BakedMaps::default(), AoMixing::Multiply, self, 0, 0);
|
||||
px.truncate(self.bytes_per_texel());
|
||||
px
|
||||
}
|
||||
@@ -110,8 +110,8 @@ fn u8_of(v: u16) -> u8 {
|
||||
(v >> 8) as u8
|
||||
}
|
||||
|
||||
/// Tile bytes (`TILE × TILE`, row-major) for `kind`, using channel defaults for absent source tiles.
|
||||
pub fn tile_bytes(composite: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u32, ty: u32) -> Vec<u8> {
|
||||
/// Tile bytes (`TILE × TILE`, row-major) for `kind` mixing baked occlusion by `ao_mixing`, with channel defaults for absent source tiles
|
||||
pub fn tile_bytes(composite: &Composite, baked: &BakedMaps, ao_mixing: AoMixing, kind: DisplayKind, tx: u32, ty: u32) -> Vec<u8> {
|
||||
let bytes_per_texel = kind.bytes_per_texel();
|
||||
let mut out = vec![0u8; TILE_AREA * bytes_per_texel];
|
||||
let srgb = srgb_lut();
|
||||
@@ -183,9 +183,12 @@ pub fn tile_bytes(composite: &Composite, baked: &BakedMaps, kind: DisplayKind, t
|
||||
|
||||
for i in 0..TILE_AREA {
|
||||
let (x, y) = (tx * TILE + (i as u32 % TILE), ty * TILE + (i as u32 / TILE));
|
||||
let baked_ao = baked
|
||||
.sample_working(BakedMap::AmbientOcclusion, x, y, (resolution, composite.height), &composite.block_scales)
|
||||
.map_or(1.0, |value| value[0]);
|
||||
let baked_ao = match ao_mixing {
|
||||
AoMixing::Multiply => baked
|
||||
.sample_working(BakedMap::AmbientOcclusion, x, y, (resolution, composite.height), &composite.block_scales)
|
||||
.map_or(1.0, |value| value[0]),
|
||||
AoMixing::None => 1.0,
|
||||
};
|
||||
let ch_ao = ao.and_then(|a| a.get(i)).map(|v| *v as f32 / 65535.0).unwrap_or(1.0);
|
||||
|
||||
let pixel = &mut out[i * 4..i * 4 + 4];
|
||||
@@ -263,7 +266,7 @@ mod tests {
|
||||
}
|
||||
for kind in DisplayKind::ALL.into_iter().filter(|k| !kinds_for(channels).any(|n| n == *k)) {
|
||||
let want = kind.default_texel().repeat(TILE_AREA);
|
||||
assert!(tile_bytes(&comp, &BakedMaps::default(), kind, 0, 0) == want, "{kind:?} for {channels:?}");
|
||||
assert!(tile_bytes(&comp, &BakedMaps::default(), AoMixing::Multiply, kind, 0, 0) == want, "{kind:?} for {channels:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -274,7 +277,7 @@ mod tests {
|
||||
comp.channels.get_mut(&Channel::BaseColor).unwrap().set(0, 0, &[to_u16(1.0), to_u16(0.5), 0]);
|
||||
comp.channels.get_mut(&Channel::Opacity).unwrap().set(0, 0, &[to_u16(0.5)]);
|
||||
|
||||
let b = tile_bytes(&comp, &BakedMaps::default(), DisplayKind::BaseColor, 0, 0);
|
||||
let b = tile_bytes(&comp, &BakedMaps::default(), AoMixing::Multiply, DisplayKind::BaseColor, 0, 0);
|
||||
|
||||
assert_eq!(b[0], 255);
|
||||
assert!((b[1] as i32 - 188).abs() <= 1, "{}", b[1]);
|
||||
@@ -288,7 +291,7 @@ mod tests {
|
||||
set.uv_tiles = vec![1001, 1002];
|
||||
set.tile_resolutions.insert(1002, 64);
|
||||
let comp = Composite { block_scales: set.block_scales(), ..Composite::new(&[], 512) };
|
||||
let alpha = |tx: u32| tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Extra, tx, 0)[3];
|
||||
let alpha = |tx: u32| tile_bytes(&comp, &BakedMaps::default(), AoMixing::Multiply, DisplayKind::Extra, tx, 0)[3];
|
||||
|
||||
// Tile 1001 fills its block; 1002 fills a quarter, encoded as 32 × log2(4)
|
||||
assert_eq!((alpha(0), alpha(3), alpha(4), alpha(7)), (0, 0, 64, 64));
|
||||
@@ -297,20 +300,28 @@ mod tests {
|
||||
#[test]
|
||||
fn missing_channels_fall_back_to_defaults() {
|
||||
let comp = Composite::new(&[], 64);
|
||||
let orm = tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Orm, 0, 0);
|
||||
let orm = tile_bytes(&comp, &BakedMaps::default(), AoMixing::Multiply, DisplayKind::Orm, 0, 0);
|
||||
|
||||
assert_eq!(&orm[..4], &[255, 128, 0, 128]);
|
||||
assert_eq!(normal_texel(&comp, &BakedMaps::default(), 0), [0.0, 0.0, 1.0, 0.5], "flat, sheen roughness 0.5 rides in alpha");
|
||||
assert_eq!(&tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Emissive, 0, 0)[..4], &[0, 0, 0, 0]);
|
||||
assert_eq!(&tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Lobes, 0, 0)[..4], &[0, 25, 0, 0], "lobes off, coat roughness 0.1");
|
||||
assert_eq!(&tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Sheen, 0, 0)[..4], &[255, 255, 255, 0]);
|
||||
assert_eq!(&tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Extra, 0, 0)[..4], &[128, 128, 0, 0], "flat coat normal, no transmission");
|
||||
assert_eq!(&tile_bytes(&comp, &BakedMaps::default(), AoMixing::Multiply, DisplayKind::Emissive, 0, 0)[..4], &[0, 0, 0, 0]);
|
||||
assert_eq!(
|
||||
&tile_bytes(&comp, &BakedMaps::default(), AoMixing::Multiply, DisplayKind::Lobes, 0, 0)[..4],
|
||||
&[0, 25, 0, 0],
|
||||
"lobes off, coat roughness 0.1"
|
||||
);
|
||||
assert_eq!(&tile_bytes(&comp, &BakedMaps::default(), AoMixing::Multiply, DisplayKind::Sheen, 0, 0)[..4], &[255, 255, 255, 0]);
|
||||
assert_eq!(
|
||||
&tile_bytes(&comp, &BakedMaps::default(), AoMixing::Multiply, DisplayKind::Extra, 0, 0)[..4],
|
||||
&[128, 128, 0, 0],
|
||||
"flat coat normal, no transmission"
|
||||
);
|
||||
|
||||
for k in DisplayKind::ALL {
|
||||
assert_eq!(k.default_texel(), tile_bytes(&comp, &BakedMaps::default(), k, 3, 5)[..k.bytes_per_texel()]);
|
||||
assert_eq!(k.default_texel(), tile_bytes(&comp, &BakedMaps::default(), AoMixing::Multiply, k, 3, 5)[..k.bytes_per_texel()]);
|
||||
}
|
||||
|
||||
let h = tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Height, 0, 0);
|
||||
let h = tile_bytes(&comp, &BakedMaps::default(), AoMixing::Multiply, DisplayKind::Height, 0, 0);
|
||||
assert_eq!(h.len(), TILE_AREA * 8);
|
||||
assert_eq!(half::f16::from_le_bytes([h[2], h[3]]).to_f32(), half::f16::from_f32(0.04).to_f32(), "default F0");
|
||||
}
|
||||
@@ -339,7 +350,7 @@ mod tests {
|
||||
|
||||
/// Decode texel `i` of the Normal display tile (0, 0).
|
||||
fn normal_texel(comp: &Composite, baked: &BakedMaps, i: usize) -> [f32; 4] {
|
||||
let bytes = tile_bytes(comp, baked, DisplayKind::Normal, 0, 0);
|
||||
let bytes = tile_bytes(comp, baked, AoMixing::Multiply, DisplayKind::Normal, 0, 0);
|
||||
[0, 1, 2, 3].map(|k| half::f16::from_le_bytes([bytes[i * 8 + k * 2], bytes[i * 8 + k * 2 + 1]]).to_f32())
|
||||
}
|
||||
|
||||
@@ -374,11 +385,11 @@ mod tests {
|
||||
comp.channels.get_mut(&Channel::Glossiness).unwrap().set(0, 0, &[to_u16(0.8)]);
|
||||
comp.channels.get_mut(&Channel::Specular).unwrap().set(0, 0, &[to_u16(1.0), to_u16(0.5), 0]);
|
||||
|
||||
let orm = tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Orm, 0, 0);
|
||||
let orm = tile_bytes(&comp, &BakedMaps::default(), AoMixing::Multiply, DisplayKind::Orm, 0, 0);
|
||||
|
||||
assert!((orm[1] as i32 - 51).abs() <= 1, "roughness = 1 - 0.8, got {}", orm[1]);
|
||||
|
||||
let h = tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Height, 0, 0);
|
||||
let h = tile_bytes(&comp, &BakedMaps::default(), AoMixing::Multiply, DisplayKind::Height, 0, 0);
|
||||
let at = |k: usize| half::f16::from_le_bytes([h[k * 2], h[k * 2 + 1]]).to_f32();
|
||||
|
||||
assert_eq!(at(0), 0.0);
|
||||
@@ -402,7 +413,7 @@ mod tests {
|
||||
set(Channel::Transmission, &[to_u16(0.6)]);
|
||||
set(Channel::CoatNormal, &[to_u16(1.0), to_u16(0.5), to_u16(1.0)]);
|
||||
|
||||
let px = |k: DisplayKind| tile_bytes(&comp, &BakedMaps::default(), k, 0, 0)[4..8].to_vec();
|
||||
let px = |k: DisplayKind| tile_bytes(&comp, &BakedMaps::default(), AoMixing::Multiply, k, 0, 0)[4..8].to_vec();
|
||||
let near = |a: &[u8], b: &[u8]| a.iter().zip(b).all(|(x, y)| x.abs_diff(*y) <= 1);
|
||||
|
||||
assert!(near(&px(DisplayKind::Lobes), &[255, 51, 153, 64]), "{:?}", px(DisplayKind::Lobes));
|
||||
|
||||
+380
-140
@@ -12,16 +12,16 @@ use std::sync::Arc;
|
||||
|
||||
use rayon::prelude::*;
|
||||
use texturecraft_core::{
|
||||
AnisotropicKuwahara, BakedMap, Bevel, BevelSmooth, BlendMode, BlockScales, Channel, ChannelKind, ColorMatch, CompareSource, ContentsOffset,
|
||||
AnisotropicKuwahara, BakedMap, Bevel, BevelSmooth, BlendMode, BlockScales, Channel, ChannelFormat, 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,
|
||||
GrayscaleConversionParameters, HeightMask, HeightToNormal, HeightToNormalMethod, 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, Surface, UvGBuffer};
|
||||
use texturecraft_texel::{DilationMap, TILE, TILE_AREA, TileImage, from_u16, noise, to_u16, to_u16_signed};
|
||||
use texturecraft_texel::{TILE, TILE_AREA, TileImage, from_u16, noise, to_u16, to_u16_signed};
|
||||
|
||||
use crate::ProjectorDepthCache;
|
||||
use crate::below::{Band, BelowCache, Level, StackKey};
|
||||
@@ -67,6 +67,9 @@ const MIN_BOUNDS_EXTENT: f32 = 1e-6;
|
||||
/// Stack values being composited, per channel.
|
||||
type Acc = [[f32; 3]; NCH];
|
||||
|
||||
/// What the live stroke's stencil lets through at a texel ([`Stencil::paint_world`])
|
||||
type StencilPaint = Option<(Option<[f32; 3]>, f32)>;
|
||||
|
||||
/// 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;
|
||||
|
||||
@@ -82,39 +85,66 @@ pub enum PaintTarget {
|
||||
Mask(LayerId),
|
||||
}
|
||||
|
||||
/// A screen-pinned image painted through the camera (projection tool / stencil).
|
||||
/// Smallest clip w a stencil paints at and smallest half extent it divides by
|
||||
const STENCIL_EPSILON: f32 = 1e-6;
|
||||
|
||||
/// Rec. 709 red, green and blue weights of a gray's luminance
|
||||
const REC709_LUMINANCE_WEIGHTS: [f32; 3] = [0.2126, 0.7152, 0.0722];
|
||||
|
||||
/// A screen-pinned image every brush tool paints through
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Stencil {
|
||||
pub image: std::sync::Arc<crate::store::ImageRes>,
|
||||
/// Camera view-projection captured when the stroke started.
|
||||
/// Camera view-projection captured when the stroke started
|
||||
pub view_proj: texturecraft_geom::glam::Mat4,
|
||||
/// Image placement in normalized device coordinates: center, half extents, rotation.
|
||||
/// Image placement in normalized device coordinates: center, half extents, rotation
|
||||
pub center: [f32; 2],
|
||||
pub half: [f32; 2],
|
||||
pub rotation: f32,
|
||||
/// Repeat the image beyond its bounds (otherwise nothing is painted outside it).
|
||||
/// Repeat the image beyond its bounds (otherwise nothing is painted outside it)
|
||||
pub tile: bool,
|
||||
/// The Projection tool paints the image's colors; every other tool paints through its gray
|
||||
pub colors: bool,
|
||||
}
|
||||
|
||||
impl Stencil {
|
||||
/// Linear color and alpha of the stencil at world point `p` (None outside the image).
|
||||
pub fn sample_world(&self, p: Vec3) -> Option<([f32; 3], f32)> {
|
||||
let c = self.view_proj * p.extend(1.0);
|
||||
if c.w <= 1e-6 {
|
||||
/// Linear color and alpha of the stencil at world point `point` (None outside the image)
|
||||
pub fn sample_world(&self, point: Vec3) -> Option<([f32; 3], f32)> {
|
||||
let sample = self.sample_raw(point)?;
|
||||
let rgb = [sample[0], sample[1], sample[2]];
|
||||
let rgb = if self.image.srgb { rgb.map(texturecraft_texel::srgb_to_linear) } else { rgb };
|
||||
Some((rgb, sample[3].clamp(0.0, 1.0)))
|
||||
}
|
||||
|
||||
/// How much paint passes at world point `point` when the stencil masks a stroke: its gray times its alpha, read as stored like a brush alpha image (0 outside the image)
|
||||
pub fn mask_world(&self, point: Vec3) -> f32 {
|
||||
let Some([red, green, blue, alpha]) = self.sample_raw(point) else { return 0.0 };
|
||||
let [red_weight, green_weight, blue_weight] = REC709_LUMINANCE_WEIGHTS;
|
||||
((red_weight * red + green_weight * green + blue_weight * blue) * alpha).clamp(0.0, 1.0)
|
||||
}
|
||||
|
||||
/// The paint a stroke receives at world point `point`: the stencil's color (Projection only) and the factor scaling the stroke there, None where nothing is painted
|
||||
pub fn paint_world(&self, point: Vec3) -> Option<(Option<[f32; 3]>, f32)> {
|
||||
if self.colors { self.sample_world(point).map(|(color, alpha)| (Some(color), alpha)) } else { Some((None, self.mask_world(point))) }
|
||||
}
|
||||
|
||||
/// The stored image value under world point `point` (None outside the image)
|
||||
fn sample_raw(&self, point: Vec3) -> Option<[f32; 4]> {
|
||||
let clip = self.view_proj * point.extend(1.0);
|
||||
if clip.w <= STENCIL_EPSILON {
|
||||
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);
|
||||
let ly = (dx * sn + dy * cs) / self.half[1].max(1e-6);
|
||||
if !self.tile && (lx.abs() > 1.0 || ly.abs() > 1.0) {
|
||||
let offset_x = clip.x / clip.w - self.center[0];
|
||||
let offset_y = clip.y / clip.w - self.center[1];
|
||||
let (sine, cosine) = (-self.rotation).sin_cos();
|
||||
let local_x = (offset_x * cosine - offset_y * sine) / self.half[0].max(STENCIL_EPSILON);
|
||||
let local_y = (offset_x * sine + offset_y * cosine) / self.half[1].max(STENCIL_EPSILON);
|
||||
if !self.tile && (local_x.abs() > 1.0 || local_y.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)))
|
||||
Some(self.image.sample(local_x * 0.5 + 0.5, 0.5 - local_y * 0.5))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -171,6 +201,12 @@ impl Inputs<'_> {
|
||||
self.gbuf.width / self.tile_grid().map_or(1, |g| g.cols.max(1))
|
||||
}
|
||||
|
||||
/// Texels across and down an atlas block
|
||||
fn block_size(&self) -> [u32; 2] {
|
||||
let (cols, rows) = self.tile_grid().map_or((1, 1), |g| (g.cols.max(1), g.rows.max(1)));
|
||||
[self.gbuf.width / cols, self.gbuf.height / rows]
|
||||
}
|
||||
|
||||
/// The current UV tile can occupy only part of its atlas block
|
||||
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)
|
||||
@@ -438,10 +474,10 @@ enum Op {
|
||||
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 `mirror` sends them in their tile
|
||||
Mirror { mirror: Mirror },
|
||||
/// 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 },
|
||||
Transform { transform: TileTransform, affine: ([[f32; 2]; 2], [f32; 2]) },
|
||||
/// 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`])
|
||||
@@ -498,11 +534,13 @@ fn neighbourhood_filters(effects: &[Effect], res: u32, channel: Option<Channel>)
|
||||
}
|
||||
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)))
|
||||
@@ -529,10 +567,11 @@ fn neighbourhood_filters(effects: &[Effect], res: u32, channel: Option<Channel>)
|
||||
}
|
||||
|
||||
// A mirror reads anywhere in its UV tile
|
||||
EffectKind::Filter(Filter::Mirror(mirror)) => Some((index, res as f32, Op::Mirror { mirror: *mirror, block: res })),
|
||||
EffectKind::Filter(Filter::Mirror(mirror)) => Some((index, res as f32, Op::Mirror { mirror: *mirror })),
|
||||
|
||||
// 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 }))
|
||||
Some((index, res as f32, Op::Transform { transform: *transform, affine: transform.affine() }))
|
||||
}
|
||||
|
||||
// Three box passes reach the band's width
|
||||
@@ -771,15 +810,15 @@ fn gather(
|
||||
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::Mirror { mirror } => {
|
||||
mirror_texel(&mirror, (x, y), (block_size, tile_size), 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::Transform { transform, affine } => transform_texel(&transform, affine, (x, y), (block_size, tile_size), &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);
|
||||
height_to_normal_texel(&filter, (x, y), (tile_size, 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);
|
||||
@@ -920,21 +959,18 @@ fn mean_region_color(data: &[f32], fallback: [f32; 3]) -> [f32; 3] {
|
||||
fn height_to_normal_texel(
|
||||
filter: &HeightToNormal,
|
||||
(x, y): (f32, f32),
|
||||
(res, center): (u32, &[f32]),
|
||||
(tile_size, center): ([u32; 2], &[f32]),
|
||||
acc: &mut [f32; 5],
|
||||
height: &dyn Fn(f32, f32) -> Option<f32>,
|
||||
) {
|
||||
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 slope = HeightToNormalMethod::Smooth.slope(|dx, dy| height(x + dx as f32, y + dy as f32).unwrap_or(own));
|
||||
let made = filter.normal_for_size(slope, tile_size).map(|value| value * 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;
|
||||
@@ -1164,21 +1200,14 @@ fn fxaa_texel((x, y): (f32, f32), comps: usize, center: &[f32], acc: &mut [f32;
|
||||
fn mirror_texel(
|
||||
mirror: &Mirror,
|
||||
(x, y): (f32, f32),
|
||||
(block, res): (u32, u32),
|
||||
(block, tile): ([u32; 2], [u32; 2]),
|
||||
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;
|
||||
let Some(([origin_x, origin_y], uv, size)) = tile_local((x, y), (block, tile)) else { return };
|
||||
let line = (Mirror::DEBUG_HALF_WIDTH * size[0] / FILTER_SIZE_RESOLUTION).max(MIN_FILTER_RADIUS) / size[0];
|
||||
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 };
|
||||
@@ -1192,30 +1221,35 @@ fn mirror_texel(
|
||||
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);
|
||||
let at = |origin: f32, along: f32, extent: f32| origin + (along * extent - 0.5).round().clamp(0.0, extent - 1.0);
|
||||
sample(at(origin_x, u, size[0]), at(origin_y, v, size[1]), 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
|
||||
/// The top left of texel `(x, y)`'s UV tile (`tile` texels at its `block`'s top left), the texel centre's UV in it and the tile's size, None past the tile
|
||||
fn tile_local((x, y): (f32, f32), (block, tile): ([u32; 2], [u32; 2])) -> Option<([f32; 2], [f32; 2], [f32; 2])> {
|
||||
let (block, size) = (block.map(|b| b.max(1) as f32), tile.map(|t| t.max(1) as f32));
|
||||
let origin = [(x / block[0]).floor() * block[0], (y / block[1]).floor() * block[1]];
|
||||
let local = [x - origin[0], y - origin[1]];
|
||||
if local[0] >= size[0] || local[1] >= size[1] {
|
||||
return None;
|
||||
}
|
||||
|
||||
Some((origin, [(local[0] + 0.5) / size[0], (local[1] + 0.5) / size[1]], size))
|
||||
}
|
||||
|
||||
/// 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 (`tile` texels per axis 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),
|
||||
(block, tile): ([u32; 2], [u32; 2]),
|
||||
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 Some(([origin_x, origin_y], uv, size)) = tile_local((x, y), (block, tile)) else { return };
|
||||
|
||||
// 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);
|
||||
let at = [0, 1].map(|axis| (columns[0][axis] * uv[0] + columns[1][axis] * uv[1] + shift[axis]) * size[axis] - 0.5);
|
||||
if !at.iter().all(|a| a.is_finite()) {
|
||||
return;
|
||||
}
|
||||
@@ -1230,7 +1264,7 @@ fn transform_texel(
|
||||
}
|
||||
|
||||
let (cx, cy) = (base_x + dx, base_y + dy);
|
||||
let inside = (0.0..size).contains(&cx) && (0.0..size).contains(&cy);
|
||||
let inside = (0.0..size[0]).contains(&cx) && (0.0..size[1]).contains(&cy);
|
||||
if !repeat && !inside {
|
||||
// Empty: no value, full weight
|
||||
total[4] += k;
|
||||
@@ -1239,7 +1273,7 @@ fn transform_texel(
|
||||
|
||||
// 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);
|
||||
sample(origin_x + cx.rem_euclid(size[0]), origin_y + cy.rem_euclid(size[1]), &mut one);
|
||||
for (slot, value) in total.iter_mut().zip(one) {
|
||||
*slot += value * k;
|
||||
}
|
||||
@@ -1596,11 +1630,17 @@ fn unpad(data: &[f32], comps: usize, (w, h): (usize, usize), (pad_x, pad_y): (us
|
||||
/// 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 };
|
||||
// Three box passes reach three radii and gathering filters reach one radius plus a bilinear texel
|
||||
// Mirror and transform can read across the whole block
|
||||
let reach = match op {
|
||||
Op::Mirror { .. } | Op::Transform { .. } => (radius_texels + 1).max(inputs.block_size().into_iter().max().unwrap_or(0)),
|
||||
_ if is_box_blur(op) => 3 * radius_texels,
|
||||
_ => radius_texels + 1,
|
||||
};
|
||||
|
||||
// A shadow also reads the shapes it was moved from
|
||||
let moved = match op {
|
||||
@@ -1615,7 +1655,7 @@ fn filter_extent(radius: f32, op: Op, inputs: &Inputs) -> (u32, u32) {
|
||||
_ => 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())
|
||||
inputs.tile_grid().map_or(longest_side, |_| inputs.block_size().into_iter().max().unwrap_or(0))
|
||||
} else {
|
||||
0
|
||||
};
|
||||
@@ -1825,7 +1865,7 @@ fn filter_region(
|
||||
|
||||
// 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),
|
||||
Some(_) => (inputs.block_size(), true),
|
||||
None => ([inputs.gbuf.width, inputs.gbuf.height], false),
|
||||
};
|
||||
let filtered = |scale: f32| -> Vec<f32> {
|
||||
@@ -1838,7 +1878,7 @@ fn filter_region(
|
||||
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) {
|
||||
let tile_size = if tiled { [tile_resolution; 2] } else { block_size };
|
||||
let tile_size = if tiled { block_size.map(|side| ((side as f32 * scale).round() as u32).max(1)) } else { block_size };
|
||||
return gather(
|
||||
op,
|
||||
(&stack_values, &cover, &grays),
|
||||
@@ -3015,6 +3055,8 @@ struct Texel<'a, 'b> {
|
||||
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)>,
|
||||
/// The live stroke's stencil sampled here once for every channel (None until a channel reads it)
|
||||
stencil_paint: Option<StencilPaint>,
|
||||
}
|
||||
|
||||
/// What a layer contributes (its mask, its content value and coverage per channel): evaluated
|
||||
@@ -3050,7 +3092,22 @@ 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(), below: None, lit: None, tape: Tape::Off, copy: None }
|
||||
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,
|
||||
stencil_paint: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Run `f` with `tape` as this texel's tape.
|
||||
@@ -3193,6 +3250,24 @@ impl<'a, 'b> Texel<'a, 'b> {
|
||||
self.surface((self.y * self.inp.gbuf.width + self.x) as usize).map(|s| s.pos)
|
||||
}
|
||||
|
||||
/// What the live stroke's `stencil` lets through here, sampled once for all of the texel's channels
|
||||
fn stencil_paint(&mut self, stencil: &Stencil) -> StencilPaint {
|
||||
let sample = |texel: &Self| texel.world().and_then(|world| stencil.paint_world(world));
|
||||
|
||||
// A symmetric fill's copy sees another surface point, so only the texel's own sample is kept
|
||||
if self.copy.is_some() {
|
||||
return sample(self);
|
||||
}
|
||||
|
||||
if let Some(paint) = self.stencil_paint {
|
||||
return paint;
|
||||
}
|
||||
|
||||
let paint = sample(self);
|
||||
self.stencil_paint = Some(paint);
|
||||
paint
|
||||
}
|
||||
|
||||
/// The surface at G-buffer index `i`, as the fill copy being sampled sees it
|
||||
#[inline(always)]
|
||||
fn surface(&self, i: usize) -> Option<Surface> {
|
||||
@@ -3286,9 +3361,11 @@ impl<'a, 'b> Texel<'a, 'b> {
|
||||
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)
|
||||
let block_width = (width / grid.cols.max(1)).max(1);
|
||||
let block_height = (height / grid.rows.max(1)).max(1);
|
||||
let scale = self.inp.block_scales.at(self.x, self.y);
|
||||
let tile_side = |block_side| ((block_side as f32 * scale).round() as u32).max(1);
|
||||
(self.x / block_width * block_width, self.y / block_height * block_height, tile_side(block_width), tile_side(block_height))
|
||||
} else {
|
||||
(0, 0, width, height)
|
||||
};
|
||||
@@ -3897,7 +3974,7 @@ impl<'a, 'b> Texel<'a, 'b> {
|
||||
self.mask_effects(plan, value, skip, plan.effects.len())
|
||||
}
|
||||
|
||||
/// Mask effects `from..to` of `plan` over `value`, recording the anchors among them.
|
||||
/// Mask effects `from..to` of `plan` over `value`, recording the anchors among them
|
||||
fn mask_effects(&mut self, plan: &MaskPlan, mut value: f32, from: usize, to: usize) -> f32 {
|
||||
// Avoid amplifying rounding error when unpremultiplying faint paint
|
||||
const MIN_PAINT_COVERAGE: f32 = 1e-5;
|
||||
@@ -3915,10 +3992,19 @@ impl<'a, 'b> Texel<'a, 'b> {
|
||||
Some(data) => (from_u16(data.get(self.o * 2).copied().unwrap_or(0)), from_u16(data.get(self.o * 2 + 1).copied().unwrap_or(0))),
|
||||
None => (0.0, 0.0),
|
||||
};
|
||||
|
||||
if effect.preview
|
||||
&& let Some(preview) = self.inp.preview
|
||||
{
|
||||
let stroke = (self.stroke * preview.opacity).clamp(0.0, 1.0);
|
||||
let mut stroke = (self.stroke * preview.opacity).clamp(0.0, 1.0);
|
||||
|
||||
// The stencil shapes the stroke as the commit does
|
||||
if let Some(stencil) = preview.stencil.as_ref()
|
||||
&& stroke > 0.0
|
||||
{
|
||||
stroke *= self.stencil_paint(stencil).map_or(0.0, |(_, factor)| factor);
|
||||
}
|
||||
|
||||
if preview.erase {
|
||||
painted *= 1.0 - stroke;
|
||||
coverage *= 1.0 - stroke;
|
||||
@@ -3932,6 +4018,7 @@ impl<'a, 'b> Texel<'a, 'b> {
|
||||
coverage = stroke + coverage * (1.0 - stroke);
|
||||
}
|
||||
}
|
||||
|
||||
if coverage > 0.0 {
|
||||
let layer_value = painted / coverage.max(MIN_PAINT_COVERAGE);
|
||||
value += (blend1(effect.blend, value, layer_value) - value) * coverage * opacity;
|
||||
@@ -4271,62 +4358,66 @@ impl<'a, 'b> Texel<'a, 'b> {
|
||||
(coverage > 0.0).then_some((value, coverage.min(1.0)))
|
||||
}
|
||||
|
||||
/// Straight value and coverage of painted data of one channel (premultiplied values plus
|
||||
/// coverage per texel), with the live stroke when `preview`.
|
||||
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);
|
||||
/// Straight value and coverage of one channel's painted data (premultiplied values plus coverage per texel), with the live stroke when `preview`
|
||||
fn painted(&mut self, data: Option<&[u16]>, chan_plan: &ChanPlan, preview: bool) -> ([f32; 3], f32) {
|
||||
// Coverage floor the premultiplied value is divided by
|
||||
const MIN_COVERAGE: f32 = 1e-5;
|
||||
|
||||
// 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));
|
||||
sa *= s.map(|(_, a)| a).unwrap_or(0.0);
|
||||
s.map(|(c, _)| c)
|
||||
let stroke_preview = if preview { self.inp.preview } else { None };
|
||||
let mut stroke_alpha = stroke_preview.map(|stroke| (self.stroke * stroke.opacity).clamp(0.0, 1.0)).unwrap_or(0.0);
|
||||
|
||||
// The stencil shapes the stroke; on the Projection tool its color is the base color
|
||||
let stencil_color = match stroke_preview.and_then(|stroke| stroke.stencil.as_ref()) {
|
||||
Some(stencil) if stroke_alpha > 0.0 => {
|
||||
let stencil_paint = self.stencil_paint(stencil);
|
||||
stroke_alpha *= stencil_paint.map(|(_, factor)| factor).unwrap_or(0.0);
|
||||
stencil_paint.and_then(|(color, _)| color)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let mut val = [0.0f32; 3];
|
||||
let mut cov = 0.0f32;
|
||||
if let Some(d) = data {
|
||||
let base = self.o * (c.comps + 1);
|
||||
for (k, slot) in val.iter_mut().take(c.comps).enumerate() {
|
||||
*slot = decode(c.kind, d.get(base + k).copied().unwrap_or(0));
|
||||
|
||||
let mut value = [0.0f32; 3];
|
||||
let mut coverage = 0.0f32;
|
||||
if let Some(texels) = data {
|
||||
let base = self.o * (chan_plan.comps + 1);
|
||||
for (component, slot) in value.iter_mut().take(chan_plan.comps).enumerate() {
|
||||
*slot = decode(chan_plan.kind, texels.get(base + component).copied().unwrap_or(0));
|
||||
}
|
||||
cov = from_u16(d.get(base + c.comps).copied().unwrap_or(0));
|
||||
coverage = from_u16(texels.get(base + chan_plan.comps).copied().unwrap_or(0));
|
||||
}
|
||||
if let Some(p) = pv
|
||||
&& sa > 0.0
|
||||
|
||||
if let Some(stroke) = stroke_preview
|
||||
&& stroke_alpha > 0.0
|
||||
{
|
||||
if p.erase {
|
||||
val = val.map(|v| v * (1.0 - sa));
|
||||
cov *= 1.0 - sa;
|
||||
} else if let Some(ch) = Channel::ALL.get(c.ch)
|
||||
&& let Some(pval) = p.values.get(ch)
|
||||
if stroke.erase {
|
||||
value = value.map(|component| component * (1.0 - stroke_alpha));
|
||||
coverage *= 1.0 - stroke_alpha;
|
||||
} else if let Some(channel) = Channel::ALL.get(chan_plan.ch)
|
||||
&& let Some(stroke_value) = stroke.values.get(channel)
|
||||
{
|
||||
let pval = match stencil {
|
||||
Some(col) if *ch == Channel::BaseColor => col,
|
||||
_ => match p.carried.get(ch) {
|
||||
Some(img) => {
|
||||
let raw = img.get(self.x, self.y).map(|v| decode(c.kind, v));
|
||||
let stroke_value = match stencil_color {
|
||||
Some(color) if *channel == Channel::BaseColor => color,
|
||||
_ => match stroke.carried.get(channel) {
|
||||
Some(carried) => {
|
||||
let raw = carried.get(self.x, self.y).map(|stored| decode(chan_plan.kind, stored));
|
||||
[raw[0], raw[1], raw[2]]
|
||||
}
|
||||
None => *pval,
|
||||
None => *stroke_value,
|
||||
},
|
||||
};
|
||||
for k in 0..c.comps {
|
||||
val[k] = pval[k] * sa + val[k] * (1.0 - sa);
|
||||
for component in 0..chan_plan.comps {
|
||||
value[component] = stroke_value[component] * stroke_alpha + value[component] * (1.0 - stroke_alpha);
|
||||
}
|
||||
cov = sa + cov * (1.0 - sa);
|
||||
coverage = stroke_alpha + coverage * (1.0 - stroke_alpha);
|
||||
}
|
||||
}
|
||||
if cov <= 0.0 {
|
||||
if coverage <= 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))
|
||||
let inverse_coverage = 1.0 / coverage.max(MIN_COVERAGE);
|
||||
let straight = if chan_plan.comps == 3 { value.map(|component| component * inverse_coverage) } else { [value[0] * inverse_coverage; 3] };
|
||||
(straight, coverage.min(1.0))
|
||||
}
|
||||
|
||||
/// Apply one content effect to a channel's straight value and coverage
|
||||
@@ -4672,13 +4763,15 @@ fn composite_block(
|
||||
quota: usize,
|
||||
fields: &Fields,
|
||||
) -> Vec<((u32, u32), Vec<Band>)> {
|
||||
let channels: Vec<Channel> = inp.project.texture_set(inp.ts).map(|s| s.channel_list()).unwrap_or_default();
|
||||
let formats: Vec<(Channel, ChannelFormat)> = inp.project.texture_set(inp.ts).map(TextureSet::formats).unwrap_or_default();
|
||||
let channels: Vec<Channel> = formats.iter().map(|(c, _)| *c).collect();
|
||||
let (w, h) = (out.resolution, out.height);
|
||||
let split = below.map(|(_, l)| l);
|
||||
let cached = |t: (u32, u32)| below.and_then(|(b, _)| b.tile(t));
|
||||
let fresh: Vec<(u32, u32)> = tiles.iter().copied().filter(|t| cached(*t).is_none()).collect();
|
||||
let recorded: std::collections::BTreeSet<(u32, u32)> = if split.is_some() { fresh.iter().copied().take(quota).collect() } else { Default::default() };
|
||||
let lanes: Vec<Lane> = channels.iter().map(|c| Lane { ch: c.index(), n: c.components(), signed: c.kind() == ChannelKind::Signed }).collect();
|
||||
let lanes: Vec<Lane> =
|
||||
formats.iter().map(|(c, f)| Lane { ch: c.index(), n: c.components(), signed: c.kind() == ChannelKind::Signed, format: *f }).collect();
|
||||
let stride: usize = lanes.iter().map(|l| l.n).sum();
|
||||
let level_count = split.map_or(0, <[Level]>::len);
|
||||
let defaults: Acc = Channel::ALL.map(Channel::default_value);
|
||||
@@ -4767,7 +4860,7 @@ fn composite_block(
|
||||
anchors.clear();
|
||||
}
|
||||
for (l, buf) in lanes.iter().zip(&mut channel_buffers) {
|
||||
let v = acc.get(l.ch).copied().unwrap_or([0.0; 3]);
|
||||
let v = crate::channel_store::stored(l.format, l.signed, acc.get(l.ch).copied().unwrap_or([0.0; 3]), l.n);
|
||||
for (k, x) in v.iter().take(l.n).enumerate() {
|
||||
let encoded = if l.signed { to_u16_signed(*x) } else { to_u16(*x) };
|
||||
if let Some(slot) = buf.get_mut(band_offset * l.n + k) {
|
||||
@@ -4784,20 +4877,26 @@ fn composite_block(
|
||||
|
||||
// Join the bands of each tile (in parallel; uncovered tiles are freed)
|
||||
let joined: Vec<Joined> = results
|
||||
.par_chunks(bands as usize)
|
||||
.par_chunks_mut(bands as usize)
|
||||
.map(|parts| {
|
||||
let any = parts.iter().any(|p| p.2);
|
||||
let data = (0..channels.len())
|
||||
.map(|k| {
|
||||
any.then(|| {
|
||||
let mut v = Vec::with_capacity(parts.iter().map(|p| p.0.get(k).map_or(0, Vec::len)).sum());
|
||||
for p in parts {
|
||||
for p in parts.iter() {
|
||||
v.extend_from_slice(p.0.get(k).map_or(&[][..], Vec::as_slice));
|
||||
}
|
||||
std::sync::Arc::new(v)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Only replay data is needed after joining the tile
|
||||
for (channel_buffers, _, _) in parts {
|
||||
channel_buffers.clear();
|
||||
}
|
||||
|
||||
(data, any)
|
||||
})
|
||||
.collect();
|
||||
@@ -4845,6 +4944,8 @@ struct Lane {
|
||||
ch: usize,
|
||||
n: usize,
|
||||
signed: bool,
|
||||
/// What the channel is stored in
|
||||
format: ChannelFormat,
|
||||
}
|
||||
|
||||
/// Restore the cached stack value of slot `o` (a texel at one nesting level). Scalars are
|
||||
@@ -4874,37 +4975,42 @@ fn store_below(cache: &mut [f32], lanes: &[Lane], stride: usize, o: usize, acc:
|
||||
}
|
||||
}
|
||||
|
||||
/// UV padding for display: fill uncovered texels in `tiles` and their neighbours from their
|
||||
/// nearest covered texel. Returns the tiles it wrote.
|
||||
pub fn pad_tiles(out: &mut Composite, dmap: &DilationMap, tiles: &[(u32, u32)]) -> std::collections::BTreeSet<(u32, u32)> {
|
||||
/// UV padding for display: fill uncovered texels in `tiles`, their neighbours and the tiles padding continues into across a seam from the covered texel `padding` gives each, returning the tiles written
|
||||
pub fn pad_tiles(out: &mut Composite, padding: &crate::PaddingMaps, tiles: &[(u32, u32)]) -> std::collections::BTreeSet<(u32, u32)> {
|
||||
let mut written = std::collections::BTreeSet::new();
|
||||
let (w, h) = (out.resolution, out.height);
|
||||
if (dmap.width, dmap.height) != (w, h) {
|
||||
if padding.size() != (w, h) {
|
||||
return written;
|
||||
}
|
||||
|
||||
let (nx, ny) = (w.div_ceil(TILE) as i64, h.div_ceil(TILE) as i64);
|
||||
let mut set = std::collections::BTreeSet::new();
|
||||
// The tiles and their neighbours, which padding reaches into
|
||||
let (tiles_across, tiles_down) = (w.div_ceil(TILE) as i64, h.div_ceil(TILE) as i64);
|
||||
let mut near_tiles = std::collections::BTreeSet::new();
|
||||
for &(tx, ty) in tiles {
|
||||
for dy in -1..=1i64 {
|
||||
for dx in -1..=1i64 {
|
||||
let (x, y) = (tx as i64 + dx, ty as i64 + dy);
|
||||
if x >= 0 && y >= 0 && x < nx && y < ny {
|
||||
set.insert((x as u32, y as u32));
|
||||
if x >= 0 && y >= 0 && x < tiles_across && y < tiles_down {
|
||||
near_tiles.insert((x as u32, y as u32));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Padding across a seam can continue from this tile into one far away
|
||||
near_tiles.extend(padding.tiles_crossed_from((tx, ty)));
|
||||
}
|
||||
let set: Vec<(u32, u32)> = set.into_iter().collect();
|
||||
for img in out.channels.values_mut() {
|
||||
let near_tiles: Vec<(u32, u32)> = near_tiles.into_iter().collect();
|
||||
|
||||
for (channel, img) in out.channels.iter_mut() {
|
||||
let comps = img.comps();
|
||||
let src: &TileImage = img;
|
||||
let across_seams = crate::PaddingMaps::crosses_seams(*channel);
|
||||
|
||||
// Each tile pads from the original image, so parallel writes stay independent
|
||||
let padded: Vec<((u32, u32), Vec<u16>)> = set
|
||||
let padded: Vec<((u32, u32), Vec<u16>)> = near_tiles
|
||||
.par_iter()
|
||||
.filter_map(|&(tx, ty)| {
|
||||
let mut data: Option<Vec<u16>> = None;
|
||||
let mut padded_tile: Option<Vec<u16>> = None;
|
||||
for ly in 0..TILE {
|
||||
for lx in 0..TILE {
|
||||
let (x, y) = (tx * TILE + lx, ty * TILE + ly);
|
||||
@@ -4912,24 +5018,25 @@ pub fn pad_tiles(out: &mut Composite, dmap: &DilationMap, tiles: &[(u32, u32)])
|
||||
continue;
|
||||
}
|
||||
|
||||
let Some((sx, sy)) = dmap.source(x, y) else { continue };
|
||||
let Some((sx, sy)) = padding.source(across_seams, x, y) else { continue };
|
||||
|
||||
if (sx, sy) == (x, y) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let v = src.get(sx, sy);
|
||||
let d = data.get_or_insert_with(|| src.tile(tx, ty).map_or_else(|| vec![0; TILE_AREA * comps], <[u16]>::to_vec));
|
||||
let o = (ly * TILE + lx) as usize * comps;
|
||||
if let Some(px) = d.get_mut(o..o + comps) {
|
||||
px.copy_from_slice(&v[..comps]);
|
||||
let source_texel = src.get(sx, sy);
|
||||
let tile_data = padded_tile.get_or_insert_with(|| src.tile(tx, ty).map_or_else(|| vec![0; TILE_AREA * comps], <[u16]>::to_vec));
|
||||
let offset = (ly * TILE + lx) as usize * comps;
|
||||
if let Some(texel) = tile_data.get_mut(offset..offset + comps) {
|
||||
texel.copy_from_slice(&source_texel[..comps]);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(((tx, ty), data?))
|
||||
Some(((tx, ty), padded_tile?))
|
||||
})
|
||||
.collect();
|
||||
for ((tx, ty), d) in padded {
|
||||
img.set_tile(tx, ty, Some(std::sync::Arc::new(d)));
|
||||
for ((tx, ty), tile_data) in padded {
|
||||
img.set_tile(tx, ty, Some(std::sync::Arc::new(tile_data)));
|
||||
written.insert((tx, ty));
|
||||
}
|
||||
}
|
||||
@@ -5524,6 +5631,17 @@ mod tests {
|
||||
run_with_images(f, preview, &ImageStore::default())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mirror_on_a_wide_set_reflects_across_its_own_height() {
|
||||
let mirror = Mirror { mode: texturecraft_core::MirrorMode::AxisY, ..Mirror::LIBRARY };
|
||||
let (size, near_bottom) = ([256, 128], 120.0);
|
||||
let read = std::cell::Cell::new(None);
|
||||
mirror_texel(&mirror, (10.0, near_bottom), (size, size), 4, None, &mut [0.0; 5], &|x, y, _| read.set(Some((x, y))));
|
||||
let (x, y) = read.get().unwrap();
|
||||
assert_eq!(x, 10.0);
|
||||
assert!(y < size[1] as f32 / 2.0, "the bottom half copies the top half: read row {y}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mirrored_fill_culls_against_the_mesh_in_each_copy_view() {
|
||||
let mut fixture = fixture();
|
||||
@@ -5562,6 +5680,52 @@ mod tests {
|
||||
assert!(close(composite.value(Channel::BaseColor, 48, 32), [1.0, 0.0, 0.0]), "the exposed side takes the fill");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rectangular_height_filter_tilts_equally_for_equal_uv_slopes() {
|
||||
let (width, height) = (16, 32);
|
||||
let texels = (width * height) as usize;
|
||||
let normals: Vec<f32> = [0.5, 0.5, 1.0, 1.0].into_iter().cycle().take(texels * 4).collect();
|
||||
let coverage = vec![1.0; texels];
|
||||
let heights: Vec<_> = (0..width * height).map(|index| (index % width) as f32 / width as f32 + (index / width) as f32 / height as f32).collect();
|
||||
|
||||
let normal = gather(
|
||||
Op::HeightToNormal(HeightToNormal::LIBRARY),
|
||||
(&normals, &coverage, &heights),
|
||||
4,
|
||||
(0, 0, width, height),
|
||||
1.0,
|
||||
(width, [width, height], [width, height]),
|
||||
1.0,
|
||||
);
|
||||
let center = (height / 2 * width + width / 2) as usize * 4;
|
||||
let (red, green) = (normal[center], normal[center + 1]);
|
||||
|
||||
assert!(red < 0.5 && green > 0.5);
|
||||
assert!((1.0 - red - green).abs() < 1e-6, "equal UV slopes produced unequal tilt: {red}, {green}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn baked_height_slopes_respect_rectangular_udim_blocks() {
|
||||
let mut fixture = fixture();
|
||||
let (block_width, block_height) = (64, 128);
|
||||
let set = &mut fixture.project.texture_sets[0];
|
||||
set.set_size(block_width, block_height);
|
||||
set.uv_tiles = vec![1001, 1011];
|
||||
let (width, height) = set.size();
|
||||
fixture.gbuf = UvGBuffer::new(&fixture.mesh, 0, width, height);
|
||||
fixture.baked.resolution = width;
|
||||
let heights = (0..width * height).map(|i| (i % width) as f32 / block_width as f32 + (i / width % block_height) as f32 / block_height as f32).collect();
|
||||
fixture.baked.maps.insert(BakedMap::Height, Arc::new(heights));
|
||||
let images = ImageStore::default();
|
||||
let inputs = inputs(&fixture, &images, None);
|
||||
|
||||
for y in [block_height - 1, block_height] {
|
||||
let slope = Texel::new(&inputs, 10, y, 0, 0.0).height_slope();
|
||||
|
||||
assert_eq!(slope, Some([1.0; 2]), "slope at row {y} must stay within its rectangular tile");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn baked_height_slopes_stay_within_each_uv_tile() {
|
||||
let mut fixture = fixture();
|
||||
@@ -6417,12 +6581,61 @@ soft {soft:?}"
|
||||
out.channels.get_mut(&Channel::Roughness).unwrap().set(10, 10, &[to_u16(0.9)]);
|
||||
let mut covered = vec![false; 64 * 64];
|
||||
covered[10 * 64 + 10] = true;
|
||||
let dmap = DilationMap::new(&covered, 64, 64, Some(4));
|
||||
pad_tiles(&mut out, &dmap, &[(0, 0)]);
|
||||
let padding = crate::PaddingMaps {
|
||||
flat: texturecraft_texel::DilationMap::new(&covered, 64, 64, Some(4)),
|
||||
crossed: Vec::new(),
|
||||
row_starts: Vec::new(),
|
||||
crossed_into: Default::default(),
|
||||
};
|
||||
pad_tiles(&mut out, &padding, &[(0, 0)]);
|
||||
assert!((out.value(Channel::Roughness, 12, 12)[0] - 0.9).abs() < 1e-3);
|
||||
assert!(out.value(Channel::Roughness, 30, 30)[0] < 0.1 || !out.channels[&Channel::Roughness].is_allocated(0, 0));
|
||||
}
|
||||
|
||||
/// Two islands of one 3D edge, tiles apart: repainting the far island repads the near island's padding past the seam
|
||||
#[test]
|
||||
fn padding_past_a_seam_follows_a_change_to_its_other_side_tiles_away() {
|
||||
use texturecraft_geom::{UvSeam, UvSeamSide};
|
||||
let (width, height) = (8 * TILE, TILE);
|
||||
let (left, right) = (4..=59u32, 404..=460u32);
|
||||
let covered: Vec<bool> = (0..width * height).map(|i| left.contains(&(i % width)) || right.contains(&(i % width))).collect();
|
||||
let at = |x: f32, y: f32| Vec2::new(x / width as f32, y / height as f32);
|
||||
let seam = UvSeam {
|
||||
sides: [
|
||||
UvSeamSide { triangle: 0, start: at(60.0, 0.0), end: at(60.0, height as f32), interior: at(4.0, 0.0) },
|
||||
UvSeamSide { triangle: 1, start: at(404.0, 0.0), end: at(404.0, height as f32), interior: at(460.0, 0.0) },
|
||||
],
|
||||
};
|
||||
let triangles: Vec<_> = covered
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(pixel, covered)| if *covered { u32::from(pixel % width as usize > 400) } else { texturecraft_geom::NO_TRI })
|
||||
.collect();
|
||||
let mesh = texturecraft_geom::primitives::plane(1.0, 1);
|
||||
let partition = texturecraft_geom::TrianglePartition::new(&mesh, 0, |_, _| Vec::<u32>::new());
|
||||
let seam_input = crate::SeamPaddingInput::new(vec![seam], &triangles, partition);
|
||||
|
||||
let padding = crate::PaddingMaps::new(texturecraft_core::UvPaddingMode::Space3d, &covered, (width, height), Some(4), (0, 0), Some(&seam_input));
|
||||
|
||||
let mut out = Composite::with_size(&[Channel::Roughness], width, height);
|
||||
let paint = |out: &mut Composite, xs: std::ops::RangeInclusive<u32>, value: f32| {
|
||||
for y in 0..height {
|
||||
for x in xs.clone() {
|
||||
out.channels.get_mut(&Channel::Roughness).unwrap().set(x, y, &[to_u16(value)]);
|
||||
}
|
||||
}
|
||||
};
|
||||
paint(&mut out, left.clone(), 0.2);
|
||||
paint(&mut out, right.clone(), 0.2);
|
||||
pad_tiles(&mut out, &padding, &all_tiles(width, height));
|
||||
|
||||
// Past the left island's seam edge, padding continues from the right island six tiles away
|
||||
paint(&mut out, right, 0.9);
|
||||
let written = pad_tiles(&mut out, &padding, &[(404 / TILE, 0)]);
|
||||
assert!((out.value(Channel::Roughness, 61, 3)[0] - 0.9).abs() < 1e-3, "{:?}", out.value(Channel::Roughness, 61, 3));
|
||||
assert!(written.contains(&(0, 0)), "the repadded tile is uploaded: {written:?}");
|
||||
}
|
||||
|
||||
fn content_fx(f: &mut Fixture, id: LayerId, kind: EffectKind) -> LayerId {
|
||||
let eid = f.project.alloc_id();
|
||||
f.project.layer_mut(id).unwrap().content_effects.push(Effect::new(eid, kind));
|
||||
@@ -6662,6 +6875,33 @@ soft {soft:?}"
|
||||
}
|
||||
}
|
||||
|
||||
/// A set taller than wide: a mirror or transform reads anywhere down its block, so a tile composited alone near the bottom matches the whole set
|
||||
#[test]
|
||||
fn a_tile_alone_on_a_tall_set_reads_a_mirror_or_transform_from_the_far_end() {
|
||||
const WIDTH: u32 = 64;
|
||||
const HEIGHT: u32 = 256;
|
||||
let column_of = |out: &Composite| (HEIGHT - TILE..HEIGHT).map(|y| out.value(Channel::Roughness, 20, y)[0]).collect::<Vec<f32>>();
|
||||
let composite = |filter: &Filter, tiles: &[(u32, u32)]| {
|
||||
let mut f = fixture();
|
||||
f.gbuf = UvGBuffer::new(&f.mesh, 0, WIDTH, HEIGHT);
|
||||
f.project.texture_sets[0].set_size(WIDTH, HEIGHT);
|
||||
checker_roughness(&mut f, Some(filter.clone()));
|
||||
let images = ImageStore::default();
|
||||
let mut out = Composite::with_size(&f.project.texture_sets[0].channel_list(), WIDTH, HEIGHT);
|
||||
composite_tiles(&inputs(&f, &images, None), &mut out, tiles);
|
||||
column_of(&out)
|
||||
};
|
||||
|
||||
let mirror = Filter::Mirror(Mirror { mode: texturecraft_core::MirrorMode::AxisY, ..Mirror::LIBRARY });
|
||||
let shift = Filter::Transform(TileTransform { offset: [0.0, 0.25], ..TileTransform::LIBRARY });
|
||||
for filter in [mirror, shift] {
|
||||
let whole = composite(&filter, &all_tiles(WIDTH, HEIGHT));
|
||||
let bottom_tile = composite(&filter, &[(0, HEIGHT / TILE - 1)]);
|
||||
let label = filter.label();
|
||||
assert!(whole.iter().zip(&bottom_tile).all(|(a, b)| (a - b).abs() < 1e-3), "{label}: the bottom tile alone\n{bottom_tile:?}\nwhole\n{whole:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_gradients_blur_intensity_blurs_what_it_looks_up() {
|
||||
let row = |filter: Option<Filter>| {
|
||||
|
||||
@@ -57,6 +57,7 @@ pub(crate) fn field_identity(inputs: &Inputs) -> u64 {
|
||||
mesh.submeshes.iter().for_each(|part| (part.material, part.start, part.count).hash(&mut hash));
|
||||
set.uv_tiles.hash(&mut hash);
|
||||
set.resolution.hash(&mut hash);
|
||||
set.resolution_height.hash(&mut hash);
|
||||
set.tile_resolutions.hash(&mut hash);
|
||||
}
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
pub mod axis_frame;
|
||||
mod baked_maps;
|
||||
pub mod below;
|
||||
mod channel_store;
|
||||
mod curvature_size_level;
|
||||
pub mod curvature_sizes;
|
||||
pub mod display;
|
||||
@@ -37,6 +38,7 @@ mod mask_gray;
|
||||
mod micro_detail;
|
||||
pub mod mip_level;
|
||||
mod organic;
|
||||
mod padding_maps;
|
||||
pub mod pattern;
|
||||
mod pattern_context;
|
||||
pub mod projector_cover;
|
||||
@@ -44,6 +46,8 @@ pub mod projector_depth;
|
||||
mod projector_depth_cache;
|
||||
pub mod projector_view;
|
||||
mod sampled_map;
|
||||
pub mod seam_padding;
|
||||
mod seam_padding_input;
|
||||
mod sections;
|
||||
mod shape_distance;
|
||||
mod slope_texel;
|
||||
@@ -51,6 +55,7 @@ mod slot_placement;
|
||||
mod soft_box;
|
||||
pub mod solo;
|
||||
pub mod store;
|
||||
mod texel_edge;
|
||||
mod texture_layer;
|
||||
mod three_d_distance;
|
||||
pub mod thumb;
|
||||
@@ -77,8 +82,10 @@ pub use eval::{
|
||||
stack_reads_neighbours,
|
||||
};
|
||||
pub use mask_gray::MaskGray;
|
||||
pub use padding_maps::PaddingMaps;
|
||||
pub use pattern_context::PatternContext;
|
||||
pub use projector_depth_cache::ProjectorDepthCache;
|
||||
pub use seam_padding_input::SeamPaddingInput;
|
||||
pub use solo::solo_project;
|
||||
pub use store::{BakedMaps, ImageRes, ImageStore, PixelStore};
|
||||
pub use thumb::{THUMB_TEXELS, ThumbImage, ThumbTarget};
|
||||
@@ -0,0 +1,183 @@
|
||||
//! A texture set's UV padding: from island edges, and across seams for the texels past one
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use texturecraft_core::{Channel, ChannelKind, UvPaddingMode};
|
||||
use texturecraft_texel::TILE;
|
||||
use texturecraft_texel::dilate::DilationMap;
|
||||
|
||||
use crate::SeamPaddingInput;
|
||||
use crate::seam_padding::{SEAM_REACH, cross_seams};
|
||||
|
||||
/// A texture set's padding: `flat` for every texel, with the few texels past a seam listed apart in `crossed` by row
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct PaddingMaps {
|
||||
/// Padding from island edges (2D), which tangent-space normals always take: a normal turns with its island, so it can't continue across a seam
|
||||
pub flat: DilationMap,
|
||||
/// Across seams (3D): (texel, source texel) indices of the padding texels that continue from a seam's other side, sorted by texel
|
||||
pub crossed: Vec<(u32, u32)>,
|
||||
/// Where each row's texels start in `crossed`, one more than the rows (empty without any), so a lookup searches one row
|
||||
pub(crate) row_starts: Vec<u32>,
|
||||
/// For each tile holding a seam's far side, the tiles whose padding continues from it, so a change there repads them however far they are
|
||||
pub(crate) crossed_into: BTreeMap<(u32, u32), BTreeSet<(u32, u32)>>,
|
||||
}
|
||||
|
||||
impl PaddingMaps {
|
||||
/// The padding for `mode`: `covered` texels of a `width × height` set padded up to `max_dist` texels inside each `block`
|
||||
pub fn new(
|
||||
mode: UvPaddingMode,
|
||||
covered: &[bool],
|
||||
(width, height): (u32, u32),
|
||||
max_dist: Option<u32>,
|
||||
block: (u32, u32),
|
||||
seams: Option<&SeamPaddingInput<'_>>,
|
||||
) -> PaddingMaps {
|
||||
let flat = DilationMap::in_rectangular_blocks(covered, width, height, max_dist, block);
|
||||
let crossed = seams
|
||||
.filter(|_| mode == UvPaddingMode::Space3d)
|
||||
.map_or_else(Vec::new, |seams| cross_seams(&flat, max_dist.map_or(SEAM_REACH, |d| d.min(SEAM_REACH)), block, seams));
|
||||
let row_starts =
|
||||
if crossed.is_empty() { Vec::new() } else { (0..=height).map(|y| crossed.partition_point(|(texel, _)| *texel < y * width) as u32).collect() };
|
||||
let tile_of = |texel: u32| ((texel % width) / TILE, (texel / width) / TILE);
|
||||
let mut crossed_into: BTreeMap<(u32, u32), BTreeSet<(u32, u32)>> = BTreeMap::new();
|
||||
for &(texel, source) in &crossed {
|
||||
crossed_into.entry(tile_of(source)).or_default().insert(tile_of(texel));
|
||||
}
|
||||
PaddingMaps { flat, crossed, row_starts, crossed_into }
|
||||
}
|
||||
|
||||
/// The tiles whose padding continues across a seam from texels in `tile`
|
||||
pub fn tiles_crossed_from(&self, tile: (u32, u32)) -> impl Iterator<Item = (u32, u32)> + '_ {
|
||||
self.crossed_into.get(&tile).into_iter().flatten().copied()
|
||||
}
|
||||
|
||||
/// Texels across and down
|
||||
pub fn size(&self) -> (u32, u32) {
|
||||
(self.flat.width, self.flat.height)
|
||||
}
|
||||
|
||||
/// Whether `channel` pads across seams; tangent-space normals pad from island edges
|
||||
pub fn crosses_seams(channel: Channel) -> bool {
|
||||
channel.kind() != ChannelKind::NormalMap
|
||||
}
|
||||
|
||||
/// The covered texel padding (x, y), itself when covered; `across_seams` takes the seams' other sides
|
||||
pub fn source(&self, across_seams: bool, x: u32, y: u32) -> Option<(u32, u32)> {
|
||||
let source = self.flat.source(x, y)?;
|
||||
if !across_seams || source == (x, y) {
|
||||
return Some(source);
|
||||
}
|
||||
|
||||
let (texel, width) = (y * self.flat.width + x, self.flat.width);
|
||||
let row = match (self.row_starts.get(y as usize), self.row_starts.get(y as usize + 1)) {
|
||||
(Some(&start), Some(&end)) => self.crossed.get(start as usize..end as usize).unwrap_or_default(),
|
||||
_ => &[],
|
||||
};
|
||||
match row.binary_search_by_key(&texel, |(crossed_texel, _)| *crossed_texel) {
|
||||
Ok(found) => row.get(found).map(|(_, crossed_source)| (crossed_source % width, crossed_source / width)),
|
||||
Err(_) => Some(source),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use texturecraft_geom::glam::Vec2;
|
||||
use texturecraft_geom::{NO_TRI, TrianglePartition, UvSeam, UvSeamSide, primitives};
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Two islands of one 3D edge: the left one's right side is the right one's left side
|
||||
fn two_islands() -> (Vec<bool>, Vec<UvSeam>) {
|
||||
let (width, height) = (32u32, 8u32);
|
||||
let covered = (0..width * height).map(|i| matches!(i % width, 4..=11 | 20..=27)).collect();
|
||||
let at = |x: f32, y: f32| Vec2::new(x / width as f32, y / height as f32);
|
||||
let left = UvSeamSide { triangle: 0, start: at(12.0, 0.0), end: at(12.0, 8.0), interior: at(4.0, 0.0) };
|
||||
let right = UvSeamSide { triangle: 1, start: at(20.0, 0.0), end: at(20.0, 8.0), interior: at(28.0, 0.0) };
|
||||
(covered, vec![UvSeam { sides: [left, right] }])
|
||||
}
|
||||
|
||||
fn islands(seams: Vec<UvSeam>, triangles: &[u32]) -> SeamPaddingInput<'_> {
|
||||
// A synthetic raster supplies its island ids directly
|
||||
let mesh = primitives::plane(1.0, 2);
|
||||
let partition = TrianglePartition::new(&mesh, 0, |_, _| Vec::<u32>::new());
|
||||
SeamPaddingInput::new(seams, triangles, partition)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_flat_seam_keeps_the_last_row_within_its_reach() {
|
||||
let (width, height) = (128, 128);
|
||||
let at = |x: f32, y: f32| Vec2::new(x / width as f32, y / height as f32);
|
||||
// The length rounds the normalized edge slightly below one
|
||||
let near = UvSeamSide { triangle: 0, start: at(1.0, 32.5), end: at(16.25, 32.5), interior: at(1.0, 40.0) };
|
||||
let far = UvSeamSide { triangle: 1, start: at(65.0, 32.5), end: at(80.25, 32.5), interior: at(65.0, 100.0) };
|
||||
let triangles: Vec<_> = (0..width * height)
|
||||
.map(|index| match (index % width, index / width) {
|
||||
(1..=15, 32..=39) => 0,
|
||||
(65..=79, 32..=99) => 1,
|
||||
_ => NO_TRI,
|
||||
})
|
||||
.collect();
|
||||
let covered: Vec<_> = triangles.iter().map(|&triangle| triangle != NO_TRI).collect();
|
||||
let seams = islands(vec![UvSeam { sides: [near, far] }], &triangles);
|
||||
|
||||
let padding = PaddingMaps::new(UvPaddingMode::Space3d, &covered, (width, height), Some(SEAM_REACH), (64, height), Some(&seams));
|
||||
|
||||
assert!(padding.source(true, 15, 0).is_some_and(|(x, _)| x >= 64), "the boundary row borrows from the far island");
|
||||
assert!(padding.source(false, 15, 0).is_some_and(|(x, _)| x < 64), "flat padding still uses the near island");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn padding_stops_at_the_far_islands_edge() {
|
||||
let (_, seams) = two_islands();
|
||||
let (width, height) = (32, 8);
|
||||
for (gap, far_strip) in [(false, 2), (true, 2), (true, 1)] {
|
||||
let triangles: Vec<_> = (0..width * height)
|
||||
.map(|pixel| match pixel % width {
|
||||
4..=11 => 0,
|
||||
20..=21 => 1,
|
||||
22 if gap => NO_TRI,
|
||||
22..=27 => far_strip,
|
||||
_ => NO_TRI,
|
||||
})
|
||||
.collect();
|
||||
let covered: Vec<_> = triangles.iter().map(|id| *id != NO_TRI).collect();
|
||||
let input = islands(seams.clone(), &triangles);
|
||||
|
||||
let padding = PaddingMaps::new(UvPaddingMode::Space3d, &covered, (width, height), Some(4), (0, 0), Some(&input));
|
||||
|
||||
assert_eq!(padding.source(true, 13, 3), Some((21, 3)), "a texel inside the far island continues the seam");
|
||||
assert_eq!(padding.source(true, 15, 3), padding.source(false, 15, 3), "another island is out of reach even with no texel gap");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn padding_past_a_seam_continues_from_its_other_side_and_normals_stay_flat() {
|
||||
let (covered, seams) = two_islands();
|
||||
let triangles: Vec<_> = (0..32 * 8)
|
||||
.map(|pixel| match pixel % 32 {
|
||||
4..=11 => 0,
|
||||
20..=27 => 1,
|
||||
_ => NO_TRI,
|
||||
})
|
||||
.collect();
|
||||
let input = islands(seams, &triangles);
|
||||
|
||||
let space_3d = PaddingMaps::new(UvPaddingMode::Space3d, &covered, (32, 8), Some(4), (0, 0), Some(&input));
|
||||
let space_2d = PaddingMaps::new(UvPaddingMode::Space2d, &covered, (32, 8), Some(4), (0, 0), Some(&input));
|
||||
let island = |padding: &PaddingMaps, across_seams: bool, x: u32| {
|
||||
padding.source(across_seams, x, 3).map(|(source_x, _)| if source_x < 16 { "left" } else { "right" })
|
||||
};
|
||||
|
||||
// Just right of the left island, then just left of the right island
|
||||
assert_eq!((island(&space_3d, true, 13), island(&space_3d, true, 18)), (Some("right"), Some("left")));
|
||||
assert_eq!((island(&space_2d, true, 13), island(&space_2d, true, 18)), (Some("left"), Some("right")));
|
||||
assert_eq!((island(&space_3d, false, 13), island(&space_3d, false, 18)), (Some("left"), Some("right")));
|
||||
assert!(PaddingMaps::crosses_seams(Channel::BaseColor) && !PaddingMaps::crosses_seams(Channel::Normal));
|
||||
|
||||
// Away from the seam, both modes pad from the near island, and only texels between the islands are kept apart
|
||||
assert_eq!(island(&space_3d, true, 2), Some("left"));
|
||||
assert!(!space_3d.crossed.is_empty() && space_2d.crossed.is_empty());
|
||||
assert!(space_3d.crossed.iter().all(|(texel, _)| (12..20).contains(&(texel % 32))));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
//! UV padding across seams (3D): texels past a UV seam continue the surface from the seam's other side
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use texturecraft_geom::glam::{IVec2, Vec2};
|
||||
use texturecraft_texel::dilate::{DilationMap, NONE};
|
||||
|
||||
use crate::SeamPaddingInput;
|
||||
use crate::texel_edge::TexelEdge;
|
||||
|
||||
/// Farthest a padding texel reaches across a seam, in texels; farther ones keep their nearest covered texel
|
||||
pub const SEAM_REACH: u32 = 32;
|
||||
|
||||
/// The padding texels of `flat` just outside a seam, each with the texel as far inside the seam's other side: (texel, source) indices sorted by texel
|
||||
pub(crate) fn cross_seams(flat: &DilationMap, reach: u32, block: (u32, u32), input: &SeamPaddingInput<'_>) -> Vec<(u32, u32)> {
|
||||
let (width, height) = (flat.width, flat.height);
|
||||
let size = Vec2::new(width as f32, height as f32);
|
||||
let block_of = |x: u32, y: u32| (x.checked_div(block.0).unwrap_or(0), y.checked_div(block.1).unwrap_or(0));
|
||||
|
||||
// Each crossed texel's source and how far outside its seam it is; a nearer seam replaces it
|
||||
let mut crossed: HashMap<u32, (u32, f32)> = HashMap::new();
|
||||
for seam in &input.seams {
|
||||
for (near, far) in [(seam.sides[0], seam.sides[1]), (seam.sides[1], seam.sides[0])] {
|
||||
let (Some(near_edge), Some(far_edge)) = (TexelEdge::new(near, size), TexelEdge::new(far, size)) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let reach = reach as f32;
|
||||
let low = near_edge.start.min(near_edge.end) - Vec2::splat(reach);
|
||||
let high = near_edge.start.max(near_edge.end) + Vec2::splat(reach);
|
||||
let (x0, y0) = (low.x.floor().max(0.0) as u32, low.y.floor().max(0.0) as u32);
|
||||
let (x1, y1) = (high.x.ceil().min(size.x) as u32, high.y.ceil().min(size.y) as u32);
|
||||
let mut side_islands = None;
|
||||
for y in y0..y1 {
|
||||
for x in near_edge.outside_columns(y, x0..x1, reach) {
|
||||
let index = y * width + x;
|
||||
let Some(&flat_source) = flat.src.get(index as usize) else { continue };
|
||||
|
||||
if flat_source == NONE || flat_source == index {
|
||||
continue;
|
||||
}
|
||||
|
||||
let point = Vec2::new(x as f32 + 0.5, y as f32 + 0.5);
|
||||
let Some((along, outside)) = near_edge.outside(point) else { continue };
|
||||
|
||||
if outside > reach || crossed.get(&index).is_some_and(|(_, distance)| outside >= *distance) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Another island's edge nearer than the seam keeps its texel
|
||||
let (source_x, source_y) = (flat_source % width, flat_source / width);
|
||||
if (source_x.abs_diff(x).max(source_y.abs_diff(y)) as f32) + 1.0 < outside {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Padding stays inside its UV tile, like the 2D padding
|
||||
let inside = near_edge.start.lerp(near_edge.end, along) + near_edge.inward * 0.5;
|
||||
if block_of(inside.x.max(0.0) as u32, inside.y.max(0.0) as u32) != block_of(x, y) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Start at the first texel centres on the seam's far side
|
||||
let far_boundary = far_edge.start.lerp(far_edge.end, along);
|
||||
let start = far_boundary + far_edge.inward * 0.5;
|
||||
let target = far_boundary + far_edge.inward * outside.max(0.5);
|
||||
if target.x < 0.0 || target.y < 0.0 || target.x >= size.x || target.y >= size.y {
|
||||
continue;
|
||||
}
|
||||
|
||||
let target_index = target.y as u32 * width + target.x as u32;
|
||||
if flat.src.get(target_index as usize) != Some(&target_index) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let (Some(near_island), Some(far_island)) =
|
||||
*side_islands.get_or_insert_with(|| (input.triangle_island(near.triangle), input.triangle_island(far.triangle)))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
|
||||
if input.island_at(flat_source) != Some(near_island) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if input.island_at(target_index) == Some(far_island) && follows_island(input, start, target, far_island, (width, height), block) {
|
||||
crossed.insert(index, (target_index, outside));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut sources: Vec<(u32, u32)> = crossed.into_iter().map(|(texel, (source, _))| (texel, source)).collect();
|
||||
sources.sort_unstable();
|
||||
sources
|
||||
}
|
||||
|
||||
fn follows_island(input: &SeamPaddingInput<'_>, start: Vec2, target: Vec2, island: usize, (width, height): (u32, u32), block: (u32, u32)) -> bool {
|
||||
let mut cell = start.floor().as_ivec2();
|
||||
let end = target.floor().as_ivec2();
|
||||
let limit = IVec2::new(width as i32, height as i32);
|
||||
if cell.cmplt(IVec2::ZERO).any() || cell.cmpge(limit).any() {
|
||||
return false;
|
||||
}
|
||||
|
||||
if block.0 != 0 && block.1 != 0 {
|
||||
let block = IVec2::new(block.0 as i32, block.1 as i32);
|
||||
if cell / block != end / block {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
let step = (end - cell).signum();
|
||||
let delta = (target - start).abs();
|
||||
let step_time = Vec2::new(1.0 / delta.x, 1.0 / delta.y);
|
||||
let boundary_time = |axis: usize| {
|
||||
if step[axis] == 0 {
|
||||
return f32::INFINITY;
|
||||
}
|
||||
|
||||
let boundary = cell[axis] + i32::from(step[axis] > 0);
|
||||
(boundary as f32 - start[axis]).abs() * step_time[axis]
|
||||
};
|
||||
let mut next = Vec2::new(boundary_time(0), boundary_time(1));
|
||||
|
||||
// Visit every texel with a nonzero stretch of the path
|
||||
let mut last_triangle = None;
|
||||
loop {
|
||||
let Some(triangle) = input.triangle_at(cell.y as u32 * width + cell.x as u32) else { return false };
|
||||
|
||||
if Some(triangle) != last_triangle {
|
||||
if input.triangle_island(triangle) != Some(island) {
|
||||
return false;
|
||||
}
|
||||
|
||||
last_triangle = Some(triangle);
|
||||
}
|
||||
|
||||
if cell == end {
|
||||
return true;
|
||||
}
|
||||
|
||||
let time = next.x.min(next.y);
|
||||
if next.x == time {
|
||||
cell.x += step.x;
|
||||
next.x = if cell.x == end.x { f32::INFINITY } else { next.x + step_time.x };
|
||||
}
|
||||
if next.y == time {
|
||||
cell.y += step.y;
|
||||
next.y = if cell.y == end.y { f32::INFINITY } else { next.y + step_time.y };
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use texturecraft_geom::{Mesh, TrianglePartition, UvSeam};
|
||||
|
||||
/// Seams and the UV island of each rasterized triangle, borrowing the existing texel-to-triangle grid
|
||||
pub struct SeamPaddingInput<'a> {
|
||||
pub(crate) seams: Vec<UvSeam>,
|
||||
triangles: &'a [u32],
|
||||
material: Option<(&'a Mesh, usize)>,
|
||||
islands: OnceLock<TrianglePartition>,
|
||||
}
|
||||
|
||||
impl<'a> SeamPaddingInput<'a> {
|
||||
/// Use seams and a partition from the same mesh and material as the rasterized triangles
|
||||
pub fn new(seams: Vec<UvSeam>, triangles: &'a [u32], islands: TrianglePartition) -> Self {
|
||||
Self { seams, triangles, material: None, islands: OnceLock::from(islands) }
|
||||
}
|
||||
|
||||
/// Find seams now and build island ownership only if a padding texel can cross
|
||||
pub fn of_material(mesh: &'a Mesh, material: usize, triangles: &'a [u32]) -> Option<Self> {
|
||||
let seams = UvSeam::of_material(mesh, material);
|
||||
if seams.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(Self { seams, triangles, material: Some((mesh, material)), islands: OnceLock::new() })
|
||||
}
|
||||
|
||||
pub(crate) fn triangle_island(&self, triangle: u32) -> Option<usize> {
|
||||
let islands = self.islands.get().or_else(|| self.material.map(|(mesh, material)| self.islands.get_or_init(|| UvSeam::islands_of(mesh, material))))?;
|
||||
islands.index_of(triangle)
|
||||
}
|
||||
|
||||
pub(crate) fn triangle_at(&self, texel: u32) -> Option<u32> {
|
||||
self.triangles.get(texel as usize).copied()
|
||||
}
|
||||
|
||||
pub(crate) fn island_at(&self, texel: u32) -> Option<usize> {
|
||||
self.triangle_island(self.triangle_at(texel)?)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
//! A UV seam side in texel space
|
||||
|
||||
use std::ops::Range;
|
||||
|
||||
use texturecraft_geom::UvSeamSide;
|
||||
use texturecraft_geom::glam::Vec2;
|
||||
|
||||
/// A seam side in texel space, with its unit normal into the island
|
||||
pub(crate) struct TexelEdge {
|
||||
pub(crate) start: Vec2,
|
||||
pub(crate) end: Vec2,
|
||||
pub(crate) inward: Vec2,
|
||||
}
|
||||
|
||||
impl TexelEdge {
|
||||
pub(crate) fn new(side: UvSeamSide, size: Vec2) -> Option<TexelEdge> {
|
||||
let (start, end, interior) = (side.start * size, side.end * size, side.interior * size);
|
||||
let normal = (end - start).perp().try_normalize()?;
|
||||
let inward = if normal.dot(interior - start) < 0.0 { -normal } else { normal };
|
||||
Some(TexelEdge { start, end, inward })
|
||||
}
|
||||
|
||||
/// How far along the edge (0..1) and how far outside the island `point` is, when it is beside the edge on the outside
|
||||
pub(crate) fn outside(&self, point: Vec2) -> Option<(f32, f32)> {
|
||||
let direction = self.end - self.start;
|
||||
let along = (point - self.start).dot(direction) / direction.length_squared();
|
||||
let outside = self.outside_distance(point);
|
||||
((0.0..=1.0).contains(&along) && outside > 0.0).then_some((along, outside))
|
||||
}
|
||||
|
||||
fn outside_distance(&self, point: Vec2) -> f32 {
|
||||
-(point - self.start).dot(self.inward)
|
||||
}
|
||||
|
||||
/// Clip columns to the exterior distance band using the same rounded distances as `outside`
|
||||
pub(crate) fn outside_columns(&self, row: u32, columns: Range<u32>, reach: f32) -> Range<u32> {
|
||||
if columns.is_empty() {
|
||||
return columns;
|
||||
}
|
||||
|
||||
let distance = |column| self.outside_distance(Vec2::new(column as f32 + 0.5, row as f32 + 0.5));
|
||||
if self.inward.x == 0.0 {
|
||||
let outside = distance(columns.start);
|
||||
return if outside > 0.0 && outside <= reach { columns } else { 0..0 };
|
||||
}
|
||||
|
||||
// Signed distance is monotone across a row even when adjacent values round to the same distance
|
||||
let (start, end) = if self.inward.x < 0.0 {
|
||||
let start = first_column_after(columns.clone(), |column| distance(column) <= 0.0);
|
||||
(start, first_column_after(start..columns.end, |column| distance(column) <= reach))
|
||||
} else {
|
||||
let start = first_column_after(columns.clone(), |column| distance(column) > reach);
|
||||
(start, first_column_after(start..columns.end, |column| distance(column) > 0.0))
|
||||
};
|
||||
start..end
|
||||
}
|
||||
}
|
||||
|
||||
fn first_column_after(mut columns: Range<u32>, before: impl Fn(u32) -> bool) -> u32 {
|
||||
while columns.start < columns.end {
|
||||
let middle = columns.start.midpoint(columns.end);
|
||||
if before(middle) {
|
||||
columns.start = middle + 1;
|
||||
} else {
|
||||
columns.end = middle;
|
||||
}
|
||||
}
|
||||
|
||||
columns.start
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use texturecraft_geom::UvSeamSide;
|
||||
use texturecraft_geom::glam::Vec2;
|
||||
|
||||
use super::TexelEdge;
|
||||
|
||||
#[test]
|
||||
fn a_diagonal_edges_band_spans_every_texel_beside_it_without_scanning_the_rectangle() {
|
||||
let size = Vec2::splat(512.0);
|
||||
let side = UvSeamSide { triangle: 0, start: Vec2::new(0.05, 0.05), end: Vec2::new(0.95, 0.9), interior: Vec2::new(0.9, 0.1) };
|
||||
let edge = TexelEdge::new(side, size).unwrap();
|
||||
let reach = 32.0;
|
||||
|
||||
let (mut beside, mut spanned) = (0, 0);
|
||||
for y in 0..512u32 {
|
||||
let centre_y = y as f32 + 0.5;
|
||||
let span = edge.outside_columns(y, 0..512, reach);
|
||||
spanned += span.len();
|
||||
for x in 0..512 {
|
||||
let point = Vec2::new(x as f32 + 0.5, centre_y);
|
||||
if edge.outside(point).is_some_and(|(_, outside)| outside <= reach) {
|
||||
beside += 1;
|
||||
assert!(span.contains(&x), "{point} is beside the edge but outside its row's span {span:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The diagonal's bounding box holds far more texels than its band
|
||||
assert!(beside > 0 && spanned < 512 * 512 / 4, "{spanned} texels spanned for {beside} beside the edge");
|
||||
}
|
||||
}
|
||||
@@ -4,9 +4,11 @@ mod ambient_occlusion_attenuation;
|
||||
mod ambient_occlusion_settings;
|
||||
mod backface_mode;
|
||||
mod bake_antialiasing;
|
||||
mod bake_change;
|
||||
mod bake_paint_target;
|
||||
mod bake_resolution;
|
||||
mod bake_settings;
|
||||
mod bake_source;
|
||||
mod bake_sync;
|
||||
mod bake_sync_group;
|
||||
mod mesh_match_mode;
|
||||
@@ -45,8 +47,10 @@ pub use ambient_occlusion_attenuation::AmbientOcclusionAttenuation;
|
||||
pub use ambient_occlusion_settings::AmbientOcclusionSettings;
|
||||
pub use backface_mode::BackfaceMode;
|
||||
pub use bake_antialiasing::BakeAntialiasing;
|
||||
pub use bake_change::BakeChange;
|
||||
pub use bake_resolution::BakeResolution;
|
||||
pub use bake_settings::BakeSettings;
|
||||
pub use bake_source::{BakeSource, fingerprint, fingerprint_words};
|
||||
pub use bake_sync::BakeSync;
|
||||
pub use bake_sync_group::BakeSyncGroup;
|
||||
pub use baked_map::BakedMap;
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// What changed since a mesh map was baked, which makes it out of date
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum BakeChange {
|
||||
LowPoly,
|
||||
HighPoly,
|
||||
Cage,
|
||||
Settings,
|
||||
MapSettings,
|
||||
}
|
||||
|
||||
impl BakeChange {
|
||||
/// Identifier in automation replies
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
BakeChange::LowPoly => "lowPoly",
|
||||
BakeChange::HighPoly => "highPoly",
|
||||
BakeChange::Cage => "cage",
|
||||
BakeChange::Settings => "settings",
|
||||
BakeChange::MapSettings => "mapSettings",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
use super::BakeChange;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Fingerprints of what one mesh map was baked from: a later change to any of them shows the map out of date
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct BakeSource {
|
||||
/// The low poly's geometry
|
||||
pub low_poly: u64,
|
||||
/// The embedded mesh file when this map reads its material colors.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub low_material_file: Option<u64>,
|
||||
/// The high poly files, in list order (0: none, the set bakes from the low poly)
|
||||
pub high_poly: u64,
|
||||
/// The cage file (0: none)
|
||||
pub cage: u64,
|
||||
/// The settings every map of the set shares (size, high poly, cage, skew) and its UV tiles
|
||||
pub settings: u64,
|
||||
/// The map's own settings
|
||||
pub map_settings: u64,
|
||||
}
|
||||
|
||||
impl BakeSource {
|
||||
/// What differs in `current` from this record, in [`BakeChange`] order (empty: up to date)
|
||||
pub fn changes(&self, current: &BakeSource) -> Vec<BakeChange> {
|
||||
// Switching color source is already reported under high poly or map settings
|
||||
let material_changed = match (self.low_material_file, current.low_material_file) {
|
||||
(Some(previous), Some(now)) => previous != now,
|
||||
(None, None) => false,
|
||||
_ => self.high_poly == current.high_poly && self.map_settings == current.map_settings,
|
||||
};
|
||||
|
||||
[
|
||||
(self.low_poly != current.low_poly || material_changed, BakeChange::LowPoly),
|
||||
(self.high_poly != current.high_poly, BakeChange::HighPoly),
|
||||
(self.cage != current.cage, BakeChange::Cage),
|
||||
(self.settings != current.settings, BakeChange::Settings),
|
||||
(self.map_settings != current.map_settings, BakeChange::MapSettings),
|
||||
]
|
||||
.into_iter()
|
||||
.filter_map(|(changed, change)| changed.then_some(change))
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// A fingerprint of `bytes` that stays the same across runs, platforms and Rust versions (unlike `std::hash`)
|
||||
pub fn fingerprint(bytes: &[u8]) -> u64 {
|
||||
let words = bytes.chunks(8).map(|chunk| {
|
||||
let mut word_bytes = [0; 8];
|
||||
word_bytes[..chunk.len()].copy_from_slice(chunk);
|
||||
u64::from_le_bytes(word_bytes)
|
||||
});
|
||||
fingerprint_words(words.chain([bytes.len() as u64]))
|
||||
}
|
||||
|
||||
/// [`fingerprint`] of a sequence of words: FNV-1a taking a 64-bit word per step
|
||||
pub fn fingerprint_words(words: impl IntoIterator<Item = u64>) -> u64 {
|
||||
// FNV-1a 64-bit offset basis and prime
|
||||
const OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325;
|
||||
const PRIME: u64 = 0x0000_0100_0000_01b3;
|
||||
|
||||
words.into_iter().fold(OFFSET_BASIS, |hash, word| (hash ^ word).wrapping_mul(PRIME))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_fingerprint_changes_with_any_byte_and_with_the_length() {
|
||||
let bytes: Vec<u8> = (0..=20).collect();
|
||||
let mut changed = bytes.clone();
|
||||
changed[17] ^= 1;
|
||||
|
||||
assert_ne!(fingerprint(&bytes), fingerprint(&changed));
|
||||
assert_ne!(fingerprint(&bytes), fingerprint(&bytes[..20]));
|
||||
assert_ne!(fingerprint(&[]), fingerprint(&[0]));
|
||||
}
|
||||
}
|
||||
@@ -37,6 +37,11 @@ impl Default for MeshMapSettings {
|
||||
}
|
||||
|
||||
impl MeshMapSettings {
|
||||
/// Whether this map reads the source mesh's material colors, independently of its enabled flag.
|
||||
pub fn reads_material_colors(&self, map: BakedMap) -> bool {
|
||||
map == BakedMap::Opacity || (map == BakedMap::Id && self.id.parameters.source == super::IdColorSource::MaterialColor)
|
||||
}
|
||||
|
||||
pub fn is_enabled(&self, map: BakedMap) -> bool {
|
||||
match map {
|
||||
BakedMap::Normal => self.normal.is_enabled,
|
||||
@@ -84,6 +89,22 @@ impl MeshMapSettings {
|
||||
}
|
||||
}
|
||||
|
||||
/// `map`'s typed parameters as JSON
|
||||
pub fn parameters_json(&self, map: BakedMap) -> serde_json::Value {
|
||||
let parameters = match map {
|
||||
// These maps have no parameters of their own
|
||||
BakedMap::Normal | BakedMap::WorldNormal | BakedMap::Opacity => return serde_json::Value::Null,
|
||||
BakedMap::Id => serde_json::to_value(self.id.parameters),
|
||||
BakedMap::AmbientOcclusion => serde_json::to_value(self.ao.parameters),
|
||||
BakedMap::Curvature => serde_json::to_value(self.curvature.parameters),
|
||||
BakedMap::Position => serde_json::to_value(self.position.parameters),
|
||||
BakedMap::Thickness => serde_json::to_value(self.thickness.parameters),
|
||||
BakedMap::Height => serde_json::to_value(self.height.parameters),
|
||||
BakedMap::BentNormal => serde_json::to_value(self.bent_normal.parameters),
|
||||
};
|
||||
parameters.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn enabled(&self) -> impl Iterator<Item = BakedMap> {
|
||||
BakedMap::ALL.into_iter().filter(|map| self.is_enabled(*map))
|
||||
}
|
||||
|
||||
+416
-10
@@ -39,6 +39,77 @@ pub enum Channel {
|
||||
Transmission,
|
||||
/// Tangent-space normal of the clear coat (relative to the mesh normal).
|
||||
CoatNormal,
|
||||
/// How much of the base layer shows (stored and exported: our shader does not read it)
|
||||
BaseWeight,
|
||||
/// Roughness of the diffuse base (stored and exported: our shader does not read it)
|
||||
BaseDiffuseRoughness,
|
||||
/// Strength of the specular lobe (stored and exported: our shader does not read it)
|
||||
SpecularWeight,
|
||||
/// Tint of the specular lobe (stored and exported: our shader does not read it)
|
||||
SpecularColor,
|
||||
/// Tint of transmitted light (stored and exported: our shader does not read it)
|
||||
TransmissionColor,
|
||||
/// Subsurface scattering color (stored and exported: our shader does not read it)
|
||||
SubsurfaceColor,
|
||||
/// Scattering distance per color (stored and exported: our shader does not read it)
|
||||
SubsurfaceRadiusScale,
|
||||
/// Clear coat tint (stored and exported: our shader does not read it)
|
||||
CoatColor,
|
||||
/// Clear coat anisotropy (stored and exported: our shader does not read it)
|
||||
CoatAnisotropy,
|
||||
/// Clear coat reflectance (stored and exported: our shader does not read it)
|
||||
CoatSpecularLevel,
|
||||
/// Tangent-space direction of the clear coat anisotropy, packed like a normal (stored and exported: our shader does not read it)
|
||||
CoatTangent,
|
||||
/// Thin-film iridescence weight (stored and exported: our shader does not read it)
|
||||
ThinFilmWeight,
|
||||
/// Tangent-space anisotropy direction, packed like a normal (stored and exported: our shader does not read it)
|
||||
Tangent,
|
||||
/// Mask for blending materials in an engine (stored and exported only)
|
||||
BlendingMask,
|
||||
/// Diffuse color of older shaders (stored and exported only)
|
||||
Diffuse,
|
||||
/// Signed displacement for render engines (stored and exported only)
|
||||
Displacement,
|
||||
/// Index of refraction, 0..1 as the target shader maps it (stored and exported only)
|
||||
Ior,
|
||||
/// Reflection amount of older shaders (stored and exported only)
|
||||
Reflection,
|
||||
/// Transmissive color of older shaders (stored and exported only)
|
||||
Transmissive,
|
||||
/// Free channels for anything a target shader needs (grey, stored and exported)
|
||||
User0,
|
||||
User1,
|
||||
User2,
|
||||
User3,
|
||||
User4,
|
||||
User5,
|
||||
User6,
|
||||
User7,
|
||||
User8,
|
||||
User9,
|
||||
User10,
|
||||
User11,
|
||||
User12,
|
||||
User13,
|
||||
User14,
|
||||
User15,
|
||||
User16,
|
||||
User17,
|
||||
User18,
|
||||
User19,
|
||||
User20,
|
||||
User21,
|
||||
User22,
|
||||
User23,
|
||||
User24,
|
||||
User25,
|
||||
User26,
|
||||
User27,
|
||||
User28,
|
||||
User29,
|
||||
User30,
|
||||
User31,
|
||||
}
|
||||
|
||||
/// How a channel's values are stored and interpreted.
|
||||
@@ -55,7 +126,7 @@ pub enum ChannelKind {
|
||||
}
|
||||
|
||||
impl Channel {
|
||||
pub const ALL: [Channel; 21] = [
|
||||
pub const ALL: [Channel; 72] = [
|
||||
Channel::BaseColor,
|
||||
Channel::Metallic,
|
||||
Channel::Roughness,
|
||||
@@ -77,8 +148,62 @@ impl Channel {
|
||||
Channel::ScatterWeight,
|
||||
Channel::Transmission,
|
||||
Channel::CoatNormal,
|
||||
Channel::BaseWeight,
|
||||
Channel::BaseDiffuseRoughness,
|
||||
Channel::SpecularWeight,
|
||||
Channel::SpecularColor,
|
||||
Channel::TransmissionColor,
|
||||
Channel::SubsurfaceColor,
|
||||
Channel::SubsurfaceRadiusScale,
|
||||
Channel::CoatColor,
|
||||
Channel::CoatAnisotropy,
|
||||
Channel::CoatSpecularLevel,
|
||||
Channel::CoatTangent,
|
||||
Channel::ThinFilmWeight,
|
||||
Channel::Tangent,
|
||||
Channel::BlendingMask,
|
||||
Channel::Diffuse,
|
||||
Channel::Displacement,
|
||||
Channel::Ior,
|
||||
Channel::Reflection,
|
||||
Channel::Transmissive,
|
||||
Channel::User0,
|
||||
Channel::User1,
|
||||
Channel::User2,
|
||||
Channel::User3,
|
||||
Channel::User4,
|
||||
Channel::User5,
|
||||
Channel::User6,
|
||||
Channel::User7,
|
||||
Channel::User8,
|
||||
Channel::User9,
|
||||
Channel::User10,
|
||||
Channel::User11,
|
||||
Channel::User12,
|
||||
Channel::User13,
|
||||
Channel::User14,
|
||||
Channel::User15,
|
||||
Channel::User16,
|
||||
Channel::User17,
|
||||
Channel::User18,
|
||||
Channel::User19,
|
||||
Channel::User20,
|
||||
Channel::User21,
|
||||
Channel::User22,
|
||||
Channel::User23,
|
||||
Channel::User24,
|
||||
Channel::User25,
|
||||
Channel::User26,
|
||||
Channel::User27,
|
||||
Channel::User28,
|
||||
Channel::User29,
|
||||
Channel::User30,
|
||||
Channel::User31,
|
||||
];
|
||||
|
||||
/// How many channels, from the start of [`Channel::ALL`], our shader reads
|
||||
pub const SHADED_COUNT: usize = 21;
|
||||
|
||||
/// The extra shading lobes (clear coat, sheen, anisotropy, subsurface scattering,
|
||||
/// transmission). Their defaults switch the lobes off, so a set without them shades exactly
|
||||
/// as before.
|
||||
@@ -101,8 +226,15 @@ impl Channel {
|
||||
pub fn kind(self) -> ChannelKind {
|
||||
match self {
|
||||
Channel::BaseColor | Channel::Emissive | Channel::Specular | Channel::SheenColor => ChannelKind::Color,
|
||||
Channel::Normal | Channel::CoatNormal => ChannelKind::NormalMap,
|
||||
Channel::Height => ChannelKind::Signed,
|
||||
Channel::SpecularColor
|
||||
| Channel::TransmissionColor
|
||||
| Channel::SubsurfaceColor
|
||||
| Channel::SubsurfaceRadiusScale
|
||||
| Channel::CoatColor
|
||||
| Channel::Diffuse
|
||||
| Channel::Transmissive => ChannelKind::Color,
|
||||
Channel::Normal | Channel::CoatNormal | Channel::Tangent | Channel::CoatTangent => ChannelKind::NormalMap,
|
||||
Channel::Height | Channel::Displacement => ChannelKind::Signed,
|
||||
_ => ChannelKind::Scalar,
|
||||
}
|
||||
}
|
||||
@@ -133,8 +265,53 @@ impl Channel {
|
||||
Channel::Normal | Channel::CoatNormal => [0.5, 0.5, 1.0],
|
||||
Channel::Opacity | Channel::AmbientOcclusion => [1.0; 3],
|
||||
Channel::SpecularLevel | Channel::Glossiness => [0.5; 3],
|
||||
// F0 of a common dielectric (4 %).
|
||||
|
||||
// F0 of a common dielectric (4 %)
|
||||
Channel::Specular => [0.04; 3],
|
||||
Channel::BaseWeight | Channel::SpecularWeight | Channel::SpecularColor | Channel::TransmissionColor | Channel::CoatColor => [1.0; 3],
|
||||
Channel::BaseDiffuseRoughness
|
||||
| Channel::CoatAnisotropy
|
||||
| Channel::ThinFilmWeight
|
||||
| Channel::BlendingMask
|
||||
| Channel::Displacement
|
||||
| Channel::Reflection
|
||||
| Channel::Transmissive => [0.0; 3],
|
||||
Channel::SubsurfaceColor => [0.8; 3],
|
||||
Channel::SubsurfaceRadiusScale => [1.0, 0.5, 0.25],
|
||||
Channel::CoatSpecularLevel | Channel::Diffuse | Channel::Ior => [0.5; 3],
|
||||
Channel::CoatTangent | Channel::Tangent => [1.0, 0.5, 0.5],
|
||||
Channel::User0
|
||||
| Channel::User1
|
||||
| Channel::User2
|
||||
| Channel::User3
|
||||
| Channel::User4
|
||||
| Channel::User5
|
||||
| Channel::User6
|
||||
| Channel::User7
|
||||
| Channel::User8
|
||||
| Channel::User9
|
||||
| Channel::User10
|
||||
| Channel::User11
|
||||
| Channel::User12
|
||||
| Channel::User13
|
||||
| Channel::User14
|
||||
| Channel::User15
|
||||
| Channel::User16
|
||||
| Channel::User17
|
||||
| Channel::User18
|
||||
| Channel::User19
|
||||
| Channel::User20
|
||||
| Channel::User21
|
||||
| Channel::User22
|
||||
| Channel::User23
|
||||
| Channel::User24
|
||||
| Channel::User25
|
||||
| Channel::User26
|
||||
| Channel::User27
|
||||
| Channel::User28
|
||||
| Channel::User29
|
||||
| Channel::User30
|
||||
| Channel::User31 => [0.0; 3],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -161,6 +338,57 @@ impl Channel {
|
||||
Channel::ScatterWeight => "Scattering weight",
|
||||
Channel::Transmission => "Transmission",
|
||||
Channel::CoatNormal => "Coat normal",
|
||||
Channel::BaseWeight => "Base weight",
|
||||
Channel::BaseDiffuseRoughness => "Base diffuse roughness",
|
||||
Channel::SpecularWeight => "Specular weight",
|
||||
Channel::SpecularColor => "Specular color",
|
||||
Channel::TransmissionColor => "Transmission color",
|
||||
Channel::SubsurfaceColor => "Subsurface color",
|
||||
Channel::SubsurfaceRadiusScale => "Subsurface radius scale",
|
||||
Channel::CoatColor => "Coat color",
|
||||
Channel::CoatAnisotropy => "Coat anisotropy",
|
||||
Channel::CoatSpecularLevel => "Coat specular level",
|
||||
Channel::CoatTangent => "Coat tangent",
|
||||
Channel::ThinFilmWeight => "Thin-film weight",
|
||||
Channel::Tangent => "Tangent",
|
||||
Channel::BlendingMask => "Blending mask",
|
||||
Channel::Diffuse => "Diffuse",
|
||||
Channel::Displacement => "Displacement",
|
||||
Channel::Ior => "Ior",
|
||||
Channel::Reflection => "Reflection",
|
||||
Channel::Transmissive => "Transmissive",
|
||||
Channel::User0 => "User0",
|
||||
Channel::User1 => "User1",
|
||||
Channel::User2 => "User2",
|
||||
Channel::User3 => "User3",
|
||||
Channel::User4 => "User4",
|
||||
Channel::User5 => "User5",
|
||||
Channel::User6 => "User6",
|
||||
Channel::User7 => "User7",
|
||||
Channel::User8 => "User8",
|
||||
Channel::User9 => "User9",
|
||||
Channel::User10 => "User10",
|
||||
Channel::User11 => "User11",
|
||||
Channel::User12 => "User12",
|
||||
Channel::User13 => "User13",
|
||||
Channel::User14 => "User14",
|
||||
Channel::User15 => "User15",
|
||||
Channel::User16 => "User16",
|
||||
Channel::User17 => "User17",
|
||||
Channel::User18 => "User18",
|
||||
Channel::User19 => "User19",
|
||||
Channel::User20 => "User20",
|
||||
Channel::User21 => "User21",
|
||||
Channel::User22 => "User22",
|
||||
Channel::User23 => "User23",
|
||||
Channel::User24 => "User24",
|
||||
Channel::User25 => "User25",
|
||||
Channel::User26 => "User26",
|
||||
Channel::User27 => "User27",
|
||||
Channel::User28 => "User28",
|
||||
Channel::User29 => "User29",
|
||||
Channel::User30 => "User30",
|
||||
Channel::User31 => "User31",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -188,6 +416,57 @@ impl Channel {
|
||||
Channel::ScatterWeight => "scatter",
|
||||
Channel::Transmission => "transm",
|
||||
Channel::CoatNormal => "coat nrm",
|
||||
Channel::BaseWeight => "base weight",
|
||||
Channel::BaseDiffuseRoughness => "diffuse rough",
|
||||
Channel::SpecularWeight => "spec weight",
|
||||
Channel::SpecularColor => "spec color",
|
||||
Channel::TransmissionColor => "transm color",
|
||||
Channel::SubsurfaceColor => "sss color",
|
||||
Channel::SubsurfaceRadiusScale => "sss radius",
|
||||
Channel::CoatColor => "coat color",
|
||||
Channel::CoatAnisotropy => "coat aniso",
|
||||
Channel::CoatSpecularLevel => "coat spec",
|
||||
Channel::CoatTangent => "coat tangent",
|
||||
Channel::ThinFilmWeight => "thin film",
|
||||
Channel::Tangent => "tangent",
|
||||
Channel::BlendingMask => "blend mask",
|
||||
Channel::Diffuse => "diffuse",
|
||||
Channel::Displacement => "displace",
|
||||
Channel::Ior => "ior",
|
||||
Channel::Reflection => "reflection",
|
||||
Channel::Transmissive => "transmissive",
|
||||
Channel::User0 => "user0",
|
||||
Channel::User1 => "user1",
|
||||
Channel::User2 => "user2",
|
||||
Channel::User3 => "user3",
|
||||
Channel::User4 => "user4",
|
||||
Channel::User5 => "user5",
|
||||
Channel::User6 => "user6",
|
||||
Channel::User7 => "user7",
|
||||
Channel::User8 => "user8",
|
||||
Channel::User9 => "user9",
|
||||
Channel::User10 => "user10",
|
||||
Channel::User11 => "user11",
|
||||
Channel::User12 => "user12",
|
||||
Channel::User13 => "user13",
|
||||
Channel::User14 => "user14",
|
||||
Channel::User15 => "user15",
|
||||
Channel::User16 => "user16",
|
||||
Channel::User17 => "user17",
|
||||
Channel::User18 => "user18",
|
||||
Channel::User19 => "user19",
|
||||
Channel::User20 => "user20",
|
||||
Channel::User21 => "user21",
|
||||
Channel::User22 => "user22",
|
||||
Channel::User23 => "user23",
|
||||
Channel::User24 => "user24",
|
||||
Channel::User25 => "user25",
|
||||
Channel::User26 => "user26",
|
||||
Channel::User27 => "user27",
|
||||
Channel::User28 => "user28",
|
||||
Channel::User29 => "user29",
|
||||
Channel::User30 => "user30",
|
||||
Channel::User31 => "user31",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -215,18 +494,84 @@ impl Channel {
|
||||
Channel::ScatterWeight => "scatterWeight",
|
||||
Channel::Transmission => "transmission",
|
||||
Channel::CoatNormal => "coatNormal",
|
||||
Channel::BaseWeight => "baseWeight",
|
||||
Channel::BaseDiffuseRoughness => "baseDiffuseRoughness",
|
||||
Channel::SpecularWeight => "specularWeight",
|
||||
Channel::SpecularColor => "specularColor",
|
||||
Channel::TransmissionColor => "transmissionColor",
|
||||
Channel::SubsurfaceColor => "subsurfaceColor",
|
||||
Channel::SubsurfaceRadiusScale => "subsurfaceRadiusScale",
|
||||
Channel::CoatColor => "coatColor",
|
||||
Channel::CoatAnisotropy => "coatAnisotropy",
|
||||
Channel::CoatSpecularLevel => "coatSpecularLevel",
|
||||
Channel::CoatTangent => "coatTangent",
|
||||
Channel::ThinFilmWeight => "thinFilmWeight",
|
||||
Channel::Tangent => "tangent",
|
||||
Channel::BlendingMask => "blendingMask",
|
||||
Channel::Diffuse => "diffuse",
|
||||
Channel::Displacement => "displacement",
|
||||
Channel::Ior => "ior",
|
||||
Channel::Reflection => "reflection",
|
||||
Channel::Transmissive => "transmissive",
|
||||
Channel::User0 => "user0",
|
||||
Channel::User1 => "user1",
|
||||
Channel::User2 => "user2",
|
||||
Channel::User3 => "user3",
|
||||
Channel::User4 => "user4",
|
||||
Channel::User5 => "user5",
|
||||
Channel::User6 => "user6",
|
||||
Channel::User7 => "user7",
|
||||
Channel::User8 => "user8",
|
||||
Channel::User9 => "user9",
|
||||
Channel::User10 => "user10",
|
||||
Channel::User11 => "user11",
|
||||
Channel::User12 => "user12",
|
||||
Channel::User13 => "user13",
|
||||
Channel::User14 => "user14",
|
||||
Channel::User15 => "user15",
|
||||
Channel::User16 => "user16",
|
||||
Channel::User17 => "user17",
|
||||
Channel::User18 => "user18",
|
||||
Channel::User19 => "user19",
|
||||
Channel::User20 => "user20",
|
||||
Channel::User21 => "user21",
|
||||
Channel::User22 => "user22",
|
||||
Channel::User23 => "user23",
|
||||
Channel::User24 => "user24",
|
||||
Channel::User25 => "user25",
|
||||
Channel::User26 => "user26",
|
||||
Channel::User27 => "user27",
|
||||
Channel::User28 => "user28",
|
||||
Channel::User29 => "user29",
|
||||
Channel::User30 => "user30",
|
||||
Channel::User31 => "user31",
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse an id, label or short label (case-insensitive, spaces/underscores ignored).
|
||||
/// Parse an id, label or short label, ignoring case, spaces, underscores and hyphens.
|
||||
pub fn parse(s: &str) -> Option<Channel> {
|
||||
let norm = |x: &str| x.to_ascii_lowercase().replace([' ', '_', '-'], "");
|
||||
let want = norm(s);
|
||||
Channel::ALL.into_iter().find(|c| norm(c.id()) == want || norm(c.label()) == want || norm(c.short()) == want || norm(&format!("{c:?}")) == want)
|
||||
if let Some(channel) = Channel::ALL.into_iter().find(|channel| channel.id().eq_ignore_ascii_case(s)) {
|
||||
return Some(channel);
|
||||
}
|
||||
|
||||
let normalize = |name: &str| name.to_ascii_lowercase().replace([' ', '_', '-'], "");
|
||||
let wanted = normalize(s);
|
||||
Channel::ALL.into_iter().find(|channel| {
|
||||
normalize(channel.id()) == wanted
|
||||
|| normalize(channel.label()) == wanted
|
||||
|| normalize(channel.short()) == wanted
|
||||
|| normalize(&format!("{channel:?}")) == wanted
|
||||
})
|
||||
}
|
||||
|
||||
/// Position in [`Channel::ALL`] (the declaration order)
|
||||
pub fn index(self) -> usize {
|
||||
Channel::ALL.iter().position(|c| *c == self).unwrap_or(0)
|
||||
self as usize
|
||||
}
|
||||
|
||||
/// Whether our shader reads the channel; the others are stored and exported for other shaders
|
||||
pub fn is_shaded(self) -> bool {
|
||||
self.index() < Channel::SHADED_COUNT
|
||||
}
|
||||
}
|
||||
|
||||
@@ -253,6 +598,39 @@ impl ChannelFormat {
|
||||
ChannelKind::Signed => ChannelFormat::L16F,
|
||||
}
|
||||
}
|
||||
|
||||
/// Every format, in the order the channel settings list them
|
||||
pub const ALL: [ChannelFormat; 9] = [
|
||||
ChannelFormat::Srgb8,
|
||||
ChannelFormat::L8,
|
||||
ChannelFormat::Rgb8,
|
||||
ChannelFormat::L16,
|
||||
ChannelFormat::Rgb16,
|
||||
ChannelFormat::L16F,
|
||||
ChannelFormat::Rgb16F,
|
||||
ChannelFormat::L32F,
|
||||
ChannelFormat::Rgb32F,
|
||||
];
|
||||
|
||||
/// A format by its label, ignoring case ("srgb8", "L16F")
|
||||
pub fn parse(label: &str) -> Option<ChannelFormat> {
|
||||
ChannelFormat::ALL.into_iter().find(|format| format.label().eq_ignore_ascii_case(label.trim()))
|
||||
}
|
||||
|
||||
/// Grey formats keep one value per texel: a colour channel stored in one turns grey
|
||||
pub fn is_grey(self) -> bool {
|
||||
matches!(self, ChannelFormat::L8 | ChannelFormat::L16 | ChannelFormat::L16F | ChannelFormat::L32F)
|
||||
}
|
||||
|
||||
/// The 16-bit format holding everything an 8-bit one does (itself for the others)
|
||||
pub fn at_least_16_bit(self) -> ChannelFormat {
|
||||
match self {
|
||||
ChannelFormat::Srgb8 | ChannelFormat::Rgb8 => ChannelFormat::Rgb16,
|
||||
ChannelFormat::L8 => ChannelFormat::L16,
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
ChannelFormat::Srgb8 => "sRGB8",
|
||||
@@ -279,6 +657,7 @@ mod tests {
|
||||
assert_eq!(Channel::parse(c.label()), Some(c));
|
||||
assert_eq!(Channel::parse(c.short()), Some(c));
|
||||
}
|
||||
|
||||
assert_eq!(Channel::parse("base color"), Some(Channel::BaseColor));
|
||||
assert_eq!(Channel::parse("nope"), None);
|
||||
}
|
||||
@@ -293,17 +672,44 @@ mod tests {
|
||||
assert!(prev.is_none_or(|p| p == c), "`{name}` names both {prev:?} and {c:?}");
|
||||
}
|
||||
}
|
||||
|
||||
for c in Channel::LOBES {
|
||||
assert!(Channel::ALL.contains(&c));
|
||||
// Tints, roughnesses and the flat coat normal only matter once their lobe has weight.
|
||||
|
||||
// Tints, roughnesses and the flat coat normal only matter once their lobe has weight
|
||||
let off =
|
||||
matches!(c, Channel::CoatRoughness | Channel::SheenColor | Channel::SheenRoughness | Channel::CoatNormal) || c.default_value() == [0.0; 3];
|
||||
assert!(off, "{c:?} must default to an inactive lobe");
|
||||
}
|
||||
|
||||
assert_eq!(Channel::parse("sheen color"), Some(Channel::SheenColor));
|
||||
assert_eq!(Channel::parse("coatWeight"), Some(Channel::CoatWeight));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn formats_parse_by_label() {
|
||||
for f in ChannelFormat::ALL {
|
||||
assert_eq!(ChannelFormat::parse(&f.label().to_lowercase()), Some(f));
|
||||
assert!(f.at_least_16_bit().is_grey() == f.is_grey());
|
||||
}
|
||||
|
||||
assert_eq!(ChannelFormat::parse("RGB4"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unshaded_channels_round_trip_through_ids() {
|
||||
// Project files and commands name channels by id: every added channel must come back as itself
|
||||
for c in Channel::ALL.into_iter().filter(|c| !c.is_shaded()) {
|
||||
assert_eq!(Channel::parse(c.id()), Some(c));
|
||||
let json = serde_json::to_string(&c).unwrap_or_default();
|
||||
assert_eq!(serde_json::from_str::<Channel>(&json).ok(), Some(c));
|
||||
}
|
||||
|
||||
assert!(Channel::LOBES.iter().chain(&Channel::DEFAULT_SET).all(|c| c.is_shaded()));
|
||||
assert_eq!(Channel::parse("User31"), Some(Channel::User31));
|
||||
assert_eq!(Channel::parse("thin-film weight"), Some(Channel::ThinFilmWeight));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn index_matches_all_order() {
|
||||
for (i, c) in Channel::ALL.iter().enumerate() {
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
//! The groups the channel manager lists material channels under
|
||||
|
||||
use crate::Channel;
|
||||
|
||||
/// A group of material channels, in the manager's reading order
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ChannelGroup {
|
||||
Base,
|
||||
Specular,
|
||||
Transmission,
|
||||
Subsurface,
|
||||
Coat,
|
||||
Sheen,
|
||||
Emission,
|
||||
ThinFilm,
|
||||
Geometry,
|
||||
Miscellaneous,
|
||||
User,
|
||||
}
|
||||
|
||||
impl ChannelGroup {
|
||||
pub const ALL: [ChannelGroup; 11] = [
|
||||
ChannelGroup::Base,
|
||||
ChannelGroup::Specular,
|
||||
ChannelGroup::Transmission,
|
||||
ChannelGroup::Subsurface,
|
||||
ChannelGroup::Coat,
|
||||
ChannelGroup::Sheen,
|
||||
ChannelGroup::Emission,
|
||||
ChannelGroup::ThinFilm,
|
||||
ChannelGroup::Geometry,
|
||||
ChannelGroup::Miscellaneous,
|
||||
ChannelGroup::User,
|
||||
];
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
ChannelGroup::Base => "Base",
|
||||
ChannelGroup::Specular => "Specular",
|
||||
ChannelGroup::Transmission => "Transmission",
|
||||
ChannelGroup::Subsurface => "Subsurface",
|
||||
ChannelGroup::Coat => "Coat",
|
||||
ChannelGroup::Sheen => "Fuzz / Sheen",
|
||||
ChannelGroup::Emission => "Emission",
|
||||
ChannelGroup::ThinFilm => "Thin-film",
|
||||
ChannelGroup::Geometry => "Geometry",
|
||||
ChannelGroup::Miscellaneous => "Miscellaneous",
|
||||
ChannelGroup::User => "User",
|
||||
}
|
||||
}
|
||||
|
||||
/// The group's channels, in the order the manager lists them
|
||||
pub fn channels(self) -> &'static [Channel] {
|
||||
use Channel as C;
|
||||
match self {
|
||||
ChannelGroup::Base => &[C::BaseWeight, C::BaseColor, C::BaseDiffuseRoughness, C::Metallic],
|
||||
ChannelGroup::Specular => &[C::SpecularWeight, C::SpecularColor, C::Roughness, C::SpecularLevel, C::AnisotropyLevel, C::AnisotropyAngle],
|
||||
ChannelGroup::Transmission => &[C::Transmission, C::TransmissionColor],
|
||||
ChannelGroup::Subsurface => &[C::ScatterWeight, C::SubsurfaceColor, C::SubsurfaceRadiusScale],
|
||||
ChannelGroup::Coat => &[C::CoatWeight, C::CoatColor, C::CoatRoughness, C::CoatAnisotropy, C::CoatSpecularLevel, C::CoatNormal, C::CoatTangent],
|
||||
ChannelGroup::Sheen => &[C::SheenWeight, C::SheenColor, C::SheenRoughness],
|
||||
ChannelGroup::Emission => &[C::Emissive],
|
||||
ChannelGroup::ThinFilm => &[C::ThinFilmWeight],
|
||||
ChannelGroup::Geometry => &[C::Opacity, C::Normal, C::Height, C::AmbientOcclusion, C::Tangent],
|
||||
ChannelGroup::Miscellaneous => &[C::BlendingMask, C::Diffuse, C::Displacement, C::Ior, C::Reflection, C::Specular, C::Glossiness, C::Transmissive],
|
||||
ChannelGroup::User => &[
|
||||
C::User0,
|
||||
C::User1,
|
||||
C::User2,
|
||||
C::User3,
|
||||
C::User4,
|
||||
C::User5,
|
||||
C::User6,
|
||||
C::User7,
|
||||
C::User8,
|
||||
C::User9,
|
||||
C::User10,
|
||||
C::User11,
|
||||
C::User12,
|
||||
C::User13,
|
||||
C::User14,
|
||||
C::User15,
|
||||
C::User16,
|
||||
C::User17,
|
||||
C::User18,
|
||||
C::User19,
|
||||
C::User20,
|
||||
C::User21,
|
||||
C::User22,
|
||||
C::User23,
|
||||
C::User24,
|
||||
C::User25,
|
||||
C::User26,
|
||||
C::User27,
|
||||
C::User28,
|
||||
C::User29,
|
||||
C::User30,
|
||||
C::User31,
|
||||
],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn every_channel_is_listed_in_exactly_one_group() {
|
||||
// A channel added to `Channel` but left out here could never be added from the manager
|
||||
let mut listed: Vec<Channel> = ChannelGroup::ALL.iter().flat_map(|group| group.channels().iter().copied()).collect();
|
||||
let count = listed.len();
|
||||
listed.sort();
|
||||
listed.dedup();
|
||||
|
||||
assert_eq!(listed.len(), count, "a channel is listed twice");
|
||||
assert_eq!(listed, Channel::ALL.to_vec());
|
||||
}
|
||||
}
|
||||
@@ -53,9 +53,14 @@ impl HeightToNormal {
|
||||
}
|
||||
|
||||
/// The unit tangent-space normal (OpenGL, +Y up the image) of a height changing by `gx` per texel to the right and `gy` per texel down
|
||||
pub fn normal(&self, [gx, gy]: [f32; 2], res: u32) -> [f32; 3] {
|
||||
let strength = self.strength(res);
|
||||
let (x, y) = (-gx * strength, gy * strength);
|
||||
pub fn normal(&self, slope: [f32; 2], res: u32) -> [f32; 3] {
|
||||
self.normal_for_size(slope, [res; 2])
|
||||
}
|
||||
|
||||
/// The same tangent-space normal for a UV tile with independent width and height
|
||||
pub fn normal_for_size(&self, [gx, gy]: [f32; 2], [width, height]: [u32; 2]) -> [f32; 3] {
|
||||
let strength_per_uv = self.strength(1);
|
||||
let (x, y) = (-gx * (strength_per_uv * width as f32), gy * (strength_per_uv * height as f32));
|
||||
let length = (x * x + y * y + 1.0).sqrt();
|
||||
if length.is_finite() { [x / length, y / length, 1.0 / length] } else { [0.0, 0.0, 1.0] }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
//! How a texture set turns its Height into normal slopes
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Height to normal method: the slope filter a texture set's height-to-normal uses
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
pub enum HeightToNormalMethod {
|
||||
/// Sharp: the difference of the two neighbours across, so single-texel detail stays crisp
|
||||
Sharp,
|
||||
/// Smooth (Sobel): a 3×3 Sobel filter, so the slope also reads the diagonal neighbours
|
||||
#[default]
|
||||
Smooth,
|
||||
}
|
||||
|
||||
impl HeightToNormalMethod {
|
||||
pub const ALL: [HeightToNormalMethod; 2] = [HeightToNormalMethod::Sharp, HeightToNormalMethod::Smooth];
|
||||
|
||||
/// Stable id for commands and inspect
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
HeightToNormalMethod::Sharp => "sharp",
|
||||
HeightToNormalMethod::Smooth => "smooth",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse(id: &str) -> Option<HeightToNormalMethod> {
|
||||
HeightToNormalMethod::ALL.into_iter().find(|value| value.id() == id)
|
||||
}
|
||||
|
||||
/// The change of height per texel to the right and down, from the heights `h(dx, dy)` around a texel
|
||||
pub fn slope(self, h: impl Fn(i32, i32) -> f32) -> [f32; 2] {
|
||||
match self {
|
||||
HeightToNormalMethod::Sharp => [(h(1, 0) - h(-1, 0)) * 0.5, (h(0, 1) - h(0, -1)) * 0.5],
|
||||
HeightToNormalMethod::Smooth => {
|
||||
// Both axes read the same four corner heights
|
||||
let upper_left = h(-1, -1);
|
||||
let upper_right = h(1, -1);
|
||||
let lower_left = h(-1, 1);
|
||||
let lower_right = h(1, 1);
|
||||
|
||||
[
|
||||
(upper_right + 2.0 * h(1, 0) + lower_right - upper_left - 2.0 * h(-1, 0) - lower_left) / 8.0,
|
||||
(lower_left + 2.0 * h(0, 1) + lower_right - upper_left - 2.0 * h(0, -1) - upper_right) / 8.0,
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -739,6 +739,15 @@ impl Source {
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Source::images`], to rename them
|
||||
pub fn images_mut(&mut self) -> Vec<&mut String> {
|
||||
match self {
|
||||
Source::Image { name, .. } => vec![name],
|
||||
Source::Procedural { pattern, .. } => pattern.tile.iter_mut().flat_map(|tile| tile.images_mut()).collect(),
|
||||
Source::Uniform(_) | Source::Anchor { .. } => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The gradient map stops of a procedural or anchor source (empty: none).
|
||||
pub fn ramp(&self) -> &[[f32; 3]] {
|
||||
match self {
|
||||
@@ -844,6 +853,12 @@ pub struct LinkPreset {
|
||||
}
|
||||
|
||||
impl Fill {
|
||||
/// The image resource names the fill holds, to rename them: its sources' and, when linked, its package and cooked outputs
|
||||
pub fn images_mut(&mut self) -> impl Iterator<Item = &mut String> {
|
||||
let link = self.link.iter_mut().map(|link| &mut **link).flat_map(|link| std::iter::once(&mut link.package).chain(link.outputs.values_mut()));
|
||||
self.sources.values_mut().flat_map(Source::images_mut).chain(link)
|
||||
}
|
||||
|
||||
/// Value used for `c` when the fill has no source for it: the channel default.
|
||||
pub fn source(&self, c: Channel) -> Source {
|
||||
self.sources.get(&c).cloned().unwrap_or_else(|| Source::uniform_of(c))
|
||||
@@ -1268,6 +1283,14 @@ impl Generator {
|
||||
if reads_geometry { &[] } else { self.kind.inputs() }
|
||||
}
|
||||
|
||||
/// The mesh maps the generator reads that a bake makes: its inputs in use, and the occlusion Dripping Rust reads whole, which no input replaces
|
||||
pub fn baked_maps_read(&self) -> &'static [BakedMap] {
|
||||
match self.kind {
|
||||
GeneratorKind::DrippingRust => &[BakedMap::AmbientOcclusion],
|
||||
_ => self.inputs_in_use(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The texture the generator blends over its signal: only on the section controls, turned on with some opacity
|
||||
pub fn texture_in_use(&self) -> Option<&TextureLayer> {
|
||||
self.texture.as_deref().filter(|texture| texture.in_use() && self.section_controls().is_some())
|
||||
@@ -1279,6 +1302,17 @@ impl Generator {
|
||||
self.inputs.values().chain(self.texture.as_ref().and_then(|texture| texture.source.as_ref())).chain(self.grunge.as_ref()).chain(micro)
|
||||
}
|
||||
|
||||
/// [`Generator::sources`], to rename the images they read
|
||||
pub fn sources_mut(&mut self) -> impl Iterator<Item = &mut Source> {
|
||||
let grayscale = match self.controls.as_deref_mut() {
|
||||
Some(KindControls::Grayscale(grayscale)) if self.kind == GeneratorKind::GrayscaleConversion => grayscale.source.as_mut(),
|
||||
_ => None,
|
||||
};
|
||||
let micro = self.micro.iter_mut().flat_map(|micro| micro.sources_mut()).chain(grayscale);
|
||||
let texture = self.texture.as_mut().and_then(|texture| texture.source.as_mut());
|
||||
self.inputs.values_mut().chain(texture).chain(self.grunge.as_mut()).chain(micro)
|
||||
}
|
||||
|
||||
/// The micro details as saved, when the generator computes with them: with a slot switched on, except a micro detail saved before Micro Details on a generator still on the earlier model, which [`Generator::earlier_micro`] reads (bring them into range before use: saved files are not trusted)
|
||||
pub fn micro_in_use(&self) -> Option<&MicroDetails> {
|
||||
self.micro.as_deref().filter(|micro| micro.in_use(self.kind) && !(micro.earlier && self.on_earlier_model()))
|
||||
@@ -2340,6 +2374,17 @@ impl EffectKind {
|
||||
sources.into_iter().flat_map(Source::images).chain(id_map)
|
||||
}
|
||||
|
||||
/// [`EffectKind::images_read`], to rename them
|
||||
pub fn images_mut(&mut self) -> Vec<&mut String> {
|
||||
match self {
|
||||
EffectKind::Fill { source, .. } => source.images_mut(),
|
||||
EffectKind::Material(fill) => fill.images_mut().collect(),
|
||||
EffectKind::Generator(generator) => generator.sources_mut().flat_map(Source::images_mut).collect(),
|
||||
EffectKind::ColorSelection(selection) => selection.id_map.iter_mut().collect(),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads a channel of the layer or of the stack below it (a compare mask's layer sides)
|
||||
pub fn reads_stack(&self) -> bool {
|
||||
matches!(self, EffectKind::Compare { left, right, .. } if left.reads_stack() || right.reads_stack())
|
||||
@@ -2402,6 +2447,11 @@ impl Effect {
|
||||
self.kind.images_read().chain(self.inputs.values().flat_map(Source::images))
|
||||
}
|
||||
|
||||
/// [`Effect::images_read`], to rename them
|
||||
pub fn images_mut(&mut self) -> impl Iterator<Item = &mut String> {
|
||||
self.kind.images_mut().into_iter().chain(self.inputs.values_mut().flat_map(Source::images_mut))
|
||||
}
|
||||
|
||||
/// Whether a source of the effect, or one of its image inputs, reads anchor point `anchor` (any anchor point when None)
|
||||
pub fn reads(&self, anchor: Option<LayerId>) -> bool {
|
||||
self.kind.reads(anchor) || self.inputs.values().any(|source| source.reads_anchor(anchor))
|
||||
|
||||
@@ -119,6 +119,11 @@ impl MicroDetails {
|
||||
self.height_source.iter().chain(self.normal_source.as_ref())
|
||||
}
|
||||
|
||||
/// [`MicroDetails::sources`], to rename the images they read
|
||||
pub fn sources_mut(&mut self) -> impl Iterator<Item = &mut Source> {
|
||||
self.height_source.iter_mut().chain(self.normal_source.as_mut())
|
||||
}
|
||||
|
||||
/// Every value brought into its range, non-finite ones to the defaults of `kind`
|
||||
pub fn clamped(self, kind: GeneratorKind) -> MicroDetails {
|
||||
let Some(defaults) = MicroDetails::defaults(kind) else { return self };
|
||||
|
||||
@@ -202,6 +202,11 @@ impl TileGenerator {
|
||||
pub fn images(&self) -> impl Iterator<Item = &str> {
|
||||
self.inputs.iter().chain(&self.background_image).map(String::as_str)
|
||||
}
|
||||
|
||||
/// [`TileGenerator::images`], to rename them
|
||||
pub fn images_mut(&mut self) -> impl Iterator<Item = &mut String> {
|
||||
self.inputs.iter_mut().chain(&mut self.background_image)
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for TileGenerator {
|
||||
|
||||
+16
-5
@@ -18,6 +18,7 @@ pub mod bevel_smooth;
|
||||
pub mod blend;
|
||||
mod block_scales;
|
||||
pub mod channel;
|
||||
pub mod channel_group;
|
||||
pub mod color_match;
|
||||
pub mod color_selection;
|
||||
pub mod compare_source;
|
||||
@@ -34,11 +35,13 @@ pub mod gradient_input;
|
||||
pub mod grayscale_conversion;
|
||||
pub mod grayscale_mode;
|
||||
pub mod height_to_normal;
|
||||
mod height_to_normal_method;
|
||||
pub mod highpass_space;
|
||||
pub mod image_input;
|
||||
pub mod layer;
|
||||
pub mod lighting_output;
|
||||
pub mod mask_outline;
|
||||
pub mod mesh_map_slot;
|
||||
pub mod mirror;
|
||||
pub mod mirror_corner;
|
||||
pub mod mirror_mode;
|
||||
@@ -51,6 +54,7 @@ pub mod project;
|
||||
pub mod projector;
|
||||
pub mod ramp_curve;
|
||||
pub mod randomized_seed;
|
||||
pub mod resource_source;
|
||||
mod saved_decal;
|
||||
mod saved_projection;
|
||||
pub mod selection_background;
|
||||
@@ -68,6 +72,7 @@ pub mod target_color_mode;
|
||||
pub mod threshold_mode;
|
||||
pub mod tile_transform;
|
||||
pub mod unit_value;
|
||||
mod uv_padding_mode;
|
||||
pub mod validation_mode;
|
||||
pub mod warp_blending;
|
||||
pub mod warp_mode;
|
||||
@@ -80,11 +85,12 @@ pub const FULL_TURN_DEGREES: f32 = 360.0;
|
||||
pub use anisotropic_kuwahara::AnisotropicKuwahara;
|
||||
pub use backface::Backface;
|
||||
pub use bake::{
|
||||
AmbientOcclusionAttenuation, AmbientOcclusionSettings, BackfaceMode, BakeAntialiasing, BakePaintTarget, BakeResolution, BakeSettings, BakeSync,
|
||||
BakeSyncGroup, BakedMap, BentNormalSettings, CageSettings, CageType, CommonBakeSettings, CurvatureMethod, CurvatureSettings, GroundPlaneSettings,
|
||||
HeightNormalization, HeightSettings, HighPolySettings, IdColorGenerator, IdColorSource, IdSettings, MapSettings, MeshCurvatureSettings, MeshMapSettings,
|
||||
MeshMatchMode, NormalMapCurvatureSettings, PositionAxis, PositionMode, PositionNormalizationScale, PositionSettings, RayDistribution, RaySettings,
|
||||
SelfOcclusion, SkewCorrectionMethod, SkewSettings, ThicknessNormalization, ThicknessSettings,
|
||||
AmbientOcclusionAttenuation, AmbientOcclusionSettings, BackfaceMode, BakeAntialiasing, BakeChange, BakePaintTarget, BakeResolution, BakeSettings,
|
||||
BakeSource, BakeSync, BakeSyncGroup, BakedMap, BentNormalSettings, CageSettings, CageType, CommonBakeSettings, CurvatureMethod, CurvatureSettings,
|
||||
GroundPlaneSettings, HeightNormalization, HeightSettings, HighPolySettings, IdColorGenerator, IdColorSource, IdSettings, MapSettings,
|
||||
MeshCurvatureSettings, MeshMapSettings, MeshMatchMode, NormalMapCurvatureSettings, PositionAxis, PositionMode, PositionNormalizationScale,
|
||||
PositionSettings, RayDistribution, RaySettings, SelfOcclusion, SkewCorrectionMethod, SkewSettings, ThicknessNormalization, ThicknessSettings, fingerprint,
|
||||
fingerprint_words,
|
||||
};
|
||||
pub use bevel::Bevel;
|
||||
pub use bevel_blur::BevelBlur;
|
||||
@@ -93,6 +99,7 @@ pub use bevel_direction::BevelDirection;
|
||||
pub use bevel_smooth::BevelSmooth;
|
||||
pub use blend::{BlendMode, blend1, blend3, lum, mix3};
|
||||
pub use channel::{Channel, ChannelFormat, ChannelKind};
|
||||
pub use channel_group::ChannelGroup;
|
||||
pub use color_match::ColorMatch;
|
||||
pub use color_selection::ColorSelection;
|
||||
pub use compare_source::CompareSource;
|
||||
@@ -108,6 +115,7 @@ pub use gradient_input::GradientInput;
|
||||
pub use grayscale_conversion::GrayscaleConversion;
|
||||
pub use grayscale_mode::GrayscaleMode;
|
||||
pub use height_to_normal::HeightToNormal;
|
||||
pub use height_to_normal_method::HeightToNormalMethod;
|
||||
pub use highpass_space::HighpassSpace;
|
||||
pub use image_input::ImageInput;
|
||||
pub use layer::{
|
||||
@@ -121,6 +129,7 @@ pub use layer::{
|
||||
};
|
||||
pub use lighting_output::LightingOutput;
|
||||
pub use mask_outline::MaskOutline;
|
||||
pub use mesh_map_slot::MeshMapSlot;
|
||||
pub use mirror::Mirror;
|
||||
pub use mirror_corner::MirrorCorner;
|
||||
pub use mirror_mode::MirrorMode;
|
||||
@@ -135,6 +144,7 @@ pub use project::{
|
||||
pub use projector::Projector;
|
||||
pub use ramp_curve::RampCurve;
|
||||
pub use randomized_seed::RandomizedSeed;
|
||||
pub use resource_source::ResourceSource;
|
||||
pub use selection_background::SelectionBackground;
|
||||
pub use shape_crop::ShapeCrop;
|
||||
pub use slope_blending::SlopeBlending;
|
||||
@@ -149,6 +159,7 @@ pub use target_color_mode::TargetColorMode;
|
||||
pub use threshold_mode::ThresholdMode;
|
||||
pub use tile_transform::{FlipMode, RepeatMode, TileTransform};
|
||||
pub use unit_value::{at_or_above_threshold, finite_unit};
|
||||
pub use uv_padding_mode::UvPaddingMode;
|
||||
pub use validation_mode::ValidationMode;
|
||||
pub use warp_blending::WarpBlending;
|
||||
pub use warp_mode::WarpMode;
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
//! The mesh map an imported image file was resampled into
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::BakedMap;
|
||||
|
||||
/// A mesh map of a texture set, and the UV tile one image of it covers.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
pub struct MeshMapSlot {
|
||||
/// Index of the texture set.
|
||||
pub texture_set: usize,
|
||||
pub map: BakedMap,
|
||||
/// The UV tile the image covers (1001 on a set without UV tiles).
|
||||
pub tile: u32,
|
||||
}
|
||||
+261
-9
@@ -4,7 +4,10 @@ use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{BakeSettings, BakeSyncGroup, BakedMap, Channel, ChannelFormat, ContentsOffset, CoreError, Effect, Layer, LayerId, LayerKind, Result};
|
||||
use crate::{
|
||||
BakeSettings, BakeSource, BakeSyncGroup, BakedMap, Channel, ChannelFormat, ContentsOffset, CoreError, Effect, HeightToNormalMethod, Layer, LayerId,
|
||||
LayerKind, Result, UvPaddingMode,
|
||||
};
|
||||
|
||||
pub use crate::env_alignment::EnvAlignment;
|
||||
pub use crate::shadow_mode::ShadowMode;
|
||||
@@ -38,6 +41,22 @@ pub enum NormalMixing {
|
||||
Replace,
|
||||
}
|
||||
|
||||
impl NormalMixing {
|
||||
pub const ALL: [NormalMixing; 2] = [NormalMixing::Combine, NormalMixing::Replace];
|
||||
|
||||
/// Stable id for commands and inspect
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
NormalMixing::Combine => "combine",
|
||||
NormalMixing::Replace => "replace",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse(id: &str) -> Option<NormalMixing> {
|
||||
NormalMixing::ALL.into_iter().find(|mixing| mixing.id() == id)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
pub enum AoMixing {
|
||||
#[default]
|
||||
@@ -45,6 +64,22 @@ pub enum AoMixing {
|
||||
None,
|
||||
}
|
||||
|
||||
impl AoMixing {
|
||||
pub const ALL: [AoMixing; 2] = [AoMixing::Multiply, AoMixing::None];
|
||||
|
||||
/// Stable id for commands and inspect
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
AoMixing::Multiply => "multiply",
|
||||
AoMixing::None => "none",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse(id: &str) -> Option<AoMixing> {
|
||||
AoMixing::ALL.into_iter().find(|mixing| mixing.id() == id)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct TextureSet {
|
||||
pub name: String,
|
||||
@@ -52,15 +87,28 @@ pub struct TextureSet {
|
||||
pub description: String,
|
||||
/// Material index in the mesh this set paints.
|
||||
pub material: usize,
|
||||
/// Power of two, 128..=8192.
|
||||
/// Texels across: a power of two, 128..=8192 (the side of a square set)
|
||||
pub resolution: u32,
|
||||
/// Texels down when they differ from `resolution` (a power of two, 128..=8192); sets with per-tile resolutions stay square
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub resolution_height: Option<u32>,
|
||||
/// Channels and their storage formats; see [`TextureSet::formats`] for what they hold
|
||||
pub channels: Vec<(Channel, ChannelFormat)>,
|
||||
/// Whether channels hold their formats' precision; until a format is set every channel keeps 16 bits, what TextureCraft always stored
|
||||
#[serde(default)]
|
||||
pub format_precision: bool,
|
||||
/// Top-level layers, bottom → top.
|
||||
pub stack: Vec<LayerId>,
|
||||
#[serde(default)]
|
||||
pub normal_mixing: NormalMixing,
|
||||
#[serde(default)]
|
||||
pub ao_mixing: AoMixing,
|
||||
/// Height to normal method; projects without it keep Smooth, the filter their exports already used
|
||||
#[serde(default)]
|
||||
pub height_to_normal: HeightToNormalMethod,
|
||||
/// UV padding; projects without it keep padding from island edges (2D), the padding they were made with
|
||||
#[serde(default)]
|
||||
pub uv_padding: UvPaddingMode,
|
||||
/// Height-to-normal strength.
|
||||
#[serde(default = "one")]
|
||||
pub height_strength: f32,
|
||||
@@ -69,6 +117,12 @@ pub struct TextureSet {
|
||||
/// Mesh maps that have been baked (pixels live with the engine / project file).
|
||||
#[serde(default)]
|
||||
pub baked: BTreeSet<BakedMap>,
|
||||
/// What each baked map was baked from; a map without a record (imported, or older project) is never out of date
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub bake_sources: BTreeMap<BakedMap, BakeSource>,
|
||||
/// The one mesh map the app rebakes by itself when what it is baked from changes
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub auto_rebake: Option<BakedMap>,
|
||||
#[serde(default = "yes")]
|
||||
pub visible: bool,
|
||||
/// UDIM numbers of the UV tiles this set paints, ascending (UV tiles mode);
|
||||
@@ -164,13 +218,19 @@ impl TextureSet {
|
||||
description: String::new(),
|
||||
material,
|
||||
resolution,
|
||||
resolution_height: None,
|
||||
channels: Channel::DEFAULT_SET.iter().map(|c| (*c, ChannelFormat::default_for(*c))).collect(),
|
||||
format_precision: false,
|
||||
stack: Vec::new(),
|
||||
normal_mixing: NormalMixing::Combine,
|
||||
ao_mixing: AoMixing::Multiply,
|
||||
height_to_normal: HeightToNormalMethod::Smooth,
|
||||
uv_padding: UvPaddingMode::Space3d,
|
||||
height_strength: 1.0,
|
||||
bake: BakeSettings::default(),
|
||||
baked: BTreeSet::new(),
|
||||
bake_sources: BTreeMap::new(),
|
||||
auto_rebake: None,
|
||||
visible: true,
|
||||
uv_tiles: Vec::new(),
|
||||
bake_excluded_tiles: BTreeSet::new(),
|
||||
@@ -187,17 +247,61 @@ impl TextureSet {
|
||||
self.uv_tiles.is_empty() || self.uv_tiles.iter().any(|tile| !self.bake_excluded_tiles.contains(tile))
|
||||
}
|
||||
|
||||
/// Fingerprint of the shared bake settings (not the set's check) and baked UV tiles (not their working resolutions)
|
||||
pub fn bake_settings_fingerprint(&self) -> u64 {
|
||||
let mut common = self.bake.common;
|
||||
common.is_enabled = true;
|
||||
let shared = (common, &self.bake.high_poly, &self.bake.cage, &self.bake.skew, &self.uv_tiles, &self.bake_excluded_tiles);
|
||||
crate::fingerprint(serde_json::to_string(&shared).unwrap_or_default().as_bytes())
|
||||
}
|
||||
|
||||
/// Fingerprint of `map`'s own bake settings (not whether it is checked)
|
||||
pub fn map_settings_fingerprint(&self, map: BakedMap) -> u64 {
|
||||
crate::fingerprint(self.bake.maps.parameters_json(map).to_string().as_bytes())
|
||||
}
|
||||
|
||||
/// Height strength for slopes measured over the whole texture width (the viewport shader,
|
||||
/// the path tracer): a UV tile atlas is one tile per column wide.
|
||||
pub fn atlas_height_strength(&self) -> f32 {
|
||||
self.height_strength / self.tile_grid().map_or(1.0, |g| g.cols as f32)
|
||||
}
|
||||
|
||||
/// Texels across and down: [`TextureSet::block_resolution`] per block of the atlas grid.
|
||||
/// Columns over rows of the atlas grid (1 for a classic set): how much more slopes down the texture tilt than across it, as in export per block
|
||||
pub fn atlas_height_y_factor(&self) -> f32 {
|
||||
self.tile_grid().map_or(1.0, |g| g.cols as f32 / g.rows.max(1) as f32)
|
||||
}
|
||||
|
||||
/// Whether the height slope joins the shaded normal ([`NormalMixing::Replace`] leaves it out)
|
||||
pub fn height_in_normal(&self) -> bool {
|
||||
self.normal_mixing == NormalMixing::Combine
|
||||
}
|
||||
|
||||
/// Texels across and down: [`TextureSet::block_size`] per block of the atlas grid
|
||||
pub fn size(&self) -> (u32, u32) {
|
||||
let (cols, rows) = self.tile_grid().map_or((1, 1), |g| (g.cols, g.rows));
|
||||
let (width, height) = self.block_size();
|
||||
(width.saturating_mul(cols), height.saturating_mul(rows))
|
||||
}
|
||||
|
||||
/// Texels down of the set's size (`resolution` for a square set)
|
||||
pub fn height(&self) -> u32 {
|
||||
self.resolution_height.unwrap_or(self.resolution)
|
||||
}
|
||||
|
||||
/// Set the size to `width × height` (`height` stored only when it differs)
|
||||
pub fn set_size(&mut self, width: u32, height: u32) {
|
||||
self.resolution = width;
|
||||
self.resolution_height = (height != width).then_some(height);
|
||||
}
|
||||
|
||||
/// Texels across and down of an atlas block: the set's size, or the largest tile resolution square when tiles have their own
|
||||
pub fn block_size(&self) -> (u32, u32) {
|
||||
if self.tile_resolutions.is_empty() {
|
||||
return (self.resolution, self.height());
|
||||
}
|
||||
|
||||
let block = self.block_resolution();
|
||||
(block.saturating_mul(cols), block.saturating_mul(rows))
|
||||
(block, block)
|
||||
}
|
||||
|
||||
/// Texels per side of UV tile `udim` (its override, else `resolution`).
|
||||
@@ -205,12 +309,12 @@ impl TextureSet {
|
||||
self.tile_resolutions.get(&udim).copied().unwrap_or(self.resolution)
|
||||
}
|
||||
|
||||
/// Texels per side of an atlas block: the largest tile resolution (`resolution` for a
|
||||
/// classic set or one without overrides).
|
||||
/// Texels across an atlas block: the largest tile resolution (`resolution` without overrides); see [`TextureSet::block_size`]
|
||||
pub fn block_resolution(&self) -> u32 {
|
||||
if self.tile_resolutions.is_empty() {
|
||||
return self.resolution;
|
||||
}
|
||||
|
||||
self.uv_tiles.iter().map(|t| self.tile_resolution(*t)).max().unwrap_or(self.resolution)
|
||||
}
|
||||
|
||||
@@ -225,9 +329,20 @@ impl TextureSet {
|
||||
|
||||
/// [`TextureSet::tile_scale`] of every atlas block, to look up by atlas texel.
|
||||
pub fn block_scales(&self) -> BlockScales {
|
||||
let Some(g) = self.tile_grid().filter(|_| !self.tile_resolutions.is_empty()) else { return BlockScales::default() };
|
||||
let scales = (0..g.rows).flat_map(|by| (0..g.cols).map(move |bx| g.udim(bx, by))).map(|u| self.tile_scale(u)).collect();
|
||||
BlockScales { block: self.block_resolution(), cols: g.cols, scales }
|
||||
if self.tile_resolutions.is_empty() {
|
||||
return BlockScales::default();
|
||||
}
|
||||
|
||||
let Some(grid) = self.tile_grid() else { return BlockScales::default() };
|
||||
let block = self.block_resolution();
|
||||
let mut scales = vec![1.0; (grid.rows * grid.cols) as usize];
|
||||
for &tile in &self.uv_tiles {
|
||||
if let Some((column, row)) = grid.block(tile) {
|
||||
scales[(row * grid.cols + column) as usize] = (self.tile_resolution(tile) as f32 / block.max(1) as f32).clamp(1e-3, 1.0);
|
||||
}
|
||||
}
|
||||
|
||||
BlockScales { block, cols: grid.cols, scales }
|
||||
}
|
||||
|
||||
/// Scale of the tile holding mesh UV `uv` (v down) and that tile's origin corner.
|
||||
@@ -262,6 +377,49 @@ impl TextureSet {
|
||||
pub fn channel_list(&self) -> Vec<Channel> {
|
||||
self.channels.iter().map(|(c, _)| *c).collect()
|
||||
}
|
||||
|
||||
/// Channels the viewport can display individually, in texture-set order.
|
||||
pub fn viewport_channels(&self) -> impl Iterator<Item = Channel> + '_ {
|
||||
self.channels.iter().map(|(channel, _)| *channel).filter(|channel| channel.is_shaded())
|
||||
}
|
||||
|
||||
/// The channels with the formats they are stored in (8-bit ones read as 16-bit without `format_precision`)
|
||||
pub fn formats(&self) -> Vec<(Channel, ChannelFormat)> {
|
||||
self.iter_formats().collect()
|
||||
}
|
||||
|
||||
/// The effective storage formats in texture-set order
|
||||
pub fn iter_formats(&self) -> impl Iterator<Item = (Channel, ChannelFormat)> + '_ {
|
||||
self.channels.iter().map(|&(channel, format)| (channel, if self.format_precision { format } else { format.at_least_16_bit() }))
|
||||
}
|
||||
|
||||
/// Add channel `c` in its default format (16-bit or more until a format is set, see [`TextureSet::formats`]); false when present
|
||||
pub fn add_channel(&mut self, c: Channel) -> bool {
|
||||
if self.has_channel(c) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let format = ChannelFormat::default_for(c);
|
||||
self.channels.push((c, if self.format_precision { format.at_least_16_bit() } else { format }));
|
||||
self.channels.sort_by_key(|(c, _)| c.index());
|
||||
true
|
||||
}
|
||||
|
||||
/// Store channel `target` in `format` (false when the set lacks it); the other channels keep what they hold
|
||||
pub fn set_channel_format(&mut self, target: Channel, format: ChannelFormat) -> bool {
|
||||
if !self.has_channel(target) {
|
||||
return false;
|
||||
}
|
||||
|
||||
self.channels = self.formats();
|
||||
self.format_precision = true;
|
||||
for (channel, stored) in &mut self.channels {
|
||||
if *channel == target {
|
||||
*stored = format;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
@@ -403,6 +561,7 @@ impl DisplaySettings {
|
||||
}
|
||||
|
||||
const AIR_INDEX_OF_REFRACTION: f32 = 1.0;
|
||||
|
||||
// Specular Level 0.5 corresponds to OpenPBR specular weight 1
|
||||
const SPECULAR_LEVEL_TO_WEIGHT_SCALE: f32 = 2.0;
|
||||
let ior = self.ior.clamp(MIN_INDEX_OF_REFRACTION, MAX_INDEX_OF_REFRACTION);
|
||||
@@ -479,6 +638,10 @@ pub struct Project {
|
||||
/// The project's colour swatches (linear RGB), in the order they were added; projects without any save none
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub swatches: Vec<[f32; 3]>,
|
||||
/// The files image resources were imported from, by resource name (the Resources Updater
|
||||
/// reads them again). Resources made in the app or imported without a file path have none.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub resource_sources: BTreeMap<String, crate::ResourceSource>,
|
||||
}
|
||||
|
||||
impl Project {
|
||||
@@ -497,6 +660,7 @@ impl Project {
|
||||
display: DisplaySettings::default(),
|
||||
cameras: Vec::new(),
|
||||
swatches: Vec::new(),
|
||||
resource_sources: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -735,24 +899,37 @@ impl Project {
|
||||
if self.format_version > FORMAT_VERSION {
|
||||
return Err(CoreError::Invalid(format!("project format {} is newer than this TextureCraft supports ({FORMAT_VERSION})", self.format_version)));
|
||||
}
|
||||
|
||||
if let Some(t) = self.texture_sets.iter().find(|t| !t.uv_tiles.is_empty() && (t.tile_grid().is_none() || !t.uv_tiles.is_sorted_by(|a, b| a < b))) {
|
||||
return Err(CoreError::Invalid(format!("texture set \"{}\" has invalid UV tiles {:?}", t.name, t.uv_tiles)));
|
||||
}
|
||||
|
||||
let bad_tile_res = |t: &TextureSet| {
|
||||
t.tile_resolutions.iter().any(|(u, r)| !t.uv_tiles.contains(u) || !r.is_power_of_two() || !(MIN_RESOLUTION..=MAX_RESOLUTION).contains(r))
|
||||
};
|
||||
if let Some(t) = self.texture_sets.iter().find(|t| bad_tile_res(t)) {
|
||||
return Err(CoreError::Invalid(format!("texture set \"{}\" has invalid UV tile resolutions {:?}", t.name, t.tile_resolutions)));
|
||||
}
|
||||
|
||||
let bad_height = |set: &TextureSet| {
|
||||
set.resolution_height
|
||||
.is_some_and(|height| !height.is_power_of_two() || !(MIN_RESOLUTION..=MAX_RESOLUTION).contains(&height) || !set.tile_resolutions.is_empty())
|
||||
};
|
||||
if let Some(set) = self.texture_sets.iter().find(|set| bad_height(set)) {
|
||||
return Err(CoreError::Invalid(format!("texture set \"{}\" has an invalid height {:?}", set.name, set.resolution_height)));
|
||||
}
|
||||
|
||||
let mut seen = BTreeSet::new();
|
||||
for ts in 0..self.texture_sets.len() {
|
||||
for (id, depth) in self.walk(ts) {
|
||||
if depth > MAX_DEPTH {
|
||||
return Err(CoreError::Invalid("layer groups nested too deeply".into()));
|
||||
}
|
||||
|
||||
if !self.layers.contains_key(&id) {
|
||||
return Err(CoreError::Invalid(format!("stack references missing layer {}", id.0)));
|
||||
}
|
||||
|
||||
if !seen.insert(id) {
|
||||
return Err(CoreError::Invalid(format!("layer {} appears twice", id.0)));
|
||||
}
|
||||
@@ -844,6 +1021,37 @@ mod tests {
|
||||
p
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn older_sets_without_the_new_fields_open_square_with_2d_padding_and_smooth_normals() {
|
||||
let mut v = serde_json::to_value(TextureSet::new("a", 0, 256)).unwrap();
|
||||
for field in ["resolution_height", "format_precision", "height_to_normal", "uv_padding"] {
|
||||
v.as_object_mut().unwrap().remove(field);
|
||||
}
|
||||
|
||||
let old: TextureSet = serde_json::from_value(v).unwrap();
|
||||
|
||||
assert_eq!(old.size(), (256, 256));
|
||||
assert_eq!((old.uv_padding, old.height_to_normal), (UvPaddingMode::Space2d, HeightToNormalMethod::Smooth));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sets_keep_16_bits_until_a_format_is_set_also_in_older_files() {
|
||||
let new = TextureSet::new("a", 0, 128);
|
||||
let mut v = serde_json::to_value(&new).unwrap();
|
||||
v.as_object_mut().unwrap().remove("format_precision");
|
||||
let mut old: TextureSet = serde_json::from_value(v).unwrap();
|
||||
let format = |t: &TextureSet, c: Channel| t.formats().into_iter().find(|(x, _)| *x == c).map(|(_, f)| f);
|
||||
|
||||
assert_eq!(format(&new, Channel::Roughness), Some(ChannelFormat::L16));
|
||||
assert_eq!(format(&old, Channel::Roughness), Some(ChannelFormat::L16));
|
||||
assert_eq!(format(&old, Channel::BaseColor), Some(ChannelFormat::Rgb16));
|
||||
|
||||
assert!(old.set_channel_format(Channel::Metallic, ChannelFormat::L8));
|
||||
assert_eq!(format(&old, Channel::Metallic), Some(ChannelFormat::L8));
|
||||
assert_eq!(format(&old, Channel::Roughness), Some(ChannelFormat::L16), "the other channels keep their precision");
|
||||
assert!(!old.set_channel_format(Channel::Emissive, ChannelFormat::L8), "a channel the set lacks");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enabling_ior_at_the_default_preserves_legacy_reflectance() {
|
||||
let mut display = DisplaySettings::default();
|
||||
@@ -1098,6 +1306,50 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn atlas_slopes_along_each_side_match_a_block_in_wide_tall_and_square_grids() {
|
||||
let mut t = TextureSet::new("a", 0, 256);
|
||||
t.height_strength = 3.0;
|
||||
for tiles in [vec![1001, 1002], vec![1001, 1011], vec![1001, 1002, 1011, 1012], vec![1001, 1002, 1003]] {
|
||||
t.uv_tiles = tiles;
|
||||
let ((width, height), (block_width, block_height)) = (t.size(), t.block_size());
|
||||
|
||||
let across = t.atlas_height_strength() * width as f32;
|
||||
let down = t.atlas_height_strength() * t.atlas_height_y_factor() * height as f32;
|
||||
|
||||
assert_eq!(across, t.height_strength * block_width as f32, "{:?}", t.uv_tiles);
|
||||
assert_eq!(down, t.height_strength * block_height as f32, "{:?}", t.uv_tiles);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_square_sets_are_wider_than_tall_per_block_and_stay_square_with_tile_sizes() {
|
||||
let mut p = project();
|
||||
let t = &mut p.texture_sets[0];
|
||||
t.set_size(1024, 256);
|
||||
let (w, h) = t.size();
|
||||
assert!(w > h, "{:?}", t.size());
|
||||
t.uv_tiles = vec![1001, 1011];
|
||||
|
||||
// Tiles stack down, each block keeping the set's shape
|
||||
assert_eq!(t.size(), (w, h * 2));
|
||||
p.validate().unwrap();
|
||||
|
||||
// A height must be a valid size, and per-tile sizes need a square set
|
||||
for bad in [Some(100), Some(16384)] {
|
||||
let mut q = p.clone();
|
||||
q.texture_sets[0].resolution_height = bad;
|
||||
assert!(q.validate().is_err(), "{bad:?}");
|
||||
}
|
||||
let mut q = p.clone();
|
||||
q.texture_sets[0].tile_resolutions.insert(1011, 128);
|
||||
assert!(q.validate().is_err());
|
||||
|
||||
// The same size both ways is stored as square
|
||||
p.texture_sets[0].set_size(512, 512);
|
||||
assert_eq!(p.texture_sets[0].resolution_height, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_rejects_newer_formats_and_dangling_ids() {
|
||||
let mut p = project();
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
//! Where an image resource was imported from, so the Resources Updater can read it again
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// The file an image resource was read from and its modification time then.
|
||||
///
|
||||
/// The resource's stored bytes are the file's bytes at that time, so a file whose size or
|
||||
/// contents differ from them has changed on disk.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ResourceSource {
|
||||
/// Path of the file on the machine that imported it.
|
||||
pub path: String,
|
||||
/// The file's modification time when it was read, in milliseconds since the Unix epoch
|
||||
/// (0 when unknown). An unchanged time and size skip reading the file again.
|
||||
#[serde(default)]
|
||||
pub modified_ms: u64,
|
||||
/// The mesh map the file was imported as (`textureSet.meshMap.import`): an update resamples it
|
||||
/// again while the map still holds what this file gave it.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub mesh_map: Option<crate::MeshMapSlot>,
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
//! Where a texture set's UV padding takes its texels from
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// UV padding mode: what fills the texels just outside a texture set's UV islands
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
pub enum UvPaddingMode {
|
||||
/// Across seams (3D): past a UV seam, the texels continue the surface from the seam's other side
|
||||
Space3d,
|
||||
/// From island edges (2D): every texel repeats the nearest covered texel in the texture
|
||||
#[default]
|
||||
Space2d,
|
||||
}
|
||||
|
||||
impl UvPaddingMode {
|
||||
pub const ALL: [UvPaddingMode; 2] = [UvPaddingMode::Space3d, UvPaddingMode::Space2d];
|
||||
|
||||
/// Stable id for commands and inspect
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
UvPaddingMode::Space3d => "3d",
|
||||
UvPaddingMode::Space2d => "2d",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse(id: &str) -> Option<UvPaddingMode> {
|
||||
UvPaddingMode::ALL.into_iter().find(|value| value.id() == id)
|
||||
}
|
||||
}
|
||||
@@ -18,12 +18,13 @@ texturecraft-paint = { workspace = true }
|
||||
texturecraft-bake = { workspace = true }
|
||||
texturecraft-formats = { workspace = true }
|
||||
rayon = { workspace = true }
|
||||
epaint_default_fonts = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
# The built-in text fonts; the web build gets them from the app (`text_cmds::provide_built_in_fonts`).
|
||||
epaint_default_fonts = { workspace = true }
|
||||
tempfile = "3"
|
||||
|
||||
[target.'cfg(any(target_os = "macos", target_os = "freebsd"))'.dependencies]
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
//! Auto-rebake: the one mesh map per texture set that is baked again whenever what it is baked from changes
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_core::{BakeSource, BakedMap};
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad, strp, u64p};
|
||||
use crate::{Result, Session, cmd};
|
||||
|
||||
pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"bake.autoRebake",
|
||||
"Auto-rebake",
|
||||
[],
|
||||
None,
|
||||
"{ts?: index (default: the active set), map: id | null} → {ts, autoRebake: id | null}. Turn on Auto-rebake for one mesh map of the set (it replaces the set's previous one), or turn it off with null. The app then rebakes that map in the background once what it is baked from changes",
|
||||
always,
|
||||
set_auto_rebake
|
||||
)]
|
||||
}
|
||||
|
||||
fn set_auto_rebake(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
const COMMAND: &str = "bake.autoRebake";
|
||||
let texture_set = match params.get("ts") {
|
||||
None => session.ts(),
|
||||
Some(_) => u64p(params, "ts")
|
||||
.and_then(|index| usize::try_from(index).ok())
|
||||
.filter(|index| *index < session.set_count())
|
||||
.ok_or_else(|| bad(COMMAND, "invalid `ts`"))?,
|
||||
};
|
||||
let map = match params.get("map") {
|
||||
Some(Value::Null) => None,
|
||||
Some(_) => Some(strp(params, "map").and_then(BakedMap::parse).ok_or_else(|| bad(COMMAND, "`map` must be a mesh map id or null"))?),
|
||||
None => return Err(bad(COMMAND, "`map` is required (a mesh map id or null)")),
|
||||
};
|
||||
|
||||
if session.doc.project.texture_set(texture_set)?.auto_rebake != map {
|
||||
session.edit("Auto-rebake", |session| {
|
||||
session.doc.project.texture_set_mut(texture_set)?.auto_rebake = map;
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
|
||||
Ok(json!({ "ts": texture_set, "autoRebake": map.map(BakedMap::id) }))
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// The auto-rebake maps that are out of date now, as (texture set, map, what a bake would read now)
|
||||
pub fn auto_rebake_due(&self) -> Vec<(usize, BakedMap, BakeSource)> {
|
||||
let sets = self.doc.project.texture_sets.iter().enumerate();
|
||||
sets.filter_map(|(index, set)| {
|
||||
let map = set.auto_rebake?;
|
||||
let record = set.bake_sources.get(&map).filter(|_| set.baked.contains(&map))?;
|
||||
let current = self.bake_source(index, map).ok()?;
|
||||
(*record != current).then_some((index, map, current))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Bake the selected map alone, or include every checked map if the atlas changed size
|
||||
pub fn auto_rebake_maps(&self, texture_set: usize, map: BakedMap) -> Vec<BakedMap> {
|
||||
let Ok(set) = self.doc.project.texture_set(texture_set) else { return vec![map] };
|
||||
|
||||
let (tile_width, tile_height) = set.bake.common.output_size();
|
||||
let (columns, rows) = set.tile_grid().map_or((1, 1), |grid| (grid.cols, grid.rows));
|
||||
let (width, height) = (tile_width * columns, tile_height * rows);
|
||||
let stored = self.doc.baked.get(&texture_set);
|
||||
let resized = stored.is_some_and(|stored| stored.resolution != width || stored.maps.keys().any(|baked| stored.height(*baked) != height));
|
||||
match resized {
|
||||
true => BakedMap::ALL.into_iter().filter(|baked| *baked == map || set.bake.maps.is_enabled(*baked)).collect(),
|
||||
false => vec![map],
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
use serde::Serialize;
|
||||
|
||||
/// Where one high poly file of a bake stands, as the Baking Log shows it
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase", tag = "state", content = "reason")]
|
||||
pub enum BakeHighState {
|
||||
/// Its texture set has not started baking
|
||||
Waiting,
|
||||
Loading,
|
||||
Loaded,
|
||||
/// Its texture set's bake failed while getting the high polys ready; the reason is the error
|
||||
Failed(String),
|
||||
/// The bake stopped before the file was loaded
|
||||
Canceled,
|
||||
}
|
||||
|
||||
impl BakeHighState {
|
||||
/// Whether the file can still change in this bake
|
||||
pub fn is_pending(&self) -> bool {
|
||||
matches!(self, Self::Waiting | Self::Loading)
|
||||
}
|
||||
|
||||
/// Whether the file counts as an issue in the log
|
||||
pub fn is_issue(&self) -> bool {
|
||||
matches!(self, Self::Failed(_) | Self::Canceled)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
use std::collections::HashSet;
|
||||
|
||||
use texturecraft_bake::NamePair;
|
||||
use texturecraft_core::{BakedMap, MeshMatchMode, Project};
|
||||
|
||||
use super::{BakeHighState, BakeLogHigh, BakeLogMap, BakeLogMatching, BakeMapState, BakeMesh};
|
||||
use crate::Session;
|
||||
|
||||
/// The latest bake map by map for the Baking Log, kept from the bake's own state, never from Log lines
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct BakeLog {
|
||||
pub maps: Vec<BakeLogMap>,
|
||||
/// Each high poly file of each texture set that bakes from the high polys, in bake order
|
||||
pub highs: Vec<BakeLogHigh>,
|
||||
/// How the parts paired by name; `None` when no set of the bake matches "By Mesh Name"
|
||||
pub matching: Option<BakeLogMatching>,
|
||||
}
|
||||
|
||||
impl BakeLog {
|
||||
/// Start over for a bake of `sets`: every checked map of each set and the `high_polys` of each set that bakes from them, waiting, in bake order
|
||||
pub fn begin(&mut self, project: &Project, high_polys: &[BakeMesh], sets: &[usize]) {
|
||||
self.maps = sets
|
||||
.iter()
|
||||
.filter_map(|index| project.texture_sets.get(*index).map(|set| (*index, set)))
|
||||
.flat_map(|(index, set)| {
|
||||
set.bake.maps.enabled().map(move |map| BakeLogMap { texture_set: index, set_name: set.name.clone(), map, state: BakeMapState::Waiting })
|
||||
})
|
||||
.collect();
|
||||
self.highs = sets
|
||||
.iter()
|
||||
.filter_map(|index| project.texture_sets.get(*index).map(|set| (*index, set)))
|
||||
.filter(|(_, set)| !set.bake.high_poly.use_low_as_high)
|
||||
.flat_map(|(index, set)| {
|
||||
high_polys.iter().map(move |high| BakeLogHigh {
|
||||
texture_set: index,
|
||||
set_name: set.name.clone(),
|
||||
file: high.name.clone(),
|
||||
state: BakeHighState::Waiting,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
self.matching = None;
|
||||
}
|
||||
|
||||
/// `set` starts baking: its high polys load and its first map is the one in progress
|
||||
pub fn set_started(&mut self, set: usize) {
|
||||
for row in self.highs.iter_mut().filter(|row| row.texture_set == set && row.state == BakeHighState::Waiting) {
|
||||
row.state = BakeHighState::Loading;
|
||||
}
|
||||
self.start_next(set);
|
||||
}
|
||||
|
||||
/// `set`'s bake has its high polys ready
|
||||
pub fn high_polys_loaded(&mut self, set: usize) {
|
||||
for row in self.highs.iter_mut().filter(|row| row.texture_set == set && row.state == BakeHighState::Loading) {
|
||||
row.state = BakeHighState::Loaded;
|
||||
}
|
||||
}
|
||||
|
||||
/// `map` of `set` is baked; the set's next map starts
|
||||
pub fn map_baked(&mut self, set: usize, map: BakedMap) {
|
||||
if let Some(row) = self.maps.iter_mut().find(|row| row.texture_set == set && row.map == map) {
|
||||
row.state = BakeMapState::Baked;
|
||||
}
|
||||
self.start_next(set);
|
||||
}
|
||||
|
||||
/// `set`'s bake was kept: a map it did not hand over is not baked
|
||||
pub fn set_finished(&mut self, set: usize) {
|
||||
for row in self.maps.iter_mut().filter(|row| row.texture_set == set && row.state.is_pending()) {
|
||||
row.state = BakeMapState::Canceled;
|
||||
}
|
||||
}
|
||||
|
||||
/// Nothing of `set` was kept: every one of its maps failed for `reason`
|
||||
pub fn set_failed(&mut self, set: usize, reason: &str) {
|
||||
for row in self.maps.iter_mut().filter(|row| row.texture_set == set) {
|
||||
row.state = BakeMapState::Failed(reason.to_owned());
|
||||
}
|
||||
|
||||
// A file that loaded is not what failed
|
||||
for row in self.highs.iter_mut().filter(|row| row.texture_set == set && row.state.is_pending()) {
|
||||
row.state = BakeHighState::Failed(reason.to_owned());
|
||||
}
|
||||
}
|
||||
|
||||
/// The bake stopped: every map still waiting or baking is canceled, and so are the finished maps of `discarded` (the set being baked, when they were not kept)
|
||||
pub fn cancel(&mut self, discarded: Option<usize>) {
|
||||
for row in &mut self.maps {
|
||||
if row.state.is_pending() || (Some(row.texture_set) == discarded && row.state == BakeMapState::Baked) {
|
||||
row.state = BakeMapState::Canceled;
|
||||
}
|
||||
}
|
||||
self.cancel_pending_highs();
|
||||
}
|
||||
|
||||
/// The whole bake was rolled back: every map that did not fail is canceled
|
||||
pub fn discard(&mut self) {
|
||||
for row in self.maps.iter_mut().filter(|row| !matches!(row.state, BakeMapState::Failed(_))) {
|
||||
row.state = BakeMapState::Canceled;
|
||||
}
|
||||
self.cancel_pending_highs();
|
||||
}
|
||||
|
||||
/// Whether a map is still waiting or baking
|
||||
pub fn is_running(&self) -> bool {
|
||||
self.maps.iter().any(|row| row.state.is_pending())
|
||||
}
|
||||
|
||||
/// Whether a high poly file is still waiting or loading
|
||||
pub fn is_loading_high_polys(&self) -> bool {
|
||||
self.highs.iter().any(|row| row.state.is_pending())
|
||||
}
|
||||
|
||||
fn cancel_pending_highs(&mut self) {
|
||||
for row in self.highs.iter_mut().filter(|row| row.state.is_pending()) {
|
||||
row.state = BakeHighState::Canceled;
|
||||
}
|
||||
}
|
||||
|
||||
fn start_next(&mut self, set: usize) {
|
||||
if self.maps.iter().any(|row| row.texture_set == set && row.state == BakeMapState::Baking) {
|
||||
return;
|
||||
}
|
||||
|
||||
if let Some(row) = self.maps.iter_mut().find(|row| row.texture_set == set && row.state == BakeMapState::Waiting) {
|
||||
row.state = BakeMapState::Baking;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Start the Baking Log over for a bake of `sets` ([`BakeLog::begin`]), with how their parts pair by name
|
||||
pub fn begin_bake_log(&mut self, sets: &[usize]) {
|
||||
let matching = self.bake_log_matching(sets);
|
||||
self.bake_log.begin(&self.doc.project, &self.doc.bake_meshes.high, sets);
|
||||
self.bake_log.matching = matching;
|
||||
}
|
||||
|
||||
/// Start the Baking Log for a bake of only `maps` of each of `sets`, checked or not
|
||||
pub fn begin_map_bake_log(&mut self, sets: &[usize], maps: &[BakedMap]) {
|
||||
self.begin_bake_log(sets);
|
||||
let project = &self.doc.project;
|
||||
self.bake_log.maps = sets
|
||||
.iter()
|
||||
.filter_map(|&texture_set| Some((texture_set, project.texture_sets.get(texture_set)?.name.clone())))
|
||||
.flat_map(|(texture_set, set_name)| {
|
||||
maps.iter().map(move |&map| BakeLogMap { texture_set, set_name: set_name.clone(), map, state: BakeMapState::Waiting })
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
|
||||
/// The name pairs of each of `sets` that matches "By Mesh Name"; a high poly part counts as unpaired only when none of them pairs with it and no set matching "Always" bakes from every part
|
||||
fn bake_log_matching(&self, sets: &[usize]) -> Option<BakeLogMatching> {
|
||||
let mut matching: Option<BakeLogMatching> = None;
|
||||
let (mut paired_highs, mut unpaired_highs) = (HashSet::new(), Vec::new());
|
||||
let mut every_high_used = false;
|
||||
for &set in sets {
|
||||
let Ok(texture_set) = self.doc.project.texture_set(set) else { continue };
|
||||
|
||||
let settings = &texture_set.bake.high_poly;
|
||||
every_high_used |= !settings.use_low_as_high && settings.match_mode == MeshMatchMode::Always;
|
||||
let Ok(Some(pairs)) = self.bake_name_pairs(set) else { continue };
|
||||
|
||||
let matching = matching.get_or_insert_with(|| BakeLogMatching {
|
||||
low_suffix: settings.low_suffix.clone(),
|
||||
high_suffix: settings.high_suffix.clone(),
|
||||
pairs: Vec::new(),
|
||||
});
|
||||
for pair in pairs {
|
||||
match (&pair.low, &pair.high) {
|
||||
(None, Some(high)) if !unpaired_highs.contains(high) => unpaired_highs.push(high.clone()),
|
||||
(None, _) => {}
|
||||
(Some(_), high) => {
|
||||
paired_highs.extend(high.clone());
|
||||
matching.pairs.push(pair);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(matching) = matching.as_mut().filter(|_| !every_high_used) {
|
||||
let unpaired = unpaired_highs.into_iter().filter(|high| !paired_highs.contains(high));
|
||||
matching.pairs.extend(unpaired.map(|high| NamePair { low: None, high: Some(high) }));
|
||||
}
|
||||
matching
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
use super::BakeHighState;
|
||||
|
||||
/// One row of the Baking Log's high poly list: a high poly file a texture set bakes from in the latest bake
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct BakeLogHigh {
|
||||
pub texture_set: usize,
|
||||
pub set_name: String,
|
||||
/// The file's name as the project keeps it (the project carries the file itself, not where it came from)
|
||||
pub file: String,
|
||||
pub state: BakeHighState,
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
use texturecraft_core::BakedMap;
|
||||
|
||||
use super::BakeMapState;
|
||||
|
||||
/// One row of the Baking Log's process list: a map of a texture set in the latest bake
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct BakeLogMap {
|
||||
pub texture_set: usize,
|
||||
pub set_name: String,
|
||||
pub map: BakedMap,
|
||||
pub state: BakeMapState,
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
use texturecraft_bake::NamePair;
|
||||
|
||||
/// The Baking Log's matching list: how the latest bake paired low poly parts with high poly parts by name
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct BakeLogMatching {
|
||||
/// The suffixes the first set matching by name strips, for the column captions
|
||||
pub low_suffix: String,
|
||||
pub high_suffix: String,
|
||||
/// Each low poly part with the high poly part it bakes from, then the high poly parts no set of the bake pairs with
|
||||
pub pairs: Vec<NamePair>,
|
||||
}
|
||||
|
||||
impl BakeLogMatching {
|
||||
/// How many parts found no partner
|
||||
pub fn issue_count(&self) -> usize {
|
||||
self.pairs.iter().filter(|pair| pair.unpaired()).count()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
use serde::Serialize;
|
||||
|
||||
/// Where one map of a bake stands, as the Baking Log shows it
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase", tag = "state", content = "reason")]
|
||||
pub enum BakeMapState {
|
||||
Waiting,
|
||||
Baking,
|
||||
Baked,
|
||||
/// The bake of its texture set failed; the reason is the error
|
||||
Failed(String),
|
||||
/// The bake stopped before this map was kept
|
||||
Canceled,
|
||||
}
|
||||
|
||||
impl BakeMapState {
|
||||
/// Whether the map can still change in this bake
|
||||
pub fn is_pending(&self) -> bool {
|
||||
matches!(self, Self::Waiting | Self::Baking)
|
||||
}
|
||||
|
||||
/// Whether the map counts as an issue in the log
|
||||
pub fn is_issue(&self) -> bool {
|
||||
matches!(self, Self::Failed(_) | Self::Canceled)
|
||||
}
|
||||
}
|
||||
@@ -11,4 +11,6 @@ pub struct BakeMesh {
|
||||
pub bytes: Arc<Vec<u8>>,
|
||||
pub mesh: Arc<Mesh>,
|
||||
pub base_color: Vec<Option<Arc<BaseColor>>>,
|
||||
/// [`texturecraft_core::fingerprint`] of `bytes`: what bakes from this file record
|
||||
pub fingerprint: u64,
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
//! What each baked map was baked from, and which maps are out of date since
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use texturecraft_core::{BakeChange, BakeSource, BakedMap, CageType, TextureSet, fingerprint, fingerprint_words};
|
||||
|
||||
use crate::{Result, Session};
|
||||
|
||||
impl Session {
|
||||
/// What a bake of `map` on texture set `texture_set` would read now
|
||||
pub fn bake_source(&self, texture_set: usize, map: BakedMap) -> Result<BakeSource> {
|
||||
let set = self.doc.project.texture_set(texture_set)?;
|
||||
Ok(self.map_bake_source(set, map, self.set_bake_source(set)))
|
||||
}
|
||||
|
||||
/// The inputs of the maps selected for one task.
|
||||
pub(super) fn task_bake_sources(&self, set: &TextureSet, maps: impl Iterator<Item = BakedMap>) -> BTreeMap<BakedMap, BakeSource> {
|
||||
let shared = std::cell::LazyCell::new(|| self.set_bake_source(set));
|
||||
maps.map(|map| (map, self.map_bake_source(set, map, *shared))).collect()
|
||||
}
|
||||
|
||||
/// The inputs shared by every map in a texture set.
|
||||
fn set_bake_source(&self, set: &TextureSet) -> BakeSource {
|
||||
let from_high = !set.bake.high_poly.use_low_as_high && !self.doc.bake_meshes.high.is_empty();
|
||||
let high_poly = match from_high {
|
||||
true => fingerprint_words(self.doc.bake_meshes.high.iter().map(|high| high.fingerprint)),
|
||||
false => 0,
|
||||
};
|
||||
let reads_cage = from_high && set.bake.cage.kind == CageType::CustomFile;
|
||||
let cage = self.doc.bake_meshes.cage.as_ref().filter(|_| reads_cage).map_or(0, |cage| cage.fingerprint);
|
||||
|
||||
BakeSource {
|
||||
low_poly: self.low_poly_fingerprint(),
|
||||
low_material_file: None,
|
||||
high_poly,
|
||||
cage,
|
||||
settings: set.bake_settings_fingerprint(),
|
||||
map_settings: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn map_bake_source(&self, set: &TextureSet, map: BakedMap, shared: BakeSource) -> BakeSource {
|
||||
let reads_low_colors = shared.high_poly == 0 && set.bake.maps.reads_material_colors(map);
|
||||
let low_material_file =
|
||||
self.mesh_source.as_ref().filter(|_| reads_low_colors).map(|(_, bytes)| *self.low_material_file_fingerprint.get_or_init(|| fingerprint(bytes)));
|
||||
|
||||
BakeSource { low_material_file, map_settings: set.map_settings_fingerprint(map), ..shared }
|
||||
}
|
||||
|
||||
/// What changed since `map` of texture set `texture_set` was baked; empty when up to date, not baked or without a record
|
||||
pub fn bake_changes(&self, texture_set: usize, map: BakedMap) -> Vec<BakeChange> {
|
||||
let Ok(set) = self.doc.project.texture_set(texture_set) else { return Vec::new() };
|
||||
|
||||
let Some(record) = set.bake_sources.get(&map).filter(|_| set.baked.contains(&map)) else { return Vec::new() };
|
||||
|
||||
self.bake_source(texture_set, map).map(|current| record.changes(¤t)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The out-of-date maps of texture set `texture_set`, each with what changed
|
||||
pub fn out_of_date_maps(&self, texture_set: usize) -> BTreeMap<BakedMap, Vec<BakeChange>> {
|
||||
let Ok(set) = self.doc.project.texture_set(texture_set) else { return BTreeMap::new() };
|
||||
|
||||
let mut records = set.bake_sources.iter().filter(|(map, _)| set.baked.contains(map)).peekable();
|
||||
|
||||
if records.peek().is_none() {
|
||||
return BTreeMap::new();
|
||||
}
|
||||
|
||||
let shared = self.set_bake_source(set);
|
||||
let changes = records.map(|(map, record)| (*map, record.changes(&self.map_bake_source(set, *map, shared))));
|
||||
changes.filter(|(_, changes)| !changes.is_empty()).collect()
|
||||
}
|
||||
|
||||
/// Fingerprint of the low poly's geometry, tangent frame, vertex colors and part assignments (computed once per loaded mesh)
|
||||
fn low_poly_fingerprint(&self) -> u64 {
|
||||
*self.low_poly_fingerprint.get_or_init(|| {
|
||||
let source = &self.source;
|
||||
let floats = source
|
||||
.positions
|
||||
.iter()
|
||||
.chain(&source.normals)
|
||||
.flat_map(|vector| vector.to_array())
|
||||
.chain(source.tangents.iter().flat_map(|tangent| tangent.to_array()))
|
||||
.chain(source.uvs.iter().flat_map(|uv| uv.to_array()))
|
||||
.chain(source.colors.iter().flat_map(|color| color.to_array()));
|
||||
let indices = source.indices.iter().copied().map(u64::from);
|
||||
let parts =
|
||||
source.submeshes.iter().flat_map(|part| [fingerprint(part.name.as_bytes()), part.material as u64, part.start.into(), part.count.into()]);
|
||||
|
||||
fingerprint_words(floats.map(|float| u64::from(float.to_bits())).chain(indices).chain(parts))
|
||||
})
|
||||
}
|
||||
|
||||
/// Keep what the `stored` maps of `texture_set` were baked from and the newest stroke their bake saw; without it they lose their record
|
||||
pub(super) fn record_bake_sources(
|
||||
&mut self,
|
||||
texture_set: usize,
|
||||
recorded: Option<(&BTreeMap<BakedMap, BakeSource>, u64)>,
|
||||
stored: &[BakedMap],
|
||||
) -> Result<()> {
|
||||
let set = self.doc.project.texture_set_mut(texture_set)?;
|
||||
match recorded {
|
||||
Some((sources, _)) => set.bake_sources.extend(sources),
|
||||
None => set.bake_sources.retain(|map, _| !stored.contains(map)),
|
||||
}
|
||||
|
||||
let baked = &set.baked;
|
||||
set.bake_sources.retain(|map, _| baked.contains(map));
|
||||
if let Some((_, painted_stroke)) = recorded {
|
||||
self.forget_painted_region(texture_set, stored, painted_stroke);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,12 @@
|
||||
use super::{MergedHigh, StreamedBake, StreamedMap};
|
||||
use crate::{EngineError, Result};
|
||||
use std::sync::Arc;
|
||||
use texturecraft_bake::{BakeOutput, BakePaintMap, BakePasses, BakeRequest, HighPoly, Progress, bake_tiles, tracing::Tracer};
|
||||
use texturecraft_bake::{BakeOutput, BakePaintMap, BakePasses, BakeRequest, HighPoly, Progress, RegionBake, TexelBox, bake_tiles_in, tracing::Tracer};
|
||||
use texturecraft_compose::BakedMaps;
|
||||
use texturecraft_core::{BakeSettings, BakedMap};
|
||||
use texturecraft_geom::{Bvh, Mesh};
|
||||
|
||||
/// A self-contained bake task that can run on another thread.
|
||||
/// A self-contained bake task that can run on another thread
|
||||
pub struct BakeTask {
|
||||
pub low_base_color: super::MaterialColors,
|
||||
pub ts: usize,
|
||||
@@ -14,18 +14,24 @@ pub struct BakeTask {
|
||||
pub bvh: Arc<Bvh>,
|
||||
pub material: usize,
|
||||
pub settings: BakeSettings,
|
||||
/// The merged high polys, unless the set bakes from the low poly.
|
||||
/// The merged high polys, unless the set bakes from the low poly
|
||||
pub high: Option<MergedHigh>,
|
||||
pub cage: Option<Arc<Mesh>>,
|
||||
pub skew: Option<Arc<BakePaintMap>>,
|
||||
pub cage_paint: Option<Arc<BakePaintMap>>,
|
||||
/// UV tile grid (columns, rows) of the set; (1, 1) without UV tiles.
|
||||
/// UV tile grid (columns, rows) of the set; (1, 1) without UV tiles
|
||||
pub tiles: (u32, u32),
|
||||
/// Snapshot of tile selection and pixels to retain while the worker runs
|
||||
pub excluded_tiles: Vec<(u32, u32)>,
|
||||
pub previous_maps: BakedMaps,
|
||||
/// The GPU ray tracer, if installed and not turned off (`bake.run {cpu: true}`).
|
||||
/// The GPU ray tracer, if installed and not turned off (`bake.run {cpu: true}`)
|
||||
pub tracer: Option<Arc<dyn Tracer>>,
|
||||
/// What each map this task makes is baked from, taken when the task was made
|
||||
pub sources: std::collections::BTreeMap<BakedMap, texturecraft_core::BakeSource>,
|
||||
/// The newest skew or cage stroke when the task was made; a later stroke still needs a rebake
|
||||
pub painted_stroke: u64,
|
||||
/// Sample only these texels and take the rest from `previous_maps` (the same size); `None` samples every texel
|
||||
pub region: Option<TexelBox>,
|
||||
}
|
||||
|
||||
impl BakeTask {
|
||||
@@ -34,13 +40,7 @@ impl BakeTask {
|
||||
self.settings.maps.enabled().collect()
|
||||
}
|
||||
|
||||
/// Bake the maps one after another, handing each one to `on_map` as soon as it is padded,
|
||||
/// and return all of them together. Each map is a bake of its own, so with a high poly
|
||||
/// the transfer rays are cast once per map: slower than [`BakeTask::run`] with several
|
||||
/// maps, in exchange for showing them as they land. The pixels are the same as `run`'s.
|
||||
/// The handed-over buffers are the returned ones too (no copy is made), so a preview that
|
||||
/// keeps them costs no second set of maps. A cancel or an error leaves the maps already
|
||||
/// handed over whole.
|
||||
/// Bake the maps one by one (same pixels as [`BakeTask::run`], rays cast per map), handing each padded map's shared buffer to `on_map`, then return them all
|
||||
pub fn run_streaming(&self, progress: &Progress, on_map: &mut dyn FnMut(StreamedMap)) -> Result<StreamedBake> {
|
||||
let maps = self.maps();
|
||||
let total = maps.len();
|
||||
@@ -48,7 +48,7 @@ impl BakeTask {
|
||||
|
||||
let mut passes = BakePasses::new(self.request());
|
||||
for (index, map) in maps.iter().copied().enumerate() {
|
||||
let mut output = passes.bake_map(map, progress, &self.excluded_tiles, self.tracer.as_deref()).map_err(bake_error)?;
|
||||
let mut output = passes.bake_map_in(map, progress, &self.excluded_tiles, self.region(), self.tracer.as_deref()).map_err(bake_error)?;
|
||||
super::preserve_tiles::restore(&mut output, &self.previous_maps, &self.excluded_tiles, self.tiles)?;
|
||||
let Some(data) = output.maps.remove(&map) else { continue };
|
||||
if combined.is_none() {
|
||||
@@ -66,7 +66,14 @@ impl BakeTask {
|
||||
// A resized partial bake also returns unchecked maps that must survive application
|
||||
let mut retained: std::collections::BTreeMap<_, _> = output.maps.into_iter().map(|(map, pixels)| (map, Arc::new(pixels))).collect();
|
||||
retained.insert(map, data);
|
||||
combined = Some(StreamedBake { resolution: output.resolution, height: output.height, maps: retained, tracer: output.tracer });
|
||||
combined = Some(StreamedBake {
|
||||
resolution: output.resolution,
|
||||
height: output.height,
|
||||
maps: retained,
|
||||
tracer: output.tracer,
|
||||
sources: self.sources.clone(),
|
||||
painted_stroke: self.painted_stroke,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -80,18 +87,25 @@ impl BakeTask {
|
||||
height: output.height,
|
||||
maps: output.maps.into_iter().map(|(map, pixels)| (map, Arc::new(pixels))).collect(),
|
||||
tracer: output.tracer,
|
||||
sources: self.sources.clone(),
|
||||
painted_stroke: self.painted_stroke,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn run(&self, progress: &Progress) -> Result<BakeOutput> {
|
||||
let mut output = bake_tiles(&self.request(), progress, &self.excluded_tiles, self.tracer.as_deref()).map_err(bake_error)?;
|
||||
let mut output = bake_tiles_in(&self.request(), progress, &self.excluded_tiles, self.region(), self.tracer.as_deref()).map_err(bake_error)?;
|
||||
super::preserve_tiles::restore(&mut output, &self.previous_maps, &self.excluded_tiles, self.tiles)?;
|
||||
super::preserve_tiles::restore_unchecked(&mut output, &self.previous_maps, &self.excluded_tiles, &[])?;
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
/// The texels to sample, with the stored maps to take the rest from; `None` samples every texel
|
||||
fn region(&self) -> Option<RegionBake<'_>> {
|
||||
self.region.map(|texels| RegionBake { texels, previous: &self.previous_maps.maps })
|
||||
}
|
||||
|
||||
fn request(&self) -> BakeRequest<'_> {
|
||||
let high =
|
||||
self.high.as_ref().map(|source| HighPoly { file_ids: &source.file_ids, mesh: &source.mesh, bvh: &source.bvh, base_color: &source.base_color });
|
||||
@@ -111,7 +125,10 @@ impl BakeTask {
|
||||
}
|
||||
|
||||
fn bake_error(error: texturecraft_bake::BakeError) -> EngineError {
|
||||
EngineError::Other(format!("bake failed: {error}"))
|
||||
match error {
|
||||
texturecraft_bake::BakeError::Cancelled => EngineError::BakeCancelled,
|
||||
error => EngineError::Other(format!("bake failed: {error}")),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
//! A canceled bake keeps the maps it finished: the Baking Log ticked them and the 3D view may have shown them
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use texturecraft_compose::BakedMaps;
|
||||
use texturecraft_core::{BakeSource, BakedMap};
|
||||
|
||||
use crate::{Result, Session};
|
||||
|
||||
impl Session {
|
||||
/// Store the maps the canceled bake of `texture_set` `finished` as one undo step and return them; none at a new output size, which would drop the set's other maps
|
||||
pub fn keep_canceled_bake(
|
||||
&mut self,
|
||||
texture_set: usize,
|
||||
finished: BakedMaps,
|
||||
sources: &BTreeMap<BakedMap, BakeSource>,
|
||||
painted_stroke: u64,
|
||||
) -> Result<Vec<BakedMap>> {
|
||||
let Some(height) = finished.maps.keys().next().map(|map| finished.height(*map)) else { return Ok(Vec::new()) };
|
||||
|
||||
let resized = self.doc.baked.get(&texture_set).is_some_and(|stored| {
|
||||
!stored.maps.is_empty() && (stored.resolution != finished.resolution || stored.maps.keys().any(|map| stored.height(*map) != height))
|
||||
});
|
||||
if resized {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
// A map the bake did not finish keeps the record of what its stored pixels were baked from
|
||||
let kept_sources: BTreeMap<BakedMap, BakeSource> =
|
||||
sources.iter().filter(|(map, _)| finished.maps.contains_key(*map)).map(|(map, source)| (*map, *source)).collect();
|
||||
let kept: Vec<BakedMap> = finished.maps.keys().copied().collect();
|
||||
self.edit("Bake mesh maps", |session| {
|
||||
session.store_bake_maps(texture_set, finished.resolution, height, finished.maps, Some((&kept_sources, painted_stroke)))
|
||||
})?;
|
||||
|
||||
// Named like the Texture Set List and the progress footer, which count sets from 1
|
||||
let name = self.doc.project.texture_sets.get(texture_set).map_or_else(|| format!("{}", texture_set + 1), |set| set.name.clone());
|
||||
self.log.info("Baker", format!("Kept {} baked maps of texture set {name} from the canceled bake", kept.len()));
|
||||
Ok(kept)
|
||||
}
|
||||
}
|
||||
@@ -15,8 +15,8 @@ use serde_json::{Value, json};
|
||||
use texturecraft_bake::tracing::Tracer;
|
||||
use texturecraft_bake::{BakeOutput, BakePaintMap, MAX_RAYS, Progress};
|
||||
use texturecraft_core::{
|
||||
BackfaceMode, BakeAntialiasing, BakeResolution, BakeSettings, BakeSyncGroup, BakedMap, CurvatureMethod, PositionMode, RayDistribution, RaySettings,
|
||||
SelfOcclusion,
|
||||
BackfaceMode, BakeAntialiasing, BakeResolution, BakeSettings, BakeSource, BakeSyncGroup, BakedMap, CurvatureMethod, PositionMode, RayDistribution,
|
||||
RaySettings, SelfOcclusion,
|
||||
};
|
||||
use texturecraft_geom::Mesh;
|
||||
|
||||
@@ -121,7 +121,8 @@ pub(super) fn parse_mesh(file_name: &str, bytes: Vec<u8>) -> Result<BakeMesh> {
|
||||
let imported = texturecraft_formats::import_high_poly_bytes(file_name, &bytes).map_err(|e| EngineError::Other(format!("{file_name}: {e}")))?;
|
||||
let base_color = imported.base_color.into_iter().map(|c| c.map(Arc::new)).collect();
|
||||
let folder = std::path::Path::new(file_name).parent().map(|folder| folder.display().to_string()).filter(|folder| !folder.is_empty());
|
||||
Ok(BakeMesh { name: file_name.to_string(), folder, bytes: Arc::new(bytes), mesh: Arc::new(imported.mesh), base_color })
|
||||
let fingerprint = texturecraft_core::fingerprint(&bytes);
|
||||
Ok(BakeMesh { name: file_name.to_string(), folder, bytes: Arc::new(bytes), mesh: Arc::new(imported.mesh), base_color, fingerprint })
|
||||
}
|
||||
|
||||
impl Session {
|
||||
@@ -130,9 +131,14 @@ impl Session {
|
||||
self.bake_task_of(texture_set, None)
|
||||
}
|
||||
|
||||
/// A task that bakes only `maps` of texture set `texture_set`, checked or not; its other baked maps stay as they are
|
||||
pub fn bake_task_for(&self, texture_set: usize, maps: &[BakedMap]) -> Result<BakeTask> {
|
||||
self.bake_task_of(texture_set, Some(maps))
|
||||
}
|
||||
|
||||
/// The bake of texture set `texture_set`'s map `map` alone, checked or not
|
||||
pub fn bake_task_only(&self, texture_set: usize, map: BakedMap) -> Result<BakeTask> {
|
||||
self.bake_task_of(texture_set, Some(map))
|
||||
self.bake_task_of(texture_set, Some(&[map]))
|
||||
}
|
||||
|
||||
/// Prepare a display-only bake, retaining previous pixels only for the displayed map's excluded UV tiles
|
||||
@@ -142,20 +148,19 @@ impl Session {
|
||||
Ok(task)
|
||||
}
|
||||
|
||||
fn bake_task_of(&self, texture_set: usize, only: Option<BakedMap>) -> Result<BakeTask> {
|
||||
fn bake_task_of(&self, texture_set: usize, only: Option<&[BakedMap]>) -> Result<BakeTask> {
|
||||
let set = self.doc.project.texture_set(texture_set)?;
|
||||
if !set.has_enabled_bake_tiles() {
|
||||
return Err(EngineError::Other(format!("texture set {} has no UV tiles selected for baking", set.name)));
|
||||
}
|
||||
|
||||
let mut settings = set.bake.clone();
|
||||
if let Some(map) = only {
|
||||
settings.maps.select([map]);
|
||||
if let Some(maps) = only {
|
||||
settings.maps.select(maps.iter().copied());
|
||||
}
|
||||
|
||||
// Read from the maps that bake, so a map baked alone while unchecked still gets the colours
|
||||
let needs_low_color = settings.maps.opacity.is_enabled
|
||||
|| (settings.maps.id.is_enabled && settings.maps.id.parameters.source == texturecraft_core::IdColorSource::MaterialColor);
|
||||
let needs_low_color = settings.maps.enabled().any(|map| settings.maps.reads_material_colors(map));
|
||||
let low_base_color = if needs_low_color && (settings.high_poly.use_low_as_high || self.doc.bake_meshes.high.is_empty()) {
|
||||
self.doc
|
||||
.bake_meshes
|
||||
@@ -183,6 +188,8 @@ impl Session {
|
||||
let previous_maps = if excluded_tiles.is_empty() { Default::default() } else { self.doc.baked.get(&texture_set).cloned().unwrap_or_default() };
|
||||
|
||||
let tracer = chosen_tracer(GPU_TRACER.get(), GPU_RAYTRACING.load(Ordering::Relaxed));
|
||||
let sources = self.task_bake_sources(set, settings.maps.enabled());
|
||||
|
||||
Ok(BakeTask {
|
||||
low_base_color,
|
||||
ts: texture_set,
|
||||
@@ -198,6 +205,9 @@ impl Session {
|
||||
excluded_tiles,
|
||||
previous_maps,
|
||||
tracer,
|
||||
sources,
|
||||
painted_stroke: self.painted_strokes,
|
||||
region: None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -260,46 +270,60 @@ impl Session {
|
||||
/// Store a finished bake as one undo step
|
||||
pub fn apply_bake(&mut self, texture_set: usize, output: BakeOutput) -> Result<()> {
|
||||
let tracer = output.tracer.clone();
|
||||
self.edit("Bake mesh maps", |session| session.store_bake(texture_set, output))?;
|
||||
self.edit("Bake mesh maps", |session| session.store_bake(texture_set, output, None))?;
|
||||
self.log.info("Baker", format!("Baked texture set {texture_set} ({tracer})"));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Apply a streamed bake like [`Session::apply_bake`], keeping the maps' shared buffers (the
|
||||
/// preview that showed them holds the same ones)
|
||||
/// Apply a streamed bake like [`Session::apply_bake`], keeping the buffers the preview that showed them shares
|
||||
pub fn apply_streamed_bake(&mut self, texture_set: usize, output: StreamedBake) -> Result<()> {
|
||||
let tracer = output.tracer.clone();
|
||||
self.edit("Bake mesh maps", |session| session.store_bake_maps(texture_set, output.resolution, output.height, output.maps))?;
|
||||
self.edit("Bake mesh maps", |session| {
|
||||
session.store_bake_maps(texture_set, output.resolution, output.height, output.maps, Some((&output.sources, output.painted_stroke)))
|
||||
})?;
|
||||
self.log.info("Baker", format!("Baked texture set {texture_set} ({tracer})"));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn store_bake(&mut self, texture_set: usize, output: BakeOutput) -> Result<()> {
|
||||
/// Store `output`, recording what its maps were baked from when known (see [`Session::record_bake_sources`])
|
||||
fn store_bake(&mut self, texture_set: usize, output: BakeOutput, recorded: Option<(&BTreeMap<BakedMap, BakeSource>, u64)>) -> Result<()> {
|
||||
let maps = output.maps.into_iter().map(|(map, pixels)| (map, Arc::new(pixels))).collect();
|
||||
self.store_bake_maps(texture_set, output.resolution, output.height, maps)
|
||||
self.store_bake_maps(texture_set, output.resolution, output.height, maps, recorded)
|
||||
}
|
||||
|
||||
fn store_bake_maps(&mut self, texture_set: usize, resolution: u32, height: u32, maps: std::collections::BTreeMap<BakedMap, Arc<Vec<f32>>>) -> Result<()> {
|
||||
pub(super) fn store_bake_maps(
|
||||
&mut self,
|
||||
texture_set: usize,
|
||||
resolution: u32,
|
||||
height: u32,
|
||||
maps: BTreeMap<BakedMap, Arc<Vec<f32>>>,
|
||||
recorded: Option<(&BTreeMap<BakedMap, BakeSource>, u64)>,
|
||||
) -> Result<()> {
|
||||
let stored: Vec<BakedMap> = maps.keys().copied().collect();
|
||||
let entry = self.doc.baked.entry(texture_set).or_default();
|
||||
if entry.resolution != resolution || entry.maps.keys().any(|map| entry.height(*map) != height) {
|
||||
let size_changed = entry.resolution != resolution || entry.maps.keys().any(|map| entry.height(*map) != height);
|
||||
crate::meshmap_cmds::detach_imported_sources(&mut self.doc.project, texture_set, |map| size_changed || maps.contains_key(&map));
|
||||
if size_changed {
|
||||
entry.maps.clear();
|
||||
}
|
||||
|
||||
entry.resolution = resolution;
|
||||
entry.maps.extend(maps);
|
||||
self.doc.project.texture_set_mut(texture_set)?.baked = entry.maps.keys().copied().collect();
|
||||
Ok(())
|
||||
self.record_bake_sources(texture_set, recorded, &stored)
|
||||
}
|
||||
|
||||
/// Bake texture set `ts` now (blocking), on the CPU when `cpu`; returns where the rays ran.
|
||||
pub fn bake_now(&mut self, ts: usize, cpu: bool) -> Result<String> {
|
||||
let mut task = self.bake_task(ts)?;
|
||||
/// Bake texture set `texture_set` now (blocking), on the CPU when `cpu`; returns where the rays ran
|
||||
pub fn bake_now(&mut self, texture_set: usize, cpu: bool) -> Result<String> {
|
||||
let mut task = self.bake_task(texture_set)?;
|
||||
if cpu {
|
||||
task.tracer = None;
|
||||
}
|
||||
let out = task.run(&Progress::new())?;
|
||||
let tracer = out.tracer.clone();
|
||||
self.apply_bake(ts, out)?;
|
||||
|
||||
let output = task.run(&Progress::new())?;
|
||||
let tracer = output.tracer.clone();
|
||||
self.edit("Bake mesh maps", |session| session.store_bake(texture_set, output, Some((&task.sources, task.painted_stroke))))?;
|
||||
self.log.info("Baker", format!("Baked texture set {texture_set} ({tracer})"));
|
||||
Ok(tracer)
|
||||
}
|
||||
|
||||
@@ -843,16 +867,21 @@ fn bake_run(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
for (index, settings) in next {
|
||||
session.doc.project.texture_set_mut(index)?.bake = settings;
|
||||
}
|
||||
session.begin_bake_log(&sets);
|
||||
|
||||
let mut tracers = Vec::with_capacity(sets.len());
|
||||
for &index in &sets {
|
||||
let mut task = session.bake_task(index)?;
|
||||
if cpu {
|
||||
task.tracer = None;
|
||||
session.bake_log.set_started(index);
|
||||
let baked = bake_one_set(session, index, cpu);
|
||||
match baked {
|
||||
Ok(tracer) => tracers.push(tracer),
|
||||
Err(error) => {
|
||||
session.bake_log.set_failed(index, &error.to_string());
|
||||
// The edit rolls back the sets baked before this one too
|
||||
session.bake_log.discard();
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
let output = task.run(&Progress::new())?;
|
||||
tracers.push(output.tracer.clone());
|
||||
session.store_bake(index, output)?;
|
||||
}
|
||||
Ok(tracers)
|
||||
})?;
|
||||
@@ -863,6 +892,24 @@ fn bake_run(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
Ok(json!({ "baked": sets, "tracer": tracers }))
|
||||
}
|
||||
|
||||
/// Bake every checked map of texture set `index` at once, store them and mark them baked in the Baking Log
|
||||
fn bake_one_set(session: &mut Session, index: usize, cpu: bool) -> Result<String> {
|
||||
let mut task = session.bake_task(index)?;
|
||||
session.bake_log.high_polys_loaded(index);
|
||||
if cpu {
|
||||
task.tracer = None;
|
||||
}
|
||||
|
||||
let maps = task.maps();
|
||||
let output = task.run(&Progress::new())?;
|
||||
let tracer = output.tracer.clone();
|
||||
session.store_bake(index, output, Some((&task.sources, task.painted_stroke)))?;
|
||||
for map in maps {
|
||||
session.bake_log.map_baked(index, map);
|
||||
}
|
||||
Ok(tracer)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod named_tracer;
|
||||
|
||||
|
||||
@@ -1,10 +1,19 @@
|
||||
//! Baking tasks, commands, settings helpers, and the mesh-map baking API
|
||||
|
||||
mod auto_rebake;
|
||||
mod bake_cage_inputs;
|
||||
mod bake_checks;
|
||||
mod bake_high_state;
|
||||
mod bake_log;
|
||||
mod bake_log_high;
|
||||
mod bake_log_map;
|
||||
mod bake_log_matching;
|
||||
mod bake_map_state;
|
||||
mod bake_mesh;
|
||||
mod bake_meshes;
|
||||
mod bake_sources;
|
||||
mod bake_task;
|
||||
mod canceled_bake;
|
||||
mod high_poly_load;
|
||||
mod high_poly_missed;
|
||||
mod layout;
|
||||
@@ -12,6 +21,7 @@ mod merged_high;
|
||||
mod mesh_map_command;
|
||||
mod model_patch;
|
||||
mod paint_command;
|
||||
mod painted_region;
|
||||
mod preserve_tiles;
|
||||
mod streamed_bake;
|
||||
mod streamed_map;
|
||||
@@ -19,6 +29,12 @@ mod sync_command;
|
||||
mod tile_command;
|
||||
|
||||
pub use bake_cage_inputs::BakeCageInputs;
|
||||
pub use bake_high_state::BakeHighState;
|
||||
pub use bake_log::BakeLog;
|
||||
pub use bake_log_high::BakeLogHigh;
|
||||
pub use bake_log_map::BakeLogMap;
|
||||
pub use bake_log_matching::BakeLogMatching;
|
||||
pub use bake_map_state::BakeMapState;
|
||||
pub use bake_mesh::BakeMesh;
|
||||
pub use bake_meshes::BakeMeshes;
|
||||
pub use bake_task::BakeTask;
|
||||
@@ -27,6 +43,7 @@ pub use high_poly_missed::{HIDDEN_HIGH_POLY_VERTEX, high_poly_missed};
|
||||
pub use merged_high::MergedHigh;
|
||||
pub use mesh_map_command::{install_gpu_tracer, meshes_json, set_gpu_raytracing, settings_params};
|
||||
pub use model_patch::settings_patch;
|
||||
pub use painted_region::PaintedRegion;
|
||||
pub use streamed_bake::StreamedBake;
|
||||
pub use streamed_map::StreamedMap;
|
||||
pub use texturecraft_bake::*;
|
||||
@@ -38,6 +55,7 @@ type MaterialColors = std::sync::Arc<Vec<Option<std::sync::Arc<texturecraft_geom
|
||||
pub(crate) fn specs() -> Vec<CommandSpec> {
|
||||
let mut commands = mesh_map_command::specs();
|
||||
commands.extend(paint_command::specs());
|
||||
commands.extend(auto_rebake::specs());
|
||||
commands.extend(tile_command::specs());
|
||||
commands.extend(sync_command::specs());
|
||||
commands
|
||||
|
||||
@@ -3,7 +3,7 @@ use crate::{Result, Session, cmd};
|
||||
use serde_json::Value;
|
||||
use std::sync::Arc;
|
||||
use texturecraft_bake::BakePaintMap;
|
||||
use texturecraft_core::BakePaintTarget;
|
||||
use texturecraft_core::{BakePaintTarget, BakedMap};
|
||||
use texturecraft_geom::glam::Vec2;
|
||||
|
||||
pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
@@ -61,10 +61,13 @@ fn set(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> Re
|
||||
None => BakePaintMap::constant(number(parameters, "value", 1.0, 0.0, 1.0)?),
|
||||
};
|
||||
map.validate().map_err(|error| bad("bake.paint", error.to_string()))?;
|
||||
|
||||
session.edit("Set Bake Paint Map", |session| {
|
||||
session.doc.bake_paint.insert((texture_set, target), Arc::new(map));
|
||||
Ok(())
|
||||
})?;
|
||||
session.note_bake_paint(texture_set, None);
|
||||
|
||||
Ok(super::meshes_json(session))
|
||||
}
|
||||
|
||||
@@ -75,18 +78,31 @@ fn clear(session: &mut Session, parameters: &Value, target: BakePaintTarget) ->
|
||||
session.doc.bake_paint.remove(&(texture_set, target));
|
||||
Ok(())
|
||||
})?;
|
||||
session.note_bake_paint(texture_set, None);
|
||||
}
|
||||
|
||||
Ok(super::meshes_json(session))
|
||||
}
|
||||
|
||||
/// Most UV points one `bake.paint` call takes
|
||||
const MAX_STROKE_POINTS: usize = 100_000;
|
||||
/// Brush radius in UV units: the default, and the smallest that still paints
|
||||
const DEFAULT_RADIUS: f32 = 0.03;
|
||||
const MIN_RADIUS: f32 = 0.00001;
|
||||
/// Brush hardness when a call gives none: halfway between a soft and a hard edge
|
||||
const DEFAULT_HARDNESS: f32 = 0.5;
|
||||
/// Side of a new paint map in texels: the default, and the range a call may ask for
|
||||
const DEFAULT_PAINT_SIZE_TEXELS: u64 = 1024;
|
||||
const PAINT_SIZE_RANGE_TEXELS: std::ops::RangeInclusive<u64> = 16..=4096;
|
||||
|
||||
fn paint(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> Result<Value> {
|
||||
const MAX_POINTS: usize = 100_000;
|
||||
let texture_set = texture_set(session, parameters)?;
|
||||
let points = parameters
|
||||
.get("points")
|
||||
.and_then(Value::as_array)
|
||||
.filter(|points| !points.is_empty() && points.len() <= MAX_POINTS)
|
||||
.ok_or_else(|| bad("bake.paint", "points must contain 1 to 100000 UV coordinates"))?;
|
||||
.filter(|points| !points.is_empty() && points.len() <= MAX_STROKE_POINTS)
|
||||
.ok_or_else(|| bad("bake.paint", format!("points must contain 1 to {MAX_STROKE_POINTS} UV coordinates")))?;
|
||||
|
||||
let points = points
|
||||
.iter()
|
||||
.map(|point| {
|
||||
@@ -97,17 +113,19 @@ fn paint(session: &mut Session, parameters: &Value, target: BakePaintTarget) ->
|
||||
}
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
|
||||
let value = number(parameters, "value", 1.0, 0.0, 1.0)?;
|
||||
let radius = number(parameters, "radius", 0.03, 0.00001, 1.0)?;
|
||||
let hardness = number(parameters, "hardness", 0.5, 0.0, 1.0)?;
|
||||
let radius = number(parameters, "radius", DEFAULT_RADIUS, MIN_RADIUS, 1.0)?;
|
||||
let hardness = number(parameters, "hardness", DEFAULT_HARDNESS, 0.0, 1.0)?;
|
||||
let strength = number(parameters, "strength", 1.0, 0.0, 1.0)?;
|
||||
let size = match parameters.get("size") {
|
||||
None => 1024,
|
||||
None => DEFAULT_PAINT_SIZE_TEXELS,
|
||||
Some(_) => u64p(parameters, "size").ok_or_else(|| bad("bake.paint", "size must be an integer"))?,
|
||||
};
|
||||
if !(16..=4096).contains(&size) {
|
||||
return Err(bad("bake.paint", "size must be between 16 and 4096"));
|
||||
if !PAINT_SIZE_RANGE_TEXELS.contains(&size) {
|
||||
return Err(bad("bake.paint", format!("size must be between {} and {}", PAINT_SIZE_RANGE_TEXELS.start(), PAINT_SIZE_RANGE_TEXELS.end())));
|
||||
}
|
||||
|
||||
let default = match target {
|
||||
BakePaintTarget::Cage => 1.0,
|
||||
BakePaintTarget::Skew => 0.0,
|
||||
@@ -116,13 +134,30 @@ fn paint(session: &mut Session, parameters: &Value, target: BakePaintTarget) ->
|
||||
BakePaintTarget::Cage => "Paint Cage",
|
||||
BakePaintTarget::Skew => "Paint Skew Correction",
|
||||
};
|
||||
|
||||
session.edit_merging(label, boolp(parameters, "continue") == Some(true), |session| {
|
||||
// Skew painting starts with Auto-rebake on for the Normal map, which shows the skew best, unless the set picked one
|
||||
let first_skew = target == BakePaintTarget::Skew && !session.doc.bake_paint.contains_key(&(texture_set, target));
|
||||
let set = session.doc.project.texture_set_mut(texture_set)?;
|
||||
if first_skew && set.auto_rebake.is_none() {
|
||||
set.auto_rebake = Some(BakedMap::Normal);
|
||||
}
|
||||
|
||||
let map = session.doc.bake_paint.entry((texture_set, target)).or_insert_with(|| Arc::new(BakePaintMap::constant(default)));
|
||||
if map.values.len() == 1 {
|
||||
*map = Arc::new(map.resized(size as u32, size as u32).map_err(|error| bad("bake.paint", error.to_string()))?);
|
||||
}
|
||||
Arc::make_mut(map).paint(&points, radius, value, hardness, strength).map_err(|error| bad("bake.paint", error.to_string()))
|
||||
})?;
|
||||
|
||||
// Bilinear sampling extends each dab's reach by one paint texel
|
||||
let paint_texel = session.doc.bake_paint.get(&(texture_set, target)).map_or(0.0, |map| 1.0 / map.width.min(map.height).max(1) as f32);
|
||||
let reach = Vec2::splat(radius + paint_texel);
|
||||
let uv_min = points.iter().fold(Vec2::INFINITY, |min, point| min.min(*point)) - reach;
|
||||
let uv_max = points.iter().fold(Vec2::NEG_INFINITY, |max, point| max.max(*point)) + reach;
|
||||
|
||||
session.note_bake_paint(texture_set, Some((uv_min, uv_max)));
|
||||
|
||||
Ok(super::meshes_json(session))
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
//! Where skew or cage painting changed what a texture set's transfer rays read since its maps were baked
|
||||
|
||||
use texturecraft_bake::{TexelBox, region_keeps_pixels};
|
||||
use texturecraft_core::{BakeSource, BakedMap};
|
||||
use texturecraft_geom::glam::Vec2;
|
||||
|
||||
use crate::{Result, Session};
|
||||
|
||||
/// The UV box painted since the last bake of a texture set's auto-rebake map
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct PaintedRegion {
|
||||
pub uv_min: Vec2,
|
||||
pub uv_max: Vec2,
|
||||
/// Counts up with every stroke, so a rebake can tell a newer stroke from the one it bakes
|
||||
pub stroke: u64,
|
||||
}
|
||||
|
||||
/// Texels added around a painted box: bilinear sampling of the paint map and antialiasing samples reach one texel past it
|
||||
const MARGIN_TEXELS: u32 = 1;
|
||||
|
||||
impl Session {
|
||||
/// Note that the bake paint of `texture_set` changed inside `uv_min`..`uv_max` (the whole map when `None`)
|
||||
pub(super) fn note_bake_paint(&mut self, texture_set: usize, uv_box: Option<(Vec2, Vec2)>) {
|
||||
let (uv_min, uv_max) = uv_box.unwrap_or((Vec2::ZERO, Vec2::ONE));
|
||||
let (uv_min, uv_max) = match self.doc.painted_regions.get(&texture_set) {
|
||||
Some(region) => (region.uv_min.min(uv_min), region.uv_max.max(uv_max)),
|
||||
None => (uv_min, uv_max),
|
||||
};
|
||||
self.painted_strokes += 1;
|
||||
self.doc.painted_regions.insert(texture_set, PaintedRegion { uv_min, uv_max, stroke: self.painted_strokes });
|
||||
}
|
||||
|
||||
/// Forget the painted box of `texture_set` once its auto-rebake map is baked again, unless a stroke came after `painted_stroke`
|
||||
pub(super) fn forget_painted_region(&mut self, texture_set: usize, stored: &[BakedMap], painted_stroke: u64) {
|
||||
let auto = self.doc.project.texture_sets.get(texture_set).and_then(|set| set.auto_rebake);
|
||||
let painted_since = self.doc.painted_regions.get(&texture_set).is_some_and(|region| region.stroke > painted_stroke);
|
||||
if !painted_since && auto.is_none_or(|map| stored.contains(&map)) {
|
||||
self.doc.painted_regions.remove(&texture_set);
|
||||
}
|
||||
}
|
||||
|
||||
/// Baked auto-rebake maps changed only by painting since, as (set, map, what a bake reads now, newest stroke)
|
||||
pub fn auto_rebake_painted(&self) -> Vec<(usize, BakedMap, BakeSource, u64)> {
|
||||
let regions = self.doc.painted_regions.iter();
|
||||
regions
|
||||
.filter_map(|(index, region)| {
|
||||
let set = self.doc.project.texture_sets.get(*index)?;
|
||||
let map = set.auto_rebake.filter(|map| set.baked.contains(map))?;
|
||||
let from_high = !set.bake.high_poly.use_low_as_high && !self.doc.bake_meshes.high.is_empty();
|
||||
from_high.then_some(())?;
|
||||
let current = self.bake_source(*index, map).ok()?;
|
||||
|
||||
// Only painting changed it: a map without a record is never out of date
|
||||
let up_to_date = set.bake_sources.get(&map).is_none_or(|record| *record == current);
|
||||
up_to_date.then_some((*index, map, current, region.stroke))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A task that bakes `map` again only where painting changed it, keeping the rest; else the whole map
|
||||
pub fn bake_painted_task(&self, texture_set: usize, map: BakedMap) -> Result<crate::BakeTask> {
|
||||
let mut task = self.bake_task_for(texture_set, &self.auto_rebake_maps(texture_set, map))?;
|
||||
let Some(region) = self.doc.painted_regions.get(&texture_set) else { return Ok(task) };
|
||||
|
||||
let (width, height) = task.settings.common.output_size();
|
||||
let stored =
|
||||
self.doc.baked.get(&texture_set).filter(|stored| stored.resolution == width && stored.height(map) == height && stored.maps.contains_key(&map));
|
||||
let Some(stored) = stored.filter(|_| task.tiles == (1, 1) && region_keeps_pixels(map)) else { return Ok(task) };
|
||||
|
||||
let texel = |uv: f32, size: u32, round: fn(f32) -> f32| (round(uv.clamp(0.0, 1.0) * size as f32) as u32).min(size);
|
||||
let painted = TexelBox {
|
||||
min: (texel(region.uv_min.x, width, f32::floor), texel(region.uv_min.y, height, f32::floor)),
|
||||
max: (texel(region.uv_max.x, width, f32::ceil), texel(region.uv_max.y, height, f32::ceil)),
|
||||
};
|
||||
task.previous_maps = stored.clone();
|
||||
task.region = Some(painted.grown(MARGIN_TEXELS, width, height));
|
||||
Ok(task)
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use texturecraft_core::BakedMap;
|
||||
use texturecraft_core::{BakeSource, BakedMap};
|
||||
|
||||
/// The result of a streamed bake: the finished maps stay shared (`Arc`) with whoever was shown them,
|
||||
/// so the preview and the document hold one buffer per map, never two
|
||||
@@ -11,4 +11,8 @@ pub struct StreamedBake {
|
||||
pub height: u32,
|
||||
pub maps: BTreeMap<BakedMap, Arc<Vec<f32>>>,
|
||||
pub tracer: String,
|
||||
/// What the baked maps were baked from (the task's [`crate::BakeTask::sources`])
|
||||
pub sources: BTreeMap<BakedMap, BakeSource>,
|
||||
/// The task's [`crate::BakeTask::painted_stroke`]
|
||||
pub painted_stroke: u64,
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
//! The `bake.log` query: the Baking Log's rows for automation
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad};
|
||||
use crate::{Result, Session, cmd};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"bake.log",
|
||||
"Baking log",
|
||||
[],
|
||||
None,
|
||||
"{} → {running, maps: [{textureSet, setName, map, state: \"waiting\" | \"baking\" | \"baked\" | \"failed\" | \"canceled\", reason?}], highPolys: [{textureSet, setName, file, state: \"waiting\" | \"loading\" | \"loaded\" | \"failed\" | \"canceled\", reason?}], matching: null | {lowSuffix, highSuffix, pairs: [{low: name | null, high: name | null}]}}. The latest bake map by map in bake order, the high poly files each set bakes from, and how parts paired by name, as the Baking Log shows them; `reason` says why a map or file failed; a `null` side of a pair is a part with no partner; `matching` is null when no set matched by mesh name. Empty before the first bake",
|
||||
always,
|
||||
log
|
||||
)]
|
||||
}
|
||||
|
||||
fn log(session: &mut Session, _: &Value) -> Result<Value> {
|
||||
let log = &session.bake_log;
|
||||
let maps = log.maps.iter().map(|row| entry(&row.state, row.texture_set, &row.set_name, "map", json!(row.map.id()))).collect::<Result<Vec<Value>>>()?;
|
||||
let high_polys = log.highs.iter().map(|row| entry(&row.state, row.texture_set, &row.set_name, "file", json!(row.file))).collect::<Result<Vec<Value>>>()?;
|
||||
let matching = log.matching.as_ref().map(|matching| {
|
||||
let pairs: Vec<Value> = matching.pairs.iter().map(|pair| json!({ "low": pair.low, "high": pair.high })).collect();
|
||||
json!({ "lowSuffix": matching.low_suffix, "highSuffix": matching.high_suffix, "pairs": pairs })
|
||||
});
|
||||
|
||||
Ok(json!({ "running": log.is_running() || log.is_loading_high_polys(), "maps": maps, "highPolys": high_polys, "matching": matching }))
|
||||
}
|
||||
|
||||
/// One row: its `state` (and `reason`), its texture set, and an item identified by `key`
|
||||
fn entry(state: &impl serde::Serialize, texture_set: usize, set_name: &str, key: &str, value: Value) -> Result<Value> {
|
||||
let mut entry = serde_json::to_value(state).map_err(|error| bad("bake.log", error.to_string()))?;
|
||||
|
||||
if let Some(fields) = entry.as_object_mut() {
|
||||
fields.insert("textureSet".into(), json!(texture_set));
|
||||
fields.insert("setName".into(), json!(set_name));
|
||||
fields.insert(key.into(), value);
|
||||
}
|
||||
|
||||
Ok(entry)
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
//! Live bake preview: while the app bakes, the 3D view shows each mesh map on the model as soon
|
||||
//! as it is finished ([`crate::BakeTask::run_streaming`]). The streamed maps live here, not in
|
||||
//! the document: nothing enters the undo history until a texture set's bake is applied
|
||||
//! ([`Session::apply_streamed_bake`]). Cancellation leaves the current set unchanged; sets already
|
||||
//! applied keep their results and undo steps. The preview shows one map at a time, raw on the
|
||||
//! model; maps and texture sets not baked yet show their neutral value.
|
||||
//! ([`Session::apply_streamed_bake`]). The UI can apply eligible finished maps on cancellation.
|
||||
//! Already applied sets keep their results and undo steps. The preview shows one raw map at a time.
|
||||
//! Maps and texture sets that are still pending show their neutral value.
|
||||
|
||||
mod preview_set;
|
||||
mod preview_show;
|
||||
|
||||
@@ -146,6 +146,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
cmd!("brush.preset.delete", "Delete a brush preset", [], None, "{name} — one of the user's presets (built-ins are read-only)", always, delete),
|
||||
cmd!("brush.preset.save", "Save brush preset", [], None, "{path} — the current brush as a .tcbrush file", always, save),
|
||||
cmd!("brush.preset.load", "Load brush preset", [], None, "{path} — a .tcbrush file's stroke on the brush, keeping the size", always, load),
|
||||
cmd!(
|
||||
"brush.preset.export",
|
||||
"Export brush preset",
|
||||
[],
|
||||
None,
|
||||
"{name, path} — one of the user's presets as a .tcbrush file, as its library folder holds it",
|
||||
always,
|
||||
export
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -325,6 +334,26 @@ fn load(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
Err(bad("brush.preset.load", "file paths are not available in the browser"))
|
||||
}
|
||||
|
||||
/// Writes user preset `name` to `path` as the library folder holds it
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn export(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
const CMD: &str = "brush.preset.export";
|
||||
let name = name_param(params, "name", CMD)?;
|
||||
let path = strp(params, "path").ok_or_else(|| bad(CMD, "`path` is required"))?;
|
||||
let preset = session.brush_presets.find(&name).and_then(|index| session.brush_presets.list.get(index));
|
||||
let preset = preset.ok_or_else(|| bad(CMD, format!("no user brush preset `{name}`")))?;
|
||||
let bytes = serde_json::to_vec_pretty(preset).map_err(|error| bad(CMD, error.to_string()))?;
|
||||
|
||||
std::fs::write(path, bytes).map_err(|error| bad(CMD, format!("cannot write {path}: {error}")))?;
|
||||
|
||||
Ok(json!({ "path": path }))
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn export(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
Err(bad("brush.preset.export", "file paths are not available in the browser"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -406,6 +435,31 @@ mod tests {
|
||||
assert_eq!(names(&test_session), ["a/b"]);
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn an_exported_preset_loads_as_the_same_brush() {
|
||||
let dir = std::env::temp_dir().join(format!("tc-brush-export-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let mut test_session = session();
|
||||
run(&mut test_session, "tool.brush", json!({"size": 41, "hardness": 70})).unwrap();
|
||||
run(&mut test_session, "brush.preset.store", json!({"name": "Ink pen"})).unwrap();
|
||||
run(&mut test_session, "tool.brush", json!({"size": 5})).unwrap();
|
||||
|
||||
let path = dir.join("shared.tcbrush");
|
||||
run(&mut test_session, "brush.preset.export", json!({"name": "ink pen", "path": path.to_str().unwrap()})).unwrap();
|
||||
|
||||
let mut fresh = session();
|
||||
assert!(fresh.load_brush_presets(dir.clone()).is_empty());
|
||||
assert_eq!(names(&fresh), ["Ink pen"], "the file carries the preset's name");
|
||||
assert_eq!(fresh.brush_presets.list[0].brush, test_session.brush_presets.list[0].brush, "the stored brush, not the current one");
|
||||
assert!(
|
||||
run(&mut test_session, "brush.preset.export", json!({"name": "Airbrush", "path": path.to_str().unwrap()})).is_err(),
|
||||
"built-ins are not exported"
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn presets_persist_in_the_folder() {
|
||||
|
||||
@@ -45,6 +45,12 @@ impl UserBrushes {
|
||||
self.dir.as_ref().map(|directory| directory.join(format!("{}.{BRUSH_EXT}", sanitize_file_stem(name.trim()))))
|
||||
}
|
||||
|
||||
/// The file user preset `name` is mirrored to (None: no such preset, or the presets live in memory only)
|
||||
pub fn file_for(&self, name: &str) -> Option<std::path::PathBuf> {
|
||||
let preset = self.list.get(self.find(name)?)?;
|
||||
preset.file.clone().or_else(|| self.file_of(&preset.name))
|
||||
}
|
||||
|
||||
/// The file a preset named `name` that was never written would have.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(super) fn file_of(&self, name: &str) -> Option<std::path::PathBuf> {
|
||||
|
||||
@@ -31,7 +31,7 @@ impl CommandSpec {
|
||||
/// that only return data or do nothing without parameters, and the ones that replace the
|
||||
/// open project (the menu asks to save first).
|
||||
pub fn bindable(&self) -> bool {
|
||||
const NOT_FROM_A_KEY: [&str; 13] = [
|
||||
const NOT_FROM_A_KEY: &[&str] = &[
|
||||
"project.inspect",
|
||||
"project.templates",
|
||||
"project.new",
|
||||
@@ -43,8 +43,10 @@ impl CommandSpec {
|
||||
"textureSet.parts",
|
||||
"bake.settings",
|
||||
"bake.preview",
|
||||
"bake.log",
|
||||
"camera.set",
|
||||
"textureSet.settings",
|
||||
"resource.status",
|
||||
];
|
||||
const NOTHING_WITHOUT_PARAMS: [&str; 4] = ["layer.blend", "tool.stencil", "tool.fillSelection", "tool.path"];
|
||||
!(self.id.ends_with(".list") || NOT_FROM_A_KEY.contains(&self.id) || NOTHING_WITHOUT_PARAMS.contains(&self.id)) && params_all_optional(self.params)
|
||||
@@ -139,11 +141,13 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(crate::project_cmds::specs());
|
||||
v.extend(crate::bake::specs());
|
||||
v.extend(crate::bake_preview::specs());
|
||||
v.extend(crate::bake_log_cmds::specs());
|
||||
v.extend(crate::materialx_cmds::specs());
|
||||
v.extend(crate::pbr_cmds::specs());
|
||||
v.extend(crate::file_cmds::specs());
|
||||
v.extend(crate::preset_cmds::specs());
|
||||
v.extend(crate::resource_cmds::specs());
|
||||
v.extend(crate::resource_update_cmds::specs());
|
||||
v.extend(crate::material_lib::specs());
|
||||
v.extend(crate::link_cmds::specs());
|
||||
v.extend(crate::smart_masks::specs());
|
||||
@@ -371,7 +375,18 @@ mod tests {
|
||||
] {
|
||||
assert!(!bindable(id), "{id} needs a parameter");
|
||||
}
|
||||
for id in ["layer.move", "layer.list", "project.inspect", "edit.history", "export.presets", "tool.state", "project.new", "camera.set", "layer.blend"] {
|
||||
for id in [
|
||||
"layer.move",
|
||||
"layer.list",
|
||||
"project.inspect",
|
||||
"edit.history",
|
||||
"export.presets",
|
||||
"tool.state",
|
||||
"project.new",
|
||||
"camera.set",
|
||||
"layer.blend",
|
||||
"bake.log",
|
||||
] {
|
||||
assert!(!bindable(id), "{id} is a query or has several forms");
|
||||
}
|
||||
}
|
||||
|
||||
+236
-60
@@ -13,14 +13,17 @@ use texturecraft_core::{NormalFormat, PROJECT_EXT};
|
||||
use texturecraft_core::{Project, TextureSet};
|
||||
use texturecraft_formats::PlannedFile;
|
||||
use texturecraft_formats::mesh_import::{MeshUvSource, import_mesh_geometry};
|
||||
use texturecraft_formats::{ExportInput, ExportOptions, ExportedFile, FileFormat, MapOverride, Padding, ProjectFile};
|
||||
use texturecraft_formats::{ExportInput, ExportOptions, ExportedFile, FileFormat, MapOverride, MapPreview, Padding, ProjectFile};
|
||||
use texturecraft_geom::glam::Vec2;
|
||||
use texturecraft_geom::{Mesh, primitives};
|
||||
use texturecraft_geom::{Mesh, UvGBuffer, primitives};
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad, normal_format_param, strp, u64p};
|
||||
use crate::session::{Document, Session};
|
||||
use crate::{EngineError, Result, cmd};
|
||||
|
||||
/// export.preview's picture width when the params name none
|
||||
const DEFAULT_PREVIEW_SIDE_PIXELS: u32 = 128;
|
||||
|
||||
type BakePaintMaps = BTreeMap<(usize, texturecraft_core::BakePaintTarget), Arc<texturecraft_bake::BakePaintMap>>;
|
||||
|
||||
fn prepare_archive<Bytes>(archive: &mut ProjectFile<Bytes, Bytes>, uv_source: Option<&Mesh>, bake_paint: &BakePaintMaps) {
|
||||
@@ -82,7 +85,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export textures",
|
||||
["File"],
|
||||
None,
|
||||
"{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|[indexes]|\"all\", format?: bmp|jpeg|jng|pgm|png|targa|tiff|hdr|exr|webp|psd (or the extension), bitDepth?: 8|16|32 (32 is float for tiff, hdr and exr; 16 is half float for exr), dithering?: bool (8-bit files), padding?: none|dilation|dilationDefault|diffusion|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, maps?: [{map: index into the preset's maps, enabled?: bool (false leaves the map out), format?, bitDepth?, dithering?}] (per map file type and bit depth), colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1; a chosen space is also recorded in the colour maps: an ICC profile in PNG, JPEG, TIFF and WebP, the chromaticities in EXR; TGA, BMP, HDR, JNG, PGM and PSD exports warn about missing metadata), reservedNames?: [file names or UDIM patterns] (from earlier commands of the same export, compared ignoring case), materialX?: bool (also write an OpenPBR .mtlx per texture set, reusing compatible OpenPBR maps and writing dedicated textures for the remaining inputs), usdAsset?: true|[export params, one object per texture set (not empty)] (also write <mesh>.usd, a binary USD file, next to the textures: the whole mesh, a UsdPreviewSurface material per texture set whose inputs read the files the export wrote with its output template (base color, roughness, metallic, normal, emissive, opacity, clear coat; packed maps read their own channels); a texture set outside the export has none; true takes this command's ts, options and reservedNames, a list gives each texture set's own `ts`, options and `reservedNames`, a file the texture export skipped is not read, the export window sends it with the last command; a failure is a warning)} → {files, warnings, materialUdimPatterns?}",
|
||||
"{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|[indexes]|\"all\", format?: bmp|jpeg|jng|pgm|png|targa|tiff|hdr|exr|webp|psd (or the extension; the maps written as psd are the layers of one <mesh>_<texture set>.psd per texture set and UV tile, which the USD asset and MaterialX don't read), bitDepth?: 8|16|32 (32 is float for tiff, hdr and exr; 16 is half float for exr), dithering?: bool (8-bit files), padding?: none|dilation|dilationDefault|diffusion|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, maps?: [{map: index into the preset's maps, enabled?: bool (false leaves the map out), format?, bitDepth?, dithering?, size?: px (wins over `size`)}] (per map file type, bit depth and size), colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1; a chosen space is also recorded in the colour maps: an ICC profile in PNG, JPEG, TIFF and WebP, the chromaticities in EXR; TGA, BMP, HDR, JNG, PGM and PSD exports warn about missing metadata), reservedNames?: [file names or UDIM patterns] (from earlier commands of the same export, compared ignoring case), materialX?: bool (also write an OpenPBR .mtlx per texture set, reusing compatible OpenPBR maps and writing dedicated textures for the remaining inputs), usdAsset?: true|[export params, one object per texture set (not empty)] (also write <mesh>.usd, a binary USD file, next to the textures: the whole mesh, a UsdPreviewSurface material per texture set whose inputs read the files the export wrote with its output template (base color, roughness, metallic, normal, emissive, opacity, clear coat; packed maps read their own channels); a texture set outside the export has none; true takes this command's ts, options and reservedNames, a list gives each texture set's own `ts`, options and `reservedNames`, a file the texture export skipped is not read, the export window sends it with the last command; a failure is a warning), shaderParameters?: true|[texture set indexes] (also write <project>_shaders.json: the shader's model and settings and the texture sets using it; true lists this command's ts, the export window sends every set of the export with the last command; a failure is a warning)} → {files, warnings, materialUdimPatterns?}",
|
||||
always,
|
||||
export_textures
|
||||
),
|
||||
@@ -100,10 +103,19 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"List export outputs",
|
||||
[],
|
||||
None,
|
||||
"{preset?: name or preset object, ts?, format?, bitDepth?, dithering?, size?, colorSpace?, maps?} → [{ts, map, file, format, bitDepth, dithering, size, sourceSize, warnings}] (keeps the first file per case-insensitive name and warns about later duplicates)",
|
||||
"{preset?: name or preset object, ts?, format?, bitDepth?, dithering?, size?, colorSpace?, maps?} → [{ts, map, file, tile: UV tile number or null, udimPattern: file pattern with <UDIM> or null, format, bitDepth, dithering, size (width), height, sourceSize, sourceHeight, warnings, layers: [{map, name}] (a PSD's maps, top first)}] (keeps the first file per case-insensitive name, warns about later duplicates, and rejects file and folder conflicts)",
|
||||
always,
|
||||
plan
|
||||
),
|
||||
cmd!(
|
||||
"export.preview",
|
||||
"Preview an output map",
|
||||
[],
|
||||
None,
|
||||
"{map: index into the preset's maps, side?: px (default 128, at most 512), plus the params of export.plan (the first texture set `ts` names)} → {width, height, channels: [\"R\", ...], pixels: [8-bit values as an sRGB file stores them, channels interleaved, row by row]}, or null when the texture set writes no file for the map",
|
||||
always,
|
||||
preview
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -157,16 +169,18 @@ impl Session {
|
||||
|
||||
/// [`Session::mesh_obj_with_mtl`], optionally replacing normals on the exported copy only.
|
||||
pub fn mesh_obj_with_mtl_and_normals(&mut self, stem: &str, recompute_normals: bool) -> Result<(Vec<u8>, texturecraft_formats::NamedFiles)> {
|
||||
// shortcut: UV-tiled sets get no maps (the OBJ keeps the mesh's UDIM UVs and an MTL map is
|
||||
// one image); their tiles export through Export textures with `$udim` names.
|
||||
// OBJ keeps UDIM UVs, while each MTL map can hold only one image
|
||||
// Export tiled textures separately with `$udim` names
|
||||
let mut mesh = self.source_mesh();
|
||||
if recompute_normals {
|
||||
mesh.compute_smooth_normals();
|
||||
}
|
||||
// A mesh without materials has one implicit material (and texture set).
|
||||
|
||||
// A mesh without materials has one implicit material and texture set
|
||||
if mesh.materials.is_empty() {
|
||||
mesh.materials.push("default".into());
|
||||
}
|
||||
|
||||
let files = self.material_files(texturecraft_formats::usd_export_options(), false, mesh.materials.len())?;
|
||||
texturecraft_formats::obj_with_mtl(&mesh, &self.doc.project.name, stem, &files).map_err(fe)
|
||||
}
|
||||
@@ -182,10 +196,11 @@ impl Session {
|
||||
pub fn mesh_glb_bytes_with_normals(&mut self, recompute_normals: bool) -> Result<Vec<u8>> {
|
||||
let files = self.material_files(texturecraft_formats::glb_export_options(), true, self.mesh.materials.len())?;
|
||||
let textures: Vec<_> = files.into_iter().map(texturecraft_formats::GlbTextures::from_files).collect();
|
||||
let mut mesh = self.mesh.as_ref().clone();
|
||||
let mut mesh = Cow::Borrowed(self.mesh.as_ref());
|
||||
if recompute_normals {
|
||||
mesh.compute_smooth_normals();
|
||||
mesh.to_mut().compute_smooth_normals();
|
||||
}
|
||||
|
||||
texturecraft_formats::glb_bytes(&mesh, &self.doc.project.name, &textures).map_err(fe)
|
||||
}
|
||||
|
||||
@@ -198,10 +213,11 @@ impl Session {
|
||||
/// [`Session::mesh_usd`], optionally replacing normals on the exported copy only.
|
||||
pub fn mesh_usd_with_normals(&mut self, format: texturecraft_formats::UsdFormat, recompute_normals: bool) -> Result<texturecraft_formats::UsdExport> {
|
||||
let files = self.material_files(texturecraft_formats::usd_export_options(), true, self.mesh.materials.len())?;
|
||||
let mut mesh = self.mesh.as_ref().clone();
|
||||
let mut mesh = Cow::Borrowed(self.mesh.as_ref());
|
||||
if recompute_normals {
|
||||
mesh.compute_smooth_normals();
|
||||
mesh.to_mut().compute_smooth_normals();
|
||||
}
|
||||
|
||||
texturecraft_formats::usd_bytes(&mesh, &self.doc.project.name, &files, format).map_err(fe)
|
||||
}
|
||||
|
||||
@@ -289,6 +305,7 @@ impl Session {
|
||||
pixels: project_file.pixels,
|
||||
baked: project_file.baked,
|
||||
resources,
|
||||
painted_regions: Default::default(),
|
||||
},
|
||||
mesh,
|
||||
project_file.mesh,
|
||||
@@ -346,51 +363,128 @@ impl Session {
|
||||
}
|
||||
|
||||
/// Render every export file for texture sets `sets` (in memory; works on the web). A file
|
||||
/// named like one an earlier set exports is left out, with a warning (see
|
||||
/// [`texturecraft_formats::skip_repeated_names`]).
|
||||
/// named like one an earlier set exports is left out, with a warning.
|
||||
pub fn export_files(&mut self, sets: &[usize], opts: &ExportOptions) -> Result<Vec<ExportedFile>> {
|
||||
let mut files = self.render_export_files(sets, opts, |_, plans| plans)?;
|
||||
texturecraft_formats::skip_repeated_names(&mut files);
|
||||
Ok(files)
|
||||
self.export_file_jobs(sets.iter().map(|&set| (set, opts)))
|
||||
}
|
||||
|
||||
/// Render one in-memory batch, using each set's own export settings when supplied.
|
||||
pub fn export_file_jobs<'a>(&mut self, jobs: impl IntoIterator<Item = (usize, &'a ExportOptions)>) -> Result<Vec<ExportedFile>> {
|
||||
self.render_export_jobs(jobs, |_, plans| plans)
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn render_export_files(
|
||||
&mut self,
|
||||
sets: &[usize],
|
||||
options: &ExportOptions,
|
||||
select: impl FnMut(usize, Vec<PlannedFile>) -> Vec<PlannedFile>,
|
||||
) -> Result<Vec<ExportedFile>> {
|
||||
self.render_export_jobs(sets.iter().map(|&set| (set, options)), select)
|
||||
}
|
||||
|
||||
fn render_export_jobs<'a>(
|
||||
&mut self,
|
||||
jobs: impl IntoIterator<Item = (usize, &'a ExportOptions)>,
|
||||
mut select: impl FnMut(usize, Vec<PlannedFile>) -> Vec<PlannedFile>,
|
||||
) -> Result<Vec<ExportedFile>> {
|
||||
let project = &self.doc.project;
|
||||
let mesh_name = stem_of(project.mesh.trim_start_matches("builtin:"));
|
||||
let mut pending = Vec::new();
|
||||
for (set_index, options) in jobs {
|
||||
let plans = texturecraft_formats::list_outputs(project, set_index, &mesh_name, options).map_err(fe)?;
|
||||
let plans = select(set_index, plans);
|
||||
if !plans.is_empty() {
|
||||
pending.push((set_index, options, plans));
|
||||
}
|
||||
}
|
||||
|
||||
// Keep each winning plan with the options of the job that produced it
|
||||
let plans = pending.iter_mut().enumerate().flat_map(|(job, (_, _, plans))| plans.drain(..).map(move |plan| (job, plan)));
|
||||
let plans = texturecraft_formats::export::keep_first_planned_names(plans);
|
||||
if pending.len() > 1 {
|
||||
texturecraft_formats::export::validate_export_paths(plans.iter().map(|(_, plan)| plan.name.as_str())).map_err(fe)?;
|
||||
}
|
||||
|
||||
for (job, plan) in plans {
|
||||
pending[job].2.push(plan);
|
||||
}
|
||||
pending.retain(|(_, _, plans)| !plans.is_empty());
|
||||
|
||||
let mut psd_bytes = 0;
|
||||
for (set_index, options, plans) in &pending {
|
||||
let set = project.texture_set(*set_index).map_err(|error| EngineError::Other(error.to_string()))?;
|
||||
texturecraft_formats::export::check_psd_batch(set, options, plans, &mut psd_bytes).map_err(fe)?;
|
||||
}
|
||||
|
||||
if self.solo.is_none() {
|
||||
self.update();
|
||||
}
|
||||
|
||||
let mesh_name = stem_of(self.doc.project.mesh.trim_start_matches("builtin:"));
|
||||
let mut out = Vec::new();
|
||||
let empty = Default::default();
|
||||
for &set_index in sets {
|
||||
let cache = self.caches.get(set_index).ok_or_else(|| EngineError::Other(format!("no texture set {set_index}")))?;
|
||||
let plans = texturecraft_formats::list_outputs(&self.doc.project, set_index, &mesh_name, options).map_err(fe)?;
|
||||
let plans = select(set_index, plans);
|
||||
if plans.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let composite =
|
||||
self.document_composite(set_index, &cache.covered_tiles).ok_or_else(|| EngineError::Other(format!("no texture set {set_index}")))?;
|
||||
let coverage = cache.gbuf.coverage_mask();
|
||||
let input = ExportInput {
|
||||
project: &self.doc.project,
|
||||
ts: set_index,
|
||||
composite: &composite,
|
||||
baked: self.doc.baked.get(&set_index).unwrap_or(&empty),
|
||||
coverage: &coverage,
|
||||
mesh_name: &mesh_name,
|
||||
};
|
||||
out.extend(texturecraft_formats::export::render_planned_maps(&input, options, plans).map_err(fe)?);
|
||||
for (set_index, options, plans) in pending {
|
||||
let files = self.with_export_input(
|
||||
set_index,
|
||||
&mesh_name,
|
||||
options.padding != Padding::None,
|
||||
|grid| Cow::Owned(grid.coverage_mask()),
|
||||
|input| texturecraft_formats::export::render_planned_maps(input, options, plans).map_err(fe),
|
||||
)?;
|
||||
out.extend(files);
|
||||
}
|
||||
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Run `with` on texture set `set_index`'s export input: its document composite, coverage and baked maps
|
||||
fn with_export_input<T, Coverage: Clone>(
|
||||
&self,
|
||||
set_index: usize,
|
||||
mesh_name: &str,
|
||||
needs_padding: bool,
|
||||
coverage: impl FnOnce(&UvGBuffer) -> Cow<'_, [Coverage]>,
|
||||
with: impl FnOnce(&ExportInput<Coverage>) -> Result<T>,
|
||||
) -> Result<T> {
|
||||
let missing = || EngineError::Other(format!("no texture set {set_index}"));
|
||||
let cache = self.caches.get(set_index).ok_or_else(missing)?;
|
||||
let composite = self.document_composite(set_index, &cache.covered_tiles).ok_or_else(missing)?;
|
||||
let coverage = coverage(&cache.gbuf);
|
||||
let seams = if needs_padding {
|
||||
self.doc.project.texture_sets.get(set_index).and_then(|set| crate::session::padding_seams(&self.mesh, set, &cache.gbuf))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let empty = Default::default();
|
||||
let input = ExportInput {
|
||||
project: &self.doc.project,
|
||||
ts: set_index,
|
||||
composite: &composite,
|
||||
baked: self.doc.baked.get(&set_index).unwrap_or(&empty),
|
||||
coverage: &coverage,
|
||||
seams: seams.as_ref(),
|
||||
mesh_name,
|
||||
};
|
||||
with(&input)
|
||||
}
|
||||
|
||||
/// A picture of output map `map` for the first texture set named in `params`, with each side at most `side` pixels.
|
||||
/// Returns None when the map writes no file.
|
||||
pub fn export_preview(&mut self, params: &Value, map: usize, side: u32) -> Result<Option<MapPreview>> {
|
||||
let options = export_options(self, params, "export.preview")?;
|
||||
let Some(&set_index) = sets_param(self, params, "export.preview")?.first() else { return Ok(None) };
|
||||
|
||||
if self.solo.is_none() {
|
||||
self.update();
|
||||
}
|
||||
let mesh_name = stem_of(self.doc.project.mesh.trim_start_matches("builtin:"));
|
||||
self.with_export_input(
|
||||
set_index,
|
||||
&mesh_name,
|
||||
false,
|
||||
|grid| Cow::Borrowed(&grid.tri),
|
||||
|input| MapPreview::sample_triangles(input, &options, map, side).map_err(fe),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn check_materials(p: &texturecraft_core::Project, mesh: &Mesh) -> Result<()> {
|
||||
@@ -452,12 +546,12 @@ pub fn export_options(session: &Session, params: &Value, cmd: &str) -> Result<Ex
|
||||
Ok(options)
|
||||
}
|
||||
|
||||
/// `maps`: per map `{map: index into the preset's maps, enabled?, format?, bitDepth?, dithering?}`.
|
||||
/// `maps`: per map `{map: index into the preset's maps, enabled?, format?, bitDepth?, dithering?, size?}`
|
||||
fn map_overrides(params: &Value, map_count: usize, cmd: &str) -> Result<std::collections::BTreeMap<usize, MapOverride>> {
|
||||
let mut overrides = std::collections::BTreeMap::new();
|
||||
let Some(list) = params.get("maps").filter(|value| !value.is_null()) else { return Ok(overrides) };
|
||||
|
||||
let list = list.as_array().ok_or_else(|| bad(cmd, "`maps` must be a list of {map, enabled?, format?, bitDepth?, dithering?}"))?;
|
||||
let list = list.as_array().ok_or_else(|| bad(cmd, "`maps` must be a list of {map, enabled?, format?, bitDepth?, dithering?, size?}"))?;
|
||||
for settings in list {
|
||||
let index = u64p(settings, "map").and_then(|value| usize::try_from(value).ok()).filter(|index| *index < map_count);
|
||||
let index = index.ok_or_else(|| bad(cmd, format!("`maps`: `map` must be the index of one of the preset's {map_count} maps")))?;
|
||||
@@ -476,6 +570,10 @@ fn map_overrides(params: &Value, map_count: usize, cmd: &str) -> Result<std::col
|
||||
if let Some(dithering) = settings.get("dithering").filter(|value| !value.is_null()) {
|
||||
options.dither = Some(dithering.as_bool().ok_or_else(|| bad(cmd, "`maps`: `dithering` must be true or false"))?);
|
||||
}
|
||||
if let Some(size) = settings.get("size").filter(|value| !value.is_null()) {
|
||||
let size = size.as_u64().and_then(|size| u32::try_from(size).ok()).ok_or_else(|| bad(cmd, "`maps`: `size` must be a size in texels"))?;
|
||||
options.size = Some(crate::session::check_resolution(size)?);
|
||||
}
|
||||
|
||||
overrides.insert(index, options);
|
||||
}
|
||||
@@ -505,8 +603,24 @@ fn set_index(s: &Session, v: &Value, cmd: &str) -> Result<usize> {
|
||||
v.as_u64().and_then(|index| usize::try_from(index).ok()).filter(|index| *index < s.set_count()).ok_or_else(|| bad(cmd, "invalid `ts`"))
|
||||
}
|
||||
|
||||
fn preview(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
let map = u64p(params, "map").and_then(|map| usize::try_from(map).ok());
|
||||
let map = map.ok_or_else(|| bad("export.preview", "`map` (an output map index) is required"))?;
|
||||
let side = u64p(params, "side").map_or(DEFAULT_PREVIEW_SIDE_PIXELS, |side| side.clamp(1, u64::from(texturecraft_formats::MAX_PREVIEW_SIDE)) as u32);
|
||||
|
||||
Ok(match session.export_preview(params, map, side)? {
|
||||
Some(preview) => json!({
|
||||
"width": preview.width,
|
||||
"height": preview.height,
|
||||
"channels": preview.channels.iter().map(|dest| format!("{dest:?}")).collect::<Vec<_>>(),
|
||||
"pixels": preview.pixels,
|
||||
}),
|
||||
None => Value::Null,
|
||||
})
|
||||
}
|
||||
|
||||
fn plan(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
use texturecraft_formats::export::{list_set_outputs, scale_export_side};
|
||||
use texturecraft_formats::export::{list_set_outputs, output_dimensions};
|
||||
|
||||
let options = export_options(session, params, "export.plan")?;
|
||||
let project = &session.doc.project;
|
||||
@@ -519,21 +633,31 @@ fn plan(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
let Some((set_index, _)) = set_outputs.first() else { continue };
|
||||
|
||||
let set = project.texture_set(*set_index).map_err(|error| EngineError::Other(error.to_string()))?;
|
||||
let block_size = set.block_resolution();
|
||||
for (_, output) in set_outputs {
|
||||
let source_size = output.tile.map_or(set.resolution, |tile| set.tile_resolution(tile));
|
||||
let size = scale_export_side(source_size, block_size, options.size);
|
||||
let source = output_dimensions(set, output.tile, None);
|
||||
|
||||
// A PSD's canvas takes the largest width and height of its exported layers
|
||||
let (size, height) = output
|
||||
.maps()
|
||||
.map(|map| output_dimensions(set, output.tile, options.map_size(map)))
|
||||
.reduce(|(width, height), (next_width, next_height)| (width.max(next_width), height.max(next_height)))
|
||||
.unwrap_or(source);
|
||||
|
||||
files.push(json!({
|
||||
"ts": set_index,
|
||||
"map": output.map,
|
||||
"file": output.name,
|
||||
"tile": output.tile,
|
||||
"udimPattern": output.udim_name,
|
||||
"format": output.format.extension(),
|
||||
"bitDepth": output.bit_depth,
|
||||
"dithering": output.dither,
|
||||
"size": size,
|
||||
"sourceSize": source_size,
|
||||
"height": height,
|
||||
"sourceSize": source.0,
|
||||
"sourceHeight": source.1,
|
||||
"warnings": output.warnings,
|
||||
"layers": output.layers.iter().map(|layer| json!({ "map": layer.map, "name": layer.name })).collect::<Vec<_>>(),
|
||||
}));
|
||||
}
|
||||
}
|
||||
@@ -740,6 +864,10 @@ impl Session {
|
||||
|
||||
next.modified = true;
|
||||
next.project_id = self.project_id;
|
||||
|
||||
// Keep the stroke counter aligned with the painted regions in the cloned document
|
||||
next.painted_strokes = self.painted_strokes;
|
||||
|
||||
let preserved = preserve_strokes.then(|| crate::preserve::preserve_strokes(self, &mut next));
|
||||
|
||||
// Keep the stored source in the current session until reimport succeeds
|
||||
@@ -748,6 +876,7 @@ impl Session {
|
||||
}
|
||||
|
||||
self.switch_to(next);
|
||||
|
||||
Ok(preserved.map_or(Value::Null, |n| json!({ "preserved": n })))
|
||||
}
|
||||
}
|
||||
@@ -761,6 +890,7 @@ fn export_textures(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
let reserved_patterns: Vec<_> = taken_names.keys().filter(|name| name.contains("<udim>")).cloned().collect();
|
||||
let material = params.get("materialX").and_then(Value::as_bool).unwrap_or(false);
|
||||
let usd_asset = usd_asset_param(session, params, &options, &sets)?;
|
||||
let shader_sets = crate::shader_parameters::shader_parameters_param(&session.doc.project, params, &sets, "file.exportTextures")?;
|
||||
let mut warnings = Vec::new();
|
||||
let mut udim_patterns = Vec::new();
|
||||
|
||||
@@ -820,6 +950,22 @@ fn export_textures(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
if let Some(exports) = &usd_asset {
|
||||
written.extend(write_usd_asset(session, dir, exports, &mut warnings));
|
||||
}
|
||||
if let Some(shader_sets) = shader_sets {
|
||||
let name = crate::shader_parameters::shader_parameters_file(&session.doc.project.name);
|
||||
let path = dir.join(&name);
|
||||
let parameters = crate::shader_parameters::shader_parameters(&session.doc.project, &shader_sets);
|
||||
|
||||
// Check the name against this command's files and the earlier commands' `reservedNames`, as the web download and headless export do
|
||||
let roots = written.iter().filter_map(|written| written.strip_prefix(dir).ok()?.components().next()?.as_os_str().to_str());
|
||||
let checked = crate::shader_parameters::check_shader_parameters_name(&name, roots.chain(taken_names.keys().map(String::as_str)));
|
||||
|
||||
// The textures are written by now: a shaders file that fails is a warning, as a failed USD asset is
|
||||
let text = checked.and_then(|()| serde_json::to_vec_pretty(¶meters).map_err(|error| error.to_string()));
|
||||
match text.and_then(|text| texturecraft_formats::write_atomic(&path, &text).map_err(|error| error.to_string())) {
|
||||
Ok(()) => written.push(path),
|
||||
Err(error) => warnings.push(format!("The shader settings file was not written: {error}")),
|
||||
}
|
||||
}
|
||||
|
||||
session.log.info("MapExporter", format!("Exported {} textures to {}", written.len(), dir.display()));
|
||||
let mut response = json!({ "files": written.iter().map(|path| path.display().to_string()).collect::<Vec<_>>(), "warnings": warnings });
|
||||
@@ -861,7 +1007,7 @@ fn usd_asset_param(session: &Session, params: &Value, options: &ExportOptions, s
|
||||
/// warning: the textures of the command are already written.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn write_usd_asset(session: &Session, dir: &std::path::Path, exports: &[UsdAssetExport], warnings: &mut Vec<String>) -> Option<std::path::PathBuf> {
|
||||
match build_usd_asset(session, dir, exports) {
|
||||
match build_usd_asset(session, dir, exports, warnings) {
|
||||
Ok(path) => Some(path),
|
||||
Err(error) => {
|
||||
warnings.push(format!("{USD_ASSET_FAILED}: {error}"));
|
||||
@@ -871,7 +1017,7 @@ fn write_usd_asset(session: &Session, dir: &std::path::Path, exports: &[UsdAsset
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn build_usd_asset(session: &Session, dir: &std::path::Path, exports: &[UsdAssetExport]) -> Result<std::path::PathBuf> {
|
||||
fn build_usd_asset(session: &Session, dir: &std::path::Path, exports: &[UsdAssetExport], warnings: &mut Vec<String>) -> Result<std::path::PathBuf> {
|
||||
use texturecraft_formats::{list_outputs, usd_layer_with_textures, usd_texture_bindings};
|
||||
let project = &session.doc.project;
|
||||
let mesh_name = stem_of(project.mesh.trim_start_matches("builtin:"));
|
||||
@@ -892,6 +1038,15 @@ fn build_usd_asset(session: &Session, dir: &std::path::Path, exports: &[UsdAsset
|
||||
|
||||
// A map that lost any file (a tile of a UDIM map) is not bound: its `<UDIM>` name would read a file it does not own
|
||||
kept.retain(|file| !skipped_maps.contains(&file.map));
|
||||
let mut unsupported = HashSet::new();
|
||||
for file in kept.iter().filter(|file| !file.format.usable_by_usd_asset() && unsupported.insert(file.format)) {
|
||||
let format = file.format.extension().to_ascii_uppercase();
|
||||
let warning =
|
||||
format!("The USD asset doesn't read {format} files, so the material of texture set \"{}\" leaves out those maps", texture_set.name);
|
||||
if !warnings.contains(&warning) {
|
||||
warnings.push(warning);
|
||||
}
|
||||
}
|
||||
by_set.entry(set).or_insert_with(|| usd_texture_bindings(texture_set, options, project.normal_format, &kept));
|
||||
}
|
||||
}
|
||||
@@ -938,8 +1093,20 @@ fn reserve_export_names(
|
||||
let mut blocked_maps = HashSet::new();
|
||||
plans.retain(|plan| {
|
||||
let name = plan.name.to_ascii_lowercase();
|
||||
if reserved_patterns.iter().any(|pattern| udim_matches(pattern, &name)) {
|
||||
blocked_maps.insert(plan.map);
|
||||
let reserved = reserved_patterns.iter().any(|pattern| udim_matches(pattern, &name));
|
||||
if !reserved && let Entry::Vacant(entry) = taken_names.entry(name) {
|
||||
entry.insert(Some(set_index));
|
||||
return true;
|
||||
}
|
||||
|
||||
// A set warning outlives the file that carried it
|
||||
for warning in plan.warnings.iter().filter(|warning| texturecraft_formats::export::is_set_warning(warning)) {
|
||||
if !warnings.contains(warning) {
|
||||
warnings.push(warning.clone());
|
||||
}
|
||||
}
|
||||
blocked_maps.extend(plan.maps());
|
||||
if reserved {
|
||||
warnings.push(format!(
|
||||
"\"{}\" was not written: an earlier MaterialX document uses that UDIM pattern. Rename a texture set or change the template file names",
|
||||
plan.name
|
||||
@@ -947,12 +1114,6 @@ fn reserve_export_names(
|
||||
return false;
|
||||
}
|
||||
|
||||
if let Entry::Vacant(entry) = taken_names.entry(name) {
|
||||
entry.insert(Some(set_index));
|
||||
return true;
|
||||
}
|
||||
|
||||
blocked_maps.insert(plan.map);
|
||||
if fallback {
|
||||
warnings.push(format!(
|
||||
"MaterialX: \"{}\" was not written: a file of the chosen template or of an earlier command of this export has the name. Rename a texture set or change the template file names",
|
||||
@@ -1029,11 +1190,11 @@ fn material_map_options(options: &ExportOptions, project_normal: NormalFormat) -
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut overrides = MapOverride::default();
|
||||
let settings = replacement.and_then(|(index, _)| options.maps.get(&index));
|
||||
let mut overrides = MapOverride { size: settings.and_then(|settings| settings.size), ..MapOverride::default() };
|
||||
let requested_format = replacement.map(|(index, _)| selected_format(index)).or(options.format_override);
|
||||
if requested_format.is_none_or(material_format) {
|
||||
overrides.format = requested_format;
|
||||
let settings = replacement.and_then(|(index, _)| options.maps.get(&index));
|
||||
overrides.bit_depth =
|
||||
settings.and_then(|settings| settings.bit_depth).or(options.bit_depth_override).or_else(|| replacement.map(|(_, selected)| selected.bit_depth));
|
||||
overrides.dither = settings.and_then(|settings| settings.dither);
|
||||
@@ -1254,6 +1415,7 @@ impl Session {
|
||||
None => "obj".into(),
|
||||
};
|
||||
let path = if ext_of(path) == ext { path.to_string() } else { format!("{path}.{ext}") };
|
||||
|
||||
let (bytes, textures) = match (ext.as_str(), texturecraft_formats::UsdFormat::from_ext(&ext)) {
|
||||
("glb", _) => (self.mesh_glb_bytes_with_normals(recompute_normals)?, Vec::new()),
|
||||
(_, Some(format)) => {
|
||||
@@ -1262,6 +1424,7 @@ impl Session {
|
||||
}
|
||||
_ => self.mesh_obj_with_mtl_and_normals(std::path::Path::new(&path).file_stem().and_then(|s| s.to_str()).unwrap_or("mesh"), recompute_normals)?,
|
||||
};
|
||||
|
||||
Ok(MeshExport { path, bytes, textures })
|
||||
}
|
||||
}
|
||||
@@ -1463,11 +1626,13 @@ f 1/1 2/2 3/3
|
||||
let dir = std::env::temp_dir().join(format!("tc_export_recompute_{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
|
||||
for (format, suffix) in [("obj", "obj"), ("glb", "glb"), ("usda", "usda")] {
|
||||
let path = dir.join(format!("cube-{format}.{suffix}"));
|
||||
let reply = crate::execute(&mut s, "file.exportMesh", &json!({"path": path, "recomputeNormals": true})).unwrap();
|
||||
let bytes = std::fs::read(reply["path"].as_str().unwrap()).unwrap();
|
||||
let back = texturecraft_formats::import_mesh_bytes(&format!("cube.{suffix}"), &bytes).unwrap().mesh;
|
||||
|
||||
assert_eq!(back.normals.len(), expected.normals.len(), "{format}: one normal per exported vertex");
|
||||
for (position, actual) in back.positions.iter().zip(&back.normals) {
|
||||
let wanted = expected
|
||||
@@ -1479,8 +1644,10 @@ f 1/1 2/2 3/3
|
||||
assert!((*actual - wanted).length() < 1e-4, "{format}: actual {actual:?}, wanted {wanted:?}");
|
||||
}
|
||||
}
|
||||
|
||||
assert!(s.source.normals.iter().all(|n| *n == texturecraft_geom::glam::Vec3::Y), "the source project is unchanged");
|
||||
assert!(s.mesh.normals.iter().all(|n| *n == texturecraft_geom::glam::Vec3::Y), "the render project is unchanged");
|
||||
|
||||
let stored_path = dir.join("stored.obj");
|
||||
let stored = crate::execute(&mut s, "file.exportMesh", &json!({"path": stored_path})).unwrap();
|
||||
let stored = std::fs::read(stored["path"].as_str().unwrap()).unwrap();
|
||||
@@ -1493,7 +1660,7 @@ f 1/1 2/2 3/3
|
||||
fn recomputed_normals_weld_uv_seams_in_exported_mesh() {
|
||||
use texturecraft_geom::glam::Vec3;
|
||||
|
||||
// Two triangles meet along 0--2, but their UV island split duplicates that edge as 3--4.
|
||||
// The UV seam duplicates edge 0–2 at vertices 3 and 4
|
||||
let positions = vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::ZERO, Vec3::Y, Vec3::new(-1.0, 0.0, 1.0)];
|
||||
let mesh = Mesh::from_parts(
|
||||
positions,
|
||||
@@ -1504,8 +1671,10 @@ f 1/1 2/2 3/3
|
||||
)
|
||||
.unwrap();
|
||||
let mut s = Session::new_project("seam", mesh, "builtin:seam", None, 128).unwrap();
|
||||
|
||||
let bytes = s.mesh_glb_bytes_with_normals(true).unwrap();
|
||||
let back = texturecraft_formats::import_mesh_bytes("seam.glb", &bytes).unwrap().mesh;
|
||||
|
||||
for point in [Vec3::ZERO, Vec3::Y] {
|
||||
let normals: Vec<_> = back.positions.iter().zip(&back.normals).filter_map(|(position, normal)| (*position == point).then_some(*normal)).collect();
|
||||
assert!(normals.len() >= 2, "{point:?}: the UV seam must still have two exported vertices");
|
||||
@@ -1651,11 +1820,18 @@ f 1/1 2/2 3/3
|
||||
let a = dir.join("a.obj");
|
||||
std::fs::write(&a, "v 0 0 0\nv 1 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n").unwrap();
|
||||
|
||||
// Same triangle count, other vertices
|
||||
// Keep the triangle count fixed while changing the geometry
|
||||
let b = dir.join("b.obj");
|
||||
std::fs::write(&b, "v 0 0 0\nv 2 0 0\nv 0 2 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n").unwrap();
|
||||
let mut s = Session::from_mesh_bytes("a.obj", &std::fs::read(&a).unwrap(), 128, "a").unwrap();
|
||||
let cage = crate::bake::BakeMesh { name: "cage".into(), folder: None, bytes: Default::default(), mesh: s.mesh.clone(), base_color: Vec::new() };
|
||||
let cage = crate::bake::BakeMesh {
|
||||
name: "cage".into(),
|
||||
folder: None,
|
||||
bytes: Default::default(),
|
||||
mesh: s.mesh.clone(),
|
||||
base_color: Vec::new(),
|
||||
fingerprint: 0,
|
||||
};
|
||||
s.doc.bake_meshes.cage = Some(cage);
|
||||
let _ = s.doc.bake_meshes.low_base_color.set(Err("old".into()));
|
||||
|
||||
|
||||
@@ -264,19 +264,32 @@ pub fn texture_set(session: &Session, index: usize) -> Value {
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
let out_of_date: std::collections::BTreeMap<_, Vec<_>> =
|
||||
session.out_of_date_maps(index).into_iter().map(|(map, changes)| (map.id(), changes.iter().map(|change| change.id()).collect())).collect();
|
||||
|
||||
json!({
|
||||
"index": index,
|
||||
"name": texture_set.name,
|
||||
"originalName": session.original_set_name(index),
|
||||
"description": texture_set.description,
|
||||
"resolution": texture_set.resolution,
|
||||
"height": texture_set.height(),
|
||||
"size": texture_set.size(),
|
||||
"blockResolution": texture_set.block_resolution(),
|
||||
"uvTiles": texture_set.uv_tiles,
|
||||
"tiles": tiles,
|
||||
"channels": texture_set.channels.iter().map(|(channel, format)| json!({ "channel": channel.id(), "format": format.label() })).collect::<Vec<_>>(),
|
||||
"channels": texture_set.formats().iter().map(|(channel, format)| json!({ "channel": channel.id(), "format": format.label(), "shaded": channel.is_shaded() })).collect::<Vec<_>>(),
|
||||
"layers": session.doc.project.walk(index).len(),
|
||||
"parts": crate::set_cmds::parts(session, index),
|
||||
"baked": crate::project_cmds::baked_json(session.doc.baked.get(&index)),
|
||||
"outOfDate": out_of_date,
|
||||
"autoRebake": texture_set.auto_rebake.map(texturecraft_core::BakedMap::id),
|
||||
"visible": texture_set.visible,
|
||||
"normalMixing": texture_set.normal_mixing.id(),
|
||||
"aoMixing": texture_set.ao_mixing.id(),
|
||||
"heightToNormal": texture_set.height_to_normal.id(),
|
||||
"uvPadding": texture_set.uv_padding.id(),
|
||||
"active": index == session.ts(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
pub mod add_mask_cmds;
|
||||
mod anchored_micro_edit;
|
||||
pub mod bake;
|
||||
pub mod bake_log_cmds;
|
||||
pub mod bake_preview;
|
||||
pub mod brush_preset_cmds;
|
||||
pub mod camera_cmds;
|
||||
@@ -51,6 +52,7 @@ pub mod material_lib;
|
||||
mod material_preview_pixel;
|
||||
pub mod materials;
|
||||
pub mod materialx_cmds;
|
||||
mod mesh_map_sampler;
|
||||
pub mod meshmap_cmds;
|
||||
mod meshmap_file_name;
|
||||
pub mod meshmap_import_cmds;
|
||||
@@ -73,10 +75,20 @@ pub mod preview;
|
||||
mod procedural_params;
|
||||
pub mod project_cmds;
|
||||
pub mod quick_mask;
|
||||
// Reloading resource files reads paths on native targets only
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod reloaded_file;
|
||||
// Remembered file comparisons exist on native targets only
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod resource_check;
|
||||
pub mod resource_cmds;
|
||||
pub mod resource_state;
|
||||
pub mod resource_status;
|
||||
pub mod resource_update_cmds;
|
||||
pub mod session;
|
||||
mod session_log;
|
||||
pub mod set_cmds;
|
||||
pub mod shader_parameters;
|
||||
pub mod smart_masks;
|
||||
mod solo;
|
||||
mod stylized_lighting_params;
|
||||
@@ -102,6 +114,8 @@ pub use fill_mode::FillMode;
|
||||
pub use log::{LogEntry, LogLevel, SessionLog};
|
||||
pub use path_tool::PathState;
|
||||
pub use project_cmds::sample_session;
|
||||
pub use resource_state::ResourceState;
|
||||
pub use resource_status::ResourceStatus;
|
||||
pub use session::{
|
||||
CloneFrom, CloneSource, Document, HISTORY_TEMPLATES, NORMAL_HEIGHT_MESH_LABEL, Session, SetCache, StackTarget, StencilLook, StencilState, Tool, ToolState,
|
||||
ViewMode, history_label, stroke_template,
|
||||
@@ -127,6 +141,8 @@ pub enum EngineError {
|
||||
BadParams { cmd: String, msg: String },
|
||||
#[error(transparent)]
|
||||
Core(#[from] texturecraft_core::CoreError),
|
||||
#[error("bake failed: bake cancelled")]
|
||||
BakeCancelled,
|
||||
#[error("{0}")]
|
||||
Other(String),
|
||||
}
|
||||
|
||||
@@ -313,7 +313,8 @@ fn save_source(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
Err(EngineError::Other("file paths are not available in the browser".into()))
|
||||
}
|
||||
|
||||
/// A MaterialCraft executable: `$<env>`, else next to this program, else `name` on `PATH`.
|
||||
/// A MaterialCraft executable: `$<env>`, else next to this program, else in the sibling
|
||||
/// `MaterialCraft` folder (the launcher's layout), else `name` on `PATH`.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn materialcraft_tool(name: &str, env: &str) -> std::path::PathBuf {
|
||||
if let Some(p) = std::env::var_os(env).filter(|p| !p.is_empty()) {
|
||||
@@ -321,7 +322,18 @@ pub fn materialcraft_tool(name: &str, env: &str) -> std::path::PathBuf {
|
||||
}
|
||||
|
||||
let exe = format!("{name}{}", std::env::consts::EXE_SUFFIX);
|
||||
std::env::current_exe().ok().and_then(|e| Some(e.parent()?.join(&exe))).filter(|p| p.is_file()).unwrap_or_else(|| exe.into())
|
||||
let app_dir = std::env::current_exe().ok().and_then(|e| e.parent().map(std::path::Path::to_path_buf));
|
||||
app_dir.and_then(|d| find_installed_tool(&d, &exe)).unwrap_or_else(|| exe.into())
|
||||
}
|
||||
|
||||
/// `exe` in `app_dir` (next to this program), else in the sibling `MaterialCraft` folder beside `app_dir`
|
||||
/// (`<root>/TextureCraft` and `<root>/MaterialCraft`, as the ArtCraft Launcher installs them). `None` if neither has it.
|
||||
/// Versioned `<app>/<version>/` layouts and macOS `.app` bundles are not searched.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn find_installed_tool(app_dir: &std::path::Path, exe: &str) -> Option<std::path::PathBuf> {
|
||||
let beside = app_dir.join(exe);
|
||||
let sibling = app_dir.parent().map(|root| root.join("MaterialCraft").join(exe));
|
||||
std::iter::once(beside).chain(sibling).find(|p| p.is_file())
|
||||
}
|
||||
|
||||
/// A command for a MaterialCraft executable that opens no console window.
|
||||
@@ -335,15 +347,80 @@ fn quiet(program: &std::path::Path) -> std::process::Command {
|
||||
}
|
||||
|
||||
/// Open `package` (a published material or authoring package) in the MaterialCraft app (`$MATERIALCRAFT`, next to this
|
||||
/// program, or on `PATH`).
|
||||
/// program, in the sibling `MaterialCraft` folder, or on `PATH`).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn open_in_materialcraft(package: &std::path::Path) -> Result<()> {
|
||||
let app = materialcraft_tool("materialcraft", "MATERIALCRAFT");
|
||||
quiet(&app).arg(package).spawn().map(drop).map_err(|e| {
|
||||
EngineError::Other(format!("MaterialCraft ({}) did not start: {e}. Install MaterialCraft next to TextureCraft or set MATERIALCRAFT", app.display()))
|
||||
EngineError::Other(format!(
|
||||
"MaterialCraft ({}) did not start: {e}. Install MaterialCraft next to TextureCraft or in a sibling MaterialCraft folder, or set MATERIALCRAFT",
|
||||
app.display()
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
/// Prefix of the folders [`stage_handoff_package`] makes in the temp folder.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const HANDOFF_PREFIX: &str = "texturecraft-open-";
|
||||
|
||||
/// Folders from earlier hand-offs older than this are removed (MaterialCraft may still have a young one open).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const HANDOFF_MAX_AGE: std::time::Duration = std::time::Duration::from_secs(7 * 24 * 3600);
|
||||
|
||||
/// Write `package` as `file_name` inside a new folder only this call can have made under the temp folder, and return the
|
||||
/// file's path (for [`open_in_materialcraft`]). A fixed `<temp>/<name>` is guessable: on a shared `/tmp` another user
|
||||
/// could plant a file or link there first and the write would go through it. The folder name is random, is created
|
||||
/// exclusively (mode `0700` on Unix) and the file is created with `create_new` (mode `0600`), so nothing planted is ever written through.
|
||||
/// The folder stays after the call because MaterialCraft needs the file while it is open; folders over a week old go.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn stage_handoff_package(file_name: &str, package: &[u8]) -> Result<std::path::PathBuf> {
|
||||
stage_handoff_package_in(&std::env::temp_dir(), file_name, package)
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn stage_handoff_package_in(base: &std::path::Path, file_name: &str, package: &[u8]) -> Result<std::path::PathBuf> {
|
||||
use std::io::Write;
|
||||
let io = |e: std::io::Error| EngineError::Other(format!("cannot stage the package for MaterialCraft: {e}"));
|
||||
if file_name.is_empty() || std::path::Path::new(file_name).file_name() != Some(std::ffi::OsStr::new(file_name)) {
|
||||
return Err(EngineError::Other(format!("`{file_name}` is not a plain file name")));
|
||||
}
|
||||
sweep_old_handoffs(base, HANDOFF_MAX_AGE);
|
||||
// Dropped (and removed) on any early return, so a failed write leaves no empty folder behind.
|
||||
let mut builder = tempfile::Builder::new();
|
||||
builder.prefix(HANDOFF_PREFIX);
|
||||
// tempfile makes folders with the default mode (0755 under the usual umask), so ask for 0700 and 0600 explicitly.
|
||||
#[cfg(unix)]
|
||||
builder.permissions(std::os::unix::fs::PermissionsExt::from_mode(0o700));
|
||||
let dir = builder.tempdir_in(base).map_err(io)?;
|
||||
let path = dir.path().join(file_name);
|
||||
let mut options = std::fs::OpenOptions::new();
|
||||
options.write(true).create_new(true);
|
||||
#[cfg(unix)]
|
||||
std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
|
||||
let mut file = options.open(&path).map_err(io)?;
|
||||
file.write_all(package).map_err(io)?;
|
||||
file.sync_all().map_err(io)?;
|
||||
let _ = dir.keep();
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
/// Remove hand-off folders in `base` last changed more than `max_age` ago. Only real folders with our prefix are
|
||||
/// touched (never a link), and every failure is ignored: a leftover folder costs disk space, not work.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn sweep_old_handoffs(base: &std::path::Path, max_age: std::time::Duration) {
|
||||
let Ok(entries) = std::fs::read_dir(base) else { return };
|
||||
for entry in entries.flatten() {
|
||||
if !entry.file_name().to_string_lossy().starts_with(HANDOFF_PREFIX) {
|
||||
continue;
|
||||
}
|
||||
let Ok(meta) = std::fs::symlink_metadata(entry.path()) else { continue };
|
||||
let old = meta.modified().ok().and_then(|t| t.elapsed().ok()).is_some_and(|age| age > max_age);
|
||||
if meta.is_dir() && old {
|
||||
let _ = std::fs::remove_dir_all(entry.path());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Source file extensions are chosen from the linked resource name, never an untrusted path.
|
||||
pub fn source_extension(name: &str) -> &'static str {
|
||||
if name.to_ascii_lowercase().ends_with(".mcmat") {
|
||||
@@ -623,6 +700,7 @@ impl Session {
|
||||
|
||||
for name in old_names.iter().filter(|name| !used_names.contains(name)) {
|
||||
session.doc.resources.remove(name);
|
||||
session.doc.project.resource_sources.remove(name);
|
||||
}
|
||||
|
||||
Ok(names)
|
||||
@@ -711,4 +789,146 @@ mod tests {
|
||||
assert_eq!(typed(&p, &json!("#+f+f+f")), None);
|
||||
assert!(typed(&p, &json!("#ff8000")).is_some());
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn touch(dir: &std::path::Path, exe: &str) -> std::path::PathBuf {
|
||||
std::fs::create_dir_all(dir).unwrap();
|
||||
let p = dir.join(exe);
|
||||
std::fs::write(&p, b"").unwrap();
|
||||
p
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn launcher_layout_finds_the_sibling_materialcraft_folder() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let app = root.path().join("TextureCraft");
|
||||
std::fs::create_dir_all(&app).unwrap();
|
||||
let tool = touch(&root.path().join("MaterialCraft"), "materialcraft-cli");
|
||||
assert_eq!(super::find_installed_tool(&app, "materialcraft-cli"), Some(tool));
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_tool_beside_the_program_wins_over_the_sibling_folder() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let app = root.path().join("TextureCraft");
|
||||
let beside = touch(&app, "materialcraft-cli");
|
||||
touch(&root.path().join("MaterialCraft"), "materialcraft-cli");
|
||||
assert_eq!(super::find_installed_tool(&app, "materialcraft-cli"), Some(beside));
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_missing_tool_is_none_so_the_caller_falls_back_to_path() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let app = root.path().join("TextureCraft");
|
||||
std::fs::create_dir_all(root.path().join("MaterialCraft")).unwrap();
|
||||
assert_eq!(super::find_installed_tool(&app, "materialcraft-cli"), None);
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_folder_named_like_the_tool_is_not_the_tool() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let app = root.path().join("TextureCraft");
|
||||
std::fs::create_dir_all(app.join("materialcraft-cli")).unwrap();
|
||||
std::fs::create_dir_all(root.path().join("MaterialCraft").join("materialcraft-cli")).unwrap();
|
||||
assert_eq!(super::find_installed_tool(&app, "materialcraft-cli"), None);
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn an_app_folder_with_no_parent_does_not_panic() {
|
||||
// The root (or an empty path) has no parent: only the beside-the-program step can apply.
|
||||
assert_eq!(super::find_installed_tool(std::path::Path::new(""), "no-such-materialcraft-tool"), None);
|
||||
let root = std::env::temp_dir().ancestors().last().map(std::path::Path::to_path_buf).unwrap_or_default();
|
||||
assert_eq!(super::find_installed_tool(&root, "no-such-materialcraft-tool"), None);
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_missing_app_folder_is_none() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let gone = root.path().join("nowhere").join("TextureCraft");
|
||||
assert_eq!(super::find_installed_tool(&gone, "materialcraft-cli"), None);
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn scratch(name: &str) -> std::path::PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("tc_handoff_{name}_{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
/// A file another user planted at the old, guessable `<temp>/<name>` is never written through.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn handoff_package_is_not_written_through_a_planted_link() {
|
||||
let base = scratch("planted");
|
||||
let victim = base.join("victim.txt");
|
||||
std::fs::write(&victim, b"precious").unwrap();
|
||||
// The old code wrote `<temp>/<name>` with `fs::write`; a hard link there reaches the victim on every platform.
|
||||
std::fs::hard_link(&victim, base.join("wood.mcraft")).unwrap();
|
||||
|
||||
let path = super::stage_handoff_package_in(&base, "wood.mcraft", b"package").unwrap();
|
||||
|
||||
assert_eq!(std::fs::read(&victim).unwrap(), b"precious");
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"package");
|
||||
assert_ne!(path.parent().unwrap(), base, "the file is inside a folder of its own");
|
||||
std::fs::remove_dir_all(&base).unwrap();
|
||||
}
|
||||
|
||||
/// Every hand-off gets its own empty-until-written folder, even when the name repeats.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn handoff_packages_get_distinct_folders() {
|
||||
let base = scratch("distinct");
|
||||
let a = super::stage_handoff_package_in(&base, "m.mcraft", b"a").unwrap();
|
||||
let b = super::stage_handoff_package_in(&base, "m.mcraft", b"b").unwrap();
|
||||
assert_ne!(a.parent(), b.parent());
|
||||
assert_eq!((std::fs::read(&a).unwrap(), std::fs::read(&b).unwrap()), (b"a".to_vec(), b"b".to_vec()));
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
assert_eq!(std::fs::metadata(a.parent().unwrap()).unwrap().permissions().mode() & 0o777, 0o700);
|
||||
assert_eq!(std::fs::metadata(&a).unwrap().permissions().mode() & 0o777, 0o600);
|
||||
}
|
||||
std::fs::remove_dir_all(&base).unwrap();
|
||||
}
|
||||
|
||||
/// A name with a path in it cannot leave the new folder.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn handoff_package_rejects_names_that_are_paths() {
|
||||
let base = scratch("names");
|
||||
for bad in ["", "..", "a/b.mcraft", "../x.mcraft"] {
|
||||
assert!(super::stage_handoff_package_in(&base, bad, b"x").is_err(), "{bad}");
|
||||
}
|
||||
assert_eq!(std::fs::read_dir(&base).unwrap().count(), 0, "a rejected name leaves nothing behind");
|
||||
std::fs::remove_dir_all(&base).unwrap();
|
||||
}
|
||||
|
||||
/// Old hand-off folders are swept; young ones, other folders and files stay.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn handoff_sweep_removes_only_old_handoff_folders() {
|
||||
let base = scratch("sweep");
|
||||
let old = base.join("texturecraft-open-old");
|
||||
let other = base.join("somebody-elses-folder");
|
||||
let file = base.join("texturecraft-open-file");
|
||||
for dir in [&old, &other] {
|
||||
std::fs::create_dir(dir).unwrap();
|
||||
}
|
||||
std::fs::write(&file, b"x").unwrap();
|
||||
// Zero age limit: everything with the prefix that is a folder counts as old.
|
||||
super::sweep_old_handoffs(&base, std::time::Duration::ZERO);
|
||||
assert!(!old.exists() && other.exists() && file.exists());
|
||||
let young = base.join("texturecraft-open-young");
|
||||
std::fs::create_dir(&young).unwrap();
|
||||
super::sweep_old_handoffs(&base, std::time::Duration::from_secs(3600));
|
||||
assert!(young.exists());
|
||||
std::fs::remove_dir_all(&base).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -120,7 +120,7 @@ fn run_bounded(command: &std::process::Command, stdout: &Path, stderr: &Path, re
|
||||
.stdout(std::fs::File::create(stdout).map_err(io)?)
|
||||
.stderr(std::fs::File::create(stderr).map_err(io)?)
|
||||
.spawn()
|
||||
.map_err(|error| io(format!("could not start the MaterialCraft cook: {error}. Install MaterialCraft or set MATERIALCRAFT_CLI")))?;
|
||||
.map_err(|error| io(format!("could not start the MaterialCraft cook: {error}. Install MaterialCraft next to TextureCraft or in a sibling MaterialCraft folder, or set MATERIALCRAFT_CLI")))?;
|
||||
|
||||
loop {
|
||||
if canceled.load(Ordering::Relaxed) {
|
||||
|
||||
@@ -42,20 +42,22 @@ impl Session {
|
||||
let (width, height, values) = atlas;
|
||||
let set = self.doc.project.texture_set(ts).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
let Some(grid) = set.tile_grid().filter(|_| per_tile) else { return Ok(vec![MaskBitmap { tile: None, width, height, values }]) };
|
||||
let block = set.block_resolution();
|
||||
let (block_width, block_height) = set.block_size();
|
||||
set.uv_tiles
|
||||
.iter()
|
||||
.map(|&tile| {
|
||||
let (block_x, block_y) = grid.block(tile).ok_or_else(|| EngineError::Other(format!("UV tile {tile} is not in the set's grid")))?;
|
||||
|
||||
// A tile smaller than its block fills the block's top-left corner
|
||||
let side = ((block as f32 * set.tile_scale(tile)).round() as u32).clamp(1, block);
|
||||
let mut tile_values = Vec::with_capacity(side as usize * side as usize);
|
||||
for row in 0..side {
|
||||
let start = ((block_y * block + row) as usize) * width as usize + (block_x * block) as usize;
|
||||
tile_values.extend_from_slice(values.get(start..start + side as usize).unwrap_or(&[]));
|
||||
let scale = set.tile_scale(tile);
|
||||
let tile_width = ((block_width as f32 * scale).round() as u32).clamp(1, block_width);
|
||||
let tile_height = ((block_height as f32 * scale).round() as u32).clamp(1, block_height);
|
||||
let mut tile_values = Vec::with_capacity(tile_width as usize * tile_height as usize);
|
||||
for row in 0..tile_height {
|
||||
let start = ((block_y * block_height + row) as usize) * width as usize + (block_x * block_width) as usize;
|
||||
tile_values.extend_from_slice(values.get(start..start + tile_width as usize).unwrap_or(&[]));
|
||||
}
|
||||
Ok(MaskBitmap { tile: Some(tile), width: side, height: side, values: tile_values })
|
||||
Ok(MaskBitmap { tile: Some(tile), width: tile_width, height: tile_height, values: tile_values })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ use std::sync::Arc;
|
||||
|
||||
use serde_json::Value;
|
||||
use texturecraft_compose::PixelStore;
|
||||
use texturecraft_core::{LayerId, LayerKind, Project, Source, TextureSet};
|
||||
use texturecraft_core::{EffectKind, Fill, LayerId, LayerKind, Project, Source, TextureSet};
|
||||
|
||||
use crate::commands::{CommandSpec, always, has_layer};
|
||||
use crate::materials::Place;
|
||||
@@ -36,7 +36,15 @@ fn fe(e: texturecraft_formats::FormatError) -> EngineError {
|
||||
EngineError::Other(e.to_string())
|
||||
}
|
||||
|
||||
/// Image resources a layer subtree uses (fill sources and their patterns, mask or content effects and the images its paths paint with)
|
||||
/// The package and cooked maps of the MaterialCraft material linked to `fill`, if any
|
||||
fn link_images(fill: &Fill, out: &mut Vec<String>) {
|
||||
if let Some(link) = &fill.link {
|
||||
out.push(link.package.clone());
|
||||
out.extend(link.outputs.values().cloned());
|
||||
}
|
||||
}
|
||||
|
||||
/// Image resources a layer subtree uses (fill sources and their patterns, linked materials, mask or content effects and the images its paths paint with)
|
||||
pub(crate) fn images_used(project: &Project, id: LayerId, out: &mut Vec<String>, depth: usize) {
|
||||
if depth > texturecraft_core::project::MAX_DEPTH {
|
||||
return;
|
||||
@@ -46,15 +54,15 @@ pub(crate) fn images_used(project: &Project, id: LayerId, out: &mut Vec<String>,
|
||||
|
||||
if let LayerKind::Fill(fill) = &layer.kind {
|
||||
out.extend(fill.sources.values().flat_map(Source::images).map(str::to_string));
|
||||
if let Some(link) = &fill.link {
|
||||
out.push(link.package.clone());
|
||||
out.extend(link.outputs.values().cloned());
|
||||
}
|
||||
link_images(fill, out);
|
||||
}
|
||||
|
||||
for effect in layer.mask.iter().flat_map(|mask| mask.effects.iter()).chain(&layer.content_effects) {
|
||||
out.extend(effect.images_read().map(str::to_string));
|
||||
out.extend(crate::path_tool::path_images(&effect.kind));
|
||||
if let EffectKind::Material(fill) = &effect.kind {
|
||||
link_images(fill, out);
|
||||
}
|
||||
}
|
||||
|
||||
for child in layer.children() {
|
||||
@@ -66,10 +74,13 @@ pub(crate) fn images_used(project: &Project, id: LayerId, out: &mut Vec<String>,
|
||||
pub(crate) fn one_set_document(src_set: &TextureSet, name: &str) -> Document {
|
||||
let mut project = Project::new(name, "builtin:none");
|
||||
let mut set = TextureSet::new(name, 0, src_set.resolution);
|
||||
set.resolution_height = src_set.resolution_height;
|
||||
set.uv_tiles = src_set.uv_tiles.clone();
|
||||
set.tile_resolutions = src_set.tile_resolutions.clone();
|
||||
set.channels = src_set.channels.clone();
|
||||
set.format_precision = src_set.format_precision;
|
||||
project.texture_sets.push(set);
|
||||
|
||||
Document {
|
||||
bake_meshes: Default::default(),
|
||||
bake_paint: BTreeMap::new(),
|
||||
@@ -77,6 +88,7 @@ pub(crate) fn one_set_document(src_set: &TextureSet, name: &str) -> Document {
|
||||
pixels: PixelStore::default(),
|
||||
baked: BTreeMap::new(),
|
||||
resources: BTreeMap::new(),
|
||||
painted_regions: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -145,6 +157,7 @@ impl Session {
|
||||
project: project_file.project,
|
||||
pixels: project_file.pixels,
|
||||
baked: BTreeMap::new(),
|
||||
painted_regions: Default::default(),
|
||||
resources,
|
||||
};
|
||||
|
||||
|
||||
@@ -34,17 +34,25 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
/// Loads an image file named in the document (relative to it): its bytes, or why not.
|
||||
pub type Loader<'a> = &'a dyn Fn(&str) -> std::result::Result<Vec<u8>, String>;
|
||||
|
||||
type LocatedImage = (Vec<u8>, Option<texturecraft_core::ResourceSource>);
|
||||
type LocatedLoader<'a> = &'a dyn Fn(&str) -> std::result::Result<LocatedImage, String>;
|
||||
|
||||
impl Session {
|
||||
/// Add `material` as a fill layer on the active texture set, loading its images with `load`.
|
||||
/// Returns the reply of `file.importMaterialX`.
|
||||
pub fn import_material(&mut self, material: Material, name: Option<&str>, load: Loader) -> Result<Value> {
|
||||
self.import_material_with_sources(material, name, &|file| load(file).map(|bytes| (bytes, None)))
|
||||
}
|
||||
|
||||
fn import_material_with_sources(&mut self, material: Material, name: Option<&str>, load: LocatedLoader) -> Result<Value> {
|
||||
let mut warnings = material.warnings.clone();
|
||||
let ts = self.ts();
|
||||
let available = self.doc.project.texture_set(ts).map(|t| t.channel_list()).unwrap_or_default();
|
||||
let mut fill = Fill { projection: Projection::Uv { scale: material.uv_tiling, rotation: 0.0, offset: [0.0, 0.0] }, ..Fill::default() };
|
||||
// Resources to add (name and encoded bytes), and their decoded images for the session.
|
||||
|
||||
let mut added: Vec<(String, Arc<Vec<u8>>)> = Vec::new();
|
||||
let mut decoded = Vec::new();
|
||||
let mut sources = Vec::new();
|
||||
let mut names: BTreeMap<String, String> = BTreeMap::new();
|
||||
let mut channels: Vec<Channel> = Vec::new();
|
||||
for (channel, value) in &material.channels {
|
||||
@@ -52,15 +60,17 @@ impl Session {
|
||||
warnings.push(format!("{} was skipped: this texture set has no such channel", channel.id()));
|
||||
continue;
|
||||
}
|
||||
|
||||
let source = match value {
|
||||
Mtlx::Constant(c) => Source::Uniform(*c),
|
||||
Mtlx::Image(file) => {
|
||||
let resource = match names.get(file) {
|
||||
Some(n) => n.clone(),
|
||||
None => {
|
||||
let loaded =
|
||||
load(file).and_then(|bytes| texturecraft_formats::decode_image(&bytes).map(|image| (bytes, image)).map_err(|e| e.to_string()));
|
||||
let (bytes, image) = match loaded {
|
||||
let loaded = load(file).and_then(|(bytes, source)| {
|
||||
texturecraft_formats::decode_image(&bytes).map(|image| (bytes, image, source)).map_err(|e| e.to_string())
|
||||
});
|
||||
let (bytes, image, source) = match loaded {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
warnings.push(format!("{} was skipped: {file}: {e}", channel.id()));
|
||||
@@ -69,11 +79,11 @@ impl Session {
|
||||
};
|
||||
let leaf = file.rsplit(['/', '\\']).next().unwrap_or(file);
|
||||
let base = texturecraft_formats::sanitize_resource_name(leaf);
|
||||
let (mut unique, mut n) = (base.clone(), 2);
|
||||
while self.doc.resources.contains_key(&unique) || added.iter().any(|(a, _)| *a == unique) {
|
||||
unique = format!("{n}_{base}");
|
||||
n += 1;
|
||||
}
|
||||
let unique = crate::resource_cmds::unique_resource_name(base, |name| {
|
||||
self.doc.resources.contains_key(name) || added.iter().any(|(added_name, _)| added_name == name)
|
||||
});
|
||||
|
||||
sources.extend(source.map(|source| (unique.clone(), source)));
|
||||
added.push((unique.clone(), Arc::new(bytes)));
|
||||
decoded.push((unique.clone(), crate::resource_cmds::decoded(image)));
|
||||
names.insert(file.clone(), unique.clone());
|
||||
@@ -90,12 +100,14 @@ impl Session {
|
||||
let why = if warnings.is_empty() { String::new() } else { format!(" ({})", warnings.join("; ")) };
|
||||
return Err(EngineError::Other(format!("file.importMaterialX: nothing to import from {:?}{why}", material.name)));
|
||||
}
|
||||
|
||||
let layer_name = name.map(str::to_string).unwrap_or_else(|| self.doc.project.next_layer_name(ts, &material.name));
|
||||
let resource_names: Vec<String> = added.iter().map(|(n, _)| n.clone()).collect();
|
||||
let id = self.edit("Import MaterialX material", |s| {
|
||||
for (n, bytes) in &added {
|
||||
s.doc.resources.insert(n.clone(), bytes.clone());
|
||||
}
|
||||
s.doc.project.resource_sources.extend(sources);
|
||||
let id = s.doc.project.alloc_id();
|
||||
crate::layer_cmds::insert_selected(s, Layer::new(id, layer_name, LayerKind::Fill(fill), &channels))
|
||||
})?;
|
||||
@@ -119,34 +131,42 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !meta.is_file() || meta.len() > texturecraft_formats::materialx_read::MAX_BYTES as u64 {
|
||||
return Err(bad(cmd, format!("{path} is not a MaterialX file of a readable size")));
|
||||
}
|
||||
|
||||
let bytes = std::fs::read(path).map_err(|e| bad(cmd, format!("cannot read {path}: {e}")))?;
|
||||
let material = texturecraft_formats::materialx_read::read_materialx(&bytes, strp(p, "material")).map_err(|e| bad(cmd, format!("{path}: {e}")))?;
|
||||
let folder = Path::new(path).parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new("."));
|
||||
let dir = folder.canonicalize().map_err(|e| bad(cmd, format!("cannot read the folder of {path}: {e}")))?;
|
||||
let load = |file: &str| -> std::result::Result<Vec<u8>, String> {
|
||||
// `<UDIM>` stands for a tile number; the first tile is read.
|
||||
let load = |file: &str| -> std::result::Result<LocatedImage, String> {
|
||||
// Import the first tile of a UDIM image
|
||||
let file = file.replace("<UDIM>", "1001");
|
||||
let rel = Path::new(&file);
|
||||
let outside = "the file is outside the material's folder";
|
||||
if rel.is_absolute() || rel.components().any(|c| matches!(c, Component::ParentDir | Component::Prefix(_) | Component::RootDir)) {
|
||||
return Err(outside.into());
|
||||
}
|
||||
|
||||
let full = dir.join(rel).canonicalize().map_err(|e| e.to_string())?;
|
||||
if !full.starts_with(&dir) {
|
||||
return Err(outside.into());
|
||||
}
|
||||
|
||||
let meta = std::fs::metadata(&full).map_err(|e| e.to_string())?;
|
||||
// A pipe or device in the folder would block the read (a pipe reports no length).
|
||||
|
||||
// Avoid blocking on pipes and devices
|
||||
if !meta.is_file() {
|
||||
return Err("it is not a regular file".into());
|
||||
}
|
||||
|
||||
let len = meta.len();
|
||||
if len > crate::resource_cmds::MAX_BYTES as u64 {
|
||||
return Err(format!("the file is over {} MB", crate::resource_cmds::MAX_BYTES >> 20));
|
||||
}
|
||||
std::fs::read(&full).map_err(|e| e.to_string())
|
||||
|
||||
let source = full.to_str().map(crate::resource_update_cmds::file_source);
|
||||
let bytes = std::fs::read(&full).map_err(|e| e.to_string())?;
|
||||
Ok((bytes, source))
|
||||
};
|
||||
s.import_material(material, strp(p, "name"), &load)
|
||||
s.import_material_with_sources(material, strp(p, "name"), &load)
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
|
||||
Loaded 100 of 367 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user