chore(merge): bring fix/cook-worker-panic up to date with main

Kept upstream's cancellation flag and Arc-held cache with the panic guard: the worker
now reports Result<Cooked, String>, and the cancellation tests send Ok(..).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
SteamSmithandClaude Sonnet 5.5 committed 2026-11-05 11:56:51 -05:00
commit bb0db63423
58 files changed
+3025 -401

No files matched your search

Generated
+3
View File
@@ -2313,8 +2313,10 @@ dependencies = [
"egui",
"image",
"log",
"materialcraft-automation",
"materialcraft-engine",
"materialcraft-ui-egui",
"rfd",
"serde_json",
"winresource",
]
@@ -2332,6 +2334,7 @@ dependencies = [
"materialcraft-render",
"rayon",
"rmcp",
"rustix 1.1.6",
"schemars",
"serde",
"serde_json",
+1
View File
@@ -68,6 +68,7 @@ eframe = { version = "0.37", default-features = false }
egui = "0.37"
wgpu = "30"
rfd = "0.17"
rustix = { version = "1", default-features = false, features = ["std", "fs", "process"] }
zip = { version = "2", default-features = false, features = ["deflate"] }
gltf = { version = "1.4", default-features = false, features = ["import", "utils"] }
tobj = { version = "4", default-features = false }
+58 -17
View File
@@ -30,17 +30,18 @@ USAGE:
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]
[--tiling <n>] [--hq [--displacement <radii>]]
Render the material on a 3D scene (rounded_cube, cube, sphere, cylinder, plane, torus,
material_ball), or one node's output (--view 2d), to PNG. No GPU needed. --hq is a beauty
render: real displacement from the height output, ambient occlusion and a key light.
material_ball), or one node's output (--view 2d), to PNG. No GPU needed. The height output
raises the surface; --hq is a beauty render with a finer mesh, ambient occlusion and a key light.
materialcraft-cli mcp [--bridge <port>] [--token <token>] [--read-root <dir>] [--write-root <dir>]
MCP server on stdio: headless (file access only below the roots), or bridged to
`materialcraft --control <port>`.
`materialcraft --control <port>`. --automation-read-root / --automation-write-root are
the same as --read-root / --write-root (mcp and serve).
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.
@@ -58,12 +59,16 @@ 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"], &[]),
("mcp", &["--bridge", "--token", "--read-root", "--write-root", "--automation-read-root", "--automation-write-root"], &[]),
("serve", &["--port", "--read-root", "--write-root", "--automation-read-root", "--automation-write-root"], &[]),
];
/// (alias, flag): the `--automation-*-root` spelling the other crafting apps use, stored under the
/// short name so the last root given wins whichever spelling it used.
const ALIASES: &[(&str, &str)] = &[("--automation-read-root", "--read-root"), ("--automation-write-root", "--write-root")];
struct Args {
pos: Vec<String>,
flags: Vec<(String, Option<String>)>,
@@ -91,7 +96,8 @@ fn parse(cmd: &str, raw: &[String]) -> Result<Args, String> {
while let Some(x) = it.next() {
if valued.contains(&x.as_str()) {
let v = it.next().ok_or_else(|| format!("{x} needs a value"))?;
a.flags.push((x.clone(), Some(v.clone())));
let name = ALIASES.iter().find(|(alias, _)| alias == x).map_or(x.as_str(), |(_, flag)| flag);
a.flags.push((name.to_string(), Some(v.clone())));
} else if bare.contains(&x.as_str()) {
a.flags.push((x.clone(), None));
} else if x.starts_with('-') && x.len() > 1 && x.parse::<f64>().is_err() {
@@ -228,7 +234,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" => {
@@ -275,14 +281,16 @@ fn run(cmd: &str, a: &Args) -> Result<(), String> {
let h = Arc::new(Mutex::new(Headless::new(Headless::default_session(), workspace(a)?)));
match a.num::<u16>("--port")? {
Some(port) => {
let (token, file) = server_token(port).map_err(|e| e.to_string())?;
rpc::serve_tcp(port, h, token, |addr| {
eprintln!("materialcraft-cli: serving JSON lines on {addr}");
if let Some(f) = &file {
eprintln!("materialcraft-cli: token in {}", f.display());
}
})
.map_err(|e| e.to_string())?;
// Bind first: a port in use must not replace its server's token file, and port 0's
// token file is named after the port actually picked.
let listener = rpc::bind_tcp(port).map_err(|e| e.to_string())?;
let addr = listener.local_addr().map_err(|e| e.to_string())?;
let (token, file) = server_token(addr.port()).map_err(|e| e.to_string())?;
eprintln!("materialcraft-cli: serving JSON lines on {addr}");
if let Some(f) = &file {
eprintln!("materialcraft-cli: token in {}", f.display());
}
rpc::serve_listener(listener, h, token).map_err(|e| e.to_string())?;
}
None => rpc::serve_lines(&h, std::io::stdin().lock(), std::io::stdout().lock()).map_err(|e| e.to_string())?,
}
@@ -301,3 +309,36 @@ fn workspace(a: &Args) -> Result<Filesystem, String> {
let ws = AuthorizedWorkspace::new(r.map(std::path::Path::new), w.map(std::path::Path::new)).map_err(|e| e.to_string())?;
Ok(Filesystem::Workspace(ws))
}
#[cfg(test)]
mod tests {
use super::*;
fn strings(v: &[&str]) -> Vec<String> {
v.iter().map(|s| s.to_string()).collect()
}
#[test]
fn automation_root_flags_are_aliases_of_the_short_ones() {
for cmd in ["mcp", "serve"] {
let a = parse(cmd, &strings(&["--automation-read-root", "/r", "--automation-write-root", "/w"])).unwrap();
assert_eq!((a.get("--read-root"), a.get("--write-root")), (Some("/r"), Some("/w")), "{cmd}");
let a = parse(cmd, &strings(&["--read-root", "/r", "--write-root", "/w"])).unwrap();
assert_eq!((a.get("--read-root"), a.get("--write-root")), (Some("/r"), Some("/w")), "{cmd}");
}
}
#[test]
fn the_last_root_flag_wins_whatever_its_spelling() {
let a = parse("mcp", &strings(&["--read-root", "/a", "--automation-read-root", "/b"])).unwrap();
assert_eq!(a.get("--read-root"), Some("/b"));
let a = parse("mcp", &strings(&["--automation-write-root", "/a", "--write-root", "/b"])).unwrap();
assert_eq!(a.get("--write-root"), Some("/b"));
}
#[test]
fn automation_root_flags_need_a_value_and_stay_unknown_elsewhere() {
assert!(parse("mcp", &strings(&["--automation-read-root"])).is_err());
assert!(parse("cook", &strings(&["--automation-read-root", "/r"])).is_err());
}
}
+3
View File
@@ -12,12 +12,15 @@ workspace = true
[dependencies]
materialcraft-engine = { workspace = true }
materialcraft-automation = { workspace = true }
materialcraft-ui-egui = { workspace = true }
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "wayland", "x11", "persistence"] }
egui = { workspace = true }
image = { workspace = true }
serde_json = { workspace = true }
log = { workspace = true }
# A start that never opens a window says why in an error dialog (src/start_failure.rs).
rfd = { workspace = true }
[build-dependencies]
winresource = "0.1"
+211 -70
View File
@@ -1,80 +1,109 @@
//! Loopback JSON-lines control server (`--control <port>`): one request per line,
//! `{"id", "method", "params"}`, one reply per line. The first request must be
//! `{"method":"auth","params":{"token":"…"}}` with the token from `MATERIALCRAFT_CONTROL_TOKEN`
//! or, when that is unset, the token written to `<temp>/materialcraft-control-<port>.token`.
//! or, when that is unset, the token written (owner-only) to
//! `<temp>/materialcraft-control-<port>.token`. Token handling, request framing and connection
//! limits are shared with `materialcraft-cli serve` (`materialcraft_automation::security`).
use std::io::{BufRead, BufReader, Read, Write};
use std::io::{BufReader, Write};
use std::net::{TcpListener, TcpStream};
use std::sync::mpsc::{Receiver, Sender, channel};
use std::time::Duration;
use materialcraft_automation::security::{
AUTH_TIMEOUT, AuthDeadline, ConnectionLimiter, LineRead, MAX_CONNECTIONS, read_bounded_line, server_token, token_matches,
};
use materialcraft_ui_egui::ControlRequest;
use serde_json::{Value, json};
/// Requests larger than this are rejected (screenshots go the other way).
const MAX_REQUEST: u64 = 8 << 20;
fn token(port: u16) -> String {
if let Ok(t) = std::env::var("MATERIALCRAFT_CONTROL_TOKEN")
&& t.len() >= 16
{
return t;
}
use std::hash::{BuildHasher, Hasher};
let mut out = String::new();
for i in 0..4u64 {
let mut h = std::collections::hash_map::RandomState::new().build_hasher();
h.write_u64(i ^ u64::from(std::process::id()));
h.write_u128(std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0));
out.push_str(&format!("{:016x}", h.finish()));
}
let path = std::env::temp_dir().join(format!("materialcraft-control-{port}.token"));
if let Err(e) = std::fs::write(&path, &out) {
eprintln!("materialcraft: could not write the control token to {}: {e}", path.display());
} else {
eprintln!("materialcraft: control token written to {}", path.display());
}
out
}
/// How long an authenticated connection may stay idle.
const IDLE_TIMEOUT: Duration = Duration::from_secs(600);
/// Listen on `127.0.0.1:port` and return the requests for the UI thread to answer
/// ([`ControlRequest::reply`]). Bind or token failures are printed and leave the channel empty.
pub fn start(port: u16, ctx: egui::Context) -> Receiver<ControlRequest> {
let (tx, rx) = channel::<ControlRequest>();
let listener = match TcpListener::bind(("127.0.0.1", port)) {
Ok(l) => l,
Err(e) => {
eprintln!("materialcraft: control server failed to bind 127.0.0.1:{port}: {e}");
return channel().1;
}
};
start_listener(listener, ctx)
}
fn start_listener(listener: TcpListener, ctx: egui::Context) -> Receiver<ControlRequest> {
let (tx, rx) = channel::<ControlRequest>();
let addr = match listener.local_addr() {
Ok(addr) => addr,
Err(e) => {
eprintln!("materialcraft: could not determine the control port: {e}");
return rx;
}
};
let token = token(port);
eprintln!("materialcraft: control server listening on 127.0.0.1:{port}");
std::thread::spawn(move || {
for stream in listener.incoming().flatten() {
let (tx, ctx, token) = (tx.clone(), ctx.clone(), token.clone());
std::thread::spawn(move || serve(stream, &token, tx, ctx));
// After binding, so an app that cannot listen never replaces another server's token.
let token = match server_token(addr.port()) {
Ok((token, Some(path))) => {
eprintln!("materialcraft: control token written to {}", path.display());
token
}
});
Ok((token, None)) => token,
Err(e) => {
eprintln!("materialcraft: control server disabled: {e}");
return rx;
}
};
eprintln!("materialcraft: control server listening on {addr}");
if let Err(e) = std::thread::Builder::new().name("materialcraft-control".into()).spawn(move || accept(listener, &token, &tx, &ctx)) {
eprintln!("materialcraft: could not start the control server: {e}");
}
rx
}
fn serve(stream: TcpStream, token: &str, tx: Sender<ControlRequest>, ctx: egui::Context) {
let _ = stream.set_read_timeout(Some(Duration::from_secs(600)));
let Ok(read) = stream.try_clone() else { return };
let mut reader = BufReader::new(read.take(u64::MAX));
let mut out = stream;
let mut authed = false;
loop {
let mut line = String::new();
let n = match reader.by_ref().take(MAX_REQUEST).read_line(&mut line) {
Ok(n) => n,
Err(_) => break,
/// Serve connections from `listener` (at most [`MAX_CONNECTIONS`] at once).
fn accept(listener: TcpListener, token: &str, tx: &Sender<ControlRequest>, ctx: &egui::Context) {
let limiter = ConnectionLimiter::default();
for stream in listener.incoming() {
let Ok(mut stream) = stream else { continue };
let Some(permit) = limiter.try_acquire(MAX_CONNECTIONS) else {
let _ = writeln!(stream, "{}", json!({"id": null, "ok": false, "error": "too many connections"}));
continue;
};
if n == 0 {
break;
let (tx, ctx, token) = (tx.clone(), ctx.clone(), token.to_string());
if let Err(e) = std::thread::Builder::new().name("materialcraft-control-client".into()).spawn(move || {
let _permit = permit;
serve(stream, &token, &tx, &ctx);
}) {
log::warn!("could not start a control connection: {e}");
}
if !line.ends_with('\n') && n as u64 >= MAX_REQUEST {
let _ = writeln!(out, "{}", json!({"id": null, "ok": false, "error": "request too large"}));
break;
}
}
/// Send `reply` with the request's `id`; false when the client is gone.
fn reply(out: &mut TcpStream, id: Value, mut reply: Value) -> bool {
if let Some(o) = reply.as_object_mut() {
o.insert("id".into(), id);
}
writeln!(out, "{reply}").is_ok() && out.flush().is_ok()
}
/// One connection: `auth` first (within [`AUTH_TIMEOUT`], one attempt), then requests
/// forwarded to the UI thread one at a time until the client disconnects or idles out.
fn serve(stream: TcpStream, token: &str, tx: &Sender<ControlRequest>, ctx: &egui::Context) {
let Ok(mut deadline) = AuthDeadline::start(&stream, AUTH_TIMEOUT).map(Some) else { return };
let _ = stream.set_read_timeout(Some(IDLE_TIMEOUT));
let Ok(read) = stream.try_clone() else { return };
let mut reader = BufReader::new(read);
let mut out = stream;
let mut line = String::new();
loop {
match read_bounded_line(&mut reader, &mut line) {
Ok(LineRead::Line) => {}
Ok(LineRead::TooLong) => {
reply(&mut out, Value::Null, json!({"ok": false, "error": "request too large"}));
return;
}
Ok(LineRead::Eof) | Err(_) => return,
}
if line.trim().is_empty() {
continue;
@@ -82,33 +111,145 @@ fn serve(stream: TcpStream, token: &str, tx: Sender<ControlRequest>, ctx: egui::
let msg: Value = match serde_json::from_str(&line) {
Ok(v) => v,
Err(e) => {
let _ = writeln!(out, "{}", json!({"id": null, "ok": false, "error": format!("bad JSON: {e}")}));
let sent = reply(&mut out, Value::Null, json!({"ok": false, "error": format!("bad JSON: {e}")}));
// Before `auth` a malformed line is the one refused attempt, as on `serve --port`.
if !sent || deadline.is_some() {
return;
}
continue;
}
};
let id = msg.get("id").cloned().unwrap_or(Value::Null);
let method = msg.get("method").and_then(Value::as_str).unwrap_or("").to_string();
let params = msg.get("params").cloned().unwrap_or(json!({}));
let mut reply = if !authed {
let ok = method == "auth" && params.get("token").and_then(Value::as_str) == Some(token);
authed = ok;
if ok { json!({"ok": true}) } else { json!({"ok": false, "error": "authenticate first: {\"method\":\"auth\",\"params\":{\"token\":…}}"}) }
} else {
let (req, rrx) = ControlRequest::new(method, params);
if tx.send(req).is_err() {
break;
if deadline.is_some() {
let supplied = params.get("token").and_then(Value::as_str).unwrap_or_default();
if method != "auth" || !token_matches(token, supplied) {
// One attempt per connection, as on `materialcraft-cli serve`.
reply(&mut out, id, json!({"ok": false, "error": "authenticate first: {\"method\":\"auth\",\"params\":{\"token\":…}}"}));
return;
}
ctx.request_repaint();
rrx.recv_timeout(Duration::from_secs(120)).unwrap_or_else(|_| json!({"ok": false, "error": "timeout"}))
};
if let Some(o) = reply.as_object_mut() {
o.insert("id".into(), id);
drop(deadline.take());
if !reply(&mut out, id, json!({"ok": true})) {
return;
}
continue;
}
if writeln!(out, "{reply}").is_err() || out.flush().is_err() || !authed {
if !authed {
continue;
}
break;
let (req, rrx) = ControlRequest::new(method, params);
if tx.send(req).is_err() {
return;
}
ctx.request_repaint();
let answer = rrx.recv_timeout(Duration::from_secs(120)).unwrap_or_else(|_| json!({"ok": false, "error": "timeout"}));
if !reply(&mut out, id, answer) {
return;
}
}
}
#[cfg(test)]
mod tests {
use std::io::BufRead;
use super::*;
const TOKEN: &str = "0123456789abcdef0123456789abcdef";
#[test]
fn ephemeral_listener_uses_its_actual_port_for_the_token() {
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
let addr = listener.local_addr().unwrap();
assert_ne!(addr.port(), 0);
let _requests = start_listener(listener, egui::Context::default());
let token = materialcraft_automation::security::client_token(addr.port(), None).unwrap();
let (mut w, mut r) = connect(addr);
let auth = json!({"method": "auth", "params": {"token": token}}).to_string();
assert_eq!(call(&mut w, &mut r, &auth).unwrap()["ok"], true);
}
/// A server on a free port whose app side answers every request with its method name.
fn server() -> std::net::SocketAddr {
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
let addr = listener.local_addr().unwrap();
let (tx, rx) = channel::<ControlRequest>();
std::thread::spawn(move || accept(listener, TOKEN, &tx, &egui::Context::default()));
std::thread::spawn(move || {
for r in rx {
let _ = r.reply.send(json!({"ok": true, "result": r.method}));
}
});
addr
}
fn connect(addr: std::net::SocketAddr) -> (TcpStream, BufReader<TcpStream>) {
let s = TcpStream::connect(addr).unwrap();
s.set_read_timeout(Some(Duration::from_secs(20))).unwrap();
let r = BufReader::new(s.try_clone().unwrap());
(s, r)
}
fn call(w: &mut TcpStream, r: &mut BufReader<TcpStream>, line: &str) -> Option<Value> {
writeln!(w, "{line}").ok()?;
let mut reply = String::new();
(r.read_line(&mut reply).ok()? > 0).then(|| serde_json::from_str(&reply).unwrap())
}
#[test]
fn requests_need_the_token() {
let addr = server();
// Anything before `auth` is refused and the connection closed.
let (mut w, mut r) = connect(addr);
let denied = call(&mut w, &mut r, r#"{"id":1,"method":"command.run","params":{"id":"file.open"}}"#).unwrap();
assert_eq!(denied["ok"], false);
assert_eq!(denied["id"], 1);
assert!(call(&mut w, &mut r, r#"{"id":2,"method":"ping"}"#).is_none(), "closed after a refused request");
// A wrong token is refused and gets no second try.
let (mut w, mut r) = connect(addr);
let wrong = format!(r#"{{"id":1,"method":"auth","params":{{"token":"{}x"}}}}"#, &TOKEN[1..]);
assert_eq!(call(&mut w, &mut r, &wrong).unwrap()["ok"], false);
let right = format!(r#"{{"id":2,"method":"auth","params":{{"token":"{TOKEN}"}}}}"#);
assert!(call(&mut w, &mut r, &right).is_none());
// So is a malformed first line: no further lines before `auth`.
let (mut w, mut r) = connect(addr);
assert_eq!(call(&mut w, &mut r, "not json").unwrap()["ok"], false);
assert!(call(&mut w, &mut r, &right).is_none(), "closed after malformed JSON before auth");
// The right token unlocks the connection.
let (mut w, mut r) = connect(addr);
let ok = call(&mut w, &mut r, &right).unwrap();
assert_eq!((ok["ok"].clone(), ok["id"].clone()), (json!(true), json!(2)));
let pong = call(&mut w, &mut r, r#"{"id":3,"method":"ping"}"#).unwrap();
assert_eq!((pong["result"].clone(), pong["id"].clone()), (json!("ping"), json!(3)));
assert_eq!(call(&mut w, &mut r, "not json").unwrap()["ok"], false);
assert_eq!(call(&mut w, &mut r, r#"{"id":4,"method":"ping"}"#).unwrap()["id"], 4, "bad JSON keeps an authenticated connection");
}
#[test]
fn connections_are_limited_and_idle_ones_time_out() {
let addr = server();
let idle: Vec<_> = (0..MAX_CONNECTIONS).map(|_| connect(addr)).collect();
// Let the server take every idle connection before the one over the limit.
std::thread::sleep(Duration::from_millis(300));
// Read without writing: the server closes at once, and unread input would reset the
// connection before its reply arrives.
let (_, mut r) = connect(addr);
let mut full = String::new();
r.read_line(&mut full).unwrap();
assert_eq!(serde_json::from_str::<Value>(&full).unwrap()["error"], "too many connections");
// Unauthenticated connections are closed after AUTH_TIMEOUT, which frees their slots.
for (_, mut r) in idle {
let mut rest = String::new();
assert_eq!(r.read_line(&mut rest).unwrap(), 0);
}
// A slot frees once its thread has ended, which can trail the client's EOF a little.
let right = format!(r#"{{"id":1,"method":"auth","params":{{"token":"{TOKEN}"}}}}"#);
let authed = (0..50).any(|_| {
let (mut w, mut r) = connect(addr);
let ok = call(&mut w, &mut r, &right).is_some_and(|v| v["ok"] == true);
if !ok {
std::thread::sleep(Duration::from_millis(100));
}
ok
});
assert!(authed, "slots are freed after the auth deadline");
}
}
+3
View File
@@ -6,6 +6,7 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
mod control_server;
mod start_failure;
use materialcraft_engine::Session;
use materialcraft_ui_egui::MaterialCraftApp;
@@ -109,6 +110,8 @@ fn main() {
);
if let Err(e) = r {
eprintln!("materialcraft: {e}");
// Say why instead of exiting silently (`start_failure`).
start_failure::report(&e);
std::process::exit(1);
}
}
+52
View File
@@ -0,0 +1,52 @@
//! A window that can't start, or stops, says why instead of the app quitting silently.
//!
//! Without a usable GPU, graphics driver or desktop (a broken or very old driver, a remote or
//! virtual machine, a program started by a service or a test harness), the window's surface
//! can't be configured and eframe returns an error. MaterialCraft used to log it and exit with no
//! window, which looks like "the app doesn't open".
//! winget-pkgs validation starts installed programs without a desktop, so a version that fails
//! like this never reaches WinGet.
//!
//! Now the reason also goes to an error dialog, as FilmCraft does since 0.14.0. The dialog keeps
//! the process alive until it is dismissed; the exit code afterwards is still the error's.
/// What the dialog and the log say. Any error `run_native` returns lands here. One from the app's
/// own start-up (`AppCreation`, e.g. a `--control` file it can't write) says only that it couldn't
/// start. Any other comes from the window or graphics, possibly after the window was up, so
/// graphics is named as the likely cause, not the certain one.
pub(crate) fn message(error: &eframe::Error) -> String {
match error {
eframe::Error::AppCreation(_) => format!("MaterialCraft could not start: {error}"),
_ => format!(
"MaterialCraft's window could not start or stopped with an error: {error}\n\nIf this keeps happening, updating the graphics driver often fixes it."
),
}
}
/// Logs the failure and shows it in a dialog, which stays until the user closes it.
pub(crate) fn report(error: &eframe::Error) {
let message = message(error);
log::error!("{message}");
let _ = rfd::MessageDialog::new().set_title("MaterialCraft").set_description(&message).set_level(rfd::MessageLevel::Error).show();
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_window_or_graphics_error_names_the_driver_as_the_likely_fix() {
let text = message(&eframe::Error::Wgpu(eframe::egui_wgpu::WgpuError::NoSurfaceFormatsAvailable));
assert!(text.starts_with("MaterialCraft's window could not start or stopped"), "{text}");
assert!(text.contains("no valid format for the surface"), "{text}");
assert!(text.contains("graphics driver"), "{text}");
}
#[test]
fn an_app_start_up_error_does_not_blame_the_graphics() {
let text = message(&eframe::Error::AppCreation("can't write the control file".into()));
assert!(text.starts_with("MaterialCraft could not start"), "{text}");
assert!(text.contains("can't write the control file"), "{text}");
assert!(!text.contains("graphics"), "{text}");
}
}
+3
View File
@@ -24,5 +24,8 @@ base64 = { workspace = true }
cap-std = { workspace = true }
getrandom = { workspace = true }
[target.'cfg(unix)'.dependencies]
rustix = { workspace = true }
[dev-dependencies]
rmcp = { workspace = true, features = ["client"] }
+30 -15
View File
@@ -4,8 +4,9 @@
use std::path::Path;
use materialcraft_engine::core::NodeId;
use materialcraft_engine::{Session, commands, file_cmds, inspect};
use materialcraft_render::{Lighting, Maps, Scene, Settings};
use materialcraft_engine::formats::material::MATERIAL_EXT;
use materialcraft_engine::{Session, commands, file_cmds, inspect, material_cmds};
use materialcraft_render::{Lighting, Maps, Relief, Scene, Settings, VIEW_TRIANGLES};
use serde_json::{Value, json};
use crate::budgets::{HQ_TRIANGLES, MAX_LOCAL_RENDER_SIDE, MAX_PNG_SIDE, check_png, encode_png};
@@ -42,10 +43,9 @@ pub struct RenderOptions {
pub full: bool,
/// 3D: UV repeats override (the session's view is not changed).
pub tiling: Option<f32>,
/// 3D: beauty render: the height output displaces a subdivided mesh, with ray-traced
/// ambient occlusion, a shadowed key light and 3×3 supersampling. Slower; for stills.
/// 3D: beauty render: a finer displaced mesh, ray-traced ambient occlusion, a shadowed key light and 3×3 supersampling.
pub hq: bool,
/// 3D, with `hq`: displacement depth in scene radii (default 0.04).
/// 3D, with `hq`: displacement depth in scene radii (default: the view's height depth).
pub displacement: Option<f32>,
}
@@ -187,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 {
@@ -199,6 +199,26 @@ impl Headless {
Ok(json!({"files": written}))
}
/// Cook a graph and write it as a portable `.mcmat` material (`.mcmat` appended when
/// missing) to `path`: `{path, graph?, size?, values?}`, the workspace-scoped
/// `file.exportMaterial`. The file is capped at what `package_open` may read back.
pub fn export_material(&mut self, p: &Value) -> Result<Value, AutomationError> {
let path = p.get("path").and_then(Value::as_str).ok_or_else(|| bad("`path` is required"))?;
let path = if path.to_ascii_lowercase().ends_with(&format!(".{MATERIAL_EXT}")) { path.to_string() } else { format!("{path}.{MATERIAL_EXT}") };
match &self.fs {
Filesystem::Denied => return Err(bad("file access is not granted: start the server with --write-root <dir>")),
Filesystem::Workspace(w) => w.check_write(&path)?,
Filesystem::TrustedLocal => {}
}
let (gi, options) = material_cmds::material_request(&self.session, "material.export", p)?;
let bytes = material_cmds::material_bytes(&self.session, gi, &options)?;
if bytes.len() as u64 > MAX_READ_BYTES {
return Err(bad(format!("the material is {} bytes (limit {MAX_READ_BYTES}); export a smaller `size`", bytes.len())));
}
self.write(&path, &bytes)?;
Ok(json!({"path": path, "bytes": bytes.len()}))
}
/// Render the 3D view or a node's 2D output as PNG.
pub fn render_png(&mut self, o: &RenderOptions) -> Result<Rendered, AutomationError> {
let max = if self.trusted() { MAX_LOCAL_RENDER_SIDE } else { MAX_PNG_SIDE };
@@ -249,6 +269,8 @@ impl Headless {
self.light = Some(Lighting::new(&v.environment));
}
let tiling = o.tiling.unwrap_or(v.tiling).clamp(0.1, 64.0);
let depth = if o.hq { o.displacement.unwrap_or(v.height_scale) } else { v.height_scale };
let relief = Relief { depth: depth.clamp(0.0, 0.5), level: v.height_level };
let mut settings = Settings {
yaw: o.yaw.unwrap_or(v.yaw),
pitch: o.pitch.unwrap_or(v.pitch),
@@ -257,7 +279,6 @@ impl Headless {
tiling,
exposure: v.exposure,
env_rotation: v.env_rotation,
height_scale: v.height_scale,
show_env: false,
supersample: 2,
transparency: v.transparency,
@@ -267,13 +288,7 @@ impl Headless {
let (w, h) = (o.width.unwrap_or(1024).clamp(16, max), o.height.unwrap_or(768).clamp(16, max));
let maps = Maps::from_usages(self.session.material_maps());
let (Some((_, scene)), Some(light)) = (&self.scene, &self.light) else { return (w, h, vec![0; (w * h * 4) as usize]) };
let displaced = match (o.hq, &maps.height) {
(true, Some(height)) => {
settings.height_scale = 0.0;
Some(Scene::displaced(&scene.mesh, height, tiling, o.displacement.unwrap_or(0.04).clamp(0.0, 0.5) * scene.radius, HQ_TRIANGLES))
}
_ => None,
};
let displaced = scene.with_relief(&maps, relief, tiling, if o.hq { HQ_TRIANGLES } else { VIEW_TRIANGLES });
if o.hq {
settings.supersample = 3;
settings.ao_rays = 8;
+100 -6
View File
@@ -4,8 +4,9 @@
//!
//! Methods: the app's `ping`, `command.run {id, params?}`, `command.list {filter?}`,
//! `session.inspect`, plus `command.batch {steps}`, `package.open {path}`, `package.save {path?}`,
//! `bitmap.import {path, name?}`, `outputs.export {dir, format?, pattern?, depth?, graph?}`
//! (workspace-scoped versions of the engine commands), `render {view?, width?, height?, yaw?,
//! `bitmap.import {path, name?}`, `outputs.export {dir, format?, pattern?, depth?, graph?}`,
//! `material.export {path, graph?, size?, values?}` (workspace-scoped versions of the engine
//! commands; the last writes a portable `.mcmat`), `render {view?, width?, height?, yaw?,
//! pitch?, scene?, node?, port?, full?}` (PNG base64, the shape of the app's `view.screenshot`)
//! and `methods`.
@@ -18,7 +19,9 @@ use serde_json::{Value, json};
use crate::budgets::json_text;
use crate::headless::RenderOptions;
use crate::security::{ConnectionLimiter, LineRead, MAX_BATCH_STEPS, MAX_CONNECTIONS, MAX_REQUEST_BYTES, read_bounded_line, token_matches};
use crate::security::{
AUTH_TIMEOUT, AuthDeadline, ConnectionLimiter, LineRead, MAX_BATCH_STEPS, MAX_CONNECTIONS, MAX_REQUEST_BYTES, read_bounded_line, token_matches,
};
use crate::{AutomationError, Headless, bad};
pub const METHODS: &[&str] = &[
@@ -32,6 +35,7 @@ pub const METHODS: &[&str] = &[
"package.save",
"bitmap.import",
"outputs.export",
"material.export",
"render",
];
@@ -84,6 +88,7 @@ impl Headless {
"package.save" => self.save(str_of(p, "path")),
"bitmap.import" => self.import_bitmap(required(p, "path")?, str_of(p, "name")),
"outputs.export" => self.export(p),
"material.export" => self.export_material(p),
"render" => {
let o = RenderOptions {
view: str_of(p, "view").map(str::to_string),
@@ -160,6 +165,7 @@ fn serve_connection(h: &Mutex<Headless>, stream: std::net::TcpStream, token: &st
let mut w = stream;
let mut line = String::new();
let mut authed = false;
let mut deadline = Some(AuthDeadline::start(&w, AUTH_TIMEOUT)?);
loop {
match read_bounded_line(&mut r, &mut line)? {
LineRead::Eof => return Ok(()),
@@ -178,15 +184,26 @@ fn serve_connection(h: &Mutex<Headless>, stream: std::net::TcpStream, token: &st
if !authed {
return write_reply(&mut w, &json!({"id": id, "ok": false, "error": "authenticate first: {\"method\":\"auth\",\"params\":{\"token\":…}}"}));
}
drop(deadline.take());
write_reply(&mut w, &json!({"id": id, "ok": true}))?;
}
}
/// Listen on `127.0.0.1:port` (0 picks a port).
pub fn bind_tcp(port: u16) -> Result<TcpListener, AutomationError> {
TcpListener::bind(("127.0.0.1", port)).map_err(|e| AutomationError::Io(format!("cannot listen on 127.0.0.1:{port}: {e}")))
}
/// Serve authenticated JSON lines on `127.0.0.1:port` (0 picks a port) with one shared
/// session. `ready` gets the bound address.
pub fn serve_tcp(port: u16, h: Arc<Mutex<Headless>>, token: String, ready: impl FnOnce(std::net::SocketAddr)) -> Result<(), AutomationError> {
let listener = TcpListener::bind(("127.0.0.1", port)).map_err(|e| AutomationError::Io(format!("cannot listen on 127.0.0.1:{port}: {e}")))?;
let listener = bind_tcp(port)?;
ready(listener.local_addr().map_err(|e| AutomationError::Io(e.to_string()))?);
serve_listener(listener, h, token)
}
/// Serve authenticated JSON lines on a bound listener (see [`bind_tcp`]) with one shared session.
pub fn serve_listener(listener: TcpListener, h: Arc<Mutex<Headless>>, token: String) -> Result<(), AutomationError> {
let limiter = ConnectionLimiter::default();
let token = Arc::new(token);
for stream in listener.incoming() {
@@ -196,10 +213,12 @@ pub fn serve_tcp(port: u16, h: Arc<Mutex<Headless>>, token: String, ready: impl
continue;
};
let (h, token) = (h.clone(), token.clone());
std::thread::spawn(move || {
if let Err(e) = std::thread::Builder::new().name("materialcraft-rpc-client".into()).spawn(move || {
let _permit = permit;
let _ = serve_connection(&h, stream, &token);
});
}) {
eprintln!("materialcraft: could not start an RPC connection: {e}");
}
}
Ok(())
}
@@ -253,6 +272,81 @@ mod tests {
assert_eq!(r[6]["result"]["failed"]["index"], 1);
}
/// A workspace session rooted at a fresh `inside` folder, with an `outside` sibling.
fn workspace_session(name: &str, write: bool) -> (std::path::PathBuf, std::path::PathBuf, Mutex<Headless>) {
let base = std::env::temp_dir().join(format!("mc-rpc-{}-{name}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
let (inside, outside) = (base.join("inside"), base.join("outside"));
std::fs::create_dir_all(&inside).unwrap();
std::fs::create_dir_all(&outside).unwrap();
let ws = crate::AuthorizedWorkspace::new(Some(&inside), write.then_some(inside.as_path())).unwrap();
let h = Mutex::new(Headless::new(materialcraft_engine::sample_session(), Filesystem::Workspace(ws)));
(inside, outside, h)
}
fn call(h: &Mutex<Headless>, method: &str, params: Value) -> Result<Value, String> {
h.lock().unwrap().handle(method, &params).map_err(|e| e.to_string())
}
#[test]
fn material_export_writes_a_portable_material_below_the_write_root() {
let (inside, _, h) = workspace_session("mat-ok", true);
std::fs::create_dir(inside.join("out")).unwrap();
let r = call(&h, "material.export", json!({"path": "out/brick", "size": 32})).unwrap();
assert_eq!(r["path"], "out/brick.mcmat");
let bytes = std::fs::read(inside.join("out/brick.mcmat")).unwrap();
assert_eq!(r["bytes"], bytes.len());
let (m, source) = materialcraft_engine::formats::material::read_material(&bytes).unwrap();
assert_eq!(m.size, [32, 32]);
assert!(m.maps.iter().any(|e| e.usage == "baseColor"));
assert!(!source.is_empty());
assert_eq!(std::fs::read_dir(inside.join("out")).unwrap().count(), 1, "no temporary files left behind");
// An explicit extension is kept (case-insensitively) and the file can be opened again.
let r = call(&h, "material.export", json!({"path": "again.MCMAT", "size": 16})).unwrap();
assert_eq!(r["path"], "again.MCMAT");
assert!(call(&h, "package.open", json!({"path": "again.MCMAT"})).is_ok());
}
#[test]
fn material_export_reports_bad_requests() {
let (inside, _, h) = workspace_session("mat-bad", true);
for bad in [json!({}), json!({"path": "m", "graph": 99}), json!({"path": "m", "values": {"no_such_input": 1}})] {
assert!(call(&h, "material.export", bad.clone()).is_err(), "{bad}");
}
assert!(call(&h, "material.export", json!({"path": "missing/dir/m"})).is_err(), "parent must exist");
assert_eq!(std::fs::read_dir(&inside).unwrap().count(), 0, "failed exports leave nothing behind");
}
#[test]
fn material_export_needs_a_write_root() {
let denied = session();
let e = call(&denied, "material.export", json!({"path": "m.mcmat"})).unwrap_err();
assert!(e.contains("not granted"), "{e}");
let (inside, _, read_only) = workspace_session("mat-readonly", false);
let e = call(&read_only, "material.export", json!({"path": "m.mcmat"})).unwrap_err();
assert!(e.contains("no write root"), "{e}");
assert_eq!(std::fs::read_dir(&inside).unwrap().count(), 0);
}
#[test]
fn material_export_cannot_escape_the_write_root() {
let (_inside, outside, h) = workspace_session("mat-escape", true);
let abs = outside.join("abs.mcmat").display().to_string();
for p in ["../outside/m.mcmat", "a/../../outside/m.mcmat", "/tmp/m.mcmat", "a\\b.mcmat", "C:/m.mcmat", "./m.mcmat", abs.as_str()] {
let e = call(&h, "material.export", json!({"path": p, "size": 16}));
assert!(e.is_err(), "accepted {p:?}");
}
#[cfg(unix)]
{
std::os::unix::fs::symlink(&outside, _inside.join("link")).unwrap();
assert!(call(&h, "material.export", json!({"path": "link/m.mcmat", "size": 16})).is_err());
}
assert_eq!(std::fs::read_dir(&outside).unwrap().count(), 0, "nothing written outside the root");
// The generic command path stays closed too: host paths are still refused.
let e = call(&h, "command.run", json!({"id": "file.exportMaterial", "params": {"path": abs}})).unwrap_err();
assert!(e.contains("disabled for automation"), "{e}");
}
#[test]
fn tcp_requires_the_token() {
use std::io::{BufRead, BufReader};
+174 -8
View File
@@ -1,10 +1,13 @@
//! Tokens and bounded framing for the loopback JSON-lines transports (the app's control channel
//! and `materialcraft-cli serve` share the token conventions).
use std::io::BufRead;
use std::path::PathBuf;
use std::io::{BufRead, Read, Write};
use std::net::{Shutdown, TcpStream};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::mpsc::{RecvTimeoutError, Sender, channel};
use std::time::Duration;
use crate::{AutomationError, bad};
@@ -14,6 +17,10 @@ pub const TOKEN_ENV: &str = "MATERIALCRAFT_CONTROL_TOKEN";
pub const MAX_REQUEST_BYTES: usize = 8 << 20;
/// Simultaneous TCP connections served by `serve --port`.
pub const MAX_CONNECTIONS: usize = 16;
/// Largest token file read (a token is at most 1024 characters, plus whitespace).
const MAX_TOKEN_FILE_BYTES: u64 = 4096;
/// Time a TCP client has to authenticate before its connection is closed.
pub const AUTH_TIMEOUT: Duration = Duration::from_secs(10);
/// Steps in one `command_batch`.
pub const MAX_BATCH_STEPS: usize = 256;
@@ -44,7 +51,7 @@ pub fn client_token(port: u16, supplied: Option<String>) -> Result<String, Autom
Some(t) => t,
None => {
let path = token_file(port);
std::fs::read_to_string(&path)
read_token_file(&path)
.map_err(|e| bad(format!("no control token: set {TOKEN_ENV} or start the app with `--control {port}` so it writes {} ({e})", path.display())))?
}
};
@@ -54,7 +61,8 @@ pub fn client_token(port: u16, supplied: Option<String>) -> Result<String, Autom
}
/// Token for a server on `port`: `MATERIALCRAFT_CONTROL_TOKEN`, else a fresh one written to
/// [`token_file`] (owner-only on Unix). Returns the token and where it was written.
/// [`token_file`] (owner-only on Unix). Returns the token and where it was written. Call it
/// once the port is bound, so a server that cannot listen never replaces another's token.
pub fn server_token(port: u16) -> Result<(String, Option<PathBuf>), AutomationError> {
if let Ok(t) = std::env::var(TOKEN_ENV) {
validate_token(t.trim())?;
@@ -62,13 +70,60 @@ pub fn server_token(port: u16) -> Result<(String, Option<PathBuf>), AutomationEr
}
let token = generate_token()?;
let path = token_file(port);
write_token_file(&path, &token).map_err(|e| {
AutomationError::Io(format!("cannot write the control token to {} ({e}); set {TOKEN_ENV} to a token of your own instead", path.display()))
})?;
Ok((token, Some(path)))
}
/// Write `token` to a new file at `path`, readable by the owner only on Unix. Whatever was at
/// `path` is removed first and the file is created exclusively (`O_EXCL`, which never follows
/// a symlink), so a file or link planted in a shared temp folder can neither keep its
/// permissions nor redirect the write; one that cannot be removed (another user's, in a sticky
/// `/tmp`) fails the call.
fn write_token_file(path: &Path, token: &str) -> std::io::Result<()> {
match std::fs::remove_file(path) {
Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(e),
_ => {}
}
let mut o = std::fs::OpenOptions::new();
o.write(true).create(true).truncate(true);
o.write(true).create_new(true);
#[cfg(unix)]
std::os::unix::fs::OpenOptionsExt::mode(&mut o, 0o600);
let res = o.open(&path).and_then(|mut f| std::io::Write::write_all(&mut f, token.as_bytes()));
res.map_err(|e| AutomationError::Io(format!("cannot write the control token to {}: {e}", path.display())))?;
Ok((token, Some(path)))
let mut f = o.open(path)?;
f.write_all(token.as_bytes())?;
f.sync_all()
}
/// Read a token file written by [`write_token_file`]. On Unix the file must be a regular file
/// (not a symlink, FIFO or device) owned by this user with no group or other permissions, so a
/// file another user planted is never trusted and a link can't make a client send one of its
/// own secrets as the token.
fn read_token_file(path: &Path) -> std::io::Result<String> {
#[cfg(unix)]
let file = {
use rustix::fs::{Mode, OFlags};
use std::os::unix::fs::MetadataExt;
let flags = OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC;
let file = std::fs::File::from(rustix::fs::open(path, flags, Mode::empty())?);
let meta = file.metadata()?;
let refuse = |why: &str| Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, format!("refusing the token file: {why}")));
if !meta.is_file() {
return refuse("not a regular file");
}
if meta.uid() != rustix::process::geteuid().as_raw() {
return refuse("owned by another user");
}
if meta.mode() & 0o077 != 0 {
return refuse("readable or writable by other users");
}
file
};
#[cfg(not(unix))]
let file = std::fs::File::open(path)?;
let mut out = String::new();
file.take(MAX_TOKEN_FILE_BYTES).read_to_string(&mut out)?;
Ok(out)
}
/// Compare equal-length tokens without an early exit.
@@ -134,6 +189,27 @@ impl Drop for Permit {
}
}
/// Closes a connection that has not authenticated in time, so idle or trickling clients can't
/// hold the few connection slots. Drop it once the client is authenticated (or gone).
pub struct AuthDeadline {
_cancel: Sender<()>,
}
impl AuthDeadline {
/// Shut `stream` down after `timeout` unless the returned deadline is dropped first.
pub fn start(stream: &TcpStream, timeout: Duration) -> std::io::Result<AuthDeadline> {
let stream = stream.try_clone()?;
let (tx, rx) = channel::<()>();
std::thread::Builder::new().name("materialcraft-auth-deadline".into()).spawn(move || {
// Dropping the deadline disconnects the channel and ends this thread at once.
if let Err(RecvTimeoutError::Timeout) = rx.recv_timeout(timeout) {
let _ = stream.shutdown(Shutdown::Both);
}
})?;
Ok(AuthDeadline { _cancel: tx })
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -149,6 +225,76 @@ mod tests {
assert!(client_token(1, Some(format!(" {a}\n"))).is_ok());
}
fn scratch(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("mc-token-{}-{name}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn token_files_round_trip_and_replace_old_ones() {
let dir = scratch("round-trip");
let path = dir.join("t.token");
write_token_file(&path, "first-token-0123456789").unwrap();
assert_eq!(read_token_file(&path).unwrap(), "first-token-0123456789");
write_token_file(&path, "second-token-0123456789").unwrap();
assert_eq!(read_token_file(&path).unwrap(), "second-token-0123456789");
let _ = std::fs::remove_dir_all(dir);
}
#[cfg(unix)]
#[test]
fn token_files_are_owner_only_even_over_an_open_file() {
use std::os::unix::fs::PermissionsExt;
let dir = scratch("perms");
let path = dir.join("t.token");
std::fs::write(&path, "old").unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o666)).unwrap();
write_token_file(&path, "fresh-token-0123456789").unwrap();
assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
let _ = std::fs::remove_dir_all(dir);
}
#[cfg(unix)]
#[test]
fn token_files_never_write_through_a_symlink() {
let dir = scratch("symlink-write");
let (path, victim) = (dir.join("t.token"), dir.join("victim"));
std::fs::write(&victim, "keep me").unwrap();
std::os::unix::fs::symlink(&victim, &path).unwrap();
write_token_file(&path, "fresh-token-0123456789").unwrap();
assert_eq!(std::fs::read_to_string(&victim).unwrap(), "keep me");
assert!(!std::fs::symlink_metadata(&path).unwrap().file_type().is_symlink());
let _ = std::fs::remove_dir_all(dir);
}
#[cfg(unix)]
#[test]
fn unsafe_token_files_are_refused() {
use std::os::unix::fs::PermissionsExt;
let dir = scratch("refuse");
// Readable by others: another user may have planted or read it.
let open = dir.join("open.token");
std::fs::write(&open, "planted-token-0123456789").unwrap();
std::fs::set_permissions(&open, std::fs::Permissions::from_mode(0o644)).unwrap();
assert!(read_token_file(&open).is_err());
// A symlink, even to an owner-only file: a client must not send that file as its token.
let secret = dir.join("secret");
write_token_file(&secret, "private-0123456789abcdef").unwrap();
let link = dir.join("link.token");
std::os::unix::fs::symlink(&secret, &link).unwrap();
assert!(read_token_file(&link).is_err());
// A FIFO is refused without blocking on open or read.
let fifo = dir.join("fifo.token");
if std::process::Command::new("mkfifo").arg(&fifo).status().is_ok_and(|s| s.success()) {
assert!(read_token_file(&fifo).is_err());
}
// A directory is not a token.
assert!(read_token_file(&dir).is_err());
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn oversized_lines_are_skipped() {
let input = format!("{}\n{{\"ok\":1}}\n", "x".repeat(MAX_REQUEST_BYTES + 10));
@@ -160,6 +306,26 @@ mod tests {
assert!(matches!(read_bounded_line(&mut r, &mut line).unwrap(), LineRead::Eof));
}
#[test]
fn auth_deadline_closes_idle_connections_only() {
let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap();
let addr = listener.local_addr().unwrap();
let idle = TcpStream::connect(addr).unwrap();
let (server_idle, _) = listener.accept().unwrap();
let _deadline = AuthDeadline::start(&server_idle, Duration::from_millis(200)).unwrap();
let mut buf = [0u8; 1];
idle.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
assert_eq!(std::io::Read::read(&mut &idle, &mut buf).unwrap(), 0, "closed by the deadline");
let kept = TcpStream::connect(addr).unwrap();
let (server_kept, _) = listener.accept().unwrap();
drop(AuthDeadline::start(&server_kept, Duration::from_millis(200)).unwrap());
std::thread::sleep(Duration::from_millis(400));
(&server_kept).write_all(b"x").unwrap();
kept.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
assert_eq!(std::io::Read::read(&mut &kept, &mut buf).unwrap(), 1, "a met deadline leaves the connection open");
}
#[test]
fn limiter_releases() {
let l = ConnectionLimiter::default();
+49 -5
View File
@@ -154,11 +154,30 @@ 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>,
}
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct MaterialExportParams {
/// Forward-slash path relative to the write root (`.mcmat` is appended if missing). The
/// parent folder must exist.
pub path: String,
/// Graph index (default: the open graph).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub graph: Option<u32>,
/// Square size in pixels, rounded to a power of two from 16 to 8192 (default: the graph's size).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub size: Option<u32>,
/// Exposed input values to cook with and embed, by input id (see `session_inspect`).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub values: Option<Value>,
}
#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
pub struct RenderParams {
/// `3d` (default: the material on the 3D view's scene) or `2d` (a node's output).
@@ -189,11 +208,10 @@ pub struct RenderParams {
/// 3D: UV repeats of the material on the scene for this render only.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tiling: Option<f32>,
/// 3D beauty render: real displacement from the height output, ambient occlusion and a
/// shadowed key light (slower).
/// 3D beauty render: a finer displaced mesh, ambient occlusion and a shadowed key light (slower).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub hq: Option<bool>,
/// With `hq`: displacement depth in scene radii (default 0.04).
/// With `hq`: displacement depth in scene radii (default: the view's height depth).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub displacement: Option<f32>,
}
@@ -305,7 +323,7 @@ impl MaterialcraftMcp {
b.call(method, p).await
}
"package.save" if p.get("path").is_none() => b.call("ui.menu.invoke", json!({"id": "file.save"})).await,
"package.save" | "package.open" | "bitmap.import" | "outputs.export" | "command.batch" | "render" => {
"package.save" | "package.open" | "bitmap.import" | "outputs.export" | "material.export" | "command.batch" | "render" => {
Err(bad(format!("`{method}` with paths works in headless mode only: the running app reads and writes its own files (use ui_menu_invoke)")))
}
_ => b.call(method, p).await,
@@ -430,6 +448,13 @@ impl MaterialcraftMcp {
to_result(self.call("outputs.export", params(&p)).await)
}
#[tool(description = "Cook a graph at full size and write it as a portable .mcmat material (cooked maps, exposed inputs, \
source package) to a path relative to the write root, for TextureCraft. Optional graph, size and exposed input values. \
Returns {path, bytes}.")]
async fn material_export(&self, Parameters(p): Parameters<MaterialExportParams>) -> Result<CallToolResult, McpError> {
to_result(self.call("material.export", params(&p)).await)
}
#[tool(description = "Headless: render the material on the 3D view's scene, or a node's output (view 2d), as a PNG up to \
2048 px a side. In bridge mode use view_screenshot.")]
async fn view_render(&self, Parameters(p): Parameters<RenderParams>) -> Result<CallToolResult, McpError> {
@@ -471,7 +496,7 @@ impl MaterialcraftMcp {
(usages baseColor, normal, roughness, metallic, height, ambientOcclusion) make a PBR material. Start with graph_new \
(templates: pbr, bricks, wood, …) or package_open, browse nodes with library_list, build with node_add / node_connect \
/ node_param (or command_run/command_batch for anything else: command_list), check your work with session_inspect and \
view_render (3d, or 2d for one node), then package_save and outputs_export. Undo: command_run edit.undo."
view_render (3d, or 2d for one node), then package_save, outputs_export or material_export (.mcmat for TextureCraft). Undo: command_run edit.undo."
)]
impl ServerHandler for MaterialcraftMcp {}
@@ -493,6 +518,25 @@ mod tests {
assert!(mcp.call("session.inspect", json!({})).await.is_ok());
}
#[tokio::test(flavor = "multi_thread")]
async fn material_export_tool_writes_through_the_workspace_only() {
let base = std::env::temp_dir().join(format!("mc-mcp-{}-material", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
std::fs::create_dir_all(&base).unwrap();
let args = || Parameters(MaterialExportParams { path: "m".into(), graph: None, size: Some(16), values: None });
let denied = MaterialcraftMcp::headless(Headless::new(materialcraft_engine::sample_session(), Filesystem::Denied));
assert_eq!(denied.material_export(args()).await.unwrap().is_error, Some(true));
let ws = crate::AuthorizedWorkspace::new(None, Some(&base)).unwrap();
let mcp = MaterialcraftMcp::headless(Headless::new(materialcraft_engine::sample_session(), Filesystem::Workspace(ws)));
assert_eq!(mcp.material_export(args()).await.unwrap().is_error, Some(false));
assert!(base.join("m.mcmat").is_file());
let escape = Parameters(MaterialExportParams { path: "../m.mcmat".into(), graph: None, size: Some(16), values: None });
assert_eq!(mcp.material_export(escape).await.unwrap().is_error, Some(true));
assert!(!base.parent().unwrap().join("m.mcmat").exists());
}
#[test]
fn oversized_replies_become_errors() {
let r = ok_json(&json!("x".repeat(crate::budgets::MAX_RESPONSE_BYTES)));
+7
View File
@@ -69,6 +69,13 @@ impl AuthorizedWorkspace {
Ok(())
}
/// Fail now, before any expensive work, when [`write`](Self::write) to `path` cannot succeed
/// for lack of a write root or because the path is malformed.
pub fn check_write(&self, path: &str) -> Result<(), AutomationError> {
relative_path(path)?;
self.write.as_ref().map(|_| ()).ok_or_else(|| denied("write"))
}
/// Create a directory (and its parents) below the write root.
pub fn create_dir_all(&self, path: &str) -> Result<(), AutomationError> {
let rel = relative_path(path)?;
+1 -1
View File
@@ -17,7 +17,7 @@ pub use graph::{
Attributes, BaseParams, Comment, Connection, ExposedParam, Frame, Graph, GraphKind, MAX_SIZE_LOG2, MIN_SIZE_LOG2, MISSING_NODE, Node, NodeId, OutputFormat,
Pin, Preset, SizeMode, missing_ports,
};
pub use package::{PACKAGE_EXT, Package, Resource};
pub use package::{PACKAGE_EXT, Package, Resource, ResourceBytes};
pub use value::{Curve, CurvePoint, Gradient, GradientKey, Value, linear_to_srgb, parse_color, srgb_to_linear};
#[derive(Debug, thiserror::Error)]
+80 -1
View File
@@ -1,5 +1,6 @@
//! Packages: the document. A package holds graphs and the resources (bitmaps) they use.
use std::hash::{DefaultHasher, Hash, Hasher};
use std::sync::Arc;
use serde::{Deserialize, Serialize};
@@ -18,7 +19,68 @@ pub struct Resource {
pub file: String,
/// The file's bytes (stored in the zip, not in `package.json`).
#[serde(skip)]
pub bytes: Arc<Vec<u8>>,
pub bytes: ResourceBytes,
}
impl Resource {
/// A resource named `name`, stored as `file` in the package.
pub fn new(name: impl Into<String>, file: impl Into<String>, bytes: ResourceBytes) -> Resource {
Resource { name: name.into(), file: file.into(), bytes }
}
}
/// A resource's bytes with a hash of their whole content, computed once when the bytes are
/// set, so caches can key on content (two files of one size are not the same image).
#[derive(Clone, Debug)]
pub struct ResourceBytes {
bytes: Arc<Vec<u8>>,
hash: u64,
}
impl ResourceBytes {
/// Take ownership of `bytes` and hash them.
pub fn new(bytes: Vec<u8>) -> ResourceBytes {
let mut h = DefaultHasher::new();
bytes.hash(&mut h);
ResourceBytes { hash: h.finish(), bytes: Arc::new(bytes) }
}
/// The bytes.
pub fn as_slice(&self) -> &[u8] {
&self.bytes
}
/// Number of bytes.
pub fn len(&self) -> usize {
self.bytes.len()
}
/// Whether there are no bytes.
pub fn is_empty(&self) -> bool {
self.bytes.is_empty()
}
/// Hash of the whole content.
pub fn content_hash(&self) -> u64 {
self.hash
}
/// Whether both values share one allocation (cheap clones of one file).
pub fn ptr_eq(&self, other: &ResourceBytes) -> bool {
Arc::ptr_eq(&self.bytes, &other.bytes)
}
}
impl Default for ResourceBytes {
fn default() -> Self {
ResourceBytes::new(Vec::new())
}
}
impl PartialEq for ResourceBytes {
fn eq(&self, other: &Self) -> bool {
self.hash == other.hash && self.bytes == other.bytes
}
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
@@ -66,3 +128,20 @@ impl Package {
(1..).map(|i| format!("{base}_{i}")).find(|n| self.graph_by_name(n).is_none()).unwrap_or_else(|| base.to_string())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn same_length_same_prefix_bytes_hash_differently() {
let a = vec![7u8; 200];
let mut b = a.clone();
b[150] = 8;
let (a, b) = (ResourceBytes::new(a), ResourceBytes::new(b));
assert_eq!(a.len(), b.len());
assert_ne!(a.content_hash(), b.content_hash());
assert_ne!(a, b);
assert_eq!(ResourceBytes::default(), ResourceBytes::new(Vec::new()));
}
}
+25 -11
View File
@@ -7,7 +7,7 @@
use serde_json::{Value as J, json};
use materialcraft_core::{Package, Resource};
use materialcraft_core::{Package, Resource, ResourceBytes};
use materialcraft_formats::{Depth, encode, output_name};
use crate::commands::{CommandSpec, always, bad, has_graph, strp, u64p};
@@ -50,7 +50,7 @@ pub(crate) fn specs() -> Vec<CommandSpec> {
"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
),
@@ -95,6 +95,7 @@ fn new_package(s: &mut Session, p: &J) -> Result<J> {
/// Make `pkg` the session's document (after open/new): history and views reset.
pub fn replace_package(s: &mut Session, pkg: Package, path: Option<String>) {
s.pkg = pkg;
s.clear_decoded();
s.path = path;
s.graph = 0;
s.selection.clear();
@@ -265,9 +266,19 @@ 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 = materialcraft_eval::cook(&pkg, gi, &materialcraft_eval::Options::new(&dec), &s.cache);
let mut out = Vec::new();
for (id, usage, ident, img) in materialcraft_eval::outputs(g, &cooked) {
let Some(img) = img else { continue };
@@ -283,8 +294,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();
@@ -299,14 +312,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 {
@@ -339,7 +353,7 @@ pub(crate) fn push_resource(pkg: &mut Package, file: &str, bytes: Vec<u8>, name:
name = format!("{stem}_{i}");
i += 1;
}
pkg.resources.push(Resource { name: name.clone(), file: format!("{name}_{file}"), bytes: std::sync::Arc::new(bytes) });
pkg.resources.push(Resource::new(name.clone(), format!("{name}_{file}"), ResourceBytes::new(bytes)));
name
}
+11 -6
View File
@@ -72,10 +72,7 @@ pub fn material_bytes(s: &Session, gi: usize, o: &MaterialOptions) -> Result<Vec
let dec = s.resource_decoder();
let mut opts = materialcraft_eval::Options::new(&dec);
opts.inputs = o.inputs.clone();
let cooked = {
let mut cache = s.cache.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
materialcraft_eval::cook(&pkg, gi, &opts, &mut cache)
};
let cooked = materialcraft_eval::cook(&pkg, gi, &opts, &s.cache);
let mut maps: Vec<(String, Vec<u8>)> = Vec::new();
let mut entries = Vec::new();
let mut size = [0, 0];
@@ -144,13 +141,21 @@ fn graph_param(s: &Session, p: &J) -> Result<usize> {
Ok(gi)
}
/// The graph and cook options a material export request asks for: `graph?`, `size?` (px) and
/// `values?` (exposed input values). Shared by `file.exportMaterial` and the workspace-scoped
/// automation export, which supply their own destination.
pub fn material_request(s: &Session, cmd: &str, p: &J) -> Result<(usize, MaterialOptions)> {
let gi = graph_param(s, p)?;
let o = MaterialOptions { size: u64p(p, "size").map(|v| v.min(8192) as u32), values: values_param(cmd, s.pkg.graph(gi)?, p)?, ..Default::default() };
Ok((gi, o))
}
#[cfg(not(target_arch = "wasm32"))]
fn export_material(s: &mut Session, p: &J) -> Result<J> {
const CMD: &str = "file.exportMaterial";
let path = strp(p, "path").ok_or_else(|| bad(CMD, "`path` is required"))?;
let path = if path.to_ascii_lowercase().ends_with(&format!(".{MATERIAL_EXT}")) { path.to_string() } else { format!("{path}.{MATERIAL_EXT}") };
let gi = graph_param(s, p)?;
let mut o = MaterialOptions { size: u64p(p, "size").map(|v| v.min(8192) as u32), values: values_param(CMD, s.pkg.graph(gi)?, p)?, ..Default::default() };
let (gi, mut o) = material_request(s, CMD, p)?;
for (id, file) in p.get("inputs").and_then(J::as_object).into_iter().flatten() {
let file = file.as_str().ok_or_else(|| bad(CMD, format!("inputs.{id} must be an image path")))?;
let bytes = std::fs::read(file).map_err(|e| bad(CMD, format!("{file}: {e}")))?;
+20 -15
View File
@@ -4,7 +4,7 @@
use std::collections::HashMap;
use std::sync::{Arc, Mutex, PoisonError};
use materialcraft_core::{Graph, NodeId, Package};
use materialcraft_core::{Graph, NodeId, Package, ResourceBytes};
use materialcraft_eval::{Cache, Cooked, Options};
use materialcraft_image::Image;
use serde::{Deserialize, Serialize};
@@ -32,8 +32,10 @@ pub struct View3d {
pub environment: String,
pub env_rotation: f32,
pub exposure: f32,
/// Parallax depth of the height output (0 = off).
/// How far the height output raises the surface (white above black), in mesh radii; 0 = off.
pub height_scale: f32,
/// The height (0..1) that stays on the surface: 0 = the relief rises out of the mesh, 0.5 = centered on it.
pub height_level: f32,
pub show_axis: bool,
pub show_grid: bool,
/// See through the mesh where the material's alpha (opacity output, else base color alpha)
@@ -55,7 +57,8 @@ impl Default for View3d {
environment: "studio".into(),
env_rotation: 0.0,
exposure: 0.0,
height_scale: 0.012,
height_scale: 0.04,
height_level: 0.0,
show_axis: false,
show_grid: false,
transparency: true,
@@ -158,7 +161,7 @@ pub struct Session {
redo: Vec<Snapshot>,
/// Edits with the same key coalesce into one undo step (slider drags).
merge_key: Option<String>,
decoded: Arc<Mutex<HashMap<String, Image>>>,
decoded: Arc<Mutex<HashMap<u64, Image>>>,
}
impl Session {
@@ -298,40 +301,42 @@ impl Session {
/// A decoder for the package's bitmap resources (memoized, shareable with worker threads).
pub fn resource_decoder(&self) -> impl Fn(&str) -> Option<Image> + Sync + Send + 'static {
let res: Vec<(String, Arc<Vec<u8>>)> = self.pkg.resources.iter().map(|r| (r.name.clone(), r.bytes.clone())).collect();
let res: Vec<(String, ResourceBytes)> = self.pkg.resources.iter().map(|r| (r.name.clone(), r.bytes.clone())).collect();
let memo = self.decoded.clone();
// Free images of resources that were deleted or replaced.
memo.lock().unwrap_or_else(PoisonError::into_inner).retain(|k, _| res.iter().any(|(_, b)| b.content_hash() == *k));
move |name: &str| {
let (_, bytes) = res.iter().find(|(n, _)| n == name)?;
let key = format!("{name}:{}", bytes.len());
let key = bytes.content_hash();
if let Some(i) = memo.lock().unwrap_or_else(PoisonError::into_inner).get(&key) {
return Some(i.clone());
}
let img = materialcraft_formats::decode(bytes).ok()?;
let img = materialcraft_formats::decode(bytes.as_slice()).ok()?;
memo.lock().unwrap_or_else(PoisonError::into_inner).insert(key, img.clone());
Some(img)
}
}
/// Forget every decoded resource image (the package was replaced).
pub(crate) fn clear_decoded(&self) {
self.decoded.lock().unwrap_or_else(PoisonError::into_inner).clear();
}
/// Cook the open graph now (at the preview size), on this thread.
pub fn cook(&mut self) -> &Cooked {
let dec = self.resource_decoder();
let mut opts = Options::new(&dec);
opts.max_size = self.preview_size;
let cooked = {
let mut cache = self.cache.lock().unwrap_or_else(PoisonError::into_inner);
materialcraft_eval::cook(&self.pkg, self.graph, &opts, &mut cache)
};
self.cooked = cooked;
self.cooked = materialcraft_eval::cook(&self.pkg, self.graph, &opts, &self.cache);
self.dirty = false;
&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);
let mut cache = self.cache.lock().unwrap_or_else(PoisonError::into_inner);
materialcraft_eval::cook(&self.pkg, gi, &opts, &mut cache)
materialcraft_eval::cook(&self.pkg, gi, &opts, &self.cache)
}
/// Cook if the graph changed since the last cook.
+4 -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?, transparency? (see through where alpha < 1), alphaView? (show the alpha channel)}",
"{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? (displacement depth in mesh radii, 0..0.5), heightLevel? (height that stays on the surface, 0..1; 0 = rises out), axis?, grid?, transparency? (see through where alpha < 1), alphaView? (show the alpha channel)}",
always,
view3d
),
@@ -138,6 +138,9 @@ fn view3d(s: &mut Session, p: &J) -> Result<J> {
if let Some(t) = f32p(p, "heightScale") {
v.height_scale = t.clamp(0.0, 0.5);
}
if let Some(t) = f32p(p, "heightLevel") {
v.height_level = t.clamp(0.0, 1.0);
}
if let Some(b) = boolp(p, "axis") {
v.show_axis = b;
}
+55
View File
@@ -0,0 +1,55 @@
//! Cook benchmarks (run with `--ignored --nocapture` in release).
use std::time::Instant;
use materialcraft_engine::{Session, execute, sample_session};
use serde_json::{Value, json};
fn run(s: &mut Session, id: &str, p: Value) -> Value {
execute(s, id, &p).unwrap_or_else(|e| panic!("{id}: {e}"))
}
/// The `rusty_metal` template plus an exposed input `level` read by one unconnected `uniform`.
fn heavy(size: u64) -> (Session, u64) {
let mut s = sample_session();
run(&mut s, "file.new", json!({"template": "rusty_metal", "size": size}));
s.preview_size = None;
let u = run(&mut s, "graph.node.add", json!({"def": "uniform", "params": {"mode": 1}}))["id"].as_u64().unwrap();
run(&mut s, "graph.exposed.add", json!({"id": "level", "default": {"t": "float", "v": 0.25}}));
let f = json!({"nodes": [{"id": 1, "op": "get_var", "value": {"t": "text", "v": "level"}}], "output": 1});
run(&mut s, "graph.node.function", json!({"id": u, "param": "color", "function": f}));
(s, u)
}
fn timed(s: &mut Session) -> (f64, usize, usize) {
let t = Instant::now();
s.cook();
let ms = t.elapsed().as_secs_f64() * 1000.0;
(ms, s.cooked.nodes.values().filter(|r| !r.cached).count(), s.cooked.nodes.len())
}
#[test]
#[ignore = "benchmark"]
fn bench_input_change() {
println!("size, cold_ms, warm_ms, input_change_ms, recooked_nodes, total_nodes");
for size in [1024, 2048] {
let (mut s, _) = heavy(size);
let (cold, ..) = timed(&mut s);
let (warm, ..) = timed(&mut s);
run(&mut s, "graph.exposed.set", json!({"id": "level", "value": 0.75}));
let (change, recooked, total) = timed(&mut s);
println!("{size}, {cold:.1}, {warm:.1}, {change:.1}, {recooked}, {total}");
}
}
#[test]
#[ignore = "benchmark"]
fn bench_param_edit() {
println!("size, cold_ms, param_edit_ms, recooked_nodes, total_nodes");
for size in [1024, 2048] {
let (mut s, u) = heavy(size);
let (cold, ..) = timed(&mut s);
run(&mut s, "graph.node.param", json!({"id": u, "param": "mode", "value": 0}));
let (edit, recooked, total) = timed(&mut s);
println!("{size}, {cold:.1}, {edit:.1}, {recooked}, {total}");
}
}
+76
View File
@@ -83,9 +83,35 @@ 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);
@@ -267,6 +293,22 @@ fn dynamic_parameters_follow_graph_inputs() {
assert!((mean(&s) - 0.5).abs() < 0.05);
}
#[test]
fn exposed_input_change_recooks_only_readers() {
let mut s = sample_session();
run(&mut s, "file.new", json!({"template": "rusty_metal", "size": 64}));
s.preview_size = None;
let u = run(&mut s, "graph.node.add", json!({"def": "uniform", "params": {"mode": 1}}))["id"].as_u64().unwrap();
run(&mut s, "graph.exposed.add", json!({"id": "level", "default": {"t": "float", "v": 0.25}}));
let f = json!({"nodes": [{"id": 1, "op": "get_var", "value": {"t": "text", "v": "level"}}], "output": 1});
run(&mut s, "graph.node.function", json!({"id": u, "param": "color", "function": f}));
s.cook();
run(&mut s, "graph.exposed.set", json!({"id": "level", "value": 0.75}));
s.cook();
let recooked: Vec<u64> = s.cooked.nodes.iter().filter(|(_, r)| !r.cached).map(|(id, _)| id.0).collect();
assert_eq!(recooked, [u], "only the node reading `level` re-cooks");
}
#[test]
fn presets_store_and_restore_inputs() {
let mut s = sample_session();
@@ -297,6 +339,24 @@ fn view3d_target_is_validated_clamped_and_reset() {
assert_eq!(s.view3d.target, [0.0; 3]);
}
/// The height output rises out of the mesh by default; depth and level are clamped and reset with the scene.
#[test]
fn view3d_height_depth_and_level_are_clamped_and_reset() {
let mut s = sample_session();
assert_eq!(s.view3d.height_level, 0.0, "the relief rises out of the surface by default");
assert!(s.view3d.height_scale > 0.0);
let view = run(&mut s, "view.3d", json!({"heightScale": 0.1, "heightLevel": 0.5}));
assert_eq!((view["heightScale"].as_f64(), view["heightLevel"].as_f64()), (Some(0.1f32 as f64), Some(0.5)));
run(&mut s, "view.3d", json!({"heightScale": 9.0, "heightLevel": -3.0}));
assert_eq!((s.view3d.height_scale, s.view3d.height_level), (0.5, 0.0));
run(&mut s, "view.3d", json!({"heightLevel": 7.0}));
assert_eq!(s.view3d.height_level, 1.0);
run(&mut s, "view.3d.reset", json!({}));
assert_eq!(s.view3d.height_level, 0.0);
}
#[test]
fn camera_prefs_bound_the_pan_and_survive_hostile_values() {
use materialcraft_engine::CameraPrefs;
@@ -317,6 +377,22 @@ fn camera_prefs_bound_the_pan_and_survive_hostile_values() {
assert_eq!(CameraPrefs { pan_limit: f32::INFINITY, pan_speed: 2.0 }.sanitized().pan_speed, 2.0);
}
#[test]
fn reimported_bitmap_shows_new_pixels() {
use materialcraft_formats::{Depth, encode};
use materialcraft_image::{Image, Kind};
let bmp = |v: f32| encode(&Image::filled(4, 4, Kind::Color, [v, v, v, 1.0]), "bmp", Depth::U8, true).unwrap();
let (dark, light) = (bmp(0.1), bmp(0.9));
assert_eq!(dark.len(), light.len(), "same-size files are the case under test");
let mut s = sample_session();
materialcraft_engine::file_cmds::add_resource(&mut s, "tex.bmp", dark, Some("tex")).unwrap();
let before = s.resource_decoder()("tex").unwrap().data[0];
s.undo();
materialcraft_engine::file_cmds::add_resource(&mut s, "tex.bmp", light, Some("tex")).unwrap();
let after = s.resource_decoder()("tex").unwrap().data[0];
assert!(after - before > 0.5, "{before} -> {after}");
}
#[test]
fn a_wire_splits_with_a_reroute_dot_and_deletes() {
let mut s = sample_session();
+257 -31
View File
@@ -9,14 +9,14 @@
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
use std::collections::{BTreeMap, HashMap};
use std::collections::{BTreeMap, HashMap, HashSet};
use std::hash::{DefaultHasher, Hash, Hasher};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use materialcraft_core::{Graph, Node, NodeId, Package, SizeMode, Value};
use materialcraft_image::{Image, Kind};
use materialcraft_nodes::{Ctx, NodeDef, PortKind, find, resolve_params};
use materialcraft_nodes::{Ctx, NodeDef, PortKind, clamp_params, find, resolve_params};
/// Sub-graphs may nest this deep (a graph instancing itself would recurse forever).
pub const MAX_DEPTH: u32 = 8;
@@ -184,11 +184,13 @@ pub struct Options<'a> {
/// Set from another thread to stop between nodes.
pub cancel: Option<&'a AtomicBool>,
pub depth: u32,
/// Graphs being cooked around this one, outermost first (cycle detection).
pub graph_stack: Vec<usize>,
}
impl<'a> Options<'a> {
pub fn new(resource: &'a (dyn Fn(&str) -> Option<Image> + Sync)) -> Options<'a> {
Options { max_size: None, only: None, inputs: BTreeMap::new(), overrides: BTreeMap::new(), resource, cancel: None, depth: 0 }
Options { max_size: None, only: None, inputs: BTreeMap::new(), overrides: BTreeMap::new(), resource, cancel: None, depth: 0, graph_stack: Vec::new() }
}
}
@@ -257,8 +259,14 @@ pub fn function_value(like: &Value, v: [f32; 4]) -> Option<Value> {
})
}
/// Cook graph `gi` of `pkg`.
pub fn cook(pkg: &Package, gi: usize, opts: &Options, cache: &mut Cache) -> Cooked {
/// Lock the cache, recovering from a poisoned lock (a cache entry is never half-written).
fn lock(cache: &Mutex<Cache>) -> std::sync::MutexGuard<'_, Cache> {
cache.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}
/// Cook graph `gi` of `pkg`. The cache is locked only around lookups and inserts, never while a
/// node cooks, so other users of the cache are not blocked for the length of a cook.
pub fn cook(pkg: &Package, gi: usize, opts: &Options, cache: &Mutex<Cache>) -> Cooked {
let t0 = now_ms();
let mut out = Cooked::default();
let Some(graph) = pkg.graphs.get(gi) else { return out };
@@ -267,7 +275,7 @@ pub fn cook(pkg: &Package, gi: usize, opts: &Options, cache: &mut Cache) -> Cook
let opts = if opts.depth == 0 && !graph.input_images.is_empty() {
let mut inputs: BTreeMap<String, Image> = graph.input_images.iter().filter_map(|(id, res)| Some((id.clone(), (opts.resource)(res)?))).collect();
inputs.extend(opts.inputs.iter().map(|(k, v)| (k.clone(), v.clone())));
bound = Options { only: opts.only.clone(), inputs, overrides: opts.overrides.clone(), ..*opts };
bound = Options { only: opts.only.clone(), inputs, overrides: opts.overrides.clone(), graph_stack: opts.graph_stack.clone(), ..*opts };
&bound
} else {
opts
@@ -294,14 +302,68 @@ pub fn cook(pkg: &Package, gi: usize, opts: &Options, cache: &mut Cache) -> Cook
break;
}
let Ok(node) = graph.node(id) else { continue };
let r = cook_node(pkg, graph, node, &out, &vars, opts, cache);
let r = cook_node(pkg, gi, graph, node, &out, &vars, opts, cache);
out.nodes.insert(id, r);
}
out.ms = (now_ms() - t0) as f32;
out
}
fn cook_node(pkg: &Package, graph: &Graph, node: &Node, done: &Cooked, vars: &BTreeMap<String, Value>, opts: &Options, cache: &mut Cache) -> NodeResult {
/// Hash each reachable graph and its resource content once. An iterative walk keeps
/// deep chains and graphs with many shared instances bounded by the package size.
fn graph_tree_hash(pkg: &Package, gi: usize) -> u64 {
let mut h = DefaultHasher::new();
let mut pending = vec![gi];
let mut seen = HashSet::new();
while let Some(index) = pending.pop() {
if !seen.insert(index) {
continue;
}
let Some(graph) = pkg.graphs.get(index) else { continue };
index.hash(&mut h);
serde_json::to_string(graph).unwrap_or_default().hash(&mut h);
for n in &graph.nodes {
if let Some(Value::Text(name)) = n.params.get("resource") {
pkg.resource(name).map(|r| r.bytes.content_hash()).hash(&mut h);
}
if n.def == "graph_instance"
&& let Some((si, _)) = instance_graph(pkg, n)
{
pending.push(si);
}
}
}
h.finish()
}
/// The graph inputs a node's cook can read: those named by `get_*` ops of its function-valued
/// parameters. Bindings and node functions are already folded into `params` before the key is
/// computed, so these are the only remaining readers of `vars` (`Ctx::vars` in the function nodes).
/// Matching every `get_*` op, not only `get_var`, over-approximates on purpose.
fn vars_read<'v>(params: &BTreeMap<String, Value>, vars: &'v BTreeMap<String, Value>) -> Vec<(&'v str, &'v Value)> {
let mut read: Vec<(&str, &Value)> = params
.values()
.filter_map(|v| if let Value::Function(g) = v { Some(g) } else { None })
.flat_map(|g| g.nodes.iter())
.filter(|n| n.op.starts_with("get_"))
.filter_map(|n| if let Some(Value::Text(name)) = &n.value { vars.get_key_value(name.as_str()) } else { None })
.map(|(k, v)| (k.as_str(), v))
.collect();
read.sort_by_key(|(k, _)| *k);
read.dedup_by_key(|(k, _)| *k);
read
}
fn cook_node(
pkg: &Package,
gi: usize,
graph: &Graph,
node: &Node,
done: &Cooked,
vars: &BTreeMap<String, Value>,
opts: &Options,
cache: &Mutex<Cache>,
) -> NodeResult {
let (in_ports, out_ports) = ports(pkg, node);
let def = find(&node.def);
// Gather inputs by port order, with their keys.
@@ -352,15 +414,20 @@ fn cook_node(pkg: &Package, graph: &Graph, node: &Node, done: &Cooked, vars: &BT
Err(e) => return fail(format!("function of `{param}`: {e}"), 0),
}
}
// Hard limits on whatever files, bindings and functions supplied (a value can't hang a cook).
if let Some(d) = def
&& node.def != "graph_instance"
{
clamp_params(d, &mut params);
}
let tile = node.base.tiling[0] && node.base.tiling[1];
// Input nodes read the caller's image for their identifier.
let input_img = node.def.starts_with("input_").then(|| opts.inputs.get(&identifier(node))).flatten();
let res_hash = match params.get("resource") {
Some(Value::Text(name)) => pkg.resource(name).map_or(0, |r| hash_of(&(r.bytes.len(), r.bytes.get(..64.min(r.bytes.len())).map(|b| b.to_vec())))),
Some(Value::Text(name)) => pkg.resource(name).map_or(0, |r| r.bytes.content_hash()),
_ => 0,
};
let sub_hash =
if node.def == "graph_instance" { instance_graph(pkg, node).map_or(0, |(_, g)| hash_of(&serde_json::to_string(g).unwrap_or_default())) } else { 0 };
let sub_hash = if node.def == "graph_instance" { instance_graph(pkg, node).map_or(0, |(si, _)| graph_tree_hash(pkg, si)) } else { 0 };
let key = hash_of(&(
&node.def,
serde_json::to_string(&params).unwrap_or_default(),
@@ -369,9 +436,9 @@ fn cook_node(pkg: &Package, graph: &Graph, node: &Node, done: &Cooked, vars: &BT
res_hash,
sub_hash,
input_img.map(image_key),
serde_json::to_string(vars).unwrap_or_default(),
serde_json::to_string(&vars_read(&params, vars)).unwrap_or_default(),
));
if let Some(v) = cache.get(key) {
if let Some(v) = lock(cache).get(key) {
return NodeResult { outputs: v, error: None, ms: 0.0, key, cached: true };
}
let t0 = now_ms();
@@ -384,7 +451,7 @@ fn cook_node(pkg: &Package, graph: &Graph, node: &Node, done: &Cooked, vars: &BT
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)
cook_instance(pkg, gi, node, &in_ports, &out_ports, &inputs, &params, (w, h), opts, cache)
} else if let Some(d) = def {
let ctx = Ctx { w, h, seed, tile, inputs: &inputs, params: &params, resource: opts.resource, vars };
(d.cook)(&ctx)
@@ -394,7 +461,7 @@ fn cook_node(pkg: &Package, graph: &Graph, node: &Node, done: &Cooked, vars: &BT
match result {
Ok(imgs) if imgs.len() == out_ports.len().max(1) || out_ports.is_empty() => {
let v = Arc::new(imgs);
cache.put(key, v.clone());
lock(cache).put(key, v.clone());
NodeResult { outputs: v, error: None, ms: (now_ms() - t0) as f32, key, cached: false }
}
Ok(imgs) => fail(format!("`{}` made {} images for {} outputs", node.def, imgs.len(), out_ports.len()), key),
@@ -402,8 +469,28 @@ fn cook_node(pkg: &Package, graph: &Graph, node: &Node, done: &Cooked, vars: &BT
}
}
/// Whether graph `from` reaches `target`, without recursive stack growth.
fn instances_reach(pkg: &Package, from: usize, target: usize) -> bool {
let mut pending = vec![from];
let mut seen = HashSet::new();
while let Some(index) = pending.pop() {
if !seen.insert(index) {
continue;
}
let Some(graph) = pkg.graphs.get(index) else { continue };
for (si, _) in graph.nodes.iter().filter(|n| n.def == "graph_instance").filter_map(|n| instance_graph(pkg, n)) {
if si == target {
return true;
}
pending.push(si);
}
}
false
}
fn cook_instance(
pkg: &Package,
gi: usize,
node: &Node,
in_ports: &[Port],
out_ports: &[Port],
@@ -411,19 +498,24 @@ fn cook_instance(
params: &BTreeMap<String, Value>,
size: (u32, u32),
opts: &Options,
cache: &mut Cache,
cache: &Mutex<Cache>,
) -> Result<Vec<Image>, String> {
if opts.depth >= MAX_DEPTH {
return Err("graph instances nest too deep (does a graph use itself?)".into());
}
let (gi, sub) = instance_graph(pkg, node).ok_or("the instanced graph does not exist")?;
let (sub_gi, sub) = instance_graph(pkg, node).ok_or("the instanced graph does not exist")?;
if sub_gi == gi || opts.graph_stack.contains(&sub_gi) || instances_reach(pkg, sub_gi, gi) {
return Err(format!("graph `{}` uses itself through a graph instance", sub.name));
}
let mut o = Options::new(opts.resource);
o.max_size = opts.max_size;
o.cancel = opts.cancel;
o.depth = opts.depth + 1;
o.graph_stack = opts.graph_stack.clone();
o.graph_stack.push(gi);
o.inputs = in_ports.iter().zip(inputs).filter_map(|(p, i)| Some((p.id.clone(), i.clone()?))).collect();
o.overrides = params.iter().filter(|(k, _)| sub.exposed.iter().any(|e| &e.id == *k)).map(|(k, v)| (k.clone(), v.clone())).collect();
let cooked = cook(pkg, gi, &o, cache);
let cooked = cook(pkg, sub_gi, &o, cache);
if cooked.cancelled {
return Err("cancelled".into());
}
@@ -489,30 +581,42 @@ mod tests {
#[test]
fn cooks_and_caches() {
let (mut p, noise, blur, out) = sample();
let mut cache = Cache::default();
let cache = Mutex::new(Cache::default());
let opts = Options::new(&no_res);
let a = cook(&p, 0, &opts, &mut cache);
let a = cook(&p, 0, &opts, &cache);
assert!(a.nodes.values().all(|r| r.error.is_none() && !r.cached));
assert_eq!(a.image(out, 0).map(|i| (i.w, i.h)), Some((64, 64)));
// Same graph: everything from the cache.
let b = cook(&p, 0, &opts, &mut cache);
let b = cook(&p, 0, &opts, &cache);
assert!(b.nodes.values().all(|r| r.cached));
// Editing the blur re-cooks the blur and the output, not the noise.
p.graphs[0].node_mut(blur).unwrap().params.insert("intensity".into(), Value::Float(5.0));
let c = cook(&p, 0, &opts, &mut cache);
let c = cook(&p, 0, &opts, &cache);
assert!(c.nodes[&noise].cached && !c.nodes[&blur].cached && !c.nodes[&out].cached);
assert_eq!(outputs(&p.graphs[0], &c).len(), 1);
}
#[test]
fn hostile_param_is_clamped_before_cooking() {
let (mut p, noise, _, _) = sample();
let blur = p.graphs[0].add_node("anisotropic_blur", [150.0, 100.0]);
p.graphs[0].connect(noise, "output", blur, "input").unwrap();
p.graphs[0].node_mut(blur).unwrap().params.insert("intensity".into(), Value::Float(1e30));
let cache = Mutex::new(Cache::default());
let c = cook(&p, 0, &Options::new(&no_res), &cache);
assert!(c.nodes[&blur].error.is_none(), "{:?}", c.nodes[&blur].error);
assert_eq!(c.image(blur, 0).map(|i| (i.w, i.h)), Some((64, 64)));
}
#[test]
fn preview_cap_and_unknown_nodes() {
let (mut p, _, _, out) = sample();
p.graphs[0].size = [10, 10];
let bad = p.graphs[0].add_node("no_such_node", [0.0, 0.0]);
let mut cache = Cache::default();
let cache = Mutex::new(Cache::default());
let mut opts = Options::new(&no_res);
opts.max_size = Some(128);
let c = cook(&p, 0, &opts, &mut cache);
let c = cook(&p, 0, &opts, &cache);
assert_eq!(c.image(out, 0).map(|i| i.w), Some(128));
assert!(c.nodes[&bad].error.is_some());
}
@@ -539,11 +643,113 @@ mod tests {
// A graph instancing itself is refused, not a stack overflow.
let selfi = g.add_node("graph_instance", [0.0, 200.0]);
g.node_mut(selfi).unwrap().params.insert("graph".into(), Value::Text("g".into()));
let mut cache = Cache::default();
let c = cook(&p, 0, &Options::new(&no_res), &mut cache);
let cache = Mutex::new(Cache::default());
let c = cook(&p, 0, &Options::new(&no_res), &cache);
let img = c.image(inst, 0).unwrap();
assert!((img.data[0] - (1.0 - 0.0722 * 0.25 - 0.2126 * 0.25 - 0.7152 * 0.25)).abs() < 1e-4, "{}", img.data[0]);
assert!(c.nodes[&selfi].error.is_some() || c.nodes[&selfi].outputs.len() == 1);
assert!(c.nodes[&selfi].error.as_deref().is_some_and(|e| e.contains("uses itself")), "{:?}", c.nodes[&selfi].error);
}
/// A graph `name` holding one instance of `target` wired to an output.
fn instancing(name: &str, target: &str) -> (Graph, NodeId) {
let mut g = Graph::new(name);
g.size = [4, 4];
let inst = g.add_node("graph_instance", [0.0, 0.0]);
g.node_mut(inst).unwrap().params.insert("graph".into(), Value::Text(target.into()));
let o = g.add_node("output", [100.0, 0.0]);
g.connect(inst, "output", o, "input").unwrap();
(g, inst)
}
#[test]
fn editing_a_nested_graph_recooks_the_top() {
let mut c = Graph::new("c");
c.size = [4, 4];
let u = c.add_node("uniform", [0.0, 0.0]);
c.node_mut(u).unwrap().params.insert("mode".into(), Value::Enum(1));
c.node_mut(u).unwrap().params.insert("color".into(), Value::Color([0.2, 0.2, 0.2, 1.0]));
let o = c.add_node("output", [100.0, 0.0]);
c.connect(u, "output", o, "input").unwrap();
let (b, _) = instancing("b", "c");
let (a, top) = instancing("a", "b");
let mut p = Package::new("p");
p.graphs = vec![a, b, c];
let cache = Mutex::new(Cache::default());
let opts = Options::new(&no_res);
let first = cook(&p, 0, &opts, &cache);
let out_a = p.graphs[0].nodes.iter().find(|n| n.def == "output").unwrap().id;
assert!((first.image(out_a, 0).unwrap().mean()[0] - 0.2).abs() < 0.01);
p.graphs[2].node_mut(u).unwrap().params.insert("color".into(), Value::Color([0.8, 0.8, 0.8, 1.0]));
let second = cook(&p, 0, &opts, &cache);
assert!(!second.nodes[&top].cached);
assert!((second.image(out_a, 0).unwrap().mean()[0] - 0.8).abs() < 0.01);
}
#[test]
fn deep_shared_instance_walks_stay_bounded() {
std::thread::Builder::new()
.stack_size(128 * 1024)
.spawn(|| {
let mut pkg = Package::new("deep");
for index in 0..2000 {
let mut graph = Graph::new(&format!("g{index}"));
// Repeated references must visit the next graph only once.
for _ in 0..4 {
let id = graph.add_node("graph_instance", [0.0; 2]);
graph.node_mut(id).unwrap().params.insert("graph".into(), Value::Text(format!("g{}", index + 1)));
}
pkg.graphs.push(graph);
}
assert!(instances_reach(&pkg, 0, 1999));
assert!(!instances_reach(&pkg, 0, 2000));
let before = graph_tree_hash(&pkg, 0);
pkg.graphs[1999].seed = 42;
assert_ne!(before, graph_tree_hash(&pkg, 0));
// A back edge must terminate both traversals too.
pkg.graphs[1999].nodes[0].params.insert("graph".into(), Value::Text("g0".into()));
assert!(instances_reach(&pkg, 1, 0));
assert!(!instances_reach(&pkg, 0, 2000));
assert_ne!(before, graph_tree_hash(&pkg, 0));
})
.unwrap()
.join()
.unwrap();
}
#[test]
fn mutual_instances_are_an_error() {
let (x, xi) = instancing("x", "y");
let (y, _) = instancing("y", "x");
let mut p = Package::new("p");
p.graphs = vec![x, y];
let cache = Mutex::new(Cache::default());
let c = cook(&p, 0, &Options::new(&no_res), &cache);
assert!(c.nodes[&xi].error.as_deref().is_some_and(|e| e.contains("uses itself")), "{:?}", c.nodes[&xi].error);
}
#[test]
fn same_size_resources_key_differently() {
use materialcraft_core::{Resource, ResourceBytes};
use std::sync::atomic::AtomicU8;
let mut g = Graph::new("g");
g.size = [4, 4];
let bm = g.add_node("bitmap", [0.0, 0.0]);
g.node_mut(bm).unwrap().params.insert("resource".into(), Value::Text("tex".into()));
let mut p = Package::new("p");
p.graphs.push(g);
p.resources.push(Resource::new("tex", "tex.bin", ResourceBytes::new(vec![1; 100])));
// Stands in for decoding: the first byte picks the shade.
let shade = AtomicU8::new(1);
let res = |_: &str| Some(Image::filled(4, 4, Kind::Gray, [f32::from(shade.load(Ordering::Relaxed)) / 10.0; 4]));
let cache = Mutex::new(Cache::default());
let opts = Options::new(&res);
let first = cook(&p, 0, &opts, &cache);
let mean = first.image(bm, 0).unwrap().mean()[0];
p.resources[0].bytes = ResourceBytes::new(vec![2; 100]);
shade.store(2, Ordering::Relaxed);
let second = cook(&p, 0, &opts, &cache);
assert!(!second.nodes[&bm].cached);
assert!((second.image(bm, 0).unwrap().mean()[0] - mean).abs() > 0.05);
}
#[test]
@@ -558,14 +764,34 @@ mod tests {
g.input_images.insert("curvature".into(), "curv".into());
p.graphs.push(g);
let res = |n: &str| (n == "curv").then(|| Image::filled(4, 4, Kind::Color, [0.8, 0.8, 0.8, 1.0]));
let mut cache = Cache::default();
let c = cook(&p, 0, &Options::new(&res), &mut cache);
let cache = Mutex::new(Cache::default());
let c = cook(&p, 0, &Options::new(&res), &cache);
let img = c.image(o, 0).unwrap();
assert!(img.is_gray() && (img.data[0] - 0.8).abs() < 1e-4, "bound image, as gray");
// The caller's image wins over the bound one.
let mut opts = Options::new(&res);
opts.inputs.insert("curvature".into(), Image::filled(4, 4, Kind::Gray, [0.1; 4]));
let c = cook(&p, 0, &opts, &mut cache);
let c = cook(&p, 0, &opts, &cache);
assert!((c.image(o, 0).unwrap().data[0] - 0.1).abs() < 1e-4);
}
#[test]
fn input_change_recooks_only_readers() {
use materialcraft_core::function::{FnGraph, FnNode};
let (mut p, noise, blur, out) = sample();
let reader = p.graphs[0].add_node("pixel_processor", [0.0, 100.0]);
let get_a = FnNode { id: 1, op: "get_var".into(), inputs: vec![], value: Some(Value::Text("a".into())), pos: [0.0; 2] };
p.graphs[0].node_mut(reader).unwrap().params.insert("function".into(), Value::Function(Box::new(FnGraph { nodes: vec![get_a], output: Some(1) })));
let cache = &Mutex::new(Cache::default());
let mut opts = Options::new(&no_res);
opts.overrides.insert("a".into(), Value::Float(0.25));
let first = cook(&p, 0, &opts, cache);
assert!(first.nodes.values().all(|r| r.error.is_none() && !r.cached));
opts.overrides.insert("a".into(), Value::Float(0.75));
let second = cook(&p, 0, &opts, cache);
for id in [noise, blur, out] {
assert!(second.nodes[&id].cached, "node {} does not read `a`", id.0);
}
assert!(!second.nodes[&reader].cached, "the reader must re-cook");
}
}
+134 -17
View File
@@ -12,10 +12,11 @@ pub mod material;
pub mod mesh;
pub mod sbs;
use std::collections::HashMap;
use std::io::{Cursor, Read, Write};
use std::sync::Arc;
use materialcraft_core::{OutputFormat, Package};
use materialcraft_core::{OutputFormat, Package, ResourceBytes};
use materialcraft_image::{Image, Kind, MAX_SIDE, linear_to_srgb, srgb_to_linear};
#[derive(Debug, thiserror::Error)]
@@ -33,6 +34,10 @@ pub type Result<T> = std::result::Result<T, FormatError>;
/// Largest `package.json` and resource accepted when reading (allocation caps).
const MAX_JSON: u64 = 64 << 20;
const MAX_RESOURCE: u64 = 256 << 20;
/// Most resource records a package may list.
const MAX_RESOURCES: usize = 4096;
/// Most decompressed bytes a package may hold across `package.json` and all its resources.
const MAX_PACKAGE_BYTES: u64 = 2 << 30;
/// Export file types: (extension, label).
pub const EXPORT_FORMATS: &[(&str, &str)] =
@@ -55,7 +60,7 @@ pub fn save_package(pkg: &Package) -> Result<Vec<u8>> {
// Images are already compressed.
let stored = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
z.start_file(format!("resources/{}", safe_file_name(&r.file)), stored).map_err(io)?;
z.write_all(&r.bytes).map_err(|e| FormatError::Io(e.to_string()))?;
z.write_all(r.bytes.as_slice()).map_err(|e| FormatError::Io(e.to_string()))?;
}
z.finish().map_err(io)?;
}
@@ -64,6 +69,11 @@ pub fn save_package(pkg: &Package) -> Result<Vec<u8>> {
/// Read a package from `.mcraft` bytes.
pub fn load_package(bytes: &[u8]) -> Result<Package> {
load_package_within(bytes, MAX_PACKAGE_BYTES)
}
/// [`load_package`] with an explicit cap on the total decompressed bytes.
fn load_package_within(bytes: &[u8], max_total: u64) -> Result<Package> {
let mut z = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|e| FormatError::BadPackage(e.to_string()))?;
let mut json = Vec::new();
z.by_name("package.json")
@@ -72,17 +82,37 @@ pub fn load_package(bytes: &[u8]) -> Result<Package> {
.read_to_end(&mut json)
.map_err(|e| FormatError::Io(e.to_string()))?;
let mut pkg: Package = serde_json::from_slice(&json).map_err(|e| FormatError::BadPackage(e.to_string()))?;
if pkg.resources.len() > MAX_RESOURCES {
return Err(FormatError::BadPackage(format!("{} resources (limit {MAX_RESOURCES})", pkg.resources.len())));
}
let mut total = json.len() as u64;
let mut read: HashMap<String, ResourceBytes> = HashMap::new();
for r in &mut pkg.resources {
let name = format!("resources/{}", safe_file_name(&r.file));
if let Some(shared) = read.get(&name) {
r.bytes = shared.clone();
continue;
}
let mut data = Vec::new();
if let Ok(mut f) = z.by_name(&name) {
f.by_ref().take(MAX_RESOURCE).read_to_end(&mut data).map_err(|e| FormatError::Io(e.to_string()))?;
}
r.bytes = Arc::new(data);
total = total.saturating_add(data.len() as u64);
if total > max_total {
return Err(FormatError::BadPackage(format!("package resources exceed {max_total} bytes")));
}
let data = ResourceBytes::new(data);
read.insert(name, data.clone());
r.bytes = data;
}
Ok(pkg)
}
/// Last-resort guard around third-party parsers: a panic inside them becomes an error.
pub(crate) fn guard<T>(f: impl FnOnce() -> Result<T>, err: impl FnOnce() -> FormatError) -> Result<T> {
std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).unwrap_or_else(|_| Err(err()))
}
/// A file name with no path parts (resources live flat in `resources/`).
pub fn safe_file_name(name: &str) -> String {
let base = name.rsplit(['/', '\\']).next().unwrap_or(name);
@@ -94,10 +124,25 @@ pub fn safe_file_name(name: &str) -> String {
/// Decode image file bytes into a linear float image (8-bit color is sRGB-decoded; grayscale
/// files stay grayscale).
pub fn decode(bytes: &[u8]) -> Result<Image> {
// TGA has no signature: try it when the format cannot be guessed.
let img = image::load_from_memory(bytes)
.or_else(|e| image::load_from_memory_with_format(bytes, image::ImageFormat::Tga).map_err(|_| e))
.map_err(|e| FormatError::Image(e.to_string()))?;
let mut reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().map_err(|e| FormatError::Image(e.to_string()))?;
if reader.format().is_none() {
// TGA has no signature: try it when the format cannot be guessed.
reader.set_format(image::ImageFormat::Tga);
}
let mut limits = image::Limits::default();
limits.max_image_width = Some(MAX_SIDE);
limits.max_image_height = Some(MAX_SIDE);
limits.max_alloc = Some(1 << 30);
reader.limits(limits);
let img = guard(
|| {
reader.decode().map_err(|e| match e {
image::ImageError::Limits(_) => FormatError::Image(format!("image is larger than {MAX_SIDE} pixels")),
e => FormatError::Image(e.to_string()),
})
},
|| FormatError::Image("the decoder failed on this file".into()),
)?;
let (w, h) = (img.width(), img.height());
if w == 0 || h == 0 || w > MAX_SIDE || h > MAX_SIDE {
return Err(FormatError::Image(format!("{w}x{h} is outside 1..={MAX_SIDE} pixels")));
@@ -109,14 +154,14 @@ pub fn decode(bytes: &[u8]) -> Result<Image> {
let data: Vec<f32> = l.pixels().map(|p| p.0[0] as f32 / 65535.0).collect();
return Ok(Image { w, h, kind: Kind::Gray, data: Arc::new(data) });
}
let rgba = img.into_rgba32f();
let data: Vec<f32> = rgba
.pixels()
.flat_map(|p| {
let [r, g, b, a] = p.0;
if float { [r, g, b, a] } else { [srgb_to_linear(r), srgb_to_linear(g), srgb_to_linear(b), a] }
})
.collect();
let mut data = img.into_rgba32f().into_raw();
if !float {
for px in data.chunks_exact_mut(4) {
for c in px.iter_mut().take(3) {
*c = srgb_to_linear(*c);
}
}
}
Ok(Image { w, h, kind: Kind::Color, data: Arc::new(data) })
}
@@ -240,12 +285,12 @@ mod tests {
g.connect(a, "output", o, "input").unwrap();
p.graphs.push(g);
let png = encode(&Image::filled(4, 4, Kind::Color, [1.0, 0.5, 0.0, 1.0]), "png", Depth::U8, true).unwrap();
p.resources.push(Resource { name: "tex".into(), file: "../../evil/tex.png".into(), bytes: Arc::new(png) });
p.resources.push(Resource::new("tex", "../../evil/tex.png", ResourceBytes::new(png)));
let bytes = save_package(&p).unwrap();
let q = load_package(&bytes).unwrap();
assert_eq!(q.graphs, p.graphs);
assert_eq!(q.resources[0].bytes, p.resources[0].bytes);
let img = decode(&q.resources[0].bytes).unwrap();
let img = decode(q.resources[0].bytes.as_slice()).unwrap();
assert!((img.get(0, 0, false)[1] - 0.5).abs() < 0.01);
assert!(load_package(b"not a zip").is_err());
}
@@ -273,4 +318,76 @@ mod tests {
assert_eq!(safe_file_name("../../etc/passwd"), "passwd");
assert_eq!(safe_file_name(".."), "resource");
}
fn zip_with(json: &serde_json::Value, entries: &[(&str, usize)]) -> Vec<u8> {
let mut buf = Cursor::new(Vec::new());
{
let mut z = zip::ZipWriter::new(&mut buf);
let opts = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
z.start_file("package.json", opts).unwrap();
z.write_all(json.to_string().as_bytes()).unwrap();
for (name, len) in entries {
z.start_file(format!("resources/{name}"), opts).unwrap();
z.write_all(&vec![0u8; *len]).unwrap();
}
z.finish().unwrap();
}
buf.into_inner()
}
fn package_json(files: &[&str]) -> serde_json::Value {
let base = serde_json::to_value(Package::new("T")).unwrap();
let mut v = base;
v["resources"] = files.iter().map(|f| serde_json::json!({ "name": "r", "file": f })).collect();
v
}
#[test]
fn many_records_share_one_entry() {
let files = vec!["big.bin"; 1000];
let bytes = zip_with(&package_json(&files), &[("big.bin", 1 << 20)]);
let pkg = load_package(&bytes).unwrap();
assert_eq!(pkg.resources.len(), 1000);
assert_eq!(pkg.resources[0].bytes.len(), 1 << 20);
assert!(pkg.resources[0].bytes.ptr_eq(&pkg.resources[999].bytes));
}
#[test]
fn too_many_resources_is_an_error() {
let files = vec!["a.bin"; MAX_RESOURCES + 1];
let bytes = zip_with(&package_json(&files), &[("a.bin", 4)]);
assert!(load_package(&bytes).is_err());
}
#[test]
fn total_budget_is_enforced() {
let bytes = zip_with(&package_json(&["a.bin", "b.bin"]), &[("a.bin", 1 << 20), ("b.bin", 1 << 20)]);
assert!(load_package_within(&bytes, 3 << 19).is_err());
assert!(load_package_within(&bytes, 3 << 20).is_ok());
}
#[test]
fn oversized_images_are_refused_before_decoding() {
let mut png = Cursor::new(Vec::new());
image::GrayImage::new(8193, 1).write_to(&mut png, image::ImageFormat::Png).unwrap();
let err = decode(png.get_ref()).unwrap_err().to_string();
assert!(err.contains("8192"), "{err}");
}
#[test]
fn tga_still_decodes() {
let mut tga = Cursor::new(Vec::new());
image::RgbaImage::new(2, 2).write_to(&mut tga, image::ImageFormat::Tga).unwrap();
let img = decode(tga.get_ref()).unwrap();
assert_eq!((img.w, img.h, img.kind), (2, 2, Kind::Color));
}
#[test]
fn decode_matches_previous_values() {
let mut png = Cursor::new(Vec::new());
image::RgbImage::from_pixel(2, 2, image::Rgb([128, 128, 128])).write_to(&mut png, image::ImageFormat::Png).unwrap();
let img = decode(png.get_ref()).unwrap();
let want = srgb_to_linear(128.0 / 255.0);
assert!((img.get(1, 1, false)[0] - want).abs() < 1e-4);
}
}
+5 -2
View File
@@ -47,7 +47,10 @@ pub fn load_mesh(name: &str, bytes: &[u8]) -> Result<Mesh> {
fn obj(bytes: &[u8]) -> Result<Mesh> {
let mut reader = std::io::BufReader::new(bytes);
let opts = tobj::LoadOptions { triangulate: true, single_index: true, ..Default::default() };
let (models, _) = tobj::load_obj_buf(&mut reader, &opts, |_| Ok((Vec::new(), Default::default()))).map_err(|e| bad(format!("OBJ: {e}")))?;
let (models, _) = crate::guard(
|| tobj::load_obj_buf(&mut reader, &opts, |_| Ok((Vec::new(), Default::default()))).map_err(|e| bad(format!("OBJ: {e}"))),
|| bad("the OBJ parser failed on this file"),
)?;
let mut positions = Vec::new();
let mut normals = Vec::new();
let mut uvs = Vec::new();
@@ -75,7 +78,7 @@ fn obj(bytes: &[u8]) -> Result<Mesh> {
}
fn gltf(bytes: &[u8]) -> Result<Mesh> {
let (doc, buffers, _) = gltf::import_slice(bytes).map_err(|e| bad(format!("glTF: {e}")))?;
let (doc, buffers, _) = crate::guard(|| gltf::import_slice(bytes).map_err(|e| bad(format!("glTF: {e}"))), || bad("the glTF parser failed on this file"))?;
let mut positions = Vec::new();
let mut normals = Vec::new();
let mut uvs = Vec::new();
+21 -9
View File
@@ -5,12 +5,11 @@
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque};
use std::fmt::Write as _;
use std::io::{Read, Write};
use std::sync::Arc;
use base64::Engine as _;
use materialcraft_core::{
BaseParams, Comment, Connection, ExposedParam, Frame, Graph, MAX_SIZE_LOG2, MIN_SIZE_LOG2, MISSING_NODE, Node, NodeId, OutputFormat, Package, Resource,
SizeMode, Value, linear_to_srgb, missing_ports, srgb_to_linear,
ResourceBytes, SizeMode, Value, linear_to_srgb, missing_ports, srgb_to_linear,
};
use materialcraft_nodes::{PortKind, find};
use roxmltree::Node as XmlNode;
@@ -776,7 +775,7 @@ impl<'text> Reader<'text, '_> {
match bytes {
Some(data) => {
let ext = if kind == "svg" { "svg".to_string() } else { format };
pkg.resources.push(Resource { name: name.clone(), file: crate::safe_file_name(&format!("{name}.{ext}")), bytes: Arc::new(data) });
pkg.resources.push(Resource::new(name.clone(), crate::safe_file_name(&format!("{name}.{ext}")), ResourceBytes::new(data)));
}
None => {
let why = if why_missing.is_empty() { "it has no data".to_string() } else { why_missing };
@@ -1074,8 +1073,13 @@ impl<'text> Reader<'text, '_> {
if let Some(node) = node {
for param in instance_params() {
let param_name = child_value(param, "name").unwrap_or("");
match def.param(param_name) {
Some(param_def) => self.set_param(node, param_name, &param_def.default, param_def.options.len(), param, &graph_name),
let id = match (def.id, param_name) {
("histogram_scan", "Position") => "position",
("histogram_scan", "Contrast") => "contrast",
_ => param_name,
};
match def.param(id) {
Some(param_def) => self.set_param(node, id, &param_def.default, param_def.options.len(), param, &graph_name),
None => self.warnings.add(format!("`{}`: parameter `{param_name}` has no MaterialCraft equivalent and was ignored", def.id)),
}
}
@@ -1086,7 +1090,15 @@ impl<'text> Reader<'text, '_> {
let port_for = |identifier: &str| if def.output_index(identifier).is_some() { identifier.to_string() } else { first_output.clone() };
let unbridged = output_uids.iter().filter(|(uid, _)| !bridgings.iter().any(|(b, _)| b == uid)).map(|(uid, _)| (uid.clone(), first_output.clone()));
let outputs = bridgings.iter().map(|(uid, identifier)| (uid.clone(), port_for(identifier))).chain(unbridged).collect();
let inputs = def.inputs.iter().map(|p| (p.id.to_string(), p.id.to_string())).collect();
let mut inputs: HashMap<_, _> = def.inputs.iter().map(|p| (p.id.to_string(), p.id.to_string())).collect();
let input_aliases: &[(&str, &str)] = match def.id {
"histogram_scan" => &[("Input_1", "input")],
"auto_levels" => &[("Input", "input")],
"flood_fill" => &[("mask", "input")],
"height_blend" => &[("height_top", "top"), ("height_bottom", "bottom")],
_ => &[],
};
inputs.extend(input_aliases.iter().map(|&(alias, port)| (alias.to_string(), port.to_string())));
ReadNode { id, index, inputs, outputs, open_inputs: false }
}
@@ -1369,7 +1381,7 @@ pub fn write_sbs(pkg: &Package) -> Result<Vec<u8>> {
if svg { "svg" } else { "bitmap" },
xml_escape(ext),
resource.bytes.len(),
encode_embedded(&resource.bytes)?
encode_embedded(resource.bytes.as_slice())?
);
}
content.push_str("</content></group>");
@@ -1853,7 +1865,7 @@ mod tests {
let orange = materialcraft_image::Image::filled(4, 4, materialcraft_image::Kind::Color, [1.0, 0.5, 0.0, 1.0]);
let png = crate::encode(&orange, "png", crate::Depth::U8, true).unwrap();
pkg.resources.push(Resource { name: "tex".into(), file: "tex.png".into(), bytes: Arc::new(png) });
pkg.resources.push(Resource::new("tex", "tex.png", ResourceBytes::new(png)));
pkg
}
@@ -2076,7 +2088,7 @@ mod tests {
assert!(read.warnings.iter().any(|w| w.contains("missing node `3D_perlin_noise`")), "{:?}", &read.warnings[..5]);
assert!(read.pkg.resources.iter().any(|r| r.name == "Untitled_Bitmap" && !r.bytes.is_empty()));
let svg = read.pkg.resources.iter().find(|r| r.name == "Untitled_Vector_Graphics").unwrap();
assert!(String::from_utf8_lossy(&svg.bytes).contains("<svg"));
assert!(String::from_utf8_lossy(svg.bytes.as_slice()).contains("<svg"));
assert_eq!(graph.frames.len(), 26);
assert_eq!(graph.size, [11, 11]);
+154
View File
@@ -0,0 +1,154 @@
//! The reported library-node aliases must preserve imported settings and connections.
use materialcraft_core::{Graph, Package, Value};
use materialcraft_formats::sbs::{read_sbs, write_sbs};
fn plain_xml(bytes: &[u8]) -> String {
let text = String::from_utf8(bytes.to_vec()).unwrap();
// Exercise XML import rather than the writer's embedded exact native-package copy.
format!("{}</package>", text.split("<!--").next().unwrap())
}
const DEFS: [&str; 4] = ["histogram_scan", "auto_levels", "flood_fill", "height_blend"];
fn fixture(def: &str) -> String {
let mut pkg = Package::new("Import check");
let mut graph = Graph::new("G");
let source = graph.add_node("uniform", [0.0, 0.0]);
let second = (def == "height_blend").then(|| graph.add_node("uniform", [0.0, 150.0]));
let filter = graph.add_node(def, [150.0, 0.0]);
graph.connect(source, "output", filter, if def == "height_blend" { "top" } else { "input" }).unwrap();
if let Some(second) = second {
graph.connect(second, "output", filter, "bottom").unwrap();
}
if def == "histogram_scan" {
let n = graph.node_mut(filter).unwrap();
n.params.insert("position".into(), Value::Float(0.25));
n.params.insert("contrast".into(), Value::Float(0.75));
}
pkg.graphs.push(graph);
plain_xml(&write_sbs(&pkg).unwrap())
}
fn aliased_fixture(def: &str) -> String {
let xml = fixture(def);
match def {
"histogram_scan" => xml
.replace("<name v=\"position\"/>", "<name v=\"Position\"/>")
.replace("<name v=\"contrast\"/>", "<name v=\"Contrast\"/>")
.replace("<identifier v=\"input\"/>", "<identifier v=\"Input_1\"/>"),
"auto_levels" => xml.replace("<identifier v=\"input\"/>", "<identifier v=\"Input\"/>"),
"flood_fill" => xml.replace("<identifier v=\"input\"/>", "<identifier v=\"mask\"/>"),
"height_blend" => {
xml.replace("<identifier v=\"top\"/>", "<identifier v=\"height_top\"/>").replace("<identifier v=\"bottom\"/>", "<identifier v=\"height_bottom\"/>")
}
_ => panic!("unknown fixture node {def}"),
}
}
fn assert_wires(pkg: &Package, def: &str) {
let g = &pkg.graphs[0];
let sources: Vec<_> = g.nodes.iter().filter(|n| n.def == "uniform").collect();
let filter = g.nodes.iter().find(|n| n.def == def).unwrap();
let ports: &[&str] = if def == "height_blend" { &["top", "bottom"] } else { &["input"] };
assert_eq!(sources.len(), ports.len());
assert_eq!(g.connections.len(), ports.len());
for (source, port) in sources.iter().zip(ports) {
let wire = g.input_of(filter.id, port).unwrap();
assert_eq!((wire.from, wire.from_port.as_str(), wire.to, wire.to_port.as_str()), (source.id, "output", filter.id, *port));
}
}
fn assert_scan_values(pkg: &Package) {
let n = pkg.graphs[0].nodes.iter().find(|n| n.def == "histogram_scan").unwrap();
assert_eq!(n.params.get("position"), Some(&Value::Float(0.25)));
assert_eq!(n.params.get("contrast"), Some(&Value::Float(0.75)));
assert!(!n.params.contains_key("Position") && !n.params.contains_key("Contrast"));
}
#[test]
fn canonical_names_keep_parameters_and_wires() {
for def in DEFS {
let read = read_sbs(fixture(def).as_bytes(), "check.sbs", &|_| None).unwrap();
assert!(!read.exact);
assert!(read.warnings.is_empty(), "{:?}", read.warnings);
assert_wires(&read.pkg, def);
if def == "histogram_scan" {
assert_scan_values(&read.pkg);
}
}
}
#[test]
fn histogram_scan_keeps_reported_parameter_spellings() {
let xml = fixture("histogram_scan").replace("<name v=\"position\"/>", "<name v=\"Position\"/>").replace("<name v=\"contrast\"/>", "<name v=\"Contrast\"/>");
let read = read_sbs(xml.as_bytes(), "check.sbs", &|_| None).unwrap();
assert!(read.warnings.is_empty(), "{:?}", read.warnings);
assert_scan_values(&read.pkg);
}
#[test]
fn histogram_scan_keeps_reported_input_connection() {
let xml = fixture("histogram_scan").replace("<identifier v=\"input\"/>", "<identifier v=\"Input_1\"/>");
let read = read_sbs(xml.as_bytes(), "check.sbs", &|_| None).unwrap();
assert!(read.warnings.is_empty(), "{:?}", read.warnings);
assert_wires(&read.pkg, "histogram_scan");
}
#[test]
fn auto_levels_keeps_reported_input_connection() {
let xml = fixture("auto_levels").replace("<identifier v=\"input\"/>", "<identifier v=\"Input\"/>");
let read = read_sbs(xml.as_bytes(), "check.sbs", &|_| None).unwrap();
assert!(read.warnings.is_empty(), "{:?}", read.warnings);
assert_wires(&read.pkg, "auto_levels");
}
#[test]
fn flood_fill_keeps_reported_mask_connection() {
let read = read_sbs(aliased_fixture("flood_fill").as_bytes(), "check.sbs", &|_| None).unwrap();
assert!(read.warnings.is_empty(), "{:?}", read.warnings);
assert_wires(&read.pkg, "flood_fill");
}
#[test]
fn height_blend_keeps_reported_connections_without_swapping_sources() {
let read = read_sbs(aliased_fixture("height_blend").as_bytes(), "check.sbs", &|_| None).unwrap();
assert!(read.warnings.is_empty(), "{:?}", read.warnings);
assert_wires(&read.pkg, "height_blend");
}
#[test]
fn aliased_imports_survive_a_structural_save_and_reload() {
for def in DEFS {
let read = read_sbs(aliased_fixture(def).as_bytes(), "check.sbs", &|_| None).unwrap();
assert!(read.warnings.is_empty(), "{:?}", read.warnings);
let xml = plain_xml(&write_sbs(&read.pkg).unwrap());
let back = read_sbs(xml.as_bytes(), "saved.sbs", &|_| None).unwrap();
assert!(!back.exact);
assert!(back.warnings.is_empty(), "{:?}", back.warnings);
assert_wires(&back.pkg, def);
if def == "histogram_scan" {
assert_scan_values(&back.pkg);
}
}
}
#[test]
fn unknown_parameters_still_warn() {
let xml = fixture("histogram_scan").replace("<name v=\"contrast\"/>", "<name v=\"UnexpectedContrast\"/>");
let read = read_sbs(xml.as_bytes(), "check.sbs", &|_| None).unwrap();
assert_eq!(read.warnings.len(), 1);
assert!(read.warnings[0].contains("UnexpectedContrast"));
let n = read.pkg.graphs[0].nodes.iter().find(|n| n.def == "histogram_scan").unwrap();
assert_eq!(n.params.get("position"), Some(&Value::Float(0.25)));
assert!(!n.params.contains_key("contrast") && !n.params.contains_key("UnexpectedContrast"));
}
#[test]
fn unknown_inputs_still_warn_and_drop_the_wire() {
for def in DEFS {
let original = if def == "height_blend" { "top" } else { "input" };
let xml = fixture(def).replace(&format!("<identifier v=\"{original}\"/>"), "<identifier v=\"UnexpectedInput\"/>");
let read = read_sbs(xml.as_bytes(), "check.sbs", &|_| None).unwrap();
assert_eq!(read.warnings.len(), 1);
assert!(read.warnings[0].contains("UnexpectedInput"));
let g = &read.pkg.graphs[0];
if def == "height_blend" {
assert_eq!(g.connections.len(), 1);
assert_eq!(g.connections[0].to_port, "bottom");
assert_eq!(g.connections[0].from, g.nodes[1].id);
assert_eq!(g.nodes.len(), 3);
} else {
assert!(g.connections.is_empty());
assert_eq!(g.nodes.len(), 2);
}
}
}
+54
View File
@@ -352,6 +352,60 @@ pub fn categories() -> Vec<(&'static str, Vec<&'static str>)> {
out
}
/// How many slider spans the hard limit extends past each end of a parameter's range.
const HARD_SPAN: f32 = 16.0;
/// Clamp `v` to `[lo, hi]`; a non-finite `v` becomes `fallback`.
fn clamp_finite(v: f32, lo: f32, hi: f32, fallback: f32) -> f32 {
if v.is_finite() { v.clamp(lo, hi) } else { fallback }
}
/// Clamp numeric parameters to hard limits: the declared slider range widened by
/// `HARD_SPAN` spans on each side (the editor lets values past the slider through, so the
/// slider range itself is not a limit). Non-finite values become the default. Keeps cooks
/// bounded whatever a file, binding, function or command supplies.
pub fn clamp_params(def: &NodeDef, params: &mut BTreeMap<String, Value>) {
for p in &def.params {
let Some(v) = params.get_mut(p.id) else { continue };
if let Value::Enum(i) = v {
if !p.options.is_empty() {
*i = (*i).min(u32::try_from(p.options.len() - 1).unwrap_or(u32::MAX));
}
continue;
}
if let Value::Color(c) = v {
for x in c {
*x = clamp_finite(*x, -HARD_SPAN, 1.0 + HARD_SPAN, 0.0);
}
continue;
}
if p.min >= p.max {
continue;
}
let span = p.max - p.min;
let (lo, hi) = (p.min - HARD_SPAN * span, p.max + HARD_SPAN * span);
// The default's component `i`, or 0 when the default is a different variant.
let fallback = |i: usize| match &p.default {
Value::Float(d) => [*d].get(i).copied(),
Value::Float2(d) => d.get(i).copied(),
Value::Float3(d) => d.get(i).copied(),
Value::Float4(d) => d.get(i).copied(),
_ => None,
};
let clamp_at = |x: &mut f32, i: usize| *x = clamp_finite(*x, lo, hi, fallback(i).unwrap_or(0.0));
let clamp_int = |x: &mut i32| *x = (*x as f32).clamp(lo, hi).round() as i32;
match v {
Value::Float(x) => clamp_at(x, 0),
Value::Float2(a) => a.iter_mut().enumerate().for_each(|(i, x)| clamp_at(x, i)),
Value::Float3(a) => a.iter_mut().enumerate().for_each(|(i, x)| clamp_at(x, i)),
Value::Float4(a) => a.iter_mut().enumerate().for_each(|(i, x)| clamp_at(x, i)),
Value::Int(x) => clamp_int(x),
Value::Int2(a) => a.iter_mut().for_each(clamp_int),
_ => {}
}
}
}
/// Parameter values for a node: catalog defaults overlaid with `overrides`.
pub fn resolve_params(def: &NodeDef, overrides: &BTreeMap<String, Value>) -> BTreeMap<String, Value> {
let mut m: BTreeMap<String, Value> = def.params.iter().map(|p| (p.id.to_string(), p.default.clone())).collect();
+14 -4
View File
@@ -361,7 +361,8 @@ fn contrast_luminosity(ctx: &Ctx) -> CookResult {
}
fn exposure(ctx: &Ctx) -> CookResult {
let k = 2f32.powf(ctx.f("stops"));
// Past +-64 stops the result is all black/white anyway; this keeps 2^stops finite.
let k = 2f32.powf(ctx.f("stops").clamp(-64.0, 64.0));
per_value(ctx, |v| v * k)
}
@@ -504,7 +505,15 @@ fn anisotropic_blur(ctx: &Ctx) -> CookResult {
Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| transform_sample(&b, u, v, [0.0, 0.0], [1.0, 1.0], -a / TAU, false, true).unwrap_or([0.0; 4]))])
}
/// Most extra horizontal passes `blur_xy` runs: a cost bound, whatever sigma it is given.
const MAX_BLUR_PASSES: i64 = 64;
/// Widest horizontal kernel half-width `blur_xy` builds: a cost bound on the kernel allocation.
const MAX_KERNEL_RADIUS: i64 = 512;
fn blur_xy(img: &Image, sx: f32, sy: f32, tile: bool) -> Image {
if !sx.is_finite() || !sy.is_finite() {
return img.clone();
}
// Separable: a horizontal-only Gaussian is a 2D one on an image stretched vertically, so
// blur fully with the smaller sigma and add the extra along x by repeated small passes.
let base = ops::gaussian(img, sy, tile);
@@ -512,12 +521,12 @@ fn blur_xy(img: &Image, sx: f32, sy: f32, tile: bool) -> Image {
if extra < 0.1 {
return base;
}
let n = (extra / 2.0).ceil().max(1.0) as i64;
let n = ((extra / 2.0).ceil().max(1.0) as i64).min(MAX_BLUR_PASSES);
let step = extra / (n as f32).sqrt();
let mut out = base;
for _ in 0..n {
let src = out.clone();
let r = (step * 2.0).ceil() as i64;
let r = ((step * 2.0).ceil() as i64).clamp(1, MAX_KERNEL_RADIUS);
let k: Vec<f32> = (-r..=r).map(|i| (-(i * i) as f32 / (2.0 * step * step)).exp()).collect();
let sum: f32 = k.iter().sum();
out = Image::generate(src.w, src.h, src.kind, |x, y| {
@@ -687,7 +696,8 @@ fn edge_detect(ctx: &Ctx) -> CookResult {
.map(|(a, b)| {
let d = a.sqrt().max(b.sqrt());
let t = (1.0 - d / w).max(0.0);
t.powf(1.0 - round * 0.8)
// A non-positive exponent on t = 0 gives inf; in range (round <= 1) it is >= 0.2.
t.powf((1.0 - round * 0.8).max(0.01))
})
.collect();
Ok(vec![ops::gray_from(ctx.w, ctx.h, v)])
+2 -1
View File
@@ -222,7 +222,8 @@ fn smoothstep_node(ctx: &Ctx) -> CookResult {
}
fn s_curve(ctx: &Ctx) -> CookResult {
let (k, p) = (1.0 + ctx.f("amount") * 4.0, ctx.f("pivot").clamp(0.01, 0.99));
// A negative k on a zero base gives inf; clamp it (k = 0 gives the finite 1).
let (k, p) = ((1.0 + ctx.f("amount") * 4.0).max(0.0), ctx.f("pivot").clamp(0.01, 0.99));
per_channel(ctx, |v, _| {
let v = v.clamp(0.0, 1.0);
if v < p { p * (v / p).powf(k) } else { 1.0 - (1.0 - p) * ((1.0 - v) / (1.0 - p)).powf(k) }
+2 -1
View File
@@ -357,7 +357,8 @@ fn plasma(ctx: &Ctx) -> CookResult {
fn turbulence(ctx: &Ctx) -> CookResult {
let (sc, r, s) = (scale(ctx), ctx.f("roughness"), ctx.seed);
Ok(vec![ctx.gen_gray(|u, v| 1.0 - ridged(u, v, sc, 6, r, s).sqrt())])
// A negative roughness makes `ridged` negative; clamp so the sqrt can't be NaN.
Ok(vec![ctx.gen_gray(|u, v| 1.0 - ridged(u, v, sc, 6, r, s).max(0.0).sqrt())])
}
fn creased(ctx: &Ctx) -> CookResult {
+46 -1
View File
@@ -28,12 +28,13 @@ pub mod svg;
pub mod text;
pub mod weathering;
pub use catalog::{CookResult, Ctx, NodeDef, ParamDef, PortDef, PortKind, catalog, categories, find, resolve_params};
pub use catalog::{CookResult, Ctx, NodeDef, ParamDef, PortDef, PortKind, catalog, categories, clamp_params, find, resolve_params};
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use materialcraft_core::Value;
use materialcraft_image::{Image, Kind};
use super::*;
@@ -72,6 +73,50 @@ mod tests {
assert!(catalog().len() >= 200, "{} nodes", catalog().len());
}
/// Every node cooks with each numeric parameter at a hostile value (huge, negative huge, NaN):
/// the hard limits keep the cook bounded, finite and the right size.
#[test]
fn every_node_survives_hostile_params() {
use std::time::{Duration, Instant};
let mut slow: Vec<(String, Duration)> = Vec::new();
let total = Instant::now();
for def in catalog() {
if def.id == "graph_instance" {
continue;
}
for p in &def.params {
for h in [1e30_f32, -1e30, f32::NAN] {
let v = match p.default {
Value::Float(_) => Value::Float(h),
Value::Int(_) => Value::Int(h as i32),
Value::Float2(_) => Value::Float2([h, h]),
Value::Enum(_) => Value::Enum(h as u32),
_ => continue,
};
let mut params = resolve_params(def, &BTreeMap::from([(p.id.to_string(), v)]));
clamp_params(def, &mut params);
let inputs = vec![None; def.inputs.len()];
let no_res = |_: &str| None;
let vars = BTreeMap::new();
let ctx = Ctx { w: 16, h: 16, seed: 7, tile: true, inputs: &inputs, params: &params, resource: &no_res, vars: &vars };
let t = Instant::now();
let out = (def.cook)(&ctx).unwrap_or_else(|e| panic!("{}.{}={h}: {e}", def.id, p.id));
let dt = t.elapsed();
assert!(dt < Duration::from_secs(2), "{}.{}={h} took {dt:?}", def.id, p.id);
if dt > Duration::from_millis(250) {
slow.push((format!("{}.{}={h}", def.id, p.id), dt));
}
for img in &out {
assert_eq!((img.w, img.h), (16, 16), "{}.{}={h}", def.id, p.id);
assert!(img.data.iter().all(|x| x.is_finite()), "{}.{}={h} produced a non-finite value", def.id, p.id);
}
}
}
}
eprintln!("hostile params: total {:?}; cooks over 250 ms: {slow:?}", total.elapsed());
}
#[test]
fn noises_tile() {
for id in [
+1 -1
View File
@@ -9,4 +9,4 @@
pub mod ibl;
pub mod preview;
pub use preview::{Lighting, Maps, Scene, Settings, builtin_mesh, pan, render, render_cancellable};
pub use preview::{Displacement, Lighting, Maps, Relief, Scene, Settings, VIEW_TRIANGLES, builtin_mesh, pan, render, render_cancellable};
+157 -52
View File
@@ -1,7 +1,7 @@
//! The 3D view's renderer: one ray per pixel (plus 2×2 supersampling when idle) against the
//! scene mesh's BVH, the material's maps sampled with tiling and parallax occlusion from the
//! height output, then metallic/roughness GGX shading under image-based light (SH diffuse,
//! prefiltered specular, an analytic environment BRDF), exposure and ACES tone mapping.
//! scene mesh's BVH, the material's maps sampled with tiling, then metallic/roughness GGX shading
//! under image-based light (SH diffuse, prefiltered specular, an analytic environment BRDF),
//! exposure and ACES tone mapping. The height output displaces real geometry ([`Scene::with_relief`]).
use std::collections::HashMap;
use std::sync::Arc;
@@ -80,37 +80,99 @@ impl Scene {
Scene::new(builtin_mesh(id))
}
/// `base` subdivided to at most `max_tris` triangles and pushed along its normals by
/// `depth × (height − 0.5)` (the height map repeated `tiling` times): real silhouettes and
/// self-occlusion for offline renders. Coincident vertices (UV seams, hard edges) move
/// together, so the surface stays closed.
pub fn displaced(base: &Mesh, height: &Image, tiling: f32, depth: f32, max_tris: usize) -> Scene {
/// `base` subdivided and moved along its normals by `depth × (height − level)`; vertices at one spot move together so it stays closed.
pub fn displaced(base: &Mesh, height: &Image, displacement: &Displacement) -> Scene {
let mut mesh = base.clone();
if mesh.normals.len() != mesh.positions.len() {
mesh.compute_normals();
}
while mesh.triangle_count() > 0 && mesh.triangle_count() * 4 <= max_tris {
while mesh.triangle_count() > 0 && mesh.triangle_count() * 4 <= displacement.max_triangles {
mesh = mesh.subdivided();
}
// Pre-filtered so fine detail (left to the normal map) does not spike the silhouette.
// Pre-filtered so detail finer than the mesh (left to the normal map) does not spike the silhouette
let height = height.resize(height.w.min(512), height.h.min(512), true);
let key = |p: Vec3| (p * 1e4).round().as_ivec3().to_array();
let mut welded: HashMap<[i32; 3], (Vec3, f32, f32)> = HashMap::new();
for ((p, n), uv) in mesh.positions.iter().zip(&mesh.normals).zip(&mesh.uvs) {
let e = welded.entry(key(*p)).or_default();
e.0 += *n;
e.1 += height.sample_gray(uv.x * tiling, uv.y * tiling, true);
e.2 += 1.0;
let level = if displacement.level.is_finite() { displacement.level.clamp(0.0, 1.0) } else { 0.0 };
let depth = if displacement.depth.is_finite() { displacement.depth } else { 0.0 };
let tiling = if displacement.tiling.is_finite() { displacement.tiling.max(0.01) } else { 1.0 };
// Vertices at the same spot (to 0.1 mm) are one point of the surface
let spots: Vec<[i32; 3]> = mesh.positions.iter().map(|p| (*p * 1e4).round().as_ivec3().to_array()).collect();
let mut spot_sums: HashMap<[i32; 3], (Vec3, f32, f32)> = HashMap::new();
for ((spot, n), uv) in spots.iter().zip(&mesh.normals).zip(&mesh.uvs) {
let (normal_sum, height_sum, count) = spot_sums.entry(*spot).or_default();
*normal_sum += *n;
*height_sum += height.sample_gray(uv.x * tiling, uv.y * tiling, true);
*count += 1.0;
}
for p in &mut mesh.positions {
if let Some((n, h, count)) = welded.get(&key(*p)) {
*p += n.normalize_or_zero() * depth * (h / count - 0.5);
let offsets: Vec<Vec3> =
spots.iter().map(|spot| spot_sums.get(spot).map_or(Vec3::ZERO, |(n, h, count)| n.normalize_or_zero() * depth * (h / count - level))).collect();
if displacement.shade_relief {
// Normals of the displaced surface, shared per spot so seams don't show
let moved = |i: u32| mesh.positions.get(i as usize).zip(offsets.get(i as usize)).map(|(p, o)| *p + *o);
let mut face_sums: HashMap<[i32; 3], Vec3> = HashMap::new();
for triangle in mesh.indices.chunks_exact(3) {
let (Some(a), Some(b), Some(c)) = (moved(triangle[0]), moved(triangle[1]), moved(triangle[2])) else { continue };
let face = (b - a).cross(c - a);
for spot in triangle.iter().filter_map(|&i| spots.get(i as usize)) {
*face_sums.entry(*spot).or_default() += face;
}
}
for (spot, n) in spots.iter().zip(mesh.normals.iter_mut()) {
if let Some(sum) = face_sums.get(spot).and_then(|s| s.try_normalize()) {
*n = sum;
}
}
mesh.tangents.clear();
}
for (p, offset) in mesh.positions.iter_mut().zip(&offsets) {
*p += *offset;
}
Scene::new(mesh)
}
/// The scene the 3D view shows for `maps`: displaced by the height output, or `None` when nothing moves.
pub fn with_relief(&self, maps: &Maps, relief: Relief, tiling: f32, max_triangles: usize) -> Option<Scene> {
let height = maps.height.as_ref()?;
if !(relief.depth.is_finite() && relief.depth > 0.0) {
return None;
}
// Without a normal map the displaced surface's own normals show the relief
let displacement = Displacement { depth: relief.depth * self.radius, level: relief.level, tiling, max_triangles, shade_relief: maps.normal.is_none() };
Some(Scene::displaced(&self.mesh, height, &displacement))
}
}
/// How the height output shapes the 3D view's mesh.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Relief {
/// How far white rises above black, in scene radii; 0 = off.
pub depth: f32,
/// The height (0..1) that stays on the original surface: 0 = everything rises out of it.
pub level: f32,
}
/// The parameters of [`Scene::displaced`].
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Displacement {
/// How far white rises above black, in world units.
pub depth: f32,
/// The height (0..1) that stays on the original surface.
pub level: f32,
/// UV repeats of the height map.
pub tiling: f32,
/// Subdivide while one more step stays within this many triangles.
pub max_triangles: usize,
/// Shade with the displaced surface's normals instead of the original ones.
pub shade_relief: bool,
}
/// Triangle budget of a displaced scene in the interactive 3D view (builds in about 0.2–0.3 s on two cores).
pub const VIEW_TRIANGLES: usize = 500_000;
/// A built-in mesh by id; unknown ids give the rounded cube.
pub fn builtin_mesh(id: &str) -> Mesh {
let mut m = materialcraft_geom::primitives::builtin(id).unwrap_or_else(|| materialcraft_geom::primitives::rounded_box(Vec3::ONE, 0.15));
@@ -171,8 +233,6 @@ pub struct Settings {
pub exposure: f32,
/// Degrees.
pub env_rotation: f32,
/// Parallax depth in UV units (0 = off).
pub height_scale: f32,
/// Show the (blurred) environment behind the mesh instead of the flat backdrop.
pub show_env: bool,
/// 1 = one ray per pixel, 2 = 2×2 supersampling.
@@ -199,7 +259,6 @@ impl Default for Settings {
tiling: 1.0,
exposure: 0.0,
env_rotation: 0.0,
height_scale: 0.03,
show_env: false,
supersample: 1,
ao_rays: 0,
@@ -346,36 +405,8 @@ fn shade(scene: &Scene, maps: &Maps, light: &Lighting, s: &Settings, origin: Vec
let tan = (tan - nrm * nrm.dot(tan)).normalize_or_zero();
let bit = nrm.cross(tan) * sign;
let uv0 = *m.uvs.get(i0)? * w0 + *m.uvs.get(i1)? * w1 + *m.uvs.get(i2)? * w2;
let mut uv = uv0 * s.tiling;
let uv = uv0 * s.tiling;
let v = -dir;
// Parallax occlusion: march the height field along the view direction in tangent space.
if s.height_scale > 0.0
&& let Some(h) = &maps.height
{
let vt = Vec3::new(v.dot(tan), v.dot(bit), v.dot(nrm).max(0.05));
let steps = 32;
let delta = Vec2::new(vt.x, -vt.y) / vt.z * s.height_scale * s.tiling / steps as f32;
let mut layer = 1.0;
let mut cur = uv;
let mut prev_h = h.sample_gray(cur.x, cur.y, true);
let mut prev_layer = layer;
for _ in 0..steps {
let hv = h.sample_gray(cur.x, cur.y, true);
if hv >= layer {
// Linear refinement between the last two samples.
let a = prev_h - prev_layer;
let b = hv - layer;
let t = if (b - a).abs() > 1e-6 { a / (a - b) } else { 0.0 };
cur -= delta * (1.0 - t.clamp(0.0, 1.0));
break;
}
prev_h = hv;
prev_layer = layer;
layer -= 1.0 / steps as f32;
cur -= delta;
}
uv = cur;
}
let a = alpha(maps, uv);
if s.alpha_view {
return Some(Shaded { color: Vec3::splat(a), alpha: 1.0, t: hit.t });
@@ -566,6 +597,80 @@ mod tests {
assert_eq!(&px[c..c + 3], &[255, 255, 255]);
}
fn flat(value: f32) -> Image {
Image::filled(8, 8, Kind::Gray, [value; 4])
}
fn displacement(depth: f32, level: f32) -> Displacement {
Displacement { depth, level, tiling: 1.0, max_triangles: 2048, shade_relief: false }
}
/// Heights of a displaced plane's vertices (it faces +y and starts at y = 0).
fn plane_heights(height: &Image, displacement: &Displacement) -> Vec<f32> {
let plane = materialcraft_geom::primitives::plane(2.0, 4);
Scene::displaced(&plane, height, displacement).mesh.positions.iter().map(|p| p.y).collect()
}
/// At level 0 the relief rises out of the surface: black stays on it and nothing sinks in.
#[test]
fn the_relief_rises_out_of_the_surface() {
let near = |heights: Vec<f32>, expected: f32| heights.iter().all(|y| (y - expected).abs() < 1e-5);
assert!(near(plane_heights(&flat(0.0), &displacement(0.2, 0.0)), 0.0), "black stays on the surface");
assert!(near(plane_heights(&flat(1.0), &displacement(0.2, 0.0)), 0.2), "white rises by the depth");
assert!(near(plane_heights(&flat(0.5), &displacement(0.2, 0.5)), 0.0), "the level height stays on the surface");
assert!(near(plane_heights(&flat(0.0), &displacement(0.2, 0.5)), -0.1), "below the level sinks");
assert!(near(plane_heights(&flat(1.0), &displacement(0.2, f32::NAN)), 0.2), "a broken level reads as 0");
}
/// Vertices at one spot (UV seams, hard edges) move together, so a displaced cube stays closed.
#[test]
fn a_displaced_cube_stays_closed() {
// No subdivision, so vertex i of the result is vertex i of the cube
let cube = builtin_mesh("cube");
let ramp = Image::gray(32, 32, |x, y| ((x + y) % 32) as f32 / 31.0);
let displaced = Scene::displaced(&cube, &ramp, &Displacement { max_triangles: 0, ..displacement(0.1, 0.0) });
assert_eq!(displaced.mesh.positions.len(), cube.positions.len());
let spot = |p: Vec3| (p * 1e4).round().as_ivec3().to_array();
let mut moved_to: HashMap<[i32; 3], Vec3> = HashMap::new();
for (before, after) in cube.positions.iter().zip(&displaced.mesh.positions) {
let first = *moved_to.entry(spot(*before)).or_insert(*after);
assert!((first - *after).length() < 1e-4, "{before:?} split into {first:?} and {after:?}");
}
}
/// Without a normal map the displaced surface's own normals shade the relief; with one, the original normals stay.
#[test]
fn relief_normals_follow_the_displaced_surface_only_when_asked() {
let plane = materialcraft_geom::primitives::plane(2.0, 8);
let slope = Image::gray(16, 16, |x, _| x as f32 / 15.0);
let tilted = |shade_relief| {
let scene = Scene::displaced(&plane, &slope, &Displacement { shade_relief, ..displacement(0.5, 0.0) });
scene.mesh.normals.iter().map(|n| n.x.abs()).fold(0.0f32, f32::max)
};
assert!(tilted(true) > 0.1, "a slope tilts the normals");
assert!(tilted(false) < 1e-5, "the original normals are kept");
}
#[test]
fn with_relief_needs_a_height_output_and_a_depth() {
let scene = Scene::builtin("plane");
let maps = Maps { height: Some(flat(1.0)), ..Maps::default() };
let relief = Relief { depth: 0.1, level: 0.0 };
assert!(scene.with_relief(&Maps::default(), relief, 1.0, 2048).is_none());
for depth in [0.0, -1.0, f32::NAN] {
assert!(scene.with_relief(&maps, Relief { depth, ..relief }, 1.0, 2048).is_none(), "{depth}");
}
// The depth is in scene radii
let raised = scene.with_relief(&maps, relief, 1.0, 2048).unwrap();
let top = raised.mesh.positions.iter().map(|p| p.y).fold(f32::MIN, f32::max);
assert!((top - 0.1 * scene.radius).abs() < 1e-4, "{top} vs {}", 0.1 * scene.radius);
}
#[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());
+37 -6
View File
@@ -36,6 +36,9 @@ fn report_failure(app: &mut MaterialCraftApp, msg: String) {
#[derive(Default)]
pub struct Cooker {
rx: Option<Receiver<Result<Cooked, String>>>,
/// Stops the running cook between nodes once its result is stale.
#[cfg(not(target_arch = "wasm32"))]
cancel: Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,
/// When the running cook started (app seconds).
pub started: Option<f64>,
}
@@ -53,12 +56,32 @@ pub fn drive(app: &mut MaterialCraftApp, ctx: &egui::Context) {
Ok(result) => {
app.cooker.rx = None;
app.cooker.started = None;
#[cfg(not(target_arch = "wasm32"))]
{
app.cooker.cancel = None;
}
match result {
Ok(c) => app.session.cooked = c,
// A stopped cook is partial: keep the previous results and cook again.
Ok(c) if c.cancelled => app.session.dirty = true,
Ok(c) => {
if !app.session.dirty {
app.session.cooked = c;
}
}
Err(msg) => report_failure(app, msg),
}
ctx.request_repaint();
}
Err(TryRecvError::Empty) if app.session.dirty => {
// Stop between nodes, but wait for this worker to finish before starting
// another. A slow node must not accumulate workers during rapid edits.
#[cfg(not(target_arch = "wasm32"))]
if let Some(flag) = &app.cooker.cancel {
flag.store(true, std::sync::atomic::Ordering::Relaxed);
}
ctx.request_repaint_after(std::time::Duration::from_millis(16));
return;
}
Err(TryRecvError::Empty) => {
ctx.request_repaint_after(std::time::Duration::from_millis(16));
return;
@@ -67,6 +90,10 @@ pub fn drive(app: &mut MaterialCraftApp, ctx: &egui::Context) {
app.cooker.rx = None;
app.cooker.started = None;
report_failure(app, "the cook worker stopped unexpectedly".into());
#[cfg(not(target_arch = "wasm32"))]
{
app.cooker.cancel = None;
}
}
}
}
@@ -85,20 +112,20 @@ fn start(app: &mut MaterialCraftApp, now: f64) {
let cache = s.cache.clone();
let dec = s.resource_decoder();
let (tx, rx) = std::sync::mpsc::channel();
let flag = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let thread_flag = flag.clone();
use materialcraft_engine::eval::Options;
use std::sync::PoisonError;
let spawned = std::thread::Builder::new().name("materialcraft-cook".into()).spawn(move || {
let mut opts = Options::new(&dec);
opts.max_size = max;
let cooked = guard("cook", || {
let mut cache = cache.lock().unwrap_or_else(PoisonError::into_inner);
Ok(materialcraft_engine::eval::cook(&pkg, gi, &opts, &mut cache))
});
opts.cancel = Some(&thread_flag);
let cooked = guard("cook", || Ok(materialcraft_engine::eval::cook(&pkg, gi, &opts, &cache)));
let _ = tx.send(cooked);
});
match spawned {
Ok(_) => {
app.cooker.rx = Some(rx);
app.cooker.cancel = Some(flag);
app.cooker.started = Some(now);
}
Err(e) => {
@@ -117,3 +144,7 @@ fn start(app: &mut MaterialCraftApp, _now: f64) {
#[cfg(test)]
#[path = "cook.test.rs"]
mod tests;
#[cfg(all(test, not(target_arch = "wasm32")))]
#[path = "cook_cancellation.test.rs"]
mod cancellation_tests;
@@ -0,0 +1,43 @@
use super::*;
use std::sync::{
Arc,
atomic::{AtomicBool, Ordering},
mpsc,
};
fn waiting() -> (MaterialCraftApp, mpsc::Sender<Result<Cooked, String>>, Arc<AtomicBool>) {
let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), crate::UiState::default());
app.session.cook();
app.session.cooked.ms = 123.0;
let (tx, rx) = mpsc::channel();
let flag = Arc::new(AtomicBool::new(false));
app.cooker.rx = Some(rx);
app.cooker.cancel = Some(flag.clone());
(app, tx, flag)
}
#[test]
fn rapid_edits_wait_for_the_cancelled_worker() {
let (mut app, tx, flag) = waiting();
app.session.dirty = true;
for _ in 0..20 {
drive(&mut app, &egui::Context::default());
assert!(app.session.dirty, "a second worker started before the first ended");
assert!(flag.load(Ordering::Relaxed));
assert!(Arc::ptr_eq(app.cooker.cancel.as_ref().unwrap(), &flag));
}
tx.send(Ok(Cooked { cancelled: true, ..Default::default() })).unwrap();
drive(&mut app, &egui::Context::default());
assert!(!app.session.dirty, "latest snapshot should start once the worker ends");
assert_eq!(app.session.cooked.ms, 123.0, "partial results replaced the display");
}
#[test]
fn ready_results_are_discarded_when_an_edit_is_pending() {
let (mut app, tx, _) = waiting();
tx.send(Ok(Cooked { ms: 7.0, ..Default::default() })).unwrap();
app.session.dirty = true;
drive(&mut app, &egui::Context::default());
assert_eq!(app.session.cooked.ms, 123.0);
assert!(!app.session.dirty);
}
+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}));
}
+305 -36
View File
@@ -1,15 +1,16 @@
//! The graph editor: a pannable, zoomable canvas of node cards (colored header, live thumbnail,
//! size label), bezier wires between typed ports, frames, comments and navigation pins.
//!
//! Gestures: left-drag a node to move it (the selection moves together), drag from a port to wire
//! it (dropping on empty canvas opens the node search, wired), drag an input to unplug and re-route
//! it, drag the empty canvas to box-select (Ctrl adds), middle-drag or Alt+drag to pan, wheel to
//! zoom, double-click a node to show it in the 2D view (a graph instance opens its graph), Space, Tab or
//! double-click the canvas for the node search, right-click for menus, drop library 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.
//! Gestures: left-drag a node to move it (the selection moves together), drag from an output to wire
//! it (dropping on empty canvas opens the node search, wired), drag from an unconnected input to an
//! output to wire it the other way, drag a connected input to unplug and re-route 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. 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;
@@ -50,6 +51,10 @@ enum Drag {
wire: WireRef,
start: Pos2,
},
WireFromInput {
to: (NodeId, String),
},
Pan,
Frame {
id: u64,
@@ -618,7 +623,23 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) {
let footer = Rect::from_min_max(pos2(sr.left(), body.bottom()), sr.max);
if let Some(img) = result.and_then(|r| r.outputs.first()) {
let bits = if n.base.format == materialcraft_engine::core::OutputFormat::Inherit { g.format.bits() } else { n.base.format.bits() };
let txt = format!("{}x{} - {}{}", img.w, img.h, if img.is_gray() { "L" } else { "C" }, bits);
let format = format!("{}{}", if img.is_gray() { "L" } else { "C" }, bits);
let txt = if let Some(limit) = app.session.preview_size {
if error.is_none() {
let [pw, ph] = g.size_px();
resp.clone().on_hover_text(format!(
"{} x {} ({format}bpc)\n{}: {pw} x {ph}\n{}: {limit} px\n{}",
img.w,
img.h,
tr("Parent size"),
tr("Preview limit"),
tr("Change Preview size while editing in Edit > Preferences. Exports use each node's configured output size.")
));
}
format!("{}x{} {}", img.w, img.h, tr("Preview"))
} else {
format!("{}x{} - {format}", img.w, img.h)
};
painter.text(footer.center(), Align2::CENTER_CENTER, txt, small.clone(), tk.text_dim);
}
if n.def == "output" {
@@ -724,6 +745,11 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) {
bezier(&painter, src.pos, p, Stroke::new(2.0, tk.accent));
}
}
Some(Drag::WireFromInput { to }) => {
if let (Some(p), Some(dst)) = (pointer, app.graph.ports.iter().find(|h| !h.output && h.node == to.0 && h.port == to.1)) {
bezier(&painter, p, dst.pos, Stroke::new(2.0, tk.accent));
}
}
_ => {}
}
@@ -813,6 +839,8 @@ fn handle_input(
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()) {
app.graph.drag = Some(Drag::Wire { from: (c.from, c.from_port.clone()), detached: Some((h.node, h.port.clone())) });
} else {
app.graph.drag = Some(Drag::WireFromInput { to: (h.node, h.port.clone()) });
}
} else if let Some((id, title, grip)) = frames.iter().find(|(_, t, g)| t.contains(p) || g.contains(p)) {
let resize = grip.contains(p) && !title.contains(p);
@@ -935,6 +963,12 @@ fn handle_input(
}
}
}
Drag::WireFromInput { to } => {
let source = pointer.and_then(|p| nearest_port(&app.graph.ports, p, 12.0)).filter(|h| h.output).cloned();
if let Some(s) = source {
app.run("graph.connect", json!({"from": s.node.0, "fromPort": s.port, "to": to.0.0, "toPort": to.1}));
}
}
Drag::Frame { id, delta, resize, nodes } => {
if delta.length() > 0.5
&& let Some(f) = app.session.graph().ok().and_then(|g| g.frames.iter().find(|f| f.id == id)).cloned()
@@ -976,6 +1010,10 @@ fn handle_input(
app.run("view.2d", json!({"node": id.0, "port": 0}));
}
}
} else if r.clicked() && app.session.selection.contains(id) && app.session.view2d.node != Some(*id) {
// A click that leaves the node selected shows it, replacing a node shown earlier (a
// Ctrl+click that deselects it does not; the shown node keeps its chosen port).
app.run("view.2d", json!({"node": id.0}));
}
r.context_menu(|ui| node_menu(app, ui, *id));
}
@@ -1114,7 +1152,7 @@ fn search_popup(app: &mut MaterialCraftApp, ui: &mut Ui, cam: &Cam) {
pick = Some(d.id);
}
egui::ScrollArea::vertical().max_height(300.0).show(ui, |ui| {
for (i, d) in list.iter().enumerate().take(60) {
for (i, d) in list.iter().enumerate() {
let r = ui.add(
egui::Button::selectable(i == s.sel, format!("{} ", d.label))
.right_text(egui::RichText::new(d.group()).size(10.0).color(tk.text_dim)),
@@ -1309,33 +1347,147 @@ fn canvas_menu(app: &mut MaterialCraftApp, ui: &mut Ui, at: Pos2) {
mod tests {
use super::*;
/// The whole app in an offscreen egui context, driven one frame at a time.
struct Frames {
ctx: egui::Context,
app: MaterialCraftApp,
time: f64,
}
impl Frames {
/// `session` after a few frames, so the canvas is laid out.
fn new(session: materialcraft_engine::Session) -> Frames {
let mut f = Frames { ctx: egui::Context::default(), app: MaterialCraftApp::headless(session, crate::UiState::default()), time: 0.0 };
for _ in 0..3 {
f.run(Vec::new(), egui::Modifiers::NONE);
}
f
}
/// One frame with `events` while `modifiers` are held, in a desktop-sized window (egui's
/// default screen is so large that the 3D view's frame would exceed the texture limit).
fn run(&mut self, events: Vec<egui::Event>, modifiers: egui::Modifiers) {
self.time += 0.05;
let events = std::iter::once(egui::Event::ModifiersChanged(modifiers)).chain(events).collect();
let screen_rect = Some(Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 960.0)));
let input = egui::RawInput { events, screen_rect, time: Some(self.time), ..Default::default() };
let app = &mut self.app;
self.ctx
.run_ui(input, |ui| {
app.step(&ui.ctx().clone());
app.draw(ui);
})
.textures_delta
.clear();
}
/// Press and release the primary button at `pos`, a second after any earlier click so
/// the two never pair into a double-click.
fn click(&mut self, pos: Pos2, modifiers: egui::Modifiers) {
self.time += 1.0;
self.run(vec![egui::Event::PointerMoved(pos)], modifiers);
for pressed in [true, false] {
self.run(vec![egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers }], modifiers);
}
}
/// The center of node `id` on screen last frame.
fn center(&self, id: NodeId) -> Pos2 {
self.app.graph.rects.iter().find(|(n, _)| *n == id).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("node {id:?} is not on screen"))
}
/// The node the 2D view shows once the graph has cooked.
fn shown(&mut self) -> Option<NodeId> {
self.app.session.cook();
self.app.session.view2d_image().map(|(id, _)| id)
}
}
/// A graph with a Perlin noise, a checker and an RGBA split side by side, framed on screen.
fn three_nodes() -> (Frames, [NodeId; 3]) {
let mut s = materialcraft_engine::sample_session();
materialcraft_engine::execute(&mut s, "file.new", &json!({"template": "empty", "size": 256})).unwrap();
let ids = ["perlin_noise", "checker", "rgba_split"].iter().enumerate().map(|(i, def)| {
let added = materialcraft_engine::execute(&mut s, "graph.node.add", &json!({"def": def, "at": [i as f32 * 300.0, 0.0]})).unwrap();
NodeId(added["id"].as_u64().unwrap())
});
let ids: [NodeId; 3] = ids.collect::<Vec<_>>().try_into().unwrap();
s.selection.clear();
(Frames::new(s), ids)
}
#[test]
fn clicking_a_node_shows_it_in_the_2d_view() {
let (mut f, [noise, checker, _]) = three_nodes();
// Shown explicitly first (a double-click, an output port or "View in 2D view").
f.app.run("view.2d", json!({"node": noise.0}));
assert_eq!(f.shown(), Some(noise));
let at = f.center(checker);
f.click(at, egui::Modifiers::NONE);
assert_eq!(f.app.session.selection, vec![checker]);
assert_eq!(f.app.session.view2d.node, Some(checker));
assert_eq!(f.shown(), Some(checker));
// And back.
let at = f.center(noise);
f.click(at, egui::Modifiers::NONE);
assert_eq!(f.app.session.view2d.node, Some(noise));
assert_eq!(f.shown(), Some(noise));
// Ctrl+click adds a node to the selection and shows it too.
let at = f.center(checker);
f.click(at, egui::Modifiers::CTRL);
assert_eq!(f.app.session.selection, vec![noise, checker]);
assert_eq!(f.shown(), Some(checker));
}
#[test]
fn ctrl_click_that_deselects_a_node_does_not_show_it() {
let (mut f, [noise, checker, _]) = three_nodes();
f.app.session.selection = vec![noise, checker];
f.app.run("view.2d", json!({"node": checker.0}));
let at = f.center(noise);
f.click(at, egui::Modifiers::CTRL);
assert_eq!(f.app.session.selection, vec![checker]);
assert_eq!(f.shown(), Some(checker));
}
#[test]
fn dragging_a_node_keeps_the_2d_view() {
let (mut f, [noise, checker, _]) = three_nodes();
f.app.run("view.2d", json!({"node": noise.0}));
let before = f.app.session.graph().unwrap().node(checker).unwrap().pos;
let from = f.center(checker);
let none = egui::Modifiers::NONE;
f.run(vec![egui::Event::PointerMoved(from)], none);
f.run(vec![egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: none }], none);
for step in 1..=8 {
f.run(vec![egui::Event::PointerMoved(from + vec2(5.0 * step as f32, 0.0))], none);
}
let to = from + vec2(40.0, 0.0);
f.run(vec![egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: none }], none);
let after = f.app.session.graph().unwrap().node(checker).unwrap().pos;
let moved = 40.0 / f.app.ui.graph_camera.zoom;
assert!((after[0] - before[0] - moved).abs() < 1e-3 && after[1] == before[1], "the checker moved {before:?} -> {after:?}, not {moved} right");
assert_eq!(f.app.session.selection, vec![checker]);
assert_eq!(f.shown(), Some(noise));
}
#[test]
fn clicking_the_shown_node_keeps_its_port() {
let (mut f, [_, _, split]) = three_nodes();
f.app.run("view.2d", json!({"node": split.0, "port": 2}));
let at = f.center(split);
f.click(at, egui::Modifiers::NONE);
assert_eq!(f.app.session.selection, vec![split]);
assert_eq!((f.app.session.view2d.node, f.app.session.view2d.port), (Some(split), 2));
}
#[test]
fn tab_opens_search_in_the_full_workspace() {
let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), crate::UiState::default());
let ctx = egui::Context::default();
for _ in 0..3 {
ctx.run_ui(egui::RawInput::default(), |ui| {
app.step(&ui.ctx().clone());
app.draw(ui);
})
.textures_delta
.clear();
}
let pointer = app.graph.view.center();
let input = egui::RawInput {
events: vec![
egui::Event::PointerMoved(pointer),
egui::Event::Key { key: egui::Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE },
],
..Default::default()
};
ctx.run_ui(input, |ui| {
app.step(&ui.ctx().clone());
app.draw(ui);
})
.textures_delta
.clear();
assert!(app.graph.search.is_some());
let mut f = Frames::new(materialcraft_engine::sample_session());
let pointer = f.app.graph.view.center();
let tab = egui::Event::Key { key: egui::Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE };
f.run(vec![egui::Event::PointerMoved(pointer), tab], egui::Modifiers::NONE);
assert!(f.app.graph.search.is_some());
}
#[test]
@@ -1387,6 +1539,56 @@ mod tests {
assert!(app.graph.selected_wires.is_empty());
}
#[test]
fn wires_connect_when_dragged_from_either_end() {
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 noise = id(app.run("graph.node.add", json!({"def": "perlin_noise", "at": [0, 0]})));
let blend = id(app.run("graph.node.add", json!({"def": "blend", "at": [450, 0]})));
let ctx = egui::Context::default();
let frame = |app: &mut MaterialCraftApp, events: Vec<egui::Event>| {
ctx.run_ui(egui::RawInput { events, screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 960.0))), ..Default::default() }, |ui| {
app.step(&ui.ctx().clone());
app.draw(ui);
})
.textures_delta
.clear();
};
for _ in 0..3 {
frame(&mut app, Vec::new());
}
let port = |app: &MaterialCraftApp, node: u64, output: bool, name: &str| {
app.graph.ports.iter().find(|h| h.node.0 == node && h.output == output && h.port == name).map(|h| h.pos).unwrap()
};
let output = port(&app, noise, true, "output");
let foreground = port(&app, blend, false, "foreground");
let background = port(&app, blend, false, "background");
let empty = app.graph.view.left_top() + vec2(5.0, 5.0);
let drag = |app: &mut MaterialCraftApp, from: Pos2, to: Pos2| {
let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE };
frame(app, vec![egui::Event::PointerMoved(from)]);
frame(app, vec![button(from, true)]);
frame(app, vec![egui::Event::PointerMoved(to)]);
frame(app, vec![button(to, false)]);
};
let source = |app: &MaterialCraftApp| app.session.graph().unwrap().input_of(NodeId(blend), "foreground").map(|c| (c.from.0, c.from_port.clone()));
// From the input: only an output finishes the wire, and a miss changes nothing.
drag(&mut app, foreground, empty);
assert_eq!(source(&app), None);
assert!(app.graph.search.is_none());
drag(&mut app, foreground, background);
assert_eq!(source(&app), None);
drag(&mut app, foreground, output);
assert_eq!(source(&app), Some((noise, "output".to_string())));
// From the output, as before.
app.run("graph.disconnect", json!({"to": blend, "toPort": "foreground"}));
drag(&mut app, output, foreground);
assert_eq!(source(&app), Some((noise, "output".to_string())));
}
#[test]
fn node_search_shortcuts_respect_hover_and_keyboard_focus() {
for key in [egui::Key::Space, egui::Key::Tab] {
@@ -1456,4 +1658,71 @@ mod tests {
assert!(p.y > r.top() + HEADER_H && p.y < r.bottom() - FOOTER_H);
}
}
fn search_harness(render: bool) -> egui_kittest::Harness<'static, MaterialCraftApp> {
let app = MaterialCraftApp::headless(materialcraft_engine::new_session(), crate::UiState::default());
let builder = egui_kittest::Harness::builder().with_size(vec2(1600.0, 960.0)).with_step_dt(1.0 / 60.0);
let builder = if render { builder.wgpu() } else { builder };
let mut h = builder.build_ui_state(
|ui, app: &mut MaterialCraftApp| {
app.step(&ui.ctx().clone());
app.draw(ui);
},
app,
);
h.run_steps(10);
let pointer = h.state().graph.view.center();
h.event(egui::Event::PointerMoved(pointer));
h.step();
h.key_press(egui::Key::Tab);
h.step();
assert!(h.state().graph.search.is_some());
h
}
fn select_result_after_cutoff(h: &mut egui_kittest::Harness<'static, MaterialCraftApp>) -> &'static str {
for _ in 0..60 {
h.key_press(egui::Key::ArrowDown);
h.step();
}
h.run_steps(3); // Let scroll_to_me bring the selected row into view.
let selected = h.state().graph.search.as_ref().unwrap().sel;
assert_eq!(selected, 60);
let def = matches("")[selected];
let popup = h.ctx.memory(|m| m.area_rect(egui::Id::unique("node-search"))).unwrap();
fn visible(shape: &egui::epaint::Shape, clip: Rect, popup: Rect, label: &str) -> bool {
match shape {
egui::epaint::Shape::Text(t) => popup.contains(t.pos) && clip.contains(t.pos) && t.galley.text().trim_start().starts_with(label),
egui::epaint::Shape::Vec(v) => v.iter().any(|s| visible(s, clip, popup, label)),
_ => false,
}
}
assert!(
h.output().shapes.iter().any(|s| visible(&s.shape, s.clip_rect, popup, def.label)),
"keyboard-selected result {selected} ({}) is not visible in the popup",
def.label
);
def.id
}
#[test]
fn keyboard_search_selection_after_sixty_results_is_visible_and_inserts() {
let mut h = search_harness(false);
let expected = select_result_after_cutoff(&mut h);
h.key_press(egui::Key::Enter);
h.step();
assert!(h.state().graph.search.is_none());
let graph = h.state().session.graph().unwrap();
assert_eq!(graph.nodes.len(), 1);
assert_eq!(graph.nodes[0].def, expected);
}
#[test]
#[ignore = "requires an offscreen GPU"]
fn search_result_after_sixty_screenshot() {
let mut h = search_harness(true);
select_result_after_cutoff(&mut h);
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();
h.render().unwrap().save(dir.join("search-result-61.png")).unwrap();
}
}
-27
View File
@@ -110,33 +110,6 @@ pub fn os_language() -> &'static str {
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");
+2 -1
View File
@@ -229,7 +229,8 @@ impl MaterialCraftApp {
self.styled = Some(style);
}
let scale = self.ui.prefs.ui_scale.clamp(0.5, 3.0);
if (ctx.zoom_factor() - scale).abs() > 1e-3 {
// Rescaling during a drag moves the control under the pointer and feeds back into its value.
if (ctx.zoom_factor() - scale).abs() > 1e-3 && !ctx.input(|i| i.pointer.any_down()) {
ctx.set_zoom_factor(scale);
}
control::poll(self, ctx);
+2 -2
View File
@@ -43,10 +43,10 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {
ui.set_width(ui.available_width());
let node = app.session.selection.last().and_then(|id| app.session.graph().ok()?.node(*id).ok().cloned());
match node {
ui.push_id((app.session.graph, node.as_ref().map(|n| n.id)), |ui| match node {
Some(n) => node_props(app, ui, &n),
None => graph_props(app, ui),
}
});
});
}
+3
View File
@@ -108,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)]
@@ -131,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,
}
+1 -7
View File
@@ -88,13 +88,7 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
let (r, resp) = ui.allocate_exact_size(ui.available_size(), Sense::hover());
crate::widgets::name(&resp, egui::Role::Image, "2D view");
ui.painter().rect_filled(r, 0.0, tk.viewport);
ui.painter().text(
r.center(),
egui::Align2::CENTER_CENTER,
tr("Double-click a node to show it here"),
egui::FontId::proportional(12.0),
tk.viewport_text,
);
ui.painter().text(r.center(), egui::Align2::CENTER_CENTER, tr("Click a node to show it here"), egui::FontId::proportional(12.0), tk.viewport_text);
return;
};
let key = app.session.cooked.nodes.get(&id).map_or(0, |r| r.key)
+162 -22
View File
@@ -7,6 +7,8 @@
//! (a panel, divider or window drag changes the size on every step), then renders on a worker
//! thread so the UI never waits for it; until it lands the last frame stays up, kept in proportion.
//! A frame that is no longer wanted is cancelled. The browser has no threads and renders here.
//!
//! The height output raises the mesh for real ([`Scene::with_relief`]), built on a worker thread and cached until its inputs change.
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
@@ -16,7 +18,7 @@ use std::time::Duration;
use egui::{Color32, ColorImage, Rect, Sense, TextureHandle, TextureOptions, Ui, pos2, vec2};
use egui_phosphor::regular as icon;
use materialcraft_engine::view_cmds::{ENVIRONMENTS, SCENES};
use materialcraft_render::{Lighting, Maps, Scene, Settings};
use materialcraft_render::{Lighting, Maps, Relief, Scene, Settings};
use serde_json::json;
use crate::MaterialCraftApp;
@@ -26,9 +28,16 @@ use crate::theme::Tokens;
/// Seconds the view's size and the camera rest before the full-quality frame renders.
pub const SETTLE: f64 = 0.15;
/// Triangle budget of the displaced mesh; the browser builds it on the UI thread, so it gets a smaller one.
const RELIEF_TRIANGLES: usize = if cfg!(target_arch = "wasm32") { 120_000 } else { materialcraft_render::VIEW_TRIANGLES };
#[derive(Default)]
pub struct View3dState {
scene: Option<(String, Arc<Scene>)>,
/// The scene displaced by the height output, keyed by what it was built from (see [`relief_key`]).
displaced: Option<(u64, Arc<Scene>)>,
/// The displaced scene building on a worker thread.
relief_job: Option<ReliefJob>,
light: Option<Arc<Lighting>>,
tex: Option<TextureHandle>,
/// What the texture shows: (content key, full quality).
@@ -50,9 +59,9 @@ pub struct View3dState {
}
impl View3dState {
/// A full-quality frame is rendering in the background.
/// A frame or its displaced geometry is still being built in the background.
pub fn busy(&self) -> bool {
self.job.is_some()
self.job.is_some() || self.relief_job.is_some()
}
}
@@ -79,6 +88,13 @@ impl Drop for Job {
}
}
/// A displaced scene building on a worker thread (`None` arrives when nothing moves).
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
struct ReliefJob {
key: u64,
rx: Receiver<Option<Arc<Scene>>>,
}
pub fn scene_label(app: &MaterialCraftApp) -> String {
let id = &app.session.view3d.scene;
if id == "custom"
@@ -153,9 +169,13 @@ fn menus(app: &mut MaterialCraftApp, ui: &mut Ui) {
}
});
ui.menu_button(tr("Renderer"), |ui| {
let mut h = app.session.view3d.height_scale * 100.0;
if crate::widgets::slider(ui, tr("Height (parallax) depth"), &mut h, 0.0..=10.0, 2).changed() {
app.run("view.3d", json!({"heightScale": h / 100.0}));
let mut depth_percent = app.session.view3d.height_scale * 100.0;
if crate::widgets::slider(ui, tr("Height depth (% of the mesh size)"), &mut depth_percent, 0.0..=20.0, 1).changed() {
app.run("view.3d", json!({"heightScale": depth_percent / 100.0}));
}
let mut level = app.session.view3d.height_level;
if crate::widgets::slider(ui, tr("Height level (0 = rises out of the surface)"), &mut level, 0.0..=1.0, 2).changed() {
app.run("view.3d", json!({"heightLevel": level}));
}
let mut t = app.session.view3d.tiling;
if crate::widgets::slider(ui, tr("Tiling"), &mut t, 0.25..=8.0, 2).changed() {
@@ -273,12 +293,12 @@ fn frame_rect(rect: Rect, rendered: Option<(u32, u32)>) -> Rect {
}
}
fn content_key(app: &MaterialCraftApp, w: u32, h: u32, show_env: bool) -> u64 {
fn content_key(app: &MaterialCraftApp, w: u32, h: u32, show_env: bool, relief_shown: Option<u64>) -> 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), 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] {
(w, h, show_env, &v.scene, &v.environment, app.session.custom_mesh.as_ref().map(|(n, _)| n), v.transparency, v.alpha_view, relief_shown).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, v.height_level] {
f.to_bits().hash(&mut hs);
}
if let Ok(g) = app.session.graph() {
@@ -298,7 +318,8 @@ fn render(app: &mut MaterialCraftApp, ctx: &egui::Context, rect: Rect, moving: b
app.view3d.changed_at = Some(now);
}
app.view3d.size = Some(size);
let key = content_key(app, size.0, size.1, app.view3d.show_env);
let relief_shown = update_relief(app, ctx);
let key = content_key(app, size.0, size.1, app.view3d.show_env, relief_shown);
collect(app, ctx, key);
if app.view3d.key == Some((key, true)) || (moving && app.view3d.key == Some((key, false))) {
return;
@@ -338,23 +359,112 @@ fn collect(app: &mut MaterialCraftApp, ctx: &egui::Context, key: u64) {
}
}
/// The scene, lighting, maps and settings of the current view (scene and lighting are cached).
fn inputs(app: &mut MaterialCraftApp, supersample: u32) -> Option<(Arc<Scene>, Arc<Lighting>, Maps, Settings)> {
let v = app.session.view3d.clone();
/// The plain scene of the current view and its cache key, building it when the scene changed.
fn base_scene(app: &mut MaterialCraftApp) -> (String, Arc<Scene>) {
let v = &app.session.view3d;
let scene_key = match (&*v.scene, &app.session.custom_mesh) {
("custom", Some((name, _))) => format!("custom:{name}"),
_ => v.scene.clone(),
};
if app.view3d.scene.as_ref().is_none_or(|(id, _)| *id != scene_key) {
let scene = match (&*v.scene, &app.session.custom_mesh) {
("custom", Some((_, mesh))) => Scene::new((**mesh).clone()),
_ => Scene::builtin(&v.scene),
};
app.view3d.scene = Some((scene_key, Arc::new(scene)));
match &app.view3d.scene {
Some((key, scene)) if *key == scene_key => (scene_key, scene.clone()),
_ => {
let scene = match (&*v.scene, &app.session.custom_mesh) {
("custom", Some((_, mesh))) => Scene::new((**mesh).clone()),
_ => Scene::builtin(&v.scene),
};
let scene = Arc::new(scene);
app.view3d.scene = Some((scene_key.clone(), scene.clone()));
(scene_key, scene)
}
}
}
/// What the displaced scene depends on (scene, height output cook, relief settings, normal map); `None` when nothing is raised.
fn relief_key(app: &MaterialCraftApp, scene_key: &str, maps: &Maps) -> Option<u64> {
use std::hash::{DefaultHasher, Hash, Hasher};
let v = &app.session.view3d;
if maps.height.is_none() || v.height_scale <= 0.0 {
return None;
}
let graph = app.session.graph().ok()?;
let height_output = materialcraft_engine::eval::outputs(graph, &app.session.cooked).into_iter().find(|(_, usage, _, _)| *usage == "height");
let height_cook = height_output.and_then(|(id, _, _, _)| app.session.cooked.nodes.get(&id).map(|r| r.key));
let mut hasher = DefaultHasher::new();
(scene_key, height_cook, maps.normal.is_some()).hash(&mut hasher);
for f in [v.height_scale, v.height_level, v.tiling] {
f.to_bits().hash(&mut hasher);
}
Some(hasher.finish())
}
/// Collect a finished relief build or start a missing one; returns the key of the displaced scene shown (`None` = plain mesh).
fn update_relief(app: &mut MaterialCraftApp, ctx: &egui::Context) -> Option<u64> {
let (scene_key, base) = base_scene(app);
let maps = Maps::from_usages(app.session.material_maps());
let wanted = relief_key(app, &scene_key, &maps);
if let Some(job) = app.view3d.relief_job.take() {
match job.rx.try_recv() {
Ok(Some(scene)) if Some(job.key) == wanted => app.view3d.displaced = Some((job.key, scene)),
Ok(_) | Err(TryRecvError::Disconnected) => {}
// Finish the active build before starting a newer one. Dropping its receiver
// cannot cancel subdivision, so rapid edits must not accumulate workers.
Err(TryRecvError::Empty) => app.view3d.relief_job = Some(job),
}
}
let wanted = wanted?;
if app.view3d.displaced.as_ref().is_some_and(|(key, _)| *key == wanted) {
return Some(wanted);
}
if app.view3d.relief_job.is_none() {
let v = &app.session.view3d;
let relief = Relief { depth: v.height_scale, level: v.height_level };
start_relief(app, ctx, wanted, base, maps, relief, v.tiling);
}
None
}
/// Build the displaced scene on a worker thread.
#[cfg(not(target_arch = "wasm32"))]
fn start_relief(app: &mut MaterialCraftApp, ctx: &egui::Context, key: u64, base: Arc<Scene>, maps: Maps, relief: Relief, tiling: f32) {
let (tx, rx) = std::sync::mpsc::channel();
let (repaint, viewport) = (ctx.clone(), ctx.viewport_id());
let (thread_base, thread_maps) = (base.clone(), maps.clone());
let spawned = std::thread::Builder::new().name("materialcraft-relief".into()).spawn(move || {
let _ = tx.send(thread_base.with_relief(&thread_maps, relief, tiling, RELIEF_TRIANGLES).map(Arc::new));
repaint.request_repaint_of(viewport);
});
match spawned {
Ok(_) => app.view3d.relief_job = Some(ReliefJob { key, rx }),
Err(e) => {
log::warn!("could not start a 3D view relief thread ({e}); building it here");
app.view3d.displaced = base.with_relief(&maps, relief, tiling, RELIEF_TRIANGLES).map(|scene| (key, Arc::new(scene)));
}
}
}
/// The browser has no threads: the displaced scene builds here (the page pauses).
#[cfg(target_arch = "wasm32")]
fn start_relief(app: &mut MaterialCraftApp, _ctx: &egui::Context, key: u64, base: Arc<Scene>, maps: Maps, relief: Relief, tiling: f32) {
app.view3d.displaced = base.with_relief(&maps, relief, tiling, RELIEF_TRIANGLES).map(|scene| (key, Arc::new(scene)));
}
/// The scene, lighting, maps and settings of the current view: the displaced scene when it is current, else the plain one.
fn inputs(app: &mut MaterialCraftApp, supersample: u32) -> Option<(Arc<Scene>, Arc<Lighting>, Maps, Settings)> {
let (scene_key, base) = base_scene(app);
let v = app.session.view3d.clone();
if app.view3d.light.as_ref().is_none_or(|l| l.name != v.environment) {
app.view3d.light = Some(Arc::new(Lighting::new(&v.environment)));
}
let settings = Settings {
yaw: v.yaw,
pitch: v.pitch,
@@ -363,7 +473,6 @@ fn inputs(app: &mut MaterialCraftApp, supersample: u32) -> Option<(Arc<Scene>, A
tiling: v.tiling,
exposure: v.exposure,
env_rotation: v.env_rotation,
height_scale: v.height_scale,
show_env: app.view3d.show_env,
supersample,
transparency: v.transparency,
@@ -371,8 +480,13 @@ fn inputs(app: &mut MaterialCraftApp, supersample: u32) -> Option<(Arc<Scene>, A
..Settings::default()
};
let maps = Maps::from_usages(app.session.material_maps());
let (Some((_, scene)), Some(light)) = (&app.view3d.scene, &app.view3d.light) else { return None };
Some((scene.clone(), light.clone(), maps, settings))
let wanted = relief_key(app, &scene_key, &maps);
let scene = match &app.view3d.displaced {
Some((key, displaced)) if Some(*key) == wanted => displaced.clone(),
_ => base,
};
let light = app.view3d.light.clone()?;
Some((scene, light, maps, settings))
}
/// Texture pixels for `rect` at `scale` pixels per point.
@@ -441,6 +555,32 @@ fn show_frame(app: &mut MaterialCraftApp, ctx: &egui::Context, frame: Frame, key
mod tests {
use super::*;
#[test]
fn changing_relief_keeps_one_worker_and_discards_stale_geometry() {
let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), crate::UiState::default());
app.session.cook();
let (scene_key, base) = base_scene(&mut app);
let maps = Maps::from_usages(app.session.material_maps());
let old_key = relief_key(&app, &scene_key, &maps).unwrap();
let (tx, rx) = std::sync::mpsc::channel();
app.view3d.relief_job = Some(ReliefJob { key: old_key, rx });
let ctx = egui::Context::default();
for index in 1..=20 {
app.session.view3d.height_scale = index as f32 * 0.001;
assert_eq!(update_relief(&mut app, &ctx), None);
assert_eq!(app.view3d.relief_job.as_ref().unwrap().key, old_key, "a second subdivision worker started");
assert!(app.view3d.busy(), "geometry work must count as a busy view");
}
let wanted = relief_key(&app, &scene_key, &maps).unwrap();
assert_ne!(old_key, wanted);
app.view3d.displaced = Some((wanted, base.clone()));
tx.send(Some(Arc::new(Scene::builtin("sphere")))).unwrap();
assert_eq!(update_relief(&mut app, &ctx), Some(wanted));
assert!(app.view3d.relief_job.is_none());
assert!(!app.view3d.busy());
assert!(Arc::ptr_eq(&app.view3d.displaced.as_ref().unwrap().1, &base), "outdated geometry replaced the current scene");
}
#[test]
fn a_frame_for_another_size_keeps_its_proportions() {
let rect = Rect::from_min_size(pos2(10.0, 20.0), vec2(400.0, 200.0));
+1 -1
View File
@@ -197,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();
+31 -7
View File
@@ -20,33 +20,57 @@ pub fn dnd_release<T: std::any::Any + Send + Sync>(resp: &Response) -> Option<st
}
/// A labelled slider in two rows: "Label ........ value" over a slim track with a round knob.
/// Returns the response of the track (`.changed()` when dragged, `.drag_stopped()` at the end).
/// Returns the track response (`.changed()` on a drag or valid numeric edit).
pub fn slider(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive<f32>, decimals: usize) -> Response {
let tk = Tokens::get(ui.ctx());
let (lo, hi) = (*range.start(), *range.end());
let w = ui.available_width();
let mut edited = false;
ui.horizontal(|ui| {
ui.label(RichText::new(label).color(tk.text));
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let mut text = format!("{:.*}", decimals, value);
let r = ui.add(egui::TextEdit::singleline(&mut text).desired_width(44.0).align(egui::Align2::RIGHT_CENTER).frame(egui::Frame::NONE));
let id = ui.next_auto_id();
// Keep incomplete input (such as "-") across frames while editing.
let draft = id.with("numeric-draft");
let editing = ui.memory(|m| m.has_focus(id) || m.had_focus_last_frame(id));
let mut text = editing.then(|| ui.data(|d| d.get_temp::<String>(draft))).flatten().unwrap_or_else(|| format!("{:.*}", decimals, value));
let r = ui.add(egui::TextEdit::singleline(&mut text).id(id).desired_width(44.0).align(egui::Align2::RIGHT_CENTER).frame(egui::Frame::NONE));
name(&r, egui::Role::TextInput, label);
if r.lost_focus()
if (r.changed() || r.lost_focus())
&& !ui.input(|i| i.key_pressed(egui::Key::Escape))
&& let Ok(v) = text.trim().parse::<f32>()
&& v.is_finite()
{
*value = v.clamp(lo, hi);
let v = v.clamp(lo, hi);
edited = v != *value;
*value = v;
}
let focused = r.has_focus();
ui.data_mut(|d| {
if focused {
d.insert_temp(draft, text);
} else {
d.remove::<String>(draft);
}
});
});
});
let (rect, mut resp) = ui.allocate_exact_size(vec2(w, 14.0), Sense::click_and_drag());
if edited {
resp.mark_changed();
}
let (v, l) = (*value as f64, label.to_string());
resp.widget_info(move || egui::WidgetInfo::slider(true, v, l.clone()));
if (resp.dragged() || resp.clicked())
&& let Some(p) = resp.interact_pointer_pos()
{
let t = ((p.x - rect.left() - 5.0) / (rect.width() - 10.0).max(1.0)).clamp(0.0, 1.0);
let v = lo + (hi - lo) * t;
let value_at = |x: f32| {
let t = ((x - rect.left() - 5.0) / (rect.width() - 10.0).max(1.0)).clamp(0.0, 1.0);
f64::from(lo) + (f64::from(hi) - f64::from(lo)) * f64::from(t)
};
// Use the same round-value aiming as egui's standard sliders, within one physical pixel.
let radius = ui.input(|i| i.aim_radius());
let v = egui::emath::smart_aim::best_in_range_f64(value_at(p.x - radius), value_at(p.x + radius)) as f32;
if (v - *value).abs() > f32::EPSILON {
*value = v;
resp.mark_changed();
+19 -4
View File
@@ -28,7 +28,7 @@ const PREVIEW: u32 = 96;
fn render_templates() -> crate::thumbs::Previews {
let light = materialcraft_render::Lighting::new("studio");
let scene = materialcraft_render::Scene::builtin("sphere");
let settings = materialcraft_render::Settings { distance: 2.7, supersample: 2, height_scale: 0.0, ..Default::default() };
let settings = materialcraft_render::Settings { distance: 2.7, supersample: 2, ..Default::default() };
materialcraft_engine::samples::TEMPLATES
.iter()
.map(|(id, _)| {
@@ -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);
+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();
}
}
+89
View File
@@ -0,0 +1,89 @@
//! Changing interface scale must not move its slider under a held pointer.
use egui::{Event, Modifiers, PointerButton, Pos2, Rect, pos2, vec2};
use egui_kittest::{
Harness,
kittest::{By, Queryable},
};
use materialcraft_ui_egui::{MaterialCraftApp, UiState};
fn harness(scale: f32, render: bool) -> Harness<'static, MaterialCraftApp> {
let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default());
app.ui.windows.preferences = true;
app.ui.prefs.ui_scale = scale;
let builder = Harness::builder().with_size(vec2(1600.0, 960.0)).with_pixels_per_point(1.0).with_step_dt(1.0 / 60.0);
let builder = if render { builder.wgpu() } else { builder };
let mut h = builder.build_ui_state(
|ui, app: &mut MaterialCraftApp| {
app.step(&ui.ctx().clone());
app.draw(ui);
},
app,
);
h.run_steps(10);
h
}
// Keep the physical window and pointer fixed, just as a native window does when zoom changes.
fn point(h: &mut Harness<'static, MaterialCraftApp>, physical: Pos2, pressed: Option<bool>) {
let zoom = h.ctx.zoom_factor();
let pos = physical / zoom;
h.input_mut().screen_rect = Some(Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 960.0) / zoom));
h.event(Event::PointerMoved(pos));
if let Some(pressed) = pressed {
h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
}
h.step();
}
fn drag_scale(h: &mut Harness<'static, MaterialCraftApp>, fraction: f32) {
let initial = h.ctx.zoom_factor();
let track = h.get(By::new().role(egui::accesskit::Role::Slider).label("Interface scale")).rect();
let start = track.center() * initial;
let target = pos2(track.left() + track.width() * fraction, track.center().y) * initial;
point(h, start, None);
point(h, start, Some(true));
point(h, target, None);
let chosen = h.state().ui.prefs.ui_scale;
assert!((chosen - initial).abs() > 0.1, "the drag did not change the setting");
for _ in 0..15 {
point(h, target, None);
assert!((h.state().ui.prefs.ui_scale - chosen).abs() < 0.001, "scale drifted under a stationary pointer");
assert!((h.ctx.zoom_factor() - initial).abs() < 0.001, "zoom changed while dragging");
}
point(h, target, Some(false));
h.run_steps(5);
assert!((h.state().ui.prefs.ui_scale - chosen).abs() < 0.001, "release changed the chosen value");
assert!((h.ctx.zoom_factor() - chosen).abs() < 0.001, "release did not apply the chosen scale");
}
#[test]
fn scale_drags_are_stable_and_apply_on_release() {
for (initial, fraction) in [(1.0, 0.7), (1.0, 0.1), (1.5, 0.2)] {
let mut h = harness(initial, false);
drag_scale(&mut h, fraction);
}
}
#[test]
fn scale_track_click_applies_after_release() {
let mut h = harness(1.0, false);
let track = h.get(By::new().role(egui::accesskit::Role::Slider).label("Interface scale")).rect();
let target = pos2(track.left() + track.width() * 0.8, track.center().y);
point(&mut h, target, None);
point(&mut h, target, Some(true));
assert_eq!(h.ctx.zoom_factor(), 1.0);
point(&mut h, target, Some(false));
h.run_steps(5);
assert!(h.state().ui.prefs.ui_scale > 1.5);
assert!((h.ctx.zoom_factor() - h.state().ui.prefs.ui_scale).abs() < 0.001);
}
#[test]
#[ignore = "requires an offscreen GPU"]
fn scale_drag_screenshot() {
let mut h = harness(1.0, true);
drag_scale(&mut h, 0.7);
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();
h.render().unwrap().save(dir.join("interface-scale-after-drag.png")).unwrap();
}
@@ -0,0 +1,29 @@
//! Isolate process-global language switching from tests that construct the UI.
use materialcraft_ui_egui::i18n::{current, is_rtl, set_language, tr, trf};
#[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");
}
+172
View File
@@ -0,0 +1,172 @@
//! Exact numeric edits must survive intervening frames and reach engine parameters.
use egui::{Event, Key, Modifiers, vec2};
use egui_kittest::{
Harness,
kittest::{By, Queryable},
};
use materialcraft_engine::core::{NodeId, Value};
use materialcraft_ui_egui::{MaterialCraftApp, UiState};
use serde_json::json;
fn harness(render: bool) -> (Harness<'static, MaterialCraftApp>, NodeId) {
let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), UiState::default());
app.run("file.new", json!({"template":"empty"})).unwrap();
let id = NodeId(app.run("graph.node.add", json!({"def":"transformation"})).unwrap()["id"].as_u64().unwrap());
app.session.reset_history();
let builder = Harness::builder().with_size(vec2(1600.0, 960.0)).with_step_dt(1.0 / 60.0);
let builder = if render { builder.wgpu() } else { builder };
let mut h = builder.build_ui_state(
|ui, app: &mut MaterialCraftApp| {
app.step(&ui.ctx().clone());
app.draw(ui);
},
app,
);
h.run_steps(8);
(h, id)
}
fn focus_x(h: &mut Harness<'static, MaterialCraftApp>, index: usize) {
h.get_all(By::new().role(egui::accesskit::Role::TextInput).label("X")).nth(index).unwrap().click();
h.step();
h.key_press_modifiers(Modifiers::COMMAND, Key::A);
h.step();
}
fn type_text(h: &mut Harness<'static, MaterialCraftApp>, text: &str) {
h.event(Event::Text(text.into()));
h.step();
h.run_steps(4);
}
fn pair(h: &Harness<'static, MaterialCraftApp>, id: NodeId, param: &str) -> [f32; 2] {
match h.state().session.graph().unwrap().node(id).unwrap().params.get(param) {
Some(Value::Float2(v)) => *v,
None => match materialcraft_engine::nodes::find("transformation").unwrap().params.iter().find(|p| p.id == param).unwrap().default {
Value::Float2(v) => v,
_ => panic!("not a pair"),
},
other => panic!("unexpected value {other:?}"),
}
}
#[test]
fn scale_x_commits_on_enter_and_focus_loss_with_undo() {
for enter in [true, false] {
let (mut h, id) = harness(false);
focus_x(&mut h, 1);
type_text(&mut h, "4");
if enter {
h.key_press(Key::Enter);
h.step();
} else {
h.get_by_label("Node label").click();
h.step();
}
h.run_steps(5);
assert_eq!(pair(&h, id, "scale"), [4.0, 1.0], "Scale X did not persist (Enter={enter})");
h.state_mut().run("edit.undo", json!({})).unwrap();
h.run_steps(3);
assert_eq!(pair(&h, id, "scale"), [1.0, 1.0]);
h.state_mut().run("edit.redo", json!({})).unwrap();
h.run_steps(3);
assert_eq!(pair(&h, id, "scale"), [4.0, 1.0]);
}
}
#[test]
fn a_negative_decimal_can_be_typed_across_frames() {
let (mut h, id) = harness(false);
focus_x(&mut h, 0);
for part in ["-", ".", "5"] {
type_text(&mut h, part);
}
h.key_press(Key::Enter);
h.step();
h.run_steps(4);
assert_eq!(pair(&h, id, "offset"), [-0.5, 0.0]);
assert_eq!(pair(&h, id, "scale"), [1.0, 1.0]);
}
#[test]
fn clicking_the_canvas_and_switching_nodes_keep_the_right_values() {
let (mut h, id) = harness(false);
focus_x(&mut h, 1);
type_text(&mut h, "4");
let pos = h.state().graph.view.left_top() + vec2(20.0, 20.0);
h.event(Event::PointerMoved(pos));
h.step();
for pressed in [true, false] {
h.event(Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
h.step();
}
h.run_steps(4);
assert!(h.state().session.selection.is_empty());
assert_eq!(pair(&h, id, "scale"), [4.0, 1.0]);
h.state_mut().run("graph.select", json!({"ids": [id.0]})).unwrap();
h.run_steps(4);
focus_x(&mut h, 1);
type_text(&mut h, "5");
let other = NodeId(h.state_mut().run("graph.node.add", json!({"def":"transformation","at":[300,0]})).unwrap()["id"].as_u64().unwrap());
h.run_steps(4);
h.key_press(Key::Enter);
h.step();
assert_eq!(pair(&h, id, "scale"), [5.0, 1.0]);
assert_eq!(pair(&h, other, "scale"), [1.0, 1.0], "an edit leaked into the newly selected node");
}
#[test]
fn invalid_input_is_ignored_and_values_are_clamped() {
let (mut h, id) = harness(false);
focus_x(&mut h, 0);
type_text(&mut h, "NaN");
h.key_press(Key::Enter);
h.step();
h.run_steps(4);
assert_eq!(pair(&h, id, "offset"), [0.0, 0.0]);
focus_x(&mut h, 0);
type_text(&mut h, "123");
h.key_press(Key::Enter);
h.step();
h.run_steps(4);
assert_eq!(pair(&h, id, "offset"), [1.0, 0.0]);
focus_x(&mut h, 0);
type_text(&mut h, "-");
h.key_press(Key::Escape);
h.step();
h.run_steps(4);
assert_eq!(pair(&h, id, "offset"), [1.0, 0.0]);
}
#[test]
fn integer_input_and_slider_track_both_update_the_node() {
let (mut h, id) = harness(false);
let input = By::new().role(egui::accesskit::Role::TextInput).label("Random seed");
h.get(input).click();
h.step();
h.key_press_modifiers(Modifiers::COMMAND, Key::A);
h.step();
type_text(&mut h, "42");
h.key_press(Key::Enter);
h.step();
h.run_steps(4);
assert_eq!(h.state().session.graph().unwrap().node(id).unwrap().base.seed, 42);
let pos = h.get(By::new().role(egui::accesskit::Role::Slider).label("Random seed")).rect().center();
h.event(Event::PointerMoved(pos));
h.step();
for pressed in [true, false] {
h.event(Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
h.step();
}
h.run_steps(4);
assert_eq!(h.state().session.graph().unwrap().node(id).unwrap().base.seed, 500);
}
#[test]
#[ignore = "requires an offscreen GPU"]
fn exact_scale_screenshot() {
let (mut h, id) = harness(true);
focus_x(&mut h, 1);
type_text(&mut h, "4");
h.key_press(Key::Enter);
h.step();
h.run_steps(8);
assert_eq!(pair(&h, id, "scale"), [4.0, 1.0]);
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();
h.render().unwrap().save(dir.join("scale-x-4.png")).unwrap();
}
@@ -0,0 +1,91 @@
//! Node cards distinguish editing previews from configured graph resolution.
use egui::{Event, epaint::Shape, vec2};
use egui_kittest::Harness;
use materialcraft_engine::core::NodeId;
use materialcraft_ui_egui::{MaterialCraftApp, UiState};
use serde_json::json;
fn harness(preview: u32, render: bool) -> (Harness<'static, MaterialCraftApp>, NodeId) {
let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default());
app.ui.prefs.preview_size = preview;
app.ui.graph_camera.zoom = 1.0;
let id = NodeId(app.run("graph.node.add", json!({"def":"uniform"})).unwrap()["id"].as_u64().unwrap());
app.apply_prefs();
app.session.cook();
let builder = Harness::builder().with_size(vec2(1600.0, 960.0)).with_step_dt(1.0 / 60.0);
let builder = if render { builder.wgpu() } else { builder };
let mut h = builder.build_ui_state(
|ui, app: &mut MaterialCraftApp| {
app.step(&ui.ctx().clone());
app.draw(ui);
},
app,
);
h.run_steps(10);
(h, id)
}
fn texts(shape: &Shape, out: &mut Vec<String>) {
match shape {
Shape::Text(t) => out.push(t.galley.text().to_owned()),
Shape::Vec(shapes) => {
for s in shapes {
texts(s, out);
}
}
_ => {}
}
}
fn painted(h: &Harness<'static, MaterialCraftApp>) -> Vec<String> {
let mut out = Vec::new();
for s in &h.output().shapes {
texts(&s.shape, &mut out);
}
out
}
#[test]
fn node_resolution_explains_the_preview_cap() {
let (mut h, id) = harness(512, false);
let img = &h.state().session.cooked.nodes[&id].outputs[0];
assert_eq!((img.w, img.h), (512, 512));
assert_eq!(h.state().session.graph().unwrap().size, [10, 10]);
assert!(painted(&h).iter().any(|t| t == "512x512 Preview"), "missing preview label: {:?}", painted(&h));
let rect = h.state().graph.rects.iter().find(|(n, _)| *n == id).unwrap().1;
h.event(Event::PointerMoved(rect.center()));
h.run_steps(90);
let text = painted(&h).join("\n");
assert!(text.contains("Parent size: 1024 x 1024"), "{text}");
assert!(text.contains("Preview limit: 512 px"), "{text}");
assert!(text.contains("Edit > Preferences"), "{text}");
assert!(text.contains("16bpc"), "format information lost: {text}");
let full = h.state().session.cook_full(0);
let img = &full.nodes[&id].outputs[0];
assert_eq!((img.w, img.h), (1024, 1024));
}
#[test]
fn full_size_mode_retains_the_resolution_and_format() {
let (h, id) = harness(0, false);
let img = &h.state().session.cooked.nodes[&id].outputs[0];
assert_eq!((img.w, img.h), (1024, 1024));
assert!(painted(&h).iter().any(|t| t == "1024x1024 - C16"), "{:?}", painted(&h));
assert!(!painted(&h).iter().any(|t| t == "1024x1024 Preview"));
}
#[test]
#[ignore = "requires an offscreen GPU"]
fn preview_resolution_screenshots() {
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 (preview, name) in [(512, "preview"), (0, "full-size")] {
let (mut h, id) = harness(preview, true);
h.render().unwrap().save(dir.join(format!("{name}.png"))).unwrap();
if preview > 0 {
let rect = h.state().graph.rects.iter().find(|(n, _)| *n == id).unwrap().1;
h.event(Event::PointerMoved(rect.center()));
h.run_steps(90);
h.render().unwrap().save(dir.join("preview-tooltip.png")).unwrap();
}
}
}
@@ -0,0 +1,89 @@
//! Pointer drags should reach nearby round values, as standard egui sliders do.
use egui::{Event, Modifiers, PointerButton, pos2, vec2};
use egui_kittest::{
Harness,
kittest::{By, Queryable},
};
use materialcraft_engine::core::{NodeId, Value};
use materialcraft_ui_egui::{MaterialCraftApp, UiState};
use serde_json::json;
fn harness(ppp: f32, render: bool) -> (Harness<'static, MaterialCraftApp>, NodeId) {
let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default());
let id = NodeId(app.run("graph.node.add", json!({"def":"transformation"})).unwrap()["id"].as_u64().unwrap());
app.session.reset_history();
let builder = Harness::builder().with_size(vec2(1600.0, 960.0)).with_pixels_per_point(ppp).with_step_dt(1.0 / 60.0);
let builder = if render { builder.wgpu() } else { builder };
let mut h = builder.build_ui_state(
|ui, app: &mut MaterialCraftApp| {
app.step(&ui.ctx().clone());
app.draw(ui);
},
app,
);
h.run_steps(8);
(h, id)
}
fn drag_near(h: &mut Harness<'static, MaterialCraftApp>, label: &str, index: usize, value: f32, lo: f32, hi: f32) {
let rect = h.get_all(By::new().role(egui::accesskit::Role::Slider).label(label)).nth(index).unwrap().rect();
let start = pos2(rect.left() + rect.width() * 0.2, rect.center().y);
// Aim slightly off the exact value, within one physical pixel.
let target = pos2(rect.left() + 5.0 + (rect.width() - 10.0) * (value - lo) / (hi - lo) + 0.4 / h.ctx.pixels_per_point(), rect.center().y);
h.event(Event::PointerMoved(start));
h.step();
h.event(Event::PointerButton { pos: start, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
h.step();
h.event(Event::PointerMoved(start + vec2(10.0, 0.0)));
h.step();
h.event(Event::PointerMoved(target));
h.step();
h.event(Event::PointerButton { pos: target, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
h.step();
h.run_steps(3);
}
fn rotation(h: &Harness<'static, MaterialCraftApp>, id: NodeId) -> f32 {
match h.state().session.graph().unwrap().node(id).unwrap().params.get("rotation") {
Some(Value::Float(v)) => *v,
None => 0.0,
other => panic!("unexpected rotation {other:?}"),
}
}
#[test]
fn dragging_can_reach_exact_round_angles_at_multiple_pixel_scales() {
for ppp in [1.0, 2.0] {
for angle in [90.0, -90.0, 0.0, 360.0, -360.0] {
let (mut h, id) = harness(ppp, false);
drag_near(&mut h, "Rotation", 0, angle, -360.0, 360.0);
assert_eq!(rotation(&h, id), angle / 360.0, "angle={angle}, pixels_per_point={ppp}");
if angle == 90.0 {
h.state_mut().run("edit.undo", json!({})).unwrap();
assert_eq!(rotation(&h, id), 0.0);
h.state_mut().run("edit.redo", json!({})).unwrap();
assert_eq!(rotation(&h, id), 0.25);
}
}
}
}
#[test]
fn fractional_parameter_values_remain_reachable() {
let (mut h, id) = harness(1.0, false);
drag_near(&mut h, "X", 1, 1.5, 0.01, 10.0);
drag_near(&mut h, "X", 0, -0.5, -1.0, 1.0);
let n = h.state().session.graph().unwrap().node(id).unwrap();
assert_eq!(n.params.get("scale"), Some(&Value::Float2([1.5, 1.0])));
assert_eq!(n.params.get("offset"), Some(&Value::Float2([-0.5, 0.0])));
}
#[test]
#[ignore = "requires an offscreen GPU"]
fn exact_angle_screenshot() {
let (mut h, id) = harness(1.0, true);
drag_near(&mut h, "Rotation", 0, 90.0, -360.0, 360.0);
assert_eq!(rotation(&h, id), 0.25);
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();
h.render().unwrap().save(dir.join("rotation-90.png")).unwrap();
}
+29 -1
View File
@@ -5,7 +5,10 @@
use std::time::Duration;
use egui::vec2;
use egui_kittest::{Harness, kittest::Queryable};
use egui_kittest::{
Harness,
kittest::{By, Queryable},
};
use materialcraft_ui_egui::{MaterialCraftApp, UiState};
use serde_json::json;
@@ -33,6 +36,27 @@ 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"]
@@ -78,6 +102,10 @@ fn snapshots() {
h.state_mut().run("view.2d", json!({"node": 16, "histogram": true}));
settle(&mut h, 30);
save(&mut h, &dir, "workspace");
h.state_mut().run("view.3d", json!({"heightScale": 0.2}));
settle(&mut h, 60);
save(&mut h, &dir, "height-relief");
h.state_mut().run("view.3d", json!({"heightScale": 0.04}));
for (tpl, name) in
[("wood", "wood"), ("rusty_metal", "rusty-metal"), ("stone_tiles", "stone-tiles"), ("fabric", "fabric"), ("ground", "ground"), ("lava", "lava")]
{
+1 -1
View File
@@ -23,7 +23,7 @@ L2 formats .sbs packages (the main format, sbs.rs), .mcraft packages (zip: pa
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
L3 render the 3D view: BVH ray casts, the height output displacing a subdivided mesh, GGX PBR with
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
+20 -7
View File
@@ -1,17 +1,26 @@
# Control protocol and MCP
> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-02 · **Change:** minor (portable materials for TextureCraft) · **Target:** the professional node-based material workflow
> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-03 · **Change:** minor (`material_export` MCP tool) · **Target:** the professional node-based material workflow
Agents drive MaterialCraft three ways, all dispatching the same engine commands:
1. **MCP** (`materialcraft-cli mcp`): headless (an in-process session, files only below
`--read-root` / `--write-root`) or bridged to the running app (`--bridge <port>`).
`--read-root` / `--write-root`, also spelled `--automation-read-root` /
`--automation-write-root` as in the other crafting apps; `serve` takes them too) or bridged to the running app (`--bridge <port>`).
2. **JSON lines** (`materialcraft-cli serve`): the same methods on stdio, or on `127.0.0.1:<port>`
behind a token.
3. **The app's control channel** (`materialcraft --control <port>`): one JSON request per line,
`{"id", "method", "params"}` → `{"id", "ok": true, "result"}` or `{"id", "ok": false, "error"}`.
The first request must be `{"method":"auth","params":{"token":"…"}}` with the token from
`MATERIALCRAFT_CONTROL_TOKEN` or the file `<temp>/materialcraft-control-<port>.token`.
`MATERIALCRAFT_CONTROL_TOKEN` (16 to 1024 printable ASCII characters) or the file
`<temp>/materialcraft-control-<port>.token`, a fresh random 256-bit token written after the port
is bound. On Unix the file is created new with mode 0600 (owner only); if an existing file there
cannot be replaced, the control server stays off and `MATERIALCRAFT_CONTROL_TOKEN` is the
alternative. Clients (`materialcraft-cli mcp --bridge`) refuse a token file that is a symlink,
not a regular file, not owned by them, or accessible to group or others. A connection gets one
authentication attempt, within 10 s; a wrong token, any other first request or malformed JSON
closes it. At most 16 connections are served at once. Whoever holds the token has full
engine-command authority, including host file access.
Set `MATERIALCRAFT_NO_PREFS=1` for scripted runs so the user's layout is left alone.
## Methods
@@ -25,7 +34,8 @@ 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 |
| `material.export {path, graph?, size?, values?}` | headless | cook and write a portable `.mcmat` (`.mcmat` appended when missing) below the write root: the workspace-scoped `file.exportMaterial` |
| `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 |
@@ -70,7 +80,7 @@ Types: `move`, `down`, `up`, `click`, `doubleClick`, `drag`, `scroll`, `key` (eg
| `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, `transparency` (see through where the alpha is below one: the opacity output, else the base color's alpha), `alphaView` (show the alpha channel) |
| `view.2d` / `view.3d` | which node the 2D view shows, channel, tiling, histogram; scene, environment, camera, tiling, `heightScale` (how far the height output raises the mesh, in mesh radii) and `heightLevel` (the height that stays on the surface; 0 = the relief rises out of it), `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 |
@@ -125,6 +135,9 @@ each has its own reader and writer (`crates/formats/src/material.rs` here), so k
`session_inspect`, `command_list`, `command_run`, `command_batch`, `library_list`, `graph_new`,
`node_add`, `node_connect`, `node_param`, `package_open`, `package_save`, `bitmap_import`,
`outputs_export`, `view_render` (headless) and, bridged to the app, `view_screenshot`,
`outputs_export`, `material_export`, `view_render` (headless) and, bridged to the app, `view_screenshot`,
`ui_screenshot`, `ui_inspect`, `ui_menu_invoke`, `ui_input`. `package_open` opens `.mcmat` files
too; exporting one is CLI-only for now (the workspace sandbox refuses `file.*` commands).
too, and `material_export` `{path, graph?, size?, values?}` writes one below `--write-root` (`path` is
relative, the parent folder must exist, `values` are exposed input values). The workspace sandbox
still refuses `file.*` commands, so a sandboxed agent exports through the tool, not `file.exportMaterial`;
mesh-map `inputs` stay a CLI feature.
+1 -1
View File
@@ -7,7 +7,7 @@ Every known shortfall, most important first. Pick from the top.
| # | Gap | Evidence | Impact | Estimate | Parity doc |
|---:|---|---|---|---:|---|
| 1 | Node library breadth | 227 nodes vs. ~400 in the reference library | Recipes that need scan processing, more grunges, splines or SDF shapes | 30 h | target-app-parity (Node library) |
| 2 | GPU 3D view with tessellation and lights | CPU renderer with parallax only | Displacement previews, light setups | 12 h | target-app-parity (3D view) |
| 2 | GPU 3D view with tessellation and lights | CPU renderer; the height output displaces a subdivided mesh (up to 500k triangles) | GPU tessellation, light setups | 12 h | target-app-parity (3D view) |
| 3 | Mesh-based generators and bakers | None | Workflows that start from a mesh | 15 h | target-app-parity (Node library) |
| 4 | Portable materials over MCP | `.mcmat` export runs from the app and the CLI; the MCP workspace sandbox refuses `file.*` commands and has no `material_export` tool | Sandboxed agents can't hand a material to TextureCraft | 1 h | target-app-parity (Files) |
| 5 | Function loops and reusable functions | Functions live on one parameter or processor | Iterative effects; sharing logic between nodes | 5 h | target-app-parity (Function graphs) |
+1 -1
View File
@@ -14,7 +14,7 @@ automation + tests), weighted by how much of the day each area carries. **Remain
| 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; 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 |
| 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 (real displacement of a subdivided mesh, rising out of the surface), 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 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 |
+1 -1
View File
@@ -106,7 +106,7 @@ Where the alpha is below one, the surface lets light through: each camera ray co
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.
cut-out sphere shows its inside. Every layer is the mesh as the height output displaced it.
**Display ▸ Transparency (alpha)** turns this off, so the alpha is ignored and the mesh is opaque.
It is on by default.