mirror of
https://github.com/storytold/texturecraft.git
synced 2026-11-24 16:30:46 +01:00
amend
This commit is contained in:
commit
0ecfa244af
238 files changed
+20004
-3064
No files matched your search
@@ -25,6 +25,8 @@ jobs:
|
||||
craft-fonts-ref: aced4137c022f1f587624d48e81ec77e1914a9cc
|
||||
os: '["ubuntu-24.04","windows-latest"]'
|
||||
toolchain: "1.96.0"
|
||||
# xtask ci runs cargo test (including doctests), not cargo nextest.
|
||||
tools: ""
|
||||
packages: >-
|
||||
libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev libgl1-mesa-dev
|
||||
libgtk-3-dev
|
||||
@@ -0,0 +1,28 @@
|
||||
name: House rules
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- AGENTS.md
|
||||
- CLAUDE.md
|
||||
- .github/workflows/house-rules.yml
|
||||
pull_request:
|
||||
paths:
|
||||
- AGENTS.md
|
||||
- CLAUDE.md
|
||||
- .github/workflows/house-rules.yml
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: house-rules-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
house-rules:
|
||||
uses: storytold/craft-common-actions/.github/workflows/house-rules.yml@main
|
||||
with:
|
||||
rust: true
|
||||
@@ -1,3 +1,56 @@
|
||||
<!-- craft-house-rules:start core source=dde09ea31e2e457f5b4653a6e76f7cdf55944bdf sha256=540e6cea75d12d0710c3dca89658328e81e508ecef102446ca5bb95b7c0b92bb -->
|
||||
## House rules
|
||||
|
||||
These apply in every Craft repository. A later rule may be stricter, not weaker. The source is `standards/house-rules-core.md` in `storytold/craft-contrib`. Propose changes there, not in a copy.
|
||||
|
||||
1. **A person is accountable.** Whoever runs an agent answers for what it opens and for its review comments.
|
||||
2. **Check, then claim.** Before writing code, read the issue comments, search pull requests for `#N` and the keywords, and check recent commits on `main`. Comment on the issue first. Release a claim you will not finish.
|
||||
3. **Verify, don't guess.** Open a definition before using it. Confirm the cause in the code, even when someone names a location.
|
||||
4. **Keep fixes narrow and tested.** Fix what the issue describes, where the bug is. Add a test that fails without the fix.
|
||||
5. **Review the diff before opening a pull request.** Identifiers exist as used, the test fails without the fix, nothing unrelated changed, and the description is true.
|
||||
6. **Look for a better pull request.** If another fixes the same thing, close yours when it is better or equal, and say why.
|
||||
7. **Report only what ran.** Say what you tested and what you could not run. Without a local build or test, say so and rely on CI before marking ready.
|
||||
8. **`main` changes through a pull request.** Do not push to it. Branch protection enforces this. There is no exception.
|
||||
9. **Stop and ask only about** licensing outside the allowlist, publishing, releases, a new remote, secrets, spending money, destructive git, and anything else hard to undo. Otherwise keep working. `plan/` is a gitignored notebook, not rules. Without it, do not ask for it and do not stop.
|
||||
10. **Keep secrets and personal details out** of the repository, logs and requests.
|
||||
11. **CI stays shared.** Workflows call `storytold/craft-common-actions`. Do not change CI in a feature or fix pull request. If CI cannot cover a change, open an issue there.
|
||||
12. **Guards say why.** A check that looks removable says what it prevents. Read that before changing it.
|
||||
13. **Instructions must be readable by everyone.** No notes about one machine, and no links to files a reader cannot open. `craftrules` is retired. Do not link to it.
|
||||
14. **Keep pull requests moving.** Concurrent pull requests are fine; unanswered actionable feedback is not. Respond in 7 days, a reminder at 14, closure eligible at 30, from when an actionable request waits on the author. Suggestions and unconfirmed bot findings do not start the clock. A fix, explanation or agreed plan resets it; unrelated activity does not. Waiting on a reviewer or maintainer pauses it and does not count against the author. A maintainer decides closure; it is never automatic. Reuse search results, do not poll, and stop at a rate limit.
|
||||
15. **No agent attribution.** A pull request does not say an agent wrote it. A repository rule may not require that.
|
||||
<!-- craft-house-rules:end -->
|
||||
<!-- craft-house-rules:start rust source=dde09ea31e2e457f5b4653a6e76f7cdf55944bdf sha256=387e0ccb4b49e567f60951d7d6fff7305054c89f43ad812b9993dc7c38528013 -->
|
||||
## Rust Craft repositories
|
||||
|
||||
These apply to native Craft apps and to shared Rust libraries. Select them by repository type. A repository that merely contains some Rust does not take this block. Rules later in a repository's file may be stricter, but not weaker. The source is `standards/house-rules-rust.md` in [storytold/craft-contrib](https://github.com/storytold/craft-contrib).
|
||||
|
||||
1. **Never crash.** Non-test code does not panic and has no `unsafe`, except where the repository file names an exception. Return errors, treat input as hostile, and bound recursion and allocations. New production crate roots copy the `deny` attribute from an existing crate: `clippy::unwrap_used`, `clippy::expect_used`, `clippy::panic`, `clippy::unimplemented`, `clippy::todo`, `clippy::unreachable`. Every crash fix comes with a test that panicked before the fix.
|
||||
2. **Clean room.** Learn from observed behaviour and public specifications. Do not copy another product's code, assets, strings or artwork. Check a dependency's licence before adding it.
|
||||
3. **Assets and fonts.** Every asset is original or suitably licensed, and is recorded in `ATTRIBUTION.md` in the same change. Font files live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), not in the app repository.
|
||||
4. **Rust only for native Craft apps.** No handwritten JavaScript or TypeScript, and no Tauri, Electron or webview shell, in those apps. Shared tooling follows its documented technical scope and maintainer-approved exceptions. Craft PR Review's existing Tauri and TypeScript UI is one such exception. It does not relax this rule for native apps. Preserve any existing web build.
|
||||
5. **Time goes through `chrono`.** Do not hand-roll calendar conversion. For dates beyond what `chrono` can represent, follow [standards/time.md](https://github.com/storytold/craft-contrib/blob/main/standards/time.md).
|
||||
6. **Contributor credits.** Add or edit only your own person's entry in `contributors/people.toml`, and only after asking them. Never guess a name or hand-edit `contributors.json`.
|
||||
|
||||
## Licence allowlist
|
||||
|
||||
Dependencies and assets use SPDX identifiers. An expression is allowed when every identifier is in this list. A repository may name a shorter list. It may not add an identifier here by editing its own copy of these rules.
|
||||
|
||||
- `ISC`
|
||||
- `MIT`
|
||||
- `BSD-2-Clause`
|
||||
- `BSD-3-Clause`
|
||||
- `Apache-2.0`
|
||||
- `OFL-1.1`
|
||||
- `Ubuntu-font-1.0`
|
||||
- `Bitstream-Vera`
|
||||
- `CC0-1.0`
|
||||
- `CC-BY-4.0`
|
||||
- `CC-BY-SA-4.0`
|
||||
- `LicenseRef-Public-Domain`
|
||||
|
||||
`LicenseRef-Storyteller-Trademark` is not in this list. It covers Storyteller brand marks only, where a repository already says so.
|
||||
<!-- craft-house-rules:end -->
|
||||
|
||||
# AGENTS.md: guide for AI agents and contributors
|
||||
|
||||
TextureCraft is an open-source, native 3D texture painter: a clean-room implementation of the
|
||||
@@ -10,10 +63,7 @@ PdfCraft, EffectCraft, DesignCraft) in user-facing text: UI, window titles, Abou
|
||||
release names, docs prose. Machine names stay lowercase: crates (`texturecraft-*`), binaries, file
|
||||
names, ids (`ai.storyteller.texturecraft`), the native project extension `.tcraft`.
|
||||
|
||||
Standards and learnings shared across the crafting apps live in `../craftrules` (checked out next
|
||||
to this repo, or `storytold/craftrules`). Read its `AGENTS.md` at the start of a session, follow its
|
||||
standards, and contribute reusable learnings back there. Shared code goes only in craft-libs
|
||||
(`standards/shared-libraries.md`); otherwise copy, don't depend.
|
||||
Shared code goes only in craft-libs; otherwise copy, don't depend.
|
||||
|
||||
The goal is 1:1 parity with Substance 3D Painter's workflow (same panels, menus, shortcuts, layer
|
||||
stack semantics and export conventions) with better performance, every feature drivable by agents,
|
||||
@@ -98,7 +148,7 @@ as a clean-room implementation, in code, docs and commits.
|
||||
|
||||
People trust TextureCraft with hours of painting. A malformed mesh or project, a bad command or MCP
|
||||
param, an odd keystroke or a full disk must produce an error the user or agent can act on, never a
|
||||
panic. The shared standard is `../craftrules/standards/never-crash.md`.
|
||||
panic.
|
||||
|
||||
- Non-test code never panics: no `unwrap()`, `expect()`, `panic!`, `unreachable!`, `todo!` or
|
||||
`unimplemented!`. Every production crate root carries
|
||||
@@ -176,6 +226,6 @@ after every arc of work that builds and passes.
|
||||
|
||||
- `ROADMAP.md`: milestones, parity estimate and remaining effort.
|
||||
- `docs/parity.md`: generated Painter menu coverage.
|
||||
- `docs/releasing.md` and `../craftrules/release/playbook.md`: release builds and signing.
|
||||
- `plan/` (local, gitignored): execution plan and notes.
|
||||
- `docs/releasing.md`: release builds and signing.
|
||||
- `plan/` is an optional gitignored notebook (execution notes). Do not ask for it and do not stop when it is absent.
|
||||
- `log/` (local, gitignored): the dev log.
|
||||
@@ -1,5 +1 @@
|
||||
# TextureCraft: instructions for Claude
|
||||
|
||||
Read [`AGENTS.md`](AGENTS.md) first: it is the guide for every agent working in this repository
|
||||
(workspace map, golden rules including the asset and attribution rules, the definition of done).
|
||||
Then read `../craftrules/AGENTS.md` for the standards shared by all Crafting Apps.
|
||||
@AGENTS.md
|
||||
Generated
+541
-9
@@ -412,6 +412,12 @@ version = "0.22.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
|
||||
|
||||
[[package]]
|
||||
name = "base64"
|
||||
version = "0.23.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
|
||||
|
||||
[[package]]
|
||||
name = "bit-set"
|
||||
version = "0.10.0"
|
||||
@@ -448,6 +454,15 @@ dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "block-buffer"
|
||||
version = "0.10.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
|
||||
dependencies = [
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "block2"
|
||||
version = "0.5.1"
|
||||
@@ -691,6 +706,16 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "core-foundation"
|
||||
version = "0.10.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6"
|
||||
dependencies = [
|
||||
"core-foundation-sys",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "core-foundation-sys"
|
||||
version = "0.8.7"
|
||||
@@ -704,7 +729,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c07782be35f9e1140080c6b96f0d44b739e2278479f64e02fdab4e32dfd8b081"
|
||||
dependencies = [
|
||||
"bitflags 1.3.2",
|
||||
"core-foundation",
|
||||
"core-foundation 0.9.4",
|
||||
"core-graphics-types",
|
||||
"foreign-types",
|
||||
"libc",
|
||||
@@ -717,19 +742,41 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf"
|
||||
dependencies = [
|
||||
"bitflags 1.3.2",
|
||||
"core-foundation",
|
||||
"core-foundation 0.9.4",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cpufeatures"
|
||||
version = "0.2.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-dialogs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"objc2 0.6.5",
|
||||
"objc2-app-kit 0.3.2",
|
||||
"objc2-foundation 0.3.2",
|
||||
"raw-window-handle",
|
||||
"rfd",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-fonts-build"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
|
||||
|
||||
[[package]]
|
||||
name = "craft-i18n"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
|
||||
dependencies = [
|
||||
"fixed_decimal",
|
||||
"icu_decimal",
|
||||
@@ -749,10 +796,44 @@ dependencies = [
|
||||
"writeable",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-keymap"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
|
||||
dependencies = [
|
||||
"egui",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-menu"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
|
||||
dependencies = [
|
||||
"craft-keymap",
|
||||
"craft-quit",
|
||||
"egui",
|
||||
"muda",
|
||||
"objc2 0.6.5",
|
||||
"objc2-app-kit 0.3.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-quit"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
|
||||
dependencies = [
|
||||
"dispatch2",
|
||||
"egui",
|
||||
"objc2 0.6.5",
|
||||
"objc2-app-kit 0.3.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
|
||||
dependencies = [
|
||||
"craft-fonts-build",
|
||||
"craft-i18n",
|
||||
@@ -770,10 +851,36 @@ dependencies = [
|
||||
"web-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-update"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"dunce",
|
||||
"egui",
|
||||
"flate2",
|
||||
"getrandom 0.3.4",
|
||||
"image",
|
||||
"log",
|
||||
"plist",
|
||||
"semver",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"tar",
|
||||
"tempfile",
|
||||
"ureq",
|
||||
"verifysign",
|
||||
"winreg",
|
||||
"winsafe",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-window"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
|
||||
dependencies = [
|
||||
"egui",
|
||||
"objc2 0.6.5",
|
||||
@@ -790,6 +897,15 @@ dependencies = [
|
||||
"cfg-if",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crossbeam-channel"
|
||||
version = "0.5.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1"
|
||||
dependencies = [
|
||||
"crossbeam-utils",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crossbeam-deque"
|
||||
version = "0.8.8"
|
||||
@@ -821,6 +937,16 @@ version = "0.2.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
|
||||
|
||||
[[package]]
|
||||
name = "crypto-common"
|
||||
version = "0.1.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
|
||||
dependencies = [
|
||||
"generic-array",
|
||||
"typenum",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cursor-icon"
|
||||
version = "1.2.0"
|
||||
@@ -861,6 +987,22 @@ dependencies = [
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "deranged"
|
||||
version = "0.5.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e"
|
||||
|
||||
[[package]]
|
||||
name = "digest"
|
||||
version = "0.10.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
|
||||
dependencies = [
|
||||
"block-buffer",
|
||||
"crypto-common",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dispatch"
|
||||
version = "0.2.0"
|
||||
@@ -920,6 +1062,12 @@ version = "0.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76"
|
||||
|
||||
[[package]]
|
||||
name = "dunce"
|
||||
version = "1.0.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"
|
||||
|
||||
[[package]]
|
||||
name = "dyn-clone"
|
||||
version = "1.0.20"
|
||||
@@ -1252,6 +1400,16 @@ version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b97b65636e5b9ef369943878ac74335ba1c55c1cb6adbf1e2c293c624248d693"
|
||||
|
||||
[[package]]
|
||||
name = "filetime"
|
||||
version = "0.2.29"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "find-msvc-tools"
|
||||
version = "0.1.14"
|
||||
@@ -1447,6 +1605,16 @@ dependencies = [
|
||||
"slab",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "generic-array"
|
||||
version = "0.14.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
|
||||
dependencies = [
|
||||
"typenum",
|
||||
"version_check",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gethostname"
|
||||
version = "1.1.0"
|
||||
@@ -1457,6 +1625,17 @@ dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "getrandom"
|
||||
version = "0.2.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"wasi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "getrandom"
|
||||
version = "0.3.4"
|
||||
@@ -1728,6 +1907,22 @@ version = "0.4.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
|
||||
|
||||
[[package]]
|
||||
name = "http"
|
||||
version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"itoa",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "httparse"
|
||||
version = "1.10.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
|
||||
|
||||
[[package]]
|
||||
name = "iana-time-zone"
|
||||
version = "0.1.65"
|
||||
@@ -2103,6 +2298,16 @@ dependencies = [
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "keyboard-types"
|
||||
version = "0.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0fbe853b403ae61a04233030ae8a79d94975281ed9770a1f9e246732b534b28d"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "khronos-egl"
|
||||
version = "6.0.0"
|
||||
@@ -2322,6 +2527,24 @@ dependencies = [
|
||||
"pxfm",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "muda"
|
||||
version = "0.21.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4340e89c178916e62879c5c36b7f699019369be413e496178a6983ce91b8bc03"
|
||||
dependencies = [
|
||||
"crossbeam-channel",
|
||||
"dpi",
|
||||
"keyboard-types",
|
||||
"objc2 0.6.5",
|
||||
"objc2-app-kit 0.3.2",
|
||||
"objc2-core-foundation",
|
||||
"objc2-foundation 0.3.2",
|
||||
"png",
|
||||
"thiserror 2.0.21",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "naga"
|
||||
version = "30.0.1"
|
||||
@@ -2436,6 +2659,12 @@ dependencies = [
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-conv"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"
|
||||
|
||||
[[package]]
|
||||
name = "num-traits"
|
||||
version = "0.2.19"
|
||||
@@ -2795,6 +3024,12 @@ version = "1.21.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
|
||||
|
||||
[[package]]
|
||||
name = "openssl-probe"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1"
|
||||
|
||||
[[package]]
|
||||
name = "orbclient"
|
||||
version = "0.3.55"
|
||||
@@ -2997,6 +3232,19 @@ version = "0.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6"
|
||||
|
||||
[[package]]
|
||||
name = "plist"
|
||||
version = "1.10.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "327a4cb2ad49dc48adfdc9da89e22c64d488b508c67a044d71ba729e4521a285"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"indexmap",
|
||||
"quick-xml 0.42.0",
|
||||
"serde",
|
||||
"time",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "png"
|
||||
version = "0.18.1"
|
||||
@@ -3081,6 +3329,12 @@ dependencies = [
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "powerfmt"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958"
|
||||
|
||||
[[package]]
|
||||
name = "presser"
|
||||
version = "0.3.1"
|
||||
@@ -3155,6 +3409,15 @@ dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quick-xml"
|
||||
version = "0.42.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.47"
|
||||
@@ -3339,6 +3602,20 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ring"
|
||||
version = "0.17.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"cfg-if",
|
||||
"getrandom 0.2.17",
|
||||
"libc",
|
||||
"untrusted",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rmcp"
|
||||
version = "3.5.1"
|
||||
@@ -3446,6 +3723,80 @@ dependencies = [
|
||||
"rustix 1.1.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustls"
|
||||
version = "0.23.46"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"
|
||||
dependencies = [
|
||||
"log",
|
||||
"once_cell",
|
||||
"ring",
|
||||
"rustls-pki-types",
|
||||
"rustls-webpki",
|
||||
"subtle",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustls-native-certs"
|
||||
version = "0.8.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4"
|
||||
dependencies = [
|
||||
"openssl-probe",
|
||||
"rustls-pki-types",
|
||||
"schannel",
|
||||
"security-framework",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustls-pki-types"
|
||||
version = "1.15.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96"
|
||||
dependencies = [
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustls-platform-verifier"
|
||||
version = "0.7.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98"
|
||||
dependencies = [
|
||||
"core-foundation 0.10.1",
|
||||
"core-foundation-sys",
|
||||
"jni",
|
||||
"log",
|
||||
"once_cell",
|
||||
"rustls",
|
||||
"rustls-native-certs",
|
||||
"rustls-platform-verifier-android",
|
||||
"rustls-webpki",
|
||||
"security-framework",
|
||||
"security-framework-sys",
|
||||
"webpki-root-certs",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustls-platform-verifier-android"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f"
|
||||
|
||||
[[package]]
|
||||
name = "rustls-webpki"
|
||||
version = "0.103.16"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281"
|
||||
dependencies = [
|
||||
"ring",
|
||||
"rustls-pki-types",
|
||||
"untrusted",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustversion"
|
||||
version = "1.0.23"
|
||||
@@ -3461,6 +3812,15 @@ dependencies = [
|
||||
"winapi-util",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "schannel"
|
||||
version = "0.1.30"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5"
|
||||
dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "schemars"
|
||||
version = "1.2.3"
|
||||
@@ -3499,6 +3859,29 @@ version = "1.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
|
||||
|
||||
[[package]]
|
||||
name = "security-framework"
|
||||
version = "3.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"core-foundation 0.10.1",
|
||||
"core-foundation-sys",
|
||||
"libc",
|
||||
"security-framework-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "security-framework-sys"
|
||||
version = "2.17.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3"
|
||||
dependencies = [
|
||||
"core-foundation-sys",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "self_cell"
|
||||
version = "1.3.0"
|
||||
@@ -3510,6 +3893,10 @@ name = "semver"
|
||||
version = "1.0.28"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "send_wrapper"
|
||||
@@ -3591,6 +3978,17 @@ dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sha2"
|
||||
version = "0.10.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures",
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "shlex"
|
||||
version = "2.0.1"
|
||||
@@ -3762,6 +4160,12 @@ version = "0.11.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
|
||||
|
||||
[[package]]
|
||||
name = "subtle"
|
||||
version = "2.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "2.0.119"
|
||||
@@ -3821,6 +4225,16 @@ dependencies = [
|
||||
"windows",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tar"
|
||||
version = "0.4.46"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840"
|
||||
dependencies = [
|
||||
"filetime",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tempfile"
|
||||
version = "3.27.0"
|
||||
@@ -3847,6 +4261,8 @@ dependencies = [
|
||||
name = "texturecraft"
|
||||
version = "0.3.1"
|
||||
dependencies = [
|
||||
"craft-menu",
|
||||
"craft-update",
|
||||
"eframe",
|
||||
"egui",
|
||||
"image",
|
||||
@@ -3958,7 +4374,7 @@ dependencies = [
|
||||
"half",
|
||||
"image",
|
||||
"lz4_flex",
|
||||
"quick-xml",
|
||||
"quick-xml 0.41.0",
|
||||
"rayon",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -4026,7 +4442,11 @@ name = "texturecraft-ui-egui"
|
||||
version = "0.3.1"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"craft-dialogs",
|
||||
"craft-keymap",
|
||||
"craft-quit",
|
||||
"craft-ui",
|
||||
"craft-update",
|
||||
"craft-window",
|
||||
"eframe",
|
||||
"egui",
|
||||
@@ -4118,6 +4538,36 @@ dependencies = [
|
||||
"zune-jpeg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "time"
|
||||
version = "0.3.55"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134"
|
||||
dependencies = [
|
||||
"deranged",
|
||||
"num-conv",
|
||||
"powerfmt",
|
||||
"serde_core",
|
||||
"time-core",
|
||||
"time-macros",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "time-core"
|
||||
version = "0.1.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109"
|
||||
|
||||
[[package]]
|
||||
name = "time-macros"
|
||||
version = "0.2.32"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85"
|
||||
dependencies = [
|
||||
"num-conv",
|
||||
"time-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tinystr"
|
||||
version = "0.8.5"
|
||||
@@ -4300,6 +4750,12 @@ version = "1.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c"
|
||||
|
||||
[[package]]
|
||||
name = "typenum"
|
||||
version = "1.20.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
|
||||
|
||||
[[package]]
|
||||
name = "uds_windows"
|
||||
version = "1.2.1"
|
||||
@@ -4347,6 +4803,41 @@ version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"
|
||||
|
||||
[[package]]
|
||||
name = "untrusted"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
|
||||
|
||||
[[package]]
|
||||
name = "ureq"
|
||||
version = "3.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7be76686bdf7198002062423ca0d8cf9b75a27c8e1de804513b97e97b555d9d"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"flate2",
|
||||
"log",
|
||||
"percent-encoding",
|
||||
"rustls",
|
||||
"rustls-pki-types",
|
||||
"rustls-platform-verifier",
|
||||
"ureq-proto",
|
||||
"utf8-zero",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ureq-proto"
|
||||
version = "0.7.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "622dce33c252115466d83f63e9744a18f12b4406aae51a01c15ad8fcf1185eb3"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"http",
|
||||
"httparse",
|
||||
"log",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "urlencoding"
|
||||
version = "2.1.3"
|
||||
@@ -4362,6 +4853,12 @@ dependencies = [
|
||||
"utf_types",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "utf8-zero"
|
||||
version = "0.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e"
|
||||
|
||||
[[package]]
|
||||
name = "utf8_iter"
|
||||
version = "1.1.0"
|
||||
@@ -4416,6 +4913,16 @@ dependencies = [
|
||||
"vello_common",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "verifysign"
|
||||
version = "1.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a6efd25aadc22c756a9012267fae0b130278d335d6ceb512ec02ce82029b5ca9"
|
||||
dependencies = [
|
||||
"core-foundation 0.10.1",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "version_check"
|
||||
version = "0.9.5"
|
||||
@@ -4596,7 +5103,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quick-xml",
|
||||
"quick-xml 0.41.0",
|
||||
"quote",
|
||||
]
|
||||
|
||||
@@ -4632,6 +5139,15 @@ dependencies = [
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "webpki-root-certs"
|
||||
version = "1.0.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e49d0e65abc00c142e8f9428da991da9f1a250c39be97459901eb12b9b49f62a"
|
||||
dependencies = [
|
||||
"rustls-pki-types",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "weezl"
|
||||
version = "0.1.12"
|
||||
@@ -5152,7 +5668,7 @@ dependencies = [
|
||||
"calloop",
|
||||
"cfg_aliases",
|
||||
"concurrent-queue",
|
||||
"core-foundation",
|
||||
"core-foundation 0.9.4",
|
||||
"core-graphics",
|
||||
"cursor-icon",
|
||||
"dpi",
|
||||
@@ -5197,6 +5713,16 @@ dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "winreg"
|
||||
version = "0.55.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cb5a765337c50e9ec252c2069be9bf91c7df47afb103b642ba3a53bf8101be97"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "winresource"
|
||||
version = "0.1.34"
|
||||
@@ -5513,6 +6039,12 @@ dependencies = [
|
||||
"synstructure",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zeroize"
|
||||
version = "1.9.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879"
|
||||
|
||||
[[package]]
|
||||
name = "zerotrie"
|
||||
version = "0.2.5"
|
||||
|
||||
+12
-2
@@ -65,9 +65,19 @@ getrandom = "0.3"
|
||||
rustix = { version = "1", default-features = false, features = ["std", "fs", "process"] }
|
||||
# Shared Craft egui components (widget palette, icon buttons, panel docking): storytold/craft-libs,
|
||||
# MIT OR Apache-2.0, pinned to one rev.
|
||||
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242", features = ["serde"] }
|
||||
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["serde"] }
|
||||
# Who draws the window frame, and the app-drawn strip as the title bar (crates/ui-egui/src/titlebar.rs).
|
||||
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242", features = ["egui"] }
|
||||
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["egui"] }
|
||||
# Release checks, the update prompt and the update helper (crates/ui-egui/src/updates_ui.rs).
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["egui"] }
|
||||
# File dialogs that never block the frame (crates/ui-egui/src/file_dialogs.rs).
|
||||
craft-dialogs = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" }
|
||||
# Shortcut chords, lookup and dispatch (crates/ui-egui/src/keymap.rs).
|
||||
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["egui"] }
|
||||
# Quitting the macOS way instead of closing the window (crates/ui-egui/src/windows.rs).
|
||||
craft-quit = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["egui"] }
|
||||
# The macOS app menu whose Quit asks about unsaved changes (apps/texturecraft/src/main.rs).
|
||||
craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" }
|
||||
|
||||
# egui 0.37 and winit: the suite's forks (storytold/egui, storytold/winit), as craft-libs pins them.
|
||||
[patch.crates-io]
|
||||
|
||||
@@ -32,6 +32,7 @@
|
||||
<img alt="MCP server for agents" src="https://img.shields.io/badge/agents-MCP%20server-555555?style=flat-square">
|
||||
<img alt="License: MIT OR Apache-2.0" src="https://img.shields.io/badge/license-MIT%20OR%20Apache--2.0-555555?style=flat-square">
|
||||
<br>
|
||||
<a href="https://sonarcloud.io/project/overview?id=storytold_texturecraft"><img alt="Scanned by SonarCloud" src="https://img.shields.io/badge/Scanned_by-SonarCloud-4b9fd5?style=flat-square&logo=sonarqubecloud&logoColor=white"></a>
|
||||
<a href="https://coderabbit.ai"><img alt="Reviewed by CodeRabbit" src="https://img.shields.io/coderabbit/prs/github/storytold/texturecraft?style=flat-square&label=Reviewed%20by%20CodeRabbit&logo=coderabbit"></a>
|
||||
</p>
|
||||
|
||||
|
||||
@@ -30,6 +30,12 @@ ron = "0.12"
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
winit = { version = "0.30", default-features = false }
|
||||
winsafe = { version = "0.0.29", default-features = false, features = ["user"] }
|
||||
# The update helper is a copy of this program (`main`).
|
||||
craft-update = { workspace = true }
|
||||
|
||||
# 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 }
|
||||
|
||||
[build-dependencies]
|
||||
winresource = "0.1"
|
||||
@@ -11,11 +11,17 @@ mod window_frame;
|
||||
|
||||
use texturecraft_engine::Session;
|
||||
use texturecraft_ui_egui::titlebar::TitleBar;
|
||||
use texturecraft_ui_egui::ui_state_store;
|
||||
use texturecraft_ui_egui::{TextureCraftApp, UiState};
|
||||
|
||||
/// The app name eframe keeps the settings under (`eframe::storage_dir`).
|
||||
const APP_NAME: &str = "TextureCraft";
|
||||
|
||||
/// The window's size when it opens, in points.
|
||||
const DEFAULT_SIZE: [f32; 2] = [1600.0, 960.0];
|
||||
/// The smallest size the window can be resized to, in points.
|
||||
const MIN_SIZE: [f32; 2] = [960.0, 600.0];
|
||||
|
||||
const ICON_PNG: &[u8] = include_bytes!("../../../assets/app-icon/hicolor/256x256/apps/ai.storyteller.texturecraft.png");
|
||||
|
||||
fn version() -> String {
|
||||
@@ -115,13 +121,16 @@ fn set_taskbar_icon(w: &winit::window::Window) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Settings › Interface › System title bar, read from the saved settings before the window opens
|
||||
/// (eframe hands the app its storage only afterwards). Missing or unreadable: off.
|
||||
fn saved_system_title_bar(persistence_path: Option<&std::path::Path>) -> bool {
|
||||
let file = persistence_path.map(std::path::Path::to_path_buf).or_else(|| eframe::storage_dir(APP_NAME).map(|d| d.join("app.ron")));
|
||||
let saved = file.and_then(|f| std::fs::read_to_string(f).ok());
|
||||
let kv = saved.and_then(|s| ron::from_str::<std::collections::HashMap<String, String>>(&s).ok());
|
||||
kv.and_then(|kv| ron::from_str::<UiState>(kv.get("ui")?).ok()).is_some_and(|ui| ui.prefs.system_title_bar)
|
||||
/// Settings › Interface › System title bar, read before the window opens from `ui.json`, else as earlier builds saved it; missing or unreadable: off
|
||||
fn saved_system_title_bar(ui_file: Option<&std::path::Path>, persistence_path: Option<&std::path::Path>) -> bool {
|
||||
if let Some(ui) = ui_file.and_then(ui_state_store::read) {
|
||||
return ui.prefs.system_title_bar;
|
||||
}
|
||||
|
||||
let file = persistence_path.map(std::path::Path::to_path_buf).or_else(|| eframe::storage_dir(APP_NAME).map(|folder| folder.join("app.ron")));
|
||||
let saved = file.and_then(|file| std::fs::read_to_string(file).ok());
|
||||
let entries = saved.and_then(|text| ron::from_str::<std::collections::HashMap<String, String>>(&text).ok());
|
||||
entries.and_then(|entries| ron::from_str::<UiState>(entries.get("ui")?).ok()).is_some_and(|ui| ui.prefs.system_title_bar)
|
||||
}
|
||||
|
||||
/// The app with the window chrome that needs the native window: the Windows borderless guard, and
|
||||
@@ -161,7 +170,17 @@ impl eframe::App for Shell {
|
||||
}
|
||||
}
|
||||
|
||||
/// A script driving the app gets no network check and no update prompt over its window.
|
||||
fn checks_for_updates_at_start(control: Option<u16>) -> bool {
|
||||
control.is_none()
|
||||
}
|
||||
|
||||
fn main() {
|
||||
// Windows: the update helper is a copy of this program started with `--finish-update`.
|
||||
#[cfg(windows)]
|
||||
if let Some(result) = craft_update::self_update::finish(&texturecraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>()) {
|
||||
std::process::exit(i32::from(result.is_err()));
|
||||
}
|
||||
let args = match parse_args() {
|
||||
Ok(Some(a)) => a,
|
||||
Ok(None) => return,
|
||||
@@ -170,21 +189,25 @@ fn main() {
|
||||
std::process::exit(2);
|
||||
}
|
||||
};
|
||||
// Errors before the window opens speak the system's language; the app then applies the saved one.
|
||||
// Errors before the window opens speak the system's language; the app then applies the saved one
|
||||
texturecraft_ui_egui::i18n::set_language(texturecraft_ui_egui::i18n::os_language());
|
||||
let prev = std::panic::take_hook();
|
||||
std::panic::set_hook(Box::new(move |info| {
|
||||
// A message box needs the main thread on macOS; other threads' panics are only logged.
|
||||
// A message box needs the main thread on macOS; other threads' panics are only logged
|
||||
fatal(&format!("internal error: {info}"), std::thread::current().name() == Some("main"));
|
||||
prev(info);
|
||||
}));
|
||||
let session = initial_session(&args);
|
||||
// Scripted runs (agents, films, tests) set TEXTURECRAFT_NO_PREFS so they neither read nor
|
||||
// overwrite the user's saved UI layout and settings: state goes to a throwaway folder.
|
||||
// Scripted runs (agents, films, tests) set TEXTURECRAFT_NO_PREFS to keep the user's saved settings untouched: state goes to throwaway files
|
||||
let persistence_path =
|
||||
std::env::var_os("TEXTURECRAFT_NO_PREFS").map(|_| std::env::temp_dir().join(format!("texturecraft-noprefs-{}.ron", std::process::id())));
|
||||
let title_bar = TitleBar::decide(saved_system_title_bar(persistence_path.as_deref()));
|
||||
let mut viewport = egui::ViewportBuilder::default().with_title(APP_NAME).with_inner_size([1600.0, 960.0]).with_min_inner_size([960.0, 600.0]);
|
||||
let ui_file =
|
||||
persistence_path.as_ref().map(|path| path.with_extension("json")).or_else(|| eframe::storage_dir(APP_NAME).map(|folder| folder.join("ui.json")));
|
||||
if let Some(file) = &ui_file {
|
||||
let _ = ui_state_store::FILE.set(file.clone());
|
||||
}
|
||||
let title_bar = TitleBar::decide(saved_system_title_bar(ui_file.as_deref(), persistence_path.as_deref()));
|
||||
let mut viewport = egui::ViewportBuilder::default().with_title(APP_NAME).with_inner_size(DEFAULT_SIZE).with_min_inner_size(MIN_SIZE);
|
||||
if let Some(i) = icon() {
|
||||
viewport = viewport.with_icon(i);
|
||||
}
|
||||
@@ -195,7 +218,7 @@ fn main() {
|
||||
std::process::exit(2);
|
||||
}
|
||||
let control = args.control;
|
||||
// The start window offers new, open and recent projects, unless a file was given or a script drives the app.
|
||||
// The start window offers new, open and recent projects, unless a file was given or a script drives the app
|
||||
let start = args.file.is_none() && control.is_none();
|
||||
let r = eframe::run_native(
|
||||
APP_NAME,
|
||||
@@ -205,10 +228,16 @@ fn main() {
|
||||
if let Some(w) = cc.winit_window() {
|
||||
set_taskbar_icon(w);
|
||||
}
|
||||
// winit's Quit ends the process without asking; this menu's asks like the close button.
|
||||
#[cfg(target_os = "macos")]
|
||||
if let Err(e) = craft_menu::mac::install_app_menu(&cc.egui_ctx, APP_NAME) {
|
||||
log::warn!("the app menu could not be installed: {e}");
|
||||
}
|
||||
let window_frame = window_frame::service(cc, matches!(title_bar, TitleBar::App(_)));
|
||||
let mut app = TextureCraftApp::new(cc, session);
|
||||
app.title_bar = title_bar;
|
||||
app.ui.windows.start = start && app.ui.prefs.start_window;
|
||||
app.set_startup_update_check(checks_for_updates_at_start(control));
|
||||
if let Some(port) = control {
|
||||
app.control = Some(control_server::start(port, cc.egui_ctx.clone()));
|
||||
}
|
||||
@@ -274,6 +303,12 @@ mod tests {
|
||||
assert_eq!(args.gpu.as_deref(), Some("3080"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_a_run_without_a_control_port_checks_for_updates_at_start() {
|
||||
assert!(checks_for_updates_at_start(None));
|
||||
assert!(!checks_for_updates_at_start(Some(9000)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_missing_or_invalid_gpu_args() {
|
||||
assert!(parse_args_from(["--gpu".to_string()]).is_err());
|
||||
@@ -296,19 +331,27 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_system_title_bar_setting_is_read_from_eframes_settings_file() {
|
||||
let path = std::env::temp_dir().join(format!("texturecraft-titlebar-test-{}.ron", std::process::id()));
|
||||
fn the_system_title_bar_setting_is_read_from_ui_json_else_as_earlier_builds_saved_it() {
|
||||
let ron_path = std::env::temp_dir().join(format!("texturecraft-titlebar-test-{}.ron", std::process::id()));
|
||||
let json_path = ron_path.with_extension("json");
|
||||
for on in [false, true] {
|
||||
let mut ui = UiState::default();
|
||||
ui.prefs.system_title_bar = on;
|
||||
// Written as eframe writes it: a pretty RON map of RON strings.
|
||||
// Written as eframe writes it: a pretty RON map of RON strings
|
||||
let kv = std::collections::HashMap::from([("ui".to_string(), ron::to_string(&ui).unwrap())]);
|
||||
std::fs::write(&path, ron::Options::default().to_string_pretty(&kv, Default::default()).unwrap()).unwrap();
|
||||
assert_eq!(saved_system_title_bar(Some(&path)), on);
|
||||
std::fs::write(&ron_path, ron::Options::default().to_string_pretty(&kv, Default::default()).unwrap()).unwrap();
|
||||
assert_eq!(saved_system_title_bar(None, Some(&ron_path)), on);
|
||||
|
||||
ui.prefs.system_title_bar = !on;
|
||||
std::fs::write(&json_path, serde_json::to_vec(&ui).unwrap()).unwrap();
|
||||
assert_eq!(saved_system_title_bar(Some(&json_path), Some(&ron_path)), !on, "ui.json comes first");
|
||||
}
|
||||
std::fs::write(&path, "not ron").unwrap();
|
||||
assert!(!saved_system_title_bar(Some(&path)));
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
assert!(!saved_system_title_bar(Some(&path)));
|
||||
|
||||
std::fs::write(&json_path, "not json").unwrap();
|
||||
std::fs::write(&ron_path, "not ron").unwrap();
|
||||
assert!(!saved_system_title_bar(Some(&json_path), Some(&ron_path)));
|
||||
std::fs::remove_file(&json_path).unwrap();
|
||||
std::fs::remove_file(&ron_path).unwrap();
|
||||
assert!(!saved_system_title_bar(Some(&json_path), Some(&ron_path)));
|
||||
}
|
||||
}
|
||||
@@ -72,7 +72,7 @@ fn join(dir: &str, name: &str) -> String {
|
||||
impl Headless {
|
||||
pub fn new(session: Session, fs: Filesystem) -> Headless {
|
||||
// Bakes run here (CLI, MCP) cast their rays on the GPU when there is one.
|
||||
texturecraft_engine::bake_cmds::install_gpu_tracer(std::sync::Arc::new(texturecraft_render::gpu_bake::GpuBaker::new()));
|
||||
texturecraft_engine::bake::install_gpu_tracer(std::sync::Arc::new(texturecraft_render::gpu_bake::GpuBaker::new()));
|
||||
Headless { session, fs, gpu: None }
|
||||
}
|
||||
|
||||
|
||||
@@ -72,7 +72,7 @@ impl Gpu {
|
||||
// The aux texture behind the mesh-map and mask views (rebuilt every render).
|
||||
let res = texturecraft_render::aux_size(cache.size);
|
||||
let aux = match s.view {
|
||||
ViewMode::MeshMap(m) => Some(texturecraft_render::mesh_maps::mesh_map_rgba(s.doc.baked.get(&ts), m, res)),
|
||||
ViewMode::MeshMap(m) => Some(texturecraft_render::mesh_maps::mesh_map_rgba(s.doc.baked.get(&ts), m, res, cache.size, &comp.block_scales)),
|
||||
ViewMode::Mask(id) if s.doc.project.locate(id).is_some_and(|(t, _, _)| t == ts) => s.mask_view_rgba(id, res),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
@@ -127,20 +127,20 @@ fn file_error(op: &str, path: &str, e: std::io::Error) -> AutomationError {
|
||||
AutomationError::Io(format!("{op} `{path}` failed: {e}"))
|
||||
}
|
||||
|
||||
/// Engine commands that take host paths (`file.open`, `file.exportTextures`, `resource.import`,
|
||||
/// `material.save`, …) would bypass the workspace: automation clients use the workspace-scoped
|
||||
/// methods instead. Any command given a `path` or `dir` is refused, and every `file.*` command
|
||||
/// but `file.close` and `file.removeUnused` (`file.save` even without `path`: a headless session's path is
|
||||
/// workspace-relative, not a host path; `file.reimportMesh` without `path` re-reads the
|
||||
/// embedded mesh).
|
||||
/// Host keys a command reads or writes a file through, at the top level or in each `files` entry
|
||||
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> {
|
||||
let has_path = ["path", "dir"].iter().any(|k| params.get(k).is_some_and(|v| !v.is_null()));
|
||||
let ok = match id {
|
||||
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
|
||||
let allowed = match id {
|
||||
"file.close" | "file.removeUnused" => true,
|
||||
"file.reimportMesh" => !has_path,
|
||||
_ => !id.starts_with("file.") && !has_path,
|
||||
};
|
||||
if ok {
|
||||
if allowed {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(bad(format!(
|
||||
@@ -149,6 +149,11 @@ pub fn authorize_command(id: &str, params: &Value) -> Result<(), AutomationError
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `params` names a host path or folder at its own top level
|
||||
fn names_host_path(params: &Value) -> bool {
|
||||
HOST_PATH_KEYS.iter().any(|key| params.get(key).is_some_and(|value| !value.is_null()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -243,6 +248,18 @@ mod tests {
|
||||
assert!(authorize_command("layer.add.fill", &json!({"color": "#ff0000", "path": null})).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_file_paths_are_denied() {
|
||||
let outside_file = json!({"files": [{"path": "/etc/x_ao.png", "map": "ao"}]});
|
||||
assert!(authorize_command("textureSet.meshMap.import", &outside_file).is_err());
|
||||
|
||||
let one_of_many = json!({"files": [{"map": "ao"}, {"path": "/etc/x_ao.png"}]});
|
||||
assert!(authorize_command("textureSet.meshMap.import", &one_of_many).is_err());
|
||||
|
||||
let no_paths = json!({"files": [{"map": "ao"}, {"path": null}]});
|
||||
assert!(authorize_command("textureSet.meshMap.import", &no_paths).is_ok());
|
||||
}
|
||||
|
||||
/// Every registry command documenting a host path must be classified (fails when a new
|
||||
/// path-taking command is added without an automation policy).
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
//! Where the bake's transfer rays start, shared by the bake and the cage the 3D view draws
|
||||
|
||||
mod cage_shell;
|
||||
mod high_poly_reach;
|
||||
mod ray_frame;
|
||||
mod ray_start;
|
||||
mod vertex_reach;
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) use cage_shell::CORNERS;
|
||||
pub use cage_shell::CageShell;
|
||||
pub use high_poly_reach::HighPolyReach;
|
||||
pub(crate) use ray_frame::RayFrame;
|
||||
pub use ray_start::RayStart;
|
||||
pub use vertex_reach::VertexReach;
|
||||
@@ -0,0 +1,65 @@
|
||||
use super::{RayFrame, RayStart};
|
||||
use crate::{BakeError, BakeRequest, MeshExtent};
|
||||
use rayon::prelude::*;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use texturecraft_geom::glam::Vec3;
|
||||
use texturecraft_geom::surface_at;
|
||||
|
||||
/// Barycentric coordinates of a triangle's three corners
|
||||
pub(crate) const CORNERS: [[f32; 2]; 3] = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]];
|
||||
|
||||
/// The cage of one texture set as the bake sees it: where its transfer rays start at each corner of the set's triangles
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct CageShell {
|
||||
/// Low-poly position of each triangle corner, three per triangle
|
||||
pub positions: Vec<Vec3>,
|
||||
pub starts: Vec<RayStart>,
|
||||
/// Corner pairs along the low poly's polygon edges, for the wireframe
|
||||
pub edges: Vec<[u32; 2]>,
|
||||
/// World units per unit of the max frontal distance setting
|
||||
pub cage_units: f32,
|
||||
}
|
||||
|
||||
impl CageShell {
|
||||
/// The cage of `request`'s texture set, from the same ray starts the bake uses
|
||||
pub fn new(request: &BakeRequest) -> Result<CageShell, BakeError> {
|
||||
let ray_frame = RayFrame::new(request, MeshExtent::of(request.mesh)?)?;
|
||||
let (frame, mesh) = (&ray_frame, request.mesh);
|
||||
let triangles: Vec<usize> = mesh.triangles_of(request.material).collect();
|
||||
let (positions, starts): (Vec<Vec3>, Vec<RayStart>) = triangles
|
||||
.par_iter()
|
||||
.flat_map_iter(|&triangle| {
|
||||
CORNERS.into_iter().map(move |barycentric| match surface_at(mesh, triangle as u32, barycentric[0], barycentric[1]) {
|
||||
Some(surface) => (surface.pos, frame.start(&surface, barycentric)),
|
||||
None => (Vec3::ZERO, RayStart::Distance { up: Vec3::ZERO, scale: 0.0 }),
|
||||
})
|
||||
})
|
||||
.unzip();
|
||||
|
||||
let wire_edges: HashSet<(u32, u32)> = mesh.wire_edges().into_iter().nth(request.material).unwrap_or_default().into_iter().collect();
|
||||
let mut edge_corners = HashMap::new();
|
||||
for (triangle_index, &triangle) in triangles.iter().enumerate() {
|
||||
let Some(vertices) = mesh.tri(triangle) else { continue };
|
||||
|
||||
for corner in 0..3 {
|
||||
let next = (corner + 1) % 3;
|
||||
let (from, to) = (vertices[corner] as u32, vertices[next] as u32);
|
||||
let key = (from.min(to), from.max(to));
|
||||
if wire_edges.contains(&key) {
|
||||
let first_corner = (triangle_index * 3) as u32;
|
||||
edge_corners.entry(key).or_insert([first_corner + corner as u32, first_corner + next as u32]);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut edges: Vec<[u32; 2]> = edge_corners.into_values().collect();
|
||||
edges.sort_unstable();
|
||||
|
||||
Ok(CageShell { positions, starts, edges, cage_units: ray_frame.cage_units })
|
||||
}
|
||||
|
||||
/// Each corner's cage position at `max_frontal`, the setting before relative-to-bounding-box scaling
|
||||
pub fn corners(&self, max_frontal: f32) -> Vec<Vec3> {
|
||||
let frontal = max_frontal * self.cage_units;
|
||||
self.positions.par_iter().zip(&self.starts).map(|(position, start)| start.origin(*position, frontal)).collect()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
use super::{RayFrame, VertexReach};
|
||||
use crate::map::transfer_keys;
|
||||
use crate::tracing::ANY;
|
||||
use crate::{BakeError, BakeRequest, MeshExtent};
|
||||
use rayon::prelude::*;
|
||||
use texturecraft_core::MeshMatchMode;
|
||||
use texturecraft_geom::glam::Vec3;
|
||||
use texturecraft_geom::{Mesh, surface_at};
|
||||
|
||||
/// Where each high-poly vertex sits relative to the transfer rays of one texture set, to show which parts its bake misses
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct HighPolyReach {
|
||||
/// Per high-poly vertex; `None` where another texture set's low poly is nearer or the request has no high poly
|
||||
pub vertices: Vec<Option<VertexReach>>,
|
||||
/// World units per unit of the cage distance settings
|
||||
pub cage_units: f32,
|
||||
pub ignore_backface: bool,
|
||||
}
|
||||
|
||||
impl HighPolyReach {
|
||||
/// The reach of `request`'s transfer rays at the high-poly vertices whose nearest low-poly point is on this set, from the same ray starts the bake uses there
|
||||
pub fn new(request: &BakeRequest) -> Result<HighPolyReach, BakeError> {
|
||||
let Some(high) = request.high else { return Ok(HighPolyReach::default()) };
|
||||
|
||||
let frame = RayFrame::new(request, MeshExtent::of(request.mesh)?)?;
|
||||
let mut in_set = vec![false; request.mesh.triangle_count()];
|
||||
for triangle in request.mesh.triangles_of(request.material) {
|
||||
if let Some(flag) = in_set.get_mut(triangle) {
|
||||
*flag = true;
|
||||
}
|
||||
}
|
||||
|
||||
let winding_normals = winding_normals(high.mesh);
|
||||
let (low_keys, high_vertex_keys) = match request.settings.high_poly.match_mode {
|
||||
MeshMatchMode::Always => (Vec::new(), Vec::new()),
|
||||
MeshMatchMode::ByMeshName => {
|
||||
let (low_keys, high_keys) = transfer_keys(request);
|
||||
(low_keys, vertex_keys(high.mesh, &high_keys))
|
||||
}
|
||||
};
|
||||
let key = |keys: &[u32], index: usize| keys.get(index).copied().unwrap_or(ANY);
|
||||
let frame = &frame;
|
||||
let vertices = high
|
||||
.mesh
|
||||
.positions
|
||||
.par_iter()
|
||||
.zip(&winding_normals)
|
||||
.enumerate()
|
||||
.map(|(vertex, (&high_position, &high_facing))| {
|
||||
let nearest = request.bvh.nearest(high_position, f32::INFINITY, &|_| true)?;
|
||||
if !in_set.get(nearest.tri as usize).copied().unwrap_or(false) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let surface = surface_at(request.mesh, nearest.tri, nearest.u, nearest.v)?;
|
||||
let ray_key = key(&low_keys, nearest.tri as usize);
|
||||
Some(VertexReach {
|
||||
low_position: surface.pos,
|
||||
start: frame.start(&surface, [nearest.u, nearest.v]),
|
||||
high_position,
|
||||
high_facing,
|
||||
name_matches: ray_key == ANY || key(&high_vertex_keys, vertex) == ray_key,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
Ok(HighPolyReach { vertices, cage_units: frame.cage_units, ignore_backface: request.settings.high_poly.ignore_backface })
|
||||
}
|
||||
|
||||
/// Whether the transfer rays miss high-poly vertex `vertex` at the `max_frontal` and `max_rear` settings; `None` when the vertex isn't this set's
|
||||
pub fn missed(&self, vertex: usize, max_frontal: f32, max_rear: f32) -> Option<bool> {
|
||||
let reach = self.vertices.get(vertex).copied().flatten()?;
|
||||
Some(reach.missed(max_frontal * self.cage_units, max_rear * self.cage_units, self.ignore_backface))
|
||||
}
|
||||
}
|
||||
|
||||
/// Each vertex's mesh-name key, from the first triangle that uses it
|
||||
fn vertex_keys(mesh: &Mesh, triangle_keys: &[u32]) -> Vec<u32> {
|
||||
let mut keys = vec![ANY; mesh.positions.len()];
|
||||
for (corners, &triangle_key) in mesh.indices.chunks_exact(3).zip(triangle_keys) {
|
||||
for &corner in corners {
|
||||
if let Some(key) = keys.get_mut(corner as usize).filter(|key| **key == ANY) {
|
||||
*key = triangle_key;
|
||||
}
|
||||
}
|
||||
}
|
||||
keys
|
||||
}
|
||||
|
||||
/// Each vertex's sum of its triangles' winding normals, weighted by area: the side the bake's backface test sees as the front
|
||||
fn winding_normals(mesh: &Mesh) -> Vec<Vec3> {
|
||||
let mut normals = vec![Vec3::ZERO; mesh.positions.len()];
|
||||
for corners in mesh.indices.chunks_exact(3) {
|
||||
let position = |corner: u32| mesh.positions.get(corner as usize).copied().unwrap_or(Vec3::ZERO);
|
||||
let winding_normal = (position(corners[1]) - position(corners[0])).cross(position(corners[2]) - position(corners[0]));
|
||||
for &corner in corners {
|
||||
if let Some(normal) = normals.get_mut(corner as usize) {
|
||||
*normal += winding_normal;
|
||||
}
|
||||
}
|
||||
}
|
||||
normals
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
use super::RayStart;
|
||||
use crate::MeshExtent;
|
||||
use crate::map::{interpolate, welded};
|
||||
use crate::skew::PreparedSkew;
|
||||
use crate::{BakeError, BakePaintMap, BakeRequest};
|
||||
use texturecraft_core::CageType;
|
||||
use texturecraft_geom::glam::Vec3;
|
||||
use texturecraft_geom::{Mesh, Surface};
|
||||
|
||||
/// What decides where transfer rays start: the cage mesh or the averaged normals, skew and painted cage amount
|
||||
pub(crate) struct RayFrame<'a> {
|
||||
mesh: &'a Mesh,
|
||||
ray_normals: Vec<Vec3>,
|
||||
cage: Option<&'a Mesh>,
|
||||
skew: Option<PreparedSkew<'a>>,
|
||||
cage_paint: Option<&'a BakePaintMap>,
|
||||
/// Cage-file offsets this short count as none: the ray starts from the distance-based cage instead
|
||||
ray_epsilon: f32,
|
||||
/// World units per unit of the cage distance settings
|
||||
pub(crate) cage_units: f32,
|
||||
}
|
||||
|
||||
impl<'a> RayFrame<'a> {
|
||||
pub(crate) fn new(request: &BakeRequest<'a>, extent: MeshExtent) -> Result<RayFrame<'a>, BakeError> {
|
||||
let settings = request.settings;
|
||||
let ray_normals = match settings.cage.average_normals && request.high.is_some() {
|
||||
true => {
|
||||
let (welded_indices, _, normals) = welded(request.mesh, extent.diagonal);
|
||||
welded_indices.iter().map(|index| normals.get(*index as usize).copied().unwrap_or(Vec3::Y)).collect()
|
||||
}
|
||||
false => Vec::new(),
|
||||
};
|
||||
|
||||
Ok(RayFrame {
|
||||
mesh: request.mesh,
|
||||
ray_normals,
|
||||
cage: if settings.cage.kind == CageType::CustomFile { request.cage } else { None },
|
||||
skew: request.skew.map(|skew_map| PreparedSkew::new(skew_map, request.mesh, extent.scale, settings.skew)).transpose()?,
|
||||
cage_paint: request.cage_paint,
|
||||
ray_epsilon: extent.ray_epsilon(),
|
||||
cage_units: if settings.cage.relative_to_bounding_box { extent.scale } else { 1.0 },
|
||||
})
|
||||
}
|
||||
|
||||
/// Where the transfer ray of the low-poly point `surface` at `barycentric` starts
|
||||
pub(crate) fn start(&self, surface: &Surface, barycentric: [f32; 2]) -> RayStart {
|
||||
let cage_offset = self
|
||||
.cage
|
||||
.and_then(|cage_mesh| interpolate(cage_mesh, &cage_mesh.positions, surface.tri, barycentric))
|
||||
.map(|cage_position| surface.pos - cage_position)
|
||||
.filter(|offset| offset.length() > self.ray_epsilon);
|
||||
if let Some(offset) = cage_offset {
|
||||
return RayStart::CageMesh(offset);
|
||||
}
|
||||
|
||||
let averaged_normal = interpolate(self.mesh, &self.ray_normals, surface.tri, barycentric).and_then(Vec3::try_normalize).unwrap_or(surface.nrm);
|
||||
let up = match &self.skew {
|
||||
Some(skew) => skew.correct(self.mesh, surface, averaged_normal),
|
||||
None => averaged_normal,
|
||||
};
|
||||
RayStart::Distance { up, scale: self.cage_paint.map_or(1.0, |map| map.sample(surface.uv)) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
use texturecraft_geom::glam::Vec3;
|
||||
|
||||
/// Where the bake's transfer ray for one low-poly point starts
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum RayStart {
|
||||
/// On the cage mesh: the offset from the cage to the low-poly point
|
||||
CageMesh(Vec3),
|
||||
/// Out along `up` by the frontal distance times `scale` (the painted cage amount)
|
||||
Distance { up: Vec3, scale: f32 },
|
||||
}
|
||||
|
||||
impl RayStart {
|
||||
/// The ray origin for the low-poly point `position` at `frontal` world units of max frontal distance
|
||||
pub fn origin(&self, position: Vec3, frontal: f32) -> Vec3 {
|
||||
match *self {
|
||||
RayStart::CageMesh(offset) => position - offset,
|
||||
RayStart::Distance { up, scale } => position + up * frontal * scale,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
use super::RayStart;
|
||||
use texturecraft_geom::glam::Vec3;
|
||||
|
||||
/// One high-poly vertex seen from the transfer ray through its nearest low-poly point
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct VertexReach {
|
||||
pub low_position: Vec3,
|
||||
pub start: RayStart,
|
||||
pub high_position: Vec3,
|
||||
/// The side the high poly's triangles face at the vertex, by their winding (not normalized)
|
||||
pub high_facing: Vec3,
|
||||
/// Whether the bake lets this low-poly point's ray hit the vertex's part (always, unless matching by mesh name)
|
||||
pub name_matches: bool,
|
||||
}
|
||||
|
||||
impl VertexReach {
|
||||
/// Whether the ray misses the vertex (or may not hit its part) at `frontal` and `rear` world units of cage distance; with `ignore_backface` it also misses a vertex whose triangles face away from the ray
|
||||
pub fn missed(&self, frontal: f32, rear: f32, ignore_backface: bool) -> bool {
|
||||
let origin = self.start.origin(self.low_position, frontal);
|
||||
let (direction, front) = match self.start {
|
||||
RayStart::CageMesh(offset) => (offset.normalize_or_zero(), offset.length()),
|
||||
RayStart::Distance { up, scale } => (-up, frontal * scale),
|
||||
};
|
||||
let along_ray = (self.high_position - origin).dot(direction);
|
||||
|
||||
!self.name_matches || !(0.0..=front + rear).contains(&along_ray) || (ignore_backface && self.high_facing.dot(direction) > 0.0)
|
||||
}
|
||||
}
|
||||
+45
-11
@@ -6,13 +6,17 @@
|
||||
mod bake_error;
|
||||
mod bake_output;
|
||||
mod bake_request;
|
||||
mod cage;
|
||||
mod high_poly;
|
||||
mod mesh_extent;
|
||||
mod progress;
|
||||
|
||||
pub use bake_error::BakeError;
|
||||
pub use bake_output::BakeOutput;
|
||||
pub use bake_request::BakeRequest;
|
||||
pub use cage::{CageShell, HighPolyReach, RayStart, VertexReach};
|
||||
pub use high_poly::HighPoly;
|
||||
pub(crate) use mesh_extent::MeshExtent;
|
||||
pub use progress::Progress;
|
||||
|
||||
mod map;
|
||||
@@ -143,14 +147,20 @@ fn alloc<T: Clone>(count: usize, value: T) -> Result<Vec<T>, BakeError> {
|
||||
}
|
||||
|
||||
pub fn bake(request: &BakeRequest, progress: &Progress) -> Result<BakeOutput, BakeError> {
|
||||
bake_in_strips(request, progress, STRIP_TEXELS, &CpuTracer)
|
||||
bake_in_strips(request, progress, STRIP_TEXELS, &CpuTracer, &[])
|
||||
}
|
||||
|
||||
/// Retry on the CPU if the supplied tracer fails
|
||||
pub fn bake_on(request: &BakeRequest, progress: &Progress, tracer: &dyn Tracer) -> Result<BakeOutput, BakeError> {
|
||||
match bake_in_strips(request, progress, STRIP_TEXELS, tracer) {
|
||||
bake_tiles(request, progress, &[], Some(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> {
|
||||
let tracer = tracer.unwrap_or(&CpuTracer);
|
||||
match bake_in_strips(request, progress, STRIP_TEXELS, tracer, excluded_tiles) {
|
||||
Err(BakeError::Tracer(error)) => {
|
||||
let mut output = bake(request, progress)?;
|
||||
let mut output = bake_in_strips(request, progress, STRIP_TEXELS, &CpuTracer, excluded_tiles)?;
|
||||
output.tracer = format!("CPU ({} unavailable: {error})", tracer.name());
|
||||
Ok(output)
|
||||
}
|
||||
@@ -160,8 +170,18 @@ pub fn bake_on(request: &BakeRequest, progress: &Progress, tracer: &dyn Tracer)
|
||||
|
||||
type OutRow<'a> = Vec<&'a mut [f32]>;
|
||||
|
||||
fn bake_in_strips(request: &BakeRequest, progress: &Progress, strip_texels: usize, tracer: &dyn Tracer) -> Result<BakeOutput, BakeError> {
|
||||
fn bake_in_strips(
|
||||
request: &BakeRequest,
|
||||
progress: &Progress,
|
||||
strip_texels: usize,
|
||||
tracer: &dyn Tracer,
|
||||
excluded_tiles: &[(u32, u32)],
|
||||
) -> Result<BakeOutput, BakeError> {
|
||||
validate(request)?;
|
||||
if excluded_tiles.iter().any(|(column, row)| *column >= request.tiles.0 || *row >= request.tiles.1) {
|
||||
return Err(BakeError::Invalid("excluded UV tile lies outside the bake atlas".into()));
|
||||
}
|
||||
|
||||
let settings = request.settings;
|
||||
let (tile_width, tile_height) = settings.common.output_size();
|
||||
let tile_size = (tile_width as usize, tile_height as usize);
|
||||
@@ -173,12 +193,13 @@ fn bake_in_strips(request: &BakeRequest, progress: &Progress, strip_texels: usiz
|
||||
let mut scene = tracer.scene(&meshes)?;
|
||||
progress.done.store(0, Relaxed);
|
||||
|
||||
// Normal-map curvature needs a normal bake even when normal output is disabled
|
||||
// Normal-map curvature needs a world normal bake even when that output is disabled
|
||||
let from_normal = settings.maps.curvature.parameters.method == CurvatureMethod::NormalMap && settings.maps.is_enabled(BakedMap::Curvature);
|
||||
let mut maps: Vec<BakedMap> = settings.maps.enabled().collect();
|
||||
if from_normal && !maps.contains(&BakedMap::Normal) {
|
||||
maps.push(BakedMap::Normal);
|
||||
if from_normal && !maps.contains(&BakedMap::WorldNormal) {
|
||||
maps.push(BakedMap::WorldNormal);
|
||||
}
|
||||
|
||||
let mut buffers = maps.iter().map(|map| alloc(width * height * map.components(), 0.0f32)).collect::<Result<Vec<_>, _>>()?;
|
||||
let mut covered = alloc(width * height, false)?;
|
||||
let mut padding_map = None;
|
||||
@@ -196,7 +217,17 @@ fn bake_in_strips(request: &BakeRequest, progress: &Progress, strip_texels: usiz
|
||||
let (sample_start_y, strip_sample_height) = (strip_start * samples_per_axis, rows * samples_per_axis);
|
||||
strip_mesh.uvs =
|
||||
request.mesh.uvs.iter().map(|uv| Vec2::new(uv.x, (uv.y * sample_height as f32 - sample_start_y as f32) / strip_sample_height as f32)).collect();
|
||||
let gbuffer = UvGBuffer::new(&strip_mesh, request.material, sample_width as u32, strip_sample_height as u32);
|
||||
let mut gbuffer = UvGBuffer::new(&strip_mesh, request.material, sample_width as u32, strip_sample_height as u32);
|
||||
for &(column, row) in excluded_tiles {
|
||||
let start_x = column as usize * tile_size.0 * samples_per_axis;
|
||||
let start_y = row as usize * tile_size.1 * samples_per_axis;
|
||||
let end_y = (start_y + tile_size.1 * samples_per_axis).min(sample_start_y + strip_sample_height);
|
||||
for sample_y in start_y.max(sample_start_y)..end_y {
|
||||
let first = (sample_y - sample_start_y) * sample_width + start_x;
|
||||
gbuffer.tri.get_mut(first..first + tile_size.0 * samples_per_axis).ok_or_else(strip_error)?.fill(NO_TRI);
|
||||
}
|
||||
}
|
||||
|
||||
let coverage_rows = covered.get_mut(strip_start * width..(strip_start + rows) * width).ok_or_else(strip_error)?;
|
||||
coverage_rows.par_chunks_mut(width).enumerate().for_each(|(row_index, row)| {
|
||||
for (x, covered_pixel) in row.iter_mut().enumerate() {
|
||||
@@ -255,15 +286,18 @@ fn bake_in_strips(request: &BakeRequest, progress: &Progress, strip_texels: usiz
|
||||
|
||||
let mut output: BTreeMap<BakedMap, Vec<f32>> = maps.into_iter().zip(buffers).collect();
|
||||
if from_normal {
|
||||
let normal = if settings.maps.is_enabled(BakedMap::Normal) { output.get(&BakedMap::Normal).cloned() } else { output.remove(&BakedMap::Normal) };
|
||||
if let (Some(normal), Some(curvature_pixels)) = (normal, output.get_mut(&BakedMap::Curvature)) {
|
||||
let world_normal =
|
||||
if settings.maps.is_enabled(BakedMap::WorldNormal) { output.get(&BakedMap::WorldNormal).cloned() } else { output.remove(&BakedMap::WorldNormal) };
|
||||
if let (Some(world_normal), Some(curvature_pixels)) = (world_normal, output.get_mut(&BakedMap::Curvature)) {
|
||||
let parameters = settings.maps.curvature.parameters.normal_map;
|
||||
map::curvature_from_normal(&normal, &covered, width, tile_size, parameters, curvature_pixels);
|
||||
let grid = map::TexelGrid { covered: &covered, size: (width, height), tile_size };
|
||||
map::curvature_from_normal(&world_normal, request.mesh, request.material, &grid, parameters, curvature_pixels);
|
||||
if parameters.enable_seams {
|
||||
map::fix_seams(request.mesh, request.material, &covered, (width, height), parameters.seams_intensity, curvature_pixels);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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));
|
||||
if let Some(padding_map) = padding_map {
|
||||
|
||||
@@ -12,11 +12,16 @@ pub(crate) use seam::fix_seams;
|
||||
mod position_projection;
|
||||
mod sampling;
|
||||
mod source;
|
||||
mod texel_grid;
|
||||
mod traced;
|
||||
mod transfer;
|
||||
mod transfer_keys;
|
||||
|
||||
pub(crate) use bake_context::BakeContext;
|
||||
pub(crate) use normal_curvature::curvature_from_normal;
|
||||
pub(crate) use sample::Sample;
|
||||
pub(crate) use sampling::{interpolate, welded};
|
||||
pub(crate) use texel_grid::TexelGrid;
|
||||
pub(crate) use traced::Traced;
|
||||
pub(crate) use transfer::Transfer;
|
||||
pub(crate) use transfer_keys::transfer_keys;
|
||||
@@ -1,28 +1,22 @@
|
||||
use super::curvature::Curvature;
|
||||
use super::sampling::{interpolate, pack, splitmix64, tangent_normal, welded};
|
||||
use super::sampling::{pack, splitmix64, tangent_normal};
|
||||
use super::{position_projection::PositionProjection, source::Source, traced::Traced, transfer::Transfer};
|
||||
use crate::skew::PreparedSkew;
|
||||
use crate::cage::{RayFrame, RayStart};
|
||||
use crate::tracing::{ANY, Hemisphere, Query, Ray, RayKind, RayScene, TraceMesh};
|
||||
use crate::{BakeError, BakeRequest};
|
||||
use crate::{BakeError, BakeRequest, MeshExtent};
|
||||
use rayon::prelude::*;
|
||||
use std::collections::HashMap;
|
||||
use texturecraft_core::{
|
||||
AmbientOcclusionAttenuation, BackfaceMode, BakeSettings, BakedMap, CageType, CurvatureMethod, MeshMatchMode, RayDistribution, RaySettings, SelfOcclusion,
|
||||
AmbientOcclusionAttenuation, BackfaceMode, BakeSettings, BakedMap, CurvatureMethod, MeshMatchMode, RayDistribution, RaySettings, SelfOcclusion,
|
||||
};
|
||||
use texturecraft_geom::glam::Vec3;
|
||||
use texturecraft_geom::{Hit, Mesh, Surface, surface_at};
|
||||
use texturecraft_geom::{Hit, Surface, surface_at};
|
||||
|
||||
const CURVATURE_CHUNK: usize = 1 << 15;
|
||||
|
||||
pub(crate) struct BakeContext<'a> {
|
||||
low: Source<'a>,
|
||||
high: Option<Source<'a>>,
|
||||
cage: Option<&'a Mesh>,
|
||||
skew: Option<PreparedSkew<'a>>,
|
||||
cage_paint: Option<&'a crate::BakePaintMap>,
|
||||
ray_normals: Vec<Vec3>,
|
||||
ray_frame: RayFrame<'a>,
|
||||
settings: &'a BakeSettings,
|
||||
eps: f32,
|
||||
frontal: f32,
|
||||
rear: f32,
|
||||
position: PositionProjection,
|
||||
@@ -36,36 +30,10 @@ pub(crate) struct BakeContext<'a> {
|
||||
impl<'a> BakeContext<'a> {
|
||||
pub(crate) fn new(request: &BakeRequest<'a>) -> Result<BakeContext<'a>, BakeError> {
|
||||
let settings = request.settings;
|
||||
let (bounds_min, bounds_max) = request.mesh.bounds();
|
||||
let mesh_diagonal = (bounds_max - bounds_min).length().max(1e-6);
|
||||
if !mesh_diagonal.is_finite() {
|
||||
return Err(BakeError::Invalid("mesh bounds are too large".into()));
|
||||
}
|
||||
|
||||
let mesh_scale = (bounds_max - bounds_min).max_element().max(1e-6);
|
||||
let mut name_keys = HashMap::new();
|
||||
let low = Source::new(request.mesh, request.bvh, request.low_base_color, &[], &settings.high_poly.low_suffix, &settings.high_poly, &mut name_keys);
|
||||
let high = request.high.map(|high_mesh| {
|
||||
Source::new(
|
||||
high_mesh.mesh,
|
||||
high_mesh.bvh,
|
||||
high_mesh.base_color,
|
||||
high_mesh.file_ids,
|
||||
&settings.high_poly.high_suffix,
|
||||
&settings.high_poly,
|
||||
&mut name_keys,
|
||||
)
|
||||
});
|
||||
let ray_normals = match settings.cage.average_normals && high.is_some() {
|
||||
true => {
|
||||
let (welded_indices, _, normals) = welded(request.mesh, mesh_diagonal);
|
||||
welded_indices.iter().map(|index| normals.get(*index as usize).copied().unwrap_or(Vec3::Y)).collect()
|
||||
}
|
||||
false => Vec::new(),
|
||||
};
|
||||
|
||||
let skew = request.skew.map(|skew_map| PreparedSkew::new(skew_map, request.mesh, mesh_scale, settings.skew)).transpose()?;
|
||||
let ray_epsilon = 1e-6 * mesh_diagonal;
|
||||
let extent = MeshExtent::of(request.mesh)?;
|
||||
let (low, high) = Source::of_request(request);
|
||||
let ray_frame = RayFrame::new(request, extent)?;
|
||||
let (mesh_scale, ray_epsilon) = (extent.scale, extent.ray_epsilon());
|
||||
let pass = |map: BakedMap, ray_settings: &RaySettings, kind: RayKind| {
|
||||
let half_angle_radians = (ray_settings.spread.clamp(0.0, 180.0) * 0.5).to_radians();
|
||||
let units = if ray_settings.relative_to_bounding_box { mesh_scale } else { 1.0 };
|
||||
@@ -91,27 +59,26 @@ impl<'a> BakeContext<'a> {
|
||||
pass.ignore_backface = parameters.ignore_backface;
|
||||
pass.same_key = parameters.self_occlusion == SelfOcclusion::SameMeshName;
|
||||
pass.attenuation = parameters.attenuation;
|
||||
pass.ground_height = parameters.ground_plane.enabled.then_some(bounds_min.y - parameters.ground_plane.offset);
|
||||
pass.ground_height = parameters.ground_plane.enabled.then_some(extent.bounds_min.y - parameters.ground_plane.offset);
|
||||
}
|
||||
|
||||
let mut bent = pass(BakedMap::BentNormal, &settings.maps.bent_normal.parameters.rays, RayKind::Occlusion);
|
||||
if let Some(pass) = &mut bent {
|
||||
pass.ignore_backface = settings.maps.bent_normal.parameters.ignore_backface;
|
||||
pass.same_key = settings.maps.bent_normal.parameters.self_occlusion == SelfOcclusion::SameMeshName;
|
||||
}
|
||||
|
||||
let mut thickness = pass(BakedMap::Thickness, &settings.maps.thickness.parameters.rays, RayKind::Thickness);
|
||||
if let Some(pass) = &mut thickness {
|
||||
pass.same_key = settings.maps.thickness.parameters.self_occlusion == SelfOcclusion::SameMeshName;
|
||||
}
|
||||
let cage_units = if settings.cage.relative_to_bounding_box { mesh_scale } else { 1.0 };
|
||||
|
||||
let cage_units = ray_frame.cage_units;
|
||||
Ok(BakeContext {
|
||||
low,
|
||||
high,
|
||||
cage: if settings.cage.kind == CageType::CustomFile { request.cage } else { None },
|
||||
skew,
|
||||
cage_paint: request.cage_paint,
|
||||
ray_normals,
|
||||
ray_frame,
|
||||
settings,
|
||||
eps: ray_epsilon,
|
||||
frontal: settings.cage.max_frontal * cage_units,
|
||||
rear: settings.cage.max_rear * cage_units,
|
||||
position: PositionProjection::new(request.mesh, request.material, settings.maps.position.parameters),
|
||||
@@ -140,22 +107,11 @@ impl<'a> BakeContext<'a> {
|
||||
}
|
||||
|
||||
pub(crate) fn transfer_ray(&self, surface: &Surface, barycentric: [f32; 2]) -> (Ray, f32) {
|
||||
let averaged_normal = interpolate(self.low.mesh, &self.ray_normals, surface.tri, barycentric).and_then(Vec3::try_normalize).unwrap_or(surface.nrm);
|
||||
let cage = self
|
||||
.cage
|
||||
.and_then(|cage_mesh| interpolate(cage_mesh, &cage_mesh.positions, surface.tri, barycentric))
|
||||
.map(|cage_position| surface.pos - cage_position)
|
||||
.filter(|offset| offset.length() > self.eps);
|
||||
let cage_scale = self.cage_paint.map_or(1.0, |map| map.sample(surface.uv));
|
||||
let (origin, direction, front) = match cage {
|
||||
Some(offset) => (surface.pos - offset, offset.normalize(), offset.length()),
|
||||
None => {
|
||||
let up = match &self.skew {
|
||||
Some(skew) => skew.correct(self.low.mesh, surface, averaged_normal),
|
||||
None => averaged_normal,
|
||||
};
|
||||
(surface.pos + up * self.frontal * cage_scale, -up, self.frontal * cage_scale)
|
||||
}
|
||||
let start = self.ray_frame.start(surface, barycentric);
|
||||
let origin = start.origin(surface.pos, self.frontal);
|
||||
let (direction, front) = match start {
|
||||
RayStart::CageMesh(offset) => (offset.normalize(), offset.length()),
|
||||
RayStart::Distance { up, scale } => (-up, self.frontal * scale),
|
||||
};
|
||||
let key = match self.settings.high_poly.match_mode {
|
||||
MeshMatchMode::Always => ANY,
|
||||
|
||||
@@ -1,42 +1,120 @@
|
||||
/// Divergence of the tangent-space normal map; positive curvature is convex
|
||||
use rayon::prelude::*;
|
||||
use texturecraft_core::NormalMapCurvatureSettings;
|
||||
use texturecraft_geom::glam::{Vec2, Vec3};
|
||||
use texturecraft_geom::{Mesh, NO_TRI, UvGBuffer};
|
||||
|
||||
use super::TexelGrid;
|
||||
|
||||
/// Output slope per unit of normal turn per texel at a 2048-texel tile and Details 0.5, set by eye on a hard-surface bake
|
||||
const SLOPE_AT_2K: f32 = 3.0;
|
||||
|
||||
/// How fast the baked world normal turns along the low poly's surface; positive curvature is convex
|
||||
pub(crate) fn curvature_from_normal(
|
||||
normal: &[f32],
|
||||
covered: &[bool],
|
||||
width: usize,
|
||||
tile_size: (usize, usize),
|
||||
settings: texturecraft_core::NormalMapCurvatureSettings,
|
||||
world_normal: &[f32],
|
||||
mesh: &Mesh,
|
||||
material: usize,
|
||||
grid: &TexelGrid,
|
||||
settings: NormalMapCurvatureSettings,
|
||||
output: &mut [f32],
|
||||
) {
|
||||
use rayon::prelude::*;
|
||||
let radius_texels = (tile_size.0.min(tile_size.1) / 512).max(1);
|
||||
let strength = 2.0f32.powf((settings.details - 0.5) * 4.0);
|
||||
let normal_component = |x: usize, y: usize, component: usize, fallback: f32| match covered.get(y * width + x) {
|
||||
Some(true) => normal.get((y * width + x) * 3 + component).copied().unwrap_or(fallback),
|
||||
_ => fallback,
|
||||
let TexelGrid { covered, size, tile_size } = *grid;
|
||||
let triangle_of_texel = triangle_of_each_texel(mesh, material, grid);
|
||||
let surface_directions = surface_direction_of_each_triangle(mesh, size);
|
||||
let normal_at = |index: usize| {
|
||||
let encoded = world_normal.get(index * 3..index * 3 + 3).and_then(|components| <[f32; 3]>::try_from(components).ok()).unwrap_or([0.5, 0.5, 1.0]);
|
||||
Vec3::from_array(encoded) * 2.0 - 1.0
|
||||
};
|
||||
output.par_chunks_mut(width).enumerate().for_each(|(y, row)| {
|
||||
|
||||
// Turn of the normal per texel, measured along the surface direction each texel axis points to
|
||||
let turn_along = |axis: usize| -> Vec<f32> {
|
||||
(0..covered.len())
|
||||
.into_par_iter()
|
||||
.map(|index| {
|
||||
let Some(direction) =
|
||||
triangle_of_texel.get(index).and_then(|triangle| surface_directions.get(*triangle as usize)).and_then(|pair| pair.get(axis).copied())
|
||||
else {
|
||||
return 0.0;
|
||||
};
|
||||
|
||||
let step = if axis == 0 { (1, 0) } else { (0, 1) };
|
||||
let forward = grid.neighbour(index, step.0, step.1);
|
||||
let backward = grid.neighbour(index, -step.0, -step.1);
|
||||
let change = match (forward, backward) {
|
||||
(Some(ahead), Some(behind)) => (normal_at(ahead) - normal_at(behind)) * 0.5,
|
||||
(Some(ahead), None) => normal_at(ahead) - normal_at(index),
|
||||
(None, Some(behind)) => normal_at(index) - normal_at(behind),
|
||||
(None, None) => Vec3::ZERO,
|
||||
};
|
||||
change.dot(direction)
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let (turn_along_x, turn_along_y) = (turn_along(0), turn_along(1));
|
||||
|
||||
let slope = SLOPE_AT_2K * tile_size.0.min(tile_size.1) as f32 / 2048.0 * 2.0f32.powf((settings.details - 0.5) * 4.0);
|
||||
output.par_chunks_mut(size.0).enumerate().for_each(|(y, row)| {
|
||||
for (x, value) in row.iter_mut().enumerate() {
|
||||
if covered.get(y * width + x) != Some(&true) {
|
||||
let index = y * size.0 + x;
|
||||
if covered.get(index) != Some(&true) {
|
||||
continue;
|
||||
}
|
||||
let (center_x, center_y) = (normal_component(x, y, 0, 0.5), normal_component(x, y, 1, 0.5));
|
||||
let (left, right) = (
|
||||
if x % tile_size.0 >= radius_texels { normal_component(x - radius_texels, y, 0, center_x) } else { center_x },
|
||||
if x % tile_size.0 + radius_texels < tile_size.0 && x + radius_texels < width {
|
||||
normal_component(x + radius_texels, y, 0, center_x)
|
||||
} else {
|
||||
center_x
|
||||
},
|
||||
);
|
||||
let (up, down) = (
|
||||
if y % tile_size.1 >= radius_texels { normal_component(x, y - radius_texels, 1, center_y) } else { center_y },
|
||||
if y % tile_size.1 + radius_texels < tile_size.1 && y + radius_texels < covered.len() / width.max(1) {
|
||||
normal_component(x, y + radius_texels, 1, center_y)
|
||||
} else {
|
||||
center_y
|
||||
},
|
||||
);
|
||||
*value = (0.5 + ((right - left) + (up - down)) * strength).clamp(0.0, 1.0);
|
||||
|
||||
// A 1-2-1 average across each derivative keeps lines equally wide in every direction
|
||||
let curvature = grid.average_along(&turn_along_x, index, (0, 1)) + grid.average_along(&turn_along_y, index, (1, 0));
|
||||
|
||||
// Rises at `slope` near flat and rolls off softly, so strong edges never clip into flat white
|
||||
*value = 0.5 + 0.5 * (2.0 * slope * curvature).tanh();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Unit surface directions of a texel step in x and in y on each triangle of the low poly
|
||||
fn surface_direction_of_each_triangle(mesh: &Mesh, size: (usize, usize)) -> Vec<[Vec3; 2]> {
|
||||
let texel_scale = Vec2::new(size.0 as f32, size.1 as f32);
|
||||
(0..mesh.indices.len() / 3)
|
||||
.map(|triangle| {
|
||||
let corner = |slot: usize| -> Option<(Vec3, Vec2)> {
|
||||
let vertex = *mesh.tri(triangle)?.get(slot)?;
|
||||
Some((*mesh.positions.get(vertex)?, *mesh.uvs.get(vertex)? * texel_scale))
|
||||
};
|
||||
let (Some((first_position, first_texel)), Some((second_position, second_texel)), Some((third_position, third_texel))) =
|
||||
(corner(0), corner(1), corner(2))
|
||||
else {
|
||||
return [Vec3::ZERO; 2];
|
||||
};
|
||||
|
||||
let (position_edge_1, position_edge_2) = (second_position - first_position, third_position - first_position);
|
||||
let (texel_edge_1, texel_edge_2) = (second_texel - first_texel, third_texel - first_texel);
|
||||
let determinant = texel_edge_1.perp_dot(texel_edge_2);
|
||||
// A triangle with no UV area has no texel directions
|
||||
if determinant.abs() < 1e-12 {
|
||||
return [Vec3::ZERO; 2];
|
||||
}
|
||||
|
||||
let along_x = (position_edge_1 * texel_edge_2.y - position_edge_2 * texel_edge_1.y) / determinant;
|
||||
let along_y = (position_edge_2 * texel_edge_1.x - position_edge_1 * texel_edge_2.x) / determinant;
|
||||
[along_x.normalize_or_zero(), along_y.normalize_or_zero()]
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Low-poly triangle under each covered texel; edge texels covered only by antialiasing borrow a neighbour's
|
||||
fn triangle_of_each_texel(mesh: &Mesh, material: usize, grid: &TexelGrid) -> Vec<u32> {
|
||||
let centres = UvGBuffer::new(mesh, material, grid.size.0 as u32, grid.size.1 as u32).tri;
|
||||
(0..centres.len())
|
||||
.into_par_iter()
|
||||
.map(|index| {
|
||||
let own = centres.get(index).copied().unwrap_or(NO_TRI);
|
||||
if own != NO_TRI || grid.covered.get(index) != Some(&true) {
|
||||
return own;
|
||||
}
|
||||
|
||||
[(1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (-1, -1), (1, -1), (-1, 1)]
|
||||
.into_iter()
|
||||
.filter_map(|(step_x, step_y)| grid.neighbour(index, step_x, step_y))
|
||||
.map(|neighbour| centres.get(neighbour).copied().unwrap_or(NO_TRI))
|
||||
.find(|triangle| *triangle != NO_TRI)
|
||||
.unwrap_or(NO_TRI)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -3,34 +3,43 @@ use std::ops::{Add, Mul};
|
||||
use texturecraft_geom::glam::Vec3;
|
||||
use texturecraft_geom::{Mesh, Surface};
|
||||
|
||||
pub(super) fn interpolate<T: Copy + Mul<f32, Output = T> + Add<Output = T>>(mesh: &Mesh, v: &[T], tri: u32, [b1, b2]: [f32; 2]) -> Option<T> {
|
||||
let [a, b, c] = mesh.tri(tri as usize)?;
|
||||
Some(*v.get(a)? * (1.0 - b1 - b2) + *v.get(b)? * b1 + *v.get(c)? * b2)
|
||||
/// `values` (one per vertex) at `barycentric` in triangle `triangle`
|
||||
pub(crate) fn interpolate<T: Copy + Mul<f32, Output = T> + Add<Output = T>>(mesh: &Mesh, values: &[T], triangle: u32, barycentric: [f32; 2]) -> Option<T> {
|
||||
let [first, second, third] = mesh.tri(triangle as usize)?;
|
||||
let [second_weight, third_weight] = barycentric;
|
||||
|
||||
Some(*values.get(first)? * (1.0 - second_weight - third_weight) + *values.get(second)? * second_weight + *values.get(third)? * third_weight)
|
||||
}
|
||||
|
||||
pub(super) fn welded(mesh: &Mesh, diag: f32) -> (Vec<u32>, Vec<Vec3>, Vec<Vec3>) {
|
||||
let q = diag * 1e-5;
|
||||
let mut ids: HashMap<[i64; 3], u32> = HashMap::new();
|
||||
let (mut pos, mut nrm) = (Vec::new(), Vec::<Vec3>::new());
|
||||
let weld: Vec<u32> = mesh
|
||||
/// Vertices closer than this fraction of the mesh diagonal count as one when welding
|
||||
const WELD_TOLERANCE_PER_DIAGONAL: f32 = 1e-5;
|
||||
|
||||
/// Vertices that share a position merged: each vertex's welded index, the welded positions and their averaged normals
|
||||
pub(crate) fn welded(mesh: &Mesh, diagonal: f32) -> (Vec<u32>, Vec<Vec3>, Vec<Vec3>) {
|
||||
let tolerance = diagonal * WELD_TOLERANCE_PER_DIAGONAL;
|
||||
let mut welded_index_of_cell: HashMap<[i64; 3], u32> = HashMap::new();
|
||||
let (mut positions, mut normal_sums) = (Vec::new(), Vec::<Vec3>::new());
|
||||
|
||||
let welded_indices: Vec<u32> = mesh
|
||||
.positions
|
||||
.iter()
|
||||
.zip(&mesh.normals)
|
||||
.map(|(p, n)| {
|
||||
let key = [p.x, p.y, p.z].map(|c| (c / q).round() as i64);
|
||||
let id = *ids.entry(key).or_insert_with(|| {
|
||||
pos.push(*p);
|
||||
nrm.push(Vec3::ZERO);
|
||||
(pos.len() - 1) as u32
|
||||
.map(|(position, normal)| {
|
||||
let cell = [position.x, position.y, position.z].map(|coordinate| (coordinate / tolerance).round() as i64);
|
||||
let welded_index = *welded_index_of_cell.entry(cell).or_insert_with(|| {
|
||||
positions.push(*position);
|
||||
normal_sums.push(Vec3::ZERO);
|
||||
(positions.len() - 1) as u32
|
||||
});
|
||||
if let Some(acc) = nrm.get_mut(id as usize) {
|
||||
*acc += *n;
|
||||
if let Some(normal_sum) = normal_sums.get_mut(welded_index as usize) {
|
||||
*normal_sum += *normal;
|
||||
}
|
||||
id
|
||||
welded_index
|
||||
})
|
||||
.collect();
|
||||
let nrm = nrm.into_iter().map(|n| n.try_normalize().unwrap_or(Vec3::ZERO)).collect();
|
||||
(weld, pos, nrm)
|
||||
|
||||
let normals = normal_sums.into_iter().map(|normal_sum| normal_sum.try_normalize().unwrap_or(Vec3::ZERO)).collect();
|
||||
(welded_indices, positions, normals)
|
||||
}
|
||||
|
||||
pub(super) fn splitmix64(x: u64) -> u64 {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use super::sampling::{generated_hue, interpolate, splitmix64};
|
||||
use crate::BakeRequest;
|
||||
use crate::tracing::{ANY, TraceMesh};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
@@ -21,6 +22,18 @@ pub(super) struct Source<'a> {
|
||||
}
|
||||
|
||||
impl<'a> Source<'a> {
|
||||
/// `request`'s low and high poly, their mesh names keyed from one shared table so the bake can match a low-poly part to its high-poly part
|
||||
pub(super) fn of_request(request: &BakeRequest<'a>) -> (Source<'a>, Option<Source<'a>>) {
|
||||
let settings = &request.settings.high_poly;
|
||||
let mut name_keys = HashMap::new();
|
||||
let low = Source::new(request.mesh, request.bvh, request.low_base_color, &[], &settings.low_suffix, settings, &mut name_keys);
|
||||
let high = request.high.map(|high_mesh| {
|
||||
Source::new(high_mesh.mesh, high_mesh.bvh, high_mesh.base_color, high_mesh.file_ids, &settings.high_suffix, settings, &mut name_keys)
|
||||
});
|
||||
|
||||
(low, high)
|
||||
}
|
||||
|
||||
pub(super) fn new(
|
||||
mesh: &'a Mesh,
|
||||
bvh: &'a Bvh,
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
/// Covered texels of a baked map, with UV tiles that neighbours never cross
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct TexelGrid<'a> {
|
||||
pub covered: &'a [bool],
|
||||
pub size: (usize, usize),
|
||||
pub tile_size: (usize, usize),
|
||||
}
|
||||
|
||||
impl TexelGrid<'_> {
|
||||
/// The covered texel one step away in the same tile, if any
|
||||
pub fn neighbour(&self, index: usize, step_x: isize, step_y: isize) -> Option<usize> {
|
||||
let (width, height) = self.size;
|
||||
let (x, y) = (index % width.max(1), index / width.max(1));
|
||||
let (next_x, next_y) = (x.checked_add_signed(step_x)?, y.checked_add_signed(step_y)?);
|
||||
if next_x >= width || next_y >= height {
|
||||
return None;
|
||||
}
|
||||
|
||||
let same_tile = next_x / self.tile_size.0.max(1) == x / self.tile_size.0.max(1) && next_y / self.tile_size.1.max(1) == y / self.tile_size.1.max(1);
|
||||
let next = next_y * width + next_x;
|
||||
(same_tile && self.covered.get(next) == Some(&true)).then_some(next)
|
||||
}
|
||||
|
||||
/// A 1-2-1 weighted average of `values` along `step`, over covered texels only
|
||||
pub fn average_along(&self, values: &[f32], index: usize, step: (isize, isize)) -> f32 {
|
||||
let centre = values.get(index).copied().unwrap_or(0.0);
|
||||
let sides = [self.neighbour(index, step.0, step.1), self.neighbour(index, -step.0, -step.1)];
|
||||
let (sum, weight) =
|
||||
sides.into_iter().flatten().fold((2.0 * centre, 2.0), |(sum, weight), side| (sum + values.get(side).copied().unwrap_or(0.0), weight + 1.0));
|
||||
sum / weight
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
use super::source::Source;
|
||||
use crate::BakeRequest;
|
||||
|
||||
/// The bake's mesh-name key of each low-poly and each high-poly triangle: with By Mesh Name a transfer ray from a low-poly triangle only hits high-poly triangles with its key
|
||||
pub(crate) fn transfer_keys(request: &BakeRequest) -> (Vec<u32>, Vec<u32>) {
|
||||
let (low, high) = Source::of_request(request);
|
||||
(low.key, high.map(|high| high.key).unwrap_or_default())
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
use crate::BakeError;
|
||||
use texturecraft_geom::Mesh;
|
||||
use texturecraft_geom::glam::Vec3;
|
||||
|
||||
/// Smallest size a mesh is treated as having, so a flat or empty mesh still gives finite distances
|
||||
const MIN_MESH_SIZE: f32 = 1e-6;
|
||||
|
||||
/// How far a ray starts past the surface it leaves, as a fraction of the mesh diagonal
|
||||
const RAY_EPSILON_PER_DIAGONAL: f32 = 1e-6;
|
||||
|
||||
/// The low-poly mesh's size, which scales the bake's relative distances
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) struct MeshExtent {
|
||||
pub(crate) bounds_min: Vec3,
|
||||
pub(crate) diagonal: f32,
|
||||
/// The bounding box's largest side
|
||||
pub(crate) scale: f32,
|
||||
}
|
||||
|
||||
impl MeshExtent {
|
||||
pub(crate) fn of(mesh: &Mesh) -> Result<MeshExtent, BakeError> {
|
||||
let (bounds_min, bounds_max) = mesh.bounds();
|
||||
let diagonal = (bounds_max - bounds_min).length().max(MIN_MESH_SIZE);
|
||||
if !diagonal.is_finite() {
|
||||
return Err(BakeError::Invalid("mesh bounds are too large".into()));
|
||||
}
|
||||
|
||||
Ok(MeshExtent { bounds_min, diagonal, scale: (bounds_max - bounds_min).max_element().max(MIN_MESH_SIZE) })
|
||||
}
|
||||
|
||||
/// How far a ray starts past the surface it leaves, in world units
|
||||
pub(crate) fn ray_epsilon(&self) -> f32 {
|
||||
RAY_EPSILON_PER_DIAGONAL * self.diagonal
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
use super::settings;
|
||||
use crate::cage::CORNERS;
|
||||
use crate::map::BakeContext;
|
||||
use crate::{BakePaintMap, BakeRequest, CageShell, HighPoly};
|
||||
use texturecraft_core::{BakedMap, CageType};
|
||||
use texturecraft_geom::glam::{Vec2, Vec3};
|
||||
use texturecraft_geom::{Bvh, Mesh, primitives, surface_at};
|
||||
|
||||
/// A painted map whose values vary over the UV square
|
||||
fn painted_map() -> BakePaintMap {
|
||||
let mut map = BakePaintMap::constant(0.25).resized(32, 32).unwrap();
|
||||
map.paint(&[Vec2::new(0.2, 0.3), Vec2::new(0.7, 0.6)], 0.3, 1.0, 0.5, 1.0).unwrap();
|
||||
map
|
||||
}
|
||||
|
||||
/// Every corner of `request`'s cage equals the origin of the bake's transfer ray at that corner, bit for bit
|
||||
fn assert_cage_matches_the_ray_origins(request: &BakeRequest) {
|
||||
let shell = CageShell::new(request).unwrap();
|
||||
let corners = shell.corners(request.settings.cage.max_frontal);
|
||||
let context = BakeContext::new(request).unwrap();
|
||||
let triangles: Vec<usize> = request.mesh.triangles_of(request.material).collect();
|
||||
assert_eq!(corners.len(), triangles.len() * 3);
|
||||
|
||||
for (corner_index, corner) in corners.iter().enumerate() {
|
||||
let barycentric = CORNERS[corner_index % 3];
|
||||
let surface = surface_at(request.mesh, triangles[corner_index / 3] as u32, barycentric[0], barycentric[1]).unwrap();
|
||||
let (ray, _) = context.transfer_ray(&surface, barycentric);
|
||||
assert_eq!(*corner, ray.origin, "corner {corner_index}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cage_corners_are_the_bake_ray_origins() {
|
||||
let low = primitives::cube(1.0);
|
||||
let high_mesh = primitives::sphere(0.8, 16, 8);
|
||||
let (low_bvh, high_bvh) = (Bvh::new(&low), Bvh::new(&high_mesh));
|
||||
let high = HighPoly { file_ids: &[], mesh: &high_mesh, bvh: &high_bvh, base_color: &[] };
|
||||
let (skew, cage_paint) = (painted_map(), painted_map());
|
||||
let mut bake_settings = settings(16, &[BakedMap::Normal]);
|
||||
bake_settings.cage.max_frontal = 0.03;
|
||||
bake_settings.skew.edge_protection = true;
|
||||
let request = |settings| BakeRequest {
|
||||
low_base_color: &[],
|
||||
mesh: &low,
|
||||
bvh: &low_bvh,
|
||||
material: 0,
|
||||
settings,
|
||||
high: Some(high),
|
||||
cage: None,
|
||||
skew: Some(&skew),
|
||||
cage_paint: Some(&cage_paint),
|
||||
tiles: (1, 1),
|
||||
};
|
||||
|
||||
assert_cage_matches_the_ray_origins(&request(&bake_settings));
|
||||
let face_normals = {
|
||||
let mut face_normals = bake_settings.clone();
|
||||
face_normals.cage.average_normals = false;
|
||||
face_normals.cage.relative_to_bounding_box = false;
|
||||
face_normals
|
||||
};
|
||||
assert_cage_matches_the_ray_origins(&request(&face_normals));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cage_follows_the_frontal_distance_and_a_cage_mesh() {
|
||||
let low = primitives::cube(1.0);
|
||||
let low_bvh = Bvh::new(&low);
|
||||
let high = HighPoly { file_ids: &[], mesh: &low, bvh: &low_bvh, base_color: &[] };
|
||||
let mut bake_settings = settings(16, &[BakedMap::Normal]);
|
||||
bake_settings.cage.relative_to_bounding_box = false;
|
||||
let request = BakeRequest {
|
||||
low_base_color: &[],
|
||||
mesh: &low,
|
||||
bvh: &low_bvh,
|
||||
material: 0,
|
||||
settings: &bake_settings,
|
||||
high: Some(high),
|
||||
cage: None,
|
||||
skew: None,
|
||||
cage_paint: None,
|
||||
tiles: (1, 1),
|
||||
};
|
||||
let shell = CageShell::new(&request).unwrap();
|
||||
let distance_from_the_cube = |max_frontal: f32| shell.corners(max_frontal).iter().map(|corner| corner.abs().max_element() - 0.5).fold(0.0, f32::max);
|
||||
|
||||
assert!(distance_from_the_cube(0.0).abs() < 1e-6, "at frontal 0 the cage is the low poly");
|
||||
// Averaged normals point diagonally at the corners, so a corner moves out by at least half the distance along each axis
|
||||
assert!(distance_from_the_cube(0.2) > 0.1 && distance_from_the_cube(0.2) <= 0.2 + 1e-6, "the cage grows with the frontal distance");
|
||||
assert_eq!(shell.edges.len(), low.wire_edges()[0].len(), "one wireframe line per polygon edge");
|
||||
|
||||
let cage_mesh = Mesh { positions: low.positions.iter().map(|position| *position * 1.5).collect(), ..low.clone() };
|
||||
let custom_settings = {
|
||||
let mut custom_settings = bake_settings.clone();
|
||||
custom_settings.cage.kind = CageType::CustomFile;
|
||||
custom_settings
|
||||
};
|
||||
let custom = BakeRequest { settings: &custom_settings, cage: Some(&cage_mesh), ..request };
|
||||
assert_cage_matches_the_ray_origins(&custom);
|
||||
let corners = CageShell::new(&custom).unwrap().corners(0.0);
|
||||
assert!(corners.iter().all(|corner| (corner.abs().max_element() - 0.75).abs() < 1e-6), "the cage mesh is drawn as it is");
|
||||
assert!(corners.iter().all(|corner| corner.is_finite() && *corner != Vec3::ZERO));
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
use super::settings;
|
||||
use crate::map::{BakeContext, transfer_keys};
|
||||
use crate::tracing::ANY;
|
||||
use crate::{BakeRequest, HighPoly, HighPolyReach, RayStart};
|
||||
use texturecraft_core::{BakedMap, MeshMatchMode};
|
||||
use texturecraft_geom::glam::Vec3;
|
||||
use texturecraft_geom::{Bvh, Mesh, primitives, surface_at};
|
||||
|
||||
/// Ray distances closer than this to the end of the ray's range are left out: rounding decides them
|
||||
const BOUNDARY: f32 = 1e-4;
|
||||
|
||||
/// How close the ray's hit must be to the vertex to count as reaching it
|
||||
const HIT_TOLERANCE: f32 = 1e-4;
|
||||
|
||||
/// A bumpy plane over the flat low poly, with the triangles right of `FLIPPED_FROM_X` wound the other way
|
||||
fn bumpy_high_poly() -> (Mesh, Vec<bool>) {
|
||||
const FLIPPED_FROM_X: f32 = 0.2;
|
||||
|
||||
let mut mesh = primitives::plane(1.0, 40);
|
||||
for position in &mut mesh.positions {
|
||||
position.y = 0.04 * (position.x * 9.0).sin() * (position.z * 7.0).cos() + 0.005;
|
||||
}
|
||||
|
||||
let mut flipped = vec![false; mesh.positions.len()];
|
||||
let mut unflipped = vec![false; mesh.positions.len()];
|
||||
for corners in mesh.indices.chunks_exact_mut(3) {
|
||||
let center_x = corners.iter().map(|&corner| mesh.positions[corner as usize].x).sum::<f32>() / 3.0;
|
||||
if center_x > FLIPPED_FROM_X {
|
||||
corners.swap(1, 2);
|
||||
}
|
||||
for &corner in corners.iter() {
|
||||
if center_x > FLIPPED_FROM_X { flipped[corner as usize] = true } else { unflipped[corner as usize] = true }
|
||||
}
|
||||
}
|
||||
// Vertices on the border face both ways: neither answer is right for them
|
||||
let mixed = flipped.iter().zip(&unflipped).map(|(flipped, unflipped)| *flipped && *unflipped).collect();
|
||||
(mesh, mixed)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_vertex_is_missed_exactly_when_the_bake_ray_misses_it() {
|
||||
let low = primitives::plane(1.0, 8);
|
||||
let (high_mesh, mixed) = bumpy_high_poly();
|
||||
let (low_bvh, high_bvh) = (Bvh::new(&low), Bvh::new(&high_mesh));
|
||||
let high = HighPoly { file_ids: &[], mesh: &high_mesh, bvh: &high_bvh, base_color: &[] };
|
||||
let back_facing = |triangle: u32, direction: Vec3| {
|
||||
let [a, b, c] = high_mesh.tri(triangle as usize).unwrap().map(|corner| high_mesh.positions[corner]);
|
||||
(b - a).cross(c - a).dot(direction) > 0.0
|
||||
};
|
||||
let mut checked = [0usize; 2];
|
||||
|
||||
for ignore_backface in [false, true] {
|
||||
for (max_frontal, max_rear) in [(0.0, 0.01), (0.02, 0.0), (0.02, 0.01), (0.05, 0.05)] {
|
||||
let mut bake_settings = settings(16, &[BakedMap::Normal]);
|
||||
bake_settings.cage.relative_to_bounding_box = false;
|
||||
bake_settings.high_poly.ignore_backface = ignore_backface;
|
||||
(bake_settings.cage.max_frontal, bake_settings.cage.max_rear) = (max_frontal, max_rear);
|
||||
let request = BakeRequest {
|
||||
low_base_color: &[],
|
||||
mesh: &low,
|
||||
bvh: &low_bvh,
|
||||
material: 0,
|
||||
settings: &bake_settings,
|
||||
high: Some(high),
|
||||
cage: None,
|
||||
skew: None,
|
||||
cage_paint: None,
|
||||
tiles: (1, 1),
|
||||
};
|
||||
let reach = HighPolyReach::new(&request).unwrap();
|
||||
let context = BakeContext::new(&request).unwrap();
|
||||
|
||||
for (vertex, vertex_reach) in reach.vertices.iter().enumerate() {
|
||||
let (vertex_reach, missed) = (vertex_reach.unwrap(), reach.missed(vertex, max_frontal, max_rear).unwrap());
|
||||
let RayStart::Distance { scale, .. } = vertex_reach.start else { panic!("a distance-based cage") };
|
||||
let height = vertex_reach.high_position.y - vertex_reach.low_position.y;
|
||||
let near_the_range_end = [max_frontal * scale, -max_rear].iter().any(|end| (height - end).abs() < BOUNDARY);
|
||||
if near_the_range_end || mixed[vertex] {
|
||||
continue;
|
||||
}
|
||||
|
||||
let nearest = low_bvh.nearest(vertex_reach.high_position, f32::INFINITY, &|_| true).unwrap();
|
||||
let surface = surface_at(&low, nearest.tri, nearest.u, nearest.v).unwrap();
|
||||
let (ray, _) = context.transfer_ray(&surface, [nearest.u, nearest.v]);
|
||||
let hit = high_bvh
|
||||
.closest_filtered(ray.origin, ray.direction, ray.max_distance, &|triangle| !(ignore_backface && back_facing(triangle, ray.direction)));
|
||||
let reaches_the_vertex = hit.is_some_and(|hit| (ray.origin + ray.direction * hit.t - vertex_reach.high_position).length() < HIT_TOLERANCE);
|
||||
assert_eq!(
|
||||
missed, !reaches_the_vertex,
|
||||
"vertex {vertex}, ignore backface {ignore_backface}, frontal {max_frontal}, rear {max_rear}: height {height}"
|
||||
);
|
||||
checked[usize::from(missed)] += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(checked[0] > 100 && checked[1] > 100, "both reached and missed vertices were compared: {checked:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_vertex_belongs_to_the_texture_set_whose_low_poly_is_nearest() {
|
||||
let mut low = primitives::plane(1.0, 4);
|
||||
let mut right = primitives::plane(1.0, 4);
|
||||
for position in &mut right.positions {
|
||||
position.x += 2.0;
|
||||
}
|
||||
low.append(&right);
|
||||
assert_eq!(low.materials.len(), 2, "each plane is its own texture set");
|
||||
let mut high_mesh = primitives::plane(3.0, 30);
|
||||
for position in &mut high_mesh.positions {
|
||||
position.x += 1.0;
|
||||
position.y = 0.3;
|
||||
}
|
||||
let (low_bvh, high_bvh) = (Bvh::new(&low), Bvh::new(&high_mesh));
|
||||
let bake_settings = settings(16, &[BakedMap::Normal]);
|
||||
let request = |material| BakeRequest {
|
||||
low_base_color: &[],
|
||||
mesh: &low,
|
||||
bvh: &low_bvh,
|
||||
material,
|
||||
settings: &bake_settings,
|
||||
high: Some(HighPoly { file_ids: &[], mesh: &high_mesh, bvh: &high_bvh, base_color: &[] }),
|
||||
cage: None,
|
||||
skew: None,
|
||||
cage_paint: None,
|
||||
tiles: (1, 1),
|
||||
};
|
||||
let (left, right) = (HighPolyReach::new(&request(0)).unwrap(), HighPolyReach::new(&request(1)).unwrap());
|
||||
|
||||
for (vertex, position) in high_mesh.positions.iter().enumerate() {
|
||||
let owners = (left.vertices[vertex].is_some(), right.vertices[vertex].is_some());
|
||||
assert!(owners != (true, true), "vertex {vertex} belongs to one set at most");
|
||||
if position.x < 0.9 {
|
||||
assert_eq!(owners, (true, false), "vertex {vertex} at {position} is over the left set");
|
||||
} else if position.x > 1.1 {
|
||||
assert_eq!(owners, (false, true), "vertex {vertex} at {position} is over the right set");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matching_by_mesh_name_misses_the_parts_with_another_name() {
|
||||
const HEIGHT_INSIDE_THE_CAGE: f32 = 0.01;
|
||||
|
||||
let mut low = primitives::plane(1.0, 8);
|
||||
low.submeshes[0].name = "part_low".into();
|
||||
let mut high_mesh = primitives::plane(0.5, 10);
|
||||
let mut other_part = primitives::plane(0.5, 10);
|
||||
for (mesh, center_x) in [(&mut high_mesh, -0.25), (&mut other_part, 0.25)] {
|
||||
for position in &mut mesh.positions {
|
||||
position.x += center_x;
|
||||
position.y = HEIGHT_INSIDE_THE_CAGE;
|
||||
}
|
||||
}
|
||||
high_mesh.append(&other_part);
|
||||
high_mesh.submeshes[0].name = "part_high".into();
|
||||
high_mesh.submeshes[1].name = "other_high".into();
|
||||
let (low_bvh, high_bvh) = (Bvh::new(&low), Bvh::new(&high_mesh));
|
||||
let mut bake_settings = settings(16, &[BakedMap::Normal]);
|
||||
bake_settings.cage.relative_to_bounding_box = false;
|
||||
bake_settings.cage.max_frontal = 0.02;
|
||||
bake_settings.high_poly.match_mode = MeshMatchMode::ByMeshName;
|
||||
let request = BakeRequest {
|
||||
low_base_color: &[],
|
||||
mesh: &low,
|
||||
bvh: &low_bvh,
|
||||
material: 0,
|
||||
settings: &bake_settings,
|
||||
high: Some(HighPoly { file_ids: &[], mesh: &high_mesh, bvh: &high_bvh, base_color: &[] }),
|
||||
cage: None,
|
||||
skew: None,
|
||||
cage_paint: None,
|
||||
tiles: (1, 1),
|
||||
};
|
||||
let reach = HighPolyReach::new(&request).unwrap();
|
||||
let context = BakeContext::new(&request).unwrap();
|
||||
let (_, high_keys) = transfer_keys(&request);
|
||||
|
||||
for (vertex, vertex_reach) in reach.vertices.iter().enumerate() {
|
||||
let (vertex_reach, missed) = (vertex_reach.unwrap(), reach.missed(vertex, 0.02, 0.01).unwrap());
|
||||
// On the line where the two parts meet, a ray reaches either part's triangles
|
||||
if vertex_reach.high_position.x.abs() < BOUNDARY {
|
||||
continue;
|
||||
}
|
||||
|
||||
let nearest = low_bvh.nearest(vertex_reach.high_position, f32::INFINITY, &|_| true).unwrap();
|
||||
let surface = surface_at(&low, nearest.tri, nearest.u, nearest.v).unwrap();
|
||||
let (ray, _) = context.transfer_ray(&surface, [nearest.u, nearest.v]);
|
||||
let same_name = |triangle: u32| ray.key == ANY || high_keys.get(triangle as usize) == Some(&ray.key);
|
||||
let hit = high_bvh.closest_filtered(ray.origin, ray.direction, ray.max_distance, &same_name);
|
||||
let reaches_the_vertex = hit.is_some_and(|hit| (ray.origin + ray.direction * hit.t - vertex_reach.high_position).length() < HIT_TOLERANCE);
|
||||
assert_eq!(missed, !reaches_the_vertex, "vertex {vertex} at {}", vertex_reach.high_position);
|
||||
assert_eq!(
|
||||
missed,
|
||||
vertex >= high_mesh.positions.len() - other_part.positions.len(),
|
||||
"only the part named like the low poly is reached: vertex {vertex}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_a_high_poly_no_vertex_has_a_reach() {
|
||||
let low = primitives::plane(1.0, 4);
|
||||
let low_bvh = Bvh::new(&low);
|
||||
let bake_settings = settings(16, &[BakedMap::Normal]);
|
||||
let request = BakeRequest {
|
||||
low_base_color: &[],
|
||||
mesh: &low,
|
||||
bvh: &low_bvh,
|
||||
material: 0,
|
||||
settings: &bake_settings,
|
||||
high: None,
|
||||
cage: None,
|
||||
skew: None,
|
||||
cage_paint: None,
|
||||
tiles: (1, 1),
|
||||
};
|
||||
|
||||
let reach = HighPolyReach::new(&request).unwrap();
|
||||
assert!(reach.vertices.is_empty());
|
||||
// Any cage distances: there is no vertex to miss
|
||||
assert_eq!(reach.missed(0, 0.02, 0.01), None);
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
use super::{bumped, covered_values, quad, quad_texel, settings, smooth_shaded_box, transfer};
|
||||
use texturecraft_core::{BakeSettings, BakedMap, CageSettings, CommonBakeSettings, CurvatureMethod, CurvatureSettings};
|
||||
use texturecraft_geom::glam::Vec3;
|
||||
use texturecraft_geom::primitives;
|
||||
|
||||
fn normal_map_settings(resolution: u32) -> BakeSettings {
|
||||
let mut base = settings(resolution, &[BakedMap::Curvature]);
|
||||
base.cage = CageSettings { max_frontal: 0.06, max_rear: 0.02, ..base.cage };
|
||||
base.common = CommonBakeSettings { dilation: 4, ..base.common };
|
||||
base.maps.curvature.parameters = CurvatureSettings { method: CurvatureMethod::NormalMap, ..base.maps.curvature.parameters };
|
||||
base.maps.curvature.parameters.normal_map.enable_seams = false;
|
||||
base
|
||||
}
|
||||
|
||||
fn coordinates_beyond(position: Vec3, threshold: f32) -> usize {
|
||||
position.abs().to_array().iter().filter(|coordinate| **coordinate > threshold).count()
|
||||
}
|
||||
|
||||
fn lowest_and_highest(values: impl IntoIterator<Item = f32>) -> (f32, f32) {
|
||||
values.into_iter().fold((f32::INFINITY, f32::NEG_INFINITY), |(lowest, highest), value| (lowest.min(value), highest.max(value)))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curvature_from_the_normal_map_sees_the_bump() {
|
||||
let out = transfer(&quad(), &bumped(0.1, 0.12), None, &normal_map_settings(64)).unwrap();
|
||||
assert!(!out.maps.contains_key(&BakedMap::WorldNormal), "the helper world normal map is not returned");
|
||||
|
||||
let curvature = &out.maps[&BakedMap::Curvature];
|
||||
assert!(curvature[quad_texel(64, 0.0, 0.0)] > 0.55, "convex top {}", curvature[quad_texel(64, 0.0, 0.0)]);
|
||||
assert!((curvature[quad_texel(64, 0.9, 0.9)] - 0.5).abs() < 0.02, "flat corner {}", curvature[quad_texel(64, 0.9, 0.9)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flat_faces_of_a_smooth_shaded_low_poly_stay_mid_grey() {
|
||||
let low = smooth_shaded_box();
|
||||
let curvature = covered_values(&low, &transfer(&low, &primitives::cube(2.0), None, &normal_map_settings(256)).unwrap(), BakedMap::Curvature);
|
||||
let faces: Vec<f32> = curvature.iter().filter(|(position, _)| coordinates_beyond(*position, 0.7) == 1).map(|(_, value)| *value).collect();
|
||||
|
||||
assert!(!faces.is_empty());
|
||||
assert!(faces.iter().all(|value| (value - 0.5).abs() < 0.02), "face range {:?}", lowest_and_highest(faces.iter().copied()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rounded_edge_is_one_convex_band() {
|
||||
let bevel = 0.1;
|
||||
let low = smooth_shaded_box();
|
||||
let curvature =
|
||||
covered_values(&low, &transfer(&low, &primitives::rounded_box(Vec3::ONE, bevel), None, &normal_map_settings(512)).unwrap(), BakedMap::Curvature);
|
||||
let across_one_edge = |from: f32, to: f32| {
|
||||
curvature
|
||||
.iter()
|
||||
.filter(move |(position, _)| (position.x - 1.0).abs() < 1e-3 && position.z.abs() < 0.3 && (from..to).contains(&position.y))
|
||||
.map(|(_, value)| *value)
|
||||
};
|
||||
|
||||
let inside_the_bevel = across_one_edge(1.0 - bevel * 0.8, 0.99).fold(1.0f32, f32::min);
|
||||
let next_to_the_bevel = lowest_and_highest(across_one_edge(0.5, 1.0 - bevel * 1.5));
|
||||
assert!(inside_the_bevel > 0.55, "the band dips inside the bevel: {inside_the_bevel}");
|
||||
assert!(next_to_the_bevel.0 > 0.48 && next_to_the_bevel.1 < 0.52, "next to the bevel {next_to_the_bevel:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_small_bump_has_no_ring_beyond_its_skirt() {
|
||||
let (resolution, sigma) = (512, 0.08);
|
||||
let out = transfer(&quad(), &bumped(0.08, sigma), None, &normal_map_settings(resolution)).unwrap();
|
||||
let curvature = &out.maps[&BakedMap::Curvature];
|
||||
let ring: Vec<f32> = (0..64)
|
||||
.map(|step| step as f32 / 64.0 * std::f32::consts::TAU)
|
||||
.flat_map(|angle| [3.0f32, 4.0].map(|radius| curvature[quad_texel(resolution, radius * sigma * angle.cos(), radius * sigma * angle.sin())]))
|
||||
.collect();
|
||||
|
||||
assert!(curvature[quad_texel(resolution, 0.0, 0.0)] > 0.6, "convex top {}", curvature[quad_texel(resolution, 0.0, 0.0)]);
|
||||
assert!(ring.iter().all(|value| (value - 0.5).abs() < 0.02), "ring {:?}", lowest_and_highest(ring.iter().copied()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn island_borders_of_flat_faces_do_not_streak() {
|
||||
let cube = primitives::cube(2.0);
|
||||
let curvature = covered_values(&cube, &transfer(&cube, &cube, None, &normal_map_settings(128)).unwrap(), BakedMap::Curvature);
|
||||
let faces: Vec<f32> = curvature.iter().filter(|(position, _)| coordinates_beyond(*position, 0.97) == 1).map(|(_, value)| *value).collect();
|
||||
|
||||
assert!(!faces.is_empty());
|
||||
assert!(faces.iter().all(|value| (value - 0.5).abs() < 0.01), "face range {:?}", lowest_and_highest(faces.iter().copied()));
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
use super::{Broken, settings};
|
||||
use crate::tracing::CpuTracer;
|
||||
use crate::{BakeRequest, Progress, bake, bake_in_strips, bake_tiles};
|
||||
use texturecraft_core::{BakeAntialiasing, BakedMap, TileGrid};
|
||||
use texturecraft_geom::glam::Vec2;
|
||||
use texturecraft_geom::{Bvh, primitives};
|
||||
|
||||
#[test]
|
||||
fn excluded_tiles_match_across_strips_antialiasing_and_cpu_fallback() {
|
||||
let mut mesh = primitives::udim_plane();
|
||||
let grid = TileGrid::of(&[1001, 1002]).unwrap();
|
||||
mesh.map_material_uvs(0, |uv| Vec2::from(grid.to_atlas(uv.to_array())));
|
||||
let bvh = Bvh::new(&mesh);
|
||||
let mut settings = settings(32, &[BakedMap::Position, BakedMap::AmbientOcclusion]);
|
||||
settings.maps.ao.parameters.rays.rays = 4;
|
||||
settings.common.antialiasing = BakeAntialiasing::Subsampling2x2;
|
||||
settings.common.dilation = 4;
|
||||
settings.common.apply_diffusion = true;
|
||||
let request = BakeRequest {
|
||||
mesh: &mesh,
|
||||
bvh: &bvh,
|
||||
material: 0,
|
||||
low_base_color: &[],
|
||||
settings: &settings,
|
||||
high: None,
|
||||
cage: None,
|
||||
skew: None,
|
||||
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 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"));
|
||||
|
||||
for map in [BakedMap::Position, BakedMap::AmbientOcclusion] {
|
||||
let components = map.components();
|
||||
for (index, pixel) in partial.maps[&map].chunks_exact(components).enumerate() {
|
||||
if index % 64 / 32 == excluded[0].0 as usize {
|
||||
assert_eq!(pixel, &map.neutral()[..components]);
|
||||
} else {
|
||||
assert_eq!(pixel, &full.maps[&map][index * components..(index + 1) * components]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
assert!(bake_tiles(&request, &Progress::new(), &[(2, 0)], None).is_err());
|
||||
assert!(bake_tiles(&request, &Progress::new(), &[(0, u32::MAX)], None).is_err());
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
use crate::{RayStart, VertexReach};
|
||||
use texturecraft_geom::glam::Vec3;
|
||||
|
||||
/// Cage distances in world units; every case's ray runs down the Y axis from 0.5 to -0.25
|
||||
const FRONTAL: f32 = 0.5;
|
||||
const REAR: f32 = 0.25;
|
||||
|
||||
/// A frontal distance a cage-mesh start must ignore: its ray starts on the cage
|
||||
const IGNORED_FRONTAL: f32 = 9.0;
|
||||
|
||||
/// How far past an end of the ray's range a vertex counts as outside it
|
||||
const PAST_THE_END: f32 = 1e-3;
|
||||
|
||||
/// A vertex at `height` above the low-poly point at the origin, its triangles facing `facing`
|
||||
fn vertex(start: RayStart, height: f32, facing: Vec3, name_matches: bool) -> VertexReach {
|
||||
VertexReach { low_position: Vec3::ZERO, start, high_position: Vec3::new(0.0, height, 0.0), high_facing: facing, name_matches }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_vertex_is_missed_outside_the_ray_range_on_another_part_or_facing_away() {
|
||||
// A painted cage amount of 2 doubles the frontal distance
|
||||
let starts = [
|
||||
(RayStart::Distance { up: Vec3::Y, scale: 1.0 }, FRONTAL),
|
||||
(RayStart::Distance { up: Vec3::Y, scale: 2.0 }, FRONTAL / 2.0),
|
||||
(RayStart::CageMesh(Vec3::new(0.0, -FRONTAL, 0.0)), IGNORED_FRONTAL),
|
||||
];
|
||||
let (top, bottom) = (FRONTAL, -REAR);
|
||||
// Height, facing, name matches, ignore backface: missed
|
||||
let cases = [
|
||||
(top, Vec3::Y, true, false, false),
|
||||
(bottom, Vec3::Y, true, false, false),
|
||||
(0.0, Vec3::Y, true, false, false),
|
||||
(top + PAST_THE_END, Vec3::Y, true, false, true),
|
||||
(bottom - PAST_THE_END, Vec3::Y, true, false, true),
|
||||
(0.0, Vec3::Y, false, false, true),
|
||||
(0.0, Vec3::NEG_Y, true, false, false),
|
||||
(0.0, Vec3::NEG_Y, true, true, true),
|
||||
(0.0, Vec3::Y, true, true, false),
|
||||
];
|
||||
|
||||
for (start, frontal) in starts {
|
||||
for (height, facing, name_matches, ignore_backface, missed) in cases {
|
||||
let reach = vertex(start, height, facing, name_matches);
|
||||
assert_eq!(
|
||||
reach.missed(frontal, REAR, ignore_backface),
|
||||
missed,
|
||||
"{start:?} at height {height}, facing {facing}, name matches {name_matches}, ignore backface {ignore_backface}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
+35
-16
@@ -14,9 +14,24 @@ use texturecraft_geom::primitives;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[path = "test/cage_shell.rs"]
|
||||
mod cage_shell;
|
||||
|
||||
#[path = "test/high_poly_reach.rs"]
|
||||
mod high_poly_reach;
|
||||
|
||||
#[path = "test/setting.rs"]
|
||||
mod setting;
|
||||
|
||||
#[path = "test/normal_map_curvature.rs"]
|
||||
mod normal_map_curvature;
|
||||
|
||||
#[path = "test/tile_selection.rs"]
|
||||
mod tile_selection;
|
||||
|
||||
#[path = "test/vertex_reach.rs"]
|
||||
mod vertex_reach;
|
||||
|
||||
fn settings(resolution: u32, maps: &[BakedMap]) -> BakeSettings {
|
||||
with_rays(
|
||||
{
|
||||
@@ -307,7 +322,7 @@ fn strips_match_a_single_pass() {
|
||||
tiles: (1, 1),
|
||||
};
|
||||
let whole = bake(&req, &Progress::new()).unwrap();
|
||||
let strips = bake_in_strips(&req, &Progress::new(), 128 * 2, &CpuTracer).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();
|
||||
@@ -562,6 +577,25 @@ fn a_high_poly_box_has_bright_edges_and_flat_faces() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_curvature_brightens_box_edges_and_never_darkens_them() {
|
||||
let mut bake_settings = settings(256, &[BakedMap::Curvature]);
|
||||
bake_settings.cage = CageSettings { max_frontal: 0.06, max_rear: 0.02, ..bake_settings.cage };
|
||||
bake_settings.maps.curvature.parameters.method = CurvatureMethod::default();
|
||||
|
||||
// A box has no concave texel, whether it is baked from itself or from a beveled high poly
|
||||
let low = primitives::cube(2.0);
|
||||
let high = primitives::rounded_box(Vec3::ONE, 0.15);
|
||||
let bakes = [("itself", run(&low, &bake_settings).unwrap()), ("a beveled high poly", transfer(&low, &high, None, &bake_settings).unwrap())];
|
||||
for (source, bake_output) in bakes {
|
||||
let curvature = covered_values(&low, &bake_output, BakedMap::Curvature);
|
||||
let darkest = curvature.iter().map(|(_, value)| *value).fold(1.0, f32::min);
|
||||
let brightest = curvature.iter().map(|(_, value)| *value).fold(0.0, f32::max);
|
||||
assert!(darkest > 0.45, "baked from {source}, darkest {darkest}");
|
||||
assert!(brightest > 0.6, "baked from {source}, brightest {brightest}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_narrow_high_poly_bevel_stays_bright() {
|
||||
let s = {
|
||||
@@ -635,21 +669,6 @@ fn bump_tilts_the_baked_normal() {
|
||||
assert!(height[quad_texel(64, 0.0, 0.0)] > height[quad_texel(64, 0.6, 0.6)] + 0.2, "the bump top is higher");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curvature_from_the_normal_map_sees_the_bump() {
|
||||
let s = {
|
||||
let mut base = settings(64, &[BakedMap::Curvature]);
|
||||
base.cage = CageSettings { max_frontal: 0.06, max_rear: 0.02, ..base.cage };
|
||||
base.maps.curvature.parameters = CurvatureSettings { method: CurvatureMethod::NormalMap, ..base.maps.curvature.parameters };
|
||||
base
|
||||
};
|
||||
let out = transfer(&quad(), &bumped(0.1, 0.4), None, &s).unwrap();
|
||||
assert!(!out.maps.contains_key(&BakedMap::Normal), "the helper normal map is not returned");
|
||||
let c = &out.maps[&BakedMap::Curvature];
|
||||
assert!(c[quad_texel(64, 0.0, 0.0)] > 0.55, "convex top {}", c[quad_texel(64, 0.0, 0.0)]);
|
||||
assert!((c[quad_texel(64, 0.9, 0.9)] - 0.5).abs() < 0.02, "flat corner {}", c[quad_texel(64, 0.9, 0.9)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bent_normals_point_away_from_occluders() {
|
||||
let mut m = quad();
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use texturecraft_core::{BakedMap, BlockScales};
|
||||
|
||||
/// Dense mesh maps with `components()` floats per texel in row-major order
|
||||
/// Each UV tile fills its block independently of the working resolution
|
||||
/// The width is `resolution`; height follows the output size and UV tile grid
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct BakedMaps {
|
||||
/// Width in texels
|
||||
pub resolution: u32,
|
||||
pub maps: BTreeMap<BakedMap, std::sync::Arc<Vec<f32>>>,
|
||||
}
|
||||
|
||||
impl BakedMaps {
|
||||
/// Sample a working atlas texel without resampling the stored bake
|
||||
pub fn sample_working(&self, map: BakedMap, x: u32, y: u32, size: (u32, u32), scales: &BlockScales) -> Option<[f32; 3]> {
|
||||
let uv = [(x as f32 + 0.5) / size.0.max(1) as f32, (y as f32 + 0.5) / size.1.max(1) as f32];
|
||||
self.sample_uv(map, scales.bake_uv(uv, size)?)
|
||||
}
|
||||
|
||||
/// Nearest sample in the uniform bake atlas
|
||||
pub fn sample_uv(&self, map: BakedMap, uv: [f32; 2]) -> Option<[f32; 3]> {
|
||||
if uv.iter().any(|value| !value.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let size = (self.resolution, self.height(map));
|
||||
self.sample(map, (uv[0] * size.0 as f32) as u32, (uv[1] * size.1 as f32) as u32, size)
|
||||
}
|
||||
|
||||
/// Height in texels of map `m`, from its length
|
||||
pub fn height(&self, m: BakedMap) -> u32 {
|
||||
self.maps.get(&m).map_or(0, |d| (d.len() / (self.resolution.max(1) as usize * m.components())) as u32)
|
||||
}
|
||||
|
||||
/// Sample the corresponding texel of an image with the supplied output size
|
||||
pub fn sample(&self, map: BakedMap, x: u32, y: u32, output_size: (u32, u32)) -> Option<[f32; 3]> {
|
||||
let data = self.maps.get(&map)?;
|
||||
let width = u64::from(self.resolution.max(1));
|
||||
let height = u64::from(self.height(map).max(1));
|
||||
let sample_x = (u64::from(x) * width / u64::from(output_size.0.max(1))).min(width - 1);
|
||||
let sample_y = (u64::from(y) * height / u64::from(output_size.1.max(1))).min(height - 1);
|
||||
let component_count = map.components();
|
||||
let offset = ((sample_y * width + sample_x) as usize).checked_mul(component_count)?;
|
||||
let texel = data.get(offset..offset.checked_add(component_count)?)?;
|
||||
Some(if component_count == 3 { [texel[0], texel[1], texel[2]] } else { [texel[0]; 3] })
|
||||
}
|
||||
|
||||
pub fn scalar(&self, m: BakedMap, x: u32, y: u32, size: (u32, u32)) -> Option<f32> {
|
||||
self.sample(m, x, y, size).map(|v| v[0])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
/// Deviations of ±0.5 (curvature − 0.5) stored as 16-bit integers.
|
||||
pub const DEVIATION_SCALE: f32 = i16::MAX as f32 * 2.0;
|
||||
|
||||
/// Curvature blurred at one detail size: deviations from flat, stored `step` times coarser than the map.
|
||||
pub struct CurvatureSizeLevel {
|
||||
pub step: u32,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
/// UV tile dimensions in stored texels; interpolation must stay inside one tile
|
||||
pub block: (u32, u32),
|
||||
pub deviation: Vec<i16>,
|
||||
}
|
||||
|
||||
impl CurvatureSizeLevel {
|
||||
/// The deviation at map texel `(x, y)`, interpolated within its UV tile
|
||||
pub fn sample(&self, x: u32, y: u32) -> f32 {
|
||||
if self.width == 0 || self.height == 0 {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
let step = self.step.max(1);
|
||||
let axis = |texel: u32, block: u32, length: u32| {
|
||||
let block = block.max(1);
|
||||
let first = if block >= length { 0 } else { (texel / block.saturating_mul(step) * block).min(length - 1) };
|
||||
let last = first.saturating_add(block - 1).min(length - 1);
|
||||
let position = ((texel as f32 + 0.5) / step as f32 - 0.5).clamp(first as f32, last as f32);
|
||||
let lower = position.floor() as u32;
|
||||
(lower, (lower + 1).min(last), position - lower as f32)
|
||||
};
|
||||
let (x0, x1, blend_x) = axis(x, self.block.0, self.width);
|
||||
let (y0, y1, blend_y) = axis(y, self.block.1, self.height);
|
||||
let stored = |x: u32, y: u32| self.deviation.get((y * self.width + x) as usize).map_or(0.0, |value| f32::from(*value) / DEVIATION_SCALE);
|
||||
let top = stored(x0, y0) + (stored(x1, y0) - stored(x0, y0)) * blend_x;
|
||||
let bottom = stored(x0, y1) + (stored(x1, y1) - stored(x0, y1)) * blend_x;
|
||||
top + (bottom - top) * blend_y
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn samples_blend_the_stored_texels() {
|
||||
let level = CurvatureSizeLevel { step: 2, width: 2, height: 1, block: (2, 1), deviation: vec![0, (0.25 * DEVIATION_SCALE) as i16] };
|
||||
assert!(level.sample(0, 0).abs() < 1e-4, "the first stored texel covers map texels 0 and 1");
|
||||
assert!((level.sample(3, 0) - 0.25).abs() < 1e-3);
|
||||
assert!(level.sample(2, 0) > 0.0 && level.sample(2, 0) < 0.25, "between stored texels the value blends");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,447 @@
|
||||
//! The baked curvature map at the detail sizes of curvature generators, built once per map and layout.
|
||||
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex, Weak};
|
||||
|
||||
use rayon::prelude::*;
|
||||
use texturecraft_core::{BakedMap, BlockScales, CurvatureDetail};
|
||||
use texturecraft_texel::dilate::{DilationMap, NONE};
|
||||
|
||||
use crate::curvature_size_level::{CurvatureSizeLevel, DEVIATION_SCALE};
|
||||
use crate::eval::{BLUR_BOX_PASSES, Inputs, blur};
|
||||
|
||||
/// The curvature map padded past its UV islands and blurred at each size of [`CurvatureDetail::SIZES`] after the first.
|
||||
pub struct CurvatureSizes {
|
||||
/// One per blurred size, built once a generator gives that size a weight above 0.
|
||||
pub levels: Vec<Option<Arc<CurvatureSizeLevel>>>,
|
||||
}
|
||||
|
||||
/// The bake map size, its UV tile block and the working texture size a cache entry was built for.
|
||||
type CacheKey = ((u32, u32), (u32, u32), (u32, u32));
|
||||
|
||||
/// Built sizes by the curvature data they come from, their layout and the tiles' scales.
|
||||
type CacheEntry = (Weak<Vec<f32>>, CacheKey, BlockScales, Arc<CurvatureSizes>);
|
||||
|
||||
static CACHE: Mutex<Vec<CacheEntry>> = Mutex::new(Vec::new());
|
||||
|
||||
// Undo snapshots keep old maps alive; their derived levels must not grow with the history
|
||||
const CACHE_BYTES: usize = 256 << 20;
|
||||
const CACHE_MAPS: usize = 16;
|
||||
|
||||
impl CurvatureSizes {
|
||||
/// The sizes of the texture set `inp` composites, holding at least those `needed` marks (one flag per blurred size); None without a baked curvature map or a needed size.
|
||||
pub fn of(inp: &Inputs, needed: &[bool]) -> Option<Arc<CurvatureSizes>> {
|
||||
let curvature = inp.baked.maps.get(&BakedMap::Curvature)?;
|
||||
let (width, height) = (inp.baked.resolution, inp.baked.height(BakedMap::Curvature));
|
||||
if !needed.contains(&true) || width == 0 || height == 0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let grid = inp.project.texture_set(inp.ts).ok().and_then(|set| set.tile_grid());
|
||||
let block = grid.map_or((width, height), |grid| (width / grid.cols.max(1), height / grid.rows.max(1)));
|
||||
let key = ((width, height), block, (inp.gbuf.width, inp.gbuf.height));
|
||||
let built = cached(curvature, key, &inp.block_scales);
|
||||
if let Some(sizes) = built.as_ref().filter(|sizes| sizes.holds(needed)) {
|
||||
return Some(sizes.clone());
|
||||
}
|
||||
|
||||
// Built without the cache locked: the build runs parallel work, and a thread waiting on it may composite a tile that asks the cache again
|
||||
let covered = covered_texels(inp, (width, height));
|
||||
let sizes = CurvatureSizes::build(curvature, (width, height), &covered, block, needed, built.as_deref());
|
||||
Some(store(curvature, key, &inp.block_scales, sizes))
|
||||
}
|
||||
|
||||
/// Whether every size `needed` marks is built.
|
||||
fn holds(&self, needed: &[bool]) -> bool {
|
||||
needed.iter().zip(&self.levels).all(|(needs, level)| !needs || level.is_some())
|
||||
}
|
||||
|
||||
/// Pad and blur each UV tile at the requested sizes, reusing levels already in `built`
|
||||
fn build(
|
||||
curvature: &[f32],
|
||||
(width, height): (u32, u32),
|
||||
covered: &[bool],
|
||||
block: (u32, u32),
|
||||
needed: &[bool],
|
||||
built: Option<&CurvatureSizes>,
|
||||
) -> CurvatureSizes {
|
||||
let padding = DilationMap::in_rectangular_blocks(covered, width, height, None, block);
|
||||
let deviation: Vec<f32> =
|
||||
padding.src.par_iter().map(|&source| if source == NONE { 0.0 } else { curvature.get(source as usize).copied().unwrap_or(0.5) - 0.5 }).collect();
|
||||
let (block_width, block_height) = (block.0.max(1).min(width), block.1.max(1).min(height));
|
||||
|
||||
let levels = CurvatureDetail::SIZES
|
||||
.iter()
|
||||
.skip(1)
|
||||
.enumerate()
|
||||
.map(|(level, size)| {
|
||||
if let Some(existing) = built.and_then(|sizes| sizes.levels.get(level)).and_then(Option::clone) {
|
||||
return Some(existing);
|
||||
}
|
||||
if !needed.get(level).copied().unwrap_or(false) {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Sizes are texels at 2K; a blur this wide holds nothing finer than half its radius, so it is stored that much coarser
|
||||
let radius = (size * block_width as f32 / 2048.0).round().max(1.0) as u32;
|
||||
let mut step = (radius / 2).max(1).next_power_of_two();
|
||||
// A coarse cell must not average curvature from different UV tiles
|
||||
while !block_width.is_multiple_of(step) || !block_height.is_multiple_of(step) {
|
||||
step /= 2;
|
||||
}
|
||||
|
||||
let mut blurred = deviation.clone();
|
||||
for block_y in (0..height).step_by(block_height as usize) {
|
||||
for block_x in (0..width).step_by(block_width as usize) {
|
||||
let region = (block_x, block_y, block_width.min(width - block_x), block_height.min(height - block_y));
|
||||
blur_block(&mut blurred, width, region, radius);
|
||||
}
|
||||
}
|
||||
Some(Arc::new(coarsen(&blurred, (width, height), step, (block_width, block_height))))
|
||||
})
|
||||
.collect();
|
||||
CurvatureSizes { levels }
|
||||
}
|
||||
}
|
||||
|
||||
/// The cached sizes of `curvature` for layout `key` and tile `scales`, if any
|
||||
fn cached(curvature: &Arc<Vec<f32>>, key: CacheKey, scales: &BlockScales) -> Option<Arc<CurvatureSizes>> {
|
||||
let mut cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
cache.retain(|(source, ..)| source.strong_count() > 0);
|
||||
let index = cache.iter().position(|entry| is_entry_for(entry, curvature, key, scales))?;
|
||||
let entry = cache.remove(index);
|
||||
let sizes = entry.3.clone();
|
||||
cache.push(entry);
|
||||
Some(sizes)
|
||||
}
|
||||
|
||||
/// Cache `sizes`, merging any levels another thread stored meanwhile
|
||||
fn store(curvature: &Arc<Vec<f32>>, key: CacheKey, scales: &BlockScales, sizes: CurvatureSizes) -> Arc<CurvatureSizes> {
|
||||
let mut cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
let sizes = if let Some((.., cached_sizes)) = cache.iter().find(|entry| is_entry_for(entry, curvature, key, scales)) {
|
||||
let levels = cached_sizes.levels.iter().zip(sizes.levels).map(|(cached, built)| cached.clone().or(built)).collect();
|
||||
CurvatureSizes { levels }
|
||||
} else {
|
||||
sizes
|
||||
};
|
||||
|
||||
// One layout per curvature map, with the most recently used map at the end
|
||||
cache.retain(|(source, ..)| source.strong_count() > 0 && !std::ptr::eq(source.as_ptr(), Arc::as_ptr(curvature)));
|
||||
let sizes = Arc::new(sizes);
|
||||
cache.push((Arc::downgrade(curvature), key, scales.clone(), sizes.clone()));
|
||||
trim_cache(&mut cache, CACHE_BYTES);
|
||||
sizes
|
||||
}
|
||||
|
||||
/// Evict the least recently used maps, retaining the newest even if it alone exceeds the budget
|
||||
fn trim_cache(cache: &mut Vec<CacheEntry>, budget: usize) {
|
||||
// Keeping the newest prevents a large atlas from rebuilding its levels for every tile
|
||||
let mut bytes = 0usize;
|
||||
let mut keep = 0;
|
||||
for (.., sizes) in cache.iter().rev() {
|
||||
let size = sizes.levels.iter().flatten().map(|level| level.deviation.len().saturating_mul(size_of::<i16>())).fold(0usize, usize::saturating_add);
|
||||
bytes = bytes.saturating_add(size);
|
||||
if keep > 0 && (bytes > budget || keep == CACHE_MAPS) {
|
||||
break;
|
||||
}
|
||||
keep += 1;
|
||||
}
|
||||
cache.drain(..cache.len() - keep);
|
||||
}
|
||||
|
||||
/// Whether cache `entry` holds the sizes of `curvature` for layout `key` and tile `scales`.
|
||||
fn is_entry_for((source, cached_key, cached_scales, _): &CacheEntry, curvature: &Arc<Vec<f32>>, key: CacheKey, scales: &BlockScales) -> bool {
|
||||
source.upgrade().is_some_and(|data| Arc::ptr_eq(&data, curvature)) && *cached_key == key && cached_scales == scales
|
||||
}
|
||||
|
||||
/// The bake atlas texels (`width × height`) overlapped by covered working texels of `inp`
|
||||
fn covered_texels(inp: &Inputs, (width, height): (u32, u32)) -> Vec<bool> {
|
||||
let working_size = (inp.gbuf.width, inp.gbuf.height);
|
||||
if working_size == (width, height) && inp.block_scales == BlockScales::default() {
|
||||
return (0..width * height).into_par_iter().map(|texel| inp.gbuf.covered(texel as usize)).collect();
|
||||
}
|
||||
|
||||
let covered: Vec<AtomicBool> = (0..width * height).map(|_| AtomicBool::new(false)).collect();
|
||||
(0..working_size.0 * working_size.1).into_par_iter().filter(|texel| inp.gbuf.covered(*texel as usize)).for_each(|texel| {
|
||||
let (x, y) = (texel % working_size.0, texel / working_size.0);
|
||||
let uv = [(x as f32 + 0.5) / working_size.0 as f32, (y as f32 + 0.5) / working_size.1 as f32];
|
||||
if let Some(baked_uv) = inp.block_scales.bake_uv(uv, working_size) {
|
||||
// A lower-resolution working texel covers a whole rectangle in the bake, not just its center
|
||||
let scale = inp.block_scales.at(x, y);
|
||||
let footprint = |center: f32, baked: u32, working: u32| {
|
||||
let half_width = 0.5 * baked as f32 / (working as f32 * scale);
|
||||
let center = center * baked as f32;
|
||||
((center - half_width).floor().max(0.0) as u32)..((center + half_width).ceil() as u32).min(baked)
|
||||
};
|
||||
let columns = footprint(baked_uv[0], width, working_size.0);
|
||||
for baked_y in footprint(baked_uv[1], height, working_size.1) {
|
||||
for baked_x in columns.clone() {
|
||||
if let Some(slot) = covered.get((baked_y * width + baked_x) as usize) {
|
||||
slot.store(true, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
covered.into_iter().map(AtomicBool::into_inner).collect()
|
||||
}
|
||||
|
||||
/// Blur the `(left, top, region_width, region_height)` block of `data` (`width` texels per row) in place, reading nothing outside it.
|
||||
fn blur_block(data: &mut [f32], width: u32, (left, top, region_width, region_height): (u32, u32, u32, u32), radius: u32) {
|
||||
let rows = top..top + region_height;
|
||||
let mut block: Vec<f32> =
|
||||
rows.flat_map(|y| (left..left + region_width).map(move |x| (y * width + x) as usize)).map(|index| data.get(index).copied().unwrap_or(0.0)).collect();
|
||||
blur(&mut block, region_width as usize, region_height as usize, radius as usize);
|
||||
|
||||
// The blur reads zero past the block's edges; dividing by the share of its window inside the block keeps the edges at full strength
|
||||
let column_weights = window_inside(region_width as usize, radius as usize);
|
||||
let row_weights = window_inside(region_height as usize, radius as usize);
|
||||
for (values, row_weight) in block.chunks_mut(region_width as usize).zip(&row_weights) {
|
||||
for (value, column_weight) in values.iter_mut().zip(&column_weights) {
|
||||
*value /= row_weight * column_weight;
|
||||
}
|
||||
}
|
||||
|
||||
for (row, values) in block.chunks(region_width as usize).enumerate() {
|
||||
let start = ((top + row as u32) * width + left) as usize;
|
||||
if let Some(target) = data.get_mut(start..start + values.len()) {
|
||||
target.copy_from_slice(values);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The share of the [`blur`] window at each texel of a line `length` long that falls inside it: 1 from three radii in.
|
||||
fn window_inside(length: usize, radius: usize) -> Vec<f32> {
|
||||
let window = (2 * radius + 1) as f64;
|
||||
let mut weights = vec![1.0f64; length];
|
||||
for _ in 0..BLUR_BOX_PASSES {
|
||||
let running_totals: Vec<f64> = std::iter::once(0.0)
|
||||
.chain(weights.iter().scan(0.0, |total, weight| {
|
||||
*total += weight;
|
||||
Some(*total)
|
||||
}))
|
||||
.collect();
|
||||
let total_at = |end: usize| running_totals.get(end.min(length)).copied().unwrap_or(0.0);
|
||||
weights = (0..length).map(|texel| (total_at(texel + radius + 1) - total_at(texel.saturating_sub(radius))) / window).collect();
|
||||
}
|
||||
weights.into_iter().map(|weight| weight as f32).collect()
|
||||
}
|
||||
|
||||
/// `data` averaged over `step × step` squares, clipping the last cells to the map
|
||||
fn coarsen(data: &[f32], (width, height): (u32, u32), step: u32, block: (u32, u32)) -> CurvatureSizeLevel {
|
||||
let (coarse_width, coarse_height) = (width.div_ceil(step), height.div_ceil(step));
|
||||
let deviation = (0..coarse_width * coarse_height)
|
||||
.into_par_iter()
|
||||
.map(|cell| {
|
||||
let (cell_x, cell_y) = (cell % coarse_width, cell / coarse_width);
|
||||
let columns = cell_x * step..((cell_x + 1) * step).min(width);
|
||||
let rows = cell_y * step..((cell_y + 1) * step).min(height);
|
||||
let count = (columns.len() * rows.len()).max(1) as f32;
|
||||
let texels = rows.flat_map(|y| columns.clone().map(move |x| (y * width + x) as usize));
|
||||
let mean = texels.map(|index| data.get(index).copied().unwrap_or(0.0)).sum::<f32>() / count;
|
||||
(mean * DEVIATION_SCALE).round().clamp(i16::MIN as f32, i16::MAX as f32) as i16
|
||||
})
|
||||
.collect();
|
||||
CurvatureSizeLevel { step, width: coarse_width, height: coarse_height, block: (block.0.div_ceil(step), block.1.div_ceil(step)), deviation }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn coarse_sizes_do_not_blend_between_uv_tiles() {
|
||||
let (width, height) = (512, 512);
|
||||
let block = (256, 256);
|
||||
let curvature: Vec<f32> = (0..width * height).map(|texel| if (texel % width) / block.0 == (texel / width) / block.1 { 0.8 } else { 0.2 }).collect();
|
||||
let covered = vec![true; curvature.len()];
|
||||
let sizes = CurvatureSizes::build(&curvature, (width, height), &covered, block, &[true; CurvatureDetail::BLURRED_SIZES], None);
|
||||
|
||||
for level in sizes.levels.iter().flatten() {
|
||||
for (x, y) in [(255, 128), (256, 128), (128, 255), (128, 256), (255, 255), (256, 256)] {
|
||||
let expected = curvature[(y * width + x) as usize] - 0.5;
|
||||
assert!((level.sample(x, y) - expected).abs() < 0.001, "step {} at ({x}, {y}): {} instead of {expected}", level.step, level.sample(x, y));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn coverage_preserves_bake_texels_above_the_working_resolution() {
|
||||
use texturecraft_core::{Project, TextureSet};
|
||||
use texturecraft_geom::{UvGBuffer, primitives};
|
||||
|
||||
let mesh = primitives::plane(2.0, 1);
|
||||
let mut project = Project::new("Coverage", "builtin:plane");
|
||||
project.texture_sets.push(TextureSet::new("Plane", 0, 64));
|
||||
let gbuf = UvGBuffer::new(&mesh, 0, 64, 64);
|
||||
let pixels = Default::default();
|
||||
let images = Default::default();
|
||||
let baked = Default::default();
|
||||
let inputs = Inputs {
|
||||
project: &project,
|
||||
ts: 0,
|
||||
mesh: &mesh,
|
||||
gbuf: &gbuf,
|
||||
pixels: &pixels,
|
||||
baked: &baked,
|
||||
block_scales: BlockScales::default(),
|
||||
preview: None,
|
||||
images: &images,
|
||||
bounds: mesh.bounds(),
|
||||
};
|
||||
|
||||
for size in [(32, 32), (64, 64), (128, 128), (128, 32)] {
|
||||
let coverage = covered_texels(&inputs, size);
|
||||
assert!(coverage.iter().all(|covered| *covered), "the plane covers the entire {size:?} bake, including between working texel centers");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn coverage_expands_scaled_tiles_without_crossing_block_borders() {
|
||||
use texturecraft_core::{Project, TextureSet};
|
||||
use texturecraft_geom::{NO_TRI, UvGBuffer, primitives};
|
||||
|
||||
let mesh = primitives::plane(2.0, 1);
|
||||
let mut project = Project::new("Tile coverage", "builtin:plane");
|
||||
let mut set = TextureSet::new("Tiles", 0, 64);
|
||||
set.uv_tiles = vec![1001, 1002, 1003];
|
||||
set.tile_resolutions.insert(1002, 32);
|
||||
let scales = set.block_scales();
|
||||
project.texture_sets.push(set);
|
||||
let mut gbuf = UvGBuffer::new(&mesh, 0, 192, 64);
|
||||
for (index, triangle) in gbuf.tri.iter_mut().enumerate() {
|
||||
if !(64..96).contains(&(index % 192)) || index / 192 >= 32 {
|
||||
*triangle = NO_TRI;
|
||||
}
|
||||
}
|
||||
let pixels = Default::default();
|
||||
let images = Default::default();
|
||||
let baked = Default::default();
|
||||
let inputs = Inputs {
|
||||
project: &project,
|
||||
ts: 0,
|
||||
mesh: &mesh,
|
||||
gbuf: &gbuf,
|
||||
pixels: &pixels,
|
||||
baked: &baked,
|
||||
block_scales: scales,
|
||||
preview: None,
|
||||
images: &images,
|
||||
bounds: mesh.bounds(),
|
||||
};
|
||||
|
||||
let covered = covered_texels(&inputs, (384, 128));
|
||||
for (index, covered) in covered.iter().enumerate() {
|
||||
assert_eq!(*covered, (128..256).contains(&(index % 384)), "bake texel ({}, {})", index % 384, index / 384);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unused_maps_are_evicted_even_while_undo_keeps_the_sources_alive() {
|
||||
let sources: Vec<_> = (0..=CACHE_MAPS).map(|_| Arc::new(vec![0.5; 16])).collect();
|
||||
let scales = BlockScales::default();
|
||||
let key = ((4, 4), (4, 4), (4, 4));
|
||||
let sizes = store(&sources[0], key, &scales, CurvatureSizes { levels: Vec::new() });
|
||||
let first = Arc::downgrade(&sizes);
|
||||
drop(sizes);
|
||||
for source in sources.iter().skip(1) {
|
||||
store(source, key, &scales, CurvatureSizes { levels: Vec::new() });
|
||||
}
|
||||
|
||||
assert!(first.upgrade().is_none(), "undo history may retain the bake, but not an unlimited number of derived maps");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cache_budget_evicts_old_levels_but_keeps_one_large_map() {
|
||||
let source = Arc::new(vec![0.5]);
|
||||
let key = ((1, 1), (1, 1), (1, 1));
|
||||
let entry = || {
|
||||
let level = CurvatureSizeLevel { step: 1, width: 4, height: 1, block: (4, 1), deviation: vec![0; 4] };
|
||||
let sizes = CurvatureSizes { levels: vec![Some(Arc::new(level))] };
|
||||
(Arc::downgrade(&source), key, BlockScales::default(), Arc::new(sizes))
|
||||
};
|
||||
let mut cache = vec![entry(), entry(), entry()];
|
||||
let oldest = Arc::downgrade(&cache[0].3);
|
||||
let newest = cache[2].3.clone();
|
||||
|
||||
trim_cache(&mut cache, 16);
|
||||
assert_eq!(cache.len(), 2);
|
||||
assert!(oldest.upgrade().is_none());
|
||||
trim_cache(&mut cache, 1);
|
||||
assert_eq!(cache.len(), 1, "the active map must not rebuild once per composite tile");
|
||||
assert!(Arc::ptr_eq(&cache[0].3, &newest));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn padding_keeps_an_island_border_from_reading_flat() {
|
||||
let map_size: u32 = 64;
|
||||
let left_half = |texel: u32| texel % map_size < map_size / 2;
|
||||
let curvature: Vec<f32> = (0..map_size * map_size).map(|texel| if left_half(texel) { 1.0 } else { 0.0 }).collect();
|
||||
let covered: Vec<bool> = (0..map_size * map_size).map(left_half).collect();
|
||||
let shape = (map_size, map_size);
|
||||
let sizes = CurvatureSizes::build(&curvature, shape, &covered, shape, &[true; CurvatureDetail::BLURRED_SIZES], None);
|
||||
|
||||
// The last covered column, halfway down
|
||||
let (border_x, border_y) = (map_size / 2 - 1, map_size / 2);
|
||||
for level in sizes.levels.iter().flatten() {
|
||||
assert!((level.sample(border_x, border_y) - 0.5).abs() < 0.01, "the border keeps the island's curvature, not the empty texels beside it");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uniform_curvature_keeps_its_strength_at_block_borders() {
|
||||
let (map_width, map_height): (u32, u32) = (256, 256);
|
||||
// Curvature 0.8 reads 0.3 above the neutral 0.5 at every size
|
||||
const CURVATURE: f32 = 0.8;
|
||||
let expected = CURVATURE - 0.5;
|
||||
let curvature = vec![CURVATURE; (map_width * map_height) as usize];
|
||||
let covered = vec![true; curvature.len()];
|
||||
let block = (map_width / 2, map_height);
|
||||
let sizes = CurvatureSizes::build(&curvature, (map_width, map_height), &covered, block, &[true; CurvatureDetail::BLURRED_SIZES], None);
|
||||
|
||||
// The map's corner, then the last texel of the left block and the first of the right one, halfway down
|
||||
let border_texels = [(0, 0), (block.0 - 1, map_height / 2), (block.0, map_height / 2)];
|
||||
for level in sizes.levels.iter().flatten() {
|
||||
for (x, y) in border_texels {
|
||||
assert!((level.sample(x, y) - expected).abs() < 0.01, "texel ({x}, {y}) reads {} instead of the uniform {expected}", level.sample(x, y));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_layout_replaces_the_sizes_of_the_old_one() {
|
||||
let curvature = Arc::new(vec![0.5; 16]);
|
||||
let scales = BlockScales::default();
|
||||
let entries_for_curvature = || {
|
||||
let cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
cache.iter().filter(|(source, ..)| std::ptr::eq(source.as_ptr(), Arc::as_ptr(&curvature))).count()
|
||||
};
|
||||
|
||||
store(&curvature, ((4, 4), (4, 4), (4, 4)), &scales, CurvatureSizes { levels: Vec::new() });
|
||||
store(&curvature, ((4, 4), (2, 2), (8, 8)), &scales, CurvatureSizes { levels: Vec::new() });
|
||||
assert_eq!(entries_for_curvature(), 1, "only the latest layout of a curvature map stays cached");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sizes_built_on_demand_match_a_full_build() {
|
||||
let map_size: u32 = 64;
|
||||
let curvature: Vec<f32> =
|
||||
(0..map_size * map_size).map(|texel| 0.5 + 0.4 * ((texel % map_size) as f32 * 0.3).sin() * ((texel / map_size) as f32 * 0.2).cos()).collect();
|
||||
let covered = vec![true; (map_size * map_size) as usize];
|
||||
let shape = (map_size, map_size);
|
||||
let all = vec![true; CurvatureDetail::BLURRED_SIZES];
|
||||
let full = CurvatureSizes::build(&curvature, shape, &covered, shape, &all, None);
|
||||
|
||||
let even: Vec<bool> = (0..all.len()).map(|level| level % 2 == 0).collect();
|
||||
let partial = CurvatureSizes::build(&curvature, shape, &covered, shape, &even, None);
|
||||
assert!(partial.levels.iter().zip(&even).all(|(level, needed)| level.is_some() == *needed), "only the needed sizes are built");
|
||||
|
||||
let completed = CurvatureSizes::build(&curvature, shape, &covered, shape, &all, Some(&partial));
|
||||
for ((built, expected), earlier) in completed.levels.iter().zip(&full.levels).zip(&partial.levels) {
|
||||
assert_eq!(built.as_ref().map(|level| &level.deviation), expected.as_ref().map(|level| &level.deviation), "the same values either way");
|
||||
if let (Some(built), Some(earlier)) = (built, earlier) {
|
||||
assert!(Arc::ptr_eq(built, earlier), "sizes already built are kept, not rebuilt");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -159,7 +159,7 @@ pub fn tile_bytes(comp: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u3
|
||||
if gloss { (get(Channel::Glossiness), default16(Channel::Glossiness)) } else { (get(Channel::Roughness), default16(Channel::Roughness)) };
|
||||
for i in 0..TILE_AREA {
|
||||
let (x, y) = (tx * TILE + (i as u32 % TILE), ty * TILE + (i as u32 / TILE));
|
||||
let baked_ao = baked.scalar(BakedMap::AmbientOcclusion, x, y, (res, comp.height)).unwrap_or(1.0);
|
||||
let baked_ao = baked.sample_working(BakedMap::AmbientOcclusion, x, y, (res, comp.height), &comp.block_scales).map_or(1.0, |value| value[0]);
|
||||
let ch_ao = ao.and_then(|a| a.get(i)).map(|v| *v as f32 / 65535.0).unwrap_or(1.0);
|
||||
let px = &mut out[i * 4..i * 4 + 4];
|
||||
px[0] = ((baked_ao * ch_ao).clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
|
||||
@@ -175,7 +175,7 @@ pub fn tile_bytes(comp: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u3
|
||||
let px = &mut out[i * 4..i * 4 + 4];
|
||||
// The baked normal is the base the painted normal details sit on (as in export).
|
||||
let (x, y) = (tx * TILE + (i as u32 % TILE), ty * TILE + (i as u32 / TILE));
|
||||
let base = baked.sample(BakedMap::Normal, x, y, (res, comp.height));
|
||||
let base = baked.sample_working(BakedMap::Normal, x, y, (res, comp.height), &comp.block_scales);
|
||||
match (n, base) {
|
||||
(Some(t), None) => {
|
||||
for (k, d) in px.iter_mut().take(3).enumerate() {
|
||||
|
||||
+687
-231
File diff suppressed because it is too large.
Load diff
@@ -7,7 +7,10 @@
|
||||
#![forbid(unsafe_code)]
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
mod baked_maps;
|
||||
pub mod below;
|
||||
mod curvature_size_level;
|
||||
pub mod curvature_sizes;
|
||||
pub mod display;
|
||||
pub mod eval;
|
||||
pub mod pattern;
|
||||
@@ -17,6 +20,6 @@ pub use below::{BelowCache, StackKey};
|
||||
pub use display::{DisplayKind, tile_bytes};
|
||||
pub use eval::{
|
||||
Composite, Inputs, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, covered_tiles, effect_histogram, flatten_layer,
|
||||
mask_image, pad_tiles,
|
||||
mask_at, mask_image, pad_tiles,
|
||||
};
|
||||
pub use store::{BakedMaps, ImageRes, ImageStore, PixelStore};
|
||||
@@ -1,9 +1,9 @@
|
||||
//! Pixel data owned by a document: painted layer channels, painted mask effects and baked mesh
|
||||
//! maps. Everything is copy-on-write, so cloning the store for undo is cheap.
|
||||
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::collections::HashMap;
|
||||
|
||||
use texturecraft_core::{BakedMap, Channel, ChannelKind, LayerId};
|
||||
use texturecraft_core::{Channel, ChannelKind, LayerId};
|
||||
use texturecraft_texel::{TileImage, from_u16, from_u16_signed};
|
||||
|
||||
/// Painted data of one paint layer channel: premultiplied value(s) plus coverage, u16 per
|
||||
@@ -56,38 +56,7 @@ pub fn decode(kind: ChannelKind, v: u16) -> f32 {
|
||||
if kind == ChannelKind::Signed { from_u16_signed(v) } else { from_u16(v) }
|
||||
}
|
||||
|
||||
/// Baked mesh maps of one texture set (dense, row-major, `components()` floats per texel). The
|
||||
/// width is `resolution`; height follows the output size and UV tile grid
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct BakedMaps {
|
||||
/// Width in texels.
|
||||
pub resolution: u32,
|
||||
pub maps: BTreeMap<BakedMap, std::sync::Arc<Vec<f32>>>,
|
||||
}
|
||||
|
||||
impl BakedMaps {
|
||||
/// Height in texels of map `m` (from its length).
|
||||
pub fn height(&self, m: BakedMap) -> u32 {
|
||||
self.maps.get(&m).map_or(0, |d| (d.len() / (self.resolution.max(1) as usize * m.components())) as u32)
|
||||
}
|
||||
|
||||
/// Sample the corresponding texel of an image with the supplied output size
|
||||
pub fn sample(&self, map: BakedMap, x: u32, y: u32, output_size: (u32, u32)) -> Option<[f32; 3]> {
|
||||
let data = self.maps.get(&map)?;
|
||||
let width = u64::from(self.resolution.max(1));
|
||||
let height = u64::from(self.height(map).max(1));
|
||||
let sample_x = (u64::from(x) * width / u64::from(output_size.0.max(1))).min(width - 1);
|
||||
let sample_y = (u64::from(y) * height / u64::from(output_size.1.max(1))).min(height - 1);
|
||||
let component_count = map.components();
|
||||
let offset = ((sample_y * width + sample_x) as usize).checked_mul(component_count)?;
|
||||
let texel = data.get(offset..offset.checked_add(component_count)?)?;
|
||||
Some(if component_count == 3 { [texel[0], texel[1], texel[2]] } else { [texel[0]; 3] })
|
||||
}
|
||||
|
||||
pub fn scalar(&self, m: BakedMap, x: u32, y: u32, size: (u32, u32)) -> Option<f32> {
|
||||
self.sample(m, x, y, size).map(|v| v[0])
|
||||
}
|
||||
}
|
||||
pub use crate::baked_maps::BakedMaps;
|
||||
|
||||
/// A decoded image resource sampled by fills (values in the file's encoding; see `srgb`).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
|
||||
@@ -90,7 +90,18 @@ fn heavy_stack(f: &mut Fixture) -> LayerId {
|
||||
}
|
||||
|
||||
fn inputs<'a>(f: &'a Fixture, ts: usize, images: &'a texturecraft_compose::ImageStore, baked: &'a texturecraft_compose::BakedMaps) -> Inputs<'a> {
|
||||
Inputs { project: &f.project, ts, mesh: &f.mesh, gbuf: &f.gbuf, pixels: &f.pixels, baked, preview: None, images, bounds: f.mesh.bounds() }
|
||||
Inputs {
|
||||
project: &f.project,
|
||||
ts,
|
||||
mesh: &f.mesh,
|
||||
gbuf: &f.gbuf,
|
||||
pixels: &f.pixels,
|
||||
baked,
|
||||
block_scales: f.project.texture_sets[ts].block_scales(),
|
||||
preview: None,
|
||||
images,
|
||||
bounds: f.mesh.bounds(),
|
||||
}
|
||||
}
|
||||
|
||||
fn run(f: &Fixture, ts: usize, tiles: &[(u32, u32)], below: Option<&mut BelowCache>) -> Composite {
|
||||
|
||||
@@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum CurvatureMethod {
|
||||
#[default]
|
||||
NormalMap,
|
||||
#[default]
|
||||
Mesh,
|
||||
}
|
||||
@@ -1,16 +1,10 @@
|
||||
use super::{CurvatureMethod, MeshCurvatureSettings, NormalMapCurvatureSettings};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct CurvatureSettings {
|
||||
pub method: CurvatureMethod,
|
||||
pub normal_map: NormalMapCurvatureSettings,
|
||||
pub mesh: MeshCurvatureSettings,
|
||||
}
|
||||
|
||||
impl Default for CurvatureSettings {
|
||||
fn default() -> Self {
|
||||
Self { method: CurvatureMethod::NormalMap, normal_map: NormalMapCurvatureSettings::default(), mesh: MeshCurvatureSettings::default() }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
/// Per-block UV tile scale for working-to-bake coordinates, filter radii, and height slopes
|
||||
/// Empty when every tile fills its block; see [`crate::TextureSet::tile_scale`]
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct BlockScales {
|
||||
pub(crate) block: u32,
|
||||
pub(crate) cols: u32,
|
||||
pub(crate) scales: Vec<f32>,
|
||||
}
|
||||
|
||||
impl BlockScales {
|
||||
/// Working atlas UV → uniform bake atlas UV, excluding unused portions of tile blocks
|
||||
pub fn bake_uv(&self, uv: [f32; 2], working_size: (u32, u32)) -> Option<[f32; 2]> {
|
||||
if working_size.0 == 0 || working_size.1 == 0 || uv.iter().any(|value| !value.is_finite() || !(0.0..1.0).contains(value)) {
|
||||
return None;
|
||||
}
|
||||
|
||||
if self.scales.is_empty() {
|
||||
return Some(uv);
|
||||
}
|
||||
|
||||
let block = self.block.max(1) as f32;
|
||||
let position = [uv[0] * working_size.0 as f32 / block, uv[1] * working_size.1 as f32 / block];
|
||||
let origin = position.map(f32::floor);
|
||||
let scale = self.at((origin[0] * block) as u32, (origin[1] * block) as u32);
|
||||
let local = [(position[0] - origin[0]) / scale, (position[1] - origin[1]) / scale];
|
||||
if local.iter().any(|value| !value.is_finite() || !(0.0..1.0).contains(value)) {
|
||||
return None;
|
||||
}
|
||||
|
||||
Some([(origin[0] + local[0]) * block / working_size.0.max(1) as f32, (origin[1] + local[1]) * block / working_size.1.max(1) as f32])
|
||||
}
|
||||
|
||||
/// The scale at atlas texel (x, y)
|
||||
pub fn at(&self, x: u32, y: u32) -> f32 {
|
||||
let (bx, by) = (x / self.block.max(1), y / self.block.max(1));
|
||||
if bx >= self.cols {
|
||||
return 1.0;
|
||||
}
|
||||
|
||||
let index = (by as usize).checked_mul(self.cols as usize).and_then(|index| index.checked_add(bx as usize));
|
||||
index.and_then(|index| self.scales.get(index)).copied().unwrap_or(1.0)
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,12 @@ use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{BlendMode, Channel, ChannelKind, lum};
|
||||
|
||||
mod curvature_detail;
|
||||
mod curvature_mode;
|
||||
|
||||
pub use curvature_detail::CurvatureDetail;
|
||||
pub use curvature_mode::CurvatureMode;
|
||||
|
||||
/// Id of a layer or effect (one id space per project).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
pub struct LayerId(pub u64);
|
||||
@@ -540,17 +546,26 @@ pub struct Generator {
|
||||
/// Direction for `Position` / `Direction` generators (world space).
|
||||
pub direction: [f32; 3],
|
||||
pub invert: bool,
|
||||
/// Mode and detail sizes of `Curvature` / `EdgeWear` generators (None: the curvature map as baked, as before detail sizes existed).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub detail: Option<CurvatureDetail>,
|
||||
}
|
||||
|
||||
impl Generator {
|
||||
pub fn new(kind: GeneratorKind) -> Generator {
|
||||
let (level, softness, noise_amount) = match kind {
|
||||
GeneratorKind::EdgeWear => (0.6, 0.12, 0.5),
|
||||
GeneratorKind::EdgeWear => (0.5, 0.25, 0.3),
|
||||
GeneratorKind::Curvature => (0.5, 0.5, 0.0),
|
||||
GeneratorKind::Dirt => (0.55, 0.25, 0.35),
|
||||
GeneratorKind::ThinAreas => (0.3, 0.2, 0.0),
|
||||
_ => (0.5, 0.25, 0.0),
|
||||
};
|
||||
Generator { kind, level, softness, noise_amount, noise_scale: 8.0, seed: 7, direction: [0.0, 1.0, 0.0], invert: false }
|
||||
let detail = match kind {
|
||||
GeneratorKind::Curvature => Some(CurvatureDetail::default()),
|
||||
GeneratorKind::EdgeWear => Some(CurvatureDetail { mode: CurvatureMode::Edges, weights: CurvatureDetail::EDGE_WEIGHTS }),
|
||||
_ => None,
|
||||
};
|
||||
Generator { kind, level, softness, noise_amount, noise_scale: 8.0, seed: 7, direction: [0.0, 1.0, 0.0], invert: false, detail }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1050,6 +1065,17 @@ impl Effect {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn curvature_generators_saved_before_detail_sizes_load_without_them() {
|
||||
let mut saved = serde_json::to_value(Generator::new(GeneratorKind::Curvature)).unwrap();
|
||||
assert!(saved.get("detail").is_some(), "new curvature generators have detail sizes");
|
||||
|
||||
saved.as_object_mut().unwrap().remove("detail");
|
||||
let loaded: Generator = serde_json::from_value(saved).unwrap();
|
||||
assert_eq!(loaded.detail, None);
|
||||
assert_eq!(Generator::new(GeneratorKind::Dirt).detail, None, "only curvature and edge wear generators have detail sizes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn levels_map_range_and_gamma() {
|
||||
let l = Levels { in_low: 0.2, in_high: 0.6, gamma: 1.0, out_low: 0.0, out_high: 1.0 };
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::curvature_mode::CurvatureMode;
|
||||
|
||||
/// How a curvature generator reads the curvature map: its mode and how much each detail size adds.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct CurvatureDetail {
|
||||
pub mode: CurvatureMode,
|
||||
/// Weight (0..1) of each size in [`CurvatureDetail::SIZES`], finest first.
|
||||
pub weights: [f32; CurvatureDetail::SIZES.len()],
|
||||
}
|
||||
|
||||
impl CurvatureDetail {
|
||||
/// Detail sizes as blur radii in texels at 2K: the map itself, then doubling radii.
|
||||
pub const SIZES: [f32; 7] = [0.0, 1.0, 2.0, 4.0, 8.0, 16.0, 32.0];
|
||||
|
||||
/// Weights falling off with size, tuned by eye on hard-surface bakes: sharp edges first, broad shapes lit faintly.
|
||||
pub const BROAD_WEIGHTS: [f32; 7] = [1.0, 0.85, 0.7, 0.55, 0.4, 0.25, 0.15];
|
||||
|
||||
/// Mostly the finer sizes, tuned the same way: worn edges are thin lines.
|
||||
pub const EDGE_WEIGHTS: [f32; 7] = [1.0, 0.8, 0.5, 0.25, 0.1, 0.0, 0.0];
|
||||
|
||||
/// How many sizes are blurred copies of the map (all but the first).
|
||||
pub const BLURRED_SIZES: usize = CurvatureDetail::SIZES.len() - 1;
|
||||
|
||||
/// Which blurred sizes this detail reads: those with a weight above 0.
|
||||
pub fn blurred_sizes_in_use(&self) -> [bool; CurvatureDetail::BLURRED_SIZES] {
|
||||
std::array::from_fn(|blurred| self.weights.get(blurred + 1).is_some_and(|weight| *weight > 0.0))
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for CurvatureDetail {
|
||||
fn default() -> Self {
|
||||
CurvatureDetail { mode: CurvatureMode::Edges, weights: CurvatureDetail::BROAD_WEIGHTS }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Which side of the curvature map a curvature generator shows.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub enum CurvatureMode {
|
||||
/// Convex edges white.
|
||||
#[default]
|
||||
Edges,
|
||||
/// Concave cavities white.
|
||||
Cavities,
|
||||
/// Edges and cavities both white.
|
||||
Both,
|
||||
/// Signed curvature around mid gray (cavities dark, edges light).
|
||||
Raw,
|
||||
}
|
||||
|
||||
impl CurvatureMode {
|
||||
pub const ALL: [CurvatureMode; 4] = [CurvatureMode::Edges, CurvatureMode::Cavities, CurvatureMode::Both, CurvatureMode::Raw];
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
CurvatureMode::Edges => "Edges",
|
||||
CurvatureMode::Cavities => "Cavities",
|
||||
CurvatureMode::Both => "Edges and cavities",
|
||||
CurvatureMode::Raw => "Raw curvature",
|
||||
}
|
||||
}
|
||||
|
||||
/// The mode named `name` (its variant or label, any case).
|
||||
pub fn parse(name: &str) -> Option<CurvatureMode> {
|
||||
let normalized = |text: &str| text.to_ascii_lowercase().replace([' ', '_', '-'], "");
|
||||
CurvatureMode::ALL.into_iter().find(|mode| normalized(&format!("{mode:?}")) == normalized(name) || normalized(mode.label()) == normalized(name))
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@
|
||||
|
||||
pub mod bake;
|
||||
pub mod blend;
|
||||
mod block_scales;
|
||||
pub mod channel;
|
||||
pub mod layer;
|
||||
pub mod project;
|
||||
@@ -23,8 +24,9 @@ pub use bake::{
|
||||
pub use blend::{BlendMode, blend1, blend3, lum, mix3};
|
||||
pub use channel::{Channel, ChannelFormat, ChannelKind};
|
||||
pub use layer::{
|
||||
ChannelBlend, CompareOp, Decal, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Levels, LinkParam,
|
||||
LinkPreset, Mask, MaskBackground, MaterialLink, PathShape, Procedural, ProceduralKind, Projection, Source, gradient, hsl_adjust, per_unit,
|
||||
ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId,
|
||||
LayerKind, Levels, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, PathShape, Procedural, ProceduralKind, Projection, Source, gradient,
|
||||
hsl_adjust, per_unit,
|
||||
};
|
||||
pub use project::{
|
||||
AoMixing, BlockScales, Camera, DepthOfField, DisplaySettings, FORMAT_VERSION, MAX_RESOLUTION, MIN_RESOLUTION, NormalFormat, NormalMixing, Project,
|
||||
|
||||
+16
-21
@@ -6,7 +6,7 @@ use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{BakeSettings, BakedMap, Channel, ChannelFormat, CoreError, Effect, Layer, LayerId, LayerKind, Result};
|
||||
|
||||
pub const FORMAT_VERSION: u32 = 1;
|
||||
pub const FORMAT_VERSION: u32 = 2;
|
||||
|
||||
/// Maximum group nesting (also bounds recursion over hostile project files)
|
||||
pub const MAX_DEPTH: usize = 16;
|
||||
@@ -63,6 +63,9 @@ pub struct TextureSet {
|
||||
/// [`TileGrid`], [`TextureSet::block_resolution`] texels square.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub uv_tiles: Vec<u32>,
|
||||
/// UV tiles excluded from baking; missing entries stay included
|
||||
#[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
|
||||
pub bake_excluded_tiles: BTreeSet<u32>,
|
||||
/// Per-tile resolutions overriding `resolution` (UDIM → texels per side). A tile smaller
|
||||
/// than the atlas block fills the block's top-left corner (see [`TextureSet::to_atlas`]).
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
@@ -132,26 +135,7 @@ impl TileGrid {
|
||||
}
|
||||
}
|
||||
|
||||
/// The fraction of its atlas block the UV tile of each block fills ([`TextureSet::tile_scale`]):
|
||||
/// such a tile has fewer texels per UV unit, so filter radii and height slopes shrink with it.
|
||||
/// Empty (every scale 1) unless a tile is smaller than its block.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct BlockScales {
|
||||
block: u32,
|
||||
cols: u32,
|
||||
scales: Vec<f32>,
|
||||
}
|
||||
|
||||
impl BlockScales {
|
||||
/// The scale at atlas texel (x, y).
|
||||
pub fn at(&self, x: u32, y: u32) -> f32 {
|
||||
let (bx, by) = (x / self.block.max(1), y / self.block.max(1));
|
||||
if bx >= self.cols {
|
||||
return 1.0;
|
||||
}
|
||||
self.scales.get(by as usize * self.cols as usize + bx as usize).copied().unwrap_or(1.0)
|
||||
}
|
||||
}
|
||||
pub use crate::block_scales::BlockScales;
|
||||
|
||||
fn one() -> f32 {
|
||||
1.0
|
||||
@@ -176,6 +160,7 @@ impl TextureSet {
|
||||
baked: BTreeSet::new(),
|
||||
visible: true,
|
||||
uv_tiles: Vec::new(),
|
||||
bake_excluded_tiles: BTreeSet::new(),
|
||||
tile_resolutions: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
@@ -185,6 +170,10 @@ impl TextureSet {
|
||||
TileGrid::of(&self.uv_tiles)
|
||||
}
|
||||
|
||||
pub fn has_enabled_bake_tiles(&self) -> bool {
|
||||
self.uv_tiles.is_empty() || self.uv_tiles.iter().any(|tile| !self.bake_excluded_tiles.contains(tile))
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
@@ -406,6 +395,11 @@ pub struct Project {
|
||||
/// it, so parts the file leaves unnamed get the same name (from it) as on import.
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub mesh_file: String,
|
||||
/// Where the mesh file was imported from (the project's "3D mesh path"). Reimport mesh reads
|
||||
/// it again from there, so edits made to the file since are picked up. Empty when unknown
|
||||
/// (built-in meshes, web imports, projects saved before it was kept).
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub mesh_path: String,
|
||||
pub normal_format: NormalFormat,
|
||||
pub texture_sets: Vec<TextureSet>,
|
||||
pub layers: BTreeMap<LayerId, Layer>,
|
||||
@@ -423,6 +417,7 @@ impl Project {
|
||||
name: name.into(),
|
||||
mesh: mesh.into(),
|
||||
mesh_file: String::new(),
|
||||
mesh_path: String::new(),
|
||||
normal_format: NormalFormat::OpenGl,
|
||||
texture_sets: Vec::new(),
|
||||
layers: BTreeMap::new(),
|
||||
|
||||
@@ -20,7 +20,7 @@ fn reference_defaults_cover_common_and_per_map_settings() {
|
||||
"id": {"source": "MaterialColor", "generator": "HueShift"},
|
||||
"ao": {"rays": rays, "ignore_backface": "Never", "self_occlusion": "Always", "attenuation": "Linear", "ground_plane": {"enabled": false, "offset": 0.0}},
|
||||
"curvature": {
|
||||
"method": "NormalMap",
|
||||
"method": "Mesh",
|
||||
"normal_map": {"details": 0.5, "enable_seams": true, "seams_intensity": 1.0},
|
||||
"mesh": {"rays": 32, "sampling_radius": 0.001, "relative_to_bounding_box": true, "self_intersection": "Always", "auto_tonemapping": true, "value_min": -1.0, "value_max": 1.0}
|
||||
},
|
||||
@@ -54,7 +54,9 @@ fn reference_defaults_cover_common_and_per_map_settings() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
assert_shape(&serde_json::to_value(decoded).unwrap(), &expected);
|
||||
|
||||
assert_eq!(BakedMap::ALL.len(), 10);
|
||||
for name in ["color_map", "Color map", "WorldDirection", "world_space_direction"] {
|
||||
assert_eq!(BakedMap::parse(name), None);
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
use super::MergedHigh;
|
||||
use std::sync::Arc;
|
||||
use texturecraft_bake::{BakeError, BakePaintMap, BakeRequest, CageShell, HighPoly, HighPolyReach};
|
||||
use texturecraft_core::BakeSettings;
|
||||
use texturecraft_geom::{Bvh, Mesh};
|
||||
|
||||
/// What a texture set's bake reads to place its transfer rays, owned so a worker thread can use it
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct BakeCageInputs {
|
||||
pub(super) mesh: Arc<Mesh>,
|
||||
pub(super) bvh: Arc<Bvh>,
|
||||
pub(super) material: usize,
|
||||
pub(super) settings: BakeSettings,
|
||||
pub(super) high: MergedHigh,
|
||||
pub(super) cage: Option<Arc<Mesh>>,
|
||||
pub(super) skew: Option<Arc<BakePaintMap>>,
|
||||
pub(super) cage_paint: Option<Arc<BakePaintMap>>,
|
||||
}
|
||||
|
||||
impl BakeCageInputs {
|
||||
/// The cage the 3D view draws: the bake's ray origins at each triangle corner
|
||||
pub fn cage_shell(&self) -> Result<CageShell, BakeError> {
|
||||
CageShell::new(&self.request())
|
||||
}
|
||||
|
||||
/// Where each high-poly vertex sits relative to the bake's transfer rays
|
||||
pub fn high_poly_reach(&self) -> Result<HighPolyReach, BakeError> {
|
||||
HighPolyReach::new(&self.request())
|
||||
}
|
||||
|
||||
fn request(&self) -> BakeRequest<'_> {
|
||||
BakeRequest {
|
||||
low_base_color: &[],
|
||||
mesh: &self.mesh,
|
||||
bvh: &self.bvh,
|
||||
material: self.material,
|
||||
settings: &self.settings,
|
||||
high: Some(HighPoly { file_ids: &self.high.file_ids, mesh: &self.high.mesh, bvh: &self.high.bvh, base_color: &self.high.base_color }),
|
||||
cage: self.cage.as_deref(),
|
||||
skew: self.skew.as_deref(),
|
||||
cage_paint: self.cage_paint.as_deref(),
|
||||
tiles: (1, 1),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,11 @@ pub struct BakeMeshes {
|
||||
}
|
||||
|
||||
impl BakeMeshes {
|
||||
/// Every high poly appended into one mesh, as bakes see it
|
||||
pub fn merged_high(&self) -> Option<&MergedHigh> {
|
||||
self.merged.as_ref()
|
||||
}
|
||||
|
||||
pub(crate) fn rebuild(&mut self) {
|
||||
self.merged = (!self.high.is_empty()).then(|| {
|
||||
let (mut mesh, mut base_color, mut file_ids) = (Mesh::default(), Vec::new(), Vec::new());
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
use super::MergedHigh;
|
||||
use crate::{EngineError, Result};
|
||||
use std::sync::Arc;
|
||||
use texturecraft_bake::{BakeOutput, BakePaintMap, BakeRequest, HighPoly, Progress, bake, bake_on, tracing::Tracer};
|
||||
use texturecraft_bake::{BakeOutput, BakePaintMap, BakeRequest, HighPoly, Progress, bake_tiles, tracing::Tracer};
|
||||
use texturecraft_compose::BakedMaps;
|
||||
use texturecraft_core::BakeSettings;
|
||||
use texturecraft_geom::{Bvh, Mesh};
|
||||
|
||||
@@ -20,6 +21,9 @@ pub struct BakeTask {
|
||||
pub cage_paint: Option<Arc<BakePaintMap>>,
|
||||
/// 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}`).
|
||||
pub tracer: Option<Arc<dyn Tracer>>,
|
||||
}
|
||||
@@ -40,10 +44,9 @@ impl BakeTask {
|
||||
cage_paint: self.cage_paint.as_deref(),
|
||||
tiles: self.tiles,
|
||||
};
|
||||
match &self.tracer {
|
||||
Some(tracer) => bake_on(&request, progress, tracer.as_ref()),
|
||||
None => bake(&request, progress),
|
||||
}
|
||||
.map_err(|e| EngineError::Other(format!("bake failed: {e}")))
|
||||
let mut output = bake_tiles(&request, progress, &self.excluded_tiles, self.tracer.as_deref())
|
||||
.map_err(|error| EngineError::Other(format!("bake failed: {error}")))?;
|
||||
super::preserve_tiles::restore(&mut output, &self.previous_maps, &self.excluded_tiles, self.tiles)?;
|
||||
Ok(output)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
use rayon::prelude::*;
|
||||
use texturecraft_bake::HighPolyReach;
|
||||
|
||||
/// Per high-poly vertex: 1.0 if its owning set's bake misses it, otherwise 0.0
|
||||
/// Distances are each set's (max frontal, max rear); filtered or unavailable sets leave their vertices unmarked
|
||||
/// `vertex_count` is the validated high-poly mesh's vertex count
|
||||
pub fn high_poly_missed(reach: &[Option<HighPolyReach>], distances: &[(f32, f32)], only_set: Option<usize>, vertex_count: usize) -> Vec<f32> {
|
||||
// Ownership is already assigned by HighPolyReach; other sets must not color the vertex
|
||||
let sets: Vec<(&HighPolyReach, f32, f32)> = reach
|
||||
.iter()
|
||||
.zip(distances)
|
||||
.enumerate()
|
||||
.filter(|(texture_set, _)| only_set.is_none_or(|only| only == *texture_set))
|
||||
.filter_map(|(_, (reach, &(max_frontal, max_rear)))| Some((reach.as_ref()?, max_frontal, max_rear)))
|
||||
.collect();
|
||||
(0..vertex_count)
|
||||
.into_par_iter()
|
||||
.map(|vertex| {
|
||||
let missed = sets.iter().find_map(|(reach, max_frontal, max_rear)| reach.missed(vertex, *max_frontal, *max_rear));
|
||||
f32::from(u8::from(missed.unwrap_or(false)))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use rayon::prelude::*;
|
||||
use texturecraft_bake::BakePaintMap;
|
||||
use texturecraft_core::TextureSet;
|
||||
use texturecraft_geom::glam::Vec2;
|
||||
|
||||
use crate::{EngineError, Result};
|
||||
|
||||
/// Correction paint stays in working coordinates; the worker reads a uniform bake atlas
|
||||
pub(super) fn paint_for_bake(painted: &Arc<BakePaintMap>, set: &TextureSet) -> Result<Arc<BakePaintMap>> {
|
||||
let Some(grid) = set.tile_grid().filter(|_| !set.tile_resolutions.is_empty()) else {
|
||||
return Ok(painted.clone());
|
||||
};
|
||||
|
||||
painted.validate().map_err(|error| EngineError::Other(error.to_string()))?;
|
||||
let (width, height) = (painted.width, painted.height);
|
||||
let mut values = vec![0.0; painted.values.len()];
|
||||
values.par_chunks_mut(width as usize).enumerate().for_each(|(y, row)| {
|
||||
for (x, value) in row.iter_mut().enumerate() {
|
||||
let uv = grid.from_atlas([(x as f32 + 0.5) / width as f32, (y as f32 + 0.5) / height as f32]);
|
||||
*value = painted.sample(Vec2::from_array(set.to_atlas(&grid, uv, uv)));
|
||||
}
|
||||
});
|
||||
Ok(Arc::new(BakePaintMap { width, height, values }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn correction_paint_follows_the_same_surface_in_bake_coordinates() {
|
||||
let mut set = TextureSet::new("Tiles", 0, 256);
|
||||
set.uv_tiles = vec![1001, 1002];
|
||||
set.tile_resolutions.insert(1002, 128);
|
||||
let mut paint = BakePaintMap::constant(0.0).resized(128, 64).unwrap();
|
||||
paint.paint(&[Vec2::new(0.625, 0.25)], 0.05, 1.0, 1.0, 1.0).unwrap();
|
||||
let paint = Arc::new(paint);
|
||||
let baked = paint_for_bake(&paint, &set).unwrap();
|
||||
assert!(paint.sample(Vec2::new(0.625, 0.25)) > 0.99);
|
||||
assert!(baked.sample(Vec2::new(0.75, 0.5)) > 0.99);
|
||||
assert_eq!(baked.sample(Vec2::new(0.25, 0.5)), 0.0);
|
||||
assert_eq!(paint.sample(Vec2::new(0.75, 0.5)), 0.0);
|
||||
}
|
||||
}
|
||||
@@ -2,10 +2,13 @@
|
||||
//! high-definition mesh list, the cage, and running a bake. Bakes cast their rays on the GPU
|
||||
//! tracer the app installs ([`install_gpu_tracer`]) and on the CPU otherwise.
|
||||
|
||||
use super::model_patch;
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
use texturecraft_core::BakePaintTarget;
|
||||
|
||||
use super::{BakeCageInputs, MergedHigh};
|
||||
use crate::{BakeMesh, BakeTask};
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_bake::tracing::Tracer;
|
||||
@@ -13,11 +16,12 @@ use texturecraft_bake::{BakeOutput, BakePaintMap, MAX_RAYS, Progress};
|
||||
use texturecraft_core::{
|
||||
BackfaceMode, BakeAntialiasing, BakeResolution, BakeSettings, BakedMap, CurvatureMethod, PositionMode, RayDistribution, RaySettings, SelfOcclusion,
|
||||
};
|
||||
use texturecraft_geom::Mesh;
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad, boolp, f32p, strp, u64p};
|
||||
use crate::{EngineError, Result, Session, cmd};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
"bake.run",
|
||||
@@ -33,7 +37,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Bake settings",
|
||||
[],
|
||||
None,
|
||||
"{ts?: index|[indices]|\"all\"|\"selected\" (default: the active set), model?: complete nested BakeSettings (named enum values), preserveEnabled?: keep each texture set enabled flag when replacing the model, resolution?, antialiasing?: 1|2|4|8, dilation?, ao?: {rays?, maxDistance?, spread?: degrees (180 = hemisphere), distribution?: cosine|uniform, ignoreBackface?: never|always|byMeshName, selfOcclusion?: always|sameMeshName}, thickness?: {rays?, maxDistance?, spread?, distribution?}, bentNormal?: {rays?, maxDistance?, spread?, distribution?}, rays?, maxDistance? (all three ray maps), curvatureMethod?: normalMap|mesh, positionMode?: boundingBox|boundingSphere|none, maps?: [ids], enabled?, useLowAsHigh?, maxFrontal?, maxRear?, averageNormals?, lowSuffix?, highSuffix?}",
|
||||
"{ts?: index|[indices]|\"all\"|\"selected\" (default: the active set), model?: complete nested BakeSettings (named enum values), preserveEnabled?: keep each texture set enabled flag when replacing the model, patch?: nested BakeSettings fields to update after model (omitted fields stay unchanged, null clears optional fields), resolution?, antialiasing?: 1|2|4|8, dilation?, ao?: {rays?, maxDistance?, spread?: degrees (180 = hemisphere), distribution?: cosine|uniform, ignoreBackface?: never|always|byMeshName, selfOcclusion?: always|sameMeshName}, thickness?: {rays?, maxDistance?, spread?, distribution?}, bentNormal?: {rays?, maxDistance?, spread?, distribution?}, rays?, maxDistance? (all three ray maps), curvatureMethod?: normalMap|mesh, positionMode?: boundingBox|boundingSphere|none, maps?: [ids], enabled?, useLowAsHigh?, maxFrontal?, maxRear?, averageNormals?, lowSuffix?, highSuffix?}",
|
||||
always,
|
||||
settings
|
||||
),
|
||||
@@ -88,8 +92,12 @@ fn parse_mesh(file_name: &str, bytes: Vec<u8>) -> Result<BakeMesh> {
|
||||
}
|
||||
|
||||
impl Session {
|
||||
pub fn bake_task(&self, ts: usize) -> Result<BakeTask> {
|
||||
let set = self.doc.project.texture_set(ts)?;
|
||||
pub fn bake_task(&self, texture_set: usize) -> 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 needs_low_color = set.bake.maps.opacity.is_enabled
|
||||
|| (set.bake.maps.id.is_enabled && set.bake.maps.id.parameters.source == texturecraft_core::IdColorSource::MaterialColor);
|
||||
let low_base_color = if needs_low_color && (set.bake.high_poly.use_low_as_high || self.bake_meshes.high.is_empty()) {
|
||||
@@ -106,20 +114,22 @@ impl Session {
|
||||
} else {
|
||||
Arc::new(Vec::new())
|
||||
};
|
||||
let high = if set.bake.high_poly.use_low_as_high { None } else { self.bake_meshes.merged.clone() };
|
||||
let cage = if high.is_some() && set.bake.cage.kind == texturecraft_core::CageType::CustomFile {
|
||||
Some(self.bake_meshes.cage.as_ref().ok_or_else(|| EngineError::Other("Custom File requires a cage mesh".into()))?.mesh.clone())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let skew = high.as_ref().and(self.doc.bake_paint.get(&(ts, BakePaintTarget::Skew)).cloned());
|
||||
let cage_paint = high.as_ref().and(self.doc.bake_paint.get(&(ts, BakePaintTarget::Cage)).cloned());
|
||||
let tiles = set.tile_grid().map_or((1, 1), |g| (g.cols, g.rows));
|
||||
|
||||
let high = self.bake_high(texture_set)?;
|
||||
let cage = self.bake_cage(texture_set, high.is_some())?;
|
||||
let skew = self.bake_paint(texture_set, high.is_some(), BakePaintTarget::Skew)?;
|
||||
let cage_paint = self.bake_paint(texture_set, high.is_some(), BakePaintTarget::Cage)?;
|
||||
|
||||
let grid = set.tile_grid();
|
||||
let tiles = grid.map_or((1, 1), |grid| (grid.cols, grid.rows));
|
||||
let excluded_tiles: Vec<_> = set.uv_tiles.iter().filter(|tile| set.bake_excluded_tiles.contains(tile)).filter_map(|tile| grid?.block(*tile)).collect();
|
||||
let previous_maps = if excluded_tiles.is_empty() { Default::default() } else { self.doc.baked.get(&texture_set).cloned().unwrap_or_default() };
|
||||
|
||||
let tracer = GPU_TRACER.get().cloned();
|
||||
Ok(BakeTask {
|
||||
low_base_color,
|
||||
ts,
|
||||
mesh: self.mesh.clone(),
|
||||
ts: texture_set,
|
||||
mesh: self.bake_mesh(texture_set)?,
|
||||
bvh: self.bvh.clone(),
|
||||
material: set.material,
|
||||
settings: set.bake.clone(),
|
||||
@@ -128,10 +138,67 @@ impl Session {
|
||||
skew,
|
||||
cage_paint,
|
||||
tiles,
|
||||
excluded_tiles,
|
||||
previous_maps,
|
||||
tracer,
|
||||
})
|
||||
}
|
||||
|
||||
/// What texture set `texture_set`'s bake reads to place its transfer rays; `None` when the set bakes without a high poly or misses its cage file
|
||||
pub fn bake_cage_inputs(&self, texture_set: usize) -> Result<Option<BakeCageInputs>> {
|
||||
let set = self.doc.project.texture_set(texture_set)?;
|
||||
let Some(high) = self.bake_high(texture_set)? else { return Ok(None) };
|
||||
let Ok(cage) = self.bake_cage(texture_set, true) else { return Ok(None) };
|
||||
|
||||
Ok(Some(BakeCageInputs {
|
||||
mesh: self.bake_mesh(texture_set)?,
|
||||
bvh: self.bvh.clone(),
|
||||
material: set.material,
|
||||
settings: set.bake.clone(),
|
||||
high,
|
||||
cage,
|
||||
skew: self.bake_paint(texture_set, true, BakePaintTarget::Skew)?,
|
||||
cage_paint: self.bake_paint(texture_set, true, BakePaintTarget::Cage)?,
|
||||
}))
|
||||
}
|
||||
|
||||
/// The merged high polys texture set `texture_set` bakes from, unless it bakes from the low poly
|
||||
fn bake_high(&self, texture_set: usize) -> Result<Option<MergedHigh>> {
|
||||
let set = self.doc.project.texture_set(texture_set)?;
|
||||
Ok(if set.bake.high_poly.use_low_as_high { None } else { self.bake_meshes.merged.clone() })
|
||||
}
|
||||
|
||||
/// Texture set `texture_set`'s cage mesh when it bakes from a high poly with a Custom File cage
|
||||
fn bake_cage(&self, texture_set: usize, has_high: bool) -> Result<Option<Arc<Mesh>>> {
|
||||
let set = self.doc.project.texture_set(texture_set)?;
|
||||
if !has_high || set.bake.cage.kind != texturecraft_core::CageType::CustomFile {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let cage = self.bake_meshes.cage.as_ref().ok_or_else(|| EngineError::Other("Custom File requires a cage mesh".into()))?;
|
||||
Ok(Some(cage.mesh.clone()))
|
||||
}
|
||||
|
||||
/// Texture set `texture_set`'s painted skew or cage map, used only when it bakes from a high poly
|
||||
fn bake_paint(&self, texture_set: usize, has_high: bool, target: BakePaintTarget) -> Result<Option<Arc<BakePaintMap>>> {
|
||||
let set = self.doc.project.texture_set(texture_set)?;
|
||||
let paint = self.doc.bake_paint.get(&(texture_set, target)).filter(|_| has_high);
|
||||
paint.map(|map| super::layout::paint_for_bake(map, set)).transpose()
|
||||
}
|
||||
|
||||
/// The low poly texture set `texture_set` bakes: UV tiles of mixed resolutions move into its atlas
|
||||
fn bake_mesh(&self, texture_set: usize) -> Result<Arc<Mesh>> {
|
||||
let set = self.doc.project.texture_set(texture_set)?;
|
||||
Ok(match set.tile_grid().filter(|_| !set.tile_resolutions.is_empty()) {
|
||||
Some(grid) => {
|
||||
let mut mesh = (*self.source).clone();
|
||||
mesh.map_material_uvs(set.material, |uv| texturecraft_geom::glam::Vec2::from_array(grid.to_atlas(uv.to_array())));
|
||||
Arc::new(mesh)
|
||||
}
|
||||
None => self.mesh.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
/// 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();
|
||||
@@ -364,7 +431,7 @@ pub fn settings_params(settings: &BakeSettings) -> Value {
|
||||
|
||||
/// Apply only the bake parameters supplied by the caller
|
||||
fn apply_settings(settings: &mut BakeSettings, params: &Value, command: &str) -> Result<()> {
|
||||
// Keep the current command limits until the reference controls are integrated
|
||||
// Preserve the legacy flat-parameter limits for existing callers
|
||||
const MAX_DILATION_PIXELS: u32 = 256;
|
||||
const MAX_SUFFIX_CHARS: usize = 64;
|
||||
|
||||
@@ -378,6 +445,14 @@ fn apply_settings(settings: &mut BakeSettings, params: &Value, command: &str) ->
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(patch) = params.get("patch") {
|
||||
let mut model = json!(settings);
|
||||
model_patch::apply_patch(&mut model, patch, command)?;
|
||||
let updated: BakeSettings = serde_json::from_value(model).map_err(|error| bad(command, error.to_string()))?;
|
||||
validate_model_settings(&updated, command)?;
|
||||
*settings = updated;
|
||||
}
|
||||
|
||||
if let Some(resolution) = u64p(params, "resolution") {
|
||||
settings.common.resolution = u32::try_from(resolution)
|
||||
.ok()
|
||||
@@ -604,8 +679,15 @@ fn settings(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn bake_run(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
let next = updated_settings(session, params, "bake.run")?;
|
||||
let next: Vec<_> = updated_settings(session, params, "bake.run")?
|
||||
.into_iter()
|
||||
.filter(|(index, _)| session.doc.project.texture_sets.get(*index).is_some_and(|texture_set| texture_set.has_enabled_bake_tiles()))
|
||||
.collect();
|
||||
let sets: Vec<usize> = next.iter().map(|(index, _)| *index).collect();
|
||||
if sets.is_empty() {
|
||||
return Ok(json!({"baked": [], "tracer": []}));
|
||||
}
|
||||
|
||||
let cpu = boolp(params, "cpu") == Some(true);
|
||||
let tracers = session.edit("Bake mesh maps", |session| {
|
||||
let mut tracers = Vec::with_capacity(next.len());
|
||||
@@ -1,11 +1,35 @@
|
||||
//! Baking tasks, commands, settings helpers, and the mesh-map baking API
|
||||
|
||||
mod bake_cage_inputs;
|
||||
mod bake_mesh;
|
||||
mod bake_meshes;
|
||||
mod bake_task;
|
||||
mod high_poly_missed;
|
||||
mod layout;
|
||||
mod merged_high;
|
||||
mod mesh_map_command;
|
||||
mod model_patch;
|
||||
mod paint_command;
|
||||
mod preserve_tiles;
|
||||
mod tile_command;
|
||||
|
||||
pub use bake_cage_inputs::BakeCageInputs;
|
||||
pub use bake_mesh::BakeMesh;
|
||||
pub use bake_meshes::BakeMeshes;
|
||||
pub use bake_task::BakeTask;
|
||||
pub use high_poly_missed::high_poly_missed;
|
||||
pub use merged_high::MergedHigh;
|
||||
pub use mesh_map_command::{install_gpu_tracer, meshes_json, settings_params};
|
||||
pub use model_patch::settings_patch;
|
||||
pub use texturecraft_bake::*;
|
||||
|
||||
use crate::CommandSpec;
|
||||
|
||||
type MaterialColors = std::sync::Arc<Vec<Option<std::sync::Arc<texturecraft_geom::BaseColor>>>>;
|
||||
|
||||
pub(crate) fn specs() -> Vec<CommandSpec> {
|
||||
let mut commands = mesh_map_command::specs();
|
||||
commands.extend(paint_command::specs());
|
||||
commands.extend(tile_command::specs());
|
||||
commands
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_core::BakeSettings;
|
||||
|
||||
use crate::Result;
|
||||
use crate::commands::bad;
|
||||
|
||||
/// Only the changed fields, using the persisted model's names and enum values
|
||||
pub fn settings_patch(before: &BakeSettings, after: &BakeSettings) -> Value {
|
||||
changed_fields(&json!(before), &json!(after)).unwrap_or_else(|| json!({}))
|
||||
}
|
||||
|
||||
fn changed_fields(before: &Value, after: &Value) -> Option<Value> {
|
||||
if before == after {
|
||||
return None;
|
||||
}
|
||||
|
||||
if let (Some(before), Some(after)) = (before.as_object(), after.as_object()) {
|
||||
let fields = after
|
||||
.iter()
|
||||
.filter_map(|(name, value)| changed_fields(before.get(name).unwrap_or(&Value::Null), value).map(|change| (name.clone(), change)))
|
||||
.collect();
|
||||
Some(Value::Object(fields))
|
||||
} else {
|
||||
Some(after.clone())
|
||||
}
|
||||
}
|
||||
|
||||
/// Merge known fields only; null is a value, so optional settings can be cleared
|
||||
pub(super) fn apply_patch(model: &mut Value, patch: &Value, command: &str) -> Result<()> {
|
||||
let fields = patch.as_object().ok_or_else(|| bad(command, "bake settings patch must be an object"))?;
|
||||
for (name, value) in fields {
|
||||
let target = model.get_mut(name).ok_or_else(|| bad(command, format!("unknown bake setting `{name}`")))?;
|
||||
if target.is_object() {
|
||||
apply_patch(target, value, command)?;
|
||||
} else {
|
||||
*target = value.clone();
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -6,7 +6,7 @@ use texturecraft_bake::BakePaintMap;
|
||||
use texturecraft_core::BakePaintTarget;
|
||||
use texturecraft_geom::glam::Vec2;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!("bake.skew.set", "Set Skew Correction", [], None, "{ts?, value?: 0..1 | path: grayscale image}", always, |session, parameters| set(
|
||||
session,
|
||||
@@ -65,7 +65,7 @@ fn set(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> Re
|
||||
session.doc.bake_paint.insert((texture_set, target), Arc::new(map));
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(crate::bake_cmds::meshes_json(session))
|
||||
Ok(super::meshes_json(session))
|
||||
}
|
||||
|
||||
fn clear(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> Result<Value> {
|
||||
@@ -76,7 +76,7 @@ fn clear(session: &mut Session, parameters: &Value, target: BakePaintTarget) ->
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
Ok(crate::bake_cmds::meshes_json(session))
|
||||
Ok(super::meshes_json(session))
|
||||
}
|
||||
|
||||
fn paint(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> Result<Value> {
|
||||
@@ -123,7 +123,7 @@ fn paint(session: &mut Session, parameters: &Value, target: BakePaintTarget) ->
|
||||
}
|
||||
Arc::make_mut(map).paint(&points, radius, value, hardness, strength).map_err(|error| bad("bake.paint", error.to_string()))
|
||||
})?;
|
||||
Ok(crate::bake_cmds::meshes_json(session))
|
||||
Ok(super::meshes_json(session))
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -0,0 +1,54 @@
|
||||
use texturecraft_bake::BakeOutput;
|
||||
use texturecraft_compose::BakedMaps;
|
||||
|
||||
use crate::{EngineError, Result};
|
||||
|
||||
/// Retain excluded tiles from the worker's snapshot, resampling when output size changes
|
||||
pub(super) fn restore(output: &mut BakeOutput, previous: &BakedMaps, excluded_tiles: &[(u32, u32)], grid: (u32, u32)) -> Result<()> {
|
||||
if excluded_tiles.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let size = (output.resolution, output.height);
|
||||
let tile_width = size.0 / grid.0.max(1);
|
||||
let tile_height = size.1 / grid.1.max(1);
|
||||
for (map, pixels) in &mut output.maps {
|
||||
let components = map.components();
|
||||
for &(column, row) in excluded_tiles {
|
||||
for y in row * tile_height..(row + 1) * tile_height {
|
||||
let first = (y as usize * size.0 as usize + column as usize * tile_width as usize) * components;
|
||||
let last = first + tile_width as usize * components;
|
||||
let row_pixels = pixels.get_mut(first..last).ok_or_else(|| EngineError::Other("excluded UV tile lies outside the baked pixels".into()))?;
|
||||
for (offset, pixel) in row_pixels.chunks_exact_mut(components).enumerate() {
|
||||
let value = previous.sample(*map, column * tile_width + offset as u32, y, size).unwrap_or_else(|| map.neutral());
|
||||
for (component, value) in pixel.iter_mut().zip(value) {
|
||||
*component = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Keep unchecked map outputs too when a partial bake changes the atlas dimensions
|
||||
for map in previous.maps.keys() {
|
||||
if output.maps.contains_key(map) || (previous.resolution == size.0 && previous.height(*map) == size.1) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let components = map.components();
|
||||
let count = (size.0 as usize)
|
||||
.checked_mul(size.1 as usize)
|
||||
.and_then(|count| count.checked_mul(components))
|
||||
.ok_or_else(|| EngineError::Other("resized bake map exceeds the addressable size".into()))?;
|
||||
let mut pixels = Vec::new();
|
||||
pixels.try_reserve_exact(count).map_err(|error| EngineError::Other(format!("cannot retain mesh map {}: {error}", map.id())))?;
|
||||
for y in 0..size.1 {
|
||||
for x in 0..size.0 {
|
||||
let value = previous.sample(*map, x, y, size).unwrap_or_else(|| map.neutral());
|
||||
pixels.extend(value.into_iter().take(components));
|
||||
}
|
||||
}
|
||||
output.maps.insert(*map, pixels);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad, boolp, u64p};
|
||||
use crate::set_cmds::ts_param;
|
||||
use crate::{Result, Session, cmd};
|
||||
|
||||
pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"bake.tile.set",
|
||||
"Include UV tile in bake",
|
||||
[],
|
||||
None,
|
||||
"{ts?, tile: UDIM number, enabled: bool} → {ts, tile, enabled}; excluded tiles keep existing baked pixels",
|
||||
always,
|
||||
set_enabled
|
||||
)]
|
||||
}
|
||||
|
||||
fn set_enabled(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
const COMMAND: &str = "bake.tile.set";
|
||||
let texture_set = ts_param(session, params, COMMAND)?;
|
||||
let tile = u64p(params, "tile").and_then(|tile| u32::try_from(tile).ok()).ok_or_else(|| bad(COMMAND, "`tile` must be a UDIM number"))?;
|
||||
let enabled = boolp(params, "enabled").ok_or_else(|| bad(COMMAND, "`enabled` must be true or false"))?;
|
||||
let settings = session.doc.project.texture_set(texture_set)?;
|
||||
if !settings.uv_tiles.contains(&tile) {
|
||||
return Err(bad(COMMAND, format!("texture set {} has no UV tile {tile}", settings.name)));
|
||||
}
|
||||
|
||||
let was_enabled = !settings.bake_excluded_tiles.contains(&tile);
|
||||
if enabled != was_enabled {
|
||||
session.edit("Include UV tile in bake", |session| {
|
||||
let settings = session.doc.project.texture_set_mut(texture_set)?;
|
||||
if enabled {
|
||||
settings.bake_excluded_tiles.remove(&tile);
|
||||
} else {
|
||||
settings.bake_excluded_tiles.insert(tile);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
Ok(json!({"ts": texture_set, "tile": tile, "enabled": enabled}))
|
||||
}
|
||||
@@ -28,6 +28,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
),
|
||||
cmd!("camera.remove", "Remove camera", [], None, "{index? | name?}", has_cameras, remove),
|
||||
cmd!("camera.rename", "Rename camera", [], None, "{index? | name?, to}", has_cameras, rename),
|
||||
cmd!("camera.bookmark1", "Go to camera 1", ["Viewport"], Some("Ctrl+1"), "{}", always, |s, _| bookmark(s, 0)),
|
||||
cmd!("camera.bookmark2", "Go to camera 2", ["Viewport"], Some("Ctrl+2"), "{}", always, |s, _| bookmark(s, 1)),
|
||||
cmd!("camera.bookmark3", "Go to camera 3", ["Viewport"], Some("Ctrl+3"), "{}", always, |s, _| bookmark(s, 2)),
|
||||
cmd!("camera.bookmark4", "Go to camera 4", ["Viewport"], Some("Ctrl+4"), "{}", always, |s, _| bookmark(s, 3)),
|
||||
cmd!("camera.bookmark5", "Go to camera 5", ["Viewport"], Some("Ctrl+5"), "{}", always, |s, _| bookmark(s, 4)),
|
||||
cmd!("camera.bookmark6", "Go to camera 6", ["Viewport"], Some("Ctrl+6"), "{}", always, |s, _| bookmark(s, 5)),
|
||||
cmd!("camera.bookmark7", "Go to camera 7", ["Viewport"], Some("Ctrl+7"), "{}", always, |s, _| bookmark(s, 6)),
|
||||
cmd!("camera.bookmark8", "Go to camera 8", ["Viewport"], Some("Ctrl+8"), "{}", always, |s, _| bookmark(s, 7)),
|
||||
cmd!("camera.bookmark9", "Go to camera 9", ["Viewport"], Some("Ctrl+9"), "{}", always, |s, _| bookmark(s, 8)),
|
||||
cmd!("viewport.focusAt", "Focus depth of field here", [], None, "{x, y (viewport pixels), viewport?: [w, h]}", always, focus_at),
|
||||
]
|
||||
}
|
||||
@@ -132,6 +141,14 @@ fn select(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(crate::view_cmds::camera_json(s))
|
||||
}
|
||||
|
||||
/// Shortcut slot `slot` (0-based): the n-th saved camera, in list order.
|
||||
fn bookmark(s: &mut Session, slot: usize) -> Result<Value> {
|
||||
if slot >= s.doc.project.cameras.len() {
|
||||
return Err(bad("camera.bookmark", "no saved camera in that slot (see camera.list)"));
|
||||
}
|
||||
select(s, &json!({ "index": slot }))
|
||||
}
|
||||
|
||||
fn remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let i = which(s, "camera.remove", p)?;
|
||||
s.edit("Remove camera", |s| {
|
||||
@@ -202,6 +219,25 @@ mod tests {
|
||||
assert_eq!(s.doc.project.cameras.len(), 2, "removing is undoable");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn number_shortcuts_go_to_the_first_nine_cameras() {
|
||||
let mut s = session();
|
||||
assert!(execute(&mut s, "camera.bookmark1", &Value::Null).is_err(), "no cameras yet");
|
||||
execute(&mut s, "camera.set", &json!({"yaw": 30})).unwrap();
|
||||
let first = s.camera;
|
||||
execute(&mut s, "camera.add", &json!({"name": "A"})).unwrap();
|
||||
execute(&mut s, "camera.orbit", &json!({"dx": 50})).unwrap();
|
||||
execute(&mut s, "camera.add", &json!({"name": "B"})).unwrap();
|
||||
execute(&mut s, "camera.bookmark1", &Value::Null).unwrap();
|
||||
assert_eq!(s.camera, first);
|
||||
execute(&mut s, "camera.bookmark2", &Value::Null).unwrap();
|
||||
assert_eq!(execute(&mut s, "camera.list", &Value::Null).unwrap()["current"], 1);
|
||||
assert!(execute(&mut s, "camera.bookmark3", &Value::Null).is_err(), "empty slot");
|
||||
let ids: Vec<_> = crate::command_specs().iter().filter(|c| c.id.starts_with("camera.bookmark")).collect();
|
||||
assert_eq!(ids.len(), 9);
|
||||
assert!(ids.iter().all(|c| c.shortcut.is_some()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cameras_round_trip_through_the_project_file() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
//! Color selection effects: the ID colors they select, picked from the ID mesh map
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_core::{BakedMap, EffectKind, LayerId};
|
||||
use texturecraft_geom::glam::Vec2;
|
||||
use texturecraft_geom::surface_at;
|
||||
|
||||
use crate::commands::{CommandSpec, bad, f32p, has_layer};
|
||||
use crate::mask_cmds::effect_id;
|
||||
use crate::tool_cmds::viewport_of;
|
||||
use crate::{Result, Session, cmd};
|
||||
|
||||
/// Most colors one color selection holds; an ID map rarely has more distinct parts
|
||||
const MAX_SELECTED_COLORS: usize = 256;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"effect.colorSelection.pick",
|
||||
"Pick ID color",
|
||||
[],
|
||||
None,
|
||||
"{effect?: a color selection (default: the selected effect), x?, y?: viewport pixels, viewport?: [w,h] | uv?: [u,v] texture set atlas UV (the 2D view), index?: replace this color instead of adding one} → {color: [r,g,b] as the ID map stores it, index} — samples the ID mesh map under the point",
|
||||
has_layer,
|
||||
pick
|
||||
)]
|
||||
}
|
||||
|
||||
/// Applies `effect.set`'s `colors` and `tolerance` params to a color selection
|
||||
pub(crate) fn apply_params(params: &Value, colors: &mut Vec<[f32; 3]>, tolerance: &mut f32) -> Result<()> {
|
||||
if let Some(list) = params.get("colors") {
|
||||
*colors = colors_param(list)?;
|
||||
}
|
||||
if let Some(value) = f32p(params, "tolerance") {
|
||||
*tolerance = value.clamp(0.0, 1.0);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A non-empty `[[r, g, b], ...]` list of finite values, clamped to 0..1
|
||||
fn colors_param(list: &Value) -> Result<Vec<[f32; 3]>> {
|
||||
const CMD: &str = "effect.set";
|
||||
let items = list.as_array().ok_or_else(|| bad(CMD, "`colors` must be a list of [r, g, b]"))?;
|
||||
if items.is_empty() || items.len() > MAX_SELECTED_COLORS {
|
||||
return Err(bad(CMD, format!("`colors` needs 1 to {MAX_SELECTED_COLORS} colors")));
|
||||
}
|
||||
|
||||
items
|
||||
.iter()
|
||||
.map(|item| match finite_numbers::<3>(item) {
|
||||
Some(color) => Ok(color.map(|value| value.clamp(0.0, 1.0) as f32)),
|
||||
_ => Err(bad(CMD, "each color must be [r, g, b] with finite numbers")),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Samples the ID map under a viewport point or at a UV and adds the color to a color selection
|
||||
fn pick(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
const CMD: &str = "effect.colorSelection.pick";
|
||||
let effect = effect_id(session, params, CMD)?;
|
||||
let (owner, color_count) = match session.doc.project.effect(effect) {
|
||||
Some((owner, found)) => match &found.kind {
|
||||
EffectKind::ColorSelection { colors, .. } => (owner, colors.len()),
|
||||
other => return Err(bad(CMD, format!("{} is not a color selection", other.name()))),
|
||||
},
|
||||
None => return Err(bad(CMD, format!("no effect {}", effect.0))),
|
||||
};
|
||||
|
||||
let index = params
|
||||
.get("index")
|
||||
.filter(|index| !index.is_null())
|
||||
.map(|index| index.as_u64().ok_or_else(|| bad(CMD, "`index` must be a non-negative integer")))
|
||||
.transpose()?;
|
||||
let index = match index {
|
||||
Some(index) => Some(usize::try_from(index).ok().filter(|index| *index < color_count).ok_or_else(|| bad(CMD, format!("no color {index} to replace")))?),
|
||||
None if color_count >= MAX_SELECTED_COLORS => return Err(bad(CMD, format!("a color selection holds at most {MAX_SELECTED_COLORS} colors"))),
|
||||
None => None,
|
||||
};
|
||||
|
||||
let color = id_color_at(session, params, owner)?;
|
||||
session.edit("Pick ID color", |session| {
|
||||
let edited = session.doc.project.effect_mut(effect).ok_or_else(|| bad(CMD, format!("no effect {}", effect.0)))?;
|
||||
if let EffectKind::ColorSelection { colors, .. } = &mut edited.kind {
|
||||
match index.and_then(|index| colors.get_mut(index)) {
|
||||
Some(slot) => *slot = color,
|
||||
None => colors.push(color),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "color": color, "index": index.unwrap_or(color_count) }))
|
||||
}
|
||||
|
||||
/// The ID map color of the texel a color selection on `owner` reads at the picked point
|
||||
fn id_color_at(session: &Session, params: &Value, owner: LayerId) -> Result<[f32; 3]> {
|
||||
const CMD: &str = "effect.colorSelection.pick";
|
||||
let (set_index, _, _) = session.doc.project.locate(owner).ok_or_else(|| bad(CMD, "the effect's layer is not in a texture set"))?;
|
||||
let set = session.doc.project.texture_set(set_index)?;
|
||||
let baked = session.baked(set_index).filter(|baked| baked.maps.contains_key(&BakedMap::Id));
|
||||
let Some(baked) = baked else {
|
||||
return Err(bad(CMD, format!("texture set \"{}\" has no ID map: bake one, or set one with textureSet.meshMap.set", set.name)));
|
||||
};
|
||||
|
||||
let uv = match params.get("uv") {
|
||||
Some(uv) => uv_param(uv)?,
|
||||
None => {
|
||||
let (Some(x), Some(y)) = (f32p(params, "x"), f32p(params, "y")) else {
|
||||
return Err(bad(CMD, "give `x` and `y` (viewport pixels) or `uv`"));
|
||||
};
|
||||
|
||||
let (uv, material) = visible_surface(session, Vec2::new(x, y), viewport_of(session, params))
|
||||
.ok_or_else(|| bad(CMD, "nothing under that point: pick on the mesh"))?;
|
||||
if material != set.material {
|
||||
return Err(bad(CMD, "that surface belongs to another texture set"));
|
||||
}
|
||||
uv
|
||||
}
|
||||
};
|
||||
|
||||
// The same texel the mask evaluates, so a picked color always selects where it was picked
|
||||
let size = set.size();
|
||||
let texel = [uv.x * size.0 as f32, uv.y * size.1 as f32];
|
||||
if !texel.iter().zip([size.0, size.1]).all(|(position, extent)| (0.0..extent as f32).contains(position)) {
|
||||
return Err(bad(CMD, "that point is outside the texture set's UV space"));
|
||||
}
|
||||
baked.sample_working(BakedMap::Id, texel[0] as u32, texel[1] as u32, size, &set.block_scales()).ok_or_else(|| bad(CMD, "no ID color there"))
|
||||
}
|
||||
|
||||
/// The UV and mesh material under viewport pixel `screen`; hidden texture sets don't stop the ray
|
||||
fn visible_surface(session: &Session, screen: Vec2, viewport: Vec2) -> Option<(Vec2, usize)> {
|
||||
let viewport = viewport.max(Vec2::ONE);
|
||||
let device = Vec2::new(screen.x / viewport.x * 2.0 - 1.0, 1.0 - screen.y / viewport.y * 2.0);
|
||||
let ray = session.camera.ray(device, viewport.x / viewport.y);
|
||||
let sets = &session.doc.project.texture_sets;
|
||||
let visible = |triangle: u32| {
|
||||
let material = session.mesh.material_of(triangle as usize).unwrap_or(0);
|
||||
sets.iter().find(|set| set.material == material).is_none_or(|set| set.visible)
|
||||
};
|
||||
|
||||
let hit = session.bvh.closest_filtered(ray.origin, ray.dir, f32::MAX, &visible)?;
|
||||
let surface = surface_at(&session.mesh, hit.tri, hit.u, hit.v)?;
|
||||
Some((surface.uv, session.mesh.material_of(hit.tri as usize).unwrap_or(0)))
|
||||
}
|
||||
|
||||
/// A `[u, v]` param of finite numbers
|
||||
fn uv_param(uv: &Value) -> Result<Vec2> {
|
||||
match finite_numbers::<2>(uv) {
|
||||
Some([u, v]) => Ok(Vec2::new(u as f32, v as f32)),
|
||||
_ => Err(bad("effect.colorSelection.pick", "`uv` must be [u, v] with finite numbers")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Validate the shape before reading components, without allocating for oversized input
|
||||
fn finite_numbers<const N: usize>(list: &Value) -> Option<[f64; N]> {
|
||||
let items: &[Value; N] = list.as_array()?.as_slice().try_into().ok()?;
|
||||
let mut numbers = [0.0; N];
|
||||
for (number, item) in numbers.iter_mut().zip(items) {
|
||||
*number = item.as_f64().filter(|value| value.is_finite())?;
|
||||
}
|
||||
Some(numbers)
|
||||
}
|
||||
@@ -56,6 +56,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(crate::layer_ops::specs());
|
||||
v.extend(crate::instance_cmds::specs());
|
||||
v.extend(crate::mask_cmds::specs());
|
||||
v.extend(crate::color_selection_cmds::specs());
|
||||
v.extend(crate::effect_clipboard::specs());
|
||||
v.extend(crate::tool_cmds::specs());
|
||||
v.extend(crate::brush_preset_cmds::specs());
|
||||
@@ -65,11 +66,11 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(crate::quick_mask::specs());
|
||||
v.extend(crate::set_cmds::specs());
|
||||
v.extend(crate::meshmap_cmds::specs());
|
||||
v.extend(crate::meshmap_import_cmds::specs());
|
||||
v.extend(crate::uv_tile_cmds::specs());
|
||||
v.extend(crate::template_cmds::specs());
|
||||
v.extend(crate::project_cmds::specs());
|
||||
v.extend(crate::bake_cmds::specs());
|
||||
v.extend(crate::bake_paint_cmds::specs());
|
||||
v.extend(crate::bake::specs());
|
||||
v.extend(crate::materialx_cmds::specs());
|
||||
v.extend(crate::file_cmds::specs());
|
||||
v.extend(crate::preset_cmds::specs());
|
||||
|
||||
@@ -132,7 +132,7 @@ impl Session {
|
||||
fn material_files(&mut self, opts: ExportOptions, tiled: bool, materials: usize) -> Result<Vec<Vec<ExportedFile>>> {
|
||||
let opts = ExportOptions { atlas: true, ..opts };
|
||||
(0..materials)
|
||||
.map(|m| match self.doc.project.texture_sets.iter().position(|t| t.material == m) {
|
||||
.map(|m| match self.texture_set_of_material(m) {
|
||||
Some(ts) if tiled || self.doc.project.texture_sets.get(ts).is_some_and(|t| t.tile_grid().is_none()) => self.export_files(&[ts], &opts),
|
||||
_ => Ok(Vec::new()),
|
||||
})
|
||||
@@ -331,6 +331,11 @@ mod native {
|
||||
strp(p, key).filter(|s| !s.trim().is_empty()).ok_or_else(|| bad(cmd, format!("`{key}` is required")))
|
||||
}
|
||||
|
||||
/// `path` made absolute (as given when that fails), for [`Project::mesh_path`].
|
||||
pub fn absolute(path: &str) -> String {
|
||||
std::path::absolute(Path::new(path)).map_or_else(|_| path.to_string(), |p| p.display().to_string())
|
||||
}
|
||||
|
||||
/// Mesh file `path` with the files it references next to it folded in (a `.gltf`'s buffers
|
||||
/// and images, a loose USD layer's textures), ready to import and store in the project.
|
||||
pub fn read_mesh(cmd: &str, path: &str) -> Result<texturecraft_formats::MeshFile> {
|
||||
@@ -349,6 +354,7 @@ mod native {
|
||||
} else {
|
||||
let f = read_mesh("file.open", path)?;
|
||||
let mut s = Session::from_mesh_bytes(&f.name, &f.bytes, 2048, &stem_of(path))?;
|
||||
s.doc.project.mesh_path = absolute(path);
|
||||
s.log.extend(f.warnings);
|
||||
Ok(s)
|
||||
}
|
||||
@@ -367,8 +373,10 @@ mod native {
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub use native::{open_path, read_mesh};
|
||||
pub use native::{absolute, open_path, read_mesh};
|
||||
|
||||
/// `file.new {mesh, name?, resolution?, uvTiles?, template?}`: a new project from the mesh file `mesh`,
|
||||
/// remembering its path for Reimport mesh.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn new_from_mesh(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = native::path_param(p, "mesh", "file.new")?;
|
||||
@@ -377,6 +385,7 @@ fn new_from_mesh(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let res = u64p(p, "resolution").or(template.as_ref().map(|t| u64::from(t.resolution))).unwrap_or(2048);
|
||||
let name = strp(p, "name").map(str::to_string).unwrap_or_else(|| stem_of(path));
|
||||
let mut next = Session::from_mesh_bytes_tiled(&f.name, &f.bytes, u32::try_from(res).unwrap_or(0), &name, crate::commands::boolp(p, "uvTiles"))?;
|
||||
next.doc.project.mesh_path = native::absolute(path);
|
||||
next.log.extend(f.warnings);
|
||||
if let Some(t) = &template {
|
||||
next.apply_template(t);
|
||||
@@ -414,14 +423,28 @@ fn save_copy(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
native::save_to(s, &path, false)
|
||||
}
|
||||
|
||||
/// `file.reimportMesh {path?, preserveStrokes?}`: reimport from `path`, or from the project's own
|
||||
/// copy of the mesh when there is none. A path given is remembered as the project's mesh path.
|
||||
/// The remembered path is never read implicitly (a project file could point it anywhere on the
|
||||
/// host); callers that may read host files pass [`Session::remembered_mesh_path`] as `path`.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn reimport(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let file = strp(p, "path").map(|path| native::read_mesh("file.reimportMesh", path)).transpose()?;
|
||||
s.reimport_mesh(file, crate::commands::boolp(p, "preserveStrokes").unwrap_or(false))
|
||||
let path = strp(p, "path");
|
||||
let file = path.map(|path| native::read_mesh("file.reimportMesh", path)).transpose()?;
|
||||
let reply = s.reimport_mesh(file, crate::commands::boolp(p, "preserveStrokes").unwrap_or(false))?;
|
||||
if let Some(path) = path {
|
||||
s.doc.project.mesh_path = native::absolute(path);
|
||||
}
|
||||
Ok(reply)
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
impl Session {
|
||||
/// The file the mesh was imported from, when it is still there: what Reimport mesh reads again.
|
||||
pub fn remembered_mesh_path(&self) -> Option<&str> {
|
||||
Some(self.doc.project.mesh_path.as_str()).filter(|m| !m.is_empty() && std::path::Path::new(m).is_file())
|
||||
}
|
||||
|
||||
/// Replace the mesh with `file` (or re-read the project's own copy) and keep the project:
|
||||
/// texture sets map by material index. Nothing changes unless the new mesh fits the project.
|
||||
/// With `preserve_strokes`, painted pixels follow the surface where the UVs changed. Replies
|
||||
@@ -448,6 +471,8 @@ impl Session {
|
||||
let mut next = Session::new(doc, mesh, source)?;
|
||||
next.log.extend(warnings);
|
||||
next.path = self.path.clone();
|
||||
next.modified = true;
|
||||
next.project_id = self.project_id;
|
||||
let preserved = preserve_strokes.then(|| crate::preserve::preserve_strokes(self, &mut next));
|
||||
self.switch_to(next);
|
||||
Ok(preserved.map_or(Value::Null, |n| json!({ "preserved": n })))
|
||||
@@ -610,6 +635,59 @@ fn close(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Reimport mesh reads the mesh file again from where it was imported, so a change saved to
|
||||
/// the file since shows up (it used to re-read the project's own copy and change nothing).
|
||||
#[test]
|
||||
fn reimport_picks_up_changes_saved_to_the_mesh_file() {
|
||||
let dir = std::env::temp_dir().join(format!("tc_reimport_disk_{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let file = dir.join("tri.obj");
|
||||
let obj = |z: f32| {
|
||||
format!(
|
||||
"v -1 -1 {z}
|
||||
v 1 -1 0
|
||||
v 1 1 0
|
||||
vt 0 0
|
||||
vt 1 0
|
||||
vt 1 1
|
||||
f 1/1 2/2 3/3
|
||||
"
|
||||
)
|
||||
};
|
||||
std::fs::write(&file, obj(0.0)).unwrap();
|
||||
let path = file.display().to_string();
|
||||
let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
|
||||
crate::execute(&mut s, "file.new", &json!({"mesh": path, "resolution": 128})).unwrap();
|
||||
let low = |s: &Session| s.mesh.positions.iter().map(|p| p.z.abs()).fold(0.0_f32, f32::max);
|
||||
assert_eq!(low(&s), 0.0);
|
||||
// Edit the file, save the project, reopen it, then reimport with no path.
|
||||
std::fs::write(&file, obj(0.5)).unwrap();
|
||||
let mut reopened = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap();
|
||||
assert_eq!(low(&reopened), 0.0, "the project still holds the old copy");
|
||||
// A command without a path never reads the remembered host path (automation allows it).
|
||||
crate::execute(&mut reopened, "file.reimportMesh", &Value::Null).unwrap();
|
||||
assert_eq!(low(&reopened), 0.0, "no path: the project's own copy");
|
||||
let remembered = reopened.remembered_mesh_path().map(str::to_string).expect("the imported file is remembered");
|
||||
crate::execute(&mut reopened, "file.reimportMesh", &json!({ "path": remembered })).unwrap();
|
||||
assert!(low(&reopened) > 0.0, "the edited file must be read again");
|
||||
// The file gone: nothing is remembered, so the UI asks for one.
|
||||
std::fs::remove_file(&file).unwrap();
|
||||
assert!(reopened.remembered_mesh_path().is_none());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reimporting_a_saved_project_marks_it_modified() {
|
||||
let obj = b"v -1 -1 0\nv 1 -1 0\nv 1 1 0\nvt 0 0\nvt 1 0\nvt 1 1\nf 1/1 2/2 3/3\n";
|
||||
let original = Session::from_mesh_bytes("mesh.obj", obj, 128, "mesh").unwrap();
|
||||
let mut saved = Session::from_project_bytes(&original.to_project_bytes().unwrap()).unwrap();
|
||||
assert!(!saved.modified);
|
||||
let project = saved.project_id;
|
||||
crate::execute(&mut saved, "file.reimportMesh", &Value::Null).unwrap();
|
||||
assert!(saved.modified, "reimport must trigger the unsaved-changes prompt");
|
||||
assert_eq!(saved.project_id, project, "a reimport stays the same project");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_mesh_writes_obj_by_default_and_textured_glb() {
|
||||
let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
//! Which polygons a polygon fill box selects.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use texturecraft_geom::glam::Vec2;
|
||||
|
||||
/// How a polygon fill box decides whether it selects a polygon
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
pub enum FillHitTest {
|
||||
/// Any part of the polygon inside the box or crossing it
|
||||
#[default]
|
||||
Intersection,
|
||||
/// The polygon's center point inside the box
|
||||
ContainedCenter,
|
||||
}
|
||||
|
||||
impl FillHitTest {
|
||||
/// Whether the box from `low` to `high` selects the polygon made of `triangles` (their corners)
|
||||
pub fn selects(self, triangles: &[[Vec2; 3]], low: Vec2, high: Vec2) -> bool {
|
||||
match self {
|
||||
FillHitTest::Intersection => triangles.iter().any(|corners| triangle_overlaps_box(*corners, low, high)),
|
||||
FillHitTest::ContainedCenter => center(triangles).is_some_and(|point| point.cmpge(low).all() && point.cmple(high).all()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Area-weighted center of the triangles (their corners' mean when they have no area)
|
||||
fn center(triangles: &[[Vec2; 3]]) -> Option<Vec2> {
|
||||
if triangles.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
// One pass: total area, area-weighted centroids and plain centroids
|
||||
let (total_area, weighted, centroids) = triangles.iter().fold((0.0, Vec2::ZERO, Vec2::ZERO), |(total_area, weighted, centroids), corners| {
|
||||
let area = (corners[1] - corners[0]).perp_dot(corners[2] - corners[0]).abs();
|
||||
let centroid = (corners[0] + corners[1] + corners[2]) / 3.0;
|
||||
(total_area + area, weighted + centroid * area, centroids + centroid)
|
||||
});
|
||||
Some(if total_area > 0.0 { weighted / total_area } else { centroids / triangles.len() as f32 })
|
||||
}
|
||||
|
||||
/// Separating axis test of a triangle against an axis-aligned box
|
||||
fn triangle_overlaps_box(corners: [Vec2; 3], low: Vec2, high: Vec2) -> bool {
|
||||
let triangle_low = corners[0].min(corners[1]).min(corners[2]);
|
||||
let triangle_high = corners[0].max(corners[1]).max(corners[2]);
|
||||
if triangle_high.cmplt(low).any() || triangle_low.cmpgt(high).any() {
|
||||
return false;
|
||||
}
|
||||
|
||||
let box_corners = [low, Vec2::new(high.x, low.y), high, Vec2::new(low.x, high.y)];
|
||||
(0..3).all(|edge| {
|
||||
let axis = (corners[(edge + 1) % 3] - corners[edge]).perp();
|
||||
let span = |points: &[Vec2]| points.iter().fold((f32::MAX, f32::MIN), |(min, max), point| (min.min(axis.dot(*point)), max.max(axis.dot(*point))));
|
||||
let (triangle_min, triangle_max) = span(&corners);
|
||||
let (box_min, box_max) = span(&box_corners);
|
||||
triangle_max >= box_min && box_max >= triangle_min
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const TRIANGLE: [Vec2; 3] = [Vec2::new(0.0, 0.0), Vec2::new(4.0, 0.0), Vec2::new(0.0, 4.0)];
|
||||
|
||||
#[test]
|
||||
fn intersection_selects_any_overlap() {
|
||||
assert!(FillHitTest::Intersection.selects(&[TRIANGLE], Vec2::splat(1.0), Vec2::splat(6.0)), "a box cutting the triangle");
|
||||
assert!(!FillHitTest::Intersection.selects(&[TRIANGLE], Vec2::splat(3.0), Vec2::splat(5.0)), "inside the bounds, past the long edge");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn contained_center_selects_only_by_the_center() {
|
||||
assert!(!FillHitTest::ContainedCenter.selects(&[TRIANGLE], Vec2::splat(2.0), Vec2::splat(6.0)), "the center (4/3, 4/3) lies outside");
|
||||
assert!(FillHitTest::ContainedCenter.selects(&[TRIANGLE], Vec2::splat(1.0), Vec2::splat(2.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_polygon_center_weighs_its_triangles_by_area() {
|
||||
let square = [[Vec2::ZERO, Vec2::new(2.0, 0.0), Vec2::new(2.0, 2.0)], [Vec2::ZERO, Vec2::new(2.0, 2.0), Vec2::new(0.0, 2.0)]];
|
||||
assert_eq!(center(&square), Some(Vec2::ONE));
|
||||
assert_eq!(center(&[]), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
//! What one polygon fill target grows to.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Polygon fill granularity: what a clicked triangle or a boxed polygon grows to
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
pub enum FillMode {
|
||||
/// The triangle itself
|
||||
#[default]
|
||||
Triangle,
|
||||
/// The source polygon (quad or n-gon) the importer split into triangles
|
||||
Polygon,
|
||||
/// The UV island: triangles sharing edges in UV space
|
||||
UvIsland,
|
||||
/// The connected geometry: triangles sharing edges by position
|
||||
Mesh,
|
||||
}
|
||||
@@ -19,6 +19,20 @@ pub struct FilterDef {
|
||||
pub mask: bool,
|
||||
}
|
||||
|
||||
impl FilterDef {
|
||||
/// Whether it builds a filter effect (levels and material finishes are effect types of their own)
|
||||
pub fn is_filter_effect(&self) -> bool {
|
||||
matches!(build(self.id, &Value::Null), Ok(EffectKind::Filter(_)))
|
||||
}
|
||||
}
|
||||
|
||||
/// The library entries that build filter effects, in shelf order, worked out once
|
||||
pub fn filter_effects() -> &'static [&'static FilterDef] {
|
||||
static FILTER_EFFECTS: std::sync::LazyLock<Vec<&'static FilterDef>> =
|
||||
std::sync::LazyLock::new(|| FILTERS.iter().filter(|def| def.is_filter_effect()).collect());
|
||||
&FILTER_EFFECTS
|
||||
}
|
||||
|
||||
const fn def(id: &'static str, label: &'static str, group: &'static str, mask: bool) -> FilterDef {
|
||||
FilterDef { id, label, group, mask }
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! without a screenshot.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_core::{Effect, EffectKind, Fill, Filter, Layer, LayerKind, NormalFormat, Projection, Source};
|
||||
use texturecraft_core::{Effect, EffectKind, Fill, Filter, Generator, Layer, LayerKind, NormalFormat, Projection, Source};
|
||||
|
||||
use crate::Session;
|
||||
use crate::session::StackTarget;
|
||||
@@ -34,38 +34,49 @@ fn fill_json(f: &Fill) -> Value {
|
||||
}
|
||||
|
||||
/// A mask or content (`content`) effect.
|
||||
fn effect_json(s: &Session, e: &Effect, content: bool) -> Value {
|
||||
let mut ej = json!({ "id": e.id.0, "name": e.name, "kind": e.kind.name(), "visible": e.visible, "blend": e.blend.label(), "opacity": e.opacity });
|
||||
match &e.kind {
|
||||
EffectKind::Generator(g) => {
|
||||
ej["generator"] = json!({ "type": format!("{:?}", g.kind), "level": g.level, "softness": g.softness, "noise": g.noise_amount, "invert": g.invert })
|
||||
fn effect_json(session: &Session, effect: &Effect, content: bool) -> Value {
|
||||
let mut out = json!({ "id": effect.id.0, "name": effect.name, "kind": effect.kind.name(), "visible": effect.visible, "blend": effect.blend.label(), "opacity": effect.opacity });
|
||||
let mask_tiles = || session.doc.pixels.masks.get(&effect.id).map_or(0, |image| image.allocated_count());
|
||||
let content_tiles = || session.doc.pixels.layers.iter().filter(|((id, _), _)| *id == effect.id).map(|(_, image)| image.allocated_count()).sum::<usize>();
|
||||
|
||||
match &effect.kind {
|
||||
EffectKind::Generator(generator) => out["generator"] = generator_json(generator),
|
||||
EffectKind::Levels(levels) => out["levels"] = json!([levels.in_low, levels.in_high, levels.gamma, levels.out_low, levels.out_high]),
|
||||
EffectKind::ColorSelection { colors, tolerance } => {
|
||||
out["colors"] = json!(colors);
|
||||
out["tolerance"] = json!(tolerance);
|
||||
}
|
||||
EffectKind::Levels(lv) => ej["levels"] = json!([lv.in_low, lv.in_high, lv.gamma, lv.out_low, lv.out_high]),
|
||||
EffectKind::Path(paths) => {
|
||||
ej["paths"] = json!(paths.iter().map(|p| json!({ "points": p.points.len(), "uv": p.uv, "closed": p.closed, "fill": p.fill })).collect::<Vec<_>>());
|
||||
ej["tiles"] = json!(if content {
|
||||
s.doc.pixels.layers.iter().filter(|((id, _), _)| *id == e.id).map(|(_, img)| img.allocated_count()).sum::<usize>()
|
||||
} else {
|
||||
s.doc.pixels.masks.get(&e.id).map(|i| i.allocated_count()).unwrap_or(0)
|
||||
});
|
||||
out["paths"] = json!(
|
||||
paths.iter().map(|path| json!({ "points": path.points.len(), "uv": path.uv, "closed": path.closed, "fill": path.fill })).collect::<Vec<_>>()
|
||||
);
|
||||
out["tiles"] = json!(if content { content_tiles() } else { mask_tiles() });
|
||||
}
|
||||
EffectKind::Paint if content => {
|
||||
ej["tiles"] = json!(s.doc.pixels.layers.iter().filter(|((id, _), _)| *id == e.id).map(|(_, img)| img.allocated_count()).sum::<usize>())
|
||||
}
|
||||
EffectKind::Paint => ej["tiles"] = json!(s.doc.pixels.masks.get(&e.id).map(|i| i.allocated_count()).unwrap_or(0)),
|
||||
EffectKind::Fill { source, .. } => ej["source"] = source_json(source),
|
||||
EffectKind::Material(f) => ej["fill"] = fill_json(f),
|
||||
EffectKind::Filter(f) => {
|
||||
ej["filter"] = json!(f);
|
||||
match f {
|
||||
Filter::Hsl { hue, saturation, lightness } => ej["hsl"] = json!([hue, saturation, lightness]),
|
||||
Filter::Blur { radius } => ej["radius"] = json!(radius),
|
||||
EffectKind::Paint if content => out["tiles"] = json!(content_tiles()),
|
||||
EffectKind::Paint => out["tiles"] = json!(mask_tiles()),
|
||||
EffectKind::Fill { source, .. } => out["source"] = source_json(source),
|
||||
EffectKind::Material(fill) => out["fill"] = fill_json(fill),
|
||||
EffectKind::Filter(filter) => {
|
||||
out["filter"] = json!(filter);
|
||||
match filter {
|
||||
Filter::Hsl { hue, saturation, lightness } => out["hsl"] = json!([hue, saturation, lightness]),
|
||||
Filter::Blur { radius } => out["radius"] = json!(radius),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
ej
|
||||
out
|
||||
}
|
||||
|
||||
/// A generator's settings, with its curvature mode and detail size weights when it has them.
|
||||
fn generator_json(generator: &Generator) -> Value {
|
||||
let mut out = json!({ "type": format!("{:?}", generator.kind), "level": generator.level, "softness": generator.softness, "noise": generator.noise_amount, "invert": generator.invert });
|
||||
if let Some(detail) = &generator.detail {
|
||||
out["mode"] = json!(format!("{:?}", detail.mode));
|
||||
out["sizes"] = json!(detail.weights);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn layer_json(s: &Session, l: &Layer, depth: usize) -> Value {
|
||||
@@ -129,26 +140,34 @@ pub fn texture_sets(s: &Session) -> Value {
|
||||
json!((0..s.set_count()).map(|i| texture_set(s, i)).collect::<Vec<_>>())
|
||||
}
|
||||
|
||||
/// One texture set; UV-tiled sets list their tiles and where each sits in the texel atlas.
|
||||
pub fn texture_set(s: &Session, i: usize) -> Value {
|
||||
let Some(t) = s.doc.project.texture_sets.get(i) else { return Value::Null };
|
||||
let grid = t.tile_grid();
|
||||
let tiles: Vec<Value> =
|
||||
t.uv_tiles.iter().filter_map(|u| grid?.block(*u).map(|(x, y)| json!({ "udim": u, "block": [x, y], "resolution": t.tile_resolution(*u) }))).collect();
|
||||
/// One texture set, including UV tile layout and bake selection
|
||||
pub fn texture_set(session: &Session, index: usize) -> Value {
|
||||
let Some(texture_set) = session.doc.project.texture_sets.get(index) else { return Value::Null };
|
||||
|
||||
let grid = texture_set.tile_grid();
|
||||
let tiles: Vec<Value> = texture_set
|
||||
.uv_tiles
|
||||
.iter()
|
||||
.filter_map(|tile| {
|
||||
grid?.block(*tile).map(|(x, y)| {
|
||||
json!({"udim": tile, "block": [x, y], "resolution": texture_set.tile_resolution(*tile), "bakeEnabled": !texture_set.bake_excluded_tiles.contains(tile)})
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
json!({
|
||||
"index": i,
|
||||
"name": t.name,
|
||||
"resolution": t.resolution,
|
||||
"size": t.size(),
|
||||
"blockResolution": t.block_resolution(),
|
||||
"uvTiles": t.uv_tiles,
|
||||
"index": index,
|
||||
"name": texture_set.name,
|
||||
"resolution": texture_set.resolution,
|
||||
"size": texture_set.size(),
|
||||
"blockResolution": texture_set.block_resolution(),
|
||||
"uvTiles": texture_set.uv_tiles,
|
||||
"tiles": tiles,
|
||||
"channels": t.channels.iter().map(|(c, f)| json!({ "channel": c.id(), "format": f.label() })).collect::<Vec<_>>(),
|
||||
"layers": s.doc.project.walk(i).len(),
|
||||
"parts": crate::set_cmds::parts(s, i),
|
||||
"baked": crate::project_cmds::baked_json(s.doc.baked.get(&i)),
|
||||
"visible": t.visible,
|
||||
"active": i == s.ts(),
|
||||
"channels": texture_set.channels.iter().map(|(channel, format)| json!({ "channel": channel.id(), "format": format.label() })).collect::<Vec<_>>(),
|
||||
"layers": session.doc.project.walk(index).len(),
|
||||
"parts": crate::set_cmds::parts(session, index),
|
||||
"baked": crate::project_cmds::baked_json(session.doc.baked.get(&index)),
|
||||
"visible": texture_set.visible,
|
||||
"active": index == session.ts(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -161,7 +180,7 @@ pub fn session(s: &Session) -> Value {
|
||||
"path": s.path,
|
||||
"modified": s.modified,
|
||||
"textureSets": texture_sets(s),
|
||||
"bakeMeshes": crate::bake_cmds::meshes_json(s),
|
||||
"bakeMeshes": crate::bake::meshes_json(s),
|
||||
"activeTextureSet": ts,
|
||||
"selectedLayer": s.selected_layer().map(|l| l.0),
|
||||
"target": match s.target { StackTarget::Content => json!("content"), StackTarget::Mask => json!("mask"), StackTarget::Effect(e) => json!(e.0) },
|
||||
|
||||
@@ -8,16 +8,16 @@
|
||||
#![forbid(unsafe_code)]
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
pub mod bake_cmds;
|
||||
#[path = "bake/mod.rs"]
|
||||
mod bake_data;
|
||||
mod bake_paint_cmds;
|
||||
pub mod bake;
|
||||
pub mod brush_preset_cmds;
|
||||
pub mod camera_cmds;
|
||||
pub mod color_selection_cmds;
|
||||
pub mod commands;
|
||||
pub mod decal_cmds;
|
||||
pub mod effect_clipboard;
|
||||
pub mod file_cmds;
|
||||
pub mod fill_hit_test;
|
||||
pub mod fill_mode;
|
||||
pub mod filter_lib;
|
||||
pub mod inspect;
|
||||
pub mod instance_cmds;
|
||||
@@ -25,12 +25,20 @@ pub mod layer_cmds;
|
||||
pub mod layer_ops;
|
||||
pub mod link_cmds;
|
||||
pub mod mask_cmds;
|
||||
mod mask_preview_pixel;
|
||||
pub mod material_lib;
|
||||
mod material_preview_pixel;
|
||||
pub mod materials;
|
||||
pub mod materialx_cmds;
|
||||
pub mod meshmap_cmds;
|
||||
mod meshmap_file_name;
|
||||
pub mod meshmap_import_cmds;
|
||||
mod orb_camera;
|
||||
pub mod orb_preview;
|
||||
pub mod painting;
|
||||
pub mod path_tool;
|
||||
mod polygon_fill;
|
||||
mod polygon_fill_drag;
|
||||
// Mesh reimport reads files: native only.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod preserve;
|
||||
@@ -45,17 +53,20 @@ pub mod smart_masks;
|
||||
pub mod template_cmds;
|
||||
pub mod text_cmds;
|
||||
pub mod tool_cmds;
|
||||
mod triangle_partition;
|
||||
mod uv_stroke_state;
|
||||
pub mod uv_tile_cmds;
|
||||
pub mod view_cmds;
|
||||
|
||||
pub use bake_data::{BakeMesh, BakeMeshes, BakeTask};
|
||||
pub use bake::{BakeMesh, BakeMeshes, BakeTask};
|
||||
pub use commands::{CommandSpec, command_specs, execute, find};
|
||||
pub use fill_hit_test::FillHitTest;
|
||||
pub use fill_mode::FillMode;
|
||||
pub use path_tool::PathState;
|
||||
pub use project_cmds::sample_session;
|
||||
pub use session::{CloneFrom, CloneSource, Document, FillMode, Session, SetCache, StackTarget, StencilState, Tool, ToolState, ViewMode};
|
||||
pub use session::{CloneFrom, CloneSource, Document, Session, SetCache, StackTarget, StencilState, Tool, ToolState, ViewMode};
|
||||
pub use set_cmds::{ResizeOutput, ResizeTask};
|
||||
|
||||
pub use texturecraft_bake as bake;
|
||||
pub use texturecraft_compose as compose;
|
||||
pub use texturecraft_core as core;
|
||||
pub use texturecraft_formats as formats;
|
||||
|
||||
+149
-56
@@ -2,8 +2,8 @@
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_core::{
|
||||
BlendMode, Channel, CompareOp, Effect, EffectKind, Filter, Generator, GeneratorKind, LayerId, Levels, Mask, MaskBackground, Procedural, ProceduralKind,
|
||||
Project, Source,
|
||||
BlendMode, Channel, CompareOp, CurvatureDetail, CurvatureMode, Effect, EffectKind, Filter, Generator, GeneratorKind, LayerId, Levels, Mask, MaskBackground,
|
||||
Procedural, ProceduralKind, Project, Source,
|
||||
};
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, f32p, has_layer, layer_param, strp, u64p};
|
||||
@@ -49,7 +49,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add generator",
|
||||
["Layers", "Effects"],
|
||||
None,
|
||||
"{layer?, name?, generator?: edgeWear|dirt|thinAreas|curvature|ambientOcclusion|position|direction, level?, softness?, noise?, invert?}",
|
||||
"{layer?, name?, generator?: edgeWear|dirt|thinAreas|curvature|ambientOcclusion|position|direction, level?, softness?, noise?, invert?, mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear)}",
|
||||
has_layer,
|
||||
add_generator
|
||||
),
|
||||
@@ -94,7 +94,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Edit effect",
|
||||
[],
|
||||
None,
|
||||
"{effect, visible?, blend?, opacity?, name?, level?, softness?, noise?, noiseScale?, invert?, value?, anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, filter parameters (see effect.add.filter)}",
|
||||
"{effect, visible?, blend?, opacity?, name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place), level?, softness?, noise?, noiseScale?, invert?, mode?, sizes?, value?, anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, colors?: [[r,g,b], ...] (a color selection's ID colors), filter parameters (see effect.add.filter)}",
|
||||
has_layer,
|
||||
set
|
||||
),
|
||||
@@ -314,39 +314,76 @@ fn add_fill(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
push_effect(s, p, EffectKind::Fill { source, projection }, blend)
|
||||
}
|
||||
|
||||
fn generator_from(p: &Value, g: &mut Generator) {
|
||||
if let Some(v) = f32p(p, "level") {
|
||||
g.level = v.clamp(0.0, 1.0);
|
||||
/// Apply `params` to `generator`, using `command` in errors
|
||||
fn generator_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> {
|
||||
if let Some(level) = f32p(params, "level") {
|
||||
generator.level = level.clamp(0.0, 1.0);
|
||||
}
|
||||
if let Some(v) = f32p(p, "softness") {
|
||||
g.softness = v.clamp(0.0, 1.0);
|
||||
if let Some(softness) = f32p(params, "softness") {
|
||||
generator.softness = softness.clamp(0.0, 1.0);
|
||||
}
|
||||
if let Some(v) = f32p(p, "noise") {
|
||||
g.noise_amount = v.clamp(0.0, 2.0);
|
||||
if let Some(noise) = f32p(params, "noise") {
|
||||
generator.noise_amount = noise.clamp(0.0, 2.0);
|
||||
}
|
||||
if let Some(v) = f32p(p, "noiseScale") {
|
||||
g.noise_scale = v.clamp(0.01, 1000.0);
|
||||
if let Some(noise_scale) = f32p(params, "noiseScale") {
|
||||
generator.noise_scale = noise_scale.clamp(0.01, 1000.0);
|
||||
}
|
||||
if let Some(v) = u64p(p, "seed") {
|
||||
g.seed = v as u32;
|
||||
if let Some(seed) = u64p(params, "seed") {
|
||||
generator.seed = seed as u32;
|
||||
}
|
||||
if let Some(v) = boolp(p, "invert") {
|
||||
g.invert = v;
|
||||
if let Some(invert) = boolp(params, "invert") {
|
||||
generator.invert = invert;
|
||||
}
|
||||
if let Some(d) = color_param(p, "direction") {
|
||||
g.direction = d;
|
||||
if let Some(direction) = color_param(params, "direction") {
|
||||
generator.direction = direction;
|
||||
}
|
||||
|
||||
// A mode or sizes also give a curvature generator saved before detail sizes its detail
|
||||
let mode = params
|
||||
.get("mode")
|
||||
.map(|value| {
|
||||
let name = value.as_str().ok_or_else(|| bad(command, "`mode` must be a string"))?;
|
||||
CurvatureMode::parse(name).ok_or_else(|| bad(command, format!("unknown curvature mode `{name}`")))
|
||||
})
|
||||
.transpose()?;
|
||||
let weights = params.get("sizes").map(|value| size_weights(command, value)).transpose()?;
|
||||
if mode.is_none() && weights.is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
if !matches!(generator.kind, GeneratorKind::Curvature | GeneratorKind::EdgeWear) {
|
||||
return Err(bad(command, "only curvature and edge wear generators have a mode and detail sizes"));
|
||||
}
|
||||
|
||||
let detail = generator.detail.get_or_insert_with(CurvatureDetail::default);
|
||||
if let Some(mode) = mode {
|
||||
detail.mode = mode;
|
||||
}
|
||||
if let Some(weights) = weights {
|
||||
detail.weights = weights;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn add_generator(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let kind = match strp(p, "generator") {
|
||||
Some(k) => GeneratorKind::parse(k).ok_or_else(|| bad("effect.add.generator", format!("unknown generator `{k}`")))?,
|
||||
/// Read one weight (0..1) per size of [`CurvatureDetail::SIZES`], finest first
|
||||
fn size_weights(command: &str, value: &Value) -> Result<[f32; CurvatureDetail::SIZES.len()]> {
|
||||
let invalid = || bad(command, format!("`sizes` takes {} numbers, finest first", CurvatureDetail::SIZES.len()));
|
||||
let items = value.as_array().filter(|items| items.len() == CurvatureDetail::SIZES.len()).ok_or_else(invalid)?;
|
||||
let mut weights = [0.0; CurvatureDetail::SIZES.len()];
|
||||
for (weight, item) in weights.iter_mut().zip(items) {
|
||||
*weight = item.as_f64().ok_or_else(invalid)?.clamp(0.0, 1.0) as f32;
|
||||
}
|
||||
Ok(weights)
|
||||
}
|
||||
|
||||
fn add_generator(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
let kind = match strp(params, "generator") {
|
||||
Some(name) => GeneratorKind::parse(name).ok_or_else(|| bad("effect.add.generator", format!("unknown generator `{name}`")))?,
|
||||
None => GeneratorKind::EdgeWear,
|
||||
};
|
||||
let mut g = Generator::new(kind);
|
||||
generator_from(p, &mut g);
|
||||
let blend = blend_param("effect.add.generator", p, "blend")?.unwrap_or(BlendMode::Normal);
|
||||
push_effect(s, p, EffectKind::Generator(g), blend)
|
||||
let mut generator = Generator::new(kind);
|
||||
generator_from("effect.add.generator", params, &mut generator)?;
|
||||
let blend = blend_param("effect.add.generator", params, "blend")?.unwrap_or(BlendMode::Normal);
|
||||
push_effect(session, params, EffectKind::Generator(generator), blend)
|
||||
}
|
||||
|
||||
pub(crate) fn levels_from(p: &Value, l: &mut Levels) {
|
||||
@@ -413,55 +450,79 @@ fn histogram(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(if content { json!({"target": "content", "channel": channel.id(), "bins": counts}) } else { json!({"target": "mask", "bins": counts}) })
|
||||
}
|
||||
|
||||
fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let eid = effect_id(s, p, "effect.set")?;
|
||||
let blend = blend_param("effect.set", p, "blend")?;
|
||||
// A fill reading an anchor: `anchor` picks the anchor point, `anchorChannel` alone
|
||||
// re-targets the current one.
|
||||
let anchor = match s.doc.project.effect(eid) {
|
||||
/// Edit visibility, blending, name, effect parameters, or a filter's type
|
||||
fn set(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
const CMD: &str = "effect.set";
|
||||
let effect = effect_id(session, params, CMD)?;
|
||||
let blend = blend_param(CMD, params, "blend")?;
|
||||
|
||||
// `anchor` picks a fill's anchor point, `anchorChannel` alone re-targets the current one
|
||||
let anchor = match session.doc.project.effect(effect) {
|
||||
Some((owner, Effect { kind: EffectKind::Fill { source, .. }, .. })) => {
|
||||
let (current, channel) = match source {
|
||||
Source::Anchor { anchor, channel } => (Some(*anchor), *channel),
|
||||
_ => (None, Channel::Height),
|
||||
};
|
||||
let channel_param = channel_param("effect.set", p, "anchorChannel")?;
|
||||
match u64p(p, "anchor").map(LayerId).or(current.filter(|_| channel_param.is_some())) {
|
||||
Some(a) => Some(anchor_source(s, "effect.set", owner, a, channel_param.unwrap_or(channel))?),
|
||||
let channel_param = channel_param(CMD, params, "anchorChannel")?;
|
||||
match u64p(params, "anchor").map(LayerId).or(current.filter(|_| channel_param.is_some())) {
|
||||
Some(anchor) => Some(anchor_source(session, CMD, owner, anchor, channel_param.unwrap_or(channel))?),
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
s.edit("Edit effect", |s| {
|
||||
let e = s.doc.project.effect_mut(eid).ok_or_else(|| bad("effect.set", format!("no effect {}", eid.0)))?;
|
||||
if let Some(v) = boolp(p, "visible") {
|
||||
e.visible = v;
|
||||
|
||||
// Naming the filter the effect already is edits its parameters like a plain effect.set
|
||||
let swapped = match strp(params, "filter") {
|
||||
Some(filter) if crate::filter_lib::find(filter).is_some_and(|def| current_filter_id(session, effect) == Some(def.id)) => None,
|
||||
Some(filter) => Some(swapped_filter(session, effect, filter, params)?),
|
||||
None => None,
|
||||
};
|
||||
let swaps_filter = swapped.is_some();
|
||||
|
||||
session.edit("Edit effect", |session| {
|
||||
let edited = session.doc.project.effect_mut(effect).ok_or_else(|| bad(CMD, format!("no effect {}", effect.0)))?;
|
||||
if let Some((kind, label)) = swapped {
|
||||
if let EffectKind::Filter(old) = &edited.kind
|
||||
&& edited.name == old.label()
|
||||
{
|
||||
edited.name = label.to_string();
|
||||
}
|
||||
edited.kind = kind;
|
||||
}
|
||||
if let Some(b) = blend {
|
||||
e.blend = b;
|
||||
|
||||
if let Some(visible) = boolp(params, "visible") {
|
||||
edited.visible = visible;
|
||||
}
|
||||
if let Some(o) = f32p(p, "opacity") {
|
||||
e.opacity = o.clamp(0.0, 1.0);
|
||||
if let Some(blend) = blend {
|
||||
edited.blend = blend;
|
||||
}
|
||||
if let Some(n) = name_param(p) {
|
||||
e.name = n.to_string();
|
||||
if let Some(opacity) = f32p(params, "opacity") {
|
||||
edited.opacity = opacity.clamp(0.0, 1.0);
|
||||
}
|
||||
match &mut e.kind {
|
||||
EffectKind::Generator(g) => generator_from(p, g),
|
||||
EffectKind::Levels(l) => levels_from(p, l),
|
||||
EffectKind::Filter(f) => crate::filter_lib::apply(p, f, "effect.set")?,
|
||||
if let Some(name) = name_param(params) {
|
||||
edited.name = name.to_string();
|
||||
}
|
||||
|
||||
match &mut edited.kind {
|
||||
EffectKind::Generator(generator) => generator_from(CMD, params, generator)?,
|
||||
EffectKind::Levels(levels) => levels_from(params, levels),
|
||||
// The swapped filter was built with the parameters already
|
||||
EffectKind::Filter(_) if swaps_filter => {}
|
||||
EffectKind::Filter(filter) => crate::filter_lib::apply(params, filter, CMD)?,
|
||||
EffectKind::Fill { source, .. } => {
|
||||
if let Some(a) = anchor {
|
||||
*source = a;
|
||||
} else if let Some(x) = f32p(p, "value")
|
||||
if let Some(anchor) = anchor {
|
||||
*source = anchor;
|
||||
} else if let Some(value) = f32p(params, "value")
|
||||
&& matches!(source, Source::Uniform(_) | Source::Anchor { .. })
|
||||
{
|
||||
*source = Source::Uniform([x.clamp(0.0, 1.0); 3]);
|
||||
*source = Source::Uniform([value.clamp(0.0, 1.0); 3]);
|
||||
}
|
||||
}
|
||||
EffectKind::ColorSelection { tolerance, .. } | EffectKind::Compare { tolerance, .. } => {
|
||||
if let Some(x) = f32p(p, "tolerance") {
|
||||
*tolerance = x.clamp(0.0, 1.0);
|
||||
EffectKind::ColorSelection { colors, tolerance } => crate::color_selection_cmds::apply_params(params, colors, tolerance)?,
|
||||
EffectKind::Compare { tolerance, .. } => {
|
||||
if let Some(value) = f32p(params, "tolerance") {
|
||||
*tolerance = value.clamp(0.0, 1.0);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
@@ -471,6 +532,38 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
/// The library id of the filter effect `effect` is, if it is one
|
||||
fn current_filter_id(s: &Session, effect: LayerId) -> Option<&'static str> {
|
||||
match &s.doc.project.effect(effect)?.1.kind {
|
||||
EffectKind::Filter(filter) => crate::filter_lib::find(filter.label()).map(|def| def.id),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Filter `id` built with `p` and its label, to replace filter effect `effect`
|
||||
fn swapped_filter(s: &Session, effect: LayerId, id: &str, p: &Value) -> Result<(EffectKind, &'static str)> {
|
||||
const CMD: &str = "effect.set";
|
||||
let (owner, current) = s.doc.project.effect(effect).ok_or_else(|| bad(CMD, format!("no effect {}", effect.0)))?;
|
||||
if !matches!(current.kind, EffectKind::Filter(_)) {
|
||||
return Err(bad(CMD, format!("`filter` changes filter effects only, not {}", current.kind.name().to_ascii_lowercase())));
|
||||
}
|
||||
|
||||
let def = crate::filter_lib::find(id).ok_or_else(|| bad(CMD, format!("unknown filter `{id}` (see filter.list)")))?;
|
||||
let mut kind = crate::filter_lib::build(def.id, &Value::Null)?;
|
||||
let EffectKind::Filter(filter) = &mut kind else {
|
||||
return Err(bad(CMD, format!("{} is its own effect type: add it with effect.add.filter", def.label)));
|
||||
};
|
||||
|
||||
let mask = s.doc.project.layer(owner)?.mask.as_ref();
|
||||
let on_mask = mask.is_some_and(|mask| mask.effects.iter().any(|masked| masked.id == effect));
|
||||
if on_mask && !def.mask {
|
||||
return Err(bad(CMD, format!("{} goes on layer content, not on masks", def.label)));
|
||||
}
|
||||
|
||||
crate::filter_lib::apply(p, filter, CMD)?;
|
||||
Ok((kind, def.label))
|
||||
}
|
||||
|
||||
/// The stack (a mask's or a layer's content effects) holding effect `eid`, and its position there.
|
||||
fn stack_of(project: &mut Project, eid: LayerId) -> Option<(&mut Vec<Effect>, usize)> {
|
||||
project.layers.values_mut().find_map(|l| {
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
//! One pixel of a smart mask preview (see [`crate::orb_preview::OrbPreview::mask`])
|
||||
|
||||
use texturecraft_geom::glam::Vec3;
|
||||
|
||||
/// The smart mask value seen at a preview pixel, with what a display needs to shade the shape.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct MaskPreviewPixel {
|
||||
/// Mask value (0..=1).
|
||||
pub mask: f32,
|
||||
/// Surface normal in view space (+X right, +Y up, +Z towards the viewer).
|
||||
pub normal: Vec3,
|
||||
/// Fraction of the pixel the shape covers (0..=1, anti-aliased outline).
|
||||
pub coverage: f32,
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
//! One pixel of a smart material preview (see [`crate::orb_preview::OrbPreview::material`])
|
||||
|
||||
use texturecraft_geom::glam::Vec3;
|
||||
|
||||
use crate::preview::Sample;
|
||||
|
||||
/// The material values seen at a preview pixel, with what a display needs to light the shape
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct MaterialPreviewPixel {
|
||||
/// Linear material values, averaged over the pixel
|
||||
pub sample: Sample,
|
||||
/// Surface normal in view space (+X right, +Y up, +Z towards the viewer)
|
||||
pub normal: Vec3,
|
||||
/// Fraction of the pixel the shape covers (0..=1, anti-aliased outline)
|
||||
pub coverage: f32,
|
||||
}
|
||||
@@ -38,55 +38,91 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ts = ts_param(s, p, CMD)?;
|
||||
let map = map_param(p, CMD)?;
|
||||
let name = strp(p, "image").ok_or_else(|| bad(CMD, "`image` (an image resource name) is required"))?;
|
||||
let img = s.images.get(name).cloned().ok_or_else(|| bad(CMD, format!("no image resource `{name}`")))?;
|
||||
let set = s.doc.project.texture_set(ts)?.clone();
|
||||
let tiles = set.tile_grid().map(|grid| tile_images(&s.images, name, &set.uv_tiles).map(|imgs| (grid, imgs))).transpose()?;
|
||||
// Every mesh map of a set shares one size: the other maps', or what a bake would make (a
|
||||
// block of the bake resolution per tile of the atlas).
|
||||
let (cols, rows) = tiles.as_ref().map_or((1, 1), |(g, _)| (g.cols, g.rows));
|
||||
let (res, height) = match s.doc.baked.get(&ts).filter(|b| !b.maps.is_empty()) {
|
||||
Some(b) => (b.resolution, b.maps.keys().next().map_or(b.resolution, |m| b.height(*m))),
|
||||
None => {
|
||||
let (width, height) = set.bake.common.output_size();
|
||||
(width.saturating_mul(cols), height.saturating_mul(rows))
|
||||
}
|
||||
let image = s.images.get(name).cloned().ok_or_else(|| bad(CMD, format!("no image resource `{name}`")))?;
|
||||
let texture_set = s.doc.project.texture_set(ts)?;
|
||||
let images = match texture_set.tile_grid() {
|
||||
Some(_) => tile_images(&s.images, CMD, name, &texture_set.uv_tiles)?,
|
||||
None => BTreeMap::from([(FIRST_TILE, image)]),
|
||||
};
|
||||
if res == 0 || height == 0 || u64::from(res) * u64::from(height) > texturecraft_bake::MAX_TEXELS || (tiles.is_none() && res > MAX_RESOLUTION) {
|
||||
return Err(bad(CMD, format!("mesh map size {res} × {height} is too large or empty")));
|
||||
}
|
||||
let directx = map == BakedMap::Normal && s.doc.project.normal_format == NormalFormat::DirectX;
|
||||
let data = match &tiles {
|
||||
None => resample(map.components(), (res, height), directx, |u, v| img.sample(u, v)),
|
||||
// An atlas texel reads the image of the tile its mesh UV falls in.
|
||||
Some((grid, imgs)) => resample(map.components(), (res, height), directx, |u, v| {
|
||||
let uv = set.from_atlas(grid, [u, v]);
|
||||
udim_at(uv).and_then(|t| imgs.get(&t)).map_or([0.0; 4], |img| img.sample(uv[0] - uv[0].floor(), uv[1] - uv[1].floor()))
|
||||
}),
|
||||
};
|
||||
s.edit("Use image as mesh map", |s| {
|
||||
let entry = s.doc.baked.entry(ts).or_default();
|
||||
entry.resolution = res;
|
||||
entry.maps.insert(map, Arc::new(data));
|
||||
s.doc.project.texture_set_mut(ts)?.baked.insert(map);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "map": map.id(), "resolution": res }))
|
||||
|
||||
let resolution = s.edit("Use image as mesh map", |s| use_images(s, CMD, ts, map, &images))?;
|
||||
Ok(json!({ "map": map.id(), "resolution": resolution }))
|
||||
}
|
||||
|
||||
/// The image of every UV tile of a set: `name` with its tile number (`ao.1001.png`) swapped for
|
||||
/// each tile's.
|
||||
fn tile_images(images: &ImageStore, name: &str, tiles: &[u32]) -> Result<BTreeMap<u32, Arc<ImageRes>>> {
|
||||
const CMD: &str = "textureSet.meshMap.set";
|
||||
let at = udim_in(name).ok_or_else(|| bad(CMD, format!("`{name}` names no UV tile: a UV-tiled set takes one image per tile, named like ao.1001.png")))?;
|
||||
/// 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}")));
|
||||
}
|
||||
|
||||
let (width, height) = image_map_size(s, cmd, ts)?;
|
||||
|
||||
let flip_green = map == BakedMap::Normal && 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();
|
||||
entry.resolution = width;
|
||||
entry.maps.insert(map, Arc::new(data));
|
||||
s.doc.project.texture_set_mut(ts)?.baked.insert(map);
|
||||
Ok(width)
|
||||
}
|
||||
|
||||
/// Dimensions shared by imported mesh maps, checked before allocating the resampled pixels
|
||||
pub(crate) fn image_map_size(s: &Session, cmd: &str, ts: usize) -> Result<(u32, u32)> {
|
||||
let texture_set = s.doc.project.texture_set(ts)?;
|
||||
let grid = texture_set.tile_grid();
|
||||
|
||||
// Every mesh map of a set shares one size: the other maps', or a bake's (a bake-size block per atlas tile)
|
||||
let (columns, rows) = grid.map_or((1, 1), |grid| (grid.cols, grid.rows));
|
||||
let (width, height) = match s.doc.baked.get(&ts).filter(|baked| !baked.maps.is_empty()) {
|
||||
Some(baked) => (baked.resolution, baked.maps.keys().next().map_or(baked.resolution, |other| baked.height(*other))),
|
||||
None => {
|
||||
let (width, height) = texture_set.bake.common.output_size();
|
||||
(width.saturating_mul(columns), height.saturating_mul(rows))
|
||||
}
|
||||
};
|
||||
let empty = width == 0 || height == 0;
|
||||
let too_many_texels = u64::from(width) * u64::from(height) > texturecraft_bake::MAX_TEXELS;
|
||||
let too_wide = grid.is_none() && width > MAX_RESOLUTION;
|
||||
if empty || too_many_texels || too_wide {
|
||||
return Err(bad(cmd, format!("mesh map size {width} × {height} is too large or empty")));
|
||||
}
|
||||
|
||||
Ok((width, height))
|
||||
}
|
||||
|
||||
/// The image of every UV tile of a set: `name` with its tile number (`ao.1001.png`) swapped for each tile's
|
||||
fn tile_images(images: &ImageStore, cmd: &str, name: &str, tiles: &[u32]) -> Result<BTreeMap<u32, Arc<ImageRes>>> {
|
||||
let tile_at =
|
||||
udim_in(name).ok_or_else(|| bad(cmd, format!("`{name}` names no UV tile: a UV-tiled set takes one image per tile, named like ao.1001.png")))?;
|
||||
let (before_tile, after_tile) = (name.get(..tile_at).unwrap_or_default(), name.get(tile_at + 4..).unwrap_or_default());
|
||||
tiles
|
||||
.iter()
|
||||
.map(|&t| {
|
||||
let tile_name = format!("{}{t}{}", name.get(..at).unwrap_or_default(), name.get(at + 4..).unwrap_or_default());
|
||||
images.get(&tile_name).cloned().map(|img| (t, img)).ok_or_else(|| bad(CMD, format!("no image `{tile_name}` for UV tile {t}")))
|
||||
.map(|&tile| {
|
||||
let tile_name = format!("{before_tile}{tile}{after_tile}");
|
||||
images.get(&tile_name).cloned().map(|image| (tile, image)).ok_or_else(|| bad(cmd, format!("no image `{tile_name}` for UV tile {tile}")))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The UV tile number in a file name (`Body_ao.1002.png` → 1002)
|
||||
pub(crate) fn tile_number(file_name: &str) -> Option<u32> {
|
||||
udim_in(file_name).and_then(|at| file_name.get(at..at + 4)).and_then(|digits| digits.parse().ok())
|
||||
}
|
||||
|
||||
/// Where the last UDIM tile number (four digits alone, in [`UDIM_RANGE`]) in `name` starts.
|
||||
fn udim_in(name: &str) -> Option<usize> {
|
||||
let b = name.as_bytes();
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
//! Which texture set and mesh map a baked map file is for, by file name (`Body_ao.1001.png` = Body's ambient occlusion)
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use texturecraft_core::{BakedMap, UDIM_RANGE};
|
||||
|
||||
/// Mesh maps named by two words anywhere in the file name; they win over the one-word names
|
||||
const TWO_WORD_NAMES: &[(&str, &[&str], BakedMap)] = &[
|
||||
("world", &["normal", "normals"], BakedMap::WorldNormal),
|
||||
("bent", &["normal", "normals"], BakedMap::BentNormal),
|
||||
("ambient", &["occlusion"], BakedMap::AmbientOcclusion),
|
||||
];
|
||||
|
||||
/// Mesh maps named by one word, including the two-word names written as one
|
||||
const ONE_WORD_NAMES: &[(&str, BakedMap)] = &[
|
||||
("worldnormal", BakedMap::WorldNormal),
|
||||
("worldnormals", BakedMap::WorldNormal),
|
||||
("bentnormal", BakedMap::BentNormal),
|
||||
("bentnormals", BakedMap::BentNormal),
|
||||
("ambientocclusion", BakedMap::AmbientOcclusion),
|
||||
("normal", BakedMap::Normal),
|
||||
("normals", BakedMap::Normal),
|
||||
("nrm", BakedMap::Normal),
|
||||
("occlusion", BakedMap::AmbientOcclusion),
|
||||
("ao", BakedMap::AmbientOcclusion),
|
||||
("curvature", BakedMap::Curvature),
|
||||
("curv", BakedMap::Curvature),
|
||||
("id", BakedMap::Id),
|
||||
("position", BakedMap::Position),
|
||||
("pos", BakedMap::Position),
|
||||
("thickness", BakedMap::Thickness),
|
||||
("height", BakedMap::Height),
|
||||
("displacement", BakedMap::Height),
|
||||
("opacity", BakedMap::Opacity),
|
||||
("alpha", BakedMap::Opacity),
|
||||
];
|
||||
|
||||
fn is_separator(c: char) -> bool {
|
||||
matches!(c, '_' | '-' | '.' | ' ')
|
||||
}
|
||||
|
||||
/// The lowercase file name without its folder and extension
|
||||
fn lowercase_stem(path: &str) -> String {
|
||||
Path::new(path).file_stem().and_then(|stem| stem.to_str()).unwrap_or_default().to_lowercase()
|
||||
}
|
||||
|
||||
/// What follows `set_name` at the start of a lowercase stem, when a separator follows it
|
||||
fn after_set_name<'a>(stem: &'a str, set_name: &str) -> Option<&'a str> {
|
||||
if set_name.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
stem.strip_prefix(&set_name.to_lowercase()).filter(|rest| rest.starts_with(is_separator))
|
||||
}
|
||||
|
||||
/// The mesh map a file holds, from the words of its name after `set_name`; the last recognised word wins
|
||||
pub(crate) fn baked_map_from_file_name(path: &str, set_name: &str) -> Option<BakedMap> {
|
||||
let stem = lowercase_stem(path);
|
||||
let rest = after_set_name(&stem, set_name).unwrap_or(&stem);
|
||||
let is_tile_number = |word: &str| word.len() == 4 && word.parse::<u32>().is_ok_and(|number| UDIM_RANGE.contains(&number));
|
||||
let words: Vec<&str> = rest.split(is_separator).filter(|word| !word.is_empty() && !is_tile_number(word)).collect();
|
||||
|
||||
let has = |name: &str| words.contains(&name);
|
||||
TWO_WORD_NAMES
|
||||
.iter()
|
||||
.find(|(first, seconds, _)| has(first) && seconds.iter().any(|second| has(second)))
|
||||
.map(|(_, _, map)| *map)
|
||||
.or_else(|| words.iter().rev().find_map(|word| ONE_WORD_NAMES.iter().find(|(name, _)| name == word).map(|(_, map)| *map)))
|
||||
}
|
||||
|
||||
/// The set a file is for: the longest set name its name starts with before a separator (any name with one set)
|
||||
pub(crate) fn texture_set_from_file_name(path: &str, set_names: &[&str]) -> Option<usize> {
|
||||
if set_names.len() == 1 {
|
||||
return Some(0);
|
||||
}
|
||||
|
||||
let stem = lowercase_stem(path);
|
||||
set_names.iter().enumerate().filter(|(_, name)| after_set_name(&stem, name).is_some()).max_by_key(|(_, name)| name.chars().count()).map(|(ts, _)| ts)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn each_word_names_its_map() {
|
||||
let cases = [
|
||||
("Body_normal.png", BakedMap::Normal),
|
||||
("Body_normals.png", BakedMap::Normal),
|
||||
("Body_nrm.png", BakedMap::Normal),
|
||||
("Body_world_normal.png", BakedMap::WorldNormal),
|
||||
("Body_normals_world.png", BakedMap::WorldNormal),
|
||||
("Body_WorldNormal.png", BakedMap::WorldNormal),
|
||||
("Body_bent_normals.png", BakedMap::BentNormal),
|
||||
("Body-ambient-occlusion.png", BakedMap::AmbientOcclusion),
|
||||
("Body_AmbientOcclusion.png", BakedMap::AmbientOcclusion),
|
||||
("Body_occlusion.png", BakedMap::AmbientOcclusion),
|
||||
("Body AO.png", BakedMap::AmbientOcclusion),
|
||||
("Body_curvature.png", BakedMap::Curvature),
|
||||
("Body_curv.png", BakedMap::Curvature),
|
||||
("Body_ID.png", BakedMap::Id),
|
||||
("Body_position.png", BakedMap::Position),
|
||||
("Body_pos.png", BakedMap::Position),
|
||||
("Body_thickness.png", BakedMap::Thickness),
|
||||
("Body_height.png", BakedMap::Height),
|
||||
("Body_displacement.png", BakedMap::Height),
|
||||
("Body_opacity.png", BakedMap::Opacity),
|
||||
("Body_alpha.png", BakedMap::Opacity),
|
||||
];
|
||||
for (file, map) in cases {
|
||||
assert_eq!(baked_map_from_file_name(file, "Body"), Some(map), "{file}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tile_numbers_and_folders_are_ignored() {
|
||||
assert_eq!(baked_map_from_file_name("/bakes/Body_ao.1001.png", "Body"), Some(BakedMap::AmbientOcclusion));
|
||||
assert_eq!(baked_map_from_file_name("Body_normal_1002.tga", "Body"), Some(BakedMap::Normal));
|
||||
assert_eq!(texture_set_from_file_name("/bakes/Body_ao.1001.png", &["Head", "Body"]), Some(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_words_match_no_map() {
|
||||
assert_eq!(baked_map_from_file_name("Body_diffuse.png", "Body"), None);
|
||||
assert_eq!(baked_map_from_file_name("Body_1001.png", "Body"), None);
|
||||
assert_eq!(baked_map_from_file_name("ambient.png", "Body"), None);
|
||||
assert_eq!(baked_map_from_file_name("", "Body"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_set_name_is_not_read_as_a_map() {
|
||||
assert_eq!(baked_map_from_file_name("World_normal.png", "World"), Some(BakedMap::Normal));
|
||||
assert_eq!(baked_map_from_file_name("ID_diffuse.png", "ID"), None);
|
||||
assert_eq!(baked_map_from_file_name("Body_ao.png", ""), Some(BakedMap::AmbientOcclusion));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_longest_set_name_wins() {
|
||||
let sets = ["Body", "Body_Upper", "Head"];
|
||||
assert_eq!(texture_set_from_file_name("Body_Upper_ao.png", &sets), Some(1));
|
||||
assert_eq!(texture_set_from_file_name("body_ao.png", &sets), Some(0));
|
||||
assert_eq!(texture_set_from_file_name("HEAD-normal.png", &sets), Some(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_set_name_must_end_at_a_separator() {
|
||||
let sets = ["Body", "Head"];
|
||||
assert_eq!(texture_set_from_file_name("Bodywork_ao.png", &sets), None);
|
||||
assert_eq!(texture_set_from_file_name("Arm_ao.png", &sets), None);
|
||||
assert_eq!(texture_set_from_file_name("Body.png", &sets), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_set_takes_every_file() {
|
||||
assert_eq!(texture_set_from_file_name("ao.png", &["Body"]), Some(0));
|
||||
assert_eq!(texture_set_from_file_name("Head_ao.png", &["Body"]), Some(0));
|
||||
assert_eq!(texture_set_from_file_name("ao.png", &[]), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
//! Import mesh maps baked in another app: many files at once, each to the set and slot its file name names
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::Path;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_core::BakedMap;
|
||||
|
||||
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::{Result, Session, cmd};
|
||||
|
||||
const CMD: &str = "textureSet.meshMap.import";
|
||||
|
||||
/// Most files one import takes: every mesh map of dozens of sets, each split over a few UV tiles
|
||||
const MAX_FILES: usize = 512;
|
||||
|
||||
/// Bound retained file bytes, decoded RGBA floats and resampled maps together, before allocating pixels
|
||||
const MAX_TOTAL_BYTES: u64 = 2 << 30;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"textureSet.meshMap.import",
|
||||
"Import baked maps",
|
||||
[],
|
||||
None,
|
||||
"{files: [{path, map?: mesh map id}]} → {assigned: [{path, ts, map}], unmatched: [path]} — each image file becomes the mesh map its name names (`Body_ao.png`, `Body_world_normal.png`; or `map`) of the texture set its name starts with (any name when there is one set), read as by textureSet.meshMap.set. A UV-tiled set takes one file per tile, named with the tile number (`Body_ao.1001.png`, `Body_ao.1002.png`). Left out and listed in `unmatched`: files matching no set or map, a second file for one slot or tile, files of a UV-tiled set without one of its tile numbers, and every file of a map missing a tile. One undo step (none when nothing matches); at most 512 files and 2 GiB of file bytes, decoded images and mesh maps; desktop only",
|
||||
always,
|
||||
import
|
||||
)]
|
||||
}
|
||||
|
||||
fn import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
import_with_budget(s, p, MAX_TOTAL_BYTES)
|
||||
}
|
||||
|
||||
fn import_with_budget(s: &mut Session, p: &Value, max_bytes: u64) -> Result<Value> {
|
||||
let files = p.get("files").and_then(Value::as_array).ok_or_else(|| bad(CMD, "`files` (a list of {path, map?}) is required"))?;
|
||||
if files.len() > MAX_FILES {
|
||||
return Err(bad(CMD, format!("at most {MAX_FILES} files at once")));
|
||||
}
|
||||
|
||||
let set_names: Vec<&str> = s.doc.project.texture_sets.iter().map(|set| set.name.as_str()).collect();
|
||||
let mut slots: BTreeMap<(usize, BakedMap), BTreeMap<u32, &str>> = BTreeMap::new();
|
||||
let mut unmatched = Vec::new();
|
||||
for file in files {
|
||||
let path = strp(file, "path").ok_or_else(|| bad(CMD, "every file needs a `path`"))?;
|
||||
let given_map = match file.get("map") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(Value::String(id)) => Some(BakedMap::parse(id).ok_or_else(|| bad(CMD, format!("unknown mesh map `{id}`")))?),
|
||||
Some(_) => return Err(bad(CMD, "`map` must be a mesh map id string")),
|
||||
};
|
||||
|
||||
match slot_of(s, &set_names, path, given_map) {
|
||||
Some((slot, tile)) if !slots.get(&slot).is_some_and(|tiles| tiles.contains_key(&tile)) => {
|
||||
slots.entry(slot).or_default().insert(tile, path);
|
||||
}
|
||||
_ => unmatched.push(path),
|
||||
}
|
||||
}
|
||||
|
||||
// A UV-tiled map needs a file for every tile of its set
|
||||
slots.retain(|(ts, _), tiles| {
|
||||
let complete =
|
||||
s.doc.project.texture_sets.get(*ts).is_some_and(|set| set.tile_grid().is_none() || set.uv_tiles.iter().all(|tile| tiles.contains_key(tile)));
|
||||
if !complete {
|
||||
unmatched.extend(tiles.values());
|
||||
}
|
||||
complete
|
||||
});
|
||||
if slots.is_empty() {
|
||||
return Ok(json!({ "assigned": [], "unmatched": unmatched }));
|
||||
}
|
||||
|
||||
let result = s.edit("Import baked maps", |s| {
|
||||
let mut assigned = Vec::new();
|
||||
let mut remaining_bytes = max_bytes;
|
||||
for ((ts, map), tiles) in &slots {
|
||||
let (width, height) = image_map_size(s, CMD, *ts)?;
|
||||
let map_bytes = u64::from(width) * u64::from(height) * map.components() as u64 * size_of::<f32>() as u64;
|
||||
reserve_bytes(&mut remaining_bytes, map_bytes)?;
|
||||
|
||||
let mut images = BTreeMap::new();
|
||||
for (tile, path) in tiles {
|
||||
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)?;
|
||||
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());
|
||||
assigned.push(json!({"path": path, "ts": ts, "map": map.id()}));
|
||||
}
|
||||
use_images(s, CMD, *ts, *map, &images)?;
|
||||
}
|
||||
Ok(assigned)
|
||||
});
|
||||
// A failed edit leaves the document as it was; forget the images it decoded
|
||||
if result.is_err() {
|
||||
s.sync_images();
|
||||
}
|
||||
|
||||
Ok(json!({ "assigned": result?, "unmatched": unmatched }))
|
||||
}
|
||||
|
||||
fn reserve_bytes(remaining_bytes: &mut u64, bytes: u64) -> Result<()> {
|
||||
*remaining_bytes = remaining_bytes.checked_sub(bytes).ok_or_else(|| bad(CMD, "the files, decoded images and mesh maps exceed the import memory budget"))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The texture set and mesh map a file is for, and its UV tile ([`FIRST_TILE`] on a set without UV tiles)
|
||||
fn slot_of(s: &Session, set_names: &[&str], path: &str, given_map: Option<BakedMap>) -> Option<((usize, BakedMap), u32)> {
|
||||
let ts = texture_set_from_file_name(path, set_names)?;
|
||||
let map = given_map.or_else(|| baked_map_from_file_name(path, set_names.get(ts).copied().unwrap_or_default()))?;
|
||||
let texture_set = s.doc.project.texture_sets.get(ts)?;
|
||||
let tile = match texture_set.tile_grid() {
|
||||
Some(_) => tile_number(Path::new(path).file_name()?.to_str()?).filter(|tile| texture_set.uv_tiles.contains(tile))?,
|
||||
None => FIRST_TILE,
|
||||
};
|
||||
Some(((ts, map), tile))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use texturecraft_core::BakeResolution;
|
||||
|
||||
#[test]
|
||||
fn import_budget_counts_decoded_images_and_resampled_maps() {
|
||||
let dir = std::env::temp_dir().join(format!("texturecraft-import-budget-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let paths = [dir.join("ao.png"), dir.join("height.png")];
|
||||
for path in &paths {
|
||||
image::RgbaImage::from_pixel(16, 16, image::Rgba([128, 128, 128, 255])).save(path).unwrap();
|
||||
}
|
||||
let file_bytes: u64 = paths.iter().map(|path| std::fs::metadata(path).unwrap().len()).sum();
|
||||
let decoded_bytes = 2 * 16 * 16 * 16;
|
||||
let map_bytes = 2 * 16 * 16 * 4;
|
||||
let required_bytes = file_bytes + decoded_bytes + map_bytes;
|
||||
let params = json!({"files": paths.map(|path| json!({"path": path}))});
|
||||
let mut session = Session::new_project("budget", texturecraft_geom::primitives::cube(2.0), "builtin:cube", None, 128).unwrap();
|
||||
session.doc.project.texture_sets[0].bake.common.resolution = BakeResolution::R16;
|
||||
let revision = session.revision;
|
||||
|
||||
for budget in [file_bytes, file_bytes + decoded_bytes, required_bytes - 1] {
|
||||
let result = import_with_budget(&mut session, ¶ms, budget);
|
||||
assert!(result.is_err(), "budget {budget} must cover decoded pixels and mesh maps: {result:?}");
|
||||
assert!(session.doc.resources.is_empty() && session.images.is_empty());
|
||||
assert!(session.doc.baked.values().all(|baked| baked.maps.is_empty()));
|
||||
assert_eq!(session.revision, revision);
|
||||
assert!(!session.modified);
|
||||
assert!(session.undo_label().is_none());
|
||||
}
|
||||
|
||||
let result = import_with_budget(&mut session, ¶ms, required_bytes).unwrap();
|
||||
assert_eq!(result["assigned"].as_array().unwrap().len(), 2);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
//! Cached camera rays for one preview orb size
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use texturecraft_geom::glam::{Quat, Vec2, Vec3};
|
||||
use texturecraft_geom::surface_at;
|
||||
|
||||
use crate::Session;
|
||||
|
||||
/// Camera angles expose the front, left and top panels
|
||||
const CAMERA_PITCH_DEG: f32 = 35.0;
|
||||
const CAMERA_YAW_DEG: f32 = -34.4;
|
||||
|
||||
/// Index into [`OrbCamera::texels`] and view-space normal; None on a miss
|
||||
pub(crate) type CameraSample = Option<(usize, Vec3)>;
|
||||
|
||||
/// What each ray of a square orthographic view of the orb sees
|
||||
pub(crate) struct OrbCamera {
|
||||
/// Rays along each side of the view
|
||||
pub rays_per_side: usize,
|
||||
/// The texels (x, y) the camera sees, each once
|
||||
pub texels: Vec<(u32, u32)>,
|
||||
/// Per ray, row-major `rays_per_side²`
|
||||
pub samples: Vec<CameraSample>,
|
||||
}
|
||||
|
||||
impl OrbCamera {
|
||||
/// Trace a square orthographic view onto a `texture_px²` texture
|
||||
pub fn new(session: &Session, texture_px: u32, rays_per_side: usize) -> OrbCamera {
|
||||
let (min, max) = session.mesh.bounds();
|
||||
let center = (min + max) * 0.5;
|
||||
let radius = session.mesh.positions.iter().map(|position| position.distance(center)).fold(0.0f32, f32::max);
|
||||
let pitch = CAMERA_PITCH_DEG.to_radians();
|
||||
let turn = Quat::from_rotation_y(CAMERA_YAW_DEG.to_radians());
|
||||
let forward = turn * Vec3::new(0.0, -pitch.sin(), -pitch.cos());
|
||||
let right = turn * Vec3::X;
|
||||
let up = right.cross(forward);
|
||||
let max_texel = texture_px.saturating_sub(1);
|
||||
|
||||
let mut texels = Vec::new();
|
||||
let mut index_of = HashMap::new();
|
||||
let samples = (0..rays_per_side * rays_per_side)
|
||||
.map(|ray| {
|
||||
let side = rays_per_side as f32;
|
||||
let ndc = Vec2::new(((ray % rays_per_side) as f32 + 0.5) / side * 2.0 - 1.0, 1.0 - ((ray / rays_per_side) as f32 + 0.5) / side * 2.0);
|
||||
// Start well outside the shape so every ray enters it from the front
|
||||
let origin = center + (right * ndc.x + up * ndc.y) * radius - forward * radius * 4.0;
|
||||
let hit = session.bvh.closest(origin, forward, radius * 8.0)?;
|
||||
let surface = surface_at(&session.mesh, hit.tri, hit.u, hit.v)?;
|
||||
let texel = (((surface.uv.x * texture_px as f32) as u32).min(max_texel), ((surface.uv.y * texture_px as f32) as u32).min(max_texel));
|
||||
let index = *index_of.entry(texel).or_insert_with(|| {
|
||||
texels.push(texel);
|
||||
texels.len() - 1
|
||||
});
|
||||
|
||||
let normal = surface.nrm;
|
||||
Some((index, Vec3::new(normal.dot(right), normal.dot(up), -normal.dot(forward))))
|
||||
})
|
||||
.collect();
|
||||
|
||||
OrbCamera { rays_per_side, texels, samples }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,297 @@
|
||||
//! Smart mask and smart material previews share one baked [`primitives::preview_orb`]
|
||||
//! Presets use `mask.smart.apply`, materials use [`materials::apply`], both read back from the compositor
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use serde_json::json;
|
||||
use texturecraft_core::{BakeResolution, BakedMap, Channel, CurvatureMethod, LayerId};
|
||||
use texturecraft_geom::glam::Vec3;
|
||||
use texturecraft_geom::primitives;
|
||||
use texturecraft_texel::TILE;
|
||||
|
||||
pub use crate::mask_preview_pixel::MaskPreviewPixel;
|
||||
pub use crate::material_preview_pixel::MaterialPreviewPixel;
|
||||
use crate::orb_camera::OrbCamera;
|
||||
use crate::preview::Sample;
|
||||
use crate::session::Document;
|
||||
use crate::{EngineError, Result, Session, materials};
|
||||
|
||||
/// Bake resolution in texels; 256 loses the thin edge lines
|
||||
const TEXTURE_PX: u32 = 512;
|
||||
/// Camera rays per preview pixel along each axis (anti-aliased outline)
|
||||
const SUPERSAMPLE: usize = 2;
|
||||
/// Bound camera samples and output allocations for shelf previews
|
||||
pub const MAX_PREVIEW_SIZE_PX: usize = 512;
|
||||
/// AO and thickness rays per texel; thumbnail detail needs fewer than the default
|
||||
const OCCLUSION_RAYS: u32 = 12;
|
||||
/// Curvature rays per texel; thumbnail detail needs fewer than the default
|
||||
const CURVATURE_RAYS: u32 = 12;
|
||||
/// Radius relative to the bounding box; isolates panel edges from the round body
|
||||
const CURVATURE_RADIUS: f32 = 0.005;
|
||||
/// The mesh maps the smart mask generators read; smart materials build on the same presets
|
||||
const MAPS: [BakedMap; 3] = [BakedMap::Curvature, BakedMap::AmbientOcclusion, BakedMap::Thickness];
|
||||
/// Keep camera views for the thumbnail and hover preview sizes
|
||||
const CAMERAS_KEPT: usize = 2;
|
||||
/// The channels a material preview shows, in [`Sample`] order
|
||||
const MATERIAL_CHANNELS: [Channel; 4] = [Channel::BaseColor, Channel::Metallic, Channel::Roughness, Channel::Height];
|
||||
/// The orb's only texture set
|
||||
const SET: usize = 0;
|
||||
|
||||
/// The baked orb and, per preview size, what its camera sees
|
||||
pub struct OrbPreview {
|
||||
session: Session,
|
||||
/// The layer smart masks are applied to
|
||||
layer: LayerId,
|
||||
/// The baked document and selection, restored before each material
|
||||
bare: (Document, BTreeMap<usize, LayerId>),
|
||||
/// Cached camera views, least recently used first
|
||||
cameras: Vec<OrbCamera>,
|
||||
}
|
||||
|
||||
impl OrbPreview {
|
||||
/// Bake the orb once (previews of any size reuse it)
|
||||
pub fn new() -> Result<OrbPreview> {
|
||||
let mut session = Session::new_project("Orb preview", primitives::preview_orb(), "builtin:preview_orb", None, TEXTURE_PX)?;
|
||||
let set = session.doc.project.texture_set_mut(SET)?;
|
||||
set.bake.common.resolution = BakeResolution::from_pixels(TEXTURE_PX).ok_or_else(|| EngineError::Other("invalid bake resolution".into()))?;
|
||||
set.bake.high_poly.use_low_as_high = true;
|
||||
set.bake.maps.curvature.parameters.method = CurvatureMethod::Mesh;
|
||||
set.bake.maps.curvature.parameters.mesh.sampling_radius = CURVATURE_RADIUS;
|
||||
set.bake.maps.curvature.parameters.mesh.rays = CURVATURE_RAYS;
|
||||
set.bake.maps.ao.parameters.rays.rays = OCCLUSION_RAYS;
|
||||
set.bake.maps.thickness.parameters.rays.rays = OCCLUSION_RAYS;
|
||||
for map in BakedMap::ALL {
|
||||
set.bake.maps.set_enabled(map, MAPS.contains(&map));
|
||||
}
|
||||
let layer = *set.stack.first().ok_or_else(|| EngineError::Other("the preview has no layer".into()))?;
|
||||
session.bake_now(SET, false)?;
|
||||
|
||||
let bare = (session.doc.clone(), session.selected.clone());
|
||||
Ok(OrbPreview { session, layer, bare, cameras: Vec::new() })
|
||||
}
|
||||
|
||||
/// Row-major `size²` pixels of smart mask `id`, with None outside the shape
|
||||
/// Returns None for unknown masks or sizes outside 1..=[`MAX_PREVIEW_SIZE_PX`]
|
||||
pub fn mask(&mut self, id: &str, size: usize) -> Option<Vec<Option<MaskPreviewPixel>>> {
|
||||
if !valid_size(size) {
|
||||
return None;
|
||||
}
|
||||
|
||||
crate::execute(&mut self.session, "mask.smart.apply", &json!({ "name": id, "layer": self.layer.0 })).ok()?;
|
||||
// Previews need no undo history; retaining snapshots grows memory across presets
|
||||
self.session.undo.clear();
|
||||
|
||||
let camera = camera_for(&mut self.cameras, &self.session, size)?;
|
||||
let values = self.session.mask_at(self.layer, &camera.texels)?;
|
||||
|
||||
let sub_pixels = (SUPERSAMPLE * SUPERSAMPLE) as f32;
|
||||
let pixels = (0..size * size)
|
||||
.map(|pixel| {
|
||||
let (mut mask_sum, mut normal_sum, mut hits) = (0.0, Vec3::ZERO, 0.0);
|
||||
for (texel, normal) in pixel_hits(camera, size, pixel) {
|
||||
mask_sum += values.get(texel).copied().unwrap_or(0.0);
|
||||
normal_sum += normal;
|
||||
hits += 1.0;
|
||||
}
|
||||
|
||||
(hits > 0.0).then(|| MaskPreviewPixel { mask: mask_sum / hits, normal: normal_sum.normalize_or_zero(), coverage: hits / sub_pixels })
|
||||
})
|
||||
.collect();
|
||||
Some(pixels)
|
||||
}
|
||||
|
||||
/// Row-major `size²` pixels of built-in material `id`, with None outside the shape
|
||||
/// Returns None for unknown materials or sizes outside 1..=[`MAX_PREVIEW_SIZE_PX`]
|
||||
pub fn material(&mut self, id: &str, size: usize) -> Option<Vec<Option<MaterialPreviewPixel>>> {
|
||||
if !valid_size(size) {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Each material goes on the bare shape, not over the previous one
|
||||
(self.session.doc, self.session.selected) = self.bare.clone();
|
||||
let applied = materials::apply(&mut self.session, id);
|
||||
// Previews need no undo history; retaining snapshots grows memory across materials
|
||||
self.session.undo.clear();
|
||||
applied.ok()?;
|
||||
|
||||
let camera = camera_for(&mut self.cameras, &self.session, size)?;
|
||||
let values = material_at(&self.session, &camera.texels)?;
|
||||
|
||||
let sub_pixels = (SUPERSAMPLE * SUPERSAMPLE) as f32;
|
||||
let pixels = (0..size * size)
|
||||
.map(|pixel| {
|
||||
let mut sum = Sample { base: [0.0; 3], metallic: 0.0, roughness: 0.0, height: 0.0 };
|
||||
let (mut normal_sum, mut hits) = (Vec3::ZERO, 0.0);
|
||||
for (texel, normal) in pixel_hits(camera, size, pixel) {
|
||||
let Some(value) = values.get(texel) else { continue };
|
||||
|
||||
sum.base = [0, 1, 2].map(|component| sum.base[component] + value.base[component]);
|
||||
sum.metallic += value.metallic;
|
||||
sum.roughness += value.roughness;
|
||||
sum.height += value.height;
|
||||
normal_sum += normal;
|
||||
hits += 1.0;
|
||||
}
|
||||
|
||||
(hits > 0.0).then(|| {
|
||||
let mean = Sample {
|
||||
base: sum.base.map(|component| component / hits),
|
||||
metallic: sum.metallic / hits,
|
||||
roughness: sum.roughness / hits,
|
||||
height: sum.height / hits,
|
||||
};
|
||||
MaterialPreviewPixel { sample: mean, normal: normal_sum.normalize_or_zero(), coverage: hits / sub_pixels }
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
Some(pixels)
|
||||
}
|
||||
}
|
||||
|
||||
/// Preview sizes the camera may allocate
|
||||
fn valid_size(size: usize) -> bool {
|
||||
(1..=MAX_PREVIEW_SIZE_PX).contains(&size)
|
||||
}
|
||||
|
||||
/// The rays through `pixel` of a `size²` preview that hit the shape, as (texel index, view-space normal)
|
||||
fn pixel_hits(camera: &OrbCamera, size: usize, pixel: usize) -> impl Iterator<Item = (usize, Vec3)> + '_ {
|
||||
let (x, y) = (pixel % size, pixel / size);
|
||||
(0..SUPERSAMPLE * SUPERSAMPLE).filter_map(move |sub_pixel| {
|
||||
let (sub_x, sub_y) = (sub_pixel % SUPERSAMPLE, sub_pixel / SUPERSAMPLE);
|
||||
let ray = (y * SUPERSAMPLE + sub_y) * camera.rays_per_side + x * SUPERSAMPLE + sub_x;
|
||||
camera.samples.get(ray).copied().flatten()
|
||||
})
|
||||
}
|
||||
|
||||
/// The material values at `texels`, compositing only the tiles that hold them
|
||||
fn material_at(session: &Session, texels: &[(u32, u32)]) -> Option<Vec<Sample>> {
|
||||
let tiles: BTreeSet<(u32, u32)> = texels.iter().map(|(x, y)| (x / TILE, y / TILE)).collect();
|
||||
let tiles: Vec<(u32, u32)> = tiles.into_iter().collect();
|
||||
|
||||
session.with_inputs(SET, |inputs| {
|
||||
let mut composite = texturecraft_compose::Composite::new(&MATERIAL_CHANNELS, TEXTURE_PX);
|
||||
texturecraft_compose::composite_tiles(inputs, &mut composite, &tiles);
|
||||
|
||||
let samples = texels
|
||||
.iter()
|
||||
.map(|&(x, y)| {
|
||||
let [base, metallic, roughness, height] = MATERIAL_CHANNELS.map(|channel| composite.value(channel, x, y));
|
||||
Sample { base, metallic: metallic[0], roughness: roughness[0], height: height[0] }
|
||||
})
|
||||
.collect();
|
||||
Some(samples)
|
||||
})
|
||||
}
|
||||
|
||||
/// Cache one camera per preview size, evicting the least recently used view
|
||||
fn camera_for<'a>(cameras: &'a mut Vec<OrbCamera>, session: &Session, size: usize) -> Option<&'a OrbCamera> {
|
||||
let rays_per_side = size * SUPERSAMPLE;
|
||||
let camera = match cameras.iter().position(|camera| camera.rays_per_side == rays_per_side) {
|
||||
Some(index) => cameras.remove(index),
|
||||
None => OrbCamera::new(session, TEXTURE_PX, rays_per_side),
|
||||
};
|
||||
if cameras.len() >= CAMERAS_KEPT {
|
||||
cameras.remove(0);
|
||||
}
|
||||
|
||||
cameras.push(camera);
|
||||
cameras.last()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Mean absolute difference of the masks of two previews over the pixels both see
|
||||
fn difference(a: &[Option<MaskPreviewPixel>], b: &[Option<MaskPreviewPixel>]) -> f32 {
|
||||
let pairs: Vec<(f32, f32)> = a.iter().zip(b).filter_map(|(a, b)| Some((a.as_ref()?.mask, b.as_ref()?.mask))).collect();
|
||||
pairs.iter().map(|(a, b)| (a - b).abs()).sum::<f32>() / pairs.len().max(1) as f32
|
||||
}
|
||||
|
||||
/// Mean mask value over the pixels a preview sees
|
||||
fn mean_mask(pixels: &[Option<MaskPreviewPixel>]) -> f32 {
|
||||
pixels.iter().flatten().map(|pixel| pixel.mask).sum::<f32>() / pixels.iter().flatten().count().max(1) as f32
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_preview_sizes_are_rejected_before_changing_the_shape() {
|
||||
let session = Session::new_project("Orb preview", primitives::cube(2.0), "builtin:cube", None, 128).unwrap();
|
||||
let layer = session.doc.project.texture_set(SET).unwrap().stack[0];
|
||||
let bare = (session.doc.clone(), session.selected.clone());
|
||||
let mut preview = OrbPreview { session, layer, bare, cameras: Vec::new() };
|
||||
let stack_size = preview.session.doc.project.texture_set(SET).unwrap().stack.len();
|
||||
for size in [0, MAX_PREVIEW_SIZE_PX + 1, usize::MAX / 2 + 1, usize::MAX] {
|
||||
assert!(preview.mask("edges_sharp", size).is_none(), "size {size} should be rejected before rendering");
|
||||
assert!(preview.material("steel_painted_worn", size).is_none(), "size {size} should be rejected before rendering");
|
||||
assert!(preview.cameras.is_empty(), "invalid sizes must not allocate a camera");
|
||||
assert!(preview.session.doc.project.layer(layer).unwrap().mask.is_none(), "invalid sizes must not apply a mask");
|
||||
assert_eq!(preview.session.doc.project.texture_set(SET).unwrap().stack.len(), stack_size, "invalid sizes must not apply a material");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn smart_mask_previews_are_in_range_tell_edges_from_cavities_and_render_at_any_size() {
|
||||
let size = 24;
|
||||
let mut preview = OrbPreview::new().unwrap();
|
||||
for smart_mask in crate::smart_masks::SMART_MASKS {
|
||||
let id = smart_mask.id;
|
||||
let pixels = preview.mask(id, size).unwrap_or_else(|| panic!("{id}"));
|
||||
assert_eq!(pixels.len(), size * size, "{id}");
|
||||
assert!(pixels[0].is_none(), "{id}: the corners are outside the shape");
|
||||
|
||||
let seen: Vec<&MaskPreviewPixel> = pixels.iter().flatten().collect();
|
||||
assert!(seen.len() > size * size / 3, "{id}: the shape fills the frame");
|
||||
for pixel in seen {
|
||||
assert!((0.0..=1.0).contains(&pixel.mask) && (0.0..=1.0).contains(&pixel.coverage) && pixel.coverage > 0.0, "{id}: {pixel:?}");
|
||||
assert!(pixel.normal.is_finite(), "{id}: {pixel:?}");
|
||||
}
|
||||
}
|
||||
|
||||
let (edges, cavities) = (preview.mask("edges_sharp", size).unwrap(), preview.mask("dirt_cavities", size).unwrap());
|
||||
let shows = |pixels: &[Option<MaskPreviewPixel>]| pixels.iter().flatten().any(|pixel| pixel.mask > 0.5);
|
||||
assert!(shows(&edges) && shows(&cavities), "both masks find something on the shape");
|
||||
assert!(difference(&edges, &cavities) > 0.05, "edges and cavities differ: {}", difference(&edges, &cavities));
|
||||
assert!(preview.mask("nope", size).is_none());
|
||||
|
||||
// The same bake renders other sizes, showing the same mask
|
||||
let big = preview.mask("edges_sharp", size * 3).unwrap();
|
||||
assert_eq!(big.len(), size * size * 9);
|
||||
assert!((mean_mask(&big) - mean_mask(&edges)).abs() < 0.05, "{} vs {}", mean_mask(&big), mean_mask(&edges));
|
||||
|
||||
preview.mask("edges_sharp", size * 2).unwrap();
|
||||
assert_eq!(preview.cameras.len(), CAMERAS_KEPT, "only the most recent sizes keep their camera");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn smart_materials_render_on_the_orb_and_show_their_wear() {
|
||||
let size = 24;
|
||||
let mut preview = OrbPreview::new().unwrap();
|
||||
for material in materials::MATERIALS.iter().filter(|material| material.smart) {
|
||||
let id = material.id;
|
||||
let pixels = preview.material(id, size).unwrap_or_else(|| panic!("{id}"));
|
||||
assert_eq!(pixels.len(), size * size, "{id}");
|
||||
assert!(pixels[0].is_none(), "{id}: the corners are outside the shape");
|
||||
|
||||
for pixel in pixels.iter().flatten() {
|
||||
let sample = pixel.sample;
|
||||
let values = sample.base.into_iter().chain([sample.metallic, sample.roughness, sample.height]);
|
||||
assert!(values.into_iter().all(f32::is_finite), "{id}: {pixel:?}");
|
||||
assert!(pixel.normal.is_finite() && pixel.coverage > 0.0, "{id}: {pixel:?}");
|
||||
}
|
||||
}
|
||||
assert!(preview.material("nope", size).is_none());
|
||||
|
||||
// Paint chipped at the edges shows the steel under it: the smart material is not its base
|
||||
let (worn, steel) = (preview.material("steel_painted_worn", size).unwrap(), preview.material("steel", size).unwrap());
|
||||
let metallic_pixels = |pixels: &[Option<MaterialPreviewPixel>]| pixels.iter().flatten().filter(|pixel| pixel.sample.metallic > 0.5).count();
|
||||
let (worn_metallic, steel_metallic) = (metallic_pixels(&worn), metallic_pixels(&steel));
|
||||
assert!(worn_metallic > 0 && worn_metallic < steel_metallic / 2, "bare steel only at the worn edges: {worn_metallic} of {steel_metallic}");
|
||||
|
||||
let base_colors = |pixels: &[Option<MaterialPreviewPixel>]| pixels.iter().flatten().map(|pixel| pixel.sample.base).collect::<Vec<_>>();
|
||||
assert_ne!(base_colors(&worn), base_colors(&steel));
|
||||
|
||||
// Each material starts from the bare orb: rendering another one in between changes nothing
|
||||
preview.material("iron_rusted", size).unwrap();
|
||||
assert_eq!(preview.material("steel_painted_worn", size).unwrap(), worn);
|
||||
}
|
||||
}
|
||||
+93
-137
@@ -7,13 +7,23 @@ use texturecraft_compose::PaintTarget;
|
||||
use texturecraft_core::{Channel, Effect, EffectKind, LayerId, LayerKind, Mask, MaskBackground};
|
||||
use texturecraft_geom::glam::Vec2;
|
||||
use texturecraft_paint::{
|
||||
CommitSource, EyeDepth, PickCtx, Pickup, PickupMode, RasterCtx, Shape, Staging, Stroke, StrokeCanvas, SurfaceHit, commit_layer, commit_mask,
|
||||
fill_triangles, pick, rasterize,
|
||||
CommitSource, EyeDepth, PickCtx, Pickup, PickupMode, RasterCtx, Shape, Staging, Stroke, StrokeCanvas, SurfaceHit, commit_layer, commit_mask, pick,
|
||||
rasterize,
|
||||
};
|
||||
|
||||
use crate::session::{ActiveStroke, CloneFrom, FillMode, Session, StackTarget, Tool};
|
||||
use crate::session::{ActiveStroke, CloneFrom, Session, StackTarget, Tool};
|
||||
use crate::uv_stroke_state::UvStrokeState;
|
||||
use crate::{EngineError, Result};
|
||||
|
||||
/// Shortest distance between 2D view stamps, so a stamp with no radius (a pen at zero pressure) can't stall a stroke.
|
||||
const MIN_UV_STAMP_STEP: f32 = 1e-5;
|
||||
|
||||
/// 2D view stamps rasterized together, bounding the memory of one batch.
|
||||
const UV_STAMP_BATCH: usize = 4096;
|
||||
|
||||
/// Covers a UV diagonal at the minimum step (about 142k stamps), including light pen pressure, while bounding hostile coordinates
|
||||
const MAX_UV_STAMPS_PER_SAMPLE: usize = 150_000;
|
||||
|
||||
impl Session {
|
||||
/// Camera visibility for a stroke at `viewport` (cached until the camera, size or mesh change).
|
||||
fn eye_depth(&mut self, viewport: Vec2) -> std::sync::Arc<EyeDepth> {
|
||||
@@ -35,6 +45,16 @@ impl Session {
|
||||
pick(&ctx, screen)
|
||||
}
|
||||
|
||||
/// The texture set that paints mesh material `material` (a [`SurfaceHit::material`])
|
||||
pub fn texture_set_of_material(&self, material: usize) -> Option<usize> {
|
||||
self.doc.project.texture_sets.iter().position(|t| t.material == material)
|
||||
}
|
||||
|
||||
/// The texture set of the surface under viewport pixel `screen`
|
||||
pub fn texture_set_at(&self, screen: Vec2, viewport: Vec2) -> Option<usize> {
|
||||
self.pick(screen, viewport).and_then(|hit| self.texture_set_of_material(hit.material))
|
||||
}
|
||||
|
||||
/// Resolve what a stroke on the selected layer paints into, creating the mask paint effect
|
||||
/// when painting a mask. Must run inside the stroke's history snapshot.
|
||||
fn paint_target(&mut self) -> Result<PaintTarget> {
|
||||
@@ -224,7 +244,7 @@ impl Session {
|
||||
stroke,
|
||||
canvas,
|
||||
depth,
|
||||
uv: uv_mode.then_some((None, 0.0)),
|
||||
uv: uv_mode.then(UvStrokeState::default),
|
||||
camera: self.camera,
|
||||
viewport,
|
||||
values,
|
||||
@@ -291,12 +311,15 @@ impl Session {
|
||||
Ok(self.continue_stroke(screen, pressure))
|
||||
}
|
||||
|
||||
/// Start a stroke in the 2D view at texture coordinate `uv`.
|
||||
/// Start a stroke in the 2D view at texture coordinate `uv` (polygon fill fills there).
|
||||
pub fn begin_stroke_uv(&mut self, uv: Vec2, pressure: f32) -> Result<()> {
|
||||
self.cancel_stroke();
|
||||
if matches!(self.tool.tool, Tool::PolygonFill | Tool::ColorPicker | Tool::GeometryMask) {
|
||||
return Err(EngineError::Other("use this tool in the 3D view".into()));
|
||||
match self.tool.tool {
|
||||
Tool::PolygonFill => return self.polygon_fill_uv(uv).map(|_| ()),
|
||||
Tool::ColorPicker | Tool::GeometryMask => return Err(EngineError::Other("use this tool in the 3D view".into())),
|
||||
_ => {}
|
||||
}
|
||||
|
||||
self.start_stroke(self.viewport, true, Some(uv))?;
|
||||
self.continue_stroke_uv(uv, pressure);
|
||||
Ok(())
|
||||
@@ -304,40 +327,49 @@ impl Session {
|
||||
|
||||
/// Add a 2D view sample (texture coordinates). Brush size is relative to the UV square.
|
||||
pub fn continue_stroke_uv(&mut self, uv: Vec2, pressure: f32) {
|
||||
let Some(st) = self.stroke.as_mut() else { return };
|
||||
let Some((last, carry)) = st.uv.as_mut() else { return };
|
||||
let Some(cache) = self.caches.get_mut(st.ts) else { return };
|
||||
let b = &st.stroke.settings;
|
||||
let p = pressure.clamp(0.0, 1.0);
|
||||
let radius = b.size * 2.0 * if p < 1.0 { b.min_size + (1.0 - b.min_size) * p } else { 1.0 };
|
||||
let step = (b.spacing * 2.0 * radius).max(1e-5);
|
||||
let mut points = Vec::new();
|
||||
match *last {
|
||||
None => points.push(uv),
|
||||
Some(prev) => {
|
||||
let seg = uv - prev;
|
||||
let len = seg.length();
|
||||
let mut t = step - *carry;
|
||||
while t <= len && points.len() < 4096 {
|
||||
points.push(prev + seg * (t / len.max(1e-9)));
|
||||
t += step;
|
||||
}
|
||||
*carry = len - (t - step);
|
||||
}
|
||||
}
|
||||
// Follow path: turn the stamp with the stroke direction (y up on screen, v grows down).
|
||||
let angle = match *last {
|
||||
Some(prev) if b.follow_path && uv != prev => b.angle + (prev.y - uv.y).atan2(uv.x - prev.x).to_degrees() - 90.0,
|
||||
_ => b.angle,
|
||||
let Some(active) = self.stroke.as_mut() else { return };
|
||||
let Some(progress) = active.uv.as_mut() else { return };
|
||||
let Some(cache) = self.caches.get_mut(active.ts) else { return };
|
||||
|
||||
let settings = &active.stroke.settings;
|
||||
let pressure = pressure.clamp(0.0, 1.0);
|
||||
let size_scale = if pressure < 1.0 { settings.min_size + (1.0 - settings.min_size) * pressure } else { 1.0 };
|
||||
let radius = settings.size * 2.0 * size_scale;
|
||||
let step = (settings.spacing * 2.0 * radius).max(MIN_UV_STAMP_STEP);
|
||||
|
||||
// Follow path: turn the stamp with the stroke direction (y up on screen, v grows down)
|
||||
let angle = match progress.last {
|
||||
Some(previous) if settings.follow_path && uv != previous => settings.angle + (previous.y - uv.y).atan2(uv.x - previous.x).to_degrees() - 90.0,
|
||||
_ => settings.angle,
|
||||
};
|
||||
*last = Some(uv);
|
||||
let n0 = st.stroke.stamps.len() as u32;
|
||||
let stamps: Vec<texturecraft_paint::UvStamp> = points
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, c)| texturecraft_paint::UvStamp { center: *c, radius, angle, flow: b.flow, hardness: b.hardness, seed: n0 + i as u32 })
|
||||
.collect();
|
||||
texturecraft_paint::rasterize_uv(&mut st.canvas, &cache.gbuf, Self::shape(&self.images, b), &stamps);
|
||||
|
||||
// The first sample is one stamp; a later one stamps every `step` along the segment from the previous
|
||||
let (start, segment, mut distance) = match progress.last.replace(uv) {
|
||||
None => (uv, Vec2::ZERO, 0.0),
|
||||
// Pressure can shrink the step below the carry from the preceding sample
|
||||
Some(previous) => (previous, uv - previous, (step - progress.carry).max(0.0)),
|
||||
};
|
||||
let length = segment.length();
|
||||
let shape = Self::shape(&self.images, settings);
|
||||
let mut batch = Vec::new();
|
||||
let mut stamped = 0;
|
||||
while distance <= length && stamped < MAX_UV_STAMPS_PER_SAMPLE {
|
||||
let batch_size = UV_STAMP_BATCH.min(MAX_UV_STAMPS_PER_SAMPLE - stamped);
|
||||
batch.clear();
|
||||
while distance <= length && batch.len() < batch_size {
|
||||
let center = start + segment * (distance / length.max(f32::MIN_POSITIVE));
|
||||
let seed = progress.stamps.wrapping_add((stamped + batch.len()) as u32);
|
||||
batch.push(texturecraft_paint::UvStamp { center, radius, angle, flow: settings.flow, hardness: settings.hardness, seed });
|
||||
distance += step;
|
||||
}
|
||||
|
||||
stamped += batch.len();
|
||||
texturecraft_paint::rasterize_uv(&mut active.canvas, &cache.gbuf, shape, &batch);
|
||||
}
|
||||
|
||||
// At most one step, so a segment cut off at the stamp limit can't push the next one's stamps backwards
|
||||
progress.carry = (length - (distance - step)).min(step);
|
||||
progress.stamps = progress.stamps.wrapping_add(stamped as u32);
|
||||
self.stroke_painted();
|
||||
}
|
||||
|
||||
@@ -472,21 +504,6 @@ impl Session {
|
||||
Ok(tiles)
|
||||
}
|
||||
|
||||
/// Polygon fill: fill the triangle / UV island / whole mesh under `screen`.
|
||||
pub fn polygon_fill(&mut self, screen: Vec2, viewport: Vec2) -> Result<usize> {
|
||||
let hit = self.pick(screen, viewport).ok_or_else(|| EngineError::Other("nothing under the cursor".into()))?;
|
||||
let ts = self.ts();
|
||||
let material = self.doc.project.texture_set(ts)?.material;
|
||||
if hit.material != material {
|
||||
return Err(EngineError::Other("that surface belongs to another texture set".into()));
|
||||
}
|
||||
let tris = self.fill_set(hit.tri, material);
|
||||
let (gbuf, mut canvas) = self.fill_canvas(ts)?;
|
||||
fill_triangles(&mut canvas, &gbuf, &tris);
|
||||
self.commit_fill("Polygon fill", ts, &canvas)?;
|
||||
Ok(tris.len())
|
||||
}
|
||||
|
||||
/// The G-buffer of texture set `ts` and an empty canvas for a one-shot fill, limited by the
|
||||
/// quick mask unless the fill edits it.
|
||||
pub(crate) fn fill_canvas(&self, ts: usize) -> Result<(std::sync::Arc<texturecraft_geom::UvGBuffer>, StrokeCanvas)> {
|
||||
@@ -500,67 +517,37 @@ impl Session {
|
||||
|
||||
/// Commit a one-shot fill with the tool's material (one undo step), or into the quick mask.
|
||||
pub(crate) fn commit_fill(&mut self, label: &str, ts: usize, canvas: &StrokeCanvas) -> Result<()> {
|
||||
let size = (canvas.alpha.width(), canvas.alpha.height());
|
||||
let src = |opacity| CommitSource { alpha: &canvas.alpha, tiles: &canvas.dirty, opacity, erase: false, per_texel: None, carried: None };
|
||||
if self.quick_mask.editing {
|
||||
self.commit_quick_mask(ts, size, src(self.tool.brush.opacity));
|
||||
return Ok(());
|
||||
return self.paint_fill(ts, canvas);
|
||||
}
|
||||
self.edit(label, |s| {
|
||||
let target = s.paint_target()?;
|
||||
let values = s.stroke_values(target);
|
||||
match target {
|
||||
PaintTarget::Layer(id) => commit_layer(&mut s.doc.pixels, id, size, &values, src(s.tool.brush.opacity), &mut Staging::default()),
|
||||
PaintTarget::Mask(eid) => commit_mask(&mut s.doc.pixels, eid, size, s.tool.mask_value, src(s.tool.brush.opacity), &mut Staging::default()),
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
|
||||
// Each fill is its own step, never merged into a box drag's step of the same label
|
||||
self.edit_merging(label, false, |session| session.paint_fill(ts, canvas))
|
||||
}
|
||||
|
||||
/// Triangles filled by the current fill mode starting from `tri`.
|
||||
fn fill_set(&self, tri: u32, material: usize) -> BTreeSet<u32> {
|
||||
let m = &self.mesh;
|
||||
match self.tool.fill_mode {
|
||||
FillMode::Triangle => [tri].into_iter().collect(),
|
||||
FillMode::Mesh => m.triangles_of(material).map(|t| t as u32).collect(),
|
||||
FillMode::UvIsland => {
|
||||
// Triangles sharing an edge in UV space form a UV island: imported meshes often
|
||||
// split vertices along hard edges (or per face) where the UVs run on, so shared
|
||||
// vertex indices alone break an island into its polygons.
|
||||
let corner = |i: usize| m.uvs.get(i).map(|uv| [(uv.x * 1e5).round() as i64, (uv.y * 1e5).round() as i64]);
|
||||
let edges = |t: usize| match m.tri(t).map(|v| v.map(corner)) {
|
||||
Some([Some(a), Some(b), Some(c)]) => [(a, b), (b, c), (c, a)].map(|(p, q)| (p.min(q), p.max(q))).to_vec(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let mut by_edge: BTreeMap<_, Vec<u32>> = BTreeMap::new();
|
||||
for t in m.triangles_of(material) {
|
||||
for e in edges(t) {
|
||||
by_edge.entry(e).or_default().push(t as u32);
|
||||
}
|
||||
}
|
||||
let mut seen = BTreeSet::new();
|
||||
let mut stack = vec![tri];
|
||||
while let Some(t) = stack.pop() {
|
||||
if !seen.insert(t) {
|
||||
continue;
|
||||
}
|
||||
for e in edges(t as usize) {
|
||||
for n in by_edge.get(&e).map(Vec::as_slice).unwrap_or(&[]) {
|
||||
if !seen.contains(n) {
|
||||
stack.push(*n);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
seen
|
||||
}
|
||||
/// Paint a one-shot fill with the tool's material into the paint target, or into the quick mask while it is edited (no undo step)
|
||||
pub(crate) fn paint_fill(&mut self, ts: usize, canvas: &StrokeCanvas) -> Result<()> {
|
||||
let size = (canvas.alpha.width(), canvas.alpha.height());
|
||||
let opacity = self.tool.brush.opacity;
|
||||
let source = CommitSource { alpha: &canvas.alpha, tiles: &canvas.dirty, opacity, erase: false, per_texel: None, carried: None };
|
||||
if self.quick_mask.editing {
|
||||
self.commit_quick_mask(ts, size, source);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let target = self.paint_target()?;
|
||||
let values = self.stroke_values(target);
|
||||
match target {
|
||||
PaintTarget::Layer(id) => commit_layer(&mut self.doc.pixels, id, size, &values, source, &mut Staging::default()),
|
||||
PaintTarget::Mask(effect) => commit_mask(&mut self.doc.pixels, effect, size, self.tool.mask_value, source, &mut Staging::default()),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Color picker: copy the material under the cursor into the tool's paint values.
|
||||
pub fn color_pick(&mut self, screen: Vec2, viewport: Vec2) -> Result<BTreeMap<Channel, [f32; 3]>> {
|
||||
let hit = self.pick(screen, viewport).ok_or_else(|| EngineError::Other("nothing under the cursor".into()))?;
|
||||
let ts = self.doc.project.texture_sets.iter().position(|t| t.material == hit.material).unwrap_or(self.ts());
|
||||
let ts = self.texture_set_of_material(hit.material).unwrap_or(self.ts());
|
||||
let cache = self.caches.get(ts).ok_or_else(|| EngineError::Other("texture set not ready".into()))?;
|
||||
let (w, h) = (cache.size.0 as f32, cache.size.1 as f32);
|
||||
let (x, y) = ((hit.uv.x * w).clamp(0.0, w - 1.0) as u32, (hit.uv.y * h).clamp(0.0, h - 1.0) as u32);
|
||||
@@ -617,34 +604,3 @@ fn with_commit_source<R>(
|
||||
let carried = st.canvas.pickup.as_ref().map(|p| &p.values);
|
||||
f(CommitSource { alpha: &st.canvas.alpha, tiles, opacity: st.stroke.settings.opacity, erase: st.erase, per_texel, carried })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use texturecraft_geom::glam::{Vec2, Vec3};
|
||||
use texturecraft_geom::mesh::Mesh;
|
||||
use texturecraft_geom::primitives;
|
||||
|
||||
use crate::session::{FillMode, Session};
|
||||
|
||||
#[test]
|
||||
fn uv_island_fill_follows_uvs_across_split_vertices() {
|
||||
// Two copies of a plane, each triangle with its own three vertices (as hard edges or
|
||||
// per-face imports leave a mesh), the second copy apart in UV space.
|
||||
let plane = primitives::plane(2.0, 4);
|
||||
let (mut positions, mut uvs) = (Vec::<Vec3>::new(), Vec::<Vec2>::new());
|
||||
for shift in [0.0, 0.5] {
|
||||
for i in plane.indices.iter().map(|i| *i as usize) {
|
||||
positions.push(plane.positions[i] + Vec3::Y * shift);
|
||||
uvs.push(plane.uvs[i] * 0.5 + shift);
|
||||
}
|
||||
}
|
||||
let indices = (0..positions.len() as u32).collect();
|
||||
let mesh = Mesh::from_parts(positions, None, uvs, indices, "m").unwrap();
|
||||
let n = plane.triangle_count();
|
||||
assert_eq!(mesh.vertex_count(), 6 * n, "no vertex is shared");
|
||||
let mut s = Session::new_project("t", mesh, "test", None, 128).unwrap();
|
||||
s.tool.fill_mode = FillMode::UvIsland;
|
||||
assert_eq!(s.fill_set(0, 0).len(), n, "the whole first island");
|
||||
assert_eq!(s.fill_set(n as u32, 0).len(), n, "only the second island");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,607 @@
|
||||
//! Polygon fill: fill the triangles, polygons, UV islands or connected meshes under a click or inside a dragged box, in either view.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::collections::{BTreeSet, HashSet};
|
||||
|
||||
use texturecraft_geom::glam::Vec2;
|
||||
use texturecraft_geom::{Mesh, NO_TRI};
|
||||
use texturecraft_paint::{EyeDepth, fill_triangles, screen_point};
|
||||
|
||||
use crate::fill_mode::FillMode;
|
||||
use crate::polygon_fill_drag::PolygonFillDrag;
|
||||
use crate::session::Session;
|
||||
use crate::triangle_partition::TrianglePartition;
|
||||
use crate::{EngineError, Result};
|
||||
|
||||
/// Corners closer than one step of this grid (per unit of position or UV) count as the same corner
|
||||
const CORNER_GRID_STEPS: f32 = 1e5;
|
||||
|
||||
impl Session {
|
||||
/// Fill the triangle / polygon / UV island / connected mesh under viewport pixel `screen`
|
||||
pub fn polygon_fill(&mut self, screen: Vec2, viewport: Vec2) -> Result<usize> {
|
||||
let hit = self.pick(screen, viewport).ok_or_else(|| EngineError::Other("nothing under the cursor".into()))?;
|
||||
if hit.material != self.fill_material()? {
|
||||
return Err(EngineError::Other("that surface belongs to another texture set".into()));
|
||||
}
|
||||
|
||||
self.fill_group_of(hit.tri)
|
||||
}
|
||||
|
||||
/// Fill like [`Session::polygon_fill`] at texture coordinate `uv` (the 2D view): the triangle covering that texel's center, so slivers thinner than a texel can't be clicked
|
||||
pub fn polygon_fill_uv(&mut self, uv: Vec2) -> Result<usize> {
|
||||
let gbuf = self.caches.get(self.ts()).map(|cache| cache.gbuf.clone()).ok_or_else(|| EngineError::Other("texture set not ready".into()))?;
|
||||
let size = Vec2::new(gbuf.width as f32, gbuf.height as f32);
|
||||
let texel = (uv * size).floor();
|
||||
let triangle = (texel.cmpge(Vec2::ZERO).all() && texel.cmplt(size).all())
|
||||
.then(|| gbuf.tri.get(texel.y as usize * gbuf.width as usize + texel.x as usize).copied())
|
||||
.flatten()
|
||||
.filter(|triangle| *triangle != NO_TRI)
|
||||
.ok_or_else(|| EngineError::Other("nothing under the cursor".into()))?;
|
||||
|
||||
self.fill_group_of(triangle)
|
||||
}
|
||||
|
||||
/// Fill what the box between viewport pixels `corner` and `opposite` selects (one undo step)
|
||||
pub fn polygon_fill_box(&mut self, corner: Vec2, opposite: Vec2, viewport: Vec2) -> Result<usize> {
|
||||
// A scripted box stands alone: it finishes any drag under way, and ends even when it fails
|
||||
self.end_polygon_fill_box();
|
||||
let shown = self.drag_polygon_fill_box(corner, opposite, viewport);
|
||||
let filled = self.end_polygon_fill_box();
|
||||
shown.map(|_| filled)
|
||||
}
|
||||
|
||||
/// Fill what the box between texture coordinates `corner` and `opposite` selects (the 2D view, one undo step)
|
||||
pub fn polygon_fill_box_uv(&mut self, corner: Vec2, opposite: Vec2) -> Result<usize> {
|
||||
self.end_polygon_fill_box();
|
||||
let shown = self.drag_polygon_fill_box_uv(corner, opposite);
|
||||
let filled = self.end_polygon_fill_box();
|
||||
shown.map(|_| filled)
|
||||
}
|
||||
|
||||
/// Show the fill of a box being dragged between viewport pixels `corner` and `opposite`
|
||||
pub fn drag_polygon_fill_box(&mut self, corner: Vec2, opposite: Vec2, viewport: Vec2) -> Result<usize> {
|
||||
// Whole pixels, as the visibility buffer is rendered at
|
||||
self.drag_polygon_fill(corner, opposite, Some(viewport.round().max(Vec2::ONE)))
|
||||
}
|
||||
|
||||
/// Show the fill of a box being dragged between texture coordinates `corner` and `opposite` (the 2D view)
|
||||
pub fn drag_polygon_fill_box_uv(&mut self, corner: Vec2, opposite: Vec2) -> Result<usize> {
|
||||
self.drag_polygon_fill(corner, opposite, None)
|
||||
}
|
||||
|
||||
/// Finish the dragged box: what it filled becomes one undo step. Returns the filled triangle count
|
||||
pub fn end_polygon_fill_box(&mut self) -> usize {
|
||||
let Some(drag) = self.polygon_fill_drag.take() else { return 0 };
|
||||
|
||||
let filled = drag.filled.len();
|
||||
// Quick mask edits keep no history, as with its strokes
|
||||
if filled > 0 && drag.quick_mask_before.is_none() {
|
||||
self.push_history("Polygon fill", drag.before);
|
||||
}
|
||||
filled
|
||||
}
|
||||
|
||||
/// Show the fill of a box from `corner` to `opposite` in the 3D view of size `viewport`, or in the 2D view when None
|
||||
fn drag_polygon_fill(&mut self, corner: Vec2, opposite: Vec2, viewport: Option<Vec2>) -> Result<usize> {
|
||||
if !corner.is_finite() || !opposite.is_finite() {
|
||||
return Err(EngineError::Other("the box corners must be finite".into()));
|
||||
}
|
||||
|
||||
let (low, high) = (corner.min(opposite), corner.max(opposite));
|
||||
self.start_polygon_fill_drag(viewport)?;
|
||||
let Some(drag) = self.polygon_fill_drag.as_mut() else { return Ok(0) };
|
||||
|
||||
if drag.failed || drag.last_box == Some((low, high)) {
|
||||
return Ok(drag.filled.len());
|
||||
}
|
||||
|
||||
drag.last_box = Some((low, high));
|
||||
let selected = self.box_selection(low, high);
|
||||
self.show_box_fill(selected)
|
||||
}
|
||||
|
||||
/// Continue a box drag only while its view, paint target and quick mask state still match
|
||||
fn start_polygon_fill_drag(&mut self, viewport: Option<Vec2>) -> Result<()> {
|
||||
let ts = self.ts();
|
||||
let target = (self.selected_layer(), self.target);
|
||||
let quick_mask = self.quick_mask.editing;
|
||||
// Finish the old target before another preview can restore its earlier document snapshot
|
||||
if let Some(drag) = &self.polygon_fill_drag {
|
||||
if drag.ts == ts && drag.target == target && drag.viewport == viewport && drag.quick_mask_before.is_some() == quick_mask {
|
||||
// A camera move (a wheel zoom mid-drag) keeps the drag, which then sees the mesh from the new camera
|
||||
if drag.camera != self.camera {
|
||||
let (points, depth) = self.box_space(viewport);
|
||||
if let Some(drag) = self.polygon_fill_drag.as_mut() {
|
||||
(drag.points, drag.depth, drag.camera, drag.last_box) = (points, depth, self.camera, None);
|
||||
}
|
||||
}
|
||||
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
self.end_polygon_fill_box();
|
||||
}
|
||||
|
||||
let material = self.fill_material()?;
|
||||
let (points, depth) = self.box_space(viewport);
|
||||
let polygons = match self.tool.fill_mode {
|
||||
FillMode::Triangle | FillMode::Polygon => None,
|
||||
FillMode::UvIsland | FillMode::Mesh => Some(TrianglePartition::new(&self.mesh, material, polygon_edges)),
|
||||
};
|
||||
self.polygon_fill_drag = Some(PolygonFillDrag {
|
||||
ts,
|
||||
target,
|
||||
viewport,
|
||||
camera: self.camera,
|
||||
before: self.doc.clone(),
|
||||
quick_mask_before: quick_mask.then(|| self.quick_mask.masks.clone()),
|
||||
points,
|
||||
depth,
|
||||
fill_groups: self.fill_partition(material),
|
||||
polygons,
|
||||
filled: BTreeSet::new(),
|
||||
last_box: None,
|
||||
failed: false,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Each vertex where a box sees it (viewport pixels for a 3D view of size `viewport`, else texture coordinates) and, for visible polygons only in 3D, what the camera sees
|
||||
fn box_space(&self, viewport: Option<Vec2>) -> (Vec<Option<Vec2>>, Option<EyeDepth>) {
|
||||
let Some(size) = viewport else { return (self.mesh.uvs.iter().copied().map(Some).collect(), None) };
|
||||
|
||||
let view_proj = self.camera.view_proj(size.x / size.y);
|
||||
let points = self.mesh.positions.iter().map(|position| screen_point(view_proj, *position, size)).collect();
|
||||
let depth = self.tool.fill_visible_only.then(|| EyeDepth::render_with_triangles(&self.shown_mesh(), &self.camera, size.x as u32, size.y as u32));
|
||||
(points, depth)
|
||||
}
|
||||
|
||||
/// The mesh material of the texture set being painted
|
||||
fn fill_material(&self) -> Result<usize> {
|
||||
Ok(self.doc.project.texture_set(self.ts())?.material)
|
||||
}
|
||||
|
||||
/// The triangles the current fill mode fills together, for `material`
|
||||
fn fill_partition(&self, material: usize) -> TrianglePartition {
|
||||
match self.tool.fill_mode {
|
||||
FillMode::Triangle => TrianglePartition::new(&self.mesh, material, |_, _| Vec::<u32>::new()),
|
||||
FillMode::Polygon => TrianglePartition::new(&self.mesh, material, polygon_edges),
|
||||
FillMode::UvIsland => TrianglePartition::new(&self.mesh, material, uv_edges),
|
||||
FillMode::Mesh => TrianglePartition::new(&self.mesh, material, position_edges),
|
||||
}
|
||||
}
|
||||
|
||||
/// Fill the fill-mode group holding `triangle` (one undo step)
|
||||
fn fill_group_of(&mut self, triangle: u32) -> Result<usize> {
|
||||
let ts = self.ts();
|
||||
let groups = self.fill_partition(self.fill_material()?);
|
||||
let triangles: BTreeSet<u32> = groups.group(triangle).unwrap_or_default().iter().copied().collect();
|
||||
|
||||
let (gbuf, mut canvas) = self.fill_canvas(ts)?;
|
||||
fill_triangles(&mut canvas, &gbuf, &triangles);
|
||||
self.commit_fill("Polygon fill", ts, &canvas)?;
|
||||
Ok(triangles.len())
|
||||
}
|
||||
|
||||
/// The mesh as the 3D view shows it: hidden texture sets' triangles collapse to a point, so nothing behind them counts as hidden
|
||||
fn shown_mesh(&self) -> Cow<'_, Mesh> {
|
||||
let sets = &self.doc.project.texture_sets;
|
||||
if sets.iter().all(|set| set.visible) {
|
||||
return Cow::Borrowed(&self.mesh);
|
||||
}
|
||||
|
||||
let mut mesh = (*self.mesh).clone();
|
||||
for set in sets.iter().filter(|set| !set.visible) {
|
||||
for triangle in self.mesh.triangles_of(set.material) {
|
||||
if let Some(corners) = mesh.indices.get_mut(triangle * 3..triangle * 3 + 3) {
|
||||
let first = corners[0];
|
||||
corners.fill(first);
|
||||
}
|
||||
}
|
||||
}
|
||||
Cow::Owned(mesh)
|
||||
}
|
||||
|
||||
/// Triangles the dragged box from `low` to `high` fills: each polygon the hit-test selects, grown by the fill mode
|
||||
fn box_selection(&self, low: Vec2, high: Vec2) -> BTreeSet<u32> {
|
||||
let Some(drag) = &self.polygon_fill_drag else { return BTreeSet::new() };
|
||||
|
||||
let visible = drag.depth.as_ref().zip(drag.viewport).map(|(depth, viewport)| visible_triangles(depth, viewport, low, high));
|
||||
let point = |vertex: usize| drag.points.get(vertex).copied().flatten();
|
||||
let corners = |triangle: u32| {
|
||||
let [first, second, third] = self.mesh.tri(triangle as usize)?;
|
||||
Some([point(first)?, point(second)?, point(third)?])
|
||||
};
|
||||
let hit_test = self.tool.fill_hit_test;
|
||||
let mut polygon_corners = Vec::new();
|
||||
let mut groups = BTreeSet::new();
|
||||
for polygon in &drag.polygons.as_ref().unwrap_or(&drag.fill_groups).groups {
|
||||
let seen = visible.as_ref().is_none_or(|visible| polygon.iter().any(|triangle| visible.contains(triangle)));
|
||||
if !seen {
|
||||
continue;
|
||||
}
|
||||
|
||||
polygon_corners.clear();
|
||||
polygon_corners.extend(polygon.iter().map_while(|triangle| corners(*triangle)));
|
||||
if polygon_corners.len() == polygon.len() && hit_test.selects(&polygon_corners, low, high) {
|
||||
groups.extend(polygon.iter().filter_map(|triangle| drag.fill_groups.index_of(*triangle)));
|
||||
}
|
||||
}
|
||||
|
||||
groups.iter().filter_map(|group| drag.fill_groups.groups.get(*group)).flatten().copied().collect()
|
||||
}
|
||||
|
||||
/// Show the box drag's fill of `selected`: the document before the drag, refilled when the selection changed
|
||||
fn show_box_fill(&mut self, selected: BTreeSet<u32>) -> Result<usize> {
|
||||
let Some(drag) = self.polygon_fill_drag.as_mut() else { return Ok(0) };
|
||||
if drag.filled == selected {
|
||||
return Ok(selected.len());
|
||||
}
|
||||
|
||||
let ts = drag.ts;
|
||||
let previous = std::mem::replace(&mut self.doc, drag.before.clone());
|
||||
if let Some(masks) = &drag.quick_mask_before {
|
||||
self.quick_mask.masks = masks.clone();
|
||||
self.quick_mask.revision = self.quick_mask.revision.wrapping_add(1);
|
||||
}
|
||||
|
||||
let painted = if selected.is_empty() {
|
||||
Ok(())
|
||||
} else {
|
||||
self.fill_canvas(ts).and_then(|(gbuf, mut canvas)| {
|
||||
fill_triangles(&mut canvas, &gbuf, &selected);
|
||||
self.paint_fill(ts, &canvas)
|
||||
})
|
||||
};
|
||||
self.invalidate_changed(&previous);
|
||||
|
||||
// A failed fill is reported once and leaves the document as before the drag; the rest of the drag fills nothing
|
||||
let selected_count = selected.len();
|
||||
if let Some(drag) = self.polygon_fill_drag.as_mut() {
|
||||
drag.failed = painted.is_err();
|
||||
drag.filled = if drag.failed { BTreeSet::new() } else { selected };
|
||||
}
|
||||
painted.map(|_| selected_count)
|
||||
}
|
||||
}
|
||||
|
||||
/// Triangles `depth` (rendered for a `viewport` pixel view) shows in the viewport pixels from `low` to `high`, both edges included
|
||||
fn visible_triangles(depth: &EyeDepth, viewport: Vec2, low: Vec2, high: Vec2) -> HashSet<u32> {
|
||||
let depth_pixels_per_viewport_pixel = Vec2::new(depth.width as f32, depth.height as f32) / viewport;
|
||||
let (low, high) = (low * depth_pixels_per_viewport_pixel, high * depth_pixels_per_viewport_pixel);
|
||||
let columns = pixel_span(low.x, high.x, depth.width);
|
||||
let rows = pixel_span(low.y, high.y, depth.height);
|
||||
|
||||
rows.flat_map(|row| depth.triangle.get(row * depth.width as usize..).into_iter().flat_map(|pixels| pixels.iter().take(columns.end).skip(columns.start)))
|
||||
.copied()
|
||||
.filter(|triangle| *triangle != NO_TRI)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The pixels `0..count` a span from `low` to `high` covers, both edges included (empty when it lies outside)
|
||||
fn pixel_span(low: f32, high: f32, count: u32) -> std::ops::Range<usize> {
|
||||
let first = low.floor().clamp(0.0, count as f32) as usize;
|
||||
let end = (high.floor() + 1.0).clamp(0.0, count as f32) as usize;
|
||||
first..end.max(first)
|
||||
}
|
||||
|
||||
/// Texture coordinates of `triangle`'s corners
|
||||
fn uv_corners(mesh: &Mesh, triangle: usize) -> Option<[Vec2; 3]> {
|
||||
let [first, second, third] = mesh.tri(triangle)?;
|
||||
Some([*mesh.uvs.get(first)?, *mesh.uvs.get(second)?, *mesh.uvs.get(third)?])
|
||||
}
|
||||
|
||||
/// The polygon diagonals of `triangle`: edges the importer added to split a polygon
|
||||
fn polygon_edges(mesh: &Mesh, triangle: usize) -> Vec<(u32, u32)> {
|
||||
let hidden = mesh.diagonals.get(triangle).copied().unwrap_or(0);
|
||||
let Some(vertices) = mesh.indices.get(triangle * 3..triangle * 3 + 3) else { return Vec::new() };
|
||||
|
||||
(0..3)
|
||||
.filter(|edge| hidden >> edge & 1 == 1)
|
||||
.map(|edge| {
|
||||
let (from, to) = (vertices[edge], vertices[(edge + 1) % 3]);
|
||||
(from.min(to), from.max(to))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `triangle`'s edges in UV space: imports often split vertices along hard edges where the UVs run on, so vertex indices alone break islands apart
|
||||
fn uv_edges(mesh: &Mesh, triangle: usize) -> Vec<([i64; 2], [i64; 2])> {
|
||||
let corner = |uv: Vec2| (uv * CORNER_GRID_STEPS).round().to_array().map(|step| step as i64);
|
||||
let Some([first, second, third]) = uv_corners(mesh, triangle).map(|uvs| uvs.map(corner)) else { return Vec::new() };
|
||||
|
||||
[(first, second), (second, third), (third, first)].map(|(from, to)| (from.min(to), from.max(to))).to_vec()
|
||||
}
|
||||
|
||||
/// `triangle`'s edges by position: UV seams and hard edges split vertices but leave the geometry connected
|
||||
fn position_edges(mesh: &Mesh, triangle: usize) -> Vec<([i64; 3], [i64; 3])> {
|
||||
let corner = |vertex: usize| mesh.positions.get(vertex).map(|position| (*position * CORNER_GRID_STEPS).round().to_array().map(|step| step as i64));
|
||||
let Some([first, second, third]) = mesh.tri(triangle) else { return Vec::new() };
|
||||
let (Some(first), Some(second), Some(third)) = (corner(first), corner(second), corner(third)) else { return Vec::new() };
|
||||
|
||||
[(first, second), (second, third), (third, first)].map(|(from, to)| (from.min(to), from.max(to))).to_vec()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use texturecraft_core::Channel;
|
||||
use texturecraft_geom::glam::{Vec2, Vec3};
|
||||
use texturecraft_geom::mesh::Mesh;
|
||||
use texturecraft_geom::primitives;
|
||||
|
||||
use crate::fill_hit_test::FillHitTest;
|
||||
use crate::fill_mode::FillMode;
|
||||
use crate::session::{Session, Tool};
|
||||
|
||||
/// The roughness the test fills paint, to tell filled texels apart
|
||||
const FILL_ROUGHNESS: f32 = 0.9;
|
||||
|
||||
/// A polygon fill session on `mesh` painting roughness [`FILL_ROUGHNESS`]
|
||||
fn fill_session(mesh: Mesh) -> Session {
|
||||
let mut session = Session::new_project("t", mesh, "test", None, 128).unwrap();
|
||||
session.viewport = Vec2::new(400.0, 400.0);
|
||||
session.tool.tool = Tool::PolygonFill;
|
||||
session.tool.values.insert(Channel::Roughness, [FILL_ROUGHNESS; 3]);
|
||||
session.update();
|
||||
session
|
||||
}
|
||||
|
||||
/// Whether the texel at texture coordinate `uv` shows the fill's roughness
|
||||
fn filled_at(session: &Session, uv: Vec2) -> bool {
|
||||
let (width, height) = session.caches[0].size;
|
||||
let roughness = session.caches[0].composite.value(Channel::Roughness, (uv.x * width as f32) as u32, (uv.y * height as f32) as u32);
|
||||
(roughness[0] - FILL_ROUGHNESS).abs() < 0.01
|
||||
}
|
||||
|
||||
/// Two copies of a plane apart in space and in UV space, each triangle with its own three vertices (as hard edges or per-face imports leave a mesh)
|
||||
fn split_planes() -> (Mesh, usize) {
|
||||
let plane = primitives::plane(2.0, 4);
|
||||
let (mut positions, mut uvs) = (Vec::<Vec3>::new(), Vec::<Vec2>::new());
|
||||
for shift in [0.0, 0.5] {
|
||||
for vertex in plane.indices.iter().map(|index| *index as usize) {
|
||||
positions.push(plane.positions[vertex] + Vec3::Y * shift);
|
||||
uvs.push(plane.uvs[vertex] * 0.5 + shift);
|
||||
}
|
||||
}
|
||||
let indices = (0..positions.len() as u32).collect();
|
||||
let mesh = Mesh::from_parts(positions, None, uvs, indices, "m").unwrap();
|
||||
assert_eq!(mesh.vertex_count(), 6 * plane.triangle_count(), "no vertex is shared");
|
||||
(mesh, plane.triangle_count())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uv_island_and_mesh_fills_follow_seams_split_vertices_leave_apart() {
|
||||
let (mesh, per_plane) = split_planes();
|
||||
let mut session = Session::new_project("t", mesh, "test", None, 128).unwrap();
|
||||
|
||||
for fill_mode in [FillMode::UvIsland, FillMode::Mesh] {
|
||||
session.tool.fill_mode = fill_mode;
|
||||
let groups = session.fill_partition(0);
|
||||
assert_eq!(groups.group(0).map(<[u32]>::len), Some(per_plane), "{fill_mode:?}: the whole first plane");
|
||||
assert_eq!(groups.group(per_plane as u32).map(<[u32]>::len), Some(per_plane), "{fill_mode:?}: only the second plane");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn polygon_mode_groups_the_two_triangles_of_each_quad() {
|
||||
let mut session = fill_session(primitives::plane(2.0, 2));
|
||||
|
||||
session.tool.fill_mode = FillMode::Triangle;
|
||||
assert_eq!(session.fill_partition(0).group(0), Some(&[0][..]));
|
||||
|
||||
session.tool.fill_mode = FillMode::Polygon;
|
||||
let mut quad = session.fill_partition(0).group(0).unwrap().to_vec();
|
||||
quad.sort_unstable();
|
||||
assert_eq!(quad, [0, 1], "the quad's two triangles and no other quad");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_uv_box_over_half_a_plane_fills_that_half() {
|
||||
let mut session = fill_session(primitives::plane(2.0, 4));
|
||||
session.tool.fill_hit_test = FillHitTest::ContainedCenter;
|
||||
|
||||
let filled = session.polygon_fill_box_uv(Vec2::new(-0.01, -0.01), Vec2::new(0.5, 1.01)).unwrap();
|
||||
session.update();
|
||||
|
||||
assert_eq!(filled, 16, "the left two columns of quads");
|
||||
assert!(filled_at(&session, Vec2::new(0.1, 0.5)) && filled_at(&session, Vec2::new(0.45, 0.9)));
|
||||
assert!(!filled_at(&session, Vec2::new(0.55, 0.5)) && !filled_at(&session, Vec2::new(0.9, 0.1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn intersection_and_contained_center_differ_on_a_box_missing_a_quads_center() {
|
||||
let mut session = fill_session(primitives::plane(2.0, 2));
|
||||
session.tool.fill_mode = FillMode::Polygon;
|
||||
let (corner, opposite) = (Vec2::new(0.0, 0.0), Vec2::new(0.2, 0.2));
|
||||
|
||||
session.tool.fill_hit_test = FillHitTest::ContainedCenter;
|
||||
assert_eq!(session.polygon_fill_box_uv(corner, opposite).unwrap(), 0, "the quad's center (0.25, 0.25) is outside");
|
||||
assert_ne!(session.undo_label(), Some("Polygon fill"), "an empty box records no undo step");
|
||||
|
||||
session.tool.fill_hit_test = FillHitTest::Intersection;
|
||||
assert_eq!(session.polygon_fill_box_uv(corner, opposite).unwrap(), 2, "the quad the box cuts");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn visible_only_skips_the_back_of_a_cube() {
|
||||
let mut session = fill_session(primitives::cube(1.0));
|
||||
session.camera.yaw = 0.6;
|
||||
session.camera.pitch = 0.4;
|
||||
let (low, high) = (Vec2::ZERO, session.viewport);
|
||||
let every_triangle = session.mesh.triangle_count();
|
||||
|
||||
session.tool.fill_visible_only = true;
|
||||
assert_eq!(session.polygon_fill_box(low, high, session.viewport).unwrap(), every_triangle / 2, "the three sides the camera sees");
|
||||
|
||||
session.tool.fill_visible_only = false;
|
||||
assert_eq!(session.polygon_fill_box(low, high, session.viewport).unwrap(), every_triangle);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn visible_only_sees_through_a_hidden_texture_set() {
|
||||
let mut session = fill_session(primitives::material_ball());
|
||||
let base = session.doc.project.texture_sets.iter().position(|set| set.name == "Base").unwrap();
|
||||
session.active_set = base;
|
||||
let (low, high) = (Vec2::ZERO, session.viewport);
|
||||
|
||||
let behind_the_ball = session.polygon_fill_box(low, high, session.viewport).unwrap();
|
||||
session.doc.project.texture_sets[0].visible = false;
|
||||
let ball_hidden = session.polygon_fill_box(low, high, session.viewport).unwrap();
|
||||
|
||||
assert!(ball_hidden > behind_the_ball, "hiding the ball shows more of the base: {ball_hidden} vs {behind_the_ball}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dragged_box_fills_live_and_records_one_step_when_it_ends() {
|
||||
let mut session = fill_session(primitives::plane(2.0, 4));
|
||||
let history = session.history_labels().len();
|
||||
|
||||
assert_eq!(session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap(), 32);
|
||||
assert_eq!(session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::new(0.45, 1.0)).unwrap(), 16, "shrinking the box unfills");
|
||||
session.update();
|
||||
assert!(filled_at(&session, Vec2::new(0.2, 0.5)) && !filled_at(&session, Vec2::new(0.8, 0.5)), "the fill shows while dragging");
|
||||
assert_eq!(session.history_labels().len(), history, "no undo step yet");
|
||||
|
||||
assert_eq!(session.end_polygon_fill_box(), 16);
|
||||
assert_eq!(session.history_labels().len(), history + 1);
|
||||
session.undo().unwrap();
|
||||
session.update();
|
||||
assert!(!filled_at(&session, Vec2::new(0.2, 0.5)), "one undo removes the whole drag");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_box_fill_leaves_no_drag_behind() {
|
||||
let mut session = fill_session(primitives::plane(2.0, 4));
|
||||
let layer = session.selected.remove(&0).unwrap();
|
||||
assert!(session.polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).is_err(), "no layer to paint on");
|
||||
|
||||
session.selected.insert(0, layer);
|
||||
assert_eq!(session.polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap(), 32, "the next box fills again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undo_and_tool_changes_finish_a_box_drag_first() {
|
||||
let mut session = fill_session(primitives::plane(2.0, 4));
|
||||
let history = session.history_labels().len();
|
||||
|
||||
session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap();
|
||||
assert_eq!(session.undo().unwrap(), "Polygon fill", "undo takes back the drag it finished");
|
||||
assert!(session.polygon_fill_drag.is_none());
|
||||
assert_eq!(session.history_labels().len(), history);
|
||||
|
||||
session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap();
|
||||
crate::tool_cmds::set_tool(&mut session, Tool::Paint).unwrap();
|
||||
assert!(session.polygon_fill_drag.is_none());
|
||||
assert_eq!(session.history_labels().len(), history + 1, "a tool change keeps the fill as one step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unmoved_box_keeps_its_fill() {
|
||||
let mut session = fill_session(primitives::plane(2.0, 4));
|
||||
let narrow_box = Vec2::new(0.3, 1.0);
|
||||
assert_eq!(session.drag_polygon_fill_box_uv(Vec2::ZERO, narrow_box).unwrap(), 16, "intersection: the two columns the box touches");
|
||||
|
||||
// Contained center would select one column, so a second selection would show 8
|
||||
session.tool.fill_hit_test = FillHitTest::ContainedCenter;
|
||||
assert_eq!(session.drag_polygon_fill_box_uv(Vec2::ZERO, narrow_box).unwrap(), 16, "the same box selects nothing again");
|
||||
assert_eq!(session.drag_polygon_fill_box_uv(Vec2::ZERO, narrow_box + Vec2::new(0.01, 0.0)).unwrap(), 8, "a moved box selects again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_uv_box_over_the_second_uv_tile_fills_that_tile_only() {
|
||||
let mut session = fill_session(primitives::udim_plane());
|
||||
assert_eq!(session.doc.project.texture_sets[0].uv_tiles, [1001, 1002]);
|
||||
session.tool.fill_hit_test = FillHitTest::ContainedCenter;
|
||||
|
||||
let every_triangle = session.mesh.triangle_count();
|
||||
assert_eq!(session.polygon_fill_box_uv(Vec2::new(0.5, 0.0), Vec2::ONE).unwrap(), every_triangle / 2, "the atlas's right half is tile 1002");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_2d_click_skips_a_triangle_with_collapsed_uvs() {
|
||||
// A face left unmapped (all corners at UV 0,0) comes first, as imports often leave them
|
||||
let plane = primitives::plane(2.0, 1);
|
||||
let mut positions = vec![Vec3::ZERO, Vec3::X, Vec3::Z];
|
||||
let mut uvs = vec![Vec2::ZERO; 3];
|
||||
positions.extend(&plane.positions);
|
||||
uvs.extend(&plane.uvs);
|
||||
let indices = [0, 1, 2].into_iter().chain(plane.indices.iter().map(|index| index + 3)).collect();
|
||||
let mut session = fill_session(Mesh::from_parts(positions, None, uvs, indices, "m").unwrap());
|
||||
|
||||
assert_eq!(session.polygon_fill_uv(Vec2::new(0.2, 0.7)).unwrap(), 1);
|
||||
session.update();
|
||||
assert!(filled_at(&session, Vec2::new(0.2, 0.7)), "the triangle under the cursor, not the collapsed one");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failing_drag_reports_once_and_records_nothing() {
|
||||
let mut session = fill_session(primitives::plane(2.0, 4));
|
||||
let history = session.history_labels().len();
|
||||
session.selected.clear();
|
||||
|
||||
assert!(session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::new(0.5, 1.0)).is_err());
|
||||
assert_eq!(session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap(), 0, "the rest of the drag fills nothing");
|
||||
assert_eq!(session.end_polygon_fill_box(), 0);
|
||||
assert_eq!(session.history_labels().len(), history);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_during_a_drag_records_the_fill_first() {
|
||||
let mut session = fill_session(primitives::plane(2.0, 4));
|
||||
session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap();
|
||||
|
||||
let layers = session.doc.project.layers.len();
|
||||
crate::execute(&mut session, "layer.add.paint", &serde_json::Value::Null).unwrap();
|
||||
assert!(session.polygon_fill_drag.is_none());
|
||||
let labels = session.history_labels();
|
||||
assert_eq!(labels.get(labels.len().wrapping_sub(2)).map(String::as_str), Some("Polygon fill"), "{labels:?}");
|
||||
|
||||
session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::new(0.45, 1.0)).unwrap();
|
||||
assert_eq!(session.doc.project.layers.len(), layers + 1, "a later drag move keeps the added layer");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_zero_size_box_on_whole_pixels_selects_what_is_under_it() {
|
||||
let mut session = fill_session(primitives::cube(1.0));
|
||||
let center = (session.viewport * 0.5).floor();
|
||||
|
||||
assert!(session.polygon_fill_box(center, center, session.viewport).unwrap() > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_camera_move_mid_drag_keeps_one_drag() {
|
||||
let mut session = fill_session(primitives::cube(1.0));
|
||||
let viewport = session.viewport;
|
||||
let history = session.history_labels().len();
|
||||
|
||||
let (corner, opposite) = (viewport * 0.4, viewport * 0.6);
|
||||
|
||||
let before_zoom = session.drag_polygon_fill_box(corner, opposite, viewport).unwrap();
|
||||
session.camera.zoom(0.5);
|
||||
let after_zoom = session.drag_polygon_fill_box(corner, opposite, viewport).unwrap();
|
||||
session.end_polygon_fill_box();
|
||||
|
||||
assert_ne!(before_zoom, after_zoom, "the same box selects again from the new camera");
|
||||
assert_eq!(session.history_labels().len(), history + 1, "a wheel zoom during the drag doesn't split it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pixel_spans_include_both_edges_and_nothing_outside() {
|
||||
assert_eq!(super::pixel_span(2.0, 2.0, 100), 2..3, "a zero-size span on a whole pixel");
|
||||
assert_eq!(super::pixel_span(-50.0, -10.0, 100), 0..0, "before the first pixel");
|
||||
assert_eq!(super::pixel_span(120.0, 150.0, 100), 100..100, "past the last pixel");
|
||||
assert_eq!(super::pixel_span(-5.0, 500.0, 100), 0..100);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_2d_click_fills_the_triangle_under_it() {
|
||||
let mut session = fill_session(primitives::plane(2.0, 1));
|
||||
|
||||
assert_eq!(session.polygon_fill_uv(Vec2::new(0.2, 0.7)).unwrap(), 1);
|
||||
session.update();
|
||||
|
||||
assert!(filled_at(&session, Vec2::new(0.2, 0.7)));
|
||||
assert!(!filled_at(&session, Vec2::new(0.7, 0.2)), "the quad's other triangle stays");
|
||||
assert!(session.polygon_fill_uv(Vec2::new(1.5, 0.5)).is_err(), "nothing outside the UVs");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
//! A polygon fill box being dragged: what it filled so far and what it needs to refill each move.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use texturecraft_core::LayerId;
|
||||
use texturecraft_geom::OrbitCamera;
|
||||
use texturecraft_geom::glam::Vec2;
|
||||
use texturecraft_paint::EyeDepth;
|
||||
use texturecraft_texel::TileImage;
|
||||
|
||||
use crate::session::{Document, StackTarget};
|
||||
use crate::triangle_partition::TrianglePartition;
|
||||
|
||||
/// A polygon fill box being dragged: the fill shows live and becomes one undo step when the drag ends
|
||||
pub(crate) struct PolygonFillDrag {
|
||||
/// The texture set it fills
|
||||
pub ts: usize,
|
||||
/// The selected layer and content, mask or effect being filled
|
||||
pub target: (Option<LayerId>, StackTarget),
|
||||
/// The 3D view's size in pixels, or None for a drag in the 2D view
|
||||
pub viewport: Option<Vec2>,
|
||||
/// The camera [`PolygonFillDrag::points`] and [`PolygonFillDrag::depth`] were made with
|
||||
pub camera: OrbitCamera,
|
||||
/// The document before the drag, refilled each time the selection changes
|
||||
pub before: Document,
|
||||
/// The quick mask's coverage before the drag, when the drag paints the quick mask
|
||||
pub quick_mask_before: Option<BTreeMap<usize, TileImage>>,
|
||||
/// Each vertex where the box sees it: viewport pixels in the 3D view (None behind the camera), texture coordinates in the 2D view
|
||||
pub points: Vec<Option<Vec2>>,
|
||||
/// What the camera sees (3D view, visible polygons only)
|
||||
pub depth: Option<EyeDepth>,
|
||||
/// What the fill mode fills together
|
||||
pub fill_groups: TrianglePartition,
|
||||
/// The polygons the box tests, when they differ from the fill groups
|
||||
pub polygons: Option<TrianglePartition>,
|
||||
/// The triangles filled so far
|
||||
pub filled: BTreeSet<u32>,
|
||||
/// The box last shown, lowest corner first: an unmoved box isn't selected again
|
||||
pub last_box: Option<(Vec2, Vec2)>,
|
||||
/// The fill failed (reported once): the rest of the drag fills nothing
|
||||
pub failed: bool,
|
||||
}
|
||||
@@ -1,12 +1,8 @@
|
||||
//! Shelf previews: built-in materials and smart masks evaluated on a unit sphere seen from +Z,
|
||||
//! without a mesh or baked maps (generators that need mesh maps are approximated with world-space
|
||||
//! noise). Cheap enough for lazily rendered thumbnails.
|
||||
//! Cheap shelf previews on a unit sphere: plain materials and library filters (smart ones use [`crate::orb_preview`])
|
||||
|
||||
use texturecraft_compose::pattern::{Coords, procedural, world_noise};
|
||||
use texturecraft_core::{
|
||||
Channel, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, Layer, LayerKind, Mask, MaskBackground, Procedural, ProceduralKind, Project,
|
||||
Projection, Source, TextureSet, blend1,
|
||||
};
|
||||
use rayon::prelude::*;
|
||||
use texturecraft_compose::pattern::{Coords, procedural};
|
||||
use texturecraft_core::{Channel, Effect, EffectKind, Fill, Filter, Layer, LayerKind, Procedural, ProceduralKind, Project, Projection, Source, TextureSet};
|
||||
use texturecraft_geom::glam::{Vec2, Vec3};
|
||||
|
||||
use crate::materials::{Builder, build};
|
||||
@@ -48,74 +44,40 @@ fn source(s: &Source, proj: &Projection, c: &Coords) -> Option<[f32; 3]> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Approximate generator: mesh-map signals become world noise (a sphere has no edges or cavities).
|
||||
fn generator(g: &Generator, c: &Coords) -> f32 {
|
||||
let dir = Vec3::from(g.direction).try_normalize().unwrap_or(Vec3::Y);
|
||||
let wear = (world_noise(c.pos, 3.0, 91) - 0.5) * 2.2;
|
||||
let cavity = (world_noise(c.pos, 3.0, 57) - 0.3).clamp(0.0, 1.0) + (1.0 - c.nrm.y) * 0.1;
|
||||
let s = match g.kind {
|
||||
GeneratorKind::Position => c.pos.dot(dir) * 0.5 + 0.5,
|
||||
GeneratorKind::Direction => c.nrm.dot(dir) * 0.5 + 0.5,
|
||||
GeneratorKind::EdgeWear => wear,
|
||||
GeneratorKind::Curvature => 0.5 + wear * 0.5,
|
||||
GeneratorKind::AmbientOcclusion => 1.0 - cavity,
|
||||
_ => cavity,
|
||||
};
|
||||
// Same thresholding as the compositor.
|
||||
let s = if g.noise_amount > 0.0 { s + (world_noise(c.pos, g.noise_scale, g.seed) - 0.5) * g.noise_amount } else { s };
|
||||
let soft = g.softness.max(1e-3);
|
||||
let t = ((s - (1.0 - g.level.clamp(0.0, 1.0) - soft)) / (2.0 * soft)).clamp(0.0, 1.0);
|
||||
let v = t * t * (3.0 - 2.0 * t);
|
||||
if g.invert { 1.0 - v } else { v }
|
||||
}
|
||||
|
||||
fn mask(m: &Mask, c: &Coords) -> f32 {
|
||||
if !m.enabled {
|
||||
return 1.0;
|
||||
}
|
||||
let mut v = if m.background == MaskBackground::White { 1.0 } else { 0.0 };
|
||||
for e in m.effects.iter().filter(|e| e.visible) {
|
||||
let val = match &e.kind {
|
||||
EffectKind::Fill { source: s, projection } => source(s, projection, c).map(|x| x[0]),
|
||||
EffectKind::Generator(g) => Some(generator(g, c)),
|
||||
EffectKind::Levels(l) => Some(l.apply(v)),
|
||||
EffectKind::Filter(Filter::Invert) => Some(1.0 - v),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(val) = val {
|
||||
let blended = if matches!(e.kind, EffectKind::Levels(_) | EffectKind::Filter(_)) { val } else { blend1(e.blend, v, val) };
|
||||
v += (blended - v) * e.opacity.clamp(0.0, 1.0);
|
||||
}
|
||||
}
|
||||
v.clamp(0.0, 1.0)
|
||||
}
|
||||
|
||||
const CHANNELS: [Channel; 4] = [Channel::BaseColor, Channel::Metallic, Channel::Roughness, Channel::Height];
|
||||
|
||||
/// Preview of built-in material `id` (None for an unknown id).
|
||||
/// Preview of plain material `id` (None for an unknown id or a smart material, whose masks need mesh maps)
|
||||
pub fn material(id: &str, size: usize) -> Option<Vec<Option<Sample>>> {
|
||||
let mut p = Project::new("preview", "");
|
||||
let layers = build(&mut Builder { p: &mut p, channels: CHANNELS.to_vec() }, id).ok()?;
|
||||
Some(
|
||||
sphere_normals(size)
|
||||
.map(|n| {
|
||||
let c = coords(n?);
|
||||
let mut acc = CHANNELS.map(Channel::default_value);
|
||||
for l in layers.iter().filter(|l| l.visible) {
|
||||
let LayerKind::Fill(f) = &l.kind else { continue };
|
||||
let w = l.mask.as_ref().map_or(1.0, |m| mask(m, &c));
|
||||
for (a, ch) in acc.iter_mut().zip(CHANNELS) {
|
||||
if let (Some(b), Some(v)) = (l.blend(ch), f.sources.get(&ch).and_then(|s| source(s, &f.projection, &c))) {
|
||||
let t = w * b.opacity.clamp(0.0, 1.0);
|
||||
*a = [0, 1, 2].map(|k| a[k] + (v[k] - a[k]) * t);
|
||||
}
|
||||
let plain = crate::materials::find(id).filter(|found| !found.smart)?;
|
||||
let mut project = Project::new("preview", "");
|
||||
let layers = build(&mut Builder { p: &mut project, channels: CHANNELS.to_vec() }, plain.id).ok()?;
|
||||
|
||||
// Pixels evaluate independently and big previews take long on one core
|
||||
let normals: Vec<_> = sphere_normals(size).collect();
|
||||
let samples = normals
|
||||
.into_par_iter()
|
||||
.map(|normal| {
|
||||
let at = coords(normal?);
|
||||
let mut values = CHANNELS.map(Channel::default_value);
|
||||
for layer in layers.iter().filter(|layer| layer.visible) {
|
||||
// Plain materials are unmasked fills
|
||||
let LayerKind::Fill(fill) = &layer.kind else { continue };
|
||||
|
||||
for (value, channel) in values.iter_mut().zip(CHANNELS) {
|
||||
let layer_value = fill.sources.get(&channel).and_then(|channel_source| source(channel_source, &fill.projection, &at));
|
||||
if let (Some(blend), Some(layer_value)) = (layer.blend(channel), layer_value) {
|
||||
let weight = blend.opacity.clamp(0.0, 1.0);
|
||||
*value = [0, 1, 2].map(|component| value[component] + (layer_value[component] - value[component]) * weight);
|
||||
}
|
||||
}
|
||||
let [base, metal, rough, height] = acc;
|
||||
Some(Sample { base, metallic: metal[0], roughness: rough[0], height: height[0] })
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
let [base, metallic, roughness, height] = values;
|
||||
Some(Sample { base, metallic: metallic[0], roughness: roughness[0], height: height[0] })
|
||||
})
|
||||
.collect();
|
||||
|
||||
Some(samples)
|
||||
}
|
||||
|
||||
/// `f` with its reach in texels multiplied by `k` (previews show at a fraction of 2K).
|
||||
@@ -164,6 +126,7 @@ pub fn filter(id: &str, size: usize) -> Option<Vec<Option<Sample>>> {
|
||||
gbuf: &gbuf,
|
||||
pixels: &pixels,
|
||||
baked: &baked,
|
||||
block_scales: p.texture_set(0).map(|set| set.block_scales()).unwrap_or_default(),
|
||||
preview: None,
|
||||
images: &images,
|
||||
bounds: mesh.bounds(),
|
||||
@@ -183,36 +146,44 @@ pub fn filter(id: &str, size: usize) -> Option<Vec<Option<Sample>>> {
|
||||
)
|
||||
}
|
||||
|
||||
/// Preview of smart mask `id`: the mask value per pixel (None for an unknown id).
|
||||
pub fn smart_mask(id: &str, size: usize) -> Option<Vec<Option<f32>>> {
|
||||
let (bg, fx) = crate::smart_masks::preset(id)?;
|
||||
let m = crate::smart_masks::build_mask(&mut Project::new("preview", ""), bg, fx);
|
||||
Some(sphere_normals(size).map(|n| n.map(|n| mask(&m, &coords(n)))).collect())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Whether every value of `sample` is finite
|
||||
fn finite(sample: &Sample) -> bool {
|
||||
sample.base.into_iter().chain([sample.metallic, sample.roughness, sample.height]).all(f32::is_finite)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn previews_cover_the_sphere_with_finite_values() {
|
||||
for m in crate::materials::MATERIALS {
|
||||
let px = material(m.id, 16).unwrap_or_else(|| panic!("{}", m.id));
|
||||
let center = px[8 * 16 + 8].unwrap_or_else(|| panic!("{}", m.id));
|
||||
assert!(center.base.iter().chain([¢er.metallic, ¢er.roughness, ¢er.height]).all(|v| v.is_finite()), "{}", m.id);
|
||||
assert!(px[0].is_none(), "corners are outside the sphere");
|
||||
let size = 16;
|
||||
for built_in in crate::materials::MATERIALS {
|
||||
let id = built_in.id;
|
||||
if built_in.smart {
|
||||
assert!(material(id, size).is_none(), "{id}: smart materials preview on the orb");
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut project = Project::new("preview", "");
|
||||
let layers = build(&mut Builder { p: &mut project, channels: CHANNELS.to_vec() }, id).unwrap();
|
||||
assert!(layers.iter().all(|layer| layer.mask.is_none()), "{id}: the sphere preview shows no masks");
|
||||
|
||||
let pixels = material(id, size).unwrap_or_else(|| panic!("{id}"));
|
||||
let center = pixels[size / 2 * size + size / 2].unwrap_or_else(|| panic!("{id}"));
|
||||
assert!(finite(¢er), "{id}");
|
||||
assert!(pixels[0].is_none(), "corners are outside the sphere");
|
||||
}
|
||||
for sm in crate::smart_masks::SMART_MASKS {
|
||||
let px = smart_mask(sm.id, 16).unwrap_or_else(|| panic!("{}", sm.id));
|
||||
assert!(px.iter().flatten().all(|v| (0.0..=1.0).contains(v)), "{}", sm.id);
|
||||
assert!(material("nope", size).is_none() && filter("nope", size).is_none());
|
||||
|
||||
let size = 24;
|
||||
for library_filter in crate::filter_lib::FILTERS {
|
||||
let id = library_filter.id;
|
||||
let pixels = filter(id, size).unwrap_or_else(|| panic!("{id}"));
|
||||
let center = pixels[size / 2 * size + size / 2].unwrap_or_else(|| panic!("{id}"));
|
||||
assert!(finite(¢er), "{id}");
|
||||
}
|
||||
assert!(material("nope", 8).is_none() && smart_mask("nope", 8).is_none() && filter("nope", 8).is_none());
|
||||
for f in crate::filter_lib::FILTERS {
|
||||
let px = filter(f.id, 24).unwrap_or_else(|| panic!("{}", f.id));
|
||||
let center = px[12 * 24 + 12].unwrap_or_else(|| panic!("{}", f.id));
|
||||
assert!(center.base.iter().chain([¢er.roughness, ¢er.height]).all(|v| v.is_finite()), "{}", f.id);
|
||||
}
|
||||
let (plain, warped) = (filter("levels", 24).unwrap(), filter("warp", 24).unwrap());
|
||||
let (plain, warped) = (filter("levels", size).unwrap(), filter("warp", size).unwrap());
|
||||
assert!(plain != warped, "the warp shows in its preview");
|
||||
}
|
||||
}
|
||||
@@ -36,12 +36,18 @@ pub(crate) fn decoded(d: texturecraft_formats::DecodedImage) -> Arc<ImageRes> {
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Add an image resource from bytes (one undo step); returns its unique, sanitized name.
|
||||
/// 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> {
|
||||
self.edit("Import resource", |s| s.add_image_resource(file_name, bytes, u64::MAX))
|
||||
}
|
||||
|
||||
/// Add an image within a decoded texel budget, inside the caller's edit
|
||||
pub(crate) fn add_image_resource(&mut self, file_name: &str, bytes: Vec<u8>, max_texels: u64) -> Result<String> {
|
||||
if bytes.len() > MAX_BYTES {
|
||||
return Err(EngineError::Other(format!("{file_name} is larger than {} MB", MAX_BYTES >> 20)));
|
||||
}
|
||||
let image = texturecraft_formats::decode_image(&bytes).map_err(|e| EngineError::Other(format!("{file_name}: {e}")))?;
|
||||
|
||||
let image = texturecraft_formats::decode_image_within(&bytes, max_texels).map_err(|e| EngineError::Other(format!("{file_name}: {e}")))?;
|
||||
let leaf = std::path::Path::new(file_name).file_name().and_then(|n| n.to_str()).unwrap_or("image");
|
||||
let base = texturecraft_formats::sanitize_resource_name(leaf);
|
||||
let mut name = base.clone();
|
||||
@@ -50,11 +56,8 @@ impl Session {
|
||||
name = format!("{n}_{base}");
|
||||
n += 1;
|
||||
}
|
||||
let key = name.clone();
|
||||
self.edit("Import resource", |s| {
|
||||
s.doc.resources.insert(key, Arc::new(bytes));
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
self.doc.resources.insert(name.clone(), Arc::new(bytes));
|
||||
self.images.insert(name.clone(), decoded(image));
|
||||
Ok(name)
|
||||
}
|
||||
@@ -98,15 +101,44 @@ 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 meta = std::fs::metadata(path).map_err(|e| bad("resource.import", format!("cannot read {path}: {e}")))?;
|
||||
if meta.len() > MAX_BYTES as u64 {
|
||||
return Err(bad("resource.import", format!("{path} is too large")));
|
||||
}
|
||||
let bytes = std::fs::read(path).map_err(|e| bad("resource.import", format!("cannot read {path}: {e}")))?;
|
||||
let bytes = read_image_file("resource.import", path, MAX_BYTES as u64)?;
|
||||
let name = s.import_resource_bytes(path, bytes)?;
|
||||
Ok(json!({ "name": name }))
|
||||
}
|
||||
|
||||
/// Read a regular image file within both the per-file cap and the caller's remaining byte budget
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn read_image_file(cmd: &str, path: &str, max_bytes: u64) -> Result<Vec<u8>> {
|
||||
use std::io::Read;
|
||||
|
||||
let max_bytes = max_bytes.min(MAX_BYTES as u64);
|
||||
let read_error = |error| bad(cmd, format!("cannot read {path}: {error}"));
|
||||
let too_large = || bad(cmd, format!("{path} is too large (limit {max_bytes} bytes)"));
|
||||
let metadata = std::fs::metadata(path).map_err(read_error)?;
|
||||
// Pipes can block on open, and devices may never reach EOF
|
||||
if !metadata.is_file() {
|
||||
return Err(bad(cmd, format!("{path} is not a regular file")));
|
||||
}
|
||||
if metadata.len() > max_bytes {
|
||||
return Err(too_large());
|
||||
}
|
||||
|
||||
// Bound the read even if the file grows after the metadata check
|
||||
let file = std::fs::File::open(path).map_err(read_error)?;
|
||||
let mut bytes = Vec::with_capacity(metadata.len() as usize);
|
||||
file.take(max_bytes + 1).read_to_end(&mut bytes).map_err(read_error)?;
|
||||
if bytes.len() as u64 > max_bytes {
|
||||
return Err(too_large());
|
||||
}
|
||||
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub(crate) fn read_image_file(cmd: &str, _: &str, _: u64) -> Result<Vec<u8>> {
|
||||
Err(bad(cmd, "file paths are not available in the browser"))
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn import(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
Err(EngineError::Other("file paths are not available in the browser; use File > Import resources".into()))
|
||||
@@ -165,3 +197,24 @@ fn add_image_fill(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
})?;
|
||||
Ok(json!({ "layer": id.0 }))
|
||||
}
|
||||
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn file_reads_obey_the_remaining_byte_budget() {
|
||||
let path = std::env::temp_dir().join(format!("texturecraft-read-image-{}.png", std::process::id()));
|
||||
std::fs::write(&path, b"1234").unwrap();
|
||||
let name = path.to_str().unwrap();
|
||||
assert!(read_image_file("test", name, 3).unwrap_err().to_string().contains("too large"));
|
||||
assert_eq!(read_image_file("test", name, 4).unwrap(), b"1234");
|
||||
std::fs::remove_file(path).unwrap();
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn devices_are_rejected_before_reading() {
|
||||
assert!(read_image_file("test", "/dev/null", 16).unwrap_err().to_string().contains("not a regular file"));
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ use texturecraft_geom::{Bvh, Mesh, OrbitCamera, UvGBuffer};
|
||||
use texturecraft_paint::{BrushSettings, EyeDepth, Stroke, StrokeCanvas};
|
||||
use texturecraft_texel::DilationMap;
|
||||
|
||||
use crate::fill_mode::FillMode;
|
||||
use crate::{EngineError, Result};
|
||||
|
||||
/// Padding (texels) applied to composites for display.
|
||||
@@ -160,15 +161,6 @@ impl ViewMode {
|
||||
}
|
||||
}
|
||||
|
||||
/// Polygon fill granularity.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
pub enum FillMode {
|
||||
#[default]
|
||||
Triangle,
|
||||
UvIsland,
|
||||
Mesh,
|
||||
}
|
||||
|
||||
/// A screen-pinned image for the Projection tool (a stencil).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct StencilState {
|
||||
@@ -210,6 +202,12 @@ pub struct ToolState {
|
||||
/// Gray painted into masks.
|
||||
pub mask_value: f32,
|
||||
pub fill_mode: FillMode,
|
||||
/// How a polygon fill box decides which polygons it selects
|
||||
#[serde(default)]
|
||||
pub fill_hit_test: crate::fill_hit_test::FillHitTest,
|
||||
/// Polygon fill boxes in the 3D view select only the polygons the camera sees
|
||||
#[serde(default = "default_fill_visible_only")]
|
||||
pub fill_visible_only: bool,
|
||||
/// Stencil used by the Projection tool.
|
||||
#[serde(default)]
|
||||
pub stencil: Option<StencilState>,
|
||||
@@ -231,6 +229,10 @@ fn default_smudge_strength() -> f32 {
|
||||
0.5
|
||||
}
|
||||
|
||||
fn default_fill_visible_only() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// What the Clone tool copies (the clone source modes).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
pub enum CloneFrom {
|
||||
@@ -260,6 +262,8 @@ impl Default for ToolState {
|
||||
enabled: [Channel::BaseColor, Channel::Metallic, Channel::Roughness, Channel::Height, Channel::Normal].into_iter().collect(),
|
||||
mask_value: 1.0,
|
||||
fill_mode: FillMode::Triangle,
|
||||
fill_hit_test: Default::default(),
|
||||
fill_visible_only: default_fill_visible_only(),
|
||||
stencil: None,
|
||||
smudge_strength: default_smudge_strength(),
|
||||
clone_source: None,
|
||||
@@ -291,8 +295,8 @@ pub(crate) struct ActiveStroke {
|
||||
pub canvas: StrokeCanvas,
|
||||
/// Camera visibility for 3D strokes (None for strokes in the 2D view).
|
||||
pub depth: Option<Arc<EyeDepth>>,
|
||||
/// 2D view strokes: last UV point and the distance carried to the next stamp.
|
||||
pub uv: Option<(Option<Vec2>, f32)>,
|
||||
/// 2D view strokes: where the stroke is between samples.
|
||||
pub uv: Option<crate::uv_stroke_state::UvStrokeState>,
|
||||
pub camera: OrbitCamera,
|
||||
pub viewport: Vec2,
|
||||
pub values: BTreeMap<Channel, [f32; 3]>,
|
||||
@@ -314,6 +318,9 @@ pub struct Session {
|
||||
pub mesh: Arc<Mesh>,
|
||||
/// Unique per loaded mesh and UV layout (GPU caches compare it).
|
||||
pub mesh_id: u64,
|
||||
/// Unique per open project: a mesh reimport or UV layout change keeps it, and opening, closing
|
||||
/// or creating a project replaces it.
|
||||
pub project_id: u64,
|
||||
/// The mesh with its own UVs (`mesh` maps UV-tiled sets into their atlas).
|
||||
pub(crate) source: Arc<Mesh>,
|
||||
pub bvh: Arc<Bvh>,
|
||||
@@ -356,6 +363,8 @@ pub struct Session {
|
||||
/// The last stroke's camera visibility buffer: reused while the camera, view size and mesh
|
||||
/// are unchanged, so back-to-back dabs start instantly.
|
||||
pub(crate) depth_cache: Option<DepthCache>,
|
||||
/// The polygon fill box being dragged
|
||||
pub(crate) polygon_fill_drag: Option<crate::polygon_fill_drag::PolygonFillDrag>,
|
||||
/// The user's export presets (kept when another project opens).
|
||||
pub export_presets: crate::preset_cmds::UserPresets,
|
||||
/// The user's project templates (kept when another project opens).
|
||||
@@ -378,6 +387,7 @@ impl Session {
|
||||
Ok(Session {
|
||||
doc,
|
||||
mesh_id: next_mesh_id(),
|
||||
project_id: next_mesh_id(),
|
||||
source,
|
||||
mesh,
|
||||
bvh: Arc::new(bvh),
|
||||
@@ -405,6 +415,7 @@ impl Session {
|
||||
revision: 1,
|
||||
log: Vec::new(),
|
||||
depth_cache: None,
|
||||
polygon_fill_drag: None,
|
||||
export_presets: Default::default(),
|
||||
templates: Default::default(),
|
||||
})
|
||||
@@ -489,22 +500,24 @@ impl Session {
|
||||
self.edit_merging(label, self.merge_edits, f)
|
||||
}
|
||||
|
||||
/// [`Session::edit`] that, with `merge`, continues the previous undo step when it has the
|
||||
/// same label (a drag in the viewport is one step however many updates it makes).
|
||||
pub fn edit_merging<T>(&mut self, label: &str, merge: bool, f: impl FnOnce(&mut Session) -> Result<T>) -> Result<T> {
|
||||
/// [`Session::edit`] that, with `merge`, continues the previous undo step when it has the same label (a viewport drag is one step however many updates it makes).
|
||||
pub fn edit_merging<T>(&mut self, label: &str, merge: bool, change: impl FnOnce(&mut Session) -> Result<T>) -> Result<T> {
|
||||
// A box fill under way becomes its own step first, so this edit isn't written over or folded into it
|
||||
self.end_polygon_fill_box();
|
||||
|
||||
let before = self.doc.clone();
|
||||
let result = f(self).and_then(|v| match self.doc.project.instance_cycle() {
|
||||
let result = change(self).and_then(|value| match self.doc.project.instance_cycle() {
|
||||
Some(id) => Err(EngineError::Other(format!("instance layer {} would draw itself", id.0))),
|
||||
None => Ok(v),
|
||||
None => Ok(value),
|
||||
});
|
||||
match result {
|
||||
Ok(v) => {
|
||||
Ok(value) => {
|
||||
self.record(label, before, merge);
|
||||
Ok(v)
|
||||
Ok(value)
|
||||
}
|
||||
Err(e) => {
|
||||
Err(error) => {
|
||||
self.doc = before;
|
||||
Err(e)
|
||||
Err(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -530,7 +543,7 @@ impl Session {
|
||||
|
||||
/// Mark dirty every texture set whose composite differs between `other` and the current
|
||||
/// document (after an edit, undo or redo).
|
||||
fn invalidate_changed(&mut self, other: &Document) {
|
||||
pub(crate) fn invalidate_changed(&mut self, other: &Document) {
|
||||
self.follow_uv_layouts(&other.project);
|
||||
self.sync_caches();
|
||||
let resources = |d: &Document| d.resources.iter().map(|(n, b)| (n.clone(), Arc::as_ptr(b))).collect::<Vec<_>>();
|
||||
@@ -625,25 +638,29 @@ impl Session {
|
||||
}
|
||||
|
||||
pub fn undo(&mut self) -> Result<String> {
|
||||
// A stroke, a box fill or an edited path under way would otherwise write over the restored document
|
||||
self.cancel_stroke();
|
||||
// An edited path would otherwise repaint over the restored document.
|
||||
self.end_polygon_fill_box();
|
||||
self.stop_path_edit();
|
||||
let (label, doc) = self.undo.pop().ok_or_else(|| EngineError::Other("nothing to undo".into()))?;
|
||||
let now = std::mem::replace(&mut self.doc, doc);
|
||||
self.after_history(&now);
|
||||
self.redo.push((label.clone(), now));
|
||||
|
||||
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.redo.push((label.clone(), current));
|
||||
self.sync_images();
|
||||
Ok(label)
|
||||
}
|
||||
|
||||
pub fn redo(&mut self) -> Result<String> {
|
||||
// A stroke, a box fill or an edited path under way would otherwise write over the restored document
|
||||
self.cancel_stroke();
|
||||
// An edited path would otherwise repaint over the restored document.
|
||||
self.end_polygon_fill_box();
|
||||
self.stop_path_edit();
|
||||
let (label, doc) = self.redo.pop().ok_or_else(|| EngineError::Other("nothing to redo".into()))?;
|
||||
let now = std::mem::replace(&mut self.doc, doc);
|
||||
self.after_history(&now);
|
||||
self.undo.push((label.clone(), now));
|
||||
|
||||
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.undo.push((label.clone(), current));
|
||||
self.sync_images();
|
||||
Ok(label)
|
||||
}
|
||||
@@ -728,6 +745,7 @@ impl Session {
|
||||
gbuf: &cache.gbuf,
|
||||
pixels: &self.doc.pixels,
|
||||
baked: self.doc.baked.get(&ts).unwrap_or(&empty),
|
||||
block_scales: cache.composite.block_scales.clone(),
|
||||
preview,
|
||||
images: &self.images,
|
||||
bounds: self.mesh.bounds(),
|
||||
@@ -816,6 +834,7 @@ impl Session {
|
||||
gbuf: &cache.gbuf,
|
||||
pixels: &self.doc.pixels,
|
||||
baked: self.doc.baked.get(&ts).unwrap_or(&empty),
|
||||
block_scales: cache.composite.block_scales.clone(),
|
||||
preview: None,
|
||||
images: &self.images,
|
||||
bounds: self.mesh.bounds(),
|
||||
@@ -829,6 +848,13 @@ impl Session {
|
||||
Some(gray.iter().flat_map(|g| [*g, *g, *g, 255]).collect())
|
||||
}
|
||||
|
||||
/// Mask values at texture-set coordinates in request order; None without an enabled mask
|
||||
/// Uncovered and out-of-range texels read zero; neighbourhood filters also read surrounding texels
|
||||
pub fn mask_at(&self, id: LayerId, texels: &[(u32, u32)]) -> Option<Vec<f32>> {
|
||||
let (texture_set, _, _) = self.doc.project.locate(id)?;
|
||||
self.with_inputs(texture_set, |inputs| texturecraft_compose::mask_at(inputs, id, texels))
|
||||
}
|
||||
|
||||
/// Histogram (`bins` buckets over 0..1) of the values entering effect `effect`: its layer's
|
||||
/// mask, or for a content effect the layer's `channel` (None for an unknown effect).
|
||||
pub fn effect_histogram(&self, effect: LayerId, channel: Channel, bins: usize) -> Option<Vec<u32>> {
|
||||
|
||||
@@ -62,14 +62,14 @@ pub fn find(name: &str) -> Option<&'static SmartMask> {
|
||||
|
||||
const UP: [f32; 3] = [0.0, 1.0, 0.0];
|
||||
|
||||
/// A mesh-map generator with explicit threshold, softness and noise breakup.
|
||||
/// A mesh-map generator with explicit threshold, softness and noise breakup (curvature as baked, without detail sizes).
|
||||
pub(crate) fn generator(kind: GeneratorKind, level: f32, softness: f32, noise: f32) -> EffectKind {
|
||||
EffectKind::Generator(Generator { level, softness, noise_amount: noise, ..Generator::new(kind) })
|
||||
EffectKind::Generator(Generator { level, softness, noise_amount: noise, detail: None, ..Generator::new(kind) })
|
||||
}
|
||||
|
||||
/// A direction or position generator (`invert` flips the result).
|
||||
pub(crate) fn directional(kind: GeneratorKind, direction: [f32; 3], level: f32, softness: f32, noise: f32, invert: bool) -> EffectKind {
|
||||
EffectKind::Generator(Generator { level, softness, noise_amount: noise, direction, invert, ..Generator::new(kind) })
|
||||
EffectKind::Generator(Generator { level, softness, noise_amount: noise, direction, invert, detail: None, ..Generator::new(kind) })
|
||||
}
|
||||
|
||||
/// A triplanar grayscale pattern fill.
|
||||
|
||||
@@ -7,7 +7,9 @@ use texturecraft_geom::glam::Vec2;
|
||||
use texturecraft_paint::{Alignment, BrushAlpha, alphas};
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad, boolp, channel_param, color_param, f32p, strp};
|
||||
use crate::session::{CloneFrom, CloneSource, FillMode, Tool};
|
||||
use crate::fill_hit_test::FillHitTest;
|
||||
use crate::fill_mode::FillMode;
|
||||
use crate::session::{CloneFrom, CloneSource, Tool};
|
||||
use crate::{Result, Session, cmd};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -69,7 +71,16 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
always,
|
||||
clone_source
|
||||
),
|
||||
cmd!("tool.fillMode", "Polygon fill mode", [], None, "{mode: triangle|uvIsland|mesh}", always, fill_mode),
|
||||
cmd!("tool.fillMode", "Polygon fill mode", [], None, "{mode: triangle|polygon|uvIsland|mesh}", always, fill_mode),
|
||||
cmd!(
|
||||
"tool.fillSelection",
|
||||
"Polygon fill selection",
|
||||
[],
|
||||
None,
|
||||
"{hitTest?: intersection|containedCenter (a box selects polygons it touches, or whose center it holds), visibleOnly?: bool (3D view boxes select only what the camera sees)}",
|
||||
always,
|
||||
fill_selection
|
||||
),
|
||||
cmd!("tool.stroke", "Paint stroke", [], None, "{points: [[x,y],...] viewport pixels, viewport?: [w,h]} — paints with the current tool", always, stroke),
|
||||
cmd!(
|
||||
"tool.strokeUv",
|
||||
@@ -80,16 +91,26 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
always,
|
||||
stroke_uv
|
||||
),
|
||||
cmd!("tool.click", "Tool click", [], None, "{x, y, viewport?: [w,h]} — polygon fill / color picker / single dab", always, click),
|
||||
cmd!(
|
||||
"tool.click",
|
||||
"Tool click",
|
||||
[],
|
||||
None,
|
||||
"{x, y, viewport?: [w,h]} — polygon fill / color picker / single dab; polygon fill also takes a box {x0, y0, x1, y1, viewport?}, a 2D view point {uv: [u,v]} or a 2D view box {uv0: [u,v], uv1: [u,v]}",
|
||||
always,
|
||||
click
|
||||
),
|
||||
cmd!("tool.state", "Tool state", [], None, "{}", always, |s, _| Ok(serde_json::to_value(&s.tool).unwrap_or(Value::Null))),
|
||||
]
|
||||
}
|
||||
|
||||
pub(crate) fn set_tool(s: &mut Session, t: Tool) -> Result<Value> {
|
||||
s.cancel_stroke();
|
||||
s.tool.tool = t;
|
||||
s.revision = s.revision.wrapping_add(1);
|
||||
Ok(json!({ "tool": t.id() }))
|
||||
pub(crate) fn set_tool(session: &mut Session, tool: Tool) -> Result<Value> {
|
||||
session.cancel_stroke();
|
||||
// A box fill under way keeps what it filled as one undo step
|
||||
session.end_polygon_fill_box();
|
||||
session.tool.tool = tool;
|
||||
session.revision = session.revision.wrapping_add(1);
|
||||
Ok(json!({ "tool": tool.id() }))
|
||||
}
|
||||
|
||||
fn select(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -319,13 +340,29 @@ fn clone_source(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(serde_json::to_value(s.tool.clone_source).unwrap_or(Value::Null))
|
||||
}
|
||||
|
||||
fn fill_mode(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.tool.fill_mode = match strp(p, "mode").unwrap_or("triangle") {
|
||||
fn fill_mode(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
session.tool.fill_mode = match strp(params, "mode").unwrap_or("triangle") {
|
||||
"triangle" => FillMode::Triangle,
|
||||
"polygon" => FillMode::Polygon,
|
||||
"uvIsland" | "island" => FillMode::UvIsland,
|
||||
"mesh" => FillMode::Mesh,
|
||||
other => return Err(bad("tool.fillMode", format!("unknown fill mode `{other}`"))),
|
||||
};
|
||||
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
fn fill_selection(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
match strp(params, "hitTest") {
|
||||
None => {}
|
||||
Some("intersection") => session.tool.fill_hit_test = FillHitTest::Intersection,
|
||||
Some("containedCenter") => session.tool.fill_hit_test = FillHitTest::ContainedCenter,
|
||||
Some(other) => return Err(bad("tool.fillSelection", format!("unknown hit-test `{other}` (intersection or containedCenter)"))),
|
||||
}
|
||||
if let Some(visible_only) = boolp(params, "visibleOnly") {
|
||||
session.tool.fill_visible_only = visible_only;
|
||||
}
|
||||
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
@@ -369,22 +406,48 @@ fn stroke(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "stamps": stamps }))
|
||||
}
|
||||
|
||||
fn click(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (Some(x), Some(y)) = (f32p(p, "x"), f32p(p, "y")) else { return Err(bad("tool.click", "`x` and `y` are required")) };
|
||||
let vp = viewport_of(s, p);
|
||||
let out = match s.tool.tool {
|
||||
Tool::PolygonFill => json!({ "triangles": s.polygon_fill(Vec2::new(x, y), vp)? }),
|
||||
fn click(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
if session.tool.tool == Tool::PolygonFill
|
||||
&& let Some(triangles) = polygon_fill_click(session, params)?
|
||||
{
|
||||
session.update();
|
||||
return Ok(json!({ "triangles": triangles }));
|
||||
}
|
||||
|
||||
let (Some(x), Some(y)) = (f32p(params, "x"), f32p(params, "y")) else { return Err(bad("tool.click", "`x` and `y` are required")) };
|
||||
|
||||
let point = Vec2::new(x, y);
|
||||
let viewport = viewport_of(session, params);
|
||||
let out = match session.tool.tool {
|
||||
Tool::PolygonFill => json!({ "triangles": session.polygon_fill(point, viewport)? }),
|
||||
Tool::ColorPicker => {
|
||||
let v = s.color_pick(Vec2::new(x, y), vp)?;
|
||||
json!(v.iter().map(|(c, v)| (c.id().to_string(), json!(v))).collect::<serde_json::Map<_, _>>())
|
||||
let picked = session.color_pick(point, viewport)?;
|
||||
json!(picked.iter().map(|(channel, value)| (channel.id().to_string(), json!(value))).collect::<serde_json::Map<_, _>>())
|
||||
}
|
||||
Tool::GeometryMask => crate::instance_cmds::toggle_part_at(s, Vec2::new(x, y), vp)?,
|
||||
_ => json!({ "stamps": s.stroke_points(&[Vec2::new(x, y)], vp)? }),
|
||||
Tool::GeometryMask => crate::instance_cmds::toggle_part_at(session, point, viewport)?,
|
||||
_ => json!({ "stamps": session.stroke_points(&[point], viewport)? }),
|
||||
};
|
||||
s.update();
|
||||
session.update();
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The polygon fill forms of `tool.click` besides a plain `{x, y}` point: None for that point
|
||||
fn polygon_fill_click(session: &mut Session, params: &Value) -> Result<Option<usize>> {
|
||||
let screen_box = (f32p(params, "x0"), f32p(params, "y0"), f32p(params, "x1"), f32p(params, "y1"));
|
||||
let given = |keys: &[&str]| keys.iter().any(|key| params.get(*key).is_some());
|
||||
let filled = match (pair(params, "uv0"), pair(params, "uv1"), pair(params, "uv"), screen_box) {
|
||||
(Some(corner), Some(opposite), ..) => session.polygon_fill_box_uv(corner.into(), opposite.into())?,
|
||||
_ if given(&["uv0", "uv1"]) => return Err(bad("tool.click", "a UV box needs `uv0` and `uv1` as [u, v]")),
|
||||
(_, _, Some(uv), _) => session.polygon_fill_uv(uv.into())?,
|
||||
_ if given(&["uv"]) => return Err(bad("tool.click", "a 2D view point needs `uv` as [u, v]")),
|
||||
(.., (Some(x0), Some(y0), Some(x1), Some(y1))) => session.polygon_fill_box(Vec2::new(x0, y0), Vec2::new(x1, y1), viewport_of(session, params))?,
|
||||
_ if given(&["x0", "y0", "x1", "y1"]) => return Err(bad("tool.click", "a screen box needs numbers `x0`, `y0`, `x1` and `y1`")),
|
||||
_ => return Ok(None),
|
||||
};
|
||||
|
||||
Ok(Some(filled))
|
||||
}
|
||||
|
||||
fn stroke_uv(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let points = points_param("tool.strokeUv", p, "points")?.ok_or_else(|| bad("tool.strokeUv", "`points` must be an array of [u, v]"))?;
|
||||
let tiles = s.stroke_uv_points(&points)?;
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
//! Triangles of one material grouped into the pieces polygon fill selects and fills.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::hash::Hash;
|
||||
|
||||
use texturecraft_geom::Mesh;
|
||||
|
||||
/// A material's triangles split into groups joined across shared edges
|
||||
pub struct TrianglePartition {
|
||||
/// The triangles of each group
|
||||
pub groups: Vec<Vec<u32>>,
|
||||
/// The index of each triangle's group
|
||||
group_of: HashMap<u32, usize>,
|
||||
}
|
||||
|
||||
impl TrianglePartition {
|
||||
/// Group `material`'s triangles of `mesh`: two triangles join when `edges` names a key for both
|
||||
pub fn new<K: Eq + Hash + Clone>(mesh: &Mesh, material: usize, edges: impl Fn(&Mesh, usize) -> Vec<K>) -> TrianglePartition {
|
||||
// Each triangle's edges once, in mesh order so the groups come out the same every time
|
||||
let triangles: Vec<u32> = mesh.triangles_of(material).map(|triangle| triangle as u32).collect();
|
||||
let position_of: HashMap<u32, usize> = triangles.iter().enumerate().map(|(position, triangle)| (*triangle, position)).collect();
|
||||
let mut edge_lists: Vec<Vec<K>> = triangles.iter().map(|triangle| edges(mesh, *triangle as usize)).collect();
|
||||
let mut by_edge: HashMap<K, Vec<u32>> = HashMap::new();
|
||||
for (triangle, triangle_edges) in triangles.iter().zip(&edge_lists) {
|
||||
for edge in triangle_edges {
|
||||
by_edge.entry(edge.clone()).or_default().push(*triangle);
|
||||
}
|
||||
}
|
||||
|
||||
let mut groups = Vec::new();
|
||||
let mut group_of = HashMap::with_capacity(triangles.len());
|
||||
for &start in &triangles {
|
||||
if group_of.contains_key(&start) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut members = Vec::new();
|
||||
let mut stack = vec![start];
|
||||
group_of.insert(start, groups.len());
|
||||
while let Some(triangle) = stack.pop() {
|
||||
members.push(triangle);
|
||||
let triangle_edges = position_of.get(&triangle).and_then(|position| edge_lists.get_mut(*position)).map(std::mem::take).unwrap_or_default();
|
||||
// Visit a shared edge once, including when many collapsed faces share the same key
|
||||
for neighbour in triangle_edges.iter().flat_map(|edge| by_edge.remove(edge).into_iter().flatten()) {
|
||||
if let std::collections::hash_map::Entry::Vacant(entry) = group_of.entry(neighbour) {
|
||||
entry.insert(groups.len());
|
||||
stack.push(neighbour);
|
||||
}
|
||||
}
|
||||
}
|
||||
groups.push(members);
|
||||
}
|
||||
TrianglePartition { groups, group_of }
|
||||
}
|
||||
|
||||
/// The index in [`TrianglePartition::groups`] of the group holding `triangle` (None for a triangle of another material)
|
||||
pub fn index_of(&self, triangle: u32) -> Option<usize> {
|
||||
self.group_of.get(&triangle).copied()
|
||||
}
|
||||
|
||||
/// The group holding `triangle` (None for a triangle of another material)
|
||||
pub fn group(&self, triangle: u32) -> Option<&[u32]> {
|
||||
self.index_of(triangle).and_then(|group| self.groups.get(group)).map(Vec::as_slice)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use texturecraft_geom::primitives;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn triangles_sharing_a_key_join_one_group() {
|
||||
let mesh = primitives::plane(2.0, 2);
|
||||
let singles = TrianglePartition::new(&mesh, 0, |_, _| Vec::<u32>::new());
|
||||
let pairs = TrianglePartition::new(&mesh, 0, |_, triangle| vec![triangle / 2]);
|
||||
|
||||
assert_eq!(singles.groups.len(), mesh.triangle_count());
|
||||
assert_eq!(pairs.groups.len(), mesh.triangle_count() / 2);
|
||||
assert_eq!(pairs.group(3).map(<[u32]>::len), Some(2));
|
||||
assert_eq!(pairs.group(99), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_edges_keep_transitive_neighbors() {
|
||||
let mesh = primitives::plane(2.0, 4);
|
||||
let groups = TrianglePartition::new(&mesh, 0, |_, triangle| vec![triangle / 4, (triangle + 1) / 4]);
|
||||
|
||||
assert_eq!(groups.groups.len(), 1);
|
||||
assert_eq!(groups.group(0).unwrap().len(), mesh.triangle_count());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "release performance measurement"]
|
||||
fn benchmark_shared_edges() {
|
||||
use std::hint::black_box;
|
||||
use std::time::Instant;
|
||||
|
||||
for subdivisions in [32, 64] {
|
||||
let mesh = primitives::plane(2.0, subdivisions);
|
||||
for collapsed in [false, true] {
|
||||
let mut times = Vec::new();
|
||||
for _ in 0..5 {
|
||||
let start = Instant::now();
|
||||
let groups = TrianglePartition::new(&mesh, 0, |mesh, triangle| {
|
||||
if collapsed {
|
||||
vec![(0, 0); 3]
|
||||
} else {
|
||||
let [first, second, third] = mesh.tri(triangle).unwrap();
|
||||
[(first, second), (second, third), (third, first)].map(|(from, to)| (from.min(to), from.max(to))).to_vec()
|
||||
}
|
||||
});
|
||||
assert_eq!(groups.groups.len(), 1);
|
||||
black_box(groups);
|
||||
times.push(start.elapsed().as_secs_f64() * 1000.0);
|
||||
}
|
||||
times.sort_by(f64::total_cmp);
|
||||
eprintln!("{} triangles, collapsed={collapsed}, median={:.3} ms, range={:.3}..{:.3} ms", mesh.triangle_count(), times[2], times[0], times[4]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
//! Where a stroke in the 2D view is between pointer samples.
|
||||
|
||||
use texturecraft_geom::glam::Vec2;
|
||||
|
||||
/// A 2D view stroke's progress: its last point, the distance carried to the next stamp and the stamps so far.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub(crate) struct UvStrokeState {
|
||||
/// The last sample's texture coordinates (None before the first sample).
|
||||
pub last: Option<Vec2>,
|
||||
/// Distance from the last stamp to the last sample, at most one stamp step.
|
||||
pub carry: f32,
|
||||
/// Stamps so far: the next stamp's seed, so noise alphas don't repeat from sample to sample.
|
||||
pub stamps: u32,
|
||||
}
|
||||
@@ -39,61 +39,69 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
]
|
||||
}
|
||||
|
||||
fn tile_resolution(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "textureSet.tile.resolution";
|
||||
let ts = ts_param(s, p, CMD)?;
|
||||
let tile = u64p(p, "tile").and_then(|t| u32::try_from(t).ok()).ok_or_else(|| bad(CMD, "`tile` (a UDIM number) is required"))?;
|
||||
let r = u64p(p, "resolution").ok_or_else(|| bad(CMD, "`resolution` is required"))?;
|
||||
let r = check_resolution(u32::try_from(r).unwrap_or(0))?;
|
||||
let set = s.doc.project.texture_set(ts)?;
|
||||
if !set.uv_tiles.contains(&tile) {
|
||||
return Err(bad(CMD, format!("texture set \"{}\" has no UV tile {tile} (tiles: {:?})", set.name, set.uv_tiles)));
|
||||
fn tile_resolution(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
const COMMAND: &str = "textureSet.tile.resolution";
|
||||
let texture_set_index = ts_param(session, params, COMMAND)?;
|
||||
let tile = u64p(params, "tile").and_then(|tile| u32::try_from(tile).ok()).ok_or_else(|| bad(COMMAND, "`tile` (a UDIM number) is required"))?;
|
||||
let resolution = u64p(params, "resolution").ok_or_else(|| bad(COMMAND, "`resolution` is required"))?;
|
||||
let resolution = check_resolution(u32::try_from(resolution).unwrap_or(0))?;
|
||||
let texture_set = session.doc.project.texture_set(texture_set_index)?;
|
||||
if !texture_set.uv_tiles.contains(&tile) {
|
||||
return Err(bad(COMMAND, format!("texture set \"{}\" has no UV tile {tile} (tiles: {:?})", texture_set.name, texture_set.uv_tiles)));
|
||||
}
|
||||
if set.tile_resolution(tile) == r {
|
||||
return Ok(json!({ "ts": ts, "tile": tile, "resolution": r, "size": set.size() }));
|
||||
|
||||
let removes_override = resolution == texture_set.resolution && texture_set.tile_resolutions.contains_key(&tile);
|
||||
if texture_set.tile_resolution(tile) == resolution && !removes_override {
|
||||
return Ok(json!({ "ts": texture_set_index, "tile": tile, "resolution": resolution, "size": texture_set.size() }));
|
||||
}
|
||||
s.cancel_stroke();
|
||||
let size = s.edit("UV tile resolution", |s| {
|
||||
let set = s.doc.project.texture_set_mut(ts)?;
|
||||
let old = set.clone();
|
||||
if r == set.resolution {
|
||||
set.tile_resolutions.remove(&tile);
|
||||
|
||||
session.cancel_stroke();
|
||||
let size = session.edit("UV tile resolution", |session| {
|
||||
let texture_set = session.doc.project.texture_set_mut(texture_set_index)?;
|
||||
let previous = texture_set.clone();
|
||||
if resolution == texture_set.resolution {
|
||||
texture_set.tile_resolutions.remove(&tile);
|
||||
} else {
|
||||
set.tile_resolutions.insert(tile, r);
|
||||
texture_set.tile_resolutions.insert(tile, resolution);
|
||||
}
|
||||
check_size(texture_set)?;
|
||||
let size = texture_set.size();
|
||||
if previous.tile_resolution(tile) != resolution {
|
||||
relayout(&mut session.doc, texture_set_index, &previous, &mut session.log)?;
|
||||
}
|
||||
check_size(set)?;
|
||||
let size = set.size();
|
||||
relayout(&mut s.doc, ts, &old, &mut s.log)?;
|
||||
Ok(size)
|
||||
})?;
|
||||
Ok(json!({ "ts": ts, "tile": tile, "resolution": r, "size": size }))
|
||||
Ok(json!({ "ts": texture_set_index, "tile": tile, "resolution": resolution, "size": size }))
|
||||
}
|
||||
|
||||
fn uv_tiles(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "textureSet.uvTiles";
|
||||
let ts = ts_param(s, p, CMD)?;
|
||||
let enabled = boolp(p, "enabled").ok_or_else(|| bad(CMD, "`enabled` (true or false) is required"))?;
|
||||
let set = s.doc.project.texture_set(ts)?;
|
||||
fn uv_tiles(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
const COMMAND: &str = "textureSet.uvTiles";
|
||||
let texture_set_index = ts_param(session, params, COMMAND)?;
|
||||
let enabled = boolp(params, "enabled").ok_or_else(|| bad(COMMAND, "`enabled` (true or false) is required"))?;
|
||||
let texture_set = session.doc.project.texture_set(texture_set_index)?;
|
||||
let tiles = if enabled {
|
||||
detect_uv_tiles(&s.source, set.material, Some(true), &mut Vec::new()).map_err(|e| bad(CMD, format!("texture set \"{}\": {e}", set.name)))?
|
||||
detect_uv_tiles(&session.source, texture_set.material, Some(true), &mut Vec::new())
|
||||
.map_err(|error| bad(COMMAND, format!("texture set \"{}\": {error}", texture_set.name)))?
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
if tiles == set.uv_tiles {
|
||||
return Ok(json!({ "ts": ts, "uvTiles": tiles, "dropped": [] }));
|
||||
if tiles == texture_set.uv_tiles {
|
||||
return Ok(json!({ "ts": texture_set_index, "uvTiles": tiles, "dropped": [] }));
|
||||
}
|
||||
// Leaving UV tile mode keeps tile 1001 (UV 0..1), the area a classic set paints.
|
||||
let dropped: Vec<u32> = set.uv_tiles.iter().copied().filter(|t| !enabled && *t != 1001).collect();
|
||||
s.cancel_stroke();
|
||||
s.edit(if enabled { "Use UV tiles" } else { "Stop using UV tiles" }, |s| {
|
||||
let set = s.doc.project.texture_set_mut(ts)?;
|
||||
let old = set.clone();
|
||||
set.tile_resolutions.retain(|u, _| tiles.contains(u));
|
||||
set.uv_tiles = tiles.clone();
|
||||
check_size(set)?;
|
||||
relayout(&mut s.doc, ts, &old, &mut s.log)
|
||||
|
||||
// Leaving UV tile mode keeps tile 1001, the area a classic set paints
|
||||
let dropped: Vec<u32> = texture_set.uv_tiles.iter().copied().filter(|tile| !enabled && *tile != 1001).collect();
|
||||
session.cancel_stroke();
|
||||
session.edit(if enabled { "Use UV tiles" } else { "Stop using UV tiles" }, |session| {
|
||||
let texture_set = session.doc.project.texture_set_mut(texture_set_index)?;
|
||||
let previous = texture_set.clone();
|
||||
texture_set.tile_resolutions.retain(|tile, _| tiles.contains(tile));
|
||||
texture_set.bake_excluded_tiles.retain(|tile| tiles.contains(tile));
|
||||
texture_set.uv_tiles = tiles.clone();
|
||||
check_size(texture_set)?;
|
||||
relayout(&mut session.doc, texture_set_index, &previous, &mut session.log)
|
||||
})?;
|
||||
Ok(json!({ "ts": ts, "uvTiles": tiles, "dropped": dropped }))
|
||||
Ok(json!({ "ts": texture_set_index, "uvTiles": tiles, "dropped": dropped }))
|
||||
}
|
||||
|
||||
/// Mesh UV → normalized atlas position of UV tile layout `set` (None where the layout holds
|
||||
@@ -119,23 +127,30 @@ fn from_layout(set: &TextureSet, a: [f32; 2]) -> Option<[f32; 2]> {
|
||||
(set.uv_tiles.contains(&udim) && local.0 <= scale && local.1 <= scale).then(|| set.from_atlas(&g, a))
|
||||
}
|
||||
|
||||
/// Resample texture set `ts`'s painted images and baked maps from layout `old` into the set's
|
||||
/// current layout (inside [`Session::edit`] after changing the set). Notes go to `log`.
|
||||
/// Move painted images into the working layout and baked maps only when the tile grid changes
|
||||
pub(crate) fn relayout(doc: &mut Document, ts: usize, old: &TextureSet, log: &mut Vec<String>) -> Result<()> {
|
||||
let new = doc.project.texture_set(ts)?.clone();
|
||||
let map = |a: [f32; 2]| from_layout(&new, a).and_then(|m| to_layout(old, m));
|
||||
let ((ow, oh), (nw, nh)) = (old.size(), new.size());
|
||||
let texel = |x: f32, y: f32| map([x / nw as f32, y / nh as f32]).map(|o| (o[0] * ow as f32, o[1] * oh as f32));
|
||||
let all = TileImage::new(nw, nh, 1);
|
||||
let map = |uv: [f32; 2]| from_layout(&new, uv).and_then(|mesh_uv| to_layout(old, mesh_uv));
|
||||
let (old_size, new_size) = (old.size(), new.size());
|
||||
let texel = |x: f32, y: f32| map([x / new_size.0 as f32, y / new_size.1 as f32]).map(|uv| (uv[0] * old_size.0 as f32, uv[1] * old_size.1 as f32));
|
||||
let all = TileImage::new(new_size.0, new_size.1, 1);
|
||||
let tiles: Vec<(u32, u32)> = (0..all.tiles_y()).flat_map(|ty| (0..all.tiles_x()).map(move |tx| (tx, ty))).collect();
|
||||
// Blocks and tiles are multiples of 64 texels (resolutions are powers of two ≥ 128), so the
|
||||
// map is affine (or None) over each destination tile.
|
||||
crate::layer_ops::map_set_images(doc, ts, |img, empty| remap_image(img, (nw, nh), empty, &texel, &tiles, true));
|
||||
|
||||
// Atlas blocks align with the 64-texel storage tiles, making each mapping affine
|
||||
crate::layer_ops::map_set_images(doc, ts, |image, empty| remap_image(image, new_size, empty, &texel, &tiles, true));
|
||||
remap_bake_paint(doc, ts, old, &new, &map)?;
|
||||
if let Some(baked) = doc.baked.get(&ts) {
|
||||
match remap_baked(baked, old, &new, &map) {
|
||||
Some(b) => {
|
||||
doc.baked.insert(ts, b);
|
||||
|
||||
if old.uv_tiles != new.uv_tiles
|
||||
&& let Some(baked) = doc.baked.get(&ts)
|
||||
{
|
||||
let mut old_bake = old.clone();
|
||||
let mut new_bake = new.clone();
|
||||
old_bake.tile_resolutions.clear();
|
||||
new_bake.tile_resolutions.clear();
|
||||
let bake_map = |uv| from_layout(&new_bake, uv).and_then(|mesh_uv| to_layout(&old_bake, mesh_uv));
|
||||
match remap_baked(baked, &old_bake, &new_bake, &bake_map) {
|
||||
Some(baked) => {
|
||||
doc.baked.insert(ts, baked);
|
||||
}
|
||||
None => {
|
||||
doc.baked.remove(&ts);
|
||||
@@ -326,6 +341,28 @@ mod tests {
|
||||
assert!(execute(&mut s, "textureSet.tile.resolution", &json!({"tile": 1001, "resolution": 100})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_a_tile_override_at_the_sets_current_resolution_restores_inheritance() {
|
||||
let mut session = udim_session();
|
||||
execute(&mut session, "textureSet.tile.resolution", &json!({"tile": 1002, "resolution": 128})).unwrap();
|
||||
execute(&mut session, "textureSet.resolution", &json!({"resolution": 128})).unwrap();
|
||||
let before = session.doc.project.clone();
|
||||
let history_steps = session.history_labels().len();
|
||||
|
||||
execute(&mut session, "textureSet.tile.resolution", &json!({"tile": 1002, "resolution": 128})).unwrap();
|
||||
|
||||
assert!(session.doc.project.texture_sets[0].tile_resolutions.is_empty());
|
||||
assert_eq!(session.history_labels().len(), history_steps + 1);
|
||||
let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap();
|
||||
assert!(reopened.doc.project.texture_sets[0].tile_resolutions.is_empty());
|
||||
session.undo().unwrap();
|
||||
assert_eq!(session.doc.project, before);
|
||||
session.redo().unwrap();
|
||||
execute(&mut session, "textureSet.resolution", &json!({"resolution": 256})).unwrap();
|
||||
assert_eq!(session.doc.project.texture_sets[0].tile_resolution(1002), 256);
|
||||
assert_eq!(session.doc.project.texture_sets[0].bake, before.texture_sets[0].bake);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_writes_each_tile_at_its_own_size() {
|
||||
let mut s = udim_session();
|
||||
|
||||
File renamed without changes.
@@ -0,0 +1,130 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::json;
|
||||
use texturecraft_engine::bake::Progress;
|
||||
use texturecraft_engine::core::BakedMap;
|
||||
use texturecraft_engine::geom::{NO_TRI, UvGBuffer, primitives};
|
||||
use texturecraft_engine::{Session, execute};
|
||||
|
||||
fn session() -> Session {
|
||||
let mut session = Session::new_project("Bake detail", primitives::udim_plane(), "builtin:udim_plane", None, 256).unwrap();
|
||||
execute(&mut session, "bake.settings", &json!({"resolution": 128, "maps": ["position"], "dilation": 0, "patch": {"common": {"apply_diffusion": false}}}))
|
||||
.unwrap();
|
||||
session
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn working_tile_resolution_preserves_bake_samples_and_pixels() {
|
||||
let mut session = session();
|
||||
let original = session.bake_task(0).unwrap().run(&Progress::new()).unwrap();
|
||||
execute(&mut session, "textureSet.tile.resolution", &json!({"tile": 1002, "resolution": 128})).unwrap();
|
||||
let task = session.bake_task(0).unwrap();
|
||||
let output = task.run(&Progress::new()).unwrap();
|
||||
assert_eq!((output.resolution, output.height), (256, 128));
|
||||
|
||||
let gbuffer = UvGBuffer::new(&task.mesh, task.material, output.resolution, output.height);
|
||||
let mut samples = [0usize; 2];
|
||||
for (index, triangle) in gbuffer.tri.iter().enumerate() {
|
||||
if *triangle != NO_TRI {
|
||||
samples[(index % 256) / 128] += 1;
|
||||
}
|
||||
}
|
||||
assert_eq!(samples, [128 * 128; 2], "each tile receives the full Bake Output Size");
|
||||
assert_eq!(output.maps, original.maps);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changing_working_resolution_never_resamples_stored_bakes() {
|
||||
let mut session = session();
|
||||
let output = session.bake_task(0).unwrap().run(&Progress::new()).unwrap();
|
||||
session.apply_bake(0, output).unwrap();
|
||||
let original = session.doc.baked[&0].clone();
|
||||
for resolution in [128, 512, 256] {
|
||||
execute(&mut session, "textureSet.tile.resolution", &json!({"tile": 1002, "resolution": resolution})).unwrap();
|
||||
let current = &session.doc.baked[&0];
|
||||
assert!(Arc::ptr_eq(¤t.maps[&BakedMap::Position], &original.maps[&BakedMap::Position]), "working resize must retain the bake buffer");
|
||||
assert_eq!(current, &original);
|
||||
let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap();
|
||||
assert_eq!(reopened.doc.baked[&0], original);
|
||||
}
|
||||
session.undo().unwrap();
|
||||
assert_eq!(session.doc.baked[&0], original);
|
||||
session.redo().unwrap();
|
||||
assert_eq!(session.doc.baked[&0], original);
|
||||
|
||||
for resolution in [512, 128] {
|
||||
execute(&mut session, "textureSet.resolution", &json!({"resolution": resolution})).unwrap();
|
||||
assert!(Arc::ptr_eq(&session.doc.baked[&0].maps[&BakedMap::Position], &original.maps[&BakedMap::Position]));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rectangular_bakes_and_excluded_vertical_tiles_ignore_working_resolution() {
|
||||
let mut mesh = primitives::udim_plane();
|
||||
let second_plane = mesh.uvs.len() / 2;
|
||||
for uv in mesh.uvs.iter_mut().skip(second_plane) {
|
||||
uv.x -= 1.0;
|
||||
uv.y -= 1.0;
|
||||
}
|
||||
let mut session = Session::new_project("Vertical bake", mesh, "builtin:udim_plane", None, 256).unwrap();
|
||||
execute(
|
||||
&mut session,
|
||||
"bake.settings",
|
||||
&json!({"resolution": 64, "maps": ["position"], "dilation": 0, "patch": {"common": {"resolution_height": "R128", "apply_diffusion": false}}}),
|
||||
)
|
||||
.unwrap();
|
||||
let original = session.bake_task(0).unwrap().run(&Progress::new()).unwrap();
|
||||
assert_eq!((original.resolution, original.height), (64, 256));
|
||||
let pixels = original.maps.clone();
|
||||
session.apply_bake(0, original).unwrap();
|
||||
execute(&mut session, "textureSet.tile.resolution", &json!({"tile": 1011, "resolution": 128})).unwrap();
|
||||
execute(&mut session, "bake.tile.set", &json!({"tile": 1011, "enabled": false})).unwrap();
|
||||
let output = session.bake_task(0).unwrap().run(&Progress::new()).unwrap();
|
||||
assert_eq!(output.maps, pixels, "rebaked and excluded tiles both keep their full rectangular detail");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn imported_mesh_maps_display_and_export_the_entire_overridden_tile() {
|
||||
use texturecraft_engine::compose::{DisplayKind, tile_bytes};
|
||||
use texturecraft_engine::formats::export::{Dest, ExportOptions, ExportPreset, FileFormat, MapSpec, SourceRef};
|
||||
|
||||
let mut session = session();
|
||||
execute(&mut session, "textureSet.tile.resolution", &json!({"tile": 1002, "resolution": 128})).unwrap();
|
||||
let image = image::GrayImage::from_fn(128, 128, |x, y| image::Luma([(x + y) as u8]));
|
||||
let mut bytes = Vec::new();
|
||||
image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap();
|
||||
for tile in [1001, 1002] {
|
||||
session.import_resource_bytes(&format!("ao.{tile}.png"), bytes.clone()).unwrap();
|
||||
}
|
||||
execute(&mut session, "textureSet.meshMap.set", &json!({"map": "ambientOcclusion", "image": "ao.1001.png"})).unwrap();
|
||||
while session.update() {}
|
||||
|
||||
let baked = &session.doc.baked[&0];
|
||||
let map = BakedMap::AmbientOcclusion;
|
||||
assert!((baked.scalar(map, 248, 120, (256, 128)).unwrap() - 240.0 / 255.0).abs() < 0.001);
|
||||
let composite = &session.caches[0].composite;
|
||||
let display = tile_bytes(composite, baked, DisplayKind::Orm, 5, 1);
|
||||
assert_eq!(display[((56 * 64 + 56) * 4) as usize], 240, "the viewport samples the far corner of the smaller working tile");
|
||||
|
||||
let options = ExportOptions::new(ExportPreset {
|
||||
name: "Bake detail".into(),
|
||||
maps: vec![MapSpec {
|
||||
file: "ao.$udim".into(),
|
||||
format: FileFormat::Png,
|
||||
bit_depth: 8,
|
||||
channels: vec![(Dest::L, SourceRef::Baked { map, component: 0 })],
|
||||
}],
|
||||
});
|
||||
let files = session.export_files(&[0], &options).unwrap();
|
||||
let file = files.iter().find(|file| file.name == "ao.1002.png").unwrap();
|
||||
let exported = image::load_from_memory(&file.bytes).unwrap().to_luma8();
|
||||
assert_eq!(exported.dimensions(), (128, 128));
|
||||
assert_eq!(exported.get_pixel(120, 120)[0], 240);
|
||||
assert_eq!(exported.get_pixel(10, 10)[0], 20);
|
||||
|
||||
let layer = session.doc.project.texture_sets[0].stack[0];
|
||||
execute(&mut session, "mask.add.black", &json!({"layer": layer.0})).unwrap();
|
||||
execute(&mut session, "effect.add.generator", &json!({"layer": layer.0, "generator": "ambientOcclusion"})).unwrap();
|
||||
let mask = session.mask_at(layer, &[(376, 120), (266, 10)]).unwrap();
|
||||
assert_eq!(mask, vec![1.0, 0.0], "generators sample the whole bake through the working layout");
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
use serde_json::json;
|
||||
use texturecraft_engine::core::{BakeResolution, BakeSettings};
|
||||
use texturecraft_engine::geom::primitives;
|
||||
use texturecraft_engine::{Session, execute};
|
||||
|
||||
fn session() -> Session {
|
||||
let mut session = Session::new_project("Bake settings", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
|
||||
let second = &mut session.doc.project.texture_sets[1].bake;
|
||||
second.common.is_enabled = false;
|
||||
second.common.resolution = BakeResolution::R128;
|
||||
second.common.resolution_height = Some(BakeResolution::R256);
|
||||
second.maps.ao.is_enabled = false;
|
||||
second.maps.ao.parameters.rays.min_distance = 0.25;
|
||||
second.maps.ao.parameters.rays.rays = 16;
|
||||
second.maps.height.parameters.scaling_divisor = 2.0;
|
||||
session
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_settings_patch_preserves_other_fields_and_is_one_undo_step() {
|
||||
let mut session = session();
|
||||
let before = session.doc.project.clone();
|
||||
let history_steps = session.history_labels().len();
|
||||
let patch = json!({"maps": {"ao": {"parameters": {"rays": {"rays": 128}}}}});
|
||||
|
||||
let result = execute(&mut session, "bake.settings", &json!({"ts": "all", "patch": patch})).unwrap();
|
||||
|
||||
let mut expected = before.clone();
|
||||
for texture_set in &mut expected.texture_sets {
|
||||
texture_set.bake.maps.ao.parameters.rays.rays = 128;
|
||||
}
|
||||
assert_eq!(session.doc.project, expected);
|
||||
assert_eq!(result.as_array().unwrap().len(), 2);
|
||||
assert_eq!(result[1]["model"], json!(expected.texture_sets[1].bake));
|
||||
assert_eq!(session.history_labels().len(), history_steps + 1);
|
||||
let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap();
|
||||
assert_eq!(reopened.doc.project.texture_sets, expected.texture_sets);
|
||||
|
||||
session.undo().unwrap();
|
||||
assert_eq!(session.doc.project, before);
|
||||
session.redo().unwrap();
|
||||
assert_eq!(session.doc.project, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_patch_validates_every_target_before_changing_any() {
|
||||
let mut session = session();
|
||||
let before = session.doc.project.clone();
|
||||
let history = session.history_labels();
|
||||
|
||||
// This maximum is valid for the active set but below the second set's minimum
|
||||
let patch = json!({"maps": {"ao": {"parameters": {"rays": {"max_distance": 0.1}}}}});
|
||||
let error = execute(&mut session, "bake.settings", &json!({"ts": "all", "patch": patch})).unwrap_err();
|
||||
assert!(error.to_string().contains("minimum occluder distance"), "{error}");
|
||||
assert_eq!(session.doc.project, before);
|
||||
assert_eq!(session.history_labels(), history);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_patch_rejects_unknown_fields_and_invalid_shapes() {
|
||||
let mut session = session();
|
||||
let before = session.doc.project.clone();
|
||||
let history = session.history_labels();
|
||||
|
||||
for patch in [
|
||||
json!(null),
|
||||
json!([]),
|
||||
json!({"unknown": 1}),
|
||||
json!({"common": null}),
|
||||
json!({"common": {"resolution": "invalid"}}),
|
||||
json!({"common": {"antialiasing": true}}),
|
||||
json!({"maps": {"ao": {"parameters": {"rays": {"rays": 257}}}}}),
|
||||
json!({"maps": {"ao": {"parameters": {"rays": {"rayz": 128}}}}}),
|
||||
] {
|
||||
assert!(execute(&mut session, "bake.settings", &json!({"ts": "all", "patch": patch})).is_err(), "{patch}");
|
||||
assert_eq!(session.doc.project, before);
|
||||
assert_eq!(session.history_labels(), history);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_patch_can_clear_optional_height_and_keeps_target_selection() {
|
||||
let mut session = session();
|
||||
let first = session.doc.project.texture_sets[0].bake.clone();
|
||||
let mut second = session.doc.project.texture_sets[1].bake.clone();
|
||||
let patch = json!({"common": {"resolution_height": null}});
|
||||
|
||||
execute(&mut session, "bake.settings", &json!({"ts": [1], "patch": patch})).unwrap();
|
||||
|
||||
second.common.resolution_height = None;
|
||||
assert_eq!(session.doc.project.texture_sets[0].bake, first);
|
||||
assert_eq!(session.doc.project.texture_sets[1].bake, second);
|
||||
|
||||
let history_steps = session.history_labels().len();
|
||||
execute(&mut session, "bake.settings", &json!({"ts": "all", "patch": {}})).unwrap();
|
||||
execute(&mut session, "bake.settings", &json!({"ts": 1, "patch": patch})).unwrap();
|
||||
assert_eq!(session.history_labels().len(), history_steps);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_patch_can_reset_one_section_without_replacing_other_settings() {
|
||||
let mut session = session();
|
||||
let mut expected = session.doc.project.clone();
|
||||
let defaults = BakeSettings::default().maps.ao.parameters;
|
||||
for texture_set in &mut expected.texture_sets {
|
||||
texture_set.bake.maps.ao.parameters = defaults;
|
||||
}
|
||||
|
||||
execute(&mut session, "bake.settings", &json!({"ts": "all", "patch": {"maps": {"ao": {"parameters": defaults}}}})).unwrap();
|
||||
|
||||
assert_eq!(session.doc.project, expected);
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_engine::bake::Progress;
|
||||
use texturecraft_engine::compose::BakedMaps;
|
||||
use texturecraft_engine::core::BakedMap;
|
||||
use texturecraft_engine::geom::primitives;
|
||||
use texturecraft_engine::{Session, execute};
|
||||
|
||||
fn session() -> Session {
|
||||
let mut session = Session::new_project("Tile baking", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap();
|
||||
execute(&mut session, "bake.settings", &json!({"resolution": 32, "maps": ["ambientOcclusion"], "rays": 2})).unwrap();
|
||||
session
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tile_selection_is_inspectable_saved_and_undoable() {
|
||||
let mut session = session();
|
||||
let before = session.doc.project.clone();
|
||||
let result = execute(&mut session, "bake.tile.set", &json!({"tile": 1002, "enabled": false})).unwrap();
|
||||
assert_eq!(result, json!({"ts": 0, "tile": 1002, "enabled": false}));
|
||||
let selected = session.doc.project.clone();
|
||||
let inspected = execute(&mut session, "textureSet.inspect", &Value::Null).unwrap();
|
||||
assert_eq!(inspected["tiles"][0]["bakeEnabled"], true);
|
||||
assert_eq!(inspected["tiles"][1]["bakeEnabled"], false);
|
||||
let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap();
|
||||
assert_eq!(reopened.doc.project, selected);
|
||||
|
||||
let history = session.history_labels();
|
||||
execute(&mut session, "bake.tile.set", &json!({"tile": 1002, "enabled": false})).unwrap();
|
||||
assert_eq!(session.history_labels(), history);
|
||||
session.undo().unwrap();
|
||||
assert_eq!(session.doc.project, before);
|
||||
session.redo().unwrap();
|
||||
assert_eq!(session.doc.project, selected);
|
||||
|
||||
for params in [json!({}), json!({"tile": 1003, "enabled": false}), json!({"tile": u64::MAX, "enabled": false}), json!({"tile": 1001, "enabled": 1})] {
|
||||
assert!(execute(&mut session, "bake.tile.set", ¶ms).is_err());
|
||||
assert_eq!(session.doc.project, selected);
|
||||
assert_eq!(session.history_labels(), history);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partial_bake_preserves_unchecked_tiles_and_uses_the_workers_selection() {
|
||||
let mut session = session();
|
||||
session.doc.baked.insert(0, BakedMaps { resolution: 64, maps: [(BakedMap::AmbientOcclusion, Arc::new(vec![0.25; 64 * 32]))].into() });
|
||||
execute(&mut session, "bake.tile.set", &json!({"tile": 1002, "enabled": false})).unwrap();
|
||||
let mut task = session.bake_task(0).unwrap();
|
||||
task.tracer = None;
|
||||
|
||||
// Editing the checkboxes while a bake runs affects the next bake
|
||||
execute(&mut session, "bake.tile.set", &json!({"tile": 1002, "enabled": true})).unwrap();
|
||||
execute(&mut session, "bake.tile.set", &json!({"tile": 1001, "enabled": false})).unwrap();
|
||||
let before = session.doc.baked.clone();
|
||||
let output = task.run(&Progress::new()).unwrap();
|
||||
session.apply_bake(0, output).unwrap();
|
||||
|
||||
let pixels = &session.doc.baked[&0].maps[&BakedMap::AmbientOcclusion];
|
||||
for row in pixels.chunks_exact(64) {
|
||||
assert!(row[..32].iter().all(|value| *value > 0.99));
|
||||
assert!(row[32..].iter().all(|value| *value == 0.25));
|
||||
}
|
||||
session.undo().unwrap();
|
||||
assert_eq!(session.doc.baked, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partial_bake_resizes_retained_tiles_and_unchecked_map_outputs() {
|
||||
let mut session = session();
|
||||
session.doc.baked.insert(
|
||||
0,
|
||||
BakedMaps {
|
||||
resolution: 64,
|
||||
maps: [(BakedMap::AmbientOcclusion, Arc::new(vec![0.25; 64 * 32])), (BakedMap::Normal, Arc::new(vec![0.4; 64 * 32 * 3]))].into(),
|
||||
},
|
||||
);
|
||||
execute(&mut session, "bake.tile.set", &json!({"tile": 1002, "enabled": false})).unwrap();
|
||||
let result = execute(&mut session, "bake.run", &json!({"resolution": 64, "cpu": true})).unwrap();
|
||||
assert_eq!(result["baked"], json!([0]));
|
||||
|
||||
let baked = &session.doc.baked[&0];
|
||||
assert_eq!((baked.resolution, baked.height(BakedMap::AmbientOcclusion)), (128, 64));
|
||||
for row in baked.maps[&BakedMap::AmbientOcclusion].chunks_exact(128) {
|
||||
assert!(row[..64].iter().all(|value| *value > 0.99));
|
||||
assert!(row[64..].iter().all(|value| *value == 0.25));
|
||||
}
|
||||
assert_eq!(baked.maps[&BakedMap::Normal].len(), 128 * 64 * 3);
|
||||
assert!(baked.maps[&BakedMap::Normal].iter().all(|value| *value == 0.4));
|
||||
let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap();
|
||||
assert_eq!(reopened.doc.baked, session.doc.baked);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tile_selection_preserves_the_correct_udim_row() {
|
||||
let mut mesh = primitives::udim_plane();
|
||||
let second_plane = mesh.uvs.len() / 2;
|
||||
for uv in mesh.uvs.iter_mut().skip(second_plane) {
|
||||
uv.x -= 1.0;
|
||||
uv.y -= 1.0;
|
||||
}
|
||||
let mut session = Session::new_project("Vertical UV tiles", mesh, "builtin:udim_plane", None, 128).unwrap();
|
||||
assert_eq!(session.doc.project.texture_sets[0].uv_tiles, [1001, 1011]);
|
||||
session.doc.baked.insert(0, BakedMaps { resolution: 32, maps: [(BakedMap::AmbientOcclusion, Arc::new(vec![0.25; 32 * 64]))].into() });
|
||||
execute(&mut session, "bake.tile.set", &json!({"tile": 1011, "enabled": false})).unwrap();
|
||||
execute(&mut session, "bake.run", &json!({"resolution": 32, "maps": ["ambientOcclusion"], "rays": 2, "cpu": true})).unwrap();
|
||||
|
||||
let pixels = &session.doc.baked[&0].maps[&BakedMap::AmbientOcclusion];
|
||||
assert!(pixels[..32 * 32].iter().all(|value| *value == 0.25));
|
||||
assert!(pixels[32 * 32..].iter().all(|value| *value > 0.99));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn excluded_tiles_without_previous_pixels_use_neutral_values() {
|
||||
let mut session = session();
|
||||
execute(&mut session, "bake.tile.set", &json!({"tile": 1001, "enabled": false})).unwrap();
|
||||
execute(&mut session, "bake.run", &json!({"maps": ["normal", "ambientOcclusion"], "cpu": true})).unwrap();
|
||||
let baked = &session.doc.baked[&0];
|
||||
for map in [BakedMap::Normal, BakedMap::AmbientOcclusion] {
|
||||
for row in baked.maps[&map].chunks_exact(64 * map.components()) {
|
||||
for pixel in row[..32 * map.components()].chunks_exact(map.components()) {
|
||||
assert_eq!(pixel, &map.neutral()[..map.components()]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_selected_tiles_is_a_noop_and_old_projects_include_every_tile() {
|
||||
let mut session = session();
|
||||
let serialized = serde_json::to_value(&session.doc.project).unwrap();
|
||||
assert!(serialized["texture_sets"][0].get("bake_excluded_tiles").is_none());
|
||||
let legacy: texturecraft_engine::core::Project = serde_json::from_value(serialized).unwrap();
|
||||
assert!(legacy.texture_sets[0].has_enabled_bake_tiles());
|
||||
|
||||
for tile in [1001, 1002] {
|
||||
execute(&mut session, "bake.tile.set", &json!({"tile": tile, "enabled": false})).unwrap();
|
||||
}
|
||||
let before = session.doc.project.clone();
|
||||
let history = session.history_labels();
|
||||
let result = execute(&mut session, "bake.run", &json!({"ts": "selected", "cpu": true})).unwrap();
|
||||
assert_eq!(result["baked"], json!([]));
|
||||
assert_eq!(session.doc.project, before);
|
||||
assert!(session.doc.baked.is_empty());
|
||||
assert_eq!(session.history_labels(), history);
|
||||
assert!(session.bake_task(0).is_err());
|
||||
|
||||
execute(&mut session, "textureSet.uvTiles", &json!({"enabled": false})).unwrap();
|
||||
assert!(session.doc.project.texture_sets[0].bake_excluded_tiles.is_empty());
|
||||
session.undo().unwrap();
|
||||
assert_eq!(session.doc.project, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn partial_bake_timing() {
|
||||
let mut session = session();
|
||||
execute(&mut session, "bake.run", &json!({"resolution": 256, "rays": 64, "cpu": true})).unwrap();
|
||||
for enabled in [true, false] {
|
||||
execute(&mut session, "bake.tile.set", &json!({"tile": 1002, "enabled": enabled})).unwrap();
|
||||
let mut task = session.bake_task(0).unwrap();
|
||||
task.tracer = None;
|
||||
let mut times = Vec::new();
|
||||
for _ in 0..5 {
|
||||
let started = std::time::Instant::now();
|
||||
task.run(&Progress::new()).unwrap();
|
||||
times.push(started.elapsed());
|
||||
}
|
||||
times.sort();
|
||||
eprintln!("{} of 2 UV tiles, 256 square, AO 64 rays, CPU: median {:?}, runs {:?}", if enabled { 2 } else { 1 }, times[2], times);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,309 @@
|
||||
//! Color selection effects: editing their ID colors and picking them from the ID mesh map
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_engine::core::{EffectKind, LayerId};
|
||||
use texturecraft_engine::geom::glam::Vec2;
|
||||
use texturecraft_engine::geom::primitives;
|
||||
use texturecraft_engine::{Session, execute};
|
||||
|
||||
const TOP_LEFT_ID: [u8; 3] = [200, 30, 10];
|
||||
const TOP_RIGHT_ID: [u8; 3] = [10, 200, 30];
|
||||
const BOTTOM_ID: [u8; 3] = [30, 10, 200];
|
||||
const NO_PART: [f32; 3] = [0.0, 0.0, 0.0];
|
||||
|
||||
fn session() -> Session {
|
||||
let mut session = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 256).unwrap();
|
||||
session.viewport = Vec2::new(400.0, 400.0);
|
||||
session.camera.yaw = 0.0;
|
||||
session.camera.pitch = 0.0;
|
||||
session.update();
|
||||
session
|
||||
}
|
||||
|
||||
/// An 8×8 ID map: two parts on the top half, one on the bottom half
|
||||
fn id_map_png() -> Vec<u8> {
|
||||
let image = image::RgbaImage::from_fn(8, 8, |x, y| {
|
||||
let [red, green, blue] = match (x < 4, y < 4) {
|
||||
(true, true) => TOP_LEFT_ID,
|
||||
(false, true) => TOP_RIGHT_ID,
|
||||
_ => BOTTOM_ID,
|
||||
};
|
||||
image::Rgba([red, green, blue, 255])
|
||||
});
|
||||
let mut bytes = Vec::new();
|
||||
image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap();
|
||||
bytes
|
||||
}
|
||||
|
||||
fn stored(id: [u8; 3]) -> [f32; 3] {
|
||||
id.map(|channel| channel as f32 / 255.0)
|
||||
}
|
||||
|
||||
fn assert_close(actual: [f32; 3], expected: [f32; 3]) {
|
||||
assert!(actual.iter().zip(expected).all(|(channel, wanted)| (channel - wanted).abs() < 1e-3), "{actual:?} vs {expected:?}");
|
||||
}
|
||||
|
||||
/// A fill layer masked by a color selection that selects no part yet: (layer, effect)
|
||||
fn masked_layer(session: &mut Session, with_id_map: bool) -> (LayerId, LayerId) {
|
||||
if with_id_map {
|
||||
let image = session.import_resource_bytes("id.png", id_map_png()).unwrap();
|
||||
execute(session, "textureSet.meshMap.set", &json!({"map": "id", "image": image})).unwrap();
|
||||
}
|
||||
|
||||
let layer = LayerId(execute(session, "layer.add.fill", &json!({"color": [0.9, 0.1, 0.1]})).unwrap()["layer"].as_u64().unwrap());
|
||||
execute(session, "mask.add.colorSelection", &json!({"color": NO_PART, "tolerance": 0.05})).unwrap();
|
||||
let effect = session.doc.project.layer(layer).unwrap().mask.as_ref().unwrap().effects[0].id;
|
||||
(layer, effect)
|
||||
}
|
||||
|
||||
fn colors(session: &Session, effect: LayerId) -> Vec<[f32; 3]> {
|
||||
match &session.doc.project.effect(effect).unwrap().1.kind {
|
||||
EffectKind::ColorSelection { colors, .. } => colors.clone(),
|
||||
other => panic!("not a color selection: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_color_picked_on_the_mesh_is_selected_where_it_was_picked() {
|
||||
let mut session = session();
|
||||
let (layer, effect) = masked_layer(&mut session, true);
|
||||
let center = Vec2::new(200.0, 200.0);
|
||||
let hit = session.pick(center, session.viewport).unwrap();
|
||||
let (width, height) = session.caches[0].size;
|
||||
let texel = ((hit.uv.x * width as f32) as u32, (hit.uv.y * height as f32) as u32);
|
||||
assert_eq!(session.mask_at(layer, &[texel]).unwrap(), vec![0.0], "nothing selected before the pick");
|
||||
|
||||
let picked = execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "x": center.x, "y": center.y})).unwrap();
|
||||
|
||||
assert_eq!(picked["index"], json!(1));
|
||||
assert_eq!(colors(&session, effect).len(), 2);
|
||||
assert_eq!(session.mask_at(layer, &[texel]).unwrap(), vec![1.0]);
|
||||
execute(&mut session, "edit.undo", &Value::Null).unwrap();
|
||||
assert_eq!(colors(&session, effect), vec![NO_PART], "one undo step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_uv_pick_adds_the_color_there_or_replaces_one() {
|
||||
let mut session = session();
|
||||
let (_, effect) = masked_layer(&mut session, true);
|
||||
|
||||
execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": [0.25, 0.25]})).unwrap();
|
||||
assert_close(colors(&session, effect)[1], stored(TOP_LEFT_ID));
|
||||
|
||||
let replaced = execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": [0.75, 0.75], "index": 0})).unwrap();
|
||||
assert_eq!(replaced["index"], json!(0));
|
||||
let picked = colors(&session, effect);
|
||||
assert_eq!(picked.len(), 2);
|
||||
assert_close(picked[0], stored(BOTTOM_ID));
|
||||
execute(&mut session, "edit.undo", &Value::Null).unwrap();
|
||||
assert_eq!(colors(&session, effect)[0], NO_PART, "one undo step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_colors_param_replaces_the_list_in_one_undo_step() {
|
||||
let mut session = session();
|
||||
let (_, effect) = masked_layer(&mut session, false);
|
||||
let edited = [stored(TOP_LEFT_ID), stored(TOP_RIGHT_ID)];
|
||||
|
||||
execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": edited, "tolerance": 0.2})).unwrap();
|
||||
assert_eq!(colors(&session, effect), edited.to_vec());
|
||||
let Some((_, found)) = session.doc.project.effect(effect) else { panic!("effect gone") };
|
||||
assert!(matches!(found.kind, EffectKind::ColorSelection { tolerance, .. } if tolerance == 0.2));
|
||||
|
||||
execute(&mut session, "edit.undo", &Value::Null).unwrap();
|
||||
assert_eq!(colors(&session, effect), vec![NO_PART]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_colors_are_refused_and_change_nothing() {
|
||||
let mut session = session();
|
||||
let (_, effect) = masked_layer(&mut session, false);
|
||||
let refused = [json!([]), json!([[0.5, 0.5]]), json!([[0.5, "x", 0.5]]), json!([[0.5, null, 0.5]]), json!("red")];
|
||||
|
||||
for colors_param in &refused {
|
||||
assert!(execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": colors_param})).is_err(), "{colors_param}");
|
||||
}
|
||||
assert_eq!(colors(&session, effect), vec![NO_PART]);
|
||||
execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": [[1e300, 0.5, 0.5]]})).unwrap();
|
||||
assert_eq!(colors(&session, effect), vec![[1.0, 0.5, 0.5]], "out-of-range values clamp to 0..1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn picking_explains_what_is_missing() {
|
||||
let mut session = session();
|
||||
let (layer, effect) = masked_layer(&mut session, false);
|
||||
let pick = |session: &mut Session, params: Value| execute(session, "effect.colorSelection.pick", ¶ms).unwrap_err().to_string();
|
||||
|
||||
assert!(pick(&mut session, json!({"effect": effect.0, "uv": [0.5, 0.5]})).contains("no ID map"));
|
||||
let image = session.import_resource_bytes("id.png", id_map_png()).unwrap();
|
||||
execute(&mut session, "textureSet.meshMap.set", &json!({"map": "id", "image": image})).unwrap();
|
||||
assert!(pick(&mut session, json!({"effect": effect.0, "x": 1, "y": 1})).contains("nothing under that point"));
|
||||
assert!(pick(&mut session, json!({"effect": effect.0, "uv": [1.5, 0.5]})).contains("outside"));
|
||||
assert!(pick(&mut session, json!({"effect": effect.0, "uv": [0.5, 0.5], "index": 7})).contains("no color 7"));
|
||||
assert!(pick(&mut session, json!({"effect": effect.0})).contains("`x` and `y`"));
|
||||
|
||||
let fill = execute(&mut session, "effect.add.fill", &json!({"layer": layer.0})).unwrap()["effect"].as_u64().unwrap();
|
||||
assert!(pick(&mut session, json!({"effect": fill, "uv": [0.5, 0.5]})).contains("not a color selection"));
|
||||
assert_eq!(colors(&session, effect), vec![NO_PART]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_params_never_crash_the_color_selection_commands() {
|
||||
let mut session = session();
|
||||
let (_, effect) = masked_layer(&mut session, true);
|
||||
let hostile = [
|
||||
json!({"effect": effect.0, "x": f32::MAX, "y": -1e30, "viewport": [0, 0]}),
|
||||
json!({"effect": effect.0, "uv": [f64::MAX, -1e300], "index": u64::MAX}),
|
||||
json!({"effect": effect.0, "uv": [0.5], "colors": [[f64::MAX, -f64::MAX, 0.0]]}),
|
||||
json!({"effect": effect.0, "uv": "x", "colors": {"r": 1}}),
|
||||
json!({"effect": u64::MAX, "uv": [0.5, 0.5]}),
|
||||
];
|
||||
|
||||
for params in &hostile {
|
||||
let _ = execute(&mut session, "effect.colorSelection.pick", params);
|
||||
let _ = execute(&mut session, "effect.set", params);
|
||||
session.update();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hidden_texture_set_does_not_block_a_pick_behind_it() {
|
||||
let mut session = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 256).unwrap();
|
||||
session.viewport = Vec2::new(400.0, 400.0);
|
||||
session.update();
|
||||
let set_named = |name: &str| session.doc.project.texture_sets.iter().position(|set| set.name == name).unwrap();
|
||||
let (base, ball) = (set_named("Base"), set_named("Ball"));
|
||||
execute(&mut session, "textureSet.select", &json!({"ts": base})).unwrap();
|
||||
let (_, effect) = masked_layer(&mut session, true);
|
||||
let pick_at = |session: &mut Session, y: f32| execute(session, "effect.colorSelection.pick", &json!({"effect": effect.0, "x": 200, "y": y}));
|
||||
let ball_in_front = |session: &Session, y: f32| {
|
||||
session.pick(Vec2::new(200.0, y), session.viewport).is_some_and(|hit| session.texture_set_of_material(hit.material) == Some(ball))
|
||||
};
|
||||
|
||||
// Down the middle until a pixel where the hidden ball covers the base: the pick reads the base
|
||||
execute(&mut session, "textureSet.visible", &json!({"ts": ball, "visible": false})).unwrap();
|
||||
let mut covered = None;
|
||||
for y in (200..400).map(|y| y as f32) {
|
||||
if ball_in_front(&session, y) && pick_at(&mut session, y).is_ok() {
|
||||
covered = Some(y);
|
||||
break;
|
||||
}
|
||||
}
|
||||
let y = covered.expect("a pixel where the ball covers the base");
|
||||
assert_eq!(colors(&session, effect).len(), 2);
|
||||
|
||||
execute(&mut session, "textureSet.visible", &json!({"ts": ball, "visible": true})).unwrap();
|
||||
assert!(pick_at(&mut session, y).unwrap_err().to_string().contains("another texture set"), "a shown ball still blocks it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_replacement_indices_are_rejected_without_editing() {
|
||||
let mut session = session();
|
||||
let (_, effect) = masked_layer(&mut session, true);
|
||||
let history = session.history_labels();
|
||||
|
||||
for index in [json!(-1), json!(0.4), json!("0"), json!(true), json!([])] {
|
||||
let result = execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": [0.25, 0.25], "index": index}));
|
||||
assert!(result.is_err(), "invalid index {index} was accepted: {result:?}");
|
||||
assert_eq!(colors(&session, effect), vec![NO_PART]);
|
||||
assert_eq!(session.history_labels(), history);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_color_limit_rejects_additions_but_allows_replacement() {
|
||||
let mut session = session();
|
||||
let (_, effect) = masked_layer(&mut session, true);
|
||||
let full = vec![NO_PART; 256];
|
||||
execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": full})).unwrap();
|
||||
let history = session.history_labels();
|
||||
let project = session.doc.project.clone();
|
||||
|
||||
for params in [json!({"effect": effect.0, "uv": [0.25, 0.25]}), json!({"effect": effect.0, "uv": [0.25, 0.25], "index": 256})] {
|
||||
assert!(execute(&mut session, "effect.colorSelection.pick", ¶ms).is_err());
|
||||
assert_eq!(colors(&session, effect), full);
|
||||
assert_eq!(session.history_labels(), history);
|
||||
}
|
||||
assert!(execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": vec![NO_PART; 257], "name": "Invalid edit"})).is_err());
|
||||
assert_eq!(session.history_labels(), history);
|
||||
assert_eq!(session.doc.project, project, "invalid colors also roll back edits to other fields");
|
||||
|
||||
execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": [0.25, 0.25], "index": 255})).unwrap();
|
||||
assert_eq!(colors(&session, effect).len(), 256);
|
||||
assert_close(colors(&session, effect)[255], stored(TOP_LEFT_ID));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inspect_exposes_the_selected_colors_and_tolerance() {
|
||||
let mut session = session();
|
||||
let (layer, effect) = masked_layer(&mut session, true);
|
||||
execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": [0.25, 0.25]})).unwrap();
|
||||
execute(&mut session, "effect.set", &json!({"effect": effect.0, "tolerance": 0.25})).unwrap();
|
||||
|
||||
let inspected = execute(&mut session, "project.inspect", &Value::Null).unwrap();
|
||||
let layer = inspected["layers"].as_array().unwrap().iter().find(|found| found["id"] == layer.0).unwrap();
|
||||
let found = &layer["mask"]["effects"][0];
|
||||
assert_eq!(found["colors"], json!(colors(&session, effect)));
|
||||
assert_eq!(found["tolerance"], json!(0.25));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn picks_use_the_working_texel_on_a_smaller_uv_tile() {
|
||||
let mut session = Session::new_project("UV tiles", primitives::udim_plane(), "builtin:udim_plane", None, 256).unwrap();
|
||||
for tile in [1001, 1002] {
|
||||
session.import_resource_bytes(&format!("id.{tile}.png"), id_map_png()).unwrap();
|
||||
}
|
||||
execute(&mut session, "textureSet.meshMap.set", &json!({"map": "id", "image": "id.1001.png"})).unwrap();
|
||||
let (layer, effect) = masked_layer(&mut session, false);
|
||||
execute(&mut session, "textureSet.tile.resolution", &json!({"tile": 1002, "resolution": 128})).unwrap();
|
||||
execute(&mut session, "effect.set", &json!({"effect": effect.0, "tolerance": 0.0})).unwrap();
|
||||
let size = session.doc.project.texture_sets[0].size();
|
||||
let uv = [0.625, 0.25];
|
||||
let texel = ((uv[0] * size.0 as f32) as u32, (uv[1] * size.1 as f32) as u32);
|
||||
assert_eq!(session.mask_at(layer, &[texel]).unwrap(), vec![0.0]);
|
||||
|
||||
execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": uv})).unwrap();
|
||||
assert_eq!(session.mask_at(layer, &[texel]).unwrap(), vec![1.0]);
|
||||
let before = colors(&session, effect);
|
||||
let result = execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": [0.9, 0.8]}));
|
||||
assert!(result.unwrap_err().to_string().contains("no ID color"), "unused tile space has no sample");
|
||||
assert_eq!(colors(&session, effect), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "release benchmark; run with --ignored --nocapture --test-threads=1"]
|
||||
fn benchmark_color_selection_edits() {
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const SAMPLES: u32 = 10;
|
||||
for resolution in [256, 1024] {
|
||||
let started = Instant::now();
|
||||
let mut session = Session::new_project("benchmark", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, resolution).unwrap();
|
||||
let (_, effect) = masked_layer(&mut session, true);
|
||||
session.update();
|
||||
let construction = started.elapsed();
|
||||
|
||||
for count in [1, 256] {
|
||||
execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": vec![NO_PART; count]})).unwrap();
|
||||
session.update();
|
||||
let params = json!({"effect": effect.0, "uv": [0.25, 0.25], "index": count - 1});
|
||||
let (mut command_time, mut composite_time) = (Duration::ZERO, Duration::ZERO);
|
||||
for _ in 0..SAMPLES {
|
||||
let started = Instant::now();
|
||||
execute(&mut session, "effect.colorSelection.pick", ¶ms).unwrap();
|
||||
command_time += started.elapsed();
|
||||
let started = Instant::now();
|
||||
session.update();
|
||||
composite_time += started.elapsed();
|
||||
execute(&mut session, "edit.undo", &Value::Null).unwrap();
|
||||
session.update();
|
||||
}
|
||||
println!(
|
||||
"{resolution}x{resolution}, {count} colors, {SAMPLES} samples: construction {construction:.3?}; pick {:.3?}; composite {:.3?}; session memory {} bytes",
|
||||
command_time / SAMPLES,
|
||||
composite_time / SAMPLES,
|
||||
session.memory().total()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,172 @@
|
||||
//! Swapping a filter effect's type in place through `effect.set {filter}`
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_engine::core::{BlendMode, Effect, EffectKind, Filter, LayerId};
|
||||
use texturecraft_engine::geom::primitives;
|
||||
use texturecraft_engine::{Session, StackTarget, execute};
|
||||
|
||||
/// A sphere project with its default layer selected
|
||||
fn session() -> Session {
|
||||
Session::new_project("t", primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 256).unwrap()
|
||||
}
|
||||
|
||||
/// Runs effect-adding `command` and returns the new effect, which it selects
|
||||
fn add(s: &mut Session, command: &str, params: Value) -> LayerId {
|
||||
execute(s, command, ¶ms).unwrap();
|
||||
let StackTarget::Effect(added) = s.target else { panic!("adding an effect selects it: {:?}", s.target) };
|
||||
|
||||
added
|
||||
}
|
||||
|
||||
/// A copy of effect `id`
|
||||
fn effect(s: &Session, id: LayerId) -> Effect {
|
||||
s.doc.project.effect(id).unwrap().1.clone()
|
||||
}
|
||||
|
||||
/// Ids of the selected layer's content effects, bottom first
|
||||
fn content_order(s: &Session) -> Vec<LayerId> {
|
||||
let layer = s.selected_layer().unwrap();
|
||||
s.doc.project.layer(layer).unwrap().content_effects.iter().map(|effect| effect.id).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn swapping_a_filter_keeps_its_place_blend_opacity_and_visibility() {
|
||||
let mut s = session();
|
||||
let below = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content"}));
|
||||
let swapped = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content"}));
|
||||
let above = add(&mut s, "effect.add.filter", json!({"filter": "grayscale", "target": "content"}));
|
||||
execute(&mut s, "effect.set", &json!({"effect": swapped.0, "blend": "Multiply", "opacity": 0.4, "visible": false})).unwrap();
|
||||
|
||||
execute(&mut s, "effect.set", &json!({"effect": swapped.0, "filter": "blur", "radius": 5.0})).unwrap();
|
||||
|
||||
let blur = effect(&s, swapped);
|
||||
assert!(matches!(blur.kind, EffectKind::Filter(Filter::Blur { radius }) if radius == 5.0), "{:?}", blur.kind);
|
||||
assert_eq!(blur.name, "Blur", "a default name follows the new filter");
|
||||
assert_eq!((blur.blend, blur.opacity, blur.visible), (BlendMode::Multiply, 0.4, false));
|
||||
assert_eq!(content_order(&s), vec![below, swapped, above]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn swapping_a_filter_keeps_a_name_the_user_chose() {
|
||||
let mut s = session();
|
||||
let id = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content", "name": "Flip"}));
|
||||
|
||||
execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "threshold"})).unwrap();
|
||||
|
||||
assert_eq!(effect(&s, id).name, "Flip");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_undo_restores_the_old_filter() {
|
||||
let mut s = session();
|
||||
let id = add(&mut s, "effect.add.filter", json!({"filter": "threshold", "target": "content", "level": 0.3}));
|
||||
|
||||
execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "sharpen"})).unwrap();
|
||||
execute(&mut s, "edit.undo", &Value::Null).unwrap();
|
||||
|
||||
let restored = effect(&s, id);
|
||||
assert!(matches!(restored.kind, EffectKind::Filter(Filter::Threshold { level }) if level == 0.3), "{:?}", restored.kind);
|
||||
assert_eq!(restored.name, "Threshold");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mask_refuses_a_content_only_filter() {
|
||||
let mut s = session();
|
||||
let id = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "mask"}));
|
||||
|
||||
let err = execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "grayscale"})).unwrap_err();
|
||||
|
||||
assert!(err.to_string().contains("not on masks"), "{err}");
|
||||
assert!(matches!(effect(&s, id).kind, EffectKind::Filter(Filter::Invert)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mask_filter_swaps_in_place_on_the_mask() {
|
||||
let mut s = session();
|
||||
let below = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "mask"}));
|
||||
let swapped = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "mask"}));
|
||||
let above = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "mask"}));
|
||||
execute(&mut s, "effect.set", &json!({"effect": swapped.0, "blend": "Multiply", "opacity": 0.4})).unwrap();
|
||||
|
||||
execute(&mut s, "effect.set", &json!({"effect": swapped.0, "filter": "blur"})).unwrap();
|
||||
|
||||
let blur = effect(&s, swapped);
|
||||
assert!(matches!(blur.kind, EffectKind::Filter(Filter::Blur { .. })), "{:?}", blur.kind);
|
||||
assert_eq!((blur.name.as_str(), blur.blend, blur.opacity), ("Blur", BlendMode::Multiply, 0.4));
|
||||
let layer = s.selected_layer().unwrap();
|
||||
let mask_order: Vec<LayerId> = s.doc.project.layer(layer).unwrap().mask.as_ref().unwrap().effects.iter().map(|effect| effect.id).collect();
|
||||
assert_eq!(mask_order, vec![below, swapped, above]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn naming_the_current_filter_edits_it_in_place() {
|
||||
let mut s = session();
|
||||
let id = add(&mut s, "effect.add.filter", json!({"filter": "blur", "target": "content", "radius": 5.0}));
|
||||
|
||||
execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "blur", "radius": 9.0})).unwrap();
|
||||
execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "blur"})).unwrap();
|
||||
|
||||
let blur = effect(&s, id);
|
||||
assert!(matches!(blur.kind, EffectKind::Filter(Filter::Blur { radius }) if radius == 9.0), "the radius is kept, not reset: {:?}", blur.kind);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_given_with_the_swap_wins() {
|
||||
let mut s = session();
|
||||
let id = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content"}));
|
||||
|
||||
execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "threshold", "name": "Edges"})).unwrap();
|
||||
|
||||
let swapped = effect(&s, id);
|
||||
assert!(matches!(swapped.kind, EffectKind::Filter(Filter::Threshold { .. })), "{:?}", swapped.kind);
|
||||
assert_eq!(swapped.name, "Edges");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refused_swap_changes_nothing_and_adds_no_undo_step() {
|
||||
let mut s = session();
|
||||
let id = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "mask"}));
|
||||
execute(&mut s, "effect.set", &json!({"effect": id.0, "blend": "Multiply", "opacity": 0.4, "name": "Flip"})).unwrap();
|
||||
let before = effect(&s, id);
|
||||
|
||||
for refused in [
|
||||
json!({"effect": id.0, "filter": "grayscale"}),
|
||||
json!({"effect": id.0, "filter": "nope"}),
|
||||
json!({"effect": id.0, "filter": "levels"}),
|
||||
json!({"effect": id.0, "filter": "colorBalance", "shadows": "not a color"}),
|
||||
] {
|
||||
assert!(execute(&mut s, "effect.set", &refused).is_err(), "{refused}");
|
||||
}
|
||||
|
||||
assert_eq!(effect(&s, id), before);
|
||||
// The last step is still the blend, opacity and name edit
|
||||
execute(&mut s, "edit.undo", &Value::Null).unwrap();
|
||||
assert_eq!(effect(&s, id).name, "Invert");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_filter_effects_swap_and_only_to_filters() {
|
||||
let mut s = session();
|
||||
let levels = add(&mut s, "effect.add.levels", json!({"target": "content"}));
|
||||
let filter = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content"}));
|
||||
|
||||
assert!(execute(&mut s, "effect.set", &json!({"effect": levels.0, "filter": "blur"})).is_err(), "levels is not a filter effect");
|
||||
assert!(execute(&mut s, "effect.set", &json!({"effect": levels.0, "filter": "nope"})).is_err(), "an unknown filter on levels");
|
||||
assert!(execute(&mut s, "effect.set", &json!({"effect": filter.0, "filter": "matFinishGrind"})).is_err(), "a material finish is a fill");
|
||||
assert!(execute(&mut s, "effect.set", &json!({"effect": filter.0, "filter": "nope"})).is_err());
|
||||
assert!(matches!(effect(&s, filter).kind, EffectKind::Filter(Filter::Invert)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_swap_parameters_report_effect_set_and_preserve_history() {
|
||||
let mut s = session();
|
||||
let id = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content"}));
|
||||
let before = effect(&s, id);
|
||||
let history = s.history_labels();
|
||||
|
||||
let error = execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "colorBalance", "shadows": "invalid", "name": "Changed"})).unwrap_err();
|
||||
|
||||
assert!(matches!(error, texturecraft_engine::EngineError::BadParams { ref cmd, .. } if cmd == "effect.set"), "{error}");
|
||||
assert_eq!(effect(&s, id), before);
|
||||
assert_eq!(s.history_labels(), history);
|
||||
}
|
||||
File renamed without changes.
@@ -0,0 +1,57 @@
|
||||
use texturecraft_engine::bake::{HighPolyReach, RayStart, VertexReach, high_poly_missed};
|
||||
use texturecraft_engine::geom::glam::Vec3;
|
||||
|
||||
fn vertex(height: f32) -> Option<VertexReach> {
|
||||
Some(VertexReach {
|
||||
low_position: Vec3::ZERO,
|
||||
start: RayStart::Distance { up: Vec3::Y, scale: 1.0 },
|
||||
high_position: Vec3::new(0.0, height, 0.0),
|
||||
high_facing: Vec3::Y,
|
||||
name_matches: true,
|
||||
})
|
||||
}
|
||||
|
||||
fn reach(vertices: Vec<Option<VertexReach>>) -> Option<HighPolyReach> {
|
||||
Some(HighPolyReach { vertices, cage_units: 1.0, ignore_backface: false })
|
||||
}
|
||||
|
||||
fn sets() -> Vec<Option<HighPolyReach>> {
|
||||
vec![None, reach(vec![vertex(0.5), vertex(-0.25), None, None, None]), reach(vec![None, None, vertex(0.5), vertex(-0.25), None])]
|
||||
}
|
||||
|
||||
const DISTANCES: [(f32, f32); 3] = [(9.0, 9.0), (0.25, 0.25), (0.5, 0.125)];
|
||||
|
||||
#[test]
|
||||
fn each_owning_set_uses_its_own_frontal_and_rear_distances() {
|
||||
let reaches = sets();
|
||||
assert_eq!(high_poly_missed(&reaches, &DISTANCES, None, 6), vec![1.0, 0.0, 0.0, 1.0, 0.0, 0.0]);
|
||||
let expanded = [(9.0, 9.0), (0.5, 0.25), (0.5, 0.25)];
|
||||
assert_eq!(high_poly_missed(&reaches, &expanded, None, 6), vec![0.0; 6]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selected_set_filter_leaves_other_sets_unmarked() {
|
||||
let reaches = sets();
|
||||
assert_eq!(high_poly_missed(&reaches, &DISTANCES, Some(1), 6), vec![1.0, 0.0, 0.0, 0.0, 0.0, 0.0]);
|
||||
assert_eq!(high_poly_missed(&reaches, &DISTANCES, Some(2), 6), vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0]);
|
||||
for only_set in [0, reaches.len(), usize::MAX] {
|
||||
assert_eq!(high_poly_missed(&reaches, &DISTANCES, Some(only_set), 6), vec![0.0; 6]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_reach_or_distances_leave_vertices_unmarked() {
|
||||
assert_eq!(high_poly_missed(&[], &DISTANCES, None, 6), vec![0.0; 6]);
|
||||
assert_eq!(high_poly_missed(&sets(), &[], None, 6), vec![0.0; 6]);
|
||||
assert_eq!(high_poly_missed(&sets(), &DISTANCES[..2], None, 6), vec![1.0, 0.0, 0.0, 0.0, 0.0, 0.0]);
|
||||
assert_eq!(high_poly_missed(&sets(), &DISTANCES, None, 1), vec![1.0]);
|
||||
assert!(high_poly_missed(&sets(), &DISTANCES, None, 0).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reached_vertex_is_not_overridden_by_a_later_set() {
|
||||
let reaches = [reach(vec![vertex(0.5)]), reach(vec![vertex(0.5)])];
|
||||
let distances = [(0.5, 0.0), (0.25, 0.0)];
|
||||
assert_eq!(high_poly_missed(&reaches, &distances, None, 1), vec![0.0]);
|
||||
assert_eq!(high_poly_missed(&reaches, &distances, Some(1), 1), vec![1.0]);
|
||||
}
|
||||
File renamed without changes.
Loaded 100 of 238 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user