Cross-app materials: .mcmat portable materials for TextureCraft

- formats: .mcmat (zip: material.json manifest, maps/<usage>.png, source.mcraft) with
  read/write and caps; color usages 8-bit sRGB, data maps 16-bit linear
- engine: file.exportMaterial {path, size?, values?, inputs?}, file.sendToTextureCraft
  (TextureCraft's library folder), graph.input.bind/unbind; file.open reads .mcmat
- core/eval: Graph::input_images preview images for input nodes (mesh maps from
  TextureCraft); caller images win; grayscale inputs convert to gray
- ui: File > Export material..., File > Send to TextureCraft, Open accepts .mcmat,
  input previews in the graph properties
- docs: control protocol (portable materials), file formats, gaps, parity ≈ 67%,
  roadmap, architecture, AGENTS convention for shared formats

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
bflatasticandClaude Opus 5.5 committed 2026-11-02 12:06:09 +07:00
1 parent d2a92adb53
commit 53ab0f2d6a
24 files changed
+715 -47

No files matched your search

+5 -1
View File
@@ -140,7 +140,11 @@ never a panic. The shared standard is `../craftrules/standards/never-crash.md`.
alternatives.
8. **Performance is a feature.** Edits re-cook only what lies downstream (the cache). Cooking runs
on a worker thread; the UI never blocks on it. Benchmark heavy nodes in release.
9. **Verify UI changes visually.** `MC_SNAPSHOT_DIR=<dir> cargo test -p materialcraft-ui-egui
9. **Cross-app formats are shared conventions.** `.mcmat` portable materials are read by
TextureCraft with its own code: keep `docs/control-protocol.md` § Portable materials, the usage
ids and the mesh-map input identifiers in step with TextureCraft, bump the manifest `version`
for incompatible changes, and never make one app depend on the other's crates.
10. **Verify UI changes visually.** `MC_SNAPSHOT_DIR=<dir> cargo test -p materialcraft-ui-egui
--release --test snapshot -- --ignored` renders the real UI offscreen; look at the PNGs.
## 4. Picking work
Generated
+1
View File
@@ -2393,6 +2393,7 @@ dependencies = [
"materialcraft-core",
"materialcraft-geom",
"materialcraft-image",
"serde",
"serde_json",
"thiserror 2.0.21",
"tobj",
+9 -3
View File
@@ -110,6 +110,10 @@ its own procedural nodes (no photos, scans or textures from anywhere else) and r
with odd inputs in tests, unlimited undo from snapshots, and lossless `.mcraft` packages.
- **Open.** Export base color, normal, roughness, metallic, height and ambient occlusion as PNG,
JPEG, TGA, TIFF, BMP, WEBP, EXR or HDR at 8, 16 or 32 bits, with your own file name pattern.
- **Works with TextureCraft.** **File ▸ Send to TextureCraft** puts a material on TextureCraft's
shelf as a portable `.mcmat`; painted onto a mesh there, its graph inputs stay live sliders and
colors, re-cooked by MaterialCraft at the texture set's resolution with the mesh's baked maps
feeding the graph's input nodes.
- **Agent-native.** Every menu item and edit is a command you can drive from the CLI, a JSON
control channel (including synthetic mouse and keyboard input) or an **MCP server**, so Claude
and other agents can build materials the way a person does.
@@ -129,6 +133,7 @@ cargo run --release -p materialcraft-cli -- new wood wood.mcraft
cargo run --release -p materialcraft-cli -- render wood.mcraft wood.png --scene material_ball --full
cargo run --release -p materialcraft-cli -- export wood.mcraft textures --format png --depth 16
cargo run --release -p materialcraft-cli -- export my.mcraft out --set wear=0.7 # with a graph input "wear" set first
cargo run --release -p materialcraft-cli -- run my.mcraft file.exportMaterial '{"path": "my.mcmat", "size": 2048}' # for TextureCraft
cd apps/materialcraft-web && trunk serve # web build
cargo xtask ci # fmt, clippy, tests, layering, wasm
```
@@ -162,12 +167,13 @@ SVG and Text, noises including tileable 3D ones, patterns, filters, the flood fi
whole-material blending and weathering), function graphs with a visual editor and dynamic
parameters, sub-graphs with exposed inputs and presets, the full editor (graph, library,
properties, 2D view with histogram, 3D view with your own OBJ/glTF meshes), `.mcraft` packages,
texture export, the browser build with file I/O, the CLI, the control channel and the MCP server
all work today. We estimate about two thirds (≈ 66%) of a material artist's daily workflow works
texture export, portable `.mcmat` materials that TextureCraft paints with (inputs stay editable
there), the browser build with file I/O, the CLI, the control channel and the MCP server
all work today. We estimate about two thirds (≈ 67%) of a material artist's daily workflow works
end to end; [docs/target-app-parity.md](docs/target-app-parity.md) has the breakdown.
**What's missing:** the rest of the node library, a GPU 3D view with tessellation and lights,
mesh-based nodes, published material archives, translations and the first signed release. The ranked list is in
mesh-based nodes, translations and the first signed release. The ranked list is in
[`docs/gaps.md`](docs/gaps.md).
**Workspace:** `crates/{core, image, geom, nodes, eval, formats, engine, render, automation, ui-egui}`
+8 -6
View File
@@ -1,6 +1,6 @@
# MaterialCraft roadmap
> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-02 · **Change:** major (≈ 66%) · **Target:** the professional node-based material workflow
> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-02 · **Change:** minor (≈ 67%: portable materials for TextureCraft) · **Target:** the professional node-based material workflow
**Stage:** alpha (in active development). MaterialCraft aims for full parity with the professional
node-based procedural material workflow, with better performance, every feature drivable by agents
@@ -8,9 +8,9 @@ node-based procedural material workflow, with better performance, every feature
## Headline numbers
- **Parity: ≈ 66%** of a material artist's daily workflow works end to end
- **Parity: ≈ 67%** of a material artist's daily workflow works end to end
([docs/target-app-parity.md](docs/target-app-parity.md)).
- **Remaining: ≈ 88 Opus 5.5 agent hours** ([docs/roadmap.md](docs/roadmap.md)).
- **Remaining: ≈ 83 Opus 5.5 agent hours** ([docs/roadmap.md](docs/roadmap.md)).
- **Nodes:** 227 (all tileable), cooked on every CPU core through a content-addressed cache; the
brick wall sample cooks in about 40 ms at preview size.
@@ -25,17 +25,17 @@ node-based procedural material workflow, with better performance, every feature
| Graph parameters and instances | 8 | 70% |
| 2D view | 5 | 80% |
| 3D view | 10 | 55% |
| Files | 8 | 60% |
| Files | 8 | 70% |
| UI and UX | 8 | 70% |
| Platforms | 4 | 50% |
| **Total** | **100** | **≈ 66%** |
| **Total** | **100** | **≈ 67%** |
## What's next
1. The rest of the node library: scan processing, more grunges, spline tools, SDF shapes.
2. A GPU 3D view with tessellation and lights.
3. Mesh-based generators and bakers.
4. Published material archives; function loops and reusable functions.
4. Function loops and reusable functions.
5. The first release on every platform.
The ranked work list is [docs/gaps.md](docs/gaps.md); file formats are in
@@ -46,6 +46,7 @@ The ranked work list is [docs/gaps.md](docs/gaps.md); file formats are in
| Date | What landed |
|---|---|
| 2026-11-02 | Cross-app materials: `.mcmat` portable materials, Send to TextureCraft, input-node preview images (mesh maps from TextureCraft), live re-cooks from TextureCraft through the CLI |
| 2026-11-02 | Visual function editor, dynamic parameters, presets and groups, 105 more nodes (flood fill, FX-Map, SVG, Text, 3D noises, weathering, material blending), mesh import, browser file I/O, 2D histogram, CLI `--set`, better samples |
| 2026-11-02 | First day: engine, ~120 nodes, cooking cache, packages, export, the full editor UI, 3D preview, CLI, control channel with synthetic input, MCP server, wasm builds |
@@ -53,5 +54,6 @@ The ranked work list is [docs/gaps.md](docs/gaps.md); file formats are in
| Date | Change | Summary |
|---|---|---|
| 2026-11-02 | minor | ≈ 66% → ≈ 67% (portable materials) |
| 2026-11-02 | major | ≈ 51% → ≈ 66% |
| 2026-11-02 | major | First version |
+5
View File
@@ -246,6 +246,10 @@ pub struct Graph {
/// Named sets of input values.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub presets: Vec<Preset>,
/// Preview images of the graph's input nodes: identifier → bitmap resource (a mesh map
/// baked in TextureCraft, say). Instances feed their inputs from their ports instead.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub input_images: BTreeMap<String, String>,
#[serde(default)]
pub attributes: Attributes,
/// The id the next node, frame, comment or pin gets.
@@ -272,6 +276,7 @@ impl Graph {
exposed: Vec::new(),
inputs: BTreeMap::new(),
presets: Vec::new(),
input_images: BTreeMap::new(),
attributes: Attributes::default(),
next_id: 1,
}
+1
View File
@@ -49,6 +49,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
SPECS.get_or_init(|| {
let mut v = Vec::new();
v.extend(crate::file_cmds::specs());
v.extend(crate::material_cmds::specs());
v.extend(crate::edit_cmds::specs());
v.extend(crate::graph_cmds::specs());
v.extend(crate::node_cmds::specs());
+22 -13
View File
@@ -85,8 +85,15 @@ pub fn replace_package(s: &mut Session, pkg: Package, path: Option<String>) {
s.dirty = true;
}
/// Open package bytes (any platform).
/// Open package bytes (any platform). A portable material (`.mcmat`) opens the package it was
/// cooked from, on its graph, with no file name (saving must not overwrite the material).
pub fn open_bytes(s: &mut Session, bytes: &[u8], name: Option<String>) -> Result<()> {
if materialcraft_formats::material::is_material(bytes) {
let (manifest, source) = materialcraft_formats::material::read_material(bytes)?;
replace_package(s, materialcraft_formats::load_package(&source)?, None);
s.graph = s.pkg.graph_by_name(&manifest.graph).map_or(0, |(i, _)| i);
return Ok(());
}
let pkg = materialcraft_formats::load_package(bytes)?;
replace_package(s, pkg, name);
Ok(())
@@ -152,8 +159,7 @@ pub fn export_outputs(s: &Session, gi: usize, ext: &str, pattern: &str, depth: O
let node = g.node(id)?;
let depth = depth
.unwrap_or_else(|| Depth::from_format(if node.base.format == materialcraft_core::OutputFormat::Inherit { g.format } else { node.base.format }));
let srgb = matches!(usage, "baseColor" | "emissive" | "specular");
let bytes = encode(img, ext, depth, srgb)?;
let bytes = encode(img, ext, depth, materialcraft_formats::material::srgb_usage(usage))?;
out.push(Exported { file: format!("{}.{}", output_name(pattern, &g.name, &ident, usage), ext.trim_start_matches('.')), bytes });
}
if out.is_empty() {
@@ -205,18 +211,21 @@ fn export(_: &mut Session, _: &J) -> Result<J> {
/// Embed image bytes as a resource; returns the resource name.
pub fn add_resource(s: &mut Session, file: &str, bytes: Vec<u8>, name: Option<&str>) -> Result<String> {
materialcraft_formats::decode(&bytes)?;
s.edit("Import bitmap", |s| Ok(push_resource(&mut s.pkg, file, bytes, name)))
}
/// Add `bytes` to `pkg` as a resource named `name` (or after `file`), made unique; returns the name.
pub(crate) fn push_resource(pkg: &mut Package, file: &str, bytes: Vec<u8>, name: Option<&str>) -> String {
let file = materialcraft_formats::safe_file_name(file);
let stem = name.map(str::to_string).unwrap_or_else(|| file.rsplit_once('.').map_or(file.clone(), |(a, _)| a.to_string()));
s.edit("Import bitmap", |s| {
let mut name = stem.clone();
let mut i = 1;
while s.pkg.resource(&name).is_some() {
name = format!("{stem}_{i}");
i += 1;
}
s.pkg.resources.push(Resource { name: name.clone(), file: format!("{name}_{file}"), bytes: std::sync::Arc::new(bytes) });
Ok(name)
})
let mut name = stem.clone();
let mut i = 1;
while pkg.resource(&name).is_some() {
name = format!("{stem}_{i}");
i += 1;
}
pkg.resources.push(Resource { name: name.clone(), file: format!("{name}_{file}"), bytes: std::sync::Arc::new(bytes) });
name
}
#[cfg(not(target_arch = "wasm32"))]
+1
View File
@@ -12,6 +12,7 @@ pub mod edit_cmds;
pub mod file_cmds;
pub mod graph_cmds;
pub mod inspect;
pub mod material_cmds;
pub mod node_cmds;
pub mod samples;
pub mod session;
+290
View File
@@ -0,0 +1,290 @@
//! Cross-app materials: portable `.mcmat` export (cooked maps, the exposed inputs other apps may
//! change, the source package), "Send to TextureCraft", and preview images for the graph's input
//! nodes (mesh maps baked in TextureCraft). See `docs/control-protocol.md` § Portable materials.
use std::collections::BTreeMap;
use serde_json::{Value as J, json};
use materialcraft_core::{Graph, Value};
use materialcraft_formats::material::{FORMAT, ImageInput, MATERIAL_EXT, Manifest, MapEntry, Parameter, PresetEntry, VERSION, portable, srgb_usage};
use materialcraft_formats::{Depth, encode};
use materialcraft_image::Image;
use materialcraft_nodes::atomic::USAGE_IDS;
use crate::commands::{CommandSpec, bad, has_graph, strp, u64p};
use crate::{Result, Session, cmd};
pub(crate) fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"file.exportMaterial",
"Export material...",
["File"],
None,
"{path, graph?, size? (px, power of two), values? {input: value}, inputs? {identifier: image path}} cooks the graph and writes a portable .mcmat material (maps, exposed inputs, source package) for TextureCraft",
has_graph,
export_material
),
cmd!(
"file.sendToTextureCraft",
"Send to TextureCraft",
["File"],
None,
"{graph?} exports the graph as a portable material into TextureCraft's library folder (Documents/TextureCraft/library), where its shelf lists it",
has_graph,
send_to_texturecraft
),
cmd!(
"graph.input.bind",
"Set input preview image",
[],
None,
"{identifier, resource? | path?} shows a bitmap resource (or an image file, embedded) on the graph's input node `identifier`, e.g. a mesh map baked in TextureCraft",
has_graph,
bind
),
cmd!("graph.input.unbind", "Clear input preview image", [], None, "{identifier}", has_graph, unbind),
]
}
/// What to cook a portable material with, over the graph's own values.
#[derive(Clone, Debug, Default)]
pub struct MaterialOptions {
/// Square size in pixels (rounded to a power of two, 16..8192); `None` = the graph's size.
pub size: Option<u32>,
/// Exposed input values (they also become the embedded package's values).
pub values: BTreeMap<String, Value>,
/// Images for the graph's input nodes, by identifier (mesh maps).
pub inputs: BTreeMap<String, Image>,
}
/// Cook graph `gi` with `o` and pack it as a portable material (`.mcmat` bytes).
pub fn material_bytes(s: &Session, gi: usize, o: &MaterialOptions) -> Result<Vec<u8>> {
let mut pkg = s.pkg.clone();
let g = pkg.graph_mut(gi)?;
if let Some(px) = o.size {
let log2 = 31 - px.clamp(16, 8192).leading_zeros();
g.size = [log2, log2];
}
g.inputs.extend(o.values.clone());
let g = pkg.graph(gi)?;
let dec = s.resource_decoder();
let mut opts = materialcraft_eval::Options::new(&dec);
opts.inputs = o.inputs.clone();
let cooked = {
let mut cache = s.cache.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
materialcraft_eval::cook(&pkg, gi, &opts, &mut cache)
};
let mut maps: Vec<(String, Vec<u8>)> = Vec::new();
let mut entries = Vec::new();
let mut size = [0, 0];
for (_, usage, _, img) in materialcraft_eval::outputs(g, &cooked) {
let Some(img) = img else { continue };
if usage == "any" || entries.iter().any(|e: &MapEntry| e.usage == usage) {
continue;
}
let srgb = srgb_usage(usage);
let file = format!("maps/{usage}.png");
maps.push((file.clone(), encode(img, "png", if srgb { Depth::U8 } else { Depth::U16 }, srgb)?));
entries.push(MapEntry { usage: usage.into(), file, color_space: if srgb { "srgb" } else { "linear" }.into() });
size = [img.w, img.h];
}
if entries.is_empty() {
return Err(bad("file.exportMaterial", format!("graph `{}` has no outputs with a material usage ({})", g.name, USAGE_IDS.join(", "))));
}
let manifest = Manifest {
format: FORMAT.into(),
version: VERSION,
name: g.name.replace('_', " "),
graph: g.name.clone(),
size,
maps: entries,
parameters: g
.exposed
.iter()
.filter(|e| portable(&e.default))
.map(|e| Parameter { param: e.clone(), value: g.input_value(&e.id).cloned().unwrap_or_else(|| e.default.clone()) })
.collect(),
inputs: image_inputs(g),
presets: g.presets.iter().map(|p| PresetEntry { name: p.name.clone(), values: p.values.clone() }).collect(),
source: String::new(),
};
let source = materialcraft_formats::save_package(&pkg)?;
Ok(materialcraft_formats::material::write_material(&manifest, &maps, &source)?)
}
/// The graph's input nodes (one entry per identifier).
pub fn image_inputs(g: &Graph) -> Vec<ImageInput> {
let mut out: Vec<ImageInput> = Vec::new();
for n in g.nodes.iter().filter(|n| matches!(n.def.as_str(), "input_grayscale" | "input_color")) {
let identifier = materialcraft_eval::identifier(n);
if !out.iter().any(|i| i.identifier == identifier) {
out.push(ImageInput { identifier, kind: if n.def == "input_grayscale" { "gray" } else { "color" }.into() });
}
}
out
}
/// `values` as typed exposed input values of graph `g`.
fn values_param(cmd: &str, g: &Graph, p: &J) -> Result<BTreeMap<String, Value>> {
let Some(obj) = p.get("values").and_then(J::as_object) else { return Ok(BTreeMap::new()) };
obj.iter()
.map(|(id, v)| {
let e = g.exposed.iter().find(|e| e.id == *id).ok_or_else(|| bad(cmd, format!("no input `{id}`")))?;
let val = e.default.coerce_json(v).ok_or_else(|| bad(cmd, format!("`{id}` takes a {}", e.default.type_name())))?;
Ok((id.clone(), val))
})
.collect()
}
fn graph_param(s: &Session, p: &J) -> Result<usize> {
let gi = u64p(p, "graph").map_or(s.graph, |g| g as usize);
s.pkg.graph(gi)?;
Ok(gi)
}
#[cfg(not(target_arch = "wasm32"))]
fn export_material(s: &mut Session, p: &J) -> Result<J> {
const CMD: &str = "file.exportMaterial";
let path = strp(p, "path").ok_or_else(|| bad(CMD, "`path` is required"))?;
let path = if path.to_ascii_lowercase().ends_with(&format!(".{MATERIAL_EXT}")) { path.to_string() } else { format!("{path}.{MATERIAL_EXT}") };
let gi = graph_param(s, p)?;
let mut o = MaterialOptions { size: u64p(p, "size").map(|v| v.min(8192) as u32), values: values_param(CMD, s.pkg.graph(gi)?, p)?, ..Default::default() };
for (id, file) in p.get("inputs").and_then(J::as_object).into_iter().flatten() {
let file = file.as_str().ok_or_else(|| bad(CMD, format!("inputs.{id} must be an image path")))?;
let bytes = std::fs::read(file).map_err(|e| bad(CMD, format!("{file}: {e}")))?;
o.inputs.insert(id.clone(), materialcraft_formats::decode(&bytes)?);
}
let bytes = material_bytes(s, gi, &o)?;
materialcraft_formats::write_atomic(std::path::Path::new(&path), &bytes)?;
s.log(format!("Exported material {path}"));
Ok(json!({"path": path, "bytes": bytes.len()}))
}
#[cfg(target_arch = "wasm32")]
fn export_material(_: &mut Session, _: &J) -> Result<J> {
Err(bad("file.exportMaterial", "the browser exports with a download"))
}
/// TextureCraft's library folder: `Documents/TextureCraft/library` in the home folder.
#[cfg(not(target_arch = "wasm32"))]
pub fn texturecraft_library() -> std::path::PathBuf {
let home = std::env::var("USERPROFILE").or_else(|_| std::env::var("HOME")).unwrap_or_else(|_| ".".into());
std::path::Path::new(&home).join("Documents").join("TextureCraft").join("library")
}
#[cfg(not(target_arch = "wasm32"))]
fn send_to_texturecraft(s: &mut Session, p: &J) -> Result<J> {
const CMD: &str = "file.sendToTextureCraft";
let gi = graph_param(s, p)?;
let bytes = material_bytes(s, gi, &MaterialOptions::default())?;
let dir = texturecraft_library();
std::fs::create_dir_all(&dir).map_err(|e| bad(CMD, format!("{}: {e}", dir.display())))?;
let path = dir.join(format!("{}.{MATERIAL_EXT}", materialcraft_formats::safe_file_name(&s.pkg.graph(gi)?.name)));
materialcraft_formats::write_atomic(&path, &bytes)?;
let path = path.display().to_string();
s.log(format!("Sent to TextureCraft: {path}"));
Ok(json!({"path": path}))
}
#[cfg(target_arch = "wasm32")]
fn send_to_texturecraft(_: &mut Session, _: &J) -> Result<J> {
Err(bad("file.sendToTextureCraft", "the browser has no shared library folder: export the material instead"))
}
fn identifier_param(s: &Session, cmd: &str, p: &J) -> Result<String> {
let id = strp(p, "identifier").ok_or_else(|| bad(cmd, "`identifier` is required"))?;
if !image_inputs(s.graph()?).iter().any(|i| i.identifier == id) {
return Err(bad(cmd, format!("the graph has no input node `{id}`")));
}
Ok(id.to_string())
}
fn bind(s: &mut Session, p: &J) -> Result<J> {
const CMD: &str = "graph.input.bind";
let id = identifier_param(s, CMD, p)?;
let file = match (strp(p, "resource"), strp(p, "path")) {
(Some(r), _) if s.pkg.resource(r).is_some() => None,
(Some(r), _) => return Err(bad(CMD, format!("no bitmap resource `{r}`"))),
(None, Some(path)) => Some(read_image_file(CMD, path)?),
(None, None) => return Err(bad(CMD, "give a `resource` or a `path`")),
};
s.edit("Set input preview image", |s| {
let res = match file {
Some((name, bytes)) => crate::file_cmds::push_resource(&mut s.pkg, &name, bytes, Some(&id)),
None => strp(p, "resource").unwrap_or_default().to_string(),
};
s.graph_mut()?.input_images.insert(id.clone(), res.clone());
Ok(json!({"identifier": id, "resource": res}))
})
}
#[cfg(not(target_arch = "wasm32"))]
fn read_image_file(cmd: &str, path: &str) -> Result<(String, Vec<u8>)> {
let bytes = std::fs::read(path).map_err(|e| bad(cmd, format!("{path}: {e}")))?;
materialcraft_formats::decode(&bytes)?;
let name = std::path::Path::new(path).file_name().and_then(|f| f.to_str()).unwrap_or("input.png").to_string();
Ok((name, bytes))
}
#[cfg(target_arch = "wasm32")]
fn read_image_file(cmd: &str, _: &str) -> Result<(String, Vec<u8>)> {
Err(bad(cmd, "the browser imports images with the file picker: import a bitmap, then pass its `resource`"))
}
fn unbind(s: &mut Session, p: &J) -> Result<J> {
let id = strp(p, "identifier").ok_or_else(|| bad("graph.input.unbind", "`identifier` is required"))?.to_string();
s.edit("Clear input preview image", |s| Ok(J::Bool(s.graph_mut()?.input_images.remove(&id).is_some())))
}
#[cfg(test)]
mod tests {
use super::*;
use materialcraft_formats::material::read_material;
#[test]
fn exports_maps_inputs_and_values() {
let mut s = crate::sample_session();
crate::execute(&mut s, "graph.exposed.add", &json!({"id": "wear", "default": 0.5})).unwrap();
crate::execute(&mut s, "graph.exposed.add", &json!({"id": "label", "default": {"t": "text", "v": "x"}})).unwrap();
let values = values_param("t", s.graph().unwrap(), &json!({"values": {"wear": 0.9}})).unwrap();
let bytes = material_bytes(&s, s.graph, &MaterialOptions { size: Some(32), values, ..Default::default() }).unwrap();
let (m, source) = read_material(&bytes).unwrap();
assert_eq!(m.size, [32, 32]);
assert!(m.maps.iter().any(|e| e.usage == "baseColor" && e.color_space == "srgb"));
assert!(m.maps.iter().any(|e| e.usage == "normal" && e.color_space == "linear"));
let ids: Vec<&str> = m.parameters.iter().map(|p| p.param.id.as_str()).collect();
assert_eq!(ids, ["wear"], "text inputs are not portable");
assert_eq!(m.parameters[0].value, Value::Float(0.9), "the manifest carries the cooked value");
assert_eq!(materialcraft_formats::load_package(&source).unwrap().graphs[s.graph].inputs.get("wear"), Some(&Value::Float(0.9)));
// The source package opens again, on the material's graph, with no file to save over.
crate::file_cmds::open_bytes(&mut s, &bytes, Some("x.mcmat".into())).unwrap();
assert_eq!(s.graph().unwrap().name, m.graph);
assert!(s.path.is_none());
}
#[test]
fn binds_preview_images_to_input_nodes() {
let mut s = crate::sample_session();
crate::execute(&mut s, "graph.node.add", &json!({"def": "input_grayscale", "params": {"identifier": "curvature"}})).unwrap();
let png = encode(&Image::filled(4, 4, materialcraft_image::Kind::Gray, [0.7; 4]), "png", Depth::U16, false).unwrap();
let res = crate::file_cmds::add_resource(&mut s, "curv.png", png, None).unwrap();
assert!(crate::execute(&mut s, "graph.input.bind", &json!({"identifier": "nope", "resource": res})).is_err());
crate::execute(&mut s, "graph.input.bind", &json!({"identifier": "curvature", "resource": res})).unwrap();
assert_eq!(s.graph().unwrap().input_images.get("curvature"), Some(&res));
let bytes = material_bytes(&s, s.graph, &MaterialOptions { size: Some(16), ..Default::default() }).unwrap();
let (m, _) = read_material(&bytes).unwrap();
assert!(m.inputs.iter().any(|i| i.identifier == "curvature" && i.kind == "gray"));
assert_eq!(crate::execute(&mut s, "graph.input.unbind", &json!({"identifier": "curvature"})).unwrap(), J::Bool(true));
assert!(s.graph().unwrap().input_images.is_empty());
}
#[test]
fn rejects_unknown_values() {
let s = crate::sample_session();
let g = s.graph().unwrap();
assert!(values_param("t", g, &json!({"values": {"no_such_input": 1}})).is_err());
assert!(values_param("t", g, &json!({})).unwrap().is_empty());
}
}
+4 -1
View File
@@ -99,7 +99,10 @@ fn panic_hunt() {
];
for spec in command_specs() {
// Skip file writes to the working directory and opening paths.
if matches!(spec.id, "file.save" | "file.saveAs" | "file.export" | "file.open" | "file.importBitmap") {
if matches!(
spec.id,
"file.save" | "file.saveAs" | "file.export" | "file.open" | "file.importBitmap" | "file.exportMaterial" | "file.sendToTextureCraft"
) {
continue;
}
for p in &hostile {
+35 -1
View File
@@ -248,6 +248,16 @@ pub fn cook(pkg: &Package, gi: usize, opts: &Options, cache: &mut Cache) -> Cook
let t0 = now_ms();
let mut out = Cooked::default();
let Some(graph) = pkg.graphs.get(gi) else { return out };
// The top-level graph's input nodes show their preview images; the caller's images win.
let bound;
let opts = if opts.depth == 0 && !graph.input_images.is_empty() {
let mut inputs: BTreeMap<String, Image> = graph.input_images.iter().filter_map(|(id, res)| Some((id.clone(), (opts.resource)(res)?))).collect();
inputs.extend(opts.inputs.iter().map(|(k, v)| (k.clone(), v.clone())));
bound = Options { only: opts.only.clone(), inputs, overrides: opts.overrides.clone(), ..*opts };
&bound
} else {
opts
};
let order = graph.topo_order();
let needed: Option<std::collections::BTreeSet<NodeId>> = opts.only.as_ref().map(|ids| {
let mut s: std::collections::BTreeSet<NodeId> = ids.iter().copied().collect();
@@ -354,7 +364,8 @@ fn cook_node(pkg: &Package, graph: &Graph, node: &Node, done: &Cooked, vars: &BT
let result: Result<Vec<Image>, String> = if node.disabled {
Ok(vec![inputs.iter().flatten().next().cloned().unwrap_or_else(|| Image::filled(w, h, Kind::Gray, [0.0; 4])); out_ports.len().max(1)])
} else if let Some(img) = input_img {
Ok(vec![img.resize(w, h, tile)])
let img = img.resize(w, h, tile);
Ok(vec![if node.def == "input_grayscale" { img.to_gray() } else { img }])
} else if node.def == "graph_instance" {
cook_instance(pkg, node, &in_ports, &out_ports, &inputs, &params, (w, h), opts, cache)
} else if let Some(d) = def {
@@ -517,4 +528,27 @@ mod tests {
assert!((img.data[0] - (1.0 - 0.0722 * 0.25 - 0.2126 * 0.25 - 0.7152 * 0.25)).abs() < 1e-4, "{}", img.data[0]);
assert!(c.nodes[&selfi].error.is_some() || c.nodes[&selfi].outputs.len() == 1);
}
#[test]
fn input_nodes_read_bound_preview_images() {
let mut p = Package::new("p");
let mut g = Graph::new("g");
g.size = [4, 4];
let i = g.add_node("input_grayscale", [0.0, 0.0]);
g.node_mut(i).unwrap().params.insert("identifier".into(), Value::Text("curvature".into()));
let o = g.add_node("output", [100.0, 0.0]);
g.connect(i, "output", o, "input").unwrap();
g.input_images.insert("curvature".into(), "curv".into());
p.graphs.push(g);
let res = |n: &str| (n == "curv").then(|| Image::filled(4, 4, Kind::Color, [0.8, 0.8, 0.8, 1.0]));
let mut cache = Cache::default();
let c = cook(&p, 0, &Options::new(&res), &mut cache);
let img = c.image(o, 0).unwrap();
assert!(img.is_gray() && (img.data[0] - 0.8).abs() < 1e-4, "bound image, as gray");
// The caller's image wins over the bound one.
let mut opts = Options::new(&res);
opts.inputs.insert("curvature".into(), Image::filled(4, 4, Kind::Gray, [0.1; 4]));
let c = cook(&p, 0, &opts, &mut cache);
assert!((c.image(o, 0).unwrap().data[0] - 0.1).abs() < 1e-4);
}
}
+1
View File
@@ -15,6 +15,7 @@ materialcraft-geom = { workspace = true }
gltf = { workspace = true }
tobj = { workspace = true }
image = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
zip = { workspace = true }
+2 -1
View File
@@ -3,11 +3,12 @@
//! File formats, L2: the native `.mcraft` package (a zip holding `package.json` and the embedded
//! `resources/`), bitmap decoding for Bitmap nodes, and texture export (PNG 8/16, JPEG, TGA,
//! TIFF 8/16, BMP, WEBP, EXR 32F, HDR) with the output naming pattern, and meshes for the 3D view
//! (OBJ, glTF/GLB). Byte-based APIs work
//! (OBJ, glTF/GLB), and portable materials (`.mcmat`, see [`material`]). Byte-based APIs work
//! everywhere, including the browser; path helpers are native only.
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
pub mod material;
pub mod mesh;
use std::io::{Cursor, Read, Write};
+191
View File
@@ -0,0 +1,191 @@
//! Portable materials (`.mcmat`): a cooked material other apps (TextureCraft) apply without a
//! graph engine, plus the package it came from so an app that can run `materialcraft-cli`
//! re-cooks it with other parameter values, sizes and mesh maps.
//!
//! A zip: `material.json` ([`Manifest`]), `maps/<usage>.png` (8-bit sRGB for color usages,
//! 16-bit linear otherwise; normals in the OpenGL convention) and `source.mcraft`.
use std::collections::BTreeMap;
use std::io::{Cursor, Read, Write};
use materialcraft_core::{ExposedParam, Value};
use serde::{Deserialize, Serialize};
use crate::{FormatError, MAX_JSON, MAX_RESOURCE, Result};
/// The portable material extension.
pub const MATERIAL_EXT: &str = "mcmat";
/// `format` of every manifest.
pub const FORMAT: &str = "craft-material";
/// Newest manifest version this build reads and writes.
pub const VERSION: u32 = 1;
const MANIFEST: &str = "material.json";
const SOURCE: &str = "source.mcraft";
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Manifest {
pub format: String,
pub version: u32,
pub name: String,
/// The graph of the source package the maps were cooked from.
pub graph: String,
/// Size of the maps in pixels.
pub size: [u32; 2],
pub maps: Vec<MapEntry>,
/// Parameters other apps may change (scalar, vector, color, toggle and option inputs).
pub parameters: Vec<Parameter>,
/// Image inputs of the graph, fed from mesh maps by identifier.
pub inputs: Vec<ImageInput>,
#[serde(default)]
pub presets: Vec<PresetEntry>,
pub source: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MapEntry {
/// Usage id: `baseColor`, `normal`, `roughness`, `metallic`, `height`, `ambientOcclusion`,
/// `emissive`, `opacity`, `specular`.
pub usage: String,
pub file: String,
/// `srgb` or `linear`.
pub color_space: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Parameter {
#[serde(flatten)]
pub param: ExposedParam,
/// The value the maps were cooked with.
pub value: Value,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ImageInput {
pub identifier: String,
/// `gray` or `color`.
pub kind: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PresetEntry {
pub name: String,
pub values: BTreeMap<String, Value>,
}
/// Whether maps of `usage` hold colors (stored sRGB-encoded) rather than data (linear).
pub fn srgb_usage(usage: &str) -> bool {
matches!(usage, "baseColor" | "emissive" | "specular")
}
/// Whether other apps can set a value of this type from the manifest.
pub fn portable(v: &Value) -> bool {
matches!(
v,
Value::Float(_)
| Value::Float2(_)
| Value::Float3(_)
| Value::Float4(_)
| Value::Int(_)
| Value::Int2(_)
| Value::Bool(_)
| Value::Color(_)
| Value::Enum(_)
)
}
/// Write a portable material: `manifest` (its `source` is set here), the encoded maps named by
/// `manifest.maps[].file`, and the source package bytes.
pub fn write_material(manifest: &Manifest, maps: &[(String, Vec<u8>)], source: &[u8]) -> Result<Vec<u8>> {
let io = |e: zip::result::ZipError| FormatError::Io(e.to_string());
let manifest = Manifest { source: SOURCE.into(), ..manifest.clone() };
let json = serde_json::to_vec_pretty(&manifest).map_err(|e| FormatError::Io(e.to_string()))?;
let mut buf = Cursor::new(Vec::new());
{
let mut z = zip::ZipWriter::new(&mut buf);
let deflate = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
// Maps and the package are already compressed.
let stored = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
z.start_file(MANIFEST, deflate).map_err(io)?;
z.write_all(&json).map_err(|e| FormatError::Io(e.to_string()))?;
for (file, bytes) in maps {
z.start_file(file.as_str(), stored).map_err(io)?;
z.write_all(bytes).map_err(|e| FormatError::Io(e.to_string()))?;
}
z.start_file(SOURCE, stored).map_err(io)?;
z.write_all(source).map_err(|e| FormatError::Io(e.to_string()))?;
z.finish().map_err(io)?;
}
Ok(buf.into_inner())
}
/// Read a portable material's manifest and source package bytes.
pub fn read_material(bytes: &[u8]) -> Result<(Manifest, Vec<u8>)> {
let bad = |m: String| FormatError::BadPackage(format!("portable material: {m}"));
let mut z = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|e| bad(e.to_string()))?;
let mut read = |name: &str, cap: u64| -> Result<Vec<u8>> {
let mut data = Vec::new();
z.by_name(name).map_err(|_| bad(format!("{name} is missing")))?.take(cap).read_to_end(&mut data).map_err(|e| FormatError::Io(e.to_string()))?;
Ok(data)
};
let manifest: Manifest = serde_json::from_slice(&read(MANIFEST, MAX_JSON)?).map_err(|e| bad(e.to_string()))?;
if manifest.format != FORMAT || manifest.version > VERSION {
return Err(bad(format!("unsupported {} version {}", manifest.format, manifest.version)));
}
let source = read(&manifest.source, MAX_RESOURCE)?;
Ok((manifest, source))
}
/// Whether `bytes` look like a portable material (a zip with `material.json`).
pub fn is_material(bytes: &[u8]) -> bool {
zip::ZipArchive::new(Cursor::new(bytes)).is_ok_and(|mut z| z.by_name(MANIFEST).is_ok())
}
#[cfg(test)]
mod tests {
use super::*;
fn manifest() -> Manifest {
let param = ExposedParam {
id: "rough".into(),
label: "Roughness".into(),
group: String::new(),
default: Value::Float(0.5),
min: 0.0,
max: 1.0,
options: Vec::new(),
};
Manifest {
format: FORMAT.into(),
version: VERSION,
name: "Bricks".into(),
graph: "Bricks".into(),
size: [64, 64],
maps: vec![MapEntry { usage: "baseColor".into(), file: "maps/baseColor.png".into(), color_space: "srgb".into() }],
parameters: vec![Parameter { param, value: Value::Float(0.25) }],
inputs: vec![ImageInput { identifier: "curvature".into(), kind: "gray".into() }],
presets: Vec::new(),
source: String::new(),
}
}
#[test]
fn round_trips_and_rejects_newer_versions() {
let m = manifest();
let bytes = write_material(&m, &[("maps/baseColor.png".into(), vec![1, 2, 3])], b"pkg").unwrap();
assert!(is_material(&bytes));
let (back, source) = read_material(&bytes).unwrap();
assert_eq!(back, Manifest { source: SOURCE.into(), ..m.clone() }, "the writer names the source entry");
assert_eq!(source, b"pkg");
// Parameters are flat objects with the value in the API's typed form.
let json = serde_json::to_value(&m).unwrap();
assert_eq!(json["parameters"][0]["id"], "rough");
assert_eq!(json["parameters"][0]["value"], serde_json::json!({"t": "float", "v": 0.25}));
let newer = Manifest { version: VERSION + 1, ..m };
assert!(read_material(&write_material(&newer, &[], b"").unwrap()).is_err());
assert!(!is_material(b"not a zip"));
assert!(read_material(b"garbage").is_err());
}
}
+2
View File
@@ -44,6 +44,8 @@ pub const CATALOG: &[Item] = &[
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")),
+36
View File
@@ -504,6 +504,7 @@ fn graph_props(app: &mut MaterialCraftApp, ui: &mut Ui) {
});
}
});
input_previews(app, ui, &g);
section(ui, "graph-outputs", tr("Outputs"), |ui| {
for n in g.nodes.iter().filter(|n| n.def == "output") {
let usage = n.params.get("usage").and_then(Value::as_i32).unwrap_or(0) as usize;
@@ -520,6 +521,41 @@ fn graph_props(app: &mut MaterialCraftApp, ui: &mut Ui) {
});
}
/// Preview images of the graph's input nodes: a bitmap resource, or (desktop) an image file such
/// as a mesh map baked in TextureCraft.
fn input_previews(app: &mut MaterialCraftApp, ui: &mut Ui, g: &materialcraft_engine::core::Graph) {
let inputs = materialcraft_engine::material_cmds::image_inputs(g);
if inputs.is_empty() {
return;
}
let resources: Vec<String> = app.session.pkg.resources.iter().map(|r| r.name.clone()).collect();
section(ui, "graph-input-images", tr("Input previews"), |ui| {
for i in &inputs {
let id = &i.identifier;
let bound = g.input_images.get(id);
ui.horizontal(|ui| {
ui.label(id);
egui::ComboBox::from_id_salt(("input-preview", id)).width(120.0).selected_text(bound.map_or(tr("None"), String::as_str)).show_ui(ui, |ui| {
if ui.selectable_label(bound.is_none(), tr("None")).clicked() {
app.run("graph.input.unbind", json!({"identifier": id}));
}
for r in &resources {
if ui.selectable_label(bound == Some(r), r).clicked() {
app.run("graph.input.bind", json!({"identifier": id, "resource": r}));
}
}
});
#[cfg(not(target_arch = "wasm32"))]
if crate::widgets::icon_button(ui, icon::FOLDER_OPEN, tr("Pick an image file (a mesh map baked in TextureCraft)"), false, 18.0).clicked()
&& let Some(p) = rfd::FileDialog::new().add_filter("Images", materialcraft_engine::formats::IMAGE_EXTENSIONS).pick_file()
{
app.run("graph.input.bind", json!({"identifier": id, "path": p.display().to_string()}));
}
});
}
});
}
/// Presets: apply one, save the current inputs under a name, delete one.
fn presets_bar(app: &mut MaterialCraftApp, ui: &mut Ui, g: &materialcraft_engine::core::Graph) {
let name_id = ui.make_persistent_id("preset-name");
+11 -1
View File
@@ -160,7 +160,7 @@ mod web {
/// File ▸ Open: a package, picked in the browser.
pub fn open(ctx: &egui::Context) {
pick(ctx, "MaterialCraft package", &["mcraft"], Pick::Package);
pick(ctx, "MaterialCraft package or material", crate::windows::OPEN_EXTS, Pick::Package);
}
/// 3D view ▸ Scene ▸ Load mesh.
@@ -185,6 +185,16 @@ mod web {
}
}
/// File ▸ Export material: download the open graph as `<graph>.mcmat`.
pub fn export_material(app: &mut MaterialCraftApp) {
use materialcraft_engine::material_cmds::{MaterialOptions, material_bytes};
let name = format!("{}.mcmat", materialcraft_engine::formats::safe_file_name(&app.session.graph().map(|g| g.name.clone()).unwrap_or_default()));
match material_bytes(&app.session, app.session.graph, &MaterialOptions::default()).map_err(|e| e.to_string()).and_then(|b| download(&name, &b)) {
Ok(()) => app.toast(format!("{} {name}", tr("Downloaded")), false),
Err(e) => app.toast(format!("{}: {e}", tr("Couldn't export")), true),
}
}
/// Export outputs: one file downloads as is, several as `<graph>_outputs.zip`.
pub fn export(app: &mut MaterialCraftApp, params: &serde_json::Value) {
let result = materialcraft_engine::file_cmds::export_params(&app.session, params)
+24 -1
View File
@@ -8,6 +8,7 @@ use egui::{Color32, RichText, TextureHandle, Ui, vec2};
use egui_phosphor::regular as icon;
use materialcraft_engine::core::NodeId;
use materialcraft_engine::core::function::FnGraph;
use materialcraft_engine::formats::material::MATERIAL_EXT;
use serde_json::{Value, json};
use crate::MaterialCraftApp;
@@ -505,6 +506,9 @@ pub fn function_summary(app: &mut MaterialCraftApp, ui: &mut Ui, node: NodeId, p
});
}
/// Extensions File ▸ Open reads: packages and portable materials (opening their source package).
pub const OPEN_EXTS: &[&str] = &["mcraft", MATERIAL_EXT];
/// File menu actions that need a file dialog. Returns true when handled.
pub fn file_action(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) -> bool {
#[cfg(not(target_arch = "wasm32"))]
@@ -513,7 +517,7 @@ pub fn file_action(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) ->
{
match id {
"file.open" => {
if let Some(p) = rfd::FileDialog::new().add_filter("MaterialCraft package", &["mcraft"]).pick_file() {
if let Some(p) = rfd::FileDialog::new().add_filter("MaterialCraft package or material", OPEN_EXTS).pick_file() {
open_path(app, &p.display().to_string());
}
true
@@ -537,6 +541,24 @@ pub fn file_action(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) ->
}
true
}
"file.exportMaterial" => {
let name = format!(
"{}.{MATERIAL_EXT}",
materialcraft_engine::formats::safe_file_name(&app.session.graph().map(|g| g.name.clone()).unwrap_or_default())
);
if let Some(p) = rfd::FileDialog::new().set_file_name(name).add_filter("MaterialCraft material", &[MATERIAL_EXT]).save_file()
&& let Some(r) = app.run("file.exportMaterial", json!({"path": p.display().to_string()}))
{
app.toast(format!("{} {}", tr("Exported"), r["path"].as_str().unwrap_or_default()), false);
}
true
}
"file.sendToTextureCraft" => {
if app.run("file.sendToTextureCraft", json!({})).is_some() {
app.toast(tr("Sent to TextureCraft: find it on the shelf under My smart materials"), false);
}
true
}
"file.importBitmap" => {
if let Some(p) = rfd::FileDialog::new().add_filter("Images", materialcraft_engine::formats::IMAGE_EXTENSIONS).pick_file()
&& let Some(r) = app.run("file.importBitmap", json!({"path": p.display().to_string()}))
@@ -558,6 +580,7 @@ pub fn file_action(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) ->
"file.open" => crate::web_files::open(ctx),
"file.importBitmap" => crate::web_files::import_bitmap(ctx),
"file.save" | "file.saveAs" => crate::web_files::save(app),
"file.exportMaterial" => crate::web_files::export_material(app),
_ => return false,
}
true
+12 -3
View File
@@ -1,6 +1,6 @@
# Architecture
> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-02 · **Change:** major (first version) · **Target:** the professional node-based material workflow
> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-02 · **Change:** minor (portable materials and TextureCraft) · **Target:** the professional node-based material workflow
MaterialCraft is a Cargo workspace of small crates in strict layers (`cargo xtask layers` enforces
them). Everything below the UI is plain Rust with no UI toolkit and builds for
@@ -18,8 +18,8 @@ L1 nodes the node library: NodeDef (ports, parameters, category, cook fn) f
L2 eval cooking: topological order, output sizes (relative to input / parent, absolute, preview
cap), parameter resolution (defaults, overrides, bindings to exposed inputs), the
content-addressed LRU cache, graph instances (sub-graphs, recursion-guarded)
L2 formats .mcraft packages (zip: package.json + resources/), bitmap decode, texture encode
(PNG/JPEG/TGA/TIFF/BMP/WEBP/EXR/HDR at 8/16/32 bits), atomic writes
L2 formats .mcraft packages (zip: package.json + resources/), .mcmat portable materials, bitmap
decode, texture encode (PNG/JPEG/TGA/TIFF/BMP/WEBP/EXR/HDR at 8/16/32 bits), atomic writes
L3 engine Session (package, open graph, selection, 2D/3D view state, snapshot undo, cache),
the command registry, inspect, sample materials and graph templates
L3 render the 3D view: BVH ray casts, parallax occlusion from the height output, GGX PBR with
@@ -73,3 +73,12 @@ checks and README screenshots.
A `.mcraft` package is a zip: `package.json` (the serde `Package`, format version 1) and
`resources/<name>` for embedded bitmaps. Node parameters are stored only where they differ from the
catalog defaults, so new defaults reach old files and files stay small.
## Other apps
A `.mcmat` portable material (`formats/src/material.rs`, `engine/src/material_cmds.rs`) holds a
graph's cooked maps, its portable exposed inputs, presets and input nodes, and the source package.
TextureCraft paints with it and re-cooks it by running `materialcraft-cli run <package>
file.exportMaterial {path, size, values, inputs}`: the apps share the file format and the command
line, never code. Graphs keep preview images for their input nodes (`Graph::input_images`, mesh
maps from TextureCraft); `eval::cook` feeds them to the top-level graph, and a caller's images win.
+38 -2
View File
@@ -1,6 +1,6 @@
# Control protocol and MCP
> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-02 · **Change:** major (first version) · **Target:** the professional node-based material workflow
> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-02 · **Change:** minor (portable materials for TextureCraft) · **Target:** the professional node-based material workflow
Agents drive MaterialCraft three ways, all dispatching the same engine commands:
@@ -83,9 +83,45 @@ casts, arithmetic (`add sub mul div mod neg dot`), logic and comparison (`and or
ne`), functions (`abs floor ceil frac sqrt exp log sin cos tan atan2 pow min max clamp lerp length
normalize rand noise`) and `if_else`. Values are 4-wide; scalars broadcast.
## Portable materials (TextureCraft)
A `.mcmat` portable material is a zip: `material.json` (manifest), `maps/<usage>.png` and
`source.mcraft` (the package). TextureCraft applies it as a fill layer and keeps the exposed inputs
editable, re-cooking through `materialcraft-cli`. The format is a convention the two apps share;
each has its own reader and writer (`crates/formats/src/material.rs` here), so keep them in step.
```json
{ "format": "craft-material", "version": 1, "name": "Brick wall", "graph": "Brick_wall", "size": [2048, 2048],
"maps": [{"usage": "baseColor", "file": "maps/baseColor.png", "colorSpace": "srgb"}],
"parameters": [{"id": "wear", "label": "Wear", "default": {"t": "float", "v": 0.5}, "min": 0, "max": 1,
"value": {"t": "float", "v": 0.8}}],
"inputs": [{"identifier": "curvature", "kind": "gray"}],
"presets": [{"name": "Worn", "values": {"wear": {"t": "float", "v": 1.0}}}],
"source": "source.mcraft" }
```
- Usages: `baseColor`, `normal`, `roughness`, `metallic`, `height`, `ambientOcclusion`, `emissive`,
`opacity`, `specular` (the first output of each). Color usages (`baseColor`, `emissive`,
`specular`) are 8-bit sRGB PNGs, the rest 16-bit linear. Normals are tangent space, OpenGL (Y+);
height is 0..1 with 0.5 at the surface.
- Parameters are the exposed inputs other apps can set (float, float2-4, int, int2, bool, color,
enum), values in the typed form `{"t", "v"}`; colors are linear RGBA.
- Inputs are the graph's input nodes. Mesh maps feed them by identifier: `ambientOcclusion`,
`curvature`, `thickness`, `position`, `worldNormal`, `normal`, `height`, `id`, `bentNormal`,
`opacity`, `colorMap`, `worldDirection`.
- Readers ignore unknown fields and refuse a `version` newer than they know.
| Command | Params |
|---|---|
| `file.exportMaterial` | `{path, graph?, size? (px), values? {input: value}, inputs? {identifier: image path}}`: cook and write a `.mcmat`. TextureCraft runs `materialcraft-cli run source.mcraft file.exportMaterial {...}` to re-cook at its texture set's resolution with its own values and baked mesh maps |
| `file.sendToTextureCraft` | `{graph?}`: export into TextureCraft's library folder (`Documents/TextureCraft/library`), where its shelf lists it |
| `graph.input.bind` / `graph.input.unbind` | `{identifier, resource? \| path?}` / `{identifier}`: a preview image for an input node (a mesh map exported from TextureCraft), saved in the package |
| `file.open` | also opens a `.mcmat`'s source package, on its graph, with no file name |
## MCP tools
`session_inspect`, `command_list`, `command_run`, `command_batch`, `library_list`, `graph_new`,
`node_add`, `node_connect`, `node_param`, `package_open`, `package_save`, `bitmap_import`,
`outputs_export`, `view_render` (headless) and, bridged to the app, `view_screenshot`,
`ui_screenshot`, `ui_inspect`, `ui_menu_invoke`, `ui_input`.
`ui_screenshot`, `ui_inspect`, `ui_menu_invoke`, `ui_input`. `package_open` opens `.mcmat` files
too; exporting one is CLI-only for now (the workspace sandbox refuses `file.*` commands).
+3 -2
View File
@@ -1,6 +1,6 @@
# File format parity
> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-02 · **Change:** major (first version) · **Target:** the professional node-based material workflow
> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-02 · **Change:** minor (`.mcmat` portable materials) · **Target:** the professional node-based material workflow
MaterialCraft does not read or write the reference app's proprietary package or archive formats
(a non-goal of the clean room). It has its own package format and reads and writes the open image
@@ -19,7 +19,7 @@ formats material artists exchange.
| Radiance HDR | Yes | Yes | Float (RGBE) | same |
| SVG, fonts (resources) | No | — | — | gap |
| Meshes for the 3D view (OBJ, glTF, FBX) | No | — | — | gap |
| Published material archives | — | No | — | gap |
| `.mcmat` portable material (zip: manifest, cooked maps, source package) | Yes (opens the source package) | Yes | Maps at 8-bit sRGB (color) / 16-bit linear (data); exposed inputs, presets and input nodes in the manifest. Our own format, shared with TextureCraft, not the reference app's archive format | `formats::material::tests`, engine `material_cmds::tests`, TextureCraft `materialcraft_link` |
Exports write base color, emissive and specular through the sRGB curve and data maps (normal,
roughness, metallic, height, ambient occlusion, opacity) linear.
@@ -28,4 +28,5 @@ roughness, metallic, height, ambient occlusion, opacity) linear.
| Date | Change | Summary |
|---|---|---|
| 2026-11-02 | minor | `.mcmat` portable materials replace the published-archive gap |
| 2026-11-02 | major | First version |
+3 -2
View File
@@ -1,6 +1,6 @@
# Gaps
> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-02 · **Change:** major (closed function editor, dynamic parameters, presets, FX-Map/SVG/Text, browser I/O, accessibility) · **Target:** the professional node-based material workflow
> **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
Every known shortfall, most important first. Pick from the top.
@@ -9,7 +9,7 @@ Every known shortfall, most important first. Pick from the top.
| 1 | Node library breadth | 227 nodes vs. ~400 in the reference library | Recipes that need scan processing, more grunges, splines or SDF shapes | 30 h | target-app-parity (Node library) |
| 2 | GPU 3D view with tessellation and lights | CPU renderer with parallax only | Displacement previews, light setups | 12 h | target-app-parity (3D view) |
| 3 | Mesh-based generators and bakers | None | Workflows that start from a mesh | 15 h | target-app-parity (Node library) |
| 4 | Published material archives | Only `.mcraft` sources (the CLI renders them with `--set`) | Sharing cooked materials with other tools | 6 h | target-app-parity (Files) |
| 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 | — |
@@ -22,5 +22,6 @@ Every known shortfall, most important first. Pick from the top.
| Date | Change | Summary |
|---|---|---|
| 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 |
+5 -5
View File
@@ -1,6 +1,6 @@
# Roadmap detail
> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-02 · **Change:** major (≈ 66%) · **Target:** the professional node-based material workflow
> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-02 · **Change:** minor (portable materials done, ≈ 67%) · **Target:** the professional node-based material workflow
## Milestones
@@ -12,7 +12,7 @@
| M3 Node breadth | In progress | 227 of ~400 library nodes |
| M4 Function graphs | In progress | Evaluator, visual editor and dynamic parameters done; loops and reusable functions next |
| M5 Graph features | In progress | Exposed inputs, instances, presets and groups done; visibility conditions next |
| M6 Files | In progress | Packages, bitmaps, export, mesh import, browser I/O done; published archives next |
| M6 Files | In progress | Packages, bitmaps, export, mesh import, browser I/O and `.mcmat` portable materials (TextureCraft interop) done; package dependencies next |
| M7 Automation | Done | CLI, control channel with synthetic input, MCP server |
| M8 3D view depth | In progress | Mesh import done; GPU renderer, tessellation, lights next |
| M9 Web + packaging | In progress | WASM builds and browser file I/O done; the first release run next |
@@ -22,7 +22,7 @@
1. Node library breadth (gap 1): scan processing, more grunges, spline tools, SDF shapes.
2. The GPU 3D view (gap 2) and mesh-based generators (gap 3).
3. Published archives (gap 4) and function loops (gap 5).
3. Function loops (gap 5) and the portable-material MCP tool (gap 4).
## Remaining effort (Opus 5.5 agent hours)
@@ -31,12 +31,12 @@
| Node library to ~400 nodes | 30 h |
| 3D view on the GPU, tessellation, lights | 12 h |
| Mesh-based generators | 15 h |
| Published archives | 6 h |
| Portable materials over MCP | 1 h |
| Function loops and reusable functions | 5 h |
| Graph features: visibility conditions, per-instance sizes | 4 h |
| UX: keymap, translations, minimap, tabs | 13 h |
| Release | 3 h |
| **Total** | **≈ 88 h** |
| **Total** | **≈ 83 h** |
## Revision history
+6 -5
View File
@@ -1,9 +1,9 @@
# Parity with the reference workflow
> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-02 · **Change:** major (function editor, 227 nodes, FX-Map/SVG/Text) · **Target:** the professional node-based material workflow (desktop app; the web app is assessed later)
> **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)
**Overall: ≈ 66%** 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: ≈ 88 Opus
**Overall: ≈ 67%** 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 |
@@ -15,10 +15,10 @@ automation + tests), weighted by how much of the day each area carries. **Remain
| Graph parameters and instances | 8 | 70% | Exposed inputs (float, int, bool, enum, color) bound to parameters of any compatible type, shown in groups, edited with one shared editor on the graph and on its instances; presets (save, apply, delete); sub-graph instances with their own inputs and outputs; graph attributes; `--set` on the CLI | Visibility conditions, per-instance output sizes, embedded vs. linked packages |
| 2D view | 5 | 80% | Pan/zoom, fit and 1:1, RGBA/R/G/B/A isolation, 3×3 tiling check, histogram, pixel readout, size/format line, save image | Color picker to parameters, UV overlay |
| 3D view | 10 | 55% | Rounded cube, cube, sphere, cylinder, plane, torus and material ball; OBJ, glTF and GLB meshes; base color, normal, roughness, metallic, height (parallax occlusion), AO, emissive and opacity; 4 procedural environments with rotation and exposure; orbit/zoom; tiling; supersampling at rest | GPU renderer with tessellation, lights, material/shader switching, path-traced renderer |
| Files | 8 | 60% | `.mcraft` packages with embedded bitmaps; 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 | Published (cooked) material archives, package dependencies, SVG and font files as resources |
| Files | 8 | 70% | `.mcraft` packages with embedded bitmaps; `.mcmat` portable materials (cooked maps, exposed inputs, presets, input nodes, the source package) that TextureCraft paints with and re-cooks through the CLI at its own resolution, values and mesh maps; preview images for input nodes; export of every output (PNG, JPEG, TGA, TIFF, BMP, WEBP, EXR, HDR; 8/16/32 bits; name pattern; sRGB vs. linear by usage); bitmap import (PNG, JPEG, TGA, TIFF, BMP, WEBP, EXR, HDR); mesh import (OBJ, glTF, GLB); open, save, import and export in the browser; atomic writes; autosave; recent files | An MCP tool for portable materials, package dependencies, SVG and font files as resources |
| UI and UX | 8 | 70% | Dockable/floatable panels (explorer, library, graph, 3D, 2D, properties, console, history), menus, main toolbar, graph toolbar with atomic quick-insert, library with live previews, properties with curve/gradient/color editors, New graph dialog with rendered templates, export dialog, preferences (brightness, accent, scale, preview size, autosave), shortcuts list, home screen at startup (samples and recent files), visual function editor, presets bar, accessible names on every widget, status bar | Translations, keymap editor, minimap, multi-graph tabs |
| Platforms | 4 | 50% | Windows, macOS, Linux, FreeBSD and web builds compile; browser file I/O; packaging scripts and release workflows | First release run |
| **Total** | **100** | **≈ 66%** | | |
| **Total** | **100** | **≈ 67%** | | |
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,5 +35,6 @@ and is tested.
| Date | Change | Summary |
|---|---|---|
| 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 |