diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index 1f24557c94..e73dfbb58f 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -126,8 +126,9 @@ fn raster_of(s: &Session, name: &str) -> Result { #[derive(Clone)] pub(crate) struct Input { held: std::sync::Arc, - /// The layer's name and its file, for one read in place from a file on this computer. - file: Option<(String, String)>, + layer_name: String, + /// The local file, for a raster read in place. + file: Option, } impl Input { @@ -137,8 +138,8 @@ impl Input { let rl = context.map().layer_by_name(name).and_then(|l| Some((l, l.raster.as_ref()?))); let (l, rl) = rl.ok_or_else(|| format!("no raster layer '{name}'"))?; let held = rl.data.clone().ok_or_else(|| format!("no raster layer '{name}'"))?; - let file = rl.path.clone().filter(|_| rl.tiled).map(|path| (l.name.clone(), path)); - Ok(Input { held, file }) + let file = rl.path.clone().filter(|_| rl.tiled); + Ok(Input { held, layer_name: l.name.clone(), file }) } /// The raster the layer holds: for one read in place from a file, its overview, with the @@ -150,7 +151,7 @@ impl Input { /// The layer's name and its file, for a layer read in place from a file on this computer. #[cfg(not(target_arch = "wasm32"))] pub(crate) fn file(&self) -> Option<(&str, &str)> { - self.file.as_ref().map(|(name, path)| (name.as_str(), path.as_str())) + self.file.as_deref().map(|path| (self.layer_name.as_str(), path)) } /// The raster the work reads: within a run ([`reading_files`]), a layer read in place from a @@ -159,11 +160,11 @@ impl Input { /// any other layer, the raster the layer holds. pub(crate) fn read(&self) -> Result { #[cfg(not(target_arch = "wasm32"))] - if let Some((name, path)) = &self.file + if let Some((name, path)) = self.file() && RUN_READS.with(|r| r.borrow().is_some()) { let kept = RUN_READS.with(|r| { - r.borrow().as_ref().and_then(|read| read.iter().find(|k| k.path.as_ref() == Some(path)).and_then(|k| k.kept.clone())) + r.borrow().as_ref().and_then(|read| read.iter().find(|k| k.path.as_deref() == Some(path)).and_then(|k| k.kept.clone())) }); let (raster, count) = match kept { Some(k) => k, @@ -172,7 +173,7 @@ impl Input { let note = super::gp::ReadNote::of(name, &raster); RUN_READS.with(|r| { if let Some(read) = r.borrow_mut().as_mut() { - read.push(RunRead { path: Some(path.clone()), kept: Some((raster.clone(), count.clone())), note }); + read.push(RunRead { path: Some(path.to_owned()), kept: Some((raster.clone(), count.clone())), note }); } }); (raster, count) @@ -201,7 +202,7 @@ impl Input { /// other layer, give [`Input::read`]. pub(crate) fn read_part(&self, part: rustgis_data::raster::Part, share: usize) -> Result { #[cfg(not(target_arch = "wasm32"))] - if let Some((name, path)) = &self.file + if let Some((name, path)) = self.file() && RUN_READS.with(|r| r.borrow().is_some()) && let Some((read, count)) = super::gp::read_tiled_part(name, path, part, share, &self.held)? { @@ -1789,7 +1790,7 @@ fn raster_function(s: &mut Session, p: &Value) -> CmdResult { fn function_work(s: &Session, p: &Value) -> Result { let src = raster_of(s, ps(p, "layer").ok_or("layer is required")?)?; let target = resample_target(s, p)?; - let name = out_name(p, format!("{}_{}", src.held().name, ps(p, "function").unwrap_or("")))?; + let name = out_name(p, format!("{}_{}", src.layer_name, ps(p, "function").unwrap_or("")))?; let defaults = s.raster_defaults.clone(); let mut p = p.clone(); // Read here, on the command's thread, where an unreadable value is said (#1600); only a remap @@ -1984,60 +1985,58 @@ fn function_chain_work(s: &Session, p: &Value) -> Result { .enumerate() .map(|(i, st)| resample_target(s, st).map_err(|e| format!("step {} ({}): {e}", i + 1, func(st)))) .collect::>()?; - let named = Some(out_name(p, String::new())?).filter(|n| !n.is_empty()); + let names: Vec<_> = steps.iter().map(func).collect(); + let out = out_name(p, format!("{}_{}", src.layer_name, names.join("_")))?; let defaults = s.raster_defaults.clone(); // A file too large to read whole at its full size: a block at a time (#2865), with the cells // around each that its steps over a cell's neighbours read, one each; a chain that can't be // made so ([`super::in_blocks::chain_halo`]) reads the file as before. #[cfg(not(target_arch = "wasm32"))] - if let Some(halo) = super::in_blocks::chain_halo(&steps) { - let names: Vec = steps.iter().map(func).collect(); - let out = named.clone().unwrap_or_else(|| format!("{}_{}", src.held().name, names.join("_"))); - if let Some(blocks) = super::in_blocks::plan(s, &src, &out)? { - let last = steps.last().cloned().unwrap_or_default(); - let shape = function_shape(&last); - return Ok(Box::new(move || { - let met = std::cell::RefCell::new(BlockRemaps::default()); - let made = blocks.with_halo(halo).run_window( - |block, ground, core| { - let mut remaps = Remaps::default(); - let mut cur: Option = None; - for (i, st) in steps.iter().enumerate() { - let input = cur.as_ref().unwrap_or(block); - // Earlier outputs in the remaining halo feed later terrain steps. - let halo: usize = steps - .iter() - .skip(i + 1) - .filter_map(|st| ps(st, "function").and_then(super::in_blocks::function_halo)) - .map(|v| v as usize) - .sum(); - let kept = [ - core[0].saturating_sub(halo), - core[1].saturating_sub(halo), - core[2].saturating_add(halo).min(input.width as usize), - core[3].saturating_add(halo).min(input.height as usize), - ]; - let pixels = apply_function(input, st, None, &mut remaps, Some(ground), Some((kept, halo > 0))) - .map_err(|e| format!("step {} ({}): {e}", i + 1, func(st)))?; - cur = Some(derive_function(input, &input.name, st, pixels)?); - } - met.borrow_mut().add(remaps); - let cur = cur.ok_or("the chain made no raster")?; - Ok(cur.bands.into_iter().next().map(|b| b.data).unwrap_or_default()) - }, - shape, - )?; - let made = also(made, met.into_inner().met().then()); - Ok(if is_hillshade(&last) { hillshade_look(made, &defaults) } else { made }) - })); - } + if let Some(halo) = super::in_blocks::chain_halo(&steps) + && let Some(blocks) = super::in_blocks::plan(s, &src, &out)? + { + let last = steps.last().cloned().unwrap_or_default(); + let shape = function_shape(&last); + return Ok(Box::new(move || { + let met = std::cell::RefCell::new(BlockRemaps::default()); + let made = blocks.with_halo(halo).run_window( + |block, ground, core| { + let mut remaps = Remaps::default(); + let mut cur: Option = None; + for (i, st) in steps.iter().enumerate() { + let input = cur.as_ref().unwrap_or(block); + // Earlier outputs in the remaining halo feed later terrain steps. + let halo: usize = steps + .iter() + .skip(i + 1) + .filter_map(|st| ps(st, "function").and_then(super::in_blocks::function_halo)) + .map(|v| v as usize) + .sum(); + let kept = [ + core[0].saturating_sub(halo), + core[1].saturating_sub(halo), + core[2].saturating_add(halo).min(input.width as usize), + core[3].saturating_add(halo).min(input.height as usize), + ]; + let pixels = apply_function(input, st, None, &mut remaps, Some(ground), Some((kept, halo > 0))) + .map_err(|e| format!("step {} ({}): {e}", i + 1, func(st)))?; + cur = Some(derive_function(input, &input.name, st, pixels)?); + } + met.borrow_mut().add(remaps); + let cur = cur.ok_or("the chain made no raster")?; + Ok(cur.bands.into_iter().next().map(|b| b.data).unwrap_or_default()) + }, + shape, + )?; + let made = also(made, met.into_inner().met().then()); + Ok(if is_hillshade(&last) { hillshade_look(made, &defaults) } else { made }) + })); } Ok(Box::new(move || { let src = src.read()?; // Each step's output, the next step's input; the first step reads the raster itself, not // a copy of it. let mut cur: Option = None; - let mut names = Vec::new(); let mut remaps = Remaps::default(); for (i, (st, target)) in steps.iter().zip(&targets).enumerate() { let f = func(st); @@ -2048,10 +2047,9 @@ fn function_chain_work(s: &Session, p: &Value) -> Result { // Only a resample takes another raster's grid; otherwise the grid is the current one. let next = derive_function(target.as_deref().unwrap_or(input), &input.name, st, pixels)?; cur = Some(next); - names.push(f); } let mut cur = cur.ok_or("the chain made no raster")?; - cur.name = named.unwrap_or_else(|| format!("{}_{}", cur.name, names.join("_"))); + cur.name = out; // A chain that ends in a hillshade is drawn as one. let mut m = match steps.last() { Some(last) if is_hillshade(last) => made_hillshade(cur, &defaults)?, @@ -2154,8 +2152,8 @@ fn viewshed_work(s: &Session, p: &Value) -> Result { } Some(other) => return Err(format!("heights must be \"nearest\" or \"bilinear\", not {other}")), }; - let name = out_name(p, format!("{}_viewshed", dem.held().name))?; - let dem_name = dem.held().name.clone(); + let name = out_name(p, format!("{}_viewshed", dem.layer_name))?; + let dem_name = dem.layer_name.clone(); Ok(Box::new(move || { let dem = dem.read()?; let (cx, cy) = dem.cell_size_ground_m(); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 754f3119e2..64c8e87a80 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -20595,6 +20595,28 @@ fn remap_reports_empty_ranges_and_no_valid_cells() { assert_eq!(said, ["Apart: no cell is scored by every criterion, so the result has no cells with values"]); } +#[test] +fn raster_workflow_outputs_use_the_visible_layer_name() { + let mut s = world(); + s.run("layer.addDataBytes", &json!({"fileName": "exportImage.tif", "data": dem_b64()})).unwrap(); + s.run("layer.rename", &json!({"layer": "exportImage", "name": "MDT Bogotá 2025"})).unwrap(); + for (command, mut p, expected) in [ + ("analysis.viewshed", json!({"lon": 10.0055, "lat": 45.0395}), "MDT Bogotá 2025_viewshed"), + ("raster.function", json!({"function": "slope"}), "MDT Bogotá 2025_slope"), + ("raster.functionChain", json!({"steps": [{"function": "slope"}, {"function": "aspect"}]}), "MDT Bogotá 2025_slope_aspect"), + ] { + p["layer"] = json!("mdt Bogotá 2025"); + let mut run = |params: &Value| { + let result = s.run(command, params).unwrap(); + s.map().layer(result["layer"].as_u64().unwrap() as u32).unwrap().name.clone() + }; + assert_eq!(run(&p), expected, "{command}"); + let custom = format!("Custom {command}"); + p["name"] = json!(custom); + assert_eq!(run(&p), custom, "{command}"); + } +} + #[test] fn analysis_workflows_models_scripts_and_raster_functions() { let mut s = world();