mirror of
https://github.com/storytold/texturecraft.git
synced 2026-11-28 17:19:24 +01:00
Merge main into feat/export-pass
This commit is contained in:
commit
6b64c5b9af
230 files changed
+7560
-2268
No files matched your search
@@ -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
|
||||
@@ -3,3 +3,4 @@
|
||||
*.ico binary
|
||||
*.icns binary
|
||||
*.ps1 text eol=crlf
|
||||
*.tcraft binary
|
||||
@@ -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-----
|
||||
@@ -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",
|
||||
|
||||
@@ -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.')
|
||||
@@ -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.
|
||||
@@ -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"]'
|
||||
@@ -17,6 +17,7 @@ licensed and keep their license file next to them.
|
||||
| `assets/app-icon/hicolor/scalable/apps/ai.storyteller.texturecraft.svg` | App icon (engraved zebra), hicolor scalable (copy of `texturecraft-small.svg`) | Project owner (ArtCraft team) | Original artwork drawn in ArtCraft for TextureCraft, vectorised with craftrules `vectorize_tile.py` | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) |
|
||||
| `assets/app-icon/texturecraft-nightly{,-1024}.png`, `assets/app-icon/texturecraft-nightly.{icns,ico}`, `assets/app-icon/nightly/{16,24,32,48,64,128,256,512}.png` | Nightly app icons (engraved zebra on deep copper) | Project owner (ArtCraft team) | Project-owned stable icon renders, with the background recolored by `packaging/nightly-icons.py` ([provenance and hashes](assets/app-icon/nightly-provenance.json)) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) |
|
||||
| `assets/app-icon/LICENSE.txt`, `assets/app-icon/README.md` | App icon licence and notes | TextureCraft contributors | original | MIT OR Apache-2.0 |
|
||||
| `assets/samples/Material Ball.tcraft` | Material Ball sample project | TextureCraft contributors | Original procedural mesh, smart materials, and baked maps generated with TextureCraft's [`sample_session`](https://github.com/storytold/texturecraft/blob/14f650202974b509524950048305f1f36fee4282/crates/engine/src/project_cmds.rs#L61), at 1024 px texture and 256 px bake resolution, then saved as a `.tcraft` project | MIT OR Apache-2.0 |
|
||||
| `docs/images/texturecraft-workspace.png` | README screenshot: the TextureCraft workspace (a 1970s portable TV in aged cream plastic with a crayon doodle) | TextureCraft contributors | original screenshot of TextureCraft | MIT OR Apache-2.0 |
|
||||
| `docs/images/texturecraft-bake.png` | README screenshot: bake mode | TextureCraft contributors | original screenshot of TextureCraft | MIT OR Apache-2.0 |
|
||||
| `docs/images/texturecraft-export.png` | README screenshot: the Export textures dialog | TextureCraft contributors | original screenshot of TextureCraft | MIT OR Apache-2.0 |
|
||||
|
||||
Generated
+973
-234
File diff suppressed because it is too large.
Load diff
+32
-28
@@ -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 }
|
||||
@@ -63,46 +63,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"
|
||||
|
||||
@@ -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).
|
||||
@@ -256,6 +256,7 @@ are built, signed and published. Every bundled asset is listed with its licence
|
||||
| Build | File |
|
||||
|---|---|
|
||||
| x86_64 | `texturecraft-<ver>-freebsd-x86_64.tar.gz` |
|
||||
| aarch64 (ARM64) | `texturecraft-<ver>-freebsd-aarch64.tar.gz` |
|
||||
|
||||
### Web (WebAssembly)
|
||||
|
||||
|
||||
+104
-112
@@ -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 |
|
||||
@@ -280,21 +280,39 @@ fn run(a: &Args) -> R {
|
||||
}
|
||||
}
|
||||
|
||||
fn batch(a: &Args) -> R {
|
||||
let path = a.pos(0, "<script.json>")?;
|
||||
let text = std::fs::read_to_string(path).map_err(|e| format!("cannot read {path}: {e}"))?;
|
||||
let script: Value = serde_json::from_str(&text).map_err(|e| format!("{path} is not JSON: {e}"))?;
|
||||
fn batch(args: &Args) -> R {
|
||||
let path = args.pos(0, "<script.json>")?;
|
||||
let script: Value = {
|
||||
let script_text = std::fs::read_to_string(path).map_err(|err| format!("cannot read {path}: {err}"))?;
|
||||
serde_json::from_str(&script_text).map_err(|err| format!("{path} is not JSON: {err}"))?
|
||||
};
|
||||
|
||||
let steps =
|
||||
script.as_array().or_else(|| script.get("steps").and_then(Value::as_array)).ok_or("the script must be a list of steps or {\"steps\": [...]}")?;
|
||||
let field = |k: &str| script.get(k).and_then(Value::as_str);
|
||||
let mut h = open(field("open").unwrap_or("builtin:material_ball"), None)?;
|
||||
let reply = h.batch(steps);
|
||||
let path_field = |field: &str| -> Result<Option<&str>, String> {
|
||||
match script.get(field) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(Value::String(path)) => Ok(Some(path.as_str())),
|
||||
Some(_) => Err(format!("the script's `{field}` field must be a string")),
|
||||
}
|
||||
};
|
||||
let input = path_field("open")?.unwrap_or("builtin:material_ball");
|
||||
let output = path_field("save")?;
|
||||
|
||||
let mut headless = open(input, None)?;
|
||||
let reply = headless.batch(steps);
|
||||
print_json(&reply)?;
|
||||
if let Some(f) = reply.get("failed").filter(|f| !f.is_null()) {
|
||||
return Err(format!("step {} (`{}`) failed: {}", f["index"], f["id"].as_str().unwrap_or_default(), f["error"].as_str().unwrap_or_default()));
|
||||
if let Some(failure) = reply.get("failed").filter(|failure| !failure.is_null()) {
|
||||
return Err(format!(
|
||||
"step {} (`{}`) failed: {}",
|
||||
failure["index"],
|
||||
failure["id"].as_str().unwrap_or_default(),
|
||||
failure["error"].as_str().unwrap_or_default()
|
||||
));
|
||||
}
|
||||
match field("save") {
|
||||
Some(out) => save(&mut h, out),
|
||||
|
||||
match output {
|
||||
Some(output_path) => save(&mut headless, output_path),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -95,6 +95,38 @@ fn new_info_run_bake_export_batch() {
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_rejects_non_string_paths() {
|
||||
let directory = tmp("batch-paths");
|
||||
let script = directory.join("script.json");
|
||||
let unexpected_project = directory.join("unexpected.tcraft");
|
||||
let invalid_open = serde_json::json!({"steps": [], "open": false, "save": p(&unexpected_project)});
|
||||
let invalid_save = serde_json::json!({
|
||||
"open": "builtin:cube",
|
||||
"save": [p(&unexpected_project)],
|
||||
"steps": [{"id": "file.saveCopy", "params": {"path": p(&unexpected_project)}}]
|
||||
});
|
||||
|
||||
for (body, field) in [(invalid_open, "open"), (invalid_save, "save")] {
|
||||
std::fs::write(&script, body.to_string()).unwrap();
|
||||
let output = cli(&["batch", p(&script)]);
|
||||
|
||||
let error = String::from_utf8_lossy(&output.stderr);
|
||||
assert_eq!(output.status.code(), Some(1), "{field}: {error}");
|
||||
assert!(error.contains(&format!("`{field}` field must be a string")), "{error}");
|
||||
assert!(output.stdout.is_empty());
|
||||
assert!(!unexpected_project.exists());
|
||||
}
|
||||
|
||||
std::fs::write(&script, r#"{"steps":[],"open":null,"save":null}"#).unwrap();
|
||||
let reply = json(&["batch", p(&script)]);
|
||||
|
||||
assert_eq!(reply["completed"], 0);
|
||||
assert!(reply["failed"].is_null());
|
||||
|
||||
let _ = std::fs::remove_dir_all(&directory);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn info_on_a_mesh_reports_uvs() {
|
||||
let d = tmp("mesh");
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
Binary file not shown.
@@ -0,0 +1,9 @@
|
||||
# Sample projects
|
||||
|
||||
Projects that ship with desktop TextureCraft and are offered by File > Open Sample Project.
|
||||
|
||||
- `Material Ball.tcraft`: the material ball with smart materials on both texture sets, generated by
|
||||
TextureCraft's own `sample_session` (1024 px textures, mesh maps baked at 256 px to keep the file small).
|
||||
|
||||
The app embeds these files and copies any missing sample into the `Samples` folder under the data
|
||||
folder when the entry is used. A file that is already there is never overwritten.
|
||||
@@ -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);
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
@@ -917,7 +925,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");
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Select camera",
|
||||
[],
|
||||
None,
|
||||
"{index? | name?} (neither, or name \"Default camera\": the default camera framing the mesh)",
|
||||
"{index? | name?} (an omitted or null index and an omitted, null, or \"Default camera\" name frame the mesh)",
|
||||
always,
|
||||
select
|
||||
),
|
||||
@@ -226,24 +226,29 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
})
|
||||
}
|
||||
|
||||
fn select(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if u64p(p, "index").is_none() && strp(p, "name").is_none_or(|n| n == DEFAULT_CAMERA) {
|
||||
// The default camera: fov and projection from the display settings, framing the mesh
|
||||
s.selected_camera_name = None;
|
||||
s.camera.fov = s.doc.project.display.fov;
|
||||
s.camera.ortho = false;
|
||||
return crate::execute(s, "viewport.frame", &Value::Null);
|
||||
fn select(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
if !params.is_object() && !params.is_null() {
|
||||
return Err(bad("camera.select", "expected a parameter object or null"));
|
||||
}
|
||||
|
||||
let i = which(s, "camera.select", p)?;
|
||||
if let Some(camera) = s.doc.project.cameras.get(i) {
|
||||
// A saved view is clamped against the whole mesh, not against a part framed with F
|
||||
s.camera.scene_radius = s.mesh.radius();
|
||||
apply(&mut s.camera, camera);
|
||||
s.selected_camera_name = Some(camera.name.clone());
|
||||
let default_name = params.get("name").is_none_or(|name| name.is_null() || name.as_str() == Some(DEFAULT_CAMERA));
|
||||
if params.get("index").is_none_or(Value::is_null) && default_name {
|
||||
session.selected_camera_name = None;
|
||||
session.camera.fov = session.doc.project.display.fov;
|
||||
session.camera.ortho = false;
|
||||
return crate::execute(session, "viewport.frame", &Value::Null);
|
||||
}
|
||||
s.revision = s.revision.wrapping_add(1);
|
||||
Ok(crate::view_cmds::camera_json(s))
|
||||
|
||||
let camera_index = which(session, "camera.select", params)?;
|
||||
if let Some(camera) = session.doc.project.cameras.get(camera_index) {
|
||||
// Use the whole mesh radius even after framing a texture set
|
||||
session.camera.scene_radius = session.mesh.radius();
|
||||
apply(&mut session.camera, camera);
|
||||
session.selected_camera_name = Some(camera.name.clone());
|
||||
}
|
||||
|
||||
session.revision = session.revision.wrapping_add(1);
|
||||
Ok(crate::view_cmds::camera_json(session))
|
||||
}
|
||||
|
||||
/// The fixed views: name, yaw and pitch in degrees. Yaw 0 puts the eye on +Z (the front), yaw 90
|
||||
@@ -453,6 +458,49 @@ mod tests {
|
||||
assert_eq!(s.doc.project.cameras.len(), 2, "removing is undoable");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_camera_selectors_leave_the_current_view_intact() {
|
||||
let mut session = session();
|
||||
execute(&mut session, "camera.set", &json!({"yaw": 30, "target": [1, 2, 3], "fov": 25, "ortho": true})).unwrap();
|
||||
let saved_view = session.camera;
|
||||
execute(&mut session, "camera.add", &json!({"name": "Side"})).unwrap();
|
||||
execute(&mut session, "camera.orbit", &json!({"dx": 15})).unwrap();
|
||||
|
||||
execute(&mut session, "camera.select", &json!({"index": 0, "name": DEFAULT_CAMERA})).unwrap();
|
||||
|
||||
assert_eq!(session.camera, saved_view);
|
||||
assert_eq!(session.selected_camera_name.as_deref(), Some("Side"));
|
||||
|
||||
let revision = session.revision;
|
||||
for params in [
|
||||
json!({"index": -1}),
|
||||
json!({"index": -0.5}),
|
||||
json!({"index": "0"}),
|
||||
json!({"name": false}),
|
||||
json!({"index": -1, "name": DEFAULT_CAMERA}),
|
||||
json!([{"index": 0}]),
|
||||
json!("Side"),
|
||||
] {
|
||||
let result = execute(&mut session, "camera.select", ¶ms);
|
||||
|
||||
assert!(matches!(result, Err(crate::EngineError::BadParams { .. })), "{params}: {result:?}");
|
||||
assert_eq!(session.camera, saved_view);
|
||||
assert_eq!(session.selected_camera_name.as_deref(), Some("Side"));
|
||||
assert_eq!(session.revision, revision);
|
||||
}
|
||||
|
||||
for params in [Value::Null, json!({"index": null, "name": null}), json!({"name": DEFAULT_CAMERA})] {
|
||||
execute(&mut session, "camera.select", &json!({"index": null, "name": "Side"})).unwrap();
|
||||
assert_eq!(session.camera, saved_view);
|
||||
|
||||
execute(&mut session, "camera.select", ¶ms).unwrap();
|
||||
|
||||
assert_eq!(session.selected_camera_name, None);
|
||||
assert!(!session.camera.ortho);
|
||||
assert_eq!(session.camera.fov, session.doc.project.display.fov);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn number_shortcuts_go_to_the_first_nine_cameras() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -12,7 +12,9 @@ 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, MapPreview, Padding, ProjectFile};
|
||||
use texturecraft_geom::glam::Vec2;
|
||||
use texturecraft_geom::{Mesh, UvGBuffer, primitives};
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad, normal_format_param, strp, u64p};
|
||||
@@ -29,7 +31,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
|
||||
),
|
||||
@@ -113,10 +115,13 @@ 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 {
|
||||
@@ -175,11 +180,16 @@ 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)?;
|
||||
|
||||
@@ -188,6 +198,7 @@ impl Session {
|
||||
source.shrink_to_fit();
|
||||
session.mesh_source = Some((extension, 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);
|
||||
@@ -211,29 +222,39 @@ 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.
|
||||
@@ -247,6 +268,11 @@ impl Session {
|
||||
self.project_with_resources(self.doc.resources.clone())
|
||||
}
|
||||
|
||||
/// The layout a project with rebuilt mesh UVs saves, so reopening it never runs the unwrapper.
|
||||
fn saved_uv_layout(&self) -> Option<Vec<Vec2>> {
|
||||
(self.doc.project.mesh_rebuild_uvs && self.mesh_source.is_some()).then(|| texturecraft_formats::mesh_import::corner_uvs(&self.source))
|
||||
}
|
||||
|
||||
fn project_with_resources<Resource>(&self, resources: BTreeMap<String, Resource>) -> ProjectFile<Resource> {
|
||||
let mut pixels = self.doc.pixels.clone();
|
||||
|
||||
@@ -265,11 +291,15 @@ impl Session {
|
||||
pixels.masks.retain(|id, img| size_of(*id) == Some((img.width(), img.height())));
|
||||
|
||||
let (high_poly, cage) = self.saved_bake_meshes();
|
||||
let mut project = self.doc.project.clone();
|
||||
project.format_version = project.save_format_version();
|
||||
|
||||
ProjectFile {
|
||||
project: self.doc.project.clone(),
|
||||
project,
|
||||
pixels,
|
||||
baked: self.doc.baked.clone(),
|
||||
mesh: self.mesh_source.clone(),
|
||||
mesh_uvs: self.saved_uv_layout(),
|
||||
high_poly,
|
||||
cage,
|
||||
bake_paint: self.saved_bake_paint(),
|
||||
@@ -621,7 +651,7 @@ mod native {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub use native::{absolute, open_path, read_mesh};
|
||||
|
||||
/// `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> {
|
||||
@@ -632,9 +662,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) {
|
||||
@@ -697,9 +729,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)
|
||||
}
|
||||
|
||||
@@ -710,16 +744,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_layout();
|
||||
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`")),
|
||||
},
|
||||
@@ -727,12 +769,13 @@ impl Session {
|
||||
|
||||
check_materials(&self.doc.project, &mesh)?;
|
||||
let mut doc = self.doc.clone();
|
||||
if let Some((ext, _)) = &source {
|
||||
if let Some((ext, _)) = replacement_source.as_ref().or(self.mesh_source.as_ref()) {
|
||||
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();
|
||||
@@ -743,6 +786,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");
|
||||
}
|
||||
@@ -750,6 +794,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 })))
|
||||
}
|
||||
|
||||
@@ -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> {
|
||||
|
||||
@@ -104,6 +104,7 @@ impl Session {
|
||||
pixels: mini.pixels,
|
||||
baked: BTreeMap::new(),
|
||||
mesh: None,
|
||||
mesh_uvs: None,
|
||||
high_poly: Vec::new(),
|
||||
cage: None,
|
||||
bake_paint: BTreeMap::new(),
|
||||
|
||||
@@ -3,12 +3,13 @@
|
||||
//! are mirrored as `<name>.json` files in a library folder (see [`Session::load_export_presets`]).
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::collections::HashSet;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_formats::export::{MAX_PRESET_NAME, sanitize_file_stem};
|
||||
use texturecraft_formats::{ExportPreset, NEW_BUILTIN_PRESET_NAMES, builtin_preset, builtin_preset_catalog, preset_from_json};
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad, boolp, strp};
|
||||
use crate::commands::{CommandSpec, always, bad, strp};
|
||||
use crate::{Result, Session, cmd};
|
||||
|
||||
/// Most user presets kept (and read from the library folder).
|
||||
@@ -95,16 +96,18 @@ impl UserPresets {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `name`, or `name 2`, `name 3`… (shortened to fit) when taken.
|
||||
fn unique_name(&self, name: &str, skip: Option<usize>) -> String {
|
||||
/// 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(|k| {
|
||||
let suffix = if k == 1 { String::new() } else { format!(" {k}") };
|
||||
.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(|n| !self.taken(n, skip))
|
||||
.unwrap_or_else(|| name.to_string())
|
||||
.find(|candidate| !file_keys.contains(&file_key(candidate)) && builtin_preset(candidate).is_none())
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -207,32 +210,50 @@ pub fn preset_param(v: &Value, cmd: &str) -> Result<ExportPreset> {
|
||||
Ok(preset)
|
||||
}
|
||||
|
||||
fn save(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn save(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
const CMD: &str = "export.preset.save";
|
||||
let mut preset = preset_param(p.get("preset").ok_or_else(|| bad(CMD, "`preset` is required"))?, CMD)?;
|
||||
let lib = &mut s.export_presets;
|
||||
let renamed = match strp(p, "rename") {
|
||||
Some(old) => Some(lib.find(old).ok_or_else(|| bad(CMD, format!("no user export preset `{old}` to rename")))?),
|
||||
None => None,
|
||||
let preset_value = params.get("preset").ok_or_else(|| bad(CMD, "`preset` is required"))?;
|
||||
let rename_from = match params.get("rename") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(Value::String(name)) => Some(name),
|
||||
Some(_) => return Err(bad(CMD, "`rename` must be a preset name")),
|
||||
};
|
||||
let target = renamed.or_else(|| lib.find(&preset.name));
|
||||
if boolp(p, "unique") == Some(true) {
|
||||
preset.name = lib.unique_name(&preset.name, renamed);
|
||||
} else if lib.taken(&preset.name, target) {
|
||||
let unique = match params.get("unique") {
|
||||
None | Some(Value::Null) => false,
|
||||
Some(Value::Bool(unique)) => *unique,
|
||||
Some(_) => return Err(bad(CMD, "`unique` must be a boolean")),
|
||||
};
|
||||
|
||||
let mut preset = preset_param(preset_value, CMD)?;
|
||||
let library = &mut session.export_presets;
|
||||
let target_index = match rename_from {
|
||||
Some(old_name) => Some(library.find(old_name).ok_or_else(|| bad(CMD, format!("no user export preset `{old_name}` to rename")))?),
|
||||
None if unique => None,
|
||||
None => library.find(&preset.name),
|
||||
};
|
||||
|
||||
if !unique && library.taken(&preset.name, target_index) {
|
||||
return Err(bad(CMD, format!("an export preset named \"{}\" exists already (built-in presets are read-only)", preset.name)));
|
||||
}
|
||||
let target = renamed.or_else(|| lib.find(&preset.name));
|
||||
if target.is_none() && lib.list.len() >= MAX_USER_PRESETS {
|
||||
|
||||
if target_index.is_none() && library.list.len() >= MAX_USER_PRESETS {
|
||||
return Err(bad(CMD, format!("at most {MAX_USER_PRESETS} user export presets")));
|
||||
}
|
||||
let previous = target.and_then(|i| lib.list.get(i)).map(|old| old.name.clone());
|
||||
lib.write(&preset, previous.as_deref()).map_err(|e| bad(CMD, e))?;
|
||||
let name = preset.name.clone();
|
||||
match target.and_then(|i| lib.list.get_mut(i)) {
|
||||
Some(slot) => *slot = preset,
|
||||
None => lib.list.push(preset),
|
||||
|
||||
if unique {
|
||||
preset.name = library.unique_name(&preset.name, target_index).ok_or_else(|| bad(CMD, "no unique export preset name is available"))?;
|
||||
}
|
||||
Ok(json!({ "name": name }))
|
||||
|
||||
let previous_name = target_index.and_then(|index| library.list.get(index)).map(|previous| previous.name.as_str());
|
||||
library.write(&preset, previous_name).map_err(|error| bad(CMD, error))?;
|
||||
|
||||
let response = json!({ "name": preset.name });
|
||||
match target_index.and_then(|index| library.list.get_mut(index)) {
|
||||
Some(slot) => *slot = preset,
|
||||
None => library.list.push(preset),
|
||||
}
|
||||
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
fn remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -275,40 +296,113 @@ mod tests {
|
||||
assert_eq!(run(&mut s, "export.preset.save", json!({"preset": preset(" Mine ")})).unwrap()["name"], "Mine");
|
||||
let got = run(&mut s, "export.preset.get", json!({"name": "mine"})).unwrap();
|
||||
assert_eq!(got, preset("Mine"), "round trip through the command");
|
||||
// Saving the same name replaces; a clash with a built-in or with `unique` renames.
|
||||
|
||||
// A same-name save replaces the current preset
|
||||
let mut edited = preset("Mine");
|
||||
edited["maps"][0]["bit_depth"] = json!(16);
|
||||
run(&mut s, "export.preset.save", json!({"preset": edited})).unwrap();
|
||||
assert_eq!(s.export_presets.list.len(), 1);
|
||||
assert_eq!(s.export_preset("Mine").unwrap().maps[0].bit_depth, 16);
|
||||
|
||||
// Built-ins need a unique name for a user copy
|
||||
assert!(run(&mut s, "export.preset.save", json!({"preset": preset("Separate maps")})).is_err());
|
||||
assert_eq!(run(&mut s, "export.preset.save", json!({"preset": preset("Separate maps"), "unique": true})).unwrap()["name"], "Separate maps 2");
|
||||
assert_eq!(run(&mut s, "export.preset.save", json!({"preset": preset("mine"), "unique": true})).unwrap()["name"], "mine 2");
|
||||
// Renaming onto another preset fails; onto a free name keeps the position.
|
||||
|
||||
// Renaming to a free name keeps the library position
|
||||
assert!(run(&mut s, "export.preset.save", json!({"preset": preset("Mine"), "rename": "mine 2"})).is_err());
|
||||
run(&mut s, "export.preset.save", json!({"preset": preset("Renamed"), "rename": "Mine"})).unwrap();
|
||||
let names: Vec<&str> = s.export_presets.list.iter().map(|p| p.name.as_str()).collect();
|
||||
assert_eq!(names, ["Renamed", "Separate maps 2", "mine 2"]);
|
||||
|
||||
let listed = run(&mut s, "export.presets", json!({})).unwrap();
|
||||
assert!(listed.as_array().unwrap().iter().any(|p| p["name"] == "Renamed" && p["builtin"] == false));
|
||||
assert!(run(&mut s, "export.preset.remove", json!({"name": "Separate maps"})).is_err(), "built-ins are read-only");
|
||||
run(&mut s, "export.preset.remove", json!({"name": "renamed"})).unwrap();
|
||||
assert!(run(&mut s, "export.preset.get", json!({"name": "Renamed"})).is_err());
|
||||
// Presets survive opening another project.
|
||||
|
||||
// Presets survive opening another project
|
||||
run(&mut s, "project.new", json!({"resolution": 128})).unwrap();
|
||||
assert_eq!(s.export_presets.list.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_save_options_do_not_replace_a_user_preset() {
|
||||
let mut session = session();
|
||||
let original = preset("Mine");
|
||||
run(&mut session, "export.preset.save", json!({"preset": original})).unwrap();
|
||||
let mut replacement = original.clone();
|
||||
replacement["maps"][0]["bit_depth"] = json!(16);
|
||||
|
||||
for (key, invalid) in [("unique", json!("true")), ("rename", json!(7))] {
|
||||
let mut params = json!({"preset": replacement});
|
||||
params[key] = invalid;
|
||||
|
||||
let error = run(&mut session, "export.preset.save", params).unwrap_err();
|
||||
|
||||
assert_eq!(run(&mut session, "export.preset.get", json!({"name": "Mine"})).unwrap(), original);
|
||||
assert!(error.to_string().contains(&format!("`{key}`")), "{error}");
|
||||
}
|
||||
|
||||
run(&mut session, "export.preset.save", json!({"preset": replacement, "unique": null, "rename": null})).unwrap();
|
||||
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();
|
||||
|
||||
// At the name length limit, adding the first suffix can reproduce the requested name
|
||||
for number in 2..=MAX_USER_PRESETS + 1 {
|
||||
let suffix = format!(" {number}");
|
||||
let name = format!("{}{suffix}", "x".repeat(MAX_PRESET_NAME - suffix.len()));
|
||||
run(&mut session, "export.preset.save", json!({"preset": preset(&name)})).unwrap();
|
||||
}
|
||||
|
||||
let first_name = session.export_presets.list[0].name.clone();
|
||||
let original = run(&mut session, "export.preset.get", json!({"name": first_name})).unwrap();
|
||||
let mut replacement = original.clone();
|
||||
replacement["maps"][0]["bit_depth"] = json!(16);
|
||||
|
||||
let result = run(&mut session, "export.preset.save", json!({"preset": replacement, "unique": true}));
|
||||
|
||||
assert_eq!(run(&mut session, "export.preset.get", json!({"name": first_name})).unwrap(), original);
|
||||
assert!(result.is_err());
|
||||
|
||||
replacement["name"] = json!("Renamed");
|
||||
run(&mut session, "export.preset.save", json!({"preset": replacement, "unique": true, "rename": first_name})).unwrap();
|
||||
|
||||
assert_eq!(run(&mut session, "export.preset.get", json!({"name": "Renamed"})).unwrap(), replacement);
|
||||
assert!(run(&mut session, "export.preset.get", json!({"name": first_name})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_presets_are_refused() {
|
||||
let mut s = session();
|
||||
let mut evil = preset("Evil");
|
||||
evil["maps"][0]["file"] = json!("../../$mesh");
|
||||
|
||||
assert!(run(&mut s, "export.preset.save", json!({"preset": evil})).is_err());
|
||||
assert!(run(&mut s, "export.preset.save", json!({"preset": "nope"})).is_err());
|
||||
assert!(run(&mut s, "export.preset.save", json!({"preset": preset("")})).is_err());
|
||||
assert!(run(&mut s, "export.preset.save", json!({"preset": preset(&"x".repeat(200))})).is_err());
|
||||
assert!(run(&mut s, "export.preset.save", json!({"preset": preset("a"), "rename": "missing"})).is_err());
|
||||
|
||||
assert!(s.export_presets.list.is_empty());
|
||||
}
|
||||
|
||||
@@ -340,7 +434,7 @@ mod tests {
|
||||
let set = s.doc.project.texture_sets[0].name.clone();
|
||||
let dir = std::env::temp_dir().join(format!("tc_user_preset_export_{}", std::process::id()));
|
||||
|
||||
// By name and as an inline object: the same files
|
||||
// Named and inline presets produce the same files
|
||||
for preset in [json!("packed"), packed] {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let r = run(&mut s, "file.exportTextures", json!({"dir": dir.display().to_string(), "preset": preset, "ts": 0})).unwrap();
|
||||
@@ -404,10 +498,12 @@ mod tests {
|
||||
assert_eq!(s.load_export_presets(dir.clone()).len(), 1, "the broken file is reported");
|
||||
run(&mut s, "export.preset.save", json!({"preset": preset("My Preset")})).unwrap();
|
||||
assert!(dir.join("My_Preset.json").is_file());
|
||||
// Names sharing a file stem clash instead of overwriting each other's file.
|
||||
|
||||
// Reject aliases that would overwrite the same library file
|
||||
assert!(run(&mut s, "export.preset.save", json!({"preset": preset("My_Preset")})).is_err());
|
||||
run(&mut s, "export.preset.save", json!({"preset": preset("Other"), "rename": "My Preset"})).unwrap();
|
||||
assert!(!dir.join("My_Preset.json").exists() && dir.join("Other.json").is_file());
|
||||
|
||||
let mut fresh = session();
|
||||
assert_eq!(fresh.load_export_presets(dir.clone()).len(), 1);
|
||||
assert_eq!(fresh.export_preset("other").unwrap().name, "Other");
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
//! with the brush as its alpha or to place as a decal.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_formats::sanitize_resource_name;
|
||||
use texturecraft_paint::text::render_text;
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad, color_param, f32p, strp};
|
||||
@@ -94,16 +95,57 @@ fn font_bytes(family: Option<&str>, style: Option<&str>) -> Result<(std::borrow:
|
||||
}
|
||||
}
|
||||
|
||||
fn add_text(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "resource.text";
|
||||
let text = strp(p, "text").ok_or_else(|| bad(cmd, "`text` is required"))?;
|
||||
let (font, index) = font_bytes(strp(p, "font"), strp(p, "style"))?;
|
||||
let size = f32p(p, "size").unwrap_or(256.0).clamp(8.0, 1024.0);
|
||||
let img = render_text(&font, index, text, size).map_err(|e| bad(cmd, e))?;
|
||||
let rgb = color_param(cmd, p, "color")?.unwrap_or([1.0; 3]).map(|c| (texturecraft_texel::linear_to_srgb(c.clamp(0.0, 1.0)) * 255.0).round() as u8);
|
||||
let png = texturecraft_formats::coverage_png(img.width, img.height, &img.coverage, rgb).map_err(|e| bad(cmd, e.to_string()))?;
|
||||
// The resource is named after the text (its first line, shortened) unless a name is given.
|
||||
let label: String = strp(p, "name").unwrap_or_else(|| text.lines().next().unwrap_or_default()).chars().take(32).collect();
|
||||
let name = s.import_resource_bytes(&format!("Text {}.png", label.trim()), png)?;
|
||||
Ok(json!({ "name": name, "width": img.width, "height": img.height }))
|
||||
fn add_text(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
const DEFAULT_TEXELS_PER_EM: f32 = 256.0;
|
||||
const MIN_TEXELS_PER_EM: f32 = 8.0;
|
||||
const MAX_TEXELS_PER_EM: f32 = 1024.0;
|
||||
const MAX_LABEL_CHARS: usize = 32;
|
||||
|
||||
let command = "resource.text";
|
||||
let text = strp(params, "text").ok_or_else(|| bad(command, "`text` is required"))?;
|
||||
let (font, face_index) = font_bytes(strp(params, "font"), strp(params, "style"))?;
|
||||
let texels_per_em = f32p(params, "size").unwrap_or(DEFAULT_TEXELS_PER_EM).clamp(MIN_TEXELS_PER_EM, MAX_TEXELS_PER_EM);
|
||||
|
||||
let image = render_text(&font, face_index, text, texels_per_em).map_err(|error| bad(command, error))?;
|
||||
drop(font);
|
||||
|
||||
let srgb_bytes = color_param(command, params, "color")?
|
||||
.unwrap_or([1.0; 3])
|
||||
.map(|channel| (texturecraft_texel::linear_to_srgb(channel.clamp(0.0, 1.0)) * 255.0).round() as u8);
|
||||
let (width, height) = (image.width, image.height);
|
||||
let png_bytes = texturecraft_formats::coverage_png(width, height, &image.coverage, srgb_bytes).map_err(|error| bad(command, error.to_string()))?;
|
||||
drop(image);
|
||||
|
||||
let label: String = strp(params, "name").unwrap_or_else(|| text.lines().next().unwrap_or_default()).chars().take(MAX_LABEL_CHARS).collect();
|
||||
|
||||
// Treat the label as text before the importer extracts a basename
|
||||
let file_name = sanitize_resource_name(&format!("Text {}.png", label.trim()));
|
||||
|
||||
let name = session.import_resource_bytes(&file_name, png_bytes)?;
|
||||
|
||||
Ok(json!({ "name": name, "width": width, "height": height }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn text_resource_name_keeps_the_label_across_a_slash() {
|
||||
let mut session = crate::sample_session(128, 32).unwrap();
|
||||
|
||||
let resource = crate::execute(&mut session, "resource.text", &json!({"text": "1/2", "font": "Hack", "size": 16})).unwrap();
|
||||
|
||||
assert_eq!(resource["name"], "Text_1_2.png");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_resource_name_keeps_the_explicit_label_across_separators() {
|
||||
let mut session = crate::sample_session(128, 32).unwrap();
|
||||
|
||||
let resource =
|
||||
crate::execute(&mut session, "resource.text", &json!({"text": "Plan", "name": "plan\\detail/page", "font": "Hack", "size": 16})).unwrap();
|
||||
|
||||
assert_eq!(resource["name"], "Text_plan_detail_page.png");
|
||||
}
|
||||
}
|
||||
@@ -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", ¶ms);
|
||||
|
||||
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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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() {
|
||||
|
||||
@@ -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,68 @@
|
||||
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 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}");
|
||||
}
|
||||
@@ -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 }
|
||||
zip = { workspace = true }
|
||||
|
||||
@@ -163,7 +163,8 @@ targets Sketchfab.
|
||||
```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>>;
|
||||
@@ -180,12 +181,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.
|
||||
|
||||
@@ -198,6 +201,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
|
||||
|
||||
@@ -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)?;
|
||||
|
||||
@@ -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 }
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ mod dae;
|
||||
mod external;
|
||||
mod fbx;
|
||||
mod gltf;
|
||||
mod mesh_uv_source;
|
||||
mod obj;
|
||||
mod ply;
|
||||
#[cfg(test)]
|
||||
@@ -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`]).
|
||||
@@ -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
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
@@ -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,6 +42,7 @@ mod load_budget;
|
||||
mod project_open_limit;
|
||||
mod ram_operation;
|
||||
mod ram_reservation;
|
||||
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};
|
||||
@@ -72,6 +77,9 @@ pub struct ProjectFile<Resource = Vec<u8>> {
|
||||
pub baked: BTreeMap<usize, BakedMaps>,
|
||||
/// Original mesh file: (extension, bytes).
|
||||
pub mesh: Option<(String, Vec<u8>)>,
|
||||
/// 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>)>,
|
||||
@@ -85,6 +93,21 @@ pub struct ProjectFile<Resource = Vec<u8>> {
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
impl<Resource> ProjectFile<Resource> {
|
||||
/// 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;
|
||||
|
||||
@@ -187,12 +210,23 @@ 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>>>) -> 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 {
|
||||
out.push(Entry {
|
||||
name: format!("mesh.{}", sanitize_ext(ext)),
|
||||
options: deflate,
|
||||
@@ -200,8 +234,18 @@ 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))) {
|
||||
out.push(Entry {
|
||||
name: unique_entry_name(dir, name, &mut used),
|
||||
options: deflate,
|
||||
@@ -209,7 +253,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 +263,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 +271,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 +283,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 +308,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,6 +323,7 @@ fn entries(pf: &ProjectFile<impl Borrow<Vec<u8>>>) -> Result<Vec<Entry<'_>>> {
|
||||
body: Box::new(move |w| w.write_all(bytes)),
|
||||
});
|
||||
}
|
||||
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
@@ -406,10 +457,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 +471,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 +509,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 +533,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 +549,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 +565,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
|
||||
|
||||
@@ -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")),
|
||||
}
|
||||
}
|
||||
@@ -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]
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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 -
|
||||
};
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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,12 +33,11 @@ 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.
|
||||
craft-dialogs = { workspace = true }
|
||||
tempfile = "3"
|
||||
# Whether the app runs in a real window, where an eyedropper pick may take clicks outside it (screen_pick).
|
||||
raw-window-handle = "0.6"
|
||||
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -287,7 +287,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);
|
||||
|
||||
+80
-13
@@ -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;
|
||||
@@ -186,7 +197,7 @@ pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
/// 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;
|
||||
}
|
||||
|
||||
@@ -454,7 +465,6 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize
|
||||
let (rect, row) = ui.allocate_exact_size(vec2(ui.available_width(), row_height), 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
|
||||
@@ -550,14 +560,21 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize
|
||||
if !thumb_box(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);
|
||||
if content_response.clicked() {
|
||||
let modifiers = ui.input(|input| input.modifiers);
|
||||
click_layer(app, modifiers, layer.id.0, Some("content"));
|
||||
|
||||
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));
|
||||
|
||||
x = thumbnail.right() + THUMBNAIL_SPACING;
|
||||
|
||||
// An instance draws its source's content, blending and (unless it has its own) mask
|
||||
@@ -574,9 +591,29 @@ 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));
|
||||
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);
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !thumb_box(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 }));
|
||||
@@ -594,17 +631,10 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize
|
||||
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));
|
||||
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 +657,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
|
||||
@@ -3298,3 +3329,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
@@ -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));
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1751,8 +1751,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;
|
||||
}
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -5,8 +5,8 @@ use serde_json::{Value, json};
|
||||
use texturecraft_engine::compose::axis_frame::{placed_from_axis, placing_moves_pattern};
|
||||
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};
|
||||
use texturecraft_engine::geom::glam::Vec3;
|
||||
use texturecraft_engine::core::{Decal, EffectKind, Fill, LayerId, LayerKind, Projection, Source};
|
||||
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
|
||||
@@ -61,47 +68,20 @@ const MIN_SIDE_STRETCH: f32 = 0.02;
|
||||
/// The least distance from the centre a resize drag measures from, so a press on the centre never divides by zero (points)
|
||||
pub(crate) const MIN_HANDLE_REACH: f32 = 1.0;
|
||||
|
||||
impl FrameGizmo {
|
||||
/// The frame as the 3D view shows it: none while the Projection row's eye hides the projection gizmos
|
||||
pub(crate) fn shown(app: &TextureCraftApp, rect: Rect) -> Option<FrameGizmo> {
|
||||
FrameGizmo::of(app, rect).filter(|_| app.session.doc.project.display.projection_gizmos)
|
||||
/// An unplaced axis planar can acquire a frame only if placing it preserves its pattern.
|
||||
fn placeable_projection<'a>(projection: &'a Projection, sources: impl Iterator<Item = &'a Source>) -> Option<&'a Projection> {
|
||||
let unplaced = matches!(projection, Projection::Planar { placed: None, .. });
|
||||
if unplaced && placing_moves_pattern(sources) {
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(projection)
|
||||
}
|
||||
|
||||
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, sources) = 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, projection, sources.values().collect::<Vec<_>>())
|
||||
}
|
||||
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 };
|
||||
|
||||
(owner, Some(effect), projection, vec![source])
|
||||
}
|
||||
StackTarget::Mask => return None,
|
||||
};
|
||||
|
||||
// An axis planar reading a pattern keeps its axis (see [`placing_moves_pattern`]): it has no frame to move
|
||||
let unplaced = matches!(projection, Projection::Planar { placed: None, .. });
|
||||
if unplaced && placing_moves_pattern(sources.into_iter()) {
|
||||
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
|
||||
@@ -113,7 +93,7 @@ impl FrameGizmo {
|
||||
};
|
||||
let (origin, across, up, out) = decal_axes(&decal)?;
|
||||
|
||||
// The corners on screen: a warp's pulled ones, or the frame's own
|
||||
// Warp corners can sit away from the frame corners
|
||||
let at = |[x, y]: [f32; 2]| project(app, rect, origin + across * x * decal.size[0] + up * y * decal.size[1]);
|
||||
let corners = match warp {
|
||||
Some([top_left, top_right, bottom_right, bottom_left]) => [at(top_left)?, at(top_right)?, at(bottom_right)?, at(bottom_left)?],
|
||||
@@ -126,29 +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)?;
|
||||
|
||||
// Screen movement per world unit along each direction, and an arrow along each one not pointing at the camera
|
||||
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 turn ring, unless the frame is seen too near edge on to grab it
|
||||
let ring = steps[0]
|
||||
.zip(steps[1])
|
||||
.filter(|(across_step, up_step)| {
|
||||
across_step.length() > f32::EPSILON && solve(*across_step, *up_step, egui::Vec2::X).is_some() && ring_open(app, rect, center, out)
|
||||
})
|
||||
.and_then(|(step, _)| {
|
||||
let radius = TURN_RING / step.length();
|
||||
let last = (TURN_RING_POINTS - 1) as f32;
|
||||
let points = (0..TURN_RING_POINTS).map(|index| {
|
||||
let (sin, cos) = (index as f32 / last * std::f32::consts::TAU).sin_cos();
|
||||
project(app, rect, origin + (across * cos + up * sin) * radius)
|
||||
});
|
||||
points.collect::<Option<Vec<_>>>()?.try_into().ok()
|
||||
});
|
||||
// The ring can still project when an arrow's endpoint is behind the camera
|
||||
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)
|
||||
@@ -157,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);
|
||||
@@ -178,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;
|
||||
|
||||
@@ -190,12 +216,53 @@ 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;
|
||||
/// 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
|
||||
}
|
||||
|
||||
/// 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
|
||||
/// 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));
|
||||
let center_clip = view_projection * origin.extend(1.0);
|
||||
let center_ndc = center_clip / center_clip.w;
|
||||
let half_size = rect.size() * 0.5;
|
||||
|
||||
// The z component tracks how the perspective divisor changes per world unit
|
||||
let screen_step = |axis: Vec3| {
|
||||
let clip_step = (view_projection * axis.extend(0.0)) / center_clip.w;
|
||||
let ndc_numerator = clip_step - center_ndc * clip_step.w;
|
||||
Vec3::new(ndc_numerator.x * half_size.x, -ndc_numerator.y * half_size.y, clip_step.w)
|
||||
};
|
||||
let across_step = screen_step(across);
|
||||
let up_step = screen_step(up);
|
||||
let ring_steps: [Vec3; RING_SEGMENTS] = std::array::from_fn(|index| {
|
||||
let (sin, cos) = (index as f32 / RING_SEGMENTS as f32 * std::f32::consts::TAU).sin_cos();
|
||||
across_step * cos + up_step * sin
|
||||
});
|
||||
|
||||
// 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 = 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;
|
||||
if !depth.is_finite() || depth <= f32::EPSILON {
|
||||
return None;
|
||||
}
|
||||
|
||||
*point += vec2(step.x, step.y) * (radius / depth);
|
||||
}
|
||||
|
||||
ring[RING_SEGMENTS] = ring[0];
|
||||
|
||||
Some(ring)
|
||||
}
|
||||
|
||||
/// `delta` as a mix of screen steps `across_step` and `up_step` (None when they are parallel on screen)
|
||||
@@ -226,6 +293,7 @@ pub(crate) fn nearest<T: Copy>(handles: impl IntoIterator<Item = (T, f32)>) -> O
|
||||
best = Some((handle, distance));
|
||||
}
|
||||
}
|
||||
|
||||
best.map(|(handle, _)| handle)
|
||||
}
|
||||
|
||||
@@ -244,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 => {
|
||||
@@ -288,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?;
|
||||
@@ -303,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))
|
||||
}
|
||||
@@ -325,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() {
|
||||
@@ -345,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
|
||||
@@ -418,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}))
|
||||
@@ -519,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()
|
||||
}
|
||||
|
||||
@@ -645,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
|
||||
@@ -667,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)));
|
||||
|
||||
@@ -676,6 +789,112 @@ pub(crate) mod tests {
|
||||
assert_eq!(corners, Projection::FRAME_CORNERS, "its corners stay where they are on the frame");
|
||||
}
|
||||
|
||||
/// The longest reach stays near the intended screen radius as the camera orbits.
|
||||
#[test]
|
||||
fn the_ring_keeps_its_screen_size_at_oblique_angles() {
|
||||
const MAX_RING_SHARE: f32 = 1.25;
|
||||
const MIN_RING_SHARE: f32 = 0.6;
|
||||
const ORBIT_DEGREES: [f32; 6] = [0.0, 40.0, 60.0, 75.0, 80.0, 84.0];
|
||||
const ZOOM_OUT_EXPONENT: f32 = 1.5;
|
||||
const MAX_FORESHORTENED_ACROSS_TO_UP_RATIO: f32 = 0.4;
|
||||
|
||||
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
|
||||
harness.state_mut().session.camera.zoom(-ZOOM_OUT_EXPONENT);
|
||||
for degrees in ORBIT_DEGREES {
|
||||
harness.state_mut().session.camera.set_angles(degrees.to_radians(), 0.0);
|
||||
harness.run_steps(2);
|
||||
|
||||
let shown = gizmo(&harness);
|
||||
let Some(ring) = shown.ring else { continue };
|
||||
let reach = ring.iter().map(|at| at.distance(shown.center)).fold(0.0, f32::max);
|
||||
let across_step = shown.steps[0].unwrap().length();
|
||||
let up_step = shown.steps[1].unwrap().length();
|
||||
|
||||
assert!(
|
||||
(TURN_RING * MIN_RING_SHARE..=TURN_RING * MAX_RING_SHARE).contains(&reach),
|
||||
"{kind} orbited {degrees} degrees: the ring reaches {reach} points"
|
||||
);
|
||||
|
||||
foreshortened_shown |= across_step < up_step * MAX_FORESHORTENED_ACROSS_TO_UP_RATIO;
|
||||
}
|
||||
|
||||
assert!(foreshortened_shown, "{kind}: the ring was checked with the across direction foreshortened");
|
||||
}
|
||||
}
|
||||
|
||||
#[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;
|
||||
const LARGE_FRAME_SIDE: f32 = 5.0;
|
||||
const CAMERA_DISTANCE: f32 = 4.0;
|
||||
const ORBIT_DEGREES: f32 = 65.0;
|
||||
const EDGE_ON_ANGLE: f32 = std::f32::consts::FRAC_PI_2;
|
||||
const MIN_RING_SHARE: f32 = 0.75;
|
||||
const MAX_RING_SHARE: f32 = 1.25;
|
||||
|
||||
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);
|
||||
|
||||
// Reverse the frame axes, then put a large frame's across step behind the camera
|
||||
for (rotation_degrees, side) in [(-45.0, FRAME_SIDE), (135.0, FRAME_SIDE), (0.0, LARGE_FRAME_SIDE)] {
|
||||
let size = [side; 2];
|
||||
harness.state_mut().run("layer.decal.set", json!({"layer": layer.0, "size": size, "rotation": rotation_degrees})).unwrap();
|
||||
harness.run_steps(2);
|
||||
|
||||
let shown = gizmo(&harness);
|
||||
let ring = shown.ring.unwrap_or_else(|| panic!("{kind} turned {rotation_degrees} degrees: the oblique ring should show"));
|
||||
let reach = ring.iter().map(|point| point.distance(shown.center)).fold(0.0, f32::max);
|
||||
|
||||
assert!(
|
||||
(expected_radius * MIN_RING_SHARE..=expected_radius * MAX_RING_SHARE).contains(&reach),
|
||||
"{kind} turned {rotation_degrees} degrees: the ring reaches {reach} points"
|
||||
);
|
||||
}
|
||||
|
||||
harness.state_mut().session.camera.set_angles(EDGE_ON_ANGLE, 0.0);
|
||||
harness.run_steps(2);
|
||||
|
||||
assert!(gizmo(&harness).ring.is_none(), "{kind}: hide the ring when the frame is edge-on");
|
||||
}
|
||||
}
|
||||
|
||||
/// Losing the focus mid-drag (Alt+Tab) ends a frame drag as a release does: one undo step, and moves after it (egui still has the button down) leave the frame alone
|
||||
#[test]
|
||||
fn losing_the_window_focus_ends_a_frame_drag() {
|
||||
@@ -748,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() {
|
||||
@@ -840,7 +1091,7 @@ pub(crate) mod tests {
|
||||
click(&mut harness, eye.center());
|
||||
|
||||
assert!(!harness.state().session.doc.project.display.projection_gizmos, "the eye hides the gizmos");
|
||||
assert!(FrameGizmo::shown(harness.state(), harness.state().viewport_rect).is_none(), "the 3D view has no frame to draw or grab");
|
||||
assert!(crate::projection_gizmo::ShownGizmo::of(harness.state(), harness.state().viewport_rect).is_none(), "the 3D view has no frame to draw or grab");
|
||||
|
||||
let before = projection(&harness, layer);
|
||||
drag(&mut harness, shown.center, shown.center + vec2(30.0, 0.0), Modifiers::NONE);
|
||||
|
||||
@@ -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,380 @@
|
||||
//! 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)).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 }
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@ use crate::i18n::{tr, trf};
|
||||
use crate::state::{ImportResources, ImportRow, ResourceUsage};
|
||||
use crate::web_files::{IMAGE_EXTS, MATERIAL_EXTS};
|
||||
use crate::widgets::primary_button;
|
||||
use crate::windows::MATERIALX_EXT;
|
||||
|
||||
/// Width of the window
|
||||
const WINDOW_WIDTH_POINTS: f32 = 640.0;
|
||||
@@ -28,6 +29,8 @@ const USAGE_WIDTH_POINTS: f32 = 110.0;
|
||||
const TARGET_WIDTH_POINTS: f32 = 190.0;
|
||||
/// Keep space for the file name in a narrow row
|
||||
const MIN_NAME_WIDTH_POINTS: f32 = 40.0;
|
||||
const CONTROL_GAP_POINTS: f32 = 4.0;
|
||||
const SECTION_GAP_POINTS: f32 = 8.0;
|
||||
|
||||
/// Opens the window with an empty list (an open window stays as it is)
|
||||
pub(crate) fn open(app: &mut TextureCraftApp) {
|
||||
@@ -62,18 +65,17 @@ pub(crate) fn keys_in(app: &mut TextureCraftApp, input: &mut egui::InputState, n
|
||||
}
|
||||
}
|
||||
|
||||
fn extension_of(row: &ImportRow) -> String {
|
||||
row.path.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase).unwrap_or_default()
|
||||
fn extension_of(row: &ImportRow) -> Option<&str> {
|
||||
row.path.extension().and_then(|extension| extension.to_str())
|
||||
}
|
||||
|
||||
/// Whether the file is a MaterialX document (added as a fill layer)
|
||||
fn is_materialx(row: &ImportRow) -> bool {
|
||||
extension_of(row) == crate::windows::MATERIALX_EXT
|
||||
fn is_smart_material_extension(extension: &str) -> bool {
|
||||
MATERIAL_EXTS.iter().any(|material_extension| extension.eq_ignore_ascii_case(material_extension))
|
||||
}
|
||||
|
||||
/// Whether the file is a material (a smart material or a MaterialX document, so it has no usage or prefix)
|
||||
fn is_material(row: &ImportRow) -> bool {
|
||||
MATERIAL_EXTS.contains(&extension_of(row).as_str()) || is_materialx(row)
|
||||
extension_of(row).is_some_and(|extension| extension.eq_ignore_ascii_case(MATERIALX_EXT) || is_smart_material_extension(extension))
|
||||
}
|
||||
|
||||
fn file_name(row: &ImportRow) -> String {
|
||||
@@ -136,10 +138,11 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
import |= ui.add_enabled(app.session.project_open && !window.rows.is_empty(), primary_button(ui, tr("Import"))).clicked();
|
||||
});
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
ui.add_space(CONTROL_GAP_POINTS);
|
||||
if !app.session.project_open {
|
||||
ui.label(tr("Open a project to import resources. Importing into the asset library is not available yet."));
|
||||
}
|
||||
|
||||
ui.horizontal(|ui| {
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
egui::ComboBox::from_id_salt("import_target").width(TARGET_WIDTH_POINTS).selected_text(tr("Open project")).show_ui(ui, |ui| {
|
||||
@@ -152,7 +155,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
ui.label(tr("Destination"));
|
||||
});
|
||||
});
|
||||
ui.add_space(8.0);
|
||||
ui.add_space(SECTION_GAP_POINTS);
|
||||
ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(tr("Choose files and assign their roles"));
|
||||
@@ -163,7 +166,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
add = ui.button(tr("Add resources")).clicked();
|
||||
});
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
ui.add_space(CONTROL_GAP_POINTS);
|
||||
|
||||
let all_label = trf("All files ({count})", &[("count", &window.rows.len())]);
|
||||
let filter_text = match window.filter {
|
||||
@@ -185,12 +188,13 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
ui.add_space(CONTROL_GAP_POINTS);
|
||||
|
||||
let filter = window.filter;
|
||||
let visible = |row: &ImportRow| filter.is_none_or(|usage| row.usage == usage);
|
||||
let modifiers = ui.input(|i| i.modifiers);
|
||||
let mut clicked = None;
|
||||
let mut clicked_row = None;
|
||||
let mut selected_usage = None;
|
||||
|
||||
let list_height = ui.available_height().max(0.0);
|
||||
egui::ScrollArea::both().min_scrolled_width(0.0).min_scrolled_height(0.0).max_height(list_height).auto_shrink([false, false]).show(
|
||||
@@ -199,13 +203,14 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
for row in window.rows.iter_mut().filter(|row| visible(row)) {
|
||||
let material = is_material(row);
|
||||
let selected = window.selected.contains(&row.id);
|
||||
|
||||
ui.horizontal(|ui| {
|
||||
let name_width = (ui.available_width() - PREFIX_WIDTH_POINTS - USAGE_WIDTH_POINTS - 2.0 * ui.spacing().item_spacing.x)
|
||||
.max(MIN_NAME_WIDTH_POINTS);
|
||||
let name =
|
||||
ui.add_sized([name_width, ui.spacing().interact_size.y], egui::Button::selectable(selected, file_name(row)).truncate());
|
||||
if name.on_hover_text(row.path.display().to_string()).clicked() {
|
||||
clicked = Some(row.id);
|
||||
clicked_row = Some(row.id);
|
||||
}
|
||||
|
||||
let prefix = ui.add_enabled(
|
||||
@@ -225,14 +230,18 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
.selected_text(row.usage.name())
|
||||
.show_ui(ui, |ui| {
|
||||
for usage in ResourceUsage::ALL {
|
||||
let item = ui.add_enabled(usage.available(), egui::Button::selectable(row.usage == usage, usage.name()));
|
||||
if usage.available() {
|
||||
if item.clicked() {
|
||||
row.usage = usage;
|
||||
ui.close();
|
||||
}
|
||||
} else {
|
||||
let available = usage.available();
|
||||
let item = ui.add_enabled(available, egui::Button::selectable(row.usage == usage, usage.name()));
|
||||
if !available {
|
||||
item.on_disabled_hover_text(tr("Not available yet"));
|
||||
} else if item.clicked() {
|
||||
if selected && window.selected.len() > 1 {
|
||||
selected_usage = Some(usage);
|
||||
} else {
|
||||
row.usage = usage;
|
||||
}
|
||||
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -244,7 +253,16 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
},
|
||||
);
|
||||
|
||||
if let Some(id) = clicked {
|
||||
// Include selected rows hidden by the filter
|
||||
if let Some(usage) = selected_usage {
|
||||
for row in &mut window.rows {
|
||||
if window.selected.contains(&row.id) && !is_material(row) {
|
||||
row.usage = usage;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(id) = clicked_row {
|
||||
let visible: Vec<u64> =
|
||||
if modifiers.shift { window.rows.iter().filter(|row| visible(row)).map(|row| row.id).collect() } else { Vec::new() };
|
||||
click_row(&mut window, &visible, id, modifiers);
|
||||
@@ -266,7 +284,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
if add {
|
||||
let mut extensions: Vec<&str> = IMAGE_EXTS.to_vec();
|
||||
extensions.extend_from_slice(MATERIAL_EXTS);
|
||||
extensions.push(crate::windows::MATERIALX_EXT);
|
||||
extensions.push(MATERIALX_EXT);
|
||||
let opening_id = window.opening_id;
|
||||
app.ask_file(FileDialog::open_many().filter(tr("Resources"), &extensions), Bound::Project, move |app, paths| {
|
||||
let Some(stored) = app.ui.windows.import_resources.as_mut().filter(|stored| stored.opening_id == opening_id) else { return };
|
||||
@@ -297,19 +315,21 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
app.ui.windows.import_resources = Some(window);
|
||||
}
|
||||
|
||||
/// Import one row. A failed file is left in the dialog with its settings.
|
||||
/// Returns true once the resource has been imported or a linked material cook has been queued.
|
||||
fn import_row(app: &mut TextureCraftApp, row: &ImportRow) -> bool {
|
||||
let Some(path) = row.path.to_str() else {
|
||||
app.toast(trf("Could not import a path that is not UTF-8: {path}", &[("path", &row.path.display())]), true);
|
||||
return false;
|
||||
};
|
||||
|
||||
if is_materialx(row) {
|
||||
return crate::windows::import_materialx(app, path);
|
||||
}
|
||||
if let Some(extension) = extension_of(row) {
|
||||
if extension.eq_ignore_ascii_case(MATERIALX_EXT) {
|
||||
return crate::windows::import_materialx(app, path);
|
||||
}
|
||||
|
||||
if is_material(row) {
|
||||
return app.run("material.load", json!({ "path": path })).is_some();
|
||||
if is_smart_material_extension(extension) {
|
||||
return app.run("material.load", json!({ "path": path })).is_some();
|
||||
}
|
||||
}
|
||||
|
||||
let Some(result) = app.run("resource.import", json!({ "path": path, "prefix": row.prefix })) else { return false };
|
||||
|
||||
@@ -4,8 +4,8 @@
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
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;
|
||||
|
||||
@@ -179,11 +179,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 +214,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.
|
||||
@@ -229,7 +229,7 @@ impl Default for 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() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -245,7 +245,7 @@ impl Bindings {
|
||||
/// 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 +253,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.
|
||||
@@ -391,7 +387,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, "");
|
||||
@@ -487,15 +485,17 @@ 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. A plain Escape while none of TextureCraft's widgets has the keyboard
|
||||
/// is the window's cancel, which the recorder takes as the Escape that cancels it.
|
||||
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(|| KeyboardShortcut::new(Modifiers::NONE, Key::Escape)))
|
||||
}
|
||||
|
||||
/// The shortcut editor window.
|
||||
@@ -509,7 +509,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)
|
||||
{
|
||||
@@ -808,6 +810,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]
|
||||
|
||||
@@ -44,6 +44,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;
|
||||
@@ -102,6 +103,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;
|
||||
@@ -139,6 +141,8 @@ mod resource_picker;
|
||||
mod resource_picker_item;
|
||||
mod round_gizmo;
|
||||
mod running_bake;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod sample_project;
|
||||
pub mod saved_search;
|
||||
mod screen_color_pick;
|
||||
pub mod screen_pick;
|
||||
@@ -155,6 +159,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;
|
||||
@@ -256,6 +261,9 @@ pub struct TextureCraftApp {
|
||||
pub session: Session,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) session_log_file: Option<session_log_file::SessionLogFile>,
|
||||
/// The folder File > Open Sample Project starts in, under the data folder
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub samples_folder: std::path::PathBuf,
|
||||
viewport_mesh_bounds: viewport_mesh_bounds::ViewportMeshBounds,
|
||||
/// A smooth move to a saved camera in progress.
|
||||
camera_glide: Option<CameraGlide>,
|
||||
@@ -294,6 +302,10 @@ 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)>,
|
||||
pub fps: f32,
|
||||
/// User smart materials found in the library folder (refreshed on demand).
|
||||
pub library: Option<Vec<std::path::PathBuf>>,
|
||||
@@ -331,6 +343,16 @@ 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))]
|
||||
@@ -416,6 +438,8 @@ impl TextureCraftApp {
|
||||
session,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
session_log_file: None,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
samples_folder: std::path::PathBuf::new(),
|
||||
viewport_mesh_bounds: viewport_mesh_bounds::ViewportMeshBounds::default(),
|
||||
ui,
|
||||
ui_store,
|
||||
@@ -437,6 +461,8 @@ 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,
|
||||
fps: 0.0,
|
||||
ui_ms: 0.0,
|
||||
profiler: profile::Profiler::default(),
|
||||
@@ -460,6 +486,11 @@ 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,
|
||||
styled: None,
|
||||
@@ -491,6 +522,7 @@ impl TextureCraftApp {
|
||||
{
|
||||
// The first window of the process fixes it; a new folder applies on restart
|
||||
let _ = DATA_FOLDER.set(data_folder(&app.ui.prefs.data_folder));
|
||||
app.samples_folder = user_dir(sample_project::SAMPLES_FOLDER);
|
||||
|
||||
if cc.winit_window().is_some() {
|
||||
match session_log_file::SessionLogFile::start(&crate::data_dir().join("logs")) {
|
||||
@@ -1099,6 +1131,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);
|
||||
}
|
||||
|
||||
@@ -1193,6 +1226,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);
|
||||
|
||||
@@ -1213,7 +1251,7 @@ 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);
|
||||
self.close_path(ctx);
|
||||
}
|
||||
|
||||
#[cfg_attr(target_arch = "wasm32", allow(unused_variables))]
|
||||
@@ -1242,7 +1280,20 @@ impl eframe::App for TextureCraftApp {
|
||||
|
||||
// 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);
|
||||
}
|
||||
});
|
||||
|
||||
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
|
||||
@@ -1250,6 +1301,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);
|
||||
|
||||
+39
-16
@@ -179,6 +179,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 +419,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 +452,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 +463,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
|
||||
// Unbound Shift+Delete and Shift+Insert use the standard cut and paste shortcuts
|
||||
ctx.input_mut(|input| {
|
||||
@@ -472,14 +491,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 +509,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
|
||||
@@ -561,17 +579,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).
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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| {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -15,9 +15,13 @@ pub(crate) enum ShownGizmo {
|
||||
impl ShownGizmo {
|
||||
/// The gizmo of the selected fill's projection: none while the Projection row's eye hides it
|
||||
pub(crate) fn of(app: &TextureCraftApp, rect: Rect) -> Option<ShownGizmo> {
|
||||
FrameGizmo::shown(app, rect)
|
||||
if !app.session.doc.project.display.projection_gizmos {
|
||||
return None;
|
||||
}
|
||||
|
||||
FrameGizmo::of(app, rect)
|
||||
.map(|frame| ShownGizmo::Frame(Box::new(frame)))
|
||||
.or_else(|| RoundGizmo::shown(app, rect).map(|round| ShownGizmo::Round(Box::new(round))))
|
||||
.or_else(|| RoundGizmo::of(app, rect).map(|round| ShownGizmo::Round(Box::new(round))))
|
||||
}
|
||||
|
||||
fn frame(gizmo: Option<&ShownGizmo>) -> Option<&FrameGizmo> {
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -56,11 +56,6 @@ fn icons_id() -> Id {
|
||||
Id::unique("rail_popup_icons")
|
||||
}
|
||||
|
||||
/// The panel whose popup title a drag left, and the title's rect, until the dock takes the drag over
|
||||
fn pending_drag_id() -> Id {
|
||||
Id::unique("rail_popup_pending_drag")
|
||||
}
|
||||
|
||||
/// Where the dock drew the viewport on this frame
|
||||
fn viewport_id() -> Id {
|
||||
Id::unique("rail_popup_viewport")
|
||||
@@ -114,16 +109,6 @@ pub(crate) fn open(app: &mut TextureCraftApp, panel: Panel) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Hand a drag that left the popup's title to the dock, once the dock has drawn the panel it floated
|
||||
pub(crate) fn hand_drag_to_dock(ctx: &egui::Context, dock_area: Id) {
|
||||
let Some((panel, title)) = ctx.data(|data| data.get_temp::<(Panel, Rect)>(pending_drag_id())) else { return };
|
||||
|
||||
ctx.data_mut(|data| data.remove::<(Panel, Rect)>(pending_drag_id()));
|
||||
if ctx.input(|input| input.pointer.primary_down()) {
|
||||
craft_ui::docking::begin_drag(ctx, dock_area, panel, title);
|
||||
}
|
||||
}
|
||||
|
||||
/// A rail popup and its dismissing press cannot start a paint stroke or move a decal
|
||||
pub(crate) fn blocks_paint_input(app: &TextureCraftApp, ctx: &egui::Context) -> bool {
|
||||
let closing_id = area_id().with("closing");
|
||||
@@ -196,13 +181,17 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
// The floating window opens where the popup was, at its size
|
||||
app.ui.rail_panel = None;
|
||||
if let Some(rect) = shown {
|
||||
app.ui.dock.float_at(panel, [rect.left(), rect.top(), rect.width(), rect.height()]);
|
||||
app.ui.dock.float_at(panel, rect);
|
||||
}
|
||||
} else if let Some(title) = dragged_from {
|
||||
// The floating window opens where the popup was
|
||||
app.ui.rail_panel = None;
|
||||
let rect = shown.unwrap_or(title);
|
||||
app.ui.dock.float_at(panel, [rect.left(), rect.top(), rect.width(), rect.height()]);
|
||||
ctx.data_mut(|data| data.insert_temp(pending_drag_id(), (panel, title)));
|
||||
let window = shown.unwrap_or(title);
|
||||
app.ui.dock.float_at(panel, window);
|
||||
// The window takes over the held press in the next pass, so the drag carries on and docks where it is released
|
||||
if let Some(pointer) = ctx.input(|input| input.pointer.latest_pos()) {
|
||||
app.docks.hand_over(panel, pointer - window.min);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -39,7 +39,10 @@ fn environment_cache_retains_source_identity_until_replaced() {
|
||||
|
||||
// The harness draws once; parallel translation tests must not change its language mid-frame
|
||||
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let mut app = egui_kittest::Harness::builder().build_eframe(|context| crate::TextureCraftApp::new(context, session())).into_state();
|
||||
let mut app = egui_kittest::Harness::builder()
|
||||
.with_context_setup(crate::framework::install_headless)
|
||||
.build_eframe(|context| crate::TextureCraftApp::new(context, session()))
|
||||
.into_state();
|
||||
app.session.doc.project.display.environment = "resource:environment".into();
|
||||
let source = Arc::new(ImageRes::new(2, 1, vec![[1.0, 0.0, 0.0, 1.0]; 2], false));
|
||||
let original_source = Arc::downgrade(&source);
|
||||
@@ -71,7 +74,10 @@ fn environment_cache_retains_source_identity_until_replaced() {
|
||||
#[test]
|
||||
fn a_new_display_background_restarts_the_render() {
|
||||
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let mut app = egui_kittest::Harness::builder().build_eframe(|context| crate::TextureCraftApp::new(context, session())).into_state();
|
||||
let mut app = egui_kittest::Harness::builder()
|
||||
.with_context_setup(crate::framework::install_headless)
|
||||
.build_eframe(|context| crate::TextureCraftApp::new(context, session()))
|
||||
.into_state();
|
||||
let before = super::key(&app, "scene", (64, 64));
|
||||
assert_eq!(super::key(&app, "scene", (64, 64)), before);
|
||||
|
||||
@@ -109,6 +115,7 @@ fn gpu_app() -> Option<crate::TextureCraftApp> {
|
||||
let mut app = egui_kittest::Harness::builder()
|
||||
.with_size(egui::vec2(800.0, 600.0))
|
||||
.renderer(WgpuTestRenderer::from_render_state(render_state))
|
||||
.with_context_setup(crate::framework::install_headless)
|
||||
.build_eframe(|context| crate::TextureCraftApp::new(context, session()))
|
||||
.into_state();
|
||||
app.session.update();
|
||||
|
||||
@@ -72,11 +72,6 @@ const BOX_AXIS_BITS: [usize; 3] = [1, 2, 4];
|
||||
const STEP_PROBE_RADII: f32 = 0.5;
|
||||
|
||||
impl RoundGizmo {
|
||||
/// The projector as the 3D view shows it: none while the Projection row's eye hides the projection gizmos
|
||||
pub(crate) fn shown(app: &TextureCraftApp, rect: Rect) -> Option<RoundGizmo> {
|
||||
RoundGizmo::of(app, rect).filter(|_| app.session.doc.project.display.projection_gizmos)
|
||||
}
|
||||
|
||||
/// The projector of the selected tri-planar, spherical or cylindrical fill
|
||||
pub(crate) fn of(app: &TextureCraftApp, rect: Rect) -> Option<RoundGizmo> {
|
||||
if app.ui.mode != crate::state::Mode::Painting {
|
||||
@@ -153,7 +148,7 @@ impl RoundGizmo {
|
||||
let pixels = (project(app, rect, origin + right * reach)? - center).length() / reach;
|
||||
let ring = TURN_RING / pixels.max(f32::MIN_POSITIVE);
|
||||
self.rings = directions.map(|direction| {
|
||||
if !ring_open(app, rect, center, direction) {
|
||||
if !ring_open(app, rect, center, direction, TURN_RING) {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
//! Installs the bundled projects in the data folder for File > Open Sample Project.
|
||||
|
||||
mod shipped_sample;
|
||||
|
||||
use std::io::ErrorKind;
|
||||
use std::path::Path;
|
||||
|
||||
use shipped_sample::ShippedSample;
|
||||
|
||||
/// The folder under the data folder that holds the sample projects
|
||||
pub(crate) const SAMPLES_FOLDER: &str = "Samples";
|
||||
|
||||
const SHIPPED_SAMPLES: &[ShippedSample] =
|
||||
&[ShippedSample { file_name: "Material Ball.tcraft", bytes: include_bytes!("../../../assets/samples/Material Ball.tcraft") }];
|
||||
|
||||
/// Makes sure `folder` exists and holds every shipped sample. A file that is already there is
|
||||
/// kept as it is, so a sample the user edited and saved stays.
|
||||
pub(crate) fn install(folder: &Path) -> Result<(), String> {
|
||||
std::fs::create_dir_all(folder).map_err(|error| format!("{}: {error}", folder.display()))?;
|
||||
|
||||
for sample in SHIPPED_SAMPLES {
|
||||
let destination = folder.join(sample.file_name);
|
||||
match destination.symlink_metadata() {
|
||||
Ok(_) => continue,
|
||||
Err(error) if error.kind() == ErrorKind::NotFound => {}
|
||||
Err(error) => return Err(format!("{}: {error}", destination.display())),
|
||||
}
|
||||
|
||||
sample.install_missing(folder, &destination).map_err(|error| format!("{}: {error}", destination.display()))?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
use std::io::{self, ErrorKind, Write as _};
|
||||
use std::path::Path;
|
||||
|
||||
/// A built-in sample project and its installed filename.
|
||||
pub(super) struct ShippedSample {
|
||||
pub(super) file_name: &'static str,
|
||||
pub(super) bytes: &'static [u8],
|
||||
}
|
||||
|
||||
impl ShippedSample {
|
||||
pub(super) fn install_missing(&self, folder: &Path, destination: &Path) -> io::Result<()> {
|
||||
let mut staged_sample = tempfile::NamedTempFile::new_in(folder)?;
|
||||
staged_sample.write_all(self.bytes)?;
|
||||
staged_sample.as_file().sync_all()?;
|
||||
|
||||
// A user can save to the destination while the bundled copy is being written
|
||||
match staged_sample.persist_noclobber(destination) {
|
||||
Ok(_) => Ok(()),
|
||||
Err(error) if error.error.kind() == ErrorKind::AlreadyExists => Ok(()),
|
||||
Err(error) => Err(error.error),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::ShippedSample;
|
||||
|
||||
#[test]
|
||||
fn a_sample_that_appears_during_install_is_kept() {
|
||||
let folder = tempfile::tempdir().unwrap();
|
||||
let sample = ShippedSample { file_name: "Sample.tcraft", bytes: b"bundled sample" };
|
||||
let destination = folder.path().join(sample.file_name);
|
||||
assert!(!destination.exists());
|
||||
std::fs::write(&destination, b"user project").unwrap();
|
||||
|
||||
sample.install_missing(folder.path(), &destination).unwrap();
|
||||
|
||||
assert_eq!(std::fs::read(&destination).unwrap(), b"user project");
|
||||
assert_eq!(std::fs::read_dir(folder.path()).unwrap().count(), 1, "the temporary copy was removed");
|
||||
}
|
||||
}
|
||||
@@ -44,8 +44,8 @@ fn pick_with(ui: &mut Ui, id: Id, linear: &mut [f32; 3], button: impl FnOnce(&mu
|
||||
pick.target = if picking { None } else { Some(id) };
|
||||
} else if picking {
|
||||
ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);
|
||||
let (clicked, escaped, pointer) =
|
||||
ui.input(|input| (input.pointer.primary_clicked(), input.key_pressed(egui::Key::Escape), input.pointer.interact_pos()));
|
||||
let (clicked, pointer) = ui.input(|input| (input.pointer.primary_clicked(), input.pointer.interact_pos()));
|
||||
let escaped = crate::framework::escape_pressed(ui.ctx());
|
||||
if escaped {
|
||||
pick.target = None;
|
||||
} else if clicked && let Some(point) = pointer {
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
//! The shelf's side panes left of the grid, toggled from the toolbar: saved searches and the folder tree
|
||||
|
||||
use craft_ui::layout::{ResizeHandle, ResizeHandleStyle, SplitAxis, SplitLayout, SplitSize, split_rect};
|
||||
use craft_behavior::dock::SplitSize;
|
||||
use craft_behavior::flow::Axis;
|
||||
use egui::{Rect, RichText, Ui, UiBuilder};
|
||||
use egui_phosphor::regular as ic;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::TextureCraftApp;
|
||||
use crate::i18n::{n_, tr};
|
||||
use crate::pane_split::{ResizeHandle, ResizeHandleStyle, SplitLayout, split_rect};
|
||||
use crate::saved_search::SavedSearch;
|
||||
use crate::shelf::TABS;
|
||||
use crate::theme::Tokens;
|
||||
@@ -93,7 +95,7 @@ fn splitter(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect) -> Option<SplitL
|
||||
// Leave room for a header and a complete row when both minima fit
|
||||
let spacing = ui.spacing();
|
||||
let minimum_points = PANE_MIN_HEIGHT_POINTS.max(2.0 * spacing.interact_size.y + spacing.item_spacing.y);
|
||||
let axis = SplitAxis::Vertical;
|
||||
let axis = Axis::Y;
|
||||
let size = SplitSize::Ratio(app.ui.shelf_panes_split);
|
||||
let mut layout = split_rect(rect, axis, size, SPLITTER_HEIGHT_POINTS, minimum_points)?;
|
||||
let available_points = layout.available();
|
||||
@@ -103,12 +105,12 @@ fn splitter(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect) -> Option<SplitL
|
||||
if available_points > 2.0 * minimum_points {
|
||||
let colors =
|
||||
ResizeHandleStyle { hovered: visuals.widgets.hovered.bg_fill, dragged: visuals.widgets.active.bg_fill, focused: visuals.selection.bg_fill };
|
||||
let resize = ResizeHandle::new(ui.scope_id().with("shelf_panes_splitter"), axis, layout.divider, tr("Resize Assets filter panes"), colors)
|
||||
let delta = ResizeHandle::new(ui.scope_id().with("shelf_panes_splitter"), axis, layout.divider, tr("Resize Assets filter panes"), colors)
|
||||
.hit_margin(0.0)
|
||||
.value(layout.first_size(), minimum_points..=available_points - minimum_points)
|
||||
.show(ui);
|
||||
if resize.delta != 0.0
|
||||
&& let Some(SplitSize::Ratio(share)) = layout.resized(size, resize.delta, minimum_points)
|
||||
if delta != 0.0
|
||||
&& let Some(SplitSize::Ratio(share)) = layout.resized(size, delta, minimum_points)
|
||||
{
|
||||
app.ui.shelf_panes_split = share;
|
||||
layout = split_rect(rect, axis, SplitSize::Ratio(share), SPLITTER_HEIGHT_POINTS, minimum_points)?;
|
||||
|
||||
@@ -0,0 +1,255 @@
|
||||
//! The frame's key presses and clipboard events as the shortcuts they run: egui's events fed to
|
||||
//! `craft_keymap::Matcher`, one press at a time in press order.
|
||||
//!
|
||||
//! - A press that runs a command is removed from egui's input, with the text it typed; one that
|
||||
//! runs nothing, or whose hit the caller declines, stays.
|
||||
//! - Held keys run their command again on each repeat (a held arrow nudges); repeats never count
|
||||
//! toward a double press.
|
||||
//! - egui's Copy, Cut and Paste events count as their plain chords (Cmd+C, Cmd+X, Cmd+V;
|
||||
//! Shift+Delete and Shift+Insert), so the desktop's clipboard events run the edit commands. The
|
||||
//! web build sends a clipboard press and the clipboard event it causes: the press decides, and
|
||||
//! its event goes with it when it runs a command and stays otherwise.
|
||||
//! - The keyboard layout is learned from what plain presses type, and taken from egui when the
|
||||
//! integration reports whether it is Latin.
|
||||
|
||||
use craft_keymap::{Active, Hit, Key, KeyInput, Keymap, Layout, Matcher, Mods, Platform, Press};
|
||||
use egui::{Event, InputState, Key as EguiKey};
|
||||
|
||||
/// eframe's web build sends a press's Text event first when no text field has focus.
|
||||
const TEXT_FIRST: bool = cfg!(target_arch = "wasm32");
|
||||
|
||||
/// What matching carries between frames: the previous press (double presses) and the layout.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Dispatcher {
|
||||
matcher: Matcher,
|
||||
layout: Layout,
|
||||
/// Whether right Alt is held. egui-winit reports AltGr with neither Ctrl nor Alt, so its
|
||||
/// presses would otherwise teach the layout as plain ones.
|
||||
right_alt: bool,
|
||||
}
|
||||
|
||||
impl Dispatcher {
|
||||
/// The keyboard layout learned so far: what a press stands for as a chord.
|
||||
pub(crate) fn layout(&self) -> &Layout {
|
||||
&self.layout
|
||||
}
|
||||
|
||||
/// The commands this frame's key presses and clipboard events run, in press order, with
|
||||
/// `accept` deciding each hit before its event is removed. A declined hit is left out and its
|
||||
/// event, with any text it typed, stays in egui's input in its place.
|
||||
pub(crate) fn dispatch_filtered(&mut self, input: &mut InputState, keymap: &Keymap, mut accept: impl FnMut(&Hit) -> bool) -> Vec<Hit> {
|
||||
let platform = keymap.platform();
|
||||
let now = input.time;
|
||||
let frame_mods = Mods::from_egui(&input.modifiers, platform);
|
||||
let events = std::mem::take(&mut input.events);
|
||||
let text_of = text_of_press(&events, TEXT_FIRST);
|
||||
if let Some(latin) = input.keyboard_layout_is_latin() {
|
||||
self.layout.set_latin(Some(latin));
|
||||
}
|
||||
self.learn(&events, &text_of, platform);
|
||||
let causes = clipboard_event_follows(&events, &self.layout, platform, input);
|
||||
let mut caused_taken: Vec<Option<bool>> = vec![None; events.len()];
|
||||
let mut drop = vec![false; events.len()];
|
||||
let mut hits = Vec::new();
|
||||
let mut kept = Vec::with_capacity(events.len());
|
||||
for (i, event) in events.into_iter().enumerate() {
|
||||
match &event {
|
||||
Event::Key { pressed: true, repeat, .. } => {
|
||||
let key = key_input(&event, platform, input);
|
||||
if self.layout.resolve(&key).is_some() {
|
||||
let press = Press { input: &key, repeat: *repeat, now, active: &Active::NONE, outer: &[] };
|
||||
let hit = self.matcher.press(&self.layout, keymap, &press).filter(&mut accept);
|
||||
if let Some((j, _)) = causes[i] {
|
||||
caused_taken[j] = Some(hit.is_some());
|
||||
}
|
||||
if let Some(hit) = hit {
|
||||
hits.push(hit);
|
||||
if let Some(j) = text_of[i].filter(|_| !(key.mods.cmd || key.mods.ctrl)) {
|
||||
drop[j] = true;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Desktop clipboard events, and web ones whose press ran nothing.
|
||||
Event::Copy | Event::Cut | Event::Paste(_) => match caused_taken[i] {
|
||||
Some(true) => continue,
|
||||
Some(false) => {}
|
||||
None => {
|
||||
let (key, held) = clipboard_chord(&event, frame_mods);
|
||||
let press = Press { input: &KeyInput::new(held).with_typed(key), repeat: false, now, active: &Active::NONE, outer: &[] };
|
||||
if let Some(hit) = self.matcher.press(&self.layout, keymap, &press).filter(&mut accept) {
|
||||
hits.push(hit);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
},
|
||||
_ => {}
|
||||
}
|
||||
kept.push((i, event));
|
||||
}
|
||||
input.events = kept.into_iter().filter(|(i, _)| !drop[*i]).map(|(_, e)| e).collect();
|
||||
hits
|
||||
}
|
||||
|
||||
/// Teaches the layout what this frame's presses typed.
|
||||
fn learn(&mut self, events: &[Event], text_of: &[Option<usize>], platform: Platform) {
|
||||
for (event, text) in events.iter().zip(text_of) {
|
||||
match event {
|
||||
Event::Key { physical_key: Some(EguiKey::AltRight), pressed, .. } => self.right_alt = *pressed,
|
||||
Event::WindowFocused(false) => self.right_alt = false,
|
||||
_ => {}
|
||||
}
|
||||
if self.right_alt {
|
||||
continue;
|
||||
}
|
||||
let Some(Event::Text(text)) = text.and_then(|j| events.get(j)) else { continue };
|
||||
if let Some(KeyInput { mods, physical: Some(physical), .. }) = KeyInput::from_egui(event, platform) {
|
||||
self.layout.observe(physical, mods, text);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A press as [`KeyInput::from_egui`] reads it, with the Latin layout's character `input` reports
|
||||
/// for its key.
|
||||
fn key_input(event: &Event, platform: Platform, input: &InputState) -> KeyInput {
|
||||
let mut key = KeyInput::from_egui(event, platform).unwrap_or(KeyInput::new(Mods::NONE));
|
||||
if let Event::Key { physical_key: Some(physical), .. } = event {
|
||||
key.latin = input.latin_layout_char(*physical);
|
||||
}
|
||||
key
|
||||
}
|
||||
|
||||
/// A clipboard event's kind.
|
||||
#[derive(Clone, Copy)]
|
||||
enum Clip {
|
||||
Copy,
|
||||
Cut,
|
||||
Paste,
|
||||
}
|
||||
|
||||
fn event_clip(event: &Event) -> Option<Clip> {
|
||||
match event {
|
||||
Event::Copy => Some(Clip::Copy),
|
||||
Event::Cut => Some(Clip::Cut),
|
||||
Event::Paste(_) => Some(Clip::Paste),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The clipboard event a backend sends for a press, if any.
|
||||
fn clipboard_kind(key: Key, held: Mods) -> Option<Clip> {
|
||||
match key {
|
||||
Key::C if held.cmd => Some(Clip::Copy),
|
||||
Key::X if held.cmd => Some(Clip::Cut),
|
||||
Key::V if held.cmd => Some(Clip::Paste),
|
||||
Key::Delete if held.shift => Some(Clip::Cut),
|
||||
Key::Insert if held.shift => Some(Clip::Paste),
|
||||
Key::Insert if held.cmd || held.ctrl => Some(Clip::Copy),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// For each clipboard key press whose clipboard event comes later in the frame, as the web build
|
||||
/// sends them: the index of that event, and the text of a Paste event.
|
||||
fn clipboard_event_follows(events: &[Event], layout: &Layout, platform: Platform, input: &InputState) -> Vec<Option<(usize, Option<String>)>> {
|
||||
let mut out = vec![None; events.len()];
|
||||
let mut ahead: [Option<usize>; 3] = [None; 3];
|
||||
for (i, event) in events.iter().enumerate().rev() {
|
||||
if let Some(seen) = event_clip(event).and_then(|c| ahead.get_mut(c as usize)) {
|
||||
*seen = Some(i);
|
||||
} else if let Event::Key { pressed: true, .. } = event {
|
||||
let chord = layout.resolve(&key_input(event, platform, input));
|
||||
let clip = chord.and_then(|c| clipboard_kind(c.key, c.mods));
|
||||
if let Some(j) = clip.and_then(|c| ahead.get_mut(c as usize)).and_then(Option::take) {
|
||||
let text = if let Some(Event::Paste(text)) = events.get(j) { Some(text.clone()) } else { None };
|
||||
out[i] = Some((j, text));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// For each key press, the index of the Text event it typed. egui-winit, and eframe's web text
|
||||
/// agent while a text field has focus, send the Text after the press, before the next one.
|
||||
/// With `text_first`, eframe's web build with no text field focused, the Text comes right before
|
||||
/// its press, and only for a press without Ctrl or Cmd.
|
||||
fn text_of_press(events: &[Event], text_first: bool) -> Vec<Option<usize>> {
|
||||
let is_text = |e: Option<&Event>| matches!(e, Some(Event::Text(t)) if !t.is_empty());
|
||||
let mut out = vec![None; events.len()];
|
||||
if text_first {
|
||||
for (i, event) in events.iter().enumerate().skip(1) {
|
||||
if let Event::Key { pressed: true, modifiers, .. } = event
|
||||
&& !(modifiers.ctrl || modifiers.command || modifiers.mac_cmd)
|
||||
&& is_text(events.get(i - 1))
|
||||
{
|
||||
out[i] = Some(i - 1);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
let mut text_ahead = None;
|
||||
for (i, event) in events.iter().enumerate().rev() {
|
||||
match event {
|
||||
Event::Key { pressed: true, .. } => out[i] = text_ahead.take(),
|
||||
_ if is_text(Some(event)) => text_ahead = Some(i),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The press a clipboard event stands for, with the modifiers held. Off macOS egui-winit also
|
||||
/// sends Cut for Shift+Delete and Paste for Shift+Insert.
|
||||
fn clipboard_chord(event: &Event, held: Mods) -> (Key, Mods) {
|
||||
let with_cmd = Mods { cmd: true, ..held };
|
||||
let shift_only = held.shift && !held.cmd;
|
||||
match event {
|
||||
Event::Cut if shift_only => (Key::Delete, held),
|
||||
Event::Cut => (Key::X, with_cmd),
|
||||
Event::Paste(_) if shift_only => (Key::Insert, held),
|
||||
Event::Paste(_) => (Key::V, with_cmd),
|
||||
_ => (Key::C, with_cmd),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use craft_keymap::{Binding, CommandDef, Scope, Scopes};
|
||||
|
||||
fn keymap() -> Keymap {
|
||||
let def = |id: &'static str, binding: &str| CommandDef::new(id, id, Scope::app()).with_default(Binding::parse(binding).unwrap());
|
||||
Keymap::new(vec![def("tool.marquee", "M"), def("edit.copy", "Ctrl+C")], Scopes::new(), Platform::Windows)
|
||||
}
|
||||
|
||||
fn press(key: EguiKey, modifiers: egui::Modifiers) -> Event {
|
||||
Event::Key { key, physical_key: Some(key), pressed: true, repeat: false, modifiers }
|
||||
}
|
||||
|
||||
/// A press that runs a command leaves egui's input with the text it typed; the others stay, in order.
|
||||
#[test]
|
||||
fn a_bound_press_and_its_text_leave_the_input() {
|
||||
let mut input = InputState::default();
|
||||
input.events =
|
||||
vec![press(EguiKey::M, egui::Modifiers::NONE), Event::Text("m".into()), press(EguiKey::Q, egui::Modifiers::NONE), Event::Text("q".into())];
|
||||
let hits = Dispatcher::default().dispatch_filtered(&mut input, &keymap(), |_| true);
|
||||
assert_eq!(hits.iter().map(|hit| hit.command.id.as_str()).collect::<Vec<_>>(), ["tool.marquee"]);
|
||||
assert_eq!(input.events, [press(EguiKey::Q, egui::Modifiers::NONE), Event::Text("q".into())]);
|
||||
}
|
||||
|
||||
/// The desktop's Copy event runs the copy command; declined, it stays for egui.
|
||||
#[test]
|
||||
fn a_clipboard_event_runs_its_chord_unless_declined() {
|
||||
let mut input = InputState::default();
|
||||
input.events = vec![Event::Copy];
|
||||
let hits = Dispatcher::default().dispatch_filtered(&mut input, &keymap(), |_| true);
|
||||
assert_eq!(hits.iter().map(|hit| hit.command.id.as_str()).collect::<Vec<_>>(), ["edit.copy"]);
|
||||
assert!(input.events.is_empty());
|
||||
|
||||
input.events = vec![Event::Copy];
|
||||
assert!(Dispatcher::default().dispatch_filtered(&mut input, &keymap(), |_| false).is_empty());
|
||||
assert_eq!(input.events, [Event::Copy]);
|
||||
}
|
||||
}
|
||||
@@ -295,6 +295,9 @@ pub struct NewProject {
|
||||
/// Import settings > Import cameras: keep the cameras stored in the mesh file
|
||||
#[serde(default = "import_cameras_default")]
|
||||
pub import_cameras: bool,
|
||||
/// Import settings > Rebuild mesh UVs.
|
||||
#[serde(default)]
|
||||
pub rebuild_uvs: bool,
|
||||
/// Color management as chosen in the window (the project is always created as Legacy)
|
||||
#[serde(skip)]
|
||||
pub color_management: crate::project_form::ColorManagement,
|
||||
@@ -332,6 +335,7 @@ impl Default for NewProject {
|
||||
template: default_template(),
|
||||
normal_format: None,
|
||||
import_cameras: true,
|
||||
rebuild_uvs: false,
|
||||
color_management: crate::project_form::ColorManagement::Legacy,
|
||||
baked_maps: Vec::new(),
|
||||
}
|
||||
@@ -635,6 +639,9 @@ pub struct UiState {
|
||||
/// How the 3D view shows symmetry
|
||||
#[serde(default)]
|
||||
pub symmetry: crate::symmetry::SymmetryDisplay,
|
||||
/// The warp tool bar: the gizmo's mode and space, its size, and the steps its drags snap to
|
||||
#[serde(default)]
|
||||
pub warp_toolbar: crate::frame_gizmo::warp_toolbar::WarpToolbarSettings,
|
||||
/// The brush, symmetry and other tool settings of the last session, which the next one starts with
|
||||
#[serde(default)]
|
||||
pub tool_settings: texturecraft_engine::ToolSettings,
|
||||
@@ -742,6 +749,7 @@ impl UiState {
|
||||
self.nav_buttons = keep.nav_buttons;
|
||||
self.keymap = keep.keymap;
|
||||
self.tool_settings = keep.tool_settings;
|
||||
self.warp_toolbar = keep.warp_toolbar;
|
||||
self.named_layouts = keep.named_layouts;
|
||||
self.bake_presets = keep.bake_presets;
|
||||
self.layout_dialog = None;
|
||||
@@ -802,6 +810,7 @@ impl Default for UiState {
|
||||
keymap: Keymap::new(),
|
||||
bake_paint_brush: crate::bake_mode::BakePaintBrush::default(),
|
||||
symmetry: crate::symmetry::SymmetryDisplay::default(),
|
||||
warp_toolbar: crate::frame_gizmo::warp_toolbar::WarpToolbarSettings::default(),
|
||||
tool_settings: Default::default(),
|
||||
bake_visualization: crate::bake_mode::BakeVisualizationToggles::default(),
|
||||
named_layouts: Vec::new(),
|
||||
@@ -856,8 +865,12 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adopting_a_layout_keeps_recent_files_export_settings_and_shortcuts() {
|
||||
fn adopting_a_layout_keeps_recent_files_and_user_settings() {
|
||||
use crate::frame_gizmo::warp_toolbar::{GizmoMode, GizmoSpace, WarpToolbarSettings};
|
||||
|
||||
let warp_toolbar = WarpToolbarSettings { mode: GizmoMode::Rotate, space: GizmoSpace::World, manipulator_size: 0.4, grid_steps: 0.5, angle_steps: 30.0 };
|
||||
let mut ui = UiState { recent: vec!["a.tcraft".into()], ..UiState::default() };
|
||||
ui.warp_toolbar = warp_toolbar;
|
||||
ui.export.preset = "Mine".into();
|
||||
ui.keymap.insert("file.save".into(), "F5".into());
|
||||
let mut layout = UiState::default();
|
||||
@@ -869,6 +882,7 @@ mod tests {
|
||||
assert_eq!(ui.recent, vec!["a.tcraft".to_string()]);
|
||||
assert_eq!(ui.export.preset, "Mine");
|
||||
assert_eq!(ui.keymap.get("file.save").map(String::as_str), Some("F5"));
|
||||
assert_eq!(ui.warp_toolbar, warp_toolbar, "loading a layout keeps the user's warp settings");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -324,9 +324,21 @@ pub fn font_definitions() -> egui::FontDefinitions {
|
||||
fonts
|
||||
}
|
||||
|
||||
/// Gives the context `fonts` through the framework runtime, which keeps its layout memory in step with them. The
|
||||
/// framework's chrome (the dock, the update dialogs) also draws in the signature and semibold families: signature
|
||||
/// takes the proportional faces and semibold TextureCraft's own semibold list. A family left out draws missing-glyph
|
||||
/// boxes.
|
||||
pub fn load_fonts(ctx: &egui::Context, mut fonts: egui::FontDefinitions) {
|
||||
let proportional = fonts.families.get(&FontFamily::Proportional).cloned().unwrap_or_default();
|
||||
let semibold = fonts.families.get(&FontFamily::Name(SEMIBOLD.into())).cloned().unwrap_or_else(|| proportional.clone());
|
||||
fonts.families.insert(craft_ui::fonts::FontRef::signature().family(), proportional);
|
||||
fonts.families.insert(FontFamily::Name(craft_ui::fonts::SEMIBOLD.into()), semibold);
|
||||
craft_ui::fonts::load(ctx, fonts);
|
||||
}
|
||||
|
||||
/// Install the fonts (once, at startup; the app applies the style from its settings).
|
||||
pub fn install(ctx: &egui::Context) {
|
||||
ctx.set_fonts(font_definitions());
|
||||
load_fonts(ctx, font_definitions());
|
||||
}
|
||||
|
||||
/// Apply brightness `b` and `accent`: store the tokens for [`Tokens::get`] and style egui with
|
||||
@@ -371,8 +383,18 @@ pub fn apply(ctx: &egui::Context, b: Brightness, accent: Accent) {
|
||||
v.selection.stroke = Stroke::new(1.0, t.text_strong);
|
||||
v.hyperlink_color = t.accent;
|
||||
let w = &mut v.widgets;
|
||||
craft_ui::theme::WidgetPalette { noninteractive: t.panel, inactive: t.button, hovered: t.row_hover, active: t.tool_active, open: t.row_hover }
|
||||
.apply_to(w, t.cr(), Stroke::new(1.0, t.text));
|
||||
for (widget, fill) in [
|
||||
(&mut w.noninteractive, t.panel),
|
||||
(&mut w.inactive, t.button),
|
||||
(&mut w.hovered, t.row_hover),
|
||||
(&mut w.active, t.tool_active),
|
||||
(&mut w.open, t.row_hover),
|
||||
] {
|
||||
widget.bg_fill = fill;
|
||||
widget.weak_bg_fill = fill;
|
||||
widget.corner_radius = t.cr();
|
||||
widget.fg_stroke = Stroke::new(1.0, t.text);
|
||||
}
|
||||
|
||||
// Hovered and pressed lettering, and `RichText::strong` (captions), in the strong colour
|
||||
w.hovered.fg_stroke.color = t.text_strong;
|
||||
|
||||
+63
-156
@@ -1,8 +1,9 @@
|
||||
//! The strip at the top of the window: the app icon at the very left, the menus and the mode label,
|
||||
//! and the window's title bar unless the system draws one. As the title bar its empty space moves
|
||||
//! the window and follows the system's double-click setting (craft-window's `title_bar`), and on a
|
||||
//! window without an OS frame it also has the minimize, maximize/restore and close buttons and
|
||||
//! invisible resize zones along the window's edges.
|
||||
//! and the window's title bar unless the system draws one. As the title bar it is craft-ui's
|
||||
//! `shell::TitleBar`: its free area moves the window and follows the system's double-click
|
||||
//! setting, and on a window without an OS frame it has the caption buttons of the desktop's
|
||||
//! layout; the window keeps invisible resize zones along its edges where the runtime does not
|
||||
//! answer the window's hit test itself (everywhere but Windows).
|
||||
//!
|
||||
//! Who draws the frame is decided once at startup ([`TitleBar::decide`]): Windows draws no OS
|
||||
//! frame, macOS keeps its traffic lights over the strip (a full-size content view with a hidden
|
||||
@@ -11,12 +12,14 @@
|
||||
//! overrides that, and Settings › Interface › System title bar brings the OS frame back on the
|
||||
//! next start. The web build has no window frame: the strip is the menu bar.
|
||||
|
||||
use craft_window::{Button, Frame, Layout};
|
||||
use craft_ui::contract::ShowContainer as _;
|
||||
use craft_ui::runtime::windows::WindowHost;
|
||||
use craft_window::policy::{Decision, TitleBarPref};
|
||||
use craft_window::{Frame, Layout};
|
||||
use egui::emath::GuiRounding as _;
|
||||
use egui::{Align, Color32, CursorIcon, Id, LayerId, Order, PointerButton, Rect, ResizeDirection, Sense, Stroke, Ui, ViewportCommand, pos2, vec2};
|
||||
use egui::{Color32, CursorIcon, Id, LayerId, Order, PointerButton, Rect, ResizeDirection, Sense, Ui, ViewportCommand, pos2, vec2};
|
||||
|
||||
use crate::TextureCraftApp;
|
||||
use crate::i18n::tr;
|
||||
use crate::theme::Tokens;
|
||||
|
||||
/// Who draws the window's title bar.
|
||||
@@ -31,13 +34,9 @@ pub enum TitleBar {
|
||||
App(Layout),
|
||||
}
|
||||
|
||||
/// One caption button: as wide as Windows' own.
|
||||
pub const BUTTON_WIDTH: f32 = 46.0;
|
||||
/// The room at the strip's left for the macOS traffic lights (their width and the gaps around them).
|
||||
const TRAFFIC_LIGHTS: f32 = 78.0;
|
||||
/// The app icon's side, in points.
|
||||
const ICON: f32 = 16.0;
|
||||
/// The space between the strip's edges (or its caption buttons) and its content.
|
||||
/// The space between the icon and the menus.
|
||||
const PAD: f32 = 8.0;
|
||||
/// Resize zone thickness along an edge, and the side of a corner zone.
|
||||
const EDGE: f32 = 5.0;
|
||||
@@ -53,6 +52,9 @@ const ICONS: [(f32, &[u8]); 5] = [
|
||||
(64.0, include_bytes!("../../../assets/app-icon/hicolor/64x64/apps/ai.storyteller.texturecraft.png")),
|
||||
];
|
||||
|
||||
/// The override variable's prefix: `TEXTURECRAFT_TITLEBAR`.
|
||||
const PREFIX: craft_window::Prefix = craft_window::Prefix::new("TEXTURECRAFT");
|
||||
|
||||
/// The Nightly strip's icon PNGs, same sizes: the deeper background tells the two windows apart at
|
||||
/// a glance and matches the packaged Nightly icon.
|
||||
const NIGHTLY_ICONS: [(f32, &[u8]); 5] = [
|
||||
@@ -64,11 +66,24 @@ const NIGHTLY_ICONS: [(f32, &[u8]); 5] = [
|
||||
];
|
||||
|
||||
impl TitleBar {
|
||||
/// Decide who draws the title bar; call once at startup, before the window is created.
|
||||
/// Decide who draws the title bar; call once at startup, before the window is created, and
|
||||
/// hand the decision to the window ([`viewport`]) and the runtime (`framework::install`).
|
||||
/// `system` is Settings › Interface › System title bar.
|
||||
pub fn decide(system: bool) -> TitleBar {
|
||||
let choice = craft_window::Choice::probe(craft_window::Prefix::new("TEXTURECRAFT"));
|
||||
Self::from_choice(choice.frame(), choice.overridden(), system)
|
||||
pub fn decide(system: bool) -> Decision {
|
||||
let choice = craft_window::Choice::probe(PREFIX);
|
||||
let wanted = Self::from_choice(choice.frame(), choice.overridden(), system);
|
||||
let pref = if wanted == TitleBar::System { TitleBarPref::System } else { TitleBarPref::Integrated };
|
||||
craft_window::policy::decide_for(PREFIX, craft_host::target::Backend::from_env(), pref)
|
||||
}
|
||||
|
||||
/// The bar a decided `frame` gives.
|
||||
pub fn of(frame: &craft_window::policy::Frame) -> TitleBar {
|
||||
use craft_window::policy::Frame as Decided;
|
||||
match frame {
|
||||
Decided::Native => TitleBar::System,
|
||||
Decided::Inset(_) => TitleBar::Integrated,
|
||||
Decided::Integrated(captions) => TitleBar::App(captions.layout.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
/// `TEXTURECRAFT_TITLEBAR` (`overridden`) wins, then the System title bar setting. Otherwise
|
||||
@@ -87,17 +102,6 @@ impl TitleBar {
|
||||
}
|
||||
}
|
||||
|
||||
/// `builder` with this frame: decorations off for the app's own, and on macOS the content
|
||||
/// under a transparent title bar without its title.
|
||||
pub fn viewport(&self, builder: egui::ViewportBuilder) -> egui::ViewportBuilder {
|
||||
let frame = match self {
|
||||
TitleBar::App(layout) => Frame::App(layout.clone()),
|
||||
_ => Frame::Desktop,
|
||||
};
|
||||
let builder = craft_window::decorate(builder, &frame);
|
||||
if *self == TitleBar::Integrated { builder.with_fullsize_content_view(true).with_titlebar_shown(false).with_title_shown(false) } else { builder }
|
||||
}
|
||||
|
||||
/// The name `ui.inspect` reports: `app`, `integrated` or `system`.
|
||||
pub fn name(&self) -> &'static str {
|
||||
match self {
|
||||
@@ -108,38 +112,48 @@ impl TitleBar {
|
||||
}
|
||||
}
|
||||
|
||||
/// `builder` with the decided frame: decorations off for the app's own, and on macOS the content
|
||||
/// under a transparent title bar without its title.
|
||||
pub fn viewport(decision: &Decision, builder: egui::ViewportBuilder) -> egui::ViewportBuilder {
|
||||
craft_window::policy::apply(builder, &decision.frame)
|
||||
}
|
||||
|
||||
/// The strip's height: the body text with room around it, 28 to 32 points (so the macOS traffic
|
||||
/// lights and Windows-sized caption buttons fit it).
|
||||
pub fn height(ui: &Ui) -> f32 {
|
||||
(ui.text_style_height(&egui::TextStyle::Body) + 14.0).clamp(28.0, 32.0)
|
||||
}
|
||||
|
||||
/// The strip: menus between the app icon and the mode label, the window buttons at the ends the
|
||||
/// layout names, and as the title bar its empty space moving the window.
|
||||
/// The strip: the app icon, then the menus. Where the system draws the frame it is the menu bar;
|
||||
/// otherwise it is the window's title bar (craft-ui's), with the caption buttons where the frame
|
||||
/// has them and resize zones along the window's edges.
|
||||
pub fn show(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
let bar = app.title_bar.clone();
|
||||
let (left, right) = match &bar {
|
||||
TitleBar::App(layout) => (layout.left.as_slice(), layout.right.as_slice()),
|
||||
_ => (&[][..], &[][..]),
|
||||
};
|
||||
egui::Panel::top("menu_bar").exact_size(height(ui)).show_separator_line(false).frame(egui::Frame::NONE.fill(tk.chrome)).show(ui, |ui| {
|
||||
let rect = ui.max_rect();
|
||||
// First, so the strip's controls drawn over it keep their own clicks.
|
||||
if bar != TitleBar::System {
|
||||
craft_window::title_bar::empty_area(ui, rect);
|
||||
}
|
||||
let ends = |n: usize| n as f32 * BUTTON_WIDTH;
|
||||
let inset = if bar == TitleBar::Integrated { TRAFFIC_LIGHTS } else { ends(left.len()) + PAD };
|
||||
let content = Rect::from_min_max(pos2(rect.left() + inset, rect.top()), pos2(rect.right() - ends(right.len()) - PAD, rect.bottom()));
|
||||
ui.scope_builder(egui::UiBuilder::new().max_rect(content).layout(egui::Layout::left_to_right(Align::Center)), |ui| {
|
||||
paint_icon(ui);
|
||||
crate::menus::menu_bar(app, ui);
|
||||
let frame = WindowHost::of(ui.ctx()).frame();
|
||||
if matches!(frame, craft_window::policy::Frame::Native) {
|
||||
egui::Panel::top("menu_bar").exact_size(height(ui)).show_separator_line(false).frame(egui::Frame::NONE.fill(tk.chrome)).show(ui, |ui| {
|
||||
let rect = ui.max_rect();
|
||||
let content = Rect::from_min_max(pos2(rect.left() + PAD, rect.top()), pos2(rect.right() - PAD, rect.bottom()));
|
||||
ui.scope_builder(egui::UiBuilder::new().max_rect(content).layout(egui::Layout::left_to_right(egui::Align::Center)), |ui| {
|
||||
paint_icon(ui);
|
||||
crate::menus::menu_bar(app, ui);
|
||||
});
|
||||
});
|
||||
caption_buttons(ui, left, rect.left(), rect);
|
||||
caption_buttons(ui, right, rect.right() - ends(right.len()), rect);
|
||||
return;
|
||||
}
|
||||
egui::Panel::top("menu_bar").show_separator_line(false).frame(egui::Frame::NONE.fill(tk.chrome)).show(ui, |ui| {
|
||||
let bar = craft_ui::shell::TitleBar::new()
|
||||
.show(ui, |ui, _| {
|
||||
paint_icon(ui);
|
||||
crate::menus::menu_bar(app, ui);
|
||||
})
|
||||
.output;
|
||||
if bar.close_requested {
|
||||
ui.ctx().send_viewport_cmd(ViewportCommand::Close);
|
||||
}
|
||||
});
|
||||
if matches!(bar, TitleBar::App(_)) {
|
||||
// Windows' frame answers the resize edges itself (the runtime's hit test).
|
||||
if matches!(frame, craft_window::policy::Frame::Integrated(_)) && !cfg!(windows) {
|
||||
resize_zones(ui);
|
||||
}
|
||||
}
|
||||
@@ -177,92 +191,6 @@ fn maximized(ctx: &egui::Context) -> bool {
|
||||
ctx.input(|i| i.viewport().maximized.unwrap_or(false))
|
||||
}
|
||||
|
||||
/// Caption button ids (stable, so tests and agents can find them).
|
||||
fn caption_id(b: Button) -> Id {
|
||||
Id::unique(("titlebar_caption", b as u8))
|
||||
}
|
||||
|
||||
/// `buttons` from `x` rightwards, the strip's full height, flush with its top so a maximized
|
||||
/// window's corner hits the outermost one.
|
||||
fn caption_buttons(ui: &mut Ui, buttons: &[Button], x: f32, bar: Rect) {
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
let max = maximized(ui.ctx());
|
||||
let focused = ui.input(|i| i.viewport().focused.unwrap_or(true));
|
||||
for (i, &b) in buttons.iter().enumerate() {
|
||||
let r = Rect::from_min_size(pos2(x + i as f32 * BUTTON_WIDTH, bar.top()), vec2(BUTTON_WIDTH, bar.height()));
|
||||
let resp = ui.interact(r, caption_id(b), Sense::click());
|
||||
let tip = match b {
|
||||
Button::Minimize => tr("Minimize"),
|
||||
Button::Maximize if max => tr("Restore"),
|
||||
Button::Maximize => tr("Maximize"),
|
||||
Button::Close => tr("Close"),
|
||||
};
|
||||
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tip));
|
||||
let close = b == Button::Close;
|
||||
let fill = match (resp.is_pointer_button_down_on(), resp.hovered()) {
|
||||
(true, _) if close => tk.danger.gamma_multiply(0.8),
|
||||
(_, true) if close => tk.danger,
|
||||
(true, _) => tk.button,
|
||||
(_, true) => tk.row_hover,
|
||||
_ => Color32::TRANSPARENT,
|
||||
};
|
||||
ui.painter().rect_filled(r, 0.0, fill);
|
||||
// White on the red, as every system's close button; dimmed while the window is inactive.
|
||||
let ink = if close && resp.hovered() {
|
||||
Color32::WHITE
|
||||
} else if focused {
|
||||
tk.text
|
||||
} else {
|
||||
tk.text_dim
|
||||
};
|
||||
paint_glyph(ui, b, max, r.center(), ink);
|
||||
if resp.on_hover_text(tip).clicked() {
|
||||
ui.ctx().send_viewport_cmd(match b {
|
||||
Button::Minimize => ViewportCommand::Minimized(true),
|
||||
Button::Maximize => ViewportCommand::Maximized(!max),
|
||||
// The same request as the system's close button.
|
||||
Button::Close => ViewportCommand::Close,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The 10-point line glyphs, one physical pixel wide per whole step of the screen's scale and on
|
||||
/// pixel centres, so they stay crisp at any scale.
|
||||
fn paint_glyph(ui: &Ui, b: Button, maximized: bool, at: egui::Pos2, ink: Color32) {
|
||||
let ppp = ui.ctx().pixels_per_point();
|
||||
let px = ppp.round().max(1.0);
|
||||
let stroke = Stroke::new(px / ppp, ink);
|
||||
// An odd width centres the line in a pixel, an even one on a pixel edge.
|
||||
let snap = |v: f32| if px as u32 % 2 == 1 { v.round_to_pixel_center(ppp) } else { v.round_to_pixels(ppp) };
|
||||
let g = Rect::from_min_max(pos2(snap(at.x - 5.0), snap(at.y - 5.0)), pos2(snap(at.x + 5.0), snap(at.y + 5.0)));
|
||||
let p = ui.painter();
|
||||
match b {
|
||||
Button::Minimize => {
|
||||
p.line_segment([g.left_center(), g.right_center()].map(|q| pos2(q.x, snap(q.y))), stroke);
|
||||
}
|
||||
// Restore: a front square with the corner of the one behind it.
|
||||
Button::Maximize if maximized => {
|
||||
let front = Rect::from_min_max(pos2(g.left(), snap(g.top() + 2.0)), pos2(snap(g.right() - 2.0), g.bottom()));
|
||||
p.rect_stroke(front, 0.0, stroke, egui::StrokeKind::Middle);
|
||||
let (l, t) = (snap(g.left() + 2.0), front.top());
|
||||
p.line(
|
||||
vec![pos2(l, t), pos2(l, g.top()), g.right_top(), pos2(g.right(), snap(g.bottom() - 2.0)), pos2(front.right(), snap(g.bottom() - 2.0))],
|
||||
stroke,
|
||||
);
|
||||
}
|
||||
Button::Maximize => {
|
||||
p.rect_stroke(g, 0.0, stroke, egui::StrokeKind::Middle);
|
||||
}
|
||||
Button::Close => {
|
||||
p.line_segment([g.left_top(), g.right_bottom()], stroke);
|
||||
p.line_segment([g.right_top(), g.left_bottom()], stroke);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The edge and corner zones of a window with content rect `w`: (zone, direction, cursor). Corners
|
||||
/// come last so they win where they overlap the edges.
|
||||
fn zones(w: Rect) -> [(Rect, ResizeDirection, CursorIcon); 8] {
|
||||
use ResizeDirection::*;
|
||||
let (e, c) = (EDGE, CORNER);
|
||||
@@ -303,17 +231,6 @@ fn resize_zones(ui: &mut Ui) {
|
||||
/// Once per frame after the UI, on macOS with the integrated strip: the traffic lights centred on
|
||||
/// the strip, inset from its left as far as from its top, and AppKit's `movable` flag following
|
||||
/// what is under the pointer (`movable` keeps the value last set).
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn sync_native(bar: &TitleBar, ui: &Ui, frame: &eframe::Frame, movable: &mut Option<bool>) {
|
||||
if *bar != TitleBar::Integrated {
|
||||
return;
|
||||
}
|
||||
let h = height(ui);
|
||||
// AppKit's buttons are 14 points tall.
|
||||
frame.set_traffic_lights_position(ui.ctx(), egui::Rangef::new(0.0, h), (h - 14.0) / 2.0);
|
||||
craft_window::title_bar::sync_movable(ui.ctx(), movable);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -342,16 +259,6 @@ mod tests {
|
||||
assert_eq!(desktop, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_app_frame_turns_decorations_off() {
|
||||
let b = TitleBar::App(Layout::default()).viewport(egui::ViewportBuilder::default());
|
||||
assert_eq!(b.decorations, Some(false));
|
||||
let b = TitleBar::Integrated.viewport(egui::ViewportBuilder::default());
|
||||
assert_eq!((b.decorations, b.fullsize_content_view, b.title_shown), (Some(true), Some(true), Some(false)));
|
||||
let b = TitleBar::System.viewport(egui::ViewportBuilder::default());
|
||||
assert_eq!((b.decorations, b.fullsize_content_view), (Some(true), None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resize_corners_win_over_edges() {
|
||||
let w = Rect::from_min_size(pos2(0.0, 0.0), vec2(1000.0, 600.0));
|
||||
|
||||
@@ -7,6 +7,7 @@ use texturecraft_engine::Tool;
|
||||
|
||||
use crate::TextureCraftApp;
|
||||
use crate::drawn_icon::DrawnIcon;
|
||||
use crate::frame_gizmo::warp_toolbar::{self, WarpTarget};
|
||||
use crate::i18n::{tr, trf};
|
||||
use crate::keymap::{shortcut_of, tip};
|
||||
use crate::state::{Mode, ViewLayout};
|
||||
@@ -58,16 +59,18 @@ pub fn paint_bar(app: &mut TextureCraftApp, ui: &mut egui::Ui) {
|
||||
return;
|
||||
}
|
||||
|
||||
let warp_target = WarpTarget::of(app);
|
||||
let tool_usable = warp_target.is_none() && app.session.tool_usable(app.session.tool.tool);
|
||||
ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH));
|
||||
if !scroll_views {
|
||||
view_buttons(app, ui);
|
||||
if app.session.tool_usable(app.session.tool.tool) {
|
||||
if warp_target.is_some() || tool_usable {
|
||||
ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH));
|
||||
}
|
||||
}
|
||||
|
||||
ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| {
|
||||
scrolling_tool_controls(app, ui, &tokens, scroll_views);
|
||||
scrolling_tool_controls(app, ui, &tokens, scroll_views, warp_target, tool_usable);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -175,7 +178,7 @@ fn rotation_dropdown(app: &mut TextureCraftApp, ui: &mut egui::Ui) {
|
||||
}
|
||||
|
||||
/// An icon button with a caret that opens `menu` below it, highlighted while open
|
||||
fn icon_dropdown(ui: &mut egui::Ui, id_salt: &str, icon: &str, tooltip: &str, menu: impl FnOnce(&mut egui::Ui)) {
|
||||
pub(crate) fn icon_dropdown(ui: &mut egui::Ui, id_salt: &str, icon: &str, tooltip: &str, menu: impl FnOnce(&mut egui::Ui)) {
|
||||
let button_size = ui.spacing().interact_size.y;
|
||||
let popup_id = ui.make_persistent_id(id_salt);
|
||||
let open = egui::Popup::is_id_open(ui.ctx(), popup_id);
|
||||
@@ -198,7 +201,14 @@ fn dropdown_row(ui: &mut egui::Ui, icon: &str, label: &str, shortcut: Option<&st
|
||||
}
|
||||
|
||||
/// Scroll tool controls and, in narrow viewports, the view buttons
|
||||
fn scrolling_tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens, scroll_views: bool) {
|
||||
fn scrolling_tool_controls(
|
||||
app: &mut TextureCraftApp,
|
||||
ui: &mut egui::Ui,
|
||||
tokens: &Tokens,
|
||||
scroll_views: bool,
|
||||
warp_target: Option<WarpTarget>,
|
||||
tool_usable: bool,
|
||||
) {
|
||||
let button_size = ui.spacing().interact_size.y;
|
||||
let strip_width = ui.available_width();
|
||||
let overflow_id = egui::Id::unique("tool_controls_overflow");
|
||||
@@ -224,13 +234,14 @@ fn scrolling_tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens:
|
||||
scroll_area.show(ui, |ui| {
|
||||
ui.scroll_with_delta(vec2(scroll_delta, 0.0));
|
||||
ui.horizontal_centered(|ui| {
|
||||
// A tool that can't act on the selection leaves the bar, as the shelf greys it
|
||||
let tool_usable = app.session.tool_usable(app.session.tool.tool);
|
||||
if tool_usable {
|
||||
if let Some(target) = warp_target {
|
||||
warp_toolbar::controls(app, ui, target);
|
||||
} else if tool_usable {
|
||||
tool_controls(app, ui, tokens);
|
||||
}
|
||||
|
||||
if scroll_views {
|
||||
if tool_usable {
|
||||
if warp_target.is_some() || tool_usable {
|
||||
ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH));
|
||||
}
|
||||
let size = vec2(view_buttons_width(button_size, ui.spacing().item_spacing.x), ui.available_height());
|
||||
|
||||
@@ -300,7 +300,7 @@ pub(crate) mod tests {
|
||||
use super::memory_storage::MemoryStorage;
|
||||
use super::*;
|
||||
use crate::docking::{Dock, Panel, default_workspace, permissions};
|
||||
use craft_ui::docking::{Action, Placement};
|
||||
use craft_behavior::dock::{Action, DockPlacement};
|
||||
|
||||
/// Save `ui` and load it back, as closing and reopening the app does
|
||||
pub(crate) fn restart(ui: &UiState) -> UiState {
|
||||
@@ -321,10 +321,10 @@ pub(crate) mod tests {
|
||||
fn moved_panels() -> Dock {
|
||||
let mut workspace = default_workspace();
|
||||
let actions = [
|
||||
Action::Move { panel: Panel::Layers, anchor: Panel::Assets, placement: Placement::Tab { before: None } },
|
||||
Action::Float { panel: Panel::Properties, rect: [900.0, 120.0, 320.0, 400.0] },
|
||||
Action::move_beside(Panel::Layers, Panel::Assets, DockPlacement::tab(None)),
|
||||
Action::float(Panel::Properties, egui::Rect::from_min_size(egui::pos2(900.0, 120.0), egui::vec2(320.0, 400.0))),
|
||||
];
|
||||
workspace.apply_all(actions, permissions).unwrap();
|
||||
workspace.apply_all(actions, false, permissions).unwrap();
|
||||
|
||||
let dock = Dock::from_value(serde_json::to_value(&workspace).unwrap());
|
||||
assert!(!dock.replaced_unreadable(), "the moved layout is valid");
|
||||
@@ -385,13 +385,14 @@ pub(crate) mod tests {
|
||||
let mut storage = MemoryStorage::default();
|
||||
UiStateStore::new(Some(file.clone())).save(&ui, &mut storage);
|
||||
let saved = std::fs::read_to_string(&file).unwrap();
|
||||
assert!(saved.contains("\"Assets\"") && saved.contains("\"version\": 2"), "{saved}");
|
||||
let version = format!("\"version\": {}", crate::docking::Workspace::VERSION);
|
||||
assert!(saved.contains("\"Assets\"") && saved.contains(&version), "{saved}");
|
||||
|
||||
let unreadable = [
|
||||
// A panel this build does not know
|
||||
saved.replacen("\"Assets\"", "\"Bogus\"", 1),
|
||||
// A layout from a newer format
|
||||
saved.replacen("\"version\": 2", "\"version\": 99", 1),
|
||||
saved.replacen(&version, "\"version\": 99", 1),
|
||||
// Not a saved state
|
||||
"not json".to_owned(),
|
||||
];
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
//! Software updates on the desktop: the check at start, Help > Check for Updates and the update
|
||||
//! prompt. An update that is ready starts its install helper when the app is dropped at exit.
|
||||
//! prompt, as craft-update's dialogs on the app's [`DialogHost`](craft_ui::dialog::DialogHost). An
|
||||
//! update that is ready starts its install helper when the app is dropped at exit.
|
||||
|
||||
use craft_ui::dialog::DialogResult;
|
||||
use craft_update::stack_dialogs::{CheckChoice, UpdateCheckDialog};
|
||||
use craft_update::updater::{Action, Status, Updater};
|
||||
use craft_update::{CheckResultDialog, CheckResultResponse};
|
||||
|
||||
use crate::TextureCraftApp;
|
||||
|
||||
@@ -57,9 +59,9 @@ pub(crate) fn tick(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
}
|
||||
let rt = &mut app.updates_rt;
|
||||
if std::mem::take(&mut rt.check_requested) {
|
||||
rt.updater.check_now(ctx);
|
||||
rt.updater.check_now();
|
||||
} else if rt.startup_check {
|
||||
rt.updater.check_at_start(ctx);
|
||||
rt.updater.check_at_start();
|
||||
}
|
||||
rt.updater.tick(ctx);
|
||||
}
|
||||
@@ -77,21 +79,44 @@ fn safe_to_close(app: &TextureCraftApp) -> bool {
|
||||
!app.session.modified && !app.session.stroke_active() && app.bake.is_none() && app.resize.is_none() && app.high_poly_job.is_none()
|
||||
}
|
||||
|
||||
/// One pass of the update flow, before the dialog host runs: answers the result dialog closed in
|
||||
/// the last pass, drives the update prompt, and keeps the result dialog open and current while the
|
||||
/// updater has something to report.
|
||||
pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
let safe = safe_to_close(app);
|
||||
match app.updates_rt.updater.show_if(ctx, safe) {
|
||||
// Answered before the dialog is kept open below, so a dismissed outcome does not open again at once
|
||||
match app.framework_dialogs.take::<UpdateCheckDialog>() {
|
||||
Some(DialogResult::Ok(CheckChoice::CheckNow | CheckChoice::CheckAgain)) => app.updates_rt.check_requested = true,
|
||||
// The next `run` asks the window to close once it is safe to
|
||||
Some(DialogResult::Ok(CheckChoice::RestartToUpdate)) => app.updates_rt.updater.restart_to_update(),
|
||||
Some(DialogResult::Ok(CheckChoice::Update)) => {
|
||||
app.updates_rt.updater.request_install(safe);
|
||||
}
|
||||
Some(DialogResult::Ok(CheckChoice::Download)) => ctx.open_url(egui::OpenUrl::new_tab(crate::UPDATE_APP.releases_url())),
|
||||
// Closing the dialog dismisses the outcome it showed
|
||||
Some(_) => app.updates_rt.updater.dismiss_status(),
|
||||
None => {}
|
||||
}
|
||||
match app.updates_rt.updater.run(&mut app.framework_dialogs, safe) {
|
||||
Action::OpenUrl(url) => ctx.open_url(egui::OpenUrl::new_tab(url)),
|
||||
Action::Close => ctx.send_viewport_cmd(egui::ViewportCommand::Close),
|
||||
Action::None => {}
|
||||
_ => {}
|
||||
}
|
||||
let rt = &mut app.updates_rt;
|
||||
if result_window_shows(rt.updater.status(), rt.updater.prompt_open()) {
|
||||
match CheckResultDialog::new(&crate::UPDATE_APP, env!("CARGO_PKG_VERSION")).show(ctx, rt.updater.status()) {
|
||||
CheckResultResponse::None => {}
|
||||
CheckResultResponse::Close => rt.updater.dismiss_status(),
|
||||
CheckResultResponse::CheckAgain => rt.check_requested = true,
|
||||
CheckResultResponse::RestartToUpdate => rt.updater.restart_to_update(),
|
||||
}
|
||||
let updater = &app.updates_rt.updater;
|
||||
let shows = result_window_shows(updater.status(), updater.prompt_open());
|
||||
let (status, installing, message) = (updater.status().clone(), updater.is_installing(), updater.status_message());
|
||||
let dialogs = &mut app.framework_dialogs;
|
||||
if shows && !dialogs.is_open::<UpdateCheckDialog>() {
|
||||
dialogs.open(UpdateCheckDialog::new(env!("CARGO_PKG_VERSION")));
|
||||
} else if !shows && dialogs.is_open::<UpdateCheckDialog>() {
|
||||
dialogs.cancel::<UpdateCheckDialog>(ctx);
|
||||
// Hidden for the prompt, not dismissed: the outcome shows again after it
|
||||
let _ = dialogs.take::<UpdateCheckDialog>();
|
||||
}
|
||||
if let Some(dialog) = dialogs.get_mut::<UpdateCheckDialog>() {
|
||||
dialog.set_status(status);
|
||||
dialog.set_installing(installing);
|
||||
dialog.set_message(message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -133,7 +158,10 @@ mod tests {
|
||||
let root = std::env::temp_dir().join(format!("texturecraft-updates-{}-{test}", std::process::id()));
|
||||
let mut session = texturecraft_engine::sample_session(256, 64).unwrap();
|
||||
session.modified = modified;
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
|
||||
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));
|
||||
h.state_mut().updates_rt.updater =
|
||||
Updater::new(&crate::UPDATE_APP, "0.0.1").with_source(ask).with_paths(Paths::under(&root)).with_pins_path(root.join("pins.json"));
|
||||
h.run_steps(2);
|
||||
@@ -149,6 +177,13 @@ mod tests {
|
||||
..Default::default()
|
||||
};
|
||||
h.state_mut().updates_rt.updater.offer(release);
|
||||
// The offer reads on a thread whether this copy can install the release itself; a later frame's tick opens
|
||||
// the prompt.
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
|
||||
while !h.state().updates_rt.updater.prompt_open() && std::time::Instant::now() < deadline {
|
||||
h.run_steps(1);
|
||||
std::thread::sleep(std::time::Duration::from_millis(2));
|
||||
}
|
||||
h.run_steps(2);
|
||||
}
|
||||
|
||||
@@ -187,7 +222,7 @@ mod tests {
|
||||
let mut h = harness(false, "prompt", ask);
|
||||
offer(&mut h);
|
||||
assert!(h.state().updates_rt.updater.prompt_open());
|
||||
h.get_by_label("LATER").click();
|
||||
h.get_by_label("Later").click();
|
||||
h.run_steps(2);
|
||||
assert!(!h.state().updates_rt.updater.prompt_open());
|
||||
}
|
||||
@@ -203,7 +238,7 @@ mod tests {
|
||||
h.key_press(egui::Key::F8);
|
||||
h.step();
|
||||
assert_eq!(h.state().ui.mode, Mode::Painting, "the prompt holds the keyboard");
|
||||
h.get_by_label("LATER").click();
|
||||
h.get_by_label("Later").click();
|
||||
h.run_steps(2);
|
||||
assert!(!crate::docking::input_blocked(h.state(), &h.ctx));
|
||||
h.key_press(egui::Key::F8);
|
||||
@@ -226,7 +261,7 @@ mod tests {
|
||||
h.key_press(egui::Key::Backspace);
|
||||
h.step();
|
||||
assert_eq!(points(&h), 2, "the prompt holds the keyboard");
|
||||
h.get_by_label("LATER").click();
|
||||
h.get_by_label("Later").click();
|
||||
h.run_steps(2);
|
||||
h.key_press(egui::Key::Backspace);
|
||||
h.step();
|
||||
|
||||
+114
-15
@@ -60,6 +60,24 @@ fn aux_view(app: &TextureCraftApp) -> Option<crate::gpu::AuxView> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The 3D view's widget: the same in the dock and with the UI hidden, so it keeps the focus when Tab hides the UI
|
||||
pub fn view_3d_id() -> egui::Id {
|
||||
egui::Id::unique("texturecraft-view3d")
|
||||
}
|
||||
|
||||
/// The 2D view's widget, as [`view_3d_id`]
|
||||
pub fn view_2d_id() -> egui::Id {
|
||||
egui::Id::unique("texturecraft-view2d")
|
||||
}
|
||||
|
||||
/// Draw the widget of a view and declare it as a document canvas of the window. In a split view both are, so the keys
|
||||
/// are the same in either.
|
||||
fn view_widget(ui: &Ui, rect: Rect, id: egui::Id, sense: Sense) -> egui::Response {
|
||||
let response = ui.interact(rect, id, sense);
|
||||
crate::framework::host_canvas(ui.ctx(), id);
|
||||
response
|
||||
}
|
||||
|
||||
/// The viewport dock tab: the paint bar, then the 3D and 2D views in the chosen layout with the mode's overlays
|
||||
pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
let mode = app.ui.mode;
|
||||
@@ -183,6 +201,8 @@ fn empty_views(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
};
|
||||
|
||||
for (rect, id) in regions {
|
||||
// Nothing to click or drag, but still the window's canvas: Tab hides and shows the UI
|
||||
view_widget(ui, rect, if id == "v2d" { view_2d_id() } else { view_3d_id() }, Sense::focusable_noninteractive());
|
||||
ui.painter().rect_filled(rect, 0.0, tokens.viewport);
|
||||
view_header(app, ui, rect, id);
|
||||
}
|
||||
@@ -381,9 +401,14 @@ fn shade(app: &TextureCraftApp) -> Shade {
|
||||
/// The texture set a shelf material or image dragged over the 3D view `response` would drop on, its edges drawn in the accent color
|
||||
fn drop_highlight(app: &TextureCraftApp, ui: &Ui, response: &egui::Response) -> Option<SetHighlight> {
|
||||
let set = crate::shelf::drop_set(app, ui, response)?;
|
||||
|
||||
Some(set_highlight(ui, set))
|
||||
}
|
||||
|
||||
fn set_highlight(ui: &Ui, texture_set: usize) -> SetHighlight {
|
||||
let accent = egui::Rgba::from(Tokens::get(ui.ctx()).viewport_accent);
|
||||
|
||||
Some(SetHighlight { set, color: [accent.r(), accent.g(), accent.b()] })
|
||||
SetHighlight { set: texture_set, color: [accent.r(), accent.g(), accent.b()] }
|
||||
}
|
||||
|
||||
/// Show what the GPU side reported (each message once while its toast is up).
|
||||
@@ -450,7 +475,15 @@ fn frame_size_in_pixels(ui: &Ui, rect: Rect) -> [u32; 2] {
|
||||
[pixels(rect.left(), rect.right()), pixels(rect.top(), rect.bottom())]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
const TEST_SCENE_SET_HOVER: &str = "scene_frame_set_hover";
|
||||
|
||||
fn add_callback(app: &mut TextureCraftApp, ui: &Ui, rect: Rect, mut frame: Frame, sync: &mut PendingSync) {
|
||||
#[cfg(test)]
|
||||
if frame.view_id == VIEW_3D {
|
||||
ui.data_mut(|data| data.insert_temp(egui::Id::unique(TEST_SCENE_SET_HOVER), frame.shade.set_hover.map(|highlight| highlight.set)));
|
||||
}
|
||||
|
||||
let tokens = Tokens::get(ui.ctx());
|
||||
let bake = bake_visualization(app);
|
||||
frame.shade.bake = bake;
|
||||
@@ -732,7 +765,7 @@ pub(crate) fn orbit(app: &mut TextureCraftApp, delta: egui::Vec2) {
|
||||
}
|
||||
|
||||
fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut PendingSync) {
|
||||
let response = ui.interact(rect, ui.scope_id().with("view3d"), Sense::click_and_drag());
|
||||
let response = view_widget(ui, rect, view_3d_id(), Sense::click_and_drag());
|
||||
app.viewport_rect = rect;
|
||||
let size = rect.size();
|
||||
app.session.viewport = Vec2::new(size.x.max(MIN_CAMERA_VIEWPORT), size.y.max(MIN_CAMERA_VIEWPORT));
|
||||
@@ -747,7 +780,8 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
|
||||
|
||||
// Navigation; S + drag moves the projection stencil instead, below
|
||||
let delta = ui.input(|input| input.pointer.delta());
|
||||
let s_held = app.ui.mode == crate::state::Mode::Painting && ui.input(|input| input.key_down(STENCIL_KEY)) && !ui.ctx().egui_wants_keyboard_input();
|
||||
let s_held =
|
||||
app.ui.mode == crate::state::Mode::Painting && ui.input(|input| input.key_down(STENCIL_KEY)) && !crate::framework::widget_has_keyboard(ui.ctx());
|
||||
|
||||
// Only an equipped Projection tool that can act moves its stencil: it isn't drawn otherwise
|
||||
let stencil_moves = tool_acts(app) && app.session.tool.tool == Tool::Projection;
|
||||
@@ -1044,12 +1078,16 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
|
||||
}
|
||||
}
|
||||
|
||||
let set_hover = app
|
||||
.hovered_texture_set
|
||||
.filter(|&(project_id, _)| project_id == app.session.project_id && !app.ui.hide_ui && !crate::docking::input_blocked(app, ui.ctx()))
|
||||
.map(|(_, texture_set)| set_highlight(ui, texture_set));
|
||||
let frame = Frame {
|
||||
view_id: crate::viewport::VIEW_3D,
|
||||
size: frame_size_in_pixels(ui, rect),
|
||||
kind: ViewKind::Scene,
|
||||
camera: app.session.camera,
|
||||
shade: Shade { highlight: drop_highlight(app, ui, &response), ..shade(app) },
|
||||
shade: Shade { highlight: drop_highlight(app, ui, &response), set_hover, ..shade(app) },
|
||||
visible: app.session.doc.project.texture_sets.iter().map(|texture_set| texture_set.visible).collect(),
|
||||
overlay: crate::symmetry::scene_overlay(app, ui, rect),
|
||||
};
|
||||
@@ -1229,7 +1267,7 @@ fn path_keys(app: &mut TextureCraftApp, ui: &Ui) {
|
||||
return;
|
||||
}
|
||||
|
||||
if !tool_acts(app) || app.session.tool.tool != Tool::Path || app.session.tool.path.points.is_empty() || ui.ctx().egui_wants_keyboard_input() {
|
||||
if !tool_acts(app) || app.session.tool.tool != Tool::Path || app.session.tool.path.points.is_empty() || crate::framework::widget_has_keyboard(ui.ctx()) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1706,7 +1744,10 @@ fn uv_fill_box_corners(view: crate::uv_view_map::UvViewMap, [origin, opposite]:
|
||||
|
||||
/// V held with the Clone tool in painting mode: clicks set the clone source
|
||||
fn clone_source_key(app: &TextureCraftApp, ui: &Ui) -> bool {
|
||||
tool_acts(app) && app.session.tool.tool == Tool::Clone && ui.input(|input| input.key_down(CLONE_SOURCE_KEY)) && !ui.ctx().egui_wants_keyboard_input()
|
||||
tool_acts(app)
|
||||
&& app.session.tool.tool == Tool::Clone
|
||||
&& ui.input(|input| input.key_down(CLONE_SOURCE_KEY))
|
||||
&& !crate::framework::widget_has_keyboard(ui.ctx())
|
||||
}
|
||||
|
||||
/// Crosshair where the Clone tool reads from.
|
||||
@@ -2089,7 +2130,7 @@ fn framed_tile_view(set: &texturecraft_engine::core::TextureSet, size: egui::Vec
|
||||
/// The 2D (UV) view: navigation, painting in texture coordinates and the overlays drawn over the texture.
|
||||
fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut PendingSync) {
|
||||
let tokens = Tokens::get(ui.ctx());
|
||||
let response = ui.interact(rect, ui.scope_id().with("view2d"), Sense::click_and_drag());
|
||||
let response = view_widget(ui, rect, view_2d_id(), Sense::click_and_drag());
|
||||
let size = rect.size();
|
||||
let (alt, shift, snap) = ui.input(|input| (input.modifiers.alt, input.modifiers.shift, input.modifiers.shift && input.modifiers.command));
|
||||
let ctrl = ui.input(|input| input.modifiers.ctrl);
|
||||
@@ -2519,6 +2560,49 @@ fn eyedrop(app: &mut TextureCraftApp, ctx: &egui::Context, bar: egui::Id, pixel:
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn hovering_a_texture_set_row_previews_it_without_selecting_it() {
|
||||
use crate::state::Mode;
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::Queryable;
|
||||
|
||||
// App creation and frames both set the shared UI language
|
||||
let _language_guard = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
|
||||
let session =
|
||||
Session::new_project("Texture set hover", texturecraft_engine::geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
|
||||
let hovered_set = 1;
|
||||
let name = session.doc.project.texture_sets[hovered_set].name.clone();
|
||||
let selected_set = session.ts();
|
||||
assert_ne!(hovered_set, selected_set);
|
||||
|
||||
let mut harness = Harness::builder()
|
||||
.with_size(egui::vec2(1600.0, 1500.0))
|
||||
.with_context_setup(crate::framework::install_headless)
|
||||
.build_eframe(|context| TextureCraftApp::new(context, session));
|
||||
let preview = |harness: &Harness<'_, TextureCraftApp>| {
|
||||
harness.ctx.data(|data| data.get_temp::<Option<usize>>(egui::Id::unique(TEST_SCENE_SET_HOVER))).expect("the 3D view submitted a scene frame")
|
||||
};
|
||||
|
||||
for mode in [Mode::Painting, Mode::Baking] {
|
||||
harness.state_mut().ui.mode = mode;
|
||||
harness.run_steps(4);
|
||||
assert_eq!(preview(&harness), None, "{mode:?}: the preview starts clear");
|
||||
|
||||
harness.get_by_label(&name).hover();
|
||||
harness.run_steps(3);
|
||||
assert_eq!(preview(&harness), Some(hovered_set), "{mode:?}: the hovered set reaches the viewport");
|
||||
assert_eq!(harness.state().session.ts(), selected_set, "{mode:?}: hover keeps the selected set");
|
||||
|
||||
let away = harness.state().viewport_rect.center();
|
||||
harness.event(egui::Event::PointerMoved(away));
|
||||
harness.run_steps(3);
|
||||
assert_eq!(preview(&harness), None, "{mode:?}: leaving the row clears the preview");
|
||||
assert_eq!(harness.state().session.ts(), selected_set, "{mode:?}: leaving the row keeps the selected set");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_hover_label_finds_the_tile_under_the_cursor_in_a_turned_view() {
|
||||
let session = Session::new_project("Tiles", texturecraft_engine::geom::primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap();
|
||||
@@ -2632,7 +2716,9 @@ mod tests {
|
||||
|
||||
for tool in [Tool::Paint, Tool::PolygonFill] {
|
||||
let session = Session::new_project("t", primitives::plane(2.0, 4), "test", None, 128).unwrap();
|
||||
let mut harness = egui_kittest::Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session));
|
||||
let mut harness = egui_kittest::Harness::builder()
|
||||
.with_context_setup(crate::framework::install_headless)
|
||||
.build_eframe(|context| TextureCraftApp::new(context, session));
|
||||
let app = harness.state_mut();
|
||||
app.session.tool.tool = tool;
|
||||
let history = app.session.history_labels().len();
|
||||
@@ -2661,7 +2747,9 @@ mod tests {
|
||||
// The harness draws the UI, so another test's interface language must not be active
|
||||
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let session = Session::new_project("t", primitives::plane(2.0, 4), "test", None, 128).unwrap();
|
||||
let mut harness = egui_kittest::Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session));
|
||||
let mut harness = egui_kittest::Harness::builder()
|
||||
.with_context_setup(crate::framework::install_headless)
|
||||
.build_eframe(|context| TextureCraftApp::new(context, session));
|
||||
let app = harness.state_mut();
|
||||
app.ui.mode = crate::state::Mode::Painting;
|
||||
app.session.view = ViewMode::Mask(LayerId(7));
|
||||
@@ -2687,7 +2775,9 @@ mod tests {
|
||||
execute(&mut session, "layer.add.fill", &json!(null)).unwrap();
|
||||
let effect = texturecraft_engine::core::LayerId(execute(&mut session, "mask.add.colorSelection", &json!(null)).unwrap()["effect"].as_u64().unwrap());
|
||||
session.target = StackTarget::Effect(effect);
|
||||
let mut harness = egui_kittest::Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session));
|
||||
let mut harness = egui_kittest::Harness::builder()
|
||||
.with_context_setup(crate::framework::install_headless)
|
||||
.build_eframe(|context| TextureCraftApp::new(context, session));
|
||||
harness.run_steps(2);
|
||||
|
||||
crate::id_color_pick::IdColorPick::start(harness.state_mut(), effect, None);
|
||||
@@ -2704,7 +2794,10 @@ mod tests {
|
||||
fn a_waiting_eyedropper_keeps_a_2d_view_click_from_painting() {
|
||||
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 harness = egui_kittest::Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session));
|
||||
let mut harness = egui_kittest::Harness::builder()
|
||||
.with_size(egui::vec2(1600.0, 960.0))
|
||||
.with_context_setup(crate::framework::install_headless)
|
||||
.build_eframe(|context| TextureCraftApp::new(context, session));
|
||||
harness.state_mut().ui.layout = ViewLayout::Only2D;
|
||||
harness.state_mut().session.tool.tool = Tool::PolygonFill;
|
||||
harness.run_steps(4);
|
||||
@@ -2750,7 +2843,9 @@ mod tests {
|
||||
let effect = texturecraft_engine::core::LayerId(result["committed"]["effect"].as_u64().unwrap());
|
||||
let EffectKind::Path(paths) = &mut session.doc.project.effect_mut(effect).unwrap().kind else { panic!("path effect") };
|
||||
paths.resize(8, paths[0].clone());
|
||||
let mut harness = egui_kittest::Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session));
|
||||
let mut harness = egui_kittest::Harness::builder()
|
||||
.with_context_setup(crate::framework::install_headless)
|
||||
.build_eframe(|context| TextureCraftApp::new(context, session));
|
||||
let context = egui::Context::default();
|
||||
let mut previous = Vec::<std::sync::Weak<Vec<Vec<Option<Vec3>>>>>::new();
|
||||
|
||||
@@ -2799,7 +2894,7 @@ mod tests {
|
||||
Session::new_project("Decal selection", texturecraft_engine::geom::primitives::material_ball(), "builtin:material_ball", None, 256).unwrap();
|
||||
let builder = egui_kittest::Harness::builder().with_size(vec2(1600.0, 960.0));
|
||||
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);
|
||||
let mut png = Vec::new();
|
||||
image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 255, 255, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
@@ -2949,7 +3044,9 @@ mod tests {
|
||||
// Hold the language lock while drawing the harness
|
||||
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 harness = egui_kittest::Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session));
|
||||
let mut harness = egui_kittest::Harness::builder()
|
||||
.with_context_setup(crate::framework::install_headless)
|
||||
.build_eframe(|context| TextureCraftApp::new(context, session));
|
||||
let app = harness.state_mut();
|
||||
app.ui.mode = crate::state::Mode::Baking;
|
||||
let before = bake_visualization(app).unwrap();
|
||||
@@ -2972,7 +3069,9 @@ mod tests {
|
||||
#[test]
|
||||
fn the_automatic_cage_shows_no_matching_error() {
|
||||
let session = texturecraft_engine::sample_session(256, 64).unwrap();
|
||||
let mut harness = egui_kittest::Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session));
|
||||
let mut harness = egui_kittest::Harness::builder()
|
||||
.with_context_setup(crate::framework::install_headless)
|
||||
.build_eframe(|context| TextureCraftApp::new(context, session));
|
||||
let app = harness.state_mut();
|
||||
app.ui.mode = crate::state::Mode::Baking;
|
||||
assert!(bake_visualization(app).unwrap().matching_error.shown);
|
||||
|
||||
@@ -449,7 +449,8 @@ mod tests {
|
||||
#[test]
|
||||
fn mesh_picks_only_update_the_current_new_project_request() {
|
||||
let session = Session::closed().unwrap();
|
||||
let mut harness = Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session));
|
||||
let mut harness =
|
||||
Harness::builder().with_context_setup(crate::framework::install_headless).build_eframe(|context| TextureCraftApp::new(context, session));
|
||||
let app = harness.state_mut();
|
||||
crate::new_project_advanced::open(app);
|
||||
app.ui.new_project.mesh_request_id = 2;
|
||||
@@ -471,7 +472,8 @@ mod tests {
|
||||
#[test]
|
||||
fn environment_pick_after_close_does_not_edit_the_placeholder() {
|
||||
let session = texturecraft_engine::sample_session(128, 32).unwrap();
|
||||
let mut harness = Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session));
|
||||
let mut harness =
|
||||
Harness::builder().with_context_setup(crate::framework::install_headless).build_eframe(|context| TextureCraftApp::new(context, session));
|
||||
let png = texturecraft_engine::formats::gray16_png(1, 1, [0.5].into_iter()).unwrap();
|
||||
let old_project_id = harness.state().session.project_id;
|
||||
|
||||
@@ -493,7 +495,8 @@ mod tests {
|
||||
#[test]
|
||||
fn environment_pick_from_replaced_project_does_not_edit_the_new_project() {
|
||||
let session = texturecraft_engine::sample_session(128, 32).unwrap();
|
||||
let mut harness = Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session));
|
||||
let mut harness =
|
||||
Harness::builder().with_context_setup(crate::framework::install_headless).build_eframe(|context| TextureCraftApp::new(context, session));
|
||||
let png = texturecraft_engine::formats::gray16_png(1, 1, [0.5].into_iter()).unwrap();
|
||||
let old_project_id = harness.state().session.project_id;
|
||||
|
||||
@@ -511,7 +514,8 @@ mod tests {
|
||||
#[test]
|
||||
fn bake_mesh_picks_after_close_do_not_edit_the_placeholder() {
|
||||
let session = texturecraft_engine::sample_session(128, 32).unwrap();
|
||||
let mut harness = Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session));
|
||||
let mut harness =
|
||||
Harness::builder().with_context_setup(crate::framework::install_headless).build_eframe(|context| TextureCraftApp::new(context, session));
|
||||
let old_project_id = harness.state().session.project_id;
|
||||
assert!(harness.state_mut().run("file.close", serde_json::Value::Null).is_some());
|
||||
let cage = harness.state().session.mesh_obj_bytes().unwrap();
|
||||
|
||||
Loaded 100 of 230 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user