Merge remote-tracking branch 'origin/main' into review/pr-35

# Conflicts:
#	crates/ui-egui/src/graph_view.rs
This commit is contained in:
Rafael Mendes committed 2026-11-05 10:23:17 -03:00
commit 80338564d4
58 files changed
+4892 -218

No files matched your search

+1
View File
@@ -46,6 +46,7 @@ jobs:
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
# The jobs below stay here only while this repo is private. They follow the shared workflow's
# FreeBSD job, on a larger runner. When the repo is public, remove them and has-freebsd: false.
+19
View File
@@ -0,0 +1,19 @@
name: SonarCloud
on:
push:
branches: [main]
pull_request:
types: [opened, synchronize, reopened]
permissions:
contents: read
concurrency:
group: sonarcloud-${{ github.ref }}
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
jobs:
sonarcloud:
uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@main
secrets: inherit
+1
View File
@@ -10,3 +10,4 @@ target/
/craft-fonts
*.mcraft.tmp
.claude/worktrees/
pr-review-guidelines.md
+8 -5
View File
@@ -11,7 +11,8 @@ 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 native package extension `.mcraft`.
(`ai.storyteller.materialcraft`). The main project format is SBS (`.sbs`); the older native
package extension `.mcraft` is still read and written.
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,7 +42,7 @@ file first, then `docs/`.
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); .mcraft packages, bitmaps, texture export
eval formats L2 graph cooking (topological order, sizes, content-addressed cache, sub-graphs); .sbs and .mcraft 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)
@@ -96,9 +97,11 @@ workflow. Work from public documentation, general domain knowledge and public al
and simplex gradient noise, Worley/cellular noise, fractal sums, Gaussian and box blurs,
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, presets or
file formats; compatibility with the reference app's package formats is a non-goal. Always describe
MaterialCraft as a clean-room implementation, in code, docs and commits.
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
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.
### Never crash (outranks feature work)
+3
View File
@@ -26,7 +26,10 @@ images, materials, sample graphs, presets, environments) may ever be added.
| `docs/images/materialcraft-lava.png` | README screenshot: the lava rock template | MaterialCraft contributors | Offscreen render of MaterialCraft's UI | MIT OR Apache-2.0 |
| `docs/images/materialcraft-ground.png` | README screenshot: the mossy ground template | MaterialCraft contributors | Offscreen render of MaterialCraft's UI | MIT OR Apache-2.0 |
| `docs/images/materialcraft-new-graph.png` | README screenshot: the New graph dialog | MaterialCraft contributors | Offscreen render of MaterialCraft's UI | MIT OR Apache-2.0 |
| `docs/images/materialcraft-alpha-transparency.png` | Docs screenshot: a cut-out material in the 3D view and a reroute dot on a wire | MaterialCraft contributors | Offscreen render of MaterialCraft's UI (`crates/ui-egui/tests/snapshot.rs`) | MIT OR Apache-2.0 |
| `docs/images/materialcraft-alpha-channel.png` | Docs screenshot: the 3D view's alpha channel view | MaterialCraft contributors | Offscreen render of MaterialCraft's UI (`crates/ui-egui/tests/snapshot.rs`) | MIT OR Apache-2.0 |
| `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 |
Generated
+25 -14
View File
@@ -2307,7 +2307,7 @@ checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"
[[package]]
name = "materialcraft"
version = "0.1.0"
version = "0.1.2"
dependencies = [
"eframe",
"egui",
@@ -2321,7 +2321,7 @@ dependencies = [
[[package]]
name = "materialcraft-automation"
version = "0.1.0"
version = "0.1.2"
dependencies = [
"base64 0.22.1",
"cap-std",
@@ -2341,7 +2341,7 @@ dependencies = [
[[package]]
name = "materialcraft-cli"
version = "0.1.0"
version = "0.1.2"
dependencies = [
"materialcraft-automation",
"materialcraft-engine",
@@ -2352,7 +2352,7 @@ dependencies = [
[[package]]
name = "materialcraft-core"
version = "0.1.0"
version = "0.1.2"
dependencies = [
"serde",
"serde_json",
@@ -2361,7 +2361,7 @@ dependencies = [
[[package]]
name = "materialcraft-engine"
version = "0.1.0"
version = "0.1.2"
dependencies = [
"materialcraft-core",
"materialcraft-eval",
@@ -2376,7 +2376,7 @@ dependencies = [
[[package]]
name = "materialcraft-eval"
version = "0.1.0"
version = "0.1.2"
dependencies = [
"materialcraft-core",
"materialcraft-image",
@@ -2386,13 +2386,17 @@ dependencies = [
[[package]]
name = "materialcraft-formats"
version = "0.1.0"
version = "0.1.2"
dependencies = [
"base64 0.22.1",
"flate2",
"gltf",
"image",
"materialcraft-core",
"materialcraft-geom",
"materialcraft-image",
"materialcraft-nodes",
"roxmltree",
"serde",
"serde_json",
"thiserror 2.0.21",
@@ -2402,7 +2406,7 @@ dependencies = [
[[package]]
name = "materialcraft-geom"
version = "0.1.0"
version = "0.1.2"
dependencies = [
"glam 0.30.10",
"mikktspace",
@@ -2413,7 +2417,7 @@ dependencies = [
[[package]]
name = "materialcraft-image"
version = "0.1.0"
version = "0.1.2"
dependencies = [
"rayon",
"thiserror 2.0.21",
@@ -2421,7 +2425,7 @@ dependencies = [
[[package]]
name = "materialcraft-nodes"
version = "0.1.0"
version = "0.1.2"
dependencies = [
"materialcraft-core",
"materialcraft-image",
@@ -2430,7 +2434,7 @@ dependencies = [
[[package]]
name = "materialcraft-render"
version = "0.1.0"
version = "0.1.2"
dependencies = [
"materialcraft-geom",
"materialcraft-image",
@@ -2439,7 +2443,7 @@ dependencies = [
[[package]]
name = "materialcraft-ui-egui"
version = "0.1.0"
version = "0.1.2"
dependencies = [
"base64 0.22.1",
"craft-ui",
@@ -2455,6 +2459,7 @@ dependencies = [
"rfd",
"serde",
"serde_json",
"sys-locale",
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
@@ -2463,7 +2468,7 @@ dependencies = [
[[package]]
name = "materialcraft-web"
version = "0.1.0"
version = "0.1.2"
dependencies = [
"eframe",
"js-sys",
@@ -3588,6 +3593,12 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "roxmltree"
version = "0.20.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97"
[[package]]
name = "rustc-hash"
version = "1.1.0"
@@ -5234,7 +5245,7 @@ checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7"
[[package]]
name = "xtask"
version = "0.1.0"
version = "0.1.2"
dependencies = [
"serde_json",
]
+3 -1
View File
@@ -35,7 +35,7 @@ default-members = [
]
[workspace.package]
version = "0.1.0"
version = "0.1.2"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.95"
@@ -76,6 +76,8 @@ rmcp = { version = "3.5", default-features = false, features = ["server", "macro
tokio = { version = "1", features = ["rt-multi-thread", "macros", "io-std", "sync", "net", "io-util", "time"] }
schemars = "1"
base64 = "0.22"
roxmltree = "0.20"
flate2 = { version = "1", default-features = false, features = ["rust_backend"] }
cap-std = "4"
getrandom = "0.3"
# Shared Craft egui components (widget palette, icon buttons, panel docking): storytold/craft-libs,
+15 -11
View File
@@ -106,14 +106,16 @@ ray-traced ambient occlusion and a shadowed key light).
- **Familiar.** The layout, panels, menus and gestures material artists already know: a package
explorer, a library of nodes with previews, the node graph with live thumbnails, a 3D view, a 2D
view and a properties panel with base and specific parameters. Space opens the node search.
view and a properties panel with base and specific parameters (Levels is edited over a
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.
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 `.mcraft` packages.
with odd inputs in tests, unlimited undo from snapshots, and lossless 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
@@ -131,20 +133,20 @@ ray-traced ambient occlusion and a shadowed key light).
git clone https://github.com/storytold/materialcraft
cd materialcraft
cargo run --release -p materialcraft # desktop app (opens the brick wall sample)
cargo run --release -p materialcraft -- package.mcraft # open a package
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 -- --control 7878 # + JSON control channel
cargo run --release -p materialcraft-cli -- mcp # MCP server (stdio)
cargo run --release -p materialcraft-cli -- new wood wood.mcraft
cargo run --release -p materialcraft-cli -- render wood.mcraft wood.png --scene sphere --full --hq
cargo run --release -p materialcraft-cli -- export wood.mcraft textures --format png --depth 16
cargo run --release -p materialcraft-cli -- export my.mcraft out --set wear=0.7 # with a graph input "wear" set first
cargo run --release -p materialcraft-cli -- run my.mcraft file.exportMaterial '{"path": "my.mcmat", "size": 2048}' # for TextureCraft
cargo run --release -p materialcraft-cli -- new wood wood.sbs
cargo run --release -p materialcraft-cli -- render wood.sbs wood.png --scene sphere --full --hq
cargo run --release -p materialcraft-cli -- export wood.sbs textures --format png --depth 16
cargo run --release -p materialcraft-cli -- export my.sbs out --set wear=0.7 # with a graph input "wear" set first
cargo run --release -p materialcraft-cli -- run my.sbs file.exportMaterial '{"path": "my.mcmat", "size": 2048}' # for TextureCraft
cd apps/materialcraft-web && trunk serve # web build
cargo xtask ci # fmt, clippy, tests, layering, wasm
```
You need Rust 1.95 or newer. The app opens with the brick wall sample; **File ▸ New ▸ Graph...**
You need Rust 1.95 or newer. The app opens with an empty graph in a new package; **File ▸ New ▸ Graph...**
starts from a PBR template or one of the sample materials.
### Use it from Claude Code and other agents
@@ -172,7 +174,9 @@ area, the remaining work and what's next.
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), `.mcraft` packages,
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
+11 -10
View File
@@ -14,23 +14,23 @@ materialcraft-cli: headless MaterialCraft
USAGE:
materialcraft-cli --version
materialcraft-cli info <package.mcraft | sample>
materialcraft-cli info <package.sbs | package.mcraft | sample>
Graphs, nodes, outputs and cook results, as JSON.
materialcraft-cli commands [--filter <text>]
List the engine commands (id, label, params).
materialcraft-cli nodes [--filter <text>] [--category <text>]
List the node library (ids, ports, parameters).
materialcraft-cli run <input> <command-id> [params-json] [-o <out.mcraft>]
materialcraft-cli run <input> <command-id> [params-json] [-o <out.sbs>]
Run one command and print its JSON result; -o saves the package.
materialcraft-cli batch <script.json>
Run [{\"id\", \"params\"}, ...] or {\"open\": <input>, \"steps\": [...], \"save\": <out.mcraft>}.
materialcraft-cli new <template> <out.mcraft> [--size <px>] [--name <name>]
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).
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>]
[--depth 8|16|32] [--pattern <p>]
[--depth 8|16|32] [--size <px>] [--pattern <p>]
Cook at full size and write every output (png, jpg, tga, tif, bmp, webp, exr, hdr).
materialcraft-cli render <input> <out.png> [--size <W>x<H>] [--view 3d|2d] [--scene <id>] [--node <id>]
[--yaw <deg>] [--pitch <deg>] [--graph <index>] [--set <input>=<value>]... [--full]
@@ -44,7 +44,8 @@ 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 a .mcraft package or `sample` (the built-in brick wall). --set gives a graph input a value
<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
(JSON, e.g. `--set roughness=0.4 --set tint=\"#aa7744\"`) before cooking. See docs/control-protocol.md.
";
@@ -57,7 +58,7 @@ const SUBCOMMANDS: &[(&str, &[&str], &[&str])] = &[
("batch", &[], &[]),
("new", &["--size", "--name"], &[]),
("cook", &["--graph", "--set"], &["--full"]),
("export", &["--graph", "--set", "--format", "--depth", "--pattern"], &[]),
("export", &["--graph", "--set", "--format", "--depth", "--size", "--pattern"], &[]),
("render", &["--size", "--view", "--scene", "--node", "--yaw", "--pitch", "--graph", "--set", "--tiling", "--displacement"], &["--full", "--hq"]),
("mcp", &["--bridge", "--token", "--read-root", "--write-root"], &[]),
("serve", &["--port", "--read-root", "--write-root"], &[]),
@@ -113,7 +114,7 @@ fn version() -> String {
}
}
/// A headless session on `input` (a .mcraft package or `sample`), with local file access.
/// A headless session on `input` (an .sbs or .mcraft 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" {
@@ -210,7 +211,7 @@ fn run(cmd: &str, a: &Args) -> Result<(), String> {
}
"new" => {
let tpl = a.pos(0, "<template>")?;
let out = a.pos(1, "<out.mcraft>")?;
let out = a.pos(1, "<out.sbs>")?;
let mut h = Headless::new(Headless::default_session(), Filesystem::TrustedLocal);
h.command_run("file.newPackage", json!({"name": a.get("--name").unwrap_or("Untitled package")})).map_err(|e| e.to_string())?;
h.command_run("file.new", json!({"template": tpl, "size": a.num::<u64>("--size")?.unwrap_or(1024), "name": a.get("--name")}))
@@ -227,7 +228,7 @@ fn run(cmd: &str, a: &Args) -> Result<(), String> {
let mut h = open(a.pos(0, "<input>")?)?;
select_graph(&mut h, a)?;
let dir = a.pos(1, "<dir>")?;
let p = json!({"dir": dir, "graph": a.num::<u64>("--graph")?, "format": a.get("--format"), "depth": a.num::<u64>("--depth")?, "pattern": a.get("--pattern")});
let p = json!({"dir": dir, "graph": a.num::<u64>("--graph")?, "format": a.get("--format"), "depth": a.num::<u64>("--depth")?, "size": a.num::<u64>("--size")?, "pattern": a.get("--pattern")});
print(&h.export(&p).map_err(|e| e.to_string())?);
}
"render" => {
+2 -2
View File
@@ -38,8 +38,8 @@ pub fn start() {
async fn run(canvas: web_sys::HtmlCanvasElement) -> Result<(), String> {
// The WebAssembly has downloaded and compiled when this runs.
step(0.5, "Preparing the sample package…").await;
let session = materialcraft_engine::sample_session();
step(0.5, "Preparing a new package…").await;
let session = materialcraft_engine::new_session();
step(0.8, "Starting the renderer…").await;
let mut options = eframe::WebOptions::default();
if query().contains("webgl")
+38 -16
View File
@@ -1,6 +1,6 @@
//! MaterialCraft desktop app.
//!
//! Usage: `materialcraft [package.mcraft] [--control <port>] [--empty] [--version]`
//! Usage: `materialcraft [package.sbs|package.mcraft] [--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)]
@@ -26,11 +26,10 @@ fn version() -> String {
struct Args {
file: Option<String>,
control: Option<u16>,
empty: bool,
}
fn parse_args() -> Result<Option<Args>, String> {
let mut args = Args { file: None, control: None, empty: false };
let mut args = Args { file: None, control: None };
let mut it = std::env::args().skip(1);
while let Some(a) = it.next() {
match a.as_str() {
@@ -39,14 +38,15 @@ fn parse_args() -> Result<Option<Args>, String> {
return Ok(None);
}
"--help" | "-h" => {
println!("{}\n\nUsage: materialcraft [package.mcraft] [--control <port>] [--empty]", version());
println!("{}\n\nUsage: materialcraft [package.sbs|package.mcraft] [--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}`"))?);
}
"--empty" => args.empty = true,
// 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}`")),
}
@@ -55,18 +55,9 @@ fn parse_args() -> Result<Option<Args>, String> {
}
fn initial_session(args: &Args) -> Session {
let mut s = if args.empty {
let mut pkg = materialcraft_engine::core::Package::new("Untitled package");
pkg.graphs.push(materialcraft_engine::samples::template("pbr", "New_graph", 10));
Session::new(pkg)
} else {
materialcraft_engine::sample_session()
};
let mut s = materialcraft_engine::new_session();
if let Some(f) = &args.file {
match std::fs::read(f)
.map_err(|e| e.to_string())
.and_then(|b| materialcraft_engine::file_cmds::open_bytes(&mut s, &b, Some(f.clone())).map_err(|e| e.to_string()))
{
match materialcraft_engine::file_cmds::open_file(&mut s, f).map_err(|e| e.to_string()) {
Ok(()) => {}
Err(e) => eprintln!("materialcraft: could not open {f}: {e}"),
}
@@ -121,3 +112,34 @@ fn main() {
std::process::exit(1);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn startup_without_a_file_has_one_empty_graph() {
let s = initial_session(&Args { file: None, control: None });
assert_eq!(s.pkg.name, "Untitled package");
assert_eq!(s.pkg.graphs.len(), 1);
let g = s.graph().unwrap();
assert_eq!(g.name, "New_graph");
assert!(g.nodes.is_empty());
assert!(g.connections.is_empty());
assert!(s.path.is_none());
assert!(!s.modified);
assert!(s.history().is_empty());
}
#[test]
fn startup_opens_the_requested_package() {
let path = std::env::temp_dir().join(format!("mc-startup-{}.mcraft", 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.path.as_deref(), path.to_str());
assert!(!s.modified);
std::fs::remove_file(path).unwrap();
}
}
+39 -20
View File
@@ -63,6 +63,21 @@ pub struct Headless {
light: Option<Lighting>,
}
/// 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>")),
Filesystem::TrustedLocal => {
let len = std::fs::metadata(path).map_err(|e| AutomationError::Io(format!("cannot read {path}: {e}")))?.len();
if len > MAX_READ_BYTES {
return Err(bad(format!("{path} is {len} bytes (limit {MAX_READ_BYTES})")));
}
std::fs::read(path).map_err(|e| AutomationError::Io(format!("cannot read {path}: {e}")))
}
Filesystem::Workspace(w) => w.read(path),
}
}
impl Headless {
pub fn new(session: Session, fs: Filesystem) -> Headless {
Headless { session, fs, scene: None, light: None }
@@ -78,17 +93,7 @@ impl Headless {
}
fn read(&self, path: &str) -> Result<Vec<u8>, AutomationError> {
match &self.fs {
Filesystem::Denied => Err(bad("file access is not granted: start the server with --read-root <dir>")),
Filesystem::TrustedLocal => {
let len = std::fs::metadata(path).map_err(|e| AutomationError::Io(format!("cannot read {path}: {e}")))?.len();
if len > MAX_READ_BYTES {
return Err(bad(format!("{path} is {len} bytes (limit {MAX_READ_BYTES})")));
}
std::fs::read(path).map_err(|e| AutomationError::Io(format!("cannot read {path}: {e}")))
}
Filesystem::Workspace(w) => w.read(path),
}
read_file(&self.fs, path)
}
fn write(&self, path: &str, bytes: &[u8]) -> Result<(), AutomationError> {
@@ -138,21 +143,33 @@ impl Headless {
batch_reply(results, None)
}
/// Open a `.mcraft` package.
/// Open an `.sbs` or `.mcraft` 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)?;
file_cmds::open_bytes(&mut self.session, &bytes, Some(path.to_string()))?;
let folder = path.replace('\\', "/").rsplit_once('/').map(|(folder, _)| format!("{folder}/")).unwrap_or_default();
let fs = &self.fs;
let linked = |relative: &str| -> Option<Vec<u8>> {
let relative = relative.trim().replace('\\', "/");
let plain = !relative.is_empty() && !relative.contains(':') && !relative.starts_with('/');
let inside = relative.split('/').all(|part| !part.is_empty() && part != "." && part != "..");
if !plain || !inside {
return None;
}
read_file(fs, &format!("{folder}{relative}")).ok()
};
file_cmds::open_bytes_linked(&mut self.session, &bytes, Some(path.to_string()), &linked)?;
Ok(self.inspect())
}
/// Save the package (`.mcraft` appended when missing) to `path` or its own file.
/// Save to `path` (`.sbs` appended without a package extension) or the package's own file; SBS unless it is a `.mcraft`.
pub fn save(&mut self, path: Option<&str>) -> Result<Value, AutomationError> {
let path = match path {
Some(p) if p.to_ascii_lowercase().ends_with(".mcraft") => p.to_string(),
Some(p) => format!("{p}.mcraft"),
None => self.session.path.clone().ok_or_else(|| bad("the package has no file yet: give a `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(&self.session)?;
let bytes = file_cmds::save_bytes_as(&self.session, file_cmds::PackageFormat::of_path(&path))?;
self.write(&path, &bytes)?;
self.session.path = Some(path.clone());
self.session.modified = false;
@@ -170,8 +187,8 @@ impl Headless {
/// 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) = file_cmds::export_params(&self.session, p)?;
let files = file_cmds::export_outputs(&self.session, gi, &ext, &pattern, depth)?;
let (gi, ext, pattern, depth, size) = file_cmds::export_params(&self.session, p)?;
let files = file_cmds::export_outputs(&self.session, gi, &ext, &pattern, depth, size)?;
self.create_dir_all(dir)?;
let mut written = Vec::new();
for f in files {
@@ -243,6 +260,8 @@ impl Headless {
height_scale: v.height_scale,
show_env: false,
supersample: 2,
transparency: v.transparency,
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));
+11 -4
View File
@@ -126,8 +126,8 @@ pub struct PathParams {
#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
pub struct SaveParams {
/// Forward-slash path relative to the write root (`.mcraft` is appended if missing). Omit to
/// save to the package's own file.
/// 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>,
}
@@ -154,6 +154,9 @@ pub struct ExportParams {
/// 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>,
@@ -404,12 +407,16 @@ impl MaterialcraftMcp {
to_result(self.run("graph.node.param", params(&p)).await)
}
#[tool(description = "Open a .mcraft package (path relative to the read root). Returns the session.")]
#[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)."
)]
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 as .mcraft (path relative to the write root; omit to save to its own file).")]
#[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."
)]
async fn package_save(&self, Parameters(p): Parameters<SaveParams>) -> Result<CallToolResult, McpError> {
to_result(self.call("package.save", params(&p)).await)
}
+25
View File
@@ -124,6 +124,31 @@ impl Node {
}
}
/// 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")]
+2 -2
View File
@@ -14,8 +14,8 @@ pub mod package;
pub mod value;
pub use graph::{
Attributes, BaseParams, Comment, Connection, ExposedParam, Frame, Graph, GraphKind, MAX_SIZE_LOG2, MIN_SIZE_LOG2, Node, NodeId, OutputFormat, Pin, Preset,
SizeMode,
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};
pub use value::{Curve, CurvePoint, Gradient, GradientKey, Value, linear_to_srgb, parse_color, srgb_to_linear};
+1
View File
@@ -54,6 +54,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(crate::graph_cmds::specs());
v.extend(crate::node_cmds::specs());
v.extend(crate::view_cmds::specs());
v.extend(crate::wire_cmds::specs());
v
})
}
+160 -29
View File
@@ -1,6 +1,9 @@
//! 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.
use serde_json::{Value as J, json};
@@ -23,15 +26,31 @@ pub(crate) fn specs() -> Vec<CommandSpec> {
new_graph
),
cmd!("file.newPackage", "Empty package", ["File", "New"], None, "{name?} replaces the session with an empty package", always, new_package),
cmd!("file.open", "Open...", ["File"], Some("Ctrl+O"), "{path} opens a .mcraft package", always, open),
cmd!("file.save", "Save", ["File"], Some("Ctrl+S"), "{path?} saves the package (.mcraft) to its own file or `path`", always, save),
cmd!(
"file.open",
"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`)",
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.saveAs", "Save as...", ["File"], Some("Ctrl+Shift+S"), "{path} saves the package under a new name", always, save),
cmd!(
"file.export",
"Export outputs...",
["File"],
Some("Ctrl+Shift+E"),
"{dir, format? (png|jpg|tga|tif|bmp|webp|exr|hdr), pattern? ($(graph)_$(identifier)), depth? (8|16|32), graph?} cooks the graph at full size and writes every output",
"{dir, format? (png|jpg|tga|tif|bmp|webp|exr|hdr), pattern? ($(graph)_$(identifier)), depth? (8|16|32), size? (px of the larger side, rounded down to a power of two, 16..8192; default the graph's size, keeping its proportions), graph?} cooks the graph at full size and writes every output",
has_graph,
export
),
@@ -83,34 +102,135 @@ pub fn replace_package(s: &mut Session, pkg: Package, path: Option<String>) {
s.reset_history();
s.modified = false;
s.dirty = true;
s.load_warnings.clear();
}
/// Open package bytes (any platform). A portable material (`.mcmat`) opens the package it was
/// cooked from, on its graph, with no file name (saving must not overwrite the material).
/// 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())
}
}
/// 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)
}
/// [`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<()> {
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(());
}
let pkg = materialcraft_formats::load_package(bytes)?;
replace_package(s, pkg, name);
// 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);
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());
}
}
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;
Ok(())
}
/// The package as `.mcraft` bytes.
/// The package as SBS bytes, the main project format.
pub fn save_bytes(s: &Session) -> Result<Vec<u8>> {
Ok(materialcraft_formats::save_package(&s.pkg)?)
save_bytes_as(s, PackageFormat::Sbs)
}
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.
#[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.
#[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("."));
let folder = std::fs::canonicalize(parent).ok();
move |relative: &str| {
let relative = relative.trim().replace('\\', "/");
let plain = !relative.is_empty() && !relative.contains(':') && !relative.starts_with('/');
if !plain || std::path::Path::new(&relative).components().any(|c| !matches!(c, std::path::Component::Normal(_))) {
return None;
}
let folder = folder.as_ref()?;
let file = std::fs::canonicalize(folder.join(&relative)).ok()?;
let metadata = std::fs::metadata(&file).ok()?;
if !file.starts_with(folder) || !metadata.is_file() || metadata.len() > MAX_LINKED_FILE_BYTES {
return None;
}
std::fs::read(file).ok()
}
}
/// 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}")))?;
open_bytes_linked(s, &bytes, Some(path.to_string()), &linked_files(path))
}
#[cfg(not(target_arch = "wasm32"))]
fn open(s: &mut Session, p: &J) -> Result<J> {
let path = strp(p, "path").ok_or_else(|| bad("file.open", "`path` is required"))?;
let bytes = std::fs::read(path).map_err(|e| bad("file.open", format!("{path}: {e}")))?;
open_bytes(s, &bytes, Some(path.to_string()))?;
open_file(s, path)?;
s.log(format!("Opened {path}"));
Ok(json!({"name": s.pkg.name, "graphs": s.pkg.graphs.len()}))
Ok(json!({"name": s.pkg.name, "graphs": s.pkg.graphs.len(), "path": s.path, "warnings": s.load_warnings}))
}
#[cfg(target_arch = "wasm32")]
@@ -121,16 +241,11 @@ fn open(_: &mut Session, _: &J) -> Result<J> {
#[cfg(not(target_arch = "wasm32"))]
fn save(s: &mut Session, p: &J) -> Result<J> {
let path = match strp(p, "path") {
Some(path) => {
let mut path = path.to_string();
if !path.to_ascii_lowercase().ends_with(".mcraft") {
path.push_str(".mcraft");
}
path
}
None => s.path.clone().ok_or_else(|| bad("file.save", "the package has no file yet: give a `path`"))?,
Some(path) => package_path(path),
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(s)?;
let bytes = save_bytes_as(s, PackageFormat::of_path(&path))?;
materialcraft_formats::write_atomic(std::path::Path::new(&path), &bytes)?;
s.path = Some(path.clone());
s.modified = false;
@@ -150,9 +265,22 @@ pub struct Exported {
}
/// Cook graph `gi` at full size and encode every output (`pattern` names files).
pub fn export_outputs(s: &Session, gi: usize, ext: &str, pattern: &str, depth: Option<Depth>) -> Result<Vec<Exported>> {
let g = s.pkg.graph(gi)?;
let cooked = s.cook_full(gi);
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.
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]);
g.size = bounded.map(|l| (l + target).saturating_sub(larger).max(4));
}
let g = pkg.graph(gi)?;
let dec = s.resource_decoder();
let cooked = {
let mut cache = s.cache.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
materialcraft_eval::cook(&pkg, gi, &materialcraft_eval::Options::new(&dec), &mut cache)
};
let mut out = Vec::new();
for (id, usage, ident, img) in materialcraft_eval::outputs(g, &cooked) {
let Some(img) = img else { continue };
@@ -168,8 +296,10 @@ pub fn export_outputs(s: &Session, gi: usize, ext: &str, pattern: &str, depth: O
Ok(out)
}
/// Export params: (graph index, extension, pattern, depth).
pub fn export_params(s: &Session, p: &J) -> Result<(usize, String, String, Option<Depth>)> {
/// 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> {
let gi = u64p(p, "graph").map_or(s.graph, |g| g as usize);
s.pkg.graph(gi)?;
let ext = strp(p, "format").unwrap_or("png").trim_start_matches('.').to_ascii_lowercase();
@@ -184,14 +314,15 @@ pub fn export_params(s: &Session, p: &J) -> Result<(usize, String, String, Optio
Some(32) => Some(Depth::F32),
Some(d) => return Err(bad("file.export", format!("depth must be 8, 16 or 32, not {d}"))),
};
Ok((gi, ext, pattern, depth))
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))
}
#[cfg(not(target_arch = "wasm32"))]
fn export(s: &mut Session, p: &J) -> Result<J> {
let dir = strp(p, "dir").ok_or_else(|| bad("file.export", "`dir` is required"))?;
let (gi, ext, pattern, depth) = export_params(s, p)?;
let files = export_outputs(s, gi, &ext, &pattern, depth)?;
let (gi, ext, pattern, depth, size) = export_params(s, p)?;
let files = export_outputs(s, gi, &ext, &pattern, depth, size)?;
std::fs::create_dir_all(dir).map_err(|e| bad("file.export", format!("{dir}: {e}")))?;
let mut written = Vec::new();
for f in files {
+1 -1
View File
@@ -49,7 +49,7 @@ pub fn session(s: &Session, graph: Option<usize>) -> J {
})
});
json!({
"package": {"name": s.pkg.name, "path": s.path, "modified": s.modified, "resources": s.pkg.resources.iter().map(|r| json!({"name": r.name, "bytes": r.bytes.len()})).collect::<Vec<_>>()},
"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<_>>(),
"openGraph": s.graph,
"graph": graph_json,
+9 -1
View File
@@ -17,9 +17,10 @@ pub mod node_cmds;
pub mod samples;
pub mod session;
pub mod view_cmds;
pub mod wire_cmds;
pub use commands::{CommandSpec, command_specs, execute, find};
pub use session::{CameraPrefs, Clip, Session, View2d, View3d};
pub use session::{CameraPrefs, Clip, Session, View2d, View3d, WARNING_PREFIX};
pub use materialcraft_core as core;
pub use materialcraft_eval as eval;
@@ -48,6 +49,13 @@ pub type Result<T> = std::result::Result<T, EngineError>;
/// Version string shown in About, `--version` and window titles.
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
/// A 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)
}
/// A session on the built-in sample package (the brick wall).
pub fn sample_session() -> Session {
Session::new(samples::sample_package())
+34 -1
View File
@@ -36,6 +36,11 @@ pub struct View3d {
pub height_scale: f32,
pub show_axis: bool,
pub show_grid: bool,
/// See through the mesh where the material's alpha (opacity output, else base color alpha)
/// is below one.
pub transparency: bool,
/// Show the material's alpha channel on the mesh instead of the lit material.
pub alpha_view: bool,
}
impl Default for View3d {
@@ -53,6 +58,8 @@ impl Default for View3d {
height_scale: 0.012,
show_axis: false,
show_grid: false,
transparency: true,
alpha_view: false,
}
}
}
@@ -118,6 +125,9 @@ pub struct Clip {
pub connections: Vec<materialcraft_core::Connection>,
}
/// The prefix of warning lines in [`Session::log`].
pub const WARNING_PREFIX: &str = "Warning: ";
pub struct Session {
pub pkg: Package,
/// Where the package was opened from or last saved to.
@@ -133,6 +143,8 @@ pub struct Session {
pub camera: CameraPrefs,
pub modified: bool,
pub log: Vec<String>,
/// What the last opened SBS package held that MaterialCraft couldn't read; empty after a clean open.
pub load_warnings: Vec<String>,
pub clipboard: Option<Clip>,
/// The last cook of the open graph.
pub cooked: Cooked,
@@ -162,6 +174,7 @@ impl Session {
camera: CameraPrefs::default(),
modified: false,
log: Vec::new(),
load_warnings: Vec::new(),
clipboard: None,
cooked: Cooked::default(),
dirty: true,
@@ -313,7 +326,7 @@ impl Session {
&self.cooked
}
/// Cook graph `gi` at full size (exports), without touching the preview results.
/// Cook graph `gi` at full size, without touching the preview results.
pub fn cook_full(&self, gi: usize) -> Cooked {
let dec = self.resource_decoder();
let opts = Options::new(&dec);
@@ -362,6 +375,26 @@ impl Session {
Ok(())
}
/// Nodes of the open graph whose last cook failed, with the error, and how many placeholders for missing SBS nodes failed besides.
pub fn cook_failures(&self) -> (Vec<(NodeId, &str)>, usize) {
let mut failed = Vec::new();
let mut placeholders = 0;
for node in self.graph().map(|g| g.nodes.as_slice()).unwrap_or_default() {
let Some(error) = self.cooked.nodes.get(&node.id).and_then(|r| r.error.as_deref()) else { continue };
if node.def == materialcraft_core::MISSING_NODE {
placeholders += 1;
} else {
failed.push((node.id, error));
}
}
(failed, placeholders)
}
/// Log a warning, shown highlighted in the Console.
pub fn warn(&mut self, msg: impl Into<String>) {
self.log(format!("{WARNING_PREFIX}{}", msg.into()));
}
pub fn log(&mut self, msg: impl Into<String>) {
self.log.push(msg.into());
if self.log.len() > 500 {
+7 -1
View File
@@ -29,7 +29,7 @@ pub(crate) fn specs() -> Vec<CommandSpec> {
"3D view settings",
[],
None,
"{scene? (cube|cylinder|plane|sphere|material_ball|rounded_cube|torus), tiling?, yaw?, pitch?, distance?, target? ([x, y, z] orbit point in mesh radii from its center, within the pan limit preference), environment? (studio|sunset|overcast|night), envRotation?, exposure?, heightScale?, axis?, grid?}",
"{scene? (cube|cylinder|plane|sphere|material_ball|rounded_cube|torus), tiling?, yaw?, pitch?, distance?, target? ([x, y, z] orbit point in mesh radii from its center, within the pan limit preference), environment? (studio|sunset|overcast|night), envRotation?, exposure?, heightScale?, axis?, grid?, transparency? (see through where alpha < 1), alphaView? (show the alpha channel)}",
always,
view3d
),
@@ -144,6 +144,12 @@ fn view3d(s: &mut Session, p: &J) -> Result<J> {
if let Some(b) = boolp(p, "grid") {
v.show_grid = b;
}
if let Some(b) = boolp(p, "transparency") {
v.transparency = b;
}
if let Some(b) = boolp(p, "alphaView") {
v.alpha_view = b;
}
Ok(serde_json::to_value(&s.view3d).unwrap_or(J::Null))
}
+129
View File
@@ -0,0 +1,129 @@
//! Wire commands: edit wires (connections) of the open graph, each addressed by the input it
//! feeds (`to`, `toPort`): split a wire with a reroute dot so it can be repositioned, delete
//! several wires at once, and swap (reverse) where a set of wires come from.
use serde_json::{Value as J, json};
use materialcraft_core::{Connection, NodeId};
use crate::commands::{CommandSpec, bad, has_graph, point, strp, u64p};
use crate::{Result, Session, cmd};
pub(crate) fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"graph.wire.insertDot",
"Insert reroute dot",
[],
None,
"{to, toPort, at? [x, y] (graph point, default: midway)} splits the wire feeding to.toPort with a Dot node there, selected",
has_graph,
insert_dot
),
cmd!(
"graph.wire.delete",
"Delete links",
[],
None,
"{wires: [{to, toPort}, ...]} deletes the wires feeding those inputs, in one undo step",
has_graph,
delete
),
cmd!(
"graph.wire.swap",
"Swap links",
[],
None,
"{wires: [{to, toPort}, ...] (two or more)} reverses where the wires come from: sorted by target node and input order, the first wire's source goes to the last input and so on (two wires swap)",
has_graph,
swap
),
]
}
/// Most wires one command takes (a graph has far fewer inputs in practice).
const MAX_WIRES: usize = 4096;
/// The wires named by `wires: [{to, toPort}, ...]`, each existing and named once.
fn wires_param(s: &Session, id: &str, p: &J) -> Result<Vec<Connection>> {
let list = p.get("wires").and_then(J::as_array).ok_or_else(|| bad(id, "`wires` is a list of {to, toPort}"))?;
if list.len() > MAX_WIRES {
return Err(bad(id, format!("at most {MAX_WIRES} wires")));
}
let g = s.graph()?;
let mut out: Vec<Connection> = Vec::with_capacity(list.len());
for w in list {
let to = w.get("to").and_then(J::as_u64).map(NodeId).ok_or_else(|| bad(id, "each wire needs `to`"))?;
let port = w.get("toPort").and_then(J::as_str).ok_or_else(|| bad(id, "each wire needs `toPort`"))?;
let c = g.input_of(to, port).ok_or_else(|| bad(id, format!("no wire feeds `{port}` of node {}", to.0)))?;
if out.iter().any(|o| o.to == c.to && o.to_port == c.to_port) {
return Err(bad(id, format!("the wire into `{port}` of node {} is listed twice", to.0)));
}
out.push(c.clone());
}
Ok(out)
}
fn delete(s: &mut Session, p: &J) -> Result<J> {
let wires = wires_param(s, "graph.wire.delete", p)?;
if wires.is_empty() {
return Err(bad("graph.wire.delete", "no wire given"));
}
s.edit("Delete links", |s| {
let g = s.graph_mut()?;
for c in &wires {
g.disconnect(c.to, &c.to_port);
}
Ok(json!({"deleted": wires.len()}))
})
}
fn swap(s: &mut Session, p: &J) -> Result<J> {
const ID: &str = "graph.wire.swap";
let mut wires = wires_param(s, ID, p)?;
if wires.len() < 2 {
return Err(bad(ID, "select two or more wires to swap"));
}
// A stable order whatever order the wires were picked in: target node, then input order.
let order = |s: &Session, c: &Connection| (c.to.0, s.input_ports(c.to).iter().position(|p| *p == c.to_port).unwrap_or(usize::MAX));
wires.sort_by_key(|c| order(s, c));
let sources: Vec<(NodeId, String)> = wires.iter().rev().map(|c| (c.from, c.from_port.clone())).collect();
s.edit("Swap links", |s| {
let g = s.graph_mut()?;
// Unplug them all first, so no half-swapped state is mistaken for a cycle.
for c in &wires {
g.disconnect(c.to, &c.to_port);
}
for (c, (from, port)) in wires.iter().zip(&sources) {
g.connect(*from, port, c.to, &c.to_port).map_err(|_| bad(ID, format!("swapping would feed node {} into itself (a cycle)", c.to.0)))?;
}
Ok(json!({"swapped": wires.len()}))
})
}
fn insert_dot(s: &mut Session, p: &J) -> Result<J> {
const ID: &str = "graph.wire.insertDot";
let to = NodeId(u64p(p, "to").ok_or_else(|| bad(ID, "`to` is required"))?);
let to_port = strp(p, "toPort").ok_or_else(|| bad(ID, "`toPort` is required"))?.to_string();
let g = s.graph()?;
let c = g.input_of(to, &to_port).cloned().ok_or_else(|| bad(ID, format!("no wire feeds `{to_port}` of node {}", to.0)))?;
let at = match point(p, "at") {
Some(at) => at,
None => {
let (a, b) = (g.node(c.from)?.pos, g.node(to)?.pos);
[(a[0] + b[0]) * 0.5, (a[1] + b[1]) * 0.5]
}
};
// Hostile but finite coordinates stay within a sane canvas.
let at = at.map(|v| v.clamp(-1e7, 1e7));
s.edit("Insert reroute dot", |s| {
let id = s.graph_mut()?.add_node("dot", at);
let input = s.input_ports(id).into_iter().next().ok_or_else(|| bad(ID, "the dot has no input"))?;
let output = s.output_ports(id).into_iter().next().ok_or_else(|| bad(ID, "the dot has no output"))?;
let g = s.graph_mut()?;
g.connect(c.from, &c.from_port, id, &input)?;
g.connect(id, &output, to, &to_port)?;
s.selection = vec![id];
Ok(json!({"id": id.0}))
})
}
+253
View File
@@ -83,9 +83,164 @@ fn package_save_and_open_round_trip() {
let out = dir.join("tex");
let r = run(&mut s, "file.export", json!({"dir": out.to_str().unwrap(), "format": "png", "depth": 8}));
assert_eq!(r["files"].as_array().unwrap().len(), 6);
let small = dir.join("small");
run(&mut s, "file.export", json!({"dir": small.to_str().unwrap(), "format": "png", "depth": 8, "size": 64}));
let file = std::fs::read_dir(&small).unwrap().next().unwrap().unwrap().path();
let img = materialcraft_formats::decode(&std::fs::read(file).unwrap()).unwrap();
assert_eq!((img.w, img.h), (64, 64));
let _ = std::fs::remove_dir_all(&dir);
}
/// `file.export` `size` is the larger side in pixels; 0 means the graph's size and the proportions are kept.
#[test]
fn export_size_keeps_proportions_and_clamps() {
let mut s = sample_session();
s.pkg.graphs[0].size = [7, 6];
let dims = |s: &Session, size: Value| {
let (gi, ext, pattern, depth, size) = materialcraft_engine::file_cmds::export_params(s, &json!({"size": size})).unwrap();
let files = materialcraft_engine::file_cmds::export_outputs(s, gi, &ext, &pattern, depth, size).unwrap();
files.iter().map(|f| materialcraft_formats::decode(&f.bytes).unwrap()).map(|i| (i.w, i.h)).collect::<Vec<_>>()
};
for size in [json!(0), json!(null)] {
assert!(dims(&s, size).iter().all(|d| *d == (128, 64)));
}
assert!(dims(&s, json!(32)).iter().all(|d| *d == (32, 16)));
let parsed = |size: Value| materialcraft_engine::file_cmds::export_params(&s, &json!({"size": size})).unwrap().4;
assert_eq!(parsed(json!(0)), None);
assert_eq!(parsed(json!(u64::MAX)), Some(u32::MAX));
s.pkg.graphs[0].size = [u32::MAX, u32::MAX];
assert!(dims(&s, json!(32)).iter().all(|d| *d == (32, 32)));
}
/// A scratch folder for one test, removed when dropped.
struct TempDir(std::path::PathBuf);
impl TempDir {
fn new(name: &str) -> TempDir {
let dir = std::env::temp_dir().join(format!("mc-{name}-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
TempDir(dir)
}
fn file(&self, name: &str) -> String {
self.0.join(name).to_str().unwrap().to_string()
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
/// A path without a package extension saves as `.sbs` and opens back exactly; `.mcraft` still saves and opens.
#[test]
fn sbs_is_the_default_save_format_and_mcraft_still_works() {
let dir = TempDir::new("sbs-default");
let mut s = sample_session();
let before = s.pkg.clone();
let sbs = run(&mut s, "file.save", json!({"path": dir.file("bricks")}))["path"].as_str().unwrap().to_string();
assert!(sbs.ends_with("bricks.sbs"), "{sbs}");
assert!(std::fs::read(&sbs).unwrap().starts_with(b"<?xml"));
run(&mut s, "file.newPackage", json!({}));
let opened = run(&mut s, "file.open", json!({"path": sbs}));
assert_eq!(opened["warnings"], json!([]));
assert_eq!(s.pkg.graphs, before.graphs);
assert_eq!(s.pkg.resources, before.resources);
assert_eq!(run(&mut s, "file.save", json!({}))["path"], json!(sbs));
let mcraft = dir.file("bricks.mcraft");
run(&mut s, "file.save", json!({"path": mcraft}));
assert!(std::fs::read(&mcraft).unwrap().starts_with(b"PK"));
run(&mut s, "file.newPackage", json!({}));
run(&mut s, "file.open", json!({"path": mcraft}));
assert_eq!(s.pkg.graphs, before.graphs);
assert_eq!(run(&mut s, "file.save", json!({}))["path"], json!(mcraft));
assert!(std::fs::read(&mcraft).unwrap().starts_with(b"PK"), "an opened .mcraft stays .mcraft");
}
/// Saving an SBS file another program wrote must not overwrite it: MaterialCraft can't write back what it couldn't read.
#[test]
fn saving_an_sbs_file_from_another_program_needs_a_new_name() {
let dir = TempDir::new("sbs-theirs");
let theirs = dir.file("theirs.sbs");
let xml = r#"<?xml version="1.0"?><package><content><graph><identifier v="G"/><compNodes><compNode><uid v="1"/><compImplementation><compFilter><filter v="curve"/><parameters><parameter><name v="curveluminance"/><paramValue><constantValueString v="POINTS"/></paramValue></parameter></parameters></compFilter></compImplementation></compNode></compNodes></graph><function><identifier v="their_function"/></function></content></package>"#;
std::fs::write(&theirs, xml).unwrap();
let mut s = sample_session();
let opened = run(&mut s, "file.open", json!({"path": theirs}));
assert_eq!(opened["path"], json!(null));
assert!(execute(&mut s, "file.save", &json!({})).is_err());
assert_eq!(std::fs::read_to_string(&theirs).unwrap(), xml, "the original is untouched");
// Saved under a new name it becomes a MaterialCraft file, which saves in place from then on
let mine = run(&mut s, "file.save", json!({"path": dir.file("mine.sbs")}))["path"].as_str().unwrap().to_string();
run(&mut s, "file.open", json!({"path": mine}));
assert_eq!(run(&mut s, "file.save", json!({}))["path"], json!(mine));
}
#[test]
fn a_broken_sbs_file_reports_an_sbs_error_and_a_renamed_mcraft_opens() {
let dir = TempDir::new("sbs-broken");
let broken = dir.file("broken.sbs");
std::fs::write(&broken, b"\xff\xfe<\x00p\x00").unwrap();
let mut s = sample_session();
let error = execute(&mut s, "file.open", &json!({"path": broken})).unwrap_err().to_string();
assert!(error.contains("SBS"), "{error}");
let renamed = dir.file("renamed.sbs");
std::fs::write(&renamed, materialcraft_engine::file_cmds::save_bytes_as(&s, materialcraft_engine::file_cmds::PackageFormat::Mcraft).unwrap()).unwrap();
run(&mut s, "file.open", json!({"path": renamed}));
}
/// An SBS file full of nodes MaterialCraft lacks opens: gaps are warnings, placeholders cook to an error, commands still work.
#[test]
fn an_sbs_file_with_missing_nodes_opens_softly() {
let sample = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/sbs/all_nodes.sbs");
let mut s = sample_session();
s.preview_size = Some(32);
let opened = run(&mut s, "file.open", json!({"path": sample.to_str().unwrap()}));
let warnings = opened["warnings"].as_array().unwrap();
assert!(warnings.len() > 100, "{} warnings", warnings.len());
assert!(warnings.iter().any(|w| w.as_str().unwrap().contains("missing node")));
assert!(s.log.iter().filter(|l| l.starts_with(materialcraft_engine::WARNING_PREFIX)).count() > 100);
let inspect = run(&mut s, "session.inspect", json!({}));
assert_eq!(inspect["package"]["warnings"].as_array().map(Vec::len), Some(warnings.len()));
assert!(s.pkg.resources.iter().any(|r| r.name == "Untitled_Bitmap" && !r.bytes.is_empty()), "the bitmap next to the package loads");
s.cook();
let graph = s.graph().unwrap();
let placeholder = graph.nodes.iter().find(|n| n.def == materialcraft_engine::core::MISSING_NODE).unwrap().id;
let mapped = graph.nodes.iter().find(|n| n.def == "perlin_noise").unwrap().id;
assert!(s.cooked.nodes[&placeholder].error.as_deref().unwrap_or("").contains("not in MaterialCraft's library"));
assert!(s.cooked.nodes[&mapped].error.is_none());
let (failed, placeholders) = s.cook_failures();
assert!(placeholders > 300 && failed.len() < 10, "{} failed, {placeholders} placeholders", failed.len());
// Commands on a placeholder are errors or no-ops, never panics
s.selection = vec![placeholder];
for (id, params) in [
("graph.node.param", json!({"id": placeholder.0, "param": "scale", "value": 2})),
("edit.copy", json!({})),
("edit.paste", json!({})),
("edit.duplicate", json!({})),
("graph.node.delete", json!({"ids": [placeholder.0]})),
("edit.undo", json!({})),
] {
let _ = execute(&mut s, id, &params);
}
for spec in command_specs().iter().filter(|spec| !spec.id.starts_with("file.")) {
let _ = execute(&mut s, spec.id, &json!({}));
}
s.cook();
run(&mut s, "file.newPackage", json!({}));
assert!(s.load_warnings.is_empty(), "a new package clears the warnings");
}
/// Every command, run with empty and hostile params, returns Ok or Err but never panics.
#[test]
fn panic_hunt() {
@@ -187,3 +342,101 @@ fn camera_prefs_bound_the_pan_and_survive_hostile_values() {
assert_eq!(s.camera, CameraPrefs::default());
assert_eq!(CameraPrefs { pan_limit: f32::INFINITY, pan_speed: 2.0 }.sanitized().pan_speed, 2.0);
}
#[test]
fn a_wire_splits_with_a_reroute_dot_and_deletes() {
let mut s = sample_session();
run(&mut s, "file.new", json!({"template": "empty"}));
let a = run(&mut s, "graph.node.add", json!({"def": "clouds_1", "at": [0, 0]}))["id"].as_u64().unwrap();
let b = run(&mut s, "graph.node.add", json!({"def": "levels", "at": [400, 0]}))["id"].as_u64().unwrap();
run(&mut s, "graph.connect", json!({"from": a, "to": b}));
let dot = run(&mut s, "graph.wire.insertDot", json!({"to": b, "toPort": "input", "at": [200, 80]}))["id"].as_u64().unwrap();
let g = s.graph().unwrap();
let d = materialcraft_engine::core::NodeId(dot);
assert_eq!(g.node(d).unwrap().def, "dot");
assert_eq!(g.node(d).unwrap().pos, [200.0, 80.0]);
assert_eq!(g.connections.len(), 2);
assert_eq!(g.input_of(d, "input").unwrap().from.0, a);
assert_eq!(g.input_of(materialcraft_engine::core::NodeId(b), "input").unwrap().from.0, dot);
assert_eq!(s.selection, vec![d]);
// The material still cooks through the dot.
s.cook();
assert!(s.cooked.nodes.values().all(|r| r.error.is_none()));
// One undo step restores the straight wire.
run(&mut s, "edit.undo", json!({}));
assert_eq!(s.graph().unwrap().nodes.len(), 2);
assert_eq!(s.graph().unwrap().input_of(materialcraft_engine::core::NodeId(b), "input").unwrap().from.0, a);
// No wire there: an error, nothing changes.
assert!(execute(&mut s, "graph.wire.insertDot", &json!({"to": a, "toPort": "input"})).is_err());
// Deleting the wire.
run(&mut s, "graph.disconnect", json!({"to": b, "toPort": "input"}));
assert!(s.graph().unwrap().connections.is_empty());
}
#[test]
fn every_template_is_opaque_in_the_3d_view() {
// The 3D view sees through a base color whose alpha is below one: the templates must not.
let mut s = sample_session();
s.preview_size = Some(64);
for (id, _) in materialcraft_engine::samples::TEMPLATES {
run(&mut s, "file.new", json!({"template": id, "size": 64}));
s.cook();
for (usage, img) in s.material_maps() {
if usage == "baseColor" && !img.is_gray() {
let min = img.data.chunks(4).map(|p| p[3]).fold(f32::INFINITY, f32::min);
assert!(min >= 0.999, "{id}: base color alpha goes down to {min}");
}
}
}
}
#[test]
fn selected_wires_swap_their_sources_and_delete_together() {
use materialcraft_engine::core::NodeId;
let mut s = sample_session();
run(&mut s, "file.new", json!({"template": "empty"}));
let a = run(&mut s, "graph.node.add", json!({"def": "clouds_1", "at": [0, 0]}))["id"].as_u64().unwrap();
let b = run(&mut s, "graph.node.add", json!({"def": "perlin_noise", "at": [0, 200]}))["id"].as_u64().unwrap();
let m = run(&mut s, "graph.node.add", json!({"def": "checker", "at": [0, 400]}))["id"].as_u64().unwrap();
let blend = run(&mut s, "graph.node.add", json!({"def": "blend", "at": [300, 100]}))["id"].as_u64().unwrap();
run(&mut s, "graph.connect", json!({"from": a, "to": blend, "toPort": "foreground"}));
run(&mut s, "graph.connect", json!({"from": b, "to": blend, "toPort": "background"}));
run(&mut s, "graph.connect", json!({"from": m, "to": blend, "toPort": "mask"}));
let src = |s: &Session, port: &str| s.graph().unwrap().input_of(NodeId(blend), port).unwrap().from.0;
let fg_bg = json!({"wires": [{"to": blend, "toPort": "background"}, {"to": blend, "toPort": "foreground"}]});
// Two wires swap, whatever order they are listed in; the other input is left alone.
run(&mut s, "graph.wire.swap", fg_bg.clone());
assert_eq!((src(&s, "foreground"), src(&s, "background"), src(&s, "mask")), (b, a, m));
run(&mut s, "graph.wire.swap", fg_bg.clone());
assert_eq!((src(&s, "foreground"), src(&s, "background")), (a, b));
// Three wires reverse in input order: foreground <-> mask, background stays.
let all = json!({"wires": [{"to": blend, "toPort": "foreground"}, {"to": blend, "toPort": "background"}, {"to": blend, "toPort": "mask"}]});
run(&mut s, "graph.wire.swap", all.clone());
assert_eq!((src(&s, "foreground"), src(&s, "background"), src(&s, "mask")), (m, b, a));
// One undo step each.
run(&mut s, "edit.undo", json!({}));
assert_eq!((src(&s, "foreground"), src(&s, "background"), src(&s, "mask")), (a, b, m));
// Bad requests change nothing.
for bad in [
json!({}),
json!({"wires": [{"to": blend, "toPort": "foreground"}]}),
json!({"wires": [{"to": blend, "toPort": "foreground"}, {"to": blend, "toPort": "foreground"}]}),
json!({"wires": [{"to": blend, "toPort": "foreground"}, {"to": a, "toPort": "input"}]}),
] {
assert!(execute(&mut s, "graph.wire.swap", &bad).is_err(), "{bad}");
}
assert_eq!(src(&s, "foreground"), a);
// A swap that would make a cycle is refused and rolled back: blend -> levels, then swap the
// wire into levels with the wire into blend's foreground.
let lv = run(&mut s, "graph.node.add", json!({"def": "levels", "at": [600, 100]}))["id"].as_u64().unwrap();
run(&mut s, "graph.connect", json!({"from": blend, "to": lv}));
let cyc = json!({"wires": [{"to": blend, "toPort": "foreground"}, {"to": lv, "toPort": "input"}]});
assert!(execute(&mut s, "graph.wire.swap", &cyc).is_err());
assert_eq!(src(&s, "foreground"), a);
assert_eq!(s.graph().unwrap().connections.len(), 4);
// Deleting several wires is one step.
run(&mut s, "graph.wire.delete", all);
assert_eq!(s.graph().unwrap().connections.len(), 1);
run(&mut s, "edit.undo", json!({}));
assert_eq!(s.graph().unwrap().connections.len(), 4);
}
+9
View File
@@ -53,6 +53,12 @@ pub fn ports(pkg: &Package, node: &Node) -> (Vec<Port>, Vec<Port>) {
};
return (io("input"), io("output"));
}
if node.def == materialcraft_core::MISSING_NODE {
let (ins, outs) = materialcraft_core::missing_ports(node);
let ins = ins.into_iter().map(|id| Port { label: id.clone(), id, kind: PortKind::Any }).collect();
let outs = outs.into_iter().map(|(id, gray)| Port { label: id.clone(), id, kind: if gray { PortKind::Gray } else { PortKind::Color } }).collect();
return (ins, outs);
}
let Some(def) = find(&node.def) else { return (Vec::new(), Vec::new()) };
let conv = |p: &materialcraft_nodes::PortDef| Port { id: p.id.into(), label: p.label.into(), kind: p.kind };
(def.inputs.iter().map(conv).collect(), def.outputs.iter().map(conv).collect())
@@ -374,6 +380,9 @@ fn cook_node(pkg: &Package, graph: &Graph, node: &Node, done: &Cooked, vars: &BT
} else if let Some(img) = input_img {
let img = img.resize(w, h, tile);
Ok(vec![if node.def == "input_grayscale" { img.to_gray() } else { img }])
} else if node.def == materialcraft_core::MISSING_NODE {
let name = if node.label.is_empty() { "this node" } else { node.label.as_str() };
Err(format!("`{name}` is not in MaterialCraft's library yet: kept as a placeholder from the SBS file"))
} else if node.def == "graph_instance" {
cook_instance(pkg, node, &in_ports, &out_ports, &inputs, &params, (w, h), opts, cache)
} else if let Some(d) = def {
+5 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "materialcraft-formats"
description = "MaterialCraft file formats: .mcraft packages, bitmap import, texture export"
description = "MaterialCraft file formats: .sbs and .mcraft packages, bitmap import, texture export"
version.workspace = true
edition.workspace = true
license.workspace = true
@@ -12,6 +12,7 @@ workspace = true
materialcraft-core = { workspace = true }
materialcraft-image = { workspace = true }
materialcraft-geom = { workspace = true }
materialcraft-nodes = { workspace = true }
gltf = { workspace = true }
tobj = { workspace = true }
image = { workspace = true }
@@ -19,3 +20,6 @@ serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
zip = { workspace = true }
roxmltree = { workspace = true }
flate2 = { workspace = true }
base64 = { workspace = true }
+2 -1
View File
@@ -1,6 +1,6 @@
//! # materialcraft-formats
//!
//! File formats, L2: the native `.mcraft` package (a zip holding `package.json` and the embedded
//! File formats, L2: SBS packages (`.sbs`, the main project format, see [`sbs`]), the older native `.mcraft` package (a zip holding `package.json` and the embedded
//! `resources/`), bitmap decoding for Bitmap nodes, and texture export (PNG 8/16, JPEG, TGA,
//! TIFF 8/16, BMP, WEBP, EXR 32F, HDR) with the output naming pattern, and meshes for the 3D view
//! (OBJ, glTF/GLB), and portable materials (`.mcmat`, see [`material`]). Byte-based APIs work
@@ -10,6 +10,7 @@
pub mod material;
pub mod mesh;
pub mod sbs;
use std::io::{Cursor, Read, Write};
use std::sync::Arc;
File diff suppressed because it is too large. Load diff
+31
View File
@@ -425,6 +425,8 @@ fn hsl(ctx: &Ctx) -> CookResult {
pub fn levels_fn(v: f32, in_low: f32, in_mid: f32, in_high: f32, out_low: f32, out_high: f32) -> f32 {
let span = in_high - in_low;
let t = if span.abs() < 1e-6 { if v >= in_high { 1.0 } else { 0.0 } } else { ((v - in_low) / span).clamp(0.0, 1.0) };
// NaN (from an input or a hostile parameter) would otherwise spread through the graph.
let t = if t.is_finite() { t } else { 0.0 };
let mid = in_mid.clamp(0.001, 0.999);
let g = 0.5f32.ln() / mid.ln();
out_low + t.powf(g) * (out_high - out_low)
@@ -522,3 +524,32 @@ pub fn output_kind(def: &NodeDef, port: usize, inputs: &[Option<Image>]) -> Kind
_ => inputs.iter().flatten().next().map_or(Kind::Gray, |i| i.kind),
}
}
#[cfg(test)]
mod levels_tests {
use super::levels_fn;
#[test]
fn levels_remaps_the_input_range_midtones_and_output_range() {
let close = |a: f32, b: f32| (a - b).abs() < 1e-5;
// Identity by default.
for v in [0.0, 0.25, 0.5, 1.0] {
assert!(close(levels_fn(v, 0.0, 0.5, 1.0, 0.0, 1.0), v));
}
// The input range stretches and clips.
assert!(close(levels_fn(0.4, 0.2, 0.5, 0.6, 0.0, 1.0), 0.5));
assert!(close(levels_fn(0.1, 0.2, 0.5, 0.6, 0.0, 1.0), 0.0));
assert!(close(levels_fn(0.9, 0.2, 0.5, 0.6, 0.0, 1.0), 1.0));
// Mid is relative to the input range: the value there becomes 0.5.
assert!(close(levels_fn(0.25, 0.0, 0.25, 1.0, 0.0, 1.0), 0.5));
assert!(close(levels_fn(0.3, 0.2, 0.25, 0.6, 0.0, 1.0), 0.5));
// The output range, inverted when low > high.
assert!(close(levels_fn(0.5, 0.0, 0.5, 1.0, 0.2, 0.6), 0.4));
assert!(close(levels_fn(0.0, 0.0, 0.5, 1.0, 1.0, 0.0), 1.0));
// A collapsed input range is a threshold; NaN never escapes.
assert_eq!(levels_fn(0.49, 0.5, 0.5, 0.5, 0.0, 1.0), 0.0);
assert_eq!(levels_fn(0.5, 0.5, 0.5, 0.5, 0.0, 1.0), 1.0);
assert!(levels_fn(f32::NAN, 0.0, 0.5, 1.0, 0.0, 1.0).is_finite());
assert!(levels_fn(0.5, f32::NAN, 0.5, f32::NAN, 0.0, 1.0).is_finite());
}
}
+98 -16
View File
@@ -182,6 +182,11 @@ pub struct Settings {
pub ao_rays: u32,
/// Strength of a shadow-casting key light from the camera's upper left (0 = off).
pub key_light: f32,
/// See through the surface where the material's alpha (the opacity output, else the base
/// color's alpha channel) is below one: what lies behind, back faces included, shows through.
pub transparency: bool,
/// Show the material's alpha channel on the mesh, unlit (white = opaque, black = clear).
pub alpha_view: bool,
}
impl Default for Settings {
@@ -199,6 +204,8 @@ impl Default for Settings {
supersample: 1,
ao_rays: 0,
key_light: 0.0,
transparency: true,
alpha_view: false,
}
}
}
@@ -257,10 +264,23 @@ fn rotate_y(v: Vec3, deg: f32) -> Vec3 {
Vec3::new(v.x * c + v.z * s, v.y, -v.x * s + v.z * c)
}
/// The material's alpha at `uv`: the opacity output, else the base color's alpha channel, else
/// opaque.
fn alpha(maps: &Maps, uv: Vec2) -> f32 {
let a = match (&maps.opacity, &maps.base_color) {
(Some(o), _) => o.sample_gray(uv.x, uv.y, true),
(None, Some(b)) if !b.is_gray() => b.sample(uv.x, uv.y, true)[3],
_ => 1.0,
};
if a.is_finite() { a.clamp(0.0, 1.0) } else { 1.0 }
}
/// Transparent surfaces a ray passes through before it gives up (what is left shows the
/// background).
const MAX_LAYERS: usize = 8;
/// Per-pixel inputs of [`shade`] beyond the camera ray.
struct Px {
/// Backdrop color (seen through transparent areas).
bg: Vec3,
/// Direction toward the key light.
key: Vec3,
/// Random rotation of the ambient occlusion ray pattern.
@@ -301,8 +321,16 @@ fn direct(n: Vec3, v: Vec3, l: Vec3, base: Vec3, f0: Vec3, metal: f32, rough: f3
(diff + spec) * ndl
}
/// Shade one camera ray; `None` = missed the mesh.
fn shade(scene: &Scene, maps: &Maps, light: &Lighting, s: &Settings, origin: Vec3, dir: Vec3, px: &Px) -> Option<Vec3> {
/// A shaded surface point: linear color (or the alpha value in [`Settings::alpha_view`]), its
/// alpha and the ray distance.
struct Shaded {
color: Vec3,
alpha: f32,
t: f32,
}
/// Shade the first surface along one ray; `None` = missed the mesh.
fn shade(scene: &Scene, maps: &Maps, light: &Lighting, s: &Settings, origin: Vec3, dir: Vec3, px: &Px) -> Option<Shaded> {
let hit = scene.bvh.closest(origin, dir, f32::MAX)?;
let m = &scene.mesh;
let [i0, i1, i2] = m.tri(hit.tri as usize)?;
@@ -310,6 +338,8 @@ fn shade(scene: &Scene, maps: &Maps, light: &Lighting, s: &Settings, origin: Vec
let w0 = 1.0 - w1 - w2;
let lerp3 = |a: Vec3, b: Vec3, c: Vec3| a * w0 + b * w1 + c * w2;
let nrm = lerp3(*m.normals.get(i0)?, *m.normals.get(i1)?, *m.normals.get(i2)?).normalize_or_zero();
// A back face (seen through a transparent front, or under an open mesh) faces the viewer.
let nrm = if nrm.dot(dir) > 0.0 { -nrm } else { nrm };
let (t0, t1, t2) = (*m.tangents.get(i0)?, *m.tangents.get(i1)?, *m.tangents.get(i2)?);
let tan = (t0.truncate() * w0 + t1.truncate() * w1 + t2.truncate() * w2).normalize_or_zero();
let sign = if t0.w < 0.0 { -1.0 } else { 1.0 };
@@ -346,6 +376,10 @@ fn shade(scene: &Scene, maps: &Maps, light: &Lighting, s: &Settings, origin: Vec
}
uv = cur;
}
let a = alpha(maps, uv);
if s.alpha_view {
return Some(Shaded { color: Vec3::splat(a), alpha: 1.0, t: hit.t });
}
let base = tex(&maps.base_color, uv).map_or(Vec3::splat(0.5), |c| Vec3::new(c[0], c[1], c[2]));
let rough = tex_gray(&maps.roughness, uv, 0.5).clamp(0.02, 1.0);
let metal = tex_gray(&maps.metallic, uv, 0.0).clamp(0.0, 1.0);
@@ -385,11 +419,27 @@ fn shade(scene: &Scene, maps: &Maps, light: &Lighting, s: &Settings, origin: Vec
if let Some(e) = tex(&maps.emissive, uv) {
c += Vec3::new(e[0], e[1], e[2]);
}
if let Some(o) = &maps.opacity {
let a = o.sample_gray(uv.x, uv.y, true).clamp(0.0, 1.0);
c = c * a + px.bg * (1.0 - a);
Some(Shaded { color: c, alpha: if s.transparency { a } else { 1.0 }, t: hit.t })
}
/// Follow one camera ray through up to [`MAX_LAYERS`] transparent surfaces, compositing front to
/// back (`miss` is what shows behind the mesh). Shaded colors are scaled by the exposure `k`.
#[allow(clippy::too_many_arguments)]
fn trace(scene: &Scene, maps: &Maps, light: &Lighting, s: &Settings, origin: Vec3, dir: Vec3, px: &Px, k: f32, miss: Vec3) -> Vec3 {
let mut acc = Vec3::ZERO;
let mut through = 1.0;
let mut o = origin;
let step = scene.radius * 1e-4;
for _ in 0..MAX_LAYERS {
let Some(h) = shade(scene, maps, light, s, o, dir, px) else { return acc + miss * through };
acc += h.color * k * h.alpha * through;
through *= 1.0 - h.alpha;
if through < 1e-3 {
return acc;
}
o += dir * (h.t + step);
}
Some(c)
acc + miss * through
}
/// The studio backdrop at screen position `p` (−1..1): a soft vignette (linear).
@@ -440,18 +490,27 @@ pub fn render_cancellable(scene: &Scene, maps: &Maps, light: &Lighting, s: &Sett
let py = 1.0 - (y as f32 + (sy as f32 + 0.5) / ss as f32) / h as f32 * 2.0;
let ray = cam.ray(Vec2::new(px, py), aspect);
let bg = backdrop(Vec2::new(px, py));
let p = Px { bg, key, jitter: jitter(x as u32 * ss + sx, y as u32 * ss + sy) };
acc += match shade(scene, maps, light, s, ray.origin, ray.dir, &p) {
Some(c) => c * k,
None => match (s.show_env, bg_env) {
(true, Some(e)) => e.sample(rotate_y(ray.dir, -s.env_rotation)) * k,
_ => bg,
},
let p = Px { key, jitter: jitter(x as u32 * ss + sx, y as u32 * ss + sy) };
let miss = match (s.show_env, bg_env) {
(true, Some(e)) => e.sample(rotate_y(ray.dir, -s.env_rotation)) * k,
_ => bg,
};
acc += if s.alpha_view {
// Display values: the alpha as is, the background tone mapped.
match shade(scene, maps, light, s, ray.origin, ray.dir, &p) {
Some(h) => h.color,
None => miss.map(|v| linear_to_srgb(aces(v))),
}
} else {
trace(scene, maps, light, s, ray.origin, ray.dir, &p, k, miss)
};
}
}
let c = acc / (ss * ss) as f32;
let q = |v: f32| (linear_to_srgb(aces(v)) * 255.0 + 0.5) as u8;
let q = |v: f32| {
let d = if s.alpha_view { v } else { linear_to_srgb(aces(v)) };
(d.clamp(0.0, 1.0) * 255.0 + 0.5) as u8
};
if let Some(px) = row.get_mut(x * 4..x * 4 + 4) {
px.copy_from_slice(&[q(c.x), q(c.y), q(c.z), 255]);
}
@@ -484,6 +543,29 @@ mod tests {
}
}
#[test]
fn alpha_shows_what_lies_behind_and_the_alpha_view_shows_the_channel() {
let (scene, light) = (Scene::builtin("sphere"), Lighting::new("studio"));
let red = |a: f32| Maps { base_color: Some(Image::filled(16, 16, Kind::Color, [0.8, 0.1, 0.1, a])), ..Maps::default() };
let c = ((24 * 64 + 32) * 4) as usize;
let s = Settings::default();
let opaque = render(&scene, &red(1.0), &light, &s, 64, 48);
let clear = render(&scene, &red(0.0), &light, &s, 64, 48);
assert!(opaque[c] > opaque[c + 1] + 40, "opaque center is red: {:?}", &opaque[c..c + 3]);
// Fully clear: the backdrop shows through both the front and the back of the sphere.
let bg = backdrop(Vec2::new(32.5 / 64.0 * 2.0 - 1.0, 1.0 - 24.5 / 48.0 * 2.0));
let bg = (linear_to_srgb(aces(bg.x)) * 255.0 + 0.5) as u8;
assert!(clear[c..c + 3].iter().all(|v| v.abs_diff(bg) <= 1), "clear {:?} vs backdrop {bg}", &clear[c..c + 3]);
// Transparency off: alpha is ignored.
assert_eq!(render(&scene, &red(0.0), &light, &Settings { transparency: false, ..s }, 64, 48), opaque);
// An opacity output wins over the base color's alpha.
let half = Maps { opacity: Some(Image::filled(16, 16, Kind::Gray, [0.5; 4])), ..red(1.0) };
let px = render(&scene, &half, &light, &Settings { alpha_view: true, ..s }, 64, 48);
assert!(px[c].abs_diff(128) <= 1 && px[c] == px[c + 1], "alpha view: {:?}", &px[c..c + 3]);
let px = render(&scene, &red(1.0), &light, &Settings { alpha_view: true, ..s }, 64, 48);
assert_eq!(&px[c..c + 3], &[255, 255, 255]);
}
#[test]
fn a_cancelled_render_gives_up_and_an_uncancelled_one_matches_render() {
let (scene, light, maps, s) = (Scene::builtin("sphere"), Lighting::new("studio"), Maps::default(), Settings::default());
+2 -1
View File
@@ -23,6 +23,7 @@ image = { workspace = true }
zip = { workspace = true }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
sys-locale = "0.3"
rfd = { workspace = true }
# Floating panels open as OS windows.
craft-ui = { workspace = true, features = ["native-windows"] }
@@ -33,7 +34,7 @@ rfd = { workspace = true }
wasm-bindgen = "0.2"
wasm-bindgen-futures = "0.4"
js-sys = "0.3"
web-sys = { version = "0.3", features = ["Window", "Document", "HtmlElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "CssStyleDeclaration"] }
web-sys = { version = "0.3", features = ["Window", "Document", "HtmlElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "CssStyleDeclaration", "Navigator"] }
# winit needs a window system on Linux, so the crate's own tests build with X11.
[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies]
+7 -1
View File
@@ -55,7 +55,7 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
open = Some(i);
}
resp.context_menu(|ui| {
for (label, a) in [("Open", "open"), ("Duplicate", "duplicate"), ("Delete", "delete")] {
for (label, a) in [("Open", "open"), ("Export outputs...", "export"), ("Duplicate", "duplicate"), ("Delete", "delete")] {
if ui.button(tr(label)).clicked() {
action = Some((a, i));
ui.close();
@@ -70,6 +70,12 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
Some(("open", i)) => {
app.run("graph.open", json!({"graph": i}));
}
Some(("export", i)) => {
// The export window works on the open graph.
if app.run("graph.open", json!({"graph": i})).is_some() {
app.ui.windows.export = true;
}
}
Some(("duplicate", i)) => {
app.run("graph.duplicate", json!({"graph": i}));
}
+92
View File
@@ -0,0 +1,92 @@
//! Arabic fallback fonts for the UI. egui's default fonts have no Arabic glyphs, so translated
//! UIs need fallback fonts from the operating system.
//!
//! Windows: Segoe UI, Tahoma, Arial
//! macOS: SF Arabic, Geeza Pro, Arial Unicode
//! Linux: Noto Sans Arabic, DejaVu Sans
use std::sync::Arc;
use egui::{FontData, FontFamily};
/// Candidate system font files: (path, face index in a collection).
#[cfg(not(target_arch = "wasm32"))]
fn system_files() -> Vec<(std::path::PathBuf, u32)> {
use std::path::PathBuf;
let mut v: Vec<(PathBuf, u32)> = Vec::new();
if cfg!(windows) {
let fonts = PathBuf::from(std::env::var("WINDIR").unwrap_or_else(|_| "C:\\Windows".into())).join("Fonts");
let files: &[&str] = &["segoeui.ttf", "tahoma.ttf", "arial.ttf"];
v.extend(files.iter().map(|f| (fonts.join(f), 0)));
} else if cfg!(target_os = "macos") {
let files: &[&str] = &["/System/Library/Fonts/SFArabic.ttf", "/System/Library/Fonts/Supplemental/GeezaPro.ttc"];
v.extend(files.iter().map(|f| (PathBuf::from(f), 0)));
v.push((PathBuf::from("/System/Library/Fonts/Supplemental/Arial Unicode.ttf"), 0));
} else {
for f in [
"/usr/share/fonts/truetype/noto/NotoSansArabic-Regular.ttf",
"/usr/share/fonts/noto/NotoSansArabic-Regular.ttf",
"/usr/share/fonts/google-noto/NotoSansArabic-Regular.ttf",
"/usr/local/share/fonts/noto/NotoSansArabic-Regular.ttf",
"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
"/usr/share/fonts/dejavu/DejaVuSans.ttf",
"/usr/local/share/fonts/dejavu/DejaVuSans.ttf",
] {
v.push((PathBuf::from(f), 0));
}
}
v
}
/// Fallback fonts manager for the egui context.
#[derive(Default)]
pub struct UiFonts {
installed: bool,
data: Option<Arc<FontData>>,
}
impl UiFonts {
/// Update fallback fonts according to active language and whether the preferences dialog is open.
pub fn update(&mut self, ctx: &egui::Context, language: &str, preferences_open: bool) {
let want_arabic = language == "ar" || preferences_open;
if !want_arabic || self.installed {
return;
}
let Some(data) = self.load_arabic() else { return };
let mut defs = crate::theme::font_definitions();
let name = "script-Arab".to_string();
defs.font_data.insert(name.clone(), data);
defs.families.entry(FontFamily::Proportional).or_default().push(name.clone());
defs.families.entry(FontFamily::Monospace).or_default().push(name);
ctx.set_fonts(defs);
self.installed = true;
}
/// Whether an Arabic fallback font has been found and loaded.
pub fn covers_arabic(&self) -> bool {
self.data.is_some()
}
fn load_arabic(&mut self) -> Option<Arc<FontData>> {
if let Some(d) = &self.data {
return Some(d.clone());
}
#[cfg(not(target_arch = "wasm32"))]
for (path, index) in system_files() {
let Ok(meta) = std::fs::metadata(&path) else { continue };
if !meta.is_file() || meta.len() == 0 || meta.len() > (128 << 20) {
continue;
}
if let Ok(bytes) = std::fs::read(&path) {
let mut data = FontData::from_owned(bytes);
data.index = index;
let arc = Arc::new(data);
self.data = Some(arc.clone());
log::info!("UI font fallback for Arabic: {}", path.display());
return Some(arc);
}
}
log::warn!("no font found for Arabic text; system fonts may show boxes");
None
}
}
+311 -24
View File
@@ -6,8 +6,10 @@
//! it, drag the empty canvas to box-select (Ctrl adds), middle-drag or Alt+drag to pan, wheel to
//! zoom, click a node to show it in the 2D view (double-click a graph instance to open its graph),
//! Space, Tab or double-click the canvas for the node search, right-click for menus, drop library
//! items to add them. Every edit is an engine command; the gestures only draw previews until they
//! commit.
//! items to add them. Click a wire to select it (Shift or Ctrl+click adds more; Delete removes them, X swaps
//! where they come from), drag a wire to pull a reroute dot out of it, double-click a wire to drop
//! a dot there, right-click a wire for its menu. Every edit is an
//! engine command; the gestures only draw previews until they commit.
use egui::{Align2, Color32, CornerRadius, FontId, Pos2, Rect, Sense, Stroke, StrokeKind, Ui, Vec2, pos2, vec2};
use egui_phosphor::regular as icon;
@@ -33,14 +35,40 @@ pub struct LibraryDrag(pub String);
#[derive(Clone, Debug)]
enum Drag {
Nodes { delta: Vec2 },
Box { start: Pos2 },
Wire { from: (NodeId, String), detached: Option<(NodeId, String)> },
Nodes {
delta: Vec2,
},
Box {
start: Pos2,
},
Wire {
from: (NodeId, String),
detached: Option<(NodeId, String)>,
},
/// Pressed on a wire: a click selects it, a drag pulls a reroute dot out of it.
WirePress {
wire: WireRef,
start: Pos2,
},
Pan,
Frame { id: u64, delta: Vec2, resize: bool, nodes: Vec<NodeId> },
Comment { id: u64, delta: Vec2 },
Frame {
id: u64,
delta: Vec2,
resize: bool,
nodes: Vec<NodeId>,
},
Comment {
id: u64,
delta: Vec2,
},
}
/// A wire, named by the input it feeds: (node, input port).
pub type WireRef = (NodeId, String);
/// Pointer distance (points) within which a wire is hit.
const WIRE_HIT: f32 = 5.0;
/// The node search popup (Space or Tab).
#[derive(Clone, Debug)]
struct Search {
@@ -77,6 +105,12 @@ pub struct GraphView {
menu_at: Pos2,
/// The graph the camera last framed.
framed_graph: Option<usize>,
/// The selected wires, in the order they were picked (Delete removes them, X swaps them).
pub selected_wires: Vec<WireRef>,
/// The wire the context menu is for (right-clicked on a wire).
menu_wire: Option<WireRef>,
/// Wires on screen last frame: the wire and its bezier control points.
pub wires: Vec<(WireRef, [Pos2; 4])>,
}
impl Default for GraphView {
@@ -91,6 +125,9 @@ impl Default for GraphView {
view: Rect::NOTHING,
menu_at: Pos2::ZERO,
framed_graph: None,
selected_wires: Vec::new(),
menu_wire: None,
wires: Vec::new(),
}
}
}
@@ -170,10 +207,47 @@ fn port_pos(r: Rect, i: usize, n: usize, output: bool, dot: bool) -> Pos2 {
pos2(if output { r.right() } else { r.left() }, start + i as f32 * PORT_GAP)
}
fn bezier(p: &egui::Painter, a: Pos2, b: Pos2, stroke: Stroke) {
/// Control points of the wire from output `a` to input `b` (screen space).
fn bezier_points(a: Pos2, b: Pos2) -> [Pos2; 4] {
let dx = ((b.x - a.x).abs() * 0.5).max(30.0);
let shape = egui::epaint::CubicBezierShape::from_points_stroke([a, a + vec2(dx, 0.0), b - vec2(dx, 0.0), b], false, Color32::TRANSPARENT, stroke);
p.add(shape);
[a, a + vec2(dx, 0.0), b - vec2(dx, 0.0), b]
}
fn bezier(p: &egui::Painter, a: Pos2, b: Pos2, stroke: Stroke) {
p.add(egui::epaint::CubicBezierShape::from_points_stroke(bezier_points(a, b), false, Color32::TRANSPARENT, stroke));
}
/// The point at `t` (0..1) along a cubic bezier.
fn bezier_at(c: &[Pos2; 4], t: f32) -> Pos2 {
let u = 1.0 - t;
let w = [u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t];
pos2(c.iter().zip(w).map(|(p, w)| p.x * w).sum(), c.iter().zip(w).map(|(p, w)| p.y * w).sum())
}
/// Distance from `p` to a cubic bezier (sampled as a polyline).
fn bezier_distance(c: &[Pos2; 4], p: Pos2) -> f32 {
const N: usize = 32;
let mut best = f32::INFINITY;
let mut prev = c[0];
for i in 1..=N {
let q = bezier_at(c, i as f32 / N as f32);
let (seg, rel) = (q - prev, p - prev);
let t = if seg.length_sq() > 0.0 { (rel.dot(seg) / seg.length_sq()).clamp(0.0, 1.0) } else { 0.0 };
best = best.min((prev + seg * t).distance(p));
prev = q;
}
best
}
/// The wire nearest `p` within [`WIRE_HIT`] points.
fn wire_at(wires: &[(WireRef, [Pos2; 4])], p: Pos2) -> Option<&WireRef> {
wires
.iter()
.filter(|(_, c)| Rect::from_points(c).expand(WIRE_HIT).contains(p))
.map(|(w, c)| (w, bezier_distance(c, p)))
.filter(|(_, d)| *d <= WIRE_HIT)
.min_by(|a, b| a.1.total_cmp(&b.1))
.map(|(w, _)| w)
}
/// The graph panel: toolbar row and canvas.
@@ -334,6 +408,7 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) {
if app.ui.frame_all || app.graph.framed_graph != Some(app.session.graph) {
app.ui.frame_all = false;
app.graph.framed_graph = Some(app.session.graph);
app.graph.selected_wires.clear();
frame(app, rect, false);
}
let painter = ui.painter_at(rect);
@@ -462,6 +537,7 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) {
Some(Drag::Wire { detached: Some(d), .. }) => Some(d.clone()),
_ => None,
};
let mut wires: Vec<(WireRef, [Pos2; 4])> = Vec::with_capacity(g.connections.len());
for c in &g.connections {
if detached.as_ref().is_some_and(|(n, p)| *n == c.to && *p == c.to_port) {
continue;
@@ -469,11 +545,32 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) {
let a = laid.iter().find(|l| l.id == c.from).and_then(|l| l.outs.iter().find(|p| p.0 == c.from_port));
let b = laid.iter().find(|l| l.id == c.to).and_then(|l| l.ins.iter().find(|p| p.0 == c.to_port));
if let (Some(a), Some(b)) = (a, b) {
let hot = selection.contains(&c.from) || selection.contains(&c.to);
let col = if hot { tk.accent } else { Color32::from_gray(0xb4) };
bezier(&painter, cam.to_screen(a.3), cam.to_screen(b.3), Stroke::new((2.0 * cam.zoom).clamp(1.0, 3.0), col));
wires.push(((c.to, c.to_port.clone()), bezier_points(cam.to_screen(a.3), cam.to_screen(b.3))));
}
}
// Hover: not where a node card or a port sits on top of the wire.
let over_card = |p: Pos2| app.graph.rects.iter().any(|(_, r)| r.contains(p)) || nearest_port(&app.graph.ports, p, 9.0).is_some();
let wire_hover = match &app.graph.drag {
None => pointer.filter(|p| rect.contains(*p) && !over_card(*p)).and_then(|p| wire_at(&wires, p)).cloned(),
Some(Drag::WirePress { wire, .. }) => Some(wire.clone()),
Some(_) => None,
};
for (w, ctrl) in &wires {
let Some(c) = g.input_of(w.0, &w.1) else { continue };
let hot = selection.contains(&c.from) || selection.contains(&c.to);
let picked = app.graph.selected_wires.contains(w);
let hovered = wire_hover.as_ref() == Some(w);
let base = (2.0 * cam.zoom).clamp(1.0, 3.0);
let stroke = if picked {
Stroke::new(base + 2.0, tk.accent)
} else if hovered {
Stroke::new(base + 1.0, Color32::WHITE)
} else {
Stroke::new(base, if hot { tk.accent } else { Color32::from_gray(0xb4) })
};
painter.add(egui::epaint::CubicBezierShape::from_points_stroke(*ctrl, false, Color32::TRANSPARENT, stroke));
}
app.graph.wires = wires;
// Nodes.
let font = FontId::proportional((10.5 * cam.zoom).clamp(6.0, 16.0));
@@ -595,7 +692,24 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) {
painter.galley(bg.min + vec2(3.0, 3.0), g_, tk.text_strong);
}
handle_input(app, ui, &resp, rect, &cam, &node_resps, &frame_hits, &comment_hits, port_hover, &laid.iter().map(|l| (l.id, l.rect)).collect::<Vec<_>>());
// A wire under a comment is not hit.
let wire_hover = wire_hover.filter(|_| !pointer.is_some_and(|p| comment_hits.iter().any(|(_, r)| r.contains(p))));
if wire_hover.is_some() {
ctx.set_cursor_icon(egui::CursorIcon::PointingHand);
}
handle_input(
app,
ui,
&resp,
rect,
&cam,
&node_resps,
&frame_hits,
&comment_hits,
port_hover,
wire_hover,
&laid.iter().map(|l| (l.id, l.rect)).collect::<Vec<_>>(),
);
// Drag previews.
match &app.graph.drag {
@@ -615,14 +729,17 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) {
search_popup(app, ui, &cam);
comment_editor(app, ui);
if let Some(e) = cooked_error_count(app) {
painter.text(rect.right_bottom() - vec2(8.0, 8.0), Align2::RIGHT_BOTTOM, e, FontId::proportional(11.0), tk.danger);
let (failed, placeholders) = app.session.cook_failures();
let mut at = rect.right_bottom() - vec2(8.0, 8.0);
if !failed.is_empty() {
let text = format!("{} {} node(s) failed", icon::WARNING, failed.len());
at.y = painter.text(at, Align2::RIGHT_BOTTOM, text, FontId::proportional(11.0), tk.danger).top() - 2.0;
}
// Placeholders for missing SBS nodes are a soft warning, not a failure
if placeholders > 0 {
let text = format!("{} {placeholders} missing node(s), see the Console", icon::WARNING);
painter.text(at, Align2::RIGHT_BOTTOM, text, FontId::proportional(11.0), tk.warning);
}
}
fn cooked_error_count(app: &MaterialCraftApp) -> Option<String> {
let n = app.session.cooked.nodes.values().filter(|r| r.error.is_some()).count();
(n > 0).then(|| format!("{} {n} node(s) failed", icon::WARNING))
}
fn grid(p: &egui::Painter, cam: &Cam, rect: Rect) {
@@ -664,6 +781,7 @@ fn handle_input(
frames: &[(u64, Rect, Rect)],
comments: &[(u64, Rect)],
port_hover: Option<PortHit>,
wire_hover: Option<WireRef>,
graph_rects: &[(NodeId, Rect)],
) {
let ctx = ui.ctx().clone();
@@ -682,7 +800,15 @@ fn handle_input(
if middle_down || (primary_pressed && mods.alt) {
app.graph.drag = Some(Drag::Pan);
} else if primary_pressed {
if let Some(h) = &port_hover {
let on_card = nodes.iter().any(|(_, r)| r.rect.contains(p)) || comments.iter().any(|(_, r)| r.contains(p));
let wire = wire_hover.as_ref().filter(|_| port_hover.is_none() && !on_card);
// Any press other than on a wire drops the wire selection.
if wire.is_none() {
app.graph.selected_wires.clear();
}
if let Some(w) = wire {
app.graph.drag = Some(Drag::WirePress { wire: w.clone(), start: p });
} else if let Some(h) = &port_hover {
if h.output {
app.graph.drag = Some(Drag::Wire { from: (h.node, h.port.clone()), detached: None });
} else if let Some(c) = app.session.graph().ok().and_then(|g| g.input_of(h.node, &h.port).cloned()) {
@@ -728,6 +854,19 @@ fn handle_input(
app.ui.graph_camera.pan = [app.ui.graph_camera.pan[0] - d.x, app.ui.graph_camera.pan[1] - d.y];
}
Some(Drag::Nodes { delta }) | Some(Drag::Frame { delta, .. }) | Some(Drag::Comment { delta, .. }) => *delta += motion,
Some(Drag::WirePress { wire, start }) => {
// Dragged far enough: a reroute dot where the press was, carried by the pointer.
if let Some(p) = pointer
&& p.distance(*start) > 4.0
{
let (wire, start) = (wire.clone(), *start);
let at = cam.to_graph(start);
app.graph.drag = None;
if app.run("graph.wire.insertDot", json!({"to": wire.0.0, "toPort": wire.1, "at": [at.x, at.y]})).is_some() {
app.graph.drag = Some(Drag::Nodes { delta: (p - start) / zoom });
}
}
}
_ => {}
}
@@ -736,6 +875,20 @@ fn handle_input(
if ended && let Some(drag) = app.graph.drag.take() {
match drag {
Drag::Pan => {}
Drag::WirePress { wire, .. } => {
app.session.selection.clear();
let sel = &mut app.graph.selected_wires;
if mods.ctrl && sel.contains(&wire) {
// Ctrl+click toggles a wire out of the selection.
sel.retain(|w| *w != wire);
} else if mods.ctrl || mods.shift {
if !sel.contains(&wire) {
sel.push(wire);
}
} else {
*sel = vec![wire];
}
}
Drag::Nodes { delta } => {
if delta.length() > 0.5 {
app.run("graph.node.move", json!({"by": [delta.x, delta.y]}));
@@ -848,15 +1001,34 @@ fn handle_input(
&& !on_node
&& let Some(p) = pointer
{
open_search(app, cam.to_graph(p), None);
match &wire_hover {
// Double-click a wire: a reroute dot there.
Some(w) => {
let at = cam.to_graph(p);
app.run("graph.wire.insertDot", json!({"to": w.0.0, "toPort": w.1, "at": [at.x, at.y]}));
app.graph.selected_wires.clear();
}
None => open_search(app, cam.to_graph(p), None),
}
}
if canvas.secondary_clicked()
&& let Some(p) = pointer
{
app.graph.menu_at = cam.to_graph(p);
app.graph.menu_wire = wire_hover.clone().filter(|_| !on_node);
// Right-clicking a selected wire keeps the selection (to swap or delete them all).
if let Some(w) = &app.graph.menu_wire
&& !app.graph.selected_wires.contains(w)
{
app.session.selection.clear();
app.graph.selected_wires = vec![w.clone()];
}
}
let at = app.graph.menu_at;
canvas.context_menu(|ui| canvas_menu(app, ui, at));
canvas.context_menu(|ui| match app.graph.menu_wire.clone() {
Some(w) => wire_menu(app, ui, w, at),
None => canvas_menu(app, ui, at),
});
// Library drops.
if let Some(payload) = canvas.dnd_release_payload::<LibraryDrag>()
@@ -1027,6 +1199,55 @@ fn node_menu(app: &mut MaterialCraftApp, ui: &mut Ui, id: NodeId) {
item(ui, "Create graph from selection", "graph.createFromSelection", json!({}));
}
/// `wires` as the `{wires: [{to, toPort}, ...]}` parameter of the wire commands.
fn wires_json(wires: &[WireRef]) -> serde_json::Value {
json!({"wires": wires.iter().map(|(to, port)| json!({"to": to.0, "toPort": port})).collect::<Vec<_>>()})
}
/// Delete the selected wires in one undo step (the Delete and Backspace keys); `false` when none
/// is selected.
pub fn delete_selected_wires(app: &mut MaterialCraftApp) -> bool {
let wires = std::mem::take(&mut app.graph.selected_wires);
if wires.is_empty() {
return false;
}
app.run("graph.wire.delete", wires_json(&wires));
true
}
/// Swap where the selected wires come from (the X key): two wires trade sources, more reverse
/// them in input order. The wires stay selected, so X again swaps back. `false` when no wire is
/// selected.
pub fn swap_selected_wires(app: &mut MaterialCraftApp) -> bool {
if app.graph.selected_wires.is_empty() {
return false;
}
let params = wires_json(&app.graph.selected_wires);
app.run("graph.wire.swap", params);
true
}
fn wire_menu(app: &mut MaterialCraftApp, ui: &mut Ui, (to, port): WireRef, at: Pos2) {
let n = app.graph.selected_wires.len();
if ui.button(format!("{} {}", icon::DOT_OUTLINE, tr("Insert reroute dot"))).clicked() {
app.run("graph.wire.insertDot", json!({"to": to.0, "toPort": port, "at": [at.x, at.y]}));
app.graph.selected_wires.clear();
ui.close();
}
if n >= 2 && ui.button(format!("{} {} (X)", icon::ARROWS_LEFT_RIGHT, tr("Swap selected links"))).clicked() {
swap_selected_wires(app);
ui.close();
}
let label = if n >= 2 { tr("Delete selected links") } else { tr("Delete link") };
if ui.button(format!("{} {label}", icon::TRASH)).clicked() {
if n < 2 {
app.graph.selected_wires = vec![(to, port)];
}
delete_selected_wires(app);
ui.close();
}
}
fn canvas_menu(app: &mut MaterialCraftApp, ui: &mut Ui, at: Pos2) {
ui.menu_button(tr("Add node"), |ui| {
for (cat, ids) in materialcraft_engine::nodes::categories() {
@@ -1235,6 +1456,55 @@ mod tests {
assert!(f.app.graph.search.is_some());
}
#[test]
fn clicked_wires_swap_with_x_and_delete_together() {
let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), crate::UiState::default());
app.run("file.new", json!({"template": "empty"}));
let id = |v: Option<serde_json::Value>| v.and_then(|v| v["id"].as_u64()).unwrap();
let a = id(app.run("graph.node.add", json!({"def": "clouds_1", "at": [0, -150]})));
let b = id(app.run("graph.node.add", json!({"def": "checker", "at": [0, 150]})));
let blend = id(app.run("graph.node.add", json!({"def": "blend", "at": [450, 0]})));
app.run("graph.connect", json!({"from": a, "to": blend, "toPort": "foreground"}));
app.run("graph.connect", json!({"from": b, "to": blend, "toPort": "background"}));
let ctx = egui::Context::default();
let mut frame = |app: &mut MaterialCraftApp, mut events: Vec<egui::Event>, modifiers: egui::Modifiers| {
events.insert(0, egui::Event::ModifiersChanged(modifiers));
let input = egui::RawInput { events, ..Default::default() };
ctx.run_ui(input, |ui| {
app.step(&ui.ctx().clone());
app.draw(ui);
})
.textures_delta
.clear();
};
for _ in 0..3 {
frame(&mut app, Vec::new(), egui::Modifiers::NONE);
}
let mid =
|app: &MaterialCraftApp, port: &str| app.graph.wires.iter().find(|(w, _)| w.0.0 == blend && w.1 == port).map(|(_, c)| bezier_at(c, 0.5)).unwrap();
let click =
|app: &mut MaterialCraftApp, frame: &mut dyn FnMut(&mut MaterialCraftApp, Vec<egui::Event>, egui::Modifiers), port: &str, m: egui::Modifiers| {
let p = mid(app, port);
let button = |pressed| egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: m };
frame(app, vec![egui::Event::PointerMoved(p)], m);
frame(app, vec![button(true)], m);
frame(app, vec![button(false)], m);
};
click(&mut app, &mut frame, "foreground", egui::Modifiers::NONE);
click(&mut app, &mut frame, "background", egui::Modifiers::SHIFT);
assert_eq!(app.graph.selected_wires.len(), 2, "{:?}", app.graph.selected_wires);
let key = |k| egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE };
let src = |app: &MaterialCraftApp, port: &str| app.session.graph().unwrap().input_of(NodeId(blend), port).unwrap().from.0;
frame(&mut app, vec![key(egui::Key::X)], egui::Modifiers::NONE);
assert_eq!((src(&app, "foreground"), src(&app, "background")), (b, a));
// Still selected: X again swaps back.
frame(&mut app, vec![key(egui::Key::X)], egui::Modifiers::NONE);
assert_eq!((src(&app, "foreground"), src(&app, "background")), (a, b));
frame(&mut app, vec![key(egui::Key::Delete)], egui::Modifiers::NONE);
assert!(app.session.graph().unwrap().connections.is_empty());
assert!(app.graph.selected_wires.is_empty());
}
#[test]
fn node_search_shortcuts_respect_hover_and_keyboard_focus() {
for key in [egui::Key::Space, egui::Key::Tab] {
@@ -1277,6 +1547,23 @@ mod tests {
assert!(matches("zzzz").is_empty());
}
#[test]
fn wires_are_hit_near_their_curve_only() {
let a = (NodeId(1), "input".to_string());
let b = (NodeId(2), "input".to_string());
let wires = vec![(a.clone(), bezier_points(pos2(0.0, 0.0), pos2(200.0, 100.0))), (b.clone(), bezier_points(pos2(0.0, 300.0), pos2(200.0, 300.0)))];
// The midpoint of a symmetric wire lies on the line between its ends.
let mid = bezier_at(&wires[0].1, 0.5);
assert!((mid - pos2(100.0, 50.0)).length() < 1e-3, "{mid:?}");
assert_eq!(wire_at(&wires, mid + vec2(0.0, 3.0)), Some(&a));
assert_eq!(wire_at(&wires, pos2(100.0, 302.0)), Some(&b));
assert_eq!(wire_at(&wires, pos2(100.0, 200.0)), None);
assert_eq!(wire_at(&wires, mid + vec2(0.0, WIRE_HIT * 3.0)), None);
// The ends are on the wire.
assert!(bezier_distance(&wires[0].1, pos2(0.0, 0.0)) < 1e-3);
assert!(bezier_distance(&wires[0].1, pos2(200.0, 100.0)) < 1e-3);
}
#[test]
fn port_positions_stay_on_the_card() {
let n = Node::new(NodeId(1), "blend", [0.0, 0.0]);
+161 -6
View File
@@ -1,12 +1,167 @@
//! Interface text. English only for now; every user-facing string goes through [`tr`] (or is
//! marked with [`n_`] where it is stored), so translations can be added without touching callers.
//! UI text lookup. Keys are the English strings, so English needs no table and a missing
//! translation falls back to English. Every user-visible literal goes through [`tr`] (or [`trf`]
//! for text with `{name}` placeholders); each language is a static `(English, translation)`
//! table, indexed into a hash map the first time the language is used. `Prefs::language` picks it.
/// Mark a string for translation where it is stored; translate with [`tr`] where it is shown.
use std::collections::HashMap;
use std::fmt::Display;
use std::sync::OnceLock;
use std::sync::atomic::{AtomicUsize, Ordering};
mod ar;
pub struct Language {
/// BCP 47 code ("en", "ar").
pub code: &'static str,
/// The language's own name, for the picker.
pub name: &'static str,
/// Its English name (the picker's fallback when no font can draw `name`).
pub english: &'static str,
/// `(English, translation)` pairs, in any order.
pub table: &'static [(&'static str, &'static str)],
}
const COUNT: usize = 2;
pub static LANGUAGES: [Language; COUNT] =
[Language { code: "en", name: "English", english: "English", table: &[] }, Language { code: "ar", name: "العربية", english: "Arabic", table: ar::TABLE }];
static MAPS: [OnceLock<HashMap<&'static str, &'static str>>; COUNT] = [const { OnceLock::new() }; COUNT];
static CURRENT: AtomicUsize = AtomicUsize::new(0);
/// Switch the UI language (unknown codes fall back to English).
pub fn set_language(code: &str) {
CURRENT.store(LANGUAGES.iter().position(|l| l.code == code).unwrap_or(0), Ordering::Relaxed);
}
/// The current UI language.
pub fn current() -> &'static Language {
LANGUAGES.get(CURRENT.load(Ordering::Relaxed)).unwrap_or(&LANGUAGES[0])
}
/// Returns true if `code` is a right-to-left language (e.g. Arabic `"ar"`).
pub fn is_rtl_code(code: &str) -> bool {
craft_ui::direction::resolve(code, craft_ui::direction::Setting::Language) == craft_ui::direction::Direction::Rtl
}
/// Returns true if the current UI language is right-to-left.
pub fn is_rtl() -> bool {
is_rtl_code(current().code)
}
/// `text` in the current language (unchanged when it has no translation).
pub fn tr(text: &str) -> &str {
let i = CURRENT.load(Ordering::Relaxed);
let (Some(lang), Some(map)) = (LANGUAGES.get(i), MAPS.get(i)) else { return text };
if lang.table.is_empty() {
return text;
}
map.get_or_init(|| lang.table.iter().copied().collect()).get(text).copied().unwrap_or(text)
}
/// Marks a static string for translation where it is defined (gettext's `N_`); it is translated
/// with [`tr`] where it is shown. The key test collects both.
pub const fn n_(text: &'static str) -> &'static str {
text
}
/// The text in the interface language.
pub fn tr(text: &str) -> &str {
text
/// `template` translated, with each `{name}` replaced by its value in `args`.
pub fn trf(template: &str, args: &[(&str, &dyn Display)]) -> String {
let mut out = String::with_capacity(template.len() + 16);
let mut rest = tr(template);
while let Some(open) = rest.find('{') {
out.push_str(&rest[..open]);
let after = &rest[open + 1..];
match after.find('}').and_then(|close| args.iter().find(|(k, _)| *k == &after[..close]).map(|(_, v)| (close, v))) {
Some((close, v)) => {
use std::fmt::Write as _;
let _ = write!(out, "{v}");
rest = &after[close + 1..];
}
None => {
out.push('{');
rest = after;
}
}
}
out.push_str(rest);
out
}
/// The supported language for a locale such as "ar-EG", "ar-SA" ("en" when none matches).
pub fn language_for_locale(locale: &str) -> &'static str {
let lang = locale.split(['-', '_', '.', '@']).next().unwrap_or("").to_ascii_lowercase();
match lang.as_str() {
"ar" => "ar",
l => LANGUAGES.iter().find(|x| x.code == l).map_or("en", |x| x.code),
}
}
/// The operating system's (or browser's) UI language, for the first run.
pub fn os_language() -> &'static str {
#[cfg(not(target_arch = "wasm32"))]
let locale = sys_locale::get_locale();
#[cfg(target_arch = "wasm32")]
let locale = web_sys::window().and_then(|w| w.navigator().language());
locale.map_or("en", |l| language_for_locale(&l))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn language_switching_and_arabic_translations_work() {
set_language("en");
assert_eq!(current().code, "en");
assert_eq!(tr("Properties"), "Properties");
assert!(!is_rtl());
set_language("ar");
assert_eq!(current().code, "ar");
assert_eq!(tr("Properties"), "الخصائص");
assert_eq!(tr("Preferences"), "التفضيلات");
assert_eq!(tr("New graph"), "مخطط جديد");
assert_eq!(tr("Export outputs"), "تصدير المخرجات");
assert_eq!(tr("Welcome to MaterialCraft"), "مرحباً بك في MaterialCraft");
assert!(is_rtl());
// Live formatting
let formatted = trf("Hello {name}", &[("name", &"World")]);
assert_eq!(formatted, "Hello World");
// Fallback for unknown text
assert_eq!(tr("Unknown untranslated string 1234"), "Unknown untranslated string 1234");
// Reset to English
set_language("en");
}
#[test]
fn locale_detection() {
assert_eq!(language_for_locale("ar"), "ar");
assert_eq!(language_for_locale("ar-EG"), "ar");
assert_eq!(language_for_locale("ar_SA.UTF-8"), "ar");
assert_eq!(language_for_locale("en-US"), "en");
assert_eq!(language_for_locale("fr-FR"), "en");
}
#[test]
fn arabic_table_has_no_duplicate_keys() {
let mut seen = std::collections::HashSet::new();
for (k, _) in ar::TABLE {
assert!(seen.insert(*k), "duplicate key in ar::TABLE: {k:?}");
}
}
#[test]
fn placeholders_match_between_key_and_arabic_translation() {
for (k, v) in ar::TABLE {
let mut kp: Vec<&str> = k.split('{').skip(1).filter_map(|s| s.split_once('}').map(|(p, _)| p)).collect();
let mut vp: Vec<&str> = v.split('{').skip(1).filter_map(|s| s.split_once('}').map(|(p, _)| p)).collect();
kp.sort();
vp.sort();
assert_eq!(kp, vp, "mismatched placeholders in {k:?} vs {v:?}");
}
}
}
+373
View File
@@ -0,0 +1,373 @@
//! Arabic UI text: (English key, translation). Keys are the English strings passed to `tr`.
pub const TABLE: &[(&str, &str)] = &[
("$pos", "$pos"),
("$size", "$size"),
("(checker)", "(رقعة شطرنج)"),
("1024 px", "1024 بكسل"),
("16 bits", "16 بت"),
("16 bits per channel", "16 بت لكل قناة"),
("16 bits per channel float (HDR)", "16 بت لكل قناة فاصلة عائمة (HDR)"),
("2048 px", "2048 بكسل"),
("256 px", "256 بكسل"),
("2D View", "عرض ثنائي الأبعاد"),
("32 bits float", "32 بت فاصلة عائمة"),
("32 bits per channel float (HDR)", "32 بت لكل قناة فاصلة عائمة (HDR)"),
("3D pan limit (mesh radii)", "حد التحريك ثلاثي الأبعاد (أنصاف أقطار المجسم)"),
("3D pan speed", "سرعة التحريك ثلاثي الأبعاد"),
("3D View", "عرض ثلاثي الأبعاد"),
("512 px", "512 بكسل"),
("8 bits", "8 بت"),
("8 bits per channel", "8 بت لكل قناة"),
("About MaterialCraft", "حول MaterialCraft"),
("About MaterialCraft...", "حول MaterialCraft..."),
("Absolute", "مطلق"),
("Accent color", "لون التمييز"),
("Actual pixels", "البكسلات الفعلية"),
("Add", "إضافة"),
("Add Comment", "إضافة تعليق"),
("Add comment", "إضافة تعليق"),
("Add Dot node", "إضافة عقدة نقطية"),
("Add Frame", "إضافة إطار"),
("Add frame around selection", "إضافة إطار حول التحديد"),
("Add frame around the selection", "إضافة إطار حول التحديد"),
("Add Navigation pin", "إضافة دبوس تنقل"),
("Add navigation pin", "إضافة دبوس تنقل"),
("Add node", "إضافة عقدة"),
("Add Output nodes with usages (base color, normal, ...) to see the material", "أضف عُقد مخرجات مع استخداماتها (اللون الأساسي، الناظم، ...) لمعاينة المادة"),
("Align centers horizontally", "محاذاة المراكز أفقياً"),
("Align centers vertically", "محاذاة المراكز رأسياً"),
("Align left", "محاذاة لليسار"),
("Align top", "محاذاة للأعلى"),
("All nodes", "كل العقد"),
("Amber", "كهرماني"),
("An open-source Crafting App by the ArtCraft team and community.", "تطبيق تصميم مفتوح المصدر من قِبل فريق ومجتمع ArtCraft."),
("And", "و (And)"),
("Apply", "تطبيق"),
("Arc tangent 2", "ظل زاوية قوسي 2"),
("ArtCraft website...", "موقع ArtCraft الإلكتروني..."),
("As JSON", "بصيغة JSON"),
("Atomic nodes", "عقد أولية"),
("Attributes", "السمات"),
("Autosave every (minutes, 0 = off)", "الحفظ التلقائي كل (دقائق، 0 = معطل)"),
("Bad function", "دالة غير صالحة"),
("Base parameters", "المعلمات الأساسية"),
("Bind to input", "ربط بالمدخل"),
("Bit depth", "عمق البت"),
("Blends", "عمليات الدمج"),
("Blue", "أزرق"),
("Boolean", "منطقي"),
("Brick wall", "جدار طوب"),
("Brightness", "السطوع"),
(
"Build tileable materials from noises, patterns and filters, see them live in 2D and 3D, and export the maps for any engine.",
"أنشئ مواد قابلة للتكرار من التشويش والأنماط والمرشحات، وعاينها مباشرة ثنائية وثلاثية الأبعاد، وصدّر الخرائط لأي محرك.",
),
("Cache", "الذاكرة المؤقتة"),
("Camera", "الكاميرا"),
("Cancel", "إلغاء"),
("Cast", "تحويل النوع"),
("Ceil", "الحد الأعلى (Ceil)"),
("Choose a folder to export to", "اختر مجلداً للتصدير إليه"),
("Clamp", "تقييد النطاق (Clamp)"),
("Clear cache", "مسح الذاكرة المؤقتة"),
("Clear recent packages", "مسح الحزم الأخيرة"),
("Close all", "إغلاق الكل"),
("Community (Discord)", "المجتمع (Discord)"),
("Comparison", "مقارنة"),
("Compute graph", "حساب المخطط"),
("Computing...", "جاري الحساب..."),
("Console", "وحدة التحكم"),
("Constant", "ثابت"),
("Control", "تحكم"),
("Copper", "نحاسي"),
("Copy", "نسخ"),
("Copy selection", "نسخ التحديد"),
("Coral", "مرجاني"),
("Cosine", "جيب التمام (Cosine)"),
("Couldn't export", "تعذر التصدير"),
("Couldn't import", "تعذر الاستيراد"),
("Couldn't load", "تعذر التحميل"),
("Couldn't open", "تعذر الفتح"),
("Couldn't save", "تعذر الحفظ"),
("Create", "إنشاء"),
("Create graph from selection", "إنشاء مخطط من التحديد"),
("Create graph in", "إنشاء مخطط في"),
("Cube", "مكعب"),
("Cut", "قص"),
("Cyan", "سماوي"),
("Cylinder", "أسطوانة"),
("Dark", "داكن"),
("Default", "افتراضي"),
("Delete", "حذف"),
("Delete and relink", "حذف وإعادة ربط"),
("Delete input", "حذف المدخل"),
("Delete preset", "حذف الإعداد المسبق"),
("Delete selection", "حذف التحديد"),
("Disable selection", "تعطيل التحديد"),
("Display", "عرض"),
("Distribute horizontally", "توزيع أفقي"),
("Distribute vertically", "توزيع رأسي"),
("Division", "قسمة"),
("Documentation", "التوثيق"),
("Documentation...", "التوثيق..."),
("Dot Product", "الجداء السلمي (Dot Product)"),
("Double-click a node to show it here", "انقر نقراً مزدوجاً على عقدة لعرضها هنا"),
("Downloaded", "تم التنزيل"),
("Duplicate", "تكرار"),
("Duplicate selection", "تكرار التحديد"),
("Duplicate selection without link", "تكرار التحديد بدون ربط"),
("Edit", "تحرير"),
("Edit function graph...", "تحرير مخطط الدوال..."),
("Empty", "فارغ"),
("Empty package", "حزمة فارغة"),
("Engine", "المحرك"),
("Environment", "البيئة"),
("Environment background", "خلفية البيئة"),
("Equal", "مساوٍ"),
("Exit", "خروج"),
("Explorer", "المستكشف"),
("Exponential", "دالة أسية (Exp)"),
("Export", "تصدير"),
("Export material...", "تصدير المادة..."),
("Export outputs", "تصدير المخرجات"),
("Export outputs...", "تصدير المخرجات..."),
("Export outputs... (Ctrl+Shift+E)", "تصدير المخرجات... (Ctrl+Shift+E)"),
("Exported", "تم التصدير"),
("Expose as graph input", "كشف كمدخل للمخطط"),
("Exposure", "التعريض"),
("File", "ملف"),
("File names", "أسماء الملفات"),
("files", "ملفات"),
("Filters", "مرشحات"),
("Fit", "ملاءمة"),
("Float", "فاصلة عائمة (Float)"),
("Float2", "فاصلة عائمة ثنائية (Float2)"),
("Float3", "فاصلة عائمة ثلاثية (Float3)"),
("Float4", "فاصلة عائمة رباعية (Float4)"),
("Flood fill", "تعبئة متصلة (Flood fill)"),
("Floor", "الحد الأدنى (Floor)"),
("Folder", "المجلد"),
("Format", "الصيغة"),
("Fractional part", "الجزء الكسري"),
("Frame all", "تأطير الكل"),
("Frame all (F)", "تأطير الكل (F)"),
("Frame all / the selection", "تأطير الكل / التحديد"),
("Front", "أمامي"),
("Full size", "الحجم الكامل"),
("full size", "الحجم الكامل"),
("Function", "دالة"),
("function", "دالة"),
("Function graph", "مخطط الدوال"),
("function nodes", "عقد الدوال"),
("Function of", "دالة لـ"),
("Get variable", "جلب متغير"),
("Go to pin", "الانتقال إلى الدبوس"),
("Graph", "مخطط"),
("Graph instance", "نسخة المخطط"),
("Graph items", "عناصر المخطط"),
("Graph name", "اسم المخطط"),
("Graph's format", "صيغة المخطط"),
("Graph...", "مخطط..."),
("Graphs in this package", "المخططات في هذه الحزمة"),
("Greater", "أكبر من"),
("Greater or equal", "أكبر من أو يساوي"),
("Green", "أخضر"),
("Height (parallax) depth", "عمق الارتفاع (اختلاف المنظر)"),
("Help", "مساعدة"),
("Histogram", "المخطط البياني (Histogram)"),
("History", "السجل"),
("Home", "الرئيسية"),
("Home screen...", "الشاشة الرئيسية..."),
("Icons", "أيقونات"),
("If...Else", "إذا...وإلا (If...Else)"),
("Import bitmap...", "استيراد صورة نقطية..."),
("Imported", "تم الاستيراد"),
("Input parameters", "معلمات المدخلات"),
("Input previews", "معاينات المدخلات"),
("Instance parameters", "معلمات النسخة"),
("Integer", "عدد صحيح"),
("Interface scale", "حجم واجهة المستخدم"),
("Join the community (Discord)...", "انضم إلى المجتمع (Discord)..."),
("Key at", "مفتاح عند"),
("Language", "اللغة"),
("Last compute", "آخر حساب"),
("Lava rock", "صخور بركانية"),
("Length", "الطول"),
("Library", "المكتبة"),
("Light", "فاتح"),
("Linear interpolation", "استيفاء خطي (Lerp)"),
("List", "قائمة"),
("Load mesh...", "تحميل مجسم..."),
("Logarithm", "لوغاريتم"),
("Logical", "منطقي"),
("Lower", "أصغر من"),
("Lower or equal", "أصغر من أو يساوي"),
("Mat ball", "كرة المادة"),
("Material filters", "مرشحات المواد"),
("Maximum", "الحد الأقصى"),
("Medium dark", "داكن متوسط"),
("Medium light", "فاتح متوسط"),
("Minimum", "الحد الأدنى"),
("Modulo", "باقي القسمة (Modulo)"),
("Mossy ground", "أرضية مغطاة بالطحالب"),
("Multiplication", "ضرب"),
("Name", "الاسم"),
("Negation", "نفي / سالب"),
("New", "جديد"),
("New graph", "مخطط جديد"),
("New graph...", "مخطط جديد..."),
("New graph... (Ctrl+N)", "مخطط جديد... (Ctrl+N)"),
("New random seed", "بذرة عشوائية جديدة"),
("Night", "ليل"),
("No font on this system can show this language", "لا يوجد خط على هذا النظام يمكنه عرض هذه اللغة"),
("No graph is open", "لا يوجد مخطط مفتوح"),
("No matching node", "لا توجد عقدة مطابقة"),
("No presets yet", "لا توجد إعدادات مسبقة بعد"),
("No recent packages", "لا توجد حزم حديثة"),
("Node search (over the graph)", "البحث عن عقدة (فوق المخطط)"),
("Node-based procedural materials, built in pure Rust.", "مواد إجرائية قائمة على العقد، مبنية بلغة Rust النقية."),
("Noises", "تشويشات"),
("None", "بلا"),
("Normal", "الناظم (Normal)"),
("Normalize", "تسوية (Normalize)"),
("Not", "ليس (Not)"),
("Not equal", "غير مساوٍ"),
("Nothing matches", "لا توجد تطابقات"),
("Open", "فتح"),
("Open graph", "فتح المخطط"),
("Open package...", "فتح حزمة..."),
("Open package... (Ctrl+O)", "فتح حزمة... (Ctrl+O)"),
("Open...", "فتح..."),
("Opened", "تم الفتح"),
("Operator", "معامل حسابي"),
("Ops", "عمليات"),
("Or", "أو (Or)"),
("Output format", "صيغة المخرج"),
("Output size", "حجم المخرج"),
("Outputs", "المخرجات"),
("Overcast", "غائم"),
("Painted metal plates", "صفائح معدنية مطلية"),
("Pan the camera", "تحريك الكاميرا"),
("Pan the graph", "تحريك المخطط"),
("Parent size:", "حجم العنصر الأصل:"),
("Paste", "لصق"),
("Patterns", "أنماط"),
("PBR material (outputs only)", "مادة PBR (مخرجات فقط)"),
("Perlin noise", "تشويش بيرلين (Perlin noise)"),
("Pick an image file (a mesh map baked in TextureCraft)", "اختر ملف صورة (خريطة مجسم مخبوزة في TextureCraft)"),
("Pink", "وردي"),
("Plane", "مستوى"),
("Polished marble", "رخام مصقول"),
("Power", "قوة / أس (Power)"),
("Preferences", "التفضيلات"),
("Preferences...", "التفضيلات..."),
("Preset name", "اسم الإعداد المسبق"),
("Presets", "الإعدادات المسبقة"),
("Preview", "معاينة"),
("Preview size", "حجم المعاينة"),
("Preview size while editing", "حجم المعاينة أثناء التحرير"),
("Properties", "الخصائص"),
("Random", "عشوائي"),
("Random seed", "بذرة عشوائية"),
("Recent", "الأخيرة"),
("Recent packages", "الحزم الأخيرة"),
("Redo", "إعادة"),
("Redo (Ctrl+Y)", "إعادة (Ctrl+Y)"),
("Relative to input", "نسبي إلى المدخل"),
("Relative to parent", "نسبي إلى الأصل"),
("Reload resources", "إعادة تحميل الموارد"),
("Remove function", "إزالة الدالة"),
("Render time", "وقت التصيير"),
("Renderer", "المصير"),
("Report a bug...", "الإبلاغ عن خطأ..."),
("Reset layout", "إعادة ضبط التخطيط"),
("Reset parameters", "إعادة ضبط المعلمات"),
("Reset scene", "إعادة ضبط المشهد"),
("Reset to default", "إعادة ضبط للافتراضي"),
("Resources", "الموارد"),
("Revert", "استرجاع"),
("Right-click a node parameter > Expose as graph input", "انقر بزر الفأرة الأيمن على معلمة العقدة > كشف كمدخل للمخطط"),
(
"Right-click or Space to add operations; drag from an output dot to an input; the starred node is the result.",
"انقر بزر الفأرة الأيمن أو مفتاح المسافة لإضافة عمليات؛ اسحب من نقطة المخرج إلى المدخل؛ العقدة المميزة بنجمة هي النتيجة.",
),
("Rotation", "التدوير"),
("Rounded cube", "مكعب مدور الحواف"),
("Rusty metal", "معدن صدئ"),
("Sample Color", "عينة لونية"),
("Sample Gray", "عينة تدرج رمادي"),
("Samplers", "عينات"),
("Samples", "عينات"),
("Save", "حفظ"),
("Save (Ctrl+S)", "حفظ (Ctrl+S)"),
("Save as...", "حفظ باسم..."),
("Save image...", "حفظ الصورة..."),
("Save package", "حفظ الحزمة"),
("Save preset", "حفظ الإعداد المسبق"),
("Saved", "تم الحفظ"),
("Scene", "المشهد"),
("Search", "بحث"),
("Search nodes...", "البحث في العقد..."),
("Select all", "تحديد الكل"),
("Select downstream nodes", "تحديد العقد اللاحقة"),
("Select upstream nodes", "تحديد العقد السابقة"),
("Send to TextureCraft", "إرسال إلى TextureCraft"),
("Sent to TextureCraft: find it on the shelf under My smart materials", "أُرسل إلى TextureCraft: ستجده على الرف ضمن موادي الذكية"),
("Set function...", "تعيين دالة..."),
("Shortcuts", "الاختصارات"),
("Shortcuts list...", "قائمة الاختصارات..."),
("Show at startup", "إظهار عند بدء التشغيل"),
("Show in the 2D view", "إظهار في العرض ثنائي الأبعاد"),
("Show node thumbnails", "إظهار الصور المصغرة للعقد"),
("Showing", "عرض"),
("Side", "جانبي"),
("Sine", "جيب الزاوية (Sine)"),
("Size", "الحجم"),
("Specific parameters", "المعلمات المخصصة"),
("Sphere", "كرة"),
("Square root", "جذر تربيعي"),
("Stone tiles", "بلاط حجري"),
("Studio", "استوديو"),
("Subtraction", "طرح"),
("Sunset", "غروب"),
("SVG", "رسوم متجهة (SVG)"),
("Swizzle", "إعادة ترتيب القنوات (Swizzle)"),
("Tangent", "ظل الزاوية (Tangent)"),
("Templates", "القوالب"),
("Text", "نص"),
("Texture generators", "مولدات الخامات"),
("The instanced graph is missing", "المخطط المنسوخ مفقود"),
("This graph exposes no inputs", "هذا المخطط لا يكشف أي مدخلات"),
("This package", "هذه الحزمة"),
("threads", "خيوط معالجة"),
("Tile 3x3", "تكرار 3x3"),
("Tiling", "التكرار"),
("Tiling (H and V)", "التكرار (أفقياً ورأسياً)"),
("To Float", "إلى فاصلة عائمة"),
("To Integer", "إلى عدد صحيح"),
("Tools", "أدوات"),
("Top", "علوي"),
("Torus", "شكل حلقي (Torus)"),
("Transforms", "التحويلات"),
("Turn the environment", "تدوير البيئة"),
("Unbind", "فك الارتباط"),
("Undo", "تراجع"),
("Undo (Ctrl+Z)", "تراجع (Ctrl+Z)"),
("Use as result", "استخدام كنتيجة"),
("Variables", "متغيرات"),
("Vector", "متجه"),
("Vector Float2", "متجه ثنائي (Float2)"),
("Vector Float3", "متجه ثلاثي (Float3)"),
("Vector Float4", "متجه رباعي (Float4)"),
("Version", "الإصدار"),
("View in 2D view", "عرض في العرض ثنائي الأبعاد"),
("Violet", "بنفسجي"),
("Weathering", "التجوية والتقادم"),
("Welcome to MaterialCraft", "مرحباً بك في MaterialCraft"),
("Wicker weave", "نسيج قش"),
("Windows", "نوافذ"),
("Wood planks", "ألواح خشبية"),
("Woven fabric", "قماش منسوج"),
("Zoom the graph and the views", "تقريب المخطط وطرق العرض"),
];
+243
View File
@@ -0,0 +1,243 @@
//! The Levels node's editor in the properties panel: a histogram of the node's input with the
//! levels transfer curve over it, the input range handles (low, mid, high) under it and the
//! output range handles (low, high) under a black-to-white bar.
//!
//! The mid handle sits where `Level in mid` really acts: relative to the input range, so it moves
//! with the low and high handles. The input low and high handles cannot cross (the low one stays
//! left of the high one); the output handles may, which inverts the result. Every drag is a
//! `graph.node.param` command, merged into one undo step per handle.
use egui::{Color32, Pos2, Rect, Sense, Shape, Stroke, StrokeKind, Ui, pos2, vec2};
use materialcraft_engine::core::{Node, NodeId, Value};
use materialcraft_engine::image::{Image, Kind};
use materialcraft_engine::nodes::atomic::levels_fn;
use serde_json::json;
use crate::MaterialCraftApp;
use crate::i18n::tr;
use crate::theme::Tokens;
/// Histogram bins (one per 8-bit level).
pub const BINS: usize = 256;
/// Smallest gap kept between the input low and high handles.
const MIN_SPAN: f32 = 0.004;
/// Histograms of an image's values in 0..1, clamped: one for a gray image, else R, G and B.
pub fn histogram(img: &Image) -> Vec<[u32; BINS]> {
let channels = if img.kind == Kind::Gray { 1 } else { 3 };
let stride = img.kind.channels();
let mut h = vec![[0u32; BINS]; channels];
for px in img.data.chunks(stride) {
for (c, bins) in h.iter_mut().enumerate() {
let v = px.get(c).copied().unwrap_or(0.0);
let v = if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 };
if let Some(b) = bins.get_mut(((v * (BINS - 1) as f32).round() as usize).min(BINS - 1)) {
*b = b.saturating_add(1);
}
}
}
h
}
/// The bar height scale: the tallest bin away from pure black and white (masks pile up there and
/// would flatten everything else), at least one.
fn scale(h: &[[u32; BINS]]) -> f32 {
let inner = h.iter().flat_map(|b| b.get(1..BINS - 1).unwrap_or(&[]).iter().copied()).max().unwrap_or(0);
let all = h.iter().flat_map(|b| b.iter().copied()).max().unwrap_or(0);
(if inner > 0 { inner } else { all }).max(1) as f32
}
/// The five levels values of `n`: in low, in mid (relative), in high, out low, out high.
pub fn values(n: &Node) -> [f32; 5] {
let get = |id: &str, d: f32| match n.params.get(id) {
Some(Value::Float(v)) if v.is_finite() => *v,
_ => d,
};
[get("in_low", 0.0), get("in_mid", 0.5), get("in_high", 1.0), get("out_low", 0.0), get("out_high", 1.0)]
}
/// Where the mid handle sits on the 0..1 axis.
pub fn mid_position(v: &[f32; 5]) -> f32 {
v[0] + v[1].clamp(0.0, 1.0) * (v[2] - v[0])
}
/// The new value of handle `k` (0 in low, 1 in mid, 2 in high, 3 out low, 4 out high) dragged to
/// `x` on the 0..1 axis: input low and high cannot cross, mid is stored relative to the range.
pub fn drag_value(v: &[f32; 5], k: usize, x: f32) -> f32 {
let x = if x.is_finite() { x.clamp(0.0, 1.0) } else { 0.0 };
let (lo, hi) = (v[0].min(v[2]), v[0].max(v[2]));
match k {
0 => x.min(hi - MIN_SPAN).max(0.0),
2 => x.max(lo + MIN_SPAN).min(1.0),
1 => {
let span = v[2] - v[0];
if span.abs() < 1e-6 { 0.5 } else { ((x - v[0]) / span).clamp(0.01, 0.99) }
}
_ => x,
}
}
/// The histogram of what feeds the node's input, computed once per cooked result.
fn input_histogram(app: &MaterialCraftApp, ui: &Ui, node: NodeId) -> Option<std::sync::Arc<Vec<[u32; BINS]>>> {
let g = app.session.graph().ok()?;
let c = g.input_of(node, "input")?;
let port = app.session.output_ports(c.from).iter().position(|p| *p == c.from_port)?;
let r = app.session.cooked.nodes.get(&c.from)?;
let img = r.outputs.get(port)?;
let id = egui::Id::unique(("levels-histogram", r.key, port));
if let Some(h) = ui.ctx().data(|d| d.get_temp::<std::sync::Arc<Vec<[u32; BINS]>>>(id)) {
return Some(h);
}
let h = std::sync::Arc::new(histogram(img));
ui.ctx().data_mut(|d| d.insert_temp(id, h.clone()));
Some(h)
}
/// A handle: a small triangle pointing up at `x`, filled with `fill`.
fn handle(p: &egui::Painter, x: f32, top: f32, fill: Color32, active: bool, tk: &Tokens) {
let s = 6.0;
let pts = vec![pos2(x, top), pos2(x - s, top + s * 1.6), pos2(x + s, top + s * 1.6)];
p.add(Shape::convex_polygon(pts, fill, Stroke::new(if active { 1.5 } else { 1.0 }, if active { tk.accent } else { Color32::from_gray(0x10) })));
}
/// The editor for Levels node `n`.
pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui, n: &Node) {
let tk = Tokens::get(ui.ctx());
let v = values(n);
// Handles of parameters driven by an input or a function are left alone.
let locked = |id: &str| n.bindings.contains_key(id) || n.functions.contains_key(id);
let ids = ["in_low", "in_mid", "in_high", "out_low", "out_high"];
let w = ui.available_width().max(120.0);
let pad = 7.0;
let (rect, _) = ui.allocate_exact_size(vec2(w, 96.0 + 16.0 + 12.0 + 16.0), Sense::hover());
let axis = |x: f32| rect.left() + pad + x * (rect.width() - 2.0 * pad);
let unaxis = |sx: f32| (sx - rect.left() - pad) / (rect.width() - 2.0 * pad).max(1.0);
let plot = Rect::from_min_max(pos2(axis(0.0), rect.top()), pos2(axis(1.0), rect.top() + 96.0));
let p = ui.painter_at(rect.expand(2.0));
p.rect_filled(plot, 2.0, Color32::from_gray(0x16));
// The input histogram.
match input_histogram(app, ui, n.id) {
Some(h) => {
let k = scale(&h);
let colors: &[Color32] = if h.len() == 1 {
&[Color32::from_gray(0xb8)]
} else {
&[
Color32::from_rgba_unmultiplied(0xe0, 0x50, 0x50, 110),
Color32::from_rgba_unmultiplied(0x50, 0xd0, 0x60, 110),
Color32::from_rgba_unmultiplied(0x50, 0x80, 0xf0, 110),
]
};
let bw = plot.width() / BINS as f32;
for (bins, col) in h.iter().zip(colors) {
for (i, &c) in bins.iter().enumerate() {
if c == 0 {
continue;
}
let hgt = (c as f32 / k).min(1.0) * (plot.height() - 2.0);
let x0 = plot.left() + i as f32 * bw;
p.rect_filled(Rect::from_min_max(pos2(x0, plot.bottom() - hgt), pos2(x0 + bw.max(1.0), plot.bottom())), 0.0, *col);
}
}
}
None => {
p.text(plot.center(), egui::Align2::CENTER_CENTER, tr("Connect an input to see its histogram"), egui::FontId::proportional(10.5), tk.text_dim);
}
}
// Shade what the input range clips, and draw the transfer curve.
let (lo, hi) = (v[0].min(v[2]), v[0].max(v[2]));
let shade = Color32::from_black_alpha(120);
p.rect_filled(Rect::from_min_max(plot.min, pos2(axis(lo), plot.bottom())), 0.0, shade);
p.rect_filled(Rect::from_min_max(pos2(axis(hi), plot.top()), plot.max), 0.0, shade);
let curve: Vec<Pos2> = (0..=96)
.map(|i| {
let x = i as f32 / 96.0;
let y = levels_fn(x, v[0], v[1], v[2], v[3], v[4]);
let y = if y.is_finite() { y.clamp(0.0, 1.0) } else { 0.0 };
pos2(axis(x), plot.bottom() - y * plot.height())
})
.collect();
p.add(Shape::line(curve, Stroke::new(1.5, tk.accent)));
p.rect_stroke(plot, 2.0, Stroke::new(1.0, Color32::from_gray(0x40)), StrokeKind::Inside);
// Input handles under the histogram, output handles under the gradient bar.
let in_row = plot.bottom() + 2.0;
let bar = Rect::from_min_max(pos2(plot.left(), in_row + 16.0), pos2(plot.right(), in_row + 26.0));
let mesh = {
let mut m = egui::Mesh::default();
m.colored_vertex(bar.left_top(), Color32::BLACK);
m.colored_vertex(bar.right_top(), Color32::WHITE);
m.colored_vertex(bar.right_bottom(), Color32::WHITE);
m.colored_vertex(bar.left_bottom(), Color32::BLACK);
m.add_triangle(0, 1, 2);
m.add_triangle(0, 2, 3);
m
};
p.add(Shape::mesh(mesh));
let out_row = bar.bottom() + 2.0;
let xs = [v[0], mid_position(&v), v[2], v[3], v[4]];
let rows = [in_row, in_row, in_row, out_row, out_row];
let fills = [Color32::from_gray(0x08), Color32::from_gray(0x80), Color32::WHITE, Color32::from_gray(0x08), Color32::WHITE];
let names = ["Level in low", "Level in mid", "Level in high", "Level out low", "Level out high"];
// Mid last, so it wins where it overlaps low or high.
for k in [0usize, 2, 3, 4, 1] {
let x = axis(xs[k].clamp(0.0, 1.0));
let hit = Rect::from_min_size(pos2(x - 7.0, rows[k] - 1.0), vec2(14.0, 13.0));
let resp = ui.interact(hit, ui.scope_id().with(("levels-handle", n.id.0, k)), if locked(ids[k]) { Sense::hover() } else { Sense::drag() });
crate::widgets::name(&resp, egui::Role::Slider, names[k]);
let active = resp.dragged() || resp.hovered();
handle(&p, x, rows[k], fills[k], active, &tk);
if resp.dragged()
&& let Some(ptr) = resp.interact_pointer_pos()
{
let nv = drag_value(&v, k, unaxis(ptr.x));
if (nv - v[k]).abs() > 1e-5 {
app.run("graph.node.param", json!({"id": n.id.0, "param": ids[k], "value": nv}));
}
}
resp.on_hover_text(format!("{}: {:.3}", tr(names[k]), v[k]));
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn histogram_counts_every_value_once_per_channel() {
let gray = Image::gray(4, 4, |x, _| x as f32 / 3.0);
let h = histogram(&gray);
assert_eq!(h.len(), 1);
assert_eq!(h[0].iter().sum::<u32>(), 16);
assert_eq!((h[0][0], h[0][85], h[0][170], h[0][255]), (4, 4, 4, 4));
let color = Image::filled(2, 2, Kind::Color, [2.0, f32::NAN, -1.0, 0.5]);
let h = histogram(&color);
assert_eq!(h.len(), 3);
// Out of range and NaN values land in the end bins.
assert_eq!((h[0][255], h[1][0], h[2][0]), (4, 4, 4));
// The scale ignores the end bins when there is anything in between.
assert_eq!(scale(&[[0; BINS]]), 1.0);
}
#[test]
fn input_handles_do_not_cross_and_mid_follows_the_range() {
let v = [0.2, 0.5, 0.6, 0.0, 1.0];
assert!((mid_position(&v) - 0.4).abs() < 1e-6);
// Low cannot pass high, high cannot pass low.
assert!(drag_value(&v, 0, 0.9) < 0.6);
assert!(drag_value(&v, 2, 0.1) > 0.2);
assert_eq!(drag_value(&v, 0, -1.0), 0.0);
assert_eq!(drag_value(&v, 2, 2.0), 1.0);
// Mid is stored relative to the range, kept inside it.
assert!((drag_value(&v, 1, 0.3) - 0.25).abs() < 1e-5);
assert_eq!(drag_value(&v, 1, 0.0), 0.01);
assert_eq!(drag_value(&v, 1, 1.0), 0.99);
// Output handles may cross (that inverts); NaN never escapes.
assert_eq!(drag_value(&v, 3, 0.8), 0.8);
assert_eq!(drag_value(&v, 4, f32::NAN), 0.0);
// A collapsed range keeps mid centered.
assert_eq!(drag_value(&[0.5, 0.3, 0.5, 0.0, 1.0], 1, 0.7), 0.5);
}
}
+11 -2
View File
@@ -11,9 +11,11 @@ pub mod control;
pub mod cook;
pub mod docking;
pub mod explorer;
pub mod fonts;
pub mod function_editor;
pub mod graph_view;
pub mod i18n;
pub mod levels_editor;
pub mod library;
pub mod menus;
pub mod properties;
@@ -69,6 +71,8 @@ pub struct MaterialCraftApp {
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
next_autosave: f64,
styled: Option<(theme::Brightness, theme::Accent)>,
/// Fallback fonts for Arabic.
pub fonts: fonts::UiFonts,
/// The icon font is installed (it takes effect on the frame after `set_fonts`).
fonts_ready: bool,
}
@@ -78,6 +82,7 @@ impl MaterialCraftApp {
let ui = cc.storage.and_then(|s| eframe::get_value::<UiState>(s, "ui")).unwrap_or_default();
theme::install(&cc.egui_ctx);
let mut app = MaterialCraftApp::headless(session, ui);
i18n::set_language(&app.ui.prefs.language);
app.fonts_ready = true;
app.ui.windows.home = app.ui.prefs.show_home;
app
@@ -108,8 +113,10 @@ impl MaterialCraftApp {
last_time: 0.0,
next_autosave,
styled: None,
fonts: fonts::UiFonts::default(),
fonts_ready: false,
};
i18n::set_language(&app.ui.prefs.language);
app.apply_prefs();
app
}
@@ -157,12 +164,12 @@ impl MaterialCraftApp {
}
self.next_autosave = now + period;
let dir = user_dir("autosave");
let path = dir.join(format!("{}.mcraft", materialcraft_engine::formats::safe_file_name(&self.session.pkg.name)));
let path = dir.join(format!("{}.sbs", materialcraft_engine::formats::safe_file_name(&self.session.pkg.name)));
let pkg = self.session.pkg.clone();
let spawned = std::thread::Builder::new().name("materialcraft-autosave".into()).spawn(move || {
let result = std::fs::create_dir_all(&dir)
.map_err(|e| e.to_string())
.and_then(|_| materialcraft_engine::formats::save_package(&pkg).map_err(|e| e.to_string()))
.and_then(|_| materialcraft_engine::formats::sbs::write_sbs(&pkg).map_err(|e| e.to_string()))
.and_then(|bytes| materialcraft_engine::formats::write_atomic(&path, &bytes).map_err(|e| e.to_string()));
match result {
Ok(()) => log::info!("autosaved {}", path.display()),
@@ -205,6 +212,8 @@ impl MaterialCraftApp {
ctx.request_repaint();
return;
}
i18n::set_language(&self.ui.prefs.language);
self.fonts.update(ctx, &self.ui.prefs.language, self.ui.windows.preferences);
let now = ctx.input(|i| i.time);
let dt = (now - self.last_time) as f32;
if dt > 0.0 {
+8
View File
@@ -252,6 +252,14 @@ pub fn shortcuts(app: &mut MaterialCraftApp, ctx: &egui::Context) {
if !ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Key { pressed: true, .. }))) {
return;
}
// Selected wires take Delete and Backspace before the node commands do, and X swaps them.
if !app.graph.selected_wires.is_empty() {
if ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Delete) | i.consume_key(egui::Modifiers::NONE, egui::Key::Backspace)) {
crate::graph_view::delete_selected_wires(app);
} else if ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::X)) {
crate::graph_view::swap_selected_wires(app);
}
}
let mut table: Vec<(&'static str, KeyboardShortcut)> = CATALOG.iter().filter_map(|i| Some((i.id, parse_shortcut(i.shortcut?)?))).collect();
for c in materialcraft_engine::command_specs() {
if table.iter().any(|(id, _)| *id == c.id) {
+4
View File
@@ -85,6 +85,10 @@ fn node_props(app: &mut MaterialCraftApp, ui: &mut Ui, n: &materialcraft_engine:
return;
}
section(ui, "specific", tr("Specific parameters"), |ui| {
if n.def == "levels" {
crate::levels_editor::show(app, ui, n);
ui.add_space(6.0);
}
let exposed: Vec<(String, String)> =
app.session.graph().map(|g| g.exposed.iter().map(|e| (e.id.clone(), e.label.clone())).collect()).unwrap_or_default();
for p in &def.params {
+6
View File
@@ -11,6 +11,8 @@ use crate::theme::{Accent, Brightness};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct Prefs {
/// UI language code (`i18n::LANGUAGES`).
pub language: String,
pub brightness: Brightness,
pub accent: Accent,
pub ui_scale: f32,
@@ -31,6 +33,7 @@ pub struct Prefs {
impl Default for Prefs {
fn default() -> Self {
Prefs {
language: crate::i18n::os_language().into(),
brightness: Brightness::default(),
accent: Accent::default(),
ui_scale: 1.0,
@@ -105,6 +108,8 @@ pub struct UiState {
pub export_dir: String,
pub export_format: String,
pub export_depth: u32,
/// Export size in pixels; 0 = the graph's own size.
pub export_size: u32,
pub export_pattern: String,
/// Frame the whole graph on the next frame.
#[serde(skip)]
@@ -128,6 +133,7 @@ impl Default for UiState {
export_dir: String::new(),
export_format: "png".into(),
export_depth: 0,
export_size: 0,
export_pattern: "$(graph)_$(identifier)".into(),
frame_all: true,
}
+19 -1
View File
@@ -142,6 +142,15 @@ fn menus(app: &mut MaterialCraftApp, ui: &mut Ui) {
});
ui.menu_button(tr("Display"), |ui| {
ui.checkbox(&mut app.view3d.show_env, tr("Environment background"));
ui.separator();
let mut t = app.session.view3d.transparency;
if ui.checkbox(&mut t, tr("Transparency (alpha)")).changed() {
app.run("view.3d", json!({"transparency": t}));
}
let mut a = app.session.view3d.alpha_view;
if ui.checkbox(&mut a, tr("Show alpha channel")).changed() {
app.run("view.3d", json!({"alphaView": a}));
}
});
ui.menu_button(tr("Renderer"), |ui| {
let mut h = app.session.view3d.height_scale * 100.0;
@@ -201,6 +210,9 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
if let Some(t) = &app.view3d.tex {
p.image(t.id(), frame_rect(rect, app.view3d.tex_size), Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);
}
if app.session.view3d.alpha_view {
p.text(rect.left_top() + vec2(8.0, 6.0), egui::Align2::LEFT_TOP, tr("Alpha channel"), egui::FontId::proportional(11.0), tk.viewport_text);
}
if app.session.material_maps().is_empty() {
p.text(
rect.center_top() + vec2(0.0, 18.0),
@@ -233,6 +245,10 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
});
crate::widgets::name(&r.response, egui::Role::ComboBox, "Scene");
ui.label(egui::RichText::new(format!("{} sRGB / ACES", icon::SUN)).size(11.0).color(tk.text_dim));
let a = app.session.view3d.alpha_view;
if crate::widgets::icon_button(ui, icon::CHECKERBOARD, tr("Show alpha channel"), a, 20.0).clicked() {
app.run("view.3d", json!({"alphaView": !a}));
}
});
});
}
@@ -261,7 +277,7 @@ fn content_key(app: &MaterialCraftApp, w: u32, h: u32, show_env: bool) -> u64 {
use std::hash::{DefaultHasher, Hash, Hasher};
let mut hs = DefaultHasher::new();
let v = &app.session.view3d;
(w, h, show_env, &v.scene, &v.environment, app.session.custom_mesh.as_ref().map(|(n, _)| n)).hash(&mut hs);
(w, h, show_env, &v.scene, &v.environment, app.session.custom_mesh.as_ref().map(|(n, _)| n), v.transparency, v.alpha_view).hash(&mut hs);
for f in [v.yaw, v.pitch, v.distance, v.target[0], v.target[1], v.target[2], v.tiling, v.exposure, v.env_rotation, v.height_scale] {
f.to_bits().hash(&mut hs);
}
@@ -350,6 +366,8 @@ fn inputs(app: &mut MaterialCraftApp, supersample: u32) -> Option<(Arc<Scene>, A
height_scale: v.height_scale,
show_env: app.view3d.show_env,
supersample,
transparency: v.transparency,
alpha_view: v.alpha_view,
..Settings::default()
};
let maps = Maps::from_usages(app.session.material_maps());
+11 -12
View File
@@ -79,6 +79,7 @@ pub fn load(app: &mut MaterialCraftApp, name: &str, bytes: Vec<u8>, bitmap: bool
Ok(()) => {
app.ui.frame_all = true;
app.toast(format!("{} {name}", tr("Opened")), false);
crate::windows::after_open(app);
}
Err(e) => app.toast(format!("{} {name}: {e}", tr("Couldn't open")), true),
}
@@ -91,16 +92,14 @@ pub fn dropped(app: &mut MaterialCraftApp, ctx: &egui::Context, file: &egui::Dro
#[cfg(not(target_arch = "wasm32"))]
{
let _ = ctx;
let lower = name.to_ascii_lowercase();
if (lower.ends_with(".sbs") || lower.ends_with(".mcraft")) && file.path().is_file() {
// Open from the path so an SBS package finds the bitmaps kept next to it.
crate::windows::open_path(app, &file.path().display().to_string());
return;
}
match file.bytes() {
Ok(bytes) => {
let package = name.to_ascii_lowercase().ends_with(".mcraft");
load(app, &name, bytes, false);
if package {
let path = file.path().display().to_string();
app.session.path = Some(path.clone());
app.ui.add_recent(&path);
}
}
Ok(bytes) => load(app, &name, bytes, false),
Err(e) => app.toast(format!("{} {name}: {e}", tr("Couldn't open")), true),
}
}
@@ -173,9 +172,9 @@ mod web {
pick(ctx, "Images", materialcraft_engine::formats::IMAGE_EXTENSIONS, Pick::Bitmap);
}
/// File ▸ Save: download the package as `<name>.mcraft`.
/// File ▸ Save: download the package as `<name>.sbs` (bitmaps embedded).
pub fn save(app: &mut MaterialCraftApp) {
let name = format!("{}.mcraft", materialcraft_engine::formats::safe_file_name(&app.session.pkg.name));
let name = format!("{}.sbs", materialcraft_engine::formats::safe_file_name(&app.session.pkg.name));
match materialcraft_engine::file_cmds::save_bytes(&app.session).map_err(|e| e.to_string()).and_then(|b| download(&name, &b)) {
Ok(()) => {
app.session.modified = false;
@@ -198,7 +197,7 @@ mod web {
/// Export outputs: one file downloads as is, several as `<graph>_outputs.zip`.
pub fn export(app: &mut MaterialCraftApp, params: &serde_json::Value) {
let result = materialcraft_engine::file_cmds::export_params(&app.session, params)
.and_then(|(gi, ext, pattern, depth)| materialcraft_engine::file_cmds::export_outputs(&app.session, gi, &ext, &pattern, depth))
.and_then(|(gi, ext, pattern, depth, size)| materialcraft_engine::file_cmds::export_outputs(&app.session, gi, &ext, &pattern, depth, size))
.map_err(|e| e.to_string())
.and_then(|files| {
let files: Vec<(String, Vec<u8>)> = files.into_iter().map(|f| (f.file, f.bytes)).collect();
+63 -16
View File
@@ -105,7 +105,8 @@ fn modal(ctx: &egui::Context, id: &str, title: &str, open: &mut bool, size: egui
.collapsible(false)
.resizable(false)
.default_size(size)
.anchor(egui::Align2::CENTER_CENTER, vec2(0.0, 0.0))
.pivot(egui::Align2::CENTER_CENTER)
.default_pos(ctx.content_rect().center())
.show(ctx, body);
}
@@ -197,7 +198,7 @@ fn new_graph(app: &mut MaterialCraftApp, ctx: &egui::Context) {
fn export(app: &mut MaterialCraftApp, ctx: &egui::Context) {
let mut open = true;
let mut go = false;
modal(ctx, "export", tr("Export outputs"), &mut open, vec2(460.0, 260.0), |ui| {
modal(ctx, "export", tr("Export outputs"), &mut open, vec2(460.0, 290.0), |ui| {
let tk = Tokens::get(ui.ctx());
let g = app.session.graph().map(|g| g.name.clone()).unwrap_or_default();
ui.label(RichText::new(format!("{}: {g}", tr("Graph"))).strong());
@@ -229,6 +230,20 @@ fn export(app: &mut MaterialCraftApp, ctx: &egui::Context) {
ui.selectable_value(&mut app.ui.export_depth, d, tr(l));
}
});
let graph_size = app.session.graph().map_or(String::new(), |g| {
let [w, h] = g.size_px();
format!("{} ({w} x {h})", tr("Graph's size"))
});
let size_label = match app.ui.export_size {
0 => graph_size.clone(),
px => format!("{px} px"),
};
crate::widgets::combo(ui, tr("Resolution"), size_label, |ui| {
ui.selectable_value(&mut app.ui.export_size, 0, graph_size);
for px in [256u32, 512, 1024, 2048, 4096, 8192] {
ui.selectable_value(&mut app.ui.export_size, px, format!("{px} px"));
}
});
ui.horizontal(|ui| {
ui.label(tr("File names"));
let r = ui.add(egui::TextEdit::singleline(&mut app.ui.export_pattern).desired_width(260.0));
@@ -250,7 +265,7 @@ fn export(app: &mut MaterialCraftApp, ctx: &egui::Context) {
app.toast(tr("Choose a folder to export to"), true);
} else {
let depth = if app.ui.export_depth == 0 { Value::Null } else { json!(app.ui.export_depth) };
let p = json!({"dir": app.ui.export_dir, "format": app.ui.export_format, "pattern": app.ui.export_pattern, "depth": depth});
let p = json!({"dir": app.ui.export_dir, "format": app.ui.export_format, "pattern": app.ui.export_pattern, "depth": depth, "size": if app.ui.export_size == 0 { Value::Null } else { json!(app.ui.export_size) }});
#[cfg(target_arch = "wasm32")]
{
crate::web_files::export(app, &p);
@@ -271,8 +286,17 @@ fn export(app: &mut MaterialCraftApp, ctx: &egui::Context) {
fn preferences(app: &mut MaterialCraftApp, ctx: &egui::Context) {
let mut open = true;
modal(ctx, "prefs", tr("Preferences"), &mut open, vec2(380.0, 300.0), |ui| {
modal(ctx, "prefs", tr("Preferences"), &mut open, vec2(380.0, 340.0), |ui| {
let p = &mut app.ui.prefs;
let current_lang = crate::i18n::current();
crate::widgets::combo(ui, tr("Language"), current_lang.name, |ui| {
for l in &crate::i18n::LANGUAGES {
if ui.selectable_label(p.language == l.code, l.name).clicked() {
p.language = l.code.to_owned();
crate::i18n::set_language(&p.language);
}
}
});
crate::widgets::combo(ui, tr("Brightness"), tr(p.brightness.label()), |ui| {
for b in Brightness::ALL {
ui.selectable_value(&mut p.brightness, b, tr(b.label()));
@@ -449,14 +473,22 @@ fn home(app: &mut MaterialCraftApp, ctx: &egui::Context) {
pub fn console(app: &mut MaterialCraftApp, ui: &mut Ui) {
let tk = Tokens::get(ui.ctx());
let console_line = |text: String, color: Color32| RichText::new(text).monospace().size(11.0).color(color);
egui::ScrollArea::vertical().stick_to_bottom(true).auto_shrink([false, false]).show(ui, |ui| {
for l in &app.session.log {
ui.label(RichText::new(l).monospace().size(11.0).color(tk.text));
for line in &app.session.log {
let warning = line.starts_with(materialcraft_engine::WARNING_PREFIX);
ui.label(console_line(line.clone(), if warning { tk.warning } else { tk.text }));
}
for (id, r) in &app.session.cooked.nodes {
if let Some(e) = &r.error {
ui.label(RichText::new(format!("node {}: {e}", id.0)).monospace().size(11.0).color(tk.danger));
}
// Placeholders for missing SBS nodes are already listed in the warnings, so they get one line
let (failed, placeholders) = app.session.cook_failures();
for (id, error) in failed {
ui.label(console_line(format!("node {}: {error}", id.0), tk.danger));
}
if placeholders > 0 {
let text = format!("{placeholders} {}", tr("placeholder node(s) stand in for nodes MaterialCraft doesn't have yet (see the warnings above)"));
ui.label(console_line(text, tk.warning));
}
});
}
@@ -510,8 +542,17 @@ pub fn function_summary(app: &mut MaterialCraftApp, ui: &mut Ui, node: NodeId, p
});
}
/// Extensions File ▸ Open reads: packages and portable materials (opening their source package).
pub const OPEN_EXTS: &[&str] = &["mcraft", MATERIAL_EXT];
/// Extensions File ▸ Open reads: SBS (the main format) and `.mcraft` packages, and materials (their source package).
pub const OPEN_EXTS: &[&str] = &["sbs", "mcraft", MATERIAL_EXT];
/// After a package opened with warnings (an SBS file using nodes MaterialCraft lacks, say), bring the Console forward.
pub fn after_open(app: &mut MaterialCraftApp) {
let warning_count = app.session.load_warnings.len();
if warning_count > 0 {
app.ui.dock.focus(crate::docking::Panel::Console);
app.toast(format!("{} {warning_count} {}", tr("Opened with"), tr("warnings: see the Console")), false);
}
}
/// File menu actions that need a file dialog. Returns true when handled.
pub fn file_action(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) -> bool {
@@ -521,7 +562,7 @@ pub fn file_action(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) ->
{
match id {
"file.open" => {
if let Some(p) = rfd::FileDialog::new().add_filter("MaterialCraft package or material", OPEN_EXTS).pick_file() {
if let Some(p) = rfd::FileDialog::new().add_filter("SBS or MaterialCraft package, or material", OPEN_EXTS).pick_file() {
open_path(app, &p.display().to_string());
}
true
@@ -535,9 +576,14 @@ pub fn file_action(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) ->
true
}
"file.save" | "file.saveAs" => {
let name = format!("{}.mcraft", materialcraft_engine::formats::safe_file_name(&app.session.pkg.name));
if let Some(p) = rfd::FileDialog::new().set_file_name(name).add_filter("MaterialCraft package", &["mcraft"]).save_file() {
let path = p.display().to_string();
let name = format!("{}.sbs", materialcraft_engine::formats::safe_file_name(&app.session.pkg.name));
if let Some(p) = rfd::FileDialog::new()
.set_file_name(name)
.add_filter("SBS package", &["sbs"])
.add_filter("MaterialCraft package (older format)", &["mcraft"])
.save_file()
{
let path = materialcraft_engine::file_cmds::package_path(&p.display().to_string());
if app.run("file.save", json!({"path": path})).is_some() {
app.ui.add_recent(&path);
app.toast(format!("{} {path}", tr("Saved")), false);
@@ -598,5 +644,6 @@ pub fn open_path(app: &mut MaterialCraftApp, path: &str) {
app.ui.add_recent(path);
app.ui.frame_all = true;
app.toast(format!("{} {path}", tr("Opened")), false);
after_open(app);
}
}
+76
View File
@@ -0,0 +1,76 @@
//! Home and export dialogs start centered, but their title bars must allow movement.
use egui::{Event, Modifiers, PointerButton, Rect, pos2, vec2};
use egui_kittest::Harness;
use materialcraft_ui_egui::{MaterialCraftApp, UiState};
type State = (MaterialCraftApp, Rect);
fn harness(id: &'static str, render: bool) -> Harness<'static, State> {
let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), UiState::default());
app.ui.windows.home = id == "home";
app.ui.windows.export = id == "export";
let builder = Harness::builder().with_size(vec2(1600.0, 960.0)).with_pixels_per_point(1.0);
let builder = if render { builder.wgpu() } else { builder };
let mut h = builder.build_ui_state(
move |ui, (app, rect): &mut State| {
app.step(&ui.ctx().clone());
app.draw(ui);
*rect = ui.ctx().memory(|m| m.area_rect(egui::Id::unique(id))).unwrap_or(Rect::NOTHING);
},
(app, Rect::NOTHING),
);
h.run_steps(10);
h
}
fn drag_title(h: &mut Harness<'static, State>) {
let from = h.state().1.min + vec2(120.0, 12.0);
h.event(Event::PointerMoved(from));
h.step();
h.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
h.step();
for step in 1..=8 {
h.event(Event::PointerMoved(from + vec2(10.0, 7.5) * step as f32));
h.step();
}
h.event(Event::PointerButton { pos: from + vec2(80.0, 60.0), button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
h.run_steps(10);
}
#[test]
fn home_and_export_can_be_dragged_and_keep_their_position() {
for id in ["home", "export"] {
let mut h = harness(id, false);
let before = h.state().1;
assert!(before.is_finite());
assert!(before.center().distance(pos2(800.0, 480.0)) < 3.0, "{id}: initial rectangle {before:?}");
drag_title(&mut h);
let moved = h.state().1;
assert!(moved.min.distance(before.min + vec2(80.0, 60.0)) < 8.0, "{id}: did not follow the drag: {before:?} -> {moved:?}");
// Later frames and reopening the same dialog must not snap it back to the center.
h.state_mut().0.ui.windows.home = false;
h.state_mut().0.ui.windows.export = false;
h.run_steps(3);
h.state_mut().0.ui.windows.home = id == "home";
h.state_mut().0.ui.windows.export = id == "export";
h.run_steps(10);
assert!(h.state().1.min.distance(moved.min) < 1.0, "{id}: reopening lost the dragged position");
h.set_size(vec2(1500.0, 900.0));
h.run_steps(10);
assert!(h.state().1.min.distance(moved.min) < 1.0, "{id}: resizing recentered the dialog");
}
}
#[test]
#[ignore = "requires an offscreen GPU; run explicitly with --ignored"]
fn dialog_drag_snapshots() {
let dir = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").expect("set MC_SNAPSHOT_DIR"));
std::fs::create_dir_all(&dir).unwrap();
for id in ["home", "export"] {
let mut h = harness(id, true);
h.render().unwrap().save(dir.join(format!("{id}-centered.png"))).unwrap();
drag_title(&mut h);
h.render().unwrap().save(dir.join(format!("{id}-moved.png"))).unwrap();
}
}
+98 -1
View File
@@ -5,7 +5,10 @@
use std::time::Duration;
use egui::vec2;
use egui_kittest::Harness;
use egui_kittest::{
Harness,
kittest::{By, Queryable},
};
use materialcraft_ui_egui::{MaterialCraftApp, UiState};
use serde_json::json;
@@ -33,6 +36,55 @@ fn save(h: &mut Harness<'static, MaterialCraftApp>, dir: &std::path::Path, name:
println!("wrote {}", dir.join(format!("{name}.png")).display());
}
#[test]
#[ignore = "requires an offscreen GPU; run explicitly with --ignored"]
fn explorer_export_opens_the_clicked_graph() {
let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), UiState::default());
app.run("graph.duplicate", json!({"graph": 0}));
app.session.pkg.graphs[1].name = "Export target".into();
app.run("graph.open", json!({"graph": 0}));
let mut h = harness(app, 1600.0, 960.0);
settle(&mut h, 5);
h.get_by_label("Export target").click_secondary();
settle(&mut h, 3);
h.get_all(By::new().label("Export outputs...")).last().unwrap().click();
settle(&mut h, 3);
assert_eq!(h.state().session.graph, 1);
assert!(h.state().ui.windows.export);
if let Some(dir) = std::env::var_os("MC_SNAPSHOT_DIR").map(std::path::PathBuf::from) {
std::fs::create_dir_all(&dir).unwrap();
save(&mut h, &dir, "explorer-export");
}
}
/// The startup graph stays empty through real UI frames; templates are still available on demand.
#[test]
#[ignore = "requires an offscreen GPU; run explicitly with --ignored"]
fn empty_startup_can_create_a_template() {
let app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default());
let mut h = harness(app, 1600.0, 960.0);
settle(&mut h, 40);
assert_eq!(h.state().session.pkg.graphs.len(), 1);
assert!(h.state().session.graph().unwrap().nodes.is_empty());
assert!(h.state().graph.rects.is_empty());
if let Some(dir) = std::env::var_os("MC_SNAPSHOT_DIR").map(std::path::PathBuf::from) {
std::fs::create_dir_all(&dir).unwrap();
save(&mut h, &dir, "empty-startup");
}
h.get_by_label("New graph...").click();
settle(&mut h, 4);
h.get_by_label("Brick wall").click();
settle(&mut h, 4);
h.get_by_label("Create").click();
settle(&mut h, 40);
assert_eq!(h.state().session.pkg.graphs.len(), 2);
assert!(!h.state().session.graph().unwrap().nodes.is_empty());
assert!(!h.state().graph.rects.is_empty());
if let Some(dir) = std::env::var_os("MC_SNAPSHOT_DIR").map(std::path::PathBuf::from) {
save(&mut h, &dir, "chosen-template");
}
}
#[test]
#[ignore]
fn snapshots() {
@@ -63,6 +115,26 @@ fn snapshots() {
save(&mut h, &dir, "new-graph");
h.state_mut().ui.windows.new_graph = false;
// A cut-out material in the 3D view (an opacity output), a reroute dot pulled out of a wire
// and another wire selected; then the alpha channel view.
h.state_mut().run("file.new", json!({"template": "wood", "size": 512}));
let holes = h.state_mut().run("graph.node.add", json!({"def": "grid_lines", "at": [0, -260]})).unwrap()["id"].as_u64().unwrap();
let out = h.state_mut().run("graph.node.add", json!({"def": "output", "at": [420, -260], "connectFrom": {"node": holes}, "params": {"usage": 7}})).unwrap()
["id"]
.as_u64()
.unwrap();
h.state_mut().run("graph.wire.insertDot", json!({"to": out, "toPort": "input", "at": [210, -330]}));
let wire = h.state().session.graph().unwrap().connections.iter().find(|c| c.to.0 != out).map(|c| (c.to, c.to_port.clone()));
h.state_mut().graph.selected_wires = wire.into_iter().collect();
h.state_mut().run("view.3d", json!({"scene": "sphere"}));
h.state_mut().ui.frame_all = true;
settle(&mut h, 60);
save(&mut h, &dir, "alpha-transparency");
h.state_mut().run("view.3d", json!({"alphaView": true}));
settle(&mut h, 40);
save(&mut h, &dir, "alpha-channel");
h.state_mut().run("view.3d", json!({"alphaView": false, "scene": "rounded_cube"}));
// A pixel processor drawing rings, with its function graph open.
h.state_mut().run("file.new", json!({"template": "empty", "name": "Rings"}));
let f = json!({"t": "function", "v": {"nodes": [
@@ -85,6 +157,31 @@ fn snapshots() {
h.state_mut().ui.frame_all = true;
settle(&mut h, 40);
save(&mut h, &dir, "function-editor");
h.state_mut().fn_editor = None;
// The Levels editor: the input histogram under the transfer curve, with its handles.
h.state_mut().run("file.new", json!({"template": "stone_tiles", "size": 512}));
let levels = {
let g = h.state().session.graph().unwrap();
g.nodes.iter().find(|n| n.def == "levels" && g.connections.iter().any(|c| c.to == n.id)).map(|n| n.id.0)
};
if let Some(id) = levels {
h.state_mut().run("graph.select", json!({"ids": [id]}));
h.state_mut().run("graph.node.param", json!({"id": id, "param": "in_low", "value": 0.3}));
h.state_mut().run("graph.node.param", json!({"id": id, "param": "in_mid", "value": 0.35}));
h.state_mut().run("graph.node.param", json!({"id": id, "param": "in_high", "value": 0.85}));
h.state_mut().run("view.2d", json!({"node": id}));
}
h.state_mut().ui.frame_all = true;
settle(&mut h, 40);
save(&mut h, &dir, "levels-editor");
// An SBS file with nodes MaterialCraft doesn't have: placeholders on the canvas, the warnings
// in the Console, which comes forward by itself.
let sample = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/sbs/all_nodes.sbs");
materialcraft_ui_egui::windows::open_path(h.state_mut(), sample.to_str().unwrap());
settle(&mut h, 60);
save(&mut h, &dir, "sbs-warnings");
}
/// Steady-state UI build time per frame with each panel closed in turn (release):
+24 -5
View File
@@ -18,12 +18,14 @@ L1 nodes the node library: NodeDef (ports, parameters, category, cook fn) f
L2 eval cooking: topological order, output sizes (relative to input / parent, absolute, preview
cap), parameter resolution (defaults, overrides, bindings to exposed inputs), the
content-addressed LRU cache, graph instances (sub-graphs, recursion-guarded)
L2 formats .mcraft packages (zip: package.json + resources/), .mcmat portable materials, bitmap
L2 formats .sbs packages (the main format, sbs.rs), .mcraft packages (zip: package.json +
resources/), .mcmat portable materials, bitmap
decode, texture encode (PNG/JPEG/TGA/TIFF/BMP/WEBP/EXR/HDR at 8/16/32 bits), atomic writes
L3 engine Session (package, open graph, selection, 2D/3D view state, snapshot undo, cache),
the command registry, inspect, sample materials and graph templates
L3 render the 3D view: BVH ray casts, parallax occlusion from the height output, GGX PBR with
prefiltered IBL + SH diffuse, ACES tone mapping; procedural environments
prefiltered IBL + SH diffuse, alpha transparency (layered ray compositing) and an
alpha channel view, ACES tone mapping; procedural environments
L4 automation MCP server (rmcp), JSON-lines RPC (stdio/TCP with token), bridge client, workspace sandbox
L5 ui-egui the egui shell: docking (craft-ui), graph editor, library, properties, 2D/3D views,
dialogs, menus, control channel with synthetic input
@@ -61,16 +63,33 @@ drag) into one undo step. See [control-protocol.md](control-protocol.md).
`MaterialCraftApp` owns the session and `UiState` (serde, persisted by eframe, readable and writable
through `ui.inspect` / `ui.set`). The dock (craft-ui) hosts eight panels around the protected graph
panel. The graph editor lays nodes out in graph space, draws cards with thumbnails from the cook
results (uploaded once per cache key), wires as cubic beziers between typed ports, and turns
gestures into commands only when they complete. The 3D view renders with `materialcraft-render`
results (uploaded once per cache key), wires as cubic beziers between typed ports (hit-tested
against the curve, so wires can be selected, deleted, swapped or split with a reroute dot), and turns
gestures into commands only when they complete. See [wires-and-alpha.md](wires-and-alpha.md). The 3D view renders with `materialcraft-render`
on the CPU: half resolution while the camera moves, 2×2 supersampled when it rests.
`crates/ui-egui/tests/snapshot.rs` renders the real UI offscreen with egui_kittest + wgpu for visual
checks and README screenshots.
The properties panel builds every parameter editor from the node catalog; the Levels node adds a
histogram editor with range handles on top of its sliders ([levels-editor.md](levels-editor.md)).
## Files
A `.mcraft` package is a zip: `package.json` (the serde `Package`, format version 1) and
SBS (`.sbs`, `formats/src/sbs.rs`) is the main project format: XML with the package's graphs, nodes,
wires, parameters, graph inputs and outputs, frames and comments, and bitmaps embedded as
zlib/base64 data. MaterialCraft writes the SBS data plus, in a trailing XML comment, its own exact
copy of the package with a hash of the `<content>` it belongs to; reading uses the exact copy while
the hash matches (so nothing MaterialCraft-specific is lost) and the SBS data otherwise. Reading never
fails on what MaterialCraft lacks: atomic filters map to atomic nodes, library nodes map by name,
instances of graphs in the same file become graph instances, and anything else becomes a
`missing_node` placeholder (`core::MISSING_NODE`) that keeps its ports, wires and raw SBS parameters,
cooks to a soft error, and is written back unchanged. Every gap is a warning in
`Session::load_warnings`, the Console (`Session::warn`) and `session.inspect` (`package.warnings`).
Bitmaps an SBS file keeps next to it load from its folder only (`file_cmds::linked_files`).
A `.mcraft` package (the older format, still read and written: packages opened from a `.mcraft`
save back to it) is a zip: `package.json` (the serde `Package`, format version 1) and
`resources/<name>` for embedded bitmaps. Node parameters are stored only where they differ from the
catalog defaults, so new defaults reach old files and files stay small.
+6 -3
View File
@@ -25,7 +25,7 @@ Agents drive MaterialCraft three ways, all dispatching the same engine commands:
| `session.inspect` | all | package, graphs, the open graph's nodes (def, params, bindings, base, ports, cook error/size/mean/ms), wires, frames, comments, pins, exposed inputs, views, history |
| `package.open {path}` / `package.save {path?}` | headless | workspace-scoped package I/O |
| `bitmap.import {path, name?}` | headless | embed an image as a resource |
| `outputs.export {dir, format?, pattern?, depth?, graph?}` | headless | cook at full size and write every output |
| `outputs.export {dir, format?, pattern?, depth?, size?, graph?}` | headless | cook at full size and write every output |
| `render {view?, width?, height?, yaw?, pitch?, scene?, node?, port?, full?, tiling?, hq?, displacement?}` | headless | PNG (base64) of the 3D view or of one node; `hq` is the beauty render (displaced mesh, ray-traced AO, shadowed key light, 3×3 supersampling), `displacement` its depth in scene radii |
| `ui.inspect` | app | UI state, the graph view rectangle, every node's screen rectangle, every port's screen position, fps, toasts |
| `ui.menu.list` / `ui.menu.invoke {id}` | app | the menu catalog; behave like a click |
@@ -62,13 +62,15 @@ Types: `move`, `down`, `up`, `click`, `doubleClick`, `drag`, `scroll`, `key` (eg
| `file.new` | `{template?, name?, size?}`; templates from `graph.templates` (`empty`, `pbr`, `bricks`, `stone_tiles`, `wood`, `rusty_metal`, `fabric`, `ground`) |
| `graph.node.add` | `{def, at?, params?, connectFrom?: {node, port?}, label?}` |
| `graph.connect` / `graph.disconnect` | `{from, fromPort?, to, toPort?}` / `{to, toPort}` |
| `graph.wire.insertDot` | `{to, toPort, at?}`: split the wire feeding `to.toPort` with a reroute Dot node at `at` (graph point, default midway), selected |
| `graph.wire.swap` / `graph.wire.delete` | `{wires: [{to, toPort}, ...]}`: swap (two) or reverse (more, in input order) where the wires come from / delete them, one undo step each |
| `graph.node.param` | `{id?, param, value}`: numbers, `[x, y]`, `"#rrggbb"`, enum index, curve `[[x, y], …]`, gradient `[[pos, color], …]`, or a typed value `{"t": "function", "v": {...}}` |
| `graph.node.base` | `{id?, sizeMode?, size?, format?, seed?, tiling?}` |
| `graph.exposed.add` / `graph.exposed.set` | `{id, label?, default?, bind?: {node, param}}` / `{id, value}` |
| `graph.node.function` | `{id?, param, function}` drives a parameter by a function graph of the graph's inputs (dynamic parameter); `{id?, param, remove: true}` removes it |
| `graph.preset.save` / `.apply` / `.delete` | `{name}`: store, restore or remove the current input values |
| `graph.createFromSelection` | `{name?, ids?}`: move nodes into a sub-graph and replace them with an instance |
| `view.2d` / `view.3d` | which node the 2D view shows, channel, tiling, histogram; scene, environment, camera, tiling, parallax depth |
| `view.2d` / `view.3d` | which node the 2D view shows, channel, tiling, histogram; scene, environment, camera, tiling, parallax depth, `transparency` (see through where the alpha is below one: the opacity output, else the base color's alpha), `alphaView` (show the alpha channel) |
| `view.3d.loadMesh` | `{path}` shows an OBJ, glTF or GLB mesh (scene `custom`) |
| `library.list` | `{filter?, category?}`: every node with ports and parameters |
@@ -116,7 +118,8 @@ each has its own reader and writer (`crates/formats/src/material.rs` here), so k
| `file.exportMaterial` | `{path, graph?, size? (px), values? {input: value}, inputs? {identifier: image path}}`: cook and write a `.mcmat`. TextureCraft runs `materialcraft-cli run source.mcraft file.exportMaterial {...}` to re-cook at its texture set's resolution with its own values and baked mesh maps |
| `file.sendToTextureCraft` | `{graph?}`: export into TextureCraft's library folder (`Documents/TextureCraft/library`), where its shelf lists it |
| `graph.input.bind` / `graph.input.unbind` | `{identifier, resource? \| path?}` / `{identifier}`: a preview image for an input node (a mesh map exported from TextureCraft), saved in the package |
| `file.open` | also opens a `.mcmat`'s source package, on its graph, with no file name |
| `file.open` | opens `.sbs` (by content) and `.mcraft` packages, and a `.mcmat`'s source package, on its graph, with no file name. Returns `warnings`: what an SBS file holds that MaterialCraft can't read yet (missing nodes are kept as placeholders); also in `session.inspect` as `package.warnings` |
| `file.save` | `{path?}`: SBS unless the file is `.mcraft`; `.sbs` is appended when `path` has no package extension |
## MCP tools
+8 -5
View File
@@ -1,14 +1,16 @@
# File format parity
> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-02 · **Change:** minor (`.mcmat` portable materials) · **Target:** the professional node-based material workflow
> **Last reviewed:** 2026-11-04 · **Last updated:** 2026-11-04 · **Change:** major (SBS is the main project format) · **Target:** the professional node-based material workflow
MaterialCraft does not read or write the reference app's proprietary package or archive formats
(a non-goal of the clean room). It has its own package format and reads and writes the open image
formats material artists exchange.
SBS packages are MaterialCraft's main project format (issue #49), read and written with its own
clean-room code from the format's public documentation and sample files. The older `.mcraft`
package is still read and written. MaterialCraft also reads and writes the open image formats
material artists exchange.
| Format | Read | Write | Fidelity | Tests |
|---|---|---|---|---|
| `.mcraft` package (zip: `package.json` + `resources/`) | Yes | Yes | Lossless (graphs, parameters, frames, comments, pins, exposed inputs, embedded bitmaps) | `formats::tests::package_round_trip`, engine `package_save_and_open_round_trip` |
| `.sbs` package (XML), the main format | Yes: atomic filters, library nodes with a MaterialCraft node of the same name (88 of the 491 in `assets/sbs/all_nodes.sbs`), graph instances, graph inputs/outputs, exposed values, parameters linked to inputs, base parameters, frames, comments, embedded and linked bitmaps and SVGs. Anything else (missing nodes, curve points, gradient keys, function graphs, environment maps) is a Console warning; missing nodes stay as placeholders | Yes: SBS data with bitmaps embedded, plus MaterialCraft's exact copy | Lossless for files MaterialCraft saved (exact copy, guarded by a content hash); placeholders round-trip their SBS data | `formats::sbs::tests`, engine `sbs_is_the_default_save_format_and_mcraft_still_works`, `an_sbs_file_with_missing_nodes_opens_softly` |
| `.mcraft` package (zip: `package.json` + `resources/`), older | Yes | Yes | Lossless (graphs, parameters, frames, comments, pins, exposed inputs, embedded bitmaps) | `formats::tests::package_round_trip`, engine `package_save_and_open_round_trip` |
| PNG | Yes (8/16-bit, gray and color) | Yes (8/16-bit) | 16-bit gray round-trips within 1/65535 | `formats::tests::export_every_format` |
| JPEG | Yes | Yes (8-bit) | Lossy | same |
| TGA | Yes | Yes (8-bit) | Lossless | same |
@@ -28,5 +30,6 @@ roughness, metallic, height, ambient occlusion, opacity) linear.
| Date | Change | Summary |
|---|---|---|
| 2026-11-04 | major | SBS packages become the main project format; `.mcraft` kept |
| 2026-11-02 | minor | `.mcmat` portable materials replace the published-archive gap |
| 2026-11-02 | major | First version |
Binary file not shown.

After

Width:  |  Height:  |  Size: 363 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 372 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 660 KiB

+76
View File
@@ -0,0 +1,76 @@
# The Levels editor
The **Levels** node remaps its input: it stretches the input range (*Level in low* to *Level in
high*), bends the midtones (*Level in mid*) and squeezes the result into the output range (*Level
out low* to *Level out high*). Select a Levels node and the **Specific parameters** section of the
properties panel shows a visual editor above the usual sliders. This is a clean-room
implementation.
<p align="center">
<img src="images/materialcraft-levels-editor.png" alt="The stone tiles material with a Levels node selected: in the properties panel, a histogram of the node's input with the levels curve over it, three input handles under it and two output handles under a black-to-white bar" width="100%">
<br><sub>The Levels editor: the input histogram, the transfer curve and the handles</sub>
</p>
## What it shows
- **The input histogram**: how many pixels of the image feeding the node have each value, in
256 bins over 0..1. A grayscale input shows one gray histogram; a color input shows red, green
and blue on top of each other. Values outside 0..1 count in the end bins. The bar heights scale
to the tallest bin *between* pure black and pure white, because masks pile up at the ends and
would flatten everything else. Without an input wire the editor says so.
- **The clipped areas**: the parts of the histogram outside the input range are darkened. Those
values all become the output low or high.
- **The transfer curve** (accent line): the output value for every input value, so the effect
of all five parameters can be read at a glance.
The histogram is computed once per cooked result of the input and reused until that result
changes.
## Handles
| Handle | Row | Parameter | Behavior |
|---|---|---|---|
| Black triangle | under the histogram | *Level in low* | Cannot pass the high handle |
| Gray triangle | under the histogram | *Level in mid* | Sits where the midtone acts: `in low + in mid × (in high − in low)`. It moves with the low and high handles and stays strictly inside the range (stored as 0.01..0.99) |
| White triangle | under the histogram | *Level in high* | Cannot pass the low handle |
| Black triangle | under the gradient bar | *Level out low* | Free |
| White triangle | under the gradient bar | *Level out high* | Free; dragging it left of the low handle inverts the output |
- Hovering a handle highlights it and shows its parameter and value.
- Dragging a handle sets its parameter live. One drag is one undo step.
- A parameter bound to a graph input or driven by a function shows its handle but cannot be
dragged; edit it where it is driven.
- The sliders below still give exact values and the right-click menu (reset, expose, bind,
function).
## What changed in the node
- *Level in mid* was always relative to the input range (0.5 = linear), but the only editor was
an absolute 0..1 slider, so its position meant nothing next to *Level in low* and *Level in
high*. The gray handle now shows where it really acts.
- Dragging the input low handle past the high one used to flip the remap without warning. The
editor keeps them apart. The sliders and commands still accept any values, so existing files
cook exactly as before.
- `levels_fn` no longer lets a NaN (from an input or a hostile parameter) spread through the
graph: it is treated as 0.
## For agents and scripts
The editor only sets the node's existing parameters, so there is nothing new to drive:
```json
{"id": 1, "method": "command.run", "params": {"id": "graph.node.param", "params": {"id": 42, "param": "in_mid", "value": 0.35}}}
```
`session.inspect` reports the parameters and the input's cooked `mean`; the 2D view's histogram
(`view.2d {"histogram": true}`) shows the node's output.
## Implementation and tests
- `crates/ui-egui/src/levels_editor.rs`: `histogram`, `values`, `mid_position`, `drag_value`
(the handle constraints) and the drawing; called from `properties.rs` for `levels` nodes.
- `crates/nodes/src/atomic.rs`: the NaN guard in `levels_fn`.
- Tests: `levels_editor::tests` (histogram counts, end bins and NaN; handle constraints and the
relative mid), `atomic::levels_tests` (identity, stretch and clip, the relative mid, output
range and inversion, threshold, NaN), and the `levels-editor` scene of the `snapshots` UI test,
which renders the screenshot above.
+2
View File
@@ -8,6 +8,7 @@ so catalogs can be added without touching callers. Today only English ships.
| Language | Code | Status | Notes |
|---|---|---|---|
| English | `en` | Complete | Source language |
| Arabic | `ar` | Complete | Full UI translation table (`crates/ui-egui/src/i18n/ar.rs`), system font fallbacks (Segoe UI / SF Arabic / Noto Sans Arabic), live language picker in Preferences |
| French, German, Spanish, Portuguese (Brazil), Italian | `fr`, `de`, `es`, `pt-br`, `it` | Not started | Planned with the shared craft-i18n catalogs |
| Japanese, Chinese (Simplified), Korean | `ja`, `zh-hans`, `ko` | Not started | Needs the craft-fonts CJK faces (`CRAFT_FONTS_DIR`), as in TextureCraft |
@@ -15,4 +16,5 @@ so catalogs can be added without touching callers. Today only English ships.
| Date | Change | Summary |
|---|---|---|
| 2026-11-03 | minor | Add complete Arabic (`ar`) UI localization and font fallbacks |
| 2026-11-02 | major | First version |
+3 -3
View File
@@ -8,15 +8,15 @@ automation + tests), weighted by how much of the day each area carries. **Remain
| Area | Weight | Done | What works | Main gaps |
|---|---:|---:|---|---|
| Graph editing | 15 | 75% | Pan/zoom canvas with grid; node cards with headers by category, live thumbnails and size/format labels; typed ports; bezier wires; drag to wire, re-route and unplug; drop a wire on empty canvas to add a wired node; box/Ctrl/Shift selection; move; frames (move with contents, resize), comments (inline edit), navigation pins; node search (Space, double-click); library drag and drop; align and distribute; copy/cut/paste/duplicate (with or without links); delete and relink; disable; select upstream/downstream; create graph from selection; snapshot undo with merged slider drags | Dot-node chains editing, wire tension preferences, compact node display mode, multi-graph tabs, minimap |
| Graph editing | 15 | 75% | Pan/zoom canvas with grid; node cards with headers by category, live thumbnails and size/format labels; typed ports; bezier wires; drag to wire, re-route and unplug; select wires (click, Shift/Ctrl+click), delete them (Delete, Backspace, wire menu) and swap their sources (X); reroute dots pulled out of a wire (drag), dropped on it (double-click) or inserted from its menu; drop a wire on empty canvas to add a wired node; box/Ctrl/Shift selection; move; frames (move with contents, resize), comments (inline edit), navigation pins; node search (Space, double-click); library drag and drop; align and distribute; copy/cut/paste/duplicate (with or without links); delete and relink; disable; select upstream/downstream; create graph from selection; snapshot undo with merged slider drags | Dot-node chains editing, wire tension preferences, compact node display mode, multi-graph tabs, minimap |
| Atomic nodes | 12 | 95% | Bitmap, Blend (16 modes, masks, alpha), Blur, Channels Shuffle, Curve, Directional Blur, Directional Warp, Distance (with color propagation), Emboss, FX-Map (grid, quadtree and scatter modes with per-instance randomness), Gradient (Dynamic), Gradient Map, Grayscale Conversion, HSL, Levels, Normal, Pixel Processor, Value Processor, Sharpen, SVG (path data, fill rules, stroke), Text (own stroke font), Transformation 2D, Uniform Color, Warp, inputs, outputs, dots, graph instances | FX-Map driven by per-iteration functions, SVG arcs and SVG files, font choice for Text |
| Node library | 20 | 45% | 227 nodes: noises (tileable 3D Perlin, simplex and Worley, cracks, stones, dirt, grunge maps and more), patterns (tile generator and sampler, bricks, hexagons, weave, shape splatter, paint strokes, scratches), filters (adjustments, blending, blurs, channels, effects, normal map tools, tiling, transforms), the flood fill family, whole-material and height blending, weathering (rust, moss, leaks, edge damage, edge wear, dust) | The rest of the reference library's ~400 graphs: more grunge and scan processing, mesh-based generators and bakers, spline tools, SDF functions |
| Function graphs | 10 | 70% | A compiled, 4-wide evaluator with ~55 ops (constants, $pos/$size, exposed variables, samplers, vectors, swizzles, math, logic, comparison, noise, random, if/else); pixel and value processors; a visual function editor; dynamic parameters (a function on any numeric, color, bool or enum parameter, evaluated from the graph's inputs) | Loops, function graphs as reusable package items |
| Graph parameters and instances | 8 | 70% | Exposed inputs (float, int, bool, enum, color) bound to parameters of any compatible type, shown in groups, edited with one shared editor on the graph and on its instances; presets (save, apply, delete); sub-graph instances with their own inputs and outputs; graph attributes; `--set` on the CLI | Visibility conditions, per-instance output sizes, embedded vs. linked packages |
| 2D view | 5 | 80% | Pan/zoom, fit and 1:1, RGBA/R/G/B/A isolation, 3×3 tiling check, histogram, pixel readout, size/format line, save image | Color picker to parameters, UV overlay |
| 3D view | 10 | 55% | Rounded cube, cube, sphere, cylinder, plane, torus and material ball; OBJ, glTF and GLB meshes; base color, normal, roughness, metallic, height (parallax occlusion), AO, emissive and opacity; 4 procedural environments with rotation and exposure; orbit/pan/zoom; tiling; supersampling at rest | GPU renderer with tessellation, lights, material/shader switching, path-traced renderer |
| 3D view | 10 | 55% | Rounded cube, cube, sphere, cylinder, plane, torus and material ball; OBJ, glTF and GLB meshes; base color, normal, roughness, metallic, height (parallax occlusion), AO, emissive and opacity; alpha transparency through layered surfaces (opacity output or base color alpha) and an alpha channel view; 4 procedural environments with rotation and exposure; orbit/pan/zoom; tiling; supersampling at rest | GPU renderer with tessellation, lights, material/shader switching, path-traced renderer |
| Files | 8 | 70% | `.mcraft` packages with embedded bitmaps; `.mcmat` portable materials (cooked maps, exposed inputs, presets, input nodes, the source package) that TextureCraft paints with and re-cooks through the CLI at its own resolution, values and mesh maps; preview images for input nodes; export of every output (PNG, JPEG, TGA, TIFF, BMP, WEBP, EXR, HDR; 8/16/32 bits; name pattern; sRGB vs. linear by usage); bitmap import (PNG, JPEG, TGA, TIFF, BMP, WEBP, EXR, HDR); mesh import (OBJ, glTF, GLB); open, save, import and export in the browser; atomic writes; autosave; recent files | An MCP tool for portable materials, package dependencies, SVG and font files as resources |
| UI and UX | 8 | 70% | Dockable/floatable panels (explorer, library, graph, 3D, 2D, properties, console, history), menus, main toolbar, graph toolbar with atomic quick-insert, library with live previews, properties with curve/gradient/color editors, New graph dialog with rendered templates, export dialog, preferences (brightness, accent, scale, preview size, autosave, 3D pan limit and speed), shortcuts list, home screen at startup (samples and recent files), visual function editor, presets bar, accessible names on every widget, status bar | Translations, keymap editor, minimap, multi-graph tabs |
| UI and UX | 8 | 70% | Dockable/floatable panels (explorer, library, graph, 3D, 2D, properties, console, history), menus, main toolbar, graph toolbar with atomic quick-insert, library with live previews, properties with curve/gradient/color editors and a Levels editor over the input histogram, New graph dialog with rendered templates, export dialog, preferences (brightness, accent, scale, preview size, autosave, 3D pan limit and speed), shortcuts list, home screen at startup (samples and recent files), visual function editor, presets bar, accessible names on every widget, status bar | Translations, keymap editor, minimap, multi-graph tabs |
| Platforms | 4 | 50% | Windows, macOS, Linux, FreeBSD and web builds compile; browser file I/O; packaging scripts and release workflows | First release run |
| **Total** | **100** | **≈ 67%** | | |
+170
View File
@@ -0,0 +1,170 @@
# Editing wires and viewing alpha in the 3D view
This page documents two editor features: selecting, deleting, swapping and rerouting wires in
the graph editor, and the alpha (transparency) support of the 3D view. Both are clean-room implementations;
every action is an engine command, so the CLI, the control channel and MCP can do the same as the
mouse.
<p align="center">
<img src="images/materialcraft-alpha-transparency.png" alt="The wood planks material with a Grid Lines opacity output on a sphere in the 3D view: the gaps are see-through and the back of the sphere shows through them; in the graph, a reroute dot bends the wire from Grid Lines to the opacity output" width="100%">
<br><sub>A cut-out material in the 3D view, and a reroute dot pulled out of a wire</sub>
</p>
## Wires in the graph editor
A wire runs from an output port to an input port. Every input takes at most one wire, so a wire is
named by the input it feeds: the target node and its input port (`to`, `toPort`).
### Gestures
| Gesture | What it does |
|---|---|
| Hover a wire | The wire turns white and the pointer becomes a hand: it can be clicked |
| Click a wire | Selects it alone (drawn thicker, in the accent color); the node selection is cleared |
| **Shift**+click a wire | Adds it to the wire selection |
| **Ctrl**+click a wire | Adds it to the wire selection, or removes it when it is already selected |
| **Delete** or **Backspace** with wires selected | Deletes every selected wire (one undo step) |
| **X** with two or more wires selected | Swaps where the selected wires come from (see below); they stay selected, so **X** again swaps back |
| Drag a wire | Pulls a reroute **Dot** out of the wire where it was pressed and moves it with the pointer, in one gesture |
| Double-click a wire | Drops a reroute Dot at that point |
| Right-click a wire | Opens the wire menu: **Insert reroute dot**, **Swap selected links (X)** (with two or more selected), **Delete link** / **Delete selected links**. Right-clicking a wire that is already selected keeps the selection |
| Click anywhere else | Drops the wire selection |
A wire is hit within 5 points of its curve. Node cards, ports and comments sit on top of wires, so
a press there acts on them, not on the wire underneath. Alt+drag and middle-drag still pan the
canvas.
### Swapping wires
Select the wires going into a node and press **X** to swap their sources. On a **Blend** node, select
the *Foreground* and *Background* wires and press **X**: what fed the foreground now feeds the
background and the other way around, so the two layers trade places without rewiring by hand.
- **Two wires** trade sources.
- **More than two** reverse their sources. The wires are ordered by target node, then by the order
of the inputs on the node (top to bottom), and the first wire's source goes to the last input,
the second's to the one before it, and so on. With *Foreground*, *Background* and *Opacity*
selected on a Blend, the foreground and opacity sources trade places and the background keeps
its own.
- The order you click the wires in does not matter, so the result is predictable.
- Wires into different nodes can be swapped too. A swap that would feed a node into itself (a
cycle) is refused with a message, and nothing changes.
- One wire alone cannot be swapped: the editor says to select two or more.
- The swap is one undo step.
### Reroute dots
A Dot is the existing `dot` node: one input, one output, passing its input through unchanged. It
lets a wire bend around other nodes. After a dot is inserted it is selected, so it can be dragged,
deleted (**Delete** removes it with both of its wires; **Backspace**, *Delete and relink*, removes
it and joins the wire back up) or given more dots. Inserting a dot is one undo step: **Ctrl+Z**
restores the straight wire.
### Commands
| Command | Params | Result |
|---|---|---|
| `graph.wire.insertDot` | `{to, toPort, at?: [x, y]}` | Splits the wire feeding `to.toPort` with a Dot centered at `at` (graph space; default: midway between the two nodes). Returns `{"id": <dot id>}` and selects the dot. Errors when no wire feeds that input. |
| `graph.wire.swap` | `{wires: [{to, toPort}, ...]}` | Swaps (two wires) or reverses (more) the sources of the listed wires, as described above. Returns `{"swapped": n}`. Errors with fewer than two wires, a wire listed twice, a missing wire or a cycle; nothing changes then. |
| `graph.wire.delete` | `{wires: [{to, toPort}, ...]}` | Deletes the listed wires in one undo step (what the Delete key and the menu run). Returns `{"deleted": n}`. |
| `graph.disconnect` | `{to, toPort}` | Deletes the single wire feeding `to.toPort`. |
Over the control channel (see [control-protocol.md](control-protocol.md)), splitting the wire
feeding node 12's `input` with a dot at (240, 80), then deleting the wire from the dot to node 12:
```json
{"id": 1, "method": "command.run", "params": {"id": "graph.wire.insertDot", "params": {"to": 12, "toPort": "input", "at": [240, 80]}}}
{"id": 2, "method": "command.run", "params": {"id": "graph.disconnect", "params": {"to": 12, "toPort": "input"}}}
```
Swapping the two layers of Blend node 7:
```json
{"id": 3, "method": "command.run", "params": {"id": "graph.wire.swap", "params": {"wires": [{"to": 7, "toPort": "foreground"}, {"to": 7, "toPort": "background"}]}}}
```
`session.inspect` lists every wire under `graph.connections` and the dot under `graph.nodes`
(`"def": "dot"`). The wire selection itself is editor state, like hover, and is not part of the
session.
## Alpha in the 3D view
<p align="center">
<img src="images/materialcraft-alpha-channel.png" alt="The same sphere in the alpha channel view: the opaque grid lines are white and the clear gaps black" width="100%">
<br><sub>The alpha channel view: white is opaque, black is clear</sub>
</p>
### Where the alpha comes from
1. The output with the **Opacity** usage, read as grayscale, when the graph has one.
2. Otherwise the alpha channel of the **Base color** output, when it is a color image.
3. Otherwise the material is opaque.
### Transparency
Where the alpha is below one, the surface lets light through: each camera ray composites the
surfaces it meets front to back (`color × alpha`, the rest passes on) through up to eight layers,
then shows what lies behind: the backdrop, or the environment when **Display ▸ Environment
background** is on. Back faces seen through a clear front are shaded facing the viewer, so a
cut-out sphere shows its inside. Parallax from the height output applies to every layer.
**Display ▸ Transparency (alpha)** turns this off, so the alpha is ignored and the mesh is opaque.
It is on by default.
Before this change, the opacity output only mixed each pixel with the flat backdrop color; the
back of the mesh and the environment never showed through.
### Alpha channel view
**Display ▸ Show alpha channel**, or the checkerboard button in the 3D view's bottom bar, shows the
alpha on the mesh unlit: white is opaque, black is clear, values in between are linear (0.5 shows
as 50% gray, without tone mapping). The view is labeled *Alpha channel* in its top-left corner.
It shows the first surface only, so the channel reads clearly.
### Commands
`view.3d` takes two booleans; both are part of the session's `view3d` state and of
`session.inspect`:
| Param | Default | Meaning |
|---|---|---|
| `transparency` | `true` | See through the mesh where the alpha is below one |
| `alphaView` | `false` | Show the alpha channel instead of the lit material |
```json
{"id": 4, "method": "command.run", "params": {"id": "view.3d", "params": {"alphaView": true}}}
```
Headless renders (`materialcraft-cli render`, the `render` RPC) use the same settings.
## Implementation notes
- `crates/render/src/preview.rs`: `alpha()` picks the alpha source; `shade()` returns color, alpha
and hit distance; `trace()` composites the layers (`MAX_LAYERS = 8`, stops once less than 0.1%
of the light gets through); `Settings::{transparency, alpha_view}`.
- `crates/engine/src/wire_cmds.rs`: `graph.wire.insertDot`, `graph.wire.swap` (unplugs every
listed wire first, then reconnects, so a half-swapped state is never mistaken for a cycle) and
`graph.wire.delete`.
- `crates/ui-egui/src/graph_view.rs`: wire hit testing (`bezier_points`, `bezier_at`,
`bezier_distance`, `wire_at`), the `WirePress` gesture, the multi-wire selection
(`GraphView::selected_wires`), the wire menu, `delete_selected_wires` and
`swap_selected_wires`; `crates/ui-egui/src/menus.rs` gives Delete, Backspace and X to selected
wires before the node commands and shortcuts.
- `crates/ui-egui/src/view3d.rs`: the Display menu toggles and the bottom-bar button.
## Tests
- `preview::tests::alpha_shows_what_lies_behind_and_the_alpha_view_shows_the_channel`: a clear
sphere shows the backdrop, transparency off ignores alpha, the opacity output wins over the base
color alpha, the alpha view shows exact values.
- `a_wire_splits_with_a_reroute_dot_and_deletes` (engine): insertion, wiring, selection, cooking
through the dot, single-step undo, the error with no wire, deletion.
- `selected_wires_swap_their_sources_and_delete_together` (engine): two-wire swap in any order,
three-wire reverse, single-step undo, refused requests (one wire, duplicates, missing wires),
a refused cycle that leaves the graph unchanged, deleting several wires in one step.
- `graph_view::tests::clicked_wires_swap_with_x_and_delete_together`: real clicks on a Blend
node's two wires (the second with Shift), X swaps, X again swaps back, Delete removes both.
- `every_template_is_opaque_in_the_3d_view` (engine): no built-in template turns see-through.
- `graph_view::tests::wires_are_hit_near_their_curve_only`: wire hit testing.
- The `snapshots` UI test renders both screenshots on this page (`alpha-transparency`,
`alpha-channel`).
+1 -1
View File
@@ -21,7 +21,7 @@ workspace_version() {
' "$ROOT/Cargo.toml"
}
VERSION="${MATERIALCRAFT_VERSION:-$(workspace_version)}"
VERSION="${MATERIALCRAFT_VERSION:-${RELEASE_VERSION:-$(workspace_version)}}"
if [ -z "$VERSION" ]; then
echo "error: could not read [workspace.package] version from $ROOT/Cargo.toml" >&2
exit 1
+22 -1
View File
@@ -18,12 +18,18 @@ set -euo pipefail
HERE="$ROOT/packaging/linux"
APP_ID=ai.storyteller.materialcraft
FLATHUB=https://dl.flathub.org/repo/flathub.flatpakrepo
# The OCI repository serves only the latest stable release, so a prerelease bundle gets no update
# source: Flatpak would otherwise replace it with that older stable build.
OCI_REPO=oci+https://getartcraft.com
if [[ "$VERSION" == *-* ]]; then OCI_REPO=""; fi
TEST=1
OCI=0
TARBALL=""
while [ $# -gt 0 ]; do
case "$1" in
--no-test) TEST=0; shift ;;
--oci) OCI=1; shift ;;
-h | --help) sed -n '2,14p' "$0"; exit 0 ;;
-*) echo "unknown argument: $1" >&2; exit 2 ;;
*) TARBALL="$1"; shift ;;
@@ -58,9 +64,24 @@ flatpak-builder --user --install-deps-from=flathub --disable-rofiles-fuse --forc
--default-branch=stable --repo="$WORK/repo" --state-dir="$WORK/state" "$WORK/build" "$WORK/$APP_ID.yml"
OUT="$DIST/$BASENAME.flatpak"
# A release build (the shared release workflow sets SIGNING_FPR, SIGNING_PUBKEY and GNUPGHOME)
# signs the commit and embeds the public key, so Flatpak verifies the bundle when installing it.
GPG_KEYS=()
if [[ -n "${SIGNING_FPR:-}" ]]; then
flatpak build-sign "$WORK/repo" "$APP_ID" stable --gpg-sign="$SIGNING_FPR" --gpg-homedir="${GNUPGHOME:?}"
GPG_KEYS=(--gpg-keys="${SIGNING_PUBKEY:?}")
if [[ "${OCI_SIGNATURES_READY:-}" != 1 ]]; then OCI_REPO=""; fi
fi
# --runtime-repo lets `flatpak install` fetch the freedesktop runtime from Flathub if missing.
flatpak build-bundle --runtime-repo="$FLATHUB" "$WORK/repo" "$OUT" "$APP_ID" stable
# --repo-url makes the installed origin update from the ArtCraft OCI repository.
flatpak build-bundle --runtime-repo="$FLATHUB" ${OCI_REPO:+--repo-url="$OCI_REPO"} "${GPG_KEYS[@]}" "$WORK/repo" "$OUT" "$APP_ID" stable
echo "wrote $OUT"
if [[ "$OCI" = 1 ]]; then
OUT_OCI="$DIST/$BASENAME-oci"
rm -rf "$OUT_OCI"
flatpak build-bundle --oci "$WORK/repo" "$OUT_OCI" "$APP_ID" stable
echo "wrote OCI layout to $OUT_OCI"
fi
if [ "$TEST" = 1 ]; then
flatpak install --user -y --noninteractive --reinstall "$OUT"
+66
View File
@@ -0,0 +1,66 @@
#!/usr/bin/env bash
# Build materialcraft as an OCI container layout and push it to GitHub Container Registry (GHCR)
# for consumption by Flatpak OCI clients (flatpak-oci-specs).
#
# Usage:
# packaging/linux/flatpak-oci.sh [--push] [TARBALL]
#
# Environment variables:
# REGISTRY Target registry image (default: ghcr.io/storytold/materialcraft)
# TAG Target image tag (default: $VERSION-$ARCH, also tags stable-$ARCH)
# GITHUB_TOKEN Token for GHCR authentication when --push is used
set -euo pipefail
# shellcheck source=../env.sh
. "$(dirname "${BASH_SOURCE[0]}")/../env.sh"
HERE="$ROOT/packaging/linux"
PUSH=0
TARBALL=""
while [[ $# -gt 0 ]]; do
case "$1" in
--push) PUSH=1; shift ;;
-h | --help) sed -n '2,12p' "$0"; exit 0 ;;
-*) echo "unknown argument: $1" >&2; exit 2 ;;
*) TARBALL="$1"; shift ;;
esac
done
ARCH="$(uname -m)"
case "$ARCH" in
x86_64) ;;
aarch64 | arm64) ARCH=aarch64 ;;
*) echo "unsupported architecture $ARCH" >&2; exit 2 ;;
esac
BASENAME="materialcraft-$VERSION-linux-$ARCH"
OUT_OCI="$DIST/$BASENAME-oci"
echo "==> Building Flatpak OCI layout for $BASENAME"
"$HERE/flatpak-bundle.sh" --oci --no-test "${TARBALL:-}"
[[ -d "$OUT_OCI" ]] || { echo "error: $OUT_OCI layout not generated" >&2; exit 1; }
REGISTRY="${REGISTRY:-ghcr.io/storytold/materialcraft}"
TAG="${TAG:-$VERSION-$ARCH}"
echo "==> OCI layout ready at $OUT_OCI (Target: $REGISTRY:$TAG)"
if [[ "$PUSH" = 1 ]]; then
command -v skopeo >/dev/null || { echo "error: skopeo is required to push OCI images (apt install skopeo)" >&2; exit 1; }
AUTH_ARGS=()
if [[ -n "${GITHUB_TOKEN:-}" ]]; then
AUTH_ARGS=(--dest-creds "${GITHUB_ACTOR:-storytold}:$GITHUB_TOKEN")
fi
echo "==> Pushing to $REGISTRY:$TAG"
skopeo copy --format oci "${AUTH_ARGS[@]}" "oci:$OUT_OCI" "docker://$REGISTRY:$TAG"
# Only a stable release-branch build may move the stable tag.
if [[ "$VERSION" != *-* && "${GITHUB_REF:-}" == refs/heads/release ]]; then
echo "==> Pushing to $REGISTRY:stable-$ARCH"
skopeo copy --format oci "${AUTH_ARGS[@]}" "oci:$OUT_OCI" "docker://$REGISTRY:stable-$ARCH"
fi
echo "==> Push complete"
fi