diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index cb4ec50b..1145b532 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -24,7 +24,8 @@ jobs:
# Same craft-fonts commit as release.yml.
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
diff --git a/.github/workflows/freebsd.yml b/.github/workflows/freebsd.yml
index 9f64bbdd..442b9fd7 100644
--- a/.github/workflows/freebsd.yml
+++ b/.github/workflows/freebsd.yml
@@ -33,4 +33,9 @@ jobs:
uses: storytold/craft-common-actions/.github/workflows/freebsd.yml@main
with:
craft-fonts-ref: aced4137c022f1f587624d48e81ec77e1914a9cc
+ # The VM's software Vulkan driver crashes (SIGSEGV) when several tests set up a device at
+ # once (photocraft serializes its GPU tests for the same reason), so tests run one at a
+ # time. The whole workspace is tested in one command: excluding packages would change
+ # feature unification and build winit without its X11/Wayland backends.
+ cargo-test-extra-args: "-- --test-threads=1"
run-package-check: true
diff --git a/.github/workflows/house-rules.yml b/.github/workflows/house-rules.yml
new file mode 100644
index 00000000..de64ad3e
--- /dev/null
+++ b/.github/workflows/house-rules.yml
@@ -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
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 3ed14bca..23727788 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -1,6 +1,10 @@
name: Release
on:
+ # A nightly dry run on main: every release build except macOS, nothing signed or released
+ # (craft-common-actions release.yml `dry-run`). Finds release-only breakage before release day.
+ schedule:
+ - cron: "44 2 * * *"
push:
branches: [release]
workflow_dispatch:
@@ -23,6 +27,7 @@ jobs:
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
uses: storytold/craft-common-actions/.github/workflows/release.yml@main
with:
+ dry-run: ${{ github.event_name == 'schedule' }}
app-name: texturecraft
app-title: "TextureCraft"
craft-fonts-ref: aced4137c022f1f587624d48e81ec77e1914a9cc
@@ -43,3 +48,4 @@ jobs:
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
+ LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
diff --git a/.github/workflows/sonarcloud.yml b/.github/workflows/sonarcloud.yml
new file mode 100644
index 00000000..8ab024cf
--- /dev/null
+++ b/.github/workflows/sonarcloud.yml
@@ -0,0 +1,19 @@
+name: SonarCloud
+
+on:
+ push:
+ branches: [main]
+ pull_request:
+ types: [opened, synchronize, reopened]
+
+permissions:
+ contents: read
+
+concurrency:
+ group: sonarcloud-${{ github.ref }}
+ cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
+
+jobs:
+ sonarcloud:
+ uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@main
+ secrets: inherit
diff --git a/AGENTS.md b/AGENTS.md
index ad435dac..9a78849f 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1,3 +1,56 @@
+
+## 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.
+
+
+## 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.
+
+
# 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,
@@ -58,6 +108,13 @@ replace it without touching the engine.
## 3. Golden rules
+### Never name the reference product (absolutely essential)
+
+- The repository never names the commercial product TextureCraft is modeled on, nor its vendor,
+ in code, comments, docs, commit messages, test names, file names or UI text. Say "the reference
+ app", "the professional model-painter workflow" or describe the feature itself.
+- Notes that name it may live only in the gitignored `plan/` folder or in this `AGENTS.md` file
+
### Assets, icons and images (absolutely essential)
- **Never use any icon, image, logo, texture, material, brush, environment, font or other asset
@@ -91,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
@@ -126,7 +183,7 @@ panic. The shared standard is `../craftrules/standards/never-crash.md`.
Benchmark heavy paths (bake, composite, export) in release and record numbers in the dev log.
8. **Cross-app formats are shared conventions.** MaterialCraft's `.mcmat` portable materials are
read here with our own code (`formats::mcmat`): keep the manifest fields, usage ids and
- mesh-map identifiers (`BakedMap::interop_id`) in step with MaterialCraft's
+ mesh-map identifiers (`BakedMap::id`) in step with MaterialCraft's
`docs/control-protocol.md`, and never depend on MaterialCraft's crates; talk to it through
`materialcraft-cli`.
9. **Verify UI changes visually.** Launch with `--control ` and call `ui.screenshot` (whole
@@ -169,6 +226,10 @@ 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.
+
+## Shared Craft libraries
+
+Before adding or changing reusable file-format, codec, protocol or UI code, check [craft-libs](https://github.com/storytold/craft-libs) and existing contributor work; reuse its public APIs or extend the appropriate shared library instead of adding an app-local duplicate, keeping app-specific policy and model mapping local and preserving compatibility, security limits and regression coverage.
diff --git a/CLAUDE.md b/CLAUDE.md
index 3e690427..43c994c2 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -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
diff --git a/CODE_STYLE.md b/CODE_STYLE.md
new file mode 100644
index 00000000..92a74a1c
--- /dev/null
+++ b/CODE_STYLE.md
@@ -0,0 +1,77 @@
+# Code style
+
+Style conventions for TextureCraft's Rust code.
+Read alongside [AGENTS.md](AGENTS.md) for repository requirements.
+
+## Naming and Rust conventions
+
+- Use descriptive names that explain purpose; include units where useful. Avoid misleading names
+ and abbreviations whose meaning is unclear in context.
+- Follow Rust naming conventions: `snake_case` for functions, variables, fields, and modules;
+ `UpperCamelCase` for types and traits; `SCREAMING_SNAKE_CASE` for constants and statics.
+- Conventional Rust names are not cryptic abbreviations. Keep names such as `fmt`, `iter`, `len`,
+ `args`, `err`, `id`, and `ui` when their meaning is clear. Do not expand them just to make them
+ longer.
+- Keep standard file and directory names such as `lib.rs`, `main.rs`, `mod.rs`, `src`, `tests`,
+ `examples`, and `benches`. Rust keywords such as `mut`, `ref`, `impl`, and `mod` are language
+ syntax, not naming problems.
+- Short names are appropriate in a clear local context: `i` for an index, `x` and `y` for
+ coordinates, `w` and `h` for image dimensions, and conventional generic parameters such as `T`.
+ Use more descriptive names when scope or ambiguity makes those hard to follow.
+
+## Magic numbers
+
+- Give non-obvious limits, thresholds, sizes, and tuning values descriptive named constants
+ instead of leaving unexplained numeric literals in the code.
+- Name constants for their purpose, with units where useful, rather than for their literal value.
+ Keep them in the narrowest useful scope.
+- Reuse an existing constant when it represents the same concept. Equal numeric values alone do
+ not mean two concepts should share a constant.
+- Explain the origin or rationale of non-obvious coefficients and tolerances in a short comment.
+ Use standard library constants for standard mathematical values.
+- Keep literals inline when their role is clear, such as zero initialization, incrementing by one,
+ or dividing by two to find a midpoint. Do not introduce names such as `ZERO` or `TWO` that add
+ no meaning.
+- Apply this guidance to tests too; clear fixture values and expected results can remain literal.
+
+## Formatting and spacing
+
+- Let `cargo fmt` and the repository's [rustfmt.toml](rustfmt.toml) handle mechanical formatting.
+ Do not introduce a competing indentation or line-wrapping convention.
+- Use one blank line between distinct logical steps: input preparation, validation, computation,
+ mutation, and result construction.
+- Keep closely related statements together. Do not add a blank line after every declaration or
+ fragment a single operation with extra spacing.
+- Put a blank line after a multiline early-exit guard, including `if` and `let ... else`, before
+ the next statement.
+- Put a blank line before a comment introducing a new step, with no blank line between the
+ comment and the code it explains.
+- Keep documentation and attributes attached to their declarations.
+- Separate function definitions with one blank line. Avoid extra empty lines just inside braces
+ or between every field, argument, or statement.
+- In tests, separate preparation, action, and verification with blank lines when those phases
+ are distinct; keep related assertions together.
+
+## Source organization
+
+- Give each struct or enum its own source file, with its implementation beside it. Use the full
+ type name in `snake_case`, such as `mesh_curvature_settings.rs` for `MeshCurvatureSettings`.
+- Preserve conventional crate roots and module entry points such as `lib.rs`, `main.rs`, and
+ `mod.rs`. Follow the command and node module placement required by `AGENTS.md`.
+- Prefer singular folder names for new domain modules, such as `map`, `setting`, or `tracing`.
+ Keep standard Rust directories and repository-mandated paths unchanged.
+- Group related types into focused modules rather than collecting unrelated types in one large file.
+- Apply these preferences to new types and source organization changes within scope. Do not
+ reorganize unrelated existing code to enforce them.
+
+## Comments
+
+- Explain intent or a non-obvious constraint rather than narrating the code.
+- Use short `//` comments. Avoid block comments and wrapped prose in ordinary implementation
+ comments; adjacent comment lines should each express a concise point.
+- Do not add trailing punctuation to ordinary code comments.
+- Preserve explanations of guards and invariants. Remove stale or redundant comments without
+ losing necessary rationale.
+- API documentation, required license headers, and examples may use conventional multiline
+ formatting and punctuation.
+- Apply the same comment guidance to production code and tests.
diff --git a/Cargo.lock b/Cargo.lock
index 5085d081..54f6ef82 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -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,50 @@ 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-cms"
+version = "0.1.0"
+source = "git+https://github.com/storytold/craft-libs?rev=272a095b61257917693da3d09f2f8ecccd7f0295#272a095b61257917693da3d09f2f8ecccd7f0295"
+dependencies = [
+ "md-5",
+ "rayon",
+]
+
+[[package]]
+name = "craft-dialogs"
+version = "0.1.0"
+source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585"
+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=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585"
[[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=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585"
dependencies = [
"fixed_decimal",
"icu_decimal",
@@ -749,10 +805,84 @@ dependencies = [
"writeable",
]
+[[package]]
+name = "craft-keymap"
+version = "0.1.0"
+source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585"
+dependencies = [
+ "egui",
+ "serde",
+ "serde_json",
+]
+
+[[package]]
+name = "craft-materialx"
+version = "0.1.0"
+source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585"
+dependencies = [
+ "craft-xml",
+ "thiserror 2.0.21",
+]
+
+[[package]]
+name = "craft-mcmat"
+version = "0.1.0"
+source = "git+https://github.com/storytold/craft-libs?rev=c376774f15ae7cd3b06a7ac664f01a8645af4b83#c376774f15ae7cd3b06a7ac664f01a8645af4b83"
+dependencies = [
+ "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c376774f15ae7cd3b06a7ac664f01a8645af4b83)",
+ "serde",
+ "serde_json",
+ "thiserror 2.0.21",
+]
+
+[[package]]
+name = "craft-menu"
+version = "0.1.0"
+source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585"
+dependencies = [
+ "craft-keymap",
+ "craft-quit",
+ "egui",
+ "muda",
+ "objc2 0.6.5",
+ "objc2-app-kit 0.3.2",
+]
+
+[[package]]
+name = "craft-mesh"
+version = "0.1.0"
+source = "git+https://github.com/storytold/craft-libs?rev=b952ca0231867c8ad6749ac44cab5fc903c3ad52#b952ca0231867c8ad6749ac44cab5fc903c3ad52"
+dependencies = [
+ "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b952ca0231867c8ad6749ac44cab5fc903c3ad52)",
+ "miniz_oxide 0.9.1",
+]
+
+[[package]]
+name = "craft-quit"
+version = "0.1.0"
+source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585"
+dependencies = [
+ "dispatch2",
+ "egui",
+ "objc2 0.6.5",
+ "objc2-app-kit 0.3.2",
+]
+
+[[package]]
+name = "craft-tcraft"
+version = "0.1.0"
+source = "git+https://github.com/storytold/craft-libs?rev=c376774f15ae7cd3b06a7ac664f01a8645af4b83#c376774f15ae7cd3b06a7ac664f01a8645af4b83"
+dependencies = [
+ "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c376774f15ae7cd3b06a7ac664f01a8645af4b83)",
+ "serde",
+ "serde_json",
+ "thiserror 2.0.21",
+]
+
[[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=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585"
dependencies = [
"craft-fonts-build",
"craft-i18n",
@@ -770,10 +900,46 @@ dependencies = [
"web-sys",
]
+[[package]]
+name = "craft-update"
+version = "0.1.0"
+source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585"
+dependencies = [
+ "chrono",
+ "dunce",
+ "egui",
+ "flate2",
+ "getrandom 0.3.4",
+ "image",
+ "log",
+ "plist",
+ "rustix 1.1.5",
+ "semver",
+ "serde",
+ "serde_json",
+ "sha2",
+ "tar",
+ "tempfile",
+ "ureq",
+ "verifysign",
+ "winreg",
+ "winsafe",
+ "zip",
+]
+
+[[package]]
+name = "craft-usd"
+version = "0.1.0"
+source = "git+https://github.com/storytold/craft-libs?rev=f7655fb3ea59d6b21681700c0ff880823f5bb709#f7655fb3ea59d6b21681700c0ff880823f5bb709"
+dependencies = [
+ "lz4_flex",
+ "thiserror 2.0.21",
+]
+
[[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=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585"
dependencies = [
"egui",
"objc2 0.6.5",
@@ -781,6 +947,36 @@ dependencies = [
"wayland-client",
]
+[[package]]
+name = "craft-xml"
+version = "0.1.0"
+source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585"
+dependencies = [
+ "quick-xml 0.41.0",
+ "serde",
+ "thiserror 2.0.21",
+]
+
+[[package]]
+name = "craft-zip"
+version = "0.1.0"
+source = "git+https://github.com/storytold/craft-libs?rev=b952ca0231867c8ad6749ac44cab5fc903c3ad52#b952ca0231867c8ad6749ac44cab5fc903c3ad52"
+dependencies = [
+ "flate2",
+ "thiserror 2.0.21",
+ "zip",
+]
+
+[[package]]
+name = "craft-zip"
+version = "0.1.0"
+source = "git+https://github.com/storytold/craft-libs?rev=c376774f15ae7cd3b06a7ac664f01a8645af4b83#c376774f15ae7cd3b06a7ac664f01a8645af4b83"
+dependencies = [
+ "flate2",
+ "thiserror 2.0.21",
+ "zip",
+]
+
[[package]]
name = "crc32fast"
version = "1.5.2"
@@ -790,6 +986,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 +1026,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 +1076,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 +1151,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"
@@ -1171,7 +1408,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
- "windows-sys 0.52.0",
+ "windows-sys 0.60.2",
]
[[package]]
@@ -1252,6 +1489,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 +1694,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 +1714,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 +1996,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 +2387,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"
@@ -2248,6 +2542,16 @@ version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4facc753ae494aeb6e3c22f839b158aebd4f9270f55cd3c79906c45476c47ab4"
+[[package]]
+name = "md-5"
+version = "0.10.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"
+dependencies = [
+ "cfg-if",
+ "digest",
+]
+
[[package]]
name = "memchr"
version = "2.8.3"
@@ -2322,6 +2626,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.60.2",
+]
+
[[package]]
name = "naga"
version = "30.0.1"
@@ -2417,6 +2739,15 @@ dependencies = [
"memchr",
]
+[[package]]
+name = "ntapi"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c3b335231dfd352ffb0f8017f3b6027a4917f7df785ea2143d8af2adc66980ae"
+dependencies = [
+ "winapi",
+]
+
[[package]]
name = "num-complex"
version = "0.4.6"
@@ -2427,6 +2758,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"
@@ -2629,6 +2966,16 @@ dependencies = [
"objc2-core-foundation",
]
+[[package]]
+name = "objc2-io-kit"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "33fafba39597d6dc1fb709123dfa8289d39406734be322956a69f0931c73bb15"
+dependencies = [
+ "libc",
+ "objc2-core-foundation",
+]
+
[[package]]
name = "objc2-io-surface"
version = "0.3.2"
@@ -2776,6 +3123,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"
@@ -2812,7 +3165,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"
dependencies = [
"libc",
- "windows-sys 0.52.0",
+ "windows-sys 0.60.2",
]
[[package]]
@@ -2978,6 +3331,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"
@@ -3062,6 +3428,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"
@@ -3136,6 +3508,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"
@@ -3320,6 +3701,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"
@@ -3414,7 +3809,7 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys 0.12.1",
- "windows-sys 0.52.0",
+ "windows-sys 0.60.2",
]
[[package]]
@@ -3427,6 +3822,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.60.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"
@@ -3442,6 +3911,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"
@@ -3480,6 +3958,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"
@@ -3491,6 +3992,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"
@@ -3572,6 +4077,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"
@@ -3743,6 +4259,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"
@@ -3788,6 +4310,30 @@ dependencies = [
"web-sys",
]
+[[package]]
+name = "sysinfo"
+version = "0.40.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0e8a3edbe0394ce115f3917a00349dd242be09eb5a091ed509eaf67b55cfb8a8"
+dependencies = [
+ "libc",
+ "memchr",
+ "ntapi",
+ "objc2-core-foundation",
+ "objc2-io-kit",
+ "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"
@@ -3795,10 +4341,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
- "getrandom 0.3.4",
+ "getrandom 0.4.3",
"once_cell",
"rustix 1.1.5",
- "windows-sys 0.52.0",
+ "windows-sys 0.60.2",
]
[[package]]
@@ -3812,8 +4358,10 @@ dependencies = [
[[package]]
name = "texturecraft"
-version = "0.3.0"
+version = "0.6.1"
dependencies = [
+ "craft-menu",
+ "craft-update",
"eframe",
"egui",
"image",
@@ -3831,7 +4379,7 @@ dependencies = [
[[package]]
name = "texturecraft-automation"
-version = "0.3.0"
+version = "0.6.1"
dependencies = [
"base64 0.22.1",
"cap-std",
@@ -3852,8 +4400,9 @@ dependencies = [
[[package]]
name = "texturecraft-bake"
-version = "0.3.0"
+version = "0.6.1"
dependencies = [
+ "bytemuck",
"rayon",
"texturecraft-core",
"texturecraft-geom",
@@ -3863,7 +4412,7 @@ dependencies = [
[[package]]
name = "texturecraft-cli"
-version = "0.3.0"
+version = "0.6.1"
dependencies = [
"image",
"serde_json",
@@ -3875,7 +4424,7 @@ dependencies = [
[[package]]
name = "texturecraft-compose"
-version = "0.3.0"
+version = "0.6.1"
dependencies = [
"half",
"rayon",
@@ -3886,7 +4435,7 @@ dependencies = [
[[package]]
name = "texturecraft-core"
-version = "0.3.0"
+version = "0.6.1"
dependencies = [
"serde",
"serde_json",
@@ -3895,7 +4444,7 @@ dependencies = [
[[package]]
name = "texturecraft-engine"
-version = "0.3.0"
+version = "0.6.1"
dependencies = [
"epaint_default_fonts",
"image",
@@ -3915,31 +4464,38 @@ dependencies = [
[[package]]
name = "texturecraft-formats"
-version = "0.3.0"
+version = "0.6.1"
dependencies = [
"base64 0.22.1",
+ "craft-cms",
+ "craft-materialx",
+ "craft-mcmat",
+ "craft-mesh",
+ "craft-tcraft",
+ "craft-usd",
+ "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c376774f15ae7cd3b06a7ac664f01a8645af4b83)",
"exr",
"flate2",
"gltf",
"half",
"image",
"lz4_flex",
- "quick-xml",
+ "quick-xml 0.41.0",
"rayon",
"serde",
"serde_json",
+ "sysinfo",
"texturecraft-compose",
"texturecraft-core",
"texturecraft-geom",
"texturecraft-texel",
"thiserror 2.0.21",
- "tobj",
"zip",
]
[[package]]
name = "texturecraft-geom"
-version = "0.3.0"
+version = "0.6.1"
dependencies = [
"glam 0.30.10",
"mikktspace",
@@ -3950,7 +4506,7 @@ dependencies = [
[[package]]
name = "texturecraft-paint"
-version = "0.3.0"
+version = "0.6.1"
dependencies = [
"epaint_default_fonts",
"harfrust",
@@ -3965,7 +4521,7 @@ dependencies = [
[[package]]
name = "texturecraft-render"
-version = "0.3.0"
+version = "0.6.1"
dependencies = [
"bytemuck",
"half",
@@ -3973,6 +4529,7 @@ dependencies = [
"log",
"pollster 0.4.0",
"rayon",
+ "serde",
"texturecraft-bake",
"texturecraft-compose",
"texturecraft-core",
@@ -3984,14 +4541,19 @@ dependencies = [
[[package]]
name = "texturecraft-texel"
-version = "0.3.0"
+version = "0.6.1"
[[package]]
name = "texturecraft-ui-egui"
-version = "0.3.0"
+version = "0.6.1"
dependencies = [
"base64 0.22.1",
+ "craft-dialogs",
+ "craft-i18n",
+ "craft-keymap",
+ "craft-quit",
"craft-ui",
+ "craft-update",
"craft-window",
"eframe",
"egui",
@@ -4000,6 +4562,7 @@ dependencies = [
"image",
"js-sys",
"log",
+ "pollster 0.4.0",
"rayon",
"rfd",
"serde",
@@ -4017,7 +4580,7 @@ dependencies = [
[[package]]
name = "texturecraft-web"
-version = "0.3.0"
+version = "0.6.1"
dependencies = [
"eframe",
"js-sys",
@@ -4083,6 +4646,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"
@@ -4094,12 +4687,6 @@ dependencies = [
"zerovec",
]
-[[package]]
-name = "tobj"
-version = "4.0.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6eb8e04167c1c0c76b5de63226fd733485ad63ef71e40de31e16272f47b099e2"
-
[[package]]
name = "tokio"
version = "1.53.3"
@@ -4265,6 +4852,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"
@@ -4312,6 +4905,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"
@@ -4327,6 +4955,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"
@@ -4381,6 +5015,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"
@@ -4561,7 +5205,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0"
dependencies = [
"proc-macro2",
- "quick-xml",
+ "quick-xml 0.41.0",
"quote",
]
@@ -4597,6 +5241,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"
@@ -4786,15 +5439,37 @@ dependencies = [
"web-sys",
]
+[[package]]
+name = "winapi"
+version = "0.3.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
+dependencies = [
+ "winapi-i686-pc-windows-gnu",
+ "winapi-x86_64-pc-windows-gnu",
+]
+
+[[package]]
+name = "winapi-i686-pc-windows-gnu"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
+
[[package]]
name = "winapi-util"
version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
- "windows-sys 0.52.0",
+ "windows-sys 0.60.2",
]
+[[package]]
+name = "winapi-x86_64-pc-windows-gnu"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
+
[[package]]
name = "windows"
version = "0.62.2"
@@ -5095,7 +5770,7 @@ dependencies = [
"calloop",
"cfg_aliases",
"concurrent-queue",
- "core-foundation",
+ "core-foundation 0.9.4",
"core-graphics",
"cursor-icon",
"dpi",
@@ -5140,6 +5815,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"
@@ -5281,7 +5966,7 @@ checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7"
[[package]]
name = "xtask"
-version = "0.3.0"
+version = "0.6.1"
dependencies = [
"serde_json",
]
@@ -5456,6 +6141,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"
diff --git a/Cargo.toml b/Cargo.toml
index d6259b75..88936e5f 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -5,13 +5,14 @@ exclude = ["vendor"]
default-members = ["crates/core", "crates/texel", "crates/geom", "crates/compose", "crates/bake", "crates/formats", "crates/paint", "crates/engine", "crates/render", "crates/automation", "crates/ui-egui", "apps/texturecraft", "apps/texturecraft-cli", "xtask"]
[workspace.package]
-version = "0.3.0"
+version = "0.6.1"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.95"
repository = "https://github.com/storytold/texturecraft"
[workspace.dependencies]
+craft-usd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "f7655fb3ea59d6b21681700c0ff880823f5bb709" }
# internal
texturecraft-core = { path = "crates/core" }
texturecraft-texel = { path = "crates/texel" }
@@ -32,6 +33,8 @@ serde_json = "1"
glam = { version = "0.30", features = ["serde", "bytemuck"] }
bytemuck = { version = "1", features = ["derive"] }
rayon = "1"
+# Free RAM, to size how much a project save holds in flight.
+sysinfo = { version = "0.40", default-features = false, features = ["system"] }
# Text alphas: shaping and glyph outlines, the versions egui's text layout already builds.
harfrust = "0.12"
skrifa = { version = "0.44", default-features = false, features = ["std"] }
@@ -47,7 +50,6 @@ wgpu = "30"
rfd = "0.17"
zip = { version = "9", default-features = false, features = ["deflate"] }
gltf = { version = "1.4", default-features = false, features = ["import", "utils", "names", "KHR_materials_emissive_strength"] }
-tobj = { version = "4", default-features = false }
flate2 = "1"
lz4_flex = { version = "0.11", default-features = false, features = ["safe-decode", "safe-encode"] }
quick-xml = "0.41"
@@ -63,9 +65,26 @@ 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"] }
+# Shared catalog lookup, pinned with the other Craft libraries.
+craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" }
+craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["serde"] }
+craft-materialx = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" }
+craft-tcraft = { git = "https://github.com/storytold/craft-libs", rev = "c376774f15ae7cd3b06a7ac664f01a8645af4b83" }
+craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "c376774f15ae7cd3b06a7ac664f01a8645af4b83" }
+craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "b952ca0231867c8ad6749ac44cab5fc903c3ad52", default-features = false, features = ["stl", "ply", "fbx", "obj"] }
+craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "c376774f15ae7cd3b06a7ac664f01a8645af4b83" }
# 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 = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", 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 = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", 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 = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" }
+# Shortcut chords, lookup and dispatch (crates/ui-egui/src/keymap.rs).
+craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", 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 = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", 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 = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" }
# egui 0.37 and winit: the suite's forks (storytold/egui, storytold/winit), as craft-libs pins them.
[patch.crates-io]
@@ -103,6 +122,13 @@ opt-level = 1
lto = "thin"
codegen-units = 1
+# Fast optimized verification: each test executable otherwise repeats cross-crate LTO.
+# `false` keeps thin LTO within each crate; release packaging keeps the profile above.
+[profile.verify]
+inherits = "release"
+lto = false
+codegen-units = 16
+
[profile.wasm-release]
inherits = "release"
opt-level = "s"
diff --git a/README.md b/README.md
index 80f807b6..69cd720c 100644
--- a/README.md
+++ b/README.md
@@ -32,6 +32,7 @@
+
diff --git a/ROADMAP.md b/ROADMAP.md
index e856b3ff..1a70d26d 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -4,7 +4,7 @@ TextureCraft aims for 1:1 parity with Adobe Substance 3D Painter's texturing wor
performance, a smaller footprint, every feature drivable by agents (MCP, CLI, control channel), and
builds for Windows, macOS, Linux, FreeBSD and the web.
-## Honest parity estimate (2026-11-02)
+## Honest parity estimate (2026-11-04)
Weighted by how much of a professional's daily work each area carries. "Done" counts what works
end to end today (engine + UI + automation + tests), not what is planned.
@@ -14,15 +14,18 @@ end to end today (engine + UI + automation + tests), not what is planned.
| Project and files | 8 | 95% | New project from glTF/GLB, FBX (binary and ASCII, 6.x and 7.x), COLLADA, **USD (usda, usdc, usdz)**, **Alembic (Ogawa)**, OBJ, PLY, STL or built-in meshes (auto-unwrap when UVs are missing; a `.gltf`'s buffers and images and a loose USD layer's textures are read from its folder and kept in the project), **project templates** (built-in and saved from a project), `.tcraft` open/save/save as/save a copy, autosave, **asks to save unsaved changes** before quitting or replacing the project (in the browser too, and before the tab closes), recent files, drag and drop, reimport mesh **with strokes preserved on the surface**, **MaterialX import** (`file.importMaterialX`: a `.mtlx` material with `open_pbr_surface`, `standard_surface` or `gltf_pbr` becomes one fill layer with its textures and values), image resources, remove unused resources, textured OBJ (MTL), GLB and **USD** mesh export, browser open/save/download | HDF5 Alembic; Alembic animation (first sample only) |
| Texture sets | 6 | 100% | One set per material, **UDIM / UV tiles** (auto-detected or switched on later with resampling, **a resolution per tile** whose filters and height slopes keep their size in UV space, one texture per tile at its own size, `$udim` export), list with visibility (show or hide all, invert, **focus** on one set), sizes 128–8192 with resampling, add/remove channels (19 channel types incl. coat, sheen, anisotropy and scattering), height strength, normal format | — |
| Layer stack | 16 | 98% | Paint, fill, folder and **instance** layers; 32 per-channel blend modes and opacities; white/black/painted masks with **mask with height**; generator, fill, levels (with a histogram of its input), invert/threshold, color selection, compare, blur, sharpen and HSL effects on masks and layer content; anchor points; effects **dragged to reorder**, duplicated, and **copied, cut and pasted** across layers, masks and sets (Ctrl+C, Ctrl+X, Ctrl+V, Ctrl+D and Delete act on a selected effect); smart masks; mask view (Alt+click); Alt+click a material channel to keep it alone; duplicate, group, drag to reorder, rename, color tags, copy/cut/paste (also as instance) across sets, flatten, instantiate across sets, save layers as smart materials; **30 library filters** (adjustments incl. histogram scan, range and shift, blur/sharpen/high pass, bevel, glow, edge detect, warps, mosaic, baked lighting, material finishes); **geometry masks** (a layer on chosen mesh parts) | A few niche filters of the reference app's catalog |
-| Painting tools | 14 | 91% | Paint, eraser, projection with image stencils, polygon fill, **path** and **lasso fill**, smudge, clone, color picker, quick mask, Shift+click lines with preview, 2D view painting; size, flow, stroke opacity, spacing, hardness, angle, follow path, jitters, alignment, angle fade, backface culling, lazy mouse, **Ctrl+drag in a view for size, hardness, flow and angle**, X/Y/Z mirror and **radial symmetry**, pen pressure in the 3D and 2D views (Windows Ink, and touch pens in the browser), procedural and image alphas, **text** in any installed font (as an alpha or a decal), **particle brush** | Pen tilt, and pen pressure on Linux, macOS and desktop browsers (not exposed by the windowing layer) |
+| Painting tools | 14 | 91% | Paint, eraser, projection with image stencils, polygon fill, **path** and **lasso fill**, smudge, clone, material picker, quick mask, Shift+click lines with preview, 2D view painting; size, flow, stroke opacity, spacing, hardness, angle, follow path, jitters, alignment, angle fade, backface culling, lazy mouse, **Ctrl+drag in a view for size, hardness, flow and angle**, X/Y/Z mirror and **radial symmetry**, pen pressure in the 3D and 2D views (Windows Ink, and touch pens in the browser), procedural and image alphas, **text** in any installed font (as an alpha or a decal), **particle brush** | Pen tilt, and pen pressure on Linux, macOS and desktop browsers (not exposed by the windowing layer) |
| Materials and assets | 8 | 92% | **MaterialCraft materials** (`.mcmat`, sent to the shelf from MaterialCraft) as fill layers whose graph inputs and presets stay editable, re-cooked at the set's resolution with its baked mesh maps; 63 procedural materials (incl. car paint, velvet, brushed steel, skin, wax, ice, snow, bark), 21 smart materials, 24 smart masks, **67 procedural brush alphas**, **18 brush presets** plus user presets, 23 procedurals, 6 environments plus imported HDR/EXR panoramas, image resources, a user smart material library, a tabbed shelf with search and **drag and drop** onto layers and the viewport | A smaller bundled library than the reference app's |
-| Baking | 10 | 100% | AO, curvature (also from the normal map), thickness, world normal, position, ID, normal, height, **bent normals, opacity, color map and world-space direction**; **high-poly meshes**, cage, frontal/rear distances, average normals, **skew correction** (`bake.skew.set`, painted in the 2D view with `bake.skew.paint` and saved in the project: a greyscale map over the atlas that turns the transfer rays onto the base normal, with hard-edge protection), **match by mesh name**; per-texture-set selection, common and per-map parameters, progress and cancel; **Auto-rebake** (`bake.autoRebake`: one map bakes itself again in the background when its bake settings, the low poly, the high polys or the skew map change); **mesh maps from images** (baked elsewhere or edited) dropped on a slot; high-poly base color textures embedded or in files beside a `.gltf`, FBX or USD layer | — |
+| Baking | 10 | 90% | All ten mesh-map bakers; low-poly and high-to-low baking with CPU/GPU tracing; mesh-name matching, backface filtering, custom and distance-based cages, frontal/rear distances and average normals; undoable 2D cage/skew painting saved per texture set; rectangular output, antialiasing, dilation/diffusion, ID sources, ray filters, AO attenuation/ground plane, curvature controls and map normalization; per-texture-set selection, progress/cancel and mesh-map import | Residual Painter map differences; reference validation for Height, Bent Normal and Opacity and across additional assets; 3D cage-editing overlay |
| Viewport and display | 12 | 95% | PBR with image-based lighting, 6 procedural environments or imported HDR/EXR panoramas with exposure, rotation, blur, opacity, ACES/linear tone mapping, HDR pipeline with bloom, vignette, sharpen and grain, key-light shadows, 4× MSAA plus idle temporal accumulation, the baked normal map under the painted normal, channel / mesh-map / mask / UV checker views, 3D and 2D wireframes of the mesh's own polygons, brush cursor, axis gizmos, subsurface scattering blur, **depth of field**, saved cameras and cameras from glTF, FBX, COLLADA and USD files, displacement (also in shadows and the path tracers), **path-traced Rendering mode** (F10, on the GPU or the CPU) with environment importance sampling and an edge-aware **denoiser**; picks a discrete GPU on multi-GPU machines (`--gpu`, `WGPU_ADAPTER_NAME`, `WGPU_POWER_PREF`), and display textures are made on demand so a mesh with many materials imports on a small GPU | Hardware ray tracing |
| Shader | 6 | 100% | Metallic/roughness and specular/glossiness PBR, **clear coat, sheen, anisotropy and subsurface scattering** (viewport and path tracer), height-to-normal, painted normals, parallax occlusion, emissive, opacity (dithered), AO intensity | — |
| Export | 8 | 92% | 10 presets (incl. Godot 4 and **OpenPBR** with every shading lobe) plus **user output templates** (per-channel packing, converted maps, JSON import/export), PNG/JPEG/TGA/TIFF/BMP/WEBP/EXR/HDR, 8/16/32-bit, padding modes, size override, OpenGL/DirectX normals, **colour space** of the colour maps (sRGB, Linear Rec.709, ACEScg, ACES2065-1; data maps never converted; the chosen space is recorded in the file as an ICC profile in PNG, JPEG, TIFF and WebP and as chromaticities in EXR), `$udim` tiles, **MaterialX** (`file.exportTextures` with `materialX`: a `.mtlx` OpenPBR material per set, `` aware), OBJ with MTL and maps, textured GLB (with clearcoat/sheen) and USD (with clear coat) mesh export, zip download in the browser | Sheen and anisotropy in USD (UsdPreviewSurface has no inputs for them; GLB and OpenPBR maps carry them) |
| UI and UX | 8 | 97% | Painter-style layout with **dockable, tabbed, floating panels**, menus, tool shelf, tool bar, asset shelf, texture set list, layer stack with context menu, properties, display/shader/history/log panels, export dialog, new project dialog, bake mode, rendering mode, settings (interface scale, autosave, viewport texture resolution, system title bar), **own title bar** with the app icon and window buttons (Windows, GNOME; integrated with the macOS traffic lights), saved UI layouts, a **History** panel that jumps to any step (back or forward), a **start window** (new, open, recent projects), **shortcut editor** with conflict detection, tooltips with shortcuts, a compact color picker (saturation/value square, hue strip, copyable RGB); all menu items live ([docs/parity.md](docs/parity.md)); **10 UI languages** with CJK and Arabic fonts ([docs/localization-parity.md](docs/localization-parity.md)); closed panels reopen where they were; frame-budgeted compositing and uploads keep 8K sets responsive | Native-speaker review of the translations |
| Platforms | 4 | 76% | Windows, macOS (universal, signed and notarized), Linux (AppImage, deb, rpm, tar.gz, Flatpak), FreeBSD and web release workflows | First real release run; web build polish |
-| **Total** | **100** | **≈ 94%** | | |
+| **Total** | **100** | **≈ 94%** | Weighted workflow-completion estimate | |
+
+Baking’s 90% estimates workflow completion: all ten map types and exposed settings have implementation
+paths, with the remaining work listed above. Pixel-level equivalence with Painter remains unverified.
Beyond the reference app: every command is available to agents through MCP, the CLI and the app's
control channel (MCP workspace tools cover every file action: projects, meshes, high polys and
@@ -38,13 +41,13 @@ parallel on separate crates:
| M1 Layer stack depth | Done | 0 h |
| M2 Tools | Pen tilt, and pen pressure on Linux, macOS and desktop browsers, once the windowing layer reports them | 0.5 h |
| M3 Assets | Done | 0 h |
-| M4 Baking | Done | 0 h |
+| M4 Baking | Validate outputs across reference assets, refine remaining map differences and add 3D cage editing | TBD |
| M5 Viewport | Hardware ray tracing: wgpu's ray queries are experimental and need an `unsafe` opt-in, which the workspace forbids (owner decision) | 1.5 h |
| M6 Shader | Done | 0 h |
| M7 Formats | Done | 0 h |
| M8 UX | Native review of translations | 1 h |
| M9 Release | The twelve signing secrets and the Default runner group (org admin); first signed release run on every platform (v0.1.0); web deployment; Flathub submission | 3 h |
-| **Total** | | **≈ 6 h** |
+| **Total** | | **≈ 6 h + baking TBD** |
## Current focus
diff --git a/apps/texturecraft-cli/tests/cli.rs b/apps/texturecraft-cli/tests/cli.rs
index 686bee97..4cb6a5aa 100644
--- a/apps/texturecraft-cli/tests/cli.rs
+++ b/apps/texturecraft-cli/tests/cli.rs
@@ -1,12 +1,34 @@
//! Drives the `texturecraft-cli` binary.
+use std::ffi::OsString;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use serde_json::Value;
+// Nextest 0.9.130+ remaps this variable when an archive is extracted on another
+// runner. Cargo's compile-time path still supports ordinary `cargo test`.
+fn cli_binary() -> OsString {
+ cli_binary_path(std::env::var_os("CARGO_BIN_EXE_texturecraft-cli"))
+}
+
+fn cli_binary_path(runner_path: Option) -> OsString {
+ runner_path.unwrap_or_else(|| env!("CARGO_BIN_EXE_texturecraft-cli").into())
+}
+
+#[test]
+fn cli_binary_prefers_relocated_runner_path() {
+ let relocated = OsString::from("relocated archive/texturecraft-cli");
+ assert_eq!(cli_binary_path(Some(relocated.clone())), relocated);
+}
+
+#[test]
+fn cli_binary_defaults_to_cargo_path() {
+ assert_eq!(cli_binary_path(None), OsString::from(env!("CARGO_BIN_EXE_texturecraft-cli")));
+}
+
fn cli(args: &[&str]) -> Output {
- Command::new(env!("CARGO_BIN_EXE_texturecraft-cli")).args(args).output().unwrap()
+ Command::new(cli_binary()).args(args).output().unwrap()
}
fn ok(args: &[&str]) -> String {
@@ -101,7 +123,7 @@ fn info_on_a_mesh_reports_uvs() {
fn serve_takes_the_automation_root_spelling_too() {
use std::io::Write as _;
let d = tmp("automation-root");
- let mut child = Command::new(env!("CARGO_BIN_EXE_texturecraft-cli"))
+ let mut child = Command::new(cli_binary())
.args(["serve", "--automation-write-root", p(&d)])
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
diff --git a/apps/texturecraft/Cargo.toml b/apps/texturecraft/Cargo.toml
index 2f80d416..b4a1d57c 100644
--- a/apps/texturecraft/Cargo.toml
+++ b/apps/texturecraft/Cargo.toml
@@ -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"
diff --git a/apps/texturecraft/src/main.rs b/apps/texturecraft/src/main.rs
index 377b2e52..2deac956 100644
--- a/apps/texturecraft/src/main.rs
+++ b/apps/texturecraft/src/main.rs
@@ -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::>(&s).ok());
- kv.and_then(|kv| ron::from_str::(kv.get("ui")?).ok()).is_some_and(|ui| ui.prefs.system_title_bar)
+/// Preferences needed before opening the initial project or window, with legacy storage fallback.
+fn saved_prefs(ui_file: Option<&std::path::Path>, persistence_path: Option<&std::path::Path>) -> texturecraft_ui_egui::state::Prefs {
+ if let Some(ui) = ui_file.and_then(ui_state_store::read) {
+ return ui.prefs;
+ }
+
+ let file = persistence_path.map(std::path::Path::to_path_buf).or_else(|| eframe::storage_dir(APP_NAME).map(|folder| folder.join("app.ron")));
+ let saved = file.and_then(|file| std::fs::read_to_string(file).ok());
+ let entries = saved.and_then(|text| ron::from_str::>(&text).ok());
+ entries.and_then(|entries| ron::from_str::(entries.get("ui")?).ok()).map(|ui| ui.prefs).unwrap_or_default()
}
/// 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) -> 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::>()) {
+ std::process::exit(i32::from(result.is_err()));
+ }
let args = match parse_args() {
Ok(Some(a)) => a,
Ok(None) => return,
@@ -170,21 +189,27 @@ 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 prefs = saved_prefs(ui_file.as_deref(), persistence_path.as_deref());
+ prefs.apply_resource_limits();
+ let session = initial_session(&args);
+ let title_bar = TitleBar::decide(prefs.system_title_bar);
+ let mut viewport = egui::ViewportBuilder::default().with_title(APP_NAME).with_inner_size(DEFAULT_SIZE).with_min_inner_size(MIN_SIZE);
if let Some(i) = icon() {
viewport = viewport.with_icon(i);
}
@@ -195,7 +220,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 +230,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 +305,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 +333,36 @@ 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 startup_preferences_use_ui_json_then_legacy_storage_then_defaults() {
+ 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.
+ ui.prefs.project_open_limit_gib = 16;
+
+ // 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();
+
+ let legacy = saved_prefs(None, Some(&ron_path));
+ assert_eq!(legacy.system_title_bar, on);
+ assert_eq!(legacy.project_open_limit_gib, 16);
+
+ ui.prefs.system_title_bar = !on;
+ ui.prefs.project_open_limit_gib = 32;
+ std::fs::write(&json_path, serde_json::to_vec(&ui).unwrap()).unwrap();
+
+ let current = saved_prefs(Some(&json_path), Some(&ron_path));
+ assert_eq!(current.system_title_bar, !on, "ui.json comes first");
+ assert_eq!(current.project_open_limit_gib, 32);
}
- 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_eq!(saved_prefs(Some(&json_path), Some(&ron_path)), texturecraft_ui_egui::state::Prefs::default());
+ std::fs::remove_file(&json_path).unwrap();
+ std::fs::remove_file(&ron_path).unwrap();
+ assert_eq!(saved_prefs(Some(&json_path), Some(&ron_path)), texturecraft_ui_egui::state::Prefs::default());
}
}
diff --git a/craft-i18n.rev b/craft-i18n.rev
new file mode 100644
index 00000000..2da99634
--- /dev/null
+++ b/craft-i18n.rev
@@ -0,0 +1 @@
+3cb11a36a58c5eabfd3a768448b55fdf086885bf
diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rs
index 87d58648..0af8274d 100644
--- a/crates/automation/src/headless.rs
+++ b/crates/automation/src/headless.rs
@@ -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 }
}
diff --git a/crates/automation/src/render.rs b/crates/automation/src/render.rs
index 4621d6a0..e390c239 100644
--- a/crates/automation/src/render.rs
+++ b/crates/automation/src/render.rs
@@ -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,
};
@@ -85,7 +85,15 @@ impl Gpu {
/// Render `s` with `kind` at `size` through `camera`; RGBA8 (sRGB) pixels.
pub fn render(&mut self, s: &mut Session, kind: ViewKind, size: [u32; 2], camera: texturecraft_engine::geom::OrbitCamera) -> Option<(u32, u32, Vec)> {
self.sync(s);
- let frame = Frame { view_id: 1, size, kind, camera, shade: shade(s), visible: s.doc.project.texture_sets.iter().map(|t| t.visible).collect() };
+ let frame = Frame {
+ view_id: 1,
+ size,
+ kind,
+ camera,
+ shade: shade(s),
+ visible: s.doc.project.texture_sets.iter().map(|t| t.visible).collect(),
+ overlay: Vec::new(),
+ };
self.h.render(&frame)
}
diff --git a/crates/automation/src/security.rs b/crates/automation/src/security.rs
index 0f5e6ab5..63c12b0e 100644
--- a/crates/automation/src/security.rs
+++ b/crates/automation/src/security.rs
@@ -178,8 +178,11 @@ pub struct ConnectionLimiter(Arc);
pub struct Permit(Arc);
impl ConnectionLimiter {
- pub fn try_acquire(&self, max: usize) -> Option {
- self.0.fetch_update(Ordering::AcqRel, Ordering::Acquire, |n| (n < max).then_some(n + 1)).ok().map(|_| Permit(self.0.clone()))
+ pub fn try_acquire(&self, max_connections: usize) -> Option {
+ self.0
+ .try_update(Ordering::AcqRel, Ordering::Acquire, |connections| (connections < max_connections).then_some(connections + 1))
+ .ok()
+ .map(|_| Permit(self.0.clone()))
}
}
@@ -328,10 +331,12 @@ mod tests {
#[test]
fn limiter_releases() {
- let l = ConnectionLimiter::default();
- let p = l.try_acquire(1).unwrap();
- assert!(l.try_acquire(1).is_none());
- drop(p);
- assert!(l.try_acquire(1).is_some());
+ let limiter = ConnectionLimiter::default();
+
+ let permit = limiter.try_acquire(1).unwrap();
+ assert!(limiter.try_acquire(1).is_none());
+
+ drop(permit);
+ assert!(limiter.try_acquire(1).is_some());
}
}
diff --git a/crates/automation/src/workspace.rs b/crates/automation/src/workspace.rs
index 2015c090..1061db2d 100644
--- a/crates/automation/src/workspace.rs
+++ b/crates/automation/src/workspace.rs
@@ -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]
diff --git a/crates/bake/Cargo.toml b/crates/bake/Cargo.toml
index 9b893562..7125135f 100644
--- a/crates/bake/Cargo.toml
+++ b/crates/bake/Cargo.toml
@@ -12,5 +12,6 @@ workspace = true
texturecraft-core = { workspace = true }
texturecraft-geom = { workspace = true }
texturecraft-texel = { workspace = true }
+bytemuck = { workspace = true, features = ["extern_crate_alloc"] }
rayon = { workspace = true }
thiserror = { workspace = true }
diff --git a/crates/bake/README.md b/crates/bake/README.md
index 786f69f3..0eac65cc 100644
--- a/crates/bake/README.md
+++ b/crates/bake/README.md
@@ -1,26 +1,41 @@
# texturecraft-bake
-Mesh-map baker: `bake(&BakeRequest, &Progress) -> BakeOutput` turns one texture set's UV layout into float maps (0..1, rows top → bottom), supersampled, padded and deterministic. The supersamples are processed in batches: their high-poly transfer rays, then the secondary rays of ambient occlusion, bent normals and thickness go to a `rays::Tracer`, then all requested maps are evaluated per sample (rayon over rows).
+Clean-room mesh-map baking from low-poly UVs and optional high-poly meshes. Persisted settings live in `texturecraft-core`; localized controls live in `texturecraft-ui-egui`. Types have individual files, with singular module folders.
-The rays run on the CPU (`rays::CpuTracer`, the oracle) or, through `bake_on(&BakeRequest, &Progress, &dyn Tracer)`, on a GPU tracer (the render crate's `gpu_bake::GpuBaker`, wgpu compute shaders on the path tracer's BVH traversal). The GPU receives the same rays and per-sample rotations and casts the same secondary-ray directions, so both agree up to float rounding; when the tracer fails (no adapter, a mesh too large for it, a lost device) `bake_on` bakes again on the CPU. `BakeOutput::tracer` says where the rays ran.
+`bake(&BakeRequest, &Progress)` runs the CPU oracle. `bake_on` accepts a `tracing::Tracer` such as the render crate's GPU baker, and retries on the CPU if that tracer fails. Both receive identical transfer rays and secondary-ray samples. Output is deterministic, floating point, and stored in rows from top to bottom. Cancellation is checked between bounded batches and before returning the result.
-With a high poly (`BakeRequest::high`, every high-definition mesh appended into one), each low-poly sample casts one ray from the cage (`BakeRequest::cage`, same triangles as the low poly) or from `max_frontal` in front of the surface back through it to `max_rear` behind (both relative to the bounding-box diagonal), along normals averaged over hard edges when `average_normals` is on. With `BakeMatch::ByMeshName`, a low-poly part only sees high-poly parts of the same name once `low_suffix` / `high_suffix` are removed (`wheel_low` ↔ `wheel_high`, case-insensitive). Every map but position and world-space direction then reads the high-poly surface that ray found (AO, thickness and bent normals cast against the high poly).
+## Projection and common settings
-Ambient occlusion, thickness and bent normals each have their own `RaySettings`: ray count, max distance (relative to the bounding-box diagonal), spread angle (the full cone around the normal; 180° = the hemisphere) and distribution (cosine-weighted or uniform over the cone). Ambient occlusion can ignore back faces and limit occluders to parts of the same mesh name (`SelfOcclusion::SameMeshName`); bent normals follow those occluder rules and share the AO rays when their settings match.
+- Independent output width and height, antialiasing, per-UV-tile dilation, and optional background diffusion
+- High-to-low matching: Always by default, or By Mesh Name using the configured low/high suffixes
+- Transfer-ray backface filtering, distance-based or custom-file cages, frontal/rear distances, and averaged normals
+- Relative distances use the longest bounding-box extent; absolute distances use imported mesh units
+- Painted cage values multiply the frontal distance; painted skew values blend toward mesh or face normals, with optional hard-edge protection
-| Map | Meaning | Range |
-| --- | --- | --- |
-| Ambient occlusion | How open the surface is (rays over the cone, distance falloff) | 0 occluded … 1 open |
-| Bent normals | Mean unoccluded direction of the bent-normal rays, world space | packed ·0.5+0.5 |
-| Thickness | Mean distance through the mesh along inward rays, relative to the max distance | 0 thin … 1 thick |
-| Curvature | Mean curvature of the position-welded mesh, or (`curvature_from_normal`) the divergence of the baked normal map over `curvature_radius` texels (0: by resolution) | 0 concave … 0.5 flat … 1 convex |
-| Normal | Tangent-space normal from the high poly (OpenGL, +Y up); flat without one | packed ·0.5+0.5 |
-| Height | High-poly offset along the ray, scaled by frontal + rear distance | 0 rear … 0.5 surface … 1 front |
-| World normal | Shading normal in world space | packed ·0.5+0.5 |
-| Position | Position in the low poly's bounding box (per axis) or bounding sphere (`position_mode`) | 0 … 1 |
-| ID | A distinct hue per mesh part (submesh) | RGB 0 … 1 |
-| Opacity | 1 where the high poly was found (times its vertex and base color alpha), 0 where the ray missed | 0 … 1 |
-| Color map | The high poly's vertex colors times its materials' base color (`HighPoly::base_color`: factor × texture at the hit UV, bilinear in linear light), sRGB-encoded like a base color texture | RGB 0 … 1 |
-| World space direction | Facing ratio towards `direction`: signed (0.5 perpendicular) or positive (`direction_mode`) | 0 away … 1 facing |
+`BakePaintMap` contains pixel data only. Cage and skew settings remain in their respective model containers. The engine stores paint maps per texture set in document snapshots and project files. The shared 2D brush supports undo, redo, reset, and UV-layout changes.
-Uncovered texels beyond the padding get `BakedMap::neutral` values. Benchmarks (2K, the 7 default maps at 64 rays): `cargo test -p texturecraft-bake --release -- --ignored --nocapture bench` (CPU, per-map breakdown) and `cargo test -p texturecraft-render --release --lib -- --ignored --nocapture gpu_bake_speed` (CPU vs GPU).
+## Map settings
+
+| Map | Implemented behavior |
+| --- | --- |
+| Normal | Tangent-space high-poly normal, internally OpenGL; flat without a high-poly transfer |
+| World Normal | World-space shading normal |
+| ID | Vertex Color, Material Color, Mesh ID, Submesh ID, or File ID; Hue Shift, Random, and Grayscale generation |
+| Ambient Occlusion | Independent ray count, distance interval, units, cone and distribution; backface and self-occlusion modes; None, Linear or Smooth attenuation; optional ground plane |
+| Bent Normal | Independent occlusion settings and mean visible direction, encoded in world space |
+| Thickness | Inward ray distances with self-occlusion filtering; raw, ray-distance or per-UV-tile min/max normalization |
+| Curvature | Mesh-ray curvature with radius, ray count, self-intersection and automatic/manual tonemapping; normal-map curvature with detail strength and corresponding UV-edge seam blending |
+| Position | All axes or a selected axis; scene or material bounds; box, uniform sphere-style or raw coordinates |
+| Height | Signed high-poly displacement with low-mesh, min/max, ray-distance or manual normalization |
+| Opacity | High-poly hit coverage multiplied by source vertex/material/texture alpha |
+
+ID Material Color reads the material factor independently of textures and vertex colors. A source without material colors uses neutral gray (0.6). Generated IDs are deterministic. Normal maps are stored in OpenGL convention; display/export apply the project's normal format.
+
+All dropdowns use enums. `BakedMap::id()` and `BakedMap::parse()` provide the shared MaterialCraft mesh-map identifiers. `bake.settings` accepts the complete nested model. No legacy Color or World Orientation map migration is provided.
+
+## Validation and limits
+
+Regression tests cover projection, matching, ray filters, normalization, rectangular maps, painting, persistence, and CPU/GPU agreement. The supplied 2048² high-to-low reference is evaluated separately, outside the repository, on UV-covered pixels. Numerical differences remain, especially in curvature and occlusion; exact Painter parity is not claimed. Painted cage control currently uses the 2D UV brush; it does not provide a 3D cage-editing overlay.
+
+CPU benchmark: `cargo test -p texturecraft-bake --release -- --ignored --nocapture bench`.
+GPU comparison: `cargo test -p texturecraft-render --release --lib -- --ignored --nocapture gpu_bake_speed`.
diff --git a/crates/bake/src/bake_error.rs b/crates/bake/src/bake_error.rs
new file mode 100644
index 00000000..f9fe3879
--- /dev/null
+++ b/crates/bake/src/bake_error.rs
@@ -0,0 +1,9 @@
+#[derive(Debug, thiserror::Error)]
+pub enum BakeError {
+ #[error("bake cancelled")]
+ Cancelled,
+ #[error("invalid bake request: {0}")]
+ Invalid(String),
+ #[error("ray tracer: {0}")]
+ Tracer(String),
+}
diff --git a/crates/bake/src/bake_output.rs b/crates/bake/src/bake_output.rs
new file mode 100644
index 00000000..bc021f6f
--- /dev/null
+++ b/crates/bake/src/bake_output.rs
@@ -0,0 +1,11 @@
+use std::collections::BTreeMap;
+use texturecraft_core::BakedMap;
+
+#[derive(Clone, Debug, PartialEq)]
+/// Row-major maps, with BakedMap::components() floats per texel
+pub struct BakeOutput {
+ pub resolution: u32,
+ pub height: u32,
+ pub maps: BTreeMap>,
+ pub tracer: String,
+}
diff --git a/crates/bake/src/bake_paint_map.rs b/crates/bake/src/bake_paint_map.rs
new file mode 100644
index 00000000..cf6f0b4d
--- /dev/null
+++ b/crates/bake/src/bake_paint_map.rs
@@ -0,0 +1,130 @@
+use crate::{BakeError, MAX_TEXELS};
+use texturecraft_geom::glam::Vec2;
+
+pub const MAX_DABS: usize = 200_000;
+
+// Bound total work across all dabs before changing any pixels
+pub const MAX_PAINT_TEXELS: u64 = 1 << 26;
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct BakePaintMap {
+ pub width: u32,
+ pub height: u32,
+ /// Values in 0..=1 over the texture set UV atlas
+ pub values: Vec,
+}
+
+impl BakePaintMap {
+ pub fn constant(value: f32) -> BakePaintMap {
+ BakePaintMap { width: 1, height: 1, values: vec![value] }
+ }
+
+ pub fn validate(&self) -> Result<(), BakeError> {
+ let invalid = |m: &str| Err(BakeError::Invalid(m.into()));
+ let texels = u64::from(self.width) * u64::from(self.height);
+ if self.width == 0 || self.height == 0 || texels > MAX_TEXELS || self.values.len() as u64 != texels {
+ return invalid("the bake paint map's size doesn't match its values");
+ }
+ if self.values.iter().any(|v| !v.is_finite()) {
+ return invalid("the bake paint map has a value that is not a finite number");
+ }
+ Ok(())
+ }
+
+ pub fn resized(&self, width: u32, height: u32) -> Result {
+ let texels = u64::from(width) * u64::from(height);
+ if width == 0 || height == 0 || texels > MAX_TEXELS {
+ return Err(BakeError::Invalid(format!("a {width} × {height} bake paint map is outside the supported size")));
+ }
+ let mut values = Vec::with_capacity(texels as usize);
+ for y in 0..height {
+ let v = (y as f32 + 0.5) / height as f32;
+ for x in 0..width {
+ values.push(self.sample(Vec2::new((x as f32 + 0.5) / width as f32, v)));
+ }
+ }
+ Ok(BakePaintMap { width, height, values })
+ }
+
+ pub fn paint(&mut self, points: &[Vec2], radius: f32, value: f32, hardness: f32, strength: f32) -> Result<(), BakeError> {
+ let ok = radius.is_finite() && radius > 0.0 && value.is_finite() && hardness.is_finite() && strength.is_finite();
+ if !ok || points.iter().any(|p| !p.is_finite()) {
+ return Err(BakeError::Invalid("the bake brush needs finite numbers and a radius above 0".into()));
+ }
+ self.validate()?;
+ let (value, hardness, strength) = (value.clamp(0.0, 1.0), hardness.clamp(0.0, 0.999), strength.clamp(0.0, 1.0));
+ let step = (radius * 0.25).max(1e-5);
+ let mut dabs = Vec::new();
+ for (i, p) in points.iter().enumerate() {
+ match i.checked_sub(1).and_then(|j| points.get(j)) {
+ Some(prev) => {
+ let n = ((*p - *prev).length() / step).ceil().clamp(1.0, MAX_DABS as f32) as usize;
+ dabs.extend((1..=n).map(|k| *prev + (*p - *prev) * (k as f32 / n as f32)));
+ }
+ None => dabs.push(*p),
+ }
+ if dabs.len() > MAX_DABS {
+ return Err(BakeError::Invalid(format!("a bake stroke is limited to {MAX_DABS} dabs; use a larger radius or fewer points")));
+ }
+ }
+ let (w, h) = (self.width as usize, self.height as usize);
+ let span = |c: Vec2| {
+ let x0 = (((c.x - radius) * w as f32).floor().max(0.0)) as usize;
+ let x1 = (((c.x + radius) * w as f32).ceil().min(w as f32)).max(0.0) as usize;
+ let y0 = (((c.y - radius) * h as f32).floor().max(0.0)) as usize;
+ let y1 = (((c.y + radius) * h as f32).ceil().min(h as f32)).max(0.0) as usize;
+ (x0, x1, y0, y1)
+ };
+ let work: u64 = dabs
+ .iter()
+ .map(|c| {
+ let (x0, x1, y0, y1) = span(*c);
+ x1.saturating_sub(x0) as u64 * y1.saturating_sub(y0) as u64
+ })
+ .fold(0, u64::saturating_add);
+ if work > MAX_PAINT_TEXELS {
+ return Err(BakeError::Invalid(format!(
+ "this stroke would visit {work} texels (limit {MAX_PAINT_TEXELS}); use a smaller radius, a smaller map or a shorter stroke"
+ )));
+ }
+ for c in dabs {
+ let (x0, x1, y0, y1) = span(c);
+ for y in y0..y1 {
+ let dv = (y as f32 + 0.5) / h as f32 - c.y;
+ for x in x0..x1 {
+ let du = (x as f32 + 0.5) / w as f32 - c.x;
+ let t = (du * du + dv * dv).sqrt() / radius;
+ if t >= 1.0 {
+ continue;
+ }
+ let fall = if t <= hardness {
+ 1.0
+ } else {
+ let k = (1.0 - t) / (1.0 - hardness);
+ k * k * (3.0 - 2.0 * k)
+ };
+ if let Some(v) = self.values.get_mut(y * w + x) {
+ *v += (value - *v) * fall * strength;
+ }
+ }
+ }
+ }
+ Ok(())
+ }
+
+ pub fn sample(&self, uv: Vec2) -> f32 {
+ let (w, h) = (self.width.max(1) as usize, self.height.max(1) as usize);
+ if !uv.is_finite() {
+ return 0.0;
+ }
+ let x = (uv.x.clamp(0.0, 1.0) * w as f32 - 0.5).clamp(0.0, w as f32 - 1.0);
+ let y = (uv.y.clamp(0.0, 1.0) * h as f32 - 0.5).clamp(0.0, h as f32 - 1.0);
+ let (x0, y0) = (x.floor() as usize, y.floor() as usize);
+ let (x1, y1) = ((x0 + 1).min(w - 1), (y0 + 1).min(h - 1));
+ let (fx, fy) = (x - x0 as f32, y - y0 as f32);
+ let v = |xx: usize, yy: usize| self.values.get(yy * w + xx).copied().unwrap_or(0.0);
+ let top = v(x0, y0) * (1.0 - fx) + v(x1, y0) * fx;
+ let bottom = v(x0, y1) * (1.0 - fx) + v(x1, y1) * fx;
+ (top * (1.0 - fy) + bottom * fy).clamp(0.0, 1.0)
+ }
+}
diff --git a/crates/bake/src/bake_request.rs b/crates/bake/src/bake_request.rs
new file mode 100644
index 00000000..69925325
--- /dev/null
+++ b/crates/bake/src/bake_request.rs
@@ -0,0 +1,19 @@
+use crate::{BakePaintMap, HighPoly};
+use std::sync::Arc;
+use texturecraft_core::BakeSettings;
+use texturecraft_geom::{BaseColor, Bvh, Mesh};
+
+#[derive(Clone, Copy, Debug)]
+pub struct BakeRequest<'a> {
+ pub mesh: &'a Mesh,
+ pub bvh: &'a Bvh,
+ pub material: usize,
+ pub low_base_color: &'a [Option>],
+ pub settings: &'a BakeSettings,
+ pub high: Option>,
+ pub cage: Option<&'a Mesh>,
+ pub skew: Option<&'a BakePaintMap>,
+ pub cage_paint: Option<&'a BakePaintMap>,
+ /// UV atlas grid; each tile uses the configured output resolution
+ pub tiles: (u32, u32),
+}
diff --git a/crates/bake/src/cage.rs b/crates/bake/src/cage.rs
new file mode 100644
index 00000000..d2c7d7f3
--- /dev/null
+++ b/crates/bake/src/cage.rs
@@ -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;
diff --git a/crates/bake/src/cage/cage_shell.rs b/crates/bake/src/cage/cage_shell.rs
new file mode 100644
index 00000000..07a8eff2
--- /dev/null
+++ b/crates/bake/src/cage/cage_shell.rs
@@ -0,0 +1,98 @@
+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,
+ pub starts: Vec,
+ /// Corner pairs along the low poly's polygon edges, for the wireframe
+ pub edges: Vec<[u32; 2]>,
+ /// Corner pairs along the low poly's hard edges without a UV seam
+ pub missing_seams: 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 {
+ let ray_frame = RayFrame::new(request, MeshExtent::of(request.mesh)?)?;
+ Self::build(request, ray_frame, || {
+ // Each scan drops other materials' edges before the next scan starts
+ let wire_edges = request.mesh.wire_edges().into_iter().nth(request.material).unwrap_or_default().into_iter().collect();
+ let missing_seam_edges = request.mesh.missing_seam_edges().into_iter().nth(request.material).unwrap_or_default().into_iter().collect();
+ (wire_edges, missing_seam_edges)
+ })
+ }
+
+ /// Build a cage using edges already scanned for every material of the low mesh
+ pub fn new_with_edges(request: &BakeRequest, wire_edges: &[Vec<(u32, u32)>], missing_seam_edges: &[Vec<(u32, u32)>]) -> Result {
+ let ray_frame = RayFrame::new(request, MeshExtent::of(request.mesh)?)?;
+ Self::build(request, ray_frame, || {
+ (
+ wire_edges.get(request.material).into_iter().flatten().copied().collect(),
+ missing_seam_edges.get(request.material).into_iter().flatten().copied().collect(),
+ )
+ })
+ }
+
+ fn build(
+ request: &BakeRequest,
+ ray_frame: RayFrame,
+ edge_sets: impl FnOnce() -> (HashSet<(u32, u32)>, HashSet<(u32, u32)>),
+ ) -> Result {
+ let (frame, mesh) = (&ray_frame, request.mesh);
+ let triangles: Vec = mesh.triangles_of(request.material).collect();
+ let (positions, starts): (Vec, Vec) = 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, missing_seam_edges) = edge_sets();
+ let (mut edge_corners, mut seam_corners) = (HashMap::new(), 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));
+ let first_corner = (triangle_index * 3) as u32;
+ let corners = [first_corner + corner as u32, first_corner + next as u32];
+ if wire_edges.contains(&key) {
+ edge_corners.entry(key).or_insert(corners);
+ }
+ if missing_seam_edges.contains(&key) {
+ seam_corners.entry(key).or_insert(corners);
+ }
+ }
+ }
+ let sorted = |corners: HashMap<(u32, u32), [u32; 2]>| {
+ let mut pairs: Vec<[u32; 2]> = corners.into_values().collect();
+ pairs.sort_unstable();
+ pairs
+ };
+
+ Ok(CageShell { positions, starts, edges: sorted(edge_corners), missing_seams: sorted(seam_corners), 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 {
+ let frontal = max_frontal * self.cage_units;
+ self.positions.par_iter().zip(&self.starts).map(|(position, start)| start.origin(*position, frontal)).collect()
+ }
+}
diff --git a/crates/bake/src/cage/high_poly_reach.rs b/crates/bake/src/cage/high_poly_reach.rs
new file mode 100644
index 00000000..2f461343
--- /dev/null
+++ b/crates/bake/src/cage/high_poly_reach.rs
@@ -0,0 +1,105 @@
+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>,
+ /// 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 {
+ 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 {
+ 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 {
+ let mut keys = vec![ANY; mesh.positions.len()];
+ for (corners, &triangle_key) in mesh.indices.as_chunks::<3>().0.iter().zip(triangle_keys) {
+ for &corner in corners {
+ 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 {
+ let mut normals = vec![Vec3::ZERO; mesh.positions.len()];
+ for corners in mesh.indices.as_chunks::<3>().0 {
+ 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
+}
diff --git a/crates/bake/src/cage/ray_frame.rs b/crates/bake/src/cage/ray_frame.rs
new file mode 100644
index 00000000..e8692cf2
--- /dev/null
+++ b/crates/bake/src/cage/ray_frame.rs
@@ -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,
+ cage: Option<&'a Mesh>,
+ skew: Option>,
+ 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, 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)) }
+ }
+}
diff --git a/crates/bake/src/cage/ray_start.rs b/crates/bake/src/cage/ray_start.rs
new file mode 100644
index 00000000..c0c3923a
--- /dev/null
+++ b/crates/bake/src/cage/ray_start.rs
@@ -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,
+ }
+ }
+}
diff --git a/crates/bake/src/cage/vertex_reach.rs b/crates/bake/src/cage/vertex_reach.rs
new file mode 100644
index 00000000..34adea92
--- /dev/null
+++ b/crates/bake/src/cage/vertex_reach.rs
@@ -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)
+ }
+}
diff --git a/crates/bake/src/high_poly.rs b/crates/bake/src/high_poly.rs
new file mode 100644
index 00000000..9901f0e7
--- /dev/null
+++ b/crates/bake/src/high_poly.rs
@@ -0,0 +1,10 @@
+use std::sync::Arc;
+use texturecraft_geom::{BaseColor, Bvh, Mesh};
+
+#[derive(Clone, Copy, Debug)]
+pub struct HighPoly<'a> {
+ pub file_ids: &'a [u32],
+ pub mesh: &'a Mesh,
+ pub bvh: &'a Bvh,
+ pub base_color: &'a [Option>],
+}
diff --git a/crates/bake/src/lib.rs b/crates/bake/src/lib.rs
index 39d466e1..1d99ab36 100644
--- a/crates/bake/src/lib.rs
+++ b/crates/bake/src/lib.rs
@@ -1,374 +1,430 @@
-//! # texturecraft-bake
-//!
-//! Mesh-map baking. [`bake`] rasterizes one texture set's UV layout with a supersampled
-//! [`UvGBuffer`] and works through it in batches of samples: the high-poly transfer rays, then
-//! the secondary rays of ambient occlusion, bent normals and thickness (each with its own
-//! [`texturecraft_core::RaySettings`]) go to a [`rays::Tracer`], then every requested
-//! [`BakedMap`] is evaluated per sample (rayon over rows), box-downsampled, and the UV islands
-//! are padded with [`DilationMap`]. The rays run on the CPU ([`rays::CpuTracer`], the oracle) or
-//! on a GPU tracer passed to [`bake_on`]. With a high poly, every map but position and
-//! world-space direction reads the high-poly surface found along the cage / frontal-rear ray;
-//! the color map multiplies its vertex colors by its materials' [`BaseColor`]s. Sampling is
-//! deterministic, so the same request always gives the same pixels.
+//! Deterministic mesh-map baking with bounded batches and CPU fallback
+
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
-mod maps;
-pub mod rays;
+mod bake_error;
+mod bake_output;
+mod bake_request;
+mod cage;
+mod high_poly;
+mod mesh_extent;
+mod name_pair;
+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 name_pair::NamePair;
+pub use progress::Progress;
+
+mod map;
mod skew;
#[cfg(test)]
mod tests;
+pub mod tracing;
use std::collections::BTreeMap;
-use std::sync::Arc;
-use std::sync::atomic::{AtomicBool, AtomicU32, Ordering::Relaxed};
+use std::sync::atomic::Ordering::Relaxed;
use rayon::prelude::*;
-use texturecraft_core::{BakeSettings, BakedMap};
+use texturecraft_core::{BakedMap, CurvatureMethod};
use texturecraft_geom::glam::{Vec2, Vec3};
-use texturecraft_geom::{BaseColor, Bvh, Mesh, NO_TRI, UvGBuffer};
+use texturecraft_geom::{Mesh, NO_TRI, Surface, UvGBuffer};
use texturecraft_texel::DilationMap;
-use crate::rays::{CpuTracer, RayScene, Tracer};
-pub use crate::skew::SkewMap;
+mod bake_paint_map;
+use crate::tracing::{CpuTracer, RayScene, Tracer};
+pub use bake_paint_map::BakePaintMap;
-/// Largest accepted output resolution (per axis).
pub const MAX_RESOLUTION: u32 = 8192;
-/// Largest accepted ray count per texel (AO, thickness).
pub const MAX_RAYS: u32 = 4096;
-/// Largest accepted output (texels over every UV tile).
pub const MAX_TEXELS: u64 = 1 << 27;
-/// Supersampled texels rasterized at once: bounds the G-buffer at ~200 MB for any resolution × AA.
+// Bound each supersampled G-buffer to roughly 200 MB
const STRIP_TEXELS: usize = 1 << 24;
-/// Supersamples ray-cast per batch: bounds the per-sample buffers (~40 MB) and a GPU submission.
const BATCH: usize = 1 << 18;
+// Curvature batches stay small so progress and cancellation remain responsive
+const CURVATURE_BATCH: usize = 1 << 15;
-/// Shared progress / cancellation flag of a running bake.
-#[derive(Debug, Default)]
-pub struct Progress {
- /// Basis points, 0..=10_000 (all requested maps done).
- pub done: AtomicU32,
- pub cancel: AtomicBool,
-}
+fn validate(request: &BakeRequest) -> Result<(), BakeError> {
+ let settings = request.settings;
+ let invalid = |message: String| Err(BakeError::Invalid(message));
+ let (resolution, resolution_height) = settings.common.output_size();
-impl Progress {
- pub fn new() -> Self {
- Self::default()
+ let (columns, rows) = request.tiles;
+ let width = u64::from(resolution) * u64::from(columns);
+ let height = u64::from(resolution_height) * u64::from(rows);
+ if columns == 0 || rows == 0 || width.saturating_mul(height) > MAX_TEXELS {
+ return invalid(format!("{columns} × {rows} UV tiles at {} exceed {MAX_TEXELS} texels", resolution));
}
- /// Completed fraction, 0..=1.
- pub fn fraction(&self) -> f32 {
- self.done.load(Relaxed).min(10_000) as f32 / 10_000.0
- }
-
- /// Ask the bake to stop; it returns [`BakeError::Cancelled`] at the next row.
- pub fn cancel(&self) {
- self.cancel.store(true, Relaxed);
- }
-}
-
-/// A high-poly source mesh (all high-definition meshes appended into one).
-#[derive(Clone, Copy, Debug)]
-pub struct HighPoly<'a> {
- pub mesh: &'a Mesh,
- pub bvh: &'a Bvh,
- /// Base color per material of `mesh` (missing or None: white).
- pub base_color: &'a [Option>],
-}
-
-/// One texture set to bake.
-#[derive(Clone, Copy, Debug)]
-pub struct BakeRequest<'a> {
- pub mesh: &'a Mesh,
- /// BVH of the whole low-poly mesh: every material occludes.
- pub bvh: &'a Bvh,
- pub material: usize,
- pub settings: &'a BakeSettings,
- pub high: Option>,
- /// Cage: the low poly inflated (same triangles); transfer rays start on it.
- pub cage: Option<&'a Mesh>,
- /// Skew correction of the high-poly transfer rays (see [`SkewMap`]); ignored with a cage mesh.
- pub skew: Option<&'a SkewMap>,
- /// UV tile grid (columns, rows) of the texture set: the maps are `settings.resolution` per
- /// tile, (1, 1) for a classic set. The mesh's UVs are in atlas space (0..1 over the grid).
- pub tiles: (u32, u32),
-}
-
-/// Baked maps: row-major `resolution × height`, `BakedMap::components()` floats per texel,
-/// rows top → bottom (y = v·H, as [`UvGBuffer`]).
-#[derive(Clone, Debug, PartialEq)]
-pub struct BakeOutput {
- /// Width in texels.
- pub resolution: u32,
- pub height: u32,
- pub maps: BTreeMap>,
- /// Where the rays ran ([`Tracer::name`]).
- pub tracer: String,
-}
-
-#[derive(Debug, thiserror::Error)]
-pub enum BakeError {
- #[error("bake cancelled")]
- Cancelled,
- #[error("invalid bake request: {0}")]
- Invalid(String),
- /// The ray tracer failed ([`bake_on`] then bakes on the CPU).
- #[error("ray tracer: {0}")]
- Tracer(String),
-}
-
-fn validate(req: &BakeRequest) -> Result<(), BakeError> {
- let s = req.settings;
- let invalid = |m: String| Err(BakeError::Invalid(m));
- if s.resolution == 0 || s.resolution > MAX_RESOLUTION {
- return invalid(format!("resolution {} is not in 1..={MAX_RESOLUTION}", s.resolution));
- }
- let (cols, rows) = req.tiles;
- if cols == 0 || rows == 0 || (s.resolution as u64 * cols as u64) * (s.resolution as u64 * rows as u64) > MAX_TEXELS {
- return invalid(format!("{cols} × {rows} UV tiles at {} exceed {MAX_TEXELS} texels", s.resolution));
- }
- if ![1, 2, 4, 8].contains(&s.antialiasing) {
- return invalid(format!("antialiasing {} is not 1, 2, 4 or 8", s.antialiasing));
- }
- for (map, r) in [(BakedMap::AmbientOcclusion, &s.ao), (BakedMap::Thickness, &s.thickness), (BakedMap::BentNormal, &s.bent_normal)] {
- if !s.maps.contains(&map) {
+ for (map, ray_settings) in [
+ (BakedMap::AmbientOcclusion, &settings.maps.ao.parameters.rays),
+ (BakedMap::Thickness, &settings.maps.thickness.parameters.rays),
+ (BakedMap::BentNormal, &settings.maps.bent_normal.parameters.rays),
+ ] {
+ if !settings.maps.is_enabled(map) {
continue;
}
- if r.rays == 0 || r.rays > MAX_RAYS {
- return invalid(format!("{} ray count {} is not in 1..={MAX_RAYS}", map.label(), r.rays));
+
+ if ray_settings.rays == 0 || ray_settings.rays > MAX_RAYS {
+ return invalid(format!("{} ray count {} is not in 1..={MAX_RAYS}", map.id(), ray_settings.rays));
}
- if !(r.max_distance.is_finite() && r.max_distance > 0.0) {
- return invalid(format!("{} max distance {} must be positive", map.label(), r.max_distance));
+
+ if !(ray_settings.max_distance.is_finite() && ray_settings.max_distance > 0.0) {
+ return invalid(format!("{} max distance {} must be positive", map.id(), ray_settings.max_distance));
}
- if !r.spread.is_finite() {
- return invalid(format!("{} spread angle is not finite", map.label()));
+
+ if !(ray_settings.min_distance.is_finite() && ray_settings.min_distance >= 0.0 && ray_settings.min_distance <= ray_settings.max_distance) {
+ return invalid(format!("{} minimum distance must be finite and between zero and its maximum distance", map.id()));
+ }
+ if !ray_settings.spread.is_finite() || !(0.0..=180.0).contains(&ray_settings.spread) {
+ return invalid(format!("{} spread angle is not finite", map.id()));
}
}
- if !s.curvature_strength.is_finite() {
- return invalid("curvature strength is not finite".into());
+
+ if !(settings.cage.max_frontal.is_finite() && settings.cage.max_frontal >= 0.0 && settings.cage.max_rear.is_finite() && settings.cage.max_rear >= 0.0) {
+ return invalid(format!("frontal/rear distances {}/{} must be finite and ≥ 0", settings.cage.max_frontal, settings.cage.max_rear));
}
- if !(s.direction.iter().all(|c| c.is_finite()) && s.direction.iter().any(|c| *c != 0.0)) {
- return invalid(format!("direction {:?} must be finite and non-zero", s.direction));
- }
- if !(s.max_frontal.is_finite() && s.max_frontal >= 0.0 && s.max_rear.is_finite() && s.max_rear >= 0.0) {
- return invalid(format!("frontal/rear distances {}/{} must be finite and ≥ 0", s.max_frontal, s.max_rear));
- }
- req.mesh.validate().map_err(|e| BakeError::Invalid(e.to_string()))?;
- if req.material >= req.mesh.materials.len().max(1) {
- return invalid(format!("material {} out of range ({} materials)", req.material, req.mesh.materials.len()));
- }
- if let Some(h) = &req.high {
- h.mesh.validate().map_err(|e| BakeError::Invalid(format!("high poly: {e}")))?;
- }
- if let Some(c) = req.cage {
- c.validate().map_err(|e| BakeError::Invalid(format!("cage: {e}")))?;
- if c.indices.len() != req.mesh.indices.len() {
- return invalid(format!("the cage has {} triangles, the low poly {}", c.triangle_count(), req.mesh.triangle_count()));
+ let curvature = settings.maps.curvature.parameters;
+ if settings.maps.curvature.is_enabled {
+ if curvature.mesh.rays == 0 || curvature.mesh.rays > MAX_RAYS || !curvature.mesh.sampling_radius.is_finite() || curvature.mesh.sampling_radius <= 0.0 {
+ return invalid("curvature requires a positive finite radius and a supported ray count".into());
+ }
+ if !curvature.mesh.value_min.is_finite()
+ || !curvature.mesh.value_max.is_finite()
+ || (!curvature.mesh.auto_tonemapping && curvature.mesh.value_min >= curvature.mesh.value_max)
+ {
+ return invalid("curvature bounds must be finite, with minimum below maximum".into());
}
}
+ for (name, value) in [
+ ("edge distance", settings.skew.edge_distance),
+ ("edge contrast", settings.skew.edge_contrast),
+ ("curvature details", curvature.normal_map.details),
+ ("seam intensity", curvature.normal_map.seams_intensity),
+ ] {
+ if !value.is_finite() || !(0.0..=1.0).contains(&value) {
+ return invalid(format!("{name} must be finite and in 0..=1"));
+ }
+ }
+ if settings.maps.height.is_enabled
+ && (!settings.maps.height.parameters.scaling_divisor.is_finite() || settings.maps.height.parameters.scaling_divisor <= 0.0)
+ {
+ return invalid("height scaling divisor must be finite and positive".into());
+ }
+ if !settings.maps.ao.parameters.ground_plane.offset.is_finite() || settings.maps.ao.parameters.ground_plane.offset < 0.0 {
+ return invalid("ground plane offset must be finite and nonnegative".into());
+ }
+ request.mesh.validate().map_err(|e| BakeError::Invalid(e.to_string()))?;
+ if request.material >= request.mesh.materials.len().max(1) {
+ return invalid(format!("material {} out of range ({} materials)", request.material, request.mesh.materials.len()));
+ }
+
+ if let Some(high) = &request.high {
+ high.mesh.validate().map_err(|e| BakeError::Invalid(format!("high poly: {e}")))?;
+ }
+
+ if let Some(map) = request.cage_paint {
+ map.validate()?;
+ }
+ if let Some(cage) = request.cage {
+ cage.validate().map_err(|e| BakeError::Invalid(format!("cage: {e}")))?;
+ if cage.indices.len() != request.mesh.indices.len() {
+ return invalid(format!("the cage has {} triangles, the low poly {}", cage.triangle_count(), request.mesh.triangle_count()));
+ }
+ }
+
Ok(())
}
-/// `vec![value; n]` that reports allocation failure instead of aborting.
-fn alloc(n: usize, value: T) -> Result, BakeError> {
- let mut v = Vec::new();
- v.try_reserve_exact(n).map_err(|_| BakeError::Invalid(format!("out of memory allocating {n} texels")))?;
- v.resize(n, value);
- Ok(v)
+fn alloc(count: usize, value: T) -> Result, BakeError> {
+ let mut values = Vec::new();
+ values.try_reserve_exact(count).map_err(|_| BakeError::Invalid(format!("out of memory allocating {count} texels")))?;
+ values.resize(count, value);
+ Ok(values)
}
-/// Bake the maps in `req.settings.maps` for one material of the low-poly mesh, on the CPU.
-pub fn bake(req: &BakeRequest, progress: &Progress) -> Result {
- bake_in_strips(req, progress, STRIP_TEXELS, &CpuTracer)
+pub fn bake(request: &BakeRequest, progress: &Progress) -> Result {
+ bake_in_strips(request, progress, STRIP_TEXELS, &CpuTracer, &[])
}
-/// [`bake`] with the rays cast by `tracer` (a GPU); when the tracer fails (no adapter, a mesh
-/// too large for it, a lost device) the bake runs again on the CPU.
-pub fn bake_on(req: &BakeRequest, progress: &Progress, tracer: &dyn Tracer) -> Result {
- match bake_in_strips(req, progress, STRIP_TEXELS, tracer) {
- Err(BakeError::Tracer(e)) => {
- let mut out = bake(req, progress)?;
- out.tracer = format!("CPU ({} unavailable: {e})", tracer.name());
- Ok(out)
+/// Retry on the CPU if the supplied tracer fails
+pub fn bake_on(request: &BakeRequest, progress: &Progress, tracer: &dyn Tracer) -> Result {
+ 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 {
+ let tracer = tracer.unwrap_or(&CpuTracer);
+ match bake_in_strips(request, progress, STRIP_TEXELS, tracer, excluded_tiles) {
+ Err(BakeError::Tracer(error)) => {
+ let mut output = bake_in_strips(request, progress, STRIP_TEXELS, &CpuTracer, excluded_tiles)?;
+ output.tracer = format!("CPU ({} unavailable: {error})", tracer.name());
+ Ok(output)
}
- r => r,
+ result => result,
}
}
-/// One output row of a strip: its slice of every map.
type OutRow<'a> = Vec<&'a mut [f32]>;
-fn bake_in_strips(req: &BakeRequest, progress: &Progress, strip_texels: usize, tracer: &dyn Tracer) -> Result {
- validate(req)?;
- let s = req.settings;
- let (tile_res, aa) = (s.resolution as usize, s.antialiasing as usize);
- let (w, h) = (tile_res * req.tiles.0 as usize, tile_res * req.tiles.1 as usize);
- let ctx = maps::Ctx::new(req)?;
- let tracer = if ctx.casts_rays() { tracer } else { &CpuTracer };
- let meshes = ctx.trace_meshes();
+fn bake_in_strips(
+ request: &BakeRequest,
+ progress: &Progress,
+ strip_texels: usize,
+ tracer: &dyn Tracer,
+ excluded_tiles: &[(u32, u32)],
+) -> Result {
+ validate(request)?;
+ if excluded_tiles.iter().any(|(column, row)| *column >= request.tiles.0 || *row >= request.tiles.1) {
+ return Err(BakeError::Invalid("excluded UV tile lies outside the bake atlas".into()));
+ }
+
+ let settings = request.settings;
+ let (tile_width, tile_height) = settings.common.output_size();
+ let tile_size = (tile_width as usize, tile_height as usize);
+ let samples_per_axis = settings.common.antialiasing.samples_per_axis() as usize;
+ let (width, height) = (tile_size.0 * request.tiles.0 as usize, tile_size.1 * request.tiles.1 as usize);
+ let context = map::BakeContext::new(request)?;
+ let tracer = if context.casts_rays() { tracer } else { &CpuTracer };
+ let meshes = context.trace_meshes();
let mut scene = tracer.scene(&meshes)?;
progress.done.store(0, Relaxed);
- // Curvature from the normal map needs the normal map: baked alongside when not requested.
- let from_normal = s.curvature_from_normal && s.maps.contains(&BakedMap::Curvature);
- let mut maps: Vec = s.maps.iter().copied().collect();
- if from_normal && !maps.contains(&BakedMap::Normal) {
- maps.push(BakedMap::Normal);
+ // 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 = settings.maps.enabled().collect();
+ if from_normal && !maps.contains(&BakedMap::WorldNormal) {
+ maps.push(BakedMap::WorldNormal);
}
- let mut bufs = maps.iter().map(|m| alloc(w * h * m.components(), 0.0f32)).collect::, _>>()?;
- let mut covered = alloc(w * h, false)?;
- let mut pad = None;
- let total = h.max(1) as u64;
- let mut rows_done = 0u64;
- let strip_err = || BakeError::Invalid("strip out of range".into());
- // Rasterize in horizontal strips of the supersampled image: a strip's G-buffer is built from
- // UVs shifted so that y = v*H - strip_top, which keeps memory bounded at 8K x 8 AA.
- let (sw, full_h) = (w * aa, h * aa);
- let strip_rows = (strip_texels / (sw * aa)).max(1).min(h);
- let batch_rows = (BATCH / (sw * aa)).max(1);
- let mut strip_mesh = Mesh { indices: req.mesh.indices.clone(), submeshes: req.mesh.submeshes.clone(), ..Mesh::default() };
- for y0 in (0..h).step_by(strip_rows) {
- let rows = strip_rows.min(h - y0);
- let (sy0, sh) = (y0 * aa, rows * aa);
- strip_mesh.uvs = req.mesh.uvs.iter().map(|uv| Vec2::new(uv.x, (uv.y * full_h as f32 - sy0 as f32) / sh as f32)).collect();
- let g = UvGBuffer::new(&strip_mesh, req.material, sw as u32, sh as u32);
- // A texel is covered when any of its supersamples is.
- let cov = covered.get_mut(y0 * w..(y0 + rows) * w).ok_or_else(strip_err)?;
- cov.par_chunks_mut(w).enumerate().for_each(|(r, row)| {
- for (x, c) in row.iter_mut().enumerate() {
- *c = (0..aa * aa).any(|k| g.tri.get((r * aa + k / aa) * sw + x * aa + k % aa).is_some_and(|t| *t != NO_TRI));
+ let mut buffers = maps.iter().map(|map| alloc(width * height * map.components(), 0.0f32)).collect::, _>>()?;
+ let mut covered = alloc(width * height, false)?;
+ let mut padding_map = None;
+ let total_rows = height.max(1) as u64;
+ let mut rows_done = 0u64;
+ let strip_error = || BakeError::Invalid("strip output of range".into());
+
+ let (sample_width, sample_height) = (width * samples_per_axis, height * samples_per_axis);
+ let rows_per_strip = (strip_texels / (sample_width * samples_per_axis)).max(1).min(height);
+ let batch = if context.traces_curvature() { CURVATURE_BATCH } else { BATCH };
+ let rows_per_batch = (batch / (sample_width * samples_per_axis)).max(1);
+ let mut strip_mesh = Mesh { indices: request.mesh.indices.clone(), submeshes: request.mesh.submeshes.clone(), ..Mesh::default() };
+ for strip_start in (0..height).step_by(rows_per_strip) {
+ let rows = rows_per_strip.min(height - strip_start);
+ 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 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() {
+ *covered_pixel = (0..samples_per_axis * samples_per_axis).any(|sample_index| {
+ gbuffer
+ .tri
+ .get(
+ (row_index * samples_per_axis + sample_index / samples_per_axis) * sample_width
+ + x * samples_per_axis
+ + sample_index % samples_per_axis,
+ )
+ .is_some_and(|triangle_index| *triangle_index != NO_TRI)
+ });
}
});
- let mut out_rows: Vec = (0..rows).map(|_| Vec::with_capacity(maps.len())).collect();
- for (m, data) in maps.iter().zip(bufs.iter_mut()) {
- let comps = m.components();
- let strip = data.get_mut(y0 * w * comps..(y0 + rows) * w * comps).ok_or_else(strip_err)?;
- for (row, chunk) in out_rows.iter_mut().zip(strip.chunks_mut(w * comps)) {
+ let mut output_rows: Vec = (0..rows).map(|_| Vec::with_capacity(maps.len())).collect();
+ for (map, data) in maps.iter().zip(buffers.iter_mut()) {
+ let component_count = map.components();
+ let strip = data.get_mut(strip_start * width * component_count..(strip_start + rows) * width * component_count).ok_or_else(strip_error)?;
+ for (row, chunk) in output_rows.iter_mut().zip(strip.chunks_mut(width * component_count)) {
row.push(chunk);
}
}
let mut bake_strip = || {
- for (b, batch) in out_rows.chunks_mut(batch_rows).enumerate() {
+ for (batch_index, batch) in output_rows.chunks_mut(rows_per_batch).enumerate() {
if progress.cancel.load(Relaxed) {
return Err(BakeError::Cancelled);
}
- // Seed by the global supersample index so strips and batches don't change the noise.
- bake_rows(&ctx, &maps, req.mesh, &g, scene.as_mut(), batch, b * batch_rows, (w, aa, sy0 * sw))?;
+ // Global sample indices keep noise unchanged across strip and batch sizes
+ bake_rows(
+ &context,
+ &maps,
+ request.mesh,
+ &gbuffer,
+ scene.as_mut(),
+ batch,
+ batch_index * rows_per_batch,
+ (width, samples_per_axis, sample_start_y * sample_width),
+ )?;
rows_done += batch.len() as u64;
- progress.done.store((rows_done.saturating_mul(10_000) / total).min(10_000) as u32, Relaxed);
+ progress.done.store((rows_done.saturating_mul(10_000) / total_rows).min(10_000) as u32, Relaxed);
}
Ok(())
};
- if y0 + rows < h || s.dilation == 0 {
+ if strip_start + rows < height || (settings.common.dilation == 0 && !settings.common.apply_diffusion) {
bake_strip()?;
} else {
- // The coverage is complete: find the padding (UV tile by UV tile) while the last strip bakes.
- let padding = || DilationMap::in_blocks(&covered, w as u32, h as u32, Some(s.dilation), s.resolution);
- let (p, baked) = rayon::join(padding, bake_strip);
+ let padding =
+ || DilationMap::in_rectangular_blocks(&covered, width as u32, height as u32, Some(settings.common.dilation), (tile_width, tile_height));
+ let (padding, baked) = rayon::join(padding, bake_strip);
baked?;
- pad = Some(p);
+ padding_map = Some(padding);
}
}
- let mut out: BTreeMap> = maps.into_iter().zip(bufs).collect();
+ let mut output: BTreeMap> = maps.into_iter().zip(buffers).collect();
if from_normal {
- let normal = if s.maps.contains(&BakedMap::Normal) { out.get(&BakedMap::Normal).cloned() } else { out.remove(&BakedMap::Normal) };
- if let (Some(normal), Some(curv)) = (normal, out.get_mut(&BakedMap::Curvature)) {
- maps::curvature_from_normal(&normal, &covered, w, tile_res, s.curvature_radius, s.curvature_strength, curv);
+ 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;
+ 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);
+ }
}
}
- if let Some(pad) = pad {
- for (m, data) in out.iter_mut() {
- pad.apply(data, m.components());
+
+ 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 {
+ for (map, data) in output.iter_mut() {
+ padding_map.apply(data, map.components());
+ if settings.common.apply_diffusion {
+ map::diffuse(data, map.components(), &padding_map, tile_size);
+ }
}
}
+ if progress.cancel.load(Relaxed) {
+ return Err(BakeError::Cancelled);
+ }
progress.done.store(10_000, Relaxed);
- Ok(BakeOutput { resolution: w as u32, height: h as u32, maps: out, tracer: tracer.name() })
+ Ok(BakeOutput { resolution: width as u32, height: height as u32, maps: output, tracer: tracer.name() })
}
-/// Bake output rows `r0..` of a strip's G-buffer `g` into `rows`: gather the covered
-/// supersamples, cast their transfer and secondary rays in batches on `scene`, then evaluate
-/// and average every map per texel. `seed0` is the strip's first supersample index.
#[allow(clippy::too_many_arguments)]
fn bake_rows(
- ctx: &maps::Ctx,
+ context: &map::BakeContext,
maps: &[BakedMap],
mesh: &Mesh,
- g: &UvGBuffer,
+ gbuffer: &UvGBuffer,
scene: &mut dyn RayScene,
rows: &mut [OutRow],
- r0: usize,
- (w, aa, seed0): (usize, usize, usize),
+ first_row: usize,
+ (width, samples_per_axis, first_sample_seed): (usize, usize, usize),
) -> Result<(), BakeError> {
- let sw = w * aa;
- let per_row: Vec> = (r0..r0 + rows.len())
+ let sample_width = width * samples_per_axis;
+ let samples_by_row: Vec> = (first_row..first_row + rows.len())
.into_par_iter()
- .map(|r| {
- let subsamples = (0..w).flat_map(|x| (0..aa * aa).map(move |k| (x, (r * aa + k / aa) * sw + x * aa + k % aa)));
- subsamples.filter_map(|(x, i)| Some(maps::Sample { x, surf: g.surface(mesh, i)?, bary: *g.bary.get(i)?, seed: (seed0 + i) as u64 })).collect()
+ .map(|row| {
+ let subsamples = (0..width).flat_map(|x| {
+ (0..samples_per_axis * samples_per_axis).map(move |sample_index| {
+ (x, (row * samples_per_axis + sample_index / samples_per_axis) * sample_width + x * samples_per_axis + sample_index % samples_per_axis)
+ })
+ });
+ subsamples
+ .filter_map(|(x, sample_index)| {
+ Some(map::Sample {
+ x,
+ surface: gbuffer.surface(mesh, sample_index)?,
+ bary: *gbuffer.bary.get(sample_index)?,
+ seed: (first_sample_seed + sample_index) as u64,
+ })
+ })
+ .collect()
})
.collect();
- // Index of each row's first sample in the batch arrays.
- let starts: Vec = per_row
+ let row_offsets: Vec = samples_by_row
.iter()
- .scan(0, |n, r| {
- *n += r.len();
- Some(*n - r.len())
+ .scan(0, |sample_count, row| {
+ *sample_count += row.len();
+ Some(*sample_count - row.len())
})
.collect();
- let samples = || per_row.par_iter().flat_map_iter(|r| r.iter());
+ let samples = || samples_by_row.par_iter().flat_map_iter(|row| row.iter());
- let transfers = match ctx.has_high() {
+ let transfers = match context.has_high() {
true => {
- let (rays, fronts): (Vec, Vec) = samples().map(|p| ctx.transfer_ray(&p.surf, p.bary)).unzip();
- let hits = scene.closest(1, &rays)?;
- hits.into_par_iter().zip(fronts).map(|(hit, front)| ctx.transfer(hit, front)).collect()
+ let (rays, frontal_distances): (Vec, Vec) = samples().map(|sample| context.transfer_ray(&sample.surface, sample.bary)).unzip();
+ let hits = scene.closest(1, &rays, context.ignore_transfer_backface())?;
+ hits.into_par_iter().zip(frontal_distances).map(|(hit, front)| context.transfer(hit, front)).collect()
}
false => Vec::new(),
};
- let transfer = |k: usize| transfers.get(k).and_then(Option::as_ref);
- let queries: Vec = match ctx.ao.is_some() || ctx.bent.is_some() || ctx.thickness.is_some() {
+ let transfer = |sample_index: usize| transfers.get(sample_index).and_then(Option::as_ref);
+ let curvature = match context.traces_curvature() {
true => {
- per_row.par_iter().zip(&starts).flat_map_iter(|(r, &first)| r.iter().zip(first..)).map(|(p, k)| ctx.query(transfer(k), &p.surf, p.seed)).collect()
+ let items: Vec<(&Surface, Option<&map::Transfer>)> = samples_by_row
+ .iter()
+ .zip(&row_offsets)
+ .flat_map(|(row, &first)| row.iter().zip(first..))
+ .map(|(sample, sample_index)| (&sample.surface, transfer(sample_index)))
+ .collect();
+ context.trace_curvature(scene, &items)?
}
false => Vec::new(),
};
- // Bent normals come with the occlusion rays when they share the settings.
- let own_bent = ctx.bent.filter(|_| ctx.bent != ctx.ao);
- let passes: Vec = [ctx.ao, own_bent, ctx.thickness].into_iter().flatten().collect();
+ let queries: Vec = match context.ao.is_some() || context.bent.is_some() || context.thickness.is_some() {
+ true => samples_by_row
+ .par_iter()
+ .zip(&row_offsets)
+ .flat_map_iter(|(row, &first)| row.iter().zip(first..))
+ .map(|(sample, sample_index)| context.query(transfer(sample_index), &sample.surface, sample.seed))
+ .collect(),
+ false => Vec::new(),
+ };
+ // Share occlusion results when the bent-normal ray settings match
+ let separate_bent_pass = context.bent.filter(|_| context.bent != context.ao);
+ let passes: Vec = [context.ao, separate_bent_pass, context.thickness].into_iter().flatten().collect();
let mut results = scene.hemispheres(&passes, &queries)?.into_iter();
- let mut next = |on: bool| if on { results.next().unwrap_or_default() } else { Vec::new() };
- let (ao, bent_own, thickness) = (next(ctx.ao.is_some()), next(own_bent.is_some()), next(ctx.thickness.is_some()));
- let bent = if own_bent.is_some() { &bent_own } else { &ao };
+ let mut next = |enabled: bool| if enabled { results.next().unwrap_or_default() } else { Vec::new() };
+ let (occlusion_results, separate_bent_results, thickness) =
+ (next(context.ao.is_some()), next(separate_bent_pass.is_some()), next(context.thickness.is_some()));
+ let bent_results = if separate_bent_pass.is_some() { &separate_bent_results } else { &occlusion_results };
- rows.par_iter_mut().zip(&per_row).zip(&starts).for_each(|((row, samples), &first)| {
- let mut sample = [[0.0f32; 3]; BakedMap::ALL.len()];
- let mut j = 0;
- for x in 0..w {
- let mut acc = [[0.0f32; 3]; BakedMap::ALL.len()];
- let mut n = 0u32;
- while let Some(p) = samples.get(j).filter(|p| p.x == x) {
- let k = first + j;
- let traced = maps::Traced {
- ao: ao.get(k).map_or(1.0, |v| v[0]),
- bent: bent.get(k).map(|v| Vec3::new(v[1], v[2], v[3])),
- thickness: thickness.get(k).map_or(1.0, |v| v[0]),
+ rows.par_iter_mut().zip(&samples_by_row).zip(&row_offsets).for_each(|((row, samples), &first)| {
+ let mut sample_values = [[0.0f32; 3]; BakedMap::ALL.len()];
+ let mut row_sample_index = 0;
+ for x in 0..width {
+ let mut accumulated = [[0.0f32; 3]; BakedMap::ALL.len()];
+ let mut sample_count = 0u32;
+ while let Some(sample) = samples.get(row_sample_index).filter(|sample| sample.x == x) {
+ let sample_index = first + row_sample_index;
+ let traced = map::Traced {
+ ao: occlusion_results.get(sample_index).map_or(1.0, |value| value[0]),
+ bent: bent_results.get(sample_index).map(|value| Vec3::new(value[1], value[2], value[3])),
+ thickness: thickness.get(sample_index).map_or(1.0, |value| value[0]),
+ curvature: curvature.get(sample_index).copied().unwrap_or(0.5),
};
- ctx.evaluate(maps, &p.surf, p.bary, transfer(k), &traced, &mut sample);
- for (a, v) in acc.iter_mut().zip(&sample) {
- a.iter_mut().zip(v).for_each(|(a, v)| *a += v);
+ context.evaluate(maps, &sample.surface, sample.bary, transfer(sample_index), &traced, &mut sample_values);
+ for (sum, value) in accumulated.iter_mut().zip(&sample_values) {
+ sum.iter_mut().zip(value).for_each(|(sum, value)| *sum += value);
}
- n += 1;
- j += 1;
+ sample_count += 1;
+ row_sample_index += 1;
}
- for ((m, dst), a) in maps.iter().zip(row.iter_mut()).zip(&acc) {
- let comps = m.components();
- let mean = a.map(|a| a / n.max(1) as f32);
- let v = if n == 0 || mean.iter().any(|v| !v.is_finite()) { m.neutral() } else { mean };
- if let Some(d) = dst.get_mut(x * comps..(x + 1) * comps) {
- d.iter_mut().zip(v).for_each(|(d, v)| *d = v);
+
+ for ((map, destination), sum) in maps.iter().zip(row.iter_mut()).zip(&accumulated) {
+ let component_count = map.components();
+ let mean = sum.map(|sum| sum / sample_count.max(1) as f32);
+ let value = if sample_count == 0 || mean.iter().any(|value| !value.is_finite()) { map.neutral() } else { mean };
+ if let Some(pixel) = destination.get_mut(x * component_count..(x + 1) * component_count) {
+ pixel.iter_mut().zip(value).for_each(|(component, value)| *component = value);
}
}
}
diff --git a/crates/bake/src/map.rs b/crates/bake/src/map.rs
new file mode 100644
index 00000000..08a98224
--- /dev/null
+++ b/crates/bake/src/map.rs
@@ -0,0 +1,29 @@
+mod bake_context;
+mod curvature;
+mod curvature_tuning;
+mod diffusion;
+mod normal_curvature;
+mod normalization;
+mod part_key;
+pub(crate) use diffusion::diffuse;
+pub(crate) use normalization::normalize;
+pub(crate) use part_key::part_key;
+mod sample;
+mod seam;
+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;
diff --git a/crates/bake/src/map/bake_context.rs b/crates/bake/src/map/bake_context.rs
new file mode 100644
index 00000000..f3e35df6
--- /dev/null
+++ b/crates/bake/src/map/bake_context.rs
@@ -0,0 +1,255 @@
+use super::curvature::Curvature;
+use super::sampling::{pack, splitmix64, tangent_normal};
+use super::{position_projection::PositionProjection, source::Source, traced::Traced, transfer::Transfer};
+use crate::cage::{RayFrame, RayStart};
+use crate::tracing::{ANY, Hemisphere, Query, Ray, RayKind, RayScene, TraceMesh};
+use crate::{BakeError, BakeRequest, MeshExtent};
+use rayon::prelude::*;
+use texturecraft_core::{
+ AmbientOcclusionAttenuation, BackfaceMode, BakeSettings, BakedMap, CurvatureMethod, MeshMatchMode, RayDistribution, RaySettings, SelfOcclusion,
+};
+use texturecraft_geom::{Hit, Surface, surface_at};
+
+const CURVATURE_CHUNK: usize = 1 << 15;
+
+pub(crate) struct BakeContext<'a> {
+ low: Source<'a>,
+ high: Option>,
+ ray_frame: RayFrame<'a>,
+ settings: &'a BakeSettings,
+ frontal: f32,
+ rear: f32,
+ position: PositionProjection,
+ curvature_method: CurvatureMethod,
+ curvature: Curvature,
+ pub ao: Option,
+ pub bent: Option,
+ pub thickness: Option,
+}
+
+impl<'a> BakeContext<'a> {
+ pub(crate) fn new(request: &BakeRequest<'a>) -> Result, BakeError> {
+ let settings = request.settings;
+ let extent = MeshExtent::of(request.mesh)?;
+ let (low, high) = Source::of_request(request);
+ let ray_frame = RayFrame::new(request, extent)?;
+ let (mesh_scale, ray_epsilon) = (extent.scale, extent.ray_epsilon());
+ let pass = |map: BakedMap, ray_settings: &RaySettings, kind: RayKind| {
+ let half_angle_radians = (ray_settings.spread.clamp(0.0, 180.0) * 0.5).to_radians();
+ let units = if ray_settings.relative_to_bounding_box { mesh_scale } else { 1.0 };
+ settings.maps.is_enabled(map).then_some(Hemisphere {
+ kind,
+ rays: ray_settings.rays,
+ dmax: ray_settings.max_distance * units,
+ min_distance: ray_settings.min_distance * units,
+ attenuation: AmbientOcclusionAttenuation::None,
+ ground_height: None,
+ eps: ray_epsilon,
+ cos_max: half_angle_radians.cos(),
+ sin_max: half_angle_radians.sin(),
+ uniform: ray_settings.distribution == RayDistribution::Uniform,
+ ignore_backface: BackfaceMode::Never,
+ same_key: false,
+ })
+ };
+
+ let mut ao = pass(BakedMap::AmbientOcclusion, &settings.maps.ao.parameters.rays, RayKind::Occlusion);
+ if let Some(pass) = &mut ao {
+ let parameters = settings.maps.ao.parameters;
+ 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(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 = ray_frame.cage_units;
+ Ok(BakeContext {
+ low,
+ high,
+ ray_frame,
+ settings,
+ 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),
+ curvature_method: settings.maps.curvature.parameters.method,
+ curvature: Curvature::new(settings, request.mesh, mesh_scale, request.tiles),
+ ao,
+ bent,
+ thickness,
+ })
+ }
+
+ pub(crate) fn ignore_transfer_backface(&self) -> bool {
+ self.settings.high_poly.ignore_backface
+ }
+
+ pub(crate) fn has_high(&self) -> bool {
+ self.high.is_some()
+ }
+
+ pub(crate) fn casts_rays(&self) -> bool {
+ self.has_high() || self.curvature.is_enabled || self.ao.is_some() || self.bent.is_some() || self.thickness.is_some()
+ }
+
+ pub(crate) fn trace_meshes(&self) -> Vec> {
+ std::iter::once(&self.low).chain(&self.high).map(Source::trace).collect()
+ }
+
+ pub(crate) fn transfer_ray(&self, surface: &Surface, barycentric: [f32; 2]) -> (Ray, f32) {
+ let start = self.ray_frame.start(surface, barycentric);
+ let origin = start.origin(surface.pos, self.frontal);
+ let (direction, front) = match start {
+ RayStart::CageMesh(offset) => (offset.normalize(), offset.length()),
+ RayStart::Distance { up, scale } => (-up, self.frontal * scale),
+ };
+ let key = match self.settings.high_poly.match_mode {
+ MeshMatchMode::Always => ANY,
+ MeshMatchMode::ByMeshName => self.low.key.get(surface.tri as usize).copied().unwrap_or(ANY),
+ };
+ (Ray { origin, direction, max_distance: front + self.rear, key }, front)
+ }
+
+ pub(crate) fn transfer(&self, hit: Option, front: f32) -> Option {
+ let (high, hit) = (self.high.as_ref()?, hit?);
+ let surface = surface_at(high.mesh, hit.tri, hit.u, hit.v)?;
+ Some(Transfer { surface, bary: [hit.u, hit.v], t: hit.t, front })
+ }
+
+ pub(crate) fn query(&self, transfer: Option<&Transfer>, low_surface: &Surface, seed: u64) -> Query {
+ let (source, surface, mesh) = match (&self.high, transfer) {
+ (Some(high), Some(transfer_hit)) => (high, &transfer_hit.surface, 1),
+ _ => (&self.low, low_surface, 0),
+ };
+ let seed_hash = splitmix64(seed);
+ let rot = [(seed_hash >> 40) as f32 / (1u64 << 24) as f32, ((seed_hash >> 16) & 0xff_ffff) as f32 / (1u64 << 24) as f32];
+ let geo = if surface.geo_nrm.dot(surface.nrm) < 0.0 { -surface.geo_nrm } else { surface.geo_nrm };
+ Query { pos: surface.pos, nrm: surface.nrm, geo, rot, key: source.key.get(surface.tri as usize).copied().unwrap_or(ANY), mesh }
+ }
+
+ pub(crate) fn traces_curvature(&self) -> bool {
+ self.curvature.is_enabled
+ }
+
+ pub(crate) fn trace_curvature(&self, scene: &mut dyn RayScene, samples: &[(&Surface, Option<&Transfer>)]) -> Result, BakeError> {
+ let mut output = vec![0.5; samples.len()];
+ let curvature = &self.curvature;
+ for mesh in [0usize, 1] {
+ let Some(source) = (if mesh == 0 { Some(&self.low) } else { self.high.as_ref() }) else { continue };
+ let tuning = if mesh == 0 { &curvature.low } else { &curvature.high };
+ let chosen: Vec<(usize, &Surface, f32)> = samples
+ .par_iter()
+ .enumerate()
+ .filter_map(|(sample_index, (low_surface, transfer_hit))| {
+ let surface = match (mesh, transfer_hit) {
+ (1, Some(hit)) => &hit.surface,
+ (0, None) => *low_surface,
+ _ => return None,
+ };
+ Some((sample_index, surface, curvature.texel(low_surface.tri)))
+ })
+ .collect();
+ let rays_per_sample = curvature.rays_per_sample.max(1);
+ let key_for = |surface: &Surface| {
+ if self.settings.maps.curvature.parameters.mesh.self_intersection == SelfOcclusion::SameMeshName {
+ source.key.get(surface.tri as usize).copied().unwrap_or(ANY)
+ } else {
+ ANY
+ }
+ };
+ let chunk_size = CURVATURE_CHUNK.min((1_048_576 / rays_per_sample).max(1));
+ for chunk in chosen.chunks(chunk_size) {
+ let mut rays: Vec = bytemuck::zeroed_vec(chunk.len() * rays_per_sample);
+ rays.par_chunks_mut(rays_per_sample)
+ .zip(chunk)
+ .for_each(|(output, (_, surface, texel))| curvature.rays(tuning, surface, *texel, key_for(surface), output));
+ let hits = scene.closest(mesh, &rays, false)?;
+ let walls =
+ |chunk_index: usize| hits.get(chunk_index * rays_per_sample..chunk_index * rays_per_sample + curvature.wall_count).unwrap_or_default();
+ let grounds: Vec = chunk
+ .par_iter()
+ .enumerate()
+ .flat_map_iter(|(chunk_index, (_, surface, texel))| {
+ let mut value = Vec::new();
+ curvature.ground_rays(surface, *texel, key_for(surface), walls(chunk_index), &mut value);
+ value
+ })
+ .collect();
+ let ground_hits = scene.closest(mesh, &grounds, false)?;
+ let ground_offsets: Vec = (0..chunk.len())
+ .scan(0, |first, chunk_index| {
+ let offset = *first;
+ *first += walls(chunk_index).iter().flatten().count();
+ Some(offset)
+ })
+ .collect();
+ let values: Vec<(usize, f32)> = chunk
+ .par_iter()
+ .zip(&ground_offsets)
+ .enumerate()
+ .map(|(chunk_index, ((sample_index, surface, texel), first))| {
+ let ground_count = walls(chunk_index).iter().flatten().count();
+ let sample_ground_hits = ground_hits.get(*first..*first + ground_count).unwrap_or_default();
+ let sample_hits = hits.get(chunk_index * rays_per_sample..(chunk_index + 1) * rays_per_sample).unwrap_or_default();
+ (*sample_index, curvature.value(tuning, source, surface, *texel, sample_hits, sample_ground_hits))
+ })
+ .collect();
+ for (sample_index, value) in values {
+ if let Some(destination) = output.get_mut(sample_index) {
+ *destination = value;
+ }
+ }
+ }
+ }
+ Ok(output)
+ }
+
+ pub(crate) fn evaluate(
+ &self,
+ maps: &[BakedMap],
+ low_surface: &Surface,
+ barycentric: [f32; 2],
+ transfer: Option<&Transfer>,
+ traced: &Traced,
+ outputs: &mut [[f32; 3]],
+ ) {
+ let (source, surface, source_barycentric) = match (&self.high, transfer) {
+ (Some(high), Some(hit)) => (high, &hit.surface, hit.bary),
+ _ => (&self.low, low_surface, barycentric),
+ };
+
+ let missed = self.high.is_some() && transfer.is_none();
+ for (&map, output) in maps.iter().zip(outputs.iter_mut()) {
+ *output = match map {
+ BakedMap::AmbientOcclusion => [traced.ao; 3],
+ BakedMap::BentNormal => pack(traced.bent.unwrap_or(surface.nrm)),
+ BakedMap::Thickness => [traced.thickness; 3],
+ BakedMap::Curvature if self.curvature_method == CurvatureMethod::NormalMap => [0.5; 3],
+ BakedMap::Curvature => [traced.curvature; 3],
+ BakedMap::WorldNormal => pack(surface.nrm),
+ BakedMap::Position => self.position.evaluate(surface.pos),
+ BakedMap::Id => source.id_color(surface, source_barycentric, self.settings.maps.id.parameters),
+ BakedMap::Normal => transfer.map_or(map.neutral(), |hit| tangent_normal(low_surface, hit.surface.nrm)),
+ BakedMap::Height => {
+ let relative_to_rays = self.settings.maps.height.parameters.normalization == texturecraft_core::HeightNormalization::RelativeToRayDistances;
+ [transfer.map_or(if relative_to_rays { 0.5 } else { 0.0 }, |hit| {
+ let height = hit.front - hit.t;
+ if relative_to_rays { (0.5 + height / (hit.front + self.rear).max(1e-20)).clamp(0.0, 1.0) } else { height }
+ }); 3]
+ }
+ BakedMap::Opacity if missed => [0.0; 3],
+ BakedMap::Opacity => [source.color(surface, source_barycentric).w; 3],
+ };
+ }
+ }
+}
diff --git a/crates/bake/src/map/curvature.rs b/crates/bake/src/map/curvature.rs
new file mode 100644
index 00000000..eac8dd52
--- /dev/null
+++ b/crates/bake/src/map/curvature.rs
@@ -0,0 +1,217 @@
+use super::{curvature_tuning::CurvatureTuning, sampling::interpolate, source::Source};
+use crate::tracing::Ray;
+use rayon::prelude::*;
+use texturecraft_core::{BakeSettings, BakedMap, CurvatureMethod};
+use texturecraft_geom::glam::Vec3;
+use texturecraft_geom::{Hit, Mesh, Surface};
+
+const RING_COUNT: usize = 4;
+const WALL_RADIUS_TEXELS: f32 = 1.5;
+const CONCAVE_WEIGHT: f32 = 1.5;
+const LOW_POLY_CONVEX_WEIGHT: f32 = 1.5;
+const HIGH_POLY_CONVEX_WEIGHT: f32 = 0.5;
+const LOW_POLY_CURVATURE_RADIUS_RATIO: f32 = 0.003;
+const LOW_POLY_CURVATURE_WEIGHT: f32 = 1.3;
+const HIGH_POLY_CURVATURE_RADIUS_RATIO: f32 = 0.0007;
+const HIGH_POLY_CURVATURE_WEIGHT: f32 = 1.6;
+const HARD_EDGE_NORMAL_CHANGE_THRESHOLD: f32 = 0.05;
+const GENTLE_CURVATURE_THRESHOLD: f32 = 0.1;
+
+pub(super) struct Curvature {
+ pub(super) is_enabled: bool,
+ walls: f32,
+ spread: f32,
+ fallback: f32,
+ texels: Vec,
+ ring: [Vec<(f32, f32)>; RING_COUNT],
+ pub(super) rays_per_sample: usize,
+ pub(super) wall_count: usize,
+ pub(super) low: CurvatureTuning,
+ pub(super) high: CurvatureTuning,
+}
+
+impl Curvature {
+ pub(super) fn new(settings: &BakeSettings, low: &Mesh, mesh_scale: f32, tiles: (u32, u32)) -> Curvature {
+ let is_enabled = settings.maps.is_enabled(BakedMap::Curvature) && settings.maps.curvature.parameters.method == CurvatureMethod::Mesh;
+ let (width, height) = settings.common.output_size();
+ let resolution = (width as f32 * height as f32 * tiles.0.max(1) as f32 * tiles.1.max(1) as f32).sqrt();
+ let texel = |triangle: usize| {
+ let [a, b, c] = low.tri(triangle)?;
+ let (position_a, position_b, position_c) = (*low.positions.get(a)?, *low.positions.get(b)?, *low.positions.get(c)?);
+ let (uv_a, uv_b, uv_c) = (*low.uvs.get(a)?, *low.uvs.get(b)?, *low.uvs.get(c)?);
+ let world_area = (position_b - position_a).cross(position_c - position_a).length();
+ let uv_area = (uv_b - uv_a).perp_dot(uv_c - uv_a).abs();
+ (uv_area > 1e-12 && world_area > 0.0).then(|| (world_area / uv_area).sqrt() / resolution)
+ };
+ let fallback = mesh_scale * 1e-3;
+ let triangle_count = if is_enabled { low.triangle_count() } else { 0 };
+ let parameters = settings.maps.curvature.parameters.mesh;
+ let radius = parameters.sampling_radius * if parameters.relative_to_bounding_box { mesh_scale } else { 1.0 };
+ let radius_scale = radius / (mesh_scale * 0.001);
+ let walls = WALL_RADIUS_TEXELS * radius_scale;
+ let rays_per_sample = parameters.rays as usize;
+ let ring: [Vec<(f32, f32)>; RING_COUNT] = std::array::from_fn(|ring_index| {
+ let count = rays_per_sample / RING_COUNT + usize::from(ring_index < rays_per_sample % RING_COUNT);
+ (0..count)
+ .map(|index| {
+ let angle = std::f32::consts::TAU * index as f32 / count.max(1) as f32;
+ (angle.cos(), angle.sin())
+ })
+ .collect()
+ });
+ Curvature {
+ is_enabled,
+ rays_per_sample,
+ wall_count: ring.first().map_or(0, Vec::len),
+ walls,
+ spread: walls * 4.0 / 3.0,
+ fallback,
+ texels: (0..triangle_count).into_par_iter().map(|t| texel(t).filter(|v| v.is_finite()).unwrap_or(fallback)).collect(),
+ low: CurvatureTuning {
+ convex: LOW_POLY_CONVEX_WEIGHT,
+ true_radius: mesh_scale * LOW_POLY_CURVATURE_RADIUS_RATIO * radius_scale,
+ true_strength: LOW_POLY_CURVATURE_WEIGHT,
+ },
+ high: CurvatureTuning {
+ convex: HIGH_POLY_CONVEX_WEIGHT,
+ true_radius: mesh_scale * HIGH_POLY_CURVATURE_RADIUS_RATIO * radius_scale,
+ true_strength: HIGH_POLY_CURVATURE_WEIGHT,
+ },
+ ring,
+ }
+ }
+
+ pub(super) fn texel(&self, tri: u32) -> f32 {
+ self.texels.get(tri as usize).copied().unwrap_or(self.fallback)
+ }
+
+ fn radii(&self, tuning: &CurvatureTuning, texel: f32) -> [f32; RING_COUNT] {
+ let r = self.walls * texel;
+ [r, r, self.spread * texel, tuning.true_radius]
+ }
+
+ fn directions(&self, ring: usize, tangent: Vec3, bitangent: Vec3) -> impl Iterator- + '_ {
+ self.ring.get(ring).into_iter().flatten().map(move |(cosine, sine)| tangent * *cosine + bitangent * *sine)
+ }
+
+ pub(super) fn rays(&self, tuning: &CurvatureTuning, surface: &Surface, texel_size: f32, key: u32, output: &mut [Ray]) {
+ let (geometric_normal, tangent, bitangent) = surface_frame(surface);
+ let mut output = output.iter_mut();
+ for (ring, radius) in self.radii(tuning, texel_size).into_iter().enumerate() {
+ for direction in self.directions(ring, tangent, bitangent) {
+ let Some(ray) = output.next() else {
+ return;
+ };
+ *ray = match ring {
+ 0 => Ray { origin: surface.pos + geometric_normal * (0.15 * radius), direction, max_distance: radius, key },
+ 1 => Ray { origin: surface.pos - geometric_normal * (0.15 * radius), direction, max_distance: radius, key },
+ _ => Ray {
+ origin: surface.pos + direction * radius + geometric_normal * (0.25 * radius),
+ direction: -geometric_normal,
+ max_distance: 2.25 * radius,
+ key,
+ },
+ };
+ }
+ }
+ }
+
+ pub(super) fn ground_rays(&self, surface: &Surface, texel_size: f32, key: u32, walls: &[Option
], output: &mut Vec) {
+ let (geometric_normal, tangent, bitangent) = surface_frame(surface);
+ let radius = self.walls * texel_size;
+ for (w, direction) in walls.iter().zip(self.directions(0, tangent, bitangent)) {
+ if let Some(hit) = w {
+ output.push(Ray {
+ origin: surface.pos + geometric_normal * (0.15 * radius) + direction * (hit.t * 0.85),
+ direction: -geometric_normal,
+ max_distance: 0.5 * radius,
+ key,
+ });
+ }
+ }
+ }
+
+ fn wall(&self, source: &Source, surface: &Surface, geometric_normal: Vec3, radius: f32, hits: &[Option], keep: &mut dyn FnMut() -> bool) -> f32 {
+ let mut sum = 0.0;
+ for hit in hits.iter().flatten() {
+ if !keep() {
+ continue;
+ }
+ let upright = triangle_normal(source.mesh, hit.tri).map_or(1.0, |normal| (1.0 - normal.dot(geometric_normal).powi(2)).max(0.0).sqrt());
+ let shaded = interpolate(source.mesh, &source.mesh.normals, hit.tri, [hit.u, hit.v]).and_then(Vec3::try_normalize).unwrap_or(surface.nrm);
+ let hard = ((1.0 - shaded.dot(surface.nrm)) / HARD_EDGE_NORMAL_CHANGE_THRESHOLD).clamp(0.0, 1.0);
+ sum += (1.0 - hit.t / radius) * upright * hard;
+ }
+ sum / hits.len().max(1) as f32
+ }
+
+ fn spread(
+ &self,
+ source: &Source,
+ surface: &Surface,
+ geometric_normal: Vec3,
+ directions: impl Iterator- ,
+ hits: &[Option
],
+ turn: f32,
+ ) -> (f32, f32) {
+ let (mut shading, mut faces) = (0.0, 0.0);
+ for (hit, direction) in hits.iter().zip(directions) {
+ let Some(hit) = hit else { continue };
+ let normal = interpolate(source.mesh, &source.mesh.normals, hit.tri, [hit.u, hit.v]).and_then(Vec3::try_normalize).unwrap_or(surface.nrm);
+ if 1.0 - normal.dot(surface.nrm) <= turn {
+ shading += (normal - surface.nrm).dot(direction);
+ if let Some(f) = triangle_normal(source.mesh, hit.tri) {
+ let f = if f.dot(geometric_normal) < 0.0 { -f } else { f };
+ faces += (f - geometric_normal).dot(direction);
+ }
+ }
+ }
+ (shading / hits.len().max(1) as f32, faces / hits.len().max(1) as f32)
+ }
+
+ pub(super) fn value(
+ &self,
+ tuning: &CurvatureTuning,
+ source: &Source,
+ surface: &Surface,
+ texel_size: f32,
+ hits: &[Option],
+ ground_hits: &[Option],
+ ) -> f32 {
+ let (geometric_normal, tangent, bitangent) = surface_frame(surface);
+ let ring = |ring_index: usize| {
+ let start: usize = self.ring.iter().take(ring_index).map(Vec::len).sum();
+ let count = self.ring.get(ring_index).map_or(0, Vec::len);
+ hits.get(start..start + count).unwrap_or_default()
+ };
+ let radius = self.walls * texel_size;
+ let mut next = ground_hits.iter();
+ let above = self.wall(source, surface, geometric_normal, radius, ring(0), &mut || next.next().copied().flatten().is_some_and(|g| g.t < 0.3 * radius));
+ let below = self.wall(source, surface, geometric_normal, radius, ring(1), &mut || true);
+ let (shading, _) = self.spread(source, surface, geometric_normal, self.directions(2, tangent, bitangent), ring(2), 2.0);
+ let (true_shading, true_faces) = self.spread(source, surface, geometric_normal, self.directions(3, tangent, bitangent), ring(3), 2.0);
+ let value =
+ -above * CONCAVE_WEIGHT + (below - above).max(0.0) * tuning.convex + shading * 0.5 + tight(agreed(true_shading, true_faces) * tuning.true_strength);
+ (value * 2.0).clamp(-1.0, 1.0)
+ }
+}
+
+fn triangle_normal(mesh: &Mesh, tri: u32) -> Option {
+ let [a, b, c] = mesh.tri(tri as usize)?;
+ let p = |i: usize| mesh.positions.get(i).copied();
+ (p(b)? - p(a)?).cross(p(c)? - p(a)?).try_normalize()
+}
+
+fn surface_frame(surface: &Surface) -> (Vec3, Vec3, Vec3) {
+ let geometric_normal = if surface.geo_nrm.dot(surface.nrm) < 0.0 { -surface.geo_nrm } else { surface.geo_nrm };
+ let (tangent, bitangent) = geometric_normal.any_orthonormal_pair();
+ (geometric_normal, tangent, bitangent)
+}
+
+fn tight(v: f32) -> f32 {
+ v.signum() * (v.abs() - GENTLE_CURVATURE_THRESHOLD).max(0.0)
+}
+
+fn agreed(shading: f32, faces: f32) -> f32 {
+ if shading * faces <= 0.0 { 0.0 } else { shading.abs().min(faces.abs()).copysign(shading) }
+}
diff --git a/crates/bake/src/map/curvature_tuning.rs b/crates/bake/src/map/curvature_tuning.rs
new file mode 100644
index 00000000..753edfb6
--- /dev/null
+++ b/crates/bake/src/map/curvature_tuning.rs
@@ -0,0 +1,5 @@
+pub(super) struct CurvatureTuning {
+ pub(super) convex: f32,
+ pub(super) true_radius: f32,
+ pub(super) true_strength: f32,
+}
diff --git a/crates/bake/src/map/diffusion.rs b/crates/bake/src/map/diffusion.rs
new file mode 100644
index 00000000..eb59801f
--- /dev/null
+++ b/crates/bake/src/map/diffusion.rs
@@ -0,0 +1,89 @@
+use texturecraft_texel::DilationMap;
+
+pub(crate) fn diffuse(pixels: &mut [f32], components: usize, padding: &DilationMap, tile_size: (usize, usize)) {
+ let width = padding.width as usize;
+ let height = padding.height as usize;
+ for start_y in (0..height).step_by(tile_size.1) {
+ for start_x in (0..width).step_by(tile_size.0) {
+ let tile_width = tile_size.0.min(width - start_x);
+ let tile_height = tile_size.1.min(height - start_y);
+ let mut values = vec![0.0; tile_width * tile_height * components];
+ let mut valid = vec![false; tile_width * tile_height];
+ for (index, covered) in valid.iter_mut().enumerate() {
+ let source = (start_y + index / tile_width) * width + start_x + index % tile_width;
+ *covered = padding.src.get(source).is_some_and(|source| *source != u32::MAX);
+ if let (Some(destination), Some(pixel)) =
+ (values.get_mut(index * components..(index + 1) * components), pixels.get(source * components..(source + 1) * components))
+ {
+ destination.copy_from_slice(pixel);
+ }
+ }
+ if !valid.iter().any(|covered| *covered) {
+ continue;
+ }
+ fill(&mut values, &valid, tile_width, tile_height, components);
+ for (index, covered) in valid.iter().enumerate() {
+ if *covered {
+ continue;
+ }
+ let destination = (start_y + index / tile_width) * width + start_x + index % tile_width;
+ if let (Some(pixel), Some(value)) =
+ (pixels.get_mut(destination * components..(destination + 1) * components), values.get(index * components..(index + 1) * components))
+ {
+ pixel.copy_from_slice(value);
+ }
+ }
+ }
+ }
+}
+
+fn fill(values: &mut [f32], valid: &[bool], width: usize, height: usize, components: usize) {
+ if width == 1 && height == 1 {
+ return;
+ }
+ let (small_width, small_height) = (width.div_ceil(2), height.div_ceil(2));
+ let mut small = vec![0.0; small_width * small_height * components];
+ let mut small_valid = vec![false; small_width * small_height];
+ for (index, covered) in small_valid.iter_mut().enumerate() {
+ let (x, y) = (index % small_width * 2, index / small_width * 2);
+ let mut count = 0;
+ for child_y in y..(y + 2).min(height) {
+ for child_x in x..(x + 2).min(width) {
+ let child = child_y * width + child_x;
+ if valid.get(child) != Some(&true) {
+ continue;
+ }
+ count += 1;
+ for component in 0..components {
+ if let Some(value) = small.get_mut(index * components + component) {
+ *value += values.get(child * components + component).copied().unwrap_or(0.0);
+ }
+ }
+ }
+ }
+ *covered = count > 0;
+ if let Some(pixel) = small.get_mut(index * components..(index + 1) * components) {
+ pixel.iter_mut().for_each(|value| *value /= count.max(1) as f32);
+ }
+ }
+ fill(&mut small, &small_valid, small_width, small_height, components);
+ for (index, covered) in valid.iter().enumerate() {
+ if *covered {
+ continue;
+ }
+ let (x, y) = ((index % width) as f32 * 0.5 - 0.25, (index / width) as f32 * 0.5 - 0.25);
+ let (fraction_x, fraction_y) = (x - x.floor(), y - y.floor());
+ let sample = |offset_x: i32, offset_y: i32, component: usize| {
+ let sample_x = (x.floor() as i32 + offset_x).clamp(0, small_width as i32 - 1) as usize;
+ let sample_y = (y.floor() as i32 + offset_y).clamp(0, small_height as i32 - 1) as usize;
+ small.get((sample_y * small_width + sample_x) * components + component).copied().unwrap_or(0.0)
+ };
+ for component in 0..components {
+ let top = sample(0, 0, component) * (1.0 - fraction_x) + sample(1, 0, component) * fraction_x;
+ let bottom = sample(0, 1, component) * (1.0 - fraction_x) + sample(1, 1, component) * fraction_x;
+ if let Some(value) = values.get_mut(index * components + component) {
+ *value = top * (1.0 - fraction_y) + bottom * fraction_y;
+ }
+ }
+ }
+}
diff --git a/crates/bake/src/map/normal_curvature.rs b/crates/bake/src/map/normal_curvature.rs
new file mode 100644
index 00000000..c96163c7
--- /dev/null
+++ b/crates/bake/src/map/normal_curvature.rs
@@ -0,0 +1,120 @@
+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(
+ world_normal: &[f32],
+ mesh: &Mesh,
+ material: usize,
+ grid: &TexelGrid,
+ settings: NormalMapCurvatureSettings,
+ output: &mut [f32],
+) {
+ 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
+ };
+
+ // Turn of the normal per texel, measured along the surface direction each texel axis points to
+ let turn_along = |axis: usize| -> Vec {
+ (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() {
+ let index = y * size.0 + x;
+ if covered.get(index) != Some(&true) {
+ continue;
+ }
+
+ // 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 {
+ 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()
+}
diff --git a/crates/bake/src/map/normalization.rs b/crates/bake/src/map/normalization.rs
new file mode 100644
index 00000000..b1de9812
--- /dev/null
+++ b/crates/bake/src/map/normalization.rs
@@ -0,0 +1,91 @@
+use rayon::prelude::*;
+use std::collections::BTreeMap;
+use texturecraft_core::{BakeSettings, BakedMap, CurvatureMethod, HeightNormalization, ThicknessNormalization};
+
+pub(crate) fn normalize(
+ maps: &mut BTreeMap>,
+ covered: &[bool],
+ width: usize,
+ tile_size: (usize, usize),
+ settings: &BakeSettings,
+ mesh_scale: f32,
+) {
+ for (map, pixels) in maps {
+ if !matches!(map, BakedMap::Curvature | BakedMap::Height | BakedMap::Thickness) {
+ continue;
+ }
+ if *map == BakedMap::Height && settings.maps.height.parameters.normalization == HeightNormalization::RelativeToRayDistances {
+ continue;
+ }
+ if *map == BakedMap::Curvature && settings.maps.curvature.parameters.method != CurvatureMethod::Mesh {
+ continue;
+ }
+ pixels.par_chunks_mut(width * tile_size.1).enumerate().for_each(|(tile_row, rows)| {
+ let coverage = covered.get(tile_row * width * tile_size.1..).unwrap_or_default();
+ for start_x in (0..width).step_by(tile_size.0) {
+ let end_x = (start_x + tile_size.0).min(width);
+ let mut minimum = f32::INFINITY;
+ let mut maximum = f32::NEG_INFINITY;
+ for (row_index, row) in rows.chunks(width).enumerate() {
+ for (x, value) in row.iter().enumerate().take(end_x).skip(start_x) {
+ if coverage.get(row_index * width + x) == Some(&true) && value.is_finite() {
+ minimum = minimum.min(*value);
+ maximum = maximum.max(*value);
+ }
+ }
+ }
+ if !minimum.is_finite() {
+ continue;
+ }
+ let (lower, upper, flat, raw) = match map {
+ BakedMap::Thickness => {
+ let parameters = settings.maps.thickness.parameters;
+ match parameters.normalization {
+ ThicknessNormalization::RelativeToMinMax => (minimum, maximum, 1.0, false),
+ ThicknessNormalization::RelativeToRayDistances => {
+ let units = if parameters.rays.relative_to_bounding_box { mesh_scale } else { 1.0 };
+ (parameters.rays.min_distance * units, parameters.rays.max_distance * units, 1.0, false)
+ }
+ ThicknessNormalization::None => (0.0, 1.0, 1.0, true),
+ }
+ }
+ BakedMap::Height => match settings.maps.height.parameters.normalization {
+ HeightNormalization::RelativeToRayDistances => {
+ let units = if settings.cage.relative_to_bounding_box { mesh_scale } else { 1.0 };
+ (-settings.cage.max_rear * units, settings.cage.max_frontal * units, 0.5, false)
+ }
+ HeightNormalization::RelativeToMinMax => (minimum, maximum, 0.5, false),
+ HeightNormalization::RelativeToLowMesh => {
+ let magnitude = minimum.abs().max(maximum.abs());
+ (-magnitude, magnitude, 0.5, false)
+ }
+ HeightNormalization::Manual => {
+ let half_range = settings.maps.height.parameters.scaling_divisor * 0.5;
+ (-half_range, half_range, 0.5, false)
+ }
+ },
+ _ => {
+ let parameters = settings.maps.curvature.parameters.mesh;
+ if parameters.auto_tonemapping {
+ let magnitude = minimum.abs().max(maximum.abs());
+ (-magnitude, magnitude, 0.5, false)
+ } else {
+ (parameters.value_min, parameters.value_max, 0.5, false)
+ }
+ }
+ };
+ if raw {
+ continue;
+ }
+ let range = upper - lower;
+ for (row_index, row) in rows.chunks_mut(width).enumerate() {
+ for (x, value) in row.iter_mut().enumerate().take(end_x).skip(start_x) {
+ if coverage.get(row_index * width + x) == Some(&true) {
+ *value = if range > f32::EPSILON { ((*value - lower) / range).clamp(0.0, 1.0) } else { flat };
+ }
+ }
+ }
+ }
+ });
+ }
+}
diff --git a/crates/bake/src/map/part_key.rs b/crates/bake/src/map/part_key.rs
new file mode 100644
index 00000000..bda45809
--- /dev/null
+++ b/crates/bake/src/map/part_key.rs
@@ -0,0 +1,18 @@
+use std::collections::HashMap;
+
+/// A mesh part's key in `keys` (shared by names that agree once `suffix` is dropped), whether it ignores backfaces, and its lowercase name without that suffix
+pub(crate) fn part_key(name: &str, suffix: &str, backface_suffix: &str, keys: &mut HashMap) -> (u32, bool, String) {
+ let name = name.trim().to_lowercase();
+ let ignore_backface = !backface_suffix.is_empty() && name.ends_with(backface_suffix);
+ let name = if ignore_backface { name.strip_suffix(backface_suffix).unwrap_or(&name).to_owned() } else { name };
+
+ (match_key(&name, suffix, keys), ignore_backface, name)
+}
+
+/// The key in `keys` of the lowercase part name `name` without `suffix`
+fn match_key(name: &str, suffix: &str, keys: &mut HashMap) -> u32 {
+ let suffix = suffix.trim().to_lowercase();
+ let base = name.strip_suffix(suffix.as_str()).filter(|_| !suffix.is_empty()).unwrap_or(name).to_string();
+ let next = keys.len() as u32;
+ *keys.entry(base).or_insert(next)
+}
diff --git a/crates/bake/src/map/position_projection.rs b/crates/bake/src/map/position_projection.rs
new file mode 100644
index 00000000..eccff2eb
--- /dev/null
+++ b/crates/bake/src/map/position_projection.rs
@@ -0,0 +1,45 @@
+use texturecraft_core::{PositionAxis, PositionMode, PositionNormalizationScale, PositionSettings};
+use texturecraft_geom::{Mesh, glam::Vec3};
+
+pub(super) struct PositionProjection {
+ settings: PositionSettings,
+ minimum: Vec3,
+ extent: Vec3,
+ center: Vec3,
+ diameter: f32,
+}
+
+impl PositionProjection {
+ pub(super) fn new(mesh: &Mesh, material: usize, settings: PositionSettings) -> Self {
+ let initial = (Vec3::splat(f32::INFINITY), Vec3::splat(f32::NEG_INFINITY));
+ let expand = |(minimum, maximum): (Vec3, Vec3), position: &Vec3| (minimum.min(*position), maximum.max(*position));
+ let (minimum, maximum) = match settings.scale {
+ PositionNormalizationScale::FullScene => mesh.positions.iter().fold(initial, expand),
+ PositionNormalizationScale::PerMaterial => mesh
+ .triangles_of(material)
+ .filter_map(|triangle| mesh.tri(triangle))
+ .flatten()
+ .filter_map(|index| mesh.positions.get(index))
+ .fold(initial, expand),
+ };
+ let minimum = if minimum.is_finite() { minimum } else { Vec3::ZERO };
+ let maximum = if maximum.is_finite() { maximum } else { Vec3::ZERO };
+ let center = (minimum + maximum) * 0.5;
+ let extent = maximum - minimum;
+ Self { settings, minimum, extent, center, diameter: extent.max_element().max(1e-20) }
+ }
+
+ pub(super) fn evaluate(&self, position: Vec3) -> [f32; 3] {
+ let value = match self.settings.normalization {
+ PositionMode::BoundingBox => ((position - self.minimum) / self.extent.max(Vec3::splat(1e-20))).clamp(Vec3::ZERO, Vec3::ONE),
+ PositionMode::BoundingSphere => ((position - self.center) / self.diameter + 0.5).clamp(Vec3::ZERO, Vec3::ONE),
+ PositionMode::None => position,
+ };
+ match self.settings.axis {
+ PositionAxis::All => value.to_array(),
+ PositionAxis::X => [value.x; 3],
+ PositionAxis::Y => [value.y; 3],
+ PositionAxis::Z => [value.z; 3],
+ }
+ }
+}
diff --git a/crates/bake/src/map/sample.rs b/crates/bake/src/map/sample.rs
new file mode 100644
index 00000000..2ff9a10e
--- /dev/null
+++ b/crates/bake/src/map/sample.rs
@@ -0,0 +1,8 @@
+use texturecraft_geom::Surface;
+
+pub(crate) struct Sample {
+ pub x: usize,
+ pub surface: Surface,
+ pub bary: [f32; 2],
+ pub seed: u64,
+}
diff --git a/crates/bake/src/map/sampling.rs b/crates/bake/src/map/sampling.rs
new file mode 100644
index 00000000..5f2d2677
--- /dev/null
+++ b/crates/bake/src/map/sampling.rs
@@ -0,0 +1,76 @@
+use std::collections::HashMap;
+use std::ops::{Add, Mul};
+use texturecraft_geom::glam::Vec3;
+use texturecraft_geom::{Mesh, Surface};
+
+/// `values` (one per vertex) at `barycentric` in triangle `triangle`
+pub(crate) fn interpolate + Add>(mesh: &Mesh, values: &[T], triangle: u32, barycentric: [f32; 2]) -> Option {
+ 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)
+}
+
+/// 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, Vec, Vec) {
+ 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::::new());
+
+ let welded_indices: Vec = mesh
+ .positions
+ .iter()
+ .zip(&mesh.normals)
+ .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(normal_sum) = normal_sums.get_mut(welded_index as usize) {
+ *normal_sum += *normal;
+ }
+ welded_index
+ })
+ .collect();
+
+ 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 {
+ let mut z = x.wrapping_add(0x9e37_79b9_7f4a_7c15);
+ z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
+ z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
+ z ^ (z >> 31)
+}
+
+pub(super) fn pack(v: Vec3) -> [f32; 3] {
+ (v * 0.5 + 0.5).clamp(Vec3::ZERO, Vec3::ONE).to_array()
+}
+
+pub(super) fn generated_hue(part: usize) -> [f32; 3] {
+ let h = ((part as f64 * 0.618_033_988_75 + 0.05).fract() * 6.0) as f32;
+ let (s, v) = (0.7f32, 0.95f32);
+ let f = h.fract();
+ let (p, q, t) = (v * (1.0 - s), v * (1.0 - s * f), v * (1.0 - s * (1.0 - f)));
+ match h as u32 {
+ 0 => [v, t, p],
+ 1 => [q, v, p],
+ 2 => [p, v, t],
+ 3 => [p, q, v],
+ 4 => [t, p, v],
+ _ => [v, p, q],
+ }
+}
+
+pub(super) fn tangent_normal(s: &Surface, n: Vec3) -> [f32; 3] {
+ let z = s.nrm;
+ let t = (s.tangent.truncate() - z * z.dot(s.tangent.truncate())).try_normalize().unwrap_or_else(|| z.any_orthonormal_vector());
+ let b = z.cross(t) * s.tangent.w;
+ pack(Vec3::new(t.dot(n), b.dot(n), z.dot(n)))
+}
diff --git a/crates/bake/src/map/seam.rs b/crates/bake/src/map/seam.rs
new file mode 100644
index 00000000..4065fd52
--- /dev/null
+++ b/crates/bake/src/map/seam.rs
@@ -0,0 +1,64 @@
+use std::collections::HashMap;
+use texturecraft_geom::{Mesh, glam::Vec2};
+
+pub(crate) fn fix_seams(mesh: &Mesh, material: usize, covered: &[bool], size: (usize, usize), intensity: f32, pixels: &mut [f32]) {
+ if intensity <= 0.0 {
+ return;
+ }
+ let (minimum, maximum) = mesh.bounds();
+ let tolerance = (maximum - minimum).length().max(1e-6) * 1e-6;
+ let position_key = |index: usize| mesh.positions.get(index).map(|position| position.to_array().map(|value| (value / tolerance).round() as i64));
+ let mut edges = HashMap::new();
+ let source = pixels.to_vec();
+ let texel_scale = Vec2::new(size.0 as f32, size.1 as f32);
+ let texel = |point: Vec2| {
+ if point.x < 0.0 || point.y < 0.0 || point.x >= size.0 as f32 || point.y >= size.1 as f32 {
+ return None;
+ }
+ let index = point.y.floor() as usize * size.0 + point.x.floor() as usize;
+ (covered.get(index) == Some(&true)).then_some(index)
+ };
+ for triangle in mesh.triangles_of(material) {
+ let Some(corners) = mesh.tri(triangle) else {
+ continue;
+ };
+ for edge in 0..3 {
+ let (Some(&first), Some(&second), Some(&third)) = (corners.get(edge), corners.get((edge + 1) % 3), corners.get((edge + 2) % 3)) else {
+ continue;
+ };
+ let (Some(first_key), Some(second_key)) = (position_key(first), position_key(second)) else {
+ continue;
+ };
+ let (first, second, key) =
+ if first_key <= second_key { (first, second, (first_key, second_key)) } else { (second, first, (second_key, first_key)) };
+ let (Some(start), Some(end), Some(interior)) = (mesh.uvs.get(first), mesh.uvs.get(second), mesh.uvs.get(third)) else {
+ continue;
+ };
+ let (start, end, interior) = (*start * texel_scale, *end * texel_scale, *interior * texel_scale);
+ let inward = (interior - (start + end) * 0.5).try_normalize().unwrap_or(Vec2::ZERO) * 0.75;
+ let Some((other_start, other_end, other_inward)) = edges.insert(key, (start, end, inward)) else {
+ continue;
+ };
+ if start.distance_squared(other_start) + end.distance_squared(other_end) < 0.25 {
+ continue;
+ }
+ let steps = start.distance(end).max(other_start.distance(other_end)).ceil().clamp(1.0, size.0.max(size.1) as f32 * 2.0) as usize;
+ for step in 0..=steps {
+ let fraction = step as f32 / steps as f32;
+ let (Some(first), Some(second)) = (texel(start.lerp(end, fraction) + inward), texel(other_start.lerp(other_end, fraction) + other_inward))
+ else {
+ continue;
+ };
+ let (Some(&first_value), Some(&second_value)) = (source.get(first), source.get(second)) else {
+ continue;
+ };
+ let average = (first_value + second_value) * 0.5;
+ for (index, value) in [(first, first_value), (second, second_value)] {
+ if let Some(destination) = pixels.get_mut(index) {
+ *destination = value + (average - value) * intensity;
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/crates/bake/src/map/source.rs b/crates/bake/src/map/source.rs
new file mode 100644
index 00000000..c5cd5f3f
--- /dev/null
+++ b/crates/bake/src/map/source.rs
@@ -0,0 +1,144 @@
+use super::part_key::part_key;
+use super::sampling::{generated_hue, interpolate, splitmix64};
+use crate::BakeRequest;
+use crate::tracing::{ANY, TraceMesh};
+use std::collections::HashMap;
+use std::sync::Arc;
+use texturecraft_core::{HighPolySettings, IdColorGenerator, IdColorSource, IdSettings};
+use texturecraft_geom::glam::{Vec2, Vec4};
+use texturecraft_geom::{BaseColor, Bvh, Mesh, Surface};
+use texturecraft_texel::{linear_to_srgb, srgb_to_linear};
+
+pub(super) struct Source<'a> {
+ pub(super) mesh: &'a Mesh,
+ bvh: &'a Bvh,
+ pub(super) part: Vec,
+ pub(super) key: Vec,
+ backface_culling: Vec,
+ file_ids: &'a [u32],
+ mesh_ids: Vec,
+ file_count: u32,
+ mesh_count: u32,
+ base_color: &'a [Option>],
+}
+
+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>) {
+ 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,
+ base_color: &'a [Option>],
+ file_ids: &'a [u32],
+ suffix: &str,
+ settings: &HighPolySettings,
+ keys: &mut HashMap,
+ ) -> Source<'a> {
+ let triangle_count = mesh.triangle_count();
+ let mut part = vec![ANY; triangle_count];
+ let mut backface_culling = vec![false; triangle_count];
+ let mut mesh_keys = HashMap::new();
+ let mut mesh_ids = Vec::with_capacity(mesh.submeshes.len());
+ let mut part_keys = Vec::with_capacity(mesh.submeshes.len());
+ let backface_suffix = settings.ignore_backface_suffix.trim().to_lowercase();
+
+ for (part_index, submesh) in mesh.submeshes.iter().enumerate() {
+ let first_triangle = (submesh.start / 3) as usize;
+ let last_triangle = (submesh.start.saturating_add(submesh.count) / 3) as usize;
+ let range = first_triangle.min(last_triangle)..last_triangle.min(triangle_count);
+ part.get_mut(range.clone()).unwrap_or_default().fill(part_index as u32);
+
+ let (key, ignore_backface, name) = part_key(&submesh.name, suffix, &backface_suffix, keys);
+ backface_culling.get_mut(range).unwrap_or_default().fill(ignore_backface);
+ part_keys.push(key);
+
+ let next = mesh_keys.len() as u32;
+ let file_id = file_ids.get(part_index).copied().unwrap_or(0);
+ mesh_ids.push(*mesh_keys.entry((file_id, name)).or_insert(next));
+ }
+
+ let key = part.iter().map(|part_index| part_keys.get(*part_index as usize).copied().unwrap_or(ANY)).collect();
+
+ Source {
+ mesh,
+ bvh,
+ part,
+ key,
+ backface_culling,
+ file_ids,
+ file_count: file_ids.iter().copied().max().unwrap_or(0).saturating_add(1),
+ mesh_count: mesh_keys.len() as u32,
+ mesh_ids,
+ base_color,
+ }
+ }
+
+ pub(super) fn trace(&self) -> TraceMesh<'_> {
+ TraceMesh { mesh: self.mesh, bvh: self.bvh, keys: &self.key, backface_culling: &self.backface_culling }
+ }
+
+ pub(super) fn id_color(&self, surface: &Surface, barycentric: [f32; 2], settings: IdSettings) -> [f32; 3] {
+ let part_index = self.part.get(surface.tri as usize).copied().unwrap_or(0) as usize;
+ match settings.source {
+ IdColorSource::VertexColor => interpolate(self.mesh, &self.mesh.colors, surface.tri, barycentric).unwrap_or(Vec4::ONE).truncate().to_array(),
+ IdColorSource::MaterialColor => {
+ let material = self.mesh.submeshes.get(part_index).map(|part| part.material);
+ material.and_then(|index| self.base_color.get(index)?.as_ref()).map_or([0.6; 3], |color| color.factor.truncate().to_array())
+ }
+ source => {
+ let (identity, count) = match source {
+ IdColorSource::FileId => (self.file_ids.get(part_index).copied().unwrap_or(0), self.file_count),
+ IdColorSource::MeshId => (self.mesh_ids.get(part_index).copied().unwrap_or(0), self.mesh_count),
+ _ => (part_index as u32, self.mesh.submeshes.len() as u32),
+ };
+ match settings.generator {
+ IdColorGenerator::HueShift => generated_hue(identity as usize),
+ IdColorGenerator::Grayscale => [(identity + 1) as f32 / count.max(1) as f32; 3],
+ IdColorGenerator::Random => {
+ let seed = splitmix64(u64::from(identity));
+ [0, 16, 32].map(|shift| ((seed >> shift) & 0xffff) as f32 / 65535.0)
+ }
+ }
+ }
+ }
+ }
+
+ pub(super) fn color(&self, surface: &Surface, barycentric: [f32; 2]) -> Vec4 {
+ let vertex = interpolate(self.mesh, &self.mesh.colors, surface.tri, barycentric).unwrap_or(Vec4::ONE);
+ let material = self.part.get(surface.tri as usize).and_then(|part_index| self.mesh.submeshes.get(*part_index as usize)).map(|submesh| submesh.material);
+ match material.and_then(|material_index| self.base_color.get(material_index)?.as_deref()) {
+ Some(material_color) => vertex * base_color(material_color, surface.uv),
+ None => vertex,
+ }
+ }
+}
+
+fn base_color(material: &BaseColor, uv: Vec2) -> Vec4 {
+ let sampled_color = if material.texels.is_empty() || !uv.is_finite() {
+ Vec4::ONE
+ } else {
+ let (width, height) = (i64::from(material.width.max(1)), i64::from(material.height.max(1)));
+ let texel = |x: i64, y: i64| {
+ let rgba = material.texels.get((y.rem_euclid(height) * width + x.rem_euclid(width)) as usize).copied().unwrap_or([255; 4]);
+ let color = |component: usize| f32::from(rgba[component]) / 255.0;
+ Vec4::new(srgb_to_linear(color(0)), srgb_to_linear(color(1)), srgb_to_linear(color(2)), color(3))
+ };
+ let (fx, fy) = (uv.x * width as f32 - 0.5, uv.y * height as f32 - 0.5);
+ let (x0, y0) = (fx.floor(), fy.floor());
+ let (tx, ty) = (fx - x0, fy - y0);
+ let (x, y) = (x0 as i64, y0 as i64);
+ texel(x, y).lerp(texel(x + 1, y), tx).lerp(texel(x, y + 1).lerp(texel(x + 1, y + 1), tx), ty)
+ };
+ let color = sampled_color * material.factor;
+ Vec4::new(linear_to_srgb(color.x), linear_to_srgb(color.y), linear_to_srgb(color.z), color.w)
+}
diff --git a/crates/bake/src/map/texel_grid.rs b/crates/bake/src/map/texel_grid.rs
new file mode 100644
index 00000000..49e2b588
--- /dev/null
+++ b/crates/bake/src/map/texel_grid.rs
@@ -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 {
+ 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
+ }
+}
diff --git a/crates/bake/src/map/traced.rs b/crates/bake/src/map/traced.rs
new file mode 100644
index 00000000..45107d66
--- /dev/null
+++ b/crates/bake/src/map/traced.rs
@@ -0,0 +1,8 @@
+use texturecraft_geom::glam::Vec3;
+
+pub(crate) struct Traced {
+ pub ao: f32,
+ pub bent: Option,
+ pub thickness: f32,
+ pub curvature: f32,
+}
diff --git a/crates/bake/src/map/transfer.rs b/crates/bake/src/map/transfer.rs
new file mode 100644
index 00000000..c1200053
--- /dev/null
+++ b/crates/bake/src/map/transfer.rs
@@ -0,0 +1,8 @@
+use texturecraft_geom::Surface;
+
+pub(crate) struct Transfer {
+ pub(super) surface: Surface,
+ pub(super) bary: [f32; 2],
+ pub(super) t: f32,
+ pub(super) front: f32,
+}
diff --git a/crates/bake/src/map/transfer_keys.rs b/crates/bake/src/map/transfer_keys.rs
new file mode 100644
index 00000000..69e9b12a
--- /dev/null
+++ b/crates/bake/src/map/transfer_keys.rs
@@ -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, Vec) {
+ let (low, high) = Source::of_request(request);
+ (low.key, high.map(|high| high.key).unwrap_or_default())
+}
diff --git a/crates/bake/src/maps.rs b/crates/bake/src/maps.rs
deleted file mode 100644
index 5aa60ba1..00000000
--- a/crates/bake/src/maps.rs
+++ /dev/null
@@ -1,440 +0,0 @@
-//! Per-sample evaluation of every baked map.
-
-use std::collections::HashMap;
-use std::ops::{Add, Mul};
-use std::sync::Arc;
-
-use texturecraft_core::{BakeMatch, BakeSettings, BakedMap, DirectionMode, PositionMode, RayDistribution, RaySettings, SelfOcclusion};
-use texturecraft_geom::glam::{Vec2, Vec3, Vec4};
-use texturecraft_geom::{BaseColor, Bvh, Hit, Mesh, Surface, surface_at};
-use texturecraft_texel::{linear_to_srgb, srgb_to_linear};
-
-use crate::rays::{ANY, Hemisphere, Query, Ray, RayKind, TraceMesh};
-use crate::skew::Prepared;
-use crate::{BakeError, BakeRequest};
-
-/// A mesh the bakers sample: the low poly, or the high poly detail is transferred from.
-struct Source<'a> {
- mesh: &'a Mesh,
- bvh: &'a Bvh,
- /// Per-vertex curvature offset from 0.5 (empty unless mesh curvature is baked).
- curvature: Vec,
- /// Submesh (part) index of each triangle ([`ANY`] outside every part).
- part: Vec,
- /// Match key of each triangle: its part name without the low / high suffix.
- key: Vec,
- /// Base color per material (empty: vertex colors only).
- base_color: &'a [Option>],
-}
-
-impl<'a> Source<'a> {
- fn new(
- mesh: &'a Mesh,
- bvh: &'a Bvh,
- base_color: &'a [Option>],
- s: &BakeSettings,
- diag: f32,
- suffix: &str,
- keys: &mut HashMap,
- ) -> Source<'a> {
- let mesh_curvature = s.maps.contains(&BakedMap::Curvature) && !s.curvature_from_normal;
- let tris = mesh.triangle_count();
- let mut part = vec![ANY; tris];
- for (i, sm) in mesh.submeshes.iter().enumerate() {
- let (a, b) = ((sm.start / 3) as usize, (sm.start.saturating_add(sm.count) / 3) as usize);
- part.get_mut(a.min(b)..b.min(tris)).unwrap_or_default().fill(i as u32);
- }
- let ids: Vec = mesh.submeshes.iter().map(|sm| match_key(&sm.name, suffix, keys)).collect();
- let key = part.iter().map(|p| ids.get(*p as usize).copied().unwrap_or(ANY)).collect();
- let curvature = if mesh_curvature { vertex_curvature(mesh, diag, s.curvature_strength) } else { Vec::new() };
- Source { mesh, bvh, curvature, part, key, base_color }
- }
-
- fn trace(&self) -> TraceMesh<'_> {
- TraceMesh { mesh: self.mesh, bvh: self.bvh, keys: &self.key }
- }
-
- fn curvature(&self, s: &Surface, bary: [f32; 2]) -> f32 {
- (0.5 + interpolate(self.mesh, &self.curvature, s.tri, bary).unwrap_or(0.0)).clamp(0.0, 1.0)
- }
-
- /// Vertex color times the material's base color (color sRGB-encoded like a base color
- /// texture, alpha linear).
- fn color(&self, s: &Surface, bary: [f32; 2]) -> Vec4 {
- let vertex = interpolate(self.mesh, &self.mesh.colors, s.tri, bary).unwrap_or(Vec4::ONE);
- let material = self.part.get(s.tri as usize).and_then(|p| self.mesh.submeshes.get(*p as usize)).map(|sm| sm.material);
- match material.and_then(|m| self.base_color.get(m)?.as_deref()) {
- Some(b) => vertex * base_color(b, s.uv),
- None => vertex,
- }
- }
-}
-
-/// `b` at `uv` (bilinear in linear light, wrapped) times its factor: color sRGB-encoded,
-/// alpha linear.
-fn base_color(b: &BaseColor, uv: Vec2) -> Vec4 {
- let tex = if b.texels.is_empty() || !uv.is_finite() {
- Vec4::ONE
- } else {
- let (w, h) = (i64::from(b.width.max(1)), i64::from(b.height.max(1)));
- let texel = |x: i64, y: i64| {
- let t = b.texels.get((y.rem_euclid(h) * w + x.rem_euclid(w)) as usize).copied().unwrap_or([255; 4]);
- let c = |k: usize| f32::from(t[k]) / 255.0;
- Vec4::new(srgb_to_linear(c(0)), srgb_to_linear(c(1)), srgb_to_linear(c(2)), c(3))
- };
- let (fx, fy) = (uv.x * w as f32 - 0.5, uv.y * h as f32 - 0.5);
- let (x0, y0) = (fx.floor(), fy.floor());
- let (tx, ty) = (fx - x0, fy - y0);
- let (x, y) = (x0 as i64, y0 as i64);
- texel(x, y).lerp(texel(x + 1, y), tx).lerp(texel(x, y + 1).lerp(texel(x + 1, y + 1), tx), ty)
- };
- let c = tex * b.factor;
- Vec4::new(linear_to_srgb(c.x), linear_to_srgb(c.y), linear_to_srgb(c.z), c.w)
-}
-
-/// The part name without its low / high suffix (case-insensitive), as a shared id.
-fn match_key(name: &str, suffix: &str, keys: &mut HashMap) -> u32 {
- let name = name.trim().to_lowercase();
- let suffix = suffix.trim().to_lowercase();
- let base = name.strip_suffix(suffix.as_str()).filter(|_| !suffix.is_empty()).unwrap_or(&name).to_string();
- let next = keys.len() as u32;
- *keys.entry(base).or_insert(next)
-}
-
-/// Barycentric interpolation of a per-vertex attribute over triangle `tri`.
-fn interpolate + Add>(mesh: &Mesh, v: &[T], tri: u32, [b1, b2]: [f32; 2]) -> Option {
- 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)
-}
-
-/// A covered low-poly supersample of a batch.
-pub(crate) struct Sample {
- /// Output column.
- pub x: usize,
- pub surf: Surface,
- pub bary: [f32; 2],
- pub seed: u64,
-}
-
-/// The high-poly surface found for a low-poly sample, and where along the ray.
-pub(crate) struct Transfer {
- surf: Surface,
- bary: [f32; 2],
- /// Hit distance from the ray origin, and the origin's distance in front of the low poly.
- t: f32,
- front: f32,
-}
-
-/// A sample's secondary-ray results.
-pub(crate) struct Traced {
- pub ao: f32,
- /// None when bent normals are not baked.
- pub bent: Option,
- pub thickness: f32,
-}
-
-/// Everything a sample needs, computed once per bake.
-pub(crate) struct Ctx<'a> {
- low: Source<'a>,
- high: Option>,
- cage: Option<&'a Mesh>,
- skew: Option>,
- /// Normals averaged over coincident vertices (rays don't split at hard edges); empty when off.
- ray_normals: Vec,
- lo: Vec3,
- extent: Vec3,
- /// Ray offset off the surface.
- eps: f32,
- frontal: f32,
- rear: f32,
- by_name: bool,
- direction: Vec3,
- direction_mode: DirectionMode,
- position_mode: PositionMode,
- curvature_from_normal: bool,
- /// Secondary-ray passes of the requested maps.
- pub ao: Option,
- pub bent: Option,
- pub thickness: Option,
-}
-
-impl<'a> Ctx<'a> {
- pub(crate) fn new(req: &BakeRequest<'a>) -> Result, BakeError> {
- let s = req.settings;
- let (lo, hi) = req.mesh.bounds();
- let diag = (hi - lo).length().max(1e-6);
- if !diag.is_finite() {
- return Err(BakeError::Invalid("mesh bounds are too large".into()));
- }
- let mut keys = HashMap::new();
- let low = Source::new(req.mesh, req.bvh, &[], s, diag, &s.low_suffix, &mut keys);
- let high = req.high.map(|h| Source::new(h.mesh, h.bvh, h.base_color, s, diag, &s.high_suffix, &mut keys));
- let ray_normals = match s.average_normals && high.is_some() {
- true => {
- let (weld, _, nrm) = welded(req.mesh, diag);
- weld.iter().map(|w| nrm.get(*w as usize).copied().unwrap_or(Vec3::Y)).collect()
- }
- false => Vec::new(),
- };
- let skew = req.skew.map(|m| Prepared::new(m, req.mesh, diag)).transpose()?;
- let eps = 1e-4 * diag;
- let pass = |map: BakedMap, r: &RaySettings, kind: RayKind| {
- let half = (r.spread.clamp(0.0, 180.0) * 0.5).to_radians();
- let occlusion = kind == RayKind::Occlusion;
- s.maps.contains(&map).then_some(Hemisphere {
- kind,
- rays: r.rays,
- dmax: r.max_distance * diag,
- eps,
- cos_max: half.cos(),
- sin_max: half.sin(),
- uniform: r.distribution == RayDistribution::Uniform,
- ignore_backface: occlusion && s.ao_ignore_backface,
- same_key: occlusion && s.ao_self_occlusion == SelfOcclusion::SameMeshName,
- })
- };
- Ok(Ctx {
- low,
- high,
- cage: req.cage,
- skew,
- ray_normals,
- lo,
- extent: hi - lo,
- eps,
- frontal: s.max_frontal * diag,
- rear: s.max_rear * diag,
- by_name: s.matching == BakeMatch::ByMeshName,
- direction: Vec3::from(s.direction).try_normalize().unwrap_or(Vec3::Y),
- direction_mode: s.direction_mode,
- position_mode: s.position_mode,
- curvature_from_normal: s.curvature_from_normal,
- ao: pass(BakedMap::AmbientOcclusion, &s.ao, RayKind::Occlusion),
- bent: pass(BakedMap::BentNormal, &s.bent_normal, RayKind::Occlusion),
- thickness: pass(BakedMap::Thickness, &s.thickness, RayKind::Thickness),
- })
- }
-
- pub(crate) fn has_high(&self) -> bool {
- self.high.is_some()
- }
-
- /// Whether the bake casts any ray.
- pub(crate) fn casts_rays(&self) -> bool {
- self.has_high() || self.ao.is_some() || self.bent.is_some() || self.thickness.is_some()
- }
-
- /// The meshes rays are cast against: the low poly, then the high poly.
- pub(crate) fn trace_meshes(&self) -> Vec> {
- std::iter::once(&self.low).chain(&self.high).map(Source::trace).collect()
- }
-
- /// The transfer ray of a low-poly sample: from the cage (or `frontal` in front of the low
- /// poly) back through it to `rear` behind, onto the matching high-poly part; and the
- /// origin's distance in front of the low poly. Parts without a key cast nothing when
- /// matched by name.
- pub(crate) fn transfer_ray(&self, s: &Surface, bary: [f32; 2]) -> (Ray, f32) {
- let n = interpolate(self.low.mesh, &self.ray_normals, s.tri, bary).and_then(Vec3::try_normalize).unwrap_or(s.nrm);
- let cage = self.cage.and_then(|c| interpolate(c, &c.positions, s.tri, bary)).map(|c| s.pos - c).filter(|v| v.length() > self.eps);
- let (origin, dir, front) = match cage {
- Some(v) => (s.pos - v, v.normalize(), v.length()),
- None => {
- // Skew correction turns the averaged direction towards the base normal.
- let up = match &self.skew {
- Some(k) => k.correct(self.low.mesh, s, n),
- None => n,
- };
- (s.pos + up * self.frontal, -up, self.frontal)
- }
- };
- let key = if self.by_name { self.low.key.get(s.tri as usize).copied().unwrap_or(ANY) } else { ANY };
- let tmax = if self.by_name && key == ANY { 0.0 } else { front + self.rear };
- (Ray { origin, dir, tmax, key }, front)
- }
-
- /// The high-poly surface a transfer ray hit.
- pub(crate) fn transfer(&self, hit: Option, front: f32) -> Option {
- let (high, hit) = (self.high.as_ref()?, hit?);
- let surf = surface_at(high.mesh, hit.tri, hit.u, hit.v)?;
- Some(Transfer { surf, bary: [hit.u, hit.v], t: hit.t, front })
- }
-
- /// The secondary-ray query of a sample: on the high poly where the transfer found it.
- pub(crate) fn query(&self, transfer: Option<&Transfer>, s: &Surface, seed: u64) -> Query {
- let (src, surf, mesh) = match (&self.high, transfer) {
- (Some(h), Some(tr)) => (h, &tr.surf, 1),
- _ => (&self.low, s, 0),
- };
- let h = splitmix64(seed);
- let rot = [(h >> 40) as f32 / (1u64 << 24) as f32, ((h >> 16) & 0xff_ffff) as f32 / (1u64 << 24) as f32];
- // The geometric normal on the side of the shading normal.
- let geo = if surf.geo_nrm.dot(surf.nrm) < 0.0 { -surf.geo_nrm } else { surf.geo_nrm };
- Query { pos: surf.pos, nrm: surf.nrm, geo, rot, key: src.key.get(surf.tri as usize).copied().unwrap_or(ANY), mesh }
- }
-
- /// Every map of `maps` at one low-poly sample, into `out` (scalars fill all three).
- pub(crate) fn evaluate(&self, maps: &[BakedMap], s: &Surface, bary: [f32; 2], transfer: Option<&Transfer>, traced: &Traced, out: &mut [[f32; 3]]) {
- // The surface the bakers read: the high poly where a ray found it, else the low poly.
- let (src, surf, sb) = match (&self.high, transfer) {
- (Some(h), Some(tr)) => (h, &tr.surf, tr.bary),
- _ => (&self.low, s, bary),
- };
- let missed = self.high.is_some() && transfer.is_none();
- for (&map, o) in maps.iter().zip(out.iter_mut()) {
- *o = match map {
- BakedMap::AmbientOcclusion => [traced.ao; 3],
- BakedMap::BentNormal => pack(traced.bent.unwrap_or(surf.nrm)),
- BakedMap::Thickness => [traced.thickness; 3],
- BakedMap::Curvature if self.curvature_from_normal => [0.5; 3],
- BakedMap::Curvature => [src.curvature(surf, sb); 3],
- BakedMap::WorldNormal => pack(surf.nrm),
- BakedMap::Position => self.position(surf.pos),
- BakedMap::Id => material_color(src.part.get(surf.tri as usize).copied().unwrap_or(0) as usize),
- BakedMap::Normal => transfer.map_or(map.neutral(), |tr| tangent_normal(s, tr.surf.nrm)),
- BakedMap::Height => [transfer.map_or(0.5, |tr| (0.5 + (tr.front - tr.t) / (tr.front + self.rear)).clamp(0.0, 1.0)); 3],
- BakedMap::Opacity if missed => [0.0; 3],
- BakedMap::Opacity => [src.color(surf, sb).w; 3],
- BakedMap::ColorMap if missed => map.neutral(),
- BakedMap::ColorMap => src.color(surf, sb).truncate().to_array(),
- BakedMap::WorldDirection => {
- let f = surf.nrm.dot(self.direction);
- [match self.direction_mode {
- DirectionMode::Signed => f * 0.5 + 0.5,
- DirectionMode::Positive => f.clamp(0.0, 1.0),
- }; 3]
- }
- };
- }
- }
-
- /// `p` normalized to 0..1 over the low poly's bounding box or bounding sphere.
- fn position(&self, p: Vec3) -> [f32; 3] {
- let v = match self.position_mode {
- PositionMode::BoundingBox => (p - self.lo) / self.extent.max(Vec3::splat(1e-20)),
- PositionMode::BoundingSphere => (p - (self.lo + self.extent * 0.5)) / self.extent.length().max(1e-20) + 0.5,
- };
- v.clamp(Vec3::ZERO, Vec3::ONE).to_array()
- }
-}
-
-/// A unit vector packed to 0..1.
-fn pack(v: Vec3) -> [f32; 3] {
- (v * 0.5 + 0.5).clamp(Vec3::ZERO, Vec3::ONE).to_array()
-}
-
-/// `n` in the tangent space of low-poly sample `s` (OpenGL: +Y up the image), packed to 0..1.
-fn tangent_normal(s: &Surface, n: Vec3) -> [f32; 3] {
- let z = s.nrm;
- let t = (s.tangent.truncate() - z * z.dot(s.tangent.truncate())).try_normalize().unwrap_or_else(|| z.any_orthonormal_vector());
- let b = z.cross(t) * s.tangent.w;
- pack(Vec3::new(t.dot(n), b.dot(n), z.dot(n)))
-}
-
-/// Curvature from a baked tangent-space normal map: the divergence of its XY over `radius`
-/// texels (convex = above 0.5; 0: one texel per 512 of a UV tile's resolution). Writes covered
-/// texels of `out` (one float per texel). `res` is the image width.
-pub(crate) fn curvature_from_normal(normal: &[f32], covered: &[bool], res: usize, tile_res: usize, radius: u32, strength: f32, out: &mut [f32]) {
- use rayon::prelude::*;
- let r = if radius > 0 { radius as usize } else { (tile_res / 512).max(1) };
- let n = |x: usize, y: usize, c: usize, fallback: f32| match covered.get(y * res + x) {
- Some(true) => normal.get((y * res + x) * 3 + c).copied().unwrap_or(fallback),
- _ => fallback,
- };
- out.par_chunks_mut(res).enumerate().for_each(|(y, row)| {
- for (x, v) in row.iter_mut().enumerate() {
- if covered.get(y * res + x) != Some(&true) {
- continue;
- }
- let (cx, cy) = (n(x, y, 0, 0.5), n(x, y, 1, 0.5));
- let (l, r_) = (n(x.saturating_sub(r), y, 0, cx), if x + r < res { n(x + r, y, 0, cx) } else { cx });
- let (u, d) = (n(x, y.saturating_sub(r), 1, cy), if y + r < res { n(x, y + r, 1, cy) } else { cy });
- // Image rows run down while +Y (OpenGL) points up: convex bumps tilt +Y above.
- *v = (0.5 + strength * ((r_ - l) + (u - d))).clamp(0.0, 1.0);
- }
- });
-}
-
-/// Position-welded copy of `mesh` (UV seams and hard edges share neighbours): the weld id of
-/// every vertex, welded positions and their averaged normals.
-fn welded(mesh: &Mesh, diag: f32) -> (Vec, Vec, Vec) {
- let q = diag * 1e-5;
- let mut ids: HashMap<[i64; 3], u32> = HashMap::new();
- let (mut pos, mut nrm) = (Vec::new(), Vec::::new());
- let weld: Vec = 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
- });
- if let Some(acc) = nrm.get_mut(id as usize) {
- *acc += *n;
- }
- id
- })
- .collect();
- let nrm = nrm.into_iter().map(|n| n.try_normalize().unwrap_or(Vec3::ZERO)).collect();
- (weld, pos, nrm)
-}
-
-/// Per-vertex curvature offset `−k · avg_edge · strength`, where `k` is the mean of
-/// `n·(p_j − p_i)/|p_j − p_i|²` over the 1-ring of the welded mesh. Convex edges give a
-/// positive offset.
-fn vertex_curvature(mesh: &Mesh, diag: f32, strength: f32) -> Vec {
- let q = diag * 1e-5;
- let (weld, pos, nrm) = welded(mesh, diag);
- let (mut ksum, mut kcnt) = (vec![0.0f32; pos.len()], vec![0u32; pos.len()]);
- let (mut edge_sum, mut edge_cnt) = (0.0f64, 0u64);
- for t in mesh.indices.chunks_exact(3) {
- for (a, b) in [(0, 1), (1, 2), (2, 0), (1, 0), (2, 1), (0, 2)] {
- let (Some(&wa), Some(&wb)) = (t.get(a).and_then(|v| weld.get(*v as usize)), t.get(b).and_then(|v| weld.get(*v as usize))) else { continue };
- let (Some(pa), Some(pb), Some(na)) = (pos.get(wa as usize), pos.get(wb as usize), nrm.get(wa as usize)) else { continue };
- let d = *pb - *pa;
- let l2 = d.length_squared();
- if wa == wb || l2 <= q * q {
- continue;
- }
- if let (Some(k), Some(c)) = (ksum.get_mut(wa as usize), kcnt.get_mut(wa as usize)) {
- *k += na.dot(d) / l2;
- *c += 1;
- }
- edge_sum += f64::from(l2.sqrt());
- edge_cnt += 1;
- }
- }
- let scale = (edge_sum / edge_cnt.max(1) as f64) as f32 * strength;
- weld.iter()
- .map(|w| {
- let i = *w as usize;
- let k = ksum.get(i).copied().unwrap_or(0.0) / kcnt.get(i).copied().unwrap_or(0).max(1) as f32;
- if k.is_finite() { -k * scale } else { 0.0 }
- })
- .collect()
-}
-
-/// A well-separated hue per part (golden-ratio steps around the HSV wheel).
-fn material_color(part: usize) -> [f32; 3] {
- let h = ((part as f64 * 0.618_033_988_75 + 0.05).fract() * 6.0) as f32;
- let (s, v) = (0.7f32, 0.95f32);
- let f = h.fract();
- let (p, q, t) = (v * (1.0 - s), v * (1.0 - s * f), v * (1.0 - s * (1.0 - f)));
- match h as u32 {
- 0 => [v, t, p],
- 1 => [q, v, p],
- 2 => [p, v, t],
- 3 => [p, q, v],
- 4 => [t, p, v],
- _ => [v, p, q],
- }
-}
-
-fn splitmix64(x: u64) -> u64 {
- let mut z = x.wrapping_add(0x9e37_79b9_7f4a_7c15);
- z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
- z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
- z ^ (z >> 31)
-}
diff --git a/crates/bake/src/mesh_extent.rs b/crates/bake/src/mesh_extent.rs
new file mode 100644
index 00000000..3c6fa48d
--- /dev/null
+++ b/crates/bake/src/mesh_extent.rs
@@ -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 {
+ 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
+ }
+}
diff --git a/crates/bake/src/name_pair.rs b/crates/bake/src/name_pair.rs
new file mode 100644
index 00000000..8863cc58
--- /dev/null
+++ b/crates/bake/src/name_pair.rs
@@ -0,0 +1,103 @@
+//! How "By Mesh Name" pairs low-poly parts with high-poly parts, listed before a bake runs
+
+use std::collections::{HashMap, HashSet};
+
+use texturecraft_core::HighPolySettings;
+use texturecraft_geom::Mesh;
+
+use crate::map::part_key;
+
+/// A low-poly part and the high-poly part its rays may hit under "By Mesh Name"; one side is missing when that part pairs with nothing
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct NamePair {
+ /// The low-poly part's name as in its mesh
+ pub low: Option,
+ /// The high-poly part's name as in its mesh
+ pub high: Option,
+}
+
+impl NamePair {
+ /// Each part of `low` in `material` with every `high` part it pairs with (a row per pair), then the `high` parts pairing with none; keyed like the bake, low poly first
+ pub fn list(low: &Mesh, material: usize, high: &Mesh, settings: &HighPolySettings) -> Vec {
+ let backface_suffix = settings.ignore_backface_suffix.trim().to_lowercase();
+ let mut keys = HashMap::new();
+ let mut keyed = |mesh: &Mesh, suffix: &str, only_material: Option| {
+ let mut seen = HashSet::new();
+ let mut parts = Vec::new();
+ for part in mesh.submeshes.iter().filter(|part| only_material.is_none_or(|material| part.material == material)) {
+ let (key, ..) = part_key(&part.name, suffix, &backface_suffix, &mut keys);
+ if seen.insert(part.name.as_str()) {
+ parts.push((key, part.name.clone()));
+ }
+ }
+ parts
+ };
+ let low_parts = keyed(low, &settings.low_suffix, Some(material));
+ let high_parts = keyed(high, &settings.high_suffix, None);
+
+ let mut pairs = Vec::new();
+ for (key, low_name) in &low_parts {
+ let matches: Vec<&String> = high_parts.iter().filter(|(high_key, _)| high_key == key).map(|(_, name)| name).collect();
+ if matches.is_empty() {
+ pairs.push(NamePair { low: Some(low_name.clone()), high: None });
+ }
+ pairs.extend(matches.into_iter().map(|high_name| NamePair { low: Some(low_name.clone()), high: Some(high_name.clone()) }));
+ }
+
+ let low_keys: HashSet = low_parts.iter().map(|(key, _)| *key).collect();
+ pairs.extend(high_parts.into_iter().filter(|(key, _)| !low_keys.contains(key)).map(|(_, name)| NamePair { low: None, high: Some(name) }));
+ pairs
+ }
+
+ /// Whether one side is missing: a part the bake will leave unpaired
+ pub fn unpaired(&self) -> bool {
+ self.low.is_none() || self.high.is_none()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use texturecraft_geom::SubMesh;
+
+ /// A mesh with one empty part per (name, material)
+ fn parts(names: &[(&str, usize)]) -> Mesh {
+ Mesh {
+ submeshes: names.iter().map(|(name, material)| SubMesh { name: (*name).into(), material: *material, start: 0, count: 0 }).collect(),
+ materials: vec!["first".into(), "second".into()],
+ ..Default::default()
+ }
+ }
+
+ fn pair(low: Option<&str>, high: Option<&str>) -> NamePair {
+ NamePair { low: low.map(Into::into), high: high.map(Into::into) }
+ }
+
+ #[test]
+ fn parts_pair_by_name_without_their_suffixes() {
+ let low = parts(&[("Barrel_low", 0), ("Base_low", 0), ("Slide_low", 1)]);
+ let high = parts(&[("Barrel_high", 0), ("Slide_high", 0), ("Grip_high", 0), ("BARREL_high_ignorebf", 0)]);
+ let settings = HighPolySettings::default();
+
+ assert_eq!(
+ NamePair::list(&low, 0, &high, &settings),
+ vec![
+ pair(Some("Barrel_low"), Some("Barrel_high")),
+ pair(Some("Barrel_low"), Some("BARREL_high_ignorebf")),
+ pair(Some("Base_low"), None),
+ pair(None, Some("Slide_high")),
+ pair(None, Some("Grip_high")),
+ ],
+ "another material's parts are left out, so its high-poly part counts as unpaired here"
+ );
+ assert_eq!(NamePair::list(&low, 1, &high, &settings).iter().filter(|pair| !pair.unpaired()).count(), 1);
+ }
+
+ #[test]
+ fn a_part_split_over_triangle_ranges_is_listed_once() {
+ let low = parts(&[("Body_low", 0), ("Body_low", 0)]);
+ let high = parts(&[("Body_high", 0), ("Body_high", 0)]);
+
+ assert_eq!(NamePair::list(&low, 0, &high, &HighPolySettings::default()), vec![pair(Some("Body_low"), Some("Body_high"))]);
+ }
+}
diff --git a/crates/bake/src/progress.rs b/crates/bake/src/progress.rs
new file mode 100644
index 00000000..5bb924ec
--- /dev/null
+++ b/crates/bake/src/progress.rs
@@ -0,0 +1,22 @@
+use std::sync::atomic::{AtomicBool, AtomicU32, Ordering::Relaxed};
+
+#[derive(Debug, Default)]
+pub struct Progress {
+ /// Completed basis points, from 0 to 10,000
+ pub done: AtomicU32,
+ pub cancel: AtomicBool,
+}
+
+impl Progress {
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ pub fn fraction(&self) -> f32 {
+ self.done.load(Relaxed).min(10_000) as f32 / 10_000.0
+ }
+
+ pub fn cancel(&self) {
+ self.cancel.store(true, Relaxed);
+ }
+}
diff --git a/crates/bake/src/rays.rs b/crates/bake/src/rays.rs
deleted file mode 100644
index 6e1ce02a..00000000
--- a/crates/bake/src/rays.rs
+++ /dev/null
@@ -1,206 +0,0 @@
-//! The ray casts of a bake, in batches. [`CpuTracer`] is the oracle; a GPU [`Tracer`] (the
-//! render crate's compute baker) must give the same results: it receives the same rays and
-//! queries, and generates the same secondary-ray directions from each query's rotation.
-
-use std::f32::consts::TAU;
-
-use rayon::prelude::*;
-use texturecraft_geom::glam::Vec3;
-use texturecraft_geom::{Bvh, Hit, Mesh};
-
-use crate::BakeError;
-
-/// A ray or query key that matches every triangle (no part filter).
-pub const ANY: u32 = u32::MAX;
-
-/// A mesh rays are cast against: [`RayScene`] mesh 0 is the low poly, mesh 1 the high poly.
-#[derive(Clone, Copy, Debug)]
-pub struct TraceMesh<'a> {
- pub mesh: &'a Mesh,
- pub bvh: &'a Bvh,
- /// Part key of every triangle (original order); triangles of no part hold [`ANY`].
- pub keys: &'a [u32],
-}
-
-impl TraceMesh<'_> {
- fn key_matches(&self, tri: u32, key: u32) -> bool {
- key == ANY || self.keys.get(tri as usize) == Some(&key)
- }
-
- /// Whether `d` meets triangle `tri` from behind (against its winding's normal).
- fn back_facing(&self, tri: u32, d: Vec3) -> bool {
- let p = |i: usize| self.mesh.positions.get(i).copied().unwrap_or(Vec3::ZERO);
- self.mesh.tri(tri as usize).is_some_and(|[a, b, c]| (p(b) - p(a)).cross(p(c) - p(a)).dot(d) > 0.0)
- }
-}
-
-/// A closest-hit ray (the high-poly transfer).
-#[derive(Clone, Copy, Debug, PartialEq)]
-pub struct Ray {
- pub origin: Vec3,
- pub dir: Vec3,
- pub tmax: f32,
- /// Only triangles with this part key are hit ([`ANY`]: all).
- pub key: u32,
-}
-
-/// One sample's secondary rays (ambient occlusion, bent normal or thickness).
-#[derive(Clone, Copy, Debug, PartialEq)]
-pub struct Query {
- pub pos: Vec3,
- /// Shading normal: the axis of the ray cone.
- pub nrm: Vec3,
- /// Geometric normal on the shading normal's side: rays below its plane are skipped.
- pub geo: Vec3,
- /// Cranley–Patterson rotation of the sample's ray set.
- pub rot: [f32; 2],
- /// Part key of the sample's triangle (for [`Hemisphere::same_key`]).
- pub key: u32,
- /// Scene mesh the rays are cast against.
- pub mesh: u32,
-}
-
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-pub enum RayKind {
- /// Out of the surface: ambient occlusion and the bent normal.
- Occlusion,
- /// Into the surface: the distance through the mesh.
- Thickness,
-}
-
-/// Parameters of one pass of secondary rays (distances absolute).
-#[derive(Clone, Copy, Debug, PartialEq)]
-pub struct Hemisphere {
- pub kind: RayKind,
- pub rays: u32,
- pub dmax: f32,
- /// Ray start offset along the geometric normal.
- pub eps: f32,
- /// Cosine and sine of the cone's half angle.
- pub cos_max: f32,
- pub sin_max: f32,
- /// Uniform over the cone's solid angle (else cosine-weighted).
- pub uniform: bool,
- pub ignore_backface: bool,
- /// Only triangles with the query's part key occlude.
- pub same_key: bool,
-}
-
-impl Hemisphere {
- /// Direction `i` of a query's ray set around `axis` (basis `t`, `b`): Hammersley points
- /// rotated by `rot`, mapped onto the cone.
- pub fn direction(&self, (t, b, axis): (Vec3, Vec3, Vec3), i: u32, rot: [f32; 2]) -> Vec3 {
- let u1 = (i as f32 / self.rays as f32 + rot[0]).fract();
- let u2 = (i.reverse_bits() as f32 / 4_294_967_296.0 + rot[1]).fract();
- let (r, z) = if self.uniform {
- let z = 1.0 - u2 * (1.0 - self.cos_max);
- ((1.0 - z * z).max(0.0).sqrt(), z)
- } else {
- let r = self.sin_max * u2.sqrt();
- (r, (1.0 - r * r).max(0.0).sqrt())
- };
- let phi = TAU * u1;
- t * (r * phi.cos()) + b * (r * phi.sin()) + axis * z
- }
-
- /// The axis, geometric normal and ray origin of `q` for this kind of rays.
- fn frame(&self, q: &Query) -> (Vec3, Vec3, Vec3) {
- let (axis, geo) = match self.kind {
- RayKind::Occlusion => (q.nrm, q.geo),
- RayKind::Thickness => (-q.nrm, -q.geo),
- };
- (axis, geo, q.pos + geo * self.eps)
- }
-
- /// `q`'s result on `m`: occlusion gives (ambient occlusion, bent normal), thickness gives
- /// (thickness, 0, 0, 0); both relative and in 0..1 (1 = open / thick).
- pub fn evaluate(&self, m: &TraceMesh, q: &Query) -> [f32; 4] {
- let (axis, geo, o) = self.frame(q);
- let (t, b) = axis.any_orthonormal_pair();
- let key = if self.same_key && self.kind == RayKind::Occlusion { q.key } else { ANY };
- let filtered = key != ANY || (self.ignore_backface && self.kind == RayKind::Occlusion);
- let (mut sum, mut bent, mut n) = (0.0f32, Vec3::ZERO, 0u32);
- for i in 0..self.rays {
- let d = self.direction((t, b, axis), i, q.rot);
- if d.dot(geo) <= 0.0 {
- continue;
- }
- let hit = match filtered {
- true => m.bvh.closest_filtered(o, d, self.dmax, &|tri| m.key_matches(tri, key) && !(self.ignore_backface && m.back_facing(tri, d))),
- false => m.bvh.closest(o, d, self.dmax),
- };
- match self.kind {
- RayKind::Occlusion => {
- let v = hit.map_or(0.0, |h| 1.0 - (h.t / self.dmax).powi(2));
- sum += v;
- bent += d * (1.0 - v);
- }
- RayKind::Thickness => sum += hit.map_or(self.dmax, |h| h.t),
- }
- n += 1;
- }
- match self.kind {
- RayKind::Occlusion => {
- let ao = if n == 0 { 1.0 } else { (1.0 - sum / n as f32).clamp(0.0, 1.0) };
- let bent = bent.try_normalize().unwrap_or(q.nrm);
- [ao, bent.x, bent.y, bent.z]
- }
- RayKind::Thickness => [if n == 0 { 1.0 } else { (sum / n as f32 / self.dmax).clamp(0.0, 1.0) }, 0.0, 0.0, 0.0],
- }
- }
-}
-
-/// Ray casts on the meshes of one bake.
-pub trait RayScene: Send {
- /// The closest hit of every ray on scene mesh `mesh` (triangles of the ray's key).
- fn closest(&mut self, mesh: usize, rays: &[Ray]) -> Result>, BakeError>;
- /// [`Hemisphere::evaluate`] of every query, for each pass.
- fn hemispheres(&mut self, passes: &[Hemisphere], queries: &[Query]) -> Result>, BakeError>;
-}
-
-/// Where ray casts run.
-pub trait Tracer: Send + Sync {
- /// Shown in logs and command results ("CPU", the GPU's name).
- fn name(&self) -> String;
- /// Prepare `meshes` (low poly, then the high poly if any) for ray casts.
- fn scene<'a>(&'a self, meshes: &[TraceMesh<'a>]) -> Result, BakeError>;
-}
-
-/// Ray casts on the CPU (rayon over the batch).
-#[derive(Clone, Copy, Debug, Default)]
-pub struct CpuTracer;
-
-struct CpuScene<'a>(Vec>);
-
-impl CpuScene<'_> {
- fn mesh(&self, i: usize) -> Result<&TraceMesh<'_>, BakeError> {
- self.0.get(i).ok_or_else(|| BakeError::Invalid(format!("no scene mesh {i}")))
- }
-}
-
-impl RayScene for CpuScene<'_> {
- fn closest(&mut self, mesh: usize, rays: &[Ray]) -> Result>, BakeError> {
- let m = self.mesh(mesh)?;
- Ok(rays
- .par_iter()
- .map(|r| match r.key {
- ANY => m.bvh.closest(r.origin, r.dir, r.tmax),
- key => m.bvh.closest_filtered(r.origin, r.dir, r.tmax, &|t| m.key_matches(t, key)),
- })
- .collect())
- }
-
- fn hemispheres(&mut self, passes: &[Hemisphere], queries: &[Query]) -> Result>, BakeError> {
- passes.iter().map(|h| queries.par_iter().map(|q| Ok(h.evaluate(self.mesh(q.mesh as usize)?, q))).collect()).collect()
- }
-}
-
-impl Tracer for CpuTracer {
- fn name(&self) -> String {
- "CPU".into()
- }
-
- fn scene<'a>(&'a self, meshes: &[TraceMesh<'a>]) -> Result, BakeError> {
- Ok(Box::new(CpuScene(meshes.to_vec())))
- }
-}
diff --git a/crates/bake/src/skew.rs b/crates/bake/src/skew.rs
index 28cd4c92..61104cb7 100644
--- a/crates/bake/src/skew.rs
+++ b/crates/bake/src/skew.rs
@@ -1,261 +1,19 @@
-//! Skew correction: a greyscale map over the UV atlas that turns the transfer rays of a
-//! high-poly bake from the averaged cage direction towards the low poly's own normal. Where the
-//! averaged direction leans away from a surface (the classic "skewed" details on a bevelled
-//! edge or a cylinder's cap), painting the map white there sends the rays straight along the
-//! surface normal instead, and grey values blend the two.
-//!
-//! Ported from SurfaceCraft's baker (`crates/bake`, MIT OR Apache-2.0), adapted to this crate's
-//! [`crate::maps::Ctx`] rays. Like the averaged cage it only changes rays that start from the
-//! built-in distance cage: a custom cage mesh sets its own directions and ignores the map.
+//! Skew correction adapted from SurfaceCraft's baker (MIT OR Apache-2.0)
-use std::collections::HashMap;
+mod prepared_skew;
-use texturecraft_geom::glam::{Vec2, Vec3};
-use texturecraft_geom::{Mesh, Surface};
-
-use crate::{BakeError, MAX_TEXELS};
-
-/// Most dabs one [`SkewMap::paint`] call places.
-pub const MAX_DABS: usize = 200_000;
-
-/// Most texels one [`SkewMap::paint`] call may visit, summed over its dabs (about 70 ms of work):
-/// a big brush on a big map costs per dab what a whole-map pass costs, so dabs alone don't bound it.
-pub const MAX_PAINT_TEXELS: u64 = 1 << 26;
-
-/// Edges steeper than this cosine between two faces count as hard (about 30 degrees).
-const HARD_EDGE_COS: f32 = 0.866;
-
-/// A skew map over the whole UV atlas.
-#[derive(Clone, Debug, PartialEq)]
-pub struct SkewMap {
- pub width: u32,
- pub height: u32,
- /// `width * height` values in 0..=1, row 0 at the top (v = 1): 0 keeps a ray on the cage's
- /// averaged direction, 1 turns it fully onto the base normal.
- pub values: Vec,
- /// Edge protection: the correction fades out within this fraction of the mesh diagonal of a
- /// hard edge (0: off).
- pub edge_distance: f32,
- /// Edge protection's falloff exponent: 1 is linear, more holds the correction back longer.
- pub edge_contrast: f32,
- /// Correct towards each triangle's flat normal instead of the interpolated vertex normal.
- pub per_triangle: bool,
-}
-
-impl SkewMap {
- /// A map of one value everywhere.
- pub fn constant(value: f32) -> SkewMap {
- SkewMap { width: 1, height: 1, values: vec![value], edge_distance: 0.0, edge_contrast: 1.0, per_triangle: false }
- }
-
- /// Refuses maps whose size doesn't match their values, non-finite numbers and absurd sizes.
- pub fn validate(&self) -> Result<(), BakeError> {
- let invalid = |m: &str| Err(BakeError::Invalid(m.into()));
- let texels = u64::from(self.width) * u64::from(self.height);
- if self.width == 0 || self.height == 0 || texels > MAX_TEXELS || self.values.len() as u64 != texels {
- return invalid("the skew map's size doesn't match its values");
- }
- if !(self.edge_distance.is_finite() && self.edge_distance >= 0.0 && self.edge_contrast.is_finite() && self.edge_contrast > 0.0) {
- return invalid("the skew edge distance must be 0 or more and the contrast above 0");
- }
- if self.values.iter().any(|v| !v.is_finite()) {
- return invalid("the skew map has a value that is not a finite number");
- }
- Ok(())
- }
-
- /// The map resampled (bilinear) to `width` × `height`; the other settings carry over.
- pub fn resized(&self, width: u32, height: u32) -> Result {
- let texels = u64::from(width) * u64::from(height);
- if width == 0 || height == 0 || texels > MAX_TEXELS {
- return Err(BakeError::Invalid(format!("a {width} × {height} skew map is outside the supported size")));
- }
- let mut values = Vec::with_capacity(texels as usize);
- for y in 0..height {
- let v = 1.0 - (y as f32 + 0.5) / height as f32;
- for x in 0..width {
- values.push(self.at(Vec2::new((x as f32 + 0.5) / width as f32, v)));
- }
- }
- Ok(SkewMap { width, height, values, ..self.clone() })
- }
-
- /// Paint round dabs along `points` (atlas uv): `value` is blended in with `strength` (0..=1),
- /// fully inside `hardness` (0..=1) of `radius` (in uv units) and fading to nothing at the rim.
- /// Dabs are placed a quarter radius apart along each segment; `MAX_DABS` bounds one call.
- pub fn paint(&mut self, points: &[Vec2], radius: f32, value: f32, hardness: f32, strength: f32) -> Result<(), BakeError> {
- let ok = radius.is_finite() && radius > 0.0 && value.is_finite() && hardness.is_finite() && strength.is_finite();
- if !ok || points.iter().any(|p| !p.is_finite()) {
- return Err(BakeError::Invalid("the skew brush needs finite numbers and a radius above 0".into()));
- }
- self.validate()?;
- let (value, hardness, strength) = (value.clamp(0.0, 1.0), hardness.clamp(0.0, 0.999), strength.clamp(0.0, 1.0));
- let step = (radius * 0.25).max(1e-5);
- let mut dabs = Vec::new();
- for (i, p) in points.iter().enumerate() {
- match i.checked_sub(1).and_then(|j| points.get(j)) {
- Some(prev) => {
- let n = ((*p - *prev).length() / step).ceil().clamp(1.0, MAX_DABS as f32) as usize;
- dabs.extend((1..=n).map(|k| *prev + (*p - *prev) * (k as f32 / n as f32)));
- }
- None => dabs.push(*p),
- }
- if dabs.len() > MAX_DABS {
- return Err(BakeError::Invalid(format!("a skew stroke is limited to {MAX_DABS} dabs; use a larger radius or fewer points")));
- }
- }
- let (w, h) = (self.width as usize, self.height as usize);
- // The texel box of a dab, row 0 at the top (v = 1).
- let span = |c: Vec2| {
- let x0 = (((c.x - radius) * w as f32).floor().max(0.0)) as usize;
- let x1 = (((c.x + radius) * w as f32).ceil().min(w as f32)).max(0.0) as usize;
- let y0 = ((((1.0 - c.y) - radius) * h as f32).floor().max(0.0)) as usize;
- let y1 = ((((1.0 - c.y) + radius) * h as f32).ceil().min(h as f32)).max(0.0) as usize;
- (x0, x1, y0, y1)
- };
- // Refuse a stroke that would take too long before the first texel changes.
- let work: u64 = dabs
- .iter()
- .map(|c| {
- let (x0, x1, y0, y1) = span(*c);
- x1.saturating_sub(x0) as u64 * y1.saturating_sub(y0) as u64
- })
- .fold(0, u64::saturating_add);
- if work > MAX_PAINT_TEXELS {
- return Err(BakeError::Invalid(format!(
- "this stroke would visit {work} texels (limit {MAX_PAINT_TEXELS}); use a smaller radius, a smaller map or a shorter stroke"
- )));
- }
- for c in dabs {
- let (x0, x1, y0, y1) = span(c);
- for y in y0..y1 {
- let dv = (1.0 - (y as f32 + 0.5) / h as f32) - c.y;
- for x in x0..x1 {
- let du = (x as f32 + 0.5) / w as f32 - c.x;
- let t = (du * du + dv * dv).sqrt() / radius;
- if t >= 1.0 {
- continue;
- }
- let fall = if t <= hardness {
- 1.0
- } else {
- let k = (1.0 - t) / (1.0 - hardness);
- k * k * (3.0 - 2.0 * k)
- };
- if let Some(v) = self.values.get_mut(y * w + x) {
- *v += (value - *v) * fall * strength;
- }
- }
- }
- }
- Ok(())
- }
-
- /// The map at atlas `uv`: bilinear, edges clamped.
- pub(crate) fn at(&self, uv: Vec2) -> f32 {
- let (w, h) = (self.width.max(1) as usize, self.height.max(1) as usize);
- if !uv.is_finite() {
- return 0.0;
- }
- let x = (uv.x.clamp(0.0, 1.0) * w as f32 - 0.5).clamp(0.0, w as f32 - 1.0);
- let y = ((1.0 - uv.y).clamp(0.0, 1.0) * h as f32 - 0.5).clamp(0.0, h as f32 - 1.0);
- let (x0, y0) = (x.floor() as usize, y.floor() as usize);
- let (x1, y1) = ((x0 + 1).min(w - 1), (y0 + 1).min(h - 1));
- let (fx, fy) = (x - x0 as f32, y - y0 as f32);
- let v = |xx: usize, yy: usize| self.values.get(yy * w + xx).copied().unwrap_or(0.0);
- let top = v(x0, y0) * (1.0 - fx) + v(x1, y0) * fx;
- let bottom = v(x0, y1) * (1.0 - fx) + v(x1, y1) * fx;
- (top * (1.0 - fy) + bottom * fy).clamp(0.0, 1.0)
- }
-}
-
-/// A skew map ready for a bake: the map plus what edge protection needs.
-pub(crate) struct Prepared<'a> {
- map: &'a SkewMap,
- /// Per triangle, which of its edges (v0-v1, v1-v2, v2-v0) are hard; only with edge protection.
- hard: Vec<[bool; 3]>,
- diag: f32,
-}
-
-impl<'a> Prepared<'a> {
- pub(crate) fn new(map: &'a SkewMap, mesh: &Mesh, diag: f32) -> Result, BakeError> {
- map.validate()?;
- let hard = if map.edge_distance > 0.0 { hard_edges(mesh) } else { Vec::new() };
- Ok(Prepared { map, hard, diag })
- }
-
- /// The ray direction `up` (unit, away from the surface) at the low-poly sample `s` turned
- /// towards its base normal: the interpolated vertex normal, or the flat one per triangle.
- pub(crate) fn correct(&self, mesh: &Mesh, s: &Surface, up: Vec3) -> Vec3 {
- let amount = self.map.at(s.uv);
- if amount <= 0.0 {
- return up;
- }
- let protect = match (self.hard.get(s.tri as usize), mesh.tri(s.tri as usize)) {
- (Some(edges), Some(c)) => {
- let near = (0..3)
- .filter(|&k| edges[k])
- .filter_map(|k| {
- let a = mesh.positions.get(*c.get(k)?)?;
- let b = mesh.positions.get(*c.get((k + 1) % 3)?)?;
- Some(segment_distance(s.pos, *a, *b))
- })
- .fold(f32::INFINITY, f32::min);
- (near / (self.map.edge_distance * self.diag).max(1e-9)).clamp(0.0, 1.0).powf(self.map.edge_contrast)
- }
- _ => 1.0,
- };
- let base = if self.map.per_triangle { s.geo_nrm } else { s.nrm };
- let t = amount * protect;
- (up * (1.0 - t) + base * t).try_normalize().unwrap_or(up)
- }
-}
-
-/// Per triangle, which edges are hard: shared with a triangle whose face normal is more than
-/// about 30 degrees away. Edges are matched by position, so split vertices still pair up.
-fn hard_edges(mesh: &Mesh) -> Vec<[bool; 3]> {
- let pt = |i: usize| mesh.positions.get(i).copied().unwrap_or(Vec3::ZERO);
- let key = |i: usize| mesh.positions.get(i).map_or([0; 3], |p| p.to_array().map(|c| (c + 0.0).to_bits()));
- let ordered = |a: [u32; 3], b: [u32; 3]| if a <= b { (a, b) } else { (b, a) };
- let count = mesh.triangle_count();
- let mut face = vec![Vec3::ZERO; count];
- let mut edges: HashMap<([u32; 3], [u32; 3]), Vec> = HashMap::new();
- for (t, f) in face.iter_mut().enumerate() {
- let Some(c) = mesh.tri(t) else { continue };
- *f = (pt(c[1]) - pt(c[0])).cross(pt(c[2]) - pt(c[0])).try_normalize().unwrap_or(Vec3::ZERO);
- for k in 0..3 {
- edges.entry(ordered(key(c[k]), key(c[(k + 1) % 3]))).or_default().push(t);
- }
- }
- (0..count)
- .map(|t| {
- let mut out = [false; 3];
- if let Some(c) = mesh.tri(t) {
- let own = face.get(t).copied().unwrap_or(Vec3::ZERO);
- for (k, hard) in out.iter_mut().enumerate() {
- let others = edges.get(&ordered(key(c[k]), key(c[(k + 1) % 3])));
- *hard = others.is_some_and(|ts| ts.iter().any(|&o| o != t && face.get(o).is_some_and(|f| f.dot(own) < HARD_EDGE_COS)));
- }
- }
- out
- })
- .collect()
-}
-
-/// Distance from `p` to the segment `a`-`b`.
-fn segment_distance(p: Vec3, a: Vec3, b: Vec3) -> f32 {
- let ab = b - a;
- let len2 = ab.length_squared();
- let t = if len2 > 1e-20 { ((p - a).dot(ab) / len2).clamp(0.0, 1.0) } else { 0.0 };
- (p - (a + ab * t)).length()
-}
+#[cfg(test)]
+use crate::BakePaintMap;
+pub(crate) use prepared_skew::PreparedSkew;
#[cfg(test)]
mod tests {
+ use super::prepared_skew::{hard_edges, segment_distance};
use super::*;
+ use texturecraft_geom::glam::{Vec2, Vec3};
+ use texturecraft_geom::{Mesh, Surface};
fn fold() -> Mesh {
- // Two triangles folded 90 degrees along (0,0,0)-(1,0,0), and a third continuing flat.
Mesh { positions: vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::Z, Vec3::new(1.0, 1.0, 0.0)], indices: vec![0, 1, 2, 0, 3, 1, 1, 4, 2], ..Mesh::default() }
}
@@ -270,19 +28,19 @@ mod tests {
#[test]
fn maps_sample_bilinearly_and_bad_ones_are_refused() {
- let map = SkewMap { width: 2, height: 1, values: vec![0.0, 1.0], ..SkewMap::constant(0.0) };
+ let map = BakePaintMap { width: 2, height: 1, values: vec![0.0, 1.0] };
assert!(map.validate().is_ok());
assert!(
- map.at(Vec2::new(0.0, 0.5)).abs() < 1e-6 && (map.at(Vec2::new(1.0, 0.5)) - 1.0).abs() < 1e-6 && (map.at(Vec2::new(0.5, 0.5)) - 0.5).abs() < 1e-6
+ map.sample(Vec2::new(0.0, 0.5)).abs() < 1e-6
+ && (map.sample(Vec2::new(1.0, 0.5)) - 1.0).abs() < 1e-6
+ && (map.sample(Vec2::new(0.5, 0.5)) - 0.5).abs() < 1e-6
);
- assert!(map.at(Vec2::new(-3.0, 9.0)).is_finite() && map.at(Vec2::new(f32::NAN, 0.0)) == 0.0);
+ assert!(map.sample(Vec2::new(-3.0, 9.0)).is_finite() && map.sample(Vec2::new(f32::NAN, 0.0)) == 0.0);
for bad in [
- SkewMap { values: vec![0.0], ..map.clone() },
- SkewMap { width: 0, values: vec![], ..map.clone() },
- SkewMap { values: vec![0.0, f32::NAN], ..map.clone() },
- SkewMap { edge_distance: -1.0, ..map.clone() },
- SkewMap { edge_contrast: 0.0, ..map.clone() },
- SkewMap { width: u32::MAX, height: u32::MAX, ..map.clone() },
+ BakePaintMap { values: vec![0.0], ..map.clone() },
+ BakePaintMap { width: 0, values: vec![], ..map.clone() },
+ BakePaintMap { values: vec![0.0, f32::NAN], ..map.clone() },
+ BakePaintMap { width: u32::MAX, height: u32::MAX, ..map.clone() },
] {
assert!(bad.validate().is_err());
}
@@ -293,50 +51,51 @@ mod tests {
let mesh = fold();
let up = Vec3::new(0.6, 0.8, 0.0);
let base = Vec3::Y;
- let go = |map: &SkewMap, pos: Vec3| {
+ let go = |map: &BakePaintMap, pos: Vec3, edge_distance: f32| {
let s = Surface { pos, nrm: base, geo_nrm: base, tangent: Default::default(), uv: Vec2::splat(0.5), tri: 0 };
- Prepared::new(map, &mesh, 1.0).unwrap().correct(&mesh, &s, up)
+ PreparedSkew::new(
+ map,
+ &mesh,
+ 1.0,
+ texturecraft_core::SkewSettings { edge_protection: edge_distance > 0.0, edge_distance, edge_contrast: 1.0, ..Default::default() },
+ )
+ .unwrap()
+ .correct(&mesh, &s, up)
};
- assert!((go(&SkewMap::constant(0.0), Vec3::ZERO) - up).length() < 1e-6, "black leaves the ray alone");
- assert!((go(&SkewMap::constant(1.0), Vec3::ZERO) - base).length() < 1e-6, "white turns it onto the base normal");
- let half = go(&SkewMap::constant(0.5), Vec3::ZERO);
+ assert!((go(&BakePaintMap::constant(0.0), Vec3::ZERO, 0.0) - up).length() < 1e-6, "black leaves the ray alone");
+ assert!((go(&BakePaintMap::constant(1.0), Vec3::ZERO, 0.0) - base).length() < 1e-6, "white turns it onto the base normal");
+ let half = go(&BakePaintMap::constant(0.5), Vec3::ZERO, 0.0);
assert!(half.x > 0.0 && half.x < up.x && (half.length() - 1.0).abs() < 1e-5, "grey is in between and still unit: {half}");
- // Triangle 0's edge (0,0,0)-(1,0,0) is hard: on it the correction is held back, far from it it is not.
- let guarded = SkewMap { edge_distance: 0.5, ..SkewMap::constant(1.0) };
- assert!((go(&guarded, Vec3::new(0.5, 0.0, 0.0)) - up).length() < 1e-6, "on the hard edge the ray stays on the cage direction");
- assert!((go(&guarded, Vec3::new(0.3, 0.9, 0.0)) - base).length() < 1e-6, "away from every hard edge the correction is full");
+ let guarded = BakePaintMap::constant(1.0);
+ assert!((go(&guarded, Vec3::new(0.5, 0.0, 0.0), 0.5) - up).length() < 1e-6, "on the hard edge the ray stays on the cage direction");
+ assert!((go(&guarded, Vec3::new(0.3, 0.9, 0.0), 0.5) - base).length() < 1e-6, "away from every hard edge the correction is full");
}
#[test]
fn painting_blends_dabs_in_and_resizing_keeps_the_picture() {
- let mut map = SkewMap::constant(0.0).resized(64, 64).unwrap();
+ let mut map = BakePaintMap::constant(0.0).resized(64, 64).unwrap();
assert!(map.values.iter().all(|v| *v == 0.0));
- // One hard dab at the centre: white inside, untouched outside, in between at the rim.
map.paint(&[Vec2::new(0.5, 0.5)], 0.2, 1.0, 1.0, 1.0).unwrap();
- let at = |m: &SkewMap, u: f32, v: f32| m.at(Vec2::new(u, v));
+ let at = |m: &BakePaintMap, u: f32, v: f32| m.sample(Vec2::new(u, v));
assert!(at(&map, 0.5, 0.5) > 0.99 && at(&map, 0.95, 0.95) == 0.0, "{} {}", at(&map, 0.5, 0.5), at(&map, 0.95, 0.95));
- // Strength blends one dab in part of the way; a stroke's overlapping dabs build up towards the value; v is up.
- let mut dab = SkewMap::constant(0.0).resized(64, 64).unwrap();
+ let mut dab = BakePaintMap::constant(0.0).resized(64, 64).unwrap();
dab.paint(&[Vec2::new(0.5, 0.5)], 0.1, 0.8, 1.0, 0.5).unwrap();
assert!((at(&dab, 0.5, 0.5) - 0.4).abs() < 0.02, "{}", at(&dab, 0.5, 0.5));
- let mut line = SkewMap::constant(0.0).resized(64, 64).unwrap();
+ let mut line = BakePaintMap::constant(0.0).resized(64, 64).unwrap();
line.paint(&[Vec2::new(0.1, 0.9), Vec2::new(0.9, 0.9)], 0.05, 0.5, 1.0, 0.5).unwrap();
assert!(at(&line, 0.5, 0.9) > 0.45 && at(&line, 0.5, 0.9) <= 0.5 + 1e-4, "{}", at(&line, 0.5, 0.9));
assert!(at(&line, 0.5, 0.1) == 0.0, "the other end of v is untouched");
- // Erasing (value 0) brings a painted area back down.
map.paint(&[Vec2::new(0.5, 0.5)], 0.2, 0.0, 1.0, 1.0).unwrap();
assert!(at(&map, 0.5, 0.5) < 0.01);
- // Resampling keeps the picture and the edge settings.
- let mut small = SkewMap { edge_distance: 0.1, ..SkewMap::constant(0.0).resized(8, 8).unwrap() };
+ let mut small = BakePaintMap::constant(0.0).resized(8, 8).unwrap();
small.paint(&[Vec2::new(0.25, 0.75)], 0.2, 1.0, 1.0, 1.0).unwrap();
let big = small.resized(32, 32).unwrap();
- assert_eq!(big.edge_distance, 0.1);
assert!((at(&big, 0.25, 0.75) - at(&small, 0.25, 0.75)).abs() < 0.1 && at(&big, 0.9, 0.1) == 0.0);
}
#[test]
fn hostile_brushes_are_refused_and_change_nothing() {
- let mut map = SkewMap::constant(0.3).resized(16, 16).unwrap();
+ let mut map = BakePaintMap::constant(0.3).resized(16, 16).unwrap();
let before = map.clone();
let c = [Vec2::new(0.5, 0.5)];
for (pts, r, v) in
@@ -344,17 +103,15 @@ mod tests {
{
assert!(map.paint(pts, r, v, 0.5, 1.0).is_err(), "{pts:?} {r} {v}");
}
- // Points far outside the atlas are harmless; a huge stroke is refused before any dab lands.
map.paint(&[Vec2::new(1e6, -1e6)], 0.1, 1.0, 0.5, 1.0).unwrap();
assert_eq!(map, before);
assert!(map.paint(&[Vec2::ZERO, Vec2::new(1e6, 1e6)], 1e-4, 1.0, 0.5, 1.0).is_err());
assert_eq!(map, before);
- // A big brush over a big map is refused up front, whatever the dab count: one dab here covers 16.7 M texels.
- let mut big = SkewMap::constant(0.0).resized(4096, 4096).unwrap();
+ let mut big = BakePaintMap::constant(0.0).resized(4096, 4096).unwrap();
let untouched = big.clone();
assert!(big.paint(&[Vec2::splat(0.5); 8], 1.0, 1.0, 0.5, 1.0).is_err());
assert_eq!(big, untouched, "nothing was painted before the refusal");
assert!(big.paint(&[Vec2::splat(0.5)], 1.0, 1.0, 0.5, 1.0).is_ok(), "one such dab is within the budget");
- assert!(SkewMap::constant(0.0).resized(0, 4).is_err() && SkewMap::constant(0.0).resized(100_000, 100_000).is_err());
+ assert!(BakePaintMap::constant(0.0).resized(0, 4).is_err() && BakePaintMap::constant(0.0).resized(100_000, 100_000).is_err());
}
}
diff --git a/crates/bake/src/skew/prepared_skew.rs b/crates/bake/src/skew/prepared_skew.rs
new file mode 100644
index 00000000..e6cce826
--- /dev/null
+++ b/crates/bake/src/skew/prepared_skew.rs
@@ -0,0 +1,92 @@
+use crate::BakeError;
+use crate::BakePaintMap;
+use std::collections::HashMap;
+use texturecraft_core::{SkewCorrectionMethod, SkewSettings};
+use texturecraft_geom::glam::Vec3;
+use texturecraft_geom::{Mesh, Surface};
+
+const HARD_EDGE_COS: f32 = 0.866;
+
+pub(crate) struct PreparedSkew<'a> {
+ map: &'a BakePaintMap,
+ settings: SkewSettings,
+ hard: Vec<[bool; 3]>,
+ mesh_scale: f32,
+}
+
+impl<'a> PreparedSkew<'a> {
+ pub(crate) fn new(map: &'a BakePaintMap, mesh: &Mesh, mesh_scale: f32, settings: SkewSettings) -> Result, BakeError> {
+ map.validate()?;
+ let hard = if settings.edge_protection && settings.edge_distance > 0.0 { hard_edges(mesh) } else { Vec::new() };
+ Ok(PreparedSkew { map, settings, hard, mesh_scale })
+ }
+
+ pub(crate) fn correct(&self, mesh: &Mesh, surface: &Surface, up: Vec3) -> Vec3 {
+ let amount = self.map.sample(surface.uv);
+ if amount <= 0.0 {
+ return up;
+ }
+ let protection = match (self.hard.get(surface.tri as usize), mesh.tri(surface.tri as usize)) {
+ (Some(edges), Some(corners)) => {
+ let nearest_edge_distance = (0..3)
+ .filter(|&edge_index| edges[edge_index])
+ .filter_map(|edge_index| {
+ let edge_start = mesh.positions.get(*corners.get(edge_index)?)?;
+ let edge_end = mesh.positions.get(*corners.get((edge_index + 1) % 3)?)?;
+ Some(segment_distance(surface.pos, *edge_start, *edge_end))
+ })
+ .fold(f32::INFINITY, f32::min);
+ (nearest_edge_distance / (self.settings.edge_distance * self.mesh_scale).max(1e-9)).clamp(0.0, 1.0).powf(self.settings.edge_contrast.max(1e-6))
+ }
+ _ => 1.0,
+ };
+ let base = match self.settings.method {
+ SkewCorrectionMethod::MeshNormalsBased => surface.nrm,
+ SkewCorrectionMethod::FaceNormalsBased => {
+ if surface.geo_nrm.dot(surface.nrm) < 0.0 {
+ -surface.geo_nrm
+ } else {
+ surface.geo_nrm
+ }
+ }
+ };
+ let blend = amount * protection;
+ (up * (1.0 - blend) + base * blend).try_normalize().unwrap_or(up)
+ }
+}
+
+pub(super) fn hard_edges(mesh: &Mesh) -> Vec<[bool; 3]> {
+ let pt = |i: usize| mesh.positions.get(i).copied().unwrap_or(Vec3::ZERO);
+ let key = |i: usize| mesh.positions.get(i).map_or([0; 3], |p| p.to_array().map(|c| (c + 0.0).to_bits()));
+ let ordered = |a: [u32; 3], b: [u32; 3]| if a <= b { (a, b) } else { (b, a) };
+ let count = mesh.triangle_count();
+ let mut face = vec![Vec3::ZERO; count];
+ let mut edges: HashMap<([u32; 3], [u32; 3]), Vec> = HashMap::new();
+ for (t, f) in face.iter_mut().enumerate() {
+ let Some(c) = mesh.tri(t) else { continue };
+ *f = (pt(c[1]) - pt(c[0])).cross(pt(c[2]) - pt(c[0])).try_normalize().unwrap_or(Vec3::ZERO);
+ for k in 0..3 {
+ edges.entry(ordered(key(c[k]), key(c[(k + 1) % 3]))).or_default().push(t);
+ }
+ }
+ (0..count)
+ .map(|t| {
+ let mut out = [false; 3];
+ if let Some(c) = mesh.tri(t) {
+ let own = face.get(t).copied().unwrap_or(Vec3::ZERO);
+ for (k, hard) in out.iter_mut().enumerate() {
+ let others = edges.get(&ordered(key(c[k]), key(c[(k + 1) % 3])));
+ *hard = others.is_some_and(|ts| ts.iter().any(|&o| o != t && face.get(o).is_some_and(|f| f.dot(own) < HARD_EDGE_COS)));
+ }
+ }
+ out
+ })
+ .collect()
+}
+
+pub(super) fn segment_distance(p: Vec3, a: Vec3, b: Vec3) -> f32 {
+ let ab = b - a;
+ let len2 = ab.length_squared();
+ let t = if len2 > 1e-20 { ((p - a).dot(ab) / len2).clamp(0.0, 1.0) } else { 0.0 };
+ (p - (a + ab * t)).length()
+}
diff --git a/crates/bake/src/test/cage_shell.rs b/crates/bake/src/test/cage_shell.rs
new file mode 100644
index 00000000..40edd3b8
--- /dev/null
+++ b/crates/bake/src/test/cage_shell.rs
@@ -0,0 +1,192 @@
+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 = 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));
+}
+
+#[test]
+fn the_cage_lists_its_hard_edges_without_a_uv_seam() {
+ // A quad whose diagonal is split into two vertices with the same UV, smooth or hard by the copy's normal
+ let quad_with_diagonal_normal = |normal: Vec3| {
+ let mut mesh = Mesh::from_parts(
+ vec![Vec3::ZERO, Vec3::X, Vec3::new(1.0, 1.0, 0.0), Vec3::Y],
+ None,
+ vec![Vec2::new(0.0, 1.0), Vec2::new(1.0, 1.0), Vec2::new(1.0, 0.0), Vec2::new(0.0, 0.0)],
+ vec![0, 1, 2, 0, 2, 3],
+ "Default",
+ )
+ .unwrap();
+ mesh.positions.push(mesh.positions[0]);
+ mesh.normals.push(normal);
+ mesh.tangents.push(mesh.tangents[0]);
+ mesh.uvs.push(mesh.uvs[0]);
+ mesh.indices[3] = 4;
+ mesh
+ };
+ let shell_of = |low: &Mesh| {
+ let bvh = Bvh::new(low);
+ let bake_settings = settings(16, &[BakedMap::Normal]);
+ let request = BakeRequest {
+ low_base_color: &[],
+ mesh: low,
+ bvh: &bvh,
+ material: 0,
+ settings: &bake_settings,
+ high: Some(HighPoly { file_ids: &[], mesh: low, bvh: &bvh, base_color: &[] }),
+ cage: None,
+ skew: None,
+ cage_paint: None,
+ tiles: (1, 1),
+ };
+ let shell = CageShell::new(&request).unwrap();
+ let shared = CageShell::new_with_edges(&request, &low.wire_edges(), &low.missing_seam_edges()).unwrap();
+ assert_eq!(shared.positions, shell.positions);
+ assert_eq!(shared.corners(0.1), shell.corners(0.1));
+ assert_eq!(shared.edges, shell.edges);
+ assert_eq!(shared.missing_seams, shell.missing_seams);
+ shell
+ };
+
+ let smooth = quad_with_diagonal_normal(Vec3::Z);
+ assert!(shell_of(&smooth).missing_seams.is_empty(), "the same normal on both sides is a smooth edge");
+
+ let hard = quad_with_diagonal_normal(Vec3::new(1.0, 0.0, 1.0).normalize());
+ let shell = shell_of(&hard);
+ let diagonal = [Vec3::ZERO, Vec3::new(1.0, 1.0, 0.0)];
+ assert_eq!(shell.missing_seams.len(), 2, "the diagonal, once per triangle");
+ for [from, to] in &shell.missing_seams {
+ let mut ends = [shell.positions[*from as usize], shell.positions[*to as usize]];
+ ends.sort_by(|a, b| a.x.total_cmp(&b.x));
+ assert_eq!(ends, diagonal, "the line runs along the hard diagonal");
+ }
+}
+
+#[test]
+fn shared_edges_select_the_requested_material() {
+ let mut mesh = primitives::cube(1.0);
+ mesh.append(&primitives::cube(1.0));
+ let bvh = Bvh::new(&mesh);
+ let bake_settings = settings(16, &[BakedMap::Normal]);
+ let wire_edges = mesh.wire_edges();
+ let missing_seam_edges = mesh.missing_seam_edges();
+
+ for material in 0..mesh.materials.len() {
+ let request = BakeRequest {
+ low_base_color: &[],
+ mesh: &mesh,
+ bvh: &bvh,
+ material,
+ settings: &bake_settings,
+ high: None,
+ cage: None,
+ skew: None,
+ cage_paint: None,
+ tiles: (1, 1),
+ };
+ let direct = CageShell::new(&request).unwrap();
+ let shared = CageShell::new_with_edges(&request, &wire_edges, &missing_seam_edges).unwrap();
+
+ assert_eq!(shared.positions, direct.positions);
+ assert_eq!(shared.starts, direct.starts);
+ assert_eq!(shared.edges, direct.edges);
+ assert_eq!(shared.missing_seams, direct.missing_seams);
+ }
+}
diff --git a/crates/bake/src/test/high_poly_reach.rs b/crates/bake/src/test/high_poly_reach.rs
new file mode 100644
index 00000000..8a4f83c4
--- /dev/null
+++ b/crates/bake/src/test/high_poly_reach.rs
@@ -0,0 +1,223 @@
+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) {
+ 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.as_chunks_mut::<3>().0 {
+ let center_x = corners.iter().map(|&corner| mesh.positions[corner as usize].x).sum::() / 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);
+}
diff --git a/crates/bake/src/test/normal_map_curvature.rs b/crates/bake/src/test/normal_map_curvature.rs
new file mode 100644
index 00000000..99ea078e
--- /dev/null
+++ b/crates/bake/src/test/normal_map_curvature.rs
@@ -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- ) -> (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
= 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 = (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 = 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()));
+}
diff --git a/crates/bake/src/test/setting.rs b/crates/bake/src/test/setting.rs
new file mode 100644
index 00000000..668338a7
--- /dev/null
+++ b/crates/bake/src/test/setting.rs
@@ -0,0 +1,206 @@
+use super::*;
+use texturecraft_core::{
+ AmbientOcclusionAttenuation, HeightNormalization, IdColorSource, MeshMatchMode, PositionAxis, PositionNormalizationScale, ThicknessNormalization,
+};
+
+#[test]
+fn rectangular_bakes_and_diffusion_preserve_surface_pixels() {
+ let mut mesh = quad();
+ for uv in &mut mesh.uvs {
+ uv.x *= 0.5;
+ }
+ let mut parameters = settings(64, &[BakedMap::Position]);
+ parameters.common.resolution_height = Some(BakeResolution::R32);
+ let plain = run(&mesh, ¶meters).unwrap();
+ assert_eq!((plain.resolution, plain.height), (64, 32));
+ assert_eq!(plain.maps[&BakedMap::Position].len(), 64 * 32 * 3);
+ parameters.common.apply_diffusion = true;
+ let diffused = run(&mesh, ¶meters).unwrap();
+ for row in 0..32 {
+ let covered = row * 64 * 3..(row * 64 + 32) * 3;
+ assert_eq!(plain.maps[&BakedMap::Position][covered.clone()], diffused.maps[&BakedMap::Position][covered]);
+ }
+ let background = (20 * 64 + 50) * 3;
+ assert_eq!(plain.maps[&BakedMap::Position][background], 0.0);
+ assert!(diffused.maps[&BakedMap::Position][background] > 0.0);
+}
+
+#[test]
+fn matching_skips_a_closer_unrelated_high_mesh_and_backfaces() {
+ let mut low = quad();
+ low.submeshes[0].name = "Panel_low".into();
+ let mut high = quad();
+ high.submeshes[0].name = "Panel_high".into();
+ high.positions.iter_mut().for_each(|position| position.y = 0.02);
+ let mut unrelated = quad();
+ unrelated.submeshes[0].name = "Other_high".into();
+ unrelated.positions.iter_mut().for_each(|position| position.y = 0.04);
+ high.append(&unrelated);
+ let mut parameters = settings(16, &[BakedMap::Height]);
+ parameters.cage.max_frontal = 0.1;
+ parameters.cage.relative_to_bounding_box = false;
+ parameters.maps.height.parameters.normalization = HeightNormalization::Manual;
+ let height = |parameters: &BakeSettings, high: &Mesh| transfer(&low, high, None, parameters).unwrap().maps[&BakedMap::Height][128];
+
+ assert!((height(¶meters, &high) - 0.54).abs() < 1e-5);
+
+ parameters.high_poly.match_mode = MeshMatchMode::ByMeshName;
+ assert!((height(¶meters, &high) - 0.52).abs() < 1e-5);
+
+ for triangle in high.indices.as_chunks_mut::<3>().0 {
+ triangle.swap(1, 2);
+ }
+
+ assert_eq!(height(¶meters, &high), 0.5);
+
+ parameters.high_poly.ignore_backface = false;
+ assert!((height(¶meters, &high) - 0.52).abs() < 1e-5);
+}
+
+#[test]
+fn occlusion_honors_minimum_distance_units_attenuation_and_named_backfaces() {
+ let mut mesh = quad();
+ let mut ceiling = quad();
+ ceiling.positions.iter_mut().for_each(|position| position.y = 0.1);
+ ceiling.submeshes[0].name = "Roof_ignorebf".into();
+ mesh.append(&ceiling);
+ let mut parameters = settings(16, &[BakedMap::AmbientOcclusion]);
+ parameters.maps.ao.parameters.rays =
+ RaySettings { rays: 1, spread: 0.0, min_distance: 0.0, max_distance: 1.0, relative_to_bounding_box: false, ..Default::default() };
+ let value = |parameters: &BakeSettings| run(&mesh, parameters).unwrap().maps[&BakedMap::AmbientOcclusion][128];
+ parameters.maps.ao.parameters.attenuation = AmbientOcclusionAttenuation::None;
+ assert_eq!(value(¶meters), 0.0);
+ parameters.maps.ao.parameters.attenuation = AmbientOcclusionAttenuation::Linear;
+ assert!((value(¶meters) - 0.1).abs() < 1e-4);
+ parameters.maps.ao.parameters.attenuation = AmbientOcclusionAttenuation::Smooth;
+ assert!((value(¶meters) - 0.028).abs() < 1e-4);
+ parameters.maps.ao.parameters.rays.min_distance = 0.15;
+ assert_eq!(value(¶meters), 1.0);
+ parameters.maps.ao.parameters.rays.min_distance = 0.0;
+ parameters.maps.ao.parameters.rays.max_distance = 0.075;
+ assert_eq!(value(¶meters), 1.0);
+ parameters.maps.ao.parameters.rays.relative_to_bounding_box = true;
+ assert!(value(¶meters) < 0.8);
+ parameters.maps.ao.parameters.ignore_backface = BackfaceMode::ByMeshName;
+ assert_eq!(value(¶meters), 1.0);
+ parameters.maps.ao.parameters.ignore_backface = BackfaceMode::Never;
+ parameters.maps.ao.parameters.self_occlusion = SelfOcclusion::SameMeshName;
+ assert_eq!(value(¶meters), 1.0);
+}
+
+#[test]
+fn bent_normal_settings_are_independent_of_ambient_occlusion() {
+ let mesh = primitives::material_ball();
+ let mut parameters = settings(32, &[BakedMap::BentNormal, BakedMap::AmbientOcclusion]);
+ let original = run(&mesh, ¶meters).unwrap();
+ parameters.maps.ao.parameters.ignore_backface = BackfaceMode::Always;
+ parameters.maps.ao.parameters.self_occlusion = SelfOcclusion::SameMeshName;
+ parameters.maps.ao.parameters.attenuation = AmbientOcclusionAttenuation::None;
+ let changed = run(&mesh, ¶meters).unwrap();
+ assert_eq!(original.maps[&BakedMap::BentNormal], changed.maps[&BakedMap::BentNormal]);
+}
+
+#[test]
+fn id_sources_keep_material_color_separate_from_vertex_color_and_textures() {
+ let low = quad();
+ let mut high = quad();
+ high.colors = vec![Vec4::new(0.8, 0.1, 0.3, 1.0); high.vertex_count()];
+ let colors = vec![Some(Arc::new(BaseColor { factor: Vec4::new(0.2, 0.4, 0.7, 1.0), width: 1, height: 1, texels: vec![[255, 0, 0, 255]] }))];
+ let (low_bvh, high_bvh) = (Bvh::new(&low), Bvh::new(&high));
+ let mut parameters = settings(16, &[BakedMap::Id]);
+ for (source, expected) in [(IdColorSource::MaterialColor, [0.2, 0.4, 0.7]), (IdColorSource::VertexColor, [0.8, 0.1, 0.3])] {
+ parameters.maps.id.parameters.source = source;
+ let request = BakeRequest {
+ low_base_color: &[],
+ mesh: &low,
+ bvh: &low_bvh,
+ material: 0,
+ settings: ¶meters,
+ high: Some(HighPoly { mesh: &high, bvh: &high_bvh, base_color: &colors, file_ids: &[0] }),
+ cage: None,
+ skew: None,
+ cage_paint: None,
+ tiles: (1, 1),
+ };
+ let output = bake(&request, &Progress::new()).unwrap();
+ for (value, expected) in output.maps[&BakedMap::Id][128 * 3..129 * 3].iter().zip(expected) {
+ assert!((value - expected).abs() < 1e-6);
+ }
+ }
+}
+
+#[test]
+fn painted_cage_limits_frontal_projection() {
+ let low = quad();
+ let mut high = quad();
+ high.positions.iter_mut().for_each(|position| position.y = 0.08);
+ let (low_bvh, high_bvh) = (Bvh::new(&low), Bvh::new(&high));
+ let mut parameters = settings(16, &[BakedMap::Opacity]);
+ parameters.cage.max_frontal = 0.1;
+ parameters.cage.relative_to_bounding_box = false;
+ let reduced = BakePaintMap::constant(0.5);
+ let mut request = BakeRequest {
+ low_base_color: &[],
+ mesh: &low,
+ bvh: &low_bvh,
+ material: 0,
+ settings: ¶meters,
+ high: Some(HighPoly { mesh: &high, bvh: &high_bvh, base_color: &[], file_ids: &[] }),
+ cage: None,
+ skew: None,
+ cage_paint: None,
+ tiles: (1, 1),
+ };
+ assert_eq!(bake(&request, &Progress::new()).unwrap().maps[&BakedMap::Opacity][128], 1.0);
+ request.cage_paint = Some(&reduced);
+ assert_eq!(bake(&request, &Progress::new()).unwrap().maps[&BakedMap::Opacity][128], 0.0);
+}
+
+#[test]
+fn position_axis_and_material_bounds_change_only_the_requested_space() {
+ let mut mesh = quad();
+ let mut distant = quad();
+ distant.positions.iter_mut().for_each(|position| position.x += 10.0);
+ mesh.append(&distant);
+ let mut parameters = settings(16, &[BakedMap::Position]);
+ parameters.maps.position.parameters.axis = PositionAxis::X;
+
+ let global = run(&mesh, ¶meters).unwrap();
+ parameters.maps.position.parameters.scale = PositionNormalizationScale::PerMaterial;
+ let local = run(&mesh, ¶meters).unwrap();
+
+ assert!(global.maps[&BakedMap::Position].iter().all(|value| *value < 0.2));
+ assert!(local.maps[&BakedMap::Position].iter().any(|value| *value > 0.9));
+ assert!(local.maps[&BakedMap::Position].as_chunks::<3>().0.iter().all(|pixel| pixel[0] == pixel[1] && pixel[1] == pixel[2]));
+}
+
+#[test]
+fn curvature_radius_and_manual_bounds_control_edge_response() {
+ let mesh = primitives::cube(2.0);
+ let mut parameters = settings(64, &[BakedMap::Curvature]);
+ let narrow = run(&mesh, ¶meters).unwrap();
+ parameters.maps.curvature.parameters.mesh.sampling_radius *= 4.0;
+ let wide = run(&mesh, ¶meters).unwrap();
+ let edge_count = |output: &BakeOutput| covered_values(&mesh, output, BakedMap::Curvature).iter().filter(|(_, value)| *value > 0.6).count();
+ assert!(edge_count(&wide) > edge_count(&narrow));
+ parameters.maps.curvature.parameters.mesh.value_min = -2.0;
+ parameters.maps.curvature.parameters.mesh.value_max = 2.0;
+ let reduced = run(&mesh, ¶meters).unwrap();
+ assert!(reduced.maps[&BakedMap::Curvature].iter().all(|value| (0.25..=0.75).contains(value)));
+}
+
+#[test]
+fn thickness_can_preserve_distance_or_normalize_each_tile() {
+ let mesh = primitives::rounded_box(Vec3::new(1.0, 0.05, 1.0), 0.0);
+ let mut parameters = settings(32, &[BakedMap::Thickness]);
+ parameters.maps.thickness.parameters.normalization = ThicknessNormalization::None;
+ parameters.maps.thickness.parameters.rays.relative_to_bounding_box = false;
+ parameters.maps.thickness.parameters.rays.max_distance = 0.3;
+ let distance = run(&mesh, ¶meters).unwrap();
+ assert!(covered_values(&mesh, &distance, BakedMap::Thickness).iter().all(|(_, value)| *value <= 0.30001));
+ parameters.maps.thickness.parameters.normalization = ThicknessNormalization::RelativeToMinMax;
+ let normalized = run(&mesh, ¶meters).unwrap();
+ let values = covered_values(&mesh, &normalized, BakedMap::Thickness);
+ assert!(values.iter().any(|(_, value)| *value == 0.0));
+ assert!(values.iter().any(|(_, value)| *value == 1.0));
+}
diff --git a/crates/bake/src/test/tile_selection.rs b/crates/bake/src/test/tile_selection.rs
new file mode 100644
index 00000000..18f13968
--- /dev/null
+++ b/crates/bake/src/test/tile_selection.rs
@@ -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());
+}
diff --git a/crates/bake/src/test/vertex_reach.rs b/crates/bake/src/test/vertex_reach.rs
new file mode 100644
index 00000000..7675e8dc
--- /dev/null
+++ b/crates/bake/src/test/vertex_reach.rs
@@ -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}"
+ );
+ }
+ }
+}
diff --git a/crates/bake/src/tests.rs b/crates/bake/src/tests.rs
index 8fcca53f..0c313462 100644
--- a/crates/bake/src/tests.rs
+++ b/crates/bake/src/tests.rs
@@ -1,18 +1,58 @@
+use std::sync::Arc;
+use texturecraft_geom::{BaseColor, Bvh};
+
+use texturecraft_core::{
+ AmbientOcclusionSettings, BakeAntialiasing, BakeResolution, BakeSettings, BentNormalSettings, CageSettings, CommonBakeSettings, CurvatureSettings,
+ PositionSettings,
+};
+
use std::sync::atomic::Ordering::Relaxed;
-use texturecraft_core::{BakeMatch, DirectionMode, PositionMode, RayDistribution, RaySettings, SelfOcclusion};
+use texturecraft_core::{BackfaceMode, PositionMode, RayDistribution, RaySettings, SelfOcclusion};
use texturecraft_geom::glam::{Vec2, Vec3, Vec4};
use texturecraft_geom::primitives;
use super::*;
-fn settings(res: u32, maps: &[BakedMap]) -> BakeSettings {
- with_rays(BakeSettings { resolution: res, dilation: 0, maps: maps.iter().copied().collect(), ..BakeSettings::default() }, 64, 0.25)
+#[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(
+ {
+ let mut base = BakeSettings::default();
+ base.common =
+ CommonBakeSettings { resolution: BakeResolution::from_pixels(resolution).unwrap(), dilation: 0, apply_diffusion: false, ..base.common };
+ base.maps.curvature.parameters = CurvatureSettings { method: CurvatureMethod::Mesh, ..base.maps.curvature.parameters };
+ base.maps.position.parameters = PositionSettings { normalization: PositionMode::BoundingBox, ..base.maps.position.parameters };
+ base.maps.curvature.parameters.mesh.auto_tonemapping = false;
+ base.maps.height.parameters.normalization = texturecraft_core::HeightNormalization::RelativeToRayDistances;
+ base.maps.thickness.parameters.normalization = texturecraft_core::ThicknessNormalization::RelativeToRayDistances;
+ base.maps.select(maps.iter().copied());
+ base
+ },
+ 64,
+ 0.25,
+ )
}
-/// `s` with every secondary-ray map at `rays` rays of length `max_distance`.
fn with_rays(mut s: BakeSettings, rays: u32, max_distance: f32) -> BakeSettings {
- for r in [&mut s.ao, &mut s.thickness, &mut s.bent_normal] {
+ for r in [&mut s.maps.ao.parameters.rays, &mut s.maps.thickness.parameters.rays, &mut s.maps.bent_normal.parameters.rays] {
*r = RaySettings { rays, max_distance, ..*r };
}
s
@@ -20,10 +60,12 @@ fn with_rays(mut s: BakeSettings, rays: u32, max_distance: f32) -> BakeSettings
fn run(mesh: &Mesh, s: &BakeSettings) -> Result {
let bvh = Bvh::new(mesh);
- bake(&BakeRequest { mesh, bvh: &bvh, material: 0, settings: s, high: None, cage: None, skew: None, tiles: (1, 1) }, &Progress::new())
+ bake(
+ &BakeRequest { low_base_color: &[], mesh, bvh: &bvh, material: 0, settings: s, high: None, cage: None, skew: None, cage_paint: None, tiles: (1, 1) },
+ &Progress::new(),
+ )
}
-/// Values of `map` (first component) at texels the UV layout covers, with their surface positions.
fn covered_values(mesh: &Mesh, out: &BakeOutput, map: BakedMap) -> Vec<(Vec3, f32)> {
let res = out.resolution;
let g = UvGBuffer::new(mesh, 0, res, res);
@@ -58,41 +100,160 @@ fn open_quad_is_unoccluded() {
#[test]
fn inside_of_a_closed_box_is_occluded() {
- let mut m = primitives::cube(2.0);
- for t in m.indices.chunks_exact_mut(3) {
- t.swap(1, 2);
+ let mut mesh = primitives::cube(2.0);
+ for triangle in mesh.indices.as_chunks_mut::<3>().0 {
+ triangle.swap(1, 2);
}
- for n in &mut m.normals {
- *n = -*n;
+ for normal in &mut mesh.normals {
+ *normal = -*normal;
}
- m.compute_tangents();
- let s = with_rays(settings(48, &[BakedMap::AmbientOcclusion]), 64, 4.0);
- let out = run(&m, &s).unwrap();
- let ao = mean(covered_values(&m, &out, BakedMap::AmbientOcclusion).into_iter().map(|v| v.1));
- assert!(ao < 0.3, "{ao}");
+ mesh.compute_tangents();
+ let parameters = with_rays(settings(64, &[BakedMap::AmbientOcclusion]), 64, 4.0);
+
+ let output = run(&mesh, ¶meters).unwrap();
+
+ let mean_occlusion = mean(covered_values(&mesh, &output, BakedMap::AmbientOcclusion).into_iter().map(|v| v.1));
+ assert!(mean_occlusion < 0.3, "{mean_occlusion}");
}
#[test]
fn thin_slab_is_thinner_than_a_block() {
- let thick = |m: &Mesh| mean(covered_values(m, &run(m, &settings(48, &[BakedMap::Thickness])).unwrap(), BakedMap::Thickness).into_iter().map(|v| v.1));
+ let thick = |m: &Mesh| mean(covered_values(m, &run(m, &settings(64, &[BakedMap::Thickness])).unwrap(), BakedMap::Thickness).into_iter().map(|v| v.1));
let slab = thick(&primitives::rounded_box(Vec3::new(1.0, 0.05, 1.0), 0.0));
let block = thick(&primitives::cube(2.0));
assert!(slab < 0.4 && block > 0.6, "slab {slab}, block {block}");
}
#[test]
-fn sphere_curvature_is_nearly_constant() {
- let m = primitives::sphere(1.0, 64, 32);
+fn sphere_curvature_stays_calm() {
+ for (rings, res) in [(64, 64), (12, 128)] {
+ let m = primitives::sphere(1.0, rings * 2, rings);
+ let s = settings(res, &[BakedMap::Curvature]);
+ let out = run(&m, &s).unwrap();
+ let c: Vec = covered_values(&m, &out, BakedMap::Curvature).into_iter().map(|v| v.1).collect();
+ let (lo, hi) = c.iter().fold((1.0f32, 0.0f32), |(lo, hi), v| (lo.min(*v), hi.max(*v)));
+ assert!(lo >= 0.5 && hi < 0.6 && hi - lo < 0.08, "{rings} rings: {lo}..{hi}");
+ }
+}
+
+#[test]
+fn flat_surface_is_exactly_mid_grey() {
+ let m = quad();
let out = run(&m, &settings(64, &[BakedMap::Curvature])).unwrap();
- let c: Vec = covered_values(&m, &out, BakedMap::Curvature).into_iter().map(|v| v.1).collect();
- let (lo, hi) = c.iter().fold((1.0f32, 0.0f32), |(lo, hi), v| (lo.min(*v), hi.max(*v)));
- assert!(lo >= 0.5 && hi < 0.6 && hi - lo < 0.03, "{lo}..{hi}");
+ let c = covered_values(&m, &out, BakedMap::Curvature);
+ assert!(c.iter().filter(|(p, _)| p.x.abs() < 0.9 && p.z.abs() < 0.9).all(|(_, v)| *v == 0.5));
+}
+
+#[test]
+fn contact_with_a_wall_is_a_dark_line_and_the_rest_stays_flat() {
+ let m = floor_and_wall(false);
+ let s = settings(128, &[BakedMap::Curvature]);
+ let line = floor_mean(&m, &s, BakedMap::Curvature, 0.96..1.0);
+ assert!(line < 0.47, "beside the wall {line}");
+ assert_eq!(floor_mean(&m, &s, BakedMap::Curvature, -0.9..0.5), 0.5);
+}
+
+fn smooth_shaded_box() -> Mesh {
+ let (mut pos, mut nrm, mut uvs, mut idx) = (Vec::new(), Vec::new(), Vec::new(), Vec::new());
+ let faces: [(Vec3, Vec3, Vec3); 6] = [
+ (Vec3::X, Vec3::Y, Vec3::Z),
+ (Vec3::NEG_X, Vec3::Z, Vec3::Y),
+ (Vec3::Y, Vec3::Z, Vec3::X),
+ (Vec3::NEG_Y, Vec3::X, Vec3::Z),
+ (Vec3::Z, Vec3::X, Vec3::Y),
+ (Vec3::NEG_Z, Vec3::Y, Vec3::X),
+ ];
+ for (f, (n, a, b)) in faces.iter().enumerate() {
+ let base = pos.len() as u32;
+ let cell = Vec2::new((f % 3) as f32 / 3.0, (f / 3) as f32 / 2.0);
+ for (u, v) in [(-1.0f32, -1.0f32), (1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)] {
+ let p = *n + *a * u + *b * v;
+ pos.push(p);
+ nrm.push(p.normalize());
+ uvs.push(cell + Vec2::new((u * 0.5 + 0.5) * 0.3 + 0.015, (v * 0.5 + 0.5) * 0.45 + 0.025));
+ }
+ idx.extend([base, base + 1, base + 2, base, base + 2, base + 3]);
+ }
+ Mesh::from_parts(pos, Some(nrm), uvs, idx, "Smooth box").unwrap()
+}
+
+fn edge_peak(m: &Mesh, res: u32, band: f32) -> f32 {
+ let c = covered_values(m, &run(m, &settings(res, &[BakedMap::Curvature])).unwrap(), BakedMap::Curvature);
+ c.iter().filter(|(p, _)| p.abs().to_array().iter().filter(|v| **v > 1.0 - band).count() >= 2).map(|(_, v)| (v - 0.5).abs()).fold(0.0, f32::max)
+}
+
+#[test]
+fn smooth_shaded_corners_draw_no_hard_line() {
+ let (hard, smooth) = (edge_peak(&primitives::cube(2.0), 256, 0.03), edge_peak(&smooth_shaded_box(), 256, 0.03));
+ assert!(hard > 0.05, "hard {hard}");
+ assert!(smooth < hard * 0.5, "smooth {smooth} hard {hard}");
+}
+
+#[test]
+fn lines_are_as_wide_in_texels_at_any_scale_of_the_part() {
+ let width = |res: u32| {
+ let m = primitives::cube(2.0);
+ let c = covered_values(&m, &run(&m, &settings(res, &[BakedMap::Curvature])).unwrap(), BakedMap::Curvature);
+ c.iter()
+ .filter(|(p, v)| (v - 0.5).abs() > 0.02 && p.abs().to_array().iter().filter(|a| **a > 0.999).count() == 1)
+ .map(|(p, _)| {
+ let mut a = p.abs().to_array();
+ a.sort_by(f32::total_cmp);
+ 1.0 - a[1]
+ })
+ .fold(0.0, f32::max)
+ };
+ let (coarse, fine) = (width(128), width(256));
+ assert!(fine > 0.0 && (fine / coarse - 0.5).abs() < 0.2, "world widths {coarse} and {fine}");
+}
+
+fn barrel(radius: f32) -> Mesh {
+ const N: u32 = 128;
+ let (mut pos, mut nrm, mut uvs, mut idx) = (Vec::new(), Vec::new(), Vec::new(), Vec::new());
+ for i in 0..=N {
+ let u = i as f32 / N as f32;
+ let (s, c) = (u * std::f32::consts::TAU).sin_cos();
+ for (y, v) in [(-1.0f32, 0.0f32), (1.0, 1.0)] {
+ pos.push(Vec3::new(c * radius, y, s * radius));
+ nrm.push(Vec3::new(c, 0.0, s));
+ uvs.push(Vec2::new(u, v));
+ }
+ }
+ for i in 0..N {
+ let b = i * 2;
+ idx.extend([b, b + 1, b + 2, b + 1, b + 3, b + 2]);
+ }
+ Mesh::from_parts(pos, Some(nrm), uvs, idx, "Barrel").unwrap()
+}
+
+#[test]
+fn a_gently_round_barrel_stays_below_the_wear_masks() {
+ let m = barrel(0.1);
+ let c = covered_values(&m, &run(&m, &settings(512, &[BakedMap::Curvature])).unwrap(), BakedMap::Curvature);
+ let (lo, hi) = c.iter().filter(|(p, _)| p.y.abs() < 0.9).fold((1.0f32, 0.0f32), |(lo, hi), (_, v)| (lo.min(*v), hi.max(*v)));
+ assert!(hi < 0.53 && hi - lo < 0.02, "{lo}..{hi}");
+}
+
+#[test]
+fn a_rounded_bevel_reads_the_same_at_any_map_size() {
+ let m = primitives::rounded_box(Vec3::ONE, 0.05);
+ let peak = |res: u32| {
+ let c = covered_values(&m, &run(&m, &settings(res, &[BakedMap::Curvature])).unwrap(), BakedMap::Curvature);
+ let mut v: Vec = c.iter().filter(|(p, _)| p.abs().to_array().iter().filter(|a| **a > 0.97).count() >= 2).map(|v| v.1).collect();
+ v.sort_by(f32::total_cmp);
+ v.get(v.len() / 2).copied().unwrap_or(0.5)
+ };
+ let (coarse, fine) = (peak(512), peak(1024));
+ assert!(coarse > 0.58, "bevel at 512: {coarse}");
+ assert!((coarse - fine).abs() < 0.1, "512: {coarse}, 1024: {fine}");
}
-/// Bevel / edge texels (two coordinates near the half extent) are convex-bright; face centres
-/// stay mid-grey.
fn check_box_curvature(m: &Mesh, edge: f32) {
- let s = BakeSettings { dilation: 4, ..settings(128, &[BakedMap::Curvature]) };
+ let s = {
+ let mut base = settings(128, &[BakedMap::Curvature]);
+ base.common = CommonBakeSettings { dilation: 4, ..base.common };
+ base
+ };
let c = covered_values(m, &run(m, &s).unwrap(), BakedMap::Curvature);
let near = |p: Vec3, t: f32| p.abs().to_array().iter().filter(|c| **c > t).count();
let edges: Vec = c.iter().filter(|(p, _)| near(*p, edge) >= 2).map(|v| v.1).collect();
@@ -116,13 +277,22 @@ fn cube_edges_are_convex() {
#[test]
fn two_runs_are_identical_and_sized() {
let m = primitives::material_ball();
- let s = with_rays(BakeSettings { antialiasing: 2, dilation: 2, maps: BakedMap::ALL.into_iter().collect(), ..settings(40, &[]) }, 8, 0.25);
+ let s = with_rays(
+ {
+ let mut base = settings(32, &[]);
+ base.common = CommonBakeSettings { antialiasing: BakeAntialiasing::Subsampling2x2, dilation: 2, ..base.common };
+ base.maps.select(BakedMap::ALL);
+ base
+ },
+ 8,
+ 0.25,
+ );
let a = run(&m, &s).unwrap();
let b = run(&m, &s).unwrap();
assert_eq!(a, b);
assert_eq!(a.maps.len(), BakedMap::ALL.len());
for (map, data) in &a.maps {
- assert_eq!(data.len(), 40 * 40 * map.components(), "{map:?}");
+ assert_eq!(data.len(), 32 * 32 * map.components(), "{map:?}");
assert!(data.iter().all(|v| v.is_finite() && (0.0..=1.0).contains(v)), "{map:?}");
}
}
@@ -131,11 +301,30 @@ fn two_runs_are_identical_and_sized() {
fn strips_match_a_single_pass() {
let m = primitives::material_ball();
let bvh = Bvh::new(&m);
- let s = with_rays(BakeSettings { antialiasing: 2, maps: BakedMap::ALL.into_iter().collect(), ..settings(64, &[]) }, 4, 0.25);
- let req = BakeRequest { mesh: &m, bvh: &bvh, material: 0, settings: &s, high: None, cage: None, skew: None, tiles: (1, 1) };
+ let s = with_rays(
+ {
+ let mut base = settings(64, &[]);
+ base.common = CommonBakeSettings { antialiasing: BakeAntialiasing::Subsampling2x2, ..base.common };
+ base.maps.select(BakedMap::ALL);
+ base
+ },
+ 4,
+ 0.25,
+ );
+ let req = BakeRequest {
+ low_base_color: &[],
+ mesh: &m,
+ bvh: &bvh,
+ material: 0,
+ settings: &s,
+ high: None,
+ cage: None,
+ skew: None,
+ cage_paint: None,
+ tiles: (1, 1),
+ };
let whole = bake(&req, &Progress::new()).unwrap();
- // 128 × 2 supersampled texels per strip = 1 output row: 64 strips.
- 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();
@@ -148,7 +337,18 @@ fn cancel_and_progress() {
let m = primitives::sphere(1.0, 16, 8);
let bvh = Bvh::new(&m);
let s = settings(16, &[BakedMap::AmbientOcclusion, BakedMap::Position]);
- let req = BakeRequest { mesh: &m, bvh: &bvh, material: 0, settings: &s, high: None, cage: None, skew: None, tiles: (1, 1) };
+ let req = BakeRequest {
+ low_base_color: &[],
+ mesh: &m,
+ bvh: &bvh,
+ material: 0,
+ settings: &s,
+ high: None,
+ cage: None,
+ skew: None,
+ cage_paint: None,
+ tiles: (1, 1),
+ };
let p = Progress::new();
p.cancel();
assert!(matches!(bake(&req, &p), Err(BakeError::Cancelled)));
@@ -158,29 +358,112 @@ fn cancel_and_progress() {
assert_eq!(p.fraction(), 1.0);
}
+#[test]
+fn a_curvature_bake_can_be_cancelled_midway_and_reports_progress() {
+ let m = primitives::rounded_box(Vec3::ONE, 0.15);
+ let bvh = Bvh::new(&m);
+ let s = settings(2048, &[BakedMap::Curvature]);
+ let req = BakeRequest {
+ low_base_color: &[],
+ mesh: &m,
+ bvh: &bvh,
+ material: 0,
+ settings: &s,
+ high: None,
+ cage: None,
+ skew: None,
+ cage_paint: None,
+ tiles: (1, 1),
+ };
+ let p = Progress::new();
+ std::thread::scope(|t| {
+ let baking = t.spawn(|| bake(&req, &p));
+ let start = std::time::Instant::now();
+ while p.done.load(Relaxed) == 0 {
+ assert!(!baking.is_finished() && start.elapsed().as_secs() < 120, "the bake ended or stalled before reporting progress");
+ std::thread::yield_now();
+ }
+ let partway = p.fraction();
+ p.cancel();
+ assert!(partway < 1.0, "{partway}");
+ assert!(matches!(baking.join().unwrap(), Err(BakeError::Cancelled)));
+ });
+}
+
+#[test]
+fn hostile_tile_dimensions_are_rejected() {
+ let mesh = quad();
+ let bvh = Bvh::new(&mesh);
+ let settings = settings(16, &[BakedMap::Position]);
+
+ for tiles in [(1 << 31, 1 << 31), (u32::MAX, u32::MAX), (MAX_TEXELS as u32, 1), (0, 1), (1, 0)] {
+ let request = BakeRequest {
+ low_base_color: &[],
+ mesh: &mesh,
+ bvh: &bvh,
+ material: 0,
+ settings: &settings,
+ high: None,
+ cage: None,
+ skew: None,
+ cage_paint: None,
+ tiles,
+ };
+
+ assert!(matches!(validate(&request), Err(BakeError::Invalid(_))), "{tiles:?}");
+ assert!(matches!(bake(&request, &Progress::new()), Err(BakeError::Invalid(_))), "{tiles:?}");
+ }
+}
+
#[test]
fn invalid_requests_are_errors() {
let m = quad();
- let ok = settings(8, &[BakedMap::AmbientOcclusion]);
+ let ok = settings(16, &[BakedMap::AmbientOcclusion]);
let bad = [
- BakeSettings { resolution: 0, ..ok.clone() },
- BakeSettings { resolution: 8193, ..ok.clone() },
- BakeSettings { antialiasing: 3, ..ok.clone() },
- BakeSettings { antialiasing: 0, ..ok.clone() },
- BakeSettings { ao: RaySettings { rays: 0, ..ok.ao }, ..ok.clone() },
- BakeSettings { ao: RaySettings { rays: MAX_RAYS + 1, ..ok.ao }, ..ok.clone() },
- BakeSettings { ao: RaySettings { max_distance: f32::NAN, ..ok.ao }, ..ok.clone() },
- BakeSettings { ao: RaySettings { max_distance: 0.0, ..ok.ao }, ..ok.clone() },
- BakeSettings { ao: RaySettings { spread: f32::INFINITY, ..ok.ao }, ..ok.clone() },
- BakeSettings { max_rear: -1.0, ..ok.clone() },
- BakeSettings { curvature_strength: f32::INFINITY, ..ok.clone() },
+ {
+ let mut base = ok.clone();
+ base.maps.ao.parameters = AmbientOcclusionSettings { rays: RaySettings { rays: 0, ..ok.maps.ao.parameters.rays }, ..base.maps.ao.parameters };
+ base
+ },
+ {
+ let mut base = ok.clone();
+ base.maps.ao.parameters =
+ AmbientOcclusionSettings { rays: RaySettings { rays: MAX_RAYS + 1, ..ok.maps.ao.parameters.rays }, ..base.maps.ao.parameters };
+ base
+ },
+ {
+ let mut base = ok.clone();
+ base.maps.ao.parameters =
+ AmbientOcclusionSettings { rays: RaySettings { max_distance: f32::NAN, ..ok.maps.ao.parameters.rays }, ..base.maps.ao.parameters };
+ base
+ },
+ {
+ let mut base = ok.clone();
+ base.maps.ao.parameters =
+ AmbientOcclusionSettings { rays: RaySettings { max_distance: 0.0, ..ok.maps.ao.parameters.rays }, ..base.maps.ao.parameters };
+ base
+ },
+ {
+ let mut base = ok.clone();
+ base.maps.ao.parameters =
+ AmbientOcclusionSettings { rays: RaySettings { spread: f32::INFINITY, ..ok.maps.ao.parameters.rays }, ..base.maps.ao.parameters };
+ base
+ },
+ {
+ let mut base = ok.clone();
+ base.cage = CageSettings { max_rear: -1.0, ..base.cage };
+ base
+ },
];
for s in &bad {
assert!(matches!(run(&m, s), Err(BakeError::Invalid(_))), "{s:?}");
}
let bvh = Bvh::new(&m);
let req = |mesh: &Mesh, material| {
- bake(&BakeRequest { mesh, bvh: &bvh, material, settings: &ok, high: None, cage: None, skew: None, tiles: (1, 1) }, &Progress::new())
+ bake(
+ &BakeRequest { low_base_color: &[], mesh, bvh: &bvh, material, settings: &ok, high: None, cage: None, skew: None, cage_paint: None, tiles: (1, 1) },
+ &Progress::new(),
+ )
};
assert!(matches!(req(&m, 1), Err(BakeError::Invalid(_))));
let mut broken = m.clone();
@@ -189,7 +472,6 @@ fn invalid_requests_are_errors() {
let mut nan = m.clone();
nan.positions[0].x = f32::NAN;
assert!(matches!(req(&nan, 0), Err(BakeError::Invalid(_))));
- // An empty mesh bakes to neutral values.
let empty = Mesh { materials: vec!["m".into()], ..Mesh::default() };
let out = req(&empty, 0).unwrap();
assert!(out.maps[&BakedMap::AmbientOcclusion].iter().all(|v| *v == 1.0));
@@ -197,13 +479,17 @@ fn invalid_requests_are_errors() {
#[test]
fn neutral_values_and_padding() {
- // The quad covers only the left half of UV space.
let mut m = quad();
for uv in &mut m.uvs {
uv.x *= 0.5;
}
let maps = [BakedMap::AmbientOcclusion, BakedMap::Curvature, BakedMap::Thickness, BakedMap::Normal, BakedMap::Position];
- let out = run(&m, &BakeSettings { dilation: 2, ..settings(16, &maps) }).unwrap();
+ let out = run(&m, &{
+ let mut base = settings(16, &maps);
+ base.common = CommonBakeSettings { dilation: 2, ..base.common };
+ base
+ })
+ .unwrap();
let pos = &out.maps[&BakedMap::Position];
let at = |x: usize, y: usize| &pos[(y * 16 + x) * 3..(y * 16 + x) * 3 + 3];
assert_eq!(at(9, 5)[0], at(7, 5)[0], "padded texel copies a texel of the last covered column");
@@ -228,13 +514,15 @@ fn normal_and_height_transfer_from_a_high_poly() {
let s = settings(16, &[BakedMap::Normal, BakedMap::Height]);
let out = bake(
&BakeRequest {
+ low_base_color: &[],
mesh: &low,
bvh: &lb,
material: 0,
settings: &s,
- high: Some(HighPoly { mesh: &high, bvh: &hb, base_color: &[] }),
+ high: Some(HighPoly { file_ids: &[], mesh: &high, bvh: &hb, base_color: &[] }),
cage: None,
skew: None,
+ cage_paint: None,
tiles: (1, 1),
},
&Progress::new(),
@@ -242,12 +530,10 @@ fn normal_and_height_transfer_from_a_high_poly() {
.unwrap();
let i = 8 * 16 + 8;
let n = &out.maps[&BakedMap::Normal][i * 3..i * 3 + 3];
- // Tangent = +X (u), bitangent = −Z (up the image), normal = +Y.
assert!((n[0] - (0.5 + 0.5 * tilt.x)).abs() < 1e-3 && (n[1] - 0.5).abs() < 1e-3 && (n[2] - (0.5 + 0.5 * tilt.y)).abs() < 1e-3, "{n:?}");
- let diag = 8.0f32.sqrt();
+ let diag = 2.0;
let expected = 0.5 + 0.005 / (0.02 * diag);
assert!((out.maps[&BakedMap::Height][i] - expected).abs() < 1e-3, "{}", out.maps[&BakedMap::Height][i]);
- // Without a high poly both maps are flat.
let flat = run(&low, &s).unwrap();
assert_eq!(&flat.maps[&BakedMap::Normal][i * 3..i * 3 + 3], [0.5, 0.5, 1.0]);
assert_eq!(flat.maps[&BakedMap::Height][i], 0.5);
@@ -255,28 +541,101 @@ fn normal_and_height_transfer_from_a_high_poly() {
fn transfer(low: &Mesh, high: &Mesh, cage: Option<&Mesh>, s: &BakeSettings) -> Result {
let (lb, hb) = (Bvh::new(low), Bvh::new(high));
+ let mut settings = s.clone();
+ if cage.is_some() {
+ settings.cage.kind = texturecraft_core::CageType::CustomFile;
+ }
bake(
&BakeRequest {
+ low_base_color: &[],
mesh: low,
bvh: &lb,
material: 0,
- settings: s,
- high: Some(HighPoly { mesh: high, bvh: &hb, base_color: &[] }),
+ settings: &settings,
+ high: Some(HighPoly { file_ids: &[], mesh: high, bvh: &hb, base_color: &[] }),
cage,
skew: None,
+ cage_paint: None,
tiles: (1, 1),
},
&Progress::new(),
)
}
-/// Texel (x, y) of a `res`² bake of [`quad`] sits over world (2u − 1, 0, 2v − 1).
+#[test]
+fn a_high_poly_box_has_bright_edges_and_flat_faces() {
+ let s = {
+ let mut base = settings(128, &[BakedMap::Curvature]);
+ base.cage = CageSettings { max_frontal: 0.06, max_rear: 0.02, ..base.cage };
+ base.common = CommonBakeSettings { dilation: 4, ..base.common };
+ base
+ };
+ for (m, edge) in [(primitives::cube(2.0), 0.97), (primitives::rounded_box(Vec3::ONE, 0.15), 0.9)] {
+ let c = covered_values(&m, &transfer(&m, &m, None, &s).unwrap(), BakedMap::Curvature);
+ let near = |p: Vec3, t: f32| p.abs().to_array().iter().filter(|c| **c > t).count();
+ let brightest = c.iter().filter(|(p, _)| near(*p, edge) >= 2).map(|v| v.1).fold(0.0, f32::max);
+ assert!(brightest > 0.55, "edge {brightest}");
+ assert!(c.iter().filter(|(p, _)| near(*p, 0.5) == 1).all(|v| (0.45..=0.55).contains(&v.1)), "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 = {
+ let mut base = settings(1024, &[BakedMap::Curvature]);
+ base.cage = CageSettings { max_frontal: 0.06, max_rear: 0.02, ..base.cage };
+ base.common = CommonBakeSettings { dilation: 4, ..base.common };
+ base
+ };
+ let brightest = |bevel: f32| {
+ let m = primitives::rounded_box(Vec3::ONE, bevel);
+ let c = covered_values(&m, &transfer(&m, &m, None, &s).unwrap(), BakedMap::Curvature);
+ let edge = 1.0 - bevel * 0.7;
+ c.iter().filter(|(p, _)| p.abs().to_array().iter().filter(|c| **c > edge).count() >= 2).map(|v| v.1).fold(0.0, f32::max)
+ };
+ let (narrow, wide) = (brightest(0.01), brightest(0.05));
+ assert!(narrow > 0.8, "narrow: {narrow}");
+ assert!(wide > 0.55, "wide: {wide}");
+}
+
+#[test]
+fn a_gently_round_high_poly_stays_below_the_wear_masks() {
+ let m = primitives::sphere(1.0, 96, 48);
+ let s = {
+ let mut base = settings(256, &[BakedMap::Curvature]);
+ base.cage = CageSettings { max_frontal: 0.06, max_rear: 0.02, ..base.cage };
+ base.common = CommonBakeSettings { dilation: 4, ..base.common };
+ base
+ };
+ let c = covered_values(&m, &transfer(&m, &m, None, &s).unwrap(), BakedMap::Curvature);
+ let over = c.iter().filter(|v| v.1 > 0.65).count() as f32 / c.len() as f32;
+ assert!(over < 0.01, "{over}");
+}
+
fn quad_texel(res: u32, x: f32, z: f32) -> usize {
let t = |c: f32| (((c + 1.0) * 0.5 * res as f32) as usize).min(res as usize - 1);
t(z) * res as usize + t(x)
}
-/// [`quad`]'s footprint with a smooth bump `h · exp(−r²/σ²)`.
fn bumped(h: f32, sigma: f32) -> Mesh {
let mut m = primitives::plane(2.0, 128);
for p in &mut m.positions {
@@ -290,17 +649,19 @@ fn bumped(h: f32, sigma: f32) -> Mesh {
#[test]
fn bump_tilts_the_baked_normal() {
let (h, sigma) = (0.1f32, 0.4f32);
- let s = BakeSettings { max_frontal: 0.06, max_rear: 0.02, ..settings(64, &[BakedMap::Normal, BakedMap::Height]) };
+ let s = {
+ let mut base = settings(64, &[BakedMap::Normal, BakedMap::Height]);
+ base.cage = CageSettings { max_frontal: 0.06, max_rear: 0.02, ..base.cage };
+ base
+ };
let out = transfer(&quad(), &bumped(h, sigma), None, &s).unwrap();
let normal = &out.maps[&BakedMap::Normal];
for (x, z) in [(0.3f32, 0.0f32), (-0.3, 0.0), (0.0, 0.3), (0.0, -0.3), (0.25, 0.25)] {
let i = quad_texel(64, x, z);
- // Analytic normal of the bump at the texel centre.
let (cx, cz) = (((i % 64) as f32 + 0.5) / 32.0 - 1.0, ((i / 64) as f32 + 0.5) / 32.0 - 1.0);
let f = h * (-(cx * cx + cz * cz) / (sigma * sigma)).exp();
let (dx, dz) = (-2.0 * cx / (sigma * sigma) * f, -2.0 * cz / (sigma * sigma) * f);
let n = Vec3::new(-dx, 1.0, -dz).normalize();
- // Tangent = +X, bitangent = −Z, normal = +Y.
let expected = [0.5 + 0.5 * n.x, 0.5 - 0.5 * n.z, 0.5 + 0.5 * n.y];
let got = &normal[i * 3..i * 3 + 3];
assert!(got.iter().zip(expected).all(|(g, e)| (g - e).abs() < 0.02), "at {x},{z}: {got:?} vs {expected:?}");
@@ -310,57 +671,8 @@ 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 = BakeSettings { max_frontal: 0.06, max_rear: 0.02, curvature_from_normal: true, ..settings(64, &[BakedMap::Curvature]) };
- 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)]);
-}
-
-/// Two unit boxes 0.2 apart: "A" (material 0, centre x = −0.6) and "B" (material 1, x = +0.6).
-fn two_boxes(suffix: &str, colors: Option<[Vec4; 2]>) -> Mesh {
- let part = |name: &str, x: f32, color: Option| {
- let mut b = primitives::cube(1.0);
- b.positions.iter_mut().for_each(|p| p.x += x);
- b.submeshes[0].name = format!("{name}{suffix}");
- b.colors = color.map(|c| vec![c; b.positions.len()]).unwrap_or_default();
- b
- };
- let mut m = part("A", -0.6, colors.map(|c| c[0]));
- m.append(&part("B", 0.6, colors.map(|c| c[1])));
- m
-}
-
-#[test]
-fn match_by_mesh_name_pairs_the_right_parts() {
- let (red, blue) = (Vec4::new(1.0, 0.0, 0.0, 1.0), Vec4::new(0.0, 0.0, 1.0, 1.0));
- let (low, high) = (two_boxes("_low", None), two_boxes("_HIGH", Some([red, blue])));
- // Rays start 1.3 in front of A's +X face: beyond B, so B's high poly is hit first unless
- // parts are matched by name.
- let s = BakeSettings { max_frontal: 0.5, ..settings(64, &[BakedMap::ColorMap]) };
- let face = |s: &BakeSettings| {
- let out = transfer(&low, &high, None, s).unwrap();
- covered_values(&low, &out, BakedMap::ColorMap)
- .into_iter()
- .filter(|(p, _)| p.x > -0.105 && p.y.abs() < 0.4 && p.z.abs() < 0.4)
- .map(|v| v.1)
- .collect::>()
- };
- let always = face(&s);
- assert!(!always.is_empty() && always.iter().all(|r| *r < 0.01), "always: B's (blue) high poly occludes A's face");
- let by_name = face(&BakeSettings { matching: BakeMatch::ByMeshName, ..s.clone() });
- assert!(by_name.iter().all(|r| *r > 0.99), "by name: A's face gets A's red");
- // Parts without a counterpart get nothing.
- let lonely = BakeSettings { matching: BakeMatch::ByMeshName, low_suffix: "_none".into(), ..s };
- assert!(face(&lonely).iter().all(|r| *r == 0.0));
-}
-
#[test]
fn bent_normals_point_away_from_occluders() {
- // A floor (material 0) with a wall standing at x = +1, facing −X (material 1).
let mut m = quad();
let wall = Mesh::from_parts(
vec![Vec3::new(1.0, 0.0, -1.0), Vec3::new(1.0, 0.0, 1.0), Vec3::new(1.0, 2.0, 1.0), Vec3::new(1.0, 2.0, -1.0)],
@@ -387,20 +699,17 @@ fn bent_normals_point_away_from_occluders() {
}
#[test]
-fn opacity_and_color_transfer_where_the_high_poly_is() {
- // The high poly covers x < 0 only, colored green.
+fn opacity_transfers_where_the_high_poly_is() {
let mut high = quad();
high.positions.iter_mut().for_each(|p| p.x = p.x.min(0.0));
high.colors = vec![Vec4::new(0.0, 1.0, 0.0, 0.5); 4];
- let out = transfer(&quad(), &high, None, &settings(32, &[BakedMap::Opacity, BakedMap::ColorMap])).unwrap();
- let (op, col) = (&out.maps[&BakedMap::Opacity], &out.maps[&BakedMap::ColorMap]);
+ let out = transfer(&quad(), &high, None, &settings(32, &[BakedMap::Opacity])).unwrap();
+ let opacity = &out.maps[&BakedMap::Opacity];
let (left, right) = (quad_texel(32, -0.5, 0.0), quad_texel(32, 0.5, 0.0));
- assert_eq!((op[left], op[right]), (0.5, 0.0), "vertex alpha where covered, 0 where missed");
- assert_eq!(&col[left * 3..left * 3 + 3], [0.0, 1.0, 0.0]);
- assert_eq!(&col[right * 3..right * 3 + 3], BakedMap::ColorMap.neutral());
- // Without a high poly the low poly covers itself (white, opaque).
- let own = run(&quad(), &settings(32, &[BakedMap::Opacity, BakedMap::ColorMap])).unwrap();
- assert_eq!((own.maps[&BakedMap::Opacity][right], own.maps[&BakedMap::ColorMap][right * 3]), (1.0, 1.0));
+ assert_eq!((opacity[left], opacity[right]), (0.5, 0.0), "vertex alpha where covered, 0 where missed");
+
+ let low_poly_bake = run(&quad(), &settings(32, &[BakedMap::Opacity])).unwrap();
+ assert_eq!(low_poly_bake.maps[&BakedMap::Opacity][right], 1.0);
}
#[test]
@@ -408,66 +717,111 @@ fn ray_distances_and_the_cage_limit_hits() {
let low = quad();
let mut high = quad();
high.positions.iter_mut().for_each(|p| p.y += 0.2);
- let diag = 8.0f32.sqrt();
+ let diag = 2.0;
let opacity = |s: &BakeSettings, cage: Option<&Mesh>| transfer(&low, &high, cage, s).map(|o| o.maps[&BakedMap::Opacity][quad_texel(16, 0.0, 0.0)]);
let near = settings(16, &[BakedMap::Opacity]);
assert_eq!(opacity(&near, None).unwrap(), 0.0, "0.2 above is beyond the default frontal distance");
- assert_eq!(opacity(&BakeSettings { max_frontal: 0.25 / diag, ..near.clone() }, None).unwrap(), 1.0);
- // The rear distance only reaches below the surface.
+ assert_eq!(
+ opacity(
+ &{
+ let mut base = near.clone();
+ base.cage = CageSettings { max_frontal: 0.25 / diag, ..base.cage };
+ base
+ },
+ None
+ )
+ .unwrap(),
+ 1.0
+ );
let mut below = high.clone();
below.positions.iter_mut().for_each(|p| p.y -= 0.4);
- let rear = |r: f32| transfer(&low, &below, None, &BakeSettings { max_rear: r, ..near.clone() }).unwrap().maps[&BakedMap::Opacity][quad_texel(16, 0.0, 0.0)];
+ let rear = |r: f32| {
+ transfer(&low, &below, None, &{
+ let mut base = near.clone();
+ base.cage = CageSettings { max_rear: r, ..base.cage };
+ base
+ })
+ .unwrap()
+ .maps[&BakedMap::Opacity][quad_texel(16, 0.0, 0.0)]
+ };
assert_eq!((rear(0.1 / diag), rear(0.25 / diag)), (0.0, 1.0));
- // A cage 0.3 above the low poly starts the rays above the high poly.
let mut cage = low.clone();
cage.positions.iter_mut().for_each(|p| p.y += 0.3);
assert_eq!(opacity(&near, Some(&cage)).unwrap(), 1.0);
- // A cage 0.1 above starts below it.
cage.positions.iter_mut().for_each(|p| p.y -= 0.2);
assert_eq!(opacity(&near, Some(&cage)).unwrap(), 0.0);
- // The cage must have the low poly's triangles.
assert!(matches!(opacity(&near, Some(&primitives::cube(1.0))), Err(BakeError::Invalid(_))));
}
-#[test]
-fn world_space_direction_is_a_facing_ratio() {
- let m = quad();
- let at =
- |d: [f32; 3]| run(&m, &BakeSettings { direction: d, ..settings(8, &[BakedMap::WorldDirection]) }).map(|o| o.maps[&BakedMap::WorldDirection][4 * 8 + 4]);
- assert_eq!(at([0.0, 2.0, 0.0]).unwrap(), 1.0);
- assert_eq!(at([1.0, 0.0, 0.0]).unwrap(), 0.5);
- assert_eq!(at([0.0, -1.0, 0.0]).unwrap(), 0.0);
- assert!(matches!(at([0.0; 3]), Err(BakeError::Invalid(_))));
-}
-
-/// `cargo test -p texturecraft-bake --release -- --ignored --nocapture bench`
#[test]
#[ignore]
fn bench_material_ball_2k() {
let m = primitives::material_ball();
let bvh = Bvh::new(&m);
- let all = with_rays(BakeSettings { resolution: 2048, ..BakeSettings::default() }, 64, 0.25);
- for maps in
- [vec![BakedMap::Position], vec![BakedMap::AmbientOcclusion], vec![BakedMap::Thickness], vec![BakedMap::Curvature], all.maps.iter().copied().collect()]
+ let all = with_rays(
+ {
+ let mut base = BakeSettings::default();
+ base.common = CommonBakeSettings { resolution: BakeResolution::R2048, ..base.common };
+ base
+ },
+ 64,
+ 0.25,
+ );
+ for maps in [vec![BakedMap::Position], vec![BakedMap::AmbientOcclusion], vec![BakedMap::Thickness], vec![BakedMap::Curvature], all.maps.enabled().collect()]
{
- let s = BakeSettings { maps: maps.into_iter().collect(), ..all.clone() };
+ let s = {
+ let mut base = all.clone();
+ base.maps.select(maps);
+ base
+ };
let t = std::time::Instant::now();
- let out =
- bake(&BakeRequest { mesh: &m, bvh: &bvh, material: 0, settings: &s, high: None, cage: None, skew: None, tiles: (1, 1) }, &Progress::new()).unwrap();
- println!("material ball, material 0, {}² × {:?}, {} rays: {:.2?}", out.resolution, out.maps.keys(), s.ao.rays, t.elapsed());
+ let out = bake(
+ &BakeRequest {
+ low_base_color: &[],
+ mesh: &m,
+ bvh: &bvh,
+ material: 0,
+ settings: &s,
+ high: None,
+ cage: None,
+ skew: None,
+ cage_paint: None,
+ tiles: (1, 1),
+ },
+ &Progress::new(),
+ )
+ .unwrap();
+ println!("material ball, material 0, {}² × {:?}, {} rays: {:.2?}", out.resolution, out.maps.keys(), s.maps.ao.parameters.rays.rays, t.elapsed());
}
}
#[test]
fn uv_tiles_bake_side_by_side_in_one_atlas() {
- // Tiles 1001 (x < 0) and 1002 (x > 0) of the UDIM plane, in atlas UVs.
let mut m = primitives::udim_plane();
let grid = texturecraft_core::TileGrid::of(&[1001, 1002]).unwrap();
m.map_material_uvs(0, |uv| Vec2::from(grid.to_atlas(uv.to_array())));
- let s = BakeSettings { dilation: 4, ..settings(32, &[BakedMap::Position]) };
+ let s = {
+ let mut base = settings(32, &[BakedMap::Position]);
+ base.common = CommonBakeSettings { dilation: 4, ..base.common };
+ base
+ };
let bvh = Bvh::new(&m);
- let out =
- bake(&BakeRequest { mesh: &m, bvh: &bvh, material: 0, settings: &s, high: None, cage: None, skew: None, tiles: (2, 1) }, &Progress::new()).unwrap();
+ let out = bake(
+ &BakeRequest {
+ low_base_color: &[],
+ mesh: &m,
+ bvh: &bvh,
+ material: 0,
+ settings: &s,
+ high: None,
+ cage: None,
+ skew: None,
+ cage_paint: None,
+ tiles: (2, 1),
+ },
+ &Progress::new(),
+ )
+ .unwrap();
assert_eq!((out.resolution, out.height), (64, 32));
let pos = &out.maps[&BakedMap::Position];
assert_eq!(pos.len(), 64 * 32 * 3);
@@ -476,12 +830,45 @@ fn uv_tiles_bake_side_by_side_in_one_atlas() {
assert!(x_at(2, y) < 0.3 && x_at(29, y) < 0.5, "tile 1001 holds the left plane");
assert!(x_at(34, y) > 0.5 && x_at(62, y) > 0.7, "tile 1002 holds the right plane");
}
- let too_many = BakeRequest { mesh: &m, bvh: &bvh, material: 0, settings: &s, high: None, cage: None, skew: None, tiles: (0, 1) };
+ let too_many = BakeRequest {
+ low_base_color: &[],
+ mesh: &m,
+ bvh: &bvh,
+ material: 0,
+ settings: &s,
+ high: None,
+ cage: None,
+ skew: None,
+ cage_paint: None,
+ tiles: (0, 1),
+ };
assert!(bake(&too_many, &Progress::new()).is_err());
}
-/// A floor ([`quad`], part "Quad") with a wall (part "Wall") standing at x = +1, facing the
-/// floor (−X) or, when `away`, away from it (+X); winding and normals agree.
+#[test]
+fn curvature_on_uv_tiles_matches_a_single_tile() {
+ let one = primitives::rounded_box(Vec3::ONE, 0.15);
+ let mut two = one.clone();
+ two.uvs.iter_mut().for_each(|uv| uv.x *= 0.5);
+ let s = {
+ let mut base = settings(64, &[BakedMap::Curvature]);
+ base.common = CommonBakeSettings { dilation: 0, ..base.common };
+ base
+ };
+ let bake_tiles = |m: &Mesh, tiles| {
+ let bvh = Bvh::new(m);
+ bake(
+ &BakeRequest { low_base_color: &[], mesh: m, bvh: &bvh, material: 0, settings: &s, high: None, cage: None, skew: None, cage_paint: None, tiles },
+ &Progress::new(),
+ )
+ .unwrap()
+ };
+ let (a, b) = (bake_tiles(&one, (1, 1)), bake_tiles(&two, (2, 1)));
+ let (a, b) = (&a.maps[&BakedMap::Curvature], &b.maps[&BakedMap::Curvature]);
+ let worst = (0..64 * 64).map(|i| (a[i] - b[(i / 64) * 128 + i % 64]).abs()).fold(0.0, f32::max);
+ assert!(worst < 1e-3, "{worst}");
+}
+
fn floor_and_wall(away: bool) -> Mesh {
let mut m = quad();
let (n, indices) = if away { (Vec3::X, vec![0, 2, 1, 0, 3, 2]) } else { (-Vec3::X, vec![0, 1, 2, 0, 2, 3]) };
@@ -497,45 +884,116 @@ fn floor_and_wall(away: bool) -> Mesh {
m
}
-/// Mean of `map` (first component) over the floor where `x` is in `range` (the wall is at 1).
fn floor_mean(m: &Mesh, s: &BakeSettings, map: BakedMap, range: std::ops::Range) -> f32 {
let out = run(m, s).unwrap();
mean(covered_values(m, &out, map).into_iter().filter(|(p, _)| range.contains(&p.x)).map(|v| v.1))
}
-/// [`floor_mean`] next to the wall.
fn near_wall(m: &Mesh, s: &BakeSettings, map: BakedMap) -> f32 {
floor_mean(m, s, map, 0.6..1.0)
}
#[test]
fn ambient_occlusion_settings_shape_the_occlusion() {
- let m = floor_and_wall(false);
- let base = with_rays(settings(32, &[BakedMap::AmbientOcclusion]), 64, 2.0);
- let ao = |f: &dyn Fn(&mut BakeSettings)| {
- let mut s = base.clone();
- f(&mut s);
- near_wall(&m, &s, BakedMap::AmbientOcclusion)
+ let mesh = floor_and_wall(false);
+ let mut base = with_rays(settings(32, &[BakedMap::AmbientOcclusion]), 64, 2.0);
+ base.maps.ao.parameters.rays.relative_to_bounding_box = false;
+ base.maps.ao.parameters.rays.max_distance = (mesh.bounds().1 - mesh.bounds().0).length() * 2.0;
+ let ao = |configure: &dyn Fn(&mut BakeSettings)| {
+ let mut bake_settings = base.clone();
+ configure(&mut bake_settings);
+ near_wall(&mesh, &bake_settings, BakedMap::AmbientOcclusion)
};
let wide = ao(&|_| {});
assert!(wide < 0.85, "the wall occludes the floor beside it: {wide}");
- // A wider spread gathers occlusion from farther away: the wall darkens a wider, softer band.
- let far = |spread: f32| floor_mean(&m, &BakeSettings { ao: RaySettings { spread, ..base.ao }, ..base.clone() }, BakedMap::AmbientOcclusion, -1.0..-0.2);
+
+ let far = |spread: f32| {
+ floor_mean(
+ &mesh,
+ &{
+ let mut base = base.clone();
+ base.maps.ao.parameters = AmbientOcclusionSettings { rays: RaySettings { spread, ..base.maps.ao.parameters.rays }, ..base.maps.ao.parameters };
+ base
+ },
+ BakedMap::AmbientOcclusion,
+ -1.0..-0.2,
+ )
+ };
let (narrow, wide_far) = (far(60.0), far(180.0));
assert!(narrow > 0.99 && wide_far < narrow - 0.05, "far from the wall: spread 60° {narrow}, 180° {wide_far}");
- // Uniform rays graze the floor more often than cosine-weighted ones: they reach the wall
- // from farther away.
- let uniform = BakeSettings { ao: RaySettings { distribution: RayDistribution::Uniform, ..base.ao }, ..base.clone() };
- let uniform_far = floor_mean(&m, &uniform, BakedMap::AmbientOcclusion, -1.0..-0.2);
+
+ let uniform = {
+ let mut base = base.clone();
+ base.maps.ao.parameters = AmbientOcclusionSettings {
+ rays: RaySettings { distribution: RayDistribution::Uniform, ..base.maps.ao.parameters.rays },
+ ..base.maps.ao.parameters
+ };
+ base
+ };
+ let uniform_far = floor_mean(&mesh, &uniform, BakedMap::AmbientOcclusion, -1.0..-0.2);
assert!(uniform_far < wide_far - 0.02, "far from the wall: uniform {uniform_far}, cosine {wide_far}");
- // Parts only occlude themselves when matched by name: the wall is another part.
- let own = ao(&|s| s.ao_self_occlusion = SelfOcclusion::SameMeshName);
+
+ let own = ao(&|bake_settings| bake_settings.maps.ao.parameters.self_occlusion = SelfOcclusion::SameMeshName);
assert!(own > 0.999, "{own}");
- // Back faces are ignored on request: a wall turned away no longer occludes.
- let back =
- |away: bool, ignore: bool| near_wall(&floor_and_wall(away), &BakeSettings { ao_ignore_backface: ignore, ..base.clone() }, BakedMap::AmbientOcclusion);
- assert!((back(true, false) - wide).abs() < 1e-6, "without the option a wall occludes from either side");
- assert!(back(true, true) > 0.999 && (back(false, true) - wide).abs() < 1e-6);
+
+ let back = |away: bool, ignore: BackfaceMode| {
+ near_wall(
+ &floor_and_wall(away),
+ &{
+ let mut base = base.clone();
+ base.maps.ao.parameters = AmbientOcclusionSettings { ignore_backface: ignore, ..base.maps.ao.parameters };
+ base
+ },
+ BakedMap::AmbientOcclusion,
+ )
+ };
+ assert!((back(true, BackfaceMode::Never) - wide).abs() < 1e-6, "without the option a wall occludes from either side");
+ assert!(back(true, BackfaceMode::Always) > 0.999 && (back(false, BackfaceMode::Always) - wide).abs() < 1e-6);
+}
+
+#[test]
+fn occlusion_falls_off_linearly_to_the_max_distance() {
+ let ceiling_height = 0.5;
+ let corners = |height: f32| [Vec3::new(-1.0, height, -1.0), Vec3::new(1.0, height, -1.0), Vec3::new(1.0, height, 1.0), Vec3::new(-1.0, height, 1.0)];
+ let mut uvs = vec![Vec2::new(0.0, 0.0), Vec2::new(1.0, 0.0), Vec2::new(1.0, 1.0), Vec2::new(0.0, 1.0)];
+ // The ceiling occludes the floor without contributing baked texels
+ uvs.extend([Vec2::ZERO; 4]);
+ let normals = [[Vec3::Y; 4], [Vec3::NEG_Y; 4]].concat();
+ let mesh = Mesh::from_parts(
+ corners(0.0).into_iter().chain(corners(ceiling_height)).collect(),
+ Some(normals),
+ uvs,
+ vec![0, 2, 1, 0, 3, 2, 4, 5, 6, 4, 6, 7],
+ "Room",
+ )
+ .unwrap();
+
+ // Nearly vertical rays meet the ceiling at half their maximum distance
+ let mut parameters = settings(16, &[BakedMap::AmbientOcclusion]);
+ parameters.maps.ao.parameters.rays =
+ RaySettings { max_distance: 2.0 * ceiling_height, relative_to_bounding_box: false, spread: 2.0, ..parameters.maps.ao.parameters.rays };
+ let output = run(&mesh, ¶meters).unwrap();
+ let ambient_occlusion = mean(covered_values(&mesh, &output, BakedMap::AmbientOcclusion).into_iter().map(|(_, value)| value));
+
+ assert!((ambient_occlusion - 0.5).abs() < 0.01, "{ambient_occlusion}");
+}
+
+#[test]
+fn secondary_ray_defaults_preserve_per_map_distances() {
+ let parameters = BakeSettings::default();
+ let expected_rays = RaySettings {
+ rays: 64,
+ min_distance: 0.00001,
+ max_distance: 1.0,
+ relative_to_bounding_box: true,
+ spread: 180.0,
+ distribution: RayDistribution::Cosine,
+ };
+
+ assert_eq!(parameters.maps.ao.parameters.rays, expected_rays);
+ assert_eq!(parameters.maps.ao.parameters.attenuation, texturecraft_core::AmbientOcclusionAttenuation::Linear);
+ assert_eq!(parameters.maps.bent_normal.parameters.rays, expected_rays);
+ assert_eq!(parameters.maps.thickness.parameters.rays, RaySettings { max_distance: 0.1, ..expected_rays });
}
#[test]
@@ -544,16 +1002,18 @@ fn bent_normals_and_thickness_have_their_own_rays() {
let s = with_rays(settings(32, &[BakedMap::BentNormal, BakedMap::AmbientOcclusion]), 64, 2.0);
let lean = |s: &BakeSettings| near_wall(&m, s, BakedMap::BentNormal) * 2.0 - 1.0;
assert!(lean(&s) < -0.15, "{}", lean(&s));
- // Bent-normal rays shorter than the gap to the wall see nothing; the AO keeps its own rays.
- let short = BakeSettings { bent_normal: RaySettings { max_distance: 0.05, rays: 16, ..s.bent_normal }, ..s.clone() };
+ let short = {
+ let mut base = s.clone();
+ base.maps.bent_normal.parameters =
+ BentNormalSettings { rays: RaySettings { max_distance: 0.05, rays: 16, ..s.maps.bent_normal.parameters.rays }, ..base.maps.bent_normal.parameters };
+ base
+ };
assert!(lean(&short) > 0.5 * lean(&s), "{} vs {}", lean(&short), lean(&s));
assert_eq!(near_wall(&m, &short, BakedMap::AmbientOcclusion), near_wall(&m, &s, BakedMap::AmbientOcclusion));
- // Thickness of the slab's top and bottom: a wider spread sends rays through it at grazing
- // angles (longer paths).
let slab = primitives::rounded_box(Vec3::new(1.0, 0.05, 1.0), 0.0);
let thick = |spread: f32| {
- let mut s = settings(48, &[BakedMap::Thickness]);
- s.thickness.spread = spread;
+ let mut s = settings(64, &[BakedMap::Thickness]);
+ s.maps.thickness.parameters.rays.spread = spread;
mean(
covered_values(&slab, &run(&slab, &s).unwrap(), BakedMap::Thickness)
.into_iter()
@@ -566,83 +1026,78 @@ fn bent_normals_and_thickness_have_their_own_rays() {
}
#[test]
-fn position_and_direction_modes() {
- let m = quad();
- let pos = |mode: PositionMode| {
- let out = run(&m, &BakeSettings { position_mode: mode, ..settings(16, &[BakedMap::Position]) }).unwrap();
- let g = UvGBuffer::new(&m, 0, 16, 16);
- (0..256).filter(|i| g.surface(&m, *i).is_some()).map(|i| [0, 1, 2].map(|k| out.maps[&BakedMap::Position][i * 3 + k])).collect::>()
+fn position_modes() {
+ let mesh = quad();
+ let positions = |mode: PositionMode| {
+ let out = run(&mesh, &{
+ let mut base = settings(16, &[BakedMap::Position]);
+ base.maps.position.parameters = PositionSettings { normalization: mode, ..base.maps.position.parameters };
+ base
+ })
+ .unwrap();
+ let gbuffer = UvGBuffer::new(&mesh, 0, 16, 16);
+ (0..256).filter(|i| gbuffer.surface(&mesh, *i).is_some()).map(|i| [0, 1, 2].map(|k| out.maps[&BakedMap::Position][i * 3 + k])).collect::>()
};
- // The flat quad: the box squashes y to 0 and stretches x, z over 0..1; the sphere keeps
- // proportions around the centre (half diagonal √2 of 2√2 per unit).
- let (bbox, sphere) = (pos(PositionMode::BoundingBox), pos(PositionMode::BoundingSphere));
- assert!(bbox.iter().all(|p| p[1] == 0.0) && bbox.iter().any(|p| p[0] < 0.05) && bbox.iter().any(|p| p[0] > 0.95));
- let r = 0.5 / 8.0f32.sqrt();
- assert!(sphere.iter().all(|p| p[1] == 0.5 && (p[0] - 0.5).abs() <= 2.0 * r + 1e-4 && (p[2] - 0.5).abs() <= 2.0 * r + 1e-4));
- let dir = |d: [f32; 3], mode| {
- run(&m, &BakeSettings { direction: d, direction_mode: mode, ..settings(8, &[BakedMap::WorldDirection]) }).unwrap().maps[&BakedMap::WorldDirection]
- [4 * 8 + 4]
+
+ let (box_positions, sphere_positions) = (positions(PositionMode::BoundingBox), positions(PositionMode::BoundingSphere));
+ assert!(box_positions.iter().all(|p| p[1] == 0.0) && box_positions.iter().any(|p| p[0] < 0.05) && box_positions.iter().any(|p| p[0] > 0.95));
+ let unit_scale = 0.25;
+ assert!(sphere_positions.iter().all(|p| p[1] == 0.5 && (p[0] - 0.5).abs() <= 2.0 * unit_scale + 1e-4 && (p[2] - 0.5).abs() <= 2.0 * unit_scale + 1e-4));
+
+ let raw_settings = {
+ let mut base = settings(16, &[BakedMap::Position]);
+ base.maps.position.parameters = PositionSettings { normalization: PositionMode::None, ..base.maps.position.parameters };
+ base
};
- assert_eq!(
- (dir([1.0, 0.0, 0.0], DirectionMode::Positive), dir([0.0, -1.0, 0.0], DirectionMode::Positive), dir([0.0, 1.0, 0.0], DirectionMode::Positive)),
- (0.0, 0.0, 1.0)
- );
- assert_eq!(dir([1.0, 0.0, 0.0], DirectionMode::Signed), 0.5);
+ let raw = run(&mesh, &raw_settings).unwrap();
+ let gbuffer = UvGBuffer::new(&mesh, 0, 16, 16);
+ for texel in 0..16 * 16 {
+ let Some(surface) = gbuffer.surface(&mesh, texel) else { continue };
+
+ let actual = &raw.maps[&BakedMap::Position][texel * 3..texel * 3 + 3];
+ assert!(actual.iter().zip(surface.pos.to_array()).all(|(actual, expected)| (actual - expected).abs() < 1e-6));
+ }
}
#[test]
-fn curvature_radius_widens_the_normal_map_sampling() {
- let at_top = |radius: u32| {
- let s =
- BakeSettings { max_frontal: 0.06, max_rear: 0.02, curvature_from_normal: true, curvature_radius: radius, ..settings(64, &[BakedMap::Curvature]) };
- transfer(&quad(), &bumped(0.1, 0.4), None, &s).unwrap().maps[&BakedMap::Curvature][quad_texel(64, 0.0, 0.0)]
- };
- let (one, four) = (at_top(1), at_top(4));
- assert!(one > 0.5 && four > one + 0.02, "radius 1: {one}, radius 4: {four}");
-}
-
-#[test]
-fn color_map_samples_the_high_poly_base_color_texture() {
+fn opacity_samples_the_high_poly_base_color_texture() {
let low = quad();
let mut high = quad();
high.positions.iter_mut().for_each(|p| p.y += 0.005);
- // Four texels across u: red, red, blue (half transparent), blue; a second material tinted
- // by its factor only.
+
let red = [255, 0, 0, 255];
let blue = [0, 0, 255, 128];
- let tex = BaseColor { factor: Vec4::ONE, width: 4, height: 1, texels: vec![red, red, blue, blue] };
- let hb = Bvh::new(&high);
- let lb = Bvh::new(&low);
- let s = settings(32, &[BakedMap::ColorMap, BakedMap::Opacity]);
- let bake_with = |c: BaseColor| {
- let base_color = [Some(Arc::new(c))];
- let req = BakeRequest {
+ let texture = BaseColor { factor: Vec4::ONE, width: 4, height: 1, texels: vec![red, red, blue, blue] };
+ let high_bvh = Bvh::new(&high);
+ let low_bvh = Bvh::new(&low);
+ let bake_settings = settings(32, &[BakedMap::Opacity]);
+ let bake_with = |base_color: BaseColor| {
+ let base_color = [Some(Arc::new(base_color))];
+ let request = BakeRequest {
+ low_base_color: &[],
mesh: &low,
- bvh: &lb,
+ bvh: &low_bvh,
material: 0,
- settings: &s,
- high: Some(HighPoly { mesh: &high, bvh: &hb, base_color: &base_color }),
+ settings: &bake_settings,
+ high: Some(HighPoly { file_ids: &[], mesh: &high, bvh: &high_bvh, base_color: &base_color }),
cage: None,
skew: None,
+ cage_paint: None,
tiles: (1, 1),
};
- bake(&req, &Progress::new()).unwrap()
+ bake(&request, &Progress::new()).unwrap()
};
- let out = bake_with(tex);
- // Row 16 (v ≈ 0.5); columns 8 and 24 sit inside the red and blue halves (u ≈ 0.27, 0.77).
+
+ let out = bake_with(texture);
+
let (left, right) = (16 * 32 + 8, 16 * 32 + 24);
- let (color, opacity) = (&out.maps[&BakedMap::ColorMap], &out.maps[&BakedMap::Opacity]);
- let near = |a: &[f32], b: [f32; 3]| a.iter().zip(b).all(|(a, b)| (a - b).abs() < 1e-3);
- assert!(near(&color[left * 3..left * 3 + 3], [1.0, 0.0, 0.0]), "{:?}", &color[left * 3..left * 3 + 3]);
- assert!(near(&color[right * 3..right * 3 + 3], [0.0, 0.0, 1.0]), "{:?}", &color[right * 3..right * 3 + 3]);
+ let opacity = &out.maps[&BakedMap::Opacity];
assert!((opacity[left] - 1.0).abs() < 1e-6 && (opacity[right] - 128.0 / 255.0).abs() < 1e-3);
- // A factor alone tints in linear light; the map holds display-encoded color like a texture.
- let half = bake_with(BaseColor { factor: Vec4::new(0.5, 1.0, 1.0, 1.0), width: 0, height: 0, texels: Vec::new() });
- let r = half.maps[&BakedMap::ColorMap][left * 3];
- assert!((r - texturecraft_texel::linear_to_srgb(0.5)).abs() < 1e-4, "{r}");
+
+ let half = bake_with(BaseColor { factor: Vec4::new(1.0, 1.0, 1.0, 0.5), width: 0, height: 0, texels: Vec::new() });
+ assert_eq!(half.maps[&BakedMap::Opacity][left], 0.5);
}
-/// A tracer that never works (no GPU).
struct Broken;
impl Tracer for Broken {
@@ -650,7 +1105,7 @@ impl Tracer for Broken {
"Broken".into()
}
- fn scene<'a>(&'a self, _: &[rays::TraceMesh<'a>]) -> Result, BakeError> {
+ fn scene<'a>(&'a self, _: &[tracing::TraceMesh<'a>]) -> Result, BakeError> {
Err(BakeError::Tracer("no device".into()))
}
}
@@ -660,16 +1115,29 @@ fn a_failing_tracer_falls_back_to_the_cpu() {
let m = floor_and_wall(false);
let bvh = Bvh::new(&m);
let s = with_rays(settings(16, &[BakedMap::AmbientOcclusion, BakedMap::Thickness]), 8, 1.0);
- let req = BakeRequest { mesh: &m, bvh: &bvh, material: 0, settings: &s, high: None, cage: None, skew: None, tiles: (1, 1) };
+ let req = BakeRequest {
+ low_base_color: &[],
+ mesh: &m,
+ bvh: &bvh,
+ material: 0,
+ settings: &s,
+ high: None,
+ cage: None,
+ skew: None,
+ cage_paint: None,
+ tiles: (1, 1),
+ };
let out = bake_on(&req, &Progress::new(), &Broken).unwrap();
assert_eq!(out.tracer, "CPU (Broken unavailable: no device)");
assert_eq!(out.maps, bake(&req, &Progress::new()).unwrap().maps);
- // Bakes without rays never ask the tracer.
- let flat = BakeSettings { maps: [BakedMap::Position].into_iter().collect(), ..s.clone() };
- assert_eq!(bake_on(&BakeRequest { settings: &flat, ..req }, &Progress::new(), &Broken).unwrap().tracer, "CPU");
+ let flat = {
+ let mut base = s.clone();
+ base.maps.select([BakedMap::Position]);
+ base
+ };
+ assert_eq!(bake_on(&BakeRequest { low_base_color: &[], settings: &flat, ..req }, &Progress::new(), &Broken).unwrap().tracer, "CPU");
}
-/// A flat quad of half-size `half` at height `y`, every vertex normal `n`.
fn plane(y: f32, half: f32, n: Vec3) -> Mesh {
Mesh::from_parts(
vec![Vec3::new(-half, y, -half), Vec3::new(half, y, -half), Vec3::new(half, y, half), Vec3::new(-half, y, half)],
@@ -682,41 +1150,49 @@ fn plane(y: f32, half: f32, n: Vec3) -> Mesh {
}
#[test]
-fn skew_correction_turns_transfer_rays_from_the_averaged_direction_to_the_base_normal() {
- // A flat low poly whose smooth normals lean (0.6, 0.8, 0); the high poly is a plane 0.3 above it.
+fn skew_correction_preserves_uniform_mesh_normals_and_rejects_invalid_values() {
let lean = Vec3::new(0.6, 0.8, 0.0);
let (low, high) = (plane(0.0, 1.0, lean), plane(0.3, 4.0, Vec3::Y));
let (lb, hb) = (Bvh::new(&low), Bvh::new(&high));
- let s = BakeSettings { max_frontal: 0.5, max_rear: 0.1, average_normals: true, ..settings(16, &[BakedMap::Height]) };
- let diag = (low.bounds().1 - low.bounds().0).length();
+ let s = {
+ let mut base = settings(16, &[BakedMap::Height]);
+ base.cage = CageSettings { max_frontal: 0.5, max_rear: 0.1, average_normals: true, ..base.cage };
+ base
+ };
+ let diag = (low.bounds().1 - low.bounds().0).max_element();
let (front, rear) = (0.5 * diag, 0.1 * diag);
- let height = |skew: Option<&SkewMap>| {
+ let height = |skew: Option<&BakePaintMap>| {
let req = BakeRequest {
+ low_base_color: &[],
mesh: &low,
bvh: &lb,
material: 0,
settings: &s,
- high: Some(HighPoly { mesh: &high, bvh: &hb, base_color: &[] }),
+ high: Some(HighPoly { file_ids: &[], mesh: &high, bvh: &hb, base_color: &[] }),
cage: None,
skew,
+ cage_paint: None,
tiles: (1, 1),
};
bake(&req, &Progress::new()).unwrap().maps[&BakedMap::Height][8 * 16 + 8]
};
- // Along a direction with vertical component c the ray meets the plane at t = front - 0.3 / c.
let expect = |c: f32| 0.5 + (0.3 / c) / (front + rear);
- let map = |v: f32, per_triangle: bool| SkewMap { per_triangle, ..SkewMap::constant(v) };
let plain = height(None);
assert!((plain - expect(0.8)).abs() < 1e-3, "leaning rays: {plain} vs {}", expect(0.8));
- assert!((height(Some(&map(0.0, true))) - plain).abs() < 1e-6, "black leaves the rays alone");
- let full = height(Some(&map(1.0, true)));
- assert!((full - expect(1.0)).abs() < 1e-3, "white turns them onto the flat normal: {full} vs {}", expect(1.0));
- let half = height(Some(&map(0.5, true)));
- assert!(half > full.min(plain) && half < full.max(plain), "grey is in between: {half}");
- // With the interpolated vertex normal as the base, correcting changes nothing on this mesh.
- assert!((height(Some(&map(1.0, false))) - plain).abs() < 1e-4);
- // A bad map is refused, not baked.
- let bad = SkewMap { values: vec![f32::NAN], ..SkewMap::constant(0.0) };
- let req = BakeRequest { mesh: &low, bvh: &lb, material: 0, settings: &s, high: None, cage: None, skew: Some(&bad), tiles: (1, 1) };
+ assert!((height(Some(&BakePaintMap::constant(0.0))) - plain).abs() < 1e-6, "black leaves the rays alone");
+ assert!((height(Some(&BakePaintMap::constant(1.0))) - plain).abs() < 1e-4);
+ let bad = BakePaintMap { values: vec![f32::NAN], ..BakePaintMap::constant(0.0) };
+ let req = BakeRequest {
+ low_base_color: &[],
+ mesh: &low,
+ bvh: &lb,
+ material: 0,
+ settings: &s,
+ high: None,
+ cage: None,
+ skew: Some(&bad),
+ cage_paint: None,
+ tiles: (1, 1),
+ };
assert!(matches!(bake(&req, &Progress::new()), Err(BakeError::Invalid(_))));
}
diff --git a/crates/bake/src/tracing.rs b/crates/bake/src/tracing.rs
new file mode 100644
index 00000000..c07596f6
--- /dev/null
+++ b/crates/bake/src/tracing.rs
@@ -0,0 +1,21 @@
+mod cpu_scene;
+mod cpu_tracer;
+mod hemisphere;
+mod query;
+mod ray;
+mod ray_kind;
+mod ray_scene;
+mod trace_mesh;
+mod tracer;
+
+pub use cpu_tracer::CpuTracer;
+pub use hemisphere::Hemisphere;
+pub use query::Query;
+pub use ray::Ray;
+pub use ray_kind::RayKind;
+pub use ray_scene::RayScene;
+pub use trace_mesh::TraceMesh;
+pub use tracer::Tracer;
+
+/// Part key that disables triangle filtering
+pub const ANY: u32 = u32::MAX;
diff --git a/crates/bake/src/tracing/cpu_scene.rs b/crates/bake/src/tracing/cpu_scene.rs
new file mode 100644
index 00000000..12f85f8b
--- /dev/null
+++ b/crates/bake/src/tracing/cpu_scene.rs
@@ -0,0 +1,34 @@
+use super::{ANY, Hemisphere, Query, Ray, RayScene, TraceMesh};
+use crate::BakeError;
+use rayon::prelude::*;
+use texturecraft_geom::Hit;
+
+pub(super) struct CpuScene<'a>(pub(super) Vec>);
+
+impl CpuScene<'_> {
+ fn mesh(&self, index: usize) -> Result<&TraceMesh<'_>, BakeError> {
+ self.0.get(index).ok_or_else(|| BakeError::Invalid(format!("no scene mesh {index}")))
+ }
+}
+
+impl RayScene for CpuScene<'_> {
+ fn closest(&mut self, mesh: usize, rays: &[Ray], ignore_backface: bool) -> Result>, BakeError> {
+ let trace_mesh = self.mesh(mesh)?;
+ Ok(rays
+ .par_iter()
+ .map(|ray| {
+ if ray.key == ANY && !ignore_backface {
+ trace_mesh.bvh.closest(ray.origin, ray.direction, ray.max_distance)
+ } else {
+ trace_mesh.bvh.closest_filtered(ray.origin, ray.direction, ray.max_distance, &|triangle| {
+ trace_mesh.key_matches(triangle, ray.key) && !(ignore_backface && trace_mesh.back_facing(triangle, ray.direction))
+ })
+ }
+ })
+ .collect())
+ }
+
+ fn hemispheres(&mut self, passes: &[Hemisphere], queries: &[Query]) -> Result>, BakeError> {
+ passes.iter().map(|hemisphere| queries.par_iter().map(|query| Ok(hemisphere.evaluate(self.mesh(query.mesh as usize)?, query))).collect()).collect()
+ }
+}
diff --git a/crates/bake/src/tracing/cpu_tracer.rs b/crates/bake/src/tracing/cpu_tracer.rs
new file mode 100644
index 00000000..5276e6aa
--- /dev/null
+++ b/crates/bake/src/tracing/cpu_tracer.rs
@@ -0,0 +1,16 @@
+use super::cpu_scene::CpuScene;
+use super::{RayScene, TraceMesh, Tracer};
+use crate::BakeError;
+
+#[derive(Clone, Copy, Debug, Default)]
+pub struct CpuTracer;
+
+impl Tracer for CpuTracer {
+ fn name(&self) -> String {
+ "CPU".into()
+ }
+
+ fn scene<'a>(&'a self, meshes: &[TraceMesh<'a>]) -> Result, BakeError> {
+ Ok(Box::new(CpuScene(meshes.to_vec())))
+ }
+}
diff --git a/crates/bake/src/tracing/hemisphere.rs b/crates/bake/src/tracing/hemisphere.rs
new file mode 100644
index 00000000..25d63e0c
--- /dev/null
+++ b/crates/bake/src/tracing/hemisphere.rs
@@ -0,0 +1,107 @@
+use super::{ANY, Query, RayKind, TraceMesh};
+use std::f32::consts::TAU;
+use texturecraft_core::{AmbientOcclusionAttenuation, BackfaceMode};
+use texturecraft_geom::glam::Vec3;
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct Hemisphere {
+ pub kind: RayKind,
+ pub rays: u32,
+ /// Maximum ray distance in mesh units
+ pub dmax: f32,
+ pub min_distance: f32,
+ pub attenuation: AmbientOcclusionAttenuation,
+ pub ground_height: Option,
+ /// Ray origin offset along the geometric normal
+ pub eps: f32,
+ pub cos_max: f32,
+ pub sin_max: f32,
+ pub uniform: bool,
+ pub ignore_backface: BackfaceMode,
+ pub same_key: bool,
+}
+
+impl Hemisphere {
+ pub fn direction(&self, (tangent, bitangent, axis): (Vec3, Vec3, Vec3), ray_index: u32, rotation: [f32; 2]) -> Vec3 {
+ let azimuth_sample = (ray_index as f32 / self.rays as f32 + rotation[0]).fract();
+ let elevation_sample = (ray_index.reverse_bits() as f32 / 4_294_967_296.0 + rotation[1]).fract();
+ let (radius, height) = if self.uniform {
+ let height = 1.0 - elevation_sample * (1.0 - self.cos_max);
+ ((1.0 - height * height).max(0.0).sqrt(), height)
+ } else {
+ let radius = self.sin_max * elevation_sample.sqrt();
+ (radius, (1.0 - radius * radius).max(0.0).sqrt())
+ };
+ let azimuth = TAU * azimuth_sample;
+ tangent * (radius * azimuth.cos()) + bitangent * (radius * azimuth.sin()) + axis * height
+ }
+
+ fn frame(&self, query: &Query) -> (Vec3, Vec3, Vec3) {
+ let (axis, geometric_normal) = match self.kind {
+ RayKind::Occlusion => (query.nrm, query.geo),
+ RayKind::Thickness => (-query.nrm, -query.geo),
+ };
+ (axis, geometric_normal, query.pos + geometric_normal * self.eps)
+ }
+
+ pub fn evaluate(&self, mesh: &TraceMesh, query: &Query) -> [f32; 4] {
+ let (axis, geometric_normal, origin) = self.frame(query);
+ let (tangent, bitangent) = axis.any_orthonormal_pair();
+ let key = if self.same_key { query.key } else { ANY };
+ let filtered = key != ANY || self.ignore_backface != BackfaceMode::Never;
+ let (mut accumulated, mut bent_normal, mut accepted_ray_count) = (0.0f32, Vec3::ZERO, 0u32);
+ for ray_index in 0..self.rays {
+ let direction = self.direction((tangent, bitangent, axis), ray_index, query.rot);
+ if direction.dot(geometric_normal) <= 0.0 {
+ continue;
+ }
+ let ray_origin = origin + direction * self.min_distance;
+ let ray_length = (self.dmax - self.min_distance).max(0.0);
+ let hit = if filtered {
+ mesh.bvh.closest_filtered(ray_origin, direction, ray_length, &|triangle| {
+ let ignore_backface = match self.ignore_backface {
+ BackfaceMode::Never => false,
+ BackfaceMode::Always => true,
+ BackfaceMode::ByMeshName => mesh.backface_culling.get(triangle as usize).copied().unwrap_or(false),
+ };
+ mesh.key_matches(triangle, key) && !(ignore_backface && mesh.back_facing(triangle, direction))
+ })
+ } else {
+ mesh.bvh.closest(ray_origin, direction, ray_length)
+ };
+ let mut distance = hit.map(|hit| hit.t + self.min_distance);
+ if let Some(height) = self.ground_height.filter(|_| direction.y < -1e-8) {
+ let ground_distance = (height - origin.y) / direction.y;
+ if (self.min_distance..=self.dmax).contains(&ground_distance) {
+ distance = Some(distance.map_or(ground_distance, |distance| distance.min(ground_distance)));
+ }
+ }
+ match self.kind {
+ RayKind::Occlusion => {
+ let occlusion = distance.map_or(0.0, |distance| self.occlusion(distance));
+ accumulated += occlusion;
+ bent_normal += direction * (1.0 - occlusion);
+ }
+ RayKind::Thickness => accumulated += distance.unwrap_or(self.dmax),
+ }
+ accepted_ray_count += 1;
+ }
+ match self.kind {
+ RayKind::Occlusion => {
+ let ambient_occlusion = if accepted_ray_count == 0 { 1.0 } else { (1.0 - accumulated / accepted_ray_count as f32).clamp(0.0, 1.0) };
+ let bent_normal = bent_normal.try_normalize().unwrap_or(query.nrm);
+ [ambient_occlusion, bent_normal.x, bent_normal.y, bent_normal.z]
+ }
+ RayKind::Thickness => [if accepted_ray_count == 0 { self.dmax } else { accumulated / accepted_ray_count as f32 }, 0.0, 0.0, 0.0],
+ }
+ }
+
+ fn occlusion(&self, distance: f32) -> f32 {
+ let fraction = ((distance - self.min_distance) / (self.dmax - self.min_distance).max(f32::EPSILON)).clamp(0.0, 1.0);
+ match self.attenuation {
+ AmbientOcclusionAttenuation::None => 1.0,
+ AmbientOcclusionAttenuation::Linear => 1.0 - fraction,
+ AmbientOcclusionAttenuation::Smooth => 1.0 - fraction * fraction * (3.0 - 2.0 * fraction),
+ }
+ }
+}
diff --git a/crates/bake/src/tracing/query.rs b/crates/bake/src/tracing/query.rs
new file mode 100644
index 00000000..a42e7091
--- /dev/null
+++ b/crates/bake/src/tracing/query.rs
@@ -0,0 +1,11 @@
+use texturecraft_geom::glam::Vec3;
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct Query {
+ pub pos: Vec3,
+ pub nrm: Vec3,
+ pub geo: Vec3,
+ pub rot: [f32; 2],
+ pub key: u32,
+ pub mesh: u32,
+}
diff --git a/crates/bake/src/tracing/ray.rs b/crates/bake/src/tracing/ray.rs
new file mode 100644
index 00000000..85303f1e
--- /dev/null
+++ b/crates/bake/src/tracing/ray.rs
@@ -0,0 +1,11 @@
+use texturecraft_geom::glam::Vec3;
+
+/// GPU buffer layout; batches upload without repacking
+#[repr(C)]
+#[derive(Clone, Copy, Debug, PartialEq, bytemuck::Pod, bytemuck::Zeroable)]
+pub struct Ray {
+ pub origin: Vec3,
+ pub max_distance: f32,
+ pub direction: Vec3,
+ pub key: u32,
+}
diff --git a/crates/bake/src/tracing/ray_kind.rs b/crates/bake/src/tracing/ray_kind.rs
new file mode 100644
index 00000000..1ce6eed9
--- /dev/null
+++ b/crates/bake/src/tracing/ray_kind.rs
@@ -0,0 +1,5 @@
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum RayKind {
+ Occlusion,
+ Thickness,
+}
diff --git a/crates/bake/src/tracing/ray_scene.rs b/crates/bake/src/tracing/ray_scene.rs
new file mode 100644
index 00000000..9a800452
--- /dev/null
+++ b/crates/bake/src/tracing/ray_scene.rs
@@ -0,0 +1,8 @@
+use super::{Hemisphere, Query, Ray};
+use crate::BakeError;
+use texturecraft_geom::Hit;
+
+pub trait RayScene: Send {
+ fn closest(&mut self, mesh: usize, rays: &[Ray], ignore_backface: bool) -> Result>, BakeError>;
+ fn hemispheres(&mut self, passes: &[Hemisphere], queries: &[Query]) -> Result>, BakeError>;
+}
diff --git a/crates/bake/src/tracing/trace_mesh.rs b/crates/bake/src/tracing/trace_mesh.rs
new file mode 100644
index 00000000..f4db3b14
--- /dev/null
+++ b/crates/bake/src/tracing/trace_mesh.rs
@@ -0,0 +1,23 @@
+use super::ANY;
+use texturecraft_geom::glam::Vec3;
+use texturecraft_geom::{Bvh, Mesh};
+
+#[derive(Clone, Copy, Debug)]
+pub struct TraceMesh<'a> {
+ pub mesh: &'a Mesh,
+ pub bvh: &'a Bvh,
+ /// Part key per triangle in original mesh order
+ pub keys: &'a [u32],
+ pub backface_culling: &'a [bool],
+}
+
+impl TraceMesh<'_> {
+ pub(super) fn key_matches(&self, triangle: u32, key: u32) -> bool {
+ key == ANY || self.keys.get(triangle as usize) == Some(&key)
+ }
+
+ pub(super) fn back_facing(&self, triangle: u32, direction: Vec3) -> bool {
+ let position = |vertex_index: usize| self.mesh.positions.get(vertex_index).copied().unwrap_or(Vec3::ZERO);
+ self.mesh.tri(triangle as usize).is_some_and(|[a, b, c]| (position(b) - position(a)).cross(position(c) - position(a)).dot(direction) > 0.0)
+ }
+}
diff --git a/crates/bake/src/tracing/tracer.rs b/crates/bake/src/tracing/tracer.rs
new file mode 100644
index 00000000..cda49f13
--- /dev/null
+++ b/crates/bake/src/tracing/tracer.rs
@@ -0,0 +1,7 @@
+use super::{RayScene, TraceMesh};
+use crate::BakeError;
+
+pub trait Tracer: Send + Sync {
+ fn name(&self) -> String;
+ fn scene<'a>(&'a self, meshes: &[TraceMesh<'a>]) -> Result, BakeError>;
+}
diff --git a/crates/compose/src/baked_maps.rs b/crates/compose/src/baked_maps.rs
new file mode 100644
index 00000000..1ce05bf7
--- /dev/null
+++ b/crates/compose/src/baked_maps.rs
@@ -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>>,
+}
+
+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 {
+ self.sample(m, x, y, size).map(|v| v[0])
+ }
+}
diff --git a/crates/compose/src/below.rs b/crates/compose/src/below.rs
index d5345c92..81868e66 100644
--- a/crates/compose/src/below.rs
+++ b/crates/compose/src/below.rs
@@ -10,10 +10,12 @@ use std::collections::{BTreeSet, HashMap, VecDeque};
use std::sync::Arc;
use texturecraft_core::project::MAX_DEPTH;
-use texturecraft_core::{BakedMap, Channel, Layer, LayerId, LayerKind, Project, TextureSet};
+use texturecraft_core::{BakedMap, Channel, EffectKind, Layer, LayerId, LayerKind, Project, Source, TextureSet};
use texturecraft_texel::TileImage;
use crate::eval::{Inputs, PaintTarget};
+use crate::held_fields::HeldFields;
+use crate::image_identity::ImageIdentity;
use crate::store::{BakedMaps, ImageStore, PixelStore};
/// Default byte budget of a [`BelowCache`], per nesting level it holds (see
@@ -40,11 +42,28 @@ pub struct BelowCache {
/// Tiles of the whole pass a caller splits into several composites (0: each composite is a
/// pass). A pass larger than the cache records only what fits.
pub pass: usize,
+ /// Tiles the caller composites next in this pass, after those of the coming composite (empty: none, or a pass that is one
+ /// composite). A stack with neighbourhood filters then filters the coming tiles and these at once and keeps the result for
+ /// the composites that follow, instead of filtering each small chunk's surroundings again.
+ pub ahead: Vec<(u32, u32)>,
+ pub(crate) held: Option,
}
impl Default for BelowCache {
fn default() -> Self {
- BelowCache { hot: None, key: None, tiles: HashMap::new(), order: VecDeque::new(), clock: 0, bytes: 0, budget: BELOW_BUDGET, levels: 1, pass: 0 }
+ BelowCache {
+ hot: None,
+ key: None,
+ tiles: HashMap::new(),
+ order: VecDeque::new(),
+ clock: 0,
+ bytes: 0,
+ budget: BELOW_BUDGET,
+ levels: 1,
+ pass: 0,
+ ahead: Vec::new(),
+ held: None,
+ }
}
}
@@ -78,48 +97,83 @@ pub struct StackKey {
layers: Vec,
pixels: Vec<(LayerId, Option, Shared)>,
baked: (u32, Vec<(BakedMap, usize)>),
- images: Vec<(String, usize)>,
+ images: Vec<(String, ImageIdentity)>,
}
impl StackKey {
- /// The key of `roots` (layers of texture set `ts`, bottom → top) and their effects.
- pub fn new(project: &Project, pixels: &PixelStore, baked: &BakedMaps, images: &ImageStore, ts: usize, roots: &[LayerId]) -> Option {
- StackKey::of_tree(project, pixels, baked, images, ts, roots.to_vec(), &project.render_tree(roots))
+ /// The key of `roots` (layers of a texture set, bottom → top) and their effects.
+ pub fn new(
+ project: &Project,
+ pixels: &PixelStore,
+ baked: &BakedMaps,
+ images: &ImageStore,
+ texture_set_index: usize,
+ roots: &[LayerId],
+ ) -> Option {
+ StackKey::of_tree(project, pixels, baked, images, texture_set_index, roots.to_vec(), &project.render_tree(roots))
}
- /// The key of the layers in `tree` (and their effects), drawn as `roots` arrange them.
+ /// The key of the layers in `render_tree` (and their effects), drawn as `roots` arrange them.
fn of_tree(
project: &Project,
pixels: &PixelStore,
baked: &BakedMaps,
images: &ImageStore,
- ts: usize,
+ texture_set_index: usize,
roots: Vec,
- tree: &BTreeSet,
+ render_tree: &BTreeSet,
) -> Option {
- let mut set = project.texture_set(ts).ok()?.clone();
+ let mut set = project.texture_set(texture_set_index).ok()?.clone();
set.name.clear();
set.description.clear();
set.stack.clear();
set.bake = Default::default();
- let effects: BTreeSet = tree.iter().filter_map(|id| project.layers.get(id)).flat_map(effect_ids).collect();
- let pixels = tree
+
+ let effect_ids: BTreeSet = render_tree.iter().filter_map(|id| project.layers.get(id)).flat_map(effect_ids).collect();
+ let pixel_handles = render_tree
.iter()
- .chain(&effects)
+ .chain(&effect_ids)
.flat_map(|id| {
- let layer = Channel::ALL.into_iter().filter_map(move |c| pixels.layer(*id, c).map(|img| (*id, Some(c), Shared(img.clone()))));
- layer.chain(pixels.masks.get(id).map(|img| (*id, None, Shared(img.clone()))))
+ let layer_channels =
+ Channel::ALL.into_iter().filter_map(move |channel| pixels.layer(*id, channel).map(|image| (*id, Some(channel), Shared(image.clone()))));
+ layer_channels.chain(pixels.masks.get(id).map(|image| (*id, None, Shared(image.clone()))))
})
.collect();
- let mut images: Vec<(String, usize)> = images.iter().map(|(n, i)| (n.clone(), Arc::as_ptr(i) as usize)).collect();
- images.sort();
+
+ let mut referenced_images = BTreeSet::new();
+ if !images.is_empty() {
+ let mut record_image_reference = |source: &Source| {
+ if let Source::Image { name, .. } = source
+ && let Some((name, _)) = images.get_key_value(name)
+ {
+ referenced_images.insert(name);
+ }
+ };
+ for layer in render_tree.iter().filter_map(|id| project.layers.get(id)) {
+ if let LayerKind::Fill(fill) = &layer.kind {
+ fill.sources.values().for_each(&mut record_image_reference);
+ }
+ for effect in layer.mask.iter().flat_map(|mask| &mask.effects).chain(&layer.content_effects) {
+ match &effect.kind {
+ EffectKind::Fill { source, .. } => record_image_reference(source),
+ EffectKind::Material(fill) => fill.sources.values().for_each(&mut record_image_reference),
+ EffectKind::Generator(generator) => generator.inputs.values().for_each(&mut record_image_reference),
+ _ => {}
+ }
+ }
+ }
+ }
+
+ let image_identities =
+ referenced_images.into_iter().filter_map(|name| images.get(name).map(|image| (name.clone(), ImageIdentity::new(image)))).collect();
+
Some(StackKey {
set,
roots,
- layers: tree.iter().filter_map(|id| project.layers.get(id)).map(render_view).collect(),
- pixels,
- baked: (baked.resolution, baked.maps.iter().map(|(m, d)| (*m, Arc::as_ptr(d) as usize)).collect()),
- images,
+ layers: render_tree.iter().filter_map(|id| project.layers.get(id)).map(render_view).collect(),
+ pixels: pixel_handles,
+ baked: (baked.resolution, baked.maps.iter().map(|(map, data)| (*map, Arc::as_ptr(data) as usize)).collect()),
+ images: image_identities,
})
}
}
@@ -137,25 +191,31 @@ impl StackKey {
}
let size = self.set.size();
let mut changed = BTreeSet::new();
- for ((id_a, ch_a, a), (id_b, ch_b, b)) in self.pixels.iter().zip(&other.pixels) {
- let (a, b) = (&a.0, &b.0);
- let same_shape = id_a == id_b && ch_a == ch_b && a.width() == b.width() && a.height() == b.height() && a.comps() == b.comps();
- // Image tiles are composite tiles only when the grids coincide.
- if !same_shape || (a.width(), a.height()) != size {
+ for ((left_id, left_channel, left_image), (right_id, right_channel, right_image)) in self.pixels.iter().zip(&other.pixels) {
+ let (left_image, right_image) = (&left_image.0, &right_image.0);
+ let same_shape = left_id == right_id
+ && left_channel == right_channel
+ && left_image.width() == right_image.width()
+ && left_image.height() == right_image.height()
+ && left_image.comps() == right_image.comps();
+
+ // Image tiles are composite tiles only when the grids coincide
+ if !same_shape || (left_image.width(), left_image.height()) != size {
return None;
}
- if a.same_tiles(b) {
+ if left_image.same_tiles(right_image) {
continue;
}
- for ty in 0..a.tiles_y() {
- for tx in 0..a.tiles_x() {
- let equal = match (a.tile_handle(tx, ty), b.tile_handle(tx, ty)) {
+
+ for tile_y in 0..left_image.tiles_y() {
+ for tile_x in 0..left_image.tiles_x() {
+ let equal = match (left_image.tile_handle(tile_x, tile_y), right_image.tile_handle(tile_x, tile_y)) {
(None, None) => true,
- (Some(x), Some(y)) => Arc::ptr_eq(x, y),
+ (Some(left_tile), Some(right_tile)) => Arc::ptr_eq(left_tile, right_tile),
_ => false,
};
if !equal {
- changed.insert((tx, ty));
+ changed.insert((tile_x, tile_y));
}
}
}
@@ -172,17 +232,18 @@ struct Shared(TileImage);
impl PartialEq for Shared {
fn eq(&self, other: &Self) -> bool {
- let (a, b) = (&self.0, &other.0);
- a.width() == b.width()
- && a.height() == b.height()
- && a.comps() == b.comps()
- && (0..a.tiles_y()).all(|ty| {
- (0..a.tiles_x()).all(|tx| match (a.tile_handle(tx, ty), b.tile_handle(tx, ty)) {
- (None, None) => true,
- (Some(x), Some(y)) => Arc::ptr_eq(x, y),
- _ => false,
- })
- })
+ let (left_image, right_image) = (&self.0, &other.0);
+ left_image.width() == right_image.width()
+ && left_image.height() == right_image.height()
+ && left_image.comps() == right_image.comps()
+ && (left_image.same_tiles(right_image)
+ || (0..left_image.tiles_y()).all(|tile_y| {
+ (0..left_image.tiles_x()).all(|tile_x| match (left_image.tile_handle(tile_x, tile_y), right_image.tile_handle(tile_x, tile_y)) {
+ (None, None) => true,
+ (Some(left_tile), Some(right_tile)) => Arc::ptr_eq(left_tile, right_tile),
+ _ => false,
+ })
+ }))
}
}
@@ -213,23 +274,30 @@ impl BelowCache {
pub fn clear(&mut self) {
let tiles = std::mem::take(&mut self.tiles);
- // Freeing a full cache (up to the byte budget in small bands) can take most of a
- // second: a thread does it so the frame that switched the hot layer doesn't stall.
+
+ // Native builds free cached bands off-thread to avoid a frame stall
#[cfg(not(target_arch = "wasm32"))]
if !tiles.is_empty() {
let _ = std::thread::Builder::new().name("texturecraft-free".into()).spawn(move || drop(tiles));
}
#[cfg(target_arch = "wasm32")]
drop(tiles);
+
self.order.clear();
self.bytes = 0;
self.key = None;
+ self.held = None;
}
pub fn bytes(&self) -> usize {
self.bytes
}
+ /// Whether neighbourhood-filter fields are kept for the composites that follow (see [`BelowCache::ahead`]).
+ pub fn holds_fields(&self) -> bool {
+ self.held.is_some()
+ }
+
/// The byte limit: the budget for the top level and as much again for a hot layer nested in
/// folders (each tile then holds the stack at two or more levels).
pub fn limit(&self) -> usize {
@@ -259,7 +327,7 @@ impl BelowCache {
self.clock += 1;
*stamp = self.clock;
self.order.push_back((t, self.clock));
- // Drop superseded uses once they outnumber the tiles.
+ // Drop superseded uses once they outnumber the tiles
if self.order.len() > 2 * self.tiles.len() + 64 {
let tiles = &self.tiles;
self.order.retain(|(t, s)| tiles.get(t).is_some_and(|(stamp, _)| stamp == s));
@@ -296,43 +364,53 @@ impl BelowCache {
/// live stroke). Empties the cache when what the cached part reads changed.
pub(crate) fn prepare(&mut self, inp: &Inputs) -> Option> {
let hot = self.hot?;
- let p = inp.project;
- let set = p.texture_set(inp.ts).ok()?;
- // Anchor readers depend on the stack below them.
- if p.render_tree(&set.stack).iter().any(|id| p.layers.get(id).is_some_and(Layer::reads_anchor)) {
+ let project = inp.project;
+ let set = project.texture_set(inp.ts).ok()?;
+
+ // Anchor readers depend on the stack below them
+ if project.render_tree(&set.stack).iter().any(|id| project.layers.get(id).is_some_and(Layer::reads_anchor)) {
return None;
}
- let levels = path(p, &set.stack, hot)?;
- let rest: Vec = levels.iter().flat_map(|l| l.below.iter().chain(&l.above)).copied().collect();
- if rest.is_empty() && levels.len() == 1 {
+
+ let levels = path(project, &set.stack, hot)?;
+ let off_path_roots: Vec = levels.iter().flat_map(|level| level.below.iter().chain(&level.above)).copied().collect();
+ if off_path_roots.is_empty() && levels.len() == 1 {
return None;
}
- let mut tree = p.render_tree(&rest);
- // Folders holding the hot layer (and the folders their instances draw) count with their
- // own state only, not their children.
- for l in levels.iter().take(levels.len() - 1) {
- let mut id = Some(l.at);
+
+ let mut cached_tree = project.render_tree(&off_path_roots);
+
+ // Cache containing folders by state, without their children
+ for level in levels.iter().take(levels.len() - 1) {
+ let mut id = Some(level.at);
for _ in 0..=MAX_DEPTH {
- let Some(i) = id.filter(|i| tree.insert(*i)) else { break };
- id = p.layers.get(&i).and_then(Layer::instance_source);
+ let Some(instance_id) = id.filter(|instance_id| cached_tree.insert(*instance_id)) else { break };
+ id = project.layers.get(&instance_id).and_then(Layer::instance_source);
}
}
- if tree.contains(&hot) {
+
+ // Repeated hot instances cannot share the off-path cache
+ if cached_tree.contains(&hot) {
return None;
}
- if let Some(pv) = inp.preview {
- let (PaintTarget::Layer(t) | PaintTarget::Mask(t)) = pv.target;
- if tree.contains(&t) || tree.iter().filter_map(|id| p.layers.get(id)).flat_map(effect_ids).any(|e| e == t) {
+
+ if let Some(preview) = inp.preview {
+ let (PaintTarget::Layer(target) | PaintTarget::Mask(target)) = preview.target;
+ if cached_tree.contains(&target)
+ || cached_tree.iter().filter_map(|id| project.layers.get(id)).flat_map(effect_ids).any(|effect_id| effect_id == target)
+ {
return None;
}
}
- let roots = set.stack.iter().chain(levels.iter().map(|l| &l.at)).copied().collect();
- let key = StackKey::of_tree(p, inp.pixels, inp.baked, inp.images, inp.ts, roots, &tree)?;
+
+ let roots = set.stack.iter().chain(levels.iter().map(|level| &level.at)).copied().collect();
+ let key = StackKey::of_tree(project, inp.pixels, inp.baked, inp.images, inp.ts, roots, &cached_tree)?;
self.levels = levels.len();
if self.key.as_ref() != Some(&key) {
self.clear();
self.key = Some(key);
}
+
Some(levels)
}
}
diff --git a/crates/compose/src/curvature_size_level.rs b/crates/compose/src/curvature_size_level.rs
new file mode 100644
index 00000000..fcd25492
--- /dev/null
+++ b/crates/compose/src/curvature_size_level.rs
@@ -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,
+}
+
+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");
+ }
+}
diff --git a/crates/compose/src/curvature_sizes.rs b/crates/compose/src/curvature_sizes.rs
new file mode 100644
index 00000000..0b7138bc
--- /dev/null
+++ b/crates/compose/src/curvature_sizes.rs
@@ -0,0 +1,476 @@
+//! 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>>,
+}
+
+/// 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>, CacheKey, BlockScales, Arc);
+
+static CACHE: Mutex> = 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> {
+ 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 =
+ 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>, key: CacheKey, scales: &BlockScales) -> Option> {
+ 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>, key: CacheKey, scales: &BlockScales, sizes: CurvatureSizes) -> Arc {
+ 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
+ };
+
+ // Keep layout variants so thumbnails and the viewport reuse their own levels
+ cache.retain(|entry| entry.0.strong_count() > 0 && !is_entry_for(entry, curvature, key, scales));
+ 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, 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::())).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>, 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 {
+ 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 = (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 =
+ 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 {
+ let window = (2 * radius + 1) as f64;
+ let mut weights = vec![1.0f64; length];
+ for _ in 0..BLUR_BOX_PASSES {
+ let running_totals: Vec = 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::() / 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 = (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 _guard = CACHE_TESTS.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
+ 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 = (0..map_size * map_size).map(|texel| if left_half(texel) { 1.0 } else { 0.0 }).collect();
+ let covered: Vec = (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));
+ }
+ }
+ }
+
+ // Cache lifecycle tests must not evict each other's entries in parallel
+ static CACHE_TESTS: Mutex<()> = Mutex::new(());
+
+ #[test]
+ fn alternating_layouts_reuse_their_cached_sizes() {
+ let _guard = CACHE_TESTS.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
+ let curvature = Arc::new(vec![0.5; 16]);
+ let scales = BlockScales::default();
+ let viewport_key = ((4, 4), (4, 4), (4, 4));
+ let thumbnail_key = ((4, 4), (4, 4), (2, 2));
+ let viewport = store(&curvature, viewport_key, &scales, CurvatureSizes { levels: Vec::new() });
+ let thumbnail = store(&curvature, thumbnail_key, &scales, CurvatureSizes { levels: Vec::new() });
+
+ assert!(Arc::ptr_eq(&cached(&curvature, viewport_key, &scales).unwrap(), &viewport), "a thumbnail must not evict the viewport layout");
+ assert!(Arc::ptr_eq(&cached(&curvature, thumbnail_key, &scales).unwrap(), &thumbnail), "both layouts stay reusable");
+ let mut set = texturecraft_core::TextureSet::new("Tiles", 0, 4);
+ set.uv_tiles = vec![1001, 1002];
+ set.tile_resolutions.insert(1002, 2);
+ let scaled = set.block_scales();
+ assert_ne!(scaled, scales);
+ assert!(cached(&curvature, viewport_key, &scaled).is_none(), "different tile scales cannot read the unscaled result");
+ let scaled_sizes = store(&curvature, viewport_key, &scaled, CurvatureSizes { levels: Vec::new() });
+ assert!(Arc::ptr_eq(&cached(&curvature, viewport_key, &scaled).unwrap(), &scaled_sizes));
+ assert!(Arc::ptr_eq(&cached(&curvature, viewport_key, &scales).unwrap(), &viewport), "scale variants also coexist");
+ let replacement = store(&curvature, viewport_key, &scales, CurvatureSizes { levels: Vec::new() });
+ assert!(Arc::ptr_eq(&cached(&curvature, viewport_key, &scales).unwrap(), &replacement));
+ assert!(Arc::ptr_eq(&cached(&curvature, thumbnail_key, &scales).unwrap(), &thumbnail), "updating one layout keeps the other");
+ }
+
+ #[test]
+ fn layout_variants_obey_the_entry_limit() {
+ let _guard = CACHE_TESTS.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
+ let curvature = Arc::new(vec![0.5; 16]);
+ let scales = BlockScales::default();
+ let key = |size| ((4, 4), (4, 4), (size, size));
+ for size in 1..=CACHE_MAPS as u32 + 1 {
+ store(&curvature, key(size), &scales, CurvatureSizes { levels: Vec::new() });
+ }
+ assert!(cached(&curvature, key(1), &scales).is_none(), "layout variants cannot grow without bound");
+ assert!(cached(&curvature, key(CACHE_MAPS as u32 + 1), &scales).is_some(), "the newest layout stays cached");
+ }
+
+ #[test]
+ fn sizes_built_on_demand_match_a_full_build() {
+ let map_size: u32 = 64;
+ let curvature: Vec =
+ (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 = (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");
+ }
+ }
+ }
+}
diff --git a/crates/compose/src/display.rs b/crates/compose/src/display.rs
index 56a4d4e1..5ebb667b 100644
--- a/crates/compose/src/display.rs
+++ b/crates/compose/src/display.rs
@@ -93,20 +93,21 @@ fn u8_of(v: u16) -> u8 {
(v >> 8) as u8
}
-/// Tile bytes (`TILE × TILE`, row-major) for `kind` from the composite, or None when the tile is
-/// absent in every source (the GPU texture keeps its cleared default).
-pub fn tile_bytes(comp: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u32, ty: u32) -> Vec {
- let bpt = kind.bytes_per_texel();
- let mut out = vec![0u8; TILE_AREA * bpt];
- let lut = srgb_lut();
- let get = |c: Channel| comp.channels.get(&c).and_then(|img| img.tile(tx, ty));
- let res = comp.resolution;
+/// Tile bytes (`TILE × TILE`, row-major) for `kind`, using channel defaults for absent source tiles.
+pub fn tile_bytes(composite: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u32, ty: u32) -> Vec {
+ let bytes_per_texel = kind.bytes_per_texel();
+ let mut out = vec![0u8; TILE_AREA * bytes_per_texel];
+ let srgb = srgb_lut();
+ let get = |c: Channel| composite.channels.get(&c).and_then(|img| img.tile(tx, ty));
+ let resolution = composite.resolution;
let default16 = |c: Channel| texturecraft_texel::to_u16(c.default_value()[0]);
- // A scalar channel's texel `i` as 8 bits (its default where the set lacks it).
+
+ // A scalar channel's texel `i` as 8 bits (its default where the set lacks it)
let scalar8 = |c: Channel| {
let (t, d) = (get(c), default16(c));
move |i: usize| u8_of(t.and_then(|t| t.get(i).copied()).unwrap_or(d))
};
+
match kind {
DisplayKind::BaseColor | DisplayKind::Emissive | DisplayKind::Sheen => {
let (c, alpha) = match kind {
@@ -117,81 +118,87 @@ pub fn tile_bytes(comp: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u3
let (src, alpha) = (get(c), scalar8(alpha));
let d = c.default_value().map(|v| (texturecraft_texel::linear_to_srgb(v) * 255.0 + 0.5) as u8);
for i in 0..TILE_AREA {
- let px = &mut out[i * 4..i * 4 + 4];
+ let pixel = &mut out[i * 4..i * 4 + 4];
match src {
Some(s) => {
for k in 0..3 {
- px[k] = lut[(s.get(i * 3 + k).copied().unwrap_or(0) >> 4) as usize];
+ pixel[k] = srgb[(s.get(i * 3 + k).copied().unwrap_or(0) >> 4) as usize];
}
}
- None => px[..3].copy_from_slice(&d),
+ None => pixel[..3].copy_from_slice(&d),
}
- px[3] = alpha(i);
+ pixel[3] = alpha(i);
}
}
DisplayKind::Lobes => {
let lanes = [Channel::CoatWeight, Channel::CoatRoughness, Channel::AnisotropyLevel, Channel::AnisotropyAngle].map(scalar8);
- for (i, px) in out.chunks_exact_mut(4).enumerate() {
- for (d, lane) in px.iter_mut().zip(&lanes) {
+ for (i, pixel) in out.as_chunks_mut::<4>().0.iter_mut().enumerate() {
+ for (d, lane) in pixel.iter_mut().zip(&lanes) {
*d = lane(i);
}
}
}
DisplayKind::Extra => {
let (n, transmission) = (get(Channel::CoatNormal), scalar8(Channel::Transmission));
- // Signed 8-bit around 128 so the flat normal packs exactly.
- let snorm = |v: u16| (128.0 + 127.0 * (v as f32 / 65535.0 * 2.0 - 1.0)).round().clamp(0.0, 255.0) as u8;
- // A TILE never straddles two atlas blocks.
- let scale = (-32.0 * comp.block_scales.at(tx * TILE, ty * TILE).log2()).round().clamp(0.0, 255.0) as u8;
- for (i, px) in out.chunks_exact_mut(4).enumerate() {
- for (k, d) in px.iter_mut().take(2).enumerate() {
- *d = n.and_then(|t| t.get(i * 3 + k)).map_or(128, |v| snorm(*v));
+
+ // Signed 8-bit around 128 so the flat normal packs exactly
+ let pack_signed_normal = |v: u16| (128.0 + 127.0 * (v as f32 / 65535.0 * 2.0 - 1.0)).round().clamp(0.0, 255.0) as u8;
+
+ // A TILE never straddles two atlas blocks
+ let scale = (-32.0 * composite.block_scales.at(tx * TILE, ty * TILE).log2()).round().clamp(0.0, 255.0) as u8;
+ for (i, pixel) in out.as_chunks_mut::<4>().0.iter_mut().enumerate() {
+ for (k, d) in pixel.iter_mut().take(2).enumerate() {
+ *d = n.and_then(|t| t.get(i * 3 + k)).map_or(128, |v| pack_signed_normal(*v));
}
- px[2] = transmission(i);
- px[3] = scale;
+ pixel[2] = transmission(i);
+ pixel[3] = scale;
}
}
DisplayKind::Orm => {
let (ao, m, s) = (get(Channel::AmbientOcclusion), get(Channel::Metallic), get(Channel::SpecularLevel));
- // Specular/glossiness sets: the viewport shades roughness = 1 − glossiness.
- let gloss = comp.channels.contains_key(&Channel::Glossiness);
+
+ // Specular/glossiness sets: the viewport shades roughness = 1 − glossiness
+ let gloss = composite.channels.contains_key(&Channel::Glossiness);
let (r, r_default) =
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).unwrap_or(1.0);
+ let baked_ao = baked
+ .sample_working(BakedMap::AmbientOcclusion, x, y, (resolution, composite.height), &composite.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;
+ let pixel = &mut out[i * 4..i * 4 + 4];
+ pixel[0] = ((baked_ao * ch_ao).clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
let v = r.and_then(|t| t.get(i).copied()).unwrap_or(r_default);
- px[1] = u8_of(if gloss { 65535 - v } else { v });
- px[2] = u8_of(m.and_then(|t| t.get(i).copied()).unwrap_or(0));
- px[3] = u8_of(s.and_then(|t| t.get(i).copied()).unwrap_or(default16(Channel::SpecularLevel)));
+ pixel[1] = u8_of(if gloss { 65535 - v } else { v });
+ pixel[2] = u8_of(m.and_then(|t| t.get(i).copied()).unwrap_or(0));
+ pixel[3] = u8_of(s.and_then(|t| t.get(i).copied()).unwrap_or(default16(Channel::SpecularLevel)));
}
}
DisplayKind::Normal => {
- let (n, sheen_rough) = (get(Channel::Normal), scalar8(Channel::SheenRoughness));
+ let (n, sheen_roughness) = (get(Channel::Normal), scalar8(Channel::SheenRoughness));
for i in 0..TILE_AREA {
- 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 pixel = &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);
+ let base = baked.sample_working(BakedMap::Normal, x, y, (resolution, composite.height), &composite.block_scales);
match (n, base) {
(Some(t), None) => {
- for (k, d) in px.iter_mut().take(3).enumerate() {
+ for (k, d) in pixel.iter_mut().take(3).enumerate() {
*d = u8_of(t.get(i * 3 + k).copied().unwrap_or(0));
}
}
(detail, Some(base)) => {
let detail = detail.map_or([0.5, 0.5, 1.0], |t| [0, 1, 2].map(|k| t.get(i * 3 + k).map_or(0.0, |v| *v as f32 / 65535.0)));
let v = texturecraft_core::blend::rnm(base, detail);
- for (d, v) in px.iter_mut().zip(v) {
+ for (d, v) in pixel.iter_mut().zip(v) {
*d = (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
}
}
- (None, None) => px[..3].copy_from_slice(&[128, 128, 255]),
+ (None, None) => pixel[..3].copy_from_slice(&[128, 128, 255]),
}
- px[3] = sheen_rough(i);
+ pixel[3] = sheen_roughness(i);
}
}
DisplayKind::Height => {
@@ -206,6 +213,7 @@ pub fn tile_bytes(comp: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u3
}
}
}
+
out
}
diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs
index d98b1fe6..1e077cbe 100644
--- a/crates/compose/src/eval.rs
+++ b/crates/compose/src/eval.rs
@@ -2,19 +2,25 @@
//! tile by tile in parallel. This is the reference implementation (the oracle) for the viewport
//! and for export.
+pub(crate) mod thumbnail;
+
use std::borrow::Cow;
use std::collections::{BTreeMap, HashMap};
+use std::sync::Arc;
use rayon::prelude::*;
use texturecraft_core::{
- BakedMap, BlendMode, BlockScales, Channel, ChannelKind, CompareOp, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId,
- LayerKind, Mask, MaskBackground, NormalFormat, Project, Projection, Source, TextureSet, TileGrid, blend1, blend3, lum, mix3, per_unit,
+ BakedMap, BlendMode, BlockScales, Channel, ChannelKind, CompareOp, CurvatureDetail, CurvatureMode, Effect, EffectKind, Fill, Filter, Generator,
+ GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Mask, MaskBackground, NormalFormat, Project, Projection, Source, TextureSet, TileGrid, blend1,
+ blend3, lum, mix3, per_unit,
};
use texturecraft_geom::glam::{Vec2, Vec3};
use texturecraft_geom::{Mesh, NO_TRI, UvGBuffer};
use texturecraft_texel::{DilationMap, TILE, TILE_AREA, TileImage, from_u16, noise, to_u16, to_u16_signed};
-use crate::below::{Band, BelowCache, Level};
+use crate::below::{Band, BelowCache, Level, StackKey};
+use crate::curvature_sizes::CurvatureSizes;
+use crate::held_fields::HeldFields;
use crate::pattern::{Coords, decal_uv, image_samples, procedural, world_noise};
use crate::store::{BakedMaps, ImageStore, PixelStore, decode};
@@ -93,6 +99,7 @@ pub struct Inputs<'a> {
pub gbuf: &'a UvGBuffer,
pub pixels: &'a PixelStore,
pub baked: &'a BakedMaps,
+ pub block_scales: BlockScales,
pub preview: Option<&'a StrokePreview>,
/// Imported image resources (fill sources).
pub images: &'a ImageStore,
@@ -203,6 +210,8 @@ struct EffectPlan<'a> {
opacity: f32,
data: Option>,
preview: bool,
+ /// The curvature detail sizes a generator with detail reads.
+ curvature_sizes: Option>,
}
struct MaskPlan<'a> {
@@ -265,48 +274,67 @@ enum Op {
Slope { scale: f32, seed: u32 },
}
-/// Index (among visible effects) of the last neighbourhood filter of an effect stack, its
-/// radius in texels (`res` texels per UV tile across) and what it does.
+/// The last neighbourhood filter of an effect stack (see [`neighbourhood_filters`]).
fn neighbourhood(effects: &[Effect], res: u32) -> Option<(usize, f32, Op)> {
- let texels = |v: f32| (v * res as f32 / 2048.0).max(0.5);
- effects
- .iter()
- .filter(|e| e.visible)
- .enumerate()
- .filter_map(|(i, e)| match &e.kind {
- EffectKind::Filter(Filter::Blur { radius }) if *radius > 0.0 => Some((i, texels(*radius), Op::Blur(None))),
- EffectKind::Filter(Filter::Sharpen { amount }) => Some((i, (1.5 * res as f32 / 2048.0).max(0.75), Op::Blur(Some(*amount)))),
- EffectKind::Filter(Filter::DirectionalBlur { radius, angle }) if *radius > 0.0 => Some((i, texels(*radius), Op::Line(direction(*angle)))),
- EffectKind::Filter(Filter::Warp { intensity, scale, seed }) if *intensity > 0.0 => {
- Some((i, texels(*intensity), Op::Warp { scale: *scale, seed: *seed, dir: None }))
- }
- EffectKind::Filter(Filter::DirectionalWarp { intensity, angle, scale, seed }) if *intensity > 0.0 => {
- Some((i, texels(*intensity), Op::Warp { scale: *scale, seed: *seed, dir: Some(direction(*angle)) }))
- }
- EffectKind::Filter(Filter::HighPass { radius }) => Some((i, texels(*radius), Op::HighPass)),
- EffectKind::Filter(Filter::EdgeDetect { width }) => Some((i, texels(*width), Op::Edge)),
- // Three box passes ramp an edge over about twice their radius.
- EffectKind::Filter(Filter::Bevel { width }) => Some((i, texels(*width * 0.5), Op::Bevel)),
- EffectKind::Filter(Filter::Glow { radius, amount }) => Some((i, texels(*radius), Op::Glow(*amount))),
- EffectKind::Filter(Filter::Mosaic { size }) => Some((i, texels(*size), Op::Mosaic)),
- EffectKind::Filter(Filter::SlopeBlur { radius, scale, seed }) if *radius > 0.0 => {
- Some((i, texels(*radius), Op::Slope { scale: *scale, seed: *seed }))
- }
- _ => None,
- })
- .last()
+ neighbourhood_filters(effects, res).last()
}
-/// Whether any effect (mask or content) of a layer drawn in texture set `ts` reads texels
-/// around each texel (blur, sharpen, warp, edge, bevel, glow, mosaic, slope blur). Conservative:
-/// hidden layers and disabled masks count too.
-pub fn stack_reads_neighbours(project: &Project, ts: usize) -> bool {
- let Some(set) = project.texture_sets.get(ts) else { return false };
- project
- .render_tree(&set.stack)
- .iter()
- .filter_map(|id| project.layers.get(id))
- .any(|l| neighbourhood(&l.content_effects, 2048).is_some() || l.mask.as_ref().is_some_and(|m| neighbourhood(&m.effects, 2048).is_some()))
+/// Below this a coverage weight counts as no coverage at all.
+const MIN_COVERAGE_WEIGHT: f32 = 1e-6;
+/// Filter sizes are texels at this many texels per side (2K), scaled to the resolution they run at.
+const FILTER_SIZE_RESOLUTION: f32 = 2048.0;
+/// The smallest radius a filter runs at, in texels.
+const MIN_FILTER_RADIUS: f32 = 0.5;
+/// Sharpen's blur radius at [`FILTER_SIZE_RESOLUTION`], and the smallest it runs at, in texels.
+const SHARPEN_RADIUS: f32 = 1.5;
+const MIN_SHARPEN_RADIUS: f32 = 0.75;
+
+/// The neighbourhood filters of an effect stack, bottom → top: index among the visible effects, radius in texels (`res` texels per UV tile across) and what it does.
+fn neighbourhood_filters(effects: &[Effect], res: u32) -> impl Iterator- + '_ {
+ let texels = move |size: f32| (size * res as f32 / FILTER_SIZE_RESOLUTION).max(MIN_FILTER_RADIUS);
+ effects.iter().filter(|effect| effect.visible).enumerate().filter_map(move |(index, effect)| match &effect.kind {
+ EffectKind::Filter(Filter::Blur { radius }) if *radius > 0.0 => Some((index, texels(*radius), Op::Blur(None))),
+ EffectKind::Filter(Filter::Sharpen { amount }) => {
+ Some((index, (SHARPEN_RADIUS * res as f32 / FILTER_SIZE_RESOLUTION).max(MIN_SHARPEN_RADIUS), Op::Blur(Some(*amount))))
+ }
+ EffectKind::Filter(Filter::DirectionalBlur { radius, angle }) if *radius > 0.0 => Some((index, texels(*radius), Op::Line(direction(*angle)))),
+ EffectKind::Filter(Filter::Warp { intensity, scale, seed }) if *intensity > 0.0 => {
+ Some((index, texels(*intensity), Op::Warp { scale: *scale, seed: *seed, dir: None }))
+ }
+ EffectKind::Filter(Filter::DirectionalWarp { intensity, angle, scale, seed }) if *intensity > 0.0 => {
+ Some((index, texels(*intensity), Op::Warp { scale: *scale, seed: *seed, dir: Some(direction(*angle)) }))
+ }
+ EffectKind::Filter(Filter::HighPass { radius }) => Some((index, texels(*radius), Op::HighPass)),
+ EffectKind::Filter(Filter::EdgeDetect { width }) => Some((index, texels(*width), Op::Edge)),
+ // Three box passes ramp an edge over about twice their radius
+ EffectKind::Filter(Filter::Bevel { width }) => Some((index, texels(*width * 0.5), Op::Bevel)),
+ EffectKind::Filter(Filter::Glow { radius, amount }) => Some((index, texels(*radius), Op::Glow(*amount))),
+ EffectKind::Filter(Filter::Mosaic { size }) => Some((index, texels(*size), Op::Mosaic)),
+ // Independent of `res`, so every caller agrees on which effects are stages; the reach covers the cells, then the blur around them
+ EffectKind::Generator(generator) if generator.global.blur > 0.0 || generator.resolution.can_reduce() => {
+ Some((index, texels(generator.global.blur_radius()) + generator.resolution.largest_cell(res) as f32, Op::Blur(None)))
+ }
+ EffectKind::Filter(Filter::SlopeBlur { radius, scale, seed }) if *radius > 0.0 => {
+ Some((index, texels(*radius), Op::Slope { scale: *scale, seed: *seed }))
+ }
+ _ => None,
+ })
+}
+
+/// Whether any mask or content effect in a texture set reads neighbouring texels. Includes
+/// filters, blurred generators and reduced-resolution generators. Hidden layers and disabled
+/// masks count too, so partial invalidation remains conservative.
+pub fn stack_reads_neighbours(project: &Project, texture_set_index: usize) -> bool {
+ const NEIGHBOUR_PROBE_RESOLUTION: u32 = 2048;
+
+ let Some(set) = project.texture_sets.get(texture_set_index) else {
+ return false;
+ };
+
+ project.render_tree(&set.stack).iter().filter_map(|id| project.layers.get(id)).any(|layer| {
+ neighbourhood(&layer.content_effects, NEIGHBOUR_PROBE_RESOLUTION).is_some()
+ || layer.mask.as_ref().is_some_and(|mask| neighbourhood(&mask.effects, NEIGHBOUR_PROBE_RESOLUTION).is_some())
+ })
}
/// Unit texel-space vector of `angle` degrees. Texel rows run down: positive angles turn
@@ -316,6 +344,12 @@ fn direction(angle: f32) -> [f32; 2] {
[cs, -sn]
}
+/// Gain on the curvature map's own deviation from flat (±0.5 reaches black and white).
+const MAP_GAIN: f32 = 2.0;
+
+/// Gain per texel of a detail size: blurring spreads an edge over about twice its radius, so wider sizes need proportionally more to reach full strength.
+const GAIN_PER_DETAIL_TEXEL: f32 = 2.0 * std::f32::consts::SQRT_2;
+
/// Samples along a directional or slope blur at most (beyond, samples spread out).
const LINE_SAMPLES: i32 = 24;
@@ -433,27 +467,45 @@ fn gather(op: Op, orig: &[f32], cover: &[f32], comps: usize, (x0, y0, w, h): (u3
/// the region it is computed in, so tiles composited in any grouping agree exactly.
const FIX: f64 = (1u64 << 24) as f64;
-/// Three running-sum box blurs (≈ Gaussian) of a `w × h` image along rows then along columns.
-/// Rows (and columns, transposed) blur in parallel.
-fn blur(data: &mut [f32], w: usize, h: usize, r: usize) {
- let fix = |v: &f32| if v.is_finite() { (f64::from(v.clamp(-1e6, 1e6)) * FIX).round() as i64 } else { 0 };
- let mut v: Vec
= data.par_iter().map(fix).collect();
- blur_rows(&mut v, w, r);
- let mut t = transpose(&v, w, h);
- blur_rows(&mut t, h, r);
- data.par_iter_mut().zip(transpose(&t, h, w)).for_each(|(d, s)| *d = (s as f64 / FIX) as f32);
+/// Texels one parallel task of a neighbourhood filter handles at least. Compositing in frame slices filters regions of a few tiles: split per texel,
+/// handing that little work to every thread costs far more than the work itself. Each texel is computed on its own, so the split does not change results.
+const MIN_PARALLEL_TEXELS: usize = 1 << 14;
+
+/// How many lines of `length` texels make a parallel task of at least [`MIN_PARALLEL_TEXELS`].
+fn lines_per_task(length: usize) -> usize {
+ (MIN_PARALLEL_TEXELS / length.max(1)).max(1)
}
+/// Three running-sum box blurs (≈ Gaussian) of a `width × height` image along its rows, then its columns, each in parallel.
+pub(crate) fn blur(data: &mut [f32], width: usize, height: usize, radius: usize) {
+ // Bound samples before fixed-point accumulation
+ const MAX_INPUT_MAGNITUDE: f32 = 1e6;
+
+ let to_fixed = |value: &f32| if value.is_finite() { (f64::from(value.clamp(-MAX_INPUT_MAGNITUDE, MAX_INPUT_MAGNITUDE)) * FIX).round() as i64 } else { 0 };
+ let mut fixed: Vec = data.par_iter().with_min_len(MIN_PARALLEL_TEXELS).map(to_fixed).collect();
+ blur_rows(&mut fixed, width, radius);
+
+ let mut columns = transpose(&fixed, width, height);
+ blur_rows(&mut columns, height, radius);
+ transpose_into(&columns, height, width, &mut fixed);
+
+ data.par_iter_mut().with_min_len(MIN_PARALLEL_TEXELS).zip(fixed).for_each(|(target, blurred)| *target = (blurred as f64 / FIX) as f32);
+}
+
+/// The box blurs `blur` runs along each axis
+pub(crate) const BLUR_BOX_PASSES: usize = 3;
+
/// Three box blurs of radius `r` along every row (`w` long) of `data`.
fn blur_rows(data: &mut [i64], w: usize, r: usize) {
if w == 0 {
return;
}
- data.par_chunks_mut(w).for_each(|row| {
- let mut tmp = vec![0i64; row.len()];
- for _ in 0..3 {
- box_line(row, &mut tmp, r);
- row.copy_from_slice(&tmp);
+
+ data.par_chunks_mut(w).with_min_len(lines_per_task(w)).for_each(|row| {
+ let mut scratch = vec![0i64; row.len()];
+ for _ in 0..BLUR_BOX_PASSES {
+ box_line(row, &mut scratch, r);
+ row.copy_from_slice(&scratch);
}
});
}
@@ -461,7 +513,8 @@ fn blur_rows(data: &mut [i64], w: usize, r: usize) {
/// One box blur of radius `r` of a line (texels past the ends count as 0).
fn box_line(src: &[i64], dst: &mut [i64], r: usize) {
let n = (2 * r + 1) as i64;
- // Rounded division of a window sum.
+
+ // Rounded division of a window sum
let avg = |acc: i64| (2 * acc + n).div_euclid(2 * n);
let mut acc: i64 = src.iter().take(r + 1).sum();
for (i, d) in dst.iter_mut().enumerate() {
@@ -476,14 +529,18 @@ fn box_line(src: &[i64], dst: &mut [i64], r: usize) {
/// `src` (`w × h`, row-major) transposed to `h × w`.
fn transpose(src: &[i64], w: usize, h: usize) -> Vec {
let mut out = vec![0i64; src.len()];
+ transpose_into(src, w, h, &mut out);
+ out
+}
+
+fn transpose_into(src: &[i64], w: usize, h: usize, out: &mut [i64]) {
if h > 0 {
- out.par_chunks_mut(h).enumerate().for_each(|(x, col)| {
+ out.par_chunks_mut(h).with_min_len(lines_per_task(h)).enumerate().for_each(|(x, col)| {
for (y, d) in col.iter_mut().enumerate() {
*d = src.get(y * w + x).copied().unwrap_or(0);
}
});
}
- out
}
/// Covered texels of tile (tx, ty): (x, y, offset inside the tile).
@@ -540,164 +597,358 @@ enum Job<'a> {
Content(Channel),
}
-/// One neighbourhood-filtered field of `layer` over `tiles` plus the filter's reach, built on
-/// the fields already computed below it.
+/// A layer's mask or content channel after every neighbourhood filter of its stack, over `tiles`.
fn field(inp: &Inputs, channels: &[Channel], below: &Fields, id: LayerId, job: Job, tiles: &[(u32, u32)]) -> Option {
- let (gw, gh) = (inp.gbuf.width, inp.gbuf.height);
let effects = match job {
- Job::Mask(m) => &m.effects,
+ Job::Mask(mask) => &mask.effects,
Job::Content(_) => &inp.project.content_layer(id)?.content_effects,
};
- let (k, radius, op) = neighbourhood(effects, inp.tile_res())?;
- let opacity = effects.iter().filter(|e| e.visible).nth(k).map(|e| e.opacity.clamp(0.0, 1.0)).unwrap_or(1.0);
- // Clamped: a hostile radius must not overflow the halo and window arithmetic.
- let r = radius.round().clamp(1.0, gw.max(gh) as f32) as u32;
- // Three box passes reach 3r texels, the other filters r (and a texel for bilinear samples).
- let blurs = matches!(op, Op::Blur(_) | Op::HighPass | Op::Bevel | Op::Glow(_));
- let reach = if blurs { 3 * r } else { r + 1 };
- let halo = reach.div_ceil(TILE);
- let (tx0, ty0) = tiles.iter().fold((u32::MAX, u32::MAX), |(a, b), t| (a.min(t.0), b.min(t.1)));
- let (tx1, ty1) = tiles.iter().fold((0, 0), |(a, b), t| (a.max(t.0), b.max(t.1)));
- let (rx0, ry0) = (tx0.saturating_sub(halo) * TILE, ty0.saturating_sub(halo) * TILE);
- let (rx1, ry1) = (((tx1 + 1 + halo) * TILE).min(gw), ((ty1 + 1 + halo) * TILE).min(gh));
- let (w, h) = (rx1.saturating_sub(rx0), ry1.saturating_sub(ry0));
- if w == 0 || h == 0 {
- return None;
+ let filters: Vec<(usize, f32, Op)> = neighbourhood_filters(effects, inp.tile_res()).collect();
+ let longest_side = inp.gbuf.width.max(inp.gbuf.height);
+
+ // Each filter's region also holds what every filter above it reads around the tiles
+ let mut margins: Vec = filters.iter().map(|&(_, radius, op)| filter_extent(radius, op, longest_side).1.div_ceil(TILE)).collect();
+ for index in (0..margins.len().saturating_sub(1)).rev() {
+ margins[index] += margins[index + 1];
}
- let comps = match job {
+
+ let mut previous: Option<(usize, Field)> = None;
+ for (&filter, &margin) in filters.iter().zip(&margins) {
+ let region = region_around(inp, tiles, margin)?;
+ let start = previous.as_ref().map(|(index, field)| (*index, field));
+ let filtered = filter_region(inp, channels, below, id, job, effects, filter, region, start)?;
+ previous = Some((filter.0, filtered));
+ }
+ previous.map(|(_, field)| field)
+}
+
+/// The tile-aligned texel region `(x0, y0, w, h)` around `tiles` plus `margin` tiles, clipped to the set.
+fn region_around(inp: &Inputs, tiles: &[(u32, u32)], margin: u32) -> Option<(u32, u32, u32, u32)> {
+ let (first_x, first_y) = tiles.iter().fold((u32::MAX, u32::MAX), |(min_x, min_y), tile| (min_x.min(tile.0), min_y.min(tile.1)));
+ let (last_x, last_y) = tiles.iter().fold((0, 0), |(max_x, max_y), tile| (max_x.max(tile.0), max_y.max(tile.1)));
+ let (x0, y0) = (first_x.saturating_sub(margin) * TILE, first_y.saturating_sub(margin) * TILE);
+ let (x1, y1) = (((last_x + 1 + margin) * TILE).min(inp.gbuf.width), ((last_y + 1 + margin) * TILE).min(inp.gbuf.height));
+ let (w, h) = (x1.saturating_sub(x0), y1.saturating_sub(y0));
+ (w > 0 && h > 0).then_some((x0, y0, w, h))
+}
+
+/// A neighbourhood filter's radius in whole texels and how many texels around a texel it reads.
+fn filter_extent(radius: f32, op: Op, longest_side: u32) -> (u32, u32) {
+ // Clamped so a hostile radius can't overflow the region arithmetic
+ let radius_texels = radius.round().clamp(1.0, longest_side as f32) as u32;
+
+ // Three box passes reach three radii; the gathering filters one radius plus a bilinear texel
+ let reach = if is_box_blur(op) { 3 * radius_texels } else { radius_texels + 1 };
+ (radius_texels, reach)
+}
+
+/// Whether neighbourhood filter `op` is computed from box blurs (the others gather samples).
+fn is_box_blur(op: Op) -> bool {
+ matches!(op, Op::Blur(_) | Op::HighPass | Op::Bevel | Op::Glow(_))
+}
+
+/// The stack up to and including neighbourhood filter `filter` over texel `region`, continued from `start` (the filter below's field) when given.
+#[allow(clippy::too_many_arguments)]
+fn filter_region(
+ inputs: &Inputs,
+ channels: &[Channel],
+ below: &Fields,
+ id: LayerId,
+ job: Job,
+ effects: &[Effect],
+ (index, radius, op): (usize, f32, Op),
+ (region_x, region_y, width, height): (u32, u32, u32, u32),
+ start: Option<(usize, &Field)>,
+) -> Option {
+ let filter_effect = effects.iter().filter(|effect| effect.visible).nth(index);
+ let opacity = filter_effect.map(|effect| effect.opacity.clamp(0.0, 1.0)).unwrap_or(1.0);
+ let (radius_texels, _) = filter_extent(radius, op, inputs.gbuf.width.max(inputs.gbuf.height));
+
+ // Generator stages keep their ramp beside the mask stack below
+ let generator = match (job, filter_effect.map(|effect| (&effect.kind, effect.blend))) {
+ (Job::Mask(_), Some((EffectKind::Generator(generator), blend))) => Some((generator, blend)),
+ _ => None,
+ };
+ let components = match job {
+ Job::Mask(_) if generator.is_some() => 2,
Job::Mask(_) => 1,
Job::Content(_) => 4,
};
- // Evaluate the stack before the filter, tile by tile (content premultiplied by coverage).
- let region_tiles: Vec<(u32, u32)> = (ry0 / TILE..ry1.div_ceil(TILE)).flat_map(|y| (rx0 / TILE..rx1.div_ceil(TILE)).map(move |x| (x, y))).collect();
+
+ // Evaluate the stack up to the filter, tile by tile (content premultiplied by coverage)
+ let (region_right, region_bottom) = (region_x + width, region_y + height);
+ let region_tiles: Vec<(u32, u32)> =
+ (region_y / TILE..region_bottom.div_ceil(TILE)).flat_map(|y| (region_x / TILE..region_right.div_ceil(TILE)).map(move |x| (x, y))).collect();
let parts: Vec> = region_tiles
.par_iter()
- .map(|&(tx, ty)| {
- let full = anchor_plan(inp, id, channels, tx, ty, Some(below));
- let preview_tile = inp.preview.and_then(|p| p.alpha.tile(tx, ty));
+ .map(|&(tile_x, tile_y)| {
+ let anchor_nodes = anchor_plan(inputs, id, channels, tile_x, tile_y, Some(below));
+ let preview_tile = inputs.preview.and_then(|preview| preview.alpha.tile(tile_x, tile_y));
let mut mask = None;
let mut nodes = Vec::new();
+ let mut generator_sizes = None;
match job {
- Job::Mask(m) => {
- let Some(mut mp) = mask_plan(inp, id, m, tx, ty, None) else { return Vec::new() };
- mp.effects.truncate(k);
- mask = Some(mp);
+ Job::Mask(layer_mask) => {
+ let Some(mut mask_stack) = mask_plan(inputs, id, layer_mask, tile_x, tile_y, None) else { return Vec::new() };
+
+ generator_sizes = mask_stack.effects.get(index).and_then(|effect| effect.curvature_sizes.clone());
+ mask_stack.effects.truncate(index);
+ mask_stack.start = start;
+ mask = Some(mask_stack);
}
- Job::Content(ch) => {
- nodes = plan(inp, &[id], &[ch], tx, ty, 0, Some(below));
- if let Some(c) = nodes.first_mut().and_then(|n| n.chans.first_mut()) {
- c.effects.truncate(k);
- c.start = None;
+ Job::Content(channel) => {
+ nodes = plan(inputs, &[id], &[channel], tile_x, tile_y, 0, Some(below));
+ if let Some(channel_plan) = nodes.first_mut().and_then(|node| node.chans.first_mut()) {
+ channel_plan.effects.truncate(index);
+ channel_plan.start = start;
}
}
}
- tile_texels(inp.gbuf, tx, ty)
- .map(|(x, y, o)| {
- let mut tex = Texel::new(inp, x, y, o, stroke_at(preview_tile, o));
- if !full.is_empty() {
- tex.anchors_below(&full, id);
+ tile_texels(inputs.gbuf, tile_x, tile_y)
+ .map(|(x, y, offset)| {
+ let mut texel = Texel::new(inputs, x, y, offset, stroke_at(preview_tile, offset));
+ if !anchor_nodes.is_empty() {
+ texel.anchors_below(&anchor_nodes, id);
}
- let v = match (&mask, nodes.first()) {
- (Some(mp), _) => [tex.mask(mp), 0.0, 0.0, 0.0],
- (None, Some(n)) => match n.chans.first().and_then(|c| tex.content(&n.content, c)) {
- Some((v, cov)) => [v[0] * cov, v[1] * cov, v[2] * cov, cov],
+
+ let value = match (&mask, nodes.first()) {
+ (Some(mask_stack), _) => {
+ let ramp = generator.map_or(0.0, |(generator, _)| texel.generator_ramp(generator, generator_sizes.as_deref()));
+ [texel.mask(mask_stack), ramp, 0.0, 0.0]
+ }
+ (None, Some(node)) => match node.chans.first().and_then(|channel_plan| texel.content(&node.content, channel_plan)) {
+ Some((color, coverage)) => [color[0] * coverage, color[1] * coverage, color[2] * coverage, coverage],
None => [0.0; 4],
},
(None, None) => [0.0; 4],
};
- (x, y, v)
+ (x, y, value)
})
.collect()
})
.collect();
- // Scatter into the region, a row of tiles at a time (the region is tile aligned).
- let n = (w * h) as usize;
- let mut orig = vec![0.0f32; n * comps];
- let mut cover = vec![0.0f32; n];
- let row_tiles = (rx1.div_ceil(TILE) - rx0 / TILE).max(1) as usize;
- let band = (TILE * w) as usize;
- orig.par_chunks_mut(band * comps).zip(cover.par_chunks_mut(band)).zip(parts.par_chunks(row_tiles)).for_each(|((orig, cover), row)| {
- for &(x, y, v) in row.iter().flatten() {
- let i = (((y - ry0) % TILE) * w + (x - rx0)) as usize;
- if let (Some(c), Some(px)) = (cover.get_mut(i), orig.get_mut(i * comps..(i + 1) * comps)) {
- *c = 1.0;
- px.copy_from_slice(&v[..comps]);
+
+ // Scatter into the region, a row of tiles at a time (the region is tile aligned)
+ let texel_count = (width * height) as usize;
+ let mut stack_values = vec![0.0f32; texel_count * components];
+ let mut cover = vec![0.0f32; texel_count];
+ let row_tiles = (region_right.div_ceil(TILE) - region_x / TILE).max(1) as usize;
+ let band = (TILE * width) as usize;
+ stack_values.par_chunks_mut(band * components).zip(cover.par_chunks_mut(band)).zip(parts.par_chunks(row_tiles)).for_each(|((stack_values, cover), row)| {
+ for &(x, y, value) in row.iter().flatten() {
+ let texel = (((y - region_y) % TILE) * width + (x - region_x)) as usize;
+ if let (Some(covered), Some(pixel)) = (cover.get_mut(texel), stack_values.get_mut(texel * components..(texel + 1) * components)) {
+ *covered = 1.0;
+ pixel.copy_from_slice(&value[..components]);
}
}
});
- // High pass centers on the channel's mid value (0 for signed channels like height).
- let mid = match job {
- Job::Content(ch) if ch.kind() == ChannelKind::Signed => 0.0,
+
+ // Release tile scatter data before allocating filter buffers
+ drop(parts);
+
+ // High pass centers on the channel's middle value (0 for signed channels like height)
+ let middle = match job {
+ Job::Content(channel) if channel.kind() == ChannelKind::Signed => 0.0,
_ => 0.5,
};
- // The filter at the radius of a tile filling `scale` of its atlas block (a smaller tile has
- // fewer texels per UV unit, so its filters reach fewer texels).
+
+ // A smaller UV tile has fewer texels per UV unit, so its filters reach fewer texels
let filtered = |scale: f32| -> Vec {
- let res = ((inp.tile_res() as f32 * scale).round() as u32).max(1);
- let r = neighbourhood(effects, res).map_or(r, |(_, radius, _)| radius.round().clamp(1.0, r as f32) as u32);
- if !blurs {
- return gather(op, &orig, &cover, comps, (rx0, ry0, w, h), r as f32, res, opacity);
+ let tile_resolution = ((inputs.tile_res() as f32 * scale).round() as u32).max(1);
+ if let Some((generator, blend)) = generator {
+ let texture_set = inputs.project.texture_set(inputs.ts).map_or(inputs.tile_res(), |set| set.resolution);
+ return generator_region(generator, blend, opacity, &stack_values, &cover, (region_x, region_y, width, height), (tile_resolution, texture_set));
}
- // Weighted so uncovered texels don't bleed in.
- let (wu, hu, ru) = (w as usize, h as usize, r as usize);
+ let scaled_radius = neighbourhood_filters(effects, tile_resolution)
+ .find(|filter| filter.0 == index)
+ .map_or(radius_texels, |filter| filter.1.round().clamp(1.0, radius_texels as f32) as u32);
+ if !is_box_blur(op) {
+ return gather(op, &stack_values, &cover, components, (region_x, region_y, width, height), scaled_radius as f32, tile_resolution, opacity);
+ }
+
+ // Weighted so uncovered texels don't bleed in
+ let (columns, rows, blur_radius) = (width as usize, height as usize, scaled_radius as usize);
let mut weights = cover.clone();
- blur(&mut weights, wu, hu, ru);
- let mut data = orig.clone();
- for p in 0..comps {
- let mut vals: Vec = orig.par_chunks(comps).map(|px| px.get(p).copied().unwrap_or(0.0)).collect();
- blur(&mut vals, wu, hu, ru);
- data.par_chunks_mut(comps).zip(vals.par_iter()).zip(weights.par_iter()).for_each(|((px, v), wt)| {
- // Content is premultiplied, so the mid value is too (coverage itself is kept).
- let cov = if comps == 4 { px.get(3).copied().unwrap_or(0.0) } else { 1.0 };
- if *wt > 1e-6
- && let Some(slot) = px.get_mut(p)
+ blur(&mut weights, columns, rows, blur_radius);
+ let mut filtered_values = stack_values.clone();
+ for component in 0..components {
+ let mut sums: Vec = stack_values.par_chunks(components).map(|pixel| pixel.get(component).copied().unwrap_or(0.0)).collect();
+ blur(&mut sums, columns, rows, blur_radius);
+ filtered_values.par_chunks_mut(components).zip(sums.par_iter()).zip(weights.par_iter()).for_each(|((pixel, sum), weight)| {
+ // Content is premultiplied, so the middle value is too (coverage itself is kept)
+ let coverage = if components == 4 { pixel.get(3).copied().unwrap_or(0.0) } else { 1.0 };
+ if *weight > MIN_COVERAGE_WEIGHT
+ && let Some(slot) = pixel.get_mut(component)
{
- let (o, blurred) = (*slot, v / wt);
- let filtered = match op {
- Op::Blur(Some(amount)) => o + amount * (o - blurred),
- Op::HighPass if p < 3 => o - blurred + mid * cov,
- // Away from 0 by at most the value itself: 0 at the edge, full inside.
- Op::Bevel if p < 3 => o.signum() * o.abs().min((2.0 * blurred * o.signum() - o.abs()).max(0.0)),
- Op::Glow(amount) if p < 3 => o + amount * blurred,
- Op::HighPass | Op::Bevel | Op::Glow(_) => o,
+ let (original, blurred) = (*slot, sum / weight);
+ let result = match op {
+ Op::Blur(Some(amount)) => original + amount * (original - blurred),
+ Op::HighPass if component < 3 => original - blurred + middle * coverage,
+ // Away from 0 by at most the value itself: 0 at the edge, full inside
+ Op::Bevel if component < 3 => original.signum() * original.abs().min((2.0 * blurred * original.signum() - original.abs()).max(0.0)),
+ Op::Glow(amount) if component < 3 => original + amount * blurred,
+ Op::HighPass | Op::Bevel | Op::Glow(_) => original,
_ => blurred,
};
- *slot = o + (filtered - o) * opacity;
+ *slot = original + (result - original) * opacity;
}
});
}
- data
+ filtered_values
};
- // Each block keeps the result at its tile's scale (blocks are TILE aligned).
- let scales = inp.project.texture_set(inp.ts).map(TextureSet::block_scales).unwrap_or_default();
- let mut levels: Vec =
- (ry0..ry1).step_by(TILE as usize).flat_map(|y| (rx0..rx1).step_by(TILE as usize).map(move |x| (x, y))).map(|(x, y)| scales.at(x, y)).collect();
+
+ // Each block keeps the result at its tile's scale (blocks are TILE aligned)
+ let scales = inputs.project.texture_set(inputs.ts).map(TextureSet::block_scales).unwrap_or_default();
+ let mut levels: Vec = (region_y..region_bottom)
+ .step_by(TILE as usize)
+ .flat_map(|y| (region_x..region_right).step_by(TILE as usize).map(move |x| (x, y)))
+ .map(|(x, y)| scales.at(x, y))
+ .collect();
levels.sort_by(f32::total_cmp);
levels.dedup();
- let (first, rest) = levels.split_first().map_or((1.0, &[][..]), |(f, r)| (*f, r));
- let mut data = filtered(first);
+ let (first, rest) = levels.split_first().map_or((1.0, &[][..]), |(first, rest)| (*first, rest));
+
+ // A generator stage's field is the mask alone
+ let field_components = if generator.is_some() { 1 } else { components };
+ let mut result = filtered(first);
for &scale in rest {
- let other = filtered(scale);
- let row = w as usize * comps;
- data.par_chunks_mut(row).zip(other.par_chunks(row)).enumerate().for_each(|(y, (dst, src))| {
- for (x, (d, s)) in dst.chunks_mut(comps).zip(src.chunks(comps)).enumerate() {
- if scales.at(rx0 + x as u32, ry0 + y as u32) == scale {
- d.copy_from_slice(s);
+ let rescaled = filtered(scale);
+ let row = width as usize * field_components;
+ result.par_chunks_mut(row).zip(rescaled.par_chunks(row)).enumerate().for_each(|(y, (target_row, source_row))| {
+ for (x, (target, source)) in target_row.chunks_mut(field_components).zip(source_row.chunks(field_components)).enumerate() {
+ if scales.at(region_x + x as u32, region_y + y as u32) == scale {
+ target.copy_from_slice(source);
}
}
});
}
- unpremultiply(&mut data, comps);
- Some(Field { x0: rx0, y0: ry0, w, h, comps, data })
+
+ unpremultiply(&mut result, field_components);
+ Some(Field { x0: region_x, y0: region_y, w: width, h: height, comps: field_components, data: result })
+}
+
+/// The mask over a region after a generator at its own resolution and blur: `stack` is (stack below, generator ramp) per texel, sizes in texels per side.
+fn generator_region(
+ generator: &Generator,
+ blend: BlendMode,
+ opacity: f32,
+ stack: &[f32],
+ cover: &[f32],
+ (region_x, region_y, width, height): (u32, u32, u32, u32),
+ (uv_tile, texture_set): (u32, u32),
+) -> Vec {
+ let (columns, rows) = (width as usize, height as usize);
+ let mut ramps: Vec = stack.par_chunks(2).map(|texel| texel.get(1).copied().unwrap_or(0.0)).collect();
+
+ // Coarser than the UV tile: averaged over cells, then the blur around them
+ let cell = generator.resolution.cell(uv_tile, texture_set) as usize;
+ if cell > 1 {
+ ramps = resampled_by_cells(&ramps, cover, (region_x as usize, region_y as usize, columns, rows), cell);
+ }
+
+ let blur_radius = generator.global.blur_radius_at(uv_tile).round() as usize;
+ if blur_radius > 0 {
+ let mut weights = cover.to_vec();
+ blur(&mut weights, columns, rows, blur_radius);
+ let mut sums: Vec = ramps.iter().zip(cover).map(|(ramp, covered)| ramp * covered).collect();
+ blur(&mut sums, columns, rows, blur_radius);
+ ramps.par_iter_mut().zip(sums.par_iter().zip(weights.par_iter())).for_each(|(ramp, (sum, weight))| {
+ if *weight > MIN_COVERAGE_WEIGHT {
+ *ramp = sum / weight;
+ }
+ });
+ }
+
+ // Finished and blended over the stack below, like the generator effect itself
+ stack
+ .par_chunks(2)
+ .zip(ramps.par_iter())
+ .map(|(texel, ramp)| {
+ let below = texel.first().copied().unwrap_or(0.0);
+ let generated = finish_generator(generator, *ramp);
+ below + (blend1(blend, below, generated) - below) * opacity
+ })
+ .collect()
+}
+
+/// `values` averaged over `cell` × `cell` texel cells on the mesh (`cover`), read back bilinearly between cell centers.
+fn resampled_by_cells(values: &[f32], cover: &[f32], (region_x, region_y, width, height): (usize, usize, usize, usize), cell: usize) -> Vec