Merge remote-tracking branch 'origin/main' into upd255b

This commit is contained in:
SteamSmith committed 2026-11-27 00:06:28 -05:00
commit 83fa0d1233
247 files changed
+9495 -2765

No files matched your search

+95
View File
@@ -5,3 +5,98 @@ xtask = "run -p xtask --"
# macros use, and then clippy and test each build their own copy of them.
[profile.dev.package."*"]
debug = "line-tables-only"
# Test builds compile the craft UI framework below the workspace's opt-level 2: the Windows test
# build spends most of its time on these crates and the generics they share, and their tests run
# no heavy pixel code. Crates whose tests run on the 2 MiB Windows test stack stay at 1; the rest
# and ui-egui use 0. `cargo run` and `cargo build` use the dev profile and are unaffected.
[profile.test.package.craft-ui]
opt-level = 1
[profile.test.package.craft-ui-contract]
opt-level = 1
[profile.test.package.craft-ui-shell]
opt-level = 1
[profile.test.package.craft-ui-canvas]
opt-level = 1
[profile.test.package.craft-ui-panels]
opt-level = 1
[profile.test.package.craft-ui-widgets]
opt-level = 1
[profile.test.package.craft-host]
opt-level = 1
[profile.test.package.craft-theme]
opt-level = 1
[profile.test.package.craft-behavior]
opt-level = 1
[profile.test.package.craft-font-catalog]
opt-level = 1
[profile.test.package.craft-ui-patterns]
opt-level = 0
[profile.test.package.craft-update]
opt-level = 0
[profile.test.package.craft-keymap]
opt-level = 0
[profile.test.package.craft-dialogs]
opt-level = 0
[profile.test.package.craft-settings]
opt-level = 0
[profile.test.package.craft-platform]
opt-level = 0
[profile.test.package.craft-window]
opt-level = 0
[profile.test.package.craft-cloud-ui]
opt-level = 0
[profile.test.package.craft-pdf]
opt-level = 0
[profile.test.package.texturecraft-ui-egui]
opt-level = 0
# The TLS stack and the dialog, browser and screen capture crates: no test makes a TLS connection, opens a file dialog or
# captures the screen, so their optimized builds only cost test build time.
[profile.test.package.ring]
opt-level = 0
[profile.test.package.rustls]
opt-level = 0
[profile.test.package.rustls-webpki]
opt-level = 0
[profile.test.package.rustls-platform-verifier]
opt-level = 0
[profile.test.package.ureq]
opt-level = 0
[profile.test.package.ureq-proto]
opt-level = 0
[profile.test.package.webbrowser]
opt-level = 0
[profile.test.package.rfd]
opt-level = 0
[profile.test.package.xcap]
opt-level = 0
+16
View File
@@ -0,0 +1,16 @@
-----BEGIN PGP PUBLIC KEY BLOCK-----
mDMEaulK1xYJKwYBBAHaRw8BAQdAqHJeDCjY6Hx5FTn/hW+aqu6V394ubLk0Zj3C
bftDwFm0IkFydENyYWZ0IExpbnV4IFJlbGVhc2UgU2lnbmluZyBLZXmIkwQTFgoA
OxYhBCt2dBtBSq1s0z5jEhOgBcC518PtBQJq6UrXAhsBBQsJCAcCAiICBhUKCQgL
AgQWAgMBAh4HAheAAAoJEBOgBcC518PtGeUA/RjvULBTLlccc+2wtJkfjSnCV+cf
PUMEGmW7XkZWkk51AP9w2A/WLv+79nREWEpZzI8LGK5EjrNazP+sY0l7j5rFCLgz
BGrpStcWCSsGAQQB2kcPAQEHQPl7XkQ1gWsvSPf/T9b4m/UHcjJjBpSOtpYlWR56
er5RiO8EGBYKACAWIQQrdnQbQUqtbNM+YxIToAXAudfD7QUCaulK1wIbAgCBCRAT
oAXAudfD7XYgBBkWCgAdFiEEVo3B9o+Prsx5fzx7AG2va7DvM04FAmrpStcACgkQ
AG2va7DvM07taQEA4d2VFkKRIP0g9TrE86KpnuXPap+LKqe0tfIxpdf9YxIA/0Wo
9H/iG8nH++nxC087p3HE0S+0UovxqkhXJLSr8B4JDOoA/iLRpqTdYmk6fVXMyPJo
SkOVuwZIGS6VgBdSQP0e2P2YAP41L5OoSvwdQIG3/uNrM+ieqpYeM597/hCLFs5A
ga/qCA==
=3wGQ
-----END PGP PUBLIC KEY BLOCK-----
+11 -9
View File
@@ -2,13 +2,13 @@
"schema": "craft-nightly-release-policy/v3",
"repository": "storytold/texturecraft",
"repository_id": 1419654881,
"producer_workflow_id": null,
"producer_workflow_id": 429738073,
"producer_workflow_path": ".github/workflows/nightly.yml",
"producer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea",
"producer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
"signer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea",
"release_branch": "release",
"signer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
"release_branch": "nightly-signer",
"manual_actors": [
"bflatastic",
"dylanmtaylor",
@@ -49,13 +49,15 @@
"issue_types": [
"VULNERABILITY"
],
"accepted_conditions": [],
"required_conditions": [
"accepted_conditions": [
{
"metric": "new_security_rating",
"comparator": "GT",
"error_threshold": "1"
},
"error_threshold": "1",
"maximum": "5"
}
],
"required_conditions": [
{
"metric": "new_reliability_rating",
"comparator": "GT",
+72
View File
@@ -0,0 +1,72 @@
name: Dispatch release-ref nightly
# Transport only, never authorization. No checkout, payload parsing or release environment.
on:
workflow_run:
workflows: [TextureCraft unsigned nightly]
types: [completed]
branches: [main]
permissions: {}
jobs:
dispatch:
# SOURCE PREPARATION: literal off until immutable shared tooling and policy qualification.
if: >-
false && github.repository == 'storytold/texturecraft' &&
github.event_name == 'workflow_run'
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
actions: write
steps:
- name: Dispatch only the exact completed producer run and attempt
shell: python
env:
GH_TOKEN: ${{ github.token }}
run: |
import json
import os
import urllib.request
def require(value, message):
if not value:
raise RuntimeError(message)
# These filters reduce noise; the protected signer-branch validator repeats admission
# against authenticated API metadata and required attestation/quality evidence.
require(os.environ.get('GITHUB_REPOSITORY') == 'storytold/texturecraft', 'wrong repository')
require(os.environ.get('GITHUB_EVENT_NAME') == 'workflow_run', 'wrong event')
with open(os.environ['GITHUB_EVENT_PATH'], encoding='utf-8') as stream:
event = json.load(stream)
require(event.get('action') == 'completed', 'producer is not complete')
require(event.get('repository', {}).get('full_name') == 'storytold/texturecraft', 'wrong event repository')
producer = event.get('workflow_run', {})
require(producer.get('head_repository', {}).get('full_name') == 'storytold/texturecraft', 'foreign producer')
require(producer.get('path') == '.github/workflows/nightly.yml', 'wrong producer path')
require(producer.get('head_branch') == 'main', 'wrong producer branch')
require(producer.get('status') == 'completed' and producer.get('conclusion') == 'success', 'producer did not succeed')
# First scheduled attempt only; reviewed manual/re-run authority belongs to release policy.
require(producer.get('event') == 'schedule', 'not an automatic scheduled producer')
run_id, attempt = producer.get('id'), producer.get('run_attempt')
require(type(run_id) is int and run_id > 0, 'invalid producer run id')
require(type(attempt) is int and attempt == 1, 'invalid automatic producer attempt')
body = json.dumps({'ref': 'refs/heads/nightly-signer', 'inputs': {
'producer_run_id': str(run_id), 'producer_run_attempt': str(attempt)
}}).encode('utf-8')
request = urllib.request.Request(
'https://api.github.com/repos/storytold/texturecraft/actions/workflows/nightly-sign.yml/dispatches',
data=body, method='POST', headers={
'Authorization': 'Bearer ' + os.environ['GH_TOKEN'],
'Accept': 'application/vnd.github+json',
'Content-Type': 'application/json',
'X-GitHub-Api-Version': '2022-11-28',
'User-Agent': 'texturecraft-nightly-dispatch'
})
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
raise RuntimeError('dispatch redirects are forbidden')
# One bounded request, no retry: duplicate transport is not publication authority.
with urllib.request.build_opener(NoRedirect()).open(request, timeout=20) as response:
require(response.status == 204, 'dispatch was not accepted')
print('Dispatched producer run/attempt to the release-ref validator; not a signing result.')
+10 -7
View File
@@ -1,7 +1,8 @@
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.
# Enabled for supervised manual dispatch on the dedicated nightly-signer branch, which only ever
# fast-forwards to reviewed main commits (never the stable release branch).
# A reusable callee does not change context; this must be a real top-level signer-branch dispatch.
on:
workflow_dispatch:
inputs:
@@ -22,21 +23,23 @@ concurrency:
jobs:
release:
# Actual context guards: official repository, manual dispatch, real release branch.
# Actual context guards: official repository, manual dispatch, real nightly-signer branch.
if: >-
github.repository == 'storytold/texturecraft' &&
github.event_name == 'workflow_dispatch' &&
github.ref == 'refs/heads/release' && github.ref_type == 'branch'
github.ref == 'refs/heads/nightly-signer' && 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
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
with:
tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
app-name: texturecraft
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.
# callee job may bind the release environment and export its keys; that environment must
# admit nightly-signer alongside release before the first dispatch.
+4 -4
View File
@@ -22,13 +22,13 @@ jobs:
actions: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
with:
tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
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).
# craft-common-actions main commit that merged the exact-analysis admission (#371, after #370,
# #369 and #364).
platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'
Generated
+972 -234
View File
File diff suppressed because it is too large. Load diff
+32 -28
View File
@@ -10,7 +10,7 @@ edition = "2024"
license = "MIT OR Apache-2.0"
[workspace.dependencies]
craft-usd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3" }
craft-usd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
# internal
texturecraft-core = { path = "crates/core" }
texturecraft-texel = { path = "crates/texel" }
@@ -41,7 +41,7 @@ skrifa = { version = "0.44", default-features = false, features = ["std"] }
epaint_default_fonts = "0.37"
log = "0.4"
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "tga", "tiff", "exr", "hdr", "bmp", "webp"] }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
half = "2"
exr = { version = "1.73", default-features = false }
eframe = { version = "0.37", default-features = false }
@@ -64,46 +64,50 @@ rustix = { version = "1", default-features = false, features = ["std", "fs", "pr
# Shared Craft egui components (widget palette, icon buttons, panel docking): storytold/craft-libs,
# MIT OR Apache-2.0, pinned to one rev.
# Shared catalog lookup, pinned with the other Craft libraries.
craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" }
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["serde"] }
craft-materialx = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" }
craft-tcraft = { git = "https://github.com/storytold/craft-libs", rev = "c376774f15ae7cd3b06a7ac664f01a8645af4b83" }
# Isolated aligned writer; existing archive readers retain their pin and behavior.
craft-zip-usdz = { package = "craft-zip", git = "https://github.com/storytold/craft-libs", rev = "5631e99fe126cffb74c673eb458db04299f2bb9b" }
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "c376774f15ae7cd3b06a7ac664f01a8645af4b83" }
craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "a20dfd1623709b0bd9830106d3a92a1a443902e3", default-features = false, features = ["stl", "ply", "fbx", "obj", "gltf", "dae", "abc"] }
craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "7a7a18cb40ac4cd5fca29c0dc224ac5178d40a89" }
craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-behavior = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-materialx = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-tcraft = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", default-features = false, features = ["stl", "ply", "fbx", "obj", "gltf", "dae", "abc"] }
craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
# Who draws the window frame, and the app-drawn strip as the title bar (crates/ui-egui/src/titlebar.rs).
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["egui"] }
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
# Release checks, the update prompt and the update helper (crates/ui-egui/src/updates_ui.rs).
craft-update = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["egui"] }
craft-update = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
# File dialogs that never block the frame (crates/ui-egui/src/file_dialogs.rs).
craft-dialogs = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" }
craft-dialogs = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
# Shortcut chords, lookup and dispatch (crates/ui-egui/src/keymap.rs).
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["egui"] }
# Quitting the macOS way instead of closing the window (crates/ui-egui/src/windows.rs).
craft-quit = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["egui"] }
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["egui"] }
# The macOS app menu whose Quit asks about unsaved changes (apps/texturecraft/src/main.rs).
craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" }
craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
# The UI runtime's host: who the app is to the framework's dialogs (crates/ui-egui/src/framework.rs).
craft-host = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
# The theme mode the app hands the runtime (crates/ui-egui/src/framework.rs).
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
# egui 0.37 and winit: the suite's forks (storytold/egui, storytold/winit), as craft-libs pins them.
[patch.crates-io]
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
emath = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
# egui-phosphor has no release for egui 0.37 (vendor/egui-phosphor/VENDORED.md).
egui-phosphor = { path = "vendor/egui-phosphor" }
[workspace.lints.rust]
unsafe_code = "forbid"
# cargo-llvm-cov always sets `cfg(coverage)`: a coverage build bakes on the CPU (texturecraft-engine
# picks no GPU tracer there) and the cfg would otherwise trip unexpected_cfgs under -D warnings.
unexpected_cfgs = { level = "warn", check-cfg = ['cfg(coverage)'] }
[workspace.lints.clippy]
dbg_macro = "warn"
+1 -1
View File
@@ -154,7 +154,7 @@ cargo run --release -p texturecraft-cli -- new builtin:crate crate.tcraft --samp
cargo run --release -p texturecraft-cli -- render crate.tcraft crate.png --samples 256 # path traced
cargo run --release -p texturecraft-cli -- export crate.tcraft textures # headless export
cd apps/texturecraft-web && trunk serve # web build
cargo xtask ci # fmt, clippy, tests, layering, wasm
cargo xtask ci # fmt, clippy, tests, layering, wasm (not on Windows)
```
You need Rust 1.95 or newer. The app opens with no project (**File ▸ Open sample project** loads a baked one, and **File ▸ Close** returns to the empty state).
+104 -112
View File
@@ -2,13 +2,15 @@
Stage: alpha (readiness assessment) · next: beta, ~75% readiness plus scoped compatibility and integration gates; remaining effort unestimated
> Last reviewed: 2026-11-16 · Last updated: 2026-11-16 · Change: major (UI/functionality audit, possible format/package reworks, unfinished `.mcmat` integration and incoming ArtCraft UI/shared-library work) · Target: reference app 12.2.0
> Last reviewed: 2026-11-25 · Last updated: 2026-11-25 · Change: major (implementation audit and revised readiness estimates) · Target: reference app 12.2.0
TextureCraft is a clean-room implementation of the professional texture-painting workflow. This
assessment covers **main at [62b2b13](https://github.com/storytold/texturecraft/commit/62b2b13fdd32740b6e118cd00c5e0d0c12b30815),
version 0.6.1**, compared with the installed reference app on 2026-11-16. It follows the
[PhotoCraft roadmap format](https://github.com/storytold/photocraft/blob/main/ROADMAP.md).
Detail: [UI gaps and functional task audit](docs/ui-parity.md), [features](docs/features.md), [menu checklist](docs/parity.md),
The implementation audit covers main at
[`3c026860`](https://github.com/storytold/texturecraft/commit/3c026860e36e5fbe2147c6c78ca0bbc617575887),
with workspace version 0.6.1. Current estimates incorporate landed workflows, Linux regression
tests and the MaterialCraft round trip. The November 16 live comparison with reference app 12.2.0
at [`62b2b13`](https://github.com/storytold/texturecraft/commit/62b2b13fdd32740b6e118cd00c5e0d0c12b30815)
provides the starting scores. The live artist tasks still need a repeat on current main.
See [UI gaps and functional tasks](docs/ui-parity.md), [features](docs/features.md), [menu checklist](docs/parity.md),
[architecture](docs/architecture.md), [automation](docs/control-protocol.md),
[localization](docs/localization-parity.md), [releasing](docs/releasing.md).
@@ -19,65 +21,51 @@ still need investigation; no `.spp` reader is implemented. Writing `.spp`, round
back into it and compatibility with other proprietary asset/preset formats are outside this goal.
Pipeline exchange uses USD, glTF/GLB, MaterialX and texture maps.
The current `.tcraft` schema/container and output-package contracts may be reworked; their
present implementations are not a frozen design. MaterialCraft `.mcmat` import remains a goal
whose next format is unfinished upstream. ArtCraft UI refactoring and further shared-library
adoption also add integration and regression work. These dependencies are part of the remaining
roadmap, even where a current task already passes.
The current `.tcraft` schema/container and output-package contracts remain open to revision.
MaterialCraft and TextureCraft have landed procedural `.mcmat` v3 support. The source-build round trip passed at the revisions below. The exchange gate still needs
a supported release pair and artist workflow checks. ArtCraft UI refactoring and
further shared-library adoption also require integration and regression checks.
## Headline numbers
| | Value | Kind |
|---|---|---|
| Feature breadth | ~80% (75–85%) | Estimated across feature families; no exhaustive target inventory |
| Ready for real work | ~60% (50–70%) | Estimated readiness of the assessed revision; no completion credit for incoming reworks/integrations |
| Mainstream practitioner | ~60% (50–70%) | Estimated for regular asset texturing, baking, masking and pipeline delivery |
| Essentials user | ~75% (65–85%) | Estimated for a simple mesh, layered materials/paint and texture export |
| Desktop menu catalog | 59/59 live | Observed through the running app; this is TextureCraft's own catalog |
| Engine commands | 178 registered | Observed through the running app; registration does not prove every parameter path |
| Functional review | 20 scoped check groups | UI, mixed-surface and command cases [recorded separately](docs/ui-parity.md#functional-task-audit); not an exhaustive coverage score |
| Remaining to beta | Unestimated | Requires acceptance tasks, performance budgets and a decision on required format/package/UI migrations |
| Remaining to full scoped parity | Unestimated | Includes possible `.tcraft`/output reworks, upstream `.mcmat`, ArtCraft UI/shared-library adoption, `.spp` feasibility and workflow/fidelity work |
| Feature breadth | ~90% | Estimated across feature families. The November 16 baseline was ~80% |
| Ready for real work | ~68% | Weighted estimate, up from ~60% on November 16. The largest gains are in feature depth, UI and interchange |
| Mainstream practitioner | ~70% | Estimated for regular asset texturing, baking, masking and pipeline delivery. The November 16 baseline was ~60% |
| Essentials user | ~85% | Estimated for a simple mesh, layered materials and paint, and texture export. The November 16 baseline was ~75% |
| Desktop menu catalog | 59/59 live | Observed on November 16 in TextureCraft's desktop catalog |
| Engine commands | 178 registered | Observed on November 16 through the running app |
| Functional review | 20 scoped check groups | November 16 UI, mixed-surface and command cases. [Functional task audit](docs/ui-parity.md#functional-task-audit) |
| Remaining to beta | Unestimated | Requires acceptance tasks, performance budgets and a decision on required format, package and UI migrations |
| Remaining to full scoped parity | Unestimated | Includes possible `.tcraft` and output-package reworks, `.mcmat` release validation, ArtCraft UI and shared libraries, `.spp` feasibility, and workflow and fidelity checks |
The former ~94% figure mostly counted implementation paths. This review also asks whether an
artist gets equivalent controls, predictable output, responsive interaction and dependable
delivery. The change is a measurement rebaseline and an expanded import goal, not a measured
loss of functionality. Percentages are rounded judgments; ranges express uncertainty, not
statistical confidence intervals. The old “~6 h + baking TBD” remainder is withdrawn: this
review provides no calibrated engineering or agent-hour forecast.
The percentages describe behavior at `62b2b13`, not how much of a settled delivery plan is
finished. Potential rework can revisit working code and require repeating the checks below.
Its scope and cost are not yet measured, so remaining effort cannot be calculated as
100 minus the readiness score. Incoming upstream work is not counted as landed functionality.
Feature breadth estimates how much of the scoped feature set is present. Readiness also weighs
control depth, output fidelity, responsiveness, project safety and delivery. The earlier ~94%
figure mostly counted implementation paths and used a narrower scope. The current figures are
audit judgments based on the evidence below. Potential format and UI rework can require repeating
earlier checks, and its scope and cost remain unestimated.
### Readiness by audience
| Audience | Ready % | Hours to ~95% | Work that dominates |
|---|---|---|---|
| Full scoped target | ~60% | Unestimated | Workflow depth, format/output-package decisions, `.mcmat`, ArtCraft UI/shared libraries, bake/display fidelity, color management, read-only `.spp` and platform validation |
| Mainstream practitioner | ~60% | Unestimated | Reliable masks/painting, MaterialCraft exchange once its contract is ready, project/package compatibility, larger projects and destination-app checks |
| Essentials user | ~75% | Unestimated | Discoverable controls, predictable startup/GPU selection and save/reopen reliability retained through format/UI migrations |
| Full scoped target | ~68% | Unestimated | Workflow depth, format and package decisions, ArtCraft UI and shared libraries, bake and display fidelity, color management, read-only `.spp` and platform validation |
| Mainstream practitioner | ~70% | Unestimated | Production-scale baking and masking, project and package compatibility, and destination-tool checks |
| Essentials user | ~85% | Unestimated | Startup and GPU coverage, discoverable controls, and dependable save/reopen for simple mesh, paint, material and texture-export tasks |
Why alpha. Mouse/keyboard tasks verified 3D/2D painting, undo/redo, material drag and drop, mask
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 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
[v0.6.1 release](https://github.com/storytold/texturecraft/releases/tag/v0.6.1) already exists;
“first release v0.1.0” is no longer an upcoming milestone.
Native/output contracts and the future MaterialCraft, ArtCraft UI and shared-library integrations
also remain unsettled. Passing a legacy reader or a standalone export check does not complete
those future workflows.
The live baseline verified mouse and keyboard painting in 3D and 2D, undo and redo, material
drag and drop, mask and generator edits, UV rectangle fill, baking, native saving and texture
export. Separate command checks covered high-to-low transfer, UDIM packing and scene/material
export. Since then, the mask and fill controls, generator coverage, Bake Mode and export workflows
have expanded. Beta readiness still depends on representative projects, hardware and performance
coverage, project recovery and destination-tool checks. The latest published stable release is
[v0.6.1](https://github.com/storytold/texturecraft/releases/tag/v0.6.1).
A proposed beta gate is ~75% readiness plus repeatable artist tasks on representative assets:
high/low baking and smart masks, precise 3D/2D painting, a multi-set UDIM project, save/reopen
without lost work, and exports checked in destination tools. Startup failures and data-loss
blockers on the supported test matrix must be resolved. This audit does not establish that gate.
blockers on the supported test matrix must be resolved. The gate remains open.
Beta scope must identify which reworks/integrations it requires and which remain later goals.
Every adopted project/package version needs a compatibility policy and regression checks;
MaterialCraft exchange must be validated against a named producer/consumer version pair before
@@ -85,66 +73,55 @@ it is advertised as ready.
## By dimension
All percentages below are estimates. The weights sum to 100; their additive result is 59.1%,
rounded to ~60%. Hardware, performance and stability scores include confidence discounts for
incomplete validation; they are not measured success rates or speed comparisons.
With the same weights, readiness rises from 59.1% to 68.0%. The table shows the November 25 scores.
The evidence column includes the November 16 scores for comparison.
| Dimension | % ready | Weight | Hours to full | Evidence / remaining work |
|---|---:|---:|---|---|
| Features (depth) | ~65% | 30 | TBD | Core editing tasks and high/low/UDIM outputs exercised; generators, properties and specialized workflows need depth. Mask anchors landed after this assessment; live UI validation remains |
| UI/UX fidelity | ~65% | 20 | TBD | Current editing/bake/export UI checked; [gaps](docs/ui-parity.md), ArtCraft UI adoption and revalidation after refactoring remain |
| File formats / interchange | ~60% | 10 | TBD | Current native save and basic exports exercised; possible `.tcraft`/output-package reworks, unfinished upstream `.mcmat`, `.spp` and consumer validation remain |
| Hardware (GPU, pen, displays) | ~50% | 8 | TBD | One Windows GPU exercised; pen tilt, pressure across platforms and display coverage remain incomplete |
| Localization | ~35% | 4 | TBD | Ten picker languages in source; optional shared catalogs/fonts and native-language review need current measurement |
| Performance | ~40% | 10 | TBD | Dirty-tile/budgeted architecture and benchmark code exist; no matched performance budgets or large-project results from this review |
| Stability | ~55% | 10 | TBD | Small save/reopen and undo/redo passed; recovery, large projects and long sessions need coverage, including after format/library migrations |
| Platforms | ~65% | 3 | TBD | Desktop/web build and packaging paths exist; this review ran Windows only |
| Automation / ecosystem | ~75% | 5 | TBD | 178 commands and CLI/control/MCP architecture; shared-library adoption, command/UI compatibility and the future MaterialCraft contract need integration checks |
| Features (depth) | ~80% | 30 | TBD | Generators, mask actions, fill controls and bake workflows expanded. Specialized artist tasks and output fidelity still need repeatable checks. November 16 estimate ~65% |
| UI/UX fidelity | ~75% | 20 | TBD | Layer targeting, the workspace, Bake Mode and export dialogs changed. Live task, layout, shortcut and accessibility checks remain. November 16 estimate ~65% |
| File formats / interchange | ~70% | 10 | TBD | Shared import/export codecs, rebuilt UV persistence and linked `.mcmat` v3 have landed. Project/output contracts, `.spp` and destination-tool coverage remain open. November 16 estimate ~60% |
| Hardware (GPU, pen, displays) | ~50% | 8 | TBD | One Windows GPU exercised; pen tilt, pressure across platforms and display coverage remain incomplete. November 16 estimate ~50% |
| Localization | ~35% | 4 | TBD | Ten picker languages in source; optional shared catalogs/fonts and native-language review need current measurement. November 16 estimate ~35% |
| Performance | ~45% | 10 | TBD | Main added dirty-region uploads, cheaper undo snapshots and faster glTF lookups. Establish response-time and memory budgets with representative large projects. November 16 estimate ~40% |
| Stability | ~60% | 10 | TBD | The live baseline covered small save/reopen and undo/redo. Rebuilt UV layouts gained persistence checks. Recovery, large projects and long sessions remain open. November 16 estimate ~55% |
| Platforms | ~70% | 3 | TBD | Desktop and web build paths exist. Nightly packaging and supervised signing workflows landed for Windows, Linux and macOS. Install, update and hardware checks remain. November 16 estimate ~65% |
| Automation / ecosystem | ~80% | 5 | TBD | CLI, control and MCP share engine commands. Bake settings sync, UV import and generator controls have command paths. The MaterialCraft source-build round trip passed. Surface-specific integration and release-pair checks remain. November 16 estimate ~75% |
## Features
These are approximate depth/readiness estimates, not percentages of matching pixels or completed
menu entries. Feature rows overlap and are not an additional additive score.
These depth estimates overlap. The overall readiness estimate uses the weighted dimensions above.
| Area | % ready | Hours | What works / main gaps |
|---|---:|---|---|
| Projects and files | ~80% | TBD | Current `.tcraft` new/save/reopen passed with layers, effects and baked maps retained. Schema/container rework remains possible; versioning/migration policy and renewed persistence/recovery tests are needed if adopted. Large cases, Alembic HDF5 and animation remain open; PBR folder/ZIP/selected-file import landed after this assessment: `file.importPbrFolder` creates one fill layer from named maps, including packed ORM and OpenGL/DirectX normals, with a UI dialog and optional native library copy; it is not credited in this score |
| Texture sets and UDIM | ~80% | TBD | Two tiles exported at independent 128/256 px sizes with expected packed-channel values; 21 channel kinds in source. Many-set/many-tile production coverage remains untested |
| Layers, masks and effects | ~75% | TBD | UI fill/black-mask creation, generator editing/duplication and native persistence passed at the assessed revision. Mask-thumbnail context actions remain missing; effect renaming and mask-stack anchors landed afterward, with live UI validation still open |
| Painting and precise 2D work | ~70% | TBD | Mouse painting in both views, keyboard undo/redo, view shortcuts, brush gesture and UV-island rectangle fill passed. Nine tool kinds exist; brush feel, pressure/tilt, other tool task suites and complete trim sheets need validation |
| Generators and smart masks | ~45% | TBD | Seven generator kinds and 24 smart-mask presets; Position/global-balance editing worked in the UI. Shared adjustments, resolution and input slots exist; richer generators, micro-detail workflows and saving user smart masks remain incomplete |
| Materials and asset library | ~60% | TBD | 72 procedural materials and 21 smart materials; shelf search/drop worked. Legacy MaterialCraft paths exist, but the planned `.mcmat` contract is unfinished upstream. Library variety, previews and cross-app integration remain work |
| MaterialCraft `.mcmat` integration | Incomplete; upstream-dependent | TBD after contract | Current reader accepts legacy v1/v2. The proposed MaterialX-based v3 still needs upstream completion, shared-library support, TextureCraft mapping/UI and tests with real producer outputs; this is not a completed material exchange workflow |
| 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 export covers OpenPBR only (no standard_surface); complex materials and larger UDIM assets remain incomplete |
| Projects and files | ~85% | TBD | November 16 estimate ~80%. PBR folders, ZIPs and selected files import into one fill layer, with packed ORM and OpenGL/DirectX normal support. New Project can rebuild mesh UVs and persist the rebuilt layout. The shipped Material Ball project is available as a starting point. Large saves, recovery and Alembic HDF5/animation remain open |
| Texture sets and UDIM | ~85% | TBD | November 16 estimate ~80%. Baseline command checks covered two tiles at different sizes and packed maps. Bake settings can sync across sets, export settings can vary by set and map, and hovering a set highlights it in the viewport. Validate many-set, many-tile projects at production sizes |
| Layers, masks and effects | ~85% | TBD | November 16 estimate ~75%. Mask thumbnails have their own effect menu and a Shift-click toggle. Effect renaming, mask anchors and user smart-mask saving/application are implemented. Repeat the workflow in a live desktop session with undo and reopen |
| Painting and precise 2D work | ~75% | TBD | November 16 estimate ~70%. The live baseline covered mouse painting, undo/redo and UV-island rectangle fill. Main added brush presets and fixes for steep-angle strokes and intermittent pen-pressure spikes. Brush feel, pressure and tilt across devices, and trim-sheet tasks still need live checks. [Presets #259](https://github.com/storytold/texturecraft/pull/259), [strokes #442](https://github.com/storytold/texturecraft/pull/442), [pressure #399](https://github.com/storytold/texturecraft/pull/399) |
| Generators and smart masks | ~75% | TBD | November 16 estimate ~45%. 16 selectable generator kinds. Added 3D distance and gradient, UV border and diagnostic generators, grayscale conversion, rust runoff, per-kind controls, custom grunge, anchored micro-details and an enlarged preview. Validate control coverage, fidelity and performance on production assets |
| Materials and asset library | ~70% | TBD | November 16 estimate ~60%. Procedural and smart materials, user smart masks, refreshed previews and resource import with usage assignment. Fill properties support independent U/V tiling, filtering, wrapping, physical-size controls, warp and per-UV-tile projection. Validate physical scale across meshes and fill persistence in artist tasks |
| MaterialCraft `.mcmat` integration | v3 round trip passed with source builds | TBD after release-pair validation | Shared reader and the desktop MaterialCraft CLI bring in a published graph as a linked fill. Exposed controls and mesh-map inputs can drive re-cooks at the texture set resolution. v1/v2 imports require republishing. Saved baked maps can be used in the browser |
| Baking | ~75% | TBD | November 16 estimate ~60%. Bake Mode adds texture-set synchronization, automatic fitted cages, background high-poly loading and a settings-driven selected-map preview. CPU/GPU map fidelity, high/low pairs on real assets and resolution-stable wear still need validation |
| Viewport, shading and rendering | ~75% | TBD | November 16 estimate ~70%. PBR/IBL, displacement and CPU/GPU path tracing are available. Main improved camera controls and 2D navigation, including the UV tile grid, and highlights hovered texture sets. Matching material/display behavior, larger scenes and hardware ray tracing remain open |
| Color management | ~35% | TBD | Linear/sRGB handling, fixed export spaces, profile metadata and Linear/ACES-filmic tone mapping are available. The project form displays disabled OpenColorIO settings. Configurable project and display transforms remain open |
| Texture and scene export | ~85% | TBD | November 16 estimate ~75%. Desktop texture export can write companion OpenPBR MaterialX and a textured USD asset. Template editing, subfolder names, per-map overrides and URP/USD presets expanded. Standard Surface and browser companion outputs remain open. Validate complex materials, UDIM and destination tools |
| 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 |
| Workspace, panels and preferences | ~75% | TBD | November 16 estimate ~65%. Menu and layout work, camera and 2D navigation updates, and full-name tooltips for truncated layer labels. Verify small windows, keyboard navigation, docking and restart persistence on the integrated desktop build |
| Automation | ~85% | TBD | November 16 estimate ~80%. Commands cover UV import, bake sync, fill and generator controls and export. The November 16 review exercised control and CLI paths. Recheck UI reachability and direct/bridged MCP coverage on current main |
Source checks matter here: [generator kinds](crates/core/src/layer.rs) number seven even though
their shared controls have grown; [polygon fill](crates/engine/src/fill_mode.rs) already includes
triangle, polygon, UV-island and mesh modes. Current [MaterialCraft import](crates/formats/src/mcmat.rs)
accepts v2 and recognizes the newer source archive layout. That is legacy compatibility, not
completion of the next `.mcmat` integration. The [upstream v3 proposal](https://github.com/storytold/materialcraft/issues/190)
describes MaterialX plus resources in equivalent folder/ZIP deliveries and excludes native source.
Its proposed exposed controls differ from re-cooking an embedded authoring graph. The final
supported subset, version policy and authoring/re-cook workflow must be agreed and tested;
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;
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.
The [generator catalog](crates/core/src/layer.rs) defines 16 kinds, and
[polygon fill](crates/engine/src/fill_mode.rs) includes triangle, polygon, UV-island and mesh modes.
The [fill properties](crates/ui-egui/src/fill_panel.rs) and
[layer-panel tests](crates/ui-egui/tests/it/layers_panel.rs) supersede the November 16 missing-control
findings UI-01 and UI-03 through UI-06 in the [UI gap inventory](docs/ui-parity.md#missing-controls-and-workflows).
Use those findings' acceptance checks for a new live run. Color management (UI-11), generator
control and output validation (UI-12) and small-window work (UI-13) still need coverage.
### Evidence from this review
| Check | Result and limit |
|---|---|
| Baseline/build | Fetched `origin/main`; HEAD matched `62b2b13`. `cargo build -p texturecraft -p texturecraft-cli --profile verify` passed; binary reported 0.6.1 and that revision |
| Baseline/build | On November 16, fetched `origin/main`; HEAD matched `62b2b13`. `cargo build -p texturecraft -p texturecraft-cli --profile verify` passed; binary reported 0.6.1 and that revision |
| Reference UI/functionality | On an original UV cube, pointer painting, paint/fill/black-mask creation and an empty generator slot worked; seven-map self-bake at 1024 px completed. Inspected fill/projection/scale menus, mask menu and export dialog. The “Read only” title did not prevent these edits; reference save/export and output equivalence remain unchecked |
| TextureCraft UI tasks | Mouse/keyboard new project, 3D/2D strokes, Ctrl+Z/Y, F1/F2/F3, brush gesture, shelf search/drop, black mask, Position generator/global balance and effect duplication worked. UV rectangle fill wrote 88 tiles per channel and undo removed it |
| Persistence | Native UI save of the deeper four-layer case followed by command reopen preserved layers, effects, 21 painted tiles per channel and ten baked maps. Earlier command save/reopen also passed. UI-only open-dialog completion was not established |
@@ -156,16 +133,32 @@ exist; older reports must not turn them into fresh missing-feature claims.
| Rework/upstream scope | Possible `.tcraft`/output-package reworks and incoming ArtCraft UI/shared-library work are planning inputs, not completed changes. The `.mcmat` v3 proposal and current legacy reader were reviewed; no future contract or current MaterialCraft producer/consumer pair was validated |
| Not run | Full Rust tests, clippy, wasm, other operating systems, pen/display hardware matrix, large UDIM projects, long sessions, matched performance benchmarks and reference image-difference corpus |
The November 25 audit verified the following on main at `3c026860`.
- **Masks, fills and generators.** Mask target menus and toggles, linked or independent tiling, filtering and wrap, physical-size controls, warp and per-tile projection, and 16 generator kinds with per-kind controls and previews. [Layer targeting #771](https://github.com/storytold/texturecraft/pull/771), [mask toggle #841](https://github.com/storytold/texturecraft/pull/841), [fill controls #762](https://github.com/storytold/texturecraft/pull/762), [generators #826](https://github.com/storytold/texturecraft/pull/826)
- **Bake and UV import.** Per-group bake settings sync, fitted cages, background import of high-poly meshes and a settings-driven map preview. Rebuilt project UVs survive reopen. [Bake Mode #799](https://github.com/storytold/texturecraft/pull/799), [UV import #748](https://github.com/storytold/texturecraft/pull/748), [reopen regression](crates/engine/tests/it/rebuilt_uv_layout.rs)
- **Interchange and shared formats.** Merged transitions to shared glTF/GLB, COLLADA, Alembic, USD and raster I/O, with project mapping in TextureCraft. Desktop texture-export dialogs gained MaterialX and USD options, and browser downloads use shared ZIP handling. [Migration tracker](https://github.com/storytold/craft-libs/issues/778), [MaterialX #784](https://github.com/storytold/texturecraft/pull/784), [USD asset #788](https://github.com/storytold/texturecraft/pull/788), [browser ZIP #792](https://github.com/storytold/texturecraft/pull/792)
- **Procedural material exchange.** MaterialCraft publishes a ZIP containing a selected SBS graph, reachable dependencies and resources. TextureCraft inspects and cooks it through the CLI. MaterialX is an optional bake output. [Producer #270](https://github.com/storytold/materialcraft/pull/270), [consumer #644](https://github.com/storytold/texturecraft/pull/644), [commands](docs/control-protocol.md#materialcraft-materials)
- **MaterialCraft compatibility test.** With MaterialCraft CLI 0.4.1 at `998d9d8f`, the Linux integration test published a selected graph, imported its v3 archive, supplied a mesh-map input and re-cooked at the target texture set size. CLI 0.4.1 at `f9174cb` failed earlier in the test when editable `.mcraft` import passed `--graph-path`. [Producer revision](https://github.com/storytold/materialcraft/commit/998d9d8f74454df047b6fb131f57b01d00a4983b), [integration test](crates/engine/tests/it/materialcraft_link.rs)
- **Desktop startup.** Interactive launches without a project now open an empty workspace. Control launches can still request the sample. Measure startup on the supported GPU matrix. [Startup #634](https://github.com/storytold/texturecraft/pull/634), [native entry point](apps/texturecraft/src/main.rs)
- **Release automation.** Isolated nightly launch profiles and a supervised Windows x86-64, Linux x86-64 and macOS arm64 workflow, with a separate signing ref. Scheduled publication remains disabled in this revision. Publication and installation still need end-to-end evidence. [Nightly preparation](docs/nightly-release-preparation.md), [producer](.github/workflows/nightly.yml)
- **Build checks.** `cargo xtask layers` passed for all 15 workspace packages. `cargo xtask wasm` passed for ten library crates and the web app.
- **Linux regression suites.** Locked release unit and integration tests for bake, compositing, formats, engine and headless UI reported 2,978 passing, zero failing and 101 ignored. The engine session suite included the hostile-input command sweep. The real MaterialCraft test was run separately with the CLI configured.
- **Packaging checks.** The local nightly workflow and policy suite passed 28 tests. The Linux tarball launcher and Arch package handoff tests passed using a stub application.
Live desktop artist tasks, browser interaction, destination-tool fidelity, hardware coverage and
signed release installation remain outside the November 25 test evidence.
## Languages
The [picker](crates/ui-egui/src/i18n.rs) contains ten languages. Shared catalogs are optional at
build time; missing entries fall back to English, and builds without catalogs offer English only.
The older [coverage table](docs/localization-parity.md) predates catalog migration, so its “100%”
rows are not a current measurement. This audit ran an English build without external catalogs.
rows are not a current measurement. The November 16 live audit ran an English build without external catalogs.
| Language | Code | UI strings | Status |
|---|---|---|---|
| English | `en` | Source language | Exercised in this audit |
| English | `en` | Source language | Exercised in the November 16 live audit |
| Simplified Chinese | `zh-Hans` | Not remeasured | Catalog/font dependent; native review pending |
| Spanish | `es` | Not remeasured | Catalog dependent; native review pending |
| Hindi | `hi` | No picker entry | Not offered |
@@ -188,16 +181,16 @@ here. Open pull requests are not credited until merged into the assessed main re
| Rank | Milestone | Estimate |
|---|---|---|
| 1 | Reliable startup and project safety across the supported GPU/platform matrix; reproduce startup/GPU reports and exercise recovery/large saves ([#541](https://github.com/storytold/texturecraft/issues/541), [#489](https://github.com/storytold/texturecraft/issues/489)) | TBD after reproduction |
| 1 | Verify empty-workspace startup, reproduce the DirectX startup report on affected hardware, and exercise large saves and recovery across supported platforms. [#489](https://github.com/storytold/texturecraft/issues/489), [#541](https://github.com/storytold/texturecraft/issues/541) | TBD after reproduction |
| 2 | Define `.tcraft` and output-package direction, scope any reworks, and establish versioning, migration and producer/consumer acceptance cases | Unestimated; design scope open |
| 3 | Plan/adopt the incoming ArtCraft UI refactor and shared-library changes; preserve command reachability and repeat UI/persistence/platform checks after adoption | TBD after upstream contracts and consumer scope |
| 4 | Bring in the completed MaterialCraft `.mcmat` contract: agree the supported MaterialX/resources/controls subset, implement the consumer through shared APIs and validate folder/archive outputs from named versions | Upstream-dependent; format unfinished |
| 5 | Bake fidelity and dependable smart-material wear: matched assets/settings at multiple resolutions, all ten maps, high/low pairs and documented differences ([#536](https://github.com/storytold/texturecraft/issues/536), [#538](https://github.com/storytold/texturecraft/issues/538)) | TBD after map corpus |
| 6 | Generator, anchor and property depth; finish the artist-facing control inventory while preserving existing shared controls ([#374](https://github.com/storytold/texturecraft/issues/374), [#389](https://github.com/storytold/texturecraft/issues/389), [#433](https://github.com/storytold/texturecraft/issues/433)) | TBD after control audit |
| 3 | Scope ArtCraft UI adoption and remaining shared-library cutovers. Consolidate the current multiple craft-libs pins in a dedicated update, preserve command reachability and rerun acceptance checks | TBD after adoption scope |
| 4 | Set the supported MaterialCraft and TextureCraft release pair and verify its installed CLI. Extend the source-build check to bundled resources, presets, resolution changes, reopen, missing CLI behavior and v1/v2 republish guidance | TBD after producer/consumer matrix |
| 5 | Measure bake fidelity and wear across resolutions, high/low pairs, all ten maps and CPU/GPU paths. Include automatic cages, name matching, settings sync and final output versus live preview | TBD after map corpus |
| 6 | Exercise the expanded generator, anchor and property controls on production assets. Finish uncovered inputs and workflows after rechecking [#374](https://github.com/storytold/texturecraft/issues/374) and [#433](https://github.com/storytold/texturecraft/issues/433) against main | TBD after control audit |
| 7 | Brush/pen precision, feedback and discoverability; complete 3D/2D/trim-sheet tasks and set responsiveness budgets ([#545](https://github.com/storytold/texturecraft/issues/545), [#485](https://github.com/storytold/texturecraft/issues/485), [#306](https://github.com/storytold/texturecraft/issues/306)) | TBD after task tests |
| 8 | Color-managed pipeline and destination checks for USD, glTF/GLB, MaterialX and texture maps, including UDIM, complex materials and the adopted output packages | TBD after consumer matrix |
| 9 | Read-only `.spp` discovery: clean-room feasibility, recoverable data and unsupported-content reporting; convert into the adopted native format without changing the source | Unestimated; feasibility unknown |
| 10 | Release/platform regression checks, web polish, current translation coverage and native review; expand the original asset library | TBD after validation |
| 10 | Verify supervised nightly signing, install, co-installation and update on the target platforms. Repeat web and localization checks and expand the original asset library | TBD after validation |
### Dependencies and possible rework
@@ -207,26 +200,24 @@ TextureCraft adoption.
| Track | Current state | Completion / revalidation gate |
|---|---|---|
| Native `.tcraft` | Current save/load works in the audit; schema/container may change | Decide the native contract and compatibility policy. For any adopted rework, check existing projects and conversion explicitly: layers, masks, effects, resources, painted tiles, UDIM layouts and baked data; retain bounded reads, atomic saves and recovery behavior |
| Output packages | Current individual exports work within the recorded scope; future package format/content/layout is not settled | Define affected artifacts, manifests, naming, resource references and versioning. Test package relocation, folder/archive delivery where applicable, color/normal/displacement metadata and real consumers; repeat install/update checks if distribution artifacts change |
| MaterialCraft `.mcmat` | Legacy v1/v2 support exists; [v3](https://github.com/storytold/materialcraft/issues/190) is unfinished upstream | Agree the published contract and supported MaterialX subset, folder/ZIP equivalence, resources and exposed inputs. Adopt it through shared libraries and test actual MaterialCraft output in TextureCraft, including unsupported versions/features. Do not assume native-source recovery or the legacy re-cook behavior |
| Native `.tcraft` | The live baseline covered save/load. Main persists rebuilt mesh UV layouts. The future container/schema remains open | Decide the contract and compatibility policy. For any adopted migration, check layers, masks, effects, resources, painted tiles, UV layouts and baked data. Exercise bounded reads, atomic saves and recovery |
| Output packages | Export templates now support subfolders, and desktop USD/MaterialX companions reference exported textures | Define affected artifacts, manifests, naming and versioning. Check package relocation, applicable folder/archive delivery, color/normal/displacement metadata and destination tools |
| MaterialCraft `.mcmat` | The [v3 procedural ZIP contract](https://github.com/storytold/materialcraft/issues/190) and shared reader have landed. TextureCraft uses the desktop CLI for cooking and rejects v1/v2 with republish guidance | Validate supported producer and consumer versions with bundled assets, exposed controls and mesh-map inputs. Test archived sources after moving the authoring files, and saved baked maps in the browser |
| ArtCraft UI refactor | Incoming suite/UI work; shared palette/theme proposals such as [craft-libs #102](https://github.com/storytold/craft-libs/pull/102) and [#397](https://github.com/storytold/craft-libs/pull/397) are examples, not the whole refactor or an adoption claim | Scope TextureCraft's adapters/components and design changes. Keep document behavior command-driven; repeat the [UI task audit](docs/ui-parity.md), input/accessibility checks, screenshots and layout/preferences persistence tests against the adopted design |
| Shared libraries | Several shared crates are already pinned in [Cargo.toml](Cargo.toml); [format migration work](https://github.com/storytold/craft-libs/issues/778) continues | Use reviewed public APIs and keep app-specific mapping/policy local. Each adoption needs consumer integration plus compatibility, security-limit, layering, wasm and regression checks; a library change alone does not complete the app's work |
| Shared libraries | Shared format adoption now includes glTF/GLB, COLLADA, Alembic, USD, runtime raster codecs and ZIP. [Cargo.toml](Cargo.toml) declares direct dependencies at six craft-libs revisions | Consolidate the pins under the repository's single-revision convention and rerun consumer compatibility, format limit, layering, wasm and regression checks. [Migration tracker](https://github.com/storytold/craft-libs/issues/778) |
### Current focus
Keep the current functional baseline while establishing project-safety and bake-fidelity checks.
Scope `.tcraft`/output-package changes and coordinate ArtCraft UI/shared-library adoption alongside
that work, so feature work budgets include possible migration and revalidation. Bring `.mcmat`
forward against the finished upstream contract rather than treating the legacy reader as completion.
Run `.spp` feasibility separately. Hardware ray tracing is a later enhancement; beta depends on
the scoped acceptance/integration gates above. [Release validation](docs/releasing.md) continues
for existing releases; there is no outstanding “first release” gate.
Establish project-recovery, startup and bake-fidelity checks on representative assets. Scope
`.tcraft` and output-package decisions and ArtCraft UI adoption alongside those checks. Repeat
the passing source-build `.mcmat` handoff with supported release builds. Read-only `.spp` remains a separate
feasibility track. Hardware ray tracing for Rendering mode remains a later enhancement.
## Progress log
| Date | Entry |
|---|---|
| 2026-11-25 | Audited main at `3c026860`. Recorded the expanded generator catalog, mask and fill controls, Bake Mode, UV rebuilds, export migrations, the v3 material handoff and supervised nightlies. Raised estimated breadth from ~80% to ~90% and weighted readiness from ~60% to ~68% |
| 2026-11-16 | Added possible native/output-package reworks, unfinished MaterialCraft `.mcmat` integration and incoming ArtCraft UI/shared-library work as explicit roadmap tracks. Current audit scores stay tied to the tested revision; migration scope and effort remain unestimated |
| 2026-11-16 | Deeper UI/functionality audit added in [docs/ui-parity.md](docs/ui-parity.md): twenty check groups, specific missing controls, reference editing/self-bake, UI export/save, analytic high/low transfer and UDIM packing. Overall percentages remain provisional estimates |
| 2026-11-16 | Approximate live review against main `62b2b13` and reference 12.2.0. Basic edit/save/reopen, GPU bake and interchange smoke checks passed. Rebaselined reporting to ~80% breadth / ~60% readiness and recorded validation limits |
@@ -238,6 +229,7 @@ for existing releases; there is no outstanding “first release” gate.
| Date | Change | Summary |
|---|---|---|
| 2026-11-25 | major | Updated implementation status and provisional readiness for current main. Retained the November 16 scores for comparison and kept the beta acceptance gates |
| 2026-11-16 | major | Added dependency/rework scope and adoption gates; distinguished legacy `.mcmat` support from the unfinished MaterialX-based proposal; expanded upcoming work without crediting unlanded integrations |
| 2026-11-16 | major | Expanded live UI tasks and output validation; added a separate UI gap inventory with acceptance checks; distinguished UI, mixed and command evidence and CPU/GPU bake paths |
| 2026-11-16 | major | Adopted headline/audience/dimension/feature/language/upcoming tables; added main-revision evidence and uncertainty, read-only `.spp` scope, current release status and acceptance gates; removed the unsupported six-hour remainder |
+1
View File
@@ -58,6 +58,7 @@ async fn run(canvas: web_sys::HtmlCanvasElement) -> Result<(), String> {
canvas,
options,
Box::new(|cc| {
texturecraft_ui_egui::framework::install_headless(&cc.egui_ctx);
let mut app = TextureCraftApp::new(cc, session);
if let Some(rs) = &cc.wgpu_render_state {
let backend = rs.adapter.get_info().backend;
+41 -32
View File
@@ -203,8 +203,8 @@ fn saved_prefs(ui_file: Option<&std::path::Path>, persistence_path: Option<&std:
entries.and_then(|entries| ron::from_str::<UiState>(entries.get("ui")?).ok()).map(|ui| ui.prefs).unwrap_or_default()
}
/// The app with the window chrome that needs the native window: the Windows borderless guard, and
/// on macOS the traffic lights and AppKit's `movable` flag.
/// The app with the window chrome that needs the native window: the Windows borderless guard, and the native window
/// the framework runtime answers the hit test of.
struct Shell {
app: TextureCraftApp,
window_frame: Option<window_frame::WindowFrameFn>,
@@ -212,8 +212,6 @@ struct Shell {
/// 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>,
}
impl eframe::App for Shell {
@@ -240,9 +238,8 @@ impl eframe::App for Shell {
}
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
texturecraft_ui_egui::framework::before_ui(ui.ctx(), &*frame);
self.app.ui(ui, frame);
#[cfg(target_os = "macos")]
texturecraft_ui_egui::titlebar::sync_native(&self.app.title_bar, ui, frame, &mut self.movable);
}
fn on_exit(&mut self) {
@@ -262,13 +259,22 @@ fn initialize_nightly_process_identity() -> Result<(), process_identity::Identit
process_identity::initialize(build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1, os_window::id_for(LaunchIdentity::NightlyV1))
}
/// A refused Nightly start explains itself in a dialog where there is a desktop to show one.
/// Whether a refusal may also open a native message box. Standard error always carries the reason;
/// this only adds a box where one renders without the app's event loop. Never on macOS: rfd's alert
/// there needs the AppKit run loop this start has not reached, so a refused nightly launch hung in
/// an invisible modal instead of exiting (GridCraft Mac smoke, 2026-11-26).
fn refusal_dialog(flavor: build_flavor::BuildFlavor, desktop_session: bool, macos: bool) -> bool {
build_flavor::needs_native_error(flavor, desktop_session) && !macos
}
/// A refused Nightly start explains itself in a dialog where the desktop shows one without the
/// app's run loop (Windows, X11/Wayland); macOS gets the standard-error line only.
fn report_launch_profile_error(error: &str) {
eprintln!("texturecraft: {error}");
let desktop_session = cfg!(windows)
|| cfg!(target_os = "macos")
|| (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty())));
if build_flavor::needs_native_error(build_flavor::COMPILED, desktop_session) {
if refusal_dialog(build_flavor::COMPILED, desktop_session, cfg!(target_os = "macos")) {
if let Err(error) = initialize_nightly_process_identity() {
eprintln!("texturecraft: {error}");
return;
@@ -387,7 +393,8 @@ fn main() {
prefs.apply_work_threads();
prefs.apply_resource_limits();
let session = initial_session(&args);
let title_bar = TitleBar::decide(prefs.system_title_bar);
let frame_decision = TitleBar::decide(prefs.system_title_bar);
let title_bar = TitleBar::of(&frame_decision.frame);
let mut viewport = egui::ViewportBuilder::default()
.with_app_id(os_window::app_id())
.with_title(os_window::name())
@@ -396,7 +403,7 @@ fn main() {
if let Some(i) = icon() {
viewport = viewport.with_icon(i);
}
let viewport = title_bar.viewport(viewport);
let viewport = texturecraft_ui_egui::titlebar::viewport(&frame_decision, viewport);
let mut options = eframe::NativeOptions { viewport, renderer: eframe::Renderer::Wgpu, persistence_path, ..Default::default() };
if let Err(e) = gpu::configure(&mut options, args.gpu, args.power_pref) {
fatal(&e.to_string(), true);
@@ -443,7 +450,8 @@ fn main() {
if let Err(e) = craft_menu::mac::install_app_menu(&cc.egui_ctx, window_name) {
log::warn!("the app menu could not be installed: {e}");
}
let window_frame = window_frame::service(cc, matches!(title_bar, TitleBar::App(_)));
texturecraft_ui_egui::framework::install(&cc.egui_ctx, frame_decision)?;
let frame_guard = window_frame::service(cc, matches!(title_bar, TitleBar::App(_)));
let mut app = TextureCraftApp::new(cc, session);
app.title_bar = title_bar;
app.set_startup_update_check(checks_for_updates_at_start(control));
@@ -459,13 +467,7 @@ fn main() {
});
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,
}))
Ok(Box::new(Shell { app, window_frame: frame_guard, exit_hook: Some(Box::new(finish_at_exit)) }))
}),
);
// A controlled return, including a handled startup error. On macOS a window already finished in
@@ -635,13 +637,10 @@ mod tests {
/// Points within which a put-back lands on the press point (the system rounds it to whole pixels)
const PUT_BACK_REACH: f32 = 1.0;
/// One frame of the window: the system's events go through the window's raw input hook, as eframe sends them; returns what the app asked of the window
/// One frame of the window: the system's events go through the window's raw input hook (the harness runs it before
/// every pass, as eframe does); returns what the app asked of the window
fn window_frame(harness: &mut egui_kittest::Harness<'static, Shell>, events: Vec<egui::Event>) -> Vec<egui::ViewportCommand> {
let ctx = harness.ctx.clone();
let mut raw = harness.input_mut().clone();
raw.events.extend(events);
eframe::App::raw_input_hook(harness.state_mut(), &ctx, &mut raw);
*harness.input_mut() = raw;
harness.input_mut().events.extend(events);
harness.step();
harness.output().viewport_output.get(&egui::ViewportId::ROOT).map(|viewport| viewport.commands.clone()).unwrap_or_default()
}
@@ -650,14 +649,10 @@ mod tests {
#[test]
fn the_window_holds_the_pointer_while_the_preview_square_is_held() {
let session = Session::new_project("Hold", texturecraft_engine::geom::primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 128).unwrap();
let builder = egui_kittest::Harness::builder().with_size(egui::vec2(DEFAULT_SIZE[0], DEFAULT_SIZE[1]));
let mut harness = builder.build_eframe(|cc| Shell {
app: TextureCraftApp::new(cc, session),
window_frame: None,
exit_hook: None,
#[cfg(target_os = "macos")]
movable: None,
});
let builder = egui_kittest::Harness::builder()
.with_size(egui::vec2(DEFAULT_SIZE[0], DEFAULT_SIZE[1]))
.with_context_setup(texturecraft_ui_egui::framework::install_headless);
let mut harness = builder.build_eframe(|cc| Shell { app: TextureCraftApp::new(cc, session), window_frame: None, exit_hook: None });
harness.run_steps(4);
let layer = harness.state_mut().app.run("layer.add.fill", serde_json::json!({})).unwrap()["layer"].clone();
harness.state_mut().app.run("layer.fill.projection", serde_json::json!({"layer": layer, "projection": "triplanar"})).unwrap();
@@ -681,3 +676,17 @@ mod tests {
assert!(seen.is_some_and(|seen| seen.distance(pad + DRAG_STEP) <= PUT_BACK_REACH), "the app reads the whole move: {seen:?}");
}
}
#[cfg(test)]
mod refusal_dialog_tests {
use super::refusal_dialog;
use crate::build_flavor::BuildFlavor;
#[test]
fn a_refusal_never_blocks_on_a_modal_before_the_event_loop_on_macos() {
assert!(refusal_dialog(BuildFlavor::NightlyV1, true, false), "a desktop refusal still shows the box where one renders");
assert!(!refusal_dialog(BuildFlavor::NightlyV1, true, true), "macOS has no run loop yet: the modal would hang");
assert!(!refusal_dialog(BuildFlavor::NightlyV1, false, false), "a headless session has no box");
assert!(!refusal_dialog(BuildFlavor::Stable, true, false), "only a nightly refusal explains itself in a box");
}
}
+2 -2
View File
@@ -225,9 +225,9 @@ impl Headless {
/// Export the working mesh to `path` (obj, glb, usda, usdc or usdz, from `format` or the
/// extension); obj writes its .mtl and textures, usda and usdc their textures, next to it.
pub fn export_mesh(&mut self, path: &str, format: Option<&str>) -> Result<Value, AutomationError> {
pub fn export_mesh(&mut self, path: &str, format: Option<&str>, recompute_normals: bool) -> Result<Value, AutomationError> {
self.require_project()?;
let out = self.session.mesh_export(path, format)?;
let out = self.session.mesh_export_with_normals(path, format, recompute_normals)?;
let dir = Path::new(&out.path).parent().and_then(|d| d.to_str()).filter(|d| !d.is_empty()).unwrap_or(".");
self.create_dir_all(dir)?;
let mut textures = Vec::new();
+4 -3
View File
@@ -4,8 +4,9 @@
//!
//! Methods: the app's `ping`, `command.run {id, params?}`, `command.list {filter?}`,
//! `session.inspect`, plus `command.batch {steps}`, `project.open {path}`,
//! `project.save {path?}`, `mesh.import {path, resolution?, name?}`, `mesh.reimport {path?,
//! preserveStrokes?}`, `mesh.export {path, format?}`, `bake.mesh.add {path, cage?}`,
//! `project.save {path?}`, `mesh.import {path, resolution?, name?}`,
//! `mesh.reimport {path?, preserveStrokes?}`, `mesh.export {path, format?, recomputeNormals?}`,
//! `bake.mesh.add {path, cage?}`,
//! `resource.import {path}`, `material.save {path, layer?, name?}`, `material.load {path}`
//! (workspace-scoped versions of the engine commands),
//! `textures.export {dir, …}`, `render {view?, width?, height?, yaw?, pitch?}` (PNG base64, the
@@ -94,7 +95,7 @@ impl Headless {
"project.save" => self.save(str_of(p, "path")),
"mesh.import" => self.import_mesh(required(p, "path")?, u32_of(p, "resolution")?, str_of(p, "name")),
"mesh.reimport" => self.reimport_mesh(str_of(p, "path"), bool_of(p, "preserveStrokes")?),
"mesh.export" => self.export_mesh(required(p, "path")?, str_of(p, "format")),
"mesh.export" => self.export_mesh(required(p, "path")?, str_of(p, "format"), bool_of(p, "recomputeNormals")?),
"bake.mesh.add" => self.add_bake_mesh(required(p, "path")?, bool_of(p, "cage")?),
"resource.import" => self.import_resource(required(p, "path")?),
"material.save" => self.material_save(p),
+3
View File
@@ -141,6 +141,9 @@ pub struct MeshExportParams {
/// written next to it) or usdz (textures packaged); default: from the extension, else obj.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub format: Option<String>,
/// Replace stored normals with smooth area-weighted normals on the exported copy (default false).
#[serde(default, rename = "recomputeNormals", skip_serializing_if = "Option::is_none")]
pub recompute_normals: Option<bool>,
}
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
+16 -3
View File
@@ -9,12 +9,15 @@ use crate::{BakeSettings, BakeSyncGroup, BakedMap, Channel, ChannelFormat, Conte
pub use crate::env_alignment::EnvAlignment;
pub use crate::shadow_mode::ShadowMode;
/// Project file format. 3: bent normal maps are in tangent space (older files hold world-space ones).
pub const FORMAT_VERSION: u32 = 3;
/// Latest project file format that TextureCraft can read.
pub const FORMAT_VERSION: u32 = REBUILT_MESH_UVS_VERSION;
/// First format whose baked bent normal maps are in tangent space
pub const TANGENT_BENT_NORMAL_VERSION: u32 = 3;
/// First format that can reopen a project using rebuilt mesh UVs.
pub const REBUILT_MESH_UVS_VERSION: u32 = 4;
/// Most colour swatches a project keeps
pub const MAX_SWATCHES: usize = 64;
@@ -429,6 +432,10 @@ pub struct Project {
/// it, so parts the file leaves unnamed get the same name (from it) as on import.
#[serde(default, skip_serializing_if = "String::is_empty")]
pub mesh_file: String,
/// The mesh UVs were rebuilt on import. The project file keeps the generated layout for
/// reopening; reimporting the mesh from a file rebuilds them again.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub mesh_rebuild_uvs: bool,
/// Where the mesh file was imported from (the project's "3D mesh path"). Reimport mesh reads
/// it again from there, so edits made to the file since are picked up. Empty when unknown
/// (built-in meshes, web imports, projects saved before it was kept).
@@ -450,10 +457,11 @@ pub struct Project {
impl Project {
pub fn new(name: impl Into<String>, mesh: impl Into<String>) -> Project {
Project {
format_version: FORMAT_VERSION,
format_version: TANGENT_BENT_NORMAL_VERSION,
name: name.into(),
mesh: mesh.into(),
mesh_file: String::new(),
mesh_rebuild_uvs: false,
mesh_path: String::new(),
normal_format: NormalFormat::OpenGl,
texture_sets: Vec::new(),
@@ -465,6 +473,11 @@ impl Project {
}
}
/// The on-disk version that preserves the project's UV layout when read back.
pub fn save_format_version(&self) -> u32 {
if self.mesh_rebuild_uvs { self.format_version.max(REBUILT_MESH_UVS_VERSION) } else { self.format_version }
}
pub fn alloc_id(&mut self) -> LayerId {
let id = LayerId(self.next_id);
self.next_id = self.next_id.saturating_add(1);
+11 -15
View File
@@ -93,6 +93,14 @@ pub fn set_gpu_raytracing(enabled: bool) {
/// The tracer a bake starting now uses: the installed one while GPU raytracing is on, else none (the CPU)
fn chosen_tracer(installed: Option<&Arc<dyn Tracer>>, enabled: bool) -> Option<Arc<dyn Tracer>> {
// The coverage build bakes on the CPU, the fallback every GPU failure takes anyway. Its tests run on
// a headless runner, and the bake's GPU device is created on a worker thread there: tearing that
// GL context down crashes the test process at exit (a wgpu-hal GLES `BadDisplay` panic, or a
// SIGSEGV in the driver), which took a different test down on every run. The compute shaders are
// never line-covered, so nothing is lost.
if cfg!(coverage) {
return None;
}
installed.filter(|_| enabled).cloned()
}
@@ -387,20 +395,6 @@ impl Session {
}
}
}
pub(crate) fn saved_bake_paint(&self) -> BTreeMap<(usize, BakePaintTarget), texturecraft_formats::BakePaintData> {
self.doc
.bake_paint
.iter()
.map(|(key, map)| (*key, texturecraft_formats::BakePaintData { width: map.width, height: map.height, values: map.values.clone() }))
.collect()
}
/// The bake meshes for a project file: (high polys, cage)
pub(crate) fn saved_bake_meshes(&self) -> (Vec<MeshFile>, Option<MeshFile>) {
let entry = |mesh: &BakeMesh| (mesh.name.clone(), mesh.bytes.as_ref().clone());
(self.doc.bake_meshes.high.iter().map(entry).collect(), self.doc.bake_meshes.cage.as_ref().map(entry))
}
}
/// `bake.highPoly.list`: the high polys and the cage (also part of `project.inspect`).
@@ -917,7 +911,9 @@ mod gpu_raytracing_tests {
fn bakes_use_the_installed_gpu_tracer_only_while_gpu_raytracing_is_on() {
let installed: Arc<dyn Tracer> = Arc::new(NamedTracer);
assert_eq!(chosen_tracer(Some(&installed), true).map(|tracer| tracer.name()), Some("gpu".to_string()));
// A coverage build keeps every bake on the CPU: its headless runner has no GPU to bake on
let gpu = (!cfg!(coverage)).then(|| "gpu".to_string());
assert_eq!(chosen_tracer(Some(&installed), true).map(|tracer| tracer.name()), gpu, "on casts the rays on the GPU");
assert!(chosen_tracer(Some(&installed), false).is_none(), "off keeps the rays on the CPU");
assert!(chosen_tracer(None, true).is_none(), "no installed tracer bakes on the CPU");
}
+248 -87
View File
@@ -12,13 +12,37 @@ use serde_json::{Value, json};
use texturecraft_core::{NormalFormat, PROJECT_EXT};
use texturecraft_core::{Project, TextureSet};
use texturecraft_formats::PlannedFile;
use texturecraft_formats::mesh_import::{MeshUvSource, import_mesh_geometry};
use texturecraft_formats::{ExportInput, ExportOptions, ExportedFile, FileFormat, MapOverride, Padding, ProjectFile};
use texturecraft_geom::glam::Vec2;
use texturecraft_geom::{Mesh, primitives};
use crate::commands::{CommandSpec, always, bad, normal_format_param, strp, u64p};
use crate::session::{Document, Session};
use crate::{EngineError, Result, cmd};
type BakePaintMaps = BTreeMap<(usize, texturecraft_core::BakePaintTarget), Arc<texturecraft_bake::BakePaintMap>>;
fn prepare_archive<Bytes>(archive: &mut ProjectFile<Bytes, Bytes>, uv_source: Option<&Mesh>, bake_paint: &BakePaintMaps) {
let project = &mut archive.project;
project.format_version = project.save_format_version();
// Drop pixel images whose size no longer matches their texture set
let size_of = |id: texturecraft_core::LayerId| {
project.locate(id).and_then(|(ts, _, _)| project.texture_sets.get(ts)).map(TextureSet::size).or_else(|| {
project.effect(id).and_then(|(owner, _)| project.locate(owner)).and_then(|(ts, _, _)| project.texture_sets.get(ts)).map(TextureSet::size)
})
};
archive.pixels.layers.retain(|(id, _), img| size_of(*id) == Some((img.width(), img.height())));
archive.pixels.masks.retain(|id, img| size_of(*id) == Some((img.width(), img.height())));
archive.mesh_uvs = uv_source.map(texturecraft_formats::mesh_import::corner_uvs);
archive.bake_paint = bake_paint
.iter()
.map(|(key, map)| (*key, texturecraft_formats::BakePaintData { width: map.width, height: map.height, values: map.values.clone() }))
.collect();
}
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
@@ -26,7 +50,7 @@ pub fn specs() -> Vec<CommandSpec> {
"New project from a mesh file",
[],
None,
"{mesh: path to .glb/.gltf/.fbx/.dae/.usd/.usda/.usdc/.usdz/.abc/.obj/.ply/.stl, resolution?: 2048, name?, uvTiles?: bool (UDIM; default: when the UVs leave tile 1001), template?: project template name, importCameras?: bool (default true: keep the cameras stored in the file)}",
"{mesh: path to .glb/.gltf/.fbx/.dae/.usd/.usda/.usdc/.usdz/.abc/.obj/.ply/.stl, resolution?: 2048, name?, uvTiles?: bool (UDIM; default: when the UVs leave tile 1001), rebuildUvs?: bool (default false: auto-unwrap where needed), template?: project template name, importCameras?: bool (default true: keep the cameras stored in the file)}",
always,
new_from_mesh
),
@@ -67,7 +91,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export Mesh...",
["File"],
None,
"{path: .obj, .glb, .usda, .usdc or .usdz file, format?: obj|glb|usda|usdc|usdz (default: from the extension, else obj); obj writes its .mtl and textures, usda/usdc their textures, next to the file} → {path, textures?}",
"{path: .obj, .glb, .usda, .usdc or .usdz file, format?: obj|glb|usda|usdc|usdz (default: from the extension, else obj), recomputeNormals?: bool (default false: smooth area-weighted normals replace the stored normals on the exported copy only); obj writes its .mtl and textures, usda/usdc their textures, next to the file} → {path, textures?}",
always,
export_mesh
),
@@ -101,24 +125,44 @@ fn leaf_of(name: &str) -> String {
}
/// Read the project's stored mesh `bytes` (extension `ext`) under the name it was imported
/// with, so its unnamed parts keep their names (and the geometry masks that use them).
fn read_stored_mesh(project: &Project, ext: &str, bytes: &[u8]) -> Result<texturecraft_formats::ImportedMesh> {
let stem = std::path::Path::new(&project.mesh_file).file_stem().and_then(|s| s.to_str()).filter(|s| !s.is_empty()).unwrap_or("mesh");
texturecraft_formats::import_mesh_bytes(&format!("{stem}.{ext}"), bytes).map_err(fe)
/// with, so its unnamed parts keep their names (and the geometry masks that use them). A saved
/// UV layout replaces the file's UVs and the automatic unwrap.
fn read_stored_mesh(project: &Project, ext: &str, bytes: &[u8], saved_layout: Option<&[Vec2]>) -> Result<Mesh> {
let stem = std::path::Path::new(&project.mesh_file).file_stem().and_then(|stem| stem.to_str()).filter(|stem| !stem.is_empty()).unwrap_or("mesh");
let file_name = format!("{stem}.{ext}");
import_mesh_geometry(&file_name, bytes, saved_layout.map_or(MeshUvSource::FromFile, MeshUvSource::Saved)).map_err(fe)
}
impl Session {
/// The working mesh as Wavefront OBJ (with its own UVs, UDIM tiles included).
pub fn mesh_obj_bytes(&self) -> Result<Vec<u8>> {
texturecraft_formats::obj_bytes(&self.source_mesh(), &self.doc.project.name).map_err(fe)
self.mesh_obj_bytes_with_normals(false)
}
/// [`Session::mesh_obj_bytes`], optionally replacing normals on the exported copy only.
pub fn mesh_obj_bytes_with_normals(&self, recompute_normals: bool) -> Result<Vec<u8>> {
let mut mesh = self.source_mesh();
if recompute_normals {
mesh.compute_smooth_normals();
}
texturecraft_formats::obj_bytes(&mesh, &self.doc.project.name).map_err(fe)
}
/// [`Session::mesh_obj_bytes`] with an MTL material library and each material's maps (like
/// [`Session::mesh_usd`]'s), to write next to it, named after `stem` (the OBJ file's).
pub fn mesh_obj_with_mtl(&mut self, stem: &str) -> Result<(Vec<u8>, texturecraft_formats::NamedFiles)> {
self.mesh_obj_with_mtl_and_normals(stem, false)
}
/// [`Session::mesh_obj_with_mtl`], optionally replacing normals on the exported copy only.
pub fn mesh_obj_with_mtl_and_normals(&mut self, stem: &str, recompute_normals: bool) -> Result<(Vec<u8>, texturecraft_formats::NamedFiles)> {
// shortcut: UV-tiled sets get no maps (the OBJ keeps the mesh's UDIM UVs and an MTL map is
// one image); their tiles export through Export textures with `$udim` names.
let mut mesh = self.source_mesh();
if recompute_normals {
mesh.compute_smooth_normals();
}
// A mesh without materials has one implicit material (and texture set).
if mesh.materials.is_empty() {
mesh.materials.push("default".into());
@@ -131,16 +175,34 @@ impl Session {
/// composite, through the texture export pipeline) embedded. glTF has no UV tiles: a
/// UV-tiled set embeds its tile atlas, with the mesh's UVs in atlas space.
pub fn mesh_glb_bytes(&mut self) -> Result<Vec<u8>> {
self.mesh_glb_bytes_with_normals(false)
}
/// [`Session::mesh_glb_bytes`], optionally replacing normals on the exported copy only.
pub fn mesh_glb_bytes_with_normals(&mut self, recompute_normals: bool) -> Result<Vec<u8>> {
let files = self.material_files(texturecraft_formats::glb_export_options(), true, self.mesh.materials.len())?;
let textures: Vec<_> = files.into_iter().map(texturecraft_formats::GlbTextures::from_files).collect();
texturecraft_formats::glb_bytes(&self.mesh, &self.doc.project.name, &textures).map_err(fe)
let mut mesh = self.mesh.as_ref().clone();
if recompute_normals {
mesh.compute_smooth_normals();
}
texturecraft_formats::glb_bytes(&mesh, &self.doc.project.name, &textures).map_err(fe)
}
/// The working mesh as USD with a UsdPreviewSurface per material (textures like
/// [`Session::mesh_glb_bytes`]): usdz packages them, usda / usdc list them to write alongside.
pub fn mesh_usd(&mut self, format: texturecraft_formats::UsdFormat) -> Result<texturecraft_formats::UsdExport> {
self.mesh_usd_with_normals(format, false)
}
/// [`Session::mesh_usd`], optionally replacing normals on the exported copy only.
pub fn mesh_usd_with_normals(&mut self, format: texturecraft_formats::UsdFormat, recompute_normals: bool) -> Result<texturecraft_formats::UsdExport> {
let files = self.material_files(texturecraft_formats::usd_export_options(), true, self.mesh.materials.len())?;
texturecraft_formats::usd_bytes(&self.mesh, &self.doc.project.name, &files, format).map_err(fe)
let mut mesh = self.mesh.as_ref().clone();
if recompute_normals {
mesh.compute_smooth_normals();
}
texturecraft_formats::usd_bytes(&mesh, &self.doc.project.name, &files, format).map_err(fe)
}
/// The texture sets of the first `materials` materials rendered with `opts` (as a tile atlas
@@ -163,19 +225,25 @@ impl Session {
/// [`Session::from_mesh_bytes`] with a UV tile mode (see [`Session::new_project_tiled`]).
pub fn from_mesh_bytes_tiled(file_name: &str, bytes: &[u8], resolution: u32, name: &str, uv_tiles: Option<bool>) -> Result<Session> {
Self::from_mesh_source(file_name, Cow::Borrowed(bytes), resolution, name, uv_tiles)
Self::from_mesh_bytes_with_uvs(file_name, bytes, resolution, name, uv_tiles, false)
}
fn from_mesh_source(file_name: &str, bytes: Cow<'_, [u8]>, resolution: u32, name: &str, uv_tiles: Option<bool>) -> Result<Session> {
let imported = texturecraft_formats::import_mesh_bytes(file_name, &bytes).map_err(fe)?;
/// Create a project with an explicit choice to rebuild the imported mesh's UVs.
pub fn from_mesh_bytes_with_uvs(file_name: &str, bytes: &[u8], resolution: u32, name: &str, uv_tiles: Option<bool>, rebuild_uvs: bool) -> Result<Session> {
Self::from_mesh_source(file_name, Cow::Borrowed(bytes), resolution, name, uv_tiles, rebuild_uvs)
}
fn from_mesh_source(file_name: &str, bytes: Cow<'_, [u8]>, resolution: u32, name: &str, uv_tiles: Option<bool>, rebuild_uvs: bool) -> Result<Session> {
let imported = texturecraft_formats::mesh_import::import_mesh_bytes_with_uvs(file_name, &bytes, rebuild_uvs).map_err(fe)?;
let extension = ext_of(file_name);
let mut session = Session::new_project_tiled(name, imported.mesh, &format!("mesh.{extension}"), None, resolution, uv_tiles)?;
// Packed mesh files can have spare capacity that the project would otherwise retain
let mut source = bytes.into_owned();
source.shrink_to_fit();
session.mesh_source = Some((extension, source));
session.mesh_source = Some((extension, Arc::new(source)));
session.doc.project.mesh_file = leaf_of(file_name);
session.doc.project.mesh_rebuild_uvs = rebuild_uvs;
session.doc.project.cameras = imported.cameras;
session.log.warnings("Importer", imported.report.warnings);
@@ -199,74 +267,79 @@ impl Session {
Session::from_project_file(pf)
}
pub fn from_project_file(pf: ProjectFile) -> Result<Session> {
let mesh = match (&pf.mesh, pf.project.mesh.strip_prefix("builtin:")) {
pub fn from_project_file(project_file: ProjectFile) -> Result<Session> {
project_file.validate_mesh_uvs().map_err(fe)?;
let mesh = match (&project_file.mesh, project_file.project.mesh.strip_prefix("builtin:")) {
(_, Some(id)) => primitives::builtin(id).ok_or_else(|| EngineError::Other(format!("unknown built-in mesh `{id}`")))?,
(Some((ext, bytes)), None) => read_stored_mesh(&pf.project, ext, bytes)?.mesh,
(Some((ext, bytes)), None) => read_stored_mesh(&project_file.project, ext, bytes, project_file.mesh_uvs.as_deref())?,
(None, None) => return Err(EngineError::Other("the project has no mesh".into())),
};
check_materials(&pf.project, &mesh)?;
let source = pf.mesh.clone();
let resources = pf.resources.into_iter().map(|(k, v)| (k, std::sync::Arc::new(v))).collect();
// Mesh construction consumed the layout data, so release it before building session caches
drop(project_file.mesh_uvs);
check_materials(&project_file.project, &mesh)?;
let resources = project_file.resources.into_iter().map(|(name, bytes)| (name, Arc::new(bytes))).collect();
let mut s = Session::new(
Document { bake_meshes: Default::default(), bake_paint: Default::default(), project: pf.project, pixels: pf.pixels, baked: pf.baked, resources },
let mut session = Session::new(
Document {
bake_meshes: Default::default(),
bake_paint: Default::default(),
project: project_file.project,
pixels: project_file.pixels,
baked: project_file.baked,
resources,
},
mesh,
source,
project_file.mesh,
)?;
s.sync_images();
s.load_bake_meshes(pf.high_poly, pf.cage);
s.load_bake_paint(pf.bake_paint);
s.log.warnings("Project", pf.warnings);
session.sync_images();
session.load_bake_meshes(project_file.high_poly, project_file.cage);
session.load_bake_paint(project_file.bake_paint);
session.log.warnings("Project", project_file.warnings);
Ok(s)
Ok(session)
}
/// The project with independently owned resource bytes.
pub fn project_file(&self) -> ProjectFile {
let resources = self.doc.resources.iter().map(|(name, bytes)| (name.clone(), bytes.as_ref().clone())).collect();
self.project_with_resources(resources)
}
/// A save snapshot that shares immutable resource payloads with the document.
pub fn project_snapshot(&self) -> ProjectFile<Arc<Vec<u8>>> {
self.project_with_resources(self.doc.resources.clone())
}
fn project_with_resources<Resource>(&self, resources: BTreeMap<String, Resource>) -> ProjectFile<Resource> {
let mut pixels = self.doc.pixels.clone();
// Drop pixel images whose size no longer matches their texture set
let size_of = |id: texturecraft_core::LayerId| {
self.doc.project.locate(id).and_then(|(ts, _, _)| self.doc.project.texture_sets.get(ts)).map(TextureSet::size).or_else(|| {
self.doc
.project
.effect(id)
.and_then(|(owner, _)| self.doc.project.locate(owner))
.and_then(|(ts, _, _)| self.doc.project.texture_sets.get(ts))
.map(TextureSet::size)
})
};
pixels.layers.retain(|(id, _), img| size_of(*id) == Some((img.width(), img.height())));
pixels.masks.retain(|id, img| size_of(*id) == Some((img.width(), img.height())));
let (high_poly, cage) = self.saved_bake_meshes();
/// Capture just the archive inputs. The caller prepares derived data before writing.
fn capture_archive<Bytes>(&self, resources: BTreeMap<String, Bytes>, store_mesh_bytes: impl Fn(&Arc<Vec<u8>>) -> Bytes) -> ProjectFile<Bytes, Bytes> {
let bake_mesh = |mesh: &crate::BakeMesh| (mesh.name.clone(), store_mesh_bytes(&mesh.bytes));
ProjectFile {
project: self.doc.project.clone(),
pixels,
pixels: self.doc.pixels.clone(),
baked: self.doc.baked.clone(),
mesh: self.mesh_source.clone(),
high_poly,
cage,
bake_paint: self.saved_bake_paint(),
mesh: self.mesh_source.as_ref().map(|(extension, bytes)| (extension.clone(), store_mesh_bytes(bytes))),
mesh_uvs: None,
high_poly: self.doc.bake_meshes.high.iter().map(bake_mesh).collect(),
cage: self.doc.bake_meshes.cage.as_ref().map(bake_mesh),
bake_paint: BTreeMap::new(),
thumbnail: None,
resources,
warnings: Vec::new(),
}
}
/// The project with independently owned resource and mesh bytes.
pub fn project_file(&self) -> ProjectFile {
let resources = self.doc.resources.iter().map(|(name, bytes)| (name.clone(), bytes.as_ref().clone())).collect();
let mut archive = self.capture_archive(resources, |bytes| bytes.as_ref().clone());
prepare_archive(&mut archive, self.saved_uv_source().map(Arc::as_ref), &self.doc.bake_paint);
archive
}
/// A save snapshot that shares immutable resource and mesh payloads with the document.
pub fn project_snapshot(&self) -> ProjectFile<Arc<Vec<u8>>, Arc<Vec<u8>>> {
let mut archive = self.capture_archive(self.doc.resources.clone(), Arc::clone);
prepare_archive(&mut archive, self.saved_uv_source().map(Arc::as_ref), &self.doc.bake_paint);
archive
}
/// The imported geometry needed to save rebuilt corner UVs and skip unwrapping on reopen.
fn saved_uv_source(&self) -> Option<&Arc<Mesh>> {
(self.doc.project.mesh_rebuild_uvs && self.mesh_source.is_some()).then_some(&self.source)
}
pub fn to_project_bytes(&self) -> Result<Vec<u8>> {
let mut reservation = texturecraft_formats::RamReservation::for_save().map_err(fe)?;
reservation.save_bytes(&self.project_snapshot()).map_err(fe)
@@ -507,23 +580,24 @@ mod native {
}
pub fn save_to(s: &mut Session, path: &str, adopt: bool) -> Result<Value> {
let path = if ext_of(path) == PROJECT_EXT { path.to_string() } else { format!("{path}.{PROJECT_EXT}") };
let mut reservation = texturecraft_formats::RamReservation::for_save().map_err(fe)?;
reservation.save(Path::new(&path), &s.project_snapshot()).map_err(fe)?;
if adopt {
s.path = Some(path.clone());
s.modified = false;
}
s.log.info("Project", format!("Saved {path}"));
Ok(json!({ "path": path }))
let output = s.save_task(path, adopt).run(None)?;
output.apply(s);
Ok(json!({ "path": output.path }))
}
}
#[cfg(not(target_arch = "wasm32"))]
pub use native::{absolute, open_path, read_mesh};
#[cfg(not(target_arch = "wasm32"))]
mod save_output;
#[cfg(not(target_arch = "wasm32"))]
mod save_target;
#[cfg(not(target_arch = "wasm32"))]
mod save_task;
#[cfg(not(target_arch = "wasm32"))]
pub use {save_output::SaveOutput, save_task::SaveTask};
/// `file.new {mesh, name?, resolution?, uvTiles?, template?, importCameras?}`: a new project from the
/// `file.new {mesh, name?, resolution?, uvTiles?, rebuildUvs?, template?, importCameras?}`: a new project from the
/// mesh file `mesh`, remembering its path for Reimport mesh.
#[cfg(not(target_arch = "wasm32"))]
fn new_from_mesh(session: &mut Session, params: &Value) -> Result<Value> {
@@ -534,9 +608,11 @@ fn new_from_mesh(session: &mut Session, params: &Value) -> Result<Value> {
let resolution = u64p(params, "resolution").or(template.as_ref().map(|template| u64::from(template.resolution))).unwrap_or(DEFAULT_RESOLUTION_PX);
let name = strp(params, "name").map(str::to_string).unwrap_or_else(|| stem_of(path));
let uv_tiles = crate::commands::boolp(params, "uvTiles");
let rebuild_uvs = crate::commands::boolp(params, "rebuildUvs").unwrap_or(false);
let mesh_file = native::read_mesh("file.new", path)?;
let mut next = Session::from_mesh_source(&mesh_file.name, Cow::Owned(mesh_file.bytes), u32::try_from(resolution).unwrap_or(0), &name, uv_tiles)?;
let mut next =
Session::from_mesh_source(&mesh_file.name, Cow::Owned(mesh_file.bytes), u32::try_from(resolution).unwrap_or(0), &name, uv_tiles, rebuild_uvs)?;
next.doc.project.mesh_path = native::absolute(path);
next.log.warnings("Importer", mesh_file.warnings);
if crate::commands::boolp(params, "importCameras") == Some(false) {
@@ -599,9 +675,11 @@ fn reimport(s: &mut Session, p: &Value) -> Result<Value> {
fn change_mesh(s: &mut Session, p: &Value) -> Result<Value> {
let path = native::path_param(p, "path", "file.changeMesh")?;
let file = native::read_mesh("file.changeMesh", path)?;
let reply = s.reimport_mesh(Some(file), crate::commands::boolp(p, "preserveStrokes").unwrap_or(true))?;
// Only after the swap succeeded: Reimport mesh and Save keep following the new file.
let reply = s.replace_mesh(Some(file), crate::commands::boolp(p, "preserveStrokes").unwrap_or(true), false)?;
// Keep following the original path if the swap fails
s.doc.project.mesh_path = native::absolute(path);
Ok(reply)
}
@@ -612,16 +690,24 @@ impl Session {
Some(self.doc.project.mesh_path.as_str()).filter(|m| !m.is_empty() && std::path::Path::new(m).is_file())
}
/// Replace the mesh with `file` (or re-read the project's own copy), keeping the project when the new mesh fits it; `preserve_strokes` moves painted pixels with the surface; replies `{preserved?}`
/// Replace the mesh with `file` or re-read the project's own copy.
/// With `preserve_strokes`, painted pixels follow the surface. The reply includes
/// `preserved` when preservation was requested.
pub fn reimport_mesh(&mut self, file: Option<texturecraft_formats::MeshFile>, preserve_strokes: bool) -> Result<Value> {
let (mesh, source, warnings, mesh_file) = match file {
Some(f) => {
let m = texturecraft_formats::import_mesh_bytes(&f.name, &f.bytes).map_err(fe)?.mesh;
(m, Some((ext_of(&f.name), f.bytes)), f.warnings, leaf_of(&f.name))
self.replace_mesh(file, preserve_strokes, self.doc.project.mesh_rebuild_uvs)
}
fn replace_mesh(&mut self, file: Option<texturecraft_formats::MeshFile>, preserve_strokes: bool, rebuild_uvs: bool) -> Result<Value> {
let (mesh, replacement_source, warnings, mesh_file) = match file {
Some(file) => {
let mesh = import_mesh_geometry(&file.name, &file.bytes, MeshUvSource::from_rebuild_setting(rebuild_uvs)).map_err(fe)?;
(mesh, Some((ext_of(&file.name), file.bytes)), file.warnings, leaf_of(&file.name))
}
None => match &self.mesh_source {
Some((ext, bytes)) => {
(read_stored_mesh(&self.doc.project, ext, bytes)?.mesh, self.mesh_source.clone(), Vec::new(), self.doc.project.mesh_file.clone())
let layout = self.saved_uv_source().map(|source| texturecraft_formats::mesh_import::corner_uvs(source));
let mesh = read_stored_mesh(&self.doc.project, ext, bytes, layout.as_deref())?;
(mesh, None, Vec::new(), self.doc.project.mesh_file.clone())
}
None => return Err(bad("file.reimportMesh", "built-in meshes can't be reimported; give `path`")),
},
@@ -629,12 +715,14 @@ impl Session {
check_materials(&self.doc.project, &mesh)?;
let mut doc = self.doc.clone();
if let Some((ext, _)) = &source {
let extension = replacement_source.as_ref().map(|(extension, _)| extension).or_else(|| self.mesh_source.as_ref().map(|(extension, _)| extension));
if let Some(ext) = extension {
doc.project.mesh = format!("mesh.{ext}");
doc.project.mesh_file = mesh_file;
doc.project.mesh_rebuild_uvs = rebuild_uvs;
}
let mut next = Session::new(doc, mesh, source)?;
let mut next = Session::new(doc, mesh, replacement_source)?;
next.log.warnings("Importer", warnings);
next.path = self.path.clone();
next.sync_images();
@@ -645,6 +733,7 @@ impl Session {
next.doc.bake_meshes.cage = None;
next.log.warn("Project", "the cage mesh was dropped: the low-poly mesh changed");
}
if self.doc.bake_paint.keys().any(|(_, target)| *target == texturecraft_core::BakePaintTarget::Skew) && self.source.uvs != next.source.uvs {
next.log.warn("Project", "the skew map is laid over the old UV layout; check it in Bake mode");
}
@@ -652,6 +741,12 @@ impl Session {
next.modified = true;
next.project_id = self.project_id;
let preserved = preserve_strokes.then(|| crate::preserve::preserve_strokes(self, &mut next));
// Keep the stored source in the current session until reimport succeeds
if next.mesh_source.is_none() {
next.mesh_source = self.mesh_source.take();
}
self.switch_to(next);
Ok(preserved.map_or(Value::Null, |n| json!({ "preserved": n })))
}
@@ -1109,7 +1204,7 @@ fn write_materialx(
#[cfg(not(target_arch = "wasm32"))]
fn export_mesh(s: &mut Session, p: &Value) -> Result<Value> {
let path = native::path_param(p, "path", "file.exportMesh")?;
let out = s.mesh_export(path, strp(p, "format"))?;
let out = s.mesh_export_with_normals(path, strp(p, "format"), crate::commands::boolp(p, "recomputeNormals").unwrap_or(false))?;
let dir = std::path::Path::new(&out.path).parent().unwrap_or(std::path::Path::new(""));
let texture_paths: Vec<std::path::PathBuf> = out.textures.iter().map(|(name, _)| dir.join(name)).collect();
let main_path = std::path::PathBuf::from(&out.path);
@@ -1146,6 +1241,12 @@ impl Session {
/// The working mesh as a file for `path`, in `format` (obj, glb, usda, usdc, usdz; default:
/// from the extension, else OBJ). The extension is appended when it doesn't match.
pub fn mesh_export(&mut self, path: &str, format: Option<&str>) -> Result<MeshExport> {
self.mesh_export_with_normals(path, format, false)
}
/// [`Session::mesh_export`], optionally computing smooth area-weighted normals on the
/// exported copy. The project's source and render meshes are never changed.
pub fn mesh_export_with_normals(&mut self, path: &str, format: Option<&str>, recompute_normals: bool) -> Result<MeshExport> {
let ext = match format {
Some(f) if MESH_EXPORT_FORMATS.contains(&f) => f.to_string(),
Some(other) => return Err(bad("file.exportMesh", format!("unknown mesh format `{other}` ({})", MESH_EXPORT_FORMATS.join(", ")))),
@@ -1154,12 +1255,12 @@ impl Session {
};
let path = if ext_of(path) == ext { path.to_string() } else { format!("{path}.{ext}") };
let (bytes, textures) = match (ext.as_str(), texturecraft_formats::UsdFormat::from_ext(&ext)) {
("glb", _) => (self.mesh_glb_bytes()?, Vec::new()),
("glb", _) => (self.mesh_glb_bytes_with_normals(recompute_normals)?, Vec::new()),
(_, Some(format)) => {
let usd = self.mesh_usd(format)?;
let usd = self.mesh_usd_with_normals(format, recompute_normals)?;
(usd.bytes, usd.textures)
}
_ => self.mesh_obj_with_mtl(std::path::Path::new(&path).file_stem().and_then(|s| s.to_str()).unwrap_or("mesh"))?,
_ => self.mesh_obj_with_mtl_and_normals(std::path::Path::new(&path).file_stem().and_then(|s| s.to_str()).unwrap_or("mesh"), recompute_normals)?,
};
Ok(MeshExport { path, bytes, textures })
}
@@ -1352,6 +1453,66 @@ f 1/1 2/2 3/3
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn mesh_export_can_recompute_normals_without_changing_the_project() {
let mut s = Session::new_project("t", primitives::cube(1.0), "builtin:cube", None, 128).unwrap();
std::sync::Arc::make_mut(&mut s.source).normals.fill(texturecraft_geom::glam::Vec3::Y);
std::sync::Arc::make_mut(&mut s.mesh).normals.fill(texturecraft_geom::glam::Vec3::Y);
let mut expected = s.source_mesh();
expected.compute_smooth_normals();
let dir = std::env::temp_dir().join(format!("tc_export_recompute_{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
for (format, suffix) in [("obj", "obj"), ("glb", "glb"), ("usda", "usda")] {
let path = dir.join(format!("cube-{format}.{suffix}"));
let reply = crate::execute(&mut s, "file.exportMesh", &json!({"path": path, "recomputeNormals": true})).unwrap();
let bytes = std::fs::read(reply["path"].as_str().unwrap()).unwrap();
let back = texturecraft_formats::import_mesh_bytes(&format!("cube.{suffix}"), &bytes).unwrap().mesh;
assert_eq!(back.normals.len(), expected.normals.len(), "{format}: one normal per exported vertex");
for (position, actual) in back.positions.iter().zip(&back.normals) {
let wanted = expected
.positions
.iter()
.zip(&expected.normals)
.find_map(|(expected_position, normal)| ((*expected_position - *position).length() < 1e-4).then_some(*normal))
.unwrap_or_else(|| panic!("{format}: exported position {position:?} is missing from the source"));
assert!((*actual - wanted).length() < 1e-4, "{format}: actual {actual:?}, wanted {wanted:?}");
}
}
assert!(s.source.normals.iter().all(|n| *n == texturecraft_geom::glam::Vec3::Y), "the source project is unchanged");
assert!(s.mesh.normals.iter().all(|n| *n == texturecraft_geom::glam::Vec3::Y), "the render project is unchanged");
let stored_path = dir.join("stored.obj");
let stored = crate::execute(&mut s, "file.exportMesh", &json!({"path": stored_path})).unwrap();
let stored = std::fs::read(stored["path"].as_str().unwrap()).unwrap();
let stored = texturecraft_formats::import_mesh_bytes("stored.obj", &stored).unwrap().mesh;
assert!(stored.normals.iter().all(|n| *n == texturecraft_geom::glam::Vec3::Y), "the default keeps stored normals for compatibility");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn recomputed_normals_weld_uv_seams_in_exported_mesh() {
use texturecraft_geom::glam::Vec3;
// Two triangles meet along 0--2, but their UV island split duplicates that edge as 3--4.
let positions = vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::ZERO, Vec3::Y, Vec3::new(-1.0, 0.0, 1.0)];
let mesh = Mesh::from_parts(
positions,
Some(vec![Vec3::Y; 6]),
vec![Vec2::new(0.0, 0.0), Vec2::new(0.5, 0.5), Vec2::new(0.0, 1.0), Vec2::new(1.0, 0.0), Vec2::new(1.0, 1.0), Vec2::new(0.5, 1.0)],
vec![0, 1, 2, 3, 4, 5],
"Default",
)
.unwrap();
let mut s = Session::new_project("seam", mesh, "builtin:seam", None, 128).unwrap();
let bytes = s.mesh_glb_bytes_with_normals(true).unwrap();
let back = texturecraft_formats::import_mesh_bytes("seam.glb", &bytes).unwrap().mesh;
for point in [Vec3::ZERO, Vec3::Y] {
let normals: Vec<_> = back.positions.iter().zip(&back.normals).filter_map(|(position, normal)| (*position == point).then_some(*normal)).collect();
assert!(normals.len() >= 2, "{point:?}: the UV seam must still have two exported vertices");
assert!(normals.windows(2).all(|pair| (pair[0] - pair[1]).length() < 1e-5), "{point:?}: UV split normals disagree: {normals:?}");
}
}
#[test]
fn rejected_glb_export_preserves_existing_files_and_publishes_nothing() {
let mut s = Session::new_project("t", primitives::cube(1.0), "builtin:cube", None, 128).unwrap();
@@ -0,0 +1,29 @@
use crate::session::Session;
/// An archive that was written successfully. Only the same project can adopt its path.
pub struct SaveOutput {
pub path: String,
pub(super) project_id: u64,
pub(super) saved_revision: Option<u64>,
pub(super) adopt: bool,
}
impl SaveOutput {
/// Apply the saved path without clearing edits made since the snapshot.
pub fn apply(&self, session: &mut Session) {
if session.project_id != self.project_id {
return;
}
if self.adopt {
session.path = Some(self.path.clone());
// A stroke started after capture changes the revision only when committed
if self.saved_revision == Some(session.save_revision) {
session.modified = false;
}
}
session.log.info("Project", format!("Saved {}", self.path));
}
}
@@ -0,0 +1,6 @@
pub(super) struct SaveTarget {
pub(super) project_id: u64,
pub(super) saved_revision: Option<u64>,
pub(super) adopt: bool,
pub(super) path: String,
}
+53
View File
@@ -0,0 +1,53 @@
use std::path::Path;
use std::sync::Arc;
use texturecraft_core::PROJECT_EXT;
use texturecraft_formats::{ProjectFile, project_file::SaveProgress};
use texturecraft_geom::Mesh;
use super::{BakePaintMaps, SaveOutput, ext_of, fe, prepare_archive, save_target::SaveTarget};
use crate::Result;
use crate::session::Session;
/// A manual save of the document at the moment it was requested. Large payloads are shared
/// until the worker assembles the archive.
pub struct SaveTask {
target: SaveTarget,
archive: ProjectFile<Arc<Vec<u8>>, Arc<Vec<u8>>>,
bake_paint: BakePaintMaps,
uv_source: Option<Arc<Mesh>>,
}
impl Session {
pub fn save_task(&self, path: &str, adopt: bool) -> SaveTask {
let path = if ext_of(path) == PROJECT_EXT { path.to_string() } else { format!("{path}.{PROJECT_EXT}") };
let saved_revision = (!self.stroke_active()).then_some(self.save_revision);
SaveTask {
target: SaveTarget { project_id: self.project_id, saved_revision, adopt, path },
archive: self.capture_archive(self.doc.resources.clone(), Arc::clone),
bake_paint: self.doc.bake_paint.clone(),
uv_source: self.saved_uv_source().cloned(),
}
}
}
impl SaveTask {
/// Complete the atomic write on the worker. Waiting for a previous save to release the
/// RAM allowance also happens here.
pub fn run(mut self, progress: Option<&SaveProgress>) -> Result<SaveOutput> {
let mut reservation = texturecraft_formats::RamReservation::for_save().map_err(fe)?;
prepare_archive(&mut self.archive, self.uv_source.as_deref(), &self.bake_paint);
drop(self.uv_source);
drop(self.bake_paint);
let path = Path::new(&self.target.path);
match progress {
Some(progress) => reservation.save_with_progress(path, &self.archive, progress),
None => reservation.save(path, &self.archive),
}
.map_err(fe)?;
Ok(SaveOutput { path: self.target.path, project_id: self.target.project_id, saved_revision: self.target.saved_revision, adopt: self.target.adopt })
}
}
+4 -1
View File
@@ -2,7 +2,7 @@
//! without a screenshot.
use serde_json::{Value, json};
use texturecraft_core::{Effect, EffectKind, Fill, Filter, Generator, Layer, LayerKind, NormalFormat, Projection, Sampling, Source};
use texturecraft_core::{Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, Layer, LayerKind, NormalFormat, Projection, Sampling, Source};
use crate::Session;
use crate::session::StackTarget;
@@ -162,6 +162,9 @@ fn generator_json(generator: &Generator) -> Value {
if let Some(light) = &generator.light {
out["light"] = json!(light);
}
if generator.on_earlier_model() && matches!(generator.kind, GeneratorKind::Position | GeneratorKind::Direction) {
out["direction"] = json!(generator.direction);
}
if let Some(texture) = &generator.texture {
out["texture"] = json!(texture);
}
+11 -2
View File
@@ -324,8 +324,8 @@ fn select(s: &mut Session, p: &Value) -> Result<Value> {
}
Some(Value::String(t)) if t == "content" => StackTarget::Content,
Some(v) => match v.as_u64() {
Some(e) if s.doc.project.effect(LayerId(e)).is_some_and(|(owner, _)| owner == id) => StackTarget::Effect(LayerId(e)),
_ => return Err(bad("layer.select", "target must be content, mask or an effect id of this layer")),
Some(effect) if selectable_effect(&s.doc.project, id, LayerId(effect)) => StackTarget::Effect(LayerId(effect)),
_ => return Err(bad("layer.select", "target must be content, mask or an effect id of this layer or of the mask it draws with")),
},
None => StackTarget::Content,
};
@@ -334,6 +334,15 @@ fn select(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "layer": id.0, "textureSet": ts, "layers": [id.0] }))
}
/// Whether the effect belongs to the layer or to the mask it draws with.
fn selectable_effect(project: &Project, layer: LayerId, effect_id: LayerId) -> bool {
let Some((owner, _)) = project.effect(effect_id) else { return false };
owner == layer
|| (owner == project.mask_owner(layer)
&& project.layers.get(&owner).and_then(|layer| layer.mask.as_ref()).is_some_and(|mask| mask.effects.iter().any(|effect| effect.id == effect_id)))
}
fn rename(s: &mut Session, p: &Value) -> Result<Value> {
let id = layer_param(s, "layer.rename", p)?;
let name = strp(p, "name").map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad("layer.rename", "`name` is required"))?.to_string();
+9 -7
View File
@@ -33,7 +33,7 @@ pub fn specs() -> Vec<CommandSpec> {
has_layer,
add_color_mask
),
cmd!("mask.toggle", "Toggle mask", ["Layers", "Mask"], None, "{layer?, enabled?}", has_layer, toggle),
cmd!("mask.toggle", "Toggle mask", ["Layers", "Mask"], None, "{layer?, enabled?} — defaults to the selected layer", always, toggle),
cmd!("mask.invertBackground", "Invert mask background", ["Layers", "Mask"], None, "{layer?}", has_layer, invert_background),
cmd!("mask.invert", "Invert mask", ["Layers", "Mask"], None, "{layer?}", has_layer, invert),
cmd!("mask.clear", "Clear mask", ["Layers", "Mask"], None, "{layer?}", has_layer, clear),
@@ -132,6 +132,7 @@ pub fn specs() -> Vec<CommandSpec> {
fn with_mask<T>(s: &mut Session, p: &Value, cmd: &str, label: &str, f: impl FnOnce(&mut Session, LayerId) -> Result<T>) -> Result<T> {
let id = layer_param(s, cmd, p)?;
s.edit(label, |s| f(s, id))
}
@@ -174,13 +175,14 @@ fn mask_of(s: &mut Session, id: LayerId) -> Result<&mut Mask> {
l.mask.as_mut().ok_or_else(|| EngineError::Other(format!("\"{name}\" has no mask")))
}
fn toggle(s: &mut Session, p: &Value) -> Result<Value> {
let on = with_mask(s, p, "mask.toggle", "Toggle mask", |s, id| {
let m = mask_of(s, id)?;
m.enabled = boolp(p, "enabled").unwrap_or(!m.enabled);
Ok(m.enabled)
fn toggle(session: &mut Session, params: &Value) -> Result<Value> {
let enabled = with_mask(session, params, "mask.toggle", "Toggle mask", |session, layer| {
let mask = mask_of(session, layer)?;
mask.enabled = boolp(params, "enabled").unwrap_or(!mask.enabled);
Ok(mask.enabled)
})?;
Ok(json!({ "enabled": on }))
Ok(json!({ "enabled": enabled }))
}
fn invert_background(s: &mut Session, p: &Value) -> Result<Value> {
+2 -1
View File
@@ -99,11 +99,12 @@ impl Session {
images_used(&mini.project, root, &mut used, 0);
let resources = used.into_iter().filter_map(|name| self.doc.resources.get(&name).map(|bytes| (name, Arc::clone(bytes)))).collect();
let snapshot = texturecraft_formats::ProjectFile {
let snapshot = texturecraft_formats::ProjectFile::<Arc<Vec<u8>>> {
project: mini.project,
pixels: mini.pixels,
baked: BTreeMap::new(),
mesh: None,
mesh_uvs: None,
high_poly: Vec::new(),
cage: None,
bake_paint: BTreeMap::new(),
+1 -2
View File
@@ -591,8 +591,7 @@ impl Session {
self.undo.remove(0);
}
self.redo.clear();
self.modified = true;
self.revision = self.revision.wrapping_add(1);
self.mark_modified();
// Recompute committed tiles at low priority because the live preview already shows them
self.mark_settle(stroke.ts, stroke.target, stroke.canvas.dirty.iter().copied());
+10 -10
View File
@@ -925,28 +925,28 @@ impl Session {
}
/// [`Session::put_path`] recompositing only the tiles it changed, with no undo step: returns the paint report and the document before
fn repaint_path(&mut self, eid: LayerId, index: usize, shape: PathShape) -> Result<(Value, Document)> {
fn repaint_path(&mut self, effect_id: LayerId, index: usize, shape: PathShape) -> Result<(Value, Document)> {
let before = self.doc.clone();
let painted = match self.put_path(eid, index, shape) {
Ok(v) => v,
Err(e) => {
let painted = match self.put_path(effect_id, index, shape) {
Ok(report) => report,
Err(error) => {
self.doc = before;
return Err(e);
return Err(error);
}
};
// Paths paint into the active set; a sublayer in another set recomposites in full
let project = &self.doc.project;
let set = project.effect(eid).and_then(|(owner, _)| project.locate(owner)).map(|(ts, _, _)| ts);
let set = project.effect(effect_id).and_then(|(owner, _)| project.locate(owner)).map(|(ts, _, _)| ts);
if set == Some(self.ts()) {
// Content or mask, the sublayer's owner decides which sets redraw
let tiles = changed_tiles(&before.pixels, &self.doc.pixels, eid);
self.mark_painted(self.ts(), Some(PaintTarget::Layer(eid)), tiles);
let tiles = changed_tiles(&before.pixels, &self.doc.pixels, effect_id);
self.mark_painted(self.ts(), Some(PaintTarget::Layer(effect_id)), tiles);
} else {
self.invalidate_changed(&before);
}
self.revision = self.revision.wrapping_add(1);
self.modified = true;
self.mark_modified();
Ok((painted, before))
}
+21 -1
View File
@@ -2,6 +2,8 @@
//! dialog's Output templates tab list, read, save and remove. On the desktop the user presets
//! are mirrored as `<name>.json` files in a library folder (see [`Session::load_export_presets`]).
use std::collections::HashSet;
use serde_json::{Value, json};
use texturecraft_formats::export::{MAX_PRESET_NAME, sanitize_file_stem};
use texturecraft_formats::{ExportPreset, builtin_preset, builtin_presets, preset_from_json};
@@ -67,13 +69,16 @@ impl UserPresets {
/// The first available name, adding a numbered suffix and shortening the base to fit.
fn unique_name(&self, name: &str, skip: Option<usize>) -> Option<String> {
// File keys also cover case-insensitive name matches
let file_keys: HashSet<_> = self.list.iter().enumerate().filter(|(index, _)| Some(*index) != skip).map(|(_, preset)| file_key(&preset.name)).collect();
(1..=MAX_USER_PRESETS + 1)
.map(|number| {
let suffix = if number == 1 { String::new() } else { format!(" {number}") };
let base: String = name.chars().take(MAX_PRESET_NAME.saturating_sub(suffix.len())).collect();
format!("{}{suffix}", base.trim_end())
})
.find(|candidate| !self.taken(candidate, skip))
.find(|candidate| !file_keys.contains(&file_key(candidate)) && builtin_preset(candidate).is_none())
}
#[cfg(not(target_arch = "wasm32"))]
@@ -295,6 +300,21 @@ mod tests {
assert_eq!(run(&mut session, "export.preset.get", json!({"name": "Mine"})).unwrap(), replacement);
}
#[test]
fn unique_saves_skip_presets_with_colliding_file_stems() {
let mut session = Session::closed().unwrap();
for name in ["My Preset", "My_Preset_2"] {
run(&mut session, "export.preset.save", json!({"preset": preset(name)})).unwrap();
}
let saved = run(&mut session, "export.preset.save", json!({"preset": preset("My Preset"), "unique": true})).unwrap();
assert_eq!(saved["name"], "My Preset 3");
for name in ["My Preset", "My_Preset_2", "My Preset 3"] {
assert_eq!(session.export_preset(name).unwrap().name, name);
}
}
#[test]
fn unique_save_at_capacity_requires_an_explicit_rename() {
let mut session = Session::closed().unwrap();
+25 -10
View File
@@ -427,7 +427,7 @@ pub struct Session {
pub(crate) source: Arc<Mesh>,
pub bvh: Arc<Bvh>,
/// Original mesh file (saved inside the project); None for built-in meshes.
pub mesh_source: Option<(String, Vec<u8>)>,
pub mesh_source: Option<(String, Arc<Vec<u8>>)>,
pub caches: Vec<SetCache>,
pub(crate) undo: Vec<(String, Document)>,
pub(crate) redo: Vec<(String, Document)>,
@@ -478,6 +478,9 @@ pub struct Session {
/// (see [`crate::commands::check_enabled`]).
pub project_open: bool,
pub modified: bool,
/// Edits to saved data, independent of viewport and tool changes.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) save_revision: u64,
/// Bumps on every document change.
pub revision: u64,
/// Messages for the UI (status bar / toasts).
@@ -524,7 +527,7 @@ impl Session {
source,
mesh,
bvh: Arc::new(bvh),
mesh_source,
mesh_source: mesh_source.map(|(extension, bytes)| (extension, Arc::new(bytes))),
caches,
undo: Vec::new(),
redo: Vec::new(),
@@ -554,6 +557,8 @@ impl Session {
path: None,
project_open: true,
modified: false,
#[cfg(not(target_arch = "wasm32"))]
save_revision: 0,
revision: 1,
log: crate::log::SessionLog::new(),
log_id: next_mesh_id(),
@@ -583,6 +588,10 @@ impl Session {
pub fn switch_to(&mut self, mut next: Session) {
// Invalidate caches even when both projects were loaded with the same revision
next.revision = self.revision.wrapping_add(1);
#[cfg(not(target_arch = "wasm32"))]
{
next.save_revision = self.save_revision.wrapping_add(1);
}
next.viewport = self.viewport;
next.export_presets = std::mem::take(&mut self.export_presets);
@@ -735,8 +744,7 @@ impl Session {
self.path_steps = Default::default();
}
self.modified = true;
self.revision = self.revision.wrapping_add(1);
self.mark_modified();
if !(merge && self.undo.last().is_some_and(|(l, _)| l == label)) {
self.undo.push((label.to_string(), before));
}
@@ -747,8 +755,7 @@ impl Session {
/// A change from `other` to the current document that is not an undo step (a path preview)
pub(crate) fn changed_without_history(&mut self, other: &Document) {
self.modified = true;
self.revision = self.revision.wrapping_add(1);
self.mark_modified();
self.invalidate_changed(other);
}
@@ -874,14 +881,23 @@ impl Session {
/// Mark the document changed and every texture set dirty.
pub fn touched(&mut self) {
self.modified = true;
self.revision = self.revision.wrapping_add(1);
self.mark_modified();
self.sync_caches();
for c in &mut self.caches {
c.invalidate_all();
}
}
/// Mark saved data changed without invalidating the texture sets.
pub fn mark_modified(&mut self) {
self.modified = true;
self.revision = self.revision.wrapping_add(1);
#[cfg(not(target_arch = "wasm32"))]
{
self.save_revision = self.save_revision.wrapping_add(1);
}
}
/// Make caches agree with the project's texture sets (resolution or channel changes).
pub fn sync_caches(&mut self) {
let sets = self.doc.project.texture_sets.clone();
@@ -992,11 +1008,10 @@ impl Session {
fn after_history(&mut self, other: &Document) {
// Pending operations may still hold layer IDs from the discarded snapshot
self.doc.project.next_id = self.doc.project.next_id.max(other.project.next_id);
self.modified = true;
self.mark_modified();
// Layers picked together belong to the stack they were picked in
self.multi.clear();
self.revision = self.revision.wrapping_add(1);
self.invalidate_changed(other);
// An undone add or duplicate takes the selected effect away
+72 -27
View File
@@ -3,9 +3,8 @@
use serde_json::{Value, json};
use texturecraft_core::project::ENVIRONMENTS;
use texturecraft_core::{BakedMap, Channel, EffectKind, EnvAlignment, Filter, Project, ShadowMode, ToneMapping};
use texturecraft_geom::glam::Vec3;
use crate::commands::{CommandSpec, always, bad, boolp, can_redo, can_undo, color_param, f32p, strp, u64p};
use crate::commands::{CommandSpec, always, bad, boolp, can_redo, can_undo, color_param, f32p, strp, u64p, vec3};
use crate::frame_target::FrameTarget;
use crate::session::ViewMode;
use crate::{Result, Session, cmd};
@@ -52,7 +51,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Set camera",
[],
None,
"{yaw?, pitch? (degrees), distance?, fov?, target?: [x,y,z], ortho?, rotation?: constrained|free (a free camera also rolls and turns over)}",
"{yaw?, pitch? (degrees), distance?, fov?, target?: [x,y,z] (three finite numbers, null keeps the current target), ortho?, rotation?: constrained|free (a free camera also rolls and turns over)}",
always,
camera_set
),
@@ -233,37 +232,49 @@ pub(crate) fn camera_json(s: &Session) -> Value {
})
}
fn camera_set(s: &mut Session, p: &Value) -> Result<Value> {
let c = &mut s.camera;
match strp(p, "rotation") {
Some("free") => c.set_free(true),
Some("constrained") => c.set_free(false),
Some(o) => return Err(bad("camera.set", format!("unknown rotation `{o}`: constrained or free"))),
fn camera_set(session: &mut Session, params: &Value) -> Result<Value> {
const MAX_PITCH_DEGREES: f32 = 89.0;
const MIN_DISTANCE_RADII: f32 = 0.05;
const MAX_DISTANCE_RADII: f32 = 200.0;
const MIN_FOV_DEGREES: f32 = 5.0;
const MAX_FOV_DEGREES: f32 = 150.0;
let target = vec3(params, "target");
if target.is_none() && params.get("target").is_some_and(|value| !value.is_null()) {
return Err(bad("camera.set", "`target` must be an array of three finite numbers"));
}
let camera = &mut session.camera;
match strp(params, "rotation") {
Some("free") => camera.set_free(true),
Some("constrained") => camera.set_free(false),
Some(other) => return Err(bad("camera.set", format!("unknown rotation `{other}`: constrained or free"))),
None => {}
}
if f32p(p, "yaw").is_some() || f32p(p, "pitch").is_some() {
// A free camera is put level at the angles
let yaw = f32p(p, "yaw").map_or(c.yaw, f32::to_radians);
let pitch = f32p(p, "pitch").map_or(c.pitch, |v| v.clamp(-89.0, 89.0).to_radians());
c.set_angles(yaw, pitch);
let yaw_degrees = f32p(params, "yaw");
let pitch_degrees = f32p(params, "pitch");
if yaw_degrees.is_some() || pitch_degrees.is_some() {
// Setting either angle levels a free camera
let yaw = yaw_degrees.map_or(camera.yaw, f32::to_radians);
let pitch = pitch_degrees.map_or(camera.pitch, |degrees| degrees.clamp(-MAX_PITCH_DEGREES, MAX_PITCH_DEGREES).to_radians());
camera.set_angles(yaw, pitch);
}
if let Some(v) = f32p(p, "distance") {
c.distance = v.clamp(c.scene_radius * 0.05, c.scene_radius * 200.0);
if let Some(distance) = f32p(params, "distance") {
camera.distance = distance.clamp(camera.scene_radius * MIN_DISTANCE_RADII, camera.scene_radius * MAX_DISTANCE_RADII);
}
if let Some(v) = f32p(p, "fov") {
c.fov = v.clamp(5.0, 150.0);
if let Some(fov_degrees) = f32p(params, "fov") {
camera.fov = fov_degrees.clamp(MIN_FOV_DEGREES, MAX_FOV_DEGREES);
}
if let Some(t) = p.get("target").and_then(Value::as_array) {
let v: Vec<f32> = t.iter().filter_map(Value::as_f64).map(|x| x as f32).collect();
if v.len() == 3 && v.iter().all(|x| x.is_finite()) {
c.target = Vec3::new(v[0], v[1], v[2]);
}
if let Some(target) = target {
camera.target = target;
}
if let Some(o) = boolp(p, "ortho") {
c.ortho = o;
if let Some(ortho) = boolp(params, "ortho") {
camera.ortho = ortho;
}
s.revision = s.revision.wrapping_add(1);
Ok(camera_json(s))
session.revision = session.revision.wrapping_add(1);
Ok(camera_json(session))
}
fn orbit(s: &mut Session, p: &Value) -> Result<Value> {
@@ -399,6 +410,40 @@ mod tests {
Session::new_project("t", texturecraft_geom::primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 128).unwrap()
}
#[test]
fn camera_set_rejects_an_invalid_target_without_changing_the_camera() {
let mut session = sphere_session();
execute(&mut session, "camera.set", &json!({"target": [1.0, 2.0, 3.0], "fov": 40.0})).unwrap();
let before = session.camera;
let revision = session.revision;
for target in [json!([10, "typo", 20, 30]), json!([1, 2]), json!([1, "typo", 3]), json!([1, 2, 1e300]), json!({"x": 1})] {
let params = json!({"target": target, "yaw": 35.0, "fov": 90.0, "rotation": "free"});
let result = execute(&mut session, "camera.set", &params);
assert!(matches!(result, Err(crate::EngineError::BadParams { cmd, .. }) if cmd == "camera.set"), "{params}");
assert_eq!(session.camera, before);
assert_eq!(session.revision, revision);
}
}
#[test]
fn camera_set_keeps_the_target_when_it_is_omitted_or_null() {
let mut session = sphere_session();
let target = json!([1.0, 2.0, 3.0]);
let initial = execute(&mut session, "camera.set", &json!({"target": target, "fov": 40.0})).unwrap();
let omitted = execute(&mut session, "camera.set", &json!({"fov": 60.0})).unwrap();
let explicit_null = execute(&mut session, "camera.set", &json!({"target": null, "fov": 80.0})).unwrap();
assert_eq!(initial["target"], target);
assert_eq!(omitted["target"], target);
assert_eq!(explicit_null["target"], target);
assert_ne!(omitted["fov"], initial["fov"]);
assert_ne!(explicit_null["fov"], omitted["fov"]);
}
fn pressed(s: &mut Session, command: &str) -> ViewMode {
execute(s, command, &json!({})).unwrap();
s.view
+28 -15
View File
@@ -1,7 +1,7 @@
//! Warp projections: the frame a new warp starts from, and Reset frame, which puts a warp's frame and corners back there
use serde_json::Value;
use texturecraft_core::{Decal, Projection};
use texturecraft_core::{Decal, Projection, Projector};
use texturecraft_geom::Mesh;
use crate::commands::{CommandSpec, bad, has_layer};
@@ -17,7 +17,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Reset frame",
[],
None,
"{layer? | effect?: content or mask fill effect id} — a warp projection's frame back around the mesh, seen from the front, with its corners unpulled (Projection Depth and the other settings stay)",
"{layer? | effect?: content or mask fill effect id, keepCorners?: bool} — refit the warp's frame around the mesh. With `keepCorners: true`, also reset the projector's rotation and scale and keep the corners; otherwise reset the corners. Projection Depth, crop, and culling stay",
has_layer,
reset_frame
)]
@@ -44,26 +44,39 @@ pub(crate) fn fitted_frame(mesh: &Mesh) -> Decal {
/// A fitted frame's smallest side, relative to the mesh diagonal (a flat mesh still gets a frame)
const SMALLEST_SIDE: f32 = 1e-3;
fn reset_frame(s: &mut Session, p: &Value) -> Result<Value> {
let target = fill_target(s, p, RESET_FRAME)?;
let fitted = fitted_frame(&s.mesh);
let (Projection::Warp { frame, corners, .. }, _) = placement_mut(s, target)? else {
fn reset_frame(session: &mut Session, params: &Value) -> Result<Value> {
let target = fill_target(session, params, RESET_FRAME)?;
let keep_corners = match params.get("keepCorners") {
Some(value) => value.as_bool().ok_or_else(|| bad(RESET_FRAME, "`keepCorners` must be a boolean"))?,
None => false,
};
let fitted = fitted_frame(&session.mesh);
let (projection, _) = placement_mut(session, target)?;
let mut reset = projection.clone();
let Projection::Warp { frame, corners, projector, .. } = &mut reset else {
return Err(bad(RESET_FRAME, "the fill's projection is not a warp projection"));
};
// A frame already fitted with unpulled corners adds no undo step
if *frame == fitted && *corners == Projection::FRAME_CORNERS {
*frame = fitted;
if keep_corners {
// Older warps may still carry a transform separate from the frame
let defaults = Projector::default();
projector.rotation = defaults.rotation;
projector.scale = defaults.scale;
} else {
*corners = Projection::FRAME_CORNERS;
}
// An unchanged projection adds no undo step
if reset == *projection {
return Ok(Value::Null);
}
s.edit("Reset frame", |s| {
let (Projection::Warp { frame, corners, .. }, _) = placement_mut(s, target)? else {
return Err(bad(RESET_FRAME, "the fill's projection is not a warp projection"));
};
*frame = fitted;
*corners = Projection::FRAME_CORNERS;
let label = if keep_corners { "Reset warp transform" } else { "Reset frame" };
session.edit(label, |session| {
*placement_mut(session, target)?.0 = reset;
Ok(())
})?;
Ok(Value::Null)
}
+36
View File
@@ -246,6 +246,42 @@ fn anchor_effects_added_through_instance_validate_against_source() {
assert!(session.doc.project.layer(LayerId(source)).unwrap().mask.is_none());
}
#[test]
fn an_instance_selects_the_effects_of_the_mask_it_draws_with() {
let mut s = session();
let source = id(execute(&mut s, "layer.add.fill", &json!({"height": 0.5})).unwrap(), "layer");
execute(&mut s, "mask.add.black", &Value::Null).unwrap();
let source_mask = id(execute(&mut s, "effect.add.generator", &json!({"generator": "position", "level": 0.5})).unwrap(), "effect");
let source_content = id(execute(&mut s, "effect.add.filter", &json!({"target": "content", "filter": "invert"})).unwrap(), "effect");
let other = id(execute(&mut s, "layer.add.fill", &Value::Null).unwrap(), "layer");
execute(&mut s, "mask.add.black", &Value::Null).unwrap();
let other_mask = id(execute(&mut s, "effect.add.generator", &json!({"generator": "position", "level": 0.5})).unwrap(), "effect");
let instance = id(execute(&mut s, "layer.instance", &json!({"layer": source})).unwrap(), "layer");
let select = |s: &mut Session, effect: u64| execute(s, "layer.select", &json!({"layer": instance, "target": effect}));
// The instance inherits its source mask
select(&mut s, source_mask).unwrap();
assert_eq!(s.selected_layer(), Some(LayerId(instance)));
assert_eq!(s.target, StackTarget::Effect(LayerId(source_mask)));
// The source's content and unrelated layers remain outside the selection
for effect in [source_content, other_mask] {
let error = select(&mut s, effect).unwrap_err().to_string();
assert!(error.contains("an effect id of this layer or of the mask it draws with"), "{error}");
}
assert_ne!(other, instance);
// A local mask overrides the source mask
execute(&mut s, "layer.select", &json!({"layer": instance})).unwrap();
execute(&mut s, "mask.add.black", &Value::Null).unwrap();
let own = id(execute(&mut s, "effect.add.generator", &json!({"generator": "position", "level": 0.5})).unwrap(), "effect");
assert!(select(&mut s, source_mask).is_err());
select(&mut s, own).unwrap();
assert_eq!(s.target, StackTarget::Effect(LayerId(own)));
}
#[test]
fn mask_anchor_points_feed_layers_above_and_folders_take_them() {
let mut s = session();
@@ -337,6 +337,67 @@ fn warp_projection_bends_to_its_corners_reaches_its_depth_and_resets_its_frame()
assert!(execute(&mut s, "layer.fill.resetFrame", &json!({"layer": layer.0})).is_err(), "only a warp has a frame to reset");
}
/// Restore the global transformation refits a warp's frame and keeps its pulled corners, in one undo step, none when the frame is fitted
#[test]
fn a_warps_frame_resets_apart_from_its_corners() {
let mut s = session();
let layer = checker_fill(&mut s);
set(&mut s, layer, json!({"projection": "warp"}));
let Projection::Warp { frame: fitted, .. } = projection(&s, layer) else { panic!("a warp") };
let pulled = [[-0.5, 0.5], [0.9, 0.9], [0.5, -0.5], [-0.5, -0.5]];
set(&mut s, layer, json!({"warpCorners": pulled}));
execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "rotation": 30})).unwrap();
let steps = s.history_labels().len();
execute(&mut s, "layer.fill.resetFrame", &json!({"layer": layer.0, "keepCorners": true})).unwrap();
let Projection::Warp { frame, corners, .. } = projection(&s, layer) else { panic!("a warp") };
assert_eq!(frame, fitted, "the frame goes back around the mesh");
assert_eq!(corners, pulled, "the pulled corners stay");
assert_eq!(s.history_labels().len(), steps + 1);
execute(&mut s, "layer.fill.resetFrame", &json!({"layer": layer.0, "keepCorners": true})).unwrap();
assert_eq!(s.history_labels().len(), steps + 1, "a fitted frame adds no undo step");
}
#[test]
fn a_warps_global_reset_clears_the_projector_transform() {
let mut session = session();
let layer = checker_fill(&mut session);
let pulled = [[-0.5, 0.5], [0.9, 0.9], [0.5, -0.5], [-0.5, -0.5]];
set(&mut session, layer, json!({"projection": "warp", "warpCorners": pulled, "depthCulling": false, "projectionDepth": 0.2}));
let fitted = projection(&session, layer);
set(&mut session, layer, json!({"projectorRotation": [12, 0, 20], "projectorScale": [2, 2, 1]}));
let edited = projection(&session, layer);
let steps = session.history_labels().len();
execute(&mut session, "layer.fill.resetFrame", &json!({"layer": layer.0, "keepCorners": true})).unwrap();
assert_eq!(projection(&session, layer), fitted, "restore the displayed frame and keep its corners and projection settings");
assert_eq!(session.history_labels().len(), steps + 1);
session.undo().unwrap();
assert_eq!(projection(&session, layer), edited);
}
#[test]
fn invalid_keep_corners_cannot_reset_the_warp() {
let mut session = session();
let layer = checker_fill(&mut session);
let pulled = [[-0.5, 0.5], [0.9, 0.9], [0.5, -0.5], [-0.5, -0.5]];
set(&mut session, layer, json!({"projection": "warp", "warpCorners": pulled}));
let before = projection(&session, layer);
let steps = session.history_labels().len();
let result = execute(&mut session, "layer.fill.resetFrame", &json!({"layer": layer.0, "keepCorners": "true"}));
assert!(result.is_err());
assert_eq!(projection(&session, layer), before);
assert_eq!(session.history_labels().len(), steps);
}
/// Depth culling keeps planar and warp projections off surfaces hidden behind others from the projector; new ones start with it on, older saves without it
#[test]
fn depth_culling_keeps_planar_and_warp_projections_off_hidden_surfaces() {
@@ -167,3 +167,26 @@ fn inspect_reports_the_reference_controls_set() {
assert!(inspected.contains(&format!("\"{key}\"")) && inspected.contains(value), "{key} with {value} in {inspected}");
}
}
#[test]
fn inspect_reports_direction_only_on_the_earlier_model() {
let mut session = session();
let earlier_dir = add(&mut session, json!({"generator": "direction", "direction": [1.0, 0.0, 0.0]}));
let light_dir = add(&mut session, json!({"generator": "direction", "lightHorizontal": 90.0}));
let earlier_pos = add(&mut session, json!({"generator": "position", "direction": [0.0, 0.0, 1.0]}));
let section_pos = add(&mut session, json!({"generator": "position", "sectionContrast": 0.25}));
let inspected = execute(&mut session, "project.inspect", &Value::Null).unwrap();
let effects = inspected["layers"][0]["mask"]["effects"].as_array().unwrap();
let gen_of = |effect_id: u64| &effects.iter().find(|entry| entry["id"] == effect_id).unwrap()["generator"];
assert_eq!(gen_of(earlier_dir)["direction"], json!([1.0, 0.0, 0.0]));
assert!(gen_of(earlier_dir).get("light").is_none());
assert!(gen_of(light_dir).get("direction").is_none());
assert!(gen_of(light_dir).get("light").is_some());
assert_eq!(gen_of(earlier_pos)["direction"], json!([0.0, 0.0, 1.0]));
assert!(gen_of(earlier_pos).get("section").is_none());
assert!(gen_of(section_pos).get("direction").is_none());
assert!(gen_of(section_pos).get("section").is_some());
}
+1
View File
@@ -62,6 +62,7 @@ mod pbr_import;
mod perf;
mod polygon_fill;
mod project_recovery;
mod rebuilt_uv_layout;
mod resources_used;
mod sample;
mod solo;
@@ -0,0 +1,93 @@
use std::io::{Cursor, Write};
use serde_json::json;
use texturecraft_engine::Session;
use texturecraft_engine::formats::mesh_import::{corner_uvs, import_mesh_bytes_with_uvs};
use texturecraft_engine::geom::glam::Vec2;
use zip::{ZipWriter, write::SimpleFileOptions};
const QUAD_OBJ: &str = "v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 1 1\nvt 0 1\nf 1/1 2/2 3/3\nf 1/1 3/3 4/4\n";
/// A layout no unwrapper of this build makes: the quad turned a quarter and inset, per corner
const LOCKED_LAYOUT: [[f32; 2]; 6] = [[0.9, 0.1], [0.9, 0.9], [0.1, 0.9], [0.9, 0.1], [0.1, 0.9], [0.1, 0.1]];
/// `uv_layout.bin` written by hand: magic, version 1, corner count, then u and v per corner
fn layout_entry(layout: &[[f32; 2]]) -> Vec<u8> {
let mut bytes = b"TCUV".to_vec();
bytes.extend(1u32.to_le_bytes());
bytes.extend(u32::try_from(layout.len()).unwrap().to_le_bytes());
for [u, v] in layout {
bytes.extend(u.to_le_bytes());
bytes.extend(v.to_le_bytes());
}
bytes
}
/// A format 4 archive of the quad with rebuilt UVs and the locked layout
fn locked_archive() -> Vec<u8> {
let session = Session::from_mesh_bytes_with_uvs("quad.obj", QUAD_OBJ.as_bytes(), 128, "quad", None, true).unwrap();
let mut project = serde_json::to_value(&session.doc.project).unwrap();
project["format_version"] = json!(4);
let mut archive = ZipWriter::new(Cursor::new(Vec::new()));
for (name, bytes) in
[("project.json", serde_json::to_vec(&project).unwrap()), ("mesh.obj", QUAD_OBJ.as_bytes().to_vec()), ("uv_layout.bin", layout_entry(&LOCKED_LAYOUT))]
{
archive.start_file(name, SimpleFileOptions::default()).unwrap();
archive.write_all(&bytes).unwrap();
}
archive.finish().unwrap().into_inner()
}
#[test]
fn a_rebuilt_project_reopens_with_its_saved_uv_layout_not_a_new_unwrap() {
let locked: Vec<Vec2> = LOCKED_LAYOUT.iter().map(|uv| Vec2::from_array(*uv)).collect();
let unwrapped = import_mesh_bytes_with_uvs("quad.obj", QUAD_OBJ.as_bytes(), true).unwrap().mesh;
let mut reopened = Session::from_project_bytes(&locked_archive()).unwrap();
let opened_layout = corner_uvs(&reopened.source_mesh());
reopened.reimport_mesh(None, false).unwrap();
let reimported_layout = corner_uvs(&reopened.source_mesh());
let resaved = Session::from_project_bytes(&reopened.to_project_bytes().unwrap()).unwrap();
assert_ne!(corner_uvs(&unwrapped), locked, "the locked layout differs from what the unwrapper makes now");
assert_eq!(opened_layout, locked);
assert_eq!(reimported_layout, locked, "reimporting the project's own mesh keeps the saved layout");
assert_eq!(corner_uvs(&resaved.source_mesh()), locked, "saving again keeps the layout");
}
#[test]
fn a_pending_save_keeps_the_rebuilt_layout_and_releases_unused_bake_geometry() {
let mut session = Session::from_project_bytes(&locked_archive()).unwrap();
session.add_high_poly_bytes("high.obj", QUAD_OBJ.as_bytes().to_vec()).unwrap();
let expected_layout = corner_uvs(&session.source_mesh());
let high = &session.doc.bake_meshes.high[0];
let encoded = std::sync::Arc::downgrade(&high.bytes);
let parsed = std::sync::Arc::downgrade(&high.mesh);
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("saved.tcraft");
let save = session.save_task(path.to_str().unwrap(), true);
drop(session);
assert!(parsed.upgrade().is_none(), "only the source UV layout needs parsed geometry");
assert!(encoded.upgrade().is_some(), "the pending archive shares the original file bytes");
save.run(None).unwrap();
let reopened = texturecraft_engine::file_cmds::open_path(path.to_str().unwrap()).unwrap();
assert!(encoded.upgrade().is_none(), "the worker released the original bytes");
assert_eq!(reopened.doc.bake_meshes.high[0].bytes.as_slice(), QUAD_OBJ.as_bytes());
assert!(reopened.doc.project.mesh_rebuild_uvs);
assert_eq!(corner_uvs(&reopened.source_mesh()), expected_layout);
}
#[test]
fn opening_a_builtin_project_refuses_rebuilt_mesh_uvs() {
let mut file = texturecraft_engine::formats::load_project_bytes(&locked_archive()).unwrap();
file.project.mesh = "builtin:plane".into();
file.mesh = None;
let error = Session::from_project_file(file).map(|_| ()).expect_err("a built-in mesh cannot use the stored layout");
assert!(error.to_string().contains("uv_layout.bin"), "{error}");
}
+2 -3
View File
@@ -11,13 +11,12 @@ workspace = true
[dependencies]
craft-usd.workspace = true
# ICC v2 serialization prerequisite: craft-libs#1735; app colour policy stays local.
craft-cms-icc-v2 = { package = "craft-cms", version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "272a095b61257917693da3d09f2f8ecccd7f0295" }
craft-cms-icc-v2 = { package = "craft-cms", version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-materialx = { workspace = true }
craft-mesh = { workspace = true }
craft-mcmat = { workspace = true }
craft-tcraft = { workspace = true }
craft-zip = { workspace = true }
craft-zip-usdz = { workspace = true }
texturecraft-core = { workspace = true }
texturecraft-texel = { workspace = true }
texturecraft-geom = { workspace = true }
@@ -26,7 +25,7 @@ image = { workspace = true }
png = "0.18"
bytemuck = { workspace = true, features = ["extern_crate_alloc"] }
craft-image-codecs = { workspace = true }
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "b130ac1fa44f923c3024884ab8ceb5ccdb88f15f" }
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
flate2 = { workspace = true }
half = { workspace = true }
quick-xml = { workspace = true }
+9 -2
View File
@@ -145,7 +145,8 @@ Built-in presets (each one lists the public specification its packing follows in
```rust
pub struct ProjectFile {
pub project: Project, pub pixels: PixelStore, pub baked: BTreeMap<usize, BakedMaps>,
pub mesh: Option<(String /* ext */, Vec<u8>)>, pub thumbnail: Option<Vec<u8>>,
pub mesh: Option<(String /* ext */, Vec<u8>)>, pub mesh_uvs: Option<Vec<Vec2>>,
pub thumbnail: Option<Vec<u8>>,
pub warnings: Vec<String>, // Import warnings, never saved
}
pub fn save_project_bytes(pf: &ProjectFile) -> Result<Vec<u8>>;
@@ -162,12 +163,14 @@ pub fn project_open_limit_gib() -> u32;
|---|---|
| `project.json` | serde JSON of `Project` |
| `mesh.<ext>` | the original mesh file bytes (absent for `builtin:<id>` meshes) |
| `uv_layout.bin` | generated UVs for an explicitly rebuilt mesh (format 4) |
| `pixels/layer_<id>_<channelId>.bin` | painted layer (or content paint effect) channel |
| `pixels/mask_<id>.bin` | painted mask effect |
| `baked/<ts>_<mapId>.bin` | baked mesh map of texture set `<ts>` |
| `thumbnail.png` | optional, stored |
`.bin`: header `TCTX`, version, width, height, components, tile count (u32 LE each), then per
Paint and bake `.bin` entries use a `TCTX` header with version, width, height, components and tile
count (u32 LE each), then per
allocated 64×64 tile `tx`, `ty` (u32 LE) and the raw `u16` LE components (sparse, lossless).
Baked maps: the same header with 0 tiles, then `width × height × components` f32 LE.
@@ -180,6 +183,10 @@ Project format version 3 stores baked bent normal maps in tangent space (OpenGL
normal map). Version 2 and older files held them in world space: loading drops those maps, keeps
the bake settings and warns that the Bent Normals map needs a re-bake.
Project format version 4 saves rebuilt mesh UVs so reopening can use the same layout. The
`uv_layout.bin` entry starts with `TCUV`, followed by the layout version and corner count (u32 LE).
Each triangle corner has one little-endian f32 pair in imported index order.
Loading runs `Project::validate`, refuses a newer `format_version` (`FormatError::NewerVersion`),
checks every tile against its texture set's resolution and component count, rejects repeated or
out-of-range tiles and trailing data, and drops pixels of layers that are in no stack. Total
+1 -1
View File
@@ -287,7 +287,7 @@ pub(crate) fn material_maps(mesh: &Mesh, stem: &str, textures: &[Vec<ExportedFil
/// A usdz package: the layer first, every entry stored uncompressed at a 64-byte aligned offset.
pub(crate) fn usdz(layer_name: &str, layer: &[u8], files: &[(String, Vec<u8>)]) -> Result<Vec<u8>> {
let mut zip = craft_zip_usdz::Writer::new();
let mut zip = craft_zip::Writer::new();
let err = |e| FormatError::Invalid(format!("usdz package: {e}"));
for (name, bytes) in std::iter::once((layer_name, layer)).chain(files.iter().map(|(n, b)| (n.as_str(), b.as_slice()))) {
zip.add_stored_aligned(name, bytes, 64).map_err(err)?;
+26 -17
View File
@@ -198,29 +198,36 @@ fn sample_file(with_tri: bool) -> Vec<u8> {
#[test]
fn imports_polymesh_through_xforms_with_face_sets_uvs_and_normals() {
let raw = read(&sample_file(true)).unwrap();
let mut names: Vec<(&str, &str)> = raw.groups.iter().map(|(m, p, _)| (m.as_str(), p.as_str())).collect();
let mut names: Vec<(&str, &str)> = raw.groups.iter().map(|(material, part, _)| (material.as_str(), part.as_str())).collect();
names.sort();
assert_eq!(names, vec![("Default", "tri"), ("left", "strip"), ("right", "strip")], "meshes take their transform's name");
assert_eq!(raw.triangle_count(), 5);
// UVs exist only on the strip, so the whole mesh is unwrapped (with a warning).
// UVs exist only on the strip, so the whole mesh is unwrapped with a warning
assert!(raw.uvs.is_none() && !raw.warnings.is_empty());
// World positions: scaled by 2, then translated.
// World positions are scaled first and then translated
let (lo, hi) = raw.positions.iter().fold((Vec3::splat(f32::MAX), Vec3::splat(f32::MIN)), |(lo, hi), p| (lo.min(*p), hi.max(*p)));
assert_eq!((lo, hi), (Vec3::new(0.0, 0.0, 3.0), Vec3::new(5.0, 4.0, 5.0)));
// Clockwise Alembic faces become counter-clockwise: the strip faces +Z.
for (m, _, tris) in &raw.groups {
if m == "Default" {
// Clockwise Alembic faces are reversed so the strip faces +Z
for (material, _, triangles) in &raw.groups {
if material == "Default" {
continue;
}
for t in tris.chunks(3) {
for t in triangles.chunks(3) {
let p = |i: u32| raw.positions[i as usize];
assert!((p(t[1]) - p(t[0])).cross(p(t[2]) - p(t[0])).z > 0.0);
}
}
let mesh = finish(raw).unwrap().mesh;
let mesh = finish(raw, false).unwrap().mesh;
assert_eq!(mesh.materials.len(), 3);
// The strip alone keeps its indexed face-varying UVs: u = x / 2 in the file's own space.
let strip = finish(read(&sample_file(false)).unwrap()).unwrap();
// The strip alone keeps its indexed face-varying UVs with u = x / 2 in local space
let strip = finish(read(&sample_file(false)).unwrap(), false).unwrap();
assert!(!strip.report.uvs_generated);
for (p, uv) in strip.mesh.positions.iter().zip(&strip.mesh.uvs) {
let local = (*p - Vec3::new(1.0, 2.0, 3.0)) / 2.0;
@@ -318,21 +325,23 @@ fn hdf5_and_garbage_are_clear_errors() {
#[test]
fn truncated_and_corrupted_files_never_panic() {
let bytes = sample_file(true);
for n in (0..bytes.len()).step_by(3) {
let _ = read(&bytes[..n]);
for end in (0..bytes.len()).step_by(3) {
let _ = read(&bytes[..end]);
}
let mut rng = 0x9e37_79b9_7f4a_7c15u64;
for _ in 0..4000 {
let mut b = bytes.clone();
let mut corrupted = bytes.clone();
for _ in 0..4 {
rng ^= rng << 13;
rng ^= rng >> 7;
rng ^= rng << 17;
let i = (rng % b.len() as u64) as usize;
b[i] = (rng >> 32) as u8;
let i = (rng % corrupted.len() as u64) as usize;
corrupted[i] = (rng >> 32) as u8;
}
if let Ok(raw) = read(&b) {
let _ = finish(raw);
if let Ok(raw) = read(&corrupted) {
let _ = finish(raw, false);
}
}
}
@@ -0,0 +1,17 @@
use texturecraft_geom::glam::Vec2;
/// How to obtain triangle UVs when reading mesh geometry.
pub enum MeshUvSource<'a> {
/// Keep complete authored UVs, or unwrap a mesh that needs them.
FromFile,
/// Generate a fresh layout even when the file contains UVs.
Rebuild,
/// Apply the project's saved UVs in triangle corner order.
Saved(&'a [Vec2]),
}
impl MeshUvSource<'_> {
pub fn from_rebuild_setting(rebuild_uvs: bool) -> Self {
if rebuild_uvs { Self::Rebuild } else { Self::FromFile }
}
}
+106 -29
View File
@@ -11,6 +11,7 @@ mod dae;
mod external;
mod fbx;
mod gltf;
mod mesh_uv_source;
mod obj;
mod ply;
#[cfg(test)]
@@ -24,7 +25,7 @@ use std::collections::hash_map::Entry;
use std::collections::{HashMap, HashSet};
use texturecraft_geom::glam::{Mat4, Vec2, Vec3, Vec4};
use texturecraft_geom::unwrap::{all_triangles_degenerate, auto_unwrap, weld_ids};
use texturecraft_geom::unwrap::{all_triangles_degenerate, auto_unwrap};
use texturecraft_geom::{BaseColor, MAX_TRIANGLES, Mesh, SubMesh, UvGBuffer};
use crate::{FormatError, Result};
@@ -32,6 +33,7 @@ use crate::{FormatError, Result};
#[cfg(not(target_arch = "wasm32"))]
pub use external::read_mesh_file;
pub use external::{MeshFile, self_contained_mesh};
pub use mesh_uv_source::MeshUvSource;
/// Mesh files larger than this are refused before reading.
pub const MAX_MESH_FILE_BYTES: u64 = 2 << 30;
@@ -108,7 +110,7 @@ pub struct MeshReport {
pub triangles: usize,
pub vertices: usize,
pub materials: usize,
/// The file had no UVs; they were generated by the automatic unwrap.
/// The UVs were generated by the automatic unwrap.
pub uvs_generated: bool,
/// Triangles with a UV outside 0..1.
pub uv_out_of_range: usize,
@@ -295,7 +297,32 @@ fn extension(file_name: &str) -> String {
/// self-contained (see [`self_contained_mesh`]); OBJ material libraries are not read (usemtl
/// names are).
pub fn import_mesh_bytes(file_name: &str, bytes: &[u8]) -> Result<ImportedMesh> {
finish(read(file_name, bytes)?)
import_mesh_bytes_with_uvs(file_name, bytes, false)
}
/// Import mesh bytes, optionally rebuilding the UV layout even when the mesh already has UVs.
pub fn import_mesh_bytes_with_uvs(file_name: &str, bytes: &[u8], rebuild_uvs: bool) -> Result<ImportedMesh> {
finish(read(file_name, bytes)?, rebuild_uvs)
}
/// Import mesh bytes with a saved UV layout ([`corner_uvs`] of the mesh as first imported)
/// instead of the file's UVs or the automatic unwrap, so the layout does not depend on the
/// unwrapper of the running version.
pub fn import_mesh_bytes_with_layout(file_name: &str, bytes: &[u8], corner_uvs: &[Vec2]) -> Result<ImportedMesh> {
finish_with_layout(read(file_name, bytes)?, MeshUvSource::Saved(corner_uvs))
}
/// Read validated geometry for project open and mesh replacement, which keep the project's cameras
/// and do not need the import dialog's UV coverage report.
pub fn import_mesh_geometry(file_name: &str, bytes: &[u8], uv_source: MeshUvSource<'_>) -> Result<Mesh> {
let (mesh, _, _) = complete_mesh(read(file_name, bytes)?, uv_source)?;
Ok(mesh)
}
/// The UV of every triangle corner, in index order: a layout that [`import_mesh_bytes_with_layout`]
/// applies to the same mesh file again.
pub fn corner_uvs(mesh: &Mesh) -> Vec<Vec2> {
mesh.indices.iter().map(|index| mesh.uvs.get(*index as usize).copied().unwrap_or_default()).collect()
}
/// Import a mesh file with the files it references next to it ([`read_mesh_file`]).
@@ -481,7 +508,7 @@ fn geometry(raw: RawMesh) -> Result<(Mesh, Vec<String>, Option<Vec<Vec2>>)> {
mesh.normals = match normals {
Some(n) if n.len() == mesh.positions.len() => n.into_iter().map(|v| v.try_normalize().unwrap_or(Vec3::Y)).collect(),
_ => smooth_normals(&mesh),
_ => mesh.smooth_normals(),
};
if let Some(c) = colors.filter(|c| c.len() == mesh.positions.len()) {
mesh.colors = c.into_iter().map(|v| if v.is_finite() { v.clamp(Vec4::ZERO, Vec4::ONE) } else { Vec4::ONE }).collect();
@@ -491,29 +518,96 @@ fn geometry(raw: RawMesh) -> Result<(Mesh, Vec<String>, Option<Vec<Vec2>>)> {
}
/// Complete a raw mesh: submeshes, normals, UVs, tangents, validation and the report.
pub(crate) fn finish(mut raw: RawMesh) -> Result<ImportedMesh> {
pub(crate) fn finish(raw: RawMesh, rebuild_uvs: bool) -> Result<ImportedMesh> {
finish_with_layout(raw, MeshUvSource::from_rebuild_setting(rebuild_uvs))
}
fn finish_with_layout(mut raw: RawMesh, uv_source: MeshUvSource<'_>) -> Result<ImportedMesh> {
let mut raw_cameras = std::mem::take(&mut raw.cameras);
raw_cameras.truncate(MAX_CAMERAS);
let (mesh, warnings, uvs_generated) = complete_mesh(raw, uv_source)?;
let report = report(&mesh, uvs_generated, warnings);
let cameras = orbit_cameras(&raw_cameras, &mesh);
Ok(ImportedMesh { mesh, report, cameras })
}
fn complete_mesh(raw: RawMesh, uv_source: MeshUvSource<'_>) -> Result<(Mesh, Vec<String>, bool)> {
let (mut mesh, mut warnings, uvs) = geometry(raw)?;
let uvs_generated = match uvs {
Some(uv) if uv.len() == mesh.positions.len() => {
let uvs_generated = match (uv_source, uvs) {
(MeshUvSource::Saved(layout), authored_uvs) => {
drop(authored_uvs);
apply_corner_uvs(&mut mesh, layout)?;
true
}
(MeshUvSource::FromFile, Some(uv)) if uv.len() == mesh.positions.len() => {
if uv.iter().any(|v| !v.is_finite()) {
warnings.push("non-finite UVs were replaced with 0".into());
}
mesh.uvs = uv.into_iter().map(|v| if v.is_finite() { v } else { Vec2::ZERO }).collect();
mesh.compute_tangents();
false
}
_ => {
(source, authored_uvs) => {
drop(authored_uvs);
let charts = auto_unwrap(&mut mesh, UNWRAP_PADDING, UNWRAP_RESOLUTION)?;
warnings.push(format!("the mesh has no UVs; generated an automatic unwrap with {charts} charts"));
let reason = if matches!(source, MeshUvSource::Rebuild) { "rebuild UVs was selected" } else { "the mesh has no UVs" };
warnings.push(format!("{reason}; generated an automatic unwrap with {charts} charts"));
true
}
};
mesh.validate()?;
let report = report(&mesh, uvs_generated, warnings);
let cameras = orbit_cameras(&raw_cameras, &mesh);
Ok(ImportedMesh { mesh, report, cameras })
Ok((mesh, warnings, uvs_generated))
}
/// Give every triangle corner its UV from `layout`, keeping independently packed materials split.
fn apply_corner_uvs(mesh: &mut Mesh, layout: &[Vec2]) -> Result<()> {
if layout.len() != mesh.indices.len() {
return Err(FormatError::Invalid(format!("the saved UV layout has {} corners but the mesh has {}", layout.len(), mesh.indices.len())));
}
if layout.iter().any(|uv| !uv.is_finite()) {
return Err(FormatError::Invalid("the saved UV layout has non-finite UVs".into()));
}
let mut remapped_vertices = HashMap::with_capacity((mesh.positions.len() * 2).min(layout.len()));
let (mut positions, mut normals, mut uvs, mut colors) = (Vec::new(), Vec::new(), Vec::new(), Vec::new());
let mut indices = Vec::with_capacity(mesh.indices.len());
// Geometry supplies contiguous submesh ranges and validates their vertex indices
for submesh in &mesh.submeshes {
let start = submesh.start as usize;
let end = start + submesh.count as usize;
let material = submesh.material as u32;
for (&vertex, &uv) in mesh.indices[start..end].iter().zip(&layout[start..end]) {
let index = *remapped_vertices.entry((vertex, material, uv.to_array().map(f32::to_bits))).or_insert_with(|| {
let source = vertex as usize;
positions.push(mesh.positions[source]);
normals.push(mesh.normals[source]);
if let Some(color) = mesh.colors.get(source) {
colors.push(*color);
}
uvs.push(uv);
(positions.len() - 1) as u32
});
indices.push(index);
}
}
drop(remapped_vertices);
mesh.positions = positions;
mesh.normals = normals;
mesh.uvs = uvs;
mesh.colors = colors;
mesh.indices = indices;
mesh.compute_tangents();
Ok(())
}
/// File cameras as orbit cameras: the target is where the view axis passes the mesh center
@@ -547,23 +641,6 @@ fn orbit_cameras(raw: &[RawCamera], mesh: &Mesh) -> Vec<texturecraft_core::Camer
.collect()
}
/// Area-weighted smooth normals over welded positions (UV seams do not split shading).
fn smooth_normals(mesh: &Mesh) -> Vec<Vec3> {
let welded_vertices = weld_ids(&mesh.positions);
let mut normals = vec![Vec3::ZERO; mesh.positions.len()];
for triangle in mesh.indices.as_chunks::<3>().0 {
let p = |i: u32| mesh.positions.get(i as usize).copied().unwrap_or_default();
let face = (p(triangle[1]) - p(triangle[0])).cross(p(triangle[2]) - p(triangle[0]));
for v in triangle {
if let Some(a) = welded_vertices.get(*v as usize).and_then(|w| normals.get_mut(*w as usize)) {
*a += face;
}
}
}
welded_vertices.iter().map(|w| normals.get(*w as usize).and_then(|n| n.try_normalize()).unwrap_or(Vec3::Y)).collect()
}
/// Inspects `mesh` and generates its UV report (overlaps, out-of-range UVs, warnings).
pub fn mesh_report(mesh: &Mesh) -> MeshReport {
report(mesh, false, Vec::new())
+42
View File
@@ -757,3 +757,45 @@ fn duplicate_gltf_material_names_keep_first_wins_and_order() {
}
assert_eq!(color_by_material.get("Dup").unwrap().factor, Vec4::new(1.0, 0.0, 0.0, 1.0));
}
#[test]
fn a_saved_layout_reproduces_the_rebuilt_mesh_without_unwrapping() {
let rebuilt = import_mesh_bytes_with_uvs("a.obj", OBJ.as_bytes(), true).unwrap().mesh;
let layout = corner_uvs(&rebuilt);
let reopened = import_mesh_bytes_with_layout("a.obj", OBJ.as_bytes(), &layout).unwrap();
let short = import_mesh_bytes_with_layout("a.obj", OBJ.as_bytes(), &layout[1..]);
let mut non_finite = layout.clone();
non_finite[0].x = f32::NAN;
assert!(!reopened.report.warnings.iter().any(|warning| warning.contains("unwrap")), "{:?}", reopened.report.warnings);
assert_eq!((&reopened.mesh.positions, &reopened.mesh.indices, &reopened.mesh.uvs), (&rebuilt.positions, &rebuilt.indices, &rebuilt.uvs));
assert_eq!(reopened.mesh.normals, rebuilt.normals);
assert!(short.is_err(), "a layout for another mesh is refused");
assert!(import_mesh_bytes_with_layout("a.obj", OBJ.as_bytes(), &non_finite).is_err());
}
#[test]
fn a_saved_layout_keeps_coincident_vertices_in_different_materials_split() {
// Synthetic mesh with coincident triangles in independently packed materials
let source = br#"#usda 1.0
def Mesh "Overlaid" {
int[] faceVertexCounts = [3, 3]
int[] faceVertexIndices = [0, 1, 2, 0, 1, 2]
point3f[] points = [(0, 0, 0), (1, 0, 0), (0, 1, 0)]
rel material:binding = </First>
def GeomSubset "second" {
uniform token familyName = "materialBind"
int[] indices = [1]
rel material:binding = </Second>
}
}
"#;
let rebuilt = import_mesh_bytes_with_uvs("overlaid.usda", source, true).unwrap().mesh;
let layout = corner_uvs(&rebuilt);
let reopened = import_mesh_bytes_with_layout("overlaid.usda", source, &layout).unwrap().mesh;
assert_eq!(&layout[..3], &layout[3..], "the independently packed triangles have equal UVs");
assert_eq!(reopened, rebuilt);
}
+1 -1
View File
@@ -707,7 +707,7 @@ def Xform "Root"
}
"#;
let albedo = png([200, 10, 10]);
let mut writer = craft_zip_usdz::Writer::new();
let mut writer = craft_zip::Writer::new();
writer.add_stored_aligned("sub/scene.usda", usda.as_bytes(), 64).unwrap();
writer.add_stored_aligned("sub/tex/albedo.png", &albedo, 64).unwrap();
let pkg = writer.finish().unwrap();
+126 -47
View File
@@ -4,6 +4,7 @@
//! |---|---|
//! | `project.json` | serde JSON of [`Project`] |
//! | `mesh.<ext>` | the original imported mesh file (absent for built-in meshes, `Project.mesh = "builtin:<id>"`) |
//! | `uv_layout.bin` | the UV of every triangle corner of a mesh whose UVs were rebuilt (format 4+, see `uv_layout`) |
//! | `highpoly/<name>` | a high-definition mesh file for baking, in list order |
//! | `cage/<name>` | the baking cage mesh file |
//! | `bake_paint/<ts>_<target>.bin` | cage or skew paint, stored as a one-component baked map |
@@ -18,19 +19,22 @@
//! count of 0, followed by `width × height × components` f32 LE. Pixels of a UV-tiled texture
//! set cover its whole atlas (`resolution` per tile, see `TileGrid`).
use std::borrow::Borrow;
use std::borrow::{Borrow, Cow};
use std::collections::{BTreeMap, HashSet};
use std::io::{Cursor, Read, Seek, Write};
use std::sync::Arc;
use texturecraft_compose::{BakedMaps, PixelStore};
use texturecraft_core::project::REBUILT_MESH_UVS_VERSION;
use texturecraft_core::{BakePaintTarget, BakedMap, Channel, FORMAT_VERSION, LayerId, Project, TANGENT_BENT_NORMAL_VERSION};
use texturecraft_geom::glam::Vec2;
use texturecraft_texel::{TILE_AREA, TileImage};
use zip::write::SimpleFileOptions;
use zip::{CompressionMethod, ZipArchive, ZipWriter};
use self::entries::Entry;
use self::load_budget::LoadBudget;
use self::uv_layout::{MAX_UV_LAYOUT_BYTES, UV_LAYOUT_ENTRY, read_uv_layout, uv_layout_bytes, write_uv_layout};
use crate::{FormatError, MAX_IMAGE_SIZE, Result, malformed};
mod entries;
@@ -38,10 +42,13 @@ mod load_budget;
mod project_open_limit;
mod ram_operation;
mod ram_reservation;
mod save_progress;
mod uv_layout;
#[cfg(not(target_arch = "wasm32"))]
pub use entries::{DEFAULT_RAM_PERCENT, DEFAULT_RESERVED_CORES, available_save_resources, configured_ram_budget, save_ram_budget, set_save_resources};
pub use project_open_limit::{DEFAULT_PROJECT_OPEN_LIMIT_GIB, project_open_limit_gib, set_project_open_limit_gib};
pub use ram_reservation::RamReservation;
pub use save_progress::SaveProgress;
const KIND: &str = "project file";
#[cfg(test)]
@@ -65,18 +72,21 @@ pub use bake_paint_data::BakePaintData;
/// Everything a project file holds.
#[derive(Clone, Debug)]
pub struct ProjectFile<Resource = Vec<u8>> {
pub struct ProjectFile<Resource = Vec<u8>, MeshBytes = Vec<u8>> {
pub project: Project,
pub pixels: PixelStore,
/// Baked mesh maps per texture set index.
pub baked: BTreeMap<usize, BakedMaps>,
/// Original mesh file: (extension, bytes).
pub mesh: Option<(String, Vec<u8>)>,
pub mesh: Option<(String, MeshBytes)>,
/// Saved UV layout of `mesh` when its UVs were rebuilt: the UV of every triangle corner, in
/// index order, as the mesh was first imported.
pub mesh_uvs: Option<Vec<Vec2>>,
/// High-definition mesh files for baking: (file name, bytes). Names are
/// [`sanitize_resource_name`]d on save.
pub high_poly: Vec<(String, Vec<u8>)>,
pub high_poly: Vec<(String, MeshBytes)>,
/// Baking cage mesh file: (file name, bytes).
pub cage: Option<(String, Vec<u8>)>,
pub cage: Option<(String, MeshBytes)>,
pub bake_paint: BTreeMap<(usize, BakePaintTarget), BakePaintData>,
pub thumbnail: Option<Vec<u8>>,
/// Imported resources (images used by fills, alphas, stencils), by name: original bytes.
@@ -85,6 +95,21 @@ pub struct ProjectFile<Resource = Vec<u8>> {
pub warnings: Vec<String>,
}
impl<Resource, MeshBytes> ProjectFile<Resource, MeshBytes> {
/// Check that the mesh source and the rebuild setting agree with the saved layout.
pub fn validate_mesh_uvs(&self) -> Result<()> {
if self.project.mesh_rebuild_uvs != self.mesh_uvs.is_some() {
return Err(malformed(KIND, format!("{UV_LAYOUT_ENTRY} is required exactly when mesh UVs were rebuilt")));
}
if self.mesh_uvs.is_some() && (self.mesh.is_none() || self.project.mesh.starts_with("builtin:")) {
return Err(malformed(KIND, format!("{UV_LAYOUT_ENTRY} requires a stored mesh")));
}
Ok(())
}
}
/// Maximum length of a resource name after sanitization.
pub const MAX_RESOURCE_NAME_LEN: usize = 120;
@@ -109,11 +134,15 @@ pub fn save_project(path: &std::path::Path, project_file: &ProjectFile) -> Resul
}
#[cfg(not(target_arch = "wasm32"))]
fn write_project_atomic(path: &std::path::Path, project_file: &ProjectFile<impl Borrow<Vec<u8>>>) -> Result<()> {
fn write_project_atomic(
path: &std::path::Path,
project_file: &ProjectFile<impl Borrow<Vec<u8>>, impl Borrow<Vec<u8>>>,
progress: Option<&SaveProgress>,
) -> Result<()> {
let (temporary_path, file) = crate::create_temp(path)?;
let result = (|| -> Result<()> {
let mut file = std::io::BufWriter::new(file);
write_project(&mut file, project_file)?;
write_project(&mut file, project_file, progress)?;
file.into_inner().map_err(|error| error.into_error())?.sync_all()?;
std::fs::rename(&temporary_path, path)?;
Ok(())
@@ -187,12 +216,24 @@ fn write_baked(w: &mut dyn Write, res: u32, h: u32, comps: usize, data: &[f32])
}
/// The zip entries of a project file, in file order. Bodies run later, possibly on other threads.
fn entries(pf: &ProjectFile<impl Borrow<Vec<u8>>>) -> Result<Vec<Entry<'_>>> {
fn entries(project_file: &ProjectFile<impl Borrow<Vec<u8>>, impl Borrow<Vec<u8>>>) -> Result<Vec<Entry<'_>>> {
project_file.validate_mesh_uvs()?;
let deflate = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated).large_file(true);
let stored = SimpleFileOptions::default().compression_method(CompressionMethod::Stored);
let json = serde_json::to_vec_pretty(&pf.project).map_err(|e| FormatError::Invalid(e.to_string()))?;
let mut project = Cow::Borrowed(&project_file.project);
// Callers can supply a document directly instead of a versioned save snapshot
let version = project.save_format_version();
if project.format_version != version {
project.to_mut().format_version = version;
}
let json = serde_json::to_vec_pretty(project.as_ref()).map_err(|e| FormatError::Invalid(e.to_string()))?;
let mut out = vec![Entry { name: "project.json".into(), options: deflate, weight: json.len() as u64, body: Box::new(move |w| w.write_all(&json)) }];
if let Some((ext, bytes)) = &pf.mesh {
if let Some((ext, bytes)) = &project_file.mesh {
let bytes = bytes.borrow();
out.push(Entry {
name: format!("mesh.{}", sanitize_ext(ext)),
options: deflate,
@@ -200,8 +241,19 @@ fn entries(pf: &ProjectFile<impl Borrow<Vec<u8>>>) -> Result<Vec<Entry<'_>>> {
body: Box::new(move |w| w.write_all(bytes)),
});
}
if let Some(layout) = &project_file.mesh_uvs {
out.push(Entry {
name: UV_LAYOUT_ENTRY.into(),
options: deflate,
weight: uv_layout_bytes(layout.len()),
body: Box::new(move |w| write_uv_layout(w, layout)),
});
}
let mut used = HashSet::new();
for (dir, (name, bytes)) in pf.high_poly.iter().map(|m| ("highpoly", m)).chain(pf.cage.iter().map(|m| ("cage", m))) {
for (dir, (name, bytes)) in project_file.high_poly.iter().map(|m| ("highpoly", m)).chain(project_file.cage.iter().map(|m| ("cage", m))) {
let bytes = bytes.borrow();
out.push(Entry {
name: unique_entry_name(dir, name, &mut used),
options: deflate,
@@ -209,7 +261,8 @@ fn entries(pf: &ProjectFile<impl Borrow<Vec<u8>>>) -> Result<Vec<Entry<'_>>> {
body: Box::new(move |w| w.write_all(bytes)),
});
}
for ((texture_set, target), map) in &pf.bake_paint {
for ((texture_set, target), map) in &project_file.bake_paint {
if map.width == 0 || map.height == 0 || map.values.len() as u64 != u64::from(map.width) * u64::from(map.height) {
return Err(FormatError::Invalid("bake paint map dimensions do not match its values".into()));
}
@@ -218,6 +271,7 @@ fn entries(pf: &ProjectFile<impl Borrow<Vec<u8>>>) -> Result<Vec<Entry<'_>>> {
BakePaintTarget::Cage => "cage",
BakePaintTarget::Skew => "skew",
};
out.push(Entry {
name: format!("bake_paint/{texture_set}_{target_name}.bin"),
options: deflate,
@@ -225,7 +279,8 @@ fn entries(pf: &ProjectFile<impl Borrow<Vec<u8>>>) -> Result<Vec<Entry<'_>>> {
body: Box::new(move |w| write_baked(w, map.width, map.height, 1, &map.values)),
});
}
let mut layers: Vec<_> = pf.pixels.layers.iter().collect();
let mut layers: Vec<_> = project_file.pixels.layers.iter().collect();
layers.sort_by_key(|(k, _)| **k);
for ((id, c), img) in layers {
let weight = (img.allocated_count() * (TILE_AREA * img.comps() * 2 + 8)) as u64;
@@ -236,13 +291,14 @@ fn entries(pf: &ProjectFile<impl Borrow<Vec<u8>>>) -> Result<Vec<Entry<'_>>> {
body: Box::new(move |mut w| write_tiles(&mut w, img)),
});
}
let mut masks: Vec<_> = pf.pixels.masks.iter().collect();
let mut masks: Vec<_> = project_file.pixels.masks.iter().collect();
masks.sort_by_key(|(k, _)| **k);
for (id, img) in masks {
let weight = (img.allocated_count() * (TILE_AREA * img.comps() * 2 + 8)) as u64;
out.push(Entry { name: format!("pixels/mask_{}.bin", id.0), options: deflate, weight, body: Box::new(move |mut w| write_tiles(&mut w, img)) });
}
for (ts, maps) in &pf.baked {
for (ts, maps) in &project_file.baked {
let r = maps.resolution;
for (m, data) in &maps.maps {
// Skip inconsistent maps so the saved project can reopen and bake them again
@@ -260,11 +316,13 @@ fn entries(pf: &ProjectFile<impl Borrow<Vec<u8>>>) -> Result<Vec<Entry<'_>>> {
});
}
}
if let Some(png) = &pf.thumbnail {
if let Some(png) = &project_file.thumbnail {
out.push(Entry { name: "thumbnail.png".into(), options: stored, weight: png.len() as u64, body: Box::new(move |w| w.write_all(png)) });
}
used.clear();
for (name, resource) in &pf.resources {
for (name, resource) in &project_file.resources {
let bytes = resource.borrow();
out.push(Entry {
name: unique_entry_name("resources", name, &mut used),
@@ -273,12 +331,17 @@ fn entries(pf: &ProjectFile<impl Borrow<Vec<u8>>>) -> Result<Vec<Entry<'_>>> {
body: Box::new(move |w| w.write_all(bytes)),
});
}
Ok(out)
}
fn write_project<W: Write + Seek>(out: W, pf: &ProjectFile<impl Borrow<Vec<u8>>>) -> Result<()> {
fn write_project<W: Write + Seek>(out: W, pf: &ProjectFile<impl Borrow<Vec<u8>>, impl Borrow<Vec<u8>>>, progress: Option<&SaveProgress>) -> Result<()> {
let mut zip = ZipWriter::new(out);
entries::write_entries(&mut zip, entries(pf)?)?;
let mut entries = entries(pf)?;
if let Some(progress) = progress {
progress.track(&mut entries);
}
entries::write_entries(&mut zip, entries)?;
zip.finish().map_err(zip_err)?;
Ok(())
}
@@ -406,10 +469,11 @@ fn load_archive<R: Read + Seek>(mut zip: ZipArchive<R>, mut budget: LoadBudget)
return Err(malformed(KIND, format!("texture set \"{}\" has resolution {} over {} UV tiles", ts.name, ts.resolution, ts.uv_tiles.len().max(1))));
}
let mut pf = ProjectFile {
let mut project_file = ProjectFile {
pixels: PixelStore::default(),
baked: BTreeMap::new(),
mesh: None,
mesh_uvs: None,
high_poly: Vec::new(),
cage: None,
bake_paint: BTreeMap::new(),
@@ -419,36 +483,36 @@ fn load_archive<R: Read + Seek>(mut zip: ZipArchive<R>, mut budget: LoadBudget)
project,
};
for i in 0..zip.len() {
let mut f = zip.by_index(i).map_err(zip_err)?;
let declared_bytes = f.size();
let name = f.name().map_err(zip_err)?.into_owned();
let size_of = |id: LayerId| texture_set_of(&pf.project, id).and_then(|ts| pf.project.texture_sets.get(ts)).map(|t| t.size());
for index in 0..zip.len() {
let mut entry = zip.by_index(index).map_err(zip_err)?;
let declared_bytes = entry.size();
let name = entry.name().map_err(zip_err)?.into_owned();
let size_of = |id: LayerId| texture_set_of(&project_file.project, id).and_then(|ts| project_file.project.texture_sets.get(ts)).map(|t| t.size());
// Unrecognized entries from newer minor revisions may be skipped
if name == "thumbnail.png" {
pf.thumbnail = Some(read_all(&mut f, MAX_THUMBNAIL, &mut budget, &name)?);
project_file.thumbnail = Some(read_all(&mut entry, MAX_THUMBNAIL, &mut budget, &name)?);
} else if let Some(res_name) = name.strip_prefix("resources/") {
if res_name.is_empty() || sanitize_resource_name(res_name) != res_name {
return Err(malformed(KIND, format!("bad resource name {name}")));
}
let bytes = read_all(&mut f, MAX_RESOURCE, &mut budget, &name)?;
pf.resources.insert(res_name.to_string(), bytes);
let bytes = read_all(&mut entry, MAX_RESOURCE, &mut budget, &name)?;
project_file.resources.insert(res_name.to_string(), bytes);
} else if let Some((dir, file)) = name.split_once('/').filter(|(d, _)| *d == "highpoly" || *d == "cage") {
if file.is_empty() || sanitize_resource_name(file) != file {
return Err(malformed(KIND, format!("bad mesh name {name}")));
}
let entry = (file.to_string(), read_all(&mut f, crate::mesh_import::MAX_MESH_FILE_BYTES, &mut budget, &name)?);
let entry = (file.to_string(), read_all(&mut entry, crate::mesh_import::MAX_MESH_FILE_BYTES, &mut budget, &name)?);
match dir {
"cage" => pf.cage = Some(entry),
_ => pf.high_poly.push(entry),
"cage" => project_file.cage = Some(entry),
_ => project_file.high_poly.push(entry),
}
} else if let Some(rest) = name.strip_prefix("bake_paint/").and_then(|name| name.strip_suffix(".bin")) {
let (texture_set, target) = rest.split_once('_').ok_or_else(|| malformed(KIND, format!("bad entry {name}")))?;
let texture_set: usize = texture_set.parse().map_err(|_| malformed(KIND, format!("bad entry {name}")))?;
if texture_set >= pf.project.texture_sets.len() {
if texture_set >= project_file.project.texture_sets.len() {
return Err(malformed(KIND, format!("unknown texture set in {name}")));
}
@@ -457,11 +521,22 @@ fn load_archive<R: Read + Seek>(mut zip: ZipArchive<R>, mut budget: LoadBudget)
"skew" => BakePaintTarget::Skew,
_ => return Err(malformed(KIND, format!("unknown bake paint target in {name}"))),
};
let (width, height, values) = read_baked(&mut f, declared_bytes, 1, &mut budget, &name)?;
pf.bake_paint.insert((texture_set, target), BakePaintData { width, height, values });
let (width, height, values) = read_baked(&mut entry, declared_bytes, 1, &mut budget, &name)?;
project_file.bake_paint.insert((texture_set, target), BakePaintData { width, height, values });
} else if let Some(ext) = name.strip_prefix("mesh.").filter(|e| !e.contains('/')) {
let bytes = read_all(&mut f, crate::mesh_import::MAX_MESH_FILE_BYTES, &mut budget, &name)?;
pf.mesh = Some((ext.to_string(), bytes));
let bytes = read_all(&mut entry, crate::mesh_import::MAX_MESH_FILE_BYTES, &mut budget, &name)?;
project_file.mesh = Some((ext.to_string(), bytes));
} else if name == UV_LAYOUT_ENTRY {
if version < REBUILT_MESH_UVS_VERSION || !project_file.project.mesh_rebuild_uvs {
return Err(malformed(KIND, format!("{UV_LAYOUT_ENTRY} requires format {REBUILT_MESH_UVS_VERSION} or later and rebuilt mesh UVs")));
}
if declared_bytes > MAX_UV_LAYOUT_BYTES {
return Err(FormatError::TooLarge(format!("{UV_LAYOUT_ENTRY} is larger than {MAX_UV_LAYOUT_BYTES} bytes")));
}
budget.take(declared_bytes).map_err(FormatError::TooLarge)?;
project_file.mesh_uvs = Some(read_uv_layout(&mut entry, declared_bytes)?);
} else if let Some(rest) = name.strip_prefix("pixels/layer_").and_then(|r| r.strip_suffix(".bin")) {
let (id, chan) = rest.split_once('_').ok_or_else(|| malformed(KIND, format!("bad entry name {name}")))?;
let id = LayerId(id.parse().map_err(|_| malformed(KIND, format!("bad entry name {name}")))?);
@@ -470,14 +545,14 @@ fn load_archive<R: Read + Seek>(mut zip: ZipArchive<R>, mut budget: LoadBudget)
// Drop pixels of layers that are no longer in any stack
let Some(size) = size_of(id) else { continue };
let img = read_tiles(&mut f, size, c.components() + 1, &mut budget, &name)?;
pf.pixels.layers.insert((id, c), img);
let img = read_tiles(&mut entry, size, c.components() + 1, &mut budget, &name)?;
project_file.pixels.layers.insert((id, c), img);
} else if let Some(rest) = name.strip_prefix("pixels/mask_").and_then(|r| r.strip_suffix(".bin")) {
let id = LayerId(rest.parse().map_err(|_| malformed(KIND, format!("bad entry name {name}")))?);
let Some(size) = size_of(id) else { continue };
let img = read_tiles(&mut f, size, 2, &mut budget, &name)?;
pf.pixels.masks.insert(id, img);
let img = read_tiles(&mut entry, size, 2, &mut budget, &name)?;
project_file.pixels.masks.insert(id, img);
} else if let Some(rest) = name.strip_prefix("baked/").and_then(|r| r.strip_suffix(".bin")) {
let (ts, map) = rest.split_once('_').ok_or_else(|| malformed(KIND, format!("bad entry name {name}")))?;
let ts: usize = ts.parse().map_err(|_| malformed(KIND, format!("bad entry name {name}")))?;
@@ -486,12 +561,12 @@ fn load_archive<R: Read + Seek>(mut zip: ZipArchive<R>, mut budget: LoadBudget)
continue;
};
if ts >= pf.project.texture_sets.len() {
if ts >= project_file.project.texture_sets.len() {
continue;
}
let (res, height, data) = read_baked(&mut f, declared_bytes, m.components(), &mut budget, &name)?;
let maps = pf.baked.entry(ts).or_default();
let (res, height, data) = read_baked(&mut entry, declared_bytes, m.components(), &mut budget, &name)?;
let maps = project_file.baked.entry(ts).or_default();
if maps.maps.is_empty() {
maps.resolution = res;
} else if maps.resolution != res || maps.maps.keys().next().is_some_and(|k| maps.height(*k) != height) {
@@ -502,18 +577,22 @@ fn load_archive<R: Read + Seek>(mut zip: ZipArchive<R>, mut budget: LoadBudget)
}
}
// Rerunning the unwrapper could lay the saved paint over a different layout
project_file.validate_mesh_uvs()?;
if version < TANGENT_BENT_NORMAL_VERSION {
drop_world_space_bent_normals(&mut pf);
drop_world_space_bent_normals(&mut project_file);
}
pf.project.format_version = FORMAT_VERSION;
project_file.project.format_version = version.max(TANGENT_BENT_NORMAL_VERSION);
if recovered {
pf.warnings.push(
project_file.warnings.push(
"Warning: Some project settings or mesh maps could not be imported. TextureCraft recovered what it could, using defaults where needed.".into(),
);
}
Ok(pf)
Ok(project_file)
}
/// Older files hold bent normal maps in world space, which every reader now takes as tangent
@@ -2,6 +2,8 @@ use std::borrow::Borrow;
use std::io::Cursor;
use std::sync::{Condvar, Mutex};
#[cfg(not(target_arch = "wasm32"))]
use super::SaveProgress;
use super::{ProjectFile, ram_operation::RamOperation, write_project};
use crate::{FormatError, Result};
@@ -54,17 +56,28 @@ impl RamReservation {
Some(Self(RamOperation::Save))
}
pub fn save_bytes(&mut self, project_file: &ProjectFile<impl Borrow<Vec<u8>>>) -> Result<Vec<u8>> {
pub fn save_bytes(&mut self, project_file: &ProjectFile<impl Borrow<Vec<u8>>, impl Borrow<Vec<u8>>>) -> Result<Vec<u8>> {
self.check_save()?;
let mut out = Cursor::new(Vec::new());
write_project(&mut out, project_file)?;
write_project(&mut out, project_file, None)?;
Ok(out.into_inner())
}
#[cfg(not(target_arch = "wasm32"))]
pub fn save(&mut self, path: &std::path::Path, project_file: &ProjectFile<impl Borrow<Vec<u8>>>) -> Result<()> {
pub fn save(&mut self, path: &std::path::Path, project_file: &ProjectFile<impl Borrow<Vec<u8>>, impl Borrow<Vec<u8>>>) -> Result<()> {
self.check_save()?;
super::write_project_atomic(path, project_file)
super::write_project_atomic(path, project_file, None)
}
#[cfg(not(target_arch = "wasm32"))]
pub fn save_with_progress(
&mut self,
path: &std::path::Path,
project_file: &ProjectFile<impl Borrow<Vec<u8>>, impl Borrow<Vec<u8>>>,
progress: &SaveProgress,
) -> Result<()> {
self.check_save()?;
super::write_project_atomic(path, project_file, Some(progress))
}
fn check_save(&self) -> Result<()> {
@@ -0,0 +1,45 @@
use std::sync::atomic::{AtomicU64, Ordering};
use super::entries::Entry;
mod progress_writer;
use progress_writer::ProgressWriter;
// Leave room on the indicator for syncing and replacing the archive
const MAX_PAYLOAD_PROGRESS: f32 = 0.95;
/// Estimated archive progress, based on the payload processed by the entry writers.
/// Completing the archive, syncing it to disk, and replacing the destination can take longer.
#[derive(Default)]
pub struct SaveProgress {
total: AtomicU64,
processed: AtomicU64,
}
impl SaveProgress {
pub fn fraction(&self) -> f32 {
let total = self.total.load(Ordering::Relaxed);
if total == 0 {
return 0.0;
}
let processed = self.processed.load(Ordering::Relaxed).min(total);
MAX_PAYLOAD_PROGRESS * (processed as f64 / total as f64) as f32
}
pub(super) fn track<'a>(&'a self, entries: &mut [Entry<'a>]) {
self.processed.store(0, Ordering::Relaxed);
self.total.store(entries.iter().fold(0u64, |sum, entry| sum.saturating_add(entry.weight)), Ordering::Relaxed);
for entry in entries {
let body = std::mem::replace(&mut entry.body, Box::new(|_| Ok(())));
let remaining = entry.weight;
entry.body = Box::new(move |target| {
let mut writer = ProgressWriter { target, progress: self, remaining, pending: 0 };
body(&mut writer)?;
writer.report();
Ok(())
});
}
}
}
@@ -0,0 +1,37 @@
use std::io::{self, Write};
use std::sync::atomic::Ordering;
use super::SaveProgress;
// Batch updates to reduce contention between compression workers
const PROGRESS_UPDATE_BYTES: u64 = 64 * 1024;
pub(super) struct ProgressWriter<'a> {
pub(super) target: &'a mut dyn Write,
pub(super) progress: &'a SaveProgress,
pub(super) remaining: u64,
pub(super) pending: u64,
}
impl ProgressWriter<'_> {
pub(super) fn report(&mut self) {
self.progress.processed.fetch_add(std::mem::take(&mut self.pending), Ordering::Relaxed);
}
}
impl Write for ProgressWriter<'_> {
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
let written = self.target.write(bytes)?;
let counted = (written as u64).min(self.remaining);
self.remaining -= counted;
self.pending += counted;
if self.pending >= PROGRESS_UPDATE_BYTES {
self.report();
}
Ok(written)
}
fn flush(&mut self) -> io::Result<()> {
self.target.flush()
}
}
+85 -1
View File
@@ -32,6 +32,7 @@ fn sample() -> Sample {
pixels,
baked: [(0, baked)].into(),
mesh: Some(("glb".into(), vec![1, 2, 3, 4, 5])),
mesh_uvs: None,
high_poly: vec![("b_high.obj".into(), vec![7; 9]), ("a_high.ply".into(), vec![6])],
cage: Some(("cage.obj".into(), vec![5, 5])),
bake_paint: [((0, texturecraft_core::BakePaintTarget::Skew), BakePaintData { width: 3, height: 2, values: vec![0.0, 0.25, 0.5, 0.75, 1.0, 0.125] })]
@@ -55,6 +56,7 @@ fn assert_same(a: &ProjectFile, b: &ProjectFile) {
}
assert_eq!(a.baked, b.baked);
assert_eq!(a.mesh, b.mesh);
assert_eq!(a.mesh_uvs, b.mesh_uvs);
assert_eq!((&a.high_poly, &a.cage), (&b.high_poly, &b.cage), "bake meshes keep their order");
assert_eq!(a.bake_paint, b.bake_paint);
assert_eq!(a.thumbnail, b.thumbnail);
@@ -104,7 +106,7 @@ fn legacy_bakes_load_as_is_without_layout_conversion() {
sample.pf.baked.insert(0, BakedMaps { resolution: 32, maps: [(BakedMap::AmbientOcclusion, Arc::new(pixels))].into() });
let loaded = load_project_bytes(&save_project_bytes(&sample.pf).unwrap()).unwrap();
assert_eq!(loaded.project.format_version, FORMAT_VERSION);
assert_eq!(loaded.project.format_version, TANGENT_BENT_NORMAL_VERSION);
assert_eq!(loaded.baked, sample.pf.baked, "old bake pixels are accepted without preserving their former layout");
assert_eq!(loaded.bake_paint, sample.pf.bake_paint, "correction paint remains in the working layout");
let reopened = load_project_bytes(&save_project_bytes(&loaded).unwrap()).unwrap();
@@ -920,3 +922,85 @@ fn zip64_entry_counts_remain_supported_and_bounded() {
}
}
}
fn rebuilt_uvs_sample() -> ProjectFile {
let mut project_file = sample().pf;
project_file.project.mesh_rebuild_uvs = true;
project_file.mesh_uvs = Some(vec![Vec2::new(0.25, 0.75), Vec2::new(1.0, 0.0), Vec2::new(0.5, 0.125)]);
project_file
}
#[test]
fn a_saved_uv_layout_round_trips_in_format_4() {
const ADDITIONAL_CORNERS: usize = 3000;
let mut project_file = rebuilt_uvs_sample();
let layout = project_file.mesh_uvs.as_mut().unwrap();
// Exercise full batches and a partial final batch with distinct UVs
layout.extend((0..ADDITIONAL_CORNERS).map(|corner| Vec2::new(corner as f32 / ADDITIONAL_CORNERS as f32, 0.5)));
let loaded = load_project_bytes(&save_project_bytes(&project_file).unwrap()).unwrap();
assert_eq!(loaded.mesh_uvs, project_file.mesh_uvs);
assert_eq!(loaded.project.format_version, REBUILT_MESH_UVS_VERSION);
}
#[test]
fn a_saved_uv_layout_requires_format_4_and_the_rebuild_setting() {
let project_file = rebuilt_uvs_sample();
let older_version = edit_project_json(&project_file, |json| json["format_version"] = TANGENT_BENT_NORMAL_VERSION.into());
let disabled_rebuild = edit_project_json(&project_file, |json| json["mesh_rebuild_uvs"] = false.into());
for archive in [older_version, disabled_rebuild] {
let error = load_project_bytes(&archive).map(|_| ()).expect_err("the archive has inconsistent UV layout metadata");
assert!(error.to_string().contains(UV_LAYOUT_ENTRY), "{error}");
}
}
#[test]
fn a_rebuilt_project_cannot_be_saved_without_its_layout() {
let mut project_file = rebuilt_uvs_sample();
project_file.mesh_uvs = None;
let error = save_project_bytes(&project_file).map(|_| ()).expect_err("the snapshot is missing the rebuilt UV layout");
assert!(error.to_string().contains(UV_LAYOUT_ENTRY), "{error}");
}
#[test]
fn rebuilt_uvs_without_a_valid_saved_layout_are_refused() {
let project_file = rebuilt_uvs_sample();
let without_layout = edit_archive(&project_file, |name, _| {
if name == UV_LAYOUT_ENTRY {
*name = "ignored.bin".into();
}
});
let edited_layout = |edit: fn(&mut Vec<u8>)| {
edit_archive(&project_file, |name, data| {
if name == UV_LAYOUT_ENTRY {
edit(data);
}
})
};
let truncated = edited_layout(|data| data.truncate(data.len() - 1));
let trailing_bytes = edited_layout(|data| data.push(0));
let short_header = edited_layout(|data| data.truncate(8));
let wrong_count = edited_layout(|data| data[8] = 9);
let non_finite = edited_layout(|data| data[12..16].copy_from_slice(&f32::NAN.to_le_bytes()));
let bad_magic = edited_layout(|data| data[0] = b'X');
for (case, bytes) in [
("missing", without_layout),
("truncated", truncated),
("trailing bytes", trailing_bytes),
("short header", short_header),
("wrong count", wrong_count),
("non-finite", non_finite),
("bad magic", bad_magic),
] {
let error = load_project_bytes(&bytes).unwrap_err();
assert!(!is_guard_error(&error), "{case}: {error}");
}
}
@@ -0,0 +1,99 @@
//! `uv_layout.bin` stores the generated UVs independently of the running unwrapper.
//! After the magic `TCUV`, the header stores a version and a corner count as little-endian u32s.
//! The body stores a little-endian f32 pair for each triangle corner in index order.
use std::io::{Read, Write};
use texturecraft_geom::MAX_TRIANGLES;
use texturecraft_geom::glam::Vec2;
use super::KIND;
use crate::{Result, malformed};
/// Zip entry name of the saved layout.
pub const UV_LAYOUT_ENTRY: &str = "uv_layout.bin";
const UV_LAYOUT_MAGIC: &[u8; 4] = b"TCUV";
const UV_LAYOUT_VERSION: u32 = 1;
const HEADER_BYTES: usize = 12;
const COORDINATE_BYTES: usize = 4;
const CORNER_BYTES: usize = 2 * COORDINATE_BYTES;
const BATCH_CORNERS: usize = 1024;
const MAX_LAYOUT_CORNERS: usize = MAX_TRIANGLES * 3;
/// Largest entry a valid mesh can need: every corner of the most triangles accepted.
pub const MAX_UV_LAYOUT_BYTES: u64 = uv_layout_bytes(MAX_LAYOUT_CORNERS);
/// Encoded size of a layout of `corners` UVs.
pub const fn uv_layout_bytes(corners: usize) -> u64 {
HEADER_BYTES as u64 + corners as u64 * CORNER_BYTES as u64
}
pub fn write_uv_layout(writer: &mut dyn Write, layout: &[Vec2]) -> std::io::Result<()> {
if layout.len() > MAX_LAYOUT_CORNERS {
return Err(std::io::Error::other("the UV layout has too many corners"));
}
writer.write_all(UV_LAYOUT_MAGIC)?;
writer.write_all(&UV_LAYOUT_VERSION.to_le_bytes())?;
writer.write_all(&(layout.len() as u32).to_le_bytes())?;
let mut buffer = [[0; CORNER_BYTES]; BATCH_CORNERS];
for batch in layout.chunks(BATCH_CORNERS) {
let encoded = &mut buffer[..batch.len()];
for (corner, uv) in encoded.iter_mut().zip(batch) {
if !uv.is_finite() {
return Err(std::io::Error::other("the UV layout has non-finite UVs"));
}
corner.copy_from_slice([uv.x.to_le_bytes(), uv.y.to_le_bytes()].as_flattened());
}
writer.write_all(encoded.as_flattened())?;
}
Ok(())
}
/// Decode one entry while holding only the decoded layout and a fixed-size buffer.
pub fn read_uv_layout(reader: &mut impl Read, entry_bytes: u64) -> Result<Vec<Vec2>> {
let bad = |why: &str| malformed(KIND, format!("{UV_LAYOUT_ENTRY}: {why}"));
let mut header = [[0; COORDINATE_BYTES]; 3];
reader.read_exact(header.as_flattened_mut()).map_err(|error| malformed(KIND, format!("{UV_LAYOUT_ENTRY}: {error}")))?;
let [magic, version, corners] = header;
if magic != *UV_LAYOUT_MAGIC {
return Err(bad("bad magic"));
}
if u32::from_le_bytes(version) != UV_LAYOUT_VERSION {
return Err(bad("unsupported version"));
}
let corners = u32::from_le_bytes(corners) as usize;
if corners > MAX_LAYOUT_CORNERS || uv_layout_bytes(corners) != entry_bytes {
return Err(bad("the corner count does not match the entry size"));
}
let mut layout = Vec::with_capacity(corners);
let mut buffer = [[[0; COORDINATE_BYTES]; 2]; BATCH_CORNERS];
while layout.len() < corners {
let count = (corners - layout.len()).min(BATCH_CORNERS);
let encoded = &mut buffer[..count];
reader.read_exact(encoded.as_flattened_mut().as_flattened_mut()).map_err(|error| malformed(KIND, format!("{UV_LAYOUT_ENTRY}: {error}")))?;
for &[u, v] in encoded.iter() {
let uv = Vec2::new(f32::from_le_bytes(u), f32::from_le_bytes(v));
if !uv.is_finite() {
return Err(bad("non-finite UVs"));
}
layout.push(uv);
}
}
// Read through the end of the ZIP entry so its checksum is checked
match reader.read_exact(&mut [0]) {
Err(error) if error.kind() == std::io::ErrorKind::UnexpectedEof => Ok(layout),
Err(error) => Err(malformed(KIND, format!("{UV_LAYOUT_ENTRY}: {error}"))),
Ok(()) => Err(bad("the corner count does not match the entry size")),
}
}
+55 -2
View File
@@ -245,6 +245,27 @@ impl Mesh {
self.normals = normals.into_iter().map(|v| v.try_normalize().unwrap_or(Vec3::Y)).collect();
}
/// Area-weighted smooth normals over welded positions, so UV and material seams do not split shading.
pub fn smooth_normals(&self) -> Vec<Vec3> {
let welded_vertices = crate::unwrap::weld_ids(&self.positions);
let mut normals = vec![Vec3::ZERO; self.positions.len()];
for triangle in self.indices.as_chunks::<3>().0 {
let p = |i: u32| self.positions.get(i as usize).copied().unwrap_or_default();
let face = (p(triangle[1]) - p(triangle[0])).cross(p(triangle[2]) - p(triangle[0]));
for v in triangle {
if let Some(accumulated) = welded_vertices.get(*v as usize).and_then(|welded| normals.get_mut(*welded as usize)) {
*accumulated += face;
}
}
}
welded_vertices.iter().map(|welded| normals.get(*welded as usize).and_then(|normal| normal.try_normalize()).unwrap_or(Vec3::Y)).collect()
}
/// Replace normals with [`Mesh::smooth_normals`] on this mesh.
pub fn compute_smooth_normals(&mut self) {
self.normals = self.smooth_normals();
}
/// The faces MikkTSpace sees: each importer quad (a fan pair marked in [`Mesh::diagonals`])
/// as one four-corner face, like Blender hands it over, and every other triangle as a
/// triangle. Polygons with more than four corners stay fan triangles. The vertex and index
@@ -315,8 +336,11 @@ impl Mesh {
if self.uvs.len() != self.positions.len() {
self.uvs = vec![Vec2::ZERO; self.positions.len()];
}
// mikktspace crashes (out-of-bounds) when every triangle is degenerate; skip it then.
if crate::unwrap::all_triangles_degenerate(self) {
// mikktspace crashes (out-of-bounds) when every triangle is degenerate; skip it then. Its
// callbacks read a missing vertex as the origin, which the degenerate check cannot see, so
// an index past the last vertex skips it too.
let n = self.positions.len();
if !self.indices.iter().all(|&i| (i as usize) < n) || crate::unwrap::all_triangles_degenerate(self) {
self.simple_tangents();
} else {
let faces = self.tangent_faces();
@@ -497,6 +521,9 @@ impl Mesh {
/// A single-material mesh from raw attributes; computes missing normals and tangents.
pub fn from_parts(positions: Vec<Vec3>, normals: Option<Vec<Vec3>>, uvs: Vec<Vec2>, indices: Vec<u32>, material: &str) -> Result<Mesh> {
if let Some(bad) = indices.iter().find(|&&i| i as usize >= positions.len()) {
return Err(GeomError::Invalid(format!("index {bad} out of range ({} vertices)", positions.len())));
}
let count = indices.len() as u32;
let mut m = Mesh {
normals: normals.unwrap_or_default(),
@@ -910,4 +937,30 @@ mod tests {
assert_eq!(m.uv_tiles(1).into_iter().collect::<Vec<_>>(), vec![(1, 0)]);
assert_eq!(m.uv_tiles(0).into_iter().collect::<Vec<_>>(), vec![(0, 0)]);
}
/// An index past the last vertex reads as the origin in MikkTSpace's callbacks. With two
/// positions at the origin and one missing, the degenerate-mesh guard (which sees the missing
/// vertex as different) let it through while MikkTSpace saw every triangle as degenerate and
/// underflowed: a panic in debug builds, an out-of-bounds walk in release.
#[test]
fn from_parts_refuses_an_out_of_range_index_without_crashing() {
let positions = vec![Vec3::ZERO, Vec3::X];
let uvs = vec![Vec2::ZERO, Vec2::X];
let e = Mesh::from_parts(positions, None, uvs, vec![0, 1, 2], "M").unwrap_err();
assert!(e.to_string().contains("out of range"), "{e}");
}
#[test]
fn tangents_of_a_mesh_with_an_out_of_range_index_fall_back_without_crashing() {
for indices in [vec![0, 1, 2], vec![0, 0, 2], vec![0, 1, 5, 0, 1, 1]] {
let mut m = Mesh::from_parts(vec![Vec3::ZERO, Vec3::X, Vec3::Y], None, vec![Vec2::ZERO, Vec2::X, Vec2::Y], vec![0, 1, 2], "M").unwrap();
m.positions.truncate(2);
m.normals.truncate(2);
m.uvs.truncate(2);
m.indices = indices;
m.compute_tangents();
assert_eq!(m.tangents.len(), 2);
assert!(m.tangents.iter().all(|t| t.is_finite()), "{:?}", m.tangents);
}
}
}
+61 -16
View File
@@ -18,6 +18,10 @@ use texturecraft_geom::glam::Vec3;
use crate::gpu_trace::{STACK, buffer, bvh_depth, bvh_rows, entry, scoped, storage};
const WORKGROUP: u32 = 64;
// The shader binds BVH nodes, triangles, input queries and results
const RAY_STORAGE_BUFFERS: u32 = 4;
// The hemisphere reduction stores one vec4 and one count per lane
const WORKGROUP_STORAGE_BYTES: u32 = WORKGROUP * (size_of::<[f32; 4]>() + size_of::<u32>()) as u32;
/// Rays per dispatch: short dispatches keep slow GPUs clear of driver watchdogs.
const RAYS_PER_DISPATCH: usize = 1 << 24;
const NONE: u32 = u32::MAX;
@@ -66,23 +70,11 @@ fn err(e: impl std::fmt::Display) -> BakeError {
impl Gpu {
fn new() -> Result<Gpu, String> {
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env());
let options = wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, ..Default::default() };
let adapter = pollster::block_on(instance.request_adapter(&options)).map_err(|e| format!("no GPU adapter: {e}"))?;
let info = adapter.get_info();
if info.device_type == wgpu::DeviceType::Cpu {
return Err(format!("{} is a software renderer", info.name));
}
let limits = adapter.limits();
if limits.max_storage_buffers_per_shader_stage < 3
|| limits.max_compute_invocations_per_workgroup < WORKGROUP
|| limits.max_compute_workgroup_size_x < WORKGROUP
{
return Err(format!("{} has no usable compute shaders", info.name));
}
let (adapter, name, limits) = bake_adapter()?;
let desc = wgpu::DeviceDescriptor { label: Some("tc_bake"), required_limits: limits, ..Default::default() };
let (device, queue) = pollster::block_on(adapter.request_device(&desc)).map_err(|e| format!("no GPU device: {e}"))?;
// Errors are caught by the scopes around every call; never let wgpu's default handler panic.
// Each GPU call has an error scope so the default handler should leave failures to those scopes
device.on_uncaptured_error(Arc::new(|_| {}));
let (layout, transfer, hemisphere) = scoped(&device, "GPU baking: pipelines", || {
let params = wgpu::BindingType::Buffer {
@@ -112,7 +104,7 @@ impl Gpu {
(layout, pipe("transfer_main"), pipe("hemisphere_main"))
})?;
let stride = size_of::<Params>().next_multiple_of(device.limits().min_uniform_buffer_offset_alignment.max(1) as usize);
Ok(Gpu { device, queue, name: info.name, layout, transfer, hemisphere, stride })
Ok(Gpu { device, queue, name, layout, transfer, hemisphere, stride })
}
/// The largest storage buffer this device binds.
@@ -122,6 +114,43 @@ impl Gpu {
}
}
/// Whether the adapter selected for mesh-map baking supports its compute shaders.
pub fn raytracing_available() -> bool {
static SUPPORTED: OnceLock<bool> = OnceLock::new();
*SUPPORTED.get_or_init(|| bake_adapter().is_ok())
}
fn bake_adapter() -> Result<(wgpu::Adapter, String, wgpu::Limits), String> {
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env());
let options = wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, ..Default::default() };
let adapter = pollster::block_on(instance.request_adapter(&options)).map_err(|e| format!("no GPU adapter: {e}"))?;
let info = adapter.get_info();
let limits = adapter.limits();
let flags = adapter.get_downlevel_capabilities().flags;
if let Some(reason) = unsupported_adapter(info.device_type, flags, &limits) {
return Err(format!("{} {reason}", info.name));
}
Ok((adapter, info.name, limits))
}
fn unsupported_adapter(device_type: wgpu::DeviceType, flags: wgpu::DownlevelFlags, limits: &wgpu::Limits) -> Option<&'static str> {
if device_type == wgpu::DeviceType::Cpu {
return Some("is a software renderer");
}
if !flags.contains(wgpu::DownlevelFlags::COMPUTE_SHADERS)
|| limits.max_storage_buffers_per_shader_stage < RAY_STORAGE_BUFFERS
|| limits.max_compute_invocations_per_workgroup < WORKGROUP
|| limits.max_compute_workgroup_size_x < WORKGROUP
|| limits.max_compute_workgroup_storage_size < WORKGROUP_STORAGE_BYTES
{
return Some("has no usable compute shaders");
}
None
}
/// The GPU [`Tracer`]. Its device is created on the first bake; without a hardware adapter
/// every bake reports [`BakeError::Tracer`] (and runs on the CPU).
#[derive(Default)]
@@ -383,6 +412,22 @@ mod tests {
use super::*;
#[test]
fn raytracing_requires_hardware_and_compute_support() {
let limits = wgpu::Limits::default();
let compute = wgpu::DownlevelFlags::COMPUTE_SHADERS;
let no_compute = wgpu::Limits { max_compute_workgroup_size_x: 0, ..limits.clone() };
let three_buffers = wgpu::Limits { max_storage_buffers_per_shader_stage: 3, ..limits.clone() };
let no_shared_memory = wgpu::Limits { max_compute_workgroup_storage_size: 0, ..limits.clone() };
assert!(unsupported_adapter(wgpu::DeviceType::DiscreteGpu, compute, &limits).is_none());
assert!(unsupported_adapter(wgpu::DeviceType::Cpu, compute, &limits).is_some());
assert!(unsupported_adapter(wgpu::DeviceType::IntegratedGpu, wgpu::DownlevelFlags::empty(), &limits).is_some());
assert!(unsupported_adapter(wgpu::DeviceType::IntegratedGpu, compute, &no_compute).is_some());
assert!(unsupported_adapter(wgpu::DeviceType::IntegratedGpu, compute, &three_buffers).is_some(), "the bind group requires four storage buffers");
assert!(unsupported_adapter(wgpu::DeviceType::IntegratedGpu, compute, &no_shared_memory).is_some());
}
/// The GPU baker, or None (test skipped) without a hardware adapter.
fn gpu() -> Option<GpuBaker> {
let g = GpuBaker::new();
+37 -21
View File
@@ -100,6 +100,7 @@ struct GlobalsRaw {
refr: [f32; 4],
highlight: [f32; 4],
highlight_shift: [f32; 4],
set_hover: [f32; 4],
bake_high: [f32; 4],
bake_matching_error: [f32; 4],
bake_cage: [f32; 4],
@@ -137,6 +138,9 @@ const HIGHLIGHT_WIDTH_PX: f32 = 1.5;
/// Opacity of the highlighted set's edge lines
const HIGHLIGHT_OPACITY: f32 = 0.9;
/// Opacity of the texture-set hover tint over the shaded material.
const SET_HOVER_OPACITY: f32 = 0.35;
/// Copies of each highlight line, shifted diagonally to the four corners of its extra width (`vs_wire_highlight`)
const HIGHLIGHT_SHIFTS: u32 = 4;
@@ -194,6 +198,8 @@ pub struct Shade {
pub wireframe_opacity: f32,
/// One texture set's mesh edges in a highlight color over the 3D view (the set under a shelf drag)
pub highlight: Option<SetHighlight>,
/// The texture set whose visible surfaces are tinted in the 3D view.
pub set_hover: Option<SetHighlight>,
/// Specular/glossiness shading: base color is the diffuse color and the Specular channel the
/// F0 color (roughness arrives as 1 - glossiness from the display conversion).
pub spec_gloss: bool,
@@ -308,6 +314,7 @@ impl Default for Shade {
wireframe_3d: false,
wireframe_opacity: 0.4,
highlight: None,
set_hover: None,
spec_gloss: false,
parallax: false,
taa: false,
@@ -1941,8 +1948,8 @@ impl Renderer {
ranges: &'a [(u32, u32, usize)],
visible: &'a [bool],
only: Option<usize>,
) -> impl Iterator<Item = (std::ops::Range<u32>, &'a SetGpu)> + 'a {
drawable_ranges(ranges, &self.material_sets, visible, only).filter_map(|(range, ts)| Some((range, self.sets.get(ts)?)))
) -> impl Iterator<Item = (std::ops::Range<u32>, usize, &'a SetGpu)> + 'a {
drawable_ranges(ranges, &self.material_sets, visible, only).filter_map(|(range, texture_set)| Some((range, texture_set, self.sets.get(texture_set)?)))
}
/// Keep the key-light shadow map current; returns its view-projection. `light` points to
@@ -2003,7 +2010,7 @@ impl Renderer {
let geo = m.dense.as_ref().filter(|_| displacing).unwrap_or(&m.geo);
pass.set_vertex_buffer(0, geo.vb.slice(..));
pass.set_index_buffer(geo.ib.slice(..), wgpu::IndexFormat::Uint32);
for (range, set) in self.drawable(&geo.draws, visible, None) {
for (range, _, set) in self.drawable(&geo.draws, visible, None) {
pass.set_bind_group(1, &set.bind_group, &[]);
pass.draw_indexed(range, 0, 0..1);
}
@@ -2125,8 +2132,9 @@ impl Renderer {
fwd: [fwd.x, fwd.y, fwd.z, 0.0],
disp,
refr: [if refraction { 1.0 } else { 0.0 }, (BEHIND_LEVELS - 1) as f32, REFRACTION_DEPTH * radius, 0.0],
highlight: highlight_globals(s, data),
highlight: highlight_globals(s.highlight, HIGHLIGHT_OPACITY, s, data),
highlight_shift: highlight_shift(frame.size),
set_hover: highlight_globals(s.set_hover, SET_HOVER_OPACITY, s, data),
..bake_globals(s.bake)
};
let flag = |b: bool| if b { 1.0 } else { 0.0 };
@@ -2135,11 +2143,12 @@ impl Renderer {
b: [fx(s.vignette), fx(s.sharpen), fx(s.grain), BLOOM_THRESHOLD],
c: dof_c,
d: sss_d,
e: [flag(cam.ortho), sample as f32, 0.0, 0.0],
e: [flag(cam.ortho), sample as f32, raw.set_hover[3], 0.0],
back_top: [s.background[0][0], s.background[0][1], s.background[0][2], 0.0],
back_bottom: [s.background[1][0], s.background[1][1], s.background[1][2], 0.0],
};
let Some(v) = self.targets(device, frame.view_id, frame.size, bloom, fx_on, refraction) else { return };
queue.write_buffer(&v.globals, 0, bytemuck::bytes_of(&raw));
queue.write_buffer(&v.post_buf, 0, bytemuck::bytes_of(&post));
upload_overlay(device, queue, v, &frame.overlay, (!data).then_some(s.exposure_ev));
@@ -2214,9 +2223,13 @@ impl Renderer {
let geo = self.geometry(m, frame);
pass.set_vertex_buffer(0, geo.vb.slice(..));
pass.set_index_buffer(geo.ib.slice(..), wgpu::IndexFormat::Uint32);
for (range, set) in self.drawable(&geo.draws, &frame.visible, None) {
// Instance index 1 lets the G-buffer mark the hovered set for the scattering composite
let hover_set = frame.shade.set_hover.filter(|_| frame.kind == ViewKind::Scene).map(|hover| hover.set);
for (range, texture_set, set) in self.drawable(&geo.draws, &frame.visible, None) {
pass.set_bind_group(1, &set.bind_group, &[]);
pass.draw_indexed(range, 0, 0..1);
let first_instance = u32::from(hover_set == Some(texture_set));
pass.draw_indexed(range, 0, first_instance..first_instance + 1);
}
}
@@ -2341,22 +2354,25 @@ impl Renderer {
let bake = frame.shade.bake.filter(|_| uv_set.is_none());
let low_poly_shown = bake.is_none_or(|bake| bake.low_poly.shown);
let (highlight, highlight_set) = highlight.filter(|(_, set)| low_poly_shown && uv_set.is_none_or(|only| only == *set)).unzip();
let hover_set = frame.shade.set_hover.filter(|_| uv_set.is_none()).map(|hover| hover.set);
// The wireframe and the highlight draw the mesh's own edges (displaced in the vertex shader too)
let passes = [
(low_poly_shown.then_some(mesh_pipeline), &geometry.vb, &geometry.ib, &geometry.draws, uv_set, 1),
(wire.filter(|_| low_poly_shown), &mesh.geo.vb, &mesh.lines, &mesh.line_draws, uv_set, 1),
(highlight, &mesh.geo.vb, &mesh.lines, &mesh.line_draws, highlight_set, HIGHLIGHT_SHIFTS),
(low_poly_shown.then_some(mesh_pipeline), &geometry.vb, &geometry.ib, &geometry.draws, uv_set, 1, hover_set),
(wire.filter(|_| low_poly_shown), &mesh.geo.vb, &mesh.lines, &mesh.line_draws, uv_set, 1, None),
(highlight, &mesh.geo.vb, &mesh.lines, &mesh.line_draws, highlight_set, HIGHLIGHT_SHIFTS, None),
];
for (pipeline, vertices, indices, ranges, only_set, instances) in passes {
for (pipeline, vertices, indices, ranges, only_set, instances, hover_set) in passes {
let Some(pipeline) = pipeline else { continue };
pass.set_pipeline(pipeline);
pass.set_vertex_buffer(0, vertices.slice(..));
pass.set_index_buffer(indices.slice(..), wgpu::IndexFormat::Uint32);
for (range, set) in self.drawable(ranges, &frame.visible, only_set) {
for (range, texture_set, set) in self.drawable(ranges, &frame.visible, only_set) {
// Instance index 1 lets the mesh shader tint the hovered draw
let first_instance = u32::from(hover_set == Some(texture_set));
pass.set_bind_group(1, &set.bind_group, &[]);
pass.draw_indexed(range, 0, 0..instances);
pass.draw_indexed(range, 0, first_instance..first_instance + instances);
}
}
@@ -2370,7 +2386,7 @@ impl Renderer {
pass.set_pipeline(&self.uv_missing_seam_pipeline);
pass.set_vertex_buffer(0, mesh.geo.vb.slice(..));
pass.set_index_buffer(seams.lines.slice(..), wgpu::IndexFormat::Uint32);
for (range, set) in self.drawable(&seams.line_draws, &frame.visible, Some(texture_set)) {
for (range, _, set) in self.drawable(&seams.line_draws, &frame.visible, Some(texture_set)) {
pass.set_bind_group(1, &set.bind_group, &[]);
pass.draw_indexed(range, 0, 0..1);
}
@@ -2404,7 +2420,7 @@ impl Renderer {
pass.set_pipeline(&self.missing_seam_pipeline);
pass.set_vertex_buffer(0, low_poly.geo.vb.slice(..));
pass.set_index_buffer(seams.lines.slice(..), wgpu::IndexFormat::Uint32);
for (range, set) in self.drawable(&seams.line_draws, &frame.visible, None) {
for (range, _, set) in self.drawable(&seams.line_draws, &frame.visible, None) {
pass.set_bind_group(1, &set.bind_group, &[]);
pass.draw_indexed(range, 0, 0..1);
}
@@ -2541,12 +2557,12 @@ fn upload_overlay(device: &wgpu::Device, queue: &wgpu::Queue, view: &mut ViewTar
}
}
/// Globals `highlight`: the highlight's color and opacity, all zero without one. Data views skip exposure and tone mapping, so they take the color as it is
fn highlight_globals(shade: &Shade, data: bool) -> [f32; 4] {
let Some(highlight) = shade.highlight else { return [0.0; 4] };
/// The highlight's color and opacity. Data views take the color as it is.
fn highlight_globals(highlight: Option<SetHighlight>, opacity: f32, shade: &Shade, data: bool) -> [f32; 4] {
let Some(highlight) = highlight else { return [0.0; 4] };
let [r, g, b] = if data { highlight.color } else { highlight.scene_color(shade.exposure_ev, shade.aces) };
[r, g, b, HIGHLIGHT_OPACITY]
[r, g, b, opacity]
}
/// The globals of bake mode's overlays and neutral material for `bake` (all zero without it)
@@ -2678,8 +2694,8 @@ mod tests {
let color = [0.8, 0.25, 0.08];
let shade = Shade { highlight: Some(SetHighlight { set: 0, color }), exposure_ev: 1.0, ..Shade::default() };
assert_eq!(highlight_globals(&shade, true), [0.8, 0.25, 0.08, HIGHLIGHT_OPACITY]);
assert_ne!(highlight_globals(&shade, false)[..3], color, "the material view undoes exposure and tone mapping");
assert_eq!(highlight_globals(shade.highlight, HIGHLIGHT_OPACITY, &shade, true), [0.8, 0.25, 0.08, HIGHLIGHT_OPACITY]);
assert_ne!(highlight_globals(shade.highlight, HIGHLIGHT_OPACITY, &shade, false)[..3], color, "the material view undoes exposure and tone mapping");
}
#[test]
+4 -4
View File
@@ -1,4 +1,4 @@
//! A texture set's mesh edges drawn over the 3D view in a highlight color (the set under a shelf drag)
//! Texture-set highlighting in the 3D viewport.
/// Brightest on-screen value the tone curve can reach without an infinite scene value
const MAX_ACES_SCREEN_VALUE: f32 = 0.99;
@@ -6,16 +6,16 @@ const MAX_ACES_SCREEN_VALUE: f32 = 0.99;
/// Scene scale the post pass applies before its ACES curve (`aces` in post.wgsl)
const ACES_INPUT_SCALE: f32 = 0.6;
/// Draw texture set `set`'s mesh edges over the 3D view in `color`
/// A texture set to highlight in the 3D viewport.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SetHighlight {
pub set: usize,
/// The lines' color on screen, linear RGB
/// The highlight color on screen, linear RGB.
pub color: [f32; 3],
}
impl SetHighlight {
/// The scene color the lines are drawn with so that exposure `exposure_ev` and the tone curve (ACES when `aces`) show them in [`Self::color`]
/// The scene color that exposure `exposure_ev` and the tone curve (ACES when `aces`) show as [`Self::color`].
pub fn scene_color(&self, exposure_ev: f32, aces: bool) -> [f32; 3] {
scene_color_showing(self.color, exposure_ev, aces)
}
+38 -27
View File
@@ -1,7 +1,6 @@
// Scene effects between the scene pass and the post pass, appended to util.wgsl and post.wgsl
// (uses `src`, `src_samp`, `post`, `fx_a`): the screen-space subsurface blur and depth of field.
// Both read the G-buffer of `fs_gbuf` (mesh.wgsl): rgb the scattering part of the diffuse light,
// a the view depth (0: background). Colors are linear HDR premultiplied by scene coverage.
// Screen-space subsurface blur and depth of field run between the scene and post passes
// G-buffer RGB holds scattering light in linear HDR premultiplied by scene coverage
// G-buffer alpha holds view depth, with zero for background and a negative sign for hover
@group(0) @binding(5) var fx_b: texture_2d<f32>;
@group(0) @binding(6) var fx_c: texture_2d<f32>;
@@ -31,19 +30,22 @@ fn px_per_world(z: f32) -> f32 {
return select(post.d.w / max(z, 1e-4), post.d.w, post.e.x > 0.5);
}
// One direction of the blur over `src` (rgb light, a depth) at pixel `p` (same-size target).
// The blur changes RGB and carries the centre's signed depth unchanged
fn sss_blur(p: vec2<f32>, dir: vec2<f32>) -> vec4<f32> {
let c = texel_at(src, p);
let sigma = post.d.xyz * px_per_world(c.a);
let z = abs(c.a);
let sigma = post.d.xyz * px_per_world(z);
let smax = max(sigma.r, max(sigma.g, sigma.b));
if (c.a <= 0.0 || smax < 0.5) {
if (z <= 0.0 || smax < 0.5) {
return c;
}
let stride = dir * (smax * 3.0 / f32(SSS_TAPS));
let depth_range = 3.0 * max(post.d.x, max(post.d.y, post.d.z));
let inv = 1.0 / (2.0 * sigma * sigma + vec3<f32>(1e-4));
// Wide blurs space their taps pixels apart: shifting them per pixel (interleaved gradient
// noise) and per accumulated frame turns what would show as copies of edges into fine grain.
// Jitter the wide blur taps so copies of edges become fine grain
let ign = fract(52.9829189 * fract(dot(p, vec2<f32>(0.06711056, 0.00583715))));
let jitter = fract(ign + post.e.y * 0.618034) - 0.5;
var sum = c.rgb;
@@ -52,30 +54,35 @@ fn sss_blur(p: vec2<f32>, dir: vec2<f32>) -> vec4<f32> {
if (k == 0) {
continue;
}
let o = f32(k) + jitter;
let t = texel_at(src, p + stride * o);
let x = o * smax * 3.0 / f32(SSS_TAPS);
let wd = select(0.0, max(1.0 - abs(t.a - c.a) / depth_range, 0.0), t.a > 0.0);
let tz = abs(t.a);
let wd = select(0.0, max(1.0 - abs(tz - z) / depth_range, 0.0), tz > 0.0);
let w = exp(-x * x * inv);
sum += mix(c.rgb, t.rgb, wd) * w;
wsum += w;
}
return vec4<f32>(sum / wsum, c.a);
}
// src: the G-buffer.
// Read scattering light and depth from the G-buffer
@fragment
fn fs_sss_h(i: FsOut) -> @location(0) vec4<f32> {
return sss_blur(i.pos.xy, vec2<f32>(1.0, 0.0));
}
// src: the horizontal pass, fx_a: the scene (without its scattering light, see `fs_mesh`). Adds
// the blurred scattering light.
// Restore scattering light from the horizontal pass to the main scene in fx_a
// Apply hover opacity at the destination so neighbouring sets keep the light they receive
@fragment
fn fs_sss_v(i: FsOut) -> @location(0) vec4<f32> {
let blurred = sss_blur(i.pos.xy, vec2<f32>(0.0, 1.0)).rgb;
let blurred = sss_blur(i.pos.xy, vec2<f32>(0.0, 1.0));
let scene = texel_at(fx_a, i.pos.xy);
return scene + vec4<f32>(blurred * clamp(scene.a, 0.0, 1.0), 0.0);
let scattering_weight = select(1.0, 1.0 - post.e.z, blurred.a < 0.0);
return scene + vec4<f32>(blurred.rgb * scattering_weight * clamp(scene.a, 0.0, 1.0), 0.0);
}
// ---- Depth of field: a thin lens. Scatter-as-gather over a golden-angle spiral at half
@@ -103,27 +110,28 @@ struct DofOut {
@location(1) near: vec4<f32>,
};
// src: the scene (full resolution), fx_a: the G-buffer.
// Read full-resolution scene colors from src and depths from fx_a
@fragment
fn fs_dof_gather(i: FsOut) -> DofOut {
let px = 1.0 / vec2<f32>(textureDimensions(src));
let zc = texel(fx_a, i.uv).a;
let zc = abs(texel(fx_a, i.uv).a);
let cc = abs(coc(zc));
let rmax = post.c.z;
// Half the spacing of the taps: the soft edge of each tap's reach.
// Half the spacing of the taps softens the edge of each tap's reach
let h = max(rmax * sqrt(PI_FX / f32(DOF_TAPS)) * 0.5, 0.5);
var acc = textureSampleLevel(src, src_samp, i.uv, 0.0);
var tot = 1.0;
var near = 0.0;
// The spiral turns per pixel (interleaved gradient noise) and per accumulated frame, so the
// taps' pattern averages into smooth discs instead of showing as dots in bright highlights.
// Rotate the taps per pixel and frame so bright highlights average into smooth discs
let ign = fract(52.9829189 * fract(dot(i.pos.xy, vec2<f32>(0.06711056, 0.00583715))));
let turn = (ign + post.c.w * 0.618034) * 6.2831853;
for (var k = 0; k < DOF_TAPS; k++) {
let r = rmax * sqrt((f32(k) + 0.5) / f32(DOF_TAPS));
let a = f32(k) * GOLDEN_ANGLE + turn;
let uv = i.uv + vec2<f32>(cos(a), sin(a)) * (r * px);
let z = texel(fx_a, uv).a;
let z = abs(texel(fx_a, uv).a);
let nearer = z > 0.0 && (zc <= 0.0 || z < zc);
var size = abs(coc(z));
if (!nearer) {
@@ -136,20 +144,23 @@ fn fs_dof_gather(i: FsOut) -> DofOut {
near = max(near, m * smoothstep(0.5, 1.5, size));
}
}
return DofOut(acc / tot, vec4<f32>(near));
}
const PI_FX: f32 = 3.14159265;
// src: the sharp scene, fx_a: the gathered blur, fx_b: the G-buffer, fx_c: the near coverage.
// Use G-buffer depth and near coverage to blend the half-resolution blur into the scene
@fragment
fn fs_dof(i: FsOut) -> @location(0) vec4<f32> {
let sharp = texel_at(src, i.pos.xy);
let f = max(smoothstep(0.5, 1.5, abs(coc(texel_at(fx_b, i.pos.xy).a))), textureSampleLevel(fx_c, src_samp, i.uv, 0.0).r);
// In focus with nothing blurred in front: the sharp pixel itself (no blend through the
// half-resolution blur at all).
if (f <= 0.0) {
let depth = abs(texel_at(fx_b, i.pos.xy).a);
let blur_weight = max(smoothstep(0.5, 1.5, abs(coc(depth))), textureSampleLevel(fx_c, src_samp, i.uv, 0.0).r);
// Preserve the full-resolution pixel where no blur reaches it
if (blur_weight <= 0.0) {
return sharp;
}
return mix(sharp, textureSampleLevel(fx_a, src_samp, i.uv, 0.0), f);
return mix(sharp, textureSampleLevel(fx_a, src_samp, i.uv, 0.0), blur_weight);
}
+25 -6
View File
@@ -26,6 +26,7 @@ struct Globals {
refr: vec4<f32>, // x screen-space refraction on (1), y lods of the scene behind, z refraction depth (world units), w -
highlight: vec4<f32>, // rgb highlighted set's edge color in the scene (before exposure and tone mapping), a opacity
highlight_shift: vec4<f32>, // xy sideways shift of each highlight line copy (clip units), zw -
set_hover: vec4<f32>, // rgb hovered set's scene color, a opacity
bake_high: vec4<f32>, // bake mode: rgb high poly color, a -
bake_matching_error: vec4<f32>, // rgb color where the bake's rays miss the high poly, a its strength (0 hidden)
bake_cage: vec4<f32>, // rgb cage surface color, a opacity
@@ -70,6 +71,7 @@ struct VOut {
@location(1) nrm: vec3<f32>,
@location(2) tan: vec4<f32>,
@location(3) uv: vec2<f32>,
@location(4) @interpolate(flat) hover: u32,
};
// The vertex moved along its normal by the height channel (displacement).
@@ -81,7 +83,7 @@ fn displaced(v: VIn) -> vec3<f32> {
}
@vertex
fn vs_mesh(v: VIn) -> VOut {
fn vs_mesh(v: VIn, @builtin(instance_index) instance_index: u32) -> VOut {
var o: VOut;
let p = displaced(v);
o.clip = g.view_proj * vec4<f32>(p, 1.0);
@@ -89,6 +91,7 @@ fn vs_mesh(v: VIn) -> VOut {
o.nrm = v.nrm;
o.tan = v.tan;
o.uv = v.uv;
o.hover = instance_index;
return o;
}
@@ -350,16 +353,26 @@ fn unlit(c: vec4<f32>) -> Shaded {
fn mesh_color(i: VOut, front: bool) -> vec4<f32> {
let o = shade_mesh(i, front);
// The subsurface pass restores the scattering light after blurring
if (g.scatter.w > 0.5) {
// The subsurface blur pass adds the scattering light back, blurred (fx.wgsl).
return o.color - vec4<f32>(o.sss, 0.0);
}
return o.color;
}
const HOVERED_SET_INSTANCE: u32 = 1u;
@fragment
fn fs_mesh(i: VOut, @builtin(front_facing) front: bool) -> @location(0) vec4<f32> {
return mesh_color(i, front);
let color = mesh_color(i, front);
if (i.hover == HOVERED_SET_INSTANCE) {
return vec4<f32>(mix(color.rgb, g.set_hover.rgb * color.a, g.set_hover.a), color.a);
}
return color;
}
// The scene behind transmissive surfaces: everything but them (what they refract).
@@ -373,17 +386,23 @@ fn fs_opaque(i: VOut, @builtin(front_facing) front: bool) -> @location(0) vec4<f
return c;
}
// The depth of field / subsurface G-buffer: rgb the scattering diffuse light (when the blur is
// on), a the view depth (the clear value 0 marks the background).
// G-buffer RGB holds scattering light and alpha holds view depth
// Zero depth marks the background
// Negative depth marks the hovered set when subsurface blur is active
@fragment
fn fs_gbuf(i: VOut, @builtin(front_facing) front: bool) -> @location(0) vec4<f32> {
let z = max(dot(i.wpos - g.eye.xyz, g.fwd.xyz), 1e-4);
var z = max(dot(i.wpos - g.eye.xyz, g.fwd.xyz), 1e-4);
var sss = vec3<f32>(0.0);
if (g.scatter.w > 0.5) {
sss = shade_mesh(i, front).sss;
if (i.hover == HOVERED_SET_INSTANCE) {
z = -z;
}
} else if (textureSample(t_base, samp, i.uv).a < hash12(i.clip.xy)) {
discard;
}
return vec4<f32>(sss, z);
}
+1 -1
View File
@@ -7,7 +7,7 @@ struct Post {
b: vec4<f32>, // x vignette, y sharpen, z grain, w bloom threshold
c: vec4<f32>, // depth of field (fx.wgsl): x circle of confusion at infinity (pixels), y focus depth, z largest circle radius (pixels), w accumulation sample
d: vec4<f32>, // subsurface blur (fx.wgsl): xyz mean free path per channel (world units), w pixels per world unit at depth 1
e: vec4<f32>, // x orthographic camera (1: pixels per world unit don't fall off with depth), y accumulation sample, zw -
e: vec4<f32>, // x orthographic camera, y accumulation sample, z hover tint opacity for the scattering composite, w -
back_top: vec4<f32>, // rgb background color at the top of the view (linear), a -
back_bottom: vec4<f32>, // rgb background color at the bottom of the view (linear), a -
};
+52
View File
@@ -1076,6 +1076,58 @@ fn subsurface_blur_spreads_only_scattering_light() {
assert!((m1 - m0).abs() < 2.0, "the blur moves light, it adds none: {m0} -> {m1}");
}
#[test]
fn the_hover_tint_covers_the_blurred_scattering_light_too() {
let Some((mut h, frame)) = setup() else { return };
// Read coverage in the flat base-color view so lighting cannot hide a set at its edge
let base_color_view = shaded(&frame, |shade| shade.view_mode = 1);
let hovered_set_mask = mesh_mask(&mut h, &base_color_view, &[0]);
let neighbour_mask = mesh_mask(&mut h, &base_color_view, &[1]);
let lit = shaded(&frame, |s| s.light = LIGHT);
fill(&mut h, &[0, 1], DisplayKind::BaseColor, &[150, 150, 150, 255]);
fill(&mut h, &[0, 1], DisplayKind::Emissive, &[0, 0, 0, 255]);
let blur = shaded(&lit, |s| s.sss_blur = Some([0.06, 0.024, 0.015]));
let hover = |frame: &Frame| shaded(frame, |s| s.set_hover = Some(texturecraft_render::SetHighlight { set: 0, color: [1.0, 0.5, 0.0] }));
let mean = |img: &Img| region_mean(&hovered_set_mask, |x, y| img.luma(x, y));
let plain = mean(&render(&mut h, &lit, "hover_sss_plain"));
let blurred = mean(&render(&mut h, &blur, "hover_sss_blur"));
let hovered_blur = mean(&render(&mut h, &hover(&blur), "hover_sss_blur_hovered"));
let hovered_plain = mean(&render(&mut h, &hover(&lit), "hover_sss_plain_hovered"));
assert!(hovered_plain != plain, "the hover tint changes the set");
// Hover must dim the light restored by the blur along with the rest of the material
assert!(
((hovered_blur - hovered_plain) - (blurred - plain)).abs() < 1.0,
"the blur changes the plain set by {} and the hovered set by {}",
blurred - plain,
hovered_blur - hovered_plain
);
// Use a wide blur so scattering light crosses the boundary between the two sets
let wide = shaded(&lit, |s| s.sss_blur = Some([0.2, 0.08, 0.05]));
let blurred_img = render(&mut h, &wide, "hover_sss_wide");
let hovered_blur_img = render(&mut h, &hover(&wide), "hover_sss_wide_hovered");
// Skip pixels that legitimately include samples of the hovered set after MSAA resolve
let width = blurred_img.w;
let mut checked = 0;
let mut worst_delta = 0.0f32;
for (index, &neighbour) in neighbour_mask.iter().enumerate() {
if neighbour && !hovered_set_mask[index] {
let (x, y) = (index as u32 % width, index as u32 / width);
let delta = (hovered_blur_img.luma(x, y) - blurred_img.luma(x, y)).abs();
checked += 1;
worst_delta = worst_delta.max(delta);
}
}
assert!(checked > 0, "the neighbour has pixels with no coverage from the hovered set");
assert!(worst_delta <= 1.0, "hovering set 0 changes the neighbouring set by up to {worst_delta} luma across {checked} pixels");
}
/// An environment that is bright only around `dir` (world space, rotation 0).
fn spot_environment(dir: texturecraft_geom::glam::Vec3) -> ImageRes {
let (w, hh) = (256u32, 128u32);
+3 -3
View File
@@ -15,10 +15,12 @@ texturecraft-render = { workspace = true }
eframe = { workspace = true, features = ["default_fonts", "wgpu", "persistence"] }
egui = { workspace = true }
craft-ui = { workspace = true }
craft-behavior = { workspace = true }
craft-i18n = { workspace = true }
craft-window = { workspace = true }
craft-keymap = { workspace = true }
craft-quit = { workspace = true }
craft-host = { workspace = true }
craft-theme = { workspace = true }
egui-phosphor = { version = "0.14", features = ["regular", "fill"] }
serde = { workspace = true }
serde_json = { workspace = true }
@@ -31,8 +33,6 @@ craft-image-codecs = { workspace = true }
# The OS UI language for the first run (MIT OR Apache-2.0; the browser asks `navigator.language`).
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
sys-locale = "0.3"
# Floating panels open as OS windows.
craft-ui = { workspace = true, features = ["native-windows"] }
# Help > Check for Updates and the check at start (updates_ui.rs).
craft-update = { workspace = true }
# Native file dialogs (file_dialogs.rs); the browser build has none.
+170
View File
@@ -0,0 +1,170 @@
//! Where a project's autosave copy goes. Each project has a file of its own, `<stem>-copy-<suffix>.tcraft`: a project's
//! name comes from its mesh file, so the name alone would let projects made from one mesh overwrite each other's copy
use std::path::{Path, PathBuf};
use texturecraft_engine::core::PROJECT_EXT;
use texturecraft_engine::formats::export::sanitize_file_stem;
use crate::TextureCraftApp;
/// Hex digits of a copy's suffix
const SUFFIX_DIGITS: usize = 16;
/// Between a copy's stem and its suffix, so a user's own file named like `report-20240115` is not taken for a copy
const COPY_MARK: &str = "-copy-";
/// The longest stem kept, so the suffix and the temporary files of a save still fit a file name
const MAX_STEM_CHARS: usize = 170;
impl TextureCraftApp {
/// The open project's autosave file in `folder`. A saved project's copy is named after its file and stays the
/// same across restarts; an unsaved project gets one that no other open project or running instance shares
pub(crate) fn autosave_path(&mut self, folder: &Path) -> PathBuf {
let Some(saved) = self.session.path.as_deref() else {
let project = self.session.project_id;
let suffix = match self.unsaved_autosave_suffix {
Some((owner, suffix)) if owner == project => suffix,
_ => {
let suffix = new_suffix(project);
self.unsaved_autosave_suffix = Some((project, suffix));
suffix
}
};
return folder.join(file_name(&self.session.doc.project.name, suffix));
};
let saved = absolute(Path::new(saved));
// A project opened from its autosave copy keeps writing there, rather than chaining suffixes
if is_copy_in(&saved, &absolute(folder)) {
return saved;
}
let stem = saved.file_stem().map_or_else(|| self.session.doc.project.name.clone(), |stem| stem.to_string_lossy().into_owned());
folder.join(file_name(&stem, hash(saved.as_os_str().as_encoded_bytes())))
}
}
fn file_name(stem: &str, suffix: u64) -> String {
let stem: String = sanitize_file_stem(stem).chars().take(MAX_STEM_CHARS).collect();
format!("{stem}{COPY_MARK}{suffix:0SUFFIX_DIGITS$x}.{PROJECT_EXT}")
}
/// `path` made absolute, as given when that fails
fn absolute(path: &Path) -> PathBuf {
std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf())
}
/// `path` with links and, on Windows, the verbatim prefix resolved so two spellings of one folder compare equal; made absolute when that fails
fn resolved(path: &Path) -> PathBuf {
std::fs::canonicalize(path).unwrap_or_else(|_| absolute(path))
}
/// Whether `path` is an autosave copy of `folder`: a project file there whose name ends in the copy mark and a suffix
fn is_copy_in(path: &Path, folder: &Path) -> bool {
let suffix = path.file_stem().and_then(|stem| stem.to_str()).and_then(|stem| stem.rsplit_once(COPY_MARK)).map(|(_, suffix)| suffix);
path.parent().is_some_and(|parent| resolved(parent) == resolved(folder))
&& path.extension().is_some_and(|extension| extension == PROJECT_EXT)
&& suffix.is_some_and(|suffix| suffix.len() == SUFFIX_DIGITS && suffix.bytes().all(|digit| digit.is_ascii_hexdigit()))
}
/// A suffix for the unsaved project `project`: from this process and the moment, so another instance or a later run
/// takes a different one
fn new_suffix(project: u64) -> u64 {
let now = chrono::Utc::now().timestamp_nanos_opt().unwrap_or_default();
let mut seed = Vec::new();
seed.extend_from_slice(&std::process::id().to_le_bytes());
seed.extend_from_slice(&now.to_le_bytes());
seed.extend_from_slice(&project.to_le_bytes());
hash(&seed)
}
/// 64-bit FNV-1a: the same bytes give the same suffix in every release, which the standard hasher does not promise.
/// Wide enough that two paths are very unlikely to share one
fn hash(bytes: &[u8]) -> u64 {
bytes.iter().fold(0xcbf2_9ce4_8422_2325, |hash, byte| (hash ^ u64::from(*byte)).wrapping_mul(0x0000_0100_0000_01b3))
}
#[cfg(test)]
mod tests {
use texturecraft_engine::Session;
use texturecraft_engine::geom::primitives;
use super::*;
fn project(name: &str) -> Session {
Session::new_project(name, primitives::cube(1.0), "builtin:cube", None, 128).unwrap()
}
fn app(session: Session) -> TextureCraftApp {
TextureCraftApp::new(&eframe::CreationContext::_new_kittest(egui::Context::default()), session)
}
fn name_of(path: &Path) -> &str {
path.file_name().and_then(|name| name.to_str()).unwrap()
}
#[test]
fn unsaved_projects_with_one_name_get_different_copies_that_stay_put() {
let folder = Path::new("autosave");
let mut first = app(project("hero"));
let mut second = app(project("hero"));
let (one, other) = (first.autosave_path(folder), second.autosave_path(folder));
assert_ne!(one, other, "another instance never writes the same file");
assert!(name_of(&one).starts_with("hero-") && name_of(&one).ends_with(".tcraft"), "{one:?}");
assert_eq!(one.parent(), Some(folder));
assert_eq!(first.autosave_path(folder), one, "the next autosave replaces this project's copy");
first.session.switch_to(project("hero"));
assert_ne!(first.autosave_path(folder), one, "a new project of the same name starts its own copy");
}
#[test]
fn a_saved_project_names_its_copy_after_its_file_and_keeps_it_across_restarts() {
let folder = Path::new("autosave");
let copy_of = |saved: &str| {
let mut app = app(project("hero"));
app.session.path = Some(saved.to_string());
app.autosave_path(folder)
};
let first = copy_of("work/Hero_v1.tcraft");
let second = copy_of("work/Hero_v2.tcraft");
let same_name_elsewhere = copy_of("backup/Hero_v1.tcraft");
assert!(name_of(&first).starts_with("Hero_v1-"), "{first:?}");
assert_ne!(first, second);
assert_ne!(first, same_name_elsewhere, "files of one name in two folders keep two copies");
assert_eq!(copy_of("work/Hero_v1.tcraft"), first, "a later run finds the same copy");
}
#[test]
fn a_project_opened_from_its_copy_keeps_writing_to_it() {
let folder = std::env::temp_dir().join("tc-autosave");
let mut app = app(project("hero"));
let copy = app.autosave_path(&folder);
app.session.path = Some(copy.display().to_string());
assert_eq!(app.autosave_path(&folder), copy);
// A file there that is not a copy is the user's own: autosave leaves it alone
let own = folder.join("hero.tcraft");
app.session.path = Some(own.display().to_string());
assert_ne!(app.autosave_path(&folder), own);
let dated = folder.join("hero-20240115.tcraft");
app.session.path = Some(dated.display().to_string());
assert_ne!(app.autosave_path(&folder), dated);
}
#[test]
fn suffixes_have_a_fixed_width_and_long_names_are_cut() {
let narrow = file_name("hero", 1);
let wide = file_name("hero", u64::MAX);
assert_eq!(narrow.len(), wide.len(), "every suffix has the same width");
assert!(file_name(&"a".repeat(500), 1).len() < 200);
}
}
+5 -1
View File
@@ -97,7 +97,11 @@ pub(crate) fn map_settings_shown(app: &TextureCraftApp) -> Option<LivePreviewTar
/// What the preview should show: the map whose settings show, while the preview is on and no real bake runs
fn wanted(app: &TextureCraftApp) -> Option<LivePreviewTarget> {
map_settings_shown(app).filter(|_| app.ui.bake_visualization.map_preview && app.bake.is_none())
if !app.ui.prefs.live_preview_baking || !app.ui.bake_visualization.map_preview || app.bake.is_some() {
return None;
}
map_settings_shown(app)
}
/// A slider dragged in Mesh Map Settings changed a setting: a running drag bake finishes and shows before the newest value bakes, so pictures keep coming while the slider moves
+5 -1
View File
@@ -61,7 +61,7 @@ pub fn texture_sets(app: &mut TextureCraftApp, ui: &mut Ui) {
.collect();
ui.push_id(set_index, |ui| {
ui.horizontal(|ui| {
let row = ui.horizontal(|ui| {
let button_size = ui.spacing().interact_size.y;
if icon_button(ui, if visible { icon::EYE } else { icon::EYE_SLASH }, tr("Show or hide the texture set"), false, button_size).clicked() {
app.run("textureSet.visible", json!({ "ts": set_index }));
@@ -88,6 +88,10 @@ pub fn texture_sets(app: &mut TextureCraftApp, ui: &mut Ui) {
}
});
if ui.is_enabled() && ui.rect_contains_pointer(row.response.rect) {
app.next_hovered_texture_set = Some((app.session.project_id, set_index));
}
if !tiles.is_empty() {
egui::CollapsingHeader::new(format!("{} ({})", tr("UV tiles (UDIM)"), tiles.len())).default_open(true).show(ui, |ui| {
for (tile, override_resolution, enabled) in &tiles {
+14 -2
View File
@@ -9,7 +9,7 @@
//! - `ui.menu.list`: the menu catalog with ids, shortcuts and whether each is live.
//! - `ui.menu.invoke {id}`: behave like a menu click (may open a window; `ui.resetUi` asks first).
//! `{id: "ui.layout.apply", name}` switches to the saved panel layout `name` (an error when there is none).
//! - `ui.reset`: reset the panels and every view setting at once, without the question the menu asks.
//! - `ui.reset`: reset the panels, view settings and interface language at once, without the question the menu asks.
//! - `ui.set {...}`: merge fields into the UI state (e.g. `{"layout":"Only3D"}`).
//! - `viewport.screenshot {view?: "3d"|"2d"}`: PNG of a viewport, base64.
//! - `ui.screenshot`: PNG of the whole window (replies after the next frame).
@@ -111,6 +111,12 @@ fn refresh_draft_preferences(draft: &mut Prefs, previous: &Prefs, current: &Pref
gpu_raytracing,
libraries,
background,
show_world_axes,
show_keyboard_helper,
only_selected_material_when_painting,
save_preprocessed_scene_files,
live_preview_baking,
local_cache_directory,
);
}
@@ -142,6 +148,12 @@ pub fn handle(app: &mut TextureCraftApp, ctx: &egui::Context, method: &str, para
},
"command.run" => {
let Some(id) = params.get("id").and_then(Value::as_str) else { return err("`id` is required") };
#[cfg(not(target_arch = "wasm32"))]
if app.save_job.is_some() && crate::manual_save::is_save(id) {
return err("A manual project save is already running");
}
let command_params = params.get("params").cloned().unwrap_or(Value::Null);
let before = app.session.camera;
match texturecraft_engine::execute(&mut app.session, id, &command_params) {
@@ -249,7 +261,7 @@ pub fn handle(app: &mut TextureCraftApp, ctx: &egui::Context, method: &str, para
// What Window > Reset UI does once the question is answered with Reset
"ui.reset" => {
app.ui.adopt_layout(crate::UiState::default());
app.ui.reset_ui();
ok(Value::Null)
}
"ui.set" => {
+19 -6
View File
@@ -43,7 +43,7 @@ pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) {
0 => import_hdr = environment(app, ui, &mut display),
1 => camera(app, ui, &mut display),
2 => post_effects(ui, &mut display),
3 => render_settings(ui, &mut display),
3 => render_settings(app, ui, &mut display),
_ => visualization(app, ui, &mut display),
});
@@ -57,8 +57,7 @@ pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) {
}
app.session.doc.project.display = display;
app.session.modified = true;
app.session.revision = app.session.revision.wrapping_add(1);
app.session.mark_modified();
}
if import_hdr {
@@ -255,9 +254,19 @@ fn post_effects(ui: &mut Ui, display: &mut DisplaySettings) {
}
}
/// Temporal anti-aliasing
fn render_settings(ui: &mut Ui, display: &mut DisplaySettings) {
/// Temporal anti-aliasing and the viewport texture resolution (an app setting, not the project's)
fn render_settings(app: &mut TextureCraftApp, ui: &mut Ui, display: &mut DisplaySettings) {
ui.checkbox(&mut display.taa, tr("Temporal anti-aliasing (refines the 3D view while it is still)"));
ui.horizontal(|ui| {
ui.label(tr("Texture resolution"));
for (value, label) in [(0_u8, tr("Full")), (1, tr("Half")), (2, tr("Quarter"))] {
ui.selectable_value(&mut app.ui.prefs.viewport_texture, value, label);
}
})
.response
.on_hover_text(tr(
"Size of the textures the viewport shows: lower uses less GPU memory with large texture sets. Painting and export keep full resolution.",
));
}
/// The mesh wireframe and the single-channel views
@@ -287,7 +296,11 @@ mod tests {
fn display_harness() -> Harness<'static, TextureCraftApp> {
let session = texturecraft_engine::sample_session(128, 32).unwrap();
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).with_step_dt(0.01).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut harness = Harness::builder()
.with_size(egui::vec2(1600.0, 1200.0))
.with_step_dt(0.01)
.with_context_setup(crate::framework::install_headless)
.build_eframe(|cc| TextureCraftApp::new(cc, session));
harness.state_mut().ui.prefs.language = "en".into();
harness.state_mut().ui.dock.focus(crate::docking::Panel::Display);
harness.run_steps(4);
+211 -138
View File
@@ -6,7 +6,7 @@ use egui_phosphor::regular as ic;
use serde_json::{Value, json};
use texturecraft_engine::compose::ThumbTarget;
use texturecraft_engine::core::{
BakedMap, BlendMode, Channel, ChannelBlend, Effect, EffectKind, Layer, LayerId, LayerKind, LinkParam, Projection, Sampling, Source,
BakedMap, BlendMode, Channel, ChannelBlend, Effect, EffectKind, Layer, LayerId, LayerKind, LinkParam, Project, Projection, Sampling, Source,
};
use texturecraft_engine::paint::alpha_params::MAX_ALPHA_CONTRAST;
use texturecraft_engine::paint::{BrushAlpha, BrushSettings, alphas};
@@ -78,6 +78,9 @@ pub(crate) fn texture_set_list(app: &mut TextureCraftApp, ui: &mut Ui) {
egui::ScrollArea::vertical().id_salt("ts_scroll").show(ui, |ui| {
for (i, (name, size, visible)) in sets.into_iter().enumerate() {
let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click());
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ListItem, ui.is_enabled(), &name));
ui.ctx().accesskit_node_builder(resp.id, |node| node.set_selected(i == active));
let p = ui.painter();
let bg = if i == active {
tk.row_selected
@@ -90,10 +93,18 @@ pub(crate) fn texture_set_list(app: &mut TextureCraftApp, ui: &mut Ui) {
if i == active {
p.rect_stroke(rect, 2.0, Stroke::new(1.0, tk.accent), egui::StrokeKind::Inside);
}
if resp.has_focus() {
p.rect_stroke(rect.shrink(2.0), 2.0, Stroke::new(1.0, tk.text_strong), egui::StrokeKind::Inside);
}
let eye = Rect::from_min_size(rect.min + vec2(4.0, 3.0), vec2(16.0, 16.0));
let eye_resp = ui.interact(eye, ui.scope_id().with(("ts_eye", i)), Sense::click()).on_hover_text(tr("Show or hide the texture set"));
p.text(eye.center(), egui::Align2::CENTER_CENTER, if visible { ic::EYE } else { ic::EYE_SLASH }, egui::FontId::proportional(13.0), tk.text);
if ui.is_enabled() && (resp.contains_pointer() || eye_resp.contains_pointer()) {
app.next_hovered_texture_set = Some((app.session.project_id, i));
}
// Narrow panels drop the shader label, then the resolution, before cutting the name
let cy = rect.center().y;
let mut right = rect.right() - 6.0;
@@ -146,6 +157,13 @@ pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) {
app.session.doc.project.texture_sets.get(set).map(|texture_set| texture_set.stack.iter().rev().copied().collect()).unwrap_or_default();
let now = ui.input(|input| input.time);
app.layer_panel.begin(&app.session, now);
let selected_stack = app.session.selected_layer().map(|layer| (layer, !targets_content(app)));
if matches!(app.session.target, StackTarget::Effect(_)) {
app.layer_panel.expanded_effects = selected_stack;
} else if app.layer_panel.expanded_effects != selected_stack {
app.layer_panel.expanded_effects = None;
}
egui::ScrollArea::vertical().id_salt("layers_scroll").auto_shrink([false, false]).show(ui, |ui| {
let mut count = 0;
for id in stack {
@@ -181,12 +199,30 @@ pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) {
select_all_layers(app, ui);
}
/// Close the name editor when its effect leaves the open stack, even while the panel is hidden.
pub(crate) fn finish_hidden_effect_rename(app: &mut TextureCraftApp) {
if let Some((id, _)) = &app.ui.rename
&& !app.session.doc.project.layers.contains_key(&LayerId(*id))
&& app.layer_panel.expanded_effects.is_none_or(|(layer, in_mask)| {
let project = &app.session.doc.project;
let effects = if in_mask {
mask_effects(project, layer)
} else {
project.layers.get(&layer).map(|layer| layer.content_effects.as_slice()).unwrap_or_default()
};
!effects.iter().any(|effect| effect.id.0 == *id)
})
{
finish_effect_rename(app);
}
}
/// Ctrl+A (Cmd+A on macOS) with the pointer over the Layers panel selects every row shown in the
/// active texture set (folder rows and the layers of open folders). A focused text field (a
/// rename, a number field) keeps the key for itself, and the key is left alone over other panels.
fn select_all_layers(app: &mut TextureCraftApp, ui: &Ui) {
let ctx = ui.ctx();
if ctx.egui_wants_keyboard_input() || !ui.ui_contains_pointer() {
if crate::framework::widget_has_keyboard(ctx) || !ui.ui_contains_pointer() {
return;
}
@@ -275,6 +311,9 @@ const THUMBNAIL_ROUNDING: f32 = 2.0;
const THUMBNAIL_BORDER_WIDTH: f32 = 1.0;
const HIDDEN_STRIKE_WIDTH: f32 = 1.5;
const DROP_LINE_WIDTH: f32 = 2.0;
/// The effect disclosure's square and glyph sizes in points.
const EFFECT_DISCLOSURE_SIZE: f32 = 13.0;
const EFFECT_DISCLOSURE_FONT_SIZE: f32 = 10.0;
/// The eye's size and the column it sits in (the eye and a gap before the thumbnail).
const EYE_SIZE: f32 = 16.0;
const EYE_COLUMN_WIDTH: f32 = 22.0;
@@ -333,15 +372,6 @@ const EFFECT_ROW_SHADES: [f32; 2] = [0.2, 0.5];
/// Width of the blend mode and opacity pair at the right of an effect row (a gap between them), and of its opacity part.
const EFFECT_BLEND_WIDTH: f32 = 82.0;
const EFFECT_OPACITY_WIDTH: f32 = 36.0;
/// Height of the "Content effects" / "Mask effects" header rows.
const GROUP_HEADER_H: f32 = 20.0;
// Group header spacing leaves room for the label and effect count
const GROUP_HEADER_CARET_OFFSET: f32 = 15.0;
const GROUP_HEADER_LABEL_GAP: f32 = 10.0;
const GROUP_HEADER_LABEL_RESERVE: f32 = 28.0;
const GROUP_HEADER_COUNT_PADDING: f32 = 8.0;
const GROUP_HEADER_LABEL_FONT_SIZE: f32 = 10.5;
/// Hover tint of alternating layer rows
const ALTERNATE_LAYER_SHADE: f32 = 0.45;
/// Maximum layer-tree nesting shown by the dock
@@ -351,8 +381,6 @@ const MAX_LAYER_TREE_DEPTH: usize = 12;
const DROP_STROKE: f32 = 2.0;
/// Checkerboard cells along each thumbnail edge
const THUMB_CHECKER_CELLS: usize = 4;
/// Keep the group label and count readable when the panel is narrow
const GROUP_HEADER_MIN_REMAINING_WIDTH: f32 = 90.0;
/// Keep both thumbnail targets inside the row before spending space on indentation
fn layer_thumbnail_layout(width: f32, depth: usize, folder: bool, preferred_size: f32) -> (f32, f32) {
@@ -371,11 +399,6 @@ fn layer_name_layout(rect: Rect, left: f32) -> (Rect, bool) {
(Rect::from_min_max(pos2(left, rect.top() + 4.0), pos2(name_right.max(left), rect.bottom() - 4.0)), show_blend)
}
/// Whether `text` at font `size` is wider than `width`, so a row shows it shortened.
fn text_is_cut(painter: &egui::Painter, text: &str, size: f32, width: f32) -> bool {
painter.layout_no_wrap(text.to_owned(), egui::FontId::proportional(size), Color32::WHITE).size().x > width
}
/// Preserve the effect eye, preview and a readable name before spending space on nesting.
fn effect_row_indent(width: f32, level: usize, preview: f32) -> f32 {
(level as f32 * INDENT).min((width - ROW_LEFT_PADDING - EYE_COLUMN_WIDTH - preview - THUMBNAIL_GAP - MIN_NAME_WIDTH - ROW_RIGHT_PADDING).max(0.0))
@@ -386,18 +409,33 @@ fn level_x(left: f32, level: usize) -> f32 {
left + ROW_LEFT_PADDING + level as f32 * INDENT + EYE_SIZE * 0.5
}
/// The effects of the mask the layer draws with, including a mask inherited from its source.
fn mask_effects(project: &Project, layer: LayerId) -> &[Effect] {
project.layers.get(&project.mask_owner(layer)).and_then(|owner| owner.mask.as_ref()).map_or(&[], |mask| mask.effects.as_slice())
}
fn layer_tree(app: &mut TextureCraftApp, ui: &mut Ui, id: LayerId, depth: usize, count: &mut usize) {
let Some(layer) = app.session.doc.project.layers.get(&id).cloned() else { return };
let index = *count;
*count += 1;
layer_row(app, ui, &layer, depth, index);
let mask_effects = layer.mask.as_ref().map_or(0, |mask| mask.effects.len());
if !layer.content_effects.is_empty() {
effect_group(app, ui, &layer, depth, false, mask_effects > 0);
}
if mask_effects > 0 {
effect_group(app, ui, &layer, depth, true, false);
if let Some((open_layer, in_mask)) = app.layer_panel.expanded_effects
&& open_layer == id
{
// Read the mask after the layer row has handled its controls
let mask_snapshot;
let stack: &[Effect] = if in_mask {
mask_snapshot = mask_effects(&app.session.doc.project, id).to_vec();
&mask_snapshot
} else {
&layer.content_effects
};
for (index, effect) in stack.iter().rev().enumerate() {
effect_row(app, ui, &layer, stack, effect, index, depth + 2, index + 1 == stack.len(), in_mask);
}
}
// A line under the layer and its effects separates it from the next layer
@@ -414,13 +452,17 @@ fn layer_tree(app: &mut TextureCraftApp, ui: &mut Ui, id: LayerId, depth: usize,
}
}
/// The picture for `target` inside `rect` (drawn over the well), whether there is one yet.
fn thumb_box(ui: &Ui, app: &mut TextureCraftApp, rect: Rect, target: ThumbTarget, dim: bool) -> bool {
/// Draw a visible thumbnail over its well, using the fallback until its picture arrives.
fn draw_thumbnail(ui: &Ui, app: &mut TextureCraftApp, rect: Rect, target: ThumbTarget, dim: bool, fallback: impl FnOnce()) {
if !ui.is_rect_visible(rect) {
return;
}
let tokens = Tokens::get(ui.ctx());
let painter = ui.painter();
painter.rect_filled(rect, THUMBNAIL_ROUNDING, tokens.field);
// A checkerboard shows through where the layer has nothing (transparent texels).
// The checkerboard shows through transparent texels
let cell_size = rect.width() / THUMB_CHECKER_CELLS as f32;
let check = tokens.field.lerp_to_gamma(tokens.row_hover, 0.6);
for y in 0..THUMB_CHECKER_CELLS {
@@ -429,16 +471,12 @@ fn thumb_box(ui: &Ui, app: &mut TextureCraftApp, rect: Rect, target: ThumbTarget
}
}
// Only rows on screen ask for a picture.
if ui.is_rect_visible(rect)
&& let Some(texture) = app.layer_panel.texture(ui.ctx(), &app.session, target)
{
if let Some(texture) = app.layer_panel.texture(ui.ctx(), &app.session, target) {
let tint = if dim { Color32::WHITE.gamma_multiply(0.4) } else { Color32::WHITE };
painter.image(texture, rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), tint);
return true;
} else {
fallback();
}
false
}
/// The row of `layer` at folder depth `depth`, the `index`th row of the stack (rows alternate shades).
@@ -451,10 +489,10 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize
let content_target = selected && targets_content(app);
let preferred_size = layer_preview_size(app);
let row_height = layer_row_height(preferred_size);
let (rect, row) = ui.allocate_exact_size(vec2(ui.available_width(), row_height), Sense::click_and_drag());
let (_, rect) = ui.allocate_space(vec2(ui.available_width(), row_height));
let row = ui.interact(rect, ui.scope_id().with(("layer_row", layer.id.0)), Sense::click_and_drag());
row.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, highlighted, &layer.name));
// Background, folder lines, the selected rows' accent edge and the colour tag
let painter = ui.painter().clone();
// The active layer gets the strong tint; the other selected rows the plain selected shade
@@ -494,7 +532,6 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize
painter.rect_stroke(rect.shrink(SOLO_OUTLINE_WIDTH * 0.5), 0.0, Stroke::new(SOLO_OUTLINE_WIDTH, tokens.warning), egui::StrokeKind::Inside);
}
// The eye
let content_left = rect.left() + ROW_LEFT_PADDING + indent;
let eye = Rect::from_center_size(pos2(content_left + EYE_SIZE * 0.5, rect.center().y), vec2(LAYER_EYE_SIZE, LAYER_EYE_SIZE));
let eye_response = ui.interact(eye, ui.scope_id().with(("eye", layer.id.0)), Sense::click()).on_hover_ui(|ui| {
@@ -547,17 +584,30 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize
// Content thumbnail: the layer's own result in the displayed channel
let channel = app.ui.layer_channel;
let thumbnail = Rect::from_min_size(pos2(x, rect.center().y - thumbnail_size * 0.5), vec2(thumbnail_size, thumbnail_size));
if !thumb_box(ui, app, thumbnail, ThumbTarget::Content { layer: layer.id, channel }, !layer.visible) {
content_glyph(&painter, &tokens, thumbnail, layer);
}
draw_thumbnail(ui, app, thumbnail, ThumbTarget::Content { layer: layer.id, channel }, !layer.visible, || {
content_glyph(&painter, &tokens, thumbnail, layer)
});
let content_label = tr("Select the layer content");
let content_response = ui.interact(thumbnail, ui.scope_id().with(("content", layer.id.0)), Sense::click()).on_hover_text(content_label);
painter.rect_stroke(thumbnail, THUMBNAIL_ROUNDING, target_stroke(&tokens, content_target), egui::StrokeKind::Outside);
let content_stack = (!layer.content_effects.is_empty()).then_some((layer.id, false));
if content_response.clicked() {
let modifiers = ui.input(|input| input.modifiers);
click_layer(app, modifiers, layer.id.0, Some("content"));
if !modifiers.shift && !modifiers.command {
app.layer_panel.toggle_effects(content_stack);
}
if !modifiers.alt && matches!(app.session.view, texturecraft_engine::ViewMode::Mask(_)) {
app.run("viewport.view", json!({"mode": "material"}));
}
}
thumbnail_context_menu(ui, &content_response, content_label, &layer.name, content_target, |ui| layer_context_menu(app, ui, layer, true));
effect_stack_thumbnail(app, &painter, &tokens, &content_response, content_stack);
x = thumbnail.right() + THUMBNAIL_SPACING;
// An instance draws its source's content, blending and (unless it has its own) mask
@@ -574,10 +624,33 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize
// Mask thumbnail, selectable on its own; or the slot that adds one
let mask_rect;
if let Some((mask_enabled, mask_background, mask_effect_count)) = mask {
if let Some((mut mask_enabled, mask_background, mask_effect_count)) = mask {
let mask_target = selected && !targets_content(app);
mask_rect = Rect::from_min_size(pos2(x, rect.center().y - thumbnail_size * 0.5), vec2(thumbnail_size, thumbnail_size));
if !thumb_box(ui, app, mask_rect, ThumbTarget::Mask { layer: layer.id }, !layer.visible || !mask_enabled) {
let mask_label = tr("Select the mask (Alt+click: show it in the viewport, Shift+click: switch it on or off)");
let mask_response = ui.interact(mask_rect, ui.scope_id().with(("mask", layer.id.0)), Sense::click()).on_hover_text(mask_label);
let mask_stack = (mask_effect_count > 0).then_some((layer.id, true));
if mask_response.clicked() {
let modifiers = ui.input(|input| input.modifiers);
if modifiers.shift && !modifiers.alt {
if app.run("mask.toggle", json!({"layer": layer.id.0})).is_some() {
mask_enabled = !mask_enabled;
mask_response.request_focus();
}
} else {
app.run("layer.select", json!({"layer": layer.id.0, "target": "mask"}));
if modifiers.alt {
let showing = app.session.view == texturecraft_engine::ViewMode::Mask(layer.id);
let view = if showing { json!({"mode": "material"}) } else { json!({"mode": "mask", "layer": layer.id.0}) };
app.run("viewport.view", view);
} else {
app.layer_panel.toggle_effects(mask_stack);
}
}
}
draw_thumbnail(ui, app, mask_rect, ThumbTarget::Mask { layer: layer.id }, !layer.visible || !mask_enabled, || {
let white = mask_background == texturecraft_engine::core::MaskBackground::White;
painter.rect_filled(mask_rect, THUMBNAIL_ROUNDING, Color32::from_gray(if white { WHITE_MASK_GRAY } else { BLACK_MASK_GRAY }));
if mask_effect_count > 0 {
@@ -589,22 +662,15 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize
tokens.text_dim,
);
}
}
});
painter.rect_stroke(mask_rect, THUMBNAIL_ROUNDING, target_stroke(&tokens, mask_target), egui::StrokeKind::Outside);
if !mask_enabled {
painter.line_segment([mask_rect.left_top(), mask_rect.right_bottom()], Stroke::new(HIDDEN_STRIKE_WIDTH, tokens.danger));
}
let mask_label = tr("Select the mask (Alt+click: show it in the viewport)");
let mask_response = ui.interact(mask_rect, ui.scope_id().with(("mask", layer.id.0)), Sense::click()).on_hover_text(mask_label);
if mask_response.clicked() {
app.run("layer.select", json!({"layer": layer.id.0, "target": "mask"}));
if ui.input(|input| input.modifiers.alt) {
let showing = app.session.view == texturecraft_engine::ViewMode::Mask(layer.id);
let view = if showing { json!({"mode": "material"}) } else { json!({"mode": "mask", "layer": layer.id.0}) };
app.run("viewport.view", view);
}
}
thumbnail_context_menu(ui, &mask_response, mask_label, &layer.name, mask_target, |ui| mask_management_menu(app, ui, layer, true));
effect_stack_thumbnail(app, &painter, &tokens, &mask_response, mask_stack);
ui.ctx().accesskit_node_builder(mask_response.id, |node| node.set_description(if mask_enabled { tr("Mask on") } else { tr("Mask off") }));
if app.session.view == texturecraft_engine::ViewMode::Mask(layer.id) {
painter.rect_stroke(
mask_rect.expand(HIGHLIGHT_OUTSET),
@@ -627,6 +693,7 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize
egui::Popup::menu(&slot).show(|ui| crate::layer_toolbar::mask_slot_menu(app, ui, layer, picker));
crate::layer_toolbar::bitmap_picker(app, &row, picker, layer.id);
}
x = mask_rect.right() + THUMBNAIL_GAP;
// Name (or rename editor) with the quieter subtitle under it
@@ -662,6 +729,7 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize
} else if show_name {
let name_color = if layer.visible { tokens.text_strong } else { tokens.text_dim };
let galley = elided(&painter, layer.name.clone(), LAYER_NAME_FONT_SIZE, name_color, name_rect.width());
let name_elided = galley.elided;
painter.galley(pos2(name_rect.left(), rect.center().y - NAME_LINE_GAP - galley.size().y), galley, tokens.text);
let kind = tr(match &layer.kind {
LayerKind::Paint => "Paint layer",
@@ -676,14 +744,12 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize
(None, 1) => format!("{kind} · {}", tr("1 effect")),
(None, count) => format!("{kind} · {}", trf("{count} effects", &[("count", &count)])),
};
let subtitle = elided(&painter, subtitle, LAYER_SUBTITLE_FONT_SIZE, tokens.text_dim, name_rect.width());
// A name or subtitle cut short by a narrow panel is shown in full on hover
if text_is_cut(&painter, &layer.name, LAYER_NAME_FONT_SIZE, name_rect.width())
|| text_is_cut(&painter, &subtitle, LAYER_SUBTITLE_FONT_SIZE, name_rect.width())
{
row.clone().on_hover_text(format!("{}\n{subtitle}", layer.name));
if name_elided || subtitle.elided {
row.clone().on_hover_text(format!("{}\n{}", layer.name, subtitle.text()));
}
let subtitle = elided(&painter, subtitle, LAYER_SUBTITLE_FONT_SIZE, tokens.text_dim, name_rect.width());
painter.galley(pos2(name_rect.left(), rect.center().y + NAME_LINE_GAP), subtitle, tokens.text_dim);
}
@@ -720,6 +786,7 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize
let modifiers = ui.input(|input| input.modifiers);
if row.clicked() && !on_control && !renaming {
click_layer(app, modifiers, layer.id.0, None);
app.layer_panel.expanded_effects = None;
}
if row.double_clicked() && !on_control && !renaming && show_name && !modifiers.shift && !modifiers.command {
app.ui.rename = Some((layer.id.0, layer.name.clone()));
@@ -838,73 +905,39 @@ fn content_glyph(p: &egui::Painter, tk: &Tokens, thumb: Rect, layer: &Layer) {
}
}
/// The "Content effects" or "Mask effects" header of `layer` and, unless folded, its effect rows
/// hung off tree lines. `more_below`: a second group follows, so the tree line goes on.
fn effect_group(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize, mask: bool, more_below: bool) {
let tokens = Tokens::get(ui.ctx());
let stack: &[Effect] = if mask { layer.mask.as_ref().map_or(&[], |layer_mask| &layer_mask.effects) } else { &layer.content_effects };
let key = (layer.id.0, mask);
let folded = app.layer_panel.folded.contains(&key);
let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), GROUP_HEADER_H), Sense::click());
let label = if mask { tr("Mask effects") } else { tr("Content effects") };
response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label));
let painter = ui.painter().clone();
painter.rect_filled(rect, 0.0, if response.hovered() { tokens.row_hover } else { tokens.panel });
let indent = ((depth + 1) as f32 * INDENT).min((rect.width() - GROUP_HEADER_MIN_REMAINING_WIDTH).max(0.0));
tree_lines(&painter, &tokens, rect, indent, &[], more_below);
let x = rect.left() + GROUP_HEADER_CARET_OFFSET + indent;
painter.text(
pos2(x, rect.center().y),
egui::Align2::CENTER_CENTER,
if folded { ic::CARET_RIGHT } else { ic::CARET_DOWN },
egui::FontId::proportional(LAYER_SUBTITLE_FONT_SIZE),
tokens.text_dim,
);
let galley = elided(
&painter,
label.to_string(),
GROUP_HEADER_LABEL_FONT_SIZE,
tokens.text_dim,
(rect.right() - GROUP_HEADER_LABEL_RESERVE - x - GROUP_HEADER_LABEL_GAP).max(0.0),
);
painter.galley(pos2(x + GROUP_HEADER_LABEL_GAP, rect.center().y - galley.size().y * 0.5), galley, tokens.text_dim);
painter.text(
pos2(rect.right() - GROUP_HEADER_COUNT_PADDING, rect.center().y),
egui::Align2::RIGHT_CENTER,
stack.len().to_string(),
egui::FontId::proportional(LAYER_SUBTITLE_FONT_SIZE),
tokens.text_dim,
);
if response.on_hover_text(tr("Fold or unfold these effects")).clicked() && !app.layer_panel.folded.remove(&key) {
app.layer_panel.folded.insert(key);
}
if folded {
/// Draw the effect disclosure on its thumbnail and expose the same state to AccessKit.
fn effect_stack_thumbnail(app: &TextureCraftApp, painter: &egui::Painter, tokens: &Tokens, response: &egui::Response, stack: Option<(LayerId, bool)>) {
let Some(stack) = stack else { return };
let expanded = app.layer_panel.expanded_effects == Some(stack);
response.ctx.accesskit_node_builder(response.id, |node| node.set_expanded(expanded));
if response.rect.width() < EFFECT_DISCLOSURE_SIZE {
return;
}
let trunks: Vec<usize> = if more_below { vec![depth] } else { Vec::new() };
for (row_index, effect) in stack.iter().rev().enumerate() {
effect_row(app, ui, layer, stack, effect, row_index, depth + 2, &trunks, row_index + 1 == stack.len(), mask);
}
let size = vec2(EFFECT_DISCLOSURE_SIZE, EFFECT_DISCLOSURE_SIZE);
let badge = Rect::from_min_size(response.rect.max - size, size);
painter.rect_filled(badge, THUMBNAIL_ROUNDING, tokens.button);
painter.text(
badge.center(),
egui::Align2::CENTER_CENTER,
if expanded { ic::CARET_DOWN } else { ic::CARET_RIGHT },
egui::FontId::proportional(EFFECT_DISCLOSURE_FONT_SIZE),
tokens.text_strong,
);
}
/// Tree connector of a row at the clamped `indent`: a line down from the parent's column (to the middle
/// of the row when `more` is false, the row's end otherwise) and a tick towards the row, with
/// lines straight through for the `trunks` of ancestors that continue.
fn tree_lines(p: &egui::Painter, tk: &Tokens, rect: Rect, indent: f32, trunks: &[usize], more: bool) {
/// Draw the line along the open effect stack and a branch to this row.
fn effect_tree_line(painter: &egui::Painter, tokens: &Tokens, rect: Rect, indent: f32, continues: bool) {
if indent < INDENT {
return;
}
let stroke = Stroke::new(1.0, tk.button_border);
for t in trunks {
if *t as f32 * INDENT + 8.0 < indent {
p.vline(level_x(rect.left(), *t), rect.y_range(), stroke);
}
}
let x = rect.left() + 15.0 + indent - INDENT;
let end = if more { rect.bottom() } else { rect.center().y };
p.vline(x, rect.top()..=end, stroke);
p.hline(x..=x + INDENT * 0.6, rect.center().y, stroke);
const BRANCH_WIDTH: f32 = INDENT * 0.6;
let stroke = Stroke::new(FOLDER_LINE_WIDTH, tokens.button_border);
let x = level_x(rect.left() + indent - INDENT, 0);
let end = if continues { rect.bottom() } else { rect.center().y };
painter.vline(x, rect.top()..=end, stroke);
painter.hline(x..=x + BRANCH_WIDTH, rect.center().y, stroke);
}
/// The drag-and-drop payload of an effect row (the effect id).
@@ -987,7 +1020,6 @@ fn effect_row(
effect: &Effect,
row_index: usize,
level: usize,
trunks: &[usize],
last: bool,
in_mask: bool,
) {
@@ -996,13 +1028,13 @@ fn effect_row(
let selected = app.session.selected_layer() == Some(layer.id) && app.session.target == StackTarget::Effect(effect_id);
let layer_preview = layer_preview_size(app);
let preview_size = effect_preview_size(layer_preview);
let (rect, row) = ui.allocate_exact_size(vec2(ui.available_width(), effect_row_height(layer_preview)), Sense::click_and_drag());
let (_, rect) = ui.allocate_space(vec2(ui.available_width(), effect_row_height(layer_preview)));
let row = ui.interact(rect, ui.scope_id().with(("effect_row", effect_id.0)), Sense::click_and_drag());
row.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, selected, &effect.name));
// Background, tree lines and the selected row's accent edge
let painter = ui.painter().clone();
// Effect rows alternate two shades just above the panel, counted from the top of their list
// Alternate the shades of unselected rows from the top of the stack
let background = if selected {
tokens.row_selected
} else if row.hovered() {
@@ -1012,12 +1044,12 @@ fn effect_row(
};
painter.rect_filled(rect, 0.0, background);
let indent = effect_row_indent(rect.width(), level, preview_size);
tree_lines(&painter, &tokens, rect, indent, trunks, !last);
effect_tree_line(&painter, &tokens, rect, indent, !last);
if selected {
painter.rect_filled(Rect::from_min_size(rect.min, vec2(SELECTED_EDGE_WIDTH, rect.height())), 0.0, tokens.accent);
}
// The eye, then the stack as it is up to and including this effect (a hidden one shows what it bypasses)
// Hidden effects preview the result that bypasses them
let content_left = rect.left() + ROW_LEFT_PADDING + indent;
let eye = Rect::from_center_size(pos2(content_left + EYE_SIZE * 0.5, rect.center().y), vec2(EYE_SIZE, EYE_SIZE));
let eye_response = ui.interact(eye, ui.scope_id().with(("eff_eye", effect_id.0)), Sense::click()).on_hover_text(tr("Enable or disable the effect"));
@@ -1028,16 +1060,16 @@ fn effect_row(
// Content rows edit the displayed channel's blend
let row_channel = (!in_mask && !app.ui.layer_material_view).then_some(channel);
if !thumb_box(ui, app, thumbnail, ThumbTarget::Stage { effect: effect_id, channel }, false) {
draw_thumbnail(ui, app, thumbnail, ThumbTarget::Stage { effect: effect_id, channel }, false, || {
let glyph = if in_mask { ic::MAGIC_WAND } else { ic::SPHERE };
painter.text(thumbnail.center(), egui::Align2::CENTER_CENTER, glyph, egui::FontId::proportional(preview_size * 0.5), tokens.text_dim);
}
});
painter.rect_stroke(thumbnail, THUMBNAIL_ROUNDING, Stroke::new(THUMBNAIL_BORDER_WIDTH, tokens.button_border), egui::StrokeKind::Outside);
if !visible {
painter.line_segment([thumbnail.left_bottom(), thumbnail.right_top()], Stroke::new(HIDDEN_STRIKE_WIDTH, tokens.text_dim));
}
// The name, then the blend mode and opacity side by side at the right when the name keeps room to be read
// Hide blend controls when the name needs the room
let name_left = thumbnail.right() + THUMBNAIL_GAP;
let controls_left = rect.right() - ROW_CONTROL_GAP - EFFECT_BLEND_WIDTH;
let show_blend = controls_left - ROW_CONTROL_GAP - name_left >= MIN_NAME_WIDTH;
@@ -1047,13 +1079,13 @@ fn effect_row(
if renaming {
let half_height = EFFECT_NAME_EDIT_HEIGHT * 0.5;
let name_rect = Rect::from_min_max(pos2(name_left, rect.center().y - half_height), pos2(name_right, rect.center().y + half_height));
effect_rename_editor(app, ui, name_rect, effect);
effect_rename_editor(app, ui, name_rect);
} else {
let name_width = (name_right - name_left).max(MIN_NAME_WIDTH);
if text_is_cut(&painter, &effect.name, EFFECT_NAME_FONT_SIZE, name_width) {
let galley = elided(&painter, effect.name.clone(), EFFECT_NAME_FONT_SIZE, name_color, name_width);
if galley.elided {
row.clone().on_hover_text(&effect.name);
}
let galley = elided(&painter, effect.name.clone(), EFFECT_NAME_FONT_SIZE, name_color, name_width);
painter.galley(pos2(name_left, rect.center().y - galley.size().y * 0.5), galley, tokens.text);
}
if show_blend {
@@ -1082,7 +1114,7 @@ fn effect_row(
app.run("layer.select", json!({"layer": layer.id.0, "target": effect_id.0}));
}
// Drag to reorder within the stack: a drop lands above this row, or below it from its lower half
// The half of the target row under the pointer determines the insertion side
if row.drag_started() {
row.dnd_set_drag_payload(EffectDrag(effect_id.0));
}
@@ -1128,7 +1160,7 @@ fn effect_row(
button = button.shortcut_text(shortcut);
}
if ui.add_enabled(enabled, button).clicked() {
// Selected first: a paste lands above it, a duplicate takes the selection
// Select the row so it anchors a paste and its duplicate takes focus
app.run("layer.select", json!({"layer": layer.id.0, "target": effect_id.0}));
app.run(command, json!({"effect": effect_id.0}));
ui.close();
@@ -1163,8 +1195,8 @@ fn effect_row(
});
}
/// The name editor of `effect` in `rect`: Enter or a click elsewhere renames, Escape cancels.
fn effect_rename_editor(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, effect: &Effect) {
/// The effect name editor: Enter or a click elsewhere renames, Escape cancels.
fn effect_rename_editor(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect) {
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(rect).layout(egui::Layout::left_to_right(egui::Align::Center)));
let Some((_, name_buffer)) = app.ui.rename.as_mut() else { return };
@@ -1175,17 +1207,22 @@ fn effect_rename_editor(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, effe
if ui.input(|input| input.key_pressed(egui::Key::Escape)) {
app.ui.rename = None;
} else if response.lost_focus() {
let name = name_buffer.trim().to_string();
app.ui.rename = None;
if !name.is_empty() && name != effect.name {
app.run("effect.set", json!({"effect": effect.id.0, "name": name}));
}
finish_effect_rename(app);
} else if !response.has_focus() {
// Only until the field has focus (see the layer rename editor)
response.request_focus();
}
}
fn finish_effect_rename(app: &mut TextureCraftApp) {
let Some((id, name)) = app.ui.rename.take() else { return };
let name = name.trim();
if !name.is_empty() && app.session.doc.project.effect(LayerId(id)).is_some_and(|(_, effect)| name != effect.name) {
app.run("effect.set", json!({"effect": id, "name": name}));
}
}
/// The Geometry mask tool: what a click does, and the selected layer's parts.
fn geometry_tool_section(app: &mut TextureCraftApp, ui: &mut Ui) {
let tk = Tokens::get(ui.ctx());
@@ -3298,3 +3335,39 @@ mod layer_layout_tests {
assert!(show_blend);
}
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod texture_set_list_tests {
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
use super::*;
#[test]
fn keyboard_selection_updates_the_texture_set_list_items() {
let session = texturecraft_engine::Session::new_project(
"Texture set selection",
texturecraft_engine::geom::primitives::material_ball(),
"builtin:material_ball",
None,
128,
)
.unwrap();
let first = session.doc.project.texture_sets[0].name.clone();
let second = session.doc.project.texture_sets[1].name.clone();
let mut harness = Harness::builder()
.with_size(vec2(1600.0, 960.0))
.with_context_setup(crate::framework::install_headless)
.build_eframe(|context| TextureCraftApp::new(context, session));
harness.run_steps(4);
harness.get_by_role_and_label(egui::Role::ListItem, &second).focus();
harness.run_steps(2);
harness.key_press(egui::Key::Enter);
harness.run_steps(3);
assert_eq!(harness.state().session.ts(), 1);
assert_eq!(harness.get_by_role_and_label(egui::Role::ListItem, &first).accesskit_node().is_selected(), Some(false));
assert_eq!(harness.get_by_role_and_label(egui::Role::ListItem, &second).accesskit_node().is_selected(), Some(true));
}
}
+290 -243
View File
@@ -1,18 +1,22 @@
//! The dock host: every side panel (assets, texture set list, layers, texture set settings,
//! properties, display/shader settings, history, log) is a tab that can be docked, tabbed,
//! resized, floated and closed around the viewport. craft-ui's shared docking
//! (`craft_ui::docking`) draws the frames, tab strips, floating windows and drop previews and
//! owns the gestures; this module names the panels, builds the default arrangement, applies
//! the dock's changes and hosts the panel bodies. The bodies live in `dock.rs`, `shelf.rs` and
//! `windows.rs`.
//! resized, floated and closed around the viewport. craft-ui's `DockArea` draws the frames, tab
//! strips, floating windows and drop previews and owns the gestures; this module names the
//! panels, builds the default arrangement, applies the dock's changes and hosts the panel bodies.
//! The bodies live in `dock.rs`, `shelf.rs` and `windows.rs`.
//!
//! The viewport is the central canvas: it stays docked, never takes tabs and is the only panel
//! that cannot close or float. The layout persists with `UiState` as a craft-ui `Workspace`;
//! a layout that does not load or validate becomes the default.
//! that cannot close or float. The layout persists with `UiState` as a craft-behavior
//! `Workspace`; a layout that does not load or validate becomes the default.
use craft_ui::docking::{Action, DockArea, DockContent, DockStyle, Layout, Location, Node, PanelLimits, PanelState, Permissions, Placement};
use craft_ui::layout::{SplitAxis, SplitSize};
use egui::{Id, Margin, RichText, Ui, Vec2, vec2};
use std::sync::Arc;
use craft_behavior::dock::{Action, DockPlacement, Layout, Location, Node, PanelState, Permissions, SplitSize};
use craft_behavior::flow::Axis;
use craft_ui::contract::{Bind, BodyCx, PlainData, SizeLimits, Tracked};
use craft_ui::docking::{DockConfig, DockPanels, GroupAt, PanelSpec, PanelSpecs};
use craft_ui::patterns::dock::DockArea;
use egui::{Margin, Rect, Ui, Vec2, ViewportId, vec2};
use serde::{Deserialize, Serialize};
use serde_json::Value;
@@ -20,11 +24,6 @@ use crate::TextureCraftApp;
use crate::i18n::tr;
use crate::theme::Tokens;
mod header_band;
mod shown_group_tab;
pub(crate) use shown_group_tab::HEADER_TITLE_LEFT;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Panel {
Viewport,
@@ -130,8 +129,8 @@ impl Panel {
}
}
/// Where the panel floats when it has never been laid out: `[x, y, width, height]`, cascaded.
fn float_rect(self) -> Option<[f32; 4]> {
/// Where the panel floats when it has never been laid out, cascaded.
fn float_rect(self) -> Option<Rect> {
let slot = match self {
Panel::Display => 0.0,
Panel::Shader => 1.0,
@@ -142,24 +141,24 @@ impl Panel {
Panel::BakingLog => 6.0,
_ => return None,
};
Some([960.0, 90.0 + 50.0 * slot, 300.0, 380.0])
Some(Rect::from_min_size(egui::pos2(960.0, 90.0 + 50.0 * slot), vec2(300.0, 380.0)))
}
}
/// The saved panel arrangement: craft-ui's workspace over TextureCraft's panels.
pub type Workspace = craft_ui::docking::Workspace<Panel>;
/// The saved panel arrangement: craft-behavior's workspace over TextureCraft's panels.
pub type Workspace = craft_behavior::dock::Workspace<Panel>;
/// The viewport never moves, floats, closes or takes tabs; panels dock beside it.
pub fn permissions(panel: &Panel) -> Permissions {
if *panel == Panel::Viewport { Permissions { accepts_splits: true, ..Permissions::PROTECTED } } else { Permissions::default() }
if *panel == Panel::Viewport { Permissions::PROTECTED.accepts_splits(true) } else { Permissions::default() }
}
fn tabs(panels: &[Panel]) -> Node<Panel> {
Node::Tabs { panels: panels.to_vec(), active: 0 }
Node::tabs(panels.to_vec(), 0)
}
fn split(axis: SplitAxis, size: SplitSize, first: Node<Panel>, second: Node<Panel>) -> Node<Panel> {
Node::Split { axis, size, first: Box::new(first), second: Box::new(second) }
fn split(axis: Axis, size: SplitSize, first: Node<Panel>, second: Node<Panel>) -> Node<Panel> {
Node::split(axis, size, first, second)
}
/// The default: assets (4 tile columns at 1920 px) left of the viewport, then texture sets, layers (tabbed with texture set settings) and properties
@@ -175,57 +174,41 @@ pub fn default_workspace() -> Workspace {
const LAYERS_SPLIT_RATIO: f32 = 0.31;
let column = split(
SplitAxis::Vertical,
Axis::Y,
SplitSize::Ratio(TEXTURE_SET_SPLIT_RATIO),
tabs(&[TextureSetList]),
split(SplitAxis::Vertical, SplitSize::Ratio(LAYERS_SPLIT_RATIO), tabs(&[Layers, TextureSetSettings]), tabs(&[Properties])),
split(Axis::Y, SplitSize::Ratio(LAYERS_SPLIT_RATIO), tabs(&[Layers, TextureSetSettings]), tabs(&[Properties])),
);
let root = split(
SplitAxis::Horizontal,
Axis::X,
SplitSize::Ratio(ASSETS_SPLIT_RATIO),
tabs(&[Assets]),
split(SplitAxis::Horizontal, SplitSize::Ratio(VIEWPORT_SPLIT_RATIO), tabs(&[Viewport]), column),
split(Axis::X, SplitSize::Ratio(VIEWPORT_SPLIT_RATIO), tabs(&[Viewport]), column),
);
let mut workspace = Workspace::new(Layout { root: Some(root), floating: Vec::new() });
for panel in Panel::ALL {
if let Some(rect) = panel.float_rect() {
workspace.hidden.push((panel, floating_location(rect)));
}
}
let mut hidden: Vec<(Panel, Location<Panel>)> = Panel::ALL.into_iter().filter_map(|panel| Some((panel, floating_location(panel.float_rect()?)))).collect();
for panel in [MeshMapSettings, CommonSettings, MeshMapBakers] {
workspace.hidden.push((
panel,
Location {
floating: None,
anchor: Some(TextureSetList),
placement: Placement::Tab { before: None },
size: None,
stack: None,
sibling: Vec::new(),
group: None,
},
));
hidden.push((panel, Location::new(Some(TextureSetList), DockPlacement::tab(None))));
}
workspace
Workspace::from_parts(Layout::new(Some(root), Vec::new()), hidden, Vec::new())
}
/// Where a closed panel reopens as its own floating window at `rect` (`[x, y, width, height]`)
fn floating_location(rect: [f32; 4]) -> Location<Panel> {
Location { floating: Some(rect), anchor: None, placement: Placement::Tab { before: None }, size: None, stack: None, sibling: Vec::new(), group: None }
/// Where a closed panel reopens as its own floating window at `rect`
fn floating_location(rect: Rect) -> Location<Panel> {
let mut location = Location::new(None, DockPlacement::tab(None));
location.floating = Some(rect);
location
}
/// craft-ui's checks plus the viewport's: a saved or hand-edited file cannot hide, float, group
/// or collapse it.
pub fn validate(workspace: &Workspace) -> Result<(), String> {
workspace.validate().map_err(|error| error.to_string())?;
let layout = &workspace.layout;
let layout = workspace.layout();
if layout.floating.iter().any(|window| window.contains(&Panel::Viewport)) {
return Err("The viewport cannot float".into());
}
if workspace.hidden.iter().any(|(panel, _)| *panel == Panel::Viewport) {
if workspace.hidden().iter().any(|(panel, _)| *panel == Panel::Viewport) {
return Err("The viewport cannot be hidden".into());
}
let mut found = false;
@@ -242,7 +225,7 @@ pub fn validate(workspace: &Workspace) -> Result<(), String> {
}
found = true;
}
Node::Stack { entries } if entries.iter().any(|entry| entry.panel == Panel::Viewport) => {
Node::Stack { entries, .. } if entries.iter().any(|entry| entry.panel == Panel::Viewport) => {
return Err("The viewport cannot be collapsed".into());
}
Node::Dock { columns, .. } if columns.iter().flat_map(|column| &column.groups).any(|group| group.panels.contains(&Panel::Viewport)) => {
@@ -269,7 +252,7 @@ const BAKING_LOG_HEIGHT: f32 = 160.0;
/// Share of the first bake column the texture set list takes above the mesh map bakers
const TEXTURE_SET_LIST_SHARE: f32 = 0.4;
/// The dock layout (part of `UiState`; serialized as a craft-ui `Workspace`).
/// The dock layout (part of `UiState`; serialized as a craft-behavior `Workspace`).
#[derive(Clone, Debug)]
pub struct Dock {
workspace: Workspace,
@@ -327,24 +310,25 @@ impl Dock {
/// Texture sets over the bakers, the two settings tabs, the log under both, then the viewport
pub(crate) fn for_baking() -> Self {
let mut workspace = default_workspace();
let painting = default_workspace();
let mut hidden = painting.hidden().to_vec();
for panel in [Panel::Assets, Panel::Layers, Panel::TextureSetSettings, Panel::Properties] {
if let Ok(location) = workspace.layout.location(&panel) {
workspace.hidden.push((panel, location));
if let Ok(location) = painting.layout().location(&panel) {
hidden.push((panel, location));
}
}
let bake_panels = [Panel::MeshMapSettings, Panel::CommonSettings, Panel::MeshMapBakers, Panel::Log];
workspace.hidden.retain(|(panel, _)| !bake_panels.contains(panel));
hidden.retain(|(panel, _)| !bake_panels.contains(panel));
let gutter_width = f32::from(crate::theme::GUTTER);
let list_column = split(SplitAxis::Vertical, SplitSize::Ratio(TEXTURE_SET_LIST_SHARE), tabs(&[Panel::TextureSetList]), tabs(&[Panel::MeshMapBakers]));
let list_column = split(Axis::Y, SplitSize::Ratio(TEXTURE_SET_LIST_SHARE), tabs(&[Panel::TextureSetList]), tabs(&[Panel::MeshMapBakers]));
let settings_column = tabs(&[Panel::CommonSettings, Panel::MeshMapSettings]);
let columns = split(SplitAxis::Horizontal, SplitSize::FixedFirst(BAKERS_COLUMN_WIDTH), list_column, settings_column);
let columns_over_log = split(SplitAxis::Vertical, SplitSize::FixedSecond(BAKING_LOG_HEIGHT), columns, tabs(&[Panel::Log]));
let columns = split(Axis::X, SplitSize::FixedFirst(BAKERS_COLUMN_WIDTH), list_column, settings_column);
let columns_over_log = split(Axis::Y, SplitSize::FixedSecond(BAKING_LOG_HEIGHT), columns, tabs(&[Panel::Log]));
let columns_width = BAKERS_COLUMN_WIDTH + gutter_width + SETTINGS_COLUMN_WIDTH;
let root = split(SplitAxis::Horizontal, SplitSize::FixedFirst(columns_width), columns_over_log, tabs(&[Panel::Viewport]));
workspace.layout = Layout { root: Some(root), floating: Vec::new() };
let root = split(Axis::X, SplitSize::FixedFirst(columns_width), columns_over_log, tabs(&[Panel::Viewport]));
let workspace = Workspace::from_parts(Layout::new(Some(root), Vec::new()), hidden, painting.floated().to_vec());
Dock { workspace, raise: None, replaced_unreadable: false }
}
@@ -353,12 +337,12 @@ impl Dock {
}
pub fn is_open(&self, p: Panel) -> bool {
self.workspace.layout.contains(&p)
self.workspace.layout().contains(&p)
}
/// Open and the front tab of its group.
pub fn is_visible(&self, p: Panel) -> bool {
self.workspace.layout.panel_state(&p) == PanelState::Front
self.workspace.layout().panel_state(&p) == PanelState::Front
}
/// Hide a visible panel, otherwise bring it up.
@@ -367,7 +351,7 @@ impl Dock {
}
pub fn close(&mut self, p: Panel) {
if let Err(error) = self.workspace.set_visible(p, false, None, permissions) {
if let Err(error) = self.workspace.set_visible(p, false, None, false, permissions) {
log::warn!("panel {p:?} was not closed: {error}");
}
}
@@ -376,7 +360,7 @@ impl Dock {
/// front.
pub fn focus(&mut self, p: Panel) {
let mut next = self.workspace.clone();
match next.set_visible(p, true, None, permissions) {
match next.set_visible(p, true, None, false, permissions) {
Ok(()) if validate(&next).is_ok() => {
self.workspace = next;
self.raise = Some(p);
@@ -386,10 +370,12 @@ impl Dock {
}
}
/// Open the closed `panel` as a floating window at `rect` (`[x, y, width, height]`)
pub(crate) fn float_at(&mut self, panel: Panel, rect: [f32; 4]) {
self.workspace.hidden.retain(|(hidden_panel, _)| *hidden_panel != panel);
self.workspace.hidden.push((panel, floating_location(rect)));
/// Open the closed `panel` as a floating window at `rect`
pub(crate) fn float_at(&mut self, panel: Panel, rect: Rect) {
let mut hidden = self.workspace.hidden().to_vec();
hidden.retain(|(hidden_panel, _)| *hidden_panel != panel);
hidden.push((panel, floating_location(rect)));
self.workspace = Workspace::from_parts(self.workspace.layout().clone(), hidden, self.workspace.floated().to_vec());
self.focus(panel);
}
@@ -397,7 +383,7 @@ impl Dock {
/// it was.
fn apply(&mut self, action: Action<Panel>) {
let mut next = self.workspace.clone();
match next.apply(action, permissions) {
match next.apply(action, false, permissions) {
Ok(_) if validate(&next).is_ok() => self.workspace = next,
Ok(_) => log::warn!("a panel move would break the viewport's rules"),
Err(error) => log::warn!("a panel move was not applied: {error}"),
@@ -405,58 +391,76 @@ impl Dock {
}
}
/// What the dock area keeps between passes: the workspace it shows and the panels' specs.
#[derive(Default)]
pub(crate) struct LiveDock {
shown: Option<Arc<Workspace>>,
specs: Tracked<DockSpecs>,
/// The panel whose floating window takes over the held press in the next pass, with the grab point inside the window.
continue_move: Option<(Panel, egui::Vec2)>,
}
impl LiveDock {
/// Asks the next pass's dock to let the window holding `panel` follow the held pointer from `grab`.
pub(crate) fn hand_over(&mut self, panel: Panel, grab: egui::Vec2) {
self.continue_move = Some((panel, grab));
}
/// The `Arc` the dock shows for `workspace`: the last one while the arrangement is the same,
/// so an idle pass keeps the workspace's revision and the dock reads no spec.
fn shown(&mut self, workspace: &Workspace) -> Arc<Workspace> {
if let Some(shown) = self.shown.as_ref().filter(|shown| ***shown == *workspace) {
return Arc::clone(shown);
}
let shown = Arc::new(workspace.clone());
self.shown = Some(Arc::clone(&shown));
shown
}
}
/// What the dock reads of the panels: their tab names, in [`Panel::ALL`] order.
#[derive(Clone, Debug, Default, PartialEq, PlainData)]
struct DockSpecs {
labels: Vec<String>,
}
impl PanelSpecs<Panel> for DockSpecs {
fn spec(&self, panel: &Panel) -> PanelSpec {
let label = Panel::ALL.iter().position(|p| p == panel).and_then(|index| self.labels.get(index)).cloned().unwrap_or_default();
// Every panel body is TextureCraft's own egui code: the dock runs it with the window's style.
let spec = PanelSpec::new(label).limits(SizeLimits::at_least(min_size(*panel))).float_size(FLOATING_SIZE.max(min_size(*panel))).host_body();
if *panel == Panel::Viewport { spec.canvas() } else { spec }
}
fn permissions(&self, panel: &Panel) -> Permissions {
permissions(panel)
}
}
/// The tab name of `panel` in the interface language.
fn label(app: &TextureCraftApp, panel: Panel) -> String {
match panel {
Panel::Properties => crate::dock::properties_title(app),
p => tr(p.name()).to_string(),
}
}
/// Reads the tab names, moving the specs' revision only when one changed.
fn refresh_specs(app: &mut TextureCraftApp) {
let labels: Vec<String> = Panel::ALL.iter().map(|panel| label(app, *panel)).collect();
if app.docks.specs.labels != labels {
app.docks.specs.labels = labels;
}
}
// ---------------------------------------------------------------------------------------------
// Drawing
fn area_id() -> Id {
Id::unique("texturecraft-docking")
}
/// From a panel's left edge to its contents' text (an empty panel's note)
pub(crate) const HEADER_TITLE_LEFT: f32 = 12.0;
/// Smallest panel extent a divider drag leaves, in points
const MIN_PANE_EXTENT: f32 = 60.0;
/// Border width of a floating panel, in points
const FLOATING_BORDER_WIDTH: f32 = 1.0;
/// Text size of the panel tabs, in points
const TAB_TEXT_SIZE: f32 = 12.5;
/// Narrowest panel tab, in points
const MIN_TAB_WIDTH: f32 = 54.0;
/// Mixing in title ink keeps the light dock's focus outline above 3:1 on both header surfaces
const LIGHT_DOCK_ACCENT_TEXT_MIX: f32 = 0.2;
/// The dock look: every panel group is a card under one chrome-coloured header bar, names in capitals at the left, a close × at the right
fn style(ui: &Ui, tokens: &Tokens) -> DockStyle {
let mut dock_style = DockStyle::from_ui(ui);
dock_style.gap = f32::from(crate::theme::GUTTER);
dock_style.min_pane = MIN_PANE_EXTENT;
dock_style.background = tokens.panel;
dock_style.tab_background = tokens.chrome;
// The selected title is brighter while the strip keeps its colour
dock_style.active_background = tokens.chrome;
dock_style.text = tokens.text_strong;
dock_style.inactive_text = tokens.text_dim;
dock_style.border = egui::Stroke::NONE;
dock_style.accent = if tokens.dark { tokens.accent } else { tokens.accent.lerp_to_gamma(tokens.text_strong, LIGHT_DOCK_ACCENT_TEXT_MIX) };
dock_style.floating_background = tokens.panel;
dock_style.floating_stroke = egui::Stroke::new(FLOATING_BORDER_WIDTH, tokens.button_border);
dock_style.font = egui::FontId::proportional(TAB_TEXT_SIZE);
dock_style.min_tab_width = MIN_TAB_WIDTH;
dock_style.tab_height = TAB_HEIGHT;
// Panels arrange in a split tree around the viewport; floating title bars only move windows
dock_style.new_dock_zones = false;
dock_style.title_bar_docks = false;
dock_style
}
/// Whether a modal layer or update dialog holds the input, so the panels, floating ones included,
/// do not take it.
/// Whether one of TextureCraft's own modal layers or the update dialogs hold the input, so the
/// panels floated into windows of their own do not take it (`FrameInput::app_modal`).
pub(crate) fn input_blocked(app: &TextureCraftApp, context: &egui::Context) -> bool {
let modal = context.memory(|memory| memory.top_modal_layer()).is_some();
#[cfg(not(target_arch = "wasm32"))]
@@ -478,57 +482,84 @@ pub fn show(app: &mut TextureCraftApp, ui: &mut Ui) {
}
let context = ui.ctx().clone();
let tokens = Tokens::get(&context);
let style = style(ui, &tokens);
let layout = app.ui.dock.workspace.layout.clone();
let mut area = DockArea::new(area_id()).input_blocked(input_blocked(app, &context));
if let Some(panel) = app.ui.dock.raise.take() {
area = area.raise_panel(panel);
}
let output = area.show_content(ui, &layout, &style, &mut Panels { app, tokens, layout: &layout, style: &style });
crate::rail_popup::hand_drag_to_dock(&context, area_id());
refresh_specs(app);
let shown = app.docks.shown(&app.ui.dock.workspace);
// The specs leave the app while its panels borrow it, and come back with their revision.
let specs = std::mem::take(&mut app.docks.specs);
let hand_over = app.docks.continue_move.take();
let raise = app.ui.dock.raise.take();
// Panels arrange in a split tree around the viewport; floating title bars only move windows.
// Each closable tab has its close button, as each group header had one for its shown panel.
let config = DockConfig::default().new_dock_zones(false).title_bar_docks(false).tab_close_buttons(true);
let (output, focused_windows) = {
let tokens = Tokens::get(&context);
let mut panels = Panels { app: &mut *app, tokens, layout: shown.layout().clone(), focused_windows: Vec::new() };
let mut area = DockArea::new("Panels", Bind::given(Arc::clone(&shown)), &specs, &mut panels, config);
if let Some(hand_over) = hand_over {
area = area.continue_move(hand_over);
}
if let Some(panel) = raise {
area = area.raise(panel);
}
let output = area.show(ui);
(output, panels.focused_windows)
};
app.docks.specs = specs;
// The popup needs the viewport the dock recorded this frame
crate::rail_popup::show(app, &context);
// Keys pressed in a panel floated into a window of its own run the app's shortcuts there
#[cfg(not(target_arch = "wasm32"))]
crate::menus::forwarded_shortcuts(app, &context, output.forwarded_events, output.forwarded_modifiers.unwrap_or_default());
for (_, viewport) in &output.windows {
let (events, held) = forwarded_events(&context, *viewport, &focused_windows);
crate::menus::forwarded_shortcuts(app, &context, events, held);
}
#[cfg(target_arch = "wasm32")]
let _ = focused_windows;
if let Some(error) = &output.error {
log::warn!("docking: {error}");
log::warn!("docking: {:?}", error.error);
}
// A layout changed by a panel takes priority over gestures from the old layout
if app.ui.dock.workspace.layout != layout {
craft_ui::docking::cancel_drag::<Panel>(&context, area_id());
if app.ui.dock.workspace != *shown {
craft_ui::runtime::drag::cancel(&context, craft_behavior::CancelReason::HostChanged);
return;
}
for action in output.actions {
for action in output.actions.into_iter().chain(output.requested) {
app.ui.dock.apply(action);
}
}
/// Size of the panel names on a header bar
const HEADER_TITLE_SIZE: f32 = 12.0;
/// Side of the close × at the right end of a header bar
const HEADER_CLOSE_SIZE: f32 = 22.0;
/// Room right of the close × button, so its glyph ends where the Properties controls end (side padding plus scroll bar gutter)
const HEADER_CLOSE_RIGHT_MARGIN: f32 = 18.0;
/// Whether a docked group's header bar ends in a close × (floating windows have one on their title bar; the viewport never closes)
fn header_closes(active: &Panel, floating: bool) -> bool {
!floating && permissions(active).closable
/// Records in `focused_windows` whether a widget of the running pass's window has the keyboard, after one of the window's
/// panels drew
fn note_focus(context: &egui::Context, focused_windows: &mut Vec<ViewportId>) {
let window = context.viewport_id();
focused_windows.retain(|focused| *focused != window);
if context.memory(|memory| memory.focused().is_some()) {
focused_windows.push(window);
}
}
/// The panels' contents, names and limits for the dock area
/// The keys, text and clipboard events `window` hands to the app's shortcuts, with the modifiers held there: nothing
/// while one of its widgets has the keyboard
#[cfg(not(target_arch = "wasm32"))]
fn forwarded_events(context: &egui::Context, window: ViewportId, focused_windows: &[ViewportId]) -> (Vec<egui::Event>, egui::Modifiers) {
use egui::Event;
let focused = focused_windows.contains(&window);
let forwarded = |event: &&Event| !focused && matches!(event, Event::Key { .. } | Event::Text(_) | Event::Copy | Event::Cut | Event::Paste(_));
context.input_for(window, |input| (input.events.iter().filter(forwarded).cloned().collect(), input.modifiers))
}
/// The panels' contents for the dock area
struct Panels<'a> {
app: &'a mut TextureCraftApp,
tokens: Tokens,
layout: &'a Layout<Panel>,
style: &'a DockStyle,
/// The arrangement the dock shows in this pass
layout: Layout<Panel>,
/// The windows in which a widget had the keyboard once their panels drew
focused_windows: Vec<ViewportId>,
}
/// Room between a panel's edges and its contents
@@ -594,100 +625,42 @@ pub(crate) fn panel_body(app: &mut TextureCraftApp, ui: &mut Ui, panel: Panel) {
});
}
impl DockContent<Panel> for Panels<'_> {
fn body(&mut self, ui: &mut Ui, panel: &Panel) {
if *panel == Panel::Viewport {
crate::rail_popup::remember_viewport(ui.ctx(), ui.max_rect());
ui.painter().rect_filled(ui.max_rect(), 0.0, self.tokens.viewport);
crate::viewport::central(self.app, ui);
return;
impl DockPanels<Panel> for Panels<'_> {
fn body(&mut self, panel: &Panel, ui: &mut Ui, _: &mut BodyCx<'_>) {
// The viewport is its group's `group_view`
if *panel != Panel::Viewport {
panel_body(self.app, ui, *panel);
}
// Before the rows, which draw over the foot of the shown tab's box
self.paint_shown_group_tab(ui, *panel);
panel_body(self.app, ui, *panel);
note_focus(ui.ctx(), &mut self.focused_windows);
}
fn logical_label(&self, panel: &Panel) -> String {
match panel {
Panel::Properties => crate::dock::properties_title(self.app),
p => tr(p.name()).to_string(),
/// The viewport, edge to edge in its group.
fn group_view(&mut self, panels: &[Panel], _: usize, ui: &mut Ui, at: GroupAt, _: &mut BodyCx<'_>) -> Option<f32> {
let GroupAt::Show(rect) = at else { return None };
if !panels.contains(&Panel::Viewport) {
return None;
}
crate::rail_popup::remember_viewport(ui.ctx(), ui.max_rect());
ui.painter().rect_filled(ui.max_rect(), 0.0, self.tokens.viewport);
crate::viewport::central(self.app, ui);
Some(rect.height())
}
fn label(&mut self, ui: &Ui, panel: &Panel, logical: &str, _font: &egui::FontId, color: egui::Color32) -> egui::WidgetText {
// Capitals on the bar only: menus and screen readers keep the logical name
let name = logical.to_uppercase();
let font = crate::theme::semibold(HEADER_TITLE_SIZE);
// Popup menu rows use their unpadded text metrics
if matches!(ui.layer_id().order, egui::Order::Foreground | egui::Order::Tooltip) {
return RichText::new(name).font(font).color(color).into();
/// A rail panel floating on its own carries the Dock button that sends it back to the rail
fn group_header(&mut self, panels: &[Panel], active: usize, ui: &mut Ui, _: &mut BodyCx<'_>) {
let Some(active) = panels.get(active).copied() else { return };
let floating = self.layout.floating.iter().any(|window| window.contains(&active));
if redocks(panels, &active, floating)
&& crate::widgets::icon_button(ui, egui_phosphor::regular::ARROW_SQUARE_IN, tr("Dock"), false, DOCK_BUTTON_SIZE).clicked()
{
self.app.ui.dock.close(active);
}
header_band::header_name(ui, &name, font, color, self.header_lift(*panel)).into()
}
fn group_header_width(&self, panels: &[Panel], active: &Panel, floating: bool, _strip_width: f32) -> f32 {
if header_closes(active, floating) {
HEADER_CLOSE_SIZE + HEADER_CLOSE_RIGHT_MARGIN
} else if redocks(panels, active, floating) {
DOCK_BUTTON_SIZE + DOCK_BUTTON_MARGIN
} else {
0.0
}
}
/// A docked group's bar ends in its close ×; a rail panel floating on its own carries the Dock button that sends it back to the rail
fn group_header(&mut self, ui: &mut Ui, panels: &[Panel], active: &Panel, floating: bool) {
if redocks(panels, active, floating) {
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if crate::widgets::icon_button(ui, egui_phosphor::regular::ARROW_SQUARE_IN, tr("Dock"), false, DOCK_BUTTON_SIZE).clicked() {
self.app.ui.dock.close(*active);
}
});
return;
}
if !header_closes(active, floating) {
return;
}
// Centre the close control on the header title line
let rect = ui.max_rect();
let button = egui::Rect::from_center_size(
egui::pos2(rect.right() - HEADER_CLOSE_RIGHT_MARGIN - HEADER_CLOSE_SIZE / 2.0, rect.center().y - self.header_lift(*active)),
vec2(HEADER_CLOSE_SIZE, HEADER_CLOSE_SIZE),
);
let clicked = ui
.scope_builder(egui::UiBuilder::new().max_rect(button), |ui| {
crate::widgets::icon_button(ui, egui_phosphor::regular::X, tr("Close Panel"), false, HEADER_CLOSE_SIZE).clicked()
})
.inner;
if clicked {
self.app.ui.dock.close(*active);
}
}
fn permissions(&self, panel: &Panel) -> Permissions {
permissions(panel)
}
fn limits(&self, panel: &Panel) -> PanelLimits {
PanelLimits { min: min_size(*panel), ..PanelLimits::default() }
}
fn floating_size(&self, panel: &Panel) -> Option<egui::Vec2> {
Some(FLOATING_SIZE.max(min_size(*panel)))
}
}
/// Size of the Dock button in a floating rail panel's tab strip
/// Size of the Dock button in a floating rail panel's header
const DOCK_BUTTON_SIZE: f32 = 22.0;
/// Room right of the Dock button, so it clears the strip's end
const DOCK_BUTTON_MARGIN: f32 = 6.0;
/// Whether a floating window holds one rail panel alone: its Dock button closes it back onto the rail
fn redocks(panels: &[Panel], active: &Panel, floating: bool) -> bool {
floating && panels.len() == 1 && crate::rail_popup::is_rail_panel(*active)
@@ -698,7 +671,60 @@ mod tests {
use super::*;
fn panels_of(w: &Workspace) -> Vec<Panel> {
w.layout.panels().into_iter().copied().collect()
w.layout().panels().into_iter().copied().collect()
}
/// What a floating panel's own window with a text field, focused when `typing`, hands on of `events`
#[cfg(not(target_arch = "wasm32"))]
fn handed_on(typing: bool, events: &[egui::Event]) -> Vec<egui::Event> {
use std::{cell::RefCell, rc::Rc};
let window = ViewportId::from_hash_of("floating panel");
let context = egui::Context::default();
context.set_embed_viewports(false);
// Runs the window's pass inside its parent's, as eframe does
let arriving = Rc::new(RefCell::new(Vec::new()));
let queued = Rc::clone(&arriving);
egui::Context::set_immediate_viewport_renderer(move |context, viewport| {
let mut input = egui::RawInput { viewport_id: viewport.ids.this, events: queued.take(), ..Default::default() };
input.viewports.insert(viewport.ids.this, egui::ViewportInfo { parent: Some(viewport.ids.parent), ..Default::default() });
let mut output = context.run_ui(input, viewport.viewport_ui_cb);
output.textures_delta.clear();
});
let mut name = String::new();
let mut handed_on = Vec::new();
// The field takes the keyboard a pass before the keys arrive
for arrived in [Vec::new(), events.to_vec()] {
*arriving.borrow_mut() = arrived;
let mut output = context.run_ui(egui::RawInput::default(), |ui| {
let mut focused_windows = Vec::new();
ui.ctx().show_viewport_immediate(window, egui::ViewportBuilder::default(), |ui, _| {
let field = ui.text_edit_singleline(&mut name);
if typing {
field.request_focus();
}
note_focus(ui.ctx(), &mut focused_windows);
});
handed_on.extend(forwarded_events(ui.ctx(), window, &focused_windows).0);
});
output.textures_delta.clear();
}
assert_eq!(name.is_empty(), !typing, "a focused field types the text");
handed_on
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_floating_panel_hands_on_its_keys_unless_a_field_there_has_the_keyboard() {
use egui::{Event, Key, Modifiers};
let key = Event::Key { key: Key::B, physical_key: Some(Key::B), pressed: true, repeat: false, modifiers: Modifiers::NONE };
let keys = [key, Event::Text("b".into()), Event::Paste("pasted".into())];
assert!(handed_on(true, &keys).is_empty(), "the field's keys are its own");
assert_eq!(handed_on(false, &keys), keys, "with nothing focused they are the app's");
}
#[test]
@@ -708,7 +734,10 @@ mod tests {
assert!(validate(&workspace).is_ok());
for panel in Panel::ALL {
assert!(workspace.layout.contains(&panel) || workspace.hidden.iter().any(|(hidden, _)| *hidden == panel), "{panel:?} is neither shown nor hidden");
assert!(
workspace.layout().contains(&panel) || workspace.hidden().iter().any(|(hidden, _)| *hidden == panel),
"{panel:?} is neither shown nor hidden"
);
}
assert_eq!(panels_of(&workspace), [Panel::Assets, Panel::Viewport, Panel::TextureSetList, Panel::Layers, Panel::TextureSetSettings, Panel::Properties]);
@@ -716,12 +745,14 @@ mod tests {
#[test]
fn a_saved_split_keeps_its_own_share() {
let mut workspace = default_workspace();
let Some(Node::Split { second: right, .. }) = workspace.layout.root.as_mut() else { panic!("assets | rest") };
let default = default_workspace();
let mut layout = default.layout().clone();
let Some(Node::Split { second: right, .. }) = layout.root.as_mut() else { panic!("assets | rest") };
let Node::Split { second: column, .. } = right.as_mut() else { panic!("viewport | right column") };
let Node::Split { second: below_sets, .. } = column.as_mut() else { panic!("texture sets | rest") };
let Node::Split { size, .. } = below_sets.as_mut() else { panic!("layers | properties") };
*size = SplitSize::Ratio(0.57);
let workspace = Workspace::from_parts(layout, default.hidden().to_vec(), default.floated().to_vec());
let back = Dock::from_value(serde_json::to_value(&workspace).unwrap());
assert_eq!(back.workspace(), &workspace, "a layout saved with the old split opens unchanged");
@@ -770,7 +801,23 @@ mod tests {
let dock = Dock::from_value(saved);
assert!(!dock.replaced_unreadable(), "the saved layout is kept");
assert!(dock.workspace().hidden.iter().any(|(panel, _)| *panel == Panel::Export), "Export joins it, closed");
assert!(dock.workspace().hidden().iter().any(|(panel, _)| *panel == Panel::Export), "Export joins it, closed");
}
#[test]
fn a_focused_panel_is_raised_for_one_frame() {
let session = texturecraft_engine::sample_session(128, 32).unwrap();
let mut harness = egui_kittest::Harness::builder()
.with_size(vec2(1600.0, 1200.0))
.with_context_setup(crate::framework::install_headless)
.build_eframe(|cc| TextureCraftApp::new(cc, session));
let dock = &mut harness.state_mut().ui.dock;
dock.focus(Panel::Display);
assert_eq!(dock.raise, Some(Panel::Display));
harness.run_steps(4);
assert_eq!(harness.state().ui.dock.raise, None);
}
#[test]
@@ -779,8 +826,8 @@ mod tests {
dock.close(Panel::Viewport);
assert!(dock.is_open(Panel::Viewport));
let before = dock.clone();
dock.apply(Action::Float { panel: Panel::Viewport, rect: [0.0, 0.0, 300.0, 300.0] });
dock.apply(Action::Move { panel: Panel::Layers, anchor: Panel::Viewport, placement: Placement::Tab { before: None } });
dock.apply(Action::float(Panel::Viewport, Rect::from_min_size(egui::Pos2::ZERO, vec2(300.0, 300.0))));
dock.apply(Action::move_beside(Panel::Layers, Panel::Viewport, DockPlacement::tab(None)));
assert_eq!(dock, before);
}
@@ -804,8 +851,8 @@ mod tests {
let mut dock = Dock::default();
dock.focus(Panel::Display);
assert!(dock.is_visible(Panel::Display));
assert_eq!(dock.workspace().layout.floating.len(), 1);
assert!(dock.workspace().layout.floating[0].contains(&Panel::Display));
assert_eq!(dock.workspace().layout().floating.len(), 1);
assert!(dock.workspace().layout().floating[0].contains(&Panel::Display));
// Hiding and showing the views one by one.
dock.toggle(Panel::Display);
assert!(!dock.is_open(Panel::Display));
-54
View File
@@ -1,54 +0,0 @@
//! Positions dock tab titles within the tab strip and the gutter above it.
use craft_ui::docking::{Layout, Node};
use craft_ui::layout::SplitAxis;
use egui::text::{LayoutJob, TextFormat};
use egui::{Align, Color32, FontId, Ui};
use super::Panel;
/// Gap left between a header band and the panel above it, in points.
const HEADER_SEPARATION: f32 = 2.0;
/// How far a header under another panel reaches above its tab strip: the gutter between them, less the separation
pub(super) const HEADER_RISE: f32 = crate::theme::GUTTER as f32 - HEADER_SEPARATION;
/// Whether `panel`'s docked group sits under another panel, a gutter above its header; floating groups and the top row have none
pub(super) fn under_a_panel(layout: &Layout<Panel>, panel: Panel) -> bool {
layout.root.as_ref().and_then(|node| group_is_below_panel(node, panel, false)).unwrap_or(false)
}
fn group_is_below_panel(node: &Node<Panel>, panel: Panel, below_panel: bool) -> Option<bool> {
match node {
Node::Split { axis, first, second, .. } => {
group_is_below_panel(second, panel, below_panel || *axis == SplitAxis::Vertical).or_else(|| group_is_below_panel(first, panel, below_panel))
}
Node::Tabs { panels, .. } if panels.contains(&panel) => Some(below_panel),
Node::Dock { columns, .. } => {
columns.iter().find_map(|column| column.groups.iter().position(|group| group.panels.contains(&panel))).map(|index| below_panel || index > 0)
}
_ => None,
}
}
/// `name` laid out so that, centred as the dock centres every name, its capitals' middle sits `lift` above the strip's (a galley's height counts descenders)
pub(super) fn header_name(ui: &Ui, name: &str, font: FontId, color: Color32, lift_points: f32) -> LayoutJob {
let format = TextFormat { font_id: font, color, valign: Align::TOP, ..Default::default() };
let mut job = LayoutJob::single_section(name.to_owned(), format);
let galley = ui.painter().layout_job(job.clone());
// Scripts without capitals use the whole galley as their ink bounds
let capital = galley.rows.first().and_then(|row| row.glyphs.iter().find(|glyph| glyph.chr.is_uppercase()).map(|glyph| (row.pos.y, glyph)));
let ink_middle = capital.map_or(galley.size().y / 2.0, |(row_top, glyph)| row_top + glyph.pos.y + glyph.uv_rect.offset.y + glyph.uv_rect.size.y / 2.0);
// Room below the name raises it when centred, room above lowers it
let shift = ink_middle - galley.size().y / 2.0 + lift_points;
if shift < 0.0
&& let Some(section) = job.sections.first_mut()
{
section.format.valign = Align::BOTTOM;
}
job.first_row_min_height = galley.size().y + 2.0 * shift.abs();
job
}
@@ -1,101 +0,0 @@
//! The active tab in a panel group, drawn as a raised box joined to the panel body
use craft_ui::docking::{DockContent, Node};
use egui::text::TextWrapping;
use egui::{Rect, Stroke, StrokeKind, Ui, pos2};
use super::header_band::{HEADER_RISE, header_name, under_a_panel};
use super::{HEADER_TITLE_SIZE, Panel, Panels, area_id};
use crate::property_sheet::{full_height_tab_rect, shown_tab_box};
use crate::theme::semibold;
/// Horizontal padding of craft-ui's dock tab, in points
const DOCK_TAB_PADDING: f32 = 24.0;
/// From a panel's left edge to its header's name
pub(crate) const HEADER_TITLE_LEFT: f32 = DOCK_TAB_PADDING / 2.0;
/// Gap between the active tab's box and its neighbours, in points
const TAB_BOX_INSET: f32 = 4.0;
/// Insets the focus outline inside the tab's actual hit rect
const TAB_FOCUS_INSET: f32 = 2.0;
/// Width of the focus outline in points
const TAB_FOCUS_STROKE_WIDTH: f32 = 1.0;
/// The tab group containing `panel`; a collapsed stack has no tabs
fn group_of(node: &Node<Panel>, panel: Panel) -> Option<&[Panel]> {
match node {
Node::Split { first, second, .. } => group_of(first, panel).or_else(|| group_of(second, panel)),
Node::Tabs { panels, .. } if panels.contains(&panel) => Some(panels),
Node::Dock { columns, .. } => {
columns.iter().flat_map(|column| &column.groups).find(|group| group.panels.contains(&panel)).map(|group| group.panels.as_slice())
}
_ => None,
}
}
impl Panels<'_> {
/// How far a header band reaches above its tab strip
fn header_rise(&self, panel: Panel) -> f32 {
if under_a_panel(self.layout, panel) { HEADER_RISE } else { 0.0 }
}
/// How far a header name sits above the tab strip's centre
pub(super) fn header_lift(&self, panel: Panel) -> f32 {
self.header_rise(panel) / 2.0
}
/// Paints the active tab and its focus outline above the renderer's fallback paint
pub(super) fn paint_shown_group_tab(&self, ui: &Ui, panel: Panel) {
let layout = self.layout;
let in_group = layout
.root
.iter()
.chain(layout.floating.iter().map(|window| &window.root))
.find_map(|root| group_of(root, panel))
.is_some_and(|group| group.len() > 1);
if !in_group {
return;
}
// The shared renderer submits the active tab before it calls the panel body
let tab_id = area_id().with(("tab", &panel));
let Some(tab) = ui.ctx().read_response(tab_id) else { return };
let body = ui.max_rect();
let tab_rect = tab.rect;
if tab.layer_id != ui.layer_id() || tab_rect.bottom() != body.top() || tab_rect.left() < body.left() || tab_rect.right() > body.right() {
return;
}
let band_top = tab_rect.top() - self.header_rise(panel);
let box_left = if tab_rect.left() > body.left() { tab_rect.left() + TAB_BOX_INSET } else { tab_rect.left() };
let box_right = tab_rect.right() - TAB_BOX_INSET;
if box_left >= box_right {
return;
}
// Extend the body's clip over the header without widening it
let clip = ui.clip_rect();
let mut painter = ui.painter().clone();
painter.set_clip_rect(Rect::from_x_y_ranges(clip.x_range(), band_top..=clip.bottom()));
let band = Rect::from_x_y_ranges(body.x_range(), band_top..=tab_rect.bottom());
shown_tab_box(&painter, &self.tokens, full_height_tab_rect(band, box_left, box_right));
let name = self.logical_label(&panel).to_uppercase();
let font = semibold(HEADER_TITLE_SIZE);
let mut job = header_name(ui, &name, font, self.style.text, (tab_rect.top() - band_top) / 2.0);
job.wrap = TextWrapping::truncate_at_width((tab_rect.width() - DOCK_TAB_PADDING).max(0.0));
let galley = painter.layout_job(job);
let at = pos2(tab_rect.left() + HEADER_TITLE_LEFT, tab_rect.center().y - galley.size().y / 2.0);
painter.galley(at, galley, self.style.text);
// Preserve the shared dock's keyboard focus ring above the opaque selected tab
let pointer_focus = ui.data(|data| data.get_temp::<bool>(tab_id.with("pointer-focus"))).unwrap_or(false);
let focus_rect = tab_rect.shrink(TAB_FOCUS_INSET);
if tab.has_focus() && !pointer_focus && focus_rect.is_positive() {
painter.rect_stroke(focus_rect, 0.0, Stroke::new(TAB_FOCUS_STROKE_WIDTH, self.style.accent), StrokeKind::Inside);
}
}
}
+4 -2
View File
@@ -1474,8 +1474,10 @@ fn source_channel_popup(ui: &Ui, pending: &mut Option<PendingDrop>, maps: &mut [
}
}
});
// The app can consume Escape before the popup sees it, so read the raw event
let escaped = ui.input(|input| input.raw.events.iter().any(|event| matches!(event, egui::Event::Key { key: egui::Key::Escape, pressed: true, .. })));
// The app's shortcuts can consume Escape before the popup sees it, so read the raw event too; the runtime keeps an
// Escape nothing of TextureCraft's has focus for as the window's cancel, which the framework reads
let escaped = crate::framework::escape_pressed(ui.ctx())
|| ui.input(|input| input.raw.events.iter().any(|event| matches!(event, egui::Event::Key { key: egui::Key::Escape, pressed: true, .. })));
if picked.is_some() || escaped || shown.is_none_or(|menu| menu.response.should_close()) {
*pending = None;
}
+2 -2
View File
@@ -6,7 +6,6 @@
use std::panic::Location;
use std::path::PathBuf;
use std::sync::Arc;
pub use craft_dialogs::{Answer, FileDialog, Override, Request};
@@ -57,7 +56,7 @@ impl FileDialogs {
/// The dialogs of the app whose context is `ctx`: an answer wakes its event loop.
pub fn new(ctx: egui::Context) -> FileDialogs {
FileDialogs {
dialogs: craft_dialogs::Dialogs::new(Arc::new(move || ctx.request_repaint())),
dialogs: craft_dialogs::Dialogs::new(craft_dialogs::Wake::new(move || ctx.request_repaint())),
asked: Vec::new(),
headless: false,
shown_folders: Vec::new(),
@@ -162,6 +161,7 @@ impl TextureCraftApp {
let paths = match answer {
Answer::Paths(paths) => paths,
Answer::Saved { path, .. } => vec![path],
Answer::Unavailable(why) => {
self.toast(trf("The file dialog couldn't be shown: {error}", &[("error", &why)]), true);
Vec::new()
+1 -1
View File
@@ -161,7 +161,7 @@ impl UiFonts {
defs.families.entry(family).or_default().push(name.clone());
}
}
ctx.set_fonts(defs);
crate::theme::load_fonts(ctx, defs);
self.installed = want;
}
+214 -70
View File
@@ -6,7 +6,7 @@ use texturecraft_engine::compose::axis_frame::{placed_from_axis, placing_moves_p
use texturecraft_engine::compose::frame_placement::folded;
use texturecraft_engine::compose::pattern::{decal_axes, decal_corners};
use texturecraft_engine::core::{Decal, EffectKind, Fill, LayerId, LayerKind, Projection, Source};
use texturecraft_engine::geom::glam::Vec3;
use texturecraft_engine::geom::glam::{Vec2, Vec3};
use crate::TextureCraftApp;
use crate::projection_gizmo::{Gizmo, dragging};
@@ -14,8 +14,10 @@ use crate::theme::{AXIS_COLORS, SHAFT_HALO, SHAFT_HALO_EXTRA_WIDTH, SHAFT_WIDTH,
use crate::viewport::{project, view_ray};
mod frame_grab;
pub(crate) mod warp_toolbar;
pub(crate) use frame_grab::FrameGrab;
use warp_toolbar::{GizmoMode, GizmoSpace, WarpToolbarSettings, to_step};
/// The selected fill's frame as the 3D view shows it
#[derive(Clone, Copy, Debug)]
@@ -35,11 +37,16 @@ pub(crate) struct FrameGizmo {
pub arrows: [Option<Pos2>; 3],
/// On screen, the turn ring round the centre in the frame's plane (None when it is edge on)
pub ring: Option<[Pos2; TURN_RING_POINTS]>,
/// A warp's tool bar settings: which handles show, their size and snapping, and the space the arrows move in
pub tools: Option<WarpToolbarSettings>,
/// In the world: the frame's centre, and its across, up and out directions
origin: Vec3,
axes: [Vec3; 3],
/// Screen movement per world unit along each direction at the centre
steps: [Option<egui::Vec2>; 3],
/// The directions the arrows move along (the frame's own, or the world's in World space) and their screen movement per world unit
move_axes: [Vec3; 3],
move_steps: [Option<egui::Vec2>; 3],
}
/// Screen length of the axis arrows, and their heads (points): long enough to grab each one apart from the others
@@ -74,33 +81,7 @@ fn placeable_projection<'a>(projection: &'a Projection, sources: impl Iterator<I
impl FrameGizmo {
/// The frame of the selected fill layer, or of the selected mask fill effect, with a planar or warp projection
pub(crate) fn of(app: &TextureCraftApp, rect: Rect) -> Option<FrameGizmo> {
use texturecraft_engine::StackTarget;
if app.ui.mode != crate::state::Mode::Painting {
return None;
}
let layers = &app.session.doc.project;
let selected = app.session.selected_layer()?;
let (layer, effect, projection) = match app.session.target {
StackTarget::Content => {
let layer = layers.content_layer(selected)?;
let LayerKind::Fill(Fill { projection, sources, .. }) = &layer.kind else { return None };
(layer.id, None, placeable_projection(projection, sources.values())?)
}
StackTarget::Effect(effect) => {
// An instance can show a frame from its inherited mask
let owner = layers.mask_owner(selected);
let mask = layers.layer(owner).ok()?.mask.as_ref()?;
let mask_effect = mask.effects.iter().find(|candidate| candidate.id == effect)?;
let EffectKind::Fill { projection, source, .. } = &mask_effect.kind else { return None };
(owner, Some(effect), placeable_projection(projection, std::iter::once(source))?)
}
StackTarget::Mask => return None,
};
let (layer, effect, projection) = selected_fill_projection(app)?;
let placed = placed_from_axis(projection, app.viewport_mesh_bounds.get(&app.session.mesh));
// Match the panel by folding the projector transform into the frame first
@@ -125,16 +106,35 @@ impl FrameGizmo {
let sides = [0, 1, 2, 3].map(|side| corners[side].lerp(corners[(side + 1) % 4], 0.5));
let center = project(app, rect, origin)?;
let tools = warp.map(|_| app.ui.warp_toolbar);
let manipulator_scale = tools.map_or(1.0, |tools| tools.gizmo_scale());
let show_move = tools.is_none_or(|tools| tools.mode == GizmoMode::Move);
let show_ring = tools.is_none_or(|tools| tools.mode == GizmoMode::Rotate);
// Arrows use the same screen steps as the drag
let reach = decal.size[0].max(decal.size[1]);
let axes = [across, up, out];
let steps = axes.map(|axis| Some((project(app, rect, origin + axis * reach)? - center) / reach.max(f32::MIN_POSITIVE)));
let arrows = steps.map(|step| step.filter(|step| step.length() * reach > MIN_SCREEN_SPAN).map(|step| center + step.normalized() * ARROW));
let step_along = |axis: Vec3| Some((project(app, rect, origin + axis * reach)? - center) / reach.max(f32::MIN_POSITIVE));
let steps = axes.map(step_along);
let (move_axes, move_steps) = if show_move && tools.is_some_and(|tools| tools.space == GizmoSpace::World) {
let world_axes = [Vec3::X, Vec3::Y, Vec3::Z];
(world_axes, world_axes.map(step_along))
} else {
(axes, steps)
};
let arrows = if show_move {
move_steps
.map(|step| step.filter(|step| step.length() * reach > MIN_SCREEN_SPAN).map(|step| center + step.normalized() * ARROW * manipulator_scale))
} else {
[None; 3]
};
// The ring can still project when an arrow's endpoint is behind the camera
let ring = if ring_open(app, rect, center, out) { turn_ring(app, rect, center, origin, across, up) } else { None };
let ring_radius = TURN_RING * manipulator_scale;
let ring =
if show_ring && ring_open(app, rect, center, out, ring_radius) { turn_ring(app, rect, center, origin, across, up, ring_radius) } else { None };
Some(FrameGizmo { layer, effect, decal, warp, corners, sides, center, arrows, ring, origin, axes, steps })
Some(FrameGizmo { layer, effect, decal, warp, corners, sides, center, arrows, ring, tools, origin, axes, steps, move_axes, move_steps })
}
/// The frame's offset after sliding it across its plane by screen movement `delta` (None when the frame is edge-on)
@@ -143,6 +143,16 @@ impl FrameGizmo {
Some(self.slid(across, up))
}
/// The tool bar's grid step and angle step (0: no snapping) while a drag snaps
fn snap_steps(&self, snapping: bool) -> (f32, f32) {
self.tools.filter(|_| snapping).map_or((0.0, 0.0), |tools| (tools.grid_step(), tools.angle_step()))
}
/// Whether the tool bar's mode offers `grab` (a planar's frame, with no tool bar, offers every handle but Place on surface's)
fn offers(&self, grab: FrameGrab) -> bool {
self.tools.map_or(grab != FrameGrab::Place, |tools| grab.offered_in(tools.mode))
}
/// Where screen point `p` meets the frame's plane, across and up in frame sizes from its centre
fn on_plane(&self, app: &TextureCraftApp, rect: Rect, p: Pos2) -> Option<[f32; 2]> {
let ray = view_ray(app, rect, p);
@@ -164,6 +174,36 @@ impl FrameGizmo {
}
}
/// The selected fill layer or mask effect and its projection, if eligible to show a frame in Painting mode
fn selected_fill_projection(app: &TextureCraftApp) -> Option<(LayerId, Option<LayerId>, &Projection)> {
use texturecraft_engine::StackTarget;
if app.ui.mode != crate::state::Mode::Painting {
return None;
}
let layers = &app.session.doc.project;
let selected = app.session.selected_layer()?;
match app.session.target {
StackTarget::Content => {
let layer = layers.content_layer(selected)?;
let LayerKind::Fill(Fill { projection, sources, .. }) = &layer.kind else { return None };
Some((layer.id, None, placeable_projection(projection, sources.values())?))
}
StackTarget::Effect(effect) => {
// Only the selected layer's effective mask may supply a frame, including an instance's inherited mask
let owner = layers.mask_owner(selected);
let mask = layers.layer(owner).ok()?.mask.as_ref()?;
let mask_effect = mask.effects.iter().find(|candidate| candidate.id == effect)?;
let EffectKind::Fill { projection, source, .. } = &mask_effect.kind else { return None };
Some((owner, Some(effect), placeable_projection(projection, std::iter::once(source))?))
}
StackTarget::Mask => None,
}
}
/// Half a turn in degrees: a ring drag's sweep is kept within one either way
const HALF_TURN: f32 = 180.0;
@@ -176,16 +216,13 @@ pub(crate) const EDGE_ON_FACING: f32 = 1e-4;
/// The smallest length a direction spans on screen to point somewhere (points): shorter, it points at the camera
pub(crate) const MIN_SCREEN_SPAN: f32 = 1.0;
/// The smallest cosine between the view ray and a turn ring's axis for the ring to show: flatter, its half height on screen is under its drawn line's width, it reads as a line and a drag along it turns half a turn at once across the centre
const MIN_RING_FACING: f32 = (SHAFT_WIDTH + SHAFT_HALO_EXTRA_WIDTH) / TURN_RING;
/// Whether a turn ring round `axis`, centred on screen at `center`, is seen open enough to show and grab
pub(crate) fn ring_open(app: &TextureCraftApp, rect: Rect, center: Pos2, axis: Vec3) -> bool {
view_ray(app, rect, center).dir.dot(axis).abs() >= MIN_RING_FACING
/// A ring seen edge-on reads as a line until its foreshortened radius clears its stroke.
pub(crate) fn ring_open(app: &TextureCraftApp, rect: Rect, center: Pos2, axis: Vec3, radius_points: f32) -> bool {
view_ray(app, rect, center).dir.dot(axis).abs() >= (SHAFT_WIDTH + SHAFT_HALO_EXTRA_WIDTH) / radius_points
}
/// Project a circle in the frame's plane whose longest screen reach is `TURN_RING` points.
fn turn_ring(app: &TextureCraftApp, rect: Rect, center: Pos2, origin: Vec3, across: Vec3, up: Vec3) -> Option<[Pos2; TURN_RING_POINTS]> {
/// Project a circle in the frame's plane with the requested screen reach in points
fn turn_ring(app: &TextureCraftApp, rect: Rect, center: Pos2, origin: Vec3, across: Vec3, up: Vec3, radius_points: f32) -> Option<[Pos2; TURN_RING_POINTS]> {
const RING_SEGMENTS: usize = TURN_RING_POINTS - 1;
let view_projection = app.session.camera.view_proj(rect.width() / rect.height().max(1.0));
@@ -206,13 +243,13 @@ fn turn_ring(app: &TextureCraftApp, rect: Rect, center: Pos2, origin: Vec3, acro
across_step * cos + up_step * sin
});
// Solve radius * length(xy) / (1 + radius * z) <= TURN_RING for every sample
let limiting_growth = ring_steps.iter().map(|step| step.truncate().length() - TURN_RING * step.z).fold(0.0, f32::max);
// Solve radius * length(xy) / (1 + radius * z) <= radius_points for every sample
let limiting_growth = ring_steps.iter().map(|step| step.truncate().length() - radius_points * step.z).fold(0.0, f32::max);
if !limiting_growth.is_finite() || limiting_growth <= f32::EPSILON {
return None;
}
let radius = TURN_RING / limiting_growth;
let radius = radius_points / limiting_growth;
let mut ring = [center; TURN_RING_POINTS];
for (point, step) in ring.iter_mut().zip(ring_steps) {
let depth = 1.0 + radius * step.z;
@@ -222,6 +259,7 @@ fn turn_ring(app: &TextureCraftApp, rect: Rect, center: Pos2, origin: Vec3, acro
*point += vec2(step.x, step.y) * (radius / depth);
}
ring[RING_SEGMENTS] = ring[0];
Some(ring)
@@ -255,6 +293,7 @@ pub(crate) fn nearest<T: Copy>(handles: impl IntoIterator<Item = (T, f32)>) -> O
best = Some((handle, distance));
}
}
best.map(|(handle, _)| handle)
}
@@ -273,37 +312,54 @@ impl Gizmo for FrameGizmo {
/// The handle under screen point `p`: the nearest one within reach, so a small frame's corners stay grabbable beside its arrows
fn grab(&self, at: Pos2) -> Option<FrameGrab> {
let mut handles = vec![(FrameGrab::Slide, center_distance(self.center, at))];
handles.extend((0..3).filter_map(|axis| Some((FrameGrab::Axis(axis), arrow_distance(at, self.center, self.arrows[axis]?)))));
let near = |points: [Pos2; 4], grab: fn(usize) -> FrameGrab| (0..4).map(move |index| (grab(index), points[index].distance(at)));
match self.warp {
Some(_) => handles.extend(near(self.corners, FrameGrab::Corner)),
None => handles.extend(near(self.corners, |_| FrameGrab::Scale)),
}
handles.extend(near(self.sides, FrameGrab::Side));
if let Some(ring) = &self.ring {
handles.push((FrameGrab::Turn, ring.windows(2).map(|pair| distance_to_segment(at, pair[0], pair[1])).fold(f32::INFINITY, f32::min)));
}
nearest(handles)
let slide = self.offers(FrameGrab::Slide).then(|| (FrameGrab::Slide, center_distance(self.center, at)));
let arrows = self.arrows.into_iter().enumerate().filter_map(|(axis, tip)| Some((FrameGrab::Axis(axis), arrow_distance(at, self.center, tip?))));
let corners = self.corners.into_iter().enumerate().map(|(index, corner)| {
let grab = if self.warp.is_some() { FrameGrab::Corner(index) } else { FrameGrab::Scale };
(grab, corner.distance(at))
});
let sides = self.sides.into_iter().enumerate().filter_map(|(index, side)| {
let grab = FrameGrab::Side(index);
self.offers(grab).then(|| (grab, side.distance(at)))
});
let turn = self.ring.as_ref().map(|ring| {
let distance = ring.windows(2).map(|pair| distance_to_segment(at, pair[0], pair[1])).fold(f32::INFINITY, f32::min);
(FrameGrab::Turn, distance)
});
// Place on surface takes any press the handles do not: just within reach, so a nearer corner wins
let place = self.offers(FrameGrab::Place).then_some((FrameGrab::Place, GRAB));
nearest(slide.into_iter().chain(arrows).chain(corners).chain(sides).chain(turn).chain(place))
}
fn same_projection(&self, other: &FrameGizmo) -> bool {
self.layer == other.layer && self.effect == other.effect
self.layer == other.layer && self.effect == other.effect && self.warp.is_some() == other.warp.is_some()
}
/// The command and params a drag of `grab` from `from` to `to` runs
fn edit(&self, app: &TextureCraftApp, rect: Rect, grab: FrameGrab, from: Pos2, to: Pos2) -> Option<(&'static str, Value)> {
self.edit_with_snap(app, rect, grab, from, to, false)
}
/// As [`Gizmo::edit`]; with `snapping` a warp's moves and turns jump by the tool bar's grid and angle steps
fn edit_with_snap(&self, app: &TextureCraftApp, rect: Rect, grab: FrameGrab, from: Pos2, to: Pos2, snapping: bool) -> Option<(&'static str, Value)> {
let delta = to - from;
let center = self.center;
let (grid_step, angle_step) = self.snap_steps(snapping);
let world = self.tools.is_some_and(|tools| tools.space == GizmoSpace::World);
let mut params = match grab {
FrameGrab::Slide => json!({"offset": self.slid_on_screen(delta)?}),
FrameGrab::Slide => {
let [across, up] = solve(self.steps[0]?, self.steps[1]?, delta)?;
json!({"offset": self.slid(to_step(across, grid_step), to_step(up, grid_step))})
}
FrameGrab::Axis(axis) => {
let step = (*self.steps.get(axis)?)?;
let distance = delta.dot(step) / step.length_sq().max(f32::MIN_POSITIVE);
let step = (*self.move_steps.get(axis)?)?;
let distance_world = to_step(delta.dot(step) / step.length_sq().max(f32::MIN_POSITIVE), grid_step);
match axis {
0 => json!({"offset": self.slid(distance, 0.0)}),
1 => json!({"offset": self.slid(0.0, distance)}),
_ => json!({"position": (self.origin + self.axes[2] * distance).to_array(), "normal": self.axes[2].to_array()}),
0 if !world => json!({"offset": self.slid(distance_world, 0.0)}),
1 if !world => json!({"offset": self.slid(0.0, distance_world)}),
_ => json!({"position": (self.origin + self.move_axes[axis] * distance_world).to_array(), "normal": self.axes[2].to_array()}),
}
}
FrameGrab::Scale => {
@@ -317,12 +373,25 @@ impl Gizmo for FrameGizmo {
size[1 - side % 2] *= stretch;
json!({"size": size})
}
FrameGrab::Place => {
let on_view = to - rect.min;
let hit = app.session.pick(Vec2::new(on_view.x, on_view.y), app.session.viewport)?;
let project = &app.session.doc.project;
let (owner_set, _, _) = project.locate(self.layer)?;
// A world-space placement must belong to the edited fill's texture set
if hit.material != project.texture_set(owner_set).ok()?.material {
return None;
}
json!({"position": hit.pos.to_array(), "normal": hit.nrm.to_array()})
}
FrameGrab::Turn => {
// Measure the turn in the frame's own plane so a tilted frame follows the pointer
let angle = |p: Pos2| self.on_plane(app, rect, p).map(|[across, up]| (up * self.decal.size[1]).atan2(across * self.decal.size[0]).to_degrees());
let swept = angle(to)? - angle(from)?;
let swept = (swept + HALF_TURN).rem_euclid(2.0 * HALF_TURN) - HALF_TURN;
json!({"rotation": self.decal.rotation + swept})
json!({"rotation": self.decal.rotation + to_step(swept, angle_step)})
}
FrameGrab::Corner(corner) => {
let mut corners = self.warp?;
@@ -332,10 +401,12 @@ impl Gizmo for FrameGizmo {
json!({"warpCorners": corners})
}
};
params["layer"] = json!(self.layer.0);
if let Some(effect) = self.effect {
params["effect"] = json!(effect.0);
}
let command = if matches!(grab, FrameGrab::Corner(_)) { "layer.fill.projection" } else { "layer.decal.set" };
Some((command, params))
}
@@ -354,14 +425,16 @@ pub(crate) fn overlay(ui: &Ui, rect: Rect, gizmo: &FrameGizmo) {
let lit = |grab: FrameGrab| active == Some(grab) || (active.is_none() && hovered == Some(grab));
let dot_fill = |grab: FrameGrab| if lit(grab) { tokens.viewport_accent } else { Color32::WHITE };
let mut outline = gizmo.corners.to_vec();
outline.push(gizmo.corners[0]);
let [first, second, third, fourth] = gizmo.corners;
let outline = [first, second, third, fourth, first];
dashed_outline(&painter, &outline);
if let Some(ring) = &gizmo.ring {
let color = if lit(FrameGrab::Turn) { tokens.viewport_accent } else { AXIS_COLORS[2] };
painter.add(egui::Shape::line(ring.to_vec(), Stroke::new(SHAFT_WIDTH + SHAFT_HALO_EXTRA_WIDTH, SHAFT_HALO)));
painter.add(egui::Shape::line(ring.to_vec(), Stroke::new(SHAFT_WIDTH, color)));
}
match gizmo.warp {
Some(_) => {
for (index, corner) in gizmo.corners.into_iter().enumerate() {
@@ -374,12 +447,15 @@ pub(crate) fn overlay(ui: &Ui, rect: Rect, gizmo: &FrameGizmo) {
}
}
}
for (index, side) in gizmo.sides.into_iter().enumerate() {
for (index, side) in gizmo.sides.into_iter().enumerate().filter(|(index, _)| gizmo.offers(FrameGrab::Side(*index))) {
handle_dot(&painter, side, SIDE_DOT, dot_fill(FrameGrab::Side(index)));
}
let arrow_color = |axis: usize| if lit(FrameGrab::Axis(axis)) { tokens.viewport_accent } else { AXIS_COLORS[axis] };
move_handles(&painter, gizmo.center, gizmo.arrows, arrow_color, dot_fill(FrameGrab::Slide));
if gizmo.offers(FrameGrab::Slide) {
move_handles(&painter, gizmo.center, gizmo.arrows, arrow_color, dot_fill(FrameGrab::Slide));
}
}
/// The centre square (filled `square`) with its X/Y/Z arrows to `arrows`, coloured by `arrow_color`; shafts and heads over a dark halo like the symmetry manipulator's
@@ -447,11 +523,17 @@ pub(crate) mod tests {
let session = Session::new_project("Gizmo", texturecraft_engine::geom::primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 128).unwrap();
let builder = egui_kittest::Harness::builder().with_size(TEST_WINDOW);
let builder = if render { builder.wgpu() } else { builder };
let mut harness = builder.build_eframe(|context| TextureCraftApp::new(context, session));
let mut harness = builder.with_context_setup(crate::framework::install_headless).build_eframe(|context| TextureCraftApp::new(context, session));
harness.run_steps(4);
harness
}
/// A warp's gizmo in `mode`, as the tool bar's buttons set it (a planar's has no modes)
pub(crate) fn show_handles(harness: &mut egui_kittest::Harness<'_, TextureCraftApp>, mode: GizmoMode) {
harness.state_mut().ui.warp_toolbar.mode = mode;
harness.run_steps(2);
}
/// The ball with a selected fill layer projecting `projection`
pub(crate) fn fill_app(projection: &str) -> (egui_kittest::Harness<'static, TextureCraftApp>, LayerId) {
fill_app_with(json!({"projection": projection}))
@@ -548,7 +630,7 @@ pub(crate) mod tests {
["X", "Y", "Z"].map(|tag| harness.get_by_label(&format!("{row} {tag}")).accesskit_node().numeric_value().unwrap() as f32)
}
fn gizmo(harness: &egui_kittest::Harness<'_, TextureCraftApp>) -> FrameGizmo {
pub(crate) fn gizmo(harness: &egui_kittest::Harness<'_, TextureCraftApp>) -> FrameGizmo {
FrameGizmo::of(harness.state(), harness.state().viewport_rect).unwrap()
}
@@ -674,6 +756,7 @@ pub(crate) mod tests {
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
for kind in ["warp", "planar"] {
let (mut harness, _) = fill_app(kind);
show_handles(&mut harness, GizmoMode::Rotate);
let start = gizmo(&harness);
let ring = start.ring.unwrap_or_else(|| panic!("{kind}: a frame facing the camera shows its ring"));
let on_ring = *ring
@@ -696,6 +779,7 @@ pub(crate) mod tests {
}
let (mut harness, layer) = fill_app("warp");
show_handles(&mut harness, GizmoMode::Scale);
let warp = gizmo(&harness);
assert_eq!(warp.grab(warp.sides[1]), Some(FrameGrab::Side(1)));
@@ -717,6 +801,7 @@ pub(crate) mod tests {
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
for kind in ["planar", "warp"] {
let (mut harness, _) = fill_app(kind);
show_handles(&mut harness, GizmoMode::Rotate);
let mut foreshortened_shown = false;
// A distant view isolates the foreshortening
@@ -743,6 +828,26 @@ pub(crate) mod tests {
}
}
#[test]
fn an_oblique_warp_ring_opens_when_its_scaled_height_clears_the_stroke() {
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let (mut harness, _) = fill_app("warp");
show_handles(&mut harness, GizmoMode::Rotate);
let camera = &mut harness.state_mut().session.camera;
camera.ortho = true;
camera.set_angles(87.0_f32.to_radians(), 0.0);
let base_size = harness.state().ui.warp_toolbar.manipulator_size;
harness.state_mut().ui.warp_toolbar.manipulator_size = base_size * 0.5;
let small = gizmo(&harness);
harness.state_mut().ui.warp_toolbar.manipulator_size = base_size * 2.0;
let large = gizmo(&harness);
assert!(small.ring.is_none(), "a ring narrower than its stroke stays hidden");
let ring = large.ring.expect("the enlarged ring clears its stroke at the same angle");
assert!(ring.iter().any(|point| large.grab(*point) == Some(FrameGrab::Turn)));
}
#[test]
fn the_ring_keeps_its_screen_size_when_the_oblique_frame_is_turning_near_the_camera() {
const FRAME_SIDE: f32 = 4.0;
@@ -756,6 +861,13 @@ pub(crate) mod tests {
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
for kind in ["planar", "warp"] {
let (mut harness, layer) = fill_app(kind);
show_handles(&mut harness, GizmoMode::Rotate);
let expected_radius = if kind == "warp" {
harness.state_mut().ui.warp_toolbar.manipulator_size *= 2.0;
TURN_RING * 2.0
} else {
TURN_RING
};
let camera = &mut harness.state_mut().session.camera;
camera.distance = CAMERA_DISTANCE;
camera.set_angles(ORBIT_DEGREES.to_radians(), 0.0);
@@ -771,7 +883,7 @@ pub(crate) mod tests {
let reach = ring.iter().map(|point| point.distance(shown.center)).fold(0.0, f32::max);
assert!(
(TURN_RING * MIN_RING_SHARE..=TURN_RING * MAX_RING_SHARE).contains(&reach),
(expected_radius * MIN_RING_SHARE..=expected_radius * MAX_RING_SHARE).contains(&reach),
"{kind} turned {rotation_degrees} degrees: the ring reaches {reach} points"
);
}
@@ -855,6 +967,38 @@ pub(crate) mod tests {
harness.run_steps(2);
}
#[test]
fn a_place_drag_ends_if_the_project_or_projection_is_replaced() {
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
for replace_project in [true, false] {
let (mut harness, layer) = fill_app("warp");
show_handles(&mut harness, GizmoMode::PlaceOnSurface);
let center = gizmo(&harness).center;
let held = center + vec2(24.0, 8.0);
press_and_move(&mut harness, center, held, Modifiers::NONE);
let start = std::sync::Arc::downgrade(&dragging::<FrameGizmo>(&harness.ctx).unwrap().start);
let next_kind = if replace_project {
harness.state_mut().run("project.new", json!({"mesh": "sphere", "resolution": 128})).unwrap();
let new_layer = harness.state_mut().run("layer.add.fill", json!({})).unwrap();
assert_eq!(new_layer["layer"], layer.0, "the new project reuses the local layer ID");
"warp"
} else {
"planar"
};
harness.state_mut().run("layer.fill.projection", json!({"layer": layer.0, "projection": next_kind})).unwrap();
let before = projection(&harness, layer);
let steps = harness.state().session.history_labels().len();
harness.event(egui::Event::PointerMoved(held + vec2(8.0, 8.0)));
harness.run_steps(2);
assert_eq!(projection(&harness, layer), before, "the old drag must not move the replacement {next_kind}");
assert_eq!(harness.state().session.history_labels().len(), steps);
assert!(start.upgrade().is_none(), "release the captured geometry while the pointer is still held");
}
}
/// A drag whose first edit changes nothing (its arrow pulled further past the offset limit) makes no undo step, so its later edits make the drag's own step instead of joining the edit before it
#[test]
fn a_drag_that_first_changes_nothing_keeps_its_own_undo_step() {
@@ -1,3 +1,5 @@
use super::warp_toolbar::GizmoMode;
/// What a drag on the frame does
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum FrameGrab {
@@ -13,15 +15,29 @@ pub(crate) enum FrameGrab {
Corner(usize),
/// The ring: turn it round its normal
Turn,
/// Place on surface: anywhere over the model puts the frame where the pointer touches it
Place,
}
impl FrameGrab {
/// Whether a warp's gizmo in `mode` offers this handle: its corners stay in every mode
pub(super) fn offered_in(self, mode: GizmoMode) -> bool {
match self {
FrameGrab::Slide | FrameGrab::Axis(_) => mode == GizmoMode::Move,
FrameGrab::Turn => mode == GizmoMode::Rotate,
FrameGrab::Side(_) => mode == GizmoMode::Scale,
FrameGrab::Place => mode == GizmoMode::PlaceOnSurface,
FrameGrab::Scale | FrameGrab::Corner(_) => true,
}
}
pub(super) fn cursor(self, dragging: bool) -> egui::CursorIcon {
match self {
FrameGrab::Slide if dragging => egui::CursorIcon::Grabbing,
FrameGrab::Slide => egui::CursorIcon::Grab,
FrameGrab::Axis(_) | FrameGrab::Corner(_) | FrameGrab::Turn => egui::CursorIcon::Move,
FrameGrab::Scale => egui::CursorIcon::ResizeNwSe,
FrameGrab::Place => egui::CursorIcon::Crosshair,
FrameGrab::Side(side) if side % 2 == 0 => egui::CursorIcon::ResizeVertical,
FrameGrab::Side(_) => egui::CursorIcon::ResizeHorizontal,
}
@@ -0,0 +1,11 @@
use serde::{Deserialize, Serialize};
/// What a warp's frame gizmo does: Move shows the arrows and centre square, Rotate the turn ring, Scale the edge dots that size the frame; Place on surface puts the frame where a drag over the model touches it
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum GizmoMode {
#[default]
Move,
Rotate,
Scale,
PlaceOnSurface,
}
@@ -0,0 +1,9 @@
use serde::{Deserialize, Serialize};
/// The directions a warp's move arrows follow: the frame's own, or the world's
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum GizmoSpace {
#[default]
Object,
World,
}
@@ -0,0 +1,383 @@
//! The warp controls of the top tool bar while the selected fill projects through a warp, in place of the tool's own: the transform tool's settings, the warp mode, the gizmo's mode and space, the mirrors and the resets
mod gizmo_mode;
mod gizmo_space;
mod snap;
mod warp_target;
mod warp_toolbar_settings;
use egui::Ui;
use egui_phosphor::regular as ic;
use serde_json::json;
pub use gizmo_mode::GizmoMode;
pub use gizmo_space::GizmoSpace;
pub(crate) use snap::to_step;
pub use warp_toolbar_settings::WarpToolbarSettings;
use crate::TextureCraftApp;
use crate::i18n::tr;
use crate::toolbar::icon_dropdown;
use crate::widgets::{icon_button, icon_dropdown_button};
use texturecraft_engine::core::Projection;
pub(crate) use warp_target::WarpTarget;
use warp_toolbar_settings::{ANGLE_STEPS, GRID_STEPS, MANIPULATOR_SIZES};
/// The width of the settings popup (points)
const POPUP_WIDTH: f32 = 220.0;
/// The gizmo mode buttons: mode, icon, label
const MODES: [(GizmoMode, &str, &str); 4] = [
(GizmoMode::Move, ic::ARROWS_OUT_CARDINAL, "Move"),
(GizmoMode::Rotate, ic::ARROWS_CLOCKWISE, "Rotate"),
(GizmoMode::Scale, ic::CORNERS_OUT, "Scale"),
(GizmoMode::PlaceOnSurface, ic::ARROW_LINE_DOWN, "Place on surface"),
];
/// The warp modes the bar lists; only the first works until the warp has a grid of vertices
const WARP_MODES: [&str; 5] = ["Transform warp", "Edit vertices", "Split both directions", "Split horizontally", "Split vertically"];
/// Why the warp modes past the first and the vertex reset are greyed out
const NEEDS_GRID: &str = "Needs the warp grid, which is not available yet";
/// The warp controls of the top tool bar, left to right
pub(crate) fn controls(app: &mut TextureCraftApp, ui: &mut Ui, target: WarpTarget) {
let size = ui.spacing().interact_size.y;
// The only tool there is, so it stays on
icon_button(ui, ic::BOUNDING_BOX, tr("Transform tool"), true, size);
manipulator_settings(app, ui, size);
warp_mode(ui);
ui.separator();
let current = app.ui.warp_toolbar.mode;
for (mode, icon, label) in MODES {
if icon_button(ui, icon, tr(label), current == mode, size).clicked() {
app.ui.warp_toolbar.mode = mode;
}
}
gizmo_space(app, ui);
ui.separator();
for (axis, icon, label, field) in [(0, ic::FLIP_HORIZONTAL, "Mirror horizontally", "flipU"), (1, ic::FLIP_VERTICAL, "Mirror vertically", "flipV")] {
if icon_button(ui, icon, tr(label), target.flip[axis], size).clicked() {
let mut fields = json!({});
fields[field] = json!(!target.flip[axis]);
app.run("layer.decal.set", target.params(fields));
}
}
resets(app, ui, &target);
}
/// The settings popup of the transform tool: the gizmo's size and the steps its drags snap to
fn manipulator_settings(app: &mut TextureCraftApp, ui: &mut Ui, size: f32) {
let popup_id = ui.make_persistent_id("warp_manipulator_settings");
let open = egui::Popup::is_id_open(ui.ctx(), popup_id);
let response = icon_dropdown_button(ui, ic::GEAR, tr("Manipulator settings"), open, size);
let response = if open { response } else { response.on_hover_text(tr("Manipulator settings")) };
// Sliders sit in the popup, so a click inside must not close it
egui::Popup::menu(&response).id(popup_id).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| {
ui.set_width(POPUP_WIDTH);
ui.label(egui::RichText::new(tr("MANIPULATOR SETTINGS")).strong());
let settings = &mut app.ui.warp_toolbar;
ui.add(egui::Slider::new(&mut settings.manipulator_size, MANIPULATOR_SIZES).text(tr("Manipulator size")).fixed_decimals(2));
ui.add(egui::Slider::new(&mut settings.grid_steps, GRID_STEPS).text(tr("Grid steps")).fixed_decimals(2))
.on_hover_text(tr("Hold Ctrl while dragging to move in these steps"));
ui.add(egui::Slider::new(&mut settings.angle_steps, ANGLE_STEPS).text(tr("Angle steps")).fixed_decimals(0))
.on_hover_text(tr("Hold Ctrl while dragging to turn in these steps"));
});
}
/// The warp mode list: Transform warp works; the others wait for the warp grid
fn warp_mode(ui: &mut Ui) {
icon_dropdown(ui, "warp_mode", ic::FRAME_CORNERS, tr(WARP_MODES[0]), |ui| {
for (index, label) in WARP_MODES.into_iter().enumerate() {
let unavailable = (index > 0).then(|| tr(NEEDS_GRID));
menu_row(ui, tr(label), index == 0, unavailable);
}
});
}
/// Object space or World space: the directions the move arrows follow
fn gizmo_space(app: &mut TextureCraftApp, ui: &mut Ui) {
let spaces = [(GizmoSpace::Object, ic::CUBE, "Object space"), (GizmoSpace::World, ic::GLOBE, "World space")];
let current = app.ui.warp_toolbar.space;
let (_, icon, label) = spaces.iter().find(|(space, ..)| *space == current).unwrap_or(&spaces[0]);
let mut chosen = None;
icon_dropdown(ui, "warp_space", icon, tr(label), |ui| {
for (space, _, label) in spaces {
if menu_row(ui, tr(label), current == space, None) {
chosen = Some(space);
}
}
});
if let Some(space) = chosen {
app.ui.warp_toolbar.space = space;
}
}
/// The reset list: the frame back around the mesh, or the corners back on the frame
fn resets(app: &mut TextureCraftApp, ui: &mut Ui, target: &WarpTarget) {
let mut command = None;
icon_dropdown(ui, "warp_reset", ic::ARROW_COUNTER_CLOCKWISE, tr("Reset"), |ui| {
if menu_row(ui, tr("Reset warp transform"), false, None) {
command = Some(("layer.fill.resetFrame", json!({"keepCorners": true})));
}
if menu_row(ui, tr("Reset all vertices"), false, None) {
command = Some(("layer.fill.projection", json!({"warpCorners": Projection::FRAME_CORNERS})));
}
// Vertices cannot be selected before the warp has a grid
menu_row(ui, tr("Reset selected vertices"), false, Some(tr(NEEDS_GRID)));
});
if let Some((id, fields)) = command {
app.run(id, target.params(fields));
}
}
/// One list entry; `unavailable` greys it out and says why on hover. Returns true when clicked
fn menu_row(ui: &mut Ui, label: &str, selected: bool, unavailable: Option<&str>) -> bool {
let response = ui.add_enabled(unavailable.is_none(), egui::Button::new(label).selected(selected));
if let Some(reason) = unavailable {
response.on_disabled_hover_text(reason);
return false;
}
response.clicked()
}
#[cfg(test)]
mod tests {
use egui::accesskit::Role;
use egui::{Modifiers, Pos2, vec2};
use egui_kittest::Harness;
use egui_kittest::kittest::Queryable;
use serde_json::json;
use texturecraft_engine::core::Projection;
use texturecraft_engine::geom::glam::{Vec2, Vec3};
use super::*;
use crate::frame_gizmo::FrameGrab;
use crate::frame_gizmo::tests::{drag, fill_app, gizmo, projection};
use crate::projection_gizmo::Gizmo;
fn click_label(harness: &mut Harness<'_, TextureCraftApp>, label: &str) {
harness.get_by_label(label).click();
harness.run_steps(2);
}
/// The warp's frame and corners
fn warp_parts(harness: &Harness<'_, TextureCraftApp>, layer: texturecraft_engine::core::LayerId) -> (texturecraft_engine::core::Decal, [[f32; 2]; 4]) {
let Projection::Warp { frame, corners, .. } = projection(harness, layer) else { panic!("a warp") };
(frame, corners)
}
#[test]
fn the_bar_shows_for_a_warp_fill_only() {
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let (mut harness, layer) = fill_app("warp");
assert!(harness.query_by_label("Transform tool").is_some());
harness.state_mut().run("layer.fill.projection", json!({"layer": layer.0, "projection": "planar"}));
harness.run_steps(2);
assert!(harness.query_by_label("Transform tool").is_none(), "a planar frame has no warp tools");
let away = harness.state().viewport_rect.left_bottom() + vec2(10.0, -10.0);
assert_eq!(gizmo(&harness).grab(away), None, "a planar frame has no Place on surface");
}
#[test]
fn each_mode_offers_only_its_handles() {
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let (mut harness, _) = fill_app("warp");
let start = gizmo(&harness);
click_label(&mut harness, "Rotate");
let ring = gizmo(&harness).ring.expect("a frame facing the camera shows its ring");
let ring_point = *ring.iter().max_by(|first, second| first.y.total_cmp(&second.y)).unwrap();
let handles: [(FrameGrab, Pos2, GizmoMode); 4] = [
(FrameGrab::Slide, start.center, GizmoMode::Move),
(FrameGrab::Axis(0), start.arrows[0].unwrap(), GizmoMode::Move),
(FrameGrab::Turn, ring_point, GizmoMode::Rotate),
(FrameGrab::Side(1), start.sides[1], GizmoMode::Scale),
];
for (_, _, label) in MODES {
click_label(&mut harness, label);
let shown = gizmo(&harness);
let mode = shown.tools.unwrap().mode;
for (grab, at, offered_in) in handles {
assert_eq!(shown.grab(at) == Some(grab), mode == offered_in, "{grab:?} in {mode:?}");
}
assert_eq!(shown.grab(shown.corners[1]), Some(FrameGrab::Corner(1)), "a warp's corners stay in {mode:?}");
}
}
#[test]
fn place_on_surface_puts_the_frame_where_the_pointer_touches_the_model() {
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let (mut harness, layer) = fill_app("warp");
let rect = harness.state().viewport_rect;
let middle = crate::viewport::project(harness.state(), rect, Vec3::ZERO).unwrap();
let (from, onto) = (middle + vec2(30.0, 20.0), middle + vec2(-60.0, -40.0));
let steps = harness.state().session.history_labels().len();
let (before, corners_before) = warp_parts(&harness, layer);
click_label(&mut harness, "Place on surface");
drag(&mut harness, from, onto, Modifiers::NONE);
let (placed, corners) = warp_parts(&harness, layer);
let on_view = onto - rect.min;
let hit = harness.state().session.pick(Vec2::new(on_view.x, on_view.y), harness.state().session.viewport).expect("the model is under the pointer");
assert!(Vec3::from(placed.center).distance(hit.pos) < 1e-2, "the frame centre sits at the surface hit: {:?} {:?}", placed.center, hit.pos);
assert!(Vec3::from(placed.normal).dot(hit.nrm) > 0.99, "the frame faces along the surface normal");
assert_eq!((placed.size, placed.rotation, corners), (before.size, before.rotation, corners_before), "its size, rotation and corners stay");
assert_eq!(harness.state().session.history_labels().len(), steps + 1, "one undo step per drag");
// Past the model's edge the frame waits where it last touched it
drag(&mut harness, onto, rect.left_bottom() + vec2(10.0, -10.0), Modifiers::NONE);
let (waiting, _) = warp_parts(&harness, layer);
assert!((Vec3::from(waiting.center).length() - 1.0).abs() < 0.05, "still on the ball: {:?}", waiting.center);
}
#[test]
fn place_on_surface_keeps_a_warp_on_its_own_texture_set() {
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let mesh = texturecraft_engine::geom::primitives::material_ball();
let session = texturecraft_engine::Session::new_project("Warp placement", mesh, "builtin:material_ball", None, 128).unwrap();
let mut harness = Harness::builder()
.with_size(vec2(1600.0, 960.0))
.with_context_setup(crate::framework::install_headless)
.build_eframe(|context| TextureCraftApp::new(context, session));
let layer = harness.state_mut().run("layer.add.fill", json!({})).unwrap()["layer"].as_u64().unwrap();
harness.state_mut().run("layer.fill.projection", json!({"layer": layer, "projection": "warp"})).unwrap();
harness.run_steps(2);
click_label(&mut harness, "Place on surface");
let app = harness.state();
let rect = app.viewport_rect;
let frame = gizmo(&harness);
let on_other_set = |point: Pos2| {
let local = point - rect.min;
app.session.texture_set_at(Vec2::new(local.x, local.y), app.session.viewport).is_some_and(|set| set != app.session.ts())
};
let movement = vec2(12.0, 0.0);
let rows = (0..rect.height() as usize).step_by(8);
let columns = (0..rect.width() as usize).step_by(8);
let mut candidates = rows.flat_map(|y| columns.clone().map(move |x| rect.min + vec2(x as f32, y as f32)));
let from = candidates
.find(|point| frame.grab(*point) == Some(FrameGrab::Place) && (0..=4).all(|step| on_other_set(*point + movement * (step as f32 / 4.0))))
.expect("a drag entirely on the material ball's other set");
let layer = frame.layer;
let before = projection(&harness, layer);
let steps = app.session.history_labels().len();
drag(&mut harness, from, from + movement, Modifiers::NONE);
assert_eq!(projection(&harness, layer), before, "the foreign surface must not take the warp");
assert_eq!(harness.state().session.history_labels().len(), steps);
}
#[test]
fn world_space_arrows_ignore_the_frames_turn() {
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let (mut harness, layer) = fill_app("warp");
let turn = |harness: &mut Harness<'_, TextureCraftApp>| {
harness.state_mut().run("layer.decal.set", json!({"layer": layer.0, "rotation": 30}));
harness.run_steps(2);
};
let arrow = |harness: &Harness<'_, TextureCraftApp>| {
let shown = gizmo(harness);
(shown.arrows[0].unwrap() - shown.center).normalized()
};
let frame_arrow = arrow(&harness);
turn(&mut harness);
assert!(arrow(&harness).dot(frame_arrow) < 0.95, "an object space arrow turns with the frame");
harness.state_mut().run("layer.decal.set", json!({"layer": layer.0, "rotation": 0}));
click_label(&mut harness, "Object space");
click_label(&mut harness, "World space");
let world_arrow = arrow(&harness);
turn(&mut harness);
assert!(arrow(&harness).dot(world_arrow) > 0.999, "a world space arrow stays on its world axis");
}
#[test]
fn holding_ctrl_moves_in_whole_grid_steps() {
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let (mut harness, layer) = fill_app("warp");
let grid_step = harness.state().ui.warp_toolbar.grid_step();
let start = gizmo(&harness);
let tip = start.arrows[0].unwrap();
let along = (tip - start.center).normalized();
// On macOS Ctrl is independent of the platform Command modifier
drag(&mut harness, tip, tip + along * 37.0, Modifiers::CTRL);
let (frame, _) = warp_parts(&harness, layer);
let steps = frame.offset[0] / grid_step;
assert!(frame.offset[0].abs() > 1e-3 && (steps - steps.round()).abs() < 1e-3, "moved by whole steps of {grid_step}: {:?}", frame.offset);
}
#[test]
fn keyboard_changes_the_warp_drag_steps() {
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let (mut harness, _) = fill_app("warp");
let before = harness.state().ui.warp_toolbar.grid_step();
click_label(&mut harness, "Manipulator settings");
harness.get_by_role_and_label(Role::Slider, "Grid steps").focus();
harness.run_steps(2);
harness.key_press(egui::Key::ArrowRight);
harness.run_steps(2);
assert!(harness.get_by_role_and_label(Role::Slider, "Grid steps").is_focused());
assert!(harness.state().ui.warp_toolbar.grid_step() > before);
assert!(harness.query_by_role_and_label(Role::Slider, "Angle steps").is_some());
}
#[test]
fn the_mirror_and_reset_buttons_edit_the_warp_in_one_undo_step_each() {
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let (mut harness, layer) = fill_app("warp");
let (fitted, _) = warp_parts(&harness, layer);
let pulled = [[-0.5, 0.5], [0.9, 0.9], [0.5, -0.5], [-0.5, -0.5]];
harness.state_mut().run("layer.fill.projection", json!({"layer": layer.0, "warpCorners": pulled}));
harness.state_mut().run("layer.decal.set", json!({"layer": layer.0, "rotation": 30}));
harness.run_steps(2);
let steps = harness.state().session.history_labels().len();
click_label(&mut harness, "Mirror horizontally");
assert_eq!(warp_parts(&harness, layer).0.flip, [true, false]);
click_label(&mut harness, "Mirror vertically");
click_label(&mut harness, "Mirror horizontally");
assert_eq!(warp_parts(&harness, layer).0.flip, [false, true], "each button toggles its own direction");
assert_eq!(harness.state().session.history_labels().len(), steps + 3);
click_label(&mut harness, "Reset");
click_label(&mut harness, "Reset warp transform");
let (frame, corners) = warp_parts(&harness, layer);
assert_eq!((frame, corners), (fitted, pulled), "the frame goes back and the corners stay");
click_label(&mut harness, "Reset");
click_label(&mut harness, "Reset all vertices");
assert_eq!(warp_parts(&harness, layer).1, Projection::FRAME_CORNERS);
assert_eq!(harness.state().session.history_labels().len(), steps + 5);
}
}
@@ -0,0 +1,24 @@
/// `value` rounded to the nearest multiple of `step`; no step (0, negative or not a number) leaves it as it is
pub(crate) fn to_step(value: f32, step: f32) -> f32 {
if step.is_finite() && step > 0.0 { (value / step).round() * step } else { value }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_value_snaps_to_the_nearest_multiple_of_the_step() {
assert!((to_step(0.29, 0.2) - 0.2).abs() < 1e-6);
assert!((to_step(0.31, 0.2) - 0.4).abs() < 1e-6);
assert!((to_step(-0.31, 0.2) + 0.4).abs() < 1e-6, "negative moves snap the same way");
assert_eq!(to_step(100.0, 45.0), 90.0);
}
#[test]
fn no_step_leaves_the_value_alone() {
for step in [0.0, -1.0, f32::NAN, f32::INFINITY] {
assert_eq!(to_step(0.37, step), 0.37, "{step}");
}
}
}
@@ -0,0 +1,34 @@
use serde_json::{Value, json};
use texturecraft_engine::core::{LayerId, Projection};
use crate::TextureCraftApp;
use crate::frame_gizmo::selected_fill_projection;
/// The selected fill with a warp projection that the tool bar edits: a fill layer, or a fill effect in its mask
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct WarpTarget {
pub layer: LayerId,
pub effect: Option<LayerId>,
/// The image mirrored left to right and top to bottom inside the frame
pub flip: [bool; 2],
}
impl WarpTarget {
/// The selected fill when it projects through a warp, in the modes where the frame gizmo shows
pub(crate) fn of(app: &TextureCraftApp) -> Option<WarpTarget> {
let (layer, effect, projection) = selected_fill_projection(app)?;
let Projection::Warp { frame, .. } = projection else { return None };
Some(WarpTarget { layer, effect, flip: frame.flip })
}
/// `fields` addressed to this fill, as every command that edits a fill's projection takes it
pub(super) fn params(&self, mut params: Value) -> Value {
params["layer"] = json!(self.layer.0);
if let Some(effect) = self.effect {
params["effect"] = json!(effect.0);
}
params
}
}
@@ -0,0 +1,63 @@
use std::ops::RangeInclusive;
use serde::{Deserialize, Serialize};
use super::{GizmoMode, GizmoSpace};
/// The manipulator size the gizmo's measurements are given at
pub(super) const DEFAULT_MANIPULATOR_SIZE: f32 = 0.2;
pub(super) const MANIPULATOR_SIZES: RangeInclusive<f32> = 0.1..=0.5;
/// The default and range of the move step (world units) and of the turn step (degrees)
pub(super) const DEFAULT_GRID_STEP: f32 = 0.2;
pub(super) const GRID_STEPS: RangeInclusive<f32> = 0.01..=1.0;
pub(super) const DEFAULT_ANGLE_STEP: f32 = 45.0;
pub(super) const ANGLE_STEPS: RangeInclusive<f32> = 1.0..=90.0;
/// The warp tool bar's settings: the gizmo's mode, space and size, and the steps its drags snap to while Ctrl is held
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct WarpToolbarSettings {
pub mode: GizmoMode,
pub space: GizmoSpace,
/// Manipulator size: [`DEFAULT_MANIPULATOR_SIZE`] draws the gizmo at its base size
pub manipulator_size: f32,
/// Move step in world units
pub grid_steps: f32,
/// Turn step in degrees
pub angle_steps: f32,
}
impl Default for WarpToolbarSettings {
fn default() -> Self {
WarpToolbarSettings {
mode: GizmoMode::default(),
space: GizmoSpace::default(),
manipulator_size: DEFAULT_MANIPULATOR_SIZE,
grid_steps: DEFAULT_GRID_STEP,
angle_steps: DEFAULT_ANGLE_STEP,
}
}
}
impl WarpToolbarSettings {
/// How many times its base size the gizmo's arrows and ring are drawn
pub(crate) fn gizmo_scale(&self) -> f32 {
within(self.manipulator_size, MANIPULATOR_SIZES, DEFAULT_MANIPULATOR_SIZE) / DEFAULT_MANIPULATOR_SIZE
}
/// The move step in world units
pub(crate) fn grid_step(&self) -> f32 {
within(self.grid_steps, GRID_STEPS, DEFAULT_GRID_STEP)
}
/// The turn step in degrees
pub(crate) fn angle_step(&self) -> f32 {
within(self.angle_steps, ANGLE_STEPS, DEFAULT_ANGLE_STEP)
}
}
/// `value` held to `range`; `fallback` for a saved value that is not a number
fn within(value: f32, range: RangeInclusive<f32>, fallback: f32) -> f32 {
if value.is_finite() { value.clamp(*range.start(), *range.end()) } else { fallback }
}
+241
View File
@@ -0,0 +1,241 @@
//! The craft-ui runtime, hosted from TextureCraft's own eframe `App` (craft-libs docs/craft-framework.md, section 2.2).
//! The desktop app calls [`install`] once, [`TextureCraftApp::before_input`] in `raw_input_hook`,
//! [`TextureCraftApp::close_path`] last in `logic`, and [`before_ui`] first in `ui`; the browser build and tests
//! install with [`install_headless`]. The framework dialogs run on [`TextureCraftApp::framework_dialogs`] after
//! TextureCraft's own UI.
//!
//! The runtime takes Escape, Tab and the clipboard events for the whole window unless one of TextureCraft's own egui
//! widgets has the keyboard. The window's Escape is read with [`escape_pressed`] and taken with
//! [`take_window_cancel`], its plain Enter taken with [`take_window_submit`]; the 3D and 2D views are declared to the runtime with [`host_canvas`], which keeps the edit
//! chords and the clipboard events in egui's input for TextureCraft's shortcuts. A bare Tab with nothing or a view
//! focused toggles the window's chrome in the runtime ([`RootEnv::tab_toggles_chrome`]), which `frame_input` turns into
//! Hide UI. A focused view leaves the keyboard to the shortcuts ([`widget_has_keyboard`]).
use std::sync::{Arc, OnceLock};
use craft_host::target::ShellInfo;
use craft_host::{AppInfo, Host};
use craft_keymap::Overrides;
use craft_ui::fonts::{I18nScripts, SystemFonts, UiFonts};
use craft_ui::runtime::commands::{ChromeCommand, CommandInput, CommandSet as _, EditCommands, NavCommand, QuitCommand};
use craft_ui::runtime::env::{RootEnv, Scale};
use craft_ui::runtime::focus::{EditSet, KeyUse};
use craft_ui::runtime::frame::{ChromeToggle, FrameInput, FrameOutput};
use craft_ui::runtime::keys::{Intent, with_window_intents};
use craft_ui::shell::embed::{self, CloseDecision};
use craft_window::policy::Decision;
use craft_window::system::WindowSystem;
use egui::ViewportId;
use crate::TextureCraftApp;
/// Each pass of the root window, first in `App::ui`: hands the runtime the native window it answers the hit test of
/// (Windows) and fits the window to its monitor once.
#[cfg(not(target_arch = "wasm32"))]
pub use craft_ui::shell::embed::before_ui;
/// The scripts of the interface languages, for the font stack.
static SCRIPTS: I18nScripts = I18nScripts;
/// The runtime's first font stack: egui's bundled faces and no installed system fonts. TextureCraft's own definitions
/// ([`crate::theme::install`]) replace it before anything is drawn.
fn ui_fonts() -> UiFonts<'static> {
UiFonts::new(&SCRIPTS).system_fonts(SystemFonts::Off)
}
fn install_with(ctx: &egui::Context, shell: ShellInfo, windows: Arc<dyn WindowSystem>, frame: Option<Decision>) -> Result<(), String> {
let mut spec = craft_ui::InstallSpec::new(shell, windows).app_id(crate::os_window::app_id());
if let Some(frame) = frame {
spec = spec.frame(frame);
}
embed::install(ctx, spec, &ui_fonts()).map(drop).map_err(|error| format!("the UI runtime could not be installed: {error}"))
}
/// Installs the runtime on the desktop window's context, once, before the first pass, with the window's `frame`
/// ([`crate::titlebar::TitleBar::decide`]).
#[cfg(not(target_arch = "wasm32"))]
pub fn install(ctx: &egui::Context, frame: Decision) -> Result<(), String> {
let shell = ShellInfo::default().backend(craft_host::target::Backend::from_env());
install_with(ctx, shell, Arc::new(craft_window::system::SystemWindows), Some(frame))
}
/// Installs the runtime on a context with no native window of its own: the browser build's canvas and test windows.
pub fn install_headless(ctx: &egui::Context) {
if let Err(error) = install_with(ctx, ShellInfo::default(), Arc::new(craft_window::system::NoWindows), None) {
log::warn!("{error}");
}
}
/// Who TextureCraft is to the framework's dialogs (the update dialogs show its name and icon).
pub(crate) fn host() -> Arc<Host> {
Arc::new(
Host::builder(AppInfo { id: "texturecraft", name: "TextureCraft", version: texturecraft_engine::VERSION })
.icon_png(include_bytes!("../../../assets/app-icon/hicolor/128x128/apps/ai.storyteller.texturecraft.png"))
.build(),
)
}
/// TextureCraft's own shortcut table keeps the keys the framework binds by default: Ctrl+Q is `ui.quit`, F6 is
/// `camera.orthographic` (and Shift+F6 stays free for it), so the framework's quit and pane moves are unbound, as is
/// Shift+Tab's panels toggle except tools (TextureCraft has one Hide UI, on Tab).
/// Overrides are keyed by command id, which the command sets give.
fn command_overrides() -> Arc<Overrides> {
static OVERRIDES: OnceLock<Arc<Overrides>> = OnceLock::new();
OVERRIDES
.get_or_init(|| {
let mut overrides = Overrides::new();
for id in [QuitCommand::Quit.id(), NavCommand::NextPane.id(), NavCommand::PreviousPane.id(), ChromeCommand::TogglePanelsKeepTools.id()] {
overrides.insert(id, Vec::new());
}
Arc::new(overrides)
})
.clone()
}
impl TextureCraftApp {
/// The framework's part of `App::raw_input_hook`, once per frame before the first pass: takes what the runtime
/// gathered since the last frame and gives the coming passes the root values (theme mode and interface scale).
pub fn before_input(&mut self, ctx: &egui::Context) {
// TextureCraft applies the interface scale itself (`logic`), so the runtime keeps the zoom it applied last.
let scale = ctx.zoom_factor();
embed::before_input(ctx, |output| self.frame_input(ctx, output, scale));
}
/// The root values of this frame. TextureCraft registers no commands with the runtime (its own shortcut table
/// runs every key, [`command_overrides`]). The runtime toggles the chrome on a bare Tab with nothing or a
/// view focused (`tab_toggles_chrome`, the views being the registered canvases) and takes it out of egui's input, and
/// each panels toggle it recorded for the root window flips Hide UI, as the `ui.hideUi` command does. While one of
/// TextureCraft's own egui modals shows in the root window, the runtime blocks the panels floated into windows of
/// their own.
pub(crate) fn frame_input(&mut self, ctx: &egui::Context, output: FrameOutput, scale: f32) -> FrameInput {
for (viewport, toggle) in &output.chrome_toggles {
if *viewport == ViewportId::ROOT && *toggle == ChromeToggle::Panels {
self.ui.hide_ui = !self.ui.hide_ui;
}
}
#[cfg(not(target_arch = "wasm32"))]
self.fired_clipboard.extend(clipboard_events(&output));
use crate::theme::Brightness;
let mode = match self.ui.prefs.brightness {
Brightness::Light | Brightness::MediumLight => craft_theme::Mode::Light,
Brightness::Dark | Brightness::MediumDark => craft_theme::Mode::Dark,
};
let mut root = RootEnv::new().mode(mode).scale(Scale::new(scale));
// Hide UI on another key leaves Tab to focus traversal and the shortcuts
root.tab_toggles_chrome = crate::keymap::shortcut_of(&self.ui.keymap, "ui.hideUi") == Some("Tab");
let app_modal = crate::docking::input_blocked(self, ctx).then_some(ViewportId::ROOT);
FrameInput::new(root).commands(CommandInput::new().overrides(command_overrides())).host(Arc::clone(&self.framework_host)).app_modal(app_modal)
}
/// The framework's part of `App::logic`, after TextureCraft's own: the root window's close path. Unsaved changes
/// hold the window open while the Unsaved Changes dialog asks ([`crate::windows::close_requested`]); otherwise
/// it closes.
pub fn close_path(&mut self, ctx: &egui::Context) {
embed::logic(ctx, || if crate::windows::close_requested(self) { CloseDecision::Hold } else { CloseDecision::Close });
}
}
/// The Copy, Cut and Paste events the runtime took from windows with no canvas of their own (a floating panel) and ran as
/// its `edit.copy`, `edit.cut` and `edit.paste`: the clipboard events TextureCraft's shortcuts read in the root window.
/// The other edit commands are not read here: TextureCraft's own loop still forwards their keys.
#[cfg(not(target_arch = "wasm32"))]
fn clipboard_events(output: &FrameOutput) -> impl Iterator<Item = egui::Event> + '_ {
output.fired.iter().filter_map(|fired| match EditCommands::from_ref(&fired.command)? {
EditCommands::Copy => Some(egui::Event::Copy),
EditCommands::Cut => Some(egui::Event::Cut),
// The layer paste takes no content from the event; the shortcut only needs the paste chord.
EditCommands::Paste => Some(egui::Event::Paste(String::new())),
_ => None,
})
}
/// Declares the view `id`, an egui widget drawn in this pass, as a document canvas of the window. With nothing or the
/// view focused, the edit chords and the clipboard events stay in egui's input for TextureCraft's shortcuts, and a bare
/// Tab is the runtime's chrome toggle (`frame_input`). Tab and Shift+Tab stop at the view, Shift+Tab moves on from it,
/// and a click gives it no focus.
pub(crate) fn host_canvas(ctx: &egui::Context, id: egui::Id) {
const KEYS: KeyUse = KeyUse::CANVAS.with_edits(EditSet::ALL);
craft_ui::runtime::focus::host_canvas(ctx, id, KEYS);
}
/// The widget that has the keyboard, the 3D and 2D views left out: a focused view leaves the keyboard to
/// TextureCraft's shortcuts, as with nothing focused.
pub(crate) fn focused_widget(ctx: &egui::Context) -> Option<egui::Id> {
use crate::viewport::{view_2d_id, view_3d_id};
ctx.memory(|memory| memory.focused()).filter(|focused| ![view_3d_id(), view_2d_id()].contains(focused))
}
/// Whether a widget other than the 3D and 2D views has the keyboard.
pub(crate) fn widget_has_keyboard(ctx: &egui::Context) -> bool {
focused_widget(ctx).is_some()
}
/// Whether Escape was pressed in this pass: from egui while one of TextureCraft's own widgets or popups has the
/// keyboard, otherwise the window's cancel, which the runtime routes to no component. Leaves it for later readers.
pub(crate) fn escape_pressed(ctx: &egui::Context) -> bool {
ctx.input(|i| i.key_pressed(egui::Key::Escape)) || window_cancel(ctx, false)
}
/// Takes the window's cancel (an Escape while nothing has framework focus) when it is there: no later reader sees it.
pub(crate) fn take_window_cancel(ctx: &egui::Context) -> bool {
window_cancel(ctx, true)
}
/// Takes the window's submit (a plain Enter while nothing has framework focus) when it is there: no later reader sees
/// it.
pub(crate) fn take_window_submit(ctx: &egui::Context) -> bool {
window_intent(ctx, Intent::Submit, true)
}
/// Whether the window's cancel is there and untaken; `take` takes it.
fn window_cancel(ctx: &egui::Context, take: bool) -> bool {
window_intent(ctx, Intent::Cancel, take)
}
/// Whether the window's `intent` is there and untaken; `take` takes it.
fn window_intent(ctx: &egui::Context, intent: Intent, take: bool) -> bool {
let mut pending = false;
with_window_intents(ctx, false, |intents| {
pending = if take { intents.take(intent.clone()) } else { intents.untaken(&intent) };
take && pending
});
pending
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
use super::*;
use craft_ui::runtime::commands::{FirePhase, FireSource, Fired};
use egui_kittest::Harness;
fn fired(command: EditCommands) -> Fired {
Fired::new(command.into(), FireSource::Key, FirePhase::Press, 0.0)
}
/// With nothing focused in a floating panel, the runtime runs the chord as `edit.copy` and takes the clipboard event
/// from egui's input, so TextureCraft's own loop never sees it: the fired command reaches the layer clipboard once.
#[test]
fn fired_copy_and_paste_from_a_float_reach_the_layer_clipboard_once() {
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut h =
Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_context_setup(install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
h.run_steps(4);
let ctx = h.ctx.clone();
let layers = |h: &Harness<'_, TextureCraftApp>| h.state().session.doc.project.layers.len();
let before = layers(&h);
let mut output = FrameOutput::default();
output.fired.push(fired(EditCommands::Copy));
h.state_mut().frame_input(&ctx, output, 1.0);
h.run_steps(3);
assert!(h.state().session.clipboard.is_some(), "the fired Copy copied the layer");
assert_eq!(layers(&h), before);
let mut output = FrameOutput::default();
output.fired.push(fired(EditCommands::Paste));
h.state_mut().frame_input(&ctx, output, 1.0);
h.run_steps(3);
assert_eq!(layers(&h), before + 1, "the fired Paste pasted the layer once");
}
}
+31 -7
View File
@@ -1,8 +1,8 @@
//! UI text lookup over the optional shared craft-i18n catalogs.
//! Missing translations and builds without catalogs use the English source text.
use std::cell::Cell;
use std::fmt::Display;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{LazyLock, OnceLock};
include!(concat!(env!("OUT_DIR"), "/craft_i18n.rs"));
@@ -52,7 +52,10 @@ pub static LANGUAGES: [Language; COUNT] = [
Language { code: "ar", name: "العربية", english: "Arabic" },
];
static CURRENT: AtomicUsize = AtomicUsize::new(0);
// Rendering and preferences use the UI thread, including independent test harnesses.
thread_local! {
static CURRENT: Cell<usize> = const { Cell::new(0) };
}
/// How a fill reads its images, as the Filtering combo names it
pub(crate) fn filtering_label(filtering: texturecraft_engine::core::Filtering) -> &'static str {
@@ -96,20 +99,20 @@ pub(crate) fn baked_map_label(map: texturecraft_engine::core::BakedMap) -> &'sta
/// The saved language that follows the operating system's (Settings > Language > Default (System Language)).
pub const SYSTEM_LANGUAGE: &str = "";
/// Switch the UI language ([`SYSTEM_LANGUAGE`] follows the system; unknown codes fall back to English).
/// Switch the calling UI thread's language. [`SYSTEM_LANGUAGE`] follows the system.
pub fn set_language(code: &str) {
let code = if code == SYSTEM_LANGUAGE { system_language() } else { code };
CURRENT.store(LANGUAGES.iter().position(|l| l.code.eq_ignore_ascii_case(code) && available(l.code)).unwrap_or(0), Ordering::Relaxed);
CURRENT.set(LANGUAGES.iter().position(|l| l.code.eq_ignore_ascii_case(code) && available(l.code)).unwrap_or(0));
}
/// The current UI language.
pub fn current() -> &'static Language {
LANGUAGES.get(CURRENT.load(Ordering::Relaxed)).unwrap_or(&LANGUAGES[0])
LANGUAGES.get(CURRENT.get()).unwrap_or(&LANGUAGES[0])
}
/// `text` in the current language (unchanged when it has no translation).
pub fn tr(text: &str) -> &str {
let lang = shared_languages().get(CURRENT.load(Ordering::Relaxed)).copied().unwrap_or(craft_i18n::Lang::EN);
let lang = shared_languages().get(CURRENT.get()).copied().unwrap_or(craft_i18n::Lang::EN);
I18N.t(lang, text)
}
@@ -182,7 +185,7 @@ fn system_language() -> &'static str {
SYSTEM.get_or_init(os_language)
}
/// Tests that switch the global UI language, or draw the UI under it, run one at a time.
/// Shared guard used by language fixture tests.
#[cfg(test)]
pub(crate) static TEST_LANGUAGE: std::sync::Mutex<()> = std::sync::Mutex::new(());
@@ -192,6 +195,27 @@ mod tests {
use super::*;
use std::collections::{BTreeSet, HashMap};
#[test]
fn a_parallel_ui_language_context_keeps_its_own_language() {
set_language("en");
let french = LANGUAGES.iter().position(|language| language.code == "fr").unwrap();
let barrier = std::sync::Barrier::new(2);
let (first, second) = std::thread::scope(|scope| {
let other = scope.spawn(|| {
// Exercise the resolved language selection even when the French catalog is absent.
CURRENT.set(french);
barrier.wait();
barrier.wait();
current().code
});
barrier.wait();
let first = current().code;
barrier.wait();
(first, other.join().unwrap())
});
assert_eq!((first, second), ("en", "fr"));
}
/// Every key the UI looks up: `tr("…")` / `trf("…"` literals in the sources, plus the
/// static catalogs whose labels are translated where they are shown.
fn keys() -> Vec<String> {
+71 -25
View File
@@ -3,9 +3,10 @@
//! the shortcut editor window (Help ▸ Shortcuts list) and the Edit ▸ Settings ▸ Shortcuts page.
use std::collections::BTreeMap;
use std::sync::OnceLock;
use craft_keymap::egui::Dispatcher;
use craft_keymap::{Active, Bindable, Chord, CommandRef, ConflictKind, KeyInput, Layout, Lookup, Mods, Overrides, Platform, Scope, Scopes};
use crate::shortcut_dispatch::Dispatcher;
use craft_keymap::{Active, Chord, CommandDef, CommandRef, ConflictKind, KeyInput, Layout, Lookup, Mods, Overrides, Platform, Scope, Scopes};
use egui::{Event, Id, Key, KeyboardShortcut, Modifiers, RichText, vec2};
use egui_phosphor::regular as ic;
@@ -41,6 +42,22 @@ pub static NOT_AVAILABLE_ACTIONS: [(&str, Binding); 2] = [
("viewport.frame", Binding { id: "ui.toggleAnimation", group: "Viewport", label: "Toggle animation", default: Some("Space") }),
];
/// Shortcut reference rows shown before Reimport mesh. Their example keys stay available to bind.
pub const REFERENCE_ACTIONS: [Binding; 7] = [
Binding { id: "ui.manipulator.toggle", group: "Viewport", label: "Toggle transform handles", default: Some("Q") },
Binding { id: "ui.manipulator.grow", group: "Viewport", label: "Enlarge transform handles", default: None },
Binding { id: "ui.manipulator.shrink", group: "Viewport", label: "Shrink transform handles", default: Some("-") },
Binding { id: "ui.manipulator.space", group: "Viewport", label: "Switch transform coordinate space", default: Some("T") },
Binding { id: "ui.warpEdit", group: "Viewport", label: "Toggle warp editing", default: Some("Shift+V") },
Binding { id: "ui.manipulator.translate", group: "Viewport", label: "Move with transform handles", default: Some("W") },
Binding { id: "ui.manipulator.rotate", group: "Viewport", label: "Rotate with transform handles", default: Some("E") },
];
fn unavailable_before(id: &str) -> impl Iterator<Item = &'static Binding> + '_ {
let reference = if id == "file.reimportMesh" { REFERENCE_ACTIONS.as_slice() } else { &[] };
reference.iter().chain(NOT_AVAILABLE_ACTIONS.iter().filter(move |(before, _)| *before == id).map(|(_, row)| row))
}
/// The shortcut list's first rows, in the reference's order. The `>` and `<` of the reference are
/// the shifted Period and Comma keys.
const LISTED_SHORTCUTS: &[ShortcutListEntry] = &[
@@ -179,11 +196,11 @@ fn active(keymap: &Keymap) -> Vec<KeyboardShortcut> {
/// The catalog as craft-keymap sees it, in `bindings()` order: the first one listed wins a shared
/// shortcut.
fn catalog() -> Vec<Bindable> {
fn catalog() -> Vec<CommandDef> {
bindings()
.iter()
.map(|b| {
let item = Bindable::new(b.id, b.label, Scope::app());
let item = CommandDef::new(b.id, b.label, Scope::app());
match b.default.and_then(parse) {
Some(chord) => item.with_default(craft_keymap::Binding::new(chord)),
None => item,
@@ -214,7 +231,7 @@ fn overrides(keymap: &Keymap) -> Overrides {
/// The keymap with `keymap`'s shortcuts for `platform`.
fn resolved(keymap: &Keymap, platform: Platform) -> craft_keymap::Keymap {
craft_keymap::Keymap::new(catalog(), Scopes::new(), platform).with_overrides(overrides(keymap))
craft_keymap::Keymap::new(catalog(), Scopes::new(), platform).with_overrides(overrides(keymap)).with_delete_keys(craft_keymap::DeleteKeys::Apart)
}
/// The resolved keymap and the dispatcher that runs it against each frame's keys.
@@ -222,14 +239,15 @@ pub struct Bindings {
stored: Keymap,
map: craft_keymap::Keymap,
dispatcher: Dispatcher,
conflicts: OnceLock<BTreeMap<&'static str, &'static Binding>>,
}
impl Default for Bindings {
fn default() -> Bindings {
let stored = Keymap::new();
let map = resolved(&stored, Platform::current());
// Held keys repeat their command. Copy, Cut and Paste events count as Ctrl+C, X and V.
Bindings { stored, map, dispatcher: Dispatcher::new().with_repeat(true).with_clipboard_events(true) }
Bindings { stored, map, dispatcher: Dispatcher::default(), conflicts: OnceLock::new() }
}
}
@@ -239,13 +257,14 @@ impl Bindings {
if self.stored != *keymap || self.map.platform() != platform {
self.stored = keymap.clone();
self.map = resolved(keymap, platform);
self.conflicts.take();
}
}
/// The ids of the commands this frame's key presses run, in press order. The presses are
/// removed from the input.
pub(crate) fn dispatch(&mut self, input: &mut egui::InputState) -> Vec<String> {
self.dispatcher.dispatch(input, &self.map, &Active::NONE).into_iter().map(|hit| hit.command.id).collect()
self.dispatcher.dispatch_filtered(input, &self.map, |_| true).into_iter().map(|hit| hit.command.id).collect()
}
/// The id of the command a key press outside the main window runs. The press is matched as
@@ -253,11 +272,7 @@ impl Bindings {
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn command_of(&self, press: &Event) -> Option<String> {
let input = KeyInput::from_egui(press, self.map.platform())?;
self.dispatcher.layout().candidates(&input).into_iter().find_map(|chord| match self.map.lookup(&chord, false, &Active::NONE) {
Lookup::Run(command) => Some(command.id),
Lookup::Cycle(commands) => commands.into_iter().next().map(|command| command.id),
_ => None,
})
craft_keymap::Matcher::single(self.dispatcher.layout(), &self.map, &input, &Active::NONE, &[]).map(|hit| hit.command.id)
}
/// The shortcut a press records: the chord it runs, keeping the held Ctrl and Cmd as they are.
@@ -279,14 +294,22 @@ impl Bindings {
matches!(self.map.lookup(&Chord::new(Mods::SHIFT, key), false, &Active::NONE), Lookup::None)
}
/// Another binding on the same shortcut as `b`.
fn conflict(&self, b: &Binding) -> Option<&'static Binding> {
/// The first conflicting action for each shortcut, computed only when an editor needs it.
fn conflicts(&self) -> &BTreeMap<&'static str, &'static Binding> {
self.conflicts.get_or_init(|| bindings().iter().filter_map(|binding| self.find_conflict(binding).map(|other| (binding.id, other))).collect())
}
fn conflict(&self, binding: &Binding) -> Option<&'static Binding> {
self.conflicts().get(binding.id).copied()
}
fn find_conflict(&self, b: &Binding) -> Option<&'static Binding> {
let clash = self.map.conflicts_with(&CommandRef::new(b.id)).into_iter().find(|c| c.kind == ConflictKind::Clash);
if let Some(clash) = clash {
return bindings().iter().find(|x| x.id == clash.b.0.id);
}
// The rows the reference lists and TextureCraft cannot run yet still own their keys
// Keep the existing reserved shortcuts for paused computation and animation
let mine = parse(shortcut(&self.stored, b)?)?;
NOT_AVAILABLE_ACTIONS.iter().map(|(_, row)| row).find(|row| row.default.and_then(parse) == Some(mine))
}
@@ -373,7 +396,7 @@ pub fn shown(text: &str) -> &str {
/// Whether the shortcuts in `edited` (kept in step with the working copy) have an item that
/// shares its shortcut with another.
pub(crate) fn has_conflict(edited: &Bindings) -> bool {
bindings().iter().any(|b| edited.conflict(b).is_some())
!edited.conflicts().is_empty()
}
/// Follow `keymap` with the checker of the Settings window.
@@ -391,7 +414,9 @@ pub(crate) fn actions_page(ui: &mut egui::Ui, keymap: &mut Keymap, recorder: &Bi
let tk = Tokens::get(&ctx);
let capture_id = Id::unique(SETTINGS_CAPTURE);
let mut capture: Option<usize> = ctx.data(|d| d.get_temp(capture_id));
if let (Some(i), Some(sc)) = (capture, pressed(&ctx, recorder)) {
if let Some(i) = capture
&& let Some(sc) = pressed(&ctx, recorder)
{
if let Some(b) = bindings().get(i) {
if sc.logical_key == Key::Delete && sc.modifiers.is_none() {
rebind(keymap, b, "");
@@ -401,6 +426,7 @@ pub(crate) fn actions_page(ui: &mut egui::Ui, keymap: &mut Keymap, recorder: &Bi
}
capture = None;
}
follow(edited, keymap, &ctx);
let cell = |ui: &mut egui::Ui, width: f32, add: &mut dyn FnMut(&mut egui::Ui)| {
@@ -410,7 +436,6 @@ pub(crate) fn actions_page(ui: &mut egui::Ui, keymap: &mut Keymap, recorder: &Bi
});
};
// A pencil that cannot be used yet
let locked_pencil = |ui: &mut egui::Ui, action: &str| {
let edit = trf("Edit the shortcut of {item}", &[("item", &tr(action))]);
ui.add_enabled_ui(false, |ui| icon_button(ui, ic::PENCIL_SIMPLE, &edit, false, 20.0)).inner.on_disabled_hover_text(tr(NOT_AVAILABLE));
@@ -430,9 +455,10 @@ pub(crate) fn actions_page(ui: &mut egui::Ui, keymap: &mut Keymap, recorder: &Bi
ui.label(caption(tr("Actions")));
ui.add_space(4.0);
for (i, b) in bindings().iter().enumerate() {
for (_, row) in NOT_AVAILABLE_ACTIONS.iter().filter(|(before, _)| *before == b.id) {
for row in unavailable_before(b.id) {
locked_row(ui, row.label, row.default.unwrap_or(""));
}
let waiting = capture == Some(i);
ui.horizontal(|ui| {
cell(ui, 300.0, &mut |ui| {
@@ -487,14 +513,23 @@ pub(crate) fn actions_page(ui: &mut egui::Ui, keymap: &mut Keymap, recorder: &Bi
});
}
/// The first key press this frame as a shortcut.
/// The first key press this frame as a shortcut, including Escape routed to the window's cancel.
/// Keep the press's modifiers so only plain Escape cancels recording.
fn pressed(ctx: &egui::Context, bindings: &Bindings) -> Option<KeyboardShortcut> {
let platform = craft_keymap::egui::platform(ctx);
ctx.input(|i| {
let press = ctx.input(|i| {
i.events.iter().find_map(|e| match e {
Event::Key { key, pressed: true, modifiers, .. } => Some(bindings.recorded(e, *key, *modifiers, platform)),
_ => None,
})
});
press.or_else(|| {
crate::framework::take_window_cancel(ctx).then(|| {
let modifiers = craft_ui::runtime::keys::escape_mods(ctx).unwrap_or(Mods::NONE);
Chord::new(modifiers, craft_keymap::Key::Escape).to_egui_shortcut()
})
})
}
@@ -509,7 +544,9 @@ pub fn window(app: &mut TextureCraftApp, ctx: &egui::Context) {
let capture_id = Id::unique(CAPTURE);
let filter_id = Id::unique("keymap_filter");
let mut capture: Option<usize> = ctx.data(|d| d.get_temp(capture_id));
if let (Some(i), Some(sc)) = (capture, pressed(ctx, &app.bindings)) {
if let Some(i) = capture
&& let Some(sc) = pressed(ctx, &app.bindings)
{
if (sc.logical_key != Key::Escape || !sc.modifiers.is_none())
&& let Some(b) = bindings().get(i)
{
@@ -517,6 +554,7 @@ pub fn window(app: &mut TextureCraftApp, ctx: &egui::Context) {
}
capture = None;
}
app.bindings.sync(&app.ui.keymap, craft_keymap::egui::platform(ctx));
let mut filter: String = ctx.data(|d| d.get_temp(filter_id)).unwrap_or_default();
let mut open = true;
@@ -530,7 +568,7 @@ pub fn window(app: &mut TextureCraftApp, ctx: &egui::Context) {
}
});
});
let clashes = bindings().iter().filter(|b| app.bindings.conflict(b).is_some()).count();
let clashes = app.bindings.conflicts().len();
if clashes > 0 {
ui.label(
RichText::new(format!("{} {}", ic::WARNING, trf("{n} items share a shortcut; the first one listed wins.", &[("n", &clashes)])))
@@ -542,7 +580,7 @@ pub fn window(app: &mut TextureCraftApp, ctx: &egui::Context) {
egui::ScrollArea::vertical().max_height(420.0).auto_shrink([false, true]).show(ui, |ui| {
egui::Grid::new("keymap_grid").num_columns(3).striped(true).spacing(vec2(10.0, 4.0)).show(ui, |ui| {
for (i, b) in bindings().iter().enumerate() {
for (_, row) in NOT_AVAILABLE_ACTIONS.iter().filter(|(before, _)| *before == b.id) {
for row in unavailable_before(b.id) {
let key = row.default.unwrap_or("");
if !needle.is_empty() && ![row.label, row.group, tr(row.label), tr(row.group), key].iter().any(|t| t.to_lowercase().contains(&needle)) {
continue;
@@ -556,6 +594,7 @@ pub fn window(app: &mut TextureCraftApp, ctx: &egui::Context) {
ui.add_enabled(false, button).on_disabled_hover_text(tr(NOT_AVAILABLE));
ui.end_row();
}
let current = shortcut(&app.ui.keymap, b);
let current_text = current.map(shown);
if !needle.is_empty()
@@ -808,6 +847,13 @@ mod tests {
keymap.insert("file.save".into(), "Equals".into());
let resolved = bindings_for(&keymap);
assert_eq!(resolved.command_of(&press(Key::Plus, Modifiers::NONE)).as_deref(), Some("file.save"), "+ stands for =");
// A layout that types = with Shift+0: the press is both chords, and the one with Shift runs.
keymap.insert("file.saveAs".into(), "Shift+Equals".into());
let mut resolved = bindings_for(&keymap);
let equals = press_at(Key::Equals, Key::Num0, Modifiers::SHIFT);
assert_eq!(dispatched(&mut resolved, vec![equals.clone()], Modifiers::SHIFT), ["file.saveAs"]);
assert_eq!(resolved.command_of(&equals).as_deref(), Some("file.saveAs"));
}
#[test]
+15 -11
View File
@@ -1,12 +1,13 @@
//! State behind the Layers panel: the thumbnail service, the GPU textures made from its pictures,
//! which effect groups are folded, and the one place the preview size is decided.
//! which effect stack is open, and the one place the preview size is decided.
use std::collections::{HashMap, HashSet};
use std::collections::HashMap;
use std::time::Duration;
use egui::{Context, TextureHandle, TextureId, TextureOptions};
use texturecraft_engine::Session;
use texturecraft_engine::compose::ThumbTarget;
use texturecraft_engine::core::LayerId;
use texturecraft_engine::thumbs::{CACHE_ENTRIES, ThumbService};
use crate::TextureCraftApp;
@@ -42,20 +43,23 @@ pub struct LayerPanel {
frame: u64,
/// Whether this frame's pictures are begun and not yet finished by [`LayerPanel::end`]
pictures_begun: bool,
/// Folded effect groups: (layer, true for the mask's). A view setting; the document is not touched.
pub(crate) folded: HashSet<(u64, bool)>,
/// The open stack, with `true` for a layer's mask. This belongs to the panel view.
pub(crate) expanded_effects: Option<(LayerId, bool)>,
}
/// How soon to look again for pictures still rendering (milliseconds)
const POLL_INTERVAL_MS: u64 = 40;
impl LayerPanel {
pub(crate) fn toggle_effects(&mut self, stack: Option<(LayerId, bool)>) {
self.expanded_effects = stack.filter(|stack| Some(*stack) != self.expanded_effects);
}
/// Start drawing the panel for this frame.
pub(crate) fn begin(&mut self, session: &Session, now: f64) {
self.begin_pictures(session, now);
// Deleted layer IDs must not accumulate in panel state
self.folded.retain(|(layer, _)| session.doc.project.layers.contains_key(&texturecraft_engine::core::LayerId(*layer)));
self.expanded_effects = self.expanded_effects.filter(|(layer, _)| session.doc.project.layers.contains_key(layer));
}
/// Advance the picture frame once, whether the panel or a picture outside it asks first
@@ -115,22 +119,22 @@ impl LayerPanel {
#[cfg(test)]
mod tests {
use super::*;
use texturecraft_engine::core::{Channel, LayerId};
use texturecraft_engine::core::Channel;
use texturecraft_engine::geom::primitives;
#[test]
fn deleted_layers_release_their_fold_state() {
fn deleted_layers_close_their_effect_stack() {
let mut session = Session::new_project("thumb", primitives::plane(1.0, 1), "builtin:plane", None, 128).unwrap();
let layer = session.selected_layer().unwrap();
let mut panel = LayerPanel::default();
panel.folded.extend([(layer.0, false), (layer.0, true)]);
panel.expanded_effects = Some((layer, false));
panel.begin(&session, 0.0);
assert_eq!(panel.folded.len(), 2, "existing layers keep their view settings");
assert_eq!(panel.expanded_effects, Some((layer, false)), "existing layers keep their view settings");
texturecraft_engine::execute(&mut session, "layer.remove", &serde_json::json!({"layer": layer.0})).unwrap();
panel.begin(&session, 1.0);
assert!(panel.folded.is_empty(), "deleted layer IDs must not accumulate in view state");
assert_eq!(panel.expanded_effects, None, "the deleted layer leaves no open stack");
}
#[test]
+120 -21
View File
@@ -10,6 +10,8 @@
mod anchor_properties;
mod angle_dial;
mod ask;
#[cfg(not(target_arch = "wasm32"))]
mod autosave_name;
mod bake_job;
pub mod bake_mode;
mod bake_preset;
@@ -44,6 +46,7 @@ mod filter_transform_rows;
mod folder_properties;
pub mod fonts;
mod frame_gizmo;
pub mod framework;
mod generator_input_card;
mod generator_input_slot;
mod generator_kind_rows;
@@ -77,6 +80,8 @@ mod levels_properties;
mod line_snap;
mod list_action;
pub mod log_panel;
#[cfg(not(target_arch = "wasm32"))]
mod manual_save;
mod mask_fill_panel;
mod mask_paint_panel;
mod mask_preview_image;
@@ -102,6 +107,7 @@ pub mod orb_previews;
mod orb_shape;
/// The channel's OS identity (app id, window and app names) — see its module docs.
pub mod os_window;
mod pane_split;
pub mod parity;
mod past_end;
mod path_hit;
@@ -157,6 +163,7 @@ pub mod shelf_preview;
mod shelf_tabs;
mod shelf_toolbar;
pub mod shelf_view;
mod shortcut_dispatch;
mod slot_thumbnail;
#[cfg(not(target_arch = "wasm32"))]
mod smart_mask_menu;
@@ -252,6 +259,7 @@ pub struct Toast {
pub error: bool,
pub until: f64,
pub show_log: bool,
announce: bool,
}
pub struct TextureCraftApp {
@@ -299,6 +307,12 @@ pub struct TextureCraftApp {
pub(crate) live_preview: bake_mode::LivePreview,
/// Last frame's viewport rect (logical points), for scripted input.
pub viewport_rect: egui::Rect,
/// Project and texture-set index from the last completed UI pass.
hovered_texture_set: Option<(u64, usize)>,
/// The set under the pointer in this pass, independent of dock drawing order.
next_hovered_texture_set: Option<(u64, usize)>,
/// Project identity of the current inline rename buffer.
rename_project_id: u64,
pub fps: f32,
/// User smart materials found in the library folder (refreshed on demand).
pub library: Option<Vec<std::path::PathBuf>>,
@@ -336,10 +350,23 @@ pub struct TextureCraftApp {
pub banner: Option<&'static str>,
/// Who draws the window's title bar (decided at startup, before the window opens).
pub title_bar: titlebar::TitleBar,
/// The dock area's workspace and panel specs between passes.
pub(crate) docks: docking::LiveDock,
/// The framework dialogs (the update dialogs), run once per pass after TextureCraft's own UI.
pub framework_dialogs: craft_ui::dialog::DialogHost,
/// Who TextureCraft is to the framework's dialogs.
pub(crate) framework_host: std::sync::Arc<craft_host::Host>,
/// The Copy, Cut and Paste the runtime took from a floating panel's window (`framework::clipboard_events`), for the
/// shortcuts of the next `logic`.
#[cfg(not(target_arch = "wasm32"))]
fired_clipboard: Vec<egui::Event>,
last_time: f64,
/// When the next autosave is due (seconds of app time; desktop only).
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
next_autosave: f64,
/// The unsaved project (its id) and the suffix of its autosave copy.
#[cfg(not(target_arch = "wasm32"))]
unsaved_autosave_suffix: Option<(u64, u64)>,
/// The brightness and accent the style was last built for.
styled: Option<(theme::Brightness, theme::Accent)>,
/// Whether the window had focus last frame.
@@ -350,10 +377,19 @@ pub struct TextureCraftApp {
/// Native file dialogs and their continuations (desktop only).
#[cfg(not(target_arch = "wasm32"))]
pub file_dialogs: file_dialogs::FileDialogs,
/// The unsaved-changes dialog's Save is waiting on the Save dialog's answer.
/// Project whose unsaved-changes dialog can still answer.
prompt_project_id: u64,
/// A manual save running on the desktop archive writer.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) save_job: Option<manual_save::SaveJob>,
/// The unsaved-changes dialog's Save is waiting for a path or a save result.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) saving_for_prompt: bool,
/// That Save dialog saved the project; the prompt goes on at its next frame.
/// A close the finished save left waiting for an open stroke, with the id of the project it
/// belongs to; decided once the stroke ends, dropped when another project replaced that one.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) quit_after_stroke: Option<u64>,
/// The requested save completed; the prompt goes on at its next frame.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) prompt_saved: bool,
/// The resolved keymap and its key dispatcher.
@@ -369,11 +405,8 @@ pub(crate) fn start_ui(saved: Option<UiState>, session: &mut Session) -> UiState
ui.tool_settings.apply(&mut session.tool);
ui
}
None => {
let mut ui = UiState::default();
ui.prefs.language = i18n::SYSTEM_LANGUAGE.into();
ui
}
// The default language follows the operating system
None => UiState::default(),
}
}
@@ -444,6 +477,9 @@ impl TextureCraftApp {
bake_map_thumbnails: bake_mode::MapThumbnails::default(),
live_preview: bake_mode::LivePreview::default(),
viewport_rect: egui::Rect::NOTHING,
hovered_texture_set: None,
next_hovered_texture_set: None,
rename_project_id: project_id,
fps: 0.0,
ui_ms: 0.0,
profiler: profile::Profiler::default(),
@@ -467,17 +503,29 @@ impl TextureCraftApp {
fonts: fonts::UiFonts::default(),
banner: None,
title_bar: titlebar::TitleBar::default(),
docks: docking::LiveDock::default(),
framework_dialogs: craft_ui::dialog::DialogHost::new(),
framework_host: framework::host(),
#[cfg(not(target_arch = "wasm32"))]
fired_clipboard: Vec::new(),
last_time: 0.0,
next_autosave,
#[cfg(not(target_arch = "wasm32"))]
unsaved_autosave_suffix: None,
styled: None,
focused: true,
#[cfg(not(target_arch = "wasm32"))]
updates_rt: updates_ui::Runtime::default(),
#[cfg(not(target_arch = "wasm32"))]
file_dialogs: file_dialogs::FileDialogs::new(cc.egui_ctx.clone()),
prompt_project_id: project_id,
#[cfg(not(target_arch = "wasm32"))]
save_job: None,
#[cfg(not(target_arch = "wasm32"))]
saving_for_prompt: false,
#[cfg(not(target_arch = "wasm32"))]
quit_after_stroke: None,
#[cfg(not(target_arch = "wasm32"))]
prompt_saved: false,
bindings: keymap::Bindings::default(),
settings_bindings: keymap::Bindings::default(),
@@ -624,13 +672,13 @@ impl TextureCraftApp {
}
pub fn toast(&mut self, text: impl Into<String>, error: bool) {
self.toasts.push(Toast { text: text.into(), error, until: self.last_time + if error { 6.0 } else { 3.0 }, show_log: false });
self.toasts.push(Toast { text: text.into(), error, until: self.last_time + if error { 6.0 } else { 3.0 }, show_log: false, announce: false });
}
/// An error toast that stays until the user dismisses it (for a problem that persists and
/// is reported once, like a texture set the GPU could not hold).
pub fn toast_sticky(&mut self, text: impl Into<String>) {
self.toasts.push(Toast { text: text.into(), error: true, until: f64::INFINITY, show_log: false });
self.toasts.push(Toast { text: text.into(), error: true, until: f64::INFINITY, show_log: false, announce: false });
}
/// Bake texture sets in the background, one after another; invalid set indices show an error without starting anything
@@ -1010,6 +1058,10 @@ impl TextureCraftApp {
/// and written on a worker thread; the project data is shared copy-on-write).
#[cfg(not(target_arch = "wasm32"))]
fn autosave(&mut self, now: f64) {
if self.save_job.is_some() {
return;
}
let period = autosave_period_seconds(self.ui.prefs.autosave_minutes);
// The clock starts at the first unsaved change
@@ -1028,11 +1080,7 @@ impl TextureCraftApp {
self.next_autosave = now + period;
let dir = user_dir("autosave");
let path = dir.join(format!(
"{}.{}",
texturecraft_engine::formats::export::sanitize_file_stem(&self.session.doc.project.name),
texturecraft_engine::core::PROJECT_EXT
));
let path = self.autosave_path(&dir);
let snapshot = self.session.project_snapshot();
let spawned = std::thread::Builder::new().name("texturecraft-autosave".into()).spawn(move || {
let result =
@@ -1072,7 +1120,7 @@ const BAKE_POLL_INTERVAL: std::time::Duration = std::time::Duration::from_millis
/// The share of the running frame rate and frame time averages each frame keeps (an average over about ten frames)
const FRAME_AVERAGE_KEEP: f32 = 0.9;
/// The interface scale applied: wider than the Settings slider, so a scale set elsewhere still applies within reason
/// The interface scale applied (`prefs.ui_scale`, set through `ui.set`; Settings has no control for it), clamped to a usable range
const UI_SCALE_APPLIED: std::ops::RangeInclusive<f32> = 0.5..=3.0;
/// Zoom factors closer than this are the same zoom (float noise), so the zoom is not set again each frame
const SAME_ZOOM_TOLERANCE: f32 = 1e-3;
@@ -1107,6 +1155,7 @@ impl TextureCraftApp {
impl eframe::App for TextureCraftApp {
/// A drag that holds the pointer reads the pointer's moves as moves of a pointer no screen edge stops
fn raw_input_hook(&mut self, ctx: &egui::Context, raw_input: &mut egui::RawInput) {
self.before_input(ctx);
pointer_lock::rewrite(ctx, raw_input);
}
@@ -1188,7 +1237,10 @@ impl eframe::App for TextureCraftApp {
ctx.set_zoom_factor(scale);
}
#[cfg(not(target_arch = "wasm32"))]
self.autosave(now);
{
self.poll_save(ctx);
self.autosave(now);
}
i18n::set_language(&self.ui.prefs.language);
#[cfg(target_arch = "wasm32")]
{
@@ -1201,6 +1253,11 @@ impl eframe::App for TextureCraftApp {
self.bindings.sync(&self.ui.keymap, craft_keymap::egui::platform(ctx));
menus::shortcuts(self, ctx);
#[cfg(not(target_arch = "wasm32"))]
{
let events = std::mem::take(&mut self.fired_clipboard);
menus::forwarded_shortcuts(self, ctx, events, egui::Modifiers::NONE);
}
screen_pick::sync(self, ctx);
move_on_model::end_when_gone(self, ctx);
@@ -1221,7 +1278,9 @@ impl eframe::App for TextureCraftApp {
self.profiler.logic_ms = (now_ms() - logic_start_ms) as f32;
// Last, so it sees every close request this frame's work made
windows::close_request(self, ctx);
#[cfg(not(target_arch = "wasm32"))]
self.resume_close_after_stroke(ctx);
self.close_path(ctx);
}
#[cfg_attr(target_arch = "wasm32", allow(unused_variables))]
@@ -1248,9 +1307,29 @@ impl eframe::App for TextureCraftApp {
let hide_ui = self.ui.hide_ui;
let tokens = theme::Tokens::get(&ctx);
// Layer and effect IDs can repeat in a replacement project
if self.rename_project_id != self.session.project_id {
self.ui.rename = None;
self.rename_project_id = self.session.project_id;
}
// The dock keeps the cards' gutter from the bars and rails around it
let panel_frame = if hide_ui { egui::Frame::NONE.fill(tokens.viewport) } else { egui::Frame::NONE.fill(tokens.chrome).inner_margin(theme::GUTTER) };
egui::CentralPanel::default().frame(panel_frame).show(ui, |ui| if hide_ui { viewport::central(self, ui) } else { docking::show(self, ui) });
egui::CentralPanel::default().frame(panel_frame).show(ui, |ui| {
if hide_ui {
viewport::central(self, ui);
} else {
docking::show(self, ui);
}
});
dock::finish_hidden_effect_rename(self);
let hovered_texture_set = self.next_hovered_texture_set.take();
if self.hovered_texture_set != hovered_texture_set {
self.hovered_texture_set = hovered_texture_set;
ctx.request_repaint();
}
windows::show(self, &ctx);
// Finish after the dock and windows have requested their thumbnails
@@ -1258,6 +1337,7 @@ impl eframe::App for TextureCraftApp {
#[cfg(not(target_arch = "wasm32"))]
updates_ui::show(self, &ctx);
self.framework_dialogs.run(ui);
toasts(self, &ctx);
#[cfg(not(target_arch = "wasm32"))]
self.file_dialogs.show_pending(frame);
@@ -1311,7 +1391,23 @@ pub fn data_folder(pref: &str) -> std::path::PathBuf {
std::path::Path::new(&home).join("Documents").join("TextureCraft")
}
/// The data folder in use: the Nightly profile when this is one, else Settings › Folders › Data folder.
/// An absolute preview cache override, or the app's default under the user's cache directory.
#[cfg(not(target_arch = "wasm32"))]
pub fn local_cache_folder(pref: &str) -> std::path::PathBuf {
let chosen = std::path::Path::new(pref.trim());
if chosen.is_absolute() {
return chosen.to_path_buf();
}
let cache = if has_data_root() {
data_dir().join("cache")
} else {
craft_update::Paths::per_user(UPDATE_APP.id).map_or_else(|_| data_dir().join("cache"), |paths| paths.cache)
};
cache.join("previews")
}
/// The Nightly profile's data folder, or the folder chosen in Settings › Files.
#[cfg(not(target_arch = "wasm32"))]
pub fn data_dir() -> std::path::PathBuf {
if let Some(root) = DATA_ROOT.get() {
@@ -1320,7 +1416,7 @@ pub fn data_dir() -> std::path::PathBuf {
DATA_FOLDER.get().cloned().unwrap_or_else(|| data_folder(""))
}
/// `<sub>` in the data folder in use (Settings › Folders › Data folder).
/// `<sub>` in the data folder in use (Settings › Files › Data folder).
#[cfg(not(target_arch = "wasm32"))]
pub fn user_dir(sub: &str) -> std::path::PathBuf {
data_dir().join(sub)
@@ -1400,7 +1496,10 @@ fn toasts(app: &mut TextureCraftApp, ctx: &egui::Context) {
ui.allocate_ui_with_layout(egui::vec2(width, 0.0), egui::Layout::top_down(egui::Align::Min), |ui| {
egui::ScrollArea::vertical().id_salt(("toast", i)).max_height(max_text_height).show(ui, |ui| {
ui.set_max_width(width);
ui.add(egui::Label::new(egui::RichText::new(&t.text).color(tk.text_strong)).wrap());
let label = ui.add(egui::Label::new(egui::RichText::new(&t.text).color(tk.text_strong)).wrap());
if t.announce {
ui.ctx().accesskit_node_builder(label.id, |node| node.set_live(egui::accesskit::Live::Polite));
}
});
if t.show_log && ui.link(i18n::tr("Open Log")).clicked() {
show_log = true;
+465
View File
@@ -0,0 +1,465 @@
//! Manual desktop saves share the atomic archive writer with autosave and headless saves.
use std::sync::{Arc, mpsc};
use std::time::Duration;
use texturecraft_engine::formats::project_file::SaveProgress;
use crate::{
TextureCraftApp,
i18n::{tr, trf},
state::Unsaved,
};
mod save_job;
pub(crate) use save_job::SaveJob;
const SAVE_POLL_INTERVAL: Duration = Duration::from_millis(80);
pub(crate) fn is_save(id: &str) -> bool {
matches!(id, "file.save" | "file.saveAs" | "file.saveCopy")
}
impl TextureCraftApp {
pub(crate) fn start_save(&mut self, path: &str, adopt: bool, for_prompt: bool, remember: bool) -> bool {
if self.save_job.is_some() {
self.toast(tr("A project save is already running"), true);
return false;
}
if let Err(error) = self.session.end_stroke() {
self.toast(error.to_string(), true);
return false;
}
let task = self.session.save_task(path, adopt);
let progress = Arc::new(SaveProgress::default());
let worker_progress = progress.clone();
let output = crate::spawn_worker("texturecraft-save", move || task.run(Some(&worker_progress)));
self.save_job = Some(SaveJob { progress, output, project_id: self.session.project_id, for_prompt, remember, quit_requested_by: None });
true
}
pub(crate) fn hold_close_for_save(&mut self) -> bool {
let Some(job) = &mut self.save_job else { return false };
// A close on a replacement project still waits for the outstanding archive
job.quit_requested_by = Some(self.session.project_id);
true
}
pub(crate) fn cancel_close_after_save(&mut self) {
self.quit_after_stroke = None;
if let Some(job) = &mut self.save_job {
job.quit_requested_by = None;
}
}
pub(crate) fn resume_close_after_stroke(&mut self, ctx: &egui::Context) {
let Some(project_id) = self.quit_after_stroke else { return };
if project_id == self.session.project_id && self.session.stroke_active() {
return;
}
self.quit_after_stroke = None;
if project_id == self.session.project_id && !crate::windows::ask_to_save(self, Unsaved::Quit) {
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
}
}
pub(crate) fn save_progress(&self) -> Option<f32> {
self.save_job.as_ref().map(|job| job.progress.fraction())
}
pub(crate) fn poll_save(&mut self, ctx: &egui::Context) {
let Some(job) = &self.save_job else { return };
let result = match job.output.try_recv() {
Ok(result) => result.map_err(|error| error.to_string()),
Err(mpsc::TryRecvError::Empty) => {
ctx.request_repaint_after(SAVE_POLL_INTERVAL);
return;
}
Err(mpsc::TryRecvError::Disconnected) => Err(tr("The project save worker stopped").into()),
};
let Some(job) = self.save_job.take() else { return };
let same_project = job.project_id == self.session.project_id;
let quit_requested = job.quit_requested_by == Some(self.session.project_id);
let continue_prompt = same_project && job.for_prompt && self.saving_for_prompt;
if continue_prompt {
self.saving_for_prompt = false;
}
let save_succeeded = result.is_ok();
match result {
Ok(output) => {
output.apply(&mut self.session);
if job.remember {
crate::windows::remember(self, &output.path);
}
if continue_prompt {
self.prompt_saved = !self.session.modified && !self.session.stroke_active() && !quit_requested;
}
self.toast(trf("Saved {path}", &[("path", &output.path)]), false);
}
Err(error) => {
let message = trf("Could not save project: {error}", &[("error", &error)]);
self.session.log.warn("Project", message.clone());
self.toast(message, true);
}
}
if quit_requested {
if self.session.stroke_active() {
self.quit_after_stroke = Some(self.session.project_id);
} else if !self.session.modified && (save_succeeded || !same_project) {
// A replacement project's own close only needs the previous writer to finish
self.ui.windows.unsaved = None;
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
} else {
crate::windows::ask_to_save(self, Unsaved::Quit);
}
}
if let Some(toast) = self.toasts.last_mut() {
toast.announce = true;
}
}
}
#[cfg(test)]
mod tests {
use egui::{ViewportCommand, ViewportEvent, ViewportId};
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT as _, Queryable as _};
use texturecraft_engine::{
Result,
file_cmds::{SaveOutput, SaveTask},
};
use super::*;
fn harness() -> Harness<'static, TextureCraftApp> {
let mut session = texturecraft_engine::sample_session(256, 64).unwrap();
session.modified = true;
let mut h = Harness::builder()
.with_size(egui::vec2(1600.0, 960.0))
.with_context_setup(crate::framework::install_headless)
.build_eframe(|cc| TextureCraftApp::new(cc, session));
// Match English labels independently of the system locale
h.state_mut().ui.prefs.language = "en".into();
h.run_steps(2);
h
}
fn temp_file(test: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!("tc-manual-save-{test}-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
dir.join("project.tcraft")
}
/// A save the test finishes by hand, so the close lands while it is still running
fn start_held_save(h: &mut Harness<'_, TextureCraftApp>, path: &std::path::Path, adopt: bool) -> (SaveTask, mpsc::Sender<Result<SaveOutput>>) {
let app = h.state_mut();
let task = app.session.save_task(&path.display().to_string(), adopt);
let (sender, output) = mpsc::channel();
app.save_job =
Some(SaveJob { progress: Arc::default(), output, project_id: app.session.project_id, for_prompt: false, remember: false, quit_requested_by: None });
(task, sender)
}
fn request_close(h: &mut Harness<'_, TextureCraftApp>) {
h.input_mut().viewports.entry(ViewportId::ROOT).or_default().events.push(ViewportEvent::Close);
h.step();
h.input_mut().viewports.entry(ViewportId::ROOT).or_default().events.clear();
h.run_steps(2);
}
/// Hands the worker's result over and reports whether the app asked to close in the next frames
fn finish(h: &mut Harness<'_, TextureCraftApp>, task: SaveTask, sender: &mpsc::Sender<Result<SaveOutput>>) -> bool {
sender.send(task.run(None)).unwrap();
sends_close(h)
}
/// Whether the app asks to close in the next frames
fn sends_close(h: &mut Harness<'_, TextureCraftApp>) -> bool {
(0..3).any(|_| {
h.step();
h.output().viewport_output.get(&ViewportId::ROOT).is_some_and(|v| v.commands.contains(&ViewportCommand::Close))
})
}
fn prompt_is_usable(h: &Harness<'_, TextureCraftApp>) -> bool {
["Save", "Don't save", "Cancel"].iter().all(|label| !h.get_by_label(label).accesskit_node().is_disabled())
}
#[test]
fn closing_during_a_regular_save_quits_once_it_has_saved() {
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let file = temp_file("close-then-saved");
let mut h = harness();
h.state_mut().session.path = Some(file.display().to_string());
let (task, sender) = start_held_save(&mut h, &file, true);
request_close(&mut h);
assert_eq!(h.state().ui.windows.unsaved, Some(Unsaved::Quit), "the changes are not written yet");
assert!(h.get_by_label("Save").accesskit_node().is_disabled(), "the prompt waits for the running save");
let closed = finish(&mut h, task, &sender);
assert!(closed, "the close goes on after the save");
assert!(file.exists());
assert!(!h.state().session.modified);
assert!(h.state().ui.windows.unsaved.is_none(), "no question is left once the changes are saved");
}
#[test]
fn closing_during_a_failed_save_keeps_a_usable_prompt() {
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let file = temp_file("close-then-failed").with_file_name("missing").join("project.tcraft");
let mut h = harness();
let (task, sender) = start_held_save(&mut h, &file, true);
request_close(&mut h);
let closed = finish(&mut h, task, &sender);
assert!(!closed);
assert!(h.state().session.modified);
assert_eq!(h.state().ui.windows.unsaved, Some(Unsaved::Quit));
assert!(prompt_is_usable(&h), "the prompt answers again after the failed write");
}
#[test]
fn closing_during_a_save_a_copy_keeps_the_prompt() {
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let file = temp_file("close-then-copied");
let mut h = harness();
let (task, sender) = start_held_save(&mut h, &file, false);
request_close(&mut h);
let closed = finish(&mut h, task, &sender);
assert!(!closed, "a copy leaves the project's own changes unsaved");
assert!(file.exists());
assert!(h.state().session.modified);
assert_eq!(h.state().ui.windows.unsaved, Some(Unsaved::Quit));
assert!(prompt_is_usable(&h));
}
#[test]
fn closing_during_a_save_keeps_the_prompt_for_later_edits() {
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let file = temp_file("close-then-edited");
let mut h = harness();
h.state_mut().session.path = Some(file.display().to_string());
let (task, sender) = start_held_save(&mut h, &file, true);
let rename = h.state_mut().run("textureSet.rename", serde_json::json!({"ts": 0, "name": "Edited while saving"}));
assert!(rename.is_some());
request_close(&mut h);
let closed = finish(&mut h, task, &sender);
assert!(!closed, "the edit made after the snapshot is not in the file");
assert!(h.state().session.modified);
assert_eq!(h.state().ui.windows.unsaved, Some(Unsaved::Quit));
assert!(prompt_is_usable(&h));
}
#[test]
fn an_edit_after_a_clean_close_asks_once_the_save_returns() {
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let file = temp_file("clean-close-then-edited");
let mut h = harness();
h.state_mut().session.modified = false;
h.state_mut().session.path = Some(file.display().to_string());
let (task, sender) = start_held_save(&mut h, &file, true);
request_close(&mut h);
assert!(h.state().ui.windows.unsaved.is_none(), "nothing to ask while the project is clean");
let rename = h.state_mut().run("textureSet.rename", serde_json::json!({"ts": 0, "name": "Edited while saving"}));
assert!(rename.is_some());
let closed = finish(&mut h, task, &sender);
assert!(!closed);
assert!(h.state().session.modified);
assert_eq!(h.state().ui.windows.unsaved, Some(Unsaved::Quit), "the close asks about the edit instead of being dropped");
assert!(prompt_is_usable(&h));
}
/// A clean project closed during its save, with paint still held down when the save returns
fn stroke_open_when_the_save_returns(test: &str) -> Harness<'static, TextureCraftApp> {
let file = temp_file(test);
let mut h = harness();
h.state_mut().session.modified = false;
h.state_mut().session.path = Some(file.display().to_string());
let (task, sender) = start_held_save(&mut h, &file, true);
request_close(&mut h);
h.state_mut().session.begin_stroke_uv(texturecraft_engine::geom::glam::Vec2::splat(0.5), 1.0).unwrap();
let closed = finish(&mut h, task, &sender);
assert!(!closed, "the open stroke may still change the project");
assert!(h.state().session.stroke_active());
assert!(h.state().ui.windows.unsaved.is_none());
h
}
#[test]
fn a_stroke_open_when_the_save_returns_asks_once_it_is_painted() {
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let mut h = stroke_open_when_the_save_returns("stroke-painted");
h.state_mut().session.end_stroke().unwrap();
let closed = sends_close(&mut h);
assert!(!closed);
assert!(h.state().session.modified);
assert_eq!(h.state().ui.windows.unsaved, Some(Unsaved::Quit), "the close asks about the painted stroke");
}
#[test]
fn a_stroke_open_when_the_save_returns_quits_once_it_is_canceled() {
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let mut h = stroke_open_when_the_save_returns("stroke-canceled");
h.state_mut().session.cancel_stroke();
let closed = sends_close(&mut h);
assert!(closed, "nothing is left to save, so the close goes on");
assert!(h.state().ui.windows.unsaved.is_none());
}
#[test]
fn opening_another_project_drops_the_close_that_waited_for_a_stroke() {
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let mut h = stroke_open_when_the_save_returns("stroke-replaced");
h.state_mut().session = texturecraft_engine::sample_session(256, 64).unwrap();
let closed = sends_close(&mut h);
assert!(!closed, "the old project's close does not quit the new one");
assert!(h.state().ui.windows.unsaved.is_none());
assert!(h.state().quit_after_stroke.is_none());
}
#[test]
fn replacing_the_project_during_a_save_drops_its_pending_close() {
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
for stroke_active in [false, true] {
let test = if stroke_active { "replace-saving-stroke" } else { "replace-saving-dirty" };
let file = temp_file(test);
let mut h = harness();
h.state_mut().session.modified = false;
let (task, sender) = start_held_save(&mut h, &file, true);
request_close(&mut h);
assert_eq!(h.state().save_job.as_ref().unwrap().quit_requested_by, Some(h.state().session.project_id));
h.state_mut().session = texturecraft_engine::sample_session(256, 64).unwrap();
if stroke_active {
h.state_mut().session.begin_stroke_uv(texturecraft_engine::geom::glam::Vec2::splat(0.5), 1.0).unwrap();
} else {
assert!(h.state_mut().run("textureSet.rename", serde_json::json!({"ts": 0, "name": "Replacement edit"})).is_some());
}
assert!(!finish(&mut h, task, &sender));
assert!(file.exists(), "the old archive still finished");
assert!(h.state().session.path.is_none(), "the replacement does not adopt the old archive");
assert!(h.state().ui.windows.unsaved.is_none(), "the old close does not prompt about the replacement");
if stroke_active {
h.state_mut().session.cancel_stroke();
assert!(!sends_close(&mut h), "the old close does not survive the replacement's stroke");
}
}
}
#[test]
fn replacing_a_project_with_an_open_quit_prompt_discards_its_answer() {
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let file = temp_file("replace-prompt");
let mut h = harness();
let (task, sender) = start_held_save(&mut h, &file, true);
request_close(&mut h);
assert_eq!(h.state().ui.windows.unsaved, Some(Unsaved::Quit));
let ctx = h.ctx.clone();
let result = crate::control::handle(h.state_mut(), &ctx, "command.run", &serde_json::json!({ "id": "file.close" }));
assert_eq!(result["ok"], true);
assert!(!finish(&mut h, task, &sender));
assert!(h.state().ui.windows.unsaved.is_none(), "the discarded project's prompt cannot act on the replacement");
}
#[test]
fn closing_the_replacement_waits_for_the_original_archive() {
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let file = temp_file("close-replacement");
let mut h = harness();
let (task, sender) = start_held_save(&mut h, &file, true);
let replacement = texturecraft_engine::sample_session(256, 64).unwrap();
h.state_mut().session.switch_to(replacement);
assert!(crate::windows::close_requested(h.state_mut()), "the new close must hold the process open for the pending write");
let closed = finish(&mut h, task, &sender);
assert!(file.exists());
assert!(closed, "the replacement's own close resumes once the writer finishes");
assert!(h.state().session.path.is_none());
assert!(h.state().ui.windows.unsaved.is_none());
}
#[test]
fn closing_the_replacement_resumes_after_the_original_save_fails() {
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let file = temp_file("close-replacement-after-failure").with_file_name("missing").join("project.tcraft");
let mut h = harness();
let (task, sender) = start_held_save(&mut h, &file, true);
let replacement = texturecraft_engine::sample_session(256, 64).unwrap();
h.state_mut().session.switch_to(replacement);
request_close(&mut h);
assert!(!sends_close(&mut h), "the replacement waits for the original save");
let result = task.run(None);
assert!(result.is_err(), "the original write fails");
sender.send(result).unwrap();
assert!(sends_close(&mut h), "the replacement's own close resumes after the failed write");
assert!(h.state().ui.windows.unsaved.is_none());
}
#[test]
fn canceling_a_stroke_after_a_successful_save_leaves_the_saved_edits_clean() {
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let file = temp_file("saved-then-cancel-stroke");
let mut h = harness();
let (task, sender) = start_held_save(&mut h, &file, true);
h.state_mut().session.begin_stroke_uv(texturecraft_engine::geom::glam::Vec2::splat(0.5), 1.0).unwrap();
assert!(!finish(&mut h, task, &sender));
h.state_mut().session.cancel_stroke();
assert!(!crate::windows::close_requested(h.state_mut()), "the saved edits and canceled stroke need no second save");
}
#[test]
fn dismissing_the_prompt_during_a_save_cancels_the_quit() {
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let file = temp_file("close-then-dismissed");
let mut h = harness();
h.state_mut().session.path = Some(file.display().to_string());
let (task, sender) = start_held_save(&mut h, &file, true);
request_close(&mut h);
h.get_by_label("Close window").click();
h.run_steps(2);
assert!(h.state().ui.windows.unsaved.is_none(), "the prompt is dismissed while the save runs");
let closed = finish(&mut h, task, &sender);
assert!(!closed, "a dismissed prompt keeps the app open");
assert!(!h.state().session.modified);
}
}
@@ -0,0 +1,12 @@
use std::sync::{Arc, mpsc};
use texturecraft_engine::{Result, file_cmds::SaveOutput, formats::project_file::SaveProgress};
pub(crate) struct SaveJob {
pub(super) progress: Arc<SaveProgress>,
pub(super) output: mpsc::Receiver<Result<SaveOutput>>,
pub(super) project_id: u64,
pub(super) for_prompt: bool,
pub(super) remember: bool,
pub(super) quit_requested_by: Option<u64>,
}
+44 -16
View File
@@ -148,6 +148,11 @@ fn tooltip_of(id: &str) -> Option<&'static str> {
/// Whether an item can run now
pub fn enabled(app: &TextureCraftApp, id: &str) -> bool {
#[cfg(not(target_arch = "wasm32"))]
if app.save_job.is_some() && crate::manual_save::is_save(id) {
return false;
}
if UNAVAILABLE.contains(&id) {
return false;
}
@@ -179,6 +184,11 @@ pub fn enabled(app: &TextureCraftApp, id: &str) -> bool {
return false;
}
// A shortcut has no explicit layer to toggle
if id == "mask.toggle" && app.session.selected_layer().is_none() {
return false;
}
if is_ui(id) {
return app.session.project_open || !ui_needs_project(id);
}
@@ -414,7 +424,7 @@ pub fn forwarded_shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context, event
continue;
}
let Some(id) = app.bindings.command_of(&event) else { continue };
invoke(app, ctx, effect_command(app, &id));
run_shortcut(app, ctx, &id);
}
}
@@ -447,9 +457,9 @@ fn effect_command<'a>(app: &TextureCraftApp, id: &'a str) -> &'a str {
}
}
/// Runs the commands bound to the keys pressed this frame, outside text fields and key capture
/// Runs the commands bound to the keys pressed this frame, with no widget but the viewport focused, outside key capture
pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) {
if crate::keymap::capturing(ctx) || (ctx.memory(|memory| memory.focused().is_some()) && ctx.egui_wants_keyboard_input()) {
if crate::keymap::capturing(ctx) || crate::framework::widget_has_keyboard(ctx) {
return;
}
@@ -458,6 +468,20 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) {
return;
}
// A plain Escape or Enter while no widget of TextureCraft's has the keyboard is the window's cancel or submit: back
// in egui's input, it runs the Escape and Enter handlers below, the shortcuts and the Path tool's keys
for (key, taken) in [(Key::Escape, crate::framework::take_window_cancel(ctx)), (Key::Enter, crate::framework::take_window_submit(ctx))] {
if taken {
let escape = craft_ui::runtime::keys::escape_mods(ctx).filter(|_| key == Key::Escape);
ctx.input_mut(|i| {
// A submit's Enter had no Ctrl or Cmd; one that came down later in the pass is not its own
let (shift, alt) = escape.map_or((i.modifiers.shift, i.modifiers.alt), |held| (held.shift, held.alt));
let modifiers = Modifiers { shift, alt, ..Modifiers::NONE };
i.events.insert(0, egui::Event::Key { key, physical_key: Some(key), pressed: true, repeat: false, modifiers });
});
}
}
// The dispatcher reads clipboard events as shortcuts; a pasted image also means Ctrl+V
// Unless bound, Shift+Delete and Shift+Insert become Ctrl+X and Ctrl+V
ctx.input_mut(|input| {
@@ -472,14 +496,13 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) {
});
// Let the innermost popup consume Escape before cancelling the active tool
let popup_open = egui::Popup::is_any_open(ctx);
// (the drop popup of the Output templates tab is open without registering with egui, and reads Escape itself)
let popup_open = egui::Popup::is_any_open(ctx) || app.ui.export.pending_drop.is_some();
let point_pick_armed = crate::generator_point_pick::armed(ctx).is_some();
let mut cancel_point_pick = false;
let picker_open = crate::color_picker::open_window(ctx).is_some();
let no_widget_focused = ctx.memory(|memory| memory.focused().is_none());
#[cfg(not(target_arch = "wasm32"))]
let nothing_focused = ctx.memory(|memory| memory.focused().is_none());
let nothing_focused = !crate::framework::widget_has_keyboard(ctx);
let log_copies = crate::log_panel::takes_copy(app, ctx);
let commands_to_invoke = ctx.input_mut(|input| {
// egui's label selection copies on these events at the end of the frame
@@ -491,7 +514,7 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) {
// Escape and Enter answer the Reset UI question first, even when a shortcut binds them
let confirming_reset = app.ui.windows.confirm_reset_ui;
if confirming_reset && !popup_open {
crate::windows::reset_ui_keys(app, input, no_widget_focused);
crate::windows::reset_ui_keys(app, input, nothing_focused);
}
// F2 renames the selected template on Output templates, before its 3D view binding
@@ -552,17 +575,22 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) {
}
for id in &commands_to_invoke {
if matches!(id.as_str(), "layer.copy" | "layer.cut")
&& let Some(layer) = app.session.selected_layer().and_then(|layer| app.session.doc.project.layers.get(&layer))
{
// Ctrl+V reaches the app only while the system clipboard holds text or an image
ctx.copy_text(layer.name.clone());
}
invoke(app, ctx, effect_command(app, id));
run_shortcut(app, ctx, id);
}
}
/// Runs the command a shortcut is bound to. A layer copy or cut also puts the layer's name on the system clipboard:
/// Ctrl+V reaches the app only while that clipboard holds text or an image.
fn run_shortcut(app: &mut TextureCraftApp, ctx: &egui::Context, id: &str) {
if matches!(id, "layer.copy" | "layer.cut")
&& let Some(layer) = app.session.selected_layer().and_then(|layer| app.session.doc.project.layers.get(&layer))
{
ctx.copy_text(layer.name.clone());
}
invoke(app, ctx, effect_command(app, id));
}
/// The desktop and web shells turn Ctrl+C, Ctrl+X and Ctrl+V (and Ctrl+Insert, Shift+Delete,
/// Shift+Insert) into clipboard events instead of key presses. Outside a text field they are the
/// shortcuts bound to Ctrl+C, Ctrl+X and Ctrl+V (copy, cut and paste a layer by default).
+15 -8
View File
@@ -31,6 +31,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) {
let mut open = true;
let (mut export, mut cancel) = (false, false);
let mut triangulated = true;
crate::windows::dialog(ctx, "mesh_export_options", tr("Mesh Export Options"), &mut open).show(ctx, |ui| {
ui.set_width(DIALOG_WIDTH);
@@ -38,24 +39,26 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) {
ui.add(egui::RadioButton::new(true, tr("Without displacement/tessellation")));
option(
ui,
true,
&mut triangulated,
false,
tr("Apply triangulation"),
&[
tr("Splits every face with more than three corners into triangles; triangles stay as they are."),
tr("TextureCraft keeps meshes as triangles, so the exported mesh is always triangulated."),
],
);
ui.add_space(GROUP_GAP);
unavailable::greyed(ui, |ui| ui.add(egui::RadioButton::new(false, tr("With displacement/tessellation"))));
option(
ui,
&mut app.ui.mesh_recompute_normals,
true,
tr("Recompute vertex normals"),
&[
tr("Replaces the mesh's vertex normals with newly computed ones in the exported file."),
tr("TextureCraft cannot do this yet: it writes the vertex normals the mesh has in the project."),
tr("On: smooth area-weighted normals from the exported geometry. Off: the project's stored normals. The project itself is not changed."),
],
);
ui.add_space(GROUP_GAP);
unavailable::greyed(ui, |ui| ui.add(egui::RadioButton::new(false, tr("With displacement/tessellation"))));
ui.add_space(8.0);
// One row keeps the window to its contents; a bare right-to-left layout fills the screen height
@@ -76,12 +79,16 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) {
}
}
/// A greyed option under a choice, ticked as the reference shows it, with an info icon at the
/// row's right end whose tooltip has the paragraphs `info`
fn option(ui: &mut Ui, checked: bool, label: &str, info: &[&str]) {
/// An option under a choice, greyed when `enabled` is false, with an info icon at the row's right
/// end whose tooltip has the paragraphs `info`.
fn option(ui: &mut Ui, checked: &mut bool, enabled: bool, label: &str, info: &[&str]) {
ui.horizontal(|ui| {
ui.add_space(OPTION_INDENT);
unavailable::checkbox(ui, checked, label);
if enabled {
ui.checkbox(checked, label);
} else {
unavailable::checkbox(ui, *checked, label);
}
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let icon = ui.label(egui::RichText::new(egui_phosphor::regular::INFO).color(Tokens::get(ui.ctx()).text_dim));
icon.on_hover_ui(|ui| {
+2 -2
View File
@@ -292,7 +292,7 @@ mod tests {
/// Presses the left button on Move on model (the preview square) and holds it; returns the system's pointer, resting there
fn press_the_button(harness: &mut Harness) -> SystemPointer {
let at = harness.get_by_label("Move on model").rect().center();
let mut pointer = SystemPointer::at(harness, at);
let mut pointer = SystemPointer::in_app(harness, at);
pointer.button(harness, PointerButton::Primary, true, Modifiers::NONE);
pointer
}
@@ -439,7 +439,7 @@ mod tests {
assert!((pad.width() - pad.height()).abs() < 1.0 && pad.width() > 60.0, "Move on model is the preview square, no row of its own: {pad:?}");
let before = projection(&harness, layer);
let mut pointer = SystemPointer::at(&mut harness, pad.left_top() + vec2(4.0, 4.0));
let mut pointer = SystemPointer::in_app(&mut harness, pad.left_top() + vec2(4.0, 4.0));
pointer.button(&mut harness, PointerButton::Primary, true, Modifiers::NONE);
assert_eq!(harness.state().moving_on_model, Some(MoveOnModel::layer(layer)), "a press at its corner starts the hold");
+18 -4
View File
@@ -13,8 +13,8 @@ use texturecraft_engine::template_cmds::template_label;
use crate::TextureCraftApp;
use crate::i18n::{tr, trf};
use crate::project_form::{
FIELD_WIDTH_POINTS, ROW_INDENT_POINTS, auto_unwrap_row, check_row, collapsible, color_management, note, physical_size, row, sub_title, tangent_space_row,
unavailable, uv_tile_radios,
FIELD_WIDTH_POINTS, ROW_INDENT_POINTS, check_row, collapsible, color_management, note, physical_size, row, sub_title, tangent_space_row, unavailable,
uv_tile_radios,
};
use crate::state::{Mode, NewProject};
use crate::theme::{Tokens, caption};
@@ -151,6 +151,7 @@ pub fn create_command(new_project: &NewProject) -> Option<Value> {
"uvTiles": new_project.uv_tiles == Some(true),
"template": new_project.template,
"importCameras": new_project.import_cameras,
"rebuildUvs": new_project.rebuild_uvs,
}))
}
@@ -169,7 +170,14 @@ fn create_project(app: &mut TextureCraftApp) -> bool {
let stem = std::path::Path::new(name).file_stem().and_then(|stem| stem.to_str()).unwrap_or("Untitled").to_string();
let template = app.session.template(&new_project.template);
match texturecraft_engine::Session::from_mesh_bytes_tiled(name, bytes, new_project.resolution, &stem, Some(new_project.uv_tiles == Some(true))) {
match texturecraft_engine::Session::from_mesh_bytes_with_uvs(
name,
bytes,
new_project.resolution,
&stem,
Some(new_project.uv_tiles == Some(true)),
new_project.rebuild_uvs,
) {
Ok(mut next) => {
if !new_project.import_cameras {
next.doc.project.cameras.clear();
@@ -259,12 +267,18 @@ fn advanced_settings(app: &mut TextureCraftApp, ui: &mut Ui) {
if check_row(ui, None, |ui| ui.checkbox(&mut uv_tiles, tr("Use UV Tile workflow")), |_| {}).changed() {
new_project.uv_tiles = Some(uv_tiles);
}
uv_tile_radios(ui, uv_tiles, tr("Tick Use UV Tile workflow first"));
ui.add_space(4.0);
sub_title(ui, tr("Import settings"), None);
check_row(ui, Some(tr("Keep the cameras stored in the mesh file")), |ui| ui.checkbox(&mut new_project.import_cameras, tr("Import cameras")), |_| {});
auto_unwrap_row(ui);
check_row(
ui,
Some(tr("Generate a fresh UV layout even when the mesh already has UVs. Meshes without UVs are always unwrapped.")),
|ui| ui.checkbox(&mut new_project.rebuild_uvs, tr("Rebuild mesh UVs")),
|_| {},
);
ui.add_space(4.0);
collapsible(ui, "np_import_baked_maps", tr("Import baked maps"), true, None, |ui| {
+269
View File
@@ -0,0 +1,269 @@
//! Two panes split by a focusable divider: the geometry of one split and its resize handle (pointer drag, arrow keys
//! and accessibility). The shelf's saved searches and path filter (`shelf_panes.rs`) use it.
use std::ops::RangeInclusive;
use craft_behavior::dock::SplitSize;
use craft_behavior::flow::Axis;
use egui::{Color32, EventFilter, Id, Key, Modifiers, Rect, Response, Sense, Ui, Vec2, accesskit};
/// Contained, non-overlapping rectangles of a single split, including its divider.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct SplitLayout {
pub(crate) first: Rect,
pub(crate) divider: Rect,
pub(crate) second: Rect,
first_size: f32,
available: f32,
}
impl SplitLayout {
/// The first pane's size along the split axis, in points.
pub(crate) fn first_size(self) -> f32 {
self.first_size
}
/// Space for both panes, excluding the divider, in points.
pub(crate) fn available(self) -> f32 {
self.available
}
/// The size after moving the divider by `delta` points, in the same sizing mode. When both minima cannot fit,
/// each pane gets half the available space. Invalid inputs and zero available space give `None`, so the caller
/// keeps its saved value.
pub(crate) fn resized(self, size: SplitSize, delta: f32, minimum: f32) -> Option<SplitSize> {
if !value(size).is_finite() || !delta.is_finite() || !valid_nonnegative(minimum) || self.available <= 0.0 {
return None;
}
let available = f64::from(self.available);
let first = clamp_first(f64::from(self.first_size) + f64::from(delta), available, minimum);
Some(match size {
SplitSize::FixedFirst(_) => SplitSize::FixedFirst(first as f32),
SplitSize::FixedSecond(_) => SplitSize::FixedSecond((available - first) as f32),
_ => SplitSize::Ratio((first / available) as f32),
})
}
}
fn value(size: SplitSize) -> f32 {
match size {
SplitSize::Ratio(v) | SplitSize::FixedFirst(v) | SplitSize::FixedSecond(v) => v,
#[allow(unreachable_patterns)]
_ => f32::NAN,
}
}
/// Divides `rect` into two panes and a divider `gap` points thick. Equal pane minima relax to half the remaining
/// span in tiny areas; finite sizes outside the available range are clamped. Inverted or non-finite rectangles, a
/// negative or non-finite gap or minimum and a non-finite size give `None`.
pub(crate) fn split_rect(rect: Rect, axis: Axis, size: SplitSize, gap: f32, minimum: f32) -> Option<SplitLayout> {
if !valid_rect(rect) || !valid_nonnegative(gap) || !valid_nonnegative(minimum) || !value(size).is_finite() {
return None;
}
let total = if axis == Axis::X { rect.width() } else { rect.height() };
let gap = gap.min(total);
let available = total - gap;
let space = f64::from(available);
// f64: two finite f32 inputs can overflow when multiplied.
let wanted = match size {
SplitSize::FixedFirst(points) => f64::from(points),
SplitSize::FixedSecond(points) => space - f64::from(points),
other => space * f64::from(value(other)),
};
let first_size = clamp_first(wanted, space, minimum) as f32;
let (mut first, mut divider, mut second) = (rect, rect, rect);
if axis == Axis::X {
first.max.x = (rect.min.x + first_size).min(rect.max.x);
divider.min.x = first.max.x;
divider.max.x = (divider.min.x + gap).min(rect.max.x);
second.min.x = divider.max.x;
} else {
first.max.y = (rect.min.y + first_size).min(rect.max.y);
divider.min.y = first.max.y;
divider.max.y = (divider.min.y + gap).min(rect.max.y);
second.min.y = divider.max.y;
}
Some(SplitLayout { first, divider, second, first_size, available })
}
fn valid_rect(rect: Rect) -> bool {
rect.min.is_finite()
&& rect.max.is_finite()
&& rect.width().is_finite()
&& rect.height().is_finite()
&& rect.min.x <= rect.max.x
&& rect.min.y <= rect.max.y
}
fn valid_nonnegative(value: f32) -> bool {
value.is_finite() && value >= 0.0
}
fn clamp_first(wanted: f64, available: f64, minimum: f32) -> f64 {
let low = f64::from(minimum).min(available * 0.5);
wanted.clamp(low, available - low)
}
/// Colours of a resize handle. The handle at rest paints no fill.
#[derive(Clone, Copy, Debug)]
pub(crate) struct ResizeHandleStyle {
pub(crate) hovered: Color32,
pub(crate) dragged: Color32,
pub(crate) focused: Color32,
}
/// A focusable divider moved by a pointer drag, the arrows along its axis while it has focus, and accessibility's
/// Increment, Decrement and SetValue. It never stores a size: [`show`](ResizeHandle::show) returns the move along the
/// axis for the caller to apply.
pub(crate) struct ResizeHandle<'a> {
id: Id,
axis: Axis,
rect: Rect,
label: &'a str,
style: ResizeHandleStyle,
hit_margin: f32,
value: Option<(f32, RangeInclusive<f32>)>,
}
/// Keyboard and accessibility step, in points.
const STEP: f32 = 8.0;
impl<'a> ResizeHandle<'a> {
pub(crate) fn new(id: Id, axis: Axis, rect: Rect, label: &'a str, style: ResizeHandleStyle) -> Self {
Self { id, axis, rect, label, style, hit_margin: 3.0, value: None }
}
/// Widens the hit rectangle along the movement axis, in points. Default: 3.
pub(crate) fn hit_margin(mut self, margin: f32) -> Self {
self.hit_margin = margin;
self
}
/// The current size and its bounds, for accessibility and its SetValue action.
pub(crate) fn value(mut self, value: f32, range: RangeInclusive<f32>) -> Self {
self.value = Some((value, range));
self
}
/// Shows the handle and returns the requested move along the axis this pass, in points (0 for none).
pub(crate) fn show(self, ui: &mut Ui) -> f32 {
let horizontal = self.axis == Axis::X;
let hit = self.rect.expand2(if horizontal { Vec2::new(self.hit_margin, 0.0) } else { Vec2::new(0.0, self.hit_margin) });
let valid = valid_rect(self.rect)
&& self.rect.width() > 0.0
&& self.rect.height() > 0.0
&& valid_rect(hit)
&& (0.0..=4096.0).contains(&self.hit_margin)
&& self
.value
.as_ref()
.is_none_or(|(value, range)| value.is_finite() && range.start().is_finite() && range.end().is_finite() && range.start() <= range.end());
let inert = Rect::from_min_size(ui.min_rect().min, Vec2::ZERO);
let mut response = ui.interact(if valid { hit } else { inert }, self.id, if valid { Sense::drag() } else { Sense::hover() });
let enabled = valid && response.enabled();
let mut delta = 0.0;
if enabled {
drag_focus(ui, &response);
if response.dragged() {
let drag = response.drag_delta();
delta = if horizontal { drag.x } else { drag.y };
}
if response.has_focus() {
let filter = EventFilter { horizontal_arrows: horizontal, vertical_arrows: !horizontal, ..Default::default() };
ui.memory_mut(|memory| memory.set_focus_lock_filter(response.id, filter));
let (back, forward) = if horizontal { (Key::ArrowLeft, Key::ArrowRight) } else { (Key::ArrowUp, Key::ArrowDown) };
ui.input_mut(|input| {
if input.consume_key(Modifiers::NONE, back) {
delta -= STEP;
}
if input.consume_key(Modifiers::NONE, forward) {
delta += STEP;
}
});
}
let mut change = 0.0;
ui.input_mut(|input| {
input.consume_accesskit_action_requests(response.id, |request| match request.action {
accesskit::Action::Increment => {
change += STEP;
true
}
accesskit::Action::Decrement => {
change -= STEP;
true
}
accesskit::Action::SetValue => {
if let (Some((value, range)), Some(accesskit::ActionData::NumericValue(new_value))) = (&self.value, &request.data)
&& new_value.is_finite()
{
change = (new_value.clamp(f64::from(*range.start()), f64::from(*range.end())) - f64::from(*value)) as f32;
delta = 0.0;
}
true
}
_ => false,
});
});
delta += change;
}
if !delta.is_finite() {
delta = 0.0;
}
if delta != 0.0 {
response.mark_changed();
}
response.widget_info(|| match &self.value {
Some((value, _)) if valid => egui::WidgetInfo::slider(enabled, f64::from(*value), self.label),
_ => egui::WidgetInfo::labeled(egui::Role::Unknown, enabled, self.label),
});
ui.ctx().accesskit_node_builder(response.id, |node| {
node.set_role(accesskit::Role::Splitter);
// Orientation describes the divider itself, across its movement axis.
node.set_orientation(if horizontal { accesskit::Orientation::Vertical } else { accesskit::Orientation::Horizontal });
if enabled {
node.add_action(accesskit::Action::Increment);
node.add_action(accesskit::Action::Decrement);
if let Some((value, range)) = &self.value {
node.set_numeric_value(f64::from(*value));
node.set_min_numeric_value(f64::from(*range.start()));
node.set_max_numeric_value(f64::from(*range.end()));
node.set_numeric_value_step(f64::from(STEP));
node.add_action(accesskit::Action::SetValue);
}
}
});
if enabled {
let fill = if response.dragged() {
Some(self.style.dragged)
} else if response.has_focus() {
Some(self.style.focused)
} else if response.hovered() {
Some(self.style.hovered)
} else {
None
};
if let Some(fill) = fill {
ui.painter().rect_filled(self.rect, 0.0, fill);
}
if response.hovered() || response.dragged() {
ui.ctx().set_cursor_icon(if horizontal { egui::CursorIcon::ResizeHorizontal } else { egui::CursorIcon::ResizeVertical });
}
}
delta
}
}
/// A pointer drag focuses its handle for the gesture only and gives the focus up on release, so the app's shortcuts
/// and its canvas arrow keys work again. A handle focused from the keyboard before the drag keeps its focus.
fn drag_focus(ui: &Ui, response: &Response) {
let key = response.id.with("pointer-focus");
if response.drag_started() {
if !response.has_focus() {
ui.ctx().data_mut(|d| d.insert_temp(key, ()));
}
response.request_focus();
}
if response.drag_stopped() && ui.ctx().data_mut(|d| d.remove_temp::<()>(key)).is_some() {
response.surrender_focus();
}
}
@@ -12,12 +12,25 @@ pub(crate) struct SystemPointer {
pub(crate) put_backs: usize,
/// The system folds a put-back into the next move, as Windows does, instead of reporting it as a move of its own
pub(crate) folds: bool,
/// The harness has no eframe app, so the test runs the app's raw input rewrite itself; an app harness runs the
/// app's `raw_input_hook` before every pass, as eframe does
rewrites: bool,
}
impl SystemPointer {
/// The pointer resting at `at` over the window
/// The pointer resting at `at` over a window that shows a bare UI, whose raw input the test rewrites as the
/// app's hook would
pub(crate) fn at<S>(harness: &mut Harness<'_, S>, at: Pos2) -> SystemPointer {
let mut pointer = SystemPointer { at, locked: false, hidden: false, put_backs: 0, folds: false };
Self::start(harness, at, true)
}
/// The pointer resting at `at` over the app's window, whose own raw input hook rewrites the input
pub(crate) fn in_app<S>(harness: &mut Harness<'_, S>, at: Pos2) -> SystemPointer {
Self::start(harness, at, false)
}
fn start<S>(harness: &mut Harness<'_, S>, at: Pos2, rewrites: bool) -> SystemPointer {
let mut pointer = SystemPointer { at, locked: false, hidden: false, put_backs: 0, folds: false, rewrites };
harness.input_mut().events.push(Event::PointerMoved(at));
pointer.frame(harness);
pointer
@@ -52,8 +65,10 @@ impl SystemPointer {
/// One frame of everything the system sent since the last: the app's raw input hook rewrites it, the app runs, and the pointer does what the app asked
pub(crate) fn frame<S>(&mut self, harness: &mut Harness<'_, S>) {
let ctx = harness.ctx.clone();
super::rewrite(&ctx, harness.input_mut());
if self.rewrites {
let ctx = harness.ctx.clone();
super::rewrite(&ctx, harness.input_mut());
}
harness.step();
let output = harness.output();
self.hidden = output.platform_output.cursor_icon == CursorIcon::None;
+1 -1
View File
@@ -108,7 +108,7 @@ fn a_number_field_scrubs_past_the_edge_with_the_pointer_held() {
let (mut harness, layer) = crate::frame_gizmo::tests::fill_app("triplanar");
hold_like(&harness.ctx, Hold::PutBack);
let press = harness.get_by_label("Offset X").rect().center();
let mut pointer = SystemPointer::at(&mut harness, press);
let mut pointer = SystemPointer::in_app(&mut harness, press);
pointer.button(&mut harness, PointerButton::Primary, true, Modifiers::NONE);
let window = harness.ctx.content_rect().width();
pointer.drags(&mut harness, vec2(2.0 * window, 0.0), 40, Modifiers::NONE);
+1
View File
@@ -158,6 +158,7 @@ pub(crate) fn uv_tile_radios(ui: &mut Ui, enabled: bool, disabled_hint: &str) {
/// Import settings ▸ Auto-unwrap and its options. Meshes without UVs are always unwrapped, so the
/// box is ticked; turning it off and the options are not available yet.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn auto_unwrap_row(ui: &mut Ui) {
check_row(
ui,
+10 -4
View File
@@ -29,12 +29,14 @@ pub(crate) fn let_go<G: Gizmo>(ctx: &egui::Context) {
/// Drags on `gizmo`'s handles (one undo step per drag, the projection updates live); returns whether a drag owns the pointer. The cursor shows what the handle under it, or the one dragged, does (only while the gizmo takes input: an Alt orbit or a held Move on model keeps its own)
pub(crate) fn input<G: Gizmo>(app: &mut TextureCraftApp, ctx: &egui::Context, response: &egui::Response, rect: Rect, gizmo: Option<&G>) -> bool {
let mut drag = dragging::<G>(ctx).filter(|drag| gizmo.is_some_and(|gizmo| gizmo.same_projection(&drag.start)));
let mesh_id = app.session.mesh_id;
let mut drag = dragging::<G>(ctx).filter(|drag| drag.mesh_id == mesh_id && gizmo.is_some_and(|gizmo| gizmo.same_projection(&drag.start)));
if response.drag_started_by(PointerButton::Primary)
&& let (Some(gizmo), Some(from)) = (gizmo, ctx.input(|input| input.pointer.press_origin()))
&& let Some(grab) = gizmo.grab(from)
{
drag = Some(GizmoDrag { grab, from, start: Arc::new(gizmo.clone()), edited_revision: None });
drag = Some(GizmoDrag { grab, from, mesh_id, start: Arc::new(gizmo.clone()), edited_revision: None });
}
// Apply a final move on release and let focus loss end a drag without one
@@ -51,19 +53,23 @@ pub(crate) fn input<G: Gizmo>(app: &mut TextureCraftApp, ctx: &egui::Context, re
// A drag lives only while its gizmo shows, so the gizmo drawn this frame names the cursor
ctx.set_cursor_icon(gizmo.unwrap_or(&drag.start).cursor(drag.grab, true));
if let Some(pointer) = response.interact_pointer_pos().filter(|_| ctx.input(|input| input.pointer.delta() != egui::Vec2::ZERO))
&& let Some((command, params)) = drag.start.edit(app, rect, drag.grab, drag.from, pointer)
let (moved, snapping) = ctx.input(|input| (input.pointer.delta() != egui::Vec2::ZERO, input.modifiers.ctrl || input.modifiers.command));
if moved
&& let Some(pointer) = response.interact_pointer_pos()
&& let Some((command, params)) = drag.start.edit_with_snap(app, rect, drag.grab, drag.from, pointer, snapping)
{
edit_in_one_step(&mut app.session, command, params, &mut drag.edited_revision);
// The panel drew before this edit: one more frame shows its fields and preview where the projection is now
ctx.request_repaint();
}
if released {
let_go::<G>(ctx);
} else {
ctx.data_mut(|data| data.insert_temp(G::drag_id(), drag));
}
true
}
@@ -20,6 +20,11 @@ pub(crate) trait Gizmo: Clone + Send + Sync + 'static {
/// The command and params a drag of `grab` from `from` to `to` runs
fn edit(&self, app: &TextureCraftApp, rect: Rect, grab: Self::Grab, from: Pos2, to: Pos2) -> Option<(&'static str, Value)>;
/// As [`Gizmo::edit`], the drag snapping to the tool bar's steps while `snapping` (a gizmo with none ignores it)
fn edit_with_snap(&self, app: &TextureCraftApp, rect: Rect, grab: Self::Grab, from: Pos2, to: Pos2, _snapping: bool) -> Option<(&'static str, Value)> {
self.edit(app, rect, grab, from, to)
}
/// The cursor over `grab`, or dragging it
fn cursor(&self, grab: Self::Grab, dragging: bool) -> egui::CursorIcon;
}
@@ -10,6 +10,8 @@ pub(crate) struct GizmoDrag<G: Gizmo> {
pub(crate) grab: G::Grab,
/// Where the drag started
pub(crate) from: Pos2,
/// The loaded mesh at press time, including its UV layout
pub(crate) mesh_id: u64,
/// The starting gizmo shared by the pointer, edit and overlay paths
pub(crate) start: Arc<G>,
/// The session revision the drag's last edit left: later updates merge into its undo step while the history is still there
@@ -285,9 +285,8 @@ impl PropertySheet<'_> {
});
// Escape ends hex editing first even when egui has already dropped the field's focus
let escape = ctx.input(|input| input.key_pressed(egui::Key::Escape))
&& ctx.memory(|memory| memory.focused().is_none_or(|focused| focused == bar.id))
&& !hex_took_escape(&ctx);
let escape =
crate::framework::escape_pressed(&ctx) && crate::framework::focused_widget(&ctx).is_none_or(|focused| focused == bar.id) && !hex_took_escape(&ctx);
if closed || (!list_open && !waiting && (pressed_outside || escape)) {
state.open = false;
crate::color_picker::forget_window(&ctx);
+2 -2
View File
@@ -74,8 +74,8 @@ pub(crate) use preview_size::PreviewSize;
pub(crate) use properties_scroll::{PropertiesScroll, PropertiesSelection};
pub(crate) use row_lead::RowLead;
pub(crate) use section_tabs::{
SectionScope, TAB_GAP, TAB_ICON_CENTER, TAB_ICON_SIZE, TAB_NAME_LEFT, TAB_PADDING, TAB_ROUNDING, TAB_TEXT_SIZE, TAB_TOP, forget_sections,
full_height_tab_rect, in_scope, room_past_end, section_tabs, shown_tab_box,
SectionScope, TAB_GAP, TAB_ICON_CENTER, TAB_ICON_SIZE, TAB_NAME_LEFT, TAB_PADDING, TAB_ROUNDING, TAB_TEXT_SIZE, TAB_TOP, forget_sections, in_scope,
room_past_end, section_tabs,
};
pub(crate) use sheet::PropertySheet;
pub(crate) use size_columns_response::SizeColumnsResponse;
@@ -109,13 +109,8 @@ fn tab_rect(strip: Rect, left: f32, right: f32) -> Rect {
Rect::from_min_max(pos2(left, strip.top() + TAB_TOP), pos2(right, strip.bottom() + TAB_BELOW))
}
/// A tab from `left` to `right` filling `strip`'s whole height and reaching as far into the panel as a section tab: a docked group's shown tab
pub(crate) fn full_height_tab_rect(strip: Rect, left: f32, right: f32) -> Rect {
Rect::from_min_max(pos2(left, strip.top()), pos2(right, strip.bottom() + TAB_BELOW))
}
/// The shown tab's box over `tab`: the panel's colour, rounded, so it rises from the panel below the strip
pub(crate) fn shown_tab_box(painter: &Painter, tokens: &Tokens, tab: Rect) {
fn shown_tab_box(painter: &Painter, tokens: &Tokens, tab: Rect) {
painter.rect_filled(tab, CornerRadius::same(TAB_ROUNDING), tokens.panel);
}
Loaded 100 of 247 files, more files were not shown because too many files have changed in this diff. Show more