mirror of
https://github.com/storytold/materialcraft.git
synced 2026-11-19 05:50:57 +01:00
Auto: Fix HDR mipmaps and reuse image processing buffers
Prevent overflow in nearest-filter mipmaps and retain regression coverage. Reuse pattern, precision, channel and blur buffers. Wait for asynchronous parameter cooks in snapshot tests. Complete scoped cleanup and remove confirmed unused dependencies. Validated affected release suites, Clippy, layering, wasm, hostile-input checks and all 43 offscreen snapshots.
This commit is contained in:
1 parent
2ee4537c65
commit
4b5c27188c
46 files changed
+670
-420
No files matched your search
Generated
-2
@@ -2826,9 +2826,7 @@ dependencies = [
|
||||
"getrandom 0.3.4",
|
||||
"image",
|
||||
"materialcraft-engine",
|
||||
"materialcraft-formats",
|
||||
"materialcraft-render",
|
||||
"rayon",
|
||||
"rmcp",
|
||||
"rustix 1.1.6",
|
||||
"schemars",
|
||||
|
||||
+1
-2
@@ -73,7 +73,6 @@ dds = { version = "0.2", default-features = false }
|
||||
half = "2"
|
||||
eframe = { version = "0.37", default-features = false }
|
||||
egui = "0.37"
|
||||
wgpu = "30"
|
||||
rfd = "0.17"
|
||||
rustix = { version = "1", default-features = false, features = ["std", "fs", "process"] }
|
||||
zip = { version = "2", default-features = false, features = ["deflate"] }
|
||||
@@ -87,7 +86,7 @@ flate2 = { version = "1", default-features = false, features = ["rust_backend"]
|
||||
cap-std = "4"
|
||||
getrandom = "0.3"
|
||||
# Shared Craft egui components (widget palette, icon buttons, panel docking): storytold/craft-libs,
|
||||
# MIT OR Apache-2.0, every craft-libs crate pinned to one rev.
|
||||
# MIT OR Apache-2.0, with each dependency pinned to its reviewed revision
|
||||
egui_kittest = "0.37"
|
||||
craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d" }
|
||||
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d", features = ["serde"] }
|
||||
|
||||
@@ -11,12 +11,10 @@ workspace = true
|
||||
[dependencies]
|
||||
materialcraft-engine = { workspace = true }
|
||||
materialcraft-render = { workspace = true }
|
||||
materialcraft-formats = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
image = { workspace = true }
|
||||
rayon = { workspace = true }
|
||||
rmcp = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
schemars = { workspace = true }
|
||||
|
||||
@@ -264,15 +264,15 @@ impl Headless {
|
||||
Ok(Rendered { width: w, height: h, png })
|
||||
}
|
||||
|
||||
fn render_2d(&mut self, o: &RenderOptions, max: u32) -> Result<(u32, u32, Vec<u8>), AutomationError> {
|
||||
let img = match o.node {
|
||||
Some(n) => self.session.cooked.image(NodeId(n), o.port.unwrap_or(0)).ok_or_else(|| bad(format!("node {n} has no cooked output")))?,
|
||||
fn render_2d(&mut self, options: &RenderOptions, maximum_side: u32) -> Result<(u32, u32, Vec<u8>), AutomationError> {
|
||||
let image = match options.node {
|
||||
Some(n) => self.session.cooked.image(NodeId(n), options.port.unwrap_or(0)).ok_or_else(|| bad(format!("node {n} has no cooked output")))?,
|
||||
None => self.session.view2d_image().map(|(_, i)| i).ok_or_else(|| bad("nothing to show: the graph has no outputs; pass `node`"))?,
|
||||
};
|
||||
|
||||
let (w, h) = (o.width.unwrap_or(img.width()).clamp(16, max), o.height.unwrap_or(img.height()).clamp(16, max));
|
||||
let img = img.resize(w, h, true);
|
||||
Ok((w, h, img.to_rgba8_display()))
|
||||
let (w, h) = (options.width.unwrap_or(image.width()).clamp(16, maximum_side), options.height.unwrap_or(image.height()).clamp(16, maximum_side));
|
||||
let image = image.resize(w, h, true);
|
||||
Ok((w, h, image.to_rgba8_display()))
|
||||
}
|
||||
|
||||
fn render_3d(&mut self, o: &RenderOptions, max: u32) -> (u32, u32, Vec<u8>) {
|
||||
|
||||
@@ -149,26 +149,27 @@ fn format(s: &mut Session, p: &J) -> Result<J> {
|
||||
})
|
||||
}
|
||||
|
||||
fn cook(s: &mut Session, p: &J) -> Result<J> {
|
||||
let index = match p.get("graph").filter(|graph| !graph.is_null()) {
|
||||
None => s.graph,
|
||||
fn cook(session: &mut Session, parameters: &J) -> Result<J> {
|
||||
let index = match parameters.get("graph").filter(|graph| !graph.is_null()) {
|
||||
None => session.graph,
|
||||
Some(graph) => {
|
||||
let index = graph.as_u64().and_then(|index| usize::try_from(index).ok()).ok_or_else(|| bad("graph.cook", "`graph` is a graph index"))?;
|
||||
let graph = s.pkg.graph(index)?;
|
||||
let graph = session.pkg.graph(index)?;
|
||||
if graph.function.is_some() {
|
||||
return Err(bad("graph.cook", "a Function Graph has no outputs to compute"));
|
||||
}
|
||||
|
||||
index
|
||||
}
|
||||
};
|
||||
let cooked = if index != s.graph || boolp(p, "full") == Some(true) { s.cook_full(index) } else { s.cook().clone() };
|
||||
let g = s.pkg.graph(index)?;
|
||||
let cooked = if index != session.graph || boolp(parameters, "full") == Some(true) { session.cook_full(index) } else { session.cook().clone() };
|
||||
let graph = session.pkg.graph(index)?;
|
||||
Ok(json!({
|
||||
"ms": cooked.ms,
|
||||
"nodes": cooked.nodes.iter().map(|(id, r)| {
|
||||
let n = g.node(*id).ok();
|
||||
json!({"id": id.0, "def": n.map(|n| n.def.clone()), "ms": r.ms, "cached": r.cached, "error": r.error,
|
||||
"size": r.outputs.first().and_then(materialcraft_eval::NodeOutput::as_image).map(|i| [i.width(), i.height()])})
|
||||
"nodes": cooked.nodes.iter().map(|(id, result)| {
|
||||
let node = graph.node(*id).ok();
|
||||
json!({"id": id.0, "def": node.map(|node| node.def.clone()), "ms": result.ms, "cached": result.cached, "error": result.error,
|
||||
"size": result.outputs.first().and_then(materialcraft_eval::NodeOutput::as_image).map(|image| [image.width(), image.height()])})
|
||||
}).collect::<Vec<_>>(),
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -32,7 +32,7 @@ impl NodeLibrary {
|
||||
let index = source.graphs.iter().position(|candidate| candidate.function.is_none() && candidate.sbs_path() == graph)?;
|
||||
let size = size.clamp(1, COOKED_SIZE);
|
||||
|
||||
// A session links the graph's instances and functions to the library, as an opened package gets
|
||||
// A session resolves library references just as it does for an opened package
|
||||
let mut session = Session::with_library(Package::clone(source), library.clone());
|
||||
session.limit_preview_caches();
|
||||
if cancel.load(Ordering::Relaxed) {
|
||||
@@ -43,7 +43,7 @@ impl NodeLibrary {
|
||||
let decode = session.resource_decoder();
|
||||
let mut options = materialcraft_eval::Options::new(&decode);
|
||||
|
||||
// Thin lines and fine grain vanish when cooked at thumbnail size, so the graph cooks larger and is scaled down
|
||||
// Cook larger before downsampling so fine detail survives in thumbnails
|
||||
let cooked_size = size.max(COOKED_SIZE);
|
||||
options.max_size = Some(cooked_size);
|
||||
options.cancel = Some(cancel);
|
||||
|
||||
@@ -54,64 +54,66 @@ pub(crate) fn specs() -> Vec<CommandSpec> {
|
||||
|
||||
pub use crate::MaterialOptions;
|
||||
|
||||
/// 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];
|
||||
/// Cook `graph_index` with `options` and pack it as a portable material (`.mcmat` bytes)
|
||||
pub fn material_bytes(session: &Session, graph_index: usize, options: &MaterialOptions) -> Result<Vec<u8>> {
|
||||
let mut package = session.pkg.clone();
|
||||
let graph = package.graph_mut(graph_index)?;
|
||||
if let Some(side_pixels) = options.size {
|
||||
let log2 = 31 - side_pixels.clamp(16, 8192).leading_zeros();
|
||||
graph.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.environment = s.environment;
|
||||
opts.inputs = o.inputs.clone();
|
||||
let cooked = materialcraft_eval::cook(&pkg, gi, &opts, &s.cache);
|
||||
graph.inputs.extend(options.values.clone());
|
||||
let graph = package.graph(graph_index)?;
|
||||
let decode = session.resource_decoder();
|
||||
let mut cook_options = materialcraft_eval::Options::new(&decode);
|
||||
cook_options.environment = session.environment;
|
||||
cook_options.inputs = options.inputs.clone();
|
||||
let cooked = materialcraft_eval::cook(&package, graph_index, &cook_options, &session.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 };
|
||||
for (_, usage, _, image) in materialcraft_eval::outputs(graph, &cooked) {
|
||||
let Some(image) = image 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)?));
|
||||
maps.push((file.clone(), encode(image, "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.width(), img.height()];
|
||||
size = [image.width(), image.height()];
|
||||
}
|
||||
if entries.is_empty() {
|
||||
return Err(bad(
|
||||
"file.exportMaterial",
|
||||
format!(
|
||||
"graph `{}` has no outputs with a material usage ({})",
|
||||
g.name,
|
||||
graph.name,
|
||||
ComponentUsage::ALL.iter().filter(|usage| **usage != ComponentUsage::ANY).map(|usage| usage.id).collect::<Vec<_>>().join(", ")
|
||||
),
|
||||
));
|
||||
}
|
||||
|
||||
let manifest = Manifest {
|
||||
format: FORMAT.into(),
|
||||
version: VERSION,
|
||||
name: g.name.replace('_', " "),
|
||||
graph: g.name.clone(),
|
||||
name: graph.name.replace('_', " "),
|
||||
graph: graph.name.clone(),
|
||||
size,
|
||||
maps: entries,
|
||||
parameters: g
|
||||
parameters: graph
|
||||
.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()) })
|
||||
.map(|e| Parameter { param: e.clone(), value: graph.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(),
|
||||
inputs: image_inputs(graph),
|
||||
presets: graph.presets.iter().map(|p| PresetEntry { name: p.name.clone(), values: p.values.clone() }).collect(),
|
||||
source: String::new(),
|
||||
};
|
||||
|
||||
let source = materialcraft_formats::sbs::write_sbs(&pkg)?;
|
||||
let source = materialcraft_formats::sbs::write_sbs(&package)?;
|
||||
Ok(materialcraft_formats::material::write_material(&manifest, &maps, &source)?)
|
||||
}
|
||||
|
||||
@@ -291,15 +293,22 @@ mod tests {
|
||||
crate::execute(&mut s, "graph.node.add", &json!({"def": "input_grayscale", "params": {"identifier": "curvature"}})).unwrap();
|
||||
let png = encode(&Image::filled(4, 4, craft_texture::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, "linear": true})).unwrap();
|
||||
|
||||
assert_eq!(s.graph().unwrap().input_images.get("curvature"), Some(&res));
|
||||
|
||||
let bytes = materialcraft_formats::sbs::write_sbs(&s.pkg).unwrap();
|
||||
let reopened = materialcraft_formats::sbs::read_sbs(&bytes, "input.sbs", &|_| None).unwrap().pkg;
|
||||
|
||||
assert_eq!(reopened.graphs[s.graph].input_images.get("curvature"), Some(&res));
|
||||
assert!(reopened.graphs[s.graph].input_images_linear.contains("curvature"));
|
||||
|
||||
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());
|
||||
@@ -338,23 +347,26 @@ mod tests {
|
||||
let output_path = dir.join("out.mcmat").to_str().unwrap().to_string();
|
||||
|
||||
let result = crate::execute(&mut s, "file.exportMaterial", &json!({"path": output_path, "size": 16, "inputs": {"normal": input_path}}));
|
||||
|
||||
assert!(result.is_ok());
|
||||
|
||||
let bytes = std::fs::read(&output_path).unwrap();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
|
||||
// The material archive stores maps uncompressed; pull the normal map
|
||||
// out of its local file header and decode it as linear data.
|
||||
// The uncompressed archive exposes the normal map after its local file header
|
||||
let name = b"maps/normal.png";
|
||||
let pos = bytes.windows(name.len()).position(|w| w == name).unwrap();
|
||||
let header = pos - 30;
|
||||
|
||||
assert_eq!(&bytes[header..header + 4], b"PK\x03\x04");
|
||||
|
||||
let name_len = u16::from_le_bytes([bytes[header + 26], bytes[header + 27]]) as usize;
|
||||
let extra_len = u16::from_le_bytes([bytes[header + 28], bytes[header + 29]]) as usize;
|
||||
let compressed = u32::from_le_bytes([bytes[header + 18], bytes[header + 19], bytes[header + 20], bytes[header + 21]]) as usize;
|
||||
let start = header + 30 + name_len + extra_len;
|
||||
let map = &bytes[start..start + compressed];
|
||||
let decoded = decode(map, true).unwrap();
|
||||
|
||||
assert!((decoded.get(0, 0, false)[0] - 128.0 / 255.0).abs() < 1e-3, "data inputs must be decoded as linear");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -426,29 +426,29 @@ impl Session {
|
||||
|
||||
/// A decoder for the package's bitmap resources (memoized, shareable with worker threads).
|
||||
pub fn resource_decoder(&self) -> impl Fn(&str) -> Option<Image> + Sync + Send + 'static {
|
||||
let mut res: Vec<(String, ResourceBytes)> = self.pkg.resources.iter().map(|r| (r.name.clone(), r.bytes.clone())).collect();
|
||||
res.extend(
|
||||
let mut resources: Vec<(String, ResourceBytes)> = self.pkg.resources.iter().map(|r| (r.name.clone(), r.bytes.clone())).collect();
|
||||
resources.extend(
|
||||
self.pkg
|
||||
.dependencies
|
||||
.iter()
|
||||
.flat_map(|(file, package)| package.resources.iter().map(move |resource| (format!("{file}\0{}", resource.name), resource.bytes.clone()))),
|
||||
);
|
||||
let memo = self.decoded.clone();
|
||||
let decoded = self.decoded.clone();
|
||||
|
||||
// Release decoded images of deleted or replaced resources
|
||||
let hashes = res.iter().map(|(_, bytes)| bytes.content_hash()).collect();
|
||||
memo.lock().unwrap_or_else(PoisonError::into_inner).retain_resources(&hashes);
|
||||
let hashes = resources.iter().map(|(_, bytes)| bytes.content_hash()).collect();
|
||||
decoded.lock().unwrap_or_else(PoisonError::into_inner).retain_resources(&hashes);
|
||||
move |requested: &str| {
|
||||
let (name, linear) = craft_texture::split_resource_key(requested);
|
||||
let (_, bytes) = res.iter().find(|(n, _)| n == name)?;
|
||||
let (_, bytes) = resources.iter().find(|(name_candidate, _)| name_candidate == name)?;
|
||||
let key = (bytes.content_hash(), linear);
|
||||
if let Some(i) = memo.lock().unwrap_or_else(PoisonError::into_inner).get(&key) {
|
||||
return Some(i);
|
||||
if let Some(image) = decoded.lock().unwrap_or_else(PoisonError::into_inner).get(&key) {
|
||||
return Some(image);
|
||||
}
|
||||
|
||||
let img = materialcraft_formats::decode(bytes.as_slice(), linear).ok()?;
|
||||
memo.lock().unwrap_or_else(PoisonError::into_inner).insert(key, img.clone());
|
||||
Some(img)
|
||||
let image = materialcraft_formats::decode(bytes.as_slice(), linear).ok()?;
|
||||
decoded.lock().unwrap_or_else(PoisonError::into_inner).insert(key, image.clone());
|
||||
Some(image)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -193,7 +193,10 @@ fn a_failed_group_recooks_if_it_cooked_a_temporary_document() {
|
||||
s.cook();
|
||||
Err(crate::EngineError::Other("failed".into()))
|
||||
});
|
||||
|
||||
assert!(result.is_err());
|
||||
|
||||
s.cook_if_dirty();
|
||||
|
||||
assert_eq!(s.cooked.image(id, 0).unwrap().data(), before.as_slice());
|
||||
}
|
||||
@@ -59,19 +59,28 @@ fn atomic_sample_round_trips_through_native_fields_and_cooks_identically() {
|
||||
assert!(!text.contains(forbidden));
|
||||
}
|
||||
let read = read_sbs(&bytes, "atomic_sample.sbs", &|_| None).unwrap();
|
||||
|
||||
assert!(read.warnings.is_empty(), "{:?}", read.warnings);
|
||||
|
||||
let mut loaded = Session::new(read.pkg);
|
||||
loaded.preview_size = Some(64);
|
||||
loaded.cook();
|
||||
|
||||
assert_eq!(original.graph().unwrap().connections.len(), loaded.graph().unwrap().connections.len());
|
||||
|
||||
for (before, after) in original.graph().unwrap().nodes.iter().zip(&loaded.graph().unwrap().nodes) {
|
||||
assert_eq!(before.def, after.def);
|
||||
|
||||
let result = &loaded.cooked.nodes[&after.id];
|
||||
|
||||
assert!(result.error.is_none(), "{}: {:?}", after.def, result.error);
|
||||
|
||||
match (original.cooked.image(before.id, 0), loaded.cooked.image(after.id, 0)) {
|
||||
(Some(before), Some(after)) => {
|
||||
assert_eq!((before.width(), before.height(), before.kind()), (after.width(), after.height(), after.kind()));
|
||||
|
||||
let error = before.data().iter().zip(after.data()).map(|(a, b)| (a - b).abs()).fold(0.0_f32, f32::max);
|
||||
|
||||
assert!(error < 1e-5, "pixel error {error}");
|
||||
}
|
||||
(None, None) => assert_eq!(original.cooked.value(before.id, 0), loaded.cooked.value(after.id, 0)),
|
||||
|
||||
@@ -101,9 +101,12 @@ fn unique_export_writes_both_maps_with_their_expected_pixels() {
|
||||
let (mut s, _) = session();
|
||||
let dir = TempDir::new("unique");
|
||||
let result = execute(&mut s, "file.export", &json!({"dir": dir.0, "pattern": "$(identifier)"})).unwrap();
|
||||
|
||||
assert_eq!(result["files"].as_array().unwrap().len(), 2);
|
||||
|
||||
for (name, value) in [("first.png", 0.2), ("second.png", 0.8)] {
|
||||
let image = formats::decode(&std::fs::read(dir.0.join(name)).unwrap(), false).unwrap();
|
||||
|
||||
assert_eq!((image.width(), image.height()), (16, 16));
|
||||
assert!((image.get(0, 0, false)[0] - value).abs() < 0.001, "{name}");
|
||||
}
|
||||
|
||||
@@ -25,17 +25,21 @@ fn output_size_function_controls_resolution_and_survives_sbs() {
|
||||
|
||||
let cooked = session.cook();
|
||||
let image = cooked.image(owner, 0).unwrap();
|
||||
|
||||
assert_eq!((image.width(), image.height()), (128, 32));
|
||||
assert!(cooked.nodes[&owner].error.is_none());
|
||||
|
||||
let bytes = formats::sbs::write_sbs(&session.pkg).unwrap();
|
||||
let loaded = formats::sbs::read_sbs(&bytes, "parameter-functions.sbs", &|_| None).unwrap();
|
||||
|
||||
assert!(loaded.warnings.is_empty(), "{:?}", loaded.warnings);
|
||||
|
||||
let mut reopened = Session::new(loaded.pkg);
|
||||
reopened.preview_size = None;
|
||||
let owner = reopened.graph().unwrap().nodes.iter().find(|node| node.def == "uniform").unwrap().id;
|
||||
let cooked = reopened.cook();
|
||||
let image = cooked.image(owner, 0).unwrap();
|
||||
|
||||
assert_eq!((image.width(), image.height()), (128, 32));
|
||||
}
|
||||
|
||||
@@ -90,6 +94,7 @@ fn native_dynamic_output_size_is_not_discarded_on_load() {
|
||||
let cooked = session.cook();
|
||||
|
||||
let image = cooked.image(owner, 0).unwrap();
|
||||
|
||||
assert_eq!((image.width(), image.height()), (64, 32));
|
||||
}
|
||||
|
||||
@@ -394,6 +399,7 @@ fn base_functions_inherit_from_the_primary_input_and_bypasses_keep_input_dimensi
|
||||
|
||||
let cooked = session.cook();
|
||||
let image = cooked.image(blend, 0).unwrap();
|
||||
|
||||
assert_eq!((image.width(), image.height()), (16, 16));
|
||||
assert_eq!(cooked.nodes[&blend].base.size, [32, 32]);
|
||||
assert_eq!(cooked.nodes[&output].base.size, [32, 32]);
|
||||
|
||||
@@ -23,23 +23,31 @@ fn grouping_noise_preserves_pixels_seed_and_undo() {
|
||||
let before_graphs = s.pkg.graphs.clone();
|
||||
let before = s.cook().image(output, 0).unwrap().clone();
|
||||
run(&mut s, "graph.createFromSelection", json!({"name": "Grouped_noise"}));
|
||||
// Force an actual cook instead of relying on the pre-grouping cache entry.
|
||||
|
||||
// Force an actual cook instead of relying on the pre-grouping cache entry
|
||||
s.cache.lock().unwrap().clear();
|
||||
let after = s.cook().image(output, 0).unwrap().clone();
|
||||
|
||||
assert!(before.data() == after.data(), "grouping changed the material at graph seed {seed}");
|
||||
assert_eq!((after.width(), after.height()), (64, 32));
|
||||
assert_eq!(s.pkg.graphs[1].seed, seed);
|
||||
|
||||
let grouped_graphs = s.pkg.graphs.clone();
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
|
||||
assert_eq!(s.pkg.graphs, before_graphs);
|
||||
assert_eq!(s.cook().image(output, 0).unwrap().data(), before.data());
|
||||
|
||||
run(&mut s, "edit.redo", json!({}));
|
||||
|
||||
assert_eq!(s.pkg.graphs, grouped_graphs);
|
||||
assert_eq!(s.cook().image(output, 0).unwrap().data(), before.data());
|
||||
|
||||
let bytes = formats::sbs::write_sbs(&s.pkg).unwrap();
|
||||
let mut reopened = Session::new(formats::sbs::read_sbs(&bytes, "seed.sbs", &|_| None).unwrap().pkg);
|
||||
reopened.preview_size = None;
|
||||
let reopened_output = reopened.graph().unwrap().nodes.iter().find(|node| node.def == "output").unwrap().id;
|
||||
|
||||
assert_eq!(reopened.cook().image(reopened_output, 0).unwrap().data(), before.data());
|
||||
}
|
||||
}
|
||||
@@ -79,15 +79,21 @@ fn package_save_and_open_round_trip() {
|
||||
let before = s.pkg.clone();
|
||||
run(&mut s, "file.newPackage", json!({}));
|
||||
run(&mut s, "file.open", json!({"path": path.to_str().unwrap()}));
|
||||
|
||||
assert_eq!(s.pkg.graphs[0].nodes.len(), before.graphs[0].nodes.len());
|
||||
|
||||
let out = dir.join("tex");
|
||||
let r = run(&mut s, "file.export", json!({"dir": out.to_str().unwrap(), "format": "png", "depth": 8}));
|
||||
|
||||
assert_eq!(r["files"].as_array().unwrap().len(), 1);
|
||||
|
||||
let small = dir.join("small");
|
||||
run(&mut s, "file.export", json!({"dir": small.to_str().unwrap(), "format": "png", "depth": 8, "size": 64}));
|
||||
let file = std::fs::read_dir(&small).unwrap().next().unwrap().unwrap().path();
|
||||
let img = materialcraft_formats::decode(&std::fs::read(file).unwrap(), false).unwrap();
|
||||
|
||||
assert_eq!((img.width(), img.height()), (64, 64));
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
@@ -113,11 +119,13 @@ fn export_size_keeps_proportions_and_clamps() {
|
||||
assert_eq!(parsed(&s, json!(0)).unwrap(), None);
|
||||
assert_eq!(parsed(&s, json!(u64::MAX)).unwrap(), Some(ExportSize::LargerSide(u32::MAX)));
|
||||
assert_eq!(parsed(&s, json!([1, u64::MAX])).unwrap(), Some(ExportSize::Exact([1, u32::MAX])));
|
||||
|
||||
for invalid in [json!("large"), json!([64]), json!([64, "wide"]), json!([64, 64, 64])] {
|
||||
assert!(parsed(&s, invalid.clone()).is_err(), "{invalid}");
|
||||
}
|
||||
|
||||
s.pkg.graphs[0].size = [u32::MAX, u32::MAX];
|
||||
|
||||
assert!(dims(&s, json!(32)).iter().all(|d| *d == (32, 32)));
|
||||
assert!(dims(&s, json!([1, u64::MAX])).iter().all(|d| *d == (16, 8192)), "sides clamp to 16..8192");
|
||||
}
|
||||
@@ -380,13 +388,16 @@ fn reimported_bitmap_shows_new_pixels() {
|
||||
use materialcraft_formats::{Depth, encode};
|
||||
let bmp = |v: f32| encode(&Image::filled(4, 4, Kind::Color, [v, v, v, 1.0]), "bmp", Depth::U8, true).unwrap();
|
||||
let (dark, light) = (bmp(0.1), bmp(0.9));
|
||||
|
||||
assert_eq!(dark.len(), light.len(), "same-size files are the case under test");
|
||||
|
||||
let mut s = sample_session();
|
||||
materialcraft_engine::file_cmds::add_resource(&mut s, "tex.bmp", dark, Some("tex")).unwrap();
|
||||
let before = s.resource_decoder()("tex").unwrap().data()[0];
|
||||
s.undo();
|
||||
materialcraft_engine::file_cmds::add_resource(&mut s, "tex.bmp", light, Some("tex")).unwrap();
|
||||
let after = s.resource_decoder()("tex").unwrap().data()[0];
|
||||
|
||||
assert!(after - before > 0.5, "{before} -> {after}");
|
||||
}
|
||||
|
||||
@@ -422,7 +433,7 @@ fn a_wire_splits_with_a_reroute_dot_and_deletes() {
|
||||
|
||||
#[test]
|
||||
fn every_template_is_opaque_in_the_3d_view() {
|
||||
// The 3D view sees through a base color whose alpha is below one: the templates must not
|
||||
// Template base colors must stay opaque in the 3D view
|
||||
let mut s = sample_session();
|
||||
s.preview_size = Some(64);
|
||||
for (id, _) in materialcraft_engine::samples::TEMPLATES {
|
||||
@@ -431,6 +442,7 @@ fn every_template_is_opaque_in_the_3d_view() {
|
||||
for (usage, img) in s.material_maps() {
|
||||
if usage == "baseColor" && !img.is_gray() {
|
||||
let min = img.data().chunks(4).map(|p| p[3]).fold(f32::INFINITY, f32::min);
|
||||
|
||||
assert!(min >= 0.999, "{id}: base color alpha goes down to {min}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,6 +47,7 @@ pub fn cook(package: &Package, graph_index: usize, options: &Options, cache: &Mu
|
||||
cooked.cancelled = true;
|
||||
break;
|
||||
}
|
||||
|
||||
let Some(node) = prepared.index.node(id) else { continue };
|
||||
|
||||
let result = cook_node(package, graph_index, &prepared, node, &cooked, &variables, options, cache);
|
||||
|
||||
@@ -37,71 +37,76 @@ pub(crate) fn instances_reach(pkg: &Package, from: usize, target: usize) -> bool
|
||||
}
|
||||
|
||||
pub(crate) fn cook_instance(
|
||||
pkg: &Package,
|
||||
gi: usize,
|
||||
package: &Package,
|
||||
graph_index: usize,
|
||||
node: &Node,
|
||||
in_ports: &[Port],
|
||||
out_ports: &[Port],
|
||||
input_ports: &[Port],
|
||||
output_ports: &[Port],
|
||||
inputs: &[Option<&NodeOutput>],
|
||||
params: &BTreeMap<String, Value>,
|
||||
size: (u32, u32),
|
||||
base: crate::resolved_base_parameters::ResolvedBaseParameters,
|
||||
opts: &Options,
|
||||
options: &Options,
|
||||
cache: &Mutex<Cache>,
|
||||
) -> Result<Vec<NodeOutput>, String> {
|
||||
if opts.depth >= MAX_DEPTH {
|
||||
if options.depth >= MAX_DEPTH {
|
||||
return Err("graph instances nest too deep (does a graph use itself?)".into());
|
||||
}
|
||||
let registry = opts.registry.unwrap_or(pkg);
|
||||
let (source, sub_gi, sub) = resolve(registry, pkg, node).ok_or("the instanced graph does not exist")?;
|
||||
let identity = std::ptr::from_ref(sub) as usize;
|
||||
if pkg.graphs.get(gi).is_some_and(|graph| std::ptr::eq(graph, sub)) || opts.graph_stack.contains(&identity) {
|
||||
return Err(format!("graph `{}` uses itself through a graph instance", sub.name));
|
||||
|
||||
let registry = options.registry.unwrap_or(package);
|
||||
let (source, source_graph_index, source_graph) = resolve(registry, package, node).ok_or("the instanced graph does not exist")?;
|
||||
let identity = std::ptr::from_ref(source_graph) as usize;
|
||||
if package.graphs.get(graph_index).is_some_and(|graph| std::ptr::eq(graph, source_graph)) || options.graph_stack.contains(&identity) {
|
||||
return Err(format!("graph `{}` uses itself through a graph instance", source_graph.name));
|
||||
}
|
||||
if sub.function.is_some() || !sub.nodes.iter().any(|node| node.def == "output") {
|
||||
|
||||
if source_graph.function.is_some() || !source_graph.nodes.iter().any(|node| node.def == "output") {
|
||||
return Err("the referenced graph must be a main graph with an output".into());
|
||||
}
|
||||
let root_resource = opts.resource_root.unwrap_or(opts.resource);
|
||||
|
||||
let root_resource = options.resource_root.unwrap_or(options.resource);
|
||||
let resource = |name: &str| match &node.instance {
|
||||
Some(instance) if !instance.package.is_empty() => {
|
||||
let (name, linear) = craft_texture::split_resource_key(name);
|
||||
root_resource(&craft_texture::resource_key(&format!("{}\0{name}", instance.package), linear))
|
||||
}
|
||||
_ => (opts.resource)(name),
|
||||
_ => (options.resource)(name),
|
||||
};
|
||||
let mut o = Options::new(&resource);
|
||||
o.environment = opts.environment;
|
||||
o.parent_tiling = Some(base.tiling);
|
||||
o.parent_pixel_ratio = Some(base.pixel_ratio);
|
||||
o.parent_base = Some(base);
|
||||
o.registry = Some(registry);
|
||||
o.resource_root = Some(root_resource);
|
||||
o.max_size = opts.max_size;
|
||||
o.cancel = opts.cancel;
|
||||
o.depth = opts.depth + 1;
|
||||
o.graph_stack = opts.graph_stack.clone();
|
||||
o.graph_stack.push(identity);
|
||||
o.only = Some(sub.nodes.iter().filter(|node| node.def == "output").map(|node| node.id).collect());
|
||||
o.inputs = in_ports.iter().zip(inputs).filter_map(|(port, input)| Some((port.id.clone(), input.as_ref()?.as_image()?.clone()))).collect();
|
||||
o.overrides = params.iter().filter(|(k, _)| sub.exposed.iter().any(|e| &e.id == *k)).map(|(k, v)| (k.clone(), v.clone())).collect();
|
||||
o.overrides.extend(in_ports.iter().zip(inputs).filter_map(|(port, input)| Some((port.id.clone(), input.as_ref()?.as_value()?.clone()))));
|
||||
let cooked = cook(source, sub_gi, &o, cache);
|
||||
let mut source_options = Options::new(&resource);
|
||||
source_options.environment = options.environment;
|
||||
source_options.parent_tiling = Some(base.tiling);
|
||||
source_options.parent_pixel_ratio = Some(base.pixel_ratio);
|
||||
source_options.parent_base = Some(base);
|
||||
source_options.registry = Some(registry);
|
||||
source_options.resource_root = Some(root_resource);
|
||||
source_options.max_size = options.max_size;
|
||||
source_options.cancel = options.cancel;
|
||||
source_options.depth = options.depth + 1;
|
||||
source_options.graph_stack = options.graph_stack.clone();
|
||||
source_options.graph_stack.push(identity);
|
||||
source_options.only = Some(source_graph.nodes.iter().filter(|node| node.def == "output").map(|node| node.id).collect());
|
||||
source_options.inputs = input_ports.iter().zip(inputs).filter_map(|(port, input)| Some((port.id.clone(), input.as_ref()?.as_image()?.clone()))).collect();
|
||||
source_options.overrides = params.iter().filter(|(k, _)| source_graph.exposed.iter().any(|e| &e.id == *k)).map(|(k, v)| (k.clone(), v.clone())).collect();
|
||||
source_options.overrides.extend(input_ports.iter().zip(inputs).filter_map(|(port, input)| Some((port.id.clone(), input.as_ref()?.as_value()?.clone()))));
|
||||
let cooked = cook(source, source_graph_index, &source_options, cache);
|
||||
if cooked.cancelled {
|
||||
return Err("cancelled".into());
|
||||
}
|
||||
|
||||
if let Some(error) = cooked.nodes.values().find_map(|result| result.error.as_deref()) {
|
||||
return Err(format!("{}: {error}", sub.name));
|
||||
return Err(format!("{}: {error}", source_graph.name));
|
||||
}
|
||||
out_ports
|
||||
|
||||
output_ports
|
||||
.iter()
|
||||
.map(|p| {
|
||||
let output = sub
|
||||
.map(|port| {
|
||||
let output = source_graph
|
||||
.nodes
|
||||
.iter()
|
||||
.find(|n| n.def == "output" && identifier(n) == p.id)
|
||||
.find(|candidate| candidate.def == "output" && identifier(candidate) == port.id)
|
||||
.and_then(|node| cooked.nodes.get(&node.id))
|
||||
.and_then(|result| result.outputs.first())
|
||||
.ok_or_else(|| format!("the source output `{}` is missing", p.id))?;
|
||||
.ok_or_else(|| format!("the source output `{}` is missing", port.id))?;
|
||||
Ok(match output {
|
||||
NodeOutput::Image(image) => NodeOutput::Image(image.resize(size.0, size.1, true)),
|
||||
NodeOutput::Value(value) => NodeOutput::Value(value.clone()),
|
||||
|
||||
@@ -49,10 +49,10 @@ fn with_pixels(image: Image, integer_sampling: bool, convert: impl Fn(&mut f32))
|
||||
limits.max_pixels = u64::MAX;
|
||||
limits.max_bytes = u64::MAX;
|
||||
|
||||
let shared = Arc::clone(image.shared_data());
|
||||
let mut data = Arc::clone(image.shared_data());
|
||||
drop(image);
|
||||
let mut data = Arc::unwrap_or_clone(shared);
|
||||
data.iter_mut().for_each(convert);
|
||||
|
||||
Arc::make_mut(&mut data).iter_mut().for_each(convert);
|
||||
|
||||
// `data` keeps the size and kind of a valid image, so `from_data` accepts it
|
||||
Image::from_data(width, height, kind, data, &limits)
|
||||
|
||||
@@ -121,6 +121,7 @@ fn hostile_param_is_clamped_before_cooking() {
|
||||
p.graphs[0].node_mut(blur).unwrap().params.insert("intensity".into(), Value::Float(1e30));
|
||||
let cache = Mutex::new(Cache::default());
|
||||
let c = cook(&p, 0, &Options::new(&no_res), &cache);
|
||||
|
||||
assert!(c.nodes[&blur].error.is_none(), "{:?}", c.nodes[&blur].error);
|
||||
assert_eq!(c.image(blur, 0).map(|i| (i.width(), i.height())), Some((64, 64)));
|
||||
}
|
||||
@@ -134,6 +135,7 @@ fn preview_cap_and_unknown_nodes() {
|
||||
let mut opts = Options::new(&no_res);
|
||||
opts.max_size = Some(128);
|
||||
let c = cook(&p, 0, &opts, &cache);
|
||||
|
||||
assert_eq!(c.image(out, 0).map(|i| i.width()), Some(128));
|
||||
assert!(c.nodes[&bad].error.is_some());
|
||||
}
|
||||
@@ -379,20 +381,27 @@ fn cached_input_fingerprint_tracks_copy_on_write_and_shape() {
|
||||
let cache = Mutex::new(Cache::default());
|
||||
let image = Image::filled(128, 128, Kind::Gray, [0.0; 4]);
|
||||
let first = image_key(&image, &cache);
|
||||
|
||||
assert_eq!(image_key(&image, &cache), first);
|
||||
|
||||
let mut data = image.data().to_vec();
|
||||
data[1] = 1.0;
|
||||
let image = Image::from_data(128, 128, Kind::Gray, data, &Limits::default()).unwrap();
|
||||
let changed = image_key(&image, &cache);
|
||||
|
||||
assert_ne!(changed, first);
|
||||
// The same buffer read as another shape.
|
||||
|
||||
// The same buffer read as another shape
|
||||
let image = Image::from_data(64, 256, Kind::Gray, Arc::clone(image.shared_data()), &Limits::default()).unwrap();
|
||||
let reshaped = image_key(&image, &cache);
|
||||
|
||||
assert_ne!(reshaped, changed);
|
||||
|
||||
cache.lock().unwrap().clear();
|
||||
|
||||
assert_eq!(image_key(&image, &cache), reshaped);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preview_cap_does_not_compound_downscaling() {
|
||||
let (mut p, noise, blur, out) = sample();
|
||||
@@ -402,10 +411,12 @@ fn preview_cap_does_not_compound_downscaling() {
|
||||
let mut opts = Options::new(&no_res);
|
||||
opts.max_size = Some(512);
|
||||
let c = cook(&p, 0, &opts, &cache);
|
||||
|
||||
assert_eq!(c.image(noise, 0).map(|i| (i.width(), i.height())), Some((512, 512)));
|
||||
assert_eq!(c.image(blur, 0).map(|i| (i.width(), i.height())), Some((128, 128)));
|
||||
assert_eq!(c.image(out, 0).map(|i| (i.width(), i.height())), Some((128, 128)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preview_cap_uses_nominal_dimensions_through_bypassed_nodes() {
|
||||
let (mut p, noise, blur, out) = sample();
|
||||
@@ -416,10 +427,12 @@ fn preview_cap_uses_nominal_dimensions_through_bypassed_nodes() {
|
||||
let mut opts = Options::new(&no_res);
|
||||
opts.max_size = Some(128);
|
||||
let c = cook(&p, 0, &opts, &cache);
|
||||
|
||||
assert_eq!(c.image(noise, 0).map(|i| (i.width(), i.height())), Some((128, 64)));
|
||||
assert_eq!(c.image(blur, 0).map(|i| (i.width(), i.height())), Some((128, 64)));
|
||||
assert_eq!(c.image(out, 0).map(|i| (i.width(), i.height())), Some((128, 64)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changed_unsampled_input_recooks() {
|
||||
let mut g = Graph::new("g");
|
||||
@@ -432,15 +445,19 @@ fn changed_unsampled_input_recooks() {
|
||||
opts.inputs.insert("input".into(), image.clone());
|
||||
let cache = Mutex::new(Cache::default());
|
||||
let first = cook(&p, 0, &opts, &cache);
|
||||
|
||||
assert!(!first.nodes[&input].cached);
|
||||
|
||||
let mut data = image.data().to_vec();
|
||||
data[1] = 1.0;
|
||||
let changed = Image::from_data(128, 128, Kind::Gray, data, &Limits::default()).unwrap();
|
||||
opts.inputs.insert("input".into(), changed);
|
||||
let second = cook(&p, 0, &opts, &cache);
|
||||
|
||||
assert!(!second.nodes[&input].cached);
|
||||
assert_eq!(second.image(input, 0).unwrap().data()[1], 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linear_input_images_and_bitmap_nodes_request_data_reads() {
|
||||
// The decoder returns 0.5 for a linear request and 0.2 for an sRGB one
|
||||
@@ -531,16 +548,25 @@ fn bound_input_image_linear_flag_change_recooks_instance() {
|
||||
let cache = Mutex::new(Cache::default());
|
||||
let opts = Options::new(&res);
|
||||
let first = cook(&p, 0, &opts, &cache);
|
||||
|
||||
assert!(first.nodes[&inst].error.is_none(), "{:?}", first.nodes[&inst].error);
|
||||
assert!(!first.nodes[&inst].cached);
|
||||
|
||||
let first_value = first.image(inst, 0).unwrap().data()[0];
|
||||
|
||||
assert!((first_value - 0.2).abs() < 1e-4, "sRGB bound image should reach the instance, got {first_value}");
|
||||
|
||||
let second = cook(&p, 0, &opts, &cache);
|
||||
|
||||
assert!(second.nodes[&inst].cached, "an unchanged instance should be served from the cache");
|
||||
|
||||
p.graphs[1].input_images_linear.insert("in".into());
|
||||
let third = cook(&p, 0, &opts, &cache);
|
||||
|
||||
assert!(!third.nodes[&inst].cached, "toggling input_images_linear must recook the instance");
|
||||
|
||||
let third_value = third.image(inst, 0).unwrap().data()[0];
|
||||
|
||||
assert!((third_value - 0.5).abs() < 1e-4, "linear bound image should reach the instance, got {third_value}");
|
||||
}
|
||||
|
||||
|
||||
+42
-39
@@ -8,7 +8,10 @@ pub fn decode(bytes: &[u8], linear: bool) -> Result<Image> {
|
||||
return guard(|| crate::dds_image::decode(bytes, linear), || FormatError::Image("DDS decoder failed".into()));
|
||||
}
|
||||
|
||||
if std::str::from_utf8(bytes.get(..bytes.len().min(4096)).unwrap_or_default()).is_ok_and(|text| text.contains("<svg")) {
|
||||
const SVG_SNIFF_BYTES: usize = 4096;
|
||||
const MAX_DECODE_BYTES: u64 = 1 << 30;
|
||||
|
||||
if std::str::from_utf8(bytes.get(..bytes.len().min(SVG_SNIFF_BYTES)).unwrap_or_default()).is_ok_and(|text| text.contains("<svg")) {
|
||||
return guard(|| crate::svg::decode(bytes), || FormatError::Image("SVG decoder failed".into()));
|
||||
}
|
||||
|
||||
@@ -20,7 +23,7 @@ pub fn decode(bytes: &[u8], linear: bool) -> Result<Image> {
|
||||
let mut limits = image::Limits::default();
|
||||
limits.max_image_width = Some(MAX_SIDE);
|
||||
limits.max_image_height = Some(MAX_SIDE);
|
||||
limits.max_alloc = Some(1 << 30);
|
||||
limits.max_alloc = Some(MAX_DECODE_BYTES);
|
||||
reader.limits(limits);
|
||||
Ok(reader)
|
||||
};
|
||||
@@ -35,16 +38,16 @@ pub fn decode(bytes: &[u8], linear: bool) -> Result<Image> {
|
||||
return Err(FormatError::Image(format!("{w}x{h} is outside 1..={MAX_SIDE} pixels")));
|
||||
}
|
||||
|
||||
let img = guard(|| open()?.decode().map_err(image_error), failed)?;
|
||||
let gray = matches!(img.color(), image::ColorType::L8 | image::ColorType::L16 | image::ColorType::La8 | image::ColorType::La16);
|
||||
let float = matches!(img.color(), image::ColorType::Rgb32F | image::ColorType::Rgba32F);
|
||||
let decoded = guard(|| open()?.decode().map_err(image_error), failed)?;
|
||||
let gray = matches!(decoded.color(), image::ColorType::L8 | image::ColorType::L16 | image::ColorType::La8 | image::ColorType::La16);
|
||||
let float = matches!(decoded.color(), image::ColorType::Rgb32F | image::ColorType::Rgba32F);
|
||||
if gray {
|
||||
let l = img.into_luma16();
|
||||
let data: Vec<f32> = l.pixels().map(|p| p.0[0] as f32 / 65535.0).collect();
|
||||
let luminance = decoded.into_luma16();
|
||||
let data: Vec<f32> = luminance.pixels().map(|p| p.0[0] as f32 / 65535.0).collect();
|
||||
return Image::from_data(w, h, Kind::Gray, data, &Limits::default()).map_err(|e| FormatError::Image(e.to_string()));
|
||||
}
|
||||
|
||||
let mut data = img.into_rgba32f().into_raw();
|
||||
let mut data = decoded.into_rgba32f().into_raw();
|
||||
if !(float || linear) {
|
||||
for px in data.as_chunks_mut::<4>().0 {
|
||||
for c in px.iter_mut().take(3) {
|
||||
@@ -56,24 +59,24 @@ pub fn decode(bytes: &[u8], linear: bool) -> Result<Image> {
|
||||
Image::from_data(w, h, Kind::Color, data, &Limits::default()).map_err(|e| FormatError::Image(e.to_string()))
|
||||
}
|
||||
|
||||
/// Encode `img` as `ext` (see [`EXPORT_FORMATS`]). `srgb`: color values are written through the sRGB curve (base color); data maps (normal, roughness…) are written linear
|
||||
pub fn encode(img: &Image, ext: &str, depth: Depth, srgb: bool) -> Result<Vec<u8>> {
|
||||
/// Encode `image` as `ext` (see [`EXPORT_FORMATS`]). `srgb`: color values are written through the sRGB curve (base color); data maps (normal, roughness…) are written linear
|
||||
pub fn encode(image: &Image, ext: &str, depth: Depth, srgb: bool) -> Result<Vec<u8>> {
|
||||
let ext = ext.trim_start_matches('.').to_ascii_lowercase();
|
||||
let enc = |v: f32| if srgb && img.kind() == Kind::Color { linear_to_srgb(v) } else { v };
|
||||
let (w, h) = (img.width(), img.height());
|
||||
let color = img.kind() == Kind::Color;
|
||||
let px = |i: usize| -> [f32; 4] {
|
||||
let encode_channel = |v: f32| if srgb && image.kind() == Kind::Color { linear_to_srgb(v) } else { v };
|
||||
let (w, h) = (image.width(), image.height());
|
||||
let color = image.kind() == Kind::Color;
|
||||
let pixel = |i: usize| -> [f32; 4] {
|
||||
if color {
|
||||
let s = img.data().get(i * 4..i * 4 + 4).unwrap_or(&[0.0, 0.0, 0.0, 1.0]);
|
||||
[enc(s[0]), enc(s[1]), enc(s[2]), s[3]]
|
||||
let s = image.data().get(i * 4..i * 4 + 4).unwrap_or(&[0.0, 0.0, 0.0, 1.0]);
|
||||
[encode_channel(s[0]), encode_channel(s[1]), encode_channel(s[2]), s[3]]
|
||||
} else {
|
||||
let v = img.data().get(i).copied().unwrap_or(0.0);
|
||||
let v = image.data().get(i).copied().unwrap_or(0.0);
|
||||
[v, v, v, 1.0]
|
||||
}
|
||||
};
|
||||
|
||||
let n = (w * h) as usize;
|
||||
let fmt = match ext.as_str() {
|
||||
let pixel_count = (w * h) as usize;
|
||||
let format = match ext.as_str() {
|
||||
"png" => image::ImageFormat::Png,
|
||||
"jpg" | "jpeg" => image::ImageFormat::Jpeg,
|
||||
"tga" => image::ImageFormat::Tga,
|
||||
@@ -84,44 +87,44 @@ pub fn encode(img: &Image, ext: &str, depth: Depth, srgb: bool) -> Result<Vec<u8
|
||||
other => return Err(FormatError::Image(format!("unsupported export format `{other}`"))),
|
||||
};
|
||||
|
||||
let float_only = matches!(fmt, image::ImageFormat::OpenExr | image::ImageFormat::Hdr);
|
||||
let sixteen_ok = fmt == image::ImageFormat::Png;
|
||||
let q8 = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
|
||||
let q16 = |v: f32| (v.clamp(0.0, 1.0) * 65535.0 + 0.5) as u16;
|
||||
let dynimg: image::DynamicImage = if float_only {
|
||||
let data: Vec<f32> = (0..n)
|
||||
let float_only = matches!(format, image::ImageFormat::OpenExr | image::ImageFormat::Hdr);
|
||||
let sixteen_ok = format == image::ImageFormat::Png;
|
||||
let quantize_u8 = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
|
||||
let quantize_u16 = |v: f32| (v.clamp(0.0, 1.0) * 65535.0 + 0.5) as u16;
|
||||
let dynamic_image: image::DynamicImage = if float_only {
|
||||
let data: Vec<f32> = (0..pixel_count)
|
||||
.flat_map(|i| {
|
||||
let p = px(i);
|
||||
let p = pixel(i);
|
||||
[p[0], p[1], p[2]]
|
||||
})
|
||||
.collect();
|
||||
let buf = image::Rgb32FImage::from_raw(w, h, data).ok_or_else(|| FormatError::Image("bad buffer".into()))?;
|
||||
buf.into()
|
||||
let buffer = image::Rgb32FImage::from_raw(w, h, data).ok_or_else(|| FormatError::Image("bad buffer".into()))?;
|
||||
buffer.into()
|
||||
} else if depth != Depth::U8 && sixteen_ok {
|
||||
if color {
|
||||
let data: Vec<u16> = (0..n).flat_map(|i| px(i).map(q16)).collect();
|
||||
let data: Vec<u16> = (0..pixel_count).flat_map(|i| pixel(i).map(quantize_u16)).collect();
|
||||
image::ImageBuffer::<image::Rgba<u16>, _>::from_raw(w, h, data).ok_or_else(|| FormatError::Image("bad buffer".into()))?.into()
|
||||
} else {
|
||||
let data: Vec<u16> = (0..n).map(|i| q16(px(i)[0])).collect();
|
||||
let data: Vec<u16> = (0..pixel_count).map(|i| quantize_u16(pixel(i)[0])).collect();
|
||||
image::ImageBuffer::<image::Luma<u16>, _>::from_raw(w, h, data).ok_or_else(|| FormatError::Image("bad buffer".into()))?.into()
|
||||
}
|
||||
} else if color && !matches!(fmt, image::ImageFormat::Jpeg) {
|
||||
let data: Vec<u8> = (0..n).flat_map(|i| px(i).map(q8)).collect();
|
||||
} else if color && !matches!(format, image::ImageFormat::Jpeg) {
|
||||
let data: Vec<u8> = (0..pixel_count).flat_map(|i| pixel(i).map(quantize_u8)).collect();
|
||||
image::RgbaImage::from_raw(w, h, data).ok_or_else(|| FormatError::Image("bad buffer".into()))?.into()
|
||||
} else if color {
|
||||
let data: Vec<u8> = (0..n)
|
||||
let data: Vec<u8> = (0..pixel_count)
|
||||
.flat_map(|i| {
|
||||
let p = px(i);
|
||||
[q8(p[0]), q8(p[1]), q8(p[2])]
|
||||
let p = pixel(i);
|
||||
[quantize_u8(p[0]), quantize_u8(p[1]), quantize_u8(p[2])]
|
||||
})
|
||||
.collect();
|
||||
image::RgbImage::from_raw(w, h, data).ok_or_else(|| FormatError::Image("bad buffer".into()))?.into()
|
||||
} else {
|
||||
let data: Vec<u8> = (0..n).map(|i| q8(px(i)[0])).collect();
|
||||
let data: Vec<u8> = (0..pixel_count).map(|i| quantize_u8(pixel(i)[0])).collect();
|
||||
image::GrayImage::from_raw(w, h, data).ok_or_else(|| FormatError::Image("bad buffer".into()))?.into()
|
||||
};
|
||||
|
||||
let mut out = Cursor::new(Vec::new());
|
||||
dynimg.write_to(&mut out, fmt).map_err(|e| FormatError::Image(e.to_string()))?;
|
||||
Ok(out.into_inner())
|
||||
let mut output = Cursor::new(Vec::new());
|
||||
dynamic_image.write_to(&mut output, format).map_err(|e| FormatError::Image(e.to_string()))?;
|
||||
Ok(output.into_inner())
|
||||
}
|
||||
@@ -79,6 +79,7 @@ mod tests {
|
||||
#[test]
|
||||
fn draws_a_shape_in_linear_light() {
|
||||
let image = decode(&svg(r##"<rect width="2" height="2" fill="#ff0000"/>"##)).unwrap();
|
||||
|
||||
let left = image.get(0, 0, false);
|
||||
|
||||
assert_eq!((image.width(), image.height()), (4, 2));
|
||||
|
||||
@@ -11,11 +11,13 @@ fn export_every_format() {
|
||||
for i in [&img, &gray] {
|
||||
let b = encode(i, ext, depth, true).unwrap_or_else(|e| panic!("{ext}: {e}"));
|
||||
let back = decode(&b, false).unwrap_or_else(|e| panic!("{ext} decode: {e}"));
|
||||
|
||||
assert_eq!((back.width(), back.height()), (8, 8));
|
||||
}
|
||||
}
|
||||
}
|
||||
let png16 = encode(&gray, "png", Depth::U16, false).unwrap();
|
||||
|
||||
assert!((decode(&png16, false).unwrap().get(7, 0, false)[0] - gray.get(7, 0, false)[0]).abs() < 1e-3);
|
||||
}
|
||||
|
||||
@@ -39,6 +41,7 @@ fn tga_still_decodes() {
|
||||
let mut tga = Cursor::new(Vec::new());
|
||||
::image::RgbaImage::new(2, 2).write_to(&mut tga, ::image::ImageFormat::Tga).unwrap();
|
||||
let img = decode(tga.get_ref(), false).unwrap();
|
||||
|
||||
assert_eq!((img.width(), img.height(), img.kind()), (2, 2, Kind::Color));
|
||||
}
|
||||
|
||||
|
||||
@@ -21,19 +21,19 @@ pub(super) fn definition() -> NodeDefinition {
|
||||
}
|
||||
|
||||
fn blend(context: &CookContext) -> CookResult {
|
||||
let (fg, bg) = (context.sized(0), context.sized(1));
|
||||
let kind = if [&fg, &bg].iter().any(|i| i.as_ref().is_some_and(|i| !i.is_gray())) { Kind::Color } else { Kind::Gray };
|
||||
let fg = fg.unwrap_or_else(|| Image::filled(context.w, context.h, kind, [0.0, 0.0, 0.0, 0.0]));
|
||||
let bg = bg.unwrap_or_else(|| Image::filled(context.w, context.h, kind, [0.0, 0.0, 0.0, 1.0]));
|
||||
let (foreground, background) = (context.sized(0), context.sized(1));
|
||||
let kind = if [&foreground, &background].iter().any(|i| i.as_ref().is_some_and(|i| !i.is_gray())) { Kind::Color } else { Kind::Gray };
|
||||
let foreground = foreground.unwrap_or_else(|| Image::filled(context.w, context.h, kind, [0.0, 0.0, 0.0, 0.0]));
|
||||
let background = background.unwrap_or_else(|| Image::filled(context.w, context.h, kind, [0.0, 0.0, 0.0, 1.0]));
|
||||
let mask = context.sized(2).map(|m| m.to_gray());
|
||||
let (mode, op) = (context.i("mode"), context.f("opacity"));
|
||||
let (mode, opacity) = (context.i("mode"), context.f("opacity"));
|
||||
let color_blending = context.i("color_blending");
|
||||
let blend_alpha = context.b("alpha") && !fg.is_gray();
|
||||
let blend_alpha = context.b("alpha") && !foreground.is_gray();
|
||||
let clamp =
|
||||
matches!(context.format, materialcraft_core::OutputFormat::U8 | materialcraft_core::OutputFormat::U16 | materialcraft_core::OutputFormat::Inherit);
|
||||
Ok(vec![Image::generate(context.w, context.h, kind, |x, y| {
|
||||
let (x, y) = (x as i64, y as i64);
|
||||
let m = mask.as_ref().map_or(1.0, |m| m.get_gray(x, y, false));
|
||||
ops::blend_px(mode, bg.get(x, y, false), fg.get(x, y, false), op * m, color_blending, blend_alpha, clamp)
|
||||
ops::blend_px(mode, background.get(x, y, false), foreground.get(x, y, false), opacity * m, color_blending, blend_alpha, clamp)
|
||||
})])
|
||||
}
|
||||
@@ -13,40 +13,45 @@ pub(super) fn axis(input: &Image, radius: f32, horizontal: bool, tile: bool) ->
|
||||
let edge_weight = (0.5 - (extent as f64 - 0.5) * weight).max(0.0);
|
||||
let (length, lines) = if horizontal { (input.width(), input.height()) } else { (input.height(), input.width()) };
|
||||
let channels = input.channels();
|
||||
let results: Vec<Vec<f32>> = (0..lines)
|
||||
.into_par_iter()
|
||||
.map(|line| {
|
||||
let get = |position: i64| {
|
||||
if horizontal { input.get(position, i64::from(line), tile) } else { input.get(i64::from(line), position, tile) }
|
||||
};
|
||||
let mut output = vec![0.0; length as usize * channels];
|
||||
for channel in 0..channels {
|
||||
// Count NaN, positive infinity and negative infinity separately
|
||||
let mut sum = 0.0_f64;
|
||||
let mut non_finite = [0_i64; 3];
|
||||
for position in (1 - extent)..extent {
|
||||
accumulate(&mut sum, &mut non_finite, get(position)[channel], 1);
|
||||
}
|
||||
|
||||
for (position, pixel) in output.chunks_exact_mut(channels).enumerate() {
|
||||
let position = position as i64;
|
||||
let mut value = window_total(sum, non_finite) * weight;
|
||||
if edge_weight > 0.0 {
|
||||
value += (f64::from(get(position - extent)[channel]) + f64::from(get(position + extent)[channel])) * edge_weight;
|
||||
}
|
||||
pixel[channel] = value as f32;
|
||||
accumulate(&mut sum, &mut non_finite, get(position + extent)[channel], 1);
|
||||
accumulate(&mut sum, &mut non_finite, get(position - extent + 1)[channel], -1);
|
||||
}
|
||||
let fill_line = |line: u32, output: &mut [f32]| {
|
||||
let get = |position: i64| {
|
||||
if horizontal { input.get(position, i64::from(line), tile) } else { input.get(i64::from(line), position, tile) }
|
||||
};
|
||||
for channel in 0..channels {
|
||||
// Count NaN, positive infinity and negative infinity separately
|
||||
let mut sum = 0.0_f64;
|
||||
let mut non_finite = [0_i64; 3];
|
||||
for position in (1 - extent)..extent {
|
||||
accumulate(&mut sum, &mut non_finite, get(position)[channel], 1);
|
||||
}
|
||||
|
||||
output
|
||||
})
|
||||
.collect();
|
||||
for (position, pixel) in output.chunks_exact_mut(channels).enumerate() {
|
||||
let position = position as i64;
|
||||
let mut value = window_total(sum, non_finite) * weight;
|
||||
if edge_weight > 0.0 {
|
||||
value += (f64::from(get(position - extent)[channel]) + f64::from(get(position + extent)[channel])) * edge_weight;
|
||||
}
|
||||
|
||||
pixel[channel] = value as f32;
|
||||
accumulate(&mut sum, &mut non_finite, get(position + extent)[channel], 1);
|
||||
accumulate(&mut sum, &mut non_finite, get(position - extent + 1)[channel], -1);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let data = if horizontal {
|
||||
results.into_iter().flatten().collect()
|
||||
let mut data = vec![0.0; input.width() as usize * input.height() as usize * channels];
|
||||
data.par_chunks_mut(length as usize * channels).enumerate().for_each(|(line, output)| fill_line(line as u32, output));
|
||||
data
|
||||
} else {
|
||||
let results: Vec<Vec<f32>> = (0..lines)
|
||||
.into_par_iter()
|
||||
.map(|line| {
|
||||
let mut output = vec![0.0; length as usize * channels];
|
||||
fill_line(line, &mut output);
|
||||
output
|
||||
})
|
||||
.collect();
|
||||
let mut data = Vec::with_capacity(input.width() as usize * input.height() as usize * channels);
|
||||
for y in 0..input.height() as usize {
|
||||
for line in &results {
|
||||
|
||||
@@ -7,16 +7,18 @@ pub(super) fn definition() -> NodeDefinition {
|
||||
}
|
||||
|
||||
fn curve(context: &CookContext) -> CookResult {
|
||||
let img = context.any_or(0, Kind::Gray, [0.0; 4]);
|
||||
let c = context.curve("curve");
|
||||
// A 1024-entry table: the curve is smooth, so linear lookups are exact enough
|
||||
let lut: Vec<f32> = (0..=1024).map(|i| c.eval(i as f32 / 1024.0)).collect();
|
||||
let f = |v: f32| {
|
||||
let t = v.clamp(0.0, 1.0) * 1024.0;
|
||||
let i = t as usize;
|
||||
let a = lut.get(i).copied().unwrap_or(0.0);
|
||||
let b = lut.get(i + 1).copied().unwrap_or(a);
|
||||
a + (b - a) * (t - i as f32)
|
||||
let image = context.any_or(0, Kind::Gray, [0.0; 4]);
|
||||
let curve = context.curve("curve");
|
||||
|
||||
// Linear interpolation over 1024 intervals approximates the smooth curve
|
||||
const TABLE_INTERVALS: usize = 1024;
|
||||
let table: Vec<f32> = (0..=TABLE_INTERVALS).map(|i| curve.eval(i as f32 / TABLE_INTERVALS as f32)).collect();
|
||||
let lookup = |value: f32| {
|
||||
let position = value.clamp(0.0, 1.0) * TABLE_INTERVALS as f32;
|
||||
let i = position as usize;
|
||||
let a = table.get(i).copied().unwrap_or(0.0);
|
||||
let b = table.get(i + 1).copied().unwrap_or(a);
|
||||
a + (b - a) * (position - i as f32)
|
||||
};
|
||||
Ok(vec![img.map(img.kind(), |p| [f(p[0]), f(p[1]), f(p[2]), p[3]])])
|
||||
Ok(vec![image.map(image.kind(), |p| [lookup(p[0]), lookup(p[1]), lookup(p[2]), p[3]])])
|
||||
}
|
||||
@@ -15,12 +15,13 @@ pub(super) fn definition() -> NodeDefinition {
|
||||
}
|
||||
|
||||
fn directional_warp(context: &CookContext) -> CookResult {
|
||||
let img = context.any_or(0, Kind::Gray, [0.0; 4]);
|
||||
let image = context.any_or(0, Kind::Gray, [0.0; 4]);
|
||||
let map = context.gray_or(1, 0.0);
|
||||
let (dx, dy) = direction(context.f("angle"));
|
||||
let k = context.f("intensity") / 256.0;
|
||||
Ok(vec![Image::generate_uv(context.w, context.h, img.kind(), |u, v| {
|
||||
let m = map.sample_gray(u, v, context.tile) * k;
|
||||
img.sample(u + dx * m, v + dy * m, context.tile)
|
||||
const BASE_RESOLUTION: f32 = 256.0;
|
||||
let intensity_scale = context.f("intensity") / BASE_RESOLUTION;
|
||||
Ok(vec![Image::generate_uv(context.w, context.h, image.kind(), |u, v| {
|
||||
let offset = map.sample_gray(u, v, context.tile) * intensity_scale;
|
||||
image.sample(u + dx * offset, v + dy * offset, context.tile)
|
||||
})])
|
||||
}
|
||||
@@ -17,31 +17,38 @@ pub(super) fn definition() -> NodeDefinition {
|
||||
|
||||
fn distance(context: &CookContext) -> CookResult {
|
||||
let mask = context.gray_or(0, 0.0);
|
||||
let maxd = (context.f("distance").max(0.0) * context.w as f32 / 256.0).max(1e-3);
|
||||
const BASE_RESOLUTION: f32 = 256.0;
|
||||
const MIN_DISTANCE_PIXELS: f32 = 1e-3;
|
||||
let maximum_distance = (context.f("distance").max(0.0) * context.w as f32 / BASE_RESOLUTION).max(MIN_DISTANCE_PIXELS);
|
||||
let data = mask.shared_data().clone();
|
||||
let inside = |i| data.get(i).copied().unwrap_or(0.0) > 0.5;
|
||||
let Some(src) = context.sized(1) else {
|
||||
let d2 = ops::distance_sq(context.w, context.h, inside, context.tile);
|
||||
return Ok(vec![ops::gray_from(context.w, context.h, d2.iter().map(|d| (1.0 - d.sqrt() / maxd).clamp(0.0, 1.0)).collect())?]);
|
||||
let Some(source) = context.sized(1) else {
|
||||
let squared_distances = ops::distance_sq(context.w, context.h, inside, context.tile);
|
||||
return Ok(vec![ops::gray_from(
|
||||
context.w,
|
||||
context.h,
|
||||
squared_distances.iter().map(|d| (1.0 - d.sqrt() / maximum_distance).clamp(0.0, 1.0)).collect(),
|
||||
)?]);
|
||||
};
|
||||
|
||||
// Propagate the exact nearest site without gaps from gradient-walk stalls
|
||||
let (d2, sites) = ops::distance_sq_with_sites(context.w, context.h, inside, context.tile);
|
||||
let (squared_distances, sites) = ops::distance_sq_with_sites(context.w, context.h, inside, context.tile);
|
||||
let combine = context.b("combine");
|
||||
Ok(vec![Image::generate(context.w, context.h, src.kind(), |x, y| {
|
||||
Ok(vec![Image::generate(context.w, context.h, source.kind(), |x, y| {
|
||||
let i = y as usize * context.w as usize + x as usize;
|
||||
let site = sites.get(i).copied().unwrap_or(usize::MAX);
|
||||
let mut c = if site == usize::MAX {
|
||||
[0.0, 0.0, 0.0, if src.is_gray() { 1.0 } else { 0.0 }]
|
||||
let mut pixel = if site == usize::MAX {
|
||||
[0.0, 0.0, 0.0, if source.is_gray() { 1.0 } else { 0.0 }]
|
||||
} else {
|
||||
src.get((site % context.w as usize) as i64, (site / context.w as usize) as i64, false)
|
||||
source.get((site % context.w as usize) as i64, (site / context.w as usize) as i64, false)
|
||||
};
|
||||
let d = d2.get(i).copied().unwrap_or(f32::INFINITY).sqrt();
|
||||
if d > maxd {
|
||||
c = [0.0, 0.0, 0.0, if src.is_gray() { 1.0 } else { 0.0 }];
|
||||
let d = squared_distances.get(i).copied().unwrap_or(f32::INFINITY).sqrt();
|
||||
if d > maximum_distance {
|
||||
pixel = [0.0, 0.0, 0.0, if source.is_gray() { 1.0 } else { 0.0 }];
|
||||
} else if combine {
|
||||
let f = (1.0 - d / maxd).clamp(0.0, 1.0);
|
||||
c = [c[0] * f, c[1] * f, c[2] * f, c[3]];
|
||||
let falloff = (1.0 - d / maximum_distance).clamp(0.0, 1.0);
|
||||
pixel = [pixel[0] * falloff, pixel[1] * falloff, pixel[2] * falloff, pixel[3]];
|
||||
}
|
||||
c
|
||||
pixel
|
||||
})])
|
||||
}
|
||||
@@ -24,7 +24,7 @@ fn normal(context: &CookContext) -> CookResult {
|
||||
|
||||
pub fn height_to_normal(height_map: &Image, intensity: f32, directx: bool, tile: bool, alpha_height: bool) -> Image {
|
||||
Image::generate(height_map.width(), height_map.height(), Kind::Color, |x, y| {
|
||||
// Backward differences place alpha wrapped discontinuity on its owning pixel
|
||||
// Backward differences place a wrapped discontinuity on its owning pixel
|
||||
let height = height_map.get_gray(x as i64, y as i64, tile);
|
||||
let dx = height - height_map.get_gray(x as i64 - 1, y as i64, tile);
|
||||
let dy = height - height_map.get_gray(x as i64, y as i64 - 1, tile);
|
||||
|
||||
@@ -21,8 +21,9 @@ fn transformation(context: &CookContext) -> CookResult {
|
||||
let input = context.input(0).cloned().unwrap_or_else(|| Image::filled(context.w, context.h, Kind::Gray, [0.0; 4]));
|
||||
let offset = context.v2("offset");
|
||||
let matrix = context.v4("matrix");
|
||||
const MIN_DETERMINANT: f32 = 1e-8;
|
||||
let determinant = matrix[0] * matrix[3] - matrix[1] * matrix[2];
|
||||
if !determinant.is_finite() || determinant.abs() < 1e-8 {
|
||||
if !determinant.is_finite() || determinant.abs() < MIN_DETERMINANT {
|
||||
return Err("transform matrix is singular".into());
|
||||
}
|
||||
|
||||
@@ -78,7 +79,8 @@ fn nearest_mip(mut input: Image, matrix: [f32; 4], context: &CookContext) -> Ima
|
||||
let sum: u32 = pixels.iter().map(|pixel| (pixel[channel].clamp(0.0, 1.0) * maximum).round() as u32).sum();
|
||||
((sum + 2) / 4) as f32 / maximum
|
||||
} else {
|
||||
pixels.iter().map(|pixel| pixel[channel]).sum::<f32>() * 0.25
|
||||
// Average in f64 so finite HDR texels cannot overflow the sum
|
||||
(pixels.iter().map(|pixel| f64::from(pixel[channel])).sum::<f64>() * 0.25) as f32
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
@@ -15,12 +15,12 @@ pub(super) fn definition() -> NodeDefinition {
|
||||
}
|
||||
|
||||
fn warp(context: &CookContext) -> CookResult {
|
||||
let img = context.any_or(0, Kind::Gray, [0.0; 4]);
|
||||
let grad = context.gray_or(1, 0.0);
|
||||
let k = context.f("intensity");
|
||||
Ok(vec![Image::generate_uv(context.w, context.h, img.kind(), |u, v| {
|
||||
let image = context.any_or(0, Kind::Gray, [0.0; 4]);
|
||||
let gradient = context.gray_or(1, 0.0);
|
||||
let intensity = context.f("intensity");
|
||||
Ok(vec![Image::generate_uv(context.w, context.h, image.kind(), |u, v| {
|
||||
let (x, y) = ((u * context.w as f32) as i64, (v * context.h as f32) as i64);
|
||||
let (dx, dy) = ops::slope(&grad, x, y, context.tile);
|
||||
img.sample(u + dx * k, v + dy * k, context.tile)
|
||||
let (dx, dy) = ops::slope(&gradient, x, y, context.tile);
|
||||
image.sample(u + dx * intensity, v + dy * intensity, context.tile)
|
||||
})])
|
||||
}
|
||||
@@ -37,7 +37,9 @@ fn every_native_function_executes_with_its_declared_ports() {
|
||||
let mut covered = BTreeSet::new();
|
||||
for definition in FUNCTIONS {
|
||||
let name = definition.id;
|
||||
|
||||
assert!(covered.insert(name), "duplicate {name}");
|
||||
|
||||
let mut graph = FunctionGraph::default();
|
||||
let mut variables = BTreeMap::new();
|
||||
let mut setting = default_value(name);
|
||||
@@ -131,11 +133,13 @@ fn branches_are_lazy_and_sequence_orders_side_effects() {
|
||||
let expected = graph.add_constant(Value::Int(17));
|
||||
let undefined = graph.add("get_integer1", &[], Some(Value::Text("missing".into())));
|
||||
graph.output = Some(graph.add("ifelse", &[condition, expected, undefined], None));
|
||||
|
||||
assert_eq!(evaluate(&graph, &BTreeMap::new()).unwrap(), Value::Int(17));
|
||||
|
||||
let set = graph.add("set", &[expected], Some(Value::Text("stored".into())));
|
||||
let get = graph.add("get_integer1", &[], Some(Value::Text("stored".into())));
|
||||
graph.output = Some(graph.add("sequence", &[set, get], None));
|
||||
|
||||
assert_eq!(evaluate(&graph, &BTreeMap::new()).unwrap(), Value::Int(17));
|
||||
}
|
||||
|
||||
@@ -153,18 +157,22 @@ fn time_and_tiling_variables_have_typed_defaults_and_host_overrides() {
|
||||
let expected = variables.get(name).unwrap_or(&default);
|
||||
let context = EvaluationContext { scope: Default::default(), position: [0.5; 2], size: [1.0; 2], images: &[], tile: true, variables: &variables };
|
||||
let program = compile(&graph, 0).unwrap();
|
||||
|
||||
assert_eq!(program.evaluate(&context, &mut EvaluationState::default()).unwrap(), *expected);
|
||||
assert_eq!(program.evaluate_pixel(&context, &mut EvaluationState::default()).unwrap(), *expected);
|
||||
}
|
||||
|
||||
assert!(evaluate(&graph, &BTreeMap::from([(name.into(), Value::Bool(false))])).unwrap_err().contains("wrong type"));
|
||||
|
||||
graph.output = Some(defined);
|
||||
|
||||
assert_eq!(evaluate(&graph, &BTreeMap::new()).unwrap(), Value::Bool(true));
|
||||
}
|
||||
|
||||
let mut graph = FunctionGraph::default();
|
||||
graph.output = Some(graph.add("get_integer1", &[], Some(Value::Text("$tiling".into()))));
|
||||
let context = EvaluationContext { scope: Default::default(), position: [0.5; 2], size: [1.0; 2], images: &[], tile: false, variables: &BTreeMap::new() };
|
||||
|
||||
assert_eq!(compile(&graph, 0).unwrap().evaluate(&context, &mut EvaluationState::default()).unwrap(), Value::Int(0));
|
||||
}
|
||||
|
||||
@@ -180,10 +188,12 @@ fn loops_recompute_state_and_have_a_budget() {
|
||||
let add = graph.add("add", &[get, one], None);
|
||||
let body = graph.add("set", &[add], Some(Value::Text("counter".into())));
|
||||
graph.output = Some(graph.add("while", &[init, condition, body], Some(Value::Int(-1))));
|
||||
|
||||
assert_eq!(evaluate(&graph, &BTreeMap::new()).unwrap(), Value::Int(3));
|
||||
|
||||
let condition = graph.add_constant(Value::Bool(false));
|
||||
graph.output = Some(graph.add("while", &[zero, condition, one], Some(Value::Int(-1))));
|
||||
|
||||
assert!(evaluate(&graph, &BTreeMap::new()).unwrap_err().contains("budget"));
|
||||
}
|
||||
|
||||
@@ -195,9 +205,12 @@ fn deep_graphs_shared_inputs_and_cycles_do_not_recurse() {
|
||||
previous = graph.add("passthrough", &[previous], None);
|
||||
}
|
||||
graph.output = Some(graph.add("abs", &[previous], None));
|
||||
|
||||
assert_eq!(evaluate(&graph, &BTreeMap::new()).unwrap(), Value::Float(1.0));
|
||||
|
||||
graph.nodes[0].op = "passthrough".into();
|
||||
graph.nodes[0].inputs = vec![Some(previous)];
|
||||
|
||||
assert!(compile(&graph, 0).err().unwrap().contains("cycle"));
|
||||
|
||||
let mut graph = FunctionGraph::constant(Value::Float(1.0));
|
||||
@@ -206,6 +219,7 @@ fn deep_graphs_shared_inputs_and_cycles_do_not_recurse() {
|
||||
previous = graph.add("add", &[previous, previous], None);
|
||||
}
|
||||
graph.output = Some(previous);
|
||||
|
||||
assert_eq!(evaluate(&graph, &BTreeMap::new()).unwrap(), Value::Float(1_073_741_824.0));
|
||||
}
|
||||
|
||||
@@ -236,6 +250,7 @@ fn pixel_assignments_are_local_and_match_exported_evaluation() {
|
||||
|
||||
let read_only = compile(&FunctionGraph::constant(Value::Float(0.5)), 7).unwrap();
|
||||
let context = EvaluationContext { scope: Default::default(), position: [0.5; 2], size: [1.0; 2], images: &[], tile: true, variables: &BTreeMap::new() };
|
||||
|
||||
assert_eq!(read_only.evaluate_pixel(&context, &mut pixel_state).unwrap(), Value::Float(0.5));
|
||||
assert!(pixel_state.variables().is_empty());
|
||||
}
|
||||
@@ -253,6 +268,7 @@ fn pixel_random_seed_and_defined_variables_match_general_evaluation() {
|
||||
for variables in [BTreeMap::from([("$randomseed".into(), Value::Int(42)), ("known".into(), Value::Bool(true))]), BTreeMap::new()] {
|
||||
let context = EvaluationContext { scope: Default::default(), position: [0.5; 2], size: [1.0; 2], images: &[], tile: true, variables: &variables };
|
||||
let expected = program.evaluate(&context, &mut EvaluationState::default()).unwrap();
|
||||
|
||||
assert_eq!(program.evaluate_pixel(&context, &mut state).unwrap(), expected);
|
||||
}
|
||||
}
|
||||
@@ -587,6 +603,7 @@ fn unconnected_ifelse_branches_use_the_value_type_not_the_condition() {
|
||||
node.type_code = declared_type;
|
||||
let selected = if condition_value { 1 } else { 2 };
|
||||
let expected = if selected == missing { zero.clone() } else { value.clone() };
|
||||
|
||||
assert_eq!(evaluate(&graph, &BTreeMap::new()).unwrap(), expected);
|
||||
}
|
||||
}
|
||||
@@ -603,6 +620,7 @@ fn unconnected_ifelse_condition_stays_boolean_and_empty_branches_keep_declared_t
|
||||
let node = graph.nodes.last_mut().unwrap();
|
||||
node.inputs = vec![None, Some(branch), None];
|
||||
node.type_code = 0;
|
||||
|
||||
assert_eq!(evaluate(&graph, &BTreeMap::new()).unwrap(), Value::Float(0.0));
|
||||
|
||||
for condition_value in [false, true] {
|
||||
@@ -612,6 +630,7 @@ fn unconnected_ifelse_condition_stays_boolean_and_empty_branches_keep_declared_t
|
||||
let node = graph.nodes.last_mut().unwrap();
|
||||
node.inputs = vec![Some(condition), None, None];
|
||||
node.type_code = 512;
|
||||
|
||||
assert_eq!(evaluate(&graph, &BTreeMap::new()).unwrap(), Value::Float2([0.0; 2]));
|
||||
}
|
||||
}
|
||||
+76
-57
@@ -6,34 +6,40 @@ use rayon::prelude::*;
|
||||
|
||||
/// Gaussian blur with standard deviation `sigma` (pixels). Small sigmas use a sampled kernel;
|
||||
/// larger ones three box passes (a close Gaussian approximation in O(1) per pixel).
|
||||
pub fn gaussian(img: &Image, sigma: f32, tile: bool) -> Image {
|
||||
if sigma.is_nan() || sigma <= 0.05 || !sigma.is_finite() {
|
||||
return img.clone();
|
||||
pub fn gaussian(image: &Image, sigma: f32, tile: bool) -> Image {
|
||||
const MIN_SIGMA_PIXELS: f32 = 0.05;
|
||||
const BOX_BLUR_MIN_SIGMA_PIXELS: f32 = 3.0;
|
||||
const KERNEL_RADIUS_SIGMAS: f32 = 3.0;
|
||||
|
||||
if sigma.is_nan() || sigma <= MIN_SIGMA_PIXELS || !sigma.is_finite() {
|
||||
return image.clone();
|
||||
}
|
||||
|
||||
let sigma = sigma.min(img.width().max(img.height()) as f32);
|
||||
if sigma < 3.0 {
|
||||
let r = (sigma * 3.0).ceil() as i64;
|
||||
let k: Vec<f32> = (-r..=r).map(|i| (-(i * i) as f32 / (2.0 * sigma * sigma)).exp()).collect();
|
||||
let s: f32 = k.iter().sum();
|
||||
let k: Vec<f32> = k.iter().map(|v| v / s).collect();
|
||||
let pass = |src: &Image, horizontal: bool| convolve_1d(src, &k, r, horizontal, tile);
|
||||
return pass(&pass(img, true), false);
|
||||
let sigma = sigma.min(image.width().max(image.height()) as f32);
|
||||
if sigma < BOX_BLUR_MIN_SIGMA_PIXELS {
|
||||
let radius = (sigma * KERNEL_RADIUS_SIGMAS).ceil() as i64;
|
||||
let kernel: Vec<f32> = (-radius..=radius).map(|i| (-(i * i) as f32 / (2.0 * sigma * sigma)).exp()).collect();
|
||||
let kernel_sum: f32 = kernel.iter().sum();
|
||||
let kernel: Vec<f32> = kernel.iter().map(|v| v / kernel_sum).collect();
|
||||
let pass = |src: &Image, horizontal: bool| convolve_1d(src, &kernel, radius, horizontal, tile);
|
||||
return pass(&pass(image, true), false);
|
||||
}
|
||||
|
||||
// Box widths for three passes (Kovesi, "Fast almost-Gaussian filtering")
|
||||
let n = 3.0f32;
|
||||
let wl = ((12.0 * sigma * sigma / n + 1.0).sqrt()).floor() as i64;
|
||||
let wl = if wl % 2 == 0 { wl - 1 } else { wl };
|
||||
let wu = wl + 2;
|
||||
let m = ((12.0 * sigma * sigma - n * (wl * wl) as f32 - 4.0 * n * wl as f32 - 3.0 * n) / (-4.0 * wl as f32 - 4.0)).round() as i64;
|
||||
let mut out = img.clone();
|
||||
let pass_count = 3.0f32;
|
||||
let lower_width = ((12.0 * sigma * sigma / pass_count + 1.0).sqrt()).floor() as i64;
|
||||
let lower_width = if lower_width % 2 == 0 { lower_width - 1 } else { lower_width };
|
||||
let upper_width = lower_width + 2;
|
||||
let lower_passes = ((12.0 * sigma * sigma - pass_count * (lower_width * lower_width) as f32 - 4.0 * pass_count * lower_width as f32 - 3.0 * pass_count)
|
||||
/ (-4.0 * lower_width as f32 - 4.0))
|
||||
.round() as i64;
|
||||
let mut output = image.clone();
|
||||
for i in 0..3 {
|
||||
let r = (if i < m { wl } else { wu } - 1) / 2;
|
||||
out = box_1d(&box_1d(&out, r.max(0), true, tile), r.max(0), false, tile);
|
||||
let radius = (if i < lower_passes { lower_width } else { upper_width } - 1) / 2;
|
||||
output = box_1d(&box_1d(&output, radius.max(0), true, tile), radius.max(0), false, tile);
|
||||
}
|
||||
|
||||
out
|
||||
output
|
||||
}
|
||||
|
||||
/// The default limits, raised to admit `src`, so a pass over an image made with raised limits
|
||||
@@ -46,66 +52,73 @@ fn limits_for(src: &Image) -> Limits {
|
||||
limits
|
||||
}
|
||||
|
||||
fn convolve_1d(src: &Image, k: &[f32], r: i64, horizontal: bool, tile: bool) -> Image {
|
||||
let c = src.channels();
|
||||
fn convolve_1d(src: &Image, kernel: &[f32], radius: i64, horizontal: bool, tile: bool) -> Image {
|
||||
let channels = src.channels();
|
||||
Image::try_generate(src.width(), src.height(), src.kind(), &limits_for(src), |x, y| {
|
||||
let mut acc = [0.0f32; 4];
|
||||
for (i, kv) in k.iter().enumerate() {
|
||||
let o = i as i64 - r;
|
||||
let p = if horizontal { src.get(x as i64 + o, y as i64, tile) } else { src.get(x as i64, y as i64 + o, tile) };
|
||||
for ch in 0..c.clamp(1, 4) {
|
||||
acc[ch] += p[ch] * kv;
|
||||
let mut accumulator = [0.0f32; 4];
|
||||
for (i, weight) in kernel.iter().enumerate() {
|
||||
let offset = i as i64 - radius;
|
||||
let pixel = if horizontal { src.get(x as i64 + offset, y as i64, tile) } else { src.get(x as i64, y as i64 + offset, tile) };
|
||||
for channel in 0..channels.clamp(1, 4) {
|
||||
accumulator[channel] += pixel[channel] * weight;
|
||||
}
|
||||
}
|
||||
if c == 1 { [acc[0], 0.0, 0.0, 0.0] } else { acc }
|
||||
if channels == 1 { [accumulator[0], 0.0, 0.0, 0.0] } else { accumulator }
|
||||
})
|
||||
.unwrap_or_else(|_| src.clone())
|
||||
}
|
||||
|
||||
/// One running-sum box pass of radius `r`.
|
||||
fn box_1d(src: &Image, r: i64, horizontal: bool, tile: bool) -> Image {
|
||||
if r <= 0 {
|
||||
/// One running-sum box pass of radius `radius`.
|
||||
fn box_1d(src: &Image, radius: i64, horizontal: bool, tile: bool) -> Image {
|
||||
if radius <= 0 {
|
||||
return src.clone();
|
||||
}
|
||||
|
||||
let (w, h) = (src.width() as usize, src.height() as usize);
|
||||
let c = src.channels();
|
||||
let inv = 1.0 / (2 * r + 1) as f64;
|
||||
let mut data = vec![0.0f32; w * h * c];
|
||||
let channels = src.channels();
|
||||
let inverse_width = 1.0 / (2 * radius + 1) as f64;
|
||||
let mut data = vec![0.0f32; w * h * channels];
|
||||
let line_len = if horizontal { w } else { h };
|
||||
let lines = if horizontal { h } else { w };
|
||||
// The running sum is kept in f64, so a window of finite values near `f32::MAX` does not overflow.
|
||||
let get = |line: usize, i: i64, ch: usize| -> f64 {
|
||||
|
||||
// f64 keeps finite HDR windows from overflowing the running sum
|
||||
let get = |line: usize, i: i64, channel: usize| -> f64 {
|
||||
let n = line_len as i64;
|
||||
let i = if tile { i.rem_euclid(n) } else { i.clamp(0, n - 1) } as usize;
|
||||
let (x, y) = if horizontal { (i, line) } else { (line, i) };
|
||||
f64::from(src.data().get((y * w + x) * c + ch).copied().unwrap_or(0.0))
|
||||
f64::from(src.data().get((y * w + x) * channels + channel).copied().unwrap_or(0.0))
|
||||
};
|
||||
|
||||
let results: Vec<Vec<f32>> = (0..lines)
|
||||
.into_par_iter()
|
||||
.map(|line| {
|
||||
let mut out = vec![0.0f32; line_len * c];
|
||||
for ch in 0..c {
|
||||
let mut sum: f64 = (-r..=r).map(|i| get(line, i, ch)).sum();
|
||||
for i in 0..line_len {
|
||||
out[i * c + ch] = (sum * inv) as f32;
|
||||
sum += get(line, i as i64 + r + 1, ch) - get(line, i as i64 - r, ch);
|
||||
}
|
||||
let fill_line = |line: usize, output: &mut [f32]| {
|
||||
for channel in 0..channels {
|
||||
let mut sum: f64 = (-radius..=radius).map(|i| get(line, i, channel)).sum();
|
||||
for i in 0..line_len {
|
||||
output[i * channels + channel] = (sum * inverse_width) as f32;
|
||||
sum += get(line, i as i64 + radius + 1, channel) - get(line, i as i64 - radius, channel);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
out
|
||||
})
|
||||
.collect();
|
||||
for (line, vals) in results.iter().enumerate() {
|
||||
for i in 0..line_len {
|
||||
let (x, y) = if horizontal { (i, line) } else { (line, i) };
|
||||
let dst = (y * w + x) * c;
|
||||
data[dst..dst + c].copy_from_slice(&vals[i * c..i * c + c]);
|
||||
if horizontal {
|
||||
data.par_chunks_mut(w * channels).enumerate().for_each(|(line, output)| fill_line(line, output));
|
||||
} else {
|
||||
let results: Vec<Vec<f32>> = (0..lines)
|
||||
.into_par_iter()
|
||||
.map(|line| {
|
||||
let mut output = vec![0.0f32; line_len * channels];
|
||||
fill_line(line, &mut output);
|
||||
output
|
||||
})
|
||||
.collect();
|
||||
for (line, values) in results.into_iter().enumerate() {
|
||||
for i in 0..line_len {
|
||||
let destination = (i * w + line) * channels;
|
||||
data[destination..destination + channels].copy_from_slice(&values[i * channels..i * channels + channels]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// `data` has the size and kind of `src`, which is a valid image.
|
||||
// A valid source has matching dimensions and data length
|
||||
Image::from_data(src.width(), src.height(), src.kind(), data, &limits_for(src)).unwrap_or_else(|_| src.clone())
|
||||
}
|
||||
|
||||
@@ -417,9 +430,11 @@ mod tests {
|
||||
let img = Image::gray(32, 32, |x, y| if (x / 4 + y / 4) % 2 == 0 { 1.0 } else { 0.0 });
|
||||
for s in [1.0, 6.0] {
|
||||
let b = gaussian(&img, s, true);
|
||||
|
||||
assert!((b.mean()[0] - img.mean()[0]).abs() < 1e-3, "sigma {s}");
|
||||
}
|
||||
let flat = gaussian(&Image::filled(8, 8, Kind::Color, [0.2, 0.4, 0.6, 1.0]), 4.0, false);
|
||||
|
||||
assert!((flat.get(3, 3, false)[1] - 0.4).abs() < 1e-5);
|
||||
}
|
||||
|
||||
@@ -427,8 +442,10 @@ mod tests {
|
||||
fn box_blur_of_large_hdr_values_stays_finite() {
|
||||
let value = 0.75 * f32::MAX;
|
||||
let blurred = gaussian(&Image::filled(16, 4, Kind::Gray, [value; 4]), 5.0, true);
|
||||
|
||||
for x in 0..16 {
|
||||
let v = blurred.get(x, 1, false)[0];
|
||||
|
||||
assert!(v.is_finite() && (v / value - 1.0).abs() < 1e-5, "pixel {x} is {v}");
|
||||
}
|
||||
}
|
||||
@@ -442,8 +459,10 @@ mod tests {
|
||||
let Ok(img) = Image::from_data(w, 1, Kind::Gray, values, &limits) else {
|
||||
panic!("a {w}x1 image fits the raised limits");
|
||||
};
|
||||
|
||||
for sigma in [1.0, 5.0] {
|
||||
let blurred = gaussian(&img, sigma, false);
|
||||
|
||||
assert_eq!((blurred.width(), blurred.height()), (w, 1), "sigma {sigma}");
|
||||
assert_ne!(blurred.data(), img.data(), "sigma {sigma} left the pixels unchanged");
|
||||
}
|
||||
|
||||
@@ -5,13 +5,15 @@ use super::{pattern_stamp::PatternStamp, region::Region, shape};
|
||||
use crate::CookContext;
|
||||
|
||||
const MAX_SAMPLES: u64 = 256_000_000;
|
||||
const MAX_STAMP_COPIES: u64 = 1_048_576;
|
||||
const MIN_STAMP_SIZE: f32 = 1e-8;
|
||||
|
||||
pub(super) fn render(context: &CookContext, stamps: &[PatternStamp], max_depth: u32) -> Result<Image, String> {
|
||||
let (width, height) = craft_texture::clamp_size(context.w, context.h);
|
||||
let kind = if context.b("color_mode") { Kind::Color } else { Kind::Gray };
|
||||
let background =
|
||||
let mut background =
|
||||
context.input(0).map(|image| image.resize(width, height, context.tile)).unwrap_or_else(|| Image::filled(width, height, kind, context.v4("background")));
|
||||
let background = if kind == Kind::Gray { background.to_gray() } else { background.to_color() };
|
||||
background = if kind == Kind::Gray { background.to_gray() } else { background.to_color() };
|
||||
if stamps.is_empty() {
|
||||
return Ok(background);
|
||||
}
|
||||
@@ -20,11 +22,12 @@ pub(super) fn render(context: &CookContext, stamps: &[PatternStamp], max_depth:
|
||||
let opacity = context.f("opacity").max(0.0);
|
||||
let weights = depth_weights(context.f("roughness"), max_depth)?;
|
||||
let integer_sampling = background.integer_sampling();
|
||||
let data = Arc::clone(background.shared_data());
|
||||
let mut data = Arc::clone(background.shared_data());
|
||||
drop(background);
|
||||
let mut pixels = Arc::unwrap_or_clone(data);
|
||||
|
||||
let pixels = Arc::make_mut(&mut data);
|
||||
let mut budget = MAX_SAMPLES;
|
||||
let mut copies_left = 1_048_576_u64;
|
||||
let mut copies_left = MAX_STAMP_COPIES;
|
||||
let render_region = Region::new(context.v4("render_region"))?;
|
||||
let period = if context.tile { Region::new(context.v4("tiling_region"))?.period() } else { [1.0; 2] };
|
||||
|
||||
@@ -33,7 +36,7 @@ pub(super) fn render(context: &CookContext, stamps: &[PatternStamp], max_depth:
|
||||
return Err("pattern parameters must be finite".into());
|
||||
}
|
||||
|
||||
if stamp.size.iter().any(|size| size.abs() < 1e-8) {
|
||||
if stamp.size.iter().any(|size| size.abs() < MIN_STAMP_SIZE) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -123,11 +126,11 @@ pub(super) fn render(context: &CookContext, stamps: &[PatternStamp], max_depth:
|
||||
}
|
||||
}
|
||||
|
||||
Image::from_data(width, height, kind, pixels, &Limits::default()).map(|image| image.with_integer_sampling(integer_sampling)).map_err(|e| e.to_string())
|
||||
Image::from_data(width, height, kind, data, &Limits::default()).map(|image| image.with_integer_sampling(integer_sampling)).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
fn depth_weights(roughness: f32, max_depth: u32) -> Result<Vec<f32>, String> {
|
||||
// Traversal is bounded by the 4096-node acyclic pattern graph. Keep this allocation bounded too
|
||||
// Match the depth allocation cap to the 4096-node acyclic traversal limit
|
||||
if max_depth >= 4096 || !roughness.is_finite() || roughness < 0.0 {
|
||||
return Err("pattern roughness must be finite and nonnegative, with depth below 4096".into());
|
||||
}
|
||||
|
||||
@@ -67,12 +67,17 @@ fn iterate_sets_number_and_switch_selects_one_child() {
|
||||
function.output = Some(function.add("get_float1", &[], Some(Value::Text("$number".into()))));
|
||||
graph.nodes[2].parameters.insert("opacity".into(), Value::Function(Box::new(function)));
|
||||
let image = cook(graph.clone()).unwrap().remove(0);
|
||||
|
||||
assert!((image.mean()[0] - 3.0).abs() < 1e-6);
|
||||
|
||||
let dot = graph.add(PatternNodeKind::Dot).unwrap();
|
||||
graph.nodes[1].children[0] = Some(dot);
|
||||
graph.nodes[3].children[0] = Some(quadrant);
|
||||
|
||||
assert_eq!(cook(graph.clone()).unwrap()[0].data(), image.data());
|
||||
|
||||
graph.nodes[1].parameters.insert("switch".into(), Value::Bool(true));
|
||||
|
||||
assert_eq!(cook(graph).unwrap()[0].mean()[0], 0.0);
|
||||
}
|
||||
|
||||
|
||||
@@ -69,11 +69,14 @@ fn every_node_cooks() {
|
||||
let result = cook(definition, &inputs, 32);
|
||||
if definition.id == "pixel_processor" {
|
||||
assert_eq!(result.unwrap_err(), "function has no result node");
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
let outputs = result.unwrap_or_else(|error| panic!("{}: {error}", definition.id));
|
||||
|
||||
assert_eq!(outputs.len(), definition.outputs.len().max(1), "{}", definition.id);
|
||||
|
||||
for image in &outputs {
|
||||
assert_eq!((image.width(), image.height()), (32, 32), "{}", definition.id);
|
||||
assert!(image.data().iter().all(|value| value.is_finite()), "{} produced a non-finite value", definition.id);
|
||||
@@ -180,6 +183,7 @@ fn dynamic_gradient_preserves_the_gradient_image_type() {
|
||||
let source = Image::filled(4, 4, Kind::Gray, [0.5; 4]);
|
||||
let gradient = Image::filled(4, 4, kind, [0.25, 0.5, 0.75, 1.0]);
|
||||
let result = cook(definition, &[Some(source), Some(gradient.clone())], 16).unwrap();
|
||||
|
||||
assert_eq!(result[0].kind(), kind);
|
||||
assert_eq!(result[0].get(0, 0, false), gradient.get(0, 0, false));
|
||||
}
|
||||
@@ -199,6 +203,7 @@ fn an_oversized_transformation_covers_the_whole_input() {
|
||||
let ramp = Image::gray(8192, 1, |x, _| x as f32 / 8191.0);
|
||||
let out = cook_sized(find("transformation").unwrap(), &[Some(ramp)], 16384, 1, &|_| None).unwrap();
|
||||
let last = out[0].get(8191, 0, false)[0];
|
||||
|
||||
assert!(last > 0.99, "the last pixel reads the ramp at {last}");
|
||||
}
|
||||
|
||||
@@ -207,20 +212,52 @@ fn an_oversized_transformation_covers_the_whole_input() {
|
||||
fn transformation_resamples_extreme_neighbors_to_finite_values() {
|
||||
let extremes = Image::gray(2, 1, |x, _| if x == 0 { f32::MAX } else { -f32::MAX });
|
||||
let out = cook_sized(find("transformation").unwrap(), &[Some(extremes)], 4, 1, &|_| None).unwrap();
|
||||
|
||||
for x in 0..4 {
|
||||
let value = out[0].get(x, 0, false)[0];
|
||||
|
||||
assert!(value.is_finite(), "pixel {x} is {value}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nearest_transformation_mips_preserve_finite_hdr_constants() {
|
||||
let definition = find("transformation").unwrap();
|
||||
let parameters = resolve_params(definition, &BTreeMap::from([("filtering".into(), Value::Enum(1))]));
|
||||
let variables = BTreeMap::new();
|
||||
let value = 0.75 * f32::MAX;
|
||||
|
||||
for kind in [Kind::Gray, Kind::Color] {
|
||||
let inputs = [Some(Image::filled(16, 16, kind, [value; 4]))];
|
||||
let context = CookContext {
|
||||
format: materialcraft_core::OutputFormat::F32,
|
||||
w: 4,
|
||||
h: 4,
|
||||
seed: 7,
|
||||
tile: false,
|
||||
inputs: &inputs,
|
||||
params: ¶meters,
|
||||
resource: &|_| None,
|
||||
vars: &variables,
|
||||
};
|
||||
|
||||
let output = (definition.cook)(&context).unwrap().remove(0);
|
||||
|
||||
assert_eq!((output.width(), output.height(), output.kind()), (4, 4, kind));
|
||||
assert!(output.data().iter().all(|pixel| *pixel == value), "{:?}", output.data());
|
||||
}
|
||||
}
|
||||
|
||||
/// A repeated input offset far past its edge keeps the offset's phase: an offset near 2^31 lands on
|
||||
/// the same place as an offset of zero, halfway between the last and the first column.
|
||||
#[test]
|
||||
fn directional_warp_repeats_a_far_offset_with_its_phase() {
|
||||
let stripes = Image::gray(3, 3, |x, _| [0.0, 1.0, 4.0][x as usize]);
|
||||
// Intensity 10 scales the map by 10 / 256, so this map moves every pixel by about 2^31.
|
||||
|
||||
// Intensity 10 scales the map by 10 / 256, moving each pixel by about 2^31
|
||||
let far = Image::filled(3, 3, Kind::Gray, [2_147_483_648.0 * 25.6; 4]);
|
||||
let out = cook(find("directional_warp").unwrap(), &[Some(stripes), Some(far)], 3).unwrap();
|
||||
|
||||
for x in 0..3 {
|
||||
assert_eq!(out[0].get_gray(x, 1, false), 2.0, "pixel {x}");
|
||||
}
|
||||
@@ -232,6 +269,7 @@ fn bitmap_shrinks_large_hdr_values_without_overflow() {
|
||||
let hdr = |_: &str| Some(Image::filled(2, 2, Kind::Color, [0.75 * f32::MAX, 0.75 * f32::MAX, 0.75 * f32::MAX, 1.0]));
|
||||
let out = cook_sized(find("bitmap").unwrap(), &[], 1, 1, &hdr).unwrap();
|
||||
let pixel = out[0].get(0, 0, false);
|
||||
|
||||
assert!(pixel.iter().all(|value| value.is_finite()), "{pixel:?}");
|
||||
assert!((pixel[0] / (0.75 * f32::MAX) - 1.0).abs() < 1e-6, "{pixel:?}");
|
||||
}
|
||||
@@ -55,11 +55,14 @@ fn distance_handles_empty_full_masks_and_no_source() {
|
||||
let empty = Image::filled(7, 5, Kind::Gray, [0.0; 4]);
|
||||
let full = Image::filled(7, 5, Kind::Gray, [1.0; 4]);
|
||||
let source = Image::generate(7, 5, Kind::Color, |x, y| [x as f32 / 7.0, y as f32 / 5.0, 0.4, 0.7]);
|
||||
|
||||
assert!(cook(empty.clone(), Some(source.clone()), tile, false, 256.0).data().iter().all(|&v| v == 0.0));
|
||||
assert_eq!(cook(full, Some(source), tile, true, 256.0).get(3, 2, false), [3.0 / 7.0, 2.0 / 5.0, 0.4, 0.7]);
|
||||
assert!(cook(empty, None, tile, true, 256.0).data().iter().all(|&v| v == 0.0));
|
||||
|
||||
let mask = Image::gray(7, 5, |x, y| if x == 0 && y == 0 { 1.0 } else { 0.0 });
|
||||
let ramp = cook(mask, None, tile, false, 512.0 / 7.0);
|
||||
|
||||
assert_eq!(ramp.get_gray(0, 0, false), 1.0);
|
||||
assert_eq!(ramp.get_gray(1, 0, false), 0.5);
|
||||
assert_eq!(ramp.get_gray(3, 0, false), 0.0);
|
||||
|
||||
@@ -22,6 +22,7 @@ fn absent_textures_have_zero_pixels_and_expected_kinds() {
|
||||
let image = outputs.first().unwrap();
|
||||
|
||||
assert_eq!(image.kind(), kind, "{id}");
|
||||
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
assert_eq!(image.get(x.into(), y.into(), false), pixel, "{id} at {x},{y}");
|
||||
|
||||
@@ -94,8 +94,9 @@ impl Scene {
|
||||
mesh = mesh.subdivided();
|
||||
}
|
||||
|
||||
// Pre-filtered so detail finer than the mesh (left to the normal map) does not spike the silhouette
|
||||
let height = height.resize(height.width().min(512), height.height().min(512), true);
|
||||
// Filter detail finer than the mesh to prevent silhouette spikes
|
||||
const MAX_HEIGHT_MAP_SIDE: u32 = 512;
|
||||
let height = height.resize(height.width().min(MAX_HEIGHT_MAP_SIDE), height.height().min(MAX_HEIGHT_MAP_SIDE), true);
|
||||
let level = if displacement.level.is_finite() { displacement.level.clamp(0.0, 1.0) } else { 0.0 };
|
||||
let depth = if displacement.depth.is_finite() { displacement.depth } else { 0.0 };
|
||||
let tiling = if displacement.tiling.is_finite() { displacement.tiling.max(0.01) } else { 1.0 };
|
||||
@@ -495,52 +496,52 @@ pub fn render(scene: &Scene, maps: &Maps, light: &Lighting, s: &Settings, w: u32
|
||||
/// [`render`] that gives up once `cancel` is set (rows not yet started are skipped) and then
|
||||
/// returns `None`: a frame the viewer no longer needs (the camera moved, the view was resized)
|
||||
/// stops holding the CPU.
|
||||
pub fn render_cancellable(scene: &Scene, maps: &Maps, light: &Lighting, s: &Settings, w: u32, h: u32, cancel: &AtomicBool) -> Option<Vec<u8>> {
|
||||
pub fn render_cancellable(scene: &Scene, maps: &Maps, light: &Lighting, settings: &Settings, w: u32, h: u32, cancel: &AtomicBool) -> Option<Vec<u8>> {
|
||||
let (w, h) = (w.clamp(1, 4096), h.clamp(1, 4096));
|
||||
let cam = camera(scene, s);
|
||||
let camera = camera(scene, settings);
|
||||
let aspect = w as f32 / h as f32;
|
||||
let ss = s.supersample.clamp(1, 4);
|
||||
let k = 2f32.powf(s.exposure);
|
||||
let bg_env = light.specular.get(3).or(light.specular.last());
|
||||
let samples_per_axis = settings.supersample.clamp(1, 4);
|
||||
let exposure_scale = 2f32.powf(settings.exposure);
|
||||
let background_environment = light.specular.get(3).or(light.specular.last());
|
||||
|
||||
// Key light from the camera's upper left, a little in front of the subject
|
||||
let fwd = cam.ray(Vec2::ZERO, aspect).dir;
|
||||
let right = fwd.cross(Vec3::Y).normalize_or(Vec3::X);
|
||||
let key = (right * -0.6 + right.cross(fwd) * 0.75 - fwd * 0.5).normalize_or_zero();
|
||||
let mut out = vec![0u8; (w * h * 4) as usize];
|
||||
out.par_chunks_mut(w as usize * 4).enumerate().for_each(|(y, row)| {
|
||||
let forward = camera.ray(Vec2::ZERO, aspect).dir;
|
||||
let right = forward.cross(Vec3::Y).normalize_or(Vec3::X);
|
||||
let key = (right * -0.6 + right.cross(forward) * 0.75 - forward * 0.5).normalize_or_zero();
|
||||
let mut output = vec![0u8; (w * h * 4) as usize];
|
||||
output.par_chunks_mut(w as usize * 4).enumerate().for_each(|(y, row)| {
|
||||
if cancel.load(Ordering::Relaxed) {
|
||||
return;
|
||||
}
|
||||
|
||||
for x in 0..w as usize {
|
||||
let mut acc = Vec3::ZERO;
|
||||
for sy in 0..ss {
|
||||
for sx in 0..ss {
|
||||
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 mut accumulated = Vec3::ZERO;
|
||||
for sy in 0..samples_per_axis {
|
||||
for sx in 0..samples_per_axis {
|
||||
let px = (x as f32 + (sx as f32 + 0.5) / samples_per_axis as f32) / w as f32 * 2.0 - 1.0;
|
||||
let py = 1.0 - (y as f32 + (sy as f32 + 0.5) / samples_per_axis as f32) / h as f32 * 2.0;
|
||||
let ray = camera.ray(Vec2::new(px, py), aspect);
|
||||
let background = backdrop(Vec2::new(px, py));
|
||||
let p = Px { key, jitter: jitter(x as u32 * samples_per_axis + sx, y as u32 * samples_per_axis + sy) };
|
||||
let miss = match (settings.show_env, background_environment) {
|
||||
(true, Some(e)) => e.sample(rotate_y(ray.dir, -settings.env_rotation)) * exposure_scale,
|
||||
_ => background,
|
||||
};
|
||||
acc += if s.alpha_view {
|
||||
accumulated += if settings.alpha_view {
|
||||
// Display values: the alpha as is, the background tone mapped
|
||||
match shade(scene, maps, light, s, ray.origin, ray.dir, &p) {
|
||||
match shade(scene, maps, light, settings, ray.origin, ray.dir, &p) {
|
||||
Some(h) => h.color,
|
||||
None => miss.map(|v| linear_to_srgb(aces(v))),
|
||||
}
|
||||
} else {
|
||||
trace(scene, maps, light, s, ray.origin, ray.dir, &p, k, miss)
|
||||
trace(scene, maps, light, settings, ray.origin, ray.dir, &p, exposure_scale, miss)
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
let c = acc / (ss * ss) as f32;
|
||||
let c = accumulated / (samples_per_axis * samples_per_axis) as f32;
|
||||
let q = |v: f32| {
|
||||
let d = if s.alpha_view { v } else { linear_to_srgb(aces(v)) };
|
||||
let d = if settings.alpha_view { v } else { linear_to_srgb(aces(v)) };
|
||||
(d.clamp(0.0, 1.0) * 255.0 + 0.5) as u8
|
||||
};
|
||||
if let Some(px) = row.get_mut(x * 4..x * 4 + 4) {
|
||||
@@ -548,7 +549,7 @@ pub fn render_cancellable(scene: &Scene, maps: &Maps, light: &Lighting, s: &Sett
|
||||
}
|
||||
}
|
||||
});
|
||||
if cancel.load(Ordering::Relaxed) { None } else { Some(out) }
|
||||
if cancel.load(Ordering::Relaxed) { None } else { Some(output) }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -77,8 +77,11 @@ fn batch_writes_every_material_graph_at_the_output_size() {
|
||||
assert!(export(&mut app, &settings));
|
||||
|
||||
assert_eq!(files(&directory), ["New_graph_base_color.png", "New_graph_height.png", "Second_mask.png"]);
|
||||
|
||||
let image = materialcraft_engine::formats::decode(&std::fs::read(directory.join("Second_mask.png")).unwrap(), true).unwrap();
|
||||
|
||||
assert_eq!((image.width(), image.height()), (64, 32));
|
||||
|
||||
let _ = std::fs::remove_dir_all(directory);
|
||||
}
|
||||
|
||||
|
||||
@@ -50,9 +50,9 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
|
||||
fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
let theme = Tokens::get(ui.ctx());
|
||||
let ctx = ui.ctx().clone();
|
||||
let (rect, resp) = ui.allocate_exact_size(ui.available_size(), Sense::click_and_drag());
|
||||
crate::widgets::name(&resp, egui::Role::Canvas, "Node graph");
|
||||
let context = ui.ctx().clone();
|
||||
let (rect, response) = ui.allocate_exact_size(ui.available_size(), Sense::click_and_drag());
|
||||
crate::widgets::name(&response, egui::Role::Canvas, "Node graph");
|
||||
app.graph.view = rect;
|
||||
if app.ui.frame_all || app.graph.framed_graph != Some(app.session.graph) {
|
||||
app.ui.frame_all = false;
|
||||
@@ -69,7 +69,7 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
camera.zoom_from_input(ui, rect);
|
||||
app.ui.graph_camera = camera.state();
|
||||
super::grid::paint(&painter, &camera, rect);
|
||||
let pointer = ctx.input(|input| input.pointer.hover_pos());
|
||||
let pointer = context.input(|input| input.pointer.hover_pos());
|
||||
|
||||
let show_thumbnails = app.ui.prefs.thumbnails;
|
||||
let Ok(graph) = app.session.graph() else { return };
|
||||
@@ -82,7 +82,6 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
};
|
||||
|
||||
// Layout every node and its ports
|
||||
|
||||
let mut layouts: Vec<NodeLayout> = Vec::with_capacity(graph.nodes.len());
|
||||
for node in &graph.nodes {
|
||||
let (ins, outs) = materialcraft_engine::eval::ports_with_connections(&app.session.pkg, node, index.incoming(node.id).iter().copied());
|
||||
@@ -211,24 +210,29 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
dot_grabs.push(grab);
|
||||
}
|
||||
|
||||
let resp = ui.interact(grab, ui.scope_id().with(("node", node.id.0)), Sense::click_and_drag());
|
||||
crate::widgets::name(&resp, egui::Role::Button, &node_label(node));
|
||||
let response = ui.interact(grab, ui.scope_id().with(("node", node.id.0)), Sense::click_and_drag());
|
||||
crate::widgets::name(&response, egui::Role::Button, &node_label(node));
|
||||
if node.def == "dot" {
|
||||
node_card::paint_dot(&painter, screen_rect, if selected { theme.accent } else { Color32::from_gray(0xb4) });
|
||||
} else {
|
||||
node_card::paint(&painter, screen_rect, camera.zoom, &node_label(node), header_color(&node.def));
|
||||
let header = node_card::header(screen_rect, camera.zoom);
|
||||
let body = node_card::body(screen_rect, camera.zoom);
|
||||
if let Some(r0) = result
|
||||
&& let Some(img) = r0.outputs.first().and_then(materialcraft_engine::eval::NodeOutput::as_image)
|
||||
if let Some(node_result) = result
|
||||
&& let Some(image) = node_result.outputs.first().and_then(materialcraft_engine::eval::NodeOutput::as_image)
|
||||
&& show_thumbnails
|
||||
&& !app.graph.thumbnails_cleared
|
||||
{
|
||||
let side = body.width().min(body.height()) - 6.0 * camera.zoom;
|
||||
let tr_ = Rect::from_center_size(body.center(), vec2(side, side));
|
||||
node_card::paint_well(&painter, tr_.expand(camera.zoom), camera.zoom);
|
||||
let tex = app.thumbs.node(&ctx, r0.key, 0, img);
|
||||
painter.image(tex, tr_, Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), if node.disabled { Color32::from_gray(90) } else { Color32::WHITE });
|
||||
let thumbnail_rect = Rect::from_center_size(body.center(), vec2(side, side));
|
||||
node_card::paint_well(&painter, thumbnail_rect.expand(camera.zoom), camera.zoom);
|
||||
let texture = app.thumbs.node(&context, node_result.key, 0, image);
|
||||
painter.image(
|
||||
texture,
|
||||
thumbnail_rect,
|
||||
Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)),
|
||||
if node.disabled { Color32::from_gray(90) } else { Color32::WHITE },
|
||||
);
|
||||
} else if let Some(value) = result.and_then(|result| result.outputs.first()).and_then(materialcraft_engine::eval::NodeOutput::as_value) {
|
||||
node_card::paint_well(&painter, body.shrink(4.0 * camera.zoom), camera.zoom);
|
||||
node_card::paint_symbol(&painter, body, camera.zoom, &super::value_text::value_text(value), theme.text_strong);
|
||||
@@ -240,25 +244,25 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
|
||||
// Footer: size and format
|
||||
let footer = Rect::from_min_max(pos2(screen_rect.left(), body.bottom()), screen_rect.max);
|
||||
if let Some(img) = result.and_then(|r| r.outputs.first().and_then(materialcraft_engine::eval::NodeOutput::as_image)) {
|
||||
if let Some(image) = result.and_then(|r| r.outputs.first().and_then(materialcraft_engine::eval::NodeOutput::as_image)) {
|
||||
let bits = result.map_or(graph.format.bits(), |result| result.base.format.bits());
|
||||
|
||||
let format = format!("{}{bits}", if img.is_gray() { "L" } else { "C" });
|
||||
let txt = if let Some(limit) = app.session.preview_size {
|
||||
let format = format!("{}{bits}", if image.is_gray() { "L" } else { "C" });
|
||||
let label_text = if let Some(limit) = app.session.preview_size {
|
||||
let [width, height] = graph.size_px();
|
||||
resp.clone().on_hover_text(format!(
|
||||
response.clone().on_hover_text(format!(
|
||||
"{} x {} ({bits}bpc)\n{}: {width} x {height}\n{}: {limit} px\n{}",
|
||||
img.width(),
|
||||
img.height(),
|
||||
image.width(),
|
||||
image.height(),
|
||||
tr("Parent size"),
|
||||
tr("Preview limit"),
|
||||
tr("Change Preview size while editing in Edit > Preferences. Exports use each node's configured output size.")
|
||||
));
|
||||
format!("{}x{} {}", img.width(), img.height(), tr("Preview"))
|
||||
format!("{}x{} {}", image.width(), image.height(), tr("Preview"))
|
||||
} else {
|
||||
format!("{}x{} - {format}", img.width(), img.height())
|
||||
format!("{}x{} - {format}", image.width(), image.height())
|
||||
};
|
||||
painter.text(footer.center(), Align2::CENTER_CENTER, txt, small.clone(), theme.text_dim);
|
||||
painter.text(footer.center(), Align2::CENTER_CENTER, label_text, small.clone(), theme.text_dim);
|
||||
}
|
||||
if node.def == "output" {
|
||||
painter.text(header.right_center() - vec2(4.0, 0.0), Align2::RIGHT_CENTER, icon::SIGN_OUT, small.clone(), Color32::WHITE);
|
||||
@@ -267,7 +271,7 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
Stroke::new(2.0, Color32::from_rgb(0xff, 0x30, 0xd0))
|
||||
} else if selected {
|
||||
Stroke::new(2.0, theme.accent)
|
||||
} else if resp.hovered() {
|
||||
} else if response.hovered() {
|
||||
Stroke::new(1.0, Color32::from_gray(0x90))
|
||||
} else {
|
||||
Stroke::new(1.0, Color32::from_gray(0x10))
|
||||
@@ -278,11 +282,11 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
painter.line_segment([screen_rect.left_top(), screen_rect.right_bottom()], Stroke::new(1.5, theme.danger));
|
||||
}
|
||||
if let Some(e) = error {
|
||||
resp.clone().on_hover_text(e);
|
||||
response.clone().on_hover_text(e);
|
||||
}
|
||||
}
|
||||
|
||||
node_responses.push((node.id, resp));
|
||||
node_responses.push((node.id, response));
|
||||
}
|
||||
|
||||
let comment_hits = super::annotation_canvas::comments(app, ui, &graph.comments, &camera);
|
||||
@@ -318,11 +322,11 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
// A wire under a comment is not hit
|
||||
let wire_hover = wire_hover.filter(|_| !pointer.is_some_and(|p| comment_hits.iter().any(|(_, r)| r.contains(p))));
|
||||
if wire_hover.is_some() {
|
||||
ctx.set_cursor_icon(egui::CursorIcon::PointingHand);
|
||||
context.set_cursor_icon(egui::CursorIcon::PointingHand);
|
||||
}
|
||||
|
||||
app.graph.inspected_node = super::node_selection::inspected(&app.session.selection, app.graph.inspected_node);
|
||||
super::input::handle(app, ui, &resp, rect, &camera, &node_responses, &frame_hits, &comment_hits, &pin_hits, port_hover, wire_hover);
|
||||
super::input::handle(app, ui, &response, rect, &camera, &node_responses, &frame_hits, &comment_hits, &pin_hits, port_hover, wire_hover);
|
||||
app.graph.inspected_node = super::node_selection::inspected(&app.session.selection, app.graph.inspected_node);
|
||||
|
||||
// GraphDrag previews
|
||||
|
||||
@@ -15,20 +15,20 @@ pub const BINS: usize = 256;
|
||||
const MIN_SPAN: f32 = 0.004;
|
||||
|
||||
/// Histograms of an image's values in 0..1, clamped: one for a gray image, else R, G and B
|
||||
pub fn histogram(img: &Image) -> Vec<[u32; BINS]> {
|
||||
let channels = if img.kind() == Kind::Gray { 1 } else { 3 };
|
||||
let stride = img.channels();
|
||||
let mut h = vec![[0u32; BINS]; channels];
|
||||
for px in img.data().chunks(stride) {
|
||||
for (c, bins) in h.iter_mut().enumerate() {
|
||||
let v = px.get(c).copied().unwrap_or(0.0);
|
||||
let v = if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 };
|
||||
if let Some(b) = bins.get_mut(((v * (BINS - 1) as f32).round() as usize).min(BINS - 1)) {
|
||||
*b = b.saturating_add(1);
|
||||
pub fn histogram(image: &Image) -> Vec<[u32; BINS]> {
|
||||
let channels = if image.kind() == Kind::Gray { 1 } else { 3 };
|
||||
let stride = image.channels();
|
||||
let mut histograms = vec![[0u32; BINS]; channels];
|
||||
for pixel in image.data().chunks(stride) {
|
||||
for (channel, bins) in histograms.iter_mut().enumerate() {
|
||||
let value = pixel.get(channel).copied().unwrap_or(0.0);
|
||||
let value = if value.is_finite() { value.clamp(0.0, 1.0) } else { 0.0 };
|
||||
if let Some(bin) = bins.get_mut(((value * (BINS - 1) as f32).round() as usize).min(BINS - 1)) {
|
||||
*bin = bin.saturating_add(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
h
|
||||
histograms
|
||||
}
|
||||
|
||||
/// The bar height scale: the tallest bin away from pure black and white (masks pile up there and would flatten everything else), at least one
|
||||
|
||||
@@ -38,27 +38,34 @@ pub fn title(app: &MaterialCraftApp) -> String {
|
||||
format!("{} - {}", name.unwrap_or_default(), tr("2D View"))
|
||||
}
|
||||
|
||||
fn rgba8(img: &Image, channel: &str) -> Vec<u8> {
|
||||
let base = img.to_rgba8_display();
|
||||
let pick = match channel {
|
||||
fn rgba8(image: &Image, channel: &str) -> Vec<u8> {
|
||||
let mut pixels = image.to_rgba8_display();
|
||||
let selected = match channel {
|
||||
"r" => Some(0),
|
||||
"g" => Some(1),
|
||||
"b" => Some(2),
|
||||
"a" => Some(3),
|
||||
_ => None,
|
||||
};
|
||||
match pick {
|
||||
Some(k) if img.kind() == Kind::Color => base.chunks(4).flat_map(|p| [p[k], p[k], p[k], 255]).collect(),
|
||||
_ => base,
|
||||
|
||||
if let Some(channel) = selected
|
||||
&& image.kind() == Kind::Color
|
||||
{
|
||||
for pixel in pixels.as_chunks_mut::<4>().0 {
|
||||
let value = pixel[channel];
|
||||
pixel.copy_from_slice(&[value, value, value, u8::MAX]);
|
||||
}
|
||||
}
|
||||
|
||||
pixels
|
||||
}
|
||||
|
||||
pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
let ctx = ui.ctx().clone();
|
||||
let theme = Tokens::get(ui.ctx());
|
||||
let context = ui.ctx().clone();
|
||||
|
||||
// Toolbar
|
||||
egui::Frame::NONE.fill(tk.panel).inner_margin(egui::Margin::symmetric(6, 3)).show(ui, |ui| {
|
||||
egui::Frame::NONE.fill(theme.panel).inner_margin(egui::Margin::symmetric(6, 3)).show(ui, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
crate::preview_resolution::show(app, ui);
|
||||
for (c, label) in [("rgba", "RGBA"), ("r", "R"), ("g", "G"), ("b", "B"), ("a", "A")] {
|
||||
@@ -87,90 +94,90 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
}
|
||||
});
|
||||
});
|
||||
let Some((id, img)) = app.session.view2d_image().map(|(id, i)| (id, i.clone())) else {
|
||||
let (r, resp) = ui.allocate_exact_size(ui.available_size(), Sense::hover());
|
||||
crate::widgets::name(&resp, egui::Role::Image, "2D view");
|
||||
ui.painter().rect_filled(r, 0.0, tk.viewport);
|
||||
ui.painter().text(r.center(), egui::Align2::CENTER_CENTER, tr("Click a node to show it here"), egui::FontId::proportional(12.0), tk.viewport_text);
|
||||
let Some((id, image)) = app.session.view2d_image().map(|(id, i)| (id, i.clone())) else {
|
||||
let (r, response) = ui.allocate_exact_size(ui.available_size(), Sense::hover());
|
||||
crate::widgets::name(&response, egui::Role::Image, "2D view");
|
||||
ui.painter().rect_filled(r, 0.0, theme.viewport);
|
||||
ui.painter().text(r.center(), egui::Align2::CENTER_CENTER, tr("Click a node to show it here"), egui::FontId::proportional(12.0), theme.viewport_text);
|
||||
return;
|
||||
};
|
||||
|
||||
let texture_limit = ctx.input(|i| i.max_texture_side).max(1);
|
||||
let texture_limit = context.input(|i| i.max_texture_side).max(1);
|
||||
let key = app.session.cooked.nodes.get(&id).map_or(0, |r| r.key)
|
||||
^ (texture_limit as u64).rotate_left(32)
|
||||
^ (img.width() as u64).rotate_left(16)
|
||||
^ img.height() as u64
|
||||
^ (image.width() as u64).rotate_left(16)
|
||||
^ image.height() as u64
|
||||
^ (app.session.view2d.port as u64).wrapping_mul(0x9e37)
|
||||
^ (app.session.view2d.channel.len() as u64 * 31)
|
||||
^ app.session.view2d.channel.bytes().next().unwrap_or(0) as u64;
|
||||
if app.view2d.tex.as_ref().is_none_or(|(k, _)| *k != key) {
|
||||
let px = rgba8(&img, &app.session.view2d.channel);
|
||||
let pixels = rgba8(&image, &app.session.view2d.channel);
|
||||
|
||||
// Keep source pixels for readout/screenshots, but respect the renderer's upload limit
|
||||
let ci = if img.width().max(img.height()) as usize > texture_limit {
|
||||
let scale = texture_limit as f64 / f64::from(img.width().max(img.height()));
|
||||
let color_image = if image.width().max(image.height()) as usize > texture_limit {
|
||||
let scale = texture_limit as f64 / f64::from(image.width().max(image.height()));
|
||||
let display =
|
||||
img.resize((f64::from(img.width()) * scale).floor().max(1.0) as u32, (f64::from(img.height()) * scale).floor().max(1.0) as u32, false);
|
||||
image.resize((f64::from(image.width()) * scale).floor().max(1.0) as u32, (f64::from(image.height()) * scale).floor().max(1.0) as u32, false);
|
||||
ColorImage::from_rgba_unmultiplied([display.width() as usize, display.height() as usize], &rgba8(&display, &app.session.view2d.channel))
|
||||
} else {
|
||||
ColorImage::from_rgba_unmultiplied([img.width() as usize, img.height() as usize], &px)
|
||||
ColorImage::from_rgba_unmultiplied([image.width() as usize, image.height() as usize], &pixels)
|
||||
};
|
||||
|
||||
app.view2d.tex = Some((key, ctx.load_texture("view2d", ci, TextureOptions::NEAREST)));
|
||||
app.view2d.shown = Some((img.width(), img.height(), px));
|
||||
app.view2d.tex = Some((key, context.load_texture("view2d", color_image, TextureOptions::NEAREST)));
|
||||
app.view2d.shown = Some((image.width(), image.height(), pixels));
|
||||
}
|
||||
|
||||
let avail = ui.available_size();
|
||||
let (rect, resp) = ui.allocate_exact_size(vec2(avail.x, (avail.y - 20.0).max(40.0)), Sense::click_and_drag());
|
||||
crate::widgets::name(&resp, egui::Role::Image, "2D view");
|
||||
let available = ui.available_size();
|
||||
let (rect, response) = ui.allocate_exact_size(vec2(available.x, (available.y - 20.0).max(40.0)), Sense::click_and_drag());
|
||||
crate::widgets::name(&response, egui::Role::Image, "2D view");
|
||||
let p = ui.painter_at(rect);
|
||||
p.rect_filled(rect, 0.0, tk.viewport);
|
||||
p.rect_filled(rect, 0.0, theme.viewport);
|
||||
|
||||
// Camera: fit, wheel zoom around the pointer, drag to pan
|
||||
app.ui.image_camera = app.ui.image_camera.sanitized();
|
||||
let cam = &mut app.ui.image_camera;
|
||||
let camera = &mut app.ui.image_camera;
|
||||
let tiles = if app.session.view2d.tiled { 3.0 } else { 1.0 };
|
||||
let fit_zoom = ((rect.width() - 16.0) / (img.width() as f32 * tiles)).min((rect.height() - 16.0) / (img.height() as f32 * tiles)).max(0.01);
|
||||
if cam.fit {
|
||||
cam.zoom = fit_zoom;
|
||||
cam.offset = [0.0, 0.0];
|
||||
let fit_zoom = ((rect.width() - 16.0) / (image.width() as f32 * tiles)).min((rect.height() - 16.0) / (image.height() as f32 * tiles)).max(0.01);
|
||||
if camera.fit {
|
||||
camera.zoom = fit_zoom;
|
||||
camera.offset = [0.0, 0.0];
|
||||
}
|
||||
|
||||
if resp.hovered() {
|
||||
if response.hovered() {
|
||||
let scroll = ui.input(|i| i.smooth_scroll_delta.y);
|
||||
if scroll.abs() > 0.0 {
|
||||
cam.fit = false;
|
||||
let old = cam.zoom;
|
||||
cam.zoom = (cam.zoom * (scroll * 0.003).exp()).clamp(0.02, 64.0);
|
||||
if let Some(ptr) = resp.hover_pos() {
|
||||
let c = rect.center() + vec2(cam.offset[0], cam.offset[1]);
|
||||
camera.fit = false;
|
||||
let old = camera.zoom;
|
||||
camera.zoom = (camera.zoom * (scroll * 0.003).exp()).clamp(0.02, 64.0);
|
||||
if let Some(ptr) = response.hover_pos() {
|
||||
let c = rect.center() + vec2(camera.offset[0], camera.offset[1]);
|
||||
let d = ptr - c;
|
||||
let k = cam.zoom / old;
|
||||
cam.offset = [cam.offset[0] - d.x * (k - 1.0), cam.offset[1] - d.y * (k - 1.0)];
|
||||
let k = camera.zoom / old;
|
||||
camera.offset = [camera.offset[0] - d.x * (k - 1.0), camera.offset[1] - d.y * (k - 1.0)];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if resp.dragged() {
|
||||
cam.fit = false;
|
||||
let d = resp.drag_delta();
|
||||
cam.offset = [cam.offset[0] + d.x, cam.offset[1] + d.y];
|
||||
if response.dragged() {
|
||||
camera.fit = false;
|
||||
let d = response.drag_delta();
|
||||
camera.offset = [camera.offset[0] + d.x, camera.offset[1] + d.y];
|
||||
}
|
||||
|
||||
let size = vec2(img.width() as f32, img.height() as f32) * cam.zoom;
|
||||
let center = rect.center() + vec2(cam.offset[0], cam.offset[1]);
|
||||
let size = vec2(image.width() as f32, image.height() as f32) * camera.zoom;
|
||||
let center = rect.center() + vec2(camera.offset[0], camera.offset[1]);
|
||||
let full = Rect::from_center_size(center, size * tiles);
|
||||
|
||||
// A checker behind transparent images
|
||||
if img.kind() == Kind::Color && app.session.view2d.channel == "rgba" {
|
||||
if image.kind() == Kind::Color && app.session.view2d.channel == "rgba" {
|
||||
let cell = 8.0;
|
||||
let vis = full.intersect(rect);
|
||||
let mut y = vis.top();
|
||||
let visible = full.intersect(rect);
|
||||
let mut y = visible.top();
|
||||
let mut row = 0;
|
||||
while y < vis.bottom() {
|
||||
let mut x = vis.left() + if row % 2 == 0 { 0.0 } else { cell };
|
||||
while x < vis.right() {
|
||||
p.rect_filled(Rect::from_min_size(pos2(x, y), vec2(cell, cell)).intersect(vis), 0.0, Color32::from_gray(0x55));
|
||||
while y < visible.bottom() {
|
||||
let mut x = visible.left() + if row % 2 == 0 { 0.0 } else { cell };
|
||||
while x < visible.right() {
|
||||
p.rect_filled(Rect::from_min_size(pos2(x, y), vec2(cell, cell)).intersect(visible), 0.0, Color32::from_gray(0x55));
|
||||
x += cell * 2.0;
|
||||
}
|
||||
y += cell;
|
||||
@@ -189,27 +196,35 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
}
|
||||
|
||||
if app.session.view2d.histogram {
|
||||
let single = img.is_gray() || app.session.view2d.channel != "rgba";
|
||||
let single = image.is_gray() || app.session.view2d.channel != "rgba";
|
||||
draw_histogram(&mut app.view2d, &p, rect, key, single);
|
||||
}
|
||||
|
||||
// Info line: size, format, zoom and the pixel under the pointer
|
||||
let info = Rect::from_min_size(pos2(rect.left(), rect.bottom()), vec2(rect.width(), 20.0));
|
||||
let bits = app.session.cooked.nodes.get(&id).map_or("16", |result| result.base.format.bits());
|
||||
let mut text = format!("{} x {} ({}, {}bpc) {:.0}%", img.width(), img.height(), if img.is_gray() { "L" } else { "RGBA" }, bits, cam.zoom * 100.0);
|
||||
if let Some(ptr) = resp.hover_pos() {
|
||||
let local = (ptr - (center - size * 0.5)) / cam.zoom;
|
||||
let mut text =
|
||||
format!("{} x {} ({}, {}bpc) {:.0}%", image.width(), image.height(), if image.is_gray() { "L" } else { "RGBA" }, bits, camera.zoom * 100.0);
|
||||
if let Some(ptr) = response.hover_pos() {
|
||||
let local = (ptr - (center - size * 0.5)) / camera.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() {
|
||||
text += &format!(" ({}, {}) {:.3}", x.rem_euclid(img.width() as i64), y.rem_euclid(img.height() as i64), v[0]);
|
||||
let v = image.get(x, y, true);
|
||||
if image.is_gray() {
|
||||
text += &format!(" ({}, {}) {:.3}", x.rem_euclid(image.width() as i64), y.rem_euclid(image.height() as i64), v[0]);
|
||||
} else {
|
||||
text +=
|
||||
&format!(" ({}, {}) {:.3} {:.3} {:.3} {:.3}", x.rem_euclid(img.width() as i64), y.rem_euclid(img.height() as i64), v[0], v[1], v[2], v[3]);
|
||||
text += &format!(
|
||||
" ({}, {}) {:.3} {:.3} {:.3} {:.3}",
|
||||
x.rem_euclid(image.width() as i64),
|
||||
y.rem_euclid(image.height() as i64),
|
||||
v[0],
|
||||
v[1],
|
||||
v[2],
|
||||
v[3]
|
||||
);
|
||||
}
|
||||
}
|
||||
ui.painter().rect_filled(info, 0.0, tk.panel);
|
||||
ui.painter().text(info.left_center() + vec2(6.0, 0.0), egui::Align2::LEFT_CENTER, text, egui::FontId::proportional(11.0), tk.text_dim);
|
||||
ui.painter().rect_filled(info, 0.0, theme.panel);
|
||||
ui.painter().text(info.left_center() + vec2(6.0, 0.0), egui::Align2::LEFT_CENTER, text, egui::FontId::proportional(11.0), theme.text_dim);
|
||||
}
|
||||
|
||||
/// The histogram card in the view's bottom-right corner, computed once per shown image.
|
||||
|
||||
@@ -48,19 +48,24 @@ fn painted(h: &Harness<'static, MaterialCraftApp>) -> Vec<String> {
|
||||
fn node_resolution_explains_the_preview_cap() {
|
||||
let (mut h, id) = harness(512, false);
|
||||
let img = h.state().session.cooked.image(id, 0).unwrap();
|
||||
|
||||
assert_eq!((img.width(), img.height()), (512, 512));
|
||||
assert_eq!(h.state().session.graph().unwrap().size, [10, 10]);
|
||||
assert!(painted(&h).iter().any(|t| t == "512x512 Preview"), "missing preview label: {:?}", painted(&h));
|
||||
|
||||
let rect = h.state().graph.rects.iter().find(|(n, _)| *n == id).unwrap().1;
|
||||
h.event(Event::PointerMoved(rect.center()));
|
||||
h.run_steps(90);
|
||||
let text = painted(&h).join("\n");
|
||||
|
||||
assert!(text.contains("Parent size: 1024 x 1024"), "{text}");
|
||||
assert!(text.contains("Preview limit: 512 px"), "{text}");
|
||||
assert!(text.contains("Edit > Preferences"), "{text}");
|
||||
assert!(text.contains("16bpc"), "format information lost: {text}");
|
||||
|
||||
let full = h.state().session.cook_full(0);
|
||||
let img = full.image(id, 0).unwrap();
|
||||
|
||||
assert_eq!((img.width(), img.height()), (1024, 1024));
|
||||
}
|
||||
|
||||
@@ -68,6 +73,7 @@ fn node_resolution_explains_the_preview_cap() {
|
||||
fn full_size_mode_retains_the_resolution_and_format() {
|
||||
let (h, id) = harness(0, false);
|
||||
let img = h.state().session.cooked.image(id, 0).unwrap();
|
||||
|
||||
assert_eq!((img.width(), img.height()), (1024, 1024));
|
||||
assert!(painted(&h).iter().any(|t| t == "1024x1024 - C16"), "{:?}", painted(&h));
|
||||
assert!(!painted(&h).iter().any(|t| t == "1024x1024 Preview"));
|
||||
|
||||
@@ -19,12 +19,15 @@ fn choose_4k(h: &mut Harness<'static, MaterialCraftApp>) {
|
||||
h.run();
|
||||
h.get_by_label("4096 px").click();
|
||||
h.run();
|
||||
|
||||
assert_eq!(h.state().session.preview_size, Some(4096));
|
||||
assert_eq!(h.state().ui.prefs.preview_size, 4096);
|
||||
|
||||
h.state_mut().session.cook();
|
||||
h.step();
|
||||
let app = h.state();
|
||||
let (_, image) = app.session.view2d_image().unwrap();
|
||||
|
||||
assert_eq!((image.width(), image.height()), (4096, 4096));
|
||||
assert!(app.session.material_maps().iter().all(|(_, image)| (image.width(), image.height()) == (4096, 4096)));
|
||||
assert!(!app.session.material_maps().is_empty());
|
||||
@@ -58,7 +61,8 @@ fn four_k_preview_refreshes_texture_after_size_change() {
|
||||
app(),
|
||||
);
|
||||
h.input_mut().max_texture_side = Some(4096);
|
||||
// The cooked key alone does not name the input size, so changing size must still refresh.
|
||||
|
||||
// The cooked key alone does not name the input size, so changing size must still refresh
|
||||
let node = h.state().session.view2d.node.unwrap();
|
||||
h.state_mut().session.preview_size = Some(4096);
|
||||
h.state_mut().session.cook();
|
||||
@@ -66,14 +70,17 @@ fn four_k_preview_refreshes_texture_after_size_change() {
|
||||
h.state_mut().ui.prefs.preview_size = 4096;
|
||||
h.step();
|
||||
let (_, image) = h.state().session.view2d_image().unwrap();
|
||||
|
||||
assert_eq!((image.width(), image.height()), (4096, 4096));
|
||||
assert_eq!(h.state().view2d.shown.as_ref().map(|(w, h, _)| (*w, *h)), Some((4096, 4096)));
|
||||
|
||||
h.state_mut().session.preview_size = Some(256);
|
||||
h.state_mut().session.cook();
|
||||
h.state_mut().session.cooked.nodes.get_mut(&node).unwrap().key = 0;
|
||||
h.state_mut().ui.prefs.preview_size = 256;
|
||||
h.step();
|
||||
let (_, image) = h.state().session.view2d_image().unwrap();
|
||||
|
||||
assert_eq!((image.width(), image.height()), (256, 256));
|
||||
assert_eq!(h.state().view2d.shown.as_ref().map(|(w, h, _)| (*w, *h)), Some((256, 256)));
|
||||
}
|
||||
|
||||
@@ -1299,6 +1299,7 @@ fn named_outputs_select_without_loading_and_open_on_double_click() {
|
||||
let query = By::new().role(egui::accesskit::Role::TreeItem).label("Base Color");
|
||||
let position = harness.get(query.clone()).rect().center();
|
||||
click_canvas(&mut harness, position);
|
||||
|
||||
assert_eq!(harness.state().session.selection, vec![materialcraft_engine::core::NodeId(source)]);
|
||||
assert_eq!(harness.state().session.view2d.node, Some(materialcraft_engine::core::NodeId(source)));
|
||||
assert!(!harness.state().graph.ports.iter().any(|port| port.node.0 == output && port.output));
|
||||
@@ -1313,12 +1314,16 @@ fn named_outputs_select_without_loading_and_open_on_double_click() {
|
||||
harness.step();
|
||||
}
|
||||
settle(&mut harness, 3);
|
||||
|
||||
assert_eq!(harness.state().session.view2d.node, Some(materialcraft_engine::core::NodeId(output)));
|
||||
assert_eq!(harness.state().session.selection, vec![materialcraft_engine::core::NodeId(output)]);
|
||||
assert!(harness.query_all(By::new().label("Identifier")).next().is_some());
|
||||
assert_eq!(serde_json::to_value(&harness.state().session.view3d).unwrap(), view3d);
|
||||
|
||||
let current = harness.state().session.material_maps().into_iter().map(|(name, image)| (name, image.shared_data().clone())).collect::<Vec<_>>();
|
||||
|
||||
assert_eq!(current, material);
|
||||
|
||||
save(&mut harness, &directory, "named-output-preview");
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,16 @@ use materialcraft_engine::core::{BaseParameter, NodeId};
|
||||
use materialcraft_ui_egui::{MaterialCraftApp, UiState};
|
||||
use serde_json::json;
|
||||
|
||||
fn wait_for_cook(harness: &mut egui_kittest::Harness<'static, MaterialCraftApp>) {
|
||||
// Cook errors can move Properties controls before a queued pointer click
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
|
||||
while (harness.state().cooker.busy() || harness.state().session.dirty) && std::time::Instant::now() < deadline {
|
||||
settle(harness, 1);
|
||||
}
|
||||
|
||||
assert!(!harness.state().cooker.busy() && !harness.state().session.dirty, "the parameter preview cook must complete");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires an offscreen GPU; run explicitly with --ignored"]
|
||||
fn parameter_functions_create_edit_reset_and_return_to_the_owner() {
|
||||
@@ -14,6 +24,7 @@ fn parameter_functions_create_edit_reset_and_return_to_the_owner() {
|
||||
let owner = NodeId(app.run("graph.node.add", json!({"def": "directional_blur"})).unwrap()["id"].as_u64().unwrap());
|
||||
let mut harness = harness(app, 1600.0, 1100.0);
|
||||
settle(&mut harness, 8);
|
||||
wait_for_cook(&mut harness);
|
||||
let button = |label| By::new().role(egui::accesskit::Role::Button).label(label);
|
||||
for parameter in BaseParameter::ALL {
|
||||
let label = format!("Parameter actions: {}", parameter.label());
|
||||
@@ -34,6 +45,7 @@ fn parameter_functions_create_edit_reset_and_return_to_the_owner() {
|
||||
save(&mut harness, &directory, "parameter-function-menu");
|
||||
harness.get(button("Empty function")).click();
|
||||
settle(&mut harness, 5);
|
||||
wait_for_cook(&mut harness);
|
||||
|
||||
assert!(harness.state().session.graph().unwrap().node(owner).unwrap().base.functions[&BaseParameter::OutputSize].nodes.is_empty());
|
||||
assert_eq!(harness.state().function_editor.as_ref().unwrap().node, Some(owner));
|
||||
@@ -68,12 +80,14 @@ fn parameter_functions_create_edit_reset_and_return_to_the_owner() {
|
||||
settle(&mut harness, 8);
|
||||
harness.get(button("Reset to default")).click();
|
||||
settle(&mut harness, 8);
|
||||
wait_for_cook(&mut harness);
|
||||
harness.get(button("Parameter actions: Output size")).click();
|
||||
settle(&mut harness, 8);
|
||||
save(&mut harness, &directory, "parameter-after-reset-menu");
|
||||
assert!(harness.query(button("Constant value")).is_some(), "the reset parameter menu must offer a constant");
|
||||
harness.get(button("Constant value")).click();
|
||||
settle(&mut harness, 4);
|
||||
wait_for_cook(&mut harness);
|
||||
|
||||
let function = &harness.state().session.graph().unwrap().node(owner).unwrap().base.functions[&BaseParameter::OutputSize];
|
||||
assert_eq!(function.nodes.len(), 1);
|
||||
@@ -93,6 +107,7 @@ fn parameter_functions_create_edit_reset_and_return_to_the_owner() {
|
||||
settle(&mut harness, 3);
|
||||
harness.get(button("Constant value")).click();
|
||||
settle(&mut harness, 4);
|
||||
wait_for_cook(&mut harness);
|
||||
assert!(harness.query(By::new().label("Expected output: Float")).is_some());
|
||||
assert!(harness.state().session.graph().unwrap().node(owner).unwrap().functions.contains_key("angle"));
|
||||
save(&mut harness, &directory, "parameter-specific-function");
|
||||
|
||||
@@ -155,6 +155,7 @@ mod tests {
|
||||
c("materialcraft-ui-egui", &[("materialcraft-automation", Normal, true), ("egui", Normal, false), ("wgpu", Normal, false)]),
|
||||
c("materialcraft", &[("eframe", Normal, false), ("materialcraft-ui-egui", Normal, true), ("winresource", Build, false)]),
|
||||
];
|
||||
|
||||
assert!(check(&g).is_empty(), "{:?}", check(&g));
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user