mirror of
https://github.com/storytold/materialcraft.git
synced 2026-11-23 07:50:58 +01:00
Ui update
This commit is contained in:
1 parent
9e60c407a6
commit
1327fd6027
45 files changed
+5658
-490
No files matched your search
Generated
+1
@@ -2459,6 +2459,7 @@ dependencies = [
|
||||
"log",
|
||||
"materialcraft-engine",
|
||||
"materialcraft-render",
|
||||
"rayon",
|
||||
"rfd",
|
||||
"serde",
|
||||
"serde_json",
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
# UI parity drop (branch 123-improving-ui)
|
||||
|
||||
What changed, per area of the reference screenshots. Everything is wired to the engine; no empty settings.
|
||||
|
||||
## Menus (File / Edit / Tools / Windows / Help)
|
||||
- File: New ▸ Graph / Empty package, Open, Recent, Save, Save as, Save a copy as, Export with dependencies, Import bitmap, Link bitmap, Export outputs, Export material, Send to TextureCraft, Close, Quit.
|
||||
- Tools: Switch engine (F9: CPU thread count, rayon pool), Cancel rendering, Suspend engine, Clear cache, Reload resources, Plugin Manager.
|
||||
- Windows: panels, Main toolbar toggle, Dependency Manager, maximize/unmaximize (Shift+Space), reset layout.
|
||||
- Help: docs, tutorials, release notes, requirements, automation, feedback, bug report, export log, about. No vendor names, no Partners.
|
||||
- Status bar: "MC Engine: CPU (n threads)".
|
||||
|
||||
## Explorer
|
||||
- Package context menu: New ▸, Import ▸ (Bitmap, Graph from a package), Link ▸ Bitmap, Reload, Save/Save as/Save a copy as, Export with dependencies, Send to ▸ TextureCraft, Copy/Paste (graphs), Close package, Compute Outputs, Show in Explorer, Dependency Manager.
|
||||
- Graph context menu: Open (Return), Copy, Paste, Remove (Del), Rename (F2, in place), View Outputs In 3D View, Compute Outputs, Export outputs.
|
||||
- Resources: Relink, Add a Bitmap node, Remove. Linked bitmaps show a link icon.
|
||||
- Default graph name is Material_Graph.
|
||||
- Not done: "Open dependencies" (we have no package-to-package links to open).
|
||||
|
||||
## Library
|
||||
- Tree: All nodes, Favorites (persisted, right-click a tile), Graph items (Comment, Frame, Pin + inputs/outputs/dot), Atomic nodes, FxMap nodes, Function nodes ▸ (groups), Texture generators ▸, Filters ▸, Material filters ▸ (ours + planned empty groups greyed with 0), Mesh-based generators, Spline & Path tools, SDF functions (planned, greyed), Functions (function graphs of the package), PBR materials ▸ This package / Plugins, Values ▸ Constant.
|
||||
- Collapsible groups with counts, search, icon/list view, tile size slider.
|
||||
- Function nodes drop into the open function editor; plugin graphs are copied into the package on drop (file.importGraph).
|
||||
|
||||
## New graph dialog
|
||||
- Category dropdown, group headings, ⓘ template info, width/height with a link toggle, "Create graph in".
|
||||
|
||||
## Graph toolbar
|
||||
- Row 1: frame all, 1:1, screenshot (PNG), graph info popup, find node, thumbnails, cook times, straight/curved wires, grid, snap, compute, clean up; right: Stack checkbox + align buttons, Parent size with link and reset.
|
||||
- Row 2: atomic quick-insert, comment, dot, frame, pin.
|
||||
|
||||
## 3D view
|
||||
- Menus: Scene (11 scenes incl. Plane hi-res, Cloth, Rounded cylinder, Sphere 2 tiles; Display UVs in 2D View; Load/Save state file; Save as default; Reset), Materials ▸ Default (Edit properties, 9 shaders, reset common/material, create graph), Lights, Camera (Frame F, viewpoints, Save Render Alt+S, Copy Render, Reset Position R), Environment, Display (wireframe, axis, backface culling, bounding box, grid, light gizmos, resolution/stats/FPS overlays), Renderer (Edit settings).
|
||||
- "Edit properties" pages in the Properties panel: Camera (focal length, projection, background type/colour, render resolution, clip planes), Lights (ambient + 2 point lights with colour strips), Environment (enabled, exposure, rotation dial/turns/degrees, environment preview), Renderer (resolution, scale, samples, AO rays), Material (OpenPBR sections: UVs, Base, Specular, Transmission, Subsurface, Coat, Fuzz, Emission, Thin-film, Geometry, Height; each with the "use map" checkbox, sRGB/Float/HSV colour strips).
|
||||
- Left tool strip: frame, property pages, display toggles.
|
||||
- Renderer: point lights with shadows, ambient, env on/off, 9 shading models, common values, wireframe, backface culling, clip planes, background colour/environment, FOV/ortho, tessellation factor.
|
||||
- Engine: `view.3d` takes nested objects (camera/lights/renderer/display/material), `view.3d.reset {what}`, `view.3d.state`, `view.3d.loadState`.
|
||||
|
||||
## Preferences (Edit ▸ Preferences)
|
||||
- Tabs General / Projects / Graph / 3D View / Bakers / Library / Shortcuts with OK / Cancel / Apply.
|
||||
- General: recent count, history size (session.settings), language (English for now), appearance, invert zoom, save/export path mode + fixed folder, temp (backup) folder, image cache budget, cook threads, auto backup interval + versions (rotating files), cooking size limit (caps previews and exports).
|
||||
- Projects: plugins folder, backups folder, default 3D state (save/clear), default lighting state, library view, preview size, 3D pan limit/speed.
|
||||
- Graph: Tab menu, drag-create, 3D on open, thumbnails, 2D on open, auto display new node, auto colour/grayscale conversion node, grid/snap/wires/timings.
|
||||
- 3D View: environment hidden by default, viewport scaling, sample count.
|
||||
- Bakers: baking threads. Library: rebuild thumbnails, clear cache. Shortcuts: node creation shortcuts (click a field, press keys).
|
||||
- Skipped on purpose: UDIM, .sbsar publishing.
|
||||
|
||||
## Plugin Manager (Tools ▸ Plugin Manager)
|
||||
- Filter, Plugins/Loaded table, Browse (opens the plugins folder), Install (copies .sbs/.mcraft files in), Refresh.
|
||||
- A plugin = a package file or a folder with package files + optional plugin.json {name, version, author, description} in Documents/MaterialCraft/plugins. Loaded plugins' graphs show in the library under PBR materials ▸ Plugins.
|
||||
|
||||
## Engine commands added
|
||||
file.linkBitmap, file.reloadResources, file.deleteResource, file.importGraph, file.packageGraphs, file.saveCopy, file.exportWithDependencies, graph.add, session.settings, view.3d.reset {what}, view.3d.state, view.3d.loadState; `view.3d` nested objects. Resources can be linked (SBS keeps relative links).
|
||||
|
||||
## Checks run here
|
||||
cargo fmt, cargo clippy --workspace --all-targets -D warnings, cargo xtask layers, cargo test --workspace --release, cargo xtask wasm.
|
||||
@@ -126,7 +126,7 @@ mod tests {
|
||||
assert_eq!(s.pkg.name, "Untitled package");
|
||||
assert_eq!(s.pkg.graphs.len(), 1);
|
||||
let g = s.graph().unwrap();
|
||||
assert_eq!(g.name, "New_graph");
|
||||
assert_eq!(g.name, "Material_Graph");
|
||||
assert!(g.nodes.is_empty());
|
||||
assert!(g.connections.is_empty());
|
||||
assert!(s.path.is_none());
|
||||
|
||||
@@ -20,12 +20,21 @@ pub struct Resource {
|
||||
/// The file's bytes (stored in the zip, not in `package.json`).
|
||||
#[serde(skip)]
|
||||
pub bytes: ResourceBytes,
|
||||
/// A linked resource: the file it is read from (relative to the package's folder when it
|
||||
/// lies inside it), reloaded by "Reload resources". `None` = embedded in the package.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub link: Option<String>,
|
||||
}
|
||||
|
||||
impl Resource {
|
||||
/// A resource named `name`, stored as `file` in the package.
|
||||
pub fn new(name: impl Into<String>, file: impl Into<String>, bytes: ResourceBytes) -> Resource {
|
||||
Resource { name: name.into(), file: file.into(), bytes }
|
||||
Resource { name: name.into(), file: file.into(), bytes, link: None }
|
||||
}
|
||||
|
||||
/// A resource that stays on disk at `link` and is read from there.
|
||||
pub fn linked(name: impl Into<String>, file: impl Into<String>, bytes: ResourceBytes, link: impl Into<String>) -> Resource {
|
||||
Resource { name: name.into(), file: file.into(), bytes, link: Some(link.into()) }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -45,6 +45,24 @@ pub(crate) fn specs() -> Vec<CommandSpec> {
|
||||
save
|
||||
),
|
||||
cmd!("file.saveAs", "Save as...", ["File"], Some("Ctrl+Shift+S"), "{path} saves the package under a new name", always, save),
|
||||
cmd!(
|
||||
"file.saveCopy",
|
||||
"Save a copy as...",
|
||||
["File"],
|
||||
None,
|
||||
"{path} writes the package to `path` while the session keeps its own file",
|
||||
always,
|
||||
save_copy
|
||||
),
|
||||
cmd!(
|
||||
"file.exportWithDependencies",
|
||||
"Export with dependencies...",
|
||||
["File"],
|
||||
None,
|
||||
"{dir} writes the package and copies of its linked bitmaps into `dir`, the links made relative; returns the files written",
|
||||
always,
|
||||
export_with_dependencies
|
||||
),
|
||||
cmd!(
|
||||
"file.export",
|
||||
"Export outputs...",
|
||||
@@ -63,6 +81,51 @@ pub(crate) fn specs() -> Vec<CommandSpec> {
|
||||
always,
|
||||
import_bitmap
|
||||
),
|
||||
cmd!(
|
||||
"file.linkBitmap",
|
||||
"Link bitmap...",
|
||||
["File"],
|
||||
None,
|
||||
"{path, name?} adds an image file as a linked resource (read from disk, reloaded by file.reloadResources; saved as a link when the file lies in the package's folder); returns its name",
|
||||
always,
|
||||
link_bitmap
|
||||
),
|
||||
cmd!(
|
||||
"file.reloadResources",
|
||||
"Reload resources",
|
||||
["File"],
|
||||
None,
|
||||
"{} reads every linked resource from its file again; returns the names reloaded and those whose file is missing",
|
||||
always,
|
||||
reload_resources
|
||||
),
|
||||
cmd!(
|
||||
"file.deleteResource",
|
||||
"Remove resource",
|
||||
[],
|
||||
None,
|
||||
"{name} removes a bitmap resource; the nodes that used it show an error until they get another",
|
||||
always,
|
||||
delete_resource
|
||||
),
|
||||
cmd!(
|
||||
"file.importGraph",
|
||||
"Import graph...",
|
||||
["File"],
|
||||
None,
|
||||
"{path, graph?} copies a graph (default: the first) of another package file into this one, with the graphs it instances and the bitmaps it uses; returns the new graph's name",
|
||||
always,
|
||||
import_graph
|
||||
),
|
||||
cmd!(
|
||||
"file.packageGraphs",
|
||||
"Graphs of a package file",
|
||||
[],
|
||||
None,
|
||||
"{path} lists the graphs of a package file without opening it: [{name, kind, outputs}]",
|
||||
always,
|
||||
package_graphs
|
||||
),
|
||||
cmd!("graph.templates", "Graph templates", [], None, "{} lists the templates for file.new", always, |_, _| Ok(json!(
|
||||
TEMPLATES.iter().map(|(id, l)| json!({"id": id, "label": l})).collect::<Vec<_>>()
|
||||
))),
|
||||
@@ -87,7 +150,7 @@ fn new_graph(s: &mut Session, p: &J) -> Result<J> {
|
||||
|
||||
fn new_package(s: &mut Session, p: &J) -> Result<J> {
|
||||
let mut pkg = Package::new(strp(p, "name").unwrap_or("Untitled package"));
|
||||
pkg.graphs.push(template("pbr", "New_graph", 10));
|
||||
pkg.graphs.push(template("pbr", "Material_Graph", 10));
|
||||
replace_package(s, pkg, None);
|
||||
Ok(json!({"name": s.pkg.name}))
|
||||
}
|
||||
@@ -142,6 +205,131 @@ pub fn package_path(path: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
fn delete_resource(s: &mut Session, p: &J) -> Result<J> {
|
||||
let name = strp(p, "name").ok_or_else(|| bad("file.deleteResource", "`name` is required"))?.to_string();
|
||||
if s.pkg.resource(&name).is_none() {
|
||||
return Err(bad("file.deleteResource", format!("no resource `{name}`")));
|
||||
}
|
||||
s.edit("Remove resource", |s| {
|
||||
s.pkg.resources.retain(|r| r.name != name);
|
||||
Ok(J::Null)
|
||||
})?;
|
||||
s.clear_decoded();
|
||||
Ok(json!({"name": name}))
|
||||
}
|
||||
|
||||
/// Read package bytes without touching the session: SBS, `.mcraft`, or a `.mcmat` material's source.
|
||||
pub fn load_bytes(bytes: &[u8], name: &str, linked: &dyn Fn(&str) -> Option<Vec<u8>>) -> Result<Package> {
|
||||
if materialcraft_formats::material::is_material(bytes) {
|
||||
let (_, source) = materialcraft_formats::material::read_material(bytes)?;
|
||||
return Ok(materialcraft_formats::load_package(&source)?);
|
||||
}
|
||||
let named_sbs = has_extension(name, PackageFormat::Sbs.ext()) && !bytes.starts_with(b"PK");
|
||||
if !named_sbs && !materialcraft_formats::sbs::is_sbs(bytes) {
|
||||
return Ok(materialcraft_formats::load_package(bytes)?);
|
||||
}
|
||||
Ok(materialcraft_formats::sbs::read_sbs(bytes, name, linked)?.pkg)
|
||||
}
|
||||
|
||||
/// Copy `graph` of `from` into the session's package: the graph, every graph it instances
|
||||
/// (recursively) and the bitmap resources its nodes use. Graphs that already exist with the
|
||||
/// same name are reused when identical, else the copy gets a unique name and the instances
|
||||
/// that point at it follow. Returns the copied graph's name.
|
||||
pub fn import_graph_from(s: &mut Session, from: &Package, graph: &str) -> Result<String> {
|
||||
let (_, root) = from.graph_by_name(graph).ok_or_else(|| bad("file.importGraph", format!("`{}` has no graph `{graph}`", from.name)))?;
|
||||
// Walk the instance tree, deepest dependencies first so renames are known when they are used.
|
||||
let mut order: Vec<String> = Vec::new();
|
||||
let mut stack = vec![root.name.clone()];
|
||||
while let Some(name) = stack.pop() {
|
||||
if order.contains(&name) {
|
||||
continue;
|
||||
}
|
||||
order.push(name.clone());
|
||||
if let Some((_, g)) = from.graph_by_name(&name) {
|
||||
for n in g.nodes.iter().filter(|n| n.def == "graph_instance") {
|
||||
if let Some(materialcraft_core::Value::Text(t)) = n.params.get("graph")
|
||||
&& !order.contains(t)
|
||||
{
|
||||
stack.push(t.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
order.reverse();
|
||||
let from = from.clone();
|
||||
s.edit("Import graph", |s| {
|
||||
let mut renamed: std::collections::BTreeMap<String, String> = std::collections::BTreeMap::new();
|
||||
for name in &order {
|
||||
let Some((_, g)) = from.graph_by_name(name) else { continue };
|
||||
let mut g = g.clone();
|
||||
for n in g.nodes.iter_mut() {
|
||||
if n.def == "graph_instance"
|
||||
&& let Some(materialcraft_core::Value::Text(t)) = n.params.get("graph").cloned()
|
||||
&& let Some(new) = renamed.get(&t)
|
||||
{
|
||||
n.params.insert("graph".into(), materialcraft_core::Value::Text(new.clone()));
|
||||
}
|
||||
if let Some(materialcraft_core::Value::Text(r)) = n.params.get("resource").cloned()
|
||||
&& let Some(res) = from.resource(&r)
|
||||
&& s.pkg.resource(&r).is_none()
|
||||
{
|
||||
s.pkg.resources.push(res.clone());
|
||||
}
|
||||
}
|
||||
if let Some((_, have)) = s.pkg.graph_by_name(name)
|
||||
&& *have == g
|
||||
{
|
||||
renamed.insert(name.clone(), name.clone());
|
||||
continue;
|
||||
}
|
||||
let new = s.pkg.unique_graph_name(name);
|
||||
g.name = new.clone();
|
||||
renamed.insert(name.clone(), new);
|
||||
s.pkg.graphs.push(g);
|
||||
}
|
||||
Ok(renamed.get(&root.name).cloned().unwrap_or_else(|| root.name.clone()))
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn load_file(cmd: &str, p: &J) -> Result<(String, Package)> {
|
||||
let path = strp(p, "path").ok_or_else(|| bad(cmd, "`path` is required"))?;
|
||||
let bytes = std::fs::read(path).map_err(|e| bad(cmd, format!("{path}: {e}")))?;
|
||||
Ok((path.to_string(), load_bytes(&bytes, path, &linked_files(path))?))
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn import_graph(s: &mut Session, p: &J) -> Result<J> {
|
||||
let (_, from) = load_file("file.importGraph", p)?;
|
||||
let graph = match strp(p, "graph") {
|
||||
Some(g) => g.to_string(),
|
||||
None => from.graphs.first().map(|g| g.name.clone()).ok_or_else(|| bad("file.importGraph", "the package has no graphs"))?,
|
||||
};
|
||||
let name = import_graph_from(s, &from, &graph)?;
|
||||
Ok(json!({"name": name}))
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn import_graph(_: &mut Session, _: &J) -> Result<J> {
|
||||
Err(bad("file.importGraph", "the browser has no package files to import from"))
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn package_graphs(_: &mut Session, p: &J) -> Result<J> {
|
||||
let (_, from) = load_file("file.packageGraphs", p)?;
|
||||
Ok(json!(
|
||||
from.graphs
|
||||
.iter()
|
||||
.map(|g| json!({"name": g.name, "kind": format!("{:?}", g.kind), "outputs": g.nodes.iter().filter(|n| n.def == "output").count()}))
|
||||
.collect::<Vec<_>>()
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn package_graphs(_: &mut Session, _: &J) -> Result<J> {
|
||||
Err(bad("file.packageGraphs", "the browser has no package files to read"))
|
||||
}
|
||||
|
||||
/// Open package bytes on any platform: SBS, `.mcraft`, or a `.mcmat` material's source package.
|
||||
pub fn open_bytes(s: &mut Session, bytes: &[u8], name: Option<String>) -> Result<()> {
|
||||
open_bytes_linked(s, bytes, name, &|_| None)
|
||||
@@ -259,6 +447,69 @@ fn save(_: &mut Session, _: &J) -> Result<J> {
|
||||
Err(bad("file.save", "the browser saves with a download"))
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn save_copy(s: &mut Session, p: &J) -> Result<J> {
|
||||
let path = package_path(strp(p, "path").ok_or_else(|| bad("file.saveCopy", "`path` is required"))?);
|
||||
let bytes = save_bytes_as(s, PackageFormat::of_path(&path))?;
|
||||
materialcraft_formats::write_atomic(std::path::Path::new(&path), &bytes)?;
|
||||
s.log(format!("Saved a copy to {path}"));
|
||||
Ok(json!({"path": path, "bytes": bytes.len()}))
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn save_copy(_: &mut Session, _: &J) -> Result<J> {
|
||||
Err(bad("file.saveCopy", "the browser saves with a download"))
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn export_with_dependencies(s: &mut Session, p: &J) -> Result<J> {
|
||||
let dir = strp(p, "dir").ok_or_else(|| bad("file.exportWithDependencies", "`dir` is required"))?;
|
||||
let dir = std::path::Path::new(dir);
|
||||
std::fs::create_dir_all(dir).map_err(|e| bad("file.exportWithDependencies", format!("{}: {e}", dir.display())))?;
|
||||
let mut written: Vec<String> = Vec::new();
|
||||
// The copy links every linked bitmap by its file name, next to the package.
|
||||
let mut pkg = s.pkg.clone();
|
||||
let mut used: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
|
||||
for r in pkg.resources.iter_mut() {
|
||||
let Some(link) = r.link.clone() else { continue };
|
||||
let bytes = match read_link(s, &link) {
|
||||
Ok(b) => b,
|
||||
Err(why) => {
|
||||
s.log(format!("`{}` exported embedded: {why}", r.name));
|
||||
r.link = None;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let base = std::path::Path::new(&link).file_name().and_then(|f| f.to_str()).unwrap_or(&r.file).to_string();
|
||||
let mut file = base.clone();
|
||||
let mut n = 2;
|
||||
while !used.insert(file.clone()) {
|
||||
file = match base.rsplit_once('.') {
|
||||
Some((stem, ext)) => format!("{stem}_{n}.{ext}"),
|
||||
None => format!("{base}_{n}"),
|
||||
};
|
||||
n += 1;
|
||||
}
|
||||
let target = dir.join(&file);
|
||||
materialcraft_formats::write_atomic(&target, &bytes)?;
|
||||
written.push(target.display().to_string());
|
||||
r.link = Some(file);
|
||||
r.bytes = ResourceBytes::new(bytes);
|
||||
}
|
||||
let name = format!("{}.{}", materialcraft_formats::safe_file_name(&pkg.name), PackageFormat::Sbs.ext());
|
||||
let target = dir.join(&name);
|
||||
let bytes = materialcraft_formats::sbs::write_sbs(&pkg)?;
|
||||
materialcraft_formats::write_atomic(&target, &bytes)?;
|
||||
written.insert(0, target.display().to_string());
|
||||
s.log(format!("Exported {} with {} dependenc{} to {}", pkg.name, written.len() - 1, if written.len() == 2 { "y" } else { "ies" }, dir.display()));
|
||||
Ok(json!({"files": written}))
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn export_with_dependencies(_: &mut Session, _: &J) -> Result<J> {
|
||||
Err(bad("file.exportWithDependencies", "the browser saves with a download"))
|
||||
}
|
||||
|
||||
/// One exported file.
|
||||
pub struct Exported {
|
||||
pub file: String,
|
||||
@@ -278,7 +529,9 @@ pub fn export_outputs(s: &Session, gi: usize, ext: &str, pattern: &str, depth: O
|
||||
}
|
||||
let g = pkg.graph(gi)?;
|
||||
let dec = s.resource_decoder();
|
||||
let cooked = materialcraft_eval::cook(&pkg, gi, &materialcraft_eval::Options::new(&dec), &s.cache);
|
||||
let mut opts = materialcraft_eval::Options::new(&dec);
|
||||
opts.max_size = s.cook_limit;
|
||||
let cooked = materialcraft_eval::cook(&pkg, gi, &opts, &s.cache);
|
||||
let mut out = Vec::new();
|
||||
let mut names = std::collections::HashSet::new();
|
||||
for (id, usage, ident, img) in materialcraft_eval::outputs(g, &cooked) {
|
||||
@@ -375,3 +628,91 @@ fn import_bitmap(s: &mut Session, p: &J) -> Result<J> {
|
||||
fn import_bitmap(_: &mut Session, _: &J) -> Result<J> {
|
||||
Err(bad("file.importBitmap", "the browser imports with the file picker"))
|
||||
}
|
||||
|
||||
/// The path a linked file is stored under: relative to the package's folder when it lies
|
||||
/// inside it (then the link survives in the saved file), else as given.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn link_path(s: &Session, path: &str) -> String {
|
||||
let Some(folder) = s.path.as_deref().and_then(|p| std::path::Path::new(p).parent()).and_then(|p| std::fs::canonicalize(p).ok()) else {
|
||||
return path.to_string();
|
||||
};
|
||||
match std::fs::canonicalize(path).ok().and_then(|f| f.strip_prefix(&folder).ok().map(|r| r.to_path_buf())) {
|
||||
Some(rel) => rel.to_string_lossy().replace('\\', "/"),
|
||||
None => path.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Read a linked resource's file: a relative link resolves next to the package.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn read_link(s: &Session, link: &str) -> std::result::Result<Vec<u8>, String> {
|
||||
let plain = !link.contains(':') && !link.starts_with('/') && !link.starts_with('\\');
|
||||
if plain && let Some(path) = &s.path {
|
||||
return linked_files(path)(link).ok_or_else(|| format!("`{link}` was not found next to the package"));
|
||||
}
|
||||
std::fs::read(link).map_err(|e| format!("{link}: {e}"))
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn link_bitmap(s: &mut Session, p: &J) -> Result<J> {
|
||||
let path = strp(p, "path").ok_or_else(|| bad("file.linkBitmap", "`path` is required"))?;
|
||||
let bytes = std::fs::read(path).map_err(|e| bad("file.linkBitmap", format!("{path}: {e}")))?;
|
||||
materialcraft_formats::decode(&bytes, false)?;
|
||||
let file = std::path::Path::new(path).file_name().and_then(|f| f.to_str()).unwrap_or("bitmap.png").to_string();
|
||||
let link = link_path(s, path);
|
||||
let wanted = strp(p, "name").map(str::to_string);
|
||||
let name = s.edit("Link bitmap", |s| {
|
||||
// Relinking an existing resource keeps its name (the nodes that use it stay valid).
|
||||
if let Some(r) = wanted.as_deref().and_then(|w| s.pkg.resources.iter_mut().find(|r| r.name == w)) {
|
||||
r.bytes = ResourceBytes::new(bytes);
|
||||
r.link = Some(link.clone());
|
||||
return Ok(r.name.clone());
|
||||
}
|
||||
let name = push_resource(&mut s.pkg, &file, bytes, wanted.as_deref());
|
||||
if let Some(r) = s.pkg.resources.iter_mut().find(|r| r.name == name) {
|
||||
r.link = Some(link.clone());
|
||||
}
|
||||
Ok(name)
|
||||
})?;
|
||||
Ok(json!({"name": name, "link": link, "use": {"command": "graph.node.add", "params": {"def": "bitmap", "params": {"resource": name}}}}))
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn link_bitmap(_: &mut Session, _: &J) -> Result<J> {
|
||||
Err(bad("file.linkBitmap", "the browser has no files to link to; import the bitmap instead"))
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn reload_resources(s: &mut Session, _: &J) -> Result<J> {
|
||||
let links: Vec<(String, String)> = s.pkg.resources.iter().filter_map(|r| r.link.clone().map(|l| (r.name.clone(), l))).collect();
|
||||
let mut fresh: Vec<(String, Vec<u8>)> = Vec::new();
|
||||
let mut missing: Vec<String> = Vec::new();
|
||||
for (name, link) in links {
|
||||
match read_link(s, &link) {
|
||||
Ok(bytes) => fresh.push((name, bytes)),
|
||||
Err(why) => {
|
||||
s.log(format!("resource `{name}` not reloaded: {why}"));
|
||||
missing.push(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
let changed: Vec<String> =
|
||||
fresh.iter().filter(|(n, b)| s.pkg.resources.iter().any(|r| &r.name == n && r.bytes.as_slice() != b.as_slice())).map(|(n, _)| n.clone()).collect();
|
||||
if !changed.is_empty() {
|
||||
s.edit("Reload resources", |s| {
|
||||
for (name, bytes) in fresh {
|
||||
if let Some(r) = s.pkg.resources.iter_mut().find(|r| r.name == name) {
|
||||
r.bytes = ResourceBytes::new(bytes);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
s.dirty = true;
|
||||
Ok(json!({"reloaded": changed, "missing": missing}))
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn reload_resources(s: &mut Session, _: &J) -> Result<J> {
|
||||
s.dirty = true;
|
||||
Ok(json!({"reloaded": [], "missing": []}))
|
||||
}
|
||||
@@ -18,6 +18,15 @@ pub(crate) fn specs() -> Vec<CommandSpec> {
|
||||
cmd!("graph.rename", "Rename graph", [], None, "{name, graph?}", has_graph, rename),
|
||||
cmd!("graph.delete", "Delete graph", [], None, "{graph?}", has_graph, delete),
|
||||
cmd!("graph.duplicate", "Duplicate graph", [], None, "{graph?}", has_graph, duplicate),
|
||||
cmd!(
|
||||
"graph.add",
|
||||
"Add graph",
|
||||
[],
|
||||
None,
|
||||
"{graph: a graph as JSON (edit.copy of a graph, graph.get)} adds the graph to the package under a unique name and opens it",
|
||||
always,
|
||||
add
|
||||
),
|
||||
cmd!("graph.size", "Graph size", [], None, "{width, height} in pixels (powers of two, 16..8192) or {log2: [w, h]}", has_graph, size),
|
||||
cmd!("graph.seed", "Random seed", [], None, "{seed}", has_graph, |s, p| {
|
||||
let seed = i64p(p, "seed").ok_or_else(|| bad("graph.seed", "`seed` is required"))?.clamp(0, i32::MAX as i64) as i32;
|
||||
@@ -151,6 +160,28 @@ fn duplicate(s: &mut Session, p: &J) -> Result<J> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Paste a whole graph (the explorer's Copy/Paste): its JSON, renamed when the name is taken.
|
||||
fn add(s: &mut Session, p: &J) -> Result<J> {
|
||||
const MAX_NODES: usize = 100_000;
|
||||
let v = p.get("graph").ok_or_else(|| bad("graph.add", "`graph` is required"))?;
|
||||
let mut g: materialcraft_core::Graph = serde_json::from_value(v.clone()).map_err(|e| bad("graph.add", format!("not a graph: {e}")))?;
|
||||
if g.nodes.len() > MAX_NODES {
|
||||
return Err(bad("graph.add", format!("a graph holds at most {MAX_NODES} nodes")));
|
||||
}
|
||||
if g.name.trim().is_empty() {
|
||||
g.name = "Material_Graph".into();
|
||||
}
|
||||
s.edit("Add graph", |s| {
|
||||
g.name = s.pkg.unique_graph_name(&g.name);
|
||||
let name = g.name.clone();
|
||||
s.pkg.graphs.push(g);
|
||||
s.graph = s.pkg.graphs.len() - 1;
|
||||
s.selection.clear();
|
||||
s.view2d.node = None;
|
||||
Ok(json!({"graph": s.graph, "name": name}))
|
||||
})
|
||||
}
|
||||
|
||||
fn size(s: &mut Session, p: &J) -> Result<J> {
|
||||
let log = |px: u64| 63 - px.clamp(1, 1 << 20).leading_zeros();
|
||||
let (w, h) = if let Some(a) = p.get("log2").and_then(J::as_array) {
|
||||
|
||||
@@ -20,11 +20,12 @@ pub mod view_cmds;
|
||||
pub mod wire_cmds;
|
||||
|
||||
pub use commands::{CommandSpec, command_specs, execute, find};
|
||||
pub use session::{CameraPrefs, Clip, Session, View2d, View3d, WARNING_PREFIX};
|
||||
pub use session::{Camera3d, CameraPrefs, Clip, Display3d, Lights3d, Material3d, Renderer3d, Session, View2d, View3d, WARNING_PREFIX};
|
||||
|
||||
pub use materialcraft_core as core;
|
||||
pub use materialcraft_eval as eval;
|
||||
pub use materialcraft_formats as formats;
|
||||
pub use materialcraft_geom as geom;
|
||||
pub use materialcraft_image as image;
|
||||
pub use materialcraft_nodes as nodes;
|
||||
|
||||
@@ -52,7 +53,7 @@ pub const VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
/// A fresh, unsaved package with one empty graph, used at desktop and browser startup.
|
||||
pub fn new_session() -> Session {
|
||||
let mut pkg = core::Package::new("Untitled package");
|
||||
pkg.graphs.push(samples::template("empty", "New_graph", 10));
|
||||
pkg.graphs.push(samples::template("empty", "Material_Graph", 10));
|
||||
Session::new(pkg)
|
||||
}
|
||||
|
||||
|
||||
+229
-10
@@ -11,8 +11,8 @@ use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{EngineError, Result};
|
||||
|
||||
/// Undo keeps this many steps.
|
||||
const MAX_UNDO: usize = 200;
|
||||
/// Undo keeps this many steps unless the session says otherwise.
|
||||
pub const MAX_UNDO: usize = 200;
|
||||
|
||||
/// The 3D view's scene and look.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
@@ -45,6 +45,199 @@ pub struct View3d {
|
||||
pub transparency: bool,
|
||||
/// Show the material's alpha channel on the mesh instead of the lit material.
|
||||
pub alpha_view: bool,
|
||||
/// Camera ▸ Edit properties.
|
||||
pub camera: Camera3d,
|
||||
/// Lights ▸ Edit properties.
|
||||
pub lights: Lights3d,
|
||||
/// Environment ▸ Edit properties: the environment lights the scene.
|
||||
pub env_enabled: bool,
|
||||
/// Renderer ▸ Edit settings.
|
||||
pub renderer: Renderer3d,
|
||||
/// Display menu toggles.
|
||||
pub display: Display3d,
|
||||
/// Materials ▸ Default ▸ Edit properties.
|
||||
pub material: Material3d,
|
||||
}
|
||||
|
||||
/// The 3D view's camera properties.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct Camera3d {
|
||||
/// Millimetres (a 36 mm frame): 35 mm ≈ 35° vertical field of view on a 3:2 frame.
|
||||
pub focal_length: f32,
|
||||
/// `perspective` or `orthographic`.
|
||||
pub projection: String,
|
||||
/// `backdrop`, `color` or `environment`.
|
||||
pub background: String,
|
||||
/// Linear RGBA.
|
||||
pub background_color: [f32; 4],
|
||||
/// Render at a fixed resolution (Save Render) instead of the viewport's.
|
||||
pub override_resolution: bool,
|
||||
pub resolution: [u32; 2],
|
||||
/// Multiplier on the render resolution.
|
||||
pub resolution_scale: f32,
|
||||
/// Clip planes from the scene size; else `near`/`far` in mesh radii from the camera.
|
||||
pub auto_clip: bool,
|
||||
pub near: f32,
|
||||
pub far: f32,
|
||||
}
|
||||
|
||||
impl Default for Camera3d {
|
||||
fn default() -> Self {
|
||||
Camera3d {
|
||||
focal_length: 35.0,
|
||||
projection: "perspective".into(),
|
||||
background: "backdrop".into(),
|
||||
background_color: [0.016, 0.016, 0.016, 1.0],
|
||||
override_resolution: false,
|
||||
resolution: [1920, 1080],
|
||||
resolution_scale: 1.0,
|
||||
auto_clip: true,
|
||||
near: 0.1,
|
||||
far: 100.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Camera3d {
|
||||
/// Vertical field of view in degrees for the focal length (36 × 24 mm frame).
|
||||
pub fn fov(&self) -> f32 {
|
||||
(2.0 * (12.0 / self.focal_length.max(1.0)).atan()).to_degrees().clamp(5.0, 120.0)
|
||||
}
|
||||
|
||||
fn sanitize(&mut self) {
|
||||
let d = Camera3d::default();
|
||||
let f = |v: f32, lo: f32, hi: f32, dv: f32| if v.is_finite() { v.clamp(lo, hi) } else { dv };
|
||||
self.focal_length = f(self.focal_length, 4.0, 1200.0, d.focal_length);
|
||||
if !["perspective", "orthographic"].contains(&self.projection.as_str()) {
|
||||
self.projection = d.projection;
|
||||
}
|
||||
if !["backdrop", "color", "environment"].contains(&self.background.as_str()) {
|
||||
self.background = d.background;
|
||||
}
|
||||
for (i, v) in self.background_color.iter_mut().enumerate() {
|
||||
*v = f(*v, 0.0, 1.0, d.background_color[i]);
|
||||
}
|
||||
self.resolution = self.resolution.map(|v| v.clamp(16, 8192));
|
||||
self.resolution_scale = f(self.resolution_scale, 0.1, 4.0, d.resolution_scale);
|
||||
self.near = f(self.near, 0.001, 1000.0, d.near);
|
||||
self.far = f(self.far, 0.01, 10_000.0, d.far).max(self.near * 1.01);
|
||||
}
|
||||
}
|
||||
|
||||
/// The 3D view's lights: an ambient term and two point lights.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct Lights3d {
|
||||
pub ambient_on: bool,
|
||||
/// Linear RGB.
|
||||
pub ambient: [f32; 3],
|
||||
pub point: [materialcraft_geom::preview::PointLight; 2],
|
||||
}
|
||||
|
||||
impl Default for Lights3d {
|
||||
fn default() -> Self {
|
||||
Lights3d { ambient_on: true, ambient: [0.0; 3], point: materialcraft_geom::preview::PointLight::DEFAULTS }
|
||||
}
|
||||
}
|
||||
|
||||
impl Lights3d {
|
||||
fn sanitize(&mut self) {
|
||||
for v in self.ambient.iter_mut() {
|
||||
*v = if v.is_finite() { v.clamp(0.0, 16.0) } else { 0.0 };
|
||||
}
|
||||
let d = materialcraft_geom::preview::PointLight::DEFAULTS;
|
||||
self.point = [self.point[0].sanitized(d[0]), self.point[1].sanitized(d[1])];
|
||||
}
|
||||
}
|
||||
|
||||
/// Renderer ▸ Edit settings.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct Renderer3d {
|
||||
pub use_viewport_resolution: bool,
|
||||
pub resolution: [u32; 2],
|
||||
/// Resolution scale of the viewport render (0.25..2).
|
||||
pub scale: f32,
|
||||
/// Supersampling of the resting frame (1..4 per axis).
|
||||
pub samples: u32,
|
||||
/// Ray-traced ambient occlusion rays per sample (0 = off).
|
||||
pub ao_rays: u32,
|
||||
}
|
||||
|
||||
impl Default for Renderer3d {
|
||||
fn default() -> Self {
|
||||
Renderer3d { use_viewport_resolution: true, resolution: [1920, 1080], scale: 1.0, samples: 2, ao_rays: 0 }
|
||||
}
|
||||
}
|
||||
|
||||
impl Renderer3d {
|
||||
fn sanitize(&mut self) {
|
||||
self.resolution = self.resolution.map(|v| v.clamp(16, 4096));
|
||||
self.scale = if self.scale.is_finite() { self.scale.clamp(0.25, 2.0) } else { 1.0 };
|
||||
self.samples = self.samples.clamp(1, 4);
|
||||
self.ao_rays = self.ao_rays.min(64);
|
||||
}
|
||||
}
|
||||
|
||||
/// Display menu toggles.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct Display3d {
|
||||
pub wireframe: bool,
|
||||
pub backface_culling: bool,
|
||||
pub bounding_box: bool,
|
||||
/// Draw the point lights.
|
||||
pub lights: bool,
|
||||
/// Overlay the render resolution.
|
||||
pub resolution: bool,
|
||||
/// Overlay the scene statistics (triangles, maps).
|
||||
pub stats: bool,
|
||||
/// Overlay the frame rate.
|
||||
pub fps: bool,
|
||||
}
|
||||
|
||||
/// Materials ▸ Default: the shading model and what each channel is without a map.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct Material3d {
|
||||
pub shader: materialcraft_geom::preview::Shader,
|
||||
pub common: materialcraft_geom::preview::Common,
|
||||
pub use_map: materialcraft_geom::preview::MapUse,
|
||||
/// Displacement subdivision budget multiplier (0.1..4).
|
||||
pub tessellation: f32,
|
||||
/// Extra UV scale of the material on the mesh.
|
||||
pub uv_scale: [f32; 2],
|
||||
}
|
||||
|
||||
impl Default for Material3d {
|
||||
fn default() -> Self {
|
||||
Material3d {
|
||||
shader: materialcraft_geom::preview::Shader::OpenPbr,
|
||||
common: materialcraft_geom::preview::Common::default(),
|
||||
use_map: materialcraft_geom::preview::MapUse::default(),
|
||||
tessellation: 1.0,
|
||||
uv_scale: [1.0, 1.0],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Material3d {
|
||||
fn sanitize(&mut self) {
|
||||
self.common = self.common.sanitized();
|
||||
self.tessellation = if self.tessellation.is_finite() { self.tessellation.clamp(0.1, 4.0) } else { 1.0 };
|
||||
self.uv_scale = self.uv_scale.map(|v| if v.is_finite() { v.clamp(0.01, 64.0) } else { 1.0 });
|
||||
}
|
||||
}
|
||||
|
||||
impl View3d {
|
||||
/// Every nested value brought into its range (after a command merged JSON in).
|
||||
pub fn sanitize(&mut self) {
|
||||
self.camera.sanitize();
|
||||
self.lights.sanitize();
|
||||
self.renderer.sanitize();
|
||||
self.material.sanitize();
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for View3d {
|
||||
@@ -66,6 +259,12 @@ impl Default for View3d {
|
||||
show_grid: false,
|
||||
transparency: true,
|
||||
alpha_view: false,
|
||||
camera: Camera3d::default(),
|
||||
lights: Lights3d::default(),
|
||||
env_enabled: true,
|
||||
renderer: Renderer3d::default(),
|
||||
display: Display3d::default(),
|
||||
material: Material3d::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -166,6 +365,10 @@ pub struct Session {
|
||||
pub cache: Arc<Mutex<Cache>>,
|
||||
/// A mesh loaded for the 3D view (`scene: "custom"`): its file name and geometry.
|
||||
pub custom_mesh: Option<(String, Arc<materialcraft_geom::Mesh>)>,
|
||||
/// Undo steps kept (Preferences ▸ History stack size).
|
||||
pub max_undo: usize,
|
||||
/// Cap on the larger side of every cook, previews and exports alike (Preferences ▸ Cooking size limit).
|
||||
pub cook_limit: Option<u32>,
|
||||
undo: Vec<Snapshot>,
|
||||
redo: Vec<Snapshot>,
|
||||
/// Edits with the same key coalesce into one undo step (slider drags).
|
||||
@@ -195,6 +398,8 @@ impl Session {
|
||||
cook_epoch: 0,
|
||||
cache: Arc::new(Mutex::new(Cache::default())),
|
||||
custom_mesh: None,
|
||||
max_undo: MAX_UNDO,
|
||||
cook_limit: None,
|
||||
undo: Vec::new(),
|
||||
redo: Vec::new(),
|
||||
merge_key: None,
|
||||
@@ -275,9 +480,7 @@ impl Session {
|
||||
&& edited
|
||||
{
|
||||
self.undo.push(snap);
|
||||
if self.undo.len() > MAX_UNDO {
|
||||
self.undo.remove(0);
|
||||
}
|
||||
self.trim_undo();
|
||||
self.redo.clear();
|
||||
}
|
||||
}
|
||||
@@ -331,9 +534,7 @@ impl Session {
|
||||
match f(self) {
|
||||
Ok(v) => {
|
||||
self.undo.push(snap);
|
||||
if self.undo.len() > MAX_UNDO {
|
||||
self.undo.remove(0);
|
||||
}
|
||||
self.trim_undo();
|
||||
self.redo.clear();
|
||||
self.changed();
|
||||
Ok(v)
|
||||
@@ -372,6 +573,23 @@ impl Session {
|
||||
self.undo.iter().map(|s| s.label.clone()).collect()
|
||||
}
|
||||
|
||||
/// Drop the oldest undo steps past `max_undo`.
|
||||
pub fn trim_undo(&mut self) {
|
||||
let max = self.max_undo.max(1);
|
||||
if self.undo.len() > max {
|
||||
let extra = self.undo.len() - max;
|
||||
self.undo.drain(..extra);
|
||||
}
|
||||
}
|
||||
|
||||
/// The preview cap and the cooking size limit, whichever is smaller.
|
||||
pub fn cook_size(&self, preview: Option<u32>) -> Option<u32> {
|
||||
match (preview, self.cook_limit) {
|
||||
(Some(p), Some(l)) => Some(p.min(l)),
|
||||
(p, l) => p.or(l),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn undo(&mut self) -> Option<String> {
|
||||
self.end_group();
|
||||
let s = self.undo.pop()?;
|
||||
@@ -432,7 +650,7 @@ impl Session {
|
||||
pub fn cook(&mut self) -> &Cooked {
|
||||
let dec = self.resource_decoder();
|
||||
let mut opts = Options::new(&dec);
|
||||
opts.max_size = self.preview_size;
|
||||
opts.max_size = self.cook_size(self.preview_size);
|
||||
self.cooked = materialcraft_eval::cook(&self.pkg, self.graph, &opts, &self.cache);
|
||||
self.dirty = false;
|
||||
self.cook_epoch = self.cook_epoch.wrapping_add(1);
|
||||
@@ -442,7 +660,8 @@ impl Session {
|
||||
/// Cook graph `gi` at full size, without touching the preview results.
|
||||
pub fn cook_full(&self, gi: usize) -> Cooked {
|
||||
let dec = self.resource_decoder();
|
||||
let opts = Options::new(&dec);
|
||||
let mut opts = Options::new(&dec);
|
||||
opts.max_size = self.cook_limit;
|
||||
materialcraft_eval::cook(&self.pkg, gi, &opts, &self.cache)
|
||||
}
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@ use crate::session::Session;
|
||||
fn normal_map_session() -> Session {
|
||||
let mut pkg = Package::new("T");
|
||||
let png = encode(&Image::filled(4, 4, Kind::Color, [0.5, 0.5, 1.0, 1.0]), "png", Depth::U8, false).unwrap();
|
||||
pkg.resources.push(Resource { name: "n".into(), file: "n.png".into(), bytes: materialcraft_core::ResourceBytes::new(png) });
|
||||
pkg.resources.push(Resource::new("n", "n.png", materialcraft_core::ResourceBytes::new(png)));
|
||||
Session::new(pkg)
|
||||
}
|
||||
|
||||
|
||||
@@ -12,14 +12,19 @@ pub const SCENES: &[(&str, &str)] = &[
|
||||
("cube", "Cube"),
|
||||
("cylinder", "Cylinder"),
|
||||
("plane", "Plane"),
|
||||
("plane_hires", "Plane (hi-res)"),
|
||||
("sphere", "Sphere"),
|
||||
("cloth", "Cloth"),
|
||||
("material_ball", "Mat ball"),
|
||||
("rounded_cube", "Rounded cube"),
|
||||
("rounded_cylinder", "Rounded cylinder"),
|
||||
("sphere_2_tiles", "Sphere 2 tiles"),
|
||||
("torus", "Torus"),
|
||||
];
|
||||
|
||||
/// Environments: (id, label).
|
||||
pub const ENVIRONMENTS: &[(&str, &str)] = &[("studio", "Studio"), ("sunset", "Sunset"), ("overcast", "Overcast"), ("night", "Night")];
|
||||
pub const ENVIRONMENTS: &[(&str, &str)] =
|
||||
&[("studio", "Studio"), ("contrast", "Studio contrast"), ("warehouse", "Warehouse"), ("sunset", "Sunset"), ("overcast", "Overcast"), ("night", "Night")];
|
||||
|
||||
pub(crate) fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
@@ -29,16 +34,34 @@ pub(crate) fn specs() -> Vec<CommandSpec> {
|
||||
"3D view settings",
|
||||
[],
|
||||
None,
|
||||
"{scene? (cube|cylinder|plane|sphere|material_ball|rounded_cube|torus), tiling?, yaw?, pitch?, distance?, target? ([x, y, z] orbit point in mesh radii from its center, within the pan limit preference), environment? (studio|sunset|overcast|night), envRotation?, exposure?, heightScale? (displacement depth in mesh radii, 0..0.5), heightLevel? (height that stays on the surface, 0..1; 0 = rises out), normalYFlip? (DirectX normal maps; default false/OpenGL), axis?, grid?, transparency? (see through where alpha < 1), alphaView? (show the alpha channel)}",
|
||||
"{scene? (cube|cylinder|plane|plane_hires|sphere|cloth|material_ball|rounded_cube|rounded_cylinder|sphere_2_tiles|torus), tiling?, yaw?, pitch?, distance?, target? ([x, y, z] orbit point in mesh radii from its center, within the pan limit preference), environment? (studio|sunset|overcast|night|contrast|warehouse), envRotation?, exposure?, envEnabled?, heightScale? (displacement depth in mesh radii, 0..0.5), heightLevel? (height that stays on the surface, 0..1; 0 = rises out), normalYFlip? (DirectX normal maps; default false/OpenGL), axis?, grid?, transparency? (see through where alpha < 1), alphaView? (show the alpha channel), camera? ({focalLength, projection, background, backgroundColor, overrideResolution, resolution, resolutionScale, autoClip, near, far}: the keys given change), lights? ({ambientOn, ambient, point: [{on, color, intensity, position}, …]}), renderer? ({useViewportResolution, resolution, scale, samples, aoRays}), display? ({wireframe, backfaceCulling, boundingBox, lights, resolution, stats, fps}), material? ({shader, common: {…}, useMap: {…}, tessellation, uvScale})} returns the whole 3D view state",
|
||||
always,
|
||||
view3d
|
||||
),
|
||||
cmd!("view.3d.loadMesh", "Load mesh...", [], None, "{path} shows an OBJ, glTF or GLB mesh in the 3D view (scene \"custom\")", always, load_mesh),
|
||||
cmd!("view.3d.reset", "Reset scene", [], None, "{}", always, |s, _| {
|
||||
s.view3d = crate::View3d::default();
|
||||
Ok(J::Null)
|
||||
}),
|
||||
cmd!("view.3d.reset", "Reset scene", [], None, "{what?: all|scene|camera|lights|environment|material|renderer|display} (default all)", always, reset3d),
|
||||
cmd!("view.3d.state", "3D view state", [], None, "{} the whole 3D view state as JSON (Scene ▸ Save current state)", always, |s, _| Ok(
|
||||
serde_json::to_value(&s.view3d).unwrap_or(J::Null)
|
||||
)),
|
||||
cmd!(
|
||||
"view.3d.loadState",
|
||||
"Load 3D view state",
|
||||
[],
|
||||
None,
|
||||
"{state: JSON from view.3d.state, keepScene?: bool} restores the 3D view",
|
||||
always,
|
||||
load_state
|
||||
),
|
||||
cmd!("view.previewSize", "Preview size", [], None, "{size: 64..8192, or 0 for full size} caps node outputs while editing", always, preview_size),
|
||||
cmd!(
|
||||
"session.settings",
|
||||
"Session settings",
|
||||
[],
|
||||
None,
|
||||
"{historySize? (1..10000 undo steps), cacheMb? (16..65536, the cooked image cache), cookLimit? (256..8192 px, or 0 for none: caps every cook, exports included)} sets what is given; returns all three",
|
||||
always,
|
||||
session_settings
|
||||
),
|
||||
cmd!(
|
||||
"library.list",
|
||||
"Library",
|
||||
@@ -86,6 +109,102 @@ fn view2d(s: &mut Session, p: &J) -> Result<J> {
|
||||
Ok(serde_json::to_value(&s.view2d).unwrap_or(J::Null))
|
||||
}
|
||||
|
||||
/// Overlay `patch` on `base`: objects merge key by key, arrays element by element (a shorter
|
||||
/// patch leaves the rest), a `null` leaves the value alone, anything else replaces.
|
||||
fn merge_json(base: &mut J, patch: &J) {
|
||||
match (base, patch) {
|
||||
(_, J::Null) => {}
|
||||
(J::Object(b), J::Object(p)) => {
|
||||
for (k, v) in p {
|
||||
match b.get_mut(k) {
|
||||
Some(slot) => merge_json(slot, v),
|
||||
None => {
|
||||
b.insert(k.clone(), v.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
(J::Array(b), J::Array(p)) => {
|
||||
for (i, v) in p.iter().enumerate() {
|
||||
match b.get_mut(i) {
|
||||
Some(slot) => merge_json(slot, v),
|
||||
None => b.push(v.clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
(b, p) => *b = p.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Merge a nested object of the `view.3d` request into one of the view's sub-structs.
|
||||
fn merge_into<T: serde::Serialize + serde::de::DeserializeOwned>(key: &str, current: &T, patch: &J) -> Result<T> {
|
||||
if !patch.is_object() {
|
||||
return Err(bad("view.3d", format!("`{key}` is an object")));
|
||||
}
|
||||
let mut v = serde_json::to_value(current).map_err(|e| bad("view.3d", e.to_string()))?;
|
||||
merge_json(&mut v, patch);
|
||||
serde_json::from_value(v).map_err(|e| bad("view.3d", format!("`{key}`: {e}")))
|
||||
}
|
||||
|
||||
fn reset3d(s: &mut Session, p: &J) -> Result<J> {
|
||||
let d = crate::View3d::default();
|
||||
let v = &mut s.view3d;
|
||||
match strp(p, "what").unwrap_or("all") {
|
||||
"all" => *v = d,
|
||||
"scene" => {
|
||||
v.scene = d.scene;
|
||||
v.tiling = d.tiling;
|
||||
v.height_scale = d.height_scale;
|
||||
v.height_level = d.height_level;
|
||||
}
|
||||
"camera" => {
|
||||
v.yaw = d.yaw;
|
||||
v.pitch = d.pitch;
|
||||
v.distance = d.distance;
|
||||
v.target = d.target;
|
||||
v.camera = d.camera;
|
||||
}
|
||||
"lights" => v.lights = d.lights,
|
||||
"environment" => {
|
||||
v.environment = d.environment;
|
||||
v.env_rotation = d.env_rotation;
|
||||
v.exposure = d.exposure;
|
||||
v.env_enabled = d.env_enabled;
|
||||
}
|
||||
"material" => v.material = d.material,
|
||||
"renderer" => v.renderer = d.renderer,
|
||||
"display" => v.display = d.display,
|
||||
other => return Err(bad("view.3d.reset", format!("unknown `what` `{other}`"))),
|
||||
}
|
||||
Ok(serde_json::to_value(&s.view3d).unwrap_or(J::Null))
|
||||
}
|
||||
|
||||
fn load_state(s: &mut Session, p: &J) -> Result<J> {
|
||||
let state = p.get("state").ok_or_else(|| bad("view.3d.loadState", "`state` is required"))?;
|
||||
let mut v: crate::View3d = merge_into("state", &crate::View3d::default(), state)?;
|
||||
v.sanitize();
|
||||
if !SCENES.iter().any(|(id, _)| *id == v.scene) && !(v.scene == "custom" && s.custom_mesh.is_some()) {
|
||||
v.scene = crate::View3d::default().scene;
|
||||
}
|
||||
if !ENVIRONMENTS.iter().any(|(id, _)| *id == v.environment) {
|
||||
v.environment = crate::View3d::default().environment;
|
||||
}
|
||||
if boolp(p, "keepScene").unwrap_or(false) {
|
||||
v.scene = s.view3d.scene.clone();
|
||||
}
|
||||
v.target = s.camera.clamp_target(v.target);
|
||||
v.yaw = if v.yaw.is_finite() { v.yaw.rem_euclid(360.0) } else { 0.0 };
|
||||
v.pitch = if v.pitch.is_finite() { v.pitch.clamp(-89.0, 89.0) } else { 0.0 };
|
||||
v.distance = if v.distance.is_finite() { v.distance.clamp(1.2, 20.0) } else { 3.2 };
|
||||
v.tiling = if v.tiling.is_finite() { v.tiling.clamp(0.1, 64.0) } else { 1.0 };
|
||||
v.exposure = if v.exposure.is_finite() { v.exposure.clamp(-10.0, 10.0) } else { 0.0 };
|
||||
v.env_rotation = if v.env_rotation.is_finite() { v.env_rotation.rem_euclid(360.0) } else { 0.0 };
|
||||
v.height_scale = if v.height_scale.is_finite() { v.height_scale.clamp(0.0, 0.5) } else { 0.0 };
|
||||
v.height_level = if v.height_level.is_finite() { v.height_level.clamp(0.0, 1.0) } else { 0.0 };
|
||||
s.view3d = v;
|
||||
Ok(serde_json::to_value(&s.view3d).unwrap_or(J::Null))
|
||||
}
|
||||
|
||||
fn view3d(s: &mut Session, p: &J) -> Result<J> {
|
||||
// Validated up front so a bad target changes nothing.
|
||||
let target = match p.get("target") {
|
||||
@@ -99,6 +218,12 @@ fn view3d(s: &mut Session, p: &J) -> Result<J> {
|
||||
}
|
||||
}
|
||||
};
|
||||
// Nested objects are parsed first: a bad one changes nothing.
|
||||
let camera = p.get("camera").map(|c| merge_into("camera", &s.view3d.camera, c)).transpose()?;
|
||||
let lights = p.get("lights").map(|l| merge_into("lights", &s.view3d.lights, l)).transpose()?;
|
||||
let renderer = p.get("renderer").map(|r| merge_into("renderer", &s.view3d.renderer, r)).transpose()?;
|
||||
let display = p.get("display").map(|d| merge_into("display", &s.view3d.display, d)).transpose()?;
|
||||
let material = p.get("material").map(|m| merge_into("material", &s.view3d.material, m)).transpose()?;
|
||||
// A rejected environment must not leave a new scene applied.
|
||||
let environment = strp(p, "environment");
|
||||
if let Some(e) = environment
|
||||
@@ -162,6 +287,25 @@ fn view3d(s: &mut Session, p: &J) -> Result<J> {
|
||||
if let Some(b) = boolp(p, "alphaView") {
|
||||
v.alpha_view = b;
|
||||
}
|
||||
if let Some(b) = boolp(p, "envEnabled") {
|
||||
v.env_enabled = b;
|
||||
}
|
||||
if let Some(c) = camera {
|
||||
v.camera = c;
|
||||
}
|
||||
if let Some(l) = lights {
|
||||
v.lights = l;
|
||||
}
|
||||
if let Some(r) = renderer {
|
||||
v.renderer = r;
|
||||
}
|
||||
if let Some(d) = display {
|
||||
v.display = d;
|
||||
}
|
||||
if let Some(m) = material {
|
||||
v.material = m;
|
||||
}
|
||||
v.sanitize();
|
||||
Ok(serde_json::to_value(&s.view3d).unwrap_or(J::Null))
|
||||
}
|
||||
|
||||
@@ -187,6 +331,28 @@ fn preview_size(s: &mut Session, p: &J) -> Result<J> {
|
||||
Ok(json!({"previewSize": s.preview_size}))
|
||||
}
|
||||
|
||||
fn session_settings(s: &mut Session, p: &J) -> Result<J> {
|
||||
if let Some(n) = u64p(p, "historySize") {
|
||||
s.max_undo = n.clamp(1, 10_000) as usize;
|
||||
s.trim_undo();
|
||||
}
|
||||
if let Some(mb) = u64p(p, "cacheMb") {
|
||||
let bytes = (mb.clamp(16, 65_536) as usize) << 20;
|
||||
if let Ok(mut c) = s.cache.lock() {
|
||||
c.set_cap(bytes);
|
||||
}
|
||||
}
|
||||
if let Some(px) = u64p(p, "cookLimit") {
|
||||
let limit = if px == 0 { None } else { Some(px.clamp(256, 8192) as u32) };
|
||||
if limit != s.cook_limit {
|
||||
s.cook_limit = limit;
|
||||
s.dirty = true;
|
||||
}
|
||||
}
|
||||
let cache_mb = s.cache.lock().map(|c| c.cap() >> 20).unwrap_or(0);
|
||||
Ok(json!({"historySize": s.max_undo, "cacheMb": cache_mb, "cookLimit": s.cook_limit.unwrap_or(0)}))
|
||||
}
|
||||
|
||||
fn library(_: &mut Session, p: &J) -> Result<J> {
|
||||
let f = strp(p, "filter").map(str::to_ascii_lowercase);
|
||||
let cat = strp(p, "category").map(str::to_ascii_lowercase);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use materialcraft_engine::{Session, command_specs, execute, sample_session};
|
||||
use materialcraft_engine::{Session, command_specs, execute, new_session, sample_session};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn run(s: &mut Session, id: &str, p: Value) -> Value {
|
||||
@@ -256,7 +256,15 @@ fn panic_hunt() {
|
||||
// Skip file writes to the working directory and opening paths.
|
||||
if matches!(
|
||||
spec.id,
|
||||
"file.save" | "file.saveAs" | "file.export" | "file.open" | "file.importBitmap" | "file.exportMaterial" | "file.sendToTextureCraft"
|
||||
"file.save"
|
||||
| "file.saveAs"
|
||||
| "file.saveCopy"
|
||||
| "file.exportWithDependencies"
|
||||
| "file.export"
|
||||
| "file.open"
|
||||
| "file.importBitmap"
|
||||
| "file.exportMaterial"
|
||||
| "file.sendToTextureCraft"
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
@@ -490,3 +498,39 @@ fn selected_wires_swap_their_sources_and_delete_together() {
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(s.graph().unwrap().connections.len(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn graphs_import_from_another_package_with_their_dependencies() {
|
||||
use materialcraft_engine::core::{Package, Resource, ResourceBytes, Value};
|
||||
let mut from = Package::new("Other");
|
||||
from.graphs.push(materialcraft_engine::samples::template("empty", "Leaf", 8));
|
||||
from.graphs.push(materialcraft_engine::samples::template("empty", "Root", 8));
|
||||
from.resources.push(Resource::new("tex", "tex.png", ResourceBytes::new(vec![1, 2, 3])));
|
||||
{
|
||||
let root = &mut from.graphs[1];
|
||||
let inst = root.add_node("graph_instance", [0.0, 0.0]);
|
||||
root.node_mut(inst).unwrap().params.insert("graph".into(), Value::Text("Leaf".into()));
|
||||
let bm = root.add_node("bitmap", [0.0, 100.0]);
|
||||
root.node_mut(bm).unwrap().params.insert("resource".into(), Value::Text("tex".into()));
|
||||
}
|
||||
let mut s = new_session();
|
||||
let name = materialcraft_engine::file_cmds::import_graph_from(&mut s, &from, "Root").unwrap();
|
||||
assert_eq!(name, "Root");
|
||||
assert!(s.pkg.graph_by_name("Leaf").is_some(), "the instanced graph comes along");
|
||||
assert!(s.pkg.resource("tex").is_some(), "the bitmap comes along");
|
||||
// Importing again reuses identical graphs instead of duplicating them.
|
||||
let again = materialcraft_engine::file_cmds::import_graph_from(&mut s, &from, "Root").unwrap();
|
||||
assert_eq!(again, "Root");
|
||||
assert_eq!(s.pkg.graphs.iter().filter(|g| g.name.starts_with("Leaf")).count(), 1);
|
||||
assert!(materialcraft_engine::file_cmds::import_graph_from(&mut s, &from, "Nope").is_err());
|
||||
// graph.add pastes a graph as JSON and refuses garbage.
|
||||
let g = serde_json::to_value(&from.graphs[0]).unwrap();
|
||||
let r = execute(&mut s, "graph.add", &json!({"graph": g})).unwrap();
|
||||
assert_eq!(r["name"], "Leaf_1");
|
||||
assert!(execute(&mut s, "graph.add", &json!({"graph": "nope"})).is_err());
|
||||
assert!(execute(&mut s, "graph.add", &json!({})).is_err());
|
||||
// Resources can be removed.
|
||||
execute(&mut s, "file.deleteResource", &json!({"name": "tex"})).unwrap();
|
||||
assert!(s.pkg.resource("tex").is_none());
|
||||
assert!(execute(&mut s, "file.deleteResource", &json!({"name": "tex"})).is_err());
|
||||
}
|
||||
@@ -51,3 +51,66 @@ fn valid_view_updates_still_apply_and_return_the_complete_settings() {
|
||||
assert_eq!(result["target"], json!([1.0, 2.0, 3.0]));
|
||||
assert_eq!(result, serde_json::to_value(&s.view3d).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_3d_settings_merge_sanitize_and_reject_as_a_whole() {
|
||||
let mut s = new_session();
|
||||
// Only the keys given change; the rest of the sub-struct stays.
|
||||
let v = execute(&mut s, "view.3d", &json!({"camera": {"focalLength": 50}, "lights": {"point": [{"on": true, "intensity": 3}]}})).unwrap();
|
||||
assert_eq!(v["camera"]["focalLength"], 50.0);
|
||||
assert_eq!(v["camera"]["projection"], "perspective");
|
||||
assert_eq!(v["lights"]["point"][0]["on"], true);
|
||||
assert_eq!(v["lights"]["point"][0]["intensity"], 3.0);
|
||||
assert_eq!(v["lights"]["point"][1]["on"], false);
|
||||
let before = s.view3d.clone();
|
||||
// A malformed nested object rejects the whole request, scalars included.
|
||||
assert!(execute(&mut s, "view.3d", &json!({"yaw": 10, "camera": "nope"})).is_err());
|
||||
assert!(execute(&mut s, "view.3d", &json!({"yaw": 10, "material": {"shader": "unknown"}})).is_err());
|
||||
assert_eq!(s.view3d, before);
|
||||
// Hostile values are clamped, not kept.
|
||||
let v = execute(&mut s, "view.3d", &json!({"camera": {"focalLength": 1e30, "near": -5, "far": 1e-9}, "material": {"common": {"ior": f64::NAN, "baseColor": [99.0, -1.0, 0.5]}, "tessellation": 1e9}})).unwrap();
|
||||
assert_eq!(v["camera"]["focalLength"], 1200.0);
|
||||
assert!(v["camera"]["far"].as_f64().unwrap() > v["camera"]["near"].as_f64().unwrap());
|
||||
assert_eq!(v["material"]["common"]["ior"], 1.5);
|
||||
assert_eq!(v["material"]["common"]["baseColor"], json!([64.0, 0.0, 0.5]));
|
||||
assert_eq!(v["material"]["tessellation"], 4.0);
|
||||
// Reset one part leaves the others.
|
||||
execute(&mut s, "view.3d", &json!({"scene": "torus"})).unwrap();
|
||||
execute(&mut s, "view.3d.reset", &json!({"what": "camera"})).unwrap();
|
||||
assert_eq!(s.view3d.camera, materialcraft_engine::Camera3d::default());
|
||||
assert_eq!(s.view3d.scene, "torus");
|
||||
assert!(execute(&mut s, "view.3d.reset", &json!({"what": "nope"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn state_round_trips_and_garbage_state_falls_back_to_defaults() {
|
||||
let mut s = new_session();
|
||||
execute(&mut s, "view.3d", &json!({"scene": "cloth", "environment": "warehouse", "exposure": 1.5, "lights": {"ambient": [0.2, 0.2, 0.2]}})).unwrap();
|
||||
let state = execute(&mut s, "view.3d.state", &json!({})).unwrap();
|
||||
execute(&mut s, "view.3d.reset", &json!({})).unwrap();
|
||||
assert_eq!(s.view3d.scene, "rounded_cube");
|
||||
execute(&mut s, "view.3d.loadState", &json!({"state": state, "keepScene": true})).unwrap();
|
||||
assert_eq!(s.view3d.scene, "rounded_cube", "keepScene leaves the mesh");
|
||||
assert_eq!(s.view3d.environment, "warehouse");
|
||||
assert_eq!(s.view3d.exposure, 1.5);
|
||||
execute(&mut s, "view.3d.loadState", &json!({"state": {"scene": "nope", "environment": "nope", "yaw": f64::INFINITY, "distance": 1e9}})).unwrap();
|
||||
assert_eq!(s.view3d.scene, "rounded_cube");
|
||||
assert_eq!(s.view3d.environment, "studio");
|
||||
assert_eq!(s.view3d.distance, 20.0);
|
||||
assert!(execute(&mut s, "view.3d.loadState", &json!({"state": 5})).is_err());
|
||||
assert!(execute(&mut s, "view.3d.loadState", &json!({})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_settings_bound_history_cache_and_cook_size() {
|
||||
let mut s = new_session();
|
||||
let v = execute(&mut s, "session.settings", &json!({"historySize": 3, "cacheMb": 1, "cookLimit": 100})).unwrap();
|
||||
assert_eq!(v["historySize"], 3);
|
||||
assert_eq!(v["cacheMb"], 16, "the cache keeps at least 16 MB");
|
||||
assert_eq!(v["cookLimit"], 256);
|
||||
for _ in 0..6 {
|
||||
execute(&mut s, "graph.node.add", &json!({"def": "uniform"})).unwrap();
|
||||
}
|
||||
assert_eq!(s.history().len(), 3, "only 3 steps are kept");
|
||||
assert_eq!(execute(&mut s, "session.settings", &json!({"cookLimit": 0})).unwrap()["cookLimit"], 0);
|
||||
}
|
||||
+21
-6
@@ -134,6 +134,26 @@ impl Cache {
|
||||
self.bytes
|
||||
}
|
||||
|
||||
/// The cache's size limit in bytes.
|
||||
pub fn cap(&self) -> usize {
|
||||
self.cap
|
||||
}
|
||||
|
||||
/// Change the size limit (at least 16 MB), evicting the least recently used entries past it.
|
||||
pub fn set_cap(&mut self, cap_bytes: usize) {
|
||||
self.cap = cap_bytes.max(16 << 20);
|
||||
self.evict();
|
||||
}
|
||||
|
||||
fn evict(&mut self) {
|
||||
while self.bytes > self.cap && self.entries.len() > 1 {
|
||||
let Some((&k, _)) = self.entries.iter().min_by_key(|(_, e)| e.2) else { break };
|
||||
if let Some(e) = self.entries.remove(&k) {
|
||||
self.bytes = self.bytes.saturating_sub(e.1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.entries.len()
|
||||
}
|
||||
@@ -164,12 +184,7 @@ impl Cache {
|
||||
self.bytes = self.bytes.saturating_sub(old.1);
|
||||
}
|
||||
self.bytes += size;
|
||||
while self.bytes > self.cap && self.entries.len() > 1 {
|
||||
let Some((&k, _)) = self.entries.iter().min_by_key(|(_, e)| e.2) else { break };
|
||||
if let Some(e) = self.entries.remove(&k) {
|
||||
self.bytes = self.bytes.saturating_sub(e.1);
|
||||
}
|
||||
}
|
||||
self.evict();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -369,7 +369,7 @@ mod tests {
|
||||
fn zip_resources(resources: &[(&str, &str)], entries: &[(&str, &[u8])]) -> Vec<u8> {
|
||||
let mut p = Package::new("T");
|
||||
for (n, f) in resources {
|
||||
p.resources.push(Resource { name: (*n).into(), file: (*f).into(), bytes: ResourceBytes::default() });
|
||||
p.resources.push(Resource::new(*n, *f, ResourceBytes::default()));
|
||||
}
|
||||
let json = serde_json::to_vec(&p).unwrap();
|
||||
let mut buf = Cursor::new(Vec::new());
|
||||
@@ -418,7 +418,7 @@ mod tests {
|
||||
fn colliding_resource_file_names_save_and_load() {
|
||||
let mut p = Package::new("T");
|
||||
for (n, f, b) in [("a", "a/x.png", 1u8), ("b", "b/x.png", 2)] {
|
||||
p.resources.push(Resource { name: n.into(), file: f.into(), bytes: ResourceBytes::new(vec![b; 8]) });
|
||||
p.resources.push(Resource::new(n, f, ResourceBytes::new(vec![b; 8])));
|
||||
}
|
||||
let q = load_package(&save_package(&p).unwrap()).unwrap();
|
||||
assert_eq!(q.resources[0].bytes.as_slice()[0], 1);
|
||||
|
||||
+35
-11
@@ -759,6 +759,7 @@ impl<'text> Reader<'text, '_> {
|
||||
let format = child_value(item, "format").unwrap_or("png").trim().to_ascii_lowercase();
|
||||
let source = child_element(item, "source");
|
||||
let mut bytes: Option<Vec<u8>> = None;
|
||||
let mut link: Option<String> = None;
|
||||
let mut why_missing = String::new();
|
||||
|
||||
if let Some(embedded) = source.and_then(|s| child_element(s, "binembedded")) {
|
||||
@@ -778,6 +779,7 @@ impl<'text> Reader<'text, '_> {
|
||||
match linked(file) {
|
||||
Some(data) => {
|
||||
bytes = Some(data);
|
||||
link = Some(file.to_string());
|
||||
break;
|
||||
}
|
||||
None => why_missing = format!("its file `{file}` was not found next to the package"),
|
||||
@@ -791,7 +793,11 @@ impl<'text> Reader<'text, '_> {
|
||||
match bytes {
|
||||
Some(data) => {
|
||||
let ext = if kind == "svg" { "svg".to_string() } else { format };
|
||||
pkg.resources.push(Resource::new(name.clone(), crate::safe_file_name(&format!("{name}.{ext}")), ResourceBytes::new(data)));
|
||||
let file = crate::safe_file_name(&format!("{name}.{ext}"));
|
||||
pkg.resources.push(match link {
|
||||
Some(l) => Resource::linked(name.clone(), file, ResourceBytes::new(data), l),
|
||||
None => Resource::new(name.clone(), file, ResourceBytes::new(data)),
|
||||
});
|
||||
}
|
||||
None => {
|
||||
let why = if why_missing.is_empty() { "it has no data".to_string() } else { why_missing };
|
||||
@@ -1398,16 +1404,34 @@ pub fn write_sbs(pkg: &Package) -> Result<Vec<u8>> {
|
||||
for resource in &pkg.resources {
|
||||
let svg = resource.file.to_ascii_lowercase().ends_with(".svg");
|
||||
let ext = resource.file.rsplit_once('.').map_or("png", |(_, e)| e);
|
||||
let _ = write!(
|
||||
content,
|
||||
"<resource><identifier v=\"{}\"/><uid v=\"{}\"/><type v=\"{}\"/><format v=\"{}\"/><filepath v=\"\"/><source><binembedded><datalength v=\"{}\"/><strdata v=\"{}\"/></binembedded></source></resource>",
|
||||
xml_escape(&resource.name),
|
||||
writer.next_uid(),
|
||||
if svg { "svg" } else { "bitmap" },
|
||||
xml_escape(ext),
|
||||
resource.bytes.len(),
|
||||
encode_embedded(resource.bytes.as_slice())?
|
||||
);
|
||||
// A resource linked to a file next to the package stays a link; one linked from
|
||||
// elsewhere (or opened without a folder) is embedded, so the file is whole.
|
||||
let relative = resource.link.as_deref().filter(|l| !l.contains(':') && !l.starts_with('/') && !l.starts_with('\\'));
|
||||
match relative {
|
||||
Some(path) => {
|
||||
let _ = write!(
|
||||
content,
|
||||
"<resource><identifier v=\"{}\"/><uid v=\"{}\"/><type v=\"{}\"/><format v=\"{}\"/><filepath v=\"{}\"/></resource>",
|
||||
xml_escape(&resource.name),
|
||||
writer.next_uid(),
|
||||
if svg { "svg" } else { "bitmap" },
|
||||
xml_escape(ext),
|
||||
xml_escape(path)
|
||||
);
|
||||
}
|
||||
None => {
|
||||
let _ = write!(
|
||||
content,
|
||||
"<resource><identifier v=\"{}\"/><uid v=\"{}\"/><type v=\"{}\"/><format v=\"{}\"/><filepath v=\"\"/><source><binembedded><datalength v=\"{}\"/><strdata v=\"{}\"/></binembedded></source></resource>",
|
||||
xml_escape(&resource.name),
|
||||
writer.next_uid(),
|
||||
if svg { "svg" } else { "bitmap" },
|
||||
xml_escape(ext),
|
||||
resource.bytes.len(),
|
||||
encode_embedded(resource.bytes.as_slice())?
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
content.push_str("</content></group>");
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ pub mod bvh;
|
||||
pub mod camera;
|
||||
pub mod gbuffer;
|
||||
pub mod mesh;
|
||||
pub mod preview;
|
||||
pub mod primitives;
|
||||
pub mod unwrap;
|
||||
|
||||
|
||||
@@ -0,0 +1,233 @@
|
||||
//! The 3D preview's plain-data description shared by the engine (where it is session state)
|
||||
//! and the renderer: what shows behind the mesh, the lights, the shading model and the
|
||||
//! material's common values.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// What shows where a camera ray misses the mesh.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Background {
|
||||
/// The studio vignette.
|
||||
Backdrop,
|
||||
/// A flat color (linear RGB).
|
||||
Color([f32; 3]),
|
||||
/// The (blurred) environment map.
|
||||
Environment,
|
||||
}
|
||||
|
||||
/// A point light in the scene (position in scene radii from the center).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct PointLight {
|
||||
pub on: bool,
|
||||
/// Linear RGB.
|
||||
pub color: [f32; 3],
|
||||
pub intensity: f32,
|
||||
pub position: [f32; 3],
|
||||
}
|
||||
|
||||
impl PointLight {
|
||||
/// The two default lights: key from the upper left, fill from the right and behind.
|
||||
pub const DEFAULTS: [PointLight; 2] = [
|
||||
PointLight { on: false, color: [1.0; 3], intensity: 1.0, position: [-2.5, 3.0, 2.5] },
|
||||
PointLight { on: false, color: [0.2; 3], intensity: 1.0, position: [3.0, 1.0, -2.0] },
|
||||
];
|
||||
|
||||
/// Every value brought into its range; non-finite values become the default.
|
||||
pub fn sanitized(mut self, default: PointLight) -> PointLight {
|
||||
for (v, d) in self.color.iter_mut().zip(default.color) {
|
||||
*v = if v.is_finite() { v.clamp(0.0, 64.0) } else { d };
|
||||
}
|
||||
self.intensity = if self.intensity.is_finite() { self.intensity.clamp(0.0, 100.0) } else { default.intensity };
|
||||
for (v, d) in self.position.iter_mut().zip(default.position) {
|
||||
*v = if v.is_finite() { v.clamp(-50.0, 50.0) } else { d };
|
||||
}
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for PointLight {
|
||||
fn default() -> Self {
|
||||
PointLight::DEFAULTS[0]
|
||||
}
|
||||
}
|
||||
|
||||
/// The shading model.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Shader {
|
||||
/// Metallic/roughness with coat, fuzz, emission, thin film, transmission and subsurface terms.
|
||||
OpenPbr,
|
||||
/// Plain metallic/roughness.
|
||||
MetallicRoughness,
|
||||
/// Metallic/roughness with the coat layer.
|
||||
Coated,
|
||||
/// Metallic/roughness with the subsurface term.
|
||||
Subsurface,
|
||||
/// Specular color / glossiness maps instead of metallic / roughness.
|
||||
SpecularGlossiness,
|
||||
/// Lambert diffuse plus a Blinn-Phong highlight from the lights.
|
||||
Blinn,
|
||||
/// Diffuse only.
|
||||
Lambert,
|
||||
/// The base color as is.
|
||||
Unlit,
|
||||
/// Normals as colors (surface inspection).
|
||||
MeshInfo,
|
||||
}
|
||||
|
||||
impl Shader {
|
||||
pub const ALL: [(Shader, &'static str); 9] = [
|
||||
(Shader::OpenPbr, "openPbr"),
|
||||
(Shader::MetallicRoughness, "metallicRoughness"),
|
||||
(Shader::Coated, "coated"),
|
||||
(Shader::Subsurface, "subsurface"),
|
||||
(Shader::SpecularGlossiness, "specularGlossiness"),
|
||||
(Shader::Blinn, "blinn"),
|
||||
(Shader::Lambert, "lambert"),
|
||||
(Shader::Unlit, "unlit"),
|
||||
(Shader::MeshInfo, "meshInfo"),
|
||||
];
|
||||
|
||||
pub fn id(self) -> &'static str {
|
||||
Self::ALL.iter().find(|(s, _)| *s == self).map_or("openPbr", |(_, id)| id)
|
||||
}
|
||||
|
||||
pub fn by_id(id: &str) -> Option<Shader> {
|
||||
Self::ALL.iter().find(|(_, i)| *i == id).map(|(s, _)| *s)
|
||||
}
|
||||
}
|
||||
|
||||
/// Which maps drive the material (off = the common value is used even when the map exists).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct MapUse {
|
||||
pub base_color: bool,
|
||||
pub roughness: bool,
|
||||
pub metallic: bool,
|
||||
pub normal: bool,
|
||||
pub height: bool,
|
||||
pub ao: bool,
|
||||
pub emissive: bool,
|
||||
pub opacity: bool,
|
||||
pub specular: bool,
|
||||
}
|
||||
|
||||
impl Default for MapUse {
|
||||
fn default() -> Self {
|
||||
MapUse { base_color: true, roughness: true, metallic: true, normal: true, height: true, ao: true, emissive: true, opacity: true, specular: true }
|
||||
}
|
||||
}
|
||||
|
||||
/// The material's common values: what each channel is where no map drives it, and the layer
|
||||
/// terms that have no map at all. Colors are linear RGB; weights 0..1.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct Common {
|
||||
pub base_weight: f32,
|
||||
pub base_color: [f32; 3],
|
||||
pub metalness: f32,
|
||||
pub diffuse_roughness: f32,
|
||||
pub specular_weight: f32,
|
||||
pub specular_color: [f32; 3],
|
||||
pub specular_roughness: f32,
|
||||
pub ior: f32,
|
||||
pub transmission_weight: f32,
|
||||
pub transmission_color: [f32; 3],
|
||||
pub subsurface_weight: f32,
|
||||
pub subsurface_color: [f32; 3],
|
||||
pub coat_weight: f32,
|
||||
pub coat_color: [f32; 3],
|
||||
pub coat_roughness: f32,
|
||||
pub coat_ior: f32,
|
||||
pub coat_darkening: f32,
|
||||
pub fuzz_weight: f32,
|
||||
pub fuzz_color: [f32; 3],
|
||||
pub emission_luminance: f32,
|
||||
pub emission_color: [f32; 3],
|
||||
pub thin_film_weight: f32,
|
||||
/// Nanometres.
|
||||
pub thin_film_thickness: f32,
|
||||
pub thin_film_ior: f32,
|
||||
pub opacity: f32,
|
||||
pub thin_walled: bool,
|
||||
pub ambient_occlusion: f32,
|
||||
pub height: f32,
|
||||
}
|
||||
|
||||
impl Default for Common {
|
||||
fn default() -> Self {
|
||||
Common {
|
||||
base_weight: 1.0,
|
||||
base_color: [0.5; 3],
|
||||
metalness: 0.0,
|
||||
diffuse_roughness: 0.0,
|
||||
specular_weight: 1.0,
|
||||
specular_color: [1.0; 3],
|
||||
specular_roughness: 0.5,
|
||||
ior: 1.5,
|
||||
transmission_weight: 0.0,
|
||||
transmission_color: [1.0; 3],
|
||||
subsurface_weight: 0.0,
|
||||
subsurface_color: [0.8; 3],
|
||||
coat_weight: 0.0,
|
||||
coat_color: [1.0; 3],
|
||||
coat_roughness: 0.0,
|
||||
coat_ior: 1.6,
|
||||
coat_darkening: 1.0,
|
||||
fuzz_weight: 0.0,
|
||||
fuzz_color: [1.0; 3],
|
||||
emission_luminance: 0.0,
|
||||
emission_color: [1.0; 3],
|
||||
thin_film_weight: 0.0,
|
||||
thin_film_thickness: 500.0,
|
||||
thin_film_ior: 1.4,
|
||||
opacity: 1.0,
|
||||
thin_walled: false,
|
||||
ambient_occlusion: 1.0,
|
||||
height: 0.5,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Common {
|
||||
/// Every value brought into its range; non-finite values become the default.
|
||||
pub fn sanitized(mut self) -> Common {
|
||||
let d = Common::default();
|
||||
let unit = |v: &mut f32, dv: f32| *v = if v.is_finite() { v.clamp(0.0, 1.0) } else { dv };
|
||||
let col = |c: &mut [f32; 3], dc: [f32; 3]| {
|
||||
for (v, dv) in c.iter_mut().zip(dc) {
|
||||
*v = if v.is_finite() { v.clamp(0.0, 64.0) } else { dv };
|
||||
}
|
||||
};
|
||||
unit(&mut self.base_weight, d.base_weight);
|
||||
col(&mut self.base_color, d.base_color);
|
||||
unit(&mut self.metalness, d.metalness);
|
||||
unit(&mut self.diffuse_roughness, d.diffuse_roughness);
|
||||
unit(&mut self.specular_weight, d.specular_weight);
|
||||
col(&mut self.specular_color, d.specular_color);
|
||||
unit(&mut self.specular_roughness, d.specular_roughness);
|
||||
self.ior = if self.ior.is_finite() { self.ior.clamp(1.0, 3.0) } else { d.ior };
|
||||
unit(&mut self.transmission_weight, d.transmission_weight);
|
||||
col(&mut self.transmission_color, d.transmission_color);
|
||||
unit(&mut self.subsurface_weight, d.subsurface_weight);
|
||||
col(&mut self.subsurface_color, d.subsurface_color);
|
||||
unit(&mut self.coat_weight, d.coat_weight);
|
||||
col(&mut self.coat_color, d.coat_color);
|
||||
unit(&mut self.coat_roughness, d.coat_roughness);
|
||||
self.coat_ior = if self.coat_ior.is_finite() { self.coat_ior.clamp(1.0, 3.0) } else { d.coat_ior };
|
||||
unit(&mut self.coat_darkening, d.coat_darkening);
|
||||
unit(&mut self.fuzz_weight, d.fuzz_weight);
|
||||
col(&mut self.fuzz_color, d.fuzz_color);
|
||||
self.emission_luminance = if self.emission_luminance.is_finite() { self.emission_luminance.clamp(0.0, 100.0) } else { d.emission_luminance };
|
||||
col(&mut self.emission_color, d.emission_color);
|
||||
unit(&mut self.thin_film_weight, d.thin_film_weight);
|
||||
self.thin_film_thickness = if self.thin_film_thickness.is_finite() { self.thin_film_thickness.clamp(0.0, 2000.0) } else { d.thin_film_thickness };
|
||||
self.thin_film_ior = if self.thin_film_ior.is_finite() { self.thin_film_ior.clamp(1.0, 3.0) } else { d.thin_film_ior };
|
||||
unit(&mut self.opacity, d.opacity);
|
||||
unit(&mut self.ambient_occlusion, d.ambient_occlusion);
|
||||
unit(&mut self.height, d.height);
|
||||
self
|
||||
}
|
||||
}
|
||||
@@ -216,6 +216,42 @@ pub fn cylinder(radius: f32, height: f32, segs: usize) -> Mesh {
|
||||
b.finish("Cylinder")
|
||||
}
|
||||
|
||||
/// A cylinder along Y with rounded rims (`bevel` = rim radius).
|
||||
pub fn rounded_cylinder(radius: f32, height: f32, bevel: f32, segs: usize) -> Mesh {
|
||||
let mut b = Builder::default();
|
||||
let h = height * 0.5;
|
||||
let bev = bevel.clamp(0.0, radius.min(h) * 0.9);
|
||||
let mut profile = Vec::new();
|
||||
for k in 0..=6 {
|
||||
let a = k as f32 / 6.0 * PI * 0.5;
|
||||
profile.push((radius - bev + bev * a.sin(), h - bev + bev * a.cos()));
|
||||
}
|
||||
for k in 0..=6 {
|
||||
let a = k as f32 / 6.0 * PI * 0.5;
|
||||
profile.push((radius - bev + bev * a.cos(), -h + bev - bev * a.sin()));
|
||||
}
|
||||
lathe_into(&mut b, Vec3::ZERO, &profile, segs.max(3), UvRect { o: Vec2::ZERO, s: Vec2::new(1.0, 0.5) }.inset(0.01));
|
||||
disk_into(&mut b, Vec3::Y * h, radius - bev, true, segs.max(3), UvRect { o: Vec2::new(0.0, 0.5), s: Vec2::splat(0.5) }.inset(0.01));
|
||||
disk_into(&mut b, -Vec3::Y * h, radius - bev, false, segs.max(3), UvRect { o: Vec2::new(0.5, 0.5), s: Vec2::splat(0.5) }.inset(0.01));
|
||||
b.finish("Rounded cylinder")
|
||||
}
|
||||
|
||||
/// A draped square of cloth: a plane with soft folds, facing +Y.
|
||||
pub fn cloth(size: f32, subdivisions: usize) -> Mesh {
|
||||
let mut b = Builder::default();
|
||||
let s = subdivisions.max(8);
|
||||
let fold = |x: f32, z: f32| 0.07 * (x * 4.2).sin() * (z * 2.6 + 0.5).cos() + 0.035 * (x * 9.0 + z * 7.0).sin() + 0.02 * (z * 12.0).cos();
|
||||
b.grid(s, s, |i, j| {
|
||||
let (u, v) = (j as f32 / s as f32, i as f32 / s as f32);
|
||||
let (x, z) = ((u - 0.5) * size, (v - 0.5) * size);
|
||||
let y = fold(x, z);
|
||||
let e = 1e-3;
|
||||
let (dx, dz) = ((fold(x + e, z) - fold(x - e, z)) / (2.0 * e), (fold(x, z + e) - fold(x, z - e)) / (2.0 * e));
|
||||
(Vec3::new(x, y, z), Vec3::new(-dx, 1.0, -dz), Vec2::new(u, v))
|
||||
});
|
||||
b.finish("Cloth")
|
||||
}
|
||||
|
||||
/// A torus around Y.
|
||||
pub fn torus(major: f32, minor: f32, segs: usize, sides: usize) -> Mesh {
|
||||
let mut b = Builder::default();
|
||||
@@ -330,8 +366,11 @@ pub fn builtin(id: &str) -> Option<Mesh> {
|
||||
"cube" => cube(2.0),
|
||||
"rounded_cube" | "roundedcube" | "box" => rounded_box(Vec3::ONE, 0.15),
|
||||
"cylinder" => cylinder(1.0, 2.0, 96),
|
||||
"rounded_cylinder" | "roundedcylinder" => rounded_cylinder(1.0, 2.0, 0.12, 96),
|
||||
"torus" => torus(1.0, 0.35, 128, 48),
|
||||
"plane" => plane(2.0, 16),
|
||||
"plane_hires" | "planehires" => plane(2.0, 128),
|
||||
"cloth" => cloth(2.0, 96),
|
||||
"crate" => crate_scene(),
|
||||
"udim_plane" | "udimplane" => udim_plane(),
|
||||
_ => return None,
|
||||
@@ -339,14 +378,17 @@ pub fn builtin(id: &str) -> Option<Mesh> {
|
||||
}
|
||||
|
||||
/// Ids accepted by [`builtin`], in menu order.
|
||||
pub const BUILTINS: [(&str, &str); 9] = [
|
||||
pub const BUILTINS: [(&str, &str); 12] = [
|
||||
("material_ball", "Material ball"),
|
||||
("sphere", "Sphere"),
|
||||
("cube", "Cube"),
|
||||
("rounded_cube", "Rounded cube"),
|
||||
("cylinder", "Cylinder"),
|
||||
("rounded_cylinder", "Rounded cylinder"),
|
||||
("torus", "Torus"),
|
||||
("plane", "Plane"),
|
||||
("plane_hires", "Plane (hi-res)"),
|
||||
("cloth", "Cloth"),
|
||||
("crate", "Crate"),
|
||||
("udim_plane", "UDIM plane"),
|
||||
];
|
||||
|
||||
@@ -9,4 +9,7 @@
|
||||
pub mod ibl;
|
||||
pub mod preview;
|
||||
|
||||
pub use preview::{Displacement, Lighting, Maps, Relief, Scene, Settings, VIEW_TRIANGLES, builtin_mesh, pan, render, render_cancellable};
|
||||
pub use preview::{
|
||||
Background, Common, Displacement, Lighting, MapUse, Maps, PointLight, Relief, Scene, Settings, Shader, VIEW_TRIANGLES, builtin_mesh, camera, pan, render,
|
||||
render_cancellable,
|
||||
};
|
||||
+361
-49
@@ -12,6 +12,8 @@ use materialcraft_geom::{Bvh, Mesh, OrbitCamera};
|
||||
use materialcraft_image::{Image, linear_to_srgb};
|
||||
use rayon::prelude::*;
|
||||
|
||||
pub use materialcraft_geom::preview::{Background, Common, MapUse, PointLight, Shader};
|
||||
|
||||
use crate::ibl::{self, EnvImage};
|
||||
|
||||
/// The material's maps (any may be missing: defaults are mid gray, flat, rough 0.5, dielectric).
|
||||
@@ -25,6 +27,10 @@ pub struct Maps {
|
||||
pub ao: Option<Image>,
|
||||
pub emissive: Option<Image>,
|
||||
pub opacity: Option<Image>,
|
||||
/// Specular color (the specular/glossiness workflow and OpenPBR's specular weight).
|
||||
pub specular: Option<Image>,
|
||||
/// Glossiness (the specular/glossiness workflow: 1 − roughness).
|
||||
pub glossiness: Option<Image>,
|
||||
}
|
||||
|
||||
impl Maps {
|
||||
@@ -41,6 +47,8 @@ impl Maps {
|
||||
"ambientOcclusion" => &mut m.ao,
|
||||
"emissive" => &mut m.emissive,
|
||||
"opacity" => &mut m.opacity,
|
||||
"specular" => &mut m.specular,
|
||||
"glossiness" => &mut m.glossiness,
|
||||
_ => continue,
|
||||
};
|
||||
if slot.is_none() {
|
||||
@@ -175,8 +183,9 @@ pub const VIEW_TRIANGLES: usize = 500_000;
|
||||
|
||||
/// A built-in mesh by id; unknown ids give the rounded cube.
|
||||
pub fn builtin_mesh(id: &str) -> Mesh {
|
||||
let mut m = materialcraft_geom::primitives::builtin(id).unwrap_or_else(|| materialcraft_geom::primitives::rounded_box(Vec3::ONE, 0.15));
|
||||
if id == "sphere" {
|
||||
let base = if id == "sphere_2_tiles" { "sphere" } else { id };
|
||||
let mut m = materialcraft_geom::primitives::builtin(base).unwrap_or_else(|| materialcraft_geom::primitives::rounded_box(Vec3::ONE, 0.15));
|
||||
if id == "sphere_2_tiles" {
|
||||
// The texture wraps twice around, so texels are square at the equator.
|
||||
m.uvs.iter_mut().for_each(|uv| uv.x *= 2.0);
|
||||
}
|
||||
@@ -219,7 +228,7 @@ impl Lighting {
|
||||
}
|
||||
|
||||
/// Camera and look.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Settings {
|
||||
/// Degrees.
|
||||
pub yaw: f32,
|
||||
@@ -249,6 +258,27 @@ pub struct Settings {
|
||||
pub transparency: bool,
|
||||
/// Show the material's alpha channel on the mesh, unlit (white = opaque, black = clear).
|
||||
pub alpha_view: bool,
|
||||
/// Vertical field of view, degrees (perspective).
|
||||
pub fov: f32,
|
||||
/// Orthographic projection.
|
||||
pub ortho: bool,
|
||||
/// What a miss shows (`show_env` = true overrides it with the environment).
|
||||
pub background: Background,
|
||||
/// Fixed near and far clip distances in scene radii from the camera (`None` = automatic).
|
||||
pub clip: Option<[f32; 2]>,
|
||||
/// Ambient light added to every surface (linear RGB; black = off).
|
||||
pub ambient: [f32; 3],
|
||||
/// Point lights.
|
||||
pub lights: [PointLight; 2],
|
||||
/// Environment lighting on (off leaves the ambient and point lights).
|
||||
pub env_light: bool,
|
||||
pub shader: Shader,
|
||||
pub common: Common,
|
||||
pub use_map: MapUse,
|
||||
/// Draw the triangle edges over the surface.
|
||||
pub wireframe: bool,
|
||||
/// Skip faces turned away from the camera.
|
||||
pub backface_culling: bool,
|
||||
}
|
||||
|
||||
impl Default for Settings {
|
||||
@@ -268,6 +298,18 @@ impl Default for Settings {
|
||||
key_light: 0.0,
|
||||
transparency: true,
|
||||
alpha_view: false,
|
||||
fov: 35.0,
|
||||
ortho: false,
|
||||
background: Background::Backdrop,
|
||||
clip: None,
|
||||
ambient: [0.0; 3],
|
||||
lights: PointLight::DEFAULTS,
|
||||
env_light: true,
|
||||
shader: Shader::OpenPbr,
|
||||
common: Common::default(),
|
||||
use_map: MapUse::default(),
|
||||
wireframe: false,
|
||||
backface_culling: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -280,9 +322,9 @@ pub fn camera(scene: &Scene, s: &Settings) -> OrbitCamera {
|
||||
yaw: s.yaw.to_radians(),
|
||||
pitch: s.pitch.clamp(-89.0, 89.0).to_radians(),
|
||||
distance: s.distance.clamp(1.05, 50.0) * scene.radius,
|
||||
fov: 35.0,
|
||||
fov: if s.fov.is_finite() { s.fov.clamp(5.0, 120.0) } else { 35.0 },
|
||||
scene_radius: scene.radius,
|
||||
ortho: false,
|
||||
ortho: s.ortho,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -295,16 +337,6 @@ pub fn pan(scene: &Scene, s: &Settings, dx: f32, dy: f32) -> [f32; 3] {
|
||||
t.to_array().map(|v| if v.is_finite() { v } else { 0.0 })
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn tex(img: &Option<Image>, uv: Vec2) -> Option<[f32; 4]> {
|
||||
img.as_ref().map(|i| i.sample(uv.x, uv.y, true))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn tex_gray(img: &Option<Image>, uv: Vec2, default: f32) -> f32 {
|
||||
img.as_ref().map_or(default, |i| i.sample_gray(uv.x, uv.y, true))
|
||||
}
|
||||
|
||||
/// Narkowicz's fit of the ACES filmic curve.
|
||||
#[inline]
|
||||
fn aces(x: f32) -> f32 {
|
||||
@@ -328,11 +360,11 @@ fn rotate_y(v: Vec3, deg: f32) -> Vec3 {
|
||||
|
||||
/// The material's alpha at `uv`: the opacity output, else the base color's alpha channel, else
|
||||
/// opaque.
|
||||
fn alpha(maps: &Maps, uv: Vec2) -> f32 {
|
||||
fn alpha(maps: &Maps, s: &Settings, uv: Vec2) -> f32 {
|
||||
let a = match (&maps.opacity, &maps.base_color) {
|
||||
(Some(o), _) => o.sample_gray(uv.x, uv.y, true),
|
||||
(None, Some(b)) if !b.is_gray() => b.sample(uv.x, uv.y, true)[3],
|
||||
_ => 1.0,
|
||||
(Some(o), _) if s.use_map.opacity => o.sample_gray(uv.x, uv.y, true),
|
||||
(_, Some(b)) if s.use_map.base_color && !b.is_gray() => b.sample(uv.x, uv.y, true)[3] * s.common.opacity,
|
||||
_ => s.common.opacity,
|
||||
};
|
||||
if a.is_finite() { a.clamp(0.0, 1.0) } else { 1.0 }
|
||||
}
|
||||
@@ -391,9 +423,101 @@ struct Shaded {
|
||||
t: f32,
|
||||
}
|
||||
|
||||
/// Schlick Fresnel for a dielectric of `ior` at `cos`.
|
||||
#[inline]
|
||||
fn fresnel(ior: f32, cos: f32) -> f32 {
|
||||
let f0 = ((ior - 1.0) / (ior + 1.0)).powi(2);
|
||||
f0 + (1.0 - f0) * (1.0 - cos.clamp(0.0, 1.0)).powi(5)
|
||||
}
|
||||
|
||||
/// Thin-film interference tint: the reflectance of a film `nm` thick with index `ior` for the
|
||||
/// three wavelengths 650/550/450 nm at `cos` (a cosine-series approximation).
|
||||
#[inline]
|
||||
fn thin_film(nm: f32, ior: f32, cos: f32) -> Vec3 {
|
||||
let sin2 = (1.0 - cos * cos).clamp(0.0, 1.0) / (ior * ior);
|
||||
let cos_t = (1.0 - sin2).max(0.0).sqrt();
|
||||
let path = 2.0 * ior * nm * cos_t;
|
||||
let r = |lambda: f32| 0.5 + 0.5 * (std::f32::consts::TAU * path / lambda).cos();
|
||||
Vec3::new(r(650.0), r(550.0), r(450.0))
|
||||
}
|
||||
|
||||
/// Blinn-Phong highlight exponent from roughness.
|
||||
#[inline]
|
||||
fn blinn_exponent(rough: f32) -> f32 {
|
||||
2.0 / (rough * rough).max(1e-3) - 2.0
|
||||
}
|
||||
|
||||
/// What the maps (or the common values) say about the surface at `uv`.
|
||||
struct Surface {
|
||||
base: Vec3,
|
||||
rough: f32,
|
||||
metal: f32,
|
||||
ao: f32,
|
||||
/// Dielectric reflectance at normal incidence (the specular workflow's specular color).
|
||||
spec_f0: Vec3,
|
||||
}
|
||||
|
||||
fn surface(maps: &Maps, s: &Settings, uv: Vec2) -> Surface {
|
||||
let c = &s.common;
|
||||
let common_base = Vec3::from(c.base_color) * c.base_weight;
|
||||
let base = match &maps.base_color {
|
||||
Some(b) if s.use_map.base_color => {
|
||||
let v = b.sample(uv.x, uv.y, true);
|
||||
Vec3::new(v[0], v[1], v[2]) * c.base_weight
|
||||
}
|
||||
_ => common_base,
|
||||
};
|
||||
let (rough, spec_f0) = if s.shader == Shader::SpecularGlossiness {
|
||||
let gloss = match &maps.glossiness {
|
||||
Some(g) => g.sample_gray(uv.x, uv.y, true),
|
||||
None => 1.0 - c.specular_roughness,
|
||||
};
|
||||
let spec = match &maps.specular {
|
||||
Some(sp) if s.use_map.specular => {
|
||||
let v = sp.sample(uv.x, uv.y, true);
|
||||
Vec3::new(v[0], v[1], v[2])
|
||||
}
|
||||
_ => Vec3::from(c.specular_color) * 0.04,
|
||||
};
|
||||
((1.0 - gloss).clamp(0.02, 1.0), spec)
|
||||
} else {
|
||||
let rough = match &maps.roughness {
|
||||
Some(r) if s.use_map.roughness => r.sample_gray(uv.x, uv.y, true),
|
||||
_ => c.specular_roughness,
|
||||
};
|
||||
let f0 = ((c.ior - 1.0) / (c.ior + 1.0)).powi(2);
|
||||
let spec_w = match &maps.specular {
|
||||
Some(sp) if s.use_map.specular && s.shader == Shader::OpenPbr => sp.sample_gray(uv.x, uv.y, true),
|
||||
_ => 1.0,
|
||||
};
|
||||
(rough.clamp(0.02, 1.0), Vec3::from(c.specular_color) * (f0 * c.specular_weight * spec_w))
|
||||
};
|
||||
let metal = match &maps.metallic {
|
||||
Some(m) if s.use_map.metallic && s.shader != Shader::SpecularGlossiness => m.sample_gray(uv.x, uv.y, true),
|
||||
_ if s.shader == Shader::SpecularGlossiness => 0.0,
|
||||
_ => c.metalness,
|
||||
};
|
||||
let ao = match &maps.ao {
|
||||
Some(a) if s.use_map.ao => a.sample_gray(uv.x, uv.y, true),
|
||||
_ => c.ambient_occlusion,
|
||||
};
|
||||
Surface { base, rough, metal: metal.clamp(0.0, 1.0), ao: ao.clamp(0.0, 1.0), spec_f0 }
|
||||
}
|
||||
|
||||
/// Shade the first surface along one ray; `None` = missed the mesh.
|
||||
fn shade(scene: &Scene, maps: &Maps, light: &Lighting, s: &Settings, origin: Vec3, dir: Vec3, px: &Px) -> Option<Shaded> {
|
||||
let hit = scene.bvh.closest(origin, dir, f32::MAX)?;
|
||||
fn shade(scene: &Scene, maps: &Maps, light: &Lighting, s: &Settings, origin: Vec3, dir: Vec3, px: &Px, tmax: f32) -> Option<Shaded> {
|
||||
let hit = if s.backface_culling {
|
||||
let m = &scene.mesh;
|
||||
scene.bvh.closest_filtered(origin, dir, tmax, &|t| {
|
||||
let Some([i0, i1, i2]) = m.tri(t as usize) else { return true };
|
||||
match (m.positions.get(i0), m.positions.get(i1), m.positions.get(i2)) {
|
||||
(Some(a), Some(b), Some(c)) => (*b - *a).cross(*c - *a).dot(dir) < 0.0,
|
||||
_ => true,
|
||||
}
|
||||
})?
|
||||
} else {
|
||||
scene.bvh.closest(origin, dir, tmax)?
|
||||
};
|
||||
let m = &scene.mesh;
|
||||
let [i0, i1, i2] = m.tri(hit.tri as usize)?;
|
||||
let (w1, w2) = (hit.u, hit.v);
|
||||
@@ -410,16 +534,17 @@ fn shade(scene: &Scene, maps: &Maps, light: &Lighting, s: &Settings, origin: Vec
|
||||
let uv0 = *m.uvs.get(i0)? * w0 + *m.uvs.get(i1)? * w1 + *m.uvs.get(i2)? * w2;
|
||||
let uv = uv0 * s.tiling;
|
||||
let v = -dir;
|
||||
let a = alpha(maps, uv);
|
||||
let t_total = hit.t;
|
||||
let a = alpha(maps, s, uv);
|
||||
// Wireframe: the edges of the triangle hit, in the barycentric sense.
|
||||
let on_edge = s.wireframe && [w0, w1, w2].iter().any(|w| *w < 0.03);
|
||||
if s.alpha_view {
|
||||
return Some(Shaded { color: Vec3::splat(a), alpha: 1.0, t: hit.t });
|
||||
return Some(Shaded { color: if on_edge { Vec3::new(1.0, 0.5, 0.0) } else { Vec3::splat(a) }, alpha: 1.0, t: t_total });
|
||||
}
|
||||
let base = tex(&maps.base_color, uv).map_or(Vec3::splat(0.5), |c| Vec3::new(c[0], c[1], c[2]));
|
||||
let rough = tex_gray(&maps.roughness, uv, 0.5).clamp(0.02, 1.0);
|
||||
let metal = tex_gray(&maps.metallic, uv, 0.0).clamp(0.0, 1.0);
|
||||
let ao = tex_gray(&maps.ao, uv, 1.0).clamp(0.0, 1.0);
|
||||
let n = match tex(&maps.normal, uv) {
|
||||
Some(c) => {
|
||||
let sf = surface(maps, s, uv);
|
||||
let n = match &maps.normal {
|
||||
Some(nm) if s.use_map.normal => {
|
||||
let c = nm.sample(uv.x, uv.y, true);
|
||||
let mut t = Vec3::new(c[0] * 2.0 - 1.0, c[1] * 2.0 - 1.0, c[2] * 2.0 - 1.0);
|
||||
if s.normal_y_flip {
|
||||
t.y = -t.y;
|
||||
@@ -428,35 +553,119 @@ fn shade(scene: &Scene, maps: &Maps, light: &Lighting, s: &Settings, origin: Vec
|
||||
// with top-left UVs.
|
||||
(tan * t.x - bit * t.y + nrm * t.z.max(0.05)).normalize_or_zero()
|
||||
}
|
||||
None => nrm,
|
||||
_ => nrm,
|
||||
};
|
||||
let n = if n.dot(v) < 0.0 { nrm } else { n };
|
||||
let ndv = n.dot(v).clamp(1e-4, 1.0);
|
||||
let f0 = Vec3::splat(0.04).lerp(base, metal);
|
||||
let diffuse_col = base * (1.0 - metal);
|
||||
let c = &s.common;
|
||||
let wire = |mut color: Vec3| {
|
||||
if on_edge {
|
||||
color = Vec3::new(1.0, 0.5, 0.0);
|
||||
}
|
||||
color
|
||||
};
|
||||
match s.shader {
|
||||
Shader::Unlit => return Some(Shaded { color: wire(sf.base), alpha: if s.transparency { a } else { 1.0 }, t: t_total }),
|
||||
Shader::MeshInfo => return Some(Shaded { color: wire(n * 0.5 + Vec3::splat(0.5)), alpha: 1.0, t: t_total }),
|
||||
_ => {}
|
||||
}
|
||||
let (base, rough, metal, ao) = (sf.base, sf.rough, sf.metal, sf.ao);
|
||||
let f0 = sf.spec_f0.lerp(base, metal);
|
||||
// Diffuse roughness darkens the grazing diffuse a little (a cheap Oren-Nayar stand-in).
|
||||
let diffuse_col = base * (1.0 - metal) * (1.0 - 0.5 * c.diffuse_roughness * (1.0 - ndv));
|
||||
let rot = |d: Vec3| rotate_y(d, -s.env_rotation);
|
||||
let r = (n * (2.0 * n.dot(v)) - v).normalize_or_zero();
|
||||
let (sa, sb) = env_brdf(rough, ndv);
|
||||
let spec = light.specular(rot(r), rough) * (f0 * sa + Vec3::splat(sb));
|
||||
let diff = light.diffuse(rot(n)) * diffuse_col;
|
||||
let mut c = (diff + spec) * ao;
|
||||
if s.ao_rays > 0 || s.key_light > 0.0 {
|
||||
let env_diff = if s.env_light { light.diffuse(rot(n)) } else { Vec3::ZERO };
|
||||
let env_spec = if s.env_light { light.specular(rot(r), rough) } else { Vec3::ZERO };
|
||||
let ambient = Vec3::from(s.ambient);
|
||||
let subsurface = matches!(s.shader, Shader::OpenPbr | Shader::Subsurface) && c.subsurface_weight > 0.0;
|
||||
let mut diff = (env_diff + ambient) * diffuse_col;
|
||||
if subsurface {
|
||||
// Light that enters and leaves nearby: the surface glows with the subsurface color.
|
||||
let sss = (env_diff + ambient) * Vec3::from(c.subsurface_color) * (1.0 - metal);
|
||||
diff = diff.lerp(sss, c.subsurface_weight);
|
||||
}
|
||||
let mut color = match s.shader {
|
||||
Shader::Lambert => diff,
|
||||
Shader::Blinn => diff + ambient * f0,
|
||||
_ => {
|
||||
let mut spec_tint = f0 * sa + Vec3::splat(sb);
|
||||
if s.shader == Shader::OpenPbr && c.thin_film_weight > 0.0 {
|
||||
let film = thin_film(c.thin_film_thickness, c.thin_film_ior, ndv);
|
||||
spec_tint = spec_tint.lerp(spec_tint * film * 2.0, c.thin_film_weight);
|
||||
}
|
||||
diff + env_spec * spec_tint
|
||||
}
|
||||
};
|
||||
color *= ao;
|
||||
// Direct lights (the key light and the point lights cast shadows).
|
||||
let need_rays = s.ao_rays > 0 || s.key_light > 0.0 || s.lights.iter().any(|l| l.on);
|
||||
if need_rays {
|
||||
// The true surface (a displaced scene's facets), offset to avoid self-hits.
|
||||
let (p0, p1, p2) = (*m.positions.get(i0)?, *m.positions.get(i1)?, *m.positions.get(i2)?);
|
||||
let face = (p1 - p0).cross(p2 - p0).normalize_or_zero();
|
||||
let face = if face.dot(nrm) < 0.0 { -face } else { face };
|
||||
let p = origin + dir * hit.t + face * scene.radius * 2e-4;
|
||||
if s.ao_rays > 0 {
|
||||
c *= ambient_occlusion(scene, p, face, s.ao_rays, px.jitter);
|
||||
color *= ambient_occlusion(scene, p, face, s.ao_rays, px.jitter);
|
||||
}
|
||||
if s.key_light > 0.0 && face.dot(px.key) > 0.0 && !scene.bvh.occluded(p, px.key, f32::MAX) {
|
||||
c += direct(n, v, px.key, base, f0, metal, rough) * s.key_light * ao;
|
||||
let mut lit = |l: Vec3, radiance: Vec3, reach: f32| {
|
||||
if face.dot(l) > 0.0 && !scene.bvh.occluded(p, l, reach) {
|
||||
let term = match s.shader {
|
||||
Shader::Lambert => diffuse_col * n.dot(l).max(0.0) / std::f32::consts::PI,
|
||||
Shader::Blinn => {
|
||||
let h = (v + l).normalize_or_zero();
|
||||
let spec = n.dot(h).max(0.0).powf(blinn_exponent(rough)) * (blinn_exponent(rough) + 8.0) / (8.0 * std::f32::consts::PI);
|
||||
(diffuse_col / std::f32::consts::PI + f0 * spec) * n.dot(l).max(0.0)
|
||||
}
|
||||
_ => direct(n, v, l, base, f0, metal, rough),
|
||||
};
|
||||
color += term * radiance * ao;
|
||||
}
|
||||
};
|
||||
if s.key_light > 0.0 {
|
||||
lit(px.key, Vec3::splat(s.key_light), f32::MAX);
|
||||
}
|
||||
for pl in s.lights.iter().filter(|l| l.on) {
|
||||
let lp = scene.center + Vec3::from(pl.position) * scene.radius;
|
||||
let to = lp - p;
|
||||
let dist = to.length().max(1e-4);
|
||||
let l = to / dist;
|
||||
// Inverse square falloff, normalised so a light at one radius has unit power.
|
||||
let radiance = Vec3::from(pl.color) * pl.intensity * (scene.radius * scene.radius) / (dist * dist) * 4.0;
|
||||
lit(l, radiance, dist);
|
||||
}
|
||||
}
|
||||
if let Some(e) = tex(&maps.emissive, uv) {
|
||||
c += Vec3::new(e[0], e[1], e[2]);
|
||||
let coat = matches!(s.shader, Shader::OpenPbr | Shader::Coated) && c.coat_weight > 0.0;
|
||||
if coat {
|
||||
// A dielectric layer over everything: its reflection on top, the base dimmed and tinted below.
|
||||
let cf = fresnel(c.coat_ior, ndv) * c.coat_weight;
|
||||
let coat_rough = c.coat_roughness.clamp(0.02, 1.0);
|
||||
let coat_spec = if s.env_light { light.specular(rot(r), coat_rough) } else { Vec3::ZERO } + ambient * 0.04;
|
||||
let darkening = 1.0 - c.coat_darkening * c.coat_weight * 0.25;
|
||||
color = color * (1.0 - cf) * Vec3::from(c.coat_color).lerp(Vec3::ONE, 1.0 - c.coat_weight) * darkening + coat_spec * cf;
|
||||
}
|
||||
Some(Shaded { color: c, alpha: if s.transparency { a } else { 1.0 }, t: hit.t })
|
||||
if s.shader == Shader::OpenPbr && c.fuzz_weight > 0.0 {
|
||||
// Sheen: a soft rim of the fuzz color.
|
||||
let rim = (1.0 - ndv).powi(3);
|
||||
color += (env_diff + ambient) * Vec3::from(c.fuzz_color) * (c.fuzz_weight * (0.15 + 0.85 * rim));
|
||||
}
|
||||
let mut alpha_out = if s.transparency { a } else { 1.0 };
|
||||
if s.shader == Shader::OpenPbr && c.transmission_weight > 0.0 {
|
||||
// Transmission: what lies behind shows through, tinted.
|
||||
color = color.lerp(color * Vec3::from(c.transmission_color), c.transmission_weight);
|
||||
alpha_out *= 1.0 - c.transmission_weight * (1.0 - metal) * (1.0 - fresnel(c.ior, ndv));
|
||||
}
|
||||
if let Some(e) = &maps.emissive
|
||||
&& s.use_map.emissive
|
||||
{
|
||||
let e = e.sample(uv.x, uv.y, true);
|
||||
color += Vec3::new(e[0], e[1], e[2]) * c.emission_luminance.max(1.0);
|
||||
} else if c.emission_luminance > 0.0 {
|
||||
color += Vec3::from(c.emission_color) * c.emission_luminance;
|
||||
}
|
||||
Some(Shaded { color: wire(color), alpha: alpha_out, t: t_total })
|
||||
}
|
||||
|
||||
/// Follow one camera ray through up to [`MAX_LAYERS`] transparent surfaces, compositing front to
|
||||
@@ -465,10 +674,12 @@ fn shade(scene: &Scene, maps: &Maps, light: &Lighting, s: &Settings, origin: Vec
|
||||
fn trace(scene: &Scene, maps: &Maps, light: &Lighting, s: &Settings, origin: Vec3, dir: Vec3, px: &Px, k: f32, miss: Vec3) -> Vec3 {
|
||||
let mut acc = Vec3::ZERO;
|
||||
let mut through = 1.0;
|
||||
let mut o = origin;
|
||||
let (tmin, mut tmax) = clip_range(scene, s);
|
||||
let mut o = origin + dir * tmin;
|
||||
let step = scene.radius * 1e-4;
|
||||
for _ in 0..MAX_LAYERS {
|
||||
let Some(h) = shade(scene, maps, light, s, o, dir, px) else { return acc + miss * through };
|
||||
let Some(h) = shade(scene, maps, light, s, o, dir, px, tmax) else { return acc + miss * through };
|
||||
tmax = (tmax - h.t - step).max(0.0);
|
||||
acc += h.color * k * h.alpha * through;
|
||||
through *= 1.0 - h.alpha;
|
||||
if through < 1e-3 {
|
||||
@@ -479,6 +690,14 @@ fn trace(scene: &Scene, maps: &Maps, light: &Lighting, s: &Settings, origin: Vec
|
||||
acc + miss * through
|
||||
}
|
||||
|
||||
/// The near and far clip distances along a camera ray (scene radii → world units).
|
||||
fn clip_range(scene: &Scene, s: &Settings) -> (f32, f32) {
|
||||
match s.clip {
|
||||
Some([n, f]) if n.is_finite() && f.is_finite() && f > n => (n.max(0.0) * scene.radius, (f - n.max(0.0)) * scene.radius),
|
||||
_ => (0.0, f32::MAX),
|
||||
}
|
||||
}
|
||||
|
||||
/// The studio backdrop at screen position `p` (−1..1): a soft vignette (linear).
|
||||
fn backdrop(p: Vec2) -> Vec3 {
|
||||
let t = (p.length() * 0.75).clamp(0.0, 1.0);
|
||||
@@ -526,15 +745,16 @@ pub fn render_cancellable(scene: &Scene, maps: &Maps, light: &Lighting, s: &Sett
|
||||
let px = (x as f32 + (sx as f32 + 0.5) / ss as f32) / w as f32 * 2.0 - 1.0;
|
||||
let py = 1.0 - (y as f32 + (sy as f32 + 0.5) / ss as f32) / h as f32 * 2.0;
|
||||
let ray = cam.ray(Vec2::new(px, py), aspect);
|
||||
let bg = backdrop(Vec2::new(px, py));
|
||||
let p = Px { key, jitter: jitter(x as u32 * ss + sx, y as u32 * ss + sy) };
|
||||
let miss = match (s.show_env, bg_env) {
|
||||
(true, Some(e)) => e.sample(rotate_y(ray.dir, -s.env_rotation)) * k,
|
||||
_ => bg,
|
||||
let miss = match (s.show_env || s.background == Background::Environment, bg_env, s.background) {
|
||||
(true, Some(e), _) => e.sample(rotate_y(ray.dir, -s.env_rotation)) * k,
|
||||
(_, _, Background::Color(c)) => Vec3::from(c),
|
||||
_ => backdrop(Vec2::new(px, py)),
|
||||
};
|
||||
acc += if s.alpha_view {
|
||||
// Display values: the alpha as is, the background tone mapped.
|
||||
match shade(scene, maps, light, s, ray.origin, ray.dir, &p) {
|
||||
let (tmin, tmax) = clip_range(scene, s);
|
||||
match shade(scene, maps, light, s, ray.origin + ray.dir * tmin, ray.dir, &p, tmax) {
|
||||
Some(h) => h.color,
|
||||
None => miss.map(|v| linear_to_srgb(aces(v))),
|
||||
}
|
||||
@@ -607,6 +827,98 @@ mod tests {
|
||||
Image::filled(8, 8, Kind::Gray, [value; 4])
|
||||
}
|
||||
|
||||
/// Mean brightness of the center pixel's neighbourhood.
|
||||
fn center_lum(px: &[u8], w: usize, h: usize) -> f32 {
|
||||
let (cx, cy) = (w / 2, h / 2);
|
||||
let mut sum = 0.0;
|
||||
for y in cy - 2..cy + 2 {
|
||||
for x in cx - 2..cx + 2 {
|
||||
let i = (y * w + x) * 4;
|
||||
sum += (px[i] as f32 + px[i + 1] as f32 + px[i + 2] as f32) / 3.0;
|
||||
}
|
||||
}
|
||||
sum / 16.0
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn point_lights_ambient_and_the_environment_switch_change_the_brightness() {
|
||||
let (scene, light) = (Scene::builtin("sphere"), Lighting::new("studio"));
|
||||
let maps = Maps { base_color: Some(Image::filled(8, 8, Kind::Color, [0.5, 0.5, 0.5, 1.0])), ..Maps::default() };
|
||||
let base = Settings::default();
|
||||
let plain = center_lum(&render(&scene, &maps, &light, &base, 64, 48), 64, 48);
|
||||
let dark = Settings { env_light: false, ..base };
|
||||
let no_env = center_lum(&render(&scene, &maps, &light, &dark, 64, 48), 64, 48);
|
||||
assert!(no_env < plain - 20.0, "no environment light leaves the sphere dark: {no_env} vs {plain}");
|
||||
let mut lit = dark;
|
||||
lit.lights[0].on = true;
|
||||
lit.lights[0].intensity = 4.0;
|
||||
let with_light = center_lum(&render(&scene, &maps, &light, &lit, 64, 48), 64, 48);
|
||||
assert!(with_light > no_env + 20.0, "a point light brightens the dark sphere: {with_light} vs {no_env}");
|
||||
let ambient = Settings { env_light: false, ambient: [0.5; 3], ..base };
|
||||
let amb = center_lum(&render(&scene, &maps, &light, &ambient, 64, 48), 64, 48);
|
||||
assert!(amb > no_env + 20.0, "ambient light lifts it again: {amb} vs {no_env}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_shader_renders_and_the_common_values_drive_unmapped_channels() {
|
||||
let (scene, light) = (Scene::builtin("rounded_cube"), Lighting::new("studio"));
|
||||
let maps = Maps::default();
|
||||
for (shader, _) in Shader::ALL {
|
||||
let s = Settings { shader, ..Settings::default() };
|
||||
let px = render(&scene, &maps, &light, &s, 48, 32);
|
||||
assert_eq!(px.len(), 48 * 32 * 4, "{shader:?}");
|
||||
}
|
||||
let mut red = Settings::default();
|
||||
red.common.base_color = [0.8, 0.05, 0.05];
|
||||
let px = render(&scene, &maps, &light, &red, 64, 48);
|
||||
let c = ((24 * 64 + 32) * 4) as usize;
|
||||
assert!(px[c] > px[c + 1] + 30, "the common base color shows without a map: {:?}", &px[c..c + 3]);
|
||||
// A map wins over the common value, unless its use is switched off.
|
||||
let blue = Maps { base_color: Some(Image::filled(8, 8, Kind::Color, [0.05, 0.05, 0.8, 1.0])), ..Maps::default() };
|
||||
let px = render(&scene, &blue, &light, &red, 64, 48);
|
||||
assert!(px[c + 2] > px[c] + 30, "the map wins: {:?}", &px[c..c + 3]);
|
||||
let mut off = red;
|
||||
off.use_map.base_color = false;
|
||||
let px = render(&scene, &blue, &light, &off, 64, 48);
|
||||
assert!(px[c] > px[c + 2] + 30, "use_map off falls back to the common color: {:?}", &px[c..c + 3]);
|
||||
// Emission from the common values lights the surface by itself.
|
||||
let mut glow = Settings { env_light: false, ..Settings::default() };
|
||||
glow.common.emission_luminance = 2.0;
|
||||
glow.common.emission_color = [0.0, 1.0, 0.0];
|
||||
let px = render(&scene, &maps, &light, &glow, 64, 48);
|
||||
assert!(px[c + 1] > 150 && px[c] < 60, "emission glows green: {:?}", &px[c..c + 3]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn background_clip_planes_wireframe_and_culling_show_in_the_frame() {
|
||||
let (scene, light) = (Scene::builtin("sphere"), Lighting::new("studio"));
|
||||
let maps = Maps::default();
|
||||
let corner = 0usize;
|
||||
let s = Settings { background: Background::Color([0.0, 1.0, 0.0]), ..Settings::default() };
|
||||
let px = render(&scene, &maps, &light, &s, 64, 48);
|
||||
assert!(px[corner + 1] > 200 && px[corner] < 40, "a flat green background: {:?}", &px[corner..corner + 3]);
|
||||
// Clip planes past the sphere: only the background is left.
|
||||
let s = Settings { background: Background::Color([0.0, 1.0, 0.0]), clip: Some([10.0, 12.0]), ..Settings::default() };
|
||||
let px = render(&scene, &maps, &light, &s, 64, 48);
|
||||
let c = ((24 * 64 + 32) * 4) as usize;
|
||||
assert!(px[c + 1] > 200 && px[c] < 40, "clipped away: {:?}", &px[c..c + 3]);
|
||||
// Wireframe paints orange along the edges of a cube's twelve triangles, not everywhere.
|
||||
let cube = Scene::builtin("cube");
|
||||
let s = Settings { wireframe: true, ..Settings::default() };
|
||||
let px = render(&cube, &maps, &light, &s, 96, 72);
|
||||
let orange = px.chunks_exact(4).filter(|p| p[0] > 200 && p[1] > 120 && p[1] < 235 && p[2] < 60).count();
|
||||
assert!(orange > 20 && orange < 96 * 72 / 2, "wire edges drawn: {orange}");
|
||||
// Backface culling on a plane seen from below leaves the background.
|
||||
let plane = Scene::builtin("plane");
|
||||
let below =
|
||||
Settings { pitch: -60.0, background: Background::Color([0.0, 1.0, 0.0]), backface_culling: true, transparency: false, ..Settings::default() };
|
||||
let px = render(&plane, &maps, &light, &below, 64, 48);
|
||||
assert!(px[c + 1] > 200 && px[c] < 40, "the plane's back face is culled: {:?}", &px[c..c + 3]);
|
||||
let shown = Settings { backface_culling: false, ..below };
|
||||
let px = render(&plane, &maps, &light, &shown, 64, 48);
|
||||
assert!(!(px[c + 1] > 200 && px[c] < 40), "without culling the back face shows: {:?}", &px[c..c + 3]);
|
||||
}
|
||||
|
||||
fn displacement(depth: f32, level: f32) -> Displacement {
|
||||
Displacement { depth, level, tiling: 1.0, max_triangles: 2048, shade_relief: false }
|
||||
}
|
||||
|
||||
@@ -25,6 +25,7 @@ zip = { workspace = true }
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
sys-locale = "0.3"
|
||||
rfd = { workspace = true }
|
||||
rayon = { workspace = true }
|
||||
# Floating panels open as OS windows.
|
||||
craft-ui = { workspace = true, features = ["native-windows"] }
|
||||
|
||||
|
||||
@@ -43,12 +43,58 @@ pub struct Cooker {
|
||||
pub started: Option<f64>,
|
||||
/// `Session::cook_epoch` when the running cook started.
|
||||
epoch: u64,
|
||||
/// Tools ▸ Suspend engine: no cook starts until resumed.
|
||||
pub suspended: bool,
|
||||
/// Tools ▸ Cancel rendering: the running cook stops and nothing restarts until the next edit.
|
||||
pub hold: bool,
|
||||
/// Tools ▸ Switch engine: worker threads for the cook (0 = all the cores).
|
||||
pub threads: usize,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pool: Option<(usize, std::sync::Arc<rayon::ThreadPool>)>,
|
||||
}
|
||||
|
||||
/// Stop the running cook (Tools ▸ Cancel rendering, Escape). The graph stays as it was until the
|
||||
/// next edit computes it again.
|
||||
pub fn cancel(app: &mut MaterialCraftApp) {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(flag) = &app.cooker.cancel {
|
||||
flag.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
app.cooker.hold = true;
|
||||
app.session.dirty = false;
|
||||
}
|
||||
|
||||
impl Cooker {
|
||||
pub fn busy(&self) -> bool {
|
||||
self.rx.is_some()
|
||||
}
|
||||
|
||||
/// The cook's thread pool for the chosen thread count (built once per count); `None` runs
|
||||
/// on the global pool (all the cores).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn pool(&mut self) -> Option<std::sync::Arc<rayon::ThreadPool>> {
|
||||
let n = self.threads;
|
||||
if n == 0 {
|
||||
self.pool = None;
|
||||
return None;
|
||||
}
|
||||
if let Some((have, p)) = &self.pool
|
||||
&& *have == n
|
||||
{
|
||||
return Some(p.clone());
|
||||
}
|
||||
match rayon::ThreadPoolBuilder::new().num_threads(n).thread_name(|i| format!("materialcraft-cook-{i}")).build() {
|
||||
Ok(p) => {
|
||||
let p = std::sync::Arc::new(p);
|
||||
self.pool = Some((n, p.clone()));
|
||||
Some(p)
|
||||
}
|
||||
Err(e) => {
|
||||
log::warn!("could not build a {n}-thread pool ({e}); using every core");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Collect a finished cook and start the next one if the graph changed.
|
||||
@@ -63,8 +109,9 @@ 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.
|
||||
Ok(c) if c.cancelled => app.session.dirty = true,
|
||||
// A stopped cook is partial: keep the previous results and cook again
|
||||
// (unless the user cancelled it: then wait for the next edit).
|
||||
Ok(c) if c.cancelled => app.session.dirty = !app.cooker.hold,
|
||||
Ok(c) => {
|
||||
if !app.session.dirty && app.cooker.epoch == app.session.cook_epoch {
|
||||
app.session.cooked = c;
|
||||
@@ -102,7 +149,8 @@ pub fn drive(app: &mut MaterialCraftApp, ctx: &egui::Context) {
|
||||
}
|
||||
}
|
||||
}
|
||||
if app.session.dirty {
|
||||
if app.session.dirty && !app.cooker.suspended {
|
||||
app.cooker.hold = false;
|
||||
start(app, ctx.input(|i| i.time));
|
||||
ctx.request_repaint();
|
||||
}
|
||||
@@ -120,12 +168,20 @@ fn start(app: &mut MaterialCraftApp, now: f64) {
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let flag = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let thread_flag = flag.clone();
|
||||
let pool = app.cooker.pool();
|
||||
use materialcraft_engine::eval::Options;
|
||||
let spawned = std::thread::Builder::new().name("materialcraft-cook".into()).spawn(move || {
|
||||
let mut opts = Options::new(&dec);
|
||||
opts.max_size = max;
|
||||
opts.cancel = Some(&thread_flag);
|
||||
let cooked = guard("cook", || Ok(materialcraft_engine::eval::cook(&pkg, gi, &opts, &cache)));
|
||||
let run = || {
|
||||
let mut opts = Options::new(&dec);
|
||||
opts.max_size = max;
|
||||
opts.cancel = Some(&thread_flag);
|
||||
guard("cook", || Ok(materialcraft_engine::eval::cook(&pkg, gi, &opts, &cache)))
|
||||
};
|
||||
// A pool of the chosen size keeps the cook's parallel work to that many threads.
|
||||
let cooked = match pool {
|
||||
Some(p) => p.install(run),
|
||||
None => run(),
|
||||
};
|
||||
let _ = tx.send(cooked);
|
||||
});
|
||||
match spawned {
|
||||
|
||||
@@ -162,11 +162,16 @@ pub struct Dock {
|
||||
workspace: Workspace,
|
||||
/// A panel to bring in front of the other floating windows on the next frame.
|
||||
raise: Option<Panel>,
|
||||
/// A panel shown alone over the whole dock (Shift+Space on a panel; Windows ▸ Unmaximize
|
||||
/// window). Not saved with the layout.
|
||||
pub maximized: Option<Panel>,
|
||||
/// The panel under the pointer on the last frame (the one Shift+Space maximizes).
|
||||
pub hovered: Option<Panel>,
|
||||
}
|
||||
|
||||
impl Default for Dock {
|
||||
fn default() -> Self {
|
||||
Dock { workspace: default_workspace(), raise: None }
|
||||
Dock { workspace: default_workspace(), raise: None, maximized: None, hovered: None }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -199,7 +204,7 @@ impl Dock {
|
||||
if validate(&workspace).is_err() {
|
||||
return Dock::default();
|
||||
}
|
||||
Dock { workspace, raise: None }
|
||||
Dock { workspace, raise: None, maximized: None, hovered: None }
|
||||
}
|
||||
|
||||
pub fn workspace(&self) -> &Workspace {
|
||||
@@ -288,6 +293,30 @@ fn style(ui: &Ui, t: &Tokens) -> DockStyle {
|
||||
pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
let ctx = ui.ctx().clone();
|
||||
let tk = Tokens::get(&ctx);
|
||||
// Shift+Space maximizes the panel under the pointer, or brings the layout back.
|
||||
if !ctx.egui_wants_keyboard_input() && ctx.input_mut(|i| i.consume_key(egui::Modifiers::SHIFT, egui::Key::Space)) {
|
||||
app.ui.dock.maximized = match app.ui.dock.maximized {
|
||||
Some(_) => None,
|
||||
None => app.ui.dock.hovered,
|
||||
};
|
||||
}
|
||||
if let Some(panel) = app.ui.dock.maximized {
|
||||
let title = Panels { app: &mut *app }.logical_label(&panel);
|
||||
egui::Frame::NONE.fill(tk.panel).show(ui, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(RichText::new(title).strong());
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if ui.small_button(tr("Unmaximize (Shift+Space)")).clicked() {
|
||||
app.ui.dock.maximized = None;
|
||||
}
|
||||
});
|
||||
});
|
||||
let rect = ui.available_rect_before_wrap();
|
||||
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(rect));
|
||||
Panels { app }.body(&mut child, &panel);
|
||||
});
|
||||
return;
|
||||
}
|
||||
let style = style(ui, &tk);
|
||||
let layout = app.ui.dock.workspace.layout.clone();
|
||||
let mut area = DockArea::new(area_id()).input_blocked(ctx.memory(|m| m.top_modal_layer()).is_some());
|
||||
@@ -317,6 +346,9 @@ struct Panels<'a> {
|
||||
impl DockContent<Panel> for Panels<'_> {
|
||||
fn body(&mut self, ui: &mut Ui, panel: &Panel) {
|
||||
let app = &mut *self.app;
|
||||
if ui.rect_contains_pointer(ui.max_rect()) {
|
||||
app.ui.dock.hovered = Some(*panel);
|
||||
}
|
||||
match panel {
|
||||
Panel::Graph => crate::graph_view::show(app, ui),
|
||||
Panel::View3d => crate::view3d::show(app, ui),
|
||||
|
||||
+290
-53
@@ -1,4 +1,4 @@
|
||||
//! The explorer: the open package, its graphs and its bitmap resources.
|
||||
//! The explorer: the open package, its graphs and its bitmap resources, each with a context menu.
|
||||
|
||||
use egui::{RichText, Sense, Ui, vec2};
|
||||
use egui_phosphor::regular as icon;
|
||||
@@ -8,6 +8,22 @@ use crate::MaterialCraftApp;
|
||||
use crate::i18n::tr;
|
||||
use crate::theme::Tokens;
|
||||
|
||||
/// What a context menu asked for; carried out after the tree is drawn.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
enum Action {
|
||||
Menu(&'static str),
|
||||
Graph(&'static str, usize),
|
||||
Resource(&'static str, usize),
|
||||
}
|
||||
|
||||
/// A graph on the explorer's clipboard (Copy / Paste a graph).
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct GraphClipboard(pub Option<serde_json::Value>);
|
||||
|
||||
/// Rename-in-place state: the graph index and the text being edited.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Rename(pub Option<(usize, String)>);
|
||||
|
||||
pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
ui.horizontal(|ui| {
|
||||
@@ -29,67 +45,288 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
}
|
||||
});
|
||||
ui.add_space(2.0);
|
||||
let mut action: Option<Action> = None;
|
||||
egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {
|
||||
let name = format!("{}{}", app.session.pkg.name, if app.session.modified { "*" } else { "" });
|
||||
ui.label(RichText::new(format!("{} {name}", icon::PACKAGE)).strong().color(tk.text_strong));
|
||||
let mut open: Option<usize> = None;
|
||||
let mut action: Option<(&str, usize)> = None;
|
||||
for (i, g) in app.session.pkg.graphs.iter().enumerate() {
|
||||
let on = i == app.session.graph;
|
||||
let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click());
|
||||
crate::widgets::name(&resp, egui::Role::TreeItem, &g.name);
|
||||
if on {
|
||||
ui.painter().rect_filled(r, 4.0, tk.row_selected);
|
||||
ui.painter().rect_stroke(r, 4.0, egui::Stroke::new(1.0, tk.accent), egui::StrokeKind::Inside);
|
||||
} else if resp.hovered() {
|
||||
ui.painter().rect_filled(r, 4.0, tk.row_hover);
|
||||
}
|
||||
ui.painter().text(
|
||||
r.left_center() + vec2(18.0, 0.0),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
format!("{} {}", icon::TREE_STRUCTURE, g.name),
|
||||
egui::FontId::proportional(12.0),
|
||||
if on { tk.text_strong } else { tk.text },
|
||||
);
|
||||
if resp.clicked() {
|
||||
open = Some(i);
|
||||
}
|
||||
resp.context_menu(|ui| {
|
||||
for (label, a) in [("Open", "open"), ("Export outputs...", "export"), ("Duplicate", "duplicate"), ("Delete", "delete")] {
|
||||
if ui.button(tr(label)).clicked() {
|
||||
action = Some((a, i));
|
||||
ui.close();
|
||||
}
|
||||
let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click());
|
||||
crate::widgets::name(&resp, egui::Role::TreeItem, &app.session.pkg.name);
|
||||
if resp.hovered() {
|
||||
ui.painter().rect_filled(r, 4.0, tk.row_hover);
|
||||
}
|
||||
ui.painter().text(
|
||||
r.left_center() + vec2(4.0, 0.0),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
format!("{} {name}", icon::PACKAGE),
|
||||
egui::FontId::proportional(12.5),
|
||||
tk.text_strong,
|
||||
);
|
||||
if let Some(path) = &app.session.path {
|
||||
resp.clone().on_hover_text(path);
|
||||
}
|
||||
resp.context_menu(|ui| package_menu(app, ui, &mut action));
|
||||
|
||||
let focused_tree = ui.ui_contains_pointer();
|
||||
for i in 0..app.session.pkg.graphs.len() {
|
||||
graph_row(app, ui, i, &mut action);
|
||||
}
|
||||
// Keyboard: Return opens, Del removes, F2 renames the open graph while the pointer is here.
|
||||
if focused_tree && app.explorer_rename.0.is_none() && !ui.ctx().egui_wants_keyboard_input() {
|
||||
let gi = app.session.graph;
|
||||
ui.input(|i| {
|
||||
if i.key_pressed(egui::Key::F2) {
|
||||
action = Some(Action::Graph("rename", gi));
|
||||
} else if i.key_pressed(egui::Key::Delete) {
|
||||
action = Some(Action::Graph("delete", gi));
|
||||
}
|
||||
});
|
||||
}
|
||||
if let Some(i) = open {
|
||||
app.run("graph.open", json!({"graph": i}));
|
||||
}
|
||||
match action {
|
||||
Some(("open", i)) => {
|
||||
app.run("graph.open", json!({"graph": i}));
|
||||
}
|
||||
Some(("export", i)) => {
|
||||
// The export window works on the open graph.
|
||||
if app.run("graph.open", json!({"graph": i})).is_some() {
|
||||
app.ui.windows.export = true;
|
||||
}
|
||||
}
|
||||
Some(("duplicate", i)) => {
|
||||
app.run("graph.duplicate", json!({"graph": i}));
|
||||
}
|
||||
Some(("delete", i)) => {
|
||||
app.run("graph.delete", json!({"graph": i}));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if !app.session.pkg.resources.is_empty() {
|
||||
ui.add_space(6.0);
|
||||
ui.label(RichText::new(tr("Resources")).color(tk.text_dim).size(11.0));
|
||||
for r in &app.session.pkg.resources {
|
||||
ui.label(format!("{} {} ({} KB)", icon::IMAGE, r.name, r.bytes.len() / 1024));
|
||||
for i in 0..app.session.pkg.resources.len() {
|
||||
let Some(r) = app.session.pkg.resources.get(i) else { continue };
|
||||
let linked = r.link.is_some();
|
||||
let text = format!("{} {} ({} KB)", if linked { icon::LINK } else { icon::IMAGE }, r.name, r.bytes.len() / 1024);
|
||||
let hover = match &r.link {
|
||||
Some(l) => format!("{} {l}", tr("Linked:")),
|
||||
None => tr("Embedded in the package").to_string(),
|
||||
};
|
||||
let resp = ui.add(egui::Label::new(text).sense(Sense::click())).on_hover_text(hover);
|
||||
resp.context_menu(|ui| {
|
||||
if linked && ui.button(tr("Relink...")).clicked() {
|
||||
action = Some(Action::Resource("relink", i));
|
||||
ui.close();
|
||||
}
|
||||
if ui.button(tr("Add a Bitmap node")).clicked() {
|
||||
action = Some(Action::Resource("node", i));
|
||||
ui.close();
|
||||
}
|
||||
if ui.button(tr("Remove")).clicked() {
|
||||
action = Some(Action::Resource("delete", i));
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
if let Some(a) = action {
|
||||
perform(app, ui.ctx(), a);
|
||||
}
|
||||
}
|
||||
|
||||
fn graph_row(app: &mut MaterialCraftApp, ui: &mut Ui, i: usize, action: &mut Option<Action>) {
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
let Some(g) = app.session.pkg.graphs.get(i) else { return };
|
||||
let gname = g.name.clone();
|
||||
let on = i == app.session.graph;
|
||||
// Rename in place.
|
||||
if let Some((ri, text)) = &mut app.explorer_rename.0
|
||||
&& *ri == i
|
||||
{
|
||||
let resp = ui.add(egui::TextEdit::singleline(text).desired_width(ui.available_width() - 24.0));
|
||||
if !resp.has_focus() && !resp.lost_focus() {
|
||||
resp.request_focus();
|
||||
}
|
||||
let enter = ui.input(|inp| inp.key_pressed(egui::Key::Enter));
|
||||
let escape = ui.input(|inp| inp.key_pressed(egui::Key::Escape));
|
||||
if resp.lost_focus() || enter {
|
||||
let new = text.trim().to_string();
|
||||
app.explorer_rename.0 = None;
|
||||
if !new.is_empty() && new != gname && !escape {
|
||||
app.run("graph.rename", json!({"graph": i, "name": new}));
|
||||
}
|
||||
} else if escape {
|
||||
app.explorer_rename.0 = None;
|
||||
}
|
||||
return;
|
||||
}
|
||||
let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click());
|
||||
crate::widgets::name(&resp, egui::Role::TreeItem, &gname);
|
||||
if on {
|
||||
ui.painter().rect_filled(r, 4.0, tk.row_selected);
|
||||
ui.painter().rect_stroke(r, 4.0, egui::Stroke::new(1.0, tk.accent), egui::StrokeKind::Inside);
|
||||
} else if resp.hovered() {
|
||||
ui.painter().rect_filled(r, 4.0, tk.row_hover);
|
||||
}
|
||||
ui.painter().text(
|
||||
r.left_center() + vec2(18.0, 0.0),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
format!("{} {}", icon::TREE_STRUCTURE, gname),
|
||||
egui::FontId::proportional(12.0),
|
||||
if on { tk.text_strong } else { tk.text },
|
||||
);
|
||||
if resp.clicked() {
|
||||
*action = Some(Action::Graph("open", i));
|
||||
}
|
||||
resp.context_menu(|ui| {
|
||||
let can_paste = app.explorer_clipboard.0.is_some();
|
||||
for (label, a, key, enabled) in [
|
||||
("Open", "open", "Return", true),
|
||||
("Copy", "copy", "", true),
|
||||
("Paste", "paste", "", can_paste),
|
||||
("Remove", "delete", "Del", true),
|
||||
("Rename", "rename", "F2", true),
|
||||
("View Outputs In 3D View", "view3d", "", true),
|
||||
("Compute Outputs", "compute", "", true),
|
||||
("Export outputs...", "export", "", true),
|
||||
] {
|
||||
if crate::menus::menu_row(ui, tr(label), key, enabled).clicked() {
|
||||
*action = Some(Action::Graph(a, i));
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn package_menu(app: &mut MaterialCraftApp, ui: &mut Ui, action: &mut Option<Action>) {
|
||||
let mut pick = |ui: &mut Ui, label: &str, id: &'static str, key: &str, enabled: bool| {
|
||||
if crate::menus::menu_row(ui, tr(label), key, enabled).clicked() {
|
||||
*action = Some(Action::Menu(id));
|
||||
ui.close();
|
||||
}
|
||||
};
|
||||
ui.menu_button(tr("New"), |ui| {
|
||||
pick(ui, "Graph...", "ui.newGraph", "Ctrl+N", true);
|
||||
pick(ui, "Function graph...", "ui.newFunctionGraph", "", false);
|
||||
});
|
||||
ui.menu_button(tr("Import"), |ui| {
|
||||
pick(ui, "Bitmap...", "file.importBitmap", "", true);
|
||||
pick(ui, "Graph from a package...", "file.importGraph", "", true);
|
||||
});
|
||||
ui.menu_button(tr("Link"), |ui| {
|
||||
pick(ui, "Bitmap...", "file.linkBitmap", "", true);
|
||||
});
|
||||
pick(ui, "Reload", "ui.reloadResources", "", true);
|
||||
ui.separator();
|
||||
pick(ui, "Save", "file.save", "Ctrl+S", true);
|
||||
pick(ui, "Save as...", "file.saveAs", "Ctrl+Shift+S", true);
|
||||
pick(ui, "Save a copy as...", "file.saveCopy", "", true);
|
||||
pick(ui, "Export with dependencies...", "file.exportWithDependencies", "", true);
|
||||
ui.menu_button(tr("Send to"), |ui| {
|
||||
pick(ui, "TextureCraft", "file.sendToTextureCraft", "", true);
|
||||
});
|
||||
ui.separator();
|
||||
pick(ui, "Copy", "explorer.copy", "", true);
|
||||
pick(ui, "Paste", "explorer.paste", "", app.explorer_clipboard.0.is_some());
|
||||
ui.separator();
|
||||
pick(ui, "Close package", "ui.closeAll", "", true);
|
||||
pick(ui, "Compute Outputs", "explorer.compute", "", true);
|
||||
pick(ui, "Show in Explorer...", "explorer.reveal", "", app.session.path.is_some());
|
||||
ui.separator();
|
||||
pick(ui, "Dependency Manager", "ui.view.dependencies", "", true);
|
||||
}
|
||||
|
||||
fn perform(app: &mut MaterialCraftApp, ctx: &egui::Context, action: Action) {
|
||||
match action {
|
||||
Action::Menu("explorer.copy") => copy_graph(app, ctx, app.session.graph),
|
||||
Action::Menu("explorer.paste") => paste_graph(app),
|
||||
Action::Menu("explorer.compute") => compute(app),
|
||||
Action::Menu("explorer.reveal") => reveal(app),
|
||||
Action::Menu(id) => crate::menus::invoke(app, ctx, id),
|
||||
Action::Graph("open", i) => {
|
||||
app.run("graph.open", json!({"graph": i}));
|
||||
}
|
||||
Action::Graph("copy", i) => copy_graph(app, ctx, i),
|
||||
Action::Graph("paste", _) => paste_graph(app),
|
||||
Action::Graph("delete", i) => {
|
||||
app.run("graph.delete", json!({"graph": i}));
|
||||
}
|
||||
Action::Graph("rename", i) => {
|
||||
if let Some(g) = app.session.pkg.graphs.get(i) {
|
||||
app.explorer_rename.0 = Some((i, g.name.clone()));
|
||||
}
|
||||
}
|
||||
Action::Graph("view3d", i) => {
|
||||
if app.run("graph.open", json!({"graph": i})).is_some() {
|
||||
app.ui.dock.focus(crate::docking::Panel::View3d);
|
||||
compute(app);
|
||||
}
|
||||
}
|
||||
Action::Graph("compute", i) => {
|
||||
if app.run("graph.open", json!({"graph": i})).is_some() {
|
||||
compute(app);
|
||||
}
|
||||
}
|
||||
Action::Graph("export", i) => {
|
||||
// The export window works on the open graph.
|
||||
if app.run("graph.open", json!({"graph": i})).is_some() {
|
||||
app.ui.windows.export = true;
|
||||
}
|
||||
}
|
||||
Action::Resource("delete", i) => {
|
||||
if let Some(name) = app.session.pkg.resources.get(i).map(|r| r.name.clone()) {
|
||||
app.run("file.deleteResource", json!({"name": name}));
|
||||
}
|
||||
}
|
||||
Action::Resource("node", i) => {
|
||||
if let Some(name) = app.session.pkg.resources.get(i).map(|r| r.name.clone()) {
|
||||
app.run("graph.node.add", json!({"def": "bitmap", "params": {"resource": name}}));
|
||||
}
|
||||
}
|
||||
Action::Resource("relink", i) => relink(app, i),
|
||||
Action::Graph(..) | Action::Resource(..) => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Copy a graph as JSON: to the explorer clipboard, and as text to the system clipboard.
|
||||
fn copy_graph(app: &mut MaterialCraftApp, ctx: &egui::Context, i: usize) {
|
||||
let Some(g) = app.session.pkg.graphs.get(i) else { return };
|
||||
match serde_json::to_value(g) {
|
||||
Ok(v) => {
|
||||
if let Ok(text) = serde_json::to_string(&v) {
|
||||
ctx.copy_text(text);
|
||||
}
|
||||
app.explorer_clipboard.0 = Some(v);
|
||||
app.toast(format!("{} {}", tr("Copied graph"), g.name), false);
|
||||
}
|
||||
Err(e) => app.toast(format!("{}: {e}", tr("Could not copy the graph")), true),
|
||||
}
|
||||
}
|
||||
|
||||
fn paste_graph(app: &mut MaterialCraftApp) {
|
||||
let Some(v) = app.explorer_clipboard.0.clone() else { return };
|
||||
if let Some(r) = app.run("graph.add", json!({"graph": v})) {
|
||||
app.toast(format!("{} {}", tr("Pasted graph"), r["name"].as_str().unwrap_or_default()), false);
|
||||
}
|
||||
}
|
||||
|
||||
/// Compute the open graph's outputs now: the cache is kept, the cook restarts (also lifts a Cancel).
|
||||
fn compute(app: &mut MaterialCraftApp) {
|
||||
app.cooker.hold = false;
|
||||
app.session.dirty = true;
|
||||
}
|
||||
|
||||
/// Show the package file in the system's file browser.
|
||||
fn reveal(app: &mut MaterialCraftApp) {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let Some(path) = app.session.path.clone() else { return };
|
||||
let folder = std::path::Path::new(&path).parent().map(|p| p.to_path_buf()).unwrap_or_default();
|
||||
let result = if cfg!(target_os = "windows") {
|
||||
std::process::Command::new("explorer").arg(format!("/select,{path}")).spawn()
|
||||
} else if cfg!(target_os = "macos") {
|
||||
std::process::Command::new("open").arg("-R").arg(&path).spawn()
|
||||
} else {
|
||||
std::process::Command::new("xdg-open").arg(&folder).spawn()
|
||||
};
|
||||
if let Err(e) = result {
|
||||
app.toast(format!("{} {} ({e})", tr("Package folder:"), folder.display()), true);
|
||||
}
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
app.toast(tr("The browser keeps no package folder"), true);
|
||||
}
|
||||
|
||||
fn relink(app: &mut MaterialCraftApp, i: usize) {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(name) = app.session.pkg.resources.get(i).map(|r| r.name.clone())
|
||||
&& let Some(p) = rfd::FileDialog::new().add_filter("Images", materialcraft_engine::formats::IMAGE_EXTENSIONS).pick_file()
|
||||
{
|
||||
app.run("file.linkBitmap", json!({"path": p.display().to_string(), "name": name}));
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
let _ = i;
|
||||
app.toast(tr("The browser has no files to link to"), true);
|
||||
}
|
||||
}
|
||||
@@ -117,6 +117,27 @@ fn commit(app: &mut MaterialCraftApp, node: NodeId, param: &str, g: &FnGraph) {
|
||||
app.run("graph.node.param", json!({"id": node.0, "param": param, "value": v}));
|
||||
}
|
||||
|
||||
/// Add a function node of `op` to the open function editor (the library's Function nodes).
|
||||
/// Returns false when no function graph is open.
|
||||
pub fn add_op(app: &mut MaterialCraftApp, op: &str) -> bool {
|
||||
let Some(e) = app.fn_editor.as_ref() else { return false };
|
||||
let (node, param) = (e.node, e.param.clone());
|
||||
let Some(mut g) = current(app, e) else { return false };
|
||||
if !FN_OPS.iter().any(|o| o.0 == op) || g.nodes.len() >= 10_000 {
|
||||
return false;
|
||||
}
|
||||
let id = g.nodes.iter().map(|n| n.id + 1).max().unwrap_or(1);
|
||||
// Below the lowest node, so new nodes never stack on one another.
|
||||
let bottom = g.nodes.iter().map(|n| n.pos[1]).fold(-ROW * 4.0, f32::max) + ROW * 4.0;
|
||||
let left = g.nodes.iter().map(|n| n.pos[0]).fold(0.0, f32::min);
|
||||
g.nodes.push(FnNode { id, op: op.into(), inputs: vec![None; arity(op)], value: default_value(op), pos: [left, bottom] });
|
||||
if g.output.is_none() {
|
||||
g.output = Some(id);
|
||||
}
|
||||
commit(app, node, ¶m, &g);
|
||||
true
|
||||
}
|
||||
|
||||
/// Draw the editor window when one is open.
|
||||
pub fn show(app: &mut MaterialCraftApp, ctx: &egui::Context) {
|
||||
let Some(mut e) = app.fn_editor.take() else { return };
|
||||
|
||||
@@ -214,6 +214,10 @@ fn port_pos(r: Rect, i: usize, n: usize, output: bool, dot: bool) -> Pos2 {
|
||||
|
||||
/// Control points of the wire from output `a` to input `b` (screen space).
|
||||
fn bezier_points(a: Pos2, b: Pos2) -> [Pos2; 4] {
|
||||
if STRAIGHT_WIRES.load(std::sync::atomic::Ordering::Relaxed) {
|
||||
let d = (b - a) / 3.0;
|
||||
return [a, a + d, a + d * 2.0, b];
|
||||
}
|
||||
let dx = ((b.x - a.x).abs() * 0.5).max(30.0);
|
||||
[a, a + vec2(dx, 0.0), b - vec2(dx, 0.0), b]
|
||||
}
|
||||
@@ -261,40 +265,78 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
canvas(app, ui);
|
||||
}
|
||||
|
||||
/// Wires are drawn straight this frame (set from the preference before the canvas draws).
|
||||
static STRAIGHT_WIRES: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
|
||||
|
||||
/// The grid step nodes snap to.
|
||||
const SNAP: f32 = 16.0;
|
||||
|
||||
fn toolbar(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
egui::Frame::NONE.fill(tk.panel).inner_margin(egui::Margin::symmetric(6, 3)).show(ui, |ui| {
|
||||
egui::Frame::NONE.fill(tk.panel).inner_margin(egui::Margin::symmetric(6, 2)).show(ui, |ui| {
|
||||
// Row 1: view and display tools.
|
||||
ui.horizontal(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = 2.0;
|
||||
let b = |ui: &mut Ui, ic: &str, tip: &str, on: bool| crate::widgets::icon_button(ui, ic, tip, on, 22.0).clicked();
|
||||
if b(ui, icon::CORNERS_OUT, tr("Frame all (F)"), false) {
|
||||
app.ui.frame_all = true;
|
||||
}
|
||||
if b(ui, icon::FRAME_CORNERS, tr("Actual size (1:1)"), (app.ui.graph_camera.zoom - 1.0).abs() < 1e-3) {
|
||||
zoom_to(app, 1.0);
|
||||
}
|
||||
if b(ui, icon::CAMERA, tr("Save a screenshot of the graph..."), false) {
|
||||
screenshot(app, ui.ctx());
|
||||
}
|
||||
let info = crate::widgets::icon_button(ui, icon::INFO, tr("Graph information"), false, 22.0);
|
||||
egui::Popup::menu(&info).show(|ui| graph_info(app, ui));
|
||||
if b(ui, icon::MAGNIFYING_GLASS, tr("Find a node (Tab)"), app.graph.search.is_some()) {
|
||||
let c = view_center(app);
|
||||
open_search(app, c, None);
|
||||
}
|
||||
ui.separator();
|
||||
let thumbs = app.ui.prefs.thumbnails;
|
||||
if b(ui, icon::IMAGE, tr("Show node thumbnails"), thumbs) {
|
||||
app.ui.prefs.thumbnails = !thumbs;
|
||||
}
|
||||
let timings = app.ui.prefs.node_timings;
|
||||
if b(ui, icon::TIMER, tr("Show cook times on nodes"), timings) {
|
||||
app.ui.prefs.node_timings = !timings;
|
||||
}
|
||||
let straight = app.ui.prefs.straight_wires;
|
||||
if b(
|
||||
ui,
|
||||
if straight { icon::LINE_SEGMENT } else { icon::WAVE_SINE },
|
||||
if straight { tr("Wires: straight (click for curved)") } else { tr("Wires: curved (click for straight)") },
|
||||
straight,
|
||||
) {
|
||||
app.ui.prefs.straight_wires = !straight;
|
||||
}
|
||||
let grid_on = app.ui.prefs.show_grid;
|
||||
if b(ui, icon::GRID_FOUR, tr("Show the grid"), grid_on) {
|
||||
app.ui.prefs.show_grid = !grid_on;
|
||||
}
|
||||
let snap = app.ui.prefs.snap_grid;
|
||||
if b(ui, icon::MAGNET, tr("Snap nodes to the grid"), snap) {
|
||||
app.ui.prefs.snap_grid = !snap;
|
||||
}
|
||||
ui.separator();
|
||||
if b(ui, icon::ARROWS_CLOCKWISE, tr("Compute outputs"), false) {
|
||||
app.cooker.hold = false;
|
||||
app.session.dirty = true;
|
||||
}
|
||||
if b(ui, icon::BROOM, tr("Clean up: remove unconnected dots and disabled nodes with nothing attached"), false) {
|
||||
clean_up(app);
|
||||
}
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
align_tools(app, ui);
|
||||
ui.separator();
|
||||
parent_size(app, ui);
|
||||
});
|
||||
});
|
||||
// Row 2: quick insert.
|
||||
ui.horizontal(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = 2.0;
|
||||
let b = |ui: &mut Ui, ic: &str, tip: &str| crate::widgets::icon_button(ui, ic, tip, false, 22.0).clicked();
|
||||
if b(ui, icon::CORNERS_OUT, tr("Frame all (F)")) {
|
||||
app.ui.frame_all = true;
|
||||
}
|
||||
for (ic, mode, tip) in [
|
||||
(icon::ALIGN_LEFT, "left", "Align left"),
|
||||
(icon::ALIGN_TOP, "top", "Align top"),
|
||||
(icon::ALIGN_CENTER_HORIZONTAL, "hcenter", "Align centers horizontally"),
|
||||
(icon::ALIGN_CENTER_VERTICAL, "vcenter", "Align centers vertically"),
|
||||
(icon::COLUMNS, "hdistribute", "Distribute horizontally"),
|
||||
(icon::ROWS, "vdistribute", "Distribute vertically"),
|
||||
] {
|
||||
if b(ui, ic, tr(tip)) {
|
||||
app.run("graph.align", json!({"mode": mode}));
|
||||
}
|
||||
}
|
||||
ui.separator();
|
||||
if b(ui, icon::SELECTION, tr("Add frame around the selection")) {
|
||||
app.run("graph.frame.add", json!({}));
|
||||
}
|
||||
if b(ui, icon::NOTE, tr("Add comment")) {
|
||||
app.run("graph.comment.add", json!({}));
|
||||
}
|
||||
if b(ui, icon::MAP_PIN, tr("Add navigation pin")) {
|
||||
let c = view_center(app);
|
||||
app.run("graph.pin.add", json!({"at": [c.x, c.y]}));
|
||||
}
|
||||
ui.separator();
|
||||
// Quick insert of the atomic nodes.
|
||||
for (ic, def) in [
|
||||
(icon::IMAGE, "bitmap"),
|
||||
(icon::PALETTE, "uniform"),
|
||||
@@ -315,6 +357,7 @@ fn toolbar(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
(icon::DIAMOND, "sharpen"),
|
||||
(icon::ARROWS_CLOCKWISE, "transformation"),
|
||||
(icon::WAVES, "warp"),
|
||||
(icon::DICE_FIVE, "fx_map"),
|
||||
(icon::SIGN_IN, "input_grayscale"),
|
||||
(icon::SIGN_OUT, "output"),
|
||||
] {
|
||||
@@ -323,18 +366,162 @@ fn toolbar(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
add_node_near_selection(app, def);
|
||||
}
|
||||
}
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
let thumbs = app.ui.prefs.thumbnails;
|
||||
if crate::widgets::icon_button(ui, icon::IMAGE, tr("Show node thumbnails"), thumbs, 22.0).clicked() {
|
||||
app.ui.prefs.thumbnails = !thumbs;
|
||||
}
|
||||
parent_size(app, ui);
|
||||
});
|
||||
ui.separator();
|
||||
if b(ui, icon::NOTE, tr("Add comment")) {
|
||||
let c = view_center(app);
|
||||
app.run("graph.comment.add", json!({"at": [c.x - 60.0, c.y - 20.0]}));
|
||||
}
|
||||
if b(ui, icon::DOT_OUTLINE, tr("Add dot (reroute)")) {
|
||||
add_node_near_selection(app, "dot");
|
||||
}
|
||||
if b(ui, icon::SELECTION, tr("Add frame around the selection")) {
|
||||
let c = view_center(app);
|
||||
let p = if app.session.selection.is_empty() { json!({"rect": [c.x - 160.0, c.y - 100.0, 320.0, 200.0]}) } else { json!({}) };
|
||||
app.run("graph.frame.add", p);
|
||||
}
|
||||
if b(ui, icon::MAP_PIN, tr("Add navigation pin")) {
|
||||
let c = view_center(app);
|
||||
app.run("graph.pin.add", json!({"at": [c.x, c.y]}));
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// "Parent size: [1024 ▾] × [1024 ▾]".
|
||||
/// Zoom the graph camera to `zoom` around the view's center.
|
||||
fn zoom_to(app: &mut MaterialCraftApp, zoom: f32) {
|
||||
let c = view_center(app);
|
||||
let v = app.graph.view;
|
||||
let cam = &mut app.ui.graph_camera;
|
||||
cam.zoom = zoom;
|
||||
cam.pan = [c.x - v.width() * 0.5 / zoom, c.y - v.height() * 0.5 / zoom];
|
||||
*cam = cam.sanitized();
|
||||
}
|
||||
|
||||
/// Save the graph panel as a PNG: a screenshot of the window, cropped to the canvas.
|
||||
fn screenshot(app: &mut MaterialCraftApp, ctx: &egui::Context) {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let name = format!("{}_graph.png", materialcraft_engine::formats::safe_file_name(&app.session.graph().map(|g| g.name.clone()).unwrap_or_default()));
|
||||
let Some(path) = rfd::FileDialog::new().set_file_name(name).add_filter("PNG", &["png"]).save_file() else { return };
|
||||
let view = app.graph.view;
|
||||
let ppp = ctx.pixels_per_point();
|
||||
let repaint = ctx.clone();
|
||||
let callback = egui::ScreenshotCallback::new(move |img| {
|
||||
let x0 = ((view.left() * ppp).max(0.0) as usize).min(img.size[0]);
|
||||
let y0 = ((view.top() * ppp).max(0.0) as usize).min(img.size[1]);
|
||||
let x1 = ((view.right() * ppp).max(0.0) as usize).clamp(x0, img.size[0]);
|
||||
let y1 = ((view.bottom() * ppp).max(0.0) as usize).clamp(y0, img.size[1]);
|
||||
let (w, h) = (x1 - x0, y1 - y0);
|
||||
if w == 0 || h == 0 {
|
||||
return;
|
||||
}
|
||||
let mut rgba = Vec::with_capacity(w * h * 4);
|
||||
for y in y0..y1 {
|
||||
for x in x0..x1 {
|
||||
rgba.extend_from_slice(&img.pixels[y * img.size[0] + x].to_array());
|
||||
}
|
||||
}
|
||||
if let Some((_, _, png)) = crate::control::encode_png(w as u32, h as u32, rgba)
|
||||
&& let Err(e) = std::fs::write(&path, png)
|
||||
{
|
||||
log::warn!("could not save the graph screenshot {}: {e}", path.display());
|
||||
}
|
||||
repaint.request_repaint();
|
||||
});
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Screenshot(callback));
|
||||
app.toast(tr("Saving a screenshot of the graph"), false);
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
let _ = ctx;
|
||||
app.toast(tr("Screenshots are saved from the desktop app"), true);
|
||||
}
|
||||
}
|
||||
|
||||
/// The ⓘ popup: what the graph is, how big and how long it takes.
|
||||
fn graph_info(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
let Ok(g) = app.session.graph() else { return };
|
||||
let [w, h] = g.size_px();
|
||||
let outputs = g.nodes.iter().filter(|n| n.def == "output").count();
|
||||
let errors = app.session.cooked.nodes.values().filter(|r| r.error.is_some()).count();
|
||||
let ms: f32 = app.session.cooked.nodes.values().map(|r| r.ms).sum();
|
||||
ui.set_min_width(220.0);
|
||||
ui.label(egui::RichText::new(&g.name).strong());
|
||||
ui.label(
|
||||
egui::RichText::new(format!("{} ({})", app.session.pkg.name, app.session.path.as_deref().unwrap_or(tr("not saved yet")))).small().color(tk.text_dim),
|
||||
);
|
||||
ui.separator();
|
||||
egui::Grid::new("graph-info").num_columns(2).spacing([12.0, 2.0]).show(ui, |ui| {
|
||||
ui.label(tr("Size"));
|
||||
ui.label(format!("{w} x {h}"));
|
||||
ui.end_row();
|
||||
ui.label(tr("Format"));
|
||||
ui.label(format!("{} bits", g.format.bits()));
|
||||
ui.end_row();
|
||||
ui.label(tr("Nodes"));
|
||||
ui.label(format!("{} ({} {})", g.nodes.len(), outputs, tr("outputs")));
|
||||
ui.end_row();
|
||||
ui.label(tr("Wires"));
|
||||
ui.label(g.connections.len().to_string());
|
||||
ui.end_row();
|
||||
ui.label(tr("Last cook"));
|
||||
ui.label(if errors > 0 { format!("{ms:.0} ms, {errors} {}", tr("error(s)")) } else { format!("{ms:.0} ms") });
|
||||
ui.end_row();
|
||||
ui.label(tr("Exposed"));
|
||||
ui.label(g.exposed.len().to_string());
|
||||
ui.end_row();
|
||||
});
|
||||
ui.separator();
|
||||
if ui.button(tr("Graph attributes...")).clicked() {
|
||||
app.run("edit.selectNone", json!({}));
|
||||
app.ui.dock.focus(crate::docking::Panel::Properties);
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove reroute dots nothing uses and disabled nodes with no wires.
|
||||
fn clean_up(app: &mut MaterialCraftApp) {
|
||||
let Ok(g) = app.session.graph() else { return };
|
||||
let wired = |id: NodeId| g.connections.iter().any(|c| c.from == id || c.to == id);
|
||||
let ids: Vec<u64> =
|
||||
g.nodes.iter().filter(|n| (n.def == "dot" && !g.connections.iter().any(|c| c.from == n.id)) || (n.disabled && !wired(n.id))).map(|n| n.id.0).collect();
|
||||
if ids.is_empty() {
|
||||
app.toast(tr("Nothing to clean up"), false);
|
||||
return;
|
||||
}
|
||||
let n = ids.len();
|
||||
if app.run("graph.select", json!({"ids": ids})).is_some() && app.run("edit.delete", json!({})).is_some() {
|
||||
app.toast(format!("{} {n}", tr("Removed nodes:")), false);
|
||||
}
|
||||
}
|
||||
|
||||
/// Stack checkbox and the align buttons (right-to-left layout: declared in reverse).
|
||||
fn align_tools(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
let stack = app.ui.stack_align;
|
||||
let two = app.session.selection.len() >= 2;
|
||||
let run = |app: &mut MaterialCraftApp, modes: &[&str]| {
|
||||
for m in modes {
|
||||
app.run("graph.align", json!({"mode": m}));
|
||||
}
|
||||
};
|
||||
if crate::widgets::icon_button(ui, icon::ROWS, tr("Align vertically (stack under one another)"), false, 22.0).clicked() && two {
|
||||
run(app, if stack { &["hcenter", "vdistribute"] } else { &["hcenter"] });
|
||||
}
|
||||
if crate::widgets::icon_button(ui, icon::COLUMNS, tr("Align horizontally (stack side by side)"), false, 22.0).clicked() && two {
|
||||
run(app, if stack { &["vcenter", "hdistribute"] } else { &["vcenter"] });
|
||||
}
|
||||
for (ic, mode, tip) in [(icon::ALIGN_TOP, "top", "Align top edges"), (icon::ALIGN_LEFT, "left", "Align left edges")] {
|
||||
if crate::widgets::icon_button(ui, ic, tr(tip), false, 22.0).clicked() && two {
|
||||
run(app, &[mode]);
|
||||
}
|
||||
}
|
||||
let r = ui.checkbox(&mut app.ui.stack_align, tr("Stack"));
|
||||
crate::widgets::name(&r, egui::Role::CheckBox, "Stack");
|
||||
r.on_hover_text(tr("Aligning also closes the gaps between the nodes"));
|
||||
}
|
||||
|
||||
/// "Parent size: [1024 ▾] 🔗 [1024 ▾] ⟲" (right-to-left layout: declared in reverse).
|
||||
fn parent_size(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
let Ok(g) = app.session.graph() else { return };
|
||||
let [w, h] = g.size;
|
||||
@@ -348,16 +535,30 @@ fn parent_size(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
});
|
||||
crate::widgets::name(&r.response, egui::Role::ComboBox, if id == "parent-w" { "Parent width" } else { "Parent height" });
|
||||
};
|
||||
if crate::widgets::icon_button(ui, icon::ARROW_COUNTER_CLOCKWISE, tr("Reset the parent size to 1024 x 1024"), false, 20.0).clicked() {
|
||||
nw = 10;
|
||||
nh = 10;
|
||||
}
|
||||
combo(ui, "parent-h", &mut nh);
|
||||
ui.label("x");
|
||||
let link = app.ui.parent_link;
|
||||
if crate::widgets::icon_button(ui, if link { icon::LINK } else { icon::LINK_BREAK }, tr("Link width and height"), link, 20.0).clicked() {
|
||||
app.ui.parent_link = !link;
|
||||
}
|
||||
combo(ui, "parent-w", &mut nw);
|
||||
ui.label(egui::RichText::new(tr("Parent size:")).color(Tokens::get(ui.ctx()).text_dim));
|
||||
if app.ui.parent_link {
|
||||
if nw != w {
|
||||
nh = nw;
|
||||
} else if nh != h {
|
||||
nw = nh;
|
||||
}
|
||||
}
|
||||
if (nw, nh) != (w, h) {
|
||||
app.run("graph.size", json!({"log2": [nw, nh]}));
|
||||
}
|
||||
}
|
||||
|
||||
fn view_center(app: &MaterialCraftApp) -> Pos2 {
|
||||
pub fn view_center(app: &MaterialCraftApp) -> Pos2 {
|
||||
let c = &app.ui.graph_camera.sanitized();
|
||||
let v = app.graph.view;
|
||||
pos2(c.pan[0] + v.width() * 0.5 / c.zoom, c.pan[1] + v.height() * 0.5 / c.zoom)
|
||||
@@ -397,8 +598,17 @@ pub fn import_bitmap_file(app: &mut MaterialCraftApp, path: &str) {
|
||||
|
||||
fn run_gesture(app: &mut MaterialCraftApp, label: &str, commands: &[(&str, serde_json::Value)]) {
|
||||
let result = app.session.group(label, |session| {
|
||||
// `"from": "last"` names the node the previous command added.
|
||||
let mut last: Option<u64> = None;
|
||||
for (id, params) in commands {
|
||||
crate::cook::execute_guarded(session, id, params).map_err(materialcraft_engine::EngineError::Other)?;
|
||||
let mut params = params.clone();
|
||||
if params.get("from").and_then(serde_json::Value::as_str) == Some("last") {
|
||||
params["from"] = json!(last.ok_or_else(|| materialcraft_engine::EngineError::Other("no node was added before".into()))?);
|
||||
}
|
||||
let r = crate::cook::execute_guarded(session, id, ¶ms).map_err(materialcraft_engine::EngineError::Other)?;
|
||||
if let Some(n) = r.get("id").and_then(serde_json::Value::as_u64) {
|
||||
last = Some(n);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
@@ -416,10 +626,48 @@ fn rewire(app: &mut MaterialCraftApp, from: &(NodeId, String), detached: Option<
|
||||
{
|
||||
commands.push(("graph.disconnect", json!({"to": n.0, "toPort": p})));
|
||||
}
|
||||
if let Some(converter) = conversion_node(app, from, to, to_port) {
|
||||
// Preferences ▸ Graph: a conversion node between a color output and a grayscale input (or the reverse).
|
||||
let (x, y) = midpoint(app, from.0, to);
|
||||
commands.push(("graph.node.add", json!({"def": converter, "at": [x, y], "connectFrom": {"node": from.0.0, "port": from.1}})));
|
||||
commands.push(("graph.connect", json!({"from": "last", "to": to.0, "toPort": to_port})));
|
||||
run_gesture(app, "Connect", &commands);
|
||||
return;
|
||||
}
|
||||
commands.push(("graph.connect", json!({"from": from.0.0, "fromPort": from.1, "to": to.0, "toPort": to_port})));
|
||||
run_gesture(app, "Connect", &commands);
|
||||
}
|
||||
|
||||
/// Connect `from` to `to`'s input, inserting a conversion node when the preference asks for one.
|
||||
pub fn connect(app: &mut MaterialCraftApp, from: &(NodeId, String), to: NodeId, to_port: &str) {
|
||||
rewire(app, from, None, to, to_port);
|
||||
}
|
||||
|
||||
/// The node that converts the kinds between an output and an input (`None` = the kinds agree
|
||||
/// or the preference is off): Grayscale Conversion for color → gray, Gradient Map for gray → color.
|
||||
fn conversion_node(app: &MaterialCraftApp, from: &(NodeId, String), to: NodeId, to_port: &str) -> Option<&'static str> {
|
||||
use materialcraft_engine::nodes::PortKind;
|
||||
if !app.ui.prefs.auto_convert {
|
||||
return None;
|
||||
}
|
||||
let g = app.session.graph().ok()?;
|
||||
let out_kind = materialcraft_engine::eval::ports(&app.session.pkg, g.node(from.0).ok()?).1.into_iter().find(|p| p.id == from.1)?.kind;
|
||||
let in_kind = materialcraft_engine::eval::ports(&app.session.pkg, g.node(to).ok()?).0.into_iter().find(|p| p.id == to_port)?.kind;
|
||||
match (out_kind, in_kind) {
|
||||
(PortKind::Color, PortKind::Gray) => Some("grayscale_conversion"),
|
||||
(PortKind::Gray, PortKind::Color) => Some("gradient_map"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Halfway between two nodes (graph space), for a node inserted between them.
|
||||
fn midpoint(app: &MaterialCraftApp, a: NodeId, b: NodeId) -> (f32, f32) {
|
||||
let g = app.session.graph().ok();
|
||||
let pos = |id: NodeId| g.and_then(|g| g.node(id).ok()).map_or([0.0, 0.0], |n| n.pos);
|
||||
let (pa, pb) = (pos(a), pos(b));
|
||||
((pa[0] + pb[0]) * 0.5, (pa[1] + pb[1]) * 0.5)
|
||||
}
|
||||
|
||||
/// Finish dragging a frame: set its rectangle and move the nodes it carries, as one undo entry.
|
||||
fn move_frame(app: &mut MaterialCraftApp, id: u64, rect: [f32; 4], nodes: &[NodeId], delta: Vec2) {
|
||||
let mut commands = vec![("graph.frame.edit", json!({"id": id, "rect": rect}))];
|
||||
@@ -473,14 +721,20 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
painter.rect_filled(rect, 0.0, Color32::from_rgb(0x2b, 0x2d, 0x31));
|
||||
app.ui.graph_camera = app.ui.graph_camera.sanitized();
|
||||
let cam = Cam { origin: rect.min, pan: Vec2::from(app.ui.graph_camera.pan), zoom: app.ui.graph_camera.zoom };
|
||||
grid(&painter, &cam, rect);
|
||||
STRAIGHT_WIRES.store(app.ui.prefs.straight_wires, std::sync::atomic::Ordering::Relaxed);
|
||||
if app.ui.prefs.show_grid {
|
||||
grid(&painter, &cam, rect);
|
||||
}
|
||||
|
||||
let pointer = ctx.input(|i| i.pointer.hover_pos());
|
||||
let hovered_canvas = pointer.is_some_and(|p| rect.contains(p)) && resp.hovered();
|
||||
|
||||
// Zoom around the pointer.
|
||||
if hovered_canvas || ui.rect_contains_pointer(rect) {
|
||||
let scroll = ctx.input(|i| i.smooth_scroll_delta.y + i.zoom_delta().ln() * 200.0);
|
||||
let mut scroll = ctx.input(|i| i.smooth_scroll_delta.y + i.zoom_delta().ln() * 200.0);
|
||||
if app.ui.prefs.invert_zoom {
|
||||
scroll = -scroll;
|
||||
}
|
||||
if scroll.abs() > 0.0
|
||||
&& let Some(p) = pointer
|
||||
&& rect.contains(p)
|
||||
@@ -698,6 +952,12 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
if n.def == "output" {
|
||||
painter.text(header.right_center() - vec2(4.0, 0.0), Align2::RIGHT_CENTER, icon::SIGN_OUT, small.clone(), Color32::WHITE);
|
||||
}
|
||||
if app.ui.prefs.node_timings
|
||||
&& let Some(r0) = result
|
||||
{
|
||||
let txt = if r0.cached { format!("{:.1} ms ({})", r0.ms, tr("cached")) } else { format!("{:.1} ms", r0.ms) };
|
||||
painter.text(header.right_top() + vec2(-2.0, HEADER_H * cam.zoom + 2.0), Align2::RIGHT_TOP, txt, small.clone(), tk.warning);
|
||||
}
|
||||
let outline = if error.is_some() {
|
||||
Stroke::new(2.0, Color32::from_rgb(0xff, 0x30, 0xd0))
|
||||
} else if selected {
|
||||
@@ -971,6 +1231,15 @@ fn handle_input(
|
||||
}
|
||||
}
|
||||
Drag::Nodes { delta } => {
|
||||
let mut delta = delta;
|
||||
// Snap: the last selected node lands on the grid, the others keep their offsets.
|
||||
if app.ui.prefs.snap_grid
|
||||
&& let Some(id) = app.session.selection.last()
|
||||
&& let Some(n) = app.session.graph().ok().and_then(|g| g.node(*id).ok())
|
||||
{
|
||||
let target = pos2(((n.pos[0] + delta.x) / SNAP).round() * SNAP, ((n.pos[1] + delta.y) / SNAP).round() * SNAP);
|
||||
delta = target - pos2(n.pos[0], n.pos[1]);
|
||||
}
|
||||
if delta.length() > 0.5 {
|
||||
app.run("graph.node.move", json!({"by": [delta.x, delta.y]}));
|
||||
}
|
||||
@@ -1003,6 +1272,7 @@ fn handle_input(
|
||||
app.run("graph.disconnect", json!({"to": n.0, "toPort": p}));
|
||||
} else if let Some(p) = pointer
|
||||
&& rect.contains(p)
|
||||
&& app.ui.prefs.drag_create
|
||||
{
|
||||
open_search(app, cam.to_graph(p), Some(from));
|
||||
}
|
||||
@@ -1012,7 +1282,7 @@ fn handle_input(
|
||||
Drag::WireFromInput { to } => {
|
||||
let source = pointer.and_then(|p| nearest_port(&app.graph.ports, p, 12.0)).filter(|h| h.output).cloned();
|
||||
if let Some(s) = source {
|
||||
app.run("graph.connect", json!({"from": s.node.0, "fromPort": s.port, "to": to.0.0, "toPort": to.1}));
|
||||
connect(app, &(s.node, s.port.clone()), to.0, &to.1);
|
||||
}
|
||||
}
|
||||
Drag::Frame { id, delta, resize, nodes } => {
|
||||
@@ -1113,17 +1383,14 @@ fn handle_input(
|
||||
{
|
||||
let gp = cam.to_graph(p);
|
||||
let at = [gp.x - NODE_W * 0.5, gp.y - 20.0];
|
||||
match payload.0.strip_prefix('@') {
|
||||
Some(graph) => app.run("graph.node.add", json!({"def": "graph_instance", "at": at, "params": {"graph": graph}})),
|
||||
None => app.run("graph.node.add", json!({"def": payload.0, "at": at})),
|
||||
};
|
||||
crate::library::add_key(app, &payload.0, at);
|
||||
}
|
||||
|
||||
// Keys over the canvas.
|
||||
let hovered = pointer.is_some_and(|p| rect.contains(p));
|
||||
if hovered && app.graph.search.is_none() {
|
||||
let space = !ctx.egui_wants_keyboard_input() && ctx.input(|i| i.key_pressed(egui::Key::Space));
|
||||
let tab = !app.graph.keyboard_was_focused && !ctx.text_edit_focused() && ctx.input(|i| i.key_pressed(egui::Key::Tab));
|
||||
let tab = app.ui.prefs.tab_key_menu && !app.graph.keyboard_was_focused && !ctx.text_edit_focused() && ctx.input(|i| i.key_pressed(egui::Key::Tab));
|
||||
if (space || tab)
|
||||
&& let Some(p) = pointer
|
||||
{
|
||||
|
||||
@@ -21,14 +21,18 @@ pub mod levels_editor;
|
||||
mod lib_test;
|
||||
pub mod library;
|
||||
pub mod menus;
|
||||
pub mod plugins;
|
||||
pub mod preferences;
|
||||
pub mod properties;
|
||||
pub mod state;
|
||||
pub mod theme;
|
||||
pub mod thumbs;
|
||||
pub mod tool_windows;
|
||||
pub mod toolbar;
|
||||
pub mod unsaved;
|
||||
pub mod view2d;
|
||||
pub mod view3d;
|
||||
pub mod view3d_props;
|
||||
pub mod web_files;
|
||||
pub mod widgets;
|
||||
pub mod windows;
|
||||
@@ -60,6 +64,21 @@ pub struct MaterialCraftApp {
|
||||
pub graph: graph_view::GraphView,
|
||||
pub view3d: view3d::View3dState,
|
||||
pub view2d: view2d::View2dState,
|
||||
/// The plugins folder's packages (Tools ▸ Plugin Manager).
|
||||
pub plugins: plugins::Plugins,
|
||||
/// A graph copied in the explorer.
|
||||
pub explorer_clipboard: explorer::GraphClipboard,
|
||||
/// The explorer's rename-in-place field.
|
||||
pub explorer_rename: explorer::Rename,
|
||||
/// Import graph: the package file picked and its graphs, waiting for a choice.
|
||||
pub import_pick: Option<(String, Vec<String>)>,
|
||||
/// The 3D view property page shown in the Properties panel, and the selection when it opened
|
||||
/// (selecting a node closes it).
|
||||
pub props3d: Option<(view3d::Page3d, Vec<materialcraft_engine::core::NodeId>)>,
|
||||
/// The cache size last pushed into the session (MB; preferences).
|
||||
applied_cache_mb: u32,
|
||||
/// The Preferences window's working copy.
|
||||
pub prefs_editor: preferences::PrefsEditor,
|
||||
/// The function graph editor window, when open.
|
||||
pub fn_editor: Option<function_editor::FnEditor>,
|
||||
/// Synthetic input from the control channel, fed to egui on the next frames.
|
||||
@@ -93,6 +112,17 @@ impl MaterialCraftApp {
|
||||
i18n::set_language(&app.ui.prefs.language);
|
||||
app.fonts_ready = true;
|
||||
app.ui.windows.home = app.ui.prefs.show_home;
|
||||
// The 3D view's saved default state, else the default lighting preference.
|
||||
match app.ui.view3d_default.clone() {
|
||||
Some(state) => {
|
||||
app.run("view.3d.loadState", serde_json::json!({"state": state}));
|
||||
}
|
||||
None => {
|
||||
let [ambient, p1, p2] = app.ui.prefs.default_lights;
|
||||
app.run("view.3d", serde_json::json!({"lights": {"ambientOn": ambient, "point": [{"on": p1}, {"on": p2}]}}));
|
||||
}
|
||||
}
|
||||
app.view3d.show_env = !app.ui.prefs.env_hidden;
|
||||
app
|
||||
}
|
||||
|
||||
@@ -112,6 +142,13 @@ impl MaterialCraftApp {
|
||||
graph: graph_view::GraphView::default(),
|
||||
view3d: view3d::View3dState::default(),
|
||||
view2d: view2d::View2dState::default(),
|
||||
plugins: plugins::Plugins::default(),
|
||||
explorer_clipboard: explorer::GraphClipboard::default(),
|
||||
explorer_rename: explorer::Rename::default(),
|
||||
import_pick: None,
|
||||
props3d: None,
|
||||
applied_cache_mb: u32::MAX,
|
||||
prefs_editor: preferences::PrefsEditor::default(),
|
||||
fn_editor: None,
|
||||
input_queue: VecDeque::new(),
|
||||
pending_screenshots: Vec::new(),
|
||||
@@ -133,6 +170,14 @@ impl MaterialCraftApp {
|
||||
|
||||
/// Push the preferences that live in the session (preview size, 3D camera).
|
||||
pub fn apply_prefs(&mut self) {
|
||||
self.cooker.threads = self.ui.prefs.cook_threads;
|
||||
let p = &self.ui.prefs;
|
||||
let settings = serde_json::json!({"historySize": p.history_size.clamp(1, 10_000), "cacheMb": if p.cache_mb == 0 { 1024 } else { p.cache_mb }, "cookLimit": p.cook_limit});
|
||||
if self.session.max_undo != p.history_size as usize || self.session.cook_limit.unwrap_or(0) != p.cook_limit || p.cache_mb != self.applied_cache_mb {
|
||||
self.applied_cache_mb = p.cache_mb;
|
||||
self.run("session.settings", settings);
|
||||
}
|
||||
self.ui.recent.truncate(self.ui.prefs.recent_count.clamp(1, 50) as usize);
|
||||
if self.session.camera != self.ui.prefs.camera.sanitized() {
|
||||
self.session.set_camera_prefs(self.ui.prefs.camera);
|
||||
}
|
||||
@@ -142,13 +187,39 @@ impl MaterialCraftApp {
|
||||
}
|
||||
}
|
||||
|
||||
/// Preferences ▸ Graph: what happens when a graph opens (3D view, 2D view, frame all).
|
||||
fn graph_opened(&mut self) {
|
||||
self.ui.frame_all = true;
|
||||
if self.ui.prefs.view_3d_on_open && !self.ui.dock.is_open(docking::Panel::View3d) {
|
||||
self.ui.dock.toggle(docking::Panel::View3d);
|
||||
}
|
||||
let output = self.session.graph().ok().and_then(|g| g.nodes.iter().find(|n| n.def == "output").map(|n| n.id.0));
|
||||
if self.ui.prefs.view_2d_on_open
|
||||
&& let Some(out) = output
|
||||
{
|
||||
let _ = cook::execute_guarded(&mut self.session, "view.2d", &serde_json::json!({"node": out, "port": 0}));
|
||||
}
|
||||
}
|
||||
|
||||
/// Run an engine command, reporting errors as toasts. Returns the result on success.
|
||||
pub fn run(&mut self, id: &str, params: Value) -> Option<Value> {
|
||||
let graph_before = (self.session.graph, self.session.pkg.graphs.len());
|
||||
match cook::execute_guarded(&mut self.session, id, ¶ms) {
|
||||
Ok(v) => {
|
||||
if id == "view.previewSize" {
|
||||
self.ui.prefs.preview_size = self.session.preview_size.unwrap_or(0);
|
||||
}
|
||||
if id == "graph.node.add" && self.ui.prefs.auto_display_new_node {
|
||||
// Preferences ▸ Graph: a new node shows in the 2D view.
|
||||
if let Some(n) = v.get("id").and_then(Value::as_u64) {
|
||||
let _ = cook::execute_guarded(&mut self.session, "view.2d", &serde_json::json!({"node": n, "port": 0}));
|
||||
}
|
||||
}
|
||||
if (self.session.graph, self.session.pkg.graphs.len()) != graph_before
|
||||
&& matches!(id, "graph.open" | "file.new" | "file.open" | "file.newPackage" | "file.importGraph" | "graph.add" | "graph.duplicate")
|
||||
{
|
||||
self.graph_opened();
|
||||
}
|
||||
Some(v)
|
||||
}
|
||||
Err(e) => {
|
||||
@@ -177,10 +248,20 @@ impl MaterialCraftApp {
|
||||
return;
|
||||
}
|
||||
self.next_autosave = now + period;
|
||||
let dir = user_dir("autosave");
|
||||
let path = dir.join(format!("{}.sbs", materialcraft_engine::formats::safe_file_name(&self.session.pkg.name)));
|
||||
let dir = if self.ui.prefs.temp_dir.trim().is_empty() { user_dir("autosave") } else { std::path::PathBuf::from(self.ui.prefs.temp_dir.trim()) };
|
||||
let stem = materialcraft_engine::formats::safe_file_name(&self.session.pkg.name);
|
||||
let path = dir.join(format!("{stem}.sbs"));
|
||||
let versions = self.ui.prefs.backup_versions.clamp(1, 50) as usize;
|
||||
let pkg = self.session.pkg.clone();
|
||||
let spawned = std::thread::Builder::new().name("materialcraft-autosave".into()).spawn(move || {
|
||||
// Older backups shift down one slot: name.sbs, name.1.sbs, name.2.sbs, …
|
||||
let slot = |i: usize| if i == 0 { dir.join(format!("{stem}.sbs")) } else { dir.join(format!("{stem}.{i}.sbs")) };
|
||||
for i in (1..versions).rev() {
|
||||
if slot(i - 1).exists() {
|
||||
let _ = std::fs::rename(slot(i - 1), slot(i));
|
||||
}
|
||||
}
|
||||
let _ = std::fs::remove_file(slot(versions));
|
||||
let result = std::fs::create_dir_all(&dir)
|
||||
.map_err(|e| e.to_string())
|
||||
.and_then(|_| materialcraft_engine::formats::sbs::write_sbs(&pkg).map_err(|e| e.to_string()))
|
||||
@@ -272,7 +353,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_main_toolbar {
|
||||
toolbar::main_toolbar(self, ui);
|
||||
}
|
||||
toolbar::status_bar(self, ui);
|
||||
egui::CentralPanel::default().frame(egui::Frame::NONE.fill(theme::Tokens::get(&ctx).chrome)).show(ui, |ui| docking::show(self, ui));
|
||||
windows::show(self, &ctx);
|
||||
|
||||
@@ -51,7 +51,7 @@ mod unsaved_state_tests {
|
||||
let mut a = app(false);
|
||||
guard(&mut a, Guarded::Menu { id: "ui.closeAll".into() });
|
||||
assert!(a.ui.windows.unsaved.is_none());
|
||||
assert_eq!(a.session.pkg.graphs.first().map(|g| g.name.as_str()), Some("New_graph"), "the empty package replaced it");
|
||||
assert_eq!(a.session.pkg.graphs.first().map(|g| g.name.as_str()), Some("Material_Graph"), "the empty package replaced it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+398
-80
@@ -1,6 +1,7 @@
|
||||
//! The library: a category tree on the left, the matching nodes as preview tiles (or a list) on
|
||||
//! the right, with search. Drag a tile into the graph, or double-click it to add it next to the
|
||||
//! selection.
|
||||
//! The library: a category tree on the left, the matching entries as preview tiles (or a list)
|
||||
//! on the right, with search and favorites. Drag a tile into the graph, or double-click it to
|
||||
//! add it next to the selection. Entries are nodes, graph items (frame, comment, pin), function
|
||||
//! nodes (for the open function graph), the package's own graphs and loaded plugin graphs.
|
||||
|
||||
use egui::{Color32, Rect, RichText, Sense, Ui, vec2};
|
||||
use egui_phosphor::regular as icon;
|
||||
@@ -10,66 +11,238 @@ use crate::graph_view::{LibraryDrag, header_color};
|
||||
use crate::i18n::tr;
|
||||
use crate::theme::Tokens;
|
||||
|
||||
/// The tree: (top level, its sub-categories as full category paths).
|
||||
fn tree() -> Vec<(&'static str, Vec<&'static str>)> {
|
||||
let mut out: Vec<(&'static str, Vec<&'static str>)> = Vec::new();
|
||||
for (cat, _) in materialcraft_engine::nodes::categories() {
|
||||
let top = cat.split('/').next().unwrap_or(cat);
|
||||
/// The favorites pseudo-category.
|
||||
pub const FAVORITES: &str = "@favorites";
|
||||
|
||||
/// Where an entry comes from, and so what adding it does.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Kind {
|
||||
/// A node of the catalog (`id` is its def).
|
||||
Node,
|
||||
/// A frame, comment or navigation pin: `id` is the engine command.
|
||||
GraphItem,
|
||||
/// A function node for the open function graph: `id` is the op.
|
||||
FnOp,
|
||||
/// A graph of the open package: `id` is its name.
|
||||
PackageGraph,
|
||||
/// A graph of a loaded plugin: `id` is the graph, `package` the file it lives in.
|
||||
PluginGraph { package: String },
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Entry {
|
||||
pub id: String,
|
||||
pub label: String,
|
||||
pub category: String,
|
||||
pub kind: Kind,
|
||||
}
|
||||
|
||||
impl Entry {
|
||||
fn new(id: impl Into<String>, label: impl Into<String>, category: impl Into<String>, kind: Kind) -> Entry {
|
||||
Entry { id: id.into(), label: label.into(), category: category.into(), kind }
|
||||
}
|
||||
|
||||
/// The key favorites and drags use.
|
||||
pub fn key(&self) -> String {
|
||||
match &self.kind {
|
||||
Kind::Node => self.id.clone(),
|
||||
Kind::GraphItem => format!("!{}", self.id),
|
||||
Kind::FnOp => format!("fn:{}", self.id),
|
||||
Kind::PackageGraph => format!("@{}", self.id),
|
||||
Kind::PluginGraph { package } => format!("+{package}\n{}", self.id),
|
||||
}
|
||||
}
|
||||
|
||||
/// The def whose header colour the tile borrows.
|
||||
fn color_def(&self) -> &str {
|
||||
match self.kind {
|
||||
Kind::Node => &self.id,
|
||||
Kind::GraphItem => "dot",
|
||||
Kind::FnOp => "pixel_processor",
|
||||
Kind::PackageGraph | Kind::PluginGraph { .. } => "graph_instance",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The tree in display order: (top level, sub-categories as full paths). Groups the catalog
|
||||
/// has no nodes for yet are listed too, greyed with a zero count.
|
||||
pub fn tree() -> Vec<(String, Vec<String>)> {
|
||||
let planned: [(&str, &[&str]); 13] = [
|
||||
("Graph items", &[]),
|
||||
("Atomic nodes", &[]),
|
||||
("FxMap nodes", &[]),
|
||||
("Function nodes", &[]),
|
||||
("Texture generators", &[]),
|
||||
("Filters", &[]),
|
||||
("Material filters", &["Material filters/1-click", "Material filters/Effects", "Material filters/Transforms", "Material filters/Scan processing"]),
|
||||
("Mesh-based generators", &[]),
|
||||
("Spline & Path tools", &[]),
|
||||
("SDF functions", &[]),
|
||||
("Functions", &[]),
|
||||
("PBR materials", &["PBR materials/This package", "PBR materials/Plugins"]),
|
||||
("Values", &["Values/Constant"]),
|
||||
];
|
||||
let mut out: Vec<(String, Vec<String>)> = planned.iter().map(|(t, subs)| (t.to_string(), subs.iter().map(|s| s.to_string()).collect())).collect();
|
||||
let mut place = |cat: String| {
|
||||
let top = cat.split('/').next().unwrap_or(&cat).to_string();
|
||||
match out.iter_mut().find(|(t, _)| *t == top) {
|
||||
Some((_, subs)) => {
|
||||
if cat != top {
|
||||
subs.push(cat);
|
||||
if cat != top && !subs.contains(&cat) {
|
||||
// Groups the catalog fills go before the planned (empty) ones.
|
||||
let at = subs.iter().position(|s| planned.iter().any(|(_, p)| p.contains(&s.as_str()))).unwrap_or(subs.len());
|
||||
subs.insert(at, cat);
|
||||
}
|
||||
}
|
||||
None => out.push((top, if cat != top { vec![cat] } else { Vec::new() })),
|
||||
None => out.push((top.clone(), if cat != top { vec![cat] } else { Vec::new() })),
|
||||
}
|
||||
};
|
||||
for (cat, _) in materialcraft_engine::nodes::categories() {
|
||||
place(cat.to_string());
|
||||
}
|
||||
for (group, _) in fn_groups() {
|
||||
place(fn_path(group));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Function node groups in catalog order: (group, ops).
|
||||
/// One function node operation of the catalog: (id, label, inputs, group).
|
||||
type FnOp = &'static (&'static str, &'static str, usize, &'static str);
|
||||
|
||||
fn fn_groups() -> Vec<(&'static str, Vec<FnOp>)> {
|
||||
let mut out: Vec<(&'static str, Vec<FnOp>)> = Vec::new();
|
||||
for op in materialcraft_engine::nodes::function::FN_OPS {
|
||||
match out.iter_mut().find(|(c, _)| *c == op.3) {
|
||||
Some((_, ops)) => ops.push(op),
|
||||
None => out.push((op.3, vec![op])),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The library path of a function node group: constants are values, the rest function nodes.
|
||||
fn fn_path(group: &str) -> String {
|
||||
if group == "Constant" { "Values/Constant".to_string() } else { format!("Function nodes/{group}") }
|
||||
}
|
||||
|
||||
fn category_icon(top: &str) -> &'static str {
|
||||
match top {
|
||||
"Atomic nodes" => icon::CUBE,
|
||||
"Graph items" => icon::FLOW_ARROW,
|
||||
"Texture generators" => icon::DICE_FIVE,
|
||||
"FxMap nodes" => icon::DICE_FIVE,
|
||||
"Function nodes" | "Values" => icon::FUNCTION,
|
||||
"Texture generators" => icon::WAVES,
|
||||
"Filters" => icon::FADERS,
|
||||
"Material filters" => icon::SPHERE,
|
||||
"Mesh-based generators" => icon::CUBE_TRANSPARENT,
|
||||
"Spline & Path tools" => icon::BEZIER_CURVE,
|
||||
"SDF functions" => icon::CIRCLES_THREE,
|
||||
"Functions" => icon::GRAPH,
|
||||
"PBR materials" => icon::PAINT_BUCKET,
|
||||
_ => icon::FOLDER_OPEN,
|
||||
}
|
||||
}
|
||||
|
||||
/// Every entry the library can show (unfiltered).
|
||||
pub fn all_entries(app: &mut MaterialCraftApp) -> Vec<Entry> {
|
||||
let mut out: Vec<Entry> = vec![
|
||||
Entry::new("graph.comment.add", tr("Comment"), "Graph items", Kind::GraphItem),
|
||||
Entry::new("graph.frame.add", tr("Frame"), "Graph items", Kind::GraphItem),
|
||||
Entry::new("graph.pin.add", tr("Pin"), "Graph items", Kind::GraphItem),
|
||||
];
|
||||
for d in materialcraft_engine::nodes::catalog() {
|
||||
if d.id == "graph_instance" {
|
||||
continue;
|
||||
}
|
||||
let category = if d.id == "fx_map" { "FxMap nodes" } else { d.category };
|
||||
out.push(Entry::new(d.id, d.label, category, Kind::Node));
|
||||
}
|
||||
for (group, ops) in fn_groups() {
|
||||
let path = fn_path(group);
|
||||
for op in ops {
|
||||
out.push(Entry::new(op.0, op.1, path.clone(), Kind::FnOp));
|
||||
}
|
||||
}
|
||||
let open = app.session.graph;
|
||||
for (i, g) in app.session.pkg.graphs.iter().enumerate() {
|
||||
if i == open {
|
||||
continue;
|
||||
}
|
||||
let cat = match g.kind {
|
||||
materialcraft_engine::core::GraphKind::Function => "Functions",
|
||||
materialcraft_engine::core::GraphKind::Material => "PBR materials/This package",
|
||||
};
|
||||
out.push(Entry::new(&g.name, &g.name, cat, Kind::PackageGraph));
|
||||
}
|
||||
for (plugin, package, graph) in app.plugin_graphs() {
|
||||
out.push(Entry::new(&graph, format!("{graph} · {plugin}"), "PBR materials/Plugins", Kind::PluginGraph { package }));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn in_category(e: &Entry, cat: &str) -> bool {
|
||||
cat.is_empty() || e.category == cat || e.category.starts_with(&format!("{cat}/"))
|
||||
}
|
||||
|
||||
/// Library entries for the current filter.
|
||||
fn entries(app: &mut MaterialCraftApp, all: &[Entry]) -> Vec<Entry> {
|
||||
let search = app.ui.library_search.to_ascii_lowercase();
|
||||
let cat = app.ui.library_category.clone();
|
||||
let favs = &app.ui.library_favorites;
|
||||
all.iter()
|
||||
.filter(|e| if cat == FAVORITES { favs.contains(&e.key()) } else { in_category(e, &cat) })
|
||||
.filter(|e| search.is_empty() || e.label.to_ascii_lowercase().contains(&search) || e.id.to_ascii_lowercase().contains(&search))
|
||||
.cloned()
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(RichText::new(icon::MAGNIFYING_GLASS).color(tk.text_dim));
|
||||
let r = ui.add(egui::TextEdit::singleline(&mut app.ui.library_search).hint_text(tr("Search")).desired_width((ui.available_width() - 56.0).max(40.0)));
|
||||
let r = ui.add(egui::TextEdit::singleline(&mut app.ui.library_search).hint_text(tr("Search")).desired_width((ui.available_width() - 130.0).max(40.0)));
|
||||
crate::widgets::name(&r, egui::Role::SearchInput, "Search the library");
|
||||
if !app.ui.library_search.is_empty() && crate::widgets::icon_button(ui, icon::X, tr("Clear search"), false, 20.0).clicked() {
|
||||
app.ui.library_search.clear();
|
||||
}
|
||||
let fav = app.ui.library_category == FAVORITES;
|
||||
if crate::widgets::icon_button(ui, icon::STAR, tr("Favorites"), fav, 20.0).clicked() {
|
||||
app.ui.library_category = if fav { String::new() } else { FAVORITES.into() };
|
||||
}
|
||||
if crate::widgets::icon_button(ui, icon::SQUARES_FOUR, tr("Icons"), !app.ui.prefs.library_list, 20.0).clicked() {
|
||||
app.ui.prefs.library_list = false;
|
||||
}
|
||||
if crate::widgets::icon_button(ui, icon::LIST, tr("List"), app.ui.prefs.library_list, 20.0).clicked() {
|
||||
app.ui.prefs.library_list = true;
|
||||
}
|
||||
if !app.ui.prefs.library_list {
|
||||
ui.add(egui::Slider::new(&mut app.ui.prefs.library_tile, 56.0..=160.0).show_value(false)).on_hover_text(tr("Tile size"));
|
||||
}
|
||||
});
|
||||
ui.add_space(2.0);
|
||||
let all = all_entries(app);
|
||||
let avail = ui.available_size();
|
||||
let tree_w = (avail.x * 0.36).clamp(90.0, 170.0);
|
||||
let tree_w = (avail.x * 0.36).clamp(90.0, 190.0);
|
||||
let top_down = egui::Layout::top_down(egui::Align::Min);
|
||||
ui.horizontal_top(|ui| {
|
||||
ui.allocate_ui_with_layout(vec2(tree_w, avail.y), top_down, |ui| {
|
||||
egui::ScrollArea::vertical().id_salt("lib-tree").auto_shrink([false, false]).show(ui, |ui| category_tree(app, ui));
|
||||
egui::ScrollArea::vertical().id_salt("lib-tree").auto_shrink([false, false]).show(ui, |ui| category_tree(app, ui, &all));
|
||||
});
|
||||
ui.separator();
|
||||
ui.allocate_ui_with_layout(vec2(ui.available_width(), avail.y), top_down, |ui| {
|
||||
egui::ScrollArea::vertical().id_salt("lib-items").auto_shrink([false, false]).show(ui, |ui| items(app, ui));
|
||||
egui::ScrollArea::vertical().id_salt("lib-items").auto_shrink([false, false]).show(ui, |ui| items(app, ui, &all));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
fn category_tree(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
fn category_tree(app: &mut MaterialCraftApp, ui: &mut Ui, all: &[Entry]) {
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
let mut row = |ui: &mut Ui, text: String, path: &str, indent: f32| {
|
||||
let count = |cat: &str| all.iter().filter(|e| in_category(e, cat)).count();
|
||||
let mut select: Option<String> = None;
|
||||
let mut toggle: Option<String> = None;
|
||||
let mut row = |ui: &mut Ui, text: String, path: &str, indent: f32, n: Option<usize>, arrow: Option<bool>| {
|
||||
let on = app.ui.library_category == path;
|
||||
let empty = n == Some(0);
|
||||
let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 20.0), Sense::click());
|
||||
crate::widgets::name(&resp, egui::Role::TreeItem, &text);
|
||||
if on {
|
||||
@@ -77,83 +250,106 @@ fn category_tree(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
} else if resp.hovered() {
|
||||
ui.painter().rect_filled(r, 4.0, tk.row_hover);
|
||||
}
|
||||
let g = crate::widgets::elided(ui.painter(), text, 11.5, if on { tk.text_strong } else { tk.text }, r.width() - indent - 4.0);
|
||||
ui.painter().galley(r.left_center() + vec2(indent, -g.size().y * 0.5), g, tk.text);
|
||||
if resp.clicked() {
|
||||
app.ui.library_category = path.to_string();
|
||||
let color = if empty {
|
||||
tk.text_dim
|
||||
} else if on {
|
||||
tk.text_strong
|
||||
} else {
|
||||
tk.text
|
||||
};
|
||||
let mut arrow_w = 0.0;
|
||||
if let Some(open) = arrow {
|
||||
arrow_w = 14.0;
|
||||
let a = Rect::from_min_size(r.min + vec2(indent - 2.0, 0.0), vec2(14.0, r.height()));
|
||||
ui.painter().text(
|
||||
a.center(),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
if open { icon::CARET_DOWN } else { icon::CARET_RIGHT },
|
||||
egui::FontId::proportional(10.0),
|
||||
tk.text_dim,
|
||||
);
|
||||
if resp.clicked() && resp.interact_pointer_pos().is_some_and(|p| a.contains(p)) {
|
||||
toggle = Some(path.to_string());
|
||||
} else if resp.clicked() {
|
||||
select = Some(path.to_string());
|
||||
}
|
||||
} else if resp.clicked() {
|
||||
select = Some(path.to_string());
|
||||
}
|
||||
let label = match n {
|
||||
Some(n) if n == 0 || indent > 10.0 => format!("{text} ({n})"),
|
||||
_ => text,
|
||||
};
|
||||
let g = crate::widgets::elided(ui.painter(), label, 11.5, color, r.width() - indent - arrow_w - 4.0);
|
||||
ui.painter().galley(r.left_center() + vec2(indent + arrow_w, -g.size().y * 0.5), g, color);
|
||||
if resp.double_clicked() && arrow.is_some() {
|
||||
toggle = Some(path.to_string());
|
||||
}
|
||||
};
|
||||
row(ui, format!("{} {}", icon::SQUARES_FOUR, tr("All nodes")), "", 4.0);
|
||||
if app.session.pkg.graphs.len() > 1 {
|
||||
row(ui, format!("{} {}", icon::TREE_STRUCTURE, tr("This package")), "@package", 4.0);
|
||||
}
|
||||
row(ui, format!("{} {}", icon::SQUARES_FOUR, tr("All nodes")), "", 4.0, None, None);
|
||||
row(ui, format!("{} {}", icon::STAR, tr("Favorites")), FAVORITES, 4.0, Some(app.ui.library_favorites.len()), None);
|
||||
for (top, subs) in tree() {
|
||||
row(ui, format!("{} {}", category_icon(top), tr(top)), top, 4.0);
|
||||
for sub in subs {
|
||||
let name = sub.rsplit('/').next().unwrap_or(sub);
|
||||
row(ui, tr(name).to_string(), sub, 22.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Library entries for the current filter: (id, label, category, is a package graph).
|
||||
fn entries(app: &MaterialCraftApp) -> Vec<(String, String, &'static str, bool)> {
|
||||
let search = app.ui.library_search.to_ascii_lowercase();
|
||||
let cat = &app.ui.library_category;
|
||||
let mut out: Vec<(String, String, &'static str, bool)> = Vec::new();
|
||||
if cat == "@package" || !search.is_empty() {
|
||||
for (i, g) in app.session.pkg.graphs.iter().enumerate() {
|
||||
if i != app.session.graph && (search.is_empty() || g.name.to_ascii_lowercase().contains(&search)) {
|
||||
out.push((g.name.clone(), g.name.clone(), "This package", true));
|
||||
let open = !app.ui.library_collapsed.contains(&top);
|
||||
let n = count(&top);
|
||||
row(ui, format!("{} {}", category_icon(&top), tr(&top)), &top, 4.0, Some(n), if subs.is_empty() { None } else { Some(open) });
|
||||
if open {
|
||||
for sub in subs {
|
||||
let name = sub.rsplit('/').next().unwrap_or(&sub);
|
||||
row(ui, tr(name).to_string(), &sub, 24.0, Some(count(&sub)), None);
|
||||
}
|
||||
}
|
||||
if cat == "@package" {
|
||||
return out;
|
||||
}
|
||||
if let Some(p) = select {
|
||||
app.ui.library_category = p;
|
||||
}
|
||||
if let Some(t) = toggle {
|
||||
if app.ui.library_collapsed.contains(&t) {
|
||||
app.ui.library_collapsed.retain(|c| *c != t);
|
||||
} else {
|
||||
app.ui.library_collapsed.push(t);
|
||||
}
|
||||
}
|
||||
for d in materialcraft_engine::nodes::catalog() {
|
||||
if d.id == "graph_instance" {
|
||||
continue;
|
||||
}
|
||||
if !(cat.is_empty() || d.category == cat || d.category.starts_with(&format!("{cat}/"))) {
|
||||
continue;
|
||||
}
|
||||
if !(search.is_empty() || d.label.to_ascii_lowercase().contains(&search) || d.id.contains(&search)) {
|
||||
continue;
|
||||
}
|
||||
out.push((d.id.to_string(), d.label.to_string(), d.category, false));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn items(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
fn items(app: &mut MaterialCraftApp, ui: &mut Ui, all: &[Entry]) {
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
let ctx = ui.ctx().clone();
|
||||
let list = entries(app);
|
||||
let list = entries(app, all);
|
||||
if list.is_empty() {
|
||||
ui.label(RichText::new(tr("Nothing matches")).color(tk.text_dim));
|
||||
let hint = if app.ui.library_category == FAVORITES {
|
||||
tr("No favorites yet: right-click a tile and choose Add to favorites")
|
||||
} else if app.ui.library_category.starts_with("PBR materials/Plugins") {
|
||||
tr("No plugin graphs: load a plugin in Tools ▸ Plugin Manager")
|
||||
} else if app.ui.library_search.is_empty() {
|
||||
tr("Nothing here yet")
|
||||
} else {
|
||||
tr("Nothing matches")
|
||||
};
|
||||
ui.label(RichText::new(hint).color(tk.text_dim));
|
||||
return;
|
||||
}
|
||||
let as_list = app.ui.prefs.library_list;
|
||||
let tile = vec2(78.0, 98.0);
|
||||
let side = app.ui.prefs.library_tile.clamp(56.0, 160.0);
|
||||
let tile = vec2(side, side + 20.0);
|
||||
let cols = if as_list { 1 } else { ((ui.available_width() + 4.0) / (tile.x + 4.0)).floor().max(1.0) as usize };
|
||||
let mut add: Option<(String, bool)> = None;
|
||||
let mut add: Option<Entry> = None;
|
||||
let mut star: Option<(String, bool)> = None;
|
||||
for chunk in list.chunks(cols) {
|
||||
ui.horizontal(|ui| {
|
||||
ui.spacing_mut().item_spacing = vec2(4.0, 4.0);
|
||||
for (id, label, cat, is_graph) in chunk {
|
||||
for e in chunk {
|
||||
let size = if as_list { vec2(ui.available_width(), 26.0) } else { tile };
|
||||
let (r, resp) = ui.allocate_exact_size(size, Sense::click_and_drag());
|
||||
crate::widgets::name(&resp, egui::Role::ListItem, label);
|
||||
let def_id = if *is_graph { "graph_instance" } else { id.as_str() };
|
||||
crate::widgets::name(&resp, egui::Role::ListItem, &e.label);
|
||||
let def_id = e.color_def();
|
||||
if resp.hovered() {
|
||||
ui.painter().rect_filled(r, 6.0, tk.row_hover);
|
||||
}
|
||||
let tex = if *is_graph { None } else { app.thumbs.library(&ctx, id) };
|
||||
let tex = if e.kind == Kind::Node { app.thumbs.library(&ctx, &e.id) } else { None };
|
||||
let img_rect = if as_list {
|
||||
Rect::from_min_size(r.min + vec2(2.0, 2.0), vec2(22.0, 22.0))
|
||||
} else {
|
||||
Rect::from_min_size(r.min + vec2(5.0, 4.0), vec2(68.0, 68.0))
|
||||
Rect::from_min_size(r.min + vec2(5.0, 4.0), vec2(side - 10.0, side - 10.0))
|
||||
};
|
||||
match tex {
|
||||
Some(t) => {
|
||||
@@ -161,10 +357,17 @@ fn items(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
}
|
||||
None => {
|
||||
ui.painter().rect_filled(img_rect, 4.0, header_color(def_id).gamma_multiply(0.7));
|
||||
let glyph = match &e.kind {
|
||||
Kind::Node => icon::CUBE,
|
||||
Kind::GraphItem => icon::NOTE_PENCIL,
|
||||
Kind::FnOp => icon::FUNCTION,
|
||||
Kind::PackageGraph => icon::TREE_STRUCTURE,
|
||||
Kind::PluginGraph { .. } => icon::PUZZLE_PIECE,
|
||||
};
|
||||
ui.painter().text(
|
||||
img_rect.center(),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
if *is_graph { icon::TREE_STRUCTURE } else { icon::CUBE },
|
||||
glyph,
|
||||
egui::FontId::proportional(img_rect.height() * 0.4),
|
||||
Color32::WHITE,
|
||||
);
|
||||
@@ -173,30 +376,145 @@ fn items(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
// The category color as a strip, like the node headers.
|
||||
let strip = Rect::from_min_size(img_rect.left_bottom() - vec2(0.0, 3.0), vec2(img_rect.width(), 3.0));
|
||||
ui.painter().rect_filled(strip, 0.0, header_color(def_id));
|
||||
let key = e.key();
|
||||
let starred = app.ui.library_favorites.contains(&key);
|
||||
if starred {
|
||||
ui.painter().text(
|
||||
img_rect.right_top() + vec2(-3.0, 3.0),
|
||||
egui::Align2::RIGHT_TOP,
|
||||
icon::STAR,
|
||||
egui::FontId::proportional(11.0),
|
||||
Color32::from_rgb(0xf5, 0xc5, 0x42),
|
||||
);
|
||||
}
|
||||
if as_list {
|
||||
let g = crate::widgets::elided(ui.painter(), label.clone(), 11.5, tk.text, r.width() - 34.0);
|
||||
let g = crate::widgets::elided(ui.painter(), e.label.clone(), 11.5, tk.text, r.width() - 34.0);
|
||||
ui.painter().galley(r.left_center() + vec2(30.0, -g.size().y * 0.5), g, tk.text);
|
||||
} else {
|
||||
let galley = ui.painter().layout(label.clone(), egui::FontId::proportional(10.5), tk.text, tile.x - 4.0);
|
||||
let galley = ui.painter().layout(e.label.clone(), egui::FontId::proportional(10.5), tk.text, tile.x - 4.0);
|
||||
let pos = egui::pos2(r.center().x - galley.size().x * 0.5, img_rect.bottom() + 3.0);
|
||||
ui.painter().galley(pos, galley, tk.text);
|
||||
}
|
||||
let resp = resp.on_hover_text(format!("{label}\n{cat}"));
|
||||
let hint = match &e.kind {
|
||||
Kind::FnOp => format!("{}\n{}\n{}", e.label, e.category, tr("Function node: for the open function graph")),
|
||||
Kind::PluginGraph { package } => format!("{}\n{}\n{package}", e.label, e.category),
|
||||
_ => format!("{}\n{}", e.label, e.category),
|
||||
};
|
||||
let resp = resp.on_hover_text(hint);
|
||||
if resp.drag_started() {
|
||||
let payload = if *is_graph { format!("@{id}") } else { id.clone() };
|
||||
egui::DragAndDrop::set_payload(&ctx, LibraryDrag(payload));
|
||||
egui::DragAndDrop::set_payload(&ctx, LibraryDrag(key.clone()));
|
||||
}
|
||||
if resp.double_clicked() {
|
||||
add = Some((id.clone(), *is_graph));
|
||||
add = Some(e.clone());
|
||||
}
|
||||
resp.context_menu(|ui| {
|
||||
if ui.button(tr("Add to graph")).clicked() {
|
||||
add = Some(e.clone());
|
||||
ui.close();
|
||||
}
|
||||
let label = if starred { tr("Remove from favorites") } else { tr("Add to favorites") };
|
||||
if ui.button(label).clicked() {
|
||||
star = Some((key.clone(), !starred));
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
if let Some((id, is_graph)) = add {
|
||||
if is_graph {
|
||||
app.run("graph.node.add", serde_json::json!({"def": "graph_instance", "params": {"graph": id}}));
|
||||
} else {
|
||||
crate::graph_view::add_node_near_selection(app, &id);
|
||||
if let Some((key, on)) = star {
|
||||
app.ui.library_favorites.retain(|k| *k != key);
|
||||
if on {
|
||||
app.ui.library_favorites.push(key);
|
||||
app.ui.library_favorites.truncate(500);
|
||||
}
|
||||
}
|
||||
if let Some(e) = add {
|
||||
add_entry(app, &e, None);
|
||||
}
|
||||
}
|
||||
|
||||
/// Add a library entry to the graph (double-click, context menu), or at `at` (a drop).
|
||||
pub fn add_entry(app: &mut MaterialCraftApp, e: &Entry, at: Option<[f32; 2]>) {
|
||||
match &e.kind {
|
||||
Kind::Node => match at {
|
||||
Some(at) => {
|
||||
app.run("graph.node.add", serde_json::json!({"def": e.id, "at": at}));
|
||||
}
|
||||
None => crate::graph_view::add_node_near_selection(app, &e.id),
|
||||
},
|
||||
Kind::GraphItem => add_graph_item(app, &e.id, at),
|
||||
Kind::FnOp => {
|
||||
if !crate::function_editor::add_op(app, &e.id) {
|
||||
app.toast(tr("Function nodes go into a function graph: open one from a Pixel Processor or a function parameter first"), true);
|
||||
}
|
||||
}
|
||||
Kind::PackageGraph => {
|
||||
let mut p = serde_json::json!({"def": "graph_instance", "params": {"graph": e.id}});
|
||||
if let Some(at) = at {
|
||||
p["at"] = serde_json::json!(at);
|
||||
}
|
||||
app.run("graph.node.add", p);
|
||||
}
|
||||
Kind::PluginGraph { package } => app.add_plugin_graph(package, &e.id, at),
|
||||
}
|
||||
}
|
||||
|
||||
/// A frame (around the selection, or an empty one at `at`), a comment or a pin.
|
||||
fn add_graph_item(app: &mut MaterialCraftApp, cmd: &str, at: Option<[f32; 2]>) {
|
||||
let c = crate::graph_view::view_center(app);
|
||||
let at = at.unwrap_or([c.x - 60.0, c.y - 20.0]);
|
||||
let params = match cmd {
|
||||
"graph.frame.add" if app.session.selection.is_empty() => serde_json::json!({"rect": [at[0], at[1], 320.0, 200.0]}),
|
||||
"graph.frame.add" => serde_json::json!({}),
|
||||
_ => serde_json::json!({"at": at}),
|
||||
};
|
||||
app.run(cmd, params);
|
||||
}
|
||||
|
||||
/// Add whatever a library drag key names at `at` (the graph view's drop handler).
|
||||
pub fn add_key(app: &mut MaterialCraftApp, key: &str, at: [f32; 2]) {
|
||||
if let Some(cmd) = key.strip_prefix('!') {
|
||||
add_graph_item(app, cmd, Some(at));
|
||||
} else if let Some(op) = key.strip_prefix("fn:") {
|
||||
if !crate::function_editor::add_op(app, op) {
|
||||
app.toast(tr("Function nodes go into a function graph: open one from a Pixel Processor or a function parameter first"), true);
|
||||
}
|
||||
} else if let Some(plugin) = key.strip_prefix('+') {
|
||||
if let Some((pkg, graph)) = plugin.split_once('\n') {
|
||||
app.add_plugin_graph(pkg, graph, Some(at));
|
||||
}
|
||||
} else if let Some(graph) = key.strip_prefix('@') {
|
||||
app.run("graph.node.add", serde_json::json!({"def": "graph_instance", "at": at, "params": {"graph": graph}}));
|
||||
} else {
|
||||
app.run("graph.node.add", serde_json::json!({"def": key, "at": at}));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_tree_lists_every_catalog_category_once() {
|
||||
let t = tree();
|
||||
for (cat, _) in materialcraft_engine::nodes::categories() {
|
||||
let top = cat.split('/').next().unwrap_or(cat);
|
||||
let hits = t.iter().filter(|(c, subs)| c == top && (cat == top || subs.iter().any(|s| s == cat))).count();
|
||||
assert_eq!(hits, 1, "{cat} appears once");
|
||||
}
|
||||
let tops: Vec<_> = t.iter().map(|(c, _)| c.clone()).collect();
|
||||
let mut dedup = tops.clone();
|
||||
dedup.dedup();
|
||||
assert_eq!(tops, dedup, "no duplicate top-level groups");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keys_round_trip_through_the_drop_handler_prefixes() {
|
||||
let plugin = Entry::new("Rust", "Rust", "PBR materials/Plugins", Kind::PluginGraph { package: "C:/p/x.sbs".into() });
|
||||
assert_eq!(plugin.key(), "+C:/p/x.sbs\nRust");
|
||||
assert_eq!(Entry::new("blur", "Blur", "Filters/Blurs", Kind::Node).key(), "blur");
|
||||
assert_eq!(Entry::new("Base", "Base", "PBR materials/This package", Kind::PackageGraph).key(), "@Base");
|
||||
assert_eq!(Entry::new("add", "Add", "Function nodes/Operator", Kind::FnOp).key(), "fn:add");
|
||||
assert_eq!(Entry::new("graph.pin.add", "Pin", "Graph items", Kind::GraphItem).key(), "!graph.pin.add");
|
||||
}
|
||||
}
|
||||
+123
-26
@@ -33,34 +33,26 @@ pub const TOP: [&str; 5] = ["File", "Edit", "Tools", "Windows", "Help"];
|
||||
|
||||
/// The menu catalog (the target menu tree with our ids).
|
||||
pub const CATALOG: &[Item] = &[
|
||||
sub("File", "New", "Graph...", "ui.newGraph", Some("Ctrl+N")),
|
||||
sub("File", "New", "Material Graph...", "ui.newGraph", Some("Ctrl+N")),
|
||||
sub("File", "New", "Function graph", "ui.newFunctionGraph", None),
|
||||
sub("File", "New", "Empty package", "file.newPackage", None),
|
||||
it("File", "Open...", "file.open", Some("Ctrl+O")),
|
||||
// "Recent packages" follows Open (menu_item draws it from the recent list).
|
||||
sep("File"),
|
||||
it("File", "Save", "file.save", Some("Ctrl+S")),
|
||||
it("File", "Save as...", "file.saveAs", Some("Ctrl+Shift+S")),
|
||||
it("File", "Save all", "ui.saveAll", Some("Ctrl+Shift+S")),
|
||||
it("File", "Close all", "ui.closeAll", None),
|
||||
sep("File"),
|
||||
it("File", "Import bitmap...", "file.importBitmap", None),
|
||||
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),
|
||||
it("File", "Reload resources", "ui.reloadResources", None),
|
||||
sep("File"),
|
||||
it("File", "Exit", "ui.quit", Some("Ctrl+Q")),
|
||||
it("Edit", "Undo", "edit.undo", Some("Ctrl+Z")),
|
||||
it("Edit", "Redo", "edit.redo", Some("Ctrl+Y")),
|
||||
sep("Edit"),
|
||||
it("Edit", "Copy", "edit.copy", Some("Ctrl+C")),
|
||||
it("Edit", "Cut", "edit.cut", Some("Ctrl+X")),
|
||||
it("Edit", "Paste", "edit.paste", Some("Ctrl+V")),
|
||||
it("Edit", "Duplicate", "edit.duplicate", Some("Ctrl+D")),
|
||||
it("Edit", "Delete", "edit.delete", Some("Delete")),
|
||||
it("Edit", "Delete and relink", "edit.deleteRelink", Some("Backspace")),
|
||||
it("Edit", "Select all", "edit.selectAll", Some("Ctrl+A")),
|
||||
sep("Edit"),
|
||||
it("Edit", "Preferences...", "ui.preferences", None),
|
||||
it("Tools", "Cancel rendering", "ui.cancelRender", Some("Escape")),
|
||||
it("Tools", "Suspend engine", "ui.suspendEngine", Some("Shift+Escape")),
|
||||
sep("Tools"),
|
||||
it("Tools", "Switch engine...", "ui.switchEngine", Some("F9")),
|
||||
sep("Tools"),
|
||||
it("Tools", "Compute graph", "graph.cook", Some("F5")),
|
||||
it("Tools", "Clear cache", "ui.clearCache", None),
|
||||
sub("Tools", "Preview size", "256 px", "ui.preview.256", None),
|
||||
@@ -69,27 +61,52 @@ pub const CATALOG: &[Item] = &[
|
||||
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", "Import bitmap...", "file.importBitmap", None),
|
||||
it("Tools", "Link bitmap...", "file.linkBitmap", None),
|
||||
it("Tools", "Export outputs...", "ui.export", Some("Ctrl+Shift+E")),
|
||||
it("Tools", "Export material...", "file.exportMaterial", None),
|
||||
it("Tools", "Send to TextureCraft", "file.sendToTextureCraft", None),
|
||||
sep("Tools"),
|
||||
it("Tools", "Plugin Manager...", "ui.pluginManager", None),
|
||||
it("Windows", "New Explorer", "ui.new.explorer", None),
|
||||
it("Windows", "New 3D View", "ui.new.3d", None),
|
||||
it("Windows", "New Library View", "ui.new.library", None),
|
||||
it("Windows", "Reset layout", "ui.resetLayout", None),
|
||||
it("Windows", "Unmaximize window", "ui.unmaximize", Some("Shift+Space")),
|
||||
sep("Windows"),
|
||||
it("Windows", "Explorer", "ui.view.explorer", None),
|
||||
it("Windows", "Graph", "ui.view.graph", None),
|
||||
it("Windows", "Properties", "ui.view.properties", None),
|
||||
it("Windows", "Parameters", "ui.view.properties", None),
|
||||
it("Windows", "Console", "ui.view.console", None),
|
||||
it("Windows", "3D View", "ui.view.3d", None),
|
||||
it("Windows", "Dependency Manager", "ui.view.dependencies", None),
|
||||
it("Windows", "2D View", "ui.view.2d", None),
|
||||
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.mainToolbar", 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", "Shortcuts list...", "ui.help.shortcuts", None),
|
||||
it("Help", "Automation documentation...", "ui.help.automation", None),
|
||||
sep("Help"),
|
||||
it("Help", "Join the community (Discord)...", "ui.help.discord", None),
|
||||
it("Help", "ArtCraft website...", "ui.help.website", None),
|
||||
it("Help", "Forums...", "ui.help.discord", None),
|
||||
it("Help", "Report a bug...", "ui.help.bug", None),
|
||||
it("Help", "Export log...", "ui.help.exportLog", None),
|
||||
it("Help", "Give feedback...", "ui.help.feedback", None),
|
||||
sep("Help"),
|
||||
it("Help", "Welcome screen...", "ui.home", None),
|
||||
it("Help", "What's new...", "ui.help.whatsNew", None),
|
||||
it("Help", "Shortcuts list...", "ui.help.shortcuts", None),
|
||||
sep("Help"),
|
||||
it("Help", "About MaterialCraft...", "ui.about", None),
|
||||
];
|
||||
|
||||
/// Items that are not in a menu but keep a global shortcut (the reference keeps them on the
|
||||
/// graph's and the explorer's context menus).
|
||||
pub const HIDDEN_SHORTCUTS: &[(&str, &str)] = &[("file.save", "Ctrl+S")];
|
||||
|
||||
fn is_ui(id: &str) -> bool {
|
||||
id.starts_with("ui.")
|
||||
}
|
||||
@@ -97,7 +114,12 @@ fn is_ui(id: &str) -> bool {
|
||||
/// Whether an item can run now.
|
||||
pub fn enabled(app: &MaterialCraftApp, id: &str) -> bool {
|
||||
if is_ui(id) {
|
||||
return id != "ui.newFunctionGraph";
|
||||
return match id {
|
||||
"ui.newFunctionGraph" => false,
|
||||
"ui.cancelRender" => app.cooker.busy(),
|
||||
"ui.unmaximize" => app.ui.dock.maximized.is_some(),
|
||||
_ => true,
|
||||
};
|
||||
}
|
||||
materialcraft_engine::find(id).is_some_and(|c| (c.enabled)(&app.session).is_ok())
|
||||
}
|
||||
@@ -123,23 +145,63 @@ pub fn invoke(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) {
|
||||
"ui.export" => app.ui.windows.export = true,
|
||||
"ui.quit" => ctx.send_viewport_cmd(egui::ViewportCommand::Close),
|
||||
"ui.preferences" => app.ui.windows.preferences = true,
|
||||
"ui.pluginManager" => app.ui.windows.plugin_manager = true,
|
||||
"ui.switchEngine" => app.ui.windows.switch_engine = true,
|
||||
"ui.view.dependencies" => app.ui.windows.dependencies = !app.ui.windows.dependencies,
|
||||
"ui.view.mainToolbar" => app.ui.prefs.show_main_toolbar = !app.ui.prefs.show_main_toolbar,
|
||||
"ui.saveAll" => invoke(app, ctx, "file.save"),
|
||||
"ui.cancelRender" => crate::cook::cancel(app),
|
||||
"ui.suspendEngine" => {
|
||||
app.cooker.suspended = !app.cooker.suspended;
|
||||
if !app.cooker.suspended {
|
||||
app.session.dirty = true;
|
||||
}
|
||||
let msg = if app.cooker.suspended { tr("Engine suspended: nothing computes until it is resumed") } else { tr("Engine resumed") };
|
||||
app.toast(msg, false);
|
||||
}
|
||||
"ui.new.explorer" => app.ui.dock.focus(crate::docking::Panel::Explorer),
|
||||
"ui.new.3d" => app.ui.dock.focus(crate::docking::Panel::View3d),
|
||||
"ui.new.library" => app.ui.dock.focus(crate::docking::Panel::Library),
|
||||
"ui.unmaximize" => app.ui.dock.maximized = None,
|
||||
"ui.view.graph" => {}
|
||||
"ui.resetLayout" => app.ui.dock = crate::docking::Dock::default(),
|
||||
// These replace the open package: ask first when it has unsaved changes.
|
||||
"ui.closeAll" | "file.newPackage" => crate::unsaved::guard(app, crate::unsaved::Guarded::Menu { id: id.to_string() }),
|
||||
"ui.reloadResources" | "ui.clearCache" => {
|
||||
"ui.clearCache" => {
|
||||
if let Ok(mut c) = app.session.cache.lock() {
|
||||
c.clear();
|
||||
}
|
||||
app.session.dirty = true;
|
||||
}
|
||||
"ui.reloadResources" => {
|
||||
if let Some(r) = app.run("file.reloadResources", Value::Null) {
|
||||
let n = r["reloaded"].as_array().map_or(0, Vec::len);
|
||||
let missing = r["missing"].as_array().map_or(0, Vec::len);
|
||||
if let Ok(mut c) = app.session.cache.lock() {
|
||||
c.clear();
|
||||
}
|
||||
app.session.dirty = true;
|
||||
let msg = match (n, missing) {
|
||||
(0, 0) => tr("Resources reloaded: nothing had changed").to_string(),
|
||||
(n, 0) => format!("{} {n}", tr("Resources reloaded:")),
|
||||
(n, m) => format!("{} {n}, {} {m} ({})", tr("Resources reloaded:"), tr("missing:"), tr("see the Console")),
|
||||
};
|
||||
app.toast(msg, missing > 0);
|
||||
}
|
||||
}
|
||||
"ui.home" => app.ui.windows.home = true,
|
||||
"ui.help.shortcuts" => app.ui.windows.shortcuts = true,
|
||||
"ui.about" => app.ui.windows.about = true,
|
||||
"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.tutorials" => ctx.open_url(egui::OpenUrl::new_tab("https://github.com/storytold/materialcraft/tree/main/docs")),
|
||||
"ui.help.releaseNotes" | "ui.help.whatsNew" => ctx.open_url(egui::OpenUrl::new_tab("https://github.com/storytold/materialcraft/releases")),
|
||||
"ui.help.requirements" => ctx.open_url(egui::OpenUrl::new_tab("https://github.com/storytold/materialcraft/blob/main/docs/releasing.md")),
|
||||
"ui.help.automation" => ctx.open_url(egui::OpenUrl::new_tab("https://github.com/storytold/materialcraft/blob/main/docs/control-protocol.md")),
|
||||
"ui.help.feedback" => ctx.open_url(egui::OpenUrl::new_tab("https://github.com/storytold/materialcraft/discussions")),
|
||||
"ui.help.bug" => ctx.open_url(egui::OpenUrl::new_tab("https://github.com/storytold/materialcraft/issues")),
|
||||
"ui.help.exportLog" => crate::windows::export_log(app),
|
||||
_ => {
|
||||
if crate::windows::file_action(app, ctx, id) {
|
||||
return;
|
||||
@@ -166,7 +228,12 @@ pub fn parse_shortcut(s: &str) -> Option<KeyboardShortcut> {
|
||||
|
||||
/// The shortcut text shown for `id` (the catalog's, else the engine command's).
|
||||
pub fn shortcut_of(id: &str) -> Option<&'static str> {
|
||||
CATALOG.iter().find(|i| i.id == id).and_then(|i| i.shortcut).or_else(|| materialcraft_engine::find(id).and_then(|c| c.shortcut))
|
||||
CATALOG
|
||||
.iter()
|
||||
.find(|i| i.id == id)
|
||||
.and_then(|i| i.shortcut)
|
||||
.or_else(|| HIDDEN_SHORTCUTS.iter().find(|(h, _)| *h == id).map(|(_, sc)| *sc))
|
||||
.or_else(|| materialcraft_engine::find(id).and_then(|c| c.shortcut))
|
||||
}
|
||||
|
||||
pub fn menu_bar(app: &mut MaterialCraftApp, ui: &mut egui::Ui) {
|
||||
@@ -204,6 +271,15 @@ pub fn menu_bar(app: &mut MaterialCraftApp, ui: &mut egui::Ui) {
|
||||
});
|
||||
}
|
||||
|
||||
/// A context-menu row with an optional shortcut hint on the right.
|
||||
pub fn menu_row(ui: &mut egui::Ui, label: &str, key: &str, enabled: bool) -> egui::Response {
|
||||
let mut b = egui::Button::new(label);
|
||||
if !key.is_empty() {
|
||||
b = b.shortcut_text(key);
|
||||
}
|
||||
ui.add_enabled(enabled, b)
|
||||
}
|
||||
|
||||
fn menu_item(app: &mut MaterialCraftApp, ctx: &egui::Context, ui: &mut egui::Ui, item: &Item) {
|
||||
let on = enabled(app, item.id);
|
||||
let mut b = egui::Button::new(tr(item.label));
|
||||
@@ -212,6 +288,9 @@ fn menu_item(app: &mut MaterialCraftApp, ctx: &egui::Context, ui: &mut egui::Ui,
|
||||
}
|
||||
let checked = match item.id {
|
||||
"ui.view.graph" => Some(true),
|
||||
"ui.view.mainToolbar" => Some(app.ui.prefs.show_main_toolbar),
|
||||
"ui.view.dependencies" => Some(app.ui.windows.dependencies),
|
||||
"ui.suspendEngine" => Some(app.cooker.suspended),
|
||||
id if id.starts_with("ui.preview.") => id.strip_prefix("ui.preview.").and_then(|s| s.parse::<u32>().ok()).map(|s| s == app.ui.prefs.preview_size),
|
||||
id => crate::docking::view_panel(id).map(|p| app.ui.dock.is_open(p)),
|
||||
};
|
||||
@@ -260,6 +339,9 @@ pub fn shortcuts(app: &mut MaterialCraftApp, ctx: &egui::Context) {
|
||||
}
|
||||
}
|
||||
let mut table: Vec<(&'static str, KeyboardShortcut)> = CATALOG.iter().filter_map(|i| Some((i.id, parse_shortcut(i.shortcut?)?))).collect();
|
||||
table.extend(HIDDEN_SHORTCUTS.iter().filter_map(|(id, sc)| Some((*id, parse_shortcut(sc)?))));
|
||||
// A disabled item leaves its key alone (Escape closes dialogs unless a cook is running).
|
||||
table.retain(|(id, _)| !is_ui(id) || enabled(app, id));
|
||||
for c in materialcraft_engine::command_specs() {
|
||||
if table.iter().any(|(id, _)| *id == c.id) {
|
||||
continue;
|
||||
@@ -281,6 +363,21 @@ pub fn shortcuts(app: &mut MaterialCraftApp, ctx: &egui::Context) {
|
||||
for id in fire {
|
||||
invoke(app, ctx, id);
|
||||
}
|
||||
// Node creation shortcuts (Preferences ▸ Shortcuts): add the node next to the selection.
|
||||
let node_keys: Vec<(String, KeyboardShortcut)> = app.ui.node_shortcuts.iter().filter_map(|(def, sc)| Some((def.clone(), parse_shortcut(sc)?))).collect();
|
||||
let mut add: Vec<String> = Vec::new();
|
||||
ctx.input_mut(|i| {
|
||||
for (def, sc) in &node_keys {
|
||||
if i.consume_shortcut(sc) {
|
||||
add.push(def.clone());
|
||||
}
|
||||
}
|
||||
});
|
||||
for def in add {
|
||||
if app.ui.dock.is_open(crate::docking::Panel::Graph) {
|
||||
crate::graph_view::add_node_near_selection(app, &def);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Menu items for `ui.menu.list`.
|
||||
|
||||
@@ -0,0 +1,335 @@
|
||||
//! Plugins (Tools ▸ Plugin Manager): packages dropped in the plugins folder whose graphs the
|
||||
//! library offers. A plugin is a package file (`.sbs`, `.mcraft`) in `Documents/MaterialCraft/plugins`,
|
||||
//! or a folder there holding package files and an optional `plugin.json`
|
||||
//! (`{"name", "version", "author", "description"}`). Loaded plugins are remembered per user.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use egui::{RichText, vec2};
|
||||
use egui_phosphor::regular as icon;
|
||||
|
||||
use crate::MaterialCraftApp;
|
||||
use crate::i18n::tr;
|
||||
use crate::theme::Tokens;
|
||||
|
||||
/// One plugin: a package file or a folder of them.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct Plugin {
|
||||
/// The plugin's key in the loaded list: its file or folder path.
|
||||
pub path: String,
|
||||
pub name: String,
|
||||
pub version: String,
|
||||
pub author: String,
|
||||
pub description: String,
|
||||
/// The package files and the graphs each one holds: (path, [graph names]).
|
||||
pub packages: Vec<(String, Vec<String>)>,
|
||||
/// Why a package could not be read, if any.
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
impl Plugin {
|
||||
/// Every graph of the plugin: (package path, graph name).
|
||||
pub fn graphs(&self) -> impl Iterator<Item = (&str, &str)> {
|
||||
self.packages.iter().flat_map(|(p, gs)| gs.iter().map(move |g| (p.as_str(), g.as_str())))
|
||||
}
|
||||
}
|
||||
|
||||
/// The plugins found in the plugins folder (scanned on first use and on Refresh).
|
||||
#[derive(Default)]
|
||||
pub struct Plugins {
|
||||
pub list: Vec<Plugin>,
|
||||
scanned: bool,
|
||||
pub filter: String,
|
||||
}
|
||||
|
||||
/// The plugins folder.
|
||||
pub fn folder() -> PathBuf {
|
||||
crate::user_dir("plugins")
|
||||
}
|
||||
|
||||
fn is_package(path: &Path) -> bool {
|
||||
path.extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("sbs") || e.eq_ignore_ascii_case("mcraft"))
|
||||
}
|
||||
|
||||
/// The graphs of a package file, read without opening it.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn graphs_of(path: &Path) -> Result<Vec<String>, String> {
|
||||
const MAX_PLUGIN_BYTES: u64 = 256 * 1024 * 1024;
|
||||
let len = std::fs::metadata(path).map_err(|e| e.to_string())?.len();
|
||||
if len > MAX_PLUGIN_BYTES {
|
||||
return Err(format!("{} is larger than {} MB", path.display(), MAX_PLUGIN_BYTES / (1024 * 1024)));
|
||||
}
|
||||
let bytes = std::fs::read(path).map_err(|e| e.to_string())?;
|
||||
let name = path.display().to_string();
|
||||
let linked = materialcraft_engine::file_cmds::linked_files(&name);
|
||||
let pkg = crate::cook::guard("plugin", || materialcraft_engine::file_cmds::load_bytes(&bytes, &name, &linked).map_err(|e| e.to_string()))?;
|
||||
Ok(pkg.graphs.iter().map(|g| g.name.clone()).collect())
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn graphs_of(_: &Path) -> Result<Vec<String>, String> {
|
||||
Err("the browser has no plugins folder".into())
|
||||
}
|
||||
|
||||
/// `plugin.json` next to a folder plugin's packages.
|
||||
#[derive(Default, serde::Deserialize)]
|
||||
#[serde(default)]
|
||||
struct Manifest {
|
||||
name: String,
|
||||
version: String,
|
||||
author: String,
|
||||
description: String,
|
||||
}
|
||||
|
||||
fn read_plugin(path: &Path) -> Plugin {
|
||||
let key = path.display().to_string();
|
||||
let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or("plugin").to_string();
|
||||
let mut plugin = Plugin { path: key, name: stem, ..Plugin::default() };
|
||||
let mut files: Vec<PathBuf> = Vec::new();
|
||||
if path.is_dir() {
|
||||
if let Ok(text) = std::fs::read_to_string(path.join("plugin.json"))
|
||||
&& let Ok(m) = serde_json::from_str::<Manifest>(&text)
|
||||
{
|
||||
if !m.name.trim().is_empty() {
|
||||
plugin.name = m.name.trim().chars().take(80).collect();
|
||||
}
|
||||
plugin.version = m.version.chars().take(32).collect();
|
||||
plugin.author = m.author.chars().take(80).collect();
|
||||
plugin.description = m.description.chars().take(400).collect();
|
||||
}
|
||||
if let Ok(rd) = std::fs::read_dir(path) {
|
||||
files.extend(rd.flatten().map(|e| e.path()).filter(|p| p.is_file() && is_package(p)));
|
||||
}
|
||||
files.sort();
|
||||
} else {
|
||||
files.push(path.to_path_buf());
|
||||
}
|
||||
for f in files {
|
||||
match graphs_of(&f) {
|
||||
Ok(graphs) => plugin.packages.push((f.display().to_string(), graphs)),
|
||||
Err(e) => plugin.error = Some(e),
|
||||
}
|
||||
}
|
||||
if plugin.packages.is_empty() && plugin.error.is_none() {
|
||||
plugin.error = Some(tr("No package files (.sbs, .mcraft) in this plugin").to_string());
|
||||
}
|
||||
plugin
|
||||
}
|
||||
|
||||
impl Plugins {
|
||||
/// Read the plugins folder again.
|
||||
pub fn refresh(&mut self) {
|
||||
self.scanned = true;
|
||||
self.list.clear();
|
||||
let Ok(rd) = std::fs::read_dir(folder()) else { return };
|
||||
let mut paths: Vec<PathBuf> = rd.flatten().map(|e| e.path()).filter(|p| p.is_dir() || is_package(p)).collect();
|
||||
paths.sort();
|
||||
self.list = paths.iter().take(500).map(|p| read_plugin(p)).collect();
|
||||
}
|
||||
|
||||
/// Scan once, on first use.
|
||||
pub fn ensure(&mut self) {
|
||||
if !self.scanned {
|
||||
self.refresh();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl MaterialCraftApp {
|
||||
/// Is the plugin at `path` loaded (its graphs in the library)?
|
||||
pub fn plugin_loaded(&self, path: &str) -> bool {
|
||||
self.ui.plugins_loaded.iter().any(|p| p == path)
|
||||
}
|
||||
|
||||
/// The graphs of every loaded plugin: (plugin name, package path, graph name).
|
||||
pub fn plugin_graphs(&mut self) -> Vec<(String, String, String)> {
|
||||
self.plugins.ensure();
|
||||
let loaded = &self.ui.plugins_loaded;
|
||||
self.plugins
|
||||
.list
|
||||
.iter()
|
||||
.filter(|p| loaded.contains(&p.path))
|
||||
.flat_map(|p| p.graphs().map(|(pkg, g)| (p.name.clone(), pkg.to_string(), g.to_string())).collect::<Vec<_>>())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Put a plugin graph into the open package and add an instance of it (library drop/double-click).
|
||||
pub fn add_plugin_graph(&mut self, package: &str, graph: &str, at: Option<[f32; 2]>) {
|
||||
let Some(v) = self.run("file.importGraph", serde_json::json!({"path": package, "graph": graph})) else { return };
|
||||
let name = v.get("name").and_then(|n| n.as_str()).unwrap_or(graph).to_string();
|
||||
let mut p = serde_json::json!({"def": "graph_instance", "params": {"graph": name}});
|
||||
if let Some(at) = at {
|
||||
p["at"] = serde_json::json!(at);
|
||||
}
|
||||
self.run("graph.node.add", p);
|
||||
}
|
||||
}
|
||||
|
||||
/// Copy the picked package files (or a folder) into the plugins folder.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn install(app: &mut MaterialCraftApp) {
|
||||
let Some(files) = rfd::FileDialog::new().add_filter("Packages", &["sbs", "mcraft"]).pick_files() else { return };
|
||||
let dir = folder();
|
||||
if let Err(e) = std::fs::create_dir_all(&dir) {
|
||||
app.toast(format!("{}: {e}", tr("Could not create the plugins folder")), true);
|
||||
return;
|
||||
}
|
||||
let mut n = 0;
|
||||
for f in files {
|
||||
let Some(name) = f.file_name() else { continue };
|
||||
match std::fs::copy(&f, dir.join(name)) {
|
||||
Ok(_) => n += 1,
|
||||
Err(e) => app.toast(format!("{}: {e}", f.display()), true),
|
||||
}
|
||||
}
|
||||
app.plugins.refresh();
|
||||
app.toast(format!("{n} {}", tr("plugin file(s) installed")), false);
|
||||
}
|
||||
|
||||
/// Open the plugins folder in the system's file browser.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn browse(app: &mut MaterialCraftApp) {
|
||||
let dir = folder();
|
||||
if let Err(e) = std::fs::create_dir_all(&dir) {
|
||||
app.toast(format!("{}: {e}", tr("Could not create the plugins folder")), true);
|
||||
return;
|
||||
}
|
||||
let program = if cfg!(target_os = "windows") {
|
||||
"explorer"
|
||||
} else if cfg!(target_os = "macos") {
|
||||
"open"
|
||||
} else {
|
||||
"xdg-open"
|
||||
};
|
||||
match std::process::Command::new(program).arg(&dir).spawn() {
|
||||
Ok(_) => app.toast(format!("{} {}", tr("Plugins folder:"), dir.display()), false),
|
||||
Err(e) => app.toast(format!("{} {} ({e})", tr("Plugins folder:"), dir.display()), true),
|
||||
}
|
||||
}
|
||||
|
||||
/// Tools ▸ Plugin Manager.
|
||||
pub fn window(app: &mut MaterialCraftApp, ctx: &egui::Context) {
|
||||
if !app.ui.windows.plugin_manager {
|
||||
return;
|
||||
}
|
||||
app.plugins.ensure();
|
||||
let mut open = true;
|
||||
let mut toggle: Option<(String, bool)> = None;
|
||||
let mut action: Option<&'static str> = None;
|
||||
crate::windows::modal(ctx, "plugin-manager", tr("Plugin Manager"), &mut open, vec2(640.0, 400.0), |ui| {
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(RichText::new(icon::MAGNIFYING_GLASS).color(tk.text_dim));
|
||||
ui.add(egui::TextEdit::singleline(&mut app.plugins.filter).hint_text(tr("Filter")).desired_width(220.0));
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if ui.button(tr("Refresh")).clicked() {
|
||||
action = Some("refresh");
|
||||
}
|
||||
if ui.button(tr("Install...")).clicked() {
|
||||
action = Some("install");
|
||||
}
|
||||
if ui.button(tr("Browse...")).on_hover_text(tr("Open the plugins folder")).clicked() {
|
||||
action = Some("browse");
|
||||
}
|
||||
});
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
let filter = app.plugins.filter.to_ascii_lowercase();
|
||||
let shown: Vec<Plugin> = app
|
||||
.plugins
|
||||
.list
|
||||
.iter()
|
||||
.filter(|p| filter.is_empty() || p.name.to_ascii_lowercase().contains(&filter) || p.path.to_ascii_lowercase().contains(&filter))
|
||||
.cloned()
|
||||
.collect();
|
||||
egui::ScrollArea::vertical().max_height(270.0).auto_shrink([false, false]).show(ui, |ui| {
|
||||
egui::Grid::new("plugins-grid").num_columns(5).striped(true).spacing([12.0, 4.0]).show(ui, |ui| {
|
||||
ui.label(RichText::new(tr("Loaded")).strong());
|
||||
ui.label(RichText::new(tr("Plugin")).strong());
|
||||
ui.label(RichText::new(tr("Version")).strong());
|
||||
ui.label(RichText::new(tr("Graphs")).strong());
|
||||
ui.label(RichText::new(tr("Location")).strong());
|
||||
ui.end_row();
|
||||
for p in &shown {
|
||||
let mut on = app.plugin_loaded(&p.path);
|
||||
let usable = p.error.is_none();
|
||||
if ui.add_enabled(usable, egui::Checkbox::without_text(&mut on)).changed() {
|
||||
toggle = Some((p.path.clone(), on));
|
||||
}
|
||||
let name = ui.label(&p.name);
|
||||
if !p.description.is_empty() || !p.author.is_empty() {
|
||||
name.on_hover_text(format!("{}\n{}", p.description, p.author));
|
||||
}
|
||||
ui.label(if p.version.is_empty() { "—".to_string() } else { p.version.clone() });
|
||||
match &p.error {
|
||||
Some(e) => {
|
||||
ui.label(RichText::new(format!("{} {}", icon::WARNING, tr("unreadable"))).color(tk.danger)).on_hover_text(e);
|
||||
}
|
||||
None => {
|
||||
let n = p.graphs().count();
|
||||
ui.label(n.to_string()).on_hover_text(p.graphs().map(|(_, g)| g).collect::<Vec<_>>().join("\n"));
|
||||
}
|
||||
}
|
||||
ui.label(RichText::new(&p.path).color(tk.text_dim).small());
|
||||
ui.end_row();
|
||||
}
|
||||
});
|
||||
if shown.is_empty() {
|
||||
ui.add_space(8.0);
|
||||
ui.label(RichText::new(format!("{} {}", tr("No plugins. Drop package files into"), folder().display())).color(tk.text_dim));
|
||||
}
|
||||
});
|
||||
ui.add_space(6.0);
|
||||
ui.label(
|
||||
RichText::new(tr("Loaded plugins add their graphs to the library (Plugins category); adding one copies the graph into your package."))
|
||||
.small()
|
||||
.color(tk.text_dim),
|
||||
);
|
||||
});
|
||||
if let Some((path, on)) = toggle {
|
||||
app.ui.plugins_loaded.retain(|p| *p != path);
|
||||
if on {
|
||||
app.ui.plugins_loaded.push(path);
|
||||
}
|
||||
}
|
||||
match action {
|
||||
Some("refresh") => app.plugins.refresh(),
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
Some("install") => install(app),
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
Some("browse") => browse(app),
|
||||
_ => {}
|
||||
}
|
||||
if !open {
|
||||
app.ui.windows.plugin_manager = false;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_folder_without_packages_reports_an_error_not_a_panic() {
|
||||
let dir = std::env::temp_dir().join(format!("mc-plugin-test-{}", std::process::id()));
|
||||
let _ = std::fs::create_dir_all(&dir);
|
||||
let _ = std::fs::write(dir.join("plugin.json"), "{\"name\": \"Test\", \"version\": \"1.0\"}");
|
||||
let p = read_plugin(&dir);
|
||||
assert_eq!(p.name, "Test");
|
||||
assert_eq!(p.version, "1.0");
|
||||
assert!(p.error.is_some());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_garbage_manifest_keeps_the_folder_name() {
|
||||
let dir = std::env::temp_dir().join(format!("mc-plugin-garbage-{}", std::process::id()));
|
||||
let _ = std::fs::create_dir_all(&dir);
|
||||
let _ = std::fs::write(dir.join("plugin.json"), "{not json");
|
||||
let _ = std::fs::write(dir.join("broken.sbs"), "<xml");
|
||||
let p = read_plugin(&dir);
|
||||
assert_eq!(Some(p.name.as_str()), dir.file_name().and_then(|s| s.to_str()));
|
||||
assert!(p.error.is_some(), "a broken package is reported");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,522 @@
|
||||
//! Edit ▸ Preferences: a tabbed window (General, Projects, Graph, 3D View, Bakers, Library,
|
||||
//! Shortcuts) edited on a copy of the preferences; OK and Apply push the copy into the app.
|
||||
|
||||
use egui::{RichText, Ui, vec2};
|
||||
use egui_phosphor::regular as icon;
|
||||
|
||||
use crate::MaterialCraftApp;
|
||||
use crate::i18n::tr;
|
||||
use crate::state::Prefs;
|
||||
use crate::theme::{Accent, Brightness, Tokens};
|
||||
|
||||
/// The tabs, in order.
|
||||
const TABS: [&str; 7] = ["General", "Projects", "Graph", "3D View", "Bakers", "Library", "Shortcuts"];
|
||||
|
||||
/// The window's working copy and tab (kept while it is open).
|
||||
#[derive(Default)]
|
||||
pub struct PrefsEditor {
|
||||
draft: Option<Prefs>,
|
||||
/// The preferences when the window opened (Cancel restores the live-previewed ones).
|
||||
original: Option<Prefs>,
|
||||
tab: usize,
|
||||
shortcut_search: String,
|
||||
shortcut_key_search: String,
|
||||
/// Node shortcuts being edited: def id → shortcut text.
|
||||
node_shortcuts: Vec<(String, String)>,
|
||||
/// The shortcut field waiting for a key press.
|
||||
capturing: Option<String>,
|
||||
}
|
||||
|
||||
fn heading(ui: &mut Ui, text: &str) {
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
ui.add_space(8.0);
|
||||
ui.label(RichText::new(text.to_uppercase()).size(12.5).color(tk.text_strong));
|
||||
ui.add_space(2.0);
|
||||
}
|
||||
|
||||
fn sub_heading(ui: &mut Ui, text: &str) {
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
ui.add_space(4.0);
|
||||
ui.label(RichText::new(text.to_uppercase()).size(11.0).color(tk.text_dim));
|
||||
}
|
||||
|
||||
/// A numeric field with a unit: "[ 10 ] Files".
|
||||
fn number(ui: &mut Ui, label: &str, value: &mut u32, range: std::ops::RangeInclusive<u32>, unit: &str) -> bool {
|
||||
let mut changed = false;
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(label);
|
||||
let r = ui.add(egui::DragValue::new(value).range(range).speed(1.0));
|
||||
crate::widgets::name(&r, egui::Role::SpinButton, label);
|
||||
changed = r.changed();
|
||||
ui.label(unit);
|
||||
});
|
||||
changed
|
||||
}
|
||||
|
||||
/// A folder field with reset, browse and "use" buttons.
|
||||
fn folder_field(ui: &mut Ui, label: &str, value: &mut String, default_hint: &str) {
|
||||
ui.label(label);
|
||||
ui.horizontal(|ui| {
|
||||
let r = ui.add(egui::TextEdit::singleline(value).hint_text(default_hint).desired_width(ui.available_width() - 60.0));
|
||||
crate::widgets::name(&r, egui::Role::TextInput, label);
|
||||
if crate::widgets::icon_button(ui, icon::ARROW_COUNTER_CLOCKWISE, tr("Reset to the default"), false, 20.0).clicked() {
|
||||
value.clear();
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if crate::widgets::icon_button(ui, icon::DOTS_THREE, tr("Browse..."), false, 20.0).clicked()
|
||||
&& let Some(p) = rfd::FileDialog::new().pick_folder()
|
||||
{
|
||||
*value = p.display().to_string();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
pub fn show(app: &mut MaterialCraftApp, ctx: &egui::Context) {
|
||||
if app.prefs_editor.draft.is_none() {
|
||||
app.prefs_editor.draft = Some(app.ui.prefs.clone());
|
||||
app.prefs_editor.original = Some(app.ui.prefs.clone());
|
||||
app.prefs_editor.node_shortcuts = app.ui.node_shortcuts.clone();
|
||||
}
|
||||
let mut open = true;
|
||||
let mut action: Option<&str> = None;
|
||||
egui::Window::new(tr("Preferences"))
|
||||
.id(egui::Id::unique("preferences"))
|
||||
.open(&mut open)
|
||||
.collapsible(false)
|
||||
.resizable(true)
|
||||
.default_size(vec2(760.0, 560.0))
|
||||
.show(ctx, |ui| {
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
let total = ui.available_height() - 36.0;
|
||||
ui.horizontal_top(|ui| {
|
||||
// Tabs down the left.
|
||||
ui.allocate_ui_with_layout(vec2(150.0, total), egui::Layout::top_down(egui::Align::Min), |ui| {
|
||||
ui.painter().rect_filled(ui.max_rect(), 0.0, tk.panel);
|
||||
ui.add_space(6.0);
|
||||
for (i, tab) in TABS.iter().enumerate() {
|
||||
let on = app.prefs_editor.tab == i;
|
||||
let (r, resp) = ui.allocate_exact_size(vec2(146.0, 32.0), egui::Sense::click());
|
||||
crate::widgets::name(&resp, egui::Role::Tab, tab);
|
||||
if on {
|
||||
ui.painter().rect_filled(r, 3.0, tk.row_selected);
|
||||
} else if resp.hovered() {
|
||||
ui.painter().rect_filled(r, 3.0, tk.row_hover);
|
||||
}
|
||||
ui.painter().text(
|
||||
r.left_center() + vec2(10.0, 0.0),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
tr(tab).to_uppercase(),
|
||||
egui::FontId::proportional(13.0),
|
||||
if on { tk.text_strong } else { tk.text },
|
||||
);
|
||||
if resp.clicked() {
|
||||
app.prefs_editor.tab = i;
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.separator();
|
||||
ui.allocate_ui_with_layout(vec2(ui.available_width(), total), egui::Layout::top_down(egui::Align::Min), |ui| {
|
||||
egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {
|
||||
ui.set_width(ui.available_width() - 8.0);
|
||||
let tab = app.prefs_editor.tab;
|
||||
match tab {
|
||||
0 => general(app, ui),
|
||||
1 => projects(app, ui),
|
||||
2 => graph(app, ui),
|
||||
3 => view3d(app, ui),
|
||||
4 => bakers(app, ui),
|
||||
5 => library(app, ui),
|
||||
_ => shortcuts(app, ui),
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
ui.separator();
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if ui.add(egui::Button::new(tr("APPLY")).min_size(vec2(90.0, 24.0))).clicked() {
|
||||
action = Some("apply");
|
||||
}
|
||||
if ui.add(egui::Button::new(tr("CANCEL")).min_size(vec2(90.0, 24.0))).clicked() {
|
||||
action = Some("cancel");
|
||||
}
|
||||
if ui.add(crate::widgets::primary_button(ui, tr("OK")).min_size(vec2(90.0, 24.0))).clicked() {
|
||||
action = Some("ok");
|
||||
}
|
||||
});
|
||||
});
|
||||
// Appearance previews live while the window is open (Cancel puts it back).
|
||||
if let Some(d) = &app.prefs_editor.draft {
|
||||
app.ui.prefs.ui_scale = d.ui_scale;
|
||||
app.ui.prefs.brightness = d.brightness;
|
||||
app.ui.prefs.accent = d.accent;
|
||||
}
|
||||
match action {
|
||||
Some("apply") => apply(app),
|
||||
Some("ok") => {
|
||||
apply(app);
|
||||
open = false;
|
||||
}
|
||||
Some("cancel") => {
|
||||
if let Some(o) = app.prefs_editor.original.take() {
|
||||
app.ui.prefs.ui_scale = o.ui_scale;
|
||||
app.ui.prefs.brightness = o.brightness;
|
||||
app.ui.prefs.accent = o.accent;
|
||||
}
|
||||
open = false;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if !open {
|
||||
app.ui.windows.preferences = false;
|
||||
app.prefs_editor.draft = None;
|
||||
app.prefs_editor.original = None;
|
||||
app.prefs_editor.capturing = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// Push the draft into the live preferences.
|
||||
fn apply(app: &mut MaterialCraftApp) {
|
||||
let Some(draft) = app.prefs_editor.draft.clone() else { return };
|
||||
app.ui.prefs = draft;
|
||||
app.ui.node_shortcuts = app.prefs_editor.node_shortcuts.clone();
|
||||
crate::i18n::set_language(&app.ui.prefs.language);
|
||||
app.apply_prefs();
|
||||
app.toast(tr("Preferences applied"), false);
|
||||
}
|
||||
|
||||
fn draft(app: &mut MaterialCraftApp) -> &mut Prefs {
|
||||
app.prefs_editor.draft.get_or_insert_with(Prefs::default)
|
||||
}
|
||||
|
||||
fn general(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
let cache_used = app.session.cache.lock().map(|c| c.bytes() >> 20).unwrap_or(0);
|
||||
let cache_cap = app.session.cache.lock().map(|c| c.cap() >> 20).unwrap_or(0);
|
||||
let cores = std::thread::available_parallelism().map_or(1, |n| n.get());
|
||||
let p = draft(app);
|
||||
heading(ui, tr("Recent documents"));
|
||||
number(ui, tr("Recent documents list contains:"), &mut p.recent_count, 1..=50, tr("Files"));
|
||||
heading(ui, tr("History"));
|
||||
number(ui, tr("History stack size:"), &mut p.history_size, 1..=10_000, tr("States"));
|
||||
heading(ui, tr("Language"));
|
||||
ui.label(tr("Choose the language of the application:"));
|
||||
crate::widgets::combo(ui, "", crate::i18n::LANGUAGES.iter().find(|l| l.code == p.language).map_or("English", |l| l.name), |ui| {
|
||||
for l in crate::i18n::LANGUAGES.iter().filter(|l| l.code == "en") {
|
||||
if ui.selectable_label(p.language == l.code, l.name).clicked() {
|
||||
p.language = l.code.to_owned();
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.label(RichText::new(tr("More languages arrive in a later version.")).small().color(tk.text_dim));
|
||||
heading(ui, tr("Appearance"));
|
||||
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);
|
||||
ui.checkbox(&mut p.show_home, tr("Show the home screen at start"));
|
||||
heading(ui, tr("Views"));
|
||||
ui.checkbox(&mut p.invert_zoom, tr("Invert zoom in views"));
|
||||
heading(ui, tr("Paths"));
|
||||
ui.label(tr("Save/Export Path:"));
|
||||
let modes = [("last", "Last path"), ("package", "The package's folder"), ("custom", "A fixed folder")];
|
||||
let cur = modes.iter().find(|(id, _)| *id == p.save_path_mode).map_or("Last path", |(_, l)| l);
|
||||
crate::widgets::combo(ui, "", tr(cur), |ui| {
|
||||
for (id, label) in modes {
|
||||
if ui.selectable_label(p.save_path_mode == id, tr(label)).clicked() {
|
||||
p.save_path_mode = id.into();
|
||||
}
|
||||
}
|
||||
});
|
||||
if p.save_path_mode == "custom" {
|
||||
folder_field(ui, tr("Fixed folder:"), &mut p.save_path, "");
|
||||
}
|
||||
folder_field(ui, tr("Temporary folder (auto backups):"), &mut p.temp_dir, &crate::user_dir("autosave").display().to_string());
|
||||
heading(ui, tr("Memory"));
|
||||
sub_heading(ui, tr("Image cache"));
|
||||
ui.label(format!("{}: {cache_used} MB {} {cache_cap} MB", tr("Current memory used"), tr("of")));
|
||||
ui.label(tr("Memory Budget:"));
|
||||
ui.horizontal(|ui| {
|
||||
let auto = p.cache_mb == 0;
|
||||
let r = egui::ComboBox::from_id_salt("cache-mode").selected_text(if auto { tr("Automatic") } else { tr("Fixed") }).show_ui(ui, |ui| {
|
||||
if ui.selectable_label(auto, tr("Automatic")).clicked() {
|
||||
p.cache_mb = 0;
|
||||
}
|
||||
if ui.selectable_label(!auto, tr("Fixed")).clicked() && auto {
|
||||
p.cache_mb = 1024;
|
||||
}
|
||||
});
|
||||
crate::widgets::name(&r.response, egui::Role::ComboBox, "Memory budget");
|
||||
if !auto {
|
||||
let r = ui.add(egui::DragValue::new(&mut p.cache_mb).range(16..=65_536).speed(16.0).suffix(" MB"));
|
||||
crate::widgets::name(&r, egui::Role::SpinButton, "Cache MB");
|
||||
} else {
|
||||
ui.label(RichText::new("1024 MB").color(tk.text_dim));
|
||||
}
|
||||
});
|
||||
sub_heading(ui, tr("Job scheduler"));
|
||||
ui.label(format!("{}: {cores}", tr("Cores on this machine")));
|
||||
let mut threads = p.cook_threads as u32;
|
||||
if number(ui, tr("Cook threads (0 = every core):"), &mut threads, 0..=256, tr("threads")) {
|
||||
p.cook_threads = threads as usize;
|
||||
}
|
||||
heading(ui, tr("Auto backup"));
|
||||
let mut backup_on = p.autosave_minutes > 0;
|
||||
if ui.checkbox(&mut backup_on, tr("Auto backup")).changed() {
|
||||
p.autosave_minutes = if backup_on { 5 } else { 0 };
|
||||
}
|
||||
ui.add_enabled_ui(backup_on, |ui| {
|
||||
let mut m = p.autosave_minutes.max(1);
|
||||
if number(ui, tr("Auto backup every:"), &mut m, 1..=120, tr("minutes")) {
|
||||
p.autosave_minutes = m;
|
||||
}
|
||||
number(ui, tr("Keep up to:"), &mut p.backup_versions, 1..=50, tr("versions"));
|
||||
});
|
||||
ui.label(
|
||||
RichText::new(tr("Backups are written to the temporary folder above; open one with File ▸ Open and save it over the original."))
|
||||
.small()
|
||||
.color(tk.text_dim),
|
||||
);
|
||||
heading(ui, tr("Cooker"));
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(tr("Cooking size limit:"));
|
||||
let mut v = (31 - p.cook_limit.clamp(256, 8192).leading_zeros()) as f32;
|
||||
if ui.add(egui::Slider::new(&mut v, 8.0..=13.0).show_value(false).step_by(1.0)).changed() {
|
||||
p.cook_limit = 1 << (v as u32);
|
||||
}
|
||||
ui.label(format!("{} {}", p.cook_limit, tr("pixels")));
|
||||
});
|
||||
ui.label(
|
||||
RichText::new(tr("Caps every cook, exports included. Preview size while editing is set in the 3D view's Display menu.")).small().color(tk.text_dim),
|
||||
);
|
||||
}
|
||||
|
||||
fn projects(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
heading(ui, tr("Configuration"));
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(tr("Preferences file:"));
|
||||
ui.label(RichText::new(tr("kept by the app in its settings store")).color(tk.text_dim));
|
||||
});
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(tr("Plugins folder:"));
|
||||
ui.label(RichText::new(crate::plugins::folder().display().to_string()).color(tk.text_dim));
|
||||
if ui.small_button(tr("Plugin Manager...")).clicked() {
|
||||
app.ui.windows.plugin_manager = true;
|
||||
}
|
||||
});
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(tr("Backups folder:"));
|
||||
let dir = if app.ui.prefs.temp_dir.is_empty() { crate::user_dir("autosave").display().to_string() } else { app.ui.prefs.temp_dir.clone() };
|
||||
ui.label(RichText::new(dir).color(tk.text_dim));
|
||||
});
|
||||
heading(ui, tr("Project"));
|
||||
sub_heading(ui, tr("3D View"));
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(tr("Default State File:"));
|
||||
let has = app.ui.view3d_default.is_some();
|
||||
ui.label(RichText::new(if has { tr("saved (Scene ▸ Save Current State As Default)") } else { tr("none: the built-in state") }).color(tk.text_dim));
|
||||
if has && ui.small_button(tr("Clear")).clicked() {
|
||||
app.ui.view3d_default = None;
|
||||
}
|
||||
if ui.small_button(tr("Save the current 3D view as the default")).clicked() {
|
||||
app.ui.view3d_default = app.run("view.3d.state", serde_json::json!({}));
|
||||
}
|
||||
});
|
||||
let p = draft(app);
|
||||
ui.label(tr("Default Lighting State (if not set by Default State File):"));
|
||||
ui.indent("lights", |ui| {
|
||||
ui.checkbox(&mut p.default_lights[0], tr("Ambient Light"));
|
||||
ui.checkbox(&mut p.default_lights[1], tr("Point Light 1"));
|
||||
ui.checkbox(&mut p.default_lights[2], tr("Point Light 2"));
|
||||
});
|
||||
sub_heading(ui, tr("Library"));
|
||||
ui.checkbox(&mut p.library_list, tr("Show the library as a list"));
|
||||
crate::widgets::slider(ui, tr("Library tile size"), &mut p.library_tile, 56.0..=160.0, 0);
|
||||
sub_heading(ui, tr("General"));
|
||||
crate::widgets::combo(
|
||||
ui,
|
||||
tr("Preview size while editing"),
|
||||
if p.preview_size == 0 { tr("Full size").to_string() } else { format!("{} px", p.preview_size) },
|
||||
|ui| {
|
||||
for s in [256u32, 512, 1024, 2048, 4096, 0] {
|
||||
let label = if s == 0 { tr("Full size").to_string() } else { format!("{s} px") };
|
||||
ui.selectable_value(&mut p.preview_size, s, label);
|
||||
}
|
||||
},
|
||||
);
|
||||
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);
|
||||
}
|
||||
|
||||
fn graph(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
let p = draft(app);
|
||||
heading(ui, tr("Common"));
|
||||
ui.checkbox(&mut p.tab_key_menu, tr("Tab key shows node menu"));
|
||||
ui.checkbox(&mut p.drag_create, tr("Enable creation of nodes by click-dragging connectors"));
|
||||
ui.checkbox(&mut p.view_3d_on_open, tr("View outputs in 3D view when opening a graph"));
|
||||
heading(ui, tr("Material graph"));
|
||||
ui.checkbox(&mut p.thumbnails, tr("Automatically compute all nodes thumbnails when opening a graph"));
|
||||
ui.checkbox(&mut p.view_2d_on_open, tr("View output in 2D view when opening a graph"));
|
||||
ui.checkbox(&mut p.auto_display_new_node, tr("Automatically display newly created node"));
|
||||
ui.checkbox(&mut p.auto_convert, tr("Automatically insert color/grayscale conversion node"));
|
||||
heading(ui, tr("Graph toolbar"));
|
||||
ui.checkbox(&mut p.show_grid, tr("Show the grid"));
|
||||
ui.checkbox(&mut p.snap_grid, tr("Snap nodes to the grid"));
|
||||
ui.checkbox(&mut p.straight_wires, tr("Straight wires"));
|
||||
ui.checkbox(&mut p.node_timings, tr("Show cook times on nodes"));
|
||||
}
|
||||
|
||||
fn view3d(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
let p = draft(app);
|
||||
heading(ui, tr("Misc"));
|
||||
ui.checkbox(&mut p.env_hidden, tr("Environment hidden by default"));
|
||||
crate::widgets::combo(
|
||||
ui,
|
||||
tr("Viewport Scaling"),
|
||||
if p.viewport_scale <= 0.0 { tr("Auto").to_string() } else { format!("{:.0} %", p.viewport_scale * 100.0) },
|
||||
|ui| {
|
||||
if ui.selectable_label(p.viewport_scale <= 0.0, tr("Auto")).clicked() {
|
||||
p.viewport_scale = 0.0;
|
||||
}
|
||||
for s in [0.5f32, 0.75, 1.0, 1.5, 2.0] {
|
||||
if ui.selectable_label((p.viewport_scale - s).abs() < 1e-3, format!("{:.0} %", s * 100.0)).clicked() {
|
||||
p.viewport_scale = s;
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
heading(ui, tr("Renderer"));
|
||||
sub_heading(ui, tr("Shading"));
|
||||
let labels = [(1u32, "Low (1 spp)"), (2, "Medium (4 spp)"), (3, "High (9 spp)"), (4, "Very high (16 spp)")];
|
||||
let cur = labels.iter().find(|(n, _)| *n == p.sample_count).map_or("Medium (4 spp)", |(_, l)| l);
|
||||
crate::widgets::combo(ui, tr("Sample Count"), tr(cur), |ui| {
|
||||
for (n, label) in labels {
|
||||
if ui.selectable_label(p.sample_count == n, tr(label)).clicked() {
|
||||
p.sample_count = n;
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.label(
|
||||
RichText::new(tr("Samples per pixel of the resting frame; the renderer settings of a session can override it."))
|
||||
.small()
|
||||
.color(Tokens::get(ui.ctx()).text_dim),
|
||||
);
|
||||
}
|
||||
|
||||
fn bakers(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
let p = draft(app);
|
||||
heading(ui, tr("Bakers"));
|
||||
let mut threads = p.bake_threads;
|
||||
if number(ui, tr("Baking threads (0 = every core):"), &mut threads, 0..=256, tr("threads")) {
|
||||
p.bake_threads = threads;
|
||||
}
|
||||
ui.label(RichText::new(tr("Mesh maps bake on the CPU ray tracer; GPU ray tracing arrives with the GPU renderer.")).small().color(tk.text_dim));
|
||||
}
|
||||
|
||||
fn library(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
heading(ui, tr("Library"));
|
||||
if ui.add(egui::Button::new(tr("Rebuild Thumbnails")).min_size(vec2(260.0, 24.0))).clicked() {
|
||||
app.thumbs.rebuild_library();
|
||||
app.toast(tr("Library thumbnails are being rebuilt"), false);
|
||||
}
|
||||
ui.add_space(6.0);
|
||||
if ui.add(egui::Button::new(tr("Clear the cooked image cache")).min_size(vec2(260.0, 24.0))).clicked() {
|
||||
if let Ok(mut c) = app.session.cache.lock() {
|
||||
c.clear();
|
||||
}
|
||||
app.session.dirty = true;
|
||||
}
|
||||
}
|
||||
|
||||
fn shortcuts(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
ui.horizontal(|ui| {
|
||||
heading(ui, tr("Node creation shortcuts"));
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if crate::widgets::icon_button(ui, icon::ARROWS_CLOCKWISE, tr("Clear every shortcut"), false, 22.0).clicked() {
|
||||
app.prefs_editor.node_shortcuts.clear();
|
||||
}
|
||||
});
|
||||
});
|
||||
ui.horizontal(|ui| {
|
||||
ui.add(egui::TextEdit::singleline(&mut app.prefs_editor.shortcut_search).hint_text(tr("Search")).desired_width(220.0));
|
||||
ui.add(egui::TextEdit::singleline(&mut app.prefs_editor.shortcut_key_search).hint_text(tr("Search by shortcut")).desired_width(160.0));
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
let n = app.prefs_editor.node_shortcuts.len();
|
||||
ui.label(RichText::new(format!("{n} {}", tr("assigned"))).color(tk.text_dim));
|
||||
});
|
||||
});
|
||||
ui.label(RichText::new(tr("Click a field and press the keys (Escape clears). The node is added next to the selection.")).small().color(tk.text_dim));
|
||||
let search = app.prefs_editor.shortcut_search.to_ascii_lowercase();
|
||||
let key_search = app.prefs_editor.shortcut_key_search.to_ascii_lowercase();
|
||||
// Capture a chord for the field that waits for one.
|
||||
if let Some(def) = app.prefs_editor.capturing.clone() {
|
||||
let pressed = ui.input(|i| {
|
||||
if i.key_pressed(egui::Key::Escape) {
|
||||
return Some(String::new());
|
||||
}
|
||||
i.events.iter().find_map(|e| match e {
|
||||
egui::Event::Key { key, pressed: true, modifiers, .. } if !matches!(key, egui::Key::Escape) => {
|
||||
let mut parts = Vec::new();
|
||||
if modifiers.ctrl || modifiers.command {
|
||||
parts.push("Ctrl");
|
||||
}
|
||||
if modifiers.shift {
|
||||
parts.push("Shift");
|
||||
}
|
||||
if modifiers.alt {
|
||||
parts.push("Alt");
|
||||
}
|
||||
let name = key.name();
|
||||
parts.push(name);
|
||||
Some(parts.join("+"))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
});
|
||||
if let Some(chord) = pressed {
|
||||
app.prefs_editor.node_shortcuts.retain(|(d, _)| *d != def);
|
||||
if !chord.is_empty() {
|
||||
// One chord per node: the previous owner loses it.
|
||||
app.prefs_editor.node_shortcuts.retain(|(_, c)| *c != chord);
|
||||
app.prefs_editor.node_shortcuts.push((def, chord));
|
||||
}
|
||||
app.prefs_editor.capturing = None;
|
||||
}
|
||||
}
|
||||
egui::Grid::new("node-shortcuts").num_columns(2).striped(true).spacing([16.0, 4.0]).show(ui, |ui| {
|
||||
for d in materialcraft_engine::nodes::catalog() {
|
||||
if d.id == "graph_instance" {
|
||||
continue;
|
||||
}
|
||||
let current = app.prefs_editor.node_shortcuts.iter().find(|(def, _)| *def == d.id).map(|(_, c)| c.clone()).unwrap_or_default();
|
||||
if !search.is_empty() && !d.label.to_ascii_lowercase().contains(&search) && !d.id.contains(&search) {
|
||||
continue;
|
||||
}
|
||||
if !key_search.is_empty() && !current.to_ascii_lowercase().contains(&key_search) {
|
||||
continue;
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
let (r, _) = ui.allocate_exact_size(vec2(14.0, 14.0), egui::Sense::hover());
|
||||
ui.painter().rect_filled(r, 3.0, crate::graph_view::header_color(d.id));
|
||||
ui.label(d.label);
|
||||
});
|
||||
let capturing = app.prefs_editor.capturing.as_deref() == Some(d.id);
|
||||
let text = if capturing { tr("Press keys...").to_string() } else { current.clone() };
|
||||
let b = ui.add(egui::Button::new(if text.is_empty() { " ".to_string() } else { text }).min_size(vec2(200.0, 20.0)).selected(capturing));
|
||||
crate::widgets::name(&b, egui::Role::TextInput, d.label);
|
||||
if b.clicked() {
|
||||
app.prefs_editor.capturing = Some(d.id.to_string());
|
||||
}
|
||||
ui.end_row();
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -14,6 +14,9 @@ use crate::theme::Tokens;
|
||||
|
||||
/// The panel title: "<node> - Properties" or "<graph> - Properties".
|
||||
pub fn title(app: &MaterialCraftApp) -> String {
|
||||
if let Some((page, _)) = &app.props3d {
|
||||
return crate::view3d_props::title(*page);
|
||||
}
|
||||
let sel = app.session.selection.last().and_then(|id| app.session.graph().ok()?.node(*id).ok().map(crate::graph_view::node_label));
|
||||
let name = sel.or_else(|| app.session.graph().ok().map(|g| g.name.clone())).unwrap_or_default();
|
||||
format!("{name} - {}", tr("Properties"))
|
||||
@@ -40,6 +43,18 @@ fn section(ui: &mut Ui, id: &str, title: &str, body: impl FnOnce(&mut Ui)) {
|
||||
}
|
||||
|
||||
pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
// A 3D view page stays until the user selects something else in the graph.
|
||||
if let Some((page, sel)) = app.props3d.clone() {
|
||||
if sel != app.session.selection {
|
||||
app.props3d = None;
|
||||
} else {
|
||||
egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {
|
||||
ui.set_width(ui.available_width());
|
||||
ui.push_id(("props3d", page.title()), |ui| crate::view3d_props::show(app, ui, page));
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {
|
||||
ui.set_width(ui.available_width());
|
||||
let node = app.session.selection.last().and_then(|id| app.session.graph().ok()?.node(*id).ok().cloned());
|
||||
|
||||
+119
-2
@@ -24,10 +24,63 @@ pub struct Prefs {
|
||||
pub thumbnails: bool,
|
||||
/// Library tiles: large icons or a list.
|
||||
pub library_list: bool,
|
||||
/// Library tile size (icons view), 56..160 px.
|
||||
pub library_tile: f32,
|
||||
/// Open the home screen when the app starts.
|
||||
pub show_home: bool,
|
||||
/// 3D view camera: pan limit and speed.
|
||||
pub camera: CameraPrefs,
|
||||
/// Show the main toolbar under the menu bar (Windows ▸ Main toolbar).
|
||||
pub show_main_toolbar: bool,
|
||||
/// Worker threads the cook may use (Tools ▸ Switch engine; 0 = every core).
|
||||
pub cook_threads: usize,
|
||||
/// Graph toolbar: show each node's cook time.
|
||||
pub node_timings: bool,
|
||||
/// Graph toolbar: straight wires instead of curves.
|
||||
pub straight_wires: bool,
|
||||
/// Graph toolbar: dropped nodes land on the grid.
|
||||
pub snap_grid: bool,
|
||||
/// Graph toolbar: draw the background grid.
|
||||
pub show_grid: bool,
|
||||
/// General: how many recent packages the File menu keeps.
|
||||
pub recent_count: u32,
|
||||
/// General: undo steps kept.
|
||||
pub history_size: u32,
|
||||
/// General: wheel zooms the other way in every view.
|
||||
pub invert_zoom: bool,
|
||||
/// General: where file dialogs open: `last`, `package` or `custom` (`save_path`).
|
||||
pub save_path_mode: String,
|
||||
pub save_path: String,
|
||||
/// General: the auto-backup folder (empty = Documents/MaterialCraft/autosave).
|
||||
pub temp_dir: String,
|
||||
/// General: the cooked image cache's size in MB (0 = automatic).
|
||||
pub cache_mb: u32,
|
||||
/// General: auto-backup versions kept per package.
|
||||
pub backup_versions: u32,
|
||||
/// General: cap on every cook's larger side in px (0 = none).
|
||||
pub cook_limit: u32,
|
||||
/// Projects: lights on in a new session when no default 3D state is saved (ambient, point 1, point 2).
|
||||
pub default_lights: [bool; 3],
|
||||
/// Graph: Tab opens the node search.
|
||||
pub tab_key_menu: bool,
|
||||
/// Graph: dragging a wire into empty space opens the node search.
|
||||
pub drag_create: bool,
|
||||
/// Graph: show the 3D view when a graph opens.
|
||||
pub view_3d_on_open: bool,
|
||||
/// Graph: show the graph's output in the 2D view when it opens.
|
||||
pub view_2d_on_open: bool,
|
||||
/// Graph: show a newly added node in the 2D view.
|
||||
pub auto_display_new_node: bool,
|
||||
/// Graph: insert a conversion node when a color wire meets a grayscale input (or the reverse).
|
||||
pub auto_convert: bool,
|
||||
/// 3D view: the environment is hidden behind the mesh by default.
|
||||
pub env_hidden: bool,
|
||||
/// 3D view: default viewport render scale (0 = auto).
|
||||
pub viewport_scale: f32,
|
||||
/// 3D view: default samples per pixel of the resting frame (n × n).
|
||||
pub sample_count: u32,
|
||||
/// Bakers: worker threads (0 = every core).
|
||||
pub bake_threads: u32,
|
||||
}
|
||||
|
||||
impl Default for Prefs {
|
||||
@@ -41,8 +94,35 @@ impl Default for Prefs {
|
||||
autosave_minutes: 5,
|
||||
thumbnails: true,
|
||||
library_list: false,
|
||||
library_tile: 78.0,
|
||||
show_home: true,
|
||||
camera: CameraPrefs::default(),
|
||||
show_main_toolbar: true,
|
||||
cook_threads: 0,
|
||||
node_timings: false,
|
||||
straight_wires: false,
|
||||
snap_grid: false,
|
||||
show_grid: true,
|
||||
recent_count: 12,
|
||||
history_size: 200,
|
||||
invert_zoom: false,
|
||||
save_path_mode: "last".into(),
|
||||
save_path: String::new(),
|
||||
temp_dir: String::new(),
|
||||
cache_mb: 0,
|
||||
backup_versions: 6,
|
||||
cook_limit: 8192,
|
||||
default_lights: [true, false, false],
|
||||
tab_key_menu: true,
|
||||
drag_create: true,
|
||||
view_3d_on_open: true,
|
||||
view_2d_on_open: true,
|
||||
auto_display_new_node: true,
|
||||
auto_convert: false,
|
||||
env_hidden: true,
|
||||
viewport_scale: 0.0,
|
||||
sample_count: 2,
|
||||
bake_threads: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -57,6 +137,10 @@ pub struct Windows {
|
||||
pub preferences: bool,
|
||||
pub shortcuts: bool,
|
||||
pub home: bool,
|
||||
pub plugin_manager: bool,
|
||||
pub switch_engine: bool,
|
||||
/// The Dependency Manager window (Windows menu).
|
||||
pub dependencies: bool,
|
||||
/// The action waiting on the "unsaved changes" dialog (readable over the control channel;
|
||||
/// never restored from a saved layout).
|
||||
#[serde(skip_deserializing)]
|
||||
@@ -126,12 +210,34 @@ pub struct UiState {
|
||||
/// Library: the selected category path ("" = all) and the search text.
|
||||
pub library_category: String,
|
||||
pub library_search: String,
|
||||
/// Library entries starred by the user (node ids, `@graph`, `fn:op`).
|
||||
pub library_favorites: Vec<String>,
|
||||
/// Library tree groups that are folded shut.
|
||||
pub library_collapsed: Vec<String>,
|
||||
/// Recently opened or saved packages, newest first.
|
||||
pub recent: Vec<String>,
|
||||
/// Plugins (file or folder paths in the plugins folder) whose graphs the library offers.
|
||||
pub plugins_loaded: Vec<String>,
|
||||
/// 3D view ▸ Scene ▸ Save Current State As Default: the state new sessions and Reset Scene use.
|
||||
pub view3d_default: Option<serde_json::Value>,
|
||||
/// The folder the last file dialog ended in (Preferences ▸ Save/Export path: Last path).
|
||||
pub last_dir: String,
|
||||
/// Preferences ▸ Shortcuts: node creation shortcuts, def id → shortcut ("Ctrl+Shift+B").
|
||||
pub node_shortcuts: Vec<(String, String)>,
|
||||
/// New graph dialog fields.
|
||||
pub new_graph_template: String,
|
||||
pub new_graph_name: String,
|
||||
pub new_graph_size: u32,
|
||||
/// New graph height when the two sizes are unlinked (0 = same as the width).
|
||||
pub new_graph_height: u32,
|
||||
/// Keep width and height the same in the new graph dialog.
|
||||
pub new_graph_link: bool,
|
||||
/// Template category shown in the new graph dialog (empty = all).
|
||||
pub new_graph_category: String,
|
||||
/// Graph toolbar: the parent size's width and height change together.
|
||||
pub parent_link: bool,
|
||||
/// Graph toolbar: the align buttons also stack the nodes (no gaps).
|
||||
pub stack_align: bool,
|
||||
/// Export dialog fields.
|
||||
pub export_dir: String,
|
||||
pub export_format: String,
|
||||
@@ -154,10 +260,21 @@ impl Default for UiState {
|
||||
image_camera: ImageCamera::default(),
|
||||
library_category: String::new(),
|
||||
library_search: String::new(),
|
||||
library_favorites: Vec::new(),
|
||||
library_collapsed: Vec::new(),
|
||||
recent: Vec::new(),
|
||||
plugins_loaded: Vec::new(),
|
||||
view3d_default: None,
|
||||
last_dir: String::new(),
|
||||
node_shortcuts: Vec::new(),
|
||||
new_graph_template: "pbr".into(),
|
||||
new_graph_name: "New_graph".into(),
|
||||
new_graph_name: "Material_Graph".into(),
|
||||
new_graph_size: 1024,
|
||||
new_graph_height: 0,
|
||||
new_graph_link: true,
|
||||
new_graph_category: String::new(),
|
||||
parent_link: true,
|
||||
stack_align: true,
|
||||
export_dir: String::new(),
|
||||
export_format: "png".into(),
|
||||
export_depth: 0,
|
||||
@@ -173,7 +290,7 @@ impl UiState {
|
||||
pub fn add_recent(&mut self, path: &str) {
|
||||
self.recent.retain(|p| p != path);
|
||||
self.recent.insert(0, path.to_string());
|
||||
self.recent.truncate(12);
|
||||
self.recent.truncate(self.prefs.recent_count.clamp(1, 50) as usize);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -21,11 +21,38 @@ pub struct Thumbs {
|
||||
/// (cook key, port) → texture and the frame it was last used.
|
||||
nodes: HashMap<(u64, usize), (TextureHandle, u64)>,
|
||||
library: HashMap<String, TextureHandle>,
|
||||
/// Environment previews by id (the equirectangular map, tone mapped).
|
||||
environments: HashMap<String, TextureHandle>,
|
||||
library_rx: Option<Receiver<Previews>>,
|
||||
library_started: bool,
|
||||
frame: u64,
|
||||
}
|
||||
|
||||
impl Thumbs {
|
||||
/// A small picture of a 3D view environment (rendered once per id).
|
||||
pub fn environment(&mut self, ctx: &egui::Context, id: &str) -> Option<egui::TextureId> {
|
||||
if let Some(t) = self.environments.get(id) {
|
||||
return Some(t.id());
|
||||
}
|
||||
let env = materialcraft_render::ibl::environment(materialcraft_render::ibl::by_id(id), 256);
|
||||
let (w, h) = (env.width as usize, env.height as usize);
|
||||
let mut rgba = Vec::with_capacity(w * h * 4);
|
||||
for px in &env.data {
|
||||
for c in px {
|
||||
// Exposure down a stop and a gamma: bright skies stay readable.
|
||||
let v = materialcraft_engine::image::linear_to_srgb((c * 0.5).min(1.0));
|
||||
rgba.push((v * 255.0 + 0.5) as u8);
|
||||
}
|
||||
rgba.push(255);
|
||||
}
|
||||
let img = ColorImage::from_rgba_unmultiplied([w, h], &rgba);
|
||||
let t = ctx.load_texture(format!("env-{id}"), img, TextureOptions::LINEAR);
|
||||
let tid = t.id();
|
||||
self.environments.insert(id.to_string(), t);
|
||||
Some(tid)
|
||||
}
|
||||
}
|
||||
|
||||
/// An image as an egui texture image (sRGB display, `side` px).
|
||||
pub fn color_image(img: &Image, side: u32) -> ColorImage {
|
||||
let small = img.resize(side, side, true);
|
||||
@@ -64,6 +91,13 @@ impl Thumbs {
|
||||
}
|
||||
}
|
||||
|
||||
/// Drop the library previews and generate them again (Preferences ▸ Library ▸ Rebuild Thumbnails).
|
||||
pub fn rebuild_library(&mut self) {
|
||||
self.library.clear();
|
||||
self.library_rx = None;
|
||||
self.library_started = false;
|
||||
}
|
||||
|
||||
/// The library preview of node `def` (generated in the background on first use).
|
||||
pub fn library(&mut self, ctx: &egui::Context, def: &str) -> Option<egui::TextureId> {
|
||||
if !self.library_started {
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
//! Tools and Windows menu dialogs: the engine switch, the dependency manager and the log export.
|
||||
|
||||
use egui::{RichText, Ui, vec2};
|
||||
use egui_phosphor::regular as icon;
|
||||
|
||||
use crate::MaterialCraftApp;
|
||||
use crate::i18n::tr;
|
||||
use crate::theme::Tokens;
|
||||
|
||||
/// The engines the cook can run on: worker thread counts (0 = every core).
|
||||
fn engines() -> Vec<(usize, String)> {
|
||||
let cores = std::thread::available_parallelism().map_or(1, |n| n.get());
|
||||
let mut out = vec![(0, format!("{} ({cores} {})", tr("CPU, all cores"), tr("threads")))];
|
||||
if cores > 2 {
|
||||
out.push((cores / 2, format!("{} ({} {})", tr("CPU, half the cores"), cores / 2, tr("threads"))));
|
||||
}
|
||||
out.push((1, tr("CPU, one thread (leaves the machine responsive)").to_string()));
|
||||
out
|
||||
}
|
||||
|
||||
/// The engine's name for the status bar.
|
||||
pub fn engine_label(app: &MaterialCraftApp) -> String {
|
||||
let cores = std::thread::available_parallelism().map_or(1, |n| n.get());
|
||||
let n = if app.cooker.threads == 0 { cores } else { app.cooker.threads.min(cores) };
|
||||
if app.cooker.suspended { format!("CPU ({n} {}, {})", tr("threads"), tr("suspended")) } else { format!("CPU ({n} {})", tr("threads")) }
|
||||
}
|
||||
|
||||
/// Tools ▸ Switch engine (F9): pick how many threads the cook may use.
|
||||
pub fn switch_engine(app: &mut MaterialCraftApp, ctx: &egui::Context) {
|
||||
let mut open = true;
|
||||
let mut chosen: Option<usize> = None;
|
||||
crate::windows::modal(ctx, "switch-engine", tr("Switch engine"), &mut open, vec2(420.0, 200.0), |ui| {
|
||||
ui.label(tr("Every graph computes on the CPU through the content-addressed cache. Choose how much of the machine it may use:"));
|
||||
ui.add_space(6.0);
|
||||
for (threads, label) in engines() {
|
||||
if ui.radio(app.cooker.threads == threads, label).clicked() {
|
||||
chosen = Some(threads);
|
||||
}
|
||||
}
|
||||
ui.add_space(8.0);
|
||||
ui.label(RichText::new(tr("The next compute uses the new setting; a running one finishes first.")).small().color(Tokens::get(ui.ctx()).text_dim));
|
||||
});
|
||||
if let Some(t) = chosen {
|
||||
app.cooker.threads = t;
|
||||
app.ui.prefs.cook_threads = t;
|
||||
app.session.dirty = true;
|
||||
open = false;
|
||||
}
|
||||
if !open {
|
||||
app.ui.windows.switch_engine = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Everything the open package depends on: its bitmap resources (embedded or linked to a file)
|
||||
/// and the graphs its graph instances point at.
|
||||
pub fn dependencies(app: &mut MaterialCraftApp, ctx: &egui::Context) {
|
||||
let mut open = true;
|
||||
let mut relink: Option<usize> = None;
|
||||
let mut reload = false;
|
||||
crate::windows::modal(ctx, "dependencies", tr("Dependency Manager"), &mut open, vec2(620.0, 380.0), |ui| {
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
ui.label(RichText::new(tr("RESOURCES")).small().color(tk.text_dim));
|
||||
if app.session.pkg.resources.is_empty() {
|
||||
ui.label(RichText::new(tr("No bitmap resources: Tools ▸ Import bitmap... embeds one, Link bitmap... keeps it on disk.")).color(tk.text_dim));
|
||||
}
|
||||
egui::Grid::new("deps-resources").num_columns(4).striped(true).spacing([12.0, 4.0]).show(ui, |ui| {
|
||||
ui.label(RichText::new(tr("Name")).strong());
|
||||
ui.label(RichText::new(tr("Source")).strong());
|
||||
ui.label(RichText::new(tr("Size")).strong());
|
||||
ui.label("");
|
||||
ui.end_row();
|
||||
for (i, r) in app.session.pkg.resources.iter().enumerate() {
|
||||
ui.label(&r.name);
|
||||
match &r.link {
|
||||
Some(path) => {
|
||||
let exists = std::path::Path::new(path).exists();
|
||||
let text = RichText::new(format!("{} {path}", icon::LINK));
|
||||
ui.label(if exists { text } else { text.color(tk.danger) }).on_hover_text(if exists {
|
||||
tr("Linked file")
|
||||
} else {
|
||||
tr("Linked file not found")
|
||||
});
|
||||
}
|
||||
None => {
|
||||
ui.label(RichText::new(format!("{} {}", icon::PACKAGE, tr("embedded in the package"))).color(tk.text_dim));
|
||||
}
|
||||
}
|
||||
ui.label(format!("{} KB", r.bytes.as_slice().len() / 1024));
|
||||
ui.horizontal(|ui| {
|
||||
if r.link.is_some() && ui.small_button(tr("Relink...")).clicked() {
|
||||
relink = Some(i);
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
}
|
||||
});
|
||||
ui.add_space(10.0);
|
||||
ui.label(RichText::new(tr("GRAPH INSTANCES")).small().color(tk.text_dim));
|
||||
let mut rows: Vec<(String, String, bool)> = Vec::new();
|
||||
for g in &app.session.pkg.graphs {
|
||||
for n in g.nodes.iter().filter(|n| n.def == "graph_instance") {
|
||||
let target = match n.params.get("graph") {
|
||||
Some(materialcraft_engine::core::Value::Text(t)) => t.clone(),
|
||||
_ => String::new(),
|
||||
};
|
||||
let found = app.session.pkg.graphs.iter().any(|x| x.name == target);
|
||||
rows.push((g.name.clone(), target, found));
|
||||
}
|
||||
}
|
||||
if rows.is_empty() {
|
||||
ui.label(RichText::new(tr("No graph instances: every graph of this package stands on its own.")).color(tk.text_dim));
|
||||
} else {
|
||||
egui::Grid::new("deps-graphs").num_columns(3).striped(true).spacing([12.0, 4.0]).show(ui, |ui| {
|
||||
ui.label(RichText::new(tr("Graph")).strong());
|
||||
ui.label(RichText::new(tr("Uses")).strong());
|
||||
ui.label(RichText::new(tr("State")).strong());
|
||||
ui.end_row();
|
||||
for (from, to, found) in rows {
|
||||
ui.label(from);
|
||||
ui.label(if to.is_empty() { tr("(not set)").to_string() } else { to });
|
||||
if found {
|
||||
ui.label(RichText::new(tr("found")).color(tk.text_dim));
|
||||
} else {
|
||||
ui.label(RichText::new(tr("missing")).color(tk.danger));
|
||||
}
|
||||
ui.end_row();
|
||||
}
|
||||
});
|
||||
}
|
||||
ui.add_space(10.0);
|
||||
ui.horizontal(|ui| {
|
||||
if ui.button(tr("Reload linked files")).clicked() {
|
||||
reload = true;
|
||||
}
|
||||
});
|
||||
});
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(i) = relink
|
||||
&& let Some(p) = rfd::FileDialog::new().add_filter("Images", materialcraft_engine::formats::IMAGE_EXTENSIONS).pick_file()
|
||||
&& let Some(name) = app.session.pkg.resources.get(i).map(|r| r.name.clone())
|
||||
{
|
||||
app.run("file.linkBitmap", serde_json::json!({"path": p.display().to_string(), "name": name}));
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let _ = relink;
|
||||
if reload {
|
||||
crate::menus::invoke(app, ctx, "ui.reloadResources");
|
||||
}
|
||||
if !open {
|
||||
app.ui.windows.dependencies = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Import graph: which graph of the picked package to copy into this one.
|
||||
pub fn import_pick(app: &mut MaterialCraftApp, ctx: &egui::Context) {
|
||||
let Some((path, graphs)) = app.import_pick.clone() else { return };
|
||||
let mut open = true;
|
||||
let mut chosen: Option<String> = None;
|
||||
crate::windows::modal(ctx, "import-graph", tr("Import graph"), &mut open, vec2(420.0, 260.0), |ui| {
|
||||
ui.label(RichText::new(&path).small().color(Tokens::get(ui.ctx()).text_dim));
|
||||
ui.add_space(4.0);
|
||||
egui::ScrollArea::vertical().max_height(180.0).show(ui, |ui| {
|
||||
for g in &graphs {
|
||||
if ui.button(format!("{} {g}", icon::TREE_STRUCTURE)).clicked() {
|
||||
chosen = Some(g.clone());
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
if let Some(g) = chosen {
|
||||
if let Some(r) = app.run("file.importGraph", serde_json::json!({"path": path, "graph": g})) {
|
||||
app.toast(format!("{} {}", tr("Imported graph"), r["name"].as_str().unwrap_or_default()), false);
|
||||
}
|
||||
open = false;
|
||||
}
|
||||
if !open {
|
||||
app.import_pick = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// Help ▸ Export log: the session's log as a text file.
|
||||
pub fn export_log(app: &mut MaterialCraftApp) {
|
||||
let text = app.session.log.join("\n");
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let Some(p) = rfd::FileDialog::new().set_file_name("materialcraft-log.txt").add_filter("Text", &["txt"]).save_file() else { return };
|
||||
match std::fs::write(&p, text) {
|
||||
Ok(()) => app.toast(format!("{} {}", tr("Log saved to"), p.display()), false),
|
||||
Err(e) => app.toast(format!("{}: {e}", tr("Could not save the log")), true),
|
||||
}
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
match crate::web_files::download("materialcraft-log.txt", text.as_bytes()) {
|
||||
Ok(()) => app.toast(tr("Log downloaded"), false),
|
||||
Err(e) => app.toast(format!("{}: {e}", tr("Could not save the log")), true),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A small heading row used by the dialogs (title left, hint right).
|
||||
pub fn heading(ui: &mut Ui, title: &str) {
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
ui.add_space(4.0);
|
||||
ui.label(RichText::new(title).small().strong().color(tk.text_dim));
|
||||
}
|
||||
@@ -48,12 +48,11 @@ pub fn status_bar(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
}
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
let cache = app.session.cache.lock().map(|c| c.bytes()).unwrap_or(0);
|
||||
let threads = std::thread::available_parallelism().map_or(1, |n| n.get());
|
||||
let engine = crate::tool_windows::engine_label(app);
|
||||
let preview = app.session.preview_size.map_or_else(|| tr("full size").to_string(), |p| format!("{p} px"));
|
||||
let text = format!(
|
||||
"{}: CPU ({threads} {}) | {}: {:.0} ms | {}: {preview} | {}: {} MB | {} {}",
|
||||
tr("Engine"),
|
||||
tr("threads"),
|
||||
"{}: {engine} | {}: {:.0} ms | {}: {preview} | {}: {} MB | {} {}",
|
||||
tr("MC Engine"),
|
||||
tr("Last compute"),
|
||||
app.session.cooked.ms,
|
||||
tr("Preview"),
|
||||
|
||||
@@ -13,6 +13,8 @@ use crate::theme::Tokens;
|
||||
#[derive(Default)]
|
||||
pub struct View2dState {
|
||||
tex: Option<(u64, TextureHandle)>,
|
||||
/// Draw the 3D scene's UV layout over the image (3D view ▸ Scene ▸ Display UVs in 2D View).
|
||||
pub show_uvs: bool,
|
||||
/// The last shown image (RGBA8, for `view.screenshot`).
|
||||
pub shown: Option<(u32, u32, Vec<u8>)>,
|
||||
/// Per-channel histograms of `shown` (R, G, B; one channel for gray), keyed like `tex`.
|
||||
@@ -40,6 +42,34 @@ pub(crate) fn resolution_menu(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
response.on_hover_text(tr("Preview size while editing"));
|
||||
}
|
||||
|
||||
/// The 3D scene's UV triangles over the image (the 0..1 tile is `tile`), clipped to `clip`.
|
||||
fn draw_uvs(app: &MaterialCraftApp, p: &egui::Painter, tile: Rect, clip: Rect) {
|
||||
let v = &app.session.view3d;
|
||||
let mesh = match (&*v.scene, &app.session.custom_mesh) {
|
||||
("custom", Some((_, m))) => (**m).clone(),
|
||||
_ => materialcraft_render::builtin_mesh(&v.scene),
|
||||
};
|
||||
const MAX_EDGES: usize = 300_000;
|
||||
let to_screen = |uv: materialcraft_engine::geom::glam::Vec2| pos2(tile.left() + uv.x * tile.width(), tile.top() + uv.y * tile.height());
|
||||
let stroke = egui::Stroke::new(1.0, Color32::from_rgba_unmultiplied(0x40, 0xc0, 0xff, 170));
|
||||
let mut drawn = 0;
|
||||
for t in 0..mesh.triangle_count() {
|
||||
let Some([a, b, c]) = mesh.tri(t) else { break };
|
||||
let (Some(ua), Some(ub), Some(uc)) = (mesh.uvs.get(a), mesh.uvs.get(b), mesh.uvs.get(c)) else { continue };
|
||||
let pts = [to_screen(*ua), to_screen(*ub), to_screen(*uc)];
|
||||
if pts.iter().all(|q| !clip.contains(*q)) {
|
||||
continue;
|
||||
}
|
||||
p.line_segment([pts[0], pts[1]], stroke);
|
||||
p.line_segment([pts[1], pts[2]], stroke);
|
||||
p.line_segment([pts[2], pts[0]], stroke);
|
||||
drawn += 3;
|
||||
if drawn > MAX_EDGES {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Histograms of the displayed 8-bit values: one for gray or isolated channels, else R, G and B.
|
||||
fn histogram(px: &[u8], channels: usize) -> Vec<[u32; BINS]> {
|
||||
let mut h = vec![[0u32; BINS]; channels];
|
||||
@@ -145,7 +175,7 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
cam.offset = [0.0, 0.0];
|
||||
}
|
||||
if resp.hovered() {
|
||||
let scroll = ui.input(|i| i.smooth_scroll_delta.y);
|
||||
let scroll = ui.input(|i| i.smooth_scroll_delta.y) * if app.ui.prefs.invert_zoom { -1.0 } else { 1.0 };
|
||||
if scroll.abs() > 0.0 {
|
||||
cam.fit = false;
|
||||
let old = cam.zoom;
|
||||
@@ -191,6 +221,10 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
p.rect_stroke(Rect::from_center_size(center, size), 0.0, egui::Stroke::new(1.0, Color32::from_white_alpha(60)), egui::StrokeKind::Outside);
|
||||
}
|
||||
}
|
||||
let zoom = cam.zoom;
|
||||
if app.view2d.show_uvs {
|
||||
draw_uvs(app, &p, Rect::from_center_size(center, size), rect);
|
||||
}
|
||||
if app.session.view2d.histogram {
|
||||
let single = img.is_gray() || app.session.view2d.channel != "rgba";
|
||||
draw_histogram(&mut app.view2d, &p, rect, key, single);
|
||||
@@ -205,9 +239,9 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
g.node(id).ok().map(|n| if n.base.format == materialcraft_engine::core::OutputFormat::Inherit { g.format.bits() } else { n.base.format.bits() })
|
||||
})
|
||||
.unwrap_or("16");
|
||||
let mut text = format!("{} x {} ({}, {}bpc) {:.0}%", img.w, img.h, if img.is_gray() { "L" } else { "RGBA" }, bits, cam.zoom * 100.0);
|
||||
let mut text = format!("{} x {} ({}, {}bpc) {:.0}%", img.w, img.h, if img.is_gray() { "L" } else { "RGBA" }, bits, zoom * 100.0);
|
||||
if let Some(ptr) = resp.hover_pos() {
|
||||
let local = (ptr - (center - size * 0.5)) / cam.zoom;
|
||||
let local = (ptr - (center - size * 0.5)) / zoom;
|
||||
let (x, y) = (local.x.floor() as i64, local.y.floor() as i64);
|
||||
let v = img.get(x, y, true);
|
||||
if img.is_gray() {
|
||||
|
||||
+534
-62
@@ -15,7 +15,7 @@ use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::mpsc::{Receiver, TryRecvError};
|
||||
use std::time::Duration;
|
||||
|
||||
use egui::{Color32, ColorImage, Rect, Sense, TextureHandle, TextureOptions, Ui, pos2, vec2};
|
||||
use egui::{Color32, ColorImage, Rect, RichText, Sense, TextureHandle, TextureOptions, Ui, pos2, vec2};
|
||||
use egui_phosphor::regular as icon;
|
||||
use materialcraft_engine::view_cmds::{ENVIRONMENTS, SCENES};
|
||||
use materialcraft_render::{Lighting, Maps, Relief, Scene, Settings};
|
||||
@@ -55,7 +55,8 @@ pub struct View3dState {
|
||||
pub renders: u64,
|
||||
/// The last frame shown (RGBA8, for `view.screenshot`).
|
||||
pub shown: Option<(u32, u32, Vec<u8>)>,
|
||||
show_env: bool,
|
||||
/// Show the environment behind the mesh.
|
||||
pub show_env: bool,
|
||||
}
|
||||
|
||||
impl View3dState {
|
||||
@@ -105,12 +106,47 @@ pub fn scene_label(app: &MaterialCraftApp) -> String {
|
||||
SCENES.iter().find(|(s, _)| s == id).map_or(id.as_str(), |(_, l)| l).to_string()
|
||||
}
|
||||
|
||||
/// Which 3D view property page the Properties panel shows (Edit properties).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Page3d {
|
||||
Camera,
|
||||
Lights,
|
||||
Environment,
|
||||
Renderer,
|
||||
Material,
|
||||
}
|
||||
|
||||
impl Page3d {
|
||||
pub fn title(self) -> &'static str {
|
||||
match self {
|
||||
Page3d::Camera => "Camera",
|
||||
Page3d::Lights => "Lights",
|
||||
Page3d::Environment => "Environment",
|
||||
Page3d::Renderer => "Renderer",
|
||||
Page3d::Material => "Material",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Open a 3D view property page in the Properties panel.
|
||||
pub fn edit_properties(app: &mut MaterialCraftApp, page: Page3d) {
|
||||
app.props3d = Some((page, app.session.selection.clone()));
|
||||
app.ui.dock.focus(crate::docking::Panel::Properties);
|
||||
}
|
||||
|
||||
fn menu_row(ui: &mut Ui, ic: &str, label: &str) -> bool {
|
||||
ui.add(egui::Button::new(format!("{ic} {label}"))).clicked()
|
||||
}
|
||||
|
||||
fn menus(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
egui::Frame::NONE.fill(tk.panel).inner_margin(egui::Margin::symmetric(4, 1)).show(ui, |ui| {
|
||||
egui::MenuBar::new().ui(ui, |ui| {
|
||||
ui.menu_button(tr("Scene"), |ui| {
|
||||
for (id, label) in SCENES {
|
||||
for (i, (id, label)) in SCENES.iter().enumerate() {
|
||||
if i == 5 {
|
||||
ui.separator();
|
||||
}
|
||||
if ui.selectable_label(app.session.view3d.scene == *id, tr(label)).clicked() {
|
||||
app.run("view.3d", json!({"scene": id}));
|
||||
ui.close();
|
||||
@@ -126,46 +162,173 @@ fn menus(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
ui.close();
|
||||
}
|
||||
ui.separator();
|
||||
if ui.button(tr("Reset scene")).clicked() {
|
||||
app.run("view.3d.reset", json!({}));
|
||||
if ui.button(tr("Display UVs in 2D View")).clicked() {
|
||||
app.view2d.show_uvs = !app.view2d.show_uvs;
|
||||
app.ui.dock.focus(crate::docking::Panel::View2d);
|
||||
ui.close();
|
||||
}
|
||||
ui.separator();
|
||||
if ui.button(tr("Load State File...")).clicked() {
|
||||
load_state(app, false);
|
||||
ui.close();
|
||||
}
|
||||
if ui.button(tr("Load State File With Mesh...")).clicked() {
|
||||
load_state(app, true);
|
||||
ui.close();
|
||||
}
|
||||
ui.separator();
|
||||
if ui.button(tr("Save Current State...")).clicked() {
|
||||
save_state(app);
|
||||
ui.close();
|
||||
}
|
||||
if ui.button(tr("Save Current State As Default")).clicked() {
|
||||
app.ui.view3d_default = app.run("view.3d.state", json!({}));
|
||||
app.toast(tr("The 3D view opens with this state from now on (Reset Scene restores it)"), false);
|
||||
ui.close();
|
||||
}
|
||||
ui.separator();
|
||||
if ui.button(tr("Reset Scene")).clicked() {
|
||||
reset_all(app);
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
ui.menu_button(tr("Materials"), |ui| {
|
||||
ui.menu_button(tr("Default"), |ui| {
|
||||
if menu_row(ui, icon::GEAR, tr("Edit properties")) {
|
||||
edit_properties(app, Page3d::Material);
|
||||
ui.close();
|
||||
}
|
||||
ui.separator();
|
||||
let current = app.session.view3d.material.shader;
|
||||
for (shader, label) in [
|
||||
(materialcraft_render::Shader::Blinn, "Blinn"),
|
||||
(materialcraft_render::Shader::Lambert, "Lambert"),
|
||||
(materialcraft_render::Shader::MeshInfo, "Mesh Info"),
|
||||
(materialcraft_render::Shader::OpenPbr, "OpenPBR [Default]"),
|
||||
(materialcraft_render::Shader::MetallicRoughness, "Metallic Roughness"),
|
||||
(materialcraft_render::Shader::Coated, "Metallic Roughness - Coated"),
|
||||
(materialcraft_render::Shader::Subsurface, "Metallic Roughness - SSS"),
|
||||
(materialcraft_render::Shader::SpecularGlossiness, "Specular Glossiness"),
|
||||
(materialcraft_render::Shader::Unlit, "Unlit"),
|
||||
] {
|
||||
if ui.selectable_label(current == shader, tr(label)).clicked() {
|
||||
app.run("view.3d", json!({"material": {"shader": shader.id()}}));
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
ui.separator();
|
||||
if ui.button(tr("Reset Common Parameters")).clicked() {
|
||||
let d = materialcraft_render::Common::default();
|
||||
app.run("view.3d", json!({"material": {"common": d, "useMap": materialcraft_render::MapUse::default()}}));
|
||||
ui.close();
|
||||
}
|
||||
if menu_row(ui, icon::ARROW_COUNTER_CLOCKWISE, tr("Reset Material")) {
|
||||
app.run("view.3d.reset", json!({"what": "material"}));
|
||||
ui.close();
|
||||
}
|
||||
ui.separator();
|
||||
if ui.button(tr("Create graph from texture inputs")).clicked() {
|
||||
crate::menus::invoke(app, ui.ctx(), "ui.newGraph");
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
ui.menu_button(tr("Lights"), |ui| {
|
||||
if menu_row(ui, icon::GEAR, tr("Edit properties")) {
|
||||
edit_properties(app, Page3d::Lights);
|
||||
ui.close();
|
||||
}
|
||||
if menu_row(ui, icon::ARROW_COUNTER_CLOCKWISE, tr("Reset Lights")) {
|
||||
app.run("view.3d.reset", json!({"what": "lights"}));
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
ui.menu_button(tr("Camera"), |ui| {
|
||||
for (label, yaw, pitch) in [("Default", 35.0, 25.0), ("Front", 0.0, 0.0), ("Top", 0.0, 89.0), ("Side", 90.0, 0.0)] {
|
||||
if ui.button(tr(label)).clicked() {
|
||||
if menu_row(ui, icon::GEAR, tr("Edit properties")) {
|
||||
edit_properties(app, Page3d::Camera);
|
||||
ui.close();
|
||||
}
|
||||
if ui.add(egui::Button::new(tr("Frame")).shortcut_text("F")).clicked() {
|
||||
frame(app);
|
||||
ui.close();
|
||||
}
|
||||
ui.label(RichText::new(tr("Viewpoint")).italics().color(tk.text_dim));
|
||||
for (label, yaw, pitch) in [
|
||||
("Default", 35.0, 25.0),
|
||||
("Front", 0.0, 0.0),
|
||||
("Right", 90.0, 0.0),
|
||||
("Back", 180.0, 0.0),
|
||||
("Left", 270.0, 0.0),
|
||||
("Top", 0.0, 89.0),
|
||||
("Bottom", 0.0, -89.0),
|
||||
] {
|
||||
if ui.button(format!(" {}", tr(label))).clicked() {
|
||||
app.run("view.3d", json!({"yaw": yaw, "pitch": pitch, "distance": 3.2, "target": [0.0, 0.0, 0.0]}));
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
ui.separator();
|
||||
if ui.add(egui::Button::new(format!("{} {}", icon::FLOPPY_DISK, tr("Save Render..."))).shortcut_text("Alt+S")).clicked() {
|
||||
save_render(app, ui.ctx());
|
||||
ui.close();
|
||||
}
|
||||
if menu_row(ui, icon::CLIPBOARD, tr("Copy Render to Clipboard")) {
|
||||
copy_render(app, ui.ctx());
|
||||
ui.close();
|
||||
}
|
||||
ui.separator();
|
||||
if ui.add(egui::Button::new(tr("Reset Position")).shortcut_text("R")).clicked() {
|
||||
app.run("view.3d", json!({"yaw": 35.0, "pitch": 25.0, "distance": 3.2, "target": [0.0, 0.0, 0.0]}));
|
||||
ui.close();
|
||||
}
|
||||
if menu_row(ui, icon::ARROW_COUNTER_CLOCKWISE, tr("Reset Camera")) {
|
||||
app.run("view.3d.reset", json!({"what": "camera"}));
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
ui.menu_button(tr("Environment"), |ui| {
|
||||
if menu_row(ui, icon::GEAR, tr("Edit properties")) {
|
||||
edit_properties(app, Page3d::Environment);
|
||||
ui.close();
|
||||
}
|
||||
if menu_row(ui, icon::ARROW_COUNTER_CLOCKWISE, tr("Reset Environment")) {
|
||||
app.run("view.3d.reset", json!({"what": "environment"}));
|
||||
ui.close();
|
||||
}
|
||||
ui.separator();
|
||||
for (id, label) in ENVIRONMENTS {
|
||||
if ui.selectable_label(app.session.view3d.environment == *id, tr(label)).clicked() {
|
||||
app.run("view.3d", json!({"environment": id}));
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
ui.separator();
|
||||
let mut rot = app.session.view3d.env_rotation;
|
||||
if crate::widgets::slider(ui, tr("Rotation"), &mut rot, 0.0..=360.0, 0).changed() {
|
||||
app.run("view.3d", json!({"envRotation": rot}));
|
||||
}
|
||||
let mut exp = app.session.view3d.exposure;
|
||||
if crate::widgets::slider(ui, tr("Exposure"), &mut exp, -4.0..=4.0, 2).changed() {
|
||||
app.run("view.3d", json!({"exposure": exp}));
|
||||
}
|
||||
});
|
||||
ui.menu_button(tr("Display"), |ui| {
|
||||
crate::view2d::resolution_menu(app, ui);
|
||||
let d = app.session.view3d.display.clone();
|
||||
let mut toggles: Vec<(&str, bool)> = Vec::new();
|
||||
for (key, label, on) in [
|
||||
("wireframe", "Wireframe", d.wireframe),
|
||||
("axis", "Axis", app.session.view3d.show_axis),
|
||||
("backfaceCulling", "Backface culling", d.backface_culling),
|
||||
("boundingBox", "Bounding box", d.bounding_box),
|
||||
("grid", "Grid", app.session.view3d.show_grid),
|
||||
("lights", "Light", d.lights),
|
||||
] {
|
||||
if ui.selectable_label(on, tr(label)).clicked() {
|
||||
toggles.push((key, !on));
|
||||
}
|
||||
}
|
||||
ui.separator();
|
||||
for (key, label, on) in [("resolution", "Resolution", d.resolution), ("stats", "Scene stats", d.stats), ("fps", "FPS", d.fps)] {
|
||||
if ui.selectable_label(on, tr(label)).clicked() {
|
||||
toggles.push((key, !on));
|
||||
}
|
||||
}
|
||||
ui.separator();
|
||||
let mut flip = app.session.view3d.normal_y_flip;
|
||||
if ui.checkbox(&mut flip, tr("Flip normal map Y (DirectX)")).changed() {
|
||||
app.run("view.3d", json!({"normalYFlip": flip}));
|
||||
}
|
||||
ui.separator();
|
||||
ui.checkbox(&mut app.view3d.show_env, tr("Environment background"));
|
||||
ui.separator();
|
||||
let mut t = app.session.view3d.transparency;
|
||||
if ui.checkbox(&mut t, tr("Transparency (alpha)")).changed() {
|
||||
app.run("view.3d", json!({"transparency": t}));
|
||||
@@ -174,30 +337,207 @@ fn menus(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
if ui.checkbox(&mut a, tr("Show alpha channel")).changed() {
|
||||
app.run("view.3d", json!({"alphaView": a}));
|
||||
}
|
||||
ui.separator();
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(tr("Preview size"));
|
||||
crate::view2d::resolution_menu(app, ui);
|
||||
});
|
||||
for (key, on) in toggles {
|
||||
match key {
|
||||
"axis" => {
|
||||
app.run("view.3d", json!({"axis": on}));
|
||||
}
|
||||
"grid" => {
|
||||
app.run("view.3d", json!({"grid": on}));
|
||||
}
|
||||
_ => {
|
||||
app.run("view.3d", json!({"display": {key: on}}));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.menu_button(tr("Renderer"), |ui| {
|
||||
let mut depth_percent = app.session.view3d.height_scale * 100.0;
|
||||
if crate::widgets::slider(ui, tr("Height depth (% of the mesh size)"), &mut depth_percent, 0.0..=20.0, 1).changed() {
|
||||
app.run("view.3d", json!({"heightScale": depth_percent / 100.0}));
|
||||
}
|
||||
let mut level = app.session.view3d.height_level;
|
||||
if crate::widgets::slider(ui, tr("Height level (0 = rises out of the surface)"), &mut level, 0.0..=1.0, 2).changed() {
|
||||
app.run("view.3d", json!({"heightLevel": level}));
|
||||
}
|
||||
let mut t = app.session.view3d.tiling;
|
||||
if crate::widgets::slider(ui, tr("Tiling"), &mut t, 0.25..=8.0, 2).changed() {
|
||||
app.run("view.3d", json!({"tiling": t}));
|
||||
if menu_row(ui, icon::GEAR, tr("Edit settings")) {
|
||||
edit_properties(app, Page3d::Renderer);
|
||||
ui.close();
|
||||
}
|
||||
ui.separator();
|
||||
let _ = ui.selectable_label(true, tr("MC Ray caster (CPU)"));
|
||||
ui.add_enabled(false, egui::Button::new(tr("GPU path tracer (not supported yet)")));
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// Camera ▸ Frame (F): fit the mesh in the view.
|
||||
pub fn frame(app: &mut MaterialCraftApp) {
|
||||
app.run("view.3d", json!({"distance": 3.2, "target": [0.0, 0.0, 0.0]}));
|
||||
}
|
||||
|
||||
/// Scene ▸ Reset Scene: the saved default state, else the built-in one.
|
||||
pub fn reset_all(app: &mut MaterialCraftApp) {
|
||||
match app.ui.view3d_default.clone() {
|
||||
Some(state) => {
|
||||
app.run("view.3d.loadState", json!({"state": state}));
|
||||
}
|
||||
None => {
|
||||
app.run("view.3d.reset", json!({}));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Scene ▸ Save Current State: the 3D view's state as a JSON file.
|
||||
fn save_state(app: &mut MaterialCraftApp) {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let Some(state) = app.run("view.3d.state", json!({})) else { return };
|
||||
let Some(p) = rfd::FileDialog::new().set_file_name("3d-view-state.json").add_filter("3D view state", &["json"]).save_file() else { return };
|
||||
match serde_json::to_string_pretty(&state).map_err(|e| e.to_string()).and_then(|t| std::fs::write(&p, t).map_err(|e| e.to_string())) {
|
||||
Ok(()) => app.toast(format!("{} {}", tr("Saved"), p.display()), false),
|
||||
Err(e) => app.toast(format!("{}: {e}", tr("Could not save the state")), true),
|
||||
}
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
app.toast(tr("The desktop app saves state files"), true);
|
||||
}
|
||||
|
||||
/// Scene ▸ Load State File: restore a saved state (`with_mesh` also switches the scene).
|
||||
fn load_state(app: &mut MaterialCraftApp, with_mesh: bool) {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let Some(p) = rfd::FileDialog::new().add_filter("3D view state", &["json"]).pick_file() else { return };
|
||||
const MAX: u64 = 4 << 20;
|
||||
if std::fs::metadata(&p).map(|m| m.len()).unwrap_or(0) > MAX {
|
||||
app.toast(tr("That is not a 3D view state file"), true);
|
||||
return;
|
||||
}
|
||||
match std::fs::read_to_string(&p).map_err(|e| e.to_string()).and_then(|t| serde_json::from_str::<serde_json::Value>(&t).map_err(|e| e.to_string())) {
|
||||
Ok(state) => {
|
||||
if app.run("view.3d.loadState", json!({"state": state, "keepScene": !with_mesh})).is_some() {
|
||||
app.toast(format!("{} {}", tr("Loaded"), p.display()), false);
|
||||
}
|
||||
}
|
||||
Err(e) => app.toast(format!("{}: {e}", tr("Could not read the state file")), true),
|
||||
}
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
let _ = with_mesh;
|
||||
app.toast(tr("The desktop app loads state files"), true);
|
||||
}
|
||||
}
|
||||
|
||||
/// Camera ▸ Save Render (Alt+S): the view at the camera's render resolution, as a PNG.
|
||||
pub fn save_render(app: &mut MaterialCraftApp, ctx: &egui::Context) {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let _ = ctx;
|
||||
let name = format!("{}_render.png", materialcraft_engine::formats::safe_file_name(&app.session.graph().map(|g| g.name.clone()).unwrap_or_default()));
|
||||
let Some(p) = rfd::FileDialog::new().set_file_name(name).add_filter("PNG", &["png"]).save_file() else { return };
|
||||
let Some((w, h, px)) = render_offscreen(app) else { return };
|
||||
match crate::control::encode_png(w, h, px)
|
||||
.ok_or_else(|| tr("could not encode the image").to_string())
|
||||
.and_then(|(_, _, png)| std::fs::write(&p, png).map_err(|e| e.to_string()))
|
||||
{
|
||||
Ok(()) => app.toast(format!("{} {}", tr("Render saved to"), p.display()), false),
|
||||
Err(e) => app.toast(format!("{}: {e}", tr("Could not save the render")), true),
|
||||
}
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
let _ = ctx;
|
||||
let Some((w, h, px)) = render_offscreen(app) else { return };
|
||||
if let Some((_, _, png)) = crate::control::encode_png(w, h, px) {
|
||||
let _ = crate::web_files::download("render.png", &png);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Camera ▸ Copy Render to Clipboard.
|
||||
pub fn copy_render(app: &mut MaterialCraftApp, ctx: &egui::Context) {
|
||||
let Some((w, h, px)) = render_offscreen(app) else { return };
|
||||
let img = ColorImage::from_rgba_unmultiplied([w as usize, h as usize], &px);
|
||||
ctx.copy_image(img);
|
||||
app.toast(tr("Render copied to the clipboard"), false);
|
||||
}
|
||||
|
||||
/// Render the view at the camera's resolution (or the last shown size) with full quality.
|
||||
fn render_offscreen(app: &mut MaterialCraftApp) -> Option<(u32, u32, Vec<u8>)> {
|
||||
let v = app.session.view3d.clone();
|
||||
let (w, h) = if v.camera.override_resolution {
|
||||
let k = v.camera.resolution_scale;
|
||||
(((v.camera.resolution[0] as f32 * k) as u32).clamp(16, 4096), ((v.camera.resolution[1] as f32 * k) as u32).clamp(16, 4096))
|
||||
} else {
|
||||
app.view3d.shown.as_ref().map_or((1280, 720), |(w, h, _)| (*w, *h))
|
||||
};
|
||||
let (scene, light, maps, settings) = inputs(app, 2)?;
|
||||
let px = materialcraft_render::render(&scene, &maps, &light, &settings, w, h);
|
||||
Some((w, h, px))
|
||||
}
|
||||
|
||||
/// The tool strip down the left of the viewport: property pages and display toggles.
|
||||
fn side_strip(app: &mut MaterialCraftApp, ui: &mut Ui, strip: Rect) {
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
ui.painter().rect_filled(strip, 0.0, tk.panel);
|
||||
ui.scope_builder(egui::UiBuilder::new().max_rect(strip.shrink2(vec2(2.0, 4.0))), |ui| {
|
||||
ui.vertical(|ui| {
|
||||
ui.spacing_mut().item_spacing.y = 2.0;
|
||||
let b = |ui: &mut Ui, ic: &str, tip: &str, on: bool| crate::widgets::icon_button(ui, ic, tip, on, 22.0).clicked();
|
||||
if b(ui, icon::CORNERS_OUT, tr("Frame (F)"), false) {
|
||||
frame(app);
|
||||
}
|
||||
let page = app.props3d.as_ref().map(|(p, _)| *p);
|
||||
for (ic, tip, pg) in [
|
||||
(icon::VIDEO_CAMERA, "Camera properties", Page3d::Camera),
|
||||
(icon::LIGHTBULB, "Light properties", Page3d::Lights),
|
||||
(icon::SUN_HORIZON, "Environment properties", Page3d::Environment),
|
||||
(icon::SPHERE, "Material properties", Page3d::Material),
|
||||
(icon::GEAR, "Renderer settings", Page3d::Renderer),
|
||||
] {
|
||||
if b(ui, ic, tr(tip), page == Some(pg)) {
|
||||
edit_properties(app, pg);
|
||||
}
|
||||
}
|
||||
ui.add_space(6.0);
|
||||
let v = app.session.view3d.clone();
|
||||
let mut set: Option<serde_json::Value> = None;
|
||||
if b(ui, icon::POLYGON, tr("Wireframe"), v.display.wireframe) {
|
||||
set = Some(json!({"display": {"wireframe": !v.display.wireframe}}));
|
||||
}
|
||||
if b(ui, icon::GRID_FOUR, tr("Grid"), v.show_grid) {
|
||||
set = Some(json!({"grid": !v.show_grid}));
|
||||
}
|
||||
if b(ui, icon::ARROWS_OUT_CARDINAL, tr("Axis"), v.show_axis) {
|
||||
set = Some(json!({"axis": !v.show_axis}));
|
||||
}
|
||||
if b(ui, icon::BOUNDING_BOX, tr("Bounding box"), v.display.bounding_box) {
|
||||
set = Some(json!({"display": {"boundingBox": !v.display.bounding_box}}));
|
||||
}
|
||||
if b(ui, icon::CUBE_TRANSPARENT, tr("Transparency (alpha)"), v.transparency) {
|
||||
set = Some(json!({"transparency": !v.transparency}));
|
||||
}
|
||||
if b(ui, icon::CHECKERBOARD, tr("Show alpha channel"), v.alpha_view) {
|
||||
set = Some(json!({"alphaView": !v.alpha_view}));
|
||||
}
|
||||
if b(ui, icon::IMAGE, tr("Environment background"), app.view3d.show_env) {
|
||||
app.view3d.show_env = !app.view3d.show_env;
|
||||
}
|
||||
if let Some(p) = set {
|
||||
app.run("view.3d", p);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
menus(app, ui);
|
||||
let avail = ui.available_size();
|
||||
let (rect, resp) = ui.allocate_exact_size(vec2(avail.x, (avail.y - 22.0).max(40.0)), Sense::click_and_drag());
|
||||
let strip_w = 28.0;
|
||||
let (whole, _) = ui.allocate_exact_size(vec2(avail.x, (avail.y - 22.0).max(40.0)), Sense::hover());
|
||||
let strip = Rect::from_min_size(whole.min, vec2(strip_w, whole.height()));
|
||||
let rect = Rect::from_min_max(pos2(whole.left() + strip_w, whole.top()), whole.max);
|
||||
let resp = ui.interact(rect, ui.scope_id().with("view3d-canvas"), Sense::click_and_drag());
|
||||
crate::widgets::name(&resp, egui::Role::Image, "3D view");
|
||||
// Camera gestures.
|
||||
let mut moving = false;
|
||||
@@ -222,7 +562,7 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
moving = true;
|
||||
}
|
||||
if resp.hovered() {
|
||||
let scroll = ui.input(|i| i.smooth_scroll_delta.y);
|
||||
let scroll = ui.input(|i| i.smooth_scroll_delta.y) * if app.ui.prefs.invert_zoom { -1.0 } else { 1.0 };
|
||||
if scroll.abs() > 0.0 {
|
||||
app.session.view3d.distance = (app.session.view3d.distance * (-scroll * 0.002).exp()).clamp(1.2, 20.0);
|
||||
moving = true;
|
||||
@@ -231,6 +571,19 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
if resp.double_clicked() {
|
||||
app.run("view.3d", json!({"yaw": 35.0, "pitch": 25.0, "distance": 3.2, "target": [0.0, 0.0, 0.0]}));
|
||||
}
|
||||
// Keys while the pointer is over the view: F frames, R resets the position, Alt+S saves a render.
|
||||
if resp.hovered() && !ui.ctx().egui_wants_keyboard_input() {
|
||||
let (f, r, alt_s) = ui.input(|i| (i.key_pressed(egui::Key::F), i.key_pressed(egui::Key::R), i.modifiers.alt && i.key_pressed(egui::Key::S)));
|
||||
if f {
|
||||
frame(app);
|
||||
}
|
||||
if r {
|
||||
app.run("view.3d", json!({"yaw": 35.0, "pitch": 25.0, "distance": 3.2, "target": [0.0, 0.0, 0.0]}));
|
||||
}
|
||||
if alt_s {
|
||||
save_render(app, ui.ctx());
|
||||
}
|
||||
}
|
||||
render(app, ui.ctx(), rect, moving || resp.is_pointer_button_down_on());
|
||||
let p = ui.painter_at(rect);
|
||||
p.rect_filled(rect, 0.0, Color32::from_rgb(0x1b, 0x1c, 0x1e));
|
||||
@@ -249,6 +602,7 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
tk.viewport_text,
|
||||
);
|
||||
}
|
||||
overlays(app, &p, rect);
|
||||
p.text(
|
||||
rect.right_bottom() - vec2(8.0, 6.0),
|
||||
egui::Align2::RIGHT_BOTTOM,
|
||||
@@ -256,8 +610,9 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
egui::FontId::proportional(10.5),
|
||||
tk.viewport_text,
|
||||
);
|
||||
side_strip(app, ui, strip);
|
||||
// Bottom bar.
|
||||
let bar = Rect::from_min_size(pos2(rect.left(), rect.bottom()), vec2(rect.width(), 22.0));
|
||||
let bar = Rect::from_min_size(pos2(whole.left(), whole.bottom()), vec2(whole.width(), 22.0));
|
||||
ui.scope_builder(egui::UiBuilder::new().max_rect(bar), |ui| {
|
||||
ui.painter().rect_filled(bar, 0.0, tk.panel);
|
||||
ui.horizontal_centered(|ui| {
|
||||
@@ -280,6 +635,77 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
});
|
||||
}
|
||||
|
||||
/// Display menu overlays: bounding box, light gizmos, resolution, scene statistics and FPS.
|
||||
fn overlays(app: &mut MaterialCraftApp, p: &egui::Painter, rect: Rect) {
|
||||
let tk = Tokens::get(p.ctx());
|
||||
let v = app.session.view3d.clone();
|
||||
let d = &v.display;
|
||||
let (bbox, lights) = (d.bounding_box, d.lights);
|
||||
if bbox || lights {
|
||||
let (_, scene) = base_scene(app);
|
||||
let settings = settings_of(&v, app.view3d.show_env, 1);
|
||||
let cam = materialcraft_render::camera(&scene, &settings);
|
||||
let aspect = rect.width() / rect.height().max(1.0);
|
||||
let to_screen = |w: materialcraft_engine::geom::glam::Vec3| {
|
||||
cam.project(w, aspect).map(|ndc| pos2(rect.left() + (ndc.x * 0.5 + 0.5) * rect.width(), rect.top() + (0.5 - ndc.y * 0.5) * rect.height()))
|
||||
};
|
||||
if bbox {
|
||||
let (lo, hi) = scene.mesh.bounds();
|
||||
let corners: Vec<_> = (0..8)
|
||||
.map(|i| {
|
||||
materialcraft_engine::geom::glam::Vec3::new(
|
||||
if i & 1 == 0 { lo.x } else { hi.x },
|
||||
if i & 2 == 0 { lo.y } else { hi.y },
|
||||
if i & 4 == 0 { lo.z } else { hi.z },
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let stroke = egui::Stroke::new(1.0, Color32::from_rgba_unmultiplied(0xff, 0xc0, 0x40, 200));
|
||||
for (a, b) in [(0, 1), (2, 3), (4, 5), (6, 7), (0, 2), (1, 3), (4, 6), (5, 7), (0, 4), (1, 5), (2, 6), (3, 7)] {
|
||||
if let (Some(pa), Some(pb)) = (to_screen(corners[a]), to_screen(corners[b])) {
|
||||
p.line_segment([pa, pb], stroke);
|
||||
}
|
||||
}
|
||||
}
|
||||
if lights {
|
||||
for (i, l) in v.lights.point.iter().enumerate() {
|
||||
let w = scene.center + materialcraft_engine::geom::glam::Vec3::from(l.position) * scene.radius;
|
||||
if let Some(q) = to_screen(w) {
|
||||
let c = if l.on { Color32::from_rgb(0xff, 0xe0, 0x60) } else { Color32::from_gray(0x80) };
|
||||
p.circle(q, 6.0, c, egui::Stroke::new(1.0, Color32::BLACK));
|
||||
p.text(q + vec2(9.0, 0.0), egui::Align2::LEFT_CENTER, format!("{} {}", tr("Light"), i + 1), egui::FontId::proportional(10.5), c);
|
||||
if let Some(center) = to_screen(scene.center) {
|
||||
p.line_segment([q, center], egui::Stroke::new(1.0, Color32::from_rgba_unmultiplied(0xff, 0xe0, 0x60, 90)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut lines: Vec<String> = Vec::new();
|
||||
if d.resolution {
|
||||
let (w, h) = app.view3d.shown.as_ref().map_or((0, 0), |(w, h, _)| (*w, *h));
|
||||
lines.push(format!("{}: {w} x {h}", tr("Resolution")));
|
||||
}
|
||||
if d.stats {
|
||||
let (_, scene) = base_scene(app);
|
||||
let tris = app.view3d.displaced.as_ref().map_or(scene.mesh.triangle_count(), |(_, s)| s.mesh.triangle_count());
|
||||
let maps = app.session.material_maps().len();
|
||||
lines.push(format!("{}: {tris} {}, {maps} {}", tr("Scene"), tr("triangles"), tr("maps")));
|
||||
}
|
||||
if d.fps {
|
||||
lines.push(format!("{:.0} FPS ({} {})", app.fps, app.view3d.renders, tr("frames")));
|
||||
}
|
||||
for (i, line) in lines.iter().enumerate() {
|
||||
p.text(
|
||||
rect.left_bottom() + vec2(8.0, -8.0 - 14.0 * (lines.len() - 1 - i) as f32),
|
||||
egui::Align2::LEFT_BOTTOM,
|
||||
line,
|
||||
egui::FontId::proportional(10.5),
|
||||
tk.viewport_text,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn scene_label_custom(app: &MaterialCraftApp) -> String {
|
||||
app.session.custom_mesh.as_ref().map_or_else(String::new, |(n, _)| n.clone())
|
||||
}
|
||||
@@ -309,6 +735,8 @@ fn content_key(app: &MaterialCraftApp, w: u32, h: u32, show_env: bool, relief_sh
|
||||
for f in [v.yaw, v.pitch, v.distance, v.target[0], v.target[1], v.target[2], v.tiling, v.exposure, v.env_rotation, v.height_scale, v.height_level] {
|
||||
f.to_bits().hash(&mut hs);
|
||||
}
|
||||
// Camera, lights, material, renderer and display settings: hashed through their JSON.
|
||||
serde_json::to_string(&(&v.camera, &v.lights, &v.material, &v.renderer, &v.display, v.env_enabled)).unwrap_or_default().hash(&mut hs);
|
||||
if let Ok(g) = app.session.graph() {
|
||||
for (id, usage, _, _) in materialcraft_engine::eval::outputs(g, &app.session.cooked) {
|
||||
(usage, app.session.cooked.nodes.get(&id).map(|r| r.key)).hash(&mut hs);
|
||||
@@ -394,7 +822,7 @@ fn relief_key(app: &MaterialCraftApp, scene_key: &str, maps: &Maps) -> Option<u6
|
||||
use std::hash::{DefaultHasher, Hash, Hasher};
|
||||
|
||||
let v = &app.session.view3d;
|
||||
if maps.height.is_none() || v.height_scale <= 0.0 {
|
||||
if maps.height.is_none() || v.height_scale <= 0.0 || !v.material.use_map.height {
|
||||
return None;
|
||||
}
|
||||
|
||||
@@ -403,8 +831,8 @@ fn relief_key(app: &MaterialCraftApp, scene_key: &str, maps: &Maps) -> Option<u6
|
||||
let height_cook = height_output.and_then(|(id, _, _, _)| app.session.cooked.nodes.get(&id).map(|r| r.key));
|
||||
|
||||
let mut hasher = DefaultHasher::new();
|
||||
(scene_key, height_cook, maps.normal.is_some()).hash(&mut hasher);
|
||||
for f in [v.height_scale, v.height_level, v.tiling] {
|
||||
(scene_key, height_cook, maps.normal.is_some() && v.material.use_map.normal, v.material.use_map.height).hash(&mut hasher);
|
||||
for f in [v.height_scale, v.height_level, v.tiling, v.material.tessellation, v.material.uv_scale[0]] {
|
||||
f.to_bits().hash(&mut hasher);
|
||||
}
|
||||
Some(hasher.finish())
|
||||
@@ -434,19 +862,22 @@ fn update_relief(app: &mut MaterialCraftApp, ctx: &egui::Context) -> Option<u64>
|
||||
if app.view3d.relief_job.is_none() {
|
||||
let v = &app.session.view3d;
|
||||
let relief = Relief { depth: v.height_scale, level: v.height_level };
|
||||
start_relief(app, ctx, wanted, base, maps, relief, v.tiling);
|
||||
let budget = ((RELIEF_TRIANGLES as f32) * v.material.tessellation.clamp(0.1, 4.0)) as usize;
|
||||
let tiling = v.tiling * v.material.uv_scale[0].max(0.01);
|
||||
start_relief(app, ctx, wanted, base, maps, relief, tiling, budget);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Build the displaced scene on a worker thread.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn start_relief(app: &mut MaterialCraftApp, ctx: &egui::Context, key: u64, base: Arc<Scene>, maps: Maps, relief: Relief, tiling: f32) {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn start_relief(app: &mut MaterialCraftApp, ctx: &egui::Context, key: u64, base: Arc<Scene>, maps: Maps, relief: Relief, tiling: f32, budget: usize) {
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let (repaint, viewport) = (ctx.clone(), ctx.viewport_id());
|
||||
let (thread_base, thread_maps) = (base.clone(), maps.clone());
|
||||
let spawned = std::thread::Builder::new().name("materialcraft-relief".into()).spawn(move || {
|
||||
let _ = tx.send(thread_base.with_relief(&thread_maps, relief, tiling, RELIEF_TRIANGLES).map(Arc::new));
|
||||
let _ = tx.send(thread_base.with_relief(&thread_maps, relief, tiling, budget).map(Arc::new));
|
||||
repaint.request_repaint_of(viewport);
|
||||
});
|
||||
|
||||
@@ -454,15 +885,16 @@ fn start_relief(app: &mut MaterialCraftApp, ctx: &egui::Context, key: u64, base:
|
||||
Ok(_) => app.view3d.relief_job = Some(ReliefJob { key, rx }),
|
||||
Err(e) => {
|
||||
log::warn!("could not start a 3D view relief thread ({e}); building it here");
|
||||
app.view3d.displaced = base.with_relief(&maps, relief, tiling, RELIEF_TRIANGLES).map(|scene| (key, Arc::new(scene)));
|
||||
app.view3d.displaced = base.with_relief(&maps, relief, tiling, budget).map(|scene| (key, Arc::new(scene)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The browser has no threads: the displaced scene builds here (the page pauses).
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn start_relief(app: &mut MaterialCraftApp, _ctx: &egui::Context, key: u64, base: Arc<Scene>, maps: Maps, relief: Relief, tiling: f32) {
|
||||
app.view3d.displaced = base.with_relief(&maps, relief, tiling, RELIEF_TRIANGLES).map(|scene| (key, Arc::new(scene)));
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn start_relief(app: &mut MaterialCraftApp, _ctx: &egui::Context, key: u64, base: Arc<Scene>, maps: Maps, relief: Relief, tiling: f32, budget: usize) {
|
||||
app.view3d.displaced = base.with_relief(&maps, relief, tiling, budget).map(|scene| (key, Arc::new(scene)));
|
||||
}
|
||||
|
||||
/// The scene, lighting, maps and settings of the current view: the displaced scene when it is current, else the plain one.
|
||||
@@ -473,21 +905,7 @@ fn inputs(app: &mut MaterialCraftApp, supersample: u32) -> Option<(Arc<Scene>, A
|
||||
app.view3d.light = Some(Arc::new(Lighting::new(&v.environment)));
|
||||
}
|
||||
|
||||
let settings = Settings {
|
||||
yaw: v.yaw,
|
||||
pitch: v.pitch,
|
||||
distance: v.distance,
|
||||
target: v.target,
|
||||
tiling: v.tiling,
|
||||
exposure: v.exposure,
|
||||
env_rotation: v.env_rotation,
|
||||
normal_y_flip: v.normal_y_flip,
|
||||
show_env: app.view3d.show_env,
|
||||
supersample,
|
||||
transparency: v.transparency,
|
||||
alpha_view: v.alpha_view,
|
||||
..Settings::default()
|
||||
};
|
||||
let settings = settings_of(&v, app.view3d.show_env, supersample);
|
||||
let maps = Maps::from_usages(app.session.material_maps());
|
||||
let wanted = relief_key(app, &scene_key, &maps);
|
||||
let scene = match &app.view3d.displaced {
|
||||
@@ -498,6 +916,56 @@ fn inputs(app: &mut MaterialCraftApp, supersample: u32) -> Option<(Arc<Scene>, A
|
||||
Some((scene, light, maps, settings))
|
||||
}
|
||||
|
||||
/// The renderer's settings for the view state.
|
||||
pub fn settings_of(v: &materialcraft_engine::View3d, show_env: bool, supersample: u32) -> Settings {
|
||||
let cam = &v.camera;
|
||||
let bg = [cam.background_color[0], cam.background_color[1], cam.background_color[2]];
|
||||
let background = match cam.background.as_str() {
|
||||
"color" => materialcraft_render::Background::Color(bg),
|
||||
"environment" => materialcraft_render::Background::Environment,
|
||||
_ => materialcraft_render::Background::Backdrop,
|
||||
};
|
||||
let lights = &v.lights;
|
||||
Settings {
|
||||
yaw: v.yaw,
|
||||
pitch: v.pitch,
|
||||
distance: v.distance,
|
||||
target: v.target,
|
||||
tiling: v.tiling * v.material.uv_scale[0].max(0.01),
|
||||
exposure: v.exposure,
|
||||
env_rotation: v.env_rotation,
|
||||
normal_y_flip: v.normal_y_flip,
|
||||
show_env,
|
||||
supersample: supersample.min(v.renderer.samples.max(1)),
|
||||
ao_rays: v.renderer.ao_rays,
|
||||
transparency: v.transparency,
|
||||
alpha_view: v.alpha_view,
|
||||
fov: cam.fov(),
|
||||
ortho: cam.projection == "orthographic",
|
||||
background,
|
||||
clip: if cam.auto_clip { None } else { Some([cam.near, cam.far]) },
|
||||
ambient: if lights.ambient_on { lights.ambient } else { [0.0; 3] },
|
||||
lights: lights.point,
|
||||
env_light: v.env_enabled,
|
||||
shader: v.material.shader,
|
||||
common: v.material.common,
|
||||
use_map: v.material.use_map,
|
||||
wireframe: v.display.wireframe,
|
||||
backface_culling: v.display.backface_culling,
|
||||
..Settings::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// The viewport render scale: the session's renderer setting, else the preference (0 = auto = 1).
|
||||
fn view_scale(app: &MaterialCraftApp) -> f32 {
|
||||
let r = &app.session.view3d.renderer;
|
||||
if !r.use_viewport_resolution {
|
||||
return r.scale;
|
||||
}
|
||||
let p = app.ui.prefs.viewport_scale;
|
||||
if p > 0.0 { p.clamp(0.25, 2.0) } else { r.scale.clamp(0.25, 2.0) }
|
||||
}
|
||||
|
||||
/// Texture pixels for `rect` at `scale` pixels per point.
|
||||
fn pixels(rect: Rect, scale: f32) -> (u32, u32) {
|
||||
(((rect.width() * scale) as u32).clamp(16, 4096), ((rect.height() * scale) as u32).clamp(16, 4096))
|
||||
@@ -515,8 +983,9 @@ fn render_now(app: &mut MaterialCraftApp, rect: Rect, scale: f32, supersample: u
|
||||
/// Start the full-quality frame (2×2 supersampled, full resolution) on a worker thread.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn start_full(app: &mut MaterialCraftApp, ctx: &egui::Context, rect: Rect, key: u64, size: (u32, u32)) {
|
||||
let Some((scene, light, maps, settings)) = inputs(app, 2) else { return };
|
||||
let (w, h) = pixels(rect, ctx.pixels_per_point());
|
||||
let samples = app.ui.prefs.sample_count.clamp(1, 4);
|
||||
let Some((scene, light, maps, settings)) = inputs(app, samples) else { return };
|
||||
let (w, h) = pixels(rect, ctx.pixels_per_point() * view_scale(app));
|
||||
let cancel = Arc::new(AtomicBool::new(false));
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let (stop, repaint, viewport) = (cancel.clone(), ctx.clone(), ctx.viewport_id());
|
||||
@@ -530,7 +999,8 @@ fn start_full(app: &mut MaterialCraftApp, ctx: &egui::Context, rect: Rect, key:
|
||||
Ok(_) => app.view3d.job = Some(Job { key, size, cancel, rx }),
|
||||
Err(e) => {
|
||||
log::warn!("could not start a 3D view render thread ({e}); rendering here");
|
||||
if let Some(frame) = render_now(app, rect, ctx.pixels_per_point(), 2) {
|
||||
let scale = ctx.pixels_per_point() * view_scale(app);
|
||||
if let Some(frame) = render_now(app, rect, scale, samples) {
|
||||
show_frame(app, ctx, frame, key, true, size);
|
||||
}
|
||||
}
|
||||
@@ -540,7 +1010,9 @@ fn start_full(app: &mut MaterialCraftApp, ctx: &egui::Context, rect: Rect, key:
|
||||
/// The browser has no threads: the full-quality frame renders here (the page pauses).
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn start_full(app: &mut MaterialCraftApp, ctx: &egui::Context, rect: Rect, key: u64, size: (u32, u32)) {
|
||||
if let Some(frame) = render_now(app, rect, ctx.pixels_per_point(), 2) {
|
||||
let samples = app.ui.prefs.sample_count.clamp(1, 4);
|
||||
let scale = ctx.pixels_per_point() * view_scale(app);
|
||||
if let Some(frame) = render_now(app, rect, scale, samples) {
|
||||
show_frame(app, ctx, frame, key, true, size);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,425 @@
|
||||
//! The 3D view's "Edit properties" pages in the Properties panel: camera, lights, environment,
|
||||
//! renderer and the material's common values. Every change is a `view.3d` command.
|
||||
|
||||
use egui::{RichText, Ui, vec2};
|
||||
use materialcraft_engine::View3d;
|
||||
use serde_json::{Value as J, json};
|
||||
|
||||
use crate::MaterialCraftApp;
|
||||
use crate::i18n::tr;
|
||||
use crate::theme::Tokens;
|
||||
use crate::view3d::Page3d;
|
||||
|
||||
/// The panel title for an open page.
|
||||
pub fn title(page: Page3d) -> String {
|
||||
format!("{} - {}", tr(page.title()), tr("Properties"))
|
||||
}
|
||||
|
||||
/// A section header like the node pages.
|
||||
fn section(ui: &mut Ui, id: &str, title: &str, body: impl FnOnce(&mut Ui)) {
|
||||
crate::widgets::section(ui, id, title, true, body);
|
||||
}
|
||||
|
||||
/// A labelled row: the label on top, the control below.
|
||||
fn labelled(ui: &mut Ui, label: &str, body: impl FnOnce(&mut Ui)) {
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
ui.add_space(2.0);
|
||||
ui.label(RichText::new(label).strong().color(tk.text));
|
||||
body(ui);
|
||||
ui.add_space(2.0);
|
||||
}
|
||||
|
||||
/// A common-value row: a checkbox (use the map when one exists), the label and "Common".
|
||||
fn common_label(ui: &mut Ui, label: &str, use_map: Option<&mut bool>) -> bool {
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
let mut changed = false;
|
||||
ui.horizontal(|ui| {
|
||||
match use_map {
|
||||
Some(flag) => {
|
||||
let r = ui.add(egui::Checkbox::without_text(flag)).on_hover_text(tr("Use the map output when the graph has one (off: the common value below)"));
|
||||
changed = r.changed();
|
||||
}
|
||||
None => {
|
||||
ui.add_space(22.0);
|
||||
}
|
||||
}
|
||||
ui.label(RichText::new(label).strong().color(tk.text));
|
||||
ui.label(RichText::new(tr("Common")).color(tk.text_dim));
|
||||
});
|
||||
changed
|
||||
}
|
||||
|
||||
pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui, page: Page3d) {
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(RichText::new(tr(page.title())).heading());
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if ui.small_button(tr("Back to the graph")).clicked() {
|
||||
app.props3d = None;
|
||||
}
|
||||
});
|
||||
});
|
||||
ui.label(RichText::new(tr("3D view properties: changes show in the view at once and are kept with the session.")).small().color(tk.text_dim));
|
||||
ui.add_space(4.0);
|
||||
let v = app.session.view3d.clone();
|
||||
let patch: Option<J> = match page {
|
||||
Page3d::Camera => camera(ui, &v),
|
||||
Page3d::Lights => lights(ui, &v),
|
||||
Page3d::Environment => environment(app, ui, &v),
|
||||
Page3d::Renderer => renderer(ui, &v),
|
||||
Page3d::Material => material(ui, &v),
|
||||
};
|
||||
if let Some(p) = patch {
|
||||
app.run("view.3d", p);
|
||||
}
|
||||
}
|
||||
|
||||
fn camera(ui: &mut Ui, v: &View3d) -> Option<J> {
|
||||
let mut c = v.camera.clone();
|
||||
let mut changed = false;
|
||||
section(ui, "cam", tr("Camera Component"), |ui| {
|
||||
labelled(ui, tr("Focal Length (mm)"), |ui| {
|
||||
changed |= crate::widgets::slider(ui, "", &mut c.focal_length, 4.0..=300.0, 0).changed();
|
||||
});
|
||||
labelled(ui, tr("Projection"), |ui| {
|
||||
let label = if c.projection == "orthographic" { tr("Orthographic") } else { tr("Perspective") };
|
||||
let r = egui::ComboBox::from_id_salt("cam-proj").width(ui.available_width()).selected_text(label).show_ui(ui, |ui| {
|
||||
for (id, label) in [("perspective", "Perspective"), ("orthographic", "Orthographic")] {
|
||||
if ui.selectable_label(c.projection == id, tr(label)).clicked() {
|
||||
c.projection = id.into();
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
crate::widgets::name(&r.response, egui::Role::ComboBox, "Projection");
|
||||
});
|
||||
labelled(ui, tr("Background Type"), |ui| {
|
||||
let labels = [("backdrop", "Studio backdrop"), ("color", "Uniform Color"), ("environment", "Environment")];
|
||||
let cur = labels.iter().find(|(id, _)| *id == c.background).map_or("Studio backdrop", |(_, l)| l);
|
||||
let r = egui::ComboBox::from_id_salt("cam-bg").width(ui.available_width()).selected_text(tr(cur)).show_ui(ui, |ui| {
|
||||
for (id, label) in labels {
|
||||
if ui.selectable_label(c.background == id, tr(label)).clicked() {
|
||||
c.background = id.into();
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
crate::widgets::name(&r.response, egui::Role::ComboBox, "Background type");
|
||||
});
|
||||
if c.background == "color" {
|
||||
labelled(ui, tr("Background Color"), |ui| {
|
||||
let mut rgb = [c.background_color[0], c.background_color[1], c.background_color[2]];
|
||||
let mut a = c.background_color[3];
|
||||
if crate::widgets::color_strip(ui, "cam-bg-color", &mut rgb, Some(&mut a)) {
|
||||
c.background_color = [rgb[0], rgb[1], rgb[2], a];
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
}
|
||||
changed |= crate::widgets::bool_button(ui, tr("Override Render Resolution"), &mut c.override_resolution);
|
||||
ui.add_enabled_ui(c.override_resolution, |ui| {
|
||||
let mut w = c.resolution[0] as f32;
|
||||
let mut h = c.resolution[1] as f32;
|
||||
labelled(ui, tr("Render resolution"), |ui| {
|
||||
if crate::widgets::slider(ui, tr("Width"), &mut w, 16.0..=8192.0, 0).changed()
|
||||
| crate::widgets::slider(ui, tr("Height"), &mut h, 16.0..=8192.0, 0).changed()
|
||||
{
|
||||
c.resolution = [w as u32, h as u32];
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
labelled(ui, tr("Render resolution scale"), |ui| {
|
||||
let r = egui::ComboBox::from_id_salt("cam-scale")
|
||||
.width(ui.available_width())
|
||||
.selected_text(format!("{:.0} %", c.resolution_scale * 100.0))
|
||||
.show_ui(ui, |ui| {
|
||||
for s in [0.25f32, 0.5, 1.0, 1.5, 2.0] {
|
||||
if ui.selectable_label((c.resolution_scale - s).abs() < 1e-3, format!("{:.0} %", s * 100.0)).clicked() {
|
||||
c.resolution_scale = s;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
crate::widgets::name(&r.response, egui::Role::ComboBox, "Render resolution scale");
|
||||
});
|
||||
});
|
||||
changed |= crate::widgets::bool_button(ui, tr("Automatic Clip Planes"), &mut c.auto_clip);
|
||||
ui.add_enabled_ui(!c.auto_clip, |ui| {
|
||||
labelled(ui, tr("Near Clip Plane"), |ui| {
|
||||
changed |= crate::widgets::slider(ui, "", &mut c.near, 0.001..=20.0, 3).changed();
|
||||
});
|
||||
labelled(ui, tr("Far Clip Plane"), |ui| {
|
||||
changed |= crate::widgets::slider(ui, "", &mut c.far, 0.01..=200.0, 2).changed();
|
||||
});
|
||||
});
|
||||
ui.label(RichText::new(tr("Clip distances are in mesh radii from the camera.")).small().color(Tokens::get(ui.ctx()).text_dim));
|
||||
});
|
||||
changed.then(|| json!({"camera": c}))
|
||||
}
|
||||
|
||||
fn lights(ui: &mut Ui, v: &View3d) -> Option<J> {
|
||||
let mut l = v.lights.clone();
|
||||
let mut changed = false;
|
||||
section(ui, "ambient", tr("Ambient Light"), |ui| {
|
||||
changed |= crate::widgets::bool_button(ui, tr("Created"), &mut l.ambient_on);
|
||||
ui.add_enabled_ui(l.ambient_on, |ui| {
|
||||
labelled(ui, tr("Color"), |ui| {
|
||||
changed |= crate::widgets::color_strip(ui, "ambient-color", &mut l.ambient, None);
|
||||
});
|
||||
});
|
||||
});
|
||||
for i in 0..2 {
|
||||
section(ui, &format!("point{i}"), &format!("{} {}", tr("Point Light"), i + 1), |ui| {
|
||||
let pl = &mut l.point[i];
|
||||
changed |= crate::widgets::bool_button(ui, tr("Created"), &mut pl.on);
|
||||
ui.add_enabled_ui(pl.on, |ui| {
|
||||
labelled(ui, tr("Color"), |ui| {
|
||||
changed |= crate::widgets::color_strip(ui, &format!("light{i}-color"), &mut pl.color, None);
|
||||
});
|
||||
labelled(ui, tr("Intensity"), |ui| {
|
||||
changed |= crate::widgets::slider(ui, "", &mut pl.intensity, 0.0..=20.0, 2).changed();
|
||||
});
|
||||
labelled(ui, tr("Position (mesh radii from the center)"), |ui| {
|
||||
for (k, axis) in ["X", "Y", "Z"].iter().enumerate() {
|
||||
changed |= crate::widgets::slider(ui, axis, &mut pl.position[k], -10.0..=10.0, 2).changed();
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
changed.then(|| json!({"lights": l}))
|
||||
}
|
||||
|
||||
fn environment(app: &mut MaterialCraftApp, ui: &mut Ui, v: &View3d) -> Option<J> {
|
||||
let mut patch = serde_json::Map::new();
|
||||
let mut enabled = v.env_enabled;
|
||||
if crate::widgets::bool_button(ui, tr("Enabled"), &mut enabled) {
|
||||
patch.insert("envEnabled".into(), json!(enabled));
|
||||
}
|
||||
labelled(ui, tr("Exposure"), |ui| {
|
||||
let mut e = v.exposure;
|
||||
if crate::widgets::slider(ui, "", &mut e, -4.0..=4.0, 2).changed() {
|
||||
patch.insert("exposure".into(), json!(e));
|
||||
}
|
||||
});
|
||||
labelled(ui, tr("Rotation Angle"), |ui| {
|
||||
let mut turns = v.env_rotation / 360.0;
|
||||
let mut degrees = v.env_rotation;
|
||||
ui.horizontal(|ui| {
|
||||
// The dial: drag around it to turn the environment.
|
||||
let (rect, resp) = ui.allocate_exact_size(vec2(56.0, 56.0), egui::Sense::click_and_drag());
|
||||
crate::widgets::name(&resp, egui::Role::Slider, "Rotation dial");
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
let c = rect.center();
|
||||
ui.painter().circle(c, 24.0, tk.row, egui::Stroke::new(1.0, tk.field_border));
|
||||
let a = v.env_rotation.to_radians();
|
||||
ui.painter().line_segment([c, c + vec2(a.cos(), -a.sin()) * 22.0], egui::Stroke::new(2.0, tk.accent));
|
||||
if (resp.dragged() || resp.clicked())
|
||||
&& let Some(p) = resp.interact_pointer_pos()
|
||||
{
|
||||
let d = p - c;
|
||||
let deg = (-d.y).atan2(d.x).to_degrees().rem_euclid(360.0);
|
||||
patch.insert("envRotation".into(), json!(deg));
|
||||
}
|
||||
ui.vertical(|ui| {
|
||||
if crate::widgets::slider(ui, tr("Turns"), &mut turns, 0.0..=1.0, 3).changed() {
|
||||
patch.insert("envRotation".into(), json!(turns * 360.0));
|
||||
}
|
||||
if crate::widgets::slider(ui, tr("Degrees"), &mut degrees, 0.0..=360.0, 1).changed() {
|
||||
patch.insert("envRotation".into(), json!(degrees));
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
labelled(ui, tr("Environment"), |ui| {
|
||||
let cur = materialcraft_engine::view_cmds::ENVIRONMENTS.iter().find(|(id, _)| *id == v.environment).map_or("", |(_, l)| l);
|
||||
let r = egui::ComboBox::from_id_salt("env-pick").width(ui.available_width()).selected_text(tr(cur)).show_ui(ui, |ui| {
|
||||
for (id, label) in materialcraft_engine::view_cmds::ENVIRONMENTS {
|
||||
if ui.selectable_label(v.environment == *id, tr(label)).clicked() {
|
||||
patch.insert("environment".into(), json!(id));
|
||||
}
|
||||
}
|
||||
});
|
||||
crate::widgets::name(&r.response, egui::Role::ComboBox, "Environment");
|
||||
// A strip of the environment: its blurred reflection, as the renderer sees it.
|
||||
let strip = app.thumbs.environment(ui.ctx(), &v.environment);
|
||||
let w = ui.available_width();
|
||||
let (rect, _) = ui.allocate_exact_size(vec2(w, w * 0.5), egui::Sense::hover());
|
||||
match strip {
|
||||
Some(t) => {
|
||||
ui.painter().image(t, rect, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), egui::Color32::WHITE);
|
||||
}
|
||||
None => {
|
||||
ui.painter().rect_filled(rect, 4.0, Tokens::get(ui.ctx()).row);
|
||||
}
|
||||
}
|
||||
let mut show_env = app.view3d.show_env;
|
||||
if ui.checkbox(&mut show_env, tr("Show the environment behind the mesh")).changed() {
|
||||
app.view3d.show_env = show_env;
|
||||
}
|
||||
});
|
||||
(!patch.is_empty()).then_some(J::Object(patch))
|
||||
}
|
||||
|
||||
fn renderer(ui: &mut Ui, v: &View3d) -> Option<J> {
|
||||
let mut r = v.renderer.clone();
|
||||
let mut changed = false;
|
||||
section(ui, "res", tr("Resolution"), |ui| {
|
||||
changed |= crate::widgets::bool_button(ui, tr("Use viewport resolution"), &mut r.use_viewport_resolution);
|
||||
ui.add_enabled_ui(!r.use_viewport_resolution, |ui| {
|
||||
let mut w = r.resolution[0] as f32;
|
||||
let mut h = r.resolution[1] as f32;
|
||||
labelled(ui, tr("Render resolution"), |ui| {
|
||||
if crate::widgets::slider(ui, tr("Width"), &mut w, 16.0..=4096.0, 0).changed()
|
||||
| crate::widgets::slider(ui, tr("Height"), &mut h, 16.0..=4096.0, 0).changed()
|
||||
{
|
||||
r.resolution = [w as u32, h as u32];
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
});
|
||||
labelled(ui, tr("Render resolution scale"), |ui| {
|
||||
let cb =
|
||||
egui::ComboBox::from_id_salt("rend-scale").width(ui.available_width()).selected_text(format!("{:.0} %", r.scale * 100.0)).show_ui(ui, |ui| {
|
||||
for s in [0.25f32, 0.5, 0.75, 1.0, 1.5, 2.0] {
|
||||
if ui.selectable_label((r.scale - s).abs() < 1e-3, format!("{:.0} %", s * 100.0)).clicked() {
|
||||
r.scale = s;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
crate::widgets::name(&cb.response, egui::Role::ComboBox, "Render resolution scale");
|
||||
});
|
||||
});
|
||||
section(ui, "quality", tr("Quality"), |ui| {
|
||||
labelled(ui, tr("Samples per pixel (resting frame)"), |ui| {
|
||||
let mut s = r.samples as f32;
|
||||
if crate::widgets::slider(ui, "", &mut s, 1.0..=4.0, 0).changed() {
|
||||
r.samples = s as u32;
|
||||
changed = true;
|
||||
}
|
||||
ui.label(RichText::new(tr("n × n rays per pixel once the camera rests")).small().color(Tokens::get(ui.ctx()).text_dim));
|
||||
});
|
||||
labelled(ui, tr("Ambient occlusion rays"), |ui| {
|
||||
let mut a = r.ao_rays as f32;
|
||||
if crate::widgets::slider(ui, "", &mut a, 0.0..=32.0, 0).changed() {
|
||||
r.ao_rays = a as u32;
|
||||
changed = true;
|
||||
}
|
||||
ui.label(RichText::new(tr("Ray-traced occlusion in the relief's crevices (0 = off)")).small().color(Tokens::get(ui.ctx()).text_dim));
|
||||
});
|
||||
});
|
||||
changed.then(|| json!({"renderer": r}))
|
||||
}
|
||||
|
||||
fn material(ui: &mut Ui, v: &View3d) -> Option<J> {
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
let mut m = v.material.clone();
|
||||
let mut changed = false;
|
||||
let mut extra = serde_json::Map::new();
|
||||
ui.label(RichText::new(format!("{} / {}", tr("OpenPBR"), tr("Tessellation + Displacement"))).color(tk.text_dim));
|
||||
let weight = |ui: &mut Ui, id: &str, label: &str, value: &mut f32, use_map: Option<&mut bool>, changed: &mut bool| {
|
||||
*changed |= common_label(ui, label, use_map);
|
||||
*changed |= crate::widgets::gray_strip(ui, id, value);
|
||||
};
|
||||
let color = |ui: &mut Ui, id: &str, label: &str, value: &mut [f32; 3], use_map: Option<&mut bool>, changed: &mut bool| {
|
||||
*changed |= common_label(ui, label, use_map);
|
||||
*changed |= crate::widgets::color_strip(ui, id, value, None);
|
||||
};
|
||||
let scalar = |ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive<f32>, changed: &mut bool| {
|
||||
common_label(ui, label, None);
|
||||
*changed |= crate::widgets::slider(ui, "", value, range, 2).changed();
|
||||
};
|
||||
section(ui, "uvs", tr("UVs"), |ui| {
|
||||
labelled(ui, tr("Tiling"), |ui| {
|
||||
let mut t = v.tiling;
|
||||
if crate::widgets::slider(ui, "", &mut t, 0.25..=16.0, 2).changed() {
|
||||
extra.insert("tiling".into(), json!(t));
|
||||
}
|
||||
});
|
||||
labelled(ui, tr("UV scale"), |ui| {
|
||||
changed |= crate::widgets::slider(ui, "U", &mut m.uv_scale[0], 0.1..=8.0, 2).changed();
|
||||
changed |= crate::widgets::slider(ui, "V", &mut m.uv_scale[1], 0.1..=8.0, 2).changed();
|
||||
});
|
||||
});
|
||||
let c = &mut m.common;
|
||||
let u = &mut m.use_map;
|
||||
section(ui, "base", tr("Base"), |ui| {
|
||||
weight(ui, "base-weight", tr("Weight"), &mut c.base_weight, None, &mut changed);
|
||||
color(ui, "base-color", tr("Color"), &mut c.base_color, Some(&mut u.base_color), &mut changed);
|
||||
weight(ui, "metalness", tr("Metalness"), &mut c.metalness, Some(&mut u.metallic), &mut changed);
|
||||
weight(ui, "diffuse-rough", tr("Diffuse roughness"), &mut c.diffuse_roughness, None, &mut changed);
|
||||
});
|
||||
section(ui, "specular", tr("Specular"), |ui| {
|
||||
weight(ui, "spec-weight", tr("Weight"), &mut c.specular_weight, Some(&mut u.specular), &mut changed);
|
||||
color(ui, "spec-color", tr("Color"), &mut c.specular_color, None, &mut changed);
|
||||
weight(ui, "spec-rough", tr("Roughness"), &mut c.specular_roughness, Some(&mut u.roughness), &mut changed);
|
||||
scalar(ui, tr("IOR"), &mut c.ior, 1.0..=3.0, &mut changed);
|
||||
});
|
||||
section(ui, "transmission", tr("Transmission"), |ui| {
|
||||
weight(ui, "trans-weight", tr("Weight"), &mut c.transmission_weight, None, &mut changed);
|
||||
color(ui, "trans-color", tr("Color"), &mut c.transmission_color, None, &mut changed);
|
||||
});
|
||||
section(ui, "subsurface", tr("Subsurface"), |ui| {
|
||||
weight(ui, "sss-weight", tr("Weight"), &mut c.subsurface_weight, None, &mut changed);
|
||||
color(ui, "sss-color", tr("Color"), &mut c.subsurface_color, None, &mut changed);
|
||||
});
|
||||
section(ui, "coat", tr("Coat"), |ui| {
|
||||
weight(ui, "coat-weight", tr("Weight"), &mut c.coat_weight, None, &mut changed);
|
||||
color(ui, "coat-color", tr("Color"), &mut c.coat_color, None, &mut changed);
|
||||
weight(ui, "coat-rough", tr("Roughness"), &mut c.coat_roughness, None, &mut changed);
|
||||
scalar(ui, tr("IOR"), &mut c.coat_ior, 1.0..=3.0, &mut changed);
|
||||
weight(ui, "coat-dark", tr("Darkening"), &mut c.coat_darkening, None, &mut changed);
|
||||
});
|
||||
section(ui, "fuzz", tr("Fuzz"), |ui| {
|
||||
weight(ui, "fuzz-weight", tr("Weight"), &mut c.fuzz_weight, None, &mut changed);
|
||||
color(ui, "fuzz-color", tr("Color"), &mut c.fuzz_color, None, &mut changed);
|
||||
});
|
||||
section(ui, "emission", tr("Emission"), |ui| {
|
||||
common_label(ui, tr("Luminance"), Some(&mut u.emissive));
|
||||
changed |= crate::widgets::slider(ui, "", &mut c.emission_luminance, 0.0..=10.0, 2).changed();
|
||||
color(ui, "emit-color", tr("Color"), &mut c.emission_color, None, &mut changed);
|
||||
});
|
||||
section(ui, "thinfilm", tr("Thin-film"), |ui| {
|
||||
weight(ui, "film-weight", tr("Weight"), &mut c.thin_film_weight, None, &mut changed);
|
||||
common_label(ui, tr("Thickness (nm)"), None);
|
||||
changed |= crate::widgets::slider(ui, "", &mut c.thin_film_thickness, 0.0..=2000.0, 0).changed();
|
||||
scalar(ui, tr("IOR"), &mut c.thin_film_ior, 1.0..=3.0, &mut changed);
|
||||
});
|
||||
section(ui, "geometry", tr("Geometry"), |ui| {
|
||||
weight(ui, "opacity", tr("Opacity"), &mut c.opacity, Some(&mut u.opacity), &mut changed);
|
||||
common_label(ui, tr("Thin walled"), None);
|
||||
let mut tw = c.thin_walled;
|
||||
if crate::widgets::bool_button(ui, "", &mut tw) {
|
||||
c.thin_walled = tw;
|
||||
changed = true;
|
||||
}
|
||||
common_label(ui, tr("DirectX normal"), Some(&mut u.normal));
|
||||
let mut flip = v.normal_y_flip;
|
||||
if crate::widgets::bool_button(ui, "", &mut flip) {
|
||||
extra.insert("normalYFlip".into(), json!(flip));
|
||||
}
|
||||
weight(ui, "ao", tr("Ambient occlusion"), &mut c.ambient_occlusion, Some(&mut u.ao), &mut changed);
|
||||
});
|
||||
section(ui, "height", tr("Height"), |ui| {
|
||||
weight(ui, "height", tr("Height"), &mut c.height, Some(&mut u.height), &mut changed);
|
||||
common_label(ui, tr("Height scale"), None);
|
||||
let mut hs = v.height_scale * 100.0;
|
||||
if crate::widgets::slider(ui, "", &mut hs, 0.0..=50.0, 1).changed() {
|
||||
extra.insert("heightScale".into(), json!(hs / 100.0));
|
||||
}
|
||||
ui.label(RichText::new(tr("% of the mesh size")).small().color(tk.text_dim));
|
||||
common_label(ui, tr("Height level"), None);
|
||||
let mut hl = v.height_level;
|
||||
if crate::widgets::slider(ui, "", &mut hl, 0.0..=1.0, 2).changed() {
|
||||
extra.insert("heightLevel".into(), json!(hl));
|
||||
}
|
||||
common_label(ui, tr("Tessellation factor"), None);
|
||||
changed |= crate::widgets::slider(ui, "", &mut m.tessellation, 0.1..=4.0, 2).changed();
|
||||
ui.label(RichText::new(tr("Multiplies the displaced mesh's triangle budget")).small().color(tk.text_dim));
|
||||
});
|
||||
if changed {
|
||||
extra.insert("material".into(), json!(m));
|
||||
}
|
||||
(!extra.is_empty()).then_some(J::Object(extra))
|
||||
}
|
||||
@@ -242,3 +242,186 @@ pub fn panel_header(ui: &mut Ui, title: &str, trailing: impl FnOnce(&mut Ui)) {
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), trailing);
|
||||
});
|
||||
}
|
||||
|
||||
/// How the colour strip's channel sliders read: sRGB 0..255, linear floats or HSV.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
enum ColorMode {
|
||||
#[default]
|
||||
Srgb,
|
||||
Float,
|
||||
Hsv,
|
||||
}
|
||||
|
||||
/// A colour row as the 3D view's property pages show it: a swatch (click opens the picker), a
|
||||
/// hue strip (click or drag sets the hue), then sRGB / Float / HSV sliders for the channels.
|
||||
/// `linear` is linear RGB; `alpha` adds a fourth slider. Returns true when the colour changed.
|
||||
pub fn color_strip(ui: &mut Ui, id: &str, linear: &mut [f32; 3], alpha: Option<&mut f32>) -> bool {
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
let mode_id = ui.make_persistent_id((id, "color-mode"));
|
||||
let mut mode: ColorMode = ui.data(|d| d.get_temp(mode_id)).unwrap_or_default();
|
||||
let mut changed = false;
|
||||
ui.horizontal(|ui| {
|
||||
changed |= color_swatch(ui, id, linear, 22.0);
|
||||
// Hue strip.
|
||||
let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width().max(60.0), 18.0), Sense::click_and_drag());
|
||||
name(&resp, egui::Role::Slider, "Hue");
|
||||
let steps = 24;
|
||||
for i in 0..steps {
|
||||
let (a, b) = (i as f32 / steps as f32, (i + 1) as f32 / steps as f32);
|
||||
let r = egui::Rect::from_min_max(
|
||||
egui::pos2(rect.left() + rect.width() * a, rect.top()),
|
||||
egui::pos2(rect.left() + rect.width() * b + 0.5, rect.bottom()),
|
||||
);
|
||||
let c = egui::ecolor::Hsva::new(a + 0.5 / steps as f32, 1.0, 1.0, 1.0);
|
||||
ui.painter().rect_filled(r, 0.0, Color32::from(c));
|
||||
}
|
||||
ui.painter().rect_stroke(rect, 2.0, Stroke::new(1.0, tk.field_border), egui::StrokeKind::Inside);
|
||||
let srgb = linear.map(materialcraft_engine::image::linear_to_srgb);
|
||||
let mut hsv = egui::ecolor::Hsva::from_rgb(srgb);
|
||||
let hx = rect.left() + rect.width() * hsv.h;
|
||||
ui.painter().line_segment([egui::pos2(hx, rect.top()), egui::pos2(hx, rect.bottom())], Stroke::new(2.0, Color32::WHITE));
|
||||
if (resp.clicked() || resp.dragged())
|
||||
&& let Some(p) = resp.interact_pointer_pos()
|
||||
{
|
||||
hsv.h = ((p.x - rect.left()) / rect.width().max(1.0)).clamp(0.0, 1.0);
|
||||
if hsv.s <= 0.0 {
|
||||
hsv.s = 1.0;
|
||||
}
|
||||
if hsv.v <= 0.0 {
|
||||
hsv.v = 1.0;
|
||||
}
|
||||
let rgb = hsv.to_rgb();
|
||||
*linear = rgb.map(materialcraft_engine::image::srgb_to_linear);
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
ui.horizontal_top(|ui| {
|
||||
ui.vertical(|ui| {
|
||||
for (m, label) in [(ColorMode::Srgb, "sRGB"), (ColorMode::Float, "Float"), (ColorMode::Hsv, "HSV")] {
|
||||
if ui.add(egui::Button::new(label).selected(mode == m).min_size(vec2(46.0, 18.0))).clicked() {
|
||||
mode = m;
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.vertical(|ui| {
|
||||
let srgb = linear.map(materialcraft_engine::image::linear_to_srgb);
|
||||
match mode {
|
||||
ColorMode::Srgb => {
|
||||
let mut v = srgb.map(|c| (c * 255.0).round());
|
||||
let mut dirty = false;
|
||||
for (i, ch) in ["R", "G", "B"].iter().enumerate() {
|
||||
dirty |= slider(ui, ch, &mut v[i], 0.0..=255.0, 0).changed();
|
||||
}
|
||||
if dirty {
|
||||
*linear = v.map(|c| materialcraft_engine::image::srgb_to_linear(c / 255.0));
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
ColorMode::Float => {
|
||||
let mut dirty = false;
|
||||
for (i, ch) in ["R", "G", "B"].iter().enumerate() {
|
||||
dirty |= slider(ui, ch, &mut linear[i], 0.0..=1.0, 3).changed();
|
||||
}
|
||||
changed |= dirty;
|
||||
}
|
||||
ColorMode::Hsv => {
|
||||
let hsv = egui::ecolor::Hsva::from_rgb(srgb);
|
||||
let mut v = [hsv.h * 360.0, hsv.s * 100.0, hsv.v * 100.0];
|
||||
let mut dirty = false;
|
||||
dirty |= slider(ui, "H", &mut v[0], 0.0..=360.0, 0).changed();
|
||||
dirty |= slider(ui, "S", &mut v[1], 0.0..=100.0, 0).changed();
|
||||
dirty |= slider(ui, "V", &mut v[2], 0.0..=100.0, 0).changed();
|
||||
if dirty {
|
||||
let rgb = egui::ecolor::Hsva::new(v[0] / 360.0, v[1] / 100.0, v[2] / 100.0, 1.0).to_rgb();
|
||||
*linear = rgb.map(materialcraft_engine::image::srgb_to_linear);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(a) = alpha {
|
||||
let mut v = if mode == ColorMode::Float { *a } else { (*a * 255.0).round() };
|
||||
let (hi, dec) = if mode == ColorMode::Float { (1.0, 3) } else { (255.0, 0) };
|
||||
if slider(ui, "A", &mut v, 0.0..=hi, dec).changed() {
|
||||
*a = if mode == ColorMode::Float { v } else { v / 255.0 };
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
ui.data_mut(|d| d.insert_temp(mode_id, mode));
|
||||
changed
|
||||
}
|
||||
|
||||
/// A grey value row like [`color_strip`]: swatch, black-to-white strip and an "L" slider
|
||||
/// (sRGB 0..255 or float). `value` is linear 0..1. Returns true when it changed.
|
||||
pub fn gray_strip(ui: &mut Ui, id: &str, value: &mut f32) -> bool {
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
let mode_id = ui.make_persistent_id((id, "gray-mode"));
|
||||
let mut float_mode: bool = ui.data(|d| d.get_temp(mode_id)).unwrap_or(false);
|
||||
let mut changed = false;
|
||||
ui.horizontal(|ui| {
|
||||
let mut rgb = [*value; 3];
|
||||
if color_swatch(ui, id, &mut rgb, 22.0) {
|
||||
*value = (rgb[0] + rgb[1] + rgb[2]) / 3.0;
|
||||
changed = true;
|
||||
}
|
||||
let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width().max(60.0), 18.0), Sense::click_and_drag());
|
||||
name(&resp, egui::Role::Slider, "Value");
|
||||
let steps = 16;
|
||||
for i in 0..steps {
|
||||
let (a, b) = (i as f32 / steps as f32, (i + 1) as f32 / steps as f32);
|
||||
let r = egui::Rect::from_min_max(
|
||||
egui::pos2(rect.left() + rect.width() * a, rect.top()),
|
||||
egui::pos2(rect.left() + rect.width() * b + 0.5, rect.bottom()),
|
||||
);
|
||||
let g = (materialcraft_engine::image::linear_to_srgb(a + 0.5 / steps as f32) * 255.0) as u8;
|
||||
ui.painter().rect_filled(r, 0.0, Color32::from_gray(g));
|
||||
}
|
||||
ui.painter().rect_stroke(rect, 2.0, Stroke::new(1.0, tk.field_border), egui::StrokeKind::Inside);
|
||||
let x = rect.left() + rect.width() * value.clamp(0.0, 1.0);
|
||||
ui.painter().line_segment([egui::pos2(x, rect.top()), egui::pos2(x, rect.bottom())], Stroke::new(2.0, tk.accent));
|
||||
if (resp.clicked() || resp.dragged())
|
||||
&& let Some(p) = resp.interact_pointer_pos()
|
||||
{
|
||||
*value = ((p.x - rect.left()) / rect.width().max(1.0)).clamp(0.0, 1.0);
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
ui.horizontal_top(|ui| {
|
||||
ui.vertical(|ui| {
|
||||
if ui.add(egui::Button::new("sRGB").selected(!float_mode).min_size(vec2(46.0, 18.0))).clicked() {
|
||||
float_mode = false;
|
||||
}
|
||||
if ui.add(egui::Button::new("Float").selected(float_mode).min_size(vec2(46.0, 18.0))).clicked() {
|
||||
float_mode = true;
|
||||
}
|
||||
});
|
||||
ui.vertical(|ui| {
|
||||
if float_mode {
|
||||
changed |= slider(ui, "L", value, 0.0..=1.0, 3).changed();
|
||||
} else {
|
||||
let mut v = (materialcraft_engine::image::linear_to_srgb(*value) * 255.0).round();
|
||||
if slider(ui, "L", &mut v, 0.0..=255.0, 0).changed() {
|
||||
*value = materialcraft_engine::image::srgb_to_linear(v / 255.0);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
ui.data_mut(|d| d.insert_temp(mode_id, float_mode));
|
||||
changed
|
||||
}
|
||||
|
||||
/// A two-state "True / False" button like the 3D view property pages. Returns true when toggled.
|
||||
pub fn bool_button(ui: &mut Ui, label: &str, value: &mut bool) -> bool {
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
ui.label(RichText::new(label).color(tk.text));
|
||||
let text = if *value { "True" } else { "False" };
|
||||
let r = ui.add(egui::Button::new(text).min_size(vec2(ui.available_width().max(60.0), 20.0)));
|
||||
name(&r, egui::Role::CheckBox, label);
|
||||
if r.clicked() {
|
||||
*value = !*value;
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
+238
-93
@@ -13,7 +13,7 @@ use serde_json::{Value, json};
|
||||
|
||||
use crate::MaterialCraftApp;
|
||||
use crate::i18n::tr;
|
||||
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)]
|
||||
@@ -85,7 +85,7 @@ pub fn show(app: &mut MaterialCraftApp, ctx: &egui::Context) {
|
||||
export(app, ctx);
|
||||
}
|
||||
if app.ui.windows.preferences {
|
||||
preferences(app, ctx);
|
||||
crate::preferences::show(app, ctx);
|
||||
}
|
||||
if app.ui.windows.about {
|
||||
about(app, ctx);
|
||||
@@ -96,10 +96,27 @@ pub fn show(app: &mut MaterialCraftApp, ctx: &egui::Context) {
|
||||
if app.ui.windows.home {
|
||||
home(app, ctx);
|
||||
}
|
||||
if app.ui.windows.switch_engine {
|
||||
crate::tool_windows::switch_engine(app, ctx);
|
||||
}
|
||||
if app.ui.windows.dependencies {
|
||||
crate::tool_windows::dependencies(app, ctx);
|
||||
}
|
||||
if app.ui.windows.plugin_manager {
|
||||
crate::plugins::window(app, ctx);
|
||||
}
|
||||
if app.import_pick.is_some() {
|
||||
crate::tool_windows::import_pick(app, ctx);
|
||||
}
|
||||
crate::unsaved::show(app, ctx);
|
||||
}
|
||||
|
||||
fn modal(ctx: &egui::Context, id: &str, title: &str, open: &mut bool, size: egui::Vec2, body: impl FnOnce(&mut Ui)) {
|
||||
/// Help ▸ Export log.
|
||||
pub fn export_log(app: &mut MaterialCraftApp) {
|
||||
crate::tool_windows::export_log(app);
|
||||
}
|
||||
|
||||
pub(crate) fn modal(ctx: &egui::Context, id: &str, title: &str, open: &mut bool, size: egui::Vec2, body: impl FnOnce(&mut Ui)) {
|
||||
egui::Window::new(title)
|
||||
.id(egui::Id::unique(id))
|
||||
.open(open)
|
||||
@@ -111,49 +128,106 @@ fn modal(ctx: &egui::Context, id: &str, title: &str, open: &mut bool, size: egui
|
||||
.show(ctx, body);
|
||||
}
|
||||
|
||||
/// Template groups for the new graph dialog: (group, template ids).
|
||||
fn template_groups() -> Vec<(&'static str, Vec<(&'static str, &'static str)>)> {
|
||||
let mut starter = Vec::new();
|
||||
let mut materials = Vec::new();
|
||||
for t in materialcraft_engine::samples::TEMPLATES {
|
||||
if matches!(t.0, "empty" | "pbr") { starter.push(*t) } else { materials.push(*t) }
|
||||
}
|
||||
vec![("Starter", starter), ("Materials", materials)]
|
||||
}
|
||||
|
||||
/// What a template holds (the ⓘ in the new graph dialog).
|
||||
fn template_info(id: &str) -> &'static str {
|
||||
match id {
|
||||
"empty" => "A graph with no nodes: start from the library.",
|
||||
"pbr" => "The PBR outputs (Base Color, Normal, Roughness, Metallic, Height, Ambient Occlusion) with nothing wired yet.",
|
||||
"bricks" => "A tiling brick wall: Tile Generator, mortar, edge wear and colour variation.",
|
||||
"stone_tiles" => "Irregular stone tiles with grout, bevelled edges and dirt in the gaps.",
|
||||
"wood" => "Wooden planks with grain, knots and gaps between boards.",
|
||||
"metal_plates" => "Painted metal plates with rivets, scratches and chipped edges.",
|
||||
"rusty_metal" => "Sheet metal with rust spreading from the edges and a worn finish.",
|
||||
"lava" => "Dark cooled rock with glowing cracks (an emissive output).",
|
||||
"marble" => "Polished marble with veins and a glossy roughness.",
|
||||
"wicker" => "A woven wicker weave with height and ambient occlusion.",
|
||||
"fabric" => "Woven fabric fibres with a tiling thread pattern.",
|
||||
"ground" => "Mossy ground: soil, pebbles and moss in the hollows.",
|
||||
_ => "A graph template.",
|
||||
}
|
||||
}
|
||||
|
||||
fn new_graph(app: &mut MaterialCraftApp, ctx: &egui::Context) {
|
||||
let mut open = true;
|
||||
let mut create = false;
|
||||
modal(ctx, "new-graph", tr("New graph"), &mut open, vec2(640.0, 490.0), |ui| {
|
||||
modal(ctx, "new-graph", tr("New graph"), &mut open, vec2(680.0, 520.0), |ui| {
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
ui.horizontal_top(|ui| {
|
||||
ui.vertical(|ui| {
|
||||
ui.set_width(400.0);
|
||||
ui.label(RichText::new(tr("Templates")).strong());
|
||||
// Three rows of templates without scrolling.
|
||||
egui::ScrollArea::vertical().max_height(400.0).show(ui, |ui| {
|
||||
for row in materialcraft_engine::samples::TEMPLATES.chunks(4) {
|
||||
ui.horizontal(|ui| {
|
||||
for (id, label) in row {
|
||||
let on = app.ui.new_graph_template == *id;
|
||||
let (r, resp) = ui.allocate_exact_size(vec2(94.0, 124.0), egui::Sense::click());
|
||||
crate::widgets::name(&resp, egui::Role::ListItem, label);
|
||||
if on {
|
||||
ui.painter().rect_filled(r, 6.0, tk.row_selected);
|
||||
ui.painter().rect_stroke(r, 6.0, egui::Stroke::new(1.5, tk.accent), egui::StrokeKind::Inside);
|
||||
} else if resp.hovered() {
|
||||
ui.painter().rect_filled(r, 6.0, tk.row_hover);
|
||||
}
|
||||
let img = egui::Rect::from_min_size(r.min + vec2(7.0, 6.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);
|
||||
ui.set_width(420.0);
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(RichText::new(tr("Category")).strong());
|
||||
let shown = if app.ui.new_graph_category.is_empty() { tr("All").to_string() } else { tr(&app.ui.new_graph_category).to_string() };
|
||||
let r = egui::ComboBox::from_id_salt("new-category").selected_text(shown).show_ui(ui, |ui| {
|
||||
ui.selectable_value(&mut app.ui.new_graph_category, String::new(), tr("All"));
|
||||
for (group, _) in template_groups() {
|
||||
ui.selectable_value(&mut app.ui.new_graph_category, group.to_string(), tr(group));
|
||||
}
|
||||
});
|
||||
crate::widgets::name(&r.response, egui::Role::ComboBox, "Category");
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
egui::ScrollArea::vertical().max_height(410.0).show(ui, |ui| {
|
||||
for (group, templates) in template_groups() {
|
||||
if !app.ui.new_graph_category.is_empty() && app.ui.new_graph_category != group {
|
||||
continue;
|
||||
}
|
||||
ui.label(RichText::new(tr(group)).small().strong().color(tk.text_dim));
|
||||
for row in templates.chunks(4) {
|
||||
ui.horizontal(|ui| {
|
||||
for (id, label) in row {
|
||||
let on = app.ui.new_graph_template == *id;
|
||||
let (r, resp) = ui.allocate_exact_size(vec2(98.0, 124.0), egui::Sense::click());
|
||||
crate::widgets::name(&resp, egui::Role::ListItem, label);
|
||||
if on {
|
||||
ui.painter().rect_filled(r, 6.0, tk.row_selected);
|
||||
ui.painter().rect_stroke(r, 6.0, egui::Stroke::new(1.5, tk.accent), egui::StrokeKind::Inside);
|
||||
} else if resp.hovered() {
|
||||
ui.painter().rect_filled(r, 6.0, tk.row_hover);
|
||||
}
|
||||
None => {
|
||||
ui.painter().circle_filled(img.center(), 36.0, tk.row);
|
||||
let img = egui::Rect::from_min_size(r.min + vec2(9.0, 6.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);
|
||||
}
|
||||
}
|
||||
// ⓘ in the corner: what the template holds.
|
||||
let info = egui::Rect::from_center_size(img.right_top() + vec2(-8.0, 8.0), vec2(16.0, 16.0));
|
||||
let info_resp = ui.interact(info, resp.id.with("info"), egui::Sense::hover());
|
||||
ui.painter().text(
|
||||
info.center(),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
icon::INFO,
|
||||
egui::FontId::proportional(13.0),
|
||||
if info_resp.hovered() { tk.text_strong } else { tk.text_dim },
|
||||
);
|
||||
info_resp.on_hover_text(tr(template_info(id)));
|
||||
let g = ui.painter().layout(tr(label).to_string(), egui::FontId::proportional(11.0), tk.text, 94.0);
|
||||
ui.painter().galley(egui::pos2(r.center().x - g.size().x * 0.5, img.bottom() + 6.0), g, tk.text);
|
||||
if resp.clicked() {
|
||||
app.ui.new_graph_template = id.to_string();
|
||||
app.ui.new_graph_name = label.replace(' ', "_");
|
||||
}
|
||||
if resp.double_clicked() {
|
||||
create = true;
|
||||
}
|
||||
}
|
||||
let g = ui.painter().layout(tr(label).to_string(), egui::FontId::proportional(11.0), tk.text, 90.0);
|
||||
ui.painter().galley(egui::pos2(r.center().x - g.size().x * 0.5, img.bottom() + 6.0), g, tk.text);
|
||||
if resp.clicked() {
|
||||
app.ui.new_graph_template = id.to_string();
|
||||
app.ui.new_graph_name = label.replace(' ', "_");
|
||||
}
|
||||
if resp.double_clicked() {
|
||||
create = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
ui.add_space(6.0);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -163,15 +237,46 @@ fn new_graph(app: &mut MaterialCraftApp, ctx: &egui::Context) {
|
||||
ui.text_edit_singleline(&mut app.ui.new_graph_name);
|
||||
ui.add_space(8.0);
|
||||
ui.label(RichText::new(tr("Size")).strong());
|
||||
let r = egui::ComboBox::from_id_salt("new-size").selected_text(format!("{} px", app.ui.new_graph_size)).show_ui(ui, |ui| {
|
||||
for s in [256u32, 512, 1024, 2048, 4096] {
|
||||
ui.selectable_value(&mut app.ui.new_graph_size, s, format!("{s} px"));
|
||||
let sizes = [16u32, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192];
|
||||
ui.horizontal(|ui| {
|
||||
let r = egui::ComboBox::from_id_salt("new-size").width(90.0).selected_text(format!("{} px", app.ui.new_graph_size)).show_ui(ui, |ui| {
|
||||
for s in sizes {
|
||||
ui.selectable_value(&mut app.ui.new_graph_size, s, format!("{s} px"));
|
||||
}
|
||||
});
|
||||
crate::widgets::name(&r.response, egui::Role::ComboBox, "Size");
|
||||
if crate::widgets::icon_button(
|
||||
ui,
|
||||
if app.ui.new_graph_link { icon::LINK } else { icon::LINK_BREAK },
|
||||
tr("Link width and height"),
|
||||
app.ui.new_graph_link,
|
||||
20.0,
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
app.ui.new_graph_link = !app.ui.new_graph_link;
|
||||
if !app.ui.new_graph_link && app.ui.new_graph_height == 0 {
|
||||
app.ui.new_graph_height = app.ui.new_graph_size;
|
||||
}
|
||||
}
|
||||
let height = if app.ui.new_graph_link || app.ui.new_graph_height == 0 { app.ui.new_graph_size } else { app.ui.new_graph_height };
|
||||
ui.add_enabled_ui(!app.ui.new_graph_link, |ui| {
|
||||
let r = egui::ComboBox::from_id_salt("new-height").width(90.0).selected_text(format!("{height} px")).show_ui(ui, |ui| {
|
||||
for s in sizes {
|
||||
ui.selectable_value(&mut app.ui.new_graph_height, s, format!("{s} px"));
|
||||
}
|
||||
});
|
||||
crate::widgets::name(&r.response, egui::Role::ComboBox, "Height");
|
||||
});
|
||||
});
|
||||
crate::widgets::name(&r.response, egui::Role::ComboBox, "Size");
|
||||
ui.label(RichText::new(tr("width × height")).small().color(tk.text_dim));
|
||||
ui.add_space(8.0);
|
||||
ui.label(RichText::new(tr("Create graph in")).strong());
|
||||
ui.label(&app.session.pkg.name);
|
||||
let r = egui::ComboBox::from_id_salt("new-package").selected_text(&app.session.pkg.name).show_ui(ui, |ui| {
|
||||
let _ = ui.selectable_label(true, &app.session.pkg.name);
|
||||
});
|
||||
crate::widgets::name(&r.response, egui::Role::ComboBox, "Create graph in");
|
||||
ui.label(RichText::new(tr("The open package (File ▸ New ▸ Empty package starts another)")).small().color(tk.text_dim));
|
||||
ui.add_space(20.0);
|
||||
ui.horizontal(|ui| {
|
||||
if ui.add(crate::widgets::primary_button(ui, tr("Create"))).clicked() {
|
||||
@@ -187,6 +292,9 @@ fn new_graph(app: &mut MaterialCraftApp, ctx: &egui::Context) {
|
||||
if create {
|
||||
let p = json!({"template": app.ui.new_graph_template, "name": app.ui.new_graph_name, "size": app.ui.new_graph_size});
|
||||
if app.run("file.new", p).is_some() {
|
||||
if !app.ui.new_graph_link && app.ui.new_graph_height != 0 && app.ui.new_graph_height != app.ui.new_graph_size {
|
||||
app.run("graph.size", json!({"width": app.ui.new_graph_size, "height": app.ui.new_graph_height}));
|
||||
}
|
||||
app.ui.frame_all = true;
|
||||
open = false;
|
||||
}
|
||||
@@ -285,54 +393,6 @@ fn export(app: &mut MaterialCraftApp, ctx: &egui::Context) {
|
||||
}
|
||||
}
|
||||
|
||||
fn preferences(app: &mut MaterialCraftApp, ctx: &egui::Context) {
|
||||
let mut open = true;
|
||||
modal(ctx, "prefs", tr("Preferences"), &mut open, vec2(380.0, 340.0), |ui| {
|
||||
let p = &mut app.ui.prefs;
|
||||
let current_lang = crate::i18n::current();
|
||||
crate::widgets::combo(ui, tr("Language"), current_lang.name, |ui| {
|
||||
for l in &crate::i18n::LANGUAGES {
|
||||
if ui.selectable_label(p.language == l.code, l.name).clicked() {
|
||||
p.language = l.code.to_owned();
|
||||
crate::i18n::set_language(&p.language);
|
||||
}
|
||||
}
|
||||
});
|
||||
crate::widgets::combo(ui, tr("Brightness"), tr(p.brightness.label()), |ui| {
|
||||
for b in Brightness::ALL {
|
||||
ui.selectable_value(&mut p.brightness, b, tr(b.label()));
|
||||
}
|
||||
});
|
||||
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;
|
||||
}
|
||||
crate::widgets::combo(
|
||||
ui,
|
||||
tr("Preview size while editing"),
|
||||
if p.preview_size == 0 { tr("Full size").to_string() } else { format!("{} px", p.preview_size) },
|
||||
|ui| {
|
||||
for s in [256u32, 512, 1024, 2048, 4096, 0] {
|
||||
let label = if s == 0 { tr("Full size").to_string() } else { format!("{s} px") };
|
||||
ui.selectable_value(&mut p.preview_size, s, label);
|
||||
}
|
||||
},
|
||||
);
|
||||
ui.checkbox(&mut p.thumbnails, tr("Show node thumbnails"));
|
||||
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 !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| {
|
||||
@@ -563,7 +623,8 @@ pub fn file_action(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) ->
|
||||
{
|
||||
match id {
|
||||
"file.open" => {
|
||||
if let Some(p) = rfd::FileDialog::new().add_filter("SBS or MaterialCraft package, or material", OPEN_EXTS).pick_file() {
|
||||
if let Some(p) = dialog(app).add_filter("SBS or MaterialCraft package, or material", OPEN_EXTS).pick_file() {
|
||||
remember_dir(app, &p);
|
||||
open_path(app, &p.display().to_string());
|
||||
}
|
||||
true
|
||||
@@ -578,12 +639,13 @@ pub fn file_action(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) ->
|
||||
}
|
||||
"file.save" | "file.saveAs" => {
|
||||
let name = format!("{}.sbs", materialcraft_engine::formats::safe_file_name(&app.session.pkg.name));
|
||||
if let Some(p) = rfd::FileDialog::new()
|
||||
if let Some(p) = dialog(app)
|
||||
.set_file_name(name)
|
||||
.add_filter("SBS package", &["sbs"])
|
||||
.add_filter("MaterialCraft package (older format)", &["mcraft"])
|
||||
.save_file()
|
||||
{
|
||||
remember_dir(app, &p);
|
||||
let path = materialcraft_engine::file_cmds::package_path(&p.display().to_string());
|
||||
if app.run("file.save", json!({"path": path})).is_some() {
|
||||
app.ui.add_recent(&path);
|
||||
@@ -611,11 +673,65 @@ pub fn file_action(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) ->
|
||||
true
|
||||
}
|
||||
"file.importBitmap" => {
|
||||
if let Some(p) = rfd::FileDialog::new().add_filter("Images", materialcraft_engine::formats::IMAGE_EXTENSIONS).pick_file() {
|
||||
if let Some(p) = dialog(app).add_filter("Images", materialcraft_engine::formats::IMAGE_EXTENSIONS).pick_file() {
|
||||
remember_dir(app, &p);
|
||||
crate::graph_view::import_bitmap_file(app, &p.display().to_string());
|
||||
}
|
||||
true
|
||||
}
|
||||
"file.linkBitmap" => {
|
||||
if let Some(p) = dialog(app).add_filter("Images", materialcraft_engine::formats::IMAGE_EXTENSIONS).pick_file()
|
||||
&& let Some(r) = app.run("file.linkBitmap", json!({"path": p.display().to_string()}))
|
||||
{
|
||||
let name = r["name"].as_str().unwrap_or_default().to_string();
|
||||
app.toast(format!("{} {name}", tr("Linked bitmap")), false);
|
||||
}
|
||||
true
|
||||
}
|
||||
"file.saveCopy" => {
|
||||
let name = format!("{}_copy.sbs", materialcraft_engine::formats::safe_file_name(&app.session.pkg.name));
|
||||
if let Some(p) = dialog(app)
|
||||
.set_file_name(name)
|
||||
.add_filter("SBS package", &["sbs"])
|
||||
.add_filter("MaterialCraft package (older format)", &["mcraft"])
|
||||
.save_file()
|
||||
&& let Some(r) = app.run("file.saveCopy", json!({"path": p.display().to_string()}))
|
||||
{
|
||||
app.toast(format!("{} {}", tr("Saved a copy to"), r["path"].as_str().unwrap_or_default()), false);
|
||||
}
|
||||
true
|
||||
}
|
||||
"file.exportWithDependencies" => {
|
||||
if let Some(dir) = dialog(app).set_title(tr("Folder for the package and its dependencies")).pick_folder()
|
||||
&& let Some(r) = app.run("file.exportWithDependencies", json!({"dir": dir.display().to_string()}))
|
||||
{
|
||||
let n = r["files"].as_array().map_or(0, Vec::len);
|
||||
app.toast(format!("{} {n} {} {}", tr("Exported"), tr("file(s) to"), dir.display()), false);
|
||||
}
|
||||
true
|
||||
}
|
||||
"file.importGraph" => {
|
||||
if let Some(p) = dialog(app).add_filter("Packages", &["sbs", "mcraft"]).pick_file() {
|
||||
remember_dir(app, &p);
|
||||
let path = p.display().to_string();
|
||||
// Several graphs: the picker window asks which; one graph imports at once.
|
||||
match app.run("file.packageGraphs", json!({"path": path})) {
|
||||
Some(list) if list.as_array().is_some_and(|a| a.len() > 1) => {
|
||||
app.import_pick = Some((
|
||||
path,
|
||||
list.as_array().cloned().unwrap_or_default().iter().filter_map(|g| g["name"].as_str().map(str::to_string)).collect(),
|
||||
));
|
||||
}
|
||||
Some(_) => {
|
||||
if let Some(r) = app.run("file.importGraph", json!({"path": path})) {
|
||||
app.toast(format!("{} {}", tr("Imported graph"), r["name"].as_str().unwrap_or_default()), false);
|
||||
}
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
@@ -632,6 +748,35 @@ pub fn file_action(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) ->
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a file dialog opens (Preferences ▸ Save/Export Path): the last folder used, the
|
||||
/// package's folder, or a fixed one.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn dialog_dir(app: &MaterialCraftApp) -> Option<std::path::PathBuf> {
|
||||
let p = &app.ui.prefs;
|
||||
let dir = match p.save_path_mode.as_str() {
|
||||
"package" => app.session.path.as_deref().and_then(|p| std::path::Path::new(p).parent()).map(|p| p.to_path_buf()),
|
||||
"custom" if !p.save_path.trim().is_empty() => Some(std::path::PathBuf::from(p.save_path.trim())),
|
||||
_ => (!app.ui.last_dir.is_empty()).then(|| std::path::PathBuf::from(&app.ui.last_dir)),
|
||||
};
|
||||
dir.filter(|d| d.is_dir())
|
||||
}
|
||||
|
||||
/// A file dialog opening in the preferred folder.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn dialog(app: &MaterialCraftApp) -> rfd::FileDialog {
|
||||
match dialog_dir(app) {
|
||||
Some(d) => rfd::FileDialog::new().set_directory(d),
|
||||
None => rfd::FileDialog::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Remember the folder of a path a dialog gave (Save/Export Path: Last path).
|
||||
pub fn remember_dir(app: &mut MaterialCraftApp, path: &std::path::Path) {
|
||||
if let Some(d) = path.parent().filter(|d| !d.as_os_str().is_empty()) {
|
||||
app.ui.last_dir = d.display().to_string();
|
||||
}
|
||||
}
|
||||
|
||||
/// Open a package from a path (recent list, drag and drop, command line). Asks first when the
|
||||
/// open package has unsaved changes.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
|
||||
@@ -81,7 +81,14 @@ Types: `move`, `down`, `up`, `click`, `doubleClick`, `drag`, `scroll`, `key` (eg
|
||||
| `graph.preset.save` / `.apply` / `.delete` | `{name}`: store, restore or remove the current input values |
|
||||
| `graph.createFromSelection` | `{name?, ids?}`: move nodes into a sub-graph and replace them with an instance |
|
||||
| `view.2d` / `view.3d` | which node the 2D view shows, channel, tiling, histogram; scene, environment, camera, tiling, `heightScale` (how far the height output raises the mesh, in mesh radii) and `heightLevel` (the height that stays on the surface; 0 = the relief rises out of it), `normalYFlip` (interpret DirectX normal maps; default false/OpenGL), `transparency` (see through where the alpha is below one: the opacity output, else the base color's alpha), `alphaView` (show the alpha channel) |
|
||||
| `view.3d` (nested) | `camera? {focalLength, projection, background, backgroundColor, overrideResolution, resolution, resolutionScale, autoClip, near, far}`, `lights? {ambientOn, ambient, point: [{on, color, intensity, position}, …]}`, `renderer? {useViewportResolution, resolution, scale, samples, aoRays}`, `display? {wireframe, backfaceCulling, boundingBox, lights, resolution, stats, fps}`, `material? {shader, common: {…}, useMap: {…}, tessellation, uvScale}`, `envEnabled?`: the keys given change, the rest stays; values are clamped |
|
||||
| `view.3d.reset` / `view.3d.state` / `view.3d.loadState` | `{what?: all\|scene\|camera\|lights\|environment\|material\|renderer\|display}` / `{}` → the state as JSON / `{state, keepScene?}` |
|
||||
| `view.3d.loadMesh` | `{path}` shows an OBJ, glTF or GLB mesh (scene `custom`) |
|
||||
| `file.linkBitmap` / `file.reloadResources` / `file.deleteResource` | `{path, name?}` a bitmap read from disk (a relative link when it lies in the package's folder) / `{}` / `{name}` |
|
||||
| `file.importGraph` / `file.packageGraphs` | `{path, graph?}` copies a graph with its instances and bitmaps from another package / `{path}` lists a package file's graphs |
|
||||
| `file.saveCopy` / `file.exportWithDependencies` | `{path}` / `{dir}` the package and copies of its linked bitmaps |
|
||||
| `graph.add` | `{graph}`: a graph as JSON, added under a unique name |
|
||||
| `session.settings` | `{historySize?, cacheMb?, cookLimit?}` (preferences) |
|
||||
| `library.list` | `{filter?, category?}`: every node with ports and parameters |
|
||||
|
||||
## Function graphs
|
||||
|
||||
+4
-3
@@ -1,19 +1,19 @@
|
||||
# Gaps
|
||||
|
||||
> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-02 · **Change:** minor (portable `.mcmat` materials closed the published-archive gap) · **Target:** the professional node-based material workflow
|
||||
> **Last reviewed:** 2026-11-06 · **Last updated:** 2026-11-06 · **Change:** major (lights, shaders, material common values and view-state files closed most of the 3D view gap; node shortcuts closed part of the keymap gap) · **Target:** the professional node-based material workflow
|
||||
|
||||
Every known shortfall, most important first. Pick from the top.
|
||||
|
||||
| # | Gap | Evidence | Impact | Estimate | Parity doc |
|
||||
|---:|---|---|---|---:|---|
|
||||
| 1 | Node library breadth | 227 nodes vs. ~400 in the reference library | Recipes that need scan processing, more grunges, splines or SDF shapes | 30 h | target-app-parity (Node library) |
|
||||
| 2 | GPU 3D view with tessellation and lights | CPU renderer; the height output displaces a subdivided mesh (up to 500k triangles) | GPU tessellation, light setups | 12 h | target-app-parity (3D view) |
|
||||
| 2 | GPU 3D view | CPU ray caster with lights, shaders and displacement (a tessellation factor scales the triangle budget) | Large meshes and high sample counts are slow; no path tracing | 12 h | target-app-parity (3D view) |
|
||||
| 3 | Mesh-based generators and bakers | None | Workflows that start from a mesh | 15 h | target-app-parity (Node library) |
|
||||
| 4 | Portable materials over MCP | `.mcmat` export runs from the app and the CLI; the MCP workspace sandbox refuses `file.*` commands and has no `material_export` tool | Sandboxed agents can't hand a material to TextureCraft | 1 h | target-app-parity (Files) |
|
||||
| 5 | Function loops and reusable functions | Functions live on one parameter or processor | Iterative effects; sharing logic between nodes | 5 h | target-app-parity (Function graphs) |
|
||||
| 6 | Input visibility conditions, per-instance output sizes | Not implemented | Organizing large graphs' inputs | 4 h | target-app-parity (Graph parameters) |
|
||||
| 7 | `ui.screenshot` times out on this test machine | The window-capture callback never fires here; `view.screenshot` and the offscreen snapshot test work | Agents bridged to the app see views but not the whole window | 1 h | — |
|
||||
| 8 | Translations and keymap editor | English only, fixed shortcuts | Non-English users; custom shortcuts | 8 h | localization-parity |
|
||||
| 8 | Translations and a menu keymap editor | English only; node creation shortcuts are editable, menu shortcuts are fixed | Non-English users; custom menu shortcuts | 7 h | localization-parity |
|
||||
| 9 | Minimap and multi-graph tabs | One graph at a time, no overview | Navigating big graphs | 5 h | target-app-parity (Graph editing, UI and UX) |
|
||||
| 10 | First signed release | Workflows copied, not run | Downloads | 3 h | target-app-parity (Platforms) |
|
||||
|
||||
@@ -21,6 +21,7 @@ Every known shortfall, most important first. Pick from the top.
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-06 | major | 3D view lights, shaders, common values, camera and renderer pages; node creation shortcuts; linked bitmaps and the dependency manager; plugins |
|
||||
| 2026-11-02 | minor | Portable `.mcmat` materials for TextureCraft closed gap 4; what's left is an MCP tool |
|
||||
| 2026-11-02 | major | Closed the function editor, dynamic parameters, FX-Map/Text/SVG, presets and groups, browser file I/O and accessible names; re-ranked |
|
||||
| 2026-11-02 | major | First list |
|
||||
@@ -1,24 +1,24 @@
|
||||
# Parity with the reference workflow
|
||||
|
||||
> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-02 · **Change:** minor (Files 60% → 70%: portable materials for TextureCraft) · **Target:** the professional node-based material workflow (desktop app; the web app is assessed later)
|
||||
> **Last reviewed:** 2026-11-06 · **Last updated:** 2026-11-06 · **Change:** major (3D view 55% → 70%, UI and UX 70% → 85%, Files 70% → 75%: the reference's menus, explorer, library, 3D view property pages, preferences and plugins) · **Target:** the professional node-based material workflow (desktop app; the web app is assessed later)
|
||||
|
||||
**Overall: ≈ 67%** of a material artist's daily workflow works end to end (engine + UI +
|
||||
**Overall: ≈ 70%** 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
|
||||
5.5 agent hours** (see [roadmap.md](roadmap.md)).
|
||||
|
||||
| Area | Weight | Done | What works | Main gaps |
|
||||
|---|---:|---:|---|---|
|
||||
| Graph editing | 15 | 75% | Pan/zoom canvas with grid; node cards with headers by category, live thumbnails and size/format labels; typed ports; bezier wires; drag to wire, re-route and unplug; select wires (click, Shift/Ctrl+click), delete them (Delete, Backspace, wire menu) and swap their sources (X); reroute dots pulled out of a wire (drag), dropped on it (double-click) or inserted from its menu; drop a wire on empty canvas to add a wired node; box/Ctrl/Shift selection; move; frames (move with contents, resize), comments (inline edit), navigation pins; node search (Space, double-click); library drag and drop; align and distribute; copy/cut/paste/duplicate (with or without links); delete and relink; disable; select upstream/downstream; create graph from selection; snapshot undo with merged slider drags | Dot-node chains editing, wire tension preferences, compact node display mode, multi-graph tabs, minimap |
|
||||
| Graph editing | 15 | 77% | Pan/zoom canvas with grid (toggle, snap); node cards with headers by category, live thumbnails and size/format labels; typed ports; bezier wires; drag to wire, re-route and unplug; select wires (click, Shift/Ctrl+click), delete them (Delete, Backspace, wire menu) and swap their sources (X); reroute dots pulled out of a wire (drag), dropped on it (double-click) or inserted from its menu; drop a wire on empty canvas to add a wired node; box/Ctrl/Shift selection; move; frames (move with contents, resize), comments (inline edit), navigation pins; node search (Space, double-click); library drag and drop; align and distribute; copy/cut/paste/duplicate (with or without links); delete and relink; disable; select upstream/downstream; create graph from selection; snapshot undo with merged slider drags; graph toolbar with 1:1, screenshot, graph info, cook times, straight/curved wires, clean-up, parent size link and reset, stack-aligned alignment; node creation shortcuts | Dot-node chains editing, compact node display mode, multi-graph tabs, minimap |
|
||||
| Atomic nodes | 12 | 95% | Bitmap, Blend (16 modes, masks, alpha), Blur, Channels Shuffle, Curve, Directional Blur, Directional Warp, Distance (with color propagation), Emboss, FX-Map (grid, quadtree and scatter modes with per-instance randomness), Gradient (Dynamic), Gradient Map, Grayscale Conversion, HSL, Levels, Normal, Pixel Processor, Value Processor, Sharpen, SVG (path data, fill rules, stroke), Text (own stroke font), Transformation 2D, Uniform Color, Warp, inputs, outputs, dots, graph instances | FX-Map driven by per-iteration functions, SVG arcs and SVG files, font choice for Text |
|
||||
| Node library | 20 | 45% | 227 nodes: noises (tileable 3D Perlin, simplex and Worley, cracks, stones, dirt, grunge maps and more), patterns (tile generator and sampler, bricks, hexagons, weave, shape splatter, paint strokes, scratches), filters (adjustments, blending, blurs, channels, effects, normal map tools, tiling, transforms), the flood fill family, whole-material and height blending, weathering (rust, moss, leaks, edge damage, edge wear, dust) | The rest of the reference library's ~400 graphs: more grunge and scan processing, mesh-based generators and bakers, spline tools, SDF functions |
|
||||
| Function graphs | 10 | 70% | A compiled, 4-wide evaluator with ~55 ops (constants, $pos/$size, exposed variables, samplers, vectors, swizzles, math, logic, comparison, noise, random, if/else); pixel and value processors; a visual function editor; dynamic parameters (a function on any numeric, color, bool or enum parameter, evaluated from the graph's inputs) | Loops, function graphs as reusable package items |
|
||||
| Graph parameters and instances | 8 | 70% | Exposed inputs (float, int, bool, enum, color) bound to parameters of any compatible type, shown in groups, edited with one shared editor on the graph and on its instances; presets (save, apply, delete); sub-graph instances with their own inputs and outputs; graph attributes; `--set` on the CLI | Visibility conditions, per-instance output sizes, embedded vs. linked packages |
|
||||
| 2D view | 5 | 80% | Pan/zoom, fit and 1:1, RGBA/R/G/B/A isolation, 3×3 tiling check, histogram, pixel readout, size/format line, save image | Color picker to parameters, UV overlay |
|
||||
| 3D view | 10 | 55% | Rounded cube, cube, sphere, cylinder, plane, torus and material ball; OBJ, glTF and GLB meshes; base color, normal, roughness, metallic, height (real displacement of a subdivided mesh, rising out of the surface), AO, emissive and opacity; alpha transparency through layered surfaces (opacity output or base color alpha) and an alpha channel view; 4 procedural environments with rotation and exposure; orbit/pan/zoom; tiling; supersampling at rest | GPU renderer with tessellation, lights, material/shader switching, path-traced renderer |
|
||||
| Files | 8 | 70% | `.mcraft` packages with embedded bitmaps; `.mcmat` portable materials (cooked maps, exposed inputs, presets, input nodes, the source package) that TextureCraft paints with and re-cooks through the CLI at its own resolution, values and mesh maps; preview images for input nodes; export of every output (PNG, JPEG, TGA, TIFF, BMP, WEBP, EXR, HDR; 8/16/32 bits; name pattern; sRGB vs. linear by usage); bitmap import (PNG, JPEG, TGA, TIFF, BMP, WEBP, EXR, HDR); mesh import (OBJ, glTF, GLB); open, save, import and export in the browser; atomic writes; autosave; recent files | An MCP tool for portable materials, package dependencies, SVG and font files as resources |
|
||||
| UI and UX | 8 | 70% | Dockable/floatable panels (explorer, library, graph, 3D, 2D, properties, console, history), menus, main toolbar, graph toolbar with atomic quick-insert, library with live previews, properties with curve/gradient/color editors and a Levels editor over the input histogram, New graph dialog with rendered templates, export dialog, preferences (brightness, accent, scale, preview size, autosave, 3D pan limit and speed), shortcuts list, home screen at startup (samples and recent files), visual function editor, presets bar, accessible names on every widget, status bar | Translations, keymap editor, minimap, multi-graph tabs |
|
||||
| 2D view | 5 | 85% | Pan/zoom, fit and 1:1, RGBA/R/G/B/A isolation, 3×3 tiling check, histogram, pixel readout, size/format line, save image, the 3D scene's UV layout as an overlay | Color picker to parameters |
|
||||
| 3D view | 10 | 70% | Eleven built-in scenes (cube, cylinder, plane, hi-res plane, sphere, cloth, material ball, rounded cube, rounded cylinder, two-tile sphere, torus); OBJ, glTF and GLB meshes; base color, normal, roughness, metallic, height (real displacement of a subdivided mesh with a tessellation factor), AO, emissive, opacity, specular and glossiness; nine shading models (OpenPBR with coat, fuzz, emission, thin film, transmission and subsurface terms; metallic/roughness, coated, SSS, specular/glossiness, Blinn, Lambert, unlit, mesh info) with common values for every unmapped channel and per-map on/off; ambient and two shadow-casting point lights; camera focal length, orthographic projection, background type/colour, render resolution and clip planes; six environments with rotation, exposure and on/off; Display toggles (wireframe, axis, backface culling, bounding box, grid, light gizmos, resolution, stats, FPS); save/copy render; save/load/default view state; all of it in Properties-panel pages and `view.3d` | GPU renderer, path tracing, draggable light gizmos |
|
||||
| Files | 8 | 70% | `.mcraft` packages with embedded bitmaps; `.mcmat` portable materials (cooked maps, exposed inputs, presets, input nodes, the source package) that TextureCraft paints with and re-cooks through the CLI at its own resolution, values and mesh maps; preview images for input nodes; export of every output (PNG, JPEG, TGA, TIFF, BMP, WEBP, EXR, HDR; 8/16/32 bits; name pattern; sRGB vs. linear by usage); bitmap import (PNG, JPEG, TGA, TIFF, BMP, WEBP, EXR, HDR); mesh import (OBJ, glTF, GLB); open, save, import and export in the browser; atomic writes; rotating auto backups; recent files; linked (not embedded) bitmaps with reload and a Dependency Manager; save a copy, export with dependencies, import a graph (with its instances and bitmaps) from another package; plugins folder whose packages feed the library | An MCP tool for portable materials, SVG and font files as resources |
|
||||
| UI and UX | 8 | 85% | Dockable/floatable panels (explorer, library, graph, 3D, 2D, properties, console, history) with maximize (Shift+Space), the reference's File/Edit/Tools/Windows/Help menus (switch engine, cancel/suspend rendering, dependency manager, plugin manager, log export), explorer context menus for packages, graphs and resources (rename in place, copy/paste graphs), library tree with favorites, collapsible groups with counts, function nodes and plugin graphs, graph toolbar, properties with curve/gradient/color editors and a Levels editor over the input histogram, New graph dialog with categories, template info and linked sizes, export dialog, tabbed preferences (general, projects, graph, 3D view, bakers, library, node shortcuts) where every setting does something, home screen, visual function editor, presets bar, accessible names on every widget, status bar with the engine | Translations, menu keymap editor, minimap, multi-graph tabs |
|
||||
| Platforms | 4 | 50% | Windows, macOS, Linux, FreeBSD and web builds compile; browser file I/O; packaging scripts and release workflows | First release run |
|
||||
| **Total** | **100** | **≈ 67%** | | |
|
||||
| **Total** | **100** | **≈ 70%** | | |
|
||||
|
||||
Beyond the reference app: every edit is a command available through MCP, the CLI and the app's
|
||||
control channel (including synthetic mouse and keyboard input), the engine runs headless with the
|
||||
@@ -35,6 +35,7 @@ and is tested.
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-06 | major | ≈ 67% → ≈ 70%: the reference UI (menus, explorer, library, new-graph dialog, graph toolbar, 3D view menus and property pages with lights, shaders and common values, tabbed preferences, plugin manager) |
|
||||
| 2026-11-02 | minor | ≈ 66% → ≈ 67%: `.mcmat` portable materials and TextureCraft interop (Files 70%) |
|
||||
| 2026-11-02 | major | Function editor, dynamic parameters, presets, 227 nodes (FX-Map, SVG, Text, 3D noises, weathering), mesh import, browser file I/O, histogram: ≈ 51% → ≈ 66% |
|
||||
| 2026-11-02 | major | First assessment after the first day of work |
|
||||
Reference in new issue
Block a user