mirror of
https://github.com/storytold/texturecraft.git
synced 2026-11-28 17:19:24 +01:00
Auto: Integrate main and fix rename validation and export naming
Preserve both branches’ engine tests. Validate the project name before applying other dialog settings, clear discarded text undo history, and keep an unsaved project’s autosave filename stable across renames. Expand export tokens once, preserve literal text in names, and sanitize flat stems directly. Reuse the dialog’s name buffer and update the command documentation and generated headless parity report.
This commit is contained in:
commit
4c1d486fc4
286 files changed
+21328
-3547
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": "f94a43818dabb2e85f2f4d5cd768bb8e5662600a",
|
||||
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@f94a43818dabb2e85f2f4d5cd768bb8e5662600a",
|
||||
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
|
||||
"signer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
|
||||
"signer_tooling_revision": "f94a43818dabb2e85f2f4d5cd768bb8e5662600a",
|
||||
"release_branch": "nightly-signer",
|
||||
"manual_actors": [
|
||||
"bflatastic",
|
||||
|
||||
@@ -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@f94a43818dabb2e85f2f4d5cd768bb8e5662600a
|
||||
with:
|
||||
ref: aced4137c022f1f587624d48e81ec77e1914a9cc
|
||||
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@605d58766e8f536564da8fc81d3676ac86816dea
|
||||
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@f94a43818dabb2e85f2f4d5cd768bb8e5662600a
|
||||
- id: rust
|
||||
uses: storytold/craft-common-actions/actions/rust-channel@605d58766e8f536564da8fc81d3676ac86816dea
|
||||
uses: storytold/craft-common-actions/actions/rust-channel@f94a43818dabb2e85f2f4d5cd768bb8e5662600a
|
||||
with:
|
||||
targets: aarch64-apple-darwin
|
||||
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
|
||||
|
||||
@@ -34,9 +34,9 @@ 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@f94a43818dabb2e85f2f4d5cd768bb8e5662600a
|
||||
with:
|
||||
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
|
||||
tooling-revision: f94a43818dabb2e85f2f4d5cd768bb8e5662600a
|
||||
app-name: texturecraft
|
||||
producer_run_id: ${{ inputs.producer_run_id }}
|
||||
producer_run_attempt: ${{ inputs.producer_run_attempt }}
|
||||
|
||||
@@ -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@f94a43818dabb2e85f2f4d5cd768bb8e5662600a
|
||||
with:
|
||||
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
|
||||
tooling-revision: f94a43818dabb2e85f2f4d5cd768bb8e5662600a
|
||||
app-name: texturecraft
|
||||
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
|
||||
craft-fonts-ref: aced4137c022f1f587624d48e81ec77e1914a9cc
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
name: Notify Services on Release Change
|
||||
|
||||
on:
|
||||
release:
|
||||
types:
|
||||
- published
|
||||
- unpublished
|
||||
- created
|
||||
- edited
|
||||
- deleted
|
||||
- prereleased
|
||||
- released
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
notify:
|
||||
uses: storytold/craft-common-actions/.github/workflows/notify-services.yml@main
|
||||
secrets:
|
||||
ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }}
|
||||
@@ -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,7 @@ 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 |
|
||||
|
||||
## Third-party assets compiled into the binary
|
||||
|
||||
@@ -52,6 +53,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
+158
-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",
|
||||
@@ -6005,6 +6139,7 @@ dependencies = [
|
||||
"texturecraft-bake",
|
||||
"texturecraft-compose",
|
||||
"texturecraft-core",
|
||||
"texturecraft-formats",
|
||||
"texturecraft-geom",
|
||||
"texturecraft-texel",
|
||||
"wasm-bindgen-futures",
|
||||
@@ -6381,7 +6516,7 @@ checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e"
|
||||
dependencies = [
|
||||
"memoffset",
|
||||
"tempfile",
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6516,6 +6651,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"
|
||||
@@ -7071,7 +7212,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]]
|
||||
@@ -7458,7 +7599,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]]
|
||||
@@ -7865,7 +8006,7 @@ dependencies = [
|
||||
"memchr",
|
||||
"nix",
|
||||
"typed-path",
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.61.2",
|
||||
"zeroize",
|
||||
"zopfli",
|
||||
]
|
||||
|
||||
+4
-1
@@ -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"] }
|
||||
|
||||
@@ -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,6 +12,16 @@ 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).
|
||||
|
||||
+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.
|
||||
#[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}");
|
||||
|
||||
@@ -202,10 +202,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}");
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -259,13 +261,22 @@ fn initialize_nightly_process_identity() -> Result<(), process_identity::Identit
|
||||
process_identity::initialize(build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1, os_window::id_for(LaunchIdentity::NightlyV1))
|
||||
}
|
||||
|
||||
/// A refused Nightly start explains itself in a dialog where there is a desktop to show one.
|
||||
/// Whether a refusal may also open a native message box. Standard error always carries the reason;
|
||||
/// this only adds a box where one renders without the app's event loop. Never on macOS: rfd's alert
|
||||
/// there needs the AppKit run loop this start has not reached, so a refused nightly launch hung in
|
||||
/// an invisible modal instead of exiting (GridCraft Mac smoke, 2026-11-26).
|
||||
fn refusal_dialog(flavor: build_flavor::BuildFlavor, desktop_session: bool, macos: bool) -> bool {
|
||||
build_flavor::needs_native_error(flavor, desktop_session) && !macos
|
||||
}
|
||||
|
||||
/// A refused Nightly start explains itself in a dialog where the desktop shows one without the
|
||||
/// app's run loop (Windows, X11/Wayland); macOS gets the standard-error line only.
|
||||
fn report_launch_profile_error(error: &str) {
|
||||
eprintln!("texturecraft: {error}");
|
||||
let desktop_session = cfg!(windows)
|
||||
|| cfg!(target_os = "macos")
|
||||
|| (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty())));
|
||||
if build_flavor::needs_native_error(build_flavor::COMPILED, desktop_session) {
|
||||
if refusal_dialog(build_flavor::COMPILED, desktop_session, cfg!(target_os = "macos")) {
|
||||
if let Err(error) = initialize_nightly_process_identity() {
|
||||
eprintln!("texturecraft: {error}");
|
||||
return;
|
||||
@@ -325,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<_>>())
|
||||
@@ -334,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,
|
||||
@@ -352,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);
|
||||
@@ -368,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")));
|
||||
@@ -384,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())
|
||||
@@ -394,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,
|
||||
@@ -415,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();
|
||||
@@ -441,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;
|
||||
@@ -461,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);
|
||||
@@ -667,3 +704,17 @@ mod tests {
|
||||
assert!(seen.is_some_and(|seen| seen.distance(pad + DRAG_STEP) <= PUT_BACK_REACH), "the app reads the whole move: {seen:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod refusal_dialog_tests {
|
||||
use super::refusal_dialog;
|
||||
use crate::build_flavor::BuildFlavor;
|
||||
|
||||
#[test]
|
||||
fn a_refusal_never_blocks_on_a_modal_before_the_event_loop_on_macos() {
|
||||
assert!(refusal_dialog(BuildFlavor::NightlyV1, true, false), "a desktop refusal still shows the box where one renders");
|
||||
assert!(!refusal_dialog(BuildFlavor::NightlyV1, true, true), "macOS has no run loop yet: the modal would hang");
|
||||
assert!(!refusal_dialog(BuildFlavor::NightlyV1, false, false), "a headless session has no box");
|
||||
assert!(!refusal_dialog(BuildFlavor::Stable, true, false), "only a nightly refusal explains itself in a box");
|
||||
}
|
||||
}
|
||||
@@ -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"] }
|
||||
@@ -225,9 +225,9 @@ impl Headless {
|
||||
|
||||
/// Export the working mesh to `path` (obj, glb, usda, usdc or usdz, from `format` or the
|
||||
/// extension); obj writes its .mtl and textures, usda and usdc their textures, next to it.
|
||||
pub fn export_mesh(&mut self, path: &str, format: Option<&str>) -> Result<Value, AutomationError> {
|
||||
pub fn export_mesh(&mut self, path: &str, format: Option<&str>, recompute_normals: bool) -> Result<Value, AutomationError> {
|
||||
self.require_project()?;
|
||||
let out = self.session.mesh_export(path, format)?;
|
||||
let out = self.session.mesh_export_with_normals(path, format, recompute_normals)?;
|
||||
let dir = Path::new(&out.path).parent().and_then(|d| d.to_str()).filter(|d| !d.is_empty()).unwrap_or(".");
|
||||
self.create_dir_all(dir)?;
|
||||
let mut textures = Vec::new();
|
||||
@@ -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 }))
|
||||
}
|
||||
|
||||
|
||||
@@ -4,8 +4,9 @@
|
||||
//!
|
||||
//! Methods: the app's `ping`, `command.run {id, params?}`, `command.list {filter?}`,
|
||||
//! `session.inspect`, plus `command.batch {steps}`, `project.open {path}`,
|
||||
//! `project.save {path?}`, `mesh.import {path, resolution?, name?}`, `mesh.reimport {path?,
|
||||
//! preserveStrokes?}`, `mesh.export {path, format?}`, `bake.mesh.add {path, cage?}`,
|
||||
//! `project.save {path?}`, `mesh.import {path, resolution?, name?}`,
|
||||
//! `mesh.reimport {path?, preserveStrokes?}`, `mesh.export {path, format?, recomputeNormals?}`,
|
||||
//! `bake.mesh.add {path, cage?}`,
|
||||
//! `resource.import {path}`, `material.save {path, layer?, name?}`, `material.load {path}`
|
||||
//! (workspace-scoped versions of the engine commands),
|
||||
//! `textures.export {dir, …}`, `render {view?, width?, height?, yaw?, pitch?}` (PNG base64, the
|
||||
@@ -88,13 +89,14 @@ 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")?),
|
||||
"project.save" => self.save(str_of(p, "path")),
|
||||
"mesh.import" => self.import_mesh(required(p, "path")?, u32_of(p, "resolution")?, str_of(p, "name")),
|
||||
"mesh.reimport" => self.reimport_mesh(str_of(p, "path"), bool_of(p, "preserveStrokes")?),
|
||||
"mesh.export" => self.export_mesh(required(p, "path")?, str_of(p, "format")),
|
||||
"mesh.export" => self.export_mesh(required(p, "path")?, str_of(p, "format"), bool_of(p, "recomputeNormals")?),
|
||||
"bake.mesh.add" => self.add_bake_mesh(required(p, "path")?, bool_of(p, "cage")?),
|
||||
"resource.import" => self.import_resource(required(p, "path")?),
|
||||
"material.save" => self.material_save(p),
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -141,6 +141,9 @@ pub struct MeshExportParams {
|
||||
/// written next to it) or usdz (textures packaged); default: from the extension, else obj.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub format: Option<String>,
|
||||
/// Replace stored normals with smooth area-weighted normals on the exported copy (default false).
|
||||
#[serde(default, rename = "recomputeNormals", skip_serializing_if = "Option::is_none")]
|
||||
pub recompute_normals: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
|
||||
@@ -174,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)]
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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))
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
+10
-5
@@ -39,6 +39,7 @@ 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 +52,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;
|
||||
@@ -80,11 +82,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;
|
||||
@@ -121,6 +124,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 +139,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;
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
@@ -4,7 +4,7 @@ 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, Layer, LayerId, LayerKind, Result};
|
||||
|
||||
pub use crate::env_alignment::EnvAlignment;
|
||||
pub use crate::shadow_mode::ShadowMode;
|
||||
@@ -69,6 +69,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);
|
||||
@@ -171,6 +177,8 @@ impl TextureSet {
|
||||
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,6 +195,19 @@ 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 {
|
||||
@@ -316,8 +337,10 @@ pub struct DisplaySettings {
|
||||
pub scatter_color: [f32; 3],
|
||||
/// Subsurface scattering mean free path as a fraction of the mesh's bounding radius.
|
||||
pub scatter_radius: f32,
|
||||
/// Index of refraction of transmissive surfaces (where the Transmission channel is painted).
|
||||
/// Index of refraction for transmission and, when enabled, dielectric reflectance.
|
||||
pub ior: f32,
|
||||
/// Use IOR to determine dielectric reflectance at normal incidence in Metallic/Roughness.
|
||||
pub ior_specular: bool,
|
||||
/// Depth of field of the viewport and the path tracer (thin lens).
|
||||
pub dof: DepthOfField,
|
||||
/// The selected fill's projection gizmos show in the 3D view (the Projection row's eye)
|
||||
@@ -381,11 +404,35 @@ pub const ENVIRONMENTS: [&str; 6] = ["Studio Soft", "Studio Contrast", "Overcast
|
||||
/// Prefix of [`DisplaySettings::environment`] naming an image resource.
|
||||
pub const ENV_RESOURCE_PREFIX: &str = "resource:";
|
||||
|
||||
/// Original dielectric F0 multiplier for the Specular Level channel.
|
||||
pub const LEGACY_DIELECTRIC_F0_SCALE: f32 = 0.08;
|
||||
|
||||
/// Project limits for the index of refraction.
|
||||
pub const MIN_INDEX_OF_REFRACTION: f32 = 1.0;
|
||||
pub const MAX_INDEX_OF_REFRACTION: f32 = 3.0;
|
||||
|
||||
impl DisplaySettings {
|
||||
/// The image resource used as the environment, if any.
|
||||
pub fn environment_resource(&self) -> Option<&str> {
|
||||
self.environment.strip_prefix(ENV_RESOURCE_PREFIX)
|
||||
}
|
||||
|
||||
/// Multiplier for Specular Level in the Metallic/Roughness model.
|
||||
pub fn dielectric_f0_scale(&self) -> f32 {
|
||||
if !self.ior_specular || self.spec_gloss || !self.ior.is_finite() {
|
||||
return LEGACY_DIELECTRIC_F0_SCALE;
|
||||
}
|
||||
|
||||
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);
|
||||
let contrast = ior - AIR_INDEX_OF_REFRACTION;
|
||||
let index_sum = ior + AIR_INDEX_OF_REFRACTION;
|
||||
|
||||
// Square before dividing so IOR 1.5 rounds to the legacy multiplier
|
||||
SPECULAR_LEVEL_TO_WEIGHT_SCALE * contrast.powi(2) / index_sum.powi(2)
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for DisplaySettings {
|
||||
@@ -416,6 +463,7 @@ impl Default for DisplaySettings {
|
||||
scatter_color: [1.0, 0.4, 0.25],
|
||||
scatter_radius: 0.1,
|
||||
ior: 1.5,
|
||||
ior_specular: false,
|
||||
dof: DepthOfField::default(),
|
||||
projection_gizmos: true,
|
||||
}
|
||||
@@ -452,6 +500,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 {
|
||||
@@ -470,6 +522,7 @@ impl Project {
|
||||
display: DisplaySettings::default(),
|
||||
cameras: Vec::new(),
|
||||
swatches: Vec::new(),
|
||||
resource_sources: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -817,6 +870,28 @@ mod tests {
|
||||
p
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enabling_ior_at_the_default_preserves_legacy_reflectance() {
|
||||
let mut display = DisplaySettings::default();
|
||||
let legacy = display.dielectric_f0_scale();
|
||||
|
||||
display.ior_specular = true;
|
||||
|
||||
assert_eq!(display.dielectric_f0_scale(), legacy);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dielectric_reflectance_clamps_ior_and_falls_back_for_non_finite_values() {
|
||||
let scale_at = |ior| DisplaySettings { ior, ior_specular: true, ..DisplaySettings::default() }.dielectric_f0_scale();
|
||||
|
||||
assert_eq!(scale_at(0.5), scale_at(1.0));
|
||||
assert_eq!(scale_at(1.0), 0.0);
|
||||
assert!(scale_at(1.5) < scale_at(3.0));
|
||||
assert_eq!(scale_at(4.0), scale_at(3.0));
|
||||
assert_eq!(scale_at(f32::NAN), LEGACY_DIELECTRIC_F0_SCALE);
|
||||
assert_eq!(scale_at(f32::INFINITY), LEGACY_DIELECTRIC_F0_SCALE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sync_takes_settings_from_a_staying_member_else_the_active_set_else_the_first() {
|
||||
let group = BakeSyncGroup::Common;
|
||||
|
||||
@@ -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,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)
|
||||
}
|
||||
|
||||
@@ -395,20 +419,6 @@ impl Session {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn saved_bake_paint(&self) -> BTreeMap<(usize, BakePaintTarget), texturecraft_formats::BakePaintData> {
|
||||
self.doc
|
||||
.bake_paint
|
||||
.iter()
|
||||
.map(|(key, map)| (*key, texturecraft_formats::BakePaintData { width: map.width, height: map.height, values: map.values.clone() }))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The bake meshes for a project file: (high polys, cage)
|
||||
pub(crate) fn saved_bake_meshes(&self) -> (Vec<MeshFile>, Option<MeshFile>) {
|
||||
let entry = |mesh: &BakeMesh| (mesh.name.clone(), mesh.bytes.as_ref().clone());
|
||||
(self.doc.bake_meshes.high.iter().map(entry).collect(), self.doc.bake_meshes.cage.as_ref().map(entry))
|
||||
}
|
||||
}
|
||||
|
||||
/// `bake.highPoly.list`: the high polys and the cage (also part of `project.inspect`).
|
||||
@@ -857,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)
|
||||
})?;
|
||||
@@ -877,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");
|
||||
}
|
||||
}
|
||||
|
||||
+389
-116
@@ -13,14 +13,39 @@ 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) {
|
||||
let project = &mut archive.project;
|
||||
project.format_version = project.save_format_version();
|
||||
|
||||
// Drop pixel images whose size no longer matches their texture set
|
||||
let size_of = |id: texturecraft_core::LayerId| {
|
||||
project.locate(id).and_then(|(ts, _, _)| project.texture_sets.get(ts)).map(TextureSet::size).or_else(|| {
|
||||
project.effect(id).and_then(|(owner, _)| project.locate(owner)).and_then(|(ts, _, _)| project.texture_sets.get(ts)).map(TextureSet::size)
|
||||
})
|
||||
};
|
||||
archive.pixels.layers.retain(|(id, _), img| size_of(*id) == Some((img.width(), img.height())));
|
||||
archive.pixels.masks.retain(|id, img| size_of(*id) == Some((img.width(), img.height())));
|
||||
|
||||
archive.mesh_uvs = uv_source.map(texturecraft_formats::mesh_import::corner_uvs);
|
||||
archive.bake_paint = bake_paint
|
||||
.iter()
|
||||
.map(|(key, map)| (*key, texturecraft_formats::BakePaintData { width: map.width, height: map.height, values: map.values.clone() }))
|
||||
.collect();
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
@@ -60,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
|
||||
),
|
||||
@@ -69,7 +94,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export Mesh...",
|
||||
["File"],
|
||||
None,
|
||||
"{path: .obj, .glb, .usda, .usdc or .usdz file, format?: obj|glb|usda|usdc|usdz (default: from the extension, else obj); obj writes its .mtl and textures, usda/usdc their textures, next to the file} → {path, textures?}",
|
||||
"{path: .obj, .glb, .usda, .usdc or .usdz file, format?: obj|glb|usda|usdc|usdz (default: from the extension, else obj), recomputeNormals?: bool (default false: smooth area-weighted normals replace the stored normals on the exported copy only); obj writes its .mtl and textures, usda/usdc their textures, next to the file} → {path, textures?}",
|
||||
always,
|
||||
export_mesh
|
||||
),
|
||||
@@ -78,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, sourceSize, 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
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -115,19 +149,38 @@ fn read_stored_mesh(project: &Project, ext: &str, bytes: &[u8], saved_layout: Op
|
||||
impl Session {
|
||||
/// The working mesh as Wavefront OBJ (with its own UVs, UDIM tiles included).
|
||||
pub fn mesh_obj_bytes(&self) -> Result<Vec<u8>> {
|
||||
texturecraft_formats::obj_bytes(&self.source_mesh(), &self.doc.project.name).map_err(fe)
|
||||
self.mesh_obj_bytes_with_normals(false)
|
||||
}
|
||||
|
||||
/// [`Session::mesh_obj_bytes`], optionally replacing normals on the exported copy only.
|
||||
pub fn mesh_obj_bytes_with_normals(&self, recompute_normals: bool) -> Result<Vec<u8>> {
|
||||
let mut mesh = self.source_mesh();
|
||||
if recompute_normals {
|
||||
mesh.compute_smooth_normals();
|
||||
}
|
||||
texturecraft_formats::obj_bytes(&mesh, &self.doc.project.name).map_err(fe)
|
||||
}
|
||||
|
||||
/// [`Session::mesh_obj_bytes`] with an MTL material library and each material's maps (like
|
||||
/// [`Session::mesh_usd`]'s), to write next to it, named after `stem` (the OBJ file's).
|
||||
pub fn mesh_obj_with_mtl(&mut self, stem: &str) -> 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.
|
||||
self.mesh_obj_with_mtl_and_normals(stem, false)
|
||||
}
|
||||
|
||||
/// [`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)> {
|
||||
// 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();
|
||||
// A mesh without materials has one implicit material (and texture set).
|
||||
if recompute_normals {
|
||||
mesh.compute_smooth_normals();
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
@@ -136,16 +189,36 @@ impl Session {
|
||||
/// composite, through the texture export pipeline) embedded. glTF has no UV tiles: a
|
||||
/// UV-tiled set embeds its tile atlas, with the mesh's UVs in atlas space.
|
||||
pub fn mesh_glb_bytes(&mut self) -> Result<Vec<u8>> {
|
||||
self.mesh_glb_bytes_with_normals(false)
|
||||
}
|
||||
|
||||
/// [`Session::mesh_glb_bytes`], optionally replacing normals on the exported copy only.
|
||||
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();
|
||||
texturecraft_formats::glb_bytes(&self.mesh, &self.doc.project.name, &textures).map_err(fe)
|
||||
let mut mesh = Cow::Borrowed(self.mesh.as_ref());
|
||||
if recompute_normals {
|
||||
mesh.to_mut().compute_smooth_normals();
|
||||
}
|
||||
|
||||
texturecraft_formats::glb_bytes(&mesh, &self.doc.project.name, &textures).map_err(fe)
|
||||
}
|
||||
|
||||
/// The working mesh as USD with a UsdPreviewSurface per material (textures like
|
||||
/// [`Session::mesh_glb_bytes`]): usdz packages them, usda / usdc list them to write alongside.
|
||||
pub fn mesh_usd(&mut self, format: texturecraft_formats::UsdFormat) -> Result<texturecraft_formats::UsdExport> {
|
||||
self.mesh_usd_with_normals(format, false)
|
||||
}
|
||||
|
||||
/// [`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())?;
|
||||
texturecraft_formats::usd_bytes(&self.mesh, &self.doc.project.name, &files, format).map_err(fe)
|
||||
let mut mesh = Cow::Borrowed(self.mesh.as_ref());
|
||||
if recompute_normals {
|
||||
mesh.to_mut().compute_smooth_normals();
|
||||
}
|
||||
|
||||
texturecraft_formats::usd_bytes(&mesh, &self.doc.project.name, &files, format).map_err(fe)
|
||||
}
|
||||
|
||||
/// The texture sets of the first `materials` materials rendered with `opts` (as a tile atlas
|
||||
@@ -184,7 +257,7 @@ impl Session {
|
||||
// Packed mesh files can have spare capacity that the project would otherwise retain
|
||||
let mut source = bytes.into_owned();
|
||||
source.shrink_to_fit();
|
||||
session.mesh_source = Some((extension, source));
|
||||
session.mesh_source = Some((extension, Arc::new(source)));
|
||||
session.doc.project.mesh_file = leaf_of(file_name);
|
||||
session.doc.project.mesh_rebuild_uvs = rebuild_uvs;
|
||||
session.doc.project.cameras = imported.cameras;
|
||||
@@ -232,6 +305,7 @@ impl Session {
|
||||
pixels: project_file.pixels,
|
||||
baked: project_file.baked,
|
||||
resources,
|
||||
painted_regions: Default::default(),
|
||||
},
|
||||
mesh,
|
||||
project_file.mesh,
|
||||
@@ -245,109 +319,163 @@ impl Session {
|
||||
Ok(session)
|
||||
}
|
||||
|
||||
/// The project with independently owned resource bytes.
|
||||
pub fn project_file(&self) -> ProjectFile {
|
||||
let resources = self.doc.resources.iter().map(|(name, bytes)| (name.clone(), bytes.as_ref().clone())).collect();
|
||||
self.project_with_resources(resources)
|
||||
}
|
||||
|
||||
/// A save snapshot that shares immutable resource payloads with the document.
|
||||
pub fn project_snapshot(&self) -> ProjectFile<Arc<Vec<u8>>> {
|
||||
self.project_with_resources(self.doc.resources.clone())
|
||||
}
|
||||
|
||||
/// The layout a project with rebuilt mesh UVs saves, so reopening it never runs the unwrapper.
|
||||
fn saved_uv_layout(&self) -> Option<Vec<Vec2>> {
|
||||
(self.doc.project.mesh_rebuild_uvs && self.mesh_source.is_some()).then(|| texturecraft_formats::mesh_import::corner_uvs(&self.source))
|
||||
}
|
||||
|
||||
fn project_with_resources<Resource>(&self, resources: BTreeMap<String, Resource>) -> ProjectFile<Resource> {
|
||||
let mut pixels = self.doc.pixels.clone();
|
||||
|
||||
// Drop pixel images whose size no longer matches their texture set
|
||||
let size_of = |id: texturecraft_core::LayerId| {
|
||||
self.doc.project.locate(id).and_then(|(ts, _, _)| self.doc.project.texture_sets.get(ts)).map(TextureSet::size).or_else(|| {
|
||||
self.doc
|
||||
.project
|
||||
.effect(id)
|
||||
.and_then(|(owner, _)| self.doc.project.locate(owner))
|
||||
.and_then(|(ts, _, _)| self.doc.project.texture_sets.get(ts))
|
||||
.map(TextureSet::size)
|
||||
})
|
||||
};
|
||||
pixels.layers.retain(|(id, _), img| size_of(*id) == Some((img.width(), img.height())));
|
||||
pixels.masks.retain(|id, img| size_of(*id) == Some((img.width(), img.height())));
|
||||
|
||||
let (high_poly, cage) = self.saved_bake_meshes();
|
||||
let mut project = self.doc.project.clone();
|
||||
project.format_version = project.save_format_version();
|
||||
|
||||
/// Capture just the archive inputs. The caller prepares derived data before writing.
|
||||
fn capture_archive<Bytes>(&self, resources: BTreeMap<String, Bytes>, store_mesh_bytes: impl Fn(&Arc<Vec<u8>>) -> Bytes) -> ProjectFile<Bytes, Bytes> {
|
||||
let bake_mesh = |mesh: &crate::BakeMesh| (mesh.name.clone(), store_mesh_bytes(&mesh.bytes));
|
||||
ProjectFile {
|
||||
project,
|
||||
pixels,
|
||||
project: self.doc.project.clone(),
|
||||
pixels: self.doc.pixels.clone(),
|
||||
baked: self.doc.baked.clone(),
|
||||
mesh: self.mesh_source.clone(),
|
||||
mesh_uvs: self.saved_uv_layout(),
|
||||
high_poly,
|
||||
cage,
|
||||
bake_paint: self.saved_bake_paint(),
|
||||
mesh: self.mesh_source.as_ref().map(|(extension, bytes)| (extension.clone(), store_mesh_bytes(bytes))),
|
||||
mesh_uvs: None,
|
||||
high_poly: self.doc.bake_meshes.high.iter().map(bake_mesh).collect(),
|
||||
cage: self.doc.bake_meshes.cage.as_ref().map(bake_mesh),
|
||||
bake_paint: BTreeMap::new(),
|
||||
thumbnail: None,
|
||||
resources,
|
||||
warnings: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The project with independently owned resource and mesh bytes.
|
||||
pub fn project_file(&self) -> ProjectFile {
|
||||
let resources = self.doc.resources.iter().map(|(name, bytes)| (name.clone(), bytes.as_ref().clone())).collect();
|
||||
let mut archive = self.capture_archive(resources, |bytes| bytes.as_ref().clone());
|
||||
prepare_archive(&mut archive, self.saved_uv_source().map(Arc::as_ref), &self.doc.bake_paint);
|
||||
archive
|
||||
}
|
||||
|
||||
/// A save snapshot that shares immutable resource and mesh payloads with the document.
|
||||
pub fn project_snapshot(&self) -> ProjectFile<Arc<Vec<u8>>, Arc<Vec<u8>>> {
|
||||
let mut archive = self.capture_archive(self.doc.resources.clone(), Arc::clone);
|
||||
prepare_archive(&mut archive, self.saved_uv_source().map(Arc::as_ref), &self.doc.bake_paint);
|
||||
archive
|
||||
}
|
||||
|
||||
/// The imported geometry needed to save rebuilt corner UVs and skip unwrapping on reopen.
|
||||
fn saved_uv_source(&self) -> Option<&Arc<Mesh>> {
|
||||
(self.doc.project.mesh_rebuild_uvs && self.mesh_source.is_some()).then_some(&self.source)
|
||||
}
|
||||
|
||||
pub fn to_project_bytes(&self) -> Result<Vec<u8>> {
|
||||
let mut reservation = texturecraft_formats::RamReservation::for_save().map_err(fe)?;
|
||||
reservation.save_bytes(&self.project_snapshot()).map_err(fe)
|
||||
}
|
||||
|
||||
/// 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,
|
||||
|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,
|
||||
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 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,
|
||||
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,
|
||||
|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<()> {
|
||||
@@ -409,12 +537,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")))?;
|
||||
@@ -433,6 +561,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);
|
||||
}
|
||||
@@ -462,6 +594,22 @@ 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};
|
||||
|
||||
@@ -479,18 +627,23 @@ fn plan(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
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);
|
||||
|
||||
// A map's own size wins over the export's; a PSD is the size of its largest layer
|
||||
let size = output.maps().map(|map| scale_export_side(source_size, block_size, options.map_size(map))).max().unwrap_or(source_size);
|
||||
|
||||
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,
|
||||
"warnings": output.warnings,
|
||||
"layers": output.layers.iter().map(|layer| json!({ "map": layer.map, "name": layer.name })).collect::<Vec<_>>(),
|
||||
}));
|
||||
}
|
||||
}
|
||||
@@ -537,21 +690,22 @@ mod native {
|
||||
}
|
||||
|
||||
pub fn save_to(s: &mut Session, path: &str, adopt: bool) -> Result<Value> {
|
||||
let path = if ext_of(path) == PROJECT_EXT { path.to_string() } else { format!("{path}.{PROJECT_EXT}") };
|
||||
let mut reservation = texturecraft_formats::RamReservation::for_save().map_err(fe)?;
|
||||
reservation.save(Path::new(&path), &s.project_snapshot()).map_err(fe)?;
|
||||
|
||||
if adopt {
|
||||
s.path = Some(path.clone());
|
||||
s.modified = false;
|
||||
}
|
||||
s.log.info("Project", format!("Saved {path}"));
|
||||
Ok(json!({ "path": path }))
|
||||
let output = s.save_task(path, adopt).run(None)?;
|
||||
output.apply(s);
|
||||
Ok(json!({ "path": output.path }))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub use native::{absolute, open_path, read_mesh};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod save_output;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod save_target;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod save_task;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub use {save_output::SaveOutput, save_task::SaveTask};
|
||||
|
||||
/// `file.new {mesh, name?, resolution?, uvTiles?, rebuildUvs?, template?, importCameras?}`: a new project from the
|
||||
/// mesh file `mesh`, remembering its path for Reimport mesh.
|
||||
@@ -661,7 +815,7 @@ impl Session {
|
||||
}
|
||||
None => match &self.mesh_source {
|
||||
Some((ext, bytes)) => {
|
||||
let layout = self.saved_uv_layout();
|
||||
let layout = self.saved_uv_source().map(|source| texturecraft_formats::mesh_import::corner_uvs(source));
|
||||
let mesh = read_stored_mesh(&self.doc.project, ext, bytes, layout.as_deref())?;
|
||||
(mesh, None, Vec::new(), self.doc.project.mesh_file.clone())
|
||||
}
|
||||
@@ -671,7 +825,8 @@ impl Session {
|
||||
|
||||
check_materials(&self.doc.project, &mesh)?;
|
||||
let mut doc = self.doc.clone();
|
||||
if let Some((ext, _)) = replacement_source.as_ref().or(self.mesh_source.as_ref()) {
|
||||
let extension = replacement_source.as_ref().map(|(extension, _)| extension).or_else(|| self.mesh_source.as_ref().map(|(extension, _)| extension));
|
||||
if let Some(ext) = extension {
|
||||
doc.project.mesh = format!("mesh.{ext}");
|
||||
doc.project.mesh_file = mesh_file;
|
||||
doc.project.mesh_rebuild_uvs = rebuild_uvs;
|
||||
@@ -695,6 +850,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
|
||||
@@ -703,6 +862,7 @@ impl Session {
|
||||
}
|
||||
|
||||
self.switch_to(next);
|
||||
|
||||
Ok(preserved.map_or(Value::Null, |n| json!({ "preserved": n })))
|
||||
}
|
||||
}
|
||||
@@ -716,6 +876,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();
|
||||
|
||||
@@ -775,6 +936,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 });
|
||||
@@ -816,7 +993,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}"));
|
||||
@@ -826,7 +1003,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:"));
|
||||
@@ -847,6 +1024,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));
|
||||
}
|
||||
}
|
||||
@@ -893,8 +1079,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
|
||||
@@ -902,12 +1100,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",
|
||||
@@ -984,11 +1176,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);
|
||||
@@ -1159,7 +1351,7 @@ fn write_materialx(
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn export_mesh(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = native::path_param(p, "path", "file.exportMesh")?;
|
||||
let out = s.mesh_export(path, strp(p, "format"))?;
|
||||
let out = s.mesh_export_with_normals(path, strp(p, "format"), crate::commands::boolp(p, "recomputeNormals").unwrap_or(false))?;
|
||||
let dir = std::path::Path::new(&out.path).parent().unwrap_or(std::path::Path::new(""));
|
||||
let texture_paths: Vec<std::path::PathBuf> = out.textures.iter().map(|(name, _)| dir.join(name)).collect();
|
||||
let main_path = std::path::PathBuf::from(&out.path);
|
||||
@@ -1196,6 +1388,12 @@ impl Session {
|
||||
/// The working mesh as a file for `path`, in `format` (obj, glb, usda, usdc, usdz; default:
|
||||
/// from the extension, else OBJ). The extension is appended when it doesn't match.
|
||||
pub fn mesh_export(&mut self, path: &str, format: Option<&str>) -> Result<MeshExport> {
|
||||
self.mesh_export_with_normals(path, format, false)
|
||||
}
|
||||
|
||||
/// [`Session::mesh_export`], optionally computing smooth area-weighted normals on the
|
||||
/// exported copy. The project's source and render meshes are never changed.
|
||||
pub fn mesh_export_with_normals(&mut self, path: &str, format: Option<&str>, recompute_normals: bool) -> Result<MeshExport> {
|
||||
let ext = match format {
|
||||
Some(f) if MESH_EXPORT_FORMATS.contains(&f) => f.to_string(),
|
||||
Some(other) => return Err(bad("file.exportMesh", format!("unknown mesh format `{other}` ({})", MESH_EXPORT_FORMATS.join(", ")))),
|
||||
@@ -1203,14 +1401,16 @@ 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()?, Vec::new()),
|
||||
("glb", _) => (self.mesh_glb_bytes_with_normals(recompute_normals)?, Vec::new()),
|
||||
(_, Some(format)) => {
|
||||
let usd = self.mesh_usd(format)?;
|
||||
let usd = self.mesh_usd_with_normals(format, recompute_normals)?;
|
||||
(usd.bytes, usd.textures)
|
||||
}
|
||||
_ => self.mesh_obj_with_mtl(std::path::Path::new(&path).file_stem().and_then(|s| s.to_str()).unwrap_or("mesh"))?,
|
||||
_ => 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 })
|
||||
}
|
||||
}
|
||||
@@ -1402,6 +1602,72 @@ f 1/1 2/2 3/3
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mesh_export_can_recompute_normals_without_changing_the_project() {
|
||||
let mut s = Session::new_project("t", primitives::cube(1.0), "builtin:cube", None, 128).unwrap();
|
||||
std::sync::Arc::make_mut(&mut s.source).normals.fill(texturecraft_geom::glam::Vec3::Y);
|
||||
std::sync::Arc::make_mut(&mut s.mesh).normals.fill(texturecraft_geom::glam::Vec3::Y);
|
||||
let mut expected = s.source_mesh();
|
||||
expected.compute_smooth_normals();
|
||||
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
|
||||
.positions
|
||||
.iter()
|
||||
.zip(&expected.normals)
|
||||
.find_map(|(expected_position, normal)| ((*expected_position - *position).length() < 1e-4).then_some(*normal))
|
||||
.unwrap_or_else(|| panic!("{format}: exported position {position:?} is missing from the source"));
|
||||
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();
|
||||
let stored = texturecraft_formats::import_mesh_bytes("stored.obj", &stored).unwrap().mesh;
|
||||
assert!(stored.normals.iter().all(|n| *n == texturecraft_geom::glam::Vec3::Y), "the default keeps stored normals for compatibility");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recomputed_normals_weld_uv_seams_in_exported_mesh() {
|
||||
use texturecraft_geom::glam::Vec3;
|
||||
|
||||
// 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,
|
||||
Some(vec![Vec3::Y; 6]),
|
||||
vec![Vec2::new(0.0, 0.0), Vec2::new(0.5, 0.5), Vec2::new(0.0, 1.0), Vec2::new(1.0, 0.0), Vec2::new(1.0, 1.0), Vec2::new(0.5, 1.0)],
|
||||
vec![0, 1, 2, 3, 4, 5],
|
||||
"Default",
|
||||
)
|
||||
.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");
|
||||
assert!(normals.windows(2).all(|pair| (pair[0] - pair[1]).length() < 1e-5), "{point:?}: UV split normals disagree: {normals:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejected_glb_export_preserves_existing_files_and_publishes_nothing() {
|
||||
let mut s = Session::new_project("t", primitives::cube(1.0), "builtin:cube", None, 128).unwrap();
|
||||
@@ -1540,11 +1806,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()));
|
||||
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
use crate::session::Session;
|
||||
|
||||
/// An archive that was written successfully. Only the same project can adopt its path.
|
||||
pub struct SaveOutput {
|
||||
pub path: String,
|
||||
pub(super) project_id: u64,
|
||||
pub(super) saved_revision: Option<u64>,
|
||||
pub(super) adopt: bool,
|
||||
}
|
||||
|
||||
impl SaveOutput {
|
||||
/// Apply the saved path without clearing edits made since the snapshot.
|
||||
pub fn apply(&self, session: &mut Session) {
|
||||
if session.project_id != self.project_id {
|
||||
return;
|
||||
}
|
||||
|
||||
if self.adopt {
|
||||
session.path = Some(self.path.clone());
|
||||
|
||||
// A stroke started after capture changes the revision only when committed
|
||||
if self.saved_revision == Some(session.save_revision) {
|
||||
session.modified = false;
|
||||
}
|
||||
}
|
||||
|
||||
session.log.info("Project", format!("Saved {}", self.path));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
pub(super) struct SaveTarget {
|
||||
pub(super) project_id: u64,
|
||||
pub(super) saved_revision: Option<u64>,
|
||||
pub(super) adopt: bool,
|
||||
pub(super) path: String,
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
|
||||
use texturecraft_core::PROJECT_EXT;
|
||||
use texturecraft_formats::{ProjectFile, project_file::SaveProgress};
|
||||
use texturecraft_geom::Mesh;
|
||||
|
||||
use super::{BakePaintMaps, SaveOutput, ext_of, fe, prepare_archive, save_target::SaveTarget};
|
||||
use crate::Result;
|
||||
use crate::session::Session;
|
||||
|
||||
/// A manual save of the document at the moment it was requested. Large payloads are shared
|
||||
/// until the worker assembles the archive.
|
||||
pub struct SaveTask {
|
||||
target: SaveTarget,
|
||||
archive: ProjectFile<Arc<Vec<u8>>, Arc<Vec<u8>>>,
|
||||
bake_paint: BakePaintMaps,
|
||||
uv_source: Option<Arc<Mesh>>,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
pub fn save_task(&self, path: &str, adopt: bool) -> SaveTask {
|
||||
let path = if ext_of(path) == PROJECT_EXT { path.to_string() } else { format!("{path}.{PROJECT_EXT}") };
|
||||
let saved_revision = (!self.stroke_active()).then_some(self.save_revision);
|
||||
|
||||
SaveTask {
|
||||
target: SaveTarget { project_id: self.project_id, saved_revision, adopt, path },
|
||||
archive: self.capture_archive(self.doc.resources.clone(), Arc::clone),
|
||||
bake_paint: self.doc.bake_paint.clone(),
|
||||
uv_source: self.saved_uv_source().cloned(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl SaveTask {
|
||||
/// Complete the atomic write on the worker. Waiting for a previous save to release the
|
||||
/// RAM allowance also happens here.
|
||||
pub fn run(mut self, progress: Option<&SaveProgress>) -> Result<SaveOutput> {
|
||||
let mut reservation = texturecraft_formats::RamReservation::for_save().map_err(fe)?;
|
||||
prepare_archive(&mut self.archive, self.uv_source.as_deref(), &self.bake_paint);
|
||||
drop(self.uv_source);
|
||||
drop(self.bake_paint);
|
||||
|
||||
let path = Path::new(&self.target.path);
|
||||
match progress {
|
||||
Some(progress) => reservation.save_with_progress(path, &self.archive, progress),
|
||||
None => reservation.save(path, &self.archive),
|
||||
}
|
||||
.map_err(fe)?;
|
||||
|
||||
Ok(SaveOutput { path: self.target.path, project_id: self.target.project_id, saved_revision: self.target.saved_revision, adopt: self.target.adopt })
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
//! without a screenshot.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_core::{Effect, EffectKind, Fill, Filter, Generator, Layer, LayerKind, NormalFormat, Projection, Sampling, Source};
|
||||
use texturecraft_core::{Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, Layer, LayerKind, NormalFormat, Projection, Sampling, Source};
|
||||
|
||||
use crate::Session;
|
||||
use crate::session::StackTarget;
|
||||
@@ -162,6 +162,9 @@ fn generator_json(generator: &Generator) -> Value {
|
||||
if let Some(light) = &generator.light {
|
||||
out["light"] = json!(light);
|
||||
}
|
||||
if generator.on_earlier_model() && matches!(generator.kind, GeneratorKind::Position | GeneratorKind::Direction) {
|
||||
out["direction"] = json!(generator.direction);
|
||||
}
|
||||
if let Some(texture) = &generator.texture {
|
||||
out["texture"] = json!(texture);
|
||||
}
|
||||
@@ -261,6 +264,10 @@ 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,
|
||||
@@ -273,6 +280,8 @@ pub fn texture_set(session: &Session, index: usize) -> Value {
|
||||
"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,
|
||||
"active": index == session.ts(),
|
||||
})
|
||||
|
||||
@@ -324,8 +324,8 @@ fn select(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
Some(Value::String(t)) if t == "content" => StackTarget::Content,
|
||||
Some(v) => match v.as_u64() {
|
||||
Some(e) if s.doc.project.effect(LayerId(e)).is_some_and(|(owner, _)| owner == id) => StackTarget::Effect(LayerId(e)),
|
||||
_ => return Err(bad("layer.select", "target must be content, mask or an effect id of this layer")),
|
||||
Some(effect) if selectable_effect(&s.doc.project, id, LayerId(effect)) => StackTarget::Effect(LayerId(effect)),
|
||||
_ => return Err(bad("layer.select", "target must be content, mask or an effect id of this layer or of the mask it draws with")),
|
||||
},
|
||||
None => StackTarget::Content,
|
||||
};
|
||||
@@ -334,6 +334,15 @@ fn select(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "layer": id.0, "textureSet": ts, "layers": [id.0] }))
|
||||
}
|
||||
|
||||
/// Whether the effect belongs to the layer or to the mask it draws with.
|
||||
fn selectable_effect(project: &Project, layer: LayerId, effect_id: LayerId) -> bool {
|
||||
let Some((owner, _)) = project.effect(effect_id) else { return false };
|
||||
|
||||
owner == layer
|
||||
|| (owner == project.mask_owner(layer)
|
||||
&& project.layers.get(&owner).and_then(|layer| layer.mask.as_ref()).is_some_and(|mask| mask.effects.iter().any(|effect| effect.id == effect_id)))
|
||||
}
|
||||
|
||||
fn rename(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = layer_param(s, "layer.rename", p)?;
|
||||
let name = strp(p, "name").map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad("layer.rename", "`name` is required"))?.to_string();
|
||||
|
||||
@@ -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),
|
||||
}
|
||||
|
||||
@@ -344,6 +344,68 @@ pub fn open_in_materialcraft(package: &std::path::Path) -> Result<()> {
|
||||
})
|
||||
}
|
||||
|
||||
/// 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 +685,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 +774,82 @@ mod tests {
|
||||
assert_eq!(typed(&p, &json!("#+f+f+f")), None);
|
||||
assert!(typed(&p, &json!("#ff8000")).is_some());
|
||||
}
|
||||
|
||||
#[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();
|
||||
}
|
||||
}
|
||||
@@ -70,6 +70,7 @@ pub(crate) fn one_set_document(src_set: &TextureSet, name: &str) -> Document {
|
||||
set.tile_resolutions = src_set.tile_resolutions.clone();
|
||||
set.channels = src_set.channels.clone();
|
||||
project.texture_sets.push(set);
|
||||
|
||||
Document {
|
||||
bake_meshes: Default::default(),
|
||||
bake_paint: BTreeMap::new(),
|
||||
@@ -77,6 +78,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(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -99,7 +101,7 @@ impl Session {
|
||||
images_used(&mini.project, root, &mut used, 0);
|
||||
let resources = used.into_iter().filter_map(|name| self.doc.resources.get(&name).map(|bytes| (name, Arc::clone(bytes)))).collect();
|
||||
|
||||
let snapshot = texturecraft_formats::ProjectFile {
|
||||
let snapshot = texturecraft_formats::ProjectFile::<Arc<Vec<u8>>> {
|
||||
project: mini.project,
|
||||
pixels: mini.pixels,
|
||||
baked: BTreeMap::new(),
|
||||
@@ -145,6 +147,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")]
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
//! Sample image resources into a mesh-map atlas or compare them with an existing atlas.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use rayon::prelude::*;
|
||||
use texturecraft_compose::ImageRes;
|
||||
use texturecraft_core::{BakedMap, NormalFormat, TileGrid, udim_at};
|
||||
|
||||
use crate::commands::bad;
|
||||
use crate::{Result, Session};
|
||||
|
||||
pub(crate) struct MeshMapSampler<'a> {
|
||||
width: u32,
|
||||
height: u32,
|
||||
components: usize,
|
||||
flip_green: bool,
|
||||
grid: Option<TileGrid>,
|
||||
first: &'a ImageRes,
|
||||
images: &'a BTreeMap<u32, Arc<ImageRes>>,
|
||||
}
|
||||
|
||||
impl<'a> MeshMapSampler<'a> {
|
||||
pub(crate) fn new(session: &Session, cmd: &str, texture_set: usize, map: BakedMap, images: &'a BTreeMap<u32, Arc<ImageRes>>) -> Result<Self> {
|
||||
let set = session.doc.project.texture_set(texture_set)?;
|
||||
let grid = set.tile_grid();
|
||||
if let Some(tile) = set.uv_tiles.iter().find(|tile| grid.is_some() && !images.contains_key(tile)) {
|
||||
return Err(bad(cmd, format!("no image for UV tile {tile}")));
|
||||
}
|
||||
|
||||
let (width, height) = crate::meshmap_cmds::image_map_size(session, cmd, texture_set)?;
|
||||
let first = images.values().next().ok_or_else(|| bad(cmd, "no image to use"))?;
|
||||
|
||||
// Both tangent-space normal maps follow the project's green-channel convention
|
||||
let flip_green = matches!(map, BakedMap::Normal | BakedMap::BentNormal) && session.doc.project.normal_format == NormalFormat::DirectX;
|
||||
Ok(Self { width, height, components: map.components(), flip_green, grid, first, images })
|
||||
}
|
||||
|
||||
fn row(&self, y: usize) -> impl Iterator<Item = [f32; 4]> + '_ {
|
||||
let v = (y as f32 + 0.5) / self.height as f32;
|
||||
(0..self.width).map(move |x| {
|
||||
let u = (x as f32 + 0.5) / self.width as f32;
|
||||
let mut pixel = match self.grid {
|
||||
None => self.first.sample(u, v),
|
||||
Some(grid) => {
|
||||
let uv = grid.from_atlas([u, v]);
|
||||
udim_at(uv).and_then(|tile| self.images.get(&tile)).map_or([0.0; 4], |image| image.sample(uv[0] - uv[0].floor(), uv[1] - uv[1].floor()))
|
||||
}
|
||||
};
|
||||
if self.flip_green {
|
||||
pixel[1] = 1.0 - pixel[1];
|
||||
}
|
||||
|
||||
pixel
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn matches(&self, current: &[f32]) -> bool {
|
||||
let row_len = self.width as usize * self.components;
|
||||
current.len() == row_len * self.height as usize
|
||||
&& current
|
||||
.par_chunks_exact(row_len)
|
||||
.enumerate()
|
||||
.all(|(y, row)| row.chunks_exact(self.components).zip(self.row(y)).all(|(stored, sampled)| stored == &sampled[..self.components]))
|
||||
}
|
||||
|
||||
pub(crate) fn render(&self) -> (u32, Vec<f32>) {
|
||||
let row_len = self.width as usize * self.components;
|
||||
let mut pixels = vec![0.0; row_len * self.height as usize];
|
||||
pixels.par_chunks_exact_mut(row_len).enumerate().for_each(|(y, row)| {
|
||||
for (output, sampled) in row.chunks_exact_mut(self.components).zip(self.row(y)) {
|
||||
output.copy_from_slice(&sampled[..self.components]);
|
||||
}
|
||||
});
|
||||
|
||||
(self.width, pixels)
|
||||
}
|
||||
}
|
||||
@@ -4,10 +4,9 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use rayon::prelude::*;
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_compose::{ImageRes, ImageStore};
|
||||
use texturecraft_core::{BakedMap, MAX_RESOLUTION, NormalFormat, UDIM_RANGE, udim_at};
|
||||
use texturecraft_core::{BakedMap, MAX_RESOLUTION, Project, UDIM_RANGE};
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad, strp};
|
||||
use crate::set_cmds::ts_param;
|
||||
@@ -45,39 +44,41 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
None => BTreeMap::from([(FIRST_TILE, image)]),
|
||||
};
|
||||
|
||||
let resolution = s.edit("Use image as mesh map", |s| use_images(s, CMD, ts, map, &images))?;
|
||||
let resolution = s.edit("Use image as mesh map", |s| {
|
||||
let resolution = use_images(s, CMD, ts, map, &images)?;
|
||||
detach_imported_sources(&mut s.doc.project, ts, |previous| previous == map);
|
||||
Ok(resolution)
|
||||
})?;
|
||||
|
||||
Ok(json!({ "map": map.id(), "resolution": resolution }))
|
||||
}
|
||||
|
||||
/// A bake, a manual assignment or a clear ends the import link but keeps the image resource
|
||||
pub(crate) fn detach_imported_sources(project: &mut Project, texture_set: usize, replaced: impl Fn(BakedMap) -> bool) {
|
||||
for source in project.resource_sources.values_mut() {
|
||||
if source.mesh_map.is_some_and(|slot| slot.texture_set == texture_set && replaced(slot.map)) {
|
||||
source.mesh_map = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The tile number a set without UV tiles keys its one image by
|
||||
pub(crate) const FIRST_TILE: u32 = *UDIM_RANGE.start();
|
||||
|
||||
/// Use `images` (by UV tile; one at [`FIRST_TILE`] without UV tiles) as mesh map `map` of set `ts` in the caller's edit; returns its width
|
||||
pub(crate) fn use_images(s: &mut Session, cmd: &str, ts: usize, map: BakedMap, images: &BTreeMap<u32, Arc<ImageRes>>) -> Result<u32> {
|
||||
let texture_set = s.doc.project.texture_set(ts)?;
|
||||
let grid = texture_set.tile_grid();
|
||||
if let Some(tile) = texture_set.uv_tiles.iter().find(|tile| grid.is_some() && !images.contains_key(tile)) {
|
||||
return Err(bad(cmd, format!("no image for UV tile {tile}")));
|
||||
}
|
||||
/// Use `images` (by UV tile; one at [`FIRST_TILE`] without UV tiles) as mesh map `map` of set `texture_set` in the caller's edit; returns its width
|
||||
pub(crate) fn use_images(session: &mut Session, command: &str, texture_set: usize, map: BakedMap, images: &BTreeMap<u32, Arc<ImageRes>>) -> Result<u32> {
|
||||
let (width, data) = crate::mesh_map_sampler::MeshMapSampler::new(session, command, texture_set, map, images)?.render();
|
||||
|
||||
let (width, height) = image_map_size(s, cmd, ts)?;
|
||||
|
||||
// Bent normals are tangent-space maps like the normal map, so both follow the project's normal format
|
||||
let flip_green = matches!(map, BakedMap::Normal | BakedMap::BentNormal) && s.doc.project.normal_format == NormalFormat::DirectX;
|
||||
let data = match (grid, images.values().next()) {
|
||||
(_, None) => return Err(bad(cmd, "no image to use")),
|
||||
(None, Some(image)) => resample(map.components(), (width, height), flip_green, |u, v| image.sample(u, v)),
|
||||
// An atlas texel reads the image of the tile its mesh UV falls in
|
||||
(Some(grid), Some(_)) => resample(map.components(), (width, height), flip_green, |u, v| {
|
||||
let uv = grid.from_atlas([u, v]);
|
||||
udim_at(uv).and_then(|tile| images.get(&tile)).map_or([0.0; 4], |image| image.sample(uv[0] - uv[0].floor(), uv[1] - uv[1].floor()))
|
||||
}),
|
||||
};
|
||||
|
||||
let entry = s.doc.baked.entry(ts).or_default();
|
||||
let entry = session.doc.baked.entry(texture_set).or_default();
|
||||
entry.resolution = width;
|
||||
entry.maps.insert(map, Arc::new(data));
|
||||
s.doc.project.texture_set_mut(ts)?.baked.insert(map);
|
||||
|
||||
let set = session.doc.project.texture_set_mut(texture_set)?;
|
||||
set.baked.insert(map);
|
||||
|
||||
// Imported pixels have no bake provenance
|
||||
set.bake_sources.remove(&map);
|
||||
|
||||
Ok(width)
|
||||
}
|
||||
|
||||
@@ -133,39 +134,26 @@ fn udim_in(name: &str) -> Option<usize> {
|
||||
})
|
||||
}
|
||||
|
||||
/// `w` × `h` texels of `comps` values each from `sample` (atlas UV → RGBA), as stored in the
|
||||
/// file (mesh maps hold data, not colors, so nothing is linearized); `flip_green` reads a
|
||||
/// DirectX normal or bent normal map.
|
||||
fn resample(comps: usize, (w, h): (u32, u32), flip_green: bool, sample: impl Fn(f32, f32) -> [f32; 4] + Sync) -> Vec<f32> {
|
||||
let mut out = vec![0.0; w as usize * h as usize * comps];
|
||||
out.par_chunks_mut(w as usize * comps).enumerate().for_each(|(y, row)| {
|
||||
let v = (y as f32 + 0.5) / h as f32;
|
||||
for (x, texel) in row.chunks_exact_mut(comps).enumerate() {
|
||||
let mut c = sample((x as f32 + 0.5) / w as f32, v);
|
||||
if flip_green {
|
||||
c[1] = 1.0 - c[1];
|
||||
}
|
||||
for (o, c) in texel.iter_mut().zip(c) {
|
||||
*o = c;
|
||||
}
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
fn clear(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "textureSet.meshMap.clear";
|
||||
let ts = ts_param(s, p, CMD)?;
|
||||
let map = map_param(p, CMD)?;
|
||||
if !s.doc.baked.get(&ts).is_some_and(|b| b.maps.contains_key(&map)) {
|
||||
return Err(bad(CMD, format!("texture set {ts} has no {} map", map.id())));
|
||||
fn clear(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
const COMMAND: &str = "textureSet.meshMap.clear";
|
||||
let texture_set = ts_param(session, params, COMMAND)?;
|
||||
let map = map_param(params, COMMAND)?;
|
||||
if !session.doc.baked.get(&texture_set).is_some_and(|baked| baked.maps.contains_key(&map)) {
|
||||
return Err(bad(COMMAND, format!("texture set {texture_set} has no {} map", map.id())));
|
||||
}
|
||||
s.edit("Clear mesh map", |s| {
|
||||
if let Some(b) = s.doc.baked.get_mut(&ts) {
|
||||
b.maps.remove(&map);
|
||||
|
||||
session.edit("Clear mesh map", |session| {
|
||||
if let Some(baked) = session.doc.baked.get_mut(&texture_set) {
|
||||
baked.maps.remove(&map);
|
||||
}
|
||||
s.doc.project.texture_set_mut(ts)?.baked.remove(&map);
|
||||
|
||||
let set = session.doc.project.texture_set_mut(texture_set)?;
|
||||
set.baked.remove(&map);
|
||||
set.bake_sources.remove(&map);
|
||||
detach_imported_sources(&mut session.doc.project, texture_set, |previous| previous == map);
|
||||
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
Ok(Value::Null)
|
||||
}
|
||||
@@ -4,12 +4,13 @@ use std::collections::BTreeMap;
|
||||
use std::path::Path;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_core::BakedMap;
|
||||
use texturecraft_core::{BakedMap, MeshMapSlot, ResourceSource};
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad, strp};
|
||||
use crate::meshmap_cmds::{FIRST_TILE, image_map_size, tile_number, use_images};
|
||||
use crate::meshmap_file_name::{baked_map_from_file_name, texture_set_from_file_name};
|
||||
use crate::resource_cmds::read_image_file;
|
||||
use crate::resource_update_cmds::file_source;
|
||||
use crate::{Result, Session, cmd};
|
||||
|
||||
const CMD: &str = "textureSet.meshMap.import";
|
||||
@@ -84,11 +85,20 @@ fn import_with_budget(s: &mut Session, p: &Value, max_bytes: u64) -> Result<Valu
|
||||
|
||||
let mut images = BTreeMap::new();
|
||||
for (tile, path) in tiles {
|
||||
let slot = MeshMapSlot { texture_set: *ts, map: *map, tile: *tile };
|
||||
let source = ResourceSource { mesh_map: Some(slot), ..file_source(path) };
|
||||
let bytes = read_image_file(CMD, path, remaining_bytes)?;
|
||||
reserve_bytes(&mut remaining_bytes, bytes.len() as u64)?;
|
||||
|
||||
let bytes_per_texel = size_of::<[f32; 4]>() as u64;
|
||||
let name = s.add_image_resource(path, bytes, remaining_bytes / bytes_per_texel)?;
|
||||
|
||||
// The slot follows only its latest file
|
||||
for earlier in s.doc.project.resource_sources.values_mut().filter(|earlier| earlier.mesh_map == Some(slot)) {
|
||||
earlier.mesh_map = None;
|
||||
}
|
||||
s.doc.project.resource_sources.insert(name.clone(), source);
|
||||
|
||||
let image = s.images.get(&name).ok_or_else(|| bad(CMD, format!("no decoded image `{name}`")))?;
|
||||
reserve_bytes(&mut remaining_bytes, u64::from(image.width) * u64::from(image.height) * bytes_per_texel)?;
|
||||
images.insert(*tile, image.clone());
|
||||
@@ -98,7 +108,8 @@ fn import_with_budget(s: &mut Session, p: &Value, max_bytes: u64) -> Result<Valu
|
||||
}
|
||||
Ok(assigned)
|
||||
});
|
||||
// A failed edit leaves the document as it was; forget the images it decoded
|
||||
|
||||
// Forget images decoded during an edit that rolled back
|
||||
if result.is_err() {
|
||||
s.sync_images();
|
||||
}
|
||||
|
||||
@@ -591,8 +591,7 @@ impl Session {
|
||||
self.undo.remove(0);
|
||||
}
|
||||
self.redo.clear();
|
||||
self.modified = true;
|
||||
self.revision = self.revision.wrapping_add(1);
|
||||
self.mark_modified();
|
||||
|
||||
// Recompute committed tiles at low priority because the live preview already shows them
|
||||
self.mark_settle(stroke.ts, stroke.target, stroke.canvas.dirty.iter().copied());
|
||||
|
||||
@@ -385,6 +385,21 @@ pub(crate) fn path_images(kind: &EffectKind) -> Vec<String> {
|
||||
shapes.iter().filter_map(|shape| read_paint(shape).ok()?.mask_image).collect()
|
||||
}
|
||||
|
||||
/// Points the stored paths of `kind` that paint with image resource `from` (as mask image or brush alpha) at `to`
|
||||
pub(crate) fn rename_path_images(kind: &mut EffectKind, from: &str, to: &str) {
|
||||
let EffectKind::Path(shapes) = kind else { return };
|
||||
|
||||
for shape in shapes {
|
||||
for pointer in ["/mask_image", "/brush/alpha_image"] {
|
||||
if let Some(image) = shape.paint.pointer_mut(pointer)
|
||||
&& image.as_str() == Some(from)
|
||||
{
|
||||
*image = serde_json::Value::String(to.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The Path tool state showing a stored path (finite points only, at most [`MAX_PATH_POINTS`])
|
||||
fn state_of(shape: &PathShape) -> PathState {
|
||||
let points = shape.points.iter().filter(|p| p.iter().all(|v| v.is_finite())).take(MAX_PATH_POINTS).map(|p| Vec3::from_array(*p)).collect();
|
||||
@@ -925,28 +940,28 @@ impl Session {
|
||||
}
|
||||
|
||||
/// [`Session::put_path`] recompositing only the tiles it changed, with no undo step: returns the paint report and the document before
|
||||
fn repaint_path(&mut self, eid: LayerId, index: usize, shape: PathShape) -> Result<(Value, Document)> {
|
||||
fn repaint_path(&mut self, effect_id: LayerId, index: usize, shape: PathShape) -> Result<(Value, Document)> {
|
||||
let before = self.doc.clone();
|
||||
let painted = match self.put_path(eid, index, shape) {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
let painted = match self.put_path(effect_id, index, shape) {
|
||||
Ok(report) => report,
|
||||
Err(error) => {
|
||||
self.doc = before;
|
||||
return Err(e);
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
|
||||
// Paths paint into the active set; a sublayer in another set recomposites in full
|
||||
let project = &self.doc.project;
|
||||
let set = project.effect(eid).and_then(|(owner, _)| project.locate(owner)).map(|(ts, _, _)| ts);
|
||||
let set = project.effect(effect_id).and_then(|(owner, _)| project.locate(owner)).map(|(ts, _, _)| ts);
|
||||
if set == Some(self.ts()) {
|
||||
// Content or mask, the sublayer's owner decides which sets redraw
|
||||
let tiles = changed_tiles(&before.pixels, &self.doc.pixels, eid);
|
||||
self.mark_painted(self.ts(), Some(PaintTarget::Layer(eid)), tiles);
|
||||
let tiles = changed_tiles(&before.pixels, &self.doc.pixels, effect_id);
|
||||
self.mark_painted(self.ts(), Some(PaintTarget::Layer(effect_id)), tiles);
|
||||
} else {
|
||||
self.invalidate_changed(&before);
|
||||
}
|
||||
self.revision = self.revision.wrapping_add(1);
|
||||
self.modified = true;
|
||||
|
||||
self.mark_modified();
|
||||
Ok((painted, before))
|
||||
}
|
||||
|
||||
|
||||
@@ -80,6 +80,9 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
pub type FileList = Vec<(String, u64)>;
|
||||
/// Reads a file of the list by name.
|
||||
pub type Loader<'a> = &'a dyn Fn(&str) -> std::result::Result<Vec<u8>, String>;
|
||||
/// The file on disk a file of the list is read from (None: an archive entry or bytes in memory),
|
||||
/// asked right before reading it.
|
||||
type Locator<'a> = &'a dyn Fn(&str) -> Option<texturecraft_core::ResourceSource>;
|
||||
|
||||
mod pbr_options;
|
||||
mod take;
|
||||
@@ -137,10 +140,16 @@ impl Session {
|
||||
/// Import the maps found among `files` as one fill layer on the active texture set; `load`
|
||||
/// reads a file by name. Returns the reply of `file.importPbrFolder`.
|
||||
pub fn import_pbr(&mut self, files: &FileList, load: Loader, options: &PbrOptions) -> Result<Value> {
|
||||
self.import_pbr_with_budget(files, load, options, import_memory_budget())
|
||||
self.import_pbr_with_budget(files, load, &|_| None, options, import_memory_budget())
|
||||
}
|
||||
|
||||
fn import_pbr_with_budget(&mut self, files: &FileList, load: Loader, options: &PbrOptions, memory_budget: u64) -> Result<Value> {
|
||||
/// [`Session::import_pbr`] that records the disk files `locate` names, so the Resources Updater can read them again
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn import_pbr_located(&mut self, files: &FileList, load: Loader, locate: Locator, options: &PbrOptions) -> Result<Value> {
|
||||
self.import_pbr_with_budget(files, load, locate, options, import_memory_budget())
|
||||
}
|
||||
|
||||
fn import_pbr_with_budget(&mut self, files: &FileList, load: Loader, locate: Locator, options: &PbrOptions, memory_budget: u64) -> Result<Value> {
|
||||
let set = detect_with(files, &options.choose)?;
|
||||
if set.is_empty() {
|
||||
return Err(EngineError::Other(format!(
|
||||
@@ -193,6 +202,10 @@ impl Session {
|
||||
let mut fill = Fill { projection: options.projection.clone(), ..Fill::default() };
|
||||
let mut added: Vec<(String, Arc<Vec<u8>>)> = Vec::new();
|
||||
let mut decoded = Vec::new();
|
||||
|
||||
// Disk files read by name, and the resources that hold one of them unchanged
|
||||
let mut file_sources: BTreeMap<String, texturecraft_core::ResourceSource> = BTreeMap::new();
|
||||
let mut resource_sources: Vec<(String, texturecraft_core::ResourceSource)> = Vec::new();
|
||||
let mut channels: Vec<Channel> = Vec::new();
|
||||
let mut total_texels = 0u64;
|
||||
let mut retained_bytes = 0u64;
|
||||
@@ -231,6 +244,9 @@ impl Session {
|
||||
let loaded = if allowed_texels == 0 {
|
||||
Err("not enough memory is available to import more textures".to_string())
|
||||
} else {
|
||||
if let Some(source) = locate(&file) {
|
||||
file_sources.insert(file.clone(), source);
|
||||
}
|
||||
load(&file).and_then(|bytes| {
|
||||
if bytes.len() as u64 > MAX_FILE_BYTES {
|
||||
return Err(format!("the file is over {} MB", MAX_FILE_BYTES >> 20));
|
||||
@@ -288,10 +304,15 @@ impl Session {
|
||||
}
|
||||
};
|
||||
let base = texturecraft_formats::sanitize_resource_name(&resource_name);
|
||||
let (mut unique, mut suffix_index) = (base.clone(), 2);
|
||||
while self.doc.resources.contains_key(&unique) || added.iter().any(|(a, _)| *a == unique) {
|
||||
unique = format!("{suffix_index}_{base}");
|
||||
suffix_index += 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)
|
||||
});
|
||||
|
||||
// Only a resource holding the file's own bytes can be compared with it later
|
||||
if take == Take::Whole
|
||||
&& let Some(source) = file_sources.get(&file)
|
||||
{
|
||||
resource_sources.push((unique.clone(), source.clone()));
|
||||
}
|
||||
|
||||
added.push((unique.clone(), resource_bytes));
|
||||
@@ -316,6 +337,7 @@ impl Session {
|
||||
for (n, bytes) in &added {
|
||||
s.doc.resources.insert(n.clone(), bytes.clone());
|
||||
}
|
||||
s.doc.project.resource_sources.extend(resource_sources);
|
||||
let id = s.doc.project.alloc_id();
|
||||
crate::layer_cmds::insert_selected(s, Layer::new(id, layer_name.clone(), LayerKind::Fill(fill), &channels))
|
||||
})?;
|
||||
@@ -420,7 +442,12 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if options.name.is_none() {
|
||||
options.name = found.name.clone();
|
||||
}
|
||||
s.import_pbr(&found.files, &|name| found.load(name), &options)
|
||||
s.import_pbr_located(
|
||||
&found.files,
|
||||
&|name| found.load(name),
|
||||
&|name| found.disk_path(name).map(|path| crate::resource_update_cmds::file_source(&path)),
|
||||
&options,
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -462,7 +489,7 @@ mod tests {
|
||||
let mut session = Session::new_project("test", crate::geom::primitives::builtin("plane").unwrap(), "builtin:plane", None, 128).unwrap();
|
||||
let load = |_: &str| Ok(bytes.clone());
|
||||
|
||||
let result = session.import_pbr_with_budget(&files, &load, &PbrOptions::default(), 64);
|
||||
let result = session.import_pbr_with_budget(&files, &load, &|_| None, &PbrOptions::default(), 64);
|
||||
|
||||
assert!(result.unwrap_err().to_string().contains("more than 1 texels"));
|
||||
assert!(session.doc.resources.is_empty());
|
||||
@@ -471,7 +498,7 @@ mod tests {
|
||||
assert_eq!(allowed_source_texels(256, 64, 3), 2);
|
||||
|
||||
let never_load = |_: &str| -> std::result::Result<Vec<u8>, String> { panic!("no source should load after the budget is spent") };
|
||||
let result = session.import_pbr_with_budget(&files, &never_load, &PbrOptions::default(), 0);
|
||||
let result = session.import_pbr_with_budget(&files, &never_load, &|_| None, &PbrOptions::default(), 0);
|
||||
|
||||
assert!(result.unwrap_err().to_string().contains("not enough memory"));
|
||||
}
|
||||
|
||||
@@ -11,6 +11,16 @@ pub(in crate::pbr_cmds) struct Found {
|
||||
}
|
||||
|
||||
impl Found {
|
||||
/// The file on disk `name` is read from (None for an archive entry or a name not in the list)
|
||||
pub(in crate::pbr_cmds) fn disk_path(&self, name: &str) -> Option<String> {
|
||||
let path = match &self.source {
|
||||
Origin::Folder { root } => root.join(name),
|
||||
Origin::Files(paths) => paths.iter().find(|p| p.file_name().is_some_and(|n| n.to_string_lossy() == name))?.clone(),
|
||||
Origin::Zip(_) => return None,
|
||||
};
|
||||
path.to_str().map(str::to_string)
|
||||
}
|
||||
|
||||
/// Reads one file of the list. Archive entries are read through a limit, since their
|
||||
/// declared size can lie.
|
||||
pub(in crate::pbr_cmds) fn load(&self, name: &str) -> std::result::Result<Vec<u8>, String> {
|
||||
|
||||
@@ -2,17 +2,19 @@
|
||||
//! dialog's Output templates tab list, read, save and remove. On the desktop the user presets
|
||||
//! are mirrored as `<name>.json` files in a library folder (see [`Session::load_export_presets`]).
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::collections::HashSet;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_formats::export::{MAX_PRESET_NAME, sanitize_file_stem};
|
||||
use texturecraft_formats::{ExportPreset, builtin_preset, builtin_presets, preset_from_json};
|
||||
use texturecraft_formats::{ExportPreset, NEW_BUILTIN_PRESET_NAMES, builtin_preset, builtin_preset_catalog, preset_from_json};
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad, strp};
|
||||
use crate::{Result, Session, cmd};
|
||||
|
||||
/// Most user presets kept (and read from the library folder).
|
||||
const MAX_USER_PRESETS: usize = 512;
|
||||
const BUILTIN_PRESET_PREFIX: &str = "builtin:";
|
||||
|
||||
/// The user's export presets.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
@@ -51,6 +53,16 @@ fn same_name(a: &str, b: &str) -> bool {
|
||||
a.trim().eq_ignore_ascii_case(b.trim())
|
||||
}
|
||||
|
||||
/// A qualified selector names a built-in independently of a saved library entry.
|
||||
pub fn unqualified_preset_name(name: &str) -> &str {
|
||||
let mut name = name.trim();
|
||||
while name.get(..BUILTIN_PRESET_PREFIX.len()).is_some_and(|prefix| prefix.eq_ignore_ascii_case(BUILTIN_PRESET_PREFIX)) {
|
||||
name = &name[BUILTIN_PRESET_PREFIX.len()..];
|
||||
}
|
||||
|
||||
name
|
||||
}
|
||||
|
||||
/// Library file stem: two names with the same stem would share a file.
|
||||
fn file_key(name: &str) -> String {
|
||||
sanitize_file_stem(name.trim()).to_ascii_lowercase()
|
||||
@@ -63,8 +75,25 @@ impl UserPresets {
|
||||
|
||||
/// `name` belongs to a built-in or to a user preset other than `skip` (or shares its file).
|
||||
fn taken(&self, name: &str, skip: Option<usize>) -> bool {
|
||||
builtin_preset(name).is_some()
|
||||
|| self.list.iter().enumerate().any(|(i, p)| Some(i) != skip && (same_name(&p.name, name) || file_key(&p.name) == file_key(name)))
|
||||
let keeps_name = skip.and_then(|index| self.list.get(index)).is_some_and(|preset| same_name(&preset.name, name));
|
||||
(!keeps_name && builtin_preset(unqualified_preset_name(name)).is_some()) || self.user_name_taken(name, skip)
|
||||
}
|
||||
|
||||
fn user_name_taken(&self, name: &str, skip: Option<usize>) -> bool {
|
||||
let key = file_key(name);
|
||||
self.list.iter().enumerate().any(|(i, preset)| Some(i) != skip && (same_name(&preset.name, name) || file_key(&preset.name) == key))
|
||||
}
|
||||
|
||||
/// Restore a saved preset under the name existing settings use.
|
||||
pub fn restore(&mut self, preset: ExportPreset) -> std::result::Result<(), String> {
|
||||
preset.validate().map_err(|error| error.to_string())?;
|
||||
let reserved = builtin_preset(&preset.name).is_some_and(|builtin| !NEW_BUILTIN_PRESET_NAMES.contains(&builtin.name.as_str()));
|
||||
if reserved || self.user_name_taken(&preset.name, None) || self.list.len() >= MAX_USER_PRESETS {
|
||||
return Err(format!("preset \"{}\" exists already or the library is full", preset.name));
|
||||
}
|
||||
|
||||
self.list.push(preset);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The first available name, adding a numbered suffix and shortening the base to fit.
|
||||
@@ -119,7 +148,21 @@ impl UserPresets {
|
||||
impl Session {
|
||||
/// A built-in or user export preset by name (case-insensitive).
|
||||
pub fn export_preset(&self, name: &str) -> Option<ExportPreset> {
|
||||
builtin_preset(name).or_else(|| self.export_presets.find(name).and_then(|i| self.export_presets.list.get(i).cloned()))
|
||||
self.export_presets.find(name).and_then(|index| self.export_presets.list.get(index).cloned()).or_else(|| builtin_preset(unqualified_preset_name(name)))
|
||||
}
|
||||
|
||||
pub fn has_user_export_preset(&self, name: &str) -> bool {
|
||||
self.export_presets.find(name).is_some()
|
||||
}
|
||||
|
||||
/// Use the familiar built-in name unless the user's library already owns that selector.
|
||||
pub fn builtin_export_preset_id<'a>(&self, name: &'a str) -> Cow<'a, str> {
|
||||
let mut id = Cow::Borrowed(name);
|
||||
while self.has_user_export_preset(&id) {
|
||||
id = Cow::Owned(format!("{BUILTIN_PRESET_PREFIX}{id}"));
|
||||
}
|
||||
|
||||
id
|
||||
}
|
||||
|
||||
/// Use `dir` as the user preset library: read its `*.json` presets (replacing the list) and
|
||||
@@ -133,10 +176,8 @@ impl Session {
|
||||
files.sort();
|
||||
let mut lib = UserPresets { list: Vec::new(), dir: Some(dir) };
|
||||
for path in files.into_iter().take(MAX_USER_PRESETS) {
|
||||
match texturecraft_formats::load_preset(&path).map_err(|e| e.to_string()) {
|
||||
Ok(p) if lib.taken(&p.name, None) => warnings.push(format!("{}: preset \"{}\" exists already", path.display(), p.name)),
|
||||
Ok(p) => lib.list.push(p),
|
||||
Err(e) => warnings.push(format!("{}: {e}", path.display())),
|
||||
if let Err(error) = texturecraft_formats::load_preset(&path).map_err(|error| error.to_string()).and_then(|preset| lib.restore(preset)) {
|
||||
warnings.push(format!("{}: {error}", path.display()));
|
||||
}
|
||||
}
|
||||
self.export_presets = lib;
|
||||
@@ -144,10 +185,12 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
fn list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let entry = |p: &ExportPreset, builtin: bool| json!({"name": p.name, "maps": p.maps.len(), "builtin": builtin});
|
||||
let builtins = builtin_presets();
|
||||
Ok(json!(builtins.iter().map(|p| entry(p, true)).chain(s.export_presets.list.iter().map(|p| entry(p, false))).collect::<Vec<_>>()))
|
||||
fn list(session: &mut Session, _: &Value) -> Result<Value> {
|
||||
let entry = |name: &str, maps: usize, builtin: bool| json!({"name": name, "maps": maps, "builtin": builtin});
|
||||
let builtins = builtin_preset_catalog().iter().map(|preset| entry(&session.builtin_export_preset_id(&preset.name), preset.maps.len(), true));
|
||||
let custom = session.export_presets.list.iter().map(|preset| entry(&preset.name, preset.maps.len(), false));
|
||||
|
||||
Ok(json!(builtins.chain(custom).collect::<Vec<_>>()))
|
||||
}
|
||||
|
||||
fn name_param<'a>(p: &'a Value, cmd: &str) -> Result<&'a str> {
|
||||
@@ -216,11 +259,16 @@ fn save(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
fn remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "export.preset.remove";
|
||||
let name = name_param(p, CMD)?;
|
||||
if builtin_preset(name).is_some() {
|
||||
return Err(bad(CMD, format!("\"{name}\" is a built-in preset and can't be removed")));
|
||||
}
|
||||
let i = s.export_presets.find(name).ok_or_else(|| bad(CMD, format!("no user export preset `{name}`")))?;
|
||||
let removed = s.export_presets.list.remove(i);
|
||||
let Some(index) = s.export_presets.find(name) else {
|
||||
let message = if builtin_preset(unqualified_preset_name(name)).is_some() {
|
||||
format!("\"{name}\" is a built-in preset and can't be removed")
|
||||
} else {
|
||||
format!("no user export preset `{name}`")
|
||||
};
|
||||
return Err(bad(CMD, message));
|
||||
};
|
||||
|
||||
let removed = s.export_presets.list.remove(index);
|
||||
s.export_presets.delete(&removed.name);
|
||||
Ok(Value::Null)
|
||||
}
|
||||
@@ -409,6 +457,36 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn feedback_existing_preset_keeps_its_name_and_export_maps() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let name = "Roblox SurfaceAppearance (separate maps)";
|
||||
let custom = preset(name);
|
||||
std::fs::write(dir.path().join(format!("{}.json", sanitize_file_stem(name))), custom.to_string()).unwrap();
|
||||
let mut s = session();
|
||||
assert_eq!(run(&mut s, "export.preset.get", json!({"name": name})).unwrap()["maps"].as_array().unwrap().len(), 4);
|
||||
|
||||
let warnings = s.load_export_presets(dir.path().to_path_buf());
|
||||
|
||||
assert!(warnings.is_empty(), "{warnings:?}");
|
||||
assert_eq!(run(&mut s, "export.preset.get", json!({"name": name.to_ascii_lowercase()})).unwrap(), custom);
|
||||
let plan = run(&mut s, "export.plan", json!({"preset": name, "ts": 0})).unwrap();
|
||||
assert_eq!(plan.as_array().unwrap().len(), 1);
|
||||
assert!(plan[0]["file"].as_str().unwrap().ends_with("_R.png"));
|
||||
|
||||
let listed = run(&mut s, "export.presets", json!({})).unwrap();
|
||||
let names = listed.as_array().unwrap();
|
||||
assert!(names.iter().any(|entry| entry["name"] == name && entry["builtin"] == false));
|
||||
let builtin = format!("builtin:{name}");
|
||||
assert!(names.iter().any(|entry| entry["name"] == builtin && entry["builtin"] == true));
|
||||
let builtin_plan = run(&mut s, "export.plan", json!({"preset": builtin, "ts": 0})).unwrap();
|
||||
assert!(builtin_plan.as_array().unwrap().len() > 1);
|
||||
run(&mut s, "export.preset.save", json!({"preset": custom})).unwrap();
|
||||
run(&mut s, "export.preset.remove", json!({"name": name})).unwrap();
|
||||
assert_eq!(run(&mut s, "export.preset.get", json!({"name": name})).unwrap()["maps"].as_array().unwrap().len(), 4);
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn the_library_folder_mirrors_saves_renames_and_removals() {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Project-level commands: new project, sample project, smart materials, inspection.
|
||||
//! Project-level commands: new project, rename, sample project, smart materials, inspection.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_compose::BakedMaps;
|
||||
@@ -63,16 +63,23 @@ fn new(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(crate::inspect::session(s))
|
||||
}
|
||||
|
||||
fn rename(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let name = strp(p, "name")
|
||||
.map(str::trim)
|
||||
.filter(|name| !name.is_empty() && name.chars().count() <= MAX_PROJECT_NAME_CHARS && !name.chars().any(char::is_control))
|
||||
.ok_or_else(|| bad("project.rename", format!("`name` must be 1-{MAX_PROJECT_NAME_CHARS} characters without control characters")))?;
|
||||
/// Trim and validate a proposed name without changing the project.
|
||||
pub fn validate_project_name(name: &str) -> Result<&str> {
|
||||
let name = name.trim();
|
||||
if name.is_empty() || name.chars().nth(MAX_PROJECT_NAME_CHARS).is_some() || name.chars().any(char::is_control) {
|
||||
return Err(bad("project.rename", format!("`name` must be 1-{MAX_PROJECT_NAME_CHARS} characters without control characters")));
|
||||
}
|
||||
|
||||
Ok(name)
|
||||
}
|
||||
|
||||
fn rename(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
let name = validate_project_name(strp(params, "name").unwrap_or_default())?;
|
||||
|
||||
// The same name is not an undo step and leaves a saved project unmodified
|
||||
if name != s.doc.project.name {
|
||||
s.edit("Rename project", |s| {
|
||||
s.doc.project.name = name.to_string();
|
||||
if name != session.doc.project.name {
|
||||
session.edit("Rename project", |session| {
|
||||
session.doc.project.name = name.to_owned();
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
//! An image file read again for a resource, checked before the project changes
|
||||
|
||||
use texturecraft_core::ResourceSource;
|
||||
use texturecraft_formats::DecodedImage;
|
||||
|
||||
use crate::Result;
|
||||
use crate::resource_cmds::{MAX_BYTES, read_image_file};
|
||||
use crate::resource_update_cmds::file_source;
|
||||
|
||||
/// A resource's new bytes, their decoded pixels and the file they came from
|
||||
pub(crate) struct ReloadedFile {
|
||||
pub name: String,
|
||||
pub bytes: Vec<u8>,
|
||||
pub image: DecodedImage,
|
||||
pub source: ResourceSource,
|
||||
}
|
||||
|
||||
impl ReloadedFile {
|
||||
pub(crate) fn read(cmd: &str, name: String, path: &str) -> Result<Self> {
|
||||
let source = file_source(path);
|
||||
let bytes = read_image_file(cmd, path, MAX_BYTES as u64)?;
|
||||
|
||||
Self::decode(cmd, name, source, bytes)
|
||||
}
|
||||
|
||||
pub(crate) fn read_changed(cmd: &str, name: &str, previous: &ResourceSource, stored: &[u8], decoded: bool) -> Result<Option<Self>> {
|
||||
let mut source = file_source(&previous.path);
|
||||
let bytes = read_image_file(cmd, &previous.path, MAX_BYTES as u64)?;
|
||||
let unchanged = bytes == stored;
|
||||
if unchanged && decoded {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
source.mesh_map = previous.mesh_map;
|
||||
let file = Self::decode(cmd, name.to_owned(), source, bytes)?;
|
||||
Ok((!unchanged).then_some(file))
|
||||
}
|
||||
|
||||
fn decode(cmd: &str, name: String, source: ResourceSource, bytes: Vec<u8>) -> Result<Self> {
|
||||
let image = texturecraft_formats::decode_image(&bytes).map_err(|error| crate::commands::bad(cmd, format!("{}: {error}", source.path)))?;
|
||||
|
||||
Ok(Self { name, bytes, image, source })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
//! A remembered comparison of a resource with its file, so an unchanged file is not read again
|
||||
|
||||
use std::sync::{Arc, Weak};
|
||||
|
||||
use crate::resource_status::ResourceStatus;
|
||||
|
||||
/// What reading a resource's file found, kept while the file's size and time stay the same
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct ResourceCheck {
|
||||
pub path: String,
|
||||
pub size: u64,
|
||||
pub modified_ms: u64,
|
||||
/// The resource bytes the file was compared with (an update or undo replaces them)
|
||||
pub bytes: Weak<Vec<u8>>,
|
||||
pub status: ResourceStatus,
|
||||
}
|
||||
|
||||
impl ResourceCheck {
|
||||
/// Whether this verdict still holds for the file and the resource's bytes
|
||||
pub(crate) fn holds_for(&self, path: &str, size: u64, modified_ms: u64, bytes: &Arc<Vec<u8>>) -> bool {
|
||||
self.path == path && self.size == size && self.modified_ms == modified_ms && std::ptr::eq(self.bytes.as_ptr(), Arc::as_ptr(bytes))
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,16 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
),
|
||||
cmd!("resource.list", "List resources", [], None, "{}", always, |s, _| Ok(list(s))),
|
||||
cmd!("resource.remove", "Remove resource", [], None, "{name}", always, remove),
|
||||
cmd!("resource.export", "Export resource", [], None, "{name, path} — the resource's file as it was imported", always, export),
|
||||
cmd!(
|
||||
"resource.rename",
|
||||
"Rename resource",
|
||||
[],
|
||||
None,
|
||||
"{name, to} — everything that uses the image follows it; `to` keeps the old extension when it has none",
|
||||
always,
|
||||
rename
|
||||
),
|
||||
cmd!("file.removeUnused", "Remove unused resources...", ["File"], None, "{}", always, remove_unused),
|
||||
cmd!(
|
||||
"layer.add.image",
|
||||
@@ -45,6 +55,30 @@ pub(crate) fn decoded(d: texturecraft_formats::DecodedImage) -> Arc<ImageRes> {
|
||||
Arc::new(ImageRes::new(d.width, d.height, d.rgba, d.srgb))
|
||||
}
|
||||
|
||||
/// Disambiguate a sanitized resource name without losing its archive key on save.
|
||||
pub(crate) fn unique_resource_name(base: String, taken: impl Fn(&str) -> bool) -> String {
|
||||
if !taken(&base) {
|
||||
return base;
|
||||
}
|
||||
|
||||
let (stem, extension) = base.rfind('.').map_or((base.as_str(), ""), |start| base.split_at(start));
|
||||
let mut index = 2;
|
||||
loop {
|
||||
let discriminator = format!("{index}_");
|
||||
let available = MAX_RESOURCE_NAME_LEN - discriminator.len();
|
||||
|
||||
// An unusually long extension must leave room for the name itself
|
||||
let (stem, extension) = if extension.len() < available { (stem, extension) } else { (base.as_str(), "") };
|
||||
let stem = &stem[..stem.len().min(available - extension.len())];
|
||||
let name = format!("{discriminator}{stem}{extension}");
|
||||
if !taken(&name) {
|
||||
return name;
|
||||
}
|
||||
|
||||
index += 1;
|
||||
}
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Add an image resource from bytes (one undo step); returns its unique, sanitized name
|
||||
pub fn import_resource_bytes(&mut self, file_name: &str, bytes: Vec<u8>) -> Result<String> {
|
||||
@@ -79,19 +113,7 @@ impl Session {
|
||||
base.insert_str(0, &prefix);
|
||||
}
|
||||
|
||||
let (stem, extension) = base.rfind('.').map_or((base.as_str(), ""), |extension_start| base.split_at(extension_start));
|
||||
let mut name = base.clone();
|
||||
let mut duplicate_index = 2;
|
||||
while self.doc.resources.contains_key(&name) || crate::fill_alpha::library_alpha_of(&name).is_some() {
|
||||
let discriminator = format!("{duplicate_index}_");
|
||||
let available = MAX_RESOURCE_NAME_LEN - discriminator.len();
|
||||
|
||||
// Leave room for a stem even for names that end in an unusually long extension
|
||||
let (stem, extension) = if extension.len() < available { (stem, extension) } else { (base.as_str(), "") };
|
||||
let stem = stem.get(..stem.len().min(available - extension.len())).unwrap_or(stem);
|
||||
name = format!("{discriminator}{stem}{extension}");
|
||||
duplicate_index += 1;
|
||||
}
|
||||
let name = unique_resource_name(base, |name| self.doc.resources.contains_key(name) || crate::fill_alpha::library_alpha_of(name).is_some());
|
||||
|
||||
self.doc.resources.insert(name.clone(), Arc::new(bytes));
|
||||
self.images.insert(name.clone(), decoded(image));
|
||||
@@ -146,6 +168,16 @@ impl Session {
|
||||
self.drop_missing_image_view();
|
||||
}
|
||||
|
||||
/// Undo and redo restore resource bytes under the same name (the Resources Updater replaces
|
||||
/// them in place): the pixels decoded from the bytes `other` held are stale
|
||||
pub(crate) fn forget_replaced_images(&mut self, other: &crate::Document) {
|
||||
for (name, bytes) in &self.doc.resources {
|
||||
if other.resources.get(name).is_some_and(|previous| !Arc::ptr_eq(previous, bytes)) {
|
||||
self.images.remove(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The "Other..." view cannot show an image that is gone (removed or renamed): the material comes back
|
||||
pub(crate) fn drop_missing_image_view(&mut self) {
|
||||
if self.view == crate::ViewMode::Image && !self.view_image.as_ref().is_some_and(|name| self.images.contains_key(name)) {
|
||||
@@ -172,8 +204,16 @@ fn list(s: &Session) -> Value {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = strp(p, "path").ok_or_else(|| bad("resource.import", "`path` is required"))?;
|
||||
let prefix = strp(p, "prefix").unwrap_or("");
|
||||
|
||||
let source = crate::resource_update_cmds::file_source(path);
|
||||
let bytes = read_image_file("resource.import", path, MAX_BYTES as u64)?;
|
||||
let name = s.import_resource_bytes_prefixed(strp(p, "prefix").unwrap_or(""), path, bytes)?;
|
||||
|
||||
let name = s.edit("Import resource", |session| {
|
||||
let name = session.add_image_resource_prefixed(prefix, path, bytes, texturecraft_formats::MAX_RESOURCE_TEXELS)?;
|
||||
session.doc.project.resource_sources.insert(name.clone(), source);
|
||||
Ok(name)
|
||||
})?;
|
||||
Ok(json!({ "name": name }))
|
||||
}
|
||||
|
||||
@@ -255,28 +295,146 @@ fn remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
s.edit("Remove resource", |s| {
|
||||
s.doc.resources.remove(&name);
|
||||
s.doc.project.resource_sources.remove(&name);
|
||||
Ok(())
|
||||
})?;
|
||||
s.sync_images();
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
/// Drop resources no layer, mask effect, the brush alpha, the projection stencil, the mask brush or the environment uses (one undo step)
|
||||
fn remove_unused(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let mut used = Vec::new();
|
||||
for set in &s.doc.project.texture_sets {
|
||||
for root in &set.stack {
|
||||
crate::material_lib::images_used(&s.doc.project, *root, &mut used, 0);
|
||||
/// Writes resource `name`'s bytes, as imported, to `path`
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let command = "resource.export";
|
||||
let name = strp(p, "name").ok_or_else(|| bad(command, "`name` is required"))?;
|
||||
let path = strp(p, "path").ok_or_else(|| bad(command, "`path` is required"))?;
|
||||
let bytes = s.doc.resources.get(name).ok_or_else(|| bad(command, format!("no resource `{name}`")))?;
|
||||
|
||||
std::fs::write(path, bytes.as_slice()).map_err(|error| bad(command, format!("cannot write {path}: {error}")))?;
|
||||
|
||||
Ok(json!({ "path": path }))
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn export(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
Err(bad("resource.export", "file paths are not available in the browser"))
|
||||
}
|
||||
|
||||
/// Renames image resource `name` to `to` and every reference to it, in one undo step
|
||||
fn rename(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let command = "resource.rename";
|
||||
let name = strp(p, "name").ok_or_else(|| bad(command, "`name` is required"))?.to_string();
|
||||
let to = strp(p, "to").ok_or_else(|| bad(command, "`to` is required"))?.trim();
|
||||
if !s.doc.resources.contains_key(&name) {
|
||||
return Err(bad(command, format!("no resource `{name}`")));
|
||||
}
|
||||
|
||||
let mut to = sanitize_resource_name(to);
|
||||
if std::path::Path::new(&to).extension().is_none()
|
||||
&& let Some(extension) = std::path::Path::new(&name).extension().and_then(|extension| extension.to_str())
|
||||
{
|
||||
// The stem gives way, so a long name keeps its extension
|
||||
let stem_room = MAX_RESOURCE_NAME_LEN.saturating_sub(extension.len() + 1);
|
||||
to.truncate(stem_room);
|
||||
to = format!("{to}.{extension}");
|
||||
}
|
||||
if to == name {
|
||||
return Ok(json!({ "name": name }));
|
||||
}
|
||||
if s.doc.resources.contains_key(&to) || crate::fill_alpha::library_alpha_of(&to).is_some() {
|
||||
return Err(bad(command, format!("a resource named `{to}` exists already")));
|
||||
}
|
||||
|
||||
s.edit("Rename resource", |s| {
|
||||
let bytes = s.doc.resources.remove(&name).ok_or_else(|| bad(command, format!("no resource `{name}`")))?;
|
||||
s.doc.resources.insert(to.clone(), bytes);
|
||||
// The Resources Updater keeps following the file the image came from
|
||||
if let Some(source) = s.doc.project.resource_sources.remove(&name) {
|
||||
s.doc.project.resource_sources.insert(to.clone(), source);
|
||||
}
|
||||
rename_references(&mut s.doc.project, &name, &to);
|
||||
|
||||
// Refuse rather than leave a reference this rename does not know about pointing at nothing
|
||||
if project_images(&s.doc.project).contains(&name) {
|
||||
return Err(bad(command, format!("`{name}` is used somewhere it can't be renamed")));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
for tool_image in s.tool_images_mut().filter(|tool_image| **tool_image == name) {
|
||||
tool_image.clone_from(&to);
|
||||
}
|
||||
|
||||
// The decoded pixels are the same: they move instead of decoding again
|
||||
if let Some(image) = s.images.remove(&name) {
|
||||
s.images.insert(to.clone(), image);
|
||||
}
|
||||
if s.library_alphas.remove(&name) {
|
||||
s.library_alphas.insert(to.clone());
|
||||
}
|
||||
s.path_cache = None;
|
||||
s.sync_images();
|
||||
Ok(json!({ "name": to }))
|
||||
}
|
||||
|
||||
/// Points every layer, effect, stored path and the environment that read image resource `from` at `to`
|
||||
fn rename_references(project: &mut texturecraft_core::Project, from: &str, to: &str) {
|
||||
for layer in project.layers.values_mut() {
|
||||
let fill_images: Vec<&mut String> = match &mut layer.kind {
|
||||
LayerKind::Fill(fill) => fill.images_mut().collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let effects = layer.mask.iter_mut().flat_map(|mask| mask.effects.iter_mut()).chain(&mut layer.content_effects);
|
||||
let mut images = fill_images;
|
||||
for effect in effects {
|
||||
crate::path_tool::rename_path_images(&mut effect.kind, from, to);
|
||||
images.extend(effect.images_mut());
|
||||
}
|
||||
|
||||
for image in images.into_iter().filter(|image| *image == from) {
|
||||
*image = to.to_string();
|
||||
}
|
||||
}
|
||||
|
||||
if project.display.environment_resource() == Some(from) {
|
||||
project.display.environment = format!("{}{to}", texturecraft_core::project::ENV_RESOURCE_PREFIX);
|
||||
}
|
||||
}
|
||||
|
||||
/// Every image resource a layer, mask effect, stored path or the environment of `project` uses
|
||||
fn project_images(project: &texturecraft_core::Project) -> Vec<String> {
|
||||
let mut used = Vec::new();
|
||||
for set in &project.texture_sets {
|
||||
for root in &set.stack {
|
||||
crate::material_lib::images_used(project, *root, &mut used, 0);
|
||||
}
|
||||
}
|
||||
used.extend(project.display.environment_resource().map(str::to_string));
|
||||
used
|
||||
}
|
||||
|
||||
/// [`project_images`] and the images the brush alpha, the projection stencil and the mask brush use
|
||||
fn images_in_use(s: &Session) -> Vec<String> {
|
||||
let mut used = project_images(&s.doc.project);
|
||||
used.extend(s.tool.stencil.as_ref().map(|st| st.image.clone()));
|
||||
used.extend(s.tool.brush.alpha_image.clone());
|
||||
used.extend(s.tool.mask_image.clone());
|
||||
used.extend(s.doc.project.display.environment_resource().map(str::to_string));
|
||||
used.extend(s.doc.project.resource_sources.iter().filter_map(|(name, source)| {
|
||||
let slot = source.mesh_map?;
|
||||
s.doc.baked.get(&slot.texture_set).is_some_and(|baked| baked.maps.contains_key(&slot.map)).then(|| name.clone())
|
||||
}));
|
||||
used
|
||||
}
|
||||
|
||||
/// Drop resources unused by layers, mesh maps, paint tools or the environment (one undo step)
|
||||
fn remove_unused(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let used = images_in_use(s);
|
||||
let unused: Vec<String> = s.doc.resources.keys().filter(|k| !used.contains(k)).cloned().collect();
|
||||
if !unused.is_empty() {
|
||||
s.edit("Remove unused resources", |s| {
|
||||
s.doc.resources.retain(|k, _| !unused.contains(k));
|
||||
s.doc.project.resource_sources.retain(|k, _| !unused.contains(k));
|
||||
Ok(())
|
||||
})?;
|
||||
s.sync_images();
|
||||
@@ -331,6 +489,120 @@ fn add_image_fill(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn export_writes_the_imported_bytes() {
|
||||
let mut session = crate::sample_session(128, 32).unwrap();
|
||||
let bytes = texturecraft_formats::gray16_png(1, 1, [0.5].into_iter()).unwrap();
|
||||
let name = session.import_resource_bytes("icon.png", bytes.clone()).unwrap();
|
||||
let path = std::env::temp_dir().join(format!("texturecraft-export-resource-{}.png", std::process::id()));
|
||||
|
||||
crate::commands::execute(&mut session, "resource.export", &json!({"name": name, "path": path.to_str().unwrap()})).unwrap();
|
||||
|
||||
assert_eq!(std::fs::read(&path).unwrap(), bytes, "the file is the resource as imported");
|
||||
std::fs::remove_file(path).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_renamed_image_stays_in_use_everywhere_it_was() {
|
||||
let mut session = crate::sample_session(128, 32).unwrap();
|
||||
let png = texturecraft_formats::gray16_png(1, 1, [0.5].into_iter()).unwrap();
|
||||
let name = session.import_resource_bytes("photo.png", png).unwrap();
|
||||
crate::execute(&mut session, "layer.add.image", &json!({"name": name})).unwrap();
|
||||
session.tool.brush.alpha_image = Some(name.clone());
|
||||
|
||||
let renamed = crate::execute(&mut session, "resource.rename", &json!({"name": name, "to": "stone"})).unwrap()["name"].as_str().unwrap().to_string();
|
||||
|
||||
assert_ne!(renamed, name);
|
||||
assert!(renamed.ends_with(".png"), "the extension stays: {renamed}");
|
||||
let used = images_in_use(&session);
|
||||
assert!(used.contains(&renamed) && !used.contains(&name), "every use follows the rename: {used:?}");
|
||||
assert!(session.images.contains_key(&renamed) && !session.images.contains_key(&name));
|
||||
|
||||
session.undo().unwrap();
|
||||
|
||||
assert!(project_images(&session.doc.project).contains(&name), "undo brings the old name back");
|
||||
assert!(session.images.contains_key(&name));
|
||||
assert_eq!(session.tool.brush.alpha_image.as_ref(), Some(&name), "the brush alpha follows the undo");
|
||||
|
||||
session.redo().unwrap();
|
||||
|
||||
assert_eq!(session.tool.brush.alpha_image.as_ref(), Some(&renamed), "the brush alpha follows the redo");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_renamed_image_keeps_following_its_file() {
|
||||
let path = std::env::temp_dir().join(format!("texturecraft-rename-source-{}.png", std::process::id()));
|
||||
std::fs::write(&path, texturecraft_formats::gray16_png(1, 1, [0.25].into_iter()).unwrap()).unwrap();
|
||||
let mut session = crate::sample_session(128, 32).unwrap();
|
||||
let name = crate::execute(&mut session, "resource.import", &json!({"path": path.to_str().unwrap()})).unwrap()["name"].as_str().unwrap().to_string();
|
||||
|
||||
let renamed = crate::execute(&mut session, "resource.rename", &json!({"name": name, "to": "stone"})).unwrap()["name"].as_str().unwrap().to_string();
|
||||
std::fs::write(&path, texturecraft_formats::gray16_png(1, 1, [0.75].into_iter()).unwrap()).unwrap();
|
||||
// An equal-size file counts as changed once its time moved, as a later save's does
|
||||
let later = std::time::SystemTime::now() + std::time::Duration::from_secs(10);
|
||||
std::fs::File::options().write(true).open(&path).unwrap().set_modified(later).unwrap();
|
||||
let updated = crate::execute(&mut session, "resource.update", &json!({"names": [renamed]})).unwrap();
|
||||
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
assert_eq!(updated["updated"], json!([renamed]), "the renamed image reads its changed file again: {updated}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renaming_a_linked_materials_package_moves_a_material_effects_link_with_it() {
|
||||
use std::collections::BTreeMap;
|
||||
use texturecraft_core::{Effect, EffectKind, MaterialLink};
|
||||
|
||||
let mut session = crate::sample_session(128, 32).unwrap();
|
||||
let png = texturecraft_formats::gray16_png(1, 1, [0.5].into_iter()).unwrap();
|
||||
let package = session.import_resource_bytes("package.png", png).unwrap();
|
||||
crate::execute(&mut session, "layer.add.image", &json!({"name": package})).unwrap();
|
||||
let layer_id = session.selected_layer().unwrap();
|
||||
let link = MaterialLink {
|
||||
name: "linked".into(),
|
||||
package: package.clone(),
|
||||
graph: String::new(),
|
||||
params: Vec::new(),
|
||||
presets: Vec::new(),
|
||||
inputs: Vec::new(),
|
||||
size: 1,
|
||||
resolution: None,
|
||||
mapping: BTreeMap::new(),
|
||||
outputs: BTreeMap::from([("basecolor".to_string(), package.clone())]),
|
||||
};
|
||||
let effect_id = session.doc.project.alloc_id();
|
||||
let material = Effect::new(effect_id, EffectKind::Material(Fill { link: Some(Box::new(link)), ..Fill::default() }));
|
||||
session.doc.project.layers.get_mut(&layer_id).unwrap().content_effects.push(material);
|
||||
|
||||
let renamed = crate::execute(&mut session, "resource.rename", &json!({"name": package, "to": "stone"})).unwrap()["name"].as_str().unwrap().to_string();
|
||||
|
||||
let effect = &session.doc.project.layers[&layer_id].content_effects[0];
|
||||
let EffectKind::Material(fill) = &effect.kind else { panic!("the effect stays a material") };
|
||||
let link = fill.link.as_ref().unwrap();
|
||||
assert_ne!(renamed, package);
|
||||
assert_eq!(link.package, renamed, "the link's package follows the rename");
|
||||
assert_eq!(link.outputs.values().collect::<Vec<_>>(), [&renamed], "the link's cooked outputs follow the rename");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renaming_an_image_a_generator_reads_as_its_grunge_moves_the_grunge_with_it() {
|
||||
use texturecraft_core::{Effect, EffectKind, Generator, GeneratorKind};
|
||||
|
||||
let mut session = crate::sample_session(128, 32).unwrap();
|
||||
let png = texturecraft_formats::gray16_png(1, 1, [0.5].into_iter()).unwrap();
|
||||
let grunge = session.import_resource_bytes("grunge.png", png).unwrap();
|
||||
crate::execute(&mut session, "layer.add.image", &json!({"name": grunge})).unwrap();
|
||||
let layer_id = session.selected_layer().unwrap();
|
||||
let generator = Generator { grunge: Some(Source::image(grunge.clone())), ..Generator::new(GeneratorKind::EdgeWear) };
|
||||
let effect_id = session.doc.project.alloc_id();
|
||||
session.doc.project.layers.get_mut(&layer_id).unwrap().content_effects.push(Effect::new(effect_id, EffectKind::Generator(generator)));
|
||||
|
||||
let renamed = crate::execute(&mut session, "resource.rename", &json!({"name": grunge, "to": "worn"})).unwrap()["name"].as_str().unwrap().to_string();
|
||||
|
||||
let EffectKind::Generator(generator) = &session.doc.project.layers[&layer_id].content_effects[0].kind else { panic!("the effect stays a generator") };
|
||||
assert_ne!(renamed, grunge);
|
||||
assert_eq!(generator.grunge, Some(Source::image(renamed)), "the generator's grunge follows the rename");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_reads_obey_the_remaining_byte_budget() {
|
||||
let path = std::env::temp_dir().join(format!("texturecraft-read-image-{}.png", std::process::id()));
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
//! One row of the Resources Updater: an image resource, its file and how they compare
|
||||
|
||||
use crate::resource_status::ResourceStatus;
|
||||
|
||||
/// An image resource, the file it came from and whether that file changed on disk
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ResourceState {
|
||||
/// The resource's name in the project.
|
||||
pub name: String,
|
||||
/// How the resource compares with its file now.
|
||||
pub status: ResourceStatus,
|
||||
/// The file it was imported from or relinked to (None: made in the app or imported without a path).
|
||||
pub path: Option<String>,
|
||||
/// Why the file could not be checked (with [`ResourceStatus::Missing`]).
|
||||
pub error: Option<String>,
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
//! Whether a resource still matches the file it was imported from
|
||||
|
||||
/// How a resource compares with its file on disk (materials have none). The order is the Resources Updater's
|
||||
/// list order: what needs attention first.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub enum ResourceStatus {
|
||||
/// The file changed since it was read: Update reads it again.
|
||||
Outdated,
|
||||
/// The file is gone, or cannot be read.
|
||||
Missing,
|
||||
/// The file still holds the resource's bytes.
|
||||
UpToDate,
|
||||
/// Made in the app or imported without a file path: there is nothing to compare with.
|
||||
NoSource,
|
||||
/// A linked MaterialCraft package stored in the project, without a source file to compare.
|
||||
Material,
|
||||
}
|
||||
|
||||
impl ResourceStatus {
|
||||
pub const ALL: [ResourceStatus; 5] =
|
||||
[ResourceStatus::Outdated, ResourceStatus::Missing, ResourceStatus::UpToDate, ResourceStatus::NoSource, ResourceStatus::Material];
|
||||
|
||||
/// The id used by the control protocol
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
ResourceStatus::Outdated => "outdated",
|
||||
ResourceStatus::Missing => "missing",
|
||||
ResourceStatus::UpToDate => "upToDate",
|
||||
ResourceStatus::NoSource => "noSource",
|
||||
ResourceStatus::Material => "material",
|
||||
}
|
||||
}
|
||||
|
||||
/// The name shown in the Resources Updater (English; the shell translates it)
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
ResourceStatus::Outdated => "Outdated",
|
||||
ResourceStatus::Missing => "Missing",
|
||||
ResourceStatus::UpToDate => "Up to date",
|
||||
ResourceStatus::NoSource => "No source file",
|
||||
ResourceStatus::Material => "Material",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,395 @@
|
||||
//! The Resources Updater: compare image resources with the files they came from, read changed
|
||||
//! files again and point a resource at another file. Each change is one undo step, and every
|
||||
//! layer, mask and view using a changed resource recomposites; a mesh map imported from a changed
|
||||
//! file is resampled while it still holds what the file gave it.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_core::ResourceSource;
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad};
|
||||
use crate::resource_state::ResourceState;
|
||||
use crate::resource_status::ResourceStatus;
|
||||
use crate::{Result, Session, cmd};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
"resource.status",
|
||||
"Check resources on disk",
|
||||
[],
|
||||
None,
|
||||
"{} → {resources: [{name, status: outdated|missing|upToDate|noSource|material, path?, error?}] (outdated first; material: a stored MaterialCraft package), total, outdated}",
|
||||
always,
|
||||
|s, _| Ok(status(s))
|
||||
),
|
||||
cmd!(
|
||||
"resource.update",
|
||||
"Update resources",
|
||||
[],
|
||||
None,
|
||||
"{names?: [resource name] (default: every outdated resource)} → {updated, failed: [{name, error}]} — reads their files again, one undo step",
|
||||
always,
|
||||
update
|
||||
),
|
||||
cmd!(
|
||||
"resource.relink",
|
||||
"Relink resource",
|
||||
[],
|
||||
None,
|
||||
"{name: image resource, path — an image file (png, jpg, tga, tif, bmp, webp, exr, hdr)} → {name, path} — the resource takes the file's pixels and follows it from now on",
|
||||
always,
|
||||
relink
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Project images and linked MaterialCraft packages, ordered by status and then by name.
|
||||
/// Equal-size files are compared when their modification time changed or is unknown.
|
||||
/// A known time lets later checks reuse the verdict.
|
||||
pub fn resource_states(&mut self) -> Vec<ResourceState> {
|
||||
let mut states = self.compare_resources();
|
||||
let materials = self.material_packages().into_iter();
|
||||
states.extend(materials.map(|name| ResourceState { name, status: ResourceStatus::Material, path: None, error: None }));
|
||||
states.sort_by(|a, b| a.status.cmp(&b.status).then_with(|| a.name.cmp(&b.name)));
|
||||
states
|
||||
}
|
||||
|
||||
/// The packages of linked MaterialCraft materials (fill layers and material effects) the project holds
|
||||
fn material_packages(&self) -> std::collections::BTreeSet<String> {
|
||||
use texturecraft_core::{EffectKind, Fill, LayerKind};
|
||||
|
||||
let package_of = |fill: &Fill| fill.link.as_ref().map(|link| link.package.clone());
|
||||
let mut packages = std::collections::BTreeSet::new();
|
||||
for layer in self.doc.project.layers.values() {
|
||||
if let LayerKind::Fill(fill) = &layer.kind {
|
||||
packages.extend(package_of(fill));
|
||||
}
|
||||
for effect in layer.mask.iter().flat_map(|mask| &mask.effects).chain(&layer.content_effects) {
|
||||
if let EffectKind::Material(fill) = &effect.kind {
|
||||
packages.extend(package_of(fill));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
packages.retain(|name| self.doc.resources.contains_key(name));
|
||||
packages
|
||||
}
|
||||
|
||||
/// Whether `name` is an image resource the Resources Updater lists
|
||||
fn is_image_resource(&self, name: &str) -> bool {
|
||||
self.doc.resources.contains_key(name) && (self.images.contains_key(name) || self.doc.project.resource_sources.contains_key(name))
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn compare_resources(&mut self) -> Vec<ResourceState> {
|
||||
let mut checks = std::mem::take(&mut self.resource_checks);
|
||||
let names: Vec<String> = self.doc.resources.keys().filter(|name| self.is_image_resource(name)).cloned().collect();
|
||||
let mut states = Vec::with_capacity(names.len());
|
||||
for name in names {
|
||||
let (Some(bytes), source) = (self.doc.resources.get(&name), self.doc.project.resource_sources.get(&name)) else { continue };
|
||||
let (status, error) = source.map_or((ResourceStatus::NoSource, None), |source| compare_with_file(&name, source, bytes, &mut checks));
|
||||
states.push(ResourceState { path: source.map(|source| source.path.clone()), name, status, error });
|
||||
}
|
||||
|
||||
checks.retain(|name, _| self.doc.resources.contains_key(name));
|
||||
self.resource_checks = checks;
|
||||
states
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn compare_resources(&mut self) -> Vec<ResourceState> {
|
||||
let sources = &self.doc.project.resource_sources;
|
||||
let browser = "file paths are not available in the browser";
|
||||
let names = self.doc.resources.keys().filter(|name| self.is_image_resource(name));
|
||||
names
|
||||
.map(|name| match sources.get(name) {
|
||||
Some(source) => {
|
||||
ResourceState { name: name.clone(), status: ResourceStatus::Missing, path: Some(source.path.clone()), error: Some(browser.into()) }
|
||||
}
|
||||
None => ResourceState { name: name.clone(), status: ResourceStatus::NoSource, path: None, error: None },
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Stream changed files into one undo step. A mesh map is compared before its first tile is replaced.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn install_reloaded(&mut self, label: &str, files: impl Iterator<Item = crate::reloaded_file::ReloadedFile>) -> Result<Vec<String>> {
|
||||
let mut files = files.peekable();
|
||||
if files.peek().is_none() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
let mut updated = Vec::new();
|
||||
let result = self.edit(label, |session| {
|
||||
let mut slots = std::collections::BTreeMap::new();
|
||||
for file in files {
|
||||
if let Some(slot) = file.source.mesh_map {
|
||||
slots.entry((slot.texture_set, slot.map)).or_insert_with(|| session.mesh_map_matches(slot.texture_set, slot.map));
|
||||
}
|
||||
|
||||
let name = file.name;
|
||||
if crate::fill_alpha::matches_saved_picture(&name, &file.image) {
|
||||
session.library_alphas.insert(name.clone());
|
||||
} else {
|
||||
session.library_alphas.remove(&name);
|
||||
}
|
||||
|
||||
session.images.insert(name.clone(), crate::resource_cmds::decoded(file.image));
|
||||
session.doc.resources.insert(name.clone(), std::sync::Arc::new(file.bytes));
|
||||
session.doc.project.resource_sources.insert(name.clone(), file.source);
|
||||
updated.push(name);
|
||||
}
|
||||
|
||||
for ((texture_set, map), matches) in slots {
|
||||
if matches {
|
||||
let images = session.mesh_map_images(texture_set, map).ok_or_else(|| bad("resource.update", "a mesh map source image is missing"))?;
|
||||
crate::meshmap_cmds::use_images(session, "resource.update", texture_set, map, &images)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
|
||||
if let Err(error) = result {
|
||||
// The edit restored the encoded bytes, so rebuild any cache entries replaced before rollback
|
||||
for name in &updated {
|
||||
self.images.remove(name);
|
||||
}
|
||||
self.sync_images();
|
||||
return Err(error);
|
||||
}
|
||||
|
||||
Ok(updated)
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn mesh_map_images(
|
||||
&self,
|
||||
texture_set: usize,
|
||||
map: texturecraft_core::BakedMap,
|
||||
) -> Option<std::collections::BTreeMap<u32, std::sync::Arc<texturecraft_compose::ImageRes>>> {
|
||||
let mut images = std::collections::BTreeMap::new();
|
||||
for (name, source) in &self.doc.project.resource_sources {
|
||||
if let Some(slot) = source.mesh_map.filter(|slot| slot.texture_set == texture_set && slot.map == map) {
|
||||
images.insert(slot.tile, self.images.get(name)?.clone());
|
||||
}
|
||||
}
|
||||
|
||||
Some(images)
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn mesh_map_matches(&self, texture_set: usize, map: texturecraft_core::BakedMap) -> bool {
|
||||
let Some(current) = self.doc.baked.get(&texture_set).and_then(|baked| baked.maps.get(&map)) else { return false };
|
||||
let Some(images) = self.mesh_map_images(texture_set, map) else { return false };
|
||||
|
||||
crate::mesh_map_sampler::MeshMapSampler::new(self, "resource.update", texture_set, map, &images).is_ok_and(|sampler| sampler.matches(current))
|
||||
}
|
||||
}
|
||||
|
||||
/// How `stored` (a resource's bytes) compares with the file `source` names now, reusing the
|
||||
/// remembered verdict in `checks` while the file's size and time stay the same
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn compare_with_file(
|
||||
name: &str,
|
||||
source: &ResourceSource,
|
||||
stored: &std::sync::Arc<Vec<u8>>,
|
||||
checks: &mut std::collections::HashMap<String, crate::resource_check::ResourceCheck>,
|
||||
) -> (ResourceStatus, Option<String>) {
|
||||
let path = std::path::Path::new(&source.path);
|
||||
let metadata = match std::fs::metadata(path) {
|
||||
Ok(metadata) if metadata.is_file() => metadata,
|
||||
Ok(_) => return (ResourceStatus::Missing, Some(format!("{} is not a regular file", source.path))),
|
||||
Err(error) => return (ResourceStatus::Missing, Some(format!("{}: {error}", source.path))),
|
||||
};
|
||||
|
||||
let size = metadata.len();
|
||||
if size != stored.len() as u64 {
|
||||
return (ResourceStatus::Outdated, None);
|
||||
}
|
||||
|
||||
let modified_ms = modified_ms(&metadata);
|
||||
if modified_ms != 0 && modified_ms == source.modified_ms {
|
||||
return (ResourceStatus::UpToDate, None);
|
||||
}
|
||||
|
||||
if let Some(check) = checks.get(name)
|
||||
&& check.holds_for(&source.path, size, modified_ms, stored)
|
||||
{
|
||||
return (check.status, None);
|
||||
}
|
||||
|
||||
// A newer time alone is not a change: the file may have been saved again unchanged
|
||||
let status = match file_matches(path, stored) {
|
||||
Ok(true) => ResourceStatus::UpToDate,
|
||||
Ok(false) => ResourceStatus::Outdated,
|
||||
Err(error) => return (ResourceStatus::Missing, Some(error.to_string())),
|
||||
};
|
||||
if modified_ms == 0 {
|
||||
// An unknown time cannot establish that the next check sees the same file contents
|
||||
checks.remove(name);
|
||||
} else {
|
||||
let bytes = std::sync::Arc::downgrade(stored);
|
||||
checks.insert(name.to_string(), crate::resource_check::ResourceCheck { path: source.path.clone(), size, modified_ms, bytes, status });
|
||||
}
|
||||
|
||||
(status, None)
|
||||
}
|
||||
|
||||
/// Compare without allocating a second copy of the resource. Read to the checked end to detect I/O errors and growth.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn file_matches(path: &std::path::Path, stored: &[u8]) -> Result<bool> {
|
||||
use std::io::{ErrorKind, Read};
|
||||
|
||||
const CMD: &str = "resource.status";
|
||||
const CHUNK_BYTES: usize = 32 * 1024;
|
||||
let read_error = |error| bad(CMD, format!("cannot read {}: {error}", path.display()));
|
||||
let too_large = || bad(CMD, format!("{} is too large (limit {} bytes)", path.display(), crate::resource_cmds::MAX_BYTES));
|
||||
let mut file = crate::resource_cmds::open_resource_file(CMD, path)?;
|
||||
let len = file.metadata().map_err(read_error)?.len();
|
||||
if len > crate::resource_cmds::MAX_BYTES as u64 {
|
||||
return Err(too_large());
|
||||
}
|
||||
|
||||
let mut chunk = [0; CHUNK_BYTES];
|
||||
let mut equal = len == stored.len() as u64;
|
||||
for start in (0..len as usize).step_by(CHUNK_BYTES) {
|
||||
let end = (start + CHUNK_BYTES).min(len as usize);
|
||||
let part = &mut chunk[..end - start];
|
||||
match file.read_exact(part) {
|
||||
Ok(()) => equal = equal && stored.get(start..end) == Some(part),
|
||||
Err(error) if error.kind() == ErrorKind::UnexpectedEof => return Ok(false),
|
||||
Err(error) => return Err(read_error(error)),
|
||||
}
|
||||
}
|
||||
|
||||
if file.read(&mut [0]).map_err(read_error)? > 0 {
|
||||
return Err(too_large());
|
||||
}
|
||||
|
||||
Ok(equal)
|
||||
}
|
||||
|
||||
/// A file's modification time in milliseconds since the Unix epoch (0 when the system has none)
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn modified_ms(metadata: &std::fs::Metadata) -> u64 {
|
||||
let since_epoch = metadata.modified().ok().and_then(|modified| modified.duration_since(std::time::UNIX_EPOCH).ok());
|
||||
since_epoch.map_or(0, |elapsed| u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX))
|
||||
}
|
||||
|
||||
/// The record for an image about to be read from `path`: its absolute path and its current
|
||||
/// modification time, taken before reading so a write during the read still shows as a change
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn file_source(path: &str) -> ResourceSource {
|
||||
let absolute = std::path::absolute(path).ok().and_then(|absolute| absolute.to_str().map(str::to_string)).unwrap_or_else(|| path.to_string());
|
||||
let modified_ms = std::fs::metadata(path).map_or(0, |metadata| modified_ms(&metadata));
|
||||
ResourceSource { path: absolute, modified_ms, mesh_map: None }
|
||||
}
|
||||
|
||||
/// The browser reads no paths; the record keeps the name it was given
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub(crate) fn file_source(path: &str) -> ResourceSource {
|
||||
ResourceSource { path: path.to_string(), modified_ms: 0, mesh_map: None }
|
||||
}
|
||||
|
||||
fn status(s: &mut Session) -> Value {
|
||||
let states = s.resource_states();
|
||||
let outdated = states.iter().filter(|state| state.status == ResourceStatus::Outdated).count();
|
||||
let resources: Vec<Value> = states
|
||||
.iter()
|
||||
.map(|state| {
|
||||
let mut row = json!({"name": state.name, "status": state.status.id()});
|
||||
if let Some(path) = &state.path {
|
||||
row["path"] = json!(path);
|
||||
}
|
||||
if let Some(error) = &state.error {
|
||||
row["error"] = json!(error);
|
||||
}
|
||||
|
||||
row
|
||||
})
|
||||
.collect();
|
||||
|
||||
json!({"resources": resources, "total": states.len(), "outdated": outdated})
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn update(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "resource.update";
|
||||
|
||||
let names: Vec<String> = match p.get("names") {
|
||||
None | Some(Value::Null) => s.resource_states().into_iter().filter(|state| state.status == ResourceStatus::Outdated).map(|state| state.name).collect(),
|
||||
Some(Value::Array(names)) => {
|
||||
names.iter().map(|name| name.as_str().map(str::to_string).ok_or_else(|| bad(CMD, "`names` must be resource names"))).collect::<Result<_>>()?
|
||||
}
|
||||
Some(_) => return Err(bad(CMD, "`names` must be an array of resource names")),
|
||||
};
|
||||
|
||||
// Validate the complete selection before opening files
|
||||
let mut selected = Vec::new();
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
for name in names {
|
||||
let bytes = s.doc.resources.get(&name).ok_or_else(|| bad(CMD, format!("no resource `{name}`")))?;
|
||||
let Some(source) = s.doc.project.resource_sources.get(&name) else {
|
||||
let reason = if s.images.contains_key(&name) {
|
||||
format!("`{name}` has no source file: relink it to a file first")
|
||||
} else {
|
||||
format!("`{name}` has no source file: only image resources can be relinked")
|
||||
};
|
||||
return Err(bad(CMD, reason));
|
||||
};
|
||||
|
||||
if seen.insert(name.clone()) {
|
||||
let decoded = s.images.contains_key(&name);
|
||||
selected.push((name, source.clone(), bytes.clone(), decoded));
|
||||
}
|
||||
}
|
||||
|
||||
let mut failed = Vec::new();
|
||||
let files = selected.into_iter().filter_map(|(name, source, stored, decoded)| {
|
||||
match crate::reloaded_file::ReloadedFile::read_changed(CMD, &name, &source, &stored, decoded) {
|
||||
Ok(file) => file,
|
||||
Err(error) => {
|
||||
failed.push(json!({"name": name, "error": error.to_string()}));
|
||||
None
|
||||
}
|
||||
}
|
||||
});
|
||||
let updated = s.install_reloaded("Update resources", files)?;
|
||||
|
||||
if updated.is_empty() && !failed.is_empty() {
|
||||
let reasons: Vec<&str> = failed.iter().filter_map(|failure| failure["error"].as_str()).collect();
|
||||
return Err(bad(CMD, format!("nothing was updated: {}", reasons.join("; "))));
|
||||
}
|
||||
|
||||
Ok(json!({"updated": updated, "failed": failed}))
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn relink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "resource.relink";
|
||||
|
||||
let name = crate::commands::strp(p, "name").ok_or_else(|| bad(CMD, "`name` is required"))?.to_string();
|
||||
let path = crate::commands::strp(p, "path").ok_or_else(|| bad(CMD, "`path` is required"))?;
|
||||
if !s.is_image_resource(&name) {
|
||||
return Err(bad(CMD, format!("no image resource `{name}`")));
|
||||
}
|
||||
|
||||
// A relinked mesh map file still feeds its mesh map
|
||||
let mut file = crate::reloaded_file::ReloadedFile::read(CMD, name.clone(), path)?;
|
||||
file.source.mesh_map = s.doc.project.resource_sources.get(&name).and_then(|source| source.mesh_map);
|
||||
let path = file.source.path.clone();
|
||||
s.install_reloaded("Relink resource", std::iter::once(file))?;
|
||||
|
||||
Ok(json!({"name": name, "path": path}))
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn update(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
Err(bad("resource.update", "file paths are not available in the browser"))
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn relink(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
Err(bad("resource.relink", "file paths are not available in the browser"))
|
||||
}
|
||||
@@ -33,6 +33,9 @@ pub struct Document {
|
||||
pub resources: BTreeMap<String, Arc<Vec<u8>>>,
|
||||
/// High-definition meshes and cage for baking (saved inside the project)
|
||||
pub bake_meshes: crate::BakeMeshes,
|
||||
/// Skew and cage paint bounds since each set's last Auto-rebake. Undo restores the bounds
|
||||
/// with their maps. The project file omits these bounds.
|
||||
pub(crate) painted_regions: BTreeMap<usize, crate::bake::PaintedRegion>,
|
||||
}
|
||||
|
||||
/// Derived per-texture-set data (rebuilt when the mesh or resolution changes).
|
||||
@@ -425,9 +428,15 @@ pub struct Session {
|
||||
pub project_id: u64,
|
||||
/// The mesh with its own UVs (`mesh` maps UV-tiled sets into their atlas).
|
||||
pub(crate) source: Arc<Mesh>,
|
||||
/// Fingerprint of the bake inputs in `source`, computed on first use
|
||||
pub(crate) low_poly_fingerprint: std::sync::OnceLock<u64>,
|
||||
/// Fingerprint of the packed mesh file, computed only for bakes that read its material colors.
|
||||
pub(crate) low_material_file_fingerprint: std::sync::OnceLock<u64>,
|
||||
/// Skew and cage strokes so far
|
||||
pub(crate) painted_strokes: u64,
|
||||
pub bvh: Arc<Bvh>,
|
||||
/// Original mesh file (saved inside the project); None for built-in meshes.
|
||||
pub mesh_source: Option<(String, Vec<u8>)>,
|
||||
pub mesh_source: Option<(String, Arc<Vec<u8>>)>,
|
||||
pub caches: Vec<SetCache>,
|
||||
pub(crate) undo: Vec<(String, Document)>,
|
||||
pub(crate) redo: Vec<(String, Document)>,
|
||||
@@ -451,6 +460,8 @@ pub struct Session {
|
||||
pub solo: Option<crate::Solo>,
|
||||
/// The live bake preview while the app bakes (see [`crate::bake_preview`]).
|
||||
pub bake_preview: Option<crate::bake_preview::BakePreview>,
|
||||
/// The latest bake, map by map (the Baking Log)
|
||||
pub bake_log: crate::bake::BakeLog,
|
||||
/// Viewport size (pixels) used by scripted strokes.
|
||||
pub viewport: Vec2,
|
||||
pub(crate) stroke: Option<ActiveStroke>,
|
||||
@@ -462,6 +473,9 @@ pub struct Session {
|
||||
pub images: texturecraft_compose::ImageStore,
|
||||
/// Resource names whose decoded pixels match a library alpha.
|
||||
pub(crate) library_alphas: BTreeSet<String>,
|
||||
/// Resources whose file was read for the Resources Updater, by name: the verdict stays while the file's size and time do
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) resource_checks: std::collections::HashMap<String, crate::resource_check::ResourceCheck>,
|
||||
/// Temporary texel mask limiting paint strokes (not saved, not in the history).
|
||||
pub quick_mask: crate::quick_mask::QuickMask,
|
||||
/// A path sublayer is being repainted from its paths (the only way to paint into one).
|
||||
@@ -478,6 +492,9 @@ pub struct Session {
|
||||
/// (see [`crate::commands::check_enabled`]).
|
||||
pub project_open: bool,
|
||||
pub modified: bool,
|
||||
/// Edits to saved data, independent of viewport and tool changes.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) save_revision: u64,
|
||||
/// Bumps on every document change.
|
||||
pub revision: u64,
|
||||
/// Messages for the UI (status bar / toasts).
|
||||
@@ -522,9 +539,12 @@ impl Session {
|
||||
mesh_id: next_mesh_id(),
|
||||
project_id: next_mesh_id(),
|
||||
source,
|
||||
low_poly_fingerprint: Default::default(),
|
||||
low_material_file_fingerprint: Default::default(),
|
||||
painted_strokes: 0,
|
||||
mesh,
|
||||
bvh: Arc::new(bvh),
|
||||
mesh_source,
|
||||
mesh_source: mesh_source.map(|(extension, bytes)| (extension, Arc::new(bytes))),
|
||||
caches,
|
||||
undo: Vec::new(),
|
||||
redo: Vec::new(),
|
||||
@@ -540,12 +560,15 @@ impl Session {
|
||||
view_image: None,
|
||||
solo: None,
|
||||
bake_preview: None,
|
||||
bake_log: Default::default(),
|
||||
viewport: Vec2::new(1280.0, 800.0),
|
||||
stroke: None,
|
||||
clipboard: None,
|
||||
blending_clipboard: None,
|
||||
images: Default::default(),
|
||||
library_alphas: BTreeSet::new(),
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
resource_checks: std::collections::HashMap::new(),
|
||||
quick_mask: Default::default(),
|
||||
painting_paths: false,
|
||||
path_cache: None,
|
||||
@@ -554,6 +577,8 @@ impl Session {
|
||||
path: None,
|
||||
project_open: true,
|
||||
modified: false,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
save_revision: 0,
|
||||
revision: 1,
|
||||
log: crate::log::SessionLog::new(),
|
||||
log_id: next_mesh_id(),
|
||||
@@ -583,6 +608,10 @@ impl Session {
|
||||
pub fn switch_to(&mut self, mut next: Session) {
|
||||
// Invalidate caches even when both projects were loaded with the same revision
|
||||
next.revision = self.revision.wrapping_add(1);
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
next.save_revision = self.save_revision.wrapping_add(1);
|
||||
}
|
||||
|
||||
next.viewport = self.viewport;
|
||||
next.export_presets = std::mem::take(&mut self.export_presets);
|
||||
@@ -635,6 +664,7 @@ impl Session {
|
||||
pixels: PixelStore::default(),
|
||||
baked: BTreeMap::new(),
|
||||
resources: BTreeMap::new(),
|
||||
painted_regions: Default::default(),
|
||||
},
|
||||
mesh,
|
||||
mesh_source,
|
||||
@@ -735,8 +765,7 @@ impl Session {
|
||||
self.path_steps = Default::default();
|
||||
}
|
||||
|
||||
self.modified = true;
|
||||
self.revision = self.revision.wrapping_add(1);
|
||||
self.mark_modified();
|
||||
if !(merge && self.undo.last().is_some_and(|(l, _)| l == label)) {
|
||||
self.undo.push((label.to_string(), before));
|
||||
}
|
||||
@@ -747,8 +776,7 @@ impl Session {
|
||||
|
||||
/// A change from `other` to the current document that is not an undo step (a path preview)
|
||||
pub(crate) fn changed_without_history(&mut self, other: &Document) {
|
||||
self.modified = true;
|
||||
self.revision = self.revision.wrapping_add(1);
|
||||
self.mark_modified();
|
||||
self.invalidate_changed(other);
|
||||
}
|
||||
|
||||
@@ -874,14 +902,23 @@ impl Session {
|
||||
|
||||
/// Mark the document changed and every texture set dirty.
|
||||
pub fn touched(&mut self) {
|
||||
self.modified = true;
|
||||
self.revision = self.revision.wrapping_add(1);
|
||||
self.mark_modified();
|
||||
self.sync_caches();
|
||||
for c in &mut self.caches {
|
||||
c.invalidate_all();
|
||||
}
|
||||
}
|
||||
|
||||
/// Mark saved data changed without invalidating the texture sets.
|
||||
pub fn mark_modified(&mut self) {
|
||||
self.modified = true;
|
||||
self.revision = self.revision.wrapping_add(1);
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
self.save_revision = self.save_revision.wrapping_add(1);
|
||||
}
|
||||
}
|
||||
|
||||
/// Make caches agree with the project's texture sets (resolution or channel changes).
|
||||
pub fn sync_caches(&mut self) {
|
||||
let sets = self.doc.project.texture_sets.clone();
|
||||
@@ -964,6 +1001,7 @@ impl Session {
|
||||
let (label, restored) = self.undo.pop().ok_or_else(|| EngineError::Other("nothing to undo".into()))?;
|
||||
let current = std::mem::replace(&mut self.doc, restored);
|
||||
self.after_history(¤t);
|
||||
self.forget_replaced_images(¤t);
|
||||
self.redo.push((label.clone(), current));
|
||||
self.sync_images();
|
||||
Ok(label)
|
||||
@@ -984,19 +1022,21 @@ impl Session {
|
||||
let (label, restored) = self.redo.pop().ok_or_else(|| EngineError::Other("nothing to redo".into()))?;
|
||||
let current = std::mem::replace(&mut self.doc, restored);
|
||||
self.after_history(¤t);
|
||||
self.forget_replaced_images(¤t);
|
||||
self.undo.push((label.clone(), current));
|
||||
self.sync_images();
|
||||
Ok(label)
|
||||
}
|
||||
|
||||
fn after_history(&mut self, other: &Document) {
|
||||
self.follow_renamed_resources(other);
|
||||
|
||||
// Pending operations may still hold layer IDs from the discarded snapshot
|
||||
self.doc.project.next_id = self.doc.project.next_id.max(other.project.next_id);
|
||||
self.modified = true;
|
||||
self.mark_modified();
|
||||
|
||||
// Layers picked together belong to the stack they were picked in
|
||||
self.multi.clear();
|
||||
self.revision = self.revision.wrapping_add(1);
|
||||
self.invalidate_changed(other);
|
||||
|
||||
// An undone add or duplicate takes the selected effect away
|
||||
@@ -1013,6 +1053,38 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
/// The image names the tools and the 2D view read, which a resource rename follows
|
||||
pub(crate) fn tool_images_mut(&mut self) -> impl Iterator<Item = &mut String> {
|
||||
[
|
||||
self.tool.stencil.as_mut().map(|stencil| &mut stencil.image),
|
||||
self.tool.brush.alpha_image.as_mut(),
|
||||
self.tool.mask_image.as_mut(),
|
||||
self.view_image.as_mut(),
|
||||
]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
}
|
||||
|
||||
/// Points tool images at a resource's name on this side of an undone or redone rename
|
||||
fn follow_renamed_resources(&mut self, other: &Document) {
|
||||
let names: Vec<String> = self.tool_images_mut().map(|name| name.clone()).collect();
|
||||
let renames: Vec<(String, String)> = names
|
||||
.into_iter()
|
||||
.filter(|name| !self.doc.resources.contains_key(name))
|
||||
.filter_map(|name| {
|
||||
let bytes = other.resources.get(&name)?;
|
||||
let to = self.doc.resources.iter().find(|(_, here)| Arc::ptr_eq(here, bytes)).map(|(here, _)| here.clone())?;
|
||||
Some((name, to))
|
||||
})
|
||||
.collect();
|
||||
|
||||
for (name, to) in renames {
|
||||
for tool_image in self.tool_images_mut().filter(|tool_image| **tool_image == name) {
|
||||
tool_image.clone_from(&to);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------------------------
|
||||
// Compositing
|
||||
|
||||
|
||||
Loaded 100 of 286 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user