diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 33b1a985..8ec51fb8 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -15,6 +15,7 @@ licensed and keep their license file next to them. | `assets/app-icon/texturecraft.icns` | App icon (engraved zebra), macOS (16-1024 px) | Project owner (ArtCraft team) | Original artwork drawn in ArtCraft for TextureCraft, rendered by `packaging/icons.sh` | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | | `assets/app-icon/hicolor/{16x16,24x24,32x32,48x48,64x64,128x128,256x256,512x512}/apps/ai.storyteller.texturecraft.png` | App icon (engraved zebra), hicolor theme PNGs | Project owner (ArtCraft team) | Original artwork drawn in ArtCraft for TextureCraft, rendered by `packaging/icons.sh` | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | | `assets/app-icon/hicolor/scalable/apps/ai.storyteller.texturecraft.svg` | App icon (engraved zebra), hicolor scalable (copy of `texturecraft-small.svg`) | Project owner (ArtCraft team) | Original artwork drawn in ArtCraft for TextureCraft, vectorised with craftrules `vectorize_tile.py` | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | +| `assets/app-icon/texturecraft-nightly{,-1024}.png`, `assets/app-icon/texturecraft-nightly.{icns,ico}`, `assets/app-icon/nightly/{16,24,32,48,64,128,256,512}.png` | Nightly app icons (engraved zebra on deep copper) | Project owner (ArtCraft team) | Project-owned stable icon renders, with the background recolored by `packaging/nightly-icons.py` ([provenance and hashes](assets/app-icon/nightly-provenance.json)) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | | `assets/app-icon/LICENSE.txt`, `assets/app-icon/README.md` | App icon licence and notes | TextureCraft contributors | original | MIT OR Apache-2.0 | | `docs/images/texturecraft-workspace.png` | README screenshot: the TextureCraft workspace (a 1970s portable TV in aged cream plastic with a crayon doodle) | TextureCraft contributors | original screenshot of TextureCraft | MIT OR Apache-2.0 | | `docs/images/texturecraft-bake.png` | README screenshot: bake mode | TextureCraft contributors | original screenshot of TextureCraft | MIT OR Apache-2.0 | @@ -26,7 +27,7 @@ licensed and keep their license file next to them. | `assets/hdr/studio_small_09_512.hdr` | Studio Small 09: a small photo studio with octaboxes on a white infinity cyc, equirect HDR reduced to 512×256 (2×2 box filter, Radiance RLE); lights the Properties panel's material orbs | Sergej Majboroda (Poly Haven) | [Poly Haven release](https://polyhaven.com/a/studio_small_09), [1K Radiance HDR](https://dl.polyhaven.org/file/ph-assets/HDRIs/hdr/1k/studio_small_09_1k.hdr) (MD5 `d5d7eb9d26d341d6aa4d11c1a54fd97c`) | [CC0 1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/) | | `docs/brand/artcraft-*.svg`, `docs/brand/artcraft-*.png` | ArtCraft logo and mark | ArtCraft Team | storytold/craftrules `assets/brand/` | ArtCraft brand terms, not open source ([`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt)) | | `crates/formats/src/mesh_import/usd/fixtures/crafted-references.usdc` | Synthetic USDC class/reference/time-sample acceptance fixture | ArtCraft Team and craft-libs contributors | [Pinned generator and provenance](crates/formats/src/mesh_import/usd/fixtures/README.md) | MIT (`crates/formats/src/mesh_import/usd/fixtures/LICENSE-MIT`) | -| `crates/formats/src/presets.rs` | Subsurface Profile, glTF Specular Glossiness, Redshift Standard Material, Roblox SurfaceAppearance and Sketchfab Metalness export presets | TextureCraft contributors, including Aalzard's Roblox and Sketchfab contributions | TextureCraft map definitions based on the published specifications linked beside each preset | MIT OR Apache-2.0 | +| `crates/formats/src/export/linear_gray.icc` | TextureCraft Linear Gray (D50) | TextureCraft contributors | Original ICC v2.1 monochrome display profile generated with Little CMS 2.14 from D50 and gamma 1.0, with a fixed creation date of 2026-01-01 | MIT OR Apache-2.0 | ## Third-party assets compiled into the binary diff --git a/Cargo.lock b/Cargo.lock index c0494fe8..be50cc5f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5181,6 +5181,7 @@ dependencies = [ "schemars", "serde", "serde_json", + "tempfile", "texturecraft-engine", "texturecraft-formats", "texturecraft-render", @@ -5284,7 +5285,6 @@ dependencies = [ "j2k", "j2k-core", "png", - "quick-xml 0.41.0", "rayon", "serde", "serde_json", diff --git a/Cargo.toml b/Cargo.toml index d2a340de..2f7b4610 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -54,7 +54,6 @@ rfd = "0.17" zip = { version = "9", default-features = false, features = ["deflate"] } gltf = { version = "1.4", default-features = false, features = ["import", "utils", "names", "KHR_materials_emissive_strength"] } flate2 = "1" -quick-xml = "0.41" mikktspace = { version = "0.3", default-features = false, features = ["glam"] } rmcp = { version = "3.5", default-features = false, features = ["server", "macros", "transport-io"] } tokio = { version = "1", features = ["rt-multi-thread", "macros", "io-std", "sync", "net", "io-util", "time"] } diff --git a/crates/automation/Cargo.toml b/crates/automation/Cargo.toml index a0c3c0ad..eb28b995 100644 --- a/crates/automation/Cargo.toml +++ b/crates/automation/Cargo.toml @@ -28,4 +28,5 @@ getrandom = { workspace = true } rustix = { workspace = true } [dev-dependencies] +tempfile = "3" rmcp = { workspace = true, features = ["client"] } diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rs index 6f86119e..3a0f5dcc 100644 --- a/crates/automation/src/headless.rs +++ b/crates/automation/src/headless.rs @@ -289,25 +289,50 @@ impl Headless { } /// Export textures to `dir` (`file.exportTextures` params: preset, ts, format, padding, size…). - pub fn export(&mut self, p: &Value) -> Result { + pub fn export(&mut self, params: &Value) -> Result { + use texturecraft_engine::shader_parameters::{shader_parameters_param, shader_parameters_sidecar}; + self.require_project()?; - let dir = p.get("dir").and_then(Value::as_str).filter(|d| !d.is_empty()).ok_or_else(|| bad("`dir` is required"))?; - let opts = file_cmds::export_options(&self.session, p, "textures.export")?; - let n = self.session.set_count(); - let sets: Vec = match p.get("ts") { - None | Some(Value::Null) => (0..n).collect(), - Some(Value::String(a)) if a == "all" => (0..n).collect(), - Some(v) => vec![v.as_u64().and_then(|t| usize::try_from(t).ok()).filter(|t| *t < n).ok_or_else(|| bad(format!("invalid `ts` {v}")))?], + let dir = params.get("dir").and_then(Value::as_str).filter(|dir| !dir.is_empty()).ok_or_else(|| bad("`dir` is required"))?; + let options = file_cmds::export_options(&self.session, params, "textures.export")?; + let set_count = self.session.set_count(); + let sets: Vec = match params.get("ts") { + None | Some(Value::Null) => (0..set_count).collect(), + Some(Value::String(selection)) if selection == "all" => (0..set_count).collect(), + Some(value) => vec![ + value + .as_u64() + .and_then(|index| usize::try_from(index).ok()) + .filter(|index| *index < set_count) + .ok_or_else(|| bad(format!("invalid `ts` {value}")))?, + ], }; - let files = self.session.export_files(&sets, &opts)?; + let shader_sets = shader_parameters_param(&self.session.doc.project, params, &sets, "textures.export")?; + + let files = self.session.export_files(&sets, &options)?; + let sidecar = shader_sets.map(|sets| shader_parameters_sidecar(&self.session.doc.project, &sets, &files)); self.create_dir_all(dir)?; let mut written = Vec::new(); - for f in &files { - let path = join(dir, &f.name); - self.write(&path, &f.bytes)?; + let mut warnings = Vec::new(); + for file in files { + let path = join(dir, &file.name); + self.write(&path, &file.bytes)?; written.push(path); + warnings.extend(file.warnings); } - let warnings: Vec<&String> = files.iter().flat_map(|f| &f.warnings).collect(); + + if let Some(sidecar) = sidecar { + let result = sidecar.and_then(|file| { + let path = join(dir, &file.name); + self.write(&path, &file.bytes).map_err(|error| error.to_string())?; + Ok(path) + }); + match result { + Ok(path) => written.push(path), + Err(error) => warnings.push(format!("The shader settings file was not written: {error}")), + } + } + Ok(json!({ "files": written, "warnings": warnings })) } diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs index 0ce54f55..886416a9 100644 --- a/crates/automation/src/server.rs +++ b/crates/automation/src/server.rs @@ -174,6 +174,9 @@ pub struct ExportParams { /// Settings for individual maps in the selected template. #[serde(default, skip_serializing_if = "Option::is_none")] pub maps: Option>, + /// Write shader settings for the exported sets (true) or the specified texture set indexes. + #[serde(default, rename = "shaderParameters", skip_serializing_if = "Option::is_none")] + pub shader_parameters: Option, } #[derive(Debug, Default, Deserialize, Serialize, JsonSchema)] diff --git a/crates/automation/src/server/export_map_params.rs b/crates/automation/src/server/export_map_params.rs index b19aa8dd..7acffc96 100644 --- a/crates/automation/src/server/export_map_params.rs +++ b/crates/automation/src/server/export_map_params.rs @@ -19,4 +19,7 @@ pub struct ExportMapParams { /// Override dithering for this map's 8-bit outputs. #[serde(default, skip_serializing_if = "Option::is_none")] pub dithering: Option, + /// Side length in pixels for this map, overriding the export size. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub size: Option, } diff --git a/crates/automation/tests/agent_tasks.rs b/crates/automation/tests/agent_tasks.rs index 93e59d23..4058e1c1 100644 --- a/crates/automation/tests/agent_tasks.rs +++ b/crates/automation/tests/agent_tasks.rs @@ -88,14 +88,15 @@ async fn inspect(c: &Conn) -> Value { #[tokio::test(flavor = "multi_thread")] async fn textures_export_accepts_per_map_settings() { - let dir = tmp("map-options"); - let (client, server) = connect(workspace(&dir)).await; + let temp = tempfile::tempdir().unwrap(); + let dir = temp.path(); + let (client, server) = connect(workspace(dir)).await; let result = tool( &client, "textures_export", json!({"dir": "textures", "preset": "glTF PBR Metal Roughness", "maps": [ - {"map": 0, "format": "pgm", "bitDepth": 16}, + {"map": 0, "format": "pgm", "bitDepth": 16, "size": 256}, {"map": 1, "enabled": false} ]}), ) @@ -104,9 +105,42 @@ async fn textures_export_accepts_per_map_settings() { let files = result["files"].as_array().unwrap(); assert_eq!(files.len(), 2, "{result}"); let graymap = files.iter().filter_map(Value::as_str).find(|path| path.ends_with(".pgm")).unwrap(); - assert!(std::fs::read(dir.join(graymap)).unwrap().starts_with(b"P5\n128 128\n65535\n")); + assert!(std::fs::read(dir.join(graymap)).unwrap().starts_with(b"P5\n256 256\n65535\n")); + let inherited = files.iter().filter_map(Value::as_str).find(|path| path.ends_with(".png")).unwrap(); + assert_eq!(image::image_dimensions(dir.join(inherited)).unwrap(), (128, 128)); + + shutdown(client, server).await; +} + +#[tokio::test(flavor = "multi_thread")] +async fn textures_export_reports_the_shader_sidecar_and_write_failures() { + let temp = tempfile::tempdir().unwrap(); + let dir = temp.path(); + let (client, server) = connect(workspace(dir)).await; + let params = json!({"dir": "textures", "shaderParameters": [0]}); + + let result = tool(&client, "textures_export", params.clone()).await; + + let files = result["files"].as_array().unwrap(); + let sidecar = files.iter().filter_map(Value::as_str).find(|name| name.ends_with("_shaders.json")).expect("shader settings file"); + let path = dir.join(sidecar); + let settings: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + assert_eq!(settings["shaders"][0]["textureSets"].as_array().unwrap().len(), 1); + assert!(settings["shaders"][0]["model"].is_string()); + + std::fs::remove_file(&path).unwrap(); + std::fs::create_dir(&path).unwrap(); + let result = tool(&client, "textures_export", params).await; + + assert!(result["warnings"].as_array().unwrap().iter().any(|warning| warning.as_str().is_some_and(|text| text.contains("shader settings file")))); + assert!(result["files"].as_array().unwrap().iter().any(|file| file.as_str().is_some_and(|name| name.ends_with(".png")))); + + let error = tool_err(&client, "textures_export", json!({"dir": "invalid", "shaderParameters": [99]})).await; + + assert!(error.contains("shaderParameters")); + assert!(!dir.join("invalid").exists()); + shutdown(client, server).await; - std::fs::remove_dir_all(dir).unwrap(); } fn top(s: &Value) -> &Value { diff --git a/crates/bake/src/bake_passes.rs b/crates/bake/src/bake_passes.rs new file mode 100644 index 00000000..eb7d5846 --- /dev/null +++ b/crates/bake/src/bake_passes.rs @@ -0,0 +1,72 @@ +use crate::cage::RayFrame; +use crate::map::BakeContext; +use crate::tracing::{CpuTracer, Tracer}; +use crate::{BakeError, BakeOutput, BakeRequest, MeshExtent, Progress}; +use std::sync::atomic::Ordering::Relaxed; +use texturecraft_core::{BakeSettings, BakedMap}; + +/// Map passes over one immutable request share the fitted cage and prepared skew. +pub struct BakePasses<'a> { + request: BakeRequest<'a>, + frame: Option<(MeshExtent, RayFrame<'a>)>, +} + +impl<'a> BakePasses<'a> { + pub fn new(request: BakeRequest<'a>) -> Self { + Self { request, frame: None } + } + + /// Bake one selected map, including the CPU fallback used by a normal bake. + pub fn bake_map( + &mut self, + map: BakedMap, + progress: &Progress, + excluded_tiles: &[(u32, u32)], + tracer: Option<&dyn Tracer>, + ) -> Result { + let mut settings = self.request.settings.clone(); + settings.maps.select([map]); + self.run(&settings, progress, excluded_tiles, tracer, super::STRIP_TEXELS) + } + + pub(super) fn run( + &mut self, + settings: &BakeSettings, + progress: &Progress, + excluded_tiles: &[(u32, u32)], + tracer: Option<&dyn Tracer>, + strip_texels: usize, + ) -> Result { + if progress.cancel.load(Relaxed) { + return Err(BakeError::Cancelled); + } + + let request = BakeRequest { settings, ..self.request }; + super::validate(&request)?; + if excluded_tiles.iter().any(|(column, row)| *column >= request.tiles.0 || *row >= request.tiles.1) { + return Err(BakeError::Invalid("excluded UV tile lies outside the bake atlas".into())); + } + + // Validate each pass separately so earlier maps can finish before a later map fails + let (extent, frame) = match &mut self.frame { + Some(geometry) => geometry, + None => { + let extent = MeshExtent::of(request.mesh)?; + self.frame.insert((extent, RayFrame::new(&self.request, extent)?)) + } + }; + let context = BakeContext::with_frame(&request, *extent, frame); + let bake = |tracer: &dyn Tracer| super::bake_prepared(&request, &context, progress, strip_texels, tracer, excluded_tiles); + match tracer { + Some(tracer) => match bake(tracer) { + Err(BakeError::Tracer(error)) => { + let mut output = bake(&CpuTracer)?; + output.tracer = format!("CPU ({} unavailable: {error})", tracer.name()); + Ok(output) + } + result => result, + }, + None => bake(&CpuTracer), + } + } +} diff --git a/crates/bake/src/cage.rs b/crates/bake/src/cage.rs index d2c7d7f3..d2c8a592 100644 --- a/crates/bake/src/cage.rs +++ b/crates/bake/src/cage.rs @@ -1,7 +1,9 @@ //! Where the bake's transfer rays start, shared by the bake and the cage the 3D view draws mod cage_shell; +mod fitted_cage; mod high_poly_reach; +mod name_keys; mod ray_frame; mod ray_start; mod vertex_reach; @@ -9,6 +11,7 @@ mod vertex_reach; #[cfg(test)] pub(crate) use cage_shell::CORNERS; pub use cage_shell::CageShell; +pub(crate) use fitted_cage::FittedCage; pub use high_poly_reach::HighPolyReach; pub(crate) use ray_frame::RayFrame; pub use ray_start::RayStart; diff --git a/crates/bake/src/cage/fitted_cage.rs b/crates/bake/src/cage/fitted_cage.rs new file mode 100644 index 00000000..079d94b0 --- /dev/null +++ b/crates/bake/src/cage/fitted_cage.rs @@ -0,0 +1,231 @@ +use super::name_keys::NameKeys; +use crate::map::interpolate; +use crate::{BakeRequest, HighPoly, MeshExtent}; +use rayon::prelude::*; +use std::borrow::Cow; +use std::collections::{HashMap, VecDeque}; +use texturecraft_geom::Mesh; +use texturecraft_geom::glam::Vec3; + +/// How much farther than the high poly the cage reaches, as a fraction of the fitted distance: the fit reads both meshes at their vertices only. Tuned with [`MARGIN_PER_DIAGONAL`] on two production meshes: the tightest pair whose rays miss no more texels than the default distances do +const MARGIN_PER_DISTANCE: f32 = 0.5; + +/// The least the cage reaches each way, as a fraction of the mesh diagonal, so a high poly lying on the low poly is still inside +const MARGIN_PER_DIAGONAL: f32 = 4e-3; + +/// How many times farther than the nearest high-poly point a low-poly vertex's ray may find the high poly: beyond it (a surface more than about 75 degrees off the ray) the ray has left the vertex's own part +const MAX_RAY_PER_NEAREST_DISTANCE: f32 = 4.0; + +/// Bound temporary high-vertex projections while giving Rayon thousands of independent queries per batch +const PROJECTION_BATCH_VERTICES: usize = 8192; + +/// The automatic cage: how far the transfer rays start in front of each low-poly vertex and how far they run behind it, fitted to the high poly +pub(crate) struct FittedCage { + /// (front, rear) in world units per low-poly vertex; `None` on parts no high poly is near + distances: Vec>, +} + +impl FittedCage { + /// Fit the cage of `request`'s low poly around `high` along `ray_normals` (where parts welded back to back cancelled a vertex's normal out, along its own): each low-poly vertex reaches the high poly straight in front of or behind it, and each high-poly vertex pushes the corners of its nearest low-poly triangle out (or in) to its height. Vertices neither finds take their neighbours' distances; a part the high poly reaches nowhere gets none + pub(crate) fn new(request: &BakeRequest, high: HighPoly, welded_indices: &[u32], ray_normals: &[Vec3], extent: MeshExtent) -> FittedCage { + let low = request.mesh; + let keys = NameKeys::of(request, high); + let welded_indices = welded_within_groups(welded_indices, &keys.low_vertices); + let welded = |vertex: usize| welded_indices.get(vertex).copied().unwrap_or(0) as usize; + let welded_count = welded_indices.iter().max().map_or(0, |last| *last as usize + 1); + + let fitting_normals = fitting_normals(low, ray_normals); + let mut reach: Vec> = vec![None; welded_count]; + let mut widen = |vertex: usize, height: f32| { + if let Some(distances) = reach.get_mut(welded(vertex)) { + let (front, rear) = distances.unwrap_or((0.0, 0.0)); + *distances = Some((front.max(height), rear.max(-height))); + } + }; + + for (vertex, height) in heights_at_low_vertices(low, high, &fitting_normals, &keys, extent.diagonal).into_iter().enumerate() { + if let Some(height) = height { + widen(vertex, height); + } + } + let mut projected = Vec::new(); + for (batch, positions) in high.mesh.positions.chunks(PROJECTION_BATCH_VERTICES).enumerate() { + let first = batch * PROJECTION_BATCH_VERTICES; + positions + .par_iter() + .enumerate() + .map(|(index, &position)| project_high_vertex(request, &fitting_normals, &keys, first + index, position)) + .collect_into_vec(&mut projected); + + for (triangle, height) in projected.drain(..).flatten() { + for corner in low.tri(triangle).into_iter().flatten() { + widen(corner, height); + } + } + } + drop(projected); + + spread_to_neighbours(&mut reach, low.indices.as_chunks::<3>().0.iter().map(|corners| corners.map(|corner| welded(corner as usize)))); + + let floor = MARGIN_PER_DIAGONAL * extent.diagonal; + let padded = |distance: f32| distance * (1.0 + MARGIN_PER_DISTANCE) + floor; + let distances = + (0..low.positions.len()).map(|vertex| reach.get(welded(vertex)).copied().flatten().map(|(front, rear)| (padded(front), padded(rear)))).collect(); + + FittedCage { distances } + } + + /// The (front, rear) distances at `barycentric` of triangle `triangle` of the low poly `low` the cage was fitted to; `None` where the high poly reaches no corner + pub(crate) fn distances(&self, low: &Mesh, triangle: u32, barycentric: [f32; 2]) -> Option<(f32, f32)> { + let corners = low.tri(triangle as usize)?; + let [first, second, third] = [0, 1, 2].map(|corner| self.distances.get(corners[corner]).copied().flatten()); + let ((first_front, first_rear), (second_front, second_rear), (third_front, third_rear)) = (first?, second?, third?); + let [second_weight, third_weight] = barycentric; + let first_weight = 1.0 - second_weight - third_weight; + + Some(( + first_front * first_weight + second_front * second_weight + third_front * third_weight, + first_rear * first_weight + second_rear * second_weight + third_rear * third_weight, + )) + } +} + +/// `welded_indices` with the vertices of different mesh-name groups (`vertex_keys`, empty when names don't matter) kept apart, so a group's distances come only from its own high poly and never spread into another group +fn welded_within_groups<'a>(welded_indices: &'a [u32], vertex_keys: &[u32]) -> Cow<'a, [u32]> { + if vertex_keys.is_empty() { + return Cow::Borrowed(welded_indices); + } + + let mut indices: HashMap<(u32, Option), u32> = HashMap::new(); + welded_indices + .iter() + .enumerate() + .map(|(vertex, &welded)| { + let next = indices.len() as u32; + *indices.entry((welded, vertex_keys.get(vertex).copied())).or_insert(next) + }) + .collect() +} + +/// `ray_normals`, except where parts welded back to back cancelled a vertex's normal out: there, the vertex's own normal, the direction its transfer rays fall back to +fn fitting_normals<'a>(low: &Mesh, ray_normals: &'a [Vec3]) -> Cow<'a, [Vec3]> { + if !ray_normals.contains(&Vec3::ZERO) { + return Cow::Borrowed(ray_normals); + } + + ray_normals + .iter() + .enumerate() + .map(|(vertex, &welded_normal)| { + if welded_normal != Vec3::ZERO { + return welded_normal; + } + + low.normals.get(vertex).and_then(|normal| normal.try_normalize()).unwrap_or(welded_normal) + }) + .collect() +} + +/// Per low-poly vertex, how far along its ray normal the high-poly surface in front of it (positive) or behind it (negative) is. A ray that only finds a surface much farther than the nearest high-poly point (within `max_distance`) found another part, so the vertex takes that nearest point's height instead +fn heights_at_low_vertices(low: &Mesh, high: HighPoly, ray_normals: &[Vec3], keys: &NameKeys, max_distance: f32) -> Vec> { + low.positions + .par_iter() + .zip(ray_normals) + .enumerate() + .map(|(vertex, (&position, &up))| { + let low_key = keys.low_vertices.get(vertex); + let rays_reach = |triangle: u32| NameKeys::matches(low_key, keys.high_triangles.get(triangle as usize)); + let nearest = high.bvh.nearest(position, max_distance, &rays_reach)?; + let nearest_position = interpolate(high.mesh, &high.mesh.positions, nearest.tri, [nearest.u, nearest.v])?; + let ray_limit = nearest.t * MAX_RAY_PER_NEAREST_DISTANCE + MARGIN_PER_DIAGONAL * max_distance; + let distance = |direction: Vec3| high.bvh.closest_filtered(position, direction, ray_limit, &rays_reach).map(|hit| hit.t); + + Some(match (distance(up), distance(-up)) { + (Some(front), Some(rear)) if front <= rear => front, + (Some(front), None) => front, + (_, Some(rear)) => -rear, + (None, None) => (nearest_position - position).dot(up), + }) + }) + .collect() +} + +/// The nearest matching low-poly triangle and signed height of one high-poly vertex +fn project_high_vertex(request: &BakeRequest, ray_normals: &[Vec3], keys: &NameKeys, vertex: usize, position: Vec3) -> Option<(usize, f32)> { + let low = request.mesh; + let high_key = keys.high_vertices.get(vertex); + let rays_reach = |triangle: u32| NameKeys::matches(keys.low_triangles.get(triangle as usize), high_key); + let nearest = request.bvh.nearest(position, f32::INFINITY, &rays_reach)?; + let barycentric = [nearest.u, nearest.v]; + let low_position = interpolate(low, &low.positions, nearest.tri, barycentric)?; + let up = interpolate(low, ray_normals, nearest.tri, barycentric)?.try_normalize()?; + + Some((nearest.tri as usize, (position - low_position).dot(up))) +} + +/// Give each vertex without distances the largest of its nearest fitted neighbours', walking outward along the edges of `triangles` +fn spread_to_neighbours(reach: &mut [Option<(f32, f32)>], triangles: impl Iterator) { + // Only unfitted vertices adjacent to a fitted region can gain distances + if reach.iter().all(Option::is_some) || reach.iter().all(Option::is_none) { + return; + } + + let mut neighbours = vec![Vec::new(); reach.len()]; + for corners in triangles { + for (corner, next) in [(0, 1), (1, 2), (2, 0)] { + if let (true, Some(list)) = (corners[next] < reach.len(), neighbours.get_mut(corners[corner])) { + list.push(corners[next]); + } + if let (true, Some(list)) = (corners[corner] < reach.len(), neighbours.get_mut(corners[next])) { + list.push(corners[corner]); + } + } + } + + // Propagate distances from the preceding breadth-first layer + let mut steps: Vec> = reach.iter().map(|distances| distances.map(|_| 0)).collect(); + let mut queue: VecDeque = (0..reach.len()).filter(|vertex| reach[*vertex].is_some()).collect(); + while let Some(vertex) = queue.pop_front() { + let (Some((front, rear)), Some(step)) = (reach[vertex], steps[vertex]) else { continue }; + + for &neighbour in &neighbours[vertex] { + match steps[neighbour] { + None => { + steps[neighbour] = Some(step + 1); + reach[neighbour] = Some((front, rear)); + queue.push_back(neighbour); + } + Some(neighbour_step) if neighbour_step == step + 1 => { + let (neighbour_front, neighbour_rear) = reach[neighbour].unwrap_or((0.0, 0.0)); + reach[neighbour] = Some((neighbour_front.max(front), neighbour_rear.max(rear))); + } + Some(_) => {} + } + } + } +} + +#[cfg(test)] +mod tests { + use super::{spread_to_neighbours, welded_within_groups}; + + #[test] + fn coincident_vertices_of_different_name_groups_are_not_welded() { + // The coincident pairs span different mesh-name groups + assert_eq!(welded_within_groups(&[0, 0, 1, 1], &[5, 7, 7, 5]).as_ref(), [0, 1, 2, 3]); + assert_eq!(welded_within_groups(&[0, 0, 1, 1], &[5, 5, 7, 7]).as_ref(), [0, 0, 1, 1], "same group: still welded"); + assert_eq!(welded_within_groups(&[0, 0, 1], &[]).as_ref(), [0, 0, 1], "without name matching nothing changes"); + } + + #[test] + fn unfitted_vertices_take_the_largest_distances_of_their_nearest_fitted_neighbours() { + // A strip of triangles 0-1-2, 1-2-3, 2-3-4: vertices 0 and 4 are fitted + let mut reach = vec![Some((1.0, 0.5)), None, None, None, Some((3.0, 0.25))]; + + spread_to_neighbours(&mut reach, [[0, 1, 2], [1, 2, 3], [2, 3, 4]].into_iter()); + + assert_eq!(reach[1], Some((1.0, 0.5)), "one step from vertex 0 only"); + assert_eq!(reach[3], Some((3.0, 0.25)), "one step from vertex 4 only"); + assert_eq!(reach[2], Some((3.0, 0.5)), "one step from both: the larger of each"); + } +} diff --git a/crates/bake/src/cage/high_poly_reach.rs b/crates/bake/src/cage/high_poly_reach.rs index 2f461343..b227ca06 100644 --- a/crates/bake/src/cage/high_poly_reach.rs +++ b/crates/bake/src/cage/high_poly_reach.rs @@ -75,7 +75,7 @@ impl HighPolyReach { } /// Each vertex's mesh-name key, from the first triangle that uses it -fn vertex_keys(mesh: &Mesh, triangle_keys: &[u32]) -> Vec { +pub(super) fn vertex_keys(mesh: &Mesh, triangle_keys: &[u32]) -> Vec { let mut keys = vec![ANY; mesh.positions.len()]; for (corners, &triangle_key) in mesh.indices.as_chunks::<3>().0.iter().zip(triangle_keys) { for &corner in corners { diff --git a/crates/bake/src/cage/name_keys.rs b/crates/bake/src/cage/name_keys.rs new file mode 100644 index 00000000..077cd826 --- /dev/null +++ b/crates/bake/src/cage/name_keys.rs @@ -0,0 +1,38 @@ +use super::high_poly_reach::vertex_keys; +use crate::map::transfer_keys; +use crate::tracing::ANY; +use crate::{BakeRequest, HighPoly}; +use texturecraft_core::MeshMatchMode; + +/// The mesh-name keys of a bake's low and high poly, per triangle and per vertex; all empty when every ray may hit every part +#[derive(Default)] +pub(super) struct NameKeys { + pub(super) low_triangles: Vec, + pub(super) low_vertices: Vec, + pub(super) high_triangles: Vec, + pub(super) high_vertices: Vec, +} + +impl NameKeys { + /// The keys `request` bakes with against `high`: filled only when it matches by mesh name + pub(super) fn of(request: &BakeRequest, high: HighPoly) -> NameKeys { + match request.settings.high_poly.match_mode { + MeshMatchMode::Always => NameKeys::default(), + MeshMatchMode::ByMeshName => { + let (low_triangles, high_triangles) = transfer_keys(request); + NameKeys { + low_vertices: vertex_keys(request.mesh, &low_triangles), + high_vertices: vertex_keys(high.mesh, &high_triangles), + low_triangles, + high_triangles, + } + } + } + } + + /// Whether a ray from the low-poly part keyed `low_key` may hit the high-poly part keyed `high_key`; a missing key is a part any ray may hit + pub(super) fn matches(low_key: Option<&u32>, high_key: Option<&u32>) -> bool { + let low_key = low_key.copied().unwrap_or(ANY); + low_key == ANY || low_key == high_key.copied().unwrap_or(ANY) + } +} diff --git a/crates/bake/src/cage/ray_frame.rs b/crates/bake/src/cage/ray_frame.rs index e8692cf2..590e52e1 100644 --- a/crates/bake/src/cage/ray_frame.rs +++ b/crates/bake/src/cage/ray_frame.rs @@ -1,4 +1,4 @@ -use super::RayStart; +use super::{FittedCage, RayStart}; use crate::MeshExtent; use crate::map::{interpolate, welded}; use crate::skew::PreparedSkew; @@ -7,11 +7,12 @@ use texturecraft_core::CageType; use texturecraft_geom::glam::Vec3; use texturecraft_geom::{Mesh, Surface}; -/// What decides where transfer rays start: the cage mesh or the averaged normals, skew and painted cage amount +/// What decides where transfer rays start: the cage mesh, the automatic cage's fitted distances, or the averaged normals, skew and painted cage amount pub(crate) struct RayFrame<'a> { mesh: &'a Mesh, ray_normals: Vec, cage: Option<&'a Mesh>, + fitted: Option, skew: Option>, cage_paint: Option<&'a BakePaintMap>, /// Cage-file offsets this short count as none: the ray starts from the distance-based cage instead @@ -23,18 +24,24 @@ pub(crate) struct RayFrame<'a> { impl<'a> RayFrame<'a> { pub(crate) fn new(request: &BakeRequest<'a>, extent: MeshExtent) -> Result, BakeError> { let settings = request.settings; - let ray_normals = match settings.cage.average_normals && request.high.is_some() { + + // The automatic cage is one closed shell, so its rays always follow the averaged normals + let automatic_high = request.high.filter(|_| settings.cage.kind == CageType::Automatic); + let (ray_normals, fitted) = match (settings.cage.average_normals || automatic_high.is_some()) && request.high.is_some() { true => { let (welded_indices, _, normals) = welded(request.mesh, extent.diagonal); - welded_indices.iter().map(|index| normals.get(*index as usize).copied().unwrap_or(Vec3::Y)).collect() + let ray_normals: Vec = welded_indices.iter().map(|index| normals.get(*index as usize).copied().unwrap_or(Vec3::Y)).collect(); + let fitted = automatic_high.map(|high| FittedCage::new(request, high, &welded_indices, &ray_normals, extent)); + (ray_normals, fitted) } - false => Vec::new(), + false => (Vec::new(), None), }; Ok(RayFrame { mesh: request.mesh, ray_normals, cage: if settings.cage.kind == CageType::CustomFile { request.cage } else { None }, + fitted, skew: request.skew.map(|skew_map| PreparedSkew::new(skew_map, request.mesh, extent.scale, settings.skew)).transpose()?, cage_paint: request.cage_paint, ray_epsilon: extent.ray_epsilon(), @@ -54,6 +61,11 @@ impl<'a> RayFrame<'a> { } let averaged_normal = interpolate(self.mesh, &self.ray_normals, surface.tri, barycentric).and_then(Vec3::try_normalize).unwrap_or(surface.nrm); + let fitted_distances = self.fitted.as_ref().and_then(|fitted| fitted.distances(self.mesh, surface.tri, barycentric)); + if let Some((front, rear)) = fitted_distances { + return RayStart::Fitted { up: averaged_normal, front, rear }; + } + let up = match &self.skew { Some(skew) => skew.correct(self.mesh, surface, averaged_normal), None => averaged_normal, diff --git a/crates/bake/src/cage/ray_start.rs b/crates/bake/src/cage/ray_start.rs index c0c3923a..8c21bb9b 100644 --- a/crates/bake/src/cage/ray_start.rs +++ b/crates/bake/src/cage/ray_start.rs @@ -7,6 +7,8 @@ pub enum RayStart { CageMesh(Vec3), /// Out along `up` by the frontal distance times `scale` (the painted cage amount) Distance { up: Vec3, scale: f32 }, + /// Out along `up` by `front` world units and reaching `rear` past the low-poly point: the automatic cage's own distances + Fitted { up: Vec3, front: f32, rear: f32 }, } impl RayStart { @@ -15,6 +17,16 @@ impl RayStart { match *self { RayStart::CageMesh(offset) => position - offset, RayStart::Distance { up, scale } => position + up * frontal * scale, + RayStart::Fitted { up, front, .. } => position + up * front, + } + } + + /// The ray's direction, how far it runs to the low-poly point and how far past it, at `frontal` and `rear` world units of the distance settings + pub fn span(&self, frontal: f32, rear: f32) -> (Vec3, f32, f32) { + match *self { + RayStart::CageMesh(offset) => (offset.normalize_or_zero(), offset.length(), rear), + RayStart::Distance { up, scale } => (-up, frontal * scale, rear), + RayStart::Fitted { up, front, rear: fitted_rear } => (-up, front, fitted_rear), } } } diff --git a/crates/bake/src/cage/vertex_reach.rs b/crates/bake/src/cage/vertex_reach.rs index 34adea92..2c6df8e8 100644 --- a/crates/bake/src/cage/vertex_reach.rs +++ b/crates/bake/src/cage/vertex_reach.rs @@ -17,10 +17,7 @@ impl VertexReach { /// Whether the ray misses the vertex (or may not hit its part) at `frontal` and `rear` world units of cage distance; with `ignore_backface` it also misses a vertex whose triangles face away from the ray pub fn missed(&self, frontal: f32, rear: f32, ignore_backface: bool) -> bool { let origin = self.start.origin(self.low_position, frontal); - let (direction, front) = match self.start { - RayStart::CageMesh(offset) => (offset.normalize_or_zero(), offset.length()), - RayStart::Distance { up, scale } => (-up, frontal * scale), - }; + let (direction, front, rear) = self.start.span(frontal, rear); let along_ray = (self.high_position - origin).dot(direction); !self.name_matches || !(0.0..=front + rear).contains(&along_ray) || (ignore_backface && self.high_facing.dot(direction) > 0.0) diff --git a/crates/bake/src/lib.rs b/crates/bake/src/lib.rs index 1d99ab36..5c8c3ba8 100644 --- a/crates/bake/src/lib.rs +++ b/crates/bake/src/lib.rs @@ -5,6 +5,7 @@ mod bake_error; mod bake_output; +mod bake_passes; mod bake_request; mod cage; mod high_poly; @@ -14,6 +15,7 @@ mod progress; pub use bake_error::BakeError; pub use bake_output::BakeOutput; +pub use bake_passes::BakePasses; pub use bake_request::BakeRequest; pub use cage::{CageShell, HighPolyReach, RayStart, VertexReach}; pub use high_poly::HighPoly; @@ -149,7 +151,7 @@ fn alloc(count: usize, value: T) -> Result, BakeError> { } pub fn bake(request: &BakeRequest, progress: &Progress) -> Result { - bake_in_strips(request, progress, STRIP_TEXELS, &CpuTracer, &[]) + bake_tiles(request, progress, &[], None) } /// Retry on the CPU if the supplied tracer fails @@ -159,19 +161,12 @@ pub fn bake_on(request: &BakeRequest, progress: &Progress, tracer: &dyn Tracer) /// Excluded atlas blocks produce no samples; their geometry still participates in ray tracing pub fn bake_tiles(request: &BakeRequest, progress: &Progress, excluded_tiles: &[(u32, u32)], tracer: Option<&dyn Tracer>) -> Result { - let tracer = tracer.unwrap_or(&CpuTracer); - match bake_in_strips(request, progress, STRIP_TEXELS, tracer, excluded_tiles) { - Err(BakeError::Tracer(error)) => { - let mut output = bake_in_strips(request, progress, STRIP_TEXELS, &CpuTracer, excluded_tiles)?; - output.tracer = format!("CPU ({} unavailable: {error})", tracer.name()); - Ok(output) - } - result => result, - } + BakePasses::new(*request).run(request.settings, progress, excluded_tiles, tracer, STRIP_TEXELS) } type OutRow<'a> = Vec<&'a mut [f32]>; +#[cfg(test)] fn bake_in_strips( request: &BakeRequest, progress: &Progress, @@ -179,9 +174,19 @@ fn bake_in_strips( tracer: &dyn Tracer, excluded_tiles: &[(u32, u32)], ) -> Result { - validate(request)?; - if excluded_tiles.iter().any(|(column, row)| *column >= request.tiles.0 || *row >= request.tiles.1) { - return Err(BakeError::Invalid("excluded UV tile lies outside the bake atlas".into())); + BakePasses::new(*request).run(request.settings, progress, excluded_tiles, Some(tracer), strip_texels) +} + +fn bake_prepared( + request: &BakeRequest, + context: &map::BakeContext, + progress: &Progress, + strip_texels: usize, + tracer: &dyn Tracer, + excluded_tiles: &[(u32, u32)], +) -> Result { + if progress.cancel.load(Relaxed) { + return Err(BakeError::Cancelled); } let settings = request.settings; @@ -189,7 +194,6 @@ fn bake_in_strips( let tile_size = (tile_width as usize, tile_height as usize); let samples_per_axis = settings.common.antialiasing.samples_per_axis() as usize; let (width, height) = (tile_size.0 * request.tiles.0 as usize, tile_size.1 * request.tiles.1 as usize); - let context = map::BakeContext::new(request)?; let tracer = if context.casts_rays() { tracer } else { &CpuTracer }; let meshes = context.trace_meshes(); let mut scene = tracer.scene(&meshes)?; @@ -259,9 +263,10 @@ fn bake_in_strips( if progress.cancel.load(Relaxed) { return Err(BakeError::Cancelled); } + // Global sample indices keep noise unchanged across strip and batch sizes bake_rows( - &context, + context, &maps, request.mesh, &gbuffer, @@ -313,6 +318,7 @@ fn bake_in_strips( if progress.cancel.load(Relaxed) { return Err(BakeError::Cancelled); } + progress.done.store(10_000, Relaxed); Ok(BakeOutput { resolution: width as u32, height: height as u32, maps: output, tracer: tracer.name() }) } @@ -349,6 +355,7 @@ fn bake_rows( .collect() }) .collect(); + let row_offsets: Vec = samples_by_row .iter() .scan(0, |sample_count, row| { @@ -362,11 +369,12 @@ fn bake_rows( true => { let (rays, frontal_distances): (Vec, Vec) = samples().map(|sample| context.transfer_ray(&sample.surface, sample.bary)).unzip(); let hits = scene.closest(1, &rays, context.ignore_transfer_backface())?; - hits.into_par_iter().zip(frontal_distances).map(|(hit, front)| context.transfer(hit, front)).collect() + hits.into_par_iter().zip(&rays).zip(frontal_distances).map(|((hit, ray), front)| context.transfer(hit, front, ray.max_distance)).collect() } false => Vec::new(), }; let transfer = |sample_index: usize| transfers.get(sample_index).and_then(Option::as_ref); + let curvature = match context.traces_curvature() { true => { let items: Vec<(&Surface, Option<&map::Transfer>)> = samples_by_row @@ -379,6 +387,7 @@ fn bake_rows( } false => Vec::new(), }; + let queries: Vec = match context.ao.is_some() || context.bent.is_some() || context.thickness.is_some() { true => samples_by_row .par_iter() @@ -388,6 +397,7 @@ fn bake_rows( .collect(), false => Vec::new(), }; + // Share occlusion results when the bent-normal ray settings match let separate_bent_pass = context.bent.filter(|_| context.bent != context.ao); let passes: Vec = [context.ao, separate_bent_pass, context.thickness].into_iter().flatten().collect(); diff --git a/crates/bake/src/map/bake_context.rs b/crates/bake/src/map/bake_context.rs index bbeb623e..156d392f 100644 --- a/crates/bake/src/map/bake_context.rs +++ b/crates/bake/src/map/bake_context.rs @@ -1,7 +1,7 @@ use super::curvature::Curvature; use super::sampling::{pack, splitmix64, tangent_normal}; use super::{position_projection::PositionProjection, source::Source, traced::Traced, transfer::Transfer}; -use crate::cage::{RayFrame, RayStart}; +use crate::cage::RayFrame; use crate::tracing::{ANY, Hemisphere, Query, Ray, RayKind, RayScene, TraceMesh}; use crate::{BakeError, BakeRequest, MeshExtent}; use rayon::prelude::*; @@ -12,10 +12,13 @@ use texturecraft_geom::{Hit, Surface, surface_at}; const CURVATURE_CHUNK: usize = 1 << 15; +/// Height relative to the rays divides by the ray's length; this keeps a zero-length ray from dividing by zero +const SHORTEST_RAY: f32 = 1e-20; + pub(crate) struct BakeContext<'a> { low: Source<'a>, high: Option>, - ray_frame: RayFrame<'a>, + ray_frame: &'a RayFrame<'a>, settings: &'a BakeSettings, frontal: f32, rear: f32, @@ -28,11 +31,9 @@ pub(crate) struct BakeContext<'a> { } impl<'a> BakeContext<'a> { - pub(crate) fn new(request: &BakeRequest<'a>) -> Result, BakeError> { + pub(crate) fn with_frame(request: &BakeRequest<'a>, extent: MeshExtent, ray_frame: &'a RayFrame<'a>) -> Self { let settings = request.settings; - let extent = MeshExtent::of(request.mesh)?; let (low, high) = Source::of_request(request); - let ray_frame = RayFrame::new(request, extent)?; let (mesh_scale, ray_epsilon) = (extent.scale, extent.ray_epsilon()); let pass = |map: BakedMap, ray_settings: &RaySettings, kind: RayKind| { let half_angle_radians = (ray_settings.spread.clamp(0.0, 180.0) * 0.5).to_radians(); @@ -74,7 +75,7 @@ impl<'a> BakeContext<'a> { } let cage_units = ray_frame.cage_units; - Ok(BakeContext { + BakeContext { low, high, ray_frame, @@ -87,7 +88,7 @@ impl<'a> BakeContext<'a> { ao, bent, thickness, - }) + } } pub(crate) fn ignore_transfer_backface(&self) -> bool { @@ -109,21 +110,19 @@ impl<'a> BakeContext<'a> { pub(crate) fn transfer_ray(&self, surface: &Surface, barycentric: [f32; 2]) -> (Ray, f32) { let start = self.ray_frame.start(surface, barycentric); let origin = start.origin(surface.pos, self.frontal); - let (direction, front) = match start { - RayStart::CageMesh(offset) => (offset.normalize(), offset.length()), - RayStart::Distance { up, scale } => (-up, self.frontal * scale), - }; + let (direction, front, rear) = start.span(self.frontal, self.rear); let key = match self.settings.high_poly.match_mode { MeshMatchMode::Always => ANY, MeshMatchMode::ByMeshName => self.low.key.get(surface.tri as usize).copied().unwrap_or(ANY), }; - (Ray { origin, direction, max_distance: front + self.rear, key }, front) + (Ray { origin, direction, max_distance: front + rear, key }, front) } - pub(crate) fn transfer(&self, hit: Option, front: f32) -> Option { + /// What the transfer ray that ran `front` to the low poly and `ray_length` in all brought back from the high poly + pub(crate) fn transfer(&self, hit: Option, front: f32, ray_length: f32) -> Option { let (high, hit) = (self.high.as_ref()?, hit?); let surface = surface_at(high.mesh, hit.tri, hit.u, hit.v)?; - Some(Transfer { surface, bary: [hit.u, hit.v], t: hit.t, front }) + Some(Transfer { surface, bary: [hit.u, hit.v], t: hit.t, front, ray_length }) } pub(crate) fn query(&self, transfer: Option<&Transfer>, low_surface: &Surface, seed: u64) -> Query { @@ -245,7 +244,7 @@ impl<'a> BakeContext<'a> { let relative_to_rays = self.settings.maps.height.parameters.normalization == texturecraft_core::HeightNormalization::RelativeToRayDistances; [transfer.map_or(if relative_to_rays { 0.5 } else { 0.0 }, |hit| { let height = hit.front - hit.t; - if relative_to_rays { (0.5 + height / (hit.front + self.rear).max(1e-20)).clamp(0.0, 1.0) } else { height } + if relative_to_rays { (0.5 + height / hit.ray_length.max(SHORTEST_RAY)).clamp(0.0, 1.0) } else { height } }); 3] } BakedMap::Opacity if missed => [0.0; 3], diff --git a/crates/bake/src/map/transfer.rs b/crates/bake/src/map/transfer.rs index c1200053..46c67f28 100644 --- a/crates/bake/src/map/transfer.rs +++ b/crates/bake/src/map/transfer.rs @@ -5,4 +5,6 @@ pub(crate) struct Transfer { pub(super) bary: [f32; 2], pub(super) t: f32, pub(super) front: f32, + /// The whole ray, from the cage to its rear end + pub(super) ray_length: f32, } diff --git a/crates/bake/src/test/cage_shell.rs b/crates/bake/src/test/cage_shell.rs index 40edd3b8..a437c089 100644 --- a/crates/bake/src/test/cage_shell.rs +++ b/crates/bake/src/test/cage_shell.rs @@ -17,7 +17,9 @@ fn painted_map() -> BakePaintMap { fn assert_cage_matches_the_ray_origins(request: &BakeRequest) { let shell = CageShell::new(request).unwrap(); let corners = shell.corners(request.settings.cage.max_frontal); - let context = BakeContext::new(request).unwrap(); + let extent = crate::MeshExtent::of(request.mesh).unwrap(); + let frame = crate::cage::RayFrame::new(request, extent).unwrap(); + let context = BakeContext::with_frame(request, extent, &frame); let triangles: Vec = request.mesh.triangles_of(request.material).collect(); assert_eq!(corners.len(), triangles.len() * 3); @@ -60,6 +62,12 @@ fn the_cage_corners_are_the_bake_ray_origins() { face_normals }; assert_cage_matches_the_ray_origins(&request(&face_normals)); + let automatic = { + let mut automatic = bake_settings.clone(); + automatic.cage.kind = CageType::Automatic; + automatic + }; + assert_cage_matches_the_ray_origins(&request(&automatic)); } #[test] diff --git a/crates/bake/src/test/fitted_cage.rs b/crates/bake/src/test/fitted_cage.rs new file mode 100644 index 00000000..3cfec7a5 --- /dev/null +++ b/crates/bake/src/test/fitted_cage.rs @@ -0,0 +1,250 @@ +use super::{covered_values, settings, transfer}; +use crate::{BakeRequest, CageShell, HighPoly, HighPolyReach}; +use texturecraft_core::{BakeSettings, BakedMap, CageType, MeshMatchMode}; +use texturecraft_geom::glam::Vec3; +use texturecraft_geom::{Bvh, Mesh, primitives}; + +/// A distance setting far larger than any fitted distance in these tests, to tell the two apart +const UNFITTED_DISTANCE: f32 = 0.5; + +/// Settings baking `maps` with the automatic cage, and distance settings no fitted cage comes near +fn automatic(maps: &[BakedMap]) -> BakeSettings { + let mut bake_settings = settings(32, maps); + bake_settings.cage.kind = CageType::Automatic; + bake_settings.cage.relative_to_bounding_box = false; + (bake_settings.cage.max_frontal, bake_settings.cage.max_rear) = (UNFITTED_DISTANCE, UNFITTED_DISTANCE); + bake_settings +} + +/// How far each corner of the automatic cage of the flat `low` around `high` rises above it, with the corner's low-poly position +fn cage_heights(low: &Mesh, high: &Mesh, bake_settings: &BakeSettings) -> Vec<(Vec3, f32)> { + let (low_bvh, high_bvh) = (Bvh::new(low), Bvh::new(high)); + let request = BakeRequest { + low_base_color: &[], + mesh: low, + bvh: &low_bvh, + material: 0, + settings: bake_settings, + high: Some(HighPoly { file_ids: &[], mesh: high, bvh: &high_bvh, base_color: &[] }), + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }; + let shell = CageShell::new(&request).unwrap(); + let corners = shell.corners(bake_settings.cage.max_frontal); + shell.positions.iter().zip(corners).map(|(position, corner)| (*position, corner.y - position.y)).collect() +} + +/// Every submesh on the first material, so the cage shell of material 0 covers all the parts +fn one_material(mesh: &mut Mesh) { + mesh.materials.truncate(1); + for submesh in &mut mesh.submeshes { + submesh.material = 0; + } +} + +#[test] +fn the_automatic_cage_reaches_a_high_poly_the_default_distances_miss() { + let low = primitives::cube(1.0); + let high = primitives::sphere(0.8, 32, 16); + let opacity_of = |bake_settings: &BakeSettings| -> Vec { + let output = transfer(&low, &high, None, bake_settings).unwrap(); + covered_values(&low, &output, BakedMap::Opacity).into_iter().map(|(_, opacity)| opacity).collect() + }; + + let distance_based = opacity_of(&settings(32, &[BakedMap::Opacity])); + assert!(distance_based.contains(&0.0), "the sphere is beyond the default distances at the middle of each face"); + + let mut bake_settings = settings(32, &[BakedMap::Opacity]); + bake_settings.cage.kind = CageType::Automatic; + let fitted = opacity_of(&bake_settings); + assert!(fitted.iter().all(|opacity| *opacity == 1.0), "every ray of the automatic cage finds the sphere"); + + // The triangles at the sphere's poles have no area, so a pole vertex has no side to face the ray with + bake_settings.high_poly.ignore_backface = false; + let (low_bvh, high_bvh) = (Bvh::new(&low), Bvh::new(&high)); + let request = BakeRequest { + low_base_color: &[], + mesh: &low, + bvh: &low_bvh, + material: 0, + settings: &bake_settings, + high: Some(HighPoly { file_ids: &[], mesh: &high, bvh: &high_bvh, base_color: &[] }), + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }; + let reach = HighPolyReach::new(&request).unwrap(); + for vertex in 0..high.positions.len() { + assert_eq!(reach.missed(vertex, 0.0, 0.0), Some(false), "high-poly vertex {vertex} is inside the cage whatever the distance settings"); + } +} + +#[test] +fn the_automatic_cage_stays_low_where_the_high_poly_is_low() { + const LOW_HEIGHT: f32 = 0.01; + const RAISED_HEIGHT: f32 = 0.2; + const RAISED_FROM_X: f32 = 0.25; + + let low = primitives::plane(1.0, 8); + let mut high = primitives::plane(1.0, 40); + for position in &mut high.positions { + position.y = if position.x > RAISED_FROM_X { RAISED_HEIGHT } else { LOW_HEIGHT }; + } + + let heights = cage_heights(&low, &high, &automatic(&[BakedMap::Normal])); + + for (position, height) in heights { + if position.x < 0.0 { + assert!((LOW_HEIGHT..RAISED_HEIGHT / 2.0).contains(&height), "the cage at {position} hugs the low part: {height}"); + } else if position.x > RAISED_FROM_X + 0.125 { + assert!((RAISED_HEIGHT..RAISED_HEIGHT * 2.0).contains(&height), "the cage at {position} clears the raised part: {height}"); + } + } +} + +#[test] +fn a_ray_that_only_finds_a_far_surface_takes_the_nearest_surface_height_instead() { + const PATCH_HEIGHT: f32 = 0.02; + const CEILING_HEIGHT: f32 = 1.0; + + // A low-plane vertex beside the patch's edge: the patch is its nearest high poly, the ceiling is straight above it + const BESIDE_PATCH: Vec3 = Vec3::new(0.125, 0.0, 0.0); + + // Far enough that the ceiling's own corners are nearest to the low plane's border, not to the vertex tested + const CEILING_REACH: f32 = 1000.0; + + // The ceiling starts just past the patch's edge (x = 0), the patch covers the low plane's other half + const CEILING_FROM_X: f32 = 0.05; + const PATCH_SIZE: f32 = 0.5; + const SAME_POSITION: f32 = 1e-4; + + let low = primitives::plane(1.0, 8); + let mut high = primitives::plane(PATCH_SIZE, 1); + for position in &mut high.positions { + *position = Vec3::new(position.x - PATCH_SIZE / 2.0, PATCH_HEIGHT, position.z); + } + let ceiling = Mesh::from_parts( + vec![ + Vec3::new(CEILING_FROM_X, CEILING_HEIGHT, -CEILING_REACH), + Vec3::new(CEILING_FROM_X, CEILING_HEIGHT, CEILING_REACH), + Vec3::new(CEILING_REACH, CEILING_HEIGHT, 0.0), + ], + None, + vec![Default::default(); 3], + vec![0, 1, 2], + "ceiling", + ) + .unwrap(); + high.append(&ceiling); + + let heights = cage_heights(&low, &high, &automatic(&[BakedMap::Normal])); + + let (_, height) = heights.iter().find(|(position, _)| position.distance(BESIDE_PATCH) < SAME_POSITION).unwrap(); + assert!(*height < CEILING_HEIGHT / 2.0, "the cage beside the patch stays near the patch, not the ceiling: {height}"); +} + +#[test] +fn a_part_no_high_poly_part_matches_keeps_the_distance_settings() { + let mut low = primitives::plane(1.0, 2); + let mut high = primitives::plane(1.0, 2); + low.submeshes[0].name = "panel_low".into(); + high.submeshes[0].name = "door_high".into(); + let mut bake_settings = automatic(&[BakedMap::Normal]); + bake_settings.high_poly.match_mode = MeshMatchMode::ByMeshName; + + let heights = cage_heights(&low, &high, &bake_settings); + + assert!(heights.iter().all(|(_, height)| *height == UNFITTED_DISTANCE)); +} + +#[test] +fn a_part_meeting_another_part_takes_its_distances_from_its_own_high_poly_only() { + const LOW_HEIGHT: f32 = 0.01; + const RAISED_HEIGHT: f32 = 0.3; + + // Two low parts sharing the edge x = 0, under a low and a raised high-poly part matched by name + let part = |name: &str, side: f32, height: f32, subdivisions: usize| { + let mut part = primitives::plane(1.0, subdivisions); + for position in &mut part.positions { + *position += Vec3::new(side * 0.5, height, 0.0); + } + part.submeshes[0].name = name.into(); + part + }; + let mut low = part("left_low", -1.0, 0.0, 4); + low.append(&part("right_low", 1.0, 0.0, 4)); + let mut high = part("left_high", -1.0, LOW_HEIGHT, 8); + high.append(&part("right_high", 1.0, RAISED_HEIGHT, 8)); + for mesh in [&mut low, &mut high] { + one_material(mesh); + } + let mut bake_settings = automatic(&[BakedMap::Normal]); + bake_settings.high_poly.match_mode = MeshMatchMode::ByMeshName; + + let heights = cage_heights(&low, &high, &bake_settings); + + // The left part's triangles come first, three corners each + let left_corners = low.submeshes[0].count as usize; + for (position, height) in &heights[..left_corners] { + assert!(*height < RAISED_HEIGHT / 2.0, "the left part's cage at {position} stays near the left high poly: {height}"); + } +} + +#[test] +fn parts_back_to_back_fit_their_cages_along_their_own_normals() { + const SHEET_DISTANCE: f32 = 0.2; + + // A plane facing up and the same plane facing down, each facing its own high-poly sheet: welded, their normals cancel out + let named = |mut mesh: Mesh, name: &str| { + mesh.submeshes[0].name = name.into(); + mesh + }; + let facing_down = |mut mesh: Mesh| { + for normal in &mut mesh.normals { + *normal = -*normal; + } + for triangle in mesh.indices.as_chunks_mut::<3>().0 { + triangle.swap(1, 2); + } + mesh + }; + let sheet = |height: f32| { + let mut sheet = primitives::plane(1.0, 8); + for position in &mut sheet.positions { + position.y = height; + } + sheet + }; + let mut low = named(primitives::plane(1.0, 4), "front_low"); + low.append(&named(facing_down(primitives::plane(1.0, 4)), "back_low")); + let mut high = named(sheet(SHEET_DISTANCE), "front_high"); + high.append(&named(facing_down(sheet(-SHEET_DISTANCE)), "back_high")); + for mesh in [&mut low, &mut high] { + one_material(mesh); + } + + for match_mode in [MeshMatchMode::Always, MeshMatchMode::ByMeshName] { + let mut bake_settings = automatic(&[BakedMap::Normal]); + bake_settings.high_poly.match_mode = match_mode; + + let heights = cage_heights(&low, &high, &bake_settings); + + // The front part's triangles come first, three corners each + let front_corners = low.submeshes[0].count as usize; + for (position, height) in &heights[..front_corners] { + assert!( + (SHEET_DISTANCE..UNFITTED_DISTANCE).contains(height), + "{match_mode:?}: the front part's cage at {position} reaches the sheet above it, fitted: {height}" + ); + } + for (position, height) in &heights[front_corners..] { + assert!( + (-UNFITTED_DISTANCE..=-SHEET_DISTANCE).contains(height), + "{match_mode:?}: the back part's cage at {position} reaches the sheet below it, fitted: {height}" + ); + } + } +} diff --git a/crates/bake/src/test/high_poly_reach.rs b/crates/bake/src/test/high_poly_reach.rs index 8a4f83c4..b001737b 100644 --- a/crates/bake/src/test/high_poly_reach.rs +++ b/crates/bake/src/test/high_poly_reach.rs @@ -69,7 +69,9 @@ fn a_vertex_is_missed_exactly_when_the_bake_ray_misses_it() { tiles: (1, 1), }; let reach = HighPolyReach::new(&request).unwrap(); - let context = BakeContext::new(&request).unwrap(); + let extent = crate::MeshExtent::of(request.mesh).unwrap(); + let frame = crate::cage::RayFrame::new(&request, extent).unwrap(); + let context = BakeContext::with_frame(&request, extent, &frame); for (vertex, vertex_reach) in reach.vertices.iter().enumerate() { let (vertex_reach, missed) = (vertex_reach.unwrap(), reach.missed(vertex, max_frontal, max_rear).unwrap()); @@ -94,6 +96,7 @@ fn a_vertex_is_missed_exactly_when_the_bake_ray_misses_it() { } } } + assert!(checked[0] > 100 && checked[1] > 100, "both reached and missed vertices were compared: {checked:?}"); } @@ -173,11 +176,14 @@ fn matching_by_mesh_name_misses_the_parts_with_another_name() { tiles: (1, 1), }; let reach = HighPolyReach::new(&request).unwrap(); - let context = BakeContext::new(&request).unwrap(); + let extent = crate::MeshExtent::of(request.mesh).unwrap(); + let frame = crate::cage::RayFrame::new(&request, extent).unwrap(); + let context = BakeContext::with_frame(&request, extent, &frame); let (_, high_keys) = transfer_keys(&request); for (vertex, vertex_reach) in reach.vertices.iter().enumerate() { let (vertex_reach, missed) = (vertex_reach.unwrap(), reach.missed(vertex, 0.02, 0.01).unwrap()); + // On the line where the two parts meet, a ray reaches either part's triangles if vertex_reach.high_position.x.abs() < BOUNDARY { continue; diff --git a/crates/bake/src/tests.rs b/crates/bake/src/tests.rs index eaa64cf2..7d94031e 100644 --- a/crates/bake/src/tests.rs +++ b/crates/bake/src/tests.rs @@ -20,6 +20,9 @@ mod bent_normal_space; #[path = "test/cage_shell.rs"] mod cage_shell; +#[path = "test/fitted_cage.rs"] +mod fitted_cage; + #[path = "test/high_poly_reach.rs"] mod high_poly_reach; diff --git a/crates/compose/src/below.rs b/crates/compose/src/below.rs index cdca3b83..dd440224 100644 --- a/crates/compose/src/below.rs +++ b/crates/compose/src/below.rs @@ -165,7 +165,7 @@ impl StackKey { match &effect.kind { EffectKind::Fill { source, .. } => source.images().into_iter().for_each(&mut record_image_name), EffectKind::Material(fill) => fill.sources.values().flat_map(Source::images).for_each(&mut record_image_name), - EffectKind::Generator(generator) => generator.inputs.values().flat_map(Source::images).for_each(&mut record_image_name), + EffectKind::Generator(generator) => generator.sources().flat_map(Source::images).for_each(&mut record_image_name), EffectKind::ColorSelection(selection) => selection.id_map.iter().for_each(|name| record_image_name(name)), _ => {} } diff --git a/crates/compose/src/curvature_sizes.rs b/crates/compose/src/curvature_sizes.rs index 0b7138bc..4660ca45 100644 --- a/crates/compose/src/curvature_sizes.rs +++ b/crates/compose/src/curvature_sizes.rs @@ -4,13 +4,16 @@ use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex, Weak}; use rayon::prelude::*; -use texturecraft_core::{BakedMap, BlockScales, CurvatureDetail}; +use texturecraft_core::{BakedMap, BlockScales}; use texturecraft_texel::dilate::{DilationMap, NONE}; use crate::curvature_size_level::{CurvatureSizeLevel, DEVIATION_SCALE}; use crate::eval::{BLUR_BOX_PASSES, Inputs, blur}; -/// The curvature map padded past its UV islands and blurred at each size of [`CurvatureDetail::SIZES`] after the first. +/// The blur radius of each level in texels at 2K: the detail sizes of [`texturecraft_core::CurvatureDetail::SIZES`] after the first, then wider ones the wear generators' edges smoothness reaches +pub const LEVEL_RADII: [f32; 8] = [1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0, 128.0]; + +/// The curvature map padded past its UV islands and blurred at each radius of [`LEVEL_RADII`] pub struct CurvatureSizes { /// One per blurred size, built once a generator gives that size a weight above 0. pub levels: Vec>>, @@ -31,7 +34,11 @@ const CACHE_MAPS: usize = 16; impl CurvatureSizes { /// The sizes of the texture set `inp` composites, holding at least those `needed` marks (one flag per blurred size); None without a baked curvature map or a needed size. pub fn of(inp: &Inputs, needed: &[bool]) -> Option> { - let curvature = inp.baked.maps.get(&BakedMap::Curvature)?; + CurvatureSizes::of_map(inp, inp.baked.maps.get(&BakedMap::Curvature)?, needed) + } + + /// The sizes of `curvature`, a map in the baked curvature map's layout (the baked map or one derived from it) + pub fn of_map(inp: &Inputs, curvature: &Arc>, needed: &[bool]) -> Option> { let (width, height) = (inp.baked.resolution, inp.baked.height(BakedMap::Curvature)); if !needed.contains(&true) || width == 0 || height == 0 { return None; @@ -70,14 +77,14 @@ impl CurvatureSizes { padding.src.par_iter().map(|&source| if source == NONE { 0.0 } else { curvature.get(source as usize).copied().unwrap_or(0.5) - 0.5 }).collect(); let (block_width, block_height) = (block.0.max(1).min(width), block.1.max(1).min(height)); - let levels = CurvatureDetail::SIZES + let levels = LEVEL_RADII .iter() - .skip(1) .enumerate() .map(|(level, size)| { if let Some(existing) = built.and_then(|sizes| sizes.levels.get(level)).and_then(Option::clone) { return Some(existing); } + if !needed.get(level).copied().unwrap_or(false) { return None; } @@ -85,6 +92,7 @@ impl CurvatureSizes { // Sizes are texels at 2K; a blur this wide holds nothing finer than half its radius, so it is stored that much coarser let radius = (size * block_width as f32 / 2048.0).round().max(1.0) as u32; let mut step = (radius / 2).max(1).next_power_of_two(); + // A coarse cell must not average curvature from different UV tiles while !block_width.is_multiple_of(step) || !block_height.is_multiple_of(step) { step /= 2; @@ -247,6 +255,8 @@ fn coarsen(data: &[f32], (width, height): (u32, u32), step: u32, block: (u32, u3 #[cfg(test)] mod tests { + use texturecraft_core::CurvatureDetail; + use super::*; #[test] @@ -473,4 +483,9 @@ mod tests { } } } + + #[test] + fn the_first_levels_are_the_detail_sizes() { + assert_eq!(LEVEL_RADII[..CurvatureDetail::BLURRED_SIZES], CurvatureDetail::SIZES[1..]); + } } diff --git a/crates/compose/src/dripping_rust.rs b/crates/compose/src/dripping_rust.rs new file mode 100644 index 00000000..c08bc90b --- /dev/null +++ b/crates/compose/src/dripping_rust.rs @@ -0,0 +1,316 @@ +//! The Dripping Rust generator: rust grown from the occlusion, broken up by grunge, then run down the mesh in drips; built once per layout and settings + +use std::sync::Arc; + +use rayon::prelude::*; +use texturecraft_core::{BakedMap, DrippingRustParameters, GeneratorKind, WearParameters}; +use texturecraft_geom::{NO_TRI, TrianglePartition}; + +use crate::eval::{Inputs, texel_coords}; +use crate::field_cache::FieldCache; +use crate::histogram_scan::histogram_scan; +use crate::wear; +use crate::working_field::{REFERENCE_TILE_TEXELS, blur_blocks, box_radius}; + +/// The rust before any grunge: `RUST_FLOOR + RUST_GAIN * max(RUST_OCCLUSION − occlusion, 0)^RUST_POWER` (fitted to the reference) +const RUST_FLOOR: f32 = 0.315; +const RUST_GAIN: f32 = 3.19; +const RUST_OCCLUSION: f32 = 0.849; +const RUST_POWER: f32 = 2.38; + +/// How much grunge breaks the rust up: the spread of the reference's noise (measured); the pattern itself is inferred +const GRUNGE_SPREAD: f32 = 0.19; + +/// Blur sizes at Spreading Smoothness 1 and Drips Smoothness 1, as gaussian sigmas in texels of a 2K UV tile (fitted) +const SPREADING_SIGMA_2K: f32 = 47.0; +const DRIPS_SIGMA_2K: f32 = 11.5; + +/// How far a drip runs at Drips Intensity 1, in texels of a 2K UV tile, and how it fades along its length: `1 − DRIP_FADE · along^DRIP_FADE_POWER` (fitted) +const DRIP_LENGTH_2K: f32 = 90.86; +const DRIP_FADE: f32 = 0.898; +const DRIP_FADE_POWER: f32 = 0.671; + +/// Coverage below which a blurred texel has nothing to average +const MIN_COVERAGE: f32 = 1e-3; + +static CACHE: FieldCache = FieldCache::new(); + +/// The rust before its spreading and contrast at every working texel of `inp` (0 outside the islands) +pub(crate) fn rust_field(inp: &Inputs, geometry: u64, rust: &DrippingRustParameters, seed: u32) -> Arc> { + let settings = vec![ + rust.spreading_smoothness.to_bits(), + rust.drips_intensity.to_bits(), + rust.drips_smoothness.to_bits(), + rust.drips_samples, + u32::from(rust.axis), + seed, + ]; + CACHE.get_or_build(inp, geometry, &[BakedMap::AmbientOcclusion], settings, |block| build(inp, rust, seed, block)) +} + +/// The value at a working texel: the rust spread and contrasted +pub(crate) fn rust_value(rust: &DrippingRustParameters, field: f32) -> f32 { + histogram_scan(field, rust.spreading, rust.contrast) +} + +fn build(inp: &Inputs, rust: &DrippingRustParameters, seed: u32, block: (u32, u32)) -> Vec { + let gbuf = inp.gbuf; + let (width, height) = (gbuf.width, gbuf.height); + let cover: Vec = (0..width * height).map(|texel| if gbuf.covered(texel as usize) { 1.0 } else { 0.0 }).collect(); + let tile_texels = |x: u32, y: u32| block.0 as f32 * inp.block_scales.at(x, y); + + // The rust from the occlusion, broken up by the Dirt generator's grunge + let grunge = WearParameters::defaults(GeneratorKind::Dirt); + let rust_at = |texel: u32| { + let (x, y) = (texel % width, texel / width); + let occlusion = inp.baked.sample_working(BakedMap::AmbientOcclusion, x, y, (width, height), &inp.block_scales).map_or(1.0, |value| value[0]); + let base = RUST_FLOOR + RUST_GAIN * (RUST_OCCLUSION - occlusion).max(0.0).powf(RUST_POWER); + let noise = grunge.map_or(0.0, |grunge| wear::grunge(GeneratorKind::Dirt, &grunge, seed, &texel_coords(inp, x, y))); + base + GRUNGE_SPREAD * noise + }; + let mut field: Vec = (0..width * height).into_par_iter().map(|texel| if gbuf.covered(texel as usize) { rust_at(texel) } else { 0.0 }).collect(); + + let radius_at = |sigma_2k: f32, smoothness: f32| move |x: u32, y: u32| box_radius(smoothness * sigma_2k * tile_texels(x, y) / REFERENCE_TILE_TEXELS); + blur_over_cover(&mut field, &cover, (width, height), block, radius_at(SPREADING_SIGMA_2K, rust.spreading_smoothness)); + let mut field = drips(inp, rust, field, (width, height), &tile_texels); + blur_over_cover(&mut field, &cover, (width, height), block, radius_at(DRIPS_SIGMA_2K, rust.drips_smoothness)); + field.iter_mut().zip(&cover).for_each(|(value, covered)| *value = if *covered > 0.0 { value.clamp(0.0, 1.0) } else { 0.0 }); + field +} + +/// `values` blurred within each UV tile block by the radius `radius_at` gives, weighted by `cover` so the empty space around the islands doesn't bleed in +fn blur_over_cover(values: &mut [f32], cover: &[f32], size: (u32, u32), block: (u32, u32), radius_at: impl Fn(u32, u32) -> usize + Copy) { + let has_blur = (0..size.1).step_by(block.1 as usize).any(|top| (0..size.0).step_by(block.0 as usize).any(|left| radius_at(left, top) > 0)); + if !has_blur { + return; + } + + let mut sums: Vec = values.iter().zip(cover).map(|(value, covered)| value * covered).collect(); + let mut weights = cover.to_vec(); + blur_blocks(&mut sums, size, block, radius_at); + blur_blocks(&mut weights, size, block, radius_at); + values.par_iter_mut().zip(sums.par_iter().zip(weights.par_iter())).zip(cover.par_iter()).for_each(|((value, (sum, weight)), covered)| { + if *covered > 0.0 && *weight > MIN_COVERAGE { + *value = sum / weight; + } + }); +} + +/// Each texel takes the most rust found uphill along the drip axis, fading with how far up it lies +fn drips( + inp: &Inputs, + rust: &DrippingRustParameters, + field: Vec, + (width, height): (u32, u32), + tile_texels: &(impl Fn(u32, u32) -> f32 + Sync), +) -> Vec { + let gbuf = inp.gbuf; + if rust.drips_samples == 0 || rust.drips_intensity <= 0.0 { + return field; + } + + let axis = usize::from(rust.axis.min(2)); + let (low, high) = inp.bounds; + let low = low.to_array()[axis]; + let extent = (high.to_array()[axis] - low).max(f32::EPSILON); + let material = inp.project.texture_set(inp.ts).map_or(0, |set| set.material); + let islands = TrianglePartition::uv_islands(inp.mesh, material); + let surface: Vec<(u32, f32)> = (0..width * height) + .into_par_iter() + .map(|texel| { + let triangle = gbuf.tri.get(texel as usize).copied().unwrap_or(NO_TRI); + let Some(island) = islands.index_of(triangle) else { return (NO_TRI, 0.0) }; + + gbuf.surface(inp.mesh, texel as usize).map_or((NO_TRI, 0.0), |surface| (island as u32, (surface.pos.to_array()[axis] - low) / extent)) + }) + .collect(); + drop(islands); + + let index_at = |x: i64, y: i64| -> Option { + if x < 0 || y < 0 || x >= i64::from(width) || y >= i64::from(height) { + return None; + } + + Some((y * i64::from(width) + x) as usize) + }; + let samples = rust.drips_samples; + let taps: Vec<_> = (1..=samples) + .map(|step| { + let fraction = step as f32 / samples as f32; + (fraction, 1.0 - DRIP_FADE * fraction.powf(DRIP_FADE_POWER)) + }) + .collect(); + + (0..width * height) + .into_par_iter() + .map(|texel| { + let (column, row) = (texel % width, texel / width); + let (x, y) = (i64::from(column), i64::from(row)); + let here = field.get(texel as usize).copied().unwrap_or(0.0); + let Some(&(island, axis_here)) = surface.get(texel as usize).filter(|(island, _)| *island != NO_TRI) else { return here }; + let axis_at = |x, y| { + let (other_island, value) = *surface.get(index_at(x, y)?)?; + (other_island == island).then_some(value) + }; + + let (dx, dy) = (slope(axis_at(x - 1, y), axis_here, axis_at(x + 1, y)), slope(axis_at(x, y - 1), axis_here, axis_at(x, y + 1))); + let length = (dx * dx + dy * dy).sqrt(); + if !length.is_finite() || length <= f32::EPSILON { + return here; + } + + let reach = rust.drips_intensity * DRIP_LENGTH_2K * tile_texels(column, row) / REFERENCE_TILE_TEXELS; + let mut most = here; + let mut current = (x, y); + 'ray: for &(fraction, fade) in &taps { + let distance = reach * fraction; + let sample = ((x as f32 + distance * dx / length).round() as i64, (y as f32 + distance * dy / length).round() as i64); + + // A sparse tap must still have continuous coverage along the ray + while current != sample { + current = next_ray_texel((x, y), current, sample, (dx, dy)); + if axis_at(current.0, current.1).is_none() { + break 'ray; + } + } + + // A tap beyond a ridge contributes only if it is higher than the receiving texel + if axis_at(sample.0, sample.1).is_some_and(|value| value >= axis_here) + && let Some(value) = index_at(sample.0, sample.1).and_then(|index| field.get(index)) + { + most = most.max(*value * fade); + } + } + most + }) + .collect() +} + +/// Finite difference within one UV island, one-sided at its edge +fn slope(before: Option, here: f32, after: Option) -> f32 { + match (before, after) { + (Some(before), Some(after)) => (after - before) * 0.5, + (None, Some(after)) => after - here, + (Some(before), None) => here - before, + (None, None) => 0.0, + } +} + +/// Advance across the next texel boundary on a ray from a texel centre toward its next tap +fn next_ray_texel(origin: (i64, i64), (x, y): (i64, i64), (target_x, target_y): (i64, i64), (dx, dy): (f32, f32)) -> (i64, i64) { + let step_x = (target_x - x).signum(); + let step_y = (target_y - y).signum(); + if step_x == 0 || step_y == 0 { + return (x + step_x, y + step_y); + } + + // Compare crossing distances without dividing by either component + let crossing_x = ((x - origin.0).abs() as f32 + 0.5) * dy.abs(); + let crossing_y = ((y - origin.1).abs() as f32 + 0.5) * dx.abs(); + (x + step_x * i64::from(crossing_x <= crossing_y), y + step_y * i64::from(crossing_y <= crossing_x)) +} + +#[cfg(test)] +mod tests { + use texturecraft_core::{Project, TextureSet}; + use texturecraft_geom::{UvGBuffer, primitives}; + + use super::*; + use crate::{BakedMaps, PixelStore}; + + const RES: u32 = 256; + + #[test] + fn a_drip_takes_no_rust_from_past_a_ridge_lower_on_the_axis() { + // A strip rising gently to a ridge at its middle, then falling steeply + let mut mesh = primitives::plane(2.0, 64); + for position in &mut mesh.positions { + position.y = if position.z <= 0.0 { 1.0 + position.z } else { 1.0 - 8.0 * position.z }; + } + let gbuf = UvGBuffer::new(&mesh, 0, RES, RES); + let mut project = Project::new("t", "strip"); + project.texture_sets.push(TextureSet::new("A", 0, RES)); + let (pixels, baked, images) = (PixelStore::default(), BakedMaps::default(), Default::default()); + let inputs = Inputs { + project: &project, + ts: 0, + mesh: &mesh, + gbuf: &gbuf, + pixels: &pixels, + baked: &baked, + block_scales: project.texture_sets[0].block_scales(), + preview: None, + images: &images, + bounds: mesh.bounds(), + }; + + // Rust only on the steep side, all lower than the gentle side's texel just below the ridge + let rusted = |surface: &texturecraft_geom::Surface| surface.pos.z > 0.01; + let field: Vec = (0..RES * RES).map(|texel| gbuf.surface(&mesh, texel as usize).filter(rusted).map_or(0.0, |_| 1.0)).collect(); + let rust = DrippingRustParameters { drips_intensity: 1.0, drips_samples: DrippingRustParameters::MAX_SAMPLES, axis: 1, ..Default::default() }; + let dripped = drips(&inputs, &rust, field, (RES, RES), &|_, _| RES as f32); + + let below_ridge = (0..RES * RES) + .find(|texel| { + gbuf.surface(&mesh, *texel as usize).is_some_and(|surface| (surface.pos.z + 0.04).abs() < 1.0 / RES as f32 && surface.pos.x.abs() < 0.1) + }) + .expect("a texel just below the ridge"); + assert_eq!(dripped[below_ridge as usize], 0.0); + } + + #[test] + fn a_runoff_streak_requires_a_continuous_uv_surface() { + const GAP_HALF_WIDTH: f32 = 1.0 / 64.0; + let mut mesh = primitives::plane(2.0, 128); + let connected_indices = mesh.indices.clone(); + let (triangles, _) = connected_indices.as_chunks::<3>(); + let separated_indices: Vec<_> = triangles + .iter() + .filter(|triangle| { + triangle.iter().all(|&corner| mesh.positions[corner as usize].z <= -GAP_HALF_WIDTH) + || triangle.iter().all(|&corner| mesh.positions[corner as usize].z >= GAP_HALF_WIDTH) + }) + .flatten() + .copied() + .collect(); + for position in &mut mesh.positions { + position.y = position.z; + } + let mut project = Project::new("Runoff", "Plane"); + project.texture_sets.push(TextureSet::new("UV islands", 0, RES)); + let (pixels, baked, images) = (PixelStore::default(), BakedMaps::default(), Default::default()); + let index = |row| (row * RES + RES / 2) as usize; + + for (connected, indices) in [(true, connected_indices), (false, separated_indices)] { + mesh.indices = indices; + mesh.submeshes[0].count = mesh.indices.len() as u32; + let gbuf = UvGBuffer::new(&mesh, 0, RES, RES); + let inputs = Inputs { + project: &project, + ts: 0, + mesh: &mesh, + gbuf: &gbuf, + pixels: &pixels, + baked: &baked, + block_scales: project.texture_sets[0].block_scales(), + preview: None, + images: &images, + bounds: mesh.bounds(), + }; + let field: Vec = + (0..RES * RES).map(|texel| f32::from(gbuf.surface(&mesh, texel as usize).is_some_and(|surface| surface.pos.z > GAP_HALF_WIDTH))).collect(); + assert!(gbuf.covered(index(124))); + assert_eq!(gbuf.covered(index(128)), connected); + assert_eq!(field[index(124)], 0.0); + assert_eq!(field[index(131)], 1.0); + + for samples in [1, DrippingRustParameters::MAX_SAMPLES] { + let rust = DrippingRustParameters { drips_intensity: 1.0, drips_samples: samples, axis: 1, ..Default::default() }; + + let dripped = drips(&inputs, &rust, field.clone(), (RES, RES), &|_, _| RES as f32); + + assert_eq!(dripped[index(124)] > 0.0, connected, "a streak with {samples} taps requires a continuous covered surface"); + } + } + } +} diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 3097e768..52184129 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -7,16 +7,17 @@ mod evaluation_inputs; pub(crate) mod thumbnail; use std::borrow::Cow; -use std::collections::{BTreeMap, HashMap}; +use std::collections::{BTreeMap, HashMap, HashSet}; use std::sync::Arc; use rayon::prelude::*; use texturecraft_core::{ AnisotropicKuwahara, BakedMap, Bevel, BevelSmooth, BlendMode, BlockScales, Channel, ChannelKind, ColorMatch, CompareSource, ContentsOffset, - CurvatureDetail, CurvatureMode, Effect, EffectKind, FLAT_CURVATURE, Fill, Filter, Filtering, Generator, GeneratorKind, HeightMask, HeightToNormal, - HighpassSpace, ImageInput, Layer, LayerId, LayerKind, Mask, MaskBackground, MaskOutline, MicroDetail, Mirror, NormalFormat, PreparedColorMatch, - PreparedGradient, Project, Projection, RepeatMode, Sampling, ShapeCrop, Source, SourceColorMode, SourceSlopeBlur, SourceWarp, StylizedShading, - TargetColorMode, TextureSet, TileGrid, TileTransform, WarpSourceMode, blend1, blend3, lum, mix3, per_unit, posterize, udim_at, + CurvatureDetail, CurvatureMode, Effect, EffectKind, FLAT_CURVATURE, Fill, Filter, Filtering, Generator, GeneratorGlobal, GeneratorKind, + GrayscaleConversionParameters, HeightMask, HeightToNormal, HighpassSpace, ImageInput, KindControls, Layer, LayerId, LayerKind, Mask, MaskBackground, + MaskOutline, Mirror, NormalFormat, PreparedColorMatch, PreparedGradient, Project, Projection, RepeatMode, Sampling, SectionParameters, ShapeCrop, Source, + SourceColorMode, SourceSlopeBlur, SourceWarp, StylizedShading, TargetColorMode, TextureSet, TileGrid, TileTransform, WarpSourceMode, WearParameters, + blend1, blend3, lum, mix3, per_unit, posterize, udim_at, }; use texturecraft_geom::glam::{Vec2, Vec3}; use texturecraft_geom::{Mesh, NO_TRI, Surface, UvGBuffer}; @@ -24,22 +25,31 @@ use texturecraft_texel::{DilationMap, TILE, TILE_AREA, TileImage, from_u16, nois use crate::ProjectorDepthCache; use crate::below::{Band, BelowCache, Level, StackKey}; -use crate::curvature_sizes::CurvatureSizes; +use crate::curvature_sizes::{CurvatureSizes, LEVEL_RADII}; +use crate::dripping_rust; use crate::effect_histogram::EffectHistogram; use crate::environment_sh::EnvironmentSh; use crate::fill_copies::FillCopies; use crate::fill_copy::FillCopy; use crate::fill_depth::FillDepth; use crate::fill_place::FillPlace; +use crate::generator_maps::GeneratorMaps; use crate::held_fields::HeldFields; use crate::mask_gray::MaskGray; +use crate::micro_detail::AnchorHeights; use crate::pattern::{Coords, image_samples, mesh_frame, pattern_pixels, placement, procedural_in, world_noise}; use crate::pattern_context::PatternContext; use crate::projector_cover::{framed_cover, projector_cover, projector_covers_all}; +use crate::sections; use crate::shape_distance::distance_filter; use crate::slope_texel::slope_texel; use crate::store::{BakedMaps, ImageRes, ImageStore, PixelStore, decode}; +use crate::texture_layer; +use crate::three_d_distance; +use crate::uv_border_distance; use crate::warp_texel::{Input, MIN_READ_WEIGHT, Sample, warp_texel}; +use crate::wear; +use crate::wear_inputs::WearInputs; use draw_placement::DrawPlacement; use evaluation_inputs::EvaluationInputs; @@ -51,6 +61,9 @@ const COVERED: f32 = 0.9999; /// Largest projected step as a share of the image's longer side for non-UV projections const SEAM_JUMP_SHARE: f32 = 0.25; +/// Narrowest extent of the mesh's bounds a position is normalised across +const MIN_BOUNDS_EXTENT: f32 = 1e-6; + /// Stack values being composited, per channel. type Acc = [[f32; 3]; NCH]; @@ -285,8 +298,8 @@ struct EffectPlan<'a> { opacity: f32, data: Option>, preview: bool, - /// The curvature detail sizes a generator with detail reads. - curvature_sizes: Option>, + /// The detail sizes and micro details a generator reads + maps: GeneratorMaps, /// A filtered mask stage retained because an anchor above it records that stage. filtered_mask: Option<&'a Field>, /// The projector's depth map of a fill or material effect that culls by depth @@ -506,8 +519,13 @@ fn neighbourhood_filters(effects: &[Effect], res: u32, channel: Option) } // Use reference-resolution reach so all callers classify the same filters as stages - EffectKind::Generator(generator) if generator.global.blur > 0.0 || generator.resolution.can_reduce() => { - Some((index, texels(generator.global.blur_radius()) + generator.resolution.largest_cell(res) as f32, Op::Blur(None))) + EffectKind::Generator(generator) + if generator.applied_global().blur > 0.0 || generator.resolution.can_reduce() || sections::generator_blur_sigma(generator) > 0.0 => + { + let section_blur = sections::generator_blur_sigma(generator); + let section_reach = if section_blur > 0.0 { texels(section_blur) } else { 0.0 }; + let reach = texels(generator.applied_global().blur_radius()) + section_reach + generator.resolution.largest_cell(res) as f32; + Some((index, reach, Op::Blur(None))) } // A mirror reads anywhere in its UV tile @@ -1440,15 +1458,19 @@ fn layer_mask(p: &Project, id: LayerId) -> Option<&Mask> { /// Layers of `list` in drawing order (bottom → top, folder and instanced folder contents after /// their folder). -fn draw_order(inp: &EvaluationInputs, list: &[LayerId], depth: usize, place: DrawPlacement, out: &mut Vec<(LayerId, DrawPlacement)>) { +fn draw_order(inp: &EvaluationInputs, list: &[LayerId], depth: usize, place: DrawPlacement, visible_only: bool, out: &mut Vec<(LayerId, DrawPlacement)>) { if depth > texturecraft_core::project::MAX_DEPTH { return; } for id in list { out.push((*id, place)); + if visible_only && !inp.project.layers.get(id).is_some_and(|layer| layer.visible) { + continue; + } + if let Some(layer) = inp.project.content_layer(*id).filter(|layer| !layer.children().is_empty()) { - draw_order(inp, layer.children(), depth + 1, place.children(inp, *id, layer), out); + draw_order(inp, layer.children(), depth + 1, place.children(inp, *id, layer), visible_only, out); } } } @@ -1646,7 +1668,7 @@ fn filter_region( _ => None, }; let components = match job { - Job::Mask(_) if generator.is_some() => 2, + Job::Mask(_) if generator.is_some() => GENERATOR_STAGE_COMPONENTS, Job::Mask(_) => 1, Job::Content(_) => 4, }; @@ -1682,15 +1704,13 @@ fn filter_region( let height_nodes = if heights { plan_in(inputs, &[id], &[Channel::Height], tile_x, tile_y, 0, Some(below), place, None) } else { Vec::new() }; let mut mask = None; let mut nodes = Vec::new(); - let mut generator_sizes = None; + let mut generator_maps = GeneratorMaps::default(); match job { Job::Mask(layer_mask) => { // The layer's own filtered content, for a compare of it (this mask's field is not built yet) - let Some(mut mask_stack) = mask_plan(inputs, id, layer_mask, tile_x, tile_y, Some(below), place) else { - continue; - }; + let mut mask_stack = mask_plan(inputs, id, layer_mask, tile_x, tile_y, Some(below), place); - generator_sizes = mask_stack.effects.get(index).and_then(|effect| effect.curvature_sizes.clone()); + generator_maps = mask_stack.effects.get(index).map(|effect| effect.maps.clone()).unwrap_or_default(); mask_stack.effects.truncate(index); mask_stack.start = start; mask = Some(mask_stack); @@ -1715,8 +1735,9 @@ fn filter_region( let value = match (&mask, nodes.first()) { (Some(mask_stack), _) => { - let ramp = generator.map_or(0.0, |(generator, _)| texel.generator_ramp(generator, generator_sizes.as_deref())); - [texel.mask(mask_stack), ramp, 0.0, 0.0] + let ramp = generator.map_or(0.0, |(generator, _)| texel.generator_ramp(generator, &generator_maps)); + let texture = generator.and_then(|(generator, _)| texel.generator_texture(generator)).unwrap_or(0.0); + [texel.mask(mask_stack), ramp, texture, 0.0] } (None, Some(node)) => match node.chans.first().and_then(|channel_plan| texel.content(&node.content, channel_plan)) { Some((color, coverage)) => [color[0] * coverage, color[1] * coverage, color[2] * coverage, coverage], @@ -1932,7 +1953,36 @@ fn filter_region( Some(Field { x0: region_x, y0: region_y, w: width, h: height, comps: field_components, data: result, anchor_stages: Vec::new() }) } -/// The mask over a region after a generator at its own resolution and blur: `stack` is (stack below, generator ramp) per texel, sizes in texels per side. +/// Where working texel (`x`, `y`) of `inp` is, for pattern evaluation (as [`Texel::coords`] sees it outside a fill copy) +pub(crate) fn texel_coords(inp: &Inputs, x: u32, y: u32) -> Coords { + let gbuf = inp.gbuf; + let mut coords = match gbuf.surface(inp.mesh, (y * gbuf.width + x) as usize) { + Some(surface) => { + let (center, radius) = mesh_frame(inp.bounds); + Coords { uv: surface.uv, pos: (surface.pos - center) / radius, nrm: surface.nrm } + } + None => Coords { uv: Vec2::new((x as f32 + 0.5) / gbuf.width as f32, (y as f32 + 0.5) / gbuf.height as f32), pos: Vec3::ZERO, nrm: Vec3::Y }, + }; + + // UV-tiled sets: projections see the mesh's own UVs (patterns repeat per tile) + if let Ok(set) = inp.project.texture_set(inp.ts) + && let Some(grid) = set.tile_grid() + { + coords.uv = Vec2::from(set.from_atlas(&grid, coords.uv.to_array())); + } + coords +} + +/// What a generator's texture or custom grunge reads with nothing in its slot +const EMPTY_IMAGE_SLOT: Source = Source::Uniform([0.0; 3]); + +/// The step Safe Rotation turns a Grayscale Conversion image by, so it keeps tiling seamlessly +const QUARTER_TURN_DEGREES: f32 = 90.0; + +/// Values per texel of a generator stage's region: the stack below, the generator's ramp and its texture's gray +const GENERATOR_STAGE_COMPONENTS: usize = 3; + +/// The mask over a region after a generator at its own resolution and blur: `stack` is (stack below, generator ramp, texture gray) per texel, sizes in texels per side fn generator_region( generator: &Generator, blend: BlendMode, @@ -1943,7 +1993,7 @@ fn generator_region( (uv_tile, texture_set): (u32, u32), ) -> Vec { let (columns, rows) = (width as usize, height as usize); - let mut ramps: Vec = stack.par_chunks(2).map(|texel| texel.get(1).copied().unwrap_or(0.0)).collect(); + let mut ramps: Vec = stack.par_chunks(GENERATOR_STAGE_COMPONENTS).map(|texel| texel.get(1).copied().unwrap_or(0.0)).collect(); // Coarser than the UV tile: averaged over cells, then the blur around them let cell = generator.resolution.cell(uv_tile, texture_set) as usize; @@ -1951,22 +2001,24 @@ fn generator_region( ramps = resampled_by_cells(&ramps, cover, (region_x as usize, region_y as usize, columns, rows), cell); } - let blur_radius = generator.global.blur_radius_at(uv_tile).round() as usize; - if blur_radius > 0 { - let mut weights = cover.to_vec(); - blur(&mut weights, columns, rows, blur_radius); - let mut sums: Vec = ramps.iter().zip(cover).map(|(ramp, covered)| ramp * covered).collect(); - blur(&mut sums, columns, rows, blur_radius); - ramps.par_iter_mut().zip(sums.par_iter().zip(weights.par_iter())).for_each(|(ramp, (sum, weight))| { - if *weight > MIN_READ_WEIGHT { - *ramp = sum / weight; - } + // The section controls act on the signal before the global blur, their own blur first + if let Some(section) = generator.section_controls() { + blur_over_cover(&mut ramps, cover, (columns, rows), sections::blur_radius_at(generator.kind, §ion, uv_tile)); + ramps.par_iter_mut().for_each(|signal| *signal = sections::adjusted(generator.kind, §ion, *signal)); + } + + // The texture blends over the adjusted signal, before the global blur + if let Some(texture) = generator.texture_in_use() { + ramps.par_iter_mut().zip(stack.par_chunks(GENERATOR_STAGE_COMPONENTS)).for_each(|(signal, texel)| { + *signal = texture_layer::blended_over(texture, *signal, texel.get(2).copied().unwrap_or(0.0)); }); } + blur_over_cover(&mut ramps, cover, (columns, rows), generator.applied_global().blur_radius_at(uv_tile).round() as usize); + // Finished and blended over the stack below, like the generator effect itself stack - .par_chunks(2) + .par_chunks(GENERATOR_STAGE_COMPONENTS) .zip(ramps.par_iter()) .map(|(texel, ramp)| { let below = texel.first().copied().unwrap_or(0.0); @@ -1976,6 +2028,23 @@ fn generator_region( .collect() } +/// `values` blurred by three box passes of `radius`, weighted by `cover` so uncovered texels don't bleed in +fn blur_over_cover(values: &mut [f32], cover: &[f32], (columns, rows): (usize, usize), radius: usize) { + if radius == 0 { + return; + } + + let mut weights = cover.to_vec(); + blur(&mut weights, columns, rows, radius); + let mut sums: Vec = values.iter().zip(cover).map(|(value, covered)| value * covered).collect(); + blur(&mut sums, columns, rows, radius); + values.par_iter_mut().zip(sums.par_iter().zip(weights.par_iter())).for_each(|(value, (sum, weight))| { + if *weight > MIN_READ_WEIGHT { + *value = sum / weight; + } + }); +} + /// `values` averaged over `cell` × `cell` texel cells on the mesh (`cover`), read back bilinearly between cell centers. fn resampled_by_cells(values: &[f32], cover: &[f32], (region_x, region_y, width, height): (usize, usize, usize, usize), cell: usize) -> Vec { // Cells are aligned to absolute texel positions, so a texel's cell is the same in every region @@ -2035,10 +2104,10 @@ fn resampled_by_cells(values: &[f32], cover: &[f32], (region_x, region_y, width, .collect() } -/// A generator's (possibly blurred) ramp after balance, contrast, invert and offset +/// A generator's (possibly blurred) ramp after balance, contrast, invert and offset (the light controls invert their shading themselves) fn finish_generator(generator: &Generator, ramp: f32) -> f32 { - let value = generator.global.apply(ramp); - let value = if generator.invert { 1.0 - value } else { value }; + let value = generator.applied_global().apply(ramp); + let value = if generator.invert && generator.light.is_none() { 1.0 - value } else { value }; let offset = if generator.offset.is_finite() { generator.offset } else { 0.0 }; (value + offset).clamp(0.0, 1.0) } @@ -2240,7 +2309,8 @@ fn unpremultiply(data: &mut [f32], comps: usize) { /// (and anchors) below it. Cheap when no layer has a blur or sharpen. pub fn neighbourhood_fields(inputs: &Inputs, channels: &[Channel], tiles: &[(u32, u32)]) -> Fields { let projectors = ProjectorDepthCache::default(); - let inputs = EvaluationInputs::new(inputs, &projectors); + let mut inputs = EvaluationInputs::new(inputs, &projectors); + prepare_generators(&mut inputs, None); evaluation_fields(&inputs, &evaluation_channels(&inputs, channels.to_vec()), tiles) } @@ -2258,18 +2328,21 @@ fn fields_of(inp: &EvaluationInputs, channels: &[Channel], (list, around): (&[La let working_width = inp.gbuf.width; let mut order = Vec::new(); - draw_order(inp, list, 0, around.into(), &mut order); + draw_order(inp, list, 0, around.into(), false, &mut order); let ids: Vec = order.iter().map(|(id, _)| *id).collect(); prepare_curvature_sizes(inp, &ids); + let field_mask = + |id, place: DrawPlacement| layer_mask(inp.project, id).filter(|mask| mask.enabled || (place.instance == 0 && inp.sampled_disabled_mask == Some(id))); + // Walk backwards to find the region each Compare needs below its position in the stack let mut below_margin = (0u32, false); let margins: Vec<_> = order .iter() .rev() - .map(|&(id, _)| { + .map(|&(id, place)| { let mask_margin = below_margin; - let effects = layer_mask(inp.project, id).filter(|mask| mask.enabled).map(|mask| mask.effects.as_slice()).unwrap_or_default(); + let effects = field_mask(id, place).map(|mask| mask.effects.as_slice()).unwrap_or_default(); let first_reader = effects.iter().filter(|effect| effect.visible).position(|effect| effect.kind.reads_stack()); if let Some(first_reader) = first_reader { for (index, radius, op) in neighbourhood_filters(effects, inp.tile_res(), None).filter(|(index, _, _)| *index > first_reader) { @@ -2285,7 +2358,7 @@ fn fields_of(inp: &EvaluationInputs, channels: &[Channel], (list, around): (&[La for ((id, place), (mask_margin, content_margin)) in order.into_iter().zip(margins.into_iter().rev()) { let Some(layer) = inp.project.content_layer(id) else { continue }; - let mask = layer_mask(inp.project, id).filter(|mask| mask.enabled && neighbourhood(&mask.effects, working_width).is_some()); + let mask = field_mask(id, place).filter(|mask| neighbourhood(&mask.effects, working_width).is_some()); // A mask comparing its own layer needs that layer's filtered content first let compares_content = mask.is_some_and(|mask| mask.effects.iter().any(|effect| effect.visible && compares_this_layer(&effect.kind))); @@ -2351,19 +2424,193 @@ fn compares_this_layer(kind: &EffectKind) -> bool { matches!(kind, EffectKind::Compare { left, right, .. } if *left == CompareSource::ThisLayer || *right == CompareSource::ThisLayer) } -/// Build the curvature detail sizes every visible generator of `layers` reads, once, before tiles composite in parallel. -fn prepare_curvature_sizes(inp: &Inputs, layers: &[LayerId]) { +/// Build the curvature detail sizes every visible generator of `layers` reads, once, before tiles composite in parallel +fn prepare_curvature_sizes(inp: &EvaluationInputs, layers: &[LayerId]) { let visible = layers.iter().filter(|id| inp.project.layers.get(id).is_some_and(|layer| layer.visible)); let masks = visible.filter_map(|id| layer_mask(inp.project, *id)).filter(|mask| mask.enabled); prepare_mask_curvature_sizes(inp, masks); } -/// Build the curvature detail sizes the visible generators of `masks` read, once, before tiles composite in parallel. -fn prepare_mask_curvature_sizes<'a>(inp: &Inputs, masks: impl Iterator) { - let mut needed = [false; CurvatureDetail::BLURRED_SIZES]; +/// Retain up to this many bytes of whole-map fields while planning tiles +const EVALUATION_FIELD_BYTES: usize = 256 << 20; + +/// Generators whose fitted signal depends on a precomputed whole-atlas field +fn whole_map_generator(kind: GeneratorKind) -> bool { + matches!(kind, GeneratorKind::UvBorderDistance | GeneratorKind::DrippingRust | GeneratorKind::UvRandomColor | GeneratorKind::UvChecker) +} + +/// A requested mask beneath a hidden folder probes the visible stack before that folder +fn requested_mask_stop(inp: &EvaluationInputs, id: LayerId) -> LayerId { + let mut stop = id; + let mut current = id; + for _ in 0..texturecraft_core::project::MAX_DEPTH { + let Some((_, Some(parent), _)) = inp.project.locate(current) else { break }; + if inp.project.layers.get(&parent).is_some_and(|layer| !layer.visible) { + stop = parent; + } + current = parent; + } + stop +} + +/// Prepare whole-map fields and build Micro Height maps from bottom to top +fn prepare_generators(inp: &mut EvaluationInputs, requested_mask: Option) { + let Ok(set) = inp.project.texture_set(inp.ts) else { return }; + let requested_stop = requested_mask.map(|id| requested_mask_stop(inp, id)); + let mut order = Vec::new(); + draw_order(inp, &set.stack, 0, ContentsOffset::NONE.into(), true, &mut order); + + let mut anchors_below = HashMap::new(); + let mut first_readers = HashMap::new(); + let mut generators_by_anchor = HashMap::<_, BTreeMap<_, _>>::new(); + let mut considered_fields = HashSet::new(); + let mut retained_fields = HashSet::new(); + let field_bytes = (inp.gbuf.width as usize).saturating_mul(inp.gbuf.height as usize).saturating_mul(size_of::()); + let mut retained_bytes = 0usize; + + for (index, &(id, place)) in order.iter().enumerate() { + let visible = inp.project.layers.get(&id).is_some_and(|layer| layer.visible); + let draw = (id, place.instance); + let masks = visible + .then_some((draw, id)) + .into_iter() + .chain(requested_mask.filter(|_| requested_stop == Some(id) && place.instance == 0 && !visible).map(|reader| ((reader, 0), reader))); + for (reader_draw, reader) in masks { + // Clone and smudge explicitly sample disabled masks + let requested = reader_draw.1 == 0 && requested_mask == Some(reader); + let effects = layer_mask(inp.project, reader).filter(|mask| mask.enabled || requested).into_iter().flat_map(|mask| &mask.effects); + for effect in effects.filter(|effect| effect.visible) { + let EffectKind::Generator(generator) = &effect.kind else { continue }; + + if let Some(anchor) = micro_height_anchor(generator) + && let Some(anchor_index) = anchors_below.get(&anchor) + { + inp.anchor_readers.insert((reader_draw, anchor), *anchor_index); + first_readers.entry((anchor, *anchor_index)).or_insert(draw); + generators_by_anchor.entry((anchor, *anchor_index)).or_default().insert(effect.id, generator); + } + + if whole_map_generator(generator.kind) + && retained_bytes.saturating_add(field_bytes) <= EVALUATION_FIELD_BYTES + && considered_fields.insert(effect.id) + { + let maps = GeneratorMaps::of(inp, generator, &curvature_sizes_in_use(generator), None, || inp.field_identity()); + if let Some(field) = &maps.field + && retained_fields.insert(Arc::as_ptr(field)) + { + retained_bytes += field_bytes; + } + inp.whole_maps.insert(effect.id, maps); + } + } + } + + if visible { + let mask_effects = layer_mask(inp.project, id).filter(|mask| mask.enabled).into_iter().flat_map(|mask| &mask.effects); + let content_effects = inp.project.content_layer(id).filter(|layer| !layer.is_group()).into_iter().flat_map(|layer| &layer.content_effects); + for effect in content_effects.chain(mask_effects).filter(|effect| effect.visible && matches!(effect.kind, EffectKind::Anchor)) { + anchors_below.insert(effect.id, index); + } + } + } + + if inp.is_session_stack() { + inp.projectors.micro_heights.retain_readers(inp.ts, &first_readers.keys().copied().collect::>()); + } + + if first_readers.is_empty() { + return; + } + + let mut readers: Vec<_> = first_readers.into_iter().collect(); + readers.sort_unstable_by_key(|((anchor, index), _)| (*index, *anchor)); + let stack = (inp.is_session_stack() && inp.preview.is_none()) + .then(|| StackKey::new(inp.project, inp.pixels, inp.baked, inp.images, inp.ts, &set.stack).map(Arc::new)) + .flatten(); + + for ((anchor, index), draw) in readers { + let build = || anchor_heights(inp, draw, anchor); + let heights = match &stack { + Some(stack) => inp.projectors.micro_heights.get_or_build(inp, (anchor, index), stack, build), + None => Arc::new(build()), + }; + if let Some(generators) = generators_by_anchor.remove(&(anchor, index)) { + for (id, generator) in generators { + let maps = GeneratorMaps::of(inp, generator, &curvature_sizes_in_use(generator), Some(heights.clone()), || inp.field_identity()); + inp.anchor_maps.insert((id, index), maps); + } + } + } +} + +fn micro_height_anchor(generator: &Generator) -> Option { + let micro = generator.micro_in_use().filter(|micro| micro.height)?; + match µ.height_source { + Some(Source::Anchor { anchor, .. }) => Some(*anchor), + _ => None, + } +} + +/// Anchor point `anchor`'s height over the whole texture set as layer `reader` reads it, in the working atlas's layout +fn anchor_heights(inp: &EvaluationInputs, reader: (LayerId, usize), anchor: LayerId) -> AnchorHeights { + let (width, height) = (inp.gbuf.width, inp.gbuf.height); + let channels = evaluation_channels(inp, vec![Channel::Height]); + let fields = evaluation_fields(inp, &channels, &all_tiles(width, height)); + let width_usize = width as usize; + let tile_side = TILE as usize; + let mut data = vec![0.0f32; width_usize * height as usize]; + + // Each tile row writes its own atlas rows + data.par_chunks_mut(width_usize.max(1) * tile_side).enumerate().for_each(|(tile_y, rows)| { + for tile_x in 0..width.div_ceil(TILE) { + let nodes = below_plan(inp, reader, &channels, (tile_x, tile_y as u32), Some(&fields), true); + let preview = inp.preview.and_then(|preview| preview.alpha.tile(tile_x, tile_y as u32)); + for (x, y, offset) in tile_texels(inp.gbuf, tile_x, tile_y as u32) { + let mut texel = Texel::new(inp, x, y, offset, stroke_at(preview, offset)); + texel.anchors_below(&nodes, reader); + if let Some(destination) = rows.get_mut((y as usize % tile_side) * width_usize + x as usize) { + *destination = texel.anchored(anchor, Channel::Height)[0]; + } + } + } + }); + AnchorHeights::new(data, (width, height), inp.block_scales.clone()) +} + +/// The blurred curvature levels `generator` reads: its wear's smoothing, else its detail sizes (a replaced curvature input reads none) +fn curvature_sizes_in_use(generator: &Generator) -> [bool; LEVEL_RADII.len()] { + if generator.inputs.contains_key(&BakedMap::Curvature) { + return [false; LEVEL_RADII.len()]; + } + + if let Some(wear) = wear_parameters(generator) { + return wear::levels_in_use(generator.kind, &wear); + } + + let detail = generator.detail_in_use().as_ref().map(CurvatureDetail::blurred_sizes_in_use).unwrap_or_default(); + std::array::from_fn(|level| detail.get(level).copied().unwrap_or(false)) +} + +/// The wear controls `generator` computes with: its own, Fiber Glass Edge Wear's defaults when it has none (it has no earlier model), else None +fn wear_parameters(generator: &Generator) -> Option { + generator.wear.or_else(|| WearParameters::defaults(generator.kind).filter(|_| generator.kind == GeneratorKind::FiberGlassEdgeWear)) +} + +/// Build the curvature detail sizes the visible generators of `masks` read, once, before tiles composite in parallel +fn prepare_mask_curvature_sizes<'a>(inp: &EvaluationInputs, masks: impl Iterator) { + let mut needed = [false; LEVEL_RADII.len()]; for effect in masks.flat_map(|mask| &mask.effects).filter(|effect| effect.visible) { - if let EffectKind::Generator(Generator { detail: Some(detail), .. }) = &effect.kind { - for (slot, in_use) in needed.iter_mut().zip(detail.blurred_sizes_in_use()) { + if let EffectKind::Generator(generator) = &effect.kind { + if micro_height_anchor(generator).is_some() || inp.whole_maps.contains_key(&effect.id) { + continue; + } + + if generator.micro_in_use().is_some() || whole_map_generator(generator.kind) { + GeneratorMaps::of(inp, generator, &curvature_sizes_in_use(generator), None, || inp.field_identity()); + continue; + } + + for (slot, in_use) in needed.iter_mut().zip(curvature_sizes_in_use(generator)) { *slot |= in_use; } } @@ -2395,7 +2642,8 @@ fn effect_plans<'a>( tile_x: u32, tile_y: u32, channel: Option, - around: ContentsOffset, + place: DrawPlacement, + id: LayerId, ) -> Vec> { effects .iter() @@ -2405,14 +2653,20 @@ fn effect_plans<'a>( Some(channel) => (inp.pixels.layer(effect.id, channel), PaintTarget::Layer(effect.id)), None => (inp.pixels.masks.get(&effect.id), PaintTarget::Mask(effect.id)), }; - let curvature_sizes = match &effect.kind { - EffectKind::Generator(Generator { detail: Some(detail), .. }) => CurvatureSizes::of(inp, &detail.blurred_sizes_in_use()), - _ => None, + let maps = match &effect.kind { + EffectKind::Generator(generator) => { + let maps = micro_height_anchor(generator) + .and_then(|anchor| inp.anchor_readers.get(&((id, place.instance), anchor))) + .and_then(|index| inp.anchor_maps.get(&(effect.id, *index))) + .or_else(|| inp.whole_maps.get(&effect.id)); + maps.cloned().unwrap_or_else(|| GeneratorMaps::of(inp, generator, &curvature_sizes_in_use(generator), None, || inp.field_identity())) + } + _ => GeneratorMaps::default(), }; let (depth, covers_all, projection) = match &effect.kind { EffectKind::Fill { projection, sampling, .. } | EffectKind::Material(Fill { projection, sampling, .. }) => { let (depth, covers_all) = fill_coverage(inp, projection, *sampling); - (depth, covers_all, (!around.is_none()).then(|| around.apply(projection))) + (depth, covers_all, (!place.offset.is_none()).then(|| place.offset.apply(projection))) } _ => (None, false, None), }; @@ -2437,7 +2691,7 @@ fn effect_plans<'a>( opacity: blend.opacity, data: if effect.kind.painted() { tile_of(inp, image, tile_x, tile_y, channel) } else { None }, preview: previews(inp, target), - curvature_sizes, + maps, filtered_mask: None, depth, covers_all, @@ -2481,21 +2735,9 @@ fn tile_of<'a>(inp: &Inputs, img: Option<&'a TileImage>, tx: u32, ty: u32, chann } /// The plan of layer `id`'s `mask` for tile (tx, ty), its fills under the Scale and Rotation `around` of the folders holding the layer -fn mask_plan<'a>( - inp: &EvaluationInputs<'a>, - id: LayerId, - mask: &'a Mask, - tx: u32, - ty: u32, - fields: Option<&'a Fields>, - place: DrawPlacement, -) -> Option> { - if !mask.enabled { - return None; - } - +fn mask_plan<'a>(inp: &EvaluationInputs<'a>, id: LayerId, mask: &'a Mask, tx: u32, ty: u32, fields: Option<&'a Fields>, place: DrawPlacement) -> MaskPlan<'a> { let background = if mask.background == MaskBackground::White { 1.0 } else { 0.0 }; - let mut effects = effect_plans(inp, &mask.effects, tx, ty, None, place.offset); + let mut effects = effect_plans(inp, &mask.effects, tx, ty, None, place, id); let filtered = fields.and_then(|fields| FieldKey::mask(id, place.offset).field(fields, place.instance)); for (index, effect) in effects.iter_mut().enumerate() { effect.filtered_mask = filtered.and_then(|field| field.anchor_stages.iter().find(|(stage, _)| *stage == index).map(|(_, field)| field)); @@ -2510,7 +2752,7 @@ fn mask_plan<'a>( } else { inp.project.content_layer(id).and_then(|l| plan_content(inp, id, l, &compared, tx, ty, 0, fields, false, place, None)) }; - Some(MaskPlan { background, effects, layer, start }) + MaskPlan { background, effects, layer, start } } /// The plans of sibling layers `list` (under the Scale and Rotation of the folders holding them) @@ -2577,7 +2819,7 @@ fn plan_node<'a>( } let (content, chans) = plan_content(inp, id, layer, channels, tx, ty, depth, fields, kids, place, stop)?; - let mask = layer_mask(inp.project, id).and_then(|m| mask_plan(inp, id, m, tx, ty, fields, place)); + let mask = layer_mask(inp.project, id).filter(|mask| mask.enabled).map(|mask| mask_plan(inp, id, mask, tx, ty, fields, place)); // Anchors in the mask record even where the layer draws nothing let mask_anchor = mask.as_ref().is_some_and(|m| m.effects.iter().any(|e| matches!(*e.kind, EffectKind::Anchor))); @@ -2641,7 +2883,7 @@ fn plan_content<'a>( } let data = if paint { tile_of(inp, inp.pixels.layer(layer.id, *c), tx, ty, Some(*c)) } else { None }; - let effects = if has_content_effects { effect_plans(inp, &layer.content_effects, tx, ty, Some(*c), place.offset) } else { Vec::new() }; + let effects = if has_content_effects { effect_plans(inp, &layer.content_effects, tx, ty, Some(*c), place, id) } else { Vec::new() }; let start = fields .and_then(|fields| FieldKey::content(id, *c, place.offset).field(fields, place.instance)) .and_then(|field| neighbourhood_filters(&layer.content_effects, inp.tile_res(), Some(*c)).last().map(|(index, _, _)| (index, field))); @@ -3276,26 +3518,84 @@ impl<'a, 'b> Texel<'a, 'b> { if needs_gray { [lum(value); 3] } else { value } } - fn generator_ramp(&mut self, generator: &Generator, curvature_sizes: Option<&CurvatureSizes>) -> f32 { + /// The generator's ramp at this texel, before its global blur, balance, contrast and invert (on the section controls, before those too). + fn generator_ramp(&mut self, generator: &Generator, maps: &GeneratorMaps) -> f32 { + if let Some(wear) = wear_parameters(generator) { + return self.wear_ramp(generator, &wear, maps); + } + + if let Some(light) = &generator.light { + let normal = + self.generator_input_color(generator, BakedMap::WorldNormal).map_or_else(|| self.coords().nrm, |encoded| Vec3::from(encoded) * 2.0 - 1.0); + let position = Vec3::from(self.position_input(generator)); + return sections::light_value(light, normal, position, generator.invert); + } + + if let Some(section) = generator.section_controls() { + return self.section_signal(generator, §ion, maps); + } + + // The kinds with only their own controls: resolved once per plan, not per texel + let resolved; + let controls = match maps.controls.as_deref() { + Some(controls) => Some(controls), + None => { + resolved = generator.kind_controls(); + resolved.as_ref() + } + }; + match controls { + Some(KindControls::Distance(distance)) => { + let position = self.uniform_position_input(generator); + return three_d_distance::distance_value(distance, position); + } + Some(KindControls::LinearGradient(gradient)) => { + let position = self.uniform_position_input(generator); + return three_d_distance::linear_gradient_value(gradient, position); + } + Some(KindControls::BorderDistance(border)) => return uv_border_distance::border_value(border, self.field_value(maps)), + Some(KindControls::Grayscale(grayscale)) => return self.grayscale_conversion(grayscale), + Some(KindControls::DrippingRust(rust)) => return dripping_rust::rust_value(rust, self.field_value(maps)), + Some(KindControls::UvRandomColor(_) | KindControls::UvChecker(_)) => return self.field_value(maps), + None => {} + } + let coords = self.coords(); - let micro = generator.micro.map_or(0.0, |micro| self.micro_detail(generator.kind, micro)); + let earlier_micro = generator.earlier_micro().map_or(0.0, |(anchor, amount)| self.earlier_micro_detail(generator.kind, anchor, amount)); + + // Micro details saved on the earlier model add to its curvature and occlusion inputs too let signal = match (generator.kind, &generator.detail) { (GeneratorKind::Curvature | GeneratorKind::EdgeWear, Some(detail)) => { // Detail sizes are blurred copies of the mesh map, so a replaced curvature input reads at its own size only - let sizes = if generator.inputs.contains_key(&BakedMap::Curvature) { None } else { curvature_sizes }; - let curvature = self.generator_input(generator, BakedMap::Curvature); - self.curvature_detail(detail, sizes, curvature, micro) + let sizes = if generator.inputs.contains_key(&BakedMap::Curvature) { None } else { maps.sizes.as_deref() }; + let curvature = self.curvature_input(generator, maps); + self.curvature_detail(detail, sizes, curvature, earlier_micro) } - (GeneratorKind::EdgeWear, None) => (self.generator_input(generator, BakedMap::Curvature).unwrap_or(0.5) - 0.5) * 2.0, - (GeneratorKind::Curvature, None) => self.generator_input(generator, BakedMap::Curvature).unwrap_or(0.5), - (GeneratorKind::Dirt, _) => 1.0 - self.generator_input(generator, BakedMap::AmbientOcclusion).unwrap_or(1.0), - (GeneratorKind::AmbientOcclusion, _) => self.generator_input(generator, BakedMap::AmbientOcclusion).unwrap_or(1.0), + (GeneratorKind::EdgeWear, None) | (GeneratorKind::FiberGlassEdgeWear, _) => (self.curvature_input(generator, maps).unwrap_or(0.5) - 0.5) * 2.0, + (GeneratorKind::Curvature, None) => self.curvature_input(generator, maps).unwrap_or(0.5), + (GeneratorKind::Dirt, _) => 1.0 - self.occlusion_input(generator, maps).unwrap_or(1.0), + (GeneratorKind::AmbientOcclusion, _) => self.occlusion_input(generator, maps).unwrap_or(1.0), (GeneratorKind::ThinAreas, _) => 1.0 - self.generator_input(generator, BakedMap::Thickness).unwrap_or(1.0), (GeneratorKind::Position, _) => coords.pos.dot(Vec3::from(generator.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, (GeneratorKind::Direction, _) => coords.nrm.dot(Vec3::from(generator.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, + // World Space Normals and 3D Distance always compute with their own controls: these arms only keep the match whole + (GeneratorKind::WorldSpaceNormals, _) => coords.nrm.y * 0.5 + 0.5, + ( + GeneratorKind::ThreeDDistance + | GeneratorKind::ThreeDLinearGradient + | GeneratorKind::UvBorderDistance + | GeneratorKind::GrayscaleConversion + | GeneratorKind::DrippingRust + | GeneratorKind::UvRandomColor + | GeneratorKind::UvChecker, + _, + ) => 0.0, + }; + let signal = if matches!(generator.kind, GeneratorKind::Curvature | GeneratorKind::EdgeWear) && generator.detail.is_some() { + signal + } else { + signal + earlier_micro }; - let signal = - if matches!(generator.kind, GeneratorKind::Curvature | GeneratorKind::EdgeWear) && generator.detail.is_some() { signal } else { signal + micro }; let signal = if generator.noise_amount > 0.0 { let noise = world_noise(coords.pos, generator.noise_scale, generator.seed); if let (GeneratorKind::Curvature | GeneratorKind::EdgeWear, Some(detail)) = (generator.kind, &generator.detail) { @@ -3316,26 +3616,218 @@ impl<'a, 'b> Texel<'a, 'b> { ramp * ramp * (3.0 - 2.0 * ramp) } - /// How a generator's micro detail moves its signal at this texel: the anchor's height (0 where - /// the anchor is not evaluated yet) as an edge where raised and a cavity where recessed. - fn micro_detail(&self, kind: GeneratorKind, micro: MicroDetail) -> f32 { - let height = self.anchor_value(micro.anchor, Channel::Height, ChannelKind::Signed)[0]; - let amount = if micro.amount.is_finite() { micro.amount.clamp(0.0, 1.0) } else { 0.0 }; - let response = height.clamp(-1.0, 1.0) * amount; - match kind { - GeneratorKind::Curvature | GeneratorKind::EdgeWear => response, + /// The signal a generator on its section controls adjusts at this texel: the axes of its map, its curvature or its occlusion + fn section_signal(&mut self, generator: &Generator, section: &SectionParameters, maps: &GeneratorMaps) -> f32 { + match generator.kind { + GeneratorKind::Curvature => { + let detail = generator.detail_in_use().unwrap_or_default(); + let sizes = if generator.inputs.contains_key(&BakedMap::Curvature) { None } else { maps.sizes.as_deref() }; + let curvature = self.curvature_input(generator, maps); + self.curvature_detail(&detail, sizes, curvature, 0.0) + } + GeneratorKind::AmbientOcclusion => self.occlusion_input(generator, maps).unwrap_or(1.0), + GeneratorKind::Position => { + let position = self.position_input(generator); + sections::axes_signal(position, §ion.axes) + } + GeneratorKind::WorldSpaceNormals => { + let normal = self.generator_input_color(generator, BakedMap::WorldNormal).unwrap_or_else(|| (self.coords().nrm * 0.5 + 0.5).to_array()); + sections::axes_signal(normal, §ion.axes) + } - // Dirt gathers in dents; dents are occluded - GeneratorKind::Dirt => -response, - GeneratorKind::AmbientOcclusion => response, - GeneratorKind::ThinAreas | GeneratorKind::Position | GeneratorKind::Direction => 0.0, + // Other kinds use their own evaluator + GeneratorKind::EdgeWear + | GeneratorKind::Dirt + | GeneratorKind::ThinAreas + | GeneratorKind::Direction + | GeneratorKind::FiberGlassEdgeWear + | GeneratorKind::ThreeDDistance + | GeneratorKind::ThreeDLinearGradient + | GeneratorKind::UvBorderDistance + | GeneratorKind::GrayscaleConversion + | GeneratorKind::DrippingRust + | GeneratorKind::UvRandomColor + | GeneratorKind::UvChecker => 0.0, } } - /// The generator's value at this texel: its ramp finished by balance, contrast, invert and offset (its blur and resolution need neighbours: see [`generator_region`]). - fn generator(&mut self, generator: &Generator, curvature_sizes: Option<&CurvatureSizes>) -> f32 { - let ramp = self.generator_ramp(generator, curvature_sizes); - finish_generator(generator, ramp) + /// The image in `generator`'s Position input, else this texel's position across the mesh's bounds: the baked Position map is not read, its normalisation is a bake setting + fn position_input(&mut self, generator: &Generator) -> [f32; 3] { + match generator.inputs.get(&BakedMap::Position) { + Some(source) => self.source(source, &Projection::default(), Sampling::default(), ChannelKind::NormalMap), + None => self.bounds_position().to_array(), + } + } + + /// A generator's whole-map field at this texel (0 without one) + fn field_value(&self, maps: &GeneratorMaps) -> f32 { + let texel = (self.y * self.inp.gbuf.width + self.x) as usize; + maps.field.as_ref().and_then(|field| field.get(texel)).copied().unwrap_or(0.0) + } + + /// The Grayscale Conversion generator at this texel: its image tiled and turned about the UV square's centre, made gray, balanced and contrasted + fn grayscale_conversion(&mut self, grayscale: &GrayscaleConversionParameters) -> f32 { + let degrees = if grayscale.safe_rotation { (grayscale.rotation / QUARTER_TURN_DEGREES).round() * QUARTER_TURN_DEGREES } else { grayscale.rotation }; + let (sin, cos) = degrees.to_radians().sin_cos(); + let centred = self.coords().uv - Vec2::splat(0.5); + let at = Vec2::new(centred.x * cos - centred.y * sin, centred.x * sin + centred.y * cos) * grayscale.tile + Vec2::splat(0.5); + let rgb = match grayscale.source.as_ref().unwrap_or(&EMPTY_IMAGE_SLOT) { + Source::Image { name, .. } => self.inp.images.get(name).map_or([0.0; 3], |image| { + let [red, green, blue, _] = image.sample(at.x, at.y); + [red, green, blue] + }), + other => self.source(other, &Projection::default(), Sampling::default(), ChannelKind::NormalMap), + }; + let gray = grayscale.grayscale.gray(rgb).clamp(0.0, 1.0); + GeneratorGlobal { balance: grayscale.balance, contrast: grayscale.contrast, ..GeneratorGlobal::default() }.apply(gray) + } + + /// The image in `generator`'s Position input, else this texel's position across the mesh's bounds scaled evenly: the longest side spans 0..1, the others centred on 0.5 + fn uniform_position_input(&mut self, generator: &Generator) -> Vec3 { + if let Some(source) = generator.inputs.get(&BakedMap::Position) { + return Vec3::from(self.source(source, &Projection::default(), Sampling::default(), ChannelKind::NormalMap)); + } + + let (low, high) = self.inp.bounds; + let longest = (high - low).max_element().max(MIN_BOUNDS_EXTENT); + self.world().map_or(Vec3::splat(0.5), |position| (position - (low + high) * 0.5) / longest + Vec3::splat(0.5)) + } + + /// This texel's world position across the mesh's bounds, 0..1 on each axis (0 where uncovered) + fn bounds_position(&self) -> Vec3 { + let (low, high) = self.inp.bounds; + self.world().map_or(Vec3::ZERO, |position| ((position - low) / (high - low).max(Vec3::splat(MIN_BOUNDS_EXTENT))).clamp(Vec3::ZERO, Vec3::ONE)) + } + + /// A wear generator's value at this texel from its curvature, occlusion and grunge, before its global adjustments and invert + fn wear_ramp(&mut self, generator: &Generator, wear: &WearParameters, maps: &GeneratorMaps) -> f32 { + let curvature = self.curvature_input(generator, maps).map_or(0.0, |curvature| curvature - 0.5); + + // Blurred levels are copies of the mesh map, so a replaced curvature input is read at its own size only + let sizes = if generator.inputs.contains_key(&BakedMap::Curvature) { None } else { maps.sizes.as_deref() }; + let blurred_curvature = self.blurred_curvature(wear::blur_sigma(generator.kind, wear), sizes, curvature); + + let occlusion = self.occlusion_input(generator, maps).unwrap_or(1.0); + let grunge = if wear.custom_grunge { + // An image not loaded yet reads mid gray, which leaves the wear as without grunge + let gray = self.slot_color(generator, generator.grunge.as_ref(), &wear::custom_grunge_placement(wear)).map_or(0.5, lum); + wear::custom_grunge(generator.kind, gray) + } else { + wear::grunge(generator.kind, wear, generator.seed, &self.coords()) + }; + wear::wear_value(generator.kind, wear, &WearInputs { curvature, blurred_curvature, occlusion, grunge }) + } + + /// The curvature deviation at this texel blurred to `sigma` (texels at 2K) between the two built levels around it; `curvature` without them + fn blurred_curvature(&self, sigma: f32, curvature_sizes: Option<&CurvatureSizes>, curvature: f32) -> f32 { + let Some((sizes, (baked_x, baked_y))) = curvature_sizes.zip(self.baked_curvature_texel()) else { return curvature }; + + let level = |index: usize| sizes.levels.get(index).and_then(Option::as_deref).map(|level| level.sample(baked_x, baked_y)); + let (narrower, wider, weight) = wear::levels_around(sigma); + let narrower = narrower.map_or(Some(curvature), level); + match (narrower, level(wider)) { + (Some(narrower), Some(wider)) => narrower + (wider - narrower) * weight, + _ => curvature, + } + } + + /// The baked curvature map's texel under this texel (None outside the baked layout) + fn baked_curvature_texel(&self) -> Option<(u32, u32)> { + let working_size = (self.res, self.inp.gbuf.height); + let texel_uv = [(self.x as f32 + 0.5) / working_size.0.max(1) as f32, (self.y as f32 + 0.5) / working_size.1.max(1) as f32]; + let baked_uv = self.inp.block_scales.bake_uv(texel_uv, working_size)?; + let baked_size = (self.inp.baked.resolution, self.inp.baked.height(BakedMap::Curvature)); + Some(((baked_uv[0] * baked_size.0 as f32) as u32, (baked_uv[1] * baked_size.1 as f32) as u32)) + } + + /// The generator's value at this texel: its ramp finished by balance, contrast, invert and offset (its blur and resolution need neighbours: see [`generator_region`]) + fn generator(&mut self, generator: &Generator, maps: &GeneratorMaps) -> f32 { + let ramp = self.generator_ramp(generator, maps); + let adjusted = generator.section_controls().map_or(ramp, |section| sections::adjusted(generator.kind, §ion, ramp)); + + // An image still loading reads black, as it does where blur or resolution compute the generator over a region + let textured = match generator.texture_in_use() { + Some(texture) => texture_layer::blended_over(texture, adjusted, self.generator_texture(generator).unwrap_or(0.0)), + None => adjusted, + }; + + finish_generator(generator, textured) + } + + /// The gray of the generator's texture at this texel (None when it blends no texture) + fn generator_texture(&mut self, generator: &Generator) -> Option { + let texture = generator.texture_in_use()?; + let rgb = self.slot_color(generator, texture.source.as_ref(), &texture_layer::texture_placement(texture))?; + Some(texture_layer::texture_gray(texture, rgb)) + } + + /// The color of a generator's image slot holding `source` (None: empty, read as black) at this texel, read where `placement` puts it (None when its image isn't loaded) + fn slot_color(&mut self, generator: &Generator, source: Option<&Source>, placement: &texture_layer::SlotPlacement) -> Option<[f32; 3]> { + match source.unwrap_or(&EMPTY_IMAGE_SLOT) { + Source::Image { name, .. } => { + let image = self.inp.images.get(name)?.clone(); + let read = |coordinates: Vec2| { + let [red, green, blue, _] = image.sample(coordinates.x, coordinates.y); + Vec3::new(red, green, blue) + }; + let color = match placement.triplanar_contrast { + Some(contrast) => { + let normal = self + .generator_input_color(generator, BakedMap::WorldNormal) + .map_or_else(|| self.coords().nrm, |encoded| Vec3::from(encoded) * 2.0 - 1.0); + let weights = texture_layer::triplanar_weights(contrast, normal); + let coordinates = texture_layer::triplanar_coordinates(placement, self.bounds_position()); + weights.iter().zip(coordinates).fold(Vec3::ZERO, |sum, (weight, at)| sum + read(at) * *weight) + } + None => read(texture_layer::uv_coordinates(placement, self.coords().uv)), + }; + Some(color.to_array()) + } + + // A value or an anchor reads the same wherever it is projected + other => Some(self.source(other, &Projection::default(), Sampling::default(), ChannelKind::NormalMap)), + } + } + + /// How a micro detail saved before Micro Details moves an earlier-model generator's signal at this texel: anchor point `anchor`'s height times `amount` (0 where the anchor is not evaluated yet), an edge where raised and a cavity where recessed + fn earlier_micro_detail(&self, kind: GeneratorKind, anchor: LayerId, amount: f32) -> f32 { + let response = self.anchor_value(anchor, Channel::Height, ChannelKind::Signed)[0].clamp(-1.0, 1.0) * amount; + match kind { + GeneratorKind::Curvature | GeneratorKind::EdgeWear | GeneratorKind::AmbientOcclusion => response, + + // Dirt gathers in dents + GeneratorKind::Dirt => -response, + + // Kinds the micro detail never moved, or without an earlier model + GeneratorKind::FiberGlassEdgeWear + | GeneratorKind::ThinAreas + | GeneratorKind::Position + | GeneratorKind::Direction + | GeneratorKind::WorldSpaceNormals + | GeneratorKind::ThreeDDistance + | GeneratorKind::ThreeDLinearGradient + | GeneratorKind::UvBorderDistance + | GeneratorKind::GrayscaleConversion + | GeneratorKind::DrippingRust + | GeneratorKind::UvRandomColor + | GeneratorKind::UvChecker => 0.0, + } + } + + /// The generator's curvature input at this texel with what its micro details add + fn curvature_input(&mut self, generator: &Generator, maps: &GeneratorMaps) -> Option { + let curvature = self.generator_input(generator, BakedMap::Curvature)?; + let working_size = (self.res, self.inp.gbuf.height); + let micro = maps.micro_curvature.as_ref().and_then(|micro| micro.term.at((self.x, self.y), working_size, &self.inp.block_scales)); + Some(curvature + micro.unwrap_or(0.0)) + } + + /// The generator's occlusion input at this texel, darkened by its micro details + fn occlusion_input(&mut self, generator: &Generator, maps: &GeneratorMaps) -> Option { + let occlusion = self.generator_input(generator, BakedMap::AmbientOcclusion)?; + let working_size = (self.res, self.inp.gbuf.height); + let micro = maps.micro_occlusion.as_ref().and_then(|micro| micro.at((self.x, self.y), working_size, &self.inp.block_scales)); + Some(occlusion * micro.unwrap_or(1.0)) } /// Generator input `map` at this texel: what replaces the mesh map in the generator's inputs, else the mesh map (None when not baked). @@ -3347,11 +3839,19 @@ impl<'a, 'b> Texel<'a, 'b> { } } - /// The curvature of `detail`'s mode at this texel from `curvature` (None: nothing to read), with its blurred detail sizes when given. - fn curvature_detail(&self, detail: &CurvatureDetail, curvature_sizes: Option<&CurvatureSizes>, curvature: Option, micro: f32) -> f32 { + /// Generator input `map` at this texel as three channels (an encoded normal or position): what replaces the mesh map, else the mesh map (None when not baked) + fn generator_input_color(&mut self, generator: &Generator, map: BakedMap) -> Option<[f32; 3]> { + match generator.inputs.get(&map) { + Some(source) => Some(self.source(source, &Projection::default(), Sampling::default(), ChannelKind::NormalMap)), + None => self.baked_color(map), + } + } + + /// The curvature of `detail`'s mode at this texel from `curvature` (None: nothing to read), with its blurred detail sizes when given and an earlier micro detail's term (see [`Texel::earlier_micro_detail`]) as an edge where positive and a cavity where negative + fn curvature_detail(&self, detail: &CurvatureDetail, curvature_sizes: Option<&CurvatureSizes>, curvature: Option, earlier_micro: f32) -> f32 { let combine = |edges: f32, cavities: f32| { - let edges = 1.0 - (1.0 - edges) * (1.0 - micro.max(0.0)); - let cavities = 1.0 - (1.0 - cavities) * (1.0 + micro.min(0.0)); + let edges = 1.0 - (1.0 - edges) * (1.0 - earlier_micro.max(0.0)); + let cavities = 1.0 - (1.0 - cavities) * (1.0 + earlier_micro.min(0.0)); match detail.mode { CurvatureMode::Edges => edges, CurvatureMode::Cavities => cavities, @@ -3360,15 +3860,10 @@ impl<'a, 'b> Texel<'a, 'b> { } }; - // Without baked curvature, only painted micro height supplies edges or cavities + // Without curvature to read only an earlier micro detail supplies edges or cavities let Some(curvature) = curvature else { return combine(0.0, 0.0) }; + let Some((baked_x, baked_y)) = self.baked_curvature_texel() else { return combine(0.0, 0.0) }; - let working_size = (self.res, self.inp.gbuf.height); - let texel_uv = [(self.x as f32 + 0.5) / working_size.0.max(1) as f32, (self.y as f32 + 0.5) / working_size.1.max(1) as f32]; - let Some(baked_uv) = self.inp.block_scales.bake_uv(texel_uv, working_size) else { return combine(0.0, 0.0) }; - - let baked_size = (self.inp.baked.resolution, self.inp.baked.height(BakedMap::Curvature)); - let (baked_x, baked_y) = ((baked_uv[0] * baked_size.0 as f32) as u32, (baked_uv[1] * baked_size.1 as f32) as u32); let blurred = |index: usize| { curvature_sizes.and_then(|sizes| sizes.levels.get(index)).and_then(Option::as_deref).map_or(0.0, |level| level.sample(baked_x, baked_y)) }; @@ -3455,7 +3950,7 @@ impl<'a, 'b> Texel<'a, 'b> { value += (blend1(effect.blend, value, fill) - value) * opacity * cover; } EffectKind::Generator(generator) => { - let generated = self.generator(generator, effect.curvature_sizes.as_deref()); + let generated = self.generator(generator, &effect.maps); value += (blend1(effect.blend, value, generated) - value) * opacity; } EffectKind::Levels(levels) => value += (levels.apply(value) - value) * opacity, @@ -3974,8 +4469,8 @@ pub fn composite_tiles_cached(inputs: &Inputs, out: &mut Composite, tiles: &[(u3 } let projectors = ProjectorDepthCache::default(); - let inputs = EvaluationInputs::new(inputs, &projectors); - composite_evaluation_tiles(&inputs, out, tiles, below); + let mut inputs = EvaluationInputs::new(inputs, &projectors); + composite_evaluation_tiles(&mut inputs, out, tiles, below); } /// Composite tile batches with a reusable cache for the mesh owned by the caller. @@ -3997,16 +4492,20 @@ pub fn composite_tiles_with_projectors( cache.bind_mesh(mesh); } - let inputs = EvaluationInputs::new(inputs, projectors); - composite_evaluation_tiles(&inputs, out, tiles, below); + let mut inputs = EvaluationInputs::new(inputs, projectors).of_the_session_stack(); + composite_evaluation_tiles(&mut inputs, out, tiles, below); } -fn composite_evaluation_tiles(inp: &EvaluationInputs, out: &mut Composite, tiles: &[(u32, u32)], mut below: Option<&mut BelowCache>) { +fn composite_evaluation_tiles(inp: &mut EvaluationInputs, out: &mut Composite, tiles: &[(u32, u32)], mut below: Option<&mut BelowCache>) { let Ok(set) = inp.project.texture_set(inp.ts) else { return }; if (inp.gbuf.width, inp.gbuf.height) != (out.resolution, out.height) { return; } + if !tiles.is_empty() { + prepare_generators(inp, None); + } + let split = below.as_deref_mut().and_then(|b| b.prepare(inp)); // Avoid caching tiles that would immediately evict each other @@ -4124,7 +4623,7 @@ fn uses_environment(project: &Project, stack: &[LayerId], depth: usize) -> bool fn has_neighbourhood(inp: &EvaluationInputs, stack: &[LayerId]) -> bool { let working_width = inp.gbuf.width; let mut order = Vec::new(); - draw_order(inp, stack, 0, DrawPlacement::default(), &mut order); + draw_order(inp, stack, 0, DrawPlacement::default(), false, &mut order); order.into_iter().any(|(id, _)| { let masked = layer_mask(inp.project, id).is_some_and(|mask| mask.enabled && neighbourhood(&mask.effects, working_width).is_some()); masked || inp.project.content_layer(id).is_some_and(|layer| !layer.is_group() && neighbourhood(&layer.content_effects, working_width).is_some()) @@ -4442,13 +4941,14 @@ pub fn pad_tiles(out: &mut Composite, dmap: &DilationMap, tiles: &[(u32, u32)]) /// Returns None without an enabled mask pub fn mask_texels(inputs: &Inputs, id: LayerId) -> Option> { let projectors = ProjectorDepthCache::default(); - let inputs = &EvaluationInputs::new(inputs, &projectors); + let inputs = &mut EvaluationInputs::new(inputs, &projectors); let mask = layer_mask(inputs.project, id).filter(|mask| mask.enabled)?; let channels = evaluation_channels(inputs, inputs.project.texture_set(inputs.ts).map(|set| set.channel_list()).unwrap_or_default()); let (width, height) = (inputs.gbuf.width, inputs.gbuf.height); let coordinates = all_tiles(width, height); // A hidden layer's mask is left out of the stack's preparation + prepare_generators(inputs, Some(id)); prepare_mask_curvature_sizes(inputs, std::iter::once(mask)); let fields = evaluation_fields(inputs, &channels, &coordinates); @@ -4479,13 +4979,14 @@ pub fn mask_image(inputs: &Inputs, id: LayerId, size: u32) -> Option> { let size = size.max(1); let pixel_count = usize::try_from(size.checked_mul(size)?).ok()?; let projectors = ProjectorDepthCache::default(); - let inputs = &EvaluationInputs::new(inputs, &projectors); + let inputs = &mut EvaluationInputs::new(inputs, &projectors); let mask = layer_mask(inputs.project, id).filter(|mask| mask.enabled)?; let channels = evaluation_channels(inputs, inputs.project.texture_set(inputs.ts).map(|set| set.channel_list()).unwrap_or_default()); let (width, height) = (inputs.gbuf.width, inputs.gbuf.height); let coordinates = all_tiles(width, height); // A hidden layer's mask is left out of the stack's preparation + prepare_generators(inputs, Some(id)); prepare_mask_curvature_sizes(inputs, std::iter::once(mask)); let fields = evaluation_fields(inputs, &channels, &coordinates); @@ -4587,9 +5088,16 @@ pub fn mask_values(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Option /// Evaluate requested tiles directly into the stroke's mask image. pub fn mask_values_into(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)], image: &mut TileImage) -> Option<()> { let projectors = ProjectorDepthCache::default(); - let inputs = &EvaluationInputs::new(inputs, &projectors); + let inputs = &mut EvaluationInputs::new(inputs, &projectors); let mask = layer_mask(inputs.project, id)?; - let channels = evaluation_channels(inputs, inputs.project.texture_set(inputs.ts).ok()?.channel_list()); + inputs.sampled_disabled_mask = (!mask.enabled).then_some(id); + let mut channels = inputs.project.texture_set(inputs.ts).ok()?.channel_list(); + if !mask.enabled { + channels = compared_channels(mask.effects.iter().filter(|effect| effect.visible && effect.kind.reads_stack()), channels); + } + + let channels = evaluation_channels(inputs, channels); + prepare_generators(inputs, Some(id)); prepare_mask_curvature_sizes(inputs, std::iter::once(mask)); let fields = evaluation_fields(inputs, &channels, tiles); @@ -4616,7 +5124,7 @@ pub fn mask_values_into(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)], imag /// Uncovered and out-of-range texels read zero; neighbourhood filters also evaluate surrounding texels pub fn mask_at(inputs: &Inputs, id: LayerId, texels: &[(u32, u32)]) -> Option> { let projectors = ProjectorDepthCache::default(); - let inputs = &EvaluationInputs::new(inputs, &projectors); + let inputs = &mut EvaluationInputs::new(inputs, &projectors); let mask = layer_mask(inputs.project, id).filter(|mask| mask.enabled)?; let mut output = vec![0.0; texels.len()]; @@ -4638,6 +5146,7 @@ pub fn mask_at(inputs: &Inputs, id: LayerId, texels: &[(u32, u32)]) -> Option