Function graph editor, home screen, browser file I/O, accessible names

A visual editor for pixel and value processor functions (operations by
category, wiring, inline values, result node), opened from Properties or by
double-clicking the processor. A home screen with rendered sample materials and
recent packages. Open, save, import and export in the browser (file picker and
downloads), and file drops on every platform. Every custom widget now carries
an accessible name and role; the offscreen snapshot test enforces it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
bflatasticandClaude Opus 5.5 committed 2026-11-02 04:24:17 +07:00
1 parent 54fc5b9571
commit 0b688a3e9c
17 files changed
+865 -71

No files matched your search

Submodule .claude/worktrees/agent-a5ada44eb1cf7ccfb added at 54fc5b9571.
Generated
+5
View File
@@ -2386,12 +2386,17 @@ dependencies = [
"egui-phosphor",
"egui_kittest",
"image",
"js-sys",
"log",
"materialcraft-engine",
"materialcraft-render",
"rfd",
"serde",
"serde_json",
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
"zip",
]
[[package]]
+9
View File
@@ -20,12 +20,21 @@ serde_json = { workspace = true }
log = { workspace = true }
base64 = "0.22"
image = { workspace = true }
zip = { workspace = true }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
rfd = { workspace = true }
# Floating panels open as OS windows.
craft-ui = { workspace = true, features = ["native-windows"] }
# Browser file I/O (web_files.rs): async pickers and Blob downloads.
[target.'cfg(target_arch = "wasm32")'.dependencies]
rfd = { workspace = true }
wasm-bindgen = "0.2"
wasm-bindgen-futures = "0.4"
js-sys = "0.3"
web-sys = { version = "0.3", features = ["Window", "Document", "HtmlElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "CssStyleDeclaration"] }
# winit needs a window system on Linux, so the crate's own tests build with X11.
[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies]
eframe = { workspace = true, features = ["x11"] }
+1
View File
@@ -37,6 +37,7 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
for (i, g) in app.session.pkg.graphs.iter().enumerate() {
let on = i == app.session.graph;
let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click());
crate::widgets::name(&resp, egui::Role::TreeItem, &g.name);
if on {
ui.painter().rect_filled(r, 4.0, tk.row_selected);
ui.painter().rect_stroke(r, 4.0, egui::Stroke::new(1.0, tk.accent), egui::StrokeKind::Inside);
+429
View File
@@ -0,0 +1,429 @@
//! The function graph editor: a window with a small node canvas for a pixel or value
//! processor's function. Right-click (or Space) adds operations by category, dragging from an
//! output to an input wires them, the starred node is the result. Each change commits the whole
//! function through `graph.node.param`.
use egui::{Align2, Color32, FontId, Pos2, Rect, Sense, Stroke, StrokeKind, Ui, Vec2, pos2, vec2};
use egui_phosphor::regular as icon;
use materialcraft_engine::core::NodeId;
use materialcraft_engine::core::Value;
use materialcraft_engine::core::function::{FnGraph, FnNode};
use materialcraft_engine::nodes::function::FN_OPS;
use serde_json::json;
use crate::MaterialCraftApp;
use crate::i18n::tr;
use crate::theme::Tokens;
const W: f32 = 130.0;
const HEADER: f32 = 18.0;
const ROW: f32 = 18.0;
/// The open editor: which node's parameter, and the canvas camera.
pub struct FnEditor {
pub node: NodeId,
pub param: String,
pan: Vec2,
zoom: f32,
drag: Option<FnDrag>,
menu_at: Pos2,
/// The camera has been fitted to the nodes.
framed: bool,
}
enum FnDrag {
Node(u32, Vec2),
Wire(u32),
Pan,
}
impl FnEditor {
pub fn new(node: NodeId, param: &str) -> FnEditor {
FnEditor { node, param: param.into(), pan: vec2(-40.0, -40.0), zoom: 1.0, drag: None, menu_at: Pos2::ZERO, framed: false }
}
}
fn arity(op: &str) -> usize {
FN_OPS.iter().find(|o| o.0 == op).map_or(0, |o| o.2)
}
fn label(op: &str) -> &'static str {
FN_OPS.iter().find(|o| o.0 == op).map_or("?", |o| o.1)
}
fn category_color(op: &str) -> Color32 {
match FN_OPS.iter().find(|o| o.0 == op).map_or("", |o| o.3) {
"Constant" => Color32::from_rgb(0x5c, 0x62, 0x6e),
"Variables" => Color32::from_rgb(0x6d, 0x52, 0xb5),
"Samplers" => Color32::from_rgb(0xa8, 0x3c, 0x34),
"Vector" | "Cast" => Color32::from_rgb(0x3a, 0x66, 0xb0),
"Operator" => Color32::from_rgb(0x3b, 0x7f, 0x4c),
"Logical" | "Comparison" | "Control" => Color32::from_rgb(0xb3, 0x5a, 0x2c),
_ => Color32::from_rgb(0x1e, 0x8a, 0xa0),
}
}
/// The value a new node of `op` starts with.
fn default_value(op: &str) -> Option<Value> {
Some(match op {
"const_float" => Value::Float(0.5),
"const_float2" => Value::Float2([0.5, 0.5]),
"const_float3" => Value::Float3([0.5, 0.5, 0.5]),
"const_float4" => Value::Float4([0.5, 0.5, 0.5, 1.0]),
"const_int" => Value::Int(1),
"const_bool" => Value::Bool(true),
"get_var" => Value::Text(String::new()),
"sample_gray" | "sample_color" => Value::Int(0),
"swizzle" => Value::Text("x".into()),
_ => return None,
})
}
fn node_rect(n: &FnNode) -> Rect {
let rows = arity(&n.op).max(1) as f32 + if n.value.is_some() { 1.0 } else { 0.0 };
Rect::from_min_size(pos2(n.pos[0], n.pos[1]), vec2(W, HEADER + rows * ROW + 6.0))
}
fn in_port(r: Rect, i: usize) -> Pos2 {
pos2(r.left(), r.top() + HEADER + ROW * (i as f32 + 0.5))
}
fn out_port(r: Rect) -> Pos2 {
pos2(r.right(), r.top() + HEADER + ROW * 0.5)
}
/// The function currently stored on the node.
fn current(app: &MaterialCraftApp, e: &FnEditor) -> Option<FnGraph> {
let n = app.session.graph().ok()?.node(e.node).ok()?;
match n.params.get(&e.param) {
Some(Value::Function(f)) => Some((**f).clone()),
_ => materialcraft_engine::nodes::find(&n.def)?.param(&e.param).and_then(|p| match &p.default {
Value::Function(f) => Some((**f).clone()),
_ => None,
}),
}
}
fn commit(app: &mut MaterialCraftApp, node: NodeId, param: &str, g: &FnGraph) {
let v = serde_json::to_value(Value::Function(Box::new(g.clone()))).unwrap_or(serde_json::Value::Null);
app.run("graph.node.param", json!({"id": node.0, "param": param, "value": v}));
}
/// Draw the editor window when one is open.
pub fn show(app: &mut MaterialCraftApp, ctx: &egui::Context) {
let Some(mut e) = app.fn_editor.take() else { return };
let Some(mut g) = current(app, &e) else { return };
let title = app.session.graph().ok().and_then(|gr| gr.node(e.node).ok()).map(crate::graph_view::node_label).unwrap_or_default();
let mut open = true;
let mut changed = false;
egui::Window::new(format!("{} - {}", title, tr("Function graph")))
.id(egui::Id::unique(("fn-editor", e.node.0, e.param.as_str())))
.open(&mut open)
.default_size(vec2(760.0, 460.0))
.resizable(true)
.show(ctx, |ui| {
let tk = Tokens::get(ui.ctx());
ui.horizontal(|ui| {
ui.label(
egui::RichText::new(tr("Right-click or Space to add operations; drag from an output dot to an input; the starred node is the result."))
.size(11.0)
.color(tk.text_dim),
);
});
changed = canvas(&mut e, &mut g, ui);
});
if changed {
commit(app, e.node, &e.param, &g);
}
if open {
app.fn_editor = Some(e);
}
}
fn canvas(e: &mut FnEditor, g: &mut FnGraph, ui: &mut Ui) -> bool {
let tk = Tokens::get(ui.ctx());
let (rect, resp) = ui.allocate_exact_size(ui.available_size().max(vec2(200.0, 200.0)), Sense::click_and_drag());
crate::widgets::name(&resp, egui::Role::Canvas, "Function graph");
let p = ui.painter_at(rect);
p.rect_filled(rect, 4.0, Color32::from_rgb(0x26, 0x28, 0x2c));
if !e.framed {
e.framed = true;
let b = g.nodes.iter().map(node_rect).fold(Rect::NOTHING, |a, r| a.union(r));
if b.is_finite() && b.width() > 0.0 {
let b = b.expand(30.0);
e.zoom = (rect.width() / b.width()).min(rect.height() / b.height()).clamp(0.3, 1.2);
e.pan = b.center().to_vec2() - rect.size() * 0.5 / e.zoom;
}
}
let to_s = |q: Pos2, e: &FnEditor| rect.min + (q.to_vec2() - e.pan) * e.zoom;
let to_g = |s: Pos2, e: &FnEditor| ((s - rect.min) / e.zoom + e.pan).to_pos2();
let mut changed = false;
let pointer = ui.input(|i| i.pointer.hover_pos());
// Zoom and pan.
if resp.hovered() {
let scroll = ui.input(|i| i.smooth_scroll_delta.y);
if scroll.abs() > 0.0
&& let Some(ptr) = pointer
{
let before = to_g(ptr, e);
e.zoom = (e.zoom * (scroll * 0.0025).exp()).clamp(0.3, 2.5);
e.pan = before.to_vec2() - (ptr - rect.min) / e.zoom;
}
}
// Wires.
for n in &g.nodes {
let r = node_rect(n);
for (i, src) in n.inputs.iter().enumerate() {
if let Some(s) = src.and_then(|s| g.node(s)) {
let a = to_s(out_port(node_rect(s)), e);
let b = to_s(in_port(r, i), e);
let dx = ((b.x - a.x).abs() * 0.5).max(24.0);
p.add(egui::epaint::CubicBezierShape::from_points_stroke(
[a, a + vec2(dx, 0.0), b - vec2(dx, 0.0), b],
false,
Color32::TRANSPARENT,
Stroke::new(2.0, Color32::from_gray(0xb4)),
));
}
}
}
// Nodes.
let font = FontId::proportional((11.0 * e.zoom).clamp(7.0, 16.0));
let mut remove: Option<u32> = None;
let mut set_output: Option<u32> = None;
let mut ports: Vec<(u32, Option<usize>, Pos2)> = Vec::new();
let ids: Vec<u32> = g.nodes.iter().map(|n| n.id).collect();
for id in ids {
let Some(idx) = g.nodes.iter().position(|n| n.id == id) else { continue };
let mut r = node_rect(&g.nodes[idx]);
if let Some(FnDrag::Node(d, delta)) = &e.drag
&& *d == id
{
r = r.translate(*delta);
}
let sr = Rect::from_min_max(to_s(r.min, e), to_s(r.max, e));
let n = &g.nodes[idx];
let is_out = g.output == Some(id);
p.rect_filled(sr, 5.0, Color32::from_rgb(0x1e, 0x20, 0x24));
let header = Rect::from_min_size(sr.min, vec2(sr.width(), HEADER * e.zoom));
p.rect_filled(header, egui::CornerRadius { nw: 5, ne: 5, sw: 0, se: 0 }, category_color(&n.op));
let star = if is_out { format!("{} ", icon::STAR) } else { String::new() };
p.text(header.left_center() + vec2(5.0, 0.0), Align2::LEFT_CENTER, format!("{star}{}", label(&n.op)), font.clone(), Color32::WHITE);
p.rect_stroke(sr, 5.0, Stroke::new(if is_out { 2.0 } else { 1.0 }, if is_out { tk.accent } else { Color32::from_gray(0x10) }), StrokeKind::Outside);
for i in 0..arity(&n.op) {
let pos = to_s(in_port(r, i), e);
p.circle(pos, 4.5, Color32::from_gray(0xc8), Stroke::new(1.0, Color32::from_gray(0x18)));
ports.push((id, Some(i), pos));
}
let op = to_s(out_port(r), e);
p.circle(op, 4.5, Color32::from_rgb(0xe8, 0xa9, 0x3c), Stroke::new(1.0, Color32::from_gray(0x18)));
ports.push((id, None, op));
// Inline value editor.
if n.value.is_some() {
let row = Rect::from_min_size(
to_s(pos2(r.left() + 6.0, r.top() + HEADER + arity(&n.op).max(1) as f32 * ROW + 2.0), e),
vec2((W - 12.0) * e.zoom, (ROW - 2.0) * e.zoom),
);
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(row));
if let Some(v) = g.nodes[idx].value.as_mut() {
changed |= value_editor(&mut child, v);
}
}
let body = ui.interact(sr, ui.scope_id().with(("fn-node", id)), Sense::click_and_drag());
crate::widgets::name(&body, egui::Role::Button, label(&g.nodes[idx].op));
if body.drag_started() && e.drag.is_none() {
e.drag = Some(FnDrag::Node(id, Vec2::ZERO));
}
body.context_menu(|ui| {
if ui.button(format!("{} {}", icon::STAR, tr("Use as result"))).clicked() {
set_output = Some(id);
ui.close();
}
if ui.button(format!("{} {}", icon::X, tr("Delete"))).clicked() {
remove = Some(id);
ui.close();
}
});
}
if let Some(id) = set_output {
g.output = Some(id);
changed = true;
}
if let Some(id) = remove {
g.nodes.retain(|n| n.id != id);
for n in &mut g.nodes {
for i in &mut n.inputs {
if *i == Some(id) {
*i = None;
}
}
}
if g.output == Some(id) {
g.output = None;
}
changed = true;
}
// Gestures: wires from output dots, panning.
let near = |ptr: Pos2| ports.iter().filter(|(_, _, q)| q.distance(ptr) < 9.0).min_by(|a, b| a.2.distance(ptr).total_cmp(&b.2.distance(ptr))).cloned();
if resp.drag_started_by(egui::PointerButton::Middle) || (resp.drag_started() && ui.input(|i| i.modifiers.alt)) {
e.drag = Some(FnDrag::Pan);
} else if ui.input(|i| i.pointer.primary_pressed())
&& e.drag.is_none()
&& let Some(ptr) = pointer
&& rect.contains(ptr)
&& let Some((id, None, _)) = near(ptr)
{
e.drag = Some(FnDrag::Wire(id));
}
let delta = ui.input(|i| i.pointer.delta());
match &mut e.drag {
Some(FnDrag::Node(_, d)) => *d += delta / e.zoom,
Some(FnDrag::Pan) => e.pan -= delta / e.zoom,
Some(FnDrag::Wire(id)) => {
if let (Some(ptr), Some(src)) = (pointer, ports.iter().find(|(n, s, _)| n == id && s.is_none())) {
p.line_segment([src.2, ptr], Stroke::new(2.0, tk.accent));
}
}
None => {}
}
if ui.input(|i| i.pointer.any_released()) {
match e.drag.take() {
Some(FnDrag::Node(id, d)) => {
if let Some(n) = g.nodes.iter_mut().find(|n| n.id == id)
&& d.length() > 0.5
{
n.pos = [n.pos[0] + d.x, n.pos[1] + d.y];
changed = true;
}
}
Some(FnDrag::Wire(src)) => {
if let Some(ptr) = pointer
&& let Some((dst, Some(slot), _)) = near(ptr)
&& dst != src
&& !reaches(g, dst, src)
&& let Some(n) = g.nodes.iter_mut().find(|n| n.id == dst)
{
if n.inputs.len() <= slot {
n.inputs.resize(slot + 1, None);
}
n.inputs[slot] = Some(src);
changed = true;
}
}
_ => {}
}
}
// Adding operations.
if resp.secondary_clicked()
&& let Some(ptr) = pointer
{
e.menu_at = to_g(ptr, e);
}
if resp.hovered()
&& ui.input(|i| i.key_pressed(egui::Key::Space))
&& let Some(ptr) = pointer
{
e.menu_at = to_g(ptr, e);
egui::Popup::open_id(ui.ctx(), resp.id.with("menu"));
}
let at = e.menu_at;
let mut add: Option<&'static str> = None;
resp.context_menu(|ui| {
let mut cats: Vec<&str> = FN_OPS.iter().map(|o| o.3).collect();
cats.dedup();
for c in cats {
ui.menu_button(tr(c), |ui| {
for o in FN_OPS.iter().filter(|o| o.3 == c) {
if ui.button(tr(o.1)).clicked() {
add = Some(o.0);
ui.close();
}
}
});
}
});
if let Some(op) = add {
let id = g.nodes.iter().map(|n| n.id + 1).max().unwrap_or(1);
g.nodes.push(FnNode { id, op: op.into(), inputs: vec![None; arity(op)], value: default_value(op), pos: [at.x, at.y] });
if g.output.is_none() {
g.output = Some(id);
}
changed = true;
}
changed
}
/// Whether `a` feeds `b` (directly or through other nodes, or is `b`): then `b` may not feed `a`.
fn reaches(g: &FnGraph, a: u32, b: u32) -> bool {
let mut stack = vec![b];
let mut seen = std::collections::BTreeSet::new();
while let Some(n) = stack.pop() {
if n == a {
return true;
}
if !seen.insert(n) {
continue;
}
if let Some(node) = g.node(n) {
stack.extend(node.inputs.iter().flatten());
}
}
false
}
/// A compact editor for a function node's value. Returns true when it changed.
fn value_editor(ui: &mut Ui, v: &mut Value) -> bool {
let drag = |ui: &mut Ui, f: &mut f32| ui.add(egui::DragValue::new(f).speed(0.01).max_decimals(3)).changed();
ui.horizontal(|ui| match v {
Value::Float(f) => drag(ui, f),
Value::Float2(a) => {
let x = drag(ui, &mut a[0]);
drag(ui, &mut a[1]) || x
}
Value::Float3(a) => {
let mut c = false;
for f in a.iter_mut() {
c |= drag(ui, f);
}
c
}
Value::Float4(a) | Value::Color(a) => {
let mut c = false;
for f in a.iter_mut() {
c |= ui.add(egui::DragValue::new(f).speed(0.01).max_decimals(2)).changed();
}
c
}
Value::Int(i) => ui.add(egui::DragValue::new(i).speed(0.1)).changed(),
Value::Bool(b) => ui.checkbox(b, "").changed(),
Value::Text(t) => {
let r = ui.add(egui::TextEdit::singleline(t).desired_width(ui.available_width()));
crate::widgets::name(&r, egui::Role::TextInput, "Value");
r.changed()
}
_ => false,
})
.inner
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn cycles_are_detected() {
let mut g = FnGraph::default();
let a = g.add("get_pos", &[], None);
let b = g.add("swizzle", &[a], Some(Value::Text("x".into())));
// a feeds b: wiring b into a would loop.
assert!(reaches(&g, a, b));
assert!(!reaches(&g, b, a));
assert_eq!(arity("add"), 2);
assert!(default_value("const_float").is_some());
}
}
+9 -1
View File
@@ -259,11 +259,12 @@ fn parent_size(app: &mut MaterialCraftApp, ui: &mut Ui) {
let mut nw = w;
let mut nh = h;
let combo = |ui: &mut Ui, id: &str, v: &mut u32| {
egui::ComboBox::from_id_salt(id).width(64.0).selected_text(format!("{}", 1u32 << *v)).show_ui(ui, |ui| {
let r = egui::ComboBox::from_id_salt(id).width(64.0).selected_text(format!("{}", 1u32 << *v)).show_ui(ui, |ui| {
for l in 4..=13u32 {
ui.selectable_value(v, l, format!("{}", 1u32 << l));
}
});
crate::widgets::name(&r.response, egui::Role::ComboBox, if id == "parent-w" { "Parent width" } else { "Parent height" });
};
combo(ui, "parent-h", &mut nh);
ui.label("x");
@@ -325,6 +326,7 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) {
let tk = Tokens::get(ui.ctx());
let ctx = ui.ctx().clone();
let (rect, resp) = ui.allocate_exact_size(ui.available_size(), Sense::click_and_drag());
crate::widgets::name(&resp, egui::Role::Canvas, "Node graph");
app.graph.view = rect;
if app.ui.frame_all || app.graph.framed_graph != Some(app.session.graph) {
app.ui.frame_all = false;
@@ -484,6 +486,7 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) {
let result = cooked.nodes.get(&n.id);
let error = result.and_then(|r| r.error.clone());
let resp = ui.interact(sr, ui.scope_id().with(("node", n.id.0)), Sense::click_and_drag());
crate::widgets::name(&resp, egui::Role::Button, &node_label(n));
if n.def == "dot" {
painter.circle(
sr.center(),
@@ -809,6 +812,10 @@ fn handle_input(
Some((d, Some(Value::Text(name)))) if d == "graph_instance" => {
app.run("graph.open", json!({"graph": name}));
}
Some((d, _)) if d == "pixel_processor" || d == "value_processor" => {
app.run("view.2d", json!({"node": id.0, "port": 0}));
app.fn_editor = Some(crate::function_editor::FnEditor::new(*id, "function"));
}
_ => {
app.run("view.2d", json!({"node": id.0, "port": 0}));
}
@@ -904,6 +911,7 @@ fn search_popup(app: &mut MaterialCraftApp, ui: &mut Ui, cam: &Cam) {
ui.horizontal(|ui| {
ui.label(egui::RichText::new(icon::MAGNIFYING_GLASS).color(tk.text_dim));
let r = ui.add(egui::TextEdit::singleline(&mut s.text).hint_text(tr("Search nodes...")).desired_width(220.0));
crate::widgets::name(&r, egui::Role::SearchInput, "Search nodes");
if s.focus {
r.request_focus();
s.focus = false;
+11 -1
View File
@@ -11,6 +11,7 @@ pub mod control;
pub mod cook;
pub mod docking;
pub mod explorer;
pub mod function_editor;
pub mod graph_view;
pub mod i18n;
pub mod library;
@@ -22,6 +23,7 @@ pub mod thumbs;
pub mod toolbar;
pub mod view2d;
pub mod view3d;
pub mod web_files;
pub mod widgets;
pub mod windows;
@@ -52,6 +54,8 @@ pub struct MaterialCraftApp {
pub graph: graph_view::GraphView,
pub view3d: view3d::View3dState,
pub view2d: view2d::View2dState,
/// The function graph editor window, when open.
pub fn_editor: Option<function_editor::FnEditor>,
/// Synthetic input from the control channel, fed to egui on the next frames.
pub input_queue: VecDeque<control::Scripted>,
pub fps: f32,
@@ -73,6 +77,7 @@ impl MaterialCraftApp {
theme::install(&cc.egui_ctx);
let mut app = MaterialCraftApp::headless(session, ui);
app.fonts_ready = true;
app.ui.windows.home = app.ui.prefs.show_home;
app
}
@@ -92,6 +97,7 @@ impl MaterialCraftApp {
graph: graph_view::GraphView::default(),
view3d: view3d::View3dState::default(),
view2d: view2d::View2dState::default(),
fn_editor: None,
input_queue: VecDeque::new(),
fps: 0.0,
ui_ms: 0.0,
@@ -209,7 +215,10 @@ impl MaterialCraftApp {
ctx.set_zoom_factor(scale);
}
control::poll(self, ctx);
windows::poll_files(self);
web_files::poll(self);
for f in ctx.input(|i| i.raw.dropped_files.clone()) {
web_files::dropped(self, ctx, &f);
}
self.apply_prefs();
cook::drive(self, ctx);
#[cfg(not(target_arch = "wasm32"))]
@@ -234,6 +243,7 @@ impl MaterialCraftApp {
toolbar::status_bar(self, ui);
egui::CentralPanel::default().frame(egui::Frame::NONE.fill(theme::Tokens::get(&ctx).chrome)).show(ui, |ui| docking::show(self, ui));
windows::show(self, &ctx);
function_editor::show(self, &ctx);
toasts(self, &ctx);
let dt = (now_ms() - t0) as f32;
self.ui_ms = if self.ui_ms == 0.0 { dt } else { self.ui_ms * 0.9 + dt * 0.1 };
+4 -1
View File
@@ -42,7 +42,8 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
let tk = Tokens::get(ui.ctx());
ui.horizontal(|ui| {
ui.label(RichText::new(icon::MAGNIFYING_GLASS).color(tk.text_dim));
ui.add(egui::TextEdit::singleline(&mut app.ui.library_search).hint_text(tr("Search")).desired_width((ui.available_width() - 56.0).max(40.0)));
let r = ui.add(egui::TextEdit::singleline(&mut app.ui.library_search).hint_text(tr("Search")).desired_width((ui.available_width() - 56.0).max(40.0)));
crate::widgets::name(&r, egui::Role::SearchInput, "Search the library");
if crate::widgets::icon_button(ui, icon::SQUARES_FOUR, tr("Icons"), !app.ui.prefs.library_list, 20.0).clicked() {
app.ui.prefs.library_list = false;
}
@@ -70,6 +71,7 @@ fn category_tree(app: &mut MaterialCraftApp, ui: &mut Ui) {
let mut row = |ui: &mut Ui, text: String, path: &str, indent: f32| {
let on = app.ui.library_category == path;
let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 20.0), Sense::click());
crate::widgets::name(&resp, egui::Role::TreeItem, &text);
if on {
ui.painter().rect_filled(r, 4.0, tk.row_selected);
} else if resp.hovered() {
@@ -142,6 +144,7 @@ fn items(app: &mut MaterialCraftApp, ui: &mut Ui) {
for (id, label, cat, is_graph) in chunk {
let size = if as_list { vec2(ui.available_width(), 26.0) } else { tile };
let (r, resp) = ui.allocate_exact_size(size, Sense::click_and_drag());
crate::widgets::name(&resp, egui::Role::ListItem, label);
let def_id = if *is_graph { "graph_instance" } else { id.as_str() };
if resp.hovered() {
ui.painter().rect_filled(r, 6.0, tk.row_hover);
+1 -1
View File
@@ -140,7 +140,7 @@ pub fn invoke(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) {
"ui.help.docs" => ctx.open_url(egui::OpenUrl::new_tab("https://github.com/storytold/materialcraft#readme")),
"ui.help.bug" => ctx.open_url(egui::OpenUrl::new_tab("https://github.com/storytold/materialcraft/issues")),
_ => {
if crate::windows::file_action(app, id) {
if crate::windows::file_action(app, ctx, id) {
return;
}
app.run(id, Value::Null);
+11 -2
View File
@@ -24,6 +24,7 @@ fn section(ui: &mut Ui, id: &str, title: &str, body: impl FnOnce(&mut Ui)) {
let id = ui.make_persistent_id(id);
let mut state = egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, true);
let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 20.0), Sense::click());
crate::widgets::name(&resp, egui::Role::Button, title);
ui.painter().rect_filled(r, 3.0, tk.row);
let chev = if state.is_open() { icon::CARET_DOWN } else { icon::CARET_RIGHT };
ui.painter().text(r.left_center() + vec2(6.0, 0.0), egui::Align2::LEFT_CENTER, chev, egui::FontId::proportional(10.0), tk.text_dim);
@@ -57,7 +58,9 @@ fn node_props(app: &mut MaterialCraftApp, ui: &mut Ui, n: &materialcraft_engine:
ui.painter().rect_filled(Rect::from_min_size(ui.cursor().min + vec2(0.0, 2.0), vec2(4.0, 16.0)), 1.0, crate::graph_view::header_color(&n.def));
ui.add_space(8.0);
let mut label = if n.label.is_empty() { crate::graph_view::node_label(n) } else { n.label.clone() };
if ui.add(egui::TextEdit::singleline(&mut label).desired_width(ui.available_width() - 4.0).font(egui::TextStyle::Heading)).changed() {
let r = ui.add(egui::TextEdit::singleline(&mut label).desired_width(ui.available_width() - 4.0).font(egui::TextStyle::Heading));
crate::widgets::name(&r, egui::Role::TextInput, "Node label");
if r.changed() {
app.run("graph.node.rename", json!({"id": n.id.0, "label": label}));
}
});
@@ -292,7 +295,9 @@ fn param_row(app: &mut MaterialCraftApp, ui: &mut Ui, node: NodeId, p: &ParamDef
ui.horizontal(|ui| {
ui.label(RichText::new(tr(p.label)).color(tk.text));
let mut s = t.clone();
if ui.add(egui::TextEdit::singleline(&mut s).desired_width(ui.available_width())).changed() {
let r = ui.add(egui::TextEdit::singleline(&mut s).desired_width(ui.available_width()));
crate::widgets::name(&r, egui::Role::TextInput, p.label);
if r.changed() {
set(app, node, p.id, json!(s));
}
});
@@ -358,6 +363,7 @@ fn graph_props(app: &mut MaterialCraftApp, ui: &mut Ui) {
ui.label(tr("Name"));
let mut name = g.name.clone();
let r = ui.add(egui::TextEdit::singleline(&mut name).desired_width(ui.available_width()));
crate::widgets::name(&r, egui::Role::TextInput, "Graph name");
if r.lost_focus() && name != g.name {
app.run("graph.rename", json!({"name": name}));
}
@@ -393,6 +399,7 @@ fn graph_props(app: &mut MaterialCraftApp, ui: &mut Ui) {
ui.label(tr(label));
let mut s = cur.clone();
let r = ui.add(egui::TextEdit::singleline(&mut s).desired_width(ui.available_width()));
crate::widgets::name(&r, egui::Role::TextInput, label);
if r.lost_focus() && s != *cur {
app.run("graph.attributes", json!({key: s}));
}
@@ -475,6 +482,7 @@ pub fn curve_editor(ui: &mut Ui, id: &str, c: &Curve) -> Option<Curve> {
let tk = Tokens::get(ui.ctx());
let w = ui.available_width().min(240.0);
let (rect, resp) = ui.allocate_exact_size(vec2(w, w * 0.75), Sense::click_and_drag());
crate::widgets::name(&resp, egui::Role::Canvas, "Curve editor");
let p = ui.painter_at(rect);
p.rect_filled(rect, 4.0, tk.field);
for i in 1..4 {
@@ -553,6 +561,7 @@ pub fn gradient_editor(ui: &mut Ui, id: &str, g: &Gradient) -> Option<Gradient>
let tk = Tokens::get(ui.ctx());
let w = ui.available_width().min(260.0);
let (rect, resp) = ui.allocate_exact_size(vec2(w, 30.0), Sense::click_and_drag());
crate::widgets::name(&resp, egui::Role::Canvas, "Gradient editor");
let p = ui.painter_at(rect.expand(6.0));
let bar = Rect::from_min_size(rect.min, vec2(w, 18.0));
let n = 64;
+3
View File
@@ -20,6 +20,8 @@ pub struct Prefs {
pub thumbnails: bool,
/// Library tiles: large icons or a list.
pub library_list: bool,
/// Open the home screen when the app starts.
pub show_home: bool,
}
impl Default for Prefs {
@@ -32,6 +34,7 @@ impl Default for Prefs {
autosave_minutes: 5,
thumbnails: true,
library_list: false,
show_home: true,
}
}
}
+3 -1
View File
@@ -66,7 +66,8 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
});
});
let Some((id, img)) = app.session.view2d_image().map(|(id, i)| (id, i.clone())) else {
let (r, _) = ui.allocate_exact_size(ui.available_size(), Sense::hover());
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(),
@@ -89,6 +90,7 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
}
let avail = ui.available_size();
let (rect, resp) = ui.allocate_exact_size(vec2(avail.x, (avail.y - 20.0).max(40.0)), Sense::click_and_drag());
crate::widgets::name(&resp, egui::Role::Image, "2D view");
let p = ui.painter_at(rect);
p.rect_filled(rect, 0.0, tk.viewport);
// Camera: fit, wheel zoom around the pointer, drag to pan.
+3 -1
View File
@@ -94,6 +94,7 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
menus(app, ui);
let avail = ui.available_size();
let (rect, resp) = ui.allocate_exact_size(vec2(avail.x, (avail.y - 22.0).max(40.0)), Sense::click_and_drag());
crate::widgets::name(&resp, egui::Role::Image, "3D view");
// Camera gestures.
let mut moving = false;
if resp.dragged() {
@@ -148,13 +149,14 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
ui.horizontal_centered(|ui| {
ui.add_space(6.0);
ui.label(egui::RichText::new(icon::SPHERE).color(tk.text_dim));
egui::ComboBox::from_id_salt("scene3d").width(110.0).selected_text(scene_label(app)).show_ui(ui, |ui| {
let r = egui::ComboBox::from_id_salt("scene3d").width(110.0).selected_text(scene_label(app)).show_ui(ui, |ui| {
for (id, label) in SCENES {
if ui.selectable_label(app.session.view3d.scene == *id, tr(label)).clicked() {
app.run("view.3d", json!({"scene": id}));
}
}
});
crate::widgets::name(&r.response, egui::Role::ComboBox, "Scene");
ui.label(egui::RichText::new(format!("{} sRGB / ACES", icon::SUN)).size(11.0).color(tk.text_dim));
});
});
+213
View File
@@ -0,0 +1,213 @@
//! Files in the browser: File ▸ Open and Import bitmap use the browser's file picker (the bytes
//! arrive on a later frame through [`poll`]); Save and Export outputs are downloads. The desktop
//! uses native dialogs and the path-based engine commands instead (`windows::file_action`).
use std::sync::{Mutex, PoisonError};
use crate::MaterialCraftApp;
use crate::i18n::tr;
/// What a picked file is for.
#[derive(Clone, Copy, PartialEq)]
#[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
enum Pick {
Package,
Bitmap,
}
/// Files picked in the browser, waiting for the next frame: (file name, bytes, purpose).
static INBOX: Mutex<Vec<(String, Vec<u8>, Pick)>> = Mutex::new(Vec::new());
/// Load files that arrived since the last frame. Call once per frame.
pub fn poll(app: &mut MaterialCraftApp) {
let picked = std::mem::take(&mut *INBOX.lock().unwrap_or_else(PoisonError::into_inner));
for (name, bytes, pick) in picked {
load(app, &name, bytes, pick == Pick::Bitmap);
}
}
/// Open a package or import an image (by extension unless `bitmap` forces an image).
pub fn load(app: &mut MaterialCraftApp, name: &str, bytes: Vec<u8>, bitmap: bool) {
let ext = name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()).unwrap_or_default();
if bitmap || materialcraft_engine::formats::IMAGE_EXTENSIONS.contains(&ext.as_str()) {
match materialcraft_engine::file_cmds::add_resource(&mut app.session, name, bytes, None) {
Ok(res) => {
crate::graph_view::add_node_near_selection(app, "bitmap");
if let Some(id) = app.session.selection.last().copied() {
app.run("graph.node.param", serde_json::json!({"id": id.0, "param": "resource", "value": res}));
}
app.toast(format!("{} {res}", tr("Imported")), false);
}
Err(e) => app.toast(format!("{} {name}: {e}", tr("Couldn't import")), true),
}
return;
}
match materialcraft_engine::file_cmds::open_bytes(&mut app.session, &bytes, Some(name.to_string())) {
Ok(()) => {
app.ui.frame_all = true;
app.toast(format!("{} {name}", tr("Opened")), false);
}
Err(e) => app.toast(format!("{} {name}: {e}", tr("Couldn't open")), true),
}
}
/// A file dropped on the window: a package opens, an image becomes a Bitmap node (in the
/// browser the bytes arrive on a later frame).
pub fn dropped(app: &mut MaterialCraftApp, ctx: &egui::Context, file: &egui::DroppedFileHandle) {
let name = file.path().file_name().and_then(|n| n.to_str()).unwrap_or("dropped").to_string();
#[cfg(not(target_arch = "wasm32"))]
{
let _ = ctx;
match file.bytes() {
Ok(bytes) => {
let package = name.to_ascii_lowercase().ends_with(".mcraft");
load(app, &name, bytes, false);
if package {
let path = file.path().display().to_string();
app.session.path = Some(path.clone());
app.ui.add_recent(&path);
}
}
Err(e) => app.toast(format!("{} {name}: {e}", tr("Couldn't open")), true),
}
}
#[cfg(target_arch = "wasm32")]
{
let _ = app;
let (file, ctx) = (file.clone(), ctx.clone());
wasm_bindgen_futures::spawn_local(async move {
match file.bytes_async().await {
Ok(bytes) => INBOX.lock().unwrap_or_else(PoisonError::into_inner).push((name, bytes, Pick::Package)),
Err(e) => log::warn!("couldn't read dropped file {name}: {e}"),
}
ctx.request_repaint();
});
}
}
/// A zip of `(name, bytes)` files (export downloads several maps at once).
pub fn zip_files(files: &[(String, Vec<u8>)]) -> Result<Vec<u8>, String> {
use std::io::Write as _;
let mut buf = std::io::Cursor::new(Vec::new());
{
let mut z = zip::ZipWriter::new(&mut buf);
let opts = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
for (name, bytes) in files {
z.start_file(name.as_str(), opts).map_err(|e| e.to_string())?;
z.write_all(bytes).map_err(|e| e.to_string())?;
}
z.finish().map_err(|e| e.to_string())?;
}
Ok(buf.into_inner())
}
#[cfg(target_arch = "wasm32")]
pub use web::*;
#[cfg(target_arch = "wasm32")]
mod web {
use std::sync::PoisonError;
use wasm_bindgen::JsCast as _;
use super::{INBOX, Pick, zip_files};
use crate::MaterialCraftApp;
use crate::i18n::tr;
fn pick(ctx: &egui::Context, filter: &'static str, exts: &'static [&'static str], kind: Pick) {
let ctx = ctx.clone();
wasm_bindgen_futures::spawn_local(async move {
if let Some(file) = rfd::AsyncFileDialog::new().add_filter(filter, exts).pick_file().await {
let bytes = file.read().await;
INBOX.lock().unwrap_or_else(PoisonError::into_inner).push((file.file_name(), bytes, kind));
}
ctx.request_repaint();
});
}
/// File ▸ Open: a package, picked in the browser.
pub fn open(ctx: &egui::Context) {
pick(ctx, "MaterialCraft package", &["mcraft"], Pick::Package);
}
/// File ▸ Import bitmap.
pub fn import_bitmap(ctx: &egui::Context) {
pick(ctx, "Images", materialcraft_engine::formats::IMAGE_EXTENSIONS, Pick::Bitmap);
}
/// File ▸ Save: download the package as `<name>.mcraft`.
pub fn save(app: &mut MaterialCraftApp) {
let name = format!("{}.mcraft", materialcraft_engine::formats::safe_file_name(&app.session.pkg.name));
match materialcraft_engine::file_cmds::save_bytes(&app.session).map_err(|e| e.to_string()).and_then(|b| download(&name, &b)) {
Ok(()) => {
app.session.modified = false;
app.toast(format!("{} {name}", tr("Downloaded")), false);
}
Err(e) => app.toast(format!("{} {name}: {e}", tr("Couldn't save")), true),
}
}
/// 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))
.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();
match files.as_slice() {
[(name, bytes)] => download(name, bytes).map(|()| name.clone()),
_ => {
let name = format!("{}_outputs.zip", app.session.graph().map(|g| g.name.clone()).unwrap_or_default());
download(&name, &zip_files(&files)?).map(|()| name)
}
}
});
match result {
Ok(name) => app.toast(format!("{} {name}", tr("Downloaded")), false),
Err(e) => app.toast(format!("{}: {e}", tr("Couldn't export")), true),
}
}
/// Start a browser download of `bytes` named `name` (Blob + a temporary `<a download>`).
pub fn download(name: &str, bytes: &[u8]) -> Result<(), String> {
let js = |e: wasm_bindgen::JsValue| format!("{e:?}");
let window = web_sys::window().ok_or("no window")?;
let document = window.document().ok_or("no document")?;
let parts = js_sys::Array::of1(&js_sys::Uint8Array::from(bytes));
let opts = web_sys::BlobPropertyBag::new();
opts.set_type(if name.ends_with(".zip") { "application/zip" } else { "application/octet-stream" });
let blob = web_sys::Blob::new_with_u8_array_sequence_and_options(&parts, &opts).map_err(js)?;
let url = web_sys::Url::create_object_url_with_blob(&blob).map_err(js)?;
let a: web_sys::HtmlAnchorElement = document.create_element("a").map_err(js)?.dyn_into().map_err(|_| "not an anchor")?;
a.set_href(&url);
a.set_download(name);
a.style().set_property("display", "none").map_err(js)?;
document.body().ok_or("no body")?.append_child(&a).map_err(js)?;
a.click();
a.remove();
// Revoke once the click has been dispatched; the download keeps its own reference.
let revoke = wasm_bindgen::closure::Closure::once_into_js(move || {
web_sys::Url::revoke_object_url(&url).ok();
});
window.set_timeout_with_callback_and_timeout_and_arguments_0(revoke.unchecked_ref(), 10_000).map_err(js)?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn zip_round_trips() {
let files = vec![("a.png".to_string(), b"one".to_vec()), ("b.png".to_string(), vec![7u8; 4096])];
let bytes = zip_files(&files).unwrap();
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
assert_eq!(zip.len(), 2);
for (name, data) in &files {
let mut out = Vec::new();
std::io::Read::read_to_end(&mut zip.by_name(name).unwrap(), &mut out).unwrap();
assert_eq!(&out, data);
}
}
}
+15 -1
View File
@@ -6,6 +6,12 @@ use egui::{Color32, CornerRadius, Response, RichText, Sense, Stroke, Ui, vec2};
use crate::theme::Tokens;
/// Give a custom widget an accessible name and role (screen readers, AccessKit, tests).
pub fn name(resp: &Response, role: egui::Role, label: &str) {
let label = label.to_string();
resp.widget_info(move || egui::WidgetInfo::labeled(role, true, label.clone()));
}
/// The drag-and-drop payload of type `T` released on `resp` this frame. Unlike
/// [`Response::dnd_release_payload`] (which clears a payload of any type), it leaves payloads
/// of other types for the next drop target.
@@ -24,6 +30,7 @@ pub fn slider(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeI
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));
name(&r, egui::Role::TextInput, label);
if r.lost_focus()
&& let Ok(v) = text.trim().parse::<f32>()
&& v.is_finite()
@@ -33,6 +40,8 @@ pub fn slider(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeI
});
});
let (rect, mut resp) = ui.allocate_exact_size(vec2(w, 14.0), Sense::click_and_drag());
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()
{
@@ -53,6 +62,8 @@ pub fn bar_slider(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::Ra
let tk = Tokens::get(ui.ctx());
let (lo, hi) = (*range.start(), *range.end());
let (rect, mut resp) = ui.allocate_exact_size(vec2(width, 28.0), Sense::click_and_drag());
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()
{
@@ -123,11 +134,12 @@ pub fn primary_button<'a>(ui: &Ui, text: &str) -> egui::Button<'a> {
pub fn combo(ui: &mut Ui, label: &str, selected: impl Into<egui::WidgetText>, menu: impl FnOnce(&mut Ui)) {
ui.horizontal(|ui| {
ui.label(label);
egui::ComboBox::from_id_salt(label)
let r = egui::ComboBox::from_id_salt(label)
.width(ui.available_width().max(60.0))
.wrap_mode(egui::TextWrapMode::Truncate)
.selected_text(selected)
.show_ui(ui, menu);
name(&r.response, egui::Role::ComboBox, label);
});
}
@@ -159,6 +171,7 @@ pub fn chip(ui: &mut Ui, text: &str, on: bool) -> Response {
let galley = ui.painter().layout_no_wrap(text.into(), egui::FontId::proportional(11.0), tk.text);
let size = vec2(galley.size().x + 14.0, 20.0);
let (rect, resp) = ui.allocate_exact_size(size, Sense::click());
name(&resp, egui::Role::Button, text);
let p = ui.painter();
let fill = if on {
tk.tool_active
@@ -179,6 +192,7 @@ pub fn color_swatch(ui: &mut Ui, id: &str, linear: &mut [f32; 3], width: f32) ->
let srgb = linear.map(|v| (materialcraft_engine::image::linear_to_srgb(v) * 255.0 + 0.5) as u8);
let mut c = Color32::from_rgb(srgb[0], srgb[1], srgb[2]);
let (rect, resp) = ui.allocate_exact_size(vec2(width, 18.0), Sense::click());
name(&resp, egui::Role::ColorWell, id);
ui.painter().rect(rect, 4.0, c, Stroke::new(1.0, tk.field_border), egui::StrokeKind::Inside);
let popup = ui.make_persistent_id(id);
if resp.clicked() {
+122 -61
View File
@@ -123,6 +123,7 @@ fn new_graph(app: &mut MaterialCraftApp, ctx: &egui::Context) {
for (id, label) in row {
let on = app.ui.new_graph_template == *id;
let (r, resp) = ui.allocate_exact_size(vec2(94.0, 124.0), egui::Sense::click());
crate::widgets::name(&resp, egui::Role::ListItem, label);
if on {
ui.painter().rect_filled(r, 6.0, tk.row_selected);
ui.painter().rect_stroke(r, 6.0, egui::Stroke::new(1.5, tk.accent), egui::StrokeKind::Inside);
@@ -158,11 +159,12 @@ fn new_graph(app: &mut MaterialCraftApp, ctx: &egui::Context) {
ui.text_edit_singleline(&mut app.ui.new_graph_name);
ui.add_space(8.0);
ui.label(RichText::new(tr("Size")).strong());
egui::ComboBox::from_id_salt("new-size").selected_text(format!("{} px", app.ui.new_graph_size)).show_ui(ui, |ui| {
let r = egui::ComboBox::from_id_salt("new-size").selected_text(format!("{} px", app.ui.new_graph_size)).show_ui(ui, |ui| {
for s in [256u32, 512, 1024, 2048, 4096] {
ui.selectable_value(&mut app.ui.new_graph_size, s, format!("{s} px"));
}
});
crate::widgets::name(&r.response, egui::Role::ComboBox, "Size");
ui.add_space(8.0);
ui.label(RichText::new(tr("Create graph in")).strong());
ui.label(&app.session.pkg.name);
@@ -197,9 +199,11 @@ fn export(app: &mut MaterialCraftApp, ctx: &egui::Context) {
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());
#[cfg(not(target_arch = "wasm32"))]
ui.horizontal(|ui| {
ui.label(tr("Folder"));
ui.add(egui::TextEdit::singleline(&mut app.ui.export_dir).desired_width(280.0));
let r = ui.add(egui::TextEdit::singleline(&mut app.ui.export_dir).desired_width(280.0));
crate::widgets::name(&r, egui::Role::TextInput, "Folder");
#[cfg(not(target_arch = "wasm32"))]
if ui.button(icon::FOLDER_OPEN).clicked()
&& let Some(d) = rfd::FileDialog::new().pick_folder()
@@ -225,7 +229,8 @@ fn export(app: &mut MaterialCraftApp, ctx: &egui::Context) {
});
ui.horizontal(|ui| {
ui.label(tr("File names"));
ui.add(egui::TextEdit::singleline(&mut app.ui.export_pattern).desired_width(260.0));
let r = ui.add(egui::TextEdit::singleline(&mut app.ui.export_pattern).desired_width(260.0));
crate::widgets::name(&r, egui::Role::TextInput, "File names");
});
ui.label(RichText::new("$(graph) $(identifier) $(usage)").size(10.5).color(tk.text_dim));
ui.add_space(8.0);
@@ -239,11 +244,17 @@ fn export(app: &mut MaterialCraftApp, ctx: &egui::Context) {
});
});
if go {
if app.ui.export_dir.trim().is_empty() {
if app.ui.export_dir.trim().is_empty() && !cfg!(target_arch = "wasm32") {
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});
#[cfg(target_arch = "wasm32")]
{
crate::web_files::export(app, &p);
open = false;
}
#[cfg(not(target_arch = "wasm32"))]
if let Some(r) = app.run("file.export", p) {
let n = r["files"].as_array().map_or(0, Vec::len);
app.toast(format!("{} {n} {}", tr("Exported"), tr("files")), false);
@@ -348,36 +359,84 @@ fn shortcuts(app: &mut MaterialCraftApp, ctx: &egui::Context) {
fn home(app: &mut MaterialCraftApp, ctx: &egui::Context) {
let mut open = true;
modal(ctx, "home", tr("Welcome to MaterialCraft"), &mut open, vec2(520.0, 340.0), |ui| {
let mut create: Option<(&str, &str)> = None;
modal(ctx, "home", tr("Home"), &mut open, vec2(760.0, 470.0), |ui| {
let tk = Tokens::get(ui.ctx());
ui.label(
RichText::new(tr("Build materials from noises, patterns and filters, see them live in 2D and 3D, and export the maps for any engine."))
.color(tk.text),
);
ui.add_space(8.0);
ui.horizontal(|ui| {
if ui.add(crate::widgets::primary_button(ui, tr("New graph"))).clicked() {
app.ui.windows.home = false;
app.ui.windows.new_graph = true;
}
if ui.button(tr("Open package...")).clicked() {
app.ui.windows.home = false;
crate::menus::invoke(app, ui.ctx(), "file.open");
}
ui.horizontal_top(|ui| {
// Left rail: actions and links.
ui.vertical(|ui| {
ui.set_width(150.0);
if ui.add(crate::widgets::primary_button(ui, tr("New graph"))).clicked() {
app.ui.windows.home = false;
app.ui.windows.new_graph = true;
}
ui.add_space(4.0);
if ui.button(format!("{} {}", icon::FOLDER_OPEN, tr("Open package..."))).clicked() {
app.ui.windows.home = false;
crate::menus::invoke(app, ui.ctx(), "file.open");
}
ui.add_space(16.0);
ui.hyperlink_to(tr("Documentation"), "https://github.com/storytold/materialcraft#readme");
ui.hyperlink_to(tr("Community (Discord)"), "https://discord.gg/artcraft");
ui.hyperlink_to("getartcraft.com", "https://getartcraft.com/apps/materialcraft");
ui.add_space(16.0);
ui.checkbox(&mut app.ui.prefs.show_home, tr("Show at startup"));
});
ui.separator();
ui.vertical(|ui| {
ui.label(RichText::new(tr("Welcome to MaterialCraft")).size(18.0).strong().color(tk.text_strong));
ui.label(
RichText::new(tr(
"Build tileable materials from noises, patterns and filters, see them live in 2D and 3D, and export the maps for any engine.",
))
.color(tk.text_dim),
);
ui.add_space(8.0);
ui.label(RichText::new(tr("Samples")).strong());
ui.horizontal_wrapped(|ui| {
for (id, label) in materialcraft_engine::samples::TEMPLATES.iter().filter(|(id, _)| !matches!(*id, "empty" | "pbr")) {
let (r, resp) = ui.allocate_exact_size(vec2(92.0, 116.0), egui::Sense::click());
crate::widgets::name(&resp, egui::Role::ListItem, label);
if resp.hovered() {
ui.painter().rect_filled(r, 6.0, tk.row_hover);
}
let img = egui::Rect::from_min_size(r.min + vec2(6.0, 4.0), vec2(80.0, 80.0));
match TEMPLATES.with(|t| t.borrow_mut().get(ui.ctx(), id)) {
Some(t) => {
ui.painter().image(t, img, egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)), Color32::WHITE);
}
None => {
ui.painter().circle_filled(img.center(), 36.0, tk.row);
}
}
let g = ui.painter().layout(tr(label).to_string(), egui::FontId::proportional(11.0), tk.text, 90.0);
ui.painter().galley(egui::pos2(r.center().x - g.size().x * 0.5, img.bottom() + 6.0), g, tk.text);
if resp.clicked() {
create = Some((id, label));
}
}
});
ui.add_space(8.0);
ui.label(RichText::new(tr("Recent")).strong());
if app.ui.recent.is_empty() {
ui.label(RichText::new(tr("No recent packages")).color(tk.text_dim));
}
#[cfg(not(target_arch = "wasm32"))]
for p in app.ui.recent.clone().into_iter().take(6) {
if ui.link(&p).clicked() {
open_path(app, &p);
app.ui.windows.home = false;
}
}
});
});
ui.add_space(8.0);
ui.label(RichText::new(tr("Recent")).strong());
if app.ui.recent.is_empty() {
ui.label(RichText::new(tr("No recent packages")).color(tk.text_dim));
}
#[cfg(not(target_arch = "wasm32"))]
for p in app.ui.recent.clone() {
if ui.link(&p).clicked() {
open_path(app, &p);
app.ui.windows.home = false;
}
}
});
if let Some((id, label)) = create {
if app.run("file.new", json!({"template": id, "name": label.replace(' ', "_"), "size": 1024})).is_some() {
app.ui.frame_all = true;
}
open = false;
}
if !open {
app.ui.windows.home = false;
}
@@ -414,37 +473,42 @@ pub fn history(app: &mut MaterialCraftApp, ui: &mut Ui) {
});
}
/// The function parameter of a pixel/value processor: its nodes as JSON, editable.
/// The function parameter of a pixel/value processor: a button opening the function graph
/// editor, and the function as JSON for copy and paste.
pub fn function_summary(app: &mut MaterialCraftApp, ui: &mut Ui, node: NodeId, param: &str, f: &FnGraph) {
let tk = Tokens::get(ui.ctx());
let id = egui::Id::unique(("fn-edit", node.0, param));
let mut text: String = ui.data(|d| d.get_temp(id)).unwrap_or_else(|| serde_json::to_string_pretty(f).unwrap_or_default());
ui.label(
RichText::new(format!("{} {}", f.nodes.len(), tr("function nodes; ops are listed in the docs (control-protocol.md)"))).size(10.5).color(tk.text_dim),
);
let r = ui.add(egui::TextEdit::multiline(&mut text).code_editor().desired_rows(8).desired_width(f32::INFINITY));
if r.changed() {
ui.data_mut(|d| d.insert_temp(id, text.clone()));
if ui.add(crate::widgets::primary_button(ui, &format!("{} {}", icon::FLOW_ARROW, tr("Edit function graph...")))).clicked() {
app.fn_editor = Some(crate::function_editor::FnEditor::new(node, param));
}
ui.horizontal(|ui| {
if ui.button(tr("Apply")).clicked() {
match serde_json::from_str::<FnGraph>(&text) {
Ok(g) => {
let v = serde_json::to_value(materialcraft_engine::core::Value::Function(Box::new(g))).unwrap_or(Value::Null);
app.run("graph.node.param", json!({"id": node.0, "param": param, "value": v}));
ui.data_mut(|d| d.remove::<String>(id));
ui.label(RichText::new(format!("{} {}", f.nodes.len(), tr("function nodes"))).size(10.5).color(tk.text_dim));
let id = egui::Id::unique(("fn-edit", node.0, param));
egui::CollapsingHeader::new(tr("As JSON")).id_salt(("fn-json", node.0, param)).default_open(false).show(ui, |ui| {
let mut text: String = ui.data(|d| d.get_temp(id)).unwrap_or_else(|| serde_json::to_string_pretty(f).unwrap_or_default());
if ui.add(egui::TextEdit::multiline(&mut text).code_editor().desired_rows(8).desired_width(f32::INFINITY)).changed() {
ui.data_mut(|d| d.insert_temp(id, text.clone()));
}
ui.horizontal(|ui| {
if ui.button(tr("Apply")).clicked() {
match serde_json::from_str::<FnGraph>(&text) {
Ok(g) => {
let v = serde_json::to_value(materialcraft_engine::core::Value::Function(Box::new(g))).unwrap_or(Value::Null);
app.run("graph.node.param", json!({"id": node.0, "param": param, "value": v}));
ui.data_mut(|d| d.remove::<String>(id));
}
Err(e) => app.toast(format!("{}: {e}", tr("Bad function")), true),
}
Err(e) => app.toast(format!("{}: {e}", tr("Bad function")), true),
}
}
if ui.button(tr("Revert")).clicked() {
ui.data_mut(|d| d.remove::<String>(id));
}
if ui.button(tr("Revert")).clicked() {
ui.data_mut(|d| d.remove::<String>(id));
}
});
});
}
/// File menu actions that need a file dialog. Returns true when handled.
pub fn file_action(app: &mut MaterialCraftApp, id: &str) -> bool {
pub fn file_action(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) -> bool {
#[cfg(not(target_arch = "wasm32"))]
let _ = ctx;
#[cfg(not(target_arch = "wasm32"))]
{
match id {
@@ -491,12 +555,12 @@ pub fn file_action(app: &mut MaterialCraftApp, id: &str) -> bool {
#[cfg(target_arch = "wasm32")]
{
match id {
"file.open" | "file.save" | "file.saveAs" | "file.importBitmap" => {
app.toast(tr("Files in the browser are coming soon: use the desktop app or the CLI for now."), true);
true
}
_ => false,
"file.open" => crate::web_files::open(ctx),
"file.importBitmap" => crate::web_files::import_bitmap(ctx),
"file.save" | "file.saveAs" => crate::web_files::save(app),
_ => return false,
}
true
}
}
@@ -509,6 +573,3 @@ pub fn open_path(app: &mut MaterialCraftApp, path: &str) {
app.toast(format!("{} {path}", tr("Opened")), false);
}
}
/// Asynchronous file results (the browser's pickers); nothing to do on the desktop.
pub fn poll_files(_app: &mut MaterialCraftApp) {}
+25 -1
View File
@@ -10,7 +10,7 @@ use materialcraft_ui_egui::{MaterialCraftApp, UiState};
use serde_json::json;
fn harness(app: MaterialCraftApp, w: f32, h: f32) -> Harness<'static, MaterialCraftApp> {
Harness::builder().with_size(vec2(w, h)).with_pixels_per_point(1.0).with_accessibility_check(false).wgpu().build_ui_state(
Harness::builder().with_size(vec2(w, h)).with_pixels_per_point(1.0).wgpu().build_ui_state(
|ui, app: &mut MaterialCraftApp| {
app.step(&ui.ctx().clone());
app.draw(ui);
@@ -59,4 +59,28 @@ fn snapshots() {
h.state_mut().ui.windows.new_graph = true;
settle(&mut h, 40);
save(&mut h, &dir, "new-graph");
h.state_mut().ui.windows.new_graph = false;
// A pixel processor drawing rings, with its function graph open.
h.state_mut().run("file.new", json!({"template": "empty", "name": "Rings"}));
let f = json!({"t": "function", "v": {"nodes": [
{"id": 1, "op": "get_pos", "pos": [0, 0]},
{"id": 2, "op": "const_float2", "value": {"t": "float2", "v": [0.5, 0.5]}, "pos": [0, 110]},
{"id": 3, "op": "sub", "inputs": [1, 2], "pos": [170, 40]},
{"id": 4, "op": "length", "inputs": [3], "pos": [340, 40]},
{"id": 5, "op": "const_float", "value": {"t": "float", "v": 60.0}, "pos": [340, 130]},
{"id": 6, "op": "mul", "inputs": [4, 5], "pos": [510, 60]},
{"id": 7, "op": "sin", "inputs": [6], "pos": [680, 60]}
], "output": 7}});
let id = h.state_mut().run("graph.node.add", json!({"def": "pixel_processor", "at": [0, 0], "params": {"output": 1}})).unwrap()["id"].as_u64().unwrap();
h.state_mut().run("graph.node.param", json!({"id": id, "param": "function", "value": f}));
let out =
h.state_mut().run("graph.node.add", json!({"def": "output", "connectFrom": {"node": id}, "params": {"usage": 4}})).unwrap()["id"].as_u64().unwrap();
let _ = out;
h.state_mut().run("graph.select", json!({"ids": [id]}));
h.state_mut().run("view.2d", json!({"node": id}));
h.state_mut().fn_editor = Some(materialcraft_ui_egui::function_editor::FnEditor::new(materialcraft_engine::core::NodeId(id), "function"));
h.state_mut().ui.frame_all = true;
settle(&mut h, 40);
save(&mut h, &dir, "function-editor");
}