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 <noreply@anthropic.com>
This commit is contained in:
bflatasticandClaude Opus 5.5 committed 2026-11-02 02:58:46 +07:00
commit 6e952a9a10
118 files changed
+19000

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
[alias]
xtask = "run -p xtask --"
+6
View File
@@ -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]"
+5
View File
@@ -0,0 +1,5 @@
* text=auto eol=lf
*.png binary
*.ico binary
*.icns binary
*.ps1 text eol=crlf
+4
View File
@@ -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
+30
View File
@@ -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
+36
View File
@@ -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
+23
View File
@@ -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
+45
View File
@@ -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 }}
+33
View File
@@ -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"
+11
View File
@@ -0,0 +1,11 @@
*~
plan/
/target
target/
/dist
/corpus
/log
/secrets
/temp
/craft-fonts
*.mcraft.tmp
+5
View File
@@ -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.
Generated
+791
View File
@@ -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"
+106
View File
@@ -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
+177
View File
@@ -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
+21
View File
@@ -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.
+26
View File
@@ -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-<family>.txt.
+4
View File
@@ -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
+14
View File
@@ -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 }
+67
View File
@@ -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<Option<u32>>,
/// The constant (`const_*`), the variable name (`get_*`) or the input index (`sample_*`).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<Value>,
#[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<FnNode>,
#[serde(default)]
pub output: Option<u32>,
}
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<Value>) -> 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
}
}
+420
View File
@@ -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<String, Value>,
/// Parameters driven by a graph input (param id → exposed input id).
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub bindings: BTreeMap<String, String>,
#[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<String>,
}
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<Node>,
pub connections: Vec<Connection>,
#[serde(default)]
pub frames: Vec<Frame>,
#[serde(default)]
pub comments: Vec<Comment>,
#[serde(default)]
pub pins: Vec<Pin>,
/// 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<ExposedParam>,
/// Current values of the exposed inputs (missing = default).
#[serde(default)]
pub inputs: BTreeMap<String, Value>,
#[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<NodeId> {
let mut indeg: BTreeMap<NodeId, usize> = 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<NodeId> = 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<NodeId> {
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<NodeId> {
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);
}
}
+32
View File
@@ -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<T> = std::result::Result<T, CoreError>;
+68
View File
@@ -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<Vec<u8>>,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Package {
pub name: String,
pub graphs: Vec<Graph>,
#[serde(default)]
pub resources: Vec<Resource>,
/// 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())
}
}
+340
View File
@@ -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<CurvePoint>,
}
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<GradientKey>,
}
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<crate::function::FnGraph>),
}
impl Value {
pub fn as_f32(&self) -> Option<f32> {
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<i32> {
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<bool> {
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<Value> {
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<Vec<f32>> {
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::<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<CurvePoint> =
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<f32> = 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);
}
}
+19
View File
@@ -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 }
+141
View File
@@ -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<J>;
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<Vec<CommandSpec>> = 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<J> {
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<String>) -> EngineError {
EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }
}
pub(crate) fn f32p(p: &J, key: &str) -> Option<f32> {
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<u64> {
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<i64> {
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<bool> {
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<NodeId> {
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<Vec<NodeId>> {
let ids: Vec<NodeId> = 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])
}
+175
View File
@@ -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<CommandSpec> {
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<Clip> {
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<J> {
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<J> {
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<Vec<NodeId>> {
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<NodeId, NodeId> = 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<J> {
let clip = match p.get("clip") {
Some(c) => serde_json::from_value::<Clip>(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::<Vec<_>>()}))
})
}
fn duplicate(s: &mut Session, p: &J) -> Result<J> {
let ids = ids_param(s, "edit.duplicate", p)?;
let clip = clip_of(s, &ids)?;
let outer: Vec<Connection> = 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::<Vec<_>>()}))
})
}
fn delete(s: &mut Session, p: &J) -> Result<J> {
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<J> {
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()}))
})
}
+234
View File
@@ -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<CommandSpec> {
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::<Vec<_>>()
))),
]
}
fn new_graph(s: &mut Session, p: &J) -> Result<J> {
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<J> {
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<String>) {
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<String>) -> 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<Vec<u8>> {
Ok(materialcraft_formats::save_package(&s.pkg)?)
}
#[cfg(not(target_arch = "wasm32"))]
fn open(s: &mut Session, p: &J) -> Result<J> {
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<J> {
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<J> {
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<J> {
Err(bad("file.save", "the browser saves with a download"))
}
/// One exported file.
pub struct Exported {
pub file: String,
pub bytes: Vec<u8>,
}
/// 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<Depth>) -> Result<Vec<Exported>> {
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<Depth>)> {
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<J> {
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<J> {
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<u8>, name: Option<&str>) -> Result<String> {
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<J> {
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<J> {
Err(bad("file.importBitmap", "the browser imports with the file picker"))
}
+492
View File
@@ -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<CommandSpec> {
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<usize> {
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<J> {
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<J> {
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<J> {
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<J> {
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<J> {
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<J> {
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<J> {
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::<Vec<_>>(),
}))
}
fn attributes(s: &mut Session, p: &J) -> Result<J> {
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<f32> = 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<J> {
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<J> {
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<J> {
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<J> {
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<J> {
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<J> {
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<J> {
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<J> {
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<J> {
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::<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<J> {
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<J> {
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<J> {
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::<Vec<_>>()}))
}
fn select_stream(s: &mut Session, p: &J, up: bool) -> Result<J> {
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<J> {
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<f32> = nodes.iter().map(|n| n.pos[0]).collect();
let ys: Vec<f32> = 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<J> {
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}))
})
}
+65
View File
@@ -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<usize>) -> 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::<Vec<_>>(),
"outputs": outs.iter().map(|p| &p.id).collect::<Vec<_>>(),
"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::<Vec<_>>(),
"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::<Vec<_>>()},
"graphs": s.pkg.graphs.iter().enumerate().map(|(i, g)| json!({"index": i, "name": g.name, "nodes": g.nodes.len(), "kind": g.kind})).collect::<Vec<_>>(),
"openGraph": s.graph,
"graph": graph_json,
"selection": s.selection.iter().map(|i| i.0).collect::<Vec<_>>(),
"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::<Vec<_>>(),
})
}
+53
View File
@@ -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<T> = std::result::Result<T, EngineError>;
/// 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())
}
+290
View File
@@ -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<CommandSpec> {
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<J> {
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<J> {
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<J> {
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<J> {
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<J> {
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(&param).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<J> {
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 &param {
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<J> {
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<J> {
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(&param),
};
Ok(J::Null)
})
}
fn connect(s: &mut Session, p: &J) -> Result<J> {
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<J> {
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<String> {
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<String> {
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()
}
}
+333
View File
@@ -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
}
+314
View File
@@ -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<NodeId>,
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<NodeId>,
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<materialcraft_core::Node>,
pub connections: Vec<materialcraft_core::Connection>,
}
pub struct Session {
pub pkg: Package,
/// Where the package was opened from or last saved to.
pub path: Option<String>,
/// Index of the graph being edited.
pub graph: usize,
pub selection: Vec<NodeId>,
pub view2d: View2d,
pub view3d: View3d,
/// Cap on node output size while editing (`None` = full size).
pub preview_size: Option<u32>,
pub modified: bool,
pub log: Vec<String>,
pub clipboard: Option<Clip>,
/// 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<Mutex<Cache>>,
undo: Vec<Snapshot>,
redo: Vec<Snapshot>,
/// Edits with the same key coalesce into one undo step (slider drags).
merge_key: Option<String>,
decoded: Arc<Mutex<HashMap<String, Image>>>,
}
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<T>(&mut self, label: &str, f: impl FnOnce(&mut Session) -> Result<T>) -> Result<T> {
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<T>(&mut self, key: &str, label: &str, f: impl FnOnce(&mut Session) -> Result<T>) -> Result<T> {
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<T>(&mut self, label: &str, f: impl FnOnce(&mut Session) -> Result<T>) -> Result<T> {
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<String> {
self.undo.iter().map(|s| s.label.clone()).collect()
}
pub fn undo(&mut self) -> Option<String> {
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<String> {
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<Image> + Sync + Send + 'static {
let res: Vec<(String, Arc<Vec<u8>>)> = 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<String>) {
self.log.push(msg.into());
if self.log.len() > 500 {
self.log.remove(0);
}
}
}
+152
View File
@@ -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<CommandSpec> {
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<J> {
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<J> {
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<J> {
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<J> {
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::<Vec<_>>(),
"outputs": d.outputs.iter().map(|p| json!({"id": p.id, "label": p.label, "kind": format!("{:?}", p.kind)})).collect::<Vec<_>>(),
"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::<Vec<_>>(),
})
})
.collect(),
))
}
+114
View File
@@ -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();
}
}
}
+15
View File
@@ -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 }
+490
View File
@@ -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<Port>, Vec<Port>) {
if node.def == "graph_instance" {
let Some((_, sub)) = instance_graph(pkg, node) else { return (Vec::new(), Vec::new()) };
let io = |def: &str| -> Vec<Port> {
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<Vec<Image>>,
pub error: Option<String>,
/// 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<NodeId, NodeResult>,
/// 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<u64, (Arc<Vec<Image>>, 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<Arc<Vec<Image>>> {
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<Vec<Image>>) {
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<u32>,
/// Cook only these nodes and what they depend on (`None` = the whole graph).
pub only: Option<Vec<NodeId>>,
/// Images for the graph's input nodes, by identifier (graph instances).
pub inputs: BTreeMap<String, Image>,
/// Values for the graph's exposed parameters (graph instances), over the graph's own.
pub overrides: BTreeMap<String, Value>,
/// Decodes a package resource (bitmap) by name.
pub resource: &'a (dyn Fn(&str) -> Option<Image> + 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<Image> + 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, 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<std::collections::BTreeSet<NodeId>> = opts.only.as_ref().map(|ids| {
let mut s: std::collections::BTreeSet<NodeId> = 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<String, Value> = 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<String, Value>, 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<Option<Image>> = Vec::with_capacity(in_ports.len());
let mut in_keys: Vec<u64> = 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(&params).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<Vec<Image>, 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, &params, (w, h), opts, cache)
} else if let Some(d) = def {
let ctx = Ctx { w, h, seed, tile, inputs: &inputs, params: &params, 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<Image>],
params: &BTreeMap<String, Value>,
size: (u32, u32),
opts: &Options,
cache: &mut Cache,
) -> Result<Vec<Image>, 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::time::Instant> = 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<Image> {
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);
}
}
+17
View File
@@ -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 }
+271
View File
@@ -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<T> = std::result::Result<T, FormatError>;
/// 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<Vec<u8>> {
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<Package> {
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<Image> {
// 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<f32> = 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<f32> = 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<Vec<u8>> {
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<f32> = (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<u16> = (0..n).flat_map(|i| px(i).map(q16)).collect();
image::ImageBuffer::<image::Rgba<u16>, _>::from_raw(w, h, data).ok_or_else(|| FormatError::Image("bad buffer".into()))?.into()
} else {
let data: Vec<u16> = (0..n).map(|i| q16(px(i)[0])).collect();
image::ImageBuffer::<image::Luma<u16>, _>::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<u8> = (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<u8> = (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<u8> = (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");
}
}
+16
View File
@@ -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 }
+494
View File
@@ -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<Node>,
/// Triangle vertices in BVH order.
tris: Vec<[Vec3; 3]>,
/// Original triangle index of each entry in `tris`.
order: Vec<u32>,
}
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<u32> = (0..tris.len() as u32).collect();
let cent: Vec<Vec3> = 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<usize>| {
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<Item = (Vec3, Vec3, u32, u32)> + '_ {
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<f32> {
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<Hit> {
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<Hit> {
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<Hit> {
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<Hit> {
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<f32> = 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());
}
}
+140
View File
@@ -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<Vec3> {
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);
}
}
+195
View File
@@ -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<u32>,
/// 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<u32>> = 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<bool> {
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<Surface> {
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<Surface> {
let [a, b, c] = mesh.tri(t as usize)?;
let b0 = 1.0 - b1 - b2;
let p = |v: &[Vec3]| -> Option<Vec3> { 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);
}
}
}
}
+28
View File
@@ -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<T> = std::result::Result<T, GeomError>;
+432
View File
@@ -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<Vec3>,
pub normals: Vec<Vec3>,
/// xyz tangent, w bitangent sign.
pub tangents: Vec<Vec4>,
pub uvs: Vec<Vec2>,
/// RGBA vertex colors in 0..1 (glTF: linear; OBJ, PLY: as stored): one per vertex, or empty.
pub colors: Vec<Vec4>,
pub indices: Vec<u32>,
/// Index ranges per material and part (node / object); `name` is the part name.
pub submeshes: Vec<SubMesh>,
pub materials: Vec<String>,
}
/// 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<usize> {
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<Item = usize> + '_ {
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<usize> = 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::<Vec2>() / 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<Vec3>, normals: Option<Vec<Vec3>>, uvs: Vec<Vec2>, indices: Vec<u32>, material: &str) -> Result<Mesh> {
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<_>>(), 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<_>>(), vec![(1, 0)]);
assert_eq!(m.uv_tiles(0).into_iter().collect::<Vec<_>>(), vec![(0, 0)]);
}
}
+399
View File
@@ -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<Vec3>,
n: Vec<Vec3>,
uv: Vec<Vec2>,
idx: Vec<u32>,
}
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<f32> {
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:<id>` in project files).
pub fn builtin(id: &str) -> Option<Mesh> {
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<_>>(), 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);
}
}
+384
View File
@@ -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<u32> {
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<usize> {
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<Option<Vec3>> = 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<usize> = (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<Chart> = 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<usize> = charts.iter().map(|c| c.material).collect();
for m in mats {
let ids: Vec<usize> = (0..charts.len()).filter(|i| charts[*i].material == m).collect();
let sizes: Vec<Vec2> = 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<Vec2>)> {
let mut order: Vec<usize> = (0..sizes.len()).collect();
order.sort_by(|a, b| sizes[*b].y.total_cmp(&sizes[*a].y));
let place = |s: f32, res: f32| -> Option<Vec<Vec2>> {
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());
}
}
+13
View File
@@ -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 }
+339
View File
@@ -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<Vec<f32>>,
}
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<u8> {
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);
}
}
+14
View File
@@ -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 }
+524
View File
@@ -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<NodeDef> {
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<f32> = (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<f32> = 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<Image>]) -> 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),
}
}
+356
View File
@@ -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<Image>],
pub params: &'a BTreeMap<String, Value>,
/// The package's bitmap resources, decoded on demand.
pub resource: &'a (dyn Fn(&str) -> Option<Image> + Sync),
/// Exposed graph inputs (for `get_*` nodes in function graphs).
pub vars: &'a BTreeMap<String, Value>,
}
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<Image> {
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<Vec<Image>, 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<PortDef>,
pub outputs: Vec<PortDef>,
pub params: Vec<ParamDef>,
/// 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<usize> {
self.inputs.iter().position(|p| p.id == id)
}
pub fn output_index(&self, id: &str) -> Option<usize> {
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<Vec<NodeDef>> = 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<String, Value>) -> BTreeMap<String, Value> {
let mut m: BTreeMap<String, Value> = 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
}
+951
View File
@@ -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<NodeDef> {
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<Image> = (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<f32> = (-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<Image> = (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<f32> = (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<f32> = 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) }
})])
}
+395
View File
@@ -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<usize>,
/// Lanes that carry meaning (1 = scalar).
dims: usize,
}
/// A compiled function graph.
#[derive(Clone, Debug)]
pub struct Program {
code: Vec<Instr>,
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<String, Value>, seed: u32) -> Result<Program, String> {
let out = g.output.ok_or("the function has no output node")?;
let mut code: Vec<Instr> = Vec::new();
let mut reg: BTreeMap<u32, usize> = 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<usize> = 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<Image>], 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::<f32>().sqrt(); 4]
}
Op::Normalize => {
let x = a(0);
let l = (0..ins.dims).map(|k| x[k] * x[k]).sum::<f32>().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());
}
}
+412
View File
@@ -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<NodeDef> {
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))
}])
}
+96
View File
@@ -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<Image>], 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: &params, 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: &params, 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);
}
}
+90
View File
@@ -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<NodeDef> {
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])])
}
+184
View File
@@ -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::<f32>() / 10000.0;
assert!((m - 0.5).abs() < 0.02);
}
}
+337
View File
@@ -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<f32> = (-r..=r).map(|i| (-(i * i) as f32 / (2.0 * sigma * sigma)).exp()).collect();
let s: f32 = k.iter().sum();
let k: Vec<f32> = 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<Vec<f32>> = (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<f32> {
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<f32> {
let n = f.len();
let f: Vec<f64> = 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<Vec<f32>> = (0..w)
.into_par_iter()
.map(|x| {
let f: Vec<f32> = (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<Vec<f32>> = (0..h)
.into_par_iter()
.map(|y| {
let f: Vec<f32> = (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<f32>) -> 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);
}
}
}
+548
View File
@@ -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<NodeDef> {
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<usize>> = 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<usize>> = 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
})])
}
+42
View File
@@ -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.
Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

+7
View File
@@ -0,0 +1,7 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="-4 -4 1038.05 108" role="img" aria-label="ArtCraft">
<title>ArtCraft</title>
<g fill="#f2f1ee">
<path transform="scale(1.02564)" d="M104.28,49.49L81.55,0h-31.23l-3.17,4.76L14.75,53.63,0,75.85l21.55,21.55,63.79-36.94,16.99,37.04,14.01-21.74-12.06-26.27ZM32.89,65.66l32.42-48.87,10.91,23.77-43.32,25.09Z"/>
<path d="M142.07824124466492 100.0V-0.20598030646411303H224.5093337988741Q235.3915640626314 -0.20598030646411303 242.47102827716765 4.2448305180051875Q249.55049249170392 8.695641342474488 253.08388530613996 15.97633917894725Q256.617278120576 23.25703701542001 256.617278120576 31.917827817510926Q256.617278120576 41.29161779108965 252.08564909759403 49.09045161033163Q247.55402007461208 56.88928542957361 238.35448280295117 61.38287869556304L259.0352045196513 100.0H227.60565795214035L210.562880671027 66.09194563707179H169.9554082596294V100.0ZM169.9554082596294 45.01525167126002H215.67753779224603Q221.38490322307234 45.01525167126002 224.71075426312564 41.60858243269406Q228.03660530317896 38.201913194128096 228.03660530317896 32.65618416032707Q228.03660530317896 28.910440606208994 226.55352218432876 26.28334868406067Q225.07043906547852 23.656256761912346 222.3149998187698 22.30626765215014Q219.55956057206106 20.956278542387935 215.67753779224603 20.956278542387935H169.9554082596294Z M312.0332229234414 100.0V22.638971534484327H268.35528177627936V-0.20598030646411303H383.5883310855678V22.638971534484327H339.91038993840584V100.0Z M458.27161556705016 101.74927113702624Q437.40714777937706 101.74927113702624 423.46369302582383 95.8454810495627Q409.5202382722706 89.94169096209913 402.57861475134996 78.38287353515625Q395.6369912304293 66.82405610821337 395.6369912304293 49.85422740524781Q395.6369912304293 25.012678585664176 411.6814700222251 11.52871357108691Q427.7259488140208 -1.9552514434903543 458.3064661074337 -1.9552514434903543Q475.456917945535 -1.9552514434903543 488.5083118603833 3.126178886035433Q501.55970577523163 8.20760921556122 508.8958646388887 17.516444792900415Q516.2320235025458 26.82528037023961 516.2320235025458 39.59306099672011H489.03300511868554Q489.03300511868554 33.14733922307762 485.1161317984869 28.595099713294914Q481.1992584782883 24.042860203512205 474.2052968660206 21.62493380443695Q467.21133525375296 19.207007405361693 457.80894061146523 19.207007405361693Q447.110456418681 19.207007405361693 439.60629072478065 22.77368929226266Q432.1021250308803 26.340371179163625 428.1899983952093 32.79558632186133Q424.2778717595383 39.25080146455903 424.2778717595383 47.95918367346938V51.60349854227405Q424.2778717595383 60.27703021080084 428.1899983952093 66.80513165087463Q432.1021250308803 73.33323309094843 439.5587615987329 76.9601226895613Q447.0153981665855 80.5870122881742 457.5934669359459 80.5870122881742Q467.61380249762595 80.5870122881742 474.8010658306936 78.272076042331Q481.98832916376114 75.9571397964878 485.8925238982956 71.46510799841701Q489.79671863283005 66.97307620034621 489.79671863283005 60.61291930974399H516.3175883855861Q516.3175883855861 73.0289470350082 509.2048350985849 82.30767875649144Q502.0920818115837 91.58641047797467 489.08347033825555 96.66784080750045Q476.07485886492736 101.74927113702624 458.27161556705016 101.74927113702624Z M537.413518212595 100.0V-0.20598030646411303H619.8446107668042Q630.7268410305614 -0.20598030646411303 637.8063052450977 4.2448305180051875Q644.885769459634 8.695641342474488 648.41916227407 15.97633917894725Q651.9525550885061 23.25703701542001 651.9525550885061 31.917827817510926Q651.9525550885061 41.29161779108965 647.4209260655241 49.09045161033163Q642.8892970425421 56.88928542957361 633.6897597708812 61.38287869556304L654.3704814875814 100.0H622.9409349200704L605.8981576389571 66.09194563707179H565.2906852275595V100.0ZM565.2906852275595 45.01525167126002H611.0128147601761Q616.7201801910024 45.01525167126002 620.0460312310557 41.60858243269406Q623.371882271109 38.201913194128096 623.371882271109 32.65618416032707Q623.371882271109 28.910440606208994 621.8887991522588 26.28334868406067Q620.4057160334086 23.656256761912346 617.6502767866998 22.30626765215014Q614.8948375399912 20.956278542387935 611.0128147601761 20.956278542387935H565.2906852275595Z M662.6163133024502 100.0 712.0998010683712 -0.20598030646411303H743.193458536939L792.6769463028602 100.0H762.4325672314772L754.402333653671 83.1409687898597H699.2874274093653L691.317401543271 100.0ZM708.9368987701752 62.32096947316873H744.7528622928611L735.0177014874674 40.96197456382106Q734.4092539371304 39.53909915668276 733.2953489896883 36.886650063206076Q732.1814440422461 34.2342009697294 731.007331383092 31.285460002220745Q729.833218723938 28.33671903471209 728.8603396867204 25.901367365445054Q727.8874606495028 23.46601569617802 727.500857207903 22.53754284917092H726.3948841615974Q725.2635539439634 25.272371609078903 723.7978960953051 28.821628225788082Q722.3322382466466 32.37088484249726 720.9822491368843 35.68880398141399Q719.6322600271221 39.00672312033072 718.6720595755688 41.04753944686133Z M807.9674540726534 100.0V-0.20598030646411303H905.8314549324839V20.956278542387935H835.8446210876178V42.14414368565506H898.3527086906836V63.30640253450711H835.8446210876178V100.0Z M958.534680649389 100.0V22.638971534484327H914.856739502227V-0.20598030646411303H1030.0897888115155V22.638971534484327H986.41184Line truncated
</g>
</svg>

After

Width:  |  Height:  |  Size: 5.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

+7
View File
@@ -0,0 +1,7 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="-4 -4 1038.05 108" role="img" aria-label="ArtCraft">
<title>ArtCraft</title>
<g fill="#0b0b0c">
<path transform="scale(1.02564)" d="M104.28,49.49L81.55,0h-31.23l-3.17,4.76L14.75,53.63,0,75.85l21.55,21.55,63.79-36.94,16.99,37.04,14.01-21.74-12.06-26.27ZM32.89,65.66l32.42-48.87,10.91,23.77-43.32,25.09Z"/>
<path d="M142.07824124466492 100.0V-0.20598030646411303H224.5093337988741Q235.3915640626314 -0.20598030646411303 242.47102827716765 4.2448305180051875Q249.55049249170392 8.695641342474488 253.08388530613996 15.97633917894725Q256.617278120576 23.25703701542001 256.617278120576 31.917827817510926Q256.617278120576 41.29161779108965 252.08564909759403 49.09045161033163Q247.55402007461208 56.88928542957361 238.35448280295117 61.38287869556304L259.0352045196513 100.0H227.60565795214035L210.562880671027 66.09194563707179H169.9554082596294V100.0ZM169.9554082596294 45.01525167126002H215.67753779224603Q221.38490322307234 45.01525167126002 224.71075426312564 41.60858243269406Q228.03660530317896 38.201913194128096 228.03660530317896 32.65618416032707Q228.03660530317896 28.910440606208994 226.55352218432876 26.28334868406067Q225.07043906547852 23.656256761912346 222.3149998187698 22.30626765215014Q219.55956057206106 20.956278542387935 215.67753779224603 20.956278542387935H169.9554082596294Z M312.0332229234414 100.0V22.638971534484327H268.35528177627936V-0.20598030646411303H383.5883310855678V22.638971534484327H339.91038993840584V100.0Z M458.27161556705016 101.74927113702624Q437.40714777937706 101.74927113702624 423.46369302582383 95.8454810495627Q409.5202382722706 89.94169096209913 402.57861475134996 78.38287353515625Q395.6369912304293 66.82405610821337 395.6369912304293 49.85422740524781Q395.6369912304293 25.012678585664176 411.6814700222251 11.52871357108691Q427.7259488140208 -1.9552514434903543 458.3064661074337 -1.9552514434903543Q475.456917945535 -1.9552514434903543 488.5083118603833 3.126178886035433Q501.55970577523163 8.20760921556122 508.8958646388887 17.516444792900415Q516.2320235025458 26.82528037023961 516.2320235025458 39.59306099672011H489.03300511868554Q489.03300511868554 33.14733922307762 485.1161317984869 28.595099713294914Q481.1992584782883 24.042860203512205 474.2052968660206 21.62493380443695Q467.21133525375296 19.207007405361693 457.80894061146523 19.207007405361693Q447.110456418681 19.207007405361693 439.60629072478065 22.77368929226266Q432.1021250308803 26.340371179163625 428.1899983952093 32.79558632186133Q424.2778717595383 39.25080146455903 424.2778717595383 47.95918367346938V51.60349854227405Q424.2778717595383 60.27703021080084 428.1899983952093 66.80513165087463Q432.1021250308803 73.33323309094843 439.5587615987329 76.9601226895613Q447.0153981665855 80.5870122881742 457.5934669359459 80.5870122881742Q467.61380249762595 80.5870122881742 474.8010658306936 78.272076042331Q481.98832916376114 75.9571397964878 485.8925238982956 71.46510799841701Q489.79671863283005 66.97307620034621 489.79671863283005 60.61291930974399H516.3175883855861Q516.3175883855861 73.0289470350082 509.2048350985849 82.30767875649144Q502.0920818115837 91.58641047797467 489.08347033825555 96.66784080750045Q476.07485886492736 101.74927113702624 458.27161556705016 101.74927113702624Z M537.413518212595 100.0V-0.20598030646411303H619.8446107668042Q630.7268410305614 -0.20598030646411303 637.8063052450977 4.2448305180051875Q644.885769459634 8.695641342474488 648.41916227407 15.97633917894725Q651.9525550885061 23.25703701542001 651.9525550885061 31.917827817510926Q651.9525550885061 41.29161779108965 647.4209260655241 49.09045161033163Q642.8892970425421 56.88928542957361 633.6897597708812 61.38287869556304L654.3704814875814 100.0H622.9409349200704L605.8981576389571 66.09194563707179H565.2906852275595V100.0ZM565.2906852275595 45.01525167126002H611.0128147601761Q616.7201801910024 45.01525167126002 620.0460312310557 41.60858243269406Q623.371882271109 38.201913194128096 623.371882271109 32.65618416032707Q623.371882271109 28.910440606208994 621.8887991522588 26.28334868406067Q620.4057160334086 23.656256761912346 617.6502767866998 22.30626765215014Q614.8948375399912 20.956278542387935 611.0128147601761 20.956278542387935H565.2906852275595Z M662.6163133024502 100.0 712.0998010683712 -0.20598030646411303H743.193458536939L792.6769463028602 100.0H762.4325672314772L754.402333653671 83.1409687898597H699.2874274093653L691.317401543271 100.0ZM708.9368987701752 62.32096947316873H744.7528622928611L735.0177014874674 40.96197456382106Q734.4092539371304 39.53909915668276 733.2953489896883 36.886650063206076Q732.1814440422461 34.2342009697294 731.007331383092 31.285460002220745Q729.833218723938 28.33671903471209 728.8603396867204 25.901367365445054Q727.8874606495028 23.46601569617802 727.500857207903 22.53754284917092H726.3948841615974Q725.2635539439634 25.272371609078903 723.7978960953051 28.821628225788082Q722.3322382466466 32.37088484249726 720.9822491368843 35.68880398141399Q719.6322600271221 39.00672312033072 718.6720595755688 41.04753944686133Z M807.9674540726534 100.0V-0.20598030646411303H905.8314549324839V20.956278542387935H835.8446210876178V42.14414368565506H898.3527086906836V63.30640253450711H835.8446210876178V100.0Z M958.534680649389 100.0V22.638971534484327H914.856739502227V-0.20598030646411303H1030.0897888115155V22.638971534484327H986.41184Line truncated
</g>
</svg>

After

Width:  |  Height:  |  Size: 5.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

+4
View File
@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="-10 -19.42 136.34 136.34" role="img" aria-label="ArtCraft">
<title>ArtCraft</title>
<path fill="#0b0b0c" d="M104.28,49.49L81.55,0h-31.23l-3.17,4.76L14.75,53.63,0,75.85l21.55,21.55,63.79-36.94,16.99,37.04,14.01-21.74-12.06-26.27ZM32.89,65.66l32.42-48.87,10.91,23.77-43.32,25.09Z"/>
</svg>

After

Width:  |  Height:  |  Size: 341 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

+4
View File
@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="-10 -19.42 136.34 136.34" role="img" aria-label="ArtCraft">
<title>ArtCraft</title>
<path fill="#4e7bfb" d="M104.28,49.49L81.55,0h-31.23l-3.17,4.76L14.75,53.63,0,75.85l21.55,21.55,63.79-36.94,16.99,37.04,14.01-21.74-12.06-26.27ZM32.89,65.66l32.42-48.87,10.91,23.77-43.32,25.09Z"/>
</svg>

After

Width:  |  Height:  |  Size: 341 B

+3
View File
@@ -0,0 +1,3 @@
# shellcheck config for the packaging scripts (CI: .github/workflows/packaging-lint.yml).
source-path=SCRIPTDIR
external-sources=true
+59
View File
@@ -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
}
+110
View File
@@ -0,0 +1,110 @@
#!/usr/bin/env bash
# Build and package MaterialCraft for FreeBSD:
#
# $DIST/materialcraft-<version>-freebsd-x86_64.tar.gz a /usr/local-style tree:
# materialcraft-<version>-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-<version>-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"
+54
View File
@@ -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; }
# The full tile at 1024 px (docs, stores).
render "$SVG" 1024 "$DIR/materialcraft-1024.png"
# Linux hicolor theme (the 256 one is also the runtime window icon and the README icon).
for s in 16 24 32 48 64 128 256 512; do
mkdir -p "$DIR/hicolor/${s}x${s}/apps"
render "$SVG" "$s" "$DIR/hicolor/${s}x${s}/apps/$ID.png"
done
mkdir -p "$DIR/hicolor/scalable/apps"
cp "$DIR/materialcraft-small.svg" "$DIR/hicolor/scalable/apps/$ID.svg"
xtask() { (cd "$ROOT" && cargo run -q -p xtask -- "$@"); }
# Windows .ico.
ICO_PNGS=()
for s in 16 20 24 32 40 48 64 128 256; do
render "$SVG" "$s" "$TMP/ico-$s.png"
ICO_PNGS+=("$TMP/ico-$s.png")
done
xtask ico "$DIR/materialcraft.ico" "${ICO_PNGS[@]}"
# macOS .icns (the same PNG slots iconutil writes).
ICNS_PNGS=()
for s in 16 32 64 128 256 512 1024; do
render "$MAC" "$s" "$TMP/icns-$s.png"
ICNS_PNGS+=("$TMP/icns-$s.png")
done
xtask icns "$DIR/materialcraft.icns" "${ICNS_PNGS[@]}"
echo "icons written to $DIR"
+72
View File
@@ -0,0 +1,72 @@
#!/bin/sh
# MaterialCraft AppImage entry point (packaging/linux/AppRun; installed by package.sh).
#
# On Wayland the compositor resolves a window's dock icon by taking the window's
# app_id (ai.storyteller.materialcraft) and looking up an installed .desktop file.
# An AppImage installs nothing, so every AppImage run would otherwise show the
# generic "Wayland" icon. Best-effort desktop integration: on first run
# (and whenever the AppImage's path changes) install the .desktop entry and the
# hicolor icons into $XDG_DATA_HOME, then launch. Every failure here must leave
# the launch untouched. Opt out with MATERIALCRAFT_NO_DESKTOP_INTEGRATION=1.
set -u
APPDIR="$(dirname "$(readlink -f "$0")")"
DESK_ID=ai.storyteller.materialcraft
integrate() {
case "${MATERIALCRAFT_NO_DESKTOP_INTEGRATION:-}" in
1 | true | yes) return 0 ;;
esac
# The AppImage runtime exports $APPIMAGE; without it (an extracted AppDir) there
# is no path to register and nothing to do.
appimage="${APPIMAGE:-}"
[ -n "$appimage" ] && [ -f "$appimage" ] || return 0
appimage="$(readlink -f "$appimage")" || return 0
# Exec= is parsed by the desktop: a path holding a quote, backquote, dollar, backslash,
# percent or a line break would need escaping (or could add lines), so skip integration.
case "$appimage" in
*[\"\`\$\\%]* | *'
'*) return 0 ;;
esac
home="${HOME:-}"
[ -n "$home" ] || return 0
data="${XDG_DATA_HOME:-$home/.local/share}"
src_desktop="$APPDIR/usr/share/applications/$DESK_ID.desktop"
[ -f "$src_desktop" ] || return 0
# Rewrite Exec to this AppImage (the binary is not on the host PATH) and drop
# TryExec, which would hide the entry; everything else is shipped as packaged.
apps="$data/applications"
mkdir -p "$apps" 2>/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" "$@"
@@ -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;
@@ -0,0 +1,65 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- AppStream metadata (software centres, Flathub). Template: package.sh and the Flatpak
manifest substitute @VERSION@ and @DATE@ from Cargo.toml and the build date. -->
<component type="desktop-application">
<id>ai.storyteller.materialcraft</id>
<metadata_license>CC0-1.0</metadata_license>
<project_license>MIT OR Apache-2.0</project_license>
<name>MaterialCraft</name>
<summary>Design procedural PBR materials with node graphs</summary>
<developer id="ai.storyteller">
<name>Learning Machines LLC</name>
</developer>
<description>
<p>
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.
</p>
<ul>
<li>Hundreds of procedural nodes: noises, patterns, adjustments, blurs, warps, normal and height tools</li>
<li>Live 2D and 3D previews with physically based shading</li>
<li>Export base color, normal, roughness, metallic, height and ambient occlusion maps as PNG, EXR, TGA, JPEG or TIFF; save packages as .mcraft</li>
<li>Every action is a command, scriptable from a CLI, a JSON control channel and an MCP server</li>
</ul>
</description>
<launchable type="desktop-id">ai.storyteller.materialcraft.desktop</launchable>
<icon type="stock">ai.storyteller.materialcraft</icon>
<!-- Only url types known to appstream 0.15 (Ubuntu 22.04, where CI validates): no vcs-browser. -->
<url type="homepage">https://getartcraft.com/apps/materialcraft</url>
<url type="bugtracker">https://github.com/storytold/materialcraft/issues</url>
<url type="help">https://github.com/storytold/materialcraft</url>
<url type="contact">https://discord.gg/artcraft</url>
<categories>
<category>Graphics</category>
<category>3DGraphics</category>
</categories>
<keywords>
<keyword>procedural</keyword>
<keyword>material</keyword>
<keyword>node graph</keyword>
<keyword>pbr</keyword>
<keyword>3d</keyword>
<keyword>mesh</keyword>
</keywords>
<branding>
<color type="primary" scheme_preference="light">#a8e3ef</color>
<color type="primary" scheme_preference="dark">#0e5f72</color>
</branding>
<requires>
<display_length compare="ge">760</display_length>
</requires>
<supports>
<control>keyboard</control>
<control>pointing</control>
<control>tablet</control>
</supports>
<provides>
<binary>materialcraft</binary>
<mediatype>application/x-materialcraft</mediatype>
</provides>
<content_rating type="oars-1.1"/>
<releases>
<release version="@VERSION@" date="@DATE@"/>
</releases>
</component>
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- shared-mime-info definitions for MaterialCraft's package format.
Installed to /usr/share/mime/packages/ (update-mime-database runs on install). -->
<mime-info xmlns="http://www.freedesktop.org/standards/shared-mime-info">
<mime-type type="application/x-materialcraft">
<comment>MaterialCraft package</comment>
<sub-class-of type="application/zip"/>
<icon name="ai.storyteller.materialcraft"/>
<glob pattern="*.mcraft" weight="60"/>
</mime-type>
</mime-info>
+98
View File
@@ -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"
+72
View File
@@ -0,0 +1,72 @@
#!/usr/bin/env bash
# Repackage a MaterialCraft Linux tarball as a single-file Flatpak bundle:
#
# $DIST/materialcraft-<version>-linux-<arch>.flatpak
#
# Usage: packaging/linux/flatpak-bundle.sh [--no-test] [TARBALL]
#
# TARBALL defaults to $DIST/materialcraft-<version>-linux-<arch>.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"
@@ -0,0 +1,50 @@
# Flatpak manifest for the single-file bundle attached to every GitHub release
# (materialcraft-<version>-linux-<arch>.flatpak). Build it with packaging/linux/flatpak-bundle.sh.
#
# It repackages the release's own Linux tarball (materialcraft-<version>-linux-<arch>.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
@@ -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
+80
View File
@@ -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
+151
View File
@@ -0,0 +1,151 @@
#!/usr/bin/env bash
# Build and package MaterialCraft for Linux (x86_64, aarch64 or cross-compiled riscv64):
#
# $DIST/materialcraft-<version>-linux-<arch>.AppImage any distro with glibc >= the build host's
# $DIST/materialcraft-<version>-linux-<arch>.AppImage.zsync delta updates (needs zsyncmake)
# $DIST/materialcraft-<version>-linux-<arch>.deb Debian, Ubuntu, Mint, Pop!_OS, ...
# $DIST/materialcraft-<version>-linux-<arch>.rpm Fedora, openSUSE, RHEL, ...
# $DIST/materialcraft-<version>-linux-<arch>.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 <materialcraft@storyteller.ai>}"
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-<name>).
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"
+13
View File
@@ -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
+89
View File
@@ -0,0 +1,89 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<!-- Template: packaging/macos/package.sh substitutes @VERSION@ (full, e.g. 0.2.0-rc.1),
@SHORT_VERSION@ (numeric X.Y.Z) and @BUILD_SHA@. -->
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleDisplayName</key>
<string>MaterialCraft</string>
<key>CFBundleName</key>
<string>MaterialCraft</string>
<key>CFBundleExecutable</key>
<string>MaterialCraft</string>
<key>CFBundleIdentifier</key>
<string>ai.storyteller.materialcraft</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleShortVersionString</key>
<string>@SHORT_VERSION@</string>
<key>CFBundleVersion</key>
<string>@SHORT_VERSION@</string>
<key>MaterialCraftVersion</key>
<string>@VERSION@</string>
<key>MaterialCraftBuildCommit</key>
<string>@BUILD_SHA@</string>
<key>CFBundleIconFile</key>
<string>MaterialCraft</string>
<key>LSApplicationCategoryType</key>
<string>public.app-category.graphics-design</string>
<!-- Must match MACOSX_DEPLOYMENT_TARGET in package.sh. Big Sur is the first release on
Apple silicon and has the Metal feature set wgpu targets. -->
<key>LSMinimumSystemVersion</key>
<string>11.0</string>
<key>NSHighResolutionCapable</key>
<true/>
<key>NSSupportsAutomaticGraphicsSwitching</key>
<true/>
<key>NSRequiresAquaSystemAppearance</key>
<false/>
<key>NSHumanReadableCopyright</key>
<string>Copyright © the MaterialCraft contributors. MIT OR Apache-2.0.</string>
<!-- MaterialCraft's own package format (a zip container). -->
<key>UTExportedTypeDeclarations</key>
<array>
<dict>
<key>UTTypeIdentifier</key>
<string>ai.storyteller.materialcraft.package</string>
<key>UTTypeDescription</key>
<string>MaterialCraft Package</string>
<key>UTTypeConformsTo</key>
<array>
<string>public.data</string>
<string>public.content</string>
</array>
<key>UTTypeIconFile</key>
<string>MaterialCraft</string>
<key>UTTypeTagSpecification</key>
<dict>
<key>public.filename-extension</key>
<array><string>mcraft</string></array>
<key>public.mime-type</key>
<array><string>application/x-materialcraft</string></array>
</dict>
</dict>
</array>
<key>CFBundleDocumentTypes</key>
<array>
<dict>
<key>CFBundleTypeName</key>
<string>MaterialCraft Package</string>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>LSHandlerRank</key>
<string>Owner</string>
<key>CFBundleTypeIconFile</key>
<string>MaterialCraft</string>
<key>LSItemContentTypes</key>
<array><string>ai.storyteller.materialcraft.package</string></array>
</dict>
</array>
</dict>
</plist>
+9
View File
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<!-- Hardened-runtime entitlements for MaterialCraft. Deliberately empty: the app is pure Rust,
loads no unsigned code, needs no JIT, and is not sandboxed (it opens files by path, from the
command line and drag-and-drop). Add exceptions here only with a reason in a comment. -->
<plist version="1.0">
<dict>
</dict>
</plist>
+50
View File
@@ -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
+167
View File
@@ -0,0 +1,167 @@
#!/usr/bin/env bash
# Build, sign and (optionally) notarize the macOS release artifacts:
#
# $DIST/materialcraft-<version>-macos-<arch>.dmg MaterialCraft.app on a drag-to-Applications DMG
# $DIST/materialcraft-cli-<version>-macos-<arch>.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"
+149
View File
@@ -0,0 +1,149 @@
#!/usr/bin/env bash
# Check the macOS release artifacts exactly as users download them:
#
# $DIST/materialcraft-<version>-macos-<arch>.dmg signed, notarized, ticket stapled
# $DIST/materialcraft-cli-<version>-macos-<arch>.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
+16
View File
@@ -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
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE application/wasm text/javascript text/html
</IfModule>
<IfModule mod_headers.c>
<FilesMatch "\.(wasm|js)$">
Header set Cache-Control "public, max-age=31536000, immutable"
</FilesMatch>
<FilesMatch "^index\.html$">
Header set Cache-Control "no-cache"
</FilesMatch>
</IfModule>
+88
View File
@@ -0,0 +1,88 @@
# Hosting MaterialCraft for the web
`materialcraft-web-<version>.zip` (from the GitHub release, or `packaging/web/package.sh`) holds a
static site in `materialcraft-web-<version>/`:
| File | What it is |
|---|---|
| `index.html` | The page. It loads everything through relative URLs. |
| `materialcraft-web-<hash>.js` | wasm-bindgen glue (generated by trunk, ES module) |
| `materialcraft-web-<hash>_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
<iframe
src="https://example.com/materialcraft/"
title="MaterialCraft procedural material designer"
style="width: 100%; height: 720px; border: 0;"
allow="fullscreen; clipboard-read; clipboard-write"
allowfullscreen>
</iframe>
```
- 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.
+13
View File
@@ -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
+56
View File
@@ -0,0 +1,56 @@
#!/usr/bin/env bash
# Build the browser version and zip it: $DIST/materialcraft-web-<version>.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-<version>/ that works
# from any URL path and inside an <iframe>. Hosting notes: packaging/web/README.md.
set -euo pipefail
# shellcheck source=../env.sh
. "$(dirname "${BASH_SOURCE[0]}")/../env.sh"
HERE="$ROOT/packaging/web"
if [ "${1:-}" != "--skip-build" ]; then
command -v trunk >/dev/null || { echo "error: trunk not found (cargo install trunk --locked)" >&2; exit 1; }
(cd "$ROOT/apps/materialcraft-web" && trunk build --release)
fi
SITE="$ROOT/dist/web"
[ -f "$SITE/index.html" ] || { echo "error: $SITE/index.html missing; run without --skip-build" >&2; exit 1; }
# Paths must be relative so the site works under any prefix (public_url = "./" in Trunk.toml).
if grep -Eq '(src|href)="/[^/]' "$SITE/index.html"; then
echo "error: $SITE/index.html has root-absolute URLs; it would break when served from a sub-path" >&2
exit 1
fi
# Size gate: Cloudflare Pages/Workers reject any single file over 25 MiB, and other
# hosts and CDNs have similar caps. Fail well before that so a regression shows up here, not at
# upload time. Override with MATERIALCRAFT_WASM_MAX_BYTES only to investigate.
MAX_WASM_BYTES="${MATERIALCRAFT_WASM_MAX_BYTES:-25165824}" # 24 MiB
WASM_COUNT=0
for wasm in "$SITE"/*.wasm; do
[ -f "$wasm" ] || continue
WASM_COUNT=$((WASM_COUNT + 1))
size=$(wc -c <"$wasm" | tr -d ' ')
echo "$(basename "$wasm"): $size bytes ($((size / 1048576)) MiB; limit $MAX_WASM_BYTES)"
if [ "$size" -gt "$MAX_WASM_BYTES" ]; then
echo "error: $(basename "$wasm") is $size bytes, over the $MAX_WASM_BYTES-byte limit (Cloudflare's per-file cap is 25 MiB)" >&2
exit 1
fi
done
[ "$WASM_COUNT" -gt 0 ] || { echo "error: no .wasm in $SITE" >&2; exit 1; }
NAME="materialcraft-web-$VERSION"
WORK="$CARGO_TARGET_DIR/web-package"
rm -rf "$WORK"
mkdir -p "$WORK/$NAME"
cp -R "$SITE/." "$WORK/$NAME/"
# Sample server configs (MIME type, caching, compression); harmless where unused.
cp "$HERE/_headers" "$HERE/.htaccess" "$WORK/$NAME/"
cp "$HERE/README.md" "$WORK/$NAME/HOSTING.md"
copy_docs "$WORK/$NAME"
rm -f "$DIST/$NAME.zip"
(cd "$WORK" && zip -qr9 "$DIST/$NAME.zip" "$NAME")
echo "wrote $DIST/$NAME.zip"
ls -lh "$DIST/$NAME.zip"
+76
View File
@@ -0,0 +1,76 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
MaterialCraft MSI (WiX Toolset v5: `dotnet tool install -g wix`). Built by package.ps1:
wix build materialcraft.wxs -arch x64 -d Version=1.2.3 -d BinDir=... -d IconPath=... -o out.msi
Per-machine install into Program Files, a Start Menu shortcut, `.mcraft` owned by MaterialCraft,
and MaterialCraft offered under "Open with" for the mesh formats it opens (without taking over
the user's default app for them).
UpgradeCode is MaterialCraft's for good: generated once (2026-10-14), never change it, or new
versions install beside old ones instead of replacing them.
-->
<Wix xmlns="http://wixtoolset.org/schemas/v4/wxs">
<Package
Name="MaterialCraft"
Manufacturer="Learning Machines LLC"
Version="$(var.Version)"
UpgradeCode="89DE105E-B6C8-4261-ADBE-25BCFA3A0C91"
Scope="perMachine"
Compressed="yes"
Language="1033">
<SummaryInformation Description="MaterialCraft procedural material designer" Manufacturer="Learning Machines LLC" />
<!-- Same-version upgrades let successive pre-releases of one X.Y.Z replace each other
(MSI versions are numeric, so 1.2.3-rc.1 and 1.2.3-rc.2 are both 1.2.3). -->
<MajorUpgrade AllowSameVersionUpgrades="yes"
DowngradeErrorMessage="A newer version of MaterialCraft is already installed." />
<MediaTemplate EmbedCab="yes" CompressionLevel="high" />
<!-- MSI caches this icon using its Id as the filename. Advertised shortcuts to an
.exe need an .exe icon identifier (ICE50), even when the source is an ICO. -->
<Icon Id="MaterialCraftIcon.exe" SourceFile="$(var.IconPath)" />
<Property Id="ARPPRODUCTICON" Value="MaterialCraftIcon.exe" />
<Property Id="ARPURLINFOABOUT" Value="https://getartcraft.com/apps/materialcraft" />
<Property Id="ARPURLUPDATEINFO" Value="https://getartcraft.com/apps/materialcraft" />
<Property Id="ARPHELPLINK" Value="https://discord.gg/artcraft" />
<StandardDirectory Id="ProgramFiles6432Folder">
<Directory Id="INSTALLFOLDER" Name="MaterialCraft" />
</StandardDirectory>
<StandardDirectory Id="ProgramMenuFolder" />
<Feature Id="Main" Title="MaterialCraft" Level="1">
<ComponentGroupRef Id="MaterialCraftFiles" />
</Feature>
</Package>
<Fragment>
<ComponentGroup Id="MaterialCraftFiles" Directory="INSTALLFOLDER">
<Component Id="MaterialCraftApp">
<File Id="MaterialCraftExe" Source="$(var.BinDir)\materialcraft.exe" KeyPath="yes">
<Shortcut Id="StartMenuShortcut" Directory="ProgramMenuFolder" Name="MaterialCraft"
Description="MaterialCraft procedural material designer" WorkingDirectory="INSTALLFOLDER" Advertise="yes"
Icon="MaterialCraftIcon.exe" IconIndex="0" />
</File>
<!-- .mcraft: MaterialCraft's own package format; MaterialCraft is its default app. -->
<ProgId Id="MaterialCraft.Package" Description="MaterialCraft Package" Icon="MaterialCraftExe" IconIndex="0">
<Extension Id="mcraft" ContentType="application/x-materialcraft">
<Verb Id="open" Command="Open" TargetFile="MaterialCraftExe" Argument="&quot;%1&quot;" />
</Extension>
</ProgId>
<!-- "Open with" app list and the Run dialog (Win+R "materialcraft"). -->
<RegistryValue Root="HKLM" Key="Software\Classes\Applications\materialcraft.exe" Name="FriendlyAppName" Value="MaterialCraft" Type="string" />
<RegistryValue Root="HKLM" Key="Software\Classes\Applications\materialcraft.exe\shell\open\command" Value="&quot;[#MaterialCraftExe]&quot; &quot;%1&quot;" Type="string" />
<RegistryValue Root="HKLM" Key="Software\Classes\Applications\materialcraft.exe\SupportedTypes" Name=".mcraft" Value="" Type="string" />
<RegistryValue Root="HKLM" Key="Software\Microsoft\Windows\CurrentVersion\App Paths\materialcraft.exe" Value="[#MaterialCraftExe]" Type="string" />
</Component>
<Component Id="MaterialCraftCli">
<File Id="MaterialCraftCliExe" Source="$(var.BinDir)\materialcraft-cli.exe" KeyPath="yes" />
</Component>
</ComponentGroup>
</Fragment>
</Wix>
+135
View File
@@ -0,0 +1,135 @@
<#
.SYNOPSIS
Build, sign and package MaterialCraft for Windows.
.DESCRIPTION
Produces, in $env:DIST (default: dist/release):
materialcraft-<version>-windows-<arch>.msi per-machine installer (WiX v5)
materialcraft-<version>-windows-<arch>-portable.zip materialcraft.exe + materialcraft-cli.exe + licences
The binaries link the C runtime statically (+crt-static), so neither the MSI nor the portable
zip needs the Visual C++ redistributable. Signing is delegated to sign.ps1 (skipped with a
warning when no signing secrets are set).
Needs: Rust (MSVC toolchain + the target), the Windows SDK (rc.exe, signtool.exe),
and WiX v5: dotnet tool install --global wix --version 5.0.2
.EXAMPLE
pwsh packaging/windows/package.ps1 -Arch x64
pwsh packaging/windows/package.ps1 -Arch x86 -SkipBuild
pwsh packaging/windows/package.ps1 -Arch arm64 # cross-compiled; needs the MSVC ARM64 build tools
#>
param(
[ValidateSet('x64', 'x86', 'arm64')] [string] $Arch = 'x64',
[switch] $SkipBuild
)
$ErrorActionPreference = 'Stop'
$Root = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path
function Invoke-Native([string] $What, [scriptblock] $Block) {
Write-Output "==> $What"
& $Block
if ($LASTEXITCODE -ne 0) { throw "$What failed with exit code $LASTEXITCODE" }
}
# The version lives in one place: [workspace.package] version in the root Cargo.toml.
$Version = $env:MATERIALCRAFT_VERSION
if (-not $Version) {
$inPkg = $false
foreach ($line in Get-Content (Join-Path $Root 'Cargo.toml')) {
if ($line -match '^\s*\[') { $inPkg = ($line.Trim() -eq '[workspace.package]'); continue }
if ($inPkg -and $line -match '^\s*version\s*=\s*"([^"]+)"') { $Version = $Matches[1]; break }
}
}
if (-not $Version) { throw 'could not read [workspace.package] version from Cargo.toml' }
# MSI ProductVersion is numeric (major.minor.build); pre-release tags are dropped there.
$MsiVersion = ($Version -split '-')[0]
$Target = switch ($Arch) { 'x64' { 'x86_64-pc-windows-msvc' } 'x86' { 'i686-pc-windows-msvc' } 'arm64' { 'aarch64-pc-windows-msvc' } }
$Dist = if ($env:DIST) { $env:DIST } else { Join-Path $Root 'dist\release' }
$TargetDir = if ($env:CARGO_TARGET_DIR) { $env:CARGO_TARGET_DIR } else { Join-Path $Root 'target' }
New-Item -ItemType Directory -Force -Path $Dist | Out-Null
if (-not $env:MATERIALCRAFT_BUILD_SHA) { $env:MATERIALCRAFT_BUILD_SHA = (git -C $Root rev-parse HEAD 2>$null) }
if (-not $env:MATERIALCRAFT_BUILD_DATE) { $env:MATERIALCRAFT_BUILD_DATE = (Get-Date).ToUniversalTime().ToString('yyyy-MM-dd') }
Write-Output "MaterialCraft $Version for Windows $Arch ($Target)"
if (-not $SkipBuild) {
# Static CRT: no VC++ redistributable needed. Scoped to the target so host build scripts and
# proc-macros are unaffected.
$flagVar = 'CARGO_TARGET_' + ($Target.ToUpper() -replace '-', '_') + '_RUSTFLAGS'
[Environment]::SetEnvironmentVariable($flagVar, '-C target-feature=+crt-static')
# Fail the build (rather than warn) if the icon/VERSIONINFO can't be embedded.
$env:MATERIALCRAFT_REQUIRE_WINRES = '1'
Invoke-Native "cargo build ($Target)" { cargo build --release --locked -p materialcraft -p materialcraft-cli --target $Target }
}
$Bin = Join-Path $TargetDir "$Target\release"
# Check both binaries' PE headers before packaging. Machine (COFF header) must match -Arch, so an
# x64 build can never ship labelled arm64. Subsystem (optional header): 2 = Windows GUI, 3 = console.
# The app must be GUI (no console window opens with it); the CLI must stay console so its output
# reaches the terminal.
function Get-PeHeader([string] $Path) {
$bytes = [System.IO.File]::ReadAllBytes($Path)
$pe = [BitConverter]::ToInt32($bytes, 0x3C)
return @{ Machine = [BitConverter]::ToUInt16($bytes, $pe + 4); Subsystem = [BitConverter]::ToUInt16($bytes, $pe + 0x5C) }
}
$Machine = switch ($Arch) { 'x64' { 0x8664 } 'x86' { 0x14C } 'arm64' { 0xAA64 } }
foreach ($check in @(@('materialcraft.exe', 2), @('materialcraft-cli.exe', 3))) {
$h = Get-PeHeader (Join-Path $Bin $check[0])
if ($h.Machine -ne $Machine) { throw "$($check[0]) is for machine 0x$('{0:X}' -f $h.Machine), expected 0x$('{0:X}' -f $Machine) ($Arch)" }
if ($h.Subsystem -ne $check[1]) { throw "$($check[0]) has PE subsystem $($h.Subsystem), expected $($check[1])" }
Write-Output "ok $($check[0]): $Arch, PE subsystem $($h.Subsystem)"
}
$Stage = Join-Path $TargetDir "windows-package\$Arch"
Remove-Item -Recurse -Force $Stage -ErrorAction SilentlyContinue
New-Item -ItemType Directory -Force -Path $Stage | Out-Null
Copy-Item (Join-Path $Bin 'materialcraft.exe'), (Join-Path $Bin 'materialcraft-cli.exe') $Stage
& (Join-Path $PSScriptRoot 'sign.ps1') (Join-Path $Stage 'materialcraft.exe') (Join-Path $Stage 'materialcraft-cli.exe')
# ---- MSI ---------------------------------------------------------------------------------------
$Msi = Join-Path $Dist "materialcraft-$Version-windows-$Arch.msi"
Invoke-Native 'wix build' {
wix build (Join-Path $PSScriptRoot 'materialcraft.wxs') -arch $Arch `
-d "Version=$MsiVersion" -d "BinDir=$Stage" -d "IconPath=$(Join-Path $Root 'assets\app-icon\materialcraft.ico')" `
-o $Msi
}
Invoke-Native 'MSI shortcut icon validation (ICE50)' {
wix msi validate $Msi -ice ICE50 -intermediateFolder (Join-Path $Stage 'msi-validation')
}
# wix writes its debug symbols (.wixpdb) next to the MSI; keep them out of the release assets.
Remove-Item -Force -ErrorAction SilentlyContinue ([IO.Path]::ChangeExtension($Msi, '.wixpdb'))
& (Join-Path $PSScriptRoot 'sign.ps1') $Msi
# ---- portable zip ------------------------------------------------------------------------------
$Portable = Join-Path $TargetDir "windows-package\materialcraft-$Version-windows-$Arch-portable"
Remove-Item -Recurse -Force $Portable -ErrorAction SilentlyContinue
New-Item -ItemType Directory -Force -Path $Portable | Out-Null
Copy-Item (Join-Path $Stage '*.exe') $Portable
foreach ($f in 'README.md', 'LICENSE-MIT', 'LICENSE-APACHE', 'NOTICE', 'ATTRIBUTION.md') {
$p = Join-Path $Root $f
if (Test-Path $p) { Copy-Item $p $Portable }
}
# Licences of the craft-fonts faces crates/ui-egui/build.rs embeds (release builds set CRAFT_FONTS_DIR).
if ($env:CRAFT_FONTS_DIR) {
foreach ($f in 'biz-ud-pgothic', 'noto-sans-cjk-sc') {
$p = Join-Path $env:CRAFT_FONTS_DIR "fonts\$f\OFL.txt"
if (Test-Path $p) { Copy-Item $p (Join-Path $Portable "OFL-$f.txt") }
}
}
$Zip = Join-Path $Dist "materialcraft-$Version-windows-$Arch-portable.zip"
Remove-Item -Force $Zip -ErrorAction SilentlyContinue
Compress-Archive -Path $Portable -DestinationPath $Zip
# Smoke-test the CLI when this machine can run it. An ARM64 build made on an x64 runner can't run
# here; .github/workflows/windows-arm64.yml installs and runs it on ARM64 instead.
$HostArch = [System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture.ToString().ToLowerInvariant()
if ($Arch -ne 'arm64' -or $HostArch -eq 'arm64') {
Invoke-Native 'materialcraft-cli --version' { & (Join-Path $Stage 'materialcraft-cli.exe') --version }
} else {
Write-Output "skipping materialcraft-cli --version: an $Arch build doesn't run on this $HostArch machine"
}
Get-Item $Msi, $Zip | Format-Table Name, Length
+95
View File
@@ -0,0 +1,95 @@
<#
.SYNOPSIS
Authenticode-sign files with signtool, using whichever signing material is configured.
.DESCRIPTION
Tries, in order:
1. A code-signing certificate file: WINDOWS_CERTIFICATE (base64 .pfx), WINDOWS_CERTIFICATE_PASSWORD
2. Azure Trusted Signing: AZURE_TENANT_ID, AZURE_CLIENT_ID, AZURE_CLIENT_SECRET,
AZURE_SIGNING_ENDPOINT (e.g. https://eus.codesigning.azure.net),
AZURE_SIGNING_ACCOUNT, AZURE_CERT_PROFILE
With neither, it prints a warning and leaves the files unsigned (exit code 0), so test builds
still produce installers.
This is the one place to adapt when the signing setup changes (an HSM/cloud key, a different
timestamp server, ...). Optional overrides: WINDOWS_TIMESTAMP_URL, SIGNTOOL (path to signtool.exe).
.EXAMPLE
pwsh packaging/windows/sign.ps1 dist/materialcraft.exe dist/MaterialCraft.msi
#>
param(
[Parameter(Mandatory = $true, ValueFromRemainingArguments = $true)]
[string[]] $Files
)
$ErrorActionPreference = 'Stop'
function Write-Warn([string] $Message) {
if ($env:GITHUB_ACTIONS) { Write-Output "::warning::$Message" } else { Write-Warning $Message }
}
function Find-SignTool {
if ($env:SIGNTOOL) { return $env:SIGNTOOL }
$onPath = Get-Command signtool.exe -ErrorAction SilentlyContinue
if ($onPath) { return $onPath.Source }
$kits = Join-Path ${env:ProgramFiles(x86)} 'Windows Kits\10\bin'
$found = Get-ChildItem -Path $kits -Recurse -Filter signtool.exe -ErrorAction SilentlyContinue |
Where-Object { $_.FullName -match '\\x64\\signtool\.exe$' } |
Sort-Object FullName -Descending | Select-Object -First 1
if (-not $found) { throw 'signtool.exe not found (install the Windows SDK)' }
return $found.FullName
}
function Invoke-SignTool([string[]] $Arguments) {
& $script:SignTool @Arguments
if ($LASTEXITCODE -ne 0) { throw "signtool $($Arguments[0]) failed with exit code $LASTEXITCODE" }
}
$Files = $Files | ForEach-Object { (Resolve-Path $_).Path }
$haveCert = [bool]$env:WINDOWS_CERTIFICATE
$azureVars = 'AZURE_TENANT_ID', 'AZURE_CLIENT_ID', 'AZURE_CLIENT_SECRET', 'AZURE_SIGNING_ENDPOINT', 'AZURE_SIGNING_ACCOUNT', 'AZURE_CERT_PROFILE'
$haveAzure = -not ($azureVars | Where-Object { -not [Environment]::GetEnvironmentVariable($_) })
if (-not $haveCert -and -not $haveAzure) {
Write-Warn "Windows signing secrets not set (WINDOWS_CERTIFICATE or AZURE_*): leaving unsigned: $($Files -join ', ')"
exit 0
}
$script:SignTool = Find-SignTool
$common = @('sign', '/v', '/fd', 'SHA256', '/td', 'SHA256', '/d', 'MaterialCraft', '/du', 'https://github.com/storytold/materialcraft')
$tmp = Join-Path ([IO.Path]::GetTempPath()) "materialcraft-sign-$PID"
New-Item -ItemType Directory -Force -Path $tmp | Out-Null
try {
if ($haveCert) {
Write-Output "Signing with WINDOWS_CERTIFICATE: $($Files -join ', ')"
$pfx = Join-Path $tmp 'cert.pfx'
[IO.File]::WriteAllBytes($pfx, [Convert]::FromBase64String($env:WINDOWS_CERTIFICATE))
$ts = if ($env:WINDOWS_TIMESTAMP_URL) { $env:WINDOWS_TIMESTAMP_URL } else { 'http://timestamp.digicert.com' }
$signArgs = $common + @('/tr', $ts, '/f', $pfx)
if ($env:WINDOWS_CERTIFICATE_PASSWORD) { $signArgs += @('/p', $env:WINDOWS_CERTIFICATE_PASSWORD) }
Invoke-SignTool ($signArgs + $Files)
}
else {
Write-Output "Signing with Azure Trusted Signing ($env:AZURE_SIGNING_ACCOUNT / $env:AZURE_CERT_PROFILE): $($Files -join ', ')"
# The dlib authenticates with DefaultAzureCredential, which reads AZURE_TENANT_ID,
# AZURE_CLIENT_ID and AZURE_CLIENT_SECRET from the environment.
$pkg = Join-Path $tmp 'trusted-signing.zip'
Invoke-WebRequest -Uri 'https://www.nuget.org/api/v2/package/Microsoft.Trusted.Signing.Client' -OutFile $pkg
Expand-Archive -Path $pkg -DestinationPath (Join-Path $tmp 'client') -Force
$dlib = Get-ChildItem -Path (Join-Path $tmp 'client') -Recurse -Filter Azure.CodeSigning.Dlib.dll |
Where-Object { $_.FullName -match '\\x64\\' } | Select-Object -First 1
if (-not $dlib) { throw 'Azure.CodeSigning.Dlib.dll not found in Microsoft.Trusted.Signing.Client' }
$metadata = Join-Path $tmp 'metadata.json'
@{
Endpoint = $env:AZURE_SIGNING_ENDPOINT
CodeSigningAccountName = $env:AZURE_SIGNING_ACCOUNT
CertificateProfileName = $env:AZURE_CERT_PROFILE
} | ConvertTo-Json | Set-Content -Path $metadata -Encoding utf8
$ts = if ($env:WINDOWS_TIMESTAMP_URL) { $env:WINDOWS_TIMESTAMP_URL } else { 'http://timestamp.acs.microsoft.com' }
Invoke-SignTool ($common + @('/tr', $ts, '/dlib', $dlib.FullName, '/dmdf', $metadata) + $Files)
}
Invoke-SignTool (@('verify', '/pa', '/v') + $Files)
}
finally {
Remove-Item -Recurse -Force $tmp -ErrorAction SilentlyContinue
}
+3
View File
@@ -0,0 +1,3 @@
# Same style as the other craft apps (EffectCraft, FilmCraft): wide lines, compact small items.
max_width = 160
use_small_heuristics = "Max"
+19
View File
@@ -0,0 +1,19 @@
[package]
name = "egui-phosphor"
description = "Phosphor icons for egui"
version = "0.14.0"
edition = "2021"
license = "MIT OR Apache-2.0"
repository = "https://github.com/amPerl/egui-phosphor"
[dependencies]
egui = { version = "0.37", default-features = false }
[features]
default = ["regular"]
thin = []
light = []
regular = []
bold = []
fill = []
subset = ["thin", "light", "regular", "bold", "fill"]
+201
View File
@@ -0,0 +1,201 @@
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
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2023 Romet Tagobert
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.
Loaded 100 of 118 files, more files were not shown because too many files have changed in this diff. Show more