looks like it works
This commit is contained in:
PiJellyPin committed 2026-11-18 08:33:49 +01:00
1 parent 49ebd50416
commit 6be3259f6c
53 files changed
+2079 -292

No files matched your search

+1
View File
@@ -89,6 +89,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(crate::view_cmds::specs());
v.extend(crate::display_cmds::specs());
v.extend(crate::view3d_commands::specs());
v.extend(crate::save_all_commands::specs());
v.extend(crate::material_preview_commands::specs());
v.extend(crate::wire_cmds::specs());
v
+22 -10
View File
@@ -6,7 +6,7 @@ use serde_json::{Value as J, json};
use materialcraft_core::{Package, Resource, ResourceBytes};
use materialcraft_formats::{Depth, encode, output_name};
use crate::commands::{CommandSpec, always, bad, has_graph, has_package, strp, u64p};
use crate::commands::{CommandSpec, always, bad, boolp, has_graph, has_package, strp, u64p};
use crate::samples::{TEMPLATES, template};
use crate::{ExportRequest, Result, Session, cmd};
@@ -17,7 +17,7 @@ pub(crate) fn specs() -> Vec<CommandSpec> {
"Graph...",
["File", "New"],
Some("Ctrl+N"),
"{name?, folder?, kind? (material|function), template? (see graph.templates), size? (px, power of two)} adds a new graph to the package and opens it",
"{name?, folder?, kind? (material|function), template? (see graph.templates), size? (px, power of two), height? (px, power of two; default size), newPackage? (create the graph in a new package)} adds a new graph to the package and opens it",
always,
new_graph
),
@@ -69,26 +69,38 @@ fn new_graph(session: &mut Session, parameters: &J) -> Result<J> {
} else {
TEMPLATES.iter().find(|entry| entry.0 == template_id).map_or("Graph", |entry| entry.1)
};
let size = u64p(parameters, "size").unwrap_or(1024).clamp(16, 8192);
let log2 = 63 - size.leading_zeros();
let width = u64p(parameters, "size").unwrap_or(1024).clamp(16, 8192);
let height = u64p(parameters, "height").unwrap_or(width).clamp(16, 8192);
let [width_log2, height_log2] = [width, height].map(|side| 63 - side.leading_zeros());
let base = strp(parameters, "name").map(str::to_string).unwrap_or_else(|| label.replace(' ', "_"));
let folder = strp(parameters, "folder").unwrap_or("");
crate::folder_path::require(&session.pkg, folder)?;
let in_new_package = boolp(parameters, "newPackage").unwrap_or(false);
if in_new_package && !folder.is_empty() {
return Err(bad("file.new", "a new package has no folders yet: leave `folder` out"));
}
if !in_new_package {
crate::folder_path::require(&session.pkg, folder)?;
}
crate::folder_path::require_graph_folder(folder)?;
let base = crate::folder_path::name(&base)?;
let name = crate::folder_path::unique(&session.pkg, folder, base);
let mut graph = if kind == materialcraft_core::GraphKind::Function {
let mut graph = materialcraft_core::Graph::new(&name);
let mut graph = materialcraft_core::Graph::new(base);
graph.function = Some(materialcraft_core::FunctionGraph::default());
graph
} else {
template(template_id, &name, log2)?
template(template_id, base, width_log2)?
};
graph.folder = folder.into();
if !session.has_package() {
// Everything is checked before a package opens, so a refused request leaves the workspace as it was
if in_new_package || !session.has_package() {
session.open_package(Package::new("Untitled package"), None)?;
}
let name = crate::folder_path::unique(&session.pkg, folder, base);
graph.name = name.clone();
graph.size = [width_log2, height_log2];
graph.folder = folder.into();
session.edit("New graph", |session| {
session.pkg.graphs.push(graph);
session.graph = session.pkg.graphs.len() - 1;
+1
View File
@@ -42,6 +42,7 @@ mod package_file_commands;
mod preview_cook;
mod preview_fingerprint;
mod resource_commands;
mod save_all_commands;
pub use material_preview::MaterialPreview;
pub use material_source::MaterialSource;
pub use open_document::OpenDocument;
+1 -1
View File
@@ -78,7 +78,7 @@ impl Session {
/// Show a material graph on open, retaining the material while editing functions
pub(crate) fn open_material_preview(&mut self) {
if self.graph().is_ok_and(|graph| graph.function.is_none()) {
if self.view_outputs_on_open && self.graph().is_ok_and(|graph| graph.function.is_none()) {
self.material_preview = MaterialPreview::for_graph(&self.pkg, self.graph);
}
}
+49
View File
@@ -0,0 +1,49 @@
//! File ▸ Save all: write every open package that has unsaved edits to its own file
use crate::commands::{CommandSpec, has_package};
use crate::{Result, Session, cmd};
use serde_json::{Value, json};
/// Register the command that saves every modified package
pub(crate) fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"file.saveAll",
"Save all",
["File"],
None,
"{} saves every modified package that has a file; returns the saved paths, the packages that still need Save as (no file yet), and any that failed",
has_package,
save_all
)]
}
/// Save each modified package in turn, then make the package that was active the active one again
fn save_all(session: &mut Session, _parameters: &Value) -> Result<Value> {
let active = session.document_id;
let modified: Vec<(u64, String, Option<String>)> = session
.open_packages()
.into_iter()
.filter(|(_, _, _, modified)| *modified)
.map(|(id, package, path, _)| (id, package.name.clone(), path.map(str::to_string)))
.collect();
let (mut saved, mut without_file, mut failed) = (Vec::new(), Vec::new(), Vec::new());
for (id, name, path) in modified {
// A package from a library alias or with no file yet needs a name chosen in Save as
if path.as_deref().is_none_or(|path| path.contains("://")) {
without_file.push(name);
continue;
}
let result = session.activate_document(id).and_then(|()| crate::execute(session, "file.save", &json!({})));
match result {
Ok(reply) => saved.push(reply["path"].clone()),
Err(error) => failed.push(json!({"package": name, "error": error.to_string()})),
}
}
if session.document_id != active {
session.activate_document(active)?;
}
Ok(json!({"saved": saved, "withoutFile": without_file, "failed": failed}))
}
+3
View File
@@ -68,6 +68,8 @@ pub struct Session {
pub view3d: View3d,
/// The 3D view a reset goes back to, when the user saved one as the default
pub default_view3d: Option<View3d>,
/// Opening a material graph shows its outputs in the 3D view (Preferences ▸ Graph)
pub view_outputs_on_open: bool,
pub material_preview: crate::MaterialPreview,
pub(crate) cooked_graph: Option<usize>,
pub(crate) material_cooked: std::collections::BTreeMap<usize, Cooked>,
@@ -143,6 +145,7 @@ impl Session {
view2d: View2d::default(),
view3d: View3d::default(),
default_view3d: None,
view_outputs_on_open: true,
preview_size: Some(512),
camera: CameraPrefs::default(),
history_prefs: crate::HistoryPrefs::default(),
@@ -270,3 +270,16 @@ fn extracted_graph_outputs_remain_unclassified() {
let output = graph.nodes.iter().find(|node| node.def == "output").unwrap();
assert_eq!(materialcraft_engine::eval::output_usage(output), "any");
}
#[test]
fn opening_a_graph_shows_its_outputs_only_while_the_preference_is_on() {
let mut session = new_session();
let shown = session.material_preview.clone();
session.view_outputs_on_open = false;
execute(&mut session, "file.new", &json!({"template": "pbr", "name": "Quiet"})).unwrap();
assert_eq!(session.material_preview, shown, "the 3D view keeps what it showed");
session.view_outputs_on_open = true;
execute(&mut session, "file.new", &json!({"template": "pbr", "name": "Shown"})).unwrap();
assert_eq!(session.material_preview.graph, Some(session.graph));
}
+51
View File
@@ -134,3 +134,54 @@ fn saving_a_new_file_preserves_its_identity_across_path_aliases() {
}
std::fs::remove_dir_all(directory).unwrap();
}
#[test]
fn save_all_writes_every_modified_package_with_a_file_and_lists_the_rest() {
let folder = std::env::temp_dir().join(format!("materialcraft-save-all-{}", std::process::id()));
std::fs::create_dir_all(&folder).unwrap();
let first_path = folder.join("first.sbs");
let second_path = folder.join("second.sbs");
let mut session = Session::new(Package::new("First"));
execute(&mut session, "file.save", &json!({"path": first_path.to_str().unwrap()})).unwrap();
execute(&mut session, "file.new", &json!({"template": "empty"})).unwrap();
let first = session.document_id;
execute(&mut session, "file.newPackage", &json!({"name": "Second"})).unwrap();
execute(&mut session, "file.save", &json!({"path": second_path.to_str().unwrap()})).unwrap();
let unchanged = std::fs::metadata(&second_path).unwrap().modified().unwrap();
execute(&mut session, "file.newPackage", &json!({"name": "Unsaved"})).unwrap();
execute(&mut session, "graph.node.add", &json!({"def": "uniform"})).unwrap();
let active = session.document_id;
let reply = execute(&mut session, "file.saveAll", &json!({})).unwrap();
assert_eq!(reply["saved"], json!([first_path.to_str().unwrap()]));
assert_eq!(reply["withoutFile"], json!(["Unsaved"]));
assert_eq!(reply["failed"], json!([]));
assert_eq!(session.document_id, active, "the package that was active stays active");
assert!(session.open_packages().iter().any(|entry| entry.0 == first && !entry.3), "the first package is saved");
assert!(session.open_packages().iter().any(|entry| entry.0 == active && entry.3), "the package without a file keeps its edits");
assert_eq!(std::fs::metadata(&second_path).unwrap().modified().unwrap(), unchanged, "an unmodified package is not written again");
std::fs::remove_dir_all(&folder).unwrap();
}
#[test]
fn a_new_graph_can_start_its_own_package_and_take_any_size() {
let mut session = Session::new(Package::new("Existing"));
let existing = session.document_id;
let reply = execute(&mut session, "file.new", &json!({"template": "pbr", "name": "Tall", "size": 512, "height": 2048, "newPackage": true})).unwrap();
assert_eq!(reply["name"], "Tall");
assert_ne!(session.document_id, existing);
assert_eq!(session.open_packages().len(), 2);
assert_eq!(session.graph().unwrap().size, [9, 11]);
// A refused request opens nothing
assert!(execute(&mut session, "file.new", &json!({"template": "invalid", "newPackage": true})).is_err());
assert!(execute(&mut session, "file.new", &json!({"folder": "Missing", "newPackage": true})).is_err());
assert_eq!(session.open_packages().len(), 2);
}
+61
View File
@@ -0,0 +1,61 @@
//! The autosaved copies of a package: numbered files in the autosave folder, the newest kept
use std::path::{Path, PathBuf};
const EXTENSION: &str = "mcraft";
/// The file name stem of `package`'s copies, before the copy's number
fn prefix(package: &str) -> String {
format!("{}-autosave-", materialcraft_engine::formats::safe_file_name(package))
}
/// The numbers of `package`'s copies in `folder`, lowest first
fn numbers(folder: &Path, package: &str) -> Vec<u64> {
let prefix = prefix(package);
let Ok(entries) = std::fs::read_dir(folder) else { return Vec::new() };
let mut numbers: Vec<u64> = entries
.filter_map(|entry| entry.ok()?.file_name().into_string().ok())
.filter_map(|name| name.strip_prefix(&prefix)?.strip_suffix(&format!(".{EXTENSION}"))?.parse().ok())
.collect();
numbers.sort_unstable();
numbers
}
/// Where the next copy of `package` goes: one number past the newest
pub(crate) fn next_path(folder: &Path, package: &str) -> PathBuf {
let next = numbers(folder, package).last().map_or(1, |newest| newest.saturating_add(1));
folder.join(format!("{}{next}.{EXTENSION}", prefix(package)))
}
/// Delete all but the newest `keep` copies of `package`; returns how many were deleted
pub(crate) fn prune(folder: &Path, package: &str, keep: u32) -> usize {
let numbers = numbers(folder, package);
let surplus = numbers.len().saturating_sub(keep.max(1) as usize);
numbers.iter().take(surplus).filter(|number| std::fs::remove_file(folder.join(format!("{}{number}.{EXTENSION}", prefix(package)))).is_ok()).count()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn copies_are_numbered_and_only_the_newest_are_kept() {
let folder = std::env::temp_dir().join(format!("materialcraft-autosave-versions-{}", std::process::id()));
std::fs::create_dir_all(&folder).unwrap();
for _ in 0..5 {
std::fs::write(next_path(&folder, "Wood"), b"copy").unwrap();
}
std::fs::write(next_path(&folder, "Metal"), b"copy").unwrap();
assert_eq!(next_path(&folder, "Wood"), folder.join("Wood-autosave-6.mcraft"));
assert_eq!(prune(&folder, "Wood", 2), 3);
assert_eq!(numbers(&folder, "Wood"), vec![4, 5]);
assert_eq!(numbers(&folder, "Metal"), vec![1], "another package's copies stay");
assert_eq!(prune(&folder, "Wood", 0), 1, "at least one copy is always kept");
std::fs::remove_dir_all(&folder).unwrap();
}
}
+37 -9
View File
@@ -61,12 +61,43 @@ pub struct Cooker {
pub started: Option<f64>,
/// `Session::cook_epoch` when the running cook started
epoch: u64,
/// Tools ▸ Suspend engine: nothing cooks until it is resumed
pub suspended: bool,
/// Tools ▸ Cancel rendering stopped the running cook: it does not start again until the next edit
stopped_by_user: bool,
}
impl Cooker {
pub fn busy(&self) -> bool {
self.rx.is_some()
}
/// Ask the running cook to stop between nodes
fn stop(&self) {
#[cfg(not(target_arch = "wasm32"))]
if let Some(flag) = &self.cancel {
flag.store(true, std::sync::atomic::Ordering::Relaxed);
}
}
}
/// Tools ▸ Cancel rendering: stop the running cook; the next edit cooks again
pub fn cancel(app: &mut MaterialCraftApp) {
if app.cooker.busy() {
app.cooker.stop();
app.cooker.stopped_by_user = true;
}
app.session.dirty = false;
}
/// Tools ▸ Suspend engine: stop cooking until it is chosen again, then cook what changed meanwhile
pub fn toggle_suspended(app: &mut MaterialCraftApp) {
app.cooker.suspended = !app.cooker.suspended;
if app.cooker.suspended {
app.cooker.stop();
} else {
app.session.dirty = true;
}
}
/// Collect a finished cook and start the next one if the graph changed
@@ -81,11 +112,12 @@ pub fn drive(app: &mut MaterialCraftApp, ctx: &egui::Context) {
app.cooker.cancel = None;
}
match result {
// A stopped cook is partial: keep the previous results and cook again
// A stopped cook is partial: keep the previous results and cook again, unless the user stopped it
Ok(c) if c.cancelled() => {
if app.cooker.epoch == app.session.cook_epoch {
if app.cooker.epoch == app.session.cook_epoch && !app.cooker.stopped_by_user {
app.session.dirty = true;
}
app.cooker.stopped_by_user = false;
}
Ok(c) => {
if !app.session.dirty && app.cooker.epoch == app.session.cook_epoch {
@@ -98,12 +130,8 @@ pub fn drive(app: &mut MaterialCraftApp, ctx: &egui::Context) {
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);
}
// Stop between nodes and wait for this worker: rapid edits must not pile up workers
app.cooker.stop();
ctx.request_repaint_after(std::time::Duration::from_millis(16));
return;
}
@@ -124,7 +152,7 @@ pub fn drive(app: &mut MaterialCraftApp, ctx: &egui::Context) {
}
}
}
if app.session.dirty {
if app.session.dirty && !app.cooker.suspended {
start(app, ctx.input(|i| i.time));
ctx.request_repaint();
}
+6 -3
View File
@@ -120,7 +120,7 @@ pub(super) fn handle(
Some(FunctionDrag::Wire(from)) => match pointer.map(|pointer| (pointer, near(pointer))) {
Some((_, Some((to, Some(input))))) if from != to => editor.edit(app, FunctionEdit::Connect { from, to, input }, false),
// Dropped on empty canvas: search for a node that takes the wire
Some((pointer, None)) if canvas_bounds.contains(pointer) => {
Some((pointer, None)) if canvas_bounds.contains(pointer) && app.ui.prefs.wire_drop_opens_node_search => {
editor.search = Some(FunctionSearch::at(camera.to_graph(pointer), Some(SearchWire::From(from))));
}
_ => {}
@@ -128,7 +128,7 @@ pub(super) fn handle(
Some(FunctionDrag::InputWire(to, input)) => match pointer.map(|pointer| (pointer, near(pointer))) {
Some((_, Some((from, None)))) if from != to => editor.edit(app, FunctionEdit::Connect { from, to, input }, false),
// Dropped on empty canvas: search for a node whose output feeds the input
Some((pointer, None)) if canvas_bounds.contains(pointer) => {
Some((pointer, None)) if canvas_bounds.contains(pointer) && app.ui.prefs.wire_drop_opens_node_search => {
editor.search = Some(FunctionSearch::at(camera.to_graph(pointer), Some(SearchWire::To(to, input))));
}
_ => {}
@@ -189,7 +189,10 @@ pub(super) fn handle(
// Space or Tab over the canvas, or a double-click on empty canvas, searches for a node to add
// Tab moves focus between widgets, so it waits only for text fields and focus held before this frame
let space = !ui.ctx().egui_wants_keyboard_input() && ui.input(|input| input.key_pressed(egui::Key::Space));
let tab = !app.graph.keyboard_was_focused && !ui.ctx().text_edit_focused() && ui.input(|input| input.key_pressed(egui::Key::Tab));
let tab = app.ui.prefs.tab_opens_node_search
&& !app.graph.keyboard_was_focused
&& !ui.ctx().text_edit_focused()
&& ui.input(|input| input.key_pressed(egui::Key::Tab));
let keys = space || tab;
let on_node = pointer.is_some_and(|pointer| geometry.rects.iter().any(|(_, bounds)| bounds.contains(pointer)));
let double_click = response.double_clicked() && !on_wire && !on_annotation && !on_node && pointer.and_then(near).is_none();
+1 -1
View File
@@ -55,7 +55,7 @@ pub(super) fn paint(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, ui:
}
let mut camera = crate::graph::GraphCamera { origin: canvas_bounds.min, pan: editor.pan, zoom: editor.zoom };
camera.zoom_from_input(ui, canvas_bounds);
camera.zoom_from_input(ui, canvas_bounds, app.ui.prefs.zoom_direction());
editor.pan = camera.pan;
editor.zoom = camera.zoom;
+1 -1
View File
@@ -66,7 +66,7 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) {
// Background and grid
painter.rect_filled(rect, 0.0, Color32::from_rgb(0x2b, 0x2d, 0x31));
let mut camera = GraphCamera { origin: rect.min, pan: Vec2::from(app.ui.graph_camera.pan), zoom: app.ui.graph_camera.zoom };
camera.zoom_from_input(ui, rect);
camera.zoom_from_input(ui, rect, app.ui.prefs.zoom_direction());
app.ui.graph_camera = camera.state();
super::grid::paint(&painter, &camera, rect);
let pointer = context.input(|input| input.pointer.hover_pos());
+3 -2
View File
@@ -31,7 +31,8 @@ impl GraphCamera {
Self { origin: view.min, pan, zoom }
}
pub(crate) fn zoom_from_input(&mut self, ui: &Ui, view: Rect) {
/// Zoom around the pointer by the wheel or a pinch; `direction` is -1 when the preferences invert the zoom
pub(crate) fn zoom_from_input(&mut self, ui: &Ui, view: Rect, direction: f32) {
self.zoom = self.zoom.clamp(crate::state::GraphCamera::ZOOM.0, crate::state::GraphCamera::ZOOM.1);
if !ui.rect_contains_pointer(view) {
return;
@@ -39,7 +40,7 @@ impl GraphCamera {
let Some(pointer) = ui.input(|input| input.pointer.hover_pos()).filter(|pointer| view.contains(*pointer)) else { return };
let scroll = ui.input(|input| input.smooth_scroll_delta.y + input.zoom_delta().ln() * 200.0);
let scroll = direction * ui.input(|input| input.smooth_scroll_delta.y + input.zoom_delta().ln() * 200.0);
if scroll.is_finite() && scroll != 0.0 {
let before = self.to_graph(pointer);
self.zoom = (self.zoom * (scroll * 0.0025).exp()).clamp(crate::state::GraphCamera::ZOOM.0, crate::state::GraphCamera::ZOOM.1);
+17 -1
View File
@@ -146,6 +146,7 @@ pub(super) fn handle(
app.run("graph.disconnect", json!({"to": node.0, "toPort": port}));
} else if let Some(position) = pointer
&& rect.contains(position)
&& app.ui.prefs.wire_drop_opens_node_search
{
open_search(app, &context, camera.to_graph(position), Some(from));
}
@@ -158,6 +159,7 @@ pub(super) fn handle(
} else if let Some(position) = pointer
&& rect.contains(position)
&& nearest_port(&app.graph.ports, position, 12.0).is_none()
&& app.ui.prefs.wire_drop_opens_node_search
{
// Dropped on empty canvas: search for a node whose output feeds the input
open_search_to(app, &context, camera.to_graph(position), to);
@@ -275,12 +277,26 @@ pub(super) fn handle(
let hovered = pointer.is_some_and(|position| rect.contains(position));
if hovered && app.graph.search.is_none() && !crate::shell::modality::Modality::capture(app, &context).is_blocked() {
let space = !context.egui_wants_keyboard_input() && context.input(|input| input.key_pressed(egui::Key::Space));
let tab = !app.graph.keyboard_was_focused && !context.text_edit_focused() && context.input(|input| input.key_pressed(egui::Key::Tab));
let tab = app.ui.prefs.tab_opens_node_search
&& !app.graph.keyboard_was_focused
&& !context.text_edit_focused()
&& context.input(|input| input.key_pressed(egui::Key::Tab));
if (space || tab)
&& let Some(position) = pointer
{
open_search(app, &context, camera.to_graph(position), None);
}
// A node creation shortcut adds its entry under the pointer
let typing = context.egui_wants_keyboard_input();
if !typing
&& let Some(position) = pointer
&& let Some(entry) = context.input(|input| crate::node_shortcuts::pressed(&app.ui.prefs.node_shortcuts, input))
{
let under_pointer = camera.to_graph(position);
let at = [under_pointer.x - NODE_W * 0.5, under_pointer.y - 20.0];
app.run("library.add", json!({"entry": entry, "at": at, "snapToGrid": app.ui.prefs.snap_to_grid}));
}
if GraphCamera::frame_key(ui, rect) {
let selected = !app.session.selection.is_empty();
frame(app, rect, selected);
+38
View File
@@ -0,0 +1,38 @@
//! Where the Help menu's links go: the ArtCraft website, the Craft wiki and this app's repository
/// Help menu ids and the pages they open
pub(crate) const HELP_LINKS: &[(&str, &str)] = &[
("ui.help.tutorials", "https://getartcraft.com/tutorials"),
("ui.help.releaseNotes", "https://github.com/storytold/materialcraft/releases"),
("ui.help.requirements", "https://craft.wiki/apps/materialcraft/install-update/"),
("ui.help.docs", "https://craft.wiki/apps/materialcraft/overview/"),
("ui.help.automation", "https://github.com/storytold/materialcraft/blob/main/docs/control-protocol.md"),
("ui.help.troubleshooting", "https://craft.wiki/apps/materialcraft/troubleshooting/"),
("ui.help.discord", "https://discord.gg/artcraft"),
("ui.help.bug", "https://github.com/storytold/materialcraft/issues/new"),
("ui.help.feedback", "https://getartcraft.com/support"),
("ui.help.apps", "https://getartcraft.com/apps"),
("ui.help.website", "https://getartcraft.com/apps/materialcraft"),
("ui.help.news", "https://getartcraft.com/news"),
];
/// The page a Help menu id opens
pub(crate) fn url(id: &str) -> Option<&'static str> {
HELP_LINKS.iter().find(|(link, _)| *link == id).map(|(_, url)| *url)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_link_is_an_https_page_of_artcraft_or_this_repository() {
for (id, url) in HELP_LINKS {
let host = url.strip_prefix("https://").and_then(|rest| rest.split('/').next()).unwrap_or_default();
assert!(["getartcraft.com", "craft.wiki", "github.com", "discord.gg"].contains(&host), "{id}: {url}");
assert!(!url.contains("github.com") || url.contains("/storytold/materialcraft"), "{id}: {url}");
}
assert_eq!(url("ui.help.docs"), Some("https://craft.wiki/apps/materialcraft/overview/"));
assert_eq!(url("ui.about"), None);
}
}
+146
View File
@@ -0,0 +1,146 @@
//! Help ▸ Home screen, also shown at startup: start a graph from a template, open a package or a
//! recent one, and find the tutorials, documentation and community
use egui::{RichText, Ui, vec2};
use egui_phosphor::regular as icon;
use crate::MaterialCraftApp;
use crate::i18n::tr;
use crate::shell::modality::Modality;
use crate::template_card::{CARD_SIZE, TemplateCard};
use crate::theme::Tokens;
const WINDOW_SIZE: egui::Vec2 = vec2(1000.0, 620.0);
const RAIL_WIDTH: f32 = 220.0;
const CARD_GAP: f32 = 14.0;
/// The links down the left side, under their headings: (heading, [(label, Help menu id)])
const LINKS: [(&str, &[(&str, &str)]); 2] = [
("Learn", &[("Tutorials", "ui.help.tutorials"), ("Documentation", "ui.help.docs"), ("What's new", "ui.help.news")]),
("Community", &[("Community (Discord)", "ui.help.discord"), ("Report a bug", "ui.help.bug"), ("All Craft apps", "ui.help.apps")]),
];
pub(crate) fn show(app: &mut MaterialCraftApp, ctx: &egui::Context) {
let mut open = true;
crate::windows::modal(ctx, "home", tr("Home"), &mut open, WINDOW_SIZE, |ui| {
ui.set_min_size(WINDOW_SIZE);
let whole = ui.available_rect_before_wrap();
let rail = egui::Rect::from_min_max(whole.min, egui::pos2(whole.left() + RAIL_WIDTH, whole.bottom()));
let content = egui::Rect::from_min_max(egui::pos2(rail.right() + 24.0, whole.top()), whole.max);
left_rail(app, &mut ui.new_child(egui::UiBuilder::new().max_rect(rail)));
start(app, &mut ui.new_child(egui::UiBuilder::new().max_rect(content)));
ui.advance_cursor_after_rect(whole);
});
if !open {
app.ui.windows.home = false;
}
}
/// The app's name, the two ways to begin, the links and the startup switch
fn left_rail(app: &mut MaterialCraftApp, ui: &mut Ui) {
let tokens = Tokens::get(ui.ctx());
let modality = Modality::capture(app, ui.ctx());
ui.painter().rect_filled(ui.max_rect(), 6.0, tokens.row);
ui.add_space(12.0);
ui.horizontal(|ui| {
ui.add_space(12.0);
ui.vertical(|ui| {
ui.label(RichText::new("MaterialCraft").size(22.0).strong().color(tokens.accent));
ui.label(RichText::new(format!("{} {}", tr("Version"), materialcraft_engine::VERSION)).small().color(tokens.text_dim));
ui.add_space(16.0);
let width = RAIL_WIDTH - 24.0;
let new_graph = crate::widgets::primary_button(ui, &format!("{} {}", icon::FILE_PLUS, tr("New graph...")));
if ui.add_enabled_ui(!modality.is_blocked(), |ui| ui.add_sized([width, 30.0], new_graph)).inner.clicked() {
app.ui.windows.home = false;
crate::new_graph_dialog::open(app, materialcraft_engine::core::GraphKind::Material);
}
let open_package = egui::Button::new(format!("{} {}", icon::FOLDER_OPEN, tr("Open package...")));
if ui.add_enabled_ui(modality.allows("file.open"), |ui| ui.add_sized([width, 30.0], open_package)).inner.clicked() {
app.ui.windows.home = false;
crate::menus::invoke(app, ui.ctx(), "file.open");
}
for (heading, links) in LINKS {
ui.add_space(18.0);
ui.label(RichText::new(tr(heading).to_uppercase()).small().strong().color(tokens.text_dim));
for (label, id) in links {
if let Some(url) = crate::help_links::url(id) {
ui.hyperlink_to(tr(label), url);
}
}
}
});
});
let bottom = egui::Rect::from_min_max(egui::pos2(ui.max_rect().left() + 12.0, ui.max_rect().bottom() - 32.0), ui.max_rect().right_bottom());
ui.new_child(egui::UiBuilder::new().max_rect(bottom)).checkbox(&mut app.ui.prefs.show_home, tr("Show at startup"));
}
/// The welcome, the template cards and the recent packages
fn start(app: &mut MaterialCraftApp, ui: &mut Ui) {
let tokens = Tokens::get(ui.ctx());
let free = !Modality::capture(app, ui.ctx()).is_blocked();
ui.label(RichText::new(tr("Welcome to MaterialCraft")).size(20.0).strong().color(tokens.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(tokens.text_dim),
);
ui.add_space(14.0);
ui.label(RichText::new(tr("Start from a template")).size(15.0).strong());
ui.add_space(6.0);
let cards = crate::template_card::cards();
let columns = ((ui.available_width() + CARD_GAP) / (CARD_SIZE.x + CARD_GAP)).floor().max(1.0) as usize;
for row in cards.chunks(columns) {
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = CARD_GAP;
if !free {
ui.disable();
}
for card in row {
let preview = crate::windows::template_preview(ui.ctx(), card.id);
if crate::template_card::show(ui, card, false, preview).clicked() && free {
begin_with(app, card);
}
}
});
ui.add_space(CARD_GAP);
}
ui.add_space(6.0);
ui.label(RichText::new(tr("Recent packages")).size(15.0).strong());
recent(app, ui);
}
/// A card opens the New graph dialog with its template chosen
fn begin_with(app: &mut MaterialCraftApp, card: &TemplateCard) {
app.ui.windows.home = false;
crate::new_graph_dialog::open(app, card.kind);
app.ui.new_graph_template = card.id.to_string();
}
/// The recently opened packages, newest first: the file's name, then where it is
fn recent(app: &mut MaterialCraftApp, ui: &mut Ui) {
let tokens = Tokens::get(ui.ctx());
if app.ui.recent.is_empty() {
ui.label(RichText::new(tr("No recent packages")).color(tokens.text_dim));
return;
}
#[cfg(not(target_arch = "wasm32"))]
egui::ScrollArea::vertical().id_salt("home-recent").show(ui, |ui| {
let free = !Modality::capture(app, ui.ctx()).is_blocked();
for path in app.ui.recent.clone() {
let file = std::path::Path::new(&path).file_name().map_or_else(|| path.clone(), |name| name.to_string_lossy().into_owned());
let text = egui::text::LayoutJob::simple_singleline(format!("{} {file}", icon::PACKAGE), egui::FontId::proportional(13.0), tokens.text);
let row = ui.add_enabled(free, egui::Button::new(text).frame_when_inactive(false)).on_hover_text(&path);
ui.label(RichText::new(&path).small().color(tokens.text_dim));
if row.clicked() {
crate::windows::open_path(app, &path);
app.ui.windows.home = false;
}
}
});
}
+123
View File
@@ -22,6 +22,9 @@ pub const TABLE: &[(&str, &str)] = &[
("8 bits", "8 بت"),
("8 bits per channel", "8 بت لكل قناة"),
("A folder: material.mtlx, material.json, resources/ and the optional preview.png", "مجلد: material.mtlx وmaterial.json وresources/ وpreview.png الاختياري"),
("A graph's name is unique in its package; a taken name gets a number", "اسم المخطط فريد في حزمته؛ يُضاف رقم إلى الاسم المستخدم"),
("A saved default is in use", "إعداد افتراضي محفوظ قيد الاستخدام"),
("A small graph of atomic nodes working together", "مخطط صغير لعقد ذرية تعمل معاً"),
("Abbe number", "عدد آبي"),
("About MaterialCraft", "حول MaterialCraft"),
("About MaterialCraft...", "حول MaterialCraft..."),
@@ -45,27 +48,35 @@ pub const TABLE: &[(&str, &str)] = &[
("Align left", "محاذاة لليسار"),
("Align top", "محاذاة للأعلى"),
("All", "الكل"),
("All Craft apps", "جميع تطبيقات Craft"),
("All Craft apps...", "جميع تطبيقات Craft..."),
("All nodes", "كل العقد"),
("All templates", "جميع القوالب"),
("Alpha", "ألفا"),
("Alpha channel", "قناة ألفا"),
("Amber", "كهرماني"),
("Ambient Light", "الضوء المحيط"),
("Ambient occlusion", "الإطباق المحيط"),
("Ambient occlusion rays", "أشعة الإطباق المحيط"),
("An empty function graph: a value computed from function nodes", "مخطط دالة فارغ: قيمة تُحسب من عقد الدوال"),
("An empty material graph", "مخطط مادة فارغ"),
("An open-source Crafting App by the ArtCraft team and community.", "تطبيق تصميم مفتوح المصدر من قِبل فريق ومجتمع ArtCraft."),
("And", "و (And)"),
("Angle above the horizon", "الزاوية فوق الأفق"),
("Angle around the scene", "الزاوية حول المشهد"),
("Anisotropy", "تباين الخواص"),
("Appearance", "المظهر"),
("Apply", "تطبيق"),
("Arc tangent 2", "ظل زاوية قوسي 2"),
("ArtCraft website...", "موقع ArtCraft الإلكتروني..."),
("As JSON", "بصيغة JSON"),
("Atomic nodes", "عقد أولية"),
("Attributes", "السمات"),
("Auto backup", "النسخ الاحتياطي التلقائي"),
("Automatic (16 bits for normal and height)", "تلقائي (16 بت للناظم والارتفاع)"),
("Automatic Clip Planes", "مستويات قطع تلقائية"),
("Automatic export when outputs change", "تصدير تلقائي عند تغيّر المخرجات"),
("Automation documentation...", "توثيق الأتمتة..."),
("Autosave every (minutes, 0 = off)", "الحفظ التلقائي كل (دقائق، 0 = معطل)"),
("Axis", "المحاور"),
("Back", "الخلف"),
@@ -77,6 +88,10 @@ pub const TABLE: &[(&str, &str)] = &[
("Bad function", "دالة غير صالحة"),
("Bake every control", "خَبز كل عناصر التحكم في الخامات"),
("Base", "الأساس"),
(
"Base color, normal, roughness, metallic, height and ambient occlusion outputs, ready to connect",
"مخرجات اللون الأساسي والناظم والخشونة والمعدنية والارتفاع والإطباق المحيط، جاهزة للتوصيل",
),
("Base parameters", "المعلمات الأساسية"),
("Batch", "دفعة"),
("Bind to input", "ربط بالمدخل"),
@@ -90,6 +105,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Bounding box", "الصندوق المحيط"),
("Brick wall", "جدار طوب"),
("Brightness", "السطوع"),
("Browse...", "استعراض..."),
(
"Build tileable materials from noises, patterns and filters, see them live in 2D and 3D, and export the maps for any engine.",
"أنشئ مواد قابلة للتكرار من التشويش والأنماط والمرشحات، وعاينها مباشرة ثنائية وثلاثية الأبعاد، وصدّر الخرائط لأي محرك.",
@@ -98,7 +114,9 @@ pub const TABLE: &[(&str, &str)] = &[
("Camera", "الكاميرا"),
("Camera: drag to orbit, pan and zoom (C)", "الكاميرا: اسحب للدوران والتحريك والتكبير (C)"),
("Cancel", "إلغاء"),
("Cancel rendering", "إلغاء التصيير"),
("Cast", "تحويل النوع"),
("Category", "الفئة"),
("Ceil", "الحد الأعلى (Ceil)"),
("Channels shown", "القنوات المعروضة"),
("Check at least one output to export", "حدّد مخرجًا واحدًا على الأقل للتصدير"),
@@ -108,6 +126,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Clamp", "تقييد النطاق (Clamp)"),
("Clear cache", "مسح الذاكرة المؤقتة"),
("Clear material assignments", "مسح تعيينات المادة"),
("Clear nodes thumbnails", "مسح صور العقد المصغرة"),
("Clear recent packages", "مسح الحزم الأخيرة"),
("Click a node to show it here", "انقر على عقدة لعرضها هنا"),
("Clip planes", "مستويات القطع"),
@@ -120,13 +139,18 @@ pub const TABLE: &[(&str, &str)] = &[
("Color", "اللون"),
("Color sampler: click the image to place it", "أداة التقاط اللون: انقر على الصورة لوضعها"),
("color space", "فضاء الألوان"),
("Common", "عام"),
("Community", "المجتمع"),
("Community (Discord)", "المجتمع (Discord)"),
("Community (Discord)...", "المجتمع (Discord)..."),
("Comparison", "مقارنة"),
("Compute graph", "حساب المخطط"),
("Compute nodes thumbnails", "حساب صور العقد المصغرة"),
("Computing...", "جاري الحساب..."),
("Console", "وحدة التحكم"),
("Constant", "ثابت"),
("Control", "تحكم"),
("Cooker", "المعالِج"),
("Copper", "نحاسي"),
("Copy", "نسخ"),
("Copy image to the clipboard", "نسخ الصورة إلى الحافظة"),
@@ -143,6 +167,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Create", "إنشاء"),
("Create graph from selection", "إنشاء مخطط من التحديد"),
("Create graph in", "إنشاء مخطط في"),
("Create nodes by dropping a wire on empty canvas", "إنشاء العقد بإفلات سلك على لوحة فارغة"),
("Cube", "مكعب"),
("Cut", "قص"),
("Cyan", "سماوي"),
@@ -150,6 +175,9 @@ pub const TABLE: &[(&str, &str)] = &[
("Dark", "داكن"),
("Darkening", "التعتيم"),
("Default", "افتراضي"),
("Default 3D view", "العرض ثلاثي الأبعاد الافتراضي"),
("Default environment", "البيئة الافتراضية"),
("Default lighting state", "حالة الإضاءة الافتراضية"),
("Delete", "حذف"),
("Delete and relink", "حذف وإعادة ربط"),
("Delete input", "حذف المدخل"),
@@ -160,6 +188,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Diffuse roughness", "خشونة الانتشار"),
("DirectX (Y-)", "DirectX (Y-)"),
("Disable selection", "تعطيل التحديد"),
("Disk limit (MiB, 0 = off)", "حد القرص (ميبيبايت، 0 = إيقاف)"),
("Dispersion scale", "مقياس التشتت"),
("Displacement", "الإزاحة"),
("Displacement scale", "مقياس الإزاحة"),
@@ -181,6 +210,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Duplicate selection without link", "تكرار التحديد بدون ربط"),
("Edit", "تحرير"),
("Edit function graph...", "تحرير مخطط الدوال..."),
("Edit node graph", "تحرير مخطط العقدة"),
("Edit properties", "تعديل الخصائص"),
("Edit settings", "تعديل الإعدادات"),
("Emission", "الانبعاث"),
@@ -189,14 +219,20 @@ pub const TABLE: &[(&str, &str)] = &[
("Enable physical size from graph", "تفعيل الحجم الفيزيائي من المخطط"),
("Enabled", "مفعّل"),
("Engine", "المحرك"),
(
"Engine suspended: choose Suspend engine in the Tools menu again (Shift+Escape) to resume",
"المحرك متوقف مؤقتاً: اختر «إيقاف المحرك مؤقتاً» من قائمة الأدوات مرة أخرى (Shift+Escape) للاستئناف",
),
("Environment", "البيئة"),
("Environment background", "خلفية البيئة"),
("Environment image", "صورة البيئة"),
("Environment shown behind the mesh by default", "إظهار البيئة خلف المجسم افتراضياً"),
("Equal", "مساوٍ"),
("Exit", "خروج"),
("Explorer", "المستكشف"),
("Exponential", "دالة أسية (Exp)"),
("Export", "تصدير"),
("Export log...", "تصدير السجل..."),
("Export material...", "تصدير المادة..."),
("Export outputs", "تصدير المخرجات"),
("Export outputs...", "تصدير المخرجات..."),
@@ -212,6 +248,7 @@ pub const TABLE: &[(&str, &str)] = &[
("File", "ملف"),
("File names", "أسماء الملفات"),
("files", "ملفات"),
("Filter", "تصفية"),
("Filters", "مرشحات"),
("Fit", "ملاءمة"),
("Flip normal map Y (DirectX)", "قلب Y لخريطة النواظم (DirectX)"),
@@ -223,6 +260,10 @@ pub const TABLE: &[(&str, &str)] = &[
("Floor", "الحد الأدنى (Floor)"),
("Focal Length (mm)", "البعد البؤري (مم)"),
("Folder", "المجلد"),
(
"For the material graph: press the keys over the graph to add the node under the pointer",
"لمخطط المادة: اضغط المفاتيح فوق المخطط لإضافة العقدة تحت المؤشر",
),
("Format", "الصيغة"),
("Fractional part", "الجزء الكسري"),
("Frame", "تأطير"),
@@ -240,8 +281,10 @@ pub const TABLE: &[(&str, &str)] = &[
("function nodes", "عقد الدوال"),
("Function of", "دالة لـ"),
("Fuzz", "الزغب"),
("General", "عام"),
("Geometry", "الهندسة"),
("Get variable", "جلب متغير"),
("Give feedback...", "إرسال ملاحظات..."),
("Glossiness", "اللمعان"),
("Go to pin", "الانتقال إلى الدبوس"),
("Graph", "مخطط"),
@@ -263,6 +306,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Height scale", "مقياس الارتفاع"),
("Height technique", "تقنية الارتفاع"),
("Help", "مساعدة"),
("High (16 spp)", "مرتفع (16 عينة/بكسل)"),
("Histogram", "المخطط البياني (Histogram)"),
("History", "السجل"),
("Hollow box", "صندوق أجوف"),
@@ -273,29 +317,38 @@ pub const TABLE: &[(&str, &str)] = &[
("Image copied to the clipboard", "تم نسخ الصورة إلى الحافظة"),
("Image information", "معلومات الصورة"),
("Import bitmap...", "استيراد صورة نقطية..."),
("Import vector graphics...", "استيراد رسومات متجهية..."),
("Imported", "تم الاستيراد"),
("Include preview.png", "تضمين preview.png"),
("Information", "المعلومات"),
("Inner box", "صندوق داخلي"),
("Input parameters", "معلمات المدخلات"),
("Input previews", "معاينات المدخلات"),
("Install...", "تثبيت..."),
("Instance parameters", "معلمات النسخة"),
("Integer", "عدد صحيح"),
("Intensity", "الشدة"),
("Interface scale", "حجم واجهة المستخدم"),
("Invert zoom in views", "عكس التكبير في العروض"),
("is already the shortcut of", "هو بالفعل اختصار"),
("Join the community (Discord)...", "انضم إلى المجتمع (Discord)..."),
("Keep supported controls", "إبقاء عناصر التحكم المدعومة"),
("Keep the width and height the same", "إبقاء العرض والارتفاع متساويين"),
(
"Keep the zoom when the image size changes; off keeps the image's size on screen",
"الحفاظ على نسبة التكبير عند تغيّر حجم الصورة؛ عند الإيقاف يبقى حجم الصورة على الشاشة ثابتًا",
),
("Keep up to", "الاحتفاظ بما يصل إلى"),
("Key at", "مفتاح عند"),
("Language", "اللغة"),
("Last compute", "آخر حساب"),
("Lava rock", "صخور بركانية"),
("Layout", "التخطيط"),
("Learn", "تعلّم"),
("Left", "اليسار"),
("Length", "الطول"),
("Library", "المكتبة"),
("Library preview cache", "ذاكرة معاينات المكتبة"),
("Light", "فاتح"),
("Light: drag to move the first point light, which switches it on (L)", "الضوء: اسحب لتحريك الضوء النقطي الأول، وهذا يشغّله (L)"),
("Lights", "الأضواء"),
@@ -305,17 +358,23 @@ pub const TABLE: &[(&str, &str)] = &[
("Load mesh...", "تحميل مجسم..."),
("Load State File With Mesh...", "تحميل ملف حالة مع المجسم..."),
("Load State File...", "تحميل ملف حالة..."),
("Loaded", "محمّلة"),
("Logarithm", "لوغاريتم"),
("Logical", "منطقي"),
("Low (1 spp)", "منخفض (1 عينة/بكسل)"),
("Lower", "أصغر من"),
("Lower or equal", "أصغر من أو يساوي"),
("Luminance", "النصوع"),
("Main toolbar", "شريط الأدوات الرئيسي"),
("Mat ball", "كرة المادة"),
("Material", "المادة"),
("Material filters", "مرشحات المواد"),
("Material graph", "مخطط مادة"),
("Materials", "المواد"),
("MaterialX export isn't available yet (#190)", "تصدير MaterialX غير متاح بعد (#190)"),
("Maximum", "الحد الأقصى"),
("Maximum stored previews", "أقصى عدد للمعاينات المخزنة"),
("Medium (4 spp)", "متوسط (4 عينات/بكسل)"),
("Medium dark", "داكن متوسط"),
("Medium light", "فاتح متوسط"),
("Mesh Info", "معلومات المجسم"),
@@ -326,6 +385,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Metalness", "المعدنية"),
("Meters per scene unit", "الأمتار لكل وحدة مشهد"),
("Minimum", "الحد الأدنى"),
("Misc", "متفرقات"),
("Modulo", "باقي القسمة (Modulo)"),
("Mossy ground", "أرضية مغطاة بالطحالب"),
("Move the pointer over the image to read its pixels", "حرّك المؤشر فوق الصورة لقراءة بكسلاتها"),
@@ -334,17 +394,22 @@ pub const TABLE: &[(&str, &str)] = &[
("Near Clip Plane", "مستوى القطع القريب"),
("Negation", "نفي / سالب"),
("New", "جديد"),
("New function graph", "مخطط دالة جديد"),
("New graph", "مخطط جديد"),
("New graph...", "مخطط جديد..."),
("New graph... (Ctrl+N)", "مخطط جديد... (Ctrl+N)"),
("New package", "حزمة جديدة"),
("New random seed", "بذرة عشوائية جديدة"),
("Next pin", "الدبوس التالي"),
("Night", "ليل"),
("No font on this system can show this language", "لا يوجد خط على هذا النظام يمكنه عرض هذه اللغة"),
("No graph is open", "لا يوجد مخطط مفتوح"),
("No graph with outputs", "لا يوجد مخطط له مخرجات"),
("No matching node", "لا توجد عقدة مطابقة"),
("No plugins are installed. MaterialCraft does not load plugins yet.", "لا توجد إضافات مثبتة. لا يحمّل MaterialCraft الإضافات بعد."),
("No presets yet", "لا توجد إعدادات مسبقة بعد"),
("No recent packages", "لا توجد حزم حديثة"),
("Node creation shortcuts", "اختصارات إنشاء العقد"),
("Node search (over the graph)", "البحث عن عقدة (فوق المخطط)"),
("Node-based procedural materials, built in pure Rust.", "مواد إجرائية قائمة على العقد، مبنية بلغة Rust النقية."),
("Noises", "تشويشات"),
@@ -353,9 +418,12 @@ pub const TABLE: &[(&str, &str)] = &[
("Normal orientation", "اتجاه الناظم (Normal)"),
("Normalize", "تسوية (Normalize)"),
("Not", "ليس (Not)"),
("Not applied: the active graph or package changed while the file dialog was open", "لم يُطبّق: تغيّر المخطط أو الحزمة النشطة أثناء فتح نافذة الملفات"),
("not available yet", "غير متاح بعد"),
("Not equal", "غير مساوٍ"),
("Not saved:", "لم يُحفظ:"),
("Nothing matches", "لا توجد تطابقات"),
("OK", "موافق"),
(
"One .mcmat archive: material.mtlx, material.json, resources/ and the optional preview.png",
"أرشيف .mcmat واحد: material.mtlx وmaterial.json وresources/ وpreview.png الاختياري",
@@ -367,6 +435,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Open package... (Ctrl+O)", "فتح حزمة... (Ctrl+O)"),
("Open...", "فتح..."),
("Opened", "تم الفتح"),
("Opened with", "فُتح مع"),
("OpenGL (Y+)", "OpenGL (Y+)"),
("Operator", "معامل حسابي"),
("Ops", "عمليات"),
@@ -378,10 +447,13 @@ pub const TABLE: &[(&str, &str)] = &[
("Outputs", "المخرجات"),
("Overcast", "غائم"),
("Override Render Resolution", "تجاوز دقة التصيير"),
("packages", "حزم"),
("packages saved", "حزم حُفظت"),
("Painted metal plates", "صفائح معدنية مطلية"),
("Pan the camera", "تحريك الكاميرا"),
("Pan the graph", "تحريك المخطط"),
("Parallax Occlusion", "إطباق المنظور"),
("Parent graph", "المخطط الأب"),
("Parent size:", "حجم العنصر الأصل:"),
("Paste", "لصق"),
("Pattern", "النمط"),
@@ -394,9 +466,17 @@ pub const TABLE: &[(&str, &str)] = &[
("Pick an image file (a mesh map baked in TextureCraft)", "اختر ملف صورة (خريطة مجسم مخبوزة في TextureCraft)"),
("Pink", "وردي"),
("Pixels", "البكسلات"),
(
"placeholder node(s) stand in for nodes MaterialCraft doesn't have yet (see the warnings above)",
"عقدة (عقد) بديلة تحل محل عقد لا يملكها MaterialCraft بعد (انظر التحذيرات أعلاه)",
),
("Plane", "مستوى"),
("Plane (hi-res)", "مستوٍ (عالي الدقة)"),
("Plot the square root of the counts, so small counts stay visible", "رسم الجذر التربيعي للأعداد لتبقى الأعداد الصغيرة ظاهرة"),
("Plugin Manager", "مدير الإضافات"),
("Plugin Manager...", "مدير الإضافات..."),
("Plugins", "الإضافات"),
("Plugins are not supported yet", "الإضافات غير مدعومة بعد"),
("Point Light 1", "الضوء النقطي 1"),
("Point Light 2", "الضوء النقطي 2"),
("Polished marble", "رخام مصقول"),
@@ -406,11 +486,15 @@ pub const TABLE: &[(&str, &str)] = &[
("Preferences...", "التفضيلات..."),
("Preset name", "اسم الإعداد المسبق"),
("Presets", "الإعدادات المسبقة"),
("Press keys, Backspace to clear, Esc to cancel", "اضغط المفاتيح، Backspace للمسح، Esc للإلغاء"),
("Preview", "معاينة"),
("Preview resolution", "دقة المعاينة"),
("Preview size", "حجم المعاينة"),
("Preview size while editing", "حجم المعاينة أثناء التحرير"),
("Previews rebuild as they come into view.", "تُعاد بناء المعاينات عند ظهورها."),
("Previous pin", "الدبوس السابق"),
("Projection", "الإسقاط"),
("Projects", "المشاريع"),
("Properties", "الخصائص"),
("Publishing arrives with the new .mcmat format (#190); these options are kept for it", "يصل النشر مع صيغة .mcmat الجديدة (#190)؛ وتُحفظ هذه الخيارات لها"),
("Radius", "نصف القطر"),
@@ -419,14 +503,20 @@ pub const TABLE: &[(&str, &str)] = &[
("Random", "عشوائي"),
("Random seed", "بذرة عشوائية"),
("Range", "النطاق"),
("Rebuild thumbnails", "إعادة بناء الصور المصغرة"),
("Recent", "الأخيرة"),
("Recent documents", "المستندات الأخيرة"),
("Recent packages", "الحزم الأخيرة"),
("Recent packages list contains", "قائمة الحزم الأخيرة تحتوي"),
("Red", "أحمر"),
("Redo", "إعادة"),
("Redo (Ctrl+Y)", "إعادة (Ctrl+Y)"),
("Refresh", "تحديث"),
("Relative to input", "نسبي إلى المدخل"),
("Relative to parent", "نسبي إلى الأصل"),
("Release notes...", "ملاحظات الإصدار..."),
("Reload resources", "إعادة تحميل الموارد"),
("Remove every node creation shortcut", "إزالة كل اختصارات إنشاء العقد"),
("Remove function", "إزالة الدالة"),
("Remove the background image", "إزالة صورة الخلفية"),
("Remove the color sampler", "إزالة أداة التقاط اللون"),
@@ -439,7 +529,9 @@ pub const TABLE: &[(&str, &str)] = &[
("Renderer", "المصير"),
("Renderer settings", "إعدادات المصيِّر"),
("Repeat the image to check its tiling", "تكرار الصورة للتحقق من تكرارها"),
("Report a bug", "الإبلاغ عن خطأ"),
("Report a bug...", "الإبلاغ عن خطأ..."),
("Reset and view outputs in 3D view", "إعادة الضبط وعرض المخرجات في العرض ثلاثي الأبعاد"),
("Reset Common Parameters", "إعادة ضبط المعاملات المشتركة"),
("Reset Environment", "إعادة ضبط البيئة"),
("Reset layout", "إعادة ضبط التخطيط"),
@@ -467,14 +559,20 @@ pub const TABLE: &[(&str, &str)] = &[
("Rounded cylinder", "أسطوانة مستديرة الحواف"),
("Rusty metal", "معدن صدئ"),
("Sample Color", "عينة لونية"),
("Sample count", "عدد العينات"),
("Sample Gray", "عينة تدرج رمادي"),
("Samplers", "عينات"),
("Samples", "عينات"),
("Samples per pixel side", "العينات لكل ضلع بكسل"),
("Save", "حفظ"),
("Save (Ctrl+S)", "حفظ (Ctrl+S)"),
("Save all", "حفظ الكل"),
("Save as...", "حفظ باسم..."),
("Save Current State As Default", "حفظ الحالة الحالية كافتراضية"),
(
"Save Current State As Default, in the 3D view's Scene menu, saves the whole view here",
"«حفظ الحالة الحالية كافتراضية» في قائمة المشهد بالعرض ثلاثي الأبعاد يحفظ العرض كاملاً هنا",
),
("Save Current State...", "حفظ الحالة الحالية..."),
("Save image...", "حفظ الصورة..."),
("Save package", "حفظ الحزمة"),
@@ -483,11 +581,13 @@ pub const TABLE: &[(&str, &str)] = &[
("Save settings", "حفظ الإعدادات"),
("Saved", "تم الحفظ"),
("Saved as the default 3D view", "حُفظ كعرض ثلاثي الأبعاد افتراضي"),
("saved; use Save as for packages without a file", "حُفظت؛ استخدم «حفظ باسم» للحزم التي ليس لها ملف"),
("Saving a render needs the desktop app; copy it to the clipboard instead", "حفظ التصيير يتطلب تطبيق سطح المكتب؛ انسخه إلى الحافظة بدلاً من ذلك"),
("Scene", "المشهد"),
("Scene browser", "متصفح المشهد"),
("Scene stats", "إحصاءات المشهد"),
("Search", "بحث"),
("Search by shortcut", "البحث بالاختصار"),
("Search nodes...", "البحث في العقد..."),
("Select all", "تحديد الكل"),
("Select downstream nodes", "تحديد العقد اللاحقة"),
@@ -506,16 +606,19 @@ pub const TABLE: &[(&str, &str)] = &[
("Shortcuts", "الاختصارات"),
("Shortcuts list...", "قائمة الاختصارات..."),
("Show a checkerboard behind transparent pixels", "إظهار رقعة شطرنج خلف البكسلات الشفافة"),
("Show all assigned", "عرض كل المعيّن"),
("Show at startup", "إظهار عند بدء التشغيل"),
("Show in the 2D view", "إظهار في العرض ثنائي الأبعاد"),
("Show node thumbnails", "إظهار الصور المصغرة للعقد"),
("Show the environment behind the mesh", "إظهار البيئة خلف المجسم"),
("Show the image in the proportions of the graph's physical size", "عرض الصورة بنسب الحجم الفعلي للمخطط"),
("Show the library as a list", "عرض المكتبة كقائمة"),
("Showing", "عرض"),
("Shown on the mesh", "المعروض على المجسم"),
("Side", "جانبي"),
("Sine", "جيب الزاوية (Sine)"),
("Size", "الحجم"),
("Snap to grid", "المحاذاة إلى الشبكة"),
("Specific parameters", "المعلمات المخصصة"),
("Specular", "الانعكاس"),
("Specular Glossiness", "انعكاس ولمعان"),
@@ -524,6 +627,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Sqrt", "الجذر التربيعي"),
("Square root", "جذر تربيعي"),
("Start export", "بدء التصدير"),
("Start from a template", "ابدأ من قالب"),
("Stone tiles", "بلاط حجري"),
("Stored with the state; this renderer does not show it", "يُحفظ مع الحالة؛ هذا المصيِّر لا يعرضه"),
("Studio", "استوديو"),
@@ -531,9 +635,12 @@ pub const TABLE: &[(&str, &str)] = &[
("Subsurface", "تحت السطح"),
("Subtraction", "طرح"),
("Sunset", "غروب"),
("Suspend engine", "إيقاف المحرك مؤقتاً"),
("SVG", "رسوم متجهة (SVG)"),
("Swizzle", "إعادة ترتيب القنوات (Swizzle)"),
("Tab key shows the node search", "مفتاح Tab يعرض البحث عن العقد"),
("Tangent", "ظل الزاوية (Tangent)"),
("Technical requirements...", "المتطلبات التقنية..."),
("Templates", "القوالب"),
("Tessellation", "التقسيم"),
("Tessellation + Displacement", "تقسيم + إزاحة"),
@@ -541,8 +648,12 @@ pub const TABLE: &[(&str, &str)] = &[
("Texture generators", "مولدات الخامات"),
("Textures", "الخامات"),
("The background image could not be shown", "تعذّر عرض صورة الخلفية"),
("The built-in default is in use", "الإعداد الافتراضي المدمج قيد الاستخدام"),
("The colors are already multiplied by their alpha", "الألوان مضروبة مسبقًا في قناة ألفا"),
("The copies are numbered files in", "النسخ ملفات مرقمة في"),
("The file dialog could not be shown", "تعذّر عرض نافذة الملفات"),
("The instanced graph is missing", "المخطط المنسوخ مفقود"),
("The log could not be saved", "تعذّر حفظ السجل"),
("The pixel under the color sampler", "البكسل تحت أداة التقاط اللون"),
("The pixel under the pointer", "البكسل تحت المؤشر"),
("The point lights cast shadows", "الأضواء النقطية تلقي ظلالاً"),
@@ -567,13 +678,18 @@ pub const TABLE: &[(&str, &str)] = &[
("Transmission", "النفاذية"),
("Transparency (alpha)", "الشفافية (ألفا)"),
("Triangles", "المثلثات"),
("Troubleshooting...", "استكشاف الأخطاء..."),
("Turn the environment", "تدوير البيئة"),
("Tutorials", "الدروس"),
("Tutorials...", "الدروس..."),
("Unbind", "فك الارتباط"),
("Undo", "تراجع"),
("Undo (Ctrl+Z)", "تراجع (Ctrl+Z)"),
("Undo history (steps)", "سجل التراجع (خطوات)"),
("Uniform Color", "لون موحّد"),
("Unlit", "غير مضاء"),
("Use as result", "استخدام كنتيجة"),
("Use the built-in default", "استخدام الإعداد الافتراضي المدمج"),
("Use this parameter; off reads as if the material had none", "استخدام هذا المعامل؛ عند الإيقاف يُقرأ كأن المادة لا تحتويه"),
("Use viewport resolution", "استخدام دقة منفذ العرض"),
("Used range", "النطاق المستخدم"),
@@ -587,15 +703,22 @@ pub const TABLE: &[(&str, &str)] = &[
("Vector Float3", "متجه ثلاثي (Float3)"),
("Vector Float4", "متجه رباعي (Float4)"),
("Version", "الإصدار"),
("versions", "نسخ"),
("Vertex Color", "لون الرؤوس"),
("Vertex tangent space", "فضاء المماس للرؤوس"),
("Vertices", "الرؤوس"),
("View in 2D view", "عرض في العرض ثنائي الأبعاد"),
("View outputs in 3D view", "عرض المخرجات في العرض ثلاثي الأبعاد"),
("View outputs in 3D view when opening a graph", "عرض المخرجات في العرض ثلاثي الأبعاد عند فتح مخطط"),
("Viewpoint", "نقطة النظر"),
("Views", "العروض"),
("Violet", "بنفسجي"),
("warnings: see the Console", "تحذيرات: انظر وحدة التحكم"),
("Weathering", "التجوية والتقادم"),
("Weight", "الوزن"),
("Welcome to MaterialCraft", "مرحباً بك في MaterialCraft"),
("What's new", "ما الجديد"),
("What's new...", "ما الجديد..."),
("Wicker weave", "نسيج قش"),
("Windows", "نوافذ"),
("Wireframe", "إطار سلكي"),
+9
View File
@@ -11,13 +11,17 @@ pub mod fonts;
pub mod function;
pub mod graph;
mod graph_drag_payload;
mod help_links;
mod history;
mod home_screen;
pub mod i18n;
pub mod levels_editor;
pub mod library;
mod material_preview_menu;
mod menu_item;
pub mod menus;
mod new_graph_dialog;
mod node_shortcuts;
mod preview_resolution;
#[path = "property/mod.rs"]
pub mod properties;
@@ -34,10 +38,15 @@ pub mod web_files;
pub mod widgets;
pub mod windows;
#[cfg(not(target_arch = "wasm32"))]
mod autosave_versions;
mod material_craft_app;
#[cfg(not(target_arch = "wasm32"))]
mod native_dialogs;
pub mod pattern;
mod plugin_manager;
pub mod preferences;
mod template_card;
mod toast;
#[cfg(not(target_arch = "wasm32"))]
pub mod updates_ui;
+19 -9
View File
@@ -155,6 +155,9 @@ impl MaterialCraftApp {
let _ = materialcraft_engine::execute(&mut self.session, "session.history", &serde_json::json!(self.ui.prefs.history));
}
self.ui.recent.truncate(self.ui.prefs.recent_limit.clamp(1, crate::state::Prefs::MAX_RECENT));
self.session.view_outputs_on_open = self.ui.prefs.view_outputs_on_open;
if self.session.camera != self.ui.prefs.camera.sanitized() {
self.session.set_camera_prefs(self.ui.prefs.camera);
}
@@ -367,21 +370,26 @@ impl MaterialCraftApp {
}
self.next_autosave = now + period;
let dir = user_dir("autosave");
let path = dir.join(format!("{}.mcraft", materialcraft_engine::formats::safe_file_name(&self.session.pkg.name)));
let folder = user_dir("autosave");
let pkg = self.session.pkg.clone();
let keep = self.ui.prefs.autosave_versions.clamp(1, crate::state::Prefs::MAX_AUTOSAVE_VERSIONS);
let spawned = std::thread::Builder::new().name("materialcraft-autosave".into()).spawn(move || {
let result = std::fs::create_dir_all(&dir)
.map_err(|e| e.to_string())
let path = crate::autosave_versions::next_path(&folder, &pkg.name);
let result = std::fs::create_dir_all(&folder)
.map_err(|error| error.to_string())
.and_then(|_| {
materialcraft_engine::formats::project::ProjectFiles::build(&pkg, "autosave.mcraft", true)
.and_then(|files| files.zip())
.map_err(|e| e.to_string())
.map_err(|error| error.to_string())
})
.and_then(|bytes| materialcraft_engine::formats::write_atomic(&path, &bytes).map_err(|e| e.to_string()));
.and_then(|bytes| materialcraft_engine::formats::write_atomic(&path, &bytes).map_err(|error| error.to_string()));
match result {
Ok(()) => log::info!("autosaved {}", path.display()),
Err(e) => log::warn!("autosave to {} failed: {e}", path.display()),
Ok(()) => {
crate::autosave_versions::prune(&folder, &pkg.name, keep);
log::info!("autosaved {}", path.display());
}
Err(error) => log::warn!("autosave to {} failed: {error}", path.display()),
}
});
if let Err(e) = spawned {
@@ -505,7 +513,9 @@ impl MaterialCraftApp {
// Tab can focus a menu or toolbar button while drawing; preserve keyboard ownership
self.graph.keyboard_was_focused = ctx.egui_wants_keyboard_input();
menus::menu_bar(self, ui);
toolbar::main_toolbar(self, ui);
if self.ui.prefs.show_toolbar {
toolbar::main_toolbar(self, ui);
}
toolbar::status_bar(self, ui);
self.ui.explorer.hovered = false;
egui::CentralPanel::default().frame(egui::Frame::NONE.fill(theme::Tokens::get(&ctx).chrome)).show(ui, |ui| docking::show(self, ui));
+53 -15
View File
@@ -87,12 +87,13 @@ pub(crate) const EXPLORER_GRAPH: &[ExplorerRow] = &[
/// The menu catalog (the target menu tree with our ids)
pub const CATALOG: &[MenuItem] = &[
sub("File", "New", "Graph...", "ui.newGraph", Some("Ctrl+N")),
sub("File", "New", "Function Graph...", "ui.newFunctionGraph", None),
sub("File", "New", "Function graph", "ui.newFunctionGraph", None),
sub("File", "New", "Empty package", "file.newPackage", None),
it("File", "Open...", "file.open", Some("Ctrl+O")),
sep("File"),
it("File", "Save", "file.save", Some("Ctrl+S")),
it("File", "Save as...", "file.saveAs", Some("Ctrl+Shift+S")),
it("File", "Save all", "file.saveAll", None),
it("File", "Close all", "ui.closeAll", None),
sep("File"),
it("File", "Import bitmap...", "file.importBitmap", None),
@@ -100,6 +101,7 @@ pub const CATALOG: &[MenuItem] = &[
it("File", "Export outputs...", "ui.export", Some("Ctrl+Shift+E")),
it("File", "Export material...", "file.exportMaterial", None),
it("File", "Send to TextureCraft", "file.sendToTextureCraft", None),
sep("File"),
it("File", "Reload resources", "ui.reloadResources", None),
sep("File"),
it("File", "Exit", "ui.quit", Some("Ctrl+Q")),
@@ -117,6 +119,9 @@ pub const CATALOG: &[MenuItem] = &[
it("Edit", "Parent graph", "ui.graph.parent", Some("Alt+ArrowLeft")),
sep("Edit"),
it("Edit", "Preferences...", "ui.preferences", None),
it("Tools", "Cancel rendering", "ui.cook.cancel", Some("Escape")),
it("Tools", "Suspend engine", "ui.cook.suspend", Some("Shift+Escape")),
sep("Tools"),
it("Tools", "Compute graph", "graph.cook", None),
it("Tools", "Snap to grid", "ui.graph.snapToGrid", None),
it("Tools", "Compute nodes thumbnails", "ui.graph.computeThumbnails", None),
@@ -132,6 +137,10 @@ pub const CATALOG: &[MenuItem] = &[
sub("Tools", "Preview size", "2048 px", "ui.preview.2048", None),
sub("Tools", "Preview size", "Full size", "ui.preview.0", None),
it("Tools", "Create graph from selection", "graph.createFromSelection", None),
sep("Tools"),
it("Tools", "Plugin Manager...", "ui.pluginManager", None),
it("Windows", "Reset layout", "ui.resetLayout", None),
sep("Windows"),
it("Windows", "Explorer", "ui.view.explorer", None),
it("Windows", "Graph", "ui.view.graph", None),
it("Windows", "Properties", "ui.view.properties", None),
@@ -141,14 +150,26 @@ pub const CATALOG: &[MenuItem] = &[
it("Windows", "Library", "ui.view.library", None),
it("Windows", "History", "ui.view.history", None),
sep("Windows"),
it("Windows", "Reset layout", "ui.resetLayout", None),
it("Help", "Home screen...", "ui.home", None),
it("Windows", "Main toolbar", "ui.view.toolbar", None),
it("Help", "Tutorials...", "ui.help.tutorials", None),
it("Help", "Release notes...", "ui.help.releaseNotes", None),
it("Help", "Technical requirements...", "ui.help.requirements", None),
it("Help", "Documentation...", "ui.help.docs", None),
it("Help", "Automation documentation...", "ui.help.automation", None),
it("Help", "Shortcuts list...", "ui.help.shortcuts", None),
sep("Help"),
it("Help", "Join the community (Discord)...", "ui.help.discord", None),
it("Help", "ArtCraft website...", "ui.help.website", None),
it("Help", "Community (Discord)...", "ui.help.discord", None),
it("Help", "Report a bug...", "ui.help.bug", None),
#[cfg(not(target_arch = "wasm32"))]
it("Help", "Export log...", "ui.help.exportLog", None),
it("Help", "Give feedback...", "ui.help.feedback", None),
it("Help", "Troubleshooting...", "ui.help.troubleshooting", None),
sep("Help"),
it("Help", "All Craft apps...", "ui.help.apps", None),
it("Help", "ArtCraft website...", "ui.help.website", None),
sep("Help"),
it("Help", "Home screen...", "ui.home", None),
it("Help", "What's new...", "ui.help.news", None),
sep("Help"),
#[cfg(not(target_arch = "wasm32"))]
it("Help", "Check for updates...", "ui.help.checkForUpdates", None),
@@ -173,6 +194,10 @@ pub fn enabled(app: &MaterialCraftApp, id: &str) -> bool {
return enabled;
}
if id == "ui.cook.cancel" {
return app.cooker.busy();
}
if matches!(id, "edit.paste" | "edit.pasteWithoutLinks") {
return app.session.graph().is_ok() && app.session.clipboard.as_ref().is_some_and(|clip| !clip.nodes.is_empty());
}
@@ -212,11 +237,8 @@ pub fn invoke(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) {
return;
}
match id {
"ui.newGraph" | "ui.newFunctionGraph" => {
app.ui.new_graph_kind =
if id == "ui.newFunctionGraph" { materialcraft_engine::core::GraphKind::Function } else { materialcraft_engine::core::GraphKind::Material };
app.ui.windows.new_graph = true;
}
"ui.newGraph" => crate::new_graph_dialog::open(app, materialcraft_engine::core::GraphKind::Material),
"ui.newFunctionGraph" => crate::new_graph_dialog::open(app, materialcraft_engine::core::GraphKind::Function),
"ui.export" => crate::export::open(app, crate::export::ExportTab::FromGraph),
"ui.quit" => ctx.send_viewport_cmd(egui::ViewportCommand::Close),
"ui.preferences" => app.ui.windows.preferences = true,
@@ -237,10 +259,17 @@ pub fn invoke(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) {
"ui.about" => app.ui.windows.about = true,
#[cfg(not(target_arch = "wasm32"))]
"ui.help.checkForUpdates" => crate::updates_ui::check(app),
"ui.help.discord" => ctx.open_url(egui::OpenUrl::new_tab("https://discord.gg/artcraft")),
"ui.help.website" => ctx.open_url(egui::OpenUrl::new_tab("https://getartcraft.com/apps/materialcraft")),
"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")),
"ui.cook.cancel" => crate::cook::cancel(app),
"ui.cook.suspend" => crate::cook::toggle_suspended(app),
"ui.pluginManager" => app.ui.windows.plugin_manager = true,
"ui.view.toolbar" => app.ui.prefs.show_toolbar = !app.ui.prefs.show_toolbar,
#[cfg(not(target_arch = "wasm32"))]
"ui.help.exportLog" => crate::native_dialogs::export_log(app),
id if crate::help_links::url(id).is_some() => {
if let Some(url) = crate::help_links::url(id) {
ctx.open_url(egui::OpenUrl::new_tab(url));
}
}
_ => {
if crate::windows::file_action(app, ctx, id) {
return;
@@ -363,6 +392,8 @@ fn menu_item(app: &mut MaterialCraftApp, context: &egui::Context, ui: &mut egui:
let checked = match item.id {
"ui.view.graph" => Some(true),
"ui.graph.snapToGrid" => Some(app.ui.prefs.snap_to_grid),
"ui.cook.suspend" => Some(app.cooker.suspended),
"ui.view.toolbar" => Some(app.ui.prefs.show_toolbar),
id if id.starts_with("ui.preview.") => {
id.strip_prefix("ui.preview.").and_then(|size| size.parse::<u32>().ok()).map(|size| size == app.ui.prefs.preview_size)
}
@@ -441,10 +472,17 @@ pub fn shortcuts(app: &mut MaterialCraftApp, ctx: &egui::Context) {
let label_selected = label_text_selected(ctx);
// A clipboard chord with nothing to copy or paste leaves its event to egui instead of reporting an error
let unavailable_clipboard_commands: Vec<&str> = ["edit.copy", "edit.cut", "edit.paste"].into_iter().filter(|id| !enabled(app, id)).collect();
// A drag in progress keeps Escape so the gesture can cancel itself
let gesture_in_progress = ctx.input(|i| i.pointer.any_down());
let hits = ctx.input_mut(|i| {
app.dispatcher.dispatch_filtered(i, &app.keymap, &Active::NONE, |hit| {
let id = hit.command.id.as_str();
modality.allows(id) && !(label_selected && matches!(id, "edit.copy" | "edit.cut")) && !unavailable_clipboard_commands.contains(&id)
// Escape cancels a cook only while one runs and no drag is held, so it keeps closing and clearing everything else
let cancels_nothing = id == "ui.cook.cancel" && (!app.cooker.busy() || gesture_in_progress);
modality.allows(id)
&& !(label_selected && matches!(id, "edit.copy" | "edit.cut"))
&& !unavailable_clipboard_commands.contains(&id)
&& !cancels_nothing
})
});
for hit in hits {
+13
View File
@@ -41,6 +41,8 @@ pub(crate) enum Then {
},
/// The image file the 2D view draws behind transparent pixels
BackgroundImage,
/// Help ▸ Export log: the Console's messages, one per line
ExportLog(String),
/// The parameters `graph.input.bind` runs with, before the path
BindInput(Value, GraphRef),
}
@@ -94,6 +96,13 @@ pub(crate) fn save_package(app: &mut MaterialCraftApp, copy: bool) {
ask(app, dialog, then);
}
/// Help ▸ Export log: ask where to write the Console's messages as a text file
pub(crate) fn export_log(app: &mut MaterialCraftApp) {
let text = app.session.log.join("\n");
let dialog = craft_dialogs::FileDialog::save().file_name("materialcraft-log.txt").filter(tr("Text"), &["txt"]);
ask(app, dialog, Then::ExportLog(text));
}
/// Save in the unsaved-changes prompt, for a package without a path: waits behind any open dialog
pub(crate) fn save_before_action(app: &mut MaterialCraftApp) {
let then = Then::SavePackage { document: app.session.document_id, copy: false, before_action: true };
@@ -179,6 +188,10 @@ fn chosen(app: &mut MaterialCraftApp, then: Then, path: &std::path::Path) {
app.toast(format!("{} {picked}", tr("Saved")), false);
}
}
Then::ExportLog(text) => match materialcraft_engine::formats::write_atomic(path, text.as_bytes()) {
Ok(()) => app.toast(format!("{} {picked}", tr("Saved")), false),
Err(error) => app.toast(format!("{}: {error}", tr("The log could not be saved")), true),
},
Then::SaveViewState => {
if app.run("view.3d.saveState", json!({"path": picked})).is_some() {
app.toast(format!("{} {picked}", tr("Saved")), false);
+209
View File
@@ -0,0 +1,209 @@
//! File ▸ New ▸ Graph: template cards by category on the left; the graph's name, size and the
//! package it goes in on the right
use egui::{RichText, Ui, vec2};
use egui_phosphor::regular as icon;
use materialcraft_engine::core::GraphKind;
use serde_json::json;
use crate::MaterialCraftApp;
use crate::i18n::tr;
use crate::template_card::{CARD_SIZE, FUNCTION_TEMPLATE, TemplateCard};
use crate::theme::Tokens;
const WINDOW_SIZE: egui::Vec2 = vec2(1000.0, 640.0);
const SETTINGS_WIDTH: f32 = 340.0;
const CARD_GAP: f32 = 14.0;
const BUTTON_WIDTH: f32 = 120.0;
/// The sides a new graph can have, in pixels
const SIDES: [u32; 6] = [256, 512, 1024, 2048, 4096, 8192];
/// The categories the dialog lists: every template, or the templates of one kind of graph
const CATEGORIES: [(Option<GraphKind>, &str); 3] =
[(None, "All templates"), (Some(GraphKind::Material), "Material graph"), (Some(GraphKind::Function), "Function graph")];
/// Open the dialog for a kind of graph, aimed at the active package (or a new one when none is open)
pub(crate) fn open(app: &mut MaterialCraftApp, kind: GraphKind) {
app.ui.new_graph_kind = kind;
app.ui.new_graph_category = Some(kind);
if kind == GraphKind::Function {
app.ui.new_graph_template = FUNCTION_TEMPLATE.into();
} else if app.ui.new_graph_template == FUNCTION_TEMPLATE {
app.ui.new_graph_template = "pbr".into();
}
app.ui.new_graph_package = app.session.has_package().then_some(app.session.document_id);
app.ui.windows.new_graph = true;
}
/// Pick a card: its kind decides the graph's kind
fn choose(app: &mut MaterialCraftApp, card: &TemplateCard) {
app.ui.new_graph_kind = card.kind;
app.ui.new_graph_template = card.id.to_string();
}
pub(crate) fn show(app: &mut MaterialCraftApp, ctx: &egui::Context) {
let mut open = true;
let mut create = false;
let title = if app.ui.new_graph_kind == GraphKind::Function { tr("New function graph") } else { tr("New graph") };
crate::windows::modal(ctx, "new-graph", title, &mut open, WINDOW_SIZE, |ui| {
ui.set_min_size(WINDOW_SIZE);
let whole = ui.available_rect_before_wrap();
let cards = egui::Rect::from_min_max(whole.min, egui::pos2(whole.right() - SETTINGS_WIDTH - 24.0, whole.bottom()));
let settings = egui::Rect::from_min_max(egui::pos2(whole.right() - SETTINGS_WIDTH, whole.top()), whole.max);
card_grid(app, &mut ui.new_child(egui::UiBuilder::new().max_rect(cards)));
create = graph_settings(app, &mut ui.new_child(egui::UiBuilder::new().max_rect(settings)));
ui.advance_cursor_after_rect(whole);
});
if create {
open = !run(app);
}
if !open {
app.ui.windows.new_graph = false;
}
}
/// Create the graph. Returns true when it was created
fn run(app: &mut MaterialCraftApp) -> bool {
let target = app.ui.new_graph_package;
if let Some(document) = target
&& document != app.session.document_id
&& app.run("package.activate", json!({"document": document})).is_none()
{
return false;
}
let kind = if app.ui.new_graph_kind == GraphKind::Function { "function" } else { "material" };
let height = if app.ui.new_graph_linked { app.ui.new_graph_size } else { app.ui.new_graph_height };
let parameters = json!({
"kind": kind,
"template": app.ui.new_graph_template,
"name": app.ui.new_graph_name,
"size": app.ui.new_graph_size,
"height": height,
"newPackage": target.is_none(),
});
let created = app.run("file.new", parameters).is_some();
if created {
app.ui.frame_all = true;
}
created
}
/// The category list and the cards of the chosen category
fn card_grid(app: &mut MaterialCraftApp, ui: &mut Ui) {
let tokens = Tokens::get(ui.ctx());
ui.horizontal(|ui| {
ui.label(RichText::new(tr("Category")).strong());
let current = CATEGORIES.iter().find(|(kind, _)| *kind == app.ui.new_graph_category).map_or("", |(_, label)| label);
let combo = egui::ComboBox::from_id_salt("new-graph-category").width(220.0).selected_text(tr(current)).show_ui(ui, |ui| {
for (kind, label) in CATEGORIES {
ui.selectable_value(&mut app.ui.new_graph_category, kind, tr(label));
}
});
crate::widgets::name(&combo.response, egui::Role::ComboBox, "Category");
});
ui.add_space(10.0);
let cards: Vec<TemplateCard> =
crate::template_card::cards().into_iter().filter(|card| app.ui.new_graph_category.is_none_or(|kind| card.kind == kind)).collect();
egui::ScrollArea::vertical().id_salt("new-graph-cards").auto_shrink([false, false]).show(ui, |ui| {
for kind in [GraphKind::Material, GraphKind::Function] {
let group: Vec<&TemplateCard> = cards.iter().filter(|card| card.kind == kind).collect();
let Some(first) = group.first() else { continue };
ui.horizontal(|ui| {
ui.label(RichText::new(tr(first.kind_label())).size(16.0).color(tokens.text_dim));
let line = ui.available_rect_before_wrap();
ui.painter().hline(line.left() + 8.0..=line.right(), line.center().y, egui::Stroke::new(1.0, tokens.separator));
});
ui.add_space(6.0);
let columns = ((ui.available_width() + CARD_GAP) / (CARD_SIZE.x + CARD_GAP)).floor().max(1.0) as usize;
for row in group.chunks(columns) {
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = CARD_GAP;
for card in row {
let chosen = app.ui.new_graph_kind == card.kind && app.ui.new_graph_template == card.id;
let preview = crate::windows::template_preview(ui.ctx(), card.id);
let response = crate::template_card::show(ui, card, chosen, preview);
if response.clicked() {
choose(app, card);
}
if response.double_clicked() {
choose(app, card);
app.ui.new_graph_create_now = true;
}
}
});
ui.add_space(CARD_GAP);
}
}
});
}
/// The graph's name, size and package, and the Create and Cancel buttons. Returns true for Create
fn graph_settings(app: &mut MaterialCraftApp, ui: &mut Ui) -> bool {
let tokens = Tokens::get(ui.ctx());
ui.horizontal(|ui| {
ui.label(RichText::new(tr("Graph name")).strong());
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
ui.label(RichText::new(icon::QUESTION).color(tokens.text_dim))
.on_hover_text(tr("A graph's name is unique in its package; a taken name gets a number"));
});
});
let name = ui.add(egui::TextEdit::singleline(&mut app.ui.new_graph_name).desired_width(f32::INFINITY));
crate::widgets::name(&name, egui::Role::TextInput, "Graph name");
ui.add_space(14.0);
if app.ui.new_graph_kind == GraphKind::Material {
ui.label(RichText::new(tr("Size")).strong());
ui.horizontal(|ui| {
let side_width = (ui.available_width() - 40.0) * 0.5;
side_combo(ui, "new-graph-width", "Width", &mut app.ui.new_graph_size, side_width);
let link = crate::widgets::icon_button(ui, icon::LINK, tr("Keep the width and height the same"), app.ui.new_graph_linked, 24.0);
if link.clicked() {
app.ui.new_graph_linked = !app.ui.new_graph_linked;
}
if app.ui.new_graph_linked {
app.ui.new_graph_height = app.ui.new_graph_size;
}
ui.add_enabled_ui(!app.ui.new_graph_linked, |ui| side_combo(ui, "new-graph-height", "Height", &mut app.ui.new_graph_height, side_width));
});
ui.add_space(14.0);
}
ui.label(RichText::new(tr("Create graph in")).strong());
let packages: Vec<(u64, String)> = app.session.open_packages().into_iter().map(|(id, package, _, _)| (id, package.name.clone())).collect();
let current = app
.ui
.new_graph_package
.and_then(|id| packages.iter().find(|(package, _)| *package == id))
.map_or_else(|| tr("New package").to_string(), |(_, name)| name.clone());
let combo = egui::ComboBox::from_id_salt("new-graph-package").width(ui.available_width()).selected_text(current).show_ui(ui, |ui| {
ui.selectable_value(&mut app.ui.new_graph_package, None, tr("New package"));
for (id, name) in &packages {
ui.selectable_value(&mut app.ui.new_graph_package, Some(*id), name);
}
});
crate::widgets::name(&combo.response, egui::Role::ComboBox, "Create graph in");
let mut create = std::mem::take(&mut app.ui.new_graph_create_now);
let bottom = ui.max_rect().bottom();
let bar = egui::Rect::from_min_max(egui::pos2(ui.max_rect().left(), bottom - 32.0), ui.max_rect().right_bottom());
let mut bar_ui = ui.new_child(egui::UiBuilder::new().max_rect(bar).layout(egui::Layout::right_to_left(egui::Align::Center)));
if bar_ui.add_sized([BUTTON_WIDTH, 28.0], egui::Button::new(tr("Cancel"))).clicked() {
app.ui.windows.new_graph = false;
}
create |= bar_ui.add_sized([BUTTON_WIDTH, 28.0], crate::widgets::primary_button(&bar_ui, tr("Create"))).clicked();
create
}
/// A list of the sides a graph can have
fn side_combo(ui: &mut Ui, id: &str, label: &str, side: &mut u32, width: f32) {
let combo = egui::ComboBox::from_id_salt(id).width(width).selected_text(format!("{side} px")).show_ui(ui, |ui| {
for option in SIDES {
ui.selectable_value(side, option, format!("{option} px"));
}
});
crate::widgets::name(&combo.response, egui::Role::ComboBox, label);
}
+82
View File
@@ -0,0 +1,82 @@
//! Node creation shortcuts (Preferences ▸ Shortcuts): a key with modifiers that adds a library
//! entry under the pointer in the graph. The text of a shortcut is the menus' form, "Ctrl+Shift+B",
//! where Ctrl is Command on macOS
use egui::{Key, Modifiers};
/// The library categories whose entries can have a creation shortcut: the atomic nodes and the graph items
pub(crate) const CATEGORIES: [&str; 2] = ["Atomic nodes", "Graph items"];
/// The text of a key pressed with `modifiers`, or `None` for a key that cannot start a shortcut
pub(crate) fn text(modifiers: Modifiers, key: Key) -> Option<String> {
// Plain Escape, Tab and Enter keep their usual work: closing, moving focus and confirming
if modifiers.is_none() && matches!(key, Key::Escape | Key::Tab | Key::Enter) {
return None;
}
let mut parts = Vec::new();
if modifiers.command {
parts.push("Ctrl");
}
if modifiers.alt {
parts.push("Alt");
}
if modifiers.shift {
parts.push("Shift");
}
parts.push(key.name());
Some(parts.join("+"))
}
/// The modifiers and key a shortcut text names
pub(crate) fn parse(text: &str) -> Option<(Modifiers, Key)> {
let mut modifiers = Modifiers::NONE;
let mut key = None;
for part in text.split('+') {
match part {
"Ctrl" | "Cmd" => modifiers.command = true,
"Alt" => modifiers.alt = true,
"Shift" => modifiers.shift = true,
name if key.is_none() => key = Some(Key::from_name(name)?),
_ => return None,
}
}
key.map(|key| (modifiers, key))
}
/// The entry whose shortcut was pressed this frame, if any
pub(crate) fn pressed(shortcuts: &std::collections::BTreeMap<String, String>, input: &egui::InputState) -> Option<String> {
shortcuts.iter().find_map(|(entry, text)| {
let (modifiers, key) = parse(text)?;
(input.modifiers.matches_logically(modifiers) && input.modifiers.shift == modifiers.shift && input.key_pressed(key)).then(|| entry.clone())
})
}
/// The app command a shortcut text already starts, if any
pub(crate) fn taken_by(text: &str) -> Option<&'static str> {
let wanted = parse(text)?;
crate::menus::shortcut_table().into_iter().find(|(_, shortcut)| parse(shortcut) == Some(wanted)).map(|(id, _)| id)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_shortcut_reads_back_as_the_keys_that_made_it() {
let both = Modifiers { command: true, shift: true, ..Modifiers::NONE };
assert_eq!(text(both, Key::B).as_deref(), Some("Ctrl+Shift+B"));
assert_eq!(parse("Ctrl+Shift+B"), Some((both, Key::B)));
assert_eq!(text(Modifiers::ALT, Key::Num1).and_then(|text| parse(&text)), Some((Modifiers::ALT, Key::Num1)));
assert_eq!(text(Modifiers::NONE, Key::Escape), None);
assert_eq!(parse("Ctrl+Nope"), None);
assert_eq!(parse("Ctrl+B+C"), None);
}
#[test]
fn a_shortcut_the_app_already_uses_is_named() {
assert_eq!(taken_by("Ctrl+S"), Some("file.save"));
assert_eq!(taken_by("Ctrl+Shift+B"), None);
}
}
+1 -1
View File
@@ -87,7 +87,7 @@ fn paint(app: &mut MaterialCraftApp, editor: &mut PatternEditor, ui: &mut Ui) ->
}
let mut camera = GraphCamera { origin: bounds.min, pan: editor.pan, zoom: editor.zoom };
camera.zoom_from_input(ui, bounds);
camera.zoom_from_input(ui, bounds, app.ui.prefs.zoom_direction());
editor.pan = camera.pan;
editor.zoom = camera.zoom;
crate::graph::grid::paint(&painter, &camera, bounds);
+55
View File
@@ -0,0 +1,55 @@
//! Tools ▸ Plugin Manager: the window only, for now. MaterialCraft loads no plugins yet, so the list
//! is empty and its buttons wait for the plugin system
use egui::{RichText, vec2};
use crate::MaterialCraftApp;
use crate::i18n::tr;
use crate::theme::Tokens;
const WINDOW_SIZE: egui::Vec2 = vec2(700.0, 460.0);
const LOADED_WIDTH: f32 = 110.0;
const BUTTON_WIDTH: f32 = 130.0;
pub(crate) fn show(app: &mut MaterialCraftApp, ctx: &egui::Context) {
let mut open = true;
crate::windows::modal(ctx, "plugin-manager", tr("Plugin Manager"), &mut open, WINDOW_SIZE, |ui| {
let tokens = Tokens::get(ui.ctx());
ui.set_min_size(WINDOW_SIZE);
let filter = ui.add(egui::TextEdit::singleline(&mut app.ui.plugin_filter).hint_text(tr("Filter")).desired_width(f32::INFINITY));
crate::widgets::name(&filter, egui::Role::SearchInput, "Filter");
ui.add_space(6.0);
// The table's header row, then its rows
let header = ui.available_rect_before_wrap().with_max_y(ui.cursor().top() + 24.0);
ui.painter().rect_filled(header, 0.0, tokens.row_hover);
ui.horizontal(|ui| {
ui.set_height(24.0);
ui.add_space(6.0);
let left = egui::Layout::left_to_right(egui::Align::Center);
let plugins_width = ui.available_width() - LOADED_WIDTH;
ui.allocate_ui_with_layout(vec2(plugins_width, 24.0), left, |ui| {
ui.set_min_width(plugins_width);
ui.label(RichText::new(tr("Plugins")).strong());
});
ui.label(RichText::new(tr("Loaded")).strong());
});
let list = ui.available_rect_before_wrap().with_max_y(ui.max_rect().bottom() - 44.0);
ui.painter().rect_filled(list, 0.0, tokens.row);
ui.new_child(egui::UiBuilder::new().max_rect(list.shrink(10.0)))
.label(RichText::new(tr("No plugins are installed. MaterialCraft does not load plugins yet.")).color(tokens.text_dim));
ui.advance_cursor_after_rect(list);
ui.add_space(8.0);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let waiting = tr("Plugins are not supported yet");
for label in ["Refresh", "Install...", "Browse..."] {
ui.add_enabled(false, egui::Button::new(tr(label)).min_size(vec2(BUTTON_WIDTH, 28.0))).on_disabled_hover_text(waiting);
}
});
});
if !open {
app.ui.windows.plugin_manager = false;
}
}
+144
View File
@@ -0,0 +1,144 @@
//! Edit ▸ Preferences: pages listed down the left side, and OK, Cancel and Apply. Changes show as
//! they are made; Cancel (or closing the window) goes back to the preferences as they were when
//! the window opened or Apply was last pressed
mod general_page;
mod graph_page;
mod library_page;
mod preferences_page;
mod preferences_state;
mod projects_page;
mod shortcuts_page;
mod view3d_page;
use egui::{RichText, Ui, vec2};
pub use preferences_page::PreferencesPage;
pub use preferences_state::PreferencesState;
use crate::MaterialCraftApp;
use crate::i18n::tr;
use crate::theme::Tokens;
const WINDOW_SIZE: egui::Vec2 = vec2(900.0, 620.0);
const PAGE_LIST_WIDTH: f32 = 150.0;
const PAGE_ROW_HEIGHT: f32 = 36.0;
const BUTTON_WIDTH: f32 = 110.0;
const BUTTON_BAR_HEIGHT: f32 = 40.0;
/// What the buttons at the bottom of the window asked for
#[derive(Clone, Copy, PartialEq, Eq)]
enum Choice {
Ok,
Cancel,
Apply,
}
/// A section heading of a page, in capitals like the reference layout
pub(super) fn heading(ui: &mut Ui, title: &str) {
ui.add_space(10.0);
ui.label(RichText::new(tr(title).to_uppercase()).size(13.0).strong().color(Tokens::get(ui.ctx()).text_strong));
ui.add_space(2.0);
}
/// A labelled whole-number field with a unit after it. Returns true when it changed
pub(super) fn number_row<T: egui::emath::Numeric>(ui: &mut Ui, label: &str, value: &mut T, range: std::ops::RangeInclusive<T>, unit: &str) -> bool {
ui.horizontal(|ui| {
let caption = ui.label(tr(label));
let changed = ui.add(egui::DragValue::new(value).range(range).speed(0.2)).labelled_by(caption.id).changed();
ui.label(tr(unit));
changed
})
.inner
}
pub fn show(app: &mut MaterialCraftApp, ctx: &egui::Context) {
if app.ui.preferences.applied.is_none() {
app.ui.preferences.applied = Some(app.ui.prefs.clone());
}
let mut open = true;
let mut choice = None;
let mut rebuild_previews = false;
crate::windows::modal(ctx, "prefs", tr("Preferences"), &mut open, WINDOW_SIZE, |ui| {
ui.set_min_size(WINDOW_SIZE);
let whole = ui.available_rect_before_wrap();
let bar_top = whole.bottom() - BUTTON_BAR_HEIGHT;
let list = egui::Rect::from_min_max(whole.min, egui::pos2(whole.left() + PAGE_LIST_WIDTH, bar_top));
let page = egui::Rect::from_min_max(egui::pos2(list.right() + 16.0, whole.top()), egui::pos2(whole.right(), bar_top));
page_list(app, &mut ui.new_child(egui::UiBuilder::new().max_rect(list)));
let mut page_ui = ui.new_child(egui::UiBuilder::new().max_rect(page));
egui::ScrollArea::vertical().id_salt("preferences-page").auto_shrink([false, false]).show(&mut page_ui, |ui| {
ui.set_width(page.width() - 12.0);
match app.ui.preferences.page {
PreferencesPage::General => general_page::show(app, ui),
PreferencesPage::Projects => projects_page::show(app, ui),
PreferencesPage::Graph => graph_page::show(app, ui),
PreferencesPage::View3d => view3d_page::show(app, ui),
PreferencesPage::Library => rebuild_previews = library_page::show(app, ui),
PreferencesPage::Shortcuts => shortcuts_page::show(app, ui),
}
});
let bar = egui::Rect::from_min_max(egui::pos2(whole.left(), bar_top), whole.max);
let mut bar_ui = ui.new_child(egui::UiBuilder::new().max_rect(bar).layout(egui::Layout::right_to_left(egui::Align::Center)));
for (label, pressed) in [("Apply", Choice::Apply), ("Cancel", Choice::Cancel), ("OK", Choice::Ok)] {
let button = if pressed == Choice::Ok { crate::widgets::primary_button(&bar_ui, tr(label)) } else { egui::Button::new(tr(label)) };
if bar_ui.add_sized([BUTTON_WIDTH, 28.0], button).clicked() {
choice = Some(pressed);
}
}
ui.advance_cursor_after_rect(whole);
});
if rebuild_previews {
app.run("library.cache.clear", serde_json::json!({}));
}
// Closing the window is Cancel
let choice = if open { choice } else { Some(Choice::Cancel) };
match choice {
Some(Choice::Apply) => app.ui.preferences.applied = Some(app.ui.prefs.clone()),
Some(Choice::Cancel) => {
if let Some(applied) = app.ui.preferences.applied.take() {
app.ui.prefs = applied;
}
close(app);
}
Some(Choice::Ok) => close(app),
None => {}
}
app.apply_prefs();
}
fn close(app: &mut MaterialCraftApp) {
app.ui.windows.preferences = false;
app.ui.preferences.applied = None;
app.ui.preferences.capturing = None;
}
/// The pages down the left side; the chosen one is highlighted
fn page_list(app: &mut MaterialCraftApp, ui: &mut Ui) {
let tokens = Tokens::get(ui.ctx());
ui.painter().rect_filled(ui.max_rect(), 0.0, tokens.row);
for page in PreferencesPage::ALL {
let chosen = app.ui.preferences.page == page;
let label = RichText::new(tr(page.label()).to_uppercase()).size(14.0).color(if chosen { tokens.text_strong } else { tokens.text });
let button = egui::Button::selectable(chosen, label).frame_when_inactive(false);
let row = ui
.allocate_ui_with_layout(
vec2(ui.available_width(), PAGE_ROW_HEIGHT),
egui::Layout::left_to_right(egui::Align::Center).with_main_justify(true).with_main_align(egui::Align::LEFT),
|ui| ui.add(button),
)
.inner;
crate::widgets::name(&row, egui::Role::Tab, page.label());
if row.clicked() {
app.ui.preferences.page = page;
app.ui.preferences.capturing = None;
}
}
}
@@ -0,0 +1,74 @@
//! Preferences ▸ General: recent packages, history, language, appearance, views, autosave and previews
use egui::Ui;
use super::{heading, number_row};
use crate::MaterialCraftApp;
use crate::i18n::tr;
use crate::state::Prefs;
use crate::theme::{Accent, Brightness};
/// The most undo steps the history slider reaches
const MAX_UNDO_STEPS: f32 = 10_000.0;
/// The longest autosave interval the slider reaches, in minutes
const MAX_AUTOSAVE_MINUTES: f32 = 60.0;
pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
let prefs = &mut app.ui.prefs;
heading(ui, "Recent documents");
number_row(ui, "Recent packages list contains", &mut prefs.recent_limit, 1..=Prefs::MAX_RECENT, "packages");
heading(ui, "History");
let mut undo_limit = prefs.history.undo_limit as f32;
if crate::widgets::slider(ui, tr("Undo history (steps)"), &mut undo_limit, 1.0..=MAX_UNDO_STEPS, 0).changed() {
prefs.history.undo_limit = undo_limit.round() as u32;
}
heading(ui, "Language");
crate::widgets::combo(ui, tr("Language"), crate::i18n::current().name, |ui| {
for language in &crate::i18n::LANGUAGES {
if ui.selectable_label(prefs.language == language.code, language.name).clicked() {
prefs.language = language.code.to_owned();
crate::i18n::set_language(&prefs.language);
}
}
});
heading(ui, "Appearance");
crate::widgets::combo(ui, tr("Brightness"), tr(prefs.brightness.label()), |ui| {
for brightness in Brightness::ALL {
ui.selectable_value(&mut prefs.brightness, brightness, tr(brightness.label()));
}
});
crate::widgets::combo(ui, tr("Accent color"), tr(prefs.accent.label()), |ui| {
for accent in Accent::ALL {
ui.selectable_value(&mut prefs.accent, accent, tr(accent.label()));
}
});
crate::widgets::slider(ui, tr("Interface scale"), &mut prefs.ui_scale, 0.75..=2.0, 2);
heading(ui, "Views");
ui.checkbox(&mut prefs.invert_zoom, tr("Invert zoom in views"));
heading(ui, "Auto backup");
let mut minutes = prefs.autosave_minutes as f32;
if crate::widgets::slider(ui, tr("Autosave every (minutes, 0 = off)"), &mut minutes, 0.0..=MAX_AUTOSAVE_MINUTES, 0).changed() {
prefs.autosave_minutes = minutes.round() as u32;
}
let mut versions = prefs.autosave_versions as usize;
if number_row(ui, "Keep up to", &mut versions, 1..=Prefs::MAX_AUTOSAVE_VERSIONS as usize, "versions") {
prefs.autosave_versions = versions as u32;
}
#[cfg(not(target_arch = "wasm32"))]
ui.label(
egui::RichText::new(format!("{} {}", tr("The copies are numbered files in"), crate::user_dir("autosave").display()))
.small()
.color(crate::theme::Tokens::get(ui.ctx()).text_dim),
);
heading(ui, "Cooker");
crate::widgets::combo(ui, tr("Preview size while editing"), crate::preview_resolution::label(prefs.preview_size), |ui| {
crate::preview_resolution::choices(ui, &mut prefs.preview_size);
});
}
@@ -0,0 +1,20 @@
//! Preferences ▸ Graph: how the graph canvases respond and what opening a graph shows
use egui::Ui;
use super::heading;
use crate::MaterialCraftApp;
use crate::i18n::tr;
pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
let prefs = &mut app.ui.prefs;
heading(ui, "Common");
ui.checkbox(&mut prefs.tab_opens_node_search, tr("Tab key shows the node search"));
ui.checkbox(&mut prefs.wire_drop_opens_node_search, tr("Create nodes by dropping a wire on empty canvas"));
ui.checkbox(&mut prefs.view_outputs_on_open, tr("View outputs in 3D view when opening a graph"));
heading(ui, "Material graph");
ui.checkbox(&mut prefs.thumbnails, tr("Show node thumbnails"));
ui.checkbox(&mut prefs.snap_to_grid, tr("Snap to grid"));
}
@@ -0,0 +1,36 @@
//! Preferences ▸ Library: the library's previews, their cache and its layout
use egui::Ui;
use super::heading;
use crate::MaterialCraftApp;
use crate::i18n::tr;
/// Width of the Rebuild thumbnails button
const REBUILD_WIDTH: f32 = 360.0;
/// Returns true when the stored previews should be thrown away, which happens after the window drew
pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) -> bool {
let prefs = &mut app.ui.prefs;
let rebuild = ui.add_sized([ui.available_width().min(REBUILD_WIDTH), 24.0], egui::Button::new(tr("Rebuild thumbnails"))).clicked();
ui.label(tr("Previews rebuild as they come into view."));
heading(ui, "Library preview cache");
#[cfg(not(target_arch = "wasm32"))]
{
use materialcraft_engine::LibraryCachePrefs;
ui.horizontal(|ui| {
let label = ui.label(tr("Disk limit (MiB, 0 = off)"));
ui.add(egui::DragValue::new(&mut prefs.library_cache.disk_mib).range(0..=LibraryCachePrefs::MAX_DISK_MIB)).labelled_by(label.id);
});
ui.horizontal(|ui| {
let label = ui.label(tr("Maximum stored previews"));
ui.add(egui::DragValue::new(&mut prefs.library_cache.max_previews).range(1..=LibraryCachePrefs::MAX_PREVIEWS)).labelled_by(label.id);
});
}
heading(ui, "Layout");
ui.checkbox(&mut prefs.library_list, tr("Show the library as a list"));
rebuild
}
@@ -0,0 +1,34 @@
/// A page of the Preferences window, listed down its left side
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum PreferencesPage {
#[default]
General,
Projects,
Graph,
View3d,
Library,
Shortcuts,
}
impl PreferencesPage {
pub const ALL: [PreferencesPage; 6] = [
PreferencesPage::General,
PreferencesPage::Projects,
PreferencesPage::Graph,
PreferencesPage::View3d,
PreferencesPage::Library,
PreferencesPage::Shortcuts,
];
/// The English name in the page list; the UI translates it
pub fn label(self) -> &'static str {
match self {
PreferencesPage::General => "General",
PreferencesPage::Projects => "Projects",
PreferencesPage::Graph => "Graph",
PreferencesPage::View3d => "3D View",
PreferencesPage::Library => "Library",
PreferencesPage::Shortcuts => "Shortcuts",
}
}
}
@@ -0,0 +1,16 @@
use super::PreferencesPage;
use crate::state::Prefs;
/// What the open Preferences window keeps between frames
#[derive(Clone, Debug, Default, PartialEq)]
pub struct PreferencesState {
pub page: PreferencesPage,
/// The preferences as they were when the window opened or Apply was last pressed; Cancel goes back to them
pub applied: Option<Prefs>,
/// The Shortcuts page's search texts and filter
pub shortcut_search: String,
pub shortcut_key_search: String,
pub only_assigned: bool,
/// The library entry whose shortcut field waits for keys
pub capturing: Option<String>,
}
@@ -0,0 +1,41 @@
//! Preferences ▸ Projects: the 3D view a new package and a reset start from
use egui::Ui;
use materialcraft_engine::view_cmds::ENVIRONMENTS;
use super::heading;
use crate::MaterialCraftApp;
use crate::i18n::tr;
pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
let tokens = crate::theme::Tokens::get(ui.ctx());
let prefs = &mut app.ui.prefs;
let mut view = prefs.default_view3d.clone().unwrap_or_default();
heading(ui, "Default 3D view");
let saved = if prefs.default_view3d.is_some() { tr("A saved default is in use") } else { tr("The built-in default is in use") };
ui.label(egui::RichText::new(saved).color(tokens.text_dim));
ui.label(egui::RichText::new(tr("Save Current State As Default, in the 3D view's Scene menu, saves the whole view here")).small().color(tokens.text_dim));
let current = ENVIRONMENTS.iter().find(|(id, _)| *id == view.environment).map_or(view.environment.clone(), |(_, label)| tr(label).to_string());
crate::widgets::combo(ui, tr("Default environment"), current, |ui| {
for (id, label) in ENVIRONMENTS {
ui.selectable_value(&mut view.environment, (*id).to_string(), tr(label));
}
});
heading(ui, "Default lighting state");
ui.checkbox(&mut view.ambient.enabled, tr("Ambient Light"));
ui.checkbox(&mut view.lights[0].enabled, tr("Point Light 1"));
ui.checkbox(&mut view.lights[1].enabled, tr("Point Light 2"));
// Only an actual change makes a saved default out of the built-in one
if view != prefs.default_view3d.clone().unwrap_or_default() {
prefs.default_view3d = Some(view);
}
ui.add_space(8.0);
if ui.add_enabled(prefs.default_view3d.is_some(), egui::Button::new(tr("Use the built-in default"))).clicked() {
prefs.default_view3d = None;
}
}
@@ -0,0 +1,138 @@
//! Preferences ▸ Shortcuts: keys that add an atomic node or a graph item under the pointer
use egui::{Key, RichText, Ui};
use egui_phosphor::regular as icon;
use materialcraft_engine::node_library::LibraryItem;
use super::heading;
use crate::MaterialCraftApp;
use crate::i18n::tr;
use crate::theme::Tokens;
const ROW_HEIGHT: f32 = 28.0;
const ICON_SIDE: f32 = 22.0;
const LABEL_WIDTH: f32 = 260.0;
const FIELD_WIDTH: f32 = 220.0;
pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
let tokens = Tokens::get(ui.ctx());
ui.horizontal(|ui| {
heading(ui, "Node creation shortcuts");
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let any = !app.ui.prefs.node_shortcuts.is_empty();
if ui
.add_enabled_ui(any, |ui| {
crate::widgets::icon_button(ui, icon::ARROW_COUNTER_CLOCKWISE, tr("Remove every node creation shortcut"), false, 22.0)
})
.inner
.clicked()
{
app.ui.prefs.node_shortcuts.clear();
}
});
});
ui.label(RichText::new(tr("For the material graph: press the keys over the graph to add the node under the pointer")).color(tokens.text_dim));
let state = &mut app.ui.preferences;
ui.horizontal(|ui| {
let search = ui.add(egui::TextEdit::singleline(&mut state.shortcut_search).hint_text(tr("Search")).desired_width(LABEL_WIDTH));
crate::widgets::name(&search, egui::Role::SearchInput, "Search");
let by_key = ui.add(egui::TextEdit::singleline(&mut state.shortcut_key_search).hint_text(tr("Search by shortcut")).desired_width(FIELD_WIDTH));
crate::widgets::name(&by_key, egui::Role::SearchInput, "Search by shortcut");
ui.toggle_value(&mut state.only_assigned, tr("Show all assigned"));
});
ui.add_space(4.0);
let (search, key_search, only_assigned) = (state.shortcut_search.to_lowercase(), state.shortcut_key_search.to_lowercase(), state.only_assigned);
let entries: Vec<_> = app
.session
.library_entries()
.into_iter()
.filter(|entry| entry.missing.is_none() && crate::node_shortcuts::CATEGORIES.contains(&entry.category.as_str()))
.filter(|entry| search.is_empty() || entry.label.to_lowercase().contains(&search))
.filter(|entry| {
let shortcut = app.ui.prefs.node_shortcuts.get(&entry.id).map(|text| text.to_lowercase());
(!only_assigned || shortcut.is_some()) && (key_search.is_empty() || shortcut.is_some_and(|text| text.contains(&key_search)))
})
.collect();
capture(app, ui);
egui::ScrollArea::vertical().auto_shrink([false, false]).show_rows(ui, ROW_HEIGHT, entries.len(), |ui, rows| {
for entry in &entries[rows] {
ui.horizontal(|ui| {
ui.set_height(ROW_HEIGHT);
let picture = match &entry.item {
LibraryItem::Node { def } if def != "dot" => app.thumbs.library(ui.ctx(), def),
_ => None,
};
match picture {
Some(texture) => {
ui.add(egui::Image::new((texture, egui::vec2(ICON_SIDE, ICON_SIDE))).corner_radius(3));
}
None => {
ui.add_sized([ICON_SIDE, ICON_SIDE], egui::Label::new(RichText::new(icon::FLOW_ARROW).color(tokens.text_dim)));
}
}
let left = egui::Layout::left_to_right(egui::Align::Center);
ui.allocate_ui_with_layout(egui::vec2(LABEL_WIDTH, ROW_HEIGHT), left, |ui| {
ui.set_min_width(LABEL_WIDTH);
ui.add(egui::Label::new(tr(&entry.label)).truncate());
});
field(app, ui, &entry.id, &entry.label);
});
}
});
}
/// The button that shows an entry's shortcut and, clicked, waits for new keys
fn field(app: &mut MaterialCraftApp, ui: &mut Ui, entry: &str, label: &str) {
let waiting = app.ui.preferences.capturing.as_deref() == Some(entry);
let text = if waiting {
tr("Press keys, Backspace to clear, Esc to cancel").to_string()
} else {
app.ui.prefs.node_shortcuts.get(entry).map(|text| crate::menus::shortcut_label(ui.ctx(), text)).unwrap_or_default()
};
// A field-like button, framed even while empty, so every row shows where its keys go
let tokens = Tokens::get(ui.ctx());
let fill = if waiting { tokens.tool_active } else { tokens.field };
let field = egui::Button::new(text).fill(fill).stroke(egui::Stroke::new(1.0, tokens.field_border));
let button = ui.add_sized([FIELD_WIDTH, ROW_HEIGHT - 6.0], field);
crate::widgets::name(&button, egui::Role::Button, &format!("Shortcut for {label}"));
if button.clicked() {
app.ui.preferences.capturing = Some(entry.to_string());
}
}
/// While a field waits, the next key press with its modifiers becomes that entry's shortcut
fn capture(app: &mut MaterialCraftApp, ui: &mut Ui) {
let Some(entry) = app.ui.preferences.capturing.clone() else { return };
let pressed = ui.input(|input| {
input.events.iter().find_map(|event| match event {
egui::Event::Key { key, pressed: true, modifiers, .. } => Some((*modifiers, *key)),
_ => None,
})
});
let Some((modifiers, key)) = pressed else { return };
app.ui.preferences.capturing = None;
if modifiers.is_none() && key == Key::Escape {
return;
}
if modifiers.is_none() && matches!(key, Key::Backspace | Key::Delete) {
app.ui.prefs.node_shortcuts.remove(&entry);
return;
}
let Some(text) = crate::node_shortcuts::text(modifiers, key) else { return };
if let Some(command) = crate::node_shortcuts::taken_by(&text) {
app.toast(format!("{text} {} {command}", tr("is already the shortcut of")), true);
return;
}
// A shortcut adds one entry: giving it to this one takes it from any other
app.ui.prefs.node_shortcuts.retain(|_, assigned| *assigned != text);
app.ui.prefs.node_shortcuts.insert(entry, text);
}
@@ -0,0 +1,37 @@
//! Preferences ▸ 3D View: what a new 3D view shows and how its camera moves
use egui::Ui;
use materialcraft_engine::geom::view::Background;
use super::heading;
use crate::MaterialCraftApp;
use crate::i18n::tr;
/// The renderer's rays per pixel side, with the names the sample count list shows
const SAMPLE_COUNTS: [(u32, &str); 3] = [(1, "Low (1 spp)"), (2, "Medium (4 spp)"), (4, "High (16 spp)")];
/// The furthest the 3D camera's target may move from the mesh, in mesh radii
const MAX_PAN_LIMIT: f32 = 20.0;
pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
let prefs = &mut app.ui.prefs;
let mut view = prefs.default_view3d.clone().unwrap_or_default();
heading(ui, "Misc");
let mut environment_shown = view.background == Background::Environment;
if ui.checkbox(&mut environment_shown, tr("Environment shown behind the mesh by default")).changed() {
view.background = if environment_shown { Background::Environment } else { Background::default() };
}
let current = SAMPLE_COUNTS.iter().find(|(samples, _)| *samples == view.samples).map_or("", |(_, label)| label);
crate::widgets::combo(ui, tr("Sample count"), tr(current), |ui| {
for (samples, label) in SAMPLE_COUNTS {
ui.selectable_value(&mut view.samples, samples, tr(label));
}
});
if view != prefs.default_view3d.clone().unwrap_or_default() {
prefs.default_view3d = Some(view);
}
heading(ui, "Camera");
crate::widgets::slider(ui, tr("3D pan limit (mesh radii)"), &mut prefs.camera.pan_limit, 0.0..=MAX_PAN_LIMIT, 1);
crate::widgets::slider(ui, tr("3D pan speed"), &mut prefs.camera.pan_speed, 0.1..=4.0, 2);
}
+8 -2
View File
@@ -96,8 +96,14 @@ fn open_blocker(app: &MaterialCraftApp) -> Option<Blocker> {
if windows.package_save.is_some() {
return Some(Blocker::Dialog);
}
(app.expose_parameter_dialog.is_some() || windows.new_graph || windows.export || windows.preferences || windows.about || app.ui.explorer.rename.is_some())
.then_some(Blocker::Dialog)
(app.expose_parameter_dialog.is_some()
|| windows.new_graph
|| windows.export
|| windows.preferences
|| windows.about
|| windows.plugin_manager
|| app.ui.explorer.rename.is_some())
.then_some(Blocker::Dialog)
}
#[cfg(test)]
+44
View File
@@ -29,6 +29,34 @@ pub struct Prefs {
pub camera: CameraPrefs,
/// The 3D view a reset and a new document start from (3D view ▸ Scene ▸ Save Current State As Default)
pub default_view3d: Option<materialcraft_engine::View3d>,
/// How many packages File ▸ Recent packages lists
pub recent_limit: usize,
/// Scrolling up zooms out in the graph, the 2D view and the 3D view
pub invert_zoom: bool,
/// Autosaved copies kept for each package, newest first
pub autosave_versions: u32,
/// Tab over the graph opens the node search
pub tab_opens_node_search: bool,
/// A wire dropped on empty canvas opens the node search to connect a new node
pub wire_drop_opens_node_search: bool,
/// Opening a material graph shows its outputs in the 3D view
pub view_outputs_on_open: bool,
/// Node creation shortcuts: library entry id to shortcut text ("Ctrl+Shift+B")
pub node_shortcuts: std::collections::BTreeMap<String, String>,
/// Windows ▸ Main toolbar
pub show_toolbar: bool,
}
impl Prefs {
/// What a wheel step up does to the zoom: 1 zooms in, -1 zooms out when the zoom is inverted
pub fn zoom_direction(&self) -> f32 {
if self.invert_zoom { -1.0 } else { 1.0 }
}
/// Most packages the recent list can hold
pub const MAX_RECENT: usize = 30;
/// Most autosaved copies kept for a package
pub const MAX_AUTOSAVE_VERSIONS: u32 = 50;
}
impl Default for Prefs {
@@ -48,6 +76,14 @@ impl Default for Prefs {
show_home: true,
camera: CameraPrefs::default(),
default_view3d: None,
recent_limit: 10,
invert_zoom: false,
autosave_versions: 6,
tab_opens_node_search: true,
wire_drop_opens_node_search: true,
view_outputs_on_open: true,
node_shortcuts: Default::default(),
show_toolbar: true,
}
}
}
@@ -66,11 +102,17 @@ mod tests {
assert!(old.snap_to_grid);
assert_eq!(old.history, HistoryPrefs::default());
assert_eq!(old.library_cache, LibraryCachePrefs::default());
assert_eq!((old.recent_limit, old.autosave_versions, old.invert_zoom), (10, 6, false));
assert!(old.tab_opens_node_search && old.wire_drop_opens_node_search && old.view_outputs_on_open && old.show_toolbar);
assert!(old.node_shortcuts.is_empty());
let p = Prefs {
camera: CameraPrefs { pan_limit: 8.0, pan_speed: 0.5 },
history: HistoryPrefs { undo_limit: 500 },
library_cache: LibraryCachePrefs { disk_mib: 512, max_previews: 12000 },
recent_limit: 4,
invert_zoom: true,
node_shortcuts: [("blur".to_string(), "Ctrl+Shift+B".to_string())].into(),
..Prefs::default()
};
@@ -79,6 +121,8 @@ mod tests {
assert_eq!(v["camera"], serde_json::json!({"panLimit": 8.0, "panSpeed": 0.5}));
assert_eq!(v["history"]["undoLimit"], 500);
assert_eq!(v["libraryCache"], serde_json::json!({"diskMib": 512, "maxPreviews": 12000}));
assert_eq!((v["recentLimit"].clone(), v["invertZoom"].clone()), (serde_json::json!(4), serde_json::json!(true)));
assert_eq!(v["nodeShortcuts"], serde_json::json!({"blur": "Ctrl+Shift+B"}));
assert_eq!(serde_json::from_value::<Prefs>(v).unwrap(), p);
}
+28 -3
View File
@@ -35,11 +35,29 @@ pub struct UiState {
pub new_graph_template: String,
pub new_graph_name: String,
pub new_graph_size: u32,
pub new_graph_height: u32,
/// The width and height of a new graph change together
pub new_graph_linked: bool,
/// The category of templates shown; `None` lists them all
#[serde(skip)]
pub new_graph_category: Option<materialcraft_engine::core::GraphKind>,
/// The package a new graph goes in; `None` is a new package
#[serde(skip)]
pub new_graph_package: Option<u64>,
/// A card was double-clicked: create on this frame
#[serde(skip)]
pub new_graph_create_now: bool,
/// Export window: the saved settings, the open tab and the copy the open window edits
pub export: crate::export::ExportSettings,
pub export_tab: crate::export::ExportTab,
#[serde(skip)]
pub export_draft: Option<crate::export::ExportSettings>,
/// The open Preferences window's page, the preferences Cancel returns to, and the Shortcuts page's search
#[serde(skip)]
pub preferences: crate::preferences::PreferencesState,
/// The Plugin Manager's filter text
#[serde(skip)]
pub plugin_filter: String,
/// Frame the whole graph on the next frame
#[serde(skip)]
pub frame_all: bool,
@@ -67,19 +85,26 @@ impl Default for UiState {
new_graph_template: "pbr".into(),
new_graph_name: "New_graph".into(),
new_graph_size: 1024,
new_graph_height: 1024,
new_graph_linked: true,
new_graph_category: None,
new_graph_package: None,
new_graph_create_now: false,
export: crate::export::ExportSettings::default(),
export_tab: crate::export::ExportTab::default(),
export_draft: None,
preferences: Default::default(),
plugin_filter: String::new(),
frame_all: true,
}
}
}
impl UiState {
/// Remember `path` at the top of the recent list
/// Remember `path` at the top of the recent list, keeping as many as the preferences ask for
pub fn add_recent(&mut self, path: &str) {
self.recent.retain(|p| p != path);
self.recent.retain(|recent| recent != path);
self.recent.insert(0, path.to_string());
self.recent.truncate(12);
self.recent.truncate(self.prefs.recent_limit.clamp(1, Prefs::MAX_RECENT));
}
}
+1
View File
@@ -10,6 +10,7 @@ pub struct Windows {
pub preferences: bool,
pub shortcuts: bool,
pub home: bool,
pub plugin_manager: bool,
#[cfg(any(test, target_arch = "wasm32"))]
#[serde(skip)]
pub package_save: Option<crate::web_files::PackageSave>,
+90
View File
@@ -0,0 +1,90 @@
//! The template cards of the New graph dialog and the home screen: a rendered preview, a name,
//! the kind of graph, and an information button that says what the template holds
use egui::{Color32, RichText, Sense, Ui, vec2};
use egui_phosphor::regular as icon;
use materialcraft_engine::core::GraphKind;
use crate::i18n::tr;
use crate::theme::Tokens;
pub(crate) const CARD_SIZE: egui::Vec2 = vec2(140.0, 196.0);
const PREVIEW_SIDE: f32 = 96.0;
/// A template a new graph can start from
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct TemplateCard {
/// The `file.new` template id; function graphs have one template
pub id: &'static str,
pub label: &'static str,
pub kind: GraphKind,
pub description: &'static str,
}
/// The id the function graph card goes by
pub(crate) const FUNCTION_TEMPLATE: &str = "function";
/// Every card: the material templates the engine has, then the function graph
pub(crate) fn cards() -> Vec<TemplateCard> {
let material =
materialcraft_engine::samples::TEMPLATES.iter().map(|(id, label)| TemplateCard { id, label, kind: GraphKind::Material, description: description(id) });
let function = TemplateCard { id: FUNCTION_TEMPLATE, label: "Function graph", kind: GraphKind::Function, description: description(FUNCTION_TEMPLATE) };
material.chain(std::iter::once(function)).collect()
}
/// What a template holds, in a sentence
fn description(id: &str) -> &'static str {
match id {
"empty" => "An empty material graph",
"pbr" => "Base color, normal, roughness, metallic, height and ambient occlusion outputs, ready to connect",
"atomics" => "A small graph of atomic nodes working together",
FUNCTION_TEMPLATE => "An empty function graph: a value computed from function nodes",
_ => "",
}
}
impl TemplateCard {
/// The name the kind of graph goes by under the card's title
pub fn kind_label(&self) -> &'static str {
if self.kind == GraphKind::Function { "Function" } else { "Material" }
}
}
/// Draw a card; `preview` is its rendered picture once ready. Returns the card's response
pub(crate) fn show(ui: &mut Ui, card: &TemplateCard, chosen: bool, preview: Option<egui::TextureId>) -> egui::Response {
let tokens = Tokens::get(ui.ctx());
let (rect, response) = ui.allocate_exact_size(CARD_SIZE, Sense::click());
crate::widgets::name(&response, egui::Role::ListItem, card.label);
let fill = if chosen || response.hovered() { tokens.row_hover } else { tokens.row };
ui.painter().rect_filled(rect, 6.0, fill);
if chosen {
ui.painter().rect_stroke(rect, 6.0, egui::Stroke::new(1.5, tokens.accent), egui::StrokeKind::Inside);
}
let picture = egui::Rect::from_center_size(egui::pos2(rect.center().x, rect.top() + 18.0 + PREVIEW_SIDE * 0.5), vec2(PREVIEW_SIDE, PREVIEW_SIDE));
match (preview, card.kind) {
(Some(texture), _) => {
ui.painter().image(texture, picture, egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)), Color32::WHITE);
}
(None, GraphKind::Function) => {
ui.painter().text(picture.center(), egui::Align2::CENTER_CENTER, icon::FUNCTION, egui::FontId::proportional(48.0), tokens.text_dim);
}
(None, _) => {
ui.painter().circle_filled(picture.center(), PREVIEW_SIDE * 0.45, tokens.separator);
}
}
let title = ui.painter().layout(tr(card.label).to_string(), egui::FontId::proportional(13.0), tokens.text_strong, CARD_SIZE.x - 12.0);
ui.painter().galley(egui::pos2(rect.center().x - title.size().x * 0.5, picture.bottom() + 14.0), title, tokens.text_strong);
let kind = tr(card.kind_label());
ui.painter().text(egui::pos2(rect.center().x, rect.bottom() - 18.0), egui::Align2::CENTER_CENTER, kind, egui::FontId::proportional(11.0), tokens.text_dim);
// The information button tells what the template holds
let info = egui::Rect::from_center_size(rect.right_top() + vec2(-16.0, 16.0), vec2(18.0, 18.0));
let info_response = ui.interact(info, response.id.with("info"), Sense::hover());
ui.painter().text(info.center(), egui::Align2::CENTER_CENTER, icon::INFO, egui::FontId::proportional(16.0), tokens.text_dim);
info_response.on_hover_text(RichText::new(tr(card.description)));
response
}
+5 -1
View File
@@ -41,7 +41,11 @@ pub fn status_bar(app: &mut MaterialCraftApp, ui: &mut Ui) {
egui::Panel::bottom("status_bar").exact_size(22.0).frame(egui::Frame::NONE.fill(tk.chrome).inner_margin(egui::Margin::symmetric(8, 0))).show(ui, |ui| {
ui.horizontal_centered(|ui| {
let busy = app.cooker.busy();
if busy {
if app.cooker.suspended {
ui.label(
RichText::new(tr("Engine suspended: choose Suspend engine in the Tools menu again (Shift+Escape) to resume")).size(11.0).color(tk.warning),
);
} else if busy {
ui.add(egui::Spinner::new().size(12.0));
ui.label(RichText::new(tr("Computing...")).size(11.0).color(tk.text_dim));
} else if !app.status.is_empty() {
+1 -1
View File
@@ -156,7 +156,7 @@ fn place(app: &mut MaterialCraftApp, ui: &Ui, response: &Response, rect: Rect, s
}
if response.hovered() {
let scroll = ui.input(|input| input.smooth_scroll_delta.y);
let scroll = app.ui.prefs.zoom_direction() * ui.input(|input| input.smooth_scroll_delta.y);
if scroll != 0.0 {
// One notch of a mouse wheel scrolls one line, and zooms one step
let points_per_notch = ui.ctx().options(|options| options.input_options.line_scroll_speed).max(1.0);
+1 -1
View File
@@ -56,7 +56,7 @@ pub(super) fn handle(app: &mut MaterialCraftApp, ui: &Ui, response: &Response, a
}
if response.hovered() {
let scroll = ui.input(|input| input.smooth_scroll_delta.y);
let scroll = app.ui.prefs.zoom_direction() * ui.input(|input| input.smooth_scroll_delta.y);
if scroll.abs() > 0.0 {
// One notch of a mouse wheel scrolls one line
let points_per_notch = ui.ctx().options(|options| options.input_options.line_scroll_speed).max(1.0);
+43 -218
View File
@@ -11,8 +11,7 @@ use serde_json::{Value, json};
use crate::MaterialCraftApp;
use crate::i18n::tr;
use crate::shell::modality::Modality;
use crate::theme::{Accent, Brightness, Tokens};
use crate::theme::Tokens;
/// Template previews for the New graph dialog (rendered in the background on first open)
#[derive(Default)]
@@ -75,19 +74,24 @@ thread_local! {
static TEMPLATES: std::cell::RefCell<TemplatePreviews> = std::cell::RefCell::new(TemplatePreviews::default());
}
/// A template's rendered preview, once the background render has finished
pub(crate) fn template_preview(ctx: &egui::Context, id: &str) -> Option<egui::TextureId> {
TEMPLATES.with(|previews| previews.borrow_mut().get(ctx, id))
}
pub fn show(app: &mut MaterialCraftApp, ctx: &egui::Context) {
if let Some(error) = app.thumbs.tick(ctx, &app.session.library, app.cooker.busy() || app.session.dirty) {
app.toast(error, true);
}
if app.ui.windows.new_graph {
new_graph(app, ctx);
crate::new_graph_dialog::show(app, ctx);
}
if app.ui.windows.export {
crate::export::show(app, ctx);
}
if app.ui.windows.preferences {
preferences(app, ctx);
crate::preferences::show(app, ctx);
}
if app.ui.windows.about {
about(app, ctx);
@@ -96,7 +100,10 @@ pub fn show(app: &mut MaterialCraftApp, ctx: &egui::Context) {
shortcuts(app, ctx);
}
if app.ui.windows.home {
home(app, ctx);
crate::home_screen::show(app, ctx);
}
if app.ui.windows.plugin_manager {
crate::plugin_manager::show(app, ctx);
}
crate::unsaved::show(app, ctx);
@@ -120,129 +127,6 @@ pub(crate) fn modal(ctx: &egui::Context, id: &str, title: &str, open: &mut bool,
.show(ctx, body);
}
fn new_graph(app: &mut MaterialCraftApp, ctx: &egui::Context) {
use materialcraft_engine::core::GraphKind;
let mut open = true;
let mut create = false;
modal(ctx, "new-graph", tr("New graph"), &mut open, vec2(440.0, 290.0), |ui| {
ui.horizontal(|ui| {
ui.selectable_value(&mut app.ui.new_graph_kind, GraphKind::Material, tr("Graph"));
ui.selectable_value(&mut app.ui.new_graph_kind, GraphKind::Function, tr("Function Graph"));
});
ui.add_space(12.0);
ui.label(tr("Graph name"));
let name = ui.text_edit_singleline(&mut app.ui.new_graph_name);
crate::widgets::name(&name, egui::Role::TextInput, "Graph name");
if app.ui.new_graph_kind == GraphKind::Material {
ui.add_space(8.0);
crate::widgets::combo(ui, tr("Template"), app.ui.new_graph_template.clone(), |ui| {
for (id, label) in materialcraft_engine::samples::TEMPLATES {
ui.selectable_value(&mut app.ui.new_graph_template, id.to_string(), tr(label));
}
});
let size = egui::ComboBox::from_label(tr("Size")).selected_text(format!("{} px", app.ui.new_graph_size)).show_ui(ui, |ui| {
for size in [256u32, 512, 1024, 2048, 4096] {
ui.selectable_value(&mut app.ui.new_graph_size, size, format!("{size} px"));
}
});
crate::widgets::name(&size.response, egui::Role::ComboBox, "Size");
}
ui.add_space(12.0);
ui.label(format!("{}: {}", tr("Package"), app.session.pkg.name));
ui.add_space(16.0);
ui.horizontal(|ui| {
if ui.add(crate::widgets::primary_button(ui, tr("Create"))).clicked() {
create = true;
}
if ui.button(tr("Cancel")).clicked() {
app.ui.windows.new_graph = false;
}
});
});
if create {
let parameters =
json!({"kind": app.ui.new_graph_kind, "template": app.ui.new_graph_template, "name": app.ui.new_graph_name, "size": app.ui.new_graph_size});
if app.run("file.new", parameters).is_some() {
app.ui.frame_all = true;
open = false;
}
}
if !open {
app.ui.windows.new_graph = false;
}
}
fn preferences(app: &mut MaterialCraftApp, ctx: &egui::Context) {
let mut open = true;
let mut clear_cache = false;
modal(ctx, "prefs", tr("Preferences"), &mut open, vec2(400.0, 500.0), |ui| {
let p = &mut app.ui.prefs;
let current_lang = crate::i18n::current();
crate::widgets::combo(ui, tr("Language"), current_lang.name, |ui| {
for l in &crate::i18n::LANGUAGES {
if ui.selectable_label(p.language == l.code, l.name).clicked() {
p.language = l.code.to_owned();
crate::i18n::set_language(&p.language);
}
}
});
crate::widgets::combo(ui, tr("Brightness"), tr(p.brightness.label()), |ui| {
for b in Brightness::ALL {
ui.selectable_value(&mut p.brightness, b, tr(b.label()));
}
});
crate::widgets::combo(ui, tr("Accent color"), tr(p.accent.label()), |ui| {
for a in Accent::ALL {
ui.selectable_value(&mut p.accent, a, tr(a.label()));
}
});
crate::widgets::slider(ui, tr("Interface scale"), &mut p.ui_scale, 0.75..=2.0, 2);
let mut auto = p.autosave_minutes as f32;
if crate::widgets::slider(ui, tr("Autosave every (minutes, 0 = off)"), &mut auto, 0.0..=60.0, 0).changed() {
p.autosave_minutes = auto.round() as u32;
}
let mut undo_limit = p.history.undo_limit as f32;
if crate::widgets::slider(ui, tr("Undo history (steps)"), &mut undo_limit, 1.0..=10_000.0, 0).changed() {
p.history.undo_limit = undo_limit.round() as u32;
}
crate::widgets::combo(ui, tr("Preview size while editing"), crate::preview_resolution::label(p.preview_size), |ui| {
crate::preview_resolution::choices(ui, &mut p.preview_size);
});
ui.checkbox(&mut p.thumbnails, tr("Show node thumbnails"));
ui.separator();
ui.label(tr("Library preview cache"));
#[cfg(not(target_arch = "wasm32"))]
{
use materialcraft_engine::LibraryCachePrefs;
ui.horizontal(|ui| {
let label = ui.label(tr("Disk limit (MiB, 0 = off)"));
ui.add(egui::DragValue::new(&mut p.library_cache.disk_mib).range(0..=LibraryCachePrefs::MAX_DISK_MIB)).labelled_by(label.id);
});
ui.horizontal(|ui| {
let label = ui.label(tr("Maximum stored previews"));
ui.add(egui::DragValue::new(&mut p.library_cache.max_previews).range(1..=LibraryCachePrefs::MAX_PREVIEWS)).labelled_by(label.id);
});
}
clear_cache = ui.button(tr("Clear cache")).clicked();
ui.label(tr("Previews rebuild as they come into view."));
ui.separator();
crate::widgets::slider(ui, tr("3D pan limit (mesh radii)"), &mut p.camera.pan_limit, 0.0..=20.0, 1);
crate::widgets::slider(ui, tr("3D pan speed"), &mut p.camera.pan_speed, 0.1..=4.0, 2);
});
if clear_cache {
app.run("library.cache.clear", serde_json::json!({}));
app.apply_prefs();
}
if !open {
app.ui.windows.preferences = false;
}
}
fn about(app: &mut MaterialCraftApp, ctx: &egui::Context) {
let mut open = true;
modal(ctx, "about", tr("About MaterialCraft"), &mut open, vec2(400.0, 260.0), |ui| {
@@ -297,96 +181,6 @@ fn shortcuts(app: &mut MaterialCraftApp, ctx: &egui::Context) {
}
}
fn home(app: &mut MaterialCraftApp, ctx: &egui::Context) {
let mut open = true;
let mut create: Option<(&str, &str)> = None;
let modality = Modality::capture(app, ctx);
let free = !modality.is_blocked();
modal(ctx, "home", tr("Home"), &mut open, vec2(760.0, 470.0), |ui| {
let tk = Tokens::get(ui.ctx());
ui.horizontal_top(|ui| {
// Left rail: actions and links
ui.vertical(|ui| {
ui.set_width(150.0);
if ui.add_enabled(free, 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.add_enabled(modality.allows("file.open"), egui::Button::new(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| {
if !free {
ui.disable();
}
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 free && 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 free && 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.add_enabled(free, egui::Link::new(&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;
}
}
pub fn console(app: &mut MaterialCraftApp, ui: &mut Ui) {
let tk = Tokens::get(ui.ctx());
let console_line = |text: String, color: Color32| RichText::new(text).monospace().size(11.0).color(color);
@@ -564,6 +358,10 @@ pub fn file_action(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) ->
crate::export::open(app, crate::export::ExportTab::Mcmat);
true
}
"file.saveAll" => {
save_all(app);
true
}
"file.sendToTextureCraft" => {
if app.run("file.sendToTextureCraft", json!({})).is_some() {
app.toast(tr("Sent to TextureCraft: find it on the shelf under My smart materials"), false);
@@ -598,6 +396,33 @@ pub fn file_action(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) ->
}
}
/// File ▸ Save all: save every modified package with a file and say which still need Save as
#[cfg(not(target_arch = "wasm32"))]
fn save_all(app: &mut MaterialCraftApp) {
let Some(reply) = app.run("file.saveAll", json!({})) else { return };
let saved: Vec<String> = reply["saved"].as_array().into_iter().flatten().filter_map(|path| path.as_str().map(str::to_string)).collect();
for path in &saved {
app.ui.add_recent(path);
}
let names = |key: &str| reply[key].as_array().into_iter().flatten().filter_map(|name| name.as_str()).collect::<Vec<_>>().join(", ");
let without_file = names("withoutFile");
let failed: Vec<String> = reply["failed"]
.as_array()
.into_iter()
.flatten()
.map(|failure| format!("{}: {}", failure["package"].as_str().unwrap_or_default(), failure["error"].as_str().unwrap_or_default()))
.collect();
if !failed.is_empty() {
app.toast(format!("{} {}", tr("Not saved:"), failed.join("; ")), true);
} else if !without_file.is_empty() {
app.toast(format!("{} {} ({without_file})", saved.len(), tr("saved; use Save as for packages without a file")), false);
} else {
app.toast(format!("{} {}", saved.len(), tr("packages saved")), false);
}
}
/// Whether File ▸ Save writes straight to the package's path (a package opened from a URL has none to write to)
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn has_local_path(app: &MaterialCraftApp) -> bool {
+3 -3
View File
@@ -38,14 +38,14 @@ mod home_modality_tests {
fn home_actions_are_live_when_nothing_blocks_them() {
let harness = harness(|_| {});
assert!(open_package(&harness));
assert!(!harness.get(By::new().role(egui::accesskit::Role::Button).label("New graph")).accesskit_node().is_disabled());
assert!(!harness.get(By::new().role(egui::accesskit::Role::Button).label_contains("New graph")).accesskit_node().is_disabled());
}
#[test]
fn open_package_is_off_behind_a_dialog_and_home_stays_open() {
let harness = harness(|app| app.ui.windows.about = true);
assert!(!open_package(&harness));
assert!(harness.get(By::new().role(egui::accesskit::Role::Button).label("New graph")).accesskit_node().is_disabled());
assert!(harness.get(By::new().role(egui::accesskit::Role::Button).label_contains("New graph")).accesskit_node().is_disabled());
assert!(harness.state().ui.windows.home);
}
@@ -62,7 +62,7 @@ mod home_modality_tests {
#[test]
fn a_sample_tile_and_a_recent_link_wait_behind_a_file_dialog() {
let mut harness = harness(file_dialog);
assert!(harness.get(By::new().role(egui::accesskit::Role::Link).label("recent.sbs")).accesskit_node().is_disabled());
assert!(harness.get(By::new().role(egui::accesskit::Role::Button).label_contains("recent.sbs")).accesskit_node().is_disabled());
let graphs = harness.state().session.pkg.graphs.len();
let (_, sample) = materialcraft_engine::samples::TEMPLATES.iter().find(|(id, _)| !matches!(*id, "empty" | "pbr")).unwrap();
harness.get(By::new().role(egui::accesskit::Role::ListItem).label(sample)).click();
+3
View File
@@ -7,9 +7,12 @@ mod dialogs;
mod export_window;
mod graph_properties;
mod interface_scale;
mod menu_bar;
mod new_graph_dialog;
mod node_look;
mod normal_maps;
mod numeric_input;
mod preferences_window;
mod preview_resolution;
mod resolution;
mod search;
+72
View File
@@ -0,0 +1,72 @@
//! The menu bar's own items: suspending and resuming the engine, the toolbar switch and the Plugin Manager
use egui::accesskit::Role;
use egui::vec2;
use egui_kittest::Harness;
use egui_kittest::kittest::{By, Queryable};
use materialcraft_ui_egui::{MaterialCraftApp, UiState, menus};
fn harness() -> Harness<'static, MaterialCraftApp> {
let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), UiState::default());
app.ui.windows.home = false;
let mut harness = Harness::builder().with_size(vec2(1600.0, 960.0)).with_pixels_per_point(1.0).build_ui_state(
|ui, app: &mut MaterialCraftApp| {
app.step(&ui.ctx().clone());
app.draw(ui);
},
app,
);
harness.run_steps(6);
harness
}
fn choose(harness: &mut Harness<'static, MaterialCraftApp>, menu: &str, item: &str) {
harness.get(By::new().role(Role::Button).label(menu)).click();
harness.run_steps(3);
harness.get(By::new().role(Role::Button).label_contains(item)).click();
harness.run_steps(3);
}
#[test]
fn a_suspended_engine_cooks_nothing_until_it_is_resumed() {
let mut harness = harness();
for _ in 0..200 {
harness.step();
if !harness.state().cooker.busy() && !harness.state().session.dirty {
break;
}
std::thread::sleep(std::time::Duration::from_millis(5));
}
choose(&mut harness, "Tools", "Suspend engine");
assert!(harness.state().cooker.suspended);
harness.state_mut().session.dirty = true;
harness.run_steps(5);
assert!(!harness.state().cooker.busy() && harness.state().session.dirty, "the edit waits");
harness.key_press_modifiers(egui::Modifiers::SHIFT, egui::Key::Escape);
harness.run_steps(2);
assert!(!harness.state().cooker.suspended, "Shift+Esc resumes the engine");
assert!(harness.state().cooker.busy() || !harness.state().session.dirty, "and what changed cooks");
}
#[test]
fn cancel_rendering_is_only_offered_while_a_cook_runs() {
let harness = harness();
assert_eq!(menus::enabled(harness.state(), "ui.cook.cancel"), harness.state().cooker.busy());
}
#[test]
fn the_main_toolbar_and_the_plugin_manager_open_from_the_menus() {
let mut harness = harness();
assert!(harness.query_by_label("Open package... (Ctrl+O)").is_some());
choose(&mut harness, "Windows", "Main toolbar");
assert!(!harness.state().ui.prefs.show_toolbar);
assert!(harness.query_by_label("Open package... (Ctrl+O)").is_none(), "the toolbar is hidden");
choose(&mut harness, "Tools", "Plugin Manager...");
assert!(harness.state().ui.windows.plugin_manager);
assert!(harness.query_by_label_contains("MaterialCraft does not load plugins yet").is_some());
}
@@ -0,0 +1,65 @@
//! File ▸ New ▸ Graph: template cards, the size of the graph and the package it goes in
use egui::accesskit::Role;
use egui::vec2;
use egui_kittest::Harness;
use egui_kittest::kittest::{By, Queryable};
use materialcraft_ui_egui::{MaterialCraftApp, UiState, menus};
fn harness() -> Harness<'static, MaterialCraftApp> {
let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), UiState::default());
app.ui.windows.home = false;
let mut harness = Harness::builder().with_size(vec2(1600.0, 960.0)).with_pixels_per_point(1.0).build_ui_state(
|ui, app: &mut MaterialCraftApp| {
app.step(&ui.ctx().clone());
app.draw(ui);
},
app,
);
harness.run_steps(6);
harness
}
fn open(harness: &mut Harness<'static, MaterialCraftApp>, id: &str) {
let context = harness.ctx.clone();
menus::invoke(harness.state_mut(), &context, id);
harness.run_steps(4);
}
#[test]
fn a_card_and_an_unlinked_size_make_the_graph_in_the_active_package() {
let mut harness = harness();
let packages = harness.state().session.open_packages().len();
open(&mut harness, "ui.newGraph");
harness.get(By::new().role(Role::ListItem).label("Atomic sample")).click();
harness.run_steps(2);
harness.get(By::new().role(Role::Button).label("Keep the width and height the same")).click();
harness.run_steps(2);
harness.state_mut().ui.new_graph_size = 512;
harness.state_mut().ui.new_graph_height = 2048;
harness.get(By::new().role(Role::Button).label("Create")).click();
harness.run_steps(6);
let session = &harness.state().session;
assert!(!harness.state().ui.windows.new_graph);
assert_eq!(session.open_packages().len(), packages);
assert_eq!(session.graph().unwrap().size, [9, 11]);
assert!(!session.graph().unwrap().nodes.is_empty(), "the atomic sample's nodes");
}
#[test]
fn a_function_graph_can_go_in_a_new_package() {
let mut harness = harness();
let packages = harness.state().session.open_packages().len();
open(&mut harness, "ui.newFunctionGraph");
assert!(harness.query_by_label("Size").is_none(), "a function graph has no size");
harness.state_mut().ui.new_graph_package = None;
harness.get(By::new().role(Role::Button).label("Create")).click();
harness.run_steps(6);
let session = &harness.state().session;
assert_eq!(session.open_packages().len(), packages + 1);
assert!(session.graph().unwrap().function.is_some());
}
@@ -0,0 +1,96 @@
//! Edit ▸ Preferences: pages, OK, Cancel and Apply, and the node creation shortcuts they set
use egui::accesskit::Role;
use egui::{Key, Modifiers, vec2};
use egui_kittest::Harness;
use egui_kittest::kittest::{By, Queryable};
use materialcraft_ui_egui::preferences::PreferencesPage;
use materialcraft_ui_egui::{MaterialCraftApp, UiState};
fn harness() -> Harness<'static, MaterialCraftApp> {
let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), UiState::default());
app.ui.windows.home = false;
let mut harness = Harness::builder().with_size(vec2(1600.0, 960.0)).with_pixels_per_point(1.0).build_ui_state(
|ui, app: &mut MaterialCraftApp| {
app.step(&ui.ctx().clone());
app.draw(ui);
},
app,
);
harness.run_steps(6);
harness
}
fn open(harness: &mut Harness<'static, MaterialCraftApp>) {
harness.state_mut().ui.windows.preferences = true;
harness.run_steps(4);
}
fn click(harness: &mut Harness<'static, MaterialCraftApp>, role: Role, label: &str) {
harness.get(By::new().role(role).label(label)).click();
harness.run_steps(4);
}
#[test]
fn cancel_returns_to_the_preferences_of_the_last_apply() {
let mut harness = harness();
open(&mut harness);
click(&mut harness, Role::CheckBox, "Invert zoom in views");
assert!(harness.state().ui.prefs.invert_zoom, "a change shows at once");
click(&mut harness, Role::Button, "Apply");
click(&mut harness, Role::Tab, "Graph");
assert_eq!(harness.state().ui.preferences.page, PreferencesPage::Graph);
click(&mut harness, Role::CheckBox, "Tab key shows the node search");
assert!(!harness.state().ui.prefs.tab_opens_node_search);
click(&mut harness, Role::Button, "Cancel");
let prefs = &harness.state().ui.prefs;
assert!(prefs.invert_zoom, "the applied change stays");
assert!(prefs.tab_opens_node_search, "the change after Apply is undone");
assert!(!harness.state().ui.windows.preferences);
open(&mut harness);
click(&mut harness, Role::CheckBox, "View outputs in 3D view when opening a graph");
click(&mut harness, Role::Button, "OK");
assert!(!harness.state().ui.prefs.view_outputs_on_open && !harness.state().session.view_outputs_on_open, "OK keeps the change and the session follows it");
assert!(!harness.state().ui.windows.preferences);
}
#[test]
fn a_shortcut_is_captured_refused_when_taken_and_adds_its_node_over_the_graph() {
let mut harness = harness();
open(&mut harness);
click(&mut harness, Role::Tab, "Shortcuts");
click(&mut harness, Role::Button, "Shortcut for Blur");
harness.key_press_modifiers(Modifiers::COMMAND, Key::S);
harness.run_steps(3);
assert!(harness.state().ui.prefs.node_shortcuts.is_empty(), "Ctrl+S already saves");
click(&mut harness, Role::Button, "Shortcut for Blur");
harness.key_press_modifiers(Modifiers::COMMAND | Modifiers::SHIFT, Key::B);
harness.run_steps(3);
assert_eq!(harness.state().ui.prefs.node_shortcuts.get("node:blur").map(String::as_str), Some("Ctrl+Shift+B"));
// The same keys on another entry move the shortcut there; the search brings it into view
harness.state_mut().ui.preferences.shortcut_search = "levels".into();
harness.run_steps(2);
click(&mut harness, Role::Button, "Shortcut for Levels");
harness.key_press_modifiers(Modifiers::COMMAND | Modifiers::SHIFT, Key::B);
harness.run_steps(3);
assert_eq!(harness.state().ui.prefs.node_shortcuts.len(), 1);
assert!(harness.state().ui.prefs.node_shortcuts.contains_key("node:levels"));
click(&mut harness, Role::Button, "OK");
let nodes = harness.state().session.graph().unwrap().nodes.len();
let canvas = harness.state().graph.view;
harness.hover_at(canvas.center());
harness.run_steps(2);
harness.key_press_modifiers(Modifiers::COMMAND | Modifiers::SHIFT, Key::B);
harness.run_steps(3);
let graph = harness.state().session.graph().unwrap();
assert_eq!(graph.nodes.len(), nodes + 1);
assert_eq!(graph.nodes.last().unwrap().def, "levels");
}
+11 -7
View File
@@ -31,6 +31,9 @@ mod library;
#[path = "snapshot/menu.rs"]
mod menu;
#[path = "snapshot/menus_and_preferences.rs"]
mod menus_and_preferences;
#[path = "snapshot/node_search.rs"]
mod node_search;
@@ -766,11 +769,9 @@ fn empty_startup_can_create_a_template() {
}
harness.get_by_label("New graph...").click();
settle(&mut harness, 4);
harness.get(By::new().role(egui::accesskit::Role::ComboBox).label("Template")).click();
settle(&mut harness, 2);
harness.get_by_label("Atomic sample").click();
harness.get(By::new().role(egui::accesskit::Role::ListItem).label("Atomic sample")).click();
settle(&mut harness, 4);
harness.get_by_label("Create").click();
harness.get(By::new().role(egui::accesskit::Role::Button).label("Create")).click();
settle(&mut harness, 40);
assert_eq!(harness.state().session.pkg.graphs.len(), 2);
assert!(!harness.state().session.graph().unwrap().nodes.is_empty());
@@ -1166,10 +1167,10 @@ fn annotations_and_function_graph_creation() {
harness.state_mut().ui.windows.new_graph = true;
settle(&mut harness, 3);
harness.get_by_label("Function Graph").click();
harness.get(By::new().role(egui::accesskit::Role::ListItem).label("Function graph")).click();
settle(&mut harness, 3);
save(&mut harness, &directory, "new-function-graph");
harness.get_by_label("Create").click();
harness.get(By::new().role(egui::accesskit::Role::Button).label("Create")).click();
settle(&mut harness, 3);
assert_eq!(harness.state().session.graph().unwrap().kind(), GraphKind::Function);
@@ -1696,11 +1697,14 @@ fn library_cache_preferences() {
settle(&mut h, 4);
h.state_mut().ui.windows.preferences = true;
settle(&mut h, 4);
// The dock has a Library tab too, so the page is chosen directly
h.state_mut().ui.preferences.page = materialcraft_ui_egui::preferences::PreferencesPage::Library;
settle(&mut h, 4);
assert!(h.query_all(By::new().label("Disk limit (MiB, 0 = off)")).next().is_some());
assert!(h.query_all(By::new().label("Maximum stored previews")).next().is_some());
h.get_by_label("Clear cache").click();
h.get_by_label("Rebuild thumbnails").click();
settle(&mut h, 4);
assert_eq!(h.state().session.library_cache_clear_epoch, 1);
@@ -0,0 +1,48 @@
//! Renders of the menu bar's menus, the Preferences pages, the New graph dialog, the home screen
//! and the Plugin Manager
use egui_kittest::kittest::Queryable;
use materialcraft_ui_egui::preferences::PreferencesPage;
use materialcraft_ui_egui::{MaterialCraftApp, UiState};
#[test]
#[ignore = "requires an offscreen GPU; run explicitly with --ignored"]
fn the_menus_and_their_windows() {
let Some(directory) = std::env::var_os("MC_SNAPSHOT_DIR").map(std::path::PathBuf::from) else { return };
std::fs::create_dir_all(&directory).unwrap();
let app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), UiState::default());
let mut harness = super::harness(app, 1600.0, 960.0);
super::settle(&mut harness, 8);
for menu in ["File", "Edit", "Tools", "Windows", "Help"] {
harness.get_by_label(menu).click();
super::settle(&mut harness, 4);
super::save(&mut harness, &directory, &format!("menu-{}", menu.to_lowercase()));
harness.key_press(egui::Key::Escape);
super::settle(&mut harness, 2);
}
harness.state_mut().ui.windows.preferences = true;
for page in PreferencesPage::ALL {
harness.state_mut().ui.preferences.page = page;
super::settle(&mut harness, 6);
super::save(&mut harness, &directory, &format!("preferences-{}", page.label().to_lowercase().replace(' ', "-")));
}
harness.state_mut().ui.windows.preferences = false;
// The template previews render in the background
harness.state_mut().ui.windows.new_graph = true;
super::settle(&mut harness, 200);
super::save(&mut harness, &directory, "new-graph");
harness.state_mut().ui.windows.new_graph = false;
harness.state_mut().ui.windows.home = true;
super::settle(&mut harness, 10);
super::save(&mut harness, &directory, "home-screen");
harness.state_mut().ui.windows.home = false;
harness.state_mut().ui.windows.plugin_manager = true;
super::settle(&mut harness, 6);
super::save(&mut harness, &directory, "plugin-manager");
}
+2 -1
View File
@@ -89,7 +89,7 @@ Types: `move`, `down`, `up`, `click`, `doubleClick`, `drag`, `scroll`, `key` (eg
| `graph.function.variables` | `{id, target?: FunctionGraphTarget}` returns ordered suggestions matching a Get node's type and caller scope; typed custom names remain supported |
| `session.environment` | `{timeSeconds?, uvTile?: [int, int], normalFormat?: int}` updates host evaluation values without modifying the package; `{}` reads them; defaults are zero and the normal-format code is passed through |
| `graph.context` | `{physicalSize?: [x, y, z], pixelRatio?: 0\|1, tiling?: [horizontal, vertical]}` edits material-graph metadata with undo; `{}` reads it; reusable functions receive their caller's context |
| `file.new` | `{template?, name?, size?}`; templates from `graph.templates` (`empty`, `pbr`, `bricks`, `stone_tiles`, `wood`, `rusty_metal`, `fabric`, `ground`) |
| `file.new` | `{template?, name?, folder?, kind?, size?, height?, newPackage?}`; templates from `graph.templates` (`empty`, `pbr`, `bricks`, `stone_tiles`, `wood`, `rusty_metal`, `fabric`, `ground`). `size` is the width in pixels and `height` defaults to it (powers of two, 16 to 8192); `newPackage: true` creates the graph in a new untitled package |
| `graph.node.edit` | `{}` resolves the selected FX-Map, processor or graph instance to `{kind, node, parameter?, graph?, document?, path?}`; use `ui.menu.invoke` to open its reference in the graph panel |
| `graph.node.info` | `{id}` returns `{text}` describing a main-graph node without changing the document or node clipboard |
| `graph.instance.add` | `{document, graph, function?: FunctionGraphTarget, at?, snapToGrid?}` adds a linked graph instance from an open package; requires a source output and rejects dependency cycles |
@@ -386,6 +386,7 @@ each has its own reader and writer (`crates/formats/src/material.rs` here), so k
| `graph.input.bind` / `graph.input.unbind` | `{identifier, resource? \| path?, linear?}` / `{identifier}`: a preview image for an input node (a mesh map exported from TextureCraft), saved in the package |
| `file.open` | `{path}` opens `.sbs` XML or an independent `.mcraft` ZIP. Also opens a `.mcmat`'s source without a save path. Returns `warnings` for unsupported content; also in `session.inspect` as `package.warnings` |
| `file.save` / `file.saveAs` / `file.saveCopyAs` | `{path?}` / `{path}` / `{path}`: `.sbs` writes XML and adjacent `resources/`; `.mcraft` writes a ZIP containing `package.sbs` and `resources/`. Unrecognized extensions get `.sbs` appended. Save Copy preserves the active path and modified state |
| `file.saveAll` | `{}` saves every modified package that has a file and returns `{saved, withoutFile, failed}`; packages without a file need `file.saveAs` |
| `file.importBitmap` / `file.importVector` | `{path, name?, folder?}` imports a supported bitmap / SVG into Resources or a subfolder without adding a node. Unsaved imports and their original bytes participate in undo. `session.inspect` reports resource name, folder, file, byte count and missing status |
| `graph.resource.add` | `{resource, document?, at?}` places a resource from the source document on the active material graph. Cross-document drops copy the asset; resource and node creation undo together |
| `folder.properties` / `folder.attributes` | `{folder, document?}` reads Identifier/Description; add `identifier?` and/or `description?` to edit. Folder attributes persist as native SBS group identifiers and descriptions. The reserved root Resources identifier cannot change |
+3 -2
View File
@@ -23,7 +23,7 @@ Explorer now preserves native SBS folder hierarchies and provides package, folde
menus for creation, copying, pasting, renaming, removal and package file actions. Moving items within
a package and removing folder subtrees support undo; empty folders survive saves.
> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-15 · **Change:** major (3D view 55% → 75%: the reference menus, tool strip, properties, shaders and lights) · **Target:** the professional node-based material workflow (desktop app; the web app is assessed later)
> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-18 · **Change:** minor (UI and UX 70% → 75%: the reference application menus, Preferences pages, New graph dialog and home screen) · **Target:** the professional node-based material workflow (desktop app; the web app is assessed later)
**Overall: ≈ 69%** of a material artist's daily workflow works end to end (engine + UI +
automation + tests), weighted by how much of the day each area carries. **Remaining: ≈ 83 Opus
@@ -39,7 +39,7 @@ automation + tests), weighted by how much of the day each area carries. **Remain
| 2D view | 5 | 90% | The reference layout: a toolbar above the image (background image, save, copy to the clipboard, output choice, UV overlay, Information and Histogram panels) and one below (channel menu with C/R/G/B/A keys, checkerboard, premultiplied alpha, sRGB or linear display, tiling across the whole view, physical size, exact fit, 1:1, stepped zoom with a zoom field, zoom lock); an Information panel with the pixel under the pointer and a color sampler (values at the image's bit depth and as floats, HSV, position); a Histogram panel with channel choice, bit depth, square-root scale, used range and a selectable range; size/format line | Color picker to parameters, floating the two panels, UV sets beyond the first |
| 3D view | 10 | 75% | The reference layout: menus (Scene, Materials, Lights, Camera, Environment, Display, Renderer), a tool strip (scene browser, Select, Camera and Light tools, environment background, shadows, a displacement pop-up, the display helpers) and a bar with the channels, the color space and the scene; the material, lights, camera, environment and renderer in the Properties panel. Thirteen built-in meshes and OBJ, glTF and GLB meshes; nine shaders (the OpenPBR Surface model with coat, fuzz, thin film, transmission and subsurface, metallic/roughness with coated and subsurface variants, specular/glossiness, Blinn, Lambert, unlit and mesh information) with every parameter editable, switchable and replaced by a graph output; height by tessellation and displacement or parallax occlusion; an ambient light and two point lights with shadows; 4 procedural environments with rotation, exposure and an on/off switch; focal length, perspective or orthographic projection, viewpoints, framing, clip planes, a studio backdrop, a background color or the environment behind the mesh, and a render resolution of its own; wireframe, backface culling, grid, axes with a scale, bounding box, light helpers, vertex tangent space, scene statistics, resolution and frame rate; tiling, UV scale and physical size; alpha transparency and an alpha channel view; save and copy the render, export the tessellated mesh as OBJ, state files and a saved default state | A GPU renderer and a path tracer, a ground plane that catches shadows, several materials on one mesh, loading shader definitions, anisotropy, dispersion and thin-walled transmission in the 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; an Export window (From graph, Batch at a chosen output size, and MaterialX and MCMAT tabs holding the #190 publishing options) writing the checked outputs (PNG, JPEG, TGA, BMP, WEBP, EXR, HDR; DDS listed for later; 8/16/32 bits; name pattern; sRGB, linear or raw per output); 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 |
| UI and UX | 8 | 75% | 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, the reference File, Tools, Windows and Help menus (Save all, Cancel rendering, Suspend engine, main toolbar toggle, help and community links), New graph dialog with template cards, a category filter, width and height and a target package, export dialog, a paged Preferences window (General, Projects, Graph, 3D View, Library and Shortcuts pages with OK, Cancel and Apply; recent list length, invert zoom, numbered autosave copies, node search on Tab and on wire drop, outputs in the 3D view on open, node creation shortcuts), a Plugin Manager window (no plugin loading yet), shortcuts list, a home screen at startup (templates, recent packages, learn and community links), visual function editor, presets bar, accessible names on every widget, status bar | A plugin system, bakers, keymap editor for application commands, minimap, multi-graph tabs |
| Platforms | 4 | 50% | Windows, macOS, Linux, FreeBSD and web builds compile; browser file I/O; packaging scripts and release workflows | First release run |
| **Total** | **100** | **≈ 69%** | | |
@@ -58,6 +58,7 @@ and is tested.
| Date | Change | Summary |
|---|---|---|
| 2026-11-18 | minor | UI and UX 70% → 75%: the reference File, Tools, Windows and Help menus, a paged Preferences window keeping every earlier setting, node creation shortcuts, the New graph dialog with sizes and a target package, a Plugin Manager window and a new home screen (#269); overall ≈ 69% → ≈ 69% |
| 2026-11-15 | major | 3D view 55% → 75%: the reference menus, tool strip and properties; shaders with editable parameters, lights with shadows, camera lens and projection, render resolution, display helpers, state files (#221); overall ≈ 67% → ≈ 69% |
| 2026-11-14 | minor | 2D view 80% → 90%: the reference toolbars, the Information and Histogram panels, display settings and stepped zoom (#221); overall unchanged at ≈ 67% |
| 2026-11-02 | minor | ≈ 66% → ≈ 67%: `.mcmat` portable materials and TextureCraft interop (Files 70%) |