Checkpoint native SBS primitive workflow

Replace the legacy Rust procedural library with clean-room native primitives, typed function execution and FX-Map graphs. Save supported content as native SBS and organize the model, evaluators, codecs and editors into focused modules.

Add shared graph editing behavior, flat filtered node menus, frame and comment editing, named Explorer outputs and an original atomic sample. Document the tested scope and remaining interoperability work.
This commit is contained in:
chasse20 committed 2026-11-05 18:23:06 -05:00
1 parent b34eb64235
commit d318484b41
338 files changed
+15374 -14789

No files matched your search

+4 -5
View File
@@ -11,8 +11,7 @@ The product name is always written **MaterialCraft** (`{Function}Craft` in Pasca
siblings PhotoCraft, VectorCraft, FilmCraft, LightCraft, PdfCraft, EffectCraft, DesignCraft,
TextureCraft) in user-facing text: UI, window titles, About, installers, release names, docs prose.
Machine names stay lowercase: crates (`materialcraft-*`), binaries, file names, ids
(`ai.storyteller.materialcraft`). The main project format is SBS (`.sbs`); the older native
package extension `.mcraft` is still read and written.
(`ai.storyteller.materialcraft`). The project format is SBS (`.sbs`). Legacy package compatibility is not required.
Standards and learnings shared across the crafting apps live in `../craftrules` (checked out next
to this repo, or `storytold/craftrules`). Read its `AGENTS.md` at the start of a session, follow its
@@ -41,8 +40,8 @@ file first, then `docs/`.
```text
crates/
core image geom L0 document model (package, graphs, nodes, values, function graphs); float images; meshes, BVH, camera
nodes L1 the node library: definitions + CPU cooks (atomic nodes, noises, patterns, filters, PBR utilities, function evaluator)
eval formats L2 graph cooking (topological order, sizes, content-addressed cache, sub-graphs); .sbs and .mcraft packages, bitmaps, texture export
nodes L1 the node library: native primitive definitions + CPU cooks, function evaluator and pattern graphs
eval formats L2 graph cooking (topological order, sizes, content-addressed cache, sub-graphs); native .sbs packages, bitmaps, texture export
engine render L3 Session + command registry (every action is a command), inspect, samples; the 3D preview renderer (CPU PBR + IBL)
automation L4 MCP server + headless JSON-lines RPC + bridge to the running app
ui-egui L5 egui shell (thin: every edit goes through engine commands)
@@ -98,7 +97,7 @@ and simplex gradient noise, Worley/cellular noise, fractal sums, Gaussian and bo
Felzenszwalb–Huttenlocher distance transforms, Sobel/central-difference normals, reoriented normal
mapping, HSL, levels, monotone cubic curves, W3C blend modes, GGX/Smith/Schlick PBR, split-sum IBL,
ACES fitted tone mapping). Never copy proprietary code, shaders, node implementations or presets.
SBS packages are the main project format (issue #49): `crates/formats/src/sbs.rs` reads and writes
SBS packages are the main project format (issue #49): `crates/formats/src/sbs/` reads and writes
them with MaterialCraft's own code, written from the format's public documentation and sample
files, never from another implementation. Always describe MaterialCraft as a clean-room
implementation, in code, docs and commits.
+4 -3
View File
@@ -31,7 +31,8 @@ images, materials, sample graphs, presets, environments) may ever be added.
| `docs/images/materialcraft-materials.png` | README render: eight sample materials on spheres | MaterialCraft contributors | `materialcraft-cli render --scene sphere --full --hq` of the templates, eight renders in a grid | MIT OR Apache-2.0 |
| `docs/images/materialcraft-levels-editor.png` | Docs screenshot: the Levels editor with the input histogram | MaterialCraft contributors | Offscreen render of MaterialCraft's UI (`crates/ui-egui/tests/snapshot.rs`) | MIT OR Apache-2.0 |
| `docs/brand/artcraft-*.svg`, `docs/brand/artcraft-*.png` | ArtCraft logo and mark | ArtCraft Team | storytold/craftrules `assets/brand/` | ArtCraft brand terms, not open source ([`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt)) |
| `crates/nodes/src/text.rs` (`GLYPHS`) | Single-stroke vector font of the Text node (A–Z, a–z, 0–9, punctuation) | MaterialCraft contributors | Original, designed as stroke data in code | MIT OR Apache-2.0 |
| `crates/nodes/src/atomic/text.rs` (`GLYPHS`) | Single-stroke vector font of the Text node (A–Z, a–z, 0–9, punctuation) | MaterialCraft contributors | Original, designed as stroke data in code | MIT OR Apache-2.0 |
| `examples/atomic_sample.sbs` | Atomic sample graph | MaterialCraft contributors | Original graph built by `crates/engine/src/atomic_sample.rs` | MIT OR Apache-2.0 |
## Third-party assets compiled into the binary
@@ -44,10 +45,10 @@ These come from Rust crate dependencies (not files in this repository) and keep
## Procedural content (no asset files)
The node library's noises and patterns (`crates/nodes`), the sample materials and graph templates
The node library's primitives (`crates/nodes`), the sample materials and graph templates
(`crates/engine/src/samples.rs`), the 3D view's environments (`crates/render/src/ibl.rs`, procedural
HDR skies and soft boxes), the built-in meshes (`crates/geom/src/primitives.rs`), the library's node
previews (`crates/ui-egui/src/thumbs.rs`, each node cooked on sample noise) and the New graph
previews (`crates/ui-egui/src/thumbs.rs`, each node cooked on sample waves) and the New graph
dialog's template spheres (`crates/ui-egui/src/windows.rs`) are generated in code by MaterialCraft
contributors (MIT OR Apache-2.0). None of them is derived from another product's presets,
shaders, materials, sample graphs or images.
Generated
+146 -1
View File
@@ -214,6 +214,12 @@ dependencies = [
"x11rb",
]
[[package]]
name = "arrayref"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb"
[[package]]
name = "arrayvec"
version = "0.7.8"
@@ -875,6 +881,12 @@ dependencies = [
"syn 3.0.9",
]
[[package]]
name = "data-url"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376"
[[package]]
name = "derive_arbitrary"
version = "1.5.0"
@@ -1327,6 +1339,12 @@ dependencies = [
"zlib-rs",
]
[[package]]
name = "float-cmp"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4"
[[package]]
name = "foldhash"
version = "0.1.5"
@@ -2013,6 +2031,12 @@ dependencies = [
"quick-error",
]
[[package]]
name = "imagesize"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09e54e57b4c48b40f7aec75635392b12b3421fa26fe8b4332e63138ed278459c"
[[package]]
name = "indexmap"
version = "2.14.2"
@@ -2398,7 +2422,8 @@ dependencies = [
"materialcraft-geom",
"materialcraft-image",
"materialcraft-nodes",
"roxmltree",
"resvg",
"roxmltree 0.20.0",
"serde",
"serde_json",
"thiserror 2.0.21",
@@ -3167,6 +3192,12 @@ dependencies = [
"siphasher",
]
[[package]]
name = "pico-args"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5be167a7af36ee22fe3115051bc51f6e6c7054c9348e28deb4f49bd6f705a315"
[[package]]
name = "pin-project"
version = "1.1.13"
@@ -3518,6 +3549,20 @@ version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832"
[[package]]
name = "resvg"
version = "0.47.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9be183ad6a216aa96f33e4c8033b0988b8b3ea6fd2359d19af5bac4643fd8e81"
dependencies = [
"log",
"pico-args",
"rgb",
"svgtypes",
"tiny-skia",
"usvg",
]
[[package]]
name = "rfd"
version = "0.17.2"
@@ -3545,6 +3590,15 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "rgb"
version = "0.8.53"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47b34b781b31e5d73e9fbc8689c70551fd1ade9a19e3e28cfec8580a79290cc4"
dependencies = [
"bytemuck",
]
[[package]]
name = "rmcp"
version = "3.8.0"
@@ -3601,6 +3655,15 @@ version = "0.20.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97"
[[package]]
name = "roxmltree"
version = "0.21.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9da7f59328b09405b181fee1018925fad50f157afb43c0c0f5c522c256dd5907"
dependencies = [
"memchr",
]
[[package]]
name = "rustc-hash"
version = "1.1.0"
@@ -3841,6 +3904,15 @@ version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e"
[[package]]
name = "simplecss"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a9c6883ca9c3c7c90e888de77b7a5c849c779d25d74a1269b0218b14e8b136c"
dependencies = [
"log",
]
[[package]]
name = "siphasher"
version = "1.0.4"
@@ -3946,12 +4018,31 @@ version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
[[package]]
name = "strict-num"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731"
dependencies = [
"float-cmp",
]
[[package]]
name = "strsim"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]]
name = "svgtypes"
version = "0.16.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f12b12995e3638c70618c1facb1ce65302f6a6f706b675f07c58a5d7391120e"
dependencies = [
"kurbo",
"siphasher",
]
[[package]]
name = "syn"
version = "2.0.119"
@@ -4073,6 +4164,32 @@ dependencies = [
"zune-jpeg",
]
[[package]]
name = "tiny-skia"
version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47ffee5eaaf5527f630fb0e356b90ebdec84d5d18d937c5e440350f88c5a91ea"
dependencies = [
"arrayref",
"arrayvec",
"bytemuck",
"cfg-if",
"log",
"png",
"tiny-skia-path",
]
[[package]]
name = "tiny-skia-path"
version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "edca365c3faccca67d06593c5980fa6c57687de727a03131735bb85f01fdeeb9"
dependencies = [
"arrayref",
"bytemuck",
"strict-num",
]
[[package]]
name = "tinystr"
version = "0.8.5"
@@ -4302,6 +4419,28 @@ version = "2.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da"
[[package]]
name = "usvg"
version = "0.47.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d46cf96c5f498d36b7a9693bc6a7075c0bb9303189d61b2249b0dc3d309c07de"
dependencies = [
"base64 0.22.1",
"data-url",
"flate2",
"imagesize",
"kurbo",
"log",
"pico-args",
"roxmltree 0.21.2",
"simplecss",
"siphasher",
"strict-num",
"svgtypes",
"tiny-skia-path",
"xmlwriter",
]
[[package]]
name = "utf16_iter"
version = "1.1.0"
@@ -5245,6 +5384,12 @@ version = "0.8.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7"
[[package]]
name = "xmlwriter"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9"
[[package]]
name = "xtask"
version = "0.1.2"
+1
View File
@@ -42,6 +42,7 @@ rust-version = "1.95"
repository = "https://github.com/storytold/materialcraft"
[workspace.dependencies]
resvg = { version = "0.47", default-features = false }
# internal
materialcraft-core = { path = "crates/core" }
materialcraft-image = { path = "crates/image" }
+14 -19
View File
@@ -18,7 +18,7 @@
</p>
<p align="center">
Build tileable PBR materials from noises, patterns and filters in a node graph, watch them
Build procedural materials from primitives and functions in a node graph, watch them
update live in 2D and on a 3D model, and export the maps for any engine. It runs natively on
macOS, Windows, Linux and FreeBSD, and in the browser via WebAssembly. Built by the ArtCraft team.
</p>
@@ -67,6 +67,9 @@
## A look around
These screenshots show the earlier procedural library. The current build uses the primitive
catalog described in [the primitive workflow](docs/atomic-workflow.md).
<table>
<tr>
<td width="50%" valign="top">
@@ -92,7 +95,8 @@
## Made in MaterialCraft
Every material below is a node graph that ships with MaterialCraft as a template, built only from
These historical renders used the former Rust library and are no longer bundled as templates.
They were built from
its own procedural nodes (no photos, scans or textures from anywhere else) and rendered by
`materialcraft-cli render --scene sphere --full --hq` (the height output displaces the mesh, with
ray-traced ambient occlusion and a shadowed key light).
@@ -110,12 +114,12 @@ ray-traced ambient occlusion and a shadowed key light).
histogram of its input, see [docs/levels-editor.md](docs/levels-editor.md)). Space opens the
node search.
- **Fast.** Every node cooks on every CPU core, and a content-addressed cache means an edit
re-cooks only what lies downstream: the brick wall sample cooks in about 40 ms at preview size.
re-cooks only what lies downstream.
Cooking runs on a worker thread, so the UI never waits.
- **Tileable by design.** Noises and patterns live on whole-number lattices, so everything tiles
seamlessly at any resolution, from 16 px to 8K.
- **Robust.** No panics in shipped code, every command tested with hostile input, every node cooked
with odd inputs in tests, unlimited undo from snapshots, and lossless project files.
with odd inputs in tests, undo from snapshots, and native SBS project files.
- **Open.** Export base color, normal, roughness, metallic, height and ambient occlusion as PNG,
JPEG, TGA, TIFF, BMP, WEBP, EXR or HDR at 8, 16 or 32 bits, with your own file name pattern.
- **Works with TextureCraft.** **File ▸ Send to TextureCraft** puts a material on TextureCraft's
@@ -134,7 +138,7 @@ git clone https://github.com/storytold/materialcraft
cd materialcraft
cargo run --release -p materialcraft # desktop app
cargo run --release -p materialcraft -- package.sbs # open a package (.sbs or .mcraft)
cargo run --release -p materialcraft -- package.sbs # open an SBS package
cargo run --release -p materialcraft -- --control 7878 # + JSON control channel
cargo run --release -p materialcraft-cli -- mcp # MCP server (stdio)
cargo run --release -p materialcraft-cli -- new wood wood.sbs
@@ -170,21 +174,12 @@ The details are in [`docs/control-protocol.md`](docs/control-protocol.md).
MaterialCraft is under active development. [**ROADMAP.md**](ROADMAP.md) has the parity estimate by
area, the remaining work and what's next.
**Where we are (2026-11-02):** the node engine and 227 nodes (the atomic nodes including FX-Map,
SVG and Text, noises including tileable 3D ones, patterns, filters, the flood fill family,
whole-material blending and weathering), function graphs with a visual editor and dynamic
parameters, sub-graphs with exposed inputs and presets, the full editor (graph, library,
properties, 2D view with histogram, 3D view with your own OBJ/glTF meshes, alpha transparency and an
alpha channel view; wires you can select, delete, swap (X) and reroute with dots, see
[docs/wires-and-alpha.md](docs/wires-and-alpha.md)), SBS project files (`.mcraft` too),
texture export, portable `.mcmat` materials that TextureCraft paints with (inputs stay editable
there), the browser build with file I/O, the CLI, the control channel and the MCP server
all work today. We estimate about two thirds (≈ 67%) of a material artist's daily workflow works
end to end; [docs/target-app-parity.md](docs/target-app-parity.md) has the breakdown.
**Current focus (2026-11-05):** primitive editing and native SBS save/load. The old Rust
procedural library has been removed. The replacement includes 30 main-graph entries, 85 function
operations and three pattern node kinds. Start with **File → New → Atomic sample**.
**What's missing:** the rest of the node library, a GPU 3D view with tessellation and lights,
mesh-based nodes, translations and the first signed release. The ranked list is in
[`docs/gaps.md`](docs/gaps.md).
See [the primitive workflow](docs/atomic-workflow.md) for usage, validation scope and limitations.
Reference-app rendering parity and full SBS library loading are still pending.
**Workspace:** `crates/{core, image, geom, nodes, eval, formats, engine, render, automation, ui-egui}`
and `apps/{materialcraft, materialcraft-cli, materialcraft-web}`. The egui frontend is its own
+11 -37
View File
@@ -1,46 +1,20 @@
# MaterialCraft roadmap
> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-02 · **Change:** minor (≈ 67%: portable materials for TextureCraft) · **Target:** the professional node-based material workflow
**Current focus (2026-11-05):** native primitive editing, evaluation and SBS save/load.
**Stage:** alpha (in active development). MaterialCraft aims for full parity with the professional
node-based procedural material workflow, with better performance, every feature drivable by agents
(MCP, CLI, control channel), and builds for Windows, macOS, Linux, FreeBSD and the web.
The old Rust procedural library has been removed. The main catalog has 30 entries: 26 native
primitives and four graph input/output items. Functions have 85 operations; pattern graphs have
Quadrant, Switch, Iterate and Dot. See [the primitive workflow](docs/atomic-workflow.md) for usage and limits.
## Headline numbers
Earlier percentage estimates and node counts are superseded by this change. Reference-app
rendering parity and arbitrary SBS round trips have not been established.
- **Parity: ≈ 67%** of a material artist's daily workflow works end to end
([docs/target-app-parity.md](docs/target-app-parity.md)).
- **Remaining: ≈ 83 Opus 5.5 agent hours** ([docs/roadmap.md](docs/roadmap.md)).
- **Nodes:** 227 (all tileable), cooked on every CPU core through a content-addressed cache; the
brick wall sample cooks in about 40 ms at preview size.
## Next steps
## By area
| Area | Weight | Done |
|---|---:|---:|
| Graph editing | 15 | 75% |
| Atomic nodes | 12 | 95% |
| Node library | 20 | 45% |
| Function graphs | 10 | 70% |
| Graph parameters and instances | 8 | 70% |
| 2D view | 5 | 80% |
| 3D view | 10 | 55% |
| Files | 8 | 70% |
| UI and UX | 8 | 70% |
| Platforms | 4 | 50% |
| **Total** | **100** | **≈ 67%** |
## What's next
1. The rest of the node library: scan processing, more grunges, spline tools, SDF shapes.
2. A GPU 3D view with tessellation and lights.
3. Mesh-based generators and bakers.
4. Function loops and reusable functions.
5. The first release on every platform.
The ranked work list is [docs/gaps.md](docs/gaps.md); file formats are in
[docs/file-format-parity.md](docs/file-format-parity.md) and languages in
[docs/localization-parity.md](docs/localization-parity.md).
1. Verify the original atomic sample in the reference application
2. Compare primitive outputs and parameter semantics against reference results
3. Add SBS graph references with cycle-safe resolution
4. Build the library from SBS definitions instead of duplicate Rust nodes
## Progress log
+16 -15
View File
@@ -1,12 +1,11 @@
//! Headless MaterialCraft command line: inspect, script, cook, export and render packages, and
//! serve agents over MCP or JSON lines. Never opens a window.
//! Headless MaterialCraft command line: inspect, script, cook, export and render packages, and serve agents over MCP or JSON lines. Never opens a window
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
use std::sync::{Arc, Mutex};
use materialcraft_automation::security::{client_token, server_token};
use materialcraft_automation::{AuthorizedWorkspace, BridgeClient, Filesystem, Headless, MaterialcraftMcp, RenderOptions, rpc};
use materialcraft_automation::{AuthorizedWorkspace, BridgeClient, Filesystem, Headless, MaterialCraftMcp, RenderOptions, rpc};
use serde_json::{Value, json};
const USAGE: &str = "\
@@ -14,7 +13,7 @@ materialcraft-cli: headless MaterialCraft
USAGE:
materialcraft-cli --version
materialcraft-cli info <package.sbs | package.mcraft | sample>
materialcraft-cli info <package.sbs | sample>
Graphs, nodes, outputs and cook results, as JSON.
materialcraft-cli commands [--filter <text>]
List the engine commands (id, label, params).
@@ -25,8 +24,7 @@ USAGE:
materialcraft-cli batch <script.json>
Run [{\"id\", \"params\"}, ...] or {\"open\": <input>, \"steps\": [...], \"save\": <out.sbs>}.
materialcraft-cli new <template> <out.sbs> [--size <px>] [--name <name>]
A new package with one graph from a template (empty, pbr, bricks, stone_tiles, wood,
metal_plates, rusty_metal, lava, marble, wicker, fabric, ground).
A new package with one graph from a template (empty, pbr, atomics).
materialcraft-cli cook <input> [--graph <index>] [--set <input>=<value>]... [--full]
Cook a graph and print per-node timings and errors.
materialcraft-cli export <input> <dir> [--graph <index>] [--set <input>=<value>]... [--format <ext>]
@@ -44,8 +42,7 @@ USAGE:
materialcraft-cli serve [--port <port>] [--read-root <dir>] [--write-root <dir>]
JSON lines ({\"id\",\"method\",\"params\"}) on stdio, or on 127.0.0.1:<port> with a token.
<input> is an .sbs or .mcraft package or `sample` (the built-in brick wall). Packages save as SBS
unless the output path ends in .mcraft. --set gives a graph input a value
<input> is an .sbs package or `sample` (the built-in atomic sample). Packages save as native SBS. --set gives a graph input a value
(JSON, e.g. `--set roughness=0.4 --set tint=\"#aa7744\"`) before cooking. See docs/control-protocol.md.
";
@@ -114,7 +111,7 @@ fn version() -> String {
}
}
/// A headless session on `input` (an .sbs or .mcraft package, or `sample`), with local file access.
/// A headless session on `input` (an .sbs package, or `sample`), with local file access
fn open(input: &str) -> Result<Headless, String> {
let mut h = Headless::new(Headless::default_session(), Filesystem::TrustedLocal);
if input != "sample" {
@@ -127,7 +124,7 @@ fn print(v: &Value) {
println!("{}", serde_json::to_string_pretty(v).unwrap_or_else(|e| format!("{{\"error\": \"{e}\"}}")));
}
/// Open `--graph` and apply every `--set <input>=<value>` (the value is JSON, else a string).
/// Open `--graph` and apply every `--set <input>=<value>` (the value is JSON, else a string)
fn select_graph(h: &mut Headless, a: &Args) -> Result<(), String> {
if let Some(g) = a.num::<u64>("--graph")? {
h.command_run("graph.open", json!({"graph": g})).map_err(|e| e.to_string())?;
@@ -183,6 +180,7 @@ fn run(cmd: &str, a: &Args) -> Result<(), String> {
Some(p) => serde_json::from_str(p).map_err(|e| format!("params: {e}"))?,
None => Value::Null,
};
print(&h.command_run(id, params).map_err(|e| e.to_string())?);
if let Some(out) = a.get("-o") {
h.save(Some(out)).map_err(|e| e.to_string())?;
@@ -199,6 +197,7 @@ fn run(cmd: &str, a: &Args) -> Result<(), String> {
obj.get("save").and_then(Value::as_str),
),
};
let mut h = open(input)?;
let r = h.batch(&steps);
print(&r);
@@ -242,6 +241,7 @@ fn run(cmd: &str, a: &Args) -> Result<(), String> {
}
None => (None, None),
};
let o = RenderOptions {
view: a.get("--view").map(str::to_string),
width: w,
@@ -256,6 +256,7 @@ fn run(cmd: &str, a: &Args) -> Result<(), String> {
hq: a.has("--hq"),
displacement: a.num("--displacement")?,
};
let r = h.render_png(&o).map_err(|e| e.to_string())?;
materialcraft_engine::formats::write_atomic(std::path::Path::new(out), &r.png).map_err(|e| e.to_string())?;
print(&json!({"path": out, "width": r.width, "height": r.height}));
@@ -265,18 +266,18 @@ fn run(cmd: &str, a: &Args) -> Result<(), String> {
let server = match a.num::<u16>("--bridge")? {
Some(port) => {
let token = client_token(port, a.get("--token").map(str::to_string)).map_err(|e| e.to_string())?;
MaterialcraftMcp::bridge(BridgeClient::new(port, token))
MaterialCraftMcp::bridge(BridgeClient::new(port, token))
}
None => MaterialcraftMcp::headless(Headless::new(Headless::default_session(), workspace(a)?)),
None => MaterialCraftMcp::headless(Headless::new(Headless::default_session(), workspace(a)?)),
};
rt.block_on(server.serve_stdio()).map_err(|e| e.to_string())?;
}
"serve" => {
let h = Arc::new(Mutex::new(Headless::new(Headless::default_session(), workspace(a)?)));
match a.num::<u16>("--port")? {
Some(port) => {
// Bind first: a port in use must not replace its server's token file, and port 0's
// token file is named after the port actually picked.
// Bind first: a port in use must not replace its server's token file, and port 0's token file is named after the port actually picked
let listener = rpc::bind_tcp(port).map_err(|e| e.to_string())?;
let addr = listener.local_addr().map_err(|e| e.to_string())?;
let (token, file) = server_token(addr.port()).map_err(|e| e.to_string())?;
@@ -294,7 +295,7 @@ fn run(cmd: &str, a: &Args) -> Result<(), String> {
Ok(())
}
/// File access for servers: none without roots, else only below them.
/// File access for servers: none without roots, else only below them
fn workspace(a: &Args) -> Result<Filesystem, String> {
let (r, w) = (a.get("--read-root"), a.get("--write-root"));
if r.is_none() && w.is_none() {
+10 -9
View File
@@ -1,6 +1,5 @@
//! MaterialCraft desktop app.
//!
//! Usage: `materialcraft [package.sbs|package.mcraft] [--control <port>] [--empty] [--version]`
//! MaterialCraft desktop app
//! Usage: `materialcraft [package.sbs] [--control <port>] [--empty] [--version]`
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
@@ -38,14 +37,14 @@ fn parse_args() -> Result<Option<Args>, String> {
return Ok(None);
}
"--help" | "-h" => {
println!("{}\n\nUsage: materialcraft [package.sbs|package.mcraft] [--control <port>] [--empty]", version());
println!("{}\n\nUsage: materialcraft [package.sbs] [--control <port>] [--empty]", version());
return Ok(None);
}
"--control" => {
let p = it.next().ok_or("--control needs a port")?;
args.control = Some(p.parse().map_err(|_| format!("invalid port `{p}`"))?);
}
// Kept for scripts written before empty startup became the default.
// Kept for scripts written before empty startup became the default
"--empty" => {}
f if !f.starts_with('-') => args.file = Some(f.to_string()),
other => return Err(format!("unknown option `{other}`")),
@@ -80,6 +79,7 @@ fn main() {
std::process::exit(2);
}
};
let prev = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
eprintln!("materialcraft: internal error: {info}");
@@ -90,8 +90,7 @@ fn main() {
if let Some(i) = icon() {
viewport = viewport.with_icon(i);
}
// Scripted runs (agents, tests) set MATERIALCRAFT_NO_PREFS so they neither read nor overwrite
// the user's saved layout and settings: state goes to a throwaway file.
// Scripted runs (agents, tests) set MATERIALCRAFT_NO_PREFS so they neither read nor overwrite the user's saved layout and settings: state goes to a throwaway file
let persistence_path =
std::env::var_os("MATERIALCRAFT_NO_PREFS").map(|_| std::env::temp_dir().join(format!("materialcraft-noprefs-{}.ron", std::process::id())));
let options = eframe::NativeOptions { viewport, renderer: eframe::Renderer::Wgpu, persistence_path, ..Default::default() };
@@ -133,11 +132,13 @@ mod tests {
#[test]
fn startup_opens_the_requested_package() {
let path = std::env::temp_dir().join(format!("mc-startup-{}.mcraft", std::process::id()));
let path = std::env::temp_dir().join(format!("mc-startup-{}.sbs", std::process::id()));
let original = materialcraft_engine::sample_session();
std::fs::write(&path, materialcraft_engine::file_cmds::save_bytes(&original).unwrap()).unwrap();
let s = initial_session(&Args { file: Some(path.to_string_lossy().into_owned()), control: None });
assert_eq!(s.pkg.graphs, original.pkg.graphs);
assert_eq!(s.pkg.graphs.len(), original.pkg.graphs.len());
assert_eq!(s.pkg.graphs[0].name, original.pkg.graphs[0].name);
assert_eq!(materialcraft_engine::file_cmds::save_bytes(&s).unwrap(), materialcraft_engine::file_cmds::save_bytes(&original).unwrap());
assert_eq!(s.path.as_deref(), path.to_str());
assert!(!s.modified);
std::fs::remove_file(path).unwrap();
+19
View File
@@ -0,0 +1,19 @@
#[derive(Debug, thiserror::Error)]
pub enum AutomationError {
#[error("{0}")]
BadRequest(String),
#[error("I/O: {0}")]
Io(String),
#[error(transparent)]
Engine(#[from] materialcraft_engine::EngineError),
#[error("bridge: {0}")]
Bridge(String),
#[error("app: {0}")]
App(String),
#[error("{0}")]
Other(String),
}
pub(crate) fn bad(msg: impl Into<String>) -> AutomationError {
AutomationError::BadRequest(msg.into())
}
+10
View File
@@ -0,0 +1,10 @@
use crate::AuthorizedWorkspace;
/// Where file paths given to [`crate::Headless`] may point
pub enum Filesystem {
/// No file access (an MCP server started without roots)
Denied,
/// Host paths as given: the local CLI user typed them
TrustedLocal,
/// Relative paths under the authorized roots (remote or agent callers)
Workspace(AuthorizedWorkspace),
}
+18 -57
View File
@@ -1,5 +1,4 @@
//! The headless backend: a [`Session`] plus file I/O and windowless renders. Synchronous and
//! UI-free; the MCP server, the RPC server and the CLI all drive it.
//! The headless backend: a [`Session`] plus file I/O and windowless renders. Synchronous and UI-free; the MCP server, the RPC server and the CLI all drive it
use std::path::Path;
@@ -10,51 +9,8 @@ use serde_json::{Value, json};
use crate::budgets::{HQ_TRIANGLES, MAX_LOCAL_RENDER_SIDE, MAX_PNG_SIDE, check_png, encode_png};
use crate::workspace::{MAX_READ_BYTES, authorize_command};
use crate::{AuthorizedWorkspace, AutomationError, bad};
/// Where file paths given to [`Headless`] may point.
pub enum Filesystem {
/// No file access (an MCP server started without roots).
Denied,
/// Host paths as given: the local CLI user typed them.
TrustedLocal,
/// Relative paths under the authorized roots (remote or agent callers).
Workspace(AuthorizedWorkspace),
}
/// What [`Headless::render_png`] draws.
#[derive(Clone, Debug, Default)]
pub struct RenderOptions {
/// `3d` (default) or `2d` (a node's output; the 2D view's node by default).
pub view: Option<String>,
pub width: Option<u32>,
pub height: Option<u32>,
/// Camera overrides in degrees (the session's view is not changed).
pub yaw: Option<f32>,
pub pitch: Option<f32>,
/// 3D scene override (`rounded_cube`, `sphere`, …).
pub scene: Option<String>,
/// 2D: the node whose output to show.
pub node: Option<u64>,
/// 2D: the output port.
pub port: Option<usize>,
/// Cook at full size instead of the preview size.
pub full: bool,
/// 3D: UV repeats override (the session's view is not changed).
pub tiling: Option<f32>,
/// 3D: beauty render: the height output displaces a subdivided mesh, with ray-traced
/// ambient occlusion, a shadowed key light and 3×3 supersampling. Slower; for stills.
pub hq: bool,
/// 3D, with `hq`: displacement depth in scene radii (default 0.04).
pub displacement: Option<f32>,
}
/// A PNG render.
pub struct Rendered {
pub width: u32,
pub height: u32,
pub png: Vec<u8>,
}
use crate::{AutomationError, bad};
pub use crate::{Filesystem, RenderOptions, Rendered};
pub struct Headless {
pub session: Session,
@@ -63,7 +19,7 @@ pub struct Headless {
light: Option<Lighting>,
}
/// Read a file under `fs`'s access rules.
/// Read a file under `fs`'s access rules
fn read_file(fs: &Filesystem, path: &str) -> Result<Vec<u8>, AutomationError> {
match fs {
Filesystem::Denied => Err(bad("file access is not granted: start the server with --read-root <dir>")),
@@ -83,7 +39,7 @@ impl Headless {
Headless { session, fs, scene: None, light: None }
}
/// The session a fresh server starts with: the brick wall sample.
/// The session a fresh server starts with: the atomic sample
pub fn default_session() -> Session {
materialcraft_engine::sample_session()
}
@@ -122,7 +78,7 @@ impl Headless {
commands::list(&self.session, filter)
}
/// Run an engine command. Untrusted callers can't reach host paths through it.
/// Run an engine command. Untrusted callers can't reach host paths through it
pub fn command_run(&mut self, id: &str, params: Value) -> Result<Value, AutomationError> {
if !self.trusted() {
authorize_command(id, &params)?;
@@ -130,7 +86,7 @@ impl Headless {
Ok(materialcraft_engine::execute(&mut self.session, id, &params)?)
}
/// Run `[{id, params?}]` in order, stopping at the first error (reported with its index).
/// Run `[{id, params?}]` in order, stopping at the first error (reported with its index)
pub fn batch(&mut self, steps: &[Value]) -> Value {
let mut results = Vec::new();
for (i, step) in steps.iter().enumerate() {
@@ -143,7 +99,7 @@ impl Headless {
batch_reply(results, None)
}
/// Open an `.sbs` or `.mcraft` package (or a `.mcmat` material's source), reading linked bitmaps under the same access rules.
/// Open an `.sbs` package (or a `.mcmat` material's source), reading linked bitmaps under the same access rules
pub fn open(&mut self, path: &str) -> Result<Value, AutomationError> {
let bytes = self.read(path)?;
let folder = path.replace('\\', "/").rsplit_once('/').map(|(folder, _)| format!("{folder}/")).unwrap_or_default();
@@ -162,21 +118,21 @@ impl Headless {
Ok(self.inspect())
}
/// Save to `path` (`.sbs` appended without a package extension) or the package's own file; SBS unless it is a `.mcraft`.
/// Save to `path` (`.sbs` appended without a package extension) or the package's own file; native SBS
pub fn save(&mut self, path: Option<&str>) -> Result<Value, AutomationError> {
let path = match path {
Some(p) => file_cmds::package_path(p),
None => self.session.path.clone().ok_or_else(|| bad("the package has no file yet (new, or opened from another program): give a `path`"))?,
};
let bytes = file_cmds::save_bytes_as(&self.session, file_cmds::PackageFormat::of_path(&path))?;
let bytes = file_cmds::save_bytes(&self.session)?;
self.write(&path, &bytes)?;
self.session.path = Some(path.clone());
self.session.modified = false;
Ok(json!({"path": path, "bytes": bytes.len()}))
}
/// Embed an image file as a bitmap resource.
/// Embed an image file as a bitmap resource
pub fn import_bitmap(&mut self, path: &str, name: Option<&str>) -> Result<Value, AutomationError> {
let bytes = self.read(path)?;
let file = Path::new(path).file_name().and_then(|f| f.to_str()).unwrap_or("bitmap.png").to_string();
@@ -184,7 +140,7 @@ impl Headless {
Ok(json!({"name": name}))
}
/// Export every output of a graph into folder `dir`.
/// Export every output of a graph into folder `dir`
pub fn export(&mut self, p: &Value) -> Result<Value, AutomationError> {
let dir = p.get("dir").and_then(Value::as_str).ok_or_else(|| bad("`dir` is required"))?;
let (gi, ext, pattern, depth, size) = file_cmds::export_params(&self.session, p)?;
@@ -199,7 +155,7 @@ impl Headless {
Ok(json!({"files": written}))
}
/// Render the 3D view or a node's 2D output as PNG.
/// Render the 3D view or a node's 2D output as PNG
pub fn render_png(&mut self, o: &RenderOptions) -> Result<Rendered, AutomationError> {
let max = if self.trusted() { MAX_LOCAL_RENDER_SIDE } else { MAX_PNG_SIDE };
let saved = self.session.preview_size;
@@ -213,6 +169,7 @@ impl Headless {
"3d" => Ok(self.render_3d(o, max)),
other => Err(bad(format!("unknown view `{other}` (3d or 2d)"))),
};
if o.full {
self.session.preview_size = saved;
self.session.dirty = true;
@@ -228,6 +185,7 @@ impl Headless {
Some(n) => self.session.cooked.image(NodeId(n), o.port.unwrap_or(0)).ok_or_else(|| bad(format!("node {n} has no cooked output")))?,
None => self.session.view2d_image().map(|(_, i)| i).ok_or_else(|| bad("nothing to show: the graph has no outputs; pass `node`"))?,
};
let (w, h) = (o.width.unwrap_or(img.w).clamp(16, max), o.height.unwrap_or(img.h).clamp(16, max));
let img = img.resize(w, h, true);
Ok((w, h, img.to_rgba8_display()))
@@ -243,6 +201,7 @@ impl Headless {
Some((_, mesh)) => Scene::new((*mesh).clone()),
None => Scene::builtin(&scene_id),
};
self.scene = Some((key, scene));
}
if self.light.as_ref().is_none_or(|l| l.name != v.environment) {
@@ -264,6 +223,7 @@ impl Headless {
alpha_view: v.alpha_view,
..Settings::default()
};
let (w, h) = (o.width.unwrap_or(1024).clamp(16, max), o.height.unwrap_or(768).clamp(16, max));
let maps = Maps::from_usages(self.session.material_maps());
let (Some((_, scene)), Some(light)) = (&self.scene, &self.light) else { return (w, h, vec![0; (w * h * 4) as usize]) };
@@ -274,6 +234,7 @@ impl Headless {
}
_ => None,
};
if o.hq {
settings.supersample = 3;
settings.ao_rays = 8;
+11 -34
View File
@@ -1,16 +1,3 @@
//! # materialcraft-automation
//!
//! Agent-facing automation, L4 (no UI toolkit):
//!
//! * [`MaterialcraftMcp`]: an MCP server (official `rmcp` SDK). Headless mode drives an
//! in-process [`Headless`] session; bridge mode forwards to a running desktop app over the
//! JSON-lines control channel (`docs/control-protocol.md`).
//! * [`Headless`]: a [`materialcraft_engine::Session`] plus file I/O through an
//! [`AuthorizedWorkspace`] and windowless renders. Shared by the MCP server, the RPC server
//! and `materialcraft-cli`.
//! * [`rpc`]: the control channel's methods (plus `render`) over stdio or loopback TCP, used by
//! `materialcraft-cli serve`.
//! * [`BridgeClient`]: the client side of the app's control channel.
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
@@ -23,26 +10,16 @@ pub mod server;
pub mod workspace;
pub use bridge::BridgeClient;
pub use headless::{Filesystem, Headless, RenderOptions};
pub use server::{Backend, MaterialcraftMcp};
mod filesystem;
mod render_options;
mod rendered;
pub use filesystem::Filesystem;
pub use headless::Headless;
pub use render_options::RenderOptions;
pub use rendered::Rendered;
pub use server::{Backend, MaterialCraftMcp};
pub use workspace::AuthorizedWorkspace;
#[derive(Debug, thiserror::Error)]
pub enum AutomationError {
#[error("{0}")]
BadRequest(String),
#[error("I/O: {0}")]
Io(String),
#[error(transparent)]
Engine(#[from] materialcraft_engine::EngineError),
#[error("bridge: {0}")]
Bridge(String),
#[error("app: {0}")]
App(String),
#[error("{0}")]
Other(String),
}
pub(crate) fn bad(msg: impl Into<String>) -> AutomationError {
AutomationError::BadRequest(msg.into())
}
mod automation_error;
pub use automation_error::AutomationError;
pub(crate) use automation_error::bad;
+25
View File
@@ -0,0 +1,25 @@
/// What [`crate::Headless::render_png`] draws
#[derive(Clone, Debug, Default)]
pub struct RenderOptions {
/// `3d` (default) or `2d` (a node's output; the 2D view's node by default)
pub view: Option<String>,
pub width: Option<u32>,
pub height: Option<u32>,
/// Camera overrides in degrees (the session's view is not changed)
pub yaw: Option<f32>,
pub pitch: Option<f32>,
/// 3D scene override (`rounded_cube`, `sphere`, …)
pub scene: Option<String>,
/// 2D: the node whose output to show
pub node: Option<u64>,
/// 2D: the output port
pub port: Option<usize>,
/// Cook at full size instead of the preview size
pub full: bool,
/// 3D: UV repeats override (the session's view is not changed)
pub tiling: Option<f32>,
/// 3D: beauty render: the height output displaces a subdivided mesh, with ray-traced ambient occlusion, a shadowed key light and 3×3 supersampling. Slower; for stills
pub hq: bool,
/// 3D, with `hq`: displacement depth in scene radii (default 0.04)
pub displacement: Option<f32>,
}
+6
View File
@@ -0,0 +1,6 @@
/// A PNG render
pub struct Rendered {
pub width: u32,
pub height: u32,
pub png: Vec<u8>,
}
+15 -22
View File
@@ -1,14 +1,3 @@
//! Headless JSON-lines server with the app's control-channel envelope:
//! `{"id","method","params"}` → `{"id","ok":true,"result"}` | `{"id","ok":false,"error"}`.
//! `materialcraft-cli serve` runs it on stdio or on a loopback TCP port (first request `auth`).
//!
//! Methods: the app's `ping`, `command.run {id, params?}`, `command.list {filter?}`,
//! `session.inspect`, plus `command.batch {steps}`, `package.open {path}`, `package.save {path?}`,
//! `bitmap.import {path, name?}`, `outputs.export {dir, format?, pattern?, depth?, graph?}`
//! (workspace-scoped versions of the engine commands), `render {view?, width?, height?, yaw?,
//! pitch?, scene?, node?, port?, full?}` (PNG base64, the shape of the app's `view.screenshot`)
//! and `methods`.
use std::io::{BufRead, Write};
use std::net::TcpListener;
use std::sync::{Arc, Mutex, PoisonError};
@@ -67,7 +56,7 @@ fn required<'a>(p: &'a Value, k: &str) -> Result<&'a str, AutomationError> {
}
impl Headless {
/// Dispatch one request. Unknown methods and bad params are errors, never panics.
/// Dispatch one request. Unknown methods and bad params are errors, never panics
pub fn handle(&mut self, method: &str, p: &Value) -> Result<Value, AutomationError> {
match method {
"ping" => Ok(json!("pong")),
@@ -101,6 +90,7 @@ impl Headless {
hq: bool_of(p, "hq")?,
displacement: f32_of(p, "displacement")?,
};
let r = self.render_png(&o)?;
Ok(json!({ "width": r.width, "height": r.height, "png": base64::engine::general_purpose::STANDARD.encode(r.png) }))
}
@@ -112,17 +102,18 @@ impl Headless {
}
}
/// Answer one request line. A panic inside a command becomes an error reply (edits run on a
/// snapshot, so the session stays consistent).
/// Answer one request line. A panic inside a command becomes an error reply (edits run on a snapshot, so the session stays consistent)
pub fn respond(h: &Mutex<Headless>, line: &str) -> Value {
let req: Value = match serde_json::from_str(line) {
Ok(v) => v,
Err(e) => return json!({"id": null, "ok": false, "error": format!("bad JSON: {e}")}),
};
let id = req.get("id").cloned().unwrap_or(Value::Null);
let Some(method) = req.get("method").and_then(Value::as_str) else {
return json!({"id": id, "ok": false, "error": "`method` is required"});
};
let params = req.get("params").cloned().unwrap_or(Value::Null);
let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| h.lock().unwrap_or_else(PoisonError::into_inner).handle(method, &params)))
.unwrap_or_else(|_| Err(AutomationError::Other(format!("internal error in `{method}`"))));
@@ -132,14 +123,14 @@ pub fn respond(h: &Mutex<Headless>, line: &str) -> Value {
}
}
/// Write one reply line; an oversized reply becomes an error with the same id.
/// Write one reply line; an oversized reply becomes an error with the same id
fn write_reply(w: &mut impl Write, reply: &Value) -> std::io::Result<()> {
let text = json_text(reply).unwrap_or_else(|e| json!({"id": reply.get("id"), "ok": false, "error": e.to_string()}).to_string());
writeln!(w, "{text}")?;
w.flush()
}
/// Serve JSON lines from `r` to `w` until EOF (stdio mode: no authentication).
/// Serve JSON lines from `r` to `w` until EOF (stdio mode: no authentication)
pub fn serve_lines(h: &Mutex<Headless>, mut r: impl BufRead, mut w: impl Write) -> std::io::Result<()> {
let mut line = String::new();
loop {
@@ -151,11 +142,12 @@ pub fn serve_lines(h: &Mutex<Headless>, mut r: impl BufRead, mut w: impl Write)
Ok(LineRead::Line) if line.trim().is_empty() => continue,
Ok(LineRead::Line) => respond(h, &line),
};
write_reply(&mut w, &reply)?;
}
}
/// One TCP connection: the first request must be `auth {token}`, as on the app's channel.
/// One TCP connection: the first request must be `auth {token}`, as on the app's channel
fn serve_connection(h: &Mutex<Headless>, stream: std::net::TcpStream, token: &str) -> std::io::Result<()> {
stream.set_read_timeout(Some(std::time::Duration::from_secs(600)))?;
let mut r = std::io::BufReader::new(stream.try_clone()?);
@@ -186,20 +178,19 @@ fn serve_connection(h: &Mutex<Headless>, stream: std::net::TcpStream, token: &st
}
}
/// Listen on `127.0.0.1:port` (0 picks a port).
/// Listen on `127.0.0.1:port` (0 picks a port)
pub fn bind_tcp(port: u16) -> Result<TcpListener, AutomationError> {
TcpListener::bind(("127.0.0.1", port)).map_err(|e| AutomationError::Io(format!("cannot listen on 127.0.0.1:{port}: {e}")))
}
/// Serve authenticated JSON lines on `127.0.0.1:port` (0 picks a port) with one shared
/// session. `ready` gets the bound address.
/// Serve authenticated JSON lines on `127.0.0.1:port` (0 picks a port) with one shared session. `ready` gets the bound address
pub fn serve_tcp(port: u16, h: Arc<Mutex<Headless>>, token: String, ready: impl FnOnce(std::net::SocketAddr)) -> Result<(), AutomationError> {
let listener = bind_tcp(port)?;
ready(listener.local_addr().map_err(|e| AutomationError::Io(e.to_string()))?);
serve_listener(listener, h, token)
}
/// Serve authenticated JSON lines on a bound listener (see [`bind_tcp`]) with one shared session.
/// Serve authenticated JSON lines on a bound listener (see [`bind_tcp`]) with one shared session
pub fn serve_listener(listener: TcpListener, h: Arc<Mutex<Headless>>, token: String) -> Result<(), AutomationError> {
let limiter = ConnectionLimiter::default();
let token = Arc::new(token);
@@ -209,6 +200,7 @@ pub fn serve_listener(listener: TcpListener, h: Arc<Mutex<Headless>>, token: Str
let _ = writeln!(stream, "{}", json!({"id": null, "ok": false, "error": "too many connections"}));
continue;
};
let (h, token) = (h.clone(), token.clone());
if let Err(e) = std::thread::Builder::new().name("materialcraft-rpc-client".into()).spawn(move || {
let _permit = permit;
@@ -248,7 +240,7 @@ mod tests {
r#"{"id":4,"method":"command.run","params":{"id":"file.open","params":{"path":"/etc/passwd"}}}"#,
"
",
r#"{"id":5,"method":"package.open","params":{"path":"x.mcraft"}}"#,
r#"{"id":5,"method":"package.open","params":{"path":"x.sbs"}}"#,
"
",
r#"{"id":6,"method":"command.batch","params":{"steps":[{"id":"edit.selectAll"},{"id":"nope"},{"id":"edit.selectAll"}]}}"#,
@@ -291,6 +283,7 @@ mod tests {
})
.collect::<Vec<_>>()
};
let denied = talk(&[r#"{"id":1,"method":"session.inspect"}"#]);
assert_eq!(denied[0]["ok"], false);
let ok = talk(&[r#"{"id":1,"method":"auth","params":{"token":"0123456789abcdef0123"}}"#, r#"{"id":2,"method":"ping"}"#]);
+10
View File
@@ -0,0 +1,10 @@
use crate::{BridgeClient, Headless};
use std::sync::{Arc, Mutex};
/// Where tools run
pub enum Backend {
/// An in-process session
Headless(Arc<Mutex<Headless>>),
/// The running desktop app, over its control channel
Bridge(Arc<BridgeClient>),
}
@@ -1,6 +1,4 @@
//! The MCP server (rmcp). Tool names are `snake_case`; each tool maps to one control-channel
//! method (see [`crate::rpc`]), answered in process (headless) or by the running app (bridge).
use super::{Backend, parameter::*};
use std::sync::{Arc, Mutex, PoisonError};
use base64::Engine as _;
@@ -8,8 +6,7 @@ use rmcp::handler::server::router::tool::ToolRouter;
use rmcp::handler::server::wrapper::Parameters;
use rmcp::model::{CallToolResult, ContentBlock as Content};
use rmcp::{ErrorData as McpError, ServerHandler, ServiceExt, tool, tool_handler, tool_router};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde::Serialize;
use serde_json::{Value, json};
use crate::budgets::{MAX_PNG_SIDE, check_png, fit_png, json_text};
@@ -18,215 +15,12 @@ use crate::security::MAX_BATCH_STEPS;
use crate::workspace::authorize_command;
use crate::{AutomationError, BridgeClient, Headless, bad};
/// Where tools run.
pub enum Backend {
/// An in-process session.
Headless(Arc<Mutex<Headless>>),
/// The running desktop app, over its control channel.
Bridge(Arc<BridgeClient>),
}
#[derive(Clone)]
pub struct MaterialcraftMcp {
pub struct MaterialCraftMcp {
backend: Arc<Backend>,
tool_router: ToolRouter<Self>,
}
// ---------------------------------------------------------------------------------------------
// Parameters (serialized back to JSON as the control method's params)
#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
pub struct FilterParams {
/// Only entries whose id or label contains this text (case-insensitive).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub filter: Option<String>,
}
#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
pub struct LibraryParams {
/// Only nodes whose id or label contains this text.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub filter: Option<String>,
/// Only nodes in this library category, e.g. "Noises", "Patterns", "Filters/Blurs".
#[serde(default, skip_serializing_if = "Option::is_none")]
pub category: Option<String>,
}
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct RunParams {
/// Command id from `command_list`, e.g. `graph.node.add`, `graph.connect`, `edit.undo`.
pub id: String,
/// Command parameters (see the command's `params` doc). Omitted = defaults; never a dialog.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub params: Option<Value>,
}
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct BatchParams {
/// Commands run in order; the batch stops at the first error and reports its index.
pub steps: Vec<RunParams>,
}
#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
pub struct NewGraphParams {
/// Template id: empty, pbr (default: six material outputs), bricks, stone_tiles, wood, metal_plates, rusty_metal, lava, marble, wicker, fabric, ground.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub template: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
/// Graph size in pixels, a power of two from 16 to 8192 (default 1024).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub size: Option<u32>,
}
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct NodeAddParams {
/// Node definition id from `library_list`, e.g. `perlin_noise`, `blend`, `levels`, `normal`, `output`.
pub def: String,
/// Graph position `[x, y]` (default: right of `connectFrom`, else the origin).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub at: Option<[f32; 2]>,
/// Parameter values by id (see `library_list`): numbers, `[x, y]`, `"#rrggbb"`, enum indices.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub params: Option<Value>,
/// Wire `{node, port?}`'s output into the new node's first input.
#[serde(default, rename = "connectFrom", skip_serializing_if = "Option::is_none")]
pub connect_from: Option<Value>,
}
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct ConnectParams {
/// Source node id.
pub from: u64,
/// Source output port id (default: its first output).
#[serde(default, rename = "fromPort", skip_serializing_if = "Option::is_none")]
pub from_port: Option<String>,
/// Target node id.
pub to: u64,
/// Target input port id (default: its first input).
#[serde(default, rename = "toPort", skip_serializing_if = "Option::is_none")]
pub to_port: Option<String>,
}
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct ParamSetParams {
/// Node id.
pub id: u64,
/// Parameter id (see `library_list`).
pub param: String,
/// The value: a number, `[x, y]`, `"#rrggbb"`, an enum index, a curve `[[x, y], …]` or a gradient `[[pos, color], …]`.
pub value: Value,
}
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct PathParams {
/// Forward-slash path relative to the workspace root.
pub path: String,
}
#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
pub struct SaveParams {
/// Forward-slash path relative to the write root (`.sbs` is appended unless it ends in `.sbs`
/// or `.mcraft`). Omit to save to the package's own file.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub path: Option<String>,
}
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct BitmapParams {
/// Image file relative to the read root (png, jpg, tga, tif, bmp, webp, exr, hdr).
pub path: String,
/// Resource name (default: the file name).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
}
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct ExportParams {
/// Output folder relative to the write root (created if missing; `.` = the root).
pub dir: String,
/// png (default), jpg, tga, tif, bmp, webp, exr, hdr.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub format: Option<String>,
/// File name pattern with $(graph), $(identifier) and $(usage) (default `$(graph)_$(identifier)`).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub pattern: Option<String>,
/// 8, 16 or 32 bits (default: the graph's output format).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub depth: Option<u32>,
/// Pixels of the larger side, rounded down to a power of two, 16 to 8192 (default: the graph's size).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub size: Option<u32>,
/// Graph index (default: the open graph).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub graph: Option<u32>,
}
#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
pub struct RenderParams {
/// `3d` (default: the material on the 3D view's scene) or `2d` (a node's output).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub view: Option<String>,
/// Pixels, 16..2048.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub width: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub height: Option<u32>,
/// Camera yaw/pitch in degrees for this render only.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub yaw: Option<f32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub pitch: Option<f32>,
/// 3D scene: rounded_cube, cube, sphere, cylinder, plane, torus, material_ball.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub scene: Option<String>,
/// 2D: the node to show (default: the 2D view's node, else the first output).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub node: Option<u64>,
/// 2D: the output port index.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub port: Option<u32>,
/// Cook at the full graph size instead of the preview size.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub full: Option<bool>,
/// 3D: UV repeats of the material on the scene for this render only.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tiling: Option<f32>,
/// 3D beauty render: real displacement from the height output, ambient occlusion and a
/// shadowed key light (slower).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub hq: Option<bool>,
/// With `hq`: displacement depth in scene radii (default 0.04).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub displacement: Option<f32>,
}
#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
pub struct ScreenshotParams {
/// `3d` (default) or `2d`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub view: Option<String>,
}
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct MenuParams {
/// Menu item id from the app's `ui.menu.list`, e.g. `file.save`, `ui.newGraph`, `ui.view.library`.
pub id: String,
}
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct InputParams {
/// Input events in window points, applied in order on the next frames. Each is one of:
/// {"type":"move","pos":[x,y]}, {"type":"down"|"up","pos":[x,y],"button":"left"|"right"|"middle"},
/// {"type":"click"|"doubleClick","pos":[x,y],"button"?}, {"type":"drag","from":[x,y],"to":[x,y],"button"?,"steps"?},
/// {"type":"scroll","pos":[x,y],"delta":[dx,dy]}, {"type":"key","key":"A"|"Enter"|"Space"|…,"modifiers"?:["ctrl","shift","alt"]},
/// {"type":"text","text":"…"}.
pub events: Vec<Value>,
}
// ---------------------------------------------------------------------------------------------
// Results
fn ok_json(v: &Value) -> CallToolResult {
match json_text(v) {
Ok(text) => CallToolResult::success(vec![Content::text(text)]),
@@ -245,7 +39,7 @@ fn to_result(r: Result<Value, AutomationError>) -> Result<CallToolResult, McpErr
})
}
/// A `{width, height, png: base64}` reply (render or app screenshot) as image content.
/// A `{width, height, png: base64}` reply (render or app screenshot) as image content
fn image_result(r: Result<Value, AutomationError>, note: &str, refit: bool) -> Result<CallToolResult, McpError> {
let png = r.and_then(|v| {
let b64 = v.get("png").and_then(Value::as_str).ok_or_else(|| AutomationError::Other("the reply has no PNG".into()))?;
@@ -266,7 +60,7 @@ fn params<T: Serialize>(p: &T) -> Value {
serde_json::to_value(p).unwrap_or(Value::Null)
}
impl MaterialcraftMcp {
impl MaterialCraftMcp {
pub fn headless(h: Headless) -> Self {
Self::with_backend(Backend::Headless(Arc::new(Mutex::new(h))))
}
@@ -276,10 +70,10 @@ impl MaterialcraftMcp {
}
pub fn with_backend(backend: Backend) -> Self {
MaterialcraftMcp { backend: Arc::new(backend), tool_router: Self::tool_router() }
MaterialCraftMcp { backend: Arc::new(backend), tool_router: Self::tool_router() }
}
/// Serve MCP on stdin/stdout until the client disconnects.
/// Serve MCP on stdin/stdout until the client disconnects
pub async fn serve_stdio(self) -> Result<(), AutomationError> {
let running = self.serve(rmcp::transport::stdio()).await.map_err(|e| AutomationError::Other(format!("MCP start: {e}")))?;
running.waiting().await.map_err(|e| AutomationError::Other(e.to_string()))?;
@@ -290,13 +84,12 @@ impl MaterialcraftMcp {
matches!(*self.backend, Backend::Bridge(_))
}
/// One control-channel method on the backend.
/// One control-channel method on the backend
async fn call(&self, method: &str, p: Value) -> Result<Value, AutomationError> {
match &*self.backend {
Backend::Headless(h) => {
let (h, m) = (h.clone(), method.to_string());
// Edits run on snapshots (`Session::edit`), so a panicking command leaves the
// session consistent: keep serving after a poisoned lock.
// Edits run on snapshots (`Session::edit`), so a panicking command leaves the session consistent: keep serving after a poisoned lock
tokio::task::spawn_blocking(move || h.lock().unwrap_or_else(PoisonError::into_inner).handle(&m, &p))
.await
.unwrap_or_else(|_| Err(AutomationError::Other(format!("internal error in `{method}`"))))
@@ -331,11 +124,10 @@ impl MaterialcraftMcp {
}
}
// ---------------------------------------------------------------------------------------------
// Tools
// --------------------------------------------------------------------------------------------- Tools
#[tool_router]
impl MaterialcraftMcp {
impl MaterialCraftMcp {
#[tool(description = "The whole session as JSON: package, graphs, the open graph's nodes (definition, parameters, base \
parameters, ports, cook errors, timings, mean values), connections, frames, comments, pins, exposed inputs, views and history.")]
async fn session_inspect(&self) -> Result<CallToolResult, McpError> {
@@ -408,15 +200,13 @@ impl MaterialcraftMcp {
}
#[tool(
description = "Open an .sbs or .mcraft package (path relative to the read root). Returns the session; `package.warnings` lists what an SBS file holds that MaterialCraft can't read yet (missing nodes are kept as placeholders)."
description = "Open an .sbs package (path relative to the read root). Returns the session; `package.warnings` lists what an SBS file holds that MaterialCraft can't read yet (missing nodes are kept as placeholders)."
)]
async fn package_open(&self, Parameters(p): Parameters<PathParams>) -> Result<CallToolResult, McpError> {
to_result(self.call("package.open", params(&p)).await)
}
#[tool(
description = "Save the package (path relative to the write root; omit to save to its own file). Saves SBS (.sbs, the main format) unless the path ends in .mcraft."
)]
#[tool(description = "Save the package (path relative to the write root; omit to save to its own file). Saves native SBS (.sbs).")]
async fn package_save(&self, Parameters(p): Parameters<SaveParams>) -> Result<CallToolResult, McpError> {
to_result(self.call("package.save", params(&p)).await)
}
@@ -472,11 +262,11 @@ impl MaterialcraftMcp {
name = "materialcraft",
instructions = "MaterialCraft procedural material designer. A package holds graphs of nodes; each graph's output nodes \
(usages baseColor, normal, roughness, metallic, height, ambientOcclusion) make a PBR material. Start with graph_new \
(templates: pbr, bricks, wood, …) or package_open, browse nodes with library_list, build with node_add / node_connect \
(templates: empty, pbr, atomics) or package_open, browse nodes with library_list, build with node_add / node_connect \
/ node_param (or command_run/command_batch for anything else: command_list), check your work with session_inspect and \
view_render (3d, or 2d for one node), then package_save and outputs_export. Undo: command_run edit.undo."
)]
impl ServerHandler for MaterialcraftMcp {}
impl ServerHandler for MaterialCraftMcp {}
#[cfg(test)]
mod tests {
@@ -485,7 +275,7 @@ mod tests {
#[tokio::test(flavor = "multi_thread")]
async fn a_panic_does_not_wedge_the_session() {
let mcp = MaterialcraftMcp::headless(Headless::new(materialcraft_engine::sample_session(), Filesystem::Denied));
let mcp = MaterialCraftMcp::headless(Headless::new(materialcraft_engine::sample_session(), Filesystem::Denied));
let Backend::Headless(h) = &*mcp.backend else { panic!("headless") };
let h2 = h.clone();
let _ = tokio::task::spawn_blocking(move || {
+6
View File
@@ -0,0 +1,6 @@
mod backend;
mod material_craft_mcp;
mod parameter;
pub use backend::Backend;
pub use material_craft_mcp::MaterialCraftMcp;
@@ -0,0 +1,9 @@
use super::RunParams;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct BatchParams {
/// Commands run in order; the batch stops at the first error and reports its index
pub steps: Vec<RunParams>,
}
@@ -0,0 +1,11 @@
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct BitmapParams {
/// Image file relative to the read root (png, jpg, tga, tif, bmp, webp, exr, hdr)
pub path: String,
/// Resource name (default: the file name)
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
}
@@ -0,0 +1,16 @@
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct ConnectParams {
/// Source node id
pub from: u64,
/// Source output port id (default: its first output)
#[serde(default, rename = "fromPort", skip_serializing_if = "Option::is_none")]
pub from_port: Option<String>,
/// Target node id
pub to: u64,
/// Target input port id (default: its first input)
#[serde(default, rename = "toPort", skip_serializing_if = "Option::is_none")]
pub to_port: Option<String>,
}
@@ -0,0 +1,23 @@
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct ExportParams {
/// Output folder relative to the write root (created if missing; `.` = the root)
pub dir: String,
/// png (default), jpg, tga, tif, bmp, webp, exr, hdr
#[serde(default, skip_serializing_if = "Option::is_none")]
pub format: Option<String>,
/// File name pattern with $(graph), $(identifier) and $(usage) (default `$(graph)_$(identifier)`)
#[serde(default, skip_serializing_if = "Option::is_none")]
pub pattern: Option<String>,
/// 8, 16 or 32 bits (default: the graph's output format)
#[serde(default, skip_serializing_if = "Option::is_none")]
pub depth: Option<u32>,
/// Pixels of the larger side, rounded down to a power of two, 16 to 8192 (default: the graph's size)
#[serde(default, skip_serializing_if = "Option::is_none")]
pub size: Option<u32>,
/// Graph index (default: the open graph)
#[serde(default, skip_serializing_if = "Option::is_none")]
pub graph: Option<u32>,
}
@@ -0,0 +1,9 @@
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
pub struct FilterParams {
/// Only entries whose id or label contains this text (case-insensitive)
#[serde(default, skip_serializing_if = "Option::is_none")]
pub filter: Option<String>,
}
@@ -0,0 +1,9 @@
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::Value;
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct InputParams {
/// Input events in window points, applied in order on the next frames
pub events: Vec<Value>,
}
@@ -0,0 +1,12 @@
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
pub struct LibraryParams {
/// Only nodes whose id or label contains this text
#[serde(default, skip_serializing_if = "Option::is_none")]
pub filter: Option<String>,
/// Library category, such as "Atomic nodes" or "Graph items"
#[serde(default, skip_serializing_if = "Option::is_none")]
pub category: Option<String>,
}
@@ -0,0 +1,8 @@
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct MenuParams {
/// Menu item id from the app's `ui.menu.list`, e.g. `file.save`, `ui.newGraph`, `ui.view.library`
pub id: String,
}
@@ -0,0 +1,33 @@
mod batch_params;
mod bitmap_params;
mod connect_params;
mod export_params;
mod filter_params;
mod input_params;
mod library_params;
mod menu_params;
mod new_graph_params;
mod node_add_params;
mod param_set_params;
mod path_params;
mod render_params;
mod run_params;
mod save_params;
mod screenshot_params;
pub use batch_params::BatchParams;
pub use bitmap_params::BitmapParams;
pub use connect_params::ConnectParams;
pub use export_params::ExportParams;
pub use filter_params::FilterParams;
pub use input_params::InputParams;
pub use library_params::LibraryParams;
pub use menu_params::MenuParams;
pub use new_graph_params::NewGraphParams;
pub use node_add_params::NodeAddParams;
pub use param_set_params::ParamSetParams;
pub use path_params::PathParams;
pub use render_params::RenderParams;
pub use run_params::RunParams;
pub use save_params::SaveParams;
pub use screenshot_params::ScreenshotParams;
@@ -0,0 +1,14 @@
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
pub struct NewGraphParams {
/// Template id: empty, pbr (six material outputs), atomics
#[serde(default, skip_serializing_if = "Option::is_none")]
pub template: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
/// Graph size in pixels, a power of two from 16 to 8192 (default 1024)
#[serde(default, skip_serializing_if = "Option::is_none")]
pub size: Option<u32>,
}
@@ -0,0 +1,18 @@
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::Value;
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct NodeAddParams {
/// Node definition id from `library_list`, e.g. `uniform`, `blend`, `levels`, `normal`, `output`
pub def: String,
/// Graph position `[x, y]` (default: right of `connectFrom`, else the origin)
#[serde(default, skip_serializing_if = "Option::is_none")]
pub at: Option<[f32; 2]>,
/// Parameter values by id (see `library_list`): numbers, `[x, y]`, `"#rrggbb"`, enum indices
#[serde(default, skip_serializing_if = "Option::is_none")]
pub params: Option<Value>,
/// Wire `{node, port?}`'s output into the new node's first input
#[serde(default, rename = "connectFrom", skip_serializing_if = "Option::is_none")]
pub connect_from: Option<Value>,
}
@@ -0,0 +1,13 @@
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::Value;
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct ParamSetParams {
/// Node id
pub id: u64,
/// Parameter id (see `library_list`)
pub param: String,
/// The value: a number, `[x, y]`, `"#rrggbb"`, an enum index, a curve `[[x, y], …]` or a gradient `[[pos, color], …]`
pub value: Value,
}
@@ -0,0 +1,8 @@
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct PathParams {
/// Forward-slash path relative to the workspace root
pub path: String,
}
@@ -0,0 +1,40 @@
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
pub struct RenderParams {
/// `3d` (default: the material on the 3D view's scene) or `2d` (a node's output)
#[serde(default, skip_serializing_if = "Option::is_none")]
pub view: Option<String>,
/// Pixels, 16..2048
#[serde(default, skip_serializing_if = "Option::is_none")]
pub width: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub height: Option<u32>,
/// Camera yaw/pitch in degrees for this render only
#[serde(default, skip_serializing_if = "Option::is_none")]
pub yaw: Option<f32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub pitch: Option<f32>,
/// 3D scene: rounded_cube, cube, sphere, cylinder, plane, torus, material_ball
#[serde(default, skip_serializing_if = "Option::is_none")]
pub scene: Option<String>,
/// 2D: the node to show (default: the 2D view's node, else the first output)
#[serde(default, skip_serializing_if = "Option::is_none")]
pub node: Option<u64>,
/// 2D: the output port index
#[serde(default, skip_serializing_if = "Option::is_none")]
pub port: Option<u32>,
/// Cook at the full graph size instead of the preview size
#[serde(default, skip_serializing_if = "Option::is_none")]
pub full: Option<bool>,
/// 3D: UV repeats of the material on the scene for this render only
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tiling: Option<f32>,
/// 3D beauty render: real displacement from the height output, ambient occlusion and a shadowed key light (slower)
#[serde(default, skip_serializing_if = "Option::is_none")]
pub hq: Option<bool>,
/// With `hq`: displacement depth in scene radii (default 0.04)
#[serde(default, skip_serializing_if = "Option::is_none")]
pub displacement: Option<f32>,
}
@@ -0,0 +1,12 @@
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::Value;
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct RunParams {
/// Command id from `command_list`, e.g. `graph.node.add`, `graph.connect`, `edit.undo`
pub id: String,
/// Command parameters (see the command's `params` doc). Omitted = defaults; never a dialog
#[serde(default, skip_serializing_if = "Option::is_none")]
pub params: Option<Value>,
}
@@ -0,0 +1,9 @@
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
pub struct SaveParams {
/// Optional path relative to the write root, with an .sbs extension
#[serde(default, skip_serializing_if = "Option::is_none")]
pub path: Option<String>,
}
@@ -0,0 +1,9 @@
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
pub struct ScreenshotParams {
/// `3d` (default) or `2d`
#[serde(default, skip_serializing_if = "Option::is_none")]
pub view: Option<String>,
}
+12 -22
View File
@@ -1,8 +1,4 @@
//! Capability-based file access for untrusted automation paths (MCP, `serve`).
//!
//! Roots are trusted launch-time configuration (`--read-root`, `--write-root`); request paths
//! are untrusted, forward-slash relative paths resolved by `cap-std` beneath the held directory
//! handle, so `..`, absolute paths, drive prefixes and symlink or junction escapes all fail.
//! Capability-based file access for untrusted automation paths (MCP, `serve`)
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
@@ -14,10 +10,10 @@ use serde_json::Value;
use crate::{AutomationError, bad};
/// Largest file read through automation (the mesh importer's own limit).
/// Largest file read through automation (the mesh importer's own limit)
pub const MAX_READ_BYTES: u64 = 256 << 20;
/// Separate read and write directory capabilities. A missing authority fails closed.
/// Separate read and write directory capabilities. A missing authority fails closed
#[derive(Clone, Default)]
pub struct AuthorizedWorkspace {
read: Option<Arc<Dir>>,
@@ -29,7 +25,7 @@ impl AuthorizedWorkspace {
Ok(Self { read: open_root(read_root, "read")?, write: open_root(write_root, "write")? })
}
/// Read one regular file below the read root.
/// Read one regular file below the read root
pub fn read(&self, path: &str) -> Result<Vec<u8>, AutomationError> {
let rel = relative_path(path)?;
let root = self.read.as_ref().ok_or_else(|| denied("read"))?;
@@ -46,8 +42,7 @@ impl AuthorizedWorkspace {
Ok(bytes)
}
/// Create or replace one file below the write root: a temporary file beside the target,
/// synced and renamed over it. The parent directory must exist.
/// Create or replace one file below the write root: a temporary file beside the target, synced and renamed over it. The parent directory must exist
pub fn write(&self, path: &str, bytes: &[u8]) -> Result<(), AutomationError> {
let rel = relative_path(path)?;
let root = self.write.as_ref().ok_or_else(|| denied("write"))?;
@@ -69,7 +64,7 @@ impl AuthorizedWorkspace {
Ok(())
}
/// Create a directory (and its parents) below the write root.
/// Create a directory (and its parents) below the write root
pub fn create_dir_all(&self, path: &str) -> Result<(), AutomationError> {
let rel = relative_path(path)?;
let root = self.write.as_ref().ok_or_else(|| denied("write"))?;
@@ -87,7 +82,7 @@ fn open_root(path: Option<&Path>, authority: &str) -> Result<Option<Arc<Dir>>, A
Ok(Some(Arc::new(dir)))
}
/// Validate an untrusted path before any I/O (cap-std then confines resolution to the root).
/// Validate an untrusted path before any I/O (cap-std then confines resolution to the root)
pub fn relative_path(raw: &str) -> Result<PathBuf, AutomationError> {
let reject = |why: &str| bad(format!("path rejected ({why}): `{raw}`; use a forward-slash path relative to the workspace root"));
if raw.is_empty() {
@@ -127,18 +122,14 @@ fn file_error(op: &str, path: &str, e: std::io::Error) -> AutomationError {
AutomationError::Io(format!("{op} `{path}` failed: {e}"))
}
/// Engine commands that take host paths (`file.open`, `file.exportTextures`, `resource.import`,
/// `material.save`, …) would bypass the workspace: automation clients use the workspace-scoped
/// methods instead. Any command given a `path` or `dir` is refused, and every `file.*` command
/// but `file.close` and `file.removeUnused` (`file.save` even without `path`: a headless session's path is
/// workspace-relative, not a host path; `file.reimportMesh` without `path` re-reads the
/// embedded mesh).
/// Route file access through the workspace boundary
pub fn authorize_command(id: &str, params: &Value) -> Result<(), AutomationError> {
let has_path = ["path", "dir"].iter().any(|k| params.get(k).is_some_and(|v| !v.is_null()));
let ok = match id {
"file.new" | "file.newPackage" => !has_path,
"file.new" | "file.newPackage" | "file.newAtomicSample" => !has_path,
_ => !id.starts_with("file.") && !has_path,
};
if ok {
Ok(())
} else {
@@ -234,12 +225,11 @@ mod tests {
assert!(authorize_command(id, &json!({"path": "/etc/x"})).is_err(), "{id}");
assert!(authorize_command(id, &json!({"dir": "/etc"})).is_err(), "{id}");
}
assert!(authorize_command("file.new", &json!({"template": "bricks"})).is_ok());
assert!(authorize_command("file.new", &json!({"template": "atomics"})).is_ok());
assert!(authorize_command("graph.node.add", &json!({"def": "blur", "path": null})).is_ok());
}
/// Every registry command documenting a host path must be classified (fails when a new
/// path-taking command is added without an automation policy).
/// Every registry command documenting a host path must be classified (fails when a new path-taking command is added without an automation policy)
#[test]
fn registry_path_params_are_classified() {
let probe = json!({"path": "/outside/probe", "dir": "/outside", "mesh": "/outside/m.obj"});
+11
View File
@@ -0,0 +1,11 @@
use serde::{Deserialize, Serialize};
/// 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,
}
+23
View File
@@ -0,0 +1,23 @@
use serde::{Deserialize, Serialize};
use crate::{OutputFormat, SizeMode};
/// Parameters every node has ("Base parameters")
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct BaseParameters {
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 BaseParameters {
fn default() -> Self {
BaseParameters { size_mode: SizeMode::RelativeToInput, size: [0, 0], format: OutputFormat::Inherit, seed: 0, tiling: [true, true] }
}
}
+34
View File
@@ -0,0 +1,34 @@
/// `[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 }
}
+15
View File
@@ -0,0 +1,15 @@
use serde::{Deserialize, Serialize};
/// Plain text on the graph 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]
}
+13
View File
@@ -0,0 +1,13 @@
use serde::{Deserialize, Serialize};
use crate::NodeId;
/// 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,
}
+9
View File
@@ -0,0 +1,9 @@
#[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,
}
+78
View File
@@ -0,0 +1,78 @@
use serde::{Deserialize, Serialize};
use crate::CurvePoint;
/// 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::new(0.0, 0.0), CurvePoint::new(1.0, 1.0)] }
}
}
impl Curve {
pub fn eval(&self, x: f32) -> f32 {
let Some(first) = self.points.first() else { return x };
if x <= first.x {
return first.y;
}
let Some(index) = self.points.windows(2).position(|points| x <= points[1].x) else {
return self.points.last().map_or(x, |point| point.y);
};
let Some([start, control_left, control_right, end]) = self.segment(index) else { return x };
let bezier = |axis: usize, t: f32| {
let inverse = 1.0 - t;
inverse.powi(3) * start[axis] + 3.0 * inverse.powi(2) * t * control_left[axis] + 3.0 * inverse * t * t * control_right[axis] + t.powi(3) * end[axis]
};
let (mut low, mut high) = (0.0, 1.0);
for _ in 0..24 {
let middle = (low + high) * 0.5;
if bezier(0, middle) < x {
low = middle;
} else {
high = middle;
}
}
bezier(1, (low + high) * 0.5)
}
pub fn segment(&self, index: usize) -> Option<[[f32; 2]; 4]> {
let left = self.points.get(index)?;
let right = self.points.get(index.checked_add(1)?)?;
let span = (right.x - left.x).max(1e-6);
let slope = |index: usize| {
let left = self.points.get(index.saturating_sub(1));
let right = self.points.get((index + 1).min(self.points.len().saturating_sub(1)));
match (left, right) {
(Some(left), Some(right)) if (right.x - left.x).abs() > 1e-6 => (right.y - left.y) / (right.x - left.x),
_ => 0.0,
}
};
let secant = (right.y - left.y) / span;
let mut slopes = [slope(index), slope(index + 1)];
if secant == 0.0 {
slopes = [0.0; 2];
} else {
for slope in &mut slopes {
if *slope * secant < 0.0 {
*slope = 0.0;
}
}
let length_squared = (slopes[0] / secant).powi(2) + (slopes[1] / secant).powi(2);
if length_squared > 9.0 {
slopes = slopes.map(|slope| slope * 3.0 / length_squared.sqrt());
}
}
let left_handle = left.right.unwrap_or([left.x + span / 3.0, left.y + slopes[0] * span / 3.0]);
let right_handle = right.left.unwrap_or([right.x - span / 3.0, right.y - slopes[1] * span / 3.0]);
Some([[left.x, left.y], left_handle, right_handle, [right.x, right.y]])
}
}
+18
View File
@@ -0,0 +1,18 @@
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,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub left: Option<[f32; 2]>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub right: Option<[f32; 2]>,
}
impl CurvePoint {
pub fn new(x: f32, y: f32) -> Self {
Self { x, y, left: None, right: None }
}
}
+26
View File
@@ -0,0 +1,26 @@
use serde::{Deserialize, Serialize};
use crate::Value;
/// The kind of value an exposed graph input carries
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ExposedParameter {
/// 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
}
+31
View File
@@ -0,0 +1,31 @@
use serde::{Deserialize, Serialize};
/// 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 = "default_title_visible")]
pub title_visible: bool,
#[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],
}
fn default_title_visible() -> bool {
true
}
impl Frame {
pub fn contains_position(&self, position: [f32; 2]) -> bool {
let [x, y, width, height] = self.rect;
position[0] >= x && position[1] >= y && position[0] <= x + width && position[1] <= y + height
}
pub fn contains_rect(&self, rect: [f32; 4]) -> bool {
self.contains_position([rect[0], rect[1]]) && self.contains_position([rect[0] + rect[2], rect[1] + rect[3]])
}
}
-67
View File
@@ -1,67 +0,0 @@
//! 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
}
}
+67
View File
@@ -0,0 +1,67 @@
use serde::{Deserialize, Serialize};
use crate::Value;
use crate::FunctionNode;
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct FunctionGraph {
pub nodes: Vec<FunctionNode>,
#[serde(default)]
pub output: Option<u32>,
}
impl FunctionGraph {
pub fn node(&self, id: u32) -> Option<&FunctionNode> {
self.nodes.iter().find(|node| node.id == id)
}
pub fn next_id(&self) -> u32 {
let maximum = self.nodes.iter().map(|node| node.id).max().unwrap_or(0);
if let Some(next) = maximum.checked_add(1) {
return next;
}
(1..=u32::MAX).find(|id| self.node(*id).is_none()).unwrap_or(0)
}
pub fn add(&mut self, operation: &str, inputs: &[u32], value: Option<Value>) -> u32 {
let id = self.next_id();
let horizontal_position = self.nodes.len() as f32 * 140.0;
let node =
FunctionNode { id, type_code: 0, op: operation.into(), inputs: inputs.iter().copied().map(Some).collect(), value, pos: [horizontal_position, 0.0] };
self.nodes.push(node);
id
}
pub fn constant(value: Value) -> FunctionGraph {
let mut graph = FunctionGraph::default();
graph.output = Some(graph.add_constant(value));
graph
}
pub fn add_constant(&mut self, value: Value) -> u32 {
let operation = match &value {
Value::Float(_) => "const_float1",
Value::Float2(_) => "const_float2",
Value::Float3(_) => "const_float3",
Value::Float4(_) | Value::Color(_) => "const_float4",
Value::Int(_) | Value::Enum(_) => "const_int1",
Value::Int2(_) => "const_int2",
Value::Int3(_) => "const_int3",
Value::Int4(_) => "const_int4",
Value::Text(_) => "const_string",
Value::Bool(_) => "const_bool",
_ => "const_float1",
};
let value = match value {
Value::Color(color) => Value::Float4(color),
Value::Enum(index) => Value::Int(index.min(i32::MAX as u32) as i32),
value => value,
};
self.add(operation, &[], Some(value))
}
}
+19
View File
@@ -0,0 +1,19 @@
use serde::{Deserialize, Serialize};
use crate::Value;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct FunctionNode {
pub id: u32,
// Zero requests type inference
#[serde(default)]
pub type_code: u32,
pub op: String,
// Slots follow the native operation's connector order
#[serde(default)]
pub inputs: Vec<Option<u32>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<Value>,
#[serde(default)]
pub pos: [f32; 2],
}
+41
View File
@@ -0,0 +1,41 @@
use serde::{Deserialize, Serialize};
use crate::GradientKey;
/// 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::new(0.0, [0.0, 0.0, 0.0, 1.0]), GradientKey::new(1.0, [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 midpoint = w[0].midpoint.clamp(0.001, 0.999);
let f = ((t - w[0].pos) / span).clamp(0.0, 1.0).powf(0.5_f32.ln() / midpoint.ln());
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));
}
}
+20
View File
@@ -0,0 +1,20 @@
use serde::{Deserialize, Serialize};
/// 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],
#[serde(default = "midpoint")]
pub midpoint: f32,
}
fn midpoint() -> f32 {
0.5
}
impl GradientKey {
pub fn new(pos: f32, color: [f32; 4]) -> Self {
Self { pos, color, midpoint: 0.5 }
}
}
+22 -261
View File
@@ -1,254 +1,17 @@
//! 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>,
/// Dynamic parameters: param id → a function graph computing its value from the graph's
/// inputs at cook time.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub functions: BTreeMap<String, crate::function::FnGraph>,
#[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(),
functions: BTreeMap::new(),
base: BaseParams::default(),
disabled: false,
}
}
}
/// The definition id of a placeholder for a node MaterialCraft does not have (a library node or
/// atomic filter named in an SBS file). The node keeps its wires and the data needed to write it
/// back; its ports come from [`missing_ports`] and it cooks to a soft error.
pub const MISSING_NODE: &str = "missing_node";
/// The ports of a [`MISSING_NODE`] placeholder: input ids, and output ids with whether each is
/// grayscale. They are stored as comma-separated text in its `inputs` and `outputs` parameters
/// (`outputs` entries are `id` or `id:gray`).
pub fn missing_ports(node: &Node) -> (Vec<String>, Vec<(String, bool)>) {
let list = |key: &str| -> Vec<String> {
match node.params.get(key) {
Some(Value::Text(s)) => s.split(',').map(str::trim).filter(|p| !p.is_empty()).take(64).map(str::to_string).collect(),
_ => Vec::new(),
}
};
let outputs = list("outputs")
.into_iter()
.map(|o| match o.split_once(':') {
Some((id, kind)) => (id.to_string(), kind == "gray"),
None => (o, false),
})
.collect();
(list("inputs"), outputs)
}
/// 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
}
/// A named set of input values (graph presets).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Preset {
pub name: String,
pub values: BTreeMap<String, Value>,
}
/// 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,
}
use crate::{Attributes, Comment, Connection, ExposedParameter, Frame, GraphKind, Node, NodeId, OutputFormat, Pin, Preset};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Graph {
pub name: String,
#[serde(default)]
pub kind: GraphKind,
pub function: Option<crate::FunctionGraph>,
pub nodes: Vec<Node>,
pub connections: Vec<Connection>,
#[serde(default)]
@@ -257,31 +20,29 @@ pub struct Graph {
pub comments: Vec<Comment>,
#[serde(default)]
pub pins: Vec<Pin>,
/// log2 of the graph ("parent") size per axis.
/// 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).
pub exposed: Vec<ExposedParameter>,
/// Current values of the exposed inputs (missing = default)
#[serde(default)]
pub inputs: BTreeMap<String, Value>,
/// Named sets of input values.
/// Named sets of input values
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub presets: Vec<Preset>,
/// Preview images of the graph's input nodes: identifier → bitmap resource (a mesh map
/// baked in TextureCraft, say). Instances feed their inputs from their ports instead.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub input_images: BTreeMap<String, String>,
#[serde(default)]
pub attributes: Attributes,
/// The id the next node, frame, comment or pin gets.
/// 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).
/// 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;
@@ -289,7 +50,7 @@ impl Graph {
pub fn new(name: &str) -> Graph {
Graph {
name: name.into(),
kind: GraphKind::Material,
function: None,
nodes: Vec::new(),
connections: Vec::new(),
frames: Vec::new(),
@@ -307,6 +68,10 @@ impl Graph {
}
}
pub fn kind(&self) -> GraphKind {
if self.function.is_some() { GraphKind::Function } else { GraphKind::Material }
}
pub fn alloc_id(&mut self) -> u64 {
let id = self.next_id;
self.next_id = self.next_id.saturating_add(1);
@@ -321,21 +86,19 @@ impl Graph {
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.
/// 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.
/// 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)?;
@@ -353,12 +116,12 @@ impl Graph {
before != self.connections.len()
}
/// The connection feeding `to.to_port`.
/// 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`.
/// 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();
@@ -374,8 +137,6 @@ impl Graph {
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 {
@@ -401,7 +162,7 @@ impl Graph {
out
}
/// Every node upstream of `id` (not including it).
/// 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];
@@ -416,7 +177,7 @@ impl Graph {
out
}
/// Every node downstream of `id` (not including it).
/// 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];
@@ -431,12 +192,12 @@ impl Graph {
out
}
/// The value of exposed input `id` (its default when unset).
/// 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.
/// 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)]
}
@@ -444,7 +205,7 @@ impl Graph {
#[cfg(test)]
mod tests {
use super::*;
use crate::*;
#[test]
fn connect_refuses_cycles_and_replaces_inputs() {
+10
View File
@@ -0,0 +1,10 @@
use serde::{Deserialize, Serialize};
/// 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,
}
+65 -27
View File
@@ -1,33 +1,71 @@
//! # 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;
mod attributes;
mod base_parameters;
mod color;
mod comment;
mod connection;
mod core_error;
mod curve;
mod curve_point;
mod exposed_parameter;
mod frame;
mod function_graph;
mod function_node;
mod gradient;
mod gradient_key;
mod graph;
mod graph_kind;
mod missing_node;
mod node;
mod node_id;
mod output_format;
mod package;
mod pattern_graph;
mod pattern_node;
mod pattern_node_kind;
mod pin;
mod preset;
mod resource;
mod resource_bytes;
mod size_mode;
mod value;
mod value_type;
pub use graph::{
Attributes, BaseParams, Comment, Connection, ExposedParam, Frame, Graph, GraphKind, MAX_SIZE_LOG2, MIN_SIZE_LOG2, MISSING_NODE, Node, NodeId, OutputFormat,
Pin, Preset, SizeMode, missing_ports,
};
pub use package::{PACKAGE_EXT, Package, Resource, ResourceBytes};
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 use attributes::Attributes;
pub use base_parameters::BaseParameters;
pub use color::{linear_to_srgb, parse_color, srgb_to_linear};
pub use comment::Comment;
pub use connection::Connection;
pub use core_error::CoreError;
pub use curve::Curve;
pub use curve_point::CurvePoint;
pub use exposed_parameter::ExposedParameter;
pub use frame::Frame;
pub use function_graph::FunctionGraph;
pub use function_node::FunctionNode;
pub use gradient::Gradient;
pub use gradient_key::GradientKey;
pub use graph::{Graph, MAX_SIZE_LOG2, MIN_SIZE_LOG2};
pub use graph_kind::GraphKind;
pub use missing_node::{MISSING_NODE, missing_ports};
pub use node::Node;
pub use node_id::NodeId;
pub use output_format::OutputFormat;
pub use package::{PACKAGE_EXT, Package};
pub use pattern_graph::PatternGraph;
pub use pattern_node::PatternNode;
pub use pattern_node_kind::PatternNodeKind;
pub use pin::Pin;
pub use preset::Preset;
pub use resource::Resource;
pub use resource_bytes::ResourceBytes;
pub use size_mode::SizeMode;
pub use value::Value;
pub use value_type::ValueType;
pub type Result<T> = std::result::Result<T, CoreError>;
#[cfg(test)]
mod value_tests;
+22
View File
@@ -0,0 +1,22 @@
use crate::Node;
use crate::Value;
pub const MISSING_NODE: &str = "missing_node";
pub fn missing_ports(node: &Node) -> (Vec<String>, Vec<(String, bool)>) {
let list = |key: &str| -> Vec<String> {
match node.params.get(key) {
Some(Value::Text(s)) => s.split(',').map(str::trim).filter(|p| !p.is_empty()).take(64).map(str::to_string).collect(),
_ => Vec::new(),
}
};
let outputs = list("outputs")
.into_iter()
.map(|o| match o.split_once(':') {
Some((id, kind)) => (id.to_string(), kind == "gray"),
None => (o, false),
})
.collect();
(list("inputs"), outputs)
}
+51
View File
@@ -0,0 +1,51 @@
use serde::{Deserialize, Serialize};
use crate::Value;
use crate::{BaseParameters, NodeId};
use std::collections::BTreeMap;
/// 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`, `pixel_processor`, `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, skip_serializing_if = "BTreeMap::is_empty")]
pub functions: BTreeMap<String, crate::FunctionGraph>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub input_values: BTreeMap<String, crate::ValueType>,
#[serde(default)]
pub base: BaseParameters,
/// 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(),
functions: BTreeMap::new(),
input_values: BTreeMap::new(),
base: BaseParameters::default(),
disabled: false,
}
}
}
+4
View File
@@ -0,0 +1,4 @@
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct NodeId(pub u64);
+38
View File
@@ -0,0 +1,38 @@
use serde::{Deserialize, Serialize};
/// 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",
}
}
}
+4 -100
View File
@@ -1,87 +1,8 @@
//! Packages: the document. A package holds graphs and the resources (bitmaps) they use.
use std::hash::{DefaultHasher, Hash, Hasher};
use std::sync::Arc;
use crate::Resource;
use crate::{CoreError, Graph, Result};
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: ResourceBytes,
}
impl Resource {
/// A resource named `name`, stored as `file` in the package.
pub fn new(name: impl Into<String>, file: impl Into<String>, bytes: ResourceBytes) -> Resource {
Resource { name: name.into(), file: file.into(), bytes }
}
}
/// A resource's bytes with a hash of their whole content, computed once when the bytes are
/// set, so caches can key on content (two files of one size are not the same image).
#[derive(Clone, Debug)]
pub struct ResourceBytes {
bytes: Arc<Vec<u8>>,
hash: u64,
}
impl ResourceBytes {
/// Take ownership of `bytes` and hash them.
pub fn new(bytes: Vec<u8>) -> ResourceBytes {
let mut h = DefaultHasher::new();
bytes.hash(&mut h);
ResourceBytes { hash: h.finish(), bytes: Arc::new(bytes) }
}
/// The bytes.
pub fn as_slice(&self) -> &[u8] {
&self.bytes
}
/// Number of bytes.
pub fn len(&self) -> usize {
self.bytes.len()
}
/// Whether there are no bytes.
pub fn is_empty(&self) -> bool {
self.bytes.is_empty()
}
/// Hash of the whole content.
pub fn content_hash(&self) -> u64 {
self.hash
}
/// Whether both values share one allocation (cheap clones of one file).
pub fn ptr_eq(&self, other: &ResourceBytes) -> bool {
Arc::ptr_eq(&self.bytes, &other.bytes)
}
}
impl Default for ResourceBytes {
fn default() -> Self {
ResourceBytes::new(Vec::new())
}
}
impl PartialEq for ResourceBytes {
fn eq(&self, other: &Self) -> bool {
self.hash == other.hash && self.bytes == other.bytes
}
}
pub const PACKAGE_EXT: &str = "sbs";
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Package {
@@ -89,7 +10,7 @@ pub struct Package {
pub graphs: Vec<Graph>,
#[serde(default)]
pub resources: Vec<Resource>,
/// Format version of `package.json`.
/// Format version of `package.json`
#[serde(default = "version")]
pub version: u32,
}
@@ -128,20 +49,3 @@ impl Package {
(1..).map(|i| format!("{base}_{i}")).find(|n| self.graph_by_name(n).is_none()).unwrap_or_else(|| base.to_string())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn same_length_same_prefix_bytes_hash_differently() {
let a = vec![7u8; 200];
let mut b = a.clone();
b[150] = 8;
let (a, b) = (ResourceBytes::new(a), ResourceBytes::new(b));
assert_eq!(a.len(), b.len());
assert_ne!(a.content_hash(), b.content_hash());
assert_ne!(a, b);
assert_eq!(ResourceBytes::default(), ResourceBytes::new(Vec::new()));
}
}
+78
View File
@@ -0,0 +1,78 @@
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
use crate::{PatternNode, PatternNodeKind};
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct PatternGraph {
pub nodes: Vec<PatternNode>,
pub root: Option<u32>,
}
impl PatternGraph {
pub fn with_root(kind: PatternNodeKind) -> Self {
Self {
root: Some(1),
nodes: vec![PatternNode { id: 1, kind, children: vec![None; kind.child_count()], parameters: BTreeMap::new(), position: [0.0; 2] }],
}
}
pub fn add(&mut self, kind: PatternNodeKind) -> Result<u32, String> {
if self.nodes.len() >= 4096 {
return Err("pattern graph exceeds the 4096-node limit".into());
}
let id = (1..=4097).find(|id| self.nodes.iter().all(|node| node.id != *id)).ok_or("no available pattern node id")?;
self.nodes.push(PatternNode {
id,
kind,
children: vec![None; kind.child_count()],
parameters: BTreeMap::new(),
position: [self.nodes.len() as f32 * 160.0, 0.0],
});
self.root.get_or_insert(id);
Ok(id)
}
pub fn validate(&self) -> Result<(), String> {
if self.nodes.len() > 4096 {
return Err("pattern graph exceeds the 4096-node limit".into());
}
let nodes: BTreeMap<_, _> = self.nodes.iter().map(|node| (node.id, node)).collect();
if nodes.len() != self.nodes.len() {
return Err("duplicate pattern node ids".into());
}
if self.root.is_some_and(|root| !nodes.contains_key(&root)) {
return Err("missing pattern root".into());
}
let mut active = BTreeSet::new();
let mut finished = BTreeSet::new();
for root in &self.nodes {
let mut pending = vec![(root.id, false)];
while let Some((id, visited)) = pending.pop() {
if finished.contains(&id) {
continue;
}
let node = nodes.get(&id).ok_or_else(|| format!("missing pattern node {id}"))?;
if node.children.len() != node.kind.child_count() {
return Err(format!("{} requires {} child slots", node.kind.label(), node.kind.child_count()));
}
if visited {
active.remove(&id);
finished.insert(id);
continue;
}
if !active.insert(id) {
return Err(format!("pattern cycle at node {id}"));
}
pending.push((id, true));
pending.extend(node.children.iter().rev().flatten().map(|child| (*child, false)));
}
}
Ok(())
}
}
+13
View File
@@ -0,0 +1,13 @@
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use crate::{PatternNodeKind, Value};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PatternNode {
pub id: u32,
pub kind: PatternNodeKind,
pub children: Vec<Option<u32>>,
pub parameters: BTreeMap<String, Value>,
pub position: [f32; 2],
}
+50
View File
@@ -0,0 +1,50 @@
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum PatternNodeKind {
#[serde(rename = "paramset")]
Quadrant,
#[serde(rename = "markov2")]
Switch,
#[serde(rename = "addnode")]
Iterate,
#[serde(rename = "passthrough")]
Dot,
}
impl PatternNodeKind {
pub const ALL: [Self; 4] = [Self::Quadrant, Self::Switch, Self::Iterate, Self::Dot];
pub fn native_id(self) -> &'static str {
match self {
Self::Quadrant => "paramset",
Self::Switch => "markov2",
Self::Iterate => "addnode",
Self::Dot => "passthrough",
}
}
pub fn label(self) -> &'static str {
match self {
Self::Quadrant => "Quadrant",
Self::Switch => "Switch",
Self::Iterate => "Iterate",
Self::Dot => "Dot",
}
}
pub fn child_count(self) -> usize {
match self {
Self::Quadrant => 4,
Self::Switch | Self::Iterate => 2,
Self::Dot => 1,
}
}
pub fn child_port(self, slot: usize) -> Option<&'static str> {
if self == Self::Dot {
return (slot == 0).then_some("output");
}
["output0", "output1", "output2", "output3"].get(..self.child_count())?.get(slot).copied()
}
}
+9
View File
@@ -0,0 +1,9 @@
use serde::{Deserialize, Serialize};
/// 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],
}
+11
View File
@@ -0,0 +1,11 @@
use serde::{Deserialize, Serialize};
use crate::Value;
use std::collections::BTreeMap;
/// A named set of input values (graph presets)
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Preset {
pub name: String,
pub values: BTreeMap<String, Value>,
}
+21
View File
@@ -0,0 +1,21 @@
use crate::ResourceBytes;
use serde::{Deserialize, Serialize};
/// 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: ResourceBytes,
}
impl Resource {
/// A resource named `name`, stored as `file` in the package
pub fn new(name: impl Into<String>, file: impl Into<String>, bytes: ResourceBytes) -> Resource {
Resource { name: name.into(), file: file.into(), bytes }
}
}
+71
View File
@@ -0,0 +1,71 @@
use std::hash::{DefaultHasher, Hash, Hasher};
use std::sync::Arc;
#[derive(Clone, Debug)]
pub struct ResourceBytes {
bytes: Arc<Vec<u8>>,
hash: u64,
}
impl ResourceBytes {
/// Take ownership of `bytes` and hash them
pub fn new(bytes: Vec<u8>) -> ResourceBytes {
let mut h = DefaultHasher::new();
bytes.hash(&mut h);
ResourceBytes { hash: h.finish(), bytes: Arc::new(bytes) }
}
/// The bytes
pub fn as_slice(&self) -> &[u8] {
&self.bytes
}
/// Number of bytes
pub fn len(&self) -> usize {
self.bytes.len()
}
/// Whether there are no bytes
pub fn is_empty(&self) -> bool {
self.bytes.is_empty()
}
/// Hash of the whole content
pub fn content_hash(&self) -> u64 {
self.hash
}
/// Whether both values share one allocation (cheap clones of one file)
pub fn ptr_eq(&self, other: &ResourceBytes) -> bool {
Arc::ptr_eq(&self.bytes, &other.bytes)
}
}
impl Default for ResourceBytes {
fn default() -> Self {
ResourceBytes::new(Vec::new())
}
}
impl PartialEq for ResourceBytes {
fn eq(&self, other: &Self) -> bool {
self.hash == other.hash && self.bytes == other.bytes
}
}
#[cfg(test)]
mod tests {
use crate::*;
#[test]
fn same_length_same_prefix_bytes_hash_differently() {
let a = vec![7u8; 200];
let mut b = a.clone();
b[150] = 8;
let (a, b) = (ResourceBytes::new(a), ResourceBytes::new(b));
assert_eq!(a.len(), b.len());
assert_ne!(a.content_hash(), b.content_hash());
assert_ne!(a, b);
assert_eq!(ResourceBytes::default(), ResourceBytes::new(Vec::new()));
}
}
+14
View File
@@ -0,0 +1,14 @@
use serde::{Deserialize, Serialize};
/// 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,
}
+45 -208
View File
@@ -1,126 +1,7 @@
//! Parameter values: the typed data a node parameter, an exposed graph input or a function-graph
//! constant holds.
use crate::{Curve, CurvePoint, Gradient, GradientKey, parse_color};
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.
/// A typed parameter value
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "t", content = "v", rename_all = "camelCase")]
pub enum Value {
@@ -130,16 +11,19 @@ pub enum Value {
Float4([f32; 4]),
Int(i32),
Int2([i32; 2]),
Int3([i32; 3]),
Int4([i32; 4]),
Bool(bool),
/// Linear RGBA, 0..1.
/// Linear RGBA, 0..1
Color([f32; 4]),
/// Index into the parameter's options.
/// 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>),
/// A function graph (pixel/value processors, dynamic parameters)
Function(Box<crate::FunctionGraph>),
PatternGraph(Box<crate::PatternGraph>),
}
impl Value {
@@ -163,6 +47,8 @@ impl Value {
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]),
Value::Int3(v) => Some(v[0]),
Value::Int4(v) => Some(v[0]),
_ => None,
}
}
@@ -176,7 +62,7 @@ impl Value {
}
}
/// Up to four floats (missing ones are 0; a color keeps its alpha).
/// 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]),
@@ -185,11 +71,13 @@ impl Value {
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]),
Value::Int3(v) => Some([v[0] as f32, v[1] as f32, v[2] as f32, 0.0]),
Value::Int4(v) => Some(v.map(|x| x as f32)),
_ => None,
}
}
/// Short type name, for errors and inspect output.
/// Short type name, for errors and inspect output
pub fn type_name(&self) -> &'static str {
match self {
Value::Float(_) => "float",
@@ -198,6 +86,8 @@ impl Value {
Value::Float4(_) => "float4",
Value::Int(_) => "int",
Value::Int2(_) => "int2",
Value::Int3(_) => "int3",
Value::Int4(_) => "int4",
Value::Bool(_) => "bool",
Value::Color(_) => "color",
Value::Enum(_) => "enum",
@@ -205,10 +95,11 @@ impl Value {
Value::Curve(_) => "curve",
Value::Gradient(_) => "gradient",
Value::Function(_) => "function",
Value::PatternGraph(_) => "patternGraph",
}
}
/// Coerce a JSON value (from a command or MCP call) into the type of `self`.
/// 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());
@@ -219,12 +110,12 @@ impl Value {
_ => None,
}
};
// A typed value as the API writes it ({"t": .., "v": ..}).
// A typed value as the API writes it ({"t": .., "v": ..})
if let Ok(v) = serde_json::from_value::<Value>(j.clone()) {
if v.type_name() == self.type_name() {
return Some(v);
}
// Another type (a float input bound to an int parameter): coerce its payload.
// Another type (a float input bound to an int parameter): coerce its payload
return j.get("v").and_then(|p| self.coerce_json(p));
}
Some(match self {
@@ -242,104 +133,50 @@ impl Value {
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::Int(_) => Value::Int(match j.as_i64() {
Some(value) => i32::try_from(value).ok()?,
None => {
let value = j.as_f64()?.round();
if !value.is_finite() || value < i32::MIN as f64 || value > i32::MAX as f64 {
return None;
}
value as i32
}
}),
Value::Int2(_) => Value::Int2(parse_integers(j)?),
Value::Int3(_) => Value::Int3(parse_integers(j)?),
Value::Int4(_) => Value::Int4(parse_integers(j)?),
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();
pts.into_iter().filter(|p| p[0].is_finite() && p[1].is_finite()).map(|p| CurvePoint::new(p[0], 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() };
let mut g = Gradient { keys: keys.iter().filter_map(|(p, c)| Some(GradientKey::new(*p, parse_color(c)?))).collect() };
g.sort();
Value::Gradient(g)
}
Value::Function(_) => return None,
Value::Function(_) | Value::PatternGraph(_) => 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;
}
fn parse_integers<const COUNT: usize>(value: &serde_json::Value) -> Option<[i32; COUNT]> {
let components = value.as_array()?;
if components.len() != COUNT {
return None;
}
#[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);
// A typed value of another type converts through its payload.
assert_eq!(Value::Int(0).coerce_json(&serde_json::json!({"t": "float", "v": 8.6})), Some(Value::Int(9)));
assert_eq!(Value::Int(0).coerce_json(&serde_json::json!({"t": "text", "v": "x"})), None);
let mut result = [0; COUNT];
for (target, component) in result.iter_mut().zip(components) {
*target = i32::try_from(component.as_i64()?).ok()?;
}
#[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);
}
Some(result)
}
+36
View File
@@ -0,0 +1,36 @@
use crate::*;
#[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::new(0.0, 0.0), CurvePoint::new(0.3, 0.1), CurvePoint::new(0.7, 0.9), CurvePoint::new(1.0, 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);
// A typed value of another type converts through its payload
assert_eq!(Value::Int(0).coerce_json(&serde_json::json!({"t": "float", "v": 8.6})), Some(Value::Int(9)));
assert_eq!(Value::Int(0).coerce_json(&serde_json::json!({"t": "text", "v": "x"})), 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);
}
+72
View File
@@ -0,0 +1,72 @@
use crate::Value;
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[repr(u32)]
pub enum ValueType {
Boolean = 4,
Integer = 16,
Integer2 = 32,
Integer3 = 64,
Integer4 = 128,
Float = 256,
Float2 = 512,
Float3 = 1024,
Float4 = 2048,
String = 16384,
}
impl ValueType {
pub const ALL: [Self; 10] =
[Self::Float, Self::Float2, Self::Float3, Self::Float4, Self::Integer, Self::Integer2, Self::Integer3, Self::Integer4, Self::Boolean, Self::String];
pub fn from_code(code: u32) -> Option<Self> {
Self::ALL.into_iter().find(|value_type| *value_type as u32 == code)
}
pub fn of(value: &Value) -> Option<Self> {
Some(match value {
Value::Bool(_) => Self::Boolean,
Value::Int(_) | Value::Enum(_) => Self::Integer,
Value::Int2(_) => Self::Integer2,
Value::Int3(_) => Self::Integer3,
Value::Int4(_) => Self::Integer4,
Value::Float(_) => Self::Float,
Value::Float2(_) => Self::Float2,
Value::Float3(_) => Self::Float3,
Value::Float4(_) | Value::Color(_) => Self::Float4,
Value::Text(_) => Self::String,
_ => return None,
})
}
pub fn label(self) -> &'static str {
match self {
Self::Boolean => "Boolean",
Self::Integer => "Integer",
Self::Integer2 => "Integer2",
Self::Integer3 => "Integer3",
Self::Integer4 => "Integer4",
Self::Float => "Float",
Self::Float2 => "Float2",
Self::Float3 => "Float3",
Self::Float4 => "Float4",
Self::String => "String",
}
}
pub fn default_value(self) -> Value {
match self {
Self::Boolean => Value::Bool(false),
Self::Integer => Value::Int(0),
Self::Integer2 => Value::Int2([0; 2]),
Self::Integer3 => Value::Int3([0; 3]),
Self::Integer4 => Value::Int4([0; 4]),
Self::Float => Value::Float(0.0),
Self::Float2 => Value::Float2([0.0; 2]),
Self::Float3 => Value::Float3([0.0; 3]),
Self::Float4 => Value::Float4([0.0; 4]),
Self::String => Value::Text(String::new()),
}
}
}
+7
View File
@@ -0,0 +1,7 @@
fn main() -> Result<(), Box<dyn std::error::Error>> {
let package = materialcraft_engine::atomic_sample()?;
let bytes = materialcraft_engine::formats::sbs::write_sbs(&package)?;
let path = std::env::args().nth(1).unwrap_or_else(|| "atomic_sample.sbs".into());
std::fs::write(path, bytes)?;
Ok(())
}
+41
View File
@@ -0,0 +1,41 @@
use crate::commands::{CommandSpec, bad, has_graph, strp, u64p};
use crate::{AnnotationSelection, Result, Session, cmd};
use serde_json::{Value, json};
pub(crate) fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"graph.annotation.select",
"Select annotation",
[],
None,
"{kind?: frame|comment, id?} clears node selection; omit kind to deselect",
has_graph,
select
)]
}
fn select(session: &mut Session, parameters: &Value) -> Result<Value> {
let selection = match strp(parameters, "kind") {
None => None,
Some(kind) => {
let id = u64p(parameters, "id").ok_or_else(|| bad("graph.annotation.select", "`id` is required"))?;
let selection = match kind {
"frame" => AnnotationSelection::Frame(id),
"comment" => AnnotationSelection::Comment(id),
_ => return Err(bad("graph.annotation.select", "kind must be frame or comment")),
};
if !selection.exists(session.graph()?) {
return Err(bad("graph.annotation.select", "annotation does not exist"));
}
Some(selection)
}
};
session.annotation_selection = selection;
if selection.is_some() {
session.selection.clear();
}
Ok(json!({"selection": selection}))
}
+18
View File
@@ -0,0 +1,18 @@
use materialcraft_core::Graph;
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", content = "id", rename_all = "camelCase")]
pub enum AnnotationSelection {
Frame(u64),
Comment(u64),
}
impl AnnotationSelection {
pub fn exists(self, graph: &Graph) -> bool {
match self {
Self::Frame(id) => graph.frames.iter().any(|frame| frame.id == id),
Self::Comment(id) => graph.comments.iter().any(|comment| comment.id == id),
}
}
}
+83
View File
@@ -0,0 +1,83 @@
use crate::{EngineError, Result};
use materialcraft_core::{FunctionGraph, Graph, Package, PatternGraph, PatternNodeKind, Value, ValueType};
pub fn atomic_sample() -> Result<Package> {
let mut package = Package::new("Atomic sample");
let mut graph = Graph::new("Atomic_sample");
graph.size = [8, 8];
let input = graph.add_node("input_value", [0.0, 0.0]);
graph.node_mut(input)?.params.insert("default".into(), Value::Float(0.35));
graph.node_mut(input)?.params.insert("identifier".into(), Value::Text("brightness".into()));
let value = graph.add_node("value_processor", [200.0, 0.0]);
let mut function = FunctionGraph::default();
let get = function.add("get_float1", &[], Some(Value::Text("brightness".into())));
let two = function.add_constant(Value::Float(2.0));
function.output = Some(function.add("mul", &[get, two], None));
graph.node_mut(value)?.input_values.insert("brightness".into(), ValueType::Float);
graph.node_mut(value)?.params.insert("function".into(), Value::Function(Box::new(function)));
graph.connect(input, "output", value, "brightness")?;
let pixel = graph.add_node("pixel_processor", [400.0, 0.0]);
let mut function = FunctionGraph::default();
let position = function.add("get_float2", &[], Some(Value::Text("$pos".into())));
let horizontal = function.add("swizzle1", &[position], Some(Value::Int(0)));
let brightness = function.add("get_float1", &[], Some(Value::Text("brightness".into())));
function.output = Some(function.add("mul", &[horizontal, brightness], None));
graph.node_mut(pixel)?.params.insert("function".into(), Value::Function(Box::new(function)));
graph.node_mut(pixel)?.params.insert("color_mode".into(), Value::Bool(false));
graph.node_mut(pixel)?.input_values.insert("brightness".into(), ValueType::Float);
graph.connect(value, "output", pixel, "brightness")?;
let pattern = graph.add_node("fx_map", [400.0, 220.0]);
let mut patterns = PatternGraph::default();
let iterate = patterns.add(PatternNodeKind::Iterate).map_err(EngineError::Other)?;
let switch = patterns.add(PatternNodeKind::Switch).map_err(EngineError::Other)?;
let quadrant = patterns.add(PatternNodeKind::Quadrant).map_err(EngineError::Other)?;
for node in &mut patterns.nodes {
match node.kind {
PatternNodeKind::Dot => {}
PatternNodeKind::Iterate => {
node.position = [160.0, 0.0];
node.children = vec![Some(switch), Some(quadrant)];
node.parameters.insert("numberadded".into(), Value::Int(8));
}
PatternNodeKind::Switch => {
node.position = [0.0, 192.0];
node.children = vec![None, Some(quadrant)];
}
PatternNodeKind::Quadrant => {
node.position = [160.0, 384.0];
node.parameters.insert("patterntype".into(), Value::Int(3));
node.parameters.insert("patternsize".into(), Value::Float2([0.12; 2]));
node.parameters.insert("opacity".into(), Value::Float4([0.5, 0.5, 0.5, 1.0]));
let mut function = FunctionGraph::default();
let number = function.add("get_float1", &[], Some(Value::Text("$number".into())));
let step = function.add_constant(Value::Float(std::f32::consts::TAU / 8.0));
let angle = function.add("mul", &[number, step], None);
let radius = function.add_constant(Value::Float(0.3));
function.output = Some(function.add("cartesian", &[radius, angle], None));
node.parameters.insert("frameoffset".into(), Value::Function(Box::new(function)));
}
}
}
patterns.root = Some(iterate);
graph.node_mut(pattern)?.params.insert("pattern".into(), Value::PatternGraph(Box::new(patterns)));
let blend = graph.add_node("blend", [600.0, 0.0]);
graph.node_mut(blend)?.params.insert("mode".into(), Value::Enum(1));
graph.connect(pattern, "output", blend, "foreground")?;
graph.connect(pixel, "output", blend, "background")?;
let blur = graph.add_node("blur", [800.0, 0.0]);
graph.node_mut(blur)?.params.insert("intensity".into(), Value::Float(1.5));
graph.connect(blend, "output", blur, "input")?;
let output = graph.add_node("output", [1000.0, 0.0]);
graph.node_mut(output)?.params.insert("usage".into(), Value::Enum(4));
graph.node_mut(output)?.params.insert("identifier".into(), Value::Text("height".into()));
graph.connect(blur, "output", output, "input")?;
let output = graph.add_node("output", [400.0, -200.0]);
graph.node_mut(output)?.params.insert("identifier".into(), Value::Text("brightness_value".into()));
graph.node_mut(output)?.params.insert("usage".into(), Value::Enum(9));
graph.connect(value, "output", output, "input")?;
package.graphs.push(graph);
Ok(package)
}
@@ -0,0 +1,13 @@
use crate::commands::{CommandSpec, always};
use crate::{Result, Session, cmd};
use serde_json::{Value, json};
pub(crate) fn specs() -> Vec<CommandSpec> {
vec![cmd!("file.newAtomicSample", "Atomic sample", ["File", "New"], None, "{} opens an original graph made only of native primitives", always, create)]
}
fn create(session: &mut Session, _: &Value) -> Result<Value> {
let package = crate::atomic_sample()?;
crate::file_cmds::replace_package(session, package, None);
Ok(json!({"graph": "Atomic_sample"}))
}
+12
View File
@@ -0,0 +1,12 @@
use materialcraft_core::{Connection, Node};
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Clip {
pub nodes: Vec<Node>,
pub connections: Vec<Connection>,
#[serde(default)]
pub inputs: Vec<Connection>,
#[serde(skip)]
pub source_graph: Option<String>,
}
+26 -11
View File
@@ -1,5 +1,4 @@
//! 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.
//! 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};
@@ -13,11 +12,11 @@ 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.
/// Menu placement, e.g. `["Edit"]`. Empty = not in menus
pub menu: &'static [&'static str],
/// Default shortcut in egui notation (`Ctrl+Shift+E`).
/// Default shortcut in egui notation (`Ctrl+Shift+E`)
pub shortcut: Option<&'static str>,
/// Parameters, for humans and agents.
/// Parameters, for humans and agents
pub params: &'static str,
pub enabled: Enabled,
pub run: Run,
@@ -49,10 +48,19 @@ pub fn command_specs() -> &'static [CommandSpec] {
SPECS.get_or_init(|| {
let mut v = Vec::new();
v.extend(crate::file_cmds::specs());
v.extend(crate::atomic_sample_commands::specs());
v.extend(crate::material_cmds::specs());
v.extend(crate::edit_cmds::specs());
v.extend(crate::graph_cmds::specs());
v.extend(crate::annotation_commands::specs());
v.extend(crate::frame_commands::specs());
v.extend(crate::function_commands::specs());
v.extend(crate::comment_commands::specs());
v.extend(crate::node_cmds::specs());
v.extend(crate::node_graph_commands::specs());
v.extend(crate::pattern_graph_commands::specs());
v.extend(crate::connection_commands::specs());
v.extend(crate::value_input_commands::specs());
v.extend(crate::view_cmds::specs());
v.extend(crate::wire_cmds::specs());
v
@@ -63,14 +71,19 @@ 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).
/// 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)
let result = (spec.run)(s, params)?;
if !s.selection.is_empty() || s.annotation_selection.is_some_and(|selection| !s.graph().is_ok_and(|graph| selection.exists(graph))) {
s.annotation_selection = None;
}
Ok(result)
}
/// Every command, as JSON (for `commands` listings and MCP).
/// 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(
@@ -108,17 +121,18 @@ 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.
/// 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.
/// 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(),
@@ -127,6 +141,7 @@ pub(crate) fn ids_param(s: &Session, cmd: &str, p: &J) -> Result<Vec<NodeId>> {
None => s.selection.clone(),
},
};
let g = s.graph()?;
for id in &ids {
g.node(*id).map_err(|_| bad(cmd, format!("no node {}", id.0)))?;
@@ -134,7 +149,7 @@ pub(crate) fn ids_param(s: &Session, cmd: &str, p: &J) -> Result<Vec<NodeId>> {
Ok(ids)
}
/// A 2D point param (`[x, y]`).
/// 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;
+57
View File
@@ -0,0 +1,57 @@
use crate::commands::{CommandSpec, bad, has_graph, point, strp, u64p};
use crate::graph_cmds::nodes_rect;
use crate::{AnnotationSelection, Result, Session, cmd};
use materialcraft_core::Comment;
use serde_json::{Value as J, json};
pub(crate) fn specs() -> Vec<CommandSpec> {
vec![
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),
]
}
fn comment_add(session: &mut Session, parameters: &J) -> Result<J> {
let at = point(parameters, "at").or_else(|| nodes_rect(session, &session.selection).map(|rect| [rect[0], rect[1] - 90.0])).unwrap_or([0.0, -120.0]);
let text = strp(parameters, "text").unwrap_or("Comment").to_string();
session.edit("Add comment", |session| {
let graph = session.graph_mut()?;
let id = graph.alloc_id();
graph.comments.push(Comment { id, text, pos: at, size: [180.0, 70.0] });
session.selection.clear();
session.annotation_selection = Some(AnnotationSelection::Comment(id));
Ok(json!({"id": id}))
})
}
fn comment_edit(session: &mut Session, parameters: &J) -> Result<J> {
let id = u64p(parameters, "id").ok_or_else(|| bad("graph.comment.edit", "`id` is required"))?;
session.edit_merged(&format!("comment{id}"), "Edit comment", |session| {
let comment =
session.graph_mut()?.comments.iter_mut().find(|comment| comment.id == id).ok_or_else(|| bad("graph.comment.edit", format!("no comment {id}")))?;
if let Some(text) = strp(parameters, "text") {
comment.text = text.into();
}
if let Some(position) = point(parameters, "at") {
comment.pos = position;
}
if let Some(size) = point(parameters, "size") {
comment.size = [size[0].max(40.0), size[1].max(24.0)];
}
Ok(J::Null)
})
}
fn comment_delete(session: &mut Session, parameters: &J) -> Result<J> {
let id = u64p(parameters, "id").ok_or_else(|| bad("graph.comment.delete", "`id` is required"))?;
session.edit("Delete comment", |session| {
session.graph_mut()?.comments.retain(|comment| comment.id != id);
Ok(J::Null)
})
}
+120
View File
@@ -0,0 +1,120 @@
use materialcraft_core::NodeId;
use serde_json::Value as J;
use crate::commands::{CommandSpec, bad, has_graph, strp, u64p};
use crate::{Result, Session, cmd};
pub(crate) fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"graph.connect",
"Connect",
[],
None,
"{from, fromPort? (output), to, toPort? (first compatible input), detach? {to, toPort}}",
has_graph,
connect
),
cmd!("graph.disconnect", "Disconnect", [], None, "{to, toPort}", has_graph, disconnect),
]
}
fn connect(session: &mut Session, parameters: &J) -> Result<J> {
let from = NodeId(u64p(parameters, "from").ok_or_else(|| bad("graph.connect", "`from` is required"))?);
let to = NodeId(u64p(parameters, "to").ok_or_else(|| bad("graph.connect", "`to` is required"))?);
let outputs = session.output_ports(from);
let from_port = strp(parameters, "fromPort")
.map(str::to_string)
.or_else(|| outputs.first().cloned())
.ok_or_else(|| bad("graph.connect", "the source has no outputs"))?;
let to_port = match strp(parameters, "toPort") {
Some(port) => port.to_string(),
None => connection_input(session, from, &from_port, to)?,
};
let detached = parameters
.get("detach")
.map(|input| {
let node = u64p(input, "to").map(NodeId).ok_or_else(|| bad("graph.connect", "detach needs `to`"))?;
let port = strp(input, "toPort").ok_or_else(|| bad("graph.connect", "detach needs `toPort`"))?;
let connection = session.graph()?.input_of(node, port).ok_or_else(|| bad("graph.connect", "the detached wire no longer exists"))?;
if connection.from != from || connection.from_port != from_port {
return Err(bad("graph.connect", "the detached wire has a different source"));
}
Ok((node, port.to_string()))
})
.transpose()?;
validate_connection(session, from, &from_port, to, &to_port)?;
session.edit("Connect", |session| {
if let Some((node, port)) = detached {
session.graph_mut()?.disconnect(node, &port);
}
session.graph_mut()?.connect(from, &from_port, to, &to_port)?;
Ok(J::Null)
})
}
pub(crate) fn connection_input(session: &Session, from: NodeId, from_port: &str, to: NodeId) -> Result<String> {
session
.input_ports(to)
.into_iter()
.find(|port| validate_connection(session, from, from_port, to, port).is_ok())
.ok_or_else(|| bad("graph.connect", "the target has no compatible input"))
}
fn validate_connection(session: &Session, from: NodeId, from_port: &str, to: NodeId, to_port: &str) -> Result<()> {
let outputs = session.output_ports(from);
let inputs = session.input_ports(to);
if !outputs.iter().any(|port| port == from_port) {
return Err(bad("graph.connect", format!("no output `{from_port}` on node {}", from.0)));
}
if !inputs.iter().any(|port| port == to_port) {
return Err(bad("graph.connect", format!("no input `{to_port}` on node {}", to.0)));
}
let graph = session.graph()?;
let target = graph.node(to)?;
let source_type = materialcraft_nodes::output_value_type(graph, from).map_err(|error| bad("graph.connect", error))?;
if let Some(expected) = target.input_values.get(to_port) {
if source_type != Some(*expected) {
return Err(bad("graph.connect", format!("input `{to_port}` requires {}", expected.label())));
}
} else if source_type.is_some() && !matches!(target.def.as_str(), "output" | "dot") {
return Err(bad("graph.connect", format!("input `{to_port}` requires an image")));
}
Ok(())
}
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(|graph| graph.node(id).ok().map(|node| materialcraft_eval::ports(&self.pkg, graph, node).0.into_iter().map(|port| port.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(|graph| graph.node(id).ok().map(|node| materialcraft_eval::ports(&self.pkg, graph, node).1.into_iter().map(|port| port.id).collect()))
.unwrap_or_default()
}
}
+71 -12
View File
@@ -1,4 +1,4 @@
//! Edit menu: undo/redo, clipboard, duplicate, delete and selection.
//! Edit menu: undo/redo, clipboard, duplicate, delete and selection
use std::collections::BTreeMap;
@@ -6,8 +6,8 @@ use serde_json::{Value as J, json};
use materialcraft_core::{Connection, NodeId};
use crate::Clip;
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> {
@@ -34,14 +34,40 @@ pub(crate) fn specs() -> Vec<CommandSpec> {
has_selection,
duplicate
),
cmd!("edit.delete", "Delete selection", [], Some("Delete"), "{ids?}", has_selection, delete),
cmd!(
"edit.pasteWithoutLinks",
"Paste without link",
[],
Some("Ctrl+Shift+V"),
"{at?, snapToGrid?} pastes without incoming links",
has_clip_or_param,
|session, parameters| {
let mut parameters = parameters.as_object().cloned().unwrap_or_default();
parameters.insert("withoutLinks".into(), J::Bool(true));
paste(session, &J::Object(parameters))
}
),
cmd!(
"edit.duplicateWithoutLinks",
"Duplicate selection without link",
[],
Some("Ctrl+Shift+D"),
"{ids?, snapToGrid?} duplicates without incoming links",
has_selection,
|session, parameters| {
let mut parameters = parameters.as_object().cloned().unwrap_or_default();
parameters.insert("withoutLinks".into(), J::Bool(true));
duplicate(session, &J::Object(parameters))
}
),
cmd!("edit.delete", "Delete selection", [], Some("Delete"), "{ids?}", has_deletable_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,
has_deletable_selection,
delete_relink
),
cmd!("edit.selectAll", "Select all", [], Some("Ctrl+A"), "{}", has_graph, |s, _| {
@@ -50,13 +76,14 @@ pub(crate) fn specs() -> Vec<CommandSpec> {
}),
cmd!("edit.selectNone", "Deselect", [], None, "{}", always, |s, _| {
s.selection.clear();
s.annotation_selection = None;
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`.
// `clip` may come with the params; the check happens in `paste`
has_graph(s)
}
@@ -65,6 +92,8 @@ fn clip_of(s: &Session, ids: &[NodeId]) -> Result<Clip> {
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(),
inputs: g.connections.iter().filter(|c| !ids.contains(&c.from) && ids.contains(&c.to)).cloned().collect(),
source_graph: Some(g.name.clone()),
})
}
@@ -82,22 +111,22 @@ fn cut(s: &mut Session, p: &J) -> Result<J> {
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>> {
/// Insert copied nodes and their wires with fresh ids
fn insert_clip(s: &mut Session, clip: &Clip, at: Option<[f32; 2]>, offset: [f32; 2], outer: &[Connection], snap: bool) -> 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]];
c.pos = crate::graph_grid::snap_position([n.pos[0] + shift[0], n.pos[1] + shift[1]], snap);
g.nodes.push(c);
}
for c in &clip.connections {
@@ -120,12 +149,16 @@ fn paste(s: &mut Session, p: &J) -> Result<J> {
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");
let keep_inputs = !crate::commands::boolp(p, "withoutLinks").unwrap_or(false) && clip.source_graph.as_deref() == Some(s.graph()?.name.as_str());
let snap = crate::commands::boolp(p, "snapToGrid").unwrap_or(false);
s.edit("Paste", |s| {
let ids = insert_clip(s, &clip, at, [40.0, 40.0], &[])?;
let ids = insert_clip(s, &clip, at, [40.0, 40.0], if keep_inputs { &clip.inputs } else { &[] }, snap)?;
s.selection = ids.clone();
Ok(json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()}))
})
@@ -134,16 +167,38 @@ fn paste(s: &mut Session, p: &J) -> Result<J> {
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)));
let snap = crate::commands::boolp(p, "snapToGrid").unwrap_or(false);
s.edit("Duplicate", |s| {
let new = insert_clip(s, &clip, None, [40.0, 40.0], if keep { &outer } else { &[] })?;
let new = insert_clip(s, &clip, None, [40.0, 40.0], if keep { &clip.inputs } else { &[] }, snap)?;
s.selection = new.clone();
Ok(json!({"ids": new.iter().map(|i| i.0).collect::<Vec<_>>()}))
})
}
fn has_deletable_selection(session: &Session) -> std::result::Result<(), String> {
if session.annotation_selection.is_some() { has_graph(session) } else { has_selection(session) }
}
fn delete_annotation(session: &mut Session) -> Result<J> {
let selection = session.annotation_selection;
session.edit("Delete annotation", |session| {
let graph = session.graph_mut()?;
match selection {
Some(crate::AnnotationSelection::Frame(id)) => graph.frames.retain(|frame| frame.id != id),
Some(crate::AnnotationSelection::Comment(id)) => graph.comments.retain(|comment| comment.id != id),
None => {}
}
session.annotation_selection = None;
Ok(json!({"deleted": 1}))
})
}
fn delete(s: &mut Session, p: &J) -> Result<J> {
if s.annotation_selection.is_some() && p.get("ids").is_none() {
return delete_annotation(s);
}
let ids = ids_param(s, "edit.delete", p)?;
s.edit("Delete", |s| {
s.graph_mut()?.remove_nodes(&ids);
@@ -156,6 +211,10 @@ fn delete(s: &mut Session, p: &J) -> Result<J> {
}
fn delete_relink(s: &mut Session, p: &J) -> Result<J> {
if s.annotation_selection.is_some() && p.get("ids").is_none() {
return delete_annotation(s);
}
let ids = ids_param(s, "edit.deleteRelink", p)?;
s.edit("Delete and relink", |s| {
let g = s.graph_mut()?;
+15
View File
@@ -0,0 +1,15 @@
#[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),
}
+5
View File
@@ -0,0 +1,5 @@
/// One exported file
pub struct Exported {
pub file: String,
pub bytes: Vec<u8>,
}
+61 -111
View File
@@ -1,9 +1,4 @@
//! 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`).
//!
//! SBS (`.sbs`) is the main project format; `.mcraft` packages still open and save as `.mcraft`.
//! What an SBS file holds that MaterialCraft can't read is a warning (Console, `package.warnings`), never an error.
pub use crate::Exported;
use serde_json::{Value as J, json};
@@ -21,7 +16,7 @@ pub(crate) fn specs() -> Vec<CommandSpec> {
"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",
"{name?, kind? (material|function), template? (see graph.templates), size? (px, power of two)} adds a new graph to the package and opens it",
always,
new_graph
),
@@ -31,19 +26,11 @@ pub(crate) fn specs() -> Vec<CommandSpec> {
"Open...",
["File"],
Some("Ctrl+O"),
"{path} opens an .sbs or .mcraft package (or a .mcmat material's source); returns `warnings` for what an SBS file holds that MaterialCraft can't read yet, and `path`, null for a file another program wrote (Save then needs a new `path`)",
"{path} opens an SBS package; returns `warnings` and `path` (null when unsupported content requires Save As)",
always,
open
),
cmd!(
"file.save",
"Save",
["File"],
Some("Ctrl+S"),
"{path?} saves the package to its own file or `path`: SBS (.sbs, the default; appended when `path` has no package extension) or .mcraft",
always,
save
),
cmd!("file.save", "Save", ["File"], Some("Ctrl+S"), "{path?} saves native SBS to the current 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",
@@ -69,36 +56,56 @@ pub(crate) fn specs() -> Vec<CommandSpec> {
]
}
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);
fn new_graph(session: &mut Session, parameters: &J) -> Result<J> {
let kind = match strp(parameters, "kind").unwrap_or("material") {
"material" => materialcraft_core::GraphKind::Material,
"function" => materialcraft_core::GraphKind::Function,
_ => return Err(bad("file.new", "kind must be material or function")),
};
let template_id = strp(parameters, "template").unwrap_or("pbr");
let label = if kind == materialcraft_core::GraphKind::Function {
"Function Graph"
} else {
TEMPLATES.iter().find(|entry| entry.0 == template_id).map_or("Graph", |entry| entry.1)
};
let size = u64p(parameters, "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}))
let base = strp(parameters, "name").map(str::to_string).unwrap_or_else(|| label.replace(' ', "_"));
session.edit("New graph", |session| {
let name = session.pkg.unique_graph_name(&base);
let graph = if kind == materialcraft_core::GraphKind::Function {
let mut graph = materialcraft_core::Graph::new(&name);
graph.function = Some(materialcraft_core::FunctionGraph::default());
graph
} else {
template(template_id, &name, log2)?
};
session.pkg.graphs.push(graph);
session.graph = session.pkg.graphs.len() - 1;
session.selection.clear();
session.annotation_selection = None;
session.view2d.node = None;
Ok(json!({"graph": session.graph, "name": name, "kind": kind}))
})
}
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));
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.
/// 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.clipboard = None;
s.clear_decoded();
s.path = path;
s.graph = 0;
s.selection.clear();
s.annotation_selection = None;
s.view2d.node = None;
s.reset_history();
s.modified = false;
@@ -106,97 +113,45 @@ pub fn replace_package(s: &mut Session, pkg: Package, path: Option<String>) {
s.load_warnings.clear();
}
/// A package file format.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PackageFormat {
/// SBS XML, the main project format.
Sbs,
/// The older native zip format.
Mcraft,
}
impl PackageFormat {
/// The format a file at `path` is saved in: `.mcraft` stays `.mcraft`, anything else is SBS.
pub fn of_path(path: &str) -> PackageFormat {
if has_extension(path, PackageFormat::Mcraft.ext()) { PackageFormat::Mcraft } else { PackageFormat::Sbs }
}
pub fn ext(self) -> &'static str {
match self {
PackageFormat::Sbs => materialcraft_formats::sbs::SBS_EXT,
PackageFormat::Mcraft => materialcraft_core::PACKAGE_EXT,
}
}
}
fn has_extension(path: &str, ext: &str) -> bool {
path.rsplit_once('.').is_some_and(|(_, e)| e.eq_ignore_ascii_case(ext))
}
/// `path` with `.sbs` appended unless it already ends in `.sbs` or `.mcraft`.
pub fn package_path(path: &str) -> String {
if [PackageFormat::Sbs, PackageFormat::Mcraft].iter().any(|f| has_extension(path, f.ext())) {
path.to_string()
} else {
format!("{path}.{}", PackageFormat::Sbs.ext())
}
if has_extension(path, materialcraft_formats::sbs::SBS_EXT) { path.to_string() } else { format!("{path}.sbs") }
}
/// Open package bytes on any platform: SBS, `.mcraft`, or a `.mcmat` material's source package.
pub fn open_bytes(s: &mut Session, bytes: &[u8], name: Option<String>) -> Result<()> {
open_bytes_linked(s, bytes, name, &|_| None)
pub fn open_bytes(session: &mut Session, bytes: &[u8], name: Option<String>) -> Result<()> {
open_bytes_linked(session, bytes, name, &|_| None)
}
/// [`open_bytes`] with `linked` loading files an SBS package links to; materials and SBS files from other programs open unnamed so Save can't overwrite them.
pub fn open_bytes_linked(s: &mut Session, bytes: &[u8], name: Option<String>, linked: &dyn Fn(&str) -> Option<Vec<u8>>) -> Result<()> {
pub fn open_bytes_linked(session: &mut Session, bytes: &[u8], name: Option<String>, linked: &dyn Fn(&str) -> Option<Vec<u8>>) -> Result<()> {
if materialcraft_formats::material::is_material(bytes) {
let (manifest, source) = materialcraft_formats::material::read_material(bytes)?;
replace_package(s, materialcraft_formats::load_package(&source)?, None);
s.graph = s.pkg.graph_by_name(&manifest.graph).map_or(0, |(i, _)| i);
return Ok(());
}
// A broken `.sbs` should report an SBS error, but a renamed zip package still opens
let named_sbs = name.as_deref().is_some_and(|n| has_extension(n, PackageFormat::Sbs.ext())) && !bytes.starts_with(b"PK");
if !named_sbs && !materialcraft_formats::sbs::is_sbs(bytes) {
replace_package(s, materialcraft_formats::load_package(bytes)?, name);
replace_package(session, materialcraft_formats::sbs::read_sbs(&source, "source.sbs", &|_| None)?.pkg, None);
session.graph = session.pkg.graph_by_name(&manifest.graph).map_or(0, |(index, _)| index);
return Ok(());
}
let read = materialcraft_formats::sbs::read_sbs(bytes, name.as_deref().unwrap_or(""), linked)?;
let from_elsewhere = !read.exact;
replace_package(s, read.pkg, if from_elsewhere { None } else { name.clone() });
if !read.warnings.is_empty() {
s.warn(format!("{} opened with {} warning(s): what MaterialCraft can't read yet is listed below", s.pkg.name, read.warnings.len()));
for warning in &read.warnings {
s.warn(warning.clone());
}
let path = if read.warnings.is_empty() { name } else { None };
replace_package(session, read.pkg, path);
for warning in &read.warnings {
session.warn(warning.clone());
}
if from_elsewhere && let Some(file) = &name {
s.log(format!("{file} was not saved by MaterialCraft: Save asks for a new file, so the original keeps everything MaterialCraft can't read"));
}
s.load_warnings = read.warnings;
session.load_warnings = read.warnings;
Ok(())
}
/// The package as SBS bytes, the main project format.
pub fn save_bytes(s: &Session) -> Result<Vec<u8>> {
save_bytes_as(s, PackageFormat::Sbs)
pub fn save_bytes(session: &Session) -> Result<Vec<u8>> {
Ok(materialcraft_formats::sbs::write_sbs(&session.pkg)?)
}
pub fn save_bytes_as(s: &Session, format: PackageFormat) -> Result<Vec<u8>> {
Ok(match format {
PackageFormat::Sbs => materialcraft_formats::sbs::write_sbs(&s.pkg)?,
PackageFormat::Mcraft => materialcraft_formats::save_package(&s.pkg)?,
})
}
/// Largest file an SBS package may link to.
/// Largest file an SBS package may link to
#[cfg(not(target_arch = "wasm32"))]
const MAX_LINKED_FILE_BYTES: u64 = 256 << 20;
/// Reads files an SBS package at `path` links to: plain relative paths that resolve inside its folder.
/// Reads files an SBS package at `path` links to: plain relative paths that resolve inside its folder
#[cfg(not(target_arch = "wasm32"))]
pub fn linked_files(path: &str) -> impl Fn(&str) -> Option<Vec<u8>> + use<> {
let parent = std::path::Path::new(path).parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or(std::path::Path::new("."));
@@ -219,7 +174,7 @@ pub fn linked_files(path: &str) -> impl Fn(&str) -> Option<Vec<u8>> + use<> {
}
}
/// Open the package file at `path` (native), with the bitmaps an SBS package keeps next to it.
/// Open the package file at `path` (native), with the bitmaps an SBS package keeps next to it
#[cfg(not(target_arch = "wasm32"))]
pub fn open_file(s: &mut Session, path: &str) -> Result<()> {
let bytes = std::fs::read(path).map_err(|e| bad("file.open", format!("{path}: {e}")))?;
@@ -246,7 +201,7 @@ fn save(s: &mut Session, p: &J) -> Result<J> {
None => s.path.clone().ok_or_else(|| bad("file.save", "the package has no file yet (new, or opened from another program): give a `path`"))?,
};
let bytes = save_bytes_as(s, PackageFormat::of_path(&path))?;
let bytes = save_bytes(s)?;
materialcraft_formats::write_atomic(std::path::Path::new(&path), &bytes)?;
s.path = Some(path.clone());
s.modified = false;
@@ -259,18 +214,12 @@ 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).
/// 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>, size: Option<u32>) -> Result<Vec<Exported>> {
let mut pkg = s.pkg.clone();
if let Some(px) = size {
let g = pkg.graph_mut(gi)?;
// The larger side becomes `px`; the other keeps its proportion.
// The larger side becomes `px`; the other keeps its proportion
let target = 31 - px.clamp(16, 8192).leading_zeros();
let bounded = g.size.map(|l| l.clamp(4, 13));
let larger = bounded[0].max(bounded[1]);
@@ -294,7 +243,7 @@ pub fn export_outputs(s: &Session, gi: usize, ext: &str, pattern: &str, depth: O
Ok(out)
}
/// Export params: (graph index, extension, pattern, depth, size).
/// Export params: (graph index, extension, pattern, depth, size)
pub type ExportArgs = (usize, String, String, Option<Depth>, Option<u32>);
pub fn export_params(s: &Session, p: &J) -> Result<ExportArgs> {
@@ -312,6 +261,7 @@ pub fn export_params(s: &Session, p: &J) -> Result<ExportArgs> {
Some(32) => Some(Depth::F32),
Some(d) => return Err(bad("file.export", format!("depth must be 8, 16 or 32, not {d}"))),
};
let size = u64p(p, "size").filter(|&px| px > 0).map(|px| px.min(u64::from(u32::MAX)) as u32);
Ok((gi, ext, pattern, depth, size))
}
@@ -337,13 +287,13 @@ 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.
/// 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)?;
s.edit("Import bitmap", |s| Ok(push_resource(&mut s.pkg, file, bytes, name)))
}
/// Add `bytes` to `pkg` as a resource named `name` (or after `file`), made unique; returns the name.
/// Add `bytes` to `pkg` as a resource named `name` (or after `file`), made unique; returns the name
pub(crate) fn push_resource(pkg: &mut Package, file: &str, bytes: Vec<u8>, name: Option<&str>) -> String {
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()));
+110
View File
@@ -0,0 +1,110 @@
use crate::commands::{CommandSpec, bad, boolp, has_graph, point, strp, u64p};
use crate::graph_cmds::nodes_rect;
use crate::{AnnotationSelection, FrameContents, Result, Session, cmd};
use materialcraft_core::Frame;
use serde_json::{Value as J, json};
pub(crate) fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"graph.frame.add",
"Add Frame",
[],
None,
"{title?, titleVisible?, description?, 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?, titleVisible?, description?, rect?, color?}", has_graph, frame_edit),
cmd!("graph.frame.delete", "Delete frame", [], None, "{id}", has_graph, frame_delete),
cmd!("graph.frame.move", "Move frame and contents", [], None, "{id, by: [dx, dy], snapToGrid?}", has_graph, frame_move),
]
}
fn rect_of(parameters: &J) -> Option<[f32; 4]> {
let values = parameters.get("rect")?.as_array()?;
let value: Vec<f32> = values.iter().filter_map(J::as_f64).map(|value| value as f32).filter(|value| value.is_finite()).collect();
(value.len() == 4).then(|| [value[0].clamp(-1e7, 1e7), value[1].clamp(-1e7, 1e7), value[2].clamp(10.0, 1e6), value[3].clamp(10.0, 1e6)])
}
fn color_of(parameters: &J) -> Option<[f32; 4]> {
materialcraft_core::parse_color(parameters.get("color")?)
}
fn frame_add(session: &mut Session, parameters: &J) -> Result<J> {
let rect = match rect_of(parameters) {
Some(rect) => rect,
None => nodes_rect(session, &session.selection)
.map(|rect| [rect[0] - 24.0, rect[1] - 44.0, rect[2] + 48.0, rect[3] + 68.0])
.unwrap_or([0.0, 0.0, 400.0, 260.0]),
};
let title = strp(parameters, "title").unwrap_or("Frame").to_string();
let color = color_of(parameters).unwrap_or([materialcraft_core::srgb_to_linear(0.102), materialcraft_core::srgb_to_linear(0.553), 1.0, 0.251]);
let title_visible = boolp(parameters, "titleVisible").unwrap_or(true);
let description = strp(parameters, "description").unwrap_or("").to_string();
session.edit("Add frame", |session| {
let graph = session.graph_mut()?;
let id = graph.alloc_id();
graph.frames.push(Frame { id, title, title_visible, description, rect, color });
session.selection.clear();
session.annotation_selection = Some(AnnotationSelection::Frame(id));
Ok(json!({"id": id}))
})
}
fn frame_edit(session: &mut Session, parameters: &J) -> Result<J> {
let id = u64p(parameters, "id").ok_or_else(|| bad("graph.frame.edit", "`id` is required"))?;
session.edit_merged(&format!("frame{id}"), "Edit frame", |session| {
let frame = session.graph_mut()?.frames.iter_mut().find(|frame| frame.id == id).ok_or_else(|| bad("graph.frame.edit", format!("no frame {id}")))?;
if let Some(text) = strp(parameters, "title") {
frame.title = text.into();
}
if let Some(visible) = boolp(parameters, "titleVisible") {
frame.title_visible = visible;
}
if let Some(text) = strp(parameters, "description") {
frame.description = text.into();
}
if let Some(rect) = rect_of(parameters) {
frame.rect = rect;
}
if let Some(color) = color_of(parameters) {
frame.color = color;
}
Ok(J::Null)
})
}
fn frame_delete(session: &mut Session, parameters: &J) -> Result<J> {
let id = u64p(parameters, "id").ok_or_else(|| bad("graph.frame.delete", "`id` is required"))?;
session.edit("Delete frame", |session| {
let graph = session.graph_mut()?;
let previous_count = graph.frames.len();
graph.frames.retain(|frame| frame.id != id);
if previous_count == graph.frames.len() {
return Err(bad("graph.frame.delete", format!("no frame {id}")));
}
Ok(J::Null)
})
}
fn frame_move(session: &mut Session, parameters: &J) -> Result<J> {
let id = u64p(parameters, "id").ok_or_else(|| bad("graph.frame.move", "`id` is required"))?;
let offset = point(parameters, "by").ok_or_else(|| bad("graph.frame.move", "`by` is required"))?;
let offset = crate::graph_grid::snap_position(offset, boolp(parameters, "snapToGrid").unwrap_or(false));
let graph = session.graph()?;
let frame = graph.frames.iter().find(|frame| frame.id == id).ok_or_else(|| bad("graph.frame.move", "frame does not exist"))?;
let contents = FrameContents::capture(graph, frame);
session.edit("Move frame and contents", |session| {
contents.translate(session.graph_mut()?, offset);
Ok(J::Null)
})
}
+51
View File
@@ -0,0 +1,51 @@
use materialcraft_core::{Frame, Graph, NodeId};
#[derive(Clone, Debug, Default)]
pub struct FrameContents {
pub nodes: Vec<NodeId>,
pub function_nodes: Vec<u32>,
pub comments: Vec<u64>,
pub frames: Vec<u64>,
pub pins: Vec<u64>,
}
impl FrameContents {
pub fn capture(graph: &Graph, frame: &Frame) -> Self {
Self {
function_nodes: graph
.function
.iter()
.flat_map(|function| &function.nodes)
.filter(|node| frame.contains_position(node.pos))
.map(|node| node.id)
.collect(),
nodes: graph.nodes.iter().filter(|node| frame.contains_position(node.pos)).map(|node| node.id).collect(),
comments: graph.comments.iter().filter(|comment| frame.contains_position(comment.pos)).map(|comment| comment.id).collect(),
frames: graph.frames.iter().filter(|candidate| candidate.id == frame.id || frame.contains_rect(candidate.rect)).map(|frame| frame.id).collect(),
pins: graph.pins.iter().filter(|pin| frame.contains_position(pin.pos)).map(|pin| pin.id).collect(),
}
}
pub fn translate(&self, graph: &mut Graph, offset: [f32; 2]) {
let translate = |position: [f32; 2]| crate::graph_grid::snap_position([position[0] + offset[0], position[1] + offset[1]], false);
if let Some(function) = &mut graph.function {
for node in function.nodes.iter_mut().filter(|node| self.function_nodes.contains(&node.id)) {
node.pos = translate(node.pos);
}
}
for node in graph.nodes.iter_mut().filter(|node| self.nodes.contains(&node.id)) {
node.pos = translate(node.pos);
}
for comment in graph.comments.iter_mut().filter(|comment| self.comments.contains(&comment.id)) {
comment.pos = translate(comment.pos);
}
for frame in graph.frames.iter_mut().filter(|frame| self.frames.contains(&frame.id)) {
let position = translate([frame.rect[0], frame.rect[1]]);
frame.rect[0] = position[0];
frame.rect[1] = position[1];
}
for pin in graph.pins.iter_mut().filter(|pin| self.pins.contains(&pin.id)) {
pin.pos = translate(pin.pos);
}
}
}
+23
View File
@@ -0,0 +1,23 @@
use crate::commands::{CommandSpec, bad, has_graph};
use crate::{Result, Session, cmd};
use materialcraft_core::FunctionGraph;
use serde_json::{Value as Json, json};
pub(crate) fn specs() -> Vec<CommandSpec> {
vec![cmd!("graph.function.set", "Edit Function Graph", [], None, "{function} replaces the current function graph", has_graph, set)]
}
fn set(session: &mut Session, parameters: &Json) -> Result<Json> {
if session.graph()?.function.is_none() {
return Err(bad("graph.function.set", "the current graph is not a Function Graph"));
}
let graph: FunctionGraph =
serde_json::from_value(parameters.get("function").cloned().unwrap_or(Json::Null)).map_err(|error| bad("graph.function.set", error.to_string()))?;
materialcraft_nodes::function::node_types(&graph).map_err(|error| bad("graph.function.set", error))?;
session.edit("Edit Function Graph", |session| {
session.graph_mut()?.function = Some(graph);
Ok(json!({}))
})
}
+16 -118
View File
@@ -1,9 +1,8 @@
//! Graph commands: open/rename/delete graphs, size and seed, frames, comments, pins, exposed
//! inputs, selection, alignment and "create graph from selection".
//! 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 materialcraft_core::{ExposedParameter, 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};
@@ -25,20 +24,6 @@ pub(crate) fn specs() -> Vec<CommandSpec> {
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!(
@@ -95,6 +80,7 @@ fn open(s: &mut Session, p: &J) -> Result<J> {
let i = graph_index(s, p)?;
s.graph = i;
s.selection.clear();
s.annotation_selection = None;
s.view2d.node = None;
s.dirty = true;
Ok(json!({"graph": i, "name": s.pkg.graphs.get(i).map(|g| g.name.clone())}))
@@ -108,7 +94,7 @@ fn rename(s: &mut Session, p: &J) -> Result<J> {
}
s.edit("Rename graph", |s| {
let old = std::mem::replace(&mut s.pkg.graph_mut(i)?.name, name.clone());
// Instances follow the rename.
// 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())) {
@@ -124,8 +110,10 @@ 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.clipboard = None;
s.graph = s.graph.min(s.pkg.graphs.len().saturating_sub(1));
s.selection.clear();
s.annotation_selection = None;
s.view2d.node = None;
Ok(json!({"graphs": s.pkg.graphs.len()}))
})
@@ -139,6 +127,7 @@ fn duplicate(s: &mut Session, p: &J) -> Result<J> {
s.pkg.graphs.push(g);
s.graph = s.pkg.graphs.len() - 1;
s.selection.clear();
s.annotation_selection = None;
Ok(json!({"graph": s.graph}))
})
}
@@ -151,6 +140,7 @@ fn size(s: &mut Session, p: &J) -> Result<J> {
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];
@@ -166,6 +156,7 @@ fn format(s: &mut Session, p: &J) -> Result<J> {
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)
@@ -180,7 +171,7 @@ fn cook(s: &mut Session, p: &J) -> Result<J> {
"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])})
"size": r.outputs.first().and_then(materialcraft_eval::NodeOutput::as_image).map(|i| [i.w, i.h])})
}).collect::<Vec<_>>(),
}))
}
@@ -197,17 +188,7 @@ fn attributes(s: &mut Session, p: &J) -> Result<J> {
})
}
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).
/// 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];
@@ -217,90 +198,6 @@ pub fn nodes_rect(s: &Session, ids: &[NodeId]) -> Option<[f32; 4]> {
(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| {
@@ -325,7 +222,7 @@ fn exposed_add(s: &mut Session, p: &J) -> Result<J> {
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.
// 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());
@@ -342,7 +239,7 @@ fn exposed_add(s: &mut Session, p: &J) -> Result<J> {
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 {
let ep = ExposedParameter {
id: id.clone(),
label: strp(p, "label").unwrap_or(&id).to_string(),
group: strp(p, "group").unwrap_or("").to_string(),
@@ -351,6 +248,7 @@ fn exposed_add(s: &mut Session, p: &J) -> Result<J> {
max: f32p(p, "max").unwrap_or(max),
options,
};
s.edit("Expose parameter", |s| {
let g = s.graph_mut()?;
g.exposed.push(ep);
@@ -406,7 +304,7 @@ fn preset_apply(s: &mut Session, p: &J) -> Result<J> {
let g = s.graph_mut()?;
let preset = g.presets.iter().find(|x| x.name == name).cloned().ok_or_else(|| bad("graph.preset.apply", format!("no preset `{name}`")))?;
for (k, v) in preset.values {
// Only inputs that still exist, with their current type.
// Only inputs that still exist, with their current type
if g.exposed.iter().any(|e| e.id == k && e.default.type_name() == v.type_name()) {
g.inputs.insert(k, v);
}
@@ -501,7 +399,7 @@ fn from_selection(s: &mut Session, p: &J) -> Result<J> {
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.
// 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);
+8
View File
@@ -0,0 +1,8 @@
pub const GRID_SPACING: f32 = 32.0;
pub fn snap_position(position: [f32; 2], enabled: bool) -> [f32; 2] {
position.map(|coordinate| {
let coordinate = if coordinate.is_finite() { coordinate.clamp(-1e7, 1e7) } else { 0.0 };
if enabled { (coordinate / GRID_SPACING).round() * GRID_SPACING } else { coordinate }
})
}
+11 -6
View File
@@ -1,4 +1,4 @@
//! `session.inspect`: everything an agent needs to verify its work without a screenshot.
//! `session.inspect`: everything an agent needs to verify its work without a screenshot
use serde_json::{Value as J, json};
@@ -12,6 +12,8 @@ pub fn session(s: &Session, graph: Option<usize>) -> J {
json!({
"index": gi,
"name": g.name,
"kind": g.kind(),
"function": g.function,
"size": g.size_px(),
"format": g.format,
"seed": g.seed,
@@ -21,7 +23,7 @@ pub fn session(s: &Session, graph: Option<usize>) -> J {
"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);
let (ins, outs) = materialcraft_eval::ports(&s.pkg, g, n);
json!({
"id": n.id.0,
"def": n.def,
@@ -30,15 +32,17 @@ pub fn session(s: &Session, graph: Option<usize>) -> J {
"params": n.params,
"bindings": n.bindings,
"functions": n.functions,
"inputValues": n.input_values,
"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()),
"value": r.outputs.first().and_then(materialcraft_eval::NodeOutput::as_value),
"size": r.outputs.first().and_then(materialcraft_eval::NodeOutput::as_image).map(|i| [i.w, i.h]),
"kind": r.outputs.first().and_then(materialcraft_eval::NodeOutput::as_image).map(|i| if i.is_gray() { "gray" } else { "color" }),
"mean": r.outputs.first().and_then(materialcraft_eval::NodeOutput::as_image).map(|i| i.mean()),
})),
})
}).collect::<Vec<_>>(),
@@ -50,9 +54,10 @@ pub fn session(s: &Session, graph: Option<usize>) -> J {
});
json!({
"package": {"name": s.pkg.name, "path": s.path, "modified": s.modified, "warnings": s.load_warnings, "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<_>>(),
"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,
"annotationSelection": s.annotation_selection,
"selection": s.selection.iter().map(|i| i.0).collect::<Vec<_>>(),
"view2d": s.view2d,
"view3d": s.view3d,
+32 -33
View File
@@ -1,9 +1,3 @@
//! # 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)]
@@ -11,16 +5,21 @@ pub mod commands;
pub mod edit_cmds;
pub mod file_cmds;
pub mod graph_cmds;
pub mod graph_grid;
pub mod inspect;
pub mod material_cmds;
pub mod node_cmds;
pub mod samples;
pub mod session;
mod value_input_commands;
pub mod view_cmds;
pub mod wire_cmds;
pub use commands::{CommandSpec, command_specs, execute, find};
pub use session::{CameraPrefs, Clip, Session, View2d, View3d, WARNING_PREFIX};
pub use session::{CameraPrefs, Session, View2d, View3d, WARNING_PREFIX};
mod clip;
mod connection_commands;
pub use clip::Clip;
pub use materialcraft_core as core;
pub use materialcraft_eval as eval;
@@ -28,35 +27,35 @@ 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),
}
mod engine_error;
pub use engine_error::EngineError;
pub type Result<T> = std::result::Result<T, EngineError>;
/// Version string shown in About, `--version` and window titles.
/// Version string shown in About, `--version` and window titles
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
/// A fresh, unsaved package with one empty graph, used at desktop and browser startup.
pub fn new_session() -> Session {
let mut pkg = core::Package::new("Untitled package");
pkg.graphs.push(samples::template("empty", "New_graph", 10));
Session::new(pkg)
}
mod startup;
pub use startup::{new_session, sample_session};
/// A session on the built-in sample package (the brick wall).
pub fn sample_session() -> Session {
Session::new(samples::sample_package())
}
mod atomic_sample;
mod atomic_sample_commands;
pub use atomic_sample::atomic_sample;
mod material_options;
pub use material_options::MaterialOptions;
mod exported;
pub use exported::Exported;
mod annotation_commands;
mod annotation_selection;
mod comment_commands;
mod frame_commands;
mod frame_contents;
mod function_commands;
mod node_graph_commands;
mod pattern_graph_commands;
mod snapshot;
pub use annotation_selection::AnnotationSelection;
pub use frame_contents::FrameContents;
+28 -26
View File
@@ -1,19 +1,23 @@
//! Cross-app materials: portable `.mcmat` export (cooked maps, the exposed inputs other apps may
//! change, the source package), "Send to TextureCraft", and preview images for the graph's input
//! nodes (mesh maps baked in TextureCraft). See `docs/control-protocol.md` § Portable materials.
#[cfg(any(test, not(target_arch = "wasm32")))]
use std::collections::BTreeMap;
use serde_json::{Value as J, json};
use materialcraft_core::{Graph, Value};
use materialcraft_formats::material::{FORMAT, ImageInput, MATERIAL_EXT, Manifest, MapEntry, Parameter, PresetEntry, VERSION, portable, srgb_usage};
use materialcraft_core::Graph;
#[cfg(any(test, not(target_arch = "wasm32")))]
use materialcraft_core::Value;
use materialcraft_formats::material::{FORMAT, ImageInput, Manifest, MapEntry, Parameter, PresetEntry, VERSION, portable, srgb_usage};
use materialcraft_formats::{Depth, encode};
#[cfg(test)]
use materialcraft_image::Image;
use materialcraft_nodes::atomic::USAGE_IDS;
use crate::commands::{CommandSpec, bad, has_graph, strp, u64p};
#[cfg(not(target_arch = "wasm32"))]
use crate::commands::u64p;
use crate::commands::{CommandSpec, bad, has_graph, strp};
use crate::{Result, Session, cmd};
#[cfg(not(target_arch = "wasm32"))]
use materialcraft_formats::material::MATERIAL_EXT;
pub(crate) fn specs() -> Vec<CommandSpec> {
vec![
@@ -48,18 +52,9 @@ pub(crate) fn specs() -> Vec<CommandSpec> {
]
}
/// What to cook a portable material with, over the graph's own values.
#[derive(Clone, Debug, Default)]
pub struct MaterialOptions {
/// Square size in pixels (rounded to a power of two, 16..8192); `None` = the graph's size.
pub size: Option<u32>,
/// Exposed input values (they also become the embedded package's values).
pub values: BTreeMap<String, Value>,
/// Images for the graph's input nodes, by identifier (mesh maps).
pub inputs: BTreeMap<String, Image>,
}
pub use crate::MaterialOptions;
/// Cook graph `gi` with `o` and pack it as a portable material (`.mcmat` bytes).
/// Cook graph `gi` with `o` and pack it as a portable material (`.mcmat` bytes)
pub fn material_bytes(s: &Session, gi: usize, o: &MaterialOptions) -> Result<Vec<u8>> {
let mut pkg = s.pkg.clone();
let g = pkg.graph_mut(gi)?;
@@ -107,11 +102,12 @@ pub fn material_bytes(s: &Session, gi: usize, o: &MaterialOptions) -> Result<Vec
presets: g.presets.iter().map(|p| PresetEntry { name: p.name.clone(), values: p.values.clone() }).collect(),
source: String::new(),
};
let source = materialcraft_formats::save_package(&pkg)?;
let source = materialcraft_formats::sbs::write_sbs(&pkg)?;
Ok(materialcraft_formats::material::write_material(&manifest, &maps, &source)?)
}
/// The graph's input nodes (one entry per identifier).
/// The graph's input nodes (one entry per identifier)
pub fn image_inputs(g: &Graph) -> Vec<ImageInput> {
let mut out: Vec<ImageInput> = Vec::new();
for n in g.nodes.iter().filter(|n| matches!(n.def.as_str(), "input_grayscale" | "input_color")) {
@@ -123,7 +119,8 @@ pub fn image_inputs(g: &Graph) -> Vec<ImageInput> {
out
}
/// `values` as typed exposed input values of graph `g`.
/// `values` as typed exposed input values of graph `g`
#[cfg(any(test, not(target_arch = "wasm32")))]
fn values_param(cmd: &str, g: &Graph, p: &J) -> Result<BTreeMap<String, Value>> {
let Some(obj) = p.get("values").and_then(J::as_object) else { return Ok(BTreeMap::new()) };
obj.iter()
@@ -135,6 +132,7 @@ fn values_param(cmd: &str, g: &Graph, p: &J) -> Result<BTreeMap<String, Value>>
.collect()
}
#[cfg(not(target_arch = "wasm32"))]
fn graph_param(s: &Session, p: &J) -> Result<usize> {
let gi = u64p(p, "graph").map_or(s.graph, |g| g as usize);
s.pkg.graph(gi)?;
@@ -164,7 +162,7 @@ fn export_material(_: &mut Session, _: &J) -> Result<J> {
Err(bad("file.exportMaterial", "the browser exports with a download"))
}
/// TextureCraft's library folder: `Documents/TextureCraft/library` in the home folder.
/// TextureCraft's library folder: `Documents/TextureCraft/library` in the home folder
#[cfg(not(target_arch = "wasm32"))]
pub fn texturecraft_library() -> std::path::PathBuf {
let home = std::env::var("USERPROFILE").or_else(|_| std::env::var("HOME")).unwrap_or_else(|_| ".".into());
@@ -207,11 +205,13 @@ fn bind(s: &mut Session, p: &J) -> Result<J> {
(None, Some(path)) => Some(read_image_file(CMD, path)?),
(None, None) => return Err(bad(CMD, "give a `resource` or a `path`")),
};
s.edit("Set input preview image", |s| {
let res = match file {
Some((name, bytes)) => crate::file_cmds::push_resource(&mut s.pkg, &name, bytes, Some(&id)),
None => strp(p, "resource").unwrap_or_default().to_string(),
};
s.graph_mut()?.input_images.insert(id.clone(), res.clone());
Ok(json!({"identifier": id, "resource": res}))
})
@@ -249,13 +249,15 @@ mod tests {
let bytes = material_bytes(&s, s.graph, &MaterialOptions { size: Some(32), values, ..Default::default() }).unwrap();
let (m, source) = read_material(&bytes).unwrap();
assert_eq!(m.size, [32, 32]);
assert!(m.maps.iter().any(|e| e.usage == "baseColor" && e.color_space == "srgb"));
assert!(m.maps.iter().any(|e| e.usage == "normal" && e.color_space == "linear"));
assert!(m.maps.iter().any(|entry| entry.usage == "height" && entry.color_space == "linear"));
let ids: Vec<&str> = m.parameters.iter().map(|p| p.param.id.as_str()).collect();
assert_eq!(ids, ["wear"], "text inputs are not portable");
assert_eq!(m.parameters[0].value, Value::Float(0.9), "the manifest carries the cooked value");
assert_eq!(materialcraft_formats::load_package(&source).unwrap().graphs[s.graph].inputs.get("wear"), Some(&Value::Float(0.9)));
// The source package opens again, on the material's graph, with no file to save over.
assert_eq!(
materialcraft_formats::sbs::read_sbs(&source, "source.sbs", &|_| None).unwrap().pkg.graphs[s.graph].input_value("wear"),
Some(&Value::Float(0.9))
);
// The source package opens again, on the material's graph, with no file to save over
crate::file_cmds::open_bytes(&mut s, &bytes, Some("x.mcmat".into())).unwrap();
assert_eq!(s.graph().unwrap().name, m.graph);
assert!(s.path.is_none());
+14
View File
@@ -0,0 +1,14 @@
use materialcraft_core::Value;
use materialcraft_image::Image;
use std::collections::BTreeMap;
/// What to cook a portable material with, over the graph's own values
#[derive(Clone, Debug, Default)]
pub struct MaterialOptions {
/// Square size in pixels (rounded to a power of two, 16..8192); `None` = the graph's size
pub size: Option<u32>,
/// Exposed input values (they also become the embedded package's values)
pub values: BTreeMap<String, Value>,
/// Images for the graph's input nodes, by identifier (mesh maps)
pub inputs: BTreeMap<String, Image>,
}
+58 -65
View File
@@ -1,10 +1,13 @@
//! Node commands: add, move, rename, disable, parameters, base parameters, bindings, wires.
//! 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 materialcraft_core::{FunctionGraph, NodeId, OutputFormat, SizeMode, Value, ValueType};
use crate::commands::{CommandSpec, bad, boolp, has_graph, has_selection, i64p, ids_param, node_param, point, strp, u64p};
use crate::connection_commands::connection_input;
use crate::graph_grid::snap_position;
use crate::commands::{CommandSpec, bad, boolp, has_graph, has_selection, i64p, ids_param, node_param, point, strp};
use crate::{Result, Session, cmd};
pub(crate) fn specs() -> Vec<CommandSpec> {
@@ -14,11 +17,11 @@ pub(crate) fn specs() -> Vec<CommandSpec> {
"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?}",
"{def (see library.list), at? [x, y], snapToGrid? bool, 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.move", "Move nodes", [], None, "{ids?, by? [dx, dy], to? [x, y], snapToGrid? bool}", 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!(
@@ -50,27 +53,36 @@ pub(crate) fn specs() -> Vec<CommandSpec> {
has_selection,
set_function
),
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> {
if s.graph()?.function.is_some() {
return Err(bad("graph.node.add", "use function operations in a Function Graph"));
}
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.
// 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 if def == "input_value" && k == "default" {
serde_json::from_value::<Value>(v.clone())
.ok()
.or_else(|| Value::Float(0.0).coerce_json(v))
.filter(|value| materialcraft_core::ValueType::of(value).is_some())
.ok_or_else(|| bad("graph.node.add", "default must be a scalar or vector value"))?
} 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));
}
}
@@ -80,15 +92,28 @@ fn add(s: &mut Session, p: &J) -> Result<J> {
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 at = snap_position(at, boolp(p, "snapToGrid").unwrap_or(false));
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;
if let Some(parameter) = catalog.and_then(|definition| definition.param("pattern")) {
n.params.insert("pattern".into(), parameter.default.clone());
}
if def == "value_processor" {
n.input_values.insert("value1".into(), ValueType::Float);
let mut function = FunctionGraph::default();
function.output = Some(function.add("get_float1", &[], Some(Value::Text("value1".into()))));
n.params.insert("function".into(), Value::Function(Box::new(function)));
}
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")))?;
let first = connection_input(s, src, &port, id)?;
s.graph_mut()?.connect(src, &port, id, &first)?;
}
s.selection = vec![id];
@@ -103,13 +128,15 @@ fn move_nodes(s: &mut Session, p: &J) -> Result<J> {
if by.is_none() && to.is_none() {
return Err(bad("graph.node.move", "`by` or `to` is required"));
}
let snap = boolp(p, "snapToGrid").unwrap_or(false);
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;
n.pos = snap_position(t, snap);
} else if let Some(d) = by {
n.pos = [n.pos[0] + d[0], n.pos[1] + d[1]];
n.pos = snap_position([n.pos[0] + d[0], n.pos[1] + d[1]], snap);
}
}
Ok(J::Null)
@@ -142,8 +169,15 @@ fn set_param(s: &mut Session, p: &J) -> Result<J> {
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`).
let value = if node.def == "input_value" && param == "default" {
let current = node.params.get("default").cloned().unwrap_or(Value::Float(0.0));
serde_json::from_value::<Value>(v.clone())
.ok()
.or_else(|| current.coerce_json(v))
.filter(|value| materialcraft_core::ValueType::of(value).is_some())
.ok_or_else(|| bad("graph.node.param", "default must be a scalar or vector value"))?
} else 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 {
@@ -163,6 +197,11 @@ fn set_param(s: &mut Session, p: &J) -> Result<J> {
}
v
};
if let Value::PatternGraph(graph) = &value {
graph.validate().map_err(|error| bad("graph.node.param", error))?;
}
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)
@@ -193,6 +232,7 @@ fn base(s: &mut Session, p: &J) -> Result<J> {
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),
@@ -202,6 +242,7 @@ fn base(s: &mut Session, p: &J) -> Result<J> {
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)
@@ -244,6 +285,7 @@ fn bind(s: &mut Session, p: &J) -> Result<J> {
Some(i) => n.bindings.insert(param, i),
None => n.bindings.remove(&param),
};
Ok(J::Null)
})
}
@@ -265,13 +307,14 @@ fn set_function(s: &mut Session, p: &J) -> Result<J> {
}
let f = match p.get("function") {
Some(f) if !f.is_null() => {
serde_json::from_value::<materialcraft_core::function::FnGraph>(f.clone()).map_err(|e| bad("graph.node.function", format!("bad function: {e}")))?
serde_json::from_value::<materialcraft_core::FunctionGraph>(f.clone()).map_err(|e| bad("graph.node.function", format!("bad function: {e}")))?
}
_ => match node.functions.get(&param) {
Some(f) => f.clone(),
None => materialcraft_core::function::FnGraph::constant(node.params.get(&param).cloned().unwrap_or_else(|| pd.default.clone())),
None => materialcraft_core::FunctionGraph::constant(node.params.get(&param).cloned().unwrap_or_else(|| pd.default.clone())),
},
};
if f.nodes.len() > 4096 {
return Err(bad("graph.node.function", "the function is too large"));
}
@@ -280,53 +323,3 @@ fn set_function(s: &mut Session, p: &J) -> Result<J> {
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()
}
}
+41
View File
@@ -0,0 +1,41 @@
use materialcraft_core::NodeId;
use serde_json::{Value, json};
use crate::commands::{CommandSpec, bad};
use crate::{Result, Session, cmd};
pub(crate) fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"graph.node.edit",
"Edit node graph",
["Edit"],
Some("Ctrl+E"),
"{} resolves the selected FX-Map graph to {node, parameter}; UI invocation opens its editor",
enabled,
edit
)]
}
fn selected_node(session: &Session) -> std::result::Result<NodeId, String> {
if session.annotation_selection.is_some() {
return Err("select an FX-Map node".into());
}
let id = session.selection.last().copied().ok_or("select an FX-Map node")?;
let graph = session.graph().map_err(|error| error.to_string())?;
let node = graph.node(id).map_err(|error| error.to_string())?;
if node.def != "fx_map" {
return Err("the selected node has no editable FX-Map graph".into());
}
Ok(id)
}
fn enabled(session: &Session) -> std::result::Result<(), String> {
selected_node(session).map(|_| ())
}
fn edit(session: &mut Session, _: &Value) -> Result<Value> {
let node = selected_node(session).map_err(|error| bad("graph.node.edit", error))?;
Ok(json!({"node": node.0, "parameter": "pattern"}))
}
@@ -0,0 +1,28 @@
use materialcraft_core::{NodeId, PatternGraph, Value};
use serde_json::{Value as Json, json};
use crate::commands::{CommandSpec, bad, has_graph};
use crate::{Result, Session, cmd};
pub(crate) fn specs() -> Vec<CommandSpec> {
vec![cmd!("graph.pattern.set", "Edit FX-Map graph", [], None, "{id, pattern} replaces an FX-Map subgraph", has_graph, set)]
}
fn set(session: &mut Session, parameters: &Json) -> Result<Json> {
let id = NodeId(parameters.get("id").and_then(Json::as_u64).ok_or_else(|| bad("graph.pattern.set", "id is required"))?);
if session.graph()?.node(id)?.def != "fx_map" {
return Err(bad("graph.pattern.set", "the node is not an FX-Map"));
}
let graph: PatternGraph =
serde_json::from_value(parameters.get("pattern").cloned().unwrap_or(Json::Null)).map_err(|error| bad("graph.pattern.set", error.to_string()))?;
graph.validate().map_err(|error| bad("graph.pattern.set", error))?;
if graph.nodes.iter().any(|node| node.position.iter().any(|coordinate| !coordinate.is_finite())) {
return Err(bad("graph.pattern.set", "node positions must be finite"));
}
session.edit("Edit FX-Map graph", |session| {
session.graph_mut()?.node_mut(id)?.params.insert("pattern".into(), Value::PatternGraph(Box::new(graph)));
Ok(json!({}))
})
}
+33 -574
View File
@@ -1,580 +1,39 @@
//! Built-in sample materials and graph templates, built in code from the node library (no
//! third-party content).
use crate::{EngineError, Result};
use materialcraft_core::{Graph, Value};
use materialcraft_core::{Graph, NodeId, Package, Value};
pub const TEMPLATES: &[(&str, &str)] = &[("empty", "Empty"), ("pbr", "Material outputs"), ("atomics", "Atomic sample")];
/// 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"),
("metal_plates", "Painted metal plates"),
("rusty_metal", "Rusty metal"),
("lava", "Lava rock"),
("marble", "Polished marble"),
("wicker", "Wicker weave"),
("fabric", "Woven fabric"),
("ground", "Mossy ground"),
];
pub fn template(id: &str, name: &str, size_log2: u32) -> Result<Graph> {
let mut graph = match id {
"empty" | "pbr" => Graph::new(name),
"atomics" => crate::atomic_sample()?.graphs.into_iter().next().ok_or_else(|| EngineError::Other("atomic sample has no graph".into()))?,
_ => return Err(EngineError::Other(format!("unknown template `{id}`"))),
};
struct B<'g> {
g: &'g mut Graph,
}
impl B<'_> {
fn n(&mut self, def: &str, x: f32, y: f32, params: &[(&str, Value)]) -> NodeId {
// Node cards are about 100 × 135 with thumbnails: spread the layout to fit them.
let id = self.g.add_node(def, [x * 1.1, y * 1.3]);
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 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 * 125.0, &[("usage", Value::Enum(*usage)), ("identifier", Value::Text((*ident).into()))]);
self.cp(*from, port, o, "input");
graph.name = name.to_string();
graph.size = [size_log2, size_log2];
if id == "pbr" {
for (index, (identifier, color)) in [
("basecolor", [0.5, 0.5, 0.5, 1.0]),
("normal", [0.5, 0.5, 1.0, 1.0]),
("roughness", [0.5, 0.5, 0.5, 1.0]),
("metallic", [0.0, 0.0, 0.0, 1.0]),
("height", [0.0, 0.0, 0.0, 1.0]),
("ambientocclusion", [1.0; 4]),
]
.into_iter()
.enumerate()
{
let source = graph.add_node("uniform", [0.0, index as f32 * 180.0]);
let node = graph.node_mut(source)?;
node.params.insert("color_mode".into(), Value::Bool(index <= 1));
node.params.insert("color".into(), Value::Color(color));
let output = graph.add_node("output", [220.0, index as f32 * 180.0]);
let node = graph.node_mut(output)?;
node.params.insert("identifier".into(), Value::Text(identifier.into()));
node.params.insert("usage".into(), Value::Enum(index as u32));
graph.connect(source, "output", output, "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),
"metal_plates" => metal_plates(&mut b),
"rusty_metal" => rusty_metal(&mut b),
"lava" => lava(&mut b),
"marble" => marble(&mut b),
"wicker" => wicker(&mut b),
"fabric" => fabric(&mut b),
"ground" => ground(&mut b),
_ => {}
}
g
}
fn bricks(b: &mut B) {
let layout = b.n("brick_generator", 0.0, 0.0, &[("bricks_x", i(4)), ("bricks_y", i(12)), ("gap", f(0.05)), ("bevel", f(0.3)), ("height_random", f(0.12))]);
let ids = b.n(
"brick_generator",
0.0,
160.0,
&[("bricks_x", i(4)), ("bricks_y", i(12)), ("gap", f(0.05)), ("bevel", f(0.0)), ("height_random", f(0.0)), ("lum_random", f(1.0))],
);
let pores = b.n("clouds_2", 0.0, 320.0, &[("scale", f(16.0))]);
let grunge = b.n("grunge_map_1", 0.0, 480.0, &[("scale", f(4.0))]);
let dirt = b.n("clouds_2", 0.0, 640.0, &[("scale", f(24.0))]);
let chipped = b.n("edge_damage", 180.0, 0.0, &[("width", f(6.0)), ("amount", f(0.6)), ("scale", f(14.0))]);
b.c(layout, chipped, "height");
let porous = b.n("blend", 360.0, 0.0, &[("mode", e(3)), ("opacity", f(0.3))]);
b.c(pores, porous, "foreground");
b.c(chipped, porous, "background");
let mortar_h = b.n("levels", 360.0, 160.0, &[("out_low", f(0.08)), ("out_high", f(0.16))]);
b.c(dirt, mortar_h, "input");
let height = b.n("blend", 540.0, 80.0, &[("mode", e(5))]);
b.c(mortar_h, height, "foreground");
b.c(porous, height, "background");
let normal = b.n("normal", 720.0, 0.0, &[("intensity", f(2.5))]);
b.c(height, normal, "input");
let ao = b.n("ambient_occlusion", 720.0, 120.0, &[("spread", f(0.05)), ("intensity", f(0.7))]);
b.c(height, ao, "height");
let tone = b.n("blend", 360.0, 320.0, &[("mode", e(9)), ("opacity", f(0.6))]);
b.c(grunge, tone, "foreground");
b.c(ids, tone, "background");
let brick_col = b.n(
"gradient_map",
540.0,
320.0,
&[("gradient", grad(&[(0.0, [0.09, 0.022, 0.012]), (0.5, [0.2, 0.05, 0.022]), (0.85, [0.3, 0.09, 0.04]), (1.0, [0.36, 0.15, 0.08])]))],
);
b.c(tone, brick_col, "input");
let mortar_col = b.n("gradient_map", 540.0, 480.0, &[("gradient", grad(&[(0.0, [0.2, 0.19, 0.17]), (1.0, [0.3, 0.28, 0.25])]))]);
b.c(dirt, mortar_col, "input");
let mask = b.n("histogram_scan", 540.0, 640.0, &[("position", f(0.9)), ("contrast", f(0.9))]);
b.c(chipped, mask, "input");
let base = b.n("blend", 720.0, 400.0, &[]);
b.c(brick_col, base, "foreground");
b.c(mortar_col, base, "background");
b.c(mask, base, "mask");
let rough = b.n("levels", 720.0, 560.0, &[("out_low", f(0.7)), ("out_high", f(0.95))]);
b.c(grunge, rough, "input");
let metal = b.n("uniform", 720.0, 680.0, &[("mode", e(1)), ("color", col(0.0, 0.0, 0.0))]);
b.outputs(
940.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 lava(b: &mut B) {
let cells = b.n("voronoi", 0.0, 0.0, &[("scale", f(6.0)), ("style", e(2))]);
let rock = b.n("clouds_2", 0.0, 160.0, &[("scale", f(12.0)), ("roughness", f(0.6))]);
let fine = b.n("cracks", 0.0, 320.0, &[("scale", f(9.0)), ("width", f(1.0))]);
let plates = b.n("levels", 180.0, 0.0, &[("in_low", f(0.02)), ("in_high", f(0.3))]);
b.c(cells, plates, "input");
let rough_h = b.n("blend", 360.0, 0.0, &[("mode", e(3)), ("opacity", f(0.4))]);
b.c(rock, rough_h, "foreground");
b.c(plates, rough_h, "background");
let height = b.n("blend", 540.0, 0.0, &[("mode", e(2)), ("opacity", f(0.25))]);
b.c(fine, height, "foreground");
b.c(rough_h, height, "background");
let normal = b.n("normal", 720.0, 0.0, &[("intensity", f(3.0))]);
b.c(height, normal, "input");
let ao = b.n("ambient_occlusion", 720.0, 120.0, &[("spread", f(0.06)), ("intensity", f(0.8))]);
b.c(height, ao, "height");
let seams = b.n("invert", 180.0, 160.0, &[]);
b.c(plates, seams, "input");
let seam_mask = b.n("levels", 360.0, 160.0, &[("in_low", f(0.6)), ("in_high", f(1.0))]);
b.c(seams, seam_mask, "input");
let glow = b.n("blur", 540.0, 160.0, &[("intensity", f(0.6))]);
b.c(seam_mask, glow, "input");
let emissive = b.n(
"gradient_map",
720.0,
240.0,
&[("gradient", grad(&[(0.0, [0.0, 0.0, 0.0]), (0.35, [0.35, 0.02, 0.0]), (0.7, [1.0, 0.28, 0.02]), (1.0, [1.0, 0.75, 0.3])]))],
);
b.c(glow, emissive, "input");
let base =
b.n("gradient_map", 720.0, 360.0, &[("gradient", grad(&[(0.0, [0.006, 0.005, 0.005]), (0.6, [0.018, 0.016, 0.016]), (1.0, [0.04, 0.036, 0.034])]))]);
b.c(height, base, "input");
let rough = b.n("levels", 720.0, 480.0, &[("out_low", f(0.72)), ("out_high", f(0.95))]);
b.c(rock, rough, "input");
let metal = b.n("uniform", 720.0, 600.0, &[("mode", e(1)), ("color", col(0.0, 0.0, 0.0))]);
b.outputs(
940.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"),
(emissive, "output", 6, "emissive"),
],
);
}
fn metal_plates(b: &mut B) {
let plates = b.n("tile_generator", 0.0, 0.0, &[("pattern", e(0)), ("x_amount", i(3)), ("y_amount", i(3)), ("scale", f(0.985))]);
let inner = b.n("tile_generator", 0.0, 160.0, &[("pattern", e(0)), ("x_amount", i(3)), ("y_amount", i(3)), ("scale", f(0.88))]);
let rivets = b.n("tile_generator", 0.0, 320.0, &[("pattern", e(2)), ("x_amount", i(27)), ("y_amount", i(27)), ("scale", f(0.42))]);
let grunge = b.n("grunge_map_1", 0.0, 480.0, &[("scale", f(3.0)), ("contrast", f(0.45))]);
let bevelled = b.n("bevel", 180.0, 0.0, &[("distance", f(0.02)), ("smoothing", f(0.5))]);
b.c(plates, bevelled, "input");
let band = b.n("blend", 180.0, 160.0, &[("mode", e(2))]);
b.c(inner, band, "foreground");
b.c(plates, band, "background");
let rivet_band = b.n("blend", 360.0, 240.0, &[("mode", e(3))]);
b.c(rivets, rivet_band, "foreground");
b.c(band, rivet_band, "background");
let plate_h = b.n("levels", 360.0, 0.0, &[("out_high", f(0.6))]);
b.c(bevelled, plate_h, "input");
let height = b.n("blend", 540.0, 0.0, &[("mode", e(1)), ("opacity", f(0.4))]);
b.c(rivet_band, height, "foreground");
b.c(plate_h, height, "background");
let normal = b.n("normal", 720.0, 0.0, &[("intensity", f(2.5))]);
b.c(height, normal, "input");
let ao = b.n("ambient_occlusion", 720.0, 120.0, &[("spread", f(0.04)), ("intensity", f(0.7))]);
b.c(height, ao, "height");
let worn = b.n("edge_damage", 540.0, 160.0, &[("width", f(5.0)), ("amount", f(0.5)), ("scale", f(16.0))]);
b.c(height, worn, "height");
let scratches = b.n("scratches_generator", 360.0, 400.0, &[("count", i(70)), ("length", f(0.05)), ("width", f(0.4))]);
let scratch_mask = b.n("levels", 540.0, 400.0, &[("in_low", f(0.5)), ("in_high", f(0.9)), ("out_high", f(0.5))]);
b.c(scratches, scratch_mask, "input");
let wear = b.n("blend", 720.0, 280.0, &[("mode", e(5))]);
b.c(scratch_mask, wear, "foreground");
b.cp(worn, "mask", wear, "background");
let paint = b.n("gradient_map", 540.0, 520.0, &[("gradient", grad(&[(0.0, [0.012, 0.035, 0.08]), (1.0, [0.035, 0.085, 0.17])]))]);
b.c(grunge, paint, "input");
let steel = b.n("uniform", 540.0, 640.0, &[("color", col(0.56, 0.56, 0.57))]);
let base = b.n("blend", 720.0, 480.0, &[]);
b.c(steel, base, "foreground");
b.c(paint, base, "background");
b.c(wear, base, "mask");
let rough_paint = b.n("uniform", 540.0, 760.0, &[("mode", e(1)), ("color", col(0.5, 0.5, 0.5))]);
let rough_steel = b.n("uniform", 540.0, 880.0, &[("mode", e(1)), ("color", col(0.25, 0.25, 0.25))]);
let rough = b.n("blend", 720.0, 640.0, &[]);
b.c(rough_steel, rough, "foreground");
b.c(rough_paint, rough, "background");
b.c(wear, rough, "mask");
b.outputs(
940.0,
&[
(base, "output", 0, "basecolor"),
(normal, "output", 1, "normal"),
(rough, "output", 2, "roughness"),
(wear, "output", 3, "metallic"),
(height, "output", 4, "height"),
(ao, "output", 5, "ambientocclusion"),
],
);
}
fn wood(b: &mut B) {
let planks = b.n(
"brick_generator",
0.0,
0.0,
&[("bricks_x", i(2)), ("bricks_y", i(7)), ("offset", f(0.37)), ("gap", f(0.012)), ("bevel", f(0.05)), ("height_random", f(0.06))],
);
let ids = b.n(
"brick_generator",
0.0,
160.0,
&[("bricks_x", i(2)), ("bricks_y", i(7)), ("offset", f(0.37)), ("gap", f(0.012)), ("bevel", f(0.0)), ("height_random", f(0.0)), ("lum_random", f(1.0))],
);
let grain = b.n("anisotropic_noise", 0.0, 320.0, &[("scale", f(3.0)), ("scale_y", f(110.0)), ("smoothness", f(0.25))]);
let warp_src = b.n("perlin_noise", 0.0, 480.0, &[("scale", f(5.0))]);
let warped = b.n("directional_warp", 180.0, 320.0, &[("intensity", f(5.0)), ("angle", f(0.25))]);
b.c(grain, warped, "input");
b.c(warp_src, warped, "intensity_input");
let height = b.n("blend", 360.0, 80.0, &[("mode", e(3)), ("opacity", f(0.18))]);
b.c(warped, height, "foreground");
b.c(planks, height, "background");
let normal = b.n("normal", 540.0, 0.0, &[("intensity", f(1.6))]);
b.c(height, normal, "input");
let ao = b.n("ambient_occlusion", 540.0, 120.0, &[("spread", f(0.03)), ("intensity", f(0.6))]);
b.c(height, ao, "height");
let tone = b.n("blend", 360.0, 240.0, &[("mode", e(9)), ("opacity", f(0.55))]);
b.c(ids, tone, "foreground");
b.c(warped, tone, "background");
let wood_col = b.n(
"gradient_map",
540.0,
240.0,
&[("gradient", grad(&[(0.0, [0.045, 0.018, 0.007]), (0.4, [0.15, 0.065, 0.024]), (0.75, [0.3, 0.15, 0.06]), (1.0, [0.42, 0.24, 0.11])]))],
);
b.c(tone, wood_col, "input");
let gaps = b.n("histogram_scan", 540.0, 400.0, &[("position", f(0.97)), ("contrast", f(0.95))]);
b.c(planks, gaps, "input");
let base = b.n("blend", 720.0, 300.0, &[("mode", e(3))]);
b.c(gaps, base, "foreground");
b.c(wood_col, base, "background");
let rough = b.n("levels", 720.0, 440.0, &[("out_low", f(0.32)), ("out_high", f(0.55))]);
b.c(warped, rough, "input");
let metal = b.n("uniform", 720.0, 560.0, &[("mode", e(1)), ("color", col(0.0, 0.0, 0.0))]);
b.outputs(
940.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 wicker(b: &mut B) {
let weave = b.n("weave", 0.0, 0.0, &[("tiling", i(7)), ("width", f(0.92))]);
let fibers = b.n("anisotropic_noise", 0.0, 160.0, &[("scale", f(2.0)), ("scale_y", f(160.0)), ("smoothness", f(0.2))]);
let tint = b.n("clouds_2", 0.0, 320.0, &[("scale", f(10.0))]);
let height = b.n("blend", 180.0, 0.0, &[("mode", e(3)), ("opacity", f(0.12))]);
b.c(fibers, height, "foreground");
b.c(weave, height, "background");
let normal = b.n("normal", 360.0, 0.0, &[("intensity", f(2.2))]);
b.c(height, normal, "input");
let ao = b.n("ambient_occlusion", 360.0, 120.0, &[("spread", f(0.03)), ("intensity", f(0.9))]);
b.c(height, ao, "height");
let tone = b.n("blend", 180.0, 240.0, &[("mode", e(9)), ("opacity", f(0.35))]);
b.c(tint, tone, "foreground");
b.c(height, tone, "background");
let base = b.n(
"gradient_map",
360.0,
240.0,
&[("gradient", grad(&[(0.0, [0.015, 0.008, 0.003]), (0.45, [0.14, 0.075, 0.025]), (0.8, [0.34, 0.21, 0.08]), (1.0, [0.46, 0.32, 0.14])]))],
);
b.c(tone, base, "input");
let rough = b.n("levels", 360.0, 400.0, &[("out_low", f(0.6)), ("out_high", f(0.8))]);
b.c(fibers, rough, "input");
let metal = b.n("uniform", 360.0, 520.0, &[("mode", e(1)), ("color", col(0.0, 0.0, 0.0))]);
b.outputs(
600.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 ground(b: &mut B) {
let stones = b.n("stones", 0.0, 0.0, &[("scale", f(6.0)), ("gap", f(0.1)), ("bevel", f(0.45)), ("height_random", f(0.35)), ("detail", f(0.25))]);
let dirt = b.n("dirt", 0.0, 160.0, &[("scale", f(6.0))]);
let clouds = b.n("clouds_2", 0.0, 320.0, &[("scale", f(10.0))]);
let hb = b.n("height_blend", 180.0, 80.0, &[("offset", f(0.22)), ("contrast", f(0.85))]);
b.c(stones, hb, "top");
b.c(dirt, hb, "bottom");
let moss = b.n("moss", 360.0, 240.0, &[("amount", f(0.4)), ("scale", f(8.0)), ("height_bias", f(0.35))]);
b.cp(hb, "height", moss, "height");
let normal = b.n("normal", 360.0, 0.0, &[("intensity", f(2.0))]);
b.cp(hb, "height", normal, "input");
let ao = b.n("ambient_occlusion", 360.0, 120.0, &[("spread", f(0.07)), ("intensity", f(0.7))]);
b.cp(hb, "height", ao, "height");
let stone_h = b.n("blend", 180.0, 320.0, &[("mode", e(9)), ("opacity", f(0.6))]);
b.c(clouds, stone_h, "foreground");
b.c(stones, stone_h, "background");
let stone_col =
b.n("gradient_map", 360.0, 360.0, &[("gradient", grad(&[(0.0, [0.03, 0.03, 0.032]), (0.55, [0.11, 0.105, 0.1]), (1.0, [0.24, 0.22, 0.2])]))]);
b.c(stone_h, stone_col, "input");
let dirt_col = b.n("gradient_map", 360.0, 480.0, &[("gradient", grad(&[(0.0, [0.02, 0.013, 0.008]), (1.0, [0.1, 0.065, 0.04])]))]);
b.c(dirt, dirt_col, "input");
let moss_col = b.n("gradient_map", 360.0, 600.0, &[("gradient", grad(&[(0.0, [0.02, 0.04, 0.008]), (1.0, [0.07, 0.14, 0.02])]))]);
b.c(clouds, moss_col, "input");
let ground_col = b.n("blend", 540.0, 360.0, &[]);
b.c(dirt_col, ground_col, "foreground");
b.c(stone_col, ground_col, "background");
b.cp(hb, "blend_mask", ground_col, "mask");
let base = b.n("blend", 720.0, 360.0, &[]);
b.c(moss_col, base, "foreground");
b.c(ground_col, base, "background");
b.c(moss, base, "mask");
let rough = b.n("levels", 720.0, 480.0, &[("out_low", f(0.7)), ("out_high", f(0.95))]);
b.c(clouds, rough, "input");
let metal = b.n("uniform", 720.0, 600.0, &[("mode", e(1)), ("color", col(0.0, 0.0, 0.0))]);
b.outputs(
940.0,
&[
(base, "output", 0, "basecolor"),
(normal, "output", 1, "normal"),
(rough, "output", 2, "roughness"),
(metal, "output", 3, "metallic"),
(hb, "height", 4, "height"),
(ao, "output", 5, "ambientocclusion"),
],
);
}
fn stone_tiles(b: &mut B) {
let layout = b.n(
"brick_generator",
0.0,
0.0,
&[("bricks_x", i(3)), ("bricks_y", i(3)), ("offset", f(0.5)), ("gap", f(0.025)), ("bevel", f(0.12)), ("height_random", f(0.2))],
);
let ids = b.n(
"brick_generator",
0.0,
160.0,
&[("bricks_x", i(3)), ("bricks_y", i(3)), ("offset", f(0.5)), ("gap", f(0.025)), ("bevel", f(0.0)), ("height_random", f(0.0)), ("lum_random", f(1.0))],
);
let cracks = b.n("cracks", 0.0, 320.0, &[("scale", f(4.0)), ("width", f(1.0))]);
let clouds = b.n("clouds_2", 0.0, 480.0, &[("scale", f(12.0))]);
let chipped = b.n("edge_damage", 180.0, 0.0, &[("width", f(10.0)), ("amount", f(0.5)), ("scale", f(10.0))]);
b.c(layout, chipped, "height");
let cracked = b.n("blend", 360.0, 0.0, &[("mode", e(2)), ("opacity", f(0.35))]);
b.c(cracks, cracked, "foreground");
b.c(chipped, cracked, "background");
let height = b.n("blend", 540.0, 0.0, &[("mode", e(3)), ("opacity", f(0.2))]);
b.c(clouds, height, "foreground");
b.c(cracked, height, "background");
let normal = b.n("normal", 720.0, 0.0, &[("intensity", f(2.0))]);
b.c(height, normal, "input");
let ao = b.n("ambient_occlusion", 720.0, 120.0, &[("spread", f(0.05)), ("intensity", f(0.7))]);
b.c(height, ao, "height");
let tone = b.n("blend", 360.0, 240.0, &[("mode", e(9)), ("opacity", f(0.45))]);
b.c(clouds, tone, "foreground");
b.c(ids, tone, "background");
let stone_col =
b.n("gradient_map", 540.0, 240.0, &[("gradient", grad(&[(0.0, [0.09, 0.08, 0.065]), (0.5, [0.2, 0.18, 0.14]), (1.0, [0.34, 0.31, 0.25])]))]);
b.c(tone, stone_col, "input");
let mask = b.n("histogram_scan", 540.0, 400.0, &[("position", f(0.9)), ("contrast", f(0.9))]);
b.c(cracked, mask, "input");
let grout = b.n("uniform", 540.0, 520.0, &[("color", col(0.04, 0.035, 0.03))]);
let base = b.n("blend", 720.0, 320.0, &[]);
b.c(stone_col, base, "foreground");
b.c(grout, base, "background");
b.c(mask, base, "mask");
let rough = b.n("levels", 720.0, 460.0, &[("out_low", f(0.6)), ("out_high", f(0.9))]);
b.c(clouds, rough, "input");
let metal = b.n("uniform", 720.0, 580.0, &[("mode", e(1)), ("color", col(0.0, 0.0, 0.0))]);
b.outputs(
940.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 marble(b: &mut B) {
let veins = b.n("marble", 0.0, 0.0, &[("scale", f(3.0)), ("turbulence", f(5.0)), ("sharpness", f(14.0)), ("direction", e(2))]);
let fine = b.n("ridged_fractal", 0.0, 160.0, &[("scale", f(6.0)), ("octaves", i(6)), ("roughness", f(0.55)), ("sharpness", f(6.0))]);
let flow = b.n("fractal_sum_base", 0.0, 320.0, &[("scale", f(3.0)), ("octaves", i(6))]);
let fine_mask = b.n("levels", 180.0, 160.0, &[("in_low", f(0.55)), ("in_high", f(1.0)), ("out_high", f(0.45))]);
b.c(fine, fine_mask, "input");
let vein_mask = b.n("blend", 360.0, 80.0, &[("mode", e(5))]);
b.c(fine_mask, vein_mask, "foreground");
b.c(veins, vein_mask, "background");
let normal = b.n("normal", 720.0, 0.0, &[("intensity", f(0.25))]);
b.c(flow, normal, "input");
let ao = b.n("ambient_occlusion", 720.0, 120.0, &[("spread", f(0.02)), ("intensity", f(0.2))]);
b.c(flow, ao, "height");
let stone = b.n("gradient_map", 540.0, 240.0, &[("gradient", grad(&[(0.0, [0.8, 0.78, 0.74]), (0.5, [0.52, 0.48, 0.42]), (1.0, [0.2, 0.17, 0.13])]))]);
b.c(vein_mask, stone, "input");
let cloudy = b.n("blend", 720.0, 240.0, &[("mode", e(3)), ("opacity", f(0.3))]);
b.c(flow, cloudy, "foreground");
b.c(stone, cloudy, "background");
let rough = b.n("uniform", 720.0, 400.0, &[("mode", e(1)), ("color", col(0.12, 0.12, 0.12))]);
let metal = b.n("uniform", 720.0, 520.0, &[("mode", e(1)), ("color", col(0.0, 0.0, 0.0))]);
b.outputs(
940.0,
&[
(cloudy, "output", 0, "basecolor"),
(normal, "output", 1, "normal"),
(rough, "output", 2, "roughness"),
(metal, "output", 3, "metallic"),
(flow, "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.4)), ("contrast", f(0.8))]);
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(3)), ("opacity", f(0.35))]);
b.c(fine, h, "foreground");
b.c(scan, h, "background");
let normal = b.n("normal", 600.0, 0.0, &[("intensity", f(1.0))]);
b.c(h, normal, "input");
let rust_col =
b.n("gradient_map", 400.0, 240.0, &[("gradient", grad(&[(0.0, [0.03, 0.01, 0.004]), (0.5, [0.11, 0.035, 0.01]), (1.0, [0.22, 0.08, 0.02])]))]);
b.c(fine, rust_col, "input");
let metal_col = b.n("uniform", 400.0, 380.0, &[("color", col(0.52, 0.53, 0.55))]);
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.32)), ("out_high", f(0.48))]);
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"),
],
);
}
/// 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
Ok(graph)
}
+12 -17
View File
@@ -9,7 +9,8 @@ use materialcraft_eval::{Cache, Cooked, Options};
use materialcraft_image::Image;
use serde::{Deserialize, Serialize};
use crate::{EngineError, Result};
use crate::snapshot::Snapshot;
use crate::{AnnotationSelection, Clip, EngineError, Result};
/// Undo keeps this many steps.
const MAX_UNDO: usize = 200;
@@ -110,21 +111,6 @@ pub struct View2d {
pub histogram: bool,
}
#[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>,
}
/// The prefix of warning lines in [`Session::log`].
pub const WARNING_PREFIX: &str = "Warning: ";
@@ -135,6 +121,7 @@ pub struct Session {
/// Index of the graph being edited.
pub graph: usize,
pub selection: Vec<NodeId>,
pub annotation_selection: Option<AnnotationSelection>,
pub view2d: View2d,
pub view3d: View3d,
/// Cap on node output size while editing (`None` = full size).
@@ -168,6 +155,7 @@ impl Session {
path: None,
graph: 0,
selection: Vec::new(),
annotation_selection: None,
view2d: View2d { channel: "rgba".into(), ..View2d::default() },
view3d: View3d::default(),
preview_size: Some(512),
@@ -197,7 +185,13 @@ impl Session {
}
fn snapshot(&self, label: &str) -> Snapshot {
Snapshot { pkg: self.pkg.clone(), graph: self.graph, selection: self.selection.clone(), label: label.into() }
Snapshot {
pkg: self.pkg.clone(),
graph: self.graph,
selection: self.selection.clone(),
annotation_selection: self.annotation_selection,
label: label.into(),
}
}
/// Run `f` as one undoable step. On error the session is restored.
@@ -246,6 +240,7 @@ impl Session {
self.pkg = s.pkg;
self.graph = s.graph.min(self.pkg.graphs.len().saturating_sub(1));
self.selection = s.selection;
self.annotation_selection = s.annotation_selection;
}
/// Mark the document modified and in need of a cook.
+11
View File
@@ -0,0 +1,11 @@
use crate::AnnotationSelection;
use materialcraft_core::{NodeId, Package};
#[derive(Clone)]
pub(crate) struct Snapshot {
pub(crate) pkg: Package,
pub(crate) graph: usize,
pub(crate) selection: Vec<NodeId>,
pub(crate) annotation_selection: Option<AnnotationSelection>,
pub(crate) label: String,
}
+19
View File
@@ -0,0 +1,19 @@
use crate::{Session, core};
/// A fresh, unsaved package with one empty graph, used at desktop and browser startup
pub fn new_session() -> Session {
let mut pkg = core::Package::new("Untitled package");
pkg.graphs.push(core::Graph::new("New_graph"));
Session::new(pkg)
}
pub fn sample_session() -> Session {
match crate::atomic_sample() {
Ok(package) => Session::new(package),
Err(error) => {
let mut session = new_session();
session.log.push(format!("Could not create the atomic sample: {error}"));
session
}
}
}
+55
View File
@@ -0,0 +1,55 @@
use materialcraft_core::ValueType;
use serde_json::{Value as JsonValue, json};
use crate::commands::{CommandSpec, bad, has_graph, node_param, strp};
use crate::{Result, Session, cmd};
const COMMAND: &str = "graph.node.value_input";
pub(crate) fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"graph.node.value_input",
"Edit value input",
[],
None,
"{id, name, type? (Float, Float2, Float3, Float4, Integer, Integer2, Integer3, Integer4, Boolean, String), remove?}",
has_graph,
edit
)]
}
fn edit(session: &mut Session, parameters: &JsonValue) -> Result<JsonValue> {
let id = node_param(session, COMMAND, parameters, "id")?;
let name = strp(parameters, "name").unwrap_or("").trim().to_string();
if name.is_empty() || name.len() > 256 || name.starts_with('$') {
return Err(bad(COMMAND, "use a nonempty input name up to 256 bytes, without a leading $"));
}
let remove = parameters.get("remove").and_then(JsonValue::as_bool).unwrap_or(false);
let type_name = strp(parameters, "type").unwrap_or("Float");
let value_type = ValueType::ALL
.into_iter()
.find(|value_type| value_type.label() == type_name)
.ok_or_else(|| bad(COMMAND, format!("unknown value type `{type_name}`")))?;
let node = session.graph()?.node(id)?;
let definition = materialcraft_nodes::find(&node.def);
if definition.is_some_and(|definition| definition.input_index(&name).is_some()) {
return Err(bad(COMMAND, "an image input already uses that name"));
}
if !remove && node.input_values.len() >= 64 && !node.input_values.contains_key(&name) {
return Err(bad(COMMAND, "a node supports up to 64 value inputs"));
}
session.edit("Edit value input", |session| {
let graph = session.graph_mut()?;
let node = graph.node_mut(id)?;
if remove {
node.input_values.remove(&name);
graph.disconnect(id, &name);
} else {
node.input_values.insert(name, value_type);
}
Ok(json!(null))
})
}
Loaded 100 of 338 files, more files were not shown because too many files have changed in this diff. Show more