diff --git a/.cargo/config.toml b/.cargo/config.toml index 5592118f..e65ef03e 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -1,2 +1,102 @@ [alias] xtask = "run -p xtask --" + +# An explicit level for dependencies: Cargo drops the profile's default debug level from crates only build scripts and +# macros use, and then clippy and test each build their own copy of them. +[profile.dev.package."*"] +debug = "line-tables-only" + +# 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 diff --git a/.gitattributes b/.gitattributes index 12adf75e..de2d0fd2 100644 --- a/.gitattributes +++ b/.gitattributes @@ -3,3 +3,4 @@ *.ico binary *.icns binary *.ps1 text eol=crlf +*.tcraft binary diff --git a/.github/nightly-linux-signing-key.asc b/.github/nightly-linux-signing-key.asc new file mode 100644 index 00000000..a1c1f31e --- /dev/null +++ b/.github/nightly-linux-signing-key.asc @@ -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----- diff --git a/.github/nightly-signing-policy.json b/.github/nightly-signing-policy.json new file mode 100644 index 00000000..35cb9eeb --- /dev/null +++ b/.github/nightly-signing-policy.json @@ -0,0 +1,112 @@ +{ + "schema": "craft-nightly-release-policy/v3", + "repository": "storytold/texturecraft", + "repository_id": 1419654881, + "producer_workflow_id": 429738073, + "producer_workflow_path": ".github/workflows/nightly.yml", + "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": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba", + "release_branch": "nightly-signer", + "manual_actors": [ + "bflatastic", + "dylanmtaylor", + "echelon", + "FredApps", + "skylartaylor" + ], + "max_age_seconds": 86400, + "candidate_policy": { + "schema": "craft-nightly-candidate-policy/v3", + "epoch": "texturecraft-nightly-20261124", + "repository": "storytold/texturecraft", + "branch": "main", + "required_workflows": [ + { + "workflow_id": 384666426, + "workflow_path": ".github/workflows/ci.yml", + "jobs": [ + { + "name": "gate / gate (ubuntu-24.04)", + "app_id": 15368, + "applicability": "required" + }, + { + "name": "gate / gate (windows-latest)", + "app_id": 15368, + "applicability": "required" + } + ] + } + ], + "sonar": { + "organization": "storytold", + "project": "storytold_texturecraft", + "app_id": 12526, + "check_name": "SonarCloud Code Analysis", + "details_url": "https://sonarcloud.io/dashboard?id=storytold_texturecraft&branch=main", + "issue_types": [ + "VULNERABILITY" + ], + "accepted_conditions": [ + { + "metric": "new_security_rating", + "comparator": "GT", + "error_threshold": "1", + "maximum": "5" + } + ], + "required_conditions": [ + { + "metric": "new_reliability_rating", + "comparator": "GT", + "error_threshold": "1" + }, + { + "metric": "new_maintainability_rating", + "comparator": "GT", + "error_threshold": "1" + }, + { + "metric": "new_coverage", + "comparator": "LT", + "error_threshold": "80" + }, + { + "metric": "new_duplicated_lines_density", + "comparator": "GT", + "error_threshold": "3" + }, + { + "metric": "new_security_hotspots_reviewed", + "comparator": "LT", + "error_threshold": "100" + } + ], + "debt": [] + } + }, + "max_artifact_bytes": 2147483648, + "automatic_signer_actors": [], + "platforms": { + "windows-x86_64": { + "unsigned_artifact_name": "nightly-unsigned-windows-x86_64", + "trust": { + "publisher_subject": "CN=Learning Machines Inc, O=Learning Machines Inc, L=Atlanta, S=Georgia, C=US" + } + }, + "linux-x86_64": { + "unsigned_artifact_name": "nightly-unsigned-linux-x86_64", + "trust": { + "fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED" + } + }, + "macos-aarch64": { + "unsigned_artifact_name": "nightly-unsigned-macos-aarch64", + "trust": { + "apple_team_id": "DJ6XS33FX8" + } + } + } +} diff --git a/.github/workflows/nightly-dispatch.yml b/.github/workflows/nightly-dispatch.yml new file mode 100644 index 00000000..bd40f765 --- /dev/null +++ b/.github/workflows/nightly-dispatch.yml @@ -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.') diff --git a/.github/workflows/nightly-macos.yml b/.github/workflows/nightly-macos.yml new file mode 100644 index 00000000..75134544 --- /dev/null +++ b/.github/workflows/nightly-macos.yml @@ -0,0 +1,91 @@ +name: Nightly macOS build + +# Builds the unsigned Apple-silicon TextureCraft Nightly (packaging/macos/nightly.sh) on a hosted +# macOS runner and checks the archive as the Launcher unpacks it, ending with the bundle's version +# query (packaging/macos/nightly-verify.sh --expect unsigned). No secrets and no environment: the real +# Nightly is signed and notarized by the shared release-ref signer (craft-common-actions), which calls +# packaging/macos/nightly-sign.sh. +on: + # macOS minutes are shared with release builds: pull requests run this only with the `full-ci` + # label, never by changed paths. `labeled` so adding it starts a run. + pull_request: + types: [opened, synchronize, reopened, labeled] + workflow_dispatch: + +permissions: + contents: read + +# A newer push to a labelled PR cancels its older run. Any event that will not build (no `full-ci` +# label, or another label added) gets a group of its own, so it never cancels a real build. +concurrency: + group: nightly-macos-${{ github.event_name == 'pull_request' && contains(github.event.pull_request.labels.*.name, 'full-ci') && (github.event.action != 'labeled' || github.event.label.name == 'full-ci') && github.ref || github.run_id }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + build: + name: Nightly .app (aarch64, unsigned) + if: >- + github.event_name == 'workflow_dispatch' || + (contains(github.event.pull_request.labels.*.name, 'full-ci') && + (github.event.action != 'labeled' || github.event.label.name == 'full-ci')) + runs-on: macos-15 + timeout-minutes: 90 + env: + CARGO_TERM_COLOR: always + CARGO_INCREMENTAL: 0 + RUST_BACKTRACE: 1 + steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + # The release's pin (release.yml craft-fonts-ref), so the bundle's notices match a shipped build. + - name: Check out craft-fonts + uses: storytold/craft-common-actions/actions/checkout-craft-fonts@605d58766e8f536564da8fc81d3676ac86816dea + with: + ref: aced4137c022f1f587624d48e81ec77e1914a9cc + - uses: storytold/craft-common-actions/actions/checkout-craft-i18n@605d58766e8f536564da8fc81d3676ac86816dea + - id: rust + uses: storytold/craft-common-actions/actions/rust-channel@605d58766e8f536564da8fc81d3676ac86816dea + with: + targets: aarch64-apple-darwin + - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + with: + toolchain: ${{ steps.rust.outputs.toolchain }} + targets: ${{ steps.rust.outputs.targets }} + components: ${{ steps.rust.outputs.components }} + # A version of the prepared Nightly form for this commit; the real one comes from the feed's + # identity job. Only nightly.sh's input checks read it. + - name: Prepare a Nightly identity for this commit + run: | + set -euo pipefail + base="$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["version"].split("-")[0])')" + sha="$(git rev-parse HEAD)" + date="$(date -u +%Y-%m-%d)" + { + echo "TEXTURECRAFT_BUILD_SHA=$sha" + echo "TEXTURECRAFT_BUILD_DATE=$date" + echo "TEXTURECRAFT_VERSION=$base-nightly.${date//-/}.$GITHUB_RUN_NUMBER.$GITHUB_RUN_ATTEMPT.g${sha:0:12}" + } >>"$GITHUB_ENV" + - name: Build the unsigned Nightly bundle + env: + TEXTURECRAFT_BUILD_CHANNEL: nightly-v1 + CARGO_TARGET_DIR: ${{ runner.temp }}/nightly-targets + DIST: ${{ runner.temp }}/nightly-dist + CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts + CRAFT_FONTS_REQUIRED: "1" + run: bash packaging/macos/nightly.sh --arch aarch64 + - name: Check the archive and the bundle's version + run: bash packaging/macos/nightly-verify.sh --expect unsigned --input "$RUNNER_TEMP/nightly-dist/texturecraft-$TEXTURECRAFT_VERSION-macos-aarch64-nightly.zip" + # Keeps the verified unsigned zip briefly for keyless signer tests and hand testing. Unsigned only. + - name: Keep the unsigned archive + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: texturecraft-nightly-macos-aarch64-unsigned + path: ${{ runner.temp }}/nightly-dist/texturecraft-${{ env.TEXTURECRAFT_VERSION }}-macos-aarch64-nightly.zip + if-no-files-found: error + retention-days: 7 + compression-level: 0 diff --git a/.github/workflows/nightly-sign.yml b/.github/workflows/nightly-sign.yml new file mode 100644 index 00000000..998acbae --- /dev/null +++ b/.github/workflows/nightly-sign.yml @@ -0,0 +1,45 @@ +name: TextureCraft release-ref nightly signer + +# 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: + producer_run_id: + description: Exact untrusted producer Actions run ID + required: true + type: string + producer_run_attempt: + description: Exact untrusted producer Actions run attempt + required: true + type: string + +permissions: {} + +concurrency: + group: texturecraft-nightly-release + cancel-in-progress: false + +jobs: + release: + # Actual context guards: official repository, manual dispatch, real nightly-signer branch. + if: >- + github.repository == 'storytold/texturecraft' && + github.event_name == 'workflow_dispatch' && + 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@be00e5ccd18b68e950c8a08532f2230e7c3d0cba + with: + 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 release environment and export its keys; that environment must + # admit nightly-signer alongside release before the first dispatch. diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml new file mode 100644 index 00000000..1600b2e0 --- /dev/null +++ b/.github/workflows/nightly.yml @@ -0,0 +1,34 @@ +name: TextureCraft unsigned nightly + +# Enabled for supervised manual runs by the reviewed manual actor only; no schedule yet. +# A later explicit opt-in may add a cadence (and turn on nightly-dispatch.yml with it). +on: + workflow_dispatch: + +permissions: + contents: read + +jobs: + unsigned: + # Actual context guards only; no inherited/platform secrets. + if: >- + github.repository == 'storytold/texturecraft' && + github.ref == 'refs/heads/main' && github.ref_type == 'branch' && + (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch') + # Maximum for the reusable workflow. Its compiler narrows to contents/actions read; + # no OIDC, attestation write, release environment or platform secrets in compilation. + permissions: + contents: read + actions: read + attestations: write + id-token: write + uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba + with: + 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 the exact-analysis admission (#371, after #370, + # #369 and #364). + platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]' diff --git a/.github/workflows/packaging-lint.yml b/.github/workflows/packaging-lint.yml index f54b0538..feb8675d 100644 --- a/.github/workflows/packaging-lint.yml +++ b/.github/workflows/packaging-lint.yml @@ -21,3 +21,7 @@ jobs: lint: # Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos. uses: storytold/craft-common-actions/.github/workflows/packaging-lint.yml@main + with: + # Runs the Nightly synthetic suites, the launcher tests and `bash -n` here, so the checks + # that need no compiler are part of CI rather than a local step. + extra-checks-script: packaging/nightly-checks.sh diff --git a/.gitignore b/.gitignore index 0996cb2f..14362878 100644 --- a/.gitignore +++ b/.gitignore @@ -7,5 +7,11 @@ target/ /log /secrets /temp +# The shared nightly workflow checks these out into the workspace; `nightly_init` refuses a dirty tree. +/.nightly-tools +/.nightly-input /craft-fonts +/craft-i18n +__pycache__/ +*.pyc *.tcraft.tmp diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index a136498a..5bfb7129 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -15,7 +15,9 @@ licensed and keep their license file next to them. | `assets/app-icon/texturecraft.icns` | App icon (engraved zebra), macOS (16-1024 px) | Project owner (ArtCraft team) | Original artwork drawn in ArtCraft for TextureCraft, rendered by `packaging/icons.sh` | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | | `assets/app-icon/hicolor/{16x16,24x24,32x32,48x48,64x64,128x128,256x256,512x512}/apps/ai.storyteller.texturecraft.png` | App icon (engraved zebra), hicolor theme PNGs | Project owner (ArtCraft team) | Original artwork drawn in ArtCraft for TextureCraft, rendered by `packaging/icons.sh` | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | | `assets/app-icon/hicolor/scalable/apps/ai.storyteller.texturecraft.svg` | App icon (engraved zebra), hicolor scalable (copy of `texturecraft-small.svg`) | Project owner (ArtCraft team) | Original artwork drawn in ArtCraft for TextureCraft, vectorised with craftrules `vectorize_tile.py` | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | +| `assets/app-icon/texturecraft-nightly{,-1024}.png`, `assets/app-icon/texturecraft-nightly.{icns,ico}`, `assets/app-icon/nightly/{16,24,32,48,64,128,256,512}.png` | Nightly app icons (engraved zebra on deep copper) | Project owner (ArtCraft team) | Project-owned stable icon renders, with the background recolored by `packaging/nightly-icons.py` ([provenance and hashes](assets/app-icon/nightly-provenance.json)) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | | `assets/app-icon/LICENSE.txt`, `assets/app-icon/README.md` | App icon licence and notes | TextureCraft contributors | original | MIT OR Apache-2.0 | +| `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 | diff --git a/Cargo.lock b/Cargo.lock index 45aedc2d..acafef1d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -80,7 +80,7 @@ dependencies = [ "futures-lite", "futures-util", "serde", - "zbus 5.19.0", + "zbus", ] [[package]] @@ -239,11 +239,20 @@ dependencies = [ "x11rb", ] +[[package]] +name = "arrayref" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb" + [[package]] name = "arrayvec" version = "0.7.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" +dependencies = [ + "serde", +] [[package]] name = "as-raw-xcb-connection" @@ -260,22 +269,6 @@ dependencies = [ "libloading", ] -[[package]] -name = "ashpd" -version = "0.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ba377f1fb1e3972907220f1f8e7c0a45164580905c981d872c1fb90d921cbcc" -dependencies = [ - "bitflags 2.13.2", - "futures-channel", - "futures-util", - "getrandom 0.4.3", - "pipewire", - "serde", - "serde_repr", - "zbus 6.3.0", -] - [[package]] name = "async-broadcast" version = "0.7.2" @@ -327,7 +320,7 @@ dependencies = [ "futures-lite", "parking", "polling", - "rustix 1.1.5", + "rustix 1.1.6", "slab", "windows-sys 0.61.2", ] @@ -358,7 +351,7 @@ dependencies = [ "cfg-if", "event-listener", "futures-lite", - "rustix 1.1.5", + "rustix 1.1.6", ] [[package]] @@ -384,7 +377,7 @@ dependencies = [ "cfg-if", "futures-core", "futures-io", - "rustix 1.1.5", + "rustix 1.1.6", "signal-hook-registry", "slab", "windows-sys 0.61.2", @@ -432,7 +425,7 @@ dependencies = [ "enumflags2", "serde", "static_assertions", - "zbus 5.19.0", + "zbus", "zbus-lockstep", "zbus-lockstep-macros", "zbus_names", @@ -447,7 +440,7 @@ checksum = "2230e48787ed3eb4088996eab66a32ca20c0b67bbd4fd6cdfe79f04f1f04c9fc" dependencies = [ "atspi-common", "serde", - "zbus 5.19.0", + "zbus", ] [[package]] @@ -529,6 +522,12 @@ dependencies = [ "serde_core", ] +[[package]] +name = "block" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d8c1fef690941d3e7788d328517591fecc684c084084702d6ff1641e993699a" + [[package]] name = "block-buffer" version = "0.10.4" @@ -623,6 +622,16 @@ version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +[[package]] +name = "calendrical_calculations" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5abbd6eeda6885048d357edc66748eea6e0268e3dd11f326fff5bd248d779c26" +dependencies = [ + "core_maths", + "displaydoc", +] + [[package]] name = "calloop" version = "0.13.0" @@ -661,9 +670,9 @@ dependencies = [ "io-lifetimes 3.0.1", "ipnet", "maybe-owned", - "rustix 1.1.5", + "rustix 1.1.6", "rustix-linux-procfs", - "windows-sys 0.61.2", + "windows-sys 0.60.2", "winx", ] @@ -676,7 +685,7 @@ dependencies = [ "cap-primitives", "io-extras", "io-lifetimes 3.0.1", - "rustix 1.1.5", + "rustix 1.1.6", ] [[package]] @@ -895,12 +904,34 @@ dependencies = [ "libc", ] +[[package]] +name = "core-graphics2" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b65858d95344d2711161cd92196732f67d6c5fea238cf12f994584828731a5c" +dependencies = [ + "bitflags 2.13.2", + "block", + "cfg-if", + "core-foundation 0.10.1", + "libc", +] + [[package]] name = "core_detect" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" +[[package]] +name = "core_maths" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30" +dependencies = [ + "libm", +] + [[package]] name = "cpufeatures" version = "0.2.17" @@ -919,19 +950,68 @@ dependencies = [ "libc", ] +[[package]] +name = "craft-appkit" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +dependencies = [ + "block2 0.6.2", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "craft-atomic" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +dependencies = [ + "rustix 1.1.6", +] + +[[package]] +name = "craft-behavior" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +dependencies = [ + "accesskit", + "bitflags 2.13.2", + "craft-host", + "craft-keymap", + "craft-theme", + "craft-tracked", + "craft-ui-macros", + "emath", + "kurbo", + "serde", + "smallvec", +] + +[[package]] +name = "craft-cloud-ui" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +dependencies = [ + "egui", +] + [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=272a095b61257917693da3d09f2f8ecccd7f0295#272a095b61257917693da3d09f2f8ecccd7f0295" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "md-5", "rayon", ] +[[package]] +name = "craft-codepage" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" + [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "rayon", ] @@ -939,27 +1019,73 @@ dependencies = [ [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "block2 0.6.2", + "craft-atomic", + "craft-host", + "craft-i18n", + "craft-platform", + "futures-lite", + "log", "objc2 0.6.5", "objc2-app-kit 0.3.2", "objc2-foundation 0.3.2", "raw-window-handle", "rfd", + "zbus", +] + +[[package]] +name = "craft-docpath" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +dependencies = [ + "serde", +] + +[[package]] +name = "craft-font-catalog" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +dependencies = [ + "harfrust 0.13.3", + "kurbo", + "skrifa 0.47.0", + "thiserror 2.0.21", + "unicode-bidi", + "unicode-segmentation", + "windows-registry", ] [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" + +[[package]] +name = "craft-host" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +dependencies = [ + "bitflags 2.13.2", + "craft-i18n", + "egui", + "serde", + "toml", + "web-time", +] [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ + "chrono", "fixed_decimal", + "icu_calendar", + "icu_collator", + "icu_datetime", "icu_decimal", "icu_locale_core", "icu_locale_fallback", @@ -969,6 +1095,7 @@ dependencies = [ "icu_provider", "icu_provider_adapters", "icu_provider_blob", + "icu_time", "log", "objc2-foundation 0.3.2", "sys-locale", @@ -980,7 +1107,7 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "craft-dds", "craft-jpeg", @@ -1007,7 +1134,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "thiserror 2.0.21", ] @@ -1015,8 +1142,13 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ + "craft-host", + "craft-i18n", + "craft-tracked", + "craft-ui-macros", + "craft-xml", "egui", "serde", "serde_json", @@ -1025,18 +1157,18 @@ dependencies = [ [[package]] name = "craft-materialx" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585)", + "craft-xml", "thiserror 2.0.21", ] [[package]] name = "craft-mcmat" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7a7a18cb40ac4cd5fca29c0dc224ac5178d40a89#7a7a18cb40ac4cd5fca29c0dc224ac5178d40a89" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7a7a18cb40ac4cd5fca29c0dc224ac5178d40a89)", + "craft-zip", "serde", "serde_json", "thiserror 2.0.21", @@ -1045,23 +1177,28 @@ dependencies = [ [[package]] name = "craft-menu" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ + "craft-behavior", + "craft-host", + "craft-i18n", "craft-keymap", "craft-quit", + "craft-theme", + "craft-ui", + "craft-window", "egui", - "muda", - "objc2 0.6.5", - "objc2-app-kit 0.3.2", + "serde", + "serde_json", ] [[package]] name = "craft-mesh" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a20dfd1623709b0bd9830106d3a92a1a443902e3#a20dfd1623709b0bd9830106d3a92a1a443902e3" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a20dfd1623709b0bd9830106d3a92a1a443902e3)", - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a20dfd1623709b0bd9830106d3a92a1a443902e3)", + "craft-xml", + "craft-zip", "miniz_oxide 0.9.1", "serde_json", ] @@ -1069,7 +1206,7 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "brotli-decompressor", "chrono", @@ -1078,10 +1215,49 @@ dependencies = [ "serde", ] +[[package]] +name = "craft-pdf" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +dependencies = [ + "serde", +] + +[[package]] +name = "craft-platform" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +dependencies = [ + "async-channel", + "async-io", + "async-process", + "core-graphics2", + "craft-atomic", + "craft-docpath", + "craft-host", + "craft-i18n", + "craft-theme", + "futures-lite", + "js-sys", + "log", + "objc2-app-kit 0.3.2", + "rfd", + "serde", + "serde_json", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "web-time", + "windows", + "x11rb", + "xcap", + "zbus", +] + [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b130ac1fa44f923c3024884ab8ceb5ccdb88f15f#b130ac1fa44f923c3024884ab8ceb5ccdb88f15f" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "encoding_rs", "flate2", @@ -1092,69 +1268,264 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "dispatch2", "egui", "objc2 0.6.5", "objc2-app-kit 0.3.2", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "craft-settings" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +dependencies = [ + "craft-atomic", + "craft-host", + "dirs", + "log", + "serde", + "serde_json", + "toml", + "toml_edit", + "web-sys", + "web-time", +] + +[[package]] +name = "craft-svg" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +dependencies = [ + "craft-xml", + "flate2", + "kurbo", + "quick-xml 0.41.0", + "resvg", + "roxmltree", + "thiserror 2.0.21", + "usvg", + "vectorcraft-geom", + "vectorcraft-pathops", ] [[package]] name = "craft-tcraft" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c376774f15ae7cd3b06a7ac664f01a8645af4b83#c376774f15ae7cd3b06a7ac664f01a8645af4b83" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c376774f15ae7cd3b06a7ac664f01a8645af4b83)", + "craft-zip", "serde", "serde_json", "thiserror 2.0.21", ] +[[package]] +name = "craft-theme" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +dependencies = [ + "bitflags 2.13.2", + "craft-tracked", + "craft-ui-macros", + "ecolor", + "log", + "serde", + "serde_json", + "smallvec", +] + [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "serde", "thiserror 2.0.21", + "tiff", ] +[[package]] +name = "craft-tracked" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" + [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ - "craft-fonts-build", + "craft-cloud-ui", + "craft-ui-canvas", + "craft-ui-contract", + "craft-ui-panels", + "craft-ui-patterns", + "craft-ui-shell", + "craft-ui-widgets", +] + +[[package]] +name = "craft-ui-canvas" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +dependencies = [ + "craft-behavior", "craft-i18n", + "craft-keymap", + "craft-theme", + "craft-ui-macros", + "craft-ui-panels", "egui", - "epaint", - "js-sys", - "log", - "objc2 0.6.5", - "objc2-app-kit 0.3.2", - "objc2-foundation 0.3.2", "serde", + "serde_json", +] + +[[package]] +name = "craft-ui-contract" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +dependencies = [ + "accesskit", + "craft-behavior", + "craft-codepage", + "craft-font-catalog", + "craft-fonts-build", + "craft-host", + "craft-i18n", + "craft-keymap", + "craft-platform", + "craft-quit", + "craft-settings", + "craft-svg", + "craft-theme", + "craft-tracked", + "craft-ui-macros", + "craft-window", + "egui", + "epaint_default_fonts", + "flate2", + "inventory", + "log", + "scoped-tls", + "serde", + "serde_json", + "siphasher", "skrifa 0.44.0", - "wasm-bindgen", + "smallvec", + "toml", + "typeid", "wasm-bindgen-futures", - "web-sys", + "web-time", +] + +[[package]] +name = "craft-ui-macros" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "craft-ui-panels" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +dependencies = [ + "craft-behavior", + "craft-host", + "craft-i18n", + "craft-keymap", + "craft-quit", + "craft-theme", + "craft-ui-macros", + "craft-ui-widgets", + "egui", + "serde", + "serde_json", +] + +[[package]] +name = "craft-ui-patterns" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +dependencies = [ + "craft-behavior", + "craft-host", + "craft-i18n", + "craft-keymap", + "craft-pdf", + "craft-theme", + "craft-ui-macros", + "craft-ui-panels", + "egui", + "serde", + "serde_json", + "toml", + "toml_edit", + "zeroize", +] + +[[package]] +name = "craft-ui-shell" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +dependencies = [ + "craft-behavior", + "craft-host", + "craft-i18n", + "craft-platform", + "craft-svg", + "craft-theme", + "craft-ui-macros", + "craft-ui-panels", + "craft-window", + "egui", + "raw-window-handle", + "serde", + "web-time", +] + +[[package]] +name = "craft-ui-widgets" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +dependencies = [ + "craft-behavior", + "craft-host", + "craft-i18n", + "craft-keymap", + "craft-svg", + "craft-theme", + "craft-ui-contract", + "craft-ui-macros", + "egui", + "log", + "serde", + "smallvec", ] [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "chrono", + "craft-host", + "craft-theme", + "craft-ui", "dunce", "egui", "flate2", - "getrandom 0.3.4", "image", "log", "plist", - "rustix 1.1.5", + "rustix 1.1.6", "semver", "serde", "serde_json", @@ -1171,38 +1542,49 @@ dependencies = [ [[package]] name = "craft-usd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "half", "lz4_flex", "thiserror 2.0.21", ] +[[package]] +name = "craft-win32" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" +dependencies = [ + "winsafe", +] + [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ + "craft-appkit", + "craft-atomic", + "craft-behavior", + "craft-host", + "craft-settings", + "craft-win32", "egui", + "muda", "objc2 0.6.5", "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "raw-window-handle", + "serde", + "serde_json", "wayland-client", + "winsafe", + "x11rb", ] [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" -dependencies = [ - "quick-xml 0.41.0", - "serde", - "thiserror 2.0.21", -] - -[[package]] -name = "craft-xml" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a20dfd1623709b0bd9830106d3a92a1a443902e3#a20dfd1623709b0bd9830106d3a92a1a443902e3" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "quick-xml 0.41.0", "serde", @@ -1212,37 +1594,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=5631e99fe126cffb74c673eb458db04299f2bb9b#5631e99fe126cffb74c673eb458db04299f2bb9b" -dependencies = [ - "flate2", - "thiserror 2.0.21", - "zip", -] - -[[package]] -name = "craft-zip" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7a7a18cb40ac4cd5fca29c0dc224ac5178d40a89#7a7a18cb40ac4cd5fca29c0dc224ac5178d40a89" -dependencies = [ - "flate2", - "thiserror 2.0.21", - "zip", -] - -[[package]] -name = "craft-zip" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a20dfd1623709b0bd9830106d3a92a1a443902e3#a20dfd1623709b0bd9830106d3a92a1a443902e3" -dependencies = [ - "flate2", - "thiserror 2.0.21", - "zip", -] - -[[package]] -name = "craft-zip" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c376774f15ae7cd3b06a7ac664f01a8645af4b83#c376774f15ae7cd3b06a7ac664f01a8645af4b83" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "flate2", "thiserror 2.0.21", @@ -1348,6 +1700,12 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "data-url" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376" + [[package]] name = "deranged" version = "0.5.9" @@ -1364,6 +1722,27 @@ dependencies = [ "crypto-common", ] +[[package]] +name = "dirs" +version = "7.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d57d423b3c82e89b9a24ca3091fee61f456a26edbd28d26c65906f4bc1dcd8f" +dependencies = [ + "dirs-sys", +] + +[[package]] +name = "dirs-sys" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" +dependencies = [ + "libc", + "option-ext", + "redox_users", + "windows-sys 0.60.2", +] + [[package]] name = "dispatch" version = "0.2.0" @@ -1449,7 +1828,7 @@ dependencies = [ "drm-ffi", "drm-fourcc", "libc", - "rustix 1.1.5", + "rustix 1.1.6", ] [[package]] @@ -1459,7 +1838,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "51a91c9b32ac4e8105dec255e849e0d66e27d7c34d184364fb93e469db08f690" dependencies = [ "drm-sys", - "rustix 1.1.5", + "rustix 1.1.6", ] [[package]] @@ -1493,7 +1872,7 @@ checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" [[package]] name = "ecolor" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" dependencies = [ "bytemuck", "emath", @@ -1503,7 +1882,7 @@ dependencies = [ [[package]] name = "eframe" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" dependencies = [ "ahash", "bytemuck", @@ -1540,7 +1919,7 @@ dependencies = [ [[package]] name = "egui" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" dependencies = [ "accesskit", "ahash", @@ -1568,7 +1947,7 @@ dependencies = [ [[package]] name = "egui-wgpu" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" dependencies = [ "ahash", "bytemuck", @@ -1587,7 +1966,7 @@ dependencies = [ [[package]] name = "egui-winit" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" dependencies = [ "accesskit_winit", "arboard", @@ -1611,7 +1990,7 @@ dependencies = [ [[package]] name = "egui_glow" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" dependencies = [ "bytemuck", "egui", @@ -1624,7 +2003,7 @@ dependencies = [ [[package]] name = "egui_kittest" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" dependencies = [ "eframe", "egui", @@ -1647,12 +2026,24 @@ checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" [[package]] name = "emath" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" dependencies = [ "bytemuck", "serde", ] +[[package]] +name = "embedded-io" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef1a6892d9eef45c8fa6b9e0086428a2cca8491aca8f787c534a3d6d0bcb3ced" + +[[package]] +name = "embedded-io" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edd0f118536f44f5ccd48bcb8b111bdc3de888b58c74639dfb034a357d0f206d" + [[package]] name = "encoding_rs" version = "0.8.44" @@ -1708,7 +2099,7 @@ dependencies = [ [[package]] name = "epaint" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" dependencies = [ "ahash", "bytemuck", @@ -1716,7 +2107,7 @@ dependencies = [ "emath", "epaint_default_fonts", "font-types", - "harfrust", + "harfrust 0.12.0", "log", "nohash-hasher", "parking_lot", @@ -1735,7 +2126,7 @@ dependencies = [ [[package]] name = "epaint_default_fonts" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" [[package]] name = "equivalent" @@ -1750,7 +2141,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -1876,6 +2267,12 @@ dependencies = [ "zlib-rs", ] +[[package]] +name = "float-cmp" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4" + [[package]] name = "foldhash" version = "0.1.5" @@ -1941,8 +2338,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94e7099f6313ecacbe1256e8ff9d617b75d1bcb16a6fddef94866d225a01a14a" dependencies = [ "io-lifetimes 2.0.4", - "rustix 1.1.5", - "windows-sys 0.59.0", + "rustix 1.1.6", + "windows-sys 0.52.0", ] [[package]] @@ -2086,7 +2483,7 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8" dependencies = [ - "rustix 1.1.5", + "rustix 1.1.6", "windows-link", ] @@ -2359,6 +2756,19 @@ dependencies = [ "smallvec", ] +[[package]] +name = "harfrust" +version = "0.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "948d0741125ba89cd3e1c23e5642415b6ade7e1d29d67ba25fb925b533e989d6" +dependencies = [ + "bitflags 2.13.2", + "bytemuck", + "once_cell", + "read-fonts 0.43.3", + "smallvec", +] + [[package]] name = "hashbrown" version = "0.15.5" @@ -2455,6 +2865,39 @@ dependencies = [ "cc", ] +[[package]] +name = "icu_calendar" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "58655df2f728e46e4eee80bddebefacf52ec3e77cdb925014b47c5a5905eb55c" +dependencies = [ + "calendrical_calculations", + "displaydoc", + "icu_locale_core", + "icu_provider", + "serde", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_collator" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08984ed58ac439ebf3e13d2cf26b0c46a60afcd21721c1d14087c0b240344dda" +dependencies = [ + "icu_collections", + "icu_locale_core", + "icu_normalizer", + "icu_properties", + "icu_provider", + "serde", + "smallvec", + "utf16_iter", + "utf8_iter", + "zerovec", +] + [[package]] name = "icu_collections" version = "2.3.0" @@ -2463,12 +2906,37 @@ checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" dependencies = [ "displaydoc", "potential_utf", + "serde", "utf8_iter", "yoke", "zerofrom", "zerovec", ] +[[package]] +name = "icu_datetime" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c44df99c4c5297b05653d1a1629f13bdc9fd4044acfbbaf30b15194a1eed4cd6" +dependencies = [ + "displaydoc", + "fixed_decimal", + "icu_calendar", + "icu_decimal", + "icu_locale_core", + "icu_pattern", + "icu_plurals", + "icu_provider", + "icu_time", + "potential_utf", + "serde", + "smallvec", + "tinystr", + "writeable", + "zerotrie", + "zerovec", +] + [[package]] name = "icu_decimal" version = "2.3.0" @@ -2530,6 +2998,7 @@ dependencies = [ "icu_normalizer_data", "icu_properties", "icu_provider", + "serde", "smallvec", "utf16_iter", "utf8_iter", @@ -2580,6 +3049,7 @@ dependencies = [ "icu_locale_core", "icu_properties_data", "icu_provider", + "serde", "zerotrie", "zerovec", ] @@ -2632,6 +3102,22 @@ dependencies = [ "zerovec", ] +[[package]] +name = "icu_time" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af37e1c3b9f3ab564b619fdf4b22de169f6381eb0f7048e3ca454290c438126b" +dependencies = [ + "calendrical_calculations", + "displaydoc", + "icu_calendar", + "icu_locale_core", + "icu_provider", + "serde", + "zerotrie", + "zerovec", +] + [[package]] name = "ident_case" version = "1.0.1" @@ -2690,6 +3176,12 @@ dependencies = [ "quick-error", ] +[[package]] +name = "imagesize" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65b27460c2c92b037f3f94c538ed9a3342f3fdf923606781629ccb35f82d042a" + [[package]] name = "indexmap" version = "2.14.2" @@ -2708,6 +3200,15 @@ version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a257582fdcde896fd96463bf2d40eefea0580021c0712a0e2b028b60b47a837a" +[[package]] +name = "inventory" +version = "0.3.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6928282826c822ad91bf1c9a1cb90a30ba1c26770749929b4656cd6be829cd7c" +dependencies = [ + "rustversion", +] + [[package]] name = "io-extras" version = "0.19.0" @@ -2891,6 +3392,7 @@ dependencies = [ "arrayvec", "euclid", "polycool", + "serde", "smallvec", ] @@ -2952,7 +3454,7 @@ dependencies = [ "libc", "libspa-sys", "nom 8.0.0", - "rustix 1.1.5", + "rustix 1.1.6", "system-deps", ] @@ -2979,7 +3481,7 @@ dependencies = [ "image", "khronos-egl", "memmap2", - "rustix 1.1.5", + "rustix 1.1.6", "thiserror 2.0.21", "tracing", "wayland-backend", @@ -2994,6 +3496,19 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" +[[package]] +name = "linesweeper" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a25df1b0c5432893f41bba817150e323703ee5f6d974f3a6808ac7fd7f046d18" +dependencies = [ + "arrayvec", + "kurbo", + "polycool", + "rustc-hash 2.1.3", + "smallvec", +] + [[package]] name = "linux-raw-sys" version = "0.4.15" @@ -3159,7 +3674,7 @@ dependencies = [ "objc2-foundation 0.3.2", "png", "thiserror 2.0.21", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -3371,8 +3886,8 @@ dependencies = [ "block2 0.5.1", "libc", "objc2 0.5.3", - "objc2-core-data", - "objc2-core-image", + "objc2-core-data 0.2.2", + "objc2-core-image 0.2.2", "objc2-foundation 0.2.2", "objc2-quartz-core 0.2.2", ] @@ -3385,10 +3900,17 @@ checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c" dependencies = [ "bitflags 2.13.2", "block2 0.6.2", + "libc", "objc2 0.6.5", + "objc2-cloud-kit 0.3.2", + "objc2-core-data 0.3.2", "objc2-core-foundation", "objc2-core-graphics", + "objc2-core-image 0.3.2", + "objc2-core-text", + "objc2-core-video", "objc2-foundation 0.3.2", + "objc2-quartz-core 0.3.2", ] [[package]] @@ -3397,9 +3919,29 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "478ae33fcac9df0a18db8302387c666b8ef08a3e2d62b510ca4fc278a384b6c0" dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "dispatch2", "objc2 0.6.5", + "objc2-avf-audio", + "objc2-core-audio-types", + "objc2-core-foundation", "objc2-core-graphics", - "objc2-core-media", + "objc2-core-image 0.3.2", + "objc2-core-video", + "objc2-foundation 0.3.2", + "objc2-image-io", + "objc2-media-toolbox", + "objc2-quartz-core 0.3.2", +] + +[[package]] +name = "objc2-avf-audio" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13a380031deed8e99db00065c45937da434ca987c034e13b87e4441f9e4090be" +dependencies = [ + "objc2 0.6.5", "objc2-foundation 0.3.2", ] @@ -3416,6 +3958,17 @@ dependencies = [ "objc2-foundation 0.2.2", ] +[[package]] +name = "objc2-cloud-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73ad74d880bb43877038da939b7427bba67e9dd42004a18b809ba7d87cee241c" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-foundation 0.3.2", +] + [[package]] name = "objc2-contacts" version = "0.2.2" @@ -3461,6 +4014,17 @@ dependencies = [ "objc2-foundation 0.2.2", ] +[[package]] +name = "objc2-core-data" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b402a653efbb5e82ce4df10683b6b28027616a2715e90009947d50b8dd298fa" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-foundation 0.3.2", +] + [[package]] name = "objc2-core-foundation" version = "0.3.2" @@ -3468,7 +4032,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" dependencies = [ "bitflags 2.13.2", + "block2 0.6.2", "dispatch2", + "libc", "objc2 0.6.5", ] @@ -3479,11 +4045,13 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807" dependencies = [ "bitflags 2.13.2", + "block2 0.6.2", "dispatch2", "libc", "objc2 0.6.5", "objc2-core-foundation", "objc2-io-surface", + "objc2-metal 0.3.2", ] [[package]] @@ -3498,6 +4066,16 @@ dependencies = [ "objc2-metal 0.2.2", ] +[[package]] +name = "objc2-core-image" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5d563b38d2b97209f8e861173de434bd0214cf020e3423a52624cd1d989f006" +dependencies = [ + "objc2 0.6.5", + "objc2-foundation 0.3.2", +] + [[package]] name = "objc2-core-location" version = "0.2.2" @@ -3517,6 +4095,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "05ec576860167a15dd9fce7fbee7512beb4e31f532159d3482d1f9c6caedf31d" dependencies = [ "bitflags 2.13.2", + "block2 0.6.2", "dispatch2", "objc2 0.6.5", "objc2-core-audio", @@ -3525,6 +4104,18 @@ dependencies = [ "objc2-core-video", ] +[[package]] +name = "objc2-core-text" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0cde0dfb48d25d2b4862161a4d5fcc0e3c24367869ad306b0c9ec0073bfed92d" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", +] + [[package]] name = "objc2-core-video" version = "0.3.2" @@ -3532,10 +4123,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d425caf1df73233f29fd8a5c3e5edbc30d2d4307870f802d18f00d83dc5141a6" dependencies = [ "bitflags 2.13.2", + "block2 0.6.2", "objc2 0.6.5", "objc2-core-foundation", "objc2-core-graphics", "objc2-io-surface", + "objc2-metal 0.3.2", ] [[package]] @@ -3565,10 +4158,22 @@ checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" dependencies = [ "bitflags 2.13.2", "block2 0.6.2", + "libc", "objc2 0.6.5", "objc2-core-foundation", ] +[[package]] +name = "objc2-image-io" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32b0446e98cf4a784cc7a0177715ff317eeaa8463841c616cfc78aa4f953c4ea" +dependencies = [ + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", +] + [[package]] name = "objc2-io-kit" version = "0.3.2" @@ -3602,6 +4207,18 @@ dependencies = [ "objc2-foundation 0.2.2", ] +[[package]] +name = "objc2-media-toolbox" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edd9fdde720df3da7046bb9097811000c1e7ab5cd579fa89d96b27d56781fb30" +dependencies = [ + "objc2 0.6.5", + "objc2-core-audio-types", + "objc2-core-foundation", + "objc2-core-media", +] + [[package]] name = "objc2-metal" version = "0.2.2" @@ -3672,9 +4289,9 @@ dependencies = [ "bitflags 2.13.2", "block2 0.5.1", "objc2 0.5.3", - "objc2-cloud-kit", - "objc2-core-data", - "objc2-core-image", + "objc2-cloud-kit 0.2.2", + "objc2-core-data 0.2.2", + "objc2-core-image 0.2.2", "objc2-core-location", "objc2-foundation 0.2.2", "objc2-link-presentation", @@ -3732,6 +4349,12 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" +[[package]] +name = "option-ext" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" + [[package]] name = "orbclient" version = "0.3.55" @@ -3768,7 +4391,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -3885,6 +4508,12 @@ dependencies = [ "siphasher", ] +[[package]] +name = "pico-args" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5be167a7af36ee22fe3115051bc51f6e6c7054c9348e28deb4f49bd6f705a315" + [[package]] name = "pin-project" version = "1.1.13" @@ -3933,7 +4562,7 @@ dependencies = [ "libspa", "libspa-sys", "pipewire-sys", - "rustix 1.1.5", + "rustix 1.1.6", ] [[package]] @@ -3995,7 +4624,7 @@ dependencies = [ "concurrent-queue", "hermit-abi", "pin-project-lite", - "rustix 1.1.5", + "rustix 1.1.6", "windows-sys 0.61.2", ] @@ -4042,6 +4671,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6764c3b5dd454e283a30e6dfe78e9b31096d9e32036b5d1eaac7a6119ccb9a24" dependencies = [ "cobs", + "embedded-io 0.4.0", + "embedded-io 0.6.1", "serde", ] @@ -4273,6 +4904,28 @@ dependencies = [ "once_cell", ] +[[package]] +name = "read-fonts" +version = "0.43.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "005c8acf251756c478b0bf402885bfd88a1476020c4c7e6060edc1aa68da38ea" +dependencies = [ + "bytemuck", + "font-types", + "once_cell", +] + +[[package]] +name = "read-fonts" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5a0cf4bb6cbce4c29756270d189a5e400ac05e91192161d83a0bcb6e68492e8" +dependencies = [ + "bytemuck", + "font-types", + "once_cell", +] + [[package]] name = "read-fonts" version = "0.45.1" @@ -4319,6 +4972,16 @@ dependencies = [ "bitflags 2.13.2", ] +[[package]] +name = "redox_users" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60dc65c0ff1a7ae1294b0c67b9f14baf70b644404010370171787bfac1038fc0" +dependencies = [ + "libredox", + "thiserror 2.0.21", +] + [[package]] name = "ref-cast" version = "1.0.27" @@ -4374,6 +5037,21 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832" +[[package]] +name = "resvg" +version = "0.48.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67e3803f97b999e80cbf7c6ecdd07a8102204d92e1633cf48783720c521196bd" +dependencies = [ + "bytemuck", + "log", + "pico-args", + "rgb", + "svgtypes", + "tiny-skia", + "usvg", +] + [[package]] name = "rfd" version = "0.17.2" @@ -4401,6 +5079,15 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "rgb" +version = "0.8.53" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47b34b781b31e5d73e9fbc8689c70551fd1ade9a19e3e28cfec8580a79290cc4" +dependencies = [ + "bytemuck", +] + [[package]] name = "ring" version = "0.17.14" @@ -4465,6 +5152,15 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "roxmltree" +version = "0.21.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9da7f59328b09405b181fee1018925fad50f157afb43c0c0f5c522c256dd5907" +dependencies = [ + "memchr", +] + [[package]] name = "rustc-hash" version = "1.1.0" @@ -4496,20 +5192,20 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.4.15", - "windows-sys 0.59.0", + "windows-sys 0.52.0", ] [[package]] name = "rustix" -version = "1.1.5" +version = "1.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" dependencies = [ "bitflags 2.13.2", "errno", "libc", "linux-raw-sys 0.12.1", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -4519,7 +5215,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2fc84bf7e9aa16c4f2c758f27412dc9841341e16aa682d9c7ac308fe3ee12056" dependencies = [ "once_cell", - "rustix 1.1.5", + "rustix 1.1.6", ] [[package]] @@ -4576,7 +5272,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -4832,6 +5528,15 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" +[[package]] +name = "simplecss" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a9c6883ca9c3c7c90e888de77b7a5c849c779d25d74a1269b0218b14e8b136c" +dependencies = [ + "log", +] + [[package]] name = "siphasher" version = "1.0.4" @@ -4860,6 +5565,16 @@ dependencies = [ "read-fonts 0.41.0", ] +[[package]] +name = "skrifa" +version = "0.47.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "526e654b303ff4ad73a5a40b25de2b3ce3d039c5e3b6da5f89ae6e57004cb40f" +dependencies = [ + "bytemuck", + "read-fonts 0.44.0", +] + [[package]] name = "skrifa" version = "0.48.0" @@ -4935,7 +5650,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -4959,6 +5674,15 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" +[[package]] +name = "strict-num" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731" +dependencies = [ + "float-cmp", +] + [[package]] name = "strsim" version = "0.11.1" @@ -4971,6 +5695,16 @@ version = "2.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" +[[package]] +name = "svgtypes" +version = "0.16.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f12b12995e3638c70618c1facb1ce65302f6a6f706b675f07c58a5d7391120e" +dependencies = [ + "kurbo", + "siphasher", +] + [[package]] name = "syn" version = "2.0.119" @@ -5066,10 +5800,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.4.3", + "getrandom 0.3.4", "once_cell", - "rustix 1.1.5", - "windows-sys 0.61.2", + "rustix 1.1.6", + "windows-sys 0.52.0", ] [[package]] @@ -5114,7 +5848,7 @@ dependencies = [ "image", "rayon", "rmcp", - "rustix 1.1.5", + "rustix 1.1.6", "schemars", "serde", "serde_json", @@ -5179,7 +5913,7 @@ dependencies = [ "image", "processkit", "rayon", - "rustix 1.1.5", + "rustix 1.1.6", "serde", "serde_json", "sysinfo", @@ -5202,6 +5936,7 @@ version = "0.6.1" dependencies = [ "base64 0.22.1", "bytemuck", + "cap-std", "craft-cms", "craft-image-codecs", "craft-materialx", @@ -5210,8 +5945,7 @@ dependencies = [ "craft-psd", "craft-tcraft", "craft-usd", - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5631e99fe126cffb74c673eb458db04299f2bb9b)", - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c376774f15ae7cd3b06a7ac664f01a8645af4b83)", + "craft-zip", "exr", "flate2", "gltf", @@ -5247,7 +5981,7 @@ name = "texturecraft-paint" version = "0.6.1" dependencies = [ "epaint_default_fonts", - "harfrust", + "harfrust 0.12.0", "rayon", "serde", "skrifa 0.44.0", @@ -5287,16 +6021,18 @@ version = "0.6.1" dependencies = [ "base64 0.22.1", "chrono", + "craft-behavior", "craft-dialogs", + "craft-host", "craft-i18n", "craft-image-codecs", "craft-keymap", - "craft-quit", + "craft-theme", "craft-ui", "craft-update", "craft-usd", "craft-window", - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c376774f15ae7cd3b06a7ac664f01a8645af4b83)", + "craft-zip", "eframe", "egui", "egui-phosphor", @@ -5322,7 +6058,7 @@ dependencies = [ "winsafe", "x11rb", "xcap", - "zbus 5.19.0", + "zbus", "zip", ] @@ -5424,6 +6160,32 @@ dependencies = [ "time-core", ] +[[package]] +name = "tiny-skia" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47ffee5eaaf5527f630fb0e356b90ebdec84d5d18d937c5e440350f88c5a91ea" +dependencies = [ + "arrayref", + "arrayvec", + "bytemuck", + "cfg-if", + "log", + "png", + "tiny-skia-path", +] + +[[package]] +name = "tiny-skia-path" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edca365c3faccca67d06593c5980fa6c57687de727a03131735bb85f01fdeeb9" +dependencies = [ + "arrayref", + "bytemuck", + "strict-num", +] + [[package]] name = "tinystr" version = "0.8.5" @@ -5519,8 +6281,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3641d5bbb5349a79e1020a242d251efbc546ad8048d133958323ce9c40a9c9c" dependencies = [ "indexmap", + "serde_core", + "serde_spanned", "toml_datetime", "toml_parser", + "toml_writer", "winnow", ] @@ -5616,7 +6381,7 @@ checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" dependencies = [ "memoffset", "tempfile", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -5708,6 +6473,25 @@ version = "2.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da" +[[package]] +name = "usvg" +version = "0.48.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "977d0a4abdef933f424a99fe09f95576e089b90aebc6f016a3bc813762493e91" +dependencies = [ + "data-url", + "imagesize", + "kurbo", + "log", + "pico-args", + "roxmltree", + "simplecss", + "siphasher", + "strict-num", + "svgtypes", + "tiny-skia-path", +] + [[package]] name = "utf16_iter" version = "1.1.0" @@ -5750,6 +6534,27 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "vectorcraft-geom" +version = "0.18.0" +source = "git+https://github.com/storytold/vectorcraft.git?rev=6b3a6b8788ebcb420d69449199cbdf323888d27e#6b3a6b8788ebcb420d69449199cbdf323888d27e" +dependencies = [ + "kurbo", + "serde", + "thiserror 2.0.21", +] + +[[package]] +name = "vectorcraft-pathops" +version = "0.18.0" +source = "git+https://github.com/storytold/vectorcraft.git?rev=6b3a6b8788ebcb420d69449199cbdf323888d27e#6b3a6b8788ebcb420d69449199cbdf323888d27e" +dependencies = [ + "kurbo", + "linesweeper", + "thiserror 2.0.21", + "vectorcraft-geom", +] + [[package]] name = "vello_common" version = "0.2.0" @@ -5888,7 +6693,7 @@ checksum = "38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078" dependencies = [ "cc", "downcast-rs", - "rustix 1.1.5", + "rustix 1.1.6", "scoped-tls", "smallvec", "wayland-sys", @@ -5901,7 +6706,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073" dependencies = [ "bitflags 2.13.2", - "rustix 1.1.5", + "rustix 1.1.6", "wayland-backend", "wayland-scanner", ] @@ -5923,7 +6728,7 @@ version = "0.31.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a52d18780be9b1314328a3de5f930b73d2200112e3849ca6cb11822793fb34d" dependencies = [ - "rustix 1.1.5", + "rustix 1.1.6", "wayland-client", "xcursor", ] @@ -5985,7 +6790,7 @@ checksum = "0dde9c29be0f723a573977de51ee455bf3dfa03652730a74f9dd3b337e374d75" dependencies = [ "bitflags 2.13.2", "downcast-rs", - "rustix 1.1.5", + "rustix 1.1.6", "wayland-backend", "wayland-scanner", ] @@ -6266,7 +7071,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -6653,7 +7458,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f3fd376f71958b862e7afb20cfe5a22830e1963462f3a17f49d82a6c1d1f42d" dependencies = [ "bitflags 2.13.2", - "windows-sys 0.59.0", + "windows-sys 0.52.0", ] [[package]] @@ -6671,7 +7476,7 @@ dependencies = [ "libc", "log", "os_pipe", - "rustix 1.1.5", + "rustix 1.1.6", "thiserror 2.0.21", "tree_magic_mini", "wayland-backend", @@ -6728,7 +7533,7 @@ dependencies = [ "libc", "libloading", "once_cell", - "rustix 1.1.5", + "rustix 1.1.6", "x11rb-protocol", ] @@ -6740,11 +7545,10 @@ checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd" [[package]] name = "xcap" -version = "0.9.10" +version = "0.9.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e833d39f662982a09608f2550fd4036725f98d78738e40fa7206a26258b06384" +checksum = "da270fd7c8581d43d731cb690bcc791fc0a7b3bc96e131a4b6552d0379640a9e" dependencies = [ - "ashpd", "dispatch2", "image", "libwayshot-xcap", @@ -6759,7 +7563,6 @@ dependencies = [ "objc2-foundation 0.3.2", "percent-encoding", "pipewire", - "pollster 1.0.1", "rand", "scopeguard", "serde", @@ -6768,6 +7571,7 @@ dependencies = [ "widestring", "windows", "xcb", + "zbus", ] [[package]] @@ -6864,7 +7668,7 @@ dependencies = [ "hex", "libc", "ordered-stream", - "rustix 1.1.5", + "rustix 1.1.6", "serde", "serde_repr", "tracing", @@ -6872,38 +7676,11 @@ dependencies = [ "uuid", "windows-sys 0.61.2", "winnow", - "zbus_macros 5.19.0", + "zbus_macros", "zbus_names", "zvariant", ] -[[package]] -name = "zbus" -version = "6.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b4aae740b23927ceabed962431abab2cdefb9f7f885e5bbab062da09bf580e4" -dependencies = [ - "async-trait", - "bitflags 2.13.2", - "endi", - "futures-core", - "hex", - "libc", - "ordered-stream", - "rustix 1.1.5", - "serde", - "serde_repr", - "socket2", - "uds_windows", - "uuid", - "windows-sys 0.61.2", - "winnow", - "zbus_macros 6.3.0", - "zbus_utils", - "zcheapstr", - "zruntime", -] - [[package]] name = "zbus-lockstep" version = "0.5.2" @@ -6943,18 +7720,6 @@ dependencies = [ "zvariant_utils", ] -[[package]] -name = "zbus_macros" -version = "6.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37c9dd4beaf145c16fcb2902862f50da86e54aed13dd368ddf64a1d17e6b8529" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.9", - "zbus_utils", -] - [[package]] name = "zbus_names" version = "4.3.4" @@ -6966,19 +7731,6 @@ dependencies = [ "zvariant", ] -[[package]] -name = "zbus_utils" -version = "6.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af55e52da295311b368c45bcae221f020e28e97a2420360170ce389218e76ec7" -dependencies = [ - "proc-macro2", - "quote", - "serde", - "syn 3.0.9", - "winnow", -] - [[package]] name = "zbus_xml" version = "5.2.1" @@ -7142,19 +7894,6 @@ dependencies = [ "simd-adler32", ] -[[package]] -name = "zruntime" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce6a55d4f521760475a30f7b96779508fe8c40dc834478709454dd1d5f0ebc72" -dependencies = [ - "futures-core", - "futures-io", - "rustix 1.1.5", - "socket2", - "windows-sys 0.61.2", -] - [[package]] name = "zune-core" version = "0.5.3" diff --git a/Cargo.toml b/Cargo.toml index de6fc98d..2b52c050 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,7 +10,7 @@ edition = "2024" license = "MIT OR Apache-2.0" [workspace.dependencies] -craft-usd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3" } +craft-usd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } # internal texturecraft-core = { path = "crates/core" } texturecraft-texel = { path = "crates/texel" } @@ -41,7 +41,7 @@ skrifa = { version = "0.44", default-features = false, features = ["std"] } epaint_default_fonts = "0.37" log = "0.4" image = { version = "0.25", default-features = false, features = ["png", "jpeg", "tga", "tiff", "exr", "hdr", "bmp", "webp"] } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } half = "2" exr = { version = "1.73", default-features = false } eframe = { version = "0.37", default-features = false } @@ -64,46 +64,50 @@ rustix = { version = "1", default-features = false, features = ["std", "fs", "pr # Shared Craft egui components (widget palette, icon buttons, panel docking): storytold/craft-libs, # MIT OR Apache-2.0, pinned to one rev. # Shared catalog lookup, pinned with the other Craft libraries. -craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } -craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["serde"] } -craft-materialx = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } -craft-tcraft = { git = "https://github.com/storytold/craft-libs", rev = "c376774f15ae7cd3b06a7ac664f01a8645af4b83" } -# Isolated aligned writer; existing archive readers retain their pin and behavior. -craft-zip-usdz = { package = "craft-zip", git = "https://github.com/storytold/craft-libs", rev = "5631e99fe126cffb74c673eb458db04299f2bb9b" } -craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "c376774f15ae7cd3b06a7ac664f01a8645af4b83" } -craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "a20dfd1623709b0bd9830106d3a92a1a443902e3", default-features = false, features = ["stl", "ply", "fbx", "obj", "gltf", "dae", "abc"] } -craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "7a7a18cb40ac4cd5fca29c0dc224ac5178d40a89" } +craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } +craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } +craft-behavior = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } +craft-materialx = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } +craft-tcraft = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } +craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } +craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", default-features = false, features = ["stl", "ply", "fbx", "obj", "gltf", "dae", "abc"] } +craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } # Who draws the window frame, and the app-drawn strip as the title bar (crates/ui-egui/src/titlebar.rs). -craft-window = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["egui"] } +craft-window = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] } # Release checks, the update prompt and the update helper (crates/ui-egui/src/updates_ui.rs). -craft-update = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["egui"] } +craft-update = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] } # File dialogs that never block the frame (crates/ui-egui/src/file_dialogs.rs). -craft-dialogs = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } +craft-dialogs = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } # Shortcut chords, lookup and dispatch (crates/ui-egui/src/keymap.rs). -craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["egui"] } -# Quitting the macOS way instead of closing the window (crates/ui-egui/src/windows.rs). -craft-quit = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["egui"] } +craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["egui"] } # The macOS app menu whose Quit asks about unsaved changes (apps/texturecraft/src/main.rs). -craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } +craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } +# The UI runtime's host: who the app is to the framework's dialogs (crates/ui-egui/src/framework.rs). +craft-host = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } +# The theme mode the app hands the runtime (crates/ui-egui/src/framework.rs). +craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } # egui 0.37 and winit: the suite's forks (storytold/egui, storytold/winit), as craft-libs pins them. [patch.crates-io] -ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -egui = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -egui-winit = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -eframe = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } +ecolor = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +emath = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +epaint = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +egui = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +eframe = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" } # egui-phosphor has no release for egui 0.37 (vendor/egui-phosphor/VENDORED.md). egui-phosphor = { path = "vendor/egui-phosphor" } [workspace.lints.rust] unsafe_code = "forbid" +# cargo-llvm-cov always sets `cfg(coverage)`: a coverage build bakes on the CPU (texturecraft-engine +# picks no GPU tracer there) and the cfg would otherwise trip unexpected_cfgs under -D warnings. +unexpected_cfgs = { level = "warn", check-cfg = ['cfg(coverage)'] } [workspace.lints.clippy] dbg_macro = "warn" diff --git a/README.md b/README.md index 345c32c1..76dfb0ea 100644 --- a/README.md +++ b/README.md @@ -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--freebsd-x86_64.tar.gz` | +| aarch64 (ARM64) | `texturecraft--freebsd-aarch64.tar.gz` | ### Web (WebAssembly) diff --git a/ROADMAP.md b/ROADMAP.md index cb114376..7dbebfbb 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -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 | diff --git a/apps/texturecraft-cli/build.rs b/apps/texturecraft-cli/build.rs index 37e0bd12..d58a4323 100644 --- a/apps/texturecraft-cli/build.rs +++ b/apps/texturecraft-cli/build.rs @@ -1,2 +1,71 @@ -// The same build provenance and Windows icon/VERSIONINFO as the app; see that file. -include!("../texturecraft/build.rs"); +// Provenance for the headless CLI: the same commit and date variables as the app, and (Windows +// only) its own icon and VERSIONINFO into `texturecraft-cli.exe`. +// +// This is deliberately not an `include!` of the app's build script: that one resolves a `#[path]` +// submodule and reads the Nightly channel, neither of which a CLI build has any use for, and a +// module path inside an included script is resolved from the included file, not from here. + +use std::process::Command; + +const ICON: &str = "../../assets/app-icon/texturecraft.ico"; + +fn main() { + println!("cargo:rerun-if-changed=build.rs"); + println!("cargo:rerun-if-changed={ICON}"); + for var in ["TEXTURECRAFT_BUILD_SHA", "TEXTURECRAFT_BUILD_DATE", "TEXTURECRAFT_REQUIRE_WINRES", "SOURCE_DATE_EPOCH"] { + println!("cargo:rerun-if-env-changed={var}"); + } + println!("cargo:rustc-env=TEXTURECRAFT_BUILD_SHA={}", env_or("TEXTURECRAFT_BUILD_SHA", git_sha)); + println!("cargo:rustc-env=TEXTURECRAFT_BUILD_DATE={}", env_or("TEXTURECRAFT_BUILD_DATE", today)); + + if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") { + windows_resources(); + } +} + +fn env_or(var: &str, fallback: fn() -> Option) -> String { + std::env::var(var).ok().map(|v| v.trim().to_owned()).filter(|v| !v.is_empty()).or_else(fallback).unwrap_or_default() +} + +fn git_sha() -> Option { + let out = Command::new("git").args(["rev-parse", "HEAD"]).output().ok().filter(|o| o.status.success())?; + let sha = String::from_utf8(out.stdout).ok()?.trim().to_owned(); + (sha.len() >= 7 && sha.bytes().all(|b| b.is_ascii_hexdigit())).then_some(sha) +} + +/// UTC date of `SOURCE_DATE_EPOCH`, or of now. +fn today() -> Option { + let secs = match std::env::var("SOURCE_DATE_EPOCH") { + Ok(v) => v.trim().parse::().ok()?, + Err(_) => std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).ok()?.as_secs(), + }; + // Days since 1970-01-01 to a civil date (Howard Hinnant's algorithm, proleptic Gregorian). + let z = i64::try_from(secs / 86_400).ok()? + 719_468; + let era = z.div_euclid(146_097); + let doe = z.rem_euclid(146_097); + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let day = doy - (153 * mp + 2) / 5 + 1; + let month = if mp < 10 { mp + 3 } else { mp - 9 }; + let year = yoe + era * 400 + i64::from(month <= 2); + Some(format!("{year:04}-{month:02}-{day:02}")) +} + +fn windows_resources() { + let mut res = winresource::WindowsResource::new(); + res.set_icon(ICON) + .set("ProductName", "TextureCraft") + .set("FileDescription", "TextureCraft command-line tool") + .set("CompanyName", "Learning Machines LLC") + .set("LegalCopyright", "Copyright (c) the TextureCraft contributors. MIT OR Apache-2.0.") + .set("OriginalFilename", "texturecraft-cli.exe") + .set("InternalName", "texturecraft-cli"); + if let Err(e) = res.compile() { + if std::env::var_os("TEXTURECRAFT_REQUIRE_WINRES").is_some() { + println!("cargo::error=embedding Windows resources into texturecraft-cli.exe failed: {e}"); + } else { + println!("cargo:warning=texturecraft-cli.exe built without icon/version resources: {e}"); + } + } +} diff --git a/apps/texturecraft-cli/src/main.rs b/apps/texturecraft-cli/src/main.rs index f15dc209..80069d9d 100644 --- a/apps/texturecraft-cli/src/main.rs +++ b/apps/texturecraft-cli/src/main.rs @@ -120,8 +120,18 @@ fn version() -> String { } } +/// The desktop app's Nightly launch options. The CLI never takes them: a Nightly install ships the +/// GUI only, and a script that passes them to the CLI has the wrong program. +fn is_launch_profile_flag(arg: &str) -> bool { + arg == "--launch-profile" || arg == "--profile-root" || arg.starts_with("--launch-profile=") || arg.starts_with("--profile-root=") +} + fn main() { let args: Vec = std::env::args().skip(1).collect(); + if let Some(flag) = args.iter().find(|arg| is_launch_profile_flag(arg.as_str())) { + eprintln!("texturecraft-cli: `{flag}` is a TextureCraft desktop launch option, not a CLI argument"); + std::process::exit(2); + } let code = match args.first().map(String::as_str) { None => { eprint!("{USAGE}"); @@ -270,21 +280,39 @@ fn run(a: &Args) -> R { } } -fn batch(a: &Args) -> R { - let path = a.pos(0, "")?; - 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, "")?; + 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, 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(()), } } diff --git a/apps/texturecraft-cli/tests/cli.rs b/apps/texturecraft-cli/tests/cli.rs index ce209c3e..6bef0017 100644 --- a/apps/texturecraft-cli/tests/cli.rs +++ b/apps/texturecraft-cli/tests/cli.rs @@ -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"); diff --git a/apps/texturecraft-web/src/web.rs b/apps/texturecraft-web/src/web.rs index cb697e0b..99dfa223 100644 --- a/apps/texturecraft-web/src/web.rs +++ b/apps/texturecraft-web/src/web.rs @@ -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; diff --git a/apps/texturecraft/Cargo.toml b/apps/texturecraft/Cargo.toml index e0c2f660..7f5ee538 100644 --- a/apps/texturecraft/Cargo.toml +++ b/apps/texturecraft/Cargo.toml @@ -30,7 +30,8 @@ ron = "0.12" # borderless (src/window_frame.rs; winsafe is MIT, User32 only). [target.'cfg(windows)'.dependencies] winit = { version = "0.30", default-features = false } -winsafe = { version = "0.0.29", default-features = false, features = ["user"] } +# `shell` carries SetCurrentProcessExplicitAppUserModelID, the Nightly taskbar identity (src/process_identity.rs). +winsafe = { version = "0.0.29", default-features = false, features = ["user", "shell"] } # The update helper is a copy of this program (`main`). craft-update = { workspace = true } diff --git a/apps/texturecraft/build.rs b/apps/texturecraft/build.rs index c77d91bd..9f712207 100644 --- a/apps/texturecraft/build.rs +++ b/apps/texturecraft/build.rs @@ -2,31 +2,78 @@ // // Shared by `texturecraft` and `texturecraft-cli` (whose build.rs `include!`s this file). // +// - Sets `TEXTURECRAFT_VERSION` for `env!`: the prepared Nightly feed identity when +// `TEXTURECRAFT_BUILD_CHANNEL=nightly-v1`, else the workspace package version. A Nightly build +// without a well-formed `TEXTURECRAFT_VERSION` fails rather than falling back to the Cargo +// version, so an archive can never carry the wrong identity. // - Always sets `TEXTURECRAFT_BUILD_SHA` (full git commit) and `TEXTURECRAFT_BUILD_DATE` // (`YYYY-MM-DD`, UTC) for `env!`. They come from the same-named environment variables (CI and // packaging/env.sh set them), else from `git` and the clock (`SOURCE_DATE_EPOCH` wins for // reproducible builds); either is an empty string when unknown, so source tarballs, wasm and // offline builds still compile. Without the env vars the commit is read when this script runs, // so a local build can show a stale commit; release builds always set the variable. -// - Windows targets only: embeds assets/app-icon/texturecraft.ico and VERSIONINFO into the exe. +// - Windows targets only: embeds the flavor's `assets/app-icon/*.ico` and VERSIONINFO into the exe. // A missing resource compiler is a warning, so a cross-compile still links, unless // `TEXTURECRAFT_REQUIRE_WINRES=1` (set by packaging/windows/package.ps1) makes it an error. -use std::process::Command; +#[path = "src/build_channel.rs"] +mod build_channel; -const ICON: &str = "../../assets/app-icon/texturecraft.ico"; +use std::process::Command; fn main() { println!("cargo:rerun-if-changed=build.rs"); - println!("cargo:rerun-if-changed={ICON}"); - for var in ["TEXTURECRAFT_BUILD_SHA", "TEXTURECRAFT_BUILD_DATE", "TEXTURECRAFT_REQUIRE_WINRES", "SOURCE_DATE_EPOCH"] { + println!("cargo:rerun-if-changed=src/build_channel.rs"); + for icon in [build_channel::windows_icon_path(false), build_channel::windows_icon_path(true)] { + println!("cargo:rerun-if-changed={icon}"); + } + for var in [ + "TEXTURECRAFT_BUILD_SHA", + "TEXTURECRAFT_BUILD_DATE", + "TEXTURECRAFT_BUILD_CHANNEL", + "TEXTURECRAFT_VERSION", + "TEXTURECRAFT_OVERRIDE_VERSION", + "TEXTURECRAFT_REQUIRE_WINRES", + "SOURCE_DATE_EPOCH", + ] { println!("cargo:rerun-if-env-changed={var}"); } + println!("cargo:rustc-check-cfg=cfg(texturecraft_nightly_v1)"); + let nightly = match std::env::var("TEXTURECRAFT_BUILD_CHANNEL").as_deref() { + Ok("nightly-v1") => { + println!("cargo:rustc-cfg=texturecraft_nightly_v1"); + true + } + // An empty value (an unset CI input) means the default stable build. + Ok("stable" | "") | Err(std::env::VarError::NotPresent) => false, + _ => { + eprintln!("unsupported TEXTURECRAFT_BUILD_CHANNEL (expected stable or nightly-v1)"); + std::process::exit(1); + } + }; + // `TEXTURECRAFT_VERSION` is the feed identity the workflow exports; the packaging scripts + // (packaging/env.sh, nightly-common.sh, linux/package.sh) spell the same value + // `TEXTURECRAFT_OVERRIDE_VERSION`, so both name the version the binary reports. + let requested = ["TEXTURECRAFT_VERSION", "TEXTURECRAFT_OVERRIDE_VERSION"] + .into_iter() + .find_map(|name| std::env::var(name).ok().map(|value| value.trim().to_owned()).filter(|value| !value.is_empty())); + let built_version = if nightly { + match requested { + Some(version) if build_channel::is_nightly_version(&version) => version, + _ => { + eprintln!("nightly-v1 requires an explicit prepared feed identity in TEXTURECRAFT_VERSION"); + std::process::exit(1); + } + } + } else { + std::env::var("CARGO_PKG_VERSION").unwrap_or_default() + }; + println!("cargo:rustc-env=TEXTURECRAFT_VERSION={built_version}"); println!("cargo:rustc-env=TEXTURECRAFT_BUILD_SHA={}", env_or("TEXTURECRAFT_BUILD_SHA", git_sha)); println!("cargo:rustc-env=TEXTURECRAFT_BUILD_DATE={}", env_or("TEXTURECRAFT_BUILD_DATE", today)); if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") { - windows_resources(); + windows_resources(nightly, &built_version); } } @@ -59,17 +106,27 @@ fn today() -> Option { Some(format!("{year:04}-{month:02}-{day:02}")) } -fn windows_resources() { +fn windows_resources(nightly: bool, built_version: &str) { let name = std::env::var("CARGO_PKG_NAME").unwrap_or_else(|_| "texturecraft".into()); - let description = if name.ends_with("-cli") { "TextureCraft command-line tool" } else { "TextureCraft 3D texture painter" }; + let description = if name.ends_with("-cli") { + if nightly { "TextureCraft Nightly command-line tool" } else { "TextureCraft command-line tool" } + } else if nightly { + "TextureCraft Nightly 3D texture painter" + } else { + "TextureCraft 3D texture painter" + }; let mut res = winresource::WindowsResource::new(); - res.set_icon(ICON) - .set("ProductName", "TextureCraft") + res.set_icon(build_channel::windows_icon_path(nightly)) + .set("ProductName", if nightly { "TextureCraft Nightly" } else { "TextureCraft" }) .set("FileDescription", description) .set("CompanyName", "Learning Machines LLC") .set("LegalCopyright", "Copyright (c) the TextureCraft contributors. MIT OR Apache-2.0.") .set("OriginalFilename", &format!("{name}.exe")) .set("InternalName", &name); + if nightly { + // The Launcher checks the PE ProductVersion against the exact feed identity, not FileVersion. + res.set("ProductVersion", built_version); + } if let Err(e) = res.compile() { if std::env::var_os("TEXTURECRAFT_REQUIRE_WINRES").is_some() { println!("cargo::error=embedding Windows resources into {name}.exe failed: {e}"); diff --git a/apps/texturecraft/src/build_channel.rs b/apps/texturecraft/src/build_channel.rs new file mode 100644 index 00000000..ebfc4a2a --- /dev/null +++ b/apps/texturecraft/src/build_channel.rs @@ -0,0 +1,62 @@ +//! The build-time nightly identity shared by the build script and its pure regression tests. +//! +//! `build.rs` includes this file (`#[path = "src/build_channel.rs"]`) and the app compiles it for +//! the same checks, so the icon and the version shape cannot drift apart between them. + +/// `X.Y.Z-nightly.YYYYMMDD...g`, the Launcher's immutable feed identity. +pub fn is_nightly_version(version: &str) -> bool { + let Some((base, suffix)) = version.split_once("-nightly.") else { return false }; + let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()); + let base: Vec<_> = base.split('.').collect(); + let parts: Vec<_> = suffix.split('.').collect(); + base.len() == 3 + && base.iter().all(|s| digits(s)) + && parts.len() == 4 + && parts[0].len() == 8 + && digits(parts[0]) + && digits(parts[1]) + && digits(parts[2]) + && parts[3].strip_prefix('g').is_some_and(|sha| sha.len() == 12 && sha.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))) +} + +/// The Windows icon embedded in the executable: the nightly art only in a nightly build. +pub fn windows_icon_path(nightly: bool) -> &'static str { + if nightly { "../../assets/app-icon/texturecraft-nightly.ico" } else { "../../assets/app-icon/texturecraft.ico" } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn windows_resource_uses_the_flavor_specific_icon_without_changing_stable() { + assert_eq!(windows_icon_path(false), "../../assets/app-icon/texturecraft.ico"); + assert_eq!(windows_icon_path(true), "../../assets/app-icon/texturecraft-nightly.ico"); + } + + #[test] + fn explicit_feed_identity_is_required_for_a_nightly_build() { + assert!(is_nightly_version("0.23.1-nightly.20261120.17.1.gabcdef012345")); + for invalid in [ + "", + "0.23.1", + "0.23.1-nightly", + "0.23.1-nightly.20261120", + "0.23.1-nightly.20261120.17.1.gABCDEF012345", + "0.23.1-nightly.20261120.17.1.gabcdef012345\n", + ] { + assert!(!is_nightly_version(invalid), "{invalid:?}"); + } + } + + #[test] + fn version_cannot_inject_a_path_or_an_extra_build_directive() { + for invalid in [ + "../0.23.1-nightly.20261120.1.1.gabcdef012345", + "0.23.1-nightly.20261120.1.1.gabcdef012345/other", + "0.23.1-nightly.20261120.1.1.gabcdef012345\ncargo:rustc-cfg=other", + ] { + assert!(!is_nightly_version(invalid)); + } + } +} diff --git a/apps/texturecraft/src/build_flavor.rs b/apps/texturecraft/src/build_flavor.rs new file mode 100644 index 00000000..294f1e19 --- /dev/null +++ b/apps/texturecraft/src/build_flavor.rs @@ -0,0 +1,94 @@ +//! The build-time channel, which is distinct from a launch selector: no runtime environment can +//! promote a stable build into the Nightly one. + +use crate::launch_profile::Profile; +use std::ffi::OsString; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BuildFlavor { + Stable, + NightlyV1, +} + +/// `TEXTURECRAFT_BUILD_CHANNEL=nightly-v1` at compile time (`build.rs`). +pub const COMPILED: BuildFlavor = if cfg!(texturecraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable }; + +/// The version this binary was built as: the prepared feed identity in a nightly build, else the +/// workspace version (`build.rs` bakes it so both flavors read it the same way). +pub const BUILT_VERSION: &str = env!("TEXTURECRAFT_VERSION"); + +/// A nightly build starts only with its profile, and a stable build only without one. +pub fn require_profile(flavor: BuildFlavor, profile: &Profile) -> Result<(), String> { + match (flavor, profile.is_nightly()) { + (BuildFlavor::NightlyV1, false) => Err("Open TextureCraft Nightly from ArtCraft Launcher".into()), + (BuildFlavor::Stable, true) => Err("This is a stable TextureCraft build; nightly-v1 requires the nightly build".into()), + _ => Ok(()), + } +} + +/// A refused nightly start explains itself in a native dialog: a release Windows build has no +/// console, and a Dock launch on macOS has none either. +pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool { + desktop_session && flavor == BuildFlavor::NightlyV1 +} + +/// `--version` or `-V` alone; a file called `--version` after `--` is never a query. +pub fn version_query(args: &[OsString]) -> bool { + matches!(args, [arg] if arg == "--version" || arg == "-V") +} + +/// The line `--version` prints: ` (nightly-v1)` in a nightly build, exactly as the +/// Launcher and the release smoke test read it. +pub fn version(flavor: BuildFlavor) -> String { + match flavor { + BuildFlavor::Stable => format!("TextureCraft {BUILT_VERSION}"), + BuildFlavor::NightlyV1 => format!("TextureCraft {BUILT_VERSION} (nightly-v1)"), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_a_nightly_desktop_refusal_requests_a_native_dialog() { + assert!(needs_native_error(BuildFlavor::NightlyV1, true)); + assert!(!needs_native_error(BuildFlavor::NightlyV1, false)); + assert!(!needs_native_error(BuildFlavor::Stable, true)); + assert!(!needs_native_error(BuildFlavor::Stable, false)); + } + + #[test] + fn nightly_build_without_a_profile_is_refused_before_startup() { + let started = std::cell::Cell::new(false); + let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true)); + assert!(result.unwrap_err().contains("ArtCraft Launcher")); + assert!(!started.get()); + } + + #[test] + fn stable_and_nightly_flavors_accept_only_their_own_profile() { + let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root")); + assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok()); + assert!(require_profile(BuildFlavor::Stable, &nightly).is_err()); + assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok()); + } + + #[test] + fn the_nightly_version_line_is_exact_and_says_its_channel() { + let nightly = version(BuildFlavor::NightlyV1); + assert!(nightly.starts_with("TextureCraft "), "{nightly}"); + assert!(nightly.ends_with(" (nightly-v1)"), "{nightly}"); + assert_eq!(nightly, format!("TextureCraft {} (nightly-v1)", BUILT_VERSION)); + assert_eq!(version(BuildFlavor::Stable), format!("TextureCraft {BUILT_VERSION}")); + } + + #[test] + fn only_a_bare_version_flag_is_a_query() { + assert!(version_query(&["--version".into()])); + assert!(version_query(&["-V".into()])); + assert!(!version_query(&["--".into(), "--version".into()])); + assert!(!version_query(&["--version".into(), "--version".into()])); + assert!(!version_query(&[])); + } +} diff --git a/apps/texturecraft/src/launch_profile.rs b/apps/texturecraft/src/launch_profile.rs new file mode 100644 index 00000000..84f5061f --- /dev/null +++ b/apps/texturecraft/src/launch_profile.rs @@ -0,0 +1,217 @@ +//! The Launcher's nightly-v1 bootstrap, selected before logging, updates, fonts or saved state. +//! Stable launches keep their arguments and directory policy unchanged, and no environment is +//! mutated: the profile is a value this process reads, not a variable it exports. + +use std::ffi::OsString; +use std::path::{Component, Path, PathBuf}; +use std::sync::OnceLock; + +pub const VERSION: &str = "nightly-v1"; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Profile { + Stable, + NightlyV1(PathBuf), +} + +impl Profile { + pub fn is_nightly(&self) -> bool { + matches!(self, Self::NightlyV1(_)) + } + + pub fn root(&self) -> Option<&Path> { + match self { + Self::Stable => None, + Self::NightlyV1(root) => Some(root), + } + } +} + +#[derive(Debug, PartialEq, Eq)] +pub struct Launch { + pub profile: Profile, + pub args: Vec, +} + +static PROFILE: OnceLock = OnceLock::new(); + +pub fn current() -> &'static Profile { + PROFILE.get().unwrap_or(&Profile::Stable) +} + +pub fn install(profile: Profile) -> Result<(), String> { + PROFILE.set(profile).map_err(|_| "the launch profile was already selected".into()) +} + +/// Recognize only the agreed literal selector/root pair before `--`. Everything after it is a +/// file, even when it looks like a profile flag. No filesystem or startup hook runs here. +pub fn parse(args: Vec) -> Result { + let mut selector = None; + let mut root = None; + let mut other = Vec::new(); + let mut files = Vec::new(); + let mut iter = args.iter(); + let mut delimiter = false; + while let Some(arg) = iter.next() { + if arg == "--" { + delimiter = true; + files.extend(iter.cloned()); + break; + } + if arg == "--launch-profile" || arg == "--profile-root" { + let slot = if arg == "--launch-profile" { &mut selector } else { &mut root }; + if slot.is_some() { + return Err("the profile selector and root must each occur exactly once".into()); + } + let value = iter.next().filter(|v| !v.is_empty()).ok_or("the profile selector/root needs a value")?; + if value.to_string_lossy().starts_with("--") { + return Err("the profile selector/root needs a value".into()); + } + *slot = Some(value.clone()); + } else if arg.to_string_lossy().starts_with("--launch-profile=") || arg.to_string_lossy().starts_with("--profile-root=") { + return Err("the nightly protocol requires separate literal selector/root argument tokens".into()); + } else { + other.push(arg.clone()); + } + } + match (selector, root) { + (None, None) => Ok(Launch { profile: Profile::Stable, args }), + (Some(version), Some(root)) if version == VERSION => { + if !delimiter || !other.is_empty() { + return Err("nightly-v1 accepts only its selector/root followed by -- and file names".into()); + } + let root = PathBuf::from(root); + if !root.is_absolute() || root.components().any(|c| matches!(c, Component::ParentDir)) { + return Err("the nightly profile root must be absolute and contain no parent traversal".into()); + } + Ok(Launch { profile: Profile::NightlyV1(root), args: std::iter::once(OsString::from("--")).chain(files).collect() }) + } + (Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".into()), + _ => Err("--launch-profile and --profile-root must be supplied together".into()), + } +} + +/// The Launcher's version check: the selector/root pair followed by exactly `--version` (or `-V`), +/// answered like a plain version query. Only [`parse`]'s lexical checks apply; the root is never +/// validated or touched, and `-- --version` stays a file name. +pub fn version_query(args: &[OsString]) -> bool { + let Some((last, pair)) = args.split_last() else { return false }; + if last != "--version" && last != "-V" { + return false; + } + let lexical = pair.iter().cloned().chain(std::iter::once(OsString::from("--"))).collect(); + matches!(parse(lexical), Ok(Launch { profile: Profile::NightlyV1(_), args }) if args.len() == 1) +} + +/// Validation finishes before the caller's first startup effect. Stable never calls the nightly +/// root validator, so its old directory resolution stays unchanged. +pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result) -> Result { + if let Profile::NightlyV1(root) = &launch.profile { + launch.profile = Profile::NightlyV1(validate(root)?); + } + Ok(launch) +} + +/// Resolve the selected private root before the caller's first startup effect. +pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option, exe: Option<&Path>) -> Result { + crate::profile_root::validate(root, env, exe, crate::profile_root::ensure_writable) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::cell::Cell; + + fn args(values: &[&str]) -> Vec { + values.iter().map(OsString::from).collect() + } + + fn absolute() -> &'static str { + if cfg!(windows) { r"C:\NightlyData\profiles\texturecraft" } else { "/nightly-data/profiles/texturecraft" } + } + + fn nightly() -> Vec { + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"]) + } + + #[test] + fn stable_arguments_and_directory_policy_are_unchanged() { + for argv in [args(&[]), args(&["model.glb"]), args(&["--gpu", "nvidia"]), args(&["--", "--launch-profile", "model.glb"])] { + let launch = prepare(parse(argv.clone()).unwrap(), |_| panic!("stable must never validate a nightly root")).unwrap(); + assert_eq!(launch, Launch { profile: Profile::Stable, args: argv }); + } + } + + #[test] + fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() { + let mut argv = nightly(); + argv.extend(args(&["--profile-root", "model with spaces.glb"])); + let launch = parse(argv).unwrap(); + assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute()))); + assert_eq!(launch.args, args(&["--", "--profile-root", "model with spaces.glb"])); + } + + #[test] + fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() { + for argv in [ + args(&["--launch-profile", VERSION]), + args(&["--profile-root", absolute()]), + args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]), + args(&["--launch-profile", VERSION, "--launch-profile", VERSION, "--profile-root", absolute(), "--"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--profile-root", absolute(), "--"]), + args(&["--launch-profile", VERSION, "--profile-root", "relative", "--"]), + args(&["--launch-profile", VERSION, "--profile-root", "", "--"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--gpu", "nvidia", "--"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute()]), + args(&["--launch-profile=nightly-v1", "--profile-root", absolute(), "--"]), + args(&["--launch-profile", VERSION, "--profile-root=/nightly-data/profiles/texturecraft", "--"]), + ] { + assert!(parse(argv.clone()).is_err(), "{argv:?}"); + } + } + + #[test] + fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() { + let pair = &["--launch-profile", VERSION, "--profile-root", absolute()]; + let reversed = &["--profile-root", absolute(), "--launch-profile", VERSION]; + for flag in ["--version", "-V"] { + for form in [pair, reversed] { + let mut argv = args(form); + argv.push(flag.into()); + assert!(version_query(&argv), "{argv:?}"); + } + } + for argv in [ + args(&["--version"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--version"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--gpu", "nvidia", "--version"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--version"]), + args(&["--version", "--launch-profile", VERSION, "--profile-root", absolute()]), + args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--version"]), + args(&["--launch-profile", VERSION, "--profile-root", "relative", "--version"]), + args(&["--launch-profile", VERSION, "--version"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--help"]), + ] { + assert!(!version_query(&argv), "{argv:?}"); + } + // Outside the query the strict protocol still refuses the version flag. + assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err()); + } + + #[test] + fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() { + let reached = Cell::new(false); + let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".into())).map(|_| reached.set(true)); + assert!(result.is_err()); + assert!(!reached.get()); + } + + #[test] + fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() { + let checked = PathBuf::from(absolute()).join("checked"); + let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap(); + assert_eq!(launch.profile.root(), Some(checked.as_path())); + assert!(launch.profile.is_nightly()); + } +} diff --git a/apps/texturecraft/src/main.rs b/apps/texturecraft/src/main.rs index 7787e1cf..4d48c210 100644 --- a/apps/texturecraft/src/main.rs +++ b/apps/texturecraft/src/main.rs @@ -5,11 +5,22 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#[cfg(test)] +mod build_channel; +mod build_flavor; mod control_server; mod gpu; +mod launch_profile; +mod nightly_session; +mod process_identity; +mod profile_root; mod window_frame; +use std::ffi::OsString; + +use launch_profile::Profile; use texturecraft_engine::Session; +use texturecraft_ui_egui::os_window::{self, LaunchIdentity}; use texturecraft_ui_egui::titlebar::TitleBar; use texturecraft_ui_egui::ui_state_store; use texturecraft_ui_egui::{TextureCraftApp, UiState}; @@ -17,14 +28,25 @@ use texturecraft_ui_egui::{TextureCraftApp, UiState}; /// The app name eframe keeps the settings under (`eframe::storage_dir`). const APP_NAME: &str = "TextureCraft"; +/// The data folder Dylan's #801 packaging lets a Stable wrapper set. A Nightly launch never reads +/// it: its profile arrives as the Launcher's literal selector/root pair, and nothing else. +const DATA_DIR_ENV: &str = "TEXTURECRAFT_DATA_DIR"; + /// The window's size when it opens, in points. const DEFAULT_SIZE: [f32; 2] = [1600.0, 960.0]; /// The smallest size the window can be resized to, in points. const MIN_SIZE: [f32; 2] = [960.0, 600.0]; const ICON_PNG: &[u8] = include_bytes!("../../../assets/app-icon/hicolor/256x256/apps/ai.storyteller.texturecraft.png"); +/// The Nightly window icon: the same artwork on the deeper background the package icon uses. +const NIGHTLY_ICON_PNG: &[u8] = include_bytes!("../../../assets/app-icon/texturecraft-nightly.png"); +/// The version line: a Nightly build names its exact feed identity and channel, and every other +/// build keeps the workspace version with the commit and date it was built from. fn version() -> String { + if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 { + return build_flavor::version(build_flavor::COMPILED); + } let sha = env!("TEXTURECRAFT_BUILD_SHA"); let short = sha.get(..7).unwrap_or(sha); let date = env!("TEXTURECRAFT_BUILD_DATE"); @@ -44,15 +66,23 @@ struct Args { power_pref: Option, } -fn parse_args() -> Result, String> { - parse_args_from(std::env::args().skip(1)) -} - fn parse_args_from>(it: I) -> Result, String> { let mut args = Args { file: None, control: None, empty: false, gpu: None, power_pref: None }; let mut it = it.into_iter(); + // Everything after `--` is a file, even when it looks like an option: the Launcher's nightly + // protocol passes the selected file that way (and a file may be called `--version`). + let mut after_delimiter = false; while let Some(a) = it.next() { + if after_delimiter { + // A Launcher hand-off may carry more than one file. Opening the first one beats a + // silent exit on a Windows build, which has no console to show the refusal on. + if args.file.is_none() { + args.file = Some(a); + } + continue; + } match a.as_str() { + "--" => after_delimiter = true, "--version" | "-V" => { println!("{}", version()); return Ok(None); @@ -119,7 +149,8 @@ fn initial_session(args: &Args) -> Session { } fn icon() -> Option { - let img = craft_image_codecs::decode(ICON_PNG).ok()?; + let png = if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 { NIGHTLY_ICON_PNG } else { ICON_PNG }; + let img = craft_image_codecs::decode(png).ok()?; Some(egui::IconData { rgba: img.to_rgba8(), width: img.width(), height: img.height() }) } @@ -134,25 +165,53 @@ fn set_taskbar_icon(w: &winit::window::Window) { } } +/// Directory for saved settings, UI state, and error logs: a Nightly launch's validated profile, +/// else `TEXTURECRAFT_DATA_DIR` (when non-empty, as a Stable package wrapper sets it), else +/// eframe's own folder for this app. +fn storage_dir() -> Option { + settings_folder( + launch_profile::current().root(), + std::env::var_os(DATA_DIR_ENV).filter(|v| !v.is_empty()).map(std::path::PathBuf::from), + eframe::storage_dir(APP_NAME), + ) +} + +/// The settings folder, in the order a launch decides it: a Nightly profile, a Stable wrapper's +/// `TEXTURECRAFT_DATA_DIR`, else eframe's own folder for this app. +/// +/// The last one is passed in rather than left to eframe. With `with_app_id` set (the Linux window +/// class the Stable entry needs), eframe derives its folder from the app id, so Stable's `app.ron` +/// — window state and the user's export presets — would move to `ai.storyteller.texturecraft` while +/// `ui.json` and `errors.log` stayed behind. `persistence_path` therefore names the file explicitly. +fn settings_folder( + profile: Option<&std::path::Path>, + wrapper_dir: Option, + legacy: Option, +) -> Option { + profile.map(std::path::Path::to_path_buf).or(wrapper_dir).or(legacy) +} + /// Preferences needed before opening the initial project or window, with legacy storage fallback. fn saved_prefs(ui_file: Option<&std::path::Path>, persistence_path: Option<&std::path::Path>) -> texturecraft_ui_egui::state::Prefs { if let Some(ui) = ui_file.and_then(ui_state_store::read) { return ui.prefs; } - let file = persistence_path.map(std::path::Path::to_path_buf).or_else(|| eframe::storage_dir(APP_NAME).map(|folder| folder.join("app.ron"))); + let file = persistence_path.map(std::path::Path::to_path_buf).or_else(|| storage_dir().map(|folder| folder.join("app.ron"))); let saved = file.and_then(|file| std::fs::read_to_string(file).ok()); let entries = saved.and_then(|text| ron::from_str::>(&text).ok()); entries.and_then(|entries| ron::from_str::(entries.get("ui")?).ok()).map(|ui| ui.prefs).unwrap_or_default() } -/// The app with the window chrome that needs the native window: the Windows borderless guard, and -/// 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, - #[cfg(target_os = "macos")] - movable: Option, + /// Runs once when the window closes. On macOS that is the only place a clean quit is handled: + /// Cmd+Q ends the process inside AppKit's terminate, after eframe's `on_exit` and before + /// `eframe::run_native` returns, so the Nightly session record is finished here, not there. + exit_hook: Option>, } impl eframe::App for Shell { @@ -179,9 +238,14 @@ 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) { + if let Some(hook) = self.exit_hook.take() { + hook(); + } } } @@ -190,20 +254,106 @@ fn checks_for_updates_at_start(control: Option) -> bool { control.is_none() } +/// The AppUserModelID a Nightly window is grouped under, set before any native window exists. +fn initialize_nightly_process_identity() -> Result<(), process_identity::IdentityError> { + process_identity::initialize(build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1, os_window::id_for(LaunchIdentity::NightlyV1)) +} + +/// 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 refusal_dialog(build_flavor::COMPILED, desktop_session, cfg!(target_os = "macos")) { + if let Err(error) = initialize_nightly_process_identity() { + eprintln!("texturecraft: {error}"); + return; + } + #[cfg(any(windows, target_os = "linux", target_os = "macos"))] + let _ = rfd::MessageDialog::new() + .set_title(os_window::name_for(LaunchIdentity::NightlyV1)) + .set_description(error) + .set_level(rfd::MessageLevel::Error) + .set_buttons(rfd::MessageButtons::Ok) + .show(); + } +} + +/// Select the immutable launch profile before any startup service or side effect, and answer the +/// Launcher's version queries before root validation, logging, IPC or a window. `None` means the +/// launch is already answered and the process returns. +fn prepare_launch() -> Option> { + let argv: Vec = std::env::args_os().skip(1).collect(); + // Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root + // --version`: both are answered here, with nothing but standard output written. + if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv)) { + use std::io::Write as _; + let _ = writeln!(std::io::stdout(), "{}", build_flavor::version(build_flavor::COMPILED)); + return None; + } + let early = launch_profile::parse(argv) + .and_then(|launch| { + build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?; + initialize_nightly_process_identity().map_err(|error| error.to_string())?; + Ok(launch) + }) + .and_then(|launch| { + launch_profile::prepare(launch, |root| launch_profile::validate_root(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref())) + }) + .unwrap_or_else(|error| { + report_launch_profile_error(&error); + std::process::exit(2) + }); + let identity = if early.profile.is_nightly() { LaunchIdentity::NightlyV1 } else { LaunchIdentity::Stable }; + if let Err(error) = launch_profile::install(early.profile).and_then(|()| os_window::select_identity(identity)) { + report_launch_profile_error(&error); + std::process::exit(2); + } + if let Profile::NightlyV1(root) = launch_profile::current() { + // Every data folder follows the profile before the first one is used. + texturecraft_ui_egui::set_data_root(root.clone()); + texturecraft_ui_egui::os_window::set_display_version(build_flavor::BUILT_VERSION.to_owned()); + } + Some(early.args) +} + +/// The launch arguments as text. A Nightly protocol argument is a path the app opens, so a value +/// that is not valid Unicode is refused rather than silently replaced. +fn launch_arguments(arguments: Vec) -> Result, String> { + arguments.into_iter().map(|value| value.into_string().map_err(|_| "an argument is not valid Unicode".to_string())).collect() +} + fn main() { - // Windows: the update helper is a copy of this program started with `--finish-update` + // Windows: the update helper is a copy of this program started with `--finish-update`. A + // Nightly install is updated by ArtCraft Launcher, so it never installs an update itself. #[cfg(windows)] - if let Some(result) = craft_update::self_update::finish(&texturecraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::>()) { + if build_flavor::COMPILED == build_flavor::BuildFlavor::Stable + && let Some(result) = craft_update::self_update::finish(&texturecraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::>()) + { std::process::exit(i32::from(result.is_err())); } - // Windows: the eyedropper's pointer keeper (screen_pick) is a copy of this program started with its own argument + // Windows: the eyedropper's pointer keeper (screen_pick) is a copy of this program started with + // its own argument. It reads no user state and is started without the profile tokens, so it + // runs before the launch protocol would refuse it. #[cfg(windows)] if std::env::args_os().nth(1).is_some_and(|arg| arg == texturecraft_ui_egui::screen_pick::KEEPER_ARG) { std::process::exit(texturecraft_ui_egui::screen_pick::keep_pointer()); } - let args = match parse_args() { + let Some(arguments) = prepare_launch() else { return }; + let nightly = launch_profile::current().is_nightly(); + let args = match launch_arguments(arguments).and_then(parse_args_from) { Ok(Some(a)) => a, Ok(None) => return, Err(e) => { @@ -211,6 +361,12 @@ fn main() { std::process::exit(2); } }; + // The control server is a stable-install service: a Nightly window is driven by the Launcher, + // and its token file would sit in the shared temp folder rather than its private profile. + if nightly && args.control.is_some() { + eprintln!("texturecraft: TextureCraft Nightly cannot start a control server (--control); use the stable app or texturecraft-cli"); + std::process::exit(2); + } // Errors before the window opens speak the system's language; the app then applies the saved one texturecraft_ui_egui::i18n::set_language(texturecraft_ui_egui::i18n::os_language()); @@ -221,11 +377,13 @@ fn main() { previous_hook(info); })); - // Scripted runs use temporary files so they cannot overwrite saved settings - let persistence_path = + // Scripted runs use temporary files so they cannot overwrite saved settings. Otherwise eframe + // is told the file explicitly, so `with_app_id` cannot move Stable's `app.ron` out of the + // folder `storage_dir` keeps `ui.json` and `errors.log` in (see `settings_folder`). + let no_prefs_path = std::env::var_os("TEXTURECRAFT_NO_PREFS").map(|_| std::env::temp_dir().join(format!("texturecraft-noprefs-{}.ron", std::process::id()))); - let ui_file = - persistence_path.as_ref().map(|path| path.with_extension("json")).or_else(|| eframe::storage_dir(APP_NAME).map(|folder| folder.join("ui.json"))); + let persistence_path = no_prefs_path.clone().or_else(|| storage_dir().map(|dir| dir.join("app.ron"))); + let ui_file = no_prefs_path.as_ref().map(|path| path.with_extension("json")).or_else(|| storage_dir().map(|folder| folder.join("ui.json"))); if let Some(file) = &ui_file { let _ = ui_state_store::FILE.set(file.clone()); } @@ -235,20 +393,51 @@ 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 mut viewport = egui::ViewportBuilder::default().with_title(APP_NAME).with_inner_size(DEFAULT_SIZE).with_min_inner_size(MIN_SIZE); + 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()) + .with_inner_size(DEFAULT_SIZE) + .with_min_inner_size(MIN_SIZE); 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); std::process::exit(2); } let control = args.control; + // The Nightly session record: one owner per profile, an unclean exit reported by the next + // start, and no document name, path or diagnostic payload collected. + let (nightly_session, session_health_warning) = match nightly_session::Session::begin_with_health( + launch_profile::current().root(), + build_flavor::BUILT_VERSION, + Some(env!("TEXTURECRAFT_BUILD_SHA")), + ) { + Ok(state) => state, + Err(error) => { + log::warn!("Nightly session health is unavailable: {error}"); + (None, true) + } + }; + let previous_nightly_unclean = nightly_session.as_ref().is_some_and(nightly_session::Session::previous_unclean); + // Set once a window has posted the interruption notice; until then the record must survive. + let unclean_notice_shown = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let notice_shown_in_window = unclean_notice_shown.clone(); + let nightly_session: nightly_session::Shared = std::sync::Arc::new(std::sync::Mutex::new(nightly_session)); + // The exit hook is the controlled return on macOS, where every quit ends the process inside + // AppKit's terminate and `run_native` never returns. Elsewhere the return path below finishes. + let finish_at_exit = { + let shared = nightly_session.clone(); + let shown = unclean_notice_shown.clone(); + move || nightly_session::finish_once(&shared, shown.load(std::sync::atomic::Ordering::Relaxed)) + }; + let window_name = os_window::name(); let result = eframe::run_native( - APP_NAME, + window_name, options, Box::new(move |cc| { #[cfg(windows)] @@ -258,24 +447,32 @@ fn main() { // winit's Quit ends the process without asking; this menu's asks like the close button #[cfg(target_os = "macos")] - if let Err(e) = craft_menu::mac::install_app_menu(&cc.egui_ctx, APP_NAME) { + if let Err(e) = craft_menu::mac::install_app_menu(&cc.egui_ctx, window_name) { log::warn!("the app menu could not be installed: {e}"); } - let window_frame = window_frame::service(cc, matches!(title_bar, TitleBar::App(_))); + 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)); if let Some(port) = control { app.control = Some(control_server::start(port, cc.egui_ctx.clone())); } - Ok(Box::new(Shell { - app, - window_frame, - #[cfg(target_os = "macos")] - movable: None, - })) + if previous_nightly_unclean || session_health_warning { + use texturecraft_ui_egui::i18n::tr; + app.banner = Some(if previous_nightly_unclean { + tr("The previous TextureCraft Nightly session did not finish normally. No diagnostics have been sent.") + } else { + tr("TextureCraft Nightly could not record session health in its profile; abnormal-exit detection is unavailable.") + }); + notice_shown_in_window.store(previous_nightly_unclean, std::sync::atomic::Ordering::Relaxed); + } + Ok(Box::new(Shell { app, window_frame: 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 + // its exit hook, so this is then a no-op. + nightly_session::finish_once(&nightly_session, unclean_notice_shown.load(std::sync::atomic::Ordering::Relaxed)); if let Err(e) = result { fatal(&e.to_string(), true); std::process::exit(1); @@ -284,7 +481,7 @@ fn main() { /// The file startup errors and crashes are appended to, beside the saved settings. fn error_log() -> Option { - eframe::storage_dir(APP_NAME).map(|d| d.join("errors.log")) + storage_dir().map(|d| d.join("errors.log")) } /// Append a line with the time (Unix seconds) and the app version; true when it was written. @@ -305,7 +502,7 @@ fn fatal(msg: &str, dialog: bool) { let saved = log.map(|f| format!("\n\n{}", trf("Details saved to {file}", &[("file", &f.display())]))).unwrap_or_default(); rfd::MessageDialog::new() .set_level(rfd::MessageLevel::Error) - .set_title(APP_NAME) + .set_title(os_window::name()) .set_description(format!("{}\n\n{msg}{saved}", tr("TextureCraft had to close:"))) .set_buttons(rfd::MessageButtons::Ok) .show(); @@ -330,6 +527,55 @@ mod tests { assert_eq!(args.gpu.as_deref(), Some("3080")); } + #[test] + fn stable_settings_stay_in_the_folder_eframe_used_before_the_app_id() { + let legacy = std::path::PathBuf::from("/legacy/TextureCraft"); + // Stable, no wrapper folder: the folder eframe picked for `APP_NAME` before `with_app_id` + // existed, so `app.ron` (window state and the export presets stored in it) does not move. + let folder = settings_folder(None, None, Some(legacy.clone())).expect("a legacy folder"); + assert_eq!(folder.join("app.ron"), legacy.join("app.ron")); + // A Stable wrapper's data folder still wins, which is what #801's packaging expects. + let wrapper = std::path::PathBuf::from("/wrapper/data"); + assert_eq!(settings_folder(None, Some(wrapper.clone()), Some(legacy.clone())), Some(wrapper.clone())); + // A Nightly profile wins over both, so no Stable folder is ever read. + assert_eq!(settings_folder(Some(std::path::Path::new("/profile")), Some(wrapper), Some(legacy)), Some(std::path::PathBuf::from("/profile"))); + // Nothing resolvable: there is no folder to fall back to and eframe keeps its own default. + assert_eq!(settings_folder(None, None, None), None); + // The app's wiring: with no profile and no wrapper folder, `app.ron` sits beside `ui.json` + // in eframe's folder for `APP_NAME`, not in the folder of the app id `with_app_id` sets. + if std::env::var_os(DATA_DIR_ENV).is_none() + && !launch_profile::current().is_nightly() + && let Some(stable) = eframe::storage_dir(APP_NAME) + { + assert_eq!(storage_dir(), Some(stable.clone())); + assert_eq!(storage_dir().map(|dir| dir.join("app.ron")), Some(stable.join("app.ron"))); + } + } + + #[test] + fn a_file_after_the_delimiter_is_a_file_even_when_it_looks_like_an_option() { + let args = parse_args_from(["--".to_string(), "--version".to_string()]).unwrap().unwrap(); + assert_eq!(args.file.as_deref(), Some("--version")); + let args = parse_args_from(["--".to_string(), "--launch-profile".to_string()]).unwrap().unwrap(); + assert_eq!(args.file.as_deref(), Some("--launch-profile")); + // Options before the delimiter still parse as options. + let args = parse_args_from(["--gpu".to_string(), "nvidia".to_string(), "--".to_string(), "a.glb".to_string()]).unwrap().unwrap(); + assert_eq!((args.gpu.as_deref(), args.file.as_deref()), (Some("nvidia"), Some("a.glb"))); + // One window opens one project: extra files after the delimiter are ignored, in that order. + let args = parse_args_from(["--".to_string(), "a.glb".to_string(), "b.glb".to_string()]).unwrap().unwrap(); + assert_eq!(args.file.as_deref(), Some("a.glb")); + } + + #[test] + fn launch_arguments_refuse_a_name_that_is_not_unicode() { + assert_eq!(launch_arguments(vec![OsString::from("--version")]).unwrap(), vec!["--version".to_string()]); + #[cfg(unix)] + { + use std::os::unix::ffi::OsStringExt as _; + assert!(launch_arguments(vec![OsString::from_vec(vec![b'a', 0xff, b'b'])]).is_err()); + } + } + #[test] fn rejects_missing_or_invalid_gpu_args() { assert!(parse_args_from(["--gpu".to_string()]).is_err()); @@ -391,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) -> Vec { - 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() } @@ -406,13 +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, - #[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(); @@ -436,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"); + } +} diff --git a/apps/texturecraft/src/nightly_session.rs b/apps/texturecraft/src/nightly_session.rs new file mode 100644 index 00000000..a1f2dee5 --- /dev/null +++ b/apps/texturecraft/src/nightly_session.rs @@ -0,0 +1,277 @@ +//! App-private Nightly session health, not telemetry and not a Launcher protocol. +//! +//! A live owner holds a separate persistent lease; a secondary launch never rewrites its record. +//! Dropping the guard does not clear the marker; only the app's controlled return path does. + +use std::fs::File; +use std::io::{self, Read}; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex, PoisonError}; + +const RECORD: &str = "nightly-session.json"; +const LEASE: &str = "nightly-session.lock"; +const MAX_METADATA_BYTES: usize = 256; + +pub struct Session { + _lease: File, + path: PathBuf, + own_record: Vec, + previous_unclean: bool, +} + +fn regular_or_missing(path: &Path) -> io::Result { + match std::fs::symlink_metadata(path) { + Ok(metadata) if metadata.file_type().is_file() && !metadata.file_type().is_symlink() => Ok(true), + Ok(_) => Err(io::Error::other("Nightly session state must be a regular file, not an alias or directory")), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false), + Err(error) => Err(error), + } +} + +/// Write `bytes` to `path` without ever following a link at the destination: the temporary file is +/// created exclusively beside it and renamed over the name, which replaces a link rather than +/// writing through it (the engine's `write_atomic` deliberately resolves the target instead). +fn write_no_follow(path: &Path, bytes: &[u8]) -> io::Result<()> { + let parent = path.parent().ok_or_else(|| io::Error::other("the Nightly record has no folder"))?; + let name = path.file_name().and_then(|name| name.to_str()).ok_or_else(|| io::Error::other("the Nightly record name is not Unicode"))?; + let temporary = parent.join(format!(".{name}.{}.tmp", std::process::id())); + let mut options = std::fs::OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt as _; + options.mode(0o600); + } + let staged = write_staged(&mut options, &temporary, bytes).and_then(|()| std::fs::rename(&temporary, path)); + if let Err(error) = staged { + let _ = std::fs::remove_file(&temporary); + return Err(error); + } + // The rename is durable only once its folder is synced (no-op where the platform has no handle). + #[cfg(unix)] + if let Ok(folder) = File::open(parent) { + let _ = folder.sync_all(); + } + Ok(()) +} + +/// Write the whole file and flush it to the device before it may replace the destination. +fn write_staged(options: &mut std::fs::OpenOptions, temporary: &Path, bytes: &[u8]) -> io::Result<()> { + use std::io::Write as _; + let mut file = options.open(temporary)?; + file.write_all(bytes)?; + file.sync_all() +} + +/// The owner's session, shared by the app's exit hook (macOS) and the code after the event loop. +/// On macOS every quit ends the process inside AppKit's terminate, after eframe's `on_exit` and +/// before `eframe::run_native` could return, so the exit hook finishes it there; the return path +/// still runs for a start that created no window. +pub type Shared = Arc>>; + +/// The controlled return ([`Session::finish`]) by whichever path comes first; later calls do nothing. +pub fn finish_once(shared: &Shared, unclean_notice_shown: bool) { + let watch = shared.lock().unwrap_or_else(PoisonError::into_inner).take(); + if let Some(watch) = watch + && let Err(error) = watch.finish(unclean_notice_shown) + { + log::warn!("Nightly session state was left intact: {error}"); + } +} + +impl Session { + /// The warning belongs to this window: a busy secondary has no health-record coverage, while + /// Stable and a lease-owning Nightly window preserve their existing result. + pub fn begin_with_health(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result<(Option, bool)> { + let watch = Self::begin(root, version, commit)?; + let unavailable = root.is_some() && watch.is_none(); + Ok((watch, unavailable)) + } + + /// `None` is Stable or another owner of this profile. Neither case touches the record. + /// The supplied root must already be the validated private Nightly profile. + pub fn begin(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result> { + let Some(root) = root else { return Ok(None) }; + if version.is_empty() || version.len() > MAX_METADATA_BYTES || commit.is_some_and(|value| value.len() > MAX_METADATA_BYTES) { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "Nightly session provenance is missing or too large")); + } + let lease_path = root.join(LEASE); + regular_or_missing(&lease_path)?; + let lease = std::fs::OpenOptions::new().read(true).write(true).create(true).truncate(false).open(lease_path)?; + match lease.try_lock() { + Ok(()) => {} + Err(std::fs::TryLockError::WouldBlock) => return Ok(None), + Err(std::fs::TryLockError::Error(error)) => return Err(error), + } + let path = root.join(RECORD); + let previous_unclean = regular_or_missing(&path)?; + let own_record = serde_json::to_vec(&serde_json::json!({ + "schema_version": 1, + "channel": "nightly-v1", + "version": version, + "commit": commit.filter(|value| !value.is_empty()), + }))?; + write_no_follow(&path, &own_record)?; + Ok(Some(Self { _lease: lease, path, own_record, previous_unclean })) + } + + pub fn previous_unclean(&self) -> bool { + self.previous_unclean + } + + /// Controlled return. If an earlier session's interruption was detected but no window showed it + /// yet, the record is left for the next owner to report; otherwise this is [`Self::complete`]. + pub fn finish(self, unclean_notice_shown: bool) -> io::Result<()> { + if self.previous_unclean && !unclean_notice_shown { + return Ok(()); + } + self.complete() + } + + /// A handled startup error is a controlled return too. An unwind, abort, forced exit or killed + /// process never calls this method. + pub fn complete(self) -> io::Result<()> { + if !regular_or_missing(&self.path)? { + return Ok(()); + } + let mut current = Vec::new(); + File::open(&self.path)?.take(self.own_record.len() as u64 + 1).read_to_end(&mut current)?; + if current != self.own_record { + return Err(io::Error::other("Nightly session state changed; leaving it intact")); + } + std::fs::remove_file(&self.path) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicU64, Ordering}; + + struct Fixture(PathBuf); + impl Fixture { + fn new() -> Self { + static NEXT: AtomicU64 = AtomicU64::new(0); + loop { + let path = std::env::temp_dir().join(format!("texturecraft-nightly-session-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); + match std::fs::create_dir(&path) { + Ok(()) => return Self(path), + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(error) => panic!("cannot create owned fixture: {error}"), + } + } + } + } + impl Drop for Fixture { + fn drop(&mut self) { + std::fs::remove_dir_all(&self.0).unwrap(); + } + } + + #[test] + fn busy_secondary_reports_unavailable_without_replacing_the_owner_record() { + let fixture = Fixture::new(); + let (stable, warning) = Session::begin_with_health(None, "stable", None).unwrap(); + assert!(stable.is_none() && !warning); + let (first, warning) = Session::begin_with_health(Some(&fixture.0), "nightly", Some("owned-commit")).unwrap(); + assert!(!warning); + let first = first.unwrap(); + let record = std::fs::read(fixture.0.join(RECORD)).unwrap(); + let (secondary, warning) = Session::begin_with_health(Some(&fixture.0), "secondary", None).unwrap(); + assert!(secondary.is_none() && warning, "a secondary window cannot claim recorded exit/crash coverage"); + assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record); + first.complete().unwrap(); + assert!(!fixture.0.join(RECORD).exists()); + } + + #[test] + fn controlled_completion_is_clean_but_an_unfinished_owner_is_reported_next_time() { + let fixture = Fixture::new(); + let first = Session::begin(Some(&fixture.0), "first", Some("recorded-commit")).unwrap().unwrap(); + assert!(!first.previous_unclean()); + let own = std::fs::read(fixture.0.join(RECORD)).unwrap(); + assert!(Session::begin(Some(&fixture.0), "secondary", None).unwrap().is_none()); + assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), own, "a busy secondary must not replace the owner's record"); + first.complete().unwrap(); + assert!(!fixture.0.join(RECORD).exists()); + let unfinished = Session::begin(Some(&fixture.0), "second", None).unwrap().unwrap(); + assert!(!unfinished.previous_unclean()); + drop(unfinished); // Unwind/abnormal-path ownership release, not a controlled completion. + let next = Session::begin(Some(&fixture.0), "third", None).unwrap().unwrap(); + assert!(next.previous_unclean()); + next.complete().unwrap(); + assert!(!fixture.0.join(RECORD).exists()); + } + + #[test] + fn an_interruption_no_window_showed_survives_a_handled_startup_failure() { + let fixture = Fixture::new(); + drop(Session::begin(Some(&fixture.0), "crashed", None).unwrap().unwrap()); + let failed = Session::begin(Some(&fixture.0), "gpu-failed", None).unwrap().unwrap(); + assert!(failed.previous_unclean()); + failed.finish(false).unwrap(); + // The next start still sees the interruption and shows it. + let retry = Session::begin(Some(&fixture.0), "next", None).unwrap().unwrap(); + assert!(retry.previous_unclean()); + retry.finish(true).unwrap(); + assert!(!fixture.0.join(RECORD).exists(), "a session that showed the notice clears its record"); + let clean = Session::begin(Some(&fixture.0), "clean", None).unwrap().unwrap(); + assert!(!clean.previous_unclean()); + clean.finish(false).unwrap(); + assert!(!fixture.0.join(RECORD).exists()); + } + + #[test] + fn the_exit_hook_and_the_return_path_finish_the_session_once() { + let fixture = Fixture::new(); + let shared: Shared = Arc::new(Mutex::new(Session::begin(Some(&fixture.0), "quitting", None).unwrap())); + // The exit hook (macOS quit: the only path that runs there). + finish_once(&shared, false); + assert!(!fixture.0.join(RECORD).exists(), "a quit that ran the exit hook is a clean exit"); + // Elsewhere the return path runs too, by then possibly after a successor took the profile. + let successor = Session::begin(Some(&fixture.0), "successor", None).unwrap().unwrap(); + assert!(!successor.previous_unclean()); + let record = std::fs::read(fixture.0.join(RECORD)).unwrap(); + finish_once(&shared, false); + assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record, "the second finish must not touch a successor's record"); + successor.complete().unwrap(); + } + + #[test] + fn cleanup_never_removes_an_unknown_changed_record() { + let fixture = Fixture::new(); + let watch = Session::begin(Some(&fixture.0), "nightly", None).unwrap().unwrap(); + std::fs::write(fixture.0.join(RECORD), b"replacement owned by someone else").unwrap(); + assert!(watch.complete().is_err()); + assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), b"replacement owned by someone else"); + } + + #[test] + fn provenance_is_bounded_and_never_collects_documents_paths_or_diagnostics() { + let fixture = Fixture::new(); + assert!(Session::begin(Some(&fixture.0), &"x".repeat(MAX_METADATA_BYTES + 1), None).is_err()); + assert_eq!(std::fs::read_dir(&fixture.0).unwrap().count(), 0); + assert!(Session::begin(None, "", None).unwrap().is_none(), "stable has no session-health side effects"); + let watch = Session::begin(Some(&fixture.0), "nightly", None).unwrap().unwrap(); + let data: serde_json::Value = serde_json::from_slice(&std::fs::read(fixture.0.join(RECORD)).unwrap()).unwrap(); + let fields = data.as_object().unwrap().keys().map(String::as_str).collect::>(); + assert_eq!(fields, ["schema_version", "channel", "version", "commit"].into_iter().collect()); + assert!(data["commit"].is_null(), "missing provenance must not be invented"); + watch.complete().unwrap(); + } + + #[test] + #[cfg(unix)] + fn reserved_state_aliases_do_not_modify_external_files() { + let fixture = Fixture::new(); + let external = fixture.0.join("stable-document"); + std::fs::write(&external, b"stable bytes").unwrap(); + for name in [LEASE, RECORD] { + let alias = fixture.0.join(name); + std::os::unix::fs::symlink(&external, &alias).unwrap(); + assert!(Session::begin(Some(&fixture.0), "nightly", None).is_err()); + assert_eq!(std::fs::read(&external).unwrap(), b"stable bytes"); + std::fs::remove_file(alias).unwrap(); + } + } +} diff --git a/apps/texturecraft/src/process_identity.rs b/apps/texturecraft/src/process_identity.rs new file mode 100644 index 00000000..f9ef611e --- /dev/null +++ b/apps/texturecraft/src/process_identity.rs @@ -0,0 +1,78 @@ +//! Set the immutable Nightly Windows identity before any native window or COM service. +//! Stable deliberately leaves its implicit shortcut/path identity unchanged, so MSI shortcut +//! matching keeps working. + +use std::fmt; +use std::sync::OnceLock; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct IdentityError(pub String); + +impl fmt::Display for IdentityError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} + +impl std::error::Error for IdentityError {} + +/// The AppUserModelID the taskbar groups the Nightly window under, distinct from Stable's. +pub fn initialize(nightly: bool, app_id: &str) -> Result<(), IdentityError> { + configure(nightly && cfg!(windows), app_id, |id| { + static RESULT: OnceLock> = OnceLock::new(); + RESULT + .get_or_init(|| { + #[cfg(windows)] + { + winsafe::SetCurrentProcessExplicitAppUserModelID(id).map_err(|error| format!("cannot set the nightly Windows identity: {error}"))?; + let actual = winsafe::GetCurrentProcessExplicitAppUserModelID() + .map_err(|error| format!("cannot read back the nightly Windows identity: {error}"))?; + if actual != id { + return Err("the native Windows identity did not match the selected nightly channel".into()); + } + Ok(()) + } + #[cfg(not(windows))] + { + let _ = id; + Ok(()) + } + }) + .clone() + }) + .map_err(IdentityError) +} + +fn configure(explicit_nightly: bool, app_id: &str, set: impl FnOnce(&str) -> Result<(), String>) -> Result<(), String> { + if explicit_nightly { set(app_id) } else { Ok(()) } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn stable_does_not_call_the_explicit_identity_api() { + configure(false, "nightly-id", |_| panic!("stable identity must remain implicit")).unwrap(); + } + + #[test] + fn nightly_applies_the_supplied_identity_once() { + let calls = std::cell::Cell::new(0); + configure(true, "nightly-id", |id| { + assert_eq!(id, "nightly-id"); + calls.set(calls.get() + 1); + Ok(()) + }) + .unwrap(); + assert_eq!(calls.get(), 1); + } + + #[test] + fn native_identity_failure_is_returned_instead_of_starting_a_window() { + let started = std::cell::Cell::new(false); + let result = configure(true, "nightly-id", |_| Err("native identity refused".into())).map(|()| started.set(true)); + assert_eq!(result.unwrap_err(), "native identity refused"); + assert!(!started.get()); + } +} diff --git a/apps/texturecraft/src/profile_root.rs b/apps/texturecraft/src/profile_root.rs new file mode 100644 index 00000000..71265909 --- /dev/null +++ b/apps/texturecraft/src/profile_root.rs @@ -0,0 +1,489 @@ +//! App-owned nightly profile fences; no stable fallback, migration or process environment changes. +//! +//! A Nightly profile has to hold *all* of its user state: eframe's `app.ron`/`ui.json`, the error +//! log, session logs, autosave copies, smart materials, layouts, templates, brush and export +//! presets. Anything that resolves to a stable folder would read and prune Stable's files, so the +//! root is refused when it overlaps one of them, when an entry inside it is an alias that leaves it, +//! or when it is not writable. + +use std::ffi::OsString; +use std::path::{Component, Path, PathBuf}; + +/// The folder names the launch checks use for this app in each platform's location. +const BRAND: &str = "TextureCraft"; +/// The bundle identifier of the stable package (macOS library folders, the Linux Flatpak). +const STABLE_ID: &str = "ai.storyteller.texturecraft"; +/// The package id of the Nightly Flatpak bundle (`packaging/linux/flatpak-bundle.sh`). Inside that +/// sandbox `FLATPAK_ID` is always set, so this exact id is the one a Nightly native launch accepts. +const NIGHTLY_ID: &str = "ai.storyteller.texturecraft.nightly"; +/// eframe lowercases its folder name on Linux (`file_storage.rs`), so Stable's real settings folder +/// is `$XDG_DATA_HOME/texturecraft`, not the capitalised `TextureCraft` the app is called. +const LINUX_STORAGE_BRAND: &str = "texturecraft"; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Platform { + Windows, + Linux, + Mac, +} + +impl Platform { + fn current() -> Result { + match std::env::consts::OS { + "windows" => Ok(Self::Windows), + "linux" => Ok(Self::Linux), + "macos" => Ok(Self::Mac), + _ => Err("nightly-v1 is not defined for this operating system".into()), + } + } + + fn ignores_case(self) -> bool { + self != Self::Linux + } +} + +fn absolute(path: PathBuf, label: &str) -> Result { + if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) { + return Err(format!("{label} must be absolute and contain no parent traversal")); + } + Ok(path) +} + +fn required_base(env: &impl Fn(&str) -> Option, key: &str) -> Result { + let value = env(key).filter(|v| !v.is_empty()).ok_or_else(|| format!("cannot establish the stable {key} boundary"))?; + absolute(PathBuf::from(value), key) +} + +fn xdg_base(env: &impl Fn(&str) -> Option, key: &str, fallback: &str) -> Result { + match env(key).filter(|v| !v.is_empty()) { + Some(value) => absolute(PathBuf::from(value), key), + None => Ok(required_base(env, "HOME")?.join(fallback)), + } +} + +/// Resolve existing ancestors before creating anything. A dangling link or an inaccessible ancestor +/// is not a missing directory that may be replaced or followed later. +fn canonical_future(path: &Path) -> Result { + let mut parent = path; + let mut missing = Vec::new(); + loop { + match std::fs::symlink_metadata(parent) { + Ok(_) => break, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + missing.push(parent.file_name().ok_or("the profile root has no existing ancestor")?.to_os_string()); + parent = parent.parent().ok_or("the profile root has no existing ancestor")?; + } + Err(error) => return Err(format!("cannot inspect the profile boundary: {error}")), + } + } + let mut resolved = std::fs::canonicalize(parent).map_err(|e| format!("cannot resolve the profile boundary: {e}"))?; + for part in missing.into_iter().rev() { + resolved.push(part); + } + Ok(resolved) +} + +/// Whether one path is the other or contains it (in either direction), compared component by +/// component and folded the way the platform's filesystem folds names. `TextureCraft2` is not +/// inside `TextureCraft`. +fn overlaps(a: &Path, b: &Path, platform: Platform) -> bool { + let parts = |p: &Path| { + p.components() + .map(|c| { + let value = c.as_os_str().to_string_lossy().into_owned(); + if platform.ignores_case() { value.to_lowercase() } else { value } + }) + .collect::>() + }; + let (a, b) = (parts(a), parts(b)); + a.starts_with(&b) || b.starts_with(&a) +} + +/// The running install: never let the profile live inside it (it would be replaced or removed by +/// the next update). +fn installation_boundary(platform: Platform, exe: &Path) -> Result { + let parent = exe.parent().ok_or("cannot establish the installation boundary")?; + if platform == Platform::Mac { + // A profile in Resources is still inside the versioned bundle, not beside MacOS. + if let Some(bundle) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))) { + return Ok(bundle.to_path_buf()); + } + } + Ok(parent.to_path_buf()) +} + +/// The default data folder, `Documents/TextureCraft`, as the app's own resolver builds it +/// (`crate::data_folder("")`): `USERPROFILE` on Windows and `HOME` elsewhere, then `Documents`. +fn default_data_folder(platform: Platform, env: &impl Fn(&str) -> Option) -> Result { + let home = match platform { + Platform::Windows => required_base(env, "USERPROFILE")?, + _ => required_base(env, "HOME")?, + }; + Ok(home.join("Documents").join(BRAND)) +} + +fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option, exe: &Path) -> Result, String> { + let mut roots = match platform { + Platform::Windows => { + // eframe's settings folder (`%APPDATA%\TextureCraft`), its local counterpart, and the MSI's + // per-machine and any per-user install folders. A custom install folder is covered by the + // executable's own folder below. + let mut roots = ["APPDATA", "LOCALAPPDATA"].into_iter().map(|key| required_base(env, key).map(|p| p.join(BRAND))).collect::, _>>()?; + roots.push(required_base(env, "LOCALAPPDATA")?.join("Programs").join("ArtCraft").join(BRAND)); + for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] { + if let Some(base) = env(key).filter(|v| !v.is_empty()) { + roots.push(absolute(PathBuf::from(base), key)?.join(BRAND)); + } + } + roots + } + Platform::Linux => { + // The four XDG roots carry eframe's settings, caches and state under the app's name. + let mut roots = + [("XDG_CONFIG_HOME", ".config"), ("XDG_DATA_HOME", ".local/share"), ("XDG_CACHE_HOME", ".cache"), ("XDG_STATE_HOME", ".local/state")] + .into_iter() + .map(|(key, fallback)| xdg_base(env, key, fallback).map(|p| p.join(BRAND))) + .collect::, _>>()?; + // eframe's own folder for this app on Linux, which is what holds Stable's `app.ron`, + // `ui.json` and `errors.log`: it folds the name, so it is the lowercase one. + roots.push(xdg_base(env, "XDG_DATA_HOME", ".local/share")?.join(LINUX_STORAGE_BRAND)); + roots.extend(["/usr/bin/texturecraft", "/usr/local/bin/texturecraft", "/opt/texturecraft"].map(PathBuf::from)); + // The stable Flatpak keeps its own per-app data folder. + roots.push(required_base(env, "HOME")?.join(format!(".var/app/{STABLE_ID}"))); + roots + } + Platform::Mac => { + let home = required_base(env, "HOME")?; + let library = home.join("Library"); + vec![ + library.join("Application Support").join(BRAND), + library.join("Caches").join(BRAND), + library.join("Caches").join(STABLE_ID), + library.join("Preferences").join(BRAND), + library.join("Preferences").join(format!("{STABLE_ID}.plist")), + library.join("Saved Application State").join(format!("{STABLE_ID}.savedState")), + home.join("Applications").join(format!("{BRAND}.app")), + PathBuf::from("/Applications").join(format!("{BRAND}.app")), + ] + } + }; + // The user's own documents folder is Stable's default data folder on every platform; a profile + // there would share autosaves, smart materials and presets with it. + roots.push(default_data_folder(platform, env)?); + roots.push(installation_boundary(platform, exe)?); + roots.into_iter().map(|p| canonical_future(&p)).collect() +} + +/// An entry inside the profile must resolve inside it, so a link planted there cannot point +/// Nightly's writes at another app's files. +fn private_subdirectory(root: &Path, name: impl AsRef, label: &str) -> Result { + let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?; + let child = canonical_future(&chosen.join(name))?; + if child == chosen || !child.starts_with(&chosen) { + return Err(format!("the nightly {label} must stay inside its selected profile")); + } + Ok(child) +} + +/// Every existing entry directly in the profile (autosave, logs, library and so on) must resolve +/// inside it. +fn entries_stay_inside(root: &Path) -> Result<(), String> { + let entries = match std::fs::read_dir(root) { + Ok(entries) => entries, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()), + Err(error) => return Err(format!("cannot inspect the nightly profile: {error}")), + }; + for entry in entries { + let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?; + private_subdirectory(root, entry.file_name(), "profile entry")?; + } + Ok(()) +} + +/// The app's writable probe: create a file exclusively in the profile and remove it again. +pub fn ensure_writable(dir: &Path) -> std::io::Result<()> { + let probe = dir.join("exclusive-write-probe"); + let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?; + drop(file); + std::fs::remove_file(probe) +} + +/// Refuse a stable folder, the running install or an alias, create a missing root with owner-only +/// access where the platform has it, and return the resolved root to use. +pub fn validate( + root: &Path, + env: impl Fn(&str) -> Option, + exe: Option<&Path>, + writable: impl FnOnce(&Path) -> std::io::Result<()>, +) -> Result { + validate_for(Platform::current()?, root, env, exe, writable) +} + +fn validate_for( + platform: Platform, + root: &Path, + env: impl Fn(&str) -> Option, + exe: Option<&Path>, + writable: impl FnOnce(&Path) -> std::io::Result<()>, +) -> Result { + absolute(root.to_path_buf(), "the nightly profile root")?; + // A native package must not carry another app's Flatpak namespace, and the Nightly bundle must + // be able to start inside its own sandbox, where the runtime always sets `FLATPAK_ID`. Its + // `~/.var/app/` sandbox is separate from stable's, so only other ids are refused. + if platform != Platform::Windows + && let Some(id) = env("FLATPAK_ID").filter(|v| !v.is_empty()) + && id != NIGHTLY_ID + { + return Err("nightly-v1 only runs inside its own Flatpak; launch through the native Launcher or the Nightly bundle".into()); + } + let chosen = canonical_future(root)?; + let exe = absolute(exe.ok_or("cannot establish the installation boundary")?.to_path_buf(), "the executable")?; + let forbidden = forbidden_roots(platform, &env, &exe)?; + if forbidden.iter().any(|stable| overlaps(&chosen, stable, platform)) { + return Err("the nightly root must not overlap stable data or an installation".into()); + } + // Existing aliases under the profile must not redirect any of its folders elsewhere. + entries_stay_inside(&chosen)?; + let mut create = std::fs::DirBuilder::new(); + create.recursive(true); + #[cfg(unix)] + { + use std::os::unix::fs::DirBuilderExt as _; + create.mode(0o700); + } + create.create(&chosen).map_err(|e| format!("cannot create the nightly profile: {e}"))?; + let confirmed = std::fs::canonicalize(&chosen).map_err(|e| format!("cannot resolve the created nightly profile: {e}"))?; + if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) { + return Err("the nightly profile changed while it was being validated".into()); + } + entries_stay_inside(&confirmed)?; + writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?; + Ok(confirmed) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::BTreeMap; + use std::sync::atomic::{AtomicU64, Ordering}; + + struct Fixture { + root: PathBuf, + env: BTreeMap, + exe: PathBuf, + } + + impl Fixture { + fn new() -> Self { + static NEXT: AtomicU64 = AtomicU64::new(0); + let root = loop { + let candidate = + std::env::temp_dir().join(format!("texturecraft-profile-policy-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); + match std::fs::create_dir(&candidate) { + Ok(()) => break std::fs::canonicalize(candidate).unwrap(), + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(error) => panic!("cannot create owned fixture: {error}"), + } + }; + let home = root.join("home"); + let exe = root.join("install/texturecraft"); + std::fs::create_dir_all(&home).unwrap(); + std::fs::create_dir_all(exe.parent().unwrap()).unwrap(); + std::fs::write(&exe, b"fixture executable, never run").unwrap(); + let env = [("HOME", home.clone()), ("USERPROFILE", home), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))] + .into_iter() + .map(|(key, value)| (key.into(), value.into_os_string())) + .collect(); + Self { root, env, exe } + } + + fn get(&self, key: &str) -> Option { + self.env.get(key).cloned() + } + + fn check(&self, platform: Platform, root: &Path) -> Result { + validate_for(platform, root, |key| self.get(key), Some(&self.exe), ensure_writable) + } + + fn home(&self) -> PathBuf { + PathBuf::from(self.get("HOME").unwrap()) + } + + fn profile(&self, name: &str) -> PathBuf { + self.root.join("profiles").join(name) + } + } + + impl Drop for Fixture { + fn drop(&mut self) { + // Only the directory this fixture created is owned for removal. + std::fs::remove_dir_all(&self.root).unwrap(); + } + } + + #[test] + fn a_fresh_private_profile_is_created_and_returned_resolved() { + let fixture = Fixture::new(); + let profile = fixture.profile("nightly"); + for platform in [Platform::Windows, Platform::Linux, Platform::Mac] { + assert_eq!(fixture.check(platform, &profile).unwrap(), profile); + assert!(profile.is_dir()); + std::fs::remove_dir_all(&profile).ok(); + } + } + + #[test] + fn every_stable_data_folder_of_each_platform_is_refused_before_any_probe() { + let fixture = Fixture::new(); + let home = fixture.home(); + let candidates: Vec<(Platform, PathBuf)> = vec![ + (Platform::Windows, PathBuf::from(fixture.get("APPDATA").unwrap()).join(BRAND)), + (Platform::Windows, PathBuf::from(fixture.get("LOCALAPPDATA").unwrap()).join(BRAND)), + (Platform::Windows, PathBuf::from(fixture.get("LOCALAPPDATA").unwrap()).join("Programs/ArtCraft").join(BRAND)), + (Platform::Windows, home.join("Documents").join(BRAND)), + (Platform::Linux, home.join(".config").join(BRAND)), + (Platform::Linux, home.join(".local/share").join(BRAND)), + (Platform::Linux, home.join(".local/share").join(LINUX_STORAGE_BRAND)), + (Platform::Linux, home.join(".cache").join(BRAND)), + (Platform::Linux, home.join(".local/state").join(BRAND)), + (Platform::Linux, home.join("Documents").join(BRAND)), + (Platform::Linux, PathBuf::from("/usr/bin/texturecraft")), + (Platform::Linux, PathBuf::from("/opt/texturecraft")), + (Platform::Linux, home.join(format!(".var/app/{STABLE_ID}"))), + (Platform::Mac, home.join("Library/Application Support").join(BRAND)), + (Platform::Mac, home.join("Library/Caches").join(BRAND)), + (Platform::Mac, home.join("Library/Preferences").join(format!("{STABLE_ID}.plist"))), + (Platform::Mac, home.join("Library/Saved Application State").join(format!("{STABLE_ID}.savedState"))), + (Platform::Mac, home.join("Documents").join(BRAND)), + (Platform::Mac, PathBuf::from(format!("/Applications/{BRAND}.app"))), + ]; + for (platform, stable) in candidates { + for candidate in [stable.clone(), stable.join("nested nightly")] { + let probed = std::cell::Cell::new(false); + let result = validate_for( + platform, + &candidate, + |key| fixture.get(key), + Some(&fixture.exe), + |_| { + probed.set(true); + Ok(()) + }, + ); + assert!(result.is_err(), "{platform:?} accepted {}", candidate.display()); + assert!(!probed.get(), "a refused root must not be probed: {}", candidate.display()); + } + } + } + + #[test] + fn the_running_install_is_fenced_on_every_platform() { + let fixture = Fixture::new(); + for platform in [Platform::Windows, Platform::Linux, Platform::Mac] { + let inside = fixture.exe.parent().unwrap().join("profile"); + assert!(fixture.check(platform, &inside).is_err(), "{platform:?} let the profile inside the install"); + } + } + + #[test] + fn lookalike_names_are_not_overlaps_but_case_folding_is() { + let fixture = Fixture::new(); + let documents = fixture.home().join("Documents"); + assert!(fixture.check(Platform::Linux, &documents.join("TextureCraft2")).is_ok(), "a neighbor with a suffix is a different folder"); + assert!(fixture.check(Platform::Linux, &documents.join("texturecraft")).is_ok(), "Linux folds names exactly"); + for platform in [Platform::Windows, Platform::Mac] { + assert!(fixture.check(platform, &documents.join("texturecraft")).is_err(), "{platform:?} must fold case"); + } + } + + #[test] + fn relative_parent_traversal_and_empty_roots_are_refused() { + let fixture = Fixture::new(); + for root in [PathBuf::from("relative/profile"), PathBuf::from("/nightly/../stable"), PathBuf::from("")] { + assert!(fixture.check(Platform::Linux, &root).is_err(), "{}", root.display()); + } + } + + #[test] + fn only_the_nightly_flatpak_may_start_with_its_own_id() { + let fixture = Fixture::new(); + let profile = fixture.profile("flatpak"); + assert!(fixture.check(Platform::Linux, &profile).is_ok()); + std::fs::remove_dir_all(&profile).ok(); + let check_with = |id: &str, candidate: &Path| { + let id = OsString::from(id); + validate_for( + Platform::Linux, + candidate, + |key| if key == "FLATPAK_ID" { Some(id.clone()) } else { fixture.get(key) }, + Some(&fixture.exe), + ensure_writable, + ) + }; + // Stable's id, its window id and an unrelated app's id are all refusals. + for id in [STABLE_ID, "ai.storyteller.texturecraft.nightly-v1", "org.example.other"] { + assert!(check_with(id, &profile).is_err(), "{id} was accepted"); + } + // The Nightly bundle's own id is the sandbox the Nightly package runs in: accepted, with the + // profile its wrapper names inside it (`${XDG_DATA_HOME}/TextureCraft-Nightly`). + let sandbox = fixture.home().join(format!(".var/app/{NIGHTLY_ID}")); + let sandboxed = sandbox.join(".local/share/TextureCraft-Nightly"); + assert_eq!(check_with(NIGHTLY_ID, &sandboxed).expect("the Nightly Flatpak may start"), sandboxed); + std::fs::remove_dir_all(&sandbox).ok(); + } + + #[test] + #[cfg(unix)] + fn an_entry_that_leaves_the_profile_is_refused() { + let fixture = Fixture::new(); + let profile = fixture.profile("aliased"); + let outside = fixture.root.join("somewhere else"); + std::fs::create_dir_all(&profile).unwrap(); + std::fs::create_dir_all(&outside).unwrap(); + std::os::unix::fs::symlink(&outside, profile.join("autosave")).unwrap(); + assert!(fixture.check(Platform::Linux, &profile).is_err(), "a link out of the profile must be refused"); + // A dangling link is not a missing folder that may be created. + std::fs::remove_file(profile.join("autosave")).unwrap(); + std::os::unix::fs::symlink(profile.join("missing"), profile.join("logs")).unwrap(); + assert!(fixture.check(Platform::Linux, &profile).is_err()); + std::fs::remove_file(profile.join("logs")).unwrap(); + // A plain folder inside it is fine. + std::fs::create_dir(profile.join("autosave")).unwrap(); + assert!(fixture.check(Platform::Linux, &profile).is_ok()); + } + + #[test] + fn a_failed_write_probe_never_falls_back_to_stable() { + let fixture = Fixture::new(); + let profile = fixture.profile("read only"); + let reached = std::cell::Cell::new(false); + let result = validate_for( + Platform::Linux, + &profile, + |key| fixture.get(key), + Some(&fixture.exe), + |_| { + reached.set(true); + Err(std::io::Error::other("read-only filesystem")) + }, + ); + assert!(result.is_err()); + assert!(reached.get()); + assert!(result.unwrap_err().contains("not writable")); + // The app must not then use the stable folder: it simply refuses to start. + assert!(fixture.check(Platform::Linux, &fixture.home().join("Documents").join(BRAND)).is_err()); + } + + #[test] + #[cfg(unix)] + fn a_profile_whose_existing_ancestor_is_a_link_resolves_before_the_fence() { + let fixture = Fixture::new(); + let real = fixture.root.join("real profiles"); + std::fs::create_dir_all(&real).unwrap(); + let link = fixture.root.join("linked"); + std::os::unix::fs::symlink(&real, &link).unwrap(); + // A link to a private folder is fine, and the resolved root is what the app uses. + let resolved = fixture.check(Platform::Linux, &link.join("nightly")).unwrap(); + assert_eq!(resolved, real.join("nightly")); + } +} diff --git a/assets/app-icon/README.md b/assets/app-icon/README.md index 07351074..38a8538c 100644 --- a/assets/app-icon/README.md +++ b/assets/app-icon/README.md @@ -57,3 +57,23 @@ pillow and potracer): OPT=0.4 DP=1 python3 vectorize_tile.py source.png '#c2672b' 2048 2 texturecraft.svg OPT=1.0 DP=0 python3 vectorize_tile.py source.png '#c2672b' 1024 4 texturecraft-small.svg ``` + +## Nightly icon + +The Nightly build ships the same engraving on a deeper copper field (`#643418`): the background +contribution of each pixel is replaced and the ink, paper and alpha padding are left exactly as +they are. No badge, crescent or letter is added, so the two icons differ only in the field. + +| File | What | +|---|---| +| `texturecraft-nightly.png` | 256 px window icon (`apps/texturecraft/src/main.rs`) | +| `texturecraft-nightly-1024.png` | full tile, 1024 px (docs) | +| `texturecraft-nightly.icns` | macOS icon set, the stable `.icns`'s own PNG slots recoloured | +| `texturecraft-nightly.ico` | Windows icon, the stable `.ico`'s own frames (16 to 256 px) recoloured | +| `nightly/.png` | per-size renders for the Nightly package and the title bar's icon in a Nightly window (16 to 512 px). Kept out of `hicolor/`, which Stable's Linux and FreeBSD packagers copy whole | +| `nightly-provenance.json` | the inputs, the palette, the transform and the SHA-256 of every output | + +`packaging/nightly-icons.py` derives all of them from the committed stable renders (no upscale, no +resvg, no Pillow): run it after `packaging/icons.sh` changes a stable file, and +`python3 packaging/nightly-icons.py --check` (part of `packaging/nightly-tests.py`) fails when a +committed Nightly file has drifted. diff --git a/assets/app-icon/nightly-provenance.json b/assets/app-icon/nightly-provenance.json new file mode 100644 index 00000000..b9c4fc52 --- /dev/null +++ b/assets/app-icon/nightly-provenance.json @@ -0,0 +1,81 @@ +{ + "title": "TextureCraft nightly deep-background icons", + "license": "MIT OR Apache-2.0", + "generator": "packaging/nightly-icons.py", + "generator_sha256": "745786e3bfbecf29077df1e4a64ed717953694038f95533d2d37507c520b791c", + "inputs": [ + { + "path": "assets/app-icon/texturecraft.icns", + "sha256": "eb5e1b19679aa9a23531219d92922e37edbdc3e2046454b8f6c64423f471b57b" + }, + { + "path": "assets/app-icon/texturecraft.ico", + "sha256": "9c3366e4af9f2c0772e00193c348feba834d407fc8b826d4276a8fcb4cc01dcb" + }, + { + "path": "assets/app-icon/texturecraft-1024.png", + "sha256": "8451f91be8c1bc9c2e1a594e193ae5d1793d2d12f26a8bc64d2bd83fe4b789e4" + }, + { + "path": "assets/app-icon/hicolor/16x16/apps/ai.storyteller.texturecraft.png", + "sha256": "79ee309754be54b56052ab05fff87a2427bbc38bb057c96094f8f070ee13ca1d" + }, + { + "path": "assets/app-icon/hicolor/24x24/apps/ai.storyteller.texturecraft.png", + "sha256": "f8f89220ce68be236d63edfd94d4fef2aad2aa9840a50e430f874649a9816171" + }, + { + "path": "assets/app-icon/hicolor/32x32/apps/ai.storyteller.texturecraft.png", + "sha256": "ff8578ffc95f5123bb2e4a00636080f02adf259334ecb0ac9f952fac3378ddb2" + }, + { + "path": "assets/app-icon/hicolor/48x48/apps/ai.storyteller.texturecraft.png", + "sha256": "f7f19ffbd8904ff462bc6d785b865153112025bbdeb868bc0f136e39c7d725e1" + }, + { + "path": "assets/app-icon/hicolor/64x64/apps/ai.storyteller.texturecraft.png", + "sha256": "39d17421579ace5dbe4705fb0a52cd6002d433ded7ba0ee2fdeb5d6d7cd16c8c" + }, + { + "path": "assets/app-icon/hicolor/128x128/apps/ai.storyteller.texturecraft.png", + "sha256": "ac629a038a215a13d86172286142502b6efd17618869652050f291d9745346d2" + }, + { + "path": "assets/app-icon/hicolor/256x256/apps/ai.storyteller.texturecraft.png", + "sha256": "757f858b26897cb0e9f0c8cd43db9ade9664dd6199bd190d1af406839769c71f" + }, + { + "path": "assets/app-icon/hicolor/512x512/apps/ai.storyteller.texturecraft.png", + "sha256": "705513dc82aa908f962b9a466743b42e53b0f586752d2d69a5b6596b8ff928f0" + } + ], + "method": { + "kind": "derivative of the project-owned stable renders; no badge, crescent or letter", + "original_palette": { + "ink": "#0b0b0c", + "paper": "#efe9dc", + "background": "#c2672b" + }, + "nightly_background": "#643418", + "transform": "Fit each pixel as the tile background plus one engraved foreground (ink or paper) and replace only the background contribution; keep alpha, padding and foreground detail. Each frame comes from the stable master of its own size: the .icns and .ico PNG frames are recoloured in place, and the per-size PNGs (in nightly/) and the 1024 master are recoloured from their own renders. No upscaling." + }, + "outputs": { + "assets/app-icon/texturecraft-nightly.icns": "e21e2c90f7402e6289038ad7db896a14780766e07f33d9cb68cbe0d423efe66d", + "assets/app-icon/texturecraft-nightly.ico": "b0dc8817a3b07f0eb8175241c1fdc1ce21ffb8d5a54e6b03979ba2f73e62d47e", + "assets/app-icon/nightly/16.png": "657c7a39547828b0eaafe4b78df28771bb953afdb62440d0c001c695ff586e76", + "assets/app-icon/nightly/24.png": "b4c263436402faa93276b77614291107f6b44309ccfe329b71c3562c1f382c11", + "assets/app-icon/nightly/32.png": "cefb99a330d103f32a07d07e49542da2231897224a3dfe479e9c9d4a53a0a17b", + "assets/app-icon/nightly/48.png": "126316a058f4a225fbea7e1c0e49dc3d27941e2a91a7f033f35b84bc6d646f22", + "assets/app-icon/nightly/64.png": "d471a4bd691fca348603571bfe9c05357120e492566e31c7b2c936361a4a2510", + "assets/app-icon/nightly/128.png": "b36b07739b98b7884ce308641407725bb499adfefd87a4286c3aa117abdb57d5", + "assets/app-icon/nightly/256.png": "82c417bbcafd9b90929b117b7f80f403e631a77a327ee868bc9e8ca7a44c7fe2", + "assets/app-icon/nightly/512.png": "de756e67f16076a08cb5c2726d1a63181a0a8b61c73ff3df0cf49e065f1c8bc2", + "assets/app-icon/texturecraft-nightly-1024.png": "509ebc6130db6c10c380bc4ee2280a6b1810eea5dc03293b86a575c1ef120736", + "assets/app-icon/texturecraft-nightly.png": "82c417bbcafd9b90929b117b7f80f403e631a77a327ee868bc9e8ca7a44c7fe2" + }, + "ico_frames": [ + "the stable .ico's own frames (16, 20, 24, 32, 40, 48, 64, 128, 256)" + ], + "icns_slots": "the stable .icns's own PNG slots (icp4 through ic10)", + "validation": "Byte comparison against the committed assets (packaging/nightly-archive-tests.py and the icon check in packaging/nightly-tests.py); native Explorer/Finder rendering is not exercised here. The per-size PNGs are kept out of hicolor/ because Stable's Linux and FreeBSD packages copy that theme tree whole." +} diff --git a/assets/app-icon/nightly/128.png b/assets/app-icon/nightly/128.png new file mode 100644 index 00000000..c220657a Binary files /dev/null and b/assets/app-icon/nightly/128.png differ diff --git a/assets/app-icon/nightly/16.png b/assets/app-icon/nightly/16.png new file mode 100644 index 00000000..39ae3282 Binary files /dev/null and b/assets/app-icon/nightly/16.png differ diff --git a/assets/app-icon/nightly/24.png b/assets/app-icon/nightly/24.png new file mode 100644 index 00000000..6e15fead Binary files /dev/null and b/assets/app-icon/nightly/24.png differ diff --git a/assets/app-icon/nightly/256.png b/assets/app-icon/nightly/256.png new file mode 100644 index 00000000..3ca334c3 Binary files /dev/null and b/assets/app-icon/nightly/256.png differ diff --git a/assets/app-icon/nightly/32.png b/assets/app-icon/nightly/32.png new file mode 100644 index 00000000..aa3c8526 Binary files /dev/null and b/assets/app-icon/nightly/32.png differ diff --git a/assets/app-icon/nightly/48.png b/assets/app-icon/nightly/48.png new file mode 100644 index 00000000..db1aeaeb Binary files /dev/null and b/assets/app-icon/nightly/48.png differ diff --git a/assets/app-icon/nightly/512.png b/assets/app-icon/nightly/512.png new file mode 100644 index 00000000..f62c465e Binary files /dev/null and b/assets/app-icon/nightly/512.png differ diff --git a/assets/app-icon/nightly/64.png b/assets/app-icon/nightly/64.png new file mode 100644 index 00000000..a85b8233 Binary files /dev/null and b/assets/app-icon/nightly/64.png differ diff --git a/assets/app-icon/texturecraft-nightly-1024.png b/assets/app-icon/texturecraft-nightly-1024.png new file mode 100644 index 00000000..d43e9fbc Binary files /dev/null and b/assets/app-icon/texturecraft-nightly-1024.png differ diff --git a/assets/app-icon/texturecraft-nightly.icns b/assets/app-icon/texturecraft-nightly.icns new file mode 100644 index 00000000..9d96db5f Binary files /dev/null and b/assets/app-icon/texturecraft-nightly.icns differ diff --git a/assets/app-icon/texturecraft-nightly.ico b/assets/app-icon/texturecraft-nightly.ico new file mode 100644 index 00000000..9d1f3eb3 Binary files /dev/null and b/assets/app-icon/texturecraft-nightly.ico differ diff --git a/assets/app-icon/texturecraft-nightly.png b/assets/app-icon/texturecraft-nightly.png new file mode 100644 index 00000000..3ca334c3 Binary files /dev/null and b/assets/app-icon/texturecraft-nightly.png differ diff --git a/assets/samples/Material Ball.tcraft b/assets/samples/Material Ball.tcraft new file mode 100644 index 00000000..915697f3 Binary files /dev/null and b/assets/samples/Material Ball.tcraft differ diff --git a/assets/samples/README.md b/assets/samples/README.md new file mode 100644 index 00000000..bc366dd4 --- /dev/null +++ b/assets/samples/README.md @@ -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. diff --git a/crates/bake/src/bake_passes.rs b/crates/bake/src/bake_passes.rs new file mode 100644 index 00000000..eb7d5846 --- /dev/null +++ b/crates/bake/src/bake_passes.rs @@ -0,0 +1,72 @@ +use crate::cage::RayFrame; +use crate::map::BakeContext; +use crate::tracing::{CpuTracer, Tracer}; +use crate::{BakeError, BakeOutput, BakeRequest, MeshExtent, Progress}; +use std::sync::atomic::Ordering::Relaxed; +use texturecraft_core::{BakeSettings, BakedMap}; + +/// Map passes over one immutable request share the fitted cage and prepared skew. +pub struct BakePasses<'a> { + request: BakeRequest<'a>, + frame: Option<(MeshExtent, RayFrame<'a>)>, +} + +impl<'a> BakePasses<'a> { + pub fn new(request: BakeRequest<'a>) -> Self { + Self { request, frame: None } + } + + /// Bake one selected map, including the CPU fallback used by a normal bake. + pub fn bake_map( + &mut self, + map: BakedMap, + progress: &Progress, + excluded_tiles: &[(u32, u32)], + tracer: Option<&dyn Tracer>, + ) -> Result { + let mut settings = self.request.settings.clone(); + settings.maps.select([map]); + self.run(&settings, progress, excluded_tiles, tracer, super::STRIP_TEXELS) + } + + pub(super) fn run( + &mut self, + settings: &BakeSettings, + progress: &Progress, + excluded_tiles: &[(u32, u32)], + tracer: Option<&dyn Tracer>, + strip_texels: usize, + ) -> Result { + if progress.cancel.load(Relaxed) { + return Err(BakeError::Cancelled); + } + + let request = BakeRequest { settings, ..self.request }; + super::validate(&request)?; + if excluded_tiles.iter().any(|(column, row)| *column >= request.tiles.0 || *row >= request.tiles.1) { + return Err(BakeError::Invalid("excluded UV tile lies outside the bake atlas".into())); + } + + // Validate each pass separately so earlier maps can finish before a later map fails + let (extent, frame) = match &mut self.frame { + Some(geometry) => geometry, + None => { + let extent = MeshExtent::of(request.mesh)?; + self.frame.insert((extent, RayFrame::new(&self.request, extent)?)) + } + }; + let context = BakeContext::with_frame(&request, *extent, frame); + let bake = |tracer: &dyn Tracer| super::bake_prepared(&request, &context, progress, strip_texels, tracer, excluded_tiles); + match tracer { + Some(tracer) => match bake(tracer) { + Err(BakeError::Tracer(error)) => { + let mut output = bake(&CpuTracer)?; + output.tracer = format!("CPU ({} unavailable: {error})", tracer.name()); + Ok(output) + } + result => result, + }, + None => bake(&CpuTracer), + } + } +} diff --git a/crates/bake/src/cage.rs b/crates/bake/src/cage.rs index d2c7d7f3..d2c8a592 100644 --- a/crates/bake/src/cage.rs +++ b/crates/bake/src/cage.rs @@ -1,7 +1,9 @@ //! Where the bake's transfer rays start, shared by the bake and the cage the 3D view draws mod cage_shell; +mod fitted_cage; mod high_poly_reach; +mod name_keys; mod ray_frame; mod ray_start; mod vertex_reach; @@ -9,6 +11,7 @@ mod vertex_reach; #[cfg(test)] pub(crate) use cage_shell::CORNERS; pub use cage_shell::CageShell; +pub(crate) use fitted_cage::FittedCage; pub use high_poly_reach::HighPolyReach; pub(crate) use ray_frame::RayFrame; pub use ray_start::RayStart; diff --git a/crates/bake/src/cage/fitted_cage.rs b/crates/bake/src/cage/fitted_cage.rs new file mode 100644 index 00000000..079d94b0 --- /dev/null +++ b/crates/bake/src/cage/fitted_cage.rs @@ -0,0 +1,231 @@ +use super::name_keys::NameKeys; +use crate::map::interpolate; +use crate::{BakeRequest, HighPoly, MeshExtent}; +use rayon::prelude::*; +use std::borrow::Cow; +use std::collections::{HashMap, VecDeque}; +use texturecraft_geom::Mesh; +use texturecraft_geom::glam::Vec3; + +/// How much farther than the high poly the cage reaches, as a fraction of the fitted distance: the fit reads both meshes at their vertices only. Tuned with [`MARGIN_PER_DIAGONAL`] on two production meshes: the tightest pair whose rays miss no more texels than the default distances do +const MARGIN_PER_DISTANCE: f32 = 0.5; + +/// The least the cage reaches each way, as a fraction of the mesh diagonal, so a high poly lying on the low poly is still inside +const MARGIN_PER_DIAGONAL: f32 = 4e-3; + +/// How many times farther than the nearest high-poly point a low-poly vertex's ray may find the high poly: beyond it (a surface more than about 75 degrees off the ray) the ray has left the vertex's own part +const MAX_RAY_PER_NEAREST_DISTANCE: f32 = 4.0; + +/// Bound temporary high-vertex projections while giving Rayon thousands of independent queries per batch +const PROJECTION_BATCH_VERTICES: usize = 8192; + +/// The automatic cage: how far the transfer rays start in front of each low-poly vertex and how far they run behind it, fitted to the high poly +pub(crate) struct FittedCage { + /// (front, rear) in world units per low-poly vertex; `None` on parts no high poly is near + distances: Vec>, +} + +impl FittedCage { + /// Fit the cage of `request`'s low poly around `high` along `ray_normals` (where parts welded back to back cancelled a vertex's normal out, along its own): each low-poly vertex reaches the high poly straight in front of or behind it, and each high-poly vertex pushes the corners of its nearest low-poly triangle out (or in) to its height. Vertices neither finds take their neighbours' distances; a part the high poly reaches nowhere gets none + pub(crate) fn new(request: &BakeRequest, high: HighPoly, welded_indices: &[u32], ray_normals: &[Vec3], extent: MeshExtent) -> FittedCage { + let low = request.mesh; + let keys = NameKeys::of(request, high); + let welded_indices = welded_within_groups(welded_indices, &keys.low_vertices); + let welded = |vertex: usize| welded_indices.get(vertex).copied().unwrap_or(0) as usize; + let welded_count = welded_indices.iter().max().map_or(0, |last| *last as usize + 1); + + let fitting_normals = fitting_normals(low, ray_normals); + let mut reach: Vec> = vec![None; welded_count]; + let mut widen = |vertex: usize, height: f32| { + if let Some(distances) = reach.get_mut(welded(vertex)) { + let (front, rear) = distances.unwrap_or((0.0, 0.0)); + *distances = Some((front.max(height), rear.max(-height))); + } + }; + + for (vertex, height) in heights_at_low_vertices(low, high, &fitting_normals, &keys, extent.diagonal).into_iter().enumerate() { + if let Some(height) = height { + widen(vertex, height); + } + } + let mut projected = Vec::new(); + for (batch, positions) in high.mesh.positions.chunks(PROJECTION_BATCH_VERTICES).enumerate() { + let first = batch * PROJECTION_BATCH_VERTICES; + positions + .par_iter() + .enumerate() + .map(|(index, &position)| project_high_vertex(request, &fitting_normals, &keys, first + index, position)) + .collect_into_vec(&mut projected); + + for (triangle, height) in projected.drain(..).flatten() { + for corner in low.tri(triangle).into_iter().flatten() { + widen(corner, height); + } + } + } + drop(projected); + + spread_to_neighbours(&mut reach, low.indices.as_chunks::<3>().0.iter().map(|corners| corners.map(|corner| welded(corner as usize)))); + + let floor = MARGIN_PER_DIAGONAL * extent.diagonal; + let padded = |distance: f32| distance * (1.0 + MARGIN_PER_DISTANCE) + floor; + let distances = + (0..low.positions.len()).map(|vertex| reach.get(welded(vertex)).copied().flatten().map(|(front, rear)| (padded(front), padded(rear)))).collect(); + + FittedCage { distances } + } + + /// The (front, rear) distances at `barycentric` of triangle `triangle` of the low poly `low` the cage was fitted to; `None` where the high poly reaches no corner + pub(crate) fn distances(&self, low: &Mesh, triangle: u32, barycentric: [f32; 2]) -> Option<(f32, f32)> { + let corners = low.tri(triangle as usize)?; + let [first, second, third] = [0, 1, 2].map(|corner| self.distances.get(corners[corner]).copied().flatten()); + let ((first_front, first_rear), (second_front, second_rear), (third_front, third_rear)) = (first?, second?, third?); + let [second_weight, third_weight] = barycentric; + let first_weight = 1.0 - second_weight - third_weight; + + Some(( + first_front * first_weight + second_front * second_weight + third_front * third_weight, + first_rear * first_weight + second_rear * second_weight + third_rear * third_weight, + )) + } +} + +/// `welded_indices` with the vertices of different mesh-name groups (`vertex_keys`, empty when names don't matter) kept apart, so a group's distances come only from its own high poly and never spread into another group +fn welded_within_groups<'a>(welded_indices: &'a [u32], vertex_keys: &[u32]) -> Cow<'a, [u32]> { + if vertex_keys.is_empty() { + return Cow::Borrowed(welded_indices); + } + + let mut indices: HashMap<(u32, Option), u32> = HashMap::new(); + welded_indices + .iter() + .enumerate() + .map(|(vertex, &welded)| { + let next = indices.len() as u32; + *indices.entry((welded, vertex_keys.get(vertex).copied())).or_insert(next) + }) + .collect() +} + +/// `ray_normals`, except where parts welded back to back cancelled a vertex's normal out: there, the vertex's own normal, the direction its transfer rays fall back to +fn fitting_normals<'a>(low: &Mesh, ray_normals: &'a [Vec3]) -> Cow<'a, [Vec3]> { + if !ray_normals.contains(&Vec3::ZERO) { + return Cow::Borrowed(ray_normals); + } + + ray_normals + .iter() + .enumerate() + .map(|(vertex, &welded_normal)| { + if welded_normal != Vec3::ZERO { + return welded_normal; + } + + low.normals.get(vertex).and_then(|normal| normal.try_normalize()).unwrap_or(welded_normal) + }) + .collect() +} + +/// Per low-poly vertex, how far along its ray normal the high-poly surface in front of it (positive) or behind it (negative) is. A ray that only finds a surface much farther than the nearest high-poly point (within `max_distance`) found another part, so the vertex takes that nearest point's height instead +fn heights_at_low_vertices(low: &Mesh, high: HighPoly, ray_normals: &[Vec3], keys: &NameKeys, max_distance: f32) -> Vec> { + low.positions + .par_iter() + .zip(ray_normals) + .enumerate() + .map(|(vertex, (&position, &up))| { + let low_key = keys.low_vertices.get(vertex); + let rays_reach = |triangle: u32| NameKeys::matches(low_key, keys.high_triangles.get(triangle as usize)); + let nearest = high.bvh.nearest(position, max_distance, &rays_reach)?; + let nearest_position = interpolate(high.mesh, &high.mesh.positions, nearest.tri, [nearest.u, nearest.v])?; + let ray_limit = nearest.t * MAX_RAY_PER_NEAREST_DISTANCE + MARGIN_PER_DIAGONAL * max_distance; + let distance = |direction: Vec3| high.bvh.closest_filtered(position, direction, ray_limit, &rays_reach).map(|hit| hit.t); + + Some(match (distance(up), distance(-up)) { + (Some(front), Some(rear)) if front <= rear => front, + (Some(front), None) => front, + (_, Some(rear)) => -rear, + (None, None) => (nearest_position - position).dot(up), + }) + }) + .collect() +} + +/// The nearest matching low-poly triangle and signed height of one high-poly vertex +fn project_high_vertex(request: &BakeRequest, ray_normals: &[Vec3], keys: &NameKeys, vertex: usize, position: Vec3) -> Option<(usize, f32)> { + let low = request.mesh; + let high_key = keys.high_vertices.get(vertex); + let rays_reach = |triangle: u32| NameKeys::matches(keys.low_triangles.get(triangle as usize), high_key); + let nearest = request.bvh.nearest(position, f32::INFINITY, &rays_reach)?; + let barycentric = [nearest.u, nearest.v]; + let low_position = interpolate(low, &low.positions, nearest.tri, barycentric)?; + let up = interpolate(low, ray_normals, nearest.tri, barycentric)?.try_normalize()?; + + Some((nearest.tri as usize, (position - low_position).dot(up))) +} + +/// Give each vertex without distances the largest of its nearest fitted neighbours', walking outward along the edges of `triangles` +fn spread_to_neighbours(reach: &mut [Option<(f32, f32)>], triangles: impl Iterator) { + // Only unfitted vertices adjacent to a fitted region can gain distances + if reach.iter().all(Option::is_some) || reach.iter().all(Option::is_none) { + return; + } + + let mut neighbours = vec![Vec::new(); reach.len()]; + for corners in triangles { + for (corner, next) in [(0, 1), (1, 2), (2, 0)] { + if let (true, Some(list)) = (corners[next] < reach.len(), neighbours.get_mut(corners[corner])) { + list.push(corners[next]); + } + if let (true, Some(list)) = (corners[corner] < reach.len(), neighbours.get_mut(corners[next])) { + list.push(corners[corner]); + } + } + } + + // Propagate distances from the preceding breadth-first layer + let mut steps: Vec> = reach.iter().map(|distances| distances.map(|_| 0)).collect(); + let mut queue: VecDeque = (0..reach.len()).filter(|vertex| reach[*vertex].is_some()).collect(); + while let Some(vertex) = queue.pop_front() { + let (Some((front, rear)), Some(step)) = (reach[vertex], steps[vertex]) else { continue }; + + for &neighbour in &neighbours[vertex] { + match steps[neighbour] { + None => { + steps[neighbour] = Some(step + 1); + reach[neighbour] = Some((front, rear)); + queue.push_back(neighbour); + } + Some(neighbour_step) if neighbour_step == step + 1 => { + let (neighbour_front, neighbour_rear) = reach[neighbour].unwrap_or((0.0, 0.0)); + reach[neighbour] = Some((neighbour_front.max(front), neighbour_rear.max(rear))); + } + Some(_) => {} + } + } + } +} + +#[cfg(test)] +mod tests { + use super::{spread_to_neighbours, welded_within_groups}; + + #[test] + fn coincident_vertices_of_different_name_groups_are_not_welded() { + // The coincident pairs span different mesh-name groups + assert_eq!(welded_within_groups(&[0, 0, 1, 1], &[5, 7, 7, 5]).as_ref(), [0, 1, 2, 3]); + assert_eq!(welded_within_groups(&[0, 0, 1, 1], &[5, 5, 7, 7]).as_ref(), [0, 0, 1, 1], "same group: still welded"); + assert_eq!(welded_within_groups(&[0, 0, 1], &[]).as_ref(), [0, 0, 1], "without name matching nothing changes"); + } + + #[test] + fn unfitted_vertices_take_the_largest_distances_of_their_nearest_fitted_neighbours() { + // A strip of triangles 0-1-2, 1-2-3, 2-3-4: vertices 0 and 4 are fitted + let mut reach = vec![Some((1.0, 0.5)), None, None, None, Some((3.0, 0.25))]; + + spread_to_neighbours(&mut reach, [[0, 1, 2], [1, 2, 3], [2, 3, 4]].into_iter()); + + assert_eq!(reach[1], Some((1.0, 0.5)), "one step from vertex 0 only"); + assert_eq!(reach[3], Some((3.0, 0.25)), "one step from vertex 4 only"); + assert_eq!(reach[2], Some((3.0, 0.5)), "one step from both: the larger of each"); + } +} diff --git a/crates/bake/src/cage/high_poly_reach.rs b/crates/bake/src/cage/high_poly_reach.rs index 2f461343..b227ca06 100644 --- a/crates/bake/src/cage/high_poly_reach.rs +++ b/crates/bake/src/cage/high_poly_reach.rs @@ -75,7 +75,7 @@ impl HighPolyReach { } /// Each vertex's mesh-name key, from the first triangle that uses it -fn vertex_keys(mesh: &Mesh, triangle_keys: &[u32]) -> Vec { +pub(super) fn vertex_keys(mesh: &Mesh, triangle_keys: &[u32]) -> Vec { let mut keys = vec![ANY; mesh.positions.len()]; for (corners, &triangle_key) in mesh.indices.as_chunks::<3>().0.iter().zip(triangle_keys) { for &corner in corners { diff --git a/crates/bake/src/cage/name_keys.rs b/crates/bake/src/cage/name_keys.rs new file mode 100644 index 00000000..077cd826 --- /dev/null +++ b/crates/bake/src/cage/name_keys.rs @@ -0,0 +1,38 @@ +use super::high_poly_reach::vertex_keys; +use crate::map::transfer_keys; +use crate::tracing::ANY; +use crate::{BakeRequest, HighPoly}; +use texturecraft_core::MeshMatchMode; + +/// The mesh-name keys of a bake's low and high poly, per triangle and per vertex; all empty when every ray may hit every part +#[derive(Default)] +pub(super) struct NameKeys { + pub(super) low_triangles: Vec, + pub(super) low_vertices: Vec, + pub(super) high_triangles: Vec, + pub(super) high_vertices: Vec, +} + +impl NameKeys { + /// The keys `request` bakes with against `high`: filled only when it matches by mesh name + pub(super) fn of(request: &BakeRequest, high: HighPoly) -> NameKeys { + match request.settings.high_poly.match_mode { + MeshMatchMode::Always => NameKeys::default(), + MeshMatchMode::ByMeshName => { + let (low_triangles, high_triangles) = transfer_keys(request); + NameKeys { + low_vertices: vertex_keys(request.mesh, &low_triangles), + high_vertices: vertex_keys(high.mesh, &high_triangles), + low_triangles, + high_triangles, + } + } + } + } + + /// Whether a ray from the low-poly part keyed `low_key` may hit the high-poly part keyed `high_key`; a missing key is a part any ray may hit + pub(super) fn matches(low_key: Option<&u32>, high_key: Option<&u32>) -> bool { + let low_key = low_key.copied().unwrap_or(ANY); + low_key == ANY || low_key == high_key.copied().unwrap_or(ANY) + } +} diff --git a/crates/bake/src/cage/ray_frame.rs b/crates/bake/src/cage/ray_frame.rs index e8692cf2..590e52e1 100644 --- a/crates/bake/src/cage/ray_frame.rs +++ b/crates/bake/src/cage/ray_frame.rs @@ -1,4 +1,4 @@ -use super::RayStart; +use super::{FittedCage, RayStart}; use crate::MeshExtent; use crate::map::{interpolate, welded}; use crate::skew::PreparedSkew; @@ -7,11 +7,12 @@ use texturecraft_core::CageType; use texturecraft_geom::glam::Vec3; use texturecraft_geom::{Mesh, Surface}; -/// What decides where transfer rays start: the cage mesh or the averaged normals, skew and painted cage amount +/// What decides where transfer rays start: the cage mesh, the automatic cage's fitted distances, or the averaged normals, skew and painted cage amount pub(crate) struct RayFrame<'a> { mesh: &'a Mesh, ray_normals: Vec, cage: Option<&'a Mesh>, + fitted: Option, skew: Option>, cage_paint: Option<&'a BakePaintMap>, /// Cage-file offsets this short count as none: the ray starts from the distance-based cage instead @@ -23,18 +24,24 @@ pub(crate) struct RayFrame<'a> { impl<'a> RayFrame<'a> { pub(crate) fn new(request: &BakeRequest<'a>, extent: MeshExtent) -> Result, BakeError> { let settings = request.settings; - let ray_normals = match settings.cage.average_normals && request.high.is_some() { + + // The automatic cage is one closed shell, so its rays always follow the averaged normals + let automatic_high = request.high.filter(|_| settings.cage.kind == CageType::Automatic); + let (ray_normals, fitted) = match (settings.cage.average_normals || automatic_high.is_some()) && request.high.is_some() { true => { let (welded_indices, _, normals) = welded(request.mesh, extent.diagonal); - welded_indices.iter().map(|index| normals.get(*index as usize).copied().unwrap_or(Vec3::Y)).collect() + let ray_normals: Vec = welded_indices.iter().map(|index| normals.get(*index as usize).copied().unwrap_or(Vec3::Y)).collect(); + let fitted = automatic_high.map(|high| FittedCage::new(request, high, &welded_indices, &ray_normals, extent)); + (ray_normals, fitted) } - false => Vec::new(), + false => (Vec::new(), None), }; Ok(RayFrame { mesh: request.mesh, ray_normals, cage: if settings.cage.kind == CageType::CustomFile { request.cage } else { None }, + fitted, skew: request.skew.map(|skew_map| PreparedSkew::new(skew_map, request.mesh, extent.scale, settings.skew)).transpose()?, cage_paint: request.cage_paint, ray_epsilon: extent.ray_epsilon(), @@ -54,6 +61,11 @@ impl<'a> RayFrame<'a> { } let averaged_normal = interpolate(self.mesh, &self.ray_normals, surface.tri, barycentric).and_then(Vec3::try_normalize).unwrap_or(surface.nrm); + let fitted_distances = self.fitted.as_ref().and_then(|fitted| fitted.distances(self.mesh, surface.tri, barycentric)); + if let Some((front, rear)) = fitted_distances { + return RayStart::Fitted { up: averaged_normal, front, rear }; + } + let up = match &self.skew { Some(skew) => skew.correct(self.mesh, surface, averaged_normal), None => averaged_normal, diff --git a/crates/bake/src/cage/ray_start.rs b/crates/bake/src/cage/ray_start.rs index c0c3923a..8c21bb9b 100644 --- a/crates/bake/src/cage/ray_start.rs +++ b/crates/bake/src/cage/ray_start.rs @@ -7,6 +7,8 @@ pub enum RayStart { CageMesh(Vec3), /// Out along `up` by the frontal distance times `scale` (the painted cage amount) Distance { up: Vec3, scale: f32 }, + /// Out along `up` by `front` world units and reaching `rear` past the low-poly point: the automatic cage's own distances + Fitted { up: Vec3, front: f32, rear: f32 }, } impl RayStart { @@ -15,6 +17,16 @@ impl RayStart { match *self { RayStart::CageMesh(offset) => position - offset, RayStart::Distance { up, scale } => position + up * frontal * scale, + RayStart::Fitted { up, front, .. } => position + up * front, + } + } + + /// The ray's direction, how far it runs to the low-poly point and how far past it, at `frontal` and `rear` world units of the distance settings + pub fn span(&self, frontal: f32, rear: f32) -> (Vec3, f32, f32) { + match *self { + RayStart::CageMesh(offset) => (offset.normalize_or_zero(), offset.length(), rear), + RayStart::Distance { up, scale } => (-up, frontal * scale, rear), + RayStart::Fitted { up, front, rear: fitted_rear } => (-up, front, fitted_rear), } } } diff --git a/crates/bake/src/cage/vertex_reach.rs b/crates/bake/src/cage/vertex_reach.rs index 34adea92..2c6df8e8 100644 --- a/crates/bake/src/cage/vertex_reach.rs +++ b/crates/bake/src/cage/vertex_reach.rs @@ -17,10 +17,7 @@ impl VertexReach { /// Whether the ray misses the vertex (or may not hit its part) at `frontal` and `rear` world units of cage distance; with `ignore_backface` it also misses a vertex whose triangles face away from the ray pub fn missed(&self, frontal: f32, rear: f32, ignore_backface: bool) -> bool { let origin = self.start.origin(self.low_position, frontal); - let (direction, front) = match self.start { - RayStart::CageMesh(offset) => (offset.normalize_or_zero(), offset.length()), - RayStart::Distance { up, scale } => (-up, frontal * scale), - }; + let (direction, front, rear) = self.start.span(frontal, rear); let along_ray = (self.high_position - origin).dot(direction); !self.name_matches || !(0.0..=front + rear).contains(&along_ray) || (ignore_backface && self.high_facing.dot(direction) > 0.0) diff --git a/crates/bake/src/lib.rs b/crates/bake/src/lib.rs index 1d99ab36..5c8c3ba8 100644 --- a/crates/bake/src/lib.rs +++ b/crates/bake/src/lib.rs @@ -5,6 +5,7 @@ mod bake_error; mod bake_output; +mod bake_passes; mod bake_request; mod cage; mod high_poly; @@ -14,6 +15,7 @@ mod progress; pub use bake_error::BakeError; pub use bake_output::BakeOutput; +pub use bake_passes::BakePasses; pub use bake_request::BakeRequest; pub use cage::{CageShell, HighPolyReach, RayStart, VertexReach}; pub use high_poly::HighPoly; @@ -149,7 +151,7 @@ fn alloc(count: usize, value: T) -> Result, BakeError> { } pub fn bake(request: &BakeRequest, progress: &Progress) -> Result { - bake_in_strips(request, progress, STRIP_TEXELS, &CpuTracer, &[]) + bake_tiles(request, progress, &[], None) } /// Retry on the CPU if the supplied tracer fails @@ -159,19 +161,12 @@ pub fn bake_on(request: &BakeRequest, progress: &Progress, tracer: &dyn Tracer) /// Excluded atlas blocks produce no samples; their geometry still participates in ray tracing pub fn bake_tiles(request: &BakeRequest, progress: &Progress, excluded_tiles: &[(u32, u32)], tracer: Option<&dyn Tracer>) -> Result { - let tracer = tracer.unwrap_or(&CpuTracer); - match bake_in_strips(request, progress, STRIP_TEXELS, tracer, excluded_tiles) { - Err(BakeError::Tracer(error)) => { - let mut output = bake_in_strips(request, progress, STRIP_TEXELS, &CpuTracer, excluded_tiles)?; - output.tracer = format!("CPU ({} unavailable: {error})", tracer.name()); - Ok(output) - } - result => result, - } + BakePasses::new(*request).run(request.settings, progress, excluded_tiles, tracer, STRIP_TEXELS) } type OutRow<'a> = Vec<&'a mut [f32]>; +#[cfg(test)] fn bake_in_strips( request: &BakeRequest, progress: &Progress, @@ -179,9 +174,19 @@ fn bake_in_strips( tracer: &dyn Tracer, excluded_tiles: &[(u32, u32)], ) -> Result { - validate(request)?; - if excluded_tiles.iter().any(|(column, row)| *column >= request.tiles.0 || *row >= request.tiles.1) { - return Err(BakeError::Invalid("excluded UV tile lies outside the bake atlas".into())); + BakePasses::new(*request).run(request.settings, progress, excluded_tiles, Some(tracer), strip_texels) +} + +fn bake_prepared( + request: &BakeRequest, + context: &map::BakeContext, + progress: &Progress, + strip_texels: usize, + tracer: &dyn Tracer, + excluded_tiles: &[(u32, u32)], +) -> Result { + if progress.cancel.load(Relaxed) { + return Err(BakeError::Cancelled); } let settings = request.settings; @@ -189,7 +194,6 @@ fn bake_in_strips( let tile_size = (tile_width as usize, tile_height as usize); let samples_per_axis = settings.common.antialiasing.samples_per_axis() as usize; let (width, height) = (tile_size.0 * request.tiles.0 as usize, tile_size.1 * request.tiles.1 as usize); - let context = map::BakeContext::new(request)?; let tracer = if context.casts_rays() { tracer } else { &CpuTracer }; let meshes = context.trace_meshes(); let mut scene = tracer.scene(&meshes)?; @@ -259,9 +263,10 @@ fn bake_in_strips( if progress.cancel.load(Relaxed) { return Err(BakeError::Cancelled); } + // Global sample indices keep noise unchanged across strip and batch sizes bake_rows( - &context, + context, &maps, request.mesh, &gbuffer, @@ -313,6 +318,7 @@ fn bake_in_strips( if progress.cancel.load(Relaxed) { return Err(BakeError::Cancelled); } + progress.done.store(10_000, Relaxed); Ok(BakeOutput { resolution: width as u32, height: height as u32, maps: output, tracer: tracer.name() }) } @@ -349,6 +355,7 @@ fn bake_rows( .collect() }) .collect(); + let row_offsets: Vec = samples_by_row .iter() .scan(0, |sample_count, row| { @@ -362,11 +369,12 @@ fn bake_rows( true => { let (rays, frontal_distances): (Vec, Vec) = samples().map(|sample| context.transfer_ray(&sample.surface, sample.bary)).unzip(); let hits = scene.closest(1, &rays, context.ignore_transfer_backface())?; - hits.into_par_iter().zip(frontal_distances).map(|(hit, front)| context.transfer(hit, front)).collect() + hits.into_par_iter().zip(&rays).zip(frontal_distances).map(|((hit, ray), front)| context.transfer(hit, front, ray.max_distance)).collect() } false => Vec::new(), }; let transfer = |sample_index: usize| transfers.get(sample_index).and_then(Option::as_ref); + let curvature = match context.traces_curvature() { true => { let items: Vec<(&Surface, Option<&map::Transfer>)> = samples_by_row @@ -379,6 +387,7 @@ fn bake_rows( } false => Vec::new(), }; + let queries: Vec = match context.ao.is_some() || context.bent.is_some() || context.thickness.is_some() { true => samples_by_row .par_iter() @@ -388,6 +397,7 @@ fn bake_rows( .collect(), false => Vec::new(), }; + // Share occlusion results when the bent-normal ray settings match let separate_bent_pass = context.bent.filter(|_| context.bent != context.ao); let passes: Vec = [context.ao, separate_bent_pass, context.thickness].into_iter().flatten().collect(); diff --git a/crates/bake/src/map/bake_context.rs b/crates/bake/src/map/bake_context.rs index bbeb623e..156d392f 100644 --- a/crates/bake/src/map/bake_context.rs +++ b/crates/bake/src/map/bake_context.rs @@ -1,7 +1,7 @@ use super::curvature::Curvature; use super::sampling::{pack, splitmix64, tangent_normal}; use super::{position_projection::PositionProjection, source::Source, traced::Traced, transfer::Transfer}; -use crate::cage::{RayFrame, RayStart}; +use crate::cage::RayFrame; use crate::tracing::{ANY, Hemisphere, Query, Ray, RayKind, RayScene, TraceMesh}; use crate::{BakeError, BakeRequest, MeshExtent}; use rayon::prelude::*; @@ -12,10 +12,13 @@ use texturecraft_geom::{Hit, Surface, surface_at}; const CURVATURE_CHUNK: usize = 1 << 15; +/// Height relative to the rays divides by the ray's length; this keeps a zero-length ray from dividing by zero +const SHORTEST_RAY: f32 = 1e-20; + pub(crate) struct BakeContext<'a> { low: Source<'a>, high: Option>, - ray_frame: RayFrame<'a>, + ray_frame: &'a RayFrame<'a>, settings: &'a BakeSettings, frontal: f32, rear: f32, @@ -28,11 +31,9 @@ pub(crate) struct BakeContext<'a> { } impl<'a> BakeContext<'a> { - pub(crate) fn new(request: &BakeRequest<'a>) -> Result, BakeError> { + pub(crate) fn with_frame(request: &BakeRequest<'a>, extent: MeshExtent, ray_frame: &'a RayFrame<'a>) -> Self { let settings = request.settings; - let extent = MeshExtent::of(request.mesh)?; let (low, high) = Source::of_request(request); - let ray_frame = RayFrame::new(request, extent)?; let (mesh_scale, ray_epsilon) = (extent.scale, extent.ray_epsilon()); let pass = |map: BakedMap, ray_settings: &RaySettings, kind: RayKind| { let half_angle_radians = (ray_settings.spread.clamp(0.0, 180.0) * 0.5).to_radians(); @@ -74,7 +75,7 @@ impl<'a> BakeContext<'a> { } let cage_units = ray_frame.cage_units; - Ok(BakeContext { + BakeContext { low, high, ray_frame, @@ -87,7 +88,7 @@ impl<'a> BakeContext<'a> { ao, bent, thickness, - }) + } } pub(crate) fn ignore_transfer_backface(&self) -> bool { @@ -109,21 +110,19 @@ impl<'a> BakeContext<'a> { pub(crate) fn transfer_ray(&self, surface: &Surface, barycentric: [f32; 2]) -> (Ray, f32) { let start = self.ray_frame.start(surface, barycentric); let origin = start.origin(surface.pos, self.frontal); - let (direction, front) = match start { - RayStart::CageMesh(offset) => (offset.normalize(), offset.length()), - RayStart::Distance { up, scale } => (-up, self.frontal * scale), - }; + let (direction, front, rear) = start.span(self.frontal, self.rear); let key = match self.settings.high_poly.match_mode { MeshMatchMode::Always => ANY, MeshMatchMode::ByMeshName => self.low.key.get(surface.tri as usize).copied().unwrap_or(ANY), }; - (Ray { origin, direction, max_distance: front + self.rear, key }, front) + (Ray { origin, direction, max_distance: front + rear, key }, front) } - pub(crate) fn transfer(&self, hit: Option, front: f32) -> Option { + /// What the transfer ray that ran `front` to the low poly and `ray_length` in all brought back from the high poly + pub(crate) fn transfer(&self, hit: Option, front: f32, ray_length: f32) -> Option { let (high, hit) = (self.high.as_ref()?, hit?); let surface = surface_at(high.mesh, hit.tri, hit.u, hit.v)?; - Some(Transfer { surface, bary: [hit.u, hit.v], t: hit.t, front }) + Some(Transfer { surface, bary: [hit.u, hit.v], t: hit.t, front, ray_length }) } pub(crate) fn query(&self, transfer: Option<&Transfer>, low_surface: &Surface, seed: u64) -> Query { @@ -245,7 +244,7 @@ impl<'a> BakeContext<'a> { let relative_to_rays = self.settings.maps.height.parameters.normalization == texturecraft_core::HeightNormalization::RelativeToRayDistances; [transfer.map_or(if relative_to_rays { 0.5 } else { 0.0 }, |hit| { let height = hit.front - hit.t; - if relative_to_rays { (0.5 + height / (hit.front + self.rear).max(1e-20)).clamp(0.0, 1.0) } else { height } + if relative_to_rays { (0.5 + height / hit.ray_length.max(SHORTEST_RAY)).clamp(0.0, 1.0) } else { height } }); 3] } BakedMap::Opacity if missed => [0.0; 3], diff --git a/crates/bake/src/map/transfer.rs b/crates/bake/src/map/transfer.rs index c1200053..46c67f28 100644 --- a/crates/bake/src/map/transfer.rs +++ b/crates/bake/src/map/transfer.rs @@ -5,4 +5,6 @@ pub(crate) struct Transfer { pub(super) bary: [f32; 2], pub(super) t: f32, pub(super) front: f32, + /// The whole ray, from the cage to its rear end + pub(super) ray_length: f32, } diff --git a/crates/bake/src/test/cage_shell.rs b/crates/bake/src/test/cage_shell.rs index 40edd3b8..a437c089 100644 --- a/crates/bake/src/test/cage_shell.rs +++ b/crates/bake/src/test/cage_shell.rs @@ -17,7 +17,9 @@ fn painted_map() -> BakePaintMap { fn assert_cage_matches_the_ray_origins(request: &BakeRequest) { let shell = CageShell::new(request).unwrap(); let corners = shell.corners(request.settings.cage.max_frontal); - let context = BakeContext::new(request).unwrap(); + let extent = crate::MeshExtent::of(request.mesh).unwrap(); + let frame = crate::cage::RayFrame::new(request, extent).unwrap(); + let context = BakeContext::with_frame(request, extent, &frame); let triangles: Vec = request.mesh.triangles_of(request.material).collect(); assert_eq!(corners.len(), triangles.len() * 3); @@ -60,6 +62,12 @@ fn the_cage_corners_are_the_bake_ray_origins() { face_normals }; assert_cage_matches_the_ray_origins(&request(&face_normals)); + let automatic = { + let mut automatic = bake_settings.clone(); + automatic.cage.kind = CageType::Automatic; + automatic + }; + assert_cage_matches_the_ray_origins(&request(&automatic)); } #[test] diff --git a/crates/bake/src/test/fitted_cage.rs b/crates/bake/src/test/fitted_cage.rs new file mode 100644 index 00000000..3cfec7a5 --- /dev/null +++ b/crates/bake/src/test/fitted_cage.rs @@ -0,0 +1,250 @@ +use super::{covered_values, settings, transfer}; +use crate::{BakeRequest, CageShell, HighPoly, HighPolyReach}; +use texturecraft_core::{BakeSettings, BakedMap, CageType, MeshMatchMode}; +use texturecraft_geom::glam::Vec3; +use texturecraft_geom::{Bvh, Mesh, primitives}; + +/// A distance setting far larger than any fitted distance in these tests, to tell the two apart +const UNFITTED_DISTANCE: f32 = 0.5; + +/// Settings baking `maps` with the automatic cage, and distance settings no fitted cage comes near +fn automatic(maps: &[BakedMap]) -> BakeSettings { + let mut bake_settings = settings(32, maps); + bake_settings.cage.kind = CageType::Automatic; + bake_settings.cage.relative_to_bounding_box = false; + (bake_settings.cage.max_frontal, bake_settings.cage.max_rear) = (UNFITTED_DISTANCE, UNFITTED_DISTANCE); + bake_settings +} + +/// How far each corner of the automatic cage of the flat `low` around `high` rises above it, with the corner's low-poly position +fn cage_heights(low: &Mesh, high: &Mesh, bake_settings: &BakeSettings) -> Vec<(Vec3, f32)> { + let (low_bvh, high_bvh) = (Bvh::new(low), Bvh::new(high)); + let request = BakeRequest { + low_base_color: &[], + mesh: low, + bvh: &low_bvh, + material: 0, + settings: bake_settings, + high: Some(HighPoly { file_ids: &[], mesh: high, bvh: &high_bvh, base_color: &[] }), + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }; + let shell = CageShell::new(&request).unwrap(); + let corners = shell.corners(bake_settings.cage.max_frontal); + shell.positions.iter().zip(corners).map(|(position, corner)| (*position, corner.y - position.y)).collect() +} + +/// Every submesh on the first material, so the cage shell of material 0 covers all the parts +fn one_material(mesh: &mut Mesh) { + mesh.materials.truncate(1); + for submesh in &mut mesh.submeshes { + submesh.material = 0; + } +} + +#[test] +fn the_automatic_cage_reaches_a_high_poly_the_default_distances_miss() { + let low = primitives::cube(1.0); + let high = primitives::sphere(0.8, 32, 16); + let opacity_of = |bake_settings: &BakeSettings| -> Vec { + let output = transfer(&low, &high, None, bake_settings).unwrap(); + covered_values(&low, &output, BakedMap::Opacity).into_iter().map(|(_, opacity)| opacity).collect() + }; + + let distance_based = opacity_of(&settings(32, &[BakedMap::Opacity])); + assert!(distance_based.contains(&0.0), "the sphere is beyond the default distances at the middle of each face"); + + let mut bake_settings = settings(32, &[BakedMap::Opacity]); + bake_settings.cage.kind = CageType::Automatic; + let fitted = opacity_of(&bake_settings); + assert!(fitted.iter().all(|opacity| *opacity == 1.0), "every ray of the automatic cage finds the sphere"); + + // The triangles at the sphere's poles have no area, so a pole vertex has no side to face the ray with + bake_settings.high_poly.ignore_backface = false; + let (low_bvh, high_bvh) = (Bvh::new(&low), Bvh::new(&high)); + let request = BakeRequest { + low_base_color: &[], + mesh: &low, + bvh: &low_bvh, + material: 0, + settings: &bake_settings, + high: Some(HighPoly { file_ids: &[], mesh: &high, bvh: &high_bvh, base_color: &[] }), + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }; + let reach = HighPolyReach::new(&request).unwrap(); + for vertex in 0..high.positions.len() { + assert_eq!(reach.missed(vertex, 0.0, 0.0), Some(false), "high-poly vertex {vertex} is inside the cage whatever the distance settings"); + } +} + +#[test] +fn the_automatic_cage_stays_low_where_the_high_poly_is_low() { + const LOW_HEIGHT: f32 = 0.01; + const RAISED_HEIGHT: f32 = 0.2; + const RAISED_FROM_X: f32 = 0.25; + + let low = primitives::plane(1.0, 8); + let mut high = primitives::plane(1.0, 40); + for position in &mut high.positions { + position.y = if position.x > RAISED_FROM_X { RAISED_HEIGHT } else { LOW_HEIGHT }; + } + + let heights = cage_heights(&low, &high, &automatic(&[BakedMap::Normal])); + + for (position, height) in heights { + if position.x < 0.0 { + assert!((LOW_HEIGHT..RAISED_HEIGHT / 2.0).contains(&height), "the cage at {position} hugs the low part: {height}"); + } else if position.x > RAISED_FROM_X + 0.125 { + assert!((RAISED_HEIGHT..RAISED_HEIGHT * 2.0).contains(&height), "the cage at {position} clears the raised part: {height}"); + } + } +} + +#[test] +fn a_ray_that_only_finds_a_far_surface_takes_the_nearest_surface_height_instead() { + const PATCH_HEIGHT: f32 = 0.02; + const CEILING_HEIGHT: f32 = 1.0; + + // A low-plane vertex beside the patch's edge: the patch is its nearest high poly, the ceiling is straight above it + const BESIDE_PATCH: Vec3 = Vec3::new(0.125, 0.0, 0.0); + + // Far enough that the ceiling's own corners are nearest to the low plane's border, not to the vertex tested + const CEILING_REACH: f32 = 1000.0; + + // The ceiling starts just past the patch's edge (x = 0), the patch covers the low plane's other half + const CEILING_FROM_X: f32 = 0.05; + const PATCH_SIZE: f32 = 0.5; + const SAME_POSITION: f32 = 1e-4; + + let low = primitives::plane(1.0, 8); + let mut high = primitives::plane(PATCH_SIZE, 1); + for position in &mut high.positions { + *position = Vec3::new(position.x - PATCH_SIZE / 2.0, PATCH_HEIGHT, position.z); + } + let ceiling = Mesh::from_parts( + vec![ + Vec3::new(CEILING_FROM_X, CEILING_HEIGHT, -CEILING_REACH), + Vec3::new(CEILING_FROM_X, CEILING_HEIGHT, CEILING_REACH), + Vec3::new(CEILING_REACH, CEILING_HEIGHT, 0.0), + ], + None, + vec![Default::default(); 3], + vec![0, 1, 2], + "ceiling", + ) + .unwrap(); + high.append(&ceiling); + + let heights = cage_heights(&low, &high, &automatic(&[BakedMap::Normal])); + + let (_, height) = heights.iter().find(|(position, _)| position.distance(BESIDE_PATCH) < SAME_POSITION).unwrap(); + assert!(*height < CEILING_HEIGHT / 2.0, "the cage beside the patch stays near the patch, not the ceiling: {height}"); +} + +#[test] +fn a_part_no_high_poly_part_matches_keeps_the_distance_settings() { + let mut low = primitives::plane(1.0, 2); + let mut high = primitives::plane(1.0, 2); + low.submeshes[0].name = "panel_low".into(); + high.submeshes[0].name = "door_high".into(); + let mut bake_settings = automatic(&[BakedMap::Normal]); + bake_settings.high_poly.match_mode = MeshMatchMode::ByMeshName; + + let heights = cage_heights(&low, &high, &bake_settings); + + assert!(heights.iter().all(|(_, height)| *height == UNFITTED_DISTANCE)); +} + +#[test] +fn a_part_meeting_another_part_takes_its_distances_from_its_own_high_poly_only() { + const LOW_HEIGHT: f32 = 0.01; + const RAISED_HEIGHT: f32 = 0.3; + + // Two low parts sharing the edge x = 0, under a low and a raised high-poly part matched by name + let part = |name: &str, side: f32, height: f32, subdivisions: usize| { + let mut part = primitives::plane(1.0, subdivisions); + for position in &mut part.positions { + *position += Vec3::new(side * 0.5, height, 0.0); + } + part.submeshes[0].name = name.into(); + part + }; + let mut low = part("left_low", -1.0, 0.0, 4); + low.append(&part("right_low", 1.0, 0.0, 4)); + let mut high = part("left_high", -1.0, LOW_HEIGHT, 8); + high.append(&part("right_high", 1.0, RAISED_HEIGHT, 8)); + for mesh in [&mut low, &mut high] { + one_material(mesh); + } + let mut bake_settings = automatic(&[BakedMap::Normal]); + bake_settings.high_poly.match_mode = MeshMatchMode::ByMeshName; + + let heights = cage_heights(&low, &high, &bake_settings); + + // The left part's triangles come first, three corners each + let left_corners = low.submeshes[0].count as usize; + for (position, height) in &heights[..left_corners] { + assert!(*height < RAISED_HEIGHT / 2.0, "the left part's cage at {position} stays near the left high poly: {height}"); + } +} + +#[test] +fn parts_back_to_back_fit_their_cages_along_their_own_normals() { + const SHEET_DISTANCE: f32 = 0.2; + + // A plane facing up and the same plane facing down, each facing its own high-poly sheet: welded, their normals cancel out + let named = |mut mesh: Mesh, name: &str| { + mesh.submeshes[0].name = name.into(); + mesh + }; + let facing_down = |mut mesh: Mesh| { + for normal in &mut mesh.normals { + *normal = -*normal; + } + for triangle in mesh.indices.as_chunks_mut::<3>().0 { + triangle.swap(1, 2); + } + mesh + }; + let sheet = |height: f32| { + let mut sheet = primitives::plane(1.0, 8); + for position in &mut sheet.positions { + position.y = height; + } + sheet + }; + let mut low = named(primitives::plane(1.0, 4), "front_low"); + low.append(&named(facing_down(primitives::plane(1.0, 4)), "back_low")); + let mut high = named(sheet(SHEET_DISTANCE), "front_high"); + high.append(&named(facing_down(sheet(-SHEET_DISTANCE)), "back_high")); + for mesh in [&mut low, &mut high] { + one_material(mesh); + } + + for match_mode in [MeshMatchMode::Always, MeshMatchMode::ByMeshName] { + let mut bake_settings = automatic(&[BakedMap::Normal]); + bake_settings.high_poly.match_mode = match_mode; + + let heights = cage_heights(&low, &high, &bake_settings); + + // The front part's triangles come first, three corners each + let front_corners = low.submeshes[0].count as usize; + for (position, height) in &heights[..front_corners] { + assert!( + (SHEET_DISTANCE..UNFITTED_DISTANCE).contains(height), + "{match_mode:?}: the front part's cage at {position} reaches the sheet above it, fitted: {height}" + ); + } + for (position, height) in &heights[front_corners..] { + assert!( + (-UNFITTED_DISTANCE..=-SHEET_DISTANCE).contains(height), + "{match_mode:?}: the back part's cage at {position} reaches the sheet below it, fitted: {height}" + ); + } + } +} diff --git a/crates/bake/src/test/high_poly_reach.rs b/crates/bake/src/test/high_poly_reach.rs index 8a4f83c4..b001737b 100644 --- a/crates/bake/src/test/high_poly_reach.rs +++ b/crates/bake/src/test/high_poly_reach.rs @@ -69,7 +69,9 @@ fn a_vertex_is_missed_exactly_when_the_bake_ray_misses_it() { tiles: (1, 1), }; let reach = HighPolyReach::new(&request).unwrap(); - let context = BakeContext::new(&request).unwrap(); + let extent = crate::MeshExtent::of(request.mesh).unwrap(); + let frame = crate::cage::RayFrame::new(&request, extent).unwrap(); + let context = BakeContext::with_frame(&request, extent, &frame); for (vertex, vertex_reach) in reach.vertices.iter().enumerate() { let (vertex_reach, missed) = (vertex_reach.unwrap(), reach.missed(vertex, max_frontal, max_rear).unwrap()); @@ -94,6 +96,7 @@ fn a_vertex_is_missed_exactly_when_the_bake_ray_misses_it() { } } } + assert!(checked[0] > 100 && checked[1] > 100, "both reached and missed vertices were compared: {checked:?}"); } @@ -173,11 +176,14 @@ fn matching_by_mesh_name_misses_the_parts_with_another_name() { tiles: (1, 1), }; let reach = HighPolyReach::new(&request).unwrap(); - let context = BakeContext::new(&request).unwrap(); + let extent = crate::MeshExtent::of(request.mesh).unwrap(); + let frame = crate::cage::RayFrame::new(&request, extent).unwrap(); + let context = BakeContext::with_frame(&request, extent, &frame); let (_, high_keys) = transfer_keys(&request); for (vertex, vertex_reach) in reach.vertices.iter().enumerate() { let (vertex_reach, missed) = (vertex_reach.unwrap(), reach.missed(vertex, 0.02, 0.01).unwrap()); + // On the line where the two parts meet, a ray reaches either part's triangles if vertex_reach.high_position.x.abs() < BOUNDARY { continue; diff --git a/crates/bake/src/tests.rs b/crates/bake/src/tests.rs index eaa64cf2..7d94031e 100644 --- a/crates/bake/src/tests.rs +++ b/crates/bake/src/tests.rs @@ -20,6 +20,9 @@ mod bent_normal_space; #[path = "test/cage_shell.rs"] mod cage_shell; +#[path = "test/fitted_cage.rs"] +mod fitted_cage; + #[path = "test/high_poly_reach.rs"] mod high_poly_reach; diff --git a/crates/compose/src/below.rs b/crates/compose/src/below.rs index cdca3b83..dd440224 100644 --- a/crates/compose/src/below.rs +++ b/crates/compose/src/below.rs @@ -165,7 +165,7 @@ impl StackKey { match &effect.kind { EffectKind::Fill { source, .. } => source.images().into_iter().for_each(&mut record_image_name), EffectKind::Material(fill) => fill.sources.values().flat_map(Source::images).for_each(&mut record_image_name), - EffectKind::Generator(generator) => generator.inputs.values().flat_map(Source::images).for_each(&mut record_image_name), + EffectKind::Generator(generator) => generator.sources().flat_map(Source::images).for_each(&mut record_image_name), EffectKind::ColorSelection(selection) => selection.id_map.iter().for_each(|name| record_image_name(name)), _ => {} } diff --git a/crates/compose/src/curvature_sizes.rs b/crates/compose/src/curvature_sizes.rs index 0b7138bc..4660ca45 100644 --- a/crates/compose/src/curvature_sizes.rs +++ b/crates/compose/src/curvature_sizes.rs @@ -4,13 +4,16 @@ use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex, Weak}; use rayon::prelude::*; -use texturecraft_core::{BakedMap, BlockScales, CurvatureDetail}; +use texturecraft_core::{BakedMap, BlockScales}; use texturecraft_texel::dilate::{DilationMap, NONE}; use crate::curvature_size_level::{CurvatureSizeLevel, DEVIATION_SCALE}; use crate::eval::{BLUR_BOX_PASSES, Inputs, blur}; -/// The curvature map padded past its UV islands and blurred at each size of [`CurvatureDetail::SIZES`] after the first. +/// The blur radius of each level in texels at 2K: the detail sizes of [`texturecraft_core::CurvatureDetail::SIZES`] after the first, then wider ones the wear generators' edges smoothness reaches +pub const LEVEL_RADII: [f32; 8] = [1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0, 128.0]; + +/// The curvature map padded past its UV islands and blurred at each radius of [`LEVEL_RADII`] pub struct CurvatureSizes { /// One per blurred size, built once a generator gives that size a weight above 0. pub levels: Vec>>, @@ -31,7 +34,11 @@ const CACHE_MAPS: usize = 16; impl CurvatureSizes { /// The sizes of the texture set `inp` composites, holding at least those `needed` marks (one flag per blurred size); None without a baked curvature map or a needed size. pub fn of(inp: &Inputs, needed: &[bool]) -> Option> { - let curvature = inp.baked.maps.get(&BakedMap::Curvature)?; + CurvatureSizes::of_map(inp, inp.baked.maps.get(&BakedMap::Curvature)?, needed) + } + + /// The sizes of `curvature`, a map in the baked curvature map's layout (the baked map or one derived from it) + pub fn of_map(inp: &Inputs, curvature: &Arc>, needed: &[bool]) -> Option> { let (width, height) = (inp.baked.resolution, inp.baked.height(BakedMap::Curvature)); if !needed.contains(&true) || width == 0 || height == 0 { return None; @@ -70,14 +77,14 @@ impl CurvatureSizes { padding.src.par_iter().map(|&source| if source == NONE { 0.0 } else { curvature.get(source as usize).copied().unwrap_or(0.5) - 0.5 }).collect(); let (block_width, block_height) = (block.0.max(1).min(width), block.1.max(1).min(height)); - let levels = CurvatureDetail::SIZES + let levels = LEVEL_RADII .iter() - .skip(1) .enumerate() .map(|(level, size)| { if let Some(existing) = built.and_then(|sizes| sizes.levels.get(level)).and_then(Option::clone) { return Some(existing); } + if !needed.get(level).copied().unwrap_or(false) { return None; } @@ -85,6 +92,7 @@ impl CurvatureSizes { // Sizes are texels at 2K; a blur this wide holds nothing finer than half its radius, so it is stored that much coarser let radius = (size * block_width as f32 / 2048.0).round().max(1.0) as u32; let mut step = (radius / 2).max(1).next_power_of_two(); + // A coarse cell must not average curvature from different UV tiles while !block_width.is_multiple_of(step) || !block_height.is_multiple_of(step) { step /= 2; @@ -247,6 +255,8 @@ fn coarsen(data: &[f32], (width, height): (u32, u32), step: u32, block: (u32, u3 #[cfg(test)] mod tests { + use texturecraft_core::CurvatureDetail; + use super::*; #[test] @@ -473,4 +483,9 @@ mod tests { } } } + + #[test] + fn the_first_levels_are_the_detail_sizes() { + assert_eq!(LEVEL_RADII[..CurvatureDetail::BLURRED_SIZES], CurvatureDetail::SIZES[1..]); + } } diff --git a/crates/compose/src/dripping_rust.rs b/crates/compose/src/dripping_rust.rs new file mode 100644 index 00000000..c08bc90b --- /dev/null +++ b/crates/compose/src/dripping_rust.rs @@ -0,0 +1,316 @@ +//! The Dripping Rust generator: rust grown from the occlusion, broken up by grunge, then run down the mesh in drips; built once per layout and settings + +use std::sync::Arc; + +use rayon::prelude::*; +use texturecraft_core::{BakedMap, DrippingRustParameters, GeneratorKind, WearParameters}; +use texturecraft_geom::{NO_TRI, TrianglePartition}; + +use crate::eval::{Inputs, texel_coords}; +use crate::field_cache::FieldCache; +use crate::histogram_scan::histogram_scan; +use crate::wear; +use crate::working_field::{REFERENCE_TILE_TEXELS, blur_blocks, box_radius}; + +/// The rust before any grunge: `RUST_FLOOR + RUST_GAIN * max(RUST_OCCLUSION − occlusion, 0)^RUST_POWER` (fitted to the reference) +const RUST_FLOOR: f32 = 0.315; +const RUST_GAIN: f32 = 3.19; +const RUST_OCCLUSION: f32 = 0.849; +const RUST_POWER: f32 = 2.38; + +/// How much grunge breaks the rust up: the spread of the reference's noise (measured); the pattern itself is inferred +const GRUNGE_SPREAD: f32 = 0.19; + +/// Blur sizes at Spreading Smoothness 1 and Drips Smoothness 1, as gaussian sigmas in texels of a 2K UV tile (fitted) +const SPREADING_SIGMA_2K: f32 = 47.0; +const DRIPS_SIGMA_2K: f32 = 11.5; + +/// How far a drip runs at Drips Intensity 1, in texels of a 2K UV tile, and how it fades along its length: `1 − DRIP_FADE · along^DRIP_FADE_POWER` (fitted) +const DRIP_LENGTH_2K: f32 = 90.86; +const DRIP_FADE: f32 = 0.898; +const DRIP_FADE_POWER: f32 = 0.671; + +/// Coverage below which a blurred texel has nothing to average +const MIN_COVERAGE: f32 = 1e-3; + +static CACHE: FieldCache = FieldCache::new(); + +/// The rust before its spreading and contrast at every working texel of `inp` (0 outside the islands) +pub(crate) fn rust_field(inp: &Inputs, geometry: u64, rust: &DrippingRustParameters, seed: u32) -> Arc> { + let settings = vec![ + rust.spreading_smoothness.to_bits(), + rust.drips_intensity.to_bits(), + rust.drips_smoothness.to_bits(), + rust.drips_samples, + u32::from(rust.axis), + seed, + ]; + CACHE.get_or_build(inp, geometry, &[BakedMap::AmbientOcclusion], settings, |block| build(inp, rust, seed, block)) +} + +/// The value at a working texel: the rust spread and contrasted +pub(crate) fn rust_value(rust: &DrippingRustParameters, field: f32) -> f32 { + histogram_scan(field, rust.spreading, rust.contrast) +} + +fn build(inp: &Inputs, rust: &DrippingRustParameters, seed: u32, block: (u32, u32)) -> Vec { + let gbuf = inp.gbuf; + let (width, height) = (gbuf.width, gbuf.height); + let cover: Vec = (0..width * height).map(|texel| if gbuf.covered(texel as usize) { 1.0 } else { 0.0 }).collect(); + let tile_texels = |x: u32, y: u32| block.0 as f32 * inp.block_scales.at(x, y); + + // The rust from the occlusion, broken up by the Dirt generator's grunge + let grunge = WearParameters::defaults(GeneratorKind::Dirt); + let rust_at = |texel: u32| { + let (x, y) = (texel % width, texel / width); + let occlusion = inp.baked.sample_working(BakedMap::AmbientOcclusion, x, y, (width, height), &inp.block_scales).map_or(1.0, |value| value[0]); + let base = RUST_FLOOR + RUST_GAIN * (RUST_OCCLUSION - occlusion).max(0.0).powf(RUST_POWER); + let noise = grunge.map_or(0.0, |grunge| wear::grunge(GeneratorKind::Dirt, &grunge, seed, &texel_coords(inp, x, y))); + base + GRUNGE_SPREAD * noise + }; + let mut field: Vec = (0..width * height).into_par_iter().map(|texel| if gbuf.covered(texel as usize) { rust_at(texel) } else { 0.0 }).collect(); + + let radius_at = |sigma_2k: f32, smoothness: f32| move |x: u32, y: u32| box_radius(smoothness * sigma_2k * tile_texels(x, y) / REFERENCE_TILE_TEXELS); + blur_over_cover(&mut field, &cover, (width, height), block, radius_at(SPREADING_SIGMA_2K, rust.spreading_smoothness)); + let mut field = drips(inp, rust, field, (width, height), &tile_texels); + blur_over_cover(&mut field, &cover, (width, height), block, radius_at(DRIPS_SIGMA_2K, rust.drips_smoothness)); + field.iter_mut().zip(&cover).for_each(|(value, covered)| *value = if *covered > 0.0 { value.clamp(0.0, 1.0) } else { 0.0 }); + field +} + +/// `values` blurred within each UV tile block by the radius `radius_at` gives, weighted by `cover` so the empty space around the islands doesn't bleed in +fn blur_over_cover(values: &mut [f32], cover: &[f32], size: (u32, u32), block: (u32, u32), radius_at: impl Fn(u32, u32) -> usize + Copy) { + let has_blur = (0..size.1).step_by(block.1 as usize).any(|top| (0..size.0).step_by(block.0 as usize).any(|left| radius_at(left, top) > 0)); + if !has_blur { + return; + } + + let mut sums: Vec = values.iter().zip(cover).map(|(value, covered)| value * covered).collect(); + let mut weights = cover.to_vec(); + blur_blocks(&mut sums, size, block, radius_at); + blur_blocks(&mut weights, size, block, radius_at); + values.par_iter_mut().zip(sums.par_iter().zip(weights.par_iter())).zip(cover.par_iter()).for_each(|((value, (sum, weight)), covered)| { + if *covered > 0.0 && *weight > MIN_COVERAGE { + *value = sum / weight; + } + }); +} + +/// Each texel takes the most rust found uphill along the drip axis, fading with how far up it lies +fn drips( + inp: &Inputs, + rust: &DrippingRustParameters, + field: Vec, + (width, height): (u32, u32), + tile_texels: &(impl Fn(u32, u32) -> f32 + Sync), +) -> Vec { + let gbuf = inp.gbuf; + if rust.drips_samples == 0 || rust.drips_intensity <= 0.0 { + return field; + } + + let axis = usize::from(rust.axis.min(2)); + let (low, high) = inp.bounds; + let low = low.to_array()[axis]; + let extent = (high.to_array()[axis] - low).max(f32::EPSILON); + let material = inp.project.texture_set(inp.ts).map_or(0, |set| set.material); + let islands = TrianglePartition::uv_islands(inp.mesh, material); + let surface: Vec<(u32, f32)> = (0..width * height) + .into_par_iter() + .map(|texel| { + let triangle = gbuf.tri.get(texel as usize).copied().unwrap_or(NO_TRI); + let Some(island) = islands.index_of(triangle) else { return (NO_TRI, 0.0) }; + + gbuf.surface(inp.mesh, texel as usize).map_or((NO_TRI, 0.0), |surface| (island as u32, (surface.pos.to_array()[axis] - low) / extent)) + }) + .collect(); + drop(islands); + + let index_at = |x: i64, y: i64| -> Option { + if x < 0 || y < 0 || x >= i64::from(width) || y >= i64::from(height) { + return None; + } + + Some((y * i64::from(width) + x) as usize) + }; + let samples = rust.drips_samples; + let taps: Vec<_> = (1..=samples) + .map(|step| { + let fraction = step as f32 / samples as f32; + (fraction, 1.0 - DRIP_FADE * fraction.powf(DRIP_FADE_POWER)) + }) + .collect(); + + (0..width * height) + .into_par_iter() + .map(|texel| { + let (column, row) = (texel % width, texel / width); + let (x, y) = (i64::from(column), i64::from(row)); + let here = field.get(texel as usize).copied().unwrap_or(0.0); + let Some(&(island, axis_here)) = surface.get(texel as usize).filter(|(island, _)| *island != NO_TRI) else { return here }; + let axis_at = |x, y| { + let (other_island, value) = *surface.get(index_at(x, y)?)?; + (other_island == island).then_some(value) + }; + + let (dx, dy) = (slope(axis_at(x - 1, y), axis_here, axis_at(x + 1, y)), slope(axis_at(x, y - 1), axis_here, axis_at(x, y + 1))); + let length = (dx * dx + dy * dy).sqrt(); + if !length.is_finite() || length <= f32::EPSILON { + return here; + } + + let reach = rust.drips_intensity * DRIP_LENGTH_2K * tile_texels(column, row) / REFERENCE_TILE_TEXELS; + let mut most = here; + let mut current = (x, y); + 'ray: for &(fraction, fade) in &taps { + let distance = reach * fraction; + let sample = ((x as f32 + distance * dx / length).round() as i64, (y as f32 + distance * dy / length).round() as i64); + + // A sparse tap must still have continuous coverage along the ray + while current != sample { + current = next_ray_texel((x, y), current, sample, (dx, dy)); + if axis_at(current.0, current.1).is_none() { + break 'ray; + } + } + + // A tap beyond a ridge contributes only if it is higher than the receiving texel + if axis_at(sample.0, sample.1).is_some_and(|value| value >= axis_here) + && let Some(value) = index_at(sample.0, sample.1).and_then(|index| field.get(index)) + { + most = most.max(*value * fade); + } + } + most + }) + .collect() +} + +/// Finite difference within one UV island, one-sided at its edge +fn slope(before: Option, here: f32, after: Option) -> f32 { + match (before, after) { + (Some(before), Some(after)) => (after - before) * 0.5, + (None, Some(after)) => after - here, + (Some(before), None) => here - before, + (None, None) => 0.0, + } +} + +/// Advance across the next texel boundary on a ray from a texel centre toward its next tap +fn next_ray_texel(origin: (i64, i64), (x, y): (i64, i64), (target_x, target_y): (i64, i64), (dx, dy): (f32, f32)) -> (i64, i64) { + let step_x = (target_x - x).signum(); + let step_y = (target_y - y).signum(); + if step_x == 0 || step_y == 0 { + return (x + step_x, y + step_y); + } + + // Compare crossing distances without dividing by either component + let crossing_x = ((x - origin.0).abs() as f32 + 0.5) * dy.abs(); + let crossing_y = ((y - origin.1).abs() as f32 + 0.5) * dx.abs(); + (x + step_x * i64::from(crossing_x <= crossing_y), y + step_y * i64::from(crossing_y <= crossing_x)) +} + +#[cfg(test)] +mod tests { + use texturecraft_core::{Project, TextureSet}; + use texturecraft_geom::{UvGBuffer, primitives}; + + use super::*; + use crate::{BakedMaps, PixelStore}; + + const RES: u32 = 256; + + #[test] + fn a_drip_takes_no_rust_from_past_a_ridge_lower_on_the_axis() { + // A strip rising gently to a ridge at its middle, then falling steeply + let mut mesh = primitives::plane(2.0, 64); + for position in &mut mesh.positions { + position.y = if position.z <= 0.0 { 1.0 + position.z } else { 1.0 - 8.0 * position.z }; + } + let gbuf = UvGBuffer::new(&mesh, 0, RES, RES); + let mut project = Project::new("t", "strip"); + project.texture_sets.push(TextureSet::new("A", 0, RES)); + let (pixels, baked, images) = (PixelStore::default(), BakedMaps::default(), Default::default()); + let inputs = Inputs { + project: &project, + ts: 0, + mesh: &mesh, + gbuf: &gbuf, + pixels: &pixels, + baked: &baked, + block_scales: project.texture_sets[0].block_scales(), + preview: None, + images: &images, + bounds: mesh.bounds(), + }; + + // Rust only on the steep side, all lower than the gentle side's texel just below the ridge + let rusted = |surface: &texturecraft_geom::Surface| surface.pos.z > 0.01; + let field: Vec = (0..RES * RES).map(|texel| gbuf.surface(&mesh, texel as usize).filter(rusted).map_or(0.0, |_| 1.0)).collect(); + let rust = DrippingRustParameters { drips_intensity: 1.0, drips_samples: DrippingRustParameters::MAX_SAMPLES, axis: 1, ..Default::default() }; + let dripped = drips(&inputs, &rust, field, (RES, RES), &|_, _| RES as f32); + + let below_ridge = (0..RES * RES) + .find(|texel| { + gbuf.surface(&mesh, *texel as usize).is_some_and(|surface| (surface.pos.z + 0.04).abs() < 1.0 / RES as f32 && surface.pos.x.abs() < 0.1) + }) + .expect("a texel just below the ridge"); + assert_eq!(dripped[below_ridge as usize], 0.0); + } + + #[test] + fn a_runoff_streak_requires_a_continuous_uv_surface() { + const GAP_HALF_WIDTH: f32 = 1.0 / 64.0; + let mut mesh = primitives::plane(2.0, 128); + let connected_indices = mesh.indices.clone(); + let (triangles, _) = connected_indices.as_chunks::<3>(); + let separated_indices: Vec<_> = triangles + .iter() + .filter(|triangle| { + triangle.iter().all(|&corner| mesh.positions[corner as usize].z <= -GAP_HALF_WIDTH) + || triangle.iter().all(|&corner| mesh.positions[corner as usize].z >= GAP_HALF_WIDTH) + }) + .flatten() + .copied() + .collect(); + for position in &mut mesh.positions { + position.y = position.z; + } + let mut project = Project::new("Runoff", "Plane"); + project.texture_sets.push(TextureSet::new("UV islands", 0, RES)); + let (pixels, baked, images) = (PixelStore::default(), BakedMaps::default(), Default::default()); + let index = |row| (row * RES + RES / 2) as usize; + + for (connected, indices) in [(true, connected_indices), (false, separated_indices)] { + mesh.indices = indices; + mesh.submeshes[0].count = mesh.indices.len() as u32; + let gbuf = UvGBuffer::new(&mesh, 0, RES, RES); + let inputs = Inputs { + project: &project, + ts: 0, + mesh: &mesh, + gbuf: &gbuf, + pixels: &pixels, + baked: &baked, + block_scales: project.texture_sets[0].block_scales(), + preview: None, + images: &images, + bounds: mesh.bounds(), + }; + let field: Vec = + (0..RES * RES).map(|texel| f32::from(gbuf.surface(&mesh, texel as usize).is_some_and(|surface| surface.pos.z > GAP_HALF_WIDTH))).collect(); + assert!(gbuf.covered(index(124))); + assert_eq!(gbuf.covered(index(128)), connected); + assert_eq!(field[index(124)], 0.0); + assert_eq!(field[index(131)], 1.0); + + for samples in [1, DrippingRustParameters::MAX_SAMPLES] { + let rust = DrippingRustParameters { drips_intensity: 1.0, drips_samples: samples, axis: 1, ..Default::default() }; + + let dripped = drips(&inputs, &rust, field.clone(), (RES, RES), &|_, _| RES as f32); + + assert_eq!(dripped[index(124)] > 0.0, connected, "a streak with {samples} taps requires a continuous covered surface"); + } + } + } +} diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 3097e768..52184129 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -7,16 +7,17 @@ mod evaluation_inputs; pub(crate) mod thumbnail; use std::borrow::Cow; -use std::collections::{BTreeMap, HashMap}; +use std::collections::{BTreeMap, HashMap, HashSet}; use std::sync::Arc; use rayon::prelude::*; use texturecraft_core::{ AnisotropicKuwahara, BakedMap, Bevel, BevelSmooth, BlendMode, BlockScales, Channel, ChannelKind, ColorMatch, CompareSource, ContentsOffset, - CurvatureDetail, CurvatureMode, Effect, EffectKind, FLAT_CURVATURE, Fill, Filter, Filtering, Generator, GeneratorKind, HeightMask, HeightToNormal, - HighpassSpace, ImageInput, Layer, LayerId, LayerKind, Mask, MaskBackground, MaskOutline, MicroDetail, Mirror, NormalFormat, PreparedColorMatch, - PreparedGradient, Project, Projection, RepeatMode, Sampling, ShapeCrop, Source, SourceColorMode, SourceSlopeBlur, SourceWarp, StylizedShading, - TargetColorMode, TextureSet, TileGrid, TileTransform, WarpSourceMode, blend1, blend3, lum, mix3, per_unit, posterize, udim_at, + CurvatureDetail, CurvatureMode, Effect, EffectKind, FLAT_CURVATURE, Fill, Filter, Filtering, Generator, GeneratorGlobal, GeneratorKind, + GrayscaleConversionParameters, HeightMask, HeightToNormal, HighpassSpace, ImageInput, KindControls, Layer, LayerId, LayerKind, Mask, MaskBackground, + MaskOutline, Mirror, NormalFormat, PreparedColorMatch, PreparedGradient, Project, Projection, RepeatMode, Sampling, SectionParameters, ShapeCrop, Source, + SourceColorMode, SourceSlopeBlur, SourceWarp, StylizedShading, TargetColorMode, TextureSet, TileGrid, TileTransform, WarpSourceMode, WearParameters, + blend1, blend3, lum, mix3, per_unit, posterize, udim_at, }; use texturecraft_geom::glam::{Vec2, Vec3}; use texturecraft_geom::{Mesh, NO_TRI, Surface, UvGBuffer}; @@ -24,22 +25,31 @@ use texturecraft_texel::{DilationMap, TILE, TILE_AREA, TileImage, from_u16, nois use crate::ProjectorDepthCache; use crate::below::{Band, BelowCache, Level, StackKey}; -use crate::curvature_sizes::CurvatureSizes; +use crate::curvature_sizes::{CurvatureSizes, LEVEL_RADII}; +use crate::dripping_rust; use crate::effect_histogram::EffectHistogram; use crate::environment_sh::EnvironmentSh; use crate::fill_copies::FillCopies; use crate::fill_copy::FillCopy; use crate::fill_depth::FillDepth; use crate::fill_place::FillPlace; +use crate::generator_maps::GeneratorMaps; use crate::held_fields::HeldFields; use crate::mask_gray::MaskGray; +use crate::micro_detail::AnchorHeights; use crate::pattern::{Coords, image_samples, mesh_frame, pattern_pixels, placement, procedural_in, world_noise}; use crate::pattern_context::PatternContext; use crate::projector_cover::{framed_cover, projector_cover, projector_covers_all}; +use crate::sections; use crate::shape_distance::distance_filter; use crate::slope_texel::slope_texel; use crate::store::{BakedMaps, ImageRes, ImageStore, PixelStore, decode}; +use crate::texture_layer; +use crate::three_d_distance; +use crate::uv_border_distance; use crate::warp_texel::{Input, MIN_READ_WEIGHT, Sample, warp_texel}; +use crate::wear; +use crate::wear_inputs::WearInputs; use draw_placement::DrawPlacement; use evaluation_inputs::EvaluationInputs; @@ -51,6 +61,9 @@ const COVERED: f32 = 0.9999; /// Largest projected step as a share of the image's longer side for non-UV projections const SEAM_JUMP_SHARE: f32 = 0.25; +/// Narrowest extent of the mesh's bounds a position is normalised across +const MIN_BOUNDS_EXTENT: f32 = 1e-6; + /// Stack values being composited, per channel. type Acc = [[f32; 3]; NCH]; @@ -285,8 +298,8 @@ struct EffectPlan<'a> { opacity: f32, data: Option>, preview: bool, - /// The curvature detail sizes a generator with detail reads. - curvature_sizes: Option>, + /// The detail sizes and micro details a generator reads + maps: GeneratorMaps, /// A filtered mask stage retained because an anchor above it records that stage. filtered_mask: Option<&'a Field>, /// The projector's depth map of a fill or material effect that culls by depth @@ -506,8 +519,13 @@ fn neighbourhood_filters(effects: &[Effect], res: u32, channel: Option) } // Use reference-resolution reach so all callers classify the same filters as stages - EffectKind::Generator(generator) if generator.global.blur > 0.0 || generator.resolution.can_reduce() => { - Some((index, texels(generator.global.blur_radius()) + generator.resolution.largest_cell(res) as f32, Op::Blur(None))) + EffectKind::Generator(generator) + if generator.applied_global().blur > 0.0 || generator.resolution.can_reduce() || sections::generator_blur_sigma(generator) > 0.0 => + { + let section_blur = sections::generator_blur_sigma(generator); + let section_reach = if section_blur > 0.0 { texels(section_blur) } else { 0.0 }; + let reach = texels(generator.applied_global().blur_radius()) + section_reach + generator.resolution.largest_cell(res) as f32; + Some((index, reach, Op::Blur(None))) } // A mirror reads anywhere in its UV tile @@ -1440,15 +1458,19 @@ fn layer_mask(p: &Project, id: LayerId) -> Option<&Mask> { /// Layers of `list` in drawing order (bottom → top, folder and instanced folder contents after /// their folder). -fn draw_order(inp: &EvaluationInputs, list: &[LayerId], depth: usize, place: DrawPlacement, out: &mut Vec<(LayerId, DrawPlacement)>) { +fn draw_order(inp: &EvaluationInputs, list: &[LayerId], depth: usize, place: DrawPlacement, visible_only: bool, out: &mut Vec<(LayerId, DrawPlacement)>) { if depth > texturecraft_core::project::MAX_DEPTH { return; } for id in list { out.push((*id, place)); + if visible_only && !inp.project.layers.get(id).is_some_and(|layer| layer.visible) { + continue; + } + if let Some(layer) = inp.project.content_layer(*id).filter(|layer| !layer.children().is_empty()) { - draw_order(inp, layer.children(), depth + 1, place.children(inp, *id, layer), out); + draw_order(inp, layer.children(), depth + 1, place.children(inp, *id, layer), visible_only, out); } } } @@ -1646,7 +1668,7 @@ fn filter_region( _ => None, }; let components = match job { - Job::Mask(_) if generator.is_some() => 2, + Job::Mask(_) if generator.is_some() => GENERATOR_STAGE_COMPONENTS, Job::Mask(_) => 1, Job::Content(_) => 4, }; @@ -1682,15 +1704,13 @@ fn filter_region( let height_nodes = if heights { plan_in(inputs, &[id], &[Channel::Height], tile_x, tile_y, 0, Some(below), place, None) } else { Vec::new() }; let mut mask = None; let mut nodes = Vec::new(); - let mut generator_sizes = None; + let mut generator_maps = GeneratorMaps::default(); match job { Job::Mask(layer_mask) => { // The layer's own filtered content, for a compare of it (this mask's field is not built yet) - let Some(mut mask_stack) = mask_plan(inputs, id, layer_mask, tile_x, tile_y, Some(below), place) else { - continue; - }; + let mut mask_stack = mask_plan(inputs, id, layer_mask, tile_x, tile_y, Some(below), place); - generator_sizes = mask_stack.effects.get(index).and_then(|effect| effect.curvature_sizes.clone()); + generator_maps = mask_stack.effects.get(index).map(|effect| effect.maps.clone()).unwrap_or_default(); mask_stack.effects.truncate(index); mask_stack.start = start; mask = Some(mask_stack); @@ -1715,8 +1735,9 @@ fn filter_region( let value = match (&mask, nodes.first()) { (Some(mask_stack), _) => { - let ramp = generator.map_or(0.0, |(generator, _)| texel.generator_ramp(generator, generator_sizes.as_deref())); - [texel.mask(mask_stack), ramp, 0.0, 0.0] + let ramp = generator.map_or(0.0, |(generator, _)| texel.generator_ramp(generator, &generator_maps)); + let texture = generator.and_then(|(generator, _)| texel.generator_texture(generator)).unwrap_or(0.0); + [texel.mask(mask_stack), ramp, texture, 0.0] } (None, Some(node)) => match node.chans.first().and_then(|channel_plan| texel.content(&node.content, channel_plan)) { Some((color, coverage)) => [color[0] * coverage, color[1] * coverage, color[2] * coverage, coverage], @@ -1932,7 +1953,36 @@ fn filter_region( Some(Field { x0: region_x, y0: region_y, w: width, h: height, comps: field_components, data: result, anchor_stages: Vec::new() }) } -/// The mask over a region after a generator at its own resolution and blur: `stack` is (stack below, generator ramp) per texel, sizes in texels per side. +/// Where working texel (`x`, `y`) of `inp` is, for pattern evaluation (as [`Texel::coords`] sees it outside a fill copy) +pub(crate) fn texel_coords(inp: &Inputs, x: u32, y: u32) -> Coords { + let gbuf = inp.gbuf; + let mut coords = match gbuf.surface(inp.mesh, (y * gbuf.width + x) as usize) { + Some(surface) => { + let (center, radius) = mesh_frame(inp.bounds); + Coords { uv: surface.uv, pos: (surface.pos - center) / radius, nrm: surface.nrm } + } + None => Coords { uv: Vec2::new((x as f32 + 0.5) / gbuf.width as f32, (y as f32 + 0.5) / gbuf.height as f32), pos: Vec3::ZERO, nrm: Vec3::Y }, + }; + + // UV-tiled sets: projections see the mesh's own UVs (patterns repeat per tile) + if let Ok(set) = inp.project.texture_set(inp.ts) + && let Some(grid) = set.tile_grid() + { + coords.uv = Vec2::from(set.from_atlas(&grid, coords.uv.to_array())); + } + coords +} + +/// What a generator's texture or custom grunge reads with nothing in its slot +const EMPTY_IMAGE_SLOT: Source = Source::Uniform([0.0; 3]); + +/// The step Safe Rotation turns a Grayscale Conversion image by, so it keeps tiling seamlessly +const QUARTER_TURN_DEGREES: f32 = 90.0; + +/// Values per texel of a generator stage's region: the stack below, the generator's ramp and its texture's gray +const GENERATOR_STAGE_COMPONENTS: usize = 3; + +/// The mask over a region after a generator at its own resolution and blur: `stack` is (stack below, generator ramp, texture gray) per texel, sizes in texels per side fn generator_region( generator: &Generator, blend: BlendMode, @@ -1943,7 +1993,7 @@ fn generator_region( (uv_tile, texture_set): (u32, u32), ) -> Vec { let (columns, rows) = (width as usize, height as usize); - let mut ramps: Vec = stack.par_chunks(2).map(|texel| texel.get(1).copied().unwrap_or(0.0)).collect(); + let mut ramps: Vec = stack.par_chunks(GENERATOR_STAGE_COMPONENTS).map(|texel| texel.get(1).copied().unwrap_or(0.0)).collect(); // Coarser than the UV tile: averaged over cells, then the blur around them let cell = generator.resolution.cell(uv_tile, texture_set) as usize; @@ -1951,22 +2001,24 @@ fn generator_region( ramps = resampled_by_cells(&ramps, cover, (region_x as usize, region_y as usize, columns, rows), cell); } - let blur_radius = generator.global.blur_radius_at(uv_tile).round() as usize; - if blur_radius > 0 { - let mut weights = cover.to_vec(); - blur(&mut weights, columns, rows, blur_radius); - let mut sums: Vec = ramps.iter().zip(cover).map(|(ramp, covered)| ramp * covered).collect(); - blur(&mut sums, columns, rows, blur_radius); - ramps.par_iter_mut().zip(sums.par_iter().zip(weights.par_iter())).for_each(|(ramp, (sum, weight))| { - if *weight > MIN_READ_WEIGHT { - *ramp = sum / weight; - } + // The section controls act on the signal before the global blur, their own blur first + if let Some(section) = generator.section_controls() { + blur_over_cover(&mut ramps, cover, (columns, rows), sections::blur_radius_at(generator.kind, §ion, uv_tile)); + ramps.par_iter_mut().for_each(|signal| *signal = sections::adjusted(generator.kind, §ion, *signal)); + } + + // The texture blends over the adjusted signal, before the global blur + if let Some(texture) = generator.texture_in_use() { + ramps.par_iter_mut().zip(stack.par_chunks(GENERATOR_STAGE_COMPONENTS)).for_each(|(signal, texel)| { + *signal = texture_layer::blended_over(texture, *signal, texel.get(2).copied().unwrap_or(0.0)); }); } + blur_over_cover(&mut ramps, cover, (columns, rows), generator.applied_global().blur_radius_at(uv_tile).round() as usize); + // Finished and blended over the stack below, like the generator effect itself stack - .par_chunks(2) + .par_chunks(GENERATOR_STAGE_COMPONENTS) .zip(ramps.par_iter()) .map(|(texel, ramp)| { let below = texel.first().copied().unwrap_or(0.0); @@ -1976,6 +2028,23 @@ fn generator_region( .collect() } +/// `values` blurred by three box passes of `radius`, weighted by `cover` so uncovered texels don't bleed in +fn blur_over_cover(values: &mut [f32], cover: &[f32], (columns, rows): (usize, usize), radius: usize) { + if radius == 0 { + return; + } + + let mut weights = cover.to_vec(); + blur(&mut weights, columns, rows, radius); + let mut sums: Vec = values.iter().zip(cover).map(|(value, covered)| value * covered).collect(); + blur(&mut sums, columns, rows, radius); + values.par_iter_mut().zip(sums.par_iter().zip(weights.par_iter())).for_each(|(value, (sum, weight))| { + if *weight > MIN_READ_WEIGHT { + *value = sum / weight; + } + }); +} + /// `values` averaged over `cell` × `cell` texel cells on the mesh (`cover`), read back bilinearly between cell centers. fn resampled_by_cells(values: &[f32], cover: &[f32], (region_x, region_y, width, height): (usize, usize, usize, usize), cell: usize) -> Vec { // Cells are aligned to absolute texel positions, so a texel's cell is the same in every region @@ -2035,10 +2104,10 @@ fn resampled_by_cells(values: &[f32], cover: &[f32], (region_x, region_y, width, .collect() } -/// A generator's (possibly blurred) ramp after balance, contrast, invert and offset +/// A generator's (possibly blurred) ramp after balance, contrast, invert and offset (the light controls invert their shading themselves) fn finish_generator(generator: &Generator, ramp: f32) -> f32 { - let value = generator.global.apply(ramp); - let value = if generator.invert { 1.0 - value } else { value }; + let value = generator.applied_global().apply(ramp); + let value = if generator.invert && generator.light.is_none() { 1.0 - value } else { value }; let offset = if generator.offset.is_finite() { generator.offset } else { 0.0 }; (value + offset).clamp(0.0, 1.0) } @@ -2240,7 +2309,8 @@ fn unpremultiply(data: &mut [f32], comps: usize) { /// (and anchors) below it. Cheap when no layer has a blur or sharpen. pub fn neighbourhood_fields(inputs: &Inputs, channels: &[Channel], tiles: &[(u32, u32)]) -> Fields { let projectors = ProjectorDepthCache::default(); - let inputs = EvaluationInputs::new(inputs, &projectors); + let mut inputs = EvaluationInputs::new(inputs, &projectors); + prepare_generators(&mut inputs, None); evaluation_fields(&inputs, &evaluation_channels(&inputs, channels.to_vec()), tiles) } @@ -2258,18 +2328,21 @@ fn fields_of(inp: &EvaluationInputs, channels: &[Channel], (list, around): (&[La let working_width = inp.gbuf.width; let mut order = Vec::new(); - draw_order(inp, list, 0, around.into(), &mut order); + draw_order(inp, list, 0, around.into(), false, &mut order); let ids: Vec = order.iter().map(|(id, _)| *id).collect(); prepare_curvature_sizes(inp, &ids); + let field_mask = + |id, place: DrawPlacement| layer_mask(inp.project, id).filter(|mask| mask.enabled || (place.instance == 0 && inp.sampled_disabled_mask == Some(id))); + // Walk backwards to find the region each Compare needs below its position in the stack let mut below_margin = (0u32, false); let margins: Vec<_> = order .iter() .rev() - .map(|&(id, _)| { + .map(|&(id, place)| { let mask_margin = below_margin; - let effects = layer_mask(inp.project, id).filter(|mask| mask.enabled).map(|mask| mask.effects.as_slice()).unwrap_or_default(); + let effects = field_mask(id, place).map(|mask| mask.effects.as_slice()).unwrap_or_default(); let first_reader = effects.iter().filter(|effect| effect.visible).position(|effect| effect.kind.reads_stack()); if let Some(first_reader) = first_reader { for (index, radius, op) in neighbourhood_filters(effects, inp.tile_res(), None).filter(|(index, _, _)| *index > first_reader) { @@ -2285,7 +2358,7 @@ fn fields_of(inp: &EvaluationInputs, channels: &[Channel], (list, around): (&[La for ((id, place), (mask_margin, content_margin)) in order.into_iter().zip(margins.into_iter().rev()) { let Some(layer) = inp.project.content_layer(id) else { continue }; - let mask = layer_mask(inp.project, id).filter(|mask| mask.enabled && neighbourhood(&mask.effects, working_width).is_some()); + let mask = field_mask(id, place).filter(|mask| neighbourhood(&mask.effects, working_width).is_some()); // A mask comparing its own layer needs that layer's filtered content first let compares_content = mask.is_some_and(|mask| mask.effects.iter().any(|effect| effect.visible && compares_this_layer(&effect.kind))); @@ -2351,19 +2424,193 @@ fn compares_this_layer(kind: &EffectKind) -> bool { matches!(kind, EffectKind::Compare { left, right, .. } if *left == CompareSource::ThisLayer || *right == CompareSource::ThisLayer) } -/// Build the curvature detail sizes every visible generator of `layers` reads, once, before tiles composite in parallel. -fn prepare_curvature_sizes(inp: &Inputs, layers: &[LayerId]) { +/// Build the curvature detail sizes every visible generator of `layers` reads, once, before tiles composite in parallel +fn prepare_curvature_sizes(inp: &EvaluationInputs, layers: &[LayerId]) { let visible = layers.iter().filter(|id| inp.project.layers.get(id).is_some_and(|layer| layer.visible)); let masks = visible.filter_map(|id| layer_mask(inp.project, *id)).filter(|mask| mask.enabled); prepare_mask_curvature_sizes(inp, masks); } -/// Build the curvature detail sizes the visible generators of `masks` read, once, before tiles composite in parallel. -fn prepare_mask_curvature_sizes<'a>(inp: &Inputs, masks: impl Iterator) { - let mut needed = [false; CurvatureDetail::BLURRED_SIZES]; +/// Retain up to this many bytes of whole-map fields while planning tiles +const EVALUATION_FIELD_BYTES: usize = 256 << 20; + +/// Generators whose fitted signal depends on a precomputed whole-atlas field +fn whole_map_generator(kind: GeneratorKind) -> bool { + matches!(kind, GeneratorKind::UvBorderDistance | GeneratorKind::DrippingRust | GeneratorKind::UvRandomColor | GeneratorKind::UvChecker) +} + +/// A requested mask beneath a hidden folder probes the visible stack before that folder +fn requested_mask_stop(inp: &EvaluationInputs, id: LayerId) -> LayerId { + let mut stop = id; + let mut current = id; + for _ in 0..texturecraft_core::project::MAX_DEPTH { + let Some((_, Some(parent), _)) = inp.project.locate(current) else { break }; + if inp.project.layers.get(&parent).is_some_and(|layer| !layer.visible) { + stop = parent; + } + current = parent; + } + stop +} + +/// Prepare whole-map fields and build Micro Height maps from bottom to top +fn prepare_generators(inp: &mut EvaluationInputs, requested_mask: Option) { + let Ok(set) = inp.project.texture_set(inp.ts) else { return }; + let requested_stop = requested_mask.map(|id| requested_mask_stop(inp, id)); + let mut order = Vec::new(); + draw_order(inp, &set.stack, 0, ContentsOffset::NONE.into(), true, &mut order); + + let mut anchors_below = HashMap::new(); + let mut first_readers = HashMap::new(); + let mut generators_by_anchor = HashMap::<_, BTreeMap<_, _>>::new(); + let mut considered_fields = HashSet::new(); + let mut retained_fields = HashSet::new(); + let field_bytes = (inp.gbuf.width as usize).saturating_mul(inp.gbuf.height as usize).saturating_mul(size_of::()); + let mut retained_bytes = 0usize; + + for (index, &(id, place)) in order.iter().enumerate() { + let visible = inp.project.layers.get(&id).is_some_and(|layer| layer.visible); + let draw = (id, place.instance); + let masks = visible + .then_some((draw, id)) + .into_iter() + .chain(requested_mask.filter(|_| requested_stop == Some(id) && place.instance == 0 && !visible).map(|reader| ((reader, 0), reader))); + for (reader_draw, reader) in masks { + // Clone and smudge explicitly sample disabled masks + let requested = reader_draw.1 == 0 && requested_mask == Some(reader); + let effects = layer_mask(inp.project, reader).filter(|mask| mask.enabled || requested).into_iter().flat_map(|mask| &mask.effects); + for effect in effects.filter(|effect| effect.visible) { + let EffectKind::Generator(generator) = &effect.kind else { continue }; + + if let Some(anchor) = micro_height_anchor(generator) + && let Some(anchor_index) = anchors_below.get(&anchor) + { + inp.anchor_readers.insert((reader_draw, anchor), *anchor_index); + first_readers.entry((anchor, *anchor_index)).or_insert(draw); + generators_by_anchor.entry((anchor, *anchor_index)).or_default().insert(effect.id, generator); + } + + if whole_map_generator(generator.kind) + && retained_bytes.saturating_add(field_bytes) <= EVALUATION_FIELD_BYTES + && considered_fields.insert(effect.id) + { + let maps = GeneratorMaps::of(inp, generator, &curvature_sizes_in_use(generator), None, || inp.field_identity()); + if let Some(field) = &maps.field + && retained_fields.insert(Arc::as_ptr(field)) + { + retained_bytes += field_bytes; + } + inp.whole_maps.insert(effect.id, maps); + } + } + } + + if visible { + let mask_effects = layer_mask(inp.project, id).filter(|mask| mask.enabled).into_iter().flat_map(|mask| &mask.effects); + let content_effects = inp.project.content_layer(id).filter(|layer| !layer.is_group()).into_iter().flat_map(|layer| &layer.content_effects); + for effect in content_effects.chain(mask_effects).filter(|effect| effect.visible && matches!(effect.kind, EffectKind::Anchor)) { + anchors_below.insert(effect.id, index); + } + } + } + + if inp.is_session_stack() { + inp.projectors.micro_heights.retain_readers(inp.ts, &first_readers.keys().copied().collect::>()); + } + + if first_readers.is_empty() { + return; + } + + let mut readers: Vec<_> = first_readers.into_iter().collect(); + readers.sort_unstable_by_key(|((anchor, index), _)| (*index, *anchor)); + let stack = (inp.is_session_stack() && inp.preview.is_none()) + .then(|| StackKey::new(inp.project, inp.pixels, inp.baked, inp.images, inp.ts, &set.stack).map(Arc::new)) + .flatten(); + + for ((anchor, index), draw) in readers { + let build = || anchor_heights(inp, draw, anchor); + let heights = match &stack { + Some(stack) => inp.projectors.micro_heights.get_or_build(inp, (anchor, index), stack, build), + None => Arc::new(build()), + }; + if let Some(generators) = generators_by_anchor.remove(&(anchor, index)) { + for (id, generator) in generators { + let maps = GeneratorMaps::of(inp, generator, &curvature_sizes_in_use(generator), Some(heights.clone()), || inp.field_identity()); + inp.anchor_maps.insert((id, index), maps); + } + } + } +} + +fn micro_height_anchor(generator: &Generator) -> Option { + let micro = generator.micro_in_use().filter(|micro| micro.height)?; + match µ.height_source { + Some(Source::Anchor { anchor, .. }) => Some(*anchor), + _ => None, + } +} + +/// Anchor point `anchor`'s height over the whole texture set as layer `reader` reads it, in the working atlas's layout +fn anchor_heights(inp: &EvaluationInputs, reader: (LayerId, usize), anchor: LayerId) -> AnchorHeights { + let (width, height) = (inp.gbuf.width, inp.gbuf.height); + let channels = evaluation_channels(inp, vec![Channel::Height]); + let fields = evaluation_fields(inp, &channels, &all_tiles(width, height)); + let width_usize = width as usize; + let tile_side = TILE as usize; + let mut data = vec![0.0f32; width_usize * height as usize]; + + // Each tile row writes its own atlas rows + data.par_chunks_mut(width_usize.max(1) * tile_side).enumerate().for_each(|(tile_y, rows)| { + for tile_x in 0..width.div_ceil(TILE) { + let nodes = below_plan(inp, reader, &channels, (tile_x, tile_y as u32), Some(&fields), true); + let preview = inp.preview.and_then(|preview| preview.alpha.tile(tile_x, tile_y as u32)); + for (x, y, offset) in tile_texels(inp.gbuf, tile_x, tile_y as u32) { + let mut texel = Texel::new(inp, x, y, offset, stroke_at(preview, offset)); + texel.anchors_below(&nodes, reader); + if let Some(destination) = rows.get_mut((y as usize % tile_side) * width_usize + x as usize) { + *destination = texel.anchored(anchor, Channel::Height)[0]; + } + } + } + }); + AnchorHeights::new(data, (width, height), inp.block_scales.clone()) +} + +/// The blurred curvature levels `generator` reads: its wear's smoothing, else its detail sizes (a replaced curvature input reads none) +fn curvature_sizes_in_use(generator: &Generator) -> [bool; LEVEL_RADII.len()] { + if generator.inputs.contains_key(&BakedMap::Curvature) { + return [false; LEVEL_RADII.len()]; + } + + if let Some(wear) = wear_parameters(generator) { + return wear::levels_in_use(generator.kind, &wear); + } + + let detail = generator.detail_in_use().as_ref().map(CurvatureDetail::blurred_sizes_in_use).unwrap_or_default(); + std::array::from_fn(|level| detail.get(level).copied().unwrap_or(false)) +} + +/// The wear controls `generator` computes with: its own, Fiber Glass Edge Wear's defaults when it has none (it has no earlier model), else None +fn wear_parameters(generator: &Generator) -> Option { + generator.wear.or_else(|| WearParameters::defaults(generator.kind).filter(|_| generator.kind == GeneratorKind::FiberGlassEdgeWear)) +} + +/// Build the curvature detail sizes the visible generators of `masks` read, once, before tiles composite in parallel +fn prepare_mask_curvature_sizes<'a>(inp: &EvaluationInputs, masks: impl Iterator) { + let mut needed = [false; LEVEL_RADII.len()]; for effect in masks.flat_map(|mask| &mask.effects).filter(|effect| effect.visible) { - if let EffectKind::Generator(Generator { detail: Some(detail), .. }) = &effect.kind { - for (slot, in_use) in needed.iter_mut().zip(detail.blurred_sizes_in_use()) { + if let EffectKind::Generator(generator) = &effect.kind { + if micro_height_anchor(generator).is_some() || inp.whole_maps.contains_key(&effect.id) { + continue; + } + + if generator.micro_in_use().is_some() || whole_map_generator(generator.kind) { + GeneratorMaps::of(inp, generator, &curvature_sizes_in_use(generator), None, || inp.field_identity()); + continue; + } + + for (slot, in_use) in needed.iter_mut().zip(curvature_sizes_in_use(generator)) { *slot |= in_use; } } @@ -2395,7 +2642,8 @@ fn effect_plans<'a>( tile_x: u32, tile_y: u32, channel: Option, - around: ContentsOffset, + place: DrawPlacement, + id: LayerId, ) -> Vec> { effects .iter() @@ -2405,14 +2653,20 @@ fn effect_plans<'a>( Some(channel) => (inp.pixels.layer(effect.id, channel), PaintTarget::Layer(effect.id)), None => (inp.pixels.masks.get(&effect.id), PaintTarget::Mask(effect.id)), }; - let curvature_sizes = match &effect.kind { - EffectKind::Generator(Generator { detail: Some(detail), .. }) => CurvatureSizes::of(inp, &detail.blurred_sizes_in_use()), - _ => None, + let maps = match &effect.kind { + EffectKind::Generator(generator) => { + let maps = micro_height_anchor(generator) + .and_then(|anchor| inp.anchor_readers.get(&((id, place.instance), anchor))) + .and_then(|index| inp.anchor_maps.get(&(effect.id, *index))) + .or_else(|| inp.whole_maps.get(&effect.id)); + maps.cloned().unwrap_or_else(|| GeneratorMaps::of(inp, generator, &curvature_sizes_in_use(generator), None, || inp.field_identity())) + } + _ => GeneratorMaps::default(), }; let (depth, covers_all, projection) = match &effect.kind { EffectKind::Fill { projection, sampling, .. } | EffectKind::Material(Fill { projection, sampling, .. }) => { let (depth, covers_all) = fill_coverage(inp, projection, *sampling); - (depth, covers_all, (!around.is_none()).then(|| around.apply(projection))) + (depth, covers_all, (!place.offset.is_none()).then(|| place.offset.apply(projection))) } _ => (None, false, None), }; @@ -2437,7 +2691,7 @@ fn effect_plans<'a>( opacity: blend.opacity, data: if effect.kind.painted() { tile_of(inp, image, tile_x, tile_y, channel) } else { None }, preview: previews(inp, target), - curvature_sizes, + maps, filtered_mask: None, depth, covers_all, @@ -2481,21 +2735,9 @@ fn tile_of<'a>(inp: &Inputs, img: Option<&'a TileImage>, tx: u32, ty: u32, chann } /// The plan of layer `id`'s `mask` for tile (tx, ty), its fills under the Scale and Rotation `around` of the folders holding the layer -fn mask_plan<'a>( - inp: &EvaluationInputs<'a>, - id: LayerId, - mask: &'a Mask, - tx: u32, - ty: u32, - fields: Option<&'a Fields>, - place: DrawPlacement, -) -> Option> { - if !mask.enabled { - return None; - } - +fn mask_plan<'a>(inp: &EvaluationInputs<'a>, id: LayerId, mask: &'a Mask, tx: u32, ty: u32, fields: Option<&'a Fields>, place: DrawPlacement) -> MaskPlan<'a> { let background = if mask.background == MaskBackground::White { 1.0 } else { 0.0 }; - let mut effects = effect_plans(inp, &mask.effects, tx, ty, None, place.offset); + let mut effects = effect_plans(inp, &mask.effects, tx, ty, None, place, id); let filtered = fields.and_then(|fields| FieldKey::mask(id, place.offset).field(fields, place.instance)); for (index, effect) in effects.iter_mut().enumerate() { effect.filtered_mask = filtered.and_then(|field| field.anchor_stages.iter().find(|(stage, _)| *stage == index).map(|(_, field)| field)); @@ -2510,7 +2752,7 @@ fn mask_plan<'a>( } else { inp.project.content_layer(id).and_then(|l| plan_content(inp, id, l, &compared, tx, ty, 0, fields, false, place, None)) }; - Some(MaskPlan { background, effects, layer, start }) + MaskPlan { background, effects, layer, start } } /// The plans of sibling layers `list` (under the Scale and Rotation of the folders holding them) @@ -2577,7 +2819,7 @@ fn plan_node<'a>( } let (content, chans) = plan_content(inp, id, layer, channels, tx, ty, depth, fields, kids, place, stop)?; - let mask = layer_mask(inp.project, id).and_then(|m| mask_plan(inp, id, m, tx, ty, fields, place)); + let mask = layer_mask(inp.project, id).filter(|mask| mask.enabled).map(|mask| mask_plan(inp, id, mask, tx, ty, fields, place)); // Anchors in the mask record even where the layer draws nothing let mask_anchor = mask.as_ref().is_some_and(|m| m.effects.iter().any(|e| matches!(*e.kind, EffectKind::Anchor))); @@ -2641,7 +2883,7 @@ fn plan_content<'a>( } let data = if paint { tile_of(inp, inp.pixels.layer(layer.id, *c), tx, ty, Some(*c)) } else { None }; - let effects = if has_content_effects { effect_plans(inp, &layer.content_effects, tx, ty, Some(*c), place.offset) } else { Vec::new() }; + let effects = if has_content_effects { effect_plans(inp, &layer.content_effects, tx, ty, Some(*c), place, id) } else { Vec::new() }; let start = fields .and_then(|fields| FieldKey::content(id, *c, place.offset).field(fields, place.instance)) .and_then(|field| neighbourhood_filters(&layer.content_effects, inp.tile_res(), Some(*c)).last().map(|(index, _, _)| (index, field))); @@ -3276,26 +3518,84 @@ impl<'a, 'b> Texel<'a, 'b> { if needs_gray { [lum(value); 3] } else { value } } - fn generator_ramp(&mut self, generator: &Generator, curvature_sizes: Option<&CurvatureSizes>) -> f32 { + /// The generator's ramp at this texel, before its global blur, balance, contrast and invert (on the section controls, before those too). + fn generator_ramp(&mut self, generator: &Generator, maps: &GeneratorMaps) -> f32 { + if let Some(wear) = wear_parameters(generator) { + return self.wear_ramp(generator, &wear, maps); + } + + if let Some(light) = &generator.light { + let normal = + self.generator_input_color(generator, BakedMap::WorldNormal).map_or_else(|| self.coords().nrm, |encoded| Vec3::from(encoded) * 2.0 - 1.0); + let position = Vec3::from(self.position_input(generator)); + return sections::light_value(light, normal, position, generator.invert); + } + + if let Some(section) = generator.section_controls() { + return self.section_signal(generator, §ion, maps); + } + + // The kinds with only their own controls: resolved once per plan, not per texel + let resolved; + let controls = match maps.controls.as_deref() { + Some(controls) => Some(controls), + None => { + resolved = generator.kind_controls(); + resolved.as_ref() + } + }; + match controls { + Some(KindControls::Distance(distance)) => { + let position = self.uniform_position_input(generator); + return three_d_distance::distance_value(distance, position); + } + Some(KindControls::LinearGradient(gradient)) => { + let position = self.uniform_position_input(generator); + return three_d_distance::linear_gradient_value(gradient, position); + } + Some(KindControls::BorderDistance(border)) => return uv_border_distance::border_value(border, self.field_value(maps)), + Some(KindControls::Grayscale(grayscale)) => return self.grayscale_conversion(grayscale), + Some(KindControls::DrippingRust(rust)) => return dripping_rust::rust_value(rust, self.field_value(maps)), + Some(KindControls::UvRandomColor(_) | KindControls::UvChecker(_)) => return self.field_value(maps), + None => {} + } + let coords = self.coords(); - let micro = generator.micro.map_or(0.0, |micro| self.micro_detail(generator.kind, micro)); + let earlier_micro = generator.earlier_micro().map_or(0.0, |(anchor, amount)| self.earlier_micro_detail(generator.kind, anchor, amount)); + + // Micro details saved on the earlier model add to its curvature and occlusion inputs too let signal = match (generator.kind, &generator.detail) { (GeneratorKind::Curvature | GeneratorKind::EdgeWear, Some(detail)) => { // Detail sizes are blurred copies of the mesh map, so a replaced curvature input reads at its own size only - let sizes = if generator.inputs.contains_key(&BakedMap::Curvature) { None } else { curvature_sizes }; - let curvature = self.generator_input(generator, BakedMap::Curvature); - self.curvature_detail(detail, sizes, curvature, micro) + let sizes = if generator.inputs.contains_key(&BakedMap::Curvature) { None } else { maps.sizes.as_deref() }; + let curvature = self.curvature_input(generator, maps); + self.curvature_detail(detail, sizes, curvature, earlier_micro) } - (GeneratorKind::EdgeWear, None) => (self.generator_input(generator, BakedMap::Curvature).unwrap_or(0.5) - 0.5) * 2.0, - (GeneratorKind::Curvature, None) => self.generator_input(generator, BakedMap::Curvature).unwrap_or(0.5), - (GeneratorKind::Dirt, _) => 1.0 - self.generator_input(generator, BakedMap::AmbientOcclusion).unwrap_or(1.0), - (GeneratorKind::AmbientOcclusion, _) => self.generator_input(generator, BakedMap::AmbientOcclusion).unwrap_or(1.0), + (GeneratorKind::EdgeWear, None) | (GeneratorKind::FiberGlassEdgeWear, _) => (self.curvature_input(generator, maps).unwrap_or(0.5) - 0.5) * 2.0, + (GeneratorKind::Curvature, None) => self.curvature_input(generator, maps).unwrap_or(0.5), + (GeneratorKind::Dirt, _) => 1.0 - self.occlusion_input(generator, maps).unwrap_or(1.0), + (GeneratorKind::AmbientOcclusion, _) => self.occlusion_input(generator, maps).unwrap_or(1.0), (GeneratorKind::ThinAreas, _) => 1.0 - self.generator_input(generator, BakedMap::Thickness).unwrap_or(1.0), (GeneratorKind::Position, _) => coords.pos.dot(Vec3::from(generator.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, (GeneratorKind::Direction, _) => coords.nrm.dot(Vec3::from(generator.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, + // World Space Normals and 3D Distance always compute with their own controls: these arms only keep the match whole + (GeneratorKind::WorldSpaceNormals, _) => coords.nrm.y * 0.5 + 0.5, + ( + GeneratorKind::ThreeDDistance + | GeneratorKind::ThreeDLinearGradient + | GeneratorKind::UvBorderDistance + | GeneratorKind::GrayscaleConversion + | GeneratorKind::DrippingRust + | GeneratorKind::UvRandomColor + | GeneratorKind::UvChecker, + _, + ) => 0.0, + }; + let signal = if matches!(generator.kind, GeneratorKind::Curvature | GeneratorKind::EdgeWear) && generator.detail.is_some() { + signal + } else { + signal + earlier_micro }; - let signal = - if matches!(generator.kind, GeneratorKind::Curvature | GeneratorKind::EdgeWear) && generator.detail.is_some() { signal } else { signal + micro }; let signal = if generator.noise_amount > 0.0 { let noise = world_noise(coords.pos, generator.noise_scale, generator.seed); if let (GeneratorKind::Curvature | GeneratorKind::EdgeWear, Some(detail)) = (generator.kind, &generator.detail) { @@ -3316,26 +3616,218 @@ impl<'a, 'b> Texel<'a, 'b> { ramp * ramp * (3.0 - 2.0 * ramp) } - /// How a generator's micro detail moves its signal at this texel: the anchor's height (0 where - /// the anchor is not evaluated yet) as an edge where raised and a cavity where recessed. - fn micro_detail(&self, kind: GeneratorKind, micro: MicroDetail) -> f32 { - let height = self.anchor_value(micro.anchor, Channel::Height, ChannelKind::Signed)[0]; - let amount = if micro.amount.is_finite() { micro.amount.clamp(0.0, 1.0) } else { 0.0 }; - let response = height.clamp(-1.0, 1.0) * amount; - match kind { - GeneratorKind::Curvature | GeneratorKind::EdgeWear => response, + /// The signal a generator on its section controls adjusts at this texel: the axes of its map, its curvature or its occlusion + fn section_signal(&mut self, generator: &Generator, section: &SectionParameters, maps: &GeneratorMaps) -> f32 { + match generator.kind { + GeneratorKind::Curvature => { + let detail = generator.detail_in_use().unwrap_or_default(); + let sizes = if generator.inputs.contains_key(&BakedMap::Curvature) { None } else { maps.sizes.as_deref() }; + let curvature = self.curvature_input(generator, maps); + self.curvature_detail(&detail, sizes, curvature, 0.0) + } + GeneratorKind::AmbientOcclusion => self.occlusion_input(generator, maps).unwrap_or(1.0), + GeneratorKind::Position => { + let position = self.position_input(generator); + sections::axes_signal(position, §ion.axes) + } + GeneratorKind::WorldSpaceNormals => { + let normal = self.generator_input_color(generator, BakedMap::WorldNormal).unwrap_or_else(|| (self.coords().nrm * 0.5 + 0.5).to_array()); + sections::axes_signal(normal, §ion.axes) + } - // Dirt gathers in dents; dents are occluded - GeneratorKind::Dirt => -response, - GeneratorKind::AmbientOcclusion => response, - GeneratorKind::ThinAreas | GeneratorKind::Position | GeneratorKind::Direction => 0.0, + // Other kinds use their own evaluator + GeneratorKind::EdgeWear + | GeneratorKind::Dirt + | GeneratorKind::ThinAreas + | GeneratorKind::Direction + | GeneratorKind::FiberGlassEdgeWear + | GeneratorKind::ThreeDDistance + | GeneratorKind::ThreeDLinearGradient + | GeneratorKind::UvBorderDistance + | GeneratorKind::GrayscaleConversion + | GeneratorKind::DrippingRust + | GeneratorKind::UvRandomColor + | GeneratorKind::UvChecker => 0.0, } } - /// The generator's value at this texel: its ramp finished by balance, contrast, invert and offset (its blur and resolution need neighbours: see [`generator_region`]). - fn generator(&mut self, generator: &Generator, curvature_sizes: Option<&CurvatureSizes>) -> f32 { - let ramp = self.generator_ramp(generator, curvature_sizes); - finish_generator(generator, ramp) + /// The image in `generator`'s Position input, else this texel's position across the mesh's bounds: the baked Position map is not read, its normalisation is a bake setting + fn position_input(&mut self, generator: &Generator) -> [f32; 3] { + match generator.inputs.get(&BakedMap::Position) { + Some(source) => self.source(source, &Projection::default(), Sampling::default(), ChannelKind::NormalMap), + None => self.bounds_position().to_array(), + } + } + + /// A generator's whole-map field at this texel (0 without one) + fn field_value(&self, maps: &GeneratorMaps) -> f32 { + let texel = (self.y * self.inp.gbuf.width + self.x) as usize; + maps.field.as_ref().and_then(|field| field.get(texel)).copied().unwrap_or(0.0) + } + + /// The Grayscale Conversion generator at this texel: its image tiled and turned about the UV square's centre, made gray, balanced and contrasted + fn grayscale_conversion(&mut self, grayscale: &GrayscaleConversionParameters) -> f32 { + let degrees = if grayscale.safe_rotation { (grayscale.rotation / QUARTER_TURN_DEGREES).round() * QUARTER_TURN_DEGREES } else { grayscale.rotation }; + let (sin, cos) = degrees.to_radians().sin_cos(); + let centred = self.coords().uv - Vec2::splat(0.5); + let at = Vec2::new(centred.x * cos - centred.y * sin, centred.x * sin + centred.y * cos) * grayscale.tile + Vec2::splat(0.5); + let rgb = match grayscale.source.as_ref().unwrap_or(&EMPTY_IMAGE_SLOT) { + Source::Image { name, .. } => self.inp.images.get(name).map_or([0.0; 3], |image| { + let [red, green, blue, _] = image.sample(at.x, at.y); + [red, green, blue] + }), + other => self.source(other, &Projection::default(), Sampling::default(), ChannelKind::NormalMap), + }; + let gray = grayscale.grayscale.gray(rgb).clamp(0.0, 1.0); + GeneratorGlobal { balance: grayscale.balance, contrast: grayscale.contrast, ..GeneratorGlobal::default() }.apply(gray) + } + + /// The image in `generator`'s Position input, else this texel's position across the mesh's bounds scaled evenly: the longest side spans 0..1, the others centred on 0.5 + fn uniform_position_input(&mut self, generator: &Generator) -> Vec3 { + if let Some(source) = generator.inputs.get(&BakedMap::Position) { + return Vec3::from(self.source(source, &Projection::default(), Sampling::default(), ChannelKind::NormalMap)); + } + + let (low, high) = self.inp.bounds; + let longest = (high - low).max_element().max(MIN_BOUNDS_EXTENT); + self.world().map_or(Vec3::splat(0.5), |position| (position - (low + high) * 0.5) / longest + Vec3::splat(0.5)) + } + + /// This texel's world position across the mesh's bounds, 0..1 on each axis (0 where uncovered) + fn bounds_position(&self) -> Vec3 { + let (low, high) = self.inp.bounds; + self.world().map_or(Vec3::ZERO, |position| ((position - low) / (high - low).max(Vec3::splat(MIN_BOUNDS_EXTENT))).clamp(Vec3::ZERO, Vec3::ONE)) + } + + /// A wear generator's value at this texel from its curvature, occlusion and grunge, before its global adjustments and invert + fn wear_ramp(&mut self, generator: &Generator, wear: &WearParameters, maps: &GeneratorMaps) -> f32 { + let curvature = self.curvature_input(generator, maps).map_or(0.0, |curvature| curvature - 0.5); + + // Blurred levels are copies of the mesh map, so a replaced curvature input is read at its own size only + let sizes = if generator.inputs.contains_key(&BakedMap::Curvature) { None } else { maps.sizes.as_deref() }; + let blurred_curvature = self.blurred_curvature(wear::blur_sigma(generator.kind, wear), sizes, curvature); + + let occlusion = self.occlusion_input(generator, maps).unwrap_or(1.0); + let grunge = if wear.custom_grunge { + // An image not loaded yet reads mid gray, which leaves the wear as without grunge + let gray = self.slot_color(generator, generator.grunge.as_ref(), &wear::custom_grunge_placement(wear)).map_or(0.5, lum); + wear::custom_grunge(generator.kind, gray) + } else { + wear::grunge(generator.kind, wear, generator.seed, &self.coords()) + }; + wear::wear_value(generator.kind, wear, &WearInputs { curvature, blurred_curvature, occlusion, grunge }) + } + + /// The curvature deviation at this texel blurred to `sigma` (texels at 2K) between the two built levels around it; `curvature` without them + fn blurred_curvature(&self, sigma: f32, curvature_sizes: Option<&CurvatureSizes>, curvature: f32) -> f32 { + let Some((sizes, (baked_x, baked_y))) = curvature_sizes.zip(self.baked_curvature_texel()) else { return curvature }; + + let level = |index: usize| sizes.levels.get(index).and_then(Option::as_deref).map(|level| level.sample(baked_x, baked_y)); + let (narrower, wider, weight) = wear::levels_around(sigma); + let narrower = narrower.map_or(Some(curvature), level); + match (narrower, level(wider)) { + (Some(narrower), Some(wider)) => narrower + (wider - narrower) * weight, + _ => curvature, + } + } + + /// The baked curvature map's texel under this texel (None outside the baked layout) + fn baked_curvature_texel(&self) -> Option<(u32, u32)> { + let working_size = (self.res, self.inp.gbuf.height); + let texel_uv = [(self.x as f32 + 0.5) / working_size.0.max(1) as f32, (self.y as f32 + 0.5) / working_size.1.max(1) as f32]; + let baked_uv = self.inp.block_scales.bake_uv(texel_uv, working_size)?; + let baked_size = (self.inp.baked.resolution, self.inp.baked.height(BakedMap::Curvature)); + Some(((baked_uv[0] * baked_size.0 as f32) as u32, (baked_uv[1] * baked_size.1 as f32) as u32)) + } + + /// The generator's value at this texel: its ramp finished by balance, contrast, invert and offset (its blur and resolution need neighbours: see [`generator_region`]) + fn generator(&mut self, generator: &Generator, maps: &GeneratorMaps) -> f32 { + let ramp = self.generator_ramp(generator, maps); + let adjusted = generator.section_controls().map_or(ramp, |section| sections::adjusted(generator.kind, §ion, ramp)); + + // An image still loading reads black, as it does where blur or resolution compute the generator over a region + let textured = match generator.texture_in_use() { + Some(texture) => texture_layer::blended_over(texture, adjusted, self.generator_texture(generator).unwrap_or(0.0)), + None => adjusted, + }; + + finish_generator(generator, textured) + } + + /// The gray of the generator's texture at this texel (None when it blends no texture) + fn generator_texture(&mut self, generator: &Generator) -> Option { + let texture = generator.texture_in_use()?; + let rgb = self.slot_color(generator, texture.source.as_ref(), &texture_layer::texture_placement(texture))?; + Some(texture_layer::texture_gray(texture, rgb)) + } + + /// The color of a generator's image slot holding `source` (None: empty, read as black) at this texel, read where `placement` puts it (None when its image isn't loaded) + fn slot_color(&mut self, generator: &Generator, source: Option<&Source>, placement: &texture_layer::SlotPlacement) -> Option<[f32; 3]> { + match source.unwrap_or(&EMPTY_IMAGE_SLOT) { + Source::Image { name, .. } => { + let image = self.inp.images.get(name)?.clone(); + let read = |coordinates: Vec2| { + let [red, green, blue, _] = image.sample(coordinates.x, coordinates.y); + Vec3::new(red, green, blue) + }; + let color = match placement.triplanar_contrast { + Some(contrast) => { + let normal = self + .generator_input_color(generator, BakedMap::WorldNormal) + .map_or_else(|| self.coords().nrm, |encoded| Vec3::from(encoded) * 2.0 - 1.0); + let weights = texture_layer::triplanar_weights(contrast, normal); + let coordinates = texture_layer::triplanar_coordinates(placement, self.bounds_position()); + weights.iter().zip(coordinates).fold(Vec3::ZERO, |sum, (weight, at)| sum + read(at) * *weight) + } + None => read(texture_layer::uv_coordinates(placement, self.coords().uv)), + }; + Some(color.to_array()) + } + + // A value or an anchor reads the same wherever it is projected + other => Some(self.source(other, &Projection::default(), Sampling::default(), ChannelKind::NormalMap)), + } + } + + /// How a micro detail saved before Micro Details moves an earlier-model generator's signal at this texel: anchor point `anchor`'s height times `amount` (0 where the anchor is not evaluated yet), an edge where raised and a cavity where recessed + fn earlier_micro_detail(&self, kind: GeneratorKind, anchor: LayerId, amount: f32) -> f32 { + let response = self.anchor_value(anchor, Channel::Height, ChannelKind::Signed)[0].clamp(-1.0, 1.0) * amount; + match kind { + GeneratorKind::Curvature | GeneratorKind::EdgeWear | GeneratorKind::AmbientOcclusion => response, + + // Dirt gathers in dents + GeneratorKind::Dirt => -response, + + // Kinds the micro detail never moved, or without an earlier model + GeneratorKind::FiberGlassEdgeWear + | GeneratorKind::ThinAreas + | GeneratorKind::Position + | GeneratorKind::Direction + | GeneratorKind::WorldSpaceNormals + | GeneratorKind::ThreeDDistance + | GeneratorKind::ThreeDLinearGradient + | GeneratorKind::UvBorderDistance + | GeneratorKind::GrayscaleConversion + | GeneratorKind::DrippingRust + | GeneratorKind::UvRandomColor + | GeneratorKind::UvChecker => 0.0, + } + } + + /// The generator's curvature input at this texel with what its micro details add + fn curvature_input(&mut self, generator: &Generator, maps: &GeneratorMaps) -> Option { + let curvature = self.generator_input(generator, BakedMap::Curvature)?; + let working_size = (self.res, self.inp.gbuf.height); + let micro = maps.micro_curvature.as_ref().and_then(|micro| micro.term.at((self.x, self.y), working_size, &self.inp.block_scales)); + Some(curvature + micro.unwrap_or(0.0)) + } + + /// The generator's occlusion input at this texel, darkened by its micro details + fn occlusion_input(&mut self, generator: &Generator, maps: &GeneratorMaps) -> Option { + let occlusion = self.generator_input(generator, BakedMap::AmbientOcclusion)?; + let working_size = (self.res, self.inp.gbuf.height); + let micro = maps.micro_occlusion.as_ref().and_then(|micro| micro.at((self.x, self.y), working_size, &self.inp.block_scales)); + Some(occlusion * micro.unwrap_or(1.0)) } /// Generator input `map` at this texel: what replaces the mesh map in the generator's inputs, else the mesh map (None when not baked). @@ -3347,11 +3839,19 @@ impl<'a, 'b> Texel<'a, 'b> { } } - /// The curvature of `detail`'s mode at this texel from `curvature` (None: nothing to read), with its blurred detail sizes when given. - fn curvature_detail(&self, detail: &CurvatureDetail, curvature_sizes: Option<&CurvatureSizes>, curvature: Option, micro: f32) -> f32 { + /// Generator input `map` at this texel as three channels (an encoded normal or position): what replaces the mesh map, else the mesh map (None when not baked) + fn generator_input_color(&mut self, generator: &Generator, map: BakedMap) -> Option<[f32; 3]> { + match generator.inputs.get(&map) { + Some(source) => Some(self.source(source, &Projection::default(), Sampling::default(), ChannelKind::NormalMap)), + None => self.baked_color(map), + } + } + + /// The curvature of `detail`'s mode at this texel from `curvature` (None: nothing to read), with its blurred detail sizes when given and an earlier micro detail's term (see [`Texel::earlier_micro_detail`]) as an edge where positive and a cavity where negative + fn curvature_detail(&self, detail: &CurvatureDetail, curvature_sizes: Option<&CurvatureSizes>, curvature: Option, earlier_micro: f32) -> f32 { let combine = |edges: f32, cavities: f32| { - let edges = 1.0 - (1.0 - edges) * (1.0 - micro.max(0.0)); - let cavities = 1.0 - (1.0 - cavities) * (1.0 + micro.min(0.0)); + let edges = 1.0 - (1.0 - edges) * (1.0 - earlier_micro.max(0.0)); + let cavities = 1.0 - (1.0 - cavities) * (1.0 + earlier_micro.min(0.0)); match detail.mode { CurvatureMode::Edges => edges, CurvatureMode::Cavities => cavities, @@ -3360,15 +3860,10 @@ impl<'a, 'b> Texel<'a, 'b> { } }; - // Without baked curvature, only painted micro height supplies edges or cavities + // Without curvature to read only an earlier micro detail supplies edges or cavities let Some(curvature) = curvature else { return combine(0.0, 0.0) }; + let Some((baked_x, baked_y)) = self.baked_curvature_texel() else { return combine(0.0, 0.0) }; - let working_size = (self.res, self.inp.gbuf.height); - let texel_uv = [(self.x as f32 + 0.5) / working_size.0.max(1) as f32, (self.y as f32 + 0.5) / working_size.1.max(1) as f32]; - let Some(baked_uv) = self.inp.block_scales.bake_uv(texel_uv, working_size) else { return combine(0.0, 0.0) }; - - let baked_size = (self.inp.baked.resolution, self.inp.baked.height(BakedMap::Curvature)); - let (baked_x, baked_y) = ((baked_uv[0] * baked_size.0 as f32) as u32, (baked_uv[1] * baked_size.1 as f32) as u32); let blurred = |index: usize| { curvature_sizes.and_then(|sizes| sizes.levels.get(index)).and_then(Option::as_deref).map_or(0.0, |level| level.sample(baked_x, baked_y)) }; @@ -3455,7 +3950,7 @@ impl<'a, 'b> Texel<'a, 'b> { value += (blend1(effect.blend, value, fill) - value) * opacity * cover; } EffectKind::Generator(generator) => { - let generated = self.generator(generator, effect.curvature_sizes.as_deref()); + let generated = self.generator(generator, &effect.maps); value += (blend1(effect.blend, value, generated) - value) * opacity; } EffectKind::Levels(levels) => value += (levels.apply(value) - value) * opacity, @@ -3974,8 +4469,8 @@ pub fn composite_tiles_cached(inputs: &Inputs, out: &mut Composite, tiles: &[(u3 } let projectors = ProjectorDepthCache::default(); - let inputs = EvaluationInputs::new(inputs, &projectors); - composite_evaluation_tiles(&inputs, out, tiles, below); + let mut inputs = EvaluationInputs::new(inputs, &projectors); + composite_evaluation_tiles(&mut inputs, out, tiles, below); } /// Composite tile batches with a reusable cache for the mesh owned by the caller. @@ -3997,16 +4492,20 @@ pub fn composite_tiles_with_projectors( cache.bind_mesh(mesh); } - let inputs = EvaluationInputs::new(inputs, projectors); - composite_evaluation_tiles(&inputs, out, tiles, below); + let mut inputs = EvaluationInputs::new(inputs, projectors).of_the_session_stack(); + composite_evaluation_tiles(&mut inputs, out, tiles, below); } -fn composite_evaluation_tiles(inp: &EvaluationInputs, out: &mut Composite, tiles: &[(u32, u32)], mut below: Option<&mut BelowCache>) { +fn composite_evaluation_tiles(inp: &mut EvaluationInputs, out: &mut Composite, tiles: &[(u32, u32)], mut below: Option<&mut BelowCache>) { let Ok(set) = inp.project.texture_set(inp.ts) else { return }; if (inp.gbuf.width, inp.gbuf.height) != (out.resolution, out.height) { return; } + if !tiles.is_empty() { + prepare_generators(inp, None); + } + let split = below.as_deref_mut().and_then(|b| b.prepare(inp)); // Avoid caching tiles that would immediately evict each other @@ -4124,7 +4623,7 @@ fn uses_environment(project: &Project, stack: &[LayerId], depth: usize) -> bool fn has_neighbourhood(inp: &EvaluationInputs, stack: &[LayerId]) -> bool { let working_width = inp.gbuf.width; let mut order = Vec::new(); - draw_order(inp, stack, 0, DrawPlacement::default(), &mut order); + draw_order(inp, stack, 0, DrawPlacement::default(), false, &mut order); order.into_iter().any(|(id, _)| { let masked = layer_mask(inp.project, id).is_some_and(|mask| mask.enabled && neighbourhood(&mask.effects, working_width).is_some()); masked || inp.project.content_layer(id).is_some_and(|layer| !layer.is_group() && neighbourhood(&layer.content_effects, working_width).is_some()) @@ -4442,13 +4941,14 @@ pub fn pad_tiles(out: &mut Composite, dmap: &DilationMap, tiles: &[(u32, u32)]) /// Returns None without an enabled mask pub fn mask_texels(inputs: &Inputs, id: LayerId) -> Option> { let projectors = ProjectorDepthCache::default(); - let inputs = &EvaluationInputs::new(inputs, &projectors); + let inputs = &mut EvaluationInputs::new(inputs, &projectors); let mask = layer_mask(inputs.project, id).filter(|mask| mask.enabled)?; let channels = evaluation_channels(inputs, inputs.project.texture_set(inputs.ts).map(|set| set.channel_list()).unwrap_or_default()); let (width, height) = (inputs.gbuf.width, inputs.gbuf.height); let coordinates = all_tiles(width, height); // A hidden layer's mask is left out of the stack's preparation + prepare_generators(inputs, Some(id)); prepare_mask_curvature_sizes(inputs, std::iter::once(mask)); let fields = evaluation_fields(inputs, &channels, &coordinates); @@ -4479,13 +4979,14 @@ pub fn mask_image(inputs: &Inputs, id: LayerId, size: u32) -> Option> { let size = size.max(1); let pixel_count = usize::try_from(size.checked_mul(size)?).ok()?; let projectors = ProjectorDepthCache::default(); - let inputs = &EvaluationInputs::new(inputs, &projectors); + let inputs = &mut EvaluationInputs::new(inputs, &projectors); let mask = layer_mask(inputs.project, id).filter(|mask| mask.enabled)?; let channels = evaluation_channels(inputs, inputs.project.texture_set(inputs.ts).map(|set| set.channel_list()).unwrap_or_default()); let (width, height) = (inputs.gbuf.width, inputs.gbuf.height); let coordinates = all_tiles(width, height); // A hidden layer's mask is left out of the stack's preparation + prepare_generators(inputs, Some(id)); prepare_mask_curvature_sizes(inputs, std::iter::once(mask)); let fields = evaluation_fields(inputs, &channels, &coordinates); @@ -4587,9 +5088,16 @@ pub fn mask_values(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Option /// Evaluate requested tiles directly into the stroke's mask image. pub fn mask_values_into(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)], image: &mut TileImage) -> Option<()> { let projectors = ProjectorDepthCache::default(); - let inputs = &EvaluationInputs::new(inputs, &projectors); + let inputs = &mut EvaluationInputs::new(inputs, &projectors); let mask = layer_mask(inputs.project, id)?; - let channels = evaluation_channels(inputs, inputs.project.texture_set(inputs.ts).ok()?.channel_list()); + inputs.sampled_disabled_mask = (!mask.enabled).then_some(id); + let mut channels = inputs.project.texture_set(inputs.ts).ok()?.channel_list(); + if !mask.enabled { + channels = compared_channels(mask.effects.iter().filter(|effect| effect.visible && effect.kind.reads_stack()), channels); + } + + let channels = evaluation_channels(inputs, channels); + prepare_generators(inputs, Some(id)); prepare_mask_curvature_sizes(inputs, std::iter::once(mask)); let fields = evaluation_fields(inputs, &channels, tiles); @@ -4616,7 +5124,7 @@ pub fn mask_values_into(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)], imag /// Uncovered and out-of-range texels read zero; neighbourhood filters also evaluate surrounding texels pub fn mask_at(inputs: &Inputs, id: LayerId, texels: &[(u32, u32)]) -> Option> { let projectors = ProjectorDepthCache::default(); - let inputs = &EvaluationInputs::new(inputs, &projectors); + let inputs = &mut EvaluationInputs::new(inputs, &projectors); let mask = layer_mask(inputs.project, id).filter(|mask| mask.enabled)?; let mut output = vec![0.0; texels.len()]; @@ -4638,6 +5146,7 @@ pub fn mask_at(inputs: &Inputs, id: LayerId, texels: &[(u32, u32)]) -> Option