Auto: Integrate main and correct FreeBSD help and runner guidance

Name the actual FreeBSD release runner and identify the Linux AppImage version check as non-blocking. Make the packager's installation example work for both FreeBSD archives and stop help output at the end of the documentation header.

Verified both extraction examples, native and cross-build smoke-test selection, the packaging dry run, and ShellCheck.
This commit is contained in:
chasse20 committed 2026-11-25 22:55:56 +00:00
commit c96c377b45
779 files changed
+86359 -9551

No files matched your search

+5
View File
@@ -1,2 +1,7 @@
[alias]
xtask = "run -p xtask --"
# An explicit level for dependencies: Cargo drops the profile's default debug level from crates only build scripts and
# macros use, and then clippy and test each build their own copy of them.
[profile.dev.package."*"]
debug = "line-tables-only"
+110
View File
@@ -0,0 +1,110 @@
{
"schema": "craft-nightly-release-policy/v3",
"repository": "storytold/texturecraft",
"repository_id": 1419654881,
"producer_workflow_id": null,
"producer_workflow_path": ".github/workflows/nightly.yml",
"producer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea",
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
"signer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea",
"release_branch": "release",
"manual_actors": [
"bflatastic",
"dylanmtaylor",
"echelon",
"FredApps",
"skylartaylor"
],
"max_age_seconds": 86400,
"candidate_policy": {
"schema": "craft-nightly-candidate-policy/v3",
"epoch": "texturecraft-nightly-20261124",
"repository": "storytold/texturecraft",
"branch": "main",
"required_workflows": [
{
"workflow_id": 384666426,
"workflow_path": ".github/workflows/ci.yml",
"jobs": [
{
"name": "gate / gate (ubuntu-24.04)",
"app_id": 15368,
"applicability": "required"
},
{
"name": "gate / gate (windows-latest)",
"app_id": 15368,
"applicability": "required"
}
]
}
],
"sonar": {
"organization": "storytold",
"project": "storytold_texturecraft",
"app_id": 12526,
"check_name": "SonarCloud Code Analysis",
"details_url": "https://sonarcloud.io/dashboard?id=storytold_texturecraft&branch=main",
"issue_types": [
"VULNERABILITY"
],
"accepted_conditions": [],
"required_conditions": [
{
"metric": "new_security_rating",
"comparator": "GT",
"error_threshold": "1"
},
{
"metric": "new_reliability_rating",
"comparator": "GT",
"error_threshold": "1"
},
{
"metric": "new_maintainability_rating",
"comparator": "GT",
"error_threshold": "1"
},
{
"metric": "new_coverage",
"comparator": "LT",
"error_threshold": "80"
},
{
"metric": "new_duplicated_lines_density",
"comparator": "GT",
"error_threshold": "3"
},
{
"metric": "new_security_hotspots_reviewed",
"comparator": "LT",
"error_threshold": "100"
}
],
"debt": []
}
},
"max_artifact_bytes": 2147483648,
"automatic_signer_actors": [],
"platforms": {
"windows-x86_64": {
"unsigned_artifact_name": "nightly-unsigned-windows-x86_64",
"trust": {
"publisher_subject": "CN=Learning Machines Inc, O=Learning Machines Inc, L=Atlanta, S=Georgia, C=US"
}
},
"linux-x86_64": {
"unsigned_artifact_name": "nightly-unsigned-linux-x86_64",
"trust": {
"fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"
}
},
"macos-aarch64": {
"unsigned_artifact_name": "nightly-unsigned-macos-aarch64",
"trust": {
"apple_team_id": "DJ6XS33FX8"
}
}
}
}
+91
View File
@@ -0,0 +1,91 @@
name: Nightly macOS build
# Builds the unsigned Apple-silicon TextureCraft Nightly (packaging/macos/nightly.sh) on a hosted
# macOS runner and checks the archive as the Launcher unpacks it, ending with the bundle's version
# query (packaging/macos/nightly-verify.sh --expect unsigned). No secrets and no environment: the real
# Nightly is signed and notarized by the shared release-ref signer (craft-common-actions), which calls
# packaging/macos/nightly-sign.sh.
on:
# macOS minutes are shared with release builds: pull requests run this only with the `full-ci`
# label, never by changed paths. `labeled` so adding it starts a run.
pull_request:
types: [opened, synchronize, reopened, labeled]
workflow_dispatch:
permissions:
contents: read
# A newer push to a labelled PR cancels its older run. Any event that will not build (no `full-ci`
# label, or another label added) gets a group of its own, so it never cancels a real build.
concurrency:
group: nightly-macos-${{ github.event_name == 'pull_request' && contains(github.event.pull_request.labels.*.name, 'full-ci') && (github.event.action != 'labeled' || github.event.label.name == 'full-ci') && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
build:
name: Nightly .app (aarch64, unsigned)
if: >-
github.event_name == 'workflow_dispatch' ||
(contains(github.event.pull_request.labels.*.name, 'full-ci') &&
(github.event.action != 'labeled' || github.event.label.name == 'full-ci'))
runs-on: macos-15
timeout-minutes: 90
env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
RUST_BACKTRACE: 1
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
# The release's pin (release.yml craft-fonts-ref), so the bundle's notices match a shipped build.
- name: Check out craft-fonts
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@605d58766e8f536564da8fc81d3676ac86816dea
with:
ref: aced4137c022f1f587624d48e81ec77e1914a9cc
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@605d58766e8f536564da8fc81d3676ac86816dea
- id: rust
uses: storytold/craft-common-actions/actions/rust-channel@605d58766e8f536564da8fc81d3676ac86816dea
with:
targets: aarch64-apple-darwin
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
with:
toolchain: ${{ steps.rust.outputs.toolchain }}
targets: ${{ steps.rust.outputs.targets }}
components: ${{ steps.rust.outputs.components }}
# A version of the prepared Nightly form for this commit; the real one comes from the feed's
# identity job. Only nightly.sh's input checks read it.
- name: Prepare a Nightly identity for this commit
run: |
set -euo pipefail
base="$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["version"].split("-")[0])')"
sha="$(git rev-parse HEAD)"
date="$(date -u +%Y-%m-%d)"
{
echo "TEXTURECRAFT_BUILD_SHA=$sha"
echo "TEXTURECRAFT_BUILD_DATE=$date"
echo "TEXTURECRAFT_VERSION=$base-nightly.${date//-/}.$GITHUB_RUN_NUMBER.$GITHUB_RUN_ATTEMPT.g${sha:0:12}"
} >>"$GITHUB_ENV"
- name: Build the unsigned Nightly bundle
env:
TEXTURECRAFT_BUILD_CHANNEL: nightly-v1
CARGO_TARGET_DIR: ${{ runner.temp }}/nightly-targets
DIST: ${{ runner.temp }}/nightly-dist
CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts
CRAFT_FONTS_REQUIRED: "1"
run: bash packaging/macos/nightly.sh --arch aarch64
- name: Check the archive and the bundle's version
run: bash packaging/macos/nightly-verify.sh --expect unsigned --input "$RUNNER_TEMP/nightly-dist/texturecraft-$TEXTURECRAFT_VERSION-macos-aarch64-nightly.zip"
# Keeps the verified unsigned zip briefly for keyless signer tests and hand testing. Unsigned only.
- name: Keep the unsigned archive
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: texturecraft-nightly-macos-aarch64-unsigned
path: ${{ runner.temp }}/nightly-dist/texturecraft-${{ env.TEXTURECRAFT_VERSION }}-macos-aarch64-nightly.zip
if-no-files-found: error
retention-days: 7
compression-level: 0
+42
View File
@@ -0,0 +1,42 @@
name: TextureCraft release-ref nightly signer
# Enabled for supervised manual dispatch on release. Main/release contents must match.
# A reusable callee does not change context; this must be a real top-level release dispatch.
on:
workflow_dispatch:
inputs:
producer_run_id:
description: Exact untrusted producer Actions run ID
required: true
type: string
producer_run_attempt:
description: Exact untrusted producer Actions run attempt
required: true
type: string
permissions: {}
concurrency:
group: texturecraft-nightly-release
cancel-in-progress: false
jobs:
release:
# Actual context guards: official repository, manual dispatch, real release branch.
if: >-
github.repository == 'storytold/texturecraft' &&
github.event_name == 'workflow_dispatch' &&
github.ref == 'refs/heads/release' && github.ref_type == 'branch'
permissions:
contents: write
actions: read
checks: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@605d58766e8f536564da8fc81d3676ac86816dea
with:
tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea
producer_run_id: ${{ inputs.producer_run_id }}
producer_run_attempt: ${{ inputs.producer_run_attempt }}
# No secrets: inherit or raw platform values in this caller. Only the isolated native
# callee job may bind the existing release environment and export keys in its signing step.
+34
View File
@@ -0,0 +1,34 @@
name: TextureCraft unsigned nightly
# Enabled for supervised manual runs by the reviewed manual actor only; no schedule yet.
# A later explicit opt-in may add a cadence (and turn on nightly-dispatch.yml with it).
on:
workflow_dispatch:
permissions:
contents: read
jobs:
unsigned:
# Actual context guards only; no inherited/platform secrets.
if: >-
github.repository == 'storytold/texturecraft' &&
github.ref == 'refs/heads/main' && github.ref_type == 'branch' &&
(github.event_name == 'schedule' || github.event_name == 'workflow_dispatch')
# Maximum for the reusable workflow. Its compiler narrows to contents/actions read;
# no OIDC, attestation write, release environment or platform secrets in compilation.
permissions:
contents: read
actions: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea
with:
tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea
app-name: texturecraft
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
craft-fonts-ref: aced4137c022f1f587624d48e81ec77e1914a9cc
# One producer run builds every listed platform for one all-or-nothing release. The pin is the
# craft-common-actions main commit that merged #339 (bounded lineage compares), on top of the
# Linux/macOS signer (#342).
platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'
+4
View File
@@ -21,3 +21,7 @@ jobs:
lint:
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
uses: storytold/craft-common-actions/.github/workflows/packaging-lint.yml@main
with:
# Runs the Nightly synthetic suites, the launcher tests and `bash -n` here, so the checks
# that need no compiler are part of CI rather than a local step.
extra-checks-script: packaging/nightly-checks.sh
+1
View File
@@ -49,3 +49,4 @@ jobs:
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }}
+6
View File
@@ -7,5 +7,11 @@ target/
/log
/secrets
/temp
# The shared nightly workflow checks these out into the workspace; `nightly_init` refuses a dirty tree.
/.nightly-tools
/.nightly-input
/craft-fonts
/craft-i18n
__pycache__/
*.pyc
*.tcraft.tmp
+13
View File
@@ -15,6 +15,7 @@ licensed and keep their license file next to them.
| `assets/app-icon/texturecraft.icns` | App icon (engraved zebra), macOS (16-1024 px) | Project owner (ArtCraft team) | Original artwork drawn in ArtCraft for TextureCraft, rendered by `packaging/icons.sh` | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) |
| `assets/app-icon/hicolor/{16x16,24x24,32x32,48x48,64x64,128x128,256x256,512x512}/apps/ai.storyteller.texturecraft.png` | App icon (engraved zebra), hicolor theme PNGs | Project owner (ArtCraft team) | Original artwork drawn in ArtCraft for TextureCraft, rendered by `packaging/icons.sh` | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) |
| `assets/app-icon/hicolor/scalable/apps/ai.storyteller.texturecraft.svg` | App icon (engraved zebra), hicolor scalable (copy of `texturecraft-small.svg`) | Project owner (ArtCraft team) | Original artwork drawn in ArtCraft for TextureCraft, vectorised with craftrules `vectorize_tile.py` | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) |
| `assets/app-icon/texturecraft-nightly{,-1024}.png`, `assets/app-icon/texturecraft-nightly.{icns,ico}`, `assets/app-icon/nightly/{16,24,32,48,64,128,256,512}.png` | Nightly app icons (engraved zebra on deep copper) | Project owner (ArtCraft team) | Project-owned stable icon renders, with the background recolored by `packaging/nightly-icons.py` ([provenance and hashes](assets/app-icon/nightly-provenance.json)) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) |
| `assets/app-icon/LICENSE.txt`, `assets/app-icon/README.md` | App icon licence and notes | TextureCraft contributors | original | MIT OR Apache-2.0 |
| `docs/images/texturecraft-workspace.png` | README screenshot: the TextureCraft workspace (a 1970s portable TV in aged cream plastic with a crayon doodle) | TextureCraft contributors | original screenshot of TextureCraft | MIT OR Apache-2.0 |
| `docs/images/texturecraft-bake.png` | README screenshot: bake mode | TextureCraft contributors | original screenshot of TextureCraft | MIT OR Apache-2.0 |
@@ -23,6 +24,7 @@ licensed and keep their license file next to them.
| `docs/images/texturecraft-light.png` | README screenshot: the light brightness level with the blue accent | TextureCraft contributors | original screenshot of TextureCraft | MIT OR Apache-2.0 |
| `docs/images/texturecraft-lantern.png` | README render: a storm lantern (original procedural mesh of lathes and swept wires, eight texture sets) in chipped red enamel, rust, soot, tarnished brass and glass with an emissive flame (`texturecraft-cli render --camera Hero --samples 2048`, 1200×900) | TextureCraft contributors | original model and render by TextureCraft | MIT OR Apache-2.0 |
| `docs/images/texturecraft-camera.png` | README render: a rangefinder camera (original procedural mesh) in black enamel worn to brass, leatherette, chrome and coated glass; the lens distance scale is an original image drawn in code (`texturecraft-cli render --camera Hero --samples 2048`, 1200×900) | TextureCraft contributors | original model and render by TextureCraft | MIT OR Apache-2.0 |
| `assets/hdr/studio_small_09_512.hdr` | Studio Small 09: a small photo studio with octaboxes on a white infinity cyc, equirect HDR reduced to 512×256 (2×2 box filter, Radiance RLE); lights the Properties panel's material orbs | Sergej Majboroda (Poly Haven) | [Poly Haven release](https://polyhaven.com/a/studio_small_09), [1K Radiance HDR](https://dl.polyhaven.org/file/ph-assets/HDRIs/hdr/1k/studio_small_09_1k.hdr) (MD5 `d5d7eb9d26d341d6aa4d11c1a54fd97c`) | [CC0 1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/) |
| `docs/brand/artcraft-*.svg`, `docs/brand/artcraft-*.png` | ArtCraft logo and mark | ArtCraft Team | storytold/craftrules `assets/brand/` | ArtCraft brand terms, not open source ([`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt)) |
| `crates/formats/src/mesh_import/usd/fixtures/crafted-references.usdc` | Synthetic USDC class/reference/time-sample acceptance fixture | ArtCraft Team and craft-libs contributors | [Pinned generator and provenance](crates/formats/src/mesh_import/usd/fixtures/README.md) | MIT (`crates/formats/src/mesh_import/usd/fixtures/LICENSE-MIT`) |
@@ -40,6 +42,17 @@ These come from Rust crate dependencies (not files in this repository) and keep
Without craft-fonts, Chinese, Japanese, Korean and Arabic UI text uses the operating system's fonts at run
time (nothing is bundled); see [docs/localization-parity.md](docs/localization-parity.md).
## Native eyedropper dependencies
| Crate | Use | Upstream | License |
|---|---|---|---|
| `raw-window-handle` | Identify native application windows | https://github.com/rust-windowing/raw-window-handle | MIT OR Apache-2.0 OR Zlib |
| `winsafe` | Windows pointer and event handling | https://github.com/rodrigocfd/winsafe | MIT |
| `xcap` | Windows screen pixel capture | https://github.com/nashaofu/xcap | Apache-2.0 |
| `widestring` | Windows string handling through `xcap` | https://github.com/VoidStarKat/widestring-rs | MIT OR Apache-2.0 |
| `x11rb` | X11 pointer and pixel capture | https://github.com/psychon/x11rb | MIT OR Apache-2.0 |
| `zbus` | Wayland desktop color-picker portal | https://github.com/z-galaxy/zbus | MIT |
## Procedural content (no asset files)
Built-in environments (`crates/render/src/ibl.rs`), smart materials and procedurals
Generated
+669 -11
View File
File diff suppressed because it is too large. Load diff
-4
View File
@@ -8,8 +8,6 @@ default-members = ["crates/core", "crates/texel", "crates/geom", "crates/compose
version = "0.6.1"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.95"
repository = "https://github.com/storytold/texturecraft"
[workspace.dependencies]
craft-usd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3" }
@@ -53,10 +51,8 @@ rfd = "0.17"
zip = { version = "9", default-features = false, features = ["deflate"] }
gltf = { version = "1.4", default-features = false, features = ["import", "utils", "names", "KHR_materials_emissive_strength"] }
flate2 = "1"
lz4_flex = { version = "0.11", default-features = false, features = ["safe-decode", "safe-encode"] }
quick-xml = "0.41"
mikktspace = { version = "0.3", default-features = false, features = ["glam"] }
proptest = "1"
rmcp = { version = "3.5", default-features = false, features = ["server", "macros", "transport-io"] }
tokio = { version = "1", features = ["rt-multi-thread", "macros", "io-std", "sync", "net", "io-util", "time"] }
schemars = "1"
+12
View File
@@ -12,6 +12,18 @@ Third-party material
This product bundles third-party material under its own licenses, listed below. The per-file
list (author, source, license) is in ATTRIBUTION.md.
Studio Small 09 HDR environment (assets/hdr/studio_small_09_512.hdr),
by Sergej Majboroda (Poly Haven) — CC0-1.0.
Source: https://polyhaven.com/a/studio_small_09 (1K HDR, reduced to 512x256).
Native eyedropper components:
- raw-window-handle — MIT OR Apache-2.0 OR Zlib. Copyright (c) 2019, 2020 Osspial.
- winsafe — MIT. Copyright (c) 2019-present, Rodrigo Cesar de Freitas Dias.
- xcap — Apache-2.0.
- widestring (through xcap on Windows) — MIT OR Apache-2.0.
- x11rb — MIT OR Apache-2.0. Copyright 2019 x11rb contributors.
- zbus — MIT. Copyright (c) 2024 Zeeshan Ali Khan and zbus contributors.
Phosphor Icons (compiled in through the egui-phosphor crate) — MIT.
egui default fonts (compiled in through the epaint_default_fonts crate): Ubuntu-Light — Ubuntu
Font Licence 1.0; Hack — MIT and Bitstream Vera License; Noto Emoji — SIL Open Font License 1.1;
+3 -3
View File
@@ -63,7 +63,7 @@ Why alpha. Mouse/keyboard tasks verified 3D/2D painting, undo/redo, material dra
and generator editing, UV rectangle fill, UI baking, native saving and texture export. Separate
command checks covered high-to-low transfer, UDIM sizes/packing and scene/material exports.
The interface is recognizably close in its painting, bake and export workspaces, but still lacks
mask-thumbnail effect menus, several fill controls and a MaterialX export option.
mask-thumbnail effect menus and several fill controls.
Generator depth is limited, bake equivalence is open,
and hardware/performance coverage is incomplete. There were **96 open issues** on the review date;
these include requests and older reports, not 96 reproduced defects. The published
@@ -118,7 +118,7 @@ menu entries. Feature rows overlap and are not an additional additive score.
| Baking | ~60% | TBD | All ten maps completed through the UI on CPU at 256 px and through commands on GPU at 128 px. Separate high/low normal/height transfer produced varying maps; cross-app pixel equivalence, larger assets and resolution-stable wear remain unproven |
| Viewport, shading and rendering | ~70% | TBD | PBR/IBL, extra shading lobes, 3D/2D views, displacement and CPU/GPU path-tracing paths. Matching material/display behavior, larger scenes and hardware ray tracing remain open |
| Color management | ~35% | TBD | Linear/sRGB handling, fixed export spaces and profile metadata; display model has Linear/ACES-filmic tone mapping. Configurable OCIO project/display workflows are absent |
| Texture and scene export | ~75% | TBD | Current PNG/UDIM/USD/GLB/MaterialX checks passed within scope. Output-package layout/content may be reworked; package contracts and consumers need separate validation. MaterialX UI output, complex materials and larger UDIM assets remain incomplete |
| Texture and scene export | ~75% | TBD | Current PNG/UDIM/USD/GLB/MaterialX checks passed within scope. Output-package layout/content may be reworked; package contracts and consumers need separate validation. MaterialX export covers OpenPBR only (no standard_surface); complex materials and larger UDIM assets remain incomplete |
| Read-only `.spp` compatibility | 0% | TBD after feasibility study | Planned; no reader, version matrix or import-fidelity corpus. `.tcraft` remains the save format |
| Workspace, panels and preferences | ~65% | TBD | Current views/layouts checked; narrow labels truncate. Incoming ArtCraft UI refactoring/shared components can change these surfaces; task, shortcut, accessibility and layout/preferences persistence checks must be repeated |
| Automation | ~80% | TBD | Command inspection and scripted editing/export work; UI, CLI and MCP surfaces share engine commands. This review exercised the control channel and CLI, not every MCP/tool path |
@@ -135,7 +135,7 @@ the legacy promise must not be carried forward automatically.
The [UI gap inventory](docs/ui-parity.md#missing-controls-and-workflows) records reproduction
routes and acceptance checks: mask context/save/export actions; independent U/V tiling,
filtering/wrap, physical-size and warp/per-tile projections; MaterialX UI output;
filtering/wrap, physical-size and warp/per-tile projections;
and configurable color-management settings. Generator depth and narrow-layout readability are
tracked as partial areas. Direct hardness/angle controls and polygon/UV rectangle fill already
exist; older reports must not turn them into fresh missing-feature claims.
+71 -2
View File
@@ -1,2 +1,71 @@
// The same build provenance and Windows icon/VERSIONINFO as the app; see that file.
include!("../texturecraft/build.rs");
// Provenance for the headless CLI: the same commit and date variables as the app, and (Windows
// only) its own icon and VERSIONINFO into `texturecraft-cli.exe`.
//
// This is deliberately not an `include!` of the app's build script: that one resolves a `#[path]`
// submodule and reads the Nightly channel, neither of which a CLI build has any use for, and a
// module path inside an included script is resolved from the included file, not from here.
use std::process::Command;
const ICON: &str = "../../assets/app-icon/texturecraft.ico";
fn main() {
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-changed={ICON}");
for var in ["TEXTURECRAFT_BUILD_SHA", "TEXTURECRAFT_BUILD_DATE", "TEXTURECRAFT_REQUIRE_WINRES", "SOURCE_DATE_EPOCH"] {
println!("cargo:rerun-if-env-changed={var}");
}
println!("cargo:rustc-env=TEXTURECRAFT_BUILD_SHA={}", env_or("TEXTURECRAFT_BUILD_SHA", git_sha));
println!("cargo:rustc-env=TEXTURECRAFT_BUILD_DATE={}", env_or("TEXTURECRAFT_BUILD_DATE", today));
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") {
windows_resources();
}
}
fn env_or(var: &str, fallback: fn() -> Option<String>) -> String {
std::env::var(var).ok().map(|v| v.trim().to_owned()).filter(|v| !v.is_empty()).or_else(fallback).unwrap_or_default()
}
fn git_sha() -> Option<String> {
let out = Command::new("git").args(["rev-parse", "HEAD"]).output().ok().filter(|o| o.status.success())?;
let sha = String::from_utf8(out.stdout).ok()?.trim().to_owned();
(sha.len() >= 7 && sha.bytes().all(|b| b.is_ascii_hexdigit())).then_some(sha)
}
/// UTC date of `SOURCE_DATE_EPOCH`, or of now.
fn today() -> Option<String> {
let secs = match std::env::var("SOURCE_DATE_EPOCH") {
Ok(v) => v.trim().parse::<u64>().ok()?,
Err(_) => std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).ok()?.as_secs(),
};
// Days since 1970-01-01 to a civil date (Howard Hinnant's algorithm, proleptic Gregorian).
let z = i64::try_from(secs / 86_400).ok()? + 719_468;
let era = z.div_euclid(146_097);
let doe = z.rem_euclid(146_097);
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let day = doy - (153 * mp + 2) / 5 + 1;
let month = if mp < 10 { mp + 3 } else { mp - 9 };
let year = yoe + era * 400 + i64::from(month <= 2);
Some(format!("{year:04}-{month:02}-{day:02}"))
}
fn windows_resources() {
let mut res = winresource::WindowsResource::new();
res.set_icon(ICON)
.set("ProductName", "TextureCraft")
.set("FileDescription", "TextureCraft command-line tool")
.set("CompanyName", "Learning Machines LLC")
.set("LegalCopyright", "Copyright (c) the TextureCraft contributors. MIT OR Apache-2.0.")
.set("OriginalFilename", "texturecraft-cli.exe")
.set("InternalName", "texturecraft-cli");
if let Err(e) = res.compile() {
if std::env::var_os("TEXTURECRAFT_REQUIRE_WINRES").is_some() {
println!("cargo::error=embedding Windows resources into texturecraft-cli.exe failed: {e}");
} else {
println!("cargo:warning=texturecraft-cli.exe built without icon/version resources: {e}");
}
}
}
+10
View File
@@ -120,8 +120,18 @@ fn version() -> String {
}
}
/// The desktop app's Nightly launch options. The CLI never takes them: a Nightly install ships the
/// GUI only, and a script that passes them to the CLI has the wrong program.
fn is_launch_profile_flag(arg: &str) -> bool {
arg == "--launch-profile" || arg == "--profile-root" || arg.starts_with("--launch-profile=") || arg.starts_with("--profile-root=")
}
fn main() {
let args: Vec<String> = std::env::args().skip(1).collect();
if let Some(flag) = args.iter().find(|arg| is_launch_profile_flag(arg.as_str())) {
eprintln!("texturecraft-cli: `{flag}` is a TextureCraft desktop launch option, not a CLI argument");
std::process::exit(2);
}
let code = match args.first().map(String::as_str) {
None => {
eprint!("{USAGE}");
-11
View File
@@ -16,17 +16,6 @@ fn cli_binary_path(runner_path: Option<OsString>) -> OsString {
runner_path.unwrap_or_else(|| env!("CARGO_BIN_EXE_texturecraft-cli").into())
}
#[test]
fn cli_binary_prefers_relocated_runner_path() {
let relocated = OsString::from("relocated archive/texturecraft-cli");
assert_eq!(cli_binary_path(Some(relocated.clone())), relocated);
}
#[test]
fn cli_binary_defaults_to_cargo_path() {
assert_eq!(cli_binary_path(None), OsString::from(env!("CARGO_BIN_EXE_texturecraft-cli")));
}
fn cli(args: &[&str]) -> Output {
Command::new(cli_binary()).args(args).output().unwrap()
}
+1 -2
View File
@@ -13,12 +13,11 @@ workspace = true
name = "texturecraft-web"
path = "src/main.rs"
[dependencies]
[target.'cfg(target_arch = "wasm32")'.dependencies]
texturecraft-engine = { workspace = true }
texturecraft-ui-egui = { workspace = true }
log = { workspace = true }
[target.'cfg(target_arch = "wasm32")'.dependencies]
# `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback.
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "persistence"] }
wasm-bindgen = "0.2"
+1 -1
View File
@@ -1,6 +1,6 @@
//! TextureCraft in the browser.
//!
//! Runs the same [`texturecraft_ui_egui::TextureCraftApp`] as the desktop app through eframe's web
//! Runs the same `TextureCraftApp` as the desktop app through eframe's web
//! runner (wgpu: WebGPU where available, WebGL2 otherwise). Build with `trunk build --release`
//! from this directory (`packaging/web/package.sh` zips the result).
//!
+7 -2
View File
@@ -15,7 +15,7 @@ texturecraft-engine = { workspace = true }
texturecraft-ui-egui = { workspace = true }
# The control channel's token, framing and connection limits (shared with `texturecraft-cli serve`).
texturecraft-automation = { workspace = true }
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "wayland", "x11", "persistence"] }
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "wayland", "x11", "persistence", "links"] }
egui = { workspace = true }
image = { workspace = true }
craft-image-codecs = { workspace = true }
@@ -30,7 +30,8 @@ ron = "0.12"
# borderless (src/window_frame.rs; winsafe is MIT, User32 only).
[target.'cfg(windows)'.dependencies]
winit = { version = "0.30", default-features = false }
winsafe = { version = "0.0.29", default-features = false, features = ["user"] }
# `shell` carries SetCurrentProcessExplicitAppUserModelID, the Nightly taskbar identity (src/process_identity.rs).
winsafe = { version = "0.0.29", default-features = false, features = ["user", "shell"] }
# The update helper is a copy of this program (`main`).
craft-update = { workspace = true }
@@ -38,5 +39,9 @@ craft-update = { workspace = true }
[target.'cfg(target_os = "macos")'.dependencies]
craft-menu = { workspace = true }
[dev-dependencies]
# The pointer-hold test drives the windowed app's frames (src/main.rs)
egui_kittest = { version = "0.37", features = ["eframe"] }
[build-dependencies]
winresource = "0.1"
+67 -10
View File
@@ -2,31 +2,78 @@
//
// Shared by `texturecraft` and `texturecraft-cli` (whose build.rs `include!`s this file).
//
// - Sets `TEXTURECRAFT_VERSION` for `env!`: the prepared Nightly feed identity when
// `TEXTURECRAFT_BUILD_CHANNEL=nightly-v1`, else the workspace package version. A Nightly build
// without a well-formed `TEXTURECRAFT_VERSION` fails rather than falling back to the Cargo
// version, so an archive can never carry the wrong identity.
// - Always sets `TEXTURECRAFT_BUILD_SHA` (full git commit) and `TEXTURECRAFT_BUILD_DATE`
// (`YYYY-MM-DD`, UTC) for `env!`. They come from the same-named environment variables (CI and
// packaging/env.sh set them), else from `git` and the clock (`SOURCE_DATE_EPOCH` wins for
// reproducible builds); either is an empty string when unknown, so source tarballs, wasm and
// offline builds still compile. Without the env vars the commit is read when this script runs,
// so a local build can show a stale commit; release builds always set the variable.
// - Windows targets only: embeds assets/app-icon/texturecraft.ico and VERSIONINFO into the exe.
// - Windows targets only: embeds the flavor's `assets/app-icon/*.ico` and VERSIONINFO into the exe.
// A missing resource compiler is a warning, so a cross-compile still links, unless
// `TEXTURECRAFT_REQUIRE_WINRES=1` (set by packaging/windows/package.ps1) makes it an error.
use std::process::Command;
#[path = "src/build_channel.rs"]
mod build_channel;
const ICON: &str = "../../assets/app-icon/texturecraft.ico";
use std::process::Command;
fn main() {
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-changed={ICON}");
for var in ["TEXTURECRAFT_BUILD_SHA", "TEXTURECRAFT_BUILD_DATE", "TEXTURECRAFT_REQUIRE_WINRES", "SOURCE_DATE_EPOCH"] {
println!("cargo:rerun-if-changed=src/build_channel.rs");
for icon in [build_channel::windows_icon_path(false), build_channel::windows_icon_path(true)] {
println!("cargo:rerun-if-changed={icon}");
}
for var in [
"TEXTURECRAFT_BUILD_SHA",
"TEXTURECRAFT_BUILD_DATE",
"TEXTURECRAFT_BUILD_CHANNEL",
"TEXTURECRAFT_VERSION",
"TEXTURECRAFT_OVERRIDE_VERSION",
"TEXTURECRAFT_REQUIRE_WINRES",
"SOURCE_DATE_EPOCH",
] {
println!("cargo:rerun-if-env-changed={var}");
}
println!("cargo:rustc-check-cfg=cfg(texturecraft_nightly_v1)");
let nightly = match std::env::var("TEXTURECRAFT_BUILD_CHANNEL").as_deref() {
Ok("nightly-v1") => {
println!("cargo:rustc-cfg=texturecraft_nightly_v1");
true
}
// An empty value (an unset CI input) means the default stable build.
Ok("stable" | "") | Err(std::env::VarError::NotPresent) => false,
_ => {
eprintln!("unsupported TEXTURECRAFT_BUILD_CHANNEL (expected stable or nightly-v1)");
std::process::exit(1);
}
};
// `TEXTURECRAFT_VERSION` is the feed identity the workflow exports; the packaging scripts
// (packaging/env.sh, nightly-common.sh, linux/package.sh) spell the same value
// `TEXTURECRAFT_OVERRIDE_VERSION`, so both name the version the binary reports.
let requested = ["TEXTURECRAFT_VERSION", "TEXTURECRAFT_OVERRIDE_VERSION"]
.into_iter()
.find_map(|name| std::env::var(name).ok().map(|value| value.trim().to_owned()).filter(|value| !value.is_empty()));
let built_version = if nightly {
match requested {
Some(version) if build_channel::is_nightly_version(&version) => version,
_ => {
eprintln!("nightly-v1 requires an explicit prepared feed identity in TEXTURECRAFT_VERSION");
std::process::exit(1);
}
}
} else {
std::env::var("CARGO_PKG_VERSION").unwrap_or_default()
};
println!("cargo:rustc-env=TEXTURECRAFT_VERSION={built_version}");
println!("cargo:rustc-env=TEXTURECRAFT_BUILD_SHA={}", env_or("TEXTURECRAFT_BUILD_SHA", git_sha));
println!("cargo:rustc-env=TEXTURECRAFT_BUILD_DATE={}", env_or("TEXTURECRAFT_BUILD_DATE", today));
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") {
windows_resources();
windows_resources(nightly, &built_version);
}
}
@@ -59,17 +106,27 @@ fn today() -> Option<String> {
Some(format!("{year:04}-{month:02}-{day:02}"))
}
fn windows_resources() {
fn windows_resources(nightly: bool, built_version: &str) {
let name = std::env::var("CARGO_PKG_NAME").unwrap_or_else(|_| "texturecraft".into());
let description = if name.ends_with("-cli") { "TextureCraft command-line tool" } else { "TextureCraft 3D texture painter" };
let description = if name.ends_with("-cli") {
if nightly { "TextureCraft Nightly command-line tool" } else { "TextureCraft command-line tool" }
} else if nightly {
"TextureCraft Nightly 3D texture painter"
} else {
"TextureCraft 3D texture painter"
};
let mut res = winresource::WindowsResource::new();
res.set_icon(ICON)
.set("ProductName", "TextureCraft")
res.set_icon(build_channel::windows_icon_path(nightly))
.set("ProductName", if nightly { "TextureCraft Nightly" } else { "TextureCraft" })
.set("FileDescription", description)
.set("CompanyName", "Learning Machines LLC")
.set("LegalCopyright", "Copyright (c) the TextureCraft contributors. MIT OR Apache-2.0.")
.set("OriginalFilename", &format!("{name}.exe"))
.set("InternalName", &name);
if nightly {
// The Launcher checks the PE ProductVersion against the exact feed identity, not FileVersion.
res.set("ProductVersion", built_version);
}
if let Err(e) = res.compile() {
if std::env::var_os("TEXTURECRAFT_REQUIRE_WINRES").is_some() {
println!("cargo::error=embedding Windows resources into {name}.exe failed: {e}");
+62
View File
@@ -0,0 +1,62 @@
//! The build-time nightly identity shared by the build script and its pure regression tests.
//!
//! `build.rs` includes this file (`#[path = "src/build_channel.rs"]`) and the app compiles it for
//! the same checks, so the icon and the version shape cannot drift apart between them.
/// `X.Y.Z-nightly.YYYYMMDD.<run>.<attempt>.g<sha12>`, the Launcher's immutable feed identity.
pub fn is_nightly_version(version: &str) -> bool {
let Some((base, suffix)) = version.split_once("-nightly.") else { return false };
let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
let base: Vec<_> = base.split('.').collect();
let parts: Vec<_> = suffix.split('.').collect();
base.len() == 3
&& base.iter().all(|s| digits(s))
&& parts.len() == 4
&& parts[0].len() == 8
&& digits(parts[0])
&& digits(parts[1])
&& digits(parts[2])
&& parts[3].strip_prefix('g').is_some_and(|sha| sha.len() == 12 && sha.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)))
}
/// The Windows icon embedded in the executable: the nightly art only in a nightly build.
pub fn windows_icon_path(nightly: bool) -> &'static str {
if nightly { "../../assets/app-icon/texturecraft-nightly.ico" } else { "../../assets/app-icon/texturecraft.ico" }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn windows_resource_uses_the_flavor_specific_icon_without_changing_stable() {
assert_eq!(windows_icon_path(false), "../../assets/app-icon/texturecraft.ico");
assert_eq!(windows_icon_path(true), "../../assets/app-icon/texturecraft-nightly.ico");
}
#[test]
fn explicit_feed_identity_is_required_for_a_nightly_build() {
assert!(is_nightly_version("0.23.1-nightly.20261120.17.1.gabcdef012345"));
for invalid in [
"",
"0.23.1",
"0.23.1-nightly",
"0.23.1-nightly.20261120",
"0.23.1-nightly.20261120.17.1.gABCDEF012345",
"0.23.1-nightly.20261120.17.1.gabcdef012345\n",
] {
assert!(!is_nightly_version(invalid), "{invalid:?}");
}
}
#[test]
fn version_cannot_inject_a_path_or_an_extra_build_directive() {
for invalid in [
"../0.23.1-nightly.20261120.1.1.gabcdef012345",
"0.23.1-nightly.20261120.1.1.gabcdef012345/other",
"0.23.1-nightly.20261120.1.1.gabcdef012345\ncargo:rustc-cfg=other",
] {
assert!(!is_nightly_version(invalid));
}
}
}
+94
View File
@@ -0,0 +1,94 @@
//! The build-time channel, which is distinct from a launch selector: no runtime environment can
//! promote a stable build into the Nightly one.
use crate::launch_profile::Profile;
use std::ffi::OsString;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BuildFlavor {
Stable,
NightlyV1,
}
/// `TEXTURECRAFT_BUILD_CHANNEL=nightly-v1` at compile time (`build.rs`).
pub const COMPILED: BuildFlavor = if cfg!(texturecraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable };
/// The version this binary was built as: the prepared feed identity in a nightly build, else the
/// workspace version (`build.rs` bakes it so both flavors read it the same way).
pub const BUILT_VERSION: &str = env!("TEXTURECRAFT_VERSION");
/// A nightly build starts only with its profile, and a stable build only without one.
pub fn require_profile(flavor: BuildFlavor, profile: &Profile) -> Result<(), String> {
match (flavor, profile.is_nightly()) {
(BuildFlavor::NightlyV1, false) => Err("Open TextureCraft Nightly from ArtCraft Launcher".into()),
(BuildFlavor::Stable, true) => Err("This is a stable TextureCraft build; nightly-v1 requires the nightly build".into()),
_ => Ok(()),
}
}
/// A refused nightly start explains itself in a native dialog: a release Windows build has no
/// console, and a Dock launch on macOS has none either.
pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool {
desktop_session && flavor == BuildFlavor::NightlyV1
}
/// `--version` or `-V` alone; a file called `--version` after `--` is never a query.
pub fn version_query(args: &[OsString]) -> bool {
matches!(args, [arg] if arg == "--version" || arg == "-V")
}
/// The line `--version` prints: `<App> <version> (nightly-v1)` in a nightly build, exactly as the
/// Launcher and the release smoke test read it.
pub fn version(flavor: BuildFlavor) -> String {
match flavor {
BuildFlavor::Stable => format!("TextureCraft {BUILT_VERSION}"),
BuildFlavor::NightlyV1 => format!("TextureCraft {BUILT_VERSION} (nightly-v1)"),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_a_nightly_desktop_refusal_requests_a_native_dialog() {
assert!(needs_native_error(BuildFlavor::NightlyV1, true));
assert!(!needs_native_error(BuildFlavor::NightlyV1, false));
assert!(!needs_native_error(BuildFlavor::Stable, true));
assert!(!needs_native_error(BuildFlavor::Stable, false));
}
#[test]
fn nightly_build_without_a_profile_is_refused_before_startup() {
let started = std::cell::Cell::new(false);
let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true));
assert!(result.unwrap_err().contains("ArtCraft Launcher"));
assert!(!started.get());
}
#[test]
fn stable_and_nightly_flavors_accept_only_their_own_profile() {
let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root"));
assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok());
assert!(require_profile(BuildFlavor::Stable, &nightly).is_err());
assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok());
}
#[test]
fn the_nightly_version_line_is_exact_and_says_its_channel() {
let nightly = version(BuildFlavor::NightlyV1);
assert!(nightly.starts_with("TextureCraft "), "{nightly}");
assert!(nightly.ends_with(" (nightly-v1)"), "{nightly}");
assert_eq!(nightly, format!("TextureCraft {} (nightly-v1)", BUILT_VERSION));
assert_eq!(version(BuildFlavor::Stable), format!("TextureCraft {BUILT_VERSION}"));
}
#[test]
fn only_a_bare_version_flag_is_a_query() {
assert!(version_query(&["--version".into()]));
assert!(version_query(&["-V".into()]));
assert!(!version_query(&["--".into(), "--version".into()]));
assert!(!version_query(&["--version".into(), "--version".into()]));
assert!(!version_query(&[]));
}
}
+21 -26
View File
@@ -134,7 +134,7 @@ fn serve(stream: TcpStream, token: &str, tx: &Sender<ControlRequest>, ctx: &egui
#[cfg(test)]
mod tests {
use std::io::BufRead;
use std::io::{BufRead, Read};
use super::*;
@@ -196,33 +196,28 @@ mod tests {
assert_eq!(call(&mut w, &mut r, r#"{"id":4,"method":"ping"}"#).unwrap()["id"], 4, "bad JSON keeps an authenticated connection");
}
fn assert_reply(reader: &mut BufReader<TcpStream>, expected: Value) -> std::io::Result<()> {
let expected = format!("{expected}\n");
let mut received = vec![0; expected.len()];
reader.read_exact(&mut received)?;
assert_eq!(received, expected.as_bytes(), "unexpected control server reply");
Ok(())
}
#[test]
fn connections_are_limited_and_idle_ones_time_out() {
fn authenticated_connections_hold_server_slots() -> std::io::Result<()> {
let addr = server();
let idle: Vec<_> = (0..MAX_CONNECTIONS).map(|_| connect(addr)).collect();
// Let the server take every idle connection before the one over the limit.
std::thread::sleep(Duration::from_millis(300));
// Read without writing: the server closes at once, and unread input would reset the
// connection before its reply arrives.
let (_, mut r) = connect(addr);
let mut full = String::new();
r.read_line(&mut full).unwrap();
assert_eq!(serde_json::from_str::<Value>(&full).unwrap()["error"], "too many connections");
// Unauthenticated connections are closed after AUTH_TIMEOUT, which frees their slots.
for (_, mut r) in idle {
let mut rest = String::new();
assert_eq!(r.read_line(&mut rest).unwrap(), 0);
}
// A slot frees once its thread has ended, which can trail the client's EOF a little.
let right = format!(r#"{{"id":1,"method":"auth","params":{{"token":"{TOKEN}"}}}}"#);
let authed = (0..50).any(|_| {
let (mut w, mut r) = connect(addr);
let ok = call(&mut w, &mut r, &right).is_some_and(|v| v["ok"] == true);
if !ok {
std::thread::sleep(Duration::from_millis(100));
}
ok
});
assert!(authed, "slots are freed after the auth deadline");
let mut held = Vec::with_capacity(MAX_CONNECTIONS);
for _ in 0..MAX_CONNECTIONS {
let (mut writer, mut reader) = connect(addr);
writeln!(writer, "{right}")?;
// The reply confirms that this connection is holding a slot.
assert_reply(&mut reader, json!({"ok": true, "id": 1}))?;
held.push((writer, reader));
}
let (_writer, mut reader) = connect(addr);
assert_reply(&mut reader, json!({"id": null, "ok": false, "error": "too many connections"}))
}
}
+217
View File
@@ -0,0 +1,217 @@
//! The Launcher's nightly-v1 bootstrap, selected before logging, updates, fonts or saved state.
//! Stable launches keep their arguments and directory policy unchanged, and no environment is
//! mutated: the profile is a value this process reads, not a variable it exports.
use std::ffi::OsString;
use std::path::{Component, Path, PathBuf};
use std::sync::OnceLock;
pub const VERSION: &str = "nightly-v1";
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Profile {
Stable,
NightlyV1(PathBuf),
}
impl Profile {
pub fn is_nightly(&self) -> bool {
matches!(self, Self::NightlyV1(_))
}
pub fn root(&self) -> Option<&Path> {
match self {
Self::Stable => None,
Self::NightlyV1(root) => Some(root),
}
}
}
#[derive(Debug, PartialEq, Eq)]
pub struct Launch {
pub profile: Profile,
pub args: Vec<OsString>,
}
static PROFILE: OnceLock<Profile> = OnceLock::new();
pub fn current() -> &'static Profile {
PROFILE.get().unwrap_or(&Profile::Stable)
}
pub fn install(profile: Profile) -> Result<(), String> {
PROFILE.set(profile).map_err(|_| "the launch profile was already selected".into())
}
/// Recognize only the agreed literal selector/root pair before `--`. Everything after it is a
/// file, even when it looks like a profile flag. No filesystem or startup hook runs here.
pub fn parse(args: Vec<OsString>) -> Result<Launch, String> {
let mut selector = None;
let mut root = None;
let mut other = Vec::new();
let mut files = Vec::new();
let mut iter = args.iter();
let mut delimiter = false;
while let Some(arg) = iter.next() {
if arg == "--" {
delimiter = true;
files.extend(iter.cloned());
break;
}
if arg == "--launch-profile" || arg == "--profile-root" {
let slot = if arg == "--launch-profile" { &mut selector } else { &mut root };
if slot.is_some() {
return Err("the profile selector and root must each occur exactly once".into());
}
let value = iter.next().filter(|v| !v.is_empty()).ok_or("the profile selector/root needs a value")?;
if value.to_string_lossy().starts_with("--") {
return Err("the profile selector/root needs a value".into());
}
*slot = Some(value.clone());
} else if arg.to_string_lossy().starts_with("--launch-profile=") || arg.to_string_lossy().starts_with("--profile-root=") {
return Err("the nightly protocol requires separate literal selector/root argument tokens".into());
} else {
other.push(arg.clone());
}
}
match (selector, root) {
(None, None) => Ok(Launch { profile: Profile::Stable, args }),
(Some(version), Some(root)) if version == VERSION => {
if !delimiter || !other.is_empty() {
return Err("nightly-v1 accepts only its selector/root followed by -- and file names".into());
}
let root = PathBuf::from(root);
if !root.is_absolute() || root.components().any(|c| matches!(c, Component::ParentDir)) {
return Err("the nightly profile root must be absolute and contain no parent traversal".into());
}
Ok(Launch { profile: Profile::NightlyV1(root), args: std::iter::once(OsString::from("--")).chain(files).collect() })
}
(Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".into()),
_ => Err("--launch-profile and --profile-root must be supplied together".into()),
}
}
/// The Launcher's version check: the selector/root pair followed by exactly `--version` (or `-V`),
/// answered like a plain version query. Only [`parse`]'s lexical checks apply; the root is never
/// validated or touched, and `-- --version` stays a file name.
pub fn version_query(args: &[OsString]) -> bool {
let Some((last, pair)) = args.split_last() else { return false };
if last != "--version" && last != "-V" {
return false;
}
let lexical = pair.iter().cloned().chain(std::iter::once(OsString::from("--"))).collect();
matches!(parse(lexical), Ok(Launch { profile: Profile::NightlyV1(_), args }) if args.len() == 1)
}
/// Validation finishes before the caller's first startup effect. Stable never calls the nightly
/// root validator, so its old directory resolution stays unchanged.
pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result<PathBuf, String>) -> Result<Launch, String> {
if let Profile::NightlyV1(root) = &launch.profile {
launch.profile = Profile::NightlyV1(validate(root)?);
}
Ok(launch)
}
/// Resolve the selected private root before the caller's first startup effect.
pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option<OsString>, exe: Option<&Path>) -> Result<PathBuf, String> {
crate::profile_root::validate(root, env, exe, crate::profile_root::ensure_writable)
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::Cell;
fn args(values: &[&str]) -> Vec<OsString> {
values.iter().map(OsString::from).collect()
}
fn absolute() -> &'static str {
if cfg!(windows) { r"C:\NightlyData\profiles\texturecraft" } else { "/nightly-data/profiles/texturecraft" }
}
fn nightly() -> Vec<OsString> {
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"])
}
#[test]
fn stable_arguments_and_directory_policy_are_unchanged() {
for argv in [args(&[]), args(&["model.glb"]), args(&["--gpu", "nvidia"]), args(&["--", "--launch-profile", "model.glb"])] {
let launch = prepare(parse(argv.clone()).unwrap(), |_| panic!("stable must never validate a nightly root")).unwrap();
assert_eq!(launch, Launch { profile: Profile::Stable, args: argv });
}
}
#[test]
fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() {
let mut argv = nightly();
argv.extend(args(&["--profile-root", "model with spaces.glb"]));
let launch = parse(argv).unwrap();
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
assert_eq!(launch.args, args(&["--", "--profile-root", "model with spaces.glb"]));
}
#[test]
fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() {
for argv in [
args(&["--launch-profile", VERSION]),
args(&["--profile-root", absolute()]),
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--launch-profile", VERSION, "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", "", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--gpu", "nvidia", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute()]),
args(&["--launch-profile=nightly-v1", "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--profile-root=/nightly-data/profiles/texturecraft", "--"]),
] {
assert!(parse(argv.clone()).is_err(), "{argv:?}");
}
}
#[test]
fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() {
let pair = &["--launch-profile", VERSION, "--profile-root", absolute()];
let reversed = &["--profile-root", absolute(), "--launch-profile", VERSION];
for flag in ["--version", "-V"] {
for form in [pair, reversed] {
let mut argv = args(form);
argv.push(flag.into());
assert!(version_query(&argv), "{argv:?}");
}
}
for argv in [
args(&["--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--gpu", "nvidia", "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--version"]),
args(&["--version", "--launch-profile", VERSION, "--profile-root", absolute()]),
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--version"]),
args(&["--launch-profile", VERSION, "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--help"]),
] {
assert!(!version_query(&argv), "{argv:?}");
}
// Outside the query the strict protocol still refuses the version flag.
assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err());
}
#[test]
fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() {
let reached = Cell::new(false);
let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".into())).map(|_| reached.set(true));
assert!(result.is_err());
assert!(!reached.get());
}
#[test]
fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() {
let checked = PathBuf::from(absolute()).join("checked");
let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap();
assert_eq!(launch.profile.root(), Some(checked.as_path()));
assert!(launch.profile.is_nightly());
}
}
+320 -28
View File
@@ -5,11 +5,22 @@
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#[cfg(test)]
mod build_channel;
mod build_flavor;
mod control_server;
mod gpu;
mod launch_profile;
mod nightly_session;
mod process_identity;
mod profile_root;
mod window_frame;
use std::ffi::OsString;
use launch_profile::Profile;
use texturecraft_engine::Session;
use texturecraft_ui_egui::os_window::{self, LaunchIdentity};
use texturecraft_ui_egui::titlebar::TitleBar;
use texturecraft_ui_egui::ui_state_store;
use texturecraft_ui_egui::{TextureCraftApp, UiState};
@@ -17,14 +28,25 @@ use texturecraft_ui_egui::{TextureCraftApp, UiState};
/// The app name eframe keeps the settings under (`eframe::storage_dir`).
const APP_NAME: &str = "TextureCraft";
/// The data folder Dylan's #801 packaging lets a Stable wrapper set. A Nightly launch never reads
/// it: its profile arrives as the Launcher's literal selector/root pair, and nothing else.
const DATA_DIR_ENV: &str = "TEXTURECRAFT_DATA_DIR";
/// The window's size when it opens, in points.
const DEFAULT_SIZE: [f32; 2] = [1600.0, 960.0];
/// The smallest size the window can be resized to, in points.
const MIN_SIZE: [f32; 2] = [960.0, 600.0];
const ICON_PNG: &[u8] = include_bytes!("../../../assets/app-icon/hicolor/256x256/apps/ai.storyteller.texturecraft.png");
/// The Nightly window icon: the same artwork on the deeper background the package icon uses.
const NIGHTLY_ICON_PNG: &[u8] = include_bytes!("../../../assets/app-icon/texturecraft-nightly.png");
/// The version line: a Nightly build names its exact feed identity and channel, and every other
/// build keeps the workspace version with the commit and date it was built from.
fn version() -> String {
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 {
return build_flavor::version(build_flavor::COMPILED);
}
let sha = env!("TEXTURECRAFT_BUILD_SHA");
let short = sha.get(..7).unwrap_or(sha);
let date = env!("TEXTURECRAFT_BUILD_DATE");
@@ -44,15 +66,23 @@ struct Args {
power_pref: Option<eframe::wgpu::PowerPreference>,
}
fn parse_args() -> Result<Option<Args>, String> {
parse_args_from(std::env::args().skip(1))
}
fn parse_args_from<I: IntoIterator<Item = String>>(it: I) -> Result<Option<Args>, String> {
let mut args = Args { file: None, control: None, empty: false, gpu: None, power_pref: None };
let mut it = it.into_iter();
// Everything after `--` is a file, even when it looks like an option: the Launcher's nightly
// protocol passes the selected file that way (and a file may be called `--version`).
let mut after_delimiter = false;
while let Some(a) = it.next() {
if after_delimiter {
// A Launcher hand-off may carry more than one file. Opening the first one beats a
// silent exit on a Windows build, which has no console to show the refusal on.
if args.file.is_none() {
args.file = Some(a);
}
continue;
}
match a.as_str() {
"--" => after_delimiter = true,
"--version" | "-V" => {
println!("{}", version());
return Ok(None);
@@ -119,7 +149,8 @@ fn initial_session(args: &Args) -> Session {
}
fn icon() -> Option<egui::IconData> {
let img = craft_image_codecs::decode(ICON_PNG).ok()?;
let png = if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 { NIGHTLY_ICON_PNG } else { ICON_PNG };
let img = craft_image_codecs::decode(png).ok()?;
Some(egui::IconData { rgba: img.to_rgba8(), width: img.width(), height: img.height() })
}
@@ -134,13 +165,39 @@ fn set_taskbar_icon(w: &winit::window::Window) {
}
}
/// Directory for saved settings, UI state, and error logs: a Nightly launch's validated profile,
/// else `TEXTURECRAFT_DATA_DIR` (when non-empty, as a Stable package wrapper sets it), else
/// eframe's own folder for this app.
fn storage_dir() -> Option<std::path::PathBuf> {
settings_folder(
launch_profile::current().root(),
std::env::var_os(DATA_DIR_ENV).filter(|v| !v.is_empty()).map(std::path::PathBuf::from),
eframe::storage_dir(APP_NAME),
)
}
/// The settings folder, in the order a launch decides it: a Nightly profile, a Stable wrapper's
/// `TEXTURECRAFT_DATA_DIR`, else eframe's own folder for this app.
///
/// The last one is passed in rather than left to eframe. With `with_app_id` set (the Linux window
/// class the Stable entry needs), eframe derives its folder from the app id, so Stable's `app.ron`
/// — window state and the user's export presets — would move to `ai.storyteller.texturecraft` while
/// `ui.json` and `errors.log` stayed behind. `persistence_path` therefore names the file explicitly.
fn settings_folder(
profile: Option<&std::path::Path>,
wrapper_dir: Option<std::path::PathBuf>,
legacy: Option<std::path::PathBuf>,
) -> Option<std::path::PathBuf> {
profile.map(std::path::Path::to_path_buf).or(wrapper_dir).or(legacy)
}
/// Preferences needed before opening the initial project or window, with legacy storage fallback.
fn saved_prefs(ui_file: Option<&std::path::Path>, persistence_path: Option<&std::path::Path>) -> texturecraft_ui_egui::state::Prefs {
if let Some(ui) = ui_file.and_then(ui_state_store::read) {
return ui.prefs;
}
let file = persistence_path.map(std::path::Path::to_path_buf).or_else(|| eframe::storage_dir(APP_NAME).map(|folder| folder.join("app.ron")));
let file = persistence_path.map(std::path::Path::to_path_buf).or_else(|| storage_dir().map(|folder| folder.join("app.ron")));
let saved = file.and_then(|file| std::fs::read_to_string(file).ok());
let entries = saved.and_then(|text| ron::from_str::<std::collections::HashMap<String, String>>(&text).ok());
entries.and_then(|entries| ron::from_str::<UiState>(entries.get("ui")?).ok()).map(|ui| ui.prefs).unwrap_or_default()
@@ -151,6 +208,10 @@ fn saved_prefs(ui_file: Option<&std::path::Path>, persistence_path: Option<&std:
struct Shell {
app: TextureCraftApp,
window_frame: Option<window_frame::WindowFrameFn>,
/// Runs once when the window closes. On macOS that is the only place a clean quit is handled:
/// Cmd+Q ends the process inside AppKit's terminate, after eframe's `on_exit` and before
/// `eframe::run_native` returns, so the Nightly session record is finished here, not there.
exit_hook: Option<Box<dyn FnOnce()>>,
#[cfg(target_os = "macos")]
movable: Option<bool>,
}
@@ -164,12 +225,14 @@ impl eframe::App for Shell {
self.app.save(storage);
}
fn raw_input_hook(&mut self, _ctx: &egui::Context, _raw: &mut egui::RawInput) {
// winit gives the window its caption back when it changes the window's flags (maximize,
// restore, …): take it off again before the frame is laid out.
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
// Restore the frameless style after winit changes the window flags
if let Some(guard) = self.window_frame.as_mut() {
guard();
}
// The app's own hook: a drag holding the pointer reads its moves from it
self.app.raw_input_hook(ctx, raw);
}
fn logic(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) {
@@ -181,6 +244,12 @@ impl eframe::App for Shell {
#[cfg(target_os = "macos")]
texturecraft_ui_egui::titlebar::sync_native(&self.app.title_bar, ui, frame, &mut self.movable);
}
fn on_exit(&mut self) {
if let Some(hook) = self.exit_hook.take() {
hook();
}
}
}
/// A script driving the app gets no network check and no update prompt over its window.
@@ -188,13 +257,97 @@ fn checks_for_updates_at_start(control: Option<u16>) -> bool {
control.is_none()
}
/// The AppUserModelID a Nightly window is grouped under, set before any native window exists.
fn initialize_nightly_process_identity() -> Result<(), process_identity::IdentityError> {
process_identity::initialize(build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1, os_window::id_for(LaunchIdentity::NightlyV1))
}
/// A refused Nightly start explains itself in a dialog where there is a desktop to show one.
fn report_launch_profile_error(error: &str) {
eprintln!("texturecraft: {error}");
let desktop_session = cfg!(windows)
|| cfg!(target_os = "macos")
|| (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty())));
if build_flavor::needs_native_error(build_flavor::COMPILED, desktop_session) {
if let Err(error) = initialize_nightly_process_identity() {
eprintln!("texturecraft: {error}");
return;
}
#[cfg(any(windows, target_os = "linux", target_os = "macos"))]
let _ = rfd::MessageDialog::new()
.set_title(os_window::name_for(LaunchIdentity::NightlyV1))
.set_description(error)
.set_level(rfd::MessageLevel::Error)
.set_buttons(rfd::MessageButtons::Ok)
.show();
}
}
/// Select the immutable launch profile before any startup service or side effect, and answer the
/// Launcher's version queries before root validation, logging, IPC or a window. `None` means the
/// launch is already answered and the process returns.
fn prepare_launch() -> Option<Vec<OsString>> {
let argv: Vec<OsString> = std::env::args_os().skip(1).collect();
// Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root <dir>
// --version`: both are answered here, with nothing but standard output written.
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv)) {
use std::io::Write as _;
let _ = writeln!(std::io::stdout(), "{}", build_flavor::version(build_flavor::COMPILED));
return None;
}
let early = launch_profile::parse(argv)
.and_then(|launch| {
build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?;
initialize_nightly_process_identity().map_err(|error| error.to_string())?;
Ok(launch)
})
.and_then(|launch| {
launch_profile::prepare(launch, |root| launch_profile::validate_root(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref()))
})
.unwrap_or_else(|error| {
report_launch_profile_error(&error);
std::process::exit(2)
});
let identity = if early.profile.is_nightly() { LaunchIdentity::NightlyV1 } else { LaunchIdentity::Stable };
if let Err(error) = launch_profile::install(early.profile).and_then(|()| os_window::select_identity(identity)) {
report_launch_profile_error(&error);
std::process::exit(2);
}
if let Profile::NightlyV1(root) = launch_profile::current() {
// Every data folder follows the profile before the first one is used.
texturecraft_ui_egui::set_data_root(root.clone());
texturecraft_ui_egui::os_window::set_display_version(build_flavor::BUILT_VERSION.to_owned());
}
Some(early.args)
}
/// The launch arguments as text. A Nightly protocol argument is a path the app opens, so a value
/// that is not valid Unicode is refused rather than silently replaced.
fn launch_arguments(arguments: Vec<OsString>) -> Result<Vec<String>, String> {
arguments.into_iter().map(|value| value.into_string().map_err(|_| "an argument is not valid Unicode".to_string())).collect()
}
fn main() {
// Windows: the update helper is a copy of this program started with `--finish-update`
// Windows: the update helper is a copy of this program started with `--finish-update`. A
// Nightly install is updated by ArtCraft Launcher, so it never installs an update itself.
#[cfg(windows)]
if let Some(result) = craft_update::self_update::finish(&texturecraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>()) {
if build_flavor::COMPILED == build_flavor::BuildFlavor::Stable
&& let Some(result) = craft_update::self_update::finish(&texturecraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>())
{
std::process::exit(i32::from(result.is_err()));
}
let args = match parse_args() {
// Windows: the eyedropper's pointer keeper (screen_pick) is a copy of this program started with
// its own argument. It reads no user state and is started without the profile tokens, so it
// runs before the launch protocol would refuse it.
#[cfg(windows)]
if std::env::args_os().nth(1).is_some_and(|arg| arg == texturecraft_ui_egui::screen_pick::KEEPER_ARG) {
std::process::exit(texturecraft_ui_egui::screen_pick::keep_pointer());
}
let Some(arguments) = prepare_launch() else { return };
let nightly = launch_profile::current().is_nightly();
let args = match launch_arguments(arguments).and_then(parse_args_from) {
Ok(Some(a)) => a,
Ok(None) => return,
Err(e) => {
@@ -202,6 +355,12 @@ fn main() {
std::process::exit(2);
}
};
// The control server is a stable-install service: a Nightly window is driven by the Launcher,
// and its token file would sit in the shared temp folder rather than its private profile.
if nightly && args.control.is_some() {
eprintln!("texturecraft: TextureCraft Nightly cannot start a control server (--control); use the stable app or texturecraft-cli");
std::process::exit(2);
}
// Errors before the window opens speak the system's language; the app then applies the saved one
texturecraft_ui_egui::i18n::set_language(texturecraft_ui_egui::i18n::os_language());
@@ -212,11 +371,13 @@ fn main() {
previous_hook(info);
}));
// Scripted runs use temporary files so they cannot overwrite saved settings
let persistence_path =
// Scripted runs use temporary files so they cannot overwrite saved settings. Otherwise eframe
// is told the file explicitly, so `with_app_id` cannot move Stable's `app.ron` out of the
// folder `storage_dir` keeps `ui.json` and `errors.log` in (see `settings_folder`).
let no_prefs_path =
std::env::var_os("TEXTURECRAFT_NO_PREFS").map(|_| std::env::temp_dir().join(format!("texturecraft-noprefs-{}.ron", std::process::id())));
let ui_file =
persistence_path.as_ref().map(|path| path.with_extension("json")).or_else(|| eframe::storage_dir(APP_NAME).map(|folder| folder.join("ui.json")));
let persistence_path = no_prefs_path.clone().or_else(|| storage_dir().map(|dir| dir.join("app.ron")));
let ui_file = no_prefs_path.as_ref().map(|path| path.with_extension("json")).or_else(|| storage_dir().map(|folder| folder.join("ui.json")));
if let Some(file) = &ui_file {
let _ = ui_state_store::FILE.set(file.clone());
}
@@ -227,7 +388,11 @@ fn main() {
prefs.apply_resource_limits();
let session = initial_session(&args);
let title_bar = TitleBar::decide(prefs.system_title_bar);
let mut viewport = egui::ViewportBuilder::default().with_title(APP_NAME).with_inner_size(DEFAULT_SIZE).with_min_inner_size(MIN_SIZE);
let mut viewport = egui::ViewportBuilder::default()
.with_app_id(os_window::app_id())
.with_title(os_window::name())
.with_inner_size(DEFAULT_SIZE)
.with_min_inner_size(MIN_SIZE);
if let Some(i) = icon() {
viewport = viewport.with_icon(i);
}
@@ -238,8 +403,34 @@ fn main() {
std::process::exit(2);
}
let control = args.control;
// The Nightly session record: one owner per profile, an unclean exit reported by the next
// start, and no document name, path or diagnostic payload collected.
let (nightly_session, session_health_warning) = match nightly_session::Session::begin_with_health(
launch_profile::current().root(),
build_flavor::BUILT_VERSION,
Some(env!("TEXTURECRAFT_BUILD_SHA")),
) {
Ok(state) => state,
Err(error) => {
log::warn!("Nightly session health is unavailable: {error}");
(None, true)
}
};
let previous_nightly_unclean = nightly_session.as_ref().is_some_and(nightly_session::Session::previous_unclean);
// Set once a window has posted the interruption notice; until then the record must survive.
let unclean_notice_shown = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let notice_shown_in_window = unclean_notice_shown.clone();
let nightly_session: nightly_session::Shared = std::sync::Arc::new(std::sync::Mutex::new(nightly_session));
// The exit hook is the controlled return on macOS, where every quit ends the process inside
// AppKit's terminate and `run_native` never returns. Elsewhere the return path below finishes.
let finish_at_exit = {
let shared = nightly_session.clone();
let shown = unclean_notice_shown.clone();
move || nightly_session::finish_once(&shared, shown.load(std::sync::atomic::Ordering::Relaxed))
};
let window_name = os_window::name();
let result = eframe::run_native(
APP_NAME,
window_name,
options,
Box::new(move |cc| {
#[cfg(windows)]
@@ -249,7 +440,7 @@ fn main() {
// winit's Quit ends the process without asking; this menu's asks like the close button
#[cfg(target_os = "macos")]
if let Err(e) = craft_menu::mac::install_app_menu(&cc.egui_ctx, APP_NAME) {
if let Err(e) = craft_menu::mac::install_app_menu(&cc.egui_ctx, window_name) {
log::warn!("the app menu could not be installed: {e}");
}
let window_frame = window_frame::service(cc, matches!(title_bar, TitleBar::App(_)));
@@ -259,14 +450,27 @@ fn main() {
if let Some(port) = control {
app.control = Some(control_server::start(port, cc.egui_ctx.clone()));
}
if previous_nightly_unclean || session_health_warning {
use texturecraft_ui_egui::i18n::tr;
app.banner = Some(if previous_nightly_unclean {
tr("The previous TextureCraft Nightly session did not finish normally. No diagnostics have been sent.")
} else {
tr("TextureCraft Nightly could not record session health in its profile; abnormal-exit detection is unavailable.")
});
notice_shown_in_window.store(previous_nightly_unclean, std::sync::atomic::Ordering::Relaxed);
}
Ok(Box::new(Shell {
app,
window_frame,
exit_hook: Some(Box::new(finish_at_exit)),
#[cfg(target_os = "macos")]
movable: None,
}))
}),
);
// A controlled return, including a handled startup error. On macOS a window already finished in
// its exit hook, so this is then a no-op.
nightly_session::finish_once(&nightly_session, unclean_notice_shown.load(std::sync::atomic::Ordering::Relaxed));
if let Err(e) = result {
fatal(&e.to_string(), true);
std::process::exit(1);
@@ -275,7 +479,7 @@ fn main() {
/// The file startup errors and crashes are appended to, beside the saved settings.
fn error_log() -> Option<std::path::PathBuf> {
eframe::storage_dir(APP_NAME).map(|d| d.join("errors.log"))
storage_dir().map(|d| d.join("errors.log"))
}
/// Append a line with the time (Unix seconds) and the app version; true when it was written.
@@ -296,7 +500,7 @@ fn fatal(msg: &str, dialog: bool) {
let saved = log.map(|f| format!("\n\n{}", trf("Details saved to {file}", &[("file", &f.display())]))).unwrap_or_default();
rfd::MessageDialog::new()
.set_level(rfd::MessageLevel::Error)
.set_title(APP_NAME)
.set_title(os_window::name())
.set_description(format!("{}\n\n{msg}{saved}", tr("TextureCraft had to close:")))
.set_buttons(rfd::MessageButtons::Ok)
.show();
@@ -322,16 +526,52 @@ mod tests {
}
#[test]
fn only_a_run_without_a_control_port_checks_for_updates_at_start() {
assert!(checks_for_updates_at_start(None));
assert!(!checks_for_updates_at_start(Some(9000)));
fn stable_settings_stay_in_the_folder_eframe_used_before_the_app_id() {
let legacy = std::path::PathBuf::from("/legacy/TextureCraft");
// Stable, no wrapper folder: the folder eframe picked for `APP_NAME` before `with_app_id`
// existed, so `app.ron` (window state and the export presets stored in it) does not move.
let folder = settings_folder(None, None, Some(legacy.clone())).expect("a legacy folder");
assert_eq!(folder.join("app.ron"), legacy.join("app.ron"));
// A Stable wrapper's data folder still wins, which is what #801's packaging expects.
let wrapper = std::path::PathBuf::from("/wrapper/data");
assert_eq!(settings_folder(None, Some(wrapper.clone()), Some(legacy.clone())), Some(wrapper.clone()));
// A Nightly profile wins over both, so no Stable folder is ever read.
assert_eq!(settings_folder(Some(std::path::Path::new("/profile")), Some(wrapper), Some(legacy)), Some(std::path::PathBuf::from("/profile")));
// Nothing resolvable: there is no folder to fall back to and eframe keeps its own default.
assert_eq!(settings_folder(None, None, None), None);
// The app's wiring: with no profile and no wrapper folder, `app.ron` sits beside `ui.json`
// in eframe's folder for `APP_NAME`, not in the folder of the app id `with_app_id` sets.
if std::env::var_os(DATA_DIR_ENV).is_none()
&& !launch_profile::current().is_nightly()
&& let Some(stable) = eframe::storage_dir(APP_NAME)
{
assert_eq!(storage_dir(), Some(stable.clone()));
assert_eq!(storage_dir().map(|dir| dir.join("app.ron")), Some(stable.join("app.ron")));
}
}
#[test]
fn bundled_app_icon_decodes_to_rgba() {
let icon = icon().unwrap();
assert!(icon.width > 0 && icon.height > 0);
assert_eq!(icon.rgba.len(), (icon.width * icon.height * 4) as usize);
fn a_file_after_the_delimiter_is_a_file_even_when_it_looks_like_an_option() {
let args = parse_args_from(["--".to_string(), "--version".to_string()]).unwrap().unwrap();
assert_eq!(args.file.as_deref(), Some("--version"));
let args = parse_args_from(["--".to_string(), "--launch-profile".to_string()]).unwrap().unwrap();
assert_eq!(args.file.as_deref(), Some("--launch-profile"));
// Options before the delimiter still parse as options.
let args = parse_args_from(["--gpu".to_string(), "nvidia".to_string(), "--".to_string(), "a.glb".to_string()]).unwrap().unwrap();
assert_eq!((args.gpu.as_deref(), args.file.as_deref()), (Some("nvidia"), Some("a.glb")));
// One window opens one project: extra files after the delimiter are ignored, in that order.
let args = parse_args_from(["--".to_string(), "a.glb".to_string(), "b.glb".to_string()]).unwrap().unwrap();
assert_eq!(args.file.as_deref(), Some("a.glb"));
}
#[test]
fn launch_arguments_refuse_a_name_that_is_not_unicode() {
assert_eq!(launch_arguments(vec![OsString::from("--version")]).unwrap(), vec!["--version".to_string()]);
#[cfg(unix)]
{
use std::os::unix::ffi::OsStringExt as _;
assert!(launch_arguments(vec![OsString::from_vec(vec![b'a', 0xff, b'b'])]).is_err());
}
}
#[test]
@@ -388,4 +628,56 @@ mod tests {
std::fs::remove_file(&ron_path).unwrap();
assert_eq!(saved_prefs(Some(&json_path), Some(&ron_path)), texturecraft_ui_egui::state::Prefs::default());
}
/// How far the test's drag moves the mouse in one frame, in points
const DRAG_STEP: egui::Vec2 = egui::vec2(80.0, 0.0);
/// Points within which a put-back lands on the press point (the system rounds it to whole pixels)
const PUT_BACK_REACH: f32 = 1.0;
/// One frame of the window: the system's events go through the window's raw input hook, as eframe sends them; returns what the app asked of the window
fn window_frame(harness: &mut egui_kittest::Harness<'static, Shell>, events: Vec<egui::Event>) -> Vec<egui::ViewportCommand> {
let ctx = harness.ctx.clone();
let mut raw = harness.input_mut().clone();
raw.events.extend(events);
eframe::App::raw_input_hook(harness.state_mut(), &ctx, &mut raw);
*harness.input_mut() = raw;
harness.step();
harness.output().viewport_output.get(&egui::ViewportId::ROOT).map(|viewport| viewport.commands.clone()).unwrap_or_default()
}
/// Holding the fill's preview square in the window holds the system's pointer: put back to the press point every frame, or locked where the system locks it
#[test]
fn the_window_holds_the_pointer_while_the_preview_square_is_held() {
let session = Session::new_project("Hold", texturecraft_engine::geom::primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 128).unwrap();
let builder = egui_kittest::Harness::builder().with_size(egui::vec2(DEFAULT_SIZE[0], DEFAULT_SIZE[1]));
let mut harness = builder.build_eframe(|cc| Shell {
app: TextureCraftApp::new(cc, session),
window_frame: None,
exit_hook: None,
#[cfg(target_os = "macos")]
movable: None,
});
harness.run_steps(4);
let layer = harness.state_mut().app.run("layer.add.fill", serde_json::json!({})).unwrap()["layer"].clone();
harness.state_mut().app.run("layer.fill.projection", serde_json::json!({"layer": layer, "projection": "triplanar"})).unwrap();
harness.run_steps(2);
let pad = egui_kittest::kittest::Queryable::get_by_label(&harness, "Move on model").rect().center();
let press = egui::Event::PointerButton { pos: pad, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE };
let pressed = window_frame(&mut harness, vec![egui::Event::PointerMoved(pad), press]);
let locked = pressed.contains(&egui::ViewportCommand::CursorGrab(egui::CursorGrab::Locked));
// A locked pointer stays still and the system reports only its raw motion
let mut moves = vec![egui::Event::MouseMoved(DRAG_STEP)];
if !locked {
moves.push(egui::Event::PointerMoved(pad + DRAG_STEP));
}
let moved = window_frame(&mut harness, moves);
let put_back = moved.iter().any(|command| matches!(command, egui::ViewportCommand::CursorPosition(to) if to.distance(pad) <= PUT_BACK_REACH));
assert!(locked || put_back, "the window puts the pointer back where the press began, so it never leaves: {moved:?}");
let seen = harness.ctx.input(|input| input.pointer.latest_pos());
assert!(seen.is_some_and(|seen| seen.distance(pad + DRAG_STEP) <= PUT_BACK_REACH), "the app reads the whole move: {seen:?}");
}
}
+277
View File
@@ -0,0 +1,277 @@
//! App-private Nightly session health, not telemetry and not a Launcher protocol.
//!
//! A live owner holds a separate persistent lease; a secondary launch never rewrites its record.
//! Dropping the guard does not clear the marker; only the app's controlled return path does.
use std::fs::File;
use std::io::{self, Read};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, PoisonError};
const RECORD: &str = "nightly-session.json";
const LEASE: &str = "nightly-session.lock";
const MAX_METADATA_BYTES: usize = 256;
pub struct Session {
_lease: File,
path: PathBuf,
own_record: Vec<u8>,
previous_unclean: bool,
}
fn regular_or_missing(path: &Path) -> io::Result<bool> {
match std::fs::symlink_metadata(path) {
Ok(metadata) if metadata.file_type().is_file() && !metadata.file_type().is_symlink() => Ok(true),
Ok(_) => Err(io::Error::other("Nightly session state must be a regular file, not an alias or directory")),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
Err(error) => Err(error),
}
}
/// Write `bytes` to `path` without ever following a link at the destination: the temporary file is
/// created exclusively beside it and renamed over the name, which replaces a link rather than
/// writing through it (the engine's `write_atomic` deliberately resolves the target instead).
fn write_no_follow(path: &Path, bytes: &[u8]) -> io::Result<()> {
let parent = path.parent().ok_or_else(|| io::Error::other("the Nightly record has no folder"))?;
let name = path.file_name().and_then(|name| name.to_str()).ok_or_else(|| io::Error::other("the Nightly record name is not Unicode"))?;
let temporary = parent.join(format!(".{name}.{}.tmp", std::process::id()));
let mut options = std::fs::OpenOptions::new();
options.write(true).create_new(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt as _;
options.mode(0o600);
}
let staged = write_staged(&mut options, &temporary, bytes).and_then(|()| std::fs::rename(&temporary, path));
if let Err(error) = staged {
let _ = std::fs::remove_file(&temporary);
return Err(error);
}
// The rename is durable only once its folder is synced (no-op where the platform has no handle).
#[cfg(unix)]
if let Ok(folder) = File::open(parent) {
let _ = folder.sync_all();
}
Ok(())
}
/// Write the whole file and flush it to the device before it may replace the destination.
fn write_staged(options: &mut std::fs::OpenOptions, temporary: &Path, bytes: &[u8]) -> io::Result<()> {
use std::io::Write as _;
let mut file = options.open(temporary)?;
file.write_all(bytes)?;
file.sync_all()
}
/// The owner's session, shared by the app's exit hook (macOS) and the code after the event loop.
/// On macOS every quit ends the process inside AppKit's terminate, after eframe's `on_exit` and
/// before `eframe::run_native` could return, so the exit hook finishes it there; the return path
/// still runs for a start that created no window.
pub type Shared = Arc<Mutex<Option<Session>>>;
/// The controlled return ([`Session::finish`]) by whichever path comes first; later calls do nothing.
pub fn finish_once(shared: &Shared, unclean_notice_shown: bool) {
let watch = shared.lock().unwrap_or_else(PoisonError::into_inner).take();
if let Some(watch) = watch
&& let Err(error) = watch.finish(unclean_notice_shown)
{
log::warn!("Nightly session state was left intact: {error}");
}
}
impl Session {
/// The warning belongs to this window: a busy secondary has no health-record coverage, while
/// Stable and a lease-owning Nightly window preserve their existing result.
pub fn begin_with_health(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result<(Option<Self>, bool)> {
let watch = Self::begin(root, version, commit)?;
let unavailable = root.is_some() && watch.is_none();
Ok((watch, unavailable))
}
/// `None` is Stable or another owner of this profile. Neither case touches the record.
/// The supplied root must already be the validated private Nightly profile.
pub fn begin(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result<Option<Self>> {
let Some(root) = root else { return Ok(None) };
if version.is_empty() || version.len() > MAX_METADATA_BYTES || commit.is_some_and(|value| value.len() > MAX_METADATA_BYTES) {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "Nightly session provenance is missing or too large"));
}
let lease_path = root.join(LEASE);
regular_or_missing(&lease_path)?;
let lease = std::fs::OpenOptions::new().read(true).write(true).create(true).truncate(false).open(lease_path)?;
match lease.try_lock() {
Ok(()) => {}
Err(std::fs::TryLockError::WouldBlock) => return Ok(None),
Err(std::fs::TryLockError::Error(error)) => return Err(error),
}
let path = root.join(RECORD);
let previous_unclean = regular_or_missing(&path)?;
let own_record = serde_json::to_vec(&serde_json::json!({
"schema_version": 1,
"channel": "nightly-v1",
"version": version,
"commit": commit.filter(|value| !value.is_empty()),
}))?;
write_no_follow(&path, &own_record)?;
Ok(Some(Self { _lease: lease, path, own_record, previous_unclean }))
}
pub fn previous_unclean(&self) -> bool {
self.previous_unclean
}
/// Controlled return. If an earlier session's interruption was detected but no window showed it
/// yet, the record is left for the next owner to report; otherwise this is [`Self::complete`].
pub fn finish(self, unclean_notice_shown: bool) -> io::Result<()> {
if self.previous_unclean && !unclean_notice_shown {
return Ok(());
}
self.complete()
}
/// A handled startup error is a controlled return too. An unwind, abort, forced exit or killed
/// process never calls this method.
pub fn complete(self) -> io::Result<()> {
if !regular_or_missing(&self.path)? {
return Ok(());
}
let mut current = Vec::new();
File::open(&self.path)?.take(self.own_record.len() as u64 + 1).read_to_end(&mut current)?;
if current != self.own_record {
return Err(io::Error::other("Nightly session state changed; leaving it intact"));
}
std::fs::remove_file(&self.path)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicU64, Ordering};
struct Fixture(PathBuf);
impl Fixture {
fn new() -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
loop {
let path = std::env::temp_dir().join(format!("texturecraft-nightly-session-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
match std::fs::create_dir(&path) {
Ok(()) => return Self(path),
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(error) => panic!("cannot create owned fixture: {error}"),
}
}
}
}
impl Drop for Fixture {
fn drop(&mut self) {
std::fs::remove_dir_all(&self.0).unwrap();
}
}
#[test]
fn busy_secondary_reports_unavailable_without_replacing_the_owner_record() {
let fixture = Fixture::new();
let (stable, warning) = Session::begin_with_health(None, "stable", None).unwrap();
assert!(stable.is_none() && !warning);
let (first, warning) = Session::begin_with_health(Some(&fixture.0), "nightly", Some("owned-commit")).unwrap();
assert!(!warning);
let first = first.unwrap();
let record = std::fs::read(fixture.0.join(RECORD)).unwrap();
let (secondary, warning) = Session::begin_with_health(Some(&fixture.0), "secondary", None).unwrap();
assert!(secondary.is_none() && warning, "a secondary window cannot claim recorded exit/crash coverage");
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record);
first.complete().unwrap();
assert!(!fixture.0.join(RECORD).exists());
}
#[test]
fn controlled_completion_is_clean_but_an_unfinished_owner_is_reported_next_time() {
let fixture = Fixture::new();
let first = Session::begin(Some(&fixture.0), "first", Some("recorded-commit")).unwrap().unwrap();
assert!(!first.previous_unclean());
let own = std::fs::read(fixture.0.join(RECORD)).unwrap();
assert!(Session::begin(Some(&fixture.0), "secondary", None).unwrap().is_none());
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), own, "a busy secondary must not replace the owner's record");
first.complete().unwrap();
assert!(!fixture.0.join(RECORD).exists());
let unfinished = Session::begin(Some(&fixture.0), "second", None).unwrap().unwrap();
assert!(!unfinished.previous_unclean());
drop(unfinished); // Unwind/abnormal-path ownership release, not a controlled completion.
let next = Session::begin(Some(&fixture.0), "third", None).unwrap().unwrap();
assert!(next.previous_unclean());
next.complete().unwrap();
assert!(!fixture.0.join(RECORD).exists());
}
#[test]
fn an_interruption_no_window_showed_survives_a_handled_startup_failure() {
let fixture = Fixture::new();
drop(Session::begin(Some(&fixture.0), "crashed", None).unwrap().unwrap());
let failed = Session::begin(Some(&fixture.0), "gpu-failed", None).unwrap().unwrap();
assert!(failed.previous_unclean());
failed.finish(false).unwrap();
// The next start still sees the interruption and shows it.
let retry = Session::begin(Some(&fixture.0), "next", None).unwrap().unwrap();
assert!(retry.previous_unclean());
retry.finish(true).unwrap();
assert!(!fixture.0.join(RECORD).exists(), "a session that showed the notice clears its record");
let clean = Session::begin(Some(&fixture.0), "clean", None).unwrap().unwrap();
assert!(!clean.previous_unclean());
clean.finish(false).unwrap();
assert!(!fixture.0.join(RECORD).exists());
}
#[test]
fn the_exit_hook_and_the_return_path_finish_the_session_once() {
let fixture = Fixture::new();
let shared: Shared = Arc::new(Mutex::new(Session::begin(Some(&fixture.0), "quitting", None).unwrap()));
// The exit hook (macOS quit: the only path that runs there).
finish_once(&shared, false);
assert!(!fixture.0.join(RECORD).exists(), "a quit that ran the exit hook is a clean exit");
// Elsewhere the return path runs too, by then possibly after a successor took the profile.
let successor = Session::begin(Some(&fixture.0), "successor", None).unwrap().unwrap();
assert!(!successor.previous_unclean());
let record = std::fs::read(fixture.0.join(RECORD)).unwrap();
finish_once(&shared, false);
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record, "the second finish must not touch a successor's record");
successor.complete().unwrap();
}
#[test]
fn cleanup_never_removes_an_unknown_changed_record() {
let fixture = Fixture::new();
let watch = Session::begin(Some(&fixture.0), "nightly", None).unwrap().unwrap();
std::fs::write(fixture.0.join(RECORD), b"replacement owned by someone else").unwrap();
assert!(watch.complete().is_err());
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), b"replacement owned by someone else");
}
#[test]
fn provenance_is_bounded_and_never_collects_documents_paths_or_diagnostics() {
let fixture = Fixture::new();
assert!(Session::begin(Some(&fixture.0), &"x".repeat(MAX_METADATA_BYTES + 1), None).is_err());
assert_eq!(std::fs::read_dir(&fixture.0).unwrap().count(), 0);
assert!(Session::begin(None, "", None).unwrap().is_none(), "stable has no session-health side effects");
let watch = Session::begin(Some(&fixture.0), "nightly", None).unwrap().unwrap();
let data: serde_json::Value = serde_json::from_slice(&std::fs::read(fixture.0.join(RECORD)).unwrap()).unwrap();
let fields = data.as_object().unwrap().keys().map(String::as_str).collect::<std::collections::BTreeSet<_>>();
assert_eq!(fields, ["schema_version", "channel", "version", "commit"].into_iter().collect());
assert!(data["commit"].is_null(), "missing provenance must not be invented");
watch.complete().unwrap();
}
#[test]
#[cfg(unix)]
fn reserved_state_aliases_do_not_modify_external_files() {
let fixture = Fixture::new();
let external = fixture.0.join("stable-document");
std::fs::write(&external, b"stable bytes").unwrap();
for name in [LEASE, RECORD] {
let alias = fixture.0.join(name);
std::os::unix::fs::symlink(&external, &alias).unwrap();
assert!(Session::begin(Some(&fixture.0), "nightly", None).is_err());
assert_eq!(std::fs::read(&external).unwrap(), b"stable bytes");
std::fs::remove_file(alias).unwrap();
}
}
}
+78
View File
@@ -0,0 +1,78 @@
//! Set the immutable Nightly Windows identity before any native window or COM service.
//! Stable deliberately leaves its implicit shortcut/path identity unchanged, so MSI shortcut
//! matching keeps working.
use std::fmt;
use std::sync::OnceLock;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct IdentityError(pub String);
impl fmt::Display for IdentityError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for IdentityError {}
/// The AppUserModelID the taskbar groups the Nightly window under, distinct from Stable's.
pub fn initialize(nightly: bool, app_id: &str) -> Result<(), IdentityError> {
configure(nightly && cfg!(windows), app_id, |id| {
static RESULT: OnceLock<Result<(), String>> = OnceLock::new();
RESULT
.get_or_init(|| {
#[cfg(windows)]
{
winsafe::SetCurrentProcessExplicitAppUserModelID(id).map_err(|error| format!("cannot set the nightly Windows identity: {error}"))?;
let actual = winsafe::GetCurrentProcessExplicitAppUserModelID()
.map_err(|error| format!("cannot read back the nightly Windows identity: {error}"))?;
if actual != id {
return Err("the native Windows identity did not match the selected nightly channel".into());
}
Ok(())
}
#[cfg(not(windows))]
{
let _ = id;
Ok(())
}
})
.clone()
})
.map_err(IdentityError)
}
fn configure(explicit_nightly: bool, app_id: &str, set: impl FnOnce(&str) -> Result<(), String>) -> Result<(), String> {
if explicit_nightly { set(app_id) } else { Ok(()) }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn stable_does_not_call_the_explicit_identity_api() {
configure(false, "nightly-id", |_| panic!("stable identity must remain implicit")).unwrap();
}
#[test]
fn nightly_applies_the_supplied_identity_once() {
let calls = std::cell::Cell::new(0);
configure(true, "nightly-id", |id| {
assert_eq!(id, "nightly-id");
calls.set(calls.get() + 1);
Ok(())
})
.unwrap();
assert_eq!(calls.get(), 1);
}
#[test]
fn native_identity_failure_is_returned_instead_of_starting_a_window() {
let started = std::cell::Cell::new(false);
let result = configure(true, "nightly-id", |_| Err("native identity refused".into())).map(|()| started.set(true));
assert_eq!(result.unwrap_err(), "native identity refused");
assert!(!started.get());
}
}
+489
View File
@@ -0,0 +1,489 @@
//! App-owned nightly profile fences; no stable fallback, migration or process environment changes.
//!
//! A Nightly profile has to hold *all* of its user state: eframe's `app.ron`/`ui.json`, the error
//! log, session logs, autosave copies, smart materials, layouts, templates, brush and export
//! presets. Anything that resolves to a stable folder would read and prune Stable's files, so the
//! root is refused when it overlaps one of them, when an entry inside it is an alias that leaves it,
//! or when it is not writable.
use std::ffi::OsString;
use std::path::{Component, Path, PathBuf};
/// The folder names the launch checks use for this app in each platform's location.
const BRAND: &str = "TextureCraft";
/// The bundle identifier of the stable package (macOS library folders, the Linux Flatpak).
const STABLE_ID: &str = "ai.storyteller.texturecraft";
/// The package id of the Nightly Flatpak bundle (`packaging/linux/flatpak-bundle.sh`). Inside that
/// sandbox `FLATPAK_ID` is always set, so this exact id is the one a Nightly native launch accepts.
const NIGHTLY_ID: &str = "ai.storyteller.texturecraft.nightly";
/// eframe lowercases its folder name on Linux (`file_storage.rs`), so Stable's real settings folder
/// is `$XDG_DATA_HOME/texturecraft`, not the capitalised `TextureCraft` the app is called.
const LINUX_STORAGE_BRAND: &str = "texturecraft";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Platform {
Windows,
Linux,
Mac,
}
impl Platform {
fn current() -> Result<Self, String> {
match std::env::consts::OS {
"windows" => Ok(Self::Windows),
"linux" => Ok(Self::Linux),
"macos" => Ok(Self::Mac),
_ => Err("nightly-v1 is not defined for this operating system".into()),
}
}
fn ignores_case(self) -> bool {
self != Self::Linux
}
}
fn absolute(path: PathBuf, label: &str) -> Result<PathBuf, String> {
if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) {
return Err(format!("{label} must be absolute and contain no parent traversal"));
}
Ok(path)
}
fn required_base(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Result<PathBuf, String> {
let value = env(key).filter(|v| !v.is_empty()).ok_or_else(|| format!("cannot establish the stable {key} boundary"))?;
absolute(PathBuf::from(value), key)
}
fn xdg_base(env: &impl Fn(&str) -> Option<OsString>, key: &str, fallback: &str) -> Result<PathBuf, String> {
match env(key).filter(|v| !v.is_empty()) {
Some(value) => absolute(PathBuf::from(value), key),
None => Ok(required_base(env, "HOME")?.join(fallback)),
}
}
/// Resolve existing ancestors before creating anything. A dangling link or an inaccessible ancestor
/// is not a missing directory that may be replaced or followed later.
fn canonical_future(path: &Path) -> Result<PathBuf, String> {
let mut parent = path;
let mut missing = Vec::new();
loop {
match std::fs::symlink_metadata(parent) {
Ok(_) => break,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
missing.push(parent.file_name().ok_or("the profile root has no existing ancestor")?.to_os_string());
parent = parent.parent().ok_or("the profile root has no existing ancestor")?;
}
Err(error) => return Err(format!("cannot inspect the profile boundary: {error}")),
}
}
let mut resolved = std::fs::canonicalize(parent).map_err(|e| format!("cannot resolve the profile boundary: {e}"))?;
for part in missing.into_iter().rev() {
resolved.push(part);
}
Ok(resolved)
}
/// Whether one path is the other or contains it (in either direction), compared component by
/// component and folded the way the platform's filesystem folds names. `TextureCraft2` is not
/// inside `TextureCraft`.
fn overlaps(a: &Path, b: &Path, platform: Platform) -> bool {
let parts = |p: &Path| {
p.components()
.map(|c| {
let value = c.as_os_str().to_string_lossy().into_owned();
if platform.ignores_case() { value.to_lowercase() } else { value }
})
.collect::<Vec<_>>()
};
let (a, b) = (parts(a), parts(b));
a.starts_with(&b) || b.starts_with(&a)
}
/// The running install: never let the profile live inside it (it would be replaced or removed by
/// the next update).
fn installation_boundary(platform: Platform, exe: &Path) -> Result<PathBuf, String> {
let parent = exe.parent().ok_or("cannot establish the installation boundary")?;
if platform == Platform::Mac {
// A profile in Resources is still inside the versioned bundle, not beside MacOS.
if let Some(bundle) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))) {
return Ok(bundle.to_path_buf());
}
}
Ok(parent.to_path_buf())
}
/// The default data folder, `Documents/TextureCraft`, as the app's own resolver builds it
/// (`crate::data_folder("")`): `USERPROFILE` on Windows and `HOME` elsewhere, then `Documents`.
fn default_data_folder(platform: Platform, env: &impl Fn(&str) -> Option<OsString>) -> Result<PathBuf, String> {
let home = match platform {
Platform::Windows => required_base(env, "USERPROFILE")?,
_ => required_base(env, "HOME")?,
};
Ok(home.join("Documents").join(BRAND))
}
fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option<OsString>, exe: &Path) -> Result<Vec<PathBuf>, String> {
let mut roots = match platform {
Platform::Windows => {
// eframe's settings folder (`%APPDATA%\TextureCraft`), its local counterpart, and the MSI's
// per-machine and any per-user install folders. A custom install folder is covered by the
// executable's own folder below.
let mut roots = ["APPDATA", "LOCALAPPDATA"].into_iter().map(|key| required_base(env, key).map(|p| p.join(BRAND))).collect::<Result<Vec<_>, _>>()?;
roots.push(required_base(env, "LOCALAPPDATA")?.join("Programs").join("ArtCraft").join(BRAND));
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
if let Some(base) = env(key).filter(|v| !v.is_empty()) {
roots.push(absolute(PathBuf::from(base), key)?.join(BRAND));
}
}
roots
}
Platform::Linux => {
// The four XDG roots carry eframe's settings, caches and state under the app's name.
let mut roots =
[("XDG_CONFIG_HOME", ".config"), ("XDG_DATA_HOME", ".local/share"), ("XDG_CACHE_HOME", ".cache"), ("XDG_STATE_HOME", ".local/state")]
.into_iter()
.map(|(key, fallback)| xdg_base(env, key, fallback).map(|p| p.join(BRAND)))
.collect::<Result<Vec<_>, _>>()?;
// eframe's own folder for this app on Linux, which is what holds Stable's `app.ron`,
// `ui.json` and `errors.log`: it folds the name, so it is the lowercase one.
roots.push(xdg_base(env, "XDG_DATA_HOME", ".local/share")?.join(LINUX_STORAGE_BRAND));
roots.extend(["/usr/bin/texturecraft", "/usr/local/bin/texturecraft", "/opt/texturecraft"].map(PathBuf::from));
// The stable Flatpak keeps its own per-app data folder.
roots.push(required_base(env, "HOME")?.join(format!(".var/app/{STABLE_ID}")));
roots
}
Platform::Mac => {
let home = required_base(env, "HOME")?;
let library = home.join("Library");
vec![
library.join("Application Support").join(BRAND),
library.join("Caches").join(BRAND),
library.join("Caches").join(STABLE_ID),
library.join("Preferences").join(BRAND),
library.join("Preferences").join(format!("{STABLE_ID}.plist")),
library.join("Saved Application State").join(format!("{STABLE_ID}.savedState")),
home.join("Applications").join(format!("{BRAND}.app")),
PathBuf::from("/Applications").join(format!("{BRAND}.app")),
]
}
};
// The user's own documents folder is Stable's default data folder on every platform; a profile
// there would share autosaves, smart materials and presets with it.
roots.push(default_data_folder(platform, env)?);
roots.push(installation_boundary(platform, exe)?);
roots.into_iter().map(|p| canonical_future(&p)).collect()
}
/// An entry inside the profile must resolve inside it, so a link planted there cannot point
/// Nightly's writes at another app's files.
fn private_subdirectory(root: &Path, name: impl AsRef<Path>, label: &str) -> Result<PathBuf, String> {
let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?;
let child = canonical_future(&chosen.join(name))?;
if child == chosen || !child.starts_with(&chosen) {
return Err(format!("the nightly {label} must stay inside its selected profile"));
}
Ok(child)
}
/// Every existing entry directly in the profile (autosave, logs, library and so on) must resolve
/// inside it.
fn entries_stay_inside(root: &Path) -> Result<(), String> {
let entries = match std::fs::read_dir(root) {
Ok(entries) => entries,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(error) => return Err(format!("cannot inspect the nightly profile: {error}")),
};
for entry in entries {
let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
private_subdirectory(root, entry.file_name(), "profile entry")?;
}
Ok(())
}
/// The app's writable probe: create a file exclusively in the profile and remove it again.
pub fn ensure_writable(dir: &Path) -> std::io::Result<()> {
let probe = dir.join("exclusive-write-probe");
let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?;
drop(file);
std::fs::remove_file(probe)
}
/// Refuse a stable folder, the running install or an alias, create a missing root with owner-only
/// access where the platform has it, and return the resolved root to use.
pub fn validate(
root: &Path,
env: impl Fn(&str) -> Option<OsString>,
exe: Option<&Path>,
writable: impl FnOnce(&Path) -> std::io::Result<()>,
) -> Result<PathBuf, String> {
validate_for(Platform::current()?, root, env, exe, writable)
}
fn validate_for(
platform: Platform,
root: &Path,
env: impl Fn(&str) -> Option<OsString>,
exe: Option<&Path>,
writable: impl FnOnce(&Path) -> std::io::Result<()>,
) -> Result<PathBuf, String> {
absolute(root.to_path_buf(), "the nightly profile root")?;
// A native package must not carry another app's Flatpak namespace, and the Nightly bundle must
// be able to start inside its own sandbox, where the runtime always sets `FLATPAK_ID`. Its
// `~/.var/app/<nightly id>` sandbox is separate from stable's, so only other ids are refused.
if platform != Platform::Windows
&& let Some(id) = env("FLATPAK_ID").filter(|v| !v.is_empty())
&& id != NIGHTLY_ID
{
return Err("nightly-v1 only runs inside its own Flatpak; launch through the native Launcher or the Nightly bundle".into());
}
let chosen = canonical_future(root)?;
let exe = absolute(exe.ok_or("cannot establish the installation boundary")?.to_path_buf(), "the executable")?;
let forbidden = forbidden_roots(platform, &env, &exe)?;
if forbidden.iter().any(|stable| overlaps(&chosen, stable, platform)) {
return Err("the nightly root must not overlap stable data or an installation".into());
}
// Existing aliases under the profile must not redirect any of its folders elsewhere.
entries_stay_inside(&chosen)?;
let mut create = std::fs::DirBuilder::new();
create.recursive(true);
#[cfg(unix)]
{
use std::os::unix::fs::DirBuilderExt as _;
create.mode(0o700);
}
create.create(&chosen).map_err(|e| format!("cannot create the nightly profile: {e}"))?;
let confirmed = std::fs::canonicalize(&chosen).map_err(|e| format!("cannot resolve the created nightly profile: {e}"))?;
if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) {
return Err("the nightly profile changed while it was being validated".into());
}
entries_stay_inside(&confirmed)?;
writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?;
Ok(confirmed)
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeMap;
use std::sync::atomic::{AtomicU64, Ordering};
struct Fixture {
root: PathBuf,
env: BTreeMap<String, OsString>,
exe: PathBuf,
}
impl Fixture {
fn new() -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
let root = loop {
let candidate =
std::env::temp_dir().join(format!("texturecraft-profile-policy-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
match std::fs::create_dir(&candidate) {
Ok(()) => break std::fs::canonicalize(candidate).unwrap(),
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(error) => panic!("cannot create owned fixture: {error}"),
}
};
let home = root.join("home");
let exe = root.join("install/texturecraft");
std::fs::create_dir_all(&home).unwrap();
std::fs::create_dir_all(exe.parent().unwrap()).unwrap();
std::fs::write(&exe, b"fixture executable, never run").unwrap();
let env = [("HOME", home.clone()), ("USERPROFILE", home), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))]
.into_iter()
.map(|(key, value)| (key.into(), value.into_os_string()))
.collect();
Self { root, env, exe }
}
fn get(&self, key: &str) -> Option<OsString> {
self.env.get(key).cloned()
}
fn check(&self, platform: Platform, root: &Path) -> Result<PathBuf, String> {
validate_for(platform, root, |key| self.get(key), Some(&self.exe), ensure_writable)
}
fn home(&self) -> PathBuf {
PathBuf::from(self.get("HOME").unwrap())
}
fn profile(&self, name: &str) -> PathBuf {
self.root.join("profiles").join(name)
}
}
impl Drop for Fixture {
fn drop(&mut self) {
// Only the directory this fixture created is owned for removal.
std::fs::remove_dir_all(&self.root).unwrap();
}
}
#[test]
fn a_fresh_private_profile_is_created_and_returned_resolved() {
let fixture = Fixture::new();
let profile = fixture.profile("nightly");
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
assert_eq!(fixture.check(platform, &profile).unwrap(), profile);
assert!(profile.is_dir());
std::fs::remove_dir_all(&profile).ok();
}
}
#[test]
fn every_stable_data_folder_of_each_platform_is_refused_before_any_probe() {
let fixture = Fixture::new();
let home = fixture.home();
let candidates: Vec<(Platform, PathBuf)> = vec![
(Platform::Windows, PathBuf::from(fixture.get("APPDATA").unwrap()).join(BRAND)),
(Platform::Windows, PathBuf::from(fixture.get("LOCALAPPDATA").unwrap()).join(BRAND)),
(Platform::Windows, PathBuf::from(fixture.get("LOCALAPPDATA").unwrap()).join("Programs/ArtCraft").join(BRAND)),
(Platform::Windows, home.join("Documents").join(BRAND)),
(Platform::Linux, home.join(".config").join(BRAND)),
(Platform::Linux, home.join(".local/share").join(BRAND)),
(Platform::Linux, home.join(".local/share").join(LINUX_STORAGE_BRAND)),
(Platform::Linux, home.join(".cache").join(BRAND)),
(Platform::Linux, home.join(".local/state").join(BRAND)),
(Platform::Linux, home.join("Documents").join(BRAND)),
(Platform::Linux, PathBuf::from("/usr/bin/texturecraft")),
(Platform::Linux, PathBuf::from("/opt/texturecraft")),
(Platform::Linux, home.join(format!(".var/app/{STABLE_ID}"))),
(Platform::Mac, home.join("Library/Application Support").join(BRAND)),
(Platform::Mac, home.join("Library/Caches").join(BRAND)),
(Platform::Mac, home.join("Library/Preferences").join(format!("{STABLE_ID}.plist"))),
(Platform::Mac, home.join("Library/Saved Application State").join(format!("{STABLE_ID}.savedState"))),
(Platform::Mac, home.join("Documents").join(BRAND)),
(Platform::Mac, PathBuf::from(format!("/Applications/{BRAND}.app"))),
];
for (platform, stable) in candidates {
for candidate in [stable.clone(), stable.join("nested nightly")] {
let probed = std::cell::Cell::new(false);
let result = validate_for(
platform,
&candidate,
|key| fixture.get(key),
Some(&fixture.exe),
|_| {
probed.set(true);
Ok(())
},
);
assert!(result.is_err(), "{platform:?} accepted {}", candidate.display());
assert!(!probed.get(), "a refused root must not be probed: {}", candidate.display());
}
}
}
#[test]
fn the_running_install_is_fenced_on_every_platform() {
let fixture = Fixture::new();
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
let inside = fixture.exe.parent().unwrap().join("profile");
assert!(fixture.check(platform, &inside).is_err(), "{platform:?} let the profile inside the install");
}
}
#[test]
fn lookalike_names_are_not_overlaps_but_case_folding_is() {
let fixture = Fixture::new();
let documents = fixture.home().join("Documents");
assert!(fixture.check(Platform::Linux, &documents.join("TextureCraft2")).is_ok(), "a neighbor with a suffix is a different folder");
assert!(fixture.check(Platform::Linux, &documents.join("texturecraft")).is_ok(), "Linux folds names exactly");
for platform in [Platform::Windows, Platform::Mac] {
assert!(fixture.check(platform, &documents.join("texturecraft")).is_err(), "{platform:?} must fold case");
}
}
#[test]
fn relative_parent_traversal_and_empty_roots_are_refused() {
let fixture = Fixture::new();
for root in [PathBuf::from("relative/profile"), PathBuf::from("/nightly/../stable"), PathBuf::from("")] {
assert!(fixture.check(Platform::Linux, &root).is_err(), "{}", root.display());
}
}
#[test]
fn only_the_nightly_flatpak_may_start_with_its_own_id() {
let fixture = Fixture::new();
let profile = fixture.profile("flatpak");
assert!(fixture.check(Platform::Linux, &profile).is_ok());
std::fs::remove_dir_all(&profile).ok();
let check_with = |id: &str, candidate: &Path| {
let id = OsString::from(id);
validate_for(
Platform::Linux,
candidate,
|key| if key == "FLATPAK_ID" { Some(id.clone()) } else { fixture.get(key) },
Some(&fixture.exe),
ensure_writable,
)
};
// Stable's id, its window id and an unrelated app's id are all refusals.
for id in [STABLE_ID, "ai.storyteller.texturecraft.nightly-v1", "org.example.other"] {
assert!(check_with(id, &profile).is_err(), "{id} was accepted");
}
// The Nightly bundle's own id is the sandbox the Nightly package runs in: accepted, with the
// profile its wrapper names inside it (`${XDG_DATA_HOME}/TextureCraft-Nightly`).
let sandbox = fixture.home().join(format!(".var/app/{NIGHTLY_ID}"));
let sandboxed = sandbox.join(".local/share/TextureCraft-Nightly");
assert_eq!(check_with(NIGHTLY_ID, &sandboxed).expect("the Nightly Flatpak may start"), sandboxed);
std::fs::remove_dir_all(&sandbox).ok();
}
#[test]
#[cfg(unix)]
fn an_entry_that_leaves_the_profile_is_refused() {
let fixture = Fixture::new();
let profile = fixture.profile("aliased");
let outside = fixture.root.join("somewhere else");
std::fs::create_dir_all(&profile).unwrap();
std::fs::create_dir_all(&outside).unwrap();
std::os::unix::fs::symlink(&outside, profile.join("autosave")).unwrap();
assert!(fixture.check(Platform::Linux, &profile).is_err(), "a link out of the profile must be refused");
// A dangling link is not a missing folder that may be created.
std::fs::remove_file(profile.join("autosave")).unwrap();
std::os::unix::fs::symlink(profile.join("missing"), profile.join("logs")).unwrap();
assert!(fixture.check(Platform::Linux, &profile).is_err());
std::fs::remove_file(profile.join("logs")).unwrap();
// A plain folder inside it is fine.
std::fs::create_dir(profile.join("autosave")).unwrap();
assert!(fixture.check(Platform::Linux, &profile).is_ok());
}
#[test]
fn a_failed_write_probe_never_falls_back_to_stable() {
let fixture = Fixture::new();
let profile = fixture.profile("read only");
let reached = std::cell::Cell::new(false);
let result = validate_for(
Platform::Linux,
&profile,
|key| fixture.get(key),
Some(&fixture.exe),
|_| {
reached.set(true);
Err(std::io::Error::other("read-only filesystem"))
},
);
assert!(result.is_err());
assert!(reached.get());
assert!(result.unwrap_err().contains("not writable"));
// The app must not then use the stable folder: it simply refuses to start.
assert!(fixture.check(Platform::Linux, &fixture.home().join("Documents").join(BRAND)).is_err());
}
#[test]
#[cfg(unix)]
fn a_profile_whose_existing_ancestor_is_a_link_resolves_before_the_fence() {
let fixture = Fixture::new();
let real = fixture.root.join("real profiles");
std::fs::create_dir_all(&real).unwrap();
let link = fixture.root.join("linked");
std::os::unix::fs::symlink(&real, &link).unwrap();
// A link to a private folder is fine, and the resolved root is what the app uses.
let resolved = fixture.check(Platform::Linux, &link.join("nightly")).unwrap();
assert_eq!(resolved, real.join("nightly"));
}
}
+20
View File
@@ -57,3 +57,23 @@ pillow and potracer):
OPT=0.4 DP=1 python3 vectorize_tile.py source.png '#c2672b' 2048 2 texturecraft.svg
OPT=1.0 DP=0 python3 vectorize_tile.py source.png '#c2672b' 1024 4 texturecraft-small.svg
```
## Nightly icon
The Nightly build ships the same engraving on a deeper copper field (`#643418`): the background
contribution of each pixel is replaced and the ink, paper and alpha padding are left exactly as
they are. No badge, crescent or letter is added, so the two icons differ only in the field.
| File | What |
|---|---|
| `texturecraft-nightly.png` | 256 px window icon (`apps/texturecraft/src/main.rs`) |
| `texturecraft-nightly-1024.png` | full tile, 1024 px (docs) |
| `texturecraft-nightly.icns` | macOS icon set, the stable `.icns`'s own PNG slots recoloured |
| `texturecraft-nightly.ico` | Windows icon, the stable `.ico`'s own frames (16 to 256 px) recoloured |
| `nightly/<size>.png` | per-size renders for the Nightly package and the title bar's icon in a Nightly window (16 to 512 px). Kept out of `hicolor/`, which Stable's Linux and FreeBSD packagers copy whole |
| `nightly-provenance.json` | the inputs, the palette, the transform and the SHA-256 of every output |
`packaging/nightly-icons.py` derives all of them from the committed stable renders (no upscale, no
resvg, no Pillow): run it after `packaging/icons.sh` changes a stable file, and
`python3 packaging/nightly-icons.py --check` (part of `packaging/nightly-tests.py`) fails when a
committed Nightly file has drifted.
+81
View File
@@ -0,0 +1,81 @@
{
"title": "TextureCraft nightly deep-background icons",
"license": "MIT OR Apache-2.0",
"generator": "packaging/nightly-icons.py",
"generator_sha256": "745786e3bfbecf29077df1e4a64ed717953694038f95533d2d37507c520b791c",
"inputs": [
{
"path": "assets/app-icon/texturecraft.icns",
"sha256": "eb5e1b19679aa9a23531219d92922e37edbdc3e2046454b8f6c64423f471b57b"
},
{
"path": "assets/app-icon/texturecraft.ico",
"sha256": "9c3366e4af9f2c0772e00193c348feba834d407fc8b826d4276a8fcb4cc01dcb"
},
{
"path": "assets/app-icon/texturecraft-1024.png",
"sha256": "8451f91be8c1bc9c2e1a594e193ae5d1793d2d12f26a8bc64d2bd83fe4b789e4"
},
{
"path": "assets/app-icon/hicolor/16x16/apps/ai.storyteller.texturecraft.png",
"sha256": "79ee309754be54b56052ab05fff87a2427bbc38bb057c96094f8f070ee13ca1d"
},
{
"path": "assets/app-icon/hicolor/24x24/apps/ai.storyteller.texturecraft.png",
"sha256": "f8f89220ce68be236d63edfd94d4fef2aad2aa9840a50e430f874649a9816171"
},
{
"path": "assets/app-icon/hicolor/32x32/apps/ai.storyteller.texturecraft.png",
"sha256": "ff8578ffc95f5123bb2e4a00636080f02adf259334ecb0ac9f952fac3378ddb2"
},
{
"path": "assets/app-icon/hicolor/48x48/apps/ai.storyteller.texturecraft.png",
"sha256": "f7f19ffbd8904ff462bc6d785b865153112025bbdeb868bc0f136e39c7d725e1"
},
{
"path": "assets/app-icon/hicolor/64x64/apps/ai.storyteller.texturecraft.png",
"sha256": "39d17421579ace5dbe4705fb0a52cd6002d433ded7ba0ee2fdeb5d6d7cd16c8c"
},
{
"path": "assets/app-icon/hicolor/128x128/apps/ai.storyteller.texturecraft.png",
"sha256": "ac629a038a215a13d86172286142502b6efd17618869652050f291d9745346d2"
},
{
"path": "assets/app-icon/hicolor/256x256/apps/ai.storyteller.texturecraft.png",
"sha256": "757f858b26897cb0e9f0c8cd43db9ade9664dd6199bd190d1af406839769c71f"
},
{
"path": "assets/app-icon/hicolor/512x512/apps/ai.storyteller.texturecraft.png",
"sha256": "705513dc82aa908f962b9a466743b42e53b0f586752d2d69a5b6596b8ff928f0"
}
],
"method": {
"kind": "derivative of the project-owned stable renders; no badge, crescent or letter",
"original_palette": {
"ink": "#0b0b0c",
"paper": "#efe9dc",
"background": "#c2672b"
},
"nightly_background": "#643418",
"transform": "Fit each pixel as the tile background plus one engraved foreground (ink or paper) and replace only the background contribution; keep alpha, padding and foreground detail. Each frame comes from the stable master of its own size: the .icns and .ico PNG frames are recoloured in place, and the per-size PNGs (in nightly/) and the 1024 master are recoloured from their own renders. No upscaling."
},
"outputs": {
"assets/app-icon/texturecraft-nightly.icns": "e21e2c90f7402e6289038ad7db896a14780766e07f33d9cb68cbe0d423efe66d",
"assets/app-icon/texturecraft-nightly.ico": "b0dc8817a3b07f0eb8175241c1fdc1ce21ffb8d5a54e6b03979ba2f73e62d47e",
"assets/app-icon/nightly/16.png": "657c7a39547828b0eaafe4b78df28771bb953afdb62440d0c001c695ff586e76",
"assets/app-icon/nightly/24.png": "b4c263436402faa93276b77614291107f6b44309ccfe329b71c3562c1f382c11",
"assets/app-icon/nightly/32.png": "cefb99a330d103f32a07d07e49542da2231897224a3dfe479e9c9d4a53a0a17b",
"assets/app-icon/nightly/48.png": "126316a058f4a225fbea7e1c0e49dc3d27941e2a91a7f033f35b84bc6d646f22",
"assets/app-icon/nightly/64.png": "d471a4bd691fca348603571bfe9c05357120e492566e31c7b2c936361a4a2510",
"assets/app-icon/nightly/128.png": "b36b07739b98b7884ce308641407725bb499adfefd87a4286c3aa117abdb57d5",
"assets/app-icon/nightly/256.png": "82c417bbcafd9b90929b117b7f80f403e631a77a327ee868bc9e8ca7a44c7fe2",
"assets/app-icon/nightly/512.png": "de756e67f16076a08cb5c2726d1a63181a0a8b61c73ff3df0cf49e065f1c8bc2",
"assets/app-icon/texturecraft-nightly-1024.png": "509ebc6130db6c10c380bc4ee2280a6b1810eea5dc03293b86a575c1ef120736",
"assets/app-icon/texturecraft-nightly.png": "82c417bbcafd9b90929b117b7f80f403e631a77a327ee868bc9e8ca7a44c7fe2"
},
"ico_frames": [
"the stable .ico's own frames (16, 20, 24, 32, 40, 48, 64, 128, 256)"
],
"icns_slots": "the stable .icns's own PNG slots (icp4 through ic10)",
"validation": "Byte comparison against the committed assets (packaging/nightly-archive-tests.py and the icon check in packaging/nightly-tests.py); native Explorer/Finder rendering is not exercised here. The per-size PNGs are kept out of hicolor/ because Stable's Linux and FreeBSD packages copy that theme tree whole."
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 9.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 484 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 810 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 82 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 220 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.
+4 -9
View File
@@ -228,14 +228,6 @@ mod tests {
out
}
#[test]
fn the_unlit_switch_decides_whether_a_channel_view_is_lit() {
let mut s = texturecraft_engine::sample_session(128, 64).unwrap();
assert!(!shade(&s).solo_lit, "channel views are flat by default");
execute(&mut s, "display.set", &json!({"soloUnlit": false})).unwrap();
assert!(shade(&s).solo_lit);
}
#[test]
fn renders_with_an_imported_hdr_environment() {
let mesh = texturecraft_engine::geom::primitives::material_ball();
@@ -284,8 +276,10 @@ mod tests {
let mut mesh = texturecraft_engine::geom::primitives::plane(2.0, 1);
mesh.append(&texturecraft_engine::geom::primitives::plane(2.0, 1));
let mut session = Session::new_project("Test", mesh, "two-planes", None, 128).unwrap();
assert_eq!(session.caches.len(), 2);
session.images.insert("red".into(), Arc::new(ImageRes { width: 1, height: 1, rgba: vec![[1.0, 0.0, 0.0, 1.0]], srgb: true }));
session.images.insert("red".into(), Arc::new(ImageRes::new(1, 1, vec![[1.0, 0.0, 0.0, 1.0]], true)));
execute(&mut session, "viewport.view", &json!({"mode": "image", "image": "red"})).unwrap();
let camera = session.camera;
let uv = |ts| ViewKind::Uv { ts, zoom: 1.0, pan: [0.0, 0.0], rotation: 0.0 };
@@ -302,6 +296,7 @@ mod tests {
assert!(first.as_chunks::<4>().0.iter().any(|pixel| pixel[0] > 200 && pixel[1] < 20));
let (_, _, second) = gpu.render(&mut session, uv(1), [128, 128], camera).unwrap();
assert!(second.as_chunks::<4>().0.iter().any(|pixel| pixel[0] > 200 && pixel[1] < 20));
assert_eq!(gpu.h.renderer.aux_size(1), Some(128));
}
-12
View File
@@ -141,18 +141,6 @@ fn sample_for_project_bake(resolution: u32) -> Headless {
backend
}
#[test]
fn project_bake_uses_documented_ray_count() {
let backend = sample_for_project_bake(256);
for texture_set in 0..backend.session.set_count() {
let task = backend.session.bake_task(texture_set).unwrap();
assert_eq!(task.settings.maps.ao.parameters.rays.rays, 32);
assert_eq!(task.settings.maps.thickness.parameters.rays.rays, 32);
assert_eq!(task.settings.maps.bent_normal.parameters.rays.rays, 32);
}
}
/// The whole-project bake at benchmark settings (1024², 32 rays, AA 1), then 2048².
#[test]
#[ignore]
+72
View File
@@ -0,0 +1,72 @@
use crate::cage::RayFrame;
use crate::map::BakeContext;
use crate::tracing::{CpuTracer, Tracer};
use crate::{BakeError, BakeOutput, BakeRequest, MeshExtent, Progress};
use std::sync::atomic::Ordering::Relaxed;
use texturecraft_core::{BakeSettings, BakedMap};
/// Map passes over one immutable request share the fitted cage and prepared skew.
pub struct BakePasses<'a> {
request: BakeRequest<'a>,
frame: Option<(MeshExtent, RayFrame<'a>)>,
}
impl<'a> BakePasses<'a> {
pub fn new(request: BakeRequest<'a>) -> Self {
Self { request, frame: None }
}
/// Bake one selected map, including the CPU fallback used by a normal bake.
pub fn bake_map(
&mut self,
map: BakedMap,
progress: &Progress,
excluded_tiles: &[(u32, u32)],
tracer: Option<&dyn Tracer>,
) -> Result<BakeOutput, BakeError> {
let mut settings = self.request.settings.clone();
settings.maps.select([map]);
self.run(&settings, progress, excluded_tiles, tracer, super::STRIP_TEXELS)
}
pub(super) fn run(
&mut self,
settings: &BakeSettings,
progress: &Progress,
excluded_tiles: &[(u32, u32)],
tracer: Option<&dyn Tracer>,
strip_texels: usize,
) -> Result<BakeOutput, BakeError> {
if progress.cancel.load(Relaxed) {
return Err(BakeError::Cancelled);
}
let request = BakeRequest { settings, ..self.request };
super::validate(&request)?;
if excluded_tiles.iter().any(|(column, row)| *column >= request.tiles.0 || *row >= request.tiles.1) {
return Err(BakeError::Invalid("excluded UV tile lies outside the bake atlas".into()));
}
// Validate each pass separately so earlier maps can finish before a later map fails
let (extent, frame) = match &mut self.frame {
Some(geometry) => geometry,
None => {
let extent = MeshExtent::of(request.mesh)?;
self.frame.insert((extent, RayFrame::new(&self.request, extent)?))
}
};
let context = BakeContext::with_frame(&request, *extent, frame);
let bake = |tracer: &dyn Tracer| super::bake_prepared(&request, &context, progress, strip_texels, tracer, excluded_tiles);
match tracer {
Some(tracer) => match bake(tracer) {
Err(BakeError::Tracer(error)) => {
let mut output = bake(&CpuTracer)?;
output.tracer = format!("CPU ({} unavailable: {error})", tracer.name());
Ok(output)
}
result => result,
},
None => bake(&CpuTracer),
}
}
}
+3
View File
@@ -1,7 +1,9 @@
//! Where the bake's transfer rays start, shared by the bake and the cage the 3D view draws
mod cage_shell;
mod fitted_cage;
mod high_poly_reach;
mod name_keys;
mod ray_frame;
mod ray_start;
mod vertex_reach;
@@ -9,6 +11,7 @@ mod vertex_reach;
#[cfg(test)]
pub(crate) use cage_shell::CORNERS;
pub use cage_shell::CageShell;
pub(crate) use fitted_cage::FittedCage;
pub use high_poly_reach::HighPolyReach;
pub(crate) use ray_frame::RayFrame;
pub use ray_start::RayStart;
+231
View File
@@ -0,0 +1,231 @@
use super::name_keys::NameKeys;
use crate::map::interpolate;
use crate::{BakeRequest, HighPoly, MeshExtent};
use rayon::prelude::*;
use std::borrow::Cow;
use std::collections::{HashMap, VecDeque};
use texturecraft_geom::Mesh;
use texturecraft_geom::glam::Vec3;
/// How much farther than the high poly the cage reaches, as a fraction of the fitted distance: the fit reads both meshes at their vertices only. Tuned with [`MARGIN_PER_DIAGONAL`] on two production meshes: the tightest pair whose rays miss no more texels than the default distances do
const MARGIN_PER_DISTANCE: f32 = 0.5;
/// The least the cage reaches each way, as a fraction of the mesh diagonal, so a high poly lying on the low poly is still inside
const MARGIN_PER_DIAGONAL: f32 = 4e-3;
/// How many times farther than the nearest high-poly point a low-poly vertex's ray may find the high poly: beyond it (a surface more than about 75 degrees off the ray) the ray has left the vertex's own part
const MAX_RAY_PER_NEAREST_DISTANCE: f32 = 4.0;
/// Bound temporary high-vertex projections while giving Rayon thousands of independent queries per batch
const PROJECTION_BATCH_VERTICES: usize = 8192;
/// The automatic cage: how far the transfer rays start in front of each low-poly vertex and how far they run behind it, fitted to the high poly
pub(crate) struct FittedCage {
/// (front, rear) in world units per low-poly vertex; `None` on parts no high poly is near
distances: Vec<Option<(f32, f32)>>,
}
impl FittedCage {
/// Fit the cage of `request`'s low poly around `high` along `ray_normals` (where parts welded back to back cancelled a vertex's normal out, along its own): each low-poly vertex reaches the high poly straight in front of or behind it, and each high-poly vertex pushes the corners of its nearest low-poly triangle out (or in) to its height. Vertices neither finds take their neighbours' distances; a part the high poly reaches nowhere gets none
pub(crate) fn new(request: &BakeRequest, high: HighPoly, welded_indices: &[u32], ray_normals: &[Vec3], extent: MeshExtent) -> FittedCage {
let low = request.mesh;
let keys = NameKeys::of(request, high);
let welded_indices = welded_within_groups(welded_indices, &keys.low_vertices);
let welded = |vertex: usize| welded_indices.get(vertex).copied().unwrap_or(0) as usize;
let welded_count = welded_indices.iter().max().map_or(0, |last| *last as usize + 1);
let fitting_normals = fitting_normals(low, ray_normals);
let mut reach: Vec<Option<(f32, f32)>> = vec![None; welded_count];
let mut widen = |vertex: usize, height: f32| {
if let Some(distances) = reach.get_mut(welded(vertex)) {
let (front, rear) = distances.unwrap_or((0.0, 0.0));
*distances = Some((front.max(height), rear.max(-height)));
}
};
for (vertex, height) in heights_at_low_vertices(low, high, &fitting_normals, &keys, extent.diagonal).into_iter().enumerate() {
if let Some(height) = height {
widen(vertex, height);
}
}
let mut projected = Vec::new();
for (batch, positions) in high.mesh.positions.chunks(PROJECTION_BATCH_VERTICES).enumerate() {
let first = batch * PROJECTION_BATCH_VERTICES;
positions
.par_iter()
.enumerate()
.map(|(index, &position)| project_high_vertex(request, &fitting_normals, &keys, first + index, position))
.collect_into_vec(&mut projected);
for (triangle, height) in projected.drain(..).flatten() {
for corner in low.tri(triangle).into_iter().flatten() {
widen(corner, height);
}
}
}
drop(projected);
spread_to_neighbours(&mut reach, low.indices.as_chunks::<3>().0.iter().map(|corners| corners.map(|corner| welded(corner as usize))));
let floor = MARGIN_PER_DIAGONAL * extent.diagonal;
let padded = |distance: f32| distance * (1.0 + MARGIN_PER_DISTANCE) + floor;
let distances =
(0..low.positions.len()).map(|vertex| reach.get(welded(vertex)).copied().flatten().map(|(front, rear)| (padded(front), padded(rear)))).collect();
FittedCage { distances }
}
/// The (front, rear) distances at `barycentric` of triangle `triangle` of the low poly `low` the cage was fitted to; `None` where the high poly reaches no corner
pub(crate) fn distances(&self, low: &Mesh, triangle: u32, barycentric: [f32; 2]) -> Option<(f32, f32)> {
let corners = low.tri(triangle as usize)?;
let [first, second, third] = [0, 1, 2].map(|corner| self.distances.get(corners[corner]).copied().flatten());
let ((first_front, first_rear), (second_front, second_rear), (third_front, third_rear)) = (first?, second?, third?);
let [second_weight, third_weight] = barycentric;
let first_weight = 1.0 - second_weight - third_weight;
Some((
first_front * first_weight + second_front * second_weight + third_front * third_weight,
first_rear * first_weight + second_rear * second_weight + third_rear * third_weight,
))
}
}
/// `welded_indices` with the vertices of different mesh-name groups (`vertex_keys`, empty when names don't matter) kept apart, so a group's distances come only from its own high poly and never spread into another group
fn welded_within_groups<'a>(welded_indices: &'a [u32], vertex_keys: &[u32]) -> Cow<'a, [u32]> {
if vertex_keys.is_empty() {
return Cow::Borrowed(welded_indices);
}
let mut indices: HashMap<(u32, Option<u32>), u32> = HashMap::new();
welded_indices
.iter()
.enumerate()
.map(|(vertex, &welded)| {
let next = indices.len() as u32;
*indices.entry((welded, vertex_keys.get(vertex).copied())).or_insert(next)
})
.collect()
}
/// `ray_normals`, except where parts welded back to back cancelled a vertex's normal out: there, the vertex's own normal, the direction its transfer rays fall back to
fn fitting_normals<'a>(low: &Mesh, ray_normals: &'a [Vec3]) -> Cow<'a, [Vec3]> {
if !ray_normals.contains(&Vec3::ZERO) {
return Cow::Borrowed(ray_normals);
}
ray_normals
.iter()
.enumerate()
.map(|(vertex, &welded_normal)| {
if welded_normal != Vec3::ZERO {
return welded_normal;
}
low.normals.get(vertex).and_then(|normal| normal.try_normalize()).unwrap_or(welded_normal)
})
.collect()
}
/// Per low-poly vertex, how far along its ray normal the high-poly surface in front of it (positive) or behind it (negative) is. A ray that only finds a surface much farther than the nearest high-poly point (within `max_distance`) found another part, so the vertex takes that nearest point's height instead
fn heights_at_low_vertices(low: &Mesh, high: HighPoly, ray_normals: &[Vec3], keys: &NameKeys, max_distance: f32) -> Vec<Option<f32>> {
low.positions
.par_iter()
.zip(ray_normals)
.enumerate()
.map(|(vertex, (&position, &up))| {
let low_key = keys.low_vertices.get(vertex);
let rays_reach = |triangle: u32| NameKeys::matches(low_key, keys.high_triangles.get(triangle as usize));
let nearest = high.bvh.nearest(position, max_distance, &rays_reach)?;
let nearest_position = interpolate(high.mesh, &high.mesh.positions, nearest.tri, [nearest.u, nearest.v])?;
let ray_limit = nearest.t * MAX_RAY_PER_NEAREST_DISTANCE + MARGIN_PER_DIAGONAL * max_distance;
let distance = |direction: Vec3| high.bvh.closest_filtered(position, direction, ray_limit, &rays_reach).map(|hit| hit.t);
Some(match (distance(up), distance(-up)) {
(Some(front), Some(rear)) if front <= rear => front,
(Some(front), None) => front,
(_, Some(rear)) => -rear,
(None, None) => (nearest_position - position).dot(up),
})
})
.collect()
}
/// The nearest matching low-poly triangle and signed height of one high-poly vertex
fn project_high_vertex(request: &BakeRequest, ray_normals: &[Vec3], keys: &NameKeys, vertex: usize, position: Vec3) -> Option<(usize, f32)> {
let low = request.mesh;
let high_key = keys.high_vertices.get(vertex);
let rays_reach = |triangle: u32| NameKeys::matches(keys.low_triangles.get(triangle as usize), high_key);
let nearest = request.bvh.nearest(position, f32::INFINITY, &rays_reach)?;
let barycentric = [nearest.u, nearest.v];
let low_position = interpolate(low, &low.positions, nearest.tri, barycentric)?;
let up = interpolate(low, ray_normals, nearest.tri, barycentric)?.try_normalize()?;
Some((nearest.tri as usize, (position - low_position).dot(up)))
}
/// Give each vertex without distances the largest of its nearest fitted neighbours', walking outward along the edges of `triangles`
fn spread_to_neighbours(reach: &mut [Option<(f32, f32)>], triangles: impl Iterator<Item = [usize; 3]>) {
// Only unfitted vertices adjacent to a fitted region can gain distances
if reach.iter().all(Option::is_some) || reach.iter().all(Option::is_none) {
return;
}
let mut neighbours = vec![Vec::new(); reach.len()];
for corners in triangles {
for (corner, next) in [(0, 1), (1, 2), (2, 0)] {
if let (true, Some(list)) = (corners[next] < reach.len(), neighbours.get_mut(corners[corner])) {
list.push(corners[next]);
}
if let (true, Some(list)) = (corners[corner] < reach.len(), neighbours.get_mut(corners[next])) {
list.push(corners[corner]);
}
}
}
// Propagate distances from the preceding breadth-first layer
let mut steps: Vec<Option<u32>> = reach.iter().map(|distances| distances.map(|_| 0)).collect();
let mut queue: VecDeque<usize> = (0..reach.len()).filter(|vertex| reach[*vertex].is_some()).collect();
while let Some(vertex) = queue.pop_front() {
let (Some((front, rear)), Some(step)) = (reach[vertex], steps[vertex]) else { continue };
for &neighbour in &neighbours[vertex] {
match steps[neighbour] {
None => {
steps[neighbour] = Some(step + 1);
reach[neighbour] = Some((front, rear));
queue.push_back(neighbour);
}
Some(neighbour_step) if neighbour_step == step + 1 => {
let (neighbour_front, neighbour_rear) = reach[neighbour].unwrap_or((0.0, 0.0));
reach[neighbour] = Some((neighbour_front.max(front), neighbour_rear.max(rear)));
}
Some(_) => {}
}
}
}
}
#[cfg(test)]
mod tests {
use super::{spread_to_neighbours, welded_within_groups};
#[test]
fn coincident_vertices_of_different_name_groups_are_not_welded() {
// The coincident pairs span different mesh-name groups
assert_eq!(welded_within_groups(&[0, 0, 1, 1], &[5, 7, 7, 5]).as_ref(), [0, 1, 2, 3]);
assert_eq!(welded_within_groups(&[0, 0, 1, 1], &[5, 5, 7, 7]).as_ref(), [0, 0, 1, 1], "same group: still welded");
assert_eq!(welded_within_groups(&[0, 0, 1], &[]).as_ref(), [0, 0, 1], "without name matching nothing changes");
}
#[test]
fn unfitted_vertices_take_the_largest_distances_of_their_nearest_fitted_neighbours() {
// A strip of triangles 0-1-2, 1-2-3, 2-3-4: vertices 0 and 4 are fitted
let mut reach = vec![Some((1.0, 0.5)), None, None, None, Some((3.0, 0.25))];
spread_to_neighbours(&mut reach, [[0, 1, 2], [1, 2, 3], [2, 3, 4]].into_iter());
assert_eq!(reach[1], Some((1.0, 0.5)), "one step from vertex 0 only");
assert_eq!(reach[3], Some((3.0, 0.25)), "one step from vertex 4 only");
assert_eq!(reach[2], Some((3.0, 0.5)), "one step from both: the larger of each");
}
}
+1 -1
View File
@@ -75,7 +75,7 @@ impl HighPolyReach {
}
/// Each vertex's mesh-name key, from the first triangle that uses it
fn vertex_keys(mesh: &Mesh, triangle_keys: &[u32]) -> Vec<u32> {
pub(super) fn vertex_keys(mesh: &Mesh, triangle_keys: &[u32]) -> Vec<u32> {
let mut keys = vec![ANY; mesh.positions.len()];
for (corners, &triangle_key) in mesh.indices.as_chunks::<3>().0.iter().zip(triangle_keys) {
for &corner in corners {
+38
View File
@@ -0,0 +1,38 @@
use super::high_poly_reach::vertex_keys;
use crate::map::transfer_keys;
use crate::tracing::ANY;
use crate::{BakeRequest, HighPoly};
use texturecraft_core::MeshMatchMode;
/// The mesh-name keys of a bake's low and high poly, per triangle and per vertex; all empty when every ray may hit every part
#[derive(Default)]
pub(super) struct NameKeys {
pub(super) low_triangles: Vec<u32>,
pub(super) low_vertices: Vec<u32>,
pub(super) high_triangles: Vec<u32>,
pub(super) high_vertices: Vec<u32>,
}
impl NameKeys {
/// The keys `request` bakes with against `high`: filled only when it matches by mesh name
pub(super) fn of(request: &BakeRequest, high: HighPoly) -> NameKeys {
match request.settings.high_poly.match_mode {
MeshMatchMode::Always => NameKeys::default(),
MeshMatchMode::ByMeshName => {
let (low_triangles, high_triangles) = transfer_keys(request);
NameKeys {
low_vertices: vertex_keys(request.mesh, &low_triangles),
high_vertices: vertex_keys(high.mesh, &high_triangles),
low_triangles,
high_triangles,
}
}
}
}
/// Whether a ray from the low-poly part keyed `low_key` may hit the high-poly part keyed `high_key`; a missing key is a part any ray may hit
pub(super) fn matches(low_key: Option<&u32>, high_key: Option<&u32>) -> bool {
let low_key = low_key.copied().unwrap_or(ANY);
low_key == ANY || low_key == high_key.copied().unwrap_or(ANY)
}
}
+17 -5
View File
@@ -1,4 +1,4 @@
use super::RayStart;
use super::{FittedCage, RayStart};
use crate::MeshExtent;
use crate::map::{interpolate, welded};
use crate::skew::PreparedSkew;
@@ -7,11 +7,12 @@ use texturecraft_core::CageType;
use texturecraft_geom::glam::Vec3;
use texturecraft_geom::{Mesh, Surface};
/// What decides where transfer rays start: the cage mesh or the averaged normals, skew and painted cage amount
/// What decides where transfer rays start: the cage mesh, the automatic cage's fitted distances, or the averaged normals, skew and painted cage amount
pub(crate) struct RayFrame<'a> {
mesh: &'a Mesh,
ray_normals: Vec<Vec3>,
cage: Option<&'a Mesh>,
fitted: Option<FittedCage>,
skew: Option<PreparedSkew<'a>>,
cage_paint: Option<&'a BakePaintMap>,
/// Cage-file offsets this short count as none: the ray starts from the distance-based cage instead
@@ -23,18 +24,24 @@ pub(crate) struct RayFrame<'a> {
impl<'a> RayFrame<'a> {
pub(crate) fn new(request: &BakeRequest<'a>, extent: MeshExtent) -> Result<RayFrame<'a>, BakeError> {
let settings = request.settings;
let ray_normals = match settings.cage.average_normals && request.high.is_some() {
// The automatic cage is one closed shell, so its rays always follow the averaged normals
let automatic_high = request.high.filter(|_| settings.cage.kind == CageType::Automatic);
let (ray_normals, fitted) = match (settings.cage.average_normals || automatic_high.is_some()) && request.high.is_some() {
true => {
let (welded_indices, _, normals) = welded(request.mesh, extent.diagonal);
welded_indices.iter().map(|index| normals.get(*index as usize).copied().unwrap_or(Vec3::Y)).collect()
let ray_normals: Vec<Vec3> = welded_indices.iter().map(|index| normals.get(*index as usize).copied().unwrap_or(Vec3::Y)).collect();
let fitted = automatic_high.map(|high| FittedCage::new(request, high, &welded_indices, &ray_normals, extent));
(ray_normals, fitted)
}
false => Vec::new(),
false => (Vec::new(), None),
};
Ok(RayFrame {
mesh: request.mesh,
ray_normals,
cage: if settings.cage.kind == CageType::CustomFile { request.cage } else { None },
fitted,
skew: request.skew.map(|skew_map| PreparedSkew::new(skew_map, request.mesh, extent.scale, settings.skew)).transpose()?,
cage_paint: request.cage_paint,
ray_epsilon: extent.ray_epsilon(),
@@ -54,6 +61,11 @@ impl<'a> RayFrame<'a> {
}
let averaged_normal = interpolate(self.mesh, &self.ray_normals, surface.tri, barycentric).and_then(Vec3::try_normalize).unwrap_or(surface.nrm);
let fitted_distances = self.fitted.as_ref().and_then(|fitted| fitted.distances(self.mesh, surface.tri, barycentric));
if let Some((front, rear)) = fitted_distances {
return RayStart::Fitted { up: averaged_normal, front, rear };
}
let up = match &self.skew {
Some(skew) => skew.correct(self.mesh, surface, averaged_normal),
None => averaged_normal,
+12
View File
@@ -7,6 +7,8 @@ pub enum RayStart {
CageMesh(Vec3),
/// Out along `up` by the frontal distance times `scale` (the painted cage amount)
Distance { up: Vec3, scale: f32 },
/// Out along `up` by `front` world units and reaching `rear` past the low-poly point: the automatic cage's own distances
Fitted { up: Vec3, front: f32, rear: f32 },
}
impl RayStart {
@@ -15,6 +17,16 @@ impl RayStart {
match *self {
RayStart::CageMesh(offset) => position - offset,
RayStart::Distance { up, scale } => position + up * frontal * scale,
RayStart::Fitted { up, front, .. } => position + up * front,
}
}
/// The ray's direction, how far it runs to the low-poly point and how far past it, at `frontal` and `rear` world units of the distance settings
pub fn span(&self, frontal: f32, rear: f32) -> (Vec3, f32, f32) {
match *self {
RayStart::CageMesh(offset) => (offset.normalize_or_zero(), offset.length(), rear),
RayStart::Distance { up, scale } => (-up, frontal * scale, rear),
RayStart::Fitted { up, front, rear: fitted_rear } => (-up, front, fitted_rear),
}
}
}
+1 -4
View File
@@ -17,10 +17,7 @@ impl VertexReach {
/// Whether the ray misses the vertex (or may not hit its part) at `frontal` and `rear` world units of cage distance; with `ignore_backface` it also misses a vertex whose triangles face away from the ray
pub fn missed(&self, frontal: f32, rear: f32, ignore_backface: bool) -> bool {
let origin = self.start.origin(self.low_position, frontal);
let (direction, front) = match self.start {
RayStart::CageMesh(offset) => (offset.normalize_or_zero(), offset.length()),
RayStart::Distance { up, scale } => (-up, frontal * scale),
};
let (direction, front, rear) = self.start.span(frontal, rear);
let along_ray = (self.high_position - origin).dot(direction);
!self.name_matches || !(0.0..=front + rear).contains(&along_ray) || (ignore_backface && self.high_facing.dot(direction) > 0.0)
+26 -16
View File
@@ -5,6 +5,7 @@
mod bake_error;
mod bake_output;
mod bake_passes;
mod bake_request;
mod cage;
mod high_poly;
@@ -14,6 +15,7 @@ mod progress;
pub use bake_error::BakeError;
pub use bake_output::BakeOutput;
pub use bake_passes::BakePasses;
pub use bake_request::BakeRequest;
pub use cage::{CageShell, HighPolyReach, RayStart, VertexReach};
pub use high_poly::HighPoly;
@@ -149,7 +151,7 @@ fn alloc<T: Clone>(count: usize, value: T) -> Result<Vec<T>, BakeError> {
}
pub fn bake(request: &BakeRequest, progress: &Progress) -> Result<BakeOutput, BakeError> {
bake_in_strips(request, progress, STRIP_TEXELS, &CpuTracer, &[])
bake_tiles(request, progress, &[], None)
}
/// Retry on the CPU if the supplied tracer fails
@@ -159,19 +161,12 @@ pub fn bake_on(request: &BakeRequest, progress: &Progress, tracer: &dyn Tracer)
/// Excluded atlas blocks produce no samples; their geometry still participates in ray tracing
pub fn bake_tiles(request: &BakeRequest, progress: &Progress, excluded_tiles: &[(u32, u32)], tracer: Option<&dyn Tracer>) -> Result<BakeOutput, BakeError> {
let tracer = tracer.unwrap_or(&CpuTracer);
match bake_in_strips(request, progress, STRIP_TEXELS, tracer, excluded_tiles) {
Err(BakeError::Tracer(error)) => {
let mut output = bake_in_strips(request, progress, STRIP_TEXELS, &CpuTracer, excluded_tiles)?;
output.tracer = format!("CPU ({} unavailable: {error})", tracer.name());
Ok(output)
}
result => result,
}
BakePasses::new(*request).run(request.settings, progress, excluded_tiles, tracer, STRIP_TEXELS)
}
type OutRow<'a> = Vec<&'a mut [f32]>;
#[cfg(test)]
fn bake_in_strips(
request: &BakeRequest,
progress: &Progress,
@@ -179,9 +174,19 @@ fn bake_in_strips(
tracer: &dyn Tracer,
excluded_tiles: &[(u32, u32)],
) -> Result<BakeOutput, BakeError> {
validate(request)?;
if excluded_tiles.iter().any(|(column, row)| *column >= request.tiles.0 || *row >= request.tiles.1) {
return Err(BakeError::Invalid("excluded UV tile lies outside the bake atlas".into()));
BakePasses::new(*request).run(request.settings, progress, excluded_tiles, Some(tracer), strip_texels)
}
fn bake_prepared(
request: &BakeRequest,
context: &map::BakeContext,
progress: &Progress,
strip_texels: usize,
tracer: &dyn Tracer,
excluded_tiles: &[(u32, u32)],
) -> Result<BakeOutput, BakeError> {
if progress.cancel.load(Relaxed) {
return Err(BakeError::Cancelled);
}
let settings = request.settings;
@@ -189,7 +194,6 @@ fn bake_in_strips(
let tile_size = (tile_width as usize, tile_height as usize);
let samples_per_axis = settings.common.antialiasing.samples_per_axis() as usize;
let (width, height) = (tile_size.0 * request.tiles.0 as usize, tile_size.1 * request.tiles.1 as usize);
let context = map::BakeContext::new(request)?;
let tracer = if context.casts_rays() { tracer } else { &CpuTracer };
let meshes = context.trace_meshes();
let mut scene = tracer.scene(&meshes)?;
@@ -259,9 +263,10 @@ fn bake_in_strips(
if progress.cancel.load(Relaxed) {
return Err(BakeError::Cancelled);
}
// Global sample indices keep noise unchanged across strip and batch sizes
bake_rows(
&context,
context,
&maps,
request.mesh,
&gbuffer,
@@ -313,6 +318,7 @@ fn bake_in_strips(
if progress.cancel.load(Relaxed) {
return Err(BakeError::Cancelled);
}
progress.done.store(10_000, Relaxed);
Ok(BakeOutput { resolution: width as u32, height: height as u32, maps: output, tracer: tracer.name() })
}
@@ -349,6 +355,7 @@ fn bake_rows(
.collect()
})
.collect();
let row_offsets: Vec<usize> = samples_by_row
.iter()
.scan(0, |sample_count, row| {
@@ -362,11 +369,12 @@ fn bake_rows(
true => {
let (rays, frontal_distances): (Vec<tracing::Ray>, Vec<f32>) = samples().map(|sample| context.transfer_ray(&sample.surface, sample.bary)).unzip();
let hits = scene.closest(1, &rays, context.ignore_transfer_backface())?;
hits.into_par_iter().zip(frontal_distances).map(|(hit, front)| context.transfer(hit, front)).collect()
hits.into_par_iter().zip(&rays).zip(frontal_distances).map(|((hit, ray), front)| context.transfer(hit, front, ray.max_distance)).collect()
}
false => Vec::new(),
};
let transfer = |sample_index: usize| transfers.get(sample_index).and_then(Option::as_ref);
let curvature = match context.traces_curvature() {
true => {
let items: Vec<(&Surface, Option<&map::Transfer>)> = samples_by_row
@@ -379,6 +387,7 @@ fn bake_rows(
}
false => Vec::new(),
};
let queries: Vec<tracing::Query> = match context.ao.is_some() || context.bent.is_some() || context.thickness.is_some() {
true => samples_by_row
.par_iter()
@@ -388,6 +397,7 @@ fn bake_rows(
.collect(),
false => Vec::new(),
};
// Share occlusion results when the bent-normal ray settings match
let separate_bent_pass = context.bent.filter(|_| context.bent != context.ao);
let passes: Vec<tracing::Hemisphere> = [context.ao, separate_bent_pass, context.thickness].into_iter().flatten().collect();
+14 -15
View File
@@ -1,7 +1,7 @@
use super::curvature::Curvature;
use super::sampling::{pack, splitmix64, tangent_normal};
use super::{position_projection::PositionProjection, source::Source, traced::Traced, transfer::Transfer};
use crate::cage::{RayFrame, RayStart};
use crate::cage::RayFrame;
use crate::tracing::{ANY, Hemisphere, Query, Ray, RayKind, RayScene, TraceMesh};
use crate::{BakeError, BakeRequest, MeshExtent};
use rayon::prelude::*;
@@ -12,10 +12,13 @@ use texturecraft_geom::{Hit, Surface, surface_at};
const CURVATURE_CHUNK: usize = 1 << 15;
/// Height relative to the rays divides by the ray's length; this keeps a zero-length ray from dividing by zero
const SHORTEST_RAY: f32 = 1e-20;
pub(crate) struct BakeContext<'a> {
low: Source<'a>,
high: Option<Source<'a>>,
ray_frame: RayFrame<'a>,
ray_frame: &'a RayFrame<'a>,
settings: &'a BakeSettings,
frontal: f32,
rear: f32,
@@ -28,11 +31,9 @@ pub(crate) struct BakeContext<'a> {
}
impl<'a> BakeContext<'a> {
pub(crate) fn new(request: &BakeRequest<'a>) -> Result<BakeContext<'a>, BakeError> {
pub(crate) fn with_frame(request: &BakeRequest<'a>, extent: MeshExtent, ray_frame: &'a RayFrame<'a>) -> Self {
let settings = request.settings;
let extent = MeshExtent::of(request.mesh)?;
let (low, high) = Source::of_request(request);
let ray_frame = RayFrame::new(request, extent)?;
let (mesh_scale, ray_epsilon) = (extent.scale, extent.ray_epsilon());
let pass = |map: BakedMap, ray_settings: &RaySettings, kind: RayKind| {
let half_angle_radians = (ray_settings.spread.clamp(0.0, 180.0) * 0.5).to_radians();
@@ -74,7 +75,7 @@ impl<'a> BakeContext<'a> {
}
let cage_units = ray_frame.cage_units;
Ok(BakeContext {
BakeContext {
low,
high,
ray_frame,
@@ -87,7 +88,7 @@ impl<'a> BakeContext<'a> {
ao,
bent,
thickness,
})
}
}
pub(crate) fn ignore_transfer_backface(&self) -> bool {
@@ -109,21 +110,19 @@ impl<'a> BakeContext<'a> {
pub(crate) fn transfer_ray(&self, surface: &Surface, barycentric: [f32; 2]) -> (Ray, f32) {
let start = self.ray_frame.start(surface, barycentric);
let origin = start.origin(surface.pos, self.frontal);
let (direction, front) = match start {
RayStart::CageMesh(offset) => (offset.normalize(), offset.length()),
RayStart::Distance { up, scale } => (-up, self.frontal * scale),
};
let (direction, front, rear) = start.span(self.frontal, self.rear);
let key = match self.settings.high_poly.match_mode {
MeshMatchMode::Always => ANY,
MeshMatchMode::ByMeshName => self.low.key.get(surface.tri as usize).copied().unwrap_or(ANY),
};
(Ray { origin, direction, max_distance: front + self.rear, key }, front)
(Ray { origin, direction, max_distance: front + rear, key }, front)
}
pub(crate) fn transfer(&self, hit: Option<Hit>, front: f32) -> Option<Transfer> {
/// What the transfer ray that ran `front` to the low poly and `ray_length` in all brought back from the high poly
pub(crate) fn transfer(&self, hit: Option<Hit>, front: f32, ray_length: f32) -> Option<Transfer> {
let (high, hit) = (self.high.as_ref()?, hit?);
let surface = surface_at(high.mesh, hit.tri, hit.u, hit.v)?;
Some(Transfer { surface, bary: [hit.u, hit.v], t: hit.t, front })
Some(Transfer { surface, bary: [hit.u, hit.v], t: hit.t, front, ray_length })
}
pub(crate) fn query(&self, transfer: Option<&Transfer>, low_surface: &Surface, seed: u64) -> Query {
@@ -245,7 +244,7 @@ impl<'a> BakeContext<'a> {
let relative_to_rays = self.settings.maps.height.parameters.normalization == texturecraft_core::HeightNormalization::RelativeToRayDistances;
[transfer.map_or(if relative_to_rays { 0.5 } else { 0.0 }, |hit| {
let height = hit.front - hit.t;
if relative_to_rays { (0.5 + height / (hit.front + self.rear).max(1e-20)).clamp(0.0, 1.0) } else { height }
if relative_to_rays { (0.5 + height / hit.ray_length.max(SHORTEST_RAY)).clamp(0.0, 1.0) } else { height }
}); 3]
}
BakedMap::Opacity if missed => [0.0; 3],
+2
View File
@@ -5,4 +5,6 @@ pub(crate) struct Transfer {
pub(super) bary: [f32; 2],
pub(super) t: f32,
pub(super) front: f32,
/// The whole ray, from the cage to its rear end
pub(super) ray_length: f32,
}
+9 -1
View File
@@ -17,7 +17,9 @@ fn painted_map() -> BakePaintMap {
fn assert_cage_matches_the_ray_origins(request: &BakeRequest) {
let shell = CageShell::new(request).unwrap();
let corners = shell.corners(request.settings.cage.max_frontal);
let context = BakeContext::new(request).unwrap();
let extent = crate::MeshExtent::of(request.mesh).unwrap();
let frame = crate::cage::RayFrame::new(request, extent).unwrap();
let context = BakeContext::with_frame(request, extent, &frame);
let triangles: Vec<usize> = request.mesh.triangles_of(request.material).collect();
assert_eq!(corners.len(), triangles.len() * 3);
@@ -60,6 +62,12 @@ fn the_cage_corners_are_the_bake_ray_origins() {
face_normals
};
assert_cage_matches_the_ray_origins(&request(&face_normals));
let automatic = {
let mut automatic = bake_settings.clone();
automatic.cage.kind = CageType::Automatic;
automatic
};
assert_cage_matches_the_ray_origins(&request(&automatic));
}
#[test]
+250
View File
@@ -0,0 +1,250 @@
use super::{covered_values, settings, transfer};
use crate::{BakeRequest, CageShell, HighPoly, HighPolyReach};
use texturecraft_core::{BakeSettings, BakedMap, CageType, MeshMatchMode};
use texturecraft_geom::glam::Vec3;
use texturecraft_geom::{Bvh, Mesh, primitives};
/// A distance setting far larger than any fitted distance in these tests, to tell the two apart
const UNFITTED_DISTANCE: f32 = 0.5;
/// Settings baking `maps` with the automatic cage, and distance settings no fitted cage comes near
fn automatic(maps: &[BakedMap]) -> BakeSettings {
let mut bake_settings = settings(32, maps);
bake_settings.cage.kind = CageType::Automatic;
bake_settings.cage.relative_to_bounding_box = false;
(bake_settings.cage.max_frontal, bake_settings.cage.max_rear) = (UNFITTED_DISTANCE, UNFITTED_DISTANCE);
bake_settings
}
/// How far each corner of the automatic cage of the flat `low` around `high` rises above it, with the corner's low-poly position
fn cage_heights(low: &Mesh, high: &Mesh, bake_settings: &BakeSettings) -> Vec<(Vec3, f32)> {
let (low_bvh, high_bvh) = (Bvh::new(low), Bvh::new(high));
let request = BakeRequest {
low_base_color: &[],
mesh: low,
bvh: &low_bvh,
material: 0,
settings: bake_settings,
high: Some(HighPoly { file_ids: &[], mesh: high, bvh: &high_bvh, base_color: &[] }),
cage: None,
skew: None,
cage_paint: None,
tiles: (1, 1),
};
let shell = CageShell::new(&request).unwrap();
let corners = shell.corners(bake_settings.cage.max_frontal);
shell.positions.iter().zip(corners).map(|(position, corner)| (*position, corner.y - position.y)).collect()
}
/// Every submesh on the first material, so the cage shell of material 0 covers all the parts
fn one_material(mesh: &mut Mesh) {
mesh.materials.truncate(1);
for submesh in &mut mesh.submeshes {
submesh.material = 0;
}
}
#[test]
fn the_automatic_cage_reaches_a_high_poly_the_default_distances_miss() {
let low = primitives::cube(1.0);
let high = primitives::sphere(0.8, 32, 16);
let opacity_of = |bake_settings: &BakeSettings| -> Vec<f32> {
let output = transfer(&low, &high, None, bake_settings).unwrap();
covered_values(&low, &output, BakedMap::Opacity).into_iter().map(|(_, opacity)| opacity).collect()
};
let distance_based = opacity_of(&settings(32, &[BakedMap::Opacity]));
assert!(distance_based.contains(&0.0), "the sphere is beyond the default distances at the middle of each face");
let mut bake_settings = settings(32, &[BakedMap::Opacity]);
bake_settings.cage.kind = CageType::Automatic;
let fitted = opacity_of(&bake_settings);
assert!(fitted.iter().all(|opacity| *opacity == 1.0), "every ray of the automatic cage finds the sphere");
// The triangles at the sphere's poles have no area, so a pole vertex has no side to face the ray with
bake_settings.high_poly.ignore_backface = false;
let (low_bvh, high_bvh) = (Bvh::new(&low), Bvh::new(&high));
let request = BakeRequest {
low_base_color: &[],
mesh: &low,
bvh: &low_bvh,
material: 0,
settings: &bake_settings,
high: Some(HighPoly { file_ids: &[], mesh: &high, bvh: &high_bvh, base_color: &[] }),
cage: None,
skew: None,
cage_paint: None,
tiles: (1, 1),
};
let reach = HighPolyReach::new(&request).unwrap();
for vertex in 0..high.positions.len() {
assert_eq!(reach.missed(vertex, 0.0, 0.0), Some(false), "high-poly vertex {vertex} is inside the cage whatever the distance settings");
}
}
#[test]
fn the_automatic_cage_stays_low_where_the_high_poly_is_low() {
const LOW_HEIGHT: f32 = 0.01;
const RAISED_HEIGHT: f32 = 0.2;
const RAISED_FROM_X: f32 = 0.25;
let low = primitives::plane(1.0, 8);
let mut high = primitives::plane(1.0, 40);
for position in &mut high.positions {
position.y = if position.x > RAISED_FROM_X { RAISED_HEIGHT } else { LOW_HEIGHT };
}
let heights = cage_heights(&low, &high, &automatic(&[BakedMap::Normal]));
for (position, height) in heights {
if position.x < 0.0 {
assert!((LOW_HEIGHT..RAISED_HEIGHT / 2.0).contains(&height), "the cage at {position} hugs the low part: {height}");
} else if position.x > RAISED_FROM_X + 0.125 {
assert!((RAISED_HEIGHT..RAISED_HEIGHT * 2.0).contains(&height), "the cage at {position} clears the raised part: {height}");
}
}
}
#[test]
fn a_ray_that_only_finds_a_far_surface_takes_the_nearest_surface_height_instead() {
const PATCH_HEIGHT: f32 = 0.02;
const CEILING_HEIGHT: f32 = 1.0;
// A low-plane vertex beside the patch's edge: the patch is its nearest high poly, the ceiling is straight above it
const BESIDE_PATCH: Vec3 = Vec3::new(0.125, 0.0, 0.0);
// Far enough that the ceiling's own corners are nearest to the low plane's border, not to the vertex tested
const CEILING_REACH: f32 = 1000.0;
// The ceiling starts just past the patch's edge (x = 0), the patch covers the low plane's other half
const CEILING_FROM_X: f32 = 0.05;
const PATCH_SIZE: f32 = 0.5;
const SAME_POSITION: f32 = 1e-4;
let low = primitives::plane(1.0, 8);
let mut high = primitives::plane(PATCH_SIZE, 1);
for position in &mut high.positions {
*position = Vec3::new(position.x - PATCH_SIZE / 2.0, PATCH_HEIGHT, position.z);
}
let ceiling = Mesh::from_parts(
vec![
Vec3::new(CEILING_FROM_X, CEILING_HEIGHT, -CEILING_REACH),
Vec3::new(CEILING_FROM_X, CEILING_HEIGHT, CEILING_REACH),
Vec3::new(CEILING_REACH, CEILING_HEIGHT, 0.0),
],
None,
vec![Default::default(); 3],
vec![0, 1, 2],
"ceiling",
)
.unwrap();
high.append(&ceiling);
let heights = cage_heights(&low, &high, &automatic(&[BakedMap::Normal]));
let (_, height) = heights.iter().find(|(position, _)| position.distance(BESIDE_PATCH) < SAME_POSITION).unwrap();
assert!(*height < CEILING_HEIGHT / 2.0, "the cage beside the patch stays near the patch, not the ceiling: {height}");
}
#[test]
fn a_part_no_high_poly_part_matches_keeps_the_distance_settings() {
let mut low = primitives::plane(1.0, 2);
let mut high = primitives::plane(1.0, 2);
low.submeshes[0].name = "panel_low".into();
high.submeshes[0].name = "door_high".into();
let mut bake_settings = automatic(&[BakedMap::Normal]);
bake_settings.high_poly.match_mode = MeshMatchMode::ByMeshName;
let heights = cage_heights(&low, &high, &bake_settings);
assert!(heights.iter().all(|(_, height)| *height == UNFITTED_DISTANCE));
}
#[test]
fn a_part_meeting_another_part_takes_its_distances_from_its_own_high_poly_only() {
const LOW_HEIGHT: f32 = 0.01;
const RAISED_HEIGHT: f32 = 0.3;
// Two low parts sharing the edge x = 0, under a low and a raised high-poly part matched by name
let part = |name: &str, side: f32, height: f32, subdivisions: usize| {
let mut part = primitives::plane(1.0, subdivisions);
for position in &mut part.positions {
*position += Vec3::new(side * 0.5, height, 0.0);
}
part.submeshes[0].name = name.into();
part
};
let mut low = part("left_low", -1.0, 0.0, 4);
low.append(&part("right_low", 1.0, 0.0, 4));
let mut high = part("left_high", -1.0, LOW_HEIGHT, 8);
high.append(&part("right_high", 1.0, RAISED_HEIGHT, 8));
for mesh in [&mut low, &mut high] {
one_material(mesh);
}
let mut bake_settings = automatic(&[BakedMap::Normal]);
bake_settings.high_poly.match_mode = MeshMatchMode::ByMeshName;
let heights = cage_heights(&low, &high, &bake_settings);
// The left part's triangles come first, three corners each
let left_corners = low.submeshes[0].count as usize;
for (position, height) in &heights[..left_corners] {
assert!(*height < RAISED_HEIGHT / 2.0, "the left part's cage at {position} stays near the left high poly: {height}");
}
}
#[test]
fn parts_back_to_back_fit_their_cages_along_their_own_normals() {
const SHEET_DISTANCE: f32 = 0.2;
// A plane facing up and the same plane facing down, each facing its own high-poly sheet: welded, their normals cancel out
let named = |mut mesh: Mesh, name: &str| {
mesh.submeshes[0].name = name.into();
mesh
};
let facing_down = |mut mesh: Mesh| {
for normal in &mut mesh.normals {
*normal = -*normal;
}
for triangle in mesh.indices.as_chunks_mut::<3>().0 {
triangle.swap(1, 2);
}
mesh
};
let sheet = |height: f32| {
let mut sheet = primitives::plane(1.0, 8);
for position in &mut sheet.positions {
position.y = height;
}
sheet
};
let mut low = named(primitives::plane(1.0, 4), "front_low");
low.append(&named(facing_down(primitives::plane(1.0, 4)), "back_low"));
let mut high = named(sheet(SHEET_DISTANCE), "front_high");
high.append(&named(facing_down(sheet(-SHEET_DISTANCE)), "back_high"));
for mesh in [&mut low, &mut high] {
one_material(mesh);
}
for match_mode in [MeshMatchMode::Always, MeshMatchMode::ByMeshName] {
let mut bake_settings = automatic(&[BakedMap::Normal]);
bake_settings.high_poly.match_mode = match_mode;
let heights = cage_heights(&low, &high, &bake_settings);
// The front part's triangles come first, three corners each
let front_corners = low.submeshes[0].count as usize;
for (position, height) in &heights[..front_corners] {
assert!(
(SHEET_DISTANCE..UNFITTED_DISTANCE).contains(height),
"{match_mode:?}: the front part's cage at {position} reaches the sheet above it, fitted: {height}"
);
}
for (position, height) in &heights[front_corners..] {
assert!(
(-UNFITTED_DISTANCE..=-SHEET_DISTANCE).contains(height),
"{match_mode:?}: the back part's cage at {position} reaches the sheet below it, fitted: {height}"
);
}
}
}
+8 -2
View File
@@ -69,7 +69,9 @@ fn a_vertex_is_missed_exactly_when_the_bake_ray_misses_it() {
tiles: (1, 1),
};
let reach = HighPolyReach::new(&request).unwrap();
let context = BakeContext::new(&request).unwrap();
let extent = crate::MeshExtent::of(request.mesh).unwrap();
let frame = crate::cage::RayFrame::new(&request, extent).unwrap();
let context = BakeContext::with_frame(&request, extent, &frame);
for (vertex, vertex_reach) in reach.vertices.iter().enumerate() {
let (vertex_reach, missed) = (vertex_reach.unwrap(), reach.missed(vertex, max_frontal, max_rear).unwrap());
@@ -94,6 +96,7 @@ fn a_vertex_is_missed_exactly_when_the_bake_ray_misses_it() {
}
}
}
assert!(checked[0] > 100 && checked[1] > 100, "both reached and missed vertices were compared: {checked:?}");
}
@@ -173,11 +176,14 @@ fn matching_by_mesh_name_misses_the_parts_with_another_name() {
tiles: (1, 1),
};
let reach = HighPolyReach::new(&request).unwrap();
let context = BakeContext::new(&request).unwrap();
let extent = crate::MeshExtent::of(request.mesh).unwrap();
let frame = crate::cage::RayFrame::new(&request, extent).unwrap();
let context = BakeContext::with_frame(&request, extent, &frame);
let (_, high_keys) = transfer_keys(&request);
for (vertex, vertex_reach) in reach.vertices.iter().enumerate() {
let (vertex_reach, missed) = (vertex_reach.unwrap(), reach.missed(vertex, 0.02, 0.01).unwrap());
// On the line where the two parts meet, a ray reaches either part's triangles
if vertex_reach.high_position.x.abs() < BOUNDARY {
continue;
+3 -18
View File
@@ -20,6 +20,9 @@ mod bent_normal_space;
#[path = "test/cage_shell.rs"]
mod cage_shell;
#[path = "test/fitted_cage.rs"]
mod fitted_cage;
#[path = "test/high_poly_reach.rs"]
mod high_poly_reach;
@@ -1056,24 +1059,6 @@ fn occlusion_falls_off_linearly_to_the_max_distance() {
assert!((ambient_occlusion - 0.5).abs() < 0.01, "{ambient_occlusion}");
}
#[test]
fn secondary_ray_defaults_preserve_per_map_distances() {
let parameters = BakeSettings::default();
let expected_rays = RaySettings {
rays: 64,
min_distance: 0.00001,
max_distance: 1.0,
relative_to_bounding_box: true,
spread: 180.0,
distribution: RayDistribution::Cosine,
};
assert_eq!(parameters.maps.ao.parameters.rays, expected_rays);
assert_eq!(parameters.maps.ao.parameters.attenuation, texturecraft_core::AmbientOcclusionAttenuation::Linear);
assert_eq!(parameters.maps.bent_normal.parameters.rays, expected_rays);
assert_eq!(parameters.maps.thickness.parameters.rays, RaySettings { max_distance: 0.1, ..expected_rays });
}
#[test]
fn bent_normals_and_thickness_have_their_own_rays() {
let m = floor_and_wall(false);
+162
View File
@@ -0,0 +1,162 @@
//! The frame an axis planar projection projects from: moving one on the model places it as that frame, so its images land where they did
use texturecraft_core::{Decal, Projection, Projector, Source};
use texturecraft_geom::glam::{EulerRot, Mat3, Vec3};
use crate::frame_placement::culling_folds;
use crate::pattern::{DEPTH_FADE_START, frame_uv_from_corner, mesh_frame, nonzero_stretch, projector_stretch};
/// Place an axis planar on a mesh within `bounds` while keeping its sampling and culling.
/// See [`culling_folds`] for when culling prevents placement.
pub fn placed_from_axis(proj: &Projection, bounds: (Vec3, Vec3)) -> Option<Projection> {
let Projection::Planar { scale, axis, offset, uv, projector, placed: None } = proj else { return None };
if !culling_folds(projector) {
return None;
}
let frame = axis_frame(*scale, *axis, Vec3::from(*offset), projector, bounds)?;
// The frame carries rotation and scale while the projected rectangle keeps axis coverage
let projector = Projector { rotation: [0.0; 3], scale: [1.0; 3], ignore_image_alpha: true, ..*projector };
// An axis planar turns its image round the top left, a frame round its centre
let uv = frame_uv_from_corner(uv);
Some(Projection::Planar { scale: *scale, axis: *axis, offset: *offset, uv, projector, placed: Some(frame) })
}
/// Whether placing an axis planar that reads `sources` would move a pattern: a procedural reads an axis planar's plane but a placed frame's uv, so such a planar keeps its axis
pub fn placing_moves_pattern<'a>(mut sources: impl Iterator<Item = &'a Source>) -> bool {
sources.any(|source| matches!(source, Source::Procedural { .. }))
}
/// The frame of an axis planar projection: its image's 0..1 square on the plane through the mesh, turned and sized by `projector`
pub fn axis_frame(scale: f32, axis: u8, offset: Vec3, projector: &Projector, bounds: (Vec3, Vec3)) -> Option<Decal> {
let (center, radius) = mesh_frame(bounds);
let [x, y, z] = projector.rotation.map(f32::to_radians);
let turn = Mat3::from_euler(EulerRot::ZYX, z, y, x);
let stretch = projector_stretch(projector);
let scale = nonzero_stretch(scale);
// Where the image's centre sits, then its across, up and out directions with the stretch along each
let origin = center + turn * (stretch * -offset / scale) * radius;
let (across, up, out) = match axis {
0 => (Vec3::Z, Vec3::Y, Vec3::NEG_X),
1 => (Vec3::X, Vec3::NEG_Z, Vec3::Y),
_ => (Vec3::X, Vec3::Y, Vec3::Z),
};
let side = |direction: Vec3| 2.0 * radius * direction.abs().dot(stretch) / scale;
// A negative stretch or scale turns that side over
let flip = |direction: Vec3| direction * side(direction).signum();
let (across, up) = (flip(across), flip(up));
let size = [side(across).abs(), side(up).abs()];
let out = turn * across.cross(up).normalize_or(out);
// Deep enough never to crop the mesh by depth: the fade starts at three quarters of it
let reach = (radius + (origin - center).length()) / DEPTH_FADE_START * DEPTH_SPARE;
let frame = Decal {
center: origin.to_array(),
normal: out.to_array(),
up: (turn * up).to_array(),
size,
rotation: 0.0,
offset: [0.0; 2],
depth: reach,
symmetry: None,
flip: [false; 2],
};
(origin.is_finite() && size.iter().all(|side| side.is_finite() && *side > 0.0) && reach.is_finite()).then_some(frame)
}
/// Extra reach past the farthest mesh point
const DEPTH_SPARE: f32 = 1.01;
#[cfg(test)]
mod tests {
use texturecraft_core::{Backface, ShapeCrop, UvTransform};
use texturecraft_geom::glam::Vec2;
use super::*;
use crate::pattern::{Coords, image_samples};
use crate::projector_cover::{framed_cover, projector_cover};
/// Points spread through the box `lo`..`hi` with varied normals
fn points(lo: Vec3, hi: Vec3) -> Vec<(Vec3, Vec3)> {
(0..64)
.map(|i| {
let spread = |salt: u32| ((i * 37 + salt * 11) % 64) as f32 / 63.0;
let position = lo + (hi - lo) * Vec3::new(spread(1), spread(2), spread(3));
let normal = Vec3::new(spread(4) - 0.4, spread(5) - 0.3, spread(6) - 0.2).normalize_or(Vec3::Z);
(position, normal)
})
.collect()
}
#[test]
fn a_placed_axis_planar_reads_images_where_it_did() {
let (lo, hi) = (Vec3::new(-1.0, -0.5, -2.0), Vec3::new(3.0, 1.5, 0.5));
let center = (lo + hi) * 0.5;
let radius = (hi - lo).length() * 0.5;
for axis in 0..3 {
for (rotation, stretch) in [([0.0; 3], [1.0; 3]), ([20.0, -35.0, 50.0], [1.5, 0.7, 2.0])] {
for crop in [ShapeCrop::ExtendsOutside, ShapeCrop::Cropped] {
let projector = Projector { rotation, scale: stretch, crop, ..Projector::default() };
let uv = UvTransform { tiling: [2.0, 3.0], rotation: 30.0, offset: [0.1, -0.2] };
let axis_planar = Projection::Planar { scale: 1.7, axis, offset: [0.3, -0.4, 0.2], uv, projector, placed: None };
let placed = placed_from_axis(&axis_planar, (lo, hi)).expect("an axis planar has a frame");
for (position, normal) in points(lo, hi) {
let coords = Coords { uv: Vec2::ZERO, pos: (position - center) / radius, nrm: normal };
let (before, _) = image_samples(&axis_planar, &coords)[0];
let (uv_after, cover) = framed_cover(&placed, position, normal, center).expect("a placed frame covers");
let (after, _) = image_samples(&placed, &Coords { uv: uv_after, ..coords })[0];
assert!(before.distance(after) < 1e-3, "axis {axis} {rotation:?}: {before} became {after}");
assert!((projector_cover(&axis_planar, &coords) - cover).abs() < 1e-3, "axis {axis} {crop:?}: cover changed at {position}");
}
}
}
}
}
#[test]
fn a_placed_axis_planar_keeps_what_backface_culling_hides() {
let (lo, hi) = (Vec3::new(-1.0, -0.5, -2.0), Vec3::new(3.0, 1.5, 0.5));
let center = (lo + hi) * 0.5;
let radius = (hi - lo).length() * 0.5;
let backface = Backface { on: true, angle: 60.0, hardness: 1.0 };
// An oblique normal exposes tilted and reversed culling under stretch
let halfway = (center, Vec3::new(1.0, 0.0, 1.0).normalize());
for stretch in [[4.0, 1.0, 1.0], [1.5, -1.5, 1.5], [1.7; 3]] {
let projector = Projector { scale: stretch, backface, ..Projector::default() };
let axis_planar = Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv: UvTransform::default(), projector, placed: None };
let Some(placed) = placed_from_axis(&axis_planar, (lo, hi)) else {
assert!(!culling_folds(&projector), "{stretch:?}: only a stretch culling cannot keep stays unplaced");
continue;
};
for (position, normal) in points(lo, hi).into_iter().chain([halfway]) {
let coords = Coords { uv: Vec2::ZERO, pos: (position - center) / radius, nrm: normal };
let (_, cover) = framed_cover(&placed, position, normal, center).expect("a placed frame covers");
assert!((projector_cover(&axis_planar, &coords) - cover).abs() < 1e-3, "{stretch:?}: culling changed at {normal}");
}
}
let even = Projector { scale: [1.7; 3], backface, ..Projector::default() };
let axis_planar = Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv: UvTransform::default(), projector: even, placed: None };
assert!(placed_from_axis(&axis_planar, (lo, hi)).is_some(), "an even stretch is still placed");
}
#[test]
fn only_axis_planars_are_placed() {
let bounds = (Vec3::NEG_ONE, Vec3::ONE);
assert!(placed_from_axis(&Projection::default(), bounds).is_none());
let frame = axis_frame(1.0, 2, Vec3::ZERO, &Projector::default(), bounds).expect("a frame");
assert!(placed_from_axis(&Projection::decal(frame), bounds).is_none());
assert!(axis_frame(f32::NAN, 2, Vec3::ZERO, &Projector::default(), bounds).is_none());
}
}
+96 -12
View File
@@ -7,13 +7,15 @@
//! identical to a full evaluation.
use std::collections::{BTreeSet, HashMap, VecDeque};
use std::sync::Arc;
use std::hash::{DefaultHasher, Hash, Hasher};
use std::sync::{Arc, Weak};
use texturecraft_core::project::MAX_DEPTH;
use texturecraft_core::{BakedMap, Channel, EffectKind, Layer, LayerId, LayerKind, Project, Source, TextureSet};
use texturecraft_core::{BakedMap, Channel, EffectKind, Filter, Layer, LayerId, LayerKind, Project, Source, TextureSet};
use texturecraft_geom::Mesh;
use texturecraft_texel::TileImage;
use crate::eval::{Inputs, PaintTarget};
use crate::eval::{Inputs, PaintTarget, lights_material};
use crate::held_fields::HeldFields;
use crate::image_identity::ImageIdentity;
use crate::store::{BakedMaps, ImageStore, PixelStore};
@@ -25,6 +27,8 @@ pub const BELOW_BUDGET: usize = 256 << 20;
/// See the module docs. One per texture set.
#[derive(Debug)]
pub struct BelowCache {
mesh: Weak<Mesh>,
borrowed_mesh_key: Option<u64>,
hot: Option<LayerId>,
key: Option<StackKey>,
/// Tiles with the stamp of their last use.
@@ -52,6 +56,8 @@ pub struct BelowCache {
impl Default for BelowCache {
fn default() -> Self {
BelowCache {
mesh: Weak::new(),
borrowed_mesh_key: None,
hot: None,
key: None,
tiles: HashMap::new(),
@@ -98,6 +104,8 @@ pub struct StackKey {
pixels: Vec<(LayerId, Option<Channel>, Shared)>,
baked: (u32, Vec<(BakedMap, usize)>),
images: Vec<(String, ImageIdentity)>,
/// The viewport environment, its rotation (bits) and its image when it is an imported one, where Baked Lighting Environment lights with them
environment: Option<(String, u32, Option<ImageIdentity>)>,
}
impl StackKey {
@@ -142,18 +150,23 @@ impl StackKey {
let mut referenced_images = BTreeSet::new();
if !images.is_empty() {
let mut record_image_reference = |source: &Source| {
referenced_images.extend(source.images().into_iter().filter_map(|name| images.get_key_value(name)).map(|(name, _)| name));
let mut record_image_name = |name: &str| {
if let Some((name, _)) = images.get_key_value(name) {
referenced_images.insert(name);
}
};
for layer in render_tree.iter().filter_map(|id| project.layers.get(id)) {
if let LayerKind::Fill(fill) = &layer.kind {
fill.sources.values().for_each(&mut record_image_reference);
fill.sources.values().flat_map(Source::images).for_each(&mut record_image_name);
}
for effect in layer.mask.iter().flat_map(|mask| &mask.effects).chain(&layer.content_effects) {
// A filter's image inputs, also one its mode leaves unread: that only empties the cache more often
effect.inputs.values().flat_map(Source::images).for_each(&mut record_image_name);
match &effect.kind {
EffectKind::Fill { source, .. } => record_image_reference(source),
EffectKind::Material(fill) => fill.sources.values().for_each(&mut record_image_reference),
EffectKind::Generator(generator) => generator.inputs.values().for_each(&mut record_image_reference),
EffectKind::Fill { source, .. } => source.images().into_iter().for_each(&mut record_image_name),
EffectKind::Material(fill) => fill.sources.values().flat_map(Source::images).for_each(&mut record_image_name),
EffectKind::Generator(generator) => generator.sources().flat_map(Source::images).for_each(&mut record_image_name),
EffectKind::ColorSelection(selection) => selection.id_map.iter().for_each(|name| record_image_name(name)),
_ => {}
}
}
@@ -163,6 +176,16 @@ impl StackKey {
let image_identities =
referenced_images.into_iter().filter_map(|name| images.get(name).map(|image| (name.clone(), ImageIdentity::new(image)))).collect();
let lit = render_tree
.iter()
.filter_map(|id| project.layers.get(id))
.flat_map(|layer| layer.content_effects.iter())
.any(|effect| matches!(effect.kind, EffectKind::Filter(Filter::EnvironmentLighting { .. })));
let environment = lit.then(|| {
let image = project.display.environment_resource().and_then(|name| images.get(name)).map(ImageIdentity::new);
(project.display.environment.clone(), project.display.env_rotation.to_bits(), image)
});
Some(StackKey {
set,
roots,
@@ -170,6 +193,7 @@ impl StackKey {
pixels: pixel_handles,
baked: (baked.resolution, baked.maps.iter().map(|(map, data)| (*map, Arc::as_ptr(data) as usize)).collect()),
images: image_identities,
environment,
})
}
}
@@ -179,12 +203,20 @@ impl StackKey {
/// changed (same set, roots, layers, baked maps and images; the same images by id, channel
/// and size). None when anything else differs: the caller recomposites everything.
pub fn changed_tiles(&self, other: &StackKey) -> Option<BTreeSet<(u32, u32)>> {
if self.set != other.set || self.roots != other.roots || self.layers != other.layers || self.baked != other.baked || self.images != other.images {
if self.set != other.set
|| self.roots != other.roots
|| self.layers != other.layers
|| self.baked != other.baked
|| self.images != other.images
|| self.environment != other.environment
{
return None;
}
if self.pixels.len() != other.pixels.len() {
return None;
}
let size = self.set.size();
let mut changed = BTreeSet::new();
for ((left_id, left_channel, left_image), (right_id, right_channel, right_image)) in self.pixels.iter().zip(&other.pixels) {
@@ -199,6 +231,7 @@ impl StackKey {
if !same_shape || (left_image.width(), left_image.height()) != size {
return None;
}
if left_image.same_tiles(right_image) {
continue;
}
@@ -260,6 +293,48 @@ fn render_view(l: &Layer) -> Layer {
}
impl BelowCache {
pub(crate) fn bind_mesh(&mut self, mesh: &Arc<Mesh>) {
if !std::ptr::eq(self.mesh.as_ptr(), mesh.as_ref()) {
self.clear();
self.borrowed_mesh_key = None;
self.mesh = Arc::downgrade(mesh);
}
}
pub(crate) fn bind_borrowed_mesh(&mut self, mesh: &Mesh) {
if std::ptr::eq(self.mesh.as_ptr(), mesh) {
return;
}
// A borrow alone cannot distinguish in-place edits or reuse of the same address
let mut key = DefaultHasher::new();
for attribute in [&mesh.positions, &mesh.normals] {
attribute.len().hash(&mut key);
for value in attribute {
value.to_array().map(f32::to_bits).hash(&mut key);
}
}
mesh.tangents.len().hash(&mut key);
for value in &mesh.tangents {
value.to_array().map(f32::to_bits).hash(&mut key);
}
mesh.uvs.len().hash(&mut key);
for value in &mesh.uvs {
value.to_array().map(f32::to_bits).hash(&mut key);
}
mesh.indices.hash(&mut key);
for part in &mesh.submeshes {
(&part.name, part.start, part.count, part.material).hash(&mut key);
}
let key = key.finish();
if self.borrowed_mesh_key != Some(key) {
self.clear();
self.mesh = Weak::new();
self.borrowed_mesh_key = Some(key);
}
}
/// Cache the stack around `hot` from now on (a different layer empties the cache).
pub fn set_hot(&mut self, hot: Option<LayerId>) {
if self.hot != hot {
@@ -363,8 +438,17 @@ impl BelowCache {
let project = inp.project;
let set = project.texture_set(inp.ts).ok()?;
// Anchor readers depend on the stack below them
if project.render_tree(&set.stack).iter().any(|id| project.layers.get(id).is_some_and(Layer::reads_anchor)) {
// Replaying cached colors would reuse the material below a lighting or validation effect
if project
.render_tree(&set.stack)
.iter()
.filter_map(|id| project.layers.get(id))
.any(|layer| layer.reads_stack() || layer.content_effects.iter().any(|effect| effect.visible && lights_material(&effect.kind)))
{
if self.key.is_some() {
self.clear();
}
return None;
}
+20 -5
View File
@@ -4,13 +4,16 @@ use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, Weak};
use rayon::prelude::*;
use texturecraft_core::{BakedMap, BlockScales, CurvatureDetail};
use texturecraft_core::{BakedMap, BlockScales};
use texturecraft_texel::dilate::{DilationMap, NONE};
use crate::curvature_size_level::{CurvatureSizeLevel, DEVIATION_SCALE};
use crate::eval::{BLUR_BOX_PASSES, Inputs, blur};
/// The curvature map padded past its UV islands and blurred at each size of [`CurvatureDetail::SIZES`] after the first.
/// The blur radius of each level in texels at 2K: the detail sizes of [`texturecraft_core::CurvatureDetail::SIZES`] after the first, then wider ones the wear generators' edges smoothness reaches
pub const LEVEL_RADII: [f32; 8] = [1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0, 128.0];
/// The curvature map padded past its UV islands and blurred at each radius of [`LEVEL_RADII`]
pub struct CurvatureSizes {
/// One per blurred size, built once a generator gives that size a weight above 0.
pub levels: Vec<Option<Arc<CurvatureSizeLevel>>>,
@@ -31,7 +34,11 @@ const CACHE_MAPS: usize = 16;
impl CurvatureSizes {
/// The sizes of the texture set `inp` composites, holding at least those `needed` marks (one flag per blurred size); None without a baked curvature map or a needed size.
pub fn of(inp: &Inputs, needed: &[bool]) -> Option<Arc<CurvatureSizes>> {
let curvature = inp.baked.maps.get(&BakedMap::Curvature)?;
CurvatureSizes::of_map(inp, inp.baked.maps.get(&BakedMap::Curvature)?, needed)
}
/// The sizes of `curvature`, a map in the baked curvature map's layout (the baked map or one derived from it)
pub fn of_map(inp: &Inputs, curvature: &Arc<Vec<f32>>, needed: &[bool]) -> Option<Arc<CurvatureSizes>> {
let (width, height) = (inp.baked.resolution, inp.baked.height(BakedMap::Curvature));
if !needed.contains(&true) || width == 0 || height == 0 {
return None;
@@ -70,14 +77,14 @@ impl CurvatureSizes {
padding.src.par_iter().map(|&source| if source == NONE { 0.0 } else { curvature.get(source as usize).copied().unwrap_or(0.5) - 0.5 }).collect();
let (block_width, block_height) = (block.0.max(1).min(width), block.1.max(1).min(height));
let levels = CurvatureDetail::SIZES
let levels = LEVEL_RADII
.iter()
.skip(1)
.enumerate()
.map(|(level, size)| {
if let Some(existing) = built.and_then(|sizes| sizes.levels.get(level)).and_then(Option::clone) {
return Some(existing);
}
if !needed.get(level).copied().unwrap_or(false) {
return None;
}
@@ -85,6 +92,7 @@ impl CurvatureSizes {
// Sizes are texels at 2K; a blur this wide holds nothing finer than half its radius, so it is stored that much coarser
let radius = (size * block_width as f32 / 2048.0).round().max(1.0) as u32;
let mut step = (radius / 2).max(1).next_power_of_two();
// A coarse cell must not average curvature from different UV tiles
while !block_width.is_multiple_of(step) || !block_height.is_multiple_of(step) {
step /= 2;
@@ -247,6 +255,8 @@ fn coarsen(data: &[f32], (width, height): (u32, u32), step: u32, block: (u32, u3
#[cfg(test)]
mod tests {
use texturecraft_core::CurvatureDetail;
use super::*;
#[test]
@@ -473,4 +483,9 @@ mod tests {
}
}
}
#[test]
fn the_first_levels_are_the_detail_sizes() {
assert_eq!(LEVEL_RADII[..CurvatureDetail::BLURRED_SIZES], CurvatureDetail::SIZES[1..]);
}
}
+64
View File
@@ -0,0 +1,64 @@
//! The lower envelope of parabolas that turns a line of squared distances into each place's squared distance to the nearest feature
/// The lower envelope of the parabolas over a line of squared distances, which gives each place's squared distance to the nearest feature along it and the line before
#[derive(Default)]
pub(crate) struct DistanceEnvelope {
/// The parabolas still lowest somewhere: their vertex and where their stretch begins
parabolas: Vec<(usize, f64)>,
/// The line as it was
heights: Vec<f32>,
}
impl DistanceEnvelope {
/// Replace `line` with each place's squared distance to the nearest feature
pub(crate) fn lower(&mut self, line: &mut [f32]) {
self.heights.clear();
self.heights.extend_from_slice(line);
self.parabolas.clear();
let heights = &self.heights;
// In f64, where squared places and their sums stay exact past 4096 texels and a wide line cannot overflow a 32-bit usize
let lifted = |at: usize| f64::from(heights.get(at).copied().unwrap_or(f32::MAX)) + at as f64 * at as f64;
for at in 0..heights.len() {
let mut start = f64::NEG_INFINITY;
while let Some(&(vertex, from)) = self.parabolas.last() {
let crossing = (lifted(at) - lifted(vertex)) / (2.0 * (at - vertex) as f64);
if crossing <= from {
self.parabolas.pop();
} else {
start = crossing;
break;
}
}
self.parabolas.push((at, start));
}
let mut current = 0;
for (at, out) in line.iter_mut().enumerate() {
while self.parabolas.get(current + 1).is_some_and(|(_, from)| *from < at as f64) {
current += 1;
}
if let Some(&(vertex, _)) = self.parabolas.get(current) {
*out = (at as f32 - vertex as f32).powi(2) + heights.get(vertex).copied().unwrap_or(f32::MAX);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Past 4096 texels a squared place is no longer exact in f32: two close features at the end of a wide line still each read 0
#[test]
fn close_features_far_along_a_wide_line_stay_exact() {
const FAR: f32 = 4.0e8;
let mut line = vec![FAR; 10_000];
line[9_950] = 1.0;
line[9_951] = 0.0;
DistanceEnvelope::default().lower(&mut line);
assert_eq!(line[9_949..9_954], [2.0, 1.0, 0.0, 1.0, 4.0]);
}
}
+316
View File
@@ -0,0 +1,316 @@
//! The Dripping Rust generator: rust grown from the occlusion, broken up by grunge, then run down the mesh in drips; built once per layout and settings
use std::sync::Arc;
use rayon::prelude::*;
use texturecraft_core::{BakedMap, DrippingRustParameters, GeneratorKind, WearParameters};
use texturecraft_geom::{NO_TRI, TrianglePartition};
use crate::eval::{Inputs, texel_coords};
use crate::field_cache::FieldCache;
use crate::histogram_scan::histogram_scan;
use crate::wear;
use crate::working_field::{REFERENCE_TILE_TEXELS, blur_blocks, box_radius};
/// The rust before any grunge: `RUST_FLOOR + RUST_GAIN * max(RUST_OCCLUSION − occlusion, 0)^RUST_POWER` (fitted to the reference)
const RUST_FLOOR: f32 = 0.315;
const RUST_GAIN: f32 = 3.19;
const RUST_OCCLUSION: f32 = 0.849;
const RUST_POWER: f32 = 2.38;
/// How much grunge breaks the rust up: the spread of the reference's noise (measured); the pattern itself is inferred
const GRUNGE_SPREAD: f32 = 0.19;
/// Blur sizes at Spreading Smoothness 1 and Drips Smoothness 1, as gaussian sigmas in texels of a 2K UV tile (fitted)
const SPREADING_SIGMA_2K: f32 = 47.0;
const DRIPS_SIGMA_2K: f32 = 11.5;
/// How far a drip runs at Drips Intensity 1, in texels of a 2K UV tile, and how it fades along its length: `1 − DRIP_FADE · along^DRIP_FADE_POWER` (fitted)
const DRIP_LENGTH_2K: f32 = 90.86;
const DRIP_FADE: f32 = 0.898;
const DRIP_FADE_POWER: f32 = 0.671;
/// Coverage below which a blurred texel has nothing to average
const MIN_COVERAGE: f32 = 1e-3;
static CACHE: FieldCache = FieldCache::new();
/// The rust before its spreading and contrast at every working texel of `inp` (0 outside the islands)
pub(crate) fn rust_field(inp: &Inputs, geometry: u64, rust: &DrippingRustParameters, seed: u32) -> Arc<Vec<f32>> {
let settings = vec![
rust.spreading_smoothness.to_bits(),
rust.drips_intensity.to_bits(),
rust.drips_smoothness.to_bits(),
rust.drips_samples,
u32::from(rust.axis),
seed,
];
CACHE.get_or_build(inp, geometry, &[BakedMap::AmbientOcclusion], settings, |block| build(inp, rust, seed, block))
}
/// The value at a working texel: the rust spread and contrasted
pub(crate) fn rust_value(rust: &DrippingRustParameters, field: f32) -> f32 {
histogram_scan(field, rust.spreading, rust.contrast)
}
fn build(inp: &Inputs, rust: &DrippingRustParameters, seed: u32, block: (u32, u32)) -> Vec<f32> {
let gbuf = inp.gbuf;
let (width, height) = (gbuf.width, gbuf.height);
let cover: Vec<f32> = (0..width * height).map(|texel| if gbuf.covered(texel as usize) { 1.0 } else { 0.0 }).collect();
let tile_texels = |x: u32, y: u32| block.0 as f32 * inp.block_scales.at(x, y);
// The rust from the occlusion, broken up by the Dirt generator's grunge
let grunge = WearParameters::defaults(GeneratorKind::Dirt);
let rust_at = |texel: u32| {
let (x, y) = (texel % width, texel / width);
let occlusion = inp.baked.sample_working(BakedMap::AmbientOcclusion, x, y, (width, height), &inp.block_scales).map_or(1.0, |value| value[0]);
let base = RUST_FLOOR + RUST_GAIN * (RUST_OCCLUSION - occlusion).max(0.0).powf(RUST_POWER);
let noise = grunge.map_or(0.0, |grunge| wear::grunge(GeneratorKind::Dirt, &grunge, seed, &texel_coords(inp, x, y)));
base + GRUNGE_SPREAD * noise
};
let mut field: Vec<f32> = (0..width * height).into_par_iter().map(|texel| if gbuf.covered(texel as usize) { rust_at(texel) } else { 0.0 }).collect();
let radius_at = |sigma_2k: f32, smoothness: f32| move |x: u32, y: u32| box_radius(smoothness * sigma_2k * tile_texels(x, y) / REFERENCE_TILE_TEXELS);
blur_over_cover(&mut field, &cover, (width, height), block, radius_at(SPREADING_SIGMA_2K, rust.spreading_smoothness));
let mut field = drips(inp, rust, field, (width, height), &tile_texels);
blur_over_cover(&mut field, &cover, (width, height), block, radius_at(DRIPS_SIGMA_2K, rust.drips_smoothness));
field.iter_mut().zip(&cover).for_each(|(value, covered)| *value = if *covered > 0.0 { value.clamp(0.0, 1.0) } else { 0.0 });
field
}
/// `values` blurred within each UV tile block by the radius `radius_at` gives, weighted by `cover` so the empty space around the islands doesn't bleed in
fn blur_over_cover(values: &mut [f32], cover: &[f32], size: (u32, u32), block: (u32, u32), radius_at: impl Fn(u32, u32) -> usize + Copy) {
let has_blur = (0..size.1).step_by(block.1 as usize).any(|top| (0..size.0).step_by(block.0 as usize).any(|left| radius_at(left, top) > 0));
if !has_blur {
return;
}
let mut sums: Vec<f32> = values.iter().zip(cover).map(|(value, covered)| value * covered).collect();
let mut weights = cover.to_vec();
blur_blocks(&mut sums, size, block, radius_at);
blur_blocks(&mut weights, size, block, radius_at);
values.par_iter_mut().zip(sums.par_iter().zip(weights.par_iter())).zip(cover.par_iter()).for_each(|((value, (sum, weight)), covered)| {
if *covered > 0.0 && *weight > MIN_COVERAGE {
*value = sum / weight;
}
});
}
/// Each texel takes the most rust found uphill along the drip axis, fading with how far up it lies
fn drips(
inp: &Inputs,
rust: &DrippingRustParameters,
field: Vec<f32>,
(width, height): (u32, u32),
tile_texels: &(impl Fn(u32, u32) -> f32 + Sync),
) -> Vec<f32> {
let gbuf = inp.gbuf;
if rust.drips_samples == 0 || rust.drips_intensity <= 0.0 {
return field;
}
let axis = usize::from(rust.axis.min(2));
let (low, high) = inp.bounds;
let low = low.to_array()[axis];
let extent = (high.to_array()[axis] - low).max(f32::EPSILON);
let material = inp.project.texture_set(inp.ts).map_or(0, |set| set.material);
let islands = TrianglePartition::uv_islands(inp.mesh, material);
let surface: Vec<(u32, f32)> = (0..width * height)
.into_par_iter()
.map(|texel| {
let triangle = gbuf.tri.get(texel as usize).copied().unwrap_or(NO_TRI);
let Some(island) = islands.index_of(triangle) else { return (NO_TRI, 0.0) };
gbuf.surface(inp.mesh, texel as usize).map_or((NO_TRI, 0.0), |surface| (island as u32, (surface.pos.to_array()[axis] - low) / extent))
})
.collect();
drop(islands);
let index_at = |x: i64, y: i64| -> Option<usize> {
if x < 0 || y < 0 || x >= i64::from(width) || y >= i64::from(height) {
return None;
}
Some((y * i64::from(width) + x) as usize)
};
let samples = rust.drips_samples;
let taps: Vec<_> = (1..=samples)
.map(|step| {
let fraction = step as f32 / samples as f32;
(fraction, 1.0 - DRIP_FADE * fraction.powf(DRIP_FADE_POWER))
})
.collect();
(0..width * height)
.into_par_iter()
.map(|texel| {
let (column, row) = (texel % width, texel / width);
let (x, y) = (i64::from(column), i64::from(row));
let here = field.get(texel as usize).copied().unwrap_or(0.0);
let Some(&(island, axis_here)) = surface.get(texel as usize).filter(|(island, _)| *island != NO_TRI) else { return here };
let axis_at = |x, y| {
let (other_island, value) = *surface.get(index_at(x, y)?)?;
(other_island == island).then_some(value)
};
let (dx, dy) = (slope(axis_at(x - 1, y), axis_here, axis_at(x + 1, y)), slope(axis_at(x, y - 1), axis_here, axis_at(x, y + 1)));
let length = (dx * dx + dy * dy).sqrt();
if !length.is_finite() || length <= f32::EPSILON {
return here;
}
let reach = rust.drips_intensity * DRIP_LENGTH_2K * tile_texels(column, row) / REFERENCE_TILE_TEXELS;
let mut most = here;
let mut current = (x, y);
'ray: for &(fraction, fade) in &taps {
let distance = reach * fraction;
let sample = ((x as f32 + distance * dx / length).round() as i64, (y as f32 + distance * dy / length).round() as i64);
// A sparse tap must still have continuous coverage along the ray
while current != sample {
current = next_ray_texel((x, y), current, sample, (dx, dy));
if axis_at(current.0, current.1).is_none() {
break 'ray;
}
}
// A tap beyond a ridge contributes only if it is higher than the receiving texel
if axis_at(sample.0, sample.1).is_some_and(|value| value >= axis_here)
&& let Some(value) = index_at(sample.0, sample.1).and_then(|index| field.get(index))
{
most = most.max(*value * fade);
}
}
most
})
.collect()
}
/// Finite difference within one UV island, one-sided at its edge
fn slope(before: Option<f32>, here: f32, after: Option<f32>) -> f32 {
match (before, after) {
(Some(before), Some(after)) => (after - before) * 0.5,
(None, Some(after)) => after - here,
(Some(before), None) => here - before,
(None, None) => 0.0,
}
}
/// Advance across the next texel boundary on a ray from a texel centre toward its next tap
fn next_ray_texel(origin: (i64, i64), (x, y): (i64, i64), (target_x, target_y): (i64, i64), (dx, dy): (f32, f32)) -> (i64, i64) {
let step_x = (target_x - x).signum();
let step_y = (target_y - y).signum();
if step_x == 0 || step_y == 0 {
return (x + step_x, y + step_y);
}
// Compare crossing distances without dividing by either component
let crossing_x = ((x - origin.0).abs() as f32 + 0.5) * dy.abs();
let crossing_y = ((y - origin.1).abs() as f32 + 0.5) * dx.abs();
(x + step_x * i64::from(crossing_x <= crossing_y), y + step_y * i64::from(crossing_y <= crossing_x))
}
#[cfg(test)]
mod tests {
use texturecraft_core::{Project, TextureSet};
use texturecraft_geom::{UvGBuffer, primitives};
use super::*;
use crate::{BakedMaps, PixelStore};
const RES: u32 = 256;
#[test]
fn a_drip_takes_no_rust_from_past_a_ridge_lower_on_the_axis() {
// A strip rising gently to a ridge at its middle, then falling steeply
let mut mesh = primitives::plane(2.0, 64);
for position in &mut mesh.positions {
position.y = if position.z <= 0.0 { 1.0 + position.z } else { 1.0 - 8.0 * position.z };
}
let gbuf = UvGBuffer::new(&mesh, 0, RES, RES);
let mut project = Project::new("t", "strip");
project.texture_sets.push(TextureSet::new("A", 0, RES));
let (pixels, baked, images) = (PixelStore::default(), BakedMaps::default(), Default::default());
let inputs = Inputs {
project: &project,
ts: 0,
mesh: &mesh,
gbuf: &gbuf,
pixels: &pixels,
baked: &baked,
block_scales: project.texture_sets[0].block_scales(),
preview: None,
images: &images,
bounds: mesh.bounds(),
};
// Rust only on the steep side, all lower than the gentle side's texel just below the ridge
let rusted = |surface: &texturecraft_geom::Surface| surface.pos.z > 0.01;
let field: Vec<f32> = (0..RES * RES).map(|texel| gbuf.surface(&mesh, texel as usize).filter(rusted).map_or(0.0, |_| 1.0)).collect();
let rust = DrippingRustParameters { drips_intensity: 1.0, drips_samples: DrippingRustParameters::MAX_SAMPLES, axis: 1, ..Default::default() };
let dripped = drips(&inputs, &rust, field, (RES, RES), &|_, _| RES as f32);
let below_ridge = (0..RES * RES)
.find(|texel| {
gbuf.surface(&mesh, *texel as usize).is_some_and(|surface| (surface.pos.z + 0.04).abs() < 1.0 / RES as f32 && surface.pos.x.abs() < 0.1)
})
.expect("a texel just below the ridge");
assert_eq!(dripped[below_ridge as usize], 0.0);
}
#[test]
fn a_runoff_streak_requires_a_continuous_uv_surface() {
const GAP_HALF_WIDTH: f32 = 1.0 / 64.0;
let mut mesh = primitives::plane(2.0, 128);
let connected_indices = mesh.indices.clone();
let (triangles, _) = connected_indices.as_chunks::<3>();
let separated_indices: Vec<_> = triangles
.iter()
.filter(|triangle| {
triangle.iter().all(|&corner| mesh.positions[corner as usize].z <= -GAP_HALF_WIDTH)
|| triangle.iter().all(|&corner| mesh.positions[corner as usize].z >= GAP_HALF_WIDTH)
})
.flatten()
.copied()
.collect();
for position in &mut mesh.positions {
position.y = position.z;
}
let mut project = Project::new("Runoff", "Plane");
project.texture_sets.push(TextureSet::new("UV islands", 0, RES));
let (pixels, baked, images) = (PixelStore::default(), BakedMaps::default(), Default::default());
let index = |row| (row * RES + RES / 2) as usize;
for (connected, indices) in [(true, connected_indices), (false, separated_indices)] {
mesh.indices = indices;
mesh.submeshes[0].count = mesh.indices.len() as u32;
let gbuf = UvGBuffer::new(&mesh, 0, RES, RES);
let inputs = Inputs {
project: &project,
ts: 0,
mesh: &mesh,
gbuf: &gbuf,
pixels: &pixels,
baked: &baked,
block_scales: project.texture_sets[0].block_scales(),
preview: None,
images: &images,
bounds: mesh.bounds(),
};
let field: Vec<f32> =
(0..RES * RES).map(|texel| f32::from(gbuf.surface(&mesh, texel as usize).is_some_and(|surface| surface.pos.z > GAP_HALF_WIDTH))).collect();
assert!(gbuf.covered(index(124)));
assert_eq!(gbuf.covered(index(128)), connected);
assert_eq!(field[index(124)], 0.0);
assert_eq!(field[index(131)], 1.0);
for samples in [1, DrippingRustParameters::MAX_SAMPLES] {
let rust = DrippingRustParameters { drips_intensity: 1.0, drips_samples: samples, axis: 1, ..Default::default() };
let dripped = drips(&inputs, &rust, field.clone(), (RES, RES), &|_, _| RES as f32);
assert_eq!(dripped[index(124)] > 0.0, connected, "a streak with {samples} taps requires a continuous covered surface");
}
}
}
}
+95
View File
@@ -0,0 +1,95 @@
//! The distribution of the values entering an effect, as the levels editor draws it
use texturecraft_core::lum;
/// Bucket counts over 0..1 of the values entering an effect, pooled and per part of a colour
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct EffectHistogram {
/// Every value, a colour's three components pooled
pub all: Vec<u32>,
/// Red, green and blue on their own; empty for a one-value channel or a mask
pub components: Vec<Vec<u32>>,
/// Each colour's luminance; a one-value channel's or a mask's values (the same as `all`)
pub luminance: Vec<u32>,
}
impl EffectHistogram {
/// `bins` empty buckets (at least one), with per-component buckets when it counts colours
pub fn new(bins: usize, color: bool) -> EffectHistogram {
let bins = bins.max(1);
EffectHistogram { all: vec![0; bins], components: if color { vec![vec![0; bins]; 3] } else { Vec::new() }, luminance: vec![0; bins] }
}
/// Counts one value of a one-value channel or a mask
pub fn add_value(&mut self, value: f32) {
bump(&mut self.all, value);
bump(&mut self.luminance, value);
}
/// Counts one colour: each component pooled and on its own, and its luminance
pub fn add_color(&mut self, color: [f32; 3]) {
for (index, component) in color.into_iter().enumerate() {
bump(&mut self.all, component);
if let Some(counts) = self.components.get_mut(index) {
bump(counts, component);
}
}
bump(&mut self.luminance, lum(color));
}
/// Both histograms' counts together (they have the same buckets)
pub fn merged(mut self, other: &EffectHistogram) -> EffectHistogram {
add_counts(&mut self.all, &other.all);
for (counts, more) in self.components.iter_mut().zip(&other.components) {
add_counts(counts, more);
}
add_counts(&mut self.luminance, &other.luminance);
self
}
}
/// One more count in the bucket of `value` (clamped to 0..1)
fn bump(counts: &mut [u32], value: f32) {
let bins = counts.len();
let index = ((value.clamp(0.0, 1.0) * bins as f32) as usize).min(bins.saturating_sub(1));
if let Some(count) = counts.get_mut(index) {
*count = count.saturating_add(1);
}
}
fn add_counts(counts: &mut [u32], more: &[u32]) {
for (count, extra) in counts.iter_mut().zip(more) {
*count = count.saturating_add(*extra);
}
}
#[cfg(test)]
mod tests {
use super::EffectHistogram;
#[test]
fn a_colour_counts_each_component_pooled_and_alone_and_its_luminance() {
let mut histogram = EffectHistogram::new(4, true);
histogram.add_color([1.0, 0.0, 0.3]);
let merged = histogram.clone().merged(&histogram);
assert_eq!(histogram.all, vec![1, 1, 0, 1]);
assert_eq!(histogram.components, vec![vec![0, 0, 0, 1], vec![1, 0, 0, 0], vec![0, 1, 0, 0]]);
assert_eq!(histogram.luminance, vec![0, 1, 0, 0], "luminance 0.33 lands in the second bucket");
assert_eq!(merged.all, vec![2, 2, 0, 2]);
assert_eq!(merged.components.first(), Some(&vec![0, 0, 0, 2]));
}
#[test]
fn a_value_has_no_components() {
let mut histogram = EffectHistogram::new(2, false);
histogram.add_value(f32::NAN);
histogram.add_value(0.9);
assert_eq!(histogram.all, vec![1, 1]);
assert_eq!(histogram.luminance, histogram.all);
assert!(histogram.components.is_empty());
}
}
+217
View File
@@ -0,0 +1,217 @@
//! The viewport environment's diffuse light as spherical harmonics, worked out once per environment, and Baked Lighting Environment's shading with it
use std::sync::{Arc, Mutex, Weak};
use texturecraft_core::project::DisplaySettings;
use texturecraft_core::{Channel, DIELECTRIC_REFLECTANCE, finite_unit, mix3};
use texturecraft_geom::glam::Vec3;
use crate::environment_sky::{VIEWPORT_WIDTH, dir_of, environment_linear, radiance, sh_basis, sh9_averaged};
use crate::store::{ImageRes, ImageStore};
/// The diffuse light of the viewport environment and the turn the viewport gives it
#[derive(Clone, Copy)]
pub struct EnvironmentSh {
coefficients: [[f32; 3]; 9],
/// The viewport's environment rotation (radians)
rotation: f32,
}
/// The last coefficients, keyed by a built-in name or the identity of an imported image
type CacheEntry = (String, Option<Weak<ImageRes>>, [[f32; 3]; 9]);
static CACHE: Mutex<Option<CacheEntry>> = Mutex::new(None);
impl EnvironmentSh {
/// The diffuse light of the environment `display` shows (an imported image from `images`), worked out once per environment
pub fn of(display: &DisplaySettings, images: &ImageStore) -> EnvironmentSh {
let image = display.environment_resource().and_then(|name| images.get(name));
let same = |entry: &CacheEntry| match (&entry.1, &image) {
(Some(identity), Some(image)) => std::ptr::eq(identity.as_ptr(), Arc::as_ptr(image)),
(None, None) => entry.0 == display.environment,
_ => false,
};
let rotation = display.env_rotation.to_radians();
let cached = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).as_ref().filter(|entry| same(entry)).map(|entry| entry.2);
if let Some(coefficients) = cached {
return EnvironmentSh { coefficients, rotation };
}
// Average outside the lock so a Rayon worker can take another tile that needs the cache
let coefficients = match image {
Some(image) => image_sh(image),
None => built_in_sh(&display.environment),
};
*CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = Some((display.environment.clone(), image.map(Arc::downgrade), coefficients));
EnvironmentSh { coefficients, rotation }
}
/// The diffuse light reaching a surface facing world direction `normal` with the environment turned `horizontal` and tilted `vertical` (radians) past the viewport's turn
pub fn irradiance(&self, normal: Vec3, horizontal: f32, vertical: f32) -> Vec3 {
let (sin_tilt, cos_tilt) = vertical.sin_cos();
let tilted = Vec3::new(normal.x, cos_tilt * normal.y - sin_tilt * normal.z, sin_tilt * normal.y + cos_tilt * normal.z);
// Turned as the viewport turns its environment
let (sin_turn, cos_turn) = (self.rotation + horizontal).sin_cos();
let direction = Vec3::new(cos_turn * tilted.x - sin_turn * tilted.z, tilted.y, sin_turn * tilted.x + cos_turn * tilted.z);
let light = sh_basis(direction).iter().zip(&self.coefficients).fold(Vec3::ZERO, |sum, (basis, coefficient)| sum + Vec3::from(*coefficient) * *basis);
light.max(Vec3::ZERO)
}
/// Baked Lighting Environment's lit base color: linear `albedo`, its metal read from `channels` (straight values by [`Channel::index`]), in `light` (the environment's diffuse light at the surface, exposure applied), darkened by ambient occlusion `ao` by `[diffuse, specular]` occlusion. The viewer looks straight at the surface, so what it reflects is the light around the normal
pub fn shade(albedo: [f32; 3], light: Vec3, ao: f32, [diffuse_occlusion, specular_occlusion]: [f32; 2], channels: &[[f32; 3]]) -> [f32; 3] {
let ao = if ao.is_finite() { ao.clamp(0.0, 1.0) } else { 1.0 };
let metal = finite_unit(channels.get(Channel::Metallic.index()).map_or(0.0, |m| m[0]));
let f0 = mix3([DIELECTRIC_REFLECTANCE; 3], albedo, metal);
let diffuse = 1.0 + (ao - 1.0) * finite_unit(diffuse_occlusion);
let specular = 1.0 + (ao - 1.0) * finite_unit(specular_occlusion);
let incoming = light.to_array();
std::array::from_fn(|k| finite_unit(albedo[k] * (1.0 - metal) * incoming[k] * diffuse + f0[k] * incoming[k] * specular))
}
}
/// The coefficients of built-in environment `name` as the viewport works them out: drawn at its width, then averaged
fn built_in_sh(name: &str) -> [[f32; 3]; 9] {
let (width, height) = (VIEWPORT_WIDTH, VIEWPORT_WIDTH / 2);
sh9_averaged(width, height, |x, y| radiance(name, dir_of((x as f32 + 0.5) / width as f32, (y as f32 + 0.5) / height as f32)))
}
/// The coefficients of an imported equirect image, every texel averaged in as the viewport does
fn image_sh(image: &ImageRes) -> [[f32; 3]; 9] {
let linear = |v: f32| environment_linear(v, image.srgb);
sh9_averaged(image.width, image.height, |x, y| {
let texel = image.rgba.get((y as usize) * image.width as usize + x as usize).copied().unwrap_or([0.0; 4]);
Vec3::new(linear(texel[0]), linear(texel[1]), linear(texel[2]))
})
}
#[cfg(test)]
mod tests {
use super::*;
/// A uniform environment lights every direction alike, whatever the turn; brighter skies light more
#[test]
fn a_uniform_image_lights_every_way_alike() {
for (width, height) in [(1, 1), (32, 16)] {
let image = ImageRes::new(width, height, vec![[0.5, 0.5, 0.5, 1.0]; (width * height) as usize], false);
let sh = EnvironmentSh { coefficients: image_sh(&image), rotation: 1.0 };
for normal in [Vec3::Y, Vec3::X, Vec3::NEG_Y, Vec3::new(0.6, 0.0, 0.8)] {
let light = sh.irradiance(normal, 0.3, 0.7);
assert!((light - Vec3::splat(0.5)).abs().max_element() < 0.02, "{width}x{height} {normal}: {light}");
}
}
}
/// The studio's key light is up and to one side: a surface facing up gets more light than one facing down, and turning the environment moves the light around
#[test]
fn a_built_in_lights_by_where_the_surface_faces_and_turns() {
let display = DisplaySettings { environment: "Studio Soft".into(), ..DisplaySettings::default() };
let sh = EnvironmentSh::of(&display, &ImageStore::default());
assert!(sh.irradiance(Vec3::Y, 0.0, 0.0).element_sum() > 2.0 * sh.irradiance(Vec3::NEG_Y, 0.0, 0.0).element_sum());
let side = Vec3::new(0.7, 0.0, 0.7).normalize();
let (here, turned) = (sh.irradiance(side, 0.0, 0.0), sh.irradiance(side, std::f32::consts::PI, 0.0));
assert!((here - turned).abs().max_element() > 0.05, "{here} vs {turned}");
let night = EnvironmentSh::of(&DisplaySettings { environment: "Night".into(), ..DisplaySettings::default() }, &ImageStore::default());
assert!(night.irradiance(Vec3::Y, 0.0, 0.0).element_sum() < sh.irradiance(Vec3::Y, 0.0, 0.0).element_sum(), "the cache follows the environment");
}
#[test]
fn replacing_an_imported_environment_releases_its_image() {
let display = DisplaySettings { environment: "resource:lighting".into(), ..DisplaySettings::default() };
for color in [[1.0, 0.0, 0.0, 1.0], [0.0, 1.0, 0.0, 1.0]] {
let image = Arc::new(ImageRes::new(32, 16, vec![color; 32 * 16], false));
let image_identity = Arc::downgrade(&image);
let images = ImageStore::from([("lighting".into(), image)]);
let lighting = EnvironmentSh::of(&display, &images);
drop(images);
let irradiance = lighting.irradiance(Vec3::Y, 0.0, 0.0);
assert!(irradiance.distance(Vec3::new(color[0], color[1], color[2])) < 0.02);
assert!(image_identity.upgrade().is_none(), "lighting should release the decoded image with its store");
}
}
/// Tiles on the thread pool that ask for a new light finish: the light is worked out with the cache unlocked, so a worker that steals another tile while it waits for its share of the averaging never waits for its own lock
#[test]
fn tiles_asking_for_a_new_light_on_the_thread_pool_finish() {
use rayon::prelude::*;
const WORKERS: usize = 8;
const TILES: usize = 1024;
// One tile in so many asks for the light; the rest finish at once, so their workers are free to steal the averaging's work
const LIT_EVERY: usize = 128;
const ROUNDS: usize = 20;
const PATIENCE: std::time::Duration = std::time::Duration::from_secs(60);
let (done, finished) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let Ok(pool) = rayon::ThreadPoolBuilder::new().num_threads(WORKERS).build() else { return };
pool.install(|| {
for round in 0..ROUNDS {
// Each round shows another environment, so its first tile misses the cache
let environment = if round % 2 == 0 { "Sunset" } else { "Night" };
let display = DisplaySettings { environment: environment.into(), ..DisplaySettings::default() };
(0..TILES).into_par_iter().filter(|tile| tile % LIT_EVERY == 0).for_each(|_| {
EnvironmentSh::of(&display, &ImageStore::default());
});
}
});
let _ = done.send(());
});
assert!(finished.recv_timeout(PATIENCE).is_ok(), "the tiles deadlocked on the cache");
}
/// Diffuse occlusion darkens non-metals by the ambient occlusion; metals take their light from the reflections, which only specular occlusion darkens
#[test]
fn occlusion_darkens_the_diffuse_and_the_reflections_apart() {
let mut channels: Vec<[f32; 3]> = Channel::ALL.iter().map(|c| c.default_value()).collect();
let light = Vec3::splat(1.0);
let dielectric = |occlusion| EnvironmentSh::shade([0.5; 3], light, 0.2, occlusion, &channels)[0];
assert!(dielectric([1.0, 0.0]) < dielectric([0.0, 0.0]) * 0.5);
channels[Channel::Metallic.index()] = [1.0; 3];
let metal = |occlusion| EnvironmentSh::shade([0.5; 3], light, 0.2, occlusion, &channels)[0];
assert_eq!(metal([1.0, 0.0]), metal([0.0, 0.0]));
assert!(metal([0.0, 1.0]) < metal([0.0, 0.0]) * 0.5);
}
/// The coefficients of `radiance` read at every place of a fine grid, the integral the averaged ones must match
fn fine_sh(width: u32, radiance: impl Fn(Vec3) -> Vec3) -> [[f32; 3]; 9] {
let height = width / 2;
crate::environment_sky::sh9(width, height, |x, y| radiance(dir_of((x as f32 + 0.5) / width as f32, (y as f32 + 0.5) / height as f32)))
}
/// Sunset's sun is smaller than a texel of a coarse grid: averaging the viewport's drawing keeps its light, as the viewport does
#[test]
fn a_small_sun_lights_as_the_viewport_shows_it() {
let display = DisplaySettings { environment: "Sunset".into(), ..DisplaySettings::default() };
let baked = EnvironmentSh::of(&display, &ImageStore::default()).coefficients;
let fine = fine_sh(1024, |direction| radiance("Sunset", direction));
for (baked, fine) in baked.iter().zip(&fine) {
for (baked, fine) in baked.iter().zip(fine) {
assert!((baked - fine).abs() < 0.02, "{baked} vs {fine}");
}
}
}
/// An imported image's small bright patch counts though it falls between the texels a coarse read would take
#[test]
fn a_small_bright_patch_of_an_image_counts() {
const BRIGHT: f32 = 500.0;
let (width, height) = (1024u32, 512u32);
let patch = |x: u32, y: u32| (97..101).contains(&x) && (193..197).contains(&y);
let rgba = (0..width * height).map(|i| if patch(i % width, i / width) { [BRIGHT, BRIGHT, BRIGHT, 1.0] } else { [0.0, 0.0, 0.0, 1.0] }).collect();
let image = ImageRes::new(width, height, rgba, false);
let averaged = image_sh(&image)[0][0];
let exact = crate::environment_sky::sh9(width, height, |x, y| if patch(x, y) { Vec3::splat(BRIGHT) } else { Vec3::ZERO })[0][0];
assert!(exact > 0.01 && (averaged - exact).abs() < exact * 0.05, "{averaged} vs {exact}");
}
}
+174
View File
@@ -0,0 +1,174 @@
//! The built-in environments (drawn in code, no image assets) and their diffuse light as spherical harmonics, for the viewport and Baked Lighting Environment
use std::f32::consts::{PI, TAU};
use rayon::prelude::*;
use texturecraft_geom::glam::{Vec2, Vec3};
use crate::soft_box::SoftBox;
/// The width the viewport draws a built-in environment at (half as tall)
pub const VIEWPORT_WIDTH: u32 = 512;
/// The width an environment is box-averaged down to before its diffuse light is worked out: averaging keeps a sun smaller than a texel
const SH_WIDTH: u32 = 128;
/// The brightest radiance the viewport keeps of an imported environment (it stores half floats)
const HALF_FLOAT_MAX: f32 = 65_000.0;
/// The irradiance convolution factor of each SH band (the cosine lobe's π, 2π/3 and π/4), one per coefficient
const COSINE_LOBE_BANDS: [f32; 9] = [PI, 2.0 * PI / 3.0, 2.0 * PI / 3.0, 2.0 * PI / 3.0, PI / 4.0, PI / 4.0, PI / 4.0, PI / 4.0, PI / 4.0];
/// The linear radiance of a component `v` of an imported environment's texel (sRGB-encoded when `srgb`): not a number is 0, capped at the half-float range, sRGB at 1
pub fn environment_linear(v: f32, srgb: bool) -> f32 {
let v = if v.is_finite() { v.clamp(0.0, HALF_FLOAT_MAX) } else { 0.0 };
if srgb { texturecraft_texel::srgb_to_linear(v.min(1.0)) } else { v }
}
/// The direction at equirect place `u = φ / 2π`, `v = θ / π`: `(sin θ cos φ, cos θ, sin θ sin φ)`, row 0 straight up
pub fn dir_of(u: f32, v: f32) -> Vec3 {
let (theta, phi) = (v * PI, u * TAU);
Vec3::new(theta.sin() * phi.cos(), theta.cos(), theta.sin() * phi.sin())
}
/// The equirect place of direction `d`
pub fn uv_of(d: Vec3) -> Vec2 {
let phi = d.z.atan2(d.x);
Vec2::new((phi / TAU).rem_euclid(1.0), d.y.clamp(-1.0, 1.0).acos() / PI)
}
/// Smoothstep of `t` over 0..1
pub(crate) fn smooth(t: f32) -> f32 {
let t = t.clamp(0.0, 1.0);
t * t * (3.0 - 2.0 * t)
}
/// How fast a sky turns from its horizon to its zenith and to its ground (powers of the height; under 1 turns early)
const ZENITH_FALLOFF: f32 = 0.6;
const GROUND_FALLOFF: f32 = 0.25;
/// A sky blending `horizon` up to `zenith` and down to `ground`
fn sky(d: Vec3, zenith: Vec3, horizon: Vec3, ground: Vec3) -> Vec3 {
if d.y >= 0.0 { horizon.lerp(zenith, d.y.powf(ZENITH_FALLOFF)) } else { horizon.lerp(ground, (-d.y).powf(GROUND_FALLOFF)) }
}
/// The Sunset sun's disc: the cosine of its edge from the centre, the width of its soft rim, and its brightness
const SUN_EDGE_COS: f32 = 0.9985;
const SUN_EDGE_WIDTH: f32 = 0.0012;
const SUN_RADIANCE: f32 = 120.0;
/// The light a built-in environment `name` sends from direction `d` (unknown names give the default studio)
pub fn radiance(name: &str, d: Vec3) -> Vec3 {
if name == "Sunset" {
let base = sky(d, Vec3::new(0.15, 0.25, 0.55), Vec3::new(1.4, 0.65, 0.3), Vec3::new(0.08, 0.06, 0.05));
let sun_dir = dir_of(0.12, 0.47);
let sun = smooth((d.dot(sun_dir) - SUN_EDGE_COS) / SUN_EDGE_WIDTH) * SUN_RADIANCE;
return base + Vec3::new(1.0, 0.6, 0.3) * sun;
}
let (azimuth, elevation) = SoftBox::angles(d);
match name {
"Studio Contrast" => {
let base = sky(d, Vec3::splat(0.04), Vec3::splat(0.03), Vec3::splat(0.01));
base + SoftBox { azimuth: 35.0, elevation: 30.0, half_width: 22.0, half_height: 18.0, color: Vec3::new(14.0, 13.2, 12.0) }.eval(azimuth, elevation)
+ SoftBox { azimuth: -150.0, elevation: 40.0, half_width: 6.0, half_height: 30.0, color: Vec3::new(4.0, 4.4, 5.0) }.eval(azimuth, elevation)
}
"Overcast" => {
let base = sky(d, Vec3::new(1.2, 1.25, 1.35), Vec3::new(0.95, 0.95, 0.95), Vec3::new(0.18, 0.2, 0.15));
base + SoftBox { azimuth: 60.0, elevation: 55.0, half_width: 40.0, half_height: 25.0, color: Vec3::splat(0.6) }.eval(azimuth, elevation)
}
"Warehouse" => {
let mut c = sky(d, Vec3::splat(0.25), Vec3::splat(0.18), Vec3::splat(0.06));
for k in 0..6 {
c += SoftBox { azimuth: -150.0 + k as f32 * 60.0, elevation: 50.0, half_width: 6.0, half_height: 3.0, color: Vec3::new(9.0, 8.5, 7.5) }
.eval(azimuth, elevation);
}
c + SoftBox { azimuth: 90.0, elevation: 5.0, half_width: 30.0, half_height: 12.0, color: Vec3::new(1.6, 1.8, 2.2) }.eval(azimuth, elevation)
}
"Night" => {
let base = sky(d, Vec3::new(0.01, 0.015, 0.04), Vec3::new(0.03, 0.03, 0.06), Vec3::splat(0.005));
base + SoftBox { azimuth: 20.0, elevation: 15.0, half_width: 10.0, half_height: 10.0, color: Vec3::new(0.4, 1.6, 4.0) }.eval(azimuth, elevation)
+ SoftBox { azimuth: -110.0, elevation: 10.0, half_width: 12.0, half_height: 8.0, color: Vec3::new(4.0, 0.8, 1.6) }.eval(azimuth, elevation)
}
// "Studio Soft" (default)
_ => {
let base = sky(d, Vec3::new(0.5, 0.52, 0.56), Vec3::new(0.32, 0.32, 0.33), Vec3::new(0.08, 0.075, 0.07));
base + SoftBox { azimuth: 40.0, elevation: 35.0, half_width: 28.0, half_height: 20.0, color: Vec3::new(5.5, 5.2, 4.8) }.eval(azimuth, elevation)
+ SoftBox { azimuth: -125.0, elevation: 20.0, half_width: 35.0, half_height: 22.0, color: Vec3::new(1.1, 1.25, 1.5) }.eval(azimuth, elevation)
+ SoftBox { azimuth: 175.0, elevation: 55.0, half_width: 8.0, half_height: 25.0, color: Vec3::new(3.0, 3.0, 3.0) }.eval(azimuth, elevation)
}
}
}
/// The 9 real spherical-harmonics basis functions at unit direction `d` (the standard band 0..2 constants)
pub fn sh_basis(d: Vec3) -> [f32; 9] {
let (x, y, z) = (d.x, d.y, d.z);
[
0.282_095,
0.488_603 * y,
0.488_603 * z,
0.488_603 * x,
1.092_548 * x * y,
1.092_548 * y * z,
0.315_392 * (3.0 * z * z - 1.0),
1.092_548 * x * z,
0.546_274 * (x * x - y * y),
]
}
/// Diffuse irradiance as 9 SH coefficients of the equirect image `width` x `height` whose texels `radiance` gives (already convolved with the cosine lobe and divided by π, so `Σ c·Y(n)` times albedo is the diffuse radiance)
pub fn sh9(width: u32, height: u32, radiance: impl Fn(u32, u32) -> Vec3) -> [[f32; 3]; 9] {
let (w, h) = (width.max(1), height.max(1));
// Sample each large texel across its angular footprint so a constant sky lights all directions
const MIN_COLUMNS: u32 = 32;
const MIN_ROWS: u32 = 16;
let samples_x = MIN_COLUMNS.div_ceil(w);
let samples_y = MIN_ROWS.div_ceil(h);
let (w, h) = (w * samples_x, h * samples_y);
let mut sums = [Vec3::ZERO; 9];
for y in 0..h {
let theta = PI * (y as f32 + 0.5) / h as f32;
let solid_angle = (TAU / w as f32) * (PI / h as f32) * theta.sin();
for x in 0..w {
let direction = dir_of((x as f32 + 0.5) / w as f32, (y as f32 + 0.5) / h as f32);
// No firefly clamp: the projection integrates, so a bright sun lights diffuse fully
let weighted = radiance(x / samples_x, y / samples_y) * solid_angle;
for (sum, basis) in sums.iter_mut().zip(sh_basis(direction)) {
*sum += weighted * basis;
}
}
}
std::array::from_fn(|k| (sums[k] * COSINE_LOBE_BANDS[k] / PI).to_array())
}
/// [`sh9`] of the equirect image `width` x `height` whose texels `radiance` gives, box-halved while wider than [`SH_WIDTH`] (an odd last row or column is dropped, as the viewport drops it)
pub fn sh9_averaged(width: u32, height: u32, radiance: impl Fn(u32, u32) -> Vec3 + Sync) -> [[f32; 3]; 9] {
if width <= SH_WIDTH {
return sh9(width, height, radiance);
}
let mut image = half(width, height, radiance);
while image.0 > SH_WIDTH {
let (w, h, data) = &image;
image = half(*w, *h, |x, y| data.get((y * w + x) as usize).copied().unwrap_or(Vec3::ZERO));
}
let (w, h, data) = image;
sh9(w, h, |x, y| data.get((y * w + x) as usize).copied().unwrap_or(Vec3::ZERO))
}
/// The equirect image `width` x `height` whose texels `texel` gives, box-downsampled by 2 (wrapping around, clamped at the poles): its width, height and texels
pub fn half(width: u32, height: u32, texel: impl Fn(u32, u32) -> Vec3 + Sync) -> (u32, u32, Vec<Vec3>) {
let (w, h) = ((width / 2).max(1), (height / 2).max(1));
let get = |x: u32, y: u32| texel(x % width.max(1), y.min(height.saturating_sub(1)));
let mut data = vec![Vec3::ZERO; (w * h) as usize];
data.par_chunks_mut(w as usize).enumerate().for_each(|(y, row)| {
for (x, texel) in row.iter_mut().enumerate() {
let (sx, sy) = (x as u32 * 2, y as u32 * 2);
*texel = (get(sx, sy) + get(sx + 1, sy) + get(sx, sy + 1) + get(sx + 1, sy + 1)) * 0.25;
}
});
(w, h, data)
}
+4899 -788
View File
File diff suppressed because it is too large. Load diff
+25
View File
@@ -0,0 +1,25 @@
//! Where a layer is drawn inside the current texture set.
use texturecraft_core::{ContentsOffset, Layer, LayerId};
use super::EvaluationInputs;
#[derive(Clone, Copy, Default)]
pub(super) struct DrawPlacement {
pub offset: ContentsOffset,
/// Zero denotes the original folder tree
pub instance: usize,
}
impl From<ContentsOffset> for DrawPlacement {
fn from(offset: ContentsOffset) -> Self {
Self { offset, instance: 0 }
}
}
impl DrawPlacement {
pub(super) fn children(self, inputs: &EvaluationInputs, id: LayerId, source: &Layer) -> Self {
let instance = if id == source.id { self.instance } else { inputs.instance_draw(self.instance, id) };
Self { offset: self.offset.then(inputs.project.contents_offset(source.id)), instance }
}
}
@@ -0,0 +1,161 @@
use std::collections::HashMap;
use std::ops::Deref;
use std::sync::{Arc, Mutex, OnceLock, PoisonError};
use texturecraft_core::{FillSymmetry, Filter, LayerId, PreparedGradient, Project, Projection, Sampling};
use super::Inputs;
use crate::ProjectorDepthCache;
use crate::environment_sh::EnvironmentSh;
use crate::fill_depth::FillDepth;
use crate::generator_maps::GeneratorMaps;
use crate::pattern::mesh_frame;
use crate::projector_depth_cache::ViewDepth;
use crate::projector_view::ProjectorView;
/// Hold up to 30 MiB of depth maps through an evaluation; later views use the shared cache
const MAX_EVALUATION_VIEWS: usize = 10;
pub(super) struct EvaluationInputs<'a> {
inputs: &'a Inputs<'a>,
pub(super) projectors: &'a ProjectorDepthCache,
environment: OnceLock<EnvironmentSh>,
instance_draws: OnceLock<HashMap<(usize, LayerId), usize>>,
depth_maps: Mutex<Vec<ViewDepth>>,
/// The disabled mask being sampled directly by clone or smudge
pub(super) sampled_disabled_mask: Option<LayerId>,
pub(super) anchor_readers: HashMap<((LayerId, usize), LayerId), usize>,
pub(super) whole_maps: HashMap<LayerId, GeneratorMaps>,
pub(super) anchor_maps: HashMap<(LayerId, usize), GeneratorMaps>,
gradients: Mutex<HashMap<usize, Arc<PreparedGradient>>>,
field_geometry: OnceLock<u64>,
/// The project is the session's own stack as the viewport composites it, not one cut down (a histogram's, a thumbnail's, a solo layer's)
session_stack: bool,
}
impl<'a> EvaluationInputs<'a> {
pub(super) fn new(inputs: &'a Inputs<'a>, projectors: &'a ProjectorDepthCache) -> Self {
Self {
inputs,
projectors,
environment: OnceLock::new(),
instance_draws: OnceLock::new(),
depth_maps: Mutex::new(Vec::new()),
sampled_disabled_mask: None,
anchor_readers: HashMap::new(),
whole_maps: HashMap::new(),
anchor_maps: HashMap::new(),
gradients: Mutex::default(),
field_geometry: OnceLock::new(),
session_stack: false,
}
}
/// These inputs evaluating the session's own stack: they keep the anchor heights the stack reads and drop the rest
pub(super) fn of_the_session_stack(self) -> Self {
Self { session_stack: true, ..self }
}
/// Whether the project evaluated is the session's own stack (see [`EvaluationInputs::of_the_session_stack`])
pub(super) fn is_session_stack(&self) -> bool {
self.session_stack
}
/// The whole-map fields share one fingerprint of the sampled geometry and layout
pub(super) fn field_identity(&self) -> u64 {
*self.field_geometry.get_or_init(|| crate::field_cache::field_identity(self.inputs))
}
pub(super) fn environment(&self) -> EnvironmentSh {
if let Some(environment) = self.environment.get() {
return *environment;
}
// Rayon may enter another plan while taking samples for the first one
let environment = EnvironmentSh::of(&self.project.display, self.images);
let _ = self.environment.set(environment);
environment
}
/// Each path through nested folder instances gets a stable identity within an evaluation.
pub(super) fn instance_draw(&self, parent: usize, id: LayerId) -> usize {
let draws = self.instance_draws.get_or_init(|| {
let mut draws = HashMap::new();
if let Ok(set) = self.project.texture_set(self.ts) {
collect_instance_draws(self.project, &set.stack, 0, 0, &mut draws);
}
draws
});
draws.get(&(parent, id)).copied().unwrap_or_default()
}
pub(super) fn projector_depth(&self, projection: &Projection, sampling: Sampling) -> Option<Arc<FillDepth>> {
let view = ProjectorView::of(projection, self.bounds)?;
let copies = sampling.symmetry.on.then(|| {
let (center, radius) = mesh_frame(self.bounds);
// Flipping the image leaves the projector's depth view unchanged
(FillSymmetry { flip: [false; 2], ..sampling.symmetry }, center, radius)
});
let key = (view, copies);
let mut depth_maps = self.depth_maps.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
if let Some((_, map)) = depth_maps.iter().find(|(cached_key, _)| *cached_key == key) {
return map.clone();
}
if depth_maps.len() >= MAX_EVALUATION_VIEWS {
// Keep overflow work out of the evaluation lock
drop(depth_maps);
return self.projectors.get(self.mesh, key);
}
let depth = self.projectors.get(self.mesh, key);
depth_maps.push((key, depth.clone()));
depth
}
pub(super) fn gradient(&self, filter: &'a Filter) -> Option<Arc<PreparedGradient>> {
if !matches!(filter, Filter::GradientMap { linear: false, .. }) {
return None;
}
// The borrowed project keeps filter addresses stable for this evaluation
let key = std::ptr::from_ref(filter) as usize;
let mut gradients = self.gradients.lock().unwrap_or_else(PoisonError::into_inner);
if let Some(prepared) = gradients.get(&key) {
return Some(Arc::clone(prepared));
}
let prepared = Arc::new(PreparedGradient::of(filter)?);
gradients.insert(key, Arc::clone(&prepared));
Some(prepared)
}
}
impl<'a> Deref for EvaluationInputs<'a> {
type Target = Inputs<'a>;
fn deref(&self) -> &Self::Target {
self.inputs
}
}
fn collect_instance_draws(project: &Project, layers: &[LayerId], parent: usize, depth: usize, draws: &mut HashMap<(usize, LayerId), usize>) {
if depth > texturecraft_core::project::MAX_DEPTH {
return;
}
for &id in layers {
let Some(source) = project.content_layer(id).filter(|layer| !layer.children().is_empty()) else { continue };
let instance = if id == source.id {
parent
} else {
let next = draws.len() + 1;
*draws.entry((parent, id)).or_insert(next)
};
collect_instance_draws(project, source.children(), instance, depth + 1, draws);
}
}
+26 -5
View File
@@ -1,25 +1,46 @@
//! Isolated folder evaluation with the original stack available for anchor inputs.
use super::{Channel, ChannelKind, Composite, Inputs, LayerId, Texel, all_tiles, neighbourhood_fields, plan, tile_texels, to_u16, to_u16_signed};
use super::{
Channel, ChannelKind, Composite, EvaluationInputs, Inputs, LayerId, ProjectorDepthCache, Tape, Texel, all_tiles, evaluation_channels, evaluation_fields,
plan, tile_texels, to_u16, to_u16_signed,
};
/// Composite one layer over channel defaults, keeping anchors from the stack below it.
pub(crate) fn composite_layer(inputs: &Inputs, layer: LayerId, channel: Channel) -> Option<Composite> {
let set = inputs.project.texture_set(inputs.ts).ok()?;
let channels = set.channel_list();
let channels = evaluation_channels(inputs, set.channel_list());
let (width, height) = (inputs.gbuf.width, inputs.gbuf.height);
let tiles = all_tiles(width, height);
let fields = neighbourhood_fields(inputs, &channels, &tiles);
let projectors = ProjectorDepthCache::default();
let inputs = &EvaluationInputs::new(inputs, &projectors);
let fields = evaluation_fields(inputs, &channels, &tiles);
let mut composite = Composite::with_size(&[channel], width, height);
let output = composite.channels.get_mut(&channel)?;
let mut recorded = Vec::new();
for (tile_x, tile_y) in tiles {
let nodes = plan(inputs, &[layer], &channels, tile_x, tile_y, 0, Some(&fields));
let full_stack = if set.stack.as_slice() == [layer] { Vec::new() } else { plan(inputs, &set.stack, &channels, tile_x, tile_y, 0, Some(&fields)) };
for (x, y, offset) in tile_texels(inputs.gbuf, tile_x, tile_y) {
let mut texel = Texel::new(inputs, x, y, offset, 0.0);
texel.anchors_below(&full_stack, layer);
texel.anchors_below(&full_stack, (layer, 0));
let mut values = Channel::ALL.map(Channel::default_value);
texel.eval(&nodes, &mut values);
if let Some(mut backdrop) = texel.below {
// Evaluate masks against the real backdrop, then show only this folder's contribution
texel.tape = Tape::Record(std::mem::take(&mut recorded));
texel.eval(&nodes, &mut backdrop);
if let Tape::Record(samples) = texel.tape {
recorded = samples;
}
let mut isolated = Texel::new(inputs, x, y, offset, 0.0);
isolated.tape = Tape::Replay(&recorded, 0);
isolated.eval(&nodes, &mut values);
recorded.clear();
} else {
texel.eval(&nodes, &mut values);
}
let value = values.get(channel.index()).copied().unwrap_or_else(|| channel.default_value());
let encoded = value.map(|component| if channel.kind() == ChannelKind::Signed { to_u16_signed(component) } else { to_u16(component) });
output.set(x, y, &encoded[..channel.components()]);
+124
View File
@@ -0,0 +1,124 @@
use std::hash::{DefaultHasher, Hash, Hasher};
use std::sync::{Arc, Mutex};
use texturecraft_core::BakedMap;
use texturecraft_geom::NO_TRI;
use crate::eval::Inputs;
use crate::field_cache_key::FieldCacheKey;
use crate::sampled_map::SampledMap;
use crate::working_field::working_block;
/// Most fields cached, and the bytes they may hold (the newest is kept whatever its size)
pub(crate) const CACHE_ENTRIES: usize = 8;
const CACHE_BYTES: usize = 256 << 20;
/// FNV-1a prime for the dense texel scan
const TEXEL_HASH_BASIS: u64 = 0xcbf2_9ce4_8422_2325;
const TEXEL_HASH_PRIME: u64 = 0x0000_0100_0000_01b3;
/// Geometry and layout data read by the whole-map generators
pub(crate) fn field_identity(inputs: &Inputs) -> u64 {
let gbuf = inputs.gbuf;
let mesh = inputs.mesh;
let mut hash = DefaultHasher::new();
(gbuf.width, gbuf.height, gbuf.tri.len(), gbuf.bary.len()).hash(&mut hash);
// Keep this scan synchronous because Rayon tile plans can share a OnceLock
let mut texels = TEXEL_HASH_BASIS;
let mut mix_texel = |value: u32| texels = (texels ^ u64::from(value)).wrapping_mul(TEXEL_HASH_PRIME);
for (index, &triangle) in gbuf.tri.iter().enumerate() {
mix_texel(triangle);
if triangle != NO_TRI
&& let Some(weights) = gbuf.bary.get(index)
{
mix_texel(weights[0].to_bits());
mix_texel(weights[1].to_bits());
}
}
texels.hash(&mut hash);
mesh.indices.hash(&mut hash);
mesh.positions.len().hash(&mut hash);
mesh.positions.iter().for_each(|value| value.to_array().map(f32::to_bits).hash(&mut hash));
mesh.uvs.len().hash(&mut hash);
mesh.uvs.iter().for_each(|value| value.to_array().map(f32::to_bits).hash(&mut hash));
mesh.normals.len().hash(&mut hash);
mesh.normals.iter().for_each(|value| value.to_array().map(f32::to_bits).hash(&mut hash));
// Surface interpolation needs tangent slots to exist even when generators do not use the values
mesh.tangents.len().hash(&mut hash);
inputs.bounds.0.to_array().map(f32::to_bits).hash(&mut hash);
inputs.bounds.1.to_array().map(f32::to_bits).hash(&mut hash);
let set = inputs.project.texture_set(inputs.ts).ok();
if let Some(set) = set {
set.material.hash(&mut hash);
mesh.submeshes.len().hash(&mut hash);
mesh.submeshes.iter().for_each(|part| (part.material, part.start, part.count).hash(&mut hash));
set.uv_tiles.hash(&mut hash);
set.resolution.hash(&mut hash);
set.tile_resolutions.hash(&mut hash);
}
hash.finish()
}
/// Built fields by what they were built from, most recently used last
pub(crate) struct FieldCache {
entries: Mutex<Vec<(FieldCacheKey, Arc<Vec<f32>>)>>,
}
impl FieldCache {
pub(crate) const fn new() -> FieldCache {
FieldCache { entries: Mutex::new(Vec::new()) }
}
/// Reuse a field keyed by [`field_identity`], the baked maps it reads and its settings.
/// Run the missing field's parallel build outside the cache lock.
pub(crate) fn get_or_build(
&self,
inp: &Inputs,
geometry: u64,
maps: &[BakedMap],
settings: Vec<u32>,
build: impl FnOnce((u32, u32)) -> Vec<f32>,
) -> Arc<Vec<f32>> {
let block = working_block(inp);
let read = maps.iter().filter_map(|map| {
inp.baked.maps.get(map).map(|data| SampledMap { data: Arc::downgrade(data), baked_size: (inp.baked.resolution, inp.baked.height(*map)) })
});
let key = FieldCacheKey { geometry, block, scales: inp.block_scales.clone(), maps: read.collect(), settings };
// A hit moves to the most recently used end
let cached = {
let mut entries = self.entries.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
entries.retain(|(key, _)| key.maps.iter().all(|map| map.data.strong_count() > 0));
let hit = entries.iter().position(|(cached, _)| *cached == key).map(|index| entries.remove(index));
hit.map(|(cached, field)| {
entries.push((cached, field.clone()));
field
})
};
if let Some(field) = cached {
return field;
}
let field = Arc::new(build(block));
let mut entries = self.entries.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
entries.retain(|(cached, _)| *cached != key);
entries.push((key, field.clone()));
let mut bytes = 0usize;
let keep = entries
.iter()
.rev()
.take_while(|(_, built)| {
bytes = bytes.saturating_add(built.len().saturating_mul(size_of::<f32>()));
bytes <= CACHE_BYTES
})
.count()
.clamp(1, CACHE_ENTRIES);
let excess = entries.len().saturating_sub(keep);
entries.drain(..excess);
field
}
}
+13
View File
@@ -0,0 +1,13 @@
use texturecraft_core::BlockScales;
use crate::sampled_map::SampledMap;
/// What a field was built from: geometry, atlas layout, baked-map identities and generator settings
#[derive(Clone, PartialEq)]
pub(crate) struct FieldCacheKey {
pub(crate) geometry: u64,
pub(crate) block: (u32, u32),
pub(crate) scales: BlockScales,
pub(crate) maps: Vec<SampledMap>,
pub(crate) settings: Vec<u32>,
}
+164
View File
@@ -0,0 +1,164 @@
//! The copies a symmetric fill makes of its projection, as mirrors and turns of the surface point each copy samples
use texturecraft_core::{FULL_TURN_DEGREES, FillSymmetry, SymmetryKind};
use texturecraft_geom::glam::{Mat3, Vec3};
use crate::fill_copy::FillCopy;
/// The copies of a fill's projection one texel shows, the original among them: the one whose half (mirror) or wedge (radial) holds the texel comes first, so it lies on top where copies overlap
pub struct FillCopies {
symmetry: FillSymmetry,
pivot: Vec3,
axis: usize,
step: f32,
first: u32,
count: u32,
next: u32,
}
impl FillCopies {
/// The copies `symmetry` makes for a texel at world point `point`, on a mesh whose bounds have centre `center` and radius `radius`
pub fn new(symmetry: &FillSymmetry, point: Vec3, center: Vec3, radius: f32) -> FillCopies {
let reach = FillSymmetry::REACH;
let position = Vec3::from(symmetry.position.map(|coordinate| if coordinate.is_finite() { coordinate.clamp(-reach, reach) } else { 0.0 }));
let pivot = center + position * radius;
let axis = symmetry.axis_index();
let count = symmetry.copies();
let step = symmetry.step();
let from_pivot = point - pivot;
let first = match symmetry.kind {
// The original keeps the half on the axis's positive side
SymmetryKind::Mirror => u32::from(from_pivot[axis] < 0.0),
SymmetryKind::Radial => {
let turned = from_pivot[(axis + 2) % 3].atan2(from_pivot[(axis + 1) % 3]).to_degrees().rem_euclid(FULL_TURN_DEGREES);
nearest_copy(turned, step, count, symmetry.span)
}
};
FillCopies { symmetry: *symmetry, pivot, axis, step, first, count, next: 0 }
}
/// Copy `index`: the original at 0, then the mirror or the radial copies in turn
pub(crate) fn copy(&self, index: u32) -> FillCopy {
let flip = if index == 0 { [false; 2] } else { self.symmetry.flip };
let turn = match self.symmetry.kind {
_ if index == 0 => Mat3::IDENTITY,
SymmetryKind::Mirror => {
let mut scale = Vec3::ONE;
scale[self.axis] = -1.0;
Mat3::from_diagonal(scale)
}
// Copy `index` is the original turned by `index` steps, so a texel samples the original turned back
SymmetryKind::Radial => Mat3::from_axis_angle(Vec3::AXES[self.axis], -(index as f32 * self.step).to_radians()),
};
FillCopy::new(turn, self.pivot, flip)
}
pub(crate) fn next_indexed(&mut self) -> Option<(usize, FillCopy)> {
if self.next >= self.count {
return None;
}
let index = (self.first + self.next) % self.count;
self.next += 1;
Some((index as usize, self.copy(index)))
}
}
/// The radial copy nearest a texel `turned` degrees round the axis, of `count` copies `step` degrees apart over `span` degrees: copy 0 across the gap a span under a full turn leaves, else the nearest by its step
fn nearest_copy(turned: f32, step: f32, count: u32, span: f32) -> u32 {
// A span of nothing (or no step at all) stacks every copy on the original
if step.is_nan() || step <= 0.0 {
return 0;
}
let by_step = (turned / step).round() as u32;
if span >= FULL_TURN_DEGREES || span.is_nan() {
return by_step % count;
}
let last = by_step.min(count - 1);
let past_last = (turned - last as f32 * step).abs();
let before_first = FULL_TURN_DEGREES - turned;
if before_first <= past_last { 0 } else { last }
}
impl Iterator for FillCopies {
type Item = FillCopy;
fn next(&mut self) -> Option<FillCopy> {
self.next_indexed().map(|(_, copy)| copy)
}
}
#[cfg(test)]
mod tests {
use texturecraft_geom::glam::Vec2;
use super::*;
fn symmetry(kind: SymmetryKind, axis: u8) -> FillSymmetry {
FillSymmetry { on: true, kind, axis, ..FillSymmetry::OFF }
}
#[test]
fn a_mirror_puts_the_texels_own_half_first_and_reflects_across_the_axis_position() {
let mut mirror = symmetry(SymmetryKind::Mirror, 0);
mirror.position = [0.5, 0.0, 0.0];
let left: Vec<FillCopy> = FillCopies::new(&mirror, Vec3::new(-1.0, 0.0, 0.0), Vec3::ZERO, 2.0).collect();
assert_eq!(left.len(), 2);
// The plane passes at x = 1 (half a radius of 2): a point at -1 sees the original at 3 first
assert!(left[0].point(Vec3::new(-1.0, 0.2, 0.0)).abs_diff_eq(Vec3::new(3.0, 0.2, 0.0), 1e-5));
assert!(left[1].point(Vec3::new(-1.0, 0.2, 0.0)).abs_diff_eq(Vec3::new(-1.0, 0.2, 0.0), 1e-5));
assert!(left[0].normal(Vec3::X).abs_diff_eq(-Vec3::X, 1e-5));
let right: Vec<FillCopy> = FillCopies::new(&mirror, Vec3::new(2.0, 0.0, 0.0), Vec3::ZERO, 2.0).collect();
assert!(right[0].point(Vec3::new(2.0, 0.3, 0.0)).abs_diff_eq(Vec3::new(2.0, 0.3, 0.0), 1e-5));
}
#[test]
fn radial_copies_turn_by_their_step_and_flip_only_the_copies() {
let mut radial = symmetry(SymmetryKind::Radial, 2);
radial.count = 4;
radial.flip = [true, false];
let copies: Vec<FillCopy> = FillCopies::new(&radial, Vec3::X, Vec3::ZERO, 1.0).collect();
assert_eq!(copies.len(), 4);
assert_eq!(copies[0].uv(Vec2::new(0.25, 0.5)), Vec2::new(0.25, 0.5));
assert_eq!(copies[1].uv(Vec2::new(0.25, 0.5)), Vec2::new(0.75, 0.5));
// Copy 1 sits a quarter turn on: a texel on +Y samples the original on +X
assert!(copies[1].point(Vec3::Y).abs_diff_eq(Vec3::X, 1e-5));
// A texel on +Y lies in copy 1's wedge, so copy 1 comes first there
let on_y: Vec<FillCopy> = FillCopies::new(&radial, Vec3::Y, Vec3::ZERO, 1.0).collect();
assert!(on_y[0].point(Vec3::Y).abs_diff_eq(Vec3::X, 1e-5));
}
#[test]
fn the_nearest_copy_is_found_by_its_step_as_a_search_of_every_copy_finds_it() {
for (count, span) in [(6, 360.0), (5, 360.0), (4, 180.0), (3, 90.0), (64, 300.0), (2, 1.0)] {
let step = radial_step(count, span);
for tenth in 0..3600 {
let turned = tenth as f32 / 10.0 + 0.05;
let gap = |index: u32| {
let past_copy = (turned - index as f32 * step).rem_euclid(FULL_TURN_DEGREES);
past_copy.min(FULL_TURN_DEGREES - past_copy)
};
let searched = (0..count).min_by(|a, b| gap(*a).total_cmp(&gap(*b))).unwrap_or(0);
assert_eq!(nearest_copy(turned, step, count, span), searched, "{count} copies over {span} at {turned}");
}
}
}
fn radial_step(count: u32, span: f32) -> f32 {
FillSymmetry { count, span, ..symmetry(SymmetryKind::Radial, 2) }.step()
}
}
+34
View File
@@ -0,0 +1,34 @@
//! One copy of a symmetric fill's projection: the mirror or turn a texel samples it through
use texturecraft_geom::glam::{Mat3, Vec2, Vec3};
/// One copy of a fill's projection: a texel at a point shows what the projection gives at [`FillCopy::point`]
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct FillCopy {
turn: Mat3,
pivot: Vec3,
flip: [bool; 2],
}
impl FillCopy {
/// A copy sampling the projection at `pivot + turn * (point - pivot)`, its image turned over across and down as `flip` says
pub fn new(turn: Mat3, pivot: Vec3, flip: [bool; 2]) -> FillCopy {
FillCopy { turn, pivot, flip }
}
/// The surface point the projection is sampled at for a texel at world point `point`
pub fn point(&self, point: Vec3) -> Vec3 {
self.pivot + self.turn * (point - self.pivot)
}
/// The normal the projection sees for a texel whose normal is `normal`
pub fn normal(&self, normal: Vec3) -> Vec3 {
self.turn * normal
}
/// `uv` in the copy's image, turned over across and down as its Flip copy says
pub fn uv(&self, uv: Vec2) -> Vec2 {
let [across, down] = self.flip;
Vec2::new(if across { 1.0 - uv.x } else { uv.x }, if down { 1.0 - uv.y } else { uv.y })
}
}
+43
View File
@@ -0,0 +1,43 @@
use texturecraft_core::FillSymmetry;
use texturecraft_geom::{Mesh, glam::Vec3};
use crate::fill_copies::FillCopies;
use crate::projector_depth::{CELL_BUDGET, GRID_SIDE, ProjectorDepth};
use crate::projector_view::ProjectorView;
pub(crate) type FillDepthKey = (ProjectorView, Option<(FillSymmetry, Vec3, f32)>);
/// Depth coverage in the original and optional symmetric views of one fill.
pub(crate) enum FillDepth {
Single(ProjectorDepth),
Copies(Box<[Option<ProjectorDepth>]>),
}
impl FillDepth {
pub(crate) fn build(mesh: &Mesh, (view, symmetry): FillDepthKey) -> Option<Self> {
let Some((symmetry, center, radius)) = symmetry else {
return ProjectorDepth::build(view, mesh).map(Self::Single);
};
let copies = FillCopies::new(&symmetry, center, center, radius);
let count = symmetry.copies() as usize;
// Share one grid's storage and raster budget across the copy views
let grid_side = (GRID_SIDE * GRID_SIDE / count).isqrt();
let cell_budget = CELL_BUDGET / count;
let maps: Box<_> =
(0..count).map(|index| ProjectorDepth::build_for_copy(view, mesh, Some(copies.copy(index as u32)), grid_side, cell_budget)).collect();
maps.iter().any(Option::is_some).then_some(Self::Copies(maps))
}
/// Read coverage at the point already transformed into the selected copy's space.
pub(crate) fn cover(&self, copy_index: usize, position: Vec3, hardness: f32) -> f32 {
let depth = match self {
Self::Single(depth) => Some(depth),
Self::Copies(maps) => maps.get(copy_index).and_then(Option::as_ref),
};
depth.map_or(1.0, |depth| depth.cover(position, hardness))
}
}
+13
View File
@@ -0,0 +1,13 @@
use texturecraft_core::{Fill, Projection};
use crate::fill_depth::FillDepth;
/// A fill as a texel samples it: the fill, its projector's depth map when it culls by depth, and whether it covers every texel
#[derive(Clone, Copy)]
pub(crate) struct FillPlace<'f> {
pub fill: &'f Fill,
pub projection: &'f Projection,
pub depth: Option<&'f FillDepth>,
/// Decided once per tile, so a texel never works its coverage out
pub covers_all: bool,
}
+358
View File
@@ -0,0 +1,358 @@
//! A frame on the surface (a placed planar or a warp) as its 3D projection settings show it: where its centre is, how it is turned and how big it is
use texturecraft_core::{Decal, Projection, Projector};
use texturecraft_geom::glam::{EulerRot, Mat3, Quat, Vec3};
use crate::pattern::{decal_axes, mesh_frame, projector_stretch};
/// The shortest frame side a depth is divided by, so a collapsed frame keeps a finite depth
pub const MIN_FRAME_SIDE: f32 = 1e-6;
/// Below this the frame faces nearly straight up or down, so world up gives no upright direction
const MIN_UP_CROSS_SQUARED: f32 = 1e-6;
/// The longer side of a frame of `size`, at least [`MIN_FRAME_SIDE`]: a warp's Projection Depth counts in it
pub fn longer_side(size: [f32; 2]) -> f32 {
size[0].max(size[1]).max(MIN_FRAME_SIDE)
}
/// How far a warp whose frame has `size` reaches in front of and behind it at Projection Depth `depth`, in world units
pub fn warp_reach(size: [f32; 2], depth: f32) -> f32 {
depth * longer_side(size)
}
/// A frame's Offset (its centre in mesh radii from the mesh's centre), Rotation (degrees round X, Y and Z, as a projector turns) and Scale (its width and height, then how far it reaches in front of and behind it, in mesh diagonals)
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct FramePlacement {
pub offset: [f32; 3],
pub rotation: [f32; 3],
pub scale: [f32; 3],
}
/// Whether moving the projector's scale into the frame preserves culling
pub fn culling_folds(projector: &Projector) -> bool {
let stretch = projector_stretch(projector);
let size = stretch.abs();
let even = size.x == size.y && size.y == size.z;
let facing_preserved = stretch.x.signum() * stretch.y.signum() * stretch.z.signum() > 0.0;
(!projector.depth.on || facing_preserved) && (!projector.backface.on || (even && facing_preserved))
}
/// Fold a placed planar or warp's turn and scale into its frame while preserving crop and culling.
/// See [`culling_folds`] for when a fold would change culling.
pub fn folded(proj: &Projection) -> Option<Projection> {
let (frame, projector) = match proj {
Projection::Planar { placed: Some(frame), projector, .. } | Projection::Warp { frame, projector, .. } => (frame, projector),
_ => return None,
};
if !projector.turns() {
return Some(proj.clone());
}
if !culling_folds(projector) {
return None;
}
let (origin, across, up, _) = decal_axes(frame)?;
let [x, y, z] = projector.rotation.map(f32::to_radians);
let turn = Mat3::from_cols(across, up, across.cross(up)) * Mat3::from_euler(EulerRot::ZYX, z, y, x);
let stretch = projector_stretch(projector);
// A negative scale turns that side over
let (across, up) = (turn.x_axis * stretch.x.signum(), turn.y_axis * stretch.y.signum());
let size = [frame.size[0] * stretch.x.abs(), frame.size[1] * stretch.y.abs()];
let reach = stretch.z.abs();
let new_frame = Decal {
center: origin.to_array(),
normal: across.cross(up).to_array(),
up: up.to_array(),
size,
rotation: 0.0,
offset: [0.0; 2],
depth: frame.depth * reach,
symmetry: frame.symmetry,
flip: frame.flip,
};
let unturned = Projector { rotation: [0.0; 3], scale: [1.0; 3], ..*projector };
let mut out = proj.clone();
match &mut out {
Projection::Planar { placed: Some(placed), projector, .. } => {
*placed = new_frame;
*projector = unturned;
}
Projection::Warp { frame: warp, projector, depth, .. } => {
// Its depth counts in lengths of the frame's longer side
*depth *= reach * longer_side(frame.size) / longer_side(size);
*warp = new_frame;
*projector = unturned;
}
_ => return None,
}
let finite = new_frame.center.iter().chain(&new_frame.normal).chain(&new_frame.up).chain(&new_frame.size).all(|v| v.is_finite());
finite.then_some(out)
}
/// How far frame projection `proj` reaches in front of and behind its frame, in world units (a warp counts its depth in lengths of the longer side)
fn reach(proj: &Projection) -> Option<f32> {
match proj {
Projection::Planar { placed: Some(frame), .. } => Some(frame.depth),
Projection::Warp { frame, depth, .. } => Some(warp_reach(frame.size, *depth)),
_ => None,
}
}
/// Where frame projection `proj` (a placed planar or a warp) sits on a mesh with bounds `bounds`, its projector folded in (None for other projections)
pub fn placement(proj: &Projection, bounds: (Vec3, Vec3)) -> Option<FramePlacement> {
let proj = folded(proj)?;
let frame = proj.frame()?;
let (center, radius) = mesh_frame(bounds);
let (origin, across, up, out) = decal_axes(frame)?;
let (z, y, x) = Quat::from_mat3(&Mat3::from_cols(across, up, out)).to_euler(EulerRot::ZYX);
let diagonal = 2.0 * radius;
let placement = FramePlacement {
offset: ((origin - center) / radius).to_array(),
rotation: [x, y, z].map(f32::to_degrees),
scale: [frame.size[0] / diagonal, frame.size[1] / diagonal, reach(&proj)? / diagonal],
};
let values = placement.offset.iter().chain(&placement.rotation).chain(&placement.scale);
values.copied().all(f32::is_finite).then_some(placement)
}
/// Frame projection `proj` (a placed planar or a warp) moved to `placement`; its projector's turn and scale are folded in first, its other settings kept (None for other projections or a degenerate placement)
pub fn placed(proj: &Projection, placement: &FramePlacement, bounds: (Vec3, Vec3)) -> Option<Projection> {
let values = placement.offset.iter().chain(&placement.rotation).chain(&placement.scale);
let [width_scale, height_scale, reach_scale] = placement.scale;
let valid_reach = reach_scale > 0.0 || (reach_scale == 0.0 && matches!(proj, Projection::Warp { .. }));
if !values.copied().all(f32::is_finite) || width_scale <= 0.0 || height_scale <= 0.0 || !valid_reach {
return None;
}
let mut proj = folded(proj)?;
let old = *proj.frame()?;
let (center, radius) = mesh_frame(bounds);
let diagonal = 2.0 * radius;
let [x, y, z] = placement.rotation.map(f32::to_radians);
let turn = Mat3::from_euler(EulerRot::ZYX, z, y, x);
let [width, height, deep] = placement.scale.map(|scale| scale * diagonal);
let frame = Decal {
center: (center + Vec3::from(placement.offset) * radius).to_array(),
normal: turn.z_axis.to_array(),
up: turn.y_axis.to_array(),
size: [width, height],
rotation: 0.0,
offset: [0.0; 2],
depth: deep,
symmetry: old.symmetry,
flip: old.flip,
};
match &mut proj {
Projection::Planar { placed: Some(placed), .. } => *placed = frame,
Projection::Warp { frame: warp, depth, .. } => {
*depth = deep / longer_side([width, height]);
// The warp's own depth is what reaches; the frame's is unused
*warp = Decal { depth: warp.depth, ..frame };
}
_ => return None,
}
Some(proj)
}
/// A frame's turn round its own normal, as seen face on with the world's up (or, looking straight down, the far side) at the top: degrees
pub fn upright_turn(frame: &Decal) -> Option<f32> {
let (_, _, up, out) = decal_axes(frame)?;
let world_up = if out.cross(Vec3::Y).length_squared() > MIN_UP_CROSS_SQUARED { Vec3::Y } else { Vec3::NEG_Z };
let upright = (world_up - out * out.dot(world_up)).try_normalize()?;
let upright_across = upright.cross(out);
let turn = (-up.dot(upright_across)).atan2(up.dot(upright)).to_degrees();
turn.is_finite().then_some(turn)
}
#[cfg(test)]
mod tests {
use texturecraft_core::{Backface, DecalFlip, DecalSymmetry, ShapeCrop, UvTransform};
use texturecraft_geom::glam::Vec2;
use super::*;
use crate::projector_cover::framed_cover;
const BOUNDS: (Vec3, Vec3) = (Vec3::new(-1.0, -2.0, -0.5), Vec3::new(3.0, 1.0, 1.5));
fn frame() -> Decal {
Decal {
center: [0.4, -0.2, 1.3],
normal: [0.2, 0.1, 1.0],
up: [0.0, 1.0, 0.1],
size: [1.2, 0.8],
rotation: 25.0,
offset: [0.1, -0.2],
depth: 0.6,
symmetry: None,
flip: [false; 2],
}
}
fn planar(projector: Projector) -> Projection {
Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv: UvTransform::default(), projector, placed: Some(frame()) }
}
fn warp(projector: Projector) -> Projection {
Projection::Warp { frame: frame(), corners: [[-0.6, 0.5], [0.5, 0.4], [0.5, -0.5], [-0.4, -0.5]], depth: 0.7, uv: UvTransform::default(), projector }
}
/// The projection's texture coordinates and cover at points through the frame's neighbourhood with varied normals
fn samples(proj: &Projection) -> Vec<Option<(Vec2, f32)>> {
let mut out = Vec::new();
for across in 0..7 {
for up in 0..7 {
for out_of in 0..3 {
let position = Vec3::new(-0.5 + across as f32 * 0.25, -0.8 + up as f32 * 0.2, 0.7 + out_of as f32 * 0.3);
let normal = Vec3::new(0.1 * across as f32 - 0.3, 0.2, 1.0).normalize();
out.push(framed_cover(proj, position, normal, (BOUNDS.0 + BOUNDS.1) * 0.5));
}
}
}
out
}
fn projector_of(proj: &Projection) -> Projector {
match proj {
Projection::Planar { projector, .. } | Projection::Warp { projector, .. } => *projector,
_ => panic!("a frame projection"),
}
}
fn close(a: &[Option<(Vec2, f32)>], b: &[Option<(Vec2, f32)>]) {
assert_eq!(a.len(), b.len());
for (index, (a, b)) in a.iter().zip(b).enumerate() {
match (a, b) {
(Some((uv_a, cover_a)), Some((uv_b, cover_b))) => {
assert!((cover_a - cover_b).abs() < 1e-3, "{index}: cover {cover_a} vs {cover_b}");
assert!(uv_a.distance(*uv_b) < 1e-3, "{index}: {uv_a} vs {uv_b}");
}
(None, None) => {}
_ => panic!("{index}: sampled on one side only: {a:?} vs {b:?}"),
}
}
}
#[test]
fn folding_a_turned_and_evenly_scaled_projector_into_its_frame_lands_the_same() {
let projector = Projector { rotation: [20.0, -35.0, 50.0], scale: [1.7; 3], crop: ShapeCrop::Cropped, ..Projector::default() };
for proj in [planar(projector), warp(projector)] {
let flat = folded(&proj).unwrap();
let Projector { rotation, scale, crop, .. } = projector_of(&flat);
assert_eq!((rotation, scale, crop), ([0.0; 3], [1.0; 3], ShapeCrop::Cropped), "the turn and scale moved into the frame, the crop stayed");
close(&samples(&proj), &samples(&flat));
}
let unturned = planar(Projector::default());
assert_eq!(folded(&unturned), Some(unturned), "nothing to fold: unchanged");
assert_eq!(folded(&Projection::default()), None);
}
#[test]
fn depth_culling_prevents_folding_with_the_opposite_facing() {
let mut projector = Projector::depth_culled();
projector.scale[2] = -1.0;
let bounds = (Vec3::NEG_ONE, Vec3::ONE);
let axis_planar = Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv: UvTransform::default(), projector, placed: None };
assert!(folded(&planar(projector)).is_none(), "an existing frame would face the opposite direction");
assert!(crate::axis_frame::placed_from_axis(&axis_planar, bounds).is_none(), "an axis projector would face the opposite direction");
assert!(folded(&planar(Projector::depth_culled())).is_some(), "unit stretch preserves facing");
}
#[test]
fn folding_keeps_what_backface_culling_hides() {
let backface = Backface { on: true, angle: 60.0, hardness: 1.0 };
let square = Decal { center: [0.0; 3], normal: [0.0, 0.0, 1.0], up: [0.0, 1.0, 0.0], size: [1.0, 1.0], rotation: 0.0, offset: [0.0; 2], ..frame() };
// An oblique normal distinguishes tilt from reflection
let normal = Vec3::new(1.0, 0.0, 1.0).normalize();
let center = (BOUNDS.0 + BOUNDS.1) * 0.5;
let cover = |proj: &Projection| framed_cover(proj, Vec3::ZERO, normal, center).map(|(_, cover)| cover);
for scale in [[4.0, 1.0, 1.0], [1.5, -1.5, 1.5], [1.7; 3]] {
let projector = Projector { scale, backface, ..Projector::default() };
let proj = Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv: UvTransform::default(), projector, placed: Some(square) };
match folded(&proj) {
Some(flat) => {
assert_eq!(cover(&proj), cover(&flat), "{scale:?}: culling changed");
close(&samples(&proj), &samples(&flat));
}
None => assert!(!culling_folds(&projector), "{scale:?}: only a scale culling cannot keep stays unfolded"),
}
}
assert!(folded(&planar(Projector { scale: [1.7; 3], backface, ..Projector::default() })).is_some(), "an even scale still folds");
}
#[test]
fn a_placement_read_and_written_back_lands_the_same_and_its_fields_move_the_frame() {
let projector = Projector { rotation: [10.0, 0.0, -30.0], scale: [1.2, 0.9, 1.3], ..Projector::default() };
for proj in [planar(Projector::default()), warp(Projector::default()), planar(projector), warp(projector)] {
let place = placement(&proj, BOUNDS).unwrap();
let back = placed(&proj, &place, BOUNDS).unwrap();
close(&samples(&folded(&proj).unwrap()), &samples(&back));
let again = placement(&back, BOUNDS).unwrap();
for (a, b) in place.offset.iter().chain(&place.rotation).chain(&place.scale).zip(again.offset.iter().chain(&again.rotation).chain(&again.scale)) {
assert!((a - b).abs() < 1e-3, "{place:?} vs {again:?}");
}
let width = folded(&proj).unwrap().frame().unwrap().size[0];
let bigger = placed(&proj, &FramePlacement { scale: [place.scale[0] * 2.0, place.scale[1], place.scale[2]], ..place }, BOUNDS).unwrap();
assert!((bigger.frame().unwrap().size[0] - width * 2.0).abs() < 1e-4, "Scale X doubles the width");
let moved = placed(&proj, &FramePlacement { offset: [0.0; 3], ..place }, BOUNDS).unwrap();
assert!((Vec3::from(moved.frame().unwrap().center) - Vec3::new(1.0, -0.5, 0.5)).length() < 1e-4, "offset 0 = the mesh's centre");
}
let place = placement(&planar(Projector::default()), BOUNDS).unwrap();
assert_eq!(placed(&planar(Projector::default()), &FramePlacement { scale: [0.0, 1.0, 1.0], ..place }, BOUNDS), None, "no zero size");
assert_eq!(placed(&planar(Projector::default()), &FramePlacement { rotation: [f32::NAN; 3], ..place }, BOUNDS), None);
assert_eq!(placement(&Projection::default(), BOUNDS), None);
}
#[test]
fn a_frames_upright_turn_is_its_turn_round_its_normal() {
let mut flat = Decal { normal: [0.0, 0.0, 1.0], up: [0.0, 1.0, 0.0], rotation: 30.0, offset: [0.0; 2], ..frame() };
assert!((upright_turn(&flat).unwrap() - 30.0).abs() < 1e-3);
flat.rotation = -100.0;
assert!((upright_turn(&flat).unwrap() + 100.0).abs() < 1e-3);
let top = Decal { normal: [0.0, 1.0, 0.0], up: [0.0, 0.0, -1.0], rotation: 0.0, ..frame() };
assert!(upright_turn(&top).unwrap().abs() < 1e-3, "seen from above the far side is up");
}
#[test]
fn folding_and_placing_keep_a_frames_mirror_copy_and_image_flip() {
let symmetry = Some(DecalSymmetry { axis: 0, flip: DecalFlip::V, offset: 0.2 });
let mirrored = Decal { symmetry, flip: [true, false], ..frame() };
let turned = Projector { rotation: [10.0, 0.0, -30.0], scale: [1.2, 0.9, 1.3], ..Projector::default() };
for proj in [
Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv: UvTransform::default(), projector: turned, placed: Some(mirrored) },
Projection::Warp {
frame: mirrored,
corners: [[-0.6, 0.5], [0.5, 0.4], [0.5, -0.5], [-0.4, -0.5]],
depth: 0.7,
uv: UvTransform::default(),
projector: turned,
},
] {
let folded = folded(&proj).unwrap();
let moved = placed(&proj, &placement(&proj, BOUNDS).unwrap(), BOUNDS).unwrap();
for frame in [folded.frame().unwrap(), moved.frame().unwrap()] {
assert_eq!((frame.symmetry, frame.flip), (symmetry, [true, false]));
}
}
}
}
+52
View File
@@ -0,0 +1,52 @@
//! The precomputed maps one generator reads: its curvature detail sizes and its micro details
use std::sync::Arc;
use texturecraft_core::{BakedMap, Generator, KindControls, MicroDetails};
use crate::curvature_sizes::CurvatureSizes;
use crate::dripping_rust::rust_field;
use crate::eval::Inputs;
use crate::micro_detail::{AnchorHeights, LayoutMap, MicroCurvature, micro_occlusion};
use crate::uv_border_distance::border_gradient;
use crate::uv_islands::{checker_field, random_color_field};
/// What a generator reads beyond its texel: built once per map and settings, shared by every tile
#[derive(Clone, Default)]
pub(crate) struct GeneratorMaps {
/// The curvature detail sizes it reads (of its micro curvature when it has some)
pub sizes: Option<Arc<CurvatureSizes>>,
/// The curvature its micro details add
pub micro_curvature: Option<Arc<MicroCurvature>>,
/// What its micro details multiply its occlusion by
pub micro_occlusion: Option<Arc<LayoutMap>>,
/// The whole-map field of UV Border Distance, Dripping Rust, UV Random Color or UV Checker at every working texel
pub field: Option<Arc<Vec<f32>>>,
/// The controls of a kind with only its own controls, brought into range
pub controls: Option<Arc<KindControls>>,
}
impl GeneratorMaps {
/// The maps `generator` reads, with the detail sizes `needed` marks (one flag per blurred size); `geometry` fingerprints sampled layout and mesh inputs for whole-map fields
pub fn of(inp: &Inputs, generator: &Generator, needed: &[bool], anchor: Option<Arc<AnchorHeights>>, geometry: impl FnOnce() -> u64) -> GeneratorMaps {
let micro = generator.micro_in_use().map(|micro| micro.clone().clamped(generator.kind));
let micro_curvature = micro
.as_ref()
.filter(|_| MicroDetails::has_curvature(generator.kind))
.and_then(|micro| MicroCurvature::of(inp, generator.kind, micro, anchor.clone()));
let micro_occlusion = micro.as_ref().filter(|_| MicroDetails::has_occlusion(generator.kind)).and_then(|micro| micro_occlusion(inp, micro, anchor));
let sizes = match &micro_curvature {
Some(micro) => CurvatureSizes::of_map(inp, &micro.curvature, needed),
None => inp.baked.maps.get(&BakedMap::Curvature).and_then(|curvature| CurvatureSizes::of_map(inp, curvature, needed)),
};
let controls = generator.kind_controls();
let field = match &controls {
Some(KindControls::BorderDistance(border)) => Some(border_gradient(inp, geometry(), border)),
Some(KindControls::DrippingRust(rust)) => Some(rust_field(inp, geometry(), rust, generator.seed)),
Some(KindControls::UvRandomColor(random)) => Some(random_color_field(inp, geometry(), random, generator.seed)),
Some(KindControls::UvChecker(checker)) => Some(checker_field(inp, geometry(), checker, generator.seed)),
_ => None,
};
GeneratorMaps { sizes, micro_curvature, micro_occlusion, field, controls: controls.map(Arc::new) }
}
}
+37
View File
@@ -0,0 +1,37 @@
use texturecraft_core::{GeneratorKind, ProceduralKind};
/// The pattern that breaks a wear kind up, its repeats across the UV square (or the mesh, triplanar) per unit of grunge scale, its rotation in degrees, and its mean and spread over the UV square (measured by `grunge_is_normalised`)
pub(crate) struct GrungePattern {
pub(crate) kind: ProceduralKind,
pub(crate) repeats_per_scale: f32,
pub(crate) rotation: f32,
/// A seeded pattern and its repeats per unit of grunge scale that varies the pattern's strength, for patterns the seed doesn't change
pub(crate) breakup: Option<(ProceduralKind, f32)>,
pub(crate) mean: f32,
pub(crate) spread: f32,
/// How strongly a custom grunge's gray away from mid gray counts, in units of the normalised grunge (Dirt reads a brighter custom grunge as cleaner)
pub(crate) custom_gain: f32,
}
/// Fine scratches on metal edges, a woven fibre on fibreglass, blotchy grime for dirt
pub(crate) const EDGE_WEAR_GRUNGE: GrungePattern =
GrungePattern { kind: ProceduralKind::Scratches, repeats_per_scale: 4.0, rotation: 0.0, breakup: None, mean: 0.037, spread: 0.149, custom_gain: 6.22 };
pub(crate) const FIBER_GLASS_GRUNGE: GrungePattern = GrungePattern {
kind: ProceduralKind::Weave,
repeats_per_scale: 16.0,
rotation: 45.0,
breakup: Some((ProceduralKind::Grunge, 4.0)),
mean: 0.539,
spread: 0.198,
custom_gain: 1.9,
};
pub(crate) const DIRT_GRUNGE: GrungePattern =
GrungePattern { kind: ProceduralKind::Grunge, repeats_per_scale: 4.0, rotation: 0.0, breakup: None, mean: 0.682, spread: 0.242, custom_gain: -5.56 };
pub(crate) fn grunge_pattern(kind: GeneratorKind) -> &'static GrungePattern {
match kind {
GeneratorKind::Dirt => &DIRT_GRUNGE,
GeneratorKind::FiberGlassEdgeWear => &FIBER_GLASS_GRUNGE,
_ => &EDGE_WEAR_GRUNGE,
}
}
+51
View File
@@ -0,0 +1,51 @@
//! The histogram scan several generators finish with: a ramp slid through the values and narrowed by a contrast
/// `value` scanned at `position` (0 all black, 1 all white) over a ramp `1 − contrast` wide; contrast 1 is a hard step
pub(crate) fn histogram_scan(value: f32, position: f32, contrast: f32) -> f32 {
// The ends hold at a hard step too, where the ramp has no width to reach them
if position <= 0.0 {
return 0.0;
}
if position >= 1.0 {
return 1.0;
}
let width = 1.0 - contrast.clamp(0.0, 1.0);
// The ramp's low end runs from 1 towards position 0 to −width towards position 1
let low = (1.0 - position) * (1.0 + width) - width;
if width <= f32::EPSILON {
return if value >= low { 1.0 } else { 0.0 };
}
((value - low) / width).clamp(0.0, 1.0)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_ends_of_the_position_are_all_black_and_all_white() {
for value in [0.0, 0.3, 1.0] {
assert_eq!(histogram_scan(value, 0.0, 0.5), 0.0, "{value}");
assert_eq!(histogram_scan(value, 1.0, 0.5), 1.0, "{value}");
}
}
#[test]
fn the_ends_of_the_position_hold_at_a_hard_step() {
assert_eq!(histogram_scan(1.0, 0.0, 1.0), 0.0, "position 0 is all black, even for white");
assert_eq!(histogram_scan(0.0, 1.0, 1.0), 1.0, "position 1 is all white, even for black");
}
#[test]
fn the_middle_position_keeps_mid_gray_and_contrast_narrows_around_it() {
assert!((histogram_scan(0.5, 0.5, 0.5) - 0.5).abs() < 1e-6);
assert!((histogram_scan(0.5, 0.5, 0.0) - 0.5).abs() < 1e-6);
assert!((histogram_scan(0.7, 0.5, 0.5) - 0.9).abs() < 1e-6, "a ramp half wide from 0.25");
assert!(histogram_scan(0.6, 0.5, 0.9) > histogram_scan(0.6, 0.5, 0.5));
assert_eq!(histogram_scan(0.51, 0.5, 1.0), 1.0);
assert_eq!(histogram_scan(0.49, 0.5, 1.0), 0.0);
}
}
+47 -2
View File
@@ -7,33 +7,78 @@
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
pub mod axis_frame;
mod baked_maps;
pub mod below;
mod curvature_size_level;
pub mod curvature_sizes;
pub mod display;
mod distance_envelope;
mod dripping_rust;
mod effect_histogram;
pub mod environment_sh;
pub mod environment_sky;
pub mod eval;
mod fabric;
mod field_cache;
mod field_cache_key;
pub mod fill_copies;
pub mod fill_copy;
mod fill_depth;
mod fill_place;
pub mod frame_placement;
mod fur_lock;
mod generator_maps;
mod grunge_pattern;
mod held_fields;
mod histogram_scan;
mod image_identity;
mod mask_gray;
mod micro_detail;
pub mod mip_level;
mod organic;
pub mod pattern;
mod pattern_context;
pub mod projector_cover;
pub mod projector_depth;
mod projector_depth_cache;
pub mod projector_view;
mod sampled_map;
mod sections;
mod shape_distance;
mod slope_texel;
mod slot_placement;
mod soft_box;
pub mod solo;
pub mod store;
mod texture_layer;
mod three_d_distance;
pub mod thumb;
pub mod tile_length;
mod tile_pattern;
mod tile_random_stream;
mod timber;
mod uv_border_distance;
mod uv_islands;
pub mod warp;
mod warp_source_sample;
mod warp_texel;
mod wear;
mod wear_inputs;
mod wear_scan;
mod working_field;
pub use below::{BelowCache, StackKey};
pub use display::{DisplayKind, kinds_for, tile_bytes};
pub use effect_histogram::EffectHistogram;
pub use eval::{
BLOCK, Composite, Inputs, MASK_CHANNEL, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, covered_tiles,
effect_histogram, flatten_layer, mask_at, mask_image, mask_texels, mask_values, pad_tiles, stack_reads_neighbours,
BLOCK, Composite, Inputs, MASK_CHANNEL, PaintTarget, Stencil, StrokePreview, all_tiles, compare_histograms, composite_tiles, composite_tiles_cached,
composite_tiles_with_projectors, covered_tiles, effect_histogram, flatten_layer, mask_at, mask_image, mask_texels, mask_values, pad_tiles,
stack_reads_neighbours,
};
pub use mask_gray::MaskGray;
pub use pattern_context::PatternContext;
pub use projector_depth_cache::ProjectorDepthCache;
pub use solo::solo_project;
pub use store::{BakedMaps, ImageRes, ImageStore, PixelStore};
pub use thumb::{THUMB_TEXELS, ThumbImage, ThumbTarget};
+62
View File
@@ -0,0 +1,62 @@
//! The gray a mask stroke paints
use std::sync::Arc;
use texturecraft_core::{Filtering, Sampling, UvWrap, lum};
use crate::ImageRes;
/// The gray a mask stroke paints: one value, or the gray of an image laid once over the texture by its UVs
#[derive(Clone, Debug, PartialEq)]
pub enum MaskGray {
Value(f32),
/// Image resource `name`, read as its gray like a mask fill reads an image
Image {
name: String,
image: Arc<ImageRes>,
},
}
impl MaskGray {
/// The gray painted at texel (`x`, `y`) of a `width` × `height` texture (the image read at the texel's centre)
pub fn at(&self, x: u32, y: u32, (width, height): (u32, u32)) -> f32 {
match self {
MaskGray::Value(value) => value.clamp(0.0, 1.0),
MaskGray::Image { image, .. } => {
let u = (x as f32 + 0.5) / width.max(1) as f32;
let v = (y as f32 + 0.5) / height.max(1) as f32;
let sampling = Sampling { filtering: Filtering::BilinearSharp, wrap: UvWrap::None, ..Sampling::SAVED_BEFORE };
let [r, g, b, _] = image.sample_filtered(u, v, sampling, 1.0);
lum([r, g, b]).clamp(0.0, 1.0)
}
}
}
/// The image resource painted, None for one value
pub fn image_name(&self) -> Option<&str> {
match self {
MaskGray::Value(_) => None,
MaskGray::Image { name, .. } => Some(name),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_mask_image_does_not_wrap_at_texture_edges() {
let black = [0.0, 0.0, 0.0, 1.0];
let white = [1.0; 4];
let image = Arc::new(ImageRes::new(2, 2, vec![black, white, white, white], false));
let brush = MaskGray::Image { name: "brush.png".to_owned(), image };
let near_corner = brush.at(0, 0, (4, 4));
let inside = brush.at(1, 1, (4, 4));
let far_corner = brush.at(3, 3, (4, 4));
assert!(near_corner < 0.01, "opposite edges must leave the black corner black, got {near_corner}");
assert!(near_corner < inside && inside < far_corner, "sampling between image texels stays bilinear");
}
}
@@ -0,0 +1,15 @@
use std::sync::{Arc, Weak};
use texturecraft_core::LayerId;
use super::anchor_heights::AnchorHeights;
use crate::below::StackKey;
/// The anchor heights built for a texture set's stack: the mesh maps they were built beside, the set, the anchor and the stack's key
pub(super) struct AnchorEntry {
pub(super) baked: Weak<Vec<f32>>,
pub(super) texture_set: usize,
pub(super) anchor: (LayerId, usize),
pub(super) stack: Arc<StackKey>,
pub(super) heights: Arc<AnchorHeights>,
}
@@ -0,0 +1,66 @@
use std::sync::{Arc, Mutex, PoisonError, Weak};
use texturecraft_core::{BakedMap, LayerId};
use super::{AnchorHeights, CACHE_BYTES, anchor_entry::AnchorEntry};
use crate::below::StackKey;
use crate::eval::Inputs;
/// Committed anchor heights reused by a session between composites
#[derive(Default)]
pub(crate) struct AnchorHeightCache {
entries: Mutex<Vec<AnchorEntry>>,
}
impl AnchorHeightCache {
pub(crate) fn retain_readers(&self, texture_set: usize, anchors: &[(LayerId, usize)]) {
self.entries
.lock()
.unwrap_or_else(PoisonError::into_inner)
.retain(|entry| entry.baked.strong_count() > 0 && (entry.texture_set != texture_set || anchors.contains(&entry.anchor)));
}
pub(crate) fn get_or_build(
&self,
inputs: &Inputs,
anchor: (LayerId, usize),
stack: &Arc<StackKey>,
build: impl FnOnce() -> AnchorHeights,
) -> Arc<AnchorHeights> {
let baked = [BakedMap::Curvature, BakedMap::AmbientOcclusion].iter().find_map(|map| inputs.baked.maps.get(map)).map(Arc::downgrade);
let Some(baked) = baked else { return Arc::new(build()) };
let same_anchor = |entry: &AnchorEntry| entry.texture_set == inputs.ts && entry.anchor == anchor;
let layout = (inputs.gbuf.width, inputs.gbuf.height);
{
let mut entries = self.entries.lock().unwrap_or_else(PoisonError::into_inner);
if let Some(index) = entries.iter().position(|entry| {
same_anchor(entry) && Weak::ptr_eq(&entry.baked, &baked) && &entry.stack == stack && entry.heights.matches_layout(layout, &inputs.block_scales)
}) {
let entry = entries.remove(index);
let heights = entry.heights.clone();
entries.push(entry);
return heights;
}
}
// Height construction plans and evaluates the stack in parallel
let heights = Arc::new(build());
let mut entries = self.entries.lock().unwrap_or_else(PoisonError::into_inner);
entries.retain(|entry| !same_anchor(entry));
entries.push(AnchorEntry { baked, texture_set: inputs.ts, anchor, stack: stack.clone(), heights: heights.clone() });
let mut bytes = 0usize;
let kept = entries
.iter()
.rev()
.take_while(|entry| {
bytes = bytes.saturating_add(entry.heights.bytes());
bytes <= CACHE_BYTES
})
.count();
let excess = entries.len() - kept;
entries.drain(..excess);
heights
}
}
@@ -0,0 +1,32 @@
use texturecraft_core::BlockScales;
/// An anchor point's height over the whole texture set, in the working atlas's layout
pub struct AnchorHeights {
data: Vec<f32>,
working_size: (u32, u32),
scales: BlockScales,
}
impl AnchorHeights {
pub fn new(data: Vec<f32>, working_size: (u32, u32), scales: BlockScales) -> AnchorHeights {
AnchorHeights { data, working_size, scales }
}
pub(super) fn matches_layout(&self, size: (u32, u32), scales: &BlockScales) -> bool {
self.working_size == size && &self.scales == scales
}
pub(super) fn bytes(&self) -> usize {
self.data.len().saturating_mul(size_of::<f32>())
}
/// The height under texel (`x`, `y`) of a `layout` sized mesh map (0 outside the working atlas)
pub(super) fn at(&self, (x, y): (u32, u32), layout: (u32, u32)) -> f32 {
let baked_uv = [(x as f32 + 0.5) / layout.0.max(1) as f32, (y as f32 + 0.5) / layout.1.max(1) as f32];
let Some(uv) = self.scales.working_uv(baked_uv, self.working_size) else { return 0.0 };
let column = ((uv[0] * self.working_size.0 as f32) as u32).min(self.working_size.0.saturating_sub(1));
let row = ((uv[1] * self.working_size.1 as f32) as u32).min(self.working_size.1.saturating_sub(1));
self.data.get((row * self.working_size.0 + column) as usize).copied().unwrap_or(0.0)
}
}
@@ -0,0 +1,26 @@
use std::sync::Weak;
use super::slot_key::SlotKey;
/// What a micro map was built from: the mesh map giving its layout, its slots, its settings, atlas dimensions and UV tile block
#[derive(Clone)]
pub(super) struct CacheKey {
pub(super) map: Weak<Vec<f32>>,
pub(super) height: Option<SlotKey>,
pub(super) normal: Option<SlotKey>,
pub(super) settings: Vec<u32>,
pub(super) size: (u32, u32),
pub(super) block: (u32, u32),
}
impl PartialEq for CacheKey {
fn eq(&self, other: &CacheKey) -> bool {
self.map.strong_count() > 0
&& self.map.ptr_eq(&other.map)
&& self.height == other.height
&& self.normal == other.normal
&& self.settings == other.settings
&& self.size == other.size
&& self.block == other.block
}
}
@@ -0,0 +1,4 @@
/// What a cached map holds, to keep the cache within [`CACHE_BYTES`](super::CACHE_BYTES)
pub(super) trait CachedBytes {
fn bytes(&self) -> usize;
}
@@ -0,0 +1,26 @@
use texturecraft_core::BlockScales;
use super::cached_bytes::CachedBytes;
/// A map in a mesh map's layout: `size` texels, each UV tile one block
pub struct LayoutMap {
pub(super) data: Vec<f32>,
pub(super) size: (u32, u32),
}
impl LayoutMap {
/// The value under working texel (`x`, `y`) of a `working_size` atlas laid out by `scales` (None outside the layout)
pub fn at(&self, (x, y): (u32, u32), working_size: (u32, u32), scales: &BlockScales) -> Option<f32> {
let uv = [(x as f32 + 0.5) / working_size.0.max(1) as f32, (y as f32 + 0.5) / working_size.1.max(1) as f32];
let baked_uv = scales.bake_uv(uv, working_size)?;
let column = ((baked_uv[0] * self.size.0 as f32) as u32).min(self.size.0.saturating_sub(1));
let row = ((baked_uv[1] * self.size.1 as f32) as u32).min(self.size.1.saturating_sub(1));
self.data.get((row * self.size.0 + column) as usize).copied()
}
}
impl CachedBytes for LayoutMap {
fn bytes(&self) -> usize {
self.data.len().saturating_mul(size_of::<f32>())
}
}
@@ -0,0 +1,51 @@
use std::sync::{Arc, Mutex};
use super::cache_key::CacheKey;
use super::cached_bytes::CachedBytes;
use super::{CACHE_BYTES, CACHE_ENTRIES};
/// Built maps by what they were built from, most recently used last
pub(super) struct MicroCache<T> {
entries: Mutex<Vec<(CacheKey, Arc<T>)>>,
}
impl<T: CachedBytes> MicroCache<T> {
pub(super) const fn new() -> MicroCache<T> {
MicroCache { entries: Mutex::new(Vec::new()) }
}
/// The map built from `key`, built by `build` when missing (outside the lock: the build runs parallel work)
pub(super) fn get_or_build(&self, key: CacheKey, build: impl FnOnce() -> T) -> Arc<T> {
let found = {
let mut entries = self.entries.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
entries.retain(|(key, _)| key.map.strong_count() > 0);
entries.iter().position(|(cached, _)| *cached == key).map(|index| {
let entry = entries.remove(index);
let built = entry.1.clone();
entries.push(entry);
built
})
};
if let Some(built) = found {
return built;
}
let built = Arc::new(build());
let mut entries = self.entries.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
entries.retain(|(cached, _)| *cached != key);
entries.push((key, built.clone()));
let mut bytes = 0usize;
let keep = entries
.iter()
.rev()
.take_while(|(_, built)| {
bytes = bytes.saturating_add(built.bytes());
bytes <= CACHE_BYTES
})
.count()
.clamp(1, CACHE_ENTRIES);
let excess = entries.len().saturating_sub(keep);
entries.drain(..excess);
built
}
}
@@ -0,0 +1,48 @@
use std::sync::Arc;
use rayon::prelude::*;
use texturecraft_core::{BakedMap, GeneratorKind, MicroDetails};
use super::cache_key::CacheKey;
use super::cached_bytes::CachedBytes;
use super::layout_map::LayoutMap;
use super::slot::Slot;
use super::{AnchorHeights, CURVATURE_CACHE, by_blocks, curvature_term, layout};
use crate::eval::Inputs;
/// The curvature a generator's micro details add
pub struct MicroCurvature {
/// What they add to the curvature input
pub term: LayoutMap,
/// The baked curvature with the term added, which the detail sizes blur
pub curvature: Arc<Vec<f32>>,
}
impl MicroCurvature {
/// The curvature `micro` adds on a `kind` generator, in the baked curvature map's layout (None without a baked curvature map)
pub fn of(inp: &Inputs, kind: GeneratorKind, micro: &MicroDetails, anchor: Option<Arc<AnchorHeights>>) -> Option<Arc<MicroCurvature>> {
let (curvature, size, block) = layout(inp, BakedMap::Curvature)?;
let height = micro.height.then(|| Slot::of(inp, micro.height_source.as_ref(), anchor));
let normal = micro.normal.then(|| Slot::of(inp, micro.normal_source.as_ref(), None));
let settings = vec![micro.curvature_type as u32, micro.curvature_intensity.to_bits(), micro.height_intensity.to_bits(), kind as u32];
let key =
CacheKey { map: Arc::downgrade(&curvature), height: height.as_ref().map(Slot::key), normal: normal.as_ref().map(Slot::key), settings, size, block };
Some(CURVATURE_CACHE.get_or_build(key, || {
let same_in_every_block = height.iter().chain(&normal).all(Slot::same_in_every_block);
let term = by_blocks(size, block, same_in_every_block, |origin, block| {
let height = height.as_ref().map(|height| height.in_block(origin, size));
let normal = normal.as_ref().map(|normal| normal.in_block(origin, size));
curvature_term(micro, height.as_ref(), normal.as_ref(), block)
});
let adjusted = curvature.par_iter().zip(term.par_iter()).map(|(curvature, term)| curvature + term).collect();
MicroCurvature { term: LayoutMap { data: term, size }, curvature: Arc::new(adjusted) }
}))
}
}
impl CachedBytes for MicroCurvature {
fn bytes(&self) -> usize {
self.term.bytes().saturating_add(self.curvature.len().saturating_mul(size_of::<f32>()))
}
}
+370
View File
@@ -0,0 +1,370 @@
//! A generator's micro details: the curvature and occlusion its micro height (an image or an anchor point's height) and normal image add to its mesh maps, built once per map, image and settings
mod anchor_entry;
mod anchor_height_cache;
mod anchor_heights;
mod cache_key;
mod cached_bytes;
mod layout_map;
mod micro_cache;
mod micro_curvature;
mod slot;
mod slot_key;
use std::sync::Arc;
pub(crate) use anchor_height_cache::AnchorHeightCache;
pub use anchor_heights::AnchorHeights;
use cache_key::CacheKey;
pub use layout_map::LayoutMap;
use micro_cache::MicroCache;
pub use micro_curvature::MicroCurvature;
use rayon::prelude::*;
use slot::Slot;
use texturecraft_core::{BakedMap, MicroCurvatureType, MicroDetails};
use crate::eval::{BLUR_BOX_PASSES, Inputs};
use crate::working_field::REFERENCE_TILE_TEXELS;
/// How steeply the micro height tilts the normal it is turned into, per unit of Height Details Intensity (fitted)
const HEIGHT_NORMAL_STRENGTH: f32 = 5.9;
/// Blur sizes of the Smooth type, in texels at 2K: the height against each of these blurred copies
const SMOOTH_SIGMAS: [f32; 7] = [1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0];
/// Below this sigma a blur is an explicit kernel; wider ones are three box passes
const BOX_BLUR_MIN_SIGMA: f32 = 2.0;
/// How many sigmas the sampled kernel reaches each side
const KERNEL_REACH_SIGMAS: f32 = 3.0;
/// Directions the occlusion looks along
const OCCLUSION_DIRECTIONS: usize = 16;
/// Most steps the occlusion takes along each direction; longer radii step further each time
const OCCLUSION_STEPS: usize = 16;
/// The occlusion radius in texels at 1K for AO Radius 1, and its exponent (fitted: radius 0.3 reaches about 6 texels, 1 about 48)
const OCCLUSION_RADIUS_TEXELS_1K: f32 = 47.675;
const OCCLUSION_RADIUS_POWER: f32 = 1.663;
/// Shorter radii at 1K occlude nothing: the reference is unchanged at AO Radius 0.1 (about 1 texel) and occludes from 0.2 (about 3)
const MIN_OCCLUSION_RADIUS_TEXELS_1K: f32 = 2.0;
/// How steep the micro height reads for occlusion per texel at 1K at AO Depth 1, and its exponent (fitted)
const OCCLUSION_DEPTH_SCALE_1K: f32 = 1473.8;
const OCCLUSION_DEPTH_POWER: f32 = 1.0654;
/// How dark a fully occluding horizon makes the occlusion (fitted)
const OCCLUSION_STRENGTH: f32 = 0.3232;
/// Most micro maps cached, and the bytes they may hold (the newest is kept whatever its size), like the curvature sizes they feed
const CACHE_ENTRIES: usize = 8;
const CACHE_BYTES: usize = 256 << 20;
/// The UV of each texel's center in a `size` block, row by row
fn block_uvs((width, height): (u32, u32)) -> impl Iterator<Item = [f32; 2]> {
(0..height).flat_map(move |y| (0..width).map(move |x| [(x as f32 + 0.5) / width as f32, (y as f32 + 0.5) / height as f32]))
}
static CURVATURE_CACHE: MicroCache<MicroCurvature> = MicroCache::new();
static OCCLUSION_CACHE: MicroCache<LayoutMap> = MicroCache::new();
/// A baked map, its size and the size of one UV tile's block in it
type MapLayout = (Arc<Vec<f32>>, (u32, u32), (u32, u32));
/// The baked `map`'s layout (None when it isn't baked)
fn layout(inp: &Inputs, map: BakedMap) -> Option<MapLayout> {
let data = inp.baked.maps.get(&map)?.clone();
let size = (inp.baked.resolution, inp.baked.height(map));
if size.0 == 0 || size.1 == 0 {
return None;
}
let grid = inp.project.texture_set(inp.ts).ok().and_then(|set| set.tile_grid());
let block = grid.map_or(size, |grid| (size.0 / grid.cols.max(1), size.1 / grid.rows.max(1)));
Some((data, size, (block.0.max(1).min(size.0), block.1.max(1).min(size.1))))
}
/// `per_block` run on each UV tile block of a `size` map, its results placed into one map
fn by_blocks(size: (u32, u32), block: (u32, u32), same_in_every_block: bool, per_block: impl Fn((u32, u32), (u32, u32)) -> Vec<f32> + Sync) -> Vec<f32> {
let blocks: Vec<(u32, u32)> = (0..size.1).step_by(block.1 as usize).flat_map(|y| (0..size.0).step_by(block.0 as usize).map(move |x| (x, y))).collect();
// Every block is a whole UV tile, so one computation serves them all unless the slots differ per block; a clipped last block differs too
let full = same_in_every_block.then(|| per_block((0, 0), block));
let mut data = vec![0.0; (size.0 * size.1) as usize];
for (left, top) in blocks {
let clipped = (block.0.min(size.0 - left), block.1.min(size.1 - top));
let own = if clipped == block && full.is_some() { None } else { Some(per_block((left, top), clipped)) };
let Some(values) = own.as_deref().or(full.as_deref()) else { continue };
for row in 0..clipped.1 {
let source = (row * clipped.0) as usize;
let target = ((top + row) * size.0 + left) as usize;
if let (Some(target), Some(source)) = (data.get_mut(target..target + clipped.0 as usize), values.get(source..source + clipped.0 as usize)) {
target.copy_from_slice(source);
}
}
}
data
}
/// What the occlusion input is multiplied by: the micro height's occlusion in the baked AO map's layout (None without a baked AO map or a micro height)
pub fn micro_occlusion(inp: &Inputs, micro: &MicroDetails, anchor: Option<Arc<AnchorHeights>>) -> Option<Arc<LayoutMap>> {
let (occlusion, size, block) = layout(inp, BakedMap::AmbientOcclusion)?;
let height = Slot::of(inp, micro.height.then_some(micro.height_source.as_ref())?, anchor);
let settings = vec![micro.ao_radius.to_bits(), micro.ao_depth.to_bits()];
let key = CacheKey { map: Arc::downgrade(&occlusion), height: Some(height.key()), normal: None, settings, size, block };
Some(OCCLUSION_CACHE.get_or_build(key, || {
let data = by_blocks(size, block, height.same_in_every_block(), |origin, block| occlusion_factor(micro, &height.in_block(origin, size), block));
LayoutMap { data, size }
}))
}
/// The fitted constants of a curvature type: what it adds everywhere, and its gain on the height and on the normal
fn type_constants(curvature_type: MicroCurvatureType) -> (f32, f32, f32) {
match curvature_type {
MicroCurvatureType::Standard => (0.00876, 12.36, 9.49),
MicroCurvatureType::Sobel => (0.0, 5.72, 4.46),
MicroCurvatureType::Smooth => (-0.00332, 0.969, 34.2),
}
}
/// The curvature the micro details add over one `size` UV tile block
fn curvature_term(micro: &MicroDetails, height: Option<&Slot>, normal: Option<&Slot>, size: (u32, u32)) -> Vec<f32> {
let (offset, height_gain, normal_gain) = type_constants(micro.curvature_type);
let texel_scale = size.0 as f32 / REFERENCE_TILE_TEXELS;
let mut term = vec![offset; (size.0 * size.1) as usize];
if let Some(height) = height {
let heights = height.heights(size);
let detail = match micro.curvature_type {
MicroCurvatureType::Smooth => smooth_detail(&heights, size, texel_scale).into_iter().map(|detail| detail * micro.height_intensity).collect(),
MicroCurvatureType::Standard | MicroCurvatureType::Sobel => {
// The height turned into a normal, then that normal's divergence
let strength = HEIGHT_NORMAL_STRENGTH * micro.height_intensity * texel_scale;
let tilted = |slope_x: f32, slope_y: f32| {
let (x, y) = (-strength * slope_x, -strength * slope_y);
let length = (x * x + y * y + 1.0).sqrt();
(x / length, y / length)
};
let (normal_x, normal_y): (Vec<f32>, Vec<f32>) = sobel_components(&heights, &heights, size).map(|(x, y)| tilted(x, y)).unzip();
divergence(&normal_x, &normal_y, size, texel_scale)
}
};
add_scaled(&mut term, &detail, micro.curvature_intensity * height_gain);
}
if let Some(normal) = normal {
let (normal_x, normal_y) = normal.normals(size);
add_scaled(&mut term, &divergence(&normal_x, &normal_y, size, texel_scale), micro.curvature_intensity * normal_gain);
}
term
}
fn add_scaled(target: &mut [f32], values: &[f32], gain: f32) {
target.par_iter_mut().zip(values.par_iter()).for_each(|(target, value)| *target += value * gain);
}
/// The Smooth type's detail: the height above its blurred copies, averaged over [`SMOOTH_SIGMAS`]
fn smooth_detail(heights: &[f32], size: (u32, u32), texel_scale: f32) -> Vec<f32> {
let mut detail = vec![0.0; heights.len()];
for sigma in SMOOTH_SIGMAS {
let blurred = gaussian_wrapped(heights, size, sigma * texel_scale);
detail.par_iter_mut().zip(heights.par_iter().zip(blurred.par_iter())).for_each(|(detail, (height, blurred))| *detail += height - blurred);
}
let count = SMOOTH_SIGMAS.len() as f32;
detail.par_iter_mut().for_each(|detail| *detail /= count);
detail
}
/// The divergence of the two normal components, per texel at 2K
fn divergence(x: &[f32], y: &[f32], size: (u32, u32), texel_scale: f32) -> Vec<f32> {
sobel_components(x, y, size).map(|(dx, dy)| (dx + dy) * texel_scale).collect()
}
/// Apply the horizontal and vertical Sobel kernels to their respective fields with periodic edges
fn sobel_components<'a>(horizontal: &'a [f32], vertical: &'a [f32], (width, height): (u32, u32)) -> impl IndexedParallelIterator<Item = (f32, f32)> + 'a {
let width = width.max(1) as usize;
let height = height.max(1) as usize;
(0..width * height).into_par_iter().map(move |index| {
let x = index % width;
let y = index / width;
let left = if x == 0 { width - 1 } else { x - 1 };
let right = if x + 1 == width { 0 } else { x + 1 };
let top = if y == 0 { height - 1 } else { y - 1 };
let bottom = if y + 1 == height { 0 } else { y + 1 };
let sample = |field: &[f32], x, y| field.get(y * width + x).copied().unwrap_or(0.0);
let column = |x| sample(horizontal, x, top) + 2.0 * sample(horizontal, x, y) + sample(horizontal, x, bottom);
let row = |y| sample(vertical, left, y) + 2.0 * sample(vertical, x, y) + sample(vertical, right, y);
((column(right) - column(left)) / 8.0, (row(bottom) - row(top)) / 8.0)
})
}
/// `values` blurred to `sigma` texels, wrapping around the block like a tiling image
fn gaussian_wrapped(values: &[f32], (width, height): (u32, u32), sigma: f32) -> Vec<f32> {
let rows = blur_lines(values, width as usize, sigma);
let columns = blur_lines(&transposed(&rows, width as usize, height as usize), height as usize, sigma);
transposed(&columns, height as usize, width as usize)
}
/// Each `length`-long line of `values` blurred to `sigma`, wrapping around
fn blur_lines(values: &[f32], length: usize, sigma: f32) -> Vec<f32> {
let length = length.max(1);
let mut out = vec![0.0; values.len()];
// Every line reads the same sampled kernel
let kernel = (sigma < BOX_BLUR_MIN_SIGMA).then(|| gaussian_kernel(sigma));
out.par_chunks_mut(length).zip(values.par_chunks(length)).for_each(|(out, line)| match &kernel {
Some(kernel) => kernel_blur(line, out, kernel),
None => {
// Three box passes of radius r spread a value with variance r(r + 1)
let radius = (((1.0 + 4.0 * sigma * sigma).sqrt() - 1.0) / 2.0).round().max(1.0) as usize;
let mut current = line.to_vec();
for _ in 0..BLUR_BOX_PASSES {
box_blur(&current, out, radius);
current.copy_from_slice(out);
}
}
});
out
}
/// A gaussian of `sigma` sampled at whole texels each side of its centre, its weights summing to 1
fn gaussian_kernel(sigma: f32) -> Vec<f32> {
let reach = (KERNEL_REACH_SIGMAS * sigma).ceil().max(1.0) as i64;
let weights: Vec<f32> = (-reach..=reach).map(|offset| (-(offset * offset) as f32 / (2.0 * sigma * sigma)).exp()).collect();
let total: f32 = weights.iter().sum();
weights.into_iter().map(|weight| weight / total).collect()
}
/// `line` blurred into `out` by `kernel` (centred, as [`gaussian_kernel`] samples it), wrapping around
fn kernel_blur(line: &[f32], out: &mut [f32], kernel: &[f32]) {
let reach = (kernel.len() / 2) as i64;
let length = line.len().max(1) as i64;
for (index, value) in out.iter_mut().enumerate() {
*value = (-reach..=reach)
.zip(kernel)
.map(|(offset, weight)| line.get((index as i64 + offset).rem_euclid(length) as usize).copied().unwrap_or(0.0) * weight)
.sum();
}
}
/// `line` averaged over `radius` texels each side into `out`, wrapping around
fn box_blur(line: &[f32], out: &mut [f32], radius: usize) {
let length = line.len().max(1) as i64;
let window = (2 * radius + 1) as f32;
let at = |index: i64| line.get(index.rem_euclid(length) as usize).copied().unwrap_or(0.0);
let mut sum: f32 = (-(radius as i64)..=radius as i64).map(at).sum();
for (index, value) in out.iter_mut().enumerate() {
*value = sum / window;
let index = index as i64;
sum += at(index + radius as i64 + 1) - at(index - radius as i64);
}
}
fn transposed(values: &[f32], width: usize, height: usize) -> Vec<f32> {
let height = height.max(1);
(0..width * height).into_par_iter().map(|texel| values.get((texel % height) * width + texel / height).copied().unwrap_or(0.0)).collect()
}
/// What the occlusion is multiplied by over one `size` UV tile block: the horizon the micro height raises above its slope, looked for in [`OCCLUSION_DIRECTIONS`]
fn occlusion_factor(micro: &MicroDetails, height: &Slot, size: (u32, u32)) -> Vec<f32> {
let tile_scale = size.0 as f32 / (REFERENCE_TILE_TEXELS / 2.0);
let radius_1k = OCCLUSION_RADIUS_TEXELS_1K * micro.ao_radius.powf(OCCLUSION_RADIUS_POWER);
let radius = (radius_1k * tile_scale).round() as usize;
let count = (size.0 * size.1) as usize;
if radius_1k < MIN_OCCLUSION_RADIUS_TEXELS_1K || radius < 1 {
return vec![1.0; count];
}
let depth = OCCLUSION_DEPTH_SCALE_1K * micro.ao_depth.powf(OCCLUSION_DEPTH_POWER) * tile_scale;
let heights = height.heights(size);
let (width, rows) = (i64::from(size.0.max(1)), i64::from(size.1.max(1)));
let at = |x: i64, y: i64| heights.get((y.rem_euclid(rows) * width + x.rem_euclid(width)) as usize).copied().unwrap_or(0.0);
// Up to OCCLUSION_STEPS distances spread over the radius
let steps: Vec<f32> = if radius <= OCCLUSION_STEPS {
(1..=radius).map(|step| step as f32).collect()
} else {
(1..=OCCLUSION_STEPS).map(|step| 1.0 + (radius - 1) as f32 * (step - 1) as f32 / (OCCLUSION_STEPS - 1) as f32).collect()
};
let directions: Vec<_> = (0..OCCLUSION_DIRECTIONS)
.map(|index| std::f32::consts::TAU * index as f32 / OCCLUSION_DIRECTIONS as f32)
.map(|angle| (angle.cos(), angle.sin()))
.map(|(dx, dy)| {
let offsets: Vec<_> = steps.iter().map(|&distance| ((dx * distance).round() as i64, (dy * distance).round() as i64, distance)).collect();
(dx, dy, offsets)
})
.collect();
let sine = |slope: f32| slope / (1.0 + slope * slope).sqrt();
(0..width * rows)
.into_par_iter()
.map(|texel| {
let (x, y) = (texel % width, texel / width);
let here = at(x, y);
let gradient = ((at(x + 1, y) - at(x - 1, y)) / 2.0, (at(x, y + 1) - at(x, y - 1)) / 2.0);
let occluded: f32 = directions
.iter()
.map(|(dx, dy, offsets)| {
let horizon = offsets
.iter()
.map(|&(offset_x, offset_y, distance)| (at(x + offset_x, y + offset_y) - here) / distance)
.fold(f32::NEG_INFINITY, f32::max);
let tangent = gradient.0 * dx + gradient.1 * dy;
(sine(horizon * depth) - sine(tangent * depth)).max(0.0)
})
.sum();
1.0 - OCCLUSION_STRENGTH * occluded / OCCLUSION_DIRECTIONS as f32
})
.collect()
}
#[cfg(test)]
mod tests {
use texturecraft_core::GeneratorKind;
use super::*;
#[test]
fn sobel_reads_a_ramp_as_its_slope() {
let size = (8, 8);
let ramp: Vec<f32> = (0..64).map(|texel| (texel % 8) as f32 * 0.1).collect();
let (x, y): (Vec<_>, Vec<_>) = sobel_components(&ramp, &ramp, size).unzip();
assert!((x[3 * 8 + 3] - 0.1).abs() < 1e-5);
assert!(y[3 * 8 + 3].abs() < 1e-5);
}
#[test]
fn wrapped_blurs_keep_the_mean() {
let size = (32, 16);
let values: Vec<f32> = (0..32 * 16).map(|texel| ((texel * 7919) % 13) as f32).collect();
let mean = values.iter().sum::<f32>() / values.len() as f32;
for sigma in [0.5, 1.0, 4.0] {
let blurred = gaussian_wrapped(&values, size, sigma);
assert!((blurred.iter().sum::<f32>() / blurred.len() as f32 - mean).abs() < 1e-3, "sigma {sigma}");
}
}
#[test]
fn a_flat_height_adds_only_the_types_offset() {
let mut micro = MicroDetails::defaults(GeneratorKind::Curvature).unwrap();
let flat = Slot::Uniform([0.4; 3]);
for curvature_type in MicroCurvatureType::ALL {
micro.curvature_type = curvature_type;
let term = curvature_term(&micro, Some(&flat), Some(&Slot::Uniform([0.5, 0.5, 1.0])), (16, 16));
assert!(term.iter().all(|value| (value - type_constants(curvature_type).0).abs() < 1e-6), "{curvature_type:?}");
}
}
#[test]
fn a_flat_height_occludes_nothing() {
let micro = MicroDetails::defaults(GeneratorKind::AmbientOcclusion).unwrap();
let factor = occlusion_factor(&micro, &Slot::Uniform([0.7; 3]), (64, 64));
assert!(factor.iter().all(|value| (value - 1.0).abs() < 1e-6));
}
}
+98
View File
@@ -0,0 +1,98 @@
use std::sync::Arc;
use texturecraft_core::{NormalFormat, Source};
use super::anchor_heights::AnchorHeights;
use super::block_uvs;
use super::slot_key::SlotKey;
use crate::eval::Inputs;
use crate::store::ImageRes;
/// What a micro details slot reads
#[derive(Clone)]
pub(super) enum Slot {
Uniform([f32; 3]),
Image {
image: Arc<ImageRes>,
flip_green: bool,
},
/// An anchor point's height, different in each UV tile block: read from the block at `origin` of a `layout` sized mesh map
Anchor {
heights: Arc<AnchorHeights>,
origin: (u32, u32),
layout: (u32, u32),
},
}
impl Slot {
/// The slot holding `source` (an empty slot, an image not loaded and an anchor not prepared yet read black; procedurals are not read)
pub(super) fn of(inp: &Inputs, source: Option<&Source>, anchor: Option<Arc<AnchorHeights>>) -> Slot {
match source {
Some(Source::Uniform(value)) => Slot::Uniform(*value),
Some(Source::Image { name, normal_format }) => match inp.images.get(name) {
Some(image) => Slot::Image { image: image.clone(), flip_green: *normal_format == NormalFormat::DirectX },
None => Slot::Uniform([0.0; 3]),
},
Some(Source::Anchor { .. }) => match anchor {
Some(heights) => Slot::Anchor { heights, origin: (0, 0), layout: (0, 0) },
None => Slot::Uniform([0.0; 3]),
},
_ => Slot::Uniform([0.0; 3]),
}
}
/// Whether every UV tile block reads the same (an image or a value repeats in each)
pub(super) fn same_in_every_block(&self) -> bool {
!matches!(self, Slot::Anchor { .. })
}
/// The slot read in the block at `origin` of a `layout` sized mesh map
pub(super) fn in_block(&self, origin: (u32, u32), layout: (u32, u32)) -> Slot {
match self {
Slot::Anchor { heights, .. } => Slot::Anchor { heights: heights.clone(), origin, layout },
other => other.clone(),
}
}
pub(super) fn key(&self) -> SlotKey {
match self {
Slot::Uniform(value) => SlotKey::Uniform(value.map(f32::to_bits)),
Slot::Image { image, flip_green } => SlotKey::Image(Arc::downgrade(image), *flip_green),
Slot::Anchor { heights, .. } => SlotKey::Anchor(Arc::downgrade(heights)),
}
}
/// The slot's color at `uv`, in the file's encoding
pub(super) fn color(&self, uv: [f32; 2]) -> [f32; 3] {
match self {
Slot::Uniform(value) => *value,
Slot::Image { image, .. } => {
let [red, green, blue, _] = image.sample(uv[0], uv[1]);
[red, green, blue]
}
Slot::Anchor { .. } => [0.0; 3],
}
}
/// The slot read as a height (its gray) over a `size` block
pub(super) fn heights(&self, size: (u32, u32)) -> Vec<f32> {
match self {
Slot::Anchor { heights, origin, layout } => {
(0..size.1).flat_map(|row| (0..size.0).map(move |column| (origin.0 + column, origin.1 + row))).map(|texel| heights.at(texel, *layout)).collect()
}
_ => block_uvs(size).map(|uv| self.color(uv).iter().sum::<f32>() / 3.0).collect(),
}
}
/// The slot read as a normal over a `size` block: its X and Y, OpenGL convention
pub(super) fn normals(&self, size: (u32, u32)) -> (Vec<f32>, Vec<f32>) {
let flip_green = matches!(self, Slot::Image { flip_green: true, .. });
block_uvs(size)
.map(|uv| {
let [red, green, _] = self.color(uv);
let y = green * 2.0 - 1.0;
(red * 2.0 - 1.0, if flip_green { -y } else { y })
})
.unzip()
}
}
@@ -0,0 +1,23 @@
use std::sync::Weak;
use super::anchor_heights::AnchorHeights;
use crate::store::ImageRes;
/// A slot as a cache key: an image by identity, a value by its bits
#[derive(Clone)]
pub(super) enum SlotKey {
Uniform([u32; 3]),
Image(Weak<ImageRes>, bool),
Anchor(Weak<AnchorHeights>),
}
impl PartialEq for SlotKey {
fn eq(&self, other: &SlotKey) -> bool {
match (self, other) {
(SlotKey::Uniform(a), SlotKey::Uniform(b)) => a == b,
(SlotKey::Image(a, a_flip), SlotKey::Image(b, b_flip)) => a.strong_count() > 0 && a.ptr_eq(b) && a_flip == b_flip,
(SlotKey::Anchor(a), SlotKey::Anchor(b)) => a.strong_count() > 0 && a.ptr_eq(b),
_ => false,
}
}
}
+103
View File
@@ -0,0 +1,103 @@
//! One halved copy of an image resource, read by high-quality bilinear filtering when an image is shrunk
use crate::store::texel_of;
/// One halved copy of an image (box-filtered; see `halve` for its edges)
#[derive(Clone, Debug, PartialEq)]
pub struct MipLevel {
pub width: u32,
pub height: u32,
pub rgba: Vec<[f32; 4]>,
}
/// Share of each of the 2 × 2 texels in a halved texel
const TEXEL_SHARE: f32 = 0.25;
/// A halved interval can overlap at most three source texels on each axis
const AREA_FILTER_ROWS: usize = 3;
impl MipLevel {
/// Downsample the whole image by area, including odd trailing rows and columns.
pub(crate) fn halve(rgba: &[[f32; 4]], width: u32, height: u32) -> MipLevel {
Self::halve_with(rgba, width, height, None::<fn([f32; 4]) -> [f32; 4]>)
}
/// Decode stored texels before averaging the first level of an sRGB color chain.
pub(crate) fn halve_with(rgba: &[[f32; 4]], width: u32, height: u32, decode: Option<impl Fn([f32; 4]) -> [f32; 4] + Copy>) -> MipLevel {
let (w, h) = ((width / 2).max(1), (height / 2).max(1));
let mut halved = Vec::with_capacity(w as usize * h as usize);
if (width <= 1 || width.is_multiple_of(2)) && (height <= 1 || height.is_multiple_of(2)) {
for y in 0..i64::from(h) {
for x in 0..i64::from(w) {
let mut sum = [0.0f32; 4];
for (dx, dy) in [(0, 0), (1, 0), (0, 1), (1, 1)] {
let stored = texel_of(rgba, width, height, x * 2 + dx, y * 2 + dy, (true, true));
let texel = decode.map_or(stored, |decode| decode(stored));
for (total, value) in sum.iter_mut().zip(texel) {
*total += value * TEXEL_SHARE;
}
}
halved.push(sum);
}
}
} else {
let row_stride = u64::from(width.max(1));
let read = |row_start, source_x| {
let index = usize::try_from(row_start + source_x).ok();
index.and_then(|index| rgba.get(index)).copied().unwrap_or_default()
};
let mut decoded_rows = decode.map(|_| std::array::from_fn::<_, AREA_FILTER_ROWS, _>(|_| (u64::MAX, Vec::with_capacity(row_stride as usize))));
for y in 0..h {
let source_rows = source_weights(y, height, h);
if let Some((decode, rows)) = decode.zip(decoded_rows.as_mut()) {
// Keep decoded rows for adjacent output intervals that share their texels
for (source_y, _) in source_rows.clone() {
let (row, texels) = &mut rows[source_y as usize % AREA_FILTER_ROWS];
if *row != source_y {
let row_start = source_y * row_stride;
texels.clear();
texels.extend((0..row_stride).map(|source_x| decode(read(row_start, source_x))));
*row = source_y;
}
}
}
for x in 0..w {
let source_columns = source_weights(x, width, w);
let mut sum = [0.0; 4];
for (source_y, vertical_weight) in source_rows.clone() {
let row_start = source_y * row_stride;
let row = decoded_rows.as_ref().map(|rows| &rows[source_y as usize % AREA_FILTER_ROWS].1);
for (source_x, horizontal_weight) in source_columns.clone() {
let texel = row.map_or_else(|| read(row_start, source_x), |row| row[source_x as usize]);
let weight = vertical_weight * horizontal_weight;
for (total, value) in sum.iter_mut().zip(texel) {
*total += value * weight;
}
}
}
halved.push(sum);
}
}
}
MipLevel { width: w, height: h, rgba: halved }
}
}
/// Source texels intersecting one output interval and their fractional coverage.
fn source_weights(index: u32, source_size: u32, output_size: u32) -> impl Iterator<Item = (u64, f32)> + Clone {
let source = u64::from(source_size.max(1));
let output = u64::from(output_size);
let inverse_source = 1.0 / source as f32;
// Scale both intervals to integer boundaries for exact overlap at either edge
let start = u64::from(index) * source;
let end = start + source;
(start / output..end.div_ceil(output)).map(move |texel| {
let overlap = end.min((texel + 1) * output) - start.max(texel * output);
(texel, overlap as f32 * inverse_source)
})
}
+372 -135
View File
@@ -1,7 +1,7 @@
//! Procedural patterns and projections.
use texturecraft_core::{Decal, DecalFlip, Procedural, ProceduralKind, Projection};
use texturecraft_geom::glam::{Vec2, Vec3};
use texturecraft_core::{Decal, FULL_TURN_DEGREES, Procedural, ProceduralKind, Projection, Projector, UvTransform};
use texturecraft_geom::glam::{EulerRot, Mat3, Vec2, Vec3};
use texturecraft_texel::noise;
use crate::pattern_context::PatternContext;
@@ -380,13 +380,21 @@ const TRIPLANAR_SKIP: f32 = 1.0 / 131_072.0;
/// Normalized triplanar blend weights (YZ, XZ, XY planes) for normal `nrm`; planes too light
/// to change a 0..1 value scaled by `gain` afterwards weigh 0 (see [`TRIPLANAR_SKIP`]).
fn triplanar_weights(nrm: Vec3, sharpness: f32, gain: f32) -> Vec3 {
let weights = sharpen(nrm.abs(), sharpness);
let weights = weights / (weights.x + weights.y + weights.z).max(1e-6);
let weights = normalized_triplanar_weights(nrm, sharpness);
let skip_threshold = TRIPLANAR_SKIP / gain.max(1.0);
let retained = Vec3::select(weights.cmplt(Vec3::splat(skip_threshold)), Vec3::ZERO, weights);
Vec3::select(weights.cmplt(Vec3::splat(skip_threshold)), Vec3::ZERO, weights)
}
// Preserve the blend if thresholding would discard every plane
if retained == Vec3::ZERO { weights } else { retained }
fn normalized_triplanar_weights(normal: Vec3, sharpness: f32) -> Vec3 {
let normal = normal.abs();
let strongest = normal.max_element();
if strongest == 0.0 || !normal.is_finite() {
return Vec3::ZERO;
}
// Keep the strongest weight at one so sharp diagonal blends cannot underflow
let weights = sharpen(normal / strongest, sharpness);
weights / weights.element_sum()
}
fn shape(pattern: &Procedural, value: f32) -> f32 {
@@ -394,6 +402,129 @@ fn shape(pattern: &Procedural, value: f32) -> f32 {
if pattern.invert { 1.0 - adjusted } else { adjusted }
}
/// `point` turned by `rotation` degrees, scaled by `tiling` and moved by `offset`, as UV transformations place it
fn place(point: Vec2, tiling: Vec2, rotation: f32, offset: Vec2) -> Vec2 {
placement(tiling, rotation, offset)(point)
}
/// [`place`] with its turn's sine and cosine worked out once, for a projection that places several points
pub(crate) fn placement(tiling: Vec2, rotation: f32, offset: Vec2) -> impl Fn(Vec2) -> Vec2 {
let (sin, cos) = rotation.to_radians().sin_cos();
move |point| Vec2::new(point.x * cos - point.y * sin, point.x * sin + point.y * cos) * tiling + offset
}
/// `point` placed as a 3D projection's UV transformation `uv` lays its image
fn place_uv(point: Vec2, uv: &UvTransform) -> Vec2 {
uv_placement(uv)(point)
}
/// [`place_uv`] worked out once for every point a projection places
fn uv_placement(uv: &UvTransform) -> impl Fn(Vec2) -> Vec2 {
placement(Vec2::from(uv.tiling), uv.rotation, Vec2::from(uv.offset))
}
/// 0..1 around a cylindrical projection's axis (`depth` over `across`), over an arc of `angle` degrees centred on the front
fn around(across: f32, depth: f32, angle: f32) -> f32 {
let turn = depth.atan2(across) / std::f32::consts::TAU + 0.5;
// A full turn reads the turn untouched, as projects saved before the angle existed did, bit for bit
if angle == FULL_TURN_DEGREES { turn } else { (turn - 0.5) * FULL_TURN_DEGREES / angle.max(MIN_CYLINDER_ANGLE) + 0.5 }
}
/// Narrowest arc in degrees a cylindrical projection wraps its image round, so a zero angle never divides by zero
pub const MIN_CYLINDER_ANGLE: f32 = *Projection::CYLINDER_ANGLE_RANGE.start();
/// How many pattern tiles a procedural lays round and down a spherical projection, so its cells stay near square
const SPHERE_PATTERN_TILES: Vec2 = Vec2::new(4.0, 2.0);
/// How many pattern tiles a procedural lays round a cylindrical projection's axis
const CYLINDER_PATTERN_TILES: f32 = 4.0;
/// Smallest frame side or depth (world units), so a flat frame never divides by zero
const MIN_FRAME_EXTENT: f32 = 1e-6;
/// Where `coords` lies round a spherical projection: 0..1 round its pole axis and down from its top
fn spherical_uv(projector: &Projector, offset: &[f32; 3], coords: &Coords) -> Vec2 {
let direction = (projector_local(projector, coords).pos + Vec3::from(*offset)).try_normalize().unwrap_or(Vec3::Y);
let u = direction.z.atan2(direction.x) / std::f32::consts::TAU + 0.5;
let v = direction.y.clamp(-1.0, 1.0).acos() / std::f32::consts::PI;
Vec2::new(u, v)
}
/// The axis index (0 X, 1 Y, 2 Z) a cylindrical projection's stored `axis` wraps round: any value but X or Z reads as Y
pub fn cylinder_axis_index(axis: u8) -> usize {
match axis {
0 => 0,
2 => 2,
_ => 1,
}
}
/// Where `coords` lies for a cylindrical projection round `axis`: 0..1 round the axis over `angle` degrees, and its height along the axis
fn cylinder_coords(axis: u8, projector: &Projector, offset: &[f32; 3], angle: f32, coords: &Coords) -> (f32, f32) {
let point = projector_local(projector, coords).pos + Vec3::from(*offset);
let (across, height, depth) = match cylinder_axis_index(axis) {
0 => (point.y, point.x, point.z),
2 => (point.x, point.z, point.y),
_ => (point.x, point.y, point.z),
};
(around(across, depth, angle), height)
}
/// Smallest mesh radius projections measure in, so a flat or empty mesh never divides by zero
const MIN_MESH_RADIUS: f32 = 1e-4;
/// Nearest to zero a projection scale or stretch gets, so it never divides by zero
const MIN_STRETCH: f32 = 1e-6;
/// The mesh's centre and its radius (half the diagonal) from its bounds
pub fn mesh_frame((lo, hi): (Vec3, Vec3)) -> (Vec3, f32) {
((lo + hi) * 0.5, ((hi - lo).length() * 0.5).max(MIN_MESH_RADIUS))
}
/// `value` kept at least [`MIN_STRETCH`] from zero, on its own side
pub fn nonzero_stretch(value: f32) -> f32 {
value.signum() * value.abs().max(MIN_STRETCH)
}
/// A projector's per-axis scale with no axis at zero, each keeping its sign
pub fn projector_stretch(projector: &Projector) -> Vec3 {
Vec3::from(projector.scale).map(nonzero_stretch)
}
/// The middle of a frame's 0..1 texture coordinates: a frame's image turns round it
pub const FRAME_UV_CENTER: Vec2 = Vec2::splat(0.5);
/// `point` (0..1 across and down a frame) placed as `uv` lays a frame's image: turned round the frame's centre, then tiled and moved from its top left
pub fn place_frame_uv(point: Vec2, uv: &UvTransform) -> Vec2 {
// An unplaced image reads `point` itself, bit for bit as decals saved before image placement did
if *uv == UvTransform::default() {
return point;
}
let tiling = Vec2::from(uv.tiling);
place(point - FRAME_UV_CENTER, tiling, uv.rotation, Vec2::from(uv.offset)) + FRAME_UV_CENTER * tiling
}
/// The image placement a frame needs to lay images exactly as `uv` does from the top left (a frame turns its image round its centre)
pub fn frame_uv_from_corner(uv: &UvTransform) -> UvTransform {
let offset = place_uv(FRAME_UV_CENTER, uv) - FRAME_UV_CENTER * Vec2::from(uv.tiling);
UvTransform { offset: offset.to_array(), ..*uv }
}
/// `coords` inside a projector turned and scaled by `projector`; the default projector returns `coords` unchanged
pub fn projector_local(projector: &Projector, coords: &Coords) -> Coords {
if !projector.turns() {
return *coords;
}
let [x, y, z] = projector.rotation.map(f32::to_radians);
let to_local = Mat3::from_euler(EulerRot::ZYX, z, y, x).transpose();
let scale = projector_stretch(projector);
let nrm = (to_local * coords.nrm * scale).try_normalize().unwrap_or(coords.nrm);
Coords { pos: to_local * coords.pos / scale, nrm, ..*coords }
}
/// Evaluate a procedural through a projection, at full resolution and without images
pub fn procedural(pattern: &Procedural, projection: &Projection, coords: &Coords) -> f32 {
procedural_in(pattern, projection, coords, &PatternContext::default())
@@ -402,51 +533,42 @@ pub fn procedural(pattern: &Procedural, projection: &Projection, coords: &Coords
/// Evaluate a procedural through a projection with what `context` gives it: its resolution and the images it reads
pub fn procedural_in(pattern: &Procedural, projection: &Projection, coords: &Coords, context: &PatternContext) -> f32 {
let pattern_scale = pattern.scale.max(MIN_PATTERN_SCALE);
let sample = |point: Vec3| plane_value(pattern, point, context);
let value = match projection {
Projection::Uv { scale, rotation, offset } => {
let (sn, cs) = rotation.to_radians().sin_cos();
let uv = Vec2::new(coords.uv.x * cs - coords.uv.y * sn, coords.uv.x * sn + coords.uv.y * cs) * Vec2::from(*scale) + Vec2::from(*offset);
// Evaluate two-dimensional patterns on a slice of the volume
sample((uv * pattern_scale).extend(0.0))
}
Projection::Triplanar { scale, sharpness, offset } => {
let p = coords.pos * *scale * pattern_scale + Vec3::from(*offset);
// Evaluate two-dimensional patterns on a slice of the volume
let flat = |point: Vec2| plane_value(pattern, point.extend(0.0), context);
let value = match projection {
Projection::UvTile => flat((coords.uv - coords.uv.floor()) * pattern_scale),
Projection::Uv { scale, rotation, offset } => flat(place(coords.uv, Vec2::from(*scale), *rotation, Vec2::from(*offset)) * pattern_scale),
Projection::Triplanar { scale, sharpness, offset, uv, projector } => {
let coords = &projector_local(projector, coords);
let point = coords.pos * *scale * pattern_scale + Vec3::from(*offset);
let place_plane = uv_placement(uv);
// Shape scales the blend by the contrast
let w = triplanar_weights(coords.nrm, *sharpness, pattern.contrast);
let planes = [(w.x, Vec3::new(p.z, p.y, 0.0)), (w.y, Vec3::new(p.x, p.z, 0.0)), (w.z, Vec3::new(p.x, p.y, 0.0))];
planes.into_iter().filter(|(w, _)| *w > 0.0).map(|(w, q)| sample(q) * w).sum()
}
Projection::Planar { scale, axis, offset } => {
let p = coords.pos * *scale * pattern_scale + Vec3::from(*offset);
let q = match axis {
0 => Vec3::new(p.z, p.y, 0.0),
1 => Vec3::new(p.x, p.z, 0.0),
_ => Vec3::new(p.x, p.y, 0.0),
};
sample(q)
}
Projection::Spherical { scale } => {
let d = coords.pos.try_normalize().unwrap_or(Vec3::Y);
let u = d.z.atan2(d.x) / std::f32::consts::TAU + 0.5;
let v = d.y.clamp(-1.0, 1.0).acos() / std::f32::consts::PI;
sample(Vec3::new(u * 4.0, v * 2.0, 0.0) * *scale * pattern_scale)
}
Projection::Cylindrical { scale, axis } => {
let p = coords.pos;
let (a, h, b) = match axis {
0 => (p.y, p.x, p.z),
2 => (p.x, p.z, p.y),
_ => (p.x, p.y, p.z),
};
let u = b.atan2(a) / std::f32::consts::TAU + 0.5;
sample(Vec3::new(u * 4.0, h, 0.0) * *scale * pattern_scale)
let weights = triplanar_weights(coords.nrm, *sharpness, pattern.contrast);
let planes = [(weights.x, Vec2::new(point.z, point.y)), (weights.y, Vec2::new(point.x, point.z)), (weights.z, Vec2::new(point.x, point.y))];
planes.into_iter().filter(|(weight, _)| *weight > 0.0).map(|(weight, plane)| flat(place_plane(plane)) * weight).sum()
}
// The decal already supplied coordinates in its local frame
Projection::Decal(_) => sample((coords.uv * pattern_scale).extend(0.0)),
// The coordinates are already in the placed or warped frame (see [`placed_uv`] and [`crate::warp::warp_uv`])
Projection::Planar { uv, placed: Some(_), .. } | Projection::Warp { uv, .. } => flat(place_frame_uv(coords.uv, uv) * pattern_scale),
Projection::Planar { scale, axis, offset, uv, projector, .. } => {
let point = projector_local(projector, coords).pos * *scale * pattern_scale + Vec3::from(*offset);
let plane = match axis {
0 => Vec2::new(point.z, point.y),
1 => Vec2::new(point.x, point.z),
_ => Vec2::new(point.x, point.y),
};
flat(place_uv(plane, uv))
}
Projection::Spherical { scale, uv, offset, projector } => {
let sphere = spherical_uv(projector, offset, coords);
flat(place_uv(sphere * SPHERE_PATTERN_TILES * *scale * pattern_scale, uv))
}
Projection::Cylindrical { scale, axis, uv, offset, projector, angle } => {
let (around_axis, height) = cylinder_coords(*axis, projector, offset, *angle, coords);
flat(place_uv(Vec2::new(around_axis * CYLINDER_PATTERN_TILES, height) * *scale * pattern_scale, uv))
}
};
shape(pattern, value)
@@ -476,7 +598,7 @@ fn plane_value(pattern: &Procedural, point: Vec3, context: &PatternContext) -> f
let base = grid.floor();
let fraction = grid - base;
let at = |dx: f32, dy: f32| pattern_value(pattern, ((base + Vec2::new(dx, dy) + 0.5) / cells).extend(point.z), context);
let at = |across: f32, down: f32| pattern_value(pattern, ((base + Vec2::new(across, down) + 0.5) / cells).extend(point.z), context);
let top_left = at(0.0, 0.0);
let bottom_left = at(0.0, 1.0);
let top = top_left + (at(1.0, 0.0) - top_left) * fraction.x;
@@ -497,45 +619,36 @@ fn pattern_value(pattern: &Procedural, point: Vec3, context: &PatternContext) ->
pub fn image_samples(projection: &Projection, coords: &Coords) -> [(Vec2, f32); 3] {
let one = |uv: Vec2| [(uv, 1.0), (Vec2::ZERO, 0.0), (Vec2::ZERO, 0.0)];
match projection {
Projection::Uv { scale, rotation, offset } => {
let (sn, cs) = rotation.to_radians().sin_cos();
let uv = Vec2::new(coords.uv.x * cs - coords.uv.y * sn, coords.uv.x * sn + coords.uv.y * cs) * Vec2::from(*scale) + Vec2::from(*offset);
one(uv)
}
Projection::Triplanar { scale, sharpness, offset } => {
let p = coords.pos * *scale + Vec3::from(*offset);
Projection::UvTile => one(coords.uv - coords.uv.floor()),
Projection::Uv { scale, rotation, offset } => one(place(coords.uv, Vec2::from(*scale), *rotation, Vec2::from(*offset))),
Projection::Triplanar { scale, sharpness, offset, uv, projector } => {
let coords = &projector_local(projector, coords);
let point = coords.pos * *scale + Vec3::from(*offset);
let place_plane = uv_placement(uv);
// Float images can exceed 1, so even a tiny plane weight can carry visible detail
let weights = coords.nrm.abs().powf(sharpness.max(1.0));
let weights = weights / (weights.x + weights.y + weights.z).max(1e-6);
[(Vec2::new(p.z, -p.y), weights.x), (Vec2::new(p.x, p.z), weights.y), (Vec2::new(p.x, -p.y), weights.z)]
let weights = normalized_triplanar_weights(coords.nrm, *sharpness);
[
(place_plane(Vec2::new(point.z, -point.y)), weights.x),
(place_plane(Vec2::new(point.x, point.z)), weights.y),
(place_plane(Vec2::new(point.x, -point.y)), weights.z),
]
}
Projection::Planar { scale, axis, offset } => {
let p = coords.pos * *scale + Vec3::from(*offset);
let q = match axis {
0 => Vec2::new(p.z, -p.y),
1 => Vec2::new(p.x, p.z),
_ => Vec2::new(p.x, -p.y),
Projection::Planar { uv, placed: Some(_), .. } | Projection::Warp { uv, .. } => one(place_frame_uv(coords.uv, uv)),
Projection::Planar { scale, axis, offset, uv, projector, .. } => {
let point = projector_local(projector, coords).pos * *scale + Vec3::from(*offset);
let plane = match axis {
0 => Vec2::new(point.z, -point.y),
1 => Vec2::new(point.x, point.z),
_ => Vec2::new(point.x, -point.y),
};
one(q * 0.5 + Vec2::splat(0.5))
one(place_uv(plane * 0.5 + Vec2::splat(0.5), uv))
}
Projection::Spherical { scale } => {
let d = coords.pos.try_normalize().unwrap_or(Vec3::Y);
let u = d.z.atan2(d.x) / std::f32::consts::TAU + 0.5;
let v = d.y.clamp(-1.0, 1.0).acos() / std::f32::consts::PI;
one(Vec2::new(u, v) * *scale)
Projection::Spherical { scale, uv, offset, projector } => one(place_uv(spherical_uv(projector, offset, coords) * *scale, uv)),
Projection::Cylindrical { scale, axis, uv, offset, projector, angle } => {
let (around_axis, height) = cylinder_coords(*axis, projector, offset, *angle, coords);
one(place_uv(Vec2::new(around_axis, 0.5 - height * 0.5) * *scale, uv))
}
Projection::Cylindrical { scale, axis } => {
let p = coords.pos;
let (a, h, b) = match axis {
0 => (p.y, p.x, p.z),
2 => (p.x, p.z, p.y),
_ => (p.x, p.y, p.z),
};
let u = b.atan2(a) / std::f32::consts::TAU + 0.5;
one(Vec2::new(u, 0.5 - h * 0.5) * *scale)
}
Projection::Decal(_) => one(coords.uv),
}
}
@@ -561,50 +674,74 @@ pub fn decal_corners(d: &Decal) -> Option<[Vec3; 4]> {
Some([o - r * hw + u * hh, o + r * hw + u * hh, o + r * hw - u * hh, o - r * hw - u * hh])
}
/// Where world point `p` with surface normal `nrm` falls in the decal: texture coordinates
/// (v down) and how much the decal covers it, None outside the frame, behind it, beyond its
/// depth or on faces turned away. Coverage fades on grazing faces and near the depth limit.
pub fn decal_uv(d: &Decal, p: Vec3, nrm: Vec3) -> Option<(Vec2, f32)> {
let (o, r, u, n) = decal_axes(d)?;
let facing = nrm.dot(n);
let q = p - o;
let (lx, ly, lz) = (q.dot(r) / d.size[0].max(1e-6), q.dot(u) / d.size[1].max(1e-6), q.dot(n).abs());
let depth = d.depth.max(1e-6);
if facing <= 0.0 || lx.abs() > 0.5 || ly.abs() > 0.5 || lz > depth || !(lx.is_finite() && ly.is_finite()) {
return None;
/// World point `point` in frame `frame` turned and scaled by `projector`: across and up in frame sizes, out along its normal in world units
pub fn frame_local(frame: &Decal, projector: &Projector, point: Vec3) -> Option<Vec3> {
let (origin, right, up, normal) = decal_axes(frame)?;
let from_origin = point - origin;
let mut local = Vec3::new(from_origin.dot(right), from_origin.dot(up), from_origin.dot(normal));
if projector.turns() {
local = projector_local(projector, &Coords { uv: Vec2::ZERO, pos: local, nrm: Vec3::Z }).pos;
}
let w = smoothstep(0.0, 0.3, facing) * (1.0 - smoothstep(0.75 * depth, depth, lz));
Some((flip_uv(Vec2::new(lx + 0.5, 0.5 - ly), d.flip), w))
frame_position(frame, local)
}
/// `uv` with the image mirrored left to right (`flip[0]`) and/or top to bottom (`flip[1]`) inside the frame.
fn flip_uv(uv: Vec2, flip: [bool; 2]) -> Vec2 {
Vec2::new(if flip[0] { 1.0 - uv.x } else { uv.x }, if flip[1] { 1.0 - uv.y } else { uv.y })
}
/// Read the position and facing of one sample when a placed frame culls by angle
pub(crate) fn frame_sample(frame: &Decal, projector: &Projector, position: Vec3, surface_normal: Vec3) -> Option<(Vec3, f32)> {
let (origin, right, up, normal) = decal_axes(frame)?;
let from_origin = position - origin;
let local = Vec3::new(from_origin.dot(right), from_origin.dot(up), from_origin.dot(normal));
/// [`decal_uv`] for a decal with a mirrored copy: whichever of the decal and its copy covers the
/// point more. The copy is the decal reflected through the plane across `center` (the mesh
/// center), so a point is looked up as its reflection (the plane is `offset` away from the center) and the image flipped as asked.
pub fn decal_uv_symmetric(d: &Decal, p: Vec3, nrm: Vec3, center: Vec3) -> Option<(Vec2, f32)> {
let direct = decal_uv(d, p, nrm);
let Some(symmetry) = d.symmetry else { return direct };
let axis = usize::from(symmetry.axis.min(2));
let (mut mirrored_position, mut mirrored_normal) = (p, nrm);
mirrored_position[axis] = 2.0 * (center[axis] + symmetry.offset) - p[axis];
mirrored_normal[axis] = -nrm[axis];
let mirrored = decal_uv(d, mirrored_position, mirrored_normal).map(|(uv, w)| {
let uv = match symmetry.flip {
DecalFlip::None => uv,
DecalFlip::U => Vec2::new(1.0 - uv.x, uv.y),
DecalFlip::V => Vec2::new(uv.x, 1.0 - uv.y),
};
(uv, w)
});
match (direct, mirrored) {
(Some(a), Some(b)) => Some(if b.1 > a.1 { b } else { a }),
(a, b) => a.or(b),
if !projector.turns() {
return Some((frame_position(frame, local)?, surface_normal.dot(normal)));
}
let normal = Vec3::new(surface_normal.dot(right), surface_normal.dot(up), surface_normal.dot(normal));
let sample = projector_local(projector, &Coords { uv: Vec2::ZERO, pos: local, nrm: normal });
Some((frame_position(frame, sample.pos)?, sample.nrm.z))
}
fn frame_position(frame: &Decal, local: Vec3) -> Option<Vec3> {
let local = Vec3::new(local.x / frame.size[0].max(MIN_FRAME_EXTENT), local.y / frame.size[1].max(MIN_FRAME_EXTENT), local.z);
local.is_finite().then_some(local)
}
/// How squarely a surface with normal `nrm` faces frame `frame` turned by `projector` (the cosine of the turn)
pub fn frame_facing(frame: &Decal, projector: &Projector, nrm: Vec3) -> f32 {
let Some((_, right, up, normal)) = decal_axes(frame) else { return 0.0 };
if !projector.turns() {
return nrm.dot(normal);
}
let turned = Vec3::new(nrm.dot(right), nrm.dot(up), nrm.dot(normal));
projector_local(projector, &Coords { uv: Vec2::ZERO, pos: Vec3::ZERO, nrm: turned }).nrm.z
}
/// Texture coordinates (v down) of a point at `local` in its frame (see [`frame_local`])
pub fn placed_uv(local: Vec3) -> Vec2 {
Vec2::new(local.x + 0.5, 0.5 - local.y)
}
/// How much frame `frame` covers a point at `local` when cropped to its shape: 0 outside the frame or past its depth, fading near the depth
pub fn frame_crop(frame: &Decal, local: Vec3) -> f32 {
if local.x.abs() > 0.5 || local.y.abs() > 0.5 {
return 0.0;
}
depth_fade(local.z, frame.depth)
}
/// Where a frame's depth fade starts, as a share of its depth
pub const DEPTH_FADE_START: f32 = 0.75;
/// How much a frame reaching `depth` in front of and behind it covers a point `z` out from it: 0 past the depth, fading near it
pub fn depth_fade(z: f32, depth: f32) -> f32 {
let (distance, depth) = (z.abs(), depth.max(MIN_FRAME_EXTENT));
if distance > depth {
return 0.0;
}
1.0 - smoothstep(DEPTH_FADE_START * depth, depth, distance)
}
/// World-space noise used by generators (seamless across UV islands).
@@ -637,20 +774,102 @@ mod tests {
// Coarse reads are exact at cell centers and blend between them
assert!((at(0.375, &coarse) - at(0.375, &exact)).abs() < 1e-5);
let blended = (at(0.125, &exact) + at(0.375, &exact)) * 0.5;
assert!((at(0.25, &coarse) - blended).abs() < 1e-5, "{} vs {blended}", at(0.25, &coarse));
assert!((at(0.25, &exact) - blended).abs() > 1e-3, "the exact pattern is not the blend, so the coarse read shows");
}
/// A decal saved before image placement reads its frame coordinates bit for bit as it did: its image at them, its procedural at them times the pattern scale
#[test]
fn an_unplaced_decal_reads_its_frame_coordinates_bit_for_bit() {
let frame = Decal {
center: [0.0; 3],
normal: [0.0, 0.0, 1.0],
up: [0.0, 1.0, 0.0],
size: [1.0; 2],
rotation: 0.0,
offset: [0.0; 2],
depth: 0.5,
symmetry: None,
flip: [false; 2],
};
let decal = Projection::decal(frame);
let pattern = Procedural { scale: 3.0, ..Procedural::new(ProceduralKind::Gradient) };
for across in 0..=1000 {
for down in [0.0, 0.1, 0.37, 1.0] {
let uv = Vec2::new(across as f32 / 1000.0, down);
let coords = Coords { uv, pos: Vec3::ZERO, nrm: Vec3::Z };
assert_eq!(image_samples(&decal, &coords)[0].0, uv, "image at {uv}");
let expected = shape(&pattern, raw(pattern.kind, (uv * pattern.scale).extend(0.0), pattern.seed));
assert_eq!(procedural(&pattern, &decal, &coords).to_bits(), expected.to_bits(), "procedural at {uv}");
}
}
}
/// A frame's image turns round the frame's centre: the centre reads the same texel at any Rotation, and an unturned image reads exactly as before for any Tiling and Offset
#[test]
fn a_frame_image_turns_round_the_frame_centre() {
let frame = Decal {
center: [0.0; 3],
normal: [0.0, 0.0, 1.0],
up: [0.0, 1.0, 0.0],
size: [1.0; 2],
rotation: 0.0,
offset: [0.0; 2],
depth: 0.5,
symmetry: None,
flip: [false; 2],
};
let at = |uv: Vec2| Coords { uv, pos: Vec3::ZERO, nrm: Vec3::Z };
let sample = |rotation: f32, tiling: [f32; 2], offset: [f32; 2], uv: Vec2| {
image_samples(
&Projection::Warp {
frame,
corners: Projection::FRAME_CORNERS,
depth: 0.1,
uv: UvTransform { tiling, rotation, offset },
projector: Projector::default(),
},
&at(uv),
)[0]
.0
};
for rotation in [37.0, 90.0, 180.0] {
let center = sample(rotation, [1.0; 2], [0.0; 2], FRAME_UV_CENTER);
assert!((center - FRAME_UV_CENTER).length() < 1e-5, "{rotation}°: the centre stays put, not swung round the top left: {center}");
}
let corner = sample(90.0, [1.0; 2], [0.0; 2], Vec2::ZERO);
assert!((corner - Vec2::new(1.0, 0.0)).length() < 1e-5, "a quarter turn brings the top left to the top right: {corner}");
let placed = Projection::Planar {
scale: 1.0,
axis: 2,
offset: [0.0; 3],
uv: UvTransform { rotation: 90.0, ..UvTransform::default() },
projector: Projector::default(),
placed: Some(frame),
};
assert!((image_samples(&placed, &at(FRAME_UV_CENTER))[0].0 - FRAME_UV_CENTER).length() < 1e-5, "a placed planar frame turns the same way");
for (tiling, offset, uv) in [([2.0, 3.0], [0.25, -0.5], Vec2::new(0.1, 0.8)), ([1.0, 1.0], [0.0, 0.0], Vec2::new(0.7, 0.2))] {
let before = uv * Vec2::from(tiling) + Vec2::from(offset);
assert!((sample(0.0, tiling, offset, uv) - before).length() < 1e-6, "unturned: as before");
}
}
#[test]
fn every_pattern_and_projection_stays_in_range() {
let projections = [
Projection::default(),
Projection::Triplanar { scale: 1.0, sharpness: 4.0, offset: [0.0; 3] },
Projection::Planar { scale: 1.0, axis: 1, offset: [0.0; 3] },
Projection::Spherical { scale: 1.0 },
Projection::Cylindrical { scale: 1.0, axis: 1 },
Projection::Decal(Decal {
Projection::Triplanar { scale: 1.0, sharpness: 4.0, offset: [0.0; 3], uv: Default::default(), projector: Default::default() },
Projection::Planar { scale: 1.0, axis: 1, offset: [0.0; 3], uv: Default::default(), projector: Default::default(), placed: None },
Projection::Spherical { scale: 1.0, uv: Default::default(), offset: [0.0; 3], projector: Default::default() },
Projection::Cylindrical { scale: 1.0, axis: 1, uv: Default::default(), offset: [0.0; 3], projector: Default::default(), angle: FULL_TURN_DEGREES },
Projection::decal(Decal {
center: [0.0; 3],
normal: [0.0, 0.0, 1.0],
up: [0.0, 1.0, 0.0],
@@ -662,18 +881,16 @@ mod tests {
flip: [false; 2],
}),
];
for kind in ProceduralKind::ALL {
let pattern = Procedural::new(kind);
for projection in &projections {
for i in 0..50 {
let t = i as f32 * 0.13;
for index in 0..50 {
let position = index as f32 * 0.13;
let coords = Coords {
uv: Vec2::new(t.fract(), (t * 0.7).fract()),
pos: Vec3::new(t.sin(), t.cos(), t * 0.1),
uv: Vec2::new(position.fract(), (position * 0.7).fract()),
pos: Vec3::new(position.sin(), position.cos(), position * 0.1),
nrm: Vec3::new(0.3, 0.9, 0.1).normalize(),
};
let value = procedural(&pattern, projection, &coords);
assert!((0.0..=1.0).contains(&value), "{kind:?} {projection:?} {value}");
@@ -702,7 +919,8 @@ mod tests {
for contrast in [1.0, 4.0, 16.0] {
let pattern = Procedural { contrast, ..Procedural::new(kind) };
for sharpness in [1.0, 4.0, 8.0, 16.0] {
let projection = Projection::Triplanar { scale: 1.0, sharpness, offset: [0.0; 3] };
let projection =
Projection::Triplanar { scale: 1.0, sharpness, offset: [0.0; 3], uv: UvTransform::default(), projector: Projector::default() };
for index in 0..400 {
// Cover axis aligned and oblique normals at varied positions
let position = index as f32 / 400.0;
@@ -715,6 +933,7 @@ mod tests {
}
assert!(largest_difference < 1.0 / 65535.0, "worst difference {largest_difference}");
let near_axis = triplanar_weights(Vec3::new(0.2, 1.0, 0.1).normalize(), 8.0, 1.0);
assert_eq!((near_axis.x, near_axis.z), (0.0, 0.0), "{near_axis}");
@@ -722,18 +941,30 @@ mod tests {
let oblique = triplanar_weights(Vec3::ONE.normalize(), 8.0, 16.0);
assert!((oblique - Vec3::splat(1.0 / 3.0)).abs().max_element() < 1e-6, "{oblique}");
// Tiny weights must survive together when their sum exceeds a u16 step
for sharpness in [47.0, 64.0] {
let diagonal = triplanar_weights(Vec3::ONE.normalize(), sharpness, 1.0);
assert!(diagonal.min_element() > 0.0, "sharpness {sharpness}: {diagonal}");
assert!(diagonal.abs_diff_eq(Vec3::splat(1.0 / 3.0), 1e-6), "sharpness {sharpness}: {diagonal}");
}
}
#[test]
fn triplanar_image_hardness_preserves_diagonal_coverage() {
let coords = Coords { uv: Vec2::ZERO, pos: Vec3::ZERO, nrm: Vec3::new(1.0, 0.95, 0.90).normalize() };
let projection =
|sharpness| Projection::Triplanar { scale: 1.0, sharpness, offset: [0.0; 3], uv: UvTransform::default(), projector: Projector::default() };
let soft = image_samples(&projection(1.0), &coords).map(|(_, weight)| weight);
let hard = image_samples(&projection(64.0), &coords).map(|(_, weight)| weight);
assert!((hard.into_iter().sum::<f32>() - 1.0).abs() < 1e-6, "{hard:?}");
assert!(hard[0] > soft[0] && hard[1] < soft[1] && hard[2] < soft[2], "{soft:?} {hard:?}");
}
#[test]
fn triplanar_image_sampling_preserves_bright_float_pixels() {
let image = crate::ImageRes { width: 2, height: 2, rgba: vec![[0.0; 4], [0.0; 4], [0.0; 4], [100_000.0; 4]], srgb: false };
let image = crate::ImageRes::new(2, 2, vec![[0.0; 4], [0.0; 4], [0.0; 4], [100_000.0; 4]], false);
let coords = Coords { uv: Vec2::ZERO, pos: Vec3::new(0.25, 0.25, 0.75), nrm: Vec3::new(0.2, 1.0, 0.1).normalize() };
let projection = Projection::Triplanar { scale: 1.0, sharpness: 8.0, offset: [0.0; 3] };
let projection = Projection::Triplanar { scale: 1.0, sharpness: 8.0, offset: [0.0; 3], uv: UvTransform::default(), projector: Projector::default() };
let weights = coords.nrm.abs().powf(8.0);
let expected = 100_000.0 * weights.x / (weights.x + weights.y + weights.z);
@@ -761,6 +992,12 @@ mod tests {
}
}
/// Where frame `frame`'s planar projection lands at `point` facing `nrm`, None where it does not cover
fn decal_uv(frame: &Decal, point: Vec3, nrm: Vec3) -> Option<(Vec2, f32)> {
let Projection::Planar { projector, .. } = Projection::decal(*frame) else { return None };
crate::projector_cover::placed_cover(frame, &projector, point, nrm).filter(|(_, cover)| *cover > 0.0)
}
#[test]
fn decals_cover_their_frame_facing_them() {
let d = Decal {
+288
View File
@@ -0,0 +1,288 @@
//! How much of a texel a 3D projection reaches: its shape crop and its backface culling
use texturecraft_core::{Backface, Decal, DecalFlip, Projection, Projector, ShapeCrop};
use texturecraft_geom::glam::{Vec2, Vec3};
use crate::frame_placement::warp_reach;
use crate::organic::smoothstep;
use crate::pattern::{Coords, depth_fade, frame_crop, frame_local, frame_sample, placed_uv, projector_local};
use crate::warp::warp_uv;
/// Nearer a cylinder's axis than this a texel has no outward direction, so it counts as facing out
const MIN_AXIS_DISTANCE: f32 = 1e-6;
/// The turn (in cosine) over which backface culling fades at hardness 0
const BACKFACE_FADE: f32 = 0.6;
/// The shape crop and backface culling [`projector_cover`] applies, None where it lets every texel through
fn cropping_projector(proj: &Projection) -> Option<&Projector> {
let projector = match proj {
Projection::Triplanar { projector, .. }
| Projection::Planar { projector, .. }
| Projection::Spherical { projector, .. }
| Projection::Cylindrical { projector, .. } => projector,
// Framed on the surface: see [`framed_cover`]
Projection::Warp { .. } | Projection::Uv { .. } | Projection::UvTile => return None,
};
Some(projector).filter(|projector| projector.crop != ShapeCrop::ExtendsOutside || projector.backface.on)
}
/// Whether [`projector_cover`] is 1 on every texel, so it needs no texel's place
pub fn projector_covers_all(proj: &Projection) -> bool {
cropping_projector(proj).is_none()
}
/// How much of the texel at `coords` the projection reaches through its shape crop and backface culling; not for placed planars or warps (see [`framed_cover`])
pub fn projector_cover(proj: &Projection, coords: &Coords) -> f32 {
let Some(projector) = cropping_projector(proj) else { return 1.0 };
let local = projector_local(projector, coords);
let (inside, facing) = match proj {
Projection::Triplanar { .. } => (local.pos.abs().max_element() <= 1.0, None),
Projection::Planar { scale, axis, offset, .. } => {
let scaled = local.pos * *scale + Vec3::from(*offset);
// The frame across the axis, and the side the image reads the right way round from
let (frame, facing) = match axis {
0 => (scaled.z.abs().max(scaled.y.abs()), -local.nrm.x),
1 => (scaled.x.abs().max(scaled.z.abs()), local.nrm.y),
_ => (scaled.x.abs().max(scaled.y.abs()), local.nrm.z),
};
(frame <= 1.0, Some(facing))
}
Projection::Spherical { offset, .. } => ((local.pos + Vec3::from(*offset)).length() <= 1.0, None),
Projection::Cylindrical { axis, offset, .. } => {
let position = local.pos + Vec3::from(*offset);
let normal = local.nrm;
let ((across, height, depth), (normal_across, normal_depth)) = match axis {
0 => ((position.y, position.x, position.z), (normal.y, normal.z)),
2 => ((position.x, position.z, position.y), (normal.x, normal.y)),
_ => ((position.x, position.y, position.z), (normal.x, normal.z)),
};
let radius = across.hypot(depth);
let outward = if radius > MIN_AXIS_DISTANCE { (normal_across * across + normal_depth * depth) / radius } else { 1.0 };
(radius <= 1.0 && height.abs() <= 1.0, Some(outward))
}
Projection::Warp { .. } | Projection::Uv { .. } | Projection::UvTile => (true, None),
};
if projector.crop == ShapeCrop::Cropped && !inside {
return 0.0;
}
match facing {
Some(facing) if projector.backface.on => backface_cover(&projector.backface, facing),
_ => 1.0,
}
}
/// How much a face turned `facing` (the cosine of its turn from the projection) keeps
pub fn backface_cover(backface: &Backface, facing: f32) -> f32 {
// A hand-edited NaN angle or hardness keeps the layer visible rather than making its texels NaN
if !(backface.angle.is_finite() && backface.hardness.is_finite()) {
return 1.0;
}
// cos(angle) as sin(90 - angle): exactly 0 at 90 degrees
let threshold = (90.0 - backface.angle).to_radians().sin();
let width = (1.0 - backface.hardness.clamp(0.0, 1.0)) * BACKFACE_FADE;
if width <= f32::EPSILON {
return f32::from(u8::from(facing > threshold));
}
smoothstep(threshold, threshold + width, facing)
}
/// A planar projection placed on the surface at world point `p` with normal `nrm`: its texture coordinates and how much its backface culling and shape crop let through (None when the frame is degenerate)
pub fn placed_cover(frame: &Decal, projector: &Projector, p: Vec3, nrm: Vec3) -> Option<(Vec2, f32)> {
let (local, mut cover) = if projector.backface.on {
let (local, facing) = frame_sample(frame, projector, p, nrm)?;
(local, backface_cover(&projector.backface, facing))
} else {
(frame_local(frame, projector, p)?, 1.0)
};
if projector.crop == ShapeCrop::Cropped {
cover *= frame_crop(frame, local);
}
Some((flip_uv(placed_uv(local), frame.flip), cover))
}
/// [`placed_cover`] for a frame with a mirrored copy: whichever of the frame and its copy covers the point more. The copy is the frame reflected through the plane `offset` away from `center` (the mesh center) on the symmetry axis, its image flipped as asked
pub fn placed_cover_symmetric(frame: &Decal, projector: &Projector, p: Vec3, nrm: Vec3, center: Vec3) -> Option<(Vec2, f32)> {
let direct = placed_cover(frame, projector, p, nrm);
let Some(symmetry) = frame.symmetry else { return direct };
let axis = usize::from(symmetry.axis.min(2));
let (mut mirrored_position, mut mirrored_normal) = (p, nrm);
mirrored_position[axis] = 2.0 * (center[axis] + symmetry.offset) - p[axis];
mirrored_normal[axis] = -nrm[axis];
let mirrored = placed_cover(frame, projector, mirrored_position, mirrored_normal).map(|(uv, cover)| {
let uv = match symmetry.flip {
DecalFlip::None => uv,
DecalFlip::U => Vec2::new(1.0 - uv.x, uv.y),
DecalFlip::V => Vec2::new(uv.x, 1.0 - uv.y),
};
(uv, cover)
});
match (direct, mirrored) {
(Some(a), Some(b)) => Some(if b.1 > a.1 { b } else { a }),
(a, b) => a.or(b),
}
}
/// `uv` with the image mirrored left to right (`flip[0]`) and/or top to bottom (`flip[1]`) inside the frame
fn flip_uv(uv: Vec2, flip: [bool; 2]) -> Vec2 {
Vec2::new(if flip[0] { 1.0 - uv.x } else { uv.x }, if flip[1] { 1.0 - uv.y } else { uv.y })
}
/// A projection from a frame on the surface (a placed planar or a warp) at world point `p` with normal `nrm`, `center` the mesh center a placed planar's mirrored copy reflects across: its texture coordinates and how much it covers there (None for other projections, a degenerate frame or where nothing lands)
pub fn framed_cover(proj: &Projection, p: Vec3, nrm: Vec3, center: Vec3) -> Option<(Vec2, f32)> {
match proj {
Projection::Planar { projector, placed: Some(frame), .. } => placed_cover_symmetric(frame, projector, p, nrm, center),
Projection::Warp { frame, corners, depth, projector, .. } => warp_cover(frame, corners, *depth, projector, p),
_ => None,
}
}
/// A warp projection at world point `p`: its texture coordinates in the quad its corners make, and, cropped to its shape, how much of the quad and of its Projection Depth (in lengths of the frame's longer side) cover it
pub fn warp_cover(frame: &Decal, corners: &[[f32; 2]; 4], depth: f32, projector: &Projector, p: Vec3) -> Option<(Vec2, f32)> {
let local = frame_local(frame, projector, p)?;
let uv = warp_uv(corners, local.truncate())?;
if projector.crop == ShapeCrop::ExtendsOutside {
return Some((uv, 1.0));
}
let inside = (0.0..=1.0).contains(&uv.x) && (0.0..=1.0).contains(&uv.y);
let reach = warp_reach(frame.size, depth);
Some((uv, if inside { depth_fade(local.z, reach) } else { 0.0 }))
}
#[cfg(test)]
mod tests {
use super::*;
/// The decal formula from before decals were placed planar projections, kept to check they still look the same
fn decal_before(frame: &Decal, point: Vec3, surface_normal: Vec3) -> Option<(Vec2, f32)> {
let (origin, right, up, normal) = crate::pattern::decal_axes(frame)?;
let facing = surface_normal.dot(normal);
let offset = point - origin;
let (local_x, local_y, local_z) = (offset.dot(right) / frame.size[0].max(1e-6), offset.dot(up) / frame.size[1].max(1e-6), offset.dot(normal).abs());
let depth = frame.depth.max(1e-6);
if facing <= 0.0 || local_x.abs() > 0.5 || local_y.abs() > 0.5 || local_z > depth || !(local_x.is_finite() && local_y.is_finite()) {
return None;
}
let cover = smoothstep(0.0, 0.3, facing) * (1.0 - smoothstep(0.75 * depth, depth, local_z));
Some((Vec2::new(local_x + 0.5, 0.5 - local_y), cover))
}
#[test]
fn a_nan_backface_angle_or_hardness_culls_nothing() {
for backface in [Backface { on: true, angle: f32::NAN, hardness: 0.5 }, Backface { on: true, angle: 60.0, hardness: f32::NAN }] {
assert_eq!(backface_cover(&backface, -0.5), 1.0, "{backface:?}");
}
}
#[test]
fn saved_decals_cover_exactly_as_before() {
let frames = [
Decal {
center: [0.0; 3],
normal: [0.0, 0.0, 1.0],
up: [0.0, 1.0, 0.0],
size: [2.0, 1.0],
rotation: 0.0,
offset: [0.0; 2],
depth: 0.5,
symmetry: None,
flip: [false; 2],
},
Decal {
center: [0.3, -0.2, 0.1],
normal: [0.4, 0.5, 0.7],
up: [0.0, 1.0, 0.0],
size: [0.7, 1.3],
rotation: 37.0,
offset: [0.2, -0.1],
depth: 0.4,
symmetry: None,
flip: [false; 2],
},
];
for frame in frames {
let Projection::Planar { projector, placed: Some(placed), .. } = Projection::decal(frame) else { panic!("a placed planar projection") };
for sample in 0..4000 {
let phase = sample as f32 * 0.137;
let point = Vec3::new(phase.sin() * 1.3, (phase * 0.71).cos() * 1.1, (phase * 0.33).sin() * 0.8);
let normal = Vec3::new((phase * 1.7).cos(), (phase * 0.9).sin(), (phase * 0.4).cos()).normalize();
let now = placed_cover(&placed, &projector, point, normal).filter(|(_, cover)| *cover > 0.0);
match (decal_before(&frame, point, normal), now) {
(Some(before), Some(now)) => assert_eq!(before, now, "{point} {normal}"),
(None, None) => {}
(before, now) => panic!("{point} {normal}: {before:?} became {now:?}"),
}
}
}
}
/// The mirrored copy's formula as the decal model before placed planar projections had it (flip and symmetry on a decal)
fn symmetric_before(d: &Decal, p: Vec3, nrm: Vec3, center: Vec3) -> Option<(Vec2, f32)> {
let flip = |uv: Vec2| flip_uv(uv, d.flip);
let direct = decal_before(d, p, nrm).map(|(uv, w)| (flip(uv), w));
let Some(symmetry) = d.symmetry else { return direct };
let axis = usize::from(symmetry.axis.min(2));
let (mut q, mut m) = (p, nrm);
q[axis] = 2.0 * (center[axis] + symmetry.offset) - p[axis];
m[axis] = -nrm[axis];
let mirrored = decal_before(d, q, m).map(|(uv, w)| {
let uv = flip(uv);
let uv = match symmetry.flip {
DecalFlip::None => uv,
DecalFlip::U => Vec2::new(1.0 - uv.x, uv.y),
DecalFlip::V => Vec2::new(uv.x, 1.0 - uv.y),
};
(uv, w)
});
match (direct, mirrored) {
(Some(a), Some(b)) => Some(if b.1 > a.1 { b } else { a }),
(a, b) => a.or(b),
}
}
#[test]
fn saved_mirrored_and_flipped_decals_cover_exactly_as_before() {
let base = Decal {
center: [0.3, -0.2, 0.1],
normal: [0.4, 0.5, 0.7],
up: [0.0, 1.0, 0.0],
size: [0.7, 1.3],
rotation: 37.0,
offset: [0.2, -0.1],
depth: 0.4,
symmetry: None,
flip: [false; 2],
};
let center = Vec3::new(0.1, -0.05, 0.2);
let frames = [
Decal { flip: [true, false], ..base },
Decal { symmetry: Some(texturecraft_core::DecalSymmetry { axis: 0, flip: DecalFlip::None, offset: 0.0 }), ..base },
Decal { symmetry: Some(texturecraft_core::DecalSymmetry { axis: 2, flip: DecalFlip::V, offset: -0.15 }), flip: [false, true], ..base },
];
for frame in frames {
let Projection::Planar { projector, placed: Some(placed), .. } = Projection::decal(frame) else { panic!("a placed planar projection") };
let mut mirrored = 0;
for i in 0..4000 {
let t = i as f32 * 0.137;
let p = Vec3::new(t.sin() * 1.3, (t * 0.71).cos() * 1.1, (t * 0.33).sin() * 0.8);
let nrm = Vec3::new((t * 1.7).cos(), (t * 0.9).sin(), (t * 0.4).cos()).normalize();
let now = placed_cover_symmetric(&placed, &projector, p, nrm, center).filter(|(_, cover)| *cover > 0.0);
let before = symmetric_before(&frame, p, nrm, center);
mirrored += usize::from(before.is_some() && decal_before(&frame, p, nrm).is_none());
assert_eq!(before, now, "{p} {nrm}");
}
assert!(frame.symmetry.is_none() || mirrored > 0, "the mirrored copy covers points the frame does not");
}
}
}
+312
View File
@@ -0,0 +1,312 @@
//! The depth map of a planar or warp projection: the surface nearest its projector across its view, for depth culling
use std::sync::Arc;
use texturecraft_core::Projection;
use texturecraft_geom::Mesh;
use texturecraft_geom::glam::{Vec2, Vec3};
use crate::fill_copy::FillCopy;
use crate::organic::smoothstep;
use crate::projector_view::ProjectorView;
/// The nearest surface in each cell of a grid across a projector's view
pub struct ProjectorDepth {
view: ProjectorView,
/// The view point at the grid's lower corner
origin: Vec2,
grid_side: usize,
/// One cell's size across and up in the view
cell: Vec2,
/// The mesh radius measured along the view's depth axis
nearness_unit: f32,
/// Per cell: the nearness of the nearest surface at the cell centre and its slope across and up (nearness -inf where no surface is)
front: Vec<[f32; 3]>,
}
/// The smallest grid cell across and up, so a flat view still divides
const MIN_CELL_SIZE: f32 = 1e-6;
/// A cell centre this close outside a triangle's edge (as a share of its area) still counts as inside, so shared edges leave no gaps
const EDGE_TOLERANCE: f32 = 1e-6;
impl ProjectorDepth {
/// Build the depth map of a borrowed mesh, if the projection uses depth culling.
pub fn of(mesh: &Mesh, bounds: (Vec3, Vec3), projection: &Projection) -> Option<Arc<ProjectorDepth>> {
let view = ProjectorView::of(projection, bounds)?;
Self::build(view, mesh).map(Arc::new)
}
/// Rasterize the mesh in this view, using a coarser grid when the cell budget requires one.
pub fn build(view: ProjectorView, mesh: &Mesh) -> Option<ProjectorDepth> {
Self::build_for_copy(view, mesh, None, GRID_SIDE, CELL_BUDGET)
}
pub(crate) fn build_for_copy(view: ProjectorView, mesh: &Mesh, copy: Option<FillCopy>, mut grid_side: usize, cell_budget: usize) -> Option<Self> {
let projected: Vec<_> = mesh.positions.iter().map(|&point| view.local(copy.map_or(point, |copy| copy.point(point)))).collect();
let (min, max) = projected
.iter()
.flatten()
.fold((Vec2::splat(f32::MAX), Vec2::splat(f32::MIN)), |(lo, hi), view_point| (lo.min(view_point.truncate()), hi.max(view_point.truncate())));
if min.x > max.x || min.y > max.y {
return None;
}
// The one-cell fallback can always afford one visit per triangle
let cell_budget = cell_budget.max(mesh.triangle_count());
let nearness_unit = view.unit();
while grid_side > 0 {
let cell = ((max - min) / grid_side as f32).max(Vec2::splat(MIN_CELL_SIZE));
let front = vec![[f32::NEG_INFINITY, 0.0, 0.0]; grid_side * grid_side];
let mut depth = ProjectorDepth { view, origin: min, grid_side, cell, nearness_unit, front };
let mut remaining = cell_budget;
let mut triangles = mesh.indices.as_chunks::<3>().0.iter().filter_map(|indices| {
let [a, b, c] = indices.map(|index| projected.get(index as usize).copied().flatten());
Some([a?, b?, c?])
});
if triangles.all(|triangle| depth.raster(triangle, &mut remaining)) {
return Some(depth);
}
// Discard any partial grid before retrying the whole mesh
grid_side /= 2;
}
None
}
/// Keep `triangle` where it is nearer than what a cell holds; false once the cell budget runs out
fn raster(&mut self, triangle: [Vec3; 3], budget: &mut usize) -> bool {
let [a, b, c] = triangle;
let (edge_ab, edge_ac) = (b - a, c - a);
let determinant = edge_ab.x * edge_ac.y - edge_ab.y * edge_ac.x;
if !determinant.is_finite() || determinant.abs() < MIN_SCREEN_AREA {
// An edge-on triangle covers no cells
return true;
}
let slope = Vec2::new((edge_ab.z * edge_ac.y - edge_ac.z * edge_ab.y) / determinant, (edge_ab.x * edge_ac.z - edge_ac.x * edge_ab.z) / determinant)
.clamp(Vec2::splat(-MAX_SLOPE), Vec2::splat(MAX_SLOPE));
// Evaluate coverage at cell centres
let [pa, pb, pc] = triangle.map(|corner| (corner.truncate() - self.origin) / self.cell);
let (lo, hi) = (pa.min(pb).min(pc), pa.max(pb).max(pc));
let first_cell = |position: f32| (position - 0.5).ceil().clamp(0.0, self.grid_side as f32) as usize;
let end_cell = |position: f32| ((position - 0.5).floor() + 1.0).clamp(0.0, self.grid_side as f32) as usize;
let (x0, x1, y0, y1) = (first_cell(lo.x), end_cell(hi.x), first_cell(lo.y), end_cell(hi.y));
let cells = x1.saturating_sub(x0).saturating_mul(y1.saturating_sub(y0));
let Some(left) = budget.checked_sub(cells) else { return false };
*budget = left;
let area = edge(pa, pb, pc);
for y in y0..y1 {
for x in x0..x1 {
let cell_centre = Vec2::new(x as f32 + 0.5, y as f32 + 0.5);
let inside = [edge(pb, pc, cell_centre), edge(pc, pa, cell_centre), edge(pa, pb, cell_centre)]
.iter()
.all(|weight| weight * area.signum() >= -EDGE_TOLERANCE * area.abs());
if !inside {
continue;
}
let near = a.z + slope.dot(self.origin + cell_centre * self.cell - a.truncate());
if let Some(cell) = self.front.get_mut(y * self.grid_side + x)
&& near > cell[0]
{
*cell = [near, slope.x, slope.y];
}
}
}
true
}
/// How much depth culling with `hardness` leaves of a projection at world point `p`: 0 behind the surface nearest the projector, 1 on it or where nothing is in front
pub fn cover(&self, position: Vec3, hardness: f32) -> f32 {
// Keep the layer visible when a hand-edited hardness is invalid
if !hardness.is_finite() {
return 1.0;
}
let Some(view_point) = self.view.local(position) else { return 1.0 };
let at = (view_point.truncate() - self.origin) / self.cell;
if !(at.x >= 0.0 && at.y >= 0.0 && at.x <= self.grid_side as f32 && at.y <= self.grid_side as f32) {
return 1.0;
}
let (x, y) = ((at.x as usize).min(self.grid_side - 1), (at.y as usize).min(self.grid_side - 1));
let Some(&[near, across, up]) = self.front.get(y * self.grid_side + x).filter(|cell| cell[0].is_finite()) else { return 1.0 };
// Extend the cell's plane to avoid culling a surface against itself
let centre = self.origin + (Vec2::new(x as f32, y as f32) + 0.5) * self.cell;
let slope = Vec2::new(across, up);
let behind = near + slope.dot(view_point.truncate() - centre) - view_point.z;
let unit = self.nearness_unit;
// Add slope bias for curvature across adjacent triangles
let bias = BIAS * unit + (slope.abs() * self.cell).element_sum().min(MAX_SLOPE_BIAS * unit);
let width = (1.0 - hardness.clamp(0.0, 1.0)) * FADE * unit;
if width <= f32::EPSILON {
return f32::from(u8::from(behind <= bias));
}
1.0 - smoothstep(bias, bias + width, behind)
}
}
/// Twice the signed area of triangle `a`, `b`, `q`
fn edge(a: Vec2, b: Vec2, q: Vec2) -> f32 {
(b - a).perp_dot(q - a)
}
/// Cells across and up the grid
pub(crate) const GRID_SIDE: usize = 512;
/// A triangle flatter than this on screen is seen edge on
const MIN_SCREEN_AREA: f32 = 1e-12;
/// Cell visits available at each resolution before large overlapping triangles require a coarser grid.
pub(crate) const CELL_BUDGET: usize = 256 * GRID_SIDE * GRID_SIDE;
/// Steepest surface slope kept, in nearness per view unit
const MAX_SLOPE: f32 = 1e4;
/// How far behind the nearest surface a point may sit and keep everything, in mesh radii
const BIAS: f32 = 0.002;
/// Most the slope adds to the bias, in mesh radii
const MAX_SLOPE_BIAS: f32 = 0.05;
/// How far behind the nearest surface culling fades out at hardness 0, in mesh radii
const FADE: f32 = 0.1;
#[cfg(test)]
mod tests {
use super::*;
use texturecraft_core::{Projector, UvTransform};
/// Two squares facing +Z, one at z = `front` covering x 0..1, one at z = `back` covering x -1..1
fn two_squares(front: f32, back: f32) -> Mesh {
let positions = vec![
Vec3::new(0.0, -1.0, front),
Vec3::new(1.0, -1.0, front),
Vec3::new(1.0, 1.0, front),
Vec3::new(0.0, 1.0, front),
Vec3::new(-1.0, -1.0, back),
Vec3::new(1.0, -1.0, back),
Vec3::new(1.0, 1.0, back),
Vec3::new(-1.0, 1.0, back),
];
Mesh { positions, indices: vec![0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7], ..Mesh::default() }
}
fn planar_z(on: bool, hardness: f32) -> Projection {
let mut projector = Projector::depth_culled();
projector.depth.on = on;
projector.depth.hardness = hardness;
Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv: UvTransform::default(), projector, placed: None }
}
#[test]
fn surfaces_behind_others_are_culled_and_the_nearest_keeps_everything() {
let mesh = two_squares(0.5, -0.5);
let bounds = mesh.bounds();
let depth = ProjectorDepth::build(ProjectorView::of(&planar_z(true, 1.0), bounds).unwrap(), &mesh).unwrap();
assert_eq!(depth.cover(Vec3::new(0.5, 0.3, 0.5), 1.0), 1.0, "the front square");
assert_eq!(depth.cover(Vec3::new(0.5, 0.3, -0.5), 1.0), 0.0, "the back square behind it");
assert_eq!(depth.cover(Vec3::new(-0.5, 0.3, -0.5), 1.0), 1.0, "the back square where nothing is in front");
let soft = depth.cover(Vec3::new(0.5, 0.3, 0.5 - 0.01), 0.0);
assert!(soft > 0.0 && soft < 1.0, "a soft cull fades just behind the front: {soft}");
assert!(ProjectorView::of(&planar_z(false, 1.0), bounds).is_none(), "off, there is nothing to build");
}
#[test]
fn folding_positive_depth_stretch_preserves_soft_culling() {
let mesh = two_squares(0.5, -0.5);
let bounds = mesh.bounds();
let mut projector = Projector::depth_culled();
projector.scale[2] = 2.0;
projector.depth.hardness = 0.0;
let stretched = Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv: UvTransform::default(), projector, placed: None };
let placed = crate::axis_frame::placed_from_axis(&stretched, bounds).unwrap();
let axis_depth = ProjectorDepth::of(&mesh, bounds, &stretched).unwrap();
let placed_depth = ProjectorDepth::of(&mesh, bounds, &placed).unwrap();
let just_behind = Vec3::new(0.5, 0.3, 0.44);
let before = axis_depth.cover(just_behind, 0.0);
let after = placed_depth.cover(just_behind, 0.0);
assert!(before > 0.0 && before < 1.0 && (before - after).abs() < 1e-4, "axis {before}, placed {after}");
}
#[test]
fn the_upper_right_grid_boundary_can_be_depth_culled() {
let mesh = two_squares(0.5, -0.5);
let depth = ProjectorDepth::of(&mesh, mesh.bounds(), &planar_z(true, 1.0)).unwrap();
assert_eq!(depth.cover(Vec3::new(1.0, 1.0, -0.5), 1.0), 0.0);
}
#[test]
fn raster_budget_fallback_accounts_for_the_last_triangle() {
let mut mesh = two_squares(0.5, -0.5);
let rear_triangles = [4, 5, 6, 4, 6, 7];
let front_triangles = [0, 1, 2, 0, 2, 3];
mesh.indices = rear_triangles.repeat(CELL_BUDGET / (GRID_SIDE * GRID_SIDE));
mesh.indices.extend(front_triangles);
let projection = planar_z(true, 1.0);
let behind = Vec3::new(0.5, 0.3, -0.5);
let front_last = ProjectorDepth::of(&mesh, mesh.bounds(), &projection).unwrap();
mesh.indices.rotate_right(front_triangles.len());
let front_first = ProjectorDepth::of(&mesh, mesh.bounds(), &projection).unwrap();
assert_eq!(front_last.cover(behind, 1.0), 0.0);
assert_eq!(front_last.cover(behind, 1.0), front_first.cover(behind, 1.0));
}
#[test]
fn a_nan_hardness_culls_nothing() {
let mesh = two_squares(0.5, -0.5);
let depth = ProjectorDepth::build(ProjectorView::of(&planar_z(true, 1.0), mesh.bounds()).unwrap(), &mesh).unwrap();
let behind = depth.cover(Vec3::new(0.5, 0.3, -0.5), f32::NAN);
assert_eq!(behind, 1.0, "a hand-edited NaN hardness keeps the back square visible");
}
#[test]
fn interleaved_meshes_keep_their_own_projector_depth() {
let mut mesh = two_squares(0.5, -0.5);
// Add enough unused vertices for the old sample to skip the changed edge
mesh.positions.resize(200, Vec3::ZERO);
let mut edited = mesh.clone();
for right in [1, 2] {
edited.positions[right].x = 0.5;
}
assert_eq!(mesh.bounds(), edited.bounds());
let proj = planar_z(true, 1.0);
let behind_the_cut = Vec3::new(0.75, 0.3, -0.5);
let bounds = mesh.bounds();
assert_eq!(ProjectorDepth::of(&mesh, bounds, &proj).unwrap().cover(behind_the_cut, 1.0), 0.0);
let rebuilt = ProjectorDepth::of(&edited, bounds, &proj).unwrap();
assert_eq!(rebuilt.cover(behind_the_cut, 1.0), 1.0, "nothing is in front there any more");
}
#[test]
fn a_slanted_surface_is_never_behind_itself() {
let positions = vec![Vec3::new(-1.0, -1.0, -0.9), Vec3::new(1.0, -1.0, 0.9), Vec3::new(1.0, 1.0, 0.9), Vec3::new(-1.0, 1.0, -0.9)];
let mesh = Mesh { positions, indices: vec![0, 1, 2, 0, 2, 3], ..Mesh::default() };
let depth = ProjectorDepth::build(ProjectorView::of(&planar_z(true, 1.0), mesh.bounds()).unwrap(), &mesh).unwrap();
for i in 0..1000 {
let (x, y) = ((i as f32 * 0.618).fract() * 1.98 - 0.99, (i as f32 * 0.377).fract() * 1.98 - 0.99);
assert_eq!(depth.cover(Vec3::new(x, y, x * 0.9), 1.0), 1.0, "{x} {y}");
}
}
}
@@ -0,0 +1,98 @@
use std::sync::{Arc, Mutex, Weak};
use texturecraft_geom::Mesh;
use crate::fill_depth::{FillDepth, FillDepthKey};
use crate::micro_detail::AnchorHeightCache;
pub(crate) type ViewDepth = (FillDepthKey, Option<Arc<FillDepth>>);
// Each fill's grids share about 3 MiB
const MAX_CACHED_VIEWS: usize = 8;
/// Reuse projector depth maps for one mesh across tile batches.
#[derive(Default)]
pub struct ProjectorDepthCache {
mesh: Weak<Mesh>,
maps: Mutex<Vec<ViewDepth>>,
pub(crate) micro_heights: AnchorHeightCache,
}
impl ProjectorDepthCache {
pub(crate) fn bind(&mut self, mesh: &Arc<Mesh>) {
if !std::ptr::eq(self.mesh.as_ptr(), mesh.as_ref()) {
self.maps.get_mut().unwrap_or_else(|poisoned| poisoned.into_inner()).clear();
self.micro_heights = AnchorHeightCache::default();
self.mesh = Arc::downgrade(mesh);
}
}
pub(crate) fn get(&self, mesh: &Mesh, key: FillDepthKey) -> Option<Arc<FillDepth>> {
// Rasterization is serial so tile workers can wait for a single build
let mut maps = self.maps.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
if let Some(index) = maps.iter().position(|(cached_key, _)| *cached_key == key) {
let entry = maps.remove(index);
let depth = entry.1.clone();
maps.insert(0, entry);
return depth;
}
let depth = FillDepth::build(mesh, key).map(Arc::new);
maps.insert(0, (key, depth.clone()));
maps.truncate(MAX_CACHED_VIEWS);
depth
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::projector_view::ProjectorView;
use texturecraft_core::{Projection, Projector, UvTransform};
use texturecraft_geom::primitives;
#[test]
fn eviction_and_mesh_replacement_release_maps_after_the_last_reader() {
let mut cache = ProjectorDepthCache::default();
let mut mesh = Arc::new(primitives::plane(2.0, 2));
let mesh_reference = Arc::downgrade(&mesh);
let bounds = mesh.bounds();
let mut maps = Vec::new();
let mut first_reader = None;
cache.bind(&mesh);
for angle_degrees in 0..MAX_CACHED_VIEWS + 4 {
let mut projector = Projector::depth_culled();
projector.rotation[2] = angle_degrees as f32;
let projection = Projection::Planar { scale: 1.0, axis: 1, offset: [0.0; 3], uv: UvTransform::default(), projector, placed: None };
let view = ProjectorView::of(&projection, bounds).unwrap();
let map = cache.get(&mesh, (view, None)).unwrap();
let reused = cache.get(&mesh, (view, None)).unwrap();
assert!(Arc::ptr_eq(&map, &reused));
maps.push(Arc::downgrade(&map));
if angle_degrees == 0 {
first_reader = Some(map);
}
}
assert_eq!(maps.iter().filter(|map| map.upgrade().is_some()).count(), MAX_CACHED_VIEWS + 1);
drop(first_reader);
assert_eq!(maps.iter().filter(|map| map.upgrade().is_some()).count(), MAX_CACHED_VIEWS);
// Mutating a uniquely held Arc disassociates its weak references
Arc::make_mut(&mut mesh).positions[0].y += 1.0;
assert!(mesh_reference.upgrade().is_none());
cache.bind(&mesh);
assert!(maps.iter().all(|map| map.upgrade().is_none()));
let projection =
Projection::Planar { scale: 1.0, axis: 1, offset: [0.0; 3], uv: UvTransform::default(), projector: Projector::depth_culled(), placed: None };
let view = ProjectorView::of(&projection, mesh.bounds()).unwrap();
let last_map = Arc::downgrade(&cache.get(&mesh, (view, None)).unwrap());
drop(cache);
assert!(last_map.upgrade().is_none());
}
}
Loaded 100 of 779 files, more files were not shown because too many files have changed in this diff. Show more