From 6e952a9a10f9bce77f330e430a828c066be6ad9b Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 02:58:46 +0700 Subject: [PATCH] Node engine: document model, image buffers, 120 nodes, cached graph cooking, packages, session and commands A clean-room, pure-Rust foundation for MaterialCraft's node-based material authoring: the package/graph/node model, float image planes, the node library (atomic nodes, tileable noises, patterns, filters, PBR utilities, function graphs for the pixel processor), a content-addressed cooking cache, .mcraft packages and texture export, and the command-driven session with snapshot undo. Infrastructure (xtask, CI, packaging) copied from TextureCraft. Co-Authored-By: Claude Opus 5.5 --- .cargo/config.toml | 2 + .coderabbit.yaml | 6 + .gitattributes | 5 + .github/actionlint.yaml | 4 + .github/workflows/ci.yml | 30 + .github/workflows/freebsd.yml | 36 + .github/workflows/packaging-lint.yml | 23 + .github/workflows/release.yml | 45 + .github/workflows/windows-arm64.yml | 33 + .gitignore | 11 + CLAUDE.md | 5 + Cargo.lock | 791 +++++ Cargo.toml | 106 + LICENSE-APACHE | 177 + LICENSE-MIT | 21 + NOTICE | 26 + clippy.toml | 4 + crates/core/Cargo.toml | 14 + crates/core/src/function.rs | 67 + crates/core/src/graph.rs | 420 +++ crates/core/src/lib.rs | 32 + crates/core/src/package.rs | 68 + crates/core/src/value.rs | 340 ++ crates/engine/Cargo.toml | 19 + crates/engine/src/commands.rs | 141 + crates/engine/src/edit_cmds.rs | 175 + crates/engine/src/file_cmds.rs | 234 ++ crates/engine/src/graph_cmds.rs | 492 +++ crates/engine/src/inspect.rs | 65 + crates/engine/src/lib.rs | 53 + crates/engine/src/node_cmds.rs | 290 ++ crates/engine/src/samples.rs | 333 ++ crates/engine/src/session.rs | 314 ++ crates/engine/src/view_cmds.rs | 152 + crates/engine/tests/session.rs | 114 + crates/eval/Cargo.toml | 15 + crates/eval/src/lib.rs | 490 +++ crates/formats/Cargo.toml | 17 + crates/formats/src/lib.rs | 271 ++ crates/geom/Cargo.toml | 16 + crates/geom/src/bvh.rs | 494 +++ crates/geom/src/camera.rs | 140 + crates/geom/src/gbuffer.rs | 195 ++ crates/geom/src/lib.rs | 28 + crates/geom/src/mesh.rs | 432 +++ crates/geom/src/primitives.rs | 399 +++ crates/geom/src/unwrap.rs | 384 +++ crates/image/Cargo.toml | 13 + crates/image/src/lib.rs | 339 ++ crates/nodes/Cargo.toml | 14 + crates/nodes/src/atomic.rs | 524 +++ crates/nodes/src/catalog.rs | 356 ++ crates/nodes/src/filters.rs | 951 +++++ crates/nodes/src/function.rs | 395 +++ crates/nodes/src/generators.rs | 412 +++ crates/nodes/src/lib.rs | 96 + crates/nodes/src/material.rs | 90 + crates/nodes/src/noise.rs | 184 + crates/nodes/src/ops.rs | 337 ++ crates/nodes/src/patterns.rs | 548 +++ docs/brand/LICENSE-brand.txt | 42 + docs/brand/artcraft-logo-white.png | Bin 0 -> 32161 bytes docs/brand/artcraft-logo-white.svg | 7 + docs/brand/artcraft-logo.png | Bin 0 -> 31302 bytes docs/brand/artcraft-logo.svg | 7 + docs/brand/artcraft-mark-black.png | Bin 0 -> 26793 bytes docs/brand/artcraft-mark-black.svg | 4 + docs/brand/artcraft-mark.png | Bin 0 -> 24715 bytes docs/brand/artcraft-mark.svg | 4 + packaging/.shellcheckrc | 3 + packaging/env.sh | 59 + packaging/freebsd/package.sh | 110 + packaging/icons.sh | 54 + packaging/linux/AppRun | 72 + .../ai.storyteller.materialcraft.desktop | 14 + ....storyteller.materialcraft.metainfo.xml.in | 65 + .../ai.storyteller.materialcraft.mime.xml | 11 + packaging/linux/apprun-test.sh | 98 + packaging/linux/flatpak-bundle.sh | 72 + .../ai.storyteller.MaterialCraft.bundle.yml | 50 + .../flatpak/ai.storyteller.MaterialCraft.yml | 66 + packaging/linux/nfpm.yaml | 80 + packaging/linux/package.sh | 151 + packaging/linux/postinst.sh | 13 + packaging/macos/Info.plist.in | 89 + packaging/macos/entitlements.plist | 9 + packaging/macos/import-cert.sh | 50 + packaging/macos/package.sh | 167 + packaging/macos/verify.sh | 149 + packaging/web/.htaccess | 16 + packaging/web/README.md | 88 + packaging/web/_headers | 13 + packaging/web/package.sh | 56 + packaging/windows/materialcraft.wxs | 76 + packaging/windows/package.ps1 | 135 + packaging/windows/sign.ps1 | 95 + rustfmt.toml | 3 + vendor/egui-phosphor/Cargo.toml | 19 + vendor/egui-phosphor/LICENSE-APACHE | 201 ++ vendor/egui-phosphor/LICENSE-MIT | 21 + vendor/egui-phosphor/README.md | 79 + vendor/egui-phosphor/VENDORED.md | 9 + vendor/egui-phosphor/res/Phosphor-Fill.ttf | Bin 0 -> 449252 bytes vendor/egui-phosphor/res/Phosphor.ttf | Bin 0 -> 488636 bytes vendor/egui-phosphor/src/lib.rs | 65 + vendor/egui-phosphor/src/subset.rs | 1016 ++++++ vendor/egui-phosphor/src/variants/bold.rs | 1 + .../egui-phosphor/src/variants/codepoints.rs | 3064 +++++++++++++++++ vendor/egui-phosphor/src/variants/fill.rs | 1 + vendor/egui-phosphor/src/variants/light.rs | 1 + vendor/egui-phosphor/src/variants/mod.rs | 83 + vendor/egui-phosphor/src/variants/regular.rs | 1 + vendor/egui-phosphor/src/variants/thin.rs | 1 + xtask/Cargo.toml | 13 + xtask/src/ico.rs | 173 + xtask/src/layers.rs | 209 ++ xtask/src/main.rs | 179 + xtask/src/version.rs | 148 + 118 files changed, 19000 insertions(+) create mode 100644 .cargo/config.toml create mode 100644 .coderabbit.yaml create mode 100644 .gitattributes create mode 100644 .github/actionlint.yaml create mode 100644 .github/workflows/ci.yml create mode 100644 .github/workflows/freebsd.yml create mode 100644 .github/workflows/packaging-lint.yml create mode 100644 .github/workflows/release.yml create mode 100644 .github/workflows/windows-arm64.yml create mode 100644 .gitignore create mode 100644 CLAUDE.md create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 LICENSE-APACHE create mode 100644 LICENSE-MIT create mode 100644 NOTICE create mode 100644 clippy.toml create mode 100644 crates/core/Cargo.toml create mode 100644 crates/core/src/function.rs create mode 100644 crates/core/src/graph.rs create mode 100644 crates/core/src/lib.rs create mode 100644 crates/core/src/package.rs create mode 100644 crates/core/src/value.rs create mode 100644 crates/engine/Cargo.toml create mode 100644 crates/engine/src/commands.rs create mode 100644 crates/engine/src/edit_cmds.rs create mode 100644 crates/engine/src/file_cmds.rs create mode 100644 crates/engine/src/graph_cmds.rs create mode 100644 crates/engine/src/inspect.rs create mode 100644 crates/engine/src/lib.rs create mode 100644 crates/engine/src/node_cmds.rs create mode 100644 crates/engine/src/samples.rs create mode 100644 crates/engine/src/session.rs create mode 100644 crates/engine/src/view_cmds.rs create mode 100644 crates/engine/tests/session.rs create mode 100644 crates/eval/Cargo.toml create mode 100644 crates/eval/src/lib.rs create mode 100644 crates/formats/Cargo.toml create mode 100644 crates/formats/src/lib.rs create mode 100644 crates/geom/Cargo.toml create mode 100644 crates/geom/src/bvh.rs create mode 100644 crates/geom/src/camera.rs create mode 100644 crates/geom/src/gbuffer.rs create mode 100644 crates/geom/src/lib.rs create mode 100644 crates/geom/src/mesh.rs create mode 100644 crates/geom/src/primitives.rs create mode 100644 crates/geom/src/unwrap.rs create mode 100644 crates/image/Cargo.toml create mode 100644 crates/image/src/lib.rs create mode 100644 crates/nodes/Cargo.toml create mode 100644 crates/nodes/src/atomic.rs create mode 100644 crates/nodes/src/catalog.rs create mode 100644 crates/nodes/src/filters.rs create mode 100644 crates/nodes/src/function.rs create mode 100644 crates/nodes/src/generators.rs create mode 100644 crates/nodes/src/lib.rs create mode 100644 crates/nodes/src/material.rs create mode 100644 crates/nodes/src/noise.rs create mode 100644 crates/nodes/src/ops.rs create mode 100644 crates/nodes/src/patterns.rs create mode 100644 docs/brand/LICENSE-brand.txt create mode 100644 docs/brand/artcraft-logo-white.png create mode 100644 docs/brand/artcraft-logo-white.svg create mode 100644 docs/brand/artcraft-logo.png create mode 100644 docs/brand/artcraft-logo.svg create mode 100644 docs/brand/artcraft-mark-black.png create mode 100644 docs/brand/artcraft-mark-black.svg create mode 100644 docs/brand/artcraft-mark.png create mode 100644 docs/brand/artcraft-mark.svg create mode 100644 packaging/.shellcheckrc create mode 100644 packaging/env.sh create mode 100644 packaging/freebsd/package.sh create mode 100644 packaging/icons.sh create mode 100644 packaging/linux/AppRun create mode 100644 packaging/linux/ai.storyteller.materialcraft.desktop create mode 100644 packaging/linux/ai.storyteller.materialcraft.metainfo.xml.in create mode 100644 packaging/linux/ai.storyteller.materialcraft.mime.xml create mode 100644 packaging/linux/apprun-test.sh create mode 100644 packaging/linux/flatpak-bundle.sh create mode 100644 packaging/linux/flatpak/ai.storyteller.MaterialCraft.bundle.yml create mode 100644 packaging/linux/flatpak/ai.storyteller.MaterialCraft.yml create mode 100644 packaging/linux/nfpm.yaml create mode 100644 packaging/linux/package.sh create mode 100644 packaging/linux/postinst.sh create mode 100644 packaging/macos/Info.plist.in create mode 100644 packaging/macos/entitlements.plist create mode 100644 packaging/macos/import-cert.sh create mode 100644 packaging/macos/package.sh create mode 100644 packaging/macos/verify.sh create mode 100644 packaging/web/.htaccess create mode 100644 packaging/web/README.md create mode 100644 packaging/web/_headers create mode 100644 packaging/web/package.sh create mode 100644 packaging/windows/materialcraft.wxs create mode 100644 packaging/windows/package.ps1 create mode 100644 packaging/windows/sign.ps1 create mode 100644 rustfmt.toml create mode 100644 vendor/egui-phosphor/Cargo.toml create mode 100644 vendor/egui-phosphor/LICENSE-APACHE create mode 100644 vendor/egui-phosphor/LICENSE-MIT create mode 100644 vendor/egui-phosphor/README.md create mode 100644 vendor/egui-phosphor/VENDORED.md create mode 100644 vendor/egui-phosphor/res/Phosphor-Fill.ttf create mode 100644 vendor/egui-phosphor/res/Phosphor.ttf create mode 100644 vendor/egui-phosphor/src/lib.rs create mode 100644 vendor/egui-phosphor/src/subset.rs create mode 100644 vendor/egui-phosphor/src/variants/bold.rs create mode 100644 vendor/egui-phosphor/src/variants/codepoints.rs create mode 100644 vendor/egui-phosphor/src/variants/fill.rs create mode 100644 vendor/egui-phosphor/src/variants/light.rs create mode 100644 vendor/egui-phosphor/src/variants/mod.rs create mode 100644 vendor/egui-phosphor/src/variants/regular.rs create mode 100644 vendor/egui-phosphor/src/variants/thin.rs create mode 100644 xtask/Cargo.toml create mode 100644 xtask/src/ico.rs create mode 100644 xtask/src/layers.rs create mode 100644 xtask/src/main.rs create mode 100644 xtask/src/version.rs diff --git a/.cargo/config.toml b/.cargo/config.toml new file mode 100644 index 00000000..5592118f --- /dev/null +++ b/.cargo/config.toml @@ -0,0 +1,2 @@ +[alias] +xtask = "run -p xtask --" diff --git a/.coderabbit.yaml b/.coderabbit.yaml new file mode 100644 index 00000000..2408084c --- /dev/null +++ b/.coderabbit.yaml @@ -0,0 +1,6 @@ +# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json +reviews: + auto_review: + # Dependabot bumps are checked by CI; skip CodeRabbit reviews on them. + ignore_usernames: + - "dependabot[bot]" diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..12adf75e --- /dev/null +++ b/.gitattributes @@ -0,0 +1,5 @@ +* text=auto eol=lf +*.png binary +*.ico binary +*.icns binary +*.ps1 text eol=crlf diff --git a/.github/actionlint.yaml b/.github/actionlint.yaml new file mode 100644 index 00000000..a7b0f0ad --- /dev/null +++ b/.github/actionlint.yaml @@ -0,0 +1,4 @@ +# Custom runner labels actionlint can't know about. +self-hosted-runner: + labels: + - github-ubuntu-16core # org 16-core larger runner, used by release.yml's FreeBSD VM job diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 00000000..a9e5501a --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,30 @@ +name: CI + +# Quality gates for every push to main and every pull request (`cargo xtask ci`), through the +# suite's shared gate workflow in craft-common-actions. +on: + push: + branches: [main] + pull_request: + workflow_dispatch: + +permissions: + contents: read + +# A newer push to a PR branch cancels its older run; every push to main runs to the end. +concurrency: + group: ci-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + gate: + # Tracks @main so suite-wide CI fixes reach every app without a PR in each repository. + uses: storytold/craft-common-actions/.github/workflows/gate.yml@main + with: + # Same craft-fonts commit as release.yml. + craft-fonts-ref: 3d9ab3a132ed0eff457e424226a435a901da30d3 + os: '["ubuntu-24.04","windows-latest"]' + toolchain: "1.96.0" + packages: >- + libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev libgl1-mesa-dev + libgtk-3-dev diff --git a/.github/workflows/freebsd.yml b/.github/workflows/freebsd.yml new file mode 100644 index 00000000..ae8422b6 --- /dev/null +++ b/.github/workflows/freebsd.yml @@ -0,0 +1,36 @@ +# Builds and tests the workspace on FreeBSD, inside a FreeBSD VM on a Linux runner +# (GitHub has no FreeBSD runners). GPU tests skip themselves when the VM has no adapter. +# It then runs packaging/freebsd/package.sh, the script the release job runs, and checks the +# tarball, so a broken FreeBSD package fails here before it can fail a release. Nothing is +# uploaded and no secrets are used. +name: FreeBSD + +# The VM build takes one to several hours, so it runs nightly on main rather than on every push +# or dependency change: a drifted dependency still shows up within a day. PRs that change the +# FreeBSD packaging itself still run it. +on: + push: + branches: [release] + schedule: + - cron: "17 2 * * *" + pull_request: + paths: + - .github/workflows/freebsd.yml + - packaging/freebsd/** + - packaging/env.sh + workflow_dispatch: + +concurrency: + group: freebsd-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + freebsd: + # 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/freebsd.yml@main + with: + craft-fonts-ref: 3d9ab3a132ed0eff457e424226a435a901da30d3 + run-package-check: true diff --git a/.github/workflows/packaging-lint.yml b/.github/workflows/packaging-lint.yml new file mode 100644 index 00000000..f54b0538 --- /dev/null +++ b/.github/workflows/packaging-lint.yml @@ -0,0 +1,23 @@ +# Quick static checks for the release pipeline (seconds, no Rust build): workflow syntax, +# packaging shell/PowerShell scripts, and the Linux desktop/AppStream/Flatpak metadata. +name: Packaging lint + +on: + push: + branches: [main, release] + paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**"] + pull_request: + paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**"] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: packaging-lint-${{ github.ref }} + cancel-in-progress: true + +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 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 00000000..43db675f --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,45 @@ +name: Release + +on: + push: + branches: [release] + workflow_dispatch: + inputs: + version: + description: "Version override for a test run, e.g. 0.2.0-rc.1 (empty: Cargo.toml)" + type: string + default: "" + +permissions: + contents: write + packages: write + +concurrency: + group: release-${{ github.ref }} + cancel-in-progress: false + +jobs: + release: + # 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/release.yml@main + with: + app-name: materialcraft + app-title: "MaterialCraft" + craft-fonts-ref: 3d9ab3a132ed0eff457e424226a435a901da30d3 + web-craft-fonts: true + version: ${{ inputs.version }} + secrets: + APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }} + APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }} + KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }} + APPLE_ID: ${{ secrets.APPLE_ID }} + APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }} + APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }} + WINDOWS_CERTIFICATE: ${{ secrets.WINDOWS_CERTIFICATE }} + WINDOWS_CERTIFICATE_PASSWORD: ${{ secrets.WINDOWS_CERTIFICATE_PASSWORD }} + AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }} + AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }} + AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }} + AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }} + AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }} + AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }} diff --git a/.github/workflows/windows-arm64.yml b/.github/workflows/windows-arm64.yml new file mode 100644 index 00000000..eafe4d20 --- /dev/null +++ b/.github/workflows/windows-arm64.yml @@ -0,0 +1,33 @@ +# Windows on ARM: package the ARM64 release the way release.yml does (cross-compiled on an x64 +# runner, unsigned here), then install that MSI on a Windows 11 ARM64 runner, check the installed +# binaries are ARM64, run the CLI natively, and uninstall. (A native ARM64 `cargo test` job is left +# out for now: PdfCraft saw an intermittent access violation in egui UI tests there.) +name: Windows ARM64 + +# Nightly on main (dependency and runner-image drift shows up within a day), and on PRs that +# change the Windows packaging itself. +on: + push: + branches: [release] + pull_request: + paths: + - .github/workflows/windows-arm64.yml + - packaging/windows/** + schedule: + - cron: "41 4 * * *" + workflow_dispatch: + +concurrency: + group: windows-arm64-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + windows-arm64: + # 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/windows-arm64.yml@main + with: + app-name: materialcraft + app-dir: "MaterialCraft" diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..d602ce1c --- /dev/null +++ b/.gitignore @@ -0,0 +1,11 @@ +*~ +plan/ +/target +target/ +/dist +/corpus +/log +/secrets +/temp +/craft-fonts +*.mcraft.tmp diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 00000000..911603ec --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,5 @@ +# MaterialCraft: instructions for Claude + +Read [`AGENTS.md`](AGENTS.md) first: it is the guide for every agent working in this repository +(workspace map, golden rules including the asset and attribution rules, the definition of done). +Then read `../craftrules/AGENTS.md` for the standards shared by all Crafting Apps. diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 00000000..f8f61c92 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,791 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "arbitrary" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed" +dependencies = [ + "derive_arbitrary", +] + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "bit_field" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e4b40c7323adcfc0a41c4b88143ed58346ff65a288fc144329c5c45e05d70c6" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" +dependencies = [ + "bytemuck_derive", +] + +[[package]] +name = "bytemuck_derive" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "byteorder-lite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "crc32fast" +version = "1.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ba106e844045ddc02c20768ac4b0b7cb45f2cc2ecbd833ac9f5dacb183c2055" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crossbeam-deque" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + +[[package]] +name = "derive_arbitrary" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b034bd7d5f032402a2479444dcc6f74e36a03f31854d41680fb240ef682a1ac" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "exr" +version = "1.74.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "711fe42c9964295e01ee3fba3f9fe0e1d24b98886950d68efe81b1c76e21adf3" +dependencies = [ + "bit_field", + "half", + "lebe", + "miniz_oxide 0.8.9", + "num-complex", + "pulp", + "smallvec", + "zune-inflate", +] + +[[package]] +name = "fax" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caf1079563223d5d59d83c85886a56e586cfd5c1a26292e971a0fa266531ac5a" + +[[package]] +name = "fdeflate" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" +dependencies = [ + "simd-adler32", +] + +[[package]] +name = "flate2" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +dependencies = [ + "crc32fast", + "miniz_oxide 0.9.1", + "zlib-rs", +] + +[[package]] +name = "glam" +version = "0.15.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3abb554f8ee44336b72d522e0a7fe86a29e09f839a36022fa869a7dfe941a54b" + +[[package]] +name = "glam" +version = "0.30.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19fc433e8437a212d1b6f1e68c7824af3aed907da60afa994e7f542d18d12aa9" +dependencies = [ + "bytemuck", + "serde_core", +] + +[[package]] +name = "half" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" +dependencies = [ + "cfg-if", + "crunchy", + "zerocopy", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "image" +version = "0.25.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" +dependencies = [ + "bytemuck", + "byteorder-lite", + "exr", + "image-webp", + "moxcms", + "num-traits", + "png", + "tiff", + "zune-core", + "zune-jpeg", +] + +[[package]] +name = "image-webp" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3" +dependencies = [ + "byteorder-lite", + "quick-error", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "lebe" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a79a3332a6609480d7d0c9eab957bca6b455b91bb84e66d19f5ff66294b85b8" + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "materialcraft-core" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "thiserror", +] + +[[package]] +name = "materialcraft-engine" +version = "0.1.0" +dependencies = [ + "materialcraft-core", + "materialcraft-eval", + "materialcraft-formats", + "materialcraft-image", + "materialcraft-nodes", + "serde", + "serde_json", + "thiserror", +] + +[[package]] +name = "materialcraft-eval" +version = "0.1.0" +dependencies = [ + "materialcraft-core", + "materialcraft-image", + "materialcraft-nodes", + "serde_json", +] + +[[package]] +name = "materialcraft-formats" +version = "0.1.0" +dependencies = [ + "image", + "materialcraft-core", + "materialcraft-image", + "serde_json", + "thiserror", + "zip", +] + +[[package]] +name = "materialcraft-geom" +version = "0.1.0" +dependencies = [ + "glam 0.30.10", + "mikktspace", + "rayon", + "serde", + "thiserror", +] + +[[package]] +name = "materialcraft-image" +version = "0.1.0" +dependencies = [ + "rayon", + "thiserror", +] + +[[package]] +name = "materialcraft-nodes" +version = "0.1.0" +dependencies = [ + "materialcraft-core", + "materialcraft-image", + "rayon", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mikktspace" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d0b56b403871a8f992ca626d52cc0a690d4841baea8955dc4af6304ac62f8b0" +dependencies = [ + "glam 0.15.2", +] + +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "moxcms" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b" +dependencies = [ + "num-traits", + "pxfm", +] + +[[package]] +name = "num-complex" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" +dependencies = [ + "bytemuck", + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "paste" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" + +[[package]] +name = "png" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" +dependencies = [ + "bitflags", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "pulp" +version = "0.22.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "046aa45b989642ec2e4717c8e72d677b13edd831a4d3b6cf37d9a3e54912496a" +dependencies = [ + "bytemuck", + "cfg-if", + "libm", + "num-complex", + "paste", + "pulp-wasm-simd-flag", + "raw-cpuid", + "reborrow", + "version_check", +] + +[[package]] +name = "pulp-wasm-simd-flag" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d8f70e07b9c3962945a74e59ca1c511bba65b6419468acc217c457d93f3c740" + +[[package]] +name = "pxfm" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" + +[[package]] +name = "quick-error" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "raw-cpuid" +version = "11.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "498cd0dc59d73224351ee52a95fee0f1a617a2eae0e7d9d720cc622c73a54186" +dependencies = [ + "bitflags", +] + +[[package]] +name = "rayon" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + +[[package]] +name = "reborrow" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03251193000f4bd3b042892be858ee50e8b3719f2b08e5833ac4353724632430" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "smallvec" +version = "1.16.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "tiff" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63feaf3343d35b6ca4d50483f94843803b0f51634937cc2ec519fc32232bc52" +dependencies = [ + "fax", + "flate2", + "half", + "quick-error", + "weezl", + "zune-jpeg", +] + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "weezl" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" + +[[package]] +name = "xtask" +version = "0.1.0" +dependencies = [ + "serde_json", +] + +[[package]] +name = "zerocopy" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zip" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1dcb24d0152526ae49b9b96c1dcf71850ca1e0b882e4e28ed898a93c41334744" +dependencies = [ + "arbitrary", + "crc32fast", + "crossbeam-utils", + "flate2", + "indexmap", + "memchr", + "zopfli", +] + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zopfli" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aaf7fc5d30c28483d93805c4a5e12b05bbb52407fa67c5f8bd552374cd01fb11" +dependencies = [ + "bumpalo", + "crc32fast", + "log", + "simd-adler32", +] + +[[package]] +name = "zune-core" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" + +[[package]] +name = "zune-inflate" +version = "0.2.54" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73ab332fe2f6680068f3582b16a24f90ad7096d5d39b974d1c0aff0125116f02" +dependencies = [ + "simd-adler32", +] + +[[package]] +name = "zune-jpeg" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296" +dependencies = [ + "zune-core", +] + +[[patch.unused]] +name = "ecolor" +version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" + +[[patch.unused]] +name = "eframe" +version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" + +[[patch.unused]] +name = "egui" +version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" + +[[patch.unused]] +name = "egui-phosphor" +version = "0.14.0" + +[[patch.unused]] +name = "egui-wgpu" +version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" + +[[patch.unused]] +name = "egui-winit" +version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" + +[[patch.unused]] +name = "egui_glow" +version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" + +[[patch.unused]] +name = "emath" +version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" + +[[patch.unused]] +name = "epaint" +version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" + +[[patch.unused]] +name = "epaint_default_fonts" +version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" + +[[patch.unused]] +name = "winit" +version = "0.30.13" +source = "git+https://github.com/storytold/winit.git?rev=a517b3846ee8457d84ee4975110bfda6797c44dc#a517b3846ee8457d84ee4975110bfda6797c44dc" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 00000000..3fd7d81e --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,106 @@ +[workspace] +resolver = "3" +members = ["crates/core", "crates/image", "crates/geom", "crates/nodes", "crates/eval", "crates/formats", "crates/engine", "xtask"] +exclude = ["vendor"] + +[workspace.package] +version = "0.1.0" +edition = "2024" +license = "MIT OR Apache-2.0" +rust-version = "1.95" +repository = "https://github.com/storytold/materialcraft" + +[workspace.dependencies] +# internal +materialcraft-core = { path = "crates/core" } +materialcraft-image = { path = "crates/image" } +materialcraft-geom = { path = "crates/geom" } +materialcraft-nodes = { path = "crates/nodes" } +materialcraft-eval = { path = "crates/eval" } +materialcraft-formats = { path = "crates/formats" } +materialcraft-engine = { path = "crates/engine" } +materialcraft-render = { path = "crates/render" } +materialcraft-automation = { path = "crates/automation" } +materialcraft-ui-egui = { path = "crates/ui-egui" } + +# external +thiserror = "2" +serde = { version = "1", features = ["derive"] } +serde_json = "1" +glam = { version = "0.30", features = ["serde", "bytemuck"] } +bytemuck = { version = "1", features = ["derive"] } +rayon = "1" +log = "0.4" +image = { version = "0.25", default-features = false, features = ["png", "jpeg", "tga", "tiff", "exr", "hdr", "bmp", "webp"] } +half = "2" +eframe = { version = "0.37", default-features = false } +egui = "0.37" +wgpu = "30" +rfd = "0.17" +zip = { version = "2", default-features = false, features = ["deflate"] } +mikktspace = { version = "0.3", default-features = false, features = ["glam"] } +rmcp = { version = "3.5", default-features = false, features = ["server", "macros", "transport-io"] } +tokio = { version = "1", features = ["rt-multi-thread", "macros", "io-std", "sync", "net", "io-util", "time"] } +schemars = "1" +base64 = "0.22" +cap-std = "4" +getrandom = "0.3" +# Shared Craft egui components (widget palette, icon buttons, panel docking): storytold/craft-libs, +# MIT OR Apache-2.0, pinned to one rev (the one TextureCraft pins). +craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242", features = ["serde"] } + +# 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" } +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" + +[workspace.lints.clippy] +dbg_macro = "warn" +todo = "warn" +# Index loops read better than zipped iterators in per-pixel code. +needless_range_loop = "allow" +field_reassign_with_default = "allow" +too_many_arguments = "allow" + +[profile.dev.package."*"] +opt-level = 2 + +[profile.dev] +opt-level = 1 + +[profile.release] +lto = "thin" +codegen-units = 1 + +[profile.wasm-release] +inherits = "release" +opt-level = "s" +lto = "fat" +codegen-units = 1 +strip = "debuginfo" + +[profile.wasm-release.package."*"] +opt-level = "s" + +# Node cooking and the vector math under it run per pixel. +[profile.wasm-release.package.materialcraft-image] +opt-level = 3 +[profile.wasm-release.package.materialcraft-nodes] +opt-level = 3 +[profile.wasm-release.package.materialcraft-render] +opt-level = 3 +[profile.wasm-release.package.glam] +opt-level = 3 diff --git a/LICENSE-APACHE b/LICENSE-APACHE new file mode 100644 index 00000000..f433b1a5 --- /dev/null +++ b/LICENSE-APACHE @@ -0,0 +1,177 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/LICENSE-MIT b/LICENSE-MIT new file mode 100644 index 00000000..79f49e29 --- /dev/null +++ b/LICENSE-MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 ArtCraft Team and the MaterialCraft contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/NOTICE b/NOTICE new file mode 100644 index 00000000..22ac266c --- /dev/null +++ b/NOTICE @@ -0,0 +1,26 @@ +MaterialCraft +Copyright (c) 2026 ArtCraft Team and the MaterialCraft contributors. +Licensed under the MIT License or the Apache License, Version 2.0, at your option +(LICENSE-MIT, LICENSE-APACHE). + +The ArtCraft name, wordmark and logos in docs/brand/ are trademarks of the ArtCraft Team. They are +not open source and are not covered by the license above; their terms are in +docs/brand/LICENSE-brand.txt. + +Third-party material + +This product bundles third-party material under its own licenses, listed below. The per-file +list (author, source, license) is in ATTRIBUTION.md. + +Phosphor Icons (compiled in through the egui-phosphor crate) — MIT. +egui default fonts (compiled in through the epaint_default_fonts crate): Ubuntu-Light — Ubuntu +Font Licence 1.0; Hack — MIT and Bitstream Vera License; Noto Emoji — SIL Open Font License 1.1; +emoji-icon-font — MIT. + +Every other bundled asset is original to MaterialCraft (generated in code or drawn for this +project). + +Builds made with craft-fonts (CRAFT_FONTS_DIR; all official releases) also embed the fonts listed +in https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md (BIZ UDPGothic on desktop and +web, Noto Sans CJK SC on desktop), under the SIL Open Font License 1.1. Their licence texts ship +with the package as OFL-.txt. diff --git a/clippy.toml b/clippy.toml new file mode 100644 index 00000000..4b6c79f5 --- /dev/null +++ b/clippy.toml @@ -0,0 +1,4 @@ +allow-unwrap-in-tests = true +allow-expect-in-tests = true +allow-panic-in-tests = true +allow-indexing-slicing-in-tests = true diff --git a/crates/core/Cargo.toml b/crates/core/Cargo.toml new file mode 100644 index 00000000..9374e16f --- /dev/null +++ b/crates/core/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "materialcraft-core" +description = "MaterialCraft document model: packages, graphs, nodes, connections, parameters" +version.workspace = true +edition.workspace = true +license.workspace = true + +[lints] +workspace = true + +[dependencies] +serde = { workspace = true } +serde_json = { workspace = true } +thiserror = { workspace = true } diff --git a/crates/core/src/function.rs b/crates/core/src/function.rs new file mode 100644 index 00000000..4e49aaf5 --- /dev/null +++ b/crates/core/src/function.rs @@ -0,0 +1,67 @@ +//! Function graphs: small typed expression graphs evaluated per pixel (pixel processor), once +//! per cook (value processor) or to compute a parameter dynamically. The data lives here; the +//! evaluator is `materialcraft_nodes::function`. + +use serde::{Deserialize, Serialize}; + +use crate::Value; + +/// A node in a function graph. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct FnNode { + pub id: u32, + /// Operation id, e.g. `const_float`, `add`, `sample_gray`, `get_float2` (see the evaluator's + /// catalog for the full list). + pub op: String, + /// Upstream node per input slot, in the op's slot order. + #[serde(default)] + pub inputs: Vec>, + /// The constant (`const_*`), the variable name (`get_*`) or the input index (`sample_*`). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub value: Option, + #[serde(default)] + pub pos: [f32; 2], +} + +/// A function graph: nodes plus the id of the node whose value is the result. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct FnGraph { + pub nodes: Vec, + #[serde(default)] + pub output: Option, +} + +impl FnGraph { + pub fn node(&self, id: u32) -> Option<&FnNode> { + self.nodes.iter().find(|n| n.id == id) + } + + fn next_id(&self) -> u32 { + self.nodes.iter().map(|n| n.id + 1).max().unwrap_or(1) + } + + /// Append a node and return its id. + pub fn add(&mut self, op: &str, inputs: &[u32], value: Option) -> u32 { + let id = self.next_id(); + let x = self.nodes.len() as f32 * 140.0; + self.nodes.push(FnNode { id, op: op.into(), inputs: inputs.iter().map(|i| Some(*i)).collect(), value, pos: [x, 0.0] }); + id + } + + /// A graph returning one constant. + pub fn constant(v: Value) -> FnGraph { + let op = match &v { + Value::Float(_) => "const_float", + Value::Float2(_) => "const_float2", + Value::Float3(_) => "const_float3", + Value::Float4(_) | Value::Color(_) => "const_float4", + Value::Int(_) | Value::Enum(_) => "const_int", + Value::Bool(_) => "const_bool", + _ => "const_float", + }; + let mut g = FnGraph::default(); + let id = g.add(op, &[], Some(v)); + g.output = Some(id); + g + } +} diff --git a/crates/core/src/graph.rs b/crates/core/src/graph.rs new file mode 100644 index 00000000..3873e5d1 --- /dev/null +++ b/crates/core/src/graph.rs @@ -0,0 +1,420 @@ +//! Graphs: nodes, connections, frames, comments, navigation pins and exposed inputs. + +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; + +use crate::{CoreError, Result, Value}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +pub struct NodeId(pub u64); + +/// How a node's output size follows its surroundings ("Output size" base parameter). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum SizeMode { + /// The size of the main (first connected) input; the graph size when none is connected. + #[default] + RelativeToInput, + /// The graph ("parent") size. + RelativeToParent, + /// `offset` is the absolute log2 size (e.g. 10 = 1024 px). + Absolute, +} + +/// The output bit depth ("Output format"). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum OutputFormat { + /// The main input's format; 16 bits for generators. + #[default] + Inherit, + U8, + U16, + F16, + F32, +} + +impl OutputFormat { + pub const ALL: [OutputFormat; 5] = [OutputFormat::Inherit, OutputFormat::U8, OutputFormat::U16, OutputFormat::F16, OutputFormat::F32]; + + pub fn label(self) -> &'static str { + match self { + OutputFormat::Inherit => "Relative to input", + OutputFormat::U8 => "8 bits per channel", + OutputFormat::U16 => "16 bits per channel", + OutputFormat::F16 => "16 bits per channel float (HDR)", + OutputFormat::F32 => "32 bits per channel float (HDR)", + } + } + + /// The suffix of a node's size label: `8`, `16`, `16F`, `32F`. + pub fn bits(self) -> &'static str { + match self { + OutputFormat::Inherit | OutputFormat::U16 => "16", + OutputFormat::U8 => "8", + OutputFormat::F16 => "16F", + OutputFormat::F32 => "32F", + } + } +} + +/// Parameters every node has ("Base parameters"). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct BaseParams { + pub size_mode: SizeMode, + /// log2 offset per axis (relative modes) or log2 size (absolute). + pub size: [i32; 2], + pub format: OutputFormat, + /// Added to the graph's random seed for this node. + pub seed: i32, + /// Whether sampling wraps at the edges (horizontal, vertical). + pub tiling: [bool; 2], +} + +impl Default for BaseParams { + fn default() -> Self { + BaseParams { size_mode: SizeMode::RelativeToInput, size: [0, 0], format: OutputFormat::Inherit, seed: 0, tiling: [true, true] } + } +} + +/// A node instance: a catalog definition (`def`) with parameter overrides. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Node { + pub id: NodeId, + /// Catalog id, e.g. `blend`, `perlin_noise`, `output`, `input_color`, `graph_instance`. + pub def: String, + /// User label; empty = the definition's label. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub label: String, + /// Graph-space position of the node's top-left corner. + pub pos: [f32; 2], + /// Values that differ from the catalog defaults. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub params: BTreeMap, + /// Parameters driven by a graph input (param id → exposed input id). + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub bindings: BTreeMap, + #[serde(default)] + pub base: BaseParams, + /// A disabled node passes its first input through. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub disabled: bool, +} + +impl Node { + pub fn new(id: NodeId, def: &str, pos: [f32; 2]) -> Node { + Node { + id, + def: def.into(), + label: String::new(), + pos, + params: BTreeMap::new(), + bindings: BTreeMap::new(), + base: BaseParams::default(), + disabled: false, + } + } +} + +/// A link from an output port to an input port. +#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Connection { + pub from: NodeId, + pub from_port: String, + pub to: NodeId, + pub to_port: String, +} + +/// A titled, colored rectangle behind a group of nodes. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Frame { + pub id: u64, + pub title: String, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub description: String, + /// `[x, y, width, height]` in graph space. + pub rect: [f32; 4], + /// Linear RGBA (alpha is the fill opacity). + pub color: [f32; 4], +} + +/// A sticky note on the canvas. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Comment { + pub id: u64, + pub text: String, + pub pos: [f32; 2], + #[serde(default = "comment_size")] + pub size: [f32; 2], +} + +fn comment_size() -> [f32; 2] { + [180.0, 70.0] +} + +/// A named bookmark on the canvas (Previous/Next pin). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Pin { + pub id: u64, + pub name: String, + pub pos: [f32; 2], +} + +/// The kind of value an exposed graph input carries. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ExposedParam { + /// Identifier, unique in the graph. + pub id: String, + pub label: String, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub group: String, + pub default: Value, + #[serde(default)] + pub min: f32, + #[serde(default = "one")] + pub max: f32, + /// Labels when the value is an enum. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub options: Vec, +} + +fn one() -> f32 { + 1.0 +} + +/// Descriptive metadata ("Attributes"). +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct Attributes { + pub category: String, + pub description: String, + pub author: String, + pub tags: String, +} + +/// Whether a graph makes images or is a function. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum GraphKind { + #[default] + Material, + Function, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Graph { + pub name: String, + #[serde(default)] + pub kind: GraphKind, + pub nodes: Vec, + pub connections: Vec, + #[serde(default)] + pub frames: Vec, + #[serde(default)] + pub comments: Vec, + #[serde(default)] + pub pins: Vec, + /// log2 of the graph ("parent") size per axis. + pub size: [u32; 2], + #[serde(default)] + pub format: OutputFormat, + #[serde(default)] + pub seed: i32, + #[serde(default)] + pub exposed: Vec, + /// Current values of the exposed inputs (missing = default). + #[serde(default)] + pub inputs: BTreeMap, + #[serde(default)] + pub attributes: Attributes, + /// The id the next node, frame, comment or pin gets. + pub next_id: u64, +} + +/// Smallest and largest graph size, as log2 (16 px .. 8192 px). +pub const MIN_SIZE_LOG2: u32 = 4; +pub const MAX_SIZE_LOG2: u32 = 13; + +impl Graph { + pub fn new(name: &str) -> Graph { + Graph { + name: name.into(), + kind: GraphKind::Material, + nodes: Vec::new(), + connections: Vec::new(), + frames: Vec::new(), + comments: Vec::new(), + pins: Vec::new(), + size: [10, 10], + format: OutputFormat::U16, + seed: 0, + exposed: Vec::new(), + inputs: BTreeMap::new(), + attributes: Attributes::default(), + next_id: 1, + } + } + + pub fn alloc_id(&mut self) -> u64 { + let id = self.next_id; + self.next_id = self.next_id.saturating_add(1); + id + } + + pub fn node(&self, id: NodeId) -> Result<&Node> { + self.nodes.iter().find(|n| n.id == id).ok_or(CoreError::NoNode(id.0)) + } + + pub fn node_mut(&mut self, id: NodeId) -> Result<&mut Node> { + self.nodes.iter_mut().find(|n| n.id == id).ok_or(CoreError::NoNode(id.0)) + } + + /// Add a node of definition `def` at `pos`; returns its id. + pub fn add_node(&mut self, def: &str, pos: [f32; 2]) -> NodeId { + let id = NodeId(self.alloc_id()); + self.nodes.push(Node::new(id, def, pos)); + id + } + + /// Remove nodes and every connection touching them. + pub fn remove_nodes(&mut self, ids: &[NodeId]) { + self.nodes.retain(|n| !ids.contains(&n.id)); + self.connections.retain(|c| !ids.contains(&c.from) && !ids.contains(&c.to)); + } + + /// Connect `from.from_port` → `to.to_port`, replacing whatever fed that input. Refuses + /// connections that would make a cycle. + pub fn connect(&mut self, from: NodeId, from_port: &str, to: NodeId, to_port: &str) -> Result<()> { + self.node(from)?; + self.node(to)?; + if from == to || self.reaches(to, from) { + return Err(CoreError::Cycle); + } + self.connections.retain(|c| !(c.to == to && c.to_port == to_port)); + self.connections.push(Connection { from, from_port: from_port.into(), to, to_port: to_port.into() }); + Ok(()) + } + + pub fn disconnect(&mut self, to: NodeId, to_port: &str) -> bool { + let before = self.connections.len(); + self.connections.retain(|c| !(c.to == to && c.to_port == to_port)); + before != self.connections.len() + } + + /// The connection feeding `to.to_port`. + pub fn input_of(&self, to: NodeId, to_port: &str) -> Option<&Connection> { + self.connections.iter().find(|c| c.to == to && c.to_port == to_port) + } + + /// Whether `b` is downstream of (or equal to) `a`. + pub fn reaches(&self, a: NodeId, b: NodeId) -> bool { + let mut stack = vec![a]; + let mut seen = std::collections::BTreeSet::new(); + while let Some(n) = stack.pop() { + if n == b { + return true; + } + if !seen.insert(n) { + continue; + } + stack.extend(self.connections.iter().filter(|c| c.from == n).map(|c| c.to)); + } + false + } + + /// Nodes in dependency order (inputs before the nodes they feed). Nodes on a cycle (only + /// possible in a hand-edited file) are left out. + pub fn topo_order(&self) -> Vec { + let mut indeg: BTreeMap = self.nodes.iter().map(|n| (n.id, 0)).collect(); + for c in &self.connections { + if let Some(d) = indeg.get_mut(&c.to) + && self.nodes.iter().any(|n| n.id == c.from) + { + *d += 1; + } + } + let mut ready: Vec = indeg.iter().filter(|(_, d)| **d == 0).map(|(id, _)| *id).collect(); + let mut out = Vec::with_capacity(self.nodes.len()); + while let Some(n) = ready.pop() { + out.push(n); + for c in self.connections.iter().filter(|c| c.from == n) { + if let Some(d) = indeg.get_mut(&c.to) { + *d = d.saturating_sub(1); + if *d == 0 { + ready.push(c.to); + } + } + } + } + out + } + + /// Every node upstream of `id` (not including it). + pub fn upstream(&self, id: NodeId) -> Vec { + let mut out = Vec::new(); + let mut stack = vec![id]; + while let Some(n) = stack.pop() { + for c in self.connections.iter().filter(|c| c.to == n) { + if !out.contains(&c.from) { + out.push(c.from); + stack.push(c.from); + } + } + } + out + } + + /// Every node downstream of `id` (not including it). + pub fn downstream(&self, id: NodeId) -> Vec { + let mut out = Vec::new(); + let mut stack = vec![id]; + while let Some(n) = stack.pop() { + for c in self.connections.iter().filter(|c| c.from == n) { + if !out.contains(&c.to) { + out.push(c.to); + stack.push(c.to); + } + } + } + out + } + + /// The value of exposed input `id` (its default when unset). + pub fn input_value(&self, id: &str) -> Option<&Value> { + self.inputs.get(id).or_else(|| self.exposed.iter().find(|e| e.id == id).map(|e| &e.default)) + } + + /// Graph size in pixels. + pub fn size_px(&self) -> [u32; 2] { + [1 << self.size[0].clamp(MIN_SIZE_LOG2, MAX_SIZE_LOG2), 1 << self.size[1].clamp(MIN_SIZE_LOG2, MAX_SIZE_LOG2)] + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn connect_refuses_cycles_and_replaces_inputs() { + let mut g = Graph::new("g"); + let a = g.add_node("uniform", [0.0, 0.0]); + let b = g.add_node("blur", [100.0, 0.0]); + let c = g.add_node("blur", [200.0, 0.0]); + g.connect(a, "output", b, "input").unwrap(); + g.connect(b, "output", c, "input").unwrap(); + assert!(matches!(g.connect(c, "output", a, "input"), Err(CoreError::Cycle))); + assert!(matches!(g.connect(c, "output", c, "input"), Err(CoreError::Cycle))); + g.connect(a, "output", c, "input").unwrap(); + assert_eq!(g.connections.len(), 2); + assert_eq!(g.topo_order().first(), Some(&a)); + assert_eq!(g.upstream(c), vec![a]); + g.remove_nodes(&[a]); + assert_eq!(g.connections.len(), 0); + } +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs new file mode 100644 index 00000000..229b3471 --- /dev/null +++ b/crates/core/src/lib.rs @@ -0,0 +1,32 @@ +//! # materialcraft-core +//! +//! The MaterialCraft document model, L0 (pure data, no I/O): a [`Package`] holds [`Graph`]s and +//! [`Resource`]s; a graph holds [`Node`]s (catalog definitions with parameter overrides), +//! [`Connection`]s between named ports, frames, comments, navigation pins and exposed inputs. +//! Parameter values are [`Value`]s; function graphs ([`function::FnGraph`]) drive pixel and value +//! processors. +#![forbid(unsafe_code)] +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +pub mod function; +pub mod graph; +pub mod package; +pub mod value; + +pub use graph::{ + Attributes, BaseParams, Comment, Connection, ExposedParam, Frame, Graph, GraphKind, MAX_SIZE_LOG2, MIN_SIZE_LOG2, Node, NodeId, OutputFormat, Pin, SizeMode, +}; +pub use package::{PACKAGE_EXT, Package, Resource}; +pub use value::{Curve, CurvePoint, Gradient, GradientKey, Value, linear_to_srgb, parse_color, srgb_to_linear}; + +#[derive(Debug, thiserror::Error)] +pub enum CoreError { + #[error("no node {0}")] + NoNode(u64), + #[error("no graph {0}")] + NoGraph(usize), + #[error("that connection would make a cycle")] + Cycle, +} + +pub type Result = std::result::Result; diff --git a/crates/core/src/package.rs b/crates/core/src/package.rs new file mode 100644 index 00000000..44d0c361 --- /dev/null +++ b/crates/core/src/package.rs @@ -0,0 +1,68 @@ +//! Packages: the document. A package holds graphs and the resources (bitmaps) they use. + +use std::sync::Arc; + +use serde::{Deserialize, Serialize}; + +use crate::{CoreError, Graph, Result}; + +/// The native package extension (a zip: `package.json` plus `resources/`). +pub const PACKAGE_EXT: &str = "mcraft"; + +/// An embedded file: a bitmap a Bitmap node shows, or an SVG. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Resource { + /// Unique name, referenced by nodes (`resource` parameter). + pub name: String, + /// File name inside the package's `resources/` folder. + pub file: String, + /// The file's bytes (stored in the zip, not in `package.json`). + #[serde(skip)] + pub bytes: Arc>, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct Package { + pub name: String, + pub graphs: Vec, + #[serde(default)] + pub resources: Vec, + /// Format version of `package.json`. + #[serde(default = "version")] + pub version: u32, +} + +fn version() -> u32 { + 1 +} + +impl Package { + pub fn new(name: &str) -> Package { + Package { name: name.into(), graphs: Vec::new(), resources: Vec::new(), version: 1 } + } + + pub fn graph(&self, i: usize) -> Result<&Graph> { + self.graphs.get(i).ok_or(CoreError::NoGraph(i)) + } + + pub fn graph_mut(&mut self, i: usize) -> Result<&mut Graph> { + self.graphs.get_mut(i).ok_or(CoreError::NoGraph(i)) + } + + pub fn graph_by_name(&self, name: &str) -> Option<(usize, &Graph)> { + self.graphs.iter().enumerate().find(|(_, g)| g.name == name) + } + + pub fn resource(&self, name: &str) -> Option<&Resource> { + self.resources.iter().find(|r| r.name == name) + } + + /// A name not used by any graph: `base`, `base_1`, `base_2`… + pub fn unique_graph_name(&self, base: &str) -> String { + let base = if base.trim().is_empty() { "Graph" } else { base.trim() }; + if self.graph_by_name(base).is_none() { + return base.to_string(); + } + (1..).map(|i| format!("{base}_{i}")).find(|n| self.graph_by_name(n).is_none()).unwrap_or_else(|| base.to_string()) + } +} diff --git a/crates/core/src/value.rs b/crates/core/src/value.rs new file mode 100644 index 00000000..136b8e4e --- /dev/null +++ b/crates/core/src/value.rs @@ -0,0 +1,340 @@ +//! Parameter values: the typed data a node parameter, an exposed graph input or a function-graph +//! constant holds. + +use serde::{Deserialize, Serialize}; + +/// One control point of a [`Curve`]: position and value, both 0..1. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct CurvePoint { + pub x: f32, + pub y: f32, +} + +/// A monotone tone curve through sorted control points (linear when it has two points). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Curve { + pub points: Vec, +} + +impl Default for Curve { + fn default() -> Self { + Curve { points: vec![CurvePoint { x: 0.0, y: 0.0 }, CurvePoint { x: 1.0, y: 1.0 }] } + } +} + +impl Curve { + /// Value at `x` (0..1): monotone cubic (Fritsch–Carlson) through the points, clamped ends. + pub fn eval(&self, x: f32) -> f32 { + let p = &self.points; + let n = p.len(); + match n { + 0 => return x, + 1 => return p[0].y, + _ => {} + } + if x <= p[0].x { + return p[0].y; + } + if x >= p[n - 1].x { + return p[n - 1].y; + } + let mut i = 0; + while i + 2 < n && x > p[i + 1].x { + i += 1; + } + let slope = |a: usize| { + let (l, r) = (a.saturating_sub(1), (a + 1).min(n - 1)); + let dx = p[r].x - p[l].x; + if dx.abs() < 1e-6 { 0.0 } else { (p[r].y - p[l].y) / dx } + }; + let (a, b) = (p[i], p[i + 1]); + let h = (b.x - a.x).max(1e-6); + let d = (b.y - a.y) / h; + let (mut m0, mut m1) = (slope(i), slope(i + 1)); + if d == 0.0 { + m0 = 0.0; + m1 = 0.0; + } else { + // Keep the segment monotone. + if m0 * d < 0.0 { + m0 = 0.0; + } + if m1 * d < 0.0 { + m1 = 0.0; + } + let (al, be) = (m0 / d, m1 / d); + let s = al * al + be * be; + if s > 9.0 { + let t = 3.0 / s.sqrt(); + m0 = t * al * d; + m1 = t * be * d; + } + } + let t = (x - a.x) / h; + let (t2, t3) = (t * t, t * t * t); + (2.0 * t3 - 3.0 * t2 + 1.0) * a.y + (t3 - 2.0 * t2 + t) * h * m0 + (-2.0 * t3 + 3.0 * t2) * b.y + (t3 - t2) * h * m1 + } +} + +/// One stop of a [`Gradient`]: position 0..1 and linear RGBA. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct GradientKey { + pub pos: f32, + pub color: [f32; 4], +} + +/// A color ramp (gradient map). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Gradient { + pub keys: Vec, +} + +impl Default for Gradient { + fn default() -> Self { + Gradient { keys: vec![GradientKey { pos: 0.0, color: [0.0, 0.0, 0.0, 1.0] }, GradientKey { pos: 1.0, color: [1.0, 1.0, 1.0, 1.0] }] } + } +} + +impl Gradient { + /// Linear interpolation between the sorted keys. + pub fn eval(&self, t: f32) -> [f32; 4] { + let k = &self.keys; + let Some(first) = k.first() else { return [t, t, t, 1.0] }; + if t <= first.pos { + return first.color; + } + for w in k.windows(2) { + if t <= w[1].pos { + let span = (w[1].pos - w[0].pos).max(1e-6); + let f = ((t - w[0].pos) / span).clamp(0.0, 1.0); + let (a, b) = (w[0].color, w[1].color); + return [a[0] + (b[0] - a[0]) * f, a[1] + (b[1] - a[1]) * f, a[2] + (b[2] - a[2]) * f, a[3] + (b[3] - a[3]) * f]; + } + } + k.last().map_or([t, t, t, 1.0], |l| l.color) + } + + /// Keys sorted by position (call after editing). + pub fn sort(&mut self) { + self.keys.sort_by(|a, b| a.pos.total_cmp(&b.pos)); + } +} + +/// A typed parameter value. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "t", content = "v", rename_all = "camelCase")] +pub enum Value { + Float(f32), + Float2([f32; 2]), + Float3([f32; 3]), + Float4([f32; 4]), + Int(i32), + Int2([i32; 2]), + Bool(bool), + /// Linear RGBA, 0..1. + Color([f32; 4]), + /// Index into the parameter's options. + Enum(u32), + Text(String), + Curve(Curve), + Gradient(Gradient), + /// A function graph (pixel/value processors, dynamic parameters). + Function(Box), +} + +impl Value { + pub fn as_f32(&self) -> Option { + match self { + Value::Float(v) => Some(*v), + Value::Int(v) => Some(*v as f32), + Value::Enum(v) => Some(*v as f32), + Value::Bool(b) => Some(if *b { 1.0 } else { 0.0 }), + Value::Float2(v) => Some(v[0]), + Value::Float3(v) => Some(v[0]), + Value::Float4(v) | Value::Color(v) => Some(v[0]), + _ => None, + } + } + + pub fn as_i32(&self) -> Option { + match self { + Value::Int(v) => Some(*v), + Value::Enum(v) => i32::try_from(*v).ok(), + Value::Float(v) if v.is_finite() => Some(v.round() as i32), + Value::Bool(b) => Some(i32::from(*b)), + Value::Int2(v) => Some(v[0]), + _ => None, + } + } + + pub fn as_bool(&self) -> Option { + match self { + Value::Bool(b) => Some(*b), + Value::Int(v) => Some(*v != 0), + Value::Float(v) => Some(*v != 0.0), + _ => None, + } + } + + /// Up to four floats (missing ones are 0; a color keeps its alpha). + pub fn as_vec4(&self) -> Option<[f32; 4]> { + match self { + Value::Float(v) => Some([*v, *v, *v, 1.0]), + Value::Float2(v) => Some([v[0], v[1], 0.0, 0.0]), + Value::Float3(v) => Some([v[0], v[1], v[2], 0.0]), + Value::Float4(v) | Value::Color(v) => Some(*v), + Value::Int(v) => Some([*v as f32; 4]), + Value::Int2(v) => Some([v[0] as f32, v[1] as f32, 0.0, 0.0]), + _ => None, + } + } + + /// Short type name, for errors and inspect output. + pub fn type_name(&self) -> &'static str { + match self { + Value::Float(_) => "float", + Value::Float2(_) => "float2", + Value::Float3(_) => "float3", + Value::Float4(_) => "float4", + Value::Int(_) => "int", + Value::Int2(_) => "int2", + Value::Bool(_) => "bool", + Value::Color(_) => "color", + Value::Enum(_) => "enum", + Value::Text(_) => "text", + Value::Curve(_) => "curve", + Value::Gradient(_) => "gradient", + Value::Function(_) => "function", + } + } + + /// Coerce a JSON value (from a command or MCP call) into the type of `self`. + pub fn coerce_json(&self, j: &serde_json::Value) -> Option { + use serde_json::Value as J; + let f = |v: &J| v.as_f64().map(|x| x as f32).filter(|x| x.is_finite()); + let arr = |n: usize| -> Option> { + match j { + J::Array(a) if a.len() >= n => a.iter().take(n).map(f).collect(), + J::Number(_) => f(j).map(|v| vec![v; n]), + _ => None, + } + }; + // A typed value as the API writes it ({"t": .., "v": ..}). + if let Ok(v) = serde_json::from_value::(j.clone()) + && v.type_name() == self.type_name() + { + return Some(v); + } + Some(match self { + Value::Float(_) => Value::Float(f(j)?), + Value::Float2(_) => { + let a = arr(2)?; + Value::Float2([a[0], a[1]]) + } + Value::Float3(_) => { + let a = arr(3)?; + Value::Float3([a[0], a[1], a[2]]) + } + Value::Float4(_) => { + let a = arr(4)?; + Value::Float4([a[0], a[1], a[2], a[3]]) + } + Value::Color(_) => Value::Color(parse_color(j)?), + Value::Int(_) => Value::Int(f(j)?.round() as i32), + Value::Int2(_) => { + let a = arr(2)?; + Value::Int2([a[0].round() as i32, a[1].round() as i32]) + } + Value::Bool(_) => Value::Bool(j.as_bool().or_else(|| f(j).map(|v| v != 0.0))?), + Value::Enum(_) => Value::Enum(u32::try_from(j.as_u64()?).ok()?), + Value::Text(_) => Value::Text(j.as_str()?.to_string()), + Value::Curve(_) => { + let pts: Vec<[f32; 2]> = serde_json::from_value(j.clone()).ok()?; + let mut points: Vec = + pts.into_iter().filter(|p| p[0].is_finite() && p[1].is_finite()).map(|p| CurvePoint { x: p[0], y: p[1] }).collect(); + points.sort_by(|a, b| a.x.total_cmp(&b.x)); + Value::Curve(Curve { points }) + } + Value::Gradient(_) => { + let keys: Vec<(f32, serde_json::Value)> = serde_json::from_value(j.clone()).ok()?; + let mut g = Gradient { keys: keys.iter().filter_map(|(p, c)| Some(GradientKey { pos: *p, color: parse_color(c)? })).collect() }; + g.sort(); + Value::Gradient(g) + } + Value::Function(_) => return None, + }) + } +} + +/// `[r, g, b(, a)]` linear floats, a single gray number, or `"#rrggbb(aa)"` (sRGB, converted to linear). +pub fn parse_color(j: &serde_json::Value) -> Option<[f32; 4]> { + use serde_json::Value as J; + match j { + J::Array(a) if a.len() >= 3 => { + let v: Vec = a.iter().take(4).filter_map(|x| x.as_f64().map(|x| x as f32)).filter(|x| x.is_finite()).collect(); + if v.len() < 3 { + return None; + } + Some([v[0], v[1], v[2], v.get(3).copied().unwrap_or(1.0)]) + } + J::Number(n) => n.as_f64().map(|v| v as f32).filter(|v| v.is_finite()).map(|v| [v, v, v, 1.0]), + J::String(s) => { + let s = s.trim_start_matches('#'); + if s.len() != 6 && s.len() != 8 { + return None; + } + let c = |i: usize| u8::from_str_radix(s.get(i..i + 2)?, 16).ok().map(|v| v as f32 / 255.0); + let a = if s.len() == 8 { c(6)? } else { 1.0 }; + Some([srgb_to_linear(c(0)?), srgb_to_linear(c(2)?), srgb_to_linear(c(4)?), a]) + } + _ => None, + } +} + +/// sRGB transfer function, encoded → linear. +pub fn srgb_to_linear(v: f32) -> f32 { + if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) } +} + +/// sRGB transfer function, linear → encoded. +pub fn linear_to_srgb(v: f32) -> f32 { + if v <= 0.003_130_8 { v * 12.92 } else { 1.055 * v.max(0.0).powf(1.0 / 2.4) - 0.055 } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn curve_identity_and_monotone() { + let c = Curve::default(); + for i in 0..=10 { + let x = i as f32 / 10.0; + assert!((c.eval(x) - x).abs() < 1e-4); + } + let s = + Curve { points: vec![CurvePoint { x: 0.0, y: 0.0 }, CurvePoint { x: 0.3, y: 0.1 }, CurvePoint { x: 0.7, y: 0.9 }, CurvePoint { x: 1.0, y: 1.0 }] }; + let mut last = -1.0; + for i in 0..=100 { + let v = s.eval(i as f32 / 100.0); + assert!(v >= last - 1e-5); + last = v; + } + } + + #[test] + fn coerce_from_json() { + assert_eq!(Value::Float(0.0).coerce_json(&serde_json::json!(0.5)), Some(Value::Float(0.5))); + assert_eq!(Value::Color([0.0; 4]).coerce_json(&serde_json::json!("#ffffff")), Some(Value::Color([1.0, 1.0, 1.0, 1.0]))); + assert_eq!(Value::Float2([0.0; 2]).coerce_json(&serde_json::json!([1, 2])), Some(Value::Float2([1.0, 2.0]))); + assert_eq!(Value::Float(0.0).coerce_json(&serde_json::json!("x")), None); + assert_eq!(Value::Float(0.0).coerce_json(&serde_json::json!(f64::MAX)), None); + } + + #[test] + fn gradient_interpolates() { + let g = Gradient::default(); + assert_eq!(g.eval(0.5), [0.5, 0.5, 0.5, 1.0]); + assert_eq!(Gradient { keys: vec![] }.eval(0.25)[0], 0.25); + } +} diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml new file mode 100644 index 00000000..8b57345d --- /dev/null +++ b/crates/engine/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "materialcraft-engine" +description = "MaterialCraft session, command registry, inspection and sample materials" +version.workspace = true +edition.workspace = true +license.workspace = true + +[lints] +workspace = true + +[dependencies] +materialcraft-core = { workspace = true } +materialcraft-image = { workspace = true } +materialcraft-nodes = { workspace = true } +materialcraft-eval = { workspace = true } +materialcraft-formats = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } +thiserror = { workspace = true } diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs new file mode 100644 index 00000000..a9acc401 --- /dev/null +++ b/crates/engine/src/commands.rs @@ -0,0 +1,141 @@ +//! The command registry. Every user-visible action is a command with a stable id; the menus, +//! shortcuts, CLI, control channel and MCP server all dispatch them by id. + +use serde_json::{Value as J, json}; + +use materialcraft_core::NodeId; + +use crate::{EngineError, Result, Session}; + +pub type Run = fn(&mut Session, &J) -> Result; +pub type Enabled = fn(&Session) -> std::result::Result<(), String>; + +pub struct CommandSpec { + pub id: &'static str, + pub label: &'static str, + /// Menu placement, e.g. `["Edit"]`. Empty = not in menus. + pub menu: &'static [&'static str], + /// Default shortcut in egui notation (`Ctrl+Shift+E`). + pub shortcut: Option<&'static str>, + /// Parameters, for humans and agents. + pub params: &'static str, + pub enabled: Enabled, + pub run: Run, +} + +pub(crate) fn always(_: &Session) -> std::result::Result<(), String> { + Ok(()) +} + +pub(crate) fn has_graph(s: &Session) -> std::result::Result<(), String> { + s.graph().map(|_| ()).map_err(|_| "no graph is open".into()) +} + +pub(crate) fn has_selection(s: &Session) -> std::result::Result<(), String> { + has_graph(s)?; + if s.selection.is_empty() { Err("no node is selected".into()) } else { Ok(()) } +} + +#[macro_export] +#[doc(hidden)] +macro_rules! cmd { + ($id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $en:expr, $run:expr) => { + $crate::commands::CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run } + }; +} + +pub fn command_specs() -> &'static [CommandSpec] { + static SPECS: std::sync::OnceLock> = std::sync::OnceLock::new(); + SPECS.get_or_init(|| { + let mut v = Vec::new(); + v.extend(crate::file_cmds::specs()); + v.extend(crate::edit_cmds::specs()); + v.extend(crate::graph_cmds::specs()); + v.extend(crate::node_cmds::specs()); + v.extend(crate::view_cmds::specs()); + v + }) +} + +pub fn find(id: &str) -> Option<&'static CommandSpec> { + command_specs().iter().find(|c| c.id == id) +} + +/// Run a command by id with JSON params (empty params = defaults, never a dialog). +pub fn execute(s: &mut Session, id: &str, params: &J) -> Result { + let spec = find(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?; + (spec.enabled)(s).map_err(|why| EngineError::Disabled { cmd: id.to_string(), why })?; + (spec.run)(s, params) +} + +/// Every command, as JSON (for `commands` listings and MCP). +pub fn list(s: &Session, filter: Option<&str>) -> J { + let f = filter.map(str::to_ascii_lowercase); + J::Array( + command_specs() + .iter() + .filter(|c| f.as_ref().is_none_or(|f| c.id.to_ascii_lowercase().contains(f) || c.label.to_ascii_lowercase().contains(f))) + .map(|c| json!({"id": c.id, "label": c.label, "menu": c.menu, "shortcut": c.shortcut, "params": c.params, "enabled": (c.enabled)(s).is_ok()})) + .collect(), + ) +} + +// ---------- param helpers ---------- + +pub(crate) fn bad(cmd: &str, msg: impl Into) -> EngineError { + EngineError::BadParams { cmd: cmd.into(), msg: msg.into() } +} + +pub(crate) fn f32p(p: &J, key: &str) -> Option { + p.get(key).and_then(J::as_f64).map(|v| v as f32).filter(|v| v.is_finite()) +} + +pub(crate) fn u64p(p: &J, key: &str) -> Option { + p.get(key).and_then(|v| v.as_u64().or_else(|| v.as_f64().filter(|f| f.is_finite() && *f >= 0.0).map(|f| f.round() as u64))) +} + +pub(crate) fn i64p(p: &J, key: &str) -> Option { + p.get(key).and_then(|v| v.as_i64().or_else(|| v.as_f64().filter(|f| f.is_finite()).map(|f| f.round() as i64))) +} + +pub(crate) fn boolp(p: &J, key: &str) -> Option { + p.get(key).and_then(J::as_bool) +} + +pub(crate) fn strp<'a>(p: &'a J, key: &str) -> Option<&'a str> { + p.get(key).and_then(J::as_str) +} + +/// A node id param (`key`), defaulting to the last selected node. +pub(crate) fn node_param(s: &Session, cmd: &str, p: &J, key: &str) -> Result { + let id = match u64p(p, key) { + Some(id) => NodeId(id), + None => *s.selection.last().ok_or_else(|| bad(cmd, format!("no node selected and no `{key}` given")))?, + }; + s.graph()?.node(id).map_err(|_| bad(cmd, format!("no node {}", id.0)))?; + Ok(id) +} + +/// A list of node ids (`ids`), defaulting to the selection. +pub(crate) fn ids_param(s: &Session, cmd: &str, p: &J) -> Result> { + let ids: Vec = match p.get("ids").and_then(J::as_array) { + Some(a) => a.iter().filter_map(J::as_u64).map(NodeId).collect(), + None => match u64p(p, "id") { + Some(id) => vec![NodeId(id)], + None => s.selection.clone(), + }, + }; + let g = s.graph()?; + for id in &ids { + g.node(*id).map_err(|_| bad(cmd, format!("no node {}", id.0)))?; + } + Ok(ids) +} + +/// A 2D point param (`[x, y]`). +pub(crate) fn point(p: &J, key: &str) -> Option<[f32; 2]> { + let a = p.get(key)?.as_array()?; + let x = a.first()?.as_f64()? as f32; + let y = a.get(1)?.as_f64()? as f32; + (x.is_finite() && y.is_finite()).then_some([x, y]) +} diff --git a/crates/engine/src/edit_cmds.rs b/crates/engine/src/edit_cmds.rs new file mode 100644 index 00000000..b0c06b9d --- /dev/null +++ b/crates/engine/src/edit_cmds.rs @@ -0,0 +1,175 @@ +//! Edit menu: undo/redo, clipboard, duplicate, delete and selection. + +use std::collections::BTreeMap; + +use serde_json::{Value as J, json}; + +use materialcraft_core::{Connection, NodeId}; + +use crate::commands::{CommandSpec, always, bad, has_graph, has_selection, ids_param, point}; +use crate::session::Clip; +use crate::{Result, Session, cmd}; + +fn can_undo(s: &Session) -> std::result::Result<(), String> { + if s.can_undo() { Ok(()) } else { Err("nothing to undo".into()) } +} + +fn can_redo(s: &Session) -> std::result::Result<(), String> { + if s.can_redo() { Ok(()) } else { Err("nothing to redo".into()) } +} + +pub(crate) fn specs() -> Vec { + vec![ + cmd!("edit.undo", "Undo", ["Edit"], Some("Ctrl+Z"), "{}", can_undo, |s, _| Ok(json!({"undone": s.undo()}))), + cmd!("edit.redo", "Redo", ["Edit"], Some("Ctrl+Y"), "{}", can_redo, |s, _| Ok(json!({"redone": s.redo()}))), + cmd!("edit.copy", "Copy selection", [], Some("Ctrl+C"), "{ids?} copies nodes (and the wires between them)", has_selection, copy), + cmd!("edit.cut", "Cut selection", [], Some("Ctrl+X"), "{ids?}", has_selection, cut), + cmd!("edit.paste", "Paste", [], Some("Ctrl+V"), "{at? [x, y], clip? (JSON from edit.copy)} pastes nodes, selected", has_clip_or_param, paste), + cmd!( + "edit.duplicate", + "Duplicate selection", + [], + Some("Ctrl+D"), + "{ids?} duplicates nodes with their inner wires and their inputs", + has_selection, + duplicate + ), + cmd!("edit.delete", "Delete selection", [], Some("Delete"), "{ids?}", has_selection, delete), + cmd!( + "edit.deleteRelink", + "Delete and relink", + [], + Some("Backspace"), + "{ids?} deletes nodes and joins what fed their first input to what they fed", + has_selection, + delete_relink + ), + cmd!("edit.selectAll", "Select all", [], Some("Ctrl+A"), "{}", has_graph, |s, _| { + s.selection = s.graph()?.nodes.iter().map(|n| n.id).collect(); + Ok(json!({"selected": s.selection.len()})) + }), + cmd!("edit.selectNone", "Deselect", [], None, "{}", always, |s, _| { + s.selection.clear(); + Ok(J::Null) + }), + ] +} + +fn has_clip_or_param(s: &Session) -> std::result::Result<(), String> { + // `clip` may come with the params; the check happens in `paste`. + has_graph(s) +} + +fn clip_of(s: &Session, ids: &[NodeId]) -> Result { + let g = s.graph()?; + Ok(Clip { + nodes: g.nodes.iter().filter(|n| ids.contains(&n.id)).cloned().collect(), + connections: g.connections.iter().filter(|c| ids.contains(&c.from) && ids.contains(&c.to)).cloned().collect(), + }) +} + +fn copy(s: &mut Session, p: &J) -> Result { + let ids = ids_param(s, "edit.copy", p)?; + let clip = clip_of(s, &ids)?; + let out = serde_json::to_value(&clip).unwrap_or(J::Null); + s.clipboard = Some(clip); + Ok(json!({"copied": ids.len(), "clip": out})) +} + +fn cut(s: &mut Session, p: &J) -> Result { + let r = copy(s, p)?; + delete(s, p)?; + Ok(r) +} + +/// Insert a clip's nodes with fresh ids, offset so their top-left lands at `at`; returns the +/// new ids. `keep_inputs`: also reconnect wires from outside nodes (duplicate). +fn insert_clip(s: &mut Session, clip: &Clip, at: Option<[f32; 2]>, offset: [f32; 2], outer: &[Connection]) -> Result> { + let g = s.graph_mut()?; + let min = clip.nodes.iter().fold([f32::MAX, f32::MAX], |m, n| [m[0].min(n.pos[0]), m[1].min(n.pos[1])]); + let shift = match at { + Some(a) if min[0] < f32::MAX => [a[0] - min[0], a[1] - min[1]], + _ => offset, + }; + let mut map: BTreeMap = BTreeMap::new(); + for n in &clip.nodes { + let id = NodeId(g.alloc_id()); + map.insert(n.id, id); + let mut c = n.clone(); + c.id = id; + c.pos = [n.pos[0] + shift[0], n.pos[1] + shift[1]]; + g.nodes.push(c); + } + for c in &clip.connections { + if let (Some(a), Some(b)) = (map.get(&c.from), map.get(&c.to)) { + let _ = g.connect(*a, &c.from_port, *b, &c.to_port); + } + } + for c in outer { + if let Some(b) = map.get(&c.to) + && g.node(c.from).is_ok() + { + let _ = g.connect(c.from, &c.from_port, *b, &c.to_port); + } + } + Ok(map.into_values().collect()) +} + +fn paste(s: &mut Session, p: &J) -> Result { + let clip = match p.get("clip") { + Some(c) => serde_json::from_value::(c.clone()).map_err(|e| bad("edit.paste", format!("bad clip: {e}")))?, + None => s.clipboard.clone().ok_or_else(|| bad("edit.paste", "the clipboard is empty"))?, + }; + if clip.nodes.len() > 10_000 { + return Err(bad("edit.paste", "too many nodes")); + } + let at = point(p, "at"); + s.edit("Paste", |s| { + let ids = insert_clip(s, &clip, at, [40.0, 40.0], &[])?; + s.selection = ids.clone(); + Ok(json!({"ids": ids.iter().map(|i| i.0).collect::>()})) + }) +} + +fn duplicate(s: &mut Session, p: &J) -> Result { + let ids = ids_param(s, "edit.duplicate", p)?; + let clip = clip_of(s, &ids)?; + let outer: Vec = s.graph()?.connections.iter().filter(|c| ids.contains(&c.to) && !ids.contains(&c.from)).cloned().collect(); + let keep = !matches!(p.get("withoutLinks"), Some(J::Bool(true))); + s.edit("Duplicate", |s| { + let new = insert_clip(s, &clip, None, [40.0, 40.0], if keep { &outer } else { &[] })?; + s.selection = new.clone(); + Ok(json!({"ids": new.iter().map(|i| i.0).collect::>()})) + }) +} + +fn delete(s: &mut Session, p: &J) -> Result { + let ids = ids_param(s, "edit.delete", p)?; + s.edit("Delete", |s| { + s.graph_mut()?.remove_nodes(&ids); + s.selection.retain(|i| !ids.contains(i)); + if s.view2d.node.is_some_and(|n| ids.contains(&n)) { + s.view2d.node = None; + } + Ok(json!({"deleted": ids.len()})) + }) +} + +fn delete_relink(s: &mut Session, p: &J) -> Result { + let ids = ids_param(s, "edit.deleteRelink", p)?; + s.edit("Delete and relink", |s| { + let g = s.graph_mut()?; + for id in &ids { + let src = g.connections.iter().find(|c| c.to == *id).map(|c| (c.from, c.from_port.clone())); + let outs: Vec<(NodeId, String)> = g.connections.iter().filter(|c| c.from == *id).map(|c| (c.to, c.to_port.clone())).collect(); + g.remove_nodes(&[*id]); + if let Some((from, port)) = src { + for (to, to_port) in outs { + let _ = g.connect(from, &port, to, &to_port); + } + } + } + s.selection.retain(|i| !ids.contains(i)); + Ok(json!({"deleted": ids.len()})) + }) +} diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs new file mode 100644 index 00000000..15058cc1 --- /dev/null +++ b/crates/engine/src/file_cmds.rs @@ -0,0 +1,234 @@ +//! File menu: new/open/save packages, new graphs from templates, bitmap resources and texture +//! export. Host-path commands are native only; the browser and agents use the byte-based +//! functions (`open_bytes`, `save_bytes`, `export_outputs`). + +use serde_json::{Value as J, json}; + +use materialcraft_core::{Package, Resource}; +use materialcraft_formats::{Depth, encode, output_name}; + +use crate::commands::{CommandSpec, always, bad, has_graph, strp, u64p}; +use crate::samples::{TEMPLATES, template}; +use crate::{Result, Session, cmd}; + +pub(crate) fn specs() -> Vec { + vec![ + cmd!( + "file.new", + "Graph...", + ["File", "New"], + Some("Ctrl+N"), + "{name?, template? (see graph.templates), size? (px, power of two)} adds a new graph to the package and opens it", + always, + new_graph + ), + cmd!("file.newPackage", "Empty package", ["File", "New"], None, "{name?} replaces the session with an empty package", always, new_package), + cmd!("file.open", "Open...", ["File"], Some("Ctrl+O"), "{path} opens a .mcraft package", always, open), + cmd!("file.save", "Save", ["File"], Some("Ctrl+S"), "{path?} saves the package (.mcraft) to its own file or `path`", always, save), + cmd!("file.saveAs", "Save as...", ["File"], Some("Ctrl+Shift+S"), "{path} saves the package under a new name", always, save), + cmd!( + "file.export", + "Export outputs...", + ["File"], + Some("Ctrl+Shift+E"), + "{dir, format? (png|jpg|tga|tif|bmp|webp|exr|hdr), pattern? ($(graph)_$(identifier)), depth? (8|16|32), graph?} cooks the graph at full size and writes every output", + has_graph, + export + ), + cmd!( + "file.importBitmap", + "Import bitmap...", + ["File"], + None, + "{path, name?} embeds an image file as a resource; returns its name", + always, + import_bitmap + ), + cmd!("graph.templates", "Graph templates", [], None, "{} lists the templates for file.new", always, |_, _| Ok(json!( + TEMPLATES.iter().map(|(id, l)| json!({"id": id, "label": l})).collect::>() + ))), + ] +} + +fn new_graph(s: &mut Session, p: &J) -> Result { + let tpl = strp(p, "template").unwrap_or("pbr"); + let label = TEMPLATES.iter().find(|t| t.0 == tpl).map_or("Graph", |t| t.1); + let size = u64p(p, "size").unwrap_or(1024).clamp(16, 8192); + let log2 = 63 - size.leading_zeros(); + let base = strp(p, "name").map(str::to_string).unwrap_or_else(|| label.replace(' ', "_")); + s.edit("New graph", |s| { + let name = s.pkg.unique_graph_name(&base); + s.pkg.graphs.push(template(tpl, &name, log2)); + s.graph = s.pkg.graphs.len() - 1; + s.selection.clear(); + s.view2d.node = None; + Ok(json!({"graph": s.graph, "name": name})) + }) +} + +fn new_package(s: &mut Session, p: &J) -> Result { + let mut pkg = Package::new(strp(p, "name").unwrap_or("Untitled package")); + pkg.graphs.push(template("pbr", "New_graph", 10)); + replace_package(s, pkg, None); + Ok(json!({"name": s.pkg.name})) +} + +/// Make `pkg` the session's document (after open/new): history and views reset. +pub fn replace_package(s: &mut Session, pkg: Package, path: Option) { + s.pkg = pkg; + s.path = path; + s.graph = 0; + s.selection.clear(); + s.view2d.node = None; + s.reset_history(); + s.modified = false; + s.dirty = true; +} + +/// Open package bytes (any platform). +pub fn open_bytes(s: &mut Session, bytes: &[u8], name: Option) -> Result<()> { + let pkg = materialcraft_formats::load_package(bytes)?; + replace_package(s, pkg, name); + Ok(()) +} + +/// The package as `.mcraft` bytes. +pub fn save_bytes(s: &Session) -> Result> { + Ok(materialcraft_formats::save_package(&s.pkg)?) +} + +#[cfg(not(target_arch = "wasm32"))] +fn open(s: &mut Session, p: &J) -> Result { + let path = strp(p, "path").ok_or_else(|| bad("file.open", "`path` is required"))?; + let bytes = std::fs::read(path).map_err(|e| bad("file.open", format!("{path}: {e}")))?; + open_bytes(s, &bytes, Some(path.to_string()))?; + s.log(format!("Opened {path}")); + Ok(json!({"name": s.pkg.name, "graphs": s.pkg.graphs.len()})) +} + +#[cfg(target_arch = "wasm32")] +fn open(_: &mut Session, _: &J) -> Result { + Err(bad("file.open", "the browser opens files with the file picker")) +} + +#[cfg(not(target_arch = "wasm32"))] +fn save(s: &mut Session, p: &J) -> Result { + let path = match strp(p, "path") { + Some(path) => { + let mut path = path.to_string(); + if !path.to_ascii_lowercase().ends_with(".mcraft") { + path.push_str(".mcraft"); + } + path + } + None => s.path.clone().ok_or_else(|| bad("file.save", "the package has no file yet: give a `path`"))?, + }; + let bytes = save_bytes(s)?; + materialcraft_formats::write_atomic(std::path::Path::new(&path), &bytes)?; + s.path = Some(path.clone()); + s.modified = false; + s.log(format!("Saved {path}")); + Ok(json!({"path": path, "bytes": bytes.len()})) +} + +#[cfg(target_arch = "wasm32")] +fn save(_: &mut Session, _: &J) -> Result { + Err(bad("file.save", "the browser saves with a download")) +} + +/// One exported file. +pub struct Exported { + pub file: String, + pub bytes: Vec, +} + +/// Cook graph `gi` at full size and encode every output (`pattern` names files). +pub fn export_outputs(s: &Session, gi: usize, ext: &str, pattern: &str, depth: Option) -> Result> { + let g = s.pkg.graph(gi)?; + let cooked = s.cook_full(gi); + let mut out = Vec::new(); + for (id, usage, ident, img) in materialcraft_eval::outputs(g, &cooked) { + let Some(img) = img else { continue }; + let node = g.node(id)?; + let depth = depth + .unwrap_or_else(|| Depth::from_format(if node.base.format == materialcraft_core::OutputFormat::Inherit { g.format } else { node.base.format })); + let srgb = matches!(usage, "baseColor" | "emissive" | "specular"); + let bytes = encode(img, ext, depth, srgb)?; + out.push(Exported { file: format!("{}.{}", output_name(pattern, &g.name, &ident, usage), ext.trim_start_matches('.')), bytes }); + } + if out.is_empty() { + return Err(bad("file.export", "the graph has no connected output nodes")); + } + Ok(out) +} + +/// Export params: (graph index, extension, pattern, depth). +pub fn export_params(s: &Session, p: &J) -> Result<(usize, String, String, Option)> { + let gi = u64p(p, "graph").map_or(s.graph, |g| g as usize); + s.pkg.graph(gi)?; + let ext = strp(p, "format").unwrap_or("png").trim_start_matches('.').to_ascii_lowercase(); + if !materialcraft_formats::EXPORT_FORMATS.iter().any(|(e, _)| *e == ext) { + return Err(bad("file.export", format!("unknown format `{ext}`"))); + } + let pattern = strp(p, "pattern").unwrap_or("$(graph)_$(identifier)").to_string(); + let depth = match u64p(p, "depth") { + None => None, + Some(8) => Some(Depth::U8), + Some(16) => Some(Depth::U16), + Some(32) => Some(Depth::F32), + Some(d) => return Err(bad("file.export", format!("depth must be 8, 16 or 32, not {d}"))), + }; + Ok((gi, ext, pattern, depth)) +} + +#[cfg(not(target_arch = "wasm32"))] +fn export(s: &mut Session, p: &J) -> Result { + let dir = strp(p, "dir").ok_or_else(|| bad("file.export", "`dir` is required"))?; + let (gi, ext, pattern, depth) = export_params(s, p)?; + let files = export_outputs(s, gi, &ext, &pattern, depth)?; + std::fs::create_dir_all(dir).map_err(|e| bad("file.export", format!("{dir}: {e}")))?; + let mut written = Vec::new(); + for f in files { + let path = std::path::Path::new(dir).join(&f.file); + materialcraft_formats::write_atomic(&path, &f.bytes)?; + written.push(path.display().to_string()); + } + s.log(format!("Exported {} files to {dir}", written.len())); + Ok(json!({"files": written})) +} + +#[cfg(target_arch = "wasm32")] +fn export(_: &mut Session, _: &J) -> Result { + Err(bad("file.export", "the browser exports with downloads")) +} + +/// Embed image bytes as a resource; returns the resource name. +pub fn add_resource(s: &mut Session, file: &str, bytes: Vec, name: Option<&str>) -> Result { + materialcraft_formats::decode(&bytes)?; + let file = materialcraft_formats::safe_file_name(file); + let stem = name.map(str::to_string).unwrap_or_else(|| file.rsplit_once('.').map_or(file.clone(), |(a, _)| a.to_string())); + s.edit("Import bitmap", |s| { + let mut name = stem.clone(); + let mut i = 1; + while s.pkg.resource(&name).is_some() { + name = format!("{stem}_{i}"); + i += 1; + } + s.pkg.resources.push(Resource { name: name.clone(), file: format!("{name}_{file}"), bytes: std::sync::Arc::new(bytes) }); + Ok(name) + }) +} + +#[cfg(not(target_arch = "wasm32"))] +fn import_bitmap(s: &mut Session, p: &J) -> Result { + let path = strp(p, "path").ok_or_else(|| bad("file.importBitmap", "`path` is required"))?; + let bytes = std::fs::read(path).map_err(|e| bad("file.importBitmap", format!("{path}: {e}")))?; + let file = std::path::Path::new(path).file_name().and_then(|f| f.to_str()).unwrap_or("bitmap.png").to_string(); + let name = add_resource(s, &file, bytes, strp(p, "name"))?; + Ok(json!({"name": name, "use": {"command": "graph.node.add", "params": {"def": "bitmap", "params": {"resource": name}}}})) +} + +#[cfg(target_arch = "wasm32")] +fn import_bitmap(_: &mut Session, _: &J) -> Result { + Err(bad("file.importBitmap", "the browser imports with the file picker")) +} diff --git a/crates/engine/src/graph_cmds.rs b/crates/engine/src/graph_cmds.rs new file mode 100644 index 00000000..825891b9 --- /dev/null +++ b/crates/engine/src/graph_cmds.rs @@ -0,0 +1,492 @@ +//! Graph commands: open/rename/delete graphs, size and seed, frames, comments, pins, exposed +//! inputs, selection, alignment and "create graph from selection". + +use serde_json::{Value as J, json}; + +use materialcraft_core::{Comment, ExposedParam, Frame, MAX_SIZE_LOG2, MIN_SIZE_LOG2, NodeId, OutputFormat, Pin, Value}; + +use crate::commands::{CommandSpec, always, bad, boolp, f32p, has_graph, has_selection, i64p, ids_param, point, strp, u64p}; +use crate::{Result, Session, cmd}; + +pub(crate) fn specs() -> Vec { + vec![ + cmd!("graph.open", "Open graph", [], None, "{graph: index or name}", always, open), + cmd!("graph.rename", "Rename graph", [], None, "{name, graph?}", has_graph, rename), + cmd!("graph.delete", "Delete graph", [], None, "{graph?}", has_graph, delete), + cmd!("graph.duplicate", "Duplicate graph", [], None, "{graph?}", has_graph, duplicate), + cmd!("graph.size", "Graph size", [], None, "{width, height} in pixels (powers of two, 16..8192) or {log2: [w, h]}", has_graph, size), + cmd!("graph.seed", "Random seed", [], None, "{seed}", has_graph, |s, p| { + let seed = i64p(p, "seed").ok_or_else(|| bad("graph.seed", "`seed` is required"))?.clamp(0, i32::MAX as i64) as i32; + s.edit_merged("graph.seed", "Random seed", |s| { + s.graph_mut()?.seed = seed; + Ok(J::Null) + }) + }), + cmd!("graph.format", "Output format", [], None, "{format: u8|u16|f16|f32}", has_graph, format), + cmd!("graph.cook", "Compute graph", [], None, "{full?: bool} cooks now; returns per-node timings and errors", has_graph, cook), + cmd!("graph.attributes", "Graph attributes", [], None, "{category?, description?, author?, tags?}", has_graph, attributes), + cmd!( + "graph.frame.add", + "Add Frame", + [], + None, + "{title?, rect? [x, y, w, h], color? [r,g,b,a]} around the selection when no rect", + has_graph, + frame_add + ), + cmd!("graph.frame.edit", "Edit frame", [], None, "{id, title?, description?, rect?, color?}", has_graph, frame_edit), + cmd!("graph.frame.delete", "Delete frame", [], None, "{id}", has_graph, frame_delete), + cmd!("graph.comment.add", "Add Comment", [], None, "{text?, at? [x, y]}", has_graph, comment_add), + cmd!("graph.comment.edit", "Edit comment", [], None, "{id, text?, at?, size?}", has_graph, comment_edit), + cmd!("graph.comment.delete", "Delete comment", [], None, "{id}", has_graph, comment_delete), + cmd!("graph.pin.add", "Add Navigation pin", [], None, "{name?, at? [x, y]}", has_graph, pin_add), + cmd!("graph.pin.delete", "Delete pin", [], None, "{id}", has_graph, pin_delete), + cmd!( + "graph.exposed.add", + "Expose parameter", + [], + None, + "{id, label?, default (a typed value or number), min?, max?, group?, bind?: {node, param}}", + has_graph, + exposed_add + ), + cmd!("graph.exposed.set", "Set input value", [], None, "{id, value}", has_graph, exposed_set), + cmd!("graph.exposed.delete", "Delete input", [], None, "{id}", has_graph, exposed_delete), + cmd!("graph.select", "Select nodes", [], None, "{ids, add?: bool}", has_graph, select), + cmd!("graph.selectUpstream", "Select upstream nodes", [], None, "{ids?}", has_selection, |s, p| select_stream(s, p, true)), + cmd!("graph.selectDownstream", "Select downstream nodes", [], None, "{ids?}", has_selection, |s, p| select_stream(s, p, false)), + cmd!("graph.align", "Align nodes", [], None, "{mode: left|right|top|bottom|hcenter|vcenter|hdistribute|vdistribute, ids?}", has_selection, align), + cmd!( + "graph.createFromSelection", + "Create graph from selection", + [], + None, + "{name?, ids?} moves the nodes into a new graph and replaces them with an instance", + has_selection, + from_selection + ), + ] +} + +fn graph_index(s: &Session, p: &J) -> Result { + match p.get("graph") { + None | Some(J::Null) => Ok(s.graph), + Some(J::String(name)) => s.pkg.graph_by_name(name).map(|(i, _)| i).ok_or_else(|| bad("graph", format!("no graph `{name}`"))), + Some(v) => { + let i = v.as_u64().ok_or_else(|| bad("graph", "`graph` is an index or a name"))? as usize; + s.pkg.graph(i)?; + Ok(i) + } + } +} + +fn open(s: &mut Session, p: &J) -> Result { + let i = graph_index(s, p)?; + s.graph = i; + s.selection.clear(); + s.view2d.node = None; + s.dirty = true; + Ok(json!({"graph": i, "name": s.pkg.graphs.get(i).map(|g| g.name.clone())})) +} + +fn rename(s: &mut Session, p: &J) -> Result { + let i = graph_index(s, p)?; + let name = strp(p, "name").map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad("graph.rename", "`name` is required"))?.to_string(); + if s.pkg.graphs.iter().enumerate().any(|(j, g)| j != i && g.name == name) { + return Err(bad("graph.rename", format!("a graph is already called `{name}`"))); + } + s.edit("Rename graph", |s| { + let old = std::mem::replace(&mut s.pkg.graph_mut(i)?.name, name.clone()); + // Instances follow the rename. + for g in &mut s.pkg.graphs { + for n in g.nodes.iter_mut().filter(|n| n.def == "graph_instance") { + if n.params.get("graph") == Some(&Value::Text(old.clone())) { + n.params.insert("graph".into(), Value::Text(name.clone())); + } + } + } + Ok(json!({"name": name})) + }) +} + +fn delete(s: &mut Session, p: &J) -> Result { + let i = graph_index(s, p)?; + s.edit("Delete graph", |s| { + s.pkg.graphs.remove(i); + s.graph = s.graph.min(s.pkg.graphs.len().saturating_sub(1)); + s.selection.clear(); + s.view2d.node = None; + Ok(json!({"graphs": s.pkg.graphs.len()})) + }) +} + +fn duplicate(s: &mut Session, p: &J) -> Result { + let i = graph_index(s, p)?; + s.edit("Duplicate graph", |s| { + let mut g = s.pkg.graph(i)?.clone(); + g.name = s.pkg.unique_graph_name(&g.name); + s.pkg.graphs.push(g); + s.graph = s.pkg.graphs.len() - 1; + s.selection.clear(); + Ok(json!({"graph": s.graph})) + }) +} + +fn size(s: &mut Session, p: &J) -> Result { + let log = |px: u64| 63 - px.clamp(1, 1 << 20).leading_zeros(); + let (w, h) = if let Some(a) = p.get("log2").and_then(J::as_array) { + (a.first().and_then(J::as_u64).unwrap_or(10) as u32, a.get(1).and_then(J::as_u64).unwrap_or(10) as u32) + } else { + let w = u64p(p, "width").ok_or_else(|| bad("graph.size", "`width` is required"))?; + (log(w), log(u64p(p, "height").unwrap_or(w))) + }; + let (w, h) = (w.clamp(MIN_SIZE_LOG2, MAX_SIZE_LOG2), h.clamp(MIN_SIZE_LOG2, MAX_SIZE_LOG2)); + s.edit("Graph size", |s| { + s.graph_mut()?.size = [w, h]; + Ok(json!({"width": 1u32 << w, "height": 1u32 << h})) + }) +} + +fn format(s: &mut Session, p: &J) -> Result { + let f = match strp(p, "format") { + Some("u8" | "8") => OutputFormat::U8, + Some("u16" | "16") => OutputFormat::U16, + Some("f16") => OutputFormat::F16, + Some("f32" | "32") => OutputFormat::F32, + _ => return Err(bad("graph.format", "`format` is u8, u16, f16 or f32")), + }; + s.edit("Output format", |s| { + s.graph_mut()?.format = f; + Ok(J::Null) + }) +} + +fn cook(s: &mut Session, p: &J) -> Result { + let cooked = if boolp(p, "full") == Some(true) { s.cook_full(s.graph) } else { s.cook().clone() }; + let g = s.graph()?; + Ok(json!({ + "ms": cooked.ms, + "nodes": cooked.nodes.iter().map(|(id, r)| { + let n = g.node(*id).ok(); + json!({"id": id.0, "def": n.map(|n| n.def.clone()), "ms": r.ms, "cached": r.cached, "error": r.error, + "size": r.outputs.first().map(|i| [i.w, i.h])}) + }).collect::>(), + })) +} + +fn attributes(s: &mut Session, p: &J) -> Result { + s.edit("Graph attributes", |s| { + let a = &mut s.graph_mut()?.attributes; + for (k, slot) in [("category", &mut a.category), ("description", &mut a.description), ("author", &mut a.author), ("tags", &mut a.tags)] { + if let Some(v) = strp(p, k) { + *slot = v.into(); + } + } + Ok(J::Null) + }) +} + +fn rect_of(p: &J) -> Option<[f32; 4]> { + let a = p.get("rect")?.as_array()?; + let v: Vec = a.iter().filter_map(J::as_f64).map(|v| v as f32).filter(|v| v.is_finite()).collect(); + (v.len() == 4).then(|| [v[0], v[1], v[2].max(10.0), v[3].max(10.0)]) +} + +fn color_of(p: &J) -> Option<[f32; 4]> { + materialcraft_core::parse_color(p.get("color")?) +} + +/// Graph-space bounding rect of nodes `ids` (node cards are about 96×110). +pub fn nodes_rect(s: &Session, ids: &[NodeId]) -> Option<[f32; 4]> { + let g = s.graph().ok()?; + let mut r = [f32::MAX, f32::MAX, f32::MIN, f32::MIN]; + for n in g.nodes.iter().filter(|n| ids.contains(&n.id)) { + r = [r[0].min(n.pos[0]), r[1].min(n.pos[1]), r[2].max(n.pos[0] + 96.0), r[3].max(n.pos[1] + 110.0)]; + } + (r[0] < f32::MAX).then(|| [r[0], r[1], r[2] - r[0], r[3] - r[1]]) +} + +fn frame_add(s: &mut Session, p: &J) -> Result { + let rect = match rect_of(p) { + Some(r) => r, + None => nodes_rect(s, &s.selection.clone()).map(|r| [r[0] - 24.0, r[1] - 44.0, r[2] + 48.0, r[3] + 68.0]).unwrap_or([0.0, 0.0, 400.0, 260.0]), + }; + let title = strp(p, "title").unwrap_or("Frame").to_string(); + let color = color_of(p).unwrap_or([0.55, 0.38, 0.12, 0.35]); + s.edit("Add frame", |s| { + let g = s.graph_mut()?; + let id = g.alloc_id(); + g.frames.push(Frame { id, title, description: String::new(), rect, color }); + Ok(json!({"id": id})) + }) +} + +fn frame_edit(s: &mut Session, p: &J) -> Result { + let id = u64p(p, "id").ok_or_else(|| bad("graph.frame.edit", "`id` is required"))?; + s.edit_merged(&format!("frame{id}"), "Edit frame", |s| { + let f = s.graph_mut()?.frames.iter_mut().find(|f| f.id == id).ok_or_else(|| bad("graph.frame.edit", format!("no frame {id}")))?; + if let Some(t) = strp(p, "title") { + f.title = t.into(); + } + if let Some(t) = strp(p, "description") { + f.description = t.into(); + } + if let Some(r) = rect_of(p) { + f.rect = r; + } + if let Some(c) = color_of(p) { + f.color = c; + } + Ok(J::Null) + }) +} + +fn frame_delete(s: &mut Session, p: &J) -> Result { + let id = u64p(p, "id").ok_or_else(|| bad("graph.frame.delete", "`id` is required"))?; + s.edit("Delete frame", |s| { + let g = s.graph_mut()?; + let n = g.frames.len(); + g.frames.retain(|f| f.id != id); + if n == g.frames.len() { + return Err(bad("graph.frame.delete", format!("no frame {id}"))); + } + Ok(J::Null) + }) +} + +fn comment_add(s: &mut Session, p: &J) -> Result { + let at = point(p, "at").or_else(|| nodes_rect(s, &s.selection.clone()).map(|r| [r[0], r[1] - 90.0])).unwrap_or([0.0, -120.0]); + let text = strp(p, "text").unwrap_or("Comment").to_string(); + s.edit("Add comment", |s| { + let g = s.graph_mut()?; + let id = g.alloc_id(); + g.comments.push(Comment { id, text, pos: at, size: [180.0, 70.0] }); + Ok(json!({"id": id})) + }) +} + +fn comment_edit(s: &mut Session, p: &J) -> Result { + let id = u64p(p, "id").ok_or_else(|| bad("graph.comment.edit", "`id` is required"))?; + s.edit_merged(&format!("comment{id}"), "Edit comment", |s| { + let c = s.graph_mut()?.comments.iter_mut().find(|c| c.id == id).ok_or_else(|| bad("graph.comment.edit", format!("no comment {id}")))?; + if let Some(t) = strp(p, "text") { + c.text = t.into(); + } + if let Some(a) = point(p, "at") { + c.pos = a; + } + if let Some(sz) = point(p, "size") { + c.size = [sz[0].max(40.0), sz[1].max(24.0)]; + } + Ok(J::Null) + }) +} + +fn comment_delete(s: &mut Session, p: &J) -> Result { + let id = u64p(p, "id").ok_or_else(|| bad("graph.comment.delete", "`id` is required"))?; + s.edit("Delete comment", |s| { + s.graph_mut()?.comments.retain(|c| c.id != id); + Ok(J::Null) + }) +} + +fn pin_add(s: &mut Session, p: &J) -> Result { + let at = point(p, "at").unwrap_or([0.0, 0.0]); + s.edit("Add pin", |s| { + let g = s.graph_mut()?; + let id = g.alloc_id(); + let name = strp(p, "name").map(str::to_string).unwrap_or_else(|| format!("Pin {}", g.pins.len() + 1)); + g.pins.push(Pin { id, name, pos: at }); + Ok(json!({"id": id})) + }) +} + +fn pin_delete(s: &mut Session, p: &J) -> Result { + let id = u64p(p, "id").ok_or_else(|| bad("graph.pin.delete", "`id` is required"))?; + s.edit("Delete pin", |s| { + s.graph_mut()?.pins.retain(|c| c.id != id); + Ok(J::Null) + }) +} + +fn exposed_add(s: &mut Session, p: &J) -> Result { + let id = strp(p, "id").map(str::trim).filter(|i| !i.is_empty()).ok_or_else(|| bad("graph.exposed.add", "`id` is required"))?.to_string(); + if s.graph()?.exposed.iter().any(|e| e.id == id) { + return Err(bad("graph.exposed.add", format!("an input is already called `{id}`"))); + } + // From a bound node parameter: its value, range and options become the input's. + let bind = p.get("bind").and_then(|b| Some((NodeId(b.get("node")?.as_u64()?), b.get("param")?.as_str()?.to_string()))); + let mut default = Value::Float(0.5); + let (mut min, mut max, mut options) = (0.0f32, 1.0f32, Vec::new()); + if let Some((node, param)) = &bind { + let g = s.graph()?; + let n = g.node(*node).map_err(|_| bad("graph.exposed.add", format!("no node {}", node.0)))?; + let def = materialcraft_nodes::find(&n.def).ok_or_else(|| bad("graph.exposed.add", "unknown node type"))?; + let pd = def.param(param).ok_or_else(|| bad("graph.exposed.add", format!("`{}` has no parameter `{param}`", n.def)))?; + default = n.params.get(param.as_str()).cloned().unwrap_or_else(|| pd.default.clone()); + (min, max) = (pd.min, pd.max); + options = pd.options.iter().map(|o| o.to_string()).collect(); + } + if let Some(d) = p.get("default") { + default = + serde_json::from_value::(d.clone()).ok().or_else(|| default.coerce_json(d)).ok_or_else(|| bad("graph.exposed.add", "bad `default`"))?; + } + let ep = ExposedParam { + id: id.clone(), + label: strp(p, "label").unwrap_or(&id).to_string(), + group: strp(p, "group").unwrap_or("").to_string(), + default, + min: f32p(p, "min").unwrap_or(min), + max: f32p(p, "max").unwrap_or(max), + options, + }; + s.edit("Expose parameter", |s| { + let g = s.graph_mut()?; + g.exposed.push(ep); + if let Some((node, param)) = bind { + g.node_mut(node)?.bindings.insert(param, id.clone()); + } + Ok(json!({"id": id})) + }) +} + +fn exposed_set(s: &mut Session, p: &J) -> Result { + let id = strp(p, "id").ok_or_else(|| bad("graph.exposed.set", "`id` is required"))?.to_string(); + let v = p.get("value").ok_or_else(|| bad("graph.exposed.set", "`value` is required"))?; + let cur = s.graph()?.exposed.iter().find(|e| e.id == id).map(|e| e.default.clone()).ok_or_else(|| bad("graph.exposed.set", format!("no input `{id}`")))?; + let val = cur.coerce_json(v).ok_or_else(|| bad("graph.exposed.set", format!("`{id}` takes a {}", cur.type_name())))?; + s.edit_merged(&format!("exposed:{id}"), "Set input", |s| { + s.graph_mut()?.inputs.insert(id.clone(), val); + Ok(J::Null) + }) +} + +fn exposed_delete(s: &mut Session, p: &J) -> Result { + let id = strp(p, "id").ok_or_else(|| bad("graph.exposed.delete", "`id` is required"))?.to_string(); + s.edit("Delete input", |s| { + let g = s.graph_mut()?; + g.exposed.retain(|e| e.id != id); + g.inputs.remove(&id); + for n in &mut g.nodes { + n.bindings.retain(|_, v| *v != id); + } + Ok(J::Null) + }) +} + +fn select(s: &mut Session, p: &J) -> Result { + let ids = ids_param(s, "graph.select", p)?; + if boolp(p, "add") == Some(true) { + for id in ids { + if !s.selection.contains(&id) { + s.selection.push(id); + } + } + } else { + s.selection = ids; + } + Ok(json!({"selection": s.selection.iter().map(|i| i.0).collect::>()})) +} + +fn select_stream(s: &mut Session, p: &J, up: bool) -> Result { + let ids = ids_param(s, "graph.select", p)?; + let g = s.graph()?; + let mut sel = ids.clone(); + for id in ids { + for n in if up { g.upstream(id) } else { g.downstream(id) } { + if !sel.contains(&n) { + sel.push(n); + } + } + } + s.selection = sel; + Ok(json!({"selected": s.selection.len()})) +} + +fn align(s: &mut Session, p: &J) -> Result { + let ids = ids_param(s, "graph.align", p)?; + let mode = strp(p, "mode").unwrap_or("left").to_string(); + s.edit("Align nodes", |s| { + let g = s.graph_mut()?; + let mut nodes: Vec<&mut materialcraft_core::Node> = g.nodes.iter_mut().filter(|n| ids.contains(&n.id)).collect(); + if nodes.len() < 2 { + return Ok(J::Null); + } + let xs: Vec = nodes.iter().map(|n| n.pos[0]).collect(); + let ys: Vec = nodes.iter().map(|n| n.pos[1]).collect(); + let (minx, maxx) = (xs.iter().copied().fold(f32::MAX, f32::min), xs.iter().copied().fold(f32::MIN, f32::max)); + let (miny, maxy) = (ys.iter().copied().fold(f32::MAX, f32::min), ys.iter().copied().fold(f32::MIN, f32::max)); + match mode.as_str() { + "left" => nodes.iter_mut().for_each(|n| n.pos[0] = minx), + "right" => nodes.iter_mut().for_each(|n| n.pos[0] = maxx), + "top" => nodes.iter_mut().for_each(|n| n.pos[1] = miny), + "bottom" => nodes.iter_mut().for_each(|n| n.pos[1] = maxy), + "hcenter" => nodes.iter_mut().for_each(|n| n.pos[0] = (minx + maxx) * 0.5), + "vcenter" => nodes.iter_mut().for_each(|n| n.pos[1] = (miny + maxy) * 0.5), + "hdistribute" | "vdistribute" => { + let k = usize::from(mode == "vdistribute"); + nodes.sort_by(|a, b| a.pos[k].total_cmp(&b.pos[k])); + let (lo, hi) = if k == 0 { (minx, maxx) } else { (miny, maxy) }; + let step = (hi - lo) / (nodes.len() - 1) as f32; + for (i, n) in nodes.iter_mut().enumerate() { + n.pos[k] = lo + step * i as f32; + } + } + other => return Err(bad("graph.align", format!("unknown mode `{other}`"))), + } + Ok(J::Null) + }) +} + +fn from_selection(s: &mut Session, p: &J) -> Result { + let ids = ids_param(s, "graph.createFromSelection", p)?; + let base = strp(p, "name").unwrap_or("Sub_graph").to_string(); + s.edit("Create graph from selection", |s| { + let name = s.pkg.unique_graph_name(&base); + let src = s.graph()?.clone(); + let mut sub = materialcraft_core::Graph::new(&name); + sub.size = src.size; + sub.next_id = src.next_id; + sub.nodes = src.nodes.iter().filter(|n| ids.contains(&n.id)).cloned().collect(); + sub.connections = src.connections.iter().filter(|c| ids.contains(&c.from) && ids.contains(&c.to)).cloned().collect(); + let incoming: Vec<_> = src.connections.iter().filter(|c| ids.contains(&c.to) && !ids.contains(&c.from)).cloned().collect(); + let outgoing: Vec<_> = src.connections.iter().filter(|c| ids.contains(&c.from) && !ids.contains(&c.to)).cloned().collect(); + let rect = nodes_rect(s, &ids).unwrap_or([0.0; 4]); + // One graph input per incoming wire, one output per distinct outgoing port. + let mut inputs = Vec::new(); + for (k, c) in incoming.iter().enumerate() { + let ident = format!("input_{}", k + 1); + let id = sub.add_node("input_color", [rect[0] - 160.0, rect[1] + k as f32 * 120.0]); + sub.node_mut(id)?.params.insert("identifier".into(), Value::Text(ident.clone())); + sub.connect(id, "output", c.to, &c.to_port)?; + inputs.push((c.from, c.from_port.clone(), ident)); + } + let mut outputs: Vec<(NodeId, String, String)> = Vec::new(); + for c in &outgoing { + if outputs.iter().any(|(n, p, _)| *n == c.from && *p == c.from_port) { + continue; + } + let ident = format!("output_{}", outputs.len() + 1); + let id = sub.add_node("output", [rect[0] + rect[2] + 80.0, rect[1] + outputs.len() as f32 * 120.0]); + let usage = materialcraft_nodes::atomic::USAGE_IDS.len() as u32 - 1; + sub.node_mut(id)?.params.extend([("identifier".to_string(), Value::Text(ident.clone())), ("usage".to_string(), Value::Enum(usage))]); + sub.connect(c.from, &c.from_port, id, "input")?; + outputs.push((c.from, c.from_port.clone(), ident)); + } + s.pkg.graphs.push(sub); + let g = s.graph_mut()?; + g.remove_nodes(&ids); + let inst = g.add_node("graph_instance", [rect[0], rect[1]]); + g.node_mut(inst)?.params.insert("graph".into(), Value::Text(name.clone())); + for (from, port, ident) in inputs { + g.connect(from, &port, inst, &ident)?; + } + for c in outgoing { + if let Some((_, _, ident)) = outputs.iter().find(|(n, p, _)| *n == c.from && *p == c.from_port) { + g.connect(inst, ident, c.to, &c.to_port)?; + } + } + s.selection = vec![inst]; + Ok(json!({"graph": name, "instance": inst.0})) + }) +} diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs new file mode 100644 index 00000000..91555b3c --- /dev/null +++ b/crates/engine/src/inspect.rs @@ -0,0 +1,65 @@ +//! `session.inspect`: everything an agent needs to verify its work without a screenshot. + +use serde_json::{Value as J, json}; + +use crate::Session; + +pub fn session(s: &Session, graph: Option) -> J { + let gi = graph.unwrap_or(s.graph); + let g = s.pkg.graphs.get(gi); + let cooked = (gi == s.graph).then_some(&s.cooked); + let graph_json = g.map(|g| { + json!({ + "index": gi, + "name": g.name, + "size": g.size_px(), + "format": g.format, + "seed": g.seed, + "attributes": g.attributes, + "exposed": g.exposed, + "inputs": g.inputs, + "nodes": g.nodes.iter().map(|n| { + let r = cooked.and_then(|c| c.nodes.get(&n.id)); + let (ins, outs) = materialcraft_eval::ports(&s.pkg, n); + json!({ + "id": n.id.0, + "def": n.def, + "label": if n.label.is_empty() { materialcraft_nodes::find(&n.def).map_or(n.def.as_str(), |d| d.label).to_string() } else { n.label.clone() }, + "pos": n.pos, + "params": n.params, + "bindings": n.bindings, + "base": n.base, + "disabled": n.disabled, + "inputs": ins.iter().map(|p| &p.id).collect::>(), + "outputs": outs.iter().map(|p| &p.id).collect::>(), + "cooked": r.map(|r| json!({ + "error": r.error, "ms": r.ms, "cached": r.cached, + "size": r.outputs.first().map(|i| [i.w, i.h]), + "kind": r.outputs.first().map(|i| if i.is_gray() { "gray" } else { "color" }), + "mean": r.outputs.first().map(|i| i.mean()), + })), + }) + }).collect::>(), + "connections": g.connections, + "frames": g.frames, + "comments": g.comments, + "pins": g.pins, + }) + }); + json!({ + "package": {"name": s.pkg.name, "path": s.path, "modified": s.modified, "resources": s.pkg.resources.iter().map(|r| json!({"name": r.name, "bytes": r.bytes.len()})).collect::>()}, + "graphs": s.pkg.graphs.iter().enumerate().map(|(i, g)| json!({"index": i, "name": g.name, "nodes": g.nodes.len(), "kind": g.kind})).collect::>(), + "openGraph": s.graph, + "graph": graph_json, + "selection": s.selection.iter().map(|i| i.0).collect::>(), + "view2d": s.view2d, + "view3d": s.view3d, + "previewSize": s.preview_size, + "cookMs": s.cooked.ms, + "dirty": s.dirty, + "history": s.history(), + "canUndo": s.can_undo(), + "canRedo": s.can_redo(), + "log": s.log.iter().rev().take(20).collect::>(), + }) +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs new file mode 100644 index 00000000..88eb1ffd --- /dev/null +++ b/crates/engine/src/lib.rs @@ -0,0 +1,53 @@ +//! # materialcraft-engine +//! +//! The MaterialCraft session, L3: a [`Session`] owns the package, the graph being edited, the +//! selection, the 2D/3D view state, snapshot undo and the cook cache. Every user-visible action +//! is a command in the [`commands`] registry, dispatched by id from the UI, the CLI, the control +//! channel and the MCP server alike. +#![forbid(unsafe_code)] +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +pub mod commands; +pub mod edit_cmds; +pub mod file_cmds; +pub mod graph_cmds; +pub mod inspect; +pub mod node_cmds; +pub mod samples; +pub mod session; +pub mod view_cmds; + +pub use commands::{CommandSpec, command_specs, execute, find}; +pub use session::{Clip, Session, View2d, View3d}; + +pub use materialcraft_core as core; +pub use materialcraft_eval as eval; +pub use materialcraft_formats as formats; +pub use materialcraft_image as image; +pub use materialcraft_nodes as nodes; + +#[derive(Debug, thiserror::Error)] +pub enum EngineError { + #[error("unknown command `{0}`")] + UnknownCommand(String), + #[error("`{cmd}` is not available: {why}")] + Disabled { cmd: String, why: String }, + #[error("`{cmd}`: {msg}")] + BadParams { cmd: String, msg: String }, + #[error(transparent)] + Core(#[from] materialcraft_core::CoreError), + #[error(transparent)] + Format(#[from] materialcraft_formats::FormatError), + #[error("{0}")] + Other(String), +} + +pub type Result = std::result::Result; + +/// Version string shown in About, `--version` and window titles. +pub const VERSION: &str = env!("CARGO_PKG_VERSION"); + +/// A session on the built-in sample package (the brick wall). +pub fn sample_session() -> Session { + Session::new(samples::sample_package()) +} diff --git a/crates/engine/src/node_cmds.rs b/crates/engine/src/node_cmds.rs new file mode 100644 index 00000000..80c2ec83 --- /dev/null +++ b/crates/engine/src/node_cmds.rs @@ -0,0 +1,290 @@ +//! Node commands: add, move, rename, disable, parameters, base parameters, bindings, wires. + +use serde_json::{Value as J, json}; + +use materialcraft_core::{NodeId, OutputFormat, SizeMode, Value}; + +use crate::commands::{CommandSpec, bad, boolp, has_graph, has_selection, i64p, ids_param, node_param, point, strp, u64p}; +use crate::{Result, Session, cmd}; + +pub(crate) fn specs() -> Vec { + vec![ + cmd!( + "graph.node.add", + "Add node", + [], + None, + "{def (see library.list), at? [x, y], params? {id: value}, connectFrom? {node, port?} wires that output into the new node's first input, label?}", + has_graph, + add + ), + cmd!("graph.node.move", "Move nodes", [], None, "{ids?, by? [dx, dy], to? [x, y] (single node)}", has_selection, move_nodes), + cmd!("graph.node.rename", "Rename node", [], None, "{id?, label}", has_selection, rename), + cmd!("graph.node.disable", "Disable selection", [], Some("Shift+D"), "{ids?, disabled? (default: toggle)}", has_selection, disable), + cmd!( + "graph.node.param", + "Set parameter", + [], + None, + "{id?, param, value} (numbers, [x, y], \"#rrggbb\", enum index, typed {t, v})", + has_selection, + set_param + ), + cmd!("graph.node.reset", "Reset parameters", [], None, "{id?, param? (default: all)}", has_selection, reset), + cmd!( + "graph.node.base", + "Set base parameters", + [], + None, + "{id?, sizeMode? (relativeToInput|relativeToParent|absolute), size? [w, h] (log2 offset, or log2 size when absolute), format? (inherit|u8|u16|f16|f32), seed?, tiling? bool}", + has_selection, + base + ), + cmd!("graph.node.bind", "Bind parameter to input", [], None, "{id?, param, input (exposed id); input null unbinds}", has_selection, bind), + cmd!("graph.connect", "Connect", [], None, "{from, fromPort? (output), to, toPort? (first input)}", has_graph, connect), + cmd!("graph.disconnect", "Disconnect", [], None, "{to, toPort}", has_graph, disconnect), + ] +} + +fn add(s: &mut Session, p: &J) -> Result { + let def = strp(p, "def").ok_or_else(|| bad("graph.node.add", "`def` is required (see library.list)"))?.to_string(); + let catalog = materialcraft_nodes::find(&def); + if catalog.is_none() { + return Err(bad("graph.node.add", format!("unknown node `{def}`"))); + } + // Typed parameter values, checked against the catalog. + let mut params = Vec::new(); + if let Some(obj) = p.get("params").and_then(J::as_object) { + for (k, v) in obj { + let v = if def == "graph_instance" && k == "graph" { + Value::Text(v.as_str().ok_or_else(|| bad("graph.node.add", "`graph` is a graph name"))?.into()) + } else { + let pd = catalog.and_then(|d| d.param(k)).ok_or_else(|| bad("graph.node.add", format!("`{def}` has no parameter `{k}`")))?; + pd.default.coerce_json(v).ok_or_else(|| bad("graph.node.add", format!("`{k}` takes a {}", pd.default.type_name())))? + }; + params.push((k.clone(), v)); + } + } + let from = p.get("connectFrom").and_then(|c| Some((NodeId(c.get("node")?.as_u64()?), c.get("port").and_then(J::as_str).unwrap_or("output").to_string()))); + let at = point(p, "at").unwrap_or_else(|| { + let g = s.graph().ok(); + let src = from.as_ref().and_then(|(n, _)| g.and_then(|g| g.node(*n).ok())); + src.map_or([0.0, 0.0], |n| [n.pos[0] + 150.0, n.pos[1]]) + }); + let label = strp(p, "label").unwrap_or("").to_string(); + s.edit("Add node", |s| { + let g = s.graph_mut()?; + let id = g.add_node(&def, at); + let n = g.node_mut(id)?; + n.label = label; + n.params.extend(params); + if let Some((src, port)) = from { + let first = s.input_ports(id).into_iter().next().ok_or_else(|| bad("graph.node.add", format!("`{def}` has no inputs")))?; + s.graph_mut()?.connect(src, &port, id, &first)?; + } + s.selection = vec![id]; + Ok(json!({"id": id.0})) + }) +} + +fn move_nodes(s: &mut Session, p: &J) -> Result { + let ids = ids_param(s, "graph.node.move", p)?; + let by = point(p, "by"); + let to = point(p, "to"); + if by.is_none() && to.is_none() { + return Err(bad("graph.node.move", "`by` or `to` is required")); + } + s.edit("Move nodes", |s| { + let g = s.graph_mut()?; + for n in g.nodes.iter_mut().filter(|n| ids.contains(&n.id)) { + if let Some(t) = to { + n.pos = t; + } else if let Some(d) = by { + n.pos = [n.pos[0] + d[0], n.pos[1] + d[1]]; + } + } + Ok(J::Null) + }) +} + +fn rename(s: &mut Session, p: &J) -> Result { + let id = node_param(s, "graph.node.rename", p, "id")?; + let label = strp(p, "label").unwrap_or("").trim().to_string(); + s.edit("Rename node", |s| { + s.graph_mut()?.node_mut(id)?.label = label; + Ok(J::Null) + }) +} + +fn disable(s: &mut Session, p: &J) -> Result { + let ids = ids_param(s, "graph.node.disable", p)?; + let set = boolp(p, "disabled"); + s.edit("Disable nodes", |s| { + let g = s.graph_mut()?; + for n in g.nodes.iter_mut().filter(|n| ids.contains(&n.id)) { + n.disabled = set.unwrap_or(!n.disabled); + } + Ok(J::Null) + }) +} + +fn set_param(s: &mut Session, p: &J) -> Result { + let id = node_param(s, "graph.node.param", p, "id")?; + let param = strp(p, "param").ok_or_else(|| bad("graph.node.param", "`param` is required"))?.to_string(); + let v = p.get("value").ok_or_else(|| bad("graph.node.param", "`value` is required"))?; + let node = s.graph()?.node(id)?.clone(); + let value = if node.def == "graph_instance" { + // Instance parameters: the sub-graph's exposed inputs (and `graph`). + if param == "graph" { + Value::Text(v.as_str().ok_or_else(|| bad("graph.node.param", "`graph` is a graph name"))?.into()) + } else { + let sub = + materialcraft_eval::instance_graph(&s.pkg, &node).map(|(_, g)| g).ok_or_else(|| bad("graph.node.param", "the instanced graph is missing"))?; + let e = sub.exposed.iter().find(|e| e.id == param).ok_or_else(|| bad("graph.node.param", format!("the graph has no input `{param}`")))?; + e.default.coerce_json(v).ok_or_else(|| bad("graph.node.param", format!("`{param}` takes a {}", e.default.type_name())))? + } + } else { + let def = materialcraft_nodes::find(&node.def).ok_or_else(|| bad("graph.node.param", format!("unknown node `{}`", node.def)))?; + let pd = def.param(¶m).ok_or_else(|| bad("graph.node.param", format!("`{}` has no parameter `{param}`", node.def)))?; + let mut v = pd.default.coerce_json(v).ok_or_else(|| bad("graph.node.param", format!("`{param}` takes a {}", pd.default.type_name())))?; + if let Value::Enum(i) = &mut v + && !pd.options.is_empty() + { + *i = (*i).min(pd.options.len() as u32 - 1); + } + v + }; + s.edit_merged(&format!("param:{}:{param}", id.0), "Set parameter", |s| { + s.graph_mut()?.node_mut(id)?.params.insert(param.clone(), value); + Ok(J::Null) + }) +} + +fn reset(s: &mut Session, p: &J) -> Result { + let id = node_param(s, "graph.node.reset", p, "id")?; + let param = strp(p, "param").map(str::to_string); + s.edit("Reset parameters", |s| { + let n = s.graph_mut()?.node_mut(id)?; + match ¶m { + Some(k) => { + n.params.remove(k); + } + None => n.params.retain(|k, _| k == "graph" || k == "identifier"), + } + Ok(J::Null) + }) +} + +fn base(s: &mut Session, p: &J) -> Result { + let id = node_param(s, "graph.node.base", p, "id")?; + let mode = match strp(p, "sizeMode") { + None => None, + Some("relativeToInput") => Some(SizeMode::RelativeToInput), + Some("relativeToParent") => Some(SizeMode::RelativeToParent), + Some("absolute") => Some(SizeMode::Absolute), + Some(o) => return Err(bad("graph.node.base", format!("unknown sizeMode `{o}`"))), + }; + let format = match strp(p, "format") { + None => None, + Some("inherit") => Some(OutputFormat::Inherit), + Some("u8") => Some(OutputFormat::U8), + Some("u16") => Some(OutputFormat::U16), + Some("f16") => Some(OutputFormat::F16), + Some("f32") => Some(OutputFormat::F32), + Some(o) => return Err(bad("graph.node.base", format!("unknown format `{o}`"))), + }; + let size = p + .get("size") + .and_then(J::as_array) + .map(|a| [a.first().and_then(J::as_i64).unwrap_or(0).clamp(-12, 13) as i32, a.get(1).and_then(J::as_i64).unwrap_or(0).clamp(-12, 13) as i32]); + let seed = i64p(p, "seed").map(|v| v.clamp(0, i32::MAX as i64) as i32); + let tiling = boolp(p, "tiling"); + s.edit_merged(&format!("base:{}", id.0), "Set base parameters", |s| { + let b = &mut s.graph_mut()?.node_mut(id)?.base; + if let Some(m) = mode { + b.size_mode = m; + } + if let Some(sz) = size { + b.size = sz; + } + if let Some(f) = format { + b.format = f; + } + if let Some(sd) = seed { + b.seed = sd; + } + if let Some(t) = tiling { + b.tiling = [t, t]; + } + Ok(J::Null) + }) +} + +fn bind(s: &mut Session, p: &J) -> Result { + let id = node_param(s, "graph.node.bind", p, "id")?; + let param = strp(p, "param").ok_or_else(|| bad("graph.node.bind", "`param` is required"))?.to_string(); + let input = strp(p, "input").map(str::to_string); + if let Some(i) = &input + && !s.graph()?.exposed.iter().any(|e| &e.id == i) + { + return Err(bad("graph.node.bind", format!("no input `{i}`"))); + } + s.edit("Bind parameter", |s| { + let n = s.graph_mut()?.node_mut(id)?; + match input { + Some(i) => n.bindings.insert(param, i), + None => n.bindings.remove(¶m), + }; + Ok(J::Null) + }) +} + +fn connect(s: &mut Session, p: &J) -> Result { + let from = NodeId(u64p(p, "from").ok_or_else(|| bad("graph.connect", "`from` is required"))?); + let to = NodeId(u64p(p, "to").ok_or_else(|| bad("graph.connect", "`to` is required"))?); + let (ins, outs) = (s.input_ports(to), s.output_ports(from)); + let from_port = + strp(p, "fromPort").map(str::to_string).or_else(|| outs.first().cloned()).ok_or_else(|| bad("graph.connect", "the source has no outputs"))?; + let to_port = strp(p, "toPort").map(str::to_string).or_else(|| ins.first().cloned()).ok_or_else(|| bad("graph.connect", "the target has no inputs"))?; + if !outs.contains(&from_port) { + return Err(bad("graph.connect", format!("no output `{from_port}` on node {} (has {outs:?})", from.0))); + } + if !ins.contains(&to_port) { + return Err(bad("graph.connect", format!("no input `{to_port}` on node {} (has {ins:?})", to.0))); + } + s.edit("Connect", |s| { + s.graph_mut()?.connect(from, &from_port, to, &to_port)?; + Ok(J::Null) + }) +} + +fn disconnect(s: &mut Session, p: &J) -> Result { + let to = NodeId(u64p(p, "to").ok_or_else(|| bad("graph.disconnect", "`to` is required"))?); + let port = strp(p, "toPort").ok_or_else(|| bad("graph.disconnect", "`toPort` is required"))?.to_string(); + s.edit("Disconnect", |s| { + if !s.graph_mut()?.disconnect(to, &port) { + return Err(bad("graph.disconnect", "nothing is connected there")); + } + Ok(J::Null) + }) +} + +impl Session { + /// Input port ids of node `id` (empty for a missing node). + pub fn input_ports(&self, id: NodeId) -> Vec { + self.graph() + .ok() + .and_then(|g| g.node(id).ok()) + .map(|n| materialcraft_eval::ports(&self.pkg, n).0.into_iter().map(|p| p.id).collect()) + .unwrap_or_default() + } + + /// Output port ids of node `id`. + pub fn output_ports(&self, id: NodeId) -> Vec { + self.graph() + .ok() + .and_then(|g| g.node(id).ok()) + .map(|n| materialcraft_eval::ports(&self.pkg, n).1.into_iter().map(|p| p.id).collect()) + .unwrap_or_default() + } +} diff --git a/crates/engine/src/samples.rs b/crates/engine/src/samples.rs new file mode 100644 index 00000000..907def6c --- /dev/null +++ b/crates/engine/src/samples.rs @@ -0,0 +1,333 @@ +//! Built-in sample materials and graph templates, built in code from the node library (no +//! third-party content). + +use materialcraft_core::{Graph, NodeId, Package, Value}; + +/// Template ids and labels for File ▸ New graph. +pub const TEMPLATES: &[(&str, &str)] = &[ + ("empty", "Empty"), + ("pbr", "PBR material (outputs only)"), + ("bricks", "Brick wall"), + ("stone_tiles", "Stone tiles"), + ("wood", "Wood planks"), + ("rusty_metal", "Rusty metal"), + ("fabric", "Woven fabric"), + ("ground", "Stone ground"), +]; + +struct B<'g> { + g: &'g mut Graph, +} + +impl B<'_> { + fn n(&mut self, def: &str, x: f32, y: f32, params: &[(&str, Value)]) -> NodeId { + let id = self.g.add_node(def, [x, y]); + if let Ok(n) = self.g.node_mut(id) { + for (k, v) in params { + n.params.insert((*k).into(), v.clone()); + } + } + id + } + fn c(&mut self, from: NodeId, to: NodeId, port: &str) { + self.cp(from, "output", to, port); + } + fn cp(&mut self, from: NodeId, from_port: &str, to: NodeId, port: &str) { + // Sample graphs are acyclic by construction; a failure would only drop a wire. + let _ = self.g.connect(from, from_port, to, port); + } + /// The six PBR outputs at `x`, fed by the given nodes. + fn outputs(&mut self, x: f32, feeds: &[(NodeId, &str, u32, &str)]) { + for (i, (from, port, usage, ident)) in feeds.iter().enumerate() { + let o = self.n("output", x, i as f32 * 110.0, &[("usage", Value::Enum(*usage)), ("identifier", Value::Text((*ident).into()))]); + self.cp(*from, port, o, "input"); + } + } +} + +fn f(v: f32) -> Value { + Value::Float(v) +} + +fn e(v: u32) -> Value { + Value::Enum(v) +} + +fn i(v: i32) -> Value { + Value::Int(v) +} + +fn col(r: f32, g: f32, b: f32) -> Value { + Value::Color([r, g, b, 1.0]) +} + +fn grad(keys: &[(f32, [f32; 3])]) -> Value { + Value::Gradient(materialcraft_core::Gradient { + keys: keys.iter().map(|(p, c)| materialcraft_core::GradientKey { pos: *p, color: [c[0], c[1], c[2], 1.0] }).collect(), + }) +} + +/// A new graph from a template (unknown ids give an empty graph). +pub fn template(id: &str, name: &str, size_log2: u32) -> Graph { + let mut g = Graph::new(name); + g.size = [size_log2, size_log2]; + let mut b = B { g: &mut g }; + match id { + "pbr" => { + let base = b.n("pbr_base_material", 0.0, 220.0, &[]); + b.outputs( + 320.0, + &[ + (base, "base_color", 0, "basecolor"), + (base, "normal", 1, "normal"), + (base, "roughness", 2, "roughness"), + (base, "metallic", 3, "metallic"), + (base, "height", 4, "height"), + (base, "ambient_occlusion", 5, "ambientocclusion"), + ], + ); + } + "bricks" => bricks(&mut b), + "stone_tiles" => stone_tiles(&mut b), + "wood" => wood(&mut b), + "rusty_metal" => rusty_metal(&mut b), + "fabric" => fabric(&mut b), + "ground" => ground(&mut b), + _ => {} + } + g +} + +fn bricks(b: &mut B) { + let bricks = b.n( + "brick_generator", + 0.0, + 0.0, + &[("bricks_x", i(4)), ("bricks_y", i(10)), ("gap", f(0.06)), ("bevel", f(0.18)), ("height_random", f(0.25)), ("lum_random", f(0.0))], + ); + let cells = b.n("cells_1", 0.0, 180.0, &[("scale", f(24.0))]); + let grunge = b.n("grunge_map_1", 0.0, 360.0, &[("scale", f(4.0))]); + let chip = b.n("blend", 180.0, 90.0, &[("mode", e(3)), ("opacity", f(0.35))]); + b.c(cells, chip, "foreground"); + b.c(bricks, chip, "background"); + let erode = b.n("slope_blur", 360.0, 90.0, &[("intensity", f(3.0)), ("mode", e(1))]); + b.c(chip, erode, "input"); + b.c(grunge, erode, "slope"); + let height = b.n("levels", 540.0, 90.0, &[("in_high", f(0.9))]); + b.c(erode, height, "input"); + let normal = b.n("normal", 720.0, 0.0, &[("intensity", f(2.2))]); + b.c(height, normal, "input"); + let ao = b.n("ambient_occlusion", 720.0, 120.0, &[("spread", f(0.05)), ("intensity", f(0.6))]); + b.c(height, ao, "height"); + // Color: per-brick tint from cells, mortar from the height mask. + let tint = b.n("cells_3", 360.0, 300.0, &[("scale", f(10.0))]); + let mix = b.n("blend", 540.0, 300.0, &[("mode", e(3)), ("opacity", f(0.6))]); + b.c(grunge, mix, "foreground"); + b.c(tint, mix, "background"); + let brick_col = + b.n("gradient_map", 720.0, 300.0, &[("gradient", grad(&[(0.0, [0.18, 0.05, 0.03]), (0.5, [0.42, 0.12, 0.06]), (1.0, [0.62, 0.28, 0.16])]))]); + b.c(mix, brick_col, "input"); + let mortar = b.n("uniform", 720.0, 440.0, &[("color", col(0.42, 0.40, 0.36))]); + let mask = b.n("histogram_scan", 720.0, 560.0, &[("position", f(0.15)), ("contrast", f(0.8))]); + b.c(height, mask, "input"); + let base = b.n("blend", 900.0, 360.0, &[("mode", e(0))]); + b.c(brick_col, base, "foreground"); + b.c(mortar, base, "background"); + b.c(mask, base, "mask"); + let rough = b.n("levels", 900.0, 520.0, &[("out_low", f(0.65)), ("out_high", f(0.95))]); + b.c(grunge, rough, "input"); + let metal = b.n("uniform", 900.0, 640.0, &[("mode", e(1)), ("color", col(0.0, 0.0, 0.0))]); + b.outputs( + 1120.0, + &[ + (base, "output", 0, "basecolor"), + (normal, "output", 1, "normal"), + (rough, "output", 2, "roughness"), + (metal, "output", 3, "metallic"), + (height, "output", 4, "height"), + (ao, "output", 5, "ambientocclusion"), + ], + ); +} + +fn stone_tiles(b: &mut B) { + let tiles = b.n( + "tile_generator", + 0.0, + 0.0, + &[("pattern", e(7)), ("x_amount", i(5)), ("y_amount", i(5)), ("scale", f(0.96)), ("offset", f(0.5)), ("lum_random", f(0.25))], + ); + let clouds = b.n("clouds_2", 0.0, 180.0, &[("scale", f(6.0))]); + let detail = b.n("blend", 200.0, 80.0, &[("mode", e(3)), ("opacity", f(0.5))]); + b.c(clouds, detail, "foreground"); + b.c(tiles, detail, "background"); + let normal = b.n("normal", 420.0, 0.0, &[("intensity", f(1.8))]); + b.c(detail, normal, "input"); + let ao = b.n("ambient_occlusion", 420.0, 120.0, &[]); + b.c(detail, ao, "height"); + let cmap = b.n("gradient_map", 420.0, 240.0, &[("gradient", grad(&[(0.0, [0.12, 0.12, 0.11]), (0.6, [0.45, 0.43, 0.40]), (1.0, [0.70, 0.68, 0.62])]))]); + b.c(detail, cmap, "input"); + let rough = b.n("invert", 420.0, 360.0, &[]); + b.c(clouds, rough, "input"); + let metal = b.n("uniform", 420.0, 480.0, &[("mode", e(1)), ("color", col(0.0, 0.0, 0.0))]); + b.outputs( + 700.0, + &[ + (cmap, "output", 0, "basecolor"), + (normal, "output", 1, "normal"), + (rough, "output", 2, "roughness"), + (metal, "output", 3, "metallic"), + (detail, "output", 4, "height"), + (ao, "output", 5, "ambientocclusion"), + ], + ); +} + +fn wood(b: &mut B) { + let grain = b.n("anisotropic_noise", 0.0, 0.0, &[("scale", f(3.0)), ("scale_y", f(96.0)), ("smoothness", f(0.3))]); + let planks = b.n( + "brick_generator", + 0.0, + 180.0, + &[("bricks_x", i(1)), ("bricks_y", i(6)), ("offset", f(0.0)), ("gap", f(0.015)), ("bevel", f(0.05)), ("height_random", f(0.1))], + ); + let warp_src = b.n("perlin_noise", 0.0, 360.0, &[("scale", f(4.0))]); + let warped = b.n("directional_warp", 200.0, 0.0, &[("intensity", f(6.0)), ("angle", f(0.25))]); + b.c(grain, warped, "input"); + b.c(warp_src, warped, "intensity_input"); + let rot = b.n("transformation", 380.0, 0.0, &[("scale", Value::Float2([1.0, 1.0]))]); + b.c(warped, rot, "input"); + let h = b.n("blend", 560.0, 90.0, &[("mode", e(3))]); + b.c(rot, h, "foreground"); + b.c(planks, h, "background"); + let normal = b.n("normal", 740.0, 0.0, &[("intensity", f(1.2))]); + b.c(h, normal, "input"); + let ao = b.n("ambient_occlusion", 740.0, 120.0, &[("spread", f(0.03))]); + b.c(h, ao, "height"); + let cmap = b.n("gradient_map", 740.0, 240.0, &[("gradient", grad(&[(0.0, [0.10, 0.04, 0.015]), (0.45, [0.33, 0.15, 0.05]), (1.0, [0.62, 0.36, 0.15])]))]); + b.c(h, cmap, "input"); + let rough = b.n("levels", 740.0, 360.0, &[("out_low", f(0.45)), ("out_high", f(0.75))]); + b.c(rot, rough, "input"); + let metal = b.n("uniform", 740.0, 480.0, &[("mode", e(1)), ("color", col(0.0, 0.0, 0.0))]); + b.outputs( + 1000.0, + &[ + (cmap, "output", 0, "basecolor"), + (normal, "output", 1, "normal"), + (rough, "output", 2, "roughness"), + (metal, "output", 3, "metallic"), + (h, "output", 4, "height"), + (ao, "output", 5, "ambientocclusion"), + ], + ); +} + +fn rusty_metal(b: &mut B) { + let rust_mask = b.n("grunge_map_1", 0.0, 0.0, &[("scale", f(3.0)), ("contrast", f(0.7))]); + let scan = b.n("histogram_scan", 200.0, 0.0, &[("position", f(0.55)), ("contrast", f(0.7))]); + b.c(rust_mask, scan, "input"); + let fine = b.n("clouds_3", 0.0, 180.0, &[("scale", f(12.0))]); + let brushed = b.n("anisotropic_noise", 0.0, 360.0, &[("scale", f(2.0)), ("scale_y", f(256.0))]); + let h = b.n("blend", 400.0, 90.0, &[("mode", e(1)), ("opacity", f(0.4))]); + b.c(fine, h, "foreground"); + b.c(scan, h, "background"); + let normal = b.n("normal", 600.0, 0.0, &[("intensity", f(1.4))]); + b.c(h, normal, "input"); + let rust_col = b.n("gradient_map", 400.0, 240.0, &[("gradient", grad(&[(0.0, [0.12, 0.04, 0.01]), (0.5, [0.38, 0.12, 0.03]), (1.0, [0.55, 0.25, 0.08])]))]); + b.c(fine, rust_col, "input"); + let metal_col = b.n("uniform", 400.0, 380.0, &[("color", col(0.55, 0.56, 0.58))]); + let base = b.n("blend", 600.0, 300.0, &[]); + b.c(rust_col, base, "foreground"); + b.c(metal_col, base, "background"); + b.c(scan, base, "mask"); + let metal = b.n("invert", 600.0, 440.0, &[]); + b.c(scan, metal, "input"); + let rough_metal = b.n("levels", 400.0, 520.0, &[("out_low", f(0.25)), ("out_high", f(0.4))]); + b.c(brushed, rough_metal, "input"); + let rough = b.n("blend", 600.0, 560.0, &[]); + let rough_rust = b.n("uniform", 400.0, 640.0, &[("mode", e(1)), ("color", col(0.85, 0.85, 0.85))]); + b.c(rough_rust, rough, "foreground"); + b.c(rough_metal, rough, "background"); + b.c(scan, rough, "mask"); + let ao = b.n("ambient_occlusion", 600.0, 680.0, &[]); + b.c(h, ao, "height"); + b.outputs( + 860.0, + &[ + (base, "output", 0, "basecolor"), + (normal, "output", 1, "normal"), + (rough, "output", 2, "roughness"), + (metal, "output", 3, "metallic"), + (h, "output", 4, "height"), + (ao, "output", 5, "ambientocclusion"), + ], + ); +} + +fn fabric(b: &mut B) { + let weave = b.n("weave", 0.0, 0.0, &[("tiling", i(16)), ("width", f(0.85))]); + let fuzz = b.n("white_noise", 0.0, 180.0, &[]); + let soft = b.n("blur", 200.0, 180.0, &[("intensity", f(0.4))]); + b.c(fuzz, soft, "input"); + let h = b.n("blend", 400.0, 60.0, &[("mode", e(3)), ("opacity", f(0.25))]); + b.c(soft, h, "foreground"); + b.c(weave, h, "background"); + let normal = b.n("normal", 600.0, 0.0, &[("intensity", f(1.0))]); + b.c(h, normal, "input"); + let ao = b.n("ambient_occlusion", 600.0, 120.0, &[("spread", f(0.02))]); + b.c(h, ao, "height"); + let cmap = b.n("gradient_map", 600.0, 240.0, &[("gradient", grad(&[(0.0, [0.02, 0.05, 0.12]), (1.0, [0.12, 0.22, 0.45])]))]); + b.c(h, cmap, "input"); + let rough = b.n("uniform", 600.0, 360.0, &[("mode", e(1)), ("color", col(0.9, 0.9, 0.9))]); + let metal = b.n("uniform", 600.0, 480.0, &[("mode", e(1)), ("color", col(0.0, 0.0, 0.0))]); + b.outputs( + 860.0, + &[ + (cmap, "output", 0, "basecolor"), + (normal, "output", 1, "normal"), + (rough, "output", 2, "roughness"), + (metal, "output", 3, "metallic"), + (h, "output", 4, "height"), + (ao, "output", 5, "ambientocclusion"), + ], + ); +} + +fn ground(b: &mut B) { + let stones = b.n("cells_4", 0.0, 0.0, &[("scale", f(6.0))]); + let pebbles = b.n("cells_1", 0.0, 180.0, &[("scale", f(18.0))]); + let dirt = b.n("dirt", 0.0, 360.0, &[("scale", f(5.0))]); + let h1 = b.n("height_blend", 220.0, 90.0, &[("offset", f(0.45)), ("contrast", f(0.85))]); + b.c(stones, h1, "top"); + b.c(pebbles, h1, "bottom"); + let h = b.n("blend", 420.0, 160.0, &[("mode", e(6)), ("opacity", f(0.8))]); + b.c(dirt, h, "foreground"); + b.cp(h1, "height", h, "background"); + let normal = b.n("normal", 620.0, 0.0, &[("intensity", f(2.0))]); + b.c(h, normal, "input"); + let ao = b.n("ambient_occlusion", 620.0, 120.0, &[]); + b.c(h, ao, "height"); + let cmap = b.n("gradient_map", 620.0, 240.0, &[("gradient", grad(&[(0.0, [0.08, 0.06, 0.04]), (0.5, [0.27, 0.22, 0.17]), (1.0, [0.55, 0.52, 0.47])]))]); + b.c(h, cmap, "input"); + let rough = b.n("levels", 620.0, 360.0, &[("out_low", f(0.6)), ("out_high", f(0.95))]); + b.c(dirt, rough, "input"); + let metal = b.n("uniform", 620.0, 480.0, &[("mode", e(1)), ("color", col(0.0, 0.0, 0.0))]); + b.outputs( + 880.0, + &[ + (cmap, "output", 0, "basecolor"), + (normal, "output", 1, "normal"), + (rough, "output", 2, "roughness"), + (metal, "output", 3, "metallic"), + (h, "output", 4, "height"), + (ao, "output", 5, "ambientocclusion"), + ], + ); +} + +/// The package the app opens with: the brick wall sample. +pub fn sample_package() -> Package { + let mut p = Package::new("Untitled package"); + p.graphs.push(template("bricks", "Brick_wall", 10)); + p +} diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs new file mode 100644 index 00000000..c8ecabbb --- /dev/null +++ b/crates/engine/src/session.rs @@ -0,0 +1,314 @@ +//! The session: the open package, the graph being edited, selection, views, snapshot undo and +//! the cook cache. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex, PoisonError}; + +use materialcraft_core::{Graph, NodeId, Package}; +use materialcraft_eval::{Cache, Cooked, Options}; +use materialcraft_image::Image; +use serde::{Deserialize, Serialize}; + +use crate::{EngineError, Result}; + +/// Undo keeps this many steps. +const MAX_UNDO: usize = 200; + +/// The 3D view's scene and look. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct View3d { + /// Built-in mesh: `rounded_cube`, `cube`, `sphere`, `cylinder`, `plane`, `torus`, `material_ball`. + pub scene: String, + /// UV repeats of the material on the mesh. + pub tiling: f32, + /// Camera yaw and pitch (degrees) and distance (mesh radii). + pub yaw: f32, + pub pitch: f32, + pub distance: f32, + /// Environment: `studio`, `sunset`, `overcast`, `night`. + pub environment: String, + pub env_rotation: f32, + pub exposure: f32, + /// Parallax depth of the height output (0 = off). + pub height_scale: f32, + pub show_axis: bool, + pub show_grid: bool, +} + +impl Default for View3d { + fn default() -> Self { + View3d { + scene: "rounded_cube".into(), + tiling: 1.0, + yaw: 35.0, + pitch: 25.0, + distance: 3.2, + environment: "studio".into(), + env_rotation: 0.0, + exposure: 0.0, + height_scale: 0.03, + show_axis: false, + show_grid: false, + } + } +} + +/// What the 2D view shows. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct View2d { + pub node: Option, + pub port: usize, + /// Repeat the image 3×3 to check tiling. + pub tiled: bool, + /// `rgba`, `r`, `g`, `b`, `a`. + pub channel: String, +} + +#[derive(Clone)] +struct Snapshot { + pkg: Package, + graph: usize, + selection: Vec, + label: String, +} + +/// Nodes and connections copied to the clipboard (as JSON, so other sessions can paste them). +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct Clip { + pub nodes: Vec, + pub connections: Vec, +} + +pub struct Session { + pub pkg: Package, + /// Where the package was opened from or last saved to. + pub path: Option, + /// Index of the graph being edited. + pub graph: usize, + pub selection: Vec, + pub view2d: View2d, + pub view3d: View3d, + /// Cap on node output size while editing (`None` = full size). + pub preview_size: Option, + pub modified: bool, + pub log: Vec, + pub clipboard: Option, + /// The last cook of the open graph. + pub cooked: Cooked, + /// Set when the graph changed and needs cooking. + pub dirty: bool, + /// Cooked node outputs, shared with background cooks. + pub cache: Arc>, + undo: Vec, + redo: Vec, + /// Edits with the same key coalesce into one undo step (slider drags). + merge_key: Option, + decoded: Arc>>, +} + +impl Session { + pub fn new(pkg: Package) -> Session { + Session { + pkg, + path: None, + graph: 0, + selection: Vec::new(), + view2d: View2d { channel: "rgba".into(), ..View2d::default() }, + view3d: View3d::default(), + preview_size: Some(512), + modified: false, + log: Vec::new(), + clipboard: None, + cooked: Cooked::default(), + dirty: true, + cache: Arc::new(Mutex::new(Cache::default())), + undo: Vec::new(), + redo: Vec::new(), + merge_key: None, + decoded: Arc::new(Mutex::new(HashMap::new())), + } + } + + /// The graph being edited. + pub fn graph(&self) -> Result<&Graph> { + self.pkg.graph(self.graph).map_err(EngineError::from) + } + + pub fn graph_mut(&mut self) -> Result<&mut Graph> { + self.pkg.graph_mut(self.graph).map_err(EngineError::from) + } + + fn snapshot(&self, label: &str) -> Snapshot { + Snapshot { pkg: self.pkg.clone(), graph: self.graph, selection: self.selection.clone(), label: label.into() } + } + + /// Run `f` as one undoable step. On error the session is restored. + pub fn edit(&mut self, label: &str, f: impl FnOnce(&mut Session) -> Result) -> Result { + self.merge_key = None; + self.edit_inner(label, f) + } + + /// Like [`Session::edit`], but consecutive edits with the same `key` (dragging one slider) + /// make a single undo step. + pub fn edit_merged(&mut self, key: &str, label: &str, f: impl FnOnce(&mut Session) -> Result) -> Result { + if self.merge_key.as_deref() == Some(key) && !self.undo.is_empty() { + let r = f(self); + if r.is_ok() { + self.changed(); + } + return r; + } + let r = self.edit_inner(label, f); + if r.is_ok() { + self.merge_key = Some(key.into()); + } + r + } + + fn edit_inner(&mut self, label: &str, f: impl FnOnce(&mut Session) -> Result) -> Result { + let snap = self.snapshot(label); + match f(self) { + Ok(v) => { + self.undo.push(snap); + if self.undo.len() > MAX_UNDO { + self.undo.remove(0); + } + self.redo.clear(); + self.changed(); + Ok(v) + } + Err(e) => { + self.restore(snap); + Err(e) + } + } + } + + fn restore(&mut self, s: Snapshot) { + self.pkg = s.pkg; + self.graph = s.graph.min(self.pkg.graphs.len().saturating_sub(1)); + self.selection = s.selection; + } + + /// Mark the document modified and in need of a cook. + pub fn changed(&mut self) { + self.modified = true; + self.dirty = true; + } + + pub fn can_undo(&self) -> bool { + !self.undo.is_empty() + } + + pub fn can_redo(&self) -> bool { + !self.redo.is_empty() + } + + /// Labels of the undo stack, oldest first. + pub fn history(&self) -> Vec { + self.undo.iter().map(|s| s.label.clone()).collect() + } + + pub fn undo(&mut self) -> Option { + let s = self.undo.pop()?; + let label = s.label.clone(); + let cur = self.snapshot(&label); + self.redo.push(cur); + self.restore(s); + self.merge_key = None; + self.changed(); + Some(label) + } + + pub fn redo(&mut self) -> Option { + let s = self.redo.pop()?; + let label = s.label.clone(); + let cur = self.snapshot(&label); + self.undo.push(cur); + self.restore(s); + self.merge_key = None; + self.changed(); + Some(label) + } + + /// Forget undo history (after opening a package). + pub fn reset_history(&mut self) { + self.undo.clear(); + self.redo.clear(); + self.merge_key = None; + } + + /// A decoder for the package's bitmap resources (memoized, shareable with worker threads). + pub fn resource_decoder(&self) -> impl Fn(&str) -> Option + Sync + Send + 'static { + let res: Vec<(String, Arc>)> = self.pkg.resources.iter().map(|r| (r.name.clone(), r.bytes.clone())).collect(); + let memo = self.decoded.clone(); + move |name: &str| { + let (_, bytes) = res.iter().find(|(n, _)| n == name)?; + let key = format!("{name}:{}", bytes.len()); + if let Some(i) = memo.lock().unwrap_or_else(PoisonError::into_inner).get(&key) { + return Some(i.clone()); + } + let img = materialcraft_formats::decode(bytes).ok()?; + memo.lock().unwrap_or_else(PoisonError::into_inner).insert(key, img.clone()); + Some(img) + } + } + + /// Cook the open graph now (at the preview size), on this thread. + pub fn cook(&mut self) -> &Cooked { + let dec = self.resource_decoder(); + let mut opts = Options::new(&dec); + opts.max_size = self.preview_size; + let cooked = { + let mut cache = self.cache.lock().unwrap_or_else(PoisonError::into_inner); + materialcraft_eval::cook(&self.pkg, self.graph, &opts, &mut cache) + }; + self.cooked = cooked; + self.dirty = false; + &self.cooked + } + + /// Cook graph `gi` at full size (exports), without touching the preview results. + pub fn cook_full(&self, gi: usize) -> Cooked { + let dec = self.resource_decoder(); + let opts = Options::new(&dec); + let mut cache = self.cache.lock().unwrap_or_else(PoisonError::into_inner); + materialcraft_eval::cook(&self.pkg, gi, &opts, &mut cache) + } + + /// Cook if the graph changed since the last cook. + pub fn cook_if_dirty(&mut self) { + if self.dirty { + self.cook(); + } + } + + /// The image the 2D view shows: the chosen node's port, else the first output node, else the + /// last selected node. + pub fn view2d_image(&self) -> Option<(NodeId, &Image)> { + let g = self.graph().ok()?; + let id = self + .view2d + .node + .filter(|id| g.node(*id).is_ok()) + .or_else(|| self.selection.last().copied()) + .or_else(|| g.nodes.iter().find(|n| n.def == "output").map(|n| n.id))?; + let port = if Some(id) == self.view2d.node { self.view2d.port } else { 0 }; + self.cooked.image(id, port).or_else(|| self.cooked.image(id, 0)).map(|i| (id, i)) + } + + /// The open graph's material channels for the 3D view: usage id → image. + pub fn material_maps(&self) -> Vec<(&'static str, &Image)> { + let Ok(g) = self.graph() else { return Vec::new() }; + materialcraft_eval::outputs(g, &self.cooked).into_iter().filter_map(|(_, usage, _, img)| Some((usage, img?))).collect() + } + + pub fn log(&mut self, msg: impl Into) { + self.log.push(msg.into()); + if self.log.len() > 500 { + self.log.remove(0); + } + } +} diff --git a/crates/engine/src/view_cmds.rs b/crates/engine/src/view_cmds.rs new file mode 100644 index 00000000..1e06fc6d --- /dev/null +++ b/crates/engine/src/view_cmds.rs @@ -0,0 +1,152 @@ +//! View commands: the 2D and 3D views, the preview size, the library listing and inspection. + +use serde_json::{Value as J, json}; + +use materialcraft_core::NodeId; + +use crate::commands::{CommandSpec, always, bad, boolp, f32p, has_graph, strp, u64p}; +use crate::{Result, Session, cmd}; + +/// Built-in 3D view scenes: (id, label). +pub const SCENES: &[(&str, &str)] = &[ + ("cube", "Cube"), + ("cylinder", "Cylinder"), + ("plane", "Plane"), + ("sphere", "Sphere"), + ("material_ball", "Mat ball"), + ("rounded_cube", "Rounded cube"), + ("torus", "Torus"), +]; + +/// Environments: (id, label). +pub const ENVIRONMENTS: &[(&str, &str)] = &[("studio", "Studio"), ("sunset", "Sunset"), ("overcast", "Overcast"), ("night", "Night")]; + +pub(crate) fn specs() -> Vec { + vec![ + cmd!("view.2d", "View output in 2D view", [], None, "{node?, port?, tiled?, channel? (rgba|r|g|b|a)}", has_graph, view2d), + cmd!( + "view.3d", + "3D view settings", + [], + None, + "{scene? (cube|cylinder|plane|sphere|material_ball|rounded_cube|torus), tiling?, yaw?, pitch?, distance?, environment? (studio|sunset|overcast|night), envRotation?, exposure?, heightScale?, axis?, grid?}", + always, + view3d + ), + cmd!("view.3d.reset", "Reset scene", [], None, "{}", always, |s, _| { + s.view3d = crate::View3d::default(); + Ok(J::Null) + }), + cmd!("view.previewSize", "Preview size", [], None, "{size: 64..8192, or 0 for full size} caps node outputs while editing", always, preview_size), + cmd!( + "library.list", + "Library", + [], + None, + "{filter?, category?} every node definition: id, label, category, inputs, outputs, parameters", + always, + library + ), + cmd!( + "session.inspect", + "Inspect", + [], + None, + "{graph?} the package, the open graph (nodes, wires, parameters, errors, timings), views and history", + always, + |s, p| { Ok(crate::inspect::session(s, u64p(p, "graph").map(|g| g as usize))) } + ), + ] +} + +fn view2d(s: &mut Session, p: &J) -> Result { + if let Some(n) = u64p(p, "node") { + s.graph()?.node(NodeId(n)).map_err(|_| bad("view.2d", format!("no node {n}")))?; + s.view2d.node = Some(NodeId(n)); + s.view2d.port = 0; + } + if let Some(port) = u64p(p, "port") { + s.view2d.port = port as usize; + } + if let Some(t) = boolp(p, "tiled") { + s.view2d.tiled = t; + } + if let Some(c) = strp(p, "channel") { + if !["rgba", "r", "g", "b", "a"].contains(&c) { + return Err(bad("view.2d", "`channel` is rgba, r, g, b or a")); + } + s.view2d.channel = c.into(); + } + Ok(serde_json::to_value(&s.view2d).unwrap_or(J::Null)) +} + +fn view3d(s: &mut Session, p: &J) -> Result { + let v = &mut s.view3d; + if let Some(sc) = strp(p, "scene") { + if !SCENES.iter().any(|(id, _)| *id == sc) { + return Err(bad("view.3d", format!("unknown scene `{sc}`"))); + } + v.scene = sc.into(); + } + if let Some(e) = strp(p, "environment") { + if !ENVIRONMENTS.iter().any(|(id, _)| *id == e) { + return Err(bad("view.3d", format!("unknown environment `{e}`"))); + } + v.environment = e.into(); + } + if let Some(t) = f32p(p, "tiling") { + v.tiling = t.clamp(0.1, 64.0); + } + if let Some(t) = f32p(p, "yaw") { + v.yaw = t.rem_euclid(360.0); + } + if let Some(t) = f32p(p, "pitch") { + v.pitch = t.clamp(-89.0, 89.0); + } + if let Some(t) = f32p(p, "distance") { + v.distance = t.clamp(1.2, 20.0); + } + if let Some(t) = f32p(p, "envRotation") { + v.env_rotation = t.rem_euclid(360.0); + } + if let Some(t) = f32p(p, "exposure") { + v.exposure = t.clamp(-10.0, 10.0); + } + if let Some(t) = f32p(p, "heightScale") { + v.height_scale = t.clamp(0.0, 0.5); + } + if let Some(b) = boolp(p, "axis") { + v.show_axis = b; + } + if let Some(b) = boolp(p, "grid") { + v.show_grid = b; + } + Ok(serde_json::to_value(&s.view3d).unwrap_or(J::Null)) +} + +fn preview_size(s: &mut Session, p: &J) -> Result { + let size = u64p(p, "size").ok_or_else(|| bad("view.previewSize", "`size` is required"))?; + s.preview_size = if size == 0 { None } else { Some(size.clamp(64, 8192) as u32) }; + s.dirty = true; + Ok(json!({"previewSize": s.preview_size})) +} + +fn library(_: &mut Session, p: &J) -> Result { + let f = strp(p, "filter").map(str::to_ascii_lowercase); + let cat = strp(p, "category").map(str::to_ascii_lowercase); + Ok(J::Array( + materialcraft_nodes::catalog() + .iter() + .filter(|d| f.as_ref().is_none_or(|f| d.id.contains(f.as_str()) || d.label.to_ascii_lowercase().contains(f.as_str()))) + .filter(|d| cat.as_ref().is_none_or(|c| d.category.to_ascii_lowercase().contains(c.as_str()))) + .map(|d| { + json!({ + "id": d.id, "label": d.label, "category": d.category, "description": d.description, + "inputs": d.inputs.iter().map(|p| json!({"id": p.id, "label": p.label, "kind": format!("{:?}", p.kind)})).collect::>(), + "outputs": d.outputs.iter().map(|p| json!({"id": p.id, "label": p.label, "kind": format!("{:?}", p.kind)})).collect::>(), + "params": d.params.iter().map(|p| json!({"id": p.id, "label": p.label, "default": p.default, "min": p.min, "max": p.max, "options": p.options})).collect::>(), + }) + }) + .collect(), + )) +} diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs new file mode 100644 index 00000000..841087a4 --- /dev/null +++ b/crates/engine/tests/session.rs @@ -0,0 +1,114 @@ +use materialcraft_engine::{Session, command_specs, execute, sample_session}; +use serde_json::{Value, json}; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + execute(s, id, &p).unwrap_or_else(|e| panic!("{id}: {e}")) +} + +#[test] +fn every_template_cooks_cleanly() { + let mut s = sample_session(); + s.preview_size = Some(128); + for (id, _) in materialcraft_engine::samples::TEMPLATES { + run(&mut s, "file.new", json!({"template": id, "size": 256})); + let c = s.cook().clone(); + let g = s.graph().unwrap(); + for (nid, r) in &c.nodes { + assert!(r.error.is_none(), "{id}: node {} ({}) failed: {:?}", nid.0, g.node(*nid).unwrap().def, r.error); + } + if *id != "empty" { + assert!(!s.material_maps().is_empty(), "{id} has no outputs"); + } + } +} + +#[test] +fn build_a_graph_by_commands() { + let mut s = sample_session(); + run(&mut s, "file.new", json!({"template": "empty", "name": "Mine"})); + let noise = run(&mut s, "graph.node.add", json!({"def": "clouds_1", "at": [0, 0], "params": {"scale": 6}}))["id"].as_u64().unwrap(); + let lv = run(&mut s, "graph.node.add", json!({"def": "levels", "connectFrom": {"node": noise}}))["id"].as_u64().unwrap(); + let out = run(&mut s, "graph.node.add", json!({"def": "output", "at": [400, 0], "params": {"usage": 4}}))["id"].as_u64().unwrap(); + run(&mut s, "graph.connect", json!({"from": lv, "to": out})); + run(&mut s, "graph.node.param", json!({"id": lv, "param": "in_low", "value": 0.3})); + run(&mut s, "graph.node.param", json!({"id": lv, "param": "in_low", "value": 0.4})); + // A slider drag is one undo step. + assert_eq!(s.history().iter().filter(|h| *h == "Set parameter").count(), 1); + s.cook(); + let i = run(&mut s, "session.inspect", json!({})); + let nodes = i["graph"]["nodes"].as_array().unwrap(); + assert_eq!(nodes.len(), 3); + assert!(nodes.iter().all(|n| n["cooked"]["error"].is_null())); + assert_eq!(i["graph"]["connections"].as_array().unwrap().len(), 2); + // Bad input is an error, not a panic, and leaves the graph unchanged. + assert!(execute(&mut s, "graph.connect", &json!({"from": out, "to": noise})).is_err()); + assert!(execute(&mut s, "graph.node.param", &json!({"id": lv, "param": "nope", "value": 1})).is_err()); + assert!(execute(&mut s, "graph.node.add", &json!({"def": "nope"})).is_err()); + // Undo and redo. + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.redo", json!({})); + // Copy/paste and duplicate. + run(&mut s, "graph.select", json!({"ids": [noise, lv]})); + run(&mut s, "edit.copy", json!({})); + run(&mut s, "edit.paste", json!({"at": [0, 300]})); + assert_eq!(s.graph().unwrap().nodes.len(), 5); + assert_eq!(s.graph().unwrap().connections.len(), 3); + run(&mut s, "edit.duplicate", json!({})); + assert_eq!(s.graph().unwrap().nodes.len(), 7); + // Create a graph from a selection: the nodes move into a sub-graph instance. + run(&mut s, "graph.select", json!({"ids": [lv]})); + let r = run(&mut s, "graph.createFromSelection", json!({"name": "Leveler"})); + assert_eq!(r["graph"], "Leveler"); + s.cook(); + assert!(s.cooked.nodes.values().all(|r| r.error.is_none())); + // Exposed inputs drive bound parameters. + run(&mut s, "graph.open", json!({"graph": "Mine"})); + run(&mut s, "graph.exposed.add", json!({"id": "detail", "bind": {"node": noise, "param": "scale"}})); + run(&mut s, "graph.exposed.set", json!({"id": "detail", "value": 12})); + s.cook(); + assert!(s.cooked.nodes.values().all(|r| r.error.is_none())); +} + +#[test] +fn package_save_and_open_round_trip() { + let mut s = sample_session(); + let dir = std::env::temp_dir().join(format!("mc-test-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("bricks.mcraft"); + run(&mut s, "file.save", json!({"path": path.to_str().unwrap()})); + let before = s.pkg.clone(); + run(&mut s, "file.newPackage", json!({})); + run(&mut s, "file.open", json!({"path": path.to_str().unwrap()})); + assert_eq!(s.pkg.graphs, before.graphs); + let out = dir.join("tex"); + let r = run(&mut s, "file.export", json!({"dir": out.to_str().unwrap(), "format": "png", "depth": 8})); + assert_eq!(r["files"].as_array().unwrap().len(), 6); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Every command, run with empty and hostile params, returns Ok or Err but never panics. +#[test] +fn panic_hunt() { + let hostile = [ + json!({}), + json!(null), + json!({"id": u64::MAX, "ids": [u64::MAX, 0], "node": -1, "value": "x", "param": "", "def": "", "graph": 999}), + json!({"width": 0, "height": u64::MAX, "size": -5, "seed": f64::MAX, "at": [f64::MAX, -1e30], "by": ["a"], "rect": [1, 2]}), + json!({"value": [1e38, -1e38, 0, 0], "param": "opacity", "def": "blend", "mode": "zzz", "format": "gif", "dir": "", "path": ""}), + json!({"from": 0, "to": 0, "fromPort": "", "toPort": "", "clip": {"nodes": "x"}, "template": "../../x", "scene": "\u{0}"}), + ]; + for spec in command_specs() { + // Skip file writes to the working directory and opening paths. + if matches!(spec.id, "file.save" | "file.saveAs" | "file.export" | "file.open" | "file.importBitmap") { + continue; + } + for p in &hostile { + let mut s = sample_session(); + s.preview_size = Some(64); + let first = s.graph().unwrap().nodes[0].id; + s.selection = vec![first]; + let _ = execute(&mut s, spec.id, p); + s.cook(); + } + } +} diff --git a/crates/eval/Cargo.toml b/crates/eval/Cargo.toml new file mode 100644 index 00000000..67db82ef --- /dev/null +++ b/crates/eval/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "materialcraft-eval" +description = "MaterialCraft graph cooking: dependency order, sizes, a content-addressed output cache, sub-graphs" +version.workspace = true +edition.workspace = true +license.workspace = true + +[lints] +workspace = true + +[dependencies] +materialcraft-core = { workspace = true } +materialcraft-image = { workspace = true } +materialcraft-nodes = { workspace = true } +serde_json = { workspace = true } diff --git a/crates/eval/src/lib.rs b/crates/eval/src/lib.rs new file mode 100644 index 00000000..832fa6ea --- /dev/null +++ b/crates/eval/src/lib.rs @@ -0,0 +1,490 @@ +//! # materialcraft-eval +//! +//! Graph cooking, L2. [`cook`] walks a graph in dependency order, works out each node's output +//! size (relative to its input or the graph, or absolute, under an optional preview cap), resolves +//! parameters (defaults, overrides, bindings to exposed inputs) and runs the node's cook. Results +//! live in a content-addressed [`Cache`]: a node's key hashes its definition, parameters, size, +//! seed, tiling and its inputs' keys, so editing one node re-cooks only what lies downstream, and +//! undo/redo finds earlier results again. Graph instances cook their sub-graph recursively. +#![forbid(unsafe_code)] +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +use std::collections::{BTreeMap, HashMap}; +use std::hash::{DefaultHasher, Hash, Hasher}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; + +use materialcraft_core::{Graph, Node, NodeId, Package, SizeMode, Value}; +use materialcraft_image::{Image, Kind}; +use materialcraft_nodes::{Ctx, NodeDef, PortKind, find, resolve_params}; + +/// Sub-graphs may nest this deep (a graph instancing itself would recurse forever). +pub const MAX_DEPTH: u32 = 8; + +/// A port as the editor and the evaluator see it (catalog ports, or a sub-graph's inputs and +/// outputs for a graph instance). +#[derive(Clone, Debug, PartialEq)] +pub struct Port { + pub id: String, + pub label: String, + pub kind: PortKind, +} + +/// The input and output ports of `node` in `pkg`. +pub fn ports(pkg: &Package, node: &Node) -> (Vec, Vec) { + if node.def == "graph_instance" { + let Some((_, sub)) = instance_graph(pkg, node) else { return (Vec::new(), Vec::new()) }; + let io = |def: &str| -> Vec { + sub.nodes + .iter() + .filter(|n| n.def == def || (def == "input" && n.def.starts_with("input_"))) + .map(|n| { + let id = identifier(n); + let kind = if n.def == "input_grayscale" { + PortKind::Gray + } else if n.def == "input_color" { + PortKind::Color + } else { + PortKind::Any + }; + Port { label: id.clone(), id, kind } + }) + .collect() + }; + return (io("input"), io("output")); + } + let Some(def) = find(&node.def) else { return (Vec::new(), Vec::new()) }; + let conv = |p: &materialcraft_nodes::PortDef| Port { id: p.id.into(), label: p.label.into(), kind: p.kind }; + (def.inputs.iter().map(conv).collect(), def.outputs.iter().map(conv).collect()) +} + +/// The graph a graph-instance node refers to. +pub fn instance_graph<'a>(pkg: &'a Package, node: &Node) -> Option<(usize, &'a Graph)> { + match node.params.get("graph") { + Some(Value::Text(name)) => pkg.graph_by_name(name), + _ => None, + } +} + +/// An input or output node's identifier (its `identifier` parameter, default "input"/"output"). +pub fn identifier(n: &Node) -> String { + match n.params.get("identifier") { + Some(Value::Text(s)) if !s.is_empty() => s.clone(), + _ => if n.def == "output" { "output" } else { "input" }.into(), + } +} + +/// One node's cooked result. +#[derive(Clone, Debug)] +pub struct NodeResult { + /// One image per output port (empty when the cook failed). + pub outputs: Arc>, + pub error: Option, + /// Cook time in milliseconds (0 when served from the cache). + pub ms: f32, + pub key: u64, + pub cached: bool, +} + +/// Results of a cook, by node. +#[derive(Clone, Debug, Default)] +pub struct Cooked { + pub nodes: BTreeMap, + /// Total wall time of the cook in milliseconds. + pub ms: f32, + pub cancelled: bool, +} + +impl Cooked { + /// Output `port` of node `id`. + pub fn image(&self, id: NodeId, port: usize) -> Option<&Image> { + self.nodes.get(&id).and_then(|r| r.outputs.get(port)) + } +} + +/// LRU cache of node outputs, bounded by bytes. +pub struct Cache { + entries: HashMap>, usize, u64)>, + bytes: usize, + cap: usize, + tick: u64, +} + +impl Default for Cache { + fn default() -> Self { + Cache::new(1 << 30) + } +} + +impl Cache { + pub fn new(cap_bytes: usize) -> Cache { + Cache { entries: HashMap::new(), bytes: 0, cap: cap_bytes, tick: 0 } + } + + pub fn bytes(&self) -> usize { + self.bytes + } + + pub fn len(&self) -> usize { + self.entries.len() + } + + pub fn is_empty(&self) -> bool { + self.entries.is_empty() + } + + pub fn clear(&mut self) { + self.entries.clear(); + self.bytes = 0; + } + + fn get(&mut self, key: u64) -> Option>> { + self.tick += 1; + let t = self.tick; + self.entries.get_mut(&key).map(|e| { + e.2 = t; + e.0.clone() + }) + } + + fn put(&mut self, key: u64, v: Arc>) { + let size: usize = v.iter().map(|i| i.data.len() * 4).sum(); + self.tick += 1; + if let Some(old) = self.entries.insert(key, (v, size, self.tick)) { + self.bytes = self.bytes.saturating_sub(old.1); + } + self.bytes += size; + while self.bytes > self.cap && self.entries.len() > 1 { + let Some((&k, _)) = self.entries.iter().min_by_key(|(_, e)| e.2) else { break }; + if let Some(e) = self.entries.remove(&k) { + self.bytes = self.bytes.saturating_sub(e.1); + } + } + } +} + +/// What to cook and how. +pub struct Options<'a> { + /// Cap on the larger side of every node's output (previews); `None` = full size. + pub max_size: Option, + /// Cook only these nodes and what they depend on (`None` = the whole graph). + pub only: Option>, + /// Images for the graph's input nodes, by identifier (graph instances). + pub inputs: BTreeMap, + /// Values for the graph's exposed parameters (graph instances), over the graph's own. + pub overrides: BTreeMap, + /// Decodes a package resource (bitmap) by name. + pub resource: &'a (dyn Fn(&str) -> Option + Sync), + /// Set from another thread to stop between nodes. + pub cancel: Option<&'a AtomicBool>, + pub depth: u32, +} + +impl<'a> Options<'a> { + pub fn new(resource: &'a (dyn Fn(&str) -> Option + Sync)) -> Options<'a> { + Options { max_size: None, only: None, inputs: BTreeMap::new(), overrides: BTreeMap::new(), resource, cancel: None, depth: 0 } + } +} + +/// The magenta image a failed node shows. +pub fn error_image(w: u32, h: u32) -> Image { + Image::filled(w, h, Kind::Color, [1.0, 0.0, 1.0, 1.0]) +} + +fn hash_of(v: &impl Hash) -> u64 { + let mut h = DefaultHasher::new(); + v.hash(&mut h); + h.finish() +} + +/// Output size of `node` given its first connected input's size. +pub fn node_size(graph: &Graph, def: Option<&NodeDef>, node: &Node, input: Option<(u32, u32)>, max: Option) -> (u32, u32) { + let parent = graph.size_px(); + let (bw, bh) = match node.base.size_mode { + SizeMode::Absolute => { + let s = |l: i32| 1u32 << l.clamp(4, 13); + (s(node.base.size[0]), s(node.base.size[1])) + } + mode => { + let base = match (mode, input, def.is_some_and(|d| d.generator)) { + (SizeMode::RelativeToInput, Some(i), false) => i, + _ => (parent[0], parent[1]), + }; + let sh = |v: u32, o: i32| { + let v = v as f64 * 2f64.powi(o.clamp(-12, 12)); + v.round().clamp(16.0, 8192.0) as u32 + }; + (sh(base.0, node.base.size[0]), sh(base.1, node.base.size[1])) + } + }; + match max { + Some(m) if bw.max(bh) > m => { + let k = m as f64 / bw.max(bh) as f64; + (((bw as f64 * k).round() as u32).max(1), ((bh as f64 * k).round() as u32).max(1)) + } + _ => (bw, bh), + } +} + +/// Cook graph `gi` of `pkg`. +pub fn cook(pkg: &Package, gi: usize, opts: &Options, cache: &mut Cache) -> Cooked { + let t0 = now_ms(); + let mut out = Cooked::default(); + let Some(graph) = pkg.graphs.get(gi) else { return out }; + let order = graph.topo_order(); + let needed: Option> = opts.only.as_ref().map(|ids| { + let mut s: std::collections::BTreeSet = ids.iter().copied().collect(); + for id in ids { + s.extend(graph.upstream(*id)); + } + s + }); + // Exposed parameter values: the graph's own, then the caller's overrides. + let mut vars: BTreeMap = graph.exposed.iter().filter_map(|e| graph.input_value(&e.id).map(|v| (e.id.clone(), v.clone()))).collect(); + for (k, v) in &opts.overrides { + vars.insert(k.clone(), v.clone()); + } + for id in order { + if needed.as_ref().is_some_and(|s| !s.contains(&id)) { + continue; + } + if opts.cancel.is_some_and(|c| c.load(Ordering::Relaxed)) { + out.cancelled = true; + break; + } + let Ok(node) = graph.node(id) else { continue }; + let r = cook_node(pkg, graph, node, &out, &vars, opts, cache); + out.nodes.insert(id, r); + } + out.ms = (now_ms() - t0) as f32; + out +} + +fn cook_node(pkg: &Package, graph: &Graph, node: &Node, done: &Cooked, vars: &BTreeMap, opts: &Options, cache: &mut Cache) -> NodeResult { + let (in_ports, out_ports) = ports(pkg, node); + let def = find(&node.def); + // Gather inputs by port order, with their keys. + let mut inputs: Vec> = Vec::with_capacity(in_ports.len()); + let mut in_keys: Vec = Vec::with_capacity(in_ports.len()); + for p in &in_ports { + let src = graph.input_of(node.id, &p.id).and_then(|c| { + let r = done.nodes.get(&c.from)?; + let from = graph.node(c.from).ok()?; + let idx = ports(pkg, from).1.iter().position(|o| o.id == c.from_port)?; + Some((r.outputs.get(idx)?.clone(), r.key ^ hash_of(&idx))) + }); + in_keys.push(src.as_ref().map_or(0, |s| s.1)); + inputs.push(src.map(|s| s.0)); + } + let first = inputs.iter().flatten().next().map(|i| (i.w, i.h)); + let (w, h) = node_size(graph, def, node, first, opts.max_size); + let fail = |msg: String, key: u64| NodeResult { + outputs: Arc::new(vec![error_image(w, h); out_ports.len().max(1)]), + error: Some(msg), + ms: 0.0, + key, + cached: false, + }; + // Parameters: defaults, overrides, then bindings to exposed inputs. + let mut params = match def { + Some(d) if node.def != "graph_instance" => resolve_params(d, &node.params), + _ => node.params.clone(), + }; + for (param, exposed) in &node.bindings { + if let (Some(v), Some(cur)) = (vars.get(exposed), params.get(param)) + && let Some(c) = cur.coerce_json(&serde_json::to_value(v).unwrap_or_default()) + { + params.insert(param.clone(), c); + } + } + let seed = (graph.seed as u32).wrapping_mul(0x9e37_79b9).wrapping_add(node.base.seed as u32); + let tile = node.base.tiling[0] && node.base.tiling[1]; + // Input nodes read the caller's image for their identifier. + let input_img = node.def.starts_with("input_").then(|| opts.inputs.get(&identifier(node))).flatten(); + let res_hash = match params.get("resource") { + Some(Value::Text(name)) => pkg.resource(name).map_or(0, |r| hash_of(&(r.bytes.len(), r.bytes.get(..64.min(r.bytes.len())).map(|b| b.to_vec())))), + _ => 0, + }; + let sub_hash = + if node.def == "graph_instance" { instance_graph(pkg, node).map_or(0, |(_, g)| hash_of(&serde_json::to_string(g).unwrap_or_default())) } else { 0 }; + let key = hash_of(&( + &node.def, + serde_json::to_string(¶ms).unwrap_or_default(), + (w, h, seed, tile, node.disabled), + &in_keys, + res_hash, + sub_hash, + input_img.map(|i| (i.w, i.h, Arc::as_ptr(&i.data) as usize)), + serde_json::to_string(vars).unwrap_or_default(), + )); + if let Some(v) = cache.get(key) { + return NodeResult { outputs: v, error: None, ms: 0.0, key, cached: true }; + } + let t0 = now_ms(); + let result: Result, String> = if node.disabled { + Ok(vec![inputs.iter().flatten().next().cloned().unwrap_or_else(|| Image::filled(w, h, Kind::Gray, [0.0; 4])); out_ports.len().max(1)]) + } else if let Some(img) = input_img { + Ok(vec![img.resize(w, h, tile)]) + } else if node.def == "graph_instance" { + cook_instance(pkg, node, &in_ports, &out_ports, &inputs, ¶ms, (w, h), opts, cache) + } else if let Some(d) = def { + let ctx = Ctx { w, h, seed, tile, inputs: &inputs, params: ¶ms, resource: opts.resource, vars }; + (d.cook)(&ctx) + } else { + Err(format!("unknown node `{}`", node.def)) + }; + match result { + Ok(imgs) if imgs.len() == out_ports.len().max(1) || out_ports.is_empty() => { + let v = Arc::new(imgs); + cache.put(key, v.clone()); + NodeResult { outputs: v, error: None, ms: (now_ms() - t0) as f32, key, cached: false } + } + Ok(imgs) => fail(format!("`{}` made {} images for {} outputs", node.def, imgs.len(), out_ports.len()), key), + Err(e) => fail(e, key), + } +} + +fn cook_instance( + pkg: &Package, + node: &Node, + in_ports: &[Port], + out_ports: &[Port], + inputs: &[Option], + params: &BTreeMap, + size: (u32, u32), + opts: &Options, + cache: &mut Cache, +) -> Result, String> { + if opts.depth >= MAX_DEPTH { + return Err("graph instances nest too deep (does a graph use itself?)".into()); + } + let (gi, sub) = instance_graph(pkg, node).ok_or("the instanced graph does not exist")?; + let mut o = Options::new(opts.resource); + o.max_size = opts.max_size; + o.cancel = opts.cancel; + o.depth = opts.depth + 1; + o.inputs = in_ports.iter().zip(inputs).filter_map(|(p, i)| Some((p.id.clone(), i.clone()?))).collect(); + o.overrides = params.iter().filter(|(k, _)| sub.exposed.iter().any(|e| &e.id == *k)).map(|(k, v)| (k.clone(), v.clone())).collect(); + let cooked = cook(pkg, gi, &o, cache); + if cooked.cancelled { + return Err("cancelled".into()); + } + Ok(out_ports + .iter() + .map(|p| { + sub.nodes + .iter() + .find(|n| n.def == "output" && identifier(n) == p.id) + .and_then(|n| cooked.image(n.id, 0)) + .map(|i| i.resize(size.0, size.1, true)) + .unwrap_or_else(|| Image::filled(size.0, size.1, Kind::Gray, [0.0; 4])) + }) + .collect()) +} + +/// The graph's output nodes with their usage id and image, in node order. +pub fn outputs<'c>(graph: &Graph, cooked: &'c Cooked) -> Vec<(NodeId, &'static str, String, Option<&'c Image>)> { + graph + .nodes + .iter() + .filter(|n| n.def == "output") + .map(|n| { + let usage = n.params.get("usage").and_then(Value::as_i32).unwrap_or(0).clamp(0, materialcraft_nodes::atomic::USAGE_IDS.len() as i32 - 1) as usize; + (n.id, materialcraft_nodes::atomic::USAGE_IDS.get(usage).copied().unwrap_or("any"), identifier(n), cooked.image(n.id, 0)) + }) + .collect() +} + +/// Milliseconds since the first call (0 on the web, where `std::time::Instant` is unavailable). +pub fn now_ms() -> f64 { + #[cfg(not(target_arch = "wasm32"))] + { + static START: std::sync::OnceLock = std::sync::OnceLock::new(); + START.get_or_init(std::time::Instant::now).elapsed().as_secs_f64() * 1000.0 + } + #[cfg(target_arch = "wasm32")] + 0.0 +} + +#[cfg(test)] +mod tests { + use super::*; + use materialcraft_core::Graph; + + fn no_res(_: &str) -> Option { + None + } + + fn sample() -> (Package, NodeId, NodeId, NodeId) { + let mut g = Graph::new("g"); + g.size = [6, 6]; + let noise = g.add_node("perlin_noise", [0.0, 0.0]); + let blur = g.add_node("blur", [150.0, 0.0]); + let out = g.add_node("output", [300.0, 0.0]); + g.connect(noise, "output", blur, "input").unwrap(); + g.connect(blur, "output", out, "input").unwrap(); + let mut p = Package::new("p"); + p.graphs.push(g); + (p, noise, blur, out) + } + + #[test] + fn cooks_and_caches() { + let (mut p, noise, blur, out) = sample(); + let mut cache = Cache::default(); + let opts = Options::new(&no_res); + let a = cook(&p, 0, &opts, &mut cache); + assert!(a.nodes.values().all(|r| r.error.is_none() && !r.cached)); + assert_eq!(a.image(out, 0).map(|i| (i.w, i.h)), Some((64, 64))); + // Same graph: everything from the cache. + let b = cook(&p, 0, &opts, &mut cache); + assert!(b.nodes.values().all(|r| r.cached)); + // Editing the blur re-cooks the blur and the output, not the noise. + p.graphs[0].node_mut(blur).unwrap().params.insert("intensity".into(), Value::Float(5.0)); + let c = cook(&p, 0, &opts, &mut cache); + assert!(c.nodes[&noise].cached && !c.nodes[&blur].cached && !c.nodes[&out].cached); + assert_eq!(outputs(&p.graphs[0], &c).len(), 1); + } + + #[test] + fn preview_cap_and_unknown_nodes() { + let (mut p, _, _, out) = sample(); + p.graphs[0].size = [10, 10]; + let bad = p.graphs[0].add_node("no_such_node", [0.0, 0.0]); + let mut cache = Cache::default(); + let mut opts = Options::new(&no_res); + opts.max_size = Some(128); + let c = cook(&p, 0, &opts, &mut cache); + assert_eq!(c.image(out, 0).map(|i| i.w), Some(128)); + assert!(c.nodes[&bad].error.is_some()); + } + + #[test] + fn graph_instances_cook_their_subgraph() { + let (mut p, ..) = sample(); + // A second graph: input → invert → output, instanced from the first. + let mut sub = Graph::new("inv"); + sub.size = [6, 6]; + let i = sub.add_node("input_grayscale", [0.0, 0.0]); + let inv = sub.add_node("invert", [100.0, 0.0]); + let o = sub.add_node("output", [200.0, 0.0]); + sub.connect(i, "output", inv, "input").unwrap(); + sub.connect(inv, "output", o, "input").unwrap(); + p.graphs.push(sub); + let g = &mut p.graphs[0]; + let u = g.add_node("uniform", [0.0, 100.0]); + g.node_mut(u).unwrap().params.insert("mode".into(), Value::Enum(1)); + g.node_mut(u).unwrap().params.insert("color".into(), Value::Color([0.25, 0.25, 0.25, 1.0])); + let inst = g.add_node("graph_instance", [100.0, 100.0]); + g.node_mut(inst).unwrap().params.insert("graph".into(), Value::Text("inv".into())); + g.connect(u, "output", inst, "input").unwrap(); + // A graph instancing itself is refused, not a stack overflow. + let selfi = g.add_node("graph_instance", [0.0, 200.0]); + g.node_mut(selfi).unwrap().params.insert("graph".into(), Value::Text("g".into())); + let mut cache = Cache::default(); + let c = cook(&p, 0, &Options::new(&no_res), &mut cache); + let img = c.image(inst, 0).unwrap(); + assert!((img.data[0] - (1.0 - 0.0722 * 0.25 - 0.2126 * 0.25 - 0.7152 * 0.25)).abs() < 1e-4, "{}", img.data[0]); + assert!(c.nodes[&selfi].error.is_some() || c.nodes[&selfi].outputs.len() == 1); + } +} diff --git a/crates/formats/Cargo.toml b/crates/formats/Cargo.toml new file mode 100644 index 00000000..984ad3a4 --- /dev/null +++ b/crates/formats/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "materialcraft-formats" +description = "MaterialCraft file formats: .mcraft packages, bitmap import, texture export" +version.workspace = true +edition.workspace = true +license.workspace = true + +[lints] +workspace = true + +[dependencies] +materialcraft-core = { workspace = true } +materialcraft-image = { workspace = true } +image = { workspace = true } +serde_json = { workspace = true } +thiserror = { workspace = true } +zip = { workspace = true } diff --git a/crates/formats/src/lib.rs b/crates/formats/src/lib.rs new file mode 100644 index 00000000..24b2a86b --- /dev/null +++ b/crates/formats/src/lib.rs @@ -0,0 +1,271 @@ +//! # materialcraft-formats +//! +//! File formats, L2: the native `.mcraft` package (a zip holding `package.json` and the embedded +//! `resources/`), bitmap decoding for Bitmap nodes, and texture export (PNG 8/16, JPEG, TGA, +//! TIFF 8/16, BMP, WEBP, EXR 32F, HDR) with the output naming pattern. Byte-based APIs work +//! everywhere, including the browser; path helpers are native only. +#![forbid(unsafe_code)] +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +use std::io::{Cursor, Read, Write}; +use std::sync::Arc; + +use materialcraft_core::{OutputFormat, Package}; +use materialcraft_image::{Image, Kind, MAX_SIDE, linear_to_srgb, srgb_to_linear}; + +#[derive(Debug, thiserror::Error)] +pub enum FormatError { + #[error("not a MaterialCraft package: {0}")] + BadPackage(String), + #[error("image: {0}")] + Image(String), + #[error("I/O: {0}")] + Io(String), +} + +pub type Result = std::result::Result; + +/// Largest `package.json` and resource accepted when reading (allocation caps). +const MAX_JSON: u64 = 64 << 20; +const MAX_RESOURCE: u64 = 256 << 20; + +/// Export file types: (extension, label). +pub const EXPORT_FORMATS: &[(&str, &str)] = + &[("png", "PNG"), ("jpg", "JPEG"), ("tga", "TGA"), ("tif", "TIFF"), ("bmp", "BMP"), ("webp", "WEBP"), ("exr", "OpenEXR"), ("hdr", "Radiance HDR")]; + +/// Image file extensions [`decode`] reads. +pub const IMAGE_EXTENSIONS: &[&str] = &["png", "jpg", "jpeg", "tga", "tif", "tiff", "bmp", "webp", "exr", "hdr"]; + +/// Write a package to `.mcraft` bytes. +pub fn save_package(pkg: &Package) -> Result> { + let json = serde_json::to_vec_pretty(pkg).map_err(|e| FormatError::Io(e.to_string()))?; + let mut buf = Cursor::new(Vec::new()); + { + let mut z = zip::ZipWriter::new(&mut buf); + let opts = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated); + let io = |e: zip::result::ZipError| FormatError::Io(e.to_string()); + z.start_file("package.json", opts).map_err(io)?; + z.write_all(&json).map_err(|e| FormatError::Io(e.to_string()))?; + for r in &pkg.resources { + // Images are already compressed. + let stored = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored); + z.start_file(format!("resources/{}", safe_file_name(&r.file)), stored).map_err(io)?; + z.write_all(&r.bytes).map_err(|e| FormatError::Io(e.to_string()))?; + } + z.finish().map_err(io)?; + } + Ok(buf.into_inner()) +} + +/// Read a package from `.mcraft` bytes. +pub fn load_package(bytes: &[u8]) -> Result { + let mut z = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|e| FormatError::BadPackage(e.to_string()))?; + let mut json = Vec::new(); + z.by_name("package.json") + .map_err(|_| FormatError::BadPackage("package.json is missing".into()))? + .take(MAX_JSON) + .read_to_end(&mut json) + .map_err(|e| FormatError::Io(e.to_string()))?; + let mut pkg: Package = serde_json::from_slice(&json).map_err(|e| FormatError::BadPackage(e.to_string()))?; + for r in &mut pkg.resources { + let name = format!("resources/{}", safe_file_name(&r.file)); + let mut data = Vec::new(); + if let Ok(mut f) = z.by_name(&name) { + f.by_ref().take(MAX_RESOURCE).read_to_end(&mut data).map_err(|e| FormatError::Io(e.to_string()))?; + } + r.bytes = Arc::new(data); + } + Ok(pkg) +} + +/// A file name with no path parts (resources live flat in `resources/`). +pub fn safe_file_name(name: &str) -> String { + let base = name.rsplit(['/', '\\']).next().unwrap_or(name); + let cleaned: String = base.chars().map(|c| if c.is_alphanumeric() || "._- ".contains(c) { c } else { '_' }).collect(); + let cleaned = cleaned.trim_start_matches('.').to_string(); + if cleaned.is_empty() { "resource".into() } else { cleaned } +} + +/// Decode image file bytes into a linear float image (8-bit color is sRGB-decoded; grayscale +/// files stay grayscale). +pub fn decode(bytes: &[u8]) -> Result { + // TGA has no signature: try it when the format cannot be guessed. + let img = image::load_from_memory(bytes) + .or_else(|e| image::load_from_memory_with_format(bytes, image::ImageFormat::Tga).map_err(|_| e)) + .map_err(|e| FormatError::Image(e.to_string()))?; + let (w, h) = (img.width(), img.height()); + if w == 0 || h == 0 || w > MAX_SIDE || h > MAX_SIDE { + return Err(FormatError::Image(format!("{w}x{h} is outside 1..={MAX_SIDE} pixels"))); + } + let gray = matches!(img.color(), image::ColorType::L8 | image::ColorType::L16 | image::ColorType::La8 | image::ColorType::La16); + let float = matches!(img.color(), image::ColorType::Rgb32F | image::ColorType::Rgba32F); + if gray { + let l = img.into_luma16(); + let data: Vec = l.pixels().map(|p| p.0[0] as f32 / 65535.0).collect(); + return Ok(Image { w, h, kind: Kind::Gray, data: Arc::new(data) }); + } + let rgba = img.into_rgba32f(); + let data: Vec = rgba + .pixels() + .flat_map(|p| { + let [r, g, b, a] = p.0; + if float { [r, g, b, a] } else { [srgb_to_linear(r), srgb_to_linear(g), srgb_to_linear(b), a] } + }) + .collect(); + Ok(Image { w, h, kind: Kind::Color, data: Arc::new(data) }) +} + +/// Bit depth for export. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Depth { + U8, + U16, + F32, +} + +impl Depth { + pub fn from_format(f: OutputFormat) -> Depth { + match f { + OutputFormat::U8 => Depth::U8, + OutputFormat::F16 | OutputFormat::F32 => Depth::F32, + _ => Depth::U16, + } + } +} + +/// Encode `img` as `ext` (see [`EXPORT_FORMATS`]). `srgb`: color values are written through the +/// sRGB curve (base color); data maps (normal, roughness…) are written linear. +pub fn encode(img: &Image, ext: &str, depth: Depth, srgb: bool) -> Result> { + let ext = ext.trim_start_matches('.').to_ascii_lowercase(); + let enc = |v: f32| if srgb && img.kind == Kind::Color { linear_to_srgb(v) } else { v }; + let (w, h) = (img.w, img.h); + let color = img.kind == Kind::Color; + let px = |i: usize| -> [f32; 4] { + if color { + let s = img.data.get(i * 4..i * 4 + 4).unwrap_or(&[0.0, 0.0, 0.0, 1.0]); + [enc(s[0]), enc(s[1]), enc(s[2]), s[3]] + } else { + let v = img.data.get(i).copied().unwrap_or(0.0); + [v, v, v, 1.0] + } + }; + let n = (w * h) as usize; + let fmt = match ext.as_str() { + "png" => image::ImageFormat::Png, + "jpg" | "jpeg" => image::ImageFormat::Jpeg, + "tga" => image::ImageFormat::Tga, + "tif" | "tiff" => image::ImageFormat::Tiff, + "bmp" => image::ImageFormat::Bmp, + "webp" => image::ImageFormat::WebP, + "exr" => image::ImageFormat::OpenExr, + "hdr" => image::ImageFormat::Hdr, + other => return Err(FormatError::Image(format!("unsupported export format `{other}`"))), + }; + let float_only = matches!(fmt, image::ImageFormat::OpenExr | image::ImageFormat::Hdr); + let sixteen_ok = matches!(fmt, image::ImageFormat::Png | image::ImageFormat::Tiff); + let q8 = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; + let q16 = |v: f32| (v.clamp(0.0, 1.0) * 65535.0 + 0.5) as u16; + let dynimg: image::DynamicImage = if float_only { + let data: Vec = (0..n) + .flat_map(|i| { + let p = px(i); + [p[0], p[1], p[2]] + }) + .collect(); + let buf = image::Rgb32FImage::from_raw(w, h, data).ok_or_else(|| FormatError::Image("bad buffer".into()))?; + buf.into() + } else if depth != Depth::U8 && sixteen_ok { + if color { + let data: Vec = (0..n).flat_map(|i| px(i).map(q16)).collect(); + image::ImageBuffer::, _>::from_raw(w, h, data).ok_or_else(|| FormatError::Image("bad buffer".into()))?.into() + } else { + let data: Vec = (0..n).map(|i| q16(px(i)[0])).collect(); + image::ImageBuffer::, _>::from_raw(w, h, data).ok_or_else(|| FormatError::Image("bad buffer".into()))?.into() + } + } else if color && !matches!(fmt, image::ImageFormat::Jpeg) { + let data: Vec = (0..n).flat_map(|i| px(i).map(q8)).collect(); + image::RgbaImage::from_raw(w, h, data).ok_or_else(|| FormatError::Image("bad buffer".into()))?.into() + } else if color { + let data: Vec = (0..n) + .flat_map(|i| { + let p = px(i); + [q8(p[0]), q8(p[1]), q8(p[2])] + }) + .collect(); + image::RgbImage::from_raw(w, h, data).ok_or_else(|| FormatError::Image("bad buffer".into()))?.into() + } else { + let data: Vec = (0..n).map(|i| q8(px(i)[0])).collect(); + image::GrayImage::from_raw(w, h, data).ok_or_else(|| FormatError::Image("bad buffer".into()))?.into() + }; + let mut out = Cursor::new(Vec::new()); + dynimg.write_to(&mut out, fmt).map_err(|e| FormatError::Image(e.to_string()))?; + Ok(out.into_inner()) +} + +/// The file stem of an exported output: `pattern` with `$(graph)`, `$(identifier)` and +/// `$(usage)` replaced, sanitized for file systems. +pub fn output_name(pattern: &str, graph: &str, identifier: &str, usage: &str) -> String { + let s = pattern.replace("$(graph)", graph).replace("$(identifier)", identifier).replace("$(usage)", usage); + safe_file_name(&s) +} + +/// Write `bytes` to `path` through a temporary file and a rename, so a failed write never leaves +/// a truncated file behind. +#[cfg(not(target_arch = "wasm32"))] +pub fn write_atomic(path: &std::path::Path, bytes: &[u8]) -> Result<()> { + let tmp = path.with_extension(format!("{}.tmp", path.extension().and_then(|e| e.to_str()).unwrap_or("out"))); + std::fs::write(&tmp, bytes).map_err(|e| FormatError::Io(format!("{}: {e}", tmp.display())))?; + std::fs::rename(&tmp, path).map_err(|e| { + let _ = std::fs::remove_file(&tmp); + FormatError::Io(format!("{}: {e}", path.display())) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use materialcraft_core::{Graph, Resource}; + + #[test] + fn package_round_trip() { + let mut p = Package::new("Test"); + let mut g = Graph::new("Bricks"); + let a = g.add_node("brick_generator", [0.0, 0.0]); + let o = g.add_node("output", [200.0, 0.0]); + g.connect(a, "output", o, "input").unwrap(); + p.graphs.push(g); + let png = encode(&Image::filled(4, 4, Kind::Color, [1.0, 0.5, 0.0, 1.0]), "png", Depth::U8, true).unwrap(); + p.resources.push(Resource { name: "tex".into(), file: "../../evil/tex.png".into(), bytes: Arc::new(png) }); + let bytes = save_package(&p).unwrap(); + let q = load_package(&bytes).unwrap(); + assert_eq!(q.graphs, p.graphs); + assert_eq!(q.resources[0].bytes, p.resources[0].bytes); + let img = decode(&q.resources[0].bytes).unwrap(); + assert!((img.get(0, 0, false)[1] - 0.5).abs() < 0.01); + assert!(load_package(b"not a zip").is_err()); + } + + #[test] + fn export_every_format() { + let img = Image::generate(8, 8, Kind::Color, |x, y| [x as f32 / 7.0, y as f32 / 7.0, 0.5, 1.0]); + let gray = img.to_gray(); + for (ext, _) in EXPORT_FORMATS { + for depth in [Depth::U8, Depth::U16, Depth::F32] { + for i in [&img, &gray] { + let b = encode(i, ext, depth, true).unwrap_or_else(|e| panic!("{ext}: {e}")); + let back = decode(&b).unwrap_or_else(|e| panic!("{ext} decode: {e}")); + assert_eq!((back.w, back.h), (8, 8)); + } + } + } + let png16 = encode(&gray, "png", Depth::U16, false).unwrap(); + assert!((decode(&png16).unwrap().get(7, 0, false)[0] - gray.get(7, 0, false)[0]).abs() < 1e-3); + } + + #[test] + fn names_are_safe() { + assert_eq!(output_name("$(graph)_$(usage)", "Bricks", "out", "baseColor"), "Bricks_baseColor"); + assert_eq!(safe_file_name("../../etc/passwd"), "passwd"); + assert_eq!(safe_file_name(".."), "resource"); + } +} diff --git a/crates/geom/Cargo.toml b/crates/geom/Cargo.toml new file mode 100644 index 00000000..df16a735 --- /dev/null +++ b/crates/geom/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "materialcraft-geom" +description = "MaterialCraft geometry: meshes, primitives, tangents, BVH ray casts, UV G-buffer, camera" +version.workspace = true +edition.workspace = true +license.workspace = true + +[lints] +workspace = true + +[dependencies] +glam = { workspace = true } +rayon = { workspace = true } +serde = { workspace = true } +thiserror = { workspace = true } +mikktspace = { workspace = true } diff --git a/crates/geom/src/bvh.rs b/crates/geom/src/bvh.rs new file mode 100644 index 00000000..695ee0a9 --- /dev/null +++ b/crates/geom/src/bvh.rs @@ -0,0 +1,494 @@ +//! Bounding volume hierarchy over a mesh's triangles: closest-hit and any-hit ray casts, and +//! box queries (used by picking, baking and brush stamps). + +use glam::{Vec3, Vec3A}; + +use crate::Mesh; + +#[derive(Clone, Copy, Debug)] +struct Node { + lo: Vec3A, + hi: Vec3A, + /// Leaf: first triangle in `order`; inner: index of the left child (right = left + 1). + first: u32, + /// Triangles in a leaf; 0 for inner nodes. + count: u32, +} + +/// A ray hit: distance, triangle and barycentrics (weights of vertices 1 and 2). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Hit { + pub t: f32, + pub tri: u32, + pub u: f32, + pub v: f32, +} + +#[derive(Clone, Debug)] +pub struct Bvh { + nodes: Vec, + /// Triangle vertices in BVH order. + tris: Vec<[Vec3; 3]>, + /// Original triangle index of each entry in `tris`. + order: Vec, +} + +const LEAF: usize = 4; + +/// Traversal stack of (node, entry distance): inline for typical depths (no allocation per +/// ray), spilling to the heap for degenerate trees. +struct Stack { + inline: [(u32, f32); 64], + len: usize, + spill: Vec<(u32, f32)>, +} + +impl Default for Stack { + fn default() -> Self { + Stack { inline: [(0, 0.0); 64], len: 0, spill: Vec::new() } + } +} + +impl Stack { + fn push(&mut self, v: (u32, f32)) { + match self.inline.get_mut(self.len) { + Some(slot) if self.spill.is_empty() => { + *slot = v; + self.len += 1; + } + _ => self.spill.push(v), + } + } + + fn pop(&mut self) -> Option<(u32, f32)> { + self.spill.pop().or_else(|| { + self.len = self.len.checked_sub(1)?; + self.inline.get(self.len).copied() + }) + } +} +const BINS: usize = 12; + +fn grow(lo: &mut Vec3, hi: &mut Vec3, p: Vec3) { + *lo = lo.min(p); + *hi = hi.max(p); +} + +fn area(lo: Vec3, hi: Vec3) -> f32 { + let d = (hi - lo).max(Vec3::ZERO); + d.x * d.y + d.y * d.z + d.z * d.x +} + +impl Bvh { + pub fn new(mesh: &Mesh) -> Bvh { + let n = mesh.triangle_count(); + let mut tris = Vec::with_capacity(n); + for t in 0..n { + let Some([a, b, c]) = mesh.tri(t) else { continue }; + let p = |i: usize| mesh.positions.get(i).copied().unwrap_or(Vec3::ZERO); + tris.push([p(a), p(b), p(c)]); + } + let mut order: Vec = (0..tris.len() as u32).collect(); + let cent: Vec = tris.iter().map(|t| (t[0] + t[1] + t[2]) / 3.0).collect(); + let mut nodes = vec![Node { lo: Vec3A::ZERO, hi: Vec3A::ZERO, first: 0, count: tris.len() as u32 }]; + let mut stack = vec![0usize]; + while let Some(ni) = stack.pop() { + let Node { first, count, .. } = nodes[ni]; + let (f, c) = (first as usize, count as usize); + let (mut lo, mut hi) = (Vec3::splat(f32::MAX), Vec3::splat(f32::MIN)); + let (mut clo, mut chi) = (Vec3::splat(f32::MAX), Vec3::splat(f32::MIN)); + for &t in &order[f..f + c] { + for p in tris[t as usize] { + grow(&mut lo, &mut hi, p); + } + grow(&mut clo, &mut chi, cent[t as usize]); + } + nodes[ni].lo = lo.into(); + nodes[ni].hi = hi.into(); + if c <= LEAF { + continue; + } + // Binned SAH along the widest centroid axis. + let ext = chi - clo; + let axis = if ext.x >= ext.y && ext.x >= ext.z { + 0 + } else if ext.y >= ext.z { + 1 + } else { + 2 + }; + if ext[axis] <= 1e-12 { + continue; + } + let mut bins = [(0u32, Vec3::splat(f32::MAX), Vec3::splat(f32::MIN)); BINS]; + let bin_of = |p: Vec3| (((p[axis] - clo[axis]) / ext[axis] * BINS as f32) as usize).min(BINS - 1); + for &t in &order[f..f + c] { + let b = &mut bins[bin_of(cent[t as usize])]; + b.0 += 1; + for p in tris[t as usize] { + grow(&mut b.1, &mut b.2, p); + } + } + let (mut best, mut best_cost) = (0usize, f32::MAX); + for split in 1..BINS { + let side = |r: std::ops::Range| { + r.fold((0u32, Vec3::splat(f32::MAX), Vec3::splat(f32::MIN)), |(n, l, h), i| (n + bins[i].0, l.min(bins[i].1), h.max(bins[i].2))) + }; + let (nl, ll, lh) = side(0..split); + let (nr, rl, rh) = side(split..BINS); + if nl == 0 || nr == 0 { + continue; + } + let cost = nl as f32 * area(ll, lh) + nr as f32 * area(rl, rh); + if cost < best_cost { + best_cost = cost; + best = split; + } + } + if best == 0 || best_cost >= c as f32 * area(lo, hi) { + continue; + } + let slice = &mut order[f..f + c]; + let mut i = 0; + for j in 0..slice.len() { + if bin_of(cent[slice[j] as usize]) < best { + slice.swap(i, j); + i += 1; + } + } + if i == 0 || i == c { + continue; + } + let left = nodes.len(); + nodes.push(Node { lo: Vec3A::ZERO, hi: Vec3A::ZERO, first, count: i as u32 }); + nodes.push(Node { lo: Vec3A::ZERO, hi: Vec3A::ZERO, first: first + i as u32, count: (c - i) as u32 }); + nodes[ni].first = left as u32; + nodes[ni].count = 0; + stack.push(left); + stack.push(left + 1); + } + let tris = order.iter().map(|t| tris[*t as usize]).collect(); + Bvh { nodes, tris, order } + } + + pub fn is_empty(&self) -> bool { + self.tris.is_empty() + } + + /// The flattened tree (for GPU traversal), root first: bounds, then for a leaf the range + /// `first..first + count` of [`Bvh::triangles`], for an inner node (`count` 0) the children + /// `first` and `first + 1`. + pub fn nodes(&self) -> impl ExactSizeIterator + '_ { + self.nodes.iter().map(|n| (n.lo.into(), n.hi.into(), n.first, n.count)) + } + + /// Triangle vertices in BVH order, and the original triangle index of each. + pub fn triangles(&self) -> (&[[Vec3; 3]], &[u32]) { + (&self.tris, &self.order) + } + + fn slab(lo: Vec3A, hi: Vec3A, o: Vec3A, inv: Vec3A, tmax: f32) -> Option { + let t0 = (lo - o) * inv; + let t1 = (hi - o) * inv; + // A ray lying in a slab plane gives 0·∞ = NaN: it is inside that slab, so the axis does + // not bound the hit. + let open = t0.is_nan_mask() | t1.is_nan_mask(); + let tn = Vec3A::select(open, Vec3A::NEG_INFINITY, t0.min(t1)).max_element().max(0.0); + let tf = Vec3A::select(open, Vec3A::INFINITY, t0.max(t1)).min_element().min(tmax); + (tn <= tf).then_some(tn) + } + + /// Möller–Trumbore, double sided. + fn hit_tri(t: &[Vec3; 3], o: Vec3, d: Vec3) -> Option<(f32, f32, f32)> { + let e1 = t[1] - t[0]; + let e2 = t[2] - t[0]; + let p = d.cross(e2); + let det = e1.dot(p); + if det.abs() < 1e-12 { + return None; + } + let inv = 1.0 / det; + let s = o - t[0]; + // A little slack on the edges: rays through a shared edge must not slip between its + // two triangles to a surface behind. + const EDGE: f32 = 1e-5; + let u = s.dot(p) * inv; + if !(-EDGE..=1.0 + EDGE).contains(&u) { + return None; + } + let q = s.cross(e1); + let v = d.dot(q) * inv; + if v < -EDGE || u + v > 1.0 + EDGE { + return None; + } + let tt = e2.dot(q) * inv; + (tt > 0.0).then_some((tt, u, v)) + } + + fn traverse(&self, o: Vec3, d: Vec3, mut tmax: f32, any: bool, filter: &dyn Fn(u32) -> bool) -> Option { + let root = self.nodes.first().filter(|_| !self.tris.is_empty())?; + let (oa, inv) = (Vec3A::from(o), Vec3A::ONE / Vec3A::from(d)); + let mut best = None; + let mut stack = Stack::default(); + stack.push((0, Self::slab(root.lo, root.hi, oa, inv, tmax)?)); + // Entries carry their entry distance: nodes behind a closer hit are skipped unopened. + while let Some((ni, tn)) = stack.pop() { + let Some(n) = self.nodes.get(ni as usize).filter(|_| tn <= tmax) else { continue }; + if n.count > 0 { + let (f, c) = (n.first as usize, n.count as usize); + for i in f..(f + c).min(self.tris.len()) { + let (Some(tri), Some(&orig)) = (self.tris.get(i), self.order.get(i)) else { continue }; + if let Some((t, u, v)) = Self::hit_tri(tri, o, d) + && t < tmax + && filter(orig) + { + tmax = t; + best = Some(Hit { t, tri: orig, u, v }); + if any { + return best; + } + } + } + } else { + // Visit the nearer child first. + let (l, r) = (n.first, n.first + 1); + let dl = self.nodes.get(l as usize).and_then(|c| Self::slab(c.lo, c.hi, oa, inv, tmax)); + let dr = self.nodes.get(r as usize).and_then(|c| Self::slab(c.lo, c.hi, oa, inv, tmax)); + match (dl, dr) { + (Some(a), Some(b)) if a <= b => { + stack.push((r, b)); + stack.push((l, a)); + } + (Some(a), Some(b)) => { + stack.push((l, a)); + stack.push((r, b)); + } + (Some(a), None) => stack.push((l, a)), + (None, Some(b)) => stack.push((r, b)), + (None, None) => {} + } + } + } + best + } + + /// Closest hit along `o + t·d` for `t` in (0, tmax). + pub fn closest(&self, o: Vec3, d: Vec3, tmax: f32) -> Option { + self.traverse(o, d, tmax, false, &|_| true) + } + + /// Closest hit on triangles accepted by `filter` (original triangle index). + pub fn closest_filtered(&self, o: Vec3, d: Vec3, tmax: f32, filter: &dyn Fn(u32) -> bool) -> Option { + self.traverse(o, d, tmax, false, filter) + } + + /// Whether anything is hit before `tmax` (occlusion rays). + pub fn occluded(&self, o: Vec3, d: Vec3, tmax: f32) -> bool { + self.traverse(o, d, tmax, true, &|_| true).is_some() + } + + /// The point nearest to `p` within `max_dist` on a triangle accepted by `filter` (original + /// index): a [`Hit`] with the distance in `t` and the barycentrics of vertices 1 and 2. + pub fn nearest(&self, p: Vec3, max_dist: f32, filter: &dyn Fn(u32) -> bool) -> Option { + let root = self.nodes.first().filter(|_| !self.tris.is_empty() && p.is_finite())?; + let pa = Vec3A::from(p); + let box_d2 = |n: &Node| (n.lo - pa).max(pa - n.hi).max(Vec3A::ZERO).length_squared(); + let (mut best_d2, mut best) = (max_dist * max_dist, None); + let mut stack = Stack::default(); + stack.push((0, box_d2(root))); + while let Some((ni, d2)) = stack.pop() { + let Some(n) = self.nodes.get(ni as usize).filter(|_| d2 <= best_d2) else { continue }; + if n.count > 0 { + for i in n.first as usize..(n.first as usize + n.count as usize).min(self.tris.len()) { + let (Some(tri), Some(&orig)) = (self.tris.get(i), self.order.get(i)) else { continue }; + if !filter(orig) { + continue; + } + let (q, u, v) = closest_on_triangle(p, tri); + let dd = (q - p).length_squared(); + if dd < best_d2 { + best_d2 = dd; + best = Some(Hit { t: dd.sqrt(), tri: orig, u, v }); + } + } + } else { + // Push the farther child first so the nearer one is searched first. + let child = |c: u32| self.nodes.get(c as usize).map(|n| (c, box_d2(n))); + let (Some(l), Some(r)) = (child(n.first), child(n.first + 1)) else { continue }; + let (near, far) = if l.1 <= r.1 { (l, r) } else { (r, l) }; + stack.push(far); + stack.push(near); + } + } + best + } + + /// Call `f` with every triangle (original index) whose bounds overlap the box. + pub fn query_box(&self, lo: Vec3, hi: Vec3, mut f: impl FnMut(u32)) { + let mut stack = vec![0u32]; + while let Some(i) = stack.pop() { + let Some(n) = self.nodes.get(i as usize) else { continue }; + if self.tris.is_empty() || n.hi.cmplt(lo.into()).any() || n.lo.cmpgt(hi.into()).any() { + continue; + } + if n.count > 0 { + for k in n.first as usize..(n.first + n.count) as usize { + let (Some(t), Some(o)) = (self.tris.get(k), self.order.get(k)) else { continue }; + let tlo = t[0].min(t[1]).min(t[2]); + let thi = t[0].max(t[1]).max(t[2]); + if !(thi.cmplt(lo).any() || tlo.cmpgt(hi).any()) { + f(*o); + } + } + } else { + stack.push(n.first); + stack.push(n.first + 1); + } + } + } +} + +/// The point of triangle `t` nearest to `p` and its barycentrics (weights of vertices 1 and 2), +/// by Voronoi region (Ericson, Real-Time Collision Detection, 5.1.5). Degenerate triangles give +/// a non-finite distance and are never nearest. +fn closest_on_triangle(p: Vec3, t: &[Vec3; 3]) -> (Vec3, f32, f32) { + let [a, b, c] = *t; + let (ab, ac, ap) = (b - a, c - a, p - a); + let (d1, d2) = (ab.dot(ap), ac.dot(ap)); + if d1 <= 0.0 && d2 <= 0.0 { + return (a, 0.0, 0.0); + } + let bp = p - b; + let (d3, d4) = (ab.dot(bp), ac.dot(bp)); + if d3 >= 0.0 && d4 <= d3 { + return (b, 1.0, 0.0); + } + let vc = d1 * d4 - d3 * d2; + if vc <= 0.0 && d1 >= 0.0 && d3 <= 0.0 { + let v = d1 / (d1 - d3); + return (a + ab * v, v, 0.0); + } + let cp = p - c; + let (d5, d6) = (ab.dot(cp), ac.dot(cp)); + if d6 >= 0.0 && d5 <= d6 { + return (c, 0.0, 1.0); + } + let vb = d5 * d2 - d1 * d6; + if vb <= 0.0 && d2 >= 0.0 && d6 <= 0.0 { + let w = d2 / (d2 - d6); + return (a + ac * w, 0.0, w); + } + let va = d3 * d6 - d5 * d4; + if va <= 0.0 && d4 - d3 >= 0.0 && d5 - d6 >= 0.0 { + let w = (d4 - d3) / ((d4 - d3) + (d5 - d6)); + return (b + (c - b) * w, 1.0 - w, w); + } + let denom = 1.0 / (va + vb + vc); + let (v, w) = (vb * denom, vc * denom); + (a + ab * v + ac * w, v, w) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::primitives; + + #[test] + fn nearest_point_matches_brute_force() { + let m = primitives::builtin("torus").unwrap(); + let bvh = Bvh::new(&m); + let mut seed = 7u32; + let mut rnd = move || { + seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + (seed >> 8) as f32 / (1u32 << 24) as f32 * 4.0 - 2.0 + }; + for _ in 0..200 { + let p = Vec3::new(rnd(), rnd(), rnd()); + let hit = bvh.nearest(p, f32::MAX, &|_| true).unwrap(); + let brute = (0..m.triangle_count()) + .map(|t| { + let [a, b, c] = m.tri(t).unwrap().map(|i| m.positions[i]); + (closest_on_triangle(p, &[a, b, c]).0 - p).length() + }) + .fold(f32::MAX, f32::min); + assert!((hit.t - brute).abs() < 1e-5, "{} vs {brute}", hit.t); + let [a, b, c] = m.tri(hit.tri as usize).unwrap().map(|i| m.positions[i]); + let q = a * (1.0 - hit.u - hit.v) + b * hit.u + c * hit.v; + assert!(((q - p).length() - hit.t).abs() < 1e-4); + } + assert!(bvh.nearest(Vec3::splat(100.0), 1.0, &|_| true).is_none(), "out of range"); + assert!(bvh.nearest(Vec3::ZERO, f32::MAX, &|_| false).is_none(), "filtered out"); + } + + #[test] + fn traversal_stack_spills_in_lifo_order() { + let mut st = Stack::default(); + for v in 0..200 { + st.push((v, v as f32)); + } + assert!((0..200).rev().all(|v| st.pop() == Some((v, v as f32)))); + assert_eq!(st.pop(), None); + } + + #[test] + fn ray_hits_sphere_at_expected_distance() { + let m = primitives::sphere(1.0, 64, 32); + let bvh = Bvh::new(&m); + let h = bvh.closest(Vec3::new(0.0, 0.0, 5.0), Vec3::NEG_Z, 100.0).unwrap(); + assert!((h.t - 4.0).abs() < 0.01, "{}", h.t); + assert!(bvh.closest(Vec3::new(0.0, 3.0, 5.0), Vec3::NEG_Z, 100.0).is_none()); + // Rays lying exactly in a node's bounding plane (y = 0 is the equator) hit the front. + // Axis-aligned rays lying in a node's bounding plane (y = 0) still find the front. + for x in [-0.5f32, -0.4, 0.3] { + let h = bvh.closest(Vec3::new(x, 0.0, 5.0), Vec3::NEG_Z, 100.0).unwrap(); + assert!(h.t < 5.0, "x {x}: hit the back at t {}", h.t); + } + // Rays through shared edges (the equator) hit the front, never slip through to the back. + let m = primitives::sphere(1.0, 48, 24); + let bvh = Bvh::new(&m); + for i in 0..200 { + let x = i as f32 / 100.0 - 1.0; + let o = Vec3::new(0.0, 0.0, 5.0); + let d = (Vec3::new(x * 0.9, 0.0, 0.0) - o).normalize(); + let h = bvh.closest(o, d, 100.0).unwrap(); + assert!(h.t < 5.0, "x {x}: hit the back at t {}", h.t); + } + assert!(bvh.occluded(Vec3::new(0.0, 0.0, 5.0), Vec3::NEG_Z, 10.0)); + assert!(!bvh.occluded(Vec3::new(0.0, 0.0, 5.0), Vec3::NEG_Z, 3.0)); + } + + #[test] + fn matches_brute_force() { + let m = primitives::material_ball(); + let bvh = Bvh::new(&m); + for i in 0..200 { + let a = i as f32 * 0.731; + let o = Vec3::new(a.cos() * 6.0, (i as f32 * 0.37).sin() * 3.0 + 1.0, a.sin() * 6.0); + let d = (Vec3::new(0.0, 1.0, 0.0) + Vec3::new((a * 3.1).sin(), (a * 1.7).cos(), (a * 2.3).sin()) * 0.6 - o).normalize(); + let fast = bvh.closest(o, d, 1e9).map(|h| h.t); + let mut slow: Option = None; + for t in 0..m.triangle_count() { + let [x, y, z] = m.tri(t).unwrap(); + if let Some((tt, _, _)) = Bvh::hit_tri(&[m.positions[x], m.positions[y], m.positions[z]], o, d) { + slow = Some(slow.map_or(tt, |s: f32| s.min(tt))); + } + } + match (fast, slow) { + (Some(a), Some(b)) => assert!((a - b).abs() < 1e-4, "{a} {b}"), + (None, None) => {} + other => panic!("mismatch {other:?}"), + } + } + } + + #[test] + fn box_query_finds_overlapping_triangles() { + let m = primitives::plane(2.0, 4); + let bvh = Bvh::new(&m); + let mut found = Vec::new(); + bvh.query_box(Vec3::new(-0.1, -0.1, -0.1), Vec3::new(0.1, 0.1, 0.1), |t| found.push(t)); + assert!(!found.is_empty() && found.len() <= 8, "{found:?}"); + let empty = Bvh::new(&Mesh::default()); + assert!(empty.closest(Vec3::ZERO, Vec3::X, 1.0).is_none()); + } +} diff --git a/crates/geom/src/camera.rs b/crates/geom/src/camera.rs new file mode 100644 index 00000000..f1303251 --- /dev/null +++ b/crates/geom/src/camera.rs @@ -0,0 +1,140 @@ +//! Orbit camera (3D view navigation) and picking rays. + +use glam::{Mat4, Vec2, Vec3, Vec4}; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct OrbitCamera { + pub target: Vec3, + /// Radians around Y. + pub yaw: f32, + /// Radians above the horizon, clamped to ±89°. + pub pitch: f32, + pub distance: f32, + /// Vertical field of view, degrees. + pub fov: f32, + /// Scene radius (sets the clip planes). + pub scene_radius: f32, + /// Orthographic projection instead of perspective. + #[serde(default)] + pub ortho: bool, +} + +impl Default for OrbitCamera { + fn default() -> Self { + OrbitCamera { target: Vec3::ZERO, yaw: 0.0, pitch: 0.12, distance: 5.0, fov: 40.0, scene_radius: 1.0, ortho: false } + } +} + +/// A ray in world space. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Ray { + pub origin: Vec3, + pub dir: Vec3, +} + +impl OrbitCamera { + pub fn eye(&self) -> Vec3 { + let (sy, cy) = self.yaw.sin_cos(); + let (sp, cp) = self.pitch.sin_cos(); + self.target + Vec3::new(cp * sy, sp, cp * cy) * self.distance + } + + pub fn forward(&self) -> Vec3 { + (self.target - self.eye()).try_normalize().unwrap_or(Vec3::NEG_Z) + } + + pub fn view(&self) -> Mat4 { + Mat4::look_at_rh(self.eye(), self.target, Vec3::Y) + } + + pub fn proj(&self, aspect: f32) -> Mat4 { + let r = self.scene_radius.max(1e-3); + let near = (self.distance - r * 4.0).max(r * 0.01).max(1e-4); + let far = self.distance + r * 50.0; + let aspect = if aspect.is_finite() && aspect > 1e-4 { aspect } else { 1.0 }; + if self.ortho { + let h = self.distance * (self.fov.to_radians() * 0.5).tan(); + Mat4::orthographic_rh(-h * aspect, h * aspect, -h, h, near.min(0.01), far) + } else { + Mat4::perspective_rh(self.fov.clamp(5.0, 150.0).to_radians(), aspect, near, far) + } + } + + pub fn view_proj(&self, aspect: f32) -> Mat4 { + self.proj(aspect) * self.view() + } + + /// Frame a bounding box, keeping the current angles. + pub fn frame(&mut self, lo: Vec3, hi: Vec3) { + self.target = (lo + hi) * 0.5; + let r = ((hi - lo).length() * 0.5).max(1e-3); + self.scene_radius = r; + self.distance = r / (self.fov.clamp(5.0, 150.0).to_radians() * 0.5).sin() * 1.1; + } + + pub fn orbit(&mut self, dx: f32, dy: f32) { + self.yaw -= dx; + self.pitch = (self.pitch + dy).clamp(-89f32.to_radians(), 89f32.to_radians()); + } + + /// Pan by a screen fraction (dx, dy in viewport heights). + pub fn pan(&mut self, dx: f32, dy: f32) { + let f = self.forward(); + let right = f.cross(Vec3::Y).try_normalize().unwrap_or(Vec3::X); + let up = right.cross(f); + let scale = self.distance * (self.fov.to_radians() * 0.5).tan() * 2.0; + self.target += (-right * dx + up * dy) * scale; + } + + /// Dolly by a factor exponent (positive zooms in). + pub fn zoom(&mut self, amount: f32) { + let r = self.scene_radius.max(1e-3); + self.distance = (self.distance * (-amount).exp()).clamp(r * 0.05, r * 200.0); + } + + /// Ray through a viewport point given in normalized device coordinates (-1..1, y up). + pub fn ray(&self, ndc: Vec2, aspect: f32) -> Ray { + let inv = self.view_proj(aspect).inverse(); + let a = inv * Vec4::new(ndc.x, ndc.y, 0.0, 1.0); + let b = inv * Vec4::new(ndc.x, ndc.y, 1.0, 1.0); + let (a, b) = (a.truncate() / a.w, b.truncate() / b.w); + Ray { origin: a, dir: (b - a).try_normalize().unwrap_or(self.forward()) } + } + + /// Project a world point to NDC (x, y in -1..1, y up; z depth). None behind the camera. + pub fn project(&self, p: Vec3, aspect: f32) -> Option { + let c = self.view_proj(aspect) * p.extend(1.0); + (c.w > 1e-6).then(|| c.truncate() / c.w) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn center_ray_points_at_target_and_projection_inverts() { + let mut c = OrbitCamera::default(); + c.frame(Vec3::splat(-1.0), Vec3::splat(1.0)); + let r = c.ray(Vec2::ZERO, 1.5); + assert!((r.dir - c.forward()).length() < 1e-4); + let p = Vec3::new(0.3, -0.2, 0.1); + let ndc = c.project(p, 1.5).unwrap(); + let r = c.ray(ndc.truncate(), 1.5); + let to_p = (p - r.origin).normalize(); + assert!(to_p.dot(r.dir) > 0.9999); + } + + #[test] + fn pitch_is_clamped_and_zoom_bounded() { + let mut c = OrbitCamera::default(); + c.orbit(0.0, 10.0); + assert!(c.pitch <= 89f32.to_radians() + 1e-6); + for _ in 0..1000 { + c.zoom(1.0); + } + assert!(c.distance > 0.0 && c.distance.is_finite()); + let _ = c.proj(f32::NAN); + } +} diff --git a/crates/geom/src/gbuffer.rs b/crates/geom/src/gbuffer.rs new file mode 100644 index 00000000..e26b923f --- /dev/null +++ b/crates/geom/src/gbuffer.rs @@ -0,0 +1,195 @@ +//! The UV-space G-buffer: which triangle (and where on it) each texel of a texture set maps +//! to. Painting, compositing, baking and padding all work from this one buffer, so they agree +//! on which texel is which surface point. + +use glam::{Vec2, Vec3, Vec4}; +use rayon::prelude::*; + +use crate::Mesh; + +/// Texel not covered by any triangle. +pub const NO_TRI: u32 = u32::MAX; + +const BAND: u32 = 32; + +#[derive(Clone, Debug, PartialEq)] +pub struct UvGBuffer { + pub width: u32, + pub height: u32, + /// Triangle under each texel center, [`NO_TRI`] when uncovered. + pub tri: Vec, + /// Barycentric weights of the triangle's second and third vertices. + pub bary: Vec<[f32; 2]>, + /// Texels written by more than one triangle (overlapping UVs). + pub overlaps: u32, +} + +/// Interpolated surface attributes at a texel. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Surface { + pub pos: Vec3, + /// Interpolated shading normal (normalized). + pub nrm: Vec3, + /// Flat triangle normal (for ray offsets). + pub geo_nrm: Vec3, + pub tangent: Vec4, + pub uv: Vec2, + pub tri: u32, +} + +fn edge(a: Vec2, b: Vec2, p: Vec2) -> f32 { + (b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x) +} + +impl UvGBuffer { + /// Rasterize the triangles of material `material` at `width × height`. + pub fn new(mesh: &Mesh, material: usize, width: u32, height: u32) -> UvGBuffer { + let (w, h) = (width.max(1), height.max(1)); + let size = Vec2::new(w as f32, h as f32); + let bands = h.div_ceil(BAND) as usize; + let mut bins: Vec> = vec![Vec::new(); bands]; + for t in mesh.triangles_of(material) { + let Some([a, b, c]) = mesh.tri(t) else { continue }; + let (Some(ua), Some(ub), Some(uc)) = (mesh.uvs.get(a), mesh.uvs.get(b), mesh.uvs.get(c)) else { continue }; + let y0 = (ua.y.min(ub.y).min(uc.y) * size.y).floor().max(0.0) as i64; + let y1 = (ua.y.max(ub.y).max(uc.y) * size.y).ceil().min(size.y) as i64; + if y1 <= y0 || !ua.is_finite() || !ub.is_finite() || !uc.is_finite() { + continue; + } + let (b0, b1) = ((y0 / BAND as i64) as usize, ((y1 - 1).max(0) / BAND as i64) as usize); + for bin in bins.iter_mut().take(b1 + 1).skip(b0) { + bin.push(t as u32); + } + } + let n = w as usize * h as usize; + let mut tri = vec![NO_TRI; n]; + let mut bary = vec![[0.0f32; 2]; n]; + let band_len = (BAND * w) as usize; + let overlaps: u32 = tri + .par_chunks_mut(band_len) + .zip(bary.par_chunks_mut(band_len)) + .enumerate() + .map(|(bi, (tri, bary))| { + let mut overlaps = 0u32; + let row0 = bi as u32 * BAND; + let rows = (tri.len() as u32) / w; + for &t in bins.get(bi).map(Vec::as_slice).unwrap_or(&[]) { + let Some([a, b, c]) = mesh.tri(t as usize) else { continue }; + let (Some(&ua), Some(&ub), Some(&uc)) = (mesh.uvs.get(a), mesh.uvs.get(b), mesh.uvs.get(c)) else { continue }; + let (pa, pb, pc) = (ua * size, ub * size, uc * size); + let area = edge(pa, pb, pc); + if area.abs() < 1e-12 { + continue; + } + let eps = -1e-6 * area.abs(); + let x0 = pa.x.min(pb.x).min(pc.x).floor().max(0.0) as u32; + let x1 = (pa.x.max(pb.x).max(pc.x).ceil().min(w as f32) as u32).min(w); + let y0 = (pa.y.min(pb.y).min(pc.y).floor().max(row0 as f32) as u32).max(row0); + let y1 = (pa.y.max(pb.y).max(pc.y).ceil() as u32).min(row0 + rows); + for y in y0..y1 { + for x in x0..x1 { + let p = Vec2::new(x as f32 + 0.5, y as f32 + 0.5); + let (w0, w1, w2) = (edge(pb, pc, p) * area.signum(), edge(pc, pa, p) * area.signum(), edge(pa, pb, p) * area.signum()); + if w0 < eps || w1 < eps || w2 < eps { + continue; + } + let i = ((y - row0) * w + x) as usize; + if let (Some(slot), Some(bw)) = (tri.get_mut(i), bary.get_mut(i)) { + if *slot != NO_TRI { + overlaps += 1; + } + *slot = t; + let inv = 1.0 / area.abs(); + *bw = [w1 * inv, w2 * inv]; + } + } + } + } + overlaps + }) + .sum(); + UvGBuffer { width: w, height: h, tri, bary, overlaps } + } + + pub fn covered(&self, i: usize) -> bool { + self.tri.get(i).is_some_and(|t| *t != NO_TRI) + } + + pub fn coverage_mask(&self) -> Vec { + self.tri.iter().map(|t| *t != NO_TRI).collect() + } + + pub fn covered_count(&self) -> usize { + self.tri.iter().filter(|t| **t != NO_TRI).count() + } + + /// Surface attributes at texel index `i` (None when uncovered). + pub fn surface(&self, mesh: &Mesh, i: usize) -> Option { + let t = *self.tri.get(i)?; + if t == NO_TRI { + return None; + } + let [b1, b2] = *self.bary.get(i)?; + surface_at(mesh, t, b1, b2) + } +} + +/// Interpolate triangle `t` at barycentrics (weights of vertices 1 and 2). +pub fn surface_at(mesh: &Mesh, t: u32, b1: f32, b2: f32) -> Option { + let [a, b, c] = mesh.tri(t as usize)?; + let b0 = 1.0 - b1 - b2; + let p = |v: &[Vec3]| -> Option { Some(*v.get(a)? * b0 + *v.get(b)? * b1 + *v.get(c)? * b2) }; + let pos = p(&mesh.positions)?; + let nrm = p(&mesh.normals)?.try_normalize().unwrap_or(Vec3::Y); + let (pa, pb, pc) = (*mesh.positions.get(a)?, *mesh.positions.get(b)?, *mesh.positions.get(c)?); + let geo_nrm = (pb - pa).cross(pc - pa).try_normalize().unwrap_or(nrm); + let tan = *mesh.tangents.get(a)? * b0 + *mesh.tangents.get(b)? * b1 + *mesh.tangents.get(c)? * b2; + let uv = *mesh.uvs.get(a)? * b0 + *mesh.uvs.get(b)? * b1 + *mesh.uvs.get(c)? * b2; + let tdir = tan.truncate().try_normalize().unwrap_or_else(|| nrm.any_orthonormal_vector()); + let w = mesh.tangents.get(a).map(|t| if t.w < 0.0 { -1.0 } else { 1.0 }).unwrap_or(1.0); + Some(Surface { pos, nrm, geo_nrm, tangent: tdir.extend(w), uv, tri: t }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::primitives; + + #[test] + fn half_triangle_covers_texels_with_centers_inside() { + // One triangle covering the lower-left half of UV space (v down: y = v·H). + let m = + Mesh::from_parts(vec![Vec3::ZERO, Vec3::X, Vec3::Y], None, vec![Vec2::new(0.0, 0.0), Vec2::new(0.0, 1.0), Vec2::new(1.0, 1.0)], vec![0, 1, 2], "m") + .unwrap(); + let g = UvGBuffer::new(&m, 0, 8, 8); + for y in 0..8u32 { + for x in 0..8u32 { + let inside = (x as f32 + 0.5) <= (y as f32 + 0.5); + assert_eq!(g.covered((y * 8 + x) as usize), inside, "({x},{y})"); + } + } + assert_eq!(g.overlaps, 0); + } + + #[test] + fn overlapping_and_degenerate_triangles() { + let uv = vec![Vec2::new(0.0, 0.0), Vec2::new(1.0, 0.0), Vec2::new(0.0, 1.0), Vec2::new(0.5, 0.5)]; + let m = Mesh::from_parts(vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::Z], None, uv, vec![0, 1, 2, 0, 1, 2, 0, 3, 3], "m").unwrap(); + let g = UvGBuffer::new(&m, 0, 16, 16); + assert!(g.overlaps > 0); + assert!(g.covered_count() > 0); + } + + #[test] + fn sphere_surface_lies_on_the_sphere() { + let m = primitives::sphere(2.0, 64, 32); + let g = UvGBuffer::new(&m, 0, 128, 128); + assert!(g.covered_count() > 128 * 128 * 9 / 10, "{}", g.covered_count()); + for i in (0..g.tri.len()).step_by(97) { + if let Some(s) = g.surface(&m, i) { + assert!((s.pos.length() - 2.0).abs() < 0.02); + assert!(s.nrm.dot(s.pos.normalize()) > 0.99); + } + } + } +} diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs new file mode 100644 index 00000000..fd5deba7 --- /dev/null +++ b/crates/geom/src/lib.rs @@ -0,0 +1,28 @@ +//! # materialcraft-geom +//! +//! Geometry for MaterialCraft: the [`Mesh`] type with normals and MikkTSpace tangents, built-in +//! [`primitives`] (material ball, sphere, cube, …), a [`Bvh`] for ray casts and box queries, +//! the UV-space [`UvGBuffer`] that maps texels to surface points, and the [`OrbitCamera`]. +#![forbid(unsafe_code)] +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +pub mod bvh; +pub mod camera; +pub mod gbuffer; +pub mod mesh; +pub mod primitives; +pub mod unwrap; + +pub use bvh::{Bvh, Hit}; +pub use camera::{OrbitCamera, Ray}; +pub use gbuffer::{NO_TRI, Surface, UvGBuffer, surface_at}; +pub use glam; +pub use mesh::{BaseColor, MAX_TRIANGLES, Mesh, SubMesh}; + +#[derive(Debug, thiserror::Error, Clone, PartialEq)] +pub enum GeomError { + #[error("invalid mesh: {0}")] + Invalid(String), +} + +pub type Result = std::result::Result; diff --git a/crates/geom/src/mesh.rs b/crates/geom/src/mesh.rs new file mode 100644 index 00000000..2ba804b2 --- /dev/null +++ b/crates/geom/src/mesh.rs @@ -0,0 +1,432 @@ +//! The internal triangle mesh. + +use glam::{Vec2, Vec3, Vec4}; + +use crate::{GeomError, Result}; + +/// A contiguous index range drawn with one material. +#[derive(Clone, Debug, PartialEq)] +pub struct SubMesh { + pub name: String, + pub material: usize, + /// First index (into [`Mesh::indices`]) and index count. + pub start: u32, + pub count: u32, +} + +/// A material's base color (what a color-map bake transfers): `factor` (linear RGBA) times an +/// optional texture sampled at the mesh UVs. +#[derive(Clone, Debug, PartialEq)] +pub struct BaseColor { + pub factor: Vec4, + pub width: u32, + pub height: u32, + /// `width × height` RGBA8 texels (color sRGB-encoded, alpha linear), rows top → bottom like + /// the UVs' v; empty without a texture. + pub texels: Vec<[u8; 4]>, +} + +/// Triangle mesh in world space. UVs use the glTF convention (origin top-left, v down). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Mesh { + pub positions: Vec, + pub normals: Vec, + /// xyz tangent, w bitangent sign. + pub tangents: Vec, + pub uvs: Vec, + /// RGBA vertex colors in 0..1 (glTF: linear; OBJ, PLY: as stored): one per vertex, or empty. + pub colors: Vec, + pub indices: Vec, + /// Index ranges per material and part (node / object); `name` is the part name. + pub submeshes: Vec, + pub materials: Vec, +} + +/// Hard cap on mesh size accepted from files (triangles). +pub const MAX_TRIANGLES: usize = 20_000_000; + +impl Mesh { + pub fn triangle_count(&self) -> usize { + self.indices.len() / 3 + } + + pub fn vertex_count(&self) -> usize { + self.positions.len() + } + + /// Axis-aligned bounds (zero box for an empty mesh). + pub fn bounds(&self) -> (Vec3, Vec3) { + if self.positions.is_empty() { + return (Vec3::ZERO, Vec3::ZERO); + } + self.positions.iter().fold((Vec3::splat(f32::MAX), Vec3::splat(f32::MIN)), |(lo, hi), p| (lo.min(*p), hi.max(*p))) + } + + /// Bounding-sphere radius around the bounds center (at least a small epsilon). + pub fn radius(&self) -> f32 { + let (lo, hi) = self.bounds(); + ((hi - lo).length() * 0.5).max(1e-4) + } + + /// Vertex indices of triangle `t`. + pub fn tri(&self, t: usize) -> Option<[usize; 3]> { + let i = self.indices.get(t * 3..t * 3 + 3)?; + Some([i[0] as usize, i[1] as usize, i[2] as usize]) + } + + /// Material of triangle `t`. + pub fn material_of(&self, t: usize) -> Option { + let idx = (t * 3) as u32; + self.submeshes.iter().find(|s| idx >= s.start && idx < s.start.saturating_add(s.count)).map(|s| s.material) + } + + /// Triangle index range belonging to material `m` (all submeshes of that material). + pub fn triangles_of(&self, m: usize) -> impl Iterator + '_ { + self.submeshes.iter().filter(move |s| s.material == m).flat_map(|s| (s.start / 3) as usize..((s.start + s.count) / 3) as usize) + } + + /// Check that attribute arrays agree and every index is in range. + pub fn validate(&self) -> Result<()> { + let n = self.positions.len(); + if self.normals.len() != n || self.uvs.len() != n || self.tangents.len() != n { + return Err(GeomError::Invalid(format!( + "attribute counts differ: {} positions, {} normals, {} uvs, {} tangents", + n, + self.normals.len(), + self.uvs.len(), + self.tangents.len() + ))); + } + if !self.colors.is_empty() && self.colors.len() != n { + return Err(GeomError::Invalid(format!("{} vertex colors for {n} vertices", self.colors.len()))); + } + if !self.indices.len().is_multiple_of(3) { + return Err(GeomError::Invalid("index count is not a multiple of 3".into())); + } + if self.triangle_count() > MAX_TRIANGLES { + return Err(GeomError::Invalid(format!("mesh has more than {MAX_TRIANGLES} triangles"))); + } + if let Some(bad) = self.indices.iter().find(|i| **i as usize >= n) { + return Err(GeomError::Invalid(format!("index {bad} out of range ({n} vertices)"))); + } + if self.positions.iter().any(|p| !p.is_finite()) { + return Err(GeomError::Invalid("mesh has non-finite positions".into())); + } + for s in &self.submeshes { + if s.start as usize + s.count as usize > self.indices.len() || s.material >= self.materials.len().max(1) { + return Err(GeomError::Invalid(format!("submesh {} is out of range", s.name))); + } + } + Ok(()) + } + + /// Area-weighted smooth normals over the index buffer. + pub fn compute_normals(&mut self) { + let mut n = vec![Vec3::ZERO; self.positions.len()]; + for t in self.indices.chunks_exact(3) { + let (a, b, c) = (t[0] as usize, t[1] as usize, t[2] as usize); + let (Some(pa), Some(pb), Some(pc)) = (self.positions.get(a), self.positions.get(b), self.positions.get(c)) else { continue }; + let face = (*pb - *pa).cross(*pc - *pa); + for v in [a, b, c] { + if let Some(x) = n.get_mut(v) { + *x += face; + } + } + } + self.normals = n.into_iter().map(|v| v.try_normalize().unwrap_or(Vec3::Y)).collect(); + } + + /// MikkTSpace tangents (falls back to per-triangle tangents if generation fails). + pub fn compute_tangents(&mut self) { + self.tangents = vec![Vec4::new(1.0, 0.0, 0.0, 1.0); self.positions.len()]; + if self.normals.len() != self.positions.len() { + self.compute_normals(); + } + if self.uvs.len() != self.positions.len() { + self.uvs = vec![Vec2::ZERO; self.positions.len()]; + } + // mikktspace crashes (out-of-bounds) when every triangle is degenerate; skip it then. + let usable = !crate::unwrap::all_triangles_degenerate(self); + let mut g = Mikk { mesh: self }; + if !usable || !mikktspace::generate_tangents(&mut g) { + self.simple_tangents(); + } + for (t, n) in self.tangents.iter_mut().zip(&self.normals) { + // Orthonormalize against the normal; repair degenerate results. + let v = t.truncate(); + let o = (v - *n * n.dot(v)).try_normalize().unwrap_or_else(|| n.any_orthonormal_vector()); + *t = o.extend(if t.w < 0.0 { -1.0 } else { 1.0 }); + } + } + + fn simple_tangents(&mut self) { + let mut acc = vec![Vec3::ZERO; self.positions.len()]; + for t in self.indices.chunks_exact(3) { + let (a, b, c) = (t[0] as usize, t[1] as usize, t[2] as usize); + let (Some(pa), Some(pb), Some(pc)) = (self.positions.get(a), self.positions.get(b), self.positions.get(c)) else { continue }; + let (Some(ua), Some(ub), Some(uc)) = (self.uvs.get(a), self.uvs.get(b), self.uvs.get(c)) else { continue }; + let (e1, e2) = (*pb - *pa, *pc - *pa); + let (d1, d2) = (*ub - *ua, *uc - *ua); + let r = d1.x * d2.y - d2.x * d1.y; + if r.abs() < 1e-12 { + continue; + } + let tan = (e1 * d2.y - e2 * d1.y) / r; + for v in [a, b, c] { + if let Some(x) = acc.get_mut(v) { + *x += tan; + } + } + } + self.tangents = acc.into_iter().map(|t| t.try_normalize().unwrap_or(Vec3::X).extend(1.0)).collect(); + } + + /// The UV tiles material `m` covers: integer parts of its triangles' UV centroids (v down), + /// ascending. Non-finite UVs are skipped. + pub fn uv_tiles(&self, m: usize) -> std::collections::BTreeSet<(i32, i32)> { + self.triangles_of(m) + .filter_map(|t| { + let [a, b, c] = self.tri(t)?; + let uv = (*self.uvs.get(a)? + *self.uvs.get(b)? + *self.uvs.get(c)?) / 3.0; + uv.is_finite().then(|| (uv.x.floor() as i32, uv.y.floor() as i32)) + }) + .collect() + } + + /// Remap the UVs of material `m`'s triangles with `f`. Vertices they share with other + /// materials are duplicated first, so the other triangles keep their UVs. + pub fn map_material_uvs(&mut self, m: usize, f: impl Fn(Vec2) -> Vec2) { + self.map_material_uvs_with(m, |_, uv| f(uv)); + } + + /// [`Mesh::map_material_uvs`] where `f` also gets the UV centroid of the first of the + /// material's triangles using the vertex: piecewise maps (UV tiles of different sizes) then + /// place a vertex on a tile border with its own triangle's tile. + pub fn map_material_uvs_with(&mut self, m: usize, f: impl Fn(Vec2, Vec2) -> Vec2) { + let mine: Vec = self.triangles_of(m).collect(); + let mut is_mine = vec![false; self.triangle_count()]; + for t in &mine { + if let Some(x) = is_mine.get_mut(*t) { + *x = true; + } + } + let mut shared = vec![false; self.positions.len()]; + for (_, tri) in self.indices.chunks_exact(3).enumerate().filter(|(t, _)| !is_mine.get(*t).copied().unwrap_or(false)) { + for v in tri { + if let Some(s) = shared.get_mut(*v as usize) { + *s = true; + } + } + } + let mut copies = std::collections::HashMap::new(); + for k in mine.iter().flat_map(|t| t * 3..t * 3 + 3) { + let Some(&v) = self.indices.get(k) else { continue }; + let v = if shared.get(v as usize).copied().unwrap_or(false) { *copies.entry(v).or_insert_with(|| self.duplicate_vertex(v as usize)) } else { v }; + if let Some(i) = self.indices.get_mut(k) { + *i = v; + } + } + // (vertex, centroid of its first triangle), each vertex once. + let mut verts = Vec::with_capacity(mine.len() * 3); + for t in &mine { + let Some(tri) = self.tri(*t) else { continue }; + let centroid = tri.iter().map(|v| self.uvs.get(*v).copied().unwrap_or_default()).sum::() / 3.0; + verts.extend(tri.map(|v| (v, centroid))); + } + verts.sort_by_key(|(v, _)| *v); + verts.dedup_by_key(|(v, _)| *v); + for (v, centroid) in verts { + if let Some(uv) = self.uvs.get_mut(v) { + *uv = f(centroid, *uv); + } + } + } + + /// Append a copy of vertex `v`; returns its index. + fn duplicate_vertex(&mut self, v: usize) -> u32 { + let i = self.positions.len() as u32; + self.positions.push(self.positions.get(v).copied().unwrap_or_default()); + self.normals.push(self.normals.get(v).copied().unwrap_or(Vec3::Y)); + self.tangents.push(self.tangents.get(v).copied().unwrap_or(Vec4::new(1.0, 0.0, 0.0, 1.0))); + self.uvs.push(self.uvs.get(v).copied().unwrap_or_default()); + if !self.colors.is_empty() { + self.colors.push(self.colors.get(v).copied().unwrap_or(Vec4::ONE)); + } + i + } + + /// Append `other`, offsetting indices; its submeshes keep their material indices shifted by + /// this mesh's material count. + pub fn append(&mut self, other: &Mesh) { + let base = self.positions.len() as u32; + let ibase = self.indices.len() as u32; + let mbase = self.materials.len(); + self.positions.extend_from_slice(&other.positions); + self.normals.extend_from_slice(&other.normals); + self.tangents.extend_from_slice(&other.tangents); + self.uvs.extend_from_slice(&other.uvs); + if !(self.colors.is_empty() && other.colors.is_empty()) { + // Vertices of the side without colors become white. + self.colors.resize(base as usize, Vec4::ONE); + self.colors.extend(other.colors.iter().copied().chain(std::iter::repeat(Vec4::ONE)).take(other.positions.len())); + } + self.indices.extend(other.indices.iter().map(|i| i + base)); + self.materials.extend(other.materials.iter().cloned()); + self.submeshes.extend(other.submeshes.iter().map(|s| SubMesh { + name: s.name.clone(), + material: s.material + mbase, + start: s.start + ibase, + count: s.count, + })); + } + + /// Uniformly scale and translate so the mesh is centered with the given bounding radius. + pub fn normalize_to(&mut self, radius: f32) { + let (lo, hi) = self.bounds(); + let c = (lo + hi) * 0.5; + let s = radius / self.radius(); + for p in &mut self.positions { + *p = (*p - c) * s; + } + } + + /// A single-material mesh from raw attributes; computes missing normals and tangents. + pub fn from_parts(positions: Vec, normals: Option>, uvs: Vec, indices: Vec, material: &str) -> Result { + let count = indices.len() as u32; + let mut m = Mesh { + normals: normals.unwrap_or_default(), + uvs, + positions, + indices, + tangents: Vec::new(), + colors: Vec::new(), + submeshes: vec![SubMesh { name: material.into(), material: 0, start: 0, count }], + materials: vec![material.into()], + }; + if m.normals.len() != m.positions.len() { + m.compute_normals(); + } + m.compute_tangents(); + m.validate()?; + Ok(m) + } +} + +struct Mikk<'a> { + mesh: &'a mut Mesh, +} + +impl Mikk<'_> { + fn vi(&self, face: usize, vert: usize) -> usize { + self.mesh.indices.get(face * 3 + vert).copied().unwrap_or(0) as usize + } +} + +impl mikktspace::Geometry for Mikk<'_> { + fn num_faces(&self) -> usize { + self.mesh.indices.len() / 3 + } + fn num_vertices_of_face(&self, _face: usize) -> usize { + 3 + } + fn position(&self, face: usize, vert: usize) -> [f32; 3] { + self.mesh.positions.get(self.vi(face, vert)).copied().unwrap_or_default().to_array() + } + fn normal(&self, face: usize, vert: usize) -> [f32; 3] { + self.mesh.normals.get(self.vi(face, vert)).copied().unwrap_or(Vec3::Y).to_array() + } + fn tex_coord(&self, face: usize, vert: usize) -> [f32; 2] { + // MikkTSpace expects OpenGL texture coordinates (v up); our UVs are glTF (v down). With + // v flipped, the bitangent `cross(N, T) * w` points up the image, as glTF requires. + let uv = self.mesh.uvs.get(self.vi(face, vert)).copied().unwrap_or_default(); + [uv.x, 1.0 - uv.y] + } + fn set_tangent_encoded(&mut self, tangent: [f32; 4], face: usize, vert: usize) { + let i = self.vi(face, vert); + if let Some(t) = self.mesh.tangents.get_mut(i) { + *t = Vec4::from_array(tangent); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn quad() -> Mesh { + Mesh::from_parts( + vec![Vec3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 0.0, 0.0), Vec3::new(1.0, 1.0, 0.0), Vec3::new(0.0, 1.0, 0.0)], + None, + vec![Vec2::new(0.0, 1.0), Vec2::new(1.0, 1.0), Vec2::new(1.0, 0.0), Vec2::new(0.0, 0.0)], + vec![0, 1, 2, 0, 2, 3], + "Default", + ) + .unwrap() + } + + #[test] + fn normals_and_tangents_of_a_quad() { + let m = quad(); + for n in &m.normals { + assert!((*n - Vec3::Z).length() < 1e-5); + } + for t in &m.tangents { + assert!((t.truncate() - Vec3::X).length() < 1e-4, "{t:?}"); + } + assert_eq!(m.material_of(1), Some(0)); + assert_eq!(m.triangles_of(0).collect::>(), vec![0, 1]); + } + + #[test] + fn validate_catches_bad_indices() { + let mut m = quad(); + m.indices[0] = 99; + assert!(m.validate().is_err()); + let mut m = quad(); + m.uvs.pop(); + assert!(m.validate().is_err()); + } + + #[test] + fn append_offsets_indices_and_materials() { + let mut a = quad(); + let b = quad(); + a.append(&b); + assert_eq!(a.indices[6], 4); + assert_eq!(a.submeshes[1].material, 1); + assert_eq!(a.submeshes[1].start, 6); + a.validate().unwrap(); + // Colors on one side only: the other side's vertices become white. + let mut red = quad(); + red.colors = vec![Vec4::new(1.0, 0.0, 0.0, 1.0); 4]; + a.append(&red); + assert_eq!(a.colors.len(), 12); + assert_eq!((a.colors[0], a.colors[8]), (Vec4::ONE, Vec4::new(1.0, 0.0, 0.0, 1.0))); + a.append(&quad()); + assert_eq!(a.colors[15], Vec4::ONE); + a.validate().unwrap(); + a.colors.pop(); + assert!(a.validate().is_err()); + } + + #[test] + fn material_uvs_remap_and_split_shared_vertices() { + // quad(): two triangles sharing an edge; put the second in its own material. + let mut m = quad(); + m.materials = vec!["a".into(), "b".into()]; + m.submeshes = vec![SubMesh { name: "a".into(), material: 0, start: 0, count: 3 }, SubMesh { name: "b".into(), material: 1, start: 3, count: 3 }]; + let before = m.clone(); + m.map_material_uvs(1, |uv| uv + Vec2::X); + m.validate().unwrap(); + assert_eq!(m.vertex_count(), 6, "the two shared vertices are split"); + assert_eq!(&m.indices[..3], &before.indices[..3]); + for k in 0..3 { + let (old, new) = (before.indices[k] as usize, m.indices[k] as usize); + assert_eq!(m.uvs[new], before.uvs[old], "material a keeps its UVs"); + let (old, new) = (before.indices[3 + k] as usize, m.indices[3 + k] as usize); + assert_eq!((m.uvs[new], m.positions[new]), (before.uvs[old] + Vec2::X, before.positions[old])); + } + assert_eq!(m.uv_tiles(1).into_iter().collect::>(), vec![(1, 0)]); + assert_eq!(m.uv_tiles(0).into_iter().collect::>(), vec![(0, 0)]); + } +} diff --git a/crates/geom/src/primitives.rs b/crates/geom/src/primitives.rs new file mode 100644 index 00000000..7f07270c --- /dev/null +++ b/crates/geom/src/primitives.rs @@ -0,0 +1,399 @@ +//! Built-in meshes with clean, non-overlapping UVs: material ball, sphere, (rounded) cube, +//! cylinder, torus and plane. Y is up; triangles are counter-clockwise seen from outside. + +use std::f32::consts::{PI, TAU}; + +use glam::{Vec2, Vec3}; + +use crate::mesh::{Mesh, SubMesh}; + +/// A UV-space rectangle: origin and size. +#[derive(Clone, Copy, Debug)] +struct UvRect { + o: Vec2, + s: Vec2, +} + +impl UvRect { + const FULL: UvRect = UvRect { o: Vec2::ZERO, s: Vec2::ONE }; + fn map(&self, u: f32, v: f32) -> Vec2 { + self.o + self.s * Vec2::new(u, v) + } + fn inset(&self, m: f32) -> UvRect { + UvRect { o: self.o + Vec2::splat(m), s: self.s - Vec2::splat(2.0 * m) } + } +} + +#[derive(Default)] +struct Builder { + p: Vec, + n: Vec, + uv: Vec, + idx: Vec, +} + +impl Builder { + fn vert(&mut self, p: Vec3, n: Vec3, uv: Vec2) -> u32 { + self.p.push(p); + self.n.push(n.try_normalize().unwrap_or(Vec3::Y)); + self.uv.push(uv); + (self.p.len() - 1) as u32 + } + + /// A grid of (rows+1)×(cols+1) vertices from `f(row, col)`, rows going "down" the texture. + fn grid(&mut self, rows: usize, cols: usize, mut f: impl FnMut(usize, usize) -> (Vec3, Vec3, Vec2)) { + let base = self.p.len() as u32; + for i in 0..=rows { + for j in 0..=cols { + let (p, n, uv) = f(i, j); + self.vert(p, n, uv); + } + } + let w = (cols + 1) as u32; + for i in 0..rows as u32 { + for j in 0..cols as u32 { + let a = base + i * w + j; + let (b, c, d) = (a + 1, a + w, a + w + 1); + self.idx.extend_from_slice(&[a, c, d, a, d, b]); + } + } + } + + fn finish(self, material: &str) -> Mesh { + let count = self.idx.len() as u32; + let mut m = Mesh { + positions: self.p, + normals: self.n, + uvs: self.uv, + indices: self.idx, + tangents: Vec::new(), + colors: Vec::new(), + submeshes: vec![SubMesh { name: material.into(), material: 0, start: 0, count }], + materials: vec![material.into()], + }; + m.compute_tangents(); + m + } +} + +/// UV sphere of `radius` centred at `center`. +pub fn sphere(radius: f32, segments: usize, rings: usize) -> Mesh { + let mut b = Builder::default(); + sphere_into(&mut b, Vec3::ZERO, radius, segments.max(3), rings.max(2), UvRect::FULL); + b.finish("Sphere") +} + +fn sphere_into(b: &mut Builder, center: Vec3, radius: f32, segs: usize, rings: usize, r: UvRect) { + b.grid(rings, segs, |i, j| { + let (u, v) = (j as f32 / segs as f32, i as f32 / rings as f32); + let (theta, phi) = (v * PI, u * TAU + PI * 1.5); + let n = Vec3::new(theta.sin() * phi.cos(), theta.cos(), -theta.sin() * phi.sin()); + (center + n * radius, n, r.map(u, v)) + }); +} + +/// A box with rounded edges (`bevel` = edge radius; 0 gives a plain cube). Faces are laid out +/// in a 3×2 UV atlas. +pub fn rounded_box(half: Vec3, bevel: f32) -> Mesh { + let mut b = Builder::default(); + rounded_box_into(&mut b, Vec3::ZERO, half, bevel, UvRect::FULL); + b.finish("Box") +} + +/// The cube primitive (sharp edges). +pub fn cube(size: f32) -> Mesh { + let mut m = rounded_box(Vec3::splat(size * 0.5), 0.0); + m.materials = vec!["Cube".into()]; + if let Some(s) = m.submeshes.first_mut() { + s.name = "Cube".into(); + } + m +} + +fn rounded_box_into(b: &mut Builder, center: Vec3, half: Vec3, bevel: f32, r: UvRect) { + let bevel = bevel.clamp(0.0, half.min_element() * 0.95); + // (normal, U = right, V = down) per face, seen from outside. + let faces = [ + (Vec3::Z, Vec3::X, -Vec3::Y), + (Vec3::X, -Vec3::Z, -Vec3::Y), + (-Vec3::Z, -Vec3::X, -Vec3::Y), + (-Vec3::X, Vec3::Z, -Vec3::Y), + (Vec3::Y, Vec3::X, Vec3::Z), + (-Vec3::Y, Vec3::X, -Vec3::Z), + ]; + let (kb, kc) = if bevel > 0.0 { (6usize, 10usize) } else { (0, 12) }; + // Coordinates along one face axis from -h to h, dense in the bevels. + let coords = |h: f32| -> Vec { + let inner = h - bevel; + let mut v = Vec::new(); + for i in 0..kb { + v.push(-h + bevel * i as f32 / kb as f32); + } + for i in 0..=kc { + v.push(-inner + 2.0 * inner * i as f32 / kc as f32); + } + for i in 1..=kb { + v.push(inner + bevel * i as f32 / kb as f32); + } + v + }; + let inner = half - Vec3::splat(bevel); + for (f, (n, u, v)) in faces.iter().enumerate() { + let cell = UvRect { o: r.map((f % 3) as f32 / 3.0, (f / 3) as f32 / 2.0), s: r.s * Vec2::new(1.0 / 3.0, 0.5) }.inset(0.01 * r.s.x); + let (hu, hv, hn) = ((*u * half).abs().max_element(), (*v * half).abs().max_element(), (*n * half).abs().max_element()); + let (cu, cv) = (coords(hu), coords(hv)); + let (cols, rows) = (cu.len() - 1, cv.len() - 1); + b.grid(rows, cols, |i, j| { + let (a, c) = (cu[j], cv[i]); + let q = *n * hn + *u * a + *v * c; + let clamped = q.clamp(-inner, inner); + let dir = (q - clamped).try_normalize().unwrap_or(*n); + let p = if bevel > 0.0 { clamped + dir * bevel } else { q }; + let nn = if bevel > 0.0 { dir } else { *n }; + (center + p, nn, cell.map((a + hu) / (2.0 * hu), (c + hv) / (2.0 * hv))) + }); + } +} + +/// Surface of revolution of a profile `(radius, y)` listed top → bottom, mapped into `r` +/// (u around, v down the profile by arc length). +fn lathe_into(b: &mut Builder, center: Vec3, profile: &[(f32, f32)], segs: usize, r: UvRect) { + if profile.len() < 2 { + return; + } + let mut len = vec![0.0f32]; + for w in profile.windows(2) { + let d = Vec2::new(w[1].0 - w[0].0, w[1].1 - w[0].1).length(); + len.push(len.last().copied().unwrap_or(0.0) + d); + } + let total = len.last().copied().unwrap_or(1.0).max(1e-6); + let rows = profile.len() - 1; + b.grid(rows, segs, |i, j| { + let (rad, y) = profile[i]; + // Profile tangent (downwards) → outward normal in the (r, y) plane. + let prev = profile[i.saturating_sub(1)]; + let next = profile[(i + 1).min(rows)]; + let t = Vec2::new(next.0 - prev.0, next.1 - prev.1).try_normalize().unwrap_or(Vec2::NEG_Y); + let n2 = Vec2::new(-t.y, t.x); + let u = j as f32 / segs as f32; + let phi = u * TAU + PI * 1.5; + let dir = Vec3::new(phi.cos(), 0.0, -phi.sin()); + let p = center + dir * rad + Vec3::Y * y; + let n = dir * n2.x + Vec3::Y * n2.y; + (p, n, r.map(u, len[i] / total)) + }); +} + +/// A flat disk facing up (+Y) or down, with planar UVs inside `r`. +fn disk_into(b: &mut Builder, center: Vec3, radius: f32, up: bool, segs: usize, r: UvRect) { + let n = if up { Vec3::Y } else { Vec3::NEG_Y }; + let c = b.vert(center, n, r.map(0.5, 0.5)); + let first = b.p.len() as u32; + for j in 0..segs { + let a = j as f32 / segs as f32 * TAU; + let (x, z) = (a.cos(), a.sin()); + // Top view: +X right, +Z down the texture; bottom view mirrors X. + let uv = if up { r.map(0.5 + x * 0.5, 0.5 + z * 0.5) } else { r.map(0.5 + x * 0.5, 0.5 - z * 0.5) }; + b.vert(center + Vec3::new(x, 0.0, z) * radius, n, uv); + } + for j in 0..segs as u32 { + let (a, bb) = (first + j, first + (j + 1) % segs as u32); + if up { + b.idx.extend_from_slice(&[c, bb, a]); + } else { + b.idx.extend_from_slice(&[c, a, bb]); + } + } +} + +/// A capped cylinder along Y. +pub fn cylinder(radius: f32, height: f32, segs: usize) -> Mesh { + let mut b = Builder::default(); + let h = height * 0.5; + lathe_into(&mut b, Vec3::ZERO, &[(radius, h), (radius, -h)], segs.max(3), UvRect { o: Vec2::ZERO, s: Vec2::new(1.0, 0.5) }.inset(0.01)); + disk_into(&mut b, Vec3::Y * h, radius, true, segs.max(3), UvRect { o: Vec2::new(0.0, 0.5), s: Vec2::splat(0.5) }.inset(0.01)); + disk_into(&mut b, -Vec3::Y * h, radius, false, segs.max(3), UvRect { o: Vec2::new(0.5, 0.5), s: Vec2::splat(0.5) }.inset(0.01)); + b.finish("Cylinder") +} + +/// A torus around Y. +pub fn torus(major: f32, minor: f32, segs: usize, sides: usize) -> Mesh { + let mut b = Builder::default(); + let (segs, sides) = (segs.max(3), sides.max(3)); + b.grid(sides, segs, |i, j| { + let (u, v) = (j as f32 / segs as f32, i as f32 / sides as f32); + let phi = u * TAU + PI * 1.5; + let theta = v * TAU; + let dir = Vec3::new(phi.cos(), 0.0, -phi.sin()); + let n = dir * theta.cos() - Vec3::Y * theta.sin(); + (dir * major + n * minor, n, Vec2::new(u, v)) + }); + b.finish("Torus") +} + +/// A subdivided plane facing +Y. +pub fn plane(size: f32, subdivisions: usize) -> Mesh { + let mut b = Builder::default(); + let s = subdivisions.max(1); + b.grid(s, s, |i, j| { + let (u, v) = (j as f32 / s as f32, i as f32 / s as f32); + (Vec3::new((u - 0.5) * size, 0.0, (v - 0.5) * size), Vec3::Y, Vec2::new(u, v)) + }); + b.finish("Plane") +} + +/// Two planes side by side on UV tiles 1001 and 1002 (UDIM): one material, 4 × 2 units. +pub fn udim_plane() -> Mesh { + let mut m = plane(2.0, 16); + let mut right = m.clone(); + for p in &mut m.positions { + p.x -= 1.0; + } + for p in &mut right.positions { + p.x += 1.0; + } + for uv in &mut right.uvs { + uv.x += 1.0; + } + right.materials.clear(); + right.submeshes.clear(); + m.append(&right); + let count = m.indices.len() as u32; + if let Some(s) = m.submeshes.first_mut() { + s.count = count; + } + m +} + +/// The default project mesh: a ball on a beveled pedestal, two materials ("Ball", "Base"). +pub fn material_ball() -> Mesh { + let mut ball = Builder::default(); + sphere_into(&mut ball, Vec3::new(0.0, 1.32, 0.0), 1.0, 128, 64, UvRect::FULL); + let mut ball = ball.finish("Ball"); + + let mut base = Builder::default(); + let (r, top, bot, bev) = (1.05f32, 0.32f32, 0.0f32, 0.07f32); + let mut profile = vec![(0.42, top + 0.06), (0.62, top + 0.06)]; + // Collar bevel and the ring the ball sits on, then the beveled drum. + for k in 1..=6 { + let a = k as f32 / 6.0 * PI * 0.5; + profile.push((0.62 + 0.06 * a.sin(), top + 0.06 * a.cos())); + } + profile.push((r - bev, top)); + for k in 1..=6 { + let a = k as f32 / 6.0 * PI * 0.5; + profile.push((r - bev + bev * a.sin(), top - bev + bev * a.cos())); + } + profile.push((r, bot + bev)); + for k in 1..=6 { + let a = k as f32 / 6.0 * PI * 0.5; + profile.push((r - bev + bev * a.cos(), bot + bev - bev * a.sin())); + } + lathe_into(&mut base, Vec3::ZERO, &profile, 128, UvRect { o: Vec2::ZERO, s: Vec2::new(1.0, 0.5) }.inset(0.01)); + disk_into(&mut base, Vec3::new(0.0, top + 0.06, 0.0), 0.42, true, 128, UvRect { o: Vec2::new(0.0, 0.5), s: Vec2::splat(0.5) }.inset(0.01)); + disk_into(&mut base, Vec3::new(0.0, bot, 0.0), r - bev, false, 128, UvRect { o: Vec2::new(0.5, 0.5), s: Vec2::splat(0.5) }.inset(0.01)); + let base = base.finish("Base"); + ball.append(&base); + ball +} + +/// A small showcase scene: a beveled crate with a rounded lid and a cylinder handle, in three +/// materials (used for demo projects and tests of multiple texture sets). +pub fn crate_scene() -> Mesh { + let mut body = Builder::default(); + rounded_box_into(&mut body, Vec3::new(0.0, 0.8, 0.0), Vec3::new(1.2, 0.8, 0.8), 0.12, UvRect::FULL); + let mut m = body.finish("Crate"); + let mut lid = Builder::default(); + rounded_box_into(&mut lid, Vec3::new(0.0, 1.72, 0.0), Vec3::new(1.28, 0.12, 0.88), 0.08, UvRect::FULL); + m.append(&lid.finish("Lid")); + let mut handle = torus(0.32, 0.07, 64, 24); + for p in &mut handle.positions { + *p = Vec3::new(p.x, p.z, -p.y) + Vec3::new(0.0, 1.84, 0.0); + } + for n in &mut handle.normals { + *n = Vec3::new(n.x, n.z, -n.y); + } + handle.materials = vec!["Handle".into()]; + if let Some(s) = handle.submeshes.first_mut() { + s.name = "Handle".into(); + } + handle.compute_tangents(); + m.append(&handle); + m +} + +/// Built-in mesh by id (`builtin:` in project files). +pub fn builtin(id: &str) -> Option { + Some(match id { + "material_ball" | "materialball" | "ball" => material_ball(), + "sphere" => sphere(1.0, 128, 64), + "cube" => cube(2.0), + "rounded_cube" | "roundedcube" | "box" => rounded_box(Vec3::ONE, 0.15), + "cylinder" => cylinder(1.0, 2.0, 96), + "torus" => torus(1.0, 0.35, 128, 48), + "plane" => plane(2.0, 16), + "crate" => crate_scene(), + "udim_plane" | "udimplane" => udim_plane(), + _ => return None, + }) +} + +/// Ids accepted by [`builtin`], in menu order. +pub const BUILTINS: [(&str, &str); 9] = [ + ("material_ball", "Material ball"), + ("sphere", "Sphere"), + ("cube", "Cube"), + ("rounded_cube", "Rounded cube"), + ("cylinder", "Cylinder"), + ("torus", "Torus"), + ("plane", "Plane"), + ("crate", "Crate"), + ("udim_plane", "UDIM plane"), +]; + +#[cfg(test)] +mod tests { + use super::*; + + /// Every triangle's winding agrees with its vertex normals, UVs stay in 0..1 (u in 0..max_u), + /// and the UV mapping is not mirrored (tangent handedness +1). + fn check(m: &Mesh, max_u: f32) { + m.validate().unwrap(); + let mut bad = 0; + for t in 0..m.triangle_count() { + let [a, b, c] = m.tri(t).unwrap(); + let face = (m.positions[b] - m.positions[a]).cross(m.positions[c] - m.positions[a]); + if face.length() < 1e-9 { + continue; + } + let n = m.normals[a] + m.normals[b] + m.normals[c]; + if face.dot(n) <= 0.0 { + bad += 1; + } + } + assert_eq!(bad, 0, "{} triangles wound against their normals", bad); + for uv in &m.uvs { + assert!((0.0..=max_u).contains(&uv.x) && (0.0..=1.0).contains(&uv.y), "{uv:?}"); + } + let mirrored = m.tangents.iter().filter(|t| t.w < 0.0).count(); + assert!(mirrored * 50 < m.tangents.len().max(1), "{mirrored} mirrored tangents"); + } + + #[test] + fn primitives_are_well_formed() { + for (id, _) in BUILTINS { + let m = builtin(id).unwrap(); + assert!(m.triangle_count() > 0, "{id}"); + check(&m, if id == "udim_plane" { 2.0 } else { 1.0 }); + } + assert!(builtin("nope").is_none()); + assert_eq!(udim_plane().uv_tiles(0).into_iter().collect::>(), vec![(0, 0), (1, 0)]); + } + + #[test] + fn material_ball_has_two_materials() { + let m = material_ball(); + assert_eq!(m.materials, vec!["Ball".to_string(), "Base".to_string()]); + assert!(m.triangles_of(0).count() > 0 && m.triangles_of(1).count() > 0); + } +} diff --git a/crates/geom/src/unwrap.rs b/crates/geom/src/unwrap.rs new file mode 100644 index 00000000..2f2eafc0 --- /dev/null +++ b/crates/geom/src/unwrap.rs @@ -0,0 +1,384 @@ +//! Automatic UV unwrapping for meshes imported without texture coordinates. +//! +//! Triangles are grouped into charts by flood fill across shared (welded) edges while each face +//! normal stays within 60° of the chart's seed face, so every chart is a height field over its +//! seed plane and projects onto it without flipping. Charts are rotated to their principal axes +//! and shelf-packed per material into 0..1 with one uniform scale, so texel density is the same +//! everywhere within a material. + +use std::collections::{HashMap, VecDeque}; + +use glam::{Vec2, Vec3}; + +use crate::{GeomError, Mesh, Result}; + +/// Faces of a chart stay within this angle of the seed face normal (cos 60°). +const CHART_COS: f32 = 0.5; +/// Packing never goes beyond this virtual resolution (texels per side). +const MAX_PACK_RES: f32 = 65_536.0; + +/// Welded vertex id per vertex: vertices at the same position (snapped to a grid of 1e-6 of +/// the bounding diagonal) share an id. Ids are dense, in order of first appearance. +pub fn weld_ids(positions: &[Vec3]) -> Vec { + let (lo, hi) = positions.iter().fold((Vec3::splat(f32::MAX), Vec3::splat(f32::MIN)), |(lo, hi), p| (lo.min(*p), hi.max(*p))); + let cell = ((hi - lo).length() * 1e-6).max(1e-12); + let mut map: HashMap<[i64; 3], u32> = HashMap::with_capacity(positions.len()); + positions + .iter() + .map(|p| { + let q = ((*p - lo) / cell).round(); + let next = map.len() as u32; + *map.entry([q.x as i64, q.y as i64, q.z as i64]).or_insert(next) + }) + .collect() +} + +/// True when the mesh has triangles and every one of them has two corners at the same position. +/// MikkTSpace (and so [`Mesh::compute_tangents`]) crashes on such meshes, so callers reject them. +pub fn all_triangles_degenerate(mesh: &Mesh) -> bool { + let p = |i: &u32| mesh.positions.get(*i as usize); + !mesh.indices.is_empty() + && mesh.indices.chunks(3).all(|t| match t { + [a, b, c] => p(a) == p(b) || p(a) == p(c) || p(b) == p(c), + _ => true, + }) +} + +struct Chart { + material: usize, + /// Projection basis (right-handed with the seed normal). + t: Vec3, + b: Vec3, + /// Rotation to the chart's principal axes (cos, sin). + rot: Vec2, + lo: Vec2, + hi: Vec2, + /// Texel offset of the chart's packed rectangle and the material's scale and resolution. + offset: Vec2, +} + +impl Chart { + fn local(&self, p: Vec3) -> Vec2 { + let q = Vec2::new(p.dot(self.t), p.dot(self.b)); + Vec2::new(q.x * self.rot.x - q.y * self.rot.y, q.x * self.rot.y + q.y * self.rot.x) + } + fn size(&self) -> Vec2 { + (self.hi - self.lo).max(Vec2::ZERO) + } +} + +/// Replace the UVs of `mesh` with an automatic non-overlapping layout: each material gets its +/// own 0..1 space with charts at least `padding_texels` (minimum 1) away from each other and +/// the borders at `resolution`. Vertices are split at chart borders; tangents are recomputed. +/// Returns the number of charts. +pub fn auto_unwrap(mesh: &mut Mesh, padding_texels: f32, resolution: u32) -> Result { + mesh.validate_indices()?; + if all_triangles_degenerate(mesh) { + return Err(GeomError::Invalid("every triangle of the mesh is degenerate".into())); + } + if mesh.normals.len() != mesh.positions.len() { + mesh.compute_normals(); + } + let n = mesh.triangle_count(); + let weld = weld_ids(&mesh.positions); + let pos = |v: usize| mesh.positions.get(v).copied().unwrap_or_default(); + let wid = |v: usize| weld.get(v).copied().unwrap_or(u32::MAX); + + // Face normals (None for degenerate faces) and materials. + let mut normal: Vec> = Vec::with_capacity(n); + let mut area = Vec::with_capacity(n); + for t in 0..n { + let [a, b, c] = mesh.tri(t).unwrap_or([0; 3]); + let cr = (pos(b) - pos(a)).cross(pos(c) - pos(a)); + area.push(cr.length() * 0.5); + normal.push(cr.try_normalize()); + } + let mut material = vec![0usize; n]; + for s in &mesh.submeshes { + for t in (s.start / 3) as usize..((s.start as usize + s.count as usize) / 3) { + if let Some(m) = material.get_mut(t) { + *m = s.material; + } + } + } + + // Manifold edge adjacency over welded vertices: edge → (face, face, count). + let mut edges: HashMap<(u32, u32), (u32, u32, u8)> = HashMap::with_capacity(n * 2); + let tri_edges = |t: usize| -> [(u32, u32); 3] { + let [a, b, c] = mesh.tri(t).unwrap_or([0; 3]); + let key = |x: usize, y: usize| { + let (p, q) = (wid(x), wid(y)); + (p.min(q), p.max(q)) + }; + [key(a, b), key(b, c), key(c, a)] + }; + for t in 0..n { + for e in tri_edges(t) { + if e.0 == e.1 { + continue; + } + let slot = edges.entry(e).or_insert((t as u32, u32::MAX, 0)); + if slot.2 == 1 { + slot.1 = t as u32; + } + slot.2 = slot.2.saturating_add(1); + } + } + + // Grow charts from the largest unassigned faces. + let mut order: Vec = (0..n).collect(); + order.sort_by(|a, b| area[*b].total_cmp(&area[*a])); + let mut chart_of = vec![u32::MAX; n]; + let mut charts: Vec = Vec::new(); + let mut queue = VecDeque::new(); + for &seed in &order { + if chart_of[seed] != u32::MAX { + continue; + } + let id = charts.len() as u32; + let sn = normal[seed].unwrap_or(Vec3::Z); + let t = sn.any_orthonormal_vector(); + charts.push(Chart { material: material[seed], t, b: sn.cross(t), rot: Vec2::X, lo: Vec2::ZERO, hi: Vec2::ZERO, offset: Vec2::ZERO }); + chart_of[seed] = id; + queue.push_back(seed); + while let Some(f) = queue.pop_front() { + for e in tri_edges(f) { + let Some(&(f0, f1, 2)) = edges.get(&e) else { continue }; + let g = if f0 as usize == f { f1 } else { f0 } as usize; + let ok = normal.get(g).is_some_and(|nn| nn.is_none_or(|nn| nn.dot(sn) >= CHART_COS)); + if ok && chart_of.get(g) == Some(&u32::MAX) && material.get(g) == Some(&material[seed]) { + chart_of[g] = id; + queue.push_back(g); + } + } + } + } + + // Principal axes and bounds of every chart. + let mut cov = vec![(Vec2::ZERO, [0.0f64; 3], 0usize); charts.len()]; + for (t, &c) in chart_of.iter().enumerate() { + let c = c as usize; + for v in mesh.tri(t).unwrap_or([0; 3]) { + if let (Some(ch), Some(acc)) = (charts.get(c), cov.get_mut(c)) { + let q = ch.local(pos(v)); + acc.0 += q; + acc.1[0] += (q.x * q.x) as f64; + acc.1[1] += (q.y * q.y) as f64; + acc.1[2] += (q.x * q.y) as f64; + acc.2 += 1; + } + } + } + for (ch, (sum, m, k)) in charts.iter_mut().zip(&cov) { + let k = (*k).max(1) as f64; + let (mx, my) = (sum.x as f64 / k, sum.y as f64 / k); + let (cxx, cyy, cxy) = (m[0] / k - mx * mx, m[1] / k - my * my, m[2] / k - mx * my); + let angle = 0.5 * (2.0 * cxy).atan2(cxx - cyy); + // Rotate so the principal axis lies along x. + ch.rot = Vec2::new((-angle).cos() as f32, (-angle).sin() as f32); + ch.lo = Vec2::splat(f32::MAX); + ch.hi = Vec2::splat(f32::MIN); + } + for (t, &c) in chart_of.iter().enumerate() { + let c = c as usize; + for v in mesh.tri(t).unwrap_or([0; 3]) { + if let Some(ch) = charts.get_mut(c) { + let q = ch.local(pos(v)); + ch.lo = ch.lo.min(q); + ch.hi = ch.hi.max(q); + } + } + } + for ch in &mut charts { + if ch.size().y > ch.size().x { + // Quarter turn (x, y) → (y, −x) so shelves stay low. + ch.rot = Vec2::new(ch.rot.y, -ch.rot.x); + let (lo, hi) = (ch.lo, ch.hi); + ch.lo = Vec2::new(lo.y, -hi.x); + ch.hi = Vec2::new(hi.y, -lo.x); + } + } + + // Pack each material's charts into its own 0..1 square. + let pad = padding_texels.max(1.0); + let mut scale = HashMap::new(); + let mats: std::collections::BTreeSet = charts.iter().map(|c| c.material).collect(); + for m in mats { + let ids: Vec = (0..charts.len()).filter(|i| charts[*i].material == m).collect(); + let sizes: Vec = ids.iter().map(|i| charts[*i].size()).collect(); + let (s, res, offsets) = pack(&sizes, resolution.max(16) as f32, pad)?; + for (i, o) in ids.iter().zip(offsets) { + charts[*i].offset = o; + } + scale.insert(m, (s, res)); + } + + // Rebuild vertices: one per (vertex, chart). + let mut remap: HashMap<(u32, u32), u32> = HashMap::with_capacity(mesh.positions.len() * 2); + let (mut positions, mut normals, mut uvs, mut colors) = (Vec::new(), Vec::new(), Vec::new(), Vec::new()); + let mut indices = Vec::with_capacity(mesh.indices.len()); + for (t, &c) in chart_of.iter().enumerate() { + let Some(ch) = charts.get(c as usize) else { continue }; + let (s, res) = scale.get(&ch.material).copied().unwrap_or((0.0, 1.0)); + for v in mesh.tri(t).unwrap_or([0; 3]) { + let idx = *remap.entry((v as u32, c)).or_insert_with(|| { + let q = ch.local(pos(v)); + // Chart y points up; UV v points down the image. + let texel = ch.offset + Vec2::splat(pad) + Vec2::new(q.x - ch.lo.x, ch.hi.y - q.y) * s; + positions.push(pos(v)); + normals.push(mesh.normals.get(v).copied().unwrap_or(Vec3::Y)); + if let Some(c) = mesh.colors.get(v) { + colors.push(*c); + } + uvs.push((texel / res).clamp(Vec2::ZERO, Vec2::ONE)); + (positions.len() - 1) as u32 + }); + indices.push(idx); + } + } + mesh.positions = positions; + mesh.normals = normals; + mesh.uvs = uvs; + mesh.colors = colors; + mesh.indices = indices; + mesh.compute_tangents(); + mesh.validate()?; + Ok(charts.len()) +} + +/// Shelf-pack rectangles of world `sizes` (each grown by `pad` texels per side) into a square of +/// `res` texels with the largest uniform scale that fits. Returns (texels per world unit, +/// resolution used, texel offset per rectangle). The resolution doubles when the padding alone +/// cannot fit (very many charts), so the result always fits in 0..1. +fn pack(sizes: &[Vec2], mut res: f32, pad: f32) -> Result<(f32, f32, Vec)> { + let mut order: Vec = (0..sizes.len()).collect(); + order.sort_by(|a, b| sizes[*b].y.total_cmp(&sizes[*a].y)); + let place = |s: f32, res: f32| -> Option> { + let mut out = vec![Vec2::ZERO; sizes.len()]; + let (mut x, mut y, mut shelf) = (0.0f32, 0.0f32, 0.0f32); + for &i in &order { + let r = sizes[i] * s + Vec2::splat(2.0 * pad); + if r.x > res { + return None; + } + if x + r.x > res { + y += shelf; + x = 0.0; + shelf = 0.0; + } + if y + r.y > res { + return None; + } + out[i] = Vec2::new(x, y); + x += r.x; + shelf = shelf.max(r.y); + } + Some(out) + }; + while place(0.0, res).is_none() { + res *= 2.0; + if res > MAX_PACK_RES { + return Err(GeomError::Invalid("too many UV charts to pack".into())); + } + } + let largest = sizes.iter().map(|s| s.max_element()).fold(0.0f32, f32::max); + if largest <= 0.0 { + return Ok((0.0, res, place(0.0, res).unwrap_or_default())); + } + let (mut lo, mut hi) = (0.0f32, (res - 2.0 * pad).max(0.0) / largest); + if place(hi, res).is_some() { + lo = hi; + } + for _ in 0..40 { + if hi - lo <= lo * 1e-4 { + break; + } + let mid = 0.5 * (lo + hi); + if place(mid, res).is_some() { lo = mid } else { hi = mid } + } + Ok((lo, res, place(lo, res).unwrap_or_default())) +} + +impl Mesh { + /// Index-range checks only (attribute arrays may be incomplete before unwrapping). + fn validate_indices(&self) -> Result<()> { + let n = self.positions.len(); + if !self.indices.len().is_multiple_of(3) || self.indices.iter().any(|i| *i as usize >= n) { + return Err(GeomError::Invalid("mesh indices are out of range".into())); + } + if self.triangle_count() > crate::MAX_TRIANGLES { + return Err(GeomError::Invalid(format!("mesh has more than {} triangles", crate::MAX_TRIANGLES))); + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{UvGBuffer, primitives}; + + fn check(mut m: Mesh, min_coverage: f32) { + m.uvs.clear(); + let charts = auto_unwrap(&mut m, 4.0, 512).unwrap(); + assert!(charts >= 1); + m.validate().unwrap(); + assert!(m.uvs.iter().all(|uv| (0.0..=1.0).contains(&uv.x) && (0.0..=1.0).contains(&uv.y))); + let g = UvGBuffer::new(&m, 0, 512, 512); + let covered = g.covered_count() as f32; + let coverage = covered / (512.0 * 512.0); + assert!(coverage > min_coverage, "coverage {coverage} with {charts} charts"); + assert!((g.overlaps as f32) < covered * 0.005, "overlaps {} of {covered}", g.overlaps); + } + + #[test] + fn sphere_unwraps_without_overlaps() { + check(primitives::sphere(1.0, 48, 24), 0.3); + } + + #[test] + fn cube_unwraps_without_overlaps() { + check(primitives::cube(2.0), 0.3); + } + + #[test] + fn torus_and_material_ball_unwrap() { + check(primitives::torus(1.0, 0.3, 48, 24), 0.2); + let mut ball = primitives::material_ball(); + ball.uvs.clear(); + auto_unwrap(&mut ball, 2.0, 1024).unwrap(); + for m in 0..ball.materials.len() { + let g = UvGBuffer::new(&ball, m, 512, 512); + assert!((g.overlaps as f32) < g.covered_count() as f32 * 0.005 + 1.0, "material {m}: {} overlaps", g.overlaps); + } + } + + #[test] + fn many_tiny_charts_still_fit() { + // 2000 disconnected triangles: the packer grows its virtual resolution. + let mut p = Vec::new(); + let mut idx = Vec::new(); + for i in 0..2000u32 { + let o = Vec3::new(i as f32 * 3.0, 0.0, 0.0); + p.extend([o, o + Vec3::X, o + Vec3::Y]); + idx.extend([i * 3, i * 3 + 1, i * 3 + 2]); + } + let mut m = Mesh::from_parts(p, None, Vec::new(), idx, "m").unwrap(); + auto_unwrap(&mut m, 4.0, 128).unwrap(); + assert!(m.uvs.iter().all(|uv| (0.0..=1.0).contains(&uv.x) && (0.0..=1.0).contains(&uv.y))); + } + + #[test] + fn degenerate_and_empty_meshes_do_not_fail() { + let mut empty = Mesh::default(); + assert_eq!(auto_unwrap(&mut empty, 4.0, 256).unwrap(), 0); + // A sliver (zero-area) triangle next to a real one. + let p = vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::X * 2.0]; + let mut m = Mesh::from_parts(p, None, Vec::new(), vec![0, 1, 2, 0, 1, 3], "m").unwrap(); + auto_unwrap(&mut m, 4.0, 256).unwrap(); + m.validate().unwrap(); + let mut point = Mesh { positions: vec![Vec3::ONE; 3], indices: vec![0, 1, 2], ..Mesh::default() }; + assert!(all_triangles_degenerate(&point)); + assert!(auto_unwrap(&mut point, 4.0, 256).is_err()); + } +} diff --git a/crates/image/Cargo.toml b/crates/image/Cargo.toml new file mode 100644 index 00000000..c8f371a3 --- /dev/null +++ b/crates/image/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "materialcraft-image" +description = "MaterialCraft image buffers: grayscale and color float planes, sampling, resampling, conversions" +version.workspace = true +edition.workspace = true +license.workspace = true + +[lints] +workspace = true + +[dependencies] +rayon = { workspace = true } +thiserror = { workspace = true } diff --git a/crates/image/src/lib.rs b/crates/image/src/lib.rs new file mode 100644 index 00000000..7f6c150e --- /dev/null +++ b/crates/image/src/lib.rs @@ -0,0 +1,339 @@ +//! # materialcraft-image +//! +//! Image buffers for node cooking, L0: an [`Image`] is a grayscale (1 channel) or color (RGBA) +//! plane of `f32`, shared copy-on-write through an `Arc` so cached node outputs cost nothing to +//! hand around. Values are linear and usually 0..1 (HDR formats may exceed it). Sampling wraps or +//! clamps per axis ("tiling"); everything per pixel runs in parallel rows (rayon). +#![forbid(unsafe_code)] +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +use std::sync::Arc; + +use rayon::prelude::*; + +/// Largest side an image may have (an allocation cap for hostile sizes). +pub const MAX_SIDE: u32 = 8192; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Kind { + Gray, + Color, +} + +impl Kind { + pub fn channels(self) -> usize { + match self { + Kind::Gray => 1, + Kind::Color => 4, + } + } +} + +#[derive(Debug, thiserror::Error)] +pub enum ImageError { + #[error("image size {0}x{1} is outside 1..={MAX_SIDE}")] + BadSize(u32, u32), +} + +#[derive(Clone, Debug)] +pub struct Image { + pub w: u32, + pub h: u32, + pub kind: Kind, + /// Row-major, `kind.channels()` floats per pixel. + pub data: Arc>, +} + +impl PartialEq for Image { + fn eq(&self, o: &Image) -> bool { + self.w == o.w && self.h == o.h && self.kind == o.kind && (Arc::ptr_eq(&self.data, &o.data) || self.data == o.data) + } +} + +/// Clamp a requested size into the allowed range. +pub fn clamp_size(w: u32, h: u32) -> (u32, u32) { + (w.clamp(1, MAX_SIDE), h.clamp(1, MAX_SIDE)) +} + +#[inline] +fn wrap(i: i64, n: u32, tile: bool) -> usize { + let n = n as i64; + if tile { i.rem_euclid(n) as usize } else { i.clamp(0, n - 1) as usize } +} + +impl Image { + /// A constant image. + pub fn filled(w: u32, h: u32, kind: Kind, v: [f32; 4]) -> Image { + let (w, h) = clamp_size(w, h); + let n = (w * h) as usize; + let data = match kind { + Kind::Gray => vec![v[0]; n], + Kind::Color => v.iter().copied().cycle().take(n * 4).collect(), + }; + Image { w, h, kind, data: Arc::new(data) } + } + + /// Generate every pixel with `f(x, y)` (pixel indices) in parallel rows. + pub fn generate(w: u32, h: u32, kind: Kind, f: impl Fn(u32, u32) -> [f32; 4] + Sync) -> Image { + let (w, h) = clamp_size(w, h); + let c = kind.channels(); + let mut data = vec![0.0f32; (w * h) as usize * c]; + data.par_chunks_mut(w as usize * c).enumerate().for_each(|(y, row)| { + for x in 0..w as usize { + let p = f(x as u32, y as u32); + row[x * c..x * c + c].copy_from_slice(&p[..c]); + } + }); + Image { w, h, kind, data: Arc::new(data) } + } + + /// Generate from normalized coordinates (pixel centers, 0..1). + pub fn generate_uv(w: u32, h: u32, kind: Kind, f: impl Fn(f32, f32) -> [f32; 4] + Sync) -> Image { + let (iw, ih) = (1.0 / w.max(1) as f32, 1.0 / h.max(1) as f32); + Image::generate(w, h, kind, |x, y| f((x as f32 + 0.5) * iw, (y as f32 + 0.5) * ih)) + } + + pub fn gray(w: u32, h: u32, f: impl Fn(u32, u32) -> f32 + Sync) -> Image { + Image::generate(w, h, Kind::Gray, |x, y| [f(x, y), 0.0, 0.0, 0.0]) + } + + pub fn channels(&self) -> usize { + self.kind.channels() + } + + pub fn is_gray(&self) -> bool { + self.kind == Kind::Gray + } + + /// The pixel at integer coordinates (wrapped or clamped), as RGBA (gray → `[v, v, v, 1]`). + #[inline] + pub fn get(&self, x: i64, y: i64, tile: bool) -> [f32; 4] { + let (x, y) = (wrap(x, self.w, tile), wrap(y, self.h, tile)); + let i = y * self.w as usize + x; + match self.kind { + Kind::Gray => { + let v = self.data.get(i).copied().unwrap_or(0.0); + [v, v, v, 1.0] + } + Kind::Color => { + let s = self.data.get(i * 4..i * 4 + 4).unwrap_or(&[0.0, 0.0, 0.0, 1.0]); + [s[0], s[1], s[2], s[3]] + } + } + } + + /// The gray value, or the Rec. 709 luminance of a color image. + #[inline] + pub fn get_gray(&self, x: i64, y: i64, tile: bool) -> f32 { + let p = self.get(x, y, tile); + match self.kind { + Kind::Gray => p[0], + Kind::Color => luminance(p), + } + } + + /// Bilinear sample at normalized `(u, v)`; pixel centers sit at `(i + 0.5) / w`. + #[inline] + pub fn sample(&self, u: f32, v: f32, tile: bool) -> [f32; 4] { + let fx = u * self.w as f32 - 0.5; + let fy = v * self.h as f32 - 0.5; + if !fx.is_finite() || !fy.is_finite() { + return [0.0, 0.0, 0.0, 1.0]; + } + let (x0, y0) = (fx.floor(), fy.floor()); + let (tx, ty) = (fx - x0, fy - y0); + let (x0, y0) = (x0 as i64, y0 as i64); + let a = self.get(x0, y0, tile); + let b = self.get(x0 + 1, y0, tile); + let c = self.get(x0, y0 + 1, tile); + let d = self.get(x0 + 1, y0 + 1, tile); + let mut o = [0.0; 4]; + for k in 0..4 { + let top = a[k] + (b[k] - a[k]) * tx; + let bot = c[k] + (d[k] - c[k]) * tx; + o[k] = top + (bot - top) * ty; + } + o + } + + #[inline] + pub fn sample_gray(&self, u: f32, v: f32, tile: bool) -> f32 { + let p = self.sample(u, v, tile); + match self.kind { + Kind::Gray => p[0], + Kind::Color => luminance(p), + } + } + + /// Nearest sample at normalized `(u, v)`. + #[inline] + pub fn sample_nearest(&self, u: f32, v: f32, tile: bool) -> [f32; 4] { + let x = (u * self.w as f32).floor(); + let y = (v * self.h as f32).floor(); + if !x.is_finite() || !y.is_finite() { + return [0.0, 0.0, 0.0, 1.0]; + } + self.get(x as i64, y as i64, tile) + } + + /// Map every pixel (as RGBA) to a new image of `kind`, same size. + pub fn map(&self, kind: Kind, f: impl Fn([f32; 4]) -> [f32; 4] + Sync) -> Image { + Image::generate(self.w, self.h, kind, |x, y| f(self.get(x as i64, y as i64, false))) + } + + /// This image as grayscale (luminance of a color image). + pub fn to_gray(&self) -> Image { + match self.kind { + Kind::Gray => self.clone(), + Kind::Color => self.map(Kind::Gray, |p| [luminance(p), 0.0, 0.0, 0.0]), + } + } + + /// This image as RGBA (gray copied to RGB, alpha 1). + pub fn to_color(&self) -> Image { + match self.kind { + Kind::Color => self.clone(), + Kind::Gray => self.map(Kind::Color, |p| p), + } + } + + pub fn to_kind(&self, kind: Kind) -> Image { + match kind { + Kind::Gray => self.to_gray(), + Kind::Color => self.to_color(), + } + } + + /// Resample to `w × h` (bilinear when enlarging, box-filtered when shrinking). + pub fn resize(&self, w: u32, h: u32, tile: bool) -> Image { + let (w, h) = clamp_size(w, h); + if w == self.w && h == self.h { + return self.clone(); + } + if w <= self.w && h <= self.h && self.w % w == 0 && self.h % h == 0 { + let (fx, fy) = ((self.w / w) as i64, (self.h / h) as i64); + let inv = 1.0 / (fx * fy) as f32; + return Image::generate(w, h, self.kind, |x, y| { + let mut s = [0.0; 4]; + for j in 0..fy { + for i in 0..fx { + let p = self.get(x as i64 * fx + i, y as i64 * fy + j, tile); + for k in 0..4 { + s[k] += p[k]; + } + } + } + s.map(|v| v * inv) + }); + } + Image::generate_uv(w, h, self.kind, |u, v| self.sample(u, v, tile)) + } + + /// Raw float access for gray images (`None` for color). + pub fn gray_data(&self) -> Option<&[f32]> { + (self.kind == Kind::Gray).then_some(self.data.as_slice()) + } + + /// 8-bit sRGB-encoded RGBA for display (gray shown as is; color through the sRGB curve). + pub fn to_rgba8_display(&self) -> Vec { + let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; + let n = (self.w * self.h) as usize; + let mut out = vec![0u8; n * 4]; + out.par_chunks_mut(4).enumerate().for_each(|(i, px)| match self.kind { + Kind::Gray => { + let v = q(self.data.get(i).copied().unwrap_or(0.0)); + px.copy_from_slice(&[v, v, v, 255]); + } + Kind::Color => { + let s = self.data.get(i * 4..i * 4 + 4).unwrap_or(&[0.0, 0.0, 0.0, 1.0]); + px.copy_from_slice(&[q(linear_to_srgb(s[0])), q(linear_to_srgb(s[1])), q(linear_to_srgb(s[2])), q(s[3])]); + } + }); + out + } + + /// Mean of each channel (as RGBA), e.g. for tests and auto levels. + pub fn mean(&self) -> [f32; 4] { + let c = self.channels(); + let n = (self.w * self.h) as f64; + let mut s = [0f64; 4]; + for px in self.data.chunks(c) { + for (k, v) in px.iter().enumerate() { + s[k] += *v as f64; + } + } + if c == 1 { + let m = (s[0] / n) as f32; + return [m, m, m, 1.0]; + } + s.map(|v| (v / n) as f32) + } + + /// Minimum and maximum over all channels (alpha excluded). + pub fn range(&self) -> (f32, f32) { + let c = self.channels(); + let mut lo = f32::INFINITY; + let mut hi = f32::NEG_INFINITY; + for px in self.data.chunks(c) { + for v in px.iter().take(c.min(3)) { + lo = lo.min(*v); + hi = hi.max(*v); + } + } + if lo > hi { (0.0, 0.0) } else { (lo, hi) } + } +} + +/// Rec. 709 luminance of a linear RGB(A) pixel. +#[inline] +pub fn luminance(p: [f32; 4]) -> f32 { + 0.2126 * p[0] + 0.7152 * p[1] + 0.0722 * p[2] +} + +#[inline] +pub fn linear_to_srgb(v: f32) -> f32 { + if v <= 0.003_130_8 { v * 12.92 } else { 1.055 * v.max(0.0).powf(1.0 / 2.4) - 0.055 } +} + +#[inline] +pub fn srgb_to_linear(v: f32) -> f32 { + if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn sample_wraps_and_clamps() { + let img = Image::gray(4, 1, |x, _| x as f32); + assert_eq!(img.get(-1, 0, true)[0], 3.0); + assert_eq!(img.get(-1, 0, false)[0], 0.0); + // Halfway between the last and the (wrapped) first pixel. + assert!((img.sample(1.0, 0.5, true)[0] - 1.5).abs() < 1e-5); + } + + #[test] + fn resize_box_and_bilinear() { + let img = Image::gray(4, 4, |x, _| if x < 2 { 0.0 } else { 1.0 }); + let small = img.resize(2, 2, true); + assert_eq!(small.data.as_slice(), &[0.0, 1.0, 0.0, 1.0]); + let big = small.resize(8, 8, false); + assert_eq!(big.w, 8); + assert!(big.data[0] < big.data[7]); + } + + #[test] + fn hostile_sizes_are_clamped() { + let img = Image::filled(0, u32::MAX, Kind::Gray, [0.5; 4]); + assert_eq!((img.w, img.h), (1, MAX_SIDE)); + assert_eq!(img.sample(f32::NAN, 0.0, true), [0.0, 0.0, 0.0, 1.0]); + } + + #[test] + fn conversions() { + let c = Image::filled(2, 2, Kind::Color, [1.0, 1.0, 1.0, 1.0]); + assert!((c.to_gray().data[0] - 1.0).abs() < 1e-5); + assert_eq!(c.to_rgba8_display()[0], 255); + } +} diff --git a/crates/nodes/Cargo.toml b/crates/nodes/Cargo.toml new file mode 100644 index 00000000..437bb96d --- /dev/null +++ b/crates/nodes/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "materialcraft-nodes" +description = "MaterialCraft node library: definitions and CPU implementations of every node" +version.workspace = true +edition.workspace = true +license.workspace = true + +[lints] +workspace = true + +[dependencies] +materialcraft-core = { workspace = true } +materialcraft-image = { workspace = true } +rayon = { workspace = true } diff --git a/crates/nodes/src/atomic.rs b/crates/nodes/src/atomic.rs new file mode 100644 index 00000000..08296bed --- /dev/null +++ b/crates/nodes/src/atomic.rs @@ -0,0 +1,524 @@ +//! The atomic nodes: the built-in operations every graph is made of (blend, blur, levels, +//! curve, HSL, warp, transform, normal, distance, …) plus the graph's own input, output and +//! dot nodes. + +use materialcraft_core::Gradient; +use materialcraft_image::{Image, Kind, luminance}; + +use crate::catalog::{CookResult, Ctx, NodeDef, PortKind, node}; +use crate::ops::{self, BLEND_MODES}; + +pub const ATOMIC: &str = "Atomic nodes"; +pub const GRAPH_ITEMS: &str = "Graph items"; + +/// Output usages (the material channel an output feeds). +pub const USAGES: &[&str] = &["Base color", "Normal", "Roughness", "Metallic", "Height", "Ambient occlusion", "Emissive", "Opacity", "Specular", "Any"]; + +/// Machine ids of [`USAGES`], used in exports and inspect output. +pub const USAGE_IDS: &[&str] = &["baseColor", "normal", "roughness", "metallic", "height", "ambientOcclusion", "emissive", "opacity", "specular", "any"]; + +pub(crate) fn defs() -> Vec { + vec![ + node("bitmap", "Bitmap", ATOMIC) + .desc("A bitmap resource of the package, resampled to the node size.") + .atomic() + .generator() + .resource("resource", "Bitmap resource") + .color_out() + .cook(bitmap), + node("blend", "Blend", ATOMIC) + .desc("Blends a foreground over a background with a blending mode, weighted by opacity and an optional mask.") + .atomic() + .any_in("foreground", "Foreground") + .any_in("background", "Background") + .gray_in("mask", "Opacity") + .float("opacity", "Opacity", 1.0, 0.0, 1.0) + .choice("mode", "Blending mode", BLEND_MODES, 0) + .choice("alpha", "Alpha blending", &["Use source alpha", "Ignore alpha"], 0) + .cook(blend), + node("blur", "Blur", ATOMIC).desc("Gaussian blur.").atomic().any_in("input", "Input").float("intensity", "Intensity", 2.0, 0.0, 32.0).cook(blur), + node("channels_shuffle", "Channels Shuffle", ATOMIC) + .desc("Builds a color image from any channels of two inputs.") + .atomic() + .any_in("input1", "Input 1") + .any_in("input2", "Input 2") + .choice("red", "Red", CHANNEL_SOURCES, 0) + .choice("green", "Green", CHANNEL_SOURCES, 1) + .choice("blue", "Blue", CHANNEL_SOURCES, 2) + .choice("alpha", "Alpha", CHANNEL_SOURCES, 3) + .color_out() + .cook(channels_shuffle), + node("curve", "Curve", ATOMIC).desc("Remaps values through a tone curve.").atomic().any_in("input", "Input").curve("curve", "Curve").cook(curve), + node("directional_blur", "Directional Blur", ATOMIC) + .desc("Blurs along one direction.") + .atomic() + .any_in("input", "Input") + .float("intensity", "Intensity", 10.0, 0.0, 64.0) + .angle("angle", "Angle", 0.0) + .cook(directional_blur), + node("directional_warp", "Directional Warp", ATOMIC) + .desc("Offsets the input along a direction, by an intensity map.") + .atomic() + .any_in("input", "Input") + .gray_in("intensity_input", "Intensity input") + .float("intensity", "Intensity", 10.0, 0.0, 64.0) + .angle("angle", "Warp angle", 0.0) + .cook(directional_warp), + node("distance", "Distance", ATOMIC) + .desc("Grows white areas of a mask into a distance gradient; with a source, spreads its colors outward.") + .atomic() + .gray_in("mask", "Mask") + .any_in("source", "Source") + .float("distance", "Maximum distance", 10.0, 0.0, 256.0) + .boolean("combine", "Combine distance with source", false) + .cook(distance), + node("emboss", "Emboss", ATOMIC) + .desc("Lights the input with the relief of a height map.") + .atomic() + .any_in("input", "Input") + .gray_in("height", "Height") + .float("intensity", "Intensity", 5.0, 0.0, 32.0) + .angle("light_angle", "Light angle", 0.375) + .color("highlight", "Highlight color", [1.0, 1.0, 1.0, 1.0]) + .color("shadow", "Shadow color", [0.0, 0.0, 0.0, 1.0]) + .cook(emboss), + node("gradient_dynamic", "Gradient (Dynamic)", ATOMIC) + .desc("Maps a grayscale input through the colors of a row of a gradient image.") + .atomic() + .gray_in("input", "Input") + .color_in("gradient", "Gradient") + .float("position", "Position", 0.5, 0.0, 1.0) + .choice("orientation", "Orientation", &["Horizontal", "Vertical"], 0) + .color_out() + .cook(gradient_dynamic), + node("gradient_map", "Gradient Map", ATOMIC) + .desc("Maps grayscale values to colors along a gradient.") + .atomic() + .gray_in("input", "Input") + .gradient("gradient", "Gradient", Gradient::default()) + .choice("mode", "Color mode", &["Color", "Grayscale"], 0) + .cook(gradient_map), + node("grayscale_conversion", "Grayscale Conversion", ATOMIC) + .desc("Weighted sum of the RGBA channels.") + .atomic() + .color_in("input", "Input") + .float("red", "Red weight", 0.333, 0.0, 1.0) + .float("green", "Green weight", 0.333, 0.0, 1.0) + .float("blue", "Blue weight", 0.333, 0.0, 1.0) + .float("alpha", "Alpha weight", 0.0, 0.0, 1.0) + .boolean("flatten_alpha", "Flatten alpha", false) + .gray_out() + .cook(grayscale_conversion), + node("hsl", "HSL", ATOMIC) + .desc("Hue, saturation and lightness adjustments (0.5 = unchanged).") + .atomic() + .color_in("input", "Input") + .float("hue", "Hue", 0.5, 0.0, 1.0) + .float("saturation", "Saturation", 0.5, 0.0, 1.0) + .float("lightness", "Lightness", 0.5, 0.0, 1.0) + .color_out() + .cook(hsl), + node("levels", "Levels", ATOMIC) + .desc("Remaps the input range, midtones and output range.") + .atomic() + .any_in("input", "Input") + .float("in_low", "Level in low", 0.0, 0.0, 1.0) + .float("in_mid", "Level in mid", 0.5, 0.0, 1.0) + .float("in_high", "Level in high", 1.0, 0.0, 1.0) + .float("out_low", "Level out low", 0.0, 0.0, 1.0) + .float("out_high", "Level out high", 1.0, 0.0, 1.0) + .cook(levels), + node("normal", "Normal", ATOMIC) + .desc("Converts a height map to a tangent-space normal map.") + .atomic() + .gray_in("input", "Input") + .float("intensity", "Intensity", 1.0, 0.0, 10.0) + .choice("format", "Normal format", &["OpenGL", "DirectX"], 0) + .boolean("height_alpha", "Height in alpha", false) + .color_out() + .cook(normal), + node("pixel_processor", "Pixel Processor", ATOMIC) + .desc("Computes every pixel with a function graph ($pos, $size; sample the inputs).") + .atomic() + .any_in("input0", "Input 0") + .any_in("input1", "Input 1") + .any_in("input2", "Input 2") + .any_in("input3", "Input 3") + .function("function", "Per pixel function", crate::function::default_pixel_function()) + .choice("output", "Output", &["Color", "Grayscale"], 0) + .cook(crate::function::pixel_processor), + node("value_processor", "Value Processor", ATOMIC) + .desc("Computes one value with a function graph and outputs it as a uniform image.") + .atomic() + .any_in("input0", "Input 0") + .function("function", "Function", materialcraft_core::function::FnGraph::constant(materialcraft_core::Value::Float(0.5))) + .cook(crate::function::value_processor), + node("sharpen", "Sharpen", ATOMIC) + .desc("Unsharp mask.") + .atomic() + .any_in("input", "Input") + .float("intensity", "Intensity", 1.0, 0.0, 10.0) + .cook(sharpen), + node("transformation", "Transformation 2D", ATOMIC) + .desc("Offsets, scales and rotates the input.") + .atomic() + .any_in("input", "Input") + .float2("offset", "Offset", [0.0, 0.0], -1.0, 1.0) + .float2("scale", "Scale", [1.0, 1.0], 0.01, 10.0) + .angle("rotation", "Rotation", 0.0) + .choice("filtering", "Filtering", &["Bilinear", "Nearest"], 0) + .color("matte", "Matte color", [0.0, 0.0, 0.0, 0.0]) + .cook(transformation), + node("uniform", "Uniform Color", ATOMIC) + .desc("A single color or gray value.") + .atomic() + .generator() + .color("color", "Color", [0.5, 0.5, 0.5, 1.0]) + .choice("mode", "Output", &["Color", "Grayscale"], 0) + .cook(uniform), + node("warp", "Warp", ATOMIC) + .desc("Distorts the input along the slopes of a gradient map.") + .atomic() + .any_in("input", "Input") + .gray_in("gradient", "Gradient") + .float("intensity", "Intensity", 1.0, 0.0, 32.0) + .cook(warp), + node("input_color", "Input Color", GRAPH_ITEMS) + .desc("A color image input of the graph.") + .atomic() + .generator() + .text("identifier", "Identifier", "input") + .color("default", "Default color", [0.5, 0.5, 0.5, 1.0]) + .color_out() + .cook(input_color_default), + node("input_grayscale", "Input Grayscale", GRAPH_ITEMS) + .desc("A grayscale image input of the graph.") + .atomic() + .generator() + .text("identifier", "Identifier", "input") + .color("default", "Default value", [0.5, 0.5, 0.5, 1.0]) + .gray_out() + .cook(input_gray_default), + node("output", "Output", GRAPH_ITEMS) + .desc("An output of the graph: a material channel (usage) or any image.") + .atomic() + .any_in("input", "Input") + .text("identifier", "Identifier", "output") + .choice("usage", "Usage", USAGES, 0) + .cook(passthrough), + node("dot", "Dot", GRAPH_ITEMS).desc("A reroute point for wires.").atomic().any_in("input", "Input").cook(passthrough), + node("graph_instance", "Graph Instance", GRAPH_ITEMS) + .desc("Another graph of the package, used as a node.") + .atomic() + .text("graph", "Graph", "") + .cook(crate::catalog::no_cook), + ] +} + +const CHANNEL_SOURCES: &[&str] = + &["Input 1 red", "Input 1 green", "Input 1 blue", "Input 1 alpha", "Input 2 red", "Input 2 green", "Input 2 blue", "Input 2 alpha", "Black", "White"]; + +fn bitmap(ctx: &Ctx) -> CookResult { + let name = ctx.text("resource"); + match (ctx.resource)(name) { + Some(img) => Ok(vec![img.resize(ctx.w, ctx.h, ctx.tile)]), + None if name.is_empty() => Ok(vec![ctx.gen_color(|u, v| { + let c = if ((u * 8.0) as i32 + (v * 8.0) as i32) % 2 == 0 { 0.8 } else { 0.2 }; + [c, c, c, 1.0] + })]), + None => Err(format!("no bitmap resource `{name}`")), + } +} + +fn blend(ctx: &Ctx) -> CookResult { + let (fg, bg) = (ctx.sized(0), ctx.sized(1)); + let kind = if [&fg, &bg].iter().any(|i| i.as_ref().is_some_and(|i| !i.is_gray())) { Kind::Color } else { Kind::Gray }; + let fg = fg.unwrap_or_else(|| Image::filled(ctx.w, ctx.h, kind, [0.0, 0.0, 0.0, 0.0])); + let bg = bg.unwrap_or_else(|| Image::filled(ctx.w, ctx.h, kind, [0.0, 0.0, 0.0, 1.0])); + let mask = ctx.sized(2).map(|m| m.to_gray()); + let (mode, op) = (ctx.i("mode"), ctx.f("opacity")); + let use_alpha = ctx.i("alpha") == 0 && !fg.is_gray(); + Ok(vec![Image::generate(ctx.w, ctx.h, kind, |x, y| { + let (x, y) = (x as i64, y as i64); + let m = mask.as_ref().map_or(1.0, |m| m.get_gray(x, y, false)); + ops::blend_px(mode, bg.get(x, y, false), fg.get(x, y, false), op * m, use_alpha, true) + })]) +} + +fn blur(ctx: &Ctx) -> CookResult { + let img = ctx.any_or(0, Kind::Gray, [0.0; 4]); + let sigma = ctx.f("intensity").max(0.0) * ctx.w as f32 / 256.0 * 0.5; + Ok(vec![ops::gaussian(&img, sigma, ctx.tile)]) +} + +fn channels_shuffle(ctx: &Ctx) -> CookResult { + let a = ctx.any_or(0, Kind::Color, [0.0, 0.0, 0.0, 1.0]).to_color(); + let b = ctx.any_or(1, Kind::Color, [0.0, 0.0, 0.0, 1.0]).to_color(); + let src = [ctx.i("red"), ctx.i("green"), ctx.i("blue"), ctx.i("alpha")]; + Ok(vec![Image::generate(ctx.w, ctx.h, Kind::Color, |x, y| { + let (pa, pb) = (a.get(x as i64, y as i64, false), b.get(x as i64, y as i64, false)); + src.map(|s| match s { + 0..=3 => pa[s as usize], + 4..=7 => pb[(s - 4) as usize], + 9 => 1.0, + _ => 0.0, + }) + })]) +} + +fn curve(ctx: &Ctx) -> CookResult { + let img = ctx.any_or(0, Kind::Gray, [0.0; 4]); + let c = ctx.curve("curve"); + // A 1024-entry table: the curve is smooth, so linear lookups are exact enough. + let lut: Vec = (0..=1024).map(|i| c.eval(i as f32 / 1024.0)).collect(); + let f = |v: f32| { + let t = v.clamp(0.0, 1.0) * 1024.0; + let i = t as usize; + let a = lut.get(i).copied().unwrap_or(0.0); + let b = lut.get(i + 1).copied().unwrap_or(a); + a + (b - a) * (t - i as f32) + }; + Ok(vec![img.map(img.kind, |p| [f(p[0]), f(p[1]), f(p[2]), p[3]])]) +} + +fn dir_vec(turns: f32) -> (f32, f32) { + let a = turns * std::f32::consts::TAU; + (a.cos(), -a.sin()) +} + +fn directional_blur(ctx: &Ctx) -> CookResult { + let img = ctx.any_or(0, Kind::Gray, [0.0; 4]); + let len = ctx.f("intensity").max(0.0) * ctx.w as f32 / 256.0; + if len < 0.5 { + return Ok(vec![img]); + } + let (dx, dy) = dir_vec(ctx.f("angle")); + let n = (len.ceil() as i32).clamp(1, 512); + let (iw, ih) = (1.0 / ctx.w as f32, 1.0 / ctx.h as f32); + Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| { + let mut acc = [0.0; 4]; + for i in -n..=n { + let t = i as f32 / n as f32 * len * 0.5; + let p = img.sample(u + dx * t * iw, v + dy * t * ih, ctx.tile); + for k in 0..4 { + acc[k] += p[k]; + } + } + acc.map(|a| a / (2 * n + 1) as f32) + })]) +} + +fn directional_warp(ctx: &Ctx) -> CookResult { + let img = ctx.any_or(0, Kind::Gray, [0.0; 4]); + let map = ctx.gray_or(1, 0.0); + let (dx, dy) = dir_vec(ctx.f("angle")); + let k = ctx.f("intensity") / 256.0; + Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| { + let m = map.sample_gray(u, v, ctx.tile) * k; + img.sample(u + dx * m, v + dy * m, ctx.tile) + })]) +} + +fn distance(ctx: &Ctx) -> CookResult { + let mask = ctx.gray_or(0, 0.0); + let maxd = (ctx.f("distance").max(0.0) * ctx.w as f32 / 256.0).max(1e-3); + let data = mask.data.clone(); + let d2 = ops::distance_sq(ctx.w, ctx.h, |i| data.get(i).copied().unwrap_or(0.0) > 0.5, ctx.tile); + let Some(src) = ctx.sized(1) else { + return Ok(vec![ops::gray_from(ctx.w, ctx.h, d2.iter().map(|d| (1.0 - d.sqrt() / maxd).clamp(0.0, 1.0)).collect())]); + }; + // Spread the source's colors: each pixel takes the color of the nearest mask pixel, found by + // walking down the distance field's gradient. + let dist: Vec = d2.iter().map(|d| d.sqrt()).collect(); + let combine = ctx.b("combine"); + let (w, h) = (ctx.w as i64, ctx.h as i64); + let field = ops::gray_from(ctx.w, ctx.h, dist); + Ok(vec![Image::generate(ctx.w, ctx.h, src.kind, |x, y| { + let (mut px, mut py) = (x as f32, y as f32); + for _ in 0..64 { + let d = field.get_gray(px.round() as i64, py.round() as i64, ctx.tile); + if d < 0.5 { + break; + } + let (gx, gy) = ops::slope(&field, px.round() as i64, py.round() as i64, ctx.tile); + let g = (gx * gx + gy * gy).sqrt().max(1e-4); + px -= gx / g * d.min(8.0); + py -= gy / g * d.min(8.0); + if !ctx.tile && (px < 0.0 || py < 0.0 || px >= w as f32 || py >= h as f32) { + break; + } + } + let mut c = src.get(px.round() as i64, py.round() as i64, ctx.tile); + let d = field.get_gray(x as i64, y as i64, ctx.tile); + if d > maxd { + c = [0.0, 0.0, 0.0, if src.is_gray() { 1.0 } else { 0.0 }]; + } else if combine { + let f = (1.0 - d / maxd).clamp(0.0, 1.0); + c = [c[0] * f, c[1] * f, c[2] * f, c[3]]; + } + c + })]) +} + +fn emboss(ctx: &Ctx) -> CookResult { + let img = ctx.any_or(0, Kind::Color, [0.5, 0.5, 0.5, 1.0]); + let hmap = ctx.gray_or(1, 0.0); + let (lx, ly) = dir_vec(ctx.f("light_angle")); + let k = ctx.f("intensity") * ctx.w as f32 / 64.0; + let (hi, sh) = (ctx.v4("highlight"), ctx.v4("shadow")); + Ok(vec![Image::generate(ctx.w, ctx.h, img.kind, |x, y| { + let (gx, gy) = ops::slope(&hmap, x as i64, y as i64, ctx.tile); + let l = (-(gx * lx + gy * ly) * k).clamp(-1.0, 1.0); + let p = img.get(x as i64, y as i64, false); + let tint = if l >= 0.0 { hi } else { sh }; + let t = l.abs(); + [p[0] + (tint[0] - p[0]) * t, p[1] + (tint[1] - p[1]) * t, p[2] + (tint[2] - p[2]) * t, p[3]] + })]) +} + +fn gradient_dynamic(ctx: &Ctx) -> CookResult { + let input = ctx.gray_or(0, 0.0); + let grad = ctx.input(1).map(|g| g.to_color()).unwrap_or_else(|| Image::generate_uv(256, 1, Kind::Color, |u, _| [u, u, u, 1.0])); + let pos = ctx.f("position"); + let vertical = ctx.i("orientation") == 1; + Ok(vec![Image::generate(ctx.w, ctx.h, Kind::Color, |x, y| { + let t = input.get_gray(x as i64, y as i64, false).clamp(0.0, 1.0); + if vertical { grad.sample(pos, t, false) } else { grad.sample(t, pos, false) } + })]) +} + +fn gradient_map(ctx: &Ctx) -> CookResult { + let input = ctx.gray_or(0, 0.0); + let g = ctx.gradient("gradient"); + let lut: Vec<[f32; 4]> = (0..=512).map(|i| g.eval(i as f32 / 512.0)).collect(); + let gray = ctx.i("mode") == 1; + let look = |v: f32| lut.get((v.clamp(0.0, 1.0) * 512.0).round() as usize).copied().unwrap_or([0.0, 0.0, 0.0, 1.0]); + Ok(vec![if gray { input.map(Kind::Gray, |p| [luminance(look(p[0])), 0.0, 0.0, 0.0]) } else { input.map(Kind::Color, |p| look(p[0])) }]) +} + +fn grayscale_conversion(ctx: &Ctx) -> CookResult { + let img = ctx.any_or(0, Kind::Color, [0.0, 0.0, 0.0, 1.0]).to_color(); + let w = [ctx.f("red"), ctx.f("green"), ctx.f("blue"), ctx.f("alpha")]; + let flatten = ctx.b("flatten_alpha"); + Ok(vec![img.map(Kind::Gray, |p| { + let mut v = p[0] * w[0] + p[1] * w[1] + p[2] * w[2] + p[3] * w[3]; + if flatten { + v *= p[3]; + } + [v, 0.0, 0.0, 0.0] + })]) +} + +fn hsl(ctx: &Ctx) -> CookResult { + let img = ctx.any_or(0, Kind::Color, [0.5, 0.5, 0.5, 1.0]).to_color(); + let (dh, sat, lig) = (ctx.f("hue") - 0.5, ctx.f("saturation"), ctx.f("lightness")); + Ok(vec![img.map(Kind::Color, |p| { + let [h, s, l] = ops::rgb_to_hsl(p); + let s = if sat <= 0.5 { s * sat * 2.0 } else { s + (1.0 - s) * (sat - 0.5) * 2.0 }; + let l = if lig <= 0.5 { l * lig * 2.0 } else { l + (1.0 - l) * (lig - 0.5) * 2.0 }; + let c = ops::hsl_to_rgb(h + dh, s.clamp(0.0, 1.0), l.clamp(0.0, 1.0)); + [c[0], c[1], c[2], p[3]] + })]) +} + +/// The Levels mapping for one value. +pub fn levels_fn(v: f32, in_low: f32, in_mid: f32, in_high: f32, out_low: f32, out_high: f32) -> f32 { + let span = in_high - in_low; + let t = if span.abs() < 1e-6 { if v >= in_high { 1.0 } else { 0.0 } } else { ((v - in_low) / span).clamp(0.0, 1.0) }; + let mid = in_mid.clamp(0.001, 0.999); + let g = 0.5f32.ln() / mid.ln(); + out_low + t.powf(g) * (out_high - out_low) +} + +fn levels(ctx: &Ctx) -> CookResult { + let img = ctx.any_or(0, Kind::Gray, [0.0; 4]); + let p = [ctx.f("in_low"), ctx.f("in_mid"), ctx.f("in_high"), ctx.f("out_low"), ctx.f("out_high")]; + let f = |v: f32| levels_fn(v, p[0], p[1], p[2], p[3], p[4]); + Ok(vec![img.map(img.kind, |c| [f(c[0]), f(c[1]), f(c[2]), c[3]])]) +} + +/// Tangent-space normal from a height map; `k` scales the slopes. +pub fn height_to_normal(h: &Image, k: f32, directx: bool, tile: bool, alpha_height: bool) -> Image { + Image::generate(h.w, h.h, Kind::Color, |x, y| { + let (dx, dy) = ops::slope(h, x as i64, y as i64, tile); + let (nx, ny, nz) = (-dx * k, dy * k, 1.0); + let l = (nx * nx + ny * ny + nz * nz).sqrt(); + let ny = if directx { -ny } else { ny }; + let a = if alpha_height { h.get_gray(x as i64, y as i64, tile) } else { 1.0 }; + [nx / l * 0.5 + 0.5, ny / l * 0.5 + 0.5, nz / l * 0.5 + 0.5, a] + }) +} + +fn normal(ctx: &Ctx) -> CookResult { + let h = ctx.gray_or(0, 0.0); + let k = ctx.f("intensity") * ctx.w as f32 / 32.0; + Ok(vec![height_to_normal(&h, k, ctx.i("format") == 1, ctx.tile, ctx.b("height_alpha"))]) +} + +fn sharpen(ctx: &Ctx) -> CookResult { + let img = ctx.any_or(0, Kind::Gray, [0.0; 4]); + let soft = ops::gaussian(&img, 1.0, ctx.tile); + let k = ctx.f("intensity"); + Ok(vec![Image::generate(ctx.w, ctx.h, img.kind, |x, y| { + let (a, b) = (img.get(x as i64, y as i64, false), soft.get(x as i64, y as i64, false)); + [a[0] + (a[0] - b[0]) * k, a[1] + (a[1] - b[1]) * k, a[2] + (a[2] - b[2]) * k, a[3]] + })]) +} + +/// Sample `img` through the inverse of offset → rotate → scale about the center. +pub fn transform_sample(img: &Image, u: f32, v: f32, offset: [f32; 2], scale: [f32; 2], rot_turns: f32, nearest: bool, tile: bool) -> Option<[f32; 4]> { + let (s, c) = (rot_turns * std::f32::consts::TAU).sin_cos(); + let (x, y) = (u - 0.5 - offset[0], v - 0.5 - offset[1]); + let (x, y) = (x * c - y * s, x * s + y * c); + let (sx, sy) = (if scale[0].abs() < 1e-4 { 1e-4 } else { scale[0] }, if scale[1].abs() < 1e-4 { 1e-4 } else { scale[1] }); + let (su, sv) = (x / sx + 0.5, y / sy + 0.5); + if !tile && !(0.0..1.0).contains(&su) || !tile && !(0.0..1.0).contains(&sv) { + return None; + } + Some(if nearest { img.sample_nearest(su, sv, tile) } else { img.sample(su, sv, tile) }) +} + +fn transformation(ctx: &Ctx) -> CookResult { + let img = ctx.any_or(0, Kind::Gray, [0.0; 4]); + let (off, sc, rot) = (ctx.v2("offset"), ctx.v2("scale"), ctx.f("rotation")); + let nearest = ctx.i("filtering") == 1; + let matte = ctx.v4("matte"); + Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| transform_sample(&img, u, v, off, sc, rot, nearest, ctx.tile).unwrap_or(matte))]) +} + +fn uniform(ctx: &Ctx) -> CookResult { + let c = ctx.v4("color"); + Ok(vec![if ctx.i("mode") == 1 { Image::filled(ctx.w, ctx.h, Kind::Gray, [luminance(c); 4]) } else { Image::filled(ctx.w, ctx.h, Kind::Color, c) }]) +} + +fn warp(ctx: &Ctx) -> CookResult { + let img = ctx.any_or(0, Kind::Gray, [0.0; 4]); + let grad = ctx.gray_or(1, 0.0); + let k = ctx.f("intensity"); + Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| { + let (x, y) = ((u * ctx.w as f32) as i64, (v * ctx.h as f32) as i64); + let (dx, dy) = ops::slope(&grad, x, y, ctx.tile); + img.sample(u + dx * k, v + dy * k, ctx.tile) + })]) +} + +fn input_color_default(ctx: &Ctx) -> CookResult { + Ok(vec![Image::filled(ctx.w, ctx.h, Kind::Color, ctx.v4("default"))]) +} + +fn input_gray_default(ctx: &Ctx) -> CookResult { + Ok(vec![Image::filled(ctx.w, ctx.h, Kind::Gray, [ctx.v4("default")[0]; 4])]) +} + +pub(crate) fn passthrough(ctx: &Ctx) -> CookResult { + Ok(vec![ctx.sized(0).unwrap_or_else(|| Image::filled(ctx.w, ctx.h, Kind::Gray, [0.0; 4]))]) +} + +/// The kind an output port produces given the node's inputs. +pub fn output_kind(def: &NodeDef, port: usize, inputs: &[Option]) -> Kind { + match def.outputs.get(port).map(|p| p.kind) { + Some(PortKind::Gray) => Kind::Gray, + Some(PortKind::Color) => Kind::Color, + _ => inputs.iter().flatten().next().map_or(Kind::Gray, |i| i.kind), + } +} diff --git a/crates/nodes/src/catalog.rs b/crates/nodes/src/catalog.rs new file mode 100644 index 00000000..1a89592b --- /dev/null +++ b/crates/nodes/src/catalog.rs @@ -0,0 +1,356 @@ +//! Node definitions: ports, parameters and the cook function of every node in the library, +//! built once into a static registry ([`catalog`]). + +use std::collections::BTreeMap; +use std::sync::OnceLock; + +use materialcraft_core::function::FnGraph; +use materialcraft_core::{Curve, Gradient, Value}; +use materialcraft_image::{Image, Kind}; + +/// What a port carries. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PortKind { + Gray, + Color, + /// Either; outputs of this kind follow the main input. + Any, +} + +#[derive(Clone, Debug)] +pub struct PortDef { + pub id: &'static str, + pub label: &'static str, + pub kind: PortKind, +} + +/// The editor widget and range of a parameter. +#[derive(Clone, Debug)] +pub struct ParamDef { + pub id: &'static str, + pub label: &'static str, + pub default: Value, + pub min: f32, + pub max: f32, + /// Labels of an enum parameter. + pub options: &'static [&'static str], + /// Section heading in the Properties panel ("" = none). + pub group: &'static str, + /// An angle in turns (shown in degrees). + pub angle: bool, + /// The name of a package resource (bitmap / SVG). + pub resource: bool, +} + +/// Where a cook runs: output size, seed, tiling, inputs and resolved parameters. +pub struct Ctx<'a> { + pub w: u32, + pub h: u32, + pub seed: u32, + pub tile: bool, + /// By input port order; `None` = not connected. + pub inputs: &'a [Option], + pub params: &'a BTreeMap, + /// The package's bitmap resources, decoded on demand. + pub resource: &'a (dyn Fn(&str) -> Option + Sync), + /// Exposed graph inputs (for `get_*` nodes in function graphs). + pub vars: &'a BTreeMap, +} + +impl Ctx<'_> { + pub fn value(&self, id: &str) -> Option<&Value> { + self.params.get(id) + } + + pub fn f(&self, id: &str) -> f32 { + self.value(id).and_then(Value::as_f32).filter(|v| v.is_finite()).unwrap_or(0.0) + } + + pub fn i(&self, id: &str) -> i32 { + self.value(id).and_then(Value::as_i32).unwrap_or(0) + } + + pub fn b(&self, id: &str) -> bool { + self.value(id).and_then(Value::as_bool).unwrap_or(false) + } + + pub fn v4(&self, id: &str) -> [f32; 4] { + self.value(id).and_then(Value::as_vec4).unwrap_or([0.0; 4]) + } + + pub fn v2(&self, id: &str) -> [f32; 2] { + let v = self.v4(id); + [v[0], v[1]] + } + + pub fn text(&self, id: &str) -> &str { + match self.value(id) { + Some(Value::Text(s)) => s, + _ => "", + } + } + + pub fn curve(&self, id: &str) -> Curve { + match self.value(id) { + Some(Value::Curve(c)) => c.clone(), + _ => Curve::default(), + } + } + + pub fn gradient(&self, id: &str) -> Gradient { + match self.value(id) { + Some(Value::Gradient(g)) => g.clone(), + _ => Gradient::default(), + } + } + + pub fn function(&self, id: &str) -> Option<&FnGraph> { + match self.value(id) { + Some(Value::Function(g)) => Some(g.as_ref()), + _ => None, + } + } + + /// Input `i` if connected. + pub fn input(&self, i: usize) -> Option<&Image> { + self.inputs.get(i).and_then(Option::as_ref) + } + + /// Input `i` resampled to the output size (`None` if not connected). + pub fn sized(&self, i: usize) -> Option { + self.input(i).map(|img| img.resize(self.w, self.h, self.tile)) + } + + /// Input `i` at the output size as gray, or a constant gray `v` when unconnected. + pub fn gray_or(&self, i: usize, v: f32) -> Image { + self.sized(i).map(|img| img.to_gray()).unwrap_or_else(|| Image::filled(self.w, self.h, Kind::Gray, [v; 4])) + } + + /// Input `i` at the output size (kind kept), or constant `v` of `kind` when unconnected. + pub fn any_or(&self, i: usize, kind: Kind, v: [f32; 4]) -> Image { + self.sized(i).unwrap_or_else(|| Image::filled(self.w, self.h, kind, v)) + } + + /// The kind an "Any" output takes: the main input's, else `fallback`. + pub fn main_kind(&self, fallback: Kind) -> Kind { + self.inputs.iter().flatten().next().map_or(fallback, |i| i.kind) + } + + /// A gray image from `f(u, v)` at the output size. + pub fn gen_gray(&self, f: impl Fn(f32, f32) -> f32 + Sync) -> Image { + Image::generate_uv(self.w, self.h, Kind::Gray, |u, v| [f(u, v), 0.0, 0.0, 0.0]) + } + + pub fn gen_color(&self, f: impl Fn(f32, f32) -> [f32; 4] + Sync) -> Image { + Image::generate_uv(self.w, self.h, Kind::Color, f) + } +} + +pub type CookResult = Result, String>; +pub type Cook = fn(&Ctx) -> CookResult; + +/// A node in the library. +#[derive(Clone, Debug)] +pub struct NodeDef { + pub id: &'static str, + pub label: &'static str, + /// Library path, e.g. `Filters/Blurs`, `Texture generators/Noises`, `Atomic nodes`. + pub category: &'static str, + pub description: &'static str, + pub inputs: Vec, + pub outputs: Vec, + pub params: Vec, + /// A generator takes its size from the graph, not from an input. + pub generator: bool, + /// One of the engine's built-in ("atomic") nodes (shown with a grey header). + pub atomic: bool, + pub cook: Cook, +} + +impl NodeDef { + pub fn param(&self, id: &str) -> Option<&ParamDef> { + self.params.iter().find(|p| p.id == id) + } + + pub fn input_index(&self, id: &str) -> Option { + self.inputs.iter().position(|p| p.id == id) + } + + pub fn output_index(&self, id: &str) -> Option { + self.outputs.iter().position(|p| p.id == id) + } + + /// The last path element of the category ("Blurs"). + pub fn group(&self) -> &'static str { + self.category.rsplit('/').next().unwrap_or(self.category) + } +} + +pub(crate) fn no_cook(_: &Ctx) -> CookResult { + Err("this node is cooked by the graph evaluator".into()) +} + +/// Builder for [`NodeDef`]s. +pub(crate) struct B(NodeDef); + +pub(crate) fn node(id: &'static str, label: &'static str, category: &'static str) -> B { + B(NodeDef { + id, + label, + category, + description: "", + inputs: Vec::new(), + outputs: Vec::new(), + params: Vec::new(), + generator: false, + atomic: false, + cook: no_cook, + }) +} + +impl B { + pub fn desc(mut self, d: &'static str) -> B { + self.0.description = d; + self + } + pub fn atomic(mut self) -> B { + self.0.atomic = true; + self + } + pub fn generator(mut self) -> B { + self.0.generator = true; + self + } + pub fn input(mut self, id: &'static str, label: &'static str, kind: PortKind) -> B { + self.0.inputs.push(PortDef { id, label, kind }); + self + } + pub fn gray_in(self, id: &'static str, label: &'static str) -> B { + self.input(id, label, PortKind::Gray) + } + pub fn color_in(self, id: &'static str, label: &'static str) -> B { + self.input(id, label, PortKind::Color) + } + pub fn any_in(self, id: &'static str, label: &'static str) -> B { + self.input(id, label, PortKind::Any) + } + pub fn output(mut self, id: &'static str, label: &'static str, kind: PortKind) -> B { + self.0.outputs.push(PortDef { id, label, kind }); + self + } + pub fn gray_out(self) -> B { + self.output("output", "Output", PortKind::Gray) + } + pub fn color_out(self) -> B { + self.output("output", "Output", PortKind::Color) + } + pub fn any_out(self) -> B { + self.output("output", "Output", PortKind::Any) + } + fn push(mut self, id: &'static str, label: &'static str, default: Value, min: f32, max: f32) -> B { + self.0.params.push(ParamDef { id, label, default, min, max, options: &[], group: "", angle: false, resource: false }); + self + } + fn last(&mut self) -> Option<&mut ParamDef> { + self.0.params.last_mut() + } + pub fn float(self, id: &'static str, label: &'static str, d: f32, min: f32, max: f32) -> B { + self.push(id, label, Value::Float(d), min, max) + } + pub fn angle(mut self, id: &'static str, label: &'static str, d: f32) -> B { + self = self.push(id, label, Value::Float(d), -1.0, 1.0); + if let Some(p) = self.last() { + p.angle = true; + } + self + } + pub fn int(self, id: &'static str, label: &'static str, d: i32, min: i32, max: i32) -> B { + self.push(id, label, Value::Int(d), min as f32, max as f32) + } + pub fn float2(self, id: &'static str, label: &'static str, d: [f32; 2], min: f32, max: f32) -> B { + self.push(id, label, Value::Float2(d), min, max) + } + pub fn boolean(self, id: &'static str, label: &'static str, d: bool) -> B { + self.push(id, label, Value::Bool(d), 0.0, 1.0) + } + pub fn color(self, id: &'static str, label: &'static str, d: [f32; 4]) -> B { + self.push(id, label, Value::Color(d), 0.0, 1.0) + } + pub fn choice(mut self, id: &'static str, label: &'static str, options: &'static [&'static str], d: u32) -> B { + self = self.push(id, label, Value::Enum(d), 0.0, options.len().saturating_sub(1) as f32); + if let Some(p) = self.last() { + p.options = options; + } + self + } + pub fn text(self, id: &'static str, label: &'static str, d: &str) -> B { + self.push(id, label, Value::Text(d.into()), 0.0, 0.0) + } + pub fn resource(mut self, id: &'static str, label: &'static str) -> B { + self = self.push(id, label, Value::Text(String::new()), 0.0, 0.0); + if let Some(p) = self.last() { + p.resource = true; + } + self + } + pub fn curve(self, id: &'static str, label: &'static str) -> B { + self.push(id, label, Value::Curve(Curve::default()), 0.0, 1.0) + } + pub fn gradient(self, id: &'static str, label: &'static str, g: Gradient) -> B { + self.push(id, label, Value::Gradient(g), 0.0, 1.0) + } + pub fn function(self, id: &'static str, label: &'static str, g: FnGraph) -> B { + self.push(id, label, Value::Function(Box::new(g)), 0.0, 0.0) + } + pub fn cook(mut self, f: Cook) -> NodeDef { + if self.0.outputs.is_empty() { + self = self.any_out(); + } + self.0.cook = f; + self.0 + } +} + +/// Every node definition, in library order. +pub fn catalog() -> &'static [NodeDef] { + static CAT: OnceLock> = OnceLock::new(); + CAT.get_or_init(|| { + let mut v = Vec::new(); + v.extend(crate::atomic::defs()); + v.extend(crate::generators::defs()); + v.extend(crate::patterns::defs()); + v.extend(crate::filters::defs()); + v.extend(crate::material::defs()); + v + }) +} + +pub fn find(id: &str) -> Option<&'static NodeDef> { + catalog().iter().find(|d| d.id == id) +} + +/// The library's category tree, in display order: (path, ids). +pub fn categories() -> Vec<(&'static str, Vec<&'static str>)> { + let mut out: Vec<(&'static str, Vec<&'static str>)> = Vec::new(); + for d in catalog() { + match out.iter_mut().find(|(c, _)| *c == d.category) { + Some((_, ids)) => ids.push(d.id), + None => out.push((d.category, vec![d.id])), + } + } + out +} + +/// Parameter values for a node: catalog defaults overlaid with `overrides`. +pub fn resolve_params(def: &NodeDef, overrides: &BTreeMap) -> BTreeMap { + let mut m: BTreeMap = def.params.iter().map(|p| (p.id.to_string(), p.default.clone())).collect(); + for (k, v) in overrides { + // Keep only known parameters whose type matches (a hand-edited file may have anything). + if let Some(d) = m.get(k) + && d.type_name() == v.type_name() + { + m.insert(k.clone(), v.clone()); + } + } + m +} diff --git a/crates/nodes/src/filters.rs b/crates/nodes/src/filters.rs new file mode 100644 index 00000000..84200347 --- /dev/null +++ b/crates/nodes/src/filters.rs @@ -0,0 +1,951 @@ +//! Filters: adjustments, blending, blurs, channels, effects, normal map tools, tiling and +//! transforms. + +use std::f32::consts::TAU; + +use materialcraft_image::{Image, Kind, luminance}; + +use crate::atomic::{height_to_normal, levels_fn, transform_sample}; +use crate::catalog::{CookResult, Ctx, NodeDef, PortKind, node}; +use crate::ops; + +const ADJ: &str = "Filters/Adjustments"; +const BLENDING: &str = "Filters/Blending"; +const BLURS: &str = "Filters/Blurs"; +const CHANNELS: &str = "Filters/Channels"; +const EFFECTS: &str = "Filters/Effects"; +const NORMAL: &str = "Filters/Normal map"; +const TILING: &str = "Filters/Tiling"; +const TRANSFORMS: &str = "Filters/Transforms"; + +pub(crate) fn defs() -> Vec { + vec![ + // ---- Adjustments + node("auto_levels", "Auto Levels", ADJ).desc("Stretches the input to the full 0..1 range.").any_in("input", "Input").cook(auto_levels), + node("clamp", "Clamp", ADJ) + .desc("Clamps values between a minimum and a maximum.") + .any_in("input", "Input") + .float("min", "Min", 0.0, 0.0, 1.0) + .float("max", "Max", 1.0, 0.0, 1.0) + .cook(clamp), + node("color_to_mask", "Color to Mask", ADJ) + .desc("White where the input is close to a key color.") + .color_in("input", "Input") + .color("color", "Key color", [1.0, 0.0, 0.0, 1.0]) + .float("range", "Range", 0.2, 0.0, 1.0) + .float("softness", "Softness", 0.1, 0.0, 1.0) + .gray_out() + .cook(color_to_mask), + node("contrast_luminosity", "Contrast/Luminosity", ADJ) + .desc("Contrast and brightness (0 = unchanged).") + .any_in("input", "Input") + .float("contrast", "Contrast", 0.0, -1.0, 1.0) + .float("luminosity", "Luminosity", 0.0, -1.0, 1.0) + .cook(contrast_luminosity), + node("exposure", "Exposure", ADJ).desc("Exposure in stops.").any_in("input", "Input").float("stops", "Exposure (EV)", 0.0, -10.0, 10.0).cook(exposure), + node("gamma", "Gamma", ADJ).desc("Raises values to a power.").any_in("input", "Input").float("gamma", "Gamma", 1.0, 0.01, 10.0).cook(gamma), + node("histogram_range", "Histogram Range", ADJ) + .desc("Compresses values into a range around a position.") + .gray_in("input", "Input") + .float("range", "Range", 0.5, 0.0, 1.0) + .float("position", "Position", 0.5, 0.0, 1.0) + .gray_out() + .cook(histogram_range), + node("histogram_scan", "Histogram Scan", ADJ) + .desc("Thresholds the input at a position with adjustable contrast.") + .gray_in("input", "Input") + .float("position", "Position", 0.5, 0.0, 1.0) + .float("contrast", "Contrast", 0.5, 0.0, 1.0) + .boolean("invert", "Invert position", false) + .gray_out() + .cook(histogram_scan), + node("histogram_shift", "Histogram Shift", ADJ) + .desc("Shifts values with wrap-around.") + .gray_in("input", "Input") + .float("position", "Position", 0.5, 0.0, 1.0) + .gray_out() + .cook(histogram_shift), + node("invert", "Invert", ADJ).desc("1 minus the input (alpha kept).").any_in("input", "Input").boolean("alpha", "Invert alpha", false).cook(invert), + node("posterize", "Posterize", ADJ) + .desc("Quantizes values to a number of steps.") + .any_in("input", "Input") + .int("steps", "Steps", 4, 2, 256) + .cook(posterize), + node("replace_color", "Replace Color", ADJ) + .desc("Shifts colors near a source color towards a target color.") + .color_in("input", "Input") + .color("source", "Source color", [1.0, 0.0, 0.0, 1.0]) + .color("target", "Target color", [0.0, 0.0, 1.0, 1.0]) + .float("range", "Range", 0.3, 0.0, 1.0) + .color_out() + .cook(replace_color), + node("threshold", "Threshold", ADJ) + .desc("White above the threshold, black below.") + .gray_in("input", "Input") + .float("threshold", "Threshold", 0.5, 0.0, 1.0) + .gray_out() + .cook(threshold), + node("colorize", "Colorize", ADJ) + .desc("Tints a grayscale image between two colors.") + .gray_in("input", "Input") + .color("dark", "Dark color", [0.05, 0.03, 0.02, 1.0]) + .color("light", "Light color", [0.9, 0.75, 0.5, 1.0]) + .color_out() + .cook(colorize), + node("channel_mixer", "Channel Mixer", ADJ) + .desc("Each output channel as a weighted sum of the input channels.") + .color_in("input", "Input") + .float2("red_rg", "Red from R, G", [1.0, 0.0], -2.0, 2.0) + .float("red_b", "Red from B", 0.0, -2.0, 2.0) + .float2("green_rg", "Green from R, G", [0.0, 1.0], -2.0, 2.0) + .float("green_b", "Green from B", 0.0, -2.0, 2.0) + .float2("blue_rg", "Blue from R, G", [0.0, 0.0], -2.0, 2.0) + .float("blue_b", "Blue from B", 1.0, -2.0, 2.0) + .color_out() + .cook(channel_mixer), + // ---- Blending + node("height_blend", "Height Blend", BLENDING) + .desc("Blends two height maps by which is higher, with a soft contrast; also outputs the mask.") + .gray_in("top", "Height top") + .gray_in("bottom", "Height bottom") + .gray_in("mask", "Mask") + .float("offset", "Height offset", 0.5, 0.0, 1.0) + .float("contrast", "Contrast", 0.9, 0.0, 1.0) + .output("height", "Height", PortKind::Gray) + .output("blend_mask", "Blend mask", PortKind::Gray) + .cook(height_blend), + node("alpha_merge", "Alpha Merge", BLENDING) + .desc("Puts a grayscale image in a color image's alpha.") + .color_in("input", "Color") + .gray_in("alpha", "Alpha") + .color_out() + .cook(alpha_merge), + node("rgba_merge", "RGBA Merge", CHANNELS) + .desc("Builds a color image from four grayscale channels.") + .gray_in("r", "R") + .gray_in("g", "G") + .gray_in("b", "B") + .gray_in("a", "A") + .color_out() + .cook(rgba_merge), + node("rgba_split", "RGBA Split", CHANNELS) + .desc("Splits a color image into four grayscale channels.") + .color_in("input", "RGBA") + .output("r", "R", PortKind::Gray) + .output("g", "G", PortKind::Gray) + .output("b", "B", PortKind::Gray) + .output("a", "A", PortKind::Gray) + .cook(rgba_split), + node("switch", "Switch", BLENDING) + .desc("Outputs input A or input B.") + .any_in("a", "Input A") + .any_in("b", "Input B") + .boolean("use_b", "Use input B", false) + .cook(switch), + // ---- Blurs + node("anisotropic_blur", "Anisotropic Blur", BLURS) + .desc("A Gaussian blur stronger along one direction.") + .any_in("input", "Input") + .float("intensity", "Intensity", 4.0, 0.0, 32.0) + .float("anisotropy", "Anisotropy", 0.5, 0.0, 1.0) + .angle("angle", "Angle", 0.0) + .cook(anisotropic_blur), + node("non_uniform_blur", "Non Uniform Blur", BLURS) + .desc("Blurs more where the blur map is white.") + .any_in("input", "Input") + .gray_in("blur_map", "Blur map") + .float("intensity", "Intensity", 4.0, 0.0, 32.0) + .cook(non_uniform_blur), + node("radial_blur", "Radial Blur", BLURS) + .desc("Zoom blur from a center.") + .any_in("input", "Input") + .float("intensity", "Intensity", 0.2, 0.0, 1.0) + .float2("center", "Center", [0.5, 0.5], 0.0, 1.0) + .cook(radial_blur), + node("slope_blur", "Slope Blur", BLURS) + .desc("Smears the input along the slopes of a map, like flowing material.") + .any_in("input", "Input") + .gray_in("slope", "Slope") + .float("intensity", "Intensity", 8.0, -64.0, 64.0) + .int("samples", "Samples", 8, 1, 32) + .choice("mode", "Mode", &["Blur", "Min", "Max"], 0) + .cook(slope_blur), + // ---- Effects + node("ambient_occlusion", "Ambient Occlusion", EFFECTS) + .desc("Darkens creases of a height map.") + .gray_in("height", "Height") + .float("spread", "Spreading", 0.15, 0.0, 1.0) + .float("intensity", "Height depth", 0.5, 0.0, 1.0) + .gray_out() + .cook(ambient_occlusion), + node("bevel", "Bevel", EFFECTS) + .desc("Rounds the edges of a mask into a height ramp.") + .gray_in("input", "Mask") + .float("distance", "Distance", 0.05, -1.0, 1.0) + .float("smoothing", "Smoothing", 0.0, 0.0, 1.0) + .gray_out() + .cook(bevel), + node("curvature", "Curvature", EFFECTS) + .desc("Convexity (white) and concavity (black) of a normal map.") + .color_in("normal", "Normal") + .float("intensity", "Intensity", 1.0, 0.0, 10.0) + .gray_out() + .cook(curvature), + node("dilation", "Dilation", EFFECTS) + .desc("Grows bright areas (maximum filter).") + .any_in("input", "Input") + .int("radius", "Radius", 2, 0, 64) + .cook(dilation), + node("erosion", "Erosion", EFFECTS) + .desc("Shrinks bright areas (minimum filter).") + .any_in("input", "Input") + .int("radius", "Radius", 2, 0, 64) + .cook(erosion), + node("edge_detect", "Edge Detect", EFFECTS) + .desc("White along the edges of a mask.") + .gray_in("input", "Input") + .float("width", "Edge width", 2.0, 0.0, 32.0) + .float("roundness", "Edge roundness", 0.5, 0.0, 1.0) + .gray_out() + .cook(edge_detect), + node("glow", "Glow", EFFECTS) + .desc("A soft glow around bright areas.") + .any_in("input", "Input") + .float("threshold", "Threshold", 0.5, 0.0, 1.0) + .float("size", "Size", 8.0, 0.0, 64.0) + .float("amount", "Amount", 0.5, 0.0, 2.0) + .cook(glow), + node("highpass", "Highpass", EFFECTS) + .desc("Keeps the fine detail, centered on gray.") + .any_in("input", "Input") + .float("radius", "Radius", 6.0, 0.0, 64.0) + .cook(highpass), + node("mosaic", "Mosaic", EFFECTS).desc("Pixelates into blocks.").any_in("input", "Input").int("cells", "Cells", 16, 1, 512).cook(mosaic), + node("swirl", "Swirl", EFFECTS) + .desc("Twists the image around its center.") + .any_in("input", "Input") + .float("amount", "Amount", 0.5, -4.0, 4.0) + .float("radius", "Radius", 0.5, 0.0, 1.0) + .cook(swirl), + node("vignette", "Vignette", EFFECTS) + .desc("Darkens towards the borders.") + .any_in("input", "Input") + .float("amount", "Amount", 0.5, 0.0, 1.0) + .float("softness", "Softness", 0.5, 0.0, 1.0) + .cook(vignette), + node("quantize", "Quantize Grayscale", EFFECTS) + .desc("Snaps gray values to steps with soft transitions.") + .gray_in("input", "Input") + .int("steps", "Steps", 4, 2, 64) + .float("smoothness", "Smoothness", 0.1, 0.0, 1.0) + .gray_out() + .cook(quantize), + // ---- Normal map + node("height_to_normal", "Height to Normal", NORMAL) + .desc("Same as Normal: a normal map from a height map.") + .gray_in("input", "Height") + .float("intensity", "Intensity", 1.0, 0.0, 10.0) + .choice("format", "Normal format", &["OpenGL", "DirectX"], 0) + .color_out() + .cook(height_normal), + node("normal_blend", "Normal Blend", NORMAL) + .desc("Combines two normal maps (reoriented normal mapping).") + .color_in("base", "Normal base") + .color_in("detail", "Normal detail") + .gray_in("mask", "Mask") + .float("opacity", "Opacity", 1.0, 0.0, 1.0) + .color_out() + .cook(normal_blend), + node("normal_invert", "Normal Invert", NORMAL) + .desc("Flips the green (and optionally red) channel: OpenGL ↔ DirectX.") + .color_in("input", "Normal") + .boolean("red", "Invert red", false) + .boolean("green", "Invert green", true) + .color_out() + .cook(normal_invert), + node("normal_normalize", "Normal Normalize", NORMAL) + .desc("Rescales normals to unit length.") + .color_in("input", "Normal") + .color_out() + .cook(normal_normalize), + node("normal_intensity", "Normal Intensity", NORMAL) + .desc("Strengthens or flattens a normal map.") + .color_in("input", "Normal") + .float("intensity", "Intensity", 1.0, 0.0, 10.0) + .color_out() + .cook(normal_intensity), + node("normal_to_height", "Normal to Height", NORMAL) + .desc("Reconstructs a height map from a normal map.") + .color_in("input", "Normal") + .float("intensity", "Height scale", 1.0, 0.0, 10.0) + .gray_out() + .cook(normal_to_height), + // ---- Tiling + node("make_it_tile", "Make It Tile", TILING) + .desc("Cross-fades the borders so a photo tiles.") + .any_in("input", "Input") + .float("blend", "Blend width", 0.25, 0.0, 0.5) + .cook(make_it_tile), + node("safe_transform", "Safe Transform", TILING) + .desc("Tiling-safe transform: whole-number tiling, offsets and 90° rotations.") + .any_in("input", "Input") + .int("tile", "Tile", 1, 1, 64) + .float2("offset", "Offset", [0.0, 0.0], -1.0, 1.0) + .choice("rotation", "Rotation", &["0°", "90°", "180°", "270°"], 0) + .boolean("flip", "Flip", false) + .cook(safe_transform), + // ---- Transforms + node("mirror", "Mirror", TRANSFORMS) + .desc("Mirrors one half of the image onto the other.") + .any_in("input", "Input") + .choice("axis", "Mirror type", &["Horizontal", "Vertical", "Corner"], 0) + .boolean("flip", "Flip side", false) + .cook(mirror), + node("kaleidoscope", "Kaleidoscope", TRANSFORMS) + .desc("Repeats a wedge of the image around the center.") + .any_in("input", "Input") + .int("segments", "Segments", 6, 2, 64) + .angle("angle", "Angle", 0.0) + .cook(kaleidoscope), + node("cartesian_to_polar", "Cartesian to Polar", TRANSFORMS) + .desc("Wraps the image around the center.") + .any_in("input", "Input") + .cook(cartesian_to_polar), + node("polar_to_cartesian", "Polar to Cartesian", TRANSFORMS) + .desc("Unwraps a circular image into bands.") + .any_in("input", "Input") + .cook(polar_to_cartesian), + node("skew", "Skew", TRANSFORMS) + .desc("Shears the image.") + .any_in("input", "Input") + .float("amount", "Amount", 0.25, -2.0, 2.0) + .boolean("vertical", "Vertical", false) + .cook(skew), + ] +} + +fn src(ctx: &Ctx) -> Image { + ctx.any_or(0, Kind::Gray, [0.0, 0.0, 0.0, 1.0]) +} + +fn per_value(ctx: &Ctx, f: impl Fn(f32) -> f32 + Sync) -> CookResult { + let img = src(ctx); + Ok(vec![img.map(img.kind, |p| [f(p[0]), f(p[1]), f(p[2]), p[3]])]) +} + +fn auto_levels(ctx: &Ctx) -> CookResult { + let img = src(ctx); + let (lo, hi) = img.range(); + let span = (hi - lo).max(1e-6); + per_value(ctx, |v| (v - lo) / span) +} + +fn clamp(ctx: &Ctx) -> CookResult { + let (a, b) = (ctx.f("min"), ctx.f("max")); + per_value(ctx, |v| v.max(a).min(b.max(a))) +} + +fn color_to_mask(ctx: &Ctx) -> CookResult { + let img = src(ctx).to_color(); + let (k, r, s) = (ctx.v4("color"), ctx.f("range"), ctx.f("softness").max(1e-4)); + Ok(vec![img.map(Kind::Gray, |p| { + let d = ((p[0] - k[0]).powi(2) + (p[1] - k[1]).powi(2) + (p[2] - k[2]).powi(2)).sqrt(); + [(1.0 - (d - r) / s).clamp(0.0, 1.0), 0.0, 0.0, 0.0] + })]) +} + +fn contrast_luminosity(ctx: &Ctx) -> CookResult { + let (c, l) = (ctx.f("contrast"), ctx.f("luminosity")); + let k = if c >= 0.0 { 1.0 / (1.0 - c * 0.99) } else { 1.0 + c }; + per_value(ctx, |v| ((v - 0.5) * k + 0.5 + l).clamp(0.0, 1.0)) +} + +fn exposure(ctx: &Ctx) -> CookResult { + let k = 2f32.powf(ctx.f("stops")); + per_value(ctx, |v| v * k) +} + +fn gamma(ctx: &Ctx) -> CookResult { + let g = ctx.f("gamma").max(0.01); + per_value(ctx, |v| v.max(0.0).powf(1.0 / g)) +} + +fn histogram_range(ctx: &Ctx) -> CookResult { + let (r, p) = (ctx.f("range"), ctx.f("position")); + let img = ctx.gray_or(0, 0.0); + Ok(vec![img.map(Kind::Gray, |c| [(p + (c[0] - 0.5) * r).clamp(0.0, 1.0), 0.0, 0.0, 0.0])]) +} + +/// The Histogram Scan mapping. +pub fn histogram_scan_fn(v: f32, position: f32, contrast: f32) -> f32 { + let width = (1.0 - contrast).max(0.001); + let lo = position * (1.0 + width) - width; + levels_fn(v, lo, 0.5, lo + width, 0.0, 1.0) +} + +fn histogram_scan(ctx: &Ctx) -> CookResult { + let p = if ctx.b("invert") { 1.0 - ctx.f("position") } else { ctx.f("position") }; + let c = ctx.f("contrast"); + let img = ctx.gray_or(0, 0.0); + Ok(vec![img.map(Kind::Gray, |v| [histogram_scan_fn(v[0], 1.0 - p, c), 0.0, 0.0, 0.0])]) +} + +fn histogram_shift(ctx: &Ctx) -> CookResult { + let p = ctx.f("position"); + let img = ctx.gray_or(0, 0.0); + Ok(vec![img.map(Kind::Gray, |v| [(v[0] + p).rem_euclid(1.0), 0.0, 0.0, 0.0])]) +} + +fn invert(ctx: &Ctx) -> CookResult { + let img = src(ctx); + let a = ctx.b("alpha"); + Ok(vec![img.map(img.kind, |p| [1.0 - p[0], 1.0 - p[1], 1.0 - p[2], if a { 1.0 - p[3] } else { p[3] }])]) +} + +fn posterize(ctx: &Ctx) -> CookResult { + let n = (ctx.i("steps").max(2) - 1) as f32; + per_value(ctx, |v| (v * n).round() / n) +} + +fn replace_color(ctx: &Ctx) -> CookResult { + let img = src(ctx).to_color(); + let (s, t, r) = (ctx.v4("source"), ctx.v4("target"), ctx.f("range").max(1e-4)); + Ok(vec![img.map(Kind::Color, |p| { + let d = ((p[0] - s[0]).powi(2) + (p[1] - s[1]).powi(2) + (p[2] - s[2]).powi(2)).sqrt(); + let w = (1.0 - d / r).clamp(0.0, 1.0); + [p[0] + (t[0] - s[0]) * w, p[1] + (t[1] - s[1]) * w, p[2] + (t[2] - s[2]) * w, p[3]] + })]) +} + +fn threshold(ctx: &Ctx) -> CookResult { + let t = ctx.f("threshold"); + let img = ctx.gray_or(0, 0.0); + Ok(vec![img.map(Kind::Gray, |v| [if v[0] >= t { 1.0 } else { 0.0 }, 0.0, 0.0, 0.0])]) +} + +fn colorize(ctx: &Ctx) -> CookResult { + let (a, b) = (ctx.v4("dark"), ctx.v4("light")); + let img = ctx.gray_or(0, 0.0); + Ok(vec![img.map(Kind::Color, |v| { + let t = v[0]; + [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t, 1.0] + })]) +} + +fn channel_mixer(ctx: &Ctx) -> CookResult { + let img = src(ctx).to_color(); + let (r, g, b) = (ctx.v2("red_rg"), ctx.v2("green_rg"), ctx.v2("blue_rg")); + let (rb, gb, bb) = (ctx.f("red_b"), ctx.f("green_b"), ctx.f("blue_b")); + Ok(vec![ + img.map(Kind::Color, |p| [r[0] * p[0] + r[1] * p[1] + rb * p[2], g[0] * p[0] + g[1] * p[1] + gb * p[2], b[0] * p[0] + b[1] * p[1] + bb * p[2], p[3]]), + ]) +} + +fn height_blend(ctx: &Ctx) -> CookResult { + let (top, bot) = (ctx.gray_or(0, 0.0), ctx.gray_or(1, 0.0)); + let mask = ctx.sized(2).map(|m| m.to_gray()); + let (off, c) = (ctx.f("offset") - 0.5, ctx.f("contrast").clamp(0.0, 0.999)); + let soft = (1.0 - c) * 0.5 + 1e-4; + let n = (ctx.w * ctx.h) as usize; + let mut h = vec![0.0; n]; + let mut m = vec![0.0; n]; + for i in 0..n { + let (t, b) = (top.data[i] + off, bot.data[i]); + let mut k = ((t - b) / soft * 0.5 + 0.5).clamp(0.0, 1.0); + if let Some(mm) = &mask { + k *= mm.data[i]; + } + h[i] = b + (t - b) * k; + m[i] = k; + } + Ok(vec![ops::gray_from(ctx.w, ctx.h, h), ops::gray_from(ctx.w, ctx.h, m)]) +} + +fn alpha_merge(ctx: &Ctx) -> CookResult { + let c = ctx.any_or(0, Kind::Color, [0.0, 0.0, 0.0, 1.0]).to_color(); + let a = ctx.gray_or(1, 1.0); + Ok(vec![Image::generate(ctx.w, ctx.h, Kind::Color, |x, y| { + let p = c.get(x as i64, y as i64, false); + [p[0], p[1], p[2], a.get_gray(x as i64, y as i64, false)] + })]) +} + +fn rgba_merge(ctx: &Ctx) -> CookResult { + let ch: Vec = (0..4).map(|i| ctx.gray_or(i, if i == 3 { 1.0 } else { 0.0 })).collect(); + Ok(vec![Image::generate(ctx.w, ctx.h, Kind::Color, |x, y| { + let i = (y * ctx.w + x) as usize; + [ch[0].data[i], ch[1].data[i], ch[2].data[i], ch[3].data[i]] + })]) +} + +fn rgba_split(ctx: &Ctx) -> CookResult { + let img = ctx.any_or(0, Kind::Color, [0.0, 0.0, 0.0, 1.0]).to_color(); + Ok((0..4).map(|k| img.map(Kind::Gray, |p| [p[k], 0.0, 0.0, 0.0])).collect()) +} + +fn switch(ctx: &Ctx) -> CookResult { + let i = usize::from(ctx.b("use_b")); + Ok(vec![ctx.sized(i).unwrap_or_else(|| Image::filled(ctx.w, ctx.h, Kind::Gray, [0.0; 4]))]) +} + +fn anisotropic_blur(ctx: &Ctx) -> CookResult { + let img = src(ctx); + let s = ctx.f("intensity") * ctx.w as f32 / 512.0; + let an = ctx.f("anisotropy"); + let a = ctx.f("angle") * TAU; + // Blur in a rotated frame: rotate, blur x/y separately, rotate back. + let (sx, sy) = (s, s * (1.0 - an)); + if a.abs() < 1e-4 { + return Ok(vec![blur_xy(&img, sx, sy, ctx.tile)]); + } + let rotated = + Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| transform_sample(&img, u, v, [0.0, 0.0], [1.0, 1.0], a / TAU, false, true).unwrap_or([0.0; 4])); + let b = blur_xy(&rotated, sx, sy, true); + Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| transform_sample(&b, u, v, [0.0, 0.0], [1.0, 1.0], -a / TAU, false, true).unwrap_or([0.0; 4]))]) +} + +fn blur_xy(img: &Image, sx: f32, sy: f32, tile: bool) -> Image { + // Separable: a horizontal-only Gaussian is a 2D one on an image stretched vertically, so + // blur fully with the smaller sigma and add the extra along x by repeated small passes. + let base = ops::gaussian(img, sy, tile); + let extra = (sx * sx - sy * sy).max(0.0).sqrt(); + if extra < 0.1 { + return base; + } + let n = (extra / 2.0).ceil().max(1.0) as i64; + let step = extra / (n as f32).sqrt(); + let mut out = base; + for _ in 0..n { + let src = out.clone(); + let r = (step * 2.0).ceil() as i64; + let k: Vec = (-r..=r).map(|i| (-(i * i) as f32 / (2.0 * step * step)).exp()).collect(); + let sum: f32 = k.iter().sum(); + out = Image::generate(src.w, src.h, src.kind, |x, y| { + let mut acc = [0.0; 4]; + for (j, kv) in k.iter().enumerate() { + let p = src.get(x as i64 + j as i64 - r, y as i64, tile); + for c in 0..4 { + acc[c] += p[c] * kv / sum; + } + } + acc + }); + } + out +} + +fn non_uniform_blur(ctx: &Ctx) -> CookResult { + let img = src(ctx); + let map = ctx.gray_or(1, 1.0); + let s = ctx.f("intensity") * ctx.w as f32 / 512.0; + // Four blur levels, blended by the map. + let levels: Vec = (0..4).map(|i| ops::gaussian(&img, s * i as f32 / 3.0, ctx.tile)).collect(); + Ok(vec![Image::generate(ctx.w, ctx.h, img.kind, |x, y| { + let t = map.get_gray(x as i64, y as i64, false).clamp(0.0, 1.0) * 3.0; + let i = (t.floor() as usize).min(2); + let f = t - i as f32; + let (a, b) = (levels[i].get(x as i64, y as i64, false), levels[i + 1].get(x as i64, y as i64, false)); + [a[0] + (b[0] - a[0]) * f, a[1] + (b[1] - a[1]) * f, a[2] + (b[2] - a[2]) * f, a[3] + (b[3] - a[3]) * f] + })]) +} + +fn radial_blur(ctx: &Ctx) -> CookResult { + let img = src(ctx); + let (k, c) = (ctx.f("intensity"), ctx.v2("center")); + let n = 24; + Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| { + let mut acc = [0.0; 4]; + for i in 0..n { + let t = 1.0 - k * i as f32 / n as f32; + let p = img.sample(c[0] + (u - c[0]) * t, c[1] + (v - c[1]) * t, ctx.tile); + for j in 0..4 { + acc[j] += p[j] / n as f32; + } + } + acc + })]) +} + +fn slope_blur(ctx: &Ctx) -> CookResult { + let img = src(ctx); + let slope = ops::gaussian(&ctx.gray_or(1, 0.5), 1.0, ctx.tile); + let k = ctx.f("intensity") / 256.0; + let n = ctx.i("samples").clamp(1, 64); + let mode = ctx.i("mode"); + Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| { + let (mut pu, mut pv) = (u, v); + let mut acc = img.sample(u, v, ctx.tile); + let mut cnt = 1.0; + for _ in 0..n { + let (x, y) = ((pu * ctx.w as f32) as i64, (pv * ctx.h as f32) as i64); + let (dx, dy) = ops::slope(&slope, x, y, ctx.tile); + let l = (dx * dx + dy * dy).sqrt().max(1e-6); + pu -= dx / l * k / n as f32 * 4.0; + pv -= dy / l * k / n as f32 * 4.0; + let p = img.sample(pu, pv, ctx.tile); + for j in 0..4 { + acc[j] = match mode { + 1 => acc[j].min(p[j]), + 2 => acc[j].max(p[j]), + _ => acc[j] + p[j], + }; + } + cnt += 1.0; + } + if mode == 0 { acc.map(|a| a / cnt) } else { acc } + })]) +} + +fn ambient_occlusion(ctx: &Ctx) -> CookResult { + let h = ctx.gray_or(0, 0.0); + let spread = ctx.f("spread").max(0.001) * ctx.w as f32 * 0.25; + let depth = ctx.f("intensity"); + let wide = ops::gaussian(&h, spread, ctx.tile); + let mid = ops::gaussian(&h, spread * 0.35, ctx.tile); + Ok(vec![Image::generate(ctx.w, ctx.h, Kind::Gray, |x, y| { + let i = (y * ctx.w + x) as usize; + let occ = ((wide.data[i] - h.data[i]).max(0.0) * 0.6 + (mid.data[i] - h.data[i]).max(0.0) * 0.4) * depth * 6.0; + [(1.0 - occ).clamp(0.0, 1.0), 0.0, 0.0, 0.0] + })]) +} + +fn bevel(ctx: &Ctx) -> CookResult { + let m = ctx.gray_or(0, 0.0); + let d = ctx.f("distance"); + let dist_px = (d.abs() * ctx.w as f32).max(1e-3); + let data = m.data.clone(); + let outside = ops::distance_sq(ctx.w, ctx.h, |i| data[i] > 0.5, ctx.tile); + let inside = ops::distance_sq(ctx.w, ctx.h, |i| data[i] <= 0.5, ctx.tile); + let v: Vec = (0..outside.len()) + .map(|i| { + if d >= 0.0 { + // Inner bevel: ramp up from the edge inward. + if data[i] > 0.5 { (inside[i].sqrt() / dist_px).min(1.0) } else { 0.0 } + } else if data[i] > 0.5 { + 1.0 + } else { + (1.0 - outside[i].sqrt() / dist_px).max(0.0) + } + }) + .collect(); + let img = ops::gray_from(ctx.w, ctx.h, v); + let s = ctx.f("smoothing") * ctx.w as f32 / 128.0; + Ok(vec![ops::gaussian(&img.map(Kind::Gray, |p| [(p[0] * std::f32::consts::FRAC_PI_2).sin(), 0.0, 0.0, 0.0]), s, ctx.tile)]) +} + +fn curvature(ctx: &Ctx) -> CookResult { + let n = ctx.any_or(0, Kind::Color, [0.5, 0.5, 1.0, 1.0]).to_color(); + let k = ctx.f("intensity") * 2.0; + Ok(vec![Image::generate(ctx.w, ctx.h, Kind::Gray, |x, y| { + let (x, y) = (x as i64, y as i64); + let dx = n.get(x + 1, y, ctx.tile)[0] - n.get(x - 1, y, ctx.tile)[0]; + let dy = n.get(x, y + 1, ctx.tile)[1] - n.get(x, y - 1, ctx.tile)[1]; + [(0.5 + (dx - dy) * k).clamp(0.0, 1.0), 0.0, 0.0, 0.0] + })]) +} + +fn morph(ctx: &Ctx, max: bool) -> CookResult { + let img = src(ctx); + let r = ctx.i("radius").clamp(0, 64) as i64; + if r == 0 { + return Ok(vec![img]); + } + // Separable square window: rows then columns. + let pass = |src: &Image, horizontal: bool| { + Image::generate(src.w, src.h, src.kind, |x, y| { + let mut acc = src.get(x as i64, y as i64, ctx.tile); + for o in -r..=r { + let p = if horizontal { src.get(x as i64 + o, y as i64, ctx.tile) } else { src.get(x as i64, y as i64 + o, ctx.tile) }; + for k in 0..4 { + acc[k] = if max { acc[k].max(p[k]) } else { acc[k].min(p[k]) }; + } + } + acc + }) + }; + Ok(vec![pass(&pass(&img, true), false)]) +} + +fn dilation(ctx: &Ctx) -> CookResult { + morph(ctx, true) +} + +fn erosion(ctx: &Ctx) -> CookResult { + morph(ctx, false) +} + +fn edge_detect(ctx: &Ctx) -> CookResult { + let m = ctx.gray_or(0, 0.0); + let w = (ctx.f("width") * ctx.w as f32 / 256.0).max(0.5); + let data = m.data.clone(); + let a = ops::distance_sq(ctx.w, ctx.h, |i| data[i] > 0.5, ctx.tile); + let b = ops::distance_sq(ctx.w, ctx.h, |i| data[i] <= 0.5, ctx.tile); + let round = ctx.f("roundness"); + let v: Vec = a + .iter() + .zip(&b) + .map(|(a, b)| { + let d = a.sqrt().max(b.sqrt()); + let t = (1.0 - d / w).max(0.0); + t.powf(1.0 - round * 0.8) + }) + .collect(); + Ok(vec![ops::gray_from(ctx.w, ctx.h, v)]) +} + +fn glow(ctx: &Ctx) -> CookResult { + let img = src(ctx); + let (t, amt) = (ctx.f("threshold"), ctx.f("amount")); + let bright = img.map(img.kind, |p| { + let l = luminance(p); + let k = if l > t { 1.0 } else { 0.0 }; + [p[0] * k, p[1] * k, p[2] * k, p[3]] + }); + let b = ops::gaussian(&bright, ctx.f("size") * ctx.w as f32 / 256.0, ctx.tile); + Ok(vec![Image::generate(ctx.w, ctx.h, img.kind, |x, y| { + let (p, g) = (img.get(x as i64, y as i64, false), b.get(x as i64, y as i64, false)); + [p[0] + g[0] * amt, p[1] + g[1] * amt, p[2] + g[2] * amt, p[3]] + })]) +} + +fn highpass(ctx: &Ctx) -> CookResult { + let img = src(ctx); + let b = ops::gaussian(&img, ctx.f("radius") * ctx.w as f32 / 256.0, ctx.tile); + Ok(vec![Image::generate(ctx.w, ctx.h, img.kind, |x, y| { + let (p, q) = (img.get(x as i64, y as i64, false), b.get(x as i64, y as i64, false)); + [p[0] - q[0] + 0.5, p[1] - q[1] + 0.5, p[2] - q[2] + 0.5, p[3]] + })]) +} + +fn mosaic(ctx: &Ctx) -> CookResult { + let img = src(ctx); + let n = ctx.i("cells").max(1) as f32; + Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| img.sample(((u * n).floor() + 0.5) / n, ((v * n).floor() + 0.5) / n, ctx.tile))]) +} + +fn swirl(ctx: &Ctx) -> CookResult { + let img = src(ctx); + let (amt, rad) = (ctx.f("amount") * TAU, ctx.f("radius").max(1e-3)); + Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| { + let (x, y) = (u - 0.5, v - 0.5); + let r = (x * x + y * y).sqrt(); + let t = (1.0 - r / rad).max(0.0); + let a = amt * t * t; + let (s, c) = a.sin_cos(); + img.sample(x * c - y * s + 0.5, x * s + y * c + 0.5, ctx.tile) + })]) +} + +fn vignette(ctx: &Ctx) -> CookResult { + let img = src(ctx); + let (amt, soft) = (ctx.f("amount"), ctx.f("softness").max(0.01)); + Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| { + let p = img.sample_nearest(u, v, false); + let r = ((u - 0.5).powi(2) + (v - 0.5).powi(2)).sqrt() * std::f32::consts::SQRT_2; + let k = 1.0 - amt * ((r - (1.0 - soft)) / soft).clamp(0.0, 1.0); + [p[0] * k, p[1] * k, p[2] * k, p[3]] + })]) +} + +fn quantize(ctx: &Ctx) -> CookResult { + let n = (ctx.i("steps").max(2) - 1) as f32; + let s = ctx.f("smoothness").clamp(0.0, 1.0) * 0.5; + let img = ctx.gray_or(0, 0.0); + Ok(vec![img.map(Kind::Gray, |p| { + let x = p[0] * n; + let f = x.fract(); + let t = if s > 0.0 { ((f - 0.5 + s) / (2.0 * s)).clamp(0.0, 1.0) } else { (f >= 0.5) as i32 as f32 }; + [(x.floor() + t * t * (3.0 - 2.0 * t)) / n, 0.0, 0.0, 0.0] + })]) +} + +fn height_normal(ctx: &Ctx) -> CookResult { + let h = ctx.gray_or(0, 0.0); + Ok(vec![height_to_normal(&h, ctx.f("intensity") * ctx.w as f32 / 32.0, ctx.i("format") == 1, ctx.tile, false)]) +} + +fn unpack(p: [f32; 4]) -> [f32; 3] { + [p[0] * 2.0 - 1.0, p[1] * 2.0 - 1.0, p[2] * 2.0 - 1.0] +} + +fn pack(n: [f32; 3], a: f32) -> [f32; 4] { + let l = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt().max(1e-6); + [n[0] / l * 0.5 + 0.5, n[1] / l * 0.5 + 0.5, n[2] / l * 0.5 + 0.5, a] +} + +fn flat_normal(ctx: &Ctx, i: usize) -> Image { + ctx.any_or(i, Kind::Color, [0.5, 0.5, 1.0, 1.0]).to_color() +} + +fn normal_blend(ctx: &Ctx) -> CookResult { + let (base, det) = (flat_normal(ctx, 0), flat_normal(ctx, 1)); + let mask = ctx.sized(2).map(|m| m.to_gray()); + let op = ctx.f("opacity"); + Ok(vec![Image::generate(ctx.w, ctx.h, Kind::Color, |x, y| { + let (x, y) = (x as i64, y as i64); + let k = op * mask.as_ref().map_or(1.0, |m| m.get_gray(x, y, false)); + let b = unpack(base.get(x, y, false)); + let mut d = unpack(det.get(x, y, false)); + d = [d[0] * k, d[1] * k, 1.0 + (d[2] - 1.0) * k]; + // Reoriented normal mapping (Barré-Brisebois & Hill). + let t = [b[0], b[1], b[2] + 1.0]; + let u = [-d[0], -d[1], d[2]]; + let dot = t[0] * u[0] + t[1] * u[1] + t[2] * u[2]; + let r = [t[0] * dot / t[2] - u[0], t[1] * dot / t[2] - u[1], t[2] * dot / t[2] - u[2]]; + pack(r, 1.0) + })]) +} + +fn normal_invert(ctx: &Ctx) -> CookResult { + let n = flat_normal(ctx, 0); + let (r, g) = (ctx.b("red"), ctx.b("green")); + Ok(vec![n.map(Kind::Color, |p| [if r { 1.0 - p[0] } else { p[0] }, if g { 1.0 - p[1] } else { p[1] }, p[2], p[3]])]) +} + +fn normal_normalize(ctx: &Ctx) -> CookResult { + let n = flat_normal(ctx, 0); + Ok(vec![n.map(Kind::Color, |p| pack(unpack(p), p[3]))]) +} + +fn normal_intensity(ctx: &Ctx) -> CookResult { + let n = flat_normal(ctx, 0); + let k = ctx.f("intensity"); + Ok(vec![n.map(Kind::Color, |p| { + let v = unpack(p); + pack([v[0] * k, v[1] * k, v[2].max(1e-3)], p[3]) + })]) +} + +fn normal_to_height(ctx: &Ctx) -> CookResult { + // Integrate the slopes at several scales (a multigrid-style Poisson solve: coarse levels set + // the broad shape, finer ones the detail). + let n = flat_normal(ctx, 0); + let (w, h) = (ctx.w, ctx.h); + let gx = n.map(Kind::Gray, |p| { + let v = unpack(p); + [-v[0] / v[2].max(0.1), 0.0, 0.0, 0.0] + }); + let gy = n.map(Kind::Gray, |p| { + let v = unpack(p); + [v[1] / v[2].max(0.1), 0.0, 0.0, 0.0] + }); + let mut height = Image::filled(8.min(w), 8.min(h), Kind::Gray, [0.0; 4]); + let mut size = 8u32; + loop { + let (sw, sh) = (size.min(w), size.min(h)); + let (gxs, gys) = (gx.resize(sw, sh, true), gy.resize(sw, sh, true)); + let scale = w as f32 / sw as f32; + let mut cur = height.resize(sw, sh, true); + for _ in 0..40 { + let prev = cur.clone(); + cur = Image::generate(sw, sh, Kind::Gray, |x, y| { + let (x, y) = (x as i64, y as i64); + let nb = prev.get(x - 1, y, true)[0] + prev.get(x + 1, y, true)[0] + prev.get(x, y - 1, true)[0] + prev.get(x, y + 1, true)[0]; + // Divergence of the gradient field (pixels of this level). + let div = (gxs.get(x + 1, y, true)[0] - gxs.get(x - 1, y, true)[0] + gys.get(x, y + 1, true)[0] - gys.get(x, y - 1, true)[0]) * 0.5 / scale; + [(nb - div) * 0.25, 0.0, 0.0, 0.0] + }); + } + height = cur; + if sw >= w && sh >= h { + break; + } + size *= 2; + } + let (lo, hi) = height.range(); + let k = ctx.f("intensity"); + let span = (hi - lo).max(1e-6); + Ok(vec![height.map(Kind::Gray, |p| [(((p[0] - lo) / span - 0.5) * k + 0.5).clamp(0.0, 1.0), 0.0, 0.0, 0.0])]) +} + +fn make_it_tile(ctx: &Ctx) -> CookResult { + let img = src(ctx); + let b = ctx.f("blend").clamp(0.01, 0.5); + // Blend the image with a half-offset copy near the borders. + Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| { + let p = img.sample(u, v, true); + let q = img.sample(u + 0.5, v + 0.5, true); + let edge = (u.min(1.0 - u)).min(v.min(1.0 - v)); + let t = (edge / b).clamp(0.0, 1.0); + let t = t * t * (3.0 - 2.0 * t); + [q[0] + (p[0] - q[0]) * t, q[1] + (p[1] - q[1]) * t, q[2] + (p[2] - q[2]) * t, q[3] + (p[3] - q[3]) * t] + })]) +} + +fn safe_transform(ctx: &Ctx) -> CookResult { + let img = src(ctx); + let n = ctx.i("tile").max(1) as f32; + let off = ctx.v2("offset"); + let (rot, flip) = (ctx.i("rotation"), ctx.b("flip")); + Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| { + let (mut x, mut y) = ((u * n - off[0]).rem_euclid(1.0), (v * n - off[1]).rem_euclid(1.0)); + for _ in 0..rot.rem_euclid(4) { + (x, y) = (y, 1.0 - x); + } + if flip { + x = 1.0 - x; + } + img.sample(x, y, true) + })]) +} + +fn mirror(ctx: &Ctx) -> CookResult { + let img = src(ctx); + let (axis, flip) = (ctx.i("axis"), ctx.b("flip")); + let m = |t: f32| { + if flip { + if t < 0.5 { 1.0 - t } else { t } + } else if t > 0.5 { + 1.0 - t + } else { + t + } + }; + Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| match axis { + 1 => img.sample(u, m(v), ctx.tile), + 2 => img.sample(m(u), m(v), ctx.tile), + _ => img.sample(m(u), v, ctx.tile), + })]) +} + +fn kaleidoscope(ctx: &Ctx) -> CookResult { + let img = src(ctx); + let seg = TAU / ctx.i("segments").clamp(2, 64) as f32; + let a0 = ctx.f("angle") * TAU; + Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| { + let (x, y) = (u - 0.5, v - 0.5); + let r = (x * x + y * y).sqrt(); + let mut a = (y.atan2(x) - a0).rem_euclid(seg); + if a > seg * 0.5 { + a = seg - a; + } + let a = a + a0; + img.sample(0.5 + r * a.cos(), 0.5 + r * a.sin(), ctx.tile) + })]) +} + +fn cartesian_to_polar(ctx: &Ctx) -> CookResult { + let img = src(ctx); + Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| { + let (x, y) = (u - 0.5, v - 0.5); + let r = (x * x + y * y).sqrt() * 2.0; + let a = (y.atan2(x) / TAU).rem_euclid(1.0); + img.sample(a, r, true) + })]) +} + +fn polar_to_cartesian(ctx: &Ctx) -> CookResult { + let img = src(ctx); + Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| { + let (a, r) = (u * TAU, v * 0.5); + img.sample(0.5 + r * a.cos(), 0.5 + r * a.sin(), ctx.tile) + })]) +} + +fn skew(ctx: &Ctx) -> CookResult { + let img = src(ctx); + let (k, vert) = (ctx.f("amount"), ctx.b("vertical")); + Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| { + if vert { img.sample(u, v + (u - 0.5) * k, ctx.tile) } else { img.sample(u + (v - 0.5) * k, v, ctx.tile) } + })]) +} diff --git a/crates/nodes/src/function.rs b/crates/nodes/src/function.rs new file mode 100644 index 00000000..55888c15 --- /dev/null +++ b/crates/nodes/src/function.rs @@ -0,0 +1,395 @@ +//! Function graph evaluation: a [`FnGraph`] is compiled once into a flat instruction list +//! (dependency order from the output node), then run per pixel with a small register file. All +//! values are 4-wide; scalars are broadcast to every lane, so component-wise ops need no type +//! checks. The pixel processor samples its inputs at any position; the value processor runs once. + +use std::collections::BTreeMap; + +use materialcraft_core::Value; +use materialcraft_core::function::FnGraph; +use materialcraft_image::{Image, Kind}; + +use crate::catalog::{CookResult, Ctx}; +use crate::noise; + +/// Function node operations: (id, label, input count, library category). +pub const FN_OPS: &[(&str, &str, usize, &str)] = &[ + ("const_float", "Float", 0, "Constant"), + ("const_float2", "Float2", 0, "Constant"), + ("const_float3", "Float3", 0, "Constant"), + ("const_float4", "Float4", 0, "Constant"), + ("const_int", "Integer", 0, "Constant"), + ("const_bool", "Boolean", 0, "Constant"), + ("get_pos", "$pos", 0, "Variables"), + ("get_size", "$size", 0, "Variables"), + ("get_var", "Get variable", 0, "Variables"), + ("sample_gray", "Sample Gray", 1, "Samplers"), + ("sample_color", "Sample Color", 1, "Samplers"), + ("vec2", "Vector Float2", 2, "Vector"), + ("vec3", "Vector Float3", 3, "Vector"), + ("vec4", "Vector Float4", 4, "Vector"), + ("swizzle", "Swizzle", 1, "Vector"), + ("to_int", "To Integer", 1, "Cast"), + ("to_float", "To Float", 1, "Cast"), + ("add", "Add", 2, "Operator"), + ("sub", "Subtraction", 2, "Operator"), + ("mul", "Multiplication", 2, "Operator"), + ("div", "Division", 2, "Operator"), + ("mod", "Modulo", 2, "Operator"), + ("neg", "Negation", 1, "Operator"), + ("dot", "Dot Product", 2, "Operator"), + ("and", "And", 2, "Logical"), + ("or", "Or", 2, "Logical"), + ("not", "Not", 1, "Logical"), + ("gt", "Greater", 2, "Comparison"), + ("ge", "Greater or equal", 2, "Comparison"), + ("lt", "Lower", 2, "Comparison"), + ("le", "Lower or equal", 2, "Comparison"), + ("eq", "Equal", 2, "Comparison"), + ("ne", "Not equal", 2, "Comparison"), + ("abs", "Absolute", 1, "Function"), + ("floor", "Floor", 1, "Function"), + ("ceil", "Ceil", 1, "Function"), + ("frac", "Fractional part", 1, "Function"), + ("sqrt", "Square root", 1, "Function"), + ("exp", "Exponential", 1, "Function"), + ("log", "Logarithm", 1, "Function"), + ("sin", "Sine", 1, "Function"), + ("cos", "Cosine", 1, "Function"), + ("tan", "Tangent", 1, "Function"), + ("atan2", "Arc tangent 2", 2, "Function"), + ("pow", "Power", 2, "Function"), + ("min", "Minimum", 2, "Function"), + ("max", "Maximum", 2, "Function"), + ("clamp", "Clamp", 3, "Function"), + ("lerp", "Linear interpolation", 3, "Function"), + ("length", "Length", 1, "Function"), + ("normalize", "Normalize", 1, "Function"), + ("rand", "Random", 1, "Function"), + ("noise", "Perlin noise", 1, "Function"), + ("if_else", "If...Else", 3, "Control"), +]; + +#[derive(Clone, Debug)] +enum Op { + Const([f32; 4]), + Pos, + Size, + Sample { input: usize, gray: bool }, + Unary(fn(f32) -> f32), + Binary(fn(f32, f32) -> f32), + Ternary(fn(f32, f32, f32) -> f32), + Dot, + Length, + Normalize, + Vec(usize), + Swizzle([usize; 4]), + Rand, + Noise, + IfElse, +} + +#[derive(Clone, Debug)] +struct Instr { + op: Op, + args: Vec, + /// Lanes that carry meaning (1 = scalar). + dims: usize, +} + +/// A compiled function graph. +#[derive(Clone, Debug)] +pub struct Program { + code: Vec, + seed: u32, +} + +fn b(v: bool) -> f32 { + if v { 1.0 } else { 0.0 } +} + +fn dims_of(v: &Value) -> usize { + match v { + Value::Float2(_) | Value::Int2(_) => 2, + Value::Float3(_) => 3, + Value::Float4(_) | Value::Color(_) => 4, + _ => 1, + } +} + +fn broadcast(v: &Value) -> [f32; 4] { + match dims_of(v) { + 1 => [v.as_f32().unwrap_or(0.0); 4], + _ => v.as_vec4().unwrap_or([0.0; 4]), + } +} + +/// Compile `g` for evaluation. `vars` resolves `get_var` names (exposed graph inputs). +pub fn compile(g: &FnGraph, vars: &BTreeMap, seed: u32) -> Result { + let out = g.output.ok_or("the function has no output node")?; + let mut code: Vec = Vec::new(); + let mut reg: BTreeMap = BTreeMap::new(); + // Iterative post-order from the output; a node seen twice on the current path is a cycle. + let mut stack: Vec<(u32, bool)> = vec![(out, false)]; + let mut on_path = std::collections::BTreeSet::new(); + while let Some((id, done)) = stack.pop() { + if reg.contains_key(&id) { + continue; + } + let n = g.node(id).ok_or_else(|| format!("missing function node {id}"))?; + if !done { + if !on_path.insert(id) { + return Err("the function graph has a cycle".into()); + } + stack.push((id, true)); + for i in n.inputs.iter().flatten() { + if !reg.contains_key(i) { + stack.push((*i, false)); + } + } + continue; + } + on_path.remove(&id); + if code.len() > 4096 { + return Err("the function graph is too large".into()); + } + let args: Vec = n.inputs.iter().map(|i| i.and_then(|i| reg.get(&i).copied())).map(|r| r.unwrap_or(usize::MAX)).collect(); + let arity = FN_OPS.iter().find(|o| o.0 == n.op).map(|o| o.2).ok_or_else(|| format!("unknown function op `{}`", n.op))?; + if args.len() < arity || args.iter().take(arity).any(|a| *a == usize::MAX) { + return Err(format!("`{}` needs {arity} connected input(s)", n.op)); + } + let dim = |k: usize| args.get(k).and_then(|r| code.get(*r)).map_or(1, |i: &Instr| i.dims); + let maxd = (0..arity).map(dim).max().unwrap_or(1); + let (op, dims) = match n.op.as_str() { + o if o.starts_with("const_") => { + let v = n.value.clone().unwrap_or(Value::Float(0.0)); + (Op::Const(broadcast(&v)), dims_of(&v)) + } + "get_pos" => (Op::Pos, 2), + "get_size" => (Op::Size, 2), + "get_var" => { + let name = match &n.value { + Some(Value::Text(s)) => s.as_str(), + _ => "", + }; + let v = vars.get(name).cloned().unwrap_or(Value::Float(0.0)); + (Op::Const(broadcast(&v)), dims_of(&v)) + } + "sample_gray" | "sample_color" => { + let input = n.value.as_ref().and_then(Value::as_i32).unwrap_or(0).clamp(0, 3) as usize; + let gray = n.op == "sample_gray"; + (Op::Sample { input, gray }, if gray { 1 } else { 4 }) + } + "vec2" => (Op::Vec(2), 2), + "vec3" => (Op::Vec(3), 3), + "vec4" => (Op::Vec(4), 4), + "swizzle" => { + let s = match &n.value { + Some(Value::Text(s)) => s.clone(), + _ => "x".into(), + }; + let mut idx = [0usize; 4]; + let mut len = 0; + for (k, ch) in s.chars().take(4).enumerate() { + idx[k] = match ch { + 'y' | 'g' => 1, + 'z' | 'b' => 2, + 'w' | 'a' => 3, + _ => 0, + }; + len = k + 1; + } + if len == 1 { + idx = [idx[0]; 4]; + } + (Op::Swizzle(idx), len.max(1)) + } + "to_int" | "floor" => (Op::Unary(f32::floor), maxd), + "to_float" => (Op::Unary(|a| a), maxd), + "add" => (Op::Binary(|a, b| a + b), maxd), + "sub" => (Op::Binary(|a, b| a - b), maxd), + "mul" => (Op::Binary(|a, b| a * b), maxd), + "div" => (Op::Binary(|a, b| if b == 0.0 { 0.0 } else { a / b }), maxd), + "mod" => (Op::Binary(|a, b| if b == 0.0 { 0.0 } else { a.rem_euclid(b) }), maxd), + "neg" => (Op::Unary(|a| -a), maxd), + "dot" => (Op::Dot, 1), + "and" => (Op::Binary(|a, x| b(a != 0.0 && x != 0.0)), maxd), + "or" => (Op::Binary(|a, x| b(a != 0.0 || x != 0.0)), maxd), + "not" => (Op::Unary(|a| b(a == 0.0)), maxd), + "gt" => (Op::Binary(|a, x| b(a > x)), maxd), + "ge" => (Op::Binary(|a, x| b(a >= x)), maxd), + "lt" => (Op::Binary(|a, x| b(a < x)), maxd), + "le" => (Op::Binary(|a, x| b(a <= x)), maxd), + "eq" => (Op::Binary(|a, x| b(a == x)), maxd), + "ne" => (Op::Binary(|a, x| b(a != x)), maxd), + "abs" => (Op::Unary(f32::abs), maxd), + "ceil" => (Op::Unary(f32::ceil), maxd), + "frac" => (Op::Unary(|a| a - a.floor()), maxd), + "sqrt" => (Op::Unary(|a| a.max(0.0).sqrt()), maxd), + "exp" => (Op::Unary(f32::exp), maxd), + "log" => (Op::Unary(|a| if a > 0.0 { a.ln() } else { 0.0 }), maxd), + "sin" => (Op::Unary(f32::sin), maxd), + "cos" => (Op::Unary(f32::cos), maxd), + "tan" => (Op::Unary(f32::tan), maxd), + "atan2" => (Op::Binary(f32::atan2), maxd), + "pow" => (Op::Binary(|a, x| if a < 0.0 && x.fract() != 0.0 { 0.0 } else { a.powf(x) }), maxd), + "min" => (Op::Binary(f32::min), maxd), + "max" => (Op::Binary(f32::max), maxd), + "clamp" => (Op::Ternary(|a, lo, hi| a.max(lo).min(hi.max(lo))), maxd), + "lerp" => (Op::Ternary(|a, x, t| a + (x - a) * t), maxd.max(dim(0)).max(dim(1))), + "length" => (Op::Length, 1), + "normalize" => (Op::Normalize, dim(0)), + "rand" => (Op::Rand, dim(0)), + "noise" => (Op::Noise, 1), + "if_else" => (Op::IfElse, dim(1).max(dim(2))), + other => return Err(format!("unknown function op `{other}`")), + }; + reg.insert(id, code.len()); + code.push(Instr { op, args: args.into_iter().take(arity).collect(), dims }); + } + Ok(Program { code, seed }) +} + +impl Program { + /// Lanes of the result. + pub fn dims(&self) -> usize { + self.code.last().map_or(1, |i| i.dims) + } + + /// Run at normalized position `pos` of an image of `size`, sampling `inputs`. + pub fn eval(&self, pos: [f32; 2], size: [f32; 2], inputs: &[Option], tile: bool, regs: &mut Vec<[f32; 4]>) -> [f32; 4] { + regs.clear(); + for ins in &self.code { + let a = |k: usize| ins.args.get(k).and_then(|r| regs.get(*r)).copied().unwrap_or([0.0; 4]); + let v = match &ins.op { + Op::Const(c) => *c, + Op::Pos => [pos[0], pos[1], 0.0, 0.0], + Op::Size => [size[0], size[1], 0.0, 0.0], + Op::Sample { input, gray } => { + let p = a(0); + match inputs.get(*input).and_then(Option::as_ref) { + Some(img) if *gray => [img.sample_gray(p[0], p[1], tile); 4], + Some(img) => img.sample(p[0], p[1], tile), + None => [0.0, 0.0, 0.0, 1.0], + } + } + Op::Unary(f) => a(0).map(f), + Op::Binary(f) => { + let (x, y) = (a(0), a(1)); + [f(x[0], y[0]), f(x[1], y[1]), f(x[2], y[2]), f(x[3], y[3])] + } + Op::Ternary(f) => { + let (x, y, z) = (a(0), a(1), a(2)); + [f(x[0], y[0], z[0]), f(x[1], y[1], z[1]), f(x[2], y[2], z[2]), f(x[3], y[3], z[3])] + } + Op::Dot => { + let (x, y) = (a(0), a(1)); + let n = ins.args.iter().filter_map(|r| self.code.get(*r)).map(|i| i.dims).max().unwrap_or(1); + [(0..n).map(|k| x[k] * y[k]).sum(); 4] + } + Op::Length => { + let x = a(0); + let n = ins.args.first().and_then(|r| self.code.get(*r)).map_or(1, |i| i.dims); + [(0..n).map(|k| x[k] * x[k]).sum::().sqrt(); 4] + } + Op::Normalize => { + let x = a(0); + let l = (0..ins.dims).map(|k| x[k] * x[k]).sum::().sqrt(); + if l > 0.0 { x.map(|c| c / l) } else { x } + } + Op::Vec(n) => { + let mut o = [0.0; 4]; + for k in 0..*n { + o[k] = a(k)[0]; + } + o + } + Op::Swizzle(idx) => { + let x = a(0); + idx.map(|i| x[i]) + } + Op::Rand => a(0).map(|c| noise::rand1(c.to_bits(), self.seed)), + Op::Noise => { + let p = a(0); + [noise::perlin(p[0], p[1], 0, self.seed) * 0.5 + 0.5; 4] + } + Op::IfElse => { + if a(0)[0] != 0.0 { + a(1) + } else { + a(2) + } + } + }; + regs.push(v); + } + regs.last().copied().unwrap_or([0.0; 4]) + } +} + +/// The default pixel processor function: the first input, unchanged. +pub fn default_pixel_function() -> FnGraph { + let mut g = FnGraph::default(); + let pos = g.add("get_pos", &[], None); + let s = g.add("sample_color", &[pos], Some(Value::Int(0))); + g.output = Some(s); + g +} + +pub(crate) fn pixel_processor(ctx: &Ctx) -> CookResult { + let f = ctx.function("function").ok_or("no function")?; + let prog = compile(f, ctx.vars, ctx.seed)?; + let gray = ctx.i("output") == 1; + let dims = prog.dims(); + let size = [ctx.w as f32, ctx.h as f32]; + let kind = if gray { Kind::Gray } else { Kind::Color }; + Ok(vec![Image::generate_uv(ctx.w, ctx.h, kind, |u, v| { + // shortcut: one register file per pixel; a thread-local would save the allocation. + let mut regs = Vec::with_capacity(prog.code.len()); + let r = prog.eval([u, v], size, ctx.inputs, ctx.tile, &mut regs); + match (gray, dims) { + (true, _) => [r[0], 0.0, 0.0, 0.0], + (false, 1) => [r[0], r[0], r[0], 1.0], + (false, 2) => [r[0], r[1], 0.0, 1.0], + (false, 3) => [r[0], r[1], r[2], 1.0], + _ => r, + } + })]) +} + +pub(crate) fn value_processor(ctx: &Ctx) -> CookResult { + let f = ctx.function("function").ok_or("no function")?; + let prog = compile(f, ctx.vars, ctx.seed)?; + let r = prog.eval([0.5, 0.5], [ctx.w as f32, ctx.h as f32], ctx.inputs, ctx.tile, &mut Vec::new()); + Ok(vec![if prog.dims() == 1 { Image::filled(ctx.w, ctx.h, Kind::Gray, [r[0]; 4]) } else { Image::filled(ctx.w, ctx.h, Kind::Color, r) }]) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn compiles_and_runs_arithmetic() { + let mut g = FnGraph::default(); + let pos = g.add("get_pos", &[], None); + let x = g.add("swizzle", &[pos], Some(Value::Text("x".into()))); + let two = g.add("const_float", &[], Some(Value::Float(2.0))); + let m = g.add("mul", &[x, two], None); + g.output = Some(m); + let p = compile(&g, &BTreeMap::new(), 0).unwrap(); + assert_eq!(p.dims(), 1); + let r = p.eval([0.25, 0.5], [8.0, 8.0], &[], true, &mut Vec::new()); + assert_eq!(r[0], 0.5); + } + + #[test] + fn rejects_bad_graphs() { + let mut g = FnGraph::default(); + let a = g.add("add", &[], None); + g.output = Some(a); + assert!(compile(&g, &BTreeMap::new(), 0).is_err()); + g.nodes[0].inputs = vec![Some(a), Some(a)]; + assert!(compile(&g, &BTreeMap::new(), 0).is_err()); + assert!(compile(&FnGraph::default(), &BTreeMap::new(), 0).is_err()); + } +} diff --git a/crates/nodes/src/generators.rs b/crates/nodes/src/generators.rs new file mode 100644 index 00000000..700a6a08 --- /dev/null +++ b/crates/nodes/src/generators.rs @@ -0,0 +1,412 @@ +//! Texture generators › Noises. All tile seamlessly: lattice scales are whole numbers of cells. + +use materialcraft_image::{Image, Kind}; + +use crate::catalog::{CookResult, Ctx, NodeDef, node}; +use crate::noise::{self, cellular, fbm, perlin, rand2, ridged, value}; +use crate::ops; + +pub const NOISES: &str = "Texture generators/Noises"; + +fn scale(ctx: &Ctx) -> f32 { + ctx.f("scale").max(1.0).round() +} + +pub(crate) fn defs() -> Vec { + let n = |id, label| node(id, label, NOISES).generator(); + vec![ + n("anisotropic_noise", "Anisotropic Noise") + .desc("Streaks of value noise stretched along one axis.") + .float("scale", "X amount", 4.0, 1.0, 64.0) + .float("scale_y", "Y amount", 64.0, 1.0, 512.0) + .float("smoothness", "Smoothness", 0.5, 0.0, 1.0) + .float("interpolation", "Interpolation", 1.0, 0.0, 1.0) + .gray_out() + .cook(anisotropic), + n("bnw_spots_1", "BnW Spots 1") + .desc("Contrasted black and white spots.") + .float("scale", "Scale", 8.0, 1.0, 64.0) + .float("roughness", "Roughness", 0.5, 0.0, 1.0) + .gray_out() + .cook(bnw1), + n("bnw_spots_2", "BnW Spots 2") + .desc("Rounder black and white spots.") + .float("scale", "Scale", 6.0, 1.0, 64.0) + .float("roughness", "Roughness", 0.3, 0.0, 1.0) + .gray_out() + .cook(bnw2), + n("bnw_spots_3", "BnW Spots 3") + .desc("Fine black and white speckles.") + .float("scale", "Scale", 16.0, 1.0, 64.0) + .float("roughness", "Roughness", 0.6, 0.0, 1.0) + .gray_out() + .cook(bnw3), + n("cells_1", "Cells 1") + .desc("Distance to the nearest cell point (soft bumps).") + .float("scale", "Scale", 8.0, 1.0, 64.0) + .float("disorder", "Disorder", 1.0, 0.0, 1.0) + .gray_out() + .cook(cells1), + n("cells_2", "Cells 2") + .desc("Cell borders (second minus first distance).") + .float("scale", "Scale", 8.0, 1.0, 64.0) + .float("disorder", "Disorder", 1.0, 0.0, 1.0) + .gray_out() + .cook(cells2), + n("cells_3", "Cells 3") + .desc("Flat cells, each a random gray.") + .float("scale", "Scale", 8.0, 1.0, 64.0) + .float("disorder", "Disorder", 1.0, 0.0, 1.0) + .gray_out() + .cook(cells3), + n("cells_4", "Cells 4") + .desc("Chebyshev cells: square bumps.") + .float("scale", "Scale", 8.0, 1.0, 64.0) + .float("disorder", "Disorder", 1.0, 0.0, 1.0) + .gray_out() + .cook(cells4), + n("clouds_1", "Clouds 1") + .desc("Soft fractal clouds.") + .float("scale", "Scale", 4.0, 1.0, 32.0) + .float("roughness", "Roughness", 0.5, 0.0, 1.0) + .gray_out() + .cook(clouds1), + n("clouds_2", "Clouds 2") + .desc("Warped, wispy clouds.") + .float("scale", "Scale", 3.0, 1.0, 32.0) + .float("roughness", "Roughness", 0.55, 0.0, 1.0) + .gray_out() + .cook(clouds2), + n("clouds_3", "Clouds 3") + .desc("Detailed, contrasted clouds.") + .float("scale", "Scale", 6.0, 1.0, 32.0) + .float("roughness", "Roughness", 0.6, 0.0, 1.0) + .gray_out() + .cook(clouds3), + n("creased", "Creased") + .desc("Ridged fractal noise: folds and creases.") + .float("scale", "Scale", 3.0, 1.0, 32.0) + .float("roughness", "Roughness", 0.55, 0.0, 1.0) + .float("warp", "Warp intensity", 0.3, 0.0, 1.0) + .gray_out() + .cook(creased), + n("crystal_1", "Crystal 1").desc("Faceted crystal plates.").float("scale", "Scale", 6.0, 1.0, 64.0).gray_out().cook(crystal1), + n("crystal_2", "Crystal 2").desc("Sharp crystal shards.").float("scale", "Scale", 6.0, 1.0, 64.0).gray_out().cook(crystal2), + n("dirt", "Dirt").desc("Clumps of dirt.").float("scale", "Scale", 6.0, 1.0, 64.0).float("density", "Density", 0.5, 0.0, 1.0).gray_out().cook(dirt), + n("dust", "Dust").desc("Sparse specks of dust.").float("density", "Density", 0.02, 0.0, 0.2).float("size", "Size", 1.0, 0.0, 8.0).gray_out().cook(dust), + n("fractal_sum_base", "Fractal Sum Base") + .desc("Sum of Perlin noise octaves.") + .float("scale", "Min level", 2.0, 1.0, 64.0) + .int("octaves", "Octaves", 8, 1, 12) + .float("roughness", "Roughness", 0.5, 0.0, 1.0) + .gray_out() + .cook(fractal_sum), + n("fur", "Fur") + .desc("Short directional fibers.") + .float("scale", "Density", 1.0, 0.1, 4.0) + .angle("angle", "Direction", 0.25) + .float("length", "Length", 8.0, 0.0, 64.0) + .gray_out() + .cook(fur), + n("gaussian_noise", "Gaussian Noise") + .desc("Smoothly interpolated value noise.") + .float("scale", "Scale", 16.0, 1.0, 256.0) + .gray_out() + .cook(gaussian_noise), + n("grunge_map_1", "Grunge Map 1") + .desc("Stains and blotches.") + .float("scale", "Scale", 3.0, 1.0, 32.0) + .float("contrast", "Contrast", 0.5, 0.0, 1.0) + .gray_out() + .cook(grunge1), + n("grunge_map_2", "Grunge Map 2") + .desc("Speckled grime.") + .float("scale", "Scale", 5.0, 1.0, 32.0) + .float("contrast", "Contrast", 0.5, 0.0, 1.0) + .gray_out() + .cook(grunge2), + n("grunge_map_3", "Grunge Map 3") + .desc("Streaky leaks.") + .float("scale", "Scale", 4.0, 1.0, 32.0) + .float("contrast", "Contrast", 0.5, 0.0, 1.0) + .gray_out() + .cook(grunge3), + n("liquid", "Liquid") + .desc("Domain-warped flowing noise.") + .float("scale", "Scale", 3.0, 1.0, 32.0) + .float("warp", "Warp", 0.6, 0.0, 2.0) + .gray_out() + .cook(liquid), + n("moisture_noise", "Moisture Noise") + .desc("Damp patches with soft edges.") + .float("scale", "Scale", 4.0, 1.0, 32.0) + .float("contrast", "Contrast", 0.5, 0.0, 1.0) + .gray_out() + .cook(moisture), + n("perlin_noise", "Perlin Noise") + .desc("Single-octave gradient noise.") + .float("scale", "Scale", 8.0, 1.0, 256.0) + .float("disorder", "Disorder", 0.0, 0.0, 1.0) + .gray_out() + .cook(perlin_noise), + n("plasma", "Plasma").desc("Interfering sine waves through noise.").float("scale", "Scale", 4.0, 1.0, 32.0).gray_out().cook(plasma), + n("turbulence", "Turbulence") + .desc("Billowing absolute-value fractal noise.") + .float("scale", "Scale", 4.0, 1.0, 32.0) + .float("roughness", "Roughness", 0.5, 0.0, 1.0) + .gray_out() + .cook(turbulence), + n("voronoi", "Voronoi") + .desc("Cellular noise with a choice of distance and output.") + .float("scale", "Scale", 8.0, 1.0, 64.0) + .float("disorder", "Disorder", 1.0, 0.0, 1.0) + .choice("metric", "Distance", &["Euclidean", "Manhattan", "Chebyshev"], 0) + .choice("style", "Output", &["F1", "F2", "F2 - F1", "Cell id"], 2) + .gray_out() + .cook(voronoi), + n("white_noise", "White Noise").desc("Independent random value per pixel.").choice("mode", "Output", &["Grayscale", "Color"], 0).cook(white_noise), + ] +} + +fn anisotropic(ctx: &Ctx) -> CookResult { + let (sx, sy) = (scale(ctx), ctx.f("scale_y").max(1.0).round()); + let smooth = ctx.f("smoothness"); + let s = ctx.seed; + let base = ctx.gen_gray(|u, v| { + let a = value(u * sx, v * sy, sy as i32, s); + let b = value(u * sx * 2.0, v * sy, sy as i32, s ^ 77) * 0.5; + (a * 0.75 + b * 0.25 * (1.0 - smooth) + 0.125 * smooth).clamp(0.0, 1.0) + }); + Ok(vec![if smooth > 0.0 { ops::gaussian(&base, smooth * 2.0, ctx.tile) } else { base }]) +} + +fn contrast(v: f32, c: f32) -> f32 { + ((v - 0.5) * (1.0 + c * 8.0) + 0.5).clamp(0.0, 1.0) +} + +fn bnw1(ctx: &Ctx) -> CookResult { + let (sc, r, s) = (scale(ctx), ctx.f("roughness"), ctx.seed); + Ok(vec![ctx.gen_gray(|u, v| contrast(fbm(u, v, sc, 6, 0.3 + r * 0.4, s), 0.6))]) +} + +fn bnw2(ctx: &Ctx) -> CookResult { + let (sc, r, s) = (scale(ctx), ctx.f("roughness"), ctx.seed); + Ok(vec![ctx.gen_gray(|u, v| contrast(fbm(u, v, sc, 3, 0.3 + r * 0.4, s), 1.2))]) +} + +fn bnw3(ctx: &Ctx) -> CookResult { + let (sc, r, s) = (scale(ctx), ctx.f("roughness"), ctx.seed); + Ok(vec![ctx.gen_gray(|u, v| contrast(fbm(u, v, sc, 7, 0.4 + r * 0.4, s), 0.9))]) +} + +fn cell_cook(ctx: &Ctx, metric: u32, f: impl Fn(noise::Cell) -> f32 + Sync) -> CookResult { + let (sc, dis, s) = (scale(ctx), ctx.f("disorder"), ctx.seed); + Ok(vec![ctx.gen_gray(|u, v| f(cellular(u * sc, v * sc, sc as i32, dis, metric, s)).clamp(0.0, 1.0))]) +} + +fn cells1(ctx: &Ctx) -> CookResult { + cell_cook(ctx, 0, |c| 1.0 - c.f1 * 1.2) +} + +fn cells2(ctx: &Ctx) -> CookResult { + cell_cook(ctx, 0, |c| ((c.f2 - c.f1) * 2.5).min(1.0)) +} + +fn cells3(ctx: &Ctx) -> CookResult { + cell_cook(ctx, 0, |c| c.id) +} + +fn cells4(ctx: &Ctx) -> CookResult { + cell_cook(ctx, 2, |c| 1.0 - c.f1 * 1.6) +} + +fn crystal1(ctx: &Ctx) -> CookResult { + let (sc, s) = (scale(ctx), ctx.seed); + Ok(vec![ctx.gen_gray(|u, v| { + let c = cellular(u * sc, v * sc, sc as i32, 1.0, 0, s); + (c.id * 0.6 + (c.f2 - c.f1).min(0.4) + 0.1).clamp(0.0, 1.0) + })]) +} + +fn crystal2(ctx: &Ctx) -> CookResult { + let (sc, s) = (scale(ctx), ctx.seed); + Ok(vec![ctx.gen_gray(|u, v| { + let c = cellular(u * sc, v * sc, sc as i32, 1.0, 1, s); + (c.id * 0.7 + (1.0 - c.f1).max(0.0) * 0.3).clamp(0.0, 1.0) + })]) +} + +fn dirt(ctx: &Ctx) -> CookResult { + let (sc, d, s) = (scale(ctx), ctx.f("density"), ctx.seed); + Ok(vec![ctx.gen_gray(|u, v| { + let base = fbm(u, v, sc, 6, 0.55, s); + let spots = 1.0 - cellular(u * sc * 4.0, v * sc * 4.0, (sc * 4.0) as i32, 1.0, 0, s ^ 9).f1; + let t = 1.0 - d; + (((base * 0.7 + spots * 0.3) - t * 0.6) * 3.0).clamp(0.0, 1.0) + })]) +} + +fn dust(ctx: &Ctx) -> CookResult { + let (d, s) = (ctx.f("density"), ctx.seed); + let img = Image::gray(ctx.w, ctx.h, |x, y| if noise::rand2(x as i32, y as i32, s) < d { 0.5 + 0.5 * noise::rand2(y as i32, x as i32, s ^ 3) } else { 0.0 }); + let sigma = ctx.f("size") * ctx.w as f32 / 1024.0; + let b = ops::gaussian(&img, sigma, ctx.tile); + let gain = 1.0 + sigma * sigma * 4.0; + Ok(vec![b.map(Kind::Gray, |p| [(p[0] * gain).min(1.0), 0.0, 0.0, 0.0])]) +} + +fn fractal_sum(ctx: &Ctx) -> CookResult { + let (sc, o, r, s) = (scale(ctx), ctx.i("octaves").clamp(1, 12) as u32, ctx.f("roughness"), ctx.seed); + Ok(vec![ctx.gen_gray(|u, v| fbm(u, v, sc, o, r, s))]) +} + +fn fur(ctx: &Ctx) -> CookResult { + let s = ctx.seed; + let density = ctx.f("scale").clamp(0.1, 4.0); + let img = Image::gray(ctx.w, ctx.h, |x, y| { + let r = rand2(x as i32, y as i32, s); + if r < 0.15 * density { rand2(y as i32, x as i32, s ^ 5) } else { 0.0 } + }); + let len = ctx.f("length") * ctx.w as f32 / 256.0; + let (dx, dy) = ((ctx.f("angle") * std::f32::consts::TAU).cos(), -(ctx.f("angle") * std::f32::consts::TAU).sin()); + let n = (len.ceil() as i32).clamp(1, 256); + let (iw, ih) = (1.0 / ctx.w as f32, 1.0 / ctx.h as f32); + Ok(vec![Image::generate_uv(ctx.w, ctx.h, Kind::Gray, |u, v| { + let mut acc = 0.0; + for i in 0..=n { + let t = i as f32 / n as f32 * len; + acc += img.sample_nearest(u - dx * t * iw, v - dy * t * ih, ctx.tile)[0] * (1.0 - i as f32 / (n + 1) as f32); + } + [(acc * 2.5 / (n as f32).sqrt()).min(1.0), 0.0, 0.0, 0.0] + })]) +} + +fn gaussian_noise(ctx: &Ctx) -> CookResult { + let (sc, s) = (scale(ctx), ctx.seed); + Ok(vec![ctx.gen_gray(|u, v| { + let a = value(u * sc, v * sc, sc as i32, s); + let b = value(u * sc * 2.0, v * sc * 2.0, (sc * 2.0) as i32, s ^ 1); + (a * 0.7 + b * 0.3).clamp(0.0, 1.0) + })]) +} + +fn grunge(ctx: &Ctx, f: impl Fn(f32, f32, f32, u32) -> f32 + Sync) -> CookResult { + let (sc, c, s) = (scale(ctx), ctx.f("contrast"), ctx.seed); + Ok(vec![ctx.gen_gray(|u, v| contrast(f(u, v, sc, s), c))]) +} + +fn grunge1(ctx: &Ctx) -> CookResult { + grunge(ctx, |u, v, sc, s| { + let a = fbm(u, v, sc, 7, 0.6, s); + let b = 1.0 - cellular(u * sc * 3.0, v * sc * 3.0, (sc * 3.0) as i32, 1.0, 0, s ^ 4).f1; + a * 0.75 + b * 0.25 + }) +} + +fn grunge2(ctx: &Ctx) -> CookResult { + grunge(ctx, |u, v, sc, s| { + let a = fbm(u, v, sc, 8, 0.65, s); + let speck = if rand2((u * 512.0) as i32, (v * 512.0) as i32, s ^ 8) > 0.9 { 0.25 } else { 0.0 }; + (a - speck).clamp(0.0, 1.0) + }) +} + +fn grunge3(ctx: &Ctx) -> CookResult { + grunge(ctx, |u, v, sc, s| { + let streak = value(u * sc * 8.0, v * sc * 0.5, (sc * 8.0) as i32, s); + let a = fbm(u, v, sc, 6, 0.55, s ^ 2); + streak * 0.5 + a * 0.5 + }) +} + +fn liquid(ctx: &Ctx) -> CookResult { + let (sc, w, s) = (scale(ctx), ctx.f("warp"), ctx.seed); + Ok(vec![ctx.gen_gray(|u, v| { + let qx = fbm(u, v, sc, 4, 0.5, s) - 0.5; + let qy = fbm(u + 0.37, v + 0.71, sc, 4, 0.5, s ^ 3) - 0.5; + fbm(u + qx * w, v + qy * w, sc, 5, 0.5, s ^ 7) + })]) +} + +fn moisture(ctx: &Ctx) -> CookResult { + let (sc, c, s) = (scale(ctx), ctx.f("contrast"), ctx.seed); + Ok(vec![ctx.gen_gray(|u, v| { + let a = fbm(u, v, sc, 6, 0.5, s); + let b = (perlin(u * sc * 2.0, v * sc * 2.0, (sc * 2.0) as i32, s ^ 6)).abs(); + contrast(a * 0.8 + (1.0 - b) * 0.2, c) + })]) +} + +fn perlin_noise(ctx: &Ctx) -> CookResult { + let (sc, d, s) = (scale(ctx), ctx.f("disorder"), ctx.seed); + Ok(vec![ctx.gen_gray(|u, v| { + let (wu, wv) = if d > 0.0 { ((perlin(u * 3.0, v * 3.0, 3, s ^ 1)) * d * 0.1, (perlin(u * 3.0, v * 3.0, 3, s ^ 2)) * d * 0.1) } else { (0.0, 0.0) }; + (perlin((u + wu) * sc, (v + wv) * sc, sc as i32, s) * 0.5 + 0.5).clamp(0.0, 1.0) + })]) +} + +fn plasma(ctx: &Ctx) -> CookResult { + let (sc, s) = (scale(ctx), ctx.seed); + let tau = std::f32::consts::TAU; + Ok(vec![ctx.gen_gray(|u, v| { + let n = fbm(u, v, sc, 3, 0.5, s) * 2.0; + let a = (u * tau * sc + n * 3.0).sin() + (v * tau * sc + n * 2.0).sin() + ((u + v) * tau * sc.round() + n).sin(); + (a / 6.0 + 0.5).clamp(0.0, 1.0) + })]) +} + +fn turbulence(ctx: &Ctx) -> CookResult { + let (sc, r, s) = (scale(ctx), ctx.f("roughness"), ctx.seed); + Ok(vec![ctx.gen_gray(|u, v| 1.0 - ridged(u, v, sc, 6, r, s).sqrt())]) +} + +fn creased(ctx: &Ctx) -> CookResult { + let (sc, r, w, s) = (scale(ctx), ctx.f("roughness"), ctx.f("warp"), ctx.seed); + Ok(vec![ctx.gen_gray(|u, v| { + let q = fbm(u, v, sc, 3, 0.5, s ^ 11) - 0.5; + ridged(u + q * w * 0.3, v - q * w * 0.3, sc, 6, r, s) + })]) +} + +fn clouds1(ctx: &Ctx) -> CookResult { + let (sc, r, s) = (scale(ctx), ctx.f("roughness"), ctx.seed); + Ok(vec![ctx.gen_gray(|u, v| fbm(u, v, sc, 8, r, s))]) +} + +fn clouds2(ctx: &Ctx) -> CookResult { + let (sc, r, s) = (scale(ctx), ctx.f("roughness"), ctx.seed); + Ok(vec![ctx.gen_gray(|u, v| { + let q = fbm(u, v, sc, 4, 0.5, s ^ 5) - 0.5; + fbm(u + q * 0.35, v + q * 0.35, sc, 8, r, s) + })]) +} + +fn clouds3(ctx: &Ctx) -> CookResult { + let (sc, r, s) = (scale(ctx), ctx.f("roughness"), ctx.seed); + Ok(vec![ctx.gen_gray(|u, v| contrast(fbm(u, v, sc, 9, r, s), 0.35))]) +} + +fn voronoi(ctx: &Ctx) -> CookResult { + let (sc, dis, s) = (scale(ctx), ctx.f("disorder"), ctx.seed); + let (metric, style) = (ctx.i("metric").clamp(0, 2) as u32, ctx.i("style")); + Ok(vec![ctx.gen_gray(|u, v| { + let c = cellular(u * sc, v * sc, sc as i32, dis, metric, s); + match style { + 0 => c.f1.min(1.0), + 1 => (c.f2 * 0.8).min(1.0), + 3 => c.id, + _ => ((c.f2 - c.f1) * 2.0).min(1.0), + } + })]) +} + +fn white_noise(ctx: &Ctx) -> CookResult { + let s = ctx.seed; + Ok(vec![if ctx.i("mode") == 1 { + Image::generate(ctx.w, ctx.h, Kind::Color, |x, y| { + [rand2(x as i32, y as i32, s), rand2(x as i32, y as i32, s ^ 1), rand2(x as i32, y as i32, s ^ 2), 1.0] + }) + } else { + Image::gray(ctx.w, ctx.h, |x, y| rand2(x as i32, y as i32, s)) + }]) +} diff --git a/crates/nodes/src/lib.rs b/crates/nodes/src/lib.rs new file mode 100644 index 00000000..782fbc0f --- /dev/null +++ b/crates/nodes/src/lib.rs @@ -0,0 +1,96 @@ +//! # materialcraft-nodes +//! +//! The node library, L1: every node's definition (ports, parameters, library category) and its +//! CPU implementation. A cook is a pure function of its inputs, resolved parameters, size, seed +//! and tiling ([`Ctx`]), so every node is testable on its own and identical in the app, the CLI, +//! the MCP server and the browser. Noises tile seamlessly. +#![forbid(unsafe_code)] +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +pub mod atomic; +pub mod catalog; +pub mod filters; +pub mod function; +pub mod generators; +pub mod material; +pub mod noise; +pub mod ops; +pub mod patterns; + +pub use catalog::{CookResult, Ctx, NodeDef, ParamDef, PortDef, PortKind, catalog, categories, find, resolve_params}; + +#[cfg(test)] +mod tests { + use std::collections::BTreeMap; + + use materialcraft_image::{Image, Kind}; + + use super::*; + + fn cook(def: &NodeDef, inputs: &[Option], size: u32) -> CookResult { + let params = resolve_params(def, &BTreeMap::new()); + let no_res = |_: &str| None; + let vars = BTreeMap::new(); + let ctx = Ctx { w: size, h: size, seed: 7, tile: true, inputs, params: ¶ms, resource: &no_res, vars: &vars }; + (def.cook)(&ctx) + } + + /// Every node cooks with no inputs and with hostile-sized inputs, returns as many images as + /// it has outputs, at the requested size, with finite values. + #[test] + fn every_node_cooks() { + let ids: Vec<&str> = catalog().iter().map(|d| d.id).collect(); + let mut seen = std::collections::BTreeSet::new(); + for id in &ids { + assert!(seen.insert(*id), "duplicate node id {id}"); + } + let odd = Image::generate(5, 3, Kind::Color, |x, y| [x as f32 / 4.0, y as f32 / 2.0, 0.5, 1.0]); + for def in catalog() { + if def.id == "graph_instance" { + continue; + } + for inputs in [vec![None; def.inputs.len()], vec![Some(odd.clone()); def.inputs.len()]] { + let out = cook(def, &inputs, 32).unwrap_or_else(|e| panic!("{}: {e}", def.id)); + assert_eq!(out.len(), def.outputs.len().max(1), "{}", def.id); + for img in &out { + assert_eq!((img.w, img.h), (32, 32), "{}", def.id); + assert!(img.data.iter().all(|v| v.is_finite()), "{} produced a non-finite value", def.id); + } + } + } + assert!(catalog().len() >= 100, "{} nodes", catalog().len()); + } + + #[test] + fn noises_tile() { + for id in ["perlin_noise", "clouds_1", "cells_1", "voronoi", "brick_generator", "tile_generator", "hexagons"] { + let def = find(id).unwrap(); + let img = &cook(def, &[], 64).unwrap()[0]; + // The jump across the wrap is no larger than typical neighbouring differences. + let mut seam = 0.0f32; + let mut inner = 0.0f32; + for y in 0..64 { + seam += (img.get(63, y, false)[0] - img.get(0, y, false)[0]).abs(); + inner += (img.get(31, y, false)[0] - img.get(32, y, false)[0]).abs(); + } + assert!(seam <= inner * 3.0 + 0.5, "{id}: seam {seam} vs inner {inner}"); + } + } + + #[test] + fn blend_and_levels_math() { + let fg = Image::filled(4, 4, Kind::Gray, [0.25; 4]); + let bg = Image::filled(4, 4, Kind::Gray, [0.5; 4]); + let def = find("blend").unwrap(); + let mut params = resolve_params(def, &BTreeMap::new()); + params.insert("mode".into(), materialcraft_core::Value::Enum(3)); + let no_res = |_: &str| None; + let vars = BTreeMap::new(); + let inputs = [Some(fg), Some(bg), None]; + let ctx = Ctx { w: 4, h: 4, seed: 0, tile: true, inputs: &inputs, params: ¶ms, resource: &no_res, vars: &vars }; + let out = (def.cook)(&ctx).unwrap(); + assert!((out[0].data[0] - 0.125).abs() < 1e-6); + assert!((atomic::levels_fn(0.5, 0.0, 0.5, 1.0, 0.0, 1.0) - 0.5).abs() < 1e-5); + assert_eq!(atomic::levels_fn(0.2, 0.4, 0.5, 0.8, 0.0, 1.0), 0.0); + } +} diff --git a/crates/nodes/src/material.rs b/crates/nodes/src/material.rs new file mode 100644 index 00000000..fd3a65e7 --- /dev/null +++ b/crates/nodes/src/material.rs @@ -0,0 +1,90 @@ +//! Material filters: nodes that make or process whole PBR materials (several outputs). + +use materialcraft_image::{Image, Kind, linear_to_srgb, srgb_to_linear}; + +use crate::atomic::height_to_normal; +use crate::catalog::{CookResult, Ctx, NodeDef, PortKind, node}; +use crate::ops; + +const PBR: &str = "Material filters/PBR utilities"; + +pub(crate) fn defs() -> Vec { + vec![ + node("pbr_base_material", "PBR Base Material", PBR) + .desc("A uniform PBR material: base color, normal, roughness, metallic, height and ambient occlusion.") + .generator() + .color("base_color", "Base color", [0.5, 0.5, 0.5, 1.0]) + .float("roughness", "Roughness", 0.5, 0.0, 1.0) + .float("metallic", "Metallic", 0.0, 0.0, 1.0) + .float("height", "Height", 0.5, 0.0, 1.0) + .float("ao", "Ambient occlusion", 1.0, 0.0, 1.0) + .output("base_color", "Base color", PortKind::Color) + .output("normal", "Normal", PortKind::Color) + .output("roughness", "Roughness", PortKind::Gray) + .output("metallic", "Metallic", PortKind::Gray) + .output("height", "Height", PortKind::Gray) + .output("ambient_occlusion", "Ambient occlusion", PortKind::Gray) + .cook(pbr_base), + node("height_normal_ao", "Height to Normal and AO", PBR) + .desc("A normal map and an ambient occlusion map from one height map.") + .gray_in("height", "Height") + .float("normal_intensity", "Normal intensity", 1.0, 0.0, 10.0) + .float("ao_spread", "AO spreading", 0.15, 0.0, 1.0) + .float("ao_depth", "AO depth", 0.5, 0.0, 1.0) + .output("normal", "Normal", PortKind::Color) + .output("ambient_occlusion", "Ambient occlusion", PortKind::Gray) + .cook(height_normal_ao), + node("albedo_safe", "Albedo Safe Color", PBR) + .desc("Keeps base colors inside the physically plausible range (sRGB 30–240).") + .color_in("input", "Base color") + .color_out() + .cook(albedo_safe), + node("metallic_mask", "Metallic From Mask", PBR) + .desc("Turns a mask into a clean metallic map (fully metallic or not).") + .gray_in("input", "Mask") + .float("threshold", "Threshold", 0.5, 0.0, 1.0) + .gray_out() + .cook(metallic_mask), + ] +} + +fn pbr_base(ctx: &Ctx) -> CookResult { + let (w, h) = (ctx.w, ctx.h); + let g = |v: f32| Image::filled(w, h, Kind::Gray, [v; 4]); + Ok(vec![ + Image::filled(w, h, Kind::Color, ctx.v4("base_color")), + Image::filled(w, h, Kind::Color, [0.5, 0.5, 1.0, 1.0]), + g(ctx.f("roughness")), + g(ctx.f("metallic")), + g(ctx.f("height")), + g(ctx.f("ao")), + ]) +} + +fn height_normal_ao(ctx: &Ctx) -> CookResult { + let h = ctx.gray_or(0, 0.5); + let n = height_to_normal(&h, ctx.f("normal_intensity") * ctx.w as f32 / 32.0, false, ctx.tile, false); + let spread = ctx.f("ao_spread").max(0.001) * ctx.w as f32 * 0.25; + let wide = ops::gaussian(&h, spread, ctx.tile); + let depth = ctx.f("ao_depth"); + let ao = Image::generate(ctx.w, ctx.h, Kind::Gray, |x, y| { + let i = (y * ctx.w + x) as usize; + [(1.0 - (wide.data[i] - h.data[i]).max(0.0) * depth * 6.0).clamp(0.0, 1.0), 0.0, 0.0, 0.0] + }); + Ok(vec![n, ao]) +} + +fn albedo_safe(ctx: &Ctx) -> CookResult { + let img = ctx.any_or(0, Kind::Color, [0.5, 0.5, 0.5, 1.0]).to_color(); + let (lo, hi) = (30.0 / 255.0, 240.0 / 255.0); + Ok(vec![img.map(Kind::Color, |p| { + let f = |v: f32| srgb_to_linear(linear_to_srgb(v).clamp(lo, hi)); + [f(p[0]), f(p[1]), f(p[2]), p[3]] + })]) +} + +fn metallic_mask(ctx: &Ctx) -> CookResult { + let t = ctx.f("threshold"); + let img = ctx.gray_or(0, 0.0); + Ok(vec![img.map(Kind::Gray, |p| [if p[0] >= t { 1.0 } else { 0.0 }, 0.0, 0.0, 0.0])]) +} diff --git a/crates/nodes/src/noise.rs b/crates/nodes/src/noise.rs new file mode 100644 index 00000000..b6e6bfd3 --- /dev/null +++ b/crates/nodes/src/noise.rs @@ -0,0 +1,184 @@ +//! Tileable noise primitives: integer hashing, value and gradient (Perlin) noise on a periodic +//! lattice, fractal sums and cellular (Worley) noise. Every function takes normalized coordinates +//! (0..1 across the image) and a period in cells, so whole-number scales tile seamlessly. + +/// A 32-bit integer hash (lowbias32 by Chris Wellons, public domain). +#[inline] +pub fn hash(mut x: u32) -> u32 { + x ^= x >> 16; + x = x.wrapping_mul(0x7feb_352d); + x ^= x >> 15; + x = x.wrapping_mul(0x846c_a68b); + x ^= x >> 16; + x +} + +#[inline] +pub fn hash3(x: i32, y: i32, seed: u32) -> u32 { + hash((x as u32).wrapping_mul(0x8da6_b343) ^ hash((y as u32).wrapping_mul(0xd816_3841) ^ seed.wrapping_mul(0xcb1a_b31f))) +} + +/// Uniform 0..1 from a lattice point. +#[inline] +pub fn rand2(x: i32, y: i32, seed: u32) -> f32 { + (hash3(x, y, seed) >> 8) as f32 / (1u32 << 24) as f32 +} + +/// Uniform 0..1 from an index. +#[inline] +pub fn rand1(i: u32, seed: u32) -> f32 { + (hash(i ^ hash(seed.wrapping_add(0x9e37_79b9))) >> 8) as f32 / (1u32 << 24) as f32 +} + +#[inline] +fn fade(t: f32) -> f32 { + t * t * t * (t * (t * 6.0 - 15.0) + 10.0) +} + +#[inline] +fn wrapi(i: i32, p: i32) -> i32 { + if p <= 0 { i } else { i.rem_euclid(p) } +} + +/// Value noise in 0..1, lattice period `p` cells (coordinates already scaled to cells). +pub fn value(x: f32, y: f32, p: i32, seed: u32) -> f32 { + let (x0, y0) = (x.floor(), y.floor()); + let (tx, ty) = (fade(x - x0), fade(y - y0)); + let (ix, iy) = (x0 as i32, y0 as i32); + let r = |i: i32, j: i32| rand2(wrapi(i, p), wrapi(j, p), seed); + let a = r(ix, iy) + (r(ix + 1, iy) - r(ix, iy)) * tx; + let b = r(ix, iy + 1) + (r(ix + 1, iy + 1) - r(ix, iy + 1)) * tx; + a + (b - a) * ty +} + +/// Gradient (Perlin) noise in about -1..1, lattice period `p` cells. +pub fn perlin(x: f32, y: f32, p: i32, seed: u32) -> f32 { + let (x0, y0) = (x.floor(), y.floor()); + let (fx, fy) = (x - x0, y - y0); + let (ix, iy) = (x0 as i32, y0 as i32); + let g = |i: i32, j: i32, dx: f32, dy: f32| { + let h = hash3(wrapi(i, p), wrapi(j, p), seed); + let a = (h >> 8) as f32 * (std::f32::consts::TAU / (1u32 << 24) as f32); + a.cos() * dx + a.sin() * dy + }; + let (u, v) = (fade(fx), fade(fy)); + let n00 = g(ix, iy, fx, fy); + let n10 = g(ix + 1, iy, fx - 1.0, fy); + let n01 = g(ix, iy + 1, fx, fy - 1.0); + let n11 = g(ix + 1, iy + 1, fx - 1.0, fy - 1.0); + let a = n00 + (n10 - n00) * u; + let b = n01 + (n11 - n01) * u; + (a + (b - a) * v) * std::f32::consts::SQRT_2 +} + +/// Fractal sum of Perlin noise in 0..1: `octaves` layers from `scale` cells, each `lacunarity` +/// (2) times finer and `gain` times weaker. Tileable when `scale` is whole. +pub fn fbm(u: f32, v: f32, scale: f32, octaves: u32, gain: f32, seed: u32) -> f32 { + let mut sum = 0.0; + let mut amp = 1.0; + let mut norm = 0.0; + let mut s = scale.max(1.0).round(); + for o in 0..octaves.clamp(1, 12) { + sum += perlin(u * s, v * s, s as i32, seed.wrapping_add(o * 1013)) * amp; + norm += amp; + amp *= gain; + s *= 2.0; + } + (sum / norm.max(1e-6)) * 0.5 + 0.5 +} + +/// Ridged (creased) fractal: `1 - |perlin|` layers, 0..1. +pub fn ridged(u: f32, v: f32, scale: f32, octaves: u32, gain: f32, seed: u32) -> f32 { + let mut sum = 0.0; + let mut amp = 1.0; + let mut norm = 0.0; + let mut s = scale.max(1.0).round(); + for o in 0..octaves.clamp(1, 12) { + let n = 1.0 - perlin(u * s, v * s, s as i32, seed.wrapping_add(o * 7919)).abs(); + sum += n * n * amp; + norm += amp; + amp *= gain; + s *= 2.0; + } + sum / norm.max(1e-6) +} + +/// Result of a cellular lookup: the nearest and second-nearest feature distances (in cells), +/// the nearest feature's random id (0..1) and its position (cells). +#[derive(Clone, Copy, Debug)] +pub struct Cell { + pub f1: f32, + pub f2: f32, + pub id: f32, + pub center: [f32; 2], +} + +/// Worley noise with one jittered feature point per cell (`jitter` 0..1), period `p` cells. +/// `metric`: 0 Euclidean, 1 Manhattan, 2 Chebyshev. +pub fn cellular(x: f32, y: f32, p: i32, jitter: f32, metric: u32, seed: u32) -> Cell { + let (ix, iy) = (x.floor() as i32, y.floor() as i32); + let mut f1 = f32::MAX; + let mut f2 = f32::MAX; + let mut id = 0.0; + let mut center = [0.0, 0.0]; + for j in -2..=2 { + for i in -2..=2 { + let (cx, cy) = (ix + i, iy + j); + let (wx, wy) = (wrapi(cx, p), wrapi(cy, p)); + let px = cx as f32 + 0.5 + (rand2(wx, wy, seed) - 0.5) * jitter; + let py = cy as f32 + 0.5 + (rand2(wx, wy, seed ^ 0x5bd1_e995) - 0.5) * jitter; + let (dx, dy) = (px - x, py - y); + let d = match metric { + 1 => dx.abs() + dy.abs(), + 2 => dx.abs().max(dy.abs()), + _ => (dx * dx + dy * dy).sqrt(), + }; + if d < f1 { + f2 = f1; + f1 = d; + id = rand2(wx, wy, seed ^ 0x2545_f491); + center = [px, py]; + } else if d < f2 { + f2 = d; + } + } + } + Cell { f1, f2, id, center } +} + +/// Gaussian-distributed sample (Box–Muller) from two uniforms. +pub fn gauss(u1: f32, u2: f32) -> f32 { + (-2.0 * u1.max(1e-7).ln()).sqrt() * (std::f32::consts::TAU * u2).cos() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn perlin_tiles_at_its_period() { + for k in 0..20 { + let y = k as f32 * 0.37; + let a = perlin(0.0, y, 4, 7); + let b = perlin(4.0, y, 4, 7); + assert!((a - b).abs() < 1e-5, "{a} {b}"); + } + let a = fbm(0.0, 0.3, 4.0, 5, 0.5, 1); + let b = fbm(1.0, 0.3, 4.0, 5, 0.5, 1); + assert!((a - b).abs() < 1e-4); + } + + #[test] + fn cellular_tiles_and_ranges() { + let a = cellular(0.1, 0.2, 5, 1.0, 0, 3).f1; + let b = cellular(5.1, 0.2, 5, 1.0, 0, 3).f1; + assert!((a - b).abs() < 1e-4); + assert!(a >= 0.0 && a < 1.5); + } + + #[test] + fn rand_is_uniformish() { + let m: f32 = (0..10000).map(|i| rand1(i, 9)).sum::() / 10000.0; + assert!((m - 0.5).abs() < 0.02); + } +} diff --git a/crates/nodes/src/ops.rs b/crates/nodes/src/ops.rs new file mode 100644 index 00000000..2b304df9 --- /dev/null +++ b/crates/nodes/src/ops.rs @@ -0,0 +1,337 @@ +//! Image operations shared by many nodes: Gaussian blur, Euclidean distance transform, slopes, +//! color space helpers and blend modes. + +use std::sync::Arc; + +use materialcraft_image::{Image, Kind}; +use rayon::prelude::*; + +/// Gaussian blur with standard deviation `sigma` (pixels). Small sigmas use a sampled kernel; +/// larger ones three box passes (a close Gaussian approximation in O(1) per pixel). +pub fn gaussian(img: &Image, sigma: f32, tile: bool) -> Image { + if !(sigma > 0.05) || !sigma.is_finite() { + return img.clone(); + } + let sigma = sigma.min(img.w.max(img.h) as f32); + if sigma < 3.0 { + let r = (sigma * 3.0).ceil() as i64; + let k: Vec = (-r..=r).map(|i| (-(i * i) as f32 / (2.0 * sigma * sigma)).exp()).collect(); + let s: f32 = k.iter().sum(); + let k: Vec = k.iter().map(|v| v / s).collect(); + let pass = |src: &Image, horizontal: bool| convolve_1d(src, &k, r, horizontal, tile); + return pass(&pass(img, true), false); + } + // Box widths for three passes (Kovesi, "Fast almost-Gaussian filtering"). + let n = 3.0f32; + let wl = ((12.0 * sigma * sigma / n + 1.0).sqrt()).floor() as i64; + let wl = if wl % 2 == 0 { wl - 1 } else { wl }; + let wu = wl + 2; + let m = ((12.0 * sigma * sigma - n * (wl * wl) as f32 - 4.0 * n * wl as f32 - 3.0 * n) / (-4.0 * wl as f32 - 4.0)).round() as i64; + let mut out = img.clone(); + for i in 0..3 { + let r = (if i < m { wl } else { wu } - 1) / 2; + out = box_1d(&box_1d(&out, r.max(0), true, tile), r.max(0), false, tile); + } + out +} + +fn convolve_1d(src: &Image, k: &[f32], r: i64, horizontal: bool, tile: bool) -> Image { + let c = src.channels(); + Image::generate(src.w, src.h, src.kind, |x, y| { + let mut acc = [0.0f32; 4]; + for (i, kv) in k.iter().enumerate() { + let o = i as i64 - r; + let p = if horizontal { src.get(x as i64 + o, y as i64, tile) } else { src.get(x as i64, y as i64 + o, tile) }; + for ch in 0..c.max(1).min(4) { + acc[ch] += p[ch] * kv; + } + } + if c == 1 { [acc[0], 0.0, 0.0, 0.0] } else { acc } + }) +} + +/// One running-sum box pass of radius `r`. +fn box_1d(src: &Image, r: i64, horizontal: bool, tile: bool) -> Image { + if r <= 0 { + return src.clone(); + } + let (w, h) = (src.w as usize, src.h as usize); + let c = src.channels(); + let inv = 1.0 / (2 * r + 1) as f32; + let mut data = vec![0.0f32; w * h * c]; + let line_len = if horizontal { w } else { h }; + let lines = if horizontal { h } else { w }; + let get = |line: usize, i: i64, ch: usize| -> f32 { + let n = line_len as i64; + let i = if tile { i.rem_euclid(n) } else { i.clamp(0, n - 1) } as usize; + let (x, y) = if horizontal { (i, line) } else { (line, i) }; + src.data.get((y * w + x) * c + ch).copied().unwrap_or(0.0) + }; + let results: Vec> = (0..lines) + .into_par_iter() + .map(|line| { + let mut out = vec![0.0f32; line_len * c]; + for ch in 0..c { + let mut sum: f32 = (-r..=r).map(|i| get(line, i, ch)).sum(); + for i in 0..line_len { + out[i * c + ch] = sum * inv; + sum += get(line, i as i64 + r + 1, ch) - get(line, i as i64 - r, ch); + } + } + out + }) + .collect(); + for (line, vals) in results.iter().enumerate() { + for i in 0..line_len { + let (x, y) = if horizontal { (i, line) } else { (line, i) }; + let dst = (y * w + x) * c; + data[dst..dst + c].copy_from_slice(&vals[i * c..i * c + c]); + } + } + Image { w: src.w, h: src.h, kind: src.kind, data: Arc::new(data) } +} + +/// Squared Euclidean distance (pixels) from every pixel to the nearest pixel where `inside` is +/// true (Felzenszwalb–Huttenlocher, exact, linear time). With `tile`, distances wrap. +pub fn distance_sq(w: u32, h: u32, inside: impl Fn(usize) -> bool + Sync, tile: bool) -> Vec { + let (w, h) = (w as usize, h as usize); + const INF: f32 = 1e20; + // Tiling: run on a 3x tiled line so distances cross the edges. + let rep = if tile { 3 } else { 1 }; + let edt_1d = |f: &[f32]| -> Vec { + let n = f.len(); + let f: Vec = f.iter().map(|v| *v as f64).collect(); + let mut d = vec![0.0f32; n]; + let mut v = vec![0usize; n]; + let mut z = vec![0.0f64; n + 1]; + let mut k = 0usize; + z[0] = -(INF as f64); + z[1] = INF as f64; + let cross = |q: usize, p: usize| ((f[q] + (q * q) as f64) - (f[p] + (p * p) as f64)) / (2.0 * q as f64 - 2.0 * p as f64); + for q in 1..n { + let mut s = cross(q, v[k]); + while k > 0 && s <= z[k] { + k -= 1; + s = cross(q, v[k]); + } + k += 1; + v[k] = q; + z[k] = s; + z[k + 1] = INF as f64; + } + k = 0; + for (q, dq) in d.iter_mut().enumerate() { + while k + 1 < n && z[k + 1] < q as f64 { + k += 1; + } + let p = v[k]; + *dq = ((q as f64 - p as f64).powi(2) + f[p]) as f32; + } + d + }; + // Columns. + let cols: Vec> = (0..w) + .into_par_iter() + .map(|x| { + let f: Vec = (0..h * rep).map(|y| if inside((y % h) * w + x) { 0.0 } else { INF }).collect(); + let d = edt_1d(&f); + let off = if tile { h } else { 0 }; + d[off..off + h].to_vec() + }) + .collect(); + // Rows. + let rows: Vec> = (0..h) + .into_par_iter() + .map(|y| { + let f: Vec = (0..w * rep).map(|x| cols[x % w][y]).collect(); + let d = edt_1d(&f); + let off = if tile { w } else { 0 }; + d[off..off + w].to_vec() + }) + .collect(); + rows.concat() +} + +/// Slope (dx, dy) of a gray image by central differences, in value units per pixel. +#[inline] +pub fn slope(img: &Image, x: i64, y: i64, tile: bool) -> (f32, f32) { + let dx = (img.get_gray(x + 1, y, tile) - img.get_gray(x - 1, y, tile)) * 0.5; + let dy = (img.get_gray(x, y + 1, tile) - img.get_gray(x, y - 1, tile)) * 0.5; + (dx, dy) +} + +pub fn rgb_to_hsl(c: [f32; 4]) -> [f32; 3] { + let (r, g, b) = (c[0], c[1], c[2]); + let mx = r.max(g).max(b); + let mn = r.min(g).min(b); + let l = (mx + mn) * 0.5; + if (mx - mn).abs() < 1e-7 { + return [0.0, 0.0, l]; + } + let d = mx - mn; + let s = if l > 0.5 { d / (2.0 - mx - mn) } else { d / (mx + mn) }; + let h = if mx == r { + (g - b) / d + if g < b { 6.0 } else { 0.0 } + } else if mx == g { + (b - r) / d + 2.0 + } else { + (r - g) / d + 4.0 + }; + [h / 6.0, s, l] +} + +pub fn hsl_to_rgb(h: f32, s: f32, l: f32) -> [f32; 3] { + if s <= 0.0 { + return [l, l, l]; + } + let q = if l < 0.5 { l * (1.0 + s) } else { l + s - l * s }; + let p = 2.0 * l - q; + let f = |mut t: f32| { + t = t.rem_euclid(1.0); + if t < 1.0 / 6.0 { + p + (q - p) * 6.0 * t + } else if t < 0.5 { + q + } else if t < 2.0 / 3.0 { + p + (q - p) * (2.0 / 3.0 - t) * 6.0 + } else { + p + } + }; + [f(h + 1.0 / 3.0), f(h), f(h - 1.0 / 3.0)] +} + +pub const BLEND_MODES: &[&str] = &[ + "Copy", + "Add (Linear dodge)", + "Subtract", + "Multiply", + "Add Sub", + "Max (Lighten)", + "Min (Darken)", + "Switch", + "Divide", + "Overlay", + "Screen", + "Soft light", + "Difference", + "Color dodge", + "Color burn", + "Hard light", +]; + +/// Blend one channel: `b` background, `f` foreground. +#[inline] +pub fn blend_channel(mode: i32, b: f32, f: f32) -> f32 { + match mode { + 1 => b + f, + 2 => b - f, + 3 => b * f, + 4 => b + 2.0 * f - 1.0, + 5 => b.max(f), + 6 => b.min(f), + 8 => { + if f.abs() < 1e-6 { + if b > 0.0 { 1.0 } else { 0.0 } + } else { + b / f + } + } + 9 => { + if b < 0.5 { + 2.0 * b * f + } else { + 1.0 - 2.0 * (1.0 - b) * (1.0 - f) + } + } + 10 => 1.0 - (1.0 - b) * (1.0 - f), + 11 => { + // W3C soft light. + if f <= 0.5 { + b - (1.0 - 2.0 * f) * b * (1.0 - b) + } else { + let d = if b <= 0.25 { ((16.0 * b - 12.0) * b + 4.0) * b } else { b.max(0.0).sqrt() }; + b + (2.0 * f - 1.0) * (d - b) + } + } + 12 => (b - f).abs(), + 13 => { + if f >= 1.0 { + 1.0 + } else { + (b / (1.0 - f)).min(1.0) + } + } + 14 => { + if f <= 0.0 { + 0.0 + } else { + 1.0 - ((1.0 - b) / f).min(1.0) + } + } + 15 => { + if f < 0.5 { + 2.0 * b * f + } else { + 1.0 - 2.0 * (1.0 - b) * (1.0 - f) + } + } + _ => f, + } +} + +/// Blend `fg` over `bg` with `mode`, weighted by `opacity` (0..1, already including any mask). +/// `use_alpha`: the foreground's alpha also weights it. +#[inline] +pub fn blend_px(mode: i32, bg: [f32; 4], fg: [f32; 4], opacity: f32, use_alpha: bool, clamp: bool) -> [f32; 4] { + let t = opacity * if use_alpha { fg[3] } else { 1.0 }; + let mut o = [0.0; 4]; + for k in 0..3 { + let mut v = blend_channel(mode, bg[k], fg[k]); + if clamp { + v = v.clamp(0.0, 1.0); + } + o[k] = bg[k] + (v - bg[k]) * t; + } + o[3] = if mode == 0 || mode == 7 { bg[3] + (fg[3] - bg[3]) * opacity } else { bg[3] }; + o +} + +/// A gray image of the output size from per-pixel values. +pub fn gray_from(w: u32, h: u32, v: Vec) -> Image { + Image { w, h, kind: Kind::Gray, data: Arc::new(v) } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn blur_keeps_mean_and_tiles() { + let img = Image::gray(32, 32, |x, y| if (x / 4 + y / 4) % 2 == 0 { 1.0 } else { 0.0 }); + for s in [1.0, 6.0] { + let b = gaussian(&img, s, true); + assert!((b.mean()[0] - img.mean()[0]).abs() < 1e-3, "sigma {s}"); + } + let flat = gaussian(&Image::filled(8, 8, Kind::Color, [0.2, 0.4, 0.6, 1.0]), 4.0, false); + assert!((flat.get(3, 3, false)[1] - 0.4).abs() < 1e-5); + } + + #[test] + fn edt_exact() { + let d = distance_sq(9, 1, |i| i == 4, false); + assert_eq!(d, vec![16.0, 9.0, 4.0, 1.0, 0.0, 1.0, 4.0, 9.0, 16.0]); + let t = distance_sq(9, 1, |i| i == 0, true); + assert_eq!(t[8], 1.0); + } + + #[test] + fn hsl_round_trip() { + let c = [0.8, 0.3, 0.1, 1.0]; + let h = rgb_to_hsl(c); + let r = hsl_to_rgb(h[0], h[1], h[2]); + for k in 0..3 { + assert!((r[k] - c[k]).abs() < 1e-5); + } + } +} diff --git a/crates/nodes/src/patterns.rs b/crates/nodes/src/patterns.rs new file mode 100644 index 00000000..e62c319f --- /dev/null +++ b/crates/nodes/src/patterns.rs @@ -0,0 +1,548 @@ +//! Texture generators › Patterns: shapes, tilings, gradients and scattered elements. + +use std::f32::consts::{PI, TAU}; + +use materialcraft_image::{Image, Kind}; + +use crate::catalog::{CookResult, Ctx, NodeDef, node}; +use crate::noise::{rand1, rand2}; + +pub const PATTERNS: &str = "Texture generators/Patterns"; + +pub const SHAPES: &[&str] = &[ + "Square", + "Disc", + "Paraboloid", + "Bell", + "Gaussian", + "Thorn", + "Pyramid", + "Brick", + "Gradation", + "Waves", + "Half bell", + "Ridged bell", + "Crescent", + "Capsule", + "Cone", + "Hexagon", +]; + +/// A shape's value at local coordinates `(x, y)` in -1..1 (1 at the center, 0 outside). +pub fn shape(kind: i32, x: f32, y: f32) -> f32 { + let r = (x * x + y * y).sqrt(); + let m = x.abs().max(y.abs()); + let v = match kind { + 0 => (m <= 1.0) as i32 as f32, + 1 => (r <= 1.0) as i32 as f32, + 2 => 1.0 - r * r, + 3 => { + let t = (1.0 - r).max(0.0); + t * t * (3.0 - 2.0 * t) + } + 4 => (-r * r * 4.0).exp() * (r <= 1.0) as i32 as f32, + 5 => (1.0 - r).max(0.0).powi(3), + 6 => 1.0 - m, + 7 => { + let bx = (1.0 - x.abs()) * 6.0; + let by = (1.0 - y.abs()) * 3.0; + bx.min(by).clamp(0.0, 1.0) + } + 8 => (x * 0.5 + 0.5) * (m <= 1.0) as i32 as f32, + 9 => (x * PI * 2.0).cos() * 0.5 + 0.5, + 10 => { + let t = (1.0 - r).max(0.0); + if y < 0.0 { 0.0 } else { t * t * (3.0 - 2.0 * t) } + } + 11 => { + let t = (1.0 - r).max(0.0); + (t * t * (3.0 - 2.0 * t)) * (1.0 - ((r * PI * 3.0).sin()).abs() * 0.4) + } + 12 => { + let r2 = ((x - 0.35) * (x - 0.35) + y * y).sqrt(); + ((r <= 1.0) && (r2 > 0.75)) as i32 as f32 + } + 13 => { + let dx = (x.abs() - 0.5).max(0.0); + let d = (dx * dx + y * y * 4.0).sqrt(); + (d <= 0.5) as i32 as f32 + } + 14 => (1.0 - r).max(0.0), + 15 => { + let (ax, ay) = (x.abs(), y.abs()); + ((ax * 0.866 + ay * 0.5).max(ay) <= 0.95) as i32 as f32 + } + _ => 0.0, + }; + v.clamp(0.0, 1.0) +} + +pub(crate) fn defs() -> Vec { + let p = |id, label| node(id, label, PATTERNS).generator(); + vec![ + p("brick_generator", "Brick Generator") + .desc("Rows of bricks with mortar gaps, bevels and random heights.") + .int("bricks_x", "Bricks X", 4, 1, 64) + .int("bricks_y", "Bricks Y", 8, 1, 64) + .float("offset", "Row offset", 0.5, 0.0, 1.0) + .float("gap", "Gap", 0.04, 0.0, 0.5) + .float("bevel", "Bevel", 0.12, 0.0, 1.0) + .float("height_random", "Height random", 0.3, 0.0, 1.0) + .float("lum_random", "Luminance random", 0.0, 0.0, 1.0) + .gray_out() + .cook(bricks), + p("checker", "Checker").desc("A checkerboard.").int("tiling", "Tiling", 4, 1, 64).gray_out().cook(checker), + p("gradient_linear_1", "Gradient Linear 1") + .desc("A ramp from black to white.") + .int("tiling", "Tiling", 1, 1, 16) + .boolean("vertical", "Vertical", false) + .gray_out() + .cook(gradient_linear_1), + p("gradient_linear_2", "Gradient Linear 2") + .desc("A mirrored ramp (white in the middle).") + .int("tiling", "Tiling", 1, 1, 16) + .boolean("vertical", "Vertical", false) + .gray_out() + .cook(gradient_linear_2), + p("gradient_radial", "Gradient Radial") + .desc("White at the center fading outward.") + .float("radius", "Radius", 0.5, 0.0, 1.0) + .gray_out() + .cook(gradient_radial), + p("hexagons", "Hexagons") + .desc("A honeycomb of beveled hexagons.") + .int("tiling", "Tiling", 4, 1, 64) + .float("size", "Size", 0.9, 0.0, 1.0) + .float("bevel", "Bevel", 0.3, 0.0, 1.0) + .gray_out() + .cook(hexagons), + p("polygon", "Polygon") + .desc("A regular polygon.") + .int("sides", "Sides", 6, 3, 32) + .float("scale", "Scale", 0.8, 0.0, 1.0) + .angle("angle", "Angle", 0.0) + .float("gradient", "Gradient", 0.0, 0.0, 1.0) + .int("tiling", "Tiling", 1, 1, 16) + .gray_out() + .cook(polygon), + p("scratches", "Scratches") + .desc("Random thin scratches.") + .int("count", "Count", 60, 0, 1000) + .float("length", "Length", 0.25, 0.0, 1.0) + .float("width", "Width", 1.0, 0.1, 8.0) + .angle("angle", "Angle", 0.1) + .float("angle_random", "Angle random", 0.2, 0.0, 1.0) + .gray_out() + .cook(scratches), + p("shape", "Shape") + .desc("A single shape, optionally tiled.") + .choice("pattern", "Pattern", SHAPES, 1) + .int("tiling", "Tiling", 1, 1, 64) + .float("size", "Size", 0.8, 0.0, 2.0) + .float2("size_xy", "Size XY", [1.0, 1.0], 0.0, 2.0) + .angle("angle", "Angle", 0.0) + .gray_out() + .cook(shape_node), + p("splatter", "Splatter") + .desc("Scattered shapes of random size and gray.") + .choice("pattern", "Pattern", SHAPES, 4) + .int("count", "Count", 64, 1, 2000) + .float("size", "Size", 0.08, 0.0, 1.0) + .float("size_random", "Size random", 0.6, 0.0, 1.0) + .float("lum_random", "Luminance random", 0.5, 0.0, 1.0) + .gray_out() + .cook(splatter), + p("star", "Star") + .desc("A star shape.") + .int("points", "Points", 5, 2, 32) + .float("inner", "Inner radius", 0.45, 0.0, 1.0) + .float("scale", "Scale", 0.8, 0.0, 1.0) + .int("tiling", "Tiling", 1, 1, 16) + .gray_out() + .cook(star), + p("stripes", "Stripes") + .desc("Parallel bands with soft edges.") + .int("count", "Count", 8, 1, 128) + .float("width", "Width", 0.5, 0.0, 1.0) + .float("softness", "Softness", 0.0, 0.0, 1.0) + .angle("angle", "Angle", 0.0) + .gray_out() + .cook(stripes), + p("tile_generator", "Tile Generator") + .desc("Places a shape on a grid with per-tile random size, position, rotation and luminance.") + .choice("pattern", "Pattern", SHAPES, 0) + .int("x_amount", "X amount", 8, 1, 128) + .int("y_amount", "Y amount", 8, 1, 128) + .float("scale", "Scale", 0.9, 0.0, 2.0) + .float2("size_xy", "Size XY", [1.0, 1.0], 0.0, 2.0) + .float("scale_random", "Scale random", 0.0, 0.0, 1.0) + .float("offset", "Row offset", 0.0, 0.0, 1.0) + .float("position_random", "Position random", 0.0, 0.0, 1.0) + .float("rotation_random", "Rotation random", 0.0, 0.0, 1.0) + .float("lum_random", "Luminance random", 0.0, 0.0, 1.0) + .float("mask_random", "Mask random", 0.0, 0.0, 1.0) + .gray_out() + .cook(tile_generator), + p("tile_sampler", "Tile Sampler") + .desc("Like Tile Generator, but each tile shows the pattern input.") + .gray_in("pattern", "Pattern input") + .gray_in("scale_map", "Scale map") + .int("x_amount", "X amount", 8, 1, 128) + .int("y_amount", "Y amount", 8, 1, 128) + .float("scale", "Scale", 1.0, 0.0, 2.0) + .float("scale_random", "Scale random", 0.0, 0.0, 1.0) + .float("offset", "Row offset", 0.0, 0.0, 1.0) + .float("position_random", "Position random", 0.0, 0.0, 1.0) + .float("rotation_random", "Rotation random", 0.0, 0.0, 1.0) + .float("lum_random", "Luminance random", 0.0, 0.0, 1.0) + .choice("blend", "Blending", &["Max", "Add"], 0) + .gray_out() + .cook(tile_sampler), + p("weave", "Weave") + .desc("Interlaced threads (height).") + .int("tiling", "Tiling", 6, 1, 64) + .float("width", "Thread width", 0.8, 0.0, 1.0) + .gray_out() + .cook(weave), + p("waveform", "Waveform") + .desc("Sine bands.") + .int("count", "Count", 8, 1, 128) + .float("amplitude", "Amplitude", 0.0, 0.0, 1.0) + .angle("angle", "Angle", 0.0) + .gray_out() + .cook(waveform), + ] +} + +/// Rotate `(x, y)` by `turns`. +#[inline] +fn rot(x: f32, y: f32, turns: f32) -> (f32, f32) { + let (s, c) = (turns * TAU).sin_cos(); + (x * c - y * s, x * s + y * c) +} + +fn bricks(ctx: &Ctx) -> CookResult { + let (bx, by) = (ctx.i("bricks_x").max(1) as f32, ctx.i("bricks_y").max(1) as f32); + let (off, gap, bevel, hr, lr, s) = (ctx.f("offset"), ctx.f("gap"), ctx.f("bevel").max(1e-4), ctx.f("height_random"), ctx.f("lum_random"), ctx.seed); + Ok(vec![ctx.gen_gray(|u, v| { + let row = (v * by).floor(); + let x = u * bx + off * row; + let col = x.floor(); + let (fx, fy) = (x - col, v * by - row); + let colw = (col as i32).rem_euclid(bx as i32); + // Distance to the brick's edge, in brick-height units. + let ex = fx.min(1.0 - fx) * by / bx; + let ey = fy.min(1.0 - fy); + let e = ex.min(ey) - gap * 0.5; + if e <= 0.0 { + return 0.0; + } + let t = (e / (bevel * 0.5)).min(1.0); + let rnd = rand2(colw, row as i32, s); + let base = 1.0 - hr * rnd; + let lum = 1.0 - lr * rand2(colw, row as i32, s ^ 99); + (t * base * lum).clamp(0.0, 1.0) + })]) +} + +fn checker(ctx: &Ctx) -> CookResult { + let n = ctx.i("tiling").max(1) as f32; + Ok(vec![ctx.gen_gray(|u, v| (((u * n).floor() + (v * n).floor()) as i32 & 1) as f32)]) +} + +fn gradient_linear_1(ctx: &Ctx) -> CookResult { + let (n, vert) = (ctx.i("tiling").max(1) as f32, ctx.b("vertical")); + Ok(vec![ctx.gen_gray(|u, v| ((if vert { v } else { u }) * n).fract())]) +} + +fn gradient_linear_2(ctx: &Ctx) -> CookResult { + let (n, vert) = (ctx.i("tiling").max(1) as f32, ctx.b("vertical")); + Ok(vec![ctx.gen_gray(|u, v| 1.0 - ((((if vert { v } else { u }) * n).fract()) * 2.0 - 1.0).abs())]) +} + +fn gradient_radial(ctx: &Ctx) -> CookResult { + let r = ctx.f("radius").max(1e-3); + Ok(vec![ctx.gen_gray(|u, v| (1.0 - ((u - 0.5).powi(2) + (v - 0.5).powi(2)).sqrt() / r).clamp(0.0, 1.0))]) +} + +fn hexagons(ctx: &Ctx) -> CookResult { + let n = ctx.i("tiling").max(1) as f32; + let (size, bevel) = (ctx.f("size"), ctx.f("bevel").max(1e-3)); + let sq3 = 3f32.sqrt(); + // Flat-top hexes of circumradius 1: two lattices, (3i, √3j) and (3i + 1.5, √3j + √3/2). The + // image holds n lattice periods across and the nearest whole number down, so it tiles. + let m = (n * 3.0 / sq3).round().max(1.0); + Ok(vec![ctx.gen_gray(|u, v| { + let (px, py) = (u * n * 3.0, v * m * sq3); + let a = ((px / 3.0).round() * 3.0, (py / sq3).round() * sq3); + let b = (((px - 1.5) / 3.0).round() * 3.0 + 1.5, ((py - sq3 * 0.5) / sq3).round() * sq3 + sq3 * 0.5); + let da = (px - a.0).powi(2) + (py - a.1).powi(2); + let db = (px - b.0).powi(2) + (py - b.1).powi(2); + let (cx, cy) = if da < db { a } else { b }; + let (dx, dy) = ((px - cx).abs(), (py - cy).abs()); + let inr = sq3 * 0.5; + let d = (dy / inr).max((dx * inr + dy * 0.5) / inr); + ((size - d) / bevel).clamp(0.0, 1.0) + })]) +} + +fn tiled(u: f32, v: f32, n: f32) -> (f32, f32) { + (((u * n).fract() - 0.5) * 2.0, ((v * n).fract() - 0.5) * 2.0) +} + +fn polygon(ctx: &Ctx) -> CookResult { + let sides = ctx.i("sides").clamp(3, 64) as f32; + let (sc, ang, grad, n) = (ctx.f("scale").max(1e-3), ctx.f("angle"), ctx.f("gradient"), ctx.i("tiling").max(1) as f32); + Ok(vec![ctx.gen_gray(|u, v| { + let (x, y) = tiled(u, v, n); + let (x, y) = rot(x, y, ang); + let a = y.atan2(x); + let seg = TAU / sides; + let d = (x * x + y * y).sqrt() * ((a.rem_euclid(seg) - seg * 0.5).cos()) / (seg * 0.5).cos(); + let e = 1.0 - d / sc; + if grad <= 0.0 { (e >= 0.0) as i32 as f32 } else { (e / grad).clamp(0.0, 1.0) } + })]) +} + +fn scratches(ctx: &Ctx) -> CookResult { + let count = ctx.i("count").clamp(0, 5000) as u32; + let (len, width, ang, ar, s) = (ctx.f("length"), ctx.f("width") / ctx.w as f32, ctx.f("angle"), ctx.f("angle_random"), ctx.seed); + let segs: Vec<([f32; 2], [f32; 2], f32)> = (0..count) + .map(|i| { + let p = [rand1(i * 4, s), rand1(i * 4 + 1, s)]; + let a = (ang + (rand1(i * 4 + 2, s) - 0.5) * ar) * TAU; + let l = len * (0.5 + 0.5 * rand1(i * 4 + 3, s)); + ([p[0], p[1]], [a.cos() * l, -a.sin() * l], 0.4 + 0.6 * rand1(i * 7 + 5, s)) + }) + .collect(); + // Bin segments by their bounding boxes on a coarse grid so each pixel tests only nearby ones. + const G: usize = 16; + let mut bins: Vec> = vec![Vec::new(); G * G]; + for (k, (p, d, _)) in segs.iter().enumerate() { + let (x0, x1) = (p[0].min(p[0] + d[0]) - width, p[0].max(p[0] + d[0]) + width); + let (y0, y1) = (p[1].min(p[1] + d[1]) - width, p[1].max(p[1] + d[1]) + width); + for gy in (y0 * G as f32).floor() as i32..=(y1 * G as f32).floor() as i32 { + for gx in (x0 * G as f32).floor() as i32..=(x1 * G as f32).floor() as i32 { + if let Some(b) = bins.get_mut(gy.rem_euclid(G as i32) as usize * G + gx.rem_euclid(G as i32) as usize) { + b.push(k); + } + } + } + } + Ok(vec![ctx.gen_gray(|u, v| { + let bin = &bins[((v * G as f32) as usize).min(G - 1) * G + ((u * G as f32) as usize).min(G - 1)]; + let mut best: f32 = 0.0; + for k in bin { + let (p, d, lum) = segs[*k]; + for (ox, oy) in [(0.0, 0.0), (1.0, 0.0), (-1.0, 0.0), (0.0, 1.0), (0.0, -1.0)] { + let (qx, qy) = (u - p[0] + ox, v - p[1] + oy); + let t = ((qx * d[0] + qy * d[1]) / (d[0] * d[0] + d[1] * d[1]).max(1e-9)).clamp(0.0, 1.0); + let (ex, ey) = (qx - d[0] * t, qy - d[1] * t); + let dist = (ex * ex + ey * ey).sqrt(); + if dist < width { + best = best.max((1.0 - dist / width) * lum * (1.0 - (t * 2.0 - 1.0).abs().powi(4))); + } + } + } + best + })]) +} + +fn shape_node(ctx: &Ctx) -> CookResult { + let (k, n, size, sxy, ang) = (ctx.i("pattern"), ctx.i("tiling").max(1) as f32, ctx.f("size").max(1e-3), ctx.v2("size_xy"), ctx.f("angle")); + Ok(vec![ctx.gen_gray(|u, v| { + let (x, y) = tiled(u, v, n); + let (x, y) = rot(x, y, ang); + shape(k, x / (size * sxy[0].max(1e-3)), y / (size * sxy[1].max(1e-3))) + })]) +} + +fn splatter(ctx: &Ctx) -> CookResult { + let count = ctx.i("count").clamp(1, 20000) as u32; + let (k, size, sr, lr, s) = (ctx.i("pattern"), ctx.f("size"), ctx.f("size_random"), ctx.f("lum_random"), ctx.seed); + let items: Vec<([f32; 2], f32, f32, f32)> = (0..count) + .map(|i| ([rand1(i * 5, s), rand1(i * 5 + 1, s)], size * (1.0 - sr * rand1(i * 5 + 2, s)), 1.0 - lr * rand1(i * 5 + 3, s), rand1(i * 5 + 4, s))) + .collect(); + let base = Image::filled(ctx.w, ctx.h, Kind::Gray, [0.0; 4]); + Ok(vec![stamp(ctx, base, &items, |x, y, _| shape(k, x, y), |a, b| a.max(b))]) +} + +/// Splat `items` (center, radius, luminance, rotation turns) onto `base` with `f` combining. +fn stamp( + ctx: &Ctx, + base: Image, + items: &[([f32; 2], f32, f32, f32)], + sh: impl Fn(f32, f32, usize) -> f32 + Sync, + combine: impl Fn(f32, f32) -> f32 + Sync, +) -> Image { + const G: usize = 32; + let mut bins: Vec> = vec![Vec::new(); G * G]; + for (i, (c, r, _, _)) in items.iter().enumerate() { + let r = r * 1.42; + for gy in ((c[1] - r) * G as f32).floor() as i32..=((c[1] + r) * G as f32).floor() as i32 { + for gx in ((c[0] - r) * G as f32).floor() as i32..=((c[0] + r) * G as f32).floor() as i32 { + if let Some(b) = bins.get_mut(gy.rem_euclid(G as i32) as usize * G + gx.rem_euclid(G as i32) as usize) + && !b.contains(&i) + { + b.push(i); + } + } + } + } + let tile = ctx.tile; + Image::generate_uv(ctx.w, ctx.h, Kind::Gray, |u, v| { + let mut acc = base.sample_nearest(u, v, false)[0]; + let bin = &bins[((v * G as f32) as usize).min(G - 1) * G + ((u * G as f32) as usize).min(G - 1)]; + for i in bin { + let (c, r, lum, rt) = items[*i]; + if r <= 0.0 { + continue; + } + let mut dx = u - c[0]; + let mut dy = v - c[1]; + if tile { + dx -= dx.round(); + dy -= dy.round(); + } + let (x, y) = rot(dx / r, dy / r, rt); + if x.abs() <= 1.0 && y.abs() <= 1.0 { + acc = combine(acc, sh(x, y, *i) * lum); + } + } + [acc, 0.0, 0.0, 0.0] + }) +} + +fn star(ctx: &Ctx) -> CookResult { + let pts = ctx.i("points").clamp(2, 64) as f32; + let (inner, sc, n) = (ctx.f("inner"), ctx.f("scale").max(1e-3), ctx.i("tiling").max(1) as f32); + Ok(vec![ctx.gen_gray(|u, v| { + let (x, y) = tiled(u, v, n); + let a = y.atan2(x) + PI / 2.0; + let seg = TAU / pts; + let t = ((a.rem_euclid(seg) / seg) * 2.0 - 1.0).abs(); + let rad = sc * (inner + (1.0 - inner) * t); + ((x * x + y * y).sqrt() <= rad) as i32 as f32 + })]) +} + +fn stripes(ctx: &Ctx) -> CookResult { + let n = ctx.i("count").max(1) as f32; + let (w, soft, ang) = (ctx.f("width"), ctx.f("softness").max(1e-3), ctx.f("angle")); + Ok(vec![ctx.gen_gray(|u, v| { + let (x, _) = rot(u - 0.5, v - 0.5, ang); + let f = (x * n).rem_euclid(1.0); + let d = (f - 0.5).abs() * 2.0; + ((w - d) / soft + 0.5).clamp(0.0, 1.0) + })]) +} + +fn tile_params(ctx: &Ctx) -> (f32, f32, f32, f32, f32, f32, f32, f32, u32) { + ( + ctx.i("x_amount").max(1) as f32, + ctx.i("y_amount").max(1) as f32, + ctx.f("scale"), + ctx.f("scale_random"), + ctx.f("offset"), + ctx.f("position_random"), + ctx.f("rotation_random"), + ctx.f("lum_random"), + ctx.seed, + ) +} + +fn tile_generator(ctx: &Ctx) -> CookResult { + let (nx, ny, sc, sr, off, pr, rr, lr, s) = tile_params(ctx); + let (k, sxy, mr) = (ctx.i("pattern"), ctx.v2("size_xy"), ctx.f("mask_random")); + Ok(vec![ctx.gen_gray(|u, v| { + let row = (v * ny).floor(); + let mut best: f32 = 0.0; + // Shapes may reach into neighbouring cells (scale > 1, position jitter): check 3×3. + for dj in -1..=1 { + for di in -1..=1 { + let r = row + dj as f32; + let x = u * nx + off * r; + let col = x.floor() + di as f32; + let (ci, ri) = ((col as i32).rem_euclid(nx as i32), (r as i32).rem_euclid(ny as i32)); + if mr > 0.0 && rand2(ci, ri, s ^ 0x55) < mr { + continue; + } + let jx = (rand2(ci, ri, s ^ 1) - 0.5) * pr; + let jy = (rand2(ci, ri, s ^ 2) - 0.5) * pr; + let size = sc * (1.0 - sr * rand2(ci, ri, s ^ 3)); + if size <= 0.0 { + continue; + } + let (lx, ly) = ((x - col - 0.5 - jx) * 2.0, (v * ny - r - 0.5 - jy) * 2.0); + let (lx, ly) = rot(lx, ly, (rand2(ci, ri, s ^ 4) - 0.5) * rr); + let val = shape(k, lx / (size * sxy[0].max(1e-3)), ly / (size * sxy[1].max(1e-3))); + best = best.max(val * (1.0 - lr * rand2(ci, ri, s ^ 5))); + } + } + best + })]) +} + +fn tile_sampler(ctx: &Ctx) -> CookResult { + let (nx, ny, sc, sr, off, pr, rr, lr, s) = tile_params(ctx); + let pattern = + ctx.input(0).map(|p| p.to_gray()).unwrap_or_else(|| Image::generate_uv(64, 64, Kind::Gray, |u, v| [shape(3, u * 2.0 - 1.0, v * 2.0 - 1.0); 4])); + let smap = ctx.input(1).map(|p| p.to_gray()); + let add = ctx.i("blend") == 1; + Ok(vec![ctx.gen_gray(|u, v| { + let row = (v * ny).floor(); + let mut acc: f32 = 0.0; + for dj in -1..=1 { + for di in -1..=1 { + let r = row + dj as f32; + let x = u * nx + off * r; + let col = x.floor() + di as f32; + let (ci, ri) = ((col as i32).rem_euclid(nx as i32), (r as i32).rem_euclid(ny as i32)); + let jx = (rand2(ci, ri, s ^ 1) - 0.5) * pr; + let jy = (rand2(ci, ri, s ^ 2) - 0.5) * pr; + let mapk = smap.as_ref().map_or(1.0, |m| m.sample_gray((col + 0.5) / nx, (r + 0.5) / ny, true)); + let size = sc * mapk * (1.0 - sr * rand2(ci, ri, s ^ 3)); + if size <= 0.0 { + continue; + } + let (lx, ly) = ((x - col - 0.5 - jx) / size, (v * ny - r - 0.5 - jy) / size); + let (lx, ly) = rot(lx, ly, (rand2(ci, ri, s ^ 4) - 0.5) * rr); + if lx.abs() > 0.5 || ly.abs() > 0.5 { + continue; + } + let val = pattern.sample_gray(lx + 0.5, ly + 0.5, false) * (1.0 - lr * rand2(ci, ri, s ^ 5)); + acc = if add { acc + val } else { acc.max(val) }; + } + } + acc.min(1.0) + })]) +} + +fn weave(ctx: &Ctx) -> CookResult { + let n = ctx.i("tiling").max(1) as f32; + let w = ctx.f("width").clamp(0.01, 1.0); + Ok(vec![ctx.gen_gray(|u, v| { + let (x, y) = (u * n, v * n); + let (cx, cy) = (x.floor() as i32, y.floor() as i32); + let (fx, fy) = (x.fract(), y.fract()); + // Horizontal thread across the cell row, vertical thread down the column; which is on + // top alternates in a checker. + let hthread = ((fy - 0.5).abs() * 2.0 <= w) as i32 as f32 * (1.0 - ((fy - 0.5) * 2.0 / w).powi(2)).max(0.0).sqrt(); + let vthread = ((fx - 0.5).abs() * 2.0 <= w) as i32 as f32 * (1.0 - ((fx - 0.5) * 2.0 / w).powi(2)).max(0.0).sqrt(); + let h_top = (cx + cy) & 1 == 0; + // The thread on top bulges along its length. + let hb = hthread * (0.6 + 0.4 * (fx * PI).sin()); + let vb = vthread * (0.6 + 0.4 * (fy * PI).sin()); + if h_top { hb.max(vb * 0.6) } else { vb.max(hb * 0.6) } + })]) +} + +fn waveform(ctx: &Ctx) -> CookResult { + let n = ctx.i("count").max(1) as f32; + let (amp, ang) = (ctx.f("amplitude"), ctx.f("angle")); + Ok(vec![ctx.gen_gray(|u, v| { + let (x, y) = rot(u - 0.5, v - 0.5, ang); + let w = (y * TAU * 2.0).sin() * amp * 0.1; + ((x + w) * TAU * n).sin() * 0.5 + 0.5 + })]) +} diff --git a/docs/brand/LICENSE-brand.txt b/docs/brand/LICENSE-brand.txt new file mode 100644 index 00000000..8ee1614b --- /dev/null +++ b/docs/brand/LICENSE-brand.txt @@ -0,0 +1,42 @@ +ArtCraft brand assets: license + +The ArtCraft name, wordmark and mark (the "ArtCraft Marks"), including every file in this +directory in every color, size and format, are owned by the ArtCraft Team. They are trademarks +and are NOT open source. They are not covered by MaterialCraft's MIT OR Apache-2.0 license, and nothing in +that license, in NOTICE or in any other file of this repository grants any right to them. + +Permission + +The ArtCraft Team grants a limited, non-exclusive, non-transferable, revocable, royalty-free +permission to use the ArtCraft Marks only: + + 1. as part of copies of this repository; and + 2. within MaterialCraft itself, its documentation and its official builds, to identify MaterialCraft as made + by the ArtCraft team and community and to link to getartcraft.com and its community. + +Conditions + +The permission holds only while every one of these is true: + + - The marks are used exactly as supplied in this directory. Do not redraw, recolor, crop, + stretch, rotate, animate, outline or add effects to them, extract parts of them, or combine + them with any other name, mark or artwork. + - They are used only in the context of MaterialCraft, and only to say that the ArtCraft team makes it. + They must never suggest that the ArtCraft Team made, sponsors, endorses, certifies or supports + any other product, service, fork, modified version, plug-in, organization or person. + - Neither the marks nor the ArtCraft name appear in the name, logo, icon, domain, social media + handle, app-store listing, advertising or marketing of anything other than MaterialCraft. + +Forks and modified versions + +If you distribute or publish a modified version of MaterialCraft, or any work derived from it, you must +remove the ArtCraft Marks from it (or replace them with your own) and must not call it ArtCraft or +present it as an ArtCraft product. You may say, in plain text, that your work is based on MaterialCraft by +the ArtCraft team. A fork kept only to propose changes back to this repository may keep the marks +unchanged. + +Everything else + +Any use not expressly permitted here needs prior written permission from the ArtCraft Team +(https://getartcraft.com/). The permission ends automatically for anyone who breaks these terms. +All other rights are reserved. diff --git a/docs/brand/artcraft-logo-white.png b/docs/brand/artcraft-logo-white.png new file mode 100644 index 0000000000000000000000000000000000000000..8cfb31d940f6663ecaf93da2bc04c5904704b4af GIT binary patch literal 32161 zcmagGcOVsP_&W||;D3K#K`{Scf5nFX|NOd=ll-r9AB~Uy96i`{lWv^HSxyfg%x-(O z&m`6g<9E-#mD!#;F#dc;?@L%mkh7cHtj~WN+V@}Z_-z&bA3o* zCmQugTzl>-ORKb*c-Z&U`tvG$_*>}nSyR(GThk|<9389a{w<;is7QZ6rzn)VPp}VW zZ_T2va;S0sj>C7-f`hP^9Xa7;Q?Qcf1fX)pi(6NDUW;l=X_Murm<kP<{UK;)woTcCfxusE2KQ-IGA+b+p2($Cuh<1Q}BPsPM zh1UJHPhjrsW^2Z`bJN4@g~{5Ev}!qq$Se0*o6K=vBa?o8dC9iiwF+|bN{&(!q#x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ZTK(U=pkW~;RrdKv1QAk z-X~d7RoxjvL!04Y`9JC1+kjU~|vB zBg=|-p{|^hbo>VvC9{jmuWYmEWp%M;{EA0I(1ZXc)b@`d-4PSU<~W+T>M}3(DpSve z?1I3_$ce`8#33329k`RIvB@hP?6zp0wLzO_`7JfN>S7XwK%bNdCRsVI!n=;RL)`1c`v|PRWDp_yiMmhqNWrj!V{Z>;W!K-HKGWQCWzvx z<4w%3H$27CVDV8&~;QB=KsyC>U98N}_E!|w}a60a)z(OnD$f6Rs!S~pQ=Bto@*rt~c zcY4S5{n{eigm9xsoC2TTym$05_A?B1djkp`R1^H=nd~$d4HnDWS06?uM;mXi4bMy= zc_#{q$t;tnTVgndl{v&DypbY>e#P#=r}5Y4U7*MWZ}RQaeM?%|eJ@%)6;n^!dRupC z8SI=9;}Gy0*Nl$xRSgR|ps=wvCw$t>1TgLuT$HA8{nt>mV6DV5?LN42AduVu-WPs{I z^X(_Juh!jLxEHn*=-of#%btlBx<4ALIb-wv-)Fe~eWvQ9>fwf+MwW%F54M++*DdE# z4;aC>an(d?kMnJAe5~Z(iDhF!uMT972oU^%9}=n5>w)yf+W4aTX{+tiWt;B%okEXr zd(MmQsaC8$kurBexawfyTGlO(^|uwS8QQluhnvZYeP|YpejF}f`R{%I{uNm=f>{3l tf56#M-sj)H5EK5_7m~~V-~M~UhsPu0=Yf5}`_KzsRMS3}sX}=8{{T + ArtCraft + + + + + diff --git a/docs/brand/artcraft-logo.png b/docs/brand/artcraft-logo.png new file mode 100644 index 0000000000000000000000000000000000000000..a4d1544caa4c8b8dae14e1d10d79afa197261e3b GIT binary patch literal 31302 zcmYg&c|6qL_x~M(A&inJ*(#B;wAgn^!h6tEh%l|lnl)pas8kYV;vGUUmXL|;+eqGe zlO^kvJv8=xU&imwc>lhSk3V`?a$om#?m5qM&htF4r)DMwJiCN;0RVUmFPy^yz)b)E zf#G0>-}!QMsTBY`kKsAp%l8u|d#Ajuy9$&hOLPVVL6{rc_2V3-@Sl@OyS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l-*4&!h;{W$nml$-)X3(d&NuJS+Y z>mqUKGQegtxo9^adFh64 ew&(x%&)c}D8%*^he-v=&6Y45j7qZXe1OE?JG~1&9 literal 0 HcmV?d00001 diff --git a/docs/brand/artcraft-logo.svg b/docs/brand/artcraft-logo.svg new file mode 100644 index 00000000..d63f3eae --- /dev/null +++ b/docs/brand/artcraft-logo.svg @@ -0,0 +1,7 @@ + + ArtCraft + + + + + diff --git a/docs/brand/artcraft-mark-black.png b/docs/brand/artcraft-mark-black.png new file mode 100644 index 0000000000000000000000000000000000000000..27664bc119d2b485ba6fee213ee749df658ab508 GIT binary patch literal 26793 zcmeFZ`9D;e z-K8wa5@jzWWZ#FG^SRDUckl1x^Cx^CpI_cfX3m`Ry0+)_yq?#&W^AZ0A}A?{5E3ys zu+J1BUihE9Xc0gB7j>86)#o0IJ5L_w+igj_>!Ee%n8%j91luxUf=;9`O~c>w z(sN#02eC14ua6@$I!nIYP&PdE?S5G^JEzc=0KeO4FAx7oYcYfWL^OWm|My@2?+E^% z7ySP}5L^V1*KzgL5&IqZj05#dbOz3qit^AzEqLLdgM<5?<|%jz` zxV5!)p1=?=K`5neA9lRAT?px3l|V@H&?IT#L4zyyeR6Wr8jTt*M@S{+C%N&BS3t-r z^fDH|%-uAs+k5UPD*V)6;CVkOX`KM_ER;Z>lr)*iYM4=dMGbP>a3O=ddWk?J53Q)4 zh$!7x*?U=HdJ9@BXNa^SNU2CH*^fpyc@R*_G+b@}*Y>tHjn%^Z zwM5!hIGD^`bySy_$qV!qXyGamp+e^YvWk)QJNESSbO=(?6M}!*!W6AJD)x{1D&ci} zs51)g>-j$HL5Yvx`p*dNbYv?+#)ncd20XnOI$x_wLyd+v*%=MkN<-|TVaA1SI3^9G z#Di!|*CK7|!2~RUpki-*^ZF~t(Pl&;B3jUgI&7?XK@M#c%^N7vkX&Uo35m5;6ZKWwvK&g-7u1!mbDc`CQa_qgw z6n*L7-8SOy$xFdaojbk{yEs#NfN)?jA>t82jDss!0=niw7H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aOApLP2j94szS0vW3Lo#Rr^ zmw3P)cH4K_;P95fJ5=joIx*%yvl=UrmE3=*sf|OVOtP&~r|=WI8n3btneTD8Jx$_2 zXSR!-OyQaj(&DHUUjoLZ@%>&@dAC`mu3!}(ZT)5ccm!8qAi|jnXgbqSJ3855+0arQ zU!6MVe>pBlBsP$C1cT%fiS`6)#RJ|j0}hts=NAW3jSBtxjF8FUJ#77RHWUZQ>jh-F zHW3jgP!bvKe7#puWCUh{NkMhhX1@{xz4S(p`m!O>A#MbuNR`q3a2E)BJ&y>|f#S^n z($dB7T_HoYdnlFMPzLi@EK(|gae)BH-j0z$3tNso?Zz9RPO*2dyca_MT6R%mf~I;K zg|44icB?f?8h^`(!lW#B>M<1z^WjTS1|;Dz67E-o7$kl~#9vP=#J?|A$B+L!@y|!{ e&&}|E4FfI_y3)`krUrPI@WZsQ-d?nobN+v7Axq-` literal 0 HcmV?d00001 diff --git a/docs/brand/artcraft-mark-black.svg b/docs/brand/artcraft-mark-black.svg new file mode 100644 index 00000000..63943537 --- /dev/null +++ b/docs/brand/artcraft-mark-black.svg @@ -0,0 +1,4 @@ + + ArtCraft + + diff --git a/docs/brand/artcraft-mark.png b/docs/brand/artcraft-mark.png new file mode 100644 index 0000000000000000000000000000000000000000..dbb3dc08955f8214561c7922730e78266600aa36 GIT binary patch literal 24715 zcmeFZ=R;HJ);@eEp-NM60I51Cih!U}q$XHEML?0>)uVu*AiYWASa3vOREknFBZ$%! zL{uPg5E}v!q*y456e-fBCE4%VLC^F2{)6|!^Wlt#>~`;UuX3%muC@O>U}Y}0Om-PU zNNn$(T{Z~u!T;q$LIUs)RYC0>LY_8zcbVFTXN+{Zh1#}1(jD>I>~LCkRBG3$rxwo3 zKN0Sf(*i{fBwQ8jJN!-N6LFV_4U5n#)ltsO;aAeneeE0Ln{xibv+VOjUL4nUnMJ#6 znN{ykA81XReVpxOPk_fvyZ;9NrHl!~e~~9|0Z0oG@xNpcegYDu;r~Sf6y86iHTXX? z!gBl{C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V(jQ&ZE+WTF;b3CJupeuTTV<29ZjFZ6#_|x+WWX zQ$yJ$FI03O=gf9vEGy*u$w@ zAcDSLs3~(%8E`Eq`LcQT6a6h1H;wHx2Yi9r8h&Pk5j<{AzB4rBi#M8$`Xw3ni7O_E zGfh3jHp_Oi!oJG}$n|O{tEeM@Ni?M{7f4mKb9DIC_tRJq(7GnOoDJ988OXjsv`Ssl zSxt&%z?9zNck0+C?3c}XK#(@WCbdxt69&cV76(Sgn&Fc-_aKR_n`@5-uX=V zM_szGd9epZFz7f*z-mH{20k5k<*;+w<-0)(qM=biXR4fv@;ZucFup1*<2S?Yp!(rT zcAGj^k|T6>Jf6s*vL{)`$3+C=_kiL42m)-4^xG7D9A)qEuIwF3o4$JZ{~eF z$09v9UkinnI7#wi7!(Z-rzY$LOK>$t5#rj_bVQ`<_b6Bl1-8$0_W{_bmH3H~fS{a1 z$e7cAdDhuSS@~wFCCMd+OQg2DESPz0_cH#B9isU1@+1;Fb2?ytejqm4wBz8rIOhIF z&QqP86bEMP_kKe)eR#Uz7=s7ZF3(9ctGB*BmyG-ehlE6U}8_SxutM1q|3WfsOJ~JfB#lB3Q5k104*I@PF8a}RHise>o`elTG zwn{N=#nhe{S7Oo@Iy8m9K9jZTx^Q6LTz;=6mlSM}QwpZ)`x Cm;%NC literal 0 HcmV?d00001 diff --git a/docs/brand/artcraft-mark.svg b/docs/brand/artcraft-mark.svg new file mode 100644 index 00000000..72e191f8 --- /dev/null +++ b/docs/brand/artcraft-mark.svg @@ -0,0 +1,4 @@ + + ArtCraft + + diff --git a/packaging/.shellcheckrc b/packaging/.shellcheckrc new file mode 100644 index 00000000..36c19d06 --- /dev/null +++ b/packaging/.shellcheckrc @@ -0,0 +1,3 @@ +# shellcheck config for the packaging scripts (CI: .github/workflows/packaging-lint.yml). +source-path=SCRIPTDIR +external-sources=true diff --git a/packaging/env.sh b/packaging/env.sh new file mode 100644 index 00000000..3705c48c --- /dev/null +++ b/packaging/env.sh @@ -0,0 +1,59 @@ +# shellcheck shell=bash +# Shared setup for the packaging scripts. Source it: `. "$(dirname "$0")/../env.sh"`. +# +# Exports: +# ROOT workspace root +# VERSION [workspace.package] version from Cargo.toml (override: MATERIALCRAFT_VERSION) +# DIST output directory for release artifacts (default: $ROOT/dist/release) +# MATERIALCRAFT_BUILD_SHA git commit baked into the binaries (apps/materialcraft/build.rs) +# MATERIALCRAFT_BUILD_DATE UTC build date, YYYY-MM-DD +# CARGO_TARGET_DIR cargo's target dir (default: $ROOT/target) + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +export ROOT + +# The version lives in exactly one place: `[workspace.package] version` in the root Cargo.toml. +# (`cargo xtask version` prints the same thing; awk avoids compiling xtask here.) +workspace_version() { + awk ' + /^\[/ { in_pkg = ($0 == "[workspace.package]") ; next } + in_pkg && $1 == "version" { gsub(/[" ]/, "", $3); print $3; exit } + ' "$ROOT/Cargo.toml" +} + +VERSION="${MATERIALCRAFT_VERSION:-$(workspace_version)}" +if [ -z "$VERSION" ]; then + echo "error: could not read [workspace.package] version from $ROOT/Cargo.toml" >&2 + exit 1 +fi +export VERSION + +DIST="${DIST:-$ROOT/dist/release}" +mkdir -p "$DIST" +export DIST + +if [ -z "${MATERIALCRAFT_BUILD_SHA:-}" ]; then + MATERIALCRAFT_BUILD_SHA="$(git -C "$ROOT" rev-parse HEAD 2>/dev/null || true)" +fi +export MATERIALCRAFT_BUILD_SHA +export MATERIALCRAFT_BUILD_DATE="${MATERIALCRAFT_BUILD_DATE:-$(date -u +%Y-%m-%d)}" +export CARGO_TARGET_DIR="${CARGO_TARGET_DIR:-$ROOT/target}" + +# Emit a GitHub Actions warning (plain stderr outside Actions). +warn() { + if [ -n "${GITHUB_ACTIONS:-}" ]; then echo "::warning::$*"; else echo "warning: $*" >&2; fi +} + +# Copy licence, notice and readme files that exist into a package directory. +copy_docs() { + local dest="$1" f + for f in README.md LICENSE-MIT LICENSE-APACHE NOTICE ATTRIBUTION.md; do + if [ -f "$ROOT/$f" ]; then cp "$ROOT/$f" "$dest/"; fi + done + # Licences of the craft-fonts faces crates/ui-egui/build.rs embeds (release builds set CRAFT_FONTS_DIR). + if [ -n "${CRAFT_FONTS_DIR:-}" ]; then + for f in biz-ud-pgothic noto-sans-cjk-sc; do + if [ -f "$CRAFT_FONTS_DIR/fonts/$f/OFL.txt" ]; then cp "$CRAFT_FONTS_DIR/fonts/$f/OFL.txt" "$dest/OFL-$f.txt"; fi + done + fi +} diff --git a/packaging/freebsd/package.sh b/packaging/freebsd/package.sh new file mode 100644 index 00000000..9a2ef130 --- /dev/null +++ b/packaging/freebsd/package.sh @@ -0,0 +1,110 @@ +#!/usr/bin/env bash +# Build and package MaterialCraft for FreeBSD: +# +# $DIST/materialcraft--freebsd-x86_64.tar.gz a /usr/local-style tree: +# materialcraft--freebsd-x86_64/{bin, share/applications, share/icons, share/mime, +# share/metainfo, share/doc/materialcraft} +# +# Install by copying the tree's contents into /usr/local: +# tar -xzf materialcraft--freebsd-x86_64.tar.gz --strip-components 1 -C /usr/local +# +# Usage: packaging/freebsd/package.sh [--skip-build] [--dry-run] +# --dry-run stage the tree from stub binaries and list it, without building (works on any OS) +# +# Needs: bash, cargo, and the packages installed in .github/workflows/freebsd.yml. +set -euo pipefail +# shellcheck source=../env.sh +. "$(dirname "${BASH_SOURCE[0]}")/../env.sh" +LINUX="$ROOT/packaging/linux" +APP_ID=ai.storyteller.materialcraft + +SKIP_BUILD=0 +DRY_RUN=0 +while [ $# -gt 0 ]; do + case "$1" in + --skip-build) SKIP_BUILD=1; shift ;; + --dry-run) DRY_RUN=1; SKIP_BUILD=1; shift ;; + -h | --help) sed -n '2,15p' "$0"; exit 0 ;; + *) echo "unknown argument: $1" >&2; exit 2 ;; + esac +done + +# FreeBSD's uname says amd64; release file names use x86_64 like the Linux and Windows ones. +MACHINE="$(uname -m)" +case "$MACHINE" in + amd64 | x86_64) HOST_ARCH=x86_64 ;; + arm64 | aarch64) HOST_ARCH=aarch64 ;; + *) echo "unsupported architecture $MACHINE" >&2; exit 2 ;; +esac +ARCH="$HOST_ARCH" +if [ -n "${CARGO_BUILD_TARGET:-}" ]; then + case "$CARGO_BUILD_TARGET" in + aarch64-unknown-freebsd) ARCH=aarch64 ;; + x86_64-unknown-freebsd) ARCH=x86_64 ;; + *) echo "error: unsupported FreeBSD target $CARGO_BUILD_TARGET" >&2; exit 2 ;; + esac +fi +if [ "$DRY_RUN" = 0 ] && [ "$(uname -s)" != FreeBSD ]; then + echo "error: build on FreeBSD (or pass --dry-run to check the tree layout)" >&2 + exit 2 +fi +BASENAME="materialcraft-$VERSION-freebsd-$ARCH" + +echo "==> MaterialCraft $VERSION for FreeBSD $ARCH" + +# The release VM has 12 GB; full parallelism on the biggest crates runs it out of memory. +export CARGO_BUILD_JOBS="${CARGO_BUILD_JOBS:-4}" +if [ "$SKIP_BUILD" = 0 ]; then + (cd "$ROOT" && cargo build --release --locked -p materialcraft -p materialcraft-cli) +fi +WORK="$CARGO_TARGET_DIR/freebsd-package" +STAGE="$WORK/$BASENAME" +rm -rf "$WORK" +mkdir -p "$WORK" + +BIN="$CARGO_TARGET_DIR/${CARGO_BUILD_TARGET:+$CARGO_BUILD_TARGET/}release" +OUT_DIR="$DIST" +if [ "$DRY_RUN" = 1 ]; then + # Stub binaries, and the tarball stays in the work dir so dist/ only ever holds real builds. + BIN="$WORK/stub-bin" + OUT_DIR="$WORK" + mkdir -p "$BIN" + for b in materialcraft materialcraft-cli; do + printf '#!/bin/sh\necho "%s %s (dry-run stub)"\n' "$b" "$VERSION" >"$BIN/$b" + chmod 755 "$BIN/$b" + done +fi + +# ---- stage a /usr/local-style tree -------------------------------------------------------------- +# FreeBSD's install(1) has no -D: create the directories first. +mkdir -p "$STAGE/bin" "$STAGE/share/applications" "$STAGE/share/mime/packages" \ + "$STAGE/share/metainfo" "$STAGE/share/icons" "$STAGE/share/doc/materialcraft" +install -m 755 "$BIN/materialcraft" "$BIN/materialcraft-cli" "$STAGE/bin/" +strip "$STAGE/bin/materialcraft" "$STAGE/bin/materialcraft-cli" 2>/dev/null || true +# The desktop entry, MIME type, metainfo and icons are the freedesktop files Linux ships. +install -m 644 "$LINUX/$APP_ID.desktop" "$STAGE/share/applications/$APP_ID.desktop" +install -m 644 "$LINUX/$APP_ID.mime.xml" "$STAGE/share/mime/packages/$APP_ID.xml" +sed -e "s/@VERSION@/$VERSION/g" -e "s/@DATE@/$MATERIALCRAFT_BUILD_DATE/g" \ + "$LINUX/$APP_ID.metainfo.xml.in" >"$STAGE/share/metainfo/$APP_ID.metainfo.xml" +cp -R "$ROOT/assets/app-icon/hicolor" "$STAGE/share/icons/" +copy_docs "$STAGE/share/doc/materialcraft" + +for f in bin/materialcraft bin/materialcraft-cli "share/applications/$APP_ID.desktop" \ + "share/icons/hicolor/256x256/apps/$APP_ID.png" "share/icons/hicolor/scalable/apps/$APP_ID.svg" \ + share/doc/materialcraft/LICENSE-MIT share/doc/materialcraft/LICENSE-APACHE; do + if [ ! -e "$STAGE/$f" ]; then echo "error: $f is missing from the package" >&2; exit 1; fi +done + +# ---- .tar.gz ------------------------------------------------------------------------------------ +mkdir -p "$OUT_DIR" +tar -C "$WORK" -czf "$OUT_DIR/$BASENAME.tar.gz" "$BASENAME" +echo "wrote $OUT_DIR/$BASENAME.tar.gz" + +if [ -z "${CARGO_BUILD_TARGET:-}" ] || [ "$DRY_RUN" = 1 ]; then + "$STAGE/bin/materialcraft-cli" --version +fi +if [ "$DRY_RUN" = 1 ]; then + echo "==> dry run: tarball contents" + tar -tzvf "$OUT_DIR/$BASENAME.tar.gz" +fi +echo "==> done" diff --git a/packaging/icons.sh b/packaging/icons.sh new file mode 100644 index 00000000..3e058c84 --- /dev/null +++ b/packaging/icons.sh @@ -0,0 +1,54 @@ +#!/usr/bin/env bash +# Regenerate every app icon from assets/app-icon/materialcraft.svg (the canonical artwork). +# +# Needs: resvg (cargo install resvg / brew install resvg) and cargo (for `cargo xtask ico|icns`). +# The outputs are committed, so packaging never needs these tools. +# +# packaging/icons.sh +set -euo pipefail +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +DIR="$ROOT/assets/app-icon" +SVG="$DIR/materialcraft.svg" +ID=ai.storyteller.materialcraft +TMP="$(mktemp -d)" +trap 'rm -rf "$TMP"' EXIT + +command -v resvg >/dev/null || { echo "error: resvg not found (cargo install resvg)" >&2; exit 1; } + +# The SVG is a full-bleed 512 tile, used as-is on Windows and Linux. macOS icons follow Apple's grid: +# the tile is 824/1024 of the canvas with a transparent margin, so widen the viewBox around it. +MAC="$TMP/mac.svg" +sed 's/viewBox="0 0 512 512"/viewBox="-62.136 -62.136 636.272 636.272"/' "$SVG" >"$MAC" +grep -q 'viewBox="-62.136' "$MAC" || { echo "error: $SVG has no 512 viewBox" >&2; exit 1; } + +render() { resvg -w "$2" -h "$2" "$1" "$3" /dev/null || return 0 + tmp="$apps/.$DESK_ID.tmp.$$" + esc="$(printf '%s' "$appimage" | sed 's/[\\&|]/\\&/g')" + if sed -e "s|^Exec=.*|Exec=\"$esc\" %F|" -e '/^TryExec=/d' "$src_desktop" 2>/dev/null >"$tmp"; then + if cmp -s "$tmp" "$apps/$DESK_ID.desktop"; then + rm -f "$tmp" + else + if mv -f "$tmp" "$apps/$DESK_ID.desktop" 2>/dev/null; then + command -v update-desktop-database >/dev/null 2>&1 && update-desktop-database "$apps" >/dev/null 2>&1 + else + rm -f "$tmp" + fi + fi + else + rm -f "$tmp" + return 0 + fi + + # Icons: per-file compare so an unchanged install costs a handful of cmp calls. + src_icons="$APPDIR/usr/share/icons/hicolor" + [ -d "$src_icons" ] || return 0 + icons="$data/icons/hicolor" + (cd "$src_icons" && find . -type f) | while IFS= read -r rel; do + mkdir -p "$icons/$(dirname "$rel")" 2>/dev/null || continue + if ! cmp -s "$src_icons/$rel" "$icons/$rel"; then + cp "$src_icons/$rel" "$icons/$rel" 2>/dev/null || true + fi + done +} + +integrate +exec "$APPDIR/usr/bin/materialcraft" "$@" diff --git a/packaging/linux/ai.storyteller.materialcraft.desktop b/packaging/linux/ai.storyteller.materialcraft.desktop new file mode 100644 index 00000000..71a8934f --- /dev/null +++ b/packaging/linux/ai.storyteller.materialcraft.desktop @@ -0,0 +1,14 @@ +[Desktop Entry] +Type=Application +Name=MaterialCraft +GenericName=Procedural Material Designer +Comment=Design procedural PBR materials with node graphs +Exec=materialcraft %F +TryExec=materialcraft +Icon=ai.storyteller.materialcraft +Terminal=false +StartupNotify=true +StartupWMClass=materialcraft +Categories=Graphics;3DGraphics; +Keywords=material;procedural;node;graph;pbr;texture;noise;3d; +MimeType=application/x-materialcraft; diff --git a/packaging/linux/ai.storyteller.materialcraft.metainfo.xml.in b/packaging/linux/ai.storyteller.materialcraft.metainfo.xml.in new file mode 100644 index 00000000..0de3e8f3 --- /dev/null +++ b/packaging/linux/ai.storyteller.materialcraft.metainfo.xml.in @@ -0,0 +1,65 @@ + + + + ai.storyteller.materialcraft + CC0-1.0 + MIT OR Apache-2.0 + MaterialCraft + Design procedural PBR materials with node graphs + + Learning Machines LLC + + +

+ MaterialCraft is an open-source, native node-based material designer: build tileable PBR + materials from noises, patterns and filters in a node graph, preview them live in 2D and 3D, + and export the texture maps for any engine. +

+
    +
  • Hundreds of procedural nodes: noises, patterns, adjustments, blurs, warps, normal and height tools
  • +
  • Live 2D and 3D previews with physically based shading
  • +
  • Export base color, normal, roughness, metallic, height and ambient occlusion maps as PNG, EXR, TGA, JPEG or TIFF; save packages as .mcraft
  • +
  • Every action is a command, scriptable from a CLI, a JSON control channel and an MCP server
  • +
+
+ ai.storyteller.materialcraft.desktop + ai.storyteller.materialcraft + + https://getartcraft.com/apps/materialcraft + https://github.com/storytold/materialcraft/issues + https://github.com/storytold/materialcraft + https://discord.gg/artcraft + + Graphics + 3DGraphics + + + procedural + material + node graph + pbr + 3d + mesh + + + #a8e3ef + #0e5f72 + + + 760 + + + keyboard + pointing + tablet + + + materialcraft + application/x-materialcraft + + + + + +
diff --git a/packaging/linux/ai.storyteller.materialcraft.mime.xml b/packaging/linux/ai.storyteller.materialcraft.mime.xml new file mode 100644 index 00000000..25174ac4 --- /dev/null +++ b/packaging/linux/ai.storyteller.materialcraft.mime.xml @@ -0,0 +1,11 @@ + + + + + MaterialCraft package + + + + + diff --git a/packaging/linux/apprun-test.sh b/packaging/linux/apprun-test.sh new file mode 100644 index 00000000..f53fb698 --- /dev/null +++ b/packaging/linux/apprun-test.sh @@ -0,0 +1,98 @@ +#!/usr/bin/env bash +# Smoke test for packaging/linux/AppRun: the AppImage's desktop integration writes +# and refreshes the host .desktop entry and icons, is idempotent, honours the opt-out +# and an unwritable HOME, and always launches the app. +# +# Runs in seconds with no build (CI: .github/workflows/packaging-lint.yml). +set -euo pipefail + +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +ROOT="$(cd "$HERE/../.." && pwd)" +APP_ID=ai.storyteller.materialcraft + +TMP="$(mktemp -d)" +trap 'rm -rf "$TMP"' EXIT + +# Fake AppDir with the real AppRun, .desktop template, icons, and a stub binary. +APPDIR="$TMP/MaterialCraft.AppDir" +mkdir -p "$APPDIR/usr/bin" +install -Dm755 "$HERE/AppRun" "$APPDIR/AppRun" +install -Dm644 "$HERE/$APP_ID.desktop" "$APPDIR/usr/share/applications/$APP_ID.desktop" +mkdir -p "$APPDIR/usr/share/icons" +cp -R "$ROOT/assets/app-icon/hicolor" "$APPDIR/usr/share/icons/" +printf '#!/bin/sh\necho "stub: $*"\n' >"$APPDIR/usr/bin/materialcraft" +chmod +x "$APPDIR/usr/bin/materialcraft" + +APPIMAGE="$TMP/materialcraft test.AppImage" # spaces on purpose: Exec must stay quoted +: >"$APPIMAGE" +export APPIMAGE +export HOME="$TMP/home" +export XDG_DATA_HOME="$HOME/.local/share" +mkdir -p "$HOME" + +fail() { + echo "FAIL: $*" >&2 + exit 1 +} + +# 1. Launch works and passes arguments through. +out="$("$APPDIR/AppRun" open graph.mcraft)" || fail "AppRun exited non-zero" +[ "$out" = "stub: open graph.mcraft" ] || fail "arguments not forwarded: $out" + +DESKTOP="$XDG_DATA_HOME/applications/$APP_ID.desktop" +[ -f "$DESKTOP" ] || fail "desktop entry not installed" + +# 2. Exec rewritten to the AppImage (quoted, spaces intact), TryExec dropped, +# everything else preserved from the packaged entry. +expected_exec="Exec=\"$(readlink -f "$APPIMAGE")\" %F" +grep -Fxq "$expected_exec" "$DESKTOP" || fail "Exec not rewritten: $(grep '^Exec=' "$DESKTOP")" +grep -q '^TryExec=' "$DESKTOP" && fail "TryExec kept, the entry would be hidden" +grep -Fxq "Icon=$APP_ID" "$DESKTOP" || fail "Icon line lost" +grep -Fxq 'Categories=Graphics;3DGraphics;' "$DESKTOP" || fail "metadata lines lost" +if command -v desktop-file-validate >/dev/null; then + desktop-file-validate "$DESKTOP" || fail "generated desktop entry is invalid" +fi + +# 3. Icons landed under the name the .desktop entry references. +for f in "16x16/apps/$APP_ID.png" "256x256/apps/$APP_ID.png" "scalable/apps/$APP_ID.svg"; do + [ -f "$XDG_DATA_HOME/icons/hicolor/$f" ] || fail "icon missing: $f" +done + +# 4. Idempotent: a second launch must not rewrite anything (inode unchanged). +before="$(stat -c %i "$DESKTOP")" +out="$("$APPDIR/AppRun")" || fail "second launch exited non-zero" +[ "$out" = "stub: " ] || fail "second launch output: $out" +after="$(stat -c %i "$DESKTOP")" +[ "$before" = "$after" ] || fail "desktop entry rewritten although unchanged" + +# 5. Moving the AppImage refreshes Exec. +mv "$APPIMAGE" "$TMP/moved.AppImage" +export APPIMAGE="$TMP/moved.AppImage" +"$APPDIR/AppRun" >/dev/null || fail "launch after move exited non-zero" +grep -Fxq "Exec=\"$(readlink -f "$APPIMAGE")\" %F" "$DESKTOP" || fail "Exec not refreshed after move" + +# 6. Opt-out installs nothing. +rm -rf "$XDG_DATA_HOME" +MATERIALCRAFT_NO_DESKTOP_INTEGRATION=1 "$APPDIR/AppRun" >/dev/null || fail "opt-out launch exited non-zero" +[ ! -e "$XDG_DATA_HOME" ] || fail "opt-out still integrated" + +# 7. An unwritable data dir never blocks the launch. +mkdir -p "$TMP/ro" && chmod a-w "$TMP/ro" +out="$(XDG_DATA_HOME="$TMP/ro/data" "$APPDIR/AppRun" out.txt)" || fail "launch blocked by unwritable data dir" +[ "$out" = "stub: out.txt" ] || fail "stub not run against unwritable data dir: $out" +chmod u+w "$TMP/ro" + +# 8. No $APPIMAGE (extracted AppDir): launch only, nothing installed. +rm -rf "$XDG_DATA_HOME" +env -u APPIMAGE "$APPDIR/AppRun" >/dev/null || fail "extracted-AppDir launch exited non-zero" +[ ! -e "$XDG_DATA_HOME" ] || fail "integrated without $APPIMAGE" + +# 9. A path that would need Exec escaping (here a `$`): launch only, nothing installed. +rm -rf "$XDG_DATA_HOME" +odd="$TMP/odd\$(id).AppImage" +: >"$odd" +out="$(APPIMAGE="$odd" "$APPDIR/AppRun" x)" || fail "launch with an odd path exited non-zero" +[ "$out" = "stub: x" ] || fail "odd path: $out" +[ ! -e "$XDG_DATA_HOME" ] || fail "integrated an AppImage path that needs escaping" + +echo "AppRun desktop integration ok" diff --git a/packaging/linux/flatpak-bundle.sh b/packaging/linux/flatpak-bundle.sh new file mode 100644 index 00000000..f3042315 --- /dev/null +++ b/packaging/linux/flatpak-bundle.sh @@ -0,0 +1,72 @@ +#!/usr/bin/env bash +# Repackage a MaterialCraft Linux tarball as a single-file Flatpak bundle: +# +# $DIST/materialcraft--linux-.flatpak +# +# Usage: packaging/linux/flatpak-bundle.sh [--no-test] [TARBALL] +# +# TARBALL defaults to $DIST/materialcraft--linux-.tar.gz from package.sh. The bundle +# is built for the host architecture (x86_64 or aarch64), which must match the tarball's. +# Needs flatpak, flatpak-builder and the SVG pixbuf loader (librsvg2-common) for the host's +# `appstreamcli compose`; the freedesktop runtime and SDK named in the manifest are +# installed per-user from Flathub. Unless --no-test, the bundle is then installed per-user and +# `materialcraft-cli --version` is run inside the sandbox as a smoke test. +# Manifest: packaging/linux/flatpak/ai.storyteller.MaterialCraft.bundle.yml. +set -euo pipefail +# shellcheck source=../env.sh +. "$(dirname "${BASH_SOURCE[0]}")/../env.sh" +HERE="$ROOT/packaging/linux" +APP_ID=ai.storyteller.materialcraft +FLATHUB=https://dl.flathub.org/repo/flathub.flatpakrepo + +TEST=1 +TARBALL="" +while [ $# -gt 0 ]; do + case "$1" in + --no-test) TEST=0; shift ;; + -h | --help) sed -n '2,14p' "$0"; exit 0 ;; + -*) echo "unknown argument: $1" >&2; exit 2 ;; + *) TARBALL="$1"; shift ;; + esac +done + +ARCH="$(uname -m)" +case "$ARCH" in + x86_64) ;; + aarch64 | arm64) ARCH=aarch64 ;; + *) echo "unsupported architecture $ARCH" >&2; exit 2 ;; +esac +BASENAME="materialcraft-$VERSION-linux-$ARCH" +TARBALL="${TARBALL:-$DIST/$BASENAME.tar.gz}" +[ -f "$TARBALL" ] || { echo "error: $TARBALL not found (run packaging/linux/package.sh --formats tar first)" >&2; exit 1; } +for tool in flatpak flatpak-builder; do + command -v "$tool" >/dev/null || { echo "error: $tool not found (apt install flatpak flatpak-builder librsvg2-common)" >&2; exit 1; } +done + +echo "==> MaterialCraft $VERSION Flatpak bundle for $ARCH from $(basename "$TARBALL")" + +WORK="$CARGO_TARGET_DIR/flatpak-bundle" +rm -rf "$WORK" +mkdir -p "$WORK/stage" +tar -xzf "$TARBALL" -C "$WORK/stage" --strip-components=1 +[ -x "$WORK/stage/bin/materialcraft" ] || { echo "error: $TARBALL has no bin/materialcraft" >&2; exit 1; } +cp "$HERE/flatpak/ai.storyteller.MaterialCraft.bundle.yml" "$WORK/$APP_ID.yml" + +flatpak remote-add --user --if-not-exists flathub "$FLATHUB" +# --disable-rofiles-fuse: no FUSE in containers and CI runners. +flatpak-builder --user --install-deps-from=flathub --disable-rofiles-fuse --force-clean \ + --default-branch=stable --repo="$WORK/repo" --state-dir="$WORK/state" "$WORK/build" "$WORK/$APP_ID.yml" + +OUT="$DIST/$BASENAME.flatpak" +# --runtime-repo lets `flatpak install` fetch the freedesktop runtime from Flathub if missing. +flatpak build-bundle --runtime-repo="$FLATHUB" "$WORK/repo" "$OUT" "$APP_ID" stable +echo "wrote $OUT" + +if [ "$TEST" = 1 ]; then + flatpak install --user -y --noninteractive --reinstall "$OUT" + flatpak info --user "$APP_ID" + flatpak run --command=materialcraft-cli "$APP_ID" --version + flatpak run --command=sh "$APP_ID" -c 'ls /app/share/applications /app/share/metainfo /app/share/mime/packages /app/share/icons/hicolor/scalable/apps' +fi +echo "==> done" +ls -lh "$OUT" diff --git a/packaging/linux/flatpak/ai.storyteller.MaterialCraft.bundle.yml b/packaging/linux/flatpak/ai.storyteller.MaterialCraft.bundle.yml new file mode 100644 index 00000000..fed3a369 --- /dev/null +++ b/packaging/linux/flatpak/ai.storyteller.MaterialCraft.bundle.yml @@ -0,0 +1,50 @@ +# Flatpak manifest for the single-file bundle attached to every GitHub release +# (materialcraft--linux-.flatpak). Build it with packaging/linux/flatpak-bundle.sh. +# +# It repackages the release's own Linux tarball (materialcraft--linux-.tar.gz, +# built on Ubuntu 22.04 by package.sh) instead of compiling Rust inside flatpak-builder: no +# network and no vendored crate sources during the build, a few seconds instead of 20+ minutes, +# and byte-for-byte the same binaries as the AppImage/deb/rpm. The script unpacks the tarball +# into `stage/` next to a copy of this file. The binaries need glibc >= 2.35 and load X11, +# Wayland, xkbcommon and Vulkan at runtime; the freedesktop runtime has all of them, and the +# GPU driver comes from its org.freedesktop.Platform.GL extension. +# +# ai.storyteller.MaterialCraft.yml (same directory) is the from-source manifest for Flathub. Keep +# runtime-version and finish-args identical in both (packaging-lint checks this). +id: ai.storyteller.materialcraft +runtime: org.freedesktop.Platform +runtime-version: '26.08' +sdk: org.freedesktop.Sdk +command: materialcraft +finish-args: + # Display: Wayland first; X11 only when no Wayland compositor is running. + - --socket=wayland + - --socket=fallback-x11 + # X11 shared memory (MIT-SHM). Without it the X11 fallback is slow or fails. + - --share=ipc + # GPU access for the wgpu viewport (Vulkan, or GL as a fallback). + - --device=dri + # Open/Save dialogs go through the file-chooser portal (rfd's xdg-portal backend) and + # drag-and-drop through the document portal, so picked files work anywhere without broad + # filesystem access. Pictures and Documents are granted so files passed by path (the command + # line, Open Recent, "Save" next to the original) work in the usual places. + - --filesystem=xdg-pictures + - --filesystem=xdg-documents + # Deliberately not granted: network (the optional --control server listens on 127.0.0.1 in + # the sandbox; `flatpak override --user --share=network ai.storyteller.materialcraft` exposes it to + # host agents) and home/host filesystem access. +modules: + - name: materialcraft + buildsystem: simple + build-commands: + - install -Dm755 bin/materialcraft /app/bin/materialcraft + - install -Dm755 bin/materialcraft-cli /app/bin/materialcraft-cli + - install -Dm644 share/applications/ai.storyteller.materialcraft.desktop /app/share/applications/ai.storyteller.materialcraft.desktop + # .mcraft, plus mesh types older shared-mime-info databases lack. + - install -Dm644 share/mime/packages/ai.storyteller.materialcraft.xml /app/share/mime/packages/ai.storyteller.materialcraft.xml + # Already has the release's version and date substituted by package.sh. + - install -Dm644 share/metainfo/ai.storyteller.materialcraft.metainfo.xml /app/share/metainfo/ai.storyteller.materialcraft.metainfo.xml + - mkdir -p /app/share/icons /app/share/doc && cp -R share/icons/hicolor /app/share/icons/ && cp -R share/doc/materialcraft /app/share/doc/ + sources: + - type: dir + path: stage diff --git a/packaging/linux/flatpak/ai.storyteller.MaterialCraft.yml b/packaging/linux/flatpak/ai.storyteller.MaterialCraft.yml new file mode 100644 index 00000000..56e599ea --- /dev/null +++ b/packaging/linux/flatpak/ai.storyteller.MaterialCraft.yml @@ -0,0 +1,66 @@ +# Flatpak manifest for MaterialCraft, ready for a Flathub submission. +# +# Flatpak builds run offline, so the crate sources must be vendored first. From the repo root: +# +# curl -fsSLO https://raw.githubusercontent.com/flatpak/flatpak-builder-tools/master/cargo/flatpak-cargo-generator.py +# python3 flatpak-cargo-generator.py Cargo.lock -o packaging/linux/flatpak/cargo-sources.json +# flatpak-builder --user --install --force-clean build-flatpak packaging/linux/flatpak/ai.storyteller.MaterialCraft.yml +# flatpak run ai.storyteller.materialcraft +# +# For Flathub, replace the `dir` source with a `git` source pinned to a release tag and commit. +# The single-file .flatpak attached to each release comes from ai.storyteller.MaterialCraft.bundle.yml, +# which repackages the prebuilt release binaries. Keep runtime-version and finish-args identical. +id: ai.storyteller.materialcraft +runtime: org.freedesktop.Platform +runtime-version: '26.08' +sdk: org.freedesktop.Sdk +sdk-extensions: + - org.freedesktop.Sdk.Extension.rust-stable +command: materialcraft +finish-args: + # Display: Wayland first; X11 only when no Wayland compositor is running. + - --socket=wayland + - --socket=fallback-x11 + # X11 shared memory (MIT-SHM). Without it the X11 fallback is slow or fails. + - --share=ipc + # GPU access for the wgpu viewport (Vulkan, or GL as a fallback). + - --device=dri + # Open/Save dialogs go through the file-chooser portal (rfd's xdg-portal backend) and + # drag-and-drop through the document portal, so picked files work anywhere without broad + # filesystem access. Pictures and Documents are granted so files passed by path (the command + # line, Open Recent, "Save" next to the original) work in the usual places. + - --filesystem=xdg-pictures + - --filesystem=xdg-documents + # Deliberately not granted: network (the optional --control server listens on 127.0.0.1 in + # the sandbox; `flatpak override --user --share=network ai.storyteller.materialcraft` exposes it to + # host agents) and home/host filesystem access. +build-options: + append-path: /usr/lib/sdk/rust-stable/bin +modules: + - name: materialcraft + buildsystem: simple + build-options: + env: + CARGO_HOME: /run/build/materialcraft/cargo + CARGO_NET_OFFLINE: 'true' + build-commands: + - cargo --offline build --release --locked -p materialcraft -p materialcraft-cli + - install -Dm755 target/release/materialcraft /app/bin/materialcraft + - install -Dm755 target/release/materialcraft-cli /app/bin/materialcraft-cli + - install -Dm644 packaging/linux/ai.storyteller.materialcraft.desktop /app/share/applications/ai.storyteller.materialcraft.desktop + - install -Dm644 packaging/linux/ai.storyteller.materialcraft.mime.xml /app/share/mime/packages/ai.storyteller.materialcraft.xml + - mkdir -p /app/share/icons && cp -R assets/app-icon/hicolor /app/share/icons/ + - >- + version=$(awk '/^\[/{p=($0=="[workspace.package]");next} p&&$1=="version"{gsub(/[" ]/,"",$3);print $3;exit}' Cargo.toml); + install -d /app/share/metainfo; + sed -e "s/@VERSION@/$version/" -e "s/@DATE@/$(date -u +%Y-%m-%d)/" + packaging/linux/ai.storyteller.materialcraft.metainfo.xml.in > /app/share/metainfo/ai.storyteller.materialcraft.metainfo.xml + sources: + - type: dir + path: ../../.. + skip: + - target + - dist + - build-flatpak + - .flatpak-builder + - cargo-sources.json diff --git a/packaging/linux/nfpm.yaml b/packaging/linux/nfpm.yaml new file mode 100644 index 00000000..dd266033 --- /dev/null +++ b/packaging/linux/nfpm.yaml @@ -0,0 +1,80 @@ +# .deb and .rpm packages (nfpm: https://nfpm.goreleaser.com). Run by package.sh, which stages +# the file tree, substitutes its path for ${STAGE} (nfpm doesn't expand env vars in `src`) and +# exports VERSION and NFPM_ARCH. +# +# nfpm package -f packaging/linux/nfpm.yaml -p deb -t dist/release/ +name: materialcraft +arch: ${NFPM_ARCH} +platform: linux +version: ${VERSION} +# semver: 0.2.0-rc.1 becomes 0.2.0~rc.1 in deb/rpm, so pre-releases sort before the release. +version_schema: semver +release: 1 +section: graphics +priority: optional +maintainer: ${MATERIALCRAFT_MAINTAINER} +vendor: Learning Machines LLC +homepage: https://getartcraft.com/apps/materialcraft +license: MIT OR Apache-2.0 +description: |- + Open-source, native node-based procedural material designer. Builds tileable PBR + materials from noises, patterns and filters in a node graph with live 2D and 3D + previews, and exports texture maps for game engines. + Includes materialcraft-cli, a headless graph cooker and command runner. + +# The binaries link only glibc and libgcc_s directly. Windowing (X11/Wayland, xkbcommon) and the +# GPU (Vulkan, EGL/GL) are loaded at runtime with dlopen, so they aren't ELF NEEDED entries and +# the package tools can't find them: list them here. winit 0.30 loads, for X11: libX11, +# libX11-xcb, libxcb, libXcursor, libXi, libxkbcommon and libxkbcommon-x11 (missing +# libxkbcommon-x11 panics); for Wayland: libwayland-client and libxkbcommon. wgpu needs libvulkan +# or libEGL. RandR goes through x11rb's protocol code and fonts are found by scanning directories, +# so libXrandr and fontconfig aren't loaded. +overrides: + deb: + depends: + - libc6 (>= 2.35) + - libgcc-s1 + - libxkbcommon0 + - libxkbcommon-x11-0 + - libwayland-client0 + - libx11-6 + - libx11-xcb1 + - libxcb1 + - libxcursor1 + - libxi6 + - libvulkan1 | libegl1 + recommends: + - mesa-vulkan-drivers + - libegl-mesa0 + - xdg-desktop-portal + rpm: + # Soname provides rather than package names, so the same requirements resolve on Fedora/RHEL + # (libxkbcommon-x11, libX11-xcb, ...) and openSUSE (libxkbcommon-x11-0, libX11-xcb1, ...). + depends: + - libxkbcommon.so.0()(64bit) + - libxkbcommon-x11.so.0()(64bit) + - libwayland-client.so.0()(64bit) + - libX11.so.6()(64bit) + - libX11-xcb.so.1()(64bit) + - libxcb.so.1()(64bit) + - libXcursor.so.1()(64bit) + - libXi.so.6()(64bit) + - (libvulkan.so.1()(64bit) or libEGL.so.1()(64bit)) + recommends: + - mesa-vulkan-drivers + - xdg-desktop-portal + +contents: + - src: ${STAGE}/usr/bin/materialcraft + dst: /usr/bin/materialcraft + file_info: { mode: 0755 } + - src: ${STAGE}/usr/bin/materialcraft-cli + dst: /usr/bin/materialcraft-cli + file_info: { mode: 0755 } + - src: ${STAGE}/usr/share/ + dst: /usr/share/ + type: tree + +scripts: + postinstall: packaging/linux/postinst.sh + postremove: packaging/linux/postinst.sh diff --git a/packaging/linux/package.sh b/packaging/linux/package.sh new file mode 100644 index 00000000..ee7791a0 --- /dev/null +++ b/packaging/linux/package.sh @@ -0,0 +1,151 @@ +#!/usr/bin/env bash +# Build and package MaterialCraft for Linux (x86_64, aarch64 or cross-compiled riscv64): +# +# $DIST/materialcraft--linux-.AppImage any distro with glibc >= the build host's +# $DIST/materialcraft--linux-.AppImage.zsync delta updates (needs zsyncmake) +# $DIST/materialcraft--linux-.deb Debian, Ubuntu, Mint, Pop!_OS, ... +# $DIST/materialcraft--linux-.rpm Fedora, openSUSE, RHEL, ... +# $DIST/materialcraft--linux-.tar.gz plain FHS-style tree (bin/, share/) +# +# Usage: packaging/linux/package.sh [--skip-build] [--formats "appimage deb rpm tar"] +# +# Needs: cargo; nfpm for deb/rpm (https://nfpm.goreleaser.com); appimagetool for the AppImage +# (downloaded into $CARGO_TARGET_DIR if missing). Build on an old distro (CI: Ubuntu 22.04, +# glibc 2.35) so the binaries run on newer ones. Optional: desktop-file-validate, appstreamcli, +# zsyncmake (the zsync package) for the AppImage's .zsync. +set -euo pipefail +# shellcheck source=../env.sh +. "$(dirname "${BASH_SOURCE[0]}")/../env.sh" +HERE="$ROOT/packaging/linux" +APP_ID=ai.storyteller.materialcraft + +SKIP_BUILD=0 +FORMATS="appimage deb rpm tar" +while [ $# -gt 0 ]; do + case "$1" in + --skip-build) SKIP_BUILD=1; shift ;; + --formats) FORMATS="$2"; shift 2 ;; + -h | --help) sed -n '2,15p' "$0"; exit 0 ;; + *) echo "unknown argument: $1" >&2; exit 2 ;; + esac +done + +ARCH="${CROSS_ARCH:-$(uname -m)}" +case "$ARCH" in + riscv64) DEB_ARCH=riscv64 ;; + x86_64) DEB_ARCH=amd64 ;; + aarch64 | arm64) ARCH=aarch64; DEB_ARCH=arm64 ;; + *) echo "unsupported architecture $ARCH" >&2; exit 2 ;; +esac +export MATERIALCRAFT_MAINTAINER="${MATERIALCRAFT_MAINTAINER:-MaterialCraft maintainers }" +BASENAME="materialcraft-$VERSION-linux-$ARCH" + +echo "==> MaterialCraft $VERSION for Linux $ARCH ($FORMATS)" + +if [ "$SKIP_BUILD" = 0 ]; then + (cd "$ROOT" && cargo build --release --locked -p materialcraft -p materialcraft-cli ${CROSS_TARGET:+--target "$CROSS_TARGET"}) +fi +BIN="$CARGO_TARGET_DIR/${CROSS_TARGET:+$CROSS_TARGET/}release" +WORK="$CARGO_TARGET_DIR/linux-package" +STAGE="$WORK/root" +rm -rf "$WORK" + +# ---- stage an FHS tree (shared by every format) ------------------------------------------------- +install -Dm755 "$BIN/materialcraft" "$STAGE/usr/bin/materialcraft" +install -Dm755 "$BIN/materialcraft-cli" "$STAGE/usr/bin/materialcraft-cli" +"${CROSS_COMPILE:-}strip" "$STAGE/usr/bin/materialcraft" "$STAGE/usr/bin/materialcraft-cli" 2>/dev/null || true +install -Dm644 "$HERE/$APP_ID.desktop" "$STAGE/usr/share/applications/$APP_ID.desktop" +install -Dm644 "$HERE/$APP_ID.mime.xml" "$STAGE/usr/share/mime/packages/$APP_ID.xml" +mkdir -p "$STAGE/usr/share/metainfo" +sed -e "s/@VERSION@/$VERSION/g" -e "s/@DATE@/$MATERIALCRAFT_BUILD_DATE/g" \ + "$HERE/$APP_ID.metainfo.xml.in" >"$STAGE/usr/share/metainfo/$APP_ID.metainfo.xml" +mkdir -p "$STAGE/usr/share/icons" +cp -R "$ROOT/assets/app-icon/hicolor" "$STAGE/usr/share/icons/" +mkdir -p "$STAGE/usr/share/doc/materialcraft" +copy_docs "$STAGE/usr/share/doc/materialcraft" + +if command -v desktop-file-validate >/dev/null; then + desktop-file-validate "$STAGE/usr/share/applications/$APP_ID.desktop" +fi +if command -v appstreamcli >/dev/null; then + appstreamcli validate --no-net --explain "$STAGE/usr/share/metainfo/$APP_ID.metainfo.xml" +fi + +has() { case " $FORMATS " in *" $1 "*) return 0 ;; *) return 1 ;; esac; } + +# ---- .tar.gz ------------------------------------------------------------------------------------ +if has tar; then + mkdir -p "$WORK/tar" + cp -R "$STAGE/usr" "$WORK/tar/$BASENAME" + tar -C "$WORK/tar" -czf "$DIST/$BASENAME.tar.gz" "$BASENAME" + echo "wrote $DIST/$BASENAME.tar.gz" +fi + +# ---- .deb / .rpm -------------------------------------------------------------------------------- +if has deb || has rpm; then + command -v nfpm >/dev/null || { echo "error: nfpm not found (https://nfpm.goreleaser.com/install/)" >&2; exit 1; } + export VERSION + export NFPM_ARCH="$DEB_ARCH" + # nfpm expands env vars in fields like `version` and `arch`, but not in `contents[].src`. + sed "s|\${STAGE}|$STAGE|g" "$HERE/nfpm.yaml" >"$WORK/nfpm.yaml" + # The riscv64 cross sysroot is Ubuntu 24.04, whose glibc floor is 2.39. + if [ "$ARCH" = riscv64 ]; then sed -i "s/libc6 (>= 2.35)/libc6 (>= 2.39)/" "$WORK/nfpm.yaml"; fi + for fmt in deb rpm; do + if has "$fmt"; then (cd "$ROOT" && nfpm package -f "$WORK/nfpm.yaml" -p "$fmt" -t "$DIST/$BASENAME.$fmt"); fi + done +fi + +# ---- AppImage ----------------------------------------------------------------------------------- +if has appimage; then + APPDIR="$WORK/MaterialCraft.AppDir" + cp -R "$STAGE" "$APPDIR" + mv "$APPDIR/usr/share/doc" "$WORK/doc-unused" + # AppRun is a script, not a symlink: it installs the .desktop entry and icons into + # $XDG_DATA_HOME before launching, so Wayland compositors can resolve the window's + # app_id to our icon instead of the generic Wayland logo (opt-out env in the + # script header). Logic is covered by packaging/linux/apprun-test.sh. + install -Dm755 "$HERE/AppRun" "$APPDIR/AppRun" + cp "$HERE/$APP_ID.desktop" "$APPDIR/$APP_ID.desktop" + cp "$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png" "$APPDIR/$APP_ID.png" + ln -s "$APP_ID.png" "$APPDIR/.DirIcon" + + TOOL="${APPIMAGETOOL:-$(command -v appimagetool || true)}" + if [ -z "$TOOL" ]; then + TOOL="$CARGO_TARGET_DIR/appimagetool-$ARCH.AppImage" + if [ ! -x "$TOOL" ]; then + curl -fsSL -o "$TOOL" "https://github.com/AppImage/appimagetool/releases/download/continuous/appimagetool-$ARCH.AppImage" + chmod +x "$TOOL" + fi + fi + # Absolute, because appimagetool runs in $DIST below (CARGO_TARGET_DIR or APPIMAGETOOL may be + # relative, e.g. target/agent-). + OUT="$(cd "$DIST" && pwd)/$BASENAME.AppImage" + APPDIR="$(cd "$APPDIR" && pwd)" + TOOL="$(cd "$(dirname "$TOOL")" && pwd)/$(basename "$TOOL")" + # A .zsync left by an earlier run would hide a missing zsyncmake and describe another file. + rm -f "$OUT.zsync" + # Update information: AppImageUpdate, AppImageLauncher and the like read it from the + # file and fetch only the blocks that changed in a newer release, through the .zsync published + # next to each AppImage on GitHub Releases. `latest` is the newest published release that is + # not a pre-release. A fork's builds point at its own releases through GITHUB_REPOSITORY. + REPO="${GITHUB_REPOSITORY:-storytold/materialcraft}" + UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest|materialcraft-*-linux-$ARCH.AppImage.zsync" + # Extract-and-run: works without FUSE (containers, CI). The output embeds the static runtime, + # so users don't need libfuse2 either. With zsyncmake on the host (CI installs the zsync + # package) appimagetool also writes the .zsync, into its working directory, hence the cd. + (cd "$DIST" && ARCH="$ARCH" APPIMAGE_EXTRACT_AND_RUN=1 "$TOOL" --no-appstream -u "$UPDATE_INFO" "$APPDIR" "$OUT") + echo "wrote $OUT" + if [ -s "$OUT.zsync" ]; then + echo "wrote $OUT.zsync" + else + warn "zsyncmake not found, so $OUT.zsync was not written; AppImage delta updates need it" + fi +fi + +if [ -n "${CROSS_TARGET:-}" ]; then + if [ -n "${EMULATOR:-}" ]; then "$EMULATOR" "$STAGE/usr/bin/materialcraft-cli" --version; fi +else + "$STAGE/usr/bin/materialcraft-cli" --version +fi +echo "==> done" +ls -lh "$DIST" diff --git a/packaging/linux/postinst.sh b/packaging/linux/postinst.sh new file mode 100644 index 00000000..775e4df9 --- /dev/null +++ b/packaging/linux/postinst.sh @@ -0,0 +1,13 @@ +#!/bin/sh +# deb/rpm post-install and post-remove: refresh the desktop, MIME and icon caches. +# Every tool is optional; missing ones are skipped. +if command -v update-desktop-database >/dev/null 2>&1; then + update-desktop-database -q /usr/share/applications || true +fi +if command -v update-mime-database >/dev/null 2>&1; then + update-mime-database /usr/share/mime || true +fi +if command -v gtk-update-icon-cache >/dev/null 2>&1; then + gtk-update-icon-cache -q -t -f /usr/share/icons/hicolor || true +fi +exit 0 diff --git a/packaging/macos/Info.plist.in b/packaging/macos/Info.plist.in new file mode 100644 index 00000000..31f9ac48 --- /dev/null +++ b/packaging/macos/Info.plist.in @@ -0,0 +1,89 @@ + + + + + + CFBundleDevelopmentRegion + en + CFBundleDisplayName + MaterialCraft + CFBundleName + MaterialCraft + CFBundleExecutable + MaterialCraft + CFBundleIdentifier + ai.storyteller.materialcraft + CFBundleInfoDictionaryVersion + 6.0 + CFBundlePackageType + APPL + CFBundleSignature + ???? + CFBundleShortVersionString + @SHORT_VERSION@ + CFBundleVersion + @SHORT_VERSION@ + MaterialCraftVersion + @VERSION@ + MaterialCraftBuildCommit + @BUILD_SHA@ + CFBundleIconFile + MaterialCraft + LSApplicationCategoryType + public.app-category.graphics-design + + LSMinimumSystemVersion + 11.0 + NSHighResolutionCapable + + NSSupportsAutomaticGraphicsSwitching + + NSRequiresAquaSystemAppearance + + NSHumanReadableCopyright + Copyright © the MaterialCraft contributors. MIT OR Apache-2.0. + + + UTExportedTypeDeclarations + + + UTTypeIdentifier + ai.storyteller.materialcraft.package + UTTypeDescription + MaterialCraft Package + UTTypeConformsTo + + public.data + public.content + + UTTypeIconFile + MaterialCraft + UTTypeTagSpecification + + public.filename-extension + mcraft + public.mime-type + application/x-materialcraft + + + + + CFBundleDocumentTypes + + + CFBundleTypeName + MaterialCraft Package + CFBundleTypeRole + Editor + LSHandlerRank + Owner + CFBundleTypeIconFile + MaterialCraft + LSItemContentTypes + ai.storyteller.materialcraft.package + + + + diff --git a/packaging/macos/entitlements.plist b/packaging/macos/entitlements.plist new file mode 100644 index 00000000..debce08a --- /dev/null +++ b/packaging/macos/entitlements.plist @@ -0,0 +1,9 @@ + + + + + + + diff --git a/packaging/macos/import-cert.sh b/packaging/macos/import-cert.sh new file mode 100644 index 00000000..08c22d1a --- /dev/null +++ b/packaging/macos/import-cert.sh @@ -0,0 +1,50 @@ +#!/usr/bin/env bash +# CI only: import the Developer ID certificate into a temporary keychain so codesign can use it. +# +# Inputs (env): APPLE_CERTIFICATE (base64 .p12), APPLE_CERTIFICATE_PASSWORD, KEYCHAIN_PASSWORD +# (optional; random if unset), RUNNER_TEMP (or TMPDIR). +# Outputs: MACOS_SIGN_IDENTITY (SHA-1 of the identity) and MACOS_KEYCHAIN, appended to +# $GITHUB_ENV when running in Actions, otherwise printed. +# +# Missing certificate: prints a warning and exits 0, so package.sh falls back to ad-hoc signing. +set -euo pipefail +umask 077 +# shellcheck source=../env.sh +. "$(dirname "${BASH_SOURCE[0]}")/../env.sh" + +if [ -z "${APPLE_CERTIFICATE:-}" ]; then + warn "APPLE_CERTIFICATE is not set: macOS builds will be ad-hoc signed and not notarized" + exit 0 +fi + +TMP="${RUNNER_TEMP:-${TMPDIR:-/tmp}}" +KEYCHAIN="$TMP/materialcraft-signing.keychain-db" +CERT="$TMP/materialcraft-signing.p12" +KC_PASS="${KEYCHAIN_PASSWORD:-$(openssl rand -hex 24)}" + +trap 'rm -f "$CERT"' EXIT +printf '%s' "$APPLE_CERTIFICATE" | base64 --decode >"$CERT" +security create-keychain -p "$KC_PASS" "$KEYCHAIN" +security set-keychain-settings -lut 21600 "$KEYCHAIN" +security unlock-keychain -p "$KC_PASS" "$KEYCHAIN" +security import "$CERT" -P "${APPLE_CERTIFICATE_PASSWORD:-}" -T /usr/bin/codesign -T /usr/bin/security -t cert -f pkcs12 -k "$KEYCHAIN" +rm -f "$CERT" +# Let codesign use the key without a UI prompt. +security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "$KC_PASS" "$KEYCHAIN" >/dev/null +# Put it on the search list (keeping the login keychain) so codesign and notarytool find it. +# shellcheck disable=SC2046 +security list-keychains -d user -s "$KEYCHAIN" $(security list-keychains -d user | tr -d '"') + +IDENTITY="$(security find-identity -v -p codesigning "$KEYCHAIN" | awk '/Developer ID Application/ { print $2; exit }')" +if [ -z "$IDENTITY" ]; then + security find-identity -v -p codesigning "$KEYCHAIN" >&2 + echo "error: no 'Developer ID Application' identity in APPLE_CERTIFICATE" >&2 + exit 1 +fi +echo "Imported signing identity $IDENTITY" +if [ -n "${GITHUB_ENV:-}" ]; then + { echo "MACOS_SIGN_IDENTITY=$IDENTITY"; echo "MACOS_KEYCHAIN=$KEYCHAIN"; } >>"$GITHUB_ENV" +else + echo "MACOS_SIGN_IDENTITY=$IDENTITY" + echo "MACOS_KEYCHAIN=$KEYCHAIN" +fi diff --git a/packaging/macos/package.sh b/packaging/macos/package.sh new file mode 100644 index 00000000..349ce55b --- /dev/null +++ b/packaging/macos/package.sh @@ -0,0 +1,167 @@ +#!/usr/bin/env bash +# Build, sign and (optionally) notarize the macOS release artifacts: +# +# $DIST/materialcraft--macos-.dmg MaterialCraft.app on a drag-to-Applications DMG +# $DIST/materialcraft-cli--macos-.zip the headless CLI +# +# Usage: packaging/macos/package.sh [--arch universal|aarch64|x86_64] [--skip-build] +# +# Signing (env): +# MACOS_SIGN_IDENTITY codesign identity (name or SHA-1). Default "-" = ad-hoc (local testing; +# Gatekeeper will reject the result on other Macs). In CI, import-cert.sh sets it. +# MACOS_KEYCHAIN keychain holding the identity (optional) +# Notarization (env; all three needed, and a real identity): +# APPLE_ID, APPLE_PASSWORD (app-specific password), APPLE_TEAM_ID +set -euo pipefail +# shellcheck source=../env.sh +. "$(dirname "${BASH_SOURCE[0]}")/../env.sh" +HERE="$ROOT/packaging/macos" + +ARCH=universal +SKIP_BUILD=0 +while [ $# -gt 0 ]; do + case "$1" in + --arch) ARCH="$2"; shift 2 ;; + --skip-build) SKIP_BUILD=1; shift ;; + -h | --help) sed -n '2,16p' "$0"; exit 0 ;; + *) echo "unknown argument: $1" >&2; exit 2 ;; + esac +done +case "$ARCH" in + universal) TARGETS=(aarch64-apple-darwin x86_64-apple-darwin) ;; + aarch64) TARGETS=(aarch64-apple-darwin) ;; + x86_64) TARGETS=(x86_64-apple-darwin) ;; + *) echo "unknown --arch $ARCH" >&2; exit 2 ;; +esac + +# Keep in sync with LSMinimumSystemVersion in Info.plist.in. +export MACOSX_DEPLOYMENT_TARGET=11.0 +IDENTITY="${MACOS_SIGN_IDENTITY:--}" +SHORT_VERSION="${VERSION%%-*}" +WORK="$CARGO_TARGET_DIR/macos-package" +APP="$WORK/MaterialCraft.app" +DMG="$DIST/materialcraft-$VERSION-macos-$ARCH.dmg" +CLI_ZIP="$DIST/materialcraft-cli-$VERSION-macos-$ARCH.zip" + +NOTARIZE=0 +if [ "$IDENTITY" = "-" ]; then + warn "macOS: ad-hoc signing (no MACOS_SIGN_IDENTITY); artifacts are not notarized" +elif [ -n "${APPLE_ID:-}" ] && [ -n "${APPLE_PASSWORD:-}" ] && [ -n "${APPLE_TEAM_ID:-}" ]; then + NOTARIZE=1 +else + warn "macOS: APPLE_ID / APPLE_PASSWORD / APPLE_TEAM_ID incomplete; signed but not notarized" +fi + +echo "==> MaterialCraft $VERSION for macOS ($ARCH), identity: $IDENTITY, notarize: $NOTARIZE" + +# ---- build ------------------------------------------------------------------------------------- +if [ "$SKIP_BUILD" = 0 ]; then + args=() + for t in "${TARGETS[@]}"; do args+=(--target "$t"); done + (cd "$ROOT" && cargo build --release --locked -p materialcraft -p materialcraft-cli "${args[@]}") +fi + +rm -rf "$WORK" +mkdir -p "$WORK/bin" +for bin in materialcraft materialcraft-cli; do + inputs=() + for t in "${TARGETS[@]}"; do inputs+=("$CARGO_TARGET_DIR/$t/release/$bin"); done + lipo -create -output "$WORK/bin/$bin" "${inputs[@]}" + lipo -info "$WORK/bin/$bin" +done + +# ---- signing helpers --------------------------------------------------------------------------- +sign() { + # Hardened runtime + secure timestamp for a real identity; ad-hoc can't be timestamped. + local ts=(--timestamp) + [ "$IDENTITY" = "-" ] && ts=(--timestamp=none) + local kc=() + [ -n "${MACOS_KEYCHAIN:-}" ] && kc=(--keychain "$MACOS_KEYCHAIN") + codesign --force --sign "$IDENTITY" ${kc[@]+"${kc[@]}"} "${ts[@]}" "$@" +} + +notarize() { + local file="$1" out id status + echo "==> notarizing $(basename "$file") (this can take a few minutes)" + out="$(xcrun notarytool submit "$file" --apple-id "$APPLE_ID" --password "$APPLE_PASSWORD" \ + --team-id "$APPLE_TEAM_ID" --wait --timeout 1h --output-format json)" || true + echo "$out" + id="$(printf '%s' "$out" | plutil -extract id raw -o - - 2>/dev/null || true)" + status="$(printf '%s' "$out" | plutil -extract status raw -o - - 2>/dev/null || true)" + if [ "$status" != "Accepted" ]; then + if [ -n "$id" ]; then + xcrun notarytool log "$id" --apple-id "$APPLE_ID" --password "$APPLE_PASSWORD" --team-id "$APPLE_TEAM_ID" || true + fi + echo "error: notarization of $(basename "$file") failed (status: ${status:-unknown})" >&2 + exit 1 + fi +} + +# ---- MaterialCraft.app ---------------------------------------------------------------------------- +echo "==> assembling $APP" +mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources" +# Executable and icon carry the display name (CFBundleExecutable / CFBundleIconFile). +cp "$WORK/bin/materialcraft" "$APP/Contents/MacOS/MaterialCraft" +cp "$ROOT/assets/app-icon/materialcraft.icns" "$APP/Contents/Resources/MaterialCraft.icns" +sed -e "s/@VERSION@/$VERSION/g" -e "s/@SHORT_VERSION@/$SHORT_VERSION/g" \ + -e "s/@BUILD_SHA@/${MATERIALCRAFT_BUILD_SHA:-unknown}/g" \ + "$HERE/Info.plist.in" >"$APP/Contents/Info.plist" +plutil -lint "$APP/Contents/Info.plist" +printf 'APPL????' >"$APP/Contents/PkgInfo" +# Licences and notices travel inside the bundle (sealed by the signature below). +copy_docs "$APP/Contents/Resources" + +# Sign inside-out: nested code first, then the bundle itself (no --deep on the final signature). +# Today the only nested code is the main executable; frameworks/helpers would be signed here too. +sign --options runtime --entitlements "$HERE/entitlements.plist" "$APP/Contents/MacOS/MaterialCraft" +sign --options runtime --entitlements "$HERE/entitlements.plist" "$APP" +codesign --verify --strict --deep --verbose=2 "$APP" + +if [ "$NOTARIZE" = 1 ]; then + ditto -c -k --keepParent "$APP" "$WORK/MaterialCraft-notarize.zip" + notarize "$WORK/MaterialCraft-notarize.zip" + xcrun stapler staple "$APP" + xcrun stapler validate "$APP" + spctl --assess --type execute -vvv "$APP" +fi + +# ---- DMG --------------------------------------------------------------------------------------- +echo "==> building $DMG" +STAGE="$WORK/dmg" +mkdir -p "$STAGE" +ditto "$APP" "$STAGE/MaterialCraft.app" +ln -s /Applications "$STAGE/Applications" +rm -f "$DMG" "$WORK/raw.dmg" +# makehybrid + convert builds the image without attaching a device, unlike `create -srcfolder`, +# which is flaky on CI runners ("Resource busy") and hangs in sandboxed sessions. +hdiutil makehybrid -hfs -hfs-volume-name "MaterialCraft $VERSION" -hfs-openfolder "$STAGE" -o "$WORK/raw.dmg" "$STAGE" +hdiutil convert "$WORK/raw.dmg" -format UDZO -imagekey zlib-level=9 -o "$DMG" +rm -f "$WORK/raw.dmg" +sign "$DMG" +codesign --verify --strict --verbose=2 "$DMG" +if [ "$NOTARIZE" = 1 ]; then + notarize "$DMG" + xcrun stapler staple "$DMG" + xcrun stapler validate "$DMG" + spctl --assess --type open --context context:primary-signature -vvv "$DMG" +fi + +# ---- CLI --------------------------------------------------------------------------------------- +echo "==> building $CLI_ZIP" +CLI_DIR="$WORK/materialcraft-cli-$VERSION-macos-$ARCH" +mkdir -p "$CLI_DIR" +cp "$WORK/bin/materialcraft-cli" "$CLI_DIR/" +copy_docs "$CLI_DIR" +# Same Developer ID and hardened runtime as the app, with an explicit reverse-DNS identifier +# (codesign would otherwise use the bare file name). +sign --options runtime --identifier ai.storyteller.materialcraft-cli "$CLI_DIR/materialcraft-cli" +codesign --verify --strict --verbose=2 "$CLI_DIR/materialcraft-cli" +rm -f "$CLI_ZIP" +ditto -c -k --keepParent "$CLI_DIR" "$CLI_ZIP" +# notarytool accepts a zip of the bare binary. A bare Mach-O can't carry a stapled ticket, so +# Gatekeeper looks the notarization up online when a quarantined copy first runs. +if [ "$NOTARIZE" = 1 ]; then notarize "$CLI_ZIP"; fi + +"$WORK/bin/materialcraft-cli" --version +echo "==> done (check the artifacts as shipped with packaging/macos/verify.sh --arch $ARCH)" +ls -lh "$DMG" "$CLI_ZIP" diff --git a/packaging/macos/verify.sh b/packaging/macos/verify.sh new file mode 100644 index 00000000..a5ba207a --- /dev/null +++ b/packaging/macos/verify.sh @@ -0,0 +1,149 @@ +#!/usr/bin/env bash +# Check the macOS release artifacts exactly as users download them: +# +# $DIST/materialcraft--macos-.dmg signed, notarized, ticket stapled +# $DIST/materialcraft-cli--macos-.zip unpacked here; the binary inside must be +# Developer ID signed with the hardened runtime, +# timestamped and notarized +# +# Usage: packaging/macos/verify.sh [--arch universal|aarch64|x86_64] +# +# With a real signing identity and notarization credentials in the environment (the same +# MACOS_SIGN_IDENTITY / APPLE_ID / APPLE_PASSWORD / APPLE_TEAM_ID that package.sh uses), every +# check is strict and a failure exits non-zero. Without them (local ad-hoc builds, or a release run +# whose secrets are missing) only the signature's integrity is checked and the rest is a warning, +# matching package.sh. Nothing here reads or prints a secret's value; it only tests whether one is set. +# +# A bare Mach-O can't carry a stapled notarization ticket (only .app, .dmg and .pkg can), so for the +# CLI Gatekeeper looks the ticket up online the first time a quarantined copy runs. `spctl --assess +# --type install` does that same online lookup here, which is how this script proves the CLI was +# notarized. +set -euo pipefail +# shellcheck source=../env.sh +. "$(dirname "${BASH_SOURCE[0]}")/../env.sh" + +ARCH=universal +while [ $# -gt 0 ]; do + case "$1" in + --arch) ARCH="$2"; shift 2 ;; + -h | --help) sed -n '2,20p' "$0"; exit 0 ;; + *) echo "unknown argument: $1" >&2; exit 2 ;; + esac +done +case "$ARCH" in + universal) WANT_ARCHS="x86_64 arm64" ;; + aarch64) WANT_ARCHS="arm64" ;; + x86_64) WANT_ARCHS="x86_64" ;; + *) echo "unknown --arch $ARCH" >&2; exit 2 ;; +esac + +DMG="$DIST/materialcraft-$VERSION-macos-$ARCH.dmg" +CLI_ZIP="$DIST/materialcraft-cli-$VERSION-macos-$ARCH.zip" +IDENTITY="${MACOS_SIGN_IDENTITY:--}" +STRICT=0 +if [ "$IDENTITY" != "-" ] && [ -n "${APPLE_ID:-}" ] && [ -n "${APPLE_PASSWORD:-}" ] && [ -n "${APPLE_TEAM_ID:-}" ]; then + STRICT=1 +fi + +FAILED=0 +fail() { + if [ "$STRICT" = 1 ]; then + echo "error: $*" >&2 + FAILED=1 + else + warn "$* (expected without signing secrets)" + fi +} + +# spctl's online ticket lookup can lag a few seconds behind notarytool's "Accepted". +assess() { + local out attempt tries=1 + [ "$STRICT" = 1 ] && tries=5 + for attempt in $(seq "$tries"); do + if out="$(spctl "$@" 2>&1)"; then + printf '%s\n' "$out" + return 0 + fi + [ "$attempt" = "$tries" ] || sleep 10 + done + printf '%s\n' "$out" + return 1 +} + +for f in "$DMG" "$CLI_ZIP"; do + if [ ! -f "$f" ]; then + echo "error: missing $f" >&2 + exit 1 + fi +done + +WORK="$(mktemp -d "${RUNNER_TEMP:-${TMPDIR:-/tmp}}/materialcraft-verify.XXXXXX")" +trap 'rm -rf "$WORK"' EXIT + +# ---- CLI zip ----------------------------------------------------------------------------------- +echo "==> $(basename "$CLI_ZIP")" +ditto -x -k "$CLI_ZIP" "$WORK/cli" +CLI="$WORK/cli/materialcraft-cli-$VERSION-macos-$ARCH/materialcraft-cli" +if [ ! -x "$CLI" ]; then + echo "error: $(basename "$CLI_ZIP") has no executable materialcraft-cli-$VERSION-macos-$ARCH/materialcraft-cli" >&2 + exit 1 +fi + +archs="$(lipo -archs "$CLI")" +for a in $WANT_ARCHS; do + case " $archs " in + *" $a "*) ;; + *) echo "error: materialcraft-cli lacks $a (has: $archs)" >&2; exit 1 ;; + esac +done + +# Integrity first: this must hold even for ad-hoc builds. +codesign --verify --strict --verbose=2 "$CLI" +details="$(codesign -d --verbose=2 "$CLI" 2>&1)" +printf '%s\n' "$details" | grep -E '^(Identifier|Format|CodeDirectory|Authority|Timestamp|TeamIdentifier)[= ]' || true + +printf '%s\n' "$details" | grep -Eq '^CodeDirectory .*flags=0x[0-9a-f]+\([^)]*runtime' \ + || fail "materialcraft-cli is not signed with the hardened runtime" +printf '%s\n' "$details" | grep -q '^Authority=Developer ID Application:' \ + || fail "materialcraft-cli is not signed with a Developer ID Application identity" +printf '%s\n' "$details" | grep -q '^Timestamp=' \ + || fail "materialcraft-cli signature has no secure timestamp" +if [ -n "${APPLE_TEAM_ID:-}" ]; then + printf '%s\n' "$details" | grep -qx "TeamIdentifier=$APPLE_TEAM_ID" \ + || fail "materialcraft-cli is signed by a different team" +fi +if gk="$(assess --assess --type install -vv "$CLI")"; then + printf '%s\n' "$gk" + printf '%s\n' "$gk" | grep -q 'source=Notarized Developer ID' \ + || fail "Gatekeeper accepts materialcraft-cli but not as notarized" +else + printf '%s\n' "$gk" + fail "Gatekeeper rejects materialcraft-cli (not notarized?)" +fi +"$CLI" --version + +# ---- DMG --------------------------------------------------------------------------------------- +echo "==> $(basename "$DMG")" +codesign --verify --strict --verbose=2 "$DMG" +if [ "$STRICT" = 1 ]; then + xcrun stapler validate "$DMG" || fail "no notarization ticket stapled to the DMG" + assess --assess --type open --context context:primary-signature -vv "$DMG" \ + || fail "Gatekeeper rejects the DMG" +fi + +if [ "$FAILED" != 0 ]; then + echo "error: macOS artifacts failed verification" >&2 + exit 1 +fi + +if [ "$STRICT" = 1 ]; then + result="signed (Developer ID, hardened runtime), notarized; DMG stapled" +else + result="signature intact; Developer ID and notarization not required (no signing secrets)" +fi +echo "==> verified: $result" +if [ -n "${GITHUB_STEP_SUMMARY:-}" ]; then + { + echo "- macOS \`$(basename "$DMG")\`, \`$(basename "$CLI_ZIP")\`: $result" + } >>"$GITHUB_STEP_SUMMARY" +fi diff --git a/packaging/web/.htaccess b/packaging/web/.htaccess new file mode 100644 index 00000000..7b7e6e18 --- /dev/null +++ b/packaging/web/.htaccess @@ -0,0 +1,16 @@ +# Apache (see HOSTING.md). Needs mod_mime; mod_deflate and mod_headers are optional. +AddType application/wasm .wasm +AddType text/javascript .js + + + AddOutputFilterByType DEFLATE application/wasm text/javascript text/html + + + + + Header set Cache-Control "public, max-age=31536000, immutable" + + + Header set Cache-Control "no-cache" + + diff --git a/packaging/web/README.md b/packaging/web/README.md new file mode 100644 index 00000000..231f8128 --- /dev/null +++ b/packaging/web/README.md @@ -0,0 +1,88 @@ +# Hosting MaterialCraft for the web + +`materialcraft-web-.zip` (from the GitHub release, or `packaging/web/package.sh`) holds a +static site in `materialcraft-web-/`: + +| File | What it is | +|---|---| +| `index.html` | The page. It loads everything through relative URLs. | +| `materialcraft-web-.js` | wasm-bindgen glue (generated by trunk, ES module) | +| `materialcraft-web-_bg.wasm` | The app (built with the `wasm-release` Cargo profile) | +| `_headers`, `.htaccess` | Sample header rules for Netlify/Cloudflare Pages and Apache | + +There is no server-side code and no hand-written JavaScript: trunk generates the glue from the +Rust crate `apps/materialcraft-web`. Upload the folder's contents anywhere that serves static files. + +`packaging/web/package.sh` fails the build when a `.wasm` grows past 24 MiB, because Cloudflare +Pages and Workers reject any file over 25 MiB. + +## Any path works + +All URLs in `index.html` are relative (`public_url = "./"` in `apps/materialcraft-web/Trunk.toml`), +so the site works at a domain root (`https://example.com/`), under a prefix +(`https://example.com/tools/materialcraft/`) and from a CDN bucket. The asset names carry a content +hash, so they can be cached forever. Only `index.html` needs revalidation. + +## Required server settings + +- **MIME type:** serve `.wasm` as `application/wasm`. Browsers refuse to stream-compile it under + any other type, and the app then loads slowly or not at all. Serve `.js` as `text/javascript`. + For nginx, check that `mime.types` has `application/wasm wasm;`. +- **Compression:** turn on gzip or Brotli for `.wasm`, `.js` and `.html` (a wasm file typically + shrinks to well under half). You can also precompress (`brotli -k *.wasm`) and let the server + send `Content-Encoding: br`. +- **Caching:** `Cache-Control: public, max-age=31536000, immutable` on the hashed `.wasm` and + `.js` files, and `no-cache` on `index.html`. +- **HTTPS:** WebGPU (and the clipboard) only work in a secure context, which means `https://` + or `http://localhost`. Over plain HTTP elsewhere, the app falls back to WebGL2. +- **No special isolation headers:** the app doesn't use `SharedArrayBuffer`, so it doesn't need + `Cross-Origin-Opener-Policy` or `Cross-Origin-Embedder-Policy`. If your site already sends COEP + `require-corp`, also send `Cross-Origin-Resource-Policy: same-origin` (or `cross-origin` when + the files live on a CDN) on the app's files. + +nginx example: + +```nginx +location /materialcraft/ { + types { application/wasm wasm; text/javascript js; text/html html; } + gzip on; + gzip_types application/wasm text/javascript text/html; + location ~* \.(wasm|js)$ { add_header Cache-Control "public, max-age=31536000, immutable"; } + location ~* index\.html$ { add_header Cache-Control "no-cache"; } +} +``` + +Local test: `python3 -m http.server 8765` inside the folder, then open http://localhost:8765/. + +## Embedding in a page (iframe) + +```html + +``` + +- The app fills the iframe and follows its size, so size the iframe and not the app. +- Keyboard shortcuts go to the iframe after the user clicks into it, as with any embedded app. +- **Sandboxed iframes** need at least + `sandbox="allow-scripts allow-same-origin allow-downloads allow-popups"`. Without + `allow-same-origin` there's no storage. Without `allow-downloads`, Save and Export (browser + downloads) are blocked. +- Don't send `X-Frame-Options: DENY` or a `frame-ancestors` CSP that excludes the embedding page. + +## Renderer selection and fallback flags + +MaterialCraft renders with wgpu. It uses **WebGPU** when the browser has it and falls back to +**WebGL2** on its own. URL query flags override this, and they work on the iframe `src` too: + +| Flag | Effect | +|---|---| +| *(none)* | WebGPU if available, otherwise WebGL2 | +| `?webgl` | Force the WebGL2 backend (useful when a WebGPU driver misbehaves, and for headless smoke tests) | + +The viewport needs a GPU backend, so there is no CPU-only mode. A browser with neither WebGPU nor +WebGL2 gets a message in place of the app. diff --git a/packaging/web/_headers b/packaging/web/_headers new file mode 100644 index 00000000..fac0fbe1 --- /dev/null +++ b/packaging/web/_headers @@ -0,0 +1,13 @@ +# Netlify / Cloudflare Pages header rules (see HOSTING.md). Other hosts: set the same headers. +/* + X-Content-Type-Options: nosniff + +/*.wasm + Content-Type: application/wasm + Cache-Control: public, max-age=31536000, immutable + +/*.js + Cache-Control: public, max-age=31536000, immutable + +/index.html + Cache-Control: no-cache diff --git a/packaging/web/package.sh b/packaging/web/package.sh new file mode 100644 index 00000000..895c522b --- /dev/null +++ b/packaging/web/package.sh @@ -0,0 +1,56 @@ +#!/usr/bin/env bash +# Build the browser version and zip it: $DIST/materialcraft-web-.zip +# +# Usage: packaging/web/package.sh [--skip-build] +# +# Needs: trunk (brew install trunk / cargo install trunk --locked) and the wasm32-unknown-unknown +# target. The zip holds a self-contained static site in materialcraft-web-/ that works +# from any URL path and inside an