Merge main into IOR specular reflection branch

Preserve the current export template tests and the authored Specular/Glossiness IOR regression.
This commit is contained in:
FredApps committed 2026-11-25 11:19:25 +01:00
commit 6b6d77ae4e
495 files changed
+50079 -6097

No files matched your search

+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
+12
View File
@@ -23,6 +23,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 +41,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
+668 -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).
//!
+3 -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 }
+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());
}
}
+264 -25
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>,
}
@@ -183,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.
@@ -190,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) => {
@@ -204,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());
@@ -214,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());
}
@@ -229,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);
}
@@ -240,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)]
@@ -251,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(_)));
@@ -261,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);
@@ -277,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.
@@ -298,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();
@@ -324,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]
@@ -416,6 +654,7 @@ mod tests {
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,
});
+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.
-8
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();
-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]
-18
View File
@@ -1056,24 +1056,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);
+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.inputs.values().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;
}
+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]);
}
}
+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)
}
+2915 -452
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 }
}
}
+74 -3
View File
@@ -1,10 +1,12 @@
use std::collections::HashMap;
use std::ops::Deref;
use std::sync::{Arc, Mutex};
use std::sync::{Arc, Mutex, OnceLock, PoisonError};
use texturecraft_core::{FillSymmetry, Projection, Sampling};
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::pattern::mesh_frame;
use crate::projector_depth_cache::ViewDepth;
@@ -16,12 +18,47 @@ const MAX_EVALUATION_VIEWS: usize = 10;
pub(super) struct EvaluationInputs<'a> {
inputs: &'a Inputs<'a>,
projectors: &'a ProjectorDepthCache,
environment: OnceLock<EnvironmentSh>,
instance_draws: OnceLock<HashMap<(usize, LayerId), usize>>,
depth_maps: Mutex<Vec<ViewDepth>>,
gradients: Mutex<HashMap<usize, Arc<PreparedGradient>>>,
}
impl<'a> EvaluationInputs<'a> {
pub(super) fn new(inputs: &'a Inputs<'a>, projectors: &'a ProjectorDepthCache) -> Self {
Self { inputs, projectors, depth_maps: Mutex::new(Vec::new()) }
Self {
inputs,
projectors,
environment: OnceLock::new(),
instance_draws: OnceLock::new(),
depth_maps: Mutex::new(Vec::new()),
gradients: Mutex::default(),
}
}
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>> {
@@ -49,6 +86,23 @@ impl<'a> EvaluationInputs<'a> {
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> {
@@ -58,3 +112,20 @@ impl<'a> Deref for EvaluationInputs<'a> {
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);
}
}
+21 -5
View File
@@ -1,14 +1,14 @@
//! Isolated folder evaluation with the original stack available for anchor inputs.
use super::{
Channel, ChannelKind, Composite, EvaluationInputs, Inputs, LayerId, ProjectorDepthCache, Texel, all_tiles, evaluation_fields, plan, tile_texels, to_u16,
to_u16_signed,
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 projectors = ProjectorDepthCache::default();
@@ -17,14 +17,30 @@ pub(crate) fn composite_layer(inputs: &Inputs, layer: LayerId, channel: Channel)
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()]);
+2 -1
View File
@@ -1,4 +1,4 @@
use texturecraft_core::Fill;
use texturecraft_core::{Fill, Projection};
use crate::fill_depth::FillDepth;
@@ -6,6 +6,7 @@ use crate::fill_depth::FillDepth;
#[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,
+13 -1
View File
@@ -13,6 +13,10 @@ pub mod below;
mod curvature_size_level;
pub mod curvature_sizes;
pub mod display;
mod distance_envelope;
mod effect_histogram;
pub mod environment_sh;
pub mod environment_sky;
pub mod eval;
mod fabric;
pub mod fill_copies;
@@ -23,6 +27,7 @@ pub mod frame_placement;
mod fur_lock;
mod held_fields;
mod image_identity;
mod mask_gray;
pub mod mip_level;
mod organic;
pub mod pattern;
@@ -31,6 +36,9 @@ pub mod projector_cover;
pub mod projector_depth;
mod projector_depth_cache;
pub mod projector_view;
mod shape_distance;
mod slope_texel;
mod soft_box;
pub mod solo;
pub mod store;
pub mod thumb;
@@ -39,14 +47,18 @@ mod tile_pattern;
mod tile_random_stream;
mod timber;
pub mod warp;
mod warp_source_sample;
mod warp_texel;
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,
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;
+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");
}
}
-6
View File
@@ -780,12 +780,6 @@ mod tests {
assert!((at(0.25, &exact) - blended).abs() > 1e-3, "the exact pattern is not the blend, so the coarse read shows");
}
/// A stored cylinder axis past Z (only a hand-edited project holds one) wraps round Y
#[test]
fn a_cylinder_axis_past_z_reads_as_y() {
assert_eq!([0, 1, 2, 3, u8::MAX].map(cylinder_axis_index), [0, 1, 2, 1, 1]);
}
/// 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() {
+1 -4
View File
@@ -17,14 +17,11 @@ pub struct ProjectorDepthCache {
}
impl ProjectorDepthCache {
pub(crate) fn bind(&mut self, mesh: &Arc<Mesh>) -> bool {
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.mesh = Arc::downgrade(mesh);
return true;
}
false
}
pub(crate) fn get(&self, mesh: &Mesh, key: FillDepthKey) -> Option<Arc<FillDepth>> {
+402
View File
@@ -0,0 +1,402 @@
//! Filters drawn from the distance to the shapes' edge: Bevel, Bevel Smooth and Directional Distance
use rayon::prelude::*;
use texturecraft_core::{Bevel, BevelBlur, BevelCorner, DirectionalDistance, Filter, lum};
use crate::distance_envelope::DistanceEnvelope;
use crate::eval::{MIN_ALPHA, blur};
/// From a texel's centre to the edge between it and the nearest texel across: half a texel short of their centres' distance
const EDGE_OFFSET: f32 = 0.5;
/// Components of a texel with color and coverage (red, green, blue, alpha)
const RGBA_COMPONENTS: usize = 4;
/// Color components of a texel, before its alpha
const COLOR_COMPONENTS: usize = 3;
/// Where a texel's alpha sits among its components
const ALPHA_INDEX: usize = 3;
/// What a texel becomes from its index, whether it is inside the shapes and its own value
type TexelResult<'a> = dyn Fn(usize, bool, f32) -> f32 + Sync + 'a;
/// Lay distance filter `filter` over premultiplied `data` (`width` × `height` texels of `components`; content's shapes from its luminance), `tile_resolution` texels across a UV tile, mixed in by `opacity`; its Distance Map `grays` (0..1 a texel) scales the distance texel by texel
pub(crate) fn distance_filter(
data: &mut [f32],
(cover, grays): (&[f32], &[f32]),
components: usize,
(width, height): (usize, usize),
filter: &Filter,
tile_resolution: u32,
opacity: f32,
) {
let map = |texel: usize| grays.get(texel).copied().unwrap_or(1.0);
let value = |pixel: &[f32]| match pixel {
[r, g, b, alpha] if *alpha > MIN_ALPHA => lum([r / alpha, g / alpha, b / alpha]),
[value] => *value,
_ => 0.0,
};
let shapes = |inside: &(dyn Fn(f32) -> bool + Sync)| -> Vec<bool> {
data.par_chunks(components).zip(cover.par_iter()).map(|(pixel, covered)| *covered > 0.0 && inside(value(pixel))).collect()
};
let smoothed = |field: &mut [f32], texels: f32| {
let radius = texels.round() as usize;
if radius > 0 {
blur(field, width, height, radius);
}
};
// Per texel: whether it is inside the shapes, and what it becomes from its own value
let (inside, result): (Vec<bool>, Box<TexelResult<'_>>) = match filter {
Filter::DistanceBevel(bevel) => {
let inside = shapes(&|value| value >= Bevel::EDGE);
let edge = edge_distances(&inside, (width, height), bevel.corner == BevelCorner::Angular);
let reach = bevel.reach(tile_resolution);
let mut slope: Vec<f32> = inside.par_iter().zip(edge.par_iter()).map(|(inside, edge)| bevel.slope(*inside, *edge, reach)).collect();
drop(edge);
let smoothing_radius = bevel.smoothing_texels(tile_resolution).round() as usize;
if smoothing_radius > 0 {
match bevel.blur {
BevelBlur::Uniform => blur(&mut slope, width, height, smoothing_radius),
BevelBlur::NonUniform => {
let mut blurred = slope.clone();
blur(&mut blurred, width, height, smoothing_radius);
// Keep the foot sharp and blur the top at full strength
slope.par_iter_mut().zip(blurred).for_each(|(sharp, blurred)| *sharp += (blurred - *sharp) * *sharp);
}
}
}
let bevel = *bevel;
(inside, Box::new(move |texel, inside, value| bevel.apply(inside, value, slope.get(texel).copied().unwrap_or(1.0))))
}
Filter::BevelSmooth(smooth) => {
let inside = shapes(&|value| smooth.inside(value));
let edge = edge_distances(&inside, (width, height), false);
let (reach, curve) = (smooth.reach(tile_resolution), smooth.curve());
let mut ramp: Vec<f32> = inside
.par_iter()
.zip(edge.par_iter())
.enumerate()
.map(|(texel, (inside, edge))| smooth.value(curve, *inside, *edge, reach * map(texel)))
.collect();
drop(edge);
smoothed(&mut ramp, smooth.smoothing_texels(tile_resolution));
(inside, Box::new(move |texel, _, value| ramp.get(texel).copied().unwrap_or(value)))
}
Filter::DirectionalDistance(trail) => {
let inside = shapes(&|value| value >= DirectionalDistance::EDGE);
let along = trail_distances(&inside, (width, height), crate::eval::direction(trail.angle), trail.reach(tile_resolution));
let trail = *trail;
// A share of the full reach is a larger share of a texel's shorter one; no trail where the map is black, the shapes stay
let shortened = move |texel: usize| {
along.get(texel).copied().flatten().and_then(|along| match map(texel) {
_ if along <= 0.0 => Some(0.0),
gray if gray > 0.0 => Some(along / gray),
_ => None,
})
};
(inside, Box::new(move |texel, _, _| trail.value(shortened(texel).filter(|along| *along <= 1.0))))
}
_ => return,
};
let has_alpha = components == RGBA_COMPONENTS;
data.par_chunks_mut(components).zip(inside.par_iter()).zip(cover.par_iter()).enumerate().for_each(|(texel, ((pixel, inside), covered))| {
if *covered <= 0.0 {
return;
}
// Content is premultiplied by its coverage, which stays
let coverage = if has_alpha { pixel.get(ALPHA_INDEX).copied().unwrap_or(0.0) } else { 1.0 };
for slot in pixel.iter_mut().take(components.min(COLOR_COMPONENTS)) {
let before = if has_alpha { if coverage > MIN_ALPHA { *slot / coverage } else { 0.0 } } else { *slot };
let after = result(texel, *inside, before);
*slot = (before + (after - before) * opacity) * coverage;
}
});
}
/// Every texel's distance (texels) to the edge between it and the nearest texel on the other side of the shapes `inside`: straight-line, or the larger axis distance when `angular`
fn edge_distances(inside: &[bool], (width, height): (usize, usize), angular: bool) -> Vec<f32> {
let distances = if angular { chessboard_distances } else { straight_distances };
let mut to_inside = distances(inside, (width, height), true);
let to_outside = distances(inside, (width, height), false);
to_inside
.par_iter_mut()
.zip(to_outside)
.zip(inside)
.for_each(|((to_inside, to_outside), inside)| *to_inside = (if *inside { to_outside } else { *to_inside } - EDGE_OFFSET).max(0.0));
to_inside
}
/// Each texel's straight-line distance to the nearest texel on the requested side.
fn straight_distances(inside: &[bool], (width, height): (usize, usize), target_side: bool) -> Vec<f32> {
// Start beyond the region so a line without a feature stays out of reach
let far = ((width + height) as f32).powi(2);
let mut rows: Vec<f32> = inside.iter().map(|inside| if *inside == target_side { 0.0 } else { far }).collect();
rows.par_chunks_mut(width.max(1)).for_each_init(DistanceEnvelope::default, |envelope, row| envelope.lower(row));
let mut columns: Vec<f32> = (0..width * height).map(|at| rows.get((at % height.max(1)) * width + at / height.max(1)).copied().unwrap_or(far)).collect();
columns.par_chunks_mut(height.max(1)).for_each_init(DistanceEnvelope::default, |envelope, column| envelope.lower(column));
// Reuse the row buffer for the final distances in row-major order
rows.resize(width * height, far);
for (index, distance) in rows.iter_mut().enumerate() {
*distance = columns.get((index % width.max(1)) * height + index / width.max(1)).copied().unwrap_or(far).sqrt();
}
rows
}
/// Each texel's distance to the nearest texel on the requested side, measured along the larger axis.
fn chessboard_distances(inside: &[bool], (width, height): (usize, usize), target_side: bool) -> Vec<f32> {
let far = (width + height) as f32;
let mut distances: Vec<f32> = inside.iter().map(|inside| if *inside == target_side { 0.0 } else { far }).collect();
// One pass down from the texels above and left, one up from those below and right
let step = |distances: &mut [f32], (x, y): (usize, usize), neighbours: [(isize, isize); 4]| {
let nearest = neighbours
.iter()
.filter_map(|(dx, dy)| {
let (neighbour_x, neighbour_y) = (x.checked_add_signed(*dx)?, y.checked_add_signed(*dy)?);
(neighbour_x < width && neighbour_y < height).then(|| distances.get(neighbour_y * width + neighbour_x).copied()).flatten()
})
.fold(f32::MAX, f32::min);
if let Some(slot) = distances.get_mut(y * width + x) {
*slot = slot.min(nearest + 1.0);
}
};
for y in 0..height {
for x in 0..width {
step(&mut distances, (x, y), [(-1, 0), (-1, -1), (0, -1), (1, -1)]);
}
}
for y in (0..height).rev() {
for x in (0..width).rev() {
step(&mut distances, (x, y), [(1, 0), (1, 1), (0, 1), (-1, 1)]);
}
}
distances
}
/// For every texel, how far (a share of `reach` texels) the nearest texel of the shapes `inside` lies behind it against `direction`, if one is in reach
fn trail_distances(inside: &[bool], (width, height): (usize, usize), direction: [f32; 2], reach: f32) -> Vec<Option<f32>> {
let steps = trail_steps((width, height), direction, reach);
// Each row of shapes as bits, a row without one as no words: steps landing on it find nothing
let shapes: Vec<Vec<u64>> = inside.par_chunks(width.max(1)).map(row_bits).collect();
let mut distances = vec![None; width * height];
distances.par_chunks_mut(width.max(1)).enumerate().for_each(|(y, row)| trail_row(row, y, &shapes, &steps));
distances
}
/// The texel steps back along a trail against `direction`, nearest first, each with its share of `reach`: texel coordinates are whole, so every texel takes the same steps
fn trail_steps((width, height): (usize, usize), direction: [f32; 2], reach: f32) -> Vec<(isize, isize, f32)> {
// Steps of one texel along the direction's longer axis visit every column (or row) the trail crosses, so no thin shape is stepped over
let longer_axis = direction[0].abs().max(direction[1].abs());
let samples = if reach > 0.0 && longer_axis > 0.0 { (reach * longer_axis).ceil() as usize } else { 0 };
let step = if samples > 0 { reach / samples as f32 } else { 0.0 };
let mut steps: Vec<(isize, isize, f32)> = Vec::new();
for sample in 0..=samples {
let back = sample as f32 * step;
// Rounded half up, so a whole texel coordinate added to it rounds the same; a NaN direction lands nowhere
let (across, down) = ((0.5 - direction[0] * back).floor(), (0.5 - direction[1] * back).floor());
if !(across.is_finite() && down.is_finite()) {
break;
}
// A step as long as the region leaves it from every texel, and never comes back in
let (across, down) = (across as isize, down as isize);
if across.unsigned_abs() >= width || down.unsigned_abs() >= height {
break;
}
// Rounding puts several samples on one texel: the nearest counts
if steps.last().is_some_and(|(last_across, last_down, _)| (*last_across, *last_down) == (across, down)) {
continue;
}
steps.push((across, down, if reach > 0.0 { back / reach } else { 0.0 }));
}
steps
}
/// A row of shapes as bits, [`u64::BITS`] texels a word; no words when it has none
fn row_bits(row: &[bool]) -> Vec<u64> {
if !row.contains(&true) {
return Vec::new();
}
let mut words = vec![0u64; row.len().div_ceil(WORD_BITS)];
for (word, texels) in words.iter_mut().zip(row.chunks(WORD_BITS)) {
*word = texels.iter().enumerate().filter(|(_, inside)| **inside).fold(0, |bits, (bit, _)| bits | 1 << bit);
}
words
}
/// Texels in a word of a row's bits
const WORD_BITS: usize = u64::BITS as usize;
/// Row `y`'s trail distances into `row`: a step at a time, every texel the step brings onto a shape takes its share, unless an earlier step did
fn trail_row(row: &mut [Option<f32>], y: usize, shapes: &[Vec<u64>], steps: &[(isize, isize, f32)]) {
let width = row.len();
let mut found = vec![0u64; width.div_ceil(WORD_BITS)];
let mut unfound = width;
// The last word's bits past the row's end are no texels
let last_word = found.len().saturating_sub(1);
let tail = width % WORD_BITS;
let last_word_texels = if tail > 0 { (1u64 << tail) - 1 } else { u64::MAX };
for (across, down, share) in steps {
// A step past the region's top or bottom leaves it for good
let Some(source) = y.checked_add_signed(*down).and_then(|source_y| shapes.get(source_y)) else { break };
if source.is_empty() {
continue;
}
for (word, found_word) in found.iter_mut().enumerate() {
let in_row = if word == last_word { last_word_texels } else { u64::MAX };
let landed = bits_from(source, (word * WORD_BITS) as isize + across) & !*found_word & in_row;
*found_word |= landed;
let mut remaining = landed;
while remaining != 0 {
let bit = remaining.trailing_zeros() as usize;
remaining &= remaining - 1;
if let Some(slot) = row.get_mut(word * WORD_BITS + bit) {
*slot = Some(*share);
}
unfound = unfound.saturating_sub(1);
}
}
if unfound == 0 {
break;
}
}
}
/// The [`WORD_BITS`] bits of row bits `source` from texel `start` on, none past either end
fn bits_from(source: &[u64], start: isize) -> u64 {
let bits = WORD_BITS as isize;
let (word, shift) = (start.div_euclid(bits), start.rem_euclid(bits) as u32);
let at = |index: isize| usize::try_from(index).ok().and_then(|index| source.get(index)).copied().unwrap_or(0);
let low = at(word) >> shift;
if shift == 0 { low } else { low | at(word + 1) << (u64::BITS - shift) }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn distances_are_straight_or_chessboard() {
// One feature texel in the middle of a 5 × 5 region
let mut feature = vec![false; 25];
feature[12] = true;
let straight = straight_distances(&feature, (5, 5), true);
let chessboard = chessboard_distances(&feature, (5, 5), true);
assert_eq!((straight[12], straight[13], chessboard[13]), (0.0, 1.0, 1.0));
assert!((straight[0] - 8f32.sqrt()).abs() < 1e-5, "{}", straight[0]);
assert_eq!(chessboard[0], 2.0, "a corner is as far as its larger axis");
let none = straight_distances(&[false; 4], (2, 2), true);
assert!(none.iter().all(|distance| *distance >= 4.0), "no feature is beyond the region");
}
#[test]
fn distances_keep_rows_and_columns_apart_in_a_region_wider_than_tall() {
// One feature texel at column 1, row 0 of a 7 × 3 region
let (width, height) = (7, 3);
let mut feature = vec![false; width * height];
feature[1] = true;
let straight = straight_distances(&feature, (width, height), true);
let chessboard = chessboard_distances(&feature, (width, height), true);
let at = |x: usize, y: usize| y * width + x;
assert_eq!((straight[at(1, 0)], straight[at(6, 0)], straight[at(1, 2)]), (0.0, 5.0, 2.0));
assert!((straight[at(6, 2)] - 29f32.sqrt()).abs() < 1e-5, "{}", straight[at(6, 2)]);
assert_eq!((chessboard[at(6, 0)], chessboard[at(0, 2)], chessboard[at(6, 2)]), (5.0, 2.0, 5.0));
}
#[test]
fn a_trail_finds_the_nearest_shape_behind_a_texel_as_a_share_of_its_reach() {
// A shape at column 0 of a 5 × 2 region; the trail runs towards +x, so a texel looks back towards -x
let (width, height) = (5, 2);
let inside: Vec<bool> = (0..width * height).map(|texel| texel % width == 0).collect();
let trail = trail_distances(&inside, (width, height), [1.0, 0.0], 4.0);
assert_eq!(trail[0], Some(0.0), "on the shape");
assert_eq!(trail[2], Some(0.5), "two texels behind, half the reach");
assert_eq!(trail[width + 4], Some(1.0), "at the reach's end");
}
#[test]
fn a_long_trail_steps_over_no_thin_shape() {
// A one-texel shape at column 0 of an 8 × 1 region, with a reach far longer than the region
let (width, height) = (8, 1);
let inside: Vec<bool> = (0..width * height).map(|texel| texel == 0).collect();
let reach = 128.0;
let trail = trail_distances(&inside, (width, height), [1.0, 0.0], reach);
assert_eq!(trail[3], Some(3.0 / reach), "three texels behind");
assert!(trail.iter().all(Option::is_some), "every texel behind the shape is in its trail: {trail:?}");
}
/// The trail as every texel walks it on its own, one sample at a time: what the shared steps must match
fn walked_trail_distances(inside: &[bool], (width, height): (usize, usize), direction: [f32; 2], reach: f32) -> Vec<Option<f32>> {
let longer_axis = direction[0].abs().max(direction[1].abs());
let samples = if reach > 0.0 && longer_axis > 0.0 { (reach * longer_axis).ceil() as usize } else { 0 };
let step = if samples > 0 { reach / samples as f32 } else { 0.0 };
(0..width * height)
.into_par_iter()
.map(|texel| {
let (x, y) = ((texel % width) as f32, (texel / width) as f32);
(0..=samples)
.map(|sample| {
let back = sample as f32 * step;
(back, (x - direction[0] * back + 0.5).floor(), (y - direction[1] * back + 0.5).floor())
})
.take_while(|(_, sample_x, sample_y)| *sample_x >= 0.0 && *sample_y >= 0.0 && (*sample_x as usize) < width && (*sample_y as usize) < height)
.find_map(|(back, sample_x, sample_y)| inside[sample_y as usize * width + sample_x as usize].then(|| back / reach))
})
.collect()
}
#[test]
fn shared_trail_steps_find_what_each_texel_walking_its_own_finds() {
// Sparse rows end partway through a word
// Keep the region small enough to avoid rounding nearly tied rays into different texels
let (width, height) = (150, 97);
let mut seed = 12345u32;
let inside: Vec<bool> = (0..width * height)
.map(|_| {
seed = seed.wrapping_mul(1_103_515_245).wrapping_add(12_345);
(seed >> 16) % 97 < 2
})
.collect();
for angle in [0.0, 17.0, 45.0, 90.0, 135.0, 200.0, 290.0, 333.0] {
for reach in [9.3, 60.0, 400.0] {
let direction = crate::eval::direction(angle);
let shared = trail_distances(&inside, (width, height), direction, reach);
let walked = walked_trail_distances(&inside, (width, height), direction, reach);
assert!(walked.iter().any(Option::is_some) && walked.iter().any(Option::is_none), "{angle}° {reach}: a field with texels in and out of reach");
assert_eq!(shared, walked, "{angle}° reach {reach}");
}
}
}
}
+46
View File
@@ -0,0 +1,46 @@
//! What a Blur Slope filter reads for one texel: its source's slope, then the values downhill of it
use texturecraft_core::{SlopeBlending, SourceSlopeBlur, SourceWarp};
use crate::eval::LINE_SAMPLES;
use crate::warp_source_sample::WarpSourceSample;
use crate::warp_texel::{Input, Sample, keep_extreme_read};
/// A source rising less than this across a texel is flat
const FLAT_STEEPNESS: f32 = 1e-6;
/// Blur Slope `slope` at texel `(x, y)` into `acc`: the reads downhill of it, blended
pub(crate) fn slope_texel(
slope: &SourceSlopeBlur,
(x, y): (f32, f32),
(res, comps): (u32, usize),
tile_sizes: ([u32; 2], [u32; 2]),
acc: &mut [f32; 5],
(sample, input): (Sample<'_>, Input<'_>),
) {
let source = WarpSourceSample::new(&slope.source, slope.seed, [x, y], (res, comps), tile_sizes, (sample, input));
let probe = SourceWarp::probe_texels(res);
let downhill = [source.at(x - probe, y) - source.at(x + probe, y), source.at(x, y - probe) - source.at(x, y + probe)];
let steepness = downhill[0].hypot(downhill[1]);
// A flat spot keeps its value
if steepness.is_nan() || steepness <= FLAT_STEEPNESS {
sample(x, y, acc);
return;
}
let [dx, dy] = downhill.map(|rise| rise / steepness);
let reach = slope.move_texels(res);
let read_count = slope.samples((reach.ceil() as u32).clamp(1, LINE_SAMPLES.unsigned_abs()));
let step = reach / read_count as f32;
let along = (0..=read_count).map(|read| read as f32 * step);
if slope.blending == SlopeBlending::Blur {
for t in along {
sample(x + dx * t, y + dy * t, acc);
}
return;
}
let reads = along.map(|t| (x + dx * t, y + dy * t));
keep_extreme_read(reads, slope.blending == SlopeBlending::Max, comps, acc, sample);
}
+35
View File
@@ -0,0 +1,35 @@
//! A soft rectangular light of the built-in environments
use texturecraft_geom::glam::Vec3;
/// A soft rectangular light: azimuth/elevation center (degrees), half sizes (degrees)
pub(crate) struct SoftBox {
pub azimuth: f32,
pub elevation: f32,
pub half_width: f32,
pub half_height: f32,
pub color: Vec3,
}
/// Where the light starts to fade, as a share of its half size, and over how much of it
const EDGE_FADE_START: f32 = 0.8;
const EDGE_FADE_WIDTH: f32 = 0.4;
impl SoftBox {
/// Convert the sampled direction to degrees once for all the lights
pub fn angles(direction: Vec3) -> (f32, f32) {
let elevation = direction.y.clamp(-1.0, 1.0).asin().to_degrees();
let azimuth = direction.z.atan2(direction.x).to_degrees();
(azimuth, elevation)
}
/// The light the box sends along the sampled azimuth and elevation
pub fn eval(&self, azimuth: f32, elevation: f32) -> Vec3 {
// The azimuth difference wrapped to -180..180 degrees
let azimuth_step = ((azimuth - self.azimuth + 540.0).rem_euclid(360.0)) - 180.0;
let (x, y) = (azimuth_step.abs() / self.half_width, (elevation - self.elevation).abs() / self.half_height);
let edge = |t: f32| 1.0 - crate::environment_sky::smooth((t - EDGE_FADE_START) / EDGE_FADE_WIDTH);
self.color * edge(x) * edge(y)
}
}
+6 -8
View File
@@ -114,7 +114,8 @@ mod tests {
fn solo_keeps_the_folders_around_a_layer_and_everything_inside_a_soloed_folder() {
let mut p = project();
let outside = add(&mut p, 0, LayerKind::Paint, None, false);
let folder = add(&mut p, 0, LayerKind::Group { children: Vec::new(), collapsed: false }, None, false);
let folder =
add(&mut p, 0, LayerKind::Group { children: Vec::new(), collapsed: false, contents: Default::default(), randomized: Vec::new() }, None, false);
let inner = add(&mut p, 0, LayerKind::Paint, Some(folder), true);
let sibling = add(&mut p, 0, LayerKind::Paint, Some(inner), false);
let view = solo_project(&p, inner, false).unwrap();
@@ -131,7 +132,8 @@ mod tests {
#[test]
fn ignoring_the_mask_disables_it_on_the_layer_and_its_folders_only() {
let mut p = project();
let folder = add(&mut p, 0, LayerKind::Group { children: Vec::new(), collapsed: false }, None, false);
let folder =
add(&mut p, 0, LayerKind::Group { children: Vec::new(), collapsed: false, contents: Default::default(), randomized: Vec::new() }, None, false);
let inner = add(&mut p, 0, LayerKind::Paint, Some(folder), true);
let other = add(&mut p, 0, LayerKind::Paint, None, false);
for id in [folder, inner, other] {
@@ -163,16 +165,12 @@ mod tests {
#[test]
fn a_soloed_instance_of_a_folder_keeps_the_folders_contents_drawn() {
let mut p = project();
let folder = add(&mut p, 0, LayerKind::Group { children: Vec::new(), collapsed: false }, None, false);
let folder =
add(&mut p, 0, LayerKind::Group { children: Vec::new(), collapsed: false, contents: Default::default(), randomized: Vec::new() }, None, false);
let inner = add(&mut p, 0, LayerKind::Paint, Some(folder), true);
let instance = add(&mut p, 0, LayerKind::Instance { source: folder }, None, false);
let view = solo_project(&p, instance, false).unwrap();
assert!(view.layers[&instance].visible && view.layers[&folder].visible && view.layers[&inner].visible);
}
#[test]
fn a_layer_in_no_stack_gives_nothing() {
assert!(solo_project(&project(), LayerId(99), true).is_none());
}
}
+9
View File
@@ -145,6 +145,15 @@ impl ImageRes {
bilinear(&self.rgba, self.width, self.height, u, v, (true, true))
}
/// The texel under (`u`, `v`) as stored, wrapping (an ID map's colors must not blend)
pub fn sample_nearest(&self, u: f32, v: f32) -> [f32; 4] {
if !u.is_finite() || !v.is_finite() {
return [0.0; 4];
}
self.nearest(u, v, (true, true))
}
/// The texel under (`u`, `v`), on the axes that do not `repeat` the edge texel past the edge
fn nearest(&self, u: f32, v: f32, repeat: (bool, bool)) -> [f32; 4] {
self.texel((u * self.width as f32).floor() as i64, (v * self.height as f32).floor() as i64, repeat)
+1 -1
View File
@@ -60,7 +60,7 @@ fn solo(project: &Project, texture_set: usize, id: LayerId, channel: Option<Chan
let mut cut = project.clone();
// Ordinary previews need no neighbouring layers or their filter allocations
if !project.render_tree(&[id]).iter().any(|layer| crate::eval::reads_anchor(project, *layer)) {
if !project.render_tree(&[id]).iter().any(|layer| crate::eval::reads_stack(project, *layer)) {
cut.texture_sets.get_mut(texture_set)?.stack = vec![id];
}
-5
View File
@@ -147,9 +147,4 @@ mod tests {
assert!(length[0] > 0.0, "{length:?}");
assert!(tiling_for_length(&flat, SIZE, length).unwrap()[0] > 0.0, "a written-back tiling is never 0");
}
#[test]
fn spherical_has_no_physical_size() {
assert_eq!(tile_length(&Projection::Spherical { scale: 1.0, uv: UvTransform::default(), offset: [0.0; 3], projector: Default::default() }, SIZE), None);
}
}
+127
View File
@@ -0,0 +1,127 @@
//! A warp's or slope blur's source as read around one texel
use texturecraft_core::{WarpSource, WarpSourceMode, lum};
use crate::eval::{MIN_ALPHA, texel_noise};
use crate::warp_texel::{Input, MIN_READ_WEIGHT, Sample};
/// A warp's or slope blur's source at one texel's neighbourhood
pub(crate) struct WarpSourceSample<'a> {
source: &'a WarpSource,
/// The default noise's seed
seed: u32,
res: u32,
comps: usize,
sample: Sample<'a>,
input: Input<'a>,
/// Half the texels the source is blurred across, worked out once per texel
half_blur: f32,
tiling: f32,
tile_origin: [f32; 2],
tile_size: [f32; 2],
}
impl<'a> WarpSourceSample<'a> {
/// Read the source around `texel`. Atlas blocks retain their full stride even when a UV tile has fewer texels.
pub(crate) fn new(
source: &'a WarpSource,
seed: u32,
texel: [f32; 2],
(res, comps): (u32, usize),
(block_size, tile_size): ([u32; 2], [u32; 2]),
(sample, input): (Sample<'a>, Input<'a>),
) -> Self {
let tiling = source.tiling_factor();
let tile_origin = if source.mode != WarpSourceMode::DefaultNoise && tiling != 1.0 {
std::array::from_fn(|axis| {
let stride = block_size[axis].max(1) as f32;
(texel[axis] / stride).floor() * stride
})
} else {
[0.0; 2]
};
Self {
source,
seed,
res,
comps,
sample,
input,
half_blur: source.blur_texels(res) / 2.0,
tiling,
tile_origin,
tile_size: tile_size.map(|size| size.max(1) as f32),
}
}
/// The source at texel position `(x, y)` after its blur, Balance and Contrast
pub(crate) fn at(&self, x: f32, y: f32) -> f32 {
let half = self.half_blur;
let value = if half > 0.0 {
let corners = [(-half, -half), (half, -half), (-half, half), (half, half)];
let (sum, count) = corners.iter().filter_map(|(dx, dy)| self.raw(x + dx, y + dy)).fold((0.0f32, 0u8), |(sum, count), read| (sum + read, count + 1));
if count == 0 { WarpSource::MID_GRAY } else { sum / f32::from(count) }
} else {
self.raw(x, y).unwrap_or(WarpSource::MID_GRAY)
};
self.source.shape(value)
}
/// The source at texel position `(x, y)` before it is shaped; None where the values it filters cover nothing
fn raw(&self, x: f32, y: f32) -> Option<f32> {
if self.source.mode == WarpSourceMode::DefaultNoise {
return Some(WarpSource::stretch_noise(texel_noise(x, y, [0.0; 2], self.res, self.source.noise_scale(), self.seed)));
}
let [x, y] = if self.tiling == 1.0 {
[x, y]
} else {
let repeat = |axis: usize, position: f32| {
let origin = self.tile_origin[axis];
let size = self.tile_size[axis];
let repeated = ((position - origin + 0.5) * self.tiling).rem_euclid(size) - 0.5;
// Keep the bilinear taps in this UV tile at the ends of each repeat
origin + repeated.clamp(0.0, size - 1.0)
};
[repeat(0, x), repeat(1, y)]
};
if self.source.mode == WarpSourceMode::CustomNoise {
return (self.input)(x, y);
}
let mut read = [0.0f32; 5];
(self.sample)(x, y, &mut read);
match (self.comps, read) {
// Content stays premultiplied by its own coverage
(4, [r, g, b, alpha, _]) if alpha > MIN_ALPHA => Some(lum([r / alpha, g / alpha, b / alpha])),
(1, [value, .., weight]) if weight > MIN_READ_WEIGHT => Some(value / weight),
_ => None,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn tiled_input_reads_stay_within_the_current_atlas_block() {
let source = WarpSource { mode: WarpSourceMode::CustomNoise, tiling: 2.0, ..WarpSource::LIBRARY };
let sample = |_x, _y, _read: &mut [f32; 5]| {};
let input = |x: f32, y: f32| {
assert!((64.0..=95.0).contains(&x) && (128.0..=159.0).contains(&y), "read at {x}, {y}");
Some(((x - 64.0) + (y - 128.0)) / 64.0)
};
let tiled = WarpSourceSample::new(&source, 0, [94.0, 158.0], (32, 1), ([64; 2], [32; 2]), (&sample, &input));
let first_repeat = tiled.at(69.0, 135.0);
let second_repeat = tiled.at(85.0, 151.0);
assert_eq!(first_repeat, second_repeat);
assert_ne!(tiled.at(70.0, 135.0), first_repeat);
assert!(tiled.at(63.0, 160.0).is_finite());
}
}
+80
View File
@@ -0,0 +1,80 @@
//! What a Warp filter reads for one texel: its source, then the moves its mode makes
use texturecraft_core::{SourceWarp, WarpBlending, WarpMode};
use crate::warp_source_sample::WarpSourceSample;
/// Bilinear sample at an absolute texel position into an accumulator (components, then weight), as [`crate::eval`]'s gather reads
pub(crate) type Sample<'a> = &'a dyn Fn(f32, f32, &mut [f32; 5]);
/// The filter's Custom Noise image input at an absolute texel position; None where the values it filters cover nothing
pub(crate) type Input<'a> = &'a dyn Fn(f32, f32) -> Option<f32>;
/// A read weighing less than this covers nothing
pub(crate) const MIN_READ_WEIGHT: f32 = 1e-6;
/// Warp `warp` at texel `(x, y)` into `acc`: where its source sends it, or those reads blended
pub(crate) fn warp_texel(
(warp, directions): (&SourceWarp, &[[f32; 2]]),
(x, y): (f32, f32),
(res, comps): (u32, usize),
tile_sizes: ([u32; 2], [u32; 2]),
acc: &mut [f32; 5],
(sample, input): (Sample<'_>, Input<'_>),
) {
let source = WarpSourceSample::new(&warp.source, warp.seed, [x, y], (res, comps), tile_sizes, (sample, input));
let reach = warp.move_texels(res);
if warp.mode == WarpMode::Warp {
let probe = SourceWarp::probe_texels(res);
let rise = [source.at(x + probe, y) - source.at(x - probe, y), source.at(x, y + probe) - source.at(x, y - probe)];
let [dx, dy] = warp.slope_move(rise, res);
sample(x + dx, y + dy, acc);
return;
}
let directions = directions.iter().copied();
let displacement = |at_x, at_y| SourceWarp::amount(source.at(at_x, at_y)) * reach;
if warp.mode == WarpMode::MultiDirectional && warp.blending == WarpBlending::Chain {
let (end_x, end_y) = directions.fold((x, y), |(at_x, at_y), [dx, dy]| {
let along = displacement(at_x, at_y);
(at_x + dx * along, at_y + dy * along)
});
sample(end_x, end_y, acc);
return;
}
// Independent directions share the source at the original texel
let along = displacement(x, y);
let reads = directions.map(|[dx, dy]| (x + dx * along, y + dy * along));
if warp.mode == WarpMode::MultiDirectional && matches!(warp.blending, WarpBlending::Max | WarpBlending::Min) {
keep_extreme_read(reads, warp.blending == WarpBlending::Max, comps, acc, sample);
} else {
for (at_x, at_y) in reads {
sample(at_x, at_y, acc);
}
}
}
/// Keeps in `acc` the largest (or smallest) of the reads at `positions`, component by component; reads that cover nothing are skipped
pub(crate) fn keep_extreme_read(positions: impl Iterator<Item = (f32, f32)>, larger: bool, comps: usize, acc: &mut [f32; 5], sample: Sample<'_>) {
let mut picked: Option<[f32; 5]> = None;
for (at_x, at_y) in positions {
let mut read = [0.0f32; 5];
sample(at_x, at_y, &mut read);
if read[4] <= MIN_READ_WEIGHT {
continue;
}
let read = read.map(|component| component / read[4]);
picked = Some(match picked {
Some(so_far) => std::array::from_fn(|k| if larger { so_far[k].max(read[k]) } else { so_far[k].min(read[k]) }),
None => read,
});
}
if let Some(picked) = picked {
let kept = comps.min(4);
acc[..kept].copy_from_slice(&picked[..kept]);
acc[4] = 1.0;
}
}
+369 -16
View File
@@ -4,14 +4,23 @@
use std::collections::BTreeMap;
use texturecraft_compose::{BelowCache, Composite, Inputs, PaintTarget, PixelStore, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached};
use texturecraft_compose::{
BelowCache, Composite, Inputs, MaskGray, PaintTarget, PixelStore, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached,
};
use texturecraft_core::project::ENV_RESOURCE_PREFIX;
use texturecraft_core::{
BakedMap, BlendMode, Channel, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Mask, MaskBackground,
Procedural, ProceduralKind, Project, Projection, Source, TextureSet,
BakedMap, BlendMode, Channel, ColorSelection, CompareOp, CompareSource, ContentsOffset, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind,
GrayscaleConversion, HeightMask, ImageInput, Layer, LayerId, LayerKind, Mask, MaskBackground, Procedural, ProceduralKind, Project, Projection, Source,
TextureSet,
};
use texturecraft_geom::{Mesh, UvGBuffer, primitives};
use texturecraft_texel::{TILE, TileImage, to_u16};
#[path = "cache_and_instances/blur_on.rs"]
mod blur_on;
use blur_on::BlurOn;
const RES: u32 = 256;
struct Fixture {
@@ -67,9 +76,9 @@ fn heavy_stack(f: &mut Fixture) -> LayerId {
);
let mut mask = Mask::new(MaskBackground::Black);
mask.effects.push(effect(f, EffectKind::Generator(Generator::new(GeneratorKind::Position))));
mask.effects.push(effect(f, EffectKind::Filter(Filter::Blur { radius: 40.0 })));
mask.effects.push(effect(f, EffectKind::Filter(Filter::Blur { radius: 40.0, wrap: false })));
add(f, 0, fill(&[(Channel::Roughness, procedural(ProceduralKind::Grunge, 0.0, 1.0))]), Some(mask));
let group = add(f, 0, LayerKind::Group { children: vec![], collapsed: false }, None);
let group = add(f, 0, LayerKind::Group { children: vec![], collapsed: false, contents: Default::default(), randomized: Vec::new() }, None);
for b in f.project.layer_mut(group).unwrap().channels.values_mut() {
b.mode = BlendMode::Passthrough;
}
@@ -81,7 +90,7 @@ fn heavy_stack(f: &mut Fixture) -> LayerId {
f,
EffectKind::Fill { source: procedural(ProceduralKind::Checker, 0.0, 1.0), projection: Projection::default(), sampling: Default::default() },
));
blurred.effects.push(effect(f, EffectKind::Filter(Filter::Blur { radius: 24.0 })));
blurred.effects.push(effect(f, EffectKind::Filter(Filter::Blur { radius: 24.0, wrap: false })));
let top = add(f, 0, LayerKind::Paint, Some(blurred));
let img = f.pixels.layer_mut(top, Channel::BaseColor, (RES, RES));
for y in 40..200 {
@@ -226,7 +235,7 @@ fn mask_with_height_follows_the_layer_height() {
}
fn group(f: &mut Fixture, folder: Option<LayerId>, mode: BlendMode, opacity: f32, mask: Option<Mask>) -> LayerId {
let id = put(f, 0, folder, LayerKind::Group { children: vec![], collapsed: false }, mask);
let id = put(f, 0, folder, LayerKind::Group { children: vec![], collapsed: false, contents: Default::default(), randomized: Vec::new() }, mask);
blend(f, id, mode, opacity);
id
}
@@ -246,7 +255,7 @@ fn generator_mask(f: &mut Fixture, kind: GeneratorKind, blur: Option<f32>) -> Ma
let mut mask = Mask::new(MaskBackground::Black);
mask.effects.push(effect(f, EffectKind::Generator(g)));
if let Some(radius) = blur {
mask.effects.push(effect(f, EffectKind::Filter(Filter::Blur { radius })));
mask.effects.push(effect(f, EffectKind::Filter(Filter::Blur { radius, wrap: false })));
}
mask
}
@@ -310,8 +319,8 @@ fn nested_stack(f: &mut Fixture) -> Nested {
blend(f, g2_above, BlendMode::Overlay, 0.7);
put(f, 0, Some(g2), LayerKind::Instance { source: base }, Some(Mask::new(MaskBackground::White)));
let g1_above = put(f, 0, Some(g1), fill(&[(Channel::BaseColor, procedural(ProceduralKind::Wood, 0.2, 0.8))]), None);
let hsl = effect(f, EffectKind::Filter(Filter::Hsl { hue: 0.2, saturation: 0.1, lightness: 0.0 }));
let blur = effect(f, EffectKind::Filter(Filter::Blur { radius: 20.0 }));
let hsl = effect(f, EffectKind::Filter(Filter::Hsl { hue: 0.2, saturation: 0.1, lightness: 0.0, perceptive: false }));
let blur = effect(f, EffectKind::Filter(Filter::Blur { radius: 20.0, wrap: false }));
f.project.layer_mut(g1_above).unwrap().content_effects.extend([hsl, blur]);
blend(f, g1_above, BlendMode::Screen, 0.5);
let mask = generator_mask(f, GeneratorKind::Position, Some(30.0));
@@ -338,7 +347,7 @@ fn stroke(target: LayerId) -> StrokePreview {
opacity: 0.9,
erase: false,
values: [(Channel::BaseColor, [1.0, 0.1, 0.1]), (Channel::Roughness, [0.2; 3])].into_iter().collect(),
mask_value: 1.0,
mask_gray: MaskGray::Value(1.0),
stencil: None,
carried: BTreeMap::new(),
carried_mask: None,
@@ -542,7 +551,7 @@ fn anchors_inside_a_content_stack_record_the_content_up_to_them() {
assert!(check_cached(&f, 0, top).is_empty(), "anchor readers evaluate everything");
// Behind a blur the cut reads the filtered field; before it, the unfiltered content
let blur = effect(&mut f, EffectKind::Filter(Filter::Blur { radius: 30.0 }));
let blur = effect(&mut f, EffectKind::Filter(Filter::Blur { radius: 30.0, wrap: false }));
f.project.layer_mut(low).unwrap().content_effects.insert(0, blur);
let blurred = reference(&f, 0);
assert!((blurred.value(Channel::Roughness, 128, 128)[0] - 0.2).abs() < 2e-3, "a flat height stays flat");
@@ -570,12 +579,12 @@ fn gathering_filters_composite_identically_in_any_grouping_and_cached() {
&mut f,
EffectKind::Fill { source: procedural(ProceduralKind::Checker, 0.0, 1.0), projection: Projection::default(), sampling: Default::default() },
));
slope.effects.push(effect(&mut f, EffectKind::Filter(Filter::SlopeBlur { radius: 24.0, scale: 3.0, seed: 1 })));
slope.effects.push(effect(&mut f, EffectKind::Filter(Filter::SlopeBlur { radius: 24.0, scale: 3.0, seed: 1, divider: 1 })));
let streaks = add(&mut f, 0, fill(&[(Channel::Metallic, procedural(ProceduralKind::Stripes, 0.0, 1.0))]), Some(slope));
let top = add(&mut f, 0, LayerKind::Paint, None);
paint_rect(&mut f, top, (30, 40), (150, 100), 0.4);
let plain = reference(&f, 0);
let warp = effect(&mut f, EffectKind::Filter(Filter::Warp { intensity: 30.0, scale: 4.0, seed: 3 }));
let warp = effect(&mut f, EffectKind::Filter(Filter::Warp { intensity: 30.0, scale: 4.0, seed: 3, divider: 1 }));
f.project.layer_mut(base).unwrap().content_effects.push(warp);
let line = effect(&mut f, EffectKind::Filter(Filter::DirectionalBlur { radius: 40.0, angle: 30.0 }));
f.project.layer_mut(streaks).unwrap().content_effects.push(line);
@@ -668,7 +677,8 @@ fn kept_filter_fields_are_not_used_after_an_edit_or_under_a_live_stroke() {
// Changing the hot mask must invalidate the retained fields
let mask = fixture.project.layer_mut(top).unwrap().mask.as_mut().unwrap();
mask.effects[1].kind = EffectKind::Filter(Filter::Blur { radius: 6.0 });
let blur = mask.effects.iter_mut().find(|effect| matches!(effect.kind, EffectKind::Filter(Filter::Blur { .. }))).unwrap();
blur.kind = EffectKind::Filter(Filter::Blur { radius: 6.0, wrap: false });
let (images, baked) = (Default::default(), Default::default());
cache.ahead = Vec::new();
composite_tiles_cached(&inputs(&fixture, 0, &images, &baked), &mut out, &all, Some(&mut cache));
@@ -707,7 +717,7 @@ fn tiles_the_cache_drops_during_a_kept_run_are_filtered_again() {
&mut fixture,
EffectKind::Fill { source: procedural(ProceduralKind::Checker, 0.0, 1.0), projection: Projection::default(), sampling: Default::default() },
));
blurred.effects.push(effect(&mut fixture, EffectKind::Filter(Filter::Blur { radius: 40.0 })));
blurred.effects.push(effect(&mut fixture, EffectKind::Filter(Filter::Blur { radius: 40.0, wrap: false })));
add(&mut fixture, 0, fill(&[(Channel::Roughness, procedural(ProceduralKind::Grunge, 0.0, 1.0))]), Some(blurred));
// Keep the blurred layer visible under the hot layer
@@ -917,3 +927,346 @@ fn generator_input_image_changes_invalidate_stack_key() {
assert!(key(&images) != original, "removing a generator input must invalidate the cache");
}
#[test]
fn compare_masks_reading_layers_fall_back_to_full_evaluation() {
let mut f = fixture();
let n = nested_stack(&mut f);
let compare = effect(
&mut f,
EffectKind::Compare {
op: CompareOp::GreaterThan,
value: 0.5,
tolerance: 0.0,
left: CompareSource::LayersBelow,
right: CompareSource::ThisLayer,
channel: Channel::Roughness,
hardness: 1.0,
},
);
// A mask above the hot layer compares the stack below it
f.project.layer_mut(n.g2_above).unwrap().mask.as_mut().unwrap().effects.push(compare);
for hot in [n.deep, n.top] {
assert!(check_cached(&f, 0, hot).is_empty(), "compare masks read the stack: nothing cached");
}
}
/// The key of set 0's whole stack over `images`
fn stack_key(fixture: &Fixture, images: &texturecraft_compose::ImageStore) -> texturecraft_compose::StackKey {
let roots = &fixture.project.texture_sets[0].stack;
texturecraft_compose::StackKey::new(&fixture.project, &fixture.pixels, &Default::default(), images, 0, roots).unwrap()
}
/// A flat image resource of `value`
fn flat_image(value: f32) -> std::sync::Arc<texturecraft_compose::ImageRes> {
std::sync::Arc::new(texturecraft_compose::ImageRes::new(RES, RES, vec![[value; 4]; (RES * RES) as usize], false))
}
#[test]
fn filter_input_and_id_map_image_changes_invalidate_stack_key() {
let mut fixture = fixture();
heavy_stack(&mut fixture);
let bottom_layer = fixture.project.texture_sets[0].stack[0];
let conversion = GrayscaleConversion { custom_input: true, ..GrayscaleConversion::LIBRARY };
let mut filter = effect(&mut fixture, EffectKind::Filter(Filter::GrayscaleConversion(conversion)));
filter.inputs.insert(ImageInput::CUSTOM_INPUT.id.into(), Source::image("input"));
let mut selection = ColorSelection::new(vec![[1.0, 0.0, 0.0]], 0.1);
selection.id_map = Some("id".into());
let selection = effect(&mut fixture, EffectKind::ColorSelection(selection));
let layer = fixture.project.layer_mut(bottom_layer).unwrap();
layer.content_effects.push(filter);
layer.mask = Some(Mask::new(MaskBackground::White));
layer.mask.as_mut().unwrap().effects.push(selection);
let mut images = texturecraft_compose::ImageStore::default();
images.insert("input".into(), flat_image(0.1));
images.insert("id".into(), flat_image(0.1));
for name in ["input", "id"] {
let original = stack_key(&fixture, &images);
images.insert(name.into(), flat_image(0.9));
assert!(stack_key(&fixture, &images) != original, "replacing the {name} image must invalidate the cache");
}
}
#[test]
fn the_environment_keys_the_stack_only_while_environment_lighting_reads_it() {
let mut fixture = fixture();
heavy_stack(&mut fixture);
let bottom_layer = fixture.project.texture_sets[0].stack[0];
let mut images = texturecraft_compose::ImageStore::default();
images.insert("sky".into(), flat_image(0.5));
fixture.project.display.environment = format!("{ENV_RESOURCE_PREFIX}sky");
let unlit = stack_key(&fixture, &images);
fixture.project.display.env_rotation += 90.0;
assert_eq!(stack_key(&fixture, &images), unlit, "without Baked Lighting Environment the turn changes nothing");
let lighting =
Filter::EnvironmentLighting { horizontal: 0.0, vertical: 0.0, exposure: 0.0, height_intensity: 0.0, ambient_occlusion: 0.0, specular_occlusion: 0.0 };
let lighting = effect(&mut fixture, EffectKind::Filter(lighting));
fixture.project.layer_mut(bottom_layer).unwrap().content_effects.push(lighting);
let lit = stack_key(&fixture, &images);
fixture.project.display.env_rotation += 90.0;
let turned = stack_key(&fixture, &images);
assert!(turned != lit, "turning the environment invalidates the cache");
assert_eq!(lit.changed_tiles(&turned), None, "and recomposites every tile");
images.insert("sky".into(), flat_image(0.9));
assert!(stack_key(&fixture, &images) != turned, "replacing the environment image invalidates the cache");
}
#[test]
fn painting_metallic_updates_validation_on_a_layer_above_it() {
let mut fixture = fixture();
let metal = add(&mut fixture, 0, LayerKind::Paint, None);
let color = add(&mut fixture, 0, fill(&[(Channel::BaseColor, Source::Uniform([0.12; 3]))]), None);
let color_layer = fixture.project.layer_mut(color).unwrap();
color_layer.channels.retain(|channel, _| *channel == Channel::BaseColor);
let validation = effect(&mut fixture, EffectKind::Filter(Filter::PbrValidate(texturecraft_core::PbrValidate::LIBRARY)));
fixture.project.layer_mut(color).unwrap().content_effects.push(validation);
let mut cache = BelowCache::default();
cache.set_hot(Some(metal));
let coordinate = RES / 2;
let tiles = [(coordinate / TILE, coordinate / TILE)];
let before = run(&fixture, 0, &tiles, Some(&mut cache)).value(Channel::BaseColor, coordinate, coordinate);
fixture.pixels.layer_mut(metal, Channel::Metallic, (RES, RES)).set(coordinate, coordinate, &[u16::MAX; 2]);
let fresh = run(&fixture, 0, &tiles, None).value(Channel::BaseColor, coordinate, coordinate);
let updated = run(&fixture, 0, &tiles, Some(&mut cache)).value(Channel::BaseColor, coordinate, coordinate);
assert_ne!(fresh, before, "the same color is valid for a dielectric and too dark for a metal");
assert_eq!(updated, fresh, "replaying the stack must reevaluate material-dependent validation");
}
/// A folder of set `ts` holding a Clouds fill whose content or mask is blurred by 8; returns the folder and the fill
fn folder_of_blurred_clouds(f: &mut Fixture, ts: usize, folder: Option<LayerId>, blur_on: BlurOn) -> (LayerId, LayerId) {
let held = put(f, ts, folder, LayerKind::Group { children: vec![], collapsed: false, contents: Default::default(), randomized: Vec::new() }, None);
let clouds = put(f, ts, Some(held), fill(&[(Channel::BaseColor, procedural(ProceduralKind::Clouds, 0.1, 0.9))]), None);
let blur = effect(f, EffectKind::Filter(Filter::Blur { radius: 8.0, wrap: false }));
match blur_on {
BlurOn::Content => f.project.layer_mut(clouds).unwrap().content_effects.push(blur),
BlurOn::Mask => {
let mut mask = Mask::new(MaskBackground::Black);
let checker = procedural(ProceduralKind::Checker, 0.0, 1.0);
mask.effects.push(effect(f, EffectKind::Fill { source: checker, projection: Projection::default(), sampling: Default::default() }));
mask.effects.push(blur);
f.project.layer_mut(clouds).unwrap().mask = Some(mask);
}
}
(held, clouds)
}
/// A top-level folder of set 0 laying Scale 2 and Rotation 25 on the fills inside it
fn offset_folder(f: &mut Fixture) -> LayerId {
let contents = ContentsOffset::new(2.0, 25.0);
put(f, 0, None, LayerKind::Group { children: vec![], collapsed: false, contents, randomized: Vec::new() }, None)
}
#[test]
fn a_neighbourhood_filter_in_an_instanced_folder_under_an_offset_folder_reads_its_content_in_the_instances_space() {
let mut mismatches = Vec::new();
for blur_on in [BlurOn::Content, BlurOn::Mask] {
let mut instanced = fixture();
let (source, _) = folder_of_blurred_clouds(&mut instanced, 1, None, blur_on);
let outer = offset_folder(&mut instanced);
put(&mut instanced, 0, Some(outer), LayerKind::Instance { source }, None);
let mut copied = fixture();
let outer = offset_folder(&mut copied);
folder_of_blurred_clouds(&mut copied, 0, Some(outer), blur_on);
let (instanced, copied) = (reference(&instanced, 0), reference(&copied, 0));
let texels = (0..RES).flat_map(|y| (0..RES).map(move |x| (x, y)));
let differences: Vec<f32> = texels
.map(|(x, y)| {
let (a, b) = (instanced.value(Channel::BaseColor, x, y), copied.value(Channel::BaseColor, x, y));
a.iter().zip(&b).map(|(a, b)| (a - b).abs()).fold(0.0, f32::max)
})
.filter(|difference| *difference > 1e-5)
.collect();
let largest = differences.iter().copied().fold(0.0, f32::max);
if !differences.is_empty() {
mismatches.push(format!("{blur_on:?} blur: the instance differs from the copy by up to {largest} on {} texels", differences.len()));
}
}
assert!(mismatches.is_empty(), "{}", mismatches.join("; "));
}
#[test]
fn a_hot_layer_with_a_neighbourhood_filter_in_an_instanced_folder_under_an_offset_folder_composites_exactly_cached() {
for blur_on in [BlurOn::Content, BlurOn::Mask] {
let mut instanced = fixture();
let (source, clouds) = folder_of_blurred_clouds(&mut instanced, 1, None, blur_on);
let outer = offset_folder(&mut instanced);
put(&mut instanced, 0, Some(outer), LayerKind::Instance { source }, None);
let cache = check_cached(&instanced, 0, clouds);
assert!(!cache.is_empty(), "{blur_on:?} blur: the hot layer is cached through its instance");
}
}
fn cache_after_changing_mesh(owned: bool) {
use std::sync::Arc;
use texturecraft_compose::{ProjectorDepthCache, composite_tiles_with_projectors};
let mut fixture = fixture();
let lower = add(&mut fixture, 0, fill(&[(Channel::BaseColor, Source::Uniform([1.0, 0.0, 0.0]))]), None);
fixture.project.layer_mut(lower).unwrap().geometry_mask = Some(vec!["Lid".into()]);
let hot = add(&mut fixture, 0, LayerKind::Paint, None);
let mut named = fixture.mesh.clone();
named.submeshes[0].name = "Lid".into();
let first = Arc::new(named);
let second = Arc::new(fixture.mesh.clone());
let images = Default::default();
let baked = Default::default();
let mut projectors = ProjectorDepthCache::default();
let mut cache = BelowCache::default();
cache.set_hot(Some(hot));
let mut render = |mesh: &Arc<Mesh>, cache: Option<&mut BelowCache>| {
let mut input = inputs(&fixture, 0, &images, &baked);
input.mesh = mesh;
let mut output = Composite::new(&fixture.project.texture_sets[0].channel_list(), RES);
if owned {
composite_tiles_with_projectors(&input, mesh, &mut projectors, &mut output, &[(1, 1)], cache);
} else {
composite_tiles_cached(&input, &mut output, &[(1, 1)], cache);
}
output
};
let before = render(&first, Some(&mut cache));
assert!(!cache.is_empty());
let expected = render(&second, None);
let actual = render(&second, Some(&mut cache));
assert!(before != expected, "the lower fill applies only to the named part");
assert!(actual == expected, "the previous mesh's cached fill was reused");
}
#[test]
fn a_borrowed_mesh_change_invalidates_cached_fills() {
cache_after_changing_mesh(false);
}
#[test]
fn a_projector_rebind_without_below_cache_invalidates_cached_fills() {
cache_after_changing_mesh(true);
}
fn roughness_compare(fixture: &mut Fixture, source: CompareSource) -> Effect {
effect(
fixture,
EffectKind::Compare {
op: CompareOp::GreaterThan,
value: 0.7,
tolerance: 0.0,
left: source,
right: CompareSource::Constant,
channel: Channel::Roughness,
hardness: 1.0,
},
)
}
#[test]
fn compare_uses_the_stack_below_each_draw_of_an_instanced_folder() {
let mut fixture = fixture();
let base = |roughness| fill(&[(Channel::BaseColor, Source::Uniform([0.0, 0.0, 1.0])), (Channel::Roughness, Source::Uniform([roughness; 3]))]);
add(&mut fixture, 0, base(0.2), None);
let folder = add(&mut fixture, 0, LayerKind::folder(), None);
let mut mask = Mask::new(MaskBackground::Black);
mask.effects.push(roughness_compare(&mut fixture, CompareSource::LayersBelow));
mask.effects.push(effect(&mut fixture, EffectKind::Filter(Filter::Blur { radius: 32.0, wrap: false })));
let red = fill(&[(Channel::BaseColor, Source::Uniform([1.0, 0.0, 0.0]))]);
put(&mut fixture, 0, Some(folder), red, Some(mask));
add(&mut fixture, 0, base(0.9), None);
add(&mut fixture, 0, LayerKind::Instance { source: folder }, None);
let color = run(&fixture, 0, &[(1, 1)], None).value(Channel::BaseColor, 96, 96);
assert!(color[0] > color[2], "the second draw should read the rougher surface: {color:?}");
}
#[test]
fn compare_reads_a_retained_channel_after_it_is_removed_from_the_outputs() {
let mut fixture = fixture();
let roughness = fill(&[(Channel::Roughness, Source::Uniform([0.9; 3]))]);
add(&mut fixture, 0, roughness, None);
let mut mask = Mask::new(MaskBackground::Black);
mask.effects.push(roughness_compare(&mut fixture, CompareSource::LayersBelow));
let red = fill(&[(Channel::BaseColor, Source::Uniform([1.0, 0.0, 0.0]))]);
add(&mut fixture, 0, red, Some(mask));
let before = run(&fixture, 0, &[(1, 1)], None).value(Channel::BaseColor, 96, 96);
fixture.project.texture_sets[0].channels.retain(|(channel, _)| *channel != Channel::Roughness);
let after = run(&fixture, 0, &[(1, 1)], None);
assert!(before[0] > before[1]);
assert_eq!(after.value(Channel::BaseColor, 96, 96), before);
assert!(!after.channels.contains_key(&Channel::Roughness));
}
#[test]
fn sparse_compare_mask_reads_filtered_content_through_the_full_blur_radius() {
use texturecraft_compose::{mask_texels, mask_values};
const SIZE: u32 = 512;
let mut fixture = fixture();
fixture.mesh = primitives::plane(2.0, 2);
fixture.gbuf = UvGBuffer::new(&fixture.mesh, 0, SIZE, SIZE);
fixture.project.texture_sets[0] = TextureSet::new("Plane", 0, SIZE);
let mut mask = Mask::new(MaskBackground::Black);
mask.effects.push(roughness_compare(&mut fixture, CompareSource::ThisLayer));
mask.effects.push(effect(&mut fixture, EffectKind::Filter(Filter::Blur { radius: 256.0, wrap: false })));
let roughness = fill(&[(Channel::Roughness, Source::Uniform([0.9; 3]))]);
let layer = add(&mut fixture, 0, roughness, Some(mask));
let edge = effect(&mut fixture, EffectKind::Filter(Filter::EdgeDetect { width: 8.0 }));
fixture.project.layer_mut(layer).unwrap().content_effects.push(edge);
let (images, baked) = (Default::default(), Default::default());
let center = SIZE / 2;
for (wrap, x) in [(false, center), (true, 0)] {
let EffectKind::Filter(Filter::Blur { wrap: enabled, .. }) =
&mut fixture.project.layer_mut(layer).unwrap().mask.as_mut().unwrap().effects.last_mut().unwrap().kind
else {
panic!("expected blur")
};
*enabled = wrap;
let inputs = inputs(&fixture, 0, &images, &baked);
let full = mask_texels(&inputs, layer).unwrap();
let tile = mask_values(&inputs, layer, &[(x / TILE, center / TILE)]).unwrap();
assert_eq!(tile.get(x, center)[0], to_u16(full[(center * SIZE + x) as usize]), "wrap={wrap}");
}
}
#[test]
fn a_folder_thumbnail_reads_compare_inputs_from_its_backdrop() {
use texturecraft_compose::{ThumbTarget, thumb};
let mut fixture = fixture();
let backdrop = fill(&[(Channel::Roughness, Source::Uniform([0.9; 3])), (Channel::BaseColor, Source::Uniform([0.0, 0.0, 1.0]))]);
add(&mut fixture, 0, backdrop, None);
let folder = add(&mut fixture, 0, LayerKind::folder(), None);
let mut mask = Mask::new(MaskBackground::Black);
mask.effects.push(roughness_compare(&mut fixture, CompareSource::LayersBelow));
put(&mut fixture, 0, Some(folder), fill(&[(Channel::BaseColor, Source::Uniform([1.0, 0.0, 0.0]))]), Some(mask));
let (images, baked) = (Default::default(), Default::default());
let inputs = inputs(&fixture, 0, &images, &baked);
let thumbnail = thumb::render(&inputs, ThumbTarget::Content { layer: folder, channel: Channel::BaseColor }).unwrap();
let center = 4 * (96 * RES + 96) as usize;
assert!(thumbnail.rgba[center] > thumbnail.rgba[center + 2], "visible red child");
}
@@ -0,0 +1,6 @@
/// Which stack contains a blur in the instanced-folder fixture.
#[derive(Clone, Copy, Debug)]
pub(super) enum BlurOn {
Content,
Mask,
}
+92
View File
@@ -0,0 +1,92 @@
//! Anisotropic Kuwahara's settings: a painterly smoothing that follows the direction of the strokes
use serde::{Deserialize, Serialize};
/// An Anisotropic Kuwahara filter: each texel takes the mean of the calmest sector of an ellipse turned along the local direction
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AnisotropicKuwahara {
/// Extract Direction Custom Input: the direction comes from the filter's Custom Input instead of the channel
pub custom_input: bool,
/// Texels at 2K the ellipse reaches (0..10)
pub radius: f32,
/// How much neighbouring sectors overlap (0 = hard sector edges)
pub smoothness: f32,
/// How strongly the calmest sector wins over the others (0.25..1)
pub sharpness: f32,
/// How far around a texel its direction is averaged, as a share of the radius
pub tensor_smoothness: f32,
/// How much the ellipse stretches along the direction where the direction is clear (0 = a circle)
pub anisotropy: f32,
/// Degrees the ellipse turns from the extracted direction
pub angle: f32,
}
impl AnisotropicKuwahara {
/// A new Anisotropic Kuwahara
pub const LIBRARY: AnisotropicKuwahara =
AnisotropicKuwahara { custom_input: false, radius: 5.0, smoothness: 0.25, sharpness: 0.25, tensor_smoothness: 0.1, anisotropy: 1.0, angle: 0.0 };
/// The largest Radius, in texels at 2K
pub const MAX_RADIUS: f32 = 10.0;
/// The least Sharpness
pub const MIN_SHARPNESS: f32 = 0.25;
/// Sectors the ellipse is split into
pub const SECTORS: usize = 8;
/// The sector weighing exponent at a Sharpness of 0 and of 1 (Sharpness stops at [`Self::MIN_SHARPNESS`], so the least it weighs with is 5.5)
const SHARPNESS_EXPONENT_MIN: f32 = 2.0;
const SHARPNESS_EXPONENT_MAX: f32 = 16.0;
/// The sample falloff exponent at no Smoothness (1 at full Smoothness)
const SECTOR_EXPONENT_MAX: f32 = 16.0;
/// How far around a texel its direction is read, as a share of the radius (Tensor Smoothness, 0..1)
pub fn tensor_reach(&self) -> f32 {
if self.tensor_smoothness.is_finite() { self.tensor_smoothness.clamp(0.0, 1.0) } else { Self::LIBRARY.tensor_smoothness }
}
/// The exponent a sector's spread is weighed with: higher picks the calmest sector more sharply
pub fn sharpness_exponent(&self) -> f32 {
let sharpness = if self.sharpness.is_finite() { self.sharpness.clamp(Self::MIN_SHARPNESS, 1.0) } else { Self::LIBRARY.sharpness };
Self::SHARPNESS_EXPONENT_MIN + sharpness * (Self::SHARPNESS_EXPONENT_MAX - Self::SHARPNESS_EXPONENT_MIN)
}
/// How sharply a sample's weight falls off away from a sector's middle: smoother sectors overlap more
pub fn sector_exponent(&self) -> f32 {
let smoothness = if self.smoothness.is_finite() { self.smoothness.clamp(0.0, 1.0) } else { Self::LIBRARY.smoothness };
1.0 + (1.0 - smoothness) * (Self::SECTOR_EXPONENT_MAX - 1.0)
}
/// The ellipse's semi-axes (along, across the direction) for `radius` texels where the direction is `clear` (0..1)
pub fn axes(&self, radius: f32, clear: f32) -> (f32, f32) {
let stretch = if self.anisotropy.is_finite() { self.anisotropy.clamp(0.0, 1.0) } else { Self::LIBRARY.anisotropy } * clear.clamp(0.0, 1.0);
(radius * (1.0 + stretch), radius / (1.0 + stretch))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_clear_direction_stretches_the_ellipse() {
let filter = AnisotropicKuwahara::LIBRARY;
assert_eq!(filter.axes(4.0, 0.0), (4.0, 4.0));
assert_eq!(filter.axes(4.0, 1.0), (8.0, 2.0));
assert_eq!(AnisotropicKuwahara { anisotropy: 0.0, ..filter }.axes(4.0, 1.0), (4.0, 4.0));
assert!(AnisotropicKuwahara { sharpness: 1.0, ..filter }.sharpness_exponent() > filter.sharpness_exponent());
assert!(AnisotropicKuwahara { smoothness: 1.0, ..filter }.sector_exponent() < filter.sector_exponent());
}
#[test]
fn sharpness_weighs_on_a_line_from_its_exponent_at_0_to_its_exponent_at_1() {
let at = |sharpness: f32| AnisotropicKuwahara { sharpness, ..AnisotropicKuwahara::LIBRARY }.sharpness_exponent();
assert_eq!(at(AnisotropicKuwahara::MIN_SHARPNESS), 5.5, "the least Sharpness, a quarter of the way along");
assert_eq!(at(0.0), 5.5, "below the least, the least");
assert_eq!(at(1.0), 16.0, "the most Sharpness weighs with the most exponent");
}
}
+98
View File
@@ -0,0 +1,98 @@
//! The Bevel filter's settings and the slope it gives a shape's edge
use serde::{Deserialize, Serialize};
use crate::{BevelBlur, BevelCorner, SIZE_REFERENCE_RES};
/// Shapes (values at or above [`Bevel::EDGE`]) sloped at their edge: inwards for a negative distance, outwards for a positive one
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Bevel {
/// Reads past the texture's edges from the far side (Bevel Wrap)
pub wrap: bool,
/// How far the slope reaches from the edge, a fraction of the UV tile: inwards below 0, outwards above (−1..1)
pub distance: f32,
pub corner: BevelCorner,
/// How much the slope is blurred (0..5, [`Bevel::SMOOTHING_TEXELS`] texels at 2K each)
pub smoothing: f32,
pub blur: BevelBlur,
}
impl Bevel {
/// The Bevel filter as the library adds it
pub const LIBRARY: Bevel = Bevel { wrap: false, distance: -0.1, corner: BevelCorner::Round, smoothing: 0.0, blur: BevelBlur::NonUniform };
/// Values at or above it are inside the shapes
pub const EDGE: f32 = 0.5;
/// Texels at 2K a unit of Smoothing blurs over
pub const SMOOTHING_TEXELS: f32 = 4.0;
/// The largest Smoothing
pub const SMOOTHING_MAX: f32 = 5.0;
/// Whether the slope lies inside the shapes
pub fn inward(&self) -> bool {
self.distance <= 0.0 || self.distance.is_nan()
}
/// How many texels the slope reaches at `res` texels across a UV tile
pub fn reach(&self, res: u32) -> f32 {
let distance = if self.distance.is_finite() { self.distance.abs().min(1.0) } else { 0.0 };
distance * res as f32
}
/// How many texels the slope is blurred over at `res` texels across a UV tile
pub fn smoothing_texels(&self, res: u32) -> f32 {
let smoothing = if self.smoothing.is_finite() { self.smoothing.clamp(0.0, Self::SMOOTHING_MAX) } else { 0.0 };
smoothing * Self::SMOOTHING_TEXELS * res as f32 / SIZE_REFERENCE_RES
}
/// The slope (0..1) at a texel `edge` texels from the shapes' edge, inside them or not, rising from 0 at its foot to 1 at its top
pub fn slope(&self, inside: bool, edge: f32, reach: f32) -> f32 {
let along = if reach > 0.0 && edge.is_finite() { (edge / reach).clamp(0.0, 1.0) } else { 1.0 };
match (self.inward(), inside) {
(true, true) => along,
(false, false) => 1.0 - along,
(true, false) => 0.0,
(false, true) => 1.0,
}
}
/// The result at a texel of `value`, inside the shapes or not, on `slope`: an inward slope scales the shapes, an outward one rises around them
pub fn apply(&self, inside: bool, value: f32, slope: f32) -> f32 {
match (self.inward(), inside) {
(true, true) => value * slope,
(false, false) => value.max(slope),
_ => value,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_negative_distance_slopes_inwards_and_a_positive_one_outwards() {
let inward = Bevel::LIBRARY;
assert_eq!(inward.reach(2048), 204.8);
assert_eq!((inward.slope(true, 0.0, 10.0), inward.slope(true, 5.0, 10.0), inward.slope(true, 20.0, 10.0)), (0.0, 0.5, 1.0));
assert_eq!(inward.apply(true, 0.8, 0.5), 0.4, "inside, scaled down towards the edge");
assert_eq!(inward.apply(false, 0.3, 0.0), 0.3, "outside untouched");
let outward = Bevel { distance: 0.1, ..inward };
assert_eq!((outward.slope(false, 0.0, 10.0), outward.slope(false, 5.0, 10.0), outward.slope(false, 20.0, 10.0)), (1.0, 0.5, 0.0));
assert_eq!(outward.apply(false, 0.2, 0.5), 0.5, "rises around the shapes");
assert_eq!(outward.apply(true, 0.7, 1.0), 0.7, "inside untouched");
}
#[test]
fn hostile_settings_stay_in_range() {
let bevel = Bevel { distance: f32::NAN, smoothing: f32::INFINITY, ..Bevel::LIBRARY };
assert_eq!((bevel.reach(2048), bevel.smoothing_texels(2048)), (0.0, 0.0));
assert_eq!(bevel.slope(true, 3.0, 0.0), 1.0, "no reach leaves the shapes whole");
let excessive = Bevel { distance: -9.0, smoothing: 9.0, ..bevel };
assert_eq!(excessive.reach(1024), 1024.0);
assert_eq!(excessive.smoothing_texels(2048), Bevel::SMOOTHING_MAX * Bevel::SMOOTHING_TEXELS, "smoothing stops at its largest");
}
}
+35
View File
@@ -0,0 +1,35 @@
//! How a Bevel's Smoothing spreads over its slope
use serde::{Deserialize, Serialize};
/// Where a Bevel's Smoothing blurs its slope
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum BevelBlur {
/// Sharp at the slope's foot, smoother towards its top
#[default]
NonUniform,
/// The same blur over the whole slope
Uniform,
}
impl BevelBlur {
/// Every blur mode, in the order a switch shows them
pub const ALL: [BevelBlur; 2] = [BevelBlur::NonUniform, BevelBlur::Uniform];
/// The name a panel shows
pub fn label(self) -> &'static str {
match self {
BevelBlur::NonUniform => "Non-Uniform",
BevelBlur::Uniform => "Uniform",
}
}
/// The id `effect.set {blurMode}` takes
pub fn id(self) -> &'static str {
match self {
BevelBlur::NonUniform => "nonUniform",
BevelBlur::Uniform => "uniform",
}
}
}
+35
View File
@@ -0,0 +1,35 @@
//! The shape a Bevel gives the corners it rounds off
use serde::{Deserialize, Serialize};
/// How a Bevel measures the distance from a shape's edge, which shows at its corners
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum BevelCorner {
/// Straight-line distance: corners the bevel goes around come out round
#[default]
Round,
/// The larger of the horizontal and vertical distance: corners stay square
Angular,
}
impl BevelCorner {
/// Every corner type, in the order a switch shows them
pub const ALL: [BevelCorner; 2] = [BevelCorner::Round, BevelCorner::Angular];
/// The name a panel shows
pub fn label(self) -> &'static str {
match self {
BevelCorner::Round => "Round",
BevelCorner::Angular => "Angular",
}
}
/// The id `effect.set {cornerType}` takes
pub fn id(self) -> &'static str {
match self {
BevelCorner::Round => "round",
BevelCorner::Angular => "angular",
}
}
}
+39
View File
@@ -0,0 +1,39 @@
//! Which side of a shape's edge a Bevel Smooth ramps on
use serde::{Deserialize, Serialize};
/// The side of the edge a Bevel Smooth's ramp lies on
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum BevelDirection {
/// From the edge outwards, the shapes staying white
#[default]
Out,
/// From the edge inwards, around the shapes staying black
In,
/// Across the edge, mid gray on it
InOut,
}
impl BevelDirection {
/// Every direction, in the order a switch shows them
pub const ALL: [BevelDirection; 3] = [BevelDirection::Out, BevelDirection::In, BevelDirection::InOut];
/// The name a panel shows
pub fn label(self) -> &'static str {
match self {
BevelDirection::Out => "Out",
BevelDirection::In => "In",
BevelDirection::InOut => "In/Out",
}
}
/// The id `effect.set {direction}` takes
pub fn id(self) -> &'static str {
match self {
BevelDirection::Out => "out",
BevelDirection::In => "in",
BevelDirection::InOut => "inOut",
}
}
}
+117
View File
@@ -0,0 +1,117 @@
//! The Bevel Smooth filter's settings and the ramp it draws from a shape's edge
use serde::{Deserialize, Serialize};
use crate::{BevelDirection, RampCurve, SIZE_REFERENCE_RES, at_or_above_threshold, finite_unit};
/// A smooth ramp from the edge of the shapes (values at or above `threshold`), outwards, inwards or across it
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BevelSmooth {
pub direction: BevelDirection,
/// How far the ramp reaches from the edge, a fraction of the UV tile (0..0.3)
pub distance: f32,
/// How much the ramp is blurred (0..10, [`BevelSmooth::SMOOTHING_TEXELS`] texels at 2K each)
pub smoothing: f32,
/// Moves the ramp up or down before its curve (−1..1)
pub curve_offset: f32,
/// Bends the ramp: below 0 it rises later, above 0 sooner (−1..1)
pub curve_shape: f32,
/// Values at or above it are inside the shapes (Mask Threshold, 0..1)
pub threshold: f32,
/// Scales the distance (Distance Map Multiplier, 0..1)
pub multiplier: f32,
/// Reads past the texture's edges from the far side (Bevel Wrap)
pub wrap: bool,
}
impl BevelSmooth {
/// The Bevel Smooth filter as the library adds it
pub const LIBRARY: BevelSmooth = BevelSmooth {
direction: BevelDirection::Out,
distance: 0.1,
smoothing: 1.0,
curve_offset: 0.0,
curve_shape: 0.0,
threshold: 0.5,
multiplier: 1.0,
wrap: false,
};
/// Texels at 2K a unit of Smoothing blurs over
pub const SMOOTHING_TEXELS: f32 = 2.0;
/// The largest Smoothing
pub const SMOOTHING_MAX: f32 = 10.0;
/// Whether `value` is inside the shapes
pub fn inside(&self, value: f32) -> bool {
at_or_above_threshold(value, self.threshold, Self::LIBRARY.threshold)
}
/// How many texels the ramp reaches at `res` texels across a UV tile
pub fn reach(&self, res: u32) -> f32 {
finite_unit(self.distance) * finite_unit(self.multiplier) * res as f32
}
/// How many texels the ramp is blurred over at `res` texels across a UV tile
pub fn smoothing_texels(&self, res: u32) -> f32 {
let smoothing = if self.smoothing.is_finite() { self.smoothing.clamp(0.0, Self::SMOOTHING_MAX) } else { 0.0 };
smoothing * Self::SMOOTHING_TEXELS * res as f32 / SIZE_REFERENCE_RES
}
/// The curve the ramp takes (Curve Offset and Curve Shape), worked out once per filter
pub fn curve(&self) -> RampCurve {
RampCurve::new(self.curve_offset, self.curve_shape)
}
/// The ramp at a texel `edge` texels from the shapes' edge, inside them or not, bent by [`BevelSmooth::curve`]
pub fn value(&self, curve: RampCurve, inside: bool, edge: f32, reach: f32) -> f32 {
let along = if reach > 0.0 && edge.is_finite() { (edge / reach).clamp(0.0, 1.0) } else { 1.0 };
let curved = curve.apply(along);
match (self.direction, inside) {
(BevelDirection::Out, true) => 1.0,
(BevelDirection::Out, false) => 1.0 - curved,
(BevelDirection::In, true) => curved,
(BevelDirection::In, false) => 0.0,
(BevelDirection::InOut, true) => 0.5 + 0.5 * curved,
(BevelDirection::InOut, false) => 0.5 - 0.5 * curved,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
/// The ramp with the curve worked out as the filter does
fn ramp(filter: BevelSmooth, inside: bool, edge: f32, reach: f32) -> f32 {
filter.value(filter.curve(), inside, edge, reach)
}
#[test]
fn the_ramp_lies_on_its_direction_side() {
let out = BevelSmooth::LIBRARY;
assert_eq!(out.reach(2048), 204.8);
assert!(out.inside(0.5) && !out.inside(0.49));
assert_eq!((ramp(out, true, 3.0, 10.0), ramp(out, false, 0.0, 10.0), ramp(out, false, 5.0, 10.0), ramp(out, false, 20.0, 10.0)), (1.0, 1.0, 0.5, 0.0));
let inward = BevelSmooth { direction: BevelDirection::In, ..out };
assert_eq!((ramp(inward, false, 3.0, 10.0), ramp(inward, true, 5.0, 10.0), ramp(inward, true, 20.0, 10.0)), (0.0, 0.5, 1.0));
let both = BevelSmooth { direction: BevelDirection::InOut, ..out };
assert_eq!(
(ramp(both, true, 0.0, 10.0), ramp(both, false, 0.0, 10.0), ramp(both, true, 10.0, 10.0), ramp(both, false, 10.0, 10.0)),
(0.5, 0.5, 1.0, 0.0)
);
}
#[test]
fn curve_offset_and_shape_bend_the_ramp() {
let inward = BevelSmooth { direction: BevelDirection::In, ..BevelSmooth::LIBRARY };
assert_eq!(ramp(BevelSmooth { curve_offset: 0.25, ..inward }, true, 5.0, 10.0), 0.75);
assert!(ramp(BevelSmooth { curve_shape: 0.5, ..inward }, true, 5.0, 10.0) > 0.5, "rises sooner");
assert!(ramp(BevelSmooth { curve_shape: -0.5, ..inward }, true, 5.0, 10.0) < 0.5, "rises later");
assert_eq!(BevelSmooth { multiplier: 0.5, ..inward }.reach(2048), 102.4);
let hostile = BevelSmooth { distance: f32::NAN, curve_offset: f32::NAN, curve_shape: f32::INFINITY, threshold: f32::NAN, ..inward };
assert_eq!((hostile.reach(2048), ramp(hostile, true, 1.0, 0.0)), (0.0, 1.0));
}
}
+132
View File
@@ -0,0 +1,132 @@
//! Color Match's settings: the colors moved so a source color lands on a target color
use serde::{Deserialize, Serialize};
use crate::{SourceColorMode, TargetColorMode, oklab};
/// A Color Match filter: every color moved, in OKLab, by the step from its source color to its target color
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ColorMatch {
/// Source Color Mode: the color moved from
pub source_mode: SourceColorMode,
/// Source Color (linear), read in Source Color Mode Parameter
pub source_color: [f32; 3],
/// Target Color Mode: the color moved to
pub target_mode: TargetColorMode,
/// Target Color (linear), read in Target Color Mode Parameter
pub target_color: [f32; 3],
/// Custom Color Variation: the colors keep at most Hue, Chroma and Luma of their difference from the source
pub custom_variation: bool,
/// Hue (degrees): how far a hue may stay from the target's
pub hue: f32,
/// Chroma: how far a chroma may stay from the target's
pub chroma: f32,
/// Luma: how far a lightness may stay from the target's
pub luma: f32,
}
impl ColorMatch {
/// Mid gray (128 sRGB) in linear
const GRAY: [f32; 3] = [0.215_860_5; 3];
/// The most Hue keeps (degrees): two hues are at most half a turn apart
pub const MAX_HUE_DEGREES: f32 = 180.0;
/// The most Chroma keeps (OKLab chroma)
pub const MAX_CHROMA: f32 = 1.0;
/// The most Luma keeps (OKLab lightness, 0..1)
pub const MAX_LUMA: f32 = 1.0;
/// A new Color Match: the texture's mean moves to the target and every texel keeps all of its difference from the mean (Color Variation at its widest), so the layer keeps its pattern until a variation is lowered
pub const LIBRARY: ColorMatch = ColorMatch {
source_mode: SourceColorMode::Average,
source_color: Self::GRAY,
target_mode: TargetColorMode::Parameter,
target_color: Self::GRAY,
custom_variation: true,
hue: Self::MAX_HUE_DEGREES,
chroma: Self::MAX_CHROMA,
luma: Self::MAX_LUMA,
};
/// Linear `color` moved by the step from `source` to `target`; without Custom Color Variation it keeps all of its difference from the source, with it at most Hue, Chroma and Luma of it (all 0: the target color itself). Hostile values give the color back
pub fn apply(&self, color: [f32; 3], source: [f32; 3], target: [f32; 3]) -> [f32; 3] {
let lab = |color: [f32; 3]| oklab::from_linear(color.map(|component| component.max(0.0)));
let [lightness, a, b] = lab(color);
let [source_lightness, source_a, source_b] = lab(source);
let [target_lightness, target_a, target_b] = lab(target);
let moved = if self.custom_variation {
self.move_polar(polar([lightness, a, b]), polar([source_lightness, source_a, source_b]), polar([target_lightness, target_a, target_b]))
} else {
[target_lightness + lightness - source_lightness, target_a + a - source_a, target_b + b - source_b]
};
matched_linear(color, moved)
}
#[inline]
pub(super) fn move_polar(
&self,
[lightness, chroma, hue]: [f32; 3],
[source_lightness, source_chroma, source_hue]: [f32; 3],
[target_lightness, target_chroma, target_hue]: [f32; 3],
) -> [f32; 3] {
let limit = |value: f32, max: f32| if value.is_finite() { value.clamp(0.0, max) } else { 0.0 };
let keep = |difference: f32, max: f32| difference.clamp(-max, max);
let turn = (hue - source_hue + std::f32::consts::PI).rem_euclid(std::f32::consts::TAU) - std::f32::consts::PI;
let out_lightness = target_lightness + keep(lightness - source_lightness, limit(self.luma, Self::MAX_LUMA));
let out_chroma = (target_chroma + keep(chroma - source_chroma, limit(self.chroma, Self::MAX_CHROMA))).max(0.0);
let out_hue = target_hue + keep(turn, limit(self.hue, Self::MAX_HUE_DEGREES).to_radians());
[out_lightness, out_chroma * out_hue.cos(), out_chroma * out_hue.sin()]
}
}
pub(super) fn polar([lightness, a, b]: [f32; 3]) -> [f32; 3] {
[lightness, a.hypot(b), b.atan2(a)]
}
pub(super) fn matched_linear(original: [f32; 3], lab: [f32; 3]) -> [f32; 3] {
let out = oklab::to_linear(lab);
if out.iter().all(|value| value.is_finite()) { out.map(|value| value.clamp(0.0, 1.0)) } else { original }
}
#[cfg(test)]
mod tests {
use super::*;
fn near(a: [f32; 3], b: [f32; 3]) -> bool {
a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-3)
}
#[test]
fn the_source_color_lands_on_the_target_and_variation_is_kept_as_asked() {
let red = [0.6, 0.1, 0.05];
let blue = [0.05, 0.1, 0.6];
let lighter_red = [0.8, 0.2, 0.1];
let lightness = |color: [f32; 3]| oklab::from_linear(color)[0];
// Without Custom Color Variation every difference from the source is kept
let keep_all = ColorMatch { custom_variation: false, ..ColorMatch::LIBRARY };
let moved = keep_all.apply(lighter_red, red, blue);
assert!(near(keep_all.apply(red, red, blue), blue), "the source itself becomes the target");
assert!(lightness(moved) > lightness(blue) + 0.05, "a lighter texel stays lighter than the target");
assert!(moved[2] > moved[0], "and turns blue");
// Custom Color Variation at 0: every color is the target
let flat = ColorMatch { luma: 0.0, chroma: 0.0, hue: 0.0, ..ColorMatch::LIBRARY };
assert!(near(flat.apply(lighter_red, red, blue), blue));
// A new Color Match's widest limits keep the lightness difference again
let library = ColorMatch::LIBRARY;
assert!(lightness(library.apply(lighter_red, red, blue)) > lightness(blue) + 0.05, "a new Color Match keeps the variation");
// Luma alone: the lightness difference kept up to it
let luma_only = ColorMatch { luma: 0.02, ..flat };
let limited = lightness(luma_only.apply(lighter_red, red, blue)) - lightness(blue);
assert!((limited - 0.02).abs() < 1e-3, "lightness kept up to Luma: {limited}");
let hostile = ColorMatch { hue: f32::NAN, chroma: f32::INFINITY, luma: -1.0, ..flat };
assert!(hostile.apply([f32::NAN, 0.5, 0.5], red, blue).iter().all(|v| v.is_finite() && (0.0..=1.0).contains(v)));
}
}
+135
View File
@@ -0,0 +1,135 @@
//! A mask effect that selects the parts of an ID map whose colors are in its list
use serde::{Deserialize, Serialize};
use crate::SelectionBackground;
/// Selects ID-map colors within a tolerance: the selected parts get the output value, the rest the background
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ColorSelection {
/// The selected ID colors, as the ID map stores them
pub colors: Vec<[f32; 3]>,
/// How far each component may be from a selected color and still count as it
pub tolerance: f32,
/// The value selected parts get
#[serde(default = "full", skip_serializing_if = "is_full")]
pub output: f32,
/// 1 is a hard edge (what selections saved before hardness did); lower ramps over 1 − hardness past the tolerance
#[serde(default = "full", skip_serializing_if = "is_full")]
pub hardness: f32,
#[serde(default, skip_serializing_if = "SelectionBackground::is_default")]
pub background: SelectionBackground,
/// The image resource read as the ID map; none reads the texture set's ID mesh map
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id_map: Option<String>,
}
fn full() -> f32 {
1.0
}
/// Whether an output or hardness is what selections saved before it existed had (not saved then, so they save as they were)
fn is_full(value: &f32) -> bool {
*value == full()
}
impl ColorSelection {
/// A selection of `colors` with the defaults of a new one
pub fn new(colors: Vec<[f32; 3]>, tolerance: f32) -> ColorSelection {
ColorSelection { colors, tolerance, output: 1.0, hardness: 1.0, background: SelectionBackground::Black, id_map: None }
}
/// How much ID color `id` is selected, 0..1 (none: no ID map there)
pub fn amount(&self, id: Option<[f32; 3]>) -> f32 {
let Some(id) = id else { return 0.0 };
if self.tolerance.is_nan() || self.hardness.is_nan() {
return 0.0;
}
let distance = self
.colors
.iter()
// Carry NaN through the component maximum so a malformed color cannot match
.map(|picked| {
picked
.iter()
.zip(id)
.map(|(picked, component)| (picked - component).abs())
.fold(0.0f32, |far, gap| if gap.is_nan() || gap > far { gap } else { far })
})
.fold(f32::INFINITY, f32::min);
if !distance.is_finite() {
return 0.0;
}
let past = distance - self.tolerance;
if past <= 0.0 {
return 1.0;
}
let width = 1.0 - self.hardness.clamp(0.0, 1.0);
if width <= 0.0 { 0.0 } else { (1.0 - past / width).clamp(0.0, 1.0) }
}
/// The gray this selection gives ID color `id` and how much of it covers the mask below (a transparent background covers only the selection)
pub fn value(&self, id: Option<[f32; 3]>) -> (f32, f32) {
let amount = self.amount(id);
match self.background.value() {
Some(background) => (background + (self.output - background) * amount, 1.0),
None => (self.output, amount),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::EffectKind;
#[test]
fn a_selection_saved_before_loads_hard_on_black_from_the_mesh_map() {
let saved = r#"{"ColorSelection":{"colors":[[1.0,0.0,0.0]],"tolerance":0.1}}"#;
let EffectKind::ColorSelection(selection) = serde_json::from_str::<EffectKind>(saved).unwrap() else { panic!("not a color selection") };
assert_eq!(selection, ColorSelection::new(vec![[1.0, 0.0, 0.0]], 0.1));
assert_eq!(serde_json::to_string(&EffectKind::ColorSelection(selection)).unwrap(), saved, "it saves as it was saved");
}
#[test]
fn the_hard_edge_selects_as_before_and_softness_ramps_past_the_tolerance() {
let mut selection = ColorSelection::new(vec![[1.0, 0.0, 0.0]], 0.1);
assert_eq!(selection.value(Some([0.95, 0.05, 0.0])), (1.0, 1.0));
assert_eq!(selection.value(Some([0.8, 0.0, 0.0])), (0.0, 1.0));
assert_eq!(selection.value(None), (0.0, 1.0));
assert_eq!(selection.value(Some([f32::NAN, 0.0, 0.0])), (0.0, 1.0));
selection.hardness = 0.8;
let (ramped, _) = selection.value(Some([0.8, 0.0, 0.0]));
assert!((ramped - 0.5).abs() < 1e-5, "{ramped}");
selection.colors.clear();
assert_eq!(selection.value(Some([1.0, 0.0, 0.0])), (0.0, 1.0));
}
#[test]
fn a_nan_tolerance_or_hardness_selects_nothing() {
let mut nan_tolerance = ColorSelection::new(vec![[1.0, 0.0, 0.0]], f32::NAN);
nan_tolerance.hardness = 0.5;
let mut nan_hardness = ColorSelection::new(vec![[1.0, 0.0, 0.0]], 0.1);
nan_hardness.hardness = f32::NAN;
for selection in [nan_tolerance, nan_hardness] {
assert_eq!(selection.amount(Some([1.0, 0.0, 0.0])), 0.0, "an exact match still needs valid settings");
assert_eq!(selection.amount(Some([0.8, 0.0, 0.0])), 0.0);
}
}
#[test]
fn the_output_and_background_set_both_sides_and_transparent_covers_only_the_selection() {
let mut selection = ColorSelection::new(vec![[0.0, 0.0, 1.0]], 0.1);
selection.output = 0.25;
selection.background = SelectionBackground::White;
assert_eq!(selection.value(Some([0.0, 0.0, 1.0])), (0.25, 1.0));
assert_eq!(selection.value(Some([1.0, 1.0, 1.0])), (1.0, 1.0));
selection.background = SelectionBackground::Transparent;
assert_eq!(selection.value(Some([0.0, 0.0, 1.0])), (0.25, 1.0));
assert_eq!(selection.value(Some([1.0, 1.0, 1.0])), (0.25, 0.0));
}
}
+60
View File
@@ -0,0 +1,60 @@
//! What one side of a compare mask reads
use serde::{Deserialize, Serialize};
/// One side of a compare mask's comparison
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum CompareSource {
/// The compared channel of the stack below the layer
LayersBelow,
/// The compared channel of the layer's own content, laid over the stack below by its coverage
ThisLayer,
/// The mask so far (the effects under the compare)
ThisMask,
/// The compare's constant
Constant,
}
impl CompareSource {
/// Menu order
pub const ALL: [CompareSource; 4] = [CompareSource::LayersBelow, CompareSource::ThisLayer, CompareSource::ThisMask, CompareSource::Constant];
/// Command id
pub fn id(self) -> &'static str {
match self {
CompareSource::LayersBelow => "layersBelow",
CompareSource::ThisLayer => "thisLayer",
CompareSource::ThisMask => "thisMask",
CompareSource::Constant => "constant",
}
}
pub fn from_id(id: &str) -> Option<CompareSource> {
CompareSource::ALL.into_iter().find(|source| source.id() == id)
}
/// Reads a material channel of the stack (the layer or the layers below)
pub fn reads_stack(self) -> bool {
matches!(self, CompareSource::LayersBelow | CompareSource::ThisLayer)
}
/// The left side of compare masks saved before sources existed
pub(crate) fn saved_left() -> CompareSource {
CompareSource::ThisMask
}
/// The right side of compare masks saved before sources existed
pub(crate) fn saved_right() -> CompareSource {
CompareSource::Constant
}
/// Whether a left side reads what saved compare masks did (not saved then)
pub(crate) fn is_saved_left(&self) -> bool {
*self == CompareSource::saved_left()
}
/// Whether a right side reads what saved compare masks did (not saved then)
pub(crate) fn is_saved_right(&self) -> bool {
*self == CompareSource::saved_right()
}
}
+126
View File
@@ -0,0 +1,126 @@
//! A folder's Scale and Rotation for the fills inside it
use serde::{Deserialize, Serialize};
use crate::layer::Projection;
/// Scale and Rotation a folder lays on every fill inside it, on top of each fill's own: the tiling is multiplied by `scale` and `rotation` (degrees) is added to the fill's angle; the fills themselves never change, so dropping the offset gives each its own back
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct ContentsOffset {
pub scale: f32,
pub rotation: f32,
}
impl Default for ContentsOffset {
/// Nothing changed, as in every folder saved before folders had an offset
fn default() -> Self {
ContentsOffset::NONE
}
}
impl ContentsOffset {
/// The offset that changes nothing
pub const NONE: ContentsOffset = ContentsOffset { scale: 1.0, rotation: 0.0 };
/// The smallest and largest Scale a folder takes
pub const SCALE_RANGE: (f32, f32) = (0.01, 100.0);
/// The Rotation a folder takes, in degrees: a half turn each way
pub const ROTATION_RANGE: (f32, f32) = (-180.0, 180.0);
/// Whether the offset changes nothing
pub fn is_none(&self) -> bool {
*self == ContentsOffset::NONE
}
/// An offset with `scale` kept in [`ContentsOffset::SCALE_RANGE`] and `rotation` wrapped into [`ContentsOffset::ROTATION_RANGE`] (non-finite values change nothing)
pub fn new(scale: f32, rotation: f32) -> ContentsOffset {
let (low, high) = ContentsOffset::SCALE_RANGE;
let scale = if scale.is_finite() { scale.clamp(low, high) } else { 1.0 };
let (turn_start, turn_end) = ContentsOffset::ROTATION_RANGE;
let rotation = if rotation.is_finite() { (rotation - turn_start).rem_euclid(turn_end - turn_start) + turn_start } else { 0.0 };
ContentsOffset { scale, rotation }
}
/// The offset of a folder inside one with offset `self` (`inner` is the inner folder's own): scales multiply, rotations add, and the result stays in range however deep folders nest
pub fn then(self, inner: ContentsOffset) -> ContentsOffset {
ContentsOffset::new(self.scale * inner.scale, self.rotation + inner.rotation)
}
/// `projection` with this offset laid on its tiling and rotation (a projection stretched once over each UV tile has neither)
pub fn apply(self, projection: &Projection) -> Projection {
// A loaded offset never went through `new`
let offset = ContentsOffset::new(self.scale, self.rotation);
let mut out = projection.clone();
match &mut out {
Projection::Uv { scale, rotation, .. } => {
*scale = scale.map(|s| s * offset.scale);
*rotation += offset.rotation;
}
Projection::UvTile => {}
Projection::Triplanar { uv, .. }
| Projection::Planar { uv, .. }
| Projection::Spherical { uv, .. }
| Projection::Cylindrical { uv, .. }
| Projection::Warp { uv, .. } => {
uv.tiling = uv.tiling.map(|t| t * offset.scale);
uv.rotation += offset.rotation;
}
}
out
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::layer::UvTransform;
#[test]
fn an_offset_multiplies_the_tiling_and_adds_to_the_angle_of_every_projection() {
let offset = ContentsOffset::new(1.5, 30.0);
let uv = offset.apply(&Projection::Uv { scale: [2.0, 4.0], rotation: 10.0, offset: [0.25, 0.0] });
assert_eq!(uv, Projection::Uv { scale: [3.0, 6.0], rotation: 40.0, offset: [0.25, 0.0] });
let spherical = Projection::Spherical {
scale: 1.0,
uv: UvTransform { tiling: [2.0, 1.0], rotation: -5.0, offset: [0.0; 2] },
offset: [0.0; 3],
projector: Default::default(),
};
let Projection::Spherical { scale, uv, .. } = offset.apply(&spherical) else { panic!("expected a spherical projection") };
assert_eq!((scale, uv.tiling, uv.rotation), (1.0, [3.0, 1.5], 25.0));
assert_eq!(offset.apply(&Projection::UvTile), Projection::UvTile);
assert_eq!(ContentsOffset::NONE.apply(&spherical), spherical);
}
#[test]
fn nested_offsets_combine_and_hostile_values_are_kept_in_range() {
let both = ContentsOffset::new(2.0, 170.0).then(ContentsOffset::new(1.5, 20.0));
assert_eq!((both.scale, both.rotation), (3.0, -170.0));
assert_eq!(ContentsOffset::new(f32::NAN, f32::INFINITY), ContentsOffset::NONE);
assert_eq!(ContentsOffset::new(1e9, 190.0), ContentsOffset { scale: 100.0, rotation: -170.0 });
assert_eq!(ContentsOffset::new(-3.0, -180.0), ContentsOffset { scale: 0.01, rotation: -180.0 });
assert!(ContentsOffset::default().is_none());
}
#[test]
fn deep_nesting_and_loaded_offsets_keep_the_scale_in_range() {
let deep = (0..17).fold(ContentsOffset::NONE, |around, _| around.then(ContentsOffset::new(100.0, 0.0)));
assert_eq!(deep.scale, ContentsOffset::SCALE_RANGE.1);
let loaded: ContentsOffset = serde_json::from_str(r#"{"scale":0,"rotation":0}"#).unwrap();
let tiled = loaded.apply(&Projection::Uv { scale: [2.0, 2.0], rotation: 0.0, offset: [0.0; 2] });
assert_eq!(tiled, Projection::Uv { scale: [0.02, 0.02], rotation: 0.0, offset: [0.0; 2] }, "a loaded Scale of 0 is kept at the smallest");
}
}
+63
View File
@@ -0,0 +1,63 @@
//! How Grayscale Conversion turns a color into gray
use serde::{Deserialize, Serialize};
use crate::GrayscaleMode;
/// The gray Grayscale Conversion reads from a color: a [`GrayscaleMode`], or its own weights per component
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum ConversionMode {
/// Halfway between the lightest and darkest component
Desaturation,
/// Red, Green, Blue and Alpha times their weights, summed
#[default]
ChannelsWeights,
/// The components' mean
Average,
/// The lightest component
Max,
/// The darkest component
Min,
}
impl ConversionMode {
/// Every mode, in the order a list shows them
pub const ALL: [ConversionMode; 5] =
[ConversionMode::Desaturation, ConversionMode::ChannelsWeights, ConversionMode::Average, ConversionMode::Max, ConversionMode::Min];
/// The name a panel shows
pub fn label(self) -> &'static str {
match self {
ConversionMode::ChannelsWeights => "Channels Weights",
other => other.mode().map_or("", GrayscaleMode::label),
}
}
/// The id `effect.set {mode}` takes
pub fn id(self) -> &'static str {
match self {
ConversionMode::ChannelsWeights => "channelsWeights",
other => other.mode().map_or("", GrayscaleMode::id),
}
}
/// The gray of straight color `rgb` with coverage `alpha`, `weights` for Red, Green, Blue and Alpha
pub fn gray(self, rgb: [f32; 3], alpha: f32, weights: [f32; 4]) -> f32 {
match self.mode() {
Some(mode) => mode.gray(rgb),
None => rgb[0] * weights[0] + rgb[1] * weights[1] + rgb[2] * weights[2] + alpha * weights[3],
}
}
/// The gradient's grayscale mode this one matches (None for Channels Weights)
fn mode(self) -> Option<GrayscaleMode> {
match self {
ConversionMode::Desaturation => Some(GrayscaleMode::Desaturation),
ConversionMode::ChannelsWeights => None,
ConversionMode::Average => Some(GrayscaleMode::Average),
ConversionMode::Max => Some(GrayscaleMode::Max),
ConversionMode::Min => Some(GrayscaleMode::Min),
}
}
}
+58
View File
@@ -0,0 +1,58 @@
//! The size a cooked source (a MaterialCraft material's maps) is made at
use serde::{Deserialize, Serialize};
use crate::layer::OutputResolution;
use crate::{MAX_RESOLUTION, MIN_RESOLUTION};
/// How big a source is cooked: relative to its texture set (following it when it changes) or a fixed size
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum CookResolution {
/// The texture set's resolution times 2 to this power
Relative(i8),
/// Pixels across
Fixed(u32),
}
impl CookResolution {
/// The texture set's own resolution (Auto)
pub const TEXTURE_SET: CookResolution = CookResolution::Relative(0);
/// Powers of two a relative size may scale the texture set's by, as a generator's output resolution does
pub const FACTORS: std::ops::RangeInclusive<i8> = OutputResolution::FACTORS;
/// Pixels across for a texture set `set` pixels across: a power of two the engine can cook, else the texture set's size
pub fn size(self, set: u32) -> u32 {
let size = match self {
CookResolution::Relative(factor) => {
let factor = factor.clamp(*Self::FACTORS.start(), *Self::FACTORS.end());
if factor >= 0 { set.saturating_mul(1 << factor) } else { set >> factor.unsigned_abs() }
}
CookResolution::Fixed(size) => size,
};
if Self::cookable(size) { size } else { set }
}
/// Whether maps may be cooked `size` pixels across
pub fn cookable(size: u32) -> bool {
size.is_power_of_two() && (MIN_RESOLUTION..=MAX_RESOLUTION).contains(&size)
}
}
#[cfg(test)]
mod tests {
use super::CookResolution;
#[test]
fn sizes_follow_the_texture_set_and_stay_cookable() {
assert_eq!(CookResolution::TEXTURE_SET.size(2048), 2048);
assert_eq!(CookResolution::Relative(-1).size(2048), 1024);
assert_eq!(CookResolution::Relative(2).size(1024), 4096);
assert_eq!(CookResolution::Relative(3).size(2048), 2048, "16384 is past the largest cook");
assert_eq!(CookResolution::Relative(i8::MIN).size(1024), 128);
assert_eq!(CookResolution::Fixed(512).size(2048), 512);
assert_eq!(CookResolution::Fixed(300).size(2048), 2048);
assert_eq!(CookResolution::Fixed(u32::MAX).size(2048), 2048);
}
}
+144
View File
@@ -0,0 +1,144 @@
//! The shapes Gradient Curve remaps values through
use serde::{Deserialize, Serialize};
use crate::layer::smoothstep;
/// Stairs climbs in this many flat steps
const STAIRS_STEPS: f32 = 4.0;
/// Triangular rises and falls this many times
const TRIANGULAR_TEETH: f32 = 2.0;
/// A remap curve from 0..1 onto 0..1
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum CurvePreset {
/// A quarter circle: rises fast, then flattens
#[default]
Round,
/// A quarter circle the other way: flat, then rises fast
Pinch,
/// Four flat steps
Stairs,
EaseOut,
Ease,
EaseIn,
/// Up to the middle and back down, rounded at the top
PeakOut,
/// Up to the middle and back down in straight lines
Peak,
/// Up to the middle and back down, pointed at the top
PeakIn,
/// Half a sine wave
Bump,
/// Two humps
DoubleBump,
/// Two straight teeth
Triangular,
}
impl CurvePreset {
/// Every preset, in the order the Preset list shows them
pub const ALL: [CurvePreset; 12] = [
CurvePreset::Round,
CurvePreset::Pinch,
CurvePreset::Stairs,
CurvePreset::EaseOut,
CurvePreset::Ease,
CurvePreset::EaseIn,
CurvePreset::PeakOut,
CurvePreset::Peak,
CurvePreset::PeakIn,
CurvePreset::Bump,
CurvePreset::DoubleBump,
CurvePreset::Triangular,
];
/// The name a panel shows
pub fn label(self) -> &'static str {
match self {
CurvePreset::Round => "Round",
CurvePreset::Pinch => "Pinch",
CurvePreset::Stairs => "Stairs",
CurvePreset::EaseOut => "Ease Out",
CurvePreset::Ease => "Ease",
CurvePreset::EaseIn => "Ease In",
CurvePreset::PeakOut => "Peak Out",
CurvePreset::Peak => "Peak",
CurvePreset::PeakIn => "Peak In",
CurvePreset::Bump => "Bump",
CurvePreset::DoubleBump => "Double Bump",
CurvePreset::Triangular => "Triangular",
}
}
/// The id `effect.set {preset}` takes
pub fn id(self) -> &'static str {
match self {
CurvePreset::Round => "round",
CurvePreset::Pinch => "pinch",
CurvePreset::Stairs => "stairs",
CurvePreset::EaseOut => "easeOut",
CurvePreset::Ease => "ease",
CurvePreset::EaseIn => "easeIn",
CurvePreset::PeakOut => "peakOut",
CurvePreset::Peak => "peak",
CurvePreset::PeakIn => "peakIn",
CurvePreset::Bump => "bump",
CurvePreset::DoubleBump => "doubleBump",
CurvePreset::Triangular => "triangular",
}
}
/// The curve at `t` (clamped to 0..1; a non-finite `t` reads 0)
pub fn at(self, t: f32) -> f32 {
let t = if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 };
let peak = 1.0 - (2.0 * t - 1.0).abs();
let y = match self {
CurvePreset::Round => (1.0 - (1.0 - t) * (1.0 - t)).sqrt(),
CurvePreset::Pinch => 1.0 - (1.0 - t * t).sqrt(),
CurvePreset::Stairs => ((t * STAIRS_STEPS).floor() / (STAIRS_STEPS - 1.0)).min(1.0),
CurvePreset::EaseOut => 1.0 - (1.0 - t) * (1.0 - t),
CurvePreset::Ease => smoothstep(0.0, 1.0, t),
CurvePreset::EaseIn => t * t,
CurvePreset::PeakOut => peak.sqrt(),
CurvePreset::Peak => peak,
CurvePreset::PeakIn => peak * peak,
CurvePreset::Bump => (std::f32::consts::PI * t).sin(),
CurvePreset::DoubleBump => (2.0 * std::f32::consts::PI * t).sin().abs(),
CurvePreset::Triangular => 1.0 - ((2.0 * TRIANGULAR_TEETH * t) % 2.0 - 1.0).abs(),
};
y.clamp(0.0, 1.0)
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Samples across 0..1 that every curve is read at
const SAMPLES: usize = 64;
#[test]
fn every_preset_stays_in_range_and_reads_a_non_finite_t_as_0() {
for preset in CurvePreset::ALL {
let values: Vec<f32> = (0..=SAMPLES).map(|i| preset.at(i as f32 / SAMPLES as f32)).collect();
assert!(values.iter().all(|value| (0.0..=1.0).contains(value)), "{}", preset.id());
assert_eq!(preset.at(f32::NAN), preset.at(0.0), "{}", preset.id());
assert_eq!(preset.at(f32::INFINITY), preset.at(0.0), "{}", preset.id());
}
}
#[test]
fn stairs_has_four_levels_and_triangular_two_teeth() {
let mut levels: Vec<f32> = (0..=SAMPLES).map(|i| CurvePreset::Stairs.at(i as f32 / SAMPLES as f32)).collect();
levels.dedup();
assert_eq!(levels, [0.0, 1.0 / 3.0, 2.0 / 3.0, 1.0]);
let triangular = |t: f32| CurvePreset::Triangular.at(t);
assert_eq!([triangular(0.0), triangular(0.25), triangular(0.5), triangular(0.75), triangular(1.0)], [0.0, 1.0, 0.0, 1.0, 0.0]);
}
}
+59
View File
@@ -0,0 +1,59 @@
//! The Directional Distance filter's settings and the trail it draws from the shapes
use serde::{Deserialize, Serialize};
use crate::finite_unit;
/// A trail fading away from the shapes (values at or above [`DirectionalDistance::EDGE`]) towards `angle`
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DirectionalDistance {
/// How far the trail reaches, a fraction of the UV tile (0..0.3)
pub distance: f32,
/// Where the trail runs to, in degrees counterclockwise from the right (270 runs down)
pub angle: f32,
/// Hardens the trail's fade (0..1)
pub contrast: f32,
/// Scales the distance (Distance Map Multiplier, 0..1)
pub multiplier: f32,
}
impl DirectionalDistance {
/// The Directional Distance filter as the library adds it
pub const LIBRARY: DirectionalDistance = DirectionalDistance { distance: 0.1, angle: 270.0, contrast: 0.0, multiplier: 1.0 };
/// Values at or above it are inside the shapes
pub const EDGE: f32 = 0.5;
/// The most contrast reaches: a hard step, kept off a division by zero
const HARDEST: f32 = 0.99;
/// How many texels the trail reaches at `res` texels across a UV tile
pub fn reach(&self, res: u32) -> f32 {
finite_unit(self.distance) * finite_unit(self.multiplier) * res as f32
}
/// The trail where the nearest shape behind a texel is `along` of the reach away (0 on a shape), or none is in reach
pub fn value(&self, along: Option<f32>) -> f32 {
let Some(along) = along.filter(|along| along.is_finite()) else { return 0.0 };
let fade = 1.0 - along.clamp(0.0, 1.0);
let contrast = if self.contrast.is_finite() { self.contrast.clamp(0.0, Self::HARDEST) } else { 0.0 };
(0.5 + (fade - 0.5) / (1.0 - contrast)).clamp(0.0, 1.0)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_trail_fades_with_distance_and_contrast_hardens_it() {
let trail = DirectionalDistance::LIBRARY;
assert_eq!(trail.reach(2048), 204.8);
assert_eq!((trail.value(Some(0.0)), trail.value(Some(0.25)), trail.value(None)), (1.0, 0.75, 0.0));
let hard = DirectionalDistance { contrast: 0.5, ..trail };
assert_eq!((hard.value(Some(0.25)), hard.value(Some(0.8))), (1.0, 0.0));
let hostile = DirectionalDistance { distance: f32::NAN, contrast: f32::INFINITY, multiplier: -1.0, ..trail };
assert_eq!((hostile.reach(2048), hostile.value(Some(f32::NAN))), (0.0, 0.0));
}
}
+31
View File
@@ -0,0 +1,31 @@
//! One of Baked Lighting Stylized's extra lights
use serde::{Deserialize, Serialize};
/// A light from `azimuth` around +Y (degrees from +Z) and `elevation` above the horizon (degrees), of strength `intensity` in `color`
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct DirectionalLight {
pub azimuth: f32,
pub elevation: f32,
pub intensity: f32,
pub color: [f32; 3],
}
impl DirectionalLight {
/// An unlit white light from `azimuth`, 45 degrees up
pub const fn off(azimuth: f32) -> DirectionalLight {
DirectionalLight { azimuth, elevation: 45.0, intensity: 0.0, color: [1.0; 3] }
}
/// The unit direction toward the light
pub fn direction(&self) -> [f32; 3] {
toward(self.azimuth, self.elevation)
}
}
/// The unit direction toward a light at `azimuth` around +Y (degrees from +Z) and `elevation` above the horizon (degrees)
fn toward(azimuth: f32, elevation: f32) -> [f32; 3] {
let (sin_azimuth, cos_azimuth) = azimuth.to_radians().sin_cos();
let (sin_elevation, cos_elevation) = elevation.to_radians().sin_cos();
[cos_elevation * sin_azimuth, sin_elevation, cos_elevation * cos_azimuth]
}
+181
View File
@@ -0,0 +1,181 @@
//! Gradient's Input Transformation: how a texel becomes the position it reads on the ramp
use serde::{Deserialize, Serialize};
use crate::grayscale_mode::GrayscaleMode;
use crate::{ChannelKind, finite_unit, lum, per_unit};
/// Keep the transition finite just below full contrast
const MIN_STEEPNESS: f32 = 1e-3;
/// The balance that leaves the gray as it is
pub(crate) const NEUTRAL_BALANCE: f32 = 0.5;
/// The gray, blurred, balanced, contrasted and maybe inverted value a gradient looks up
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct GradientInput {
/// How a color becomes gray (masks and scalar channels are gray already)
pub mode: GrayscaleMode,
/// Blurs the gray before the lookup, in texels at 2K (0..16)
pub blur: f32,
/// Shifts the gray: above 0.5 lighter, below darker
pub balance: f32,
/// Steepens the gray around its middle: 1 is a hard step
pub contrast: f32,
pub invert: bool,
}
impl Default for GradientInput {
/// What gradients read in projects saved before the Input Transformation: luma, untouched
fn default() -> Self {
GradientInput { mode: GrayscaleMode::Luma, blur: 0.0, balance: NEUTRAL_BALANCE, contrast: 0.0, invert: false }
}
}
impl GradientInput {
/// The library's starting transformation: the average of the components, untouched
pub const LIBRARY: GradientInput = GradientInput { mode: GrayscaleMode::Average, blur: 0.0, balance: NEUTRAL_BALANCE, contrast: 0.0, invert: false };
/// Whether it reads gradients as projects saved before it did (skipped when saving)
pub fn is_unchanged(&self) -> bool {
*self == GradientInput::default()
}
/// The ramp position of gray `x`
pub fn shape(&self, x: f32) -> f32 {
// Preserve the exact input when the transformation is neutral
if self.balance == NEUTRAL_BALANCE && self.contrast == 0.0 && !self.invert {
return x;
}
shape_gray(x, self.balance, self.contrast, self.invert)
}
/// Apply a gradient to a channel using its ramp sampler
pub fn map(&self, kind: ChannelKind, value: [f32; 3], sample: impl Fn(f32) -> Option<[f32; 3]>) -> Option<[f32; 3]> {
if kind == ChannelKind::Color {
return sample(self.shape(self.mode.gray(value)));
}
// Preserve the signed-channel mapping and leave normals alone
Some(per_unit(kind, value, |gray| sample(self.shape(gray)).map_or(gray, lum)))
}
}
/// Gray `x` balanced (0.5 keeps it), contrasted around mid gray (0 keeps it, 1 is a step at 0.5) and maybe inverted, in 0..1
pub fn shape_gray(x: f32, balance: f32, contrast: f32, invert: bool) -> f32 {
let balanced = finite_unit(x) + finite_unit(balance) - NEUTRAL_BALANCE;
let contrast = finite_unit(contrast);
let shaped = if contrast == 1.0 {
f32::from(balanced >= NEUTRAL_BALANCE)
} else {
let steep = (1.0 - contrast).max(MIN_STEEPNESS);
finite_unit((balanced - NEUTRAL_BALANCE) / steep + NEUTRAL_BALANCE)
};
if invert { 1.0 - shaped } else { shaped }
}
/// A ramp stop's place and color
type Stop = (f32, [f32; 3]);
pub(crate) fn ramp_stops<'a>(colors: &'a [[f32; 3]], positions: &'a [f32]) -> impl ExactSizeIterator<Item = Stop> + 'a {
let last = colors.len().saturating_sub(1);
colors.iter().copied().enumerate().map(move |(index, color)| {
let even_position = || if last == 0 { 0.0 } else { index as f32 / last as f32 };
let position = positions.get(index).copied().filter(|position| position.is_finite()).unwrap_or_else(even_position);
let position = if position <= 0.0 { 0.0 } else { position.min(1.0) };
(position, color)
})
}
/// The color at `t` on a ramp of `colors` placed at `positions` (each 0..1, evenly spaced where missing), blended in linear or sRGB
pub fn ramp(colors: &[[f32; 3]], positions: &[f32], linear: bool, t: f32) -> Option<[f32; 3]> {
let stops = ramp_stops(colors, positions);
let t = if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 };
// Keep the last stop at or before the sample and the first stop after it
let (mut before, mut after): (Option<Stop>, Option<Stop>) = (None, None);
for (position, color) in stops {
if position <= t {
if before.is_none_or(|(so_far, _)| position.total_cmp(&so_far).is_ge()) {
before = Some((position, color));
}
} else if after.is_none_or(|(so_far, _)| position.total_cmp(&so_far).is_lt()) {
after = Some((position, color));
}
}
let ((before_place, before_color), (after_place, after_color)) = match (before, after) {
(Some(before), Some(after)) => (before, after),
(Some(only), None) | (None, Some(only)) => (only, only),
(None, None) => return None,
};
let encode = |color: [f32; 3]| if linear { color } else { color.map(linear_to_srgb) };
Some(interpolate((before_place, encode(before_color)), (after_place, encode(after_color)), linear, t))
}
pub(crate) fn interpolate((before_place, before_color): Stop, (after_place, after_color): Stop, linear: bool, t: f32) -> [f32; 3] {
let share = if after_place > before_place { ((t - before_place) / (after_place - before_place)).clamp(0.0, 1.0) } else { 0.0 };
let color = std::array::from_fn(|component| before_color[component] + (after_color[component] - before_color[component]) * share);
if linear { color } else { color.map(srgb_to_linear) }
}
// A copy of texturecraft_texel's: texel and core are both layer 0, so core cannot use it
/// sRGB transfer of a linear component
pub(crate) fn linear_to_srgb(v: f32) -> f32 {
let v = v.clamp(0.0, 1.0);
if v <= 0.003_130_8 { v * 12.92 } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 }
}
/// Linear value of an sRGB component
pub(crate) fn srgb_to_linear(v: f32) -> f32 {
let v = v.clamp(0.0, 1.0);
if v <= 0.040_45 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_ramp_reads_its_stops_in_place_order_whatever_their_list_order() {
let (black, gray, white) = ([0.0; 3], [0.5; 3], [1.0; 3]);
let colors = [white, black, gray];
let positions = [1.0, 0.0, 0.5];
let quarter = ramp(&colors, &positions, true, 0.25);
let ends = (ramp(&colors, &positions, true, 0.0), ramp(&colors, &positions, true, 1.0));
let past_one_stop = ramp(&[gray, white], &[0.5, 0.5], true, 0.25);
assert_eq!(ramp(&[black, white], &[0.0, -0.0], true, 0.0), Some(white));
assert_eq!(quarter, Some([0.25; 3]));
assert_eq!(ends, (Some(black), Some(white)));
assert_eq!(past_one_stop, Some(gray), "before the first stop, its color");
assert_eq!(ramp(&[], &[], true, 0.5), None);
}
#[test]
fn full_contrast_separates_neighbors_of_mid_gray() {
let below = shape_gray(0.49975, NEUTRAL_BALANCE, 1.0, false);
let above = shape_gray(0.50025, NEUTRAL_BALANCE, 1.0, false);
assert_eq!((below, above), (0.0, 1.0));
assert_eq!(shape_gray(0.50025, NEUTRAL_BALANCE, 1.0, true), below);
}
#[test]
fn an_untouched_input_passes_every_gray_on_bit_for_bit() {
const SAMPLES: u16 = 1000;
let untouched = [GradientInput::default(), GradientInput::LIBRARY];
let grays = (0..=SAMPLES).map(|step| f32::from(step) / f32::from(SAMPLES)).chain([-0.25, 1.5]);
for input in untouched {
for gray in grays.clone() {
assert_eq!(input.shape(gray).to_bits(), gray.to_bits(), "{input:?} at {gray}");
}
}
}
}
+93
View File
@@ -0,0 +1,93 @@
//! Grayscale Conversion's settings: which gray it reads and how it shapes it
use serde::{Deserialize, Serialize};
use crate::blend::lum;
use crate::gradient_input::{NEUTRAL_BALANCE, shape_gray};
use crate::layer::per_unit;
use crate::{ChannelKind, ConversionMode};
/// A Grayscale Conversion filter: the gray of the current channel (or of its Custom Input), balanced, contrasted and maybe inverted
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GrayscaleConversion {
/// Channel Input Custom Input: the gray of the filter's Custom Input instead of the channel's
pub custom_input: bool,
pub invert: bool,
pub balance: f32,
pub contrast: f32,
pub mode: ConversionMode,
/// Channels Weights' Red, Green, Blue and Alpha
pub weights: [f32; 4],
}
impl GrayscaleConversion {
/// A new Grayscale Conversion: a third of each color component, alpha left out
pub const LIBRARY: GrayscaleConversion = GrayscaleConversion {
custom_input: false,
invert: false,
balance: NEUTRAL_BALANCE,
contrast: 0.0,
mode: ConversionMode::ChannelsWeights,
weights: [0.33, 0.33, 0.33, 0.0],
};
/// The settings a Grayscale filter saved before them takes on its first edit: its luminance weights, so it looks the same
pub fn of_luminance() -> GrayscaleConversion {
let [red, green, blue] = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]].map(lum);
GrayscaleConversion { weights: [red, green, blue, 0.0], ..Self::LIBRARY }
}
/// The shaped gray of straight color `rgb` with coverage `alpha`
pub fn gray(&self, rgb: [f32; 3], alpha: f32) -> f32 {
shape_gray(self.mode.gray(rgb, alpha, self.weights), self.balance, self.contrast, self.invert)
}
/// `v` of a `kind` channel (coverage `alpha`) or `custom_input` turned gray: colors gray, scalar and signed in their range, normals as they are
pub fn channel_value(&self, kind: ChannelKind, v: [f32; 3], custom_input: Option<[f32; 3]>, alpha: f32) -> [f32; 3] {
match (kind, custom_input) {
(ChannelKind::NormalMap, _) => v,
(ChannelKind::Color, None) => [self.gray(v, alpha); 3],
(ChannelKind::Color, Some(input)) => [self.gray(input, alpha); 3],
(_, None) => per_unit(kind, v, |x| self.gray([x; 3], alpha)),
(_, Some(input)) => per_unit(kind, v, |_| self.gray(input, alpha)),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_saved_grayscale_keeps_its_luminance() {
let color = [0.8, 0.3, 0.1];
assert!((GrayscaleConversion::of_luminance().gray(color, 1.0) - lum(color)).abs() < 1e-5);
}
#[test]
fn weights_balance_contrast_and_invert_shape_the_gray() {
let only_red = GrayscaleConversion { weights: [1.0, 0.0, 0.0, 0.0], ..GrayscaleConversion::LIBRARY };
assert!((only_red.gray([0.6, 1.0, 1.0], 1.0) - 0.6).abs() < 1e-6);
let alpha = GrayscaleConversion { weights: [0.0, 0.0, 0.0, 1.0], ..GrayscaleConversion::LIBRARY };
assert!((alpha.gray([1.0; 3], 0.25) - 0.25).abs() < 1e-6, "Alpha weighs the coverage");
let inverted = GrayscaleConversion { invert: true, mode: ConversionMode::Max, ..GrayscaleConversion::LIBRARY };
assert!((inverted.gray([0.2, 0.7, 0.1], 1.0) - 0.3).abs() < 1e-6);
let contrasted = GrayscaleConversion { contrast: 1.0, mode: ConversionMode::Average, ..GrayscaleConversion::LIBRARY };
assert_eq!(contrasted.gray([0.6; 3], 1.0), 1.0);
}
#[test]
fn only_colors_turn_gray() {
let conversion = GrayscaleConversion::LIBRARY;
let height = conversion.channel_value(ChannelKind::Signed, [-0.6; 3], None, 1.0);
let normal = conversion.channel_value(ChannelKind::NormalMap, [0.2, 0.7, 0.9], None, 1.0);
assert!(height.iter().all(|x| (x + 0.6).abs() < 0.02), "a signed height keeps its sign: {height:?}");
assert_eq!(normal, [0.2, 0.7, 0.9]);
}
}
+58
View File
@@ -0,0 +1,58 @@
//! How a color becomes the gray a gradient looks up
use serde::{Deserialize, Serialize};
/// The gray a color reads as, before a gradient maps it
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum GrayscaleMode {
/// Halfway between the lightest and darkest component
Desaturation,
/// Weighted by how bright each component looks (what gradients read in projects saved before the modes)
#[default]
Luma,
/// The components' mean
Average,
/// The lightest component
Max,
/// The darkest component
Min,
}
impl GrayscaleMode {
/// Every mode, in the order a list shows them
pub const ALL: [GrayscaleMode; 5] = [GrayscaleMode::Desaturation, GrayscaleMode::Luma, GrayscaleMode::Average, GrayscaleMode::Max, GrayscaleMode::Min];
/// The name a panel shows
pub fn label(self) -> &'static str {
match self {
GrayscaleMode::Desaturation => "Desaturation",
GrayscaleMode::Luma => "Luma",
GrayscaleMode::Average => "Average",
GrayscaleMode::Max => "Max",
GrayscaleMode::Min => "Min",
}
}
/// The id `effect.set {grayscaleMode}` takes
pub fn id(self) -> &'static str {
match self {
GrayscaleMode::Desaturation => "desaturation",
GrayscaleMode::Luma => "luma",
GrayscaleMode::Average => "average",
GrayscaleMode::Max => "max",
GrayscaleMode::Min => "min",
}
}
/// The gray of linear color `[r, g, b]`
pub fn gray(self, [r, g, b]: [f32; 3]) -> f32 {
match self {
GrayscaleMode::Desaturation => (r.max(g).max(b) + r.min(g).min(b)) / 2.0,
GrayscaleMode::Luma => crate::blend::lum([r, g, b]),
GrayscaleMode::Average => (r + g + b) / 3.0,
GrayscaleMode::Max => r.max(g).max(b),
GrayscaleMode::Min => r.min(g).min(b),
}
}
}
+85
View File
@@ -0,0 +1,85 @@
//! Height To Normal's settings: the layer's Height turned into its Normal
use serde::{Deserialize, Serialize};
/// A Height To Normal filter: the normal of the slopes of the layer's Height, over or in place of its Normal
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct HeightToNormal {
/// Overwrite Existing Normal: the made normal replaces the Normal below instead of being laid over it
pub overwrite: bool,
/// Use World Units: the slope comes from Surface Size and Height Depth instead of Normal Intensity
pub world_units: bool,
/// Surface Size (cm): how wide a UV tile is on the model
pub surface_size: f32,
/// Height Depth (cm): how deep a height of 1 is
pub height_depth: f32,
/// Normal Intensity: how strongly the slopes tilt the normal without world units
pub intensity: f32,
}
impl HeightToNormal {
/// A new Height To Normal
pub const LIBRARY: HeightToNormal = HeightToNormal { overwrite: true, world_units: true, surface_size: 300.0, height_depth: 16.0, intensity: 10.0 };
/// The smallest Surface Size: whole cm, so the reference's 0.1 rounds up to 1
pub const MIN_SURFACE_SIZE: f32 = 1.0;
/// The largest Surface Size (cm)
pub const MAX_SURFACE_SIZE: f32 = 1000.0;
/// The largest Height Depth (cm)
pub const MAX_HEIGHT_DEPTH: f32 = 100.0;
/// The largest Normal Intensity
pub const MAX_INTENSITY: f32 = 50.0;
/// Height Depth over Surface Size a Normal Intensity of 1 tilts like (so the default 10 matches the default 16 cm over 300 cm)
const INTENSITY_UNIT: f32 = Self::LIBRARY.height_depth / Self::LIBRARY.surface_size / Self::LIBRARY.intensity;
/// How much a change of height per texel tilts the normal at `res` texels across a UV tile (0 for hostile values)
pub fn strength(&self, res: u32) -> f32 {
let finite = |value: f32, max: f32| if value.is_finite() { value.clamp(0.0, max) } else { 0.0 };
if self.world_units && !self.surface_size.is_finite() {
return 0.0;
}
let per_tile = if self.world_units {
finite(self.height_depth, Self::MAX_HEIGHT_DEPTH) / finite(self.surface_size, Self::MAX_SURFACE_SIZE).max(Self::MIN_SURFACE_SIZE)
} else {
finite(self.intensity, Self::MAX_INTENSITY) * Self::INTENSITY_UNIT
};
per_tile * res as f32
}
/// The unit tangent-space normal (OpenGL, +Y up the image) of a height changing by `gx` per texel to the right and `gy` per texel down
pub fn normal(&self, [gx, gy]: [f32; 2], res: u32) -> [f32; 3] {
let strength = self.strength(res);
let (x, y) = (-gx * strength, gy * strength);
let length = (x * x + y * y + 1.0).sqrt();
if length.is_finite() { [x / length, y / length, 1.0 / length] } else { [0.0, 0.0, 1.0] }
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn world_units_and_normal_intensity_tilt_the_normal_up_the_slope() {
let filter = HeightToNormal::LIBRARY;
assert_eq!(filter.normal([0.0, 0.0], 2048), [0.0, 0.0, 1.0], "a flat height");
let [x, y, z] = filter.normal([0.01, 0.0], 2048);
assert!(x < 0.0 && y == 0.0 && z > 0.0, "rising to the right faces left");
let expected = 0.01 * 16.0 / 300.0 * 2048.0;
assert!((-x / z - expected).abs() < 1e-4, "16 cm over 300 cm");
let intensity = HeightToNormal { world_units: false, ..filter };
assert!((intensity.strength(2048) - filter.strength(2048)).abs() < 1e-3, "Normal Intensity 10 matches the world default");
assert!(HeightToNormal { intensity: 20.0, ..intensity }.strength(2048) > intensity.strength(2048));
assert!(HeightToNormal { height_depth: 32.0, ..filter }.strength(2048) > filter.strength(2048));
assert_eq!(filter.normal([0.0, 0.01], 2048)[1].signum(), 1.0, "rising down the image faces up");
assert_eq!(HeightToNormal { surface_size: f32::NAN, ..filter }.strength(2048), 0.0);
let hostile = HeightToNormal { surface_size: f32::NAN, height_depth: f32::INFINITY, ..filter };
assert!(hostile.normal([1.0, 1.0], 2048).iter().all(|v| v.is_finite()));
}
}
+84
View File
@@ -0,0 +1,84 @@
//! The color space a Highpass filter works in
use serde::{Deserialize, Serialize};
use crate::gradient_input::{linear_to_srgb, srgb_to_linear};
/// ACEScg (AP1) to linear sRGB (Rec. 709) primaries, white point adapted (the published ACES matrix)
const AP1_TO_REC709: [[f32; 3]; 3] = [[1.705_05, -0.621_79, -0.083_26], [-0.130_26, 1.140_80, -0.010_55], [-0.024_00, -0.128_97, 1.152_97]];
/// Linear sRGB (Rec. 709) to ACEScg (AP1) primaries: the inverse of [`AP1_TO_REC709`]
const REC709_TO_AP1: [[f32; 3]; 3] = [[0.613_10, 0.339_52, 0.047_37], [0.070_19, 0.916_35, 0.013_45], [0.020_62, 0.109_57, 0.869_81]];
/// Where a Highpass takes its detail: in the working space (masks always), or in sRGB from linear sRGB or ACEScg colors
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum HighpassSpace {
/// The values as they are (what a Highpass did in projects saved before the Color Space)
#[default]
Working,
/// Colors read as linear sRGB, filtered sRGB encoded
SrgbFromLinear,
/// Colors read as ACEScg, filtered sRGB encoded
SrgbFromAcescg,
}
impl HighpassSpace {
/// Every space, in the order a list shows them
pub const ALL: [HighpassSpace; 3] = [HighpassSpace::Working, HighpassSpace::SrgbFromLinear, HighpassSpace::SrgbFromAcescg];
/// The name a panel shows
pub fn label(self) -> &'static str {
match self {
HighpassSpace::Working => "Working space / Mask",
HighpassSpace::SrgbFromLinear => "sRGB (from Linear sRGB)",
HighpassSpace::SrgbFromAcescg => "sRGB (from ACEScg)",
}
}
/// The id `effect.set {colorSpace}` takes
pub fn id(self) -> &'static str {
match self {
HighpassSpace::Working => "working",
HighpassSpace::SrgbFromLinear => "srgbFromLinear",
HighpassSpace::SrgbFromAcescg => "srgbFromAcescg",
}
}
/// Straight color `rgb` in this space
pub fn encode(self, rgb: [f32; 3]) -> [f32; 3] {
match self {
HighpassSpace::Working => rgb,
HighpassSpace::SrgbFromLinear => rgb.map(linear_to_srgb),
HighpassSpace::SrgbFromAcescg => times(&AP1_TO_REC709, rgb).map(linear_to_srgb),
}
}
/// Straight color `rgb` of this space back in the working space
pub fn decode(self, rgb: [f32; 3]) -> [f32; 3] {
match self {
HighpassSpace::Working => rgb,
HighpassSpace::SrgbFromLinear => rgb.map(srgb_to_linear),
HighpassSpace::SrgbFromAcescg => times(&REC709_TO_AP1, rgb.map(srgb_to_linear)),
}
}
}
/// Matrix `m` times column `v`
fn times(m: &[[f32; 3]; 3], v: [f32; 3]) -> [f32; 3] {
m.map(|row| row[0] * v[0] + row[1] * v[1] + row[2] * v[2])
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_space_round_trips_a_color_in_its_gamut() {
for space in HighpassSpace::ALL {
let back = space.decode(space.encode([0.5, 0.4, 0.3]));
assert!(back.iter().zip([0.5, 0.4, 0.3]).all(|(a, b)| (a - b).abs() < 2e-3), "{space:?}: {back:?}");
}
assert!((HighpassSpace::SrgbFromLinear.encode([0.214; 3])[0] - 0.5).abs() < 1e-2, "linear mid gray is sRGB 0.5");
}
}
+89
View File
@@ -0,0 +1,89 @@
//! An image a filter reads besides the stack it filters (its image inputs), as a source on the filter's effect
use crate::{Filter, Source, SourceColorMode, TargetColorMode, WarpSourceMode};
/// One image input of a filter: the key its source is stored under on the effect, its name and the gray it reads until a source is set
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ImageInput {
pub id: &'static str,
pub label: &'static str,
/// The gray the input reads while no source is set (what the filter did before it had the input)
pub default: f32,
/// Added by a mode of the filter (shown under that mode), not one of its Image inputs
pub by_mode: bool,
}
impl ImageInput {
/// Bevel Smooth's and Directional Distance's Distance Map: scales the distance per texel
pub const DISTANCE_MAP: ImageInput = ImageInput { id: "distanceMap", label: "Distance Map", default: 1.0, by_mode: false };
/// Warp's and Blur Slope's Custom Noise (Source Type Custom Noise): the source its texels move or read along; mid gray moves nothing
pub const CUSTOM_NOISE: ImageInput = ImageInput { id: "customNoise", label: "Custom Noise", default: 0.5, by_mode: true };
/// The Custom Input of Grayscale Conversion (the color it reads instead of the channel) and Anisotropic Kuwahara (its direction's gray); mid gray until set
pub const CUSTOM_INPUT: ImageInput = ImageInput { id: "customInput", label: "Custom Input", default: 0.5, by_mode: true };
/// Color Match's Input (Source Color Mode Input): the color each texel moves from; mid gray until set
pub const SOURCE_INPUT: ImageInput = ImageInput { id: "input", label: "Input", default: 0.5, by_mode: true };
/// Color Match's Image Input (Target Color Mode Image Input): the color each texel moves to; mid gray until set
pub const TARGET_INPUT: ImageInput = ImageInput { id: "imageInput", label: "Image Input", default: 0.5, by_mode: true };
/// The image inputs `filter` reads now (a mode's input only while that mode is on)
pub fn of(filter: &Filter) -> Vec<ImageInput> {
Self::all(filter).iter().copied().filter(|input| input.is_on(filter)).collect()
}
/// The input of `filter` stored under `id`, also while its mode is off
pub fn named(filter: &Filter, id: &str) -> Option<ImageInput> {
Self::all(filter).iter().find(|input| input.id == id).copied()
}
/// Every image input `filter` has, its modes' inputs also while those modes are off
fn all(filter: &Filter) -> &'static [ImageInput] {
match filter {
Filter::BevelSmooth(_) | Filter::DirectionalDistance(_) => &[Self::DISTANCE_MAP],
Filter::SourceWarp(_) | Filter::SourceSlopeBlur(_) => &[Self::CUSTOM_NOISE],
Filter::GrayscaleConversion(_) | Filter::AnisotropicKuwahara(_) => &[Self::CUSTOM_INPUT],
Filter::ColorMatch(_) => &[Self::SOURCE_INPUT, Self::TARGET_INPUT],
_ => &[],
}
}
/// Whether `filter` reads this input now: an input a mode adds only while that mode is on
fn is_on(&self, filter: &Filter) -> bool {
match filter {
Filter::SourceWarp(warp) => warp.source.mode == WarpSourceMode::CustomNoise,
Filter::SourceSlopeBlur(slope) => slope.source.mode == WarpSourceMode::CustomNoise,
Filter::GrayscaleConversion(conversion) => conversion.custom_input,
Filter::AnisotropicKuwahara(kuwahara) => kuwahara.custom_input,
Filter::ColorMatch(matcher) if *self == Self::SOURCE_INPUT => matcher.source_mode == SourceColorMode::Input,
Filter::ColorMatch(matcher) => matcher.target_mode == TargetColorMode::ImageInput,
_ => true,
}
}
/// The source the input reads while none is set
pub fn default_source(&self) -> Source {
Source::Uniform([self.default; 3])
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{BevelSmooth, SourceWarp, WarpSource};
#[test]
fn a_warp_has_its_custom_noise_only_in_that_source_mode() {
let warp = SourceWarp::LIBRARY;
assert!(ImageInput::of(&Filter::SourceWarp(warp)).is_empty());
let custom = SourceWarp { source: WarpSource { mode: WarpSourceMode::CustomNoise, ..warp.source }, ..warp };
assert_eq!(ImageInput::of(&Filter::SourceWarp(custom)), vec![ImageInput::CUSTOM_NOISE]);
assert_eq!(ImageInput::named(&Filter::SourceWarp(warp), "customNoise"), Some(ImageInput::CUSTOM_NOISE), "kept while the mode is off");
assert_eq!(ImageInput::of(&Filter::BevelSmooth(BevelSmooth::LIBRARY)), vec![ImageInput::DISTANCE_MAP]);
assert_eq!(ImageInput::named(&Filter::BevelSmooth(BevelSmooth::LIBRARY), "customNoise"), None);
assert_eq!(ImageInput::DISTANCE_MAP.default_source(), Source::Uniform([1.0; 3]));
}
}
+905 -137
View File
File diff suppressed because it is too large. Load diff
+104 -4
View File
@@ -7,26 +7,77 @@
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
pub mod anisotropic_kuwahara;
pub mod backface;
pub mod bake;
pub mod bevel;
pub mod bevel_blur;
pub mod bevel_corner;
pub mod bevel_direction;
pub mod bevel_smooth;
pub mod blend;
mod block_scales;
pub mod channel;
pub mod color_match;
pub mod color_selection;
pub mod compare_source;
pub mod contents_offset;
pub mod conversion_mode;
pub mod cook_resolution;
pub mod curve_preset;
pub mod depth_culling;
pub mod directional_distance;
pub mod directional_light;
mod env_alignment;
pub mod fill_symmetry;
pub mod gradient_input;
pub mod grayscale_conversion;
pub mod grayscale_mode;
pub mod height_to_normal;
pub mod highpass_space;
pub mod image_input;
pub mod layer;
pub mod lighting_output;
pub mod mask_outline;
pub mod mirror;
pub mod mirror_corner;
pub mod mirror_mode;
pub mod oklab;
pub mod outline_position;
pub mod pbr_validate;
mod prepared_color_match;
mod prepared_gradient;
pub mod project;
pub mod projector;
pub mod ramp_curve;
pub mod randomized_seed;
mod saved_decal;
mod saved_projection;
pub mod selection_background;
mod shadow_mode;
pub mod shape_crop;
pub mod slope_blending;
pub mod source_color_mode;
pub mod source_slope_blur;
pub mod source_warp;
pub mod stylized_lighting;
pub mod stylized_shading;
pub mod sun_and_sky;
pub mod symmetry_kind;
pub mod target_color_mode;
pub mod threshold_mode;
pub mod tile_transform;
pub mod unit_value;
pub mod validation_mode;
pub mod warp_blending;
pub mod warp_mode;
pub mod warp_source;
pub mod warp_source_mode;
/// A full turn, in degrees
pub const FULL_TURN_DEGREES: f32 = 360.0;
pub use anisotropic_kuwahara::AnisotropicKuwahara;
pub use backface::Backface;
pub use bake::{
AmbientOcclusionAttenuation, AmbientOcclusionSettings, BackfaceMode, BakeAntialiasing, BakePaintTarget, BakeResolution, BakeSettings, BakedMap,
@@ -35,23 +86,72 @@ pub use bake::{
NormalMapCurvatureSettings, PositionAxis, PositionMode, PositionNormalizationScale, PositionSettings, RayDistribution, RaySettings, SelfOcclusion,
SkewCorrectionMethod, SkewSettings, ThicknessNormalization, ThicknessSettings,
};
pub use bevel::Bevel;
pub use bevel_blur::BevelBlur;
pub use bevel_corner::BevelCorner;
pub use bevel_direction::BevelDirection;
pub use bevel_smooth::BevelSmooth;
pub use blend::{BlendMode, blend1, blend3, lum, mix3};
pub use channel::{Channel, ChannelFormat, ChannelKind};
pub use color_match::ColorMatch;
pub use color_selection::ColorSelection;
pub use compare_source::CompareSource;
pub use contents_offset::ContentsOffset;
pub use conversion_mode::ConversionMode;
pub use cook_resolution::CookResolution;
pub use curve_preset::CurvePreset;
pub use depth_culling::DepthCulling;
pub use directional_distance::DirectionalDistance;
pub use directional_light::DirectionalLight;
pub use fill_symmetry::FillSymmetry;
pub use gradient_input::GradientInput;
pub use grayscale_conversion::GrayscaleConversion;
pub use grayscale_mode::GrayscaleMode;
pub use height_to_normal::HeightToNormal;
pub use highpass_space::HighpassSpace;
pub use image_input::ImageInput;
pub use layer::{
ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, Effect, EffectKind, Fill, Filter, Filtering, Generator,
GeneratorGlobal, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Levels, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroDetail,
OutputResolution, PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, Sampling, ScaleMode, Source, TileBlending, TileGenerator,
TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, gradient, hsl_adjust, per_unit,
OutputResolution, POSTERIZE_LEVELS_MAX, POSTERIZE_LEVELS_MIN, PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, SIZE_REFERENCE_RES,
Sampling, ScaleMode, Source, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, gradient,
hsl_adjust, per_unit, posterize,
};
pub use lighting_output::LightingOutput;
pub use mask_outline::MaskOutline;
pub use mirror::Mirror;
pub use mirror_corner::MirrorCorner;
pub use mirror_mode::MirrorMode;
pub use outline_position::OutlinePosition;
pub use pbr_validate::PbrValidate;
pub use prepared_color_match::PreparedColorMatch;
pub use prepared_gradient::PreparedGradient;
pub use project::{
AoMixing, BlockScales, Camera, DepthOfField, DisplaySettings, EnvAlignment, FORMAT_VERSION, MAX_RESOLUTION, MIN_RESOLUTION, NormalFormat, NormalMixing,
Project, ShadowMode, TANGENT_BENT_NORMAL_VERSION, TextureSet, TileGrid, ToneMapping, UDIM_RANGE, udim_at,
AoMixing, BlockScales, Camera, DepthOfField, DisplaySettings, EnvAlignment, FORMAT_VERSION, MAX_RESOLUTION, MAX_SWATCHES, MIN_RESOLUTION, NormalFormat,
NormalMixing, Project, ShadowMode, TANGENT_BENT_NORMAL_VERSION, TextureSet, TileGrid, ToneMapping, UDIM_RANGE, udim_at,
};
pub use projector::Projector;
pub use ramp_curve::RampCurve;
pub use randomized_seed::RandomizedSeed;
pub use selection_background::SelectionBackground;
pub use shape_crop::ShapeCrop;
pub use slope_blending::SlopeBlending;
pub use source_color_mode::SourceColorMode;
pub use source_slope_blur::SourceSlopeBlur;
pub use source_warp::SourceWarp;
pub use stylized_lighting::{DIELECTRIC_REFLECTANCE, StylizedLighting};
pub use stylized_shading::{FLAT_CURVATURE, StylizedShading};
pub use sun_and_sky::SunAndSky;
pub use symmetry_kind::SymmetryKind;
pub use target_color_mode::TargetColorMode;
pub use threshold_mode::ThresholdMode;
pub use tile_transform::{FlipMode, RepeatMode, TileTransform};
pub use unit_value::{at_or_above_threshold, finite_unit};
pub use validation_mode::ValidationMode;
pub use warp_blending::WarpBlending;
pub use warp_mode::WarpMode;
pub use warp_source::WarpSource;
pub use warp_source_mode::WarpSourceMode;
#[derive(Debug, thiserror::Error, Clone, PartialEq)]
pub enum CoreError {
+49
View File
@@ -0,0 +1,49 @@
//! What Baked Lighting Stylized paints into the base color
use serde::{Deserialize, Serialize};
/// The lit parts Baked Lighting Stylized keeps
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum LightingOutput {
/// The lit surface and its highlights
#[default]
DiffuseSpecular,
/// The lit surface only (what Baked Lighting painted before it had highlights)
Diffuse,
/// The highlights only
Specular,
}
impl LightingOutput {
/// Every output, in the order a list shows them
pub const ALL: [LightingOutput; 3] = [LightingOutput::DiffuseSpecular, LightingOutput::Diffuse, LightingOutput::Specular];
/// The name a panel shows
pub fn label(self) -> &'static str {
match self {
LightingOutput::DiffuseSpecular => "Diffuse + Specular",
LightingOutput::Diffuse => "Diffuse only",
LightingOutput::Specular => "Specular only",
}
}
/// The id `effect.set {output}` takes
pub fn id(self) -> &'static str {
match self {
LightingOutput::DiffuseSpecular => "diffuseSpecular",
LightingOutput::Diffuse => "diffuse",
LightingOutput::Specular => "specular",
}
}
/// Whether the lit surface is kept
pub fn diffuse(self) -> bool {
self != LightingOutput::Specular
}
/// Whether the highlights are kept
pub fn specular(self) -> bool {
self != LightingOutput::Diffuse
}
}
+94
View File
@@ -0,0 +1,94 @@
//! The Mask Outline filter's settings and the band it draws
use serde::{Deserialize, Serialize};
use crate::{OutlinePosition, RampCurve, at_or_above_threshold};
/// A band along the edge where values cross a threshold, outside, inside or on both sides of the shapes
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MaskOutline {
pub position: OutlinePosition,
/// The band on black; otherwise it is laid over the values below
pub from_black: bool,
/// Values at or above it are inside the shapes (0..1)
pub threshold: f32,
/// How far the band reaches from the edge, a fraction of the UV tile (0..1)
pub width: f32,
/// How much of the band fades out towards its far side (0..1)
pub blur: f32,
/// Bends that fade: below 0 it falls off sooner, above 0 later (−1..1)
pub curve: f32,
}
impl MaskOutline {
/// The Mask Outline filter as the library adds it
pub const LIBRARY: MaskOutline = MaskOutline { position: OutlinePosition::Outside, from_black: true, threshold: 1.0, width: 0.05, blur: 0.0, curve: 0.0 };
/// Whether `value` is inside the shapes
pub fn inside(&self, value: f32) -> bool {
at_or_above_threshold(value, self.threshold, Self::LIBRARY.threshold)
}
/// The curve the band's fade takes (Curve), worked out once per filter
pub fn fade_curve(&self) -> RampCurve {
RampCurve::new(0.0, self.curve)
}
/// The band at a texel inside the shapes or not, `closeness` to the edge going from 1 at it to 0 at the band's reach, its fade bent by [`MaskOutline::fade_curve`]
pub fn band(&self, fade_curve: RampCurve, inside: bool, closeness: f32) -> f32 {
let closeness = if closeness.is_finite() { closeness.clamp(0.0, 1.0) } else { 0.0 };
if !self.position.covers(inside) || closeness <= 0.0 || !self.width.is_finite() || self.width <= 0.0 {
return 0.0;
}
let blur = if self.blur.is_finite() { self.blur.clamp(0.0, 1.0) } else { 0.0 };
if blur <= 0.0 {
return 1.0;
}
fade_curve.apply(closeness / blur)
}
/// The result at a texel of value `value`: the band on black, or over the value
pub fn apply(&self, value: f32, band: f32) -> f32 {
if self.from_black { band } else { value.max(band) }
}
}
#[cfg(test)]
mod tests {
use super::*;
/// The band with the curve worked out as the filter does
fn band(filter: MaskOutline, inside: bool, closeness: f32) -> f32 {
filter.band(filter.fade_curve(), inside, closeness)
}
#[test]
fn the_band_lies_on_its_side_of_the_edge() {
let outline = MaskOutline::LIBRARY;
assert!(outline.inside(1.0) && !outline.inside(0.99));
assert_eq!(band(outline, false, 0.3), 1.0, "a hard band outside");
assert_eq!(band(outline, true, 0.3), 0.0, "nothing inside an outside band");
assert_eq!(band(outline, false, 0.0), 0.0, "nothing past its reach");
let inside = MaskOutline { position: OutlinePosition::Inside, ..outline };
assert_eq!((band(inside, true, 0.3), band(inside, false, 0.3)), (1.0, 0.0));
let both = MaskOutline { position: OutlinePosition::Both, ..outline };
assert_eq!((band(both, true, 0.3), band(both, false, 0.3)), (1.0, 1.0));
assert_eq!(outline.apply(0.4, 0.0), 0.0, "from black");
assert_eq!(MaskOutline { from_black: false, ..outline }.apply(0.4, 0.0), 0.4, "over the values");
}
#[test]
fn blur_fades_the_band_and_curve_shape_bends_the_fade() {
let soft = MaskOutline { blur: 1.0, ..MaskOutline::LIBRARY };
assert!((band(soft, false, 0.5) - 0.5).abs() < 1e-6, "a linear fade");
assert!(band(MaskOutline { curve: 0.5, ..soft }, false, 0.5) > 0.5, "falls off later");
assert!(band(MaskOutline { curve: -0.5, ..soft }, false, 0.5) < 0.5, "falls off sooner");
assert_eq!(band(MaskOutline { blur: 0.5, ..soft }, false, 0.6), 1.0, "only the far part fades");
assert_eq!(band(MaskOutline { width: f32::NAN, threshold: f32::NAN, ..soft }, false, 0.5), 0.0);
}
}
+104
View File
@@ -0,0 +1,104 @@
//! The Mirror filter's settings and where it reads each texel from
use serde::{Deserialize, Serialize};
use crate::{MirrorCorner, MirrorMode};
/// A mirror filter: one side of an axis (or one quarter) of each UV tile copied over the rest
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Mirror {
/// Draws the mirror's axes over the result (Display Debug)
pub debug: bool,
pub mode: MirrorMode,
/// Where the X and Y axes sit across the tile (0..1)
pub offset: [f32; 2],
/// Copies the right (X) or bottom (Y) side instead of the left or top one
pub invert: [bool; 2],
pub corner: MirrorCorner,
}
impl Mirror {
/// The Mirror filter as the library adds it: left onto right across the middle
pub const LIBRARY: Mirror = Mirror { debug: false, mode: MirrorMode::AxisX, offset: [0.5, 0.5], invert: [false, false], corner: MirrorCorner::TopLeft };
/// Half the width of a debug axis line, in texels at 2K
pub const DEBUG_HALF_WIDTH: f32 = 2.0;
/// Where in its tile (0..1 across, 0..1 down) the texel at `uv` reads from; a copy that reaches past an edge folds back at it
pub fn source(&self, [u, v]: [f32; 2]) -> [f32; 2] {
let across = |at: f32, axis: f32, keep_after: bool| {
let copied = if keep_after { at < axis } else { at > axis };
fold(if copied { 2.0 * axis - at } else { at })
};
match self.mode {
MirrorMode::AxisX => [across(u, self.axis(0), self.invert[0]), v],
MirrorMode::AxisY => [u, across(v, self.axis(1), self.invert[1])],
MirrorMode::Corner => {
let (right, bottom) = self.corner.sides();
[across(u, 0.5, right), across(v, 0.5, bottom)]
}
}
}
/// Whether `uv` lies within `half_width` (a fraction of the tile) of one of the mirror's axes
pub fn on_axis(&self, [u, v]: [f32; 2], half_width: f32) -> bool {
let near = |at: f32, axis: f32| (at - axis).abs() <= half_width;
match self.mode {
MirrorMode::AxisX => near(u, self.axis(0)),
MirrorMode::AxisY => near(v, self.axis(1)),
MirrorMode::Corner => near(u, 0.5) || near(v, 0.5),
}
}
/// The axis position along `axis` (0 = X, 1 = Y), within the tile even from a hostile file
fn axis(&self, axis: usize) -> f32 {
let at = self.offset.get(axis).copied().unwrap_or(0.5);
if at.is_finite() { at.clamp(0.0, 1.0) } else { 0.5 }
}
}
/// `at` folded back into 0..1 at the tile's edges, as a mirror reflects
fn fold(at: f32) -> f32 {
let wrapped = at.rem_euclid(2.0);
if wrapped > 1.0 { 2.0 - wrapped } else { wrapped }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn each_mode_reads_the_kept_side() {
let mut mirror = Mirror::LIBRARY;
assert_eq!(mirror.source([0.25, 0.4]), [0.25, 0.4], "the left side stays");
assert_eq!(mirror.source([0.75, 0.4]), [0.25, 0.4], "the right side reads the left");
mirror.invert[0] = true;
assert_eq!(mirror.source([0.25, 0.4]), [0.75, 0.4], "inverted, the left side reads the right");
mirror.offset[0] = 0.25;
mirror.invert[0] = false;
assert_eq!(mirror.source([0.75, 0.0]), [0.25, 0.0], "a copy past the left edge folds back at it");
mirror.mode = MirrorMode::AxisY;
assert_eq!(mirror.source([0.9, 0.75]), [0.9, 0.25], "Axis Y reads the top for the bottom");
mirror.mode = MirrorMode::Corner;
mirror.corner = MirrorCorner::BottomRight;
assert_eq!(mirror.source([0.25, 0.25]), [0.75, 0.75], "every quarter reads the kept one");
assert_eq!(mirror.source([0.75, 0.75]), [0.75, 0.75]);
assert!(mirror.on_axis([0.5, 0.1], 0.01) && mirror.on_axis([0.1, 0.5], 0.01) && !mirror.on_axis([0.1, 0.1], 0.01));
}
#[test]
fn a_hostile_offset_stays_in_the_tile() {
let mirror = Mirror { offset: [f32::NAN, f32::INFINITY], ..Mirror::LIBRARY };
let [u, v] = mirror.source([0.9, 0.9]);
assert!((0.0..=1.0).contains(&u) && (0.0..=1.0).contains(&v));
}
}
+49
View File
@@ -0,0 +1,49 @@
//! The quarter a corner mirror copies
use serde::{Deserialize, Serialize};
/// The quarter of each UV tile a corner mirror keeps and copies over the other three
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum MirrorCorner {
#[default]
TopLeft,
TopRight,
BottomLeft,
BottomRight,
}
impl MirrorCorner {
/// Every corner, in the order a list shows them
pub const ALL: [MirrorCorner; 4] = [MirrorCorner::TopLeft, MirrorCorner::TopRight, MirrorCorner::BottomLeft, MirrorCorner::BottomRight];
/// The name a panel shows
pub fn label(self) -> &'static str {
match self {
MirrorCorner::TopLeft => "Top Left",
MirrorCorner::TopRight => "Top Right",
MirrorCorner::BottomLeft => "Bottom Left",
MirrorCorner::BottomRight => "Bottom Right",
}
}
/// The id `effect.set {cornerType}` takes
pub fn id(self) -> &'static str {
match self {
MirrorCorner::TopLeft => "topLeft",
MirrorCorner::TopRight => "topRight",
MirrorCorner::BottomLeft => "bottomLeft",
MirrorCorner::BottomRight => "bottomRight",
}
}
/// Whether the kept quarter is on the right half and on the bottom half
pub fn sides(self) -> (bool, bool) {
match self {
MirrorCorner::TopLeft => (false, false),
MirrorCorner::TopRight => (true, false),
MirrorCorner::BottomLeft => (false, true),
MirrorCorner::BottomRight => (true, true),
}
}
}
+39
View File
@@ -0,0 +1,39 @@
//! Which way a mirror filter copies a texture
use serde::{Deserialize, Serialize};
/// The side of an axis, or the corner, a mirror filter copies over the rest of each UV tile
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum MirrorMode {
/// Across a vertical axis, left onto right
#[default]
AxisX,
/// Across a horizontal axis, top onto bottom
AxisY,
/// One quarter onto the other three
Corner,
}
impl MirrorMode {
/// Every mode, in the order a list shows them
pub const ALL: [MirrorMode; 3] = [MirrorMode::AxisX, MirrorMode::AxisY, MirrorMode::Corner];
/// The name a panel shows
pub fn label(self) -> &'static str {
match self {
MirrorMode::AxisX => "Mirror Axis X",
MirrorMode::AxisY => "Mirror Axis Y",
MirrorMode::Corner => "Mirror Corner",
}
}
/// The id `effect.set {mode}` takes
pub fn id(self) -> &'static str {
match self {
MirrorMode::AxisX => "axisX",
MirrorMode::AxisY => "axisY",
MirrorMode::Corner => "corner",
}
}
}
+40
View File
@@ -0,0 +1,40 @@
//! The OKLab perceptual color space (Björn Ottosson's public construction): hue, chroma and lightness shifts that keep perceived lightness
/// Linear sRGB to OKLab `[L, a, b]`
pub fn from_linear([r, g, b]: [f32; 3]) -> [f32; 3] {
let l = (0.412_221_46 * r + 0.536_332_55 * g + 0.051_445_995 * b).cbrt();
let m = (0.211_903_5 * r + 0.680_699_5 * g + 0.107_396_96 * b).cbrt();
let s = (0.088_302_46 * r + 0.281_718_85 * g + 0.629_978_7 * b).cbrt();
[
0.210_454_26 * l + 0.793_617_8 * m - 0.004_072_047 * s,
1.977_998_5 * l - 2.428_592_2 * m + 0.450_593_7 * s,
0.025_904_037 * l + 0.782_771_77 * m - 0.808_675_77 * s,
]
}
/// OKLab `[L, a, b]` back to linear sRGB (unclamped)
pub fn to_linear([lightness, a, b]: [f32; 3]) -> [f32; 3] {
let l = (lightness + 0.396_337_78 * a + 0.215_803_76 * b).powi(3);
let m = (lightness - 0.105_561_346 * a - 0.063_854_17 * b).powi(3);
let s = (lightness - 0.089_484_18 * a - 1.291_485_5 * b).powi(3);
[
4.076_741_7 * l - 3.307_711_6 * m + 0.230_969_94 * s,
-1.268_438 * l + 2.609_757_4 * m - 0.341_319_38 * s,
-0.004_196_086_3 * l - 0.703_418_6 * m + 1.707_614_7 * s,
]
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn colors_round_trip_and_white_has_lightness_one() {
let white = from_linear([1.0; 3]);
assert!((white[0] - 1.0).abs() < 1e-3 && white[1].abs() < 1e-3 && white[2].abs() < 1e-3, "{white:?}");
for color in [[0.8, 0.2, 0.1], [0.05, 0.5, 0.9], [0.3, 0.3, 0.3]] {
let back = to_linear(from_linear(color));
assert!(color.iter().zip(back).all(|(a, b)| (a - b).abs() < 1e-3), "{color:?} -> {back:?}");
}
}
}
+48
View File
@@ -0,0 +1,48 @@
//! Which side of a mask's edge a Mask Outline draws on
use serde::{Deserialize, Serialize};
/// The side of the threshold edge a Mask Outline's band lies on
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum OutlinePosition {
/// Around the shapes, outside them
#[default]
Outside,
/// Inside the shapes, along their edge
Inside,
/// On both sides of the edge
Both,
}
impl OutlinePosition {
/// Every position, in the order a switch shows them
pub const ALL: [OutlinePosition; 3] = [OutlinePosition::Outside, OutlinePosition::Inside, OutlinePosition::Both];
/// The name a panel shows
pub fn label(self) -> &'static str {
match self {
OutlinePosition::Outside => "Outside",
OutlinePosition::Inside => "Inside",
OutlinePosition::Both => "Both",
}
}
/// The id `effect.set {maskPosition}` takes
pub fn id(self) -> &'static str {
match self {
OutlinePosition::Outside => "outside",
OutlinePosition::Inside => "inside",
OutlinePosition::Both => "both",
}
}
/// Whether the band covers a texel inside the shapes (`inside`)
pub fn covers(self, inside: bool) -> bool {
match self {
OutlinePosition::Outside => !inside,
OutlinePosition::Inside => inside,
OutlinePosition::Both => true,
}
}
}
Loaded 100 of 495 files, more files were not shown because too many files have changed in this diff. Show more