mirror of
https://github.com/storytold/texturecraft.git
synced 2026-11-28 17:19:24 +01:00
Auto: Fix headless export options and reduce export memory use
Integrate main and honor per-map sizes and shader sidecars through MCP. Preserve texture writes when an optional sidecar fails, and cover both outcomes through the tool transport. Bound layered PSD working memory, preserve set and UDIM names, and report effective dithering. Match previews to stored channels and identify linear grayscale JP2 samples correctly. Reuse sample buffers, cache unchanged template plans, and share identical grayscale preview textures. Remove the obsolete direct XML dependency. Apply the maintainer’s preset attribution decision and retain the ICC credit and codec notices.
This commit is contained in:
commit
47c6ea8f21
254 files changed
+17857
-1916
No files matched your search
+2
-1
@@ -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
|
||||
|
||||
|
||||
Generated
+1
-1
@@ -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",
|
||||
|
||||
@@ -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"] }
|
||||
|
||||
@@ -28,4 +28,5 @@ getrandom = { workspace = true }
|
||||
rustix = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
rmcp = { workspace = true, features = ["client"] }
|
||||
@@ -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<Value, AutomationError> {
|
||||
pub fn export(&mut self, params: &Value) -> Result<Value, AutomationError> {
|
||||
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<usize> = 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<usize> = 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 }))
|
||||
}
|
||||
|
||||
|
||||
@@ -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<Vec<ExportMapParams>>,
|
||||
/// 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<Value>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
|
||||
|
||||
@@ -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<bool>,
|
||||
/// Side length in pixels for this map, overriding the export size.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub size: Option<u32>,
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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<BakeOutput, BakeError> {
|
||||
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<BakeOutput, BakeError> {
|
||||
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),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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<Option<(f32, f32)>>,
|
||||
}
|
||||
|
||||
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<Option<(f32, f32)>> = 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>), 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<Option<f32>> {
|
||||
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<Item = [usize; 3]>) {
|
||||
// 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<Option<u32>> = reach.iter().map(|distances| distances.map(|_| 0)).collect();
|
||||
let mut queue: VecDeque<usize> = (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");
|
||||
}
|
||||
}
|
||||
@@ -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<u32> {
|
||||
pub(super) fn vertex_keys(mesh: &Mesh, triangle_keys: &[u32]) -> Vec<u32> {
|
||||
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 {
|
||||
|
||||
@@ -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<u32>,
|
||||
pub(super) low_vertices: Vec<u32>,
|
||||
pub(super) high_triangles: Vec<u32>,
|
||||
pub(super) high_vertices: Vec<u32>,
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -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<Vec3>,
|
||||
cage: Option<&'a Mesh>,
|
||||
fitted: Option<FittedCage>,
|
||||
skew: Option<PreparedSkew<'a>>,
|
||||
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<RayFrame<'a>, 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<Vec3> = 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,
|
||||
|
||||
@@ -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),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
+26
-16
@@ -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<T: Clone>(count: usize, value: T) -> Result<Vec<T>, BakeError> {
|
||||
}
|
||||
|
||||
pub fn bake(request: &BakeRequest, progress: &Progress) -> Result<BakeOutput, BakeError> {
|
||||
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<BakeOutput, BakeError> {
|
||||
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<BakeOutput, BakeError> {
|
||||
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<BakeOutput, BakeError> {
|
||||
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<usize> = samples_by_row
|
||||
.iter()
|
||||
.scan(0, |sample_count, row| {
|
||||
@@ -362,11 +369,12 @@ fn bake_rows(
|
||||
true => {
|
||||
let (rays, frontal_distances): (Vec<tracing::Ray>, Vec<f32>) = 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<tracing::Query> = 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<tracing::Hemisphere> = [context.ao, separate_bent_pass, context.thickness].into_iter().flatten().collect();
|
||||
|
||||
@@ -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<Source<'a>>,
|
||||
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<BakeContext<'a>, 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<Hit>, front: f32) -> Option<Transfer> {
|
||||
/// 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<Hit>, front: f32, ray_length: f32) -> Option<Transfer> {
|
||||
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],
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
@@ -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<usize> = 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]
|
||||
|
||||
@@ -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<f32> {
|
||||
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}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -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)),
|
||||
_ => {}
|
||||
}
|
||||
|
||||
@@ -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<Option<Arc<CurvatureSizeLevel>>>,
|
||||
@@ -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<Arc<CurvatureSizes>> {
|
||||
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<Vec<f32>>, needed: &[bool]) -> Option<Arc<CurvatureSizes>> {
|
||||
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..]);
|
||||
}
|
||||
}
|
||||
@@ -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<Vec<f32>> {
|
||||
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<f32> {
|
||||
let gbuf = inp.gbuf;
|
||||
let (width, height) = (gbuf.width, gbuf.height);
|
||||
let cover: Vec<f32> = (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<f32> = (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<f32> = 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<f32>,
|
||||
(width, height): (u32, u32),
|
||||
tile_texels: &(impl Fn(u32, u32) -> f32 + Sync),
|
||||
) -> Vec<f32> {
|
||||
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<usize> {
|
||||
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<f32>, here: f32, after: Option<f32>) -> 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<f32> = (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<f32> =
|
||||
(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");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+1104
-191
File diff suppressed because it is too large.
Load diff
@@ -8,6 +8,7 @@ use super::Inputs;
|
||||
use crate::ProjectorDepthCache;
|
||||
use crate::environment_sh::EnvironmentSh;
|
||||
use crate::fill_depth::FillDepth;
|
||||
use crate::generator_maps::GeneratorMaps;
|
||||
use crate::pattern::mesh_frame;
|
||||
use crate::projector_depth_cache::ViewDepth;
|
||||
use crate::projector_view::ProjectorView;
|
||||
@@ -17,11 +18,19 @@ const MAX_EVALUATION_VIEWS: usize = 10;
|
||||
|
||||
pub(super) struct EvaluationInputs<'a> {
|
||||
inputs: &'a Inputs<'a>,
|
||||
projectors: &'a ProjectorDepthCache,
|
||||
pub(super) projectors: &'a ProjectorDepthCache,
|
||||
environment: OnceLock<EnvironmentSh>,
|
||||
instance_draws: OnceLock<HashMap<(usize, LayerId), usize>>,
|
||||
depth_maps: Mutex<Vec<ViewDepth>>,
|
||||
/// The disabled mask being sampled directly by clone or smudge
|
||||
pub(super) sampled_disabled_mask: Option<LayerId>,
|
||||
pub(super) anchor_readers: HashMap<((LayerId, usize), LayerId), usize>,
|
||||
pub(super) whole_maps: HashMap<LayerId, GeneratorMaps>,
|
||||
pub(super) anchor_maps: HashMap<(LayerId, usize), GeneratorMaps>,
|
||||
gradients: Mutex<HashMap<usize, Arc<PreparedGradient>>>,
|
||||
field_geometry: OnceLock<u64>,
|
||||
/// The project is the session's own stack as the viewport composites it, not one cut down (a histogram's, a thumbnail's, a solo layer's)
|
||||
session_stack: bool,
|
||||
}
|
||||
|
||||
impl<'a> EvaluationInputs<'a> {
|
||||
@@ -32,10 +41,31 @@ impl<'a> EvaluationInputs<'a> {
|
||||
environment: OnceLock::new(),
|
||||
instance_draws: OnceLock::new(),
|
||||
depth_maps: Mutex::new(Vec::new()),
|
||||
sampled_disabled_mask: None,
|
||||
anchor_readers: HashMap::new(),
|
||||
whole_maps: HashMap::new(),
|
||||
anchor_maps: HashMap::new(),
|
||||
gradients: Mutex::default(),
|
||||
field_geometry: OnceLock::new(),
|
||||
session_stack: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// These inputs evaluating the session's own stack: they keep the anchor heights the stack reads and drop the rest
|
||||
pub(super) fn of_the_session_stack(self) -> Self {
|
||||
Self { session_stack: true, ..self }
|
||||
}
|
||||
|
||||
/// Whether the project evaluated is the session's own stack (see [`EvaluationInputs::of_the_session_stack`])
|
||||
pub(super) fn is_session_stack(&self) -> bool {
|
||||
self.session_stack
|
||||
}
|
||||
|
||||
/// The whole-map fields share one fingerprint of the sampled geometry and layout
|
||||
pub(super) fn field_identity(&self) -> u64 {
|
||||
*self.field_geometry.get_or_init(|| crate::field_cache::field_identity(self.inputs))
|
||||
}
|
||||
|
||||
pub(super) fn environment(&self) -> EnvironmentSh {
|
||||
if let Some(environment) = self.environment.get() {
|
||||
return *environment;
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
use std::hash::{DefaultHasher, Hash, Hasher};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use texturecraft_core::BakedMap;
|
||||
use texturecraft_geom::NO_TRI;
|
||||
|
||||
use crate::eval::Inputs;
|
||||
use crate::field_cache_key::FieldCacheKey;
|
||||
use crate::sampled_map::SampledMap;
|
||||
use crate::working_field::working_block;
|
||||
|
||||
/// Most fields cached, and the bytes they may hold (the newest is kept whatever its size)
|
||||
pub(crate) const CACHE_ENTRIES: usize = 8;
|
||||
const CACHE_BYTES: usize = 256 << 20;
|
||||
|
||||
/// FNV-1a prime for the dense texel scan
|
||||
const TEXEL_HASH_BASIS: u64 = 0xcbf2_9ce4_8422_2325;
|
||||
const TEXEL_HASH_PRIME: u64 = 0x0000_0100_0000_01b3;
|
||||
|
||||
/// Geometry and layout data read by the whole-map generators
|
||||
pub(crate) fn field_identity(inputs: &Inputs) -> u64 {
|
||||
let gbuf = inputs.gbuf;
|
||||
let mesh = inputs.mesh;
|
||||
let mut hash = DefaultHasher::new();
|
||||
(gbuf.width, gbuf.height, gbuf.tri.len(), gbuf.bary.len()).hash(&mut hash);
|
||||
|
||||
// Keep this scan synchronous because Rayon tile plans can share a OnceLock
|
||||
let mut texels = TEXEL_HASH_BASIS;
|
||||
let mut mix_texel = |value: u32| texels = (texels ^ u64::from(value)).wrapping_mul(TEXEL_HASH_PRIME);
|
||||
for (index, &triangle) in gbuf.tri.iter().enumerate() {
|
||||
mix_texel(triangle);
|
||||
if triangle != NO_TRI
|
||||
&& let Some(weights) = gbuf.bary.get(index)
|
||||
{
|
||||
mix_texel(weights[0].to_bits());
|
||||
mix_texel(weights[1].to_bits());
|
||||
}
|
||||
}
|
||||
texels.hash(&mut hash);
|
||||
|
||||
mesh.indices.hash(&mut hash);
|
||||
mesh.positions.len().hash(&mut hash);
|
||||
mesh.positions.iter().for_each(|value| value.to_array().map(f32::to_bits).hash(&mut hash));
|
||||
mesh.uvs.len().hash(&mut hash);
|
||||
mesh.uvs.iter().for_each(|value| value.to_array().map(f32::to_bits).hash(&mut hash));
|
||||
mesh.normals.len().hash(&mut hash);
|
||||
mesh.normals.iter().for_each(|value| value.to_array().map(f32::to_bits).hash(&mut hash));
|
||||
|
||||
// Surface interpolation needs tangent slots to exist even when generators do not use the values
|
||||
mesh.tangents.len().hash(&mut hash);
|
||||
inputs.bounds.0.to_array().map(f32::to_bits).hash(&mut hash);
|
||||
inputs.bounds.1.to_array().map(f32::to_bits).hash(&mut hash);
|
||||
let set = inputs.project.texture_set(inputs.ts).ok();
|
||||
if let Some(set) = set {
|
||||
set.material.hash(&mut hash);
|
||||
mesh.submeshes.len().hash(&mut hash);
|
||||
mesh.submeshes.iter().for_each(|part| (part.material, part.start, part.count).hash(&mut hash));
|
||||
set.uv_tiles.hash(&mut hash);
|
||||
set.resolution.hash(&mut hash);
|
||||
set.tile_resolutions.hash(&mut hash);
|
||||
}
|
||||
|
||||
hash.finish()
|
||||
}
|
||||
|
||||
/// Built fields by what they were built from, most recently used last
|
||||
pub(crate) struct FieldCache {
|
||||
entries: Mutex<Vec<(FieldCacheKey, Arc<Vec<f32>>)>>,
|
||||
}
|
||||
|
||||
impl FieldCache {
|
||||
pub(crate) const fn new() -> FieldCache {
|
||||
FieldCache { entries: Mutex::new(Vec::new()) }
|
||||
}
|
||||
|
||||
/// Reuse a field keyed by [`field_identity`], the baked maps it reads and its settings.
|
||||
/// Run the missing field's parallel build outside the cache lock.
|
||||
pub(crate) fn get_or_build(
|
||||
&self,
|
||||
inp: &Inputs,
|
||||
geometry: u64,
|
||||
maps: &[BakedMap],
|
||||
settings: Vec<u32>,
|
||||
build: impl FnOnce((u32, u32)) -> Vec<f32>,
|
||||
) -> Arc<Vec<f32>> {
|
||||
let block = working_block(inp);
|
||||
let read = maps.iter().filter_map(|map| {
|
||||
inp.baked.maps.get(map).map(|data| SampledMap { data: Arc::downgrade(data), baked_size: (inp.baked.resolution, inp.baked.height(*map)) })
|
||||
});
|
||||
let key = FieldCacheKey { geometry, block, scales: inp.block_scales.clone(), maps: read.collect(), settings };
|
||||
|
||||
// A hit moves to the most recently used end
|
||||
let cached = {
|
||||
let mut entries = self.entries.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
entries.retain(|(key, _)| key.maps.iter().all(|map| map.data.strong_count() > 0));
|
||||
let hit = entries.iter().position(|(cached, _)| *cached == key).map(|index| entries.remove(index));
|
||||
hit.map(|(cached, field)| {
|
||||
entries.push((cached, field.clone()));
|
||||
field
|
||||
})
|
||||
};
|
||||
if let Some(field) = cached {
|
||||
return field;
|
||||
}
|
||||
|
||||
let field = Arc::new(build(block));
|
||||
let mut entries = self.entries.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
entries.retain(|(cached, _)| *cached != key);
|
||||
entries.push((key, field.clone()));
|
||||
let mut bytes = 0usize;
|
||||
let keep = entries
|
||||
.iter()
|
||||
.rev()
|
||||
.take_while(|(_, built)| {
|
||||
bytes = bytes.saturating_add(built.len().saturating_mul(size_of::<f32>()));
|
||||
bytes <= CACHE_BYTES
|
||||
})
|
||||
.count()
|
||||
.clamp(1, CACHE_ENTRIES);
|
||||
let excess = entries.len().saturating_sub(keep);
|
||||
entries.drain(..excess);
|
||||
field
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
use texturecraft_core::BlockScales;
|
||||
|
||||
use crate::sampled_map::SampledMap;
|
||||
|
||||
/// What a field was built from: geometry, atlas layout, baked-map identities and generator settings
|
||||
#[derive(Clone, PartialEq)]
|
||||
pub(crate) struct FieldCacheKey {
|
||||
pub(crate) geometry: u64,
|
||||
pub(crate) block: (u32, u32),
|
||||
pub(crate) scales: BlockScales,
|
||||
pub(crate) maps: Vec<SampledMap>,
|
||||
pub(crate) settings: Vec<u32>,
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
//! The precomputed maps one generator reads: its curvature detail sizes and its micro details
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use texturecraft_core::{BakedMap, Generator, KindControls, MicroDetails};
|
||||
|
||||
use crate::curvature_sizes::CurvatureSizes;
|
||||
use crate::dripping_rust::rust_field;
|
||||
use crate::eval::Inputs;
|
||||
use crate::micro_detail::{AnchorHeights, LayoutMap, MicroCurvature, micro_occlusion};
|
||||
use crate::uv_border_distance::border_gradient;
|
||||
use crate::uv_islands::{checker_field, random_color_field};
|
||||
|
||||
/// What a generator reads beyond its texel: built once per map and settings, shared by every tile
|
||||
#[derive(Clone, Default)]
|
||||
pub(crate) struct GeneratorMaps {
|
||||
/// The curvature detail sizes it reads (of its micro curvature when it has some)
|
||||
pub sizes: Option<Arc<CurvatureSizes>>,
|
||||
/// The curvature its micro details add
|
||||
pub micro_curvature: Option<Arc<MicroCurvature>>,
|
||||
/// What its micro details multiply its occlusion by
|
||||
pub micro_occlusion: Option<Arc<LayoutMap>>,
|
||||
/// The whole-map field of UV Border Distance, Dripping Rust, UV Random Color or UV Checker at every working texel
|
||||
pub field: Option<Arc<Vec<f32>>>,
|
||||
/// The controls of a kind with only its own controls, brought into range
|
||||
pub controls: Option<Arc<KindControls>>,
|
||||
}
|
||||
|
||||
impl GeneratorMaps {
|
||||
/// The maps `generator` reads, with the detail sizes `needed` marks (one flag per blurred size); `geometry` fingerprints sampled layout and mesh inputs for whole-map fields
|
||||
pub fn of(inp: &Inputs, generator: &Generator, needed: &[bool], anchor: Option<Arc<AnchorHeights>>, geometry: impl FnOnce() -> u64) -> GeneratorMaps {
|
||||
let micro = generator.micro_in_use().map(|micro| micro.clone().clamped(generator.kind));
|
||||
let micro_curvature = micro
|
||||
.as_ref()
|
||||
.filter(|_| MicroDetails::has_curvature(generator.kind))
|
||||
.and_then(|micro| MicroCurvature::of(inp, generator.kind, micro, anchor.clone()));
|
||||
let micro_occlusion = micro.as_ref().filter(|_| MicroDetails::has_occlusion(generator.kind)).and_then(|micro| micro_occlusion(inp, micro, anchor));
|
||||
let sizes = match µ_curvature {
|
||||
Some(micro) => CurvatureSizes::of_map(inp, µ.curvature, needed),
|
||||
None => inp.baked.maps.get(&BakedMap::Curvature).and_then(|curvature| CurvatureSizes::of_map(inp, curvature, needed)),
|
||||
};
|
||||
let controls = generator.kind_controls();
|
||||
let field = match &controls {
|
||||
Some(KindControls::BorderDistance(border)) => Some(border_gradient(inp, geometry(), border)),
|
||||
Some(KindControls::DrippingRust(rust)) => Some(rust_field(inp, geometry(), rust, generator.seed)),
|
||||
Some(KindControls::UvRandomColor(random)) => Some(random_color_field(inp, geometry(), random, generator.seed)),
|
||||
Some(KindControls::UvChecker(checker)) => Some(checker_field(inp, geometry(), checker, generator.seed)),
|
||||
_ => None,
|
||||
};
|
||||
GeneratorMaps { sizes, micro_curvature, micro_occlusion, field, controls: controls.map(Arc::new) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
use texturecraft_core::{GeneratorKind, ProceduralKind};
|
||||
|
||||
/// The pattern that breaks a wear kind up, its repeats across the UV square (or the mesh, triplanar) per unit of grunge scale, its rotation in degrees, and its mean and spread over the UV square (measured by `grunge_is_normalised`)
|
||||
pub(crate) struct GrungePattern {
|
||||
pub(crate) kind: ProceduralKind,
|
||||
pub(crate) repeats_per_scale: f32,
|
||||
pub(crate) rotation: f32,
|
||||
/// A seeded pattern and its repeats per unit of grunge scale that varies the pattern's strength, for patterns the seed doesn't change
|
||||
pub(crate) breakup: Option<(ProceduralKind, f32)>,
|
||||
pub(crate) mean: f32,
|
||||
pub(crate) spread: f32,
|
||||
/// How strongly a custom grunge's gray away from mid gray counts, in units of the normalised grunge (Dirt reads a brighter custom grunge as cleaner)
|
||||
pub(crate) custom_gain: f32,
|
||||
}
|
||||
|
||||
/// Fine scratches on metal edges, a woven fibre on fibreglass, blotchy grime for dirt
|
||||
pub(crate) const EDGE_WEAR_GRUNGE: GrungePattern =
|
||||
GrungePattern { kind: ProceduralKind::Scratches, repeats_per_scale: 4.0, rotation: 0.0, breakup: None, mean: 0.037, spread: 0.149, custom_gain: 6.22 };
|
||||
pub(crate) const FIBER_GLASS_GRUNGE: GrungePattern = GrungePattern {
|
||||
kind: ProceduralKind::Weave,
|
||||
repeats_per_scale: 16.0,
|
||||
rotation: 45.0,
|
||||
breakup: Some((ProceduralKind::Grunge, 4.0)),
|
||||
mean: 0.539,
|
||||
spread: 0.198,
|
||||
custom_gain: 1.9,
|
||||
};
|
||||
pub(crate) const DIRT_GRUNGE: GrungePattern =
|
||||
GrungePattern { kind: ProceduralKind::Grunge, repeats_per_scale: 4.0, rotation: 0.0, breakup: None, mean: 0.682, spread: 0.242, custom_gain: -5.56 };
|
||||
|
||||
pub(crate) fn grunge_pattern(kind: GeneratorKind) -> &'static GrungePattern {
|
||||
match kind {
|
||||
GeneratorKind::Dirt => &DIRT_GRUNGE,
|
||||
GeneratorKind::FiberGlassEdgeWear => &FIBER_GLASS_GRUNGE,
|
||||
_ => &EDGE_WEAR_GRUNGE,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
//! The histogram scan several generators finish with: a ramp slid through the values and narrowed by a contrast
|
||||
|
||||
/// `value` scanned at `position` (0 all black, 1 all white) over a ramp `1 − contrast` wide; contrast 1 is a hard step
|
||||
pub(crate) fn histogram_scan(value: f32, position: f32, contrast: f32) -> f32 {
|
||||
// The ends hold at a hard step too, where the ramp has no width to reach them
|
||||
if position <= 0.0 {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
if position >= 1.0 {
|
||||
return 1.0;
|
||||
}
|
||||
|
||||
let width = 1.0 - contrast.clamp(0.0, 1.0);
|
||||
|
||||
// The ramp's low end runs from 1 towards position 0 to −width towards position 1
|
||||
let low = (1.0 - position) * (1.0 + width) - width;
|
||||
if width <= f32::EPSILON {
|
||||
return if value >= low { 1.0 } else { 0.0 };
|
||||
}
|
||||
((value - low) / width).clamp(0.0, 1.0)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_ends_of_the_position_are_all_black_and_all_white() {
|
||||
for value in [0.0, 0.3, 1.0] {
|
||||
assert_eq!(histogram_scan(value, 0.0, 0.5), 0.0, "{value}");
|
||||
assert_eq!(histogram_scan(value, 1.0, 0.5), 1.0, "{value}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_ends_of_the_position_hold_at_a_hard_step() {
|
||||
assert_eq!(histogram_scan(1.0, 0.0, 1.0), 0.0, "position 0 is all black, even for white");
|
||||
assert_eq!(histogram_scan(0.0, 1.0, 1.0), 1.0, "position 1 is all white, even for black");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_middle_position_keeps_mid_gray_and_contrast_narrows_around_it() {
|
||||
assert!((histogram_scan(0.5, 0.5, 0.5) - 0.5).abs() < 1e-6);
|
||||
assert!((histogram_scan(0.5, 0.5, 0.0) - 0.5).abs() < 1e-6);
|
||||
assert!((histogram_scan(0.7, 0.5, 0.5) - 0.9).abs() < 1e-6, "a ramp half wide from 0.25");
|
||||
assert!(histogram_scan(0.6, 0.5, 0.9) > histogram_scan(0.6, 0.5, 0.5));
|
||||
assert_eq!(histogram_scan(0.51, 0.5, 1.0), 1.0);
|
||||
assert_eq!(histogram_scan(0.49, 0.5, 1.0), 0.0);
|
||||
}
|
||||
}
|
||||
@@ -14,20 +14,27 @@ mod curvature_size_level;
|
||||
pub mod curvature_sizes;
|
||||
pub mod display;
|
||||
mod distance_envelope;
|
||||
mod dripping_rust;
|
||||
mod effect_histogram;
|
||||
pub mod environment_sh;
|
||||
pub mod environment_sky;
|
||||
pub mod eval;
|
||||
mod fabric;
|
||||
mod field_cache;
|
||||
mod field_cache_key;
|
||||
pub mod fill_copies;
|
||||
pub mod fill_copy;
|
||||
mod fill_depth;
|
||||
mod fill_place;
|
||||
pub mod frame_placement;
|
||||
mod fur_lock;
|
||||
mod generator_maps;
|
||||
mod grunge_pattern;
|
||||
mod held_fields;
|
||||
mod histogram_scan;
|
||||
mod image_identity;
|
||||
mod mask_gray;
|
||||
mod micro_detail;
|
||||
pub mod mip_level;
|
||||
mod organic;
|
||||
pub mod pattern;
|
||||
@@ -36,19 +43,30 @@ pub mod projector_cover;
|
||||
pub mod projector_depth;
|
||||
mod projector_depth_cache;
|
||||
pub mod projector_view;
|
||||
mod sampled_map;
|
||||
mod sections;
|
||||
mod shape_distance;
|
||||
mod slope_texel;
|
||||
mod slot_placement;
|
||||
mod soft_box;
|
||||
pub mod solo;
|
||||
pub mod store;
|
||||
mod texture_layer;
|
||||
mod three_d_distance;
|
||||
pub mod thumb;
|
||||
pub mod tile_length;
|
||||
mod tile_pattern;
|
||||
mod tile_random_stream;
|
||||
mod timber;
|
||||
mod uv_border_distance;
|
||||
mod uv_islands;
|
||||
pub mod warp;
|
||||
mod warp_source_sample;
|
||||
mod warp_texel;
|
||||
mod wear;
|
||||
mod wear_inputs;
|
||||
mod wear_scan;
|
||||
mod working_field;
|
||||
|
||||
pub use below::{BelowCache, StackKey};
|
||||
pub use display::{DisplayKind, kinds_for, tile_bytes};
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
use std::sync::{Arc, Weak};
|
||||
|
||||
use texturecraft_core::LayerId;
|
||||
|
||||
use super::anchor_heights::AnchorHeights;
|
||||
use crate::below::StackKey;
|
||||
|
||||
/// The anchor heights built for a texture set's stack: the mesh maps they were built beside, the set, the anchor and the stack's key
|
||||
pub(super) struct AnchorEntry {
|
||||
pub(super) baked: Weak<Vec<f32>>,
|
||||
pub(super) texture_set: usize,
|
||||
pub(super) anchor: (LayerId, usize),
|
||||
pub(super) stack: Arc<StackKey>,
|
||||
pub(super) heights: Arc<AnchorHeights>,
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
use std::sync::{Arc, Mutex, PoisonError, Weak};
|
||||
|
||||
use texturecraft_core::{BakedMap, LayerId};
|
||||
|
||||
use super::{AnchorHeights, CACHE_BYTES, anchor_entry::AnchorEntry};
|
||||
use crate::below::StackKey;
|
||||
use crate::eval::Inputs;
|
||||
|
||||
/// Committed anchor heights reused by a session between composites
|
||||
#[derive(Default)]
|
||||
pub(crate) struct AnchorHeightCache {
|
||||
entries: Mutex<Vec<AnchorEntry>>,
|
||||
}
|
||||
|
||||
impl AnchorHeightCache {
|
||||
pub(crate) fn retain_readers(&self, texture_set: usize, anchors: &[(LayerId, usize)]) {
|
||||
self.entries
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.retain(|entry| entry.baked.strong_count() > 0 && (entry.texture_set != texture_set || anchors.contains(&entry.anchor)));
|
||||
}
|
||||
|
||||
pub(crate) fn get_or_build(
|
||||
&self,
|
||||
inputs: &Inputs,
|
||||
anchor: (LayerId, usize),
|
||||
stack: &Arc<StackKey>,
|
||||
build: impl FnOnce() -> AnchorHeights,
|
||||
) -> Arc<AnchorHeights> {
|
||||
let baked = [BakedMap::Curvature, BakedMap::AmbientOcclusion].iter().find_map(|map| inputs.baked.maps.get(map)).map(Arc::downgrade);
|
||||
let Some(baked) = baked else { return Arc::new(build()) };
|
||||
let same_anchor = |entry: &AnchorEntry| entry.texture_set == inputs.ts && entry.anchor == anchor;
|
||||
let layout = (inputs.gbuf.width, inputs.gbuf.height);
|
||||
|
||||
{
|
||||
let mut entries = self.entries.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if let Some(index) = entries.iter().position(|entry| {
|
||||
same_anchor(entry) && Weak::ptr_eq(&entry.baked, &baked) && &entry.stack == stack && entry.heights.matches_layout(layout, &inputs.block_scales)
|
||||
}) {
|
||||
let entry = entries.remove(index);
|
||||
let heights = entry.heights.clone();
|
||||
entries.push(entry);
|
||||
return heights;
|
||||
}
|
||||
}
|
||||
|
||||
// Height construction plans and evaluates the stack in parallel
|
||||
let heights = Arc::new(build());
|
||||
let mut entries = self.entries.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
entries.retain(|entry| !same_anchor(entry));
|
||||
entries.push(AnchorEntry { baked, texture_set: inputs.ts, anchor, stack: stack.clone(), heights: heights.clone() });
|
||||
|
||||
let mut bytes = 0usize;
|
||||
let kept = entries
|
||||
.iter()
|
||||
.rev()
|
||||
.take_while(|entry| {
|
||||
bytes = bytes.saturating_add(entry.heights.bytes());
|
||||
bytes <= CACHE_BYTES
|
||||
})
|
||||
.count();
|
||||
let excess = entries.len() - kept;
|
||||
entries.drain(..excess);
|
||||
heights
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
use texturecraft_core::BlockScales;
|
||||
|
||||
/// An anchor point's height over the whole texture set, in the working atlas's layout
|
||||
pub struct AnchorHeights {
|
||||
data: Vec<f32>,
|
||||
working_size: (u32, u32),
|
||||
scales: BlockScales,
|
||||
}
|
||||
|
||||
impl AnchorHeights {
|
||||
pub fn new(data: Vec<f32>, working_size: (u32, u32), scales: BlockScales) -> AnchorHeights {
|
||||
AnchorHeights { data, working_size, scales }
|
||||
}
|
||||
|
||||
pub(super) fn matches_layout(&self, size: (u32, u32), scales: &BlockScales) -> bool {
|
||||
self.working_size == size && &self.scales == scales
|
||||
}
|
||||
|
||||
pub(super) fn bytes(&self) -> usize {
|
||||
self.data.len().saturating_mul(size_of::<f32>())
|
||||
}
|
||||
|
||||
/// The height under texel (`x`, `y`) of a `layout` sized mesh map (0 outside the working atlas)
|
||||
pub(super) fn at(&self, (x, y): (u32, u32), layout: (u32, u32)) -> f32 {
|
||||
let baked_uv = [(x as f32 + 0.5) / layout.0.max(1) as f32, (y as f32 + 0.5) / layout.1.max(1) as f32];
|
||||
let Some(uv) = self.scales.working_uv(baked_uv, self.working_size) else { return 0.0 };
|
||||
|
||||
let column = ((uv[0] * self.working_size.0 as f32) as u32).min(self.working_size.0.saturating_sub(1));
|
||||
let row = ((uv[1] * self.working_size.1 as f32) as u32).min(self.working_size.1.saturating_sub(1));
|
||||
self.data.get((row * self.working_size.0 + column) as usize).copied().unwrap_or(0.0)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
use std::sync::Weak;
|
||||
|
||||
use super::slot_key::SlotKey;
|
||||
|
||||
/// What a micro map was built from: the mesh map giving its layout, its slots, its settings, atlas dimensions and UV tile block
|
||||
#[derive(Clone)]
|
||||
pub(super) struct CacheKey {
|
||||
pub(super) map: Weak<Vec<f32>>,
|
||||
pub(super) height: Option<SlotKey>,
|
||||
pub(super) normal: Option<SlotKey>,
|
||||
pub(super) settings: Vec<u32>,
|
||||
pub(super) size: (u32, u32),
|
||||
pub(super) block: (u32, u32),
|
||||
}
|
||||
|
||||
impl PartialEq for CacheKey {
|
||||
fn eq(&self, other: &CacheKey) -> bool {
|
||||
self.map.strong_count() > 0
|
||||
&& self.map.ptr_eq(&other.map)
|
||||
&& self.height == other.height
|
||||
&& self.normal == other.normal
|
||||
&& self.settings == other.settings
|
||||
&& self.size == other.size
|
||||
&& self.block == other.block
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
/// What a cached map holds, to keep the cache within [`CACHE_BYTES`](super::CACHE_BYTES)
|
||||
pub(super) trait CachedBytes {
|
||||
fn bytes(&self) -> usize;
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
use texturecraft_core::BlockScales;
|
||||
|
||||
use super::cached_bytes::CachedBytes;
|
||||
|
||||
/// A map in a mesh map's layout: `size` texels, each UV tile one block
|
||||
pub struct LayoutMap {
|
||||
pub(super) data: Vec<f32>,
|
||||
pub(super) size: (u32, u32),
|
||||
}
|
||||
|
||||
impl LayoutMap {
|
||||
/// The value under working texel (`x`, `y`) of a `working_size` atlas laid out by `scales` (None outside the layout)
|
||||
pub fn at(&self, (x, y): (u32, u32), working_size: (u32, u32), scales: &BlockScales) -> Option<f32> {
|
||||
let uv = [(x as f32 + 0.5) / working_size.0.max(1) as f32, (y as f32 + 0.5) / working_size.1.max(1) as f32];
|
||||
let baked_uv = scales.bake_uv(uv, working_size)?;
|
||||
let column = ((baked_uv[0] * self.size.0 as f32) as u32).min(self.size.0.saturating_sub(1));
|
||||
let row = ((baked_uv[1] * self.size.1 as f32) as u32).min(self.size.1.saturating_sub(1));
|
||||
self.data.get((row * self.size.0 + column) as usize).copied()
|
||||
}
|
||||
}
|
||||
|
||||
impl CachedBytes for LayoutMap {
|
||||
fn bytes(&self) -> usize {
|
||||
self.data.len().saturating_mul(size_of::<f32>())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use super::cache_key::CacheKey;
|
||||
use super::cached_bytes::CachedBytes;
|
||||
use super::{CACHE_BYTES, CACHE_ENTRIES};
|
||||
|
||||
/// Built maps by what they were built from, most recently used last
|
||||
pub(super) struct MicroCache<T> {
|
||||
entries: Mutex<Vec<(CacheKey, Arc<T>)>>,
|
||||
}
|
||||
|
||||
impl<T: CachedBytes> MicroCache<T> {
|
||||
pub(super) const fn new() -> MicroCache<T> {
|
||||
MicroCache { entries: Mutex::new(Vec::new()) }
|
||||
}
|
||||
|
||||
/// The map built from `key`, built by `build` when missing (outside the lock: the build runs parallel work)
|
||||
pub(super) fn get_or_build(&self, key: CacheKey, build: impl FnOnce() -> T) -> Arc<T> {
|
||||
let found = {
|
||||
let mut entries = self.entries.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
entries.retain(|(key, _)| key.map.strong_count() > 0);
|
||||
entries.iter().position(|(cached, _)| *cached == key).map(|index| {
|
||||
let entry = entries.remove(index);
|
||||
let built = entry.1.clone();
|
||||
entries.push(entry);
|
||||
built
|
||||
})
|
||||
};
|
||||
if let Some(built) = found {
|
||||
return built;
|
||||
}
|
||||
|
||||
let built = Arc::new(build());
|
||||
let mut entries = self.entries.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
entries.retain(|(cached, _)| *cached != key);
|
||||
entries.push((key, built.clone()));
|
||||
let mut bytes = 0usize;
|
||||
let keep = entries
|
||||
.iter()
|
||||
.rev()
|
||||
.take_while(|(_, built)| {
|
||||
bytes = bytes.saturating_add(built.bytes());
|
||||
bytes <= CACHE_BYTES
|
||||
})
|
||||
.count()
|
||||
.clamp(1, CACHE_ENTRIES);
|
||||
let excess = entries.len().saturating_sub(keep);
|
||||
entries.drain(..excess);
|
||||
built
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use rayon::prelude::*;
|
||||
use texturecraft_core::{BakedMap, GeneratorKind, MicroDetails};
|
||||
|
||||
use super::cache_key::CacheKey;
|
||||
use super::cached_bytes::CachedBytes;
|
||||
use super::layout_map::LayoutMap;
|
||||
use super::slot::Slot;
|
||||
use super::{AnchorHeights, CURVATURE_CACHE, by_blocks, curvature_term, layout};
|
||||
use crate::eval::Inputs;
|
||||
|
||||
/// The curvature a generator's micro details add
|
||||
pub struct MicroCurvature {
|
||||
/// What they add to the curvature input
|
||||
pub term: LayoutMap,
|
||||
/// The baked curvature with the term added, which the detail sizes blur
|
||||
pub curvature: Arc<Vec<f32>>,
|
||||
}
|
||||
|
||||
impl MicroCurvature {
|
||||
/// The curvature `micro` adds on a `kind` generator, in the baked curvature map's layout (None without a baked curvature map)
|
||||
pub fn of(inp: &Inputs, kind: GeneratorKind, micro: &MicroDetails, anchor: Option<Arc<AnchorHeights>>) -> Option<Arc<MicroCurvature>> {
|
||||
let (curvature, size, block) = layout(inp, BakedMap::Curvature)?;
|
||||
let height = micro.height.then(|| Slot::of(inp, micro.height_source.as_ref(), anchor));
|
||||
let normal = micro.normal.then(|| Slot::of(inp, micro.normal_source.as_ref(), None));
|
||||
let settings = vec![micro.curvature_type as u32, micro.curvature_intensity.to_bits(), micro.height_intensity.to_bits(), kind as u32];
|
||||
let key =
|
||||
CacheKey { map: Arc::downgrade(&curvature), height: height.as_ref().map(Slot::key), normal: normal.as_ref().map(Slot::key), settings, size, block };
|
||||
|
||||
Some(CURVATURE_CACHE.get_or_build(key, || {
|
||||
let same_in_every_block = height.iter().chain(&normal).all(Slot::same_in_every_block);
|
||||
let term = by_blocks(size, block, same_in_every_block, |origin, block| {
|
||||
let height = height.as_ref().map(|height| height.in_block(origin, size));
|
||||
let normal = normal.as_ref().map(|normal| normal.in_block(origin, size));
|
||||
curvature_term(micro, height.as_ref(), normal.as_ref(), block)
|
||||
});
|
||||
let adjusted = curvature.par_iter().zip(term.par_iter()).map(|(curvature, term)| curvature + term).collect();
|
||||
MicroCurvature { term: LayoutMap { data: term, size }, curvature: Arc::new(adjusted) }
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
impl CachedBytes for MicroCurvature {
|
||||
fn bytes(&self) -> usize {
|
||||
self.term.bytes().saturating_add(self.curvature.len().saturating_mul(size_of::<f32>()))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,370 @@
|
||||
//! A generator's micro details: the curvature and occlusion its micro height (an image or an anchor point's height) and normal image add to its mesh maps, built once per map, image and settings
|
||||
|
||||
mod anchor_entry;
|
||||
mod anchor_height_cache;
|
||||
mod anchor_heights;
|
||||
mod cache_key;
|
||||
mod cached_bytes;
|
||||
mod layout_map;
|
||||
mod micro_cache;
|
||||
mod micro_curvature;
|
||||
mod slot;
|
||||
mod slot_key;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
pub(crate) use anchor_height_cache::AnchorHeightCache;
|
||||
pub use anchor_heights::AnchorHeights;
|
||||
use cache_key::CacheKey;
|
||||
pub use layout_map::LayoutMap;
|
||||
use micro_cache::MicroCache;
|
||||
pub use micro_curvature::MicroCurvature;
|
||||
use rayon::prelude::*;
|
||||
use slot::Slot;
|
||||
use texturecraft_core::{BakedMap, MicroCurvatureType, MicroDetails};
|
||||
|
||||
use crate::eval::{BLUR_BOX_PASSES, Inputs};
|
||||
use crate::working_field::REFERENCE_TILE_TEXELS;
|
||||
|
||||
/// How steeply the micro height tilts the normal it is turned into, per unit of Height Details Intensity (fitted)
|
||||
const HEIGHT_NORMAL_STRENGTH: f32 = 5.9;
|
||||
|
||||
/// Blur sizes of the Smooth type, in texels at 2K: the height against each of these blurred copies
|
||||
const SMOOTH_SIGMAS: [f32; 7] = [1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0];
|
||||
|
||||
/// Below this sigma a blur is an explicit kernel; wider ones are three box passes
|
||||
const BOX_BLUR_MIN_SIGMA: f32 = 2.0;
|
||||
|
||||
/// How many sigmas the sampled kernel reaches each side
|
||||
const KERNEL_REACH_SIGMAS: f32 = 3.0;
|
||||
|
||||
/// Directions the occlusion looks along
|
||||
const OCCLUSION_DIRECTIONS: usize = 16;
|
||||
|
||||
/// Most steps the occlusion takes along each direction; longer radii step further each time
|
||||
const OCCLUSION_STEPS: usize = 16;
|
||||
|
||||
/// The occlusion radius in texels at 1K for AO Radius 1, and its exponent (fitted: radius 0.3 reaches about 6 texels, 1 about 48)
|
||||
const OCCLUSION_RADIUS_TEXELS_1K: f32 = 47.675;
|
||||
const OCCLUSION_RADIUS_POWER: f32 = 1.663;
|
||||
|
||||
/// Shorter radii at 1K occlude nothing: the reference is unchanged at AO Radius 0.1 (about 1 texel) and occludes from 0.2 (about 3)
|
||||
const MIN_OCCLUSION_RADIUS_TEXELS_1K: f32 = 2.0;
|
||||
|
||||
/// How steep the micro height reads for occlusion per texel at 1K at AO Depth 1, and its exponent (fitted)
|
||||
const OCCLUSION_DEPTH_SCALE_1K: f32 = 1473.8;
|
||||
const OCCLUSION_DEPTH_POWER: f32 = 1.0654;
|
||||
|
||||
/// How dark a fully occluding horizon makes the occlusion (fitted)
|
||||
const OCCLUSION_STRENGTH: f32 = 0.3232;
|
||||
|
||||
/// Most micro maps cached, and the bytes they may hold (the newest is kept whatever its size), like the curvature sizes they feed
|
||||
const CACHE_ENTRIES: usize = 8;
|
||||
const CACHE_BYTES: usize = 256 << 20;
|
||||
|
||||
/// The UV of each texel's center in a `size` block, row by row
|
||||
fn block_uvs((width, height): (u32, u32)) -> impl Iterator<Item = [f32; 2]> {
|
||||
(0..height).flat_map(move |y| (0..width).map(move |x| [(x as f32 + 0.5) / width as f32, (y as f32 + 0.5) / height as f32]))
|
||||
}
|
||||
|
||||
static CURVATURE_CACHE: MicroCache<MicroCurvature> = MicroCache::new();
|
||||
static OCCLUSION_CACHE: MicroCache<LayoutMap> = MicroCache::new();
|
||||
|
||||
/// A baked map, its size and the size of one UV tile's block in it
|
||||
type MapLayout = (Arc<Vec<f32>>, (u32, u32), (u32, u32));
|
||||
|
||||
/// The baked `map`'s layout (None when it isn't baked)
|
||||
fn layout(inp: &Inputs, map: BakedMap) -> Option<MapLayout> {
|
||||
let data = inp.baked.maps.get(&map)?.clone();
|
||||
let size = (inp.baked.resolution, inp.baked.height(map));
|
||||
if size.0 == 0 || size.1 == 0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let grid = inp.project.texture_set(inp.ts).ok().and_then(|set| set.tile_grid());
|
||||
let block = grid.map_or(size, |grid| (size.0 / grid.cols.max(1), size.1 / grid.rows.max(1)));
|
||||
Some((data, size, (block.0.max(1).min(size.0), block.1.max(1).min(size.1))))
|
||||
}
|
||||
|
||||
/// `per_block` run on each UV tile block of a `size` map, its results placed into one map
|
||||
fn by_blocks(size: (u32, u32), block: (u32, u32), same_in_every_block: bool, per_block: impl Fn((u32, u32), (u32, u32)) -> Vec<f32> + Sync) -> Vec<f32> {
|
||||
let blocks: Vec<(u32, u32)> = (0..size.1).step_by(block.1 as usize).flat_map(|y| (0..size.0).step_by(block.0 as usize).map(move |x| (x, y))).collect();
|
||||
|
||||
// Every block is a whole UV tile, so one computation serves them all unless the slots differ per block; a clipped last block differs too
|
||||
let full = same_in_every_block.then(|| per_block((0, 0), block));
|
||||
let mut data = vec![0.0; (size.0 * size.1) as usize];
|
||||
for (left, top) in blocks {
|
||||
let clipped = (block.0.min(size.0 - left), block.1.min(size.1 - top));
|
||||
let own = if clipped == block && full.is_some() { None } else { Some(per_block((left, top), clipped)) };
|
||||
let Some(values) = own.as_deref().or(full.as_deref()) else { continue };
|
||||
for row in 0..clipped.1 {
|
||||
let source = (row * clipped.0) as usize;
|
||||
let target = ((top + row) * size.0 + left) as usize;
|
||||
if let (Some(target), Some(source)) = (data.get_mut(target..target + clipped.0 as usize), values.get(source..source + clipped.0 as usize)) {
|
||||
target.copy_from_slice(source);
|
||||
}
|
||||
}
|
||||
}
|
||||
data
|
||||
}
|
||||
|
||||
/// What the occlusion input is multiplied by: the micro height's occlusion in the baked AO map's layout (None without a baked AO map or a micro height)
|
||||
pub fn micro_occlusion(inp: &Inputs, micro: &MicroDetails, anchor: Option<Arc<AnchorHeights>>) -> Option<Arc<LayoutMap>> {
|
||||
let (occlusion, size, block) = layout(inp, BakedMap::AmbientOcclusion)?;
|
||||
let height = Slot::of(inp, micro.height.then_some(micro.height_source.as_ref())?, anchor);
|
||||
let settings = vec![micro.ao_radius.to_bits(), micro.ao_depth.to_bits()];
|
||||
let key = CacheKey { map: Arc::downgrade(&occlusion), height: Some(height.key()), normal: None, settings, size, block };
|
||||
|
||||
Some(OCCLUSION_CACHE.get_or_build(key, || {
|
||||
let data = by_blocks(size, block, height.same_in_every_block(), |origin, block| occlusion_factor(micro, &height.in_block(origin, size), block));
|
||||
LayoutMap { data, size }
|
||||
}))
|
||||
}
|
||||
|
||||
/// The fitted constants of a curvature type: what it adds everywhere, and its gain on the height and on the normal
|
||||
fn type_constants(curvature_type: MicroCurvatureType) -> (f32, f32, f32) {
|
||||
match curvature_type {
|
||||
MicroCurvatureType::Standard => (0.00876, 12.36, 9.49),
|
||||
MicroCurvatureType::Sobel => (0.0, 5.72, 4.46),
|
||||
MicroCurvatureType::Smooth => (-0.00332, 0.969, 34.2),
|
||||
}
|
||||
}
|
||||
|
||||
/// The curvature the micro details add over one `size` UV tile block
|
||||
fn curvature_term(micro: &MicroDetails, height: Option<&Slot>, normal: Option<&Slot>, size: (u32, u32)) -> Vec<f32> {
|
||||
let (offset, height_gain, normal_gain) = type_constants(micro.curvature_type);
|
||||
let texel_scale = size.0 as f32 / REFERENCE_TILE_TEXELS;
|
||||
let mut term = vec![offset; (size.0 * size.1) as usize];
|
||||
|
||||
if let Some(height) = height {
|
||||
let heights = height.heights(size);
|
||||
let detail = match micro.curvature_type {
|
||||
MicroCurvatureType::Smooth => smooth_detail(&heights, size, texel_scale).into_iter().map(|detail| detail * micro.height_intensity).collect(),
|
||||
MicroCurvatureType::Standard | MicroCurvatureType::Sobel => {
|
||||
// The height turned into a normal, then that normal's divergence
|
||||
let strength = HEIGHT_NORMAL_STRENGTH * micro.height_intensity * texel_scale;
|
||||
let tilted = |slope_x: f32, slope_y: f32| {
|
||||
let (x, y) = (-strength * slope_x, -strength * slope_y);
|
||||
let length = (x * x + y * y + 1.0).sqrt();
|
||||
(x / length, y / length)
|
||||
};
|
||||
let (normal_x, normal_y): (Vec<f32>, Vec<f32>) = sobel_components(&heights, &heights, size).map(|(x, y)| tilted(x, y)).unzip();
|
||||
divergence(&normal_x, &normal_y, size, texel_scale)
|
||||
}
|
||||
};
|
||||
add_scaled(&mut term, &detail, micro.curvature_intensity * height_gain);
|
||||
}
|
||||
if let Some(normal) = normal {
|
||||
let (normal_x, normal_y) = normal.normals(size);
|
||||
add_scaled(&mut term, &divergence(&normal_x, &normal_y, size, texel_scale), micro.curvature_intensity * normal_gain);
|
||||
}
|
||||
term
|
||||
}
|
||||
|
||||
fn add_scaled(target: &mut [f32], values: &[f32], gain: f32) {
|
||||
target.par_iter_mut().zip(values.par_iter()).for_each(|(target, value)| *target += value * gain);
|
||||
}
|
||||
|
||||
/// The Smooth type's detail: the height above its blurred copies, averaged over [`SMOOTH_SIGMAS`]
|
||||
fn smooth_detail(heights: &[f32], size: (u32, u32), texel_scale: f32) -> Vec<f32> {
|
||||
let mut detail = vec![0.0; heights.len()];
|
||||
for sigma in SMOOTH_SIGMAS {
|
||||
let blurred = gaussian_wrapped(heights, size, sigma * texel_scale);
|
||||
detail.par_iter_mut().zip(heights.par_iter().zip(blurred.par_iter())).for_each(|(detail, (height, blurred))| *detail += height - blurred);
|
||||
}
|
||||
let count = SMOOTH_SIGMAS.len() as f32;
|
||||
detail.par_iter_mut().for_each(|detail| *detail /= count);
|
||||
detail
|
||||
}
|
||||
|
||||
/// The divergence of the two normal components, per texel at 2K
|
||||
fn divergence(x: &[f32], y: &[f32], size: (u32, u32), texel_scale: f32) -> Vec<f32> {
|
||||
sobel_components(x, y, size).map(|(dx, dy)| (dx + dy) * texel_scale).collect()
|
||||
}
|
||||
|
||||
/// Apply the horizontal and vertical Sobel kernels to their respective fields with periodic edges
|
||||
fn sobel_components<'a>(horizontal: &'a [f32], vertical: &'a [f32], (width, height): (u32, u32)) -> impl IndexedParallelIterator<Item = (f32, f32)> + 'a {
|
||||
let width = width.max(1) as usize;
|
||||
let height = height.max(1) as usize;
|
||||
|
||||
(0..width * height).into_par_iter().map(move |index| {
|
||||
let x = index % width;
|
||||
let y = index / width;
|
||||
let left = if x == 0 { width - 1 } else { x - 1 };
|
||||
let right = if x + 1 == width { 0 } else { x + 1 };
|
||||
let top = if y == 0 { height - 1 } else { y - 1 };
|
||||
let bottom = if y + 1 == height { 0 } else { y + 1 };
|
||||
|
||||
let sample = |field: &[f32], x, y| field.get(y * width + x).copied().unwrap_or(0.0);
|
||||
let column = |x| sample(horizontal, x, top) + 2.0 * sample(horizontal, x, y) + sample(horizontal, x, bottom);
|
||||
let row = |y| sample(vertical, left, y) + 2.0 * sample(vertical, x, y) + sample(vertical, right, y);
|
||||
((column(right) - column(left)) / 8.0, (row(bottom) - row(top)) / 8.0)
|
||||
})
|
||||
}
|
||||
|
||||
/// `values` blurred to `sigma` texels, wrapping around the block like a tiling image
|
||||
fn gaussian_wrapped(values: &[f32], (width, height): (u32, u32), sigma: f32) -> Vec<f32> {
|
||||
let rows = blur_lines(values, width as usize, sigma);
|
||||
let columns = blur_lines(&transposed(&rows, width as usize, height as usize), height as usize, sigma);
|
||||
transposed(&columns, height as usize, width as usize)
|
||||
}
|
||||
|
||||
/// Each `length`-long line of `values` blurred to `sigma`, wrapping around
|
||||
fn blur_lines(values: &[f32], length: usize, sigma: f32) -> Vec<f32> {
|
||||
let length = length.max(1);
|
||||
let mut out = vec![0.0; values.len()];
|
||||
|
||||
// Every line reads the same sampled kernel
|
||||
let kernel = (sigma < BOX_BLUR_MIN_SIGMA).then(|| gaussian_kernel(sigma));
|
||||
out.par_chunks_mut(length).zip(values.par_chunks(length)).for_each(|(out, line)| match &kernel {
|
||||
Some(kernel) => kernel_blur(line, out, kernel),
|
||||
None => {
|
||||
// Three box passes of radius r spread a value with variance r(r + 1)
|
||||
let radius = (((1.0 + 4.0 * sigma * sigma).sqrt() - 1.0) / 2.0).round().max(1.0) as usize;
|
||||
let mut current = line.to_vec();
|
||||
for _ in 0..BLUR_BOX_PASSES {
|
||||
box_blur(¤t, out, radius);
|
||||
current.copy_from_slice(out);
|
||||
}
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// A gaussian of `sigma` sampled at whole texels each side of its centre, its weights summing to 1
|
||||
fn gaussian_kernel(sigma: f32) -> Vec<f32> {
|
||||
let reach = (KERNEL_REACH_SIGMAS * sigma).ceil().max(1.0) as i64;
|
||||
let weights: Vec<f32> = (-reach..=reach).map(|offset| (-(offset * offset) as f32 / (2.0 * sigma * sigma)).exp()).collect();
|
||||
let total: f32 = weights.iter().sum();
|
||||
weights.into_iter().map(|weight| weight / total).collect()
|
||||
}
|
||||
|
||||
/// `line` blurred into `out` by `kernel` (centred, as [`gaussian_kernel`] samples it), wrapping around
|
||||
fn kernel_blur(line: &[f32], out: &mut [f32], kernel: &[f32]) {
|
||||
let reach = (kernel.len() / 2) as i64;
|
||||
let length = line.len().max(1) as i64;
|
||||
for (index, value) in out.iter_mut().enumerate() {
|
||||
*value = (-reach..=reach)
|
||||
.zip(kernel)
|
||||
.map(|(offset, weight)| line.get((index as i64 + offset).rem_euclid(length) as usize).copied().unwrap_or(0.0) * weight)
|
||||
.sum();
|
||||
}
|
||||
}
|
||||
|
||||
/// `line` averaged over `radius` texels each side into `out`, wrapping around
|
||||
fn box_blur(line: &[f32], out: &mut [f32], radius: usize) {
|
||||
let length = line.len().max(1) as i64;
|
||||
let window = (2 * radius + 1) as f32;
|
||||
let at = |index: i64| line.get(index.rem_euclid(length) as usize).copied().unwrap_or(0.0);
|
||||
let mut sum: f32 = (-(radius as i64)..=radius as i64).map(at).sum();
|
||||
for (index, value) in out.iter_mut().enumerate() {
|
||||
*value = sum / window;
|
||||
let index = index as i64;
|
||||
sum += at(index + radius as i64 + 1) - at(index - radius as i64);
|
||||
}
|
||||
}
|
||||
|
||||
fn transposed(values: &[f32], width: usize, height: usize) -> Vec<f32> {
|
||||
let height = height.max(1);
|
||||
(0..width * height).into_par_iter().map(|texel| values.get((texel % height) * width + texel / height).copied().unwrap_or(0.0)).collect()
|
||||
}
|
||||
|
||||
/// What the occlusion is multiplied by over one `size` UV tile block: the horizon the micro height raises above its slope, looked for in [`OCCLUSION_DIRECTIONS`]
|
||||
fn occlusion_factor(micro: &MicroDetails, height: &Slot, size: (u32, u32)) -> Vec<f32> {
|
||||
let tile_scale = size.0 as f32 / (REFERENCE_TILE_TEXELS / 2.0);
|
||||
let radius_1k = OCCLUSION_RADIUS_TEXELS_1K * micro.ao_radius.powf(OCCLUSION_RADIUS_POWER);
|
||||
let radius = (radius_1k * tile_scale).round() as usize;
|
||||
let count = (size.0 * size.1) as usize;
|
||||
if radius_1k < MIN_OCCLUSION_RADIUS_TEXELS_1K || radius < 1 {
|
||||
return vec![1.0; count];
|
||||
}
|
||||
|
||||
let depth = OCCLUSION_DEPTH_SCALE_1K * micro.ao_depth.powf(OCCLUSION_DEPTH_POWER) * tile_scale;
|
||||
let heights = height.heights(size);
|
||||
let (width, rows) = (i64::from(size.0.max(1)), i64::from(size.1.max(1)));
|
||||
let at = |x: i64, y: i64| heights.get((y.rem_euclid(rows) * width + x.rem_euclid(width)) as usize).copied().unwrap_or(0.0);
|
||||
|
||||
// Up to OCCLUSION_STEPS distances spread over the radius
|
||||
let steps: Vec<f32> = if radius <= OCCLUSION_STEPS {
|
||||
(1..=radius).map(|step| step as f32).collect()
|
||||
} else {
|
||||
(1..=OCCLUSION_STEPS).map(|step| 1.0 + (radius - 1) as f32 * (step - 1) as f32 / (OCCLUSION_STEPS - 1) as f32).collect()
|
||||
};
|
||||
let directions: Vec<_> = (0..OCCLUSION_DIRECTIONS)
|
||||
.map(|index| std::f32::consts::TAU * index as f32 / OCCLUSION_DIRECTIONS as f32)
|
||||
.map(|angle| (angle.cos(), angle.sin()))
|
||||
.map(|(dx, dy)| {
|
||||
let offsets: Vec<_> = steps.iter().map(|&distance| ((dx * distance).round() as i64, (dy * distance).round() as i64, distance)).collect();
|
||||
(dx, dy, offsets)
|
||||
})
|
||||
.collect();
|
||||
let sine = |slope: f32| slope / (1.0 + slope * slope).sqrt();
|
||||
|
||||
(0..width * rows)
|
||||
.into_par_iter()
|
||||
.map(|texel| {
|
||||
let (x, y) = (texel % width, texel / width);
|
||||
let here = at(x, y);
|
||||
let gradient = ((at(x + 1, y) - at(x - 1, y)) / 2.0, (at(x, y + 1) - at(x, y - 1)) / 2.0);
|
||||
let occluded: f32 = directions
|
||||
.iter()
|
||||
.map(|(dx, dy, offsets)| {
|
||||
let horizon = offsets
|
||||
.iter()
|
||||
.map(|&(offset_x, offset_y, distance)| (at(x + offset_x, y + offset_y) - here) / distance)
|
||||
.fold(f32::NEG_INFINITY, f32::max);
|
||||
let tangent = gradient.0 * dx + gradient.1 * dy;
|
||||
(sine(horizon * depth) - sine(tangent * depth)).max(0.0)
|
||||
})
|
||||
.sum();
|
||||
1.0 - OCCLUSION_STRENGTH * occluded / OCCLUSION_DIRECTIONS as f32
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use texturecraft_core::GeneratorKind;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn sobel_reads_a_ramp_as_its_slope() {
|
||||
let size = (8, 8);
|
||||
let ramp: Vec<f32> = (0..64).map(|texel| (texel % 8) as f32 * 0.1).collect();
|
||||
|
||||
let (x, y): (Vec<_>, Vec<_>) = sobel_components(&ramp, &ramp, size).unzip();
|
||||
|
||||
assert!((x[3 * 8 + 3] - 0.1).abs() < 1e-5);
|
||||
assert!(y[3 * 8 + 3].abs() < 1e-5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrapped_blurs_keep_the_mean() {
|
||||
let size = (32, 16);
|
||||
let values: Vec<f32> = (0..32 * 16).map(|texel| ((texel * 7919) % 13) as f32).collect();
|
||||
let mean = values.iter().sum::<f32>() / values.len() as f32;
|
||||
for sigma in [0.5, 1.0, 4.0] {
|
||||
let blurred = gaussian_wrapped(&values, size, sigma);
|
||||
assert!((blurred.iter().sum::<f32>() / blurred.len() as f32 - mean).abs() < 1e-3, "sigma {sigma}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_flat_height_adds_only_the_types_offset() {
|
||||
let mut micro = MicroDetails::defaults(GeneratorKind::Curvature).unwrap();
|
||||
let flat = Slot::Uniform([0.4; 3]);
|
||||
for curvature_type in MicroCurvatureType::ALL {
|
||||
micro.curvature_type = curvature_type;
|
||||
let term = curvature_term(µ, Some(&flat), Some(&Slot::Uniform([0.5, 0.5, 1.0])), (16, 16));
|
||||
assert!(term.iter().all(|value| (value - type_constants(curvature_type).0).abs() < 1e-6), "{curvature_type:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_flat_height_occludes_nothing() {
|
||||
let micro = MicroDetails::defaults(GeneratorKind::AmbientOcclusion).unwrap();
|
||||
let factor = occlusion_factor(µ, &Slot::Uniform([0.7; 3]), (64, 64));
|
||||
assert!(factor.iter().all(|value| (value - 1.0).abs() < 1e-6));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use texturecraft_core::{NormalFormat, Source};
|
||||
|
||||
use super::anchor_heights::AnchorHeights;
|
||||
use super::block_uvs;
|
||||
use super::slot_key::SlotKey;
|
||||
use crate::eval::Inputs;
|
||||
use crate::store::ImageRes;
|
||||
|
||||
/// What a micro details slot reads
|
||||
#[derive(Clone)]
|
||||
pub(super) enum Slot {
|
||||
Uniform([f32; 3]),
|
||||
Image {
|
||||
image: Arc<ImageRes>,
|
||||
flip_green: bool,
|
||||
},
|
||||
/// An anchor point's height, different in each UV tile block: read from the block at `origin` of a `layout` sized mesh map
|
||||
Anchor {
|
||||
heights: Arc<AnchorHeights>,
|
||||
origin: (u32, u32),
|
||||
layout: (u32, u32),
|
||||
},
|
||||
}
|
||||
|
||||
impl Slot {
|
||||
/// The slot holding `source` (an empty slot, an image not loaded and an anchor not prepared yet read black; procedurals are not read)
|
||||
pub(super) fn of(inp: &Inputs, source: Option<&Source>, anchor: Option<Arc<AnchorHeights>>) -> Slot {
|
||||
match source {
|
||||
Some(Source::Uniform(value)) => Slot::Uniform(*value),
|
||||
Some(Source::Image { name, normal_format }) => match inp.images.get(name) {
|
||||
Some(image) => Slot::Image { image: image.clone(), flip_green: *normal_format == NormalFormat::DirectX },
|
||||
None => Slot::Uniform([0.0; 3]),
|
||||
},
|
||||
Some(Source::Anchor { .. }) => match anchor {
|
||||
Some(heights) => Slot::Anchor { heights, origin: (0, 0), layout: (0, 0) },
|
||||
None => Slot::Uniform([0.0; 3]),
|
||||
},
|
||||
_ => Slot::Uniform([0.0; 3]),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether every UV tile block reads the same (an image or a value repeats in each)
|
||||
pub(super) fn same_in_every_block(&self) -> bool {
|
||||
!matches!(self, Slot::Anchor { .. })
|
||||
}
|
||||
|
||||
/// The slot read in the block at `origin` of a `layout` sized mesh map
|
||||
pub(super) fn in_block(&self, origin: (u32, u32), layout: (u32, u32)) -> Slot {
|
||||
match self {
|
||||
Slot::Anchor { heights, .. } => Slot::Anchor { heights: heights.clone(), origin, layout },
|
||||
other => other.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn key(&self) -> SlotKey {
|
||||
match self {
|
||||
Slot::Uniform(value) => SlotKey::Uniform(value.map(f32::to_bits)),
|
||||
Slot::Image { image, flip_green } => SlotKey::Image(Arc::downgrade(image), *flip_green),
|
||||
Slot::Anchor { heights, .. } => SlotKey::Anchor(Arc::downgrade(heights)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The slot's color at `uv`, in the file's encoding
|
||||
pub(super) fn color(&self, uv: [f32; 2]) -> [f32; 3] {
|
||||
match self {
|
||||
Slot::Uniform(value) => *value,
|
||||
Slot::Image { image, .. } => {
|
||||
let [red, green, blue, _] = image.sample(uv[0], uv[1]);
|
||||
[red, green, blue]
|
||||
}
|
||||
Slot::Anchor { .. } => [0.0; 3],
|
||||
}
|
||||
}
|
||||
|
||||
/// The slot read as a height (its gray) over a `size` block
|
||||
pub(super) fn heights(&self, size: (u32, u32)) -> Vec<f32> {
|
||||
match self {
|
||||
Slot::Anchor { heights, origin, layout } => {
|
||||
(0..size.1).flat_map(|row| (0..size.0).map(move |column| (origin.0 + column, origin.1 + row))).map(|texel| heights.at(texel, *layout)).collect()
|
||||
}
|
||||
_ => block_uvs(size).map(|uv| self.color(uv).iter().sum::<f32>() / 3.0).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The slot read as a normal over a `size` block: its X and Y, OpenGL convention
|
||||
pub(super) fn normals(&self, size: (u32, u32)) -> (Vec<f32>, Vec<f32>) {
|
||||
let flip_green = matches!(self, Slot::Image { flip_green: true, .. });
|
||||
block_uvs(size)
|
||||
.map(|uv| {
|
||||
let [red, green, _] = self.color(uv);
|
||||
let y = green * 2.0 - 1.0;
|
||||
(red * 2.0 - 1.0, if flip_green { -y } else { y })
|
||||
})
|
||||
.unzip()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
use std::sync::Weak;
|
||||
|
||||
use super::anchor_heights::AnchorHeights;
|
||||
use crate::store::ImageRes;
|
||||
|
||||
/// A slot as a cache key: an image by identity, a value by its bits
|
||||
#[derive(Clone)]
|
||||
pub(super) enum SlotKey {
|
||||
Uniform([u32; 3]),
|
||||
Image(Weak<ImageRes>, bool),
|
||||
Anchor(Weak<AnchorHeights>),
|
||||
}
|
||||
|
||||
impl PartialEq for SlotKey {
|
||||
fn eq(&self, other: &SlotKey) -> bool {
|
||||
match (self, other) {
|
||||
(SlotKey::Uniform(a), SlotKey::Uniform(b)) => a == b,
|
||||
(SlotKey::Image(a, a_flip), SlotKey::Image(b, b_flip)) => a.strong_count() > 0 && a.ptr_eq(b) && a_flip == b_flip,
|
||||
(SlotKey::Anchor(a), SlotKey::Anchor(b)) => a.strong_count() > 0 && a.ptr_eq(b),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ use std::sync::{Arc, Mutex, Weak};
|
||||
use texturecraft_geom::Mesh;
|
||||
|
||||
use crate::fill_depth::{FillDepth, FillDepthKey};
|
||||
use crate::micro_detail::AnchorHeightCache;
|
||||
|
||||
pub(crate) type ViewDepth = (FillDepthKey, Option<Arc<FillDepth>>);
|
||||
|
||||
@@ -14,12 +15,14 @@ const MAX_CACHED_VIEWS: usize = 8;
|
||||
pub struct ProjectorDepthCache {
|
||||
mesh: Weak<Mesh>,
|
||||
maps: Mutex<Vec<ViewDepth>>,
|
||||
pub(crate) micro_heights: AnchorHeightCache,
|
||||
}
|
||||
|
||||
impl ProjectorDepthCache {
|
||||
pub(crate) fn bind(&mut self, mesh: &Arc<Mesh>) {
|
||||
if !std::ptr::eq(self.mesh.as_ptr(), mesh.as_ref()) {
|
||||
self.maps.get_mut().unwrap_or_else(|poisoned| poisoned.into_inner()).clear();
|
||||
self.micro_heights = AnchorHeightCache::default();
|
||||
self.mesh = Arc::downgrade(mesh);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
use std::sync::Weak;
|
||||
|
||||
/// A mesh map a whole-map field samples: its allocation and the size it was baked at (one allocation read as another layout reads other texels)
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct SampledMap {
|
||||
pub(crate) data: Weak<Vec<f32>>,
|
||||
pub(crate) baked_size: (u32, u32),
|
||||
}
|
||||
|
||||
impl PartialEq for SampledMap {
|
||||
fn eq(&self, other: &SampledMap) -> bool {
|
||||
self.data.strong_count() > 0 && self.data.ptr_eq(&other.data) && self.baked_size == other.baked_size
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
//! The section controls of the Curvature, Ambient Occlusion, Position and World Space Normals generators, and the Light generator's shading
|
||||
|
||||
use texturecraft_core::{AxisBlend, AxisLayer, Generator, GeneratorGlobal, GeneratorKind, LightParameters, SectionParameters};
|
||||
use texturecraft_geom::glam::Vec3;
|
||||
|
||||
/// Gaussian sigma of the section blur per unit of its slider, in texels at [`GeneratorGlobal::BLUR_RESOLUTION`]
|
||||
const BLUR_SIGMA_PER_UNIT: f32 = 4.5;
|
||||
|
||||
/// Base of the section balance's power curve: balance 0 raises the signal to 1/25, balance 1 to 25
|
||||
const BALANCE_POWER_BASE: f32 = 25.0;
|
||||
|
||||
/// How far above the middle a signal must be to turn white at full contrast
|
||||
const FULL_CONTRAST_STEP_OFFSET: f32 = 4.6e-5;
|
||||
|
||||
/// The order the axes combine in, as indices into [`SectionParameters::axes`]: top to bottom is the base, front to back goes last
|
||||
const AXIS_ORDER: [usize; 3] = [SectionParameters::TOP_TO_BOTTOM, SectionParameters::RIGHT_TO_LEFT, SectionParameters::FRONT_TO_BACK];
|
||||
|
||||
/// Distance of a light-facing tangent plane from the centre of the position map's unit cube
|
||||
const ATTENUATION_PLANE_OFFSET: f32 = 0.5;
|
||||
|
||||
/// Light attenuation above which the falloff fades the whole mesh towards black instead of steepening
|
||||
const ATTENUATION_STEEPEST: f32 = 0.5;
|
||||
|
||||
/// Shortest decoded normal still given a direction
|
||||
const MIN_NORMAL_LENGTH: f32 = 1e-6;
|
||||
|
||||
/// A map's three channels (0..1) combined by `axes`: each axis read from its channel, inverted, blended over the axes before it and weighted
|
||||
pub(crate) fn axes_signal(channels: [f32; 3], axes: &[AxisLayer; 3]) -> f32 {
|
||||
AXIS_ORDER.iter().fold(0.0, |base, &index| {
|
||||
let axis = axes[index];
|
||||
if axis.weight <= 0.0 {
|
||||
return base;
|
||||
}
|
||||
|
||||
let layer = if axis.invert { 1.0 - channels[index] } else { channels[index] };
|
||||
(base + (blended(axis.blend, base, layer) - base) * axis.weight).clamp(0.0, 1.0)
|
||||
})
|
||||
}
|
||||
|
||||
/// `layer` blended over `base` by `blend`, unclamped
|
||||
pub(crate) fn blended(blend: AxisBlend, base: f32, layer: f32) -> f32 {
|
||||
match blend {
|
||||
AxisBlend::Normal => layer,
|
||||
AxisBlend::Add => base + layer,
|
||||
AxisBlend::Subtract => base - layer,
|
||||
AxisBlend::Multiply => base * layer,
|
||||
AxisBlend::AddSub => base + 2.0 * layer - 1.0,
|
||||
AxisBlend::Max => base.max(layer),
|
||||
}
|
||||
}
|
||||
|
||||
/// Gaussian sigma of the section blur of a generator of `kind`, in texels at [`GeneratorGlobal::BLUR_RESOLUTION`] (0 for kinds without it)
|
||||
pub(crate) fn blur_sigma(kind: GeneratorKind, section: &SectionParameters) -> f32 {
|
||||
if SectionParameters::has_blur(kind) {
|
||||
section.blur.clamp(*SectionParameters::BLUR_RANGE.start(), *SectionParameters::BLUR_RANGE.end()) * BLUR_SIGMA_PER_UNIT
|
||||
} else {
|
||||
0.0
|
||||
}
|
||||
}
|
||||
|
||||
/// Gaussian sigma of `generator`'s section blur in texels at 2K (0 without one)
|
||||
pub(crate) fn generator_blur_sigma(generator: &Generator) -> f32 {
|
||||
generator.section_controls().map_or(0.0, |section| blur_sigma(generator.kind, §ion))
|
||||
}
|
||||
|
||||
/// The radius of the three box passes that blur like the section blur at `resolution` texels per side
|
||||
pub(crate) fn blur_radius_at(kind: GeneratorKind, section: &SectionParameters, resolution: u32) -> usize {
|
||||
let sigma = blur_sigma(kind, section) * resolution as f32 / GeneratorGlobal::BLUR_RESOLUTION;
|
||||
crate::working_field::box_radius(sigma)
|
||||
}
|
||||
|
||||
/// `signal` after the section's balance, contrast, brightness and invert, as far as a generator of `kind` has them
|
||||
pub(crate) fn adjusted(kind: GeneratorKind, section: &SectionParameters, signal: f32) -> f32 {
|
||||
let mut value = signal.clamp(0.0, 1.0);
|
||||
if SectionParameters::has_balance(kind) {
|
||||
let balance = section.balance.clamp(0.0, 1.0);
|
||||
value = if kind == GeneratorKind::AmbientOcclusion {
|
||||
GeneratorGlobal { balance, ..GeneratorGlobal::default() }.apply(value)
|
||||
} else {
|
||||
value.powf(BALANCE_POWER_BASE.powf(2.0 * balance - 1.0))
|
||||
};
|
||||
}
|
||||
|
||||
value = contrasted(value, section.contrast.clamp(0.0, 1.0));
|
||||
|
||||
if SectionParameters::has_brightness(kind) {
|
||||
let brightness = section.brightness.clamp(*SectionParameters::BRIGHTNESS_RANGE.start(), *SectionParameters::BRIGHTNESS_RANGE.end());
|
||||
value = if brightness > 0.0 { value + brightness * (1.0 - value) } else { value * (1.0 + brightness) };
|
||||
}
|
||||
|
||||
if section.invert { 1.0 - value } else { value }
|
||||
}
|
||||
|
||||
/// `value` with its range narrowed around the middle by `contrast` (1 a step just above the middle)
|
||||
fn contrasted(value: f32, contrast: f32) -> f32 {
|
||||
if contrast <= 0.0 {
|
||||
return value;
|
||||
}
|
||||
|
||||
let half_range = 0.5 * (1.0 - contrast);
|
||||
if 2.0 * half_range < GeneratorGlobal::MIN_RANGE {
|
||||
return if value > 0.5 + FULL_CONTRAST_STEP_OFFSET { 1.0 } else { 0.0 };
|
||||
}
|
||||
((value - (0.5 - half_range)) / (2.0 * half_range)).clamp(0.0, 1.0)
|
||||
}
|
||||
|
||||
/// The direction the light comes from: `horizontal` degrees around the up axis from -X towards +Z, `vertical` degrees above the horizon
|
||||
pub(crate) fn light_direction(horizontal: f32, vertical: f32) -> Vec3 {
|
||||
let (horizontal, vertical) = (horizontal.to_radians(), vertical.to_radians());
|
||||
Vec3::new(-vertical.cos() * horizontal.cos(), vertical.sin(), vertical.cos() * horizontal.sin())
|
||||
}
|
||||
|
||||
/// The Light generator at a texel with world `normal` and `position` (0..1 across the mesh's bounds): lit, highlighted and faded with depth
|
||||
pub(crate) fn light_value(light: &LightParameters, normal: Vec3, position: Vec3, invert: bool) -> f32 {
|
||||
let direction = light_direction(light.horizontal, light.vertical);
|
||||
let normal = if normal.length() > MIN_NORMAL_LENGTH { normal.normalize() } else { Vec3::Y };
|
||||
|
||||
// Glossiness 0 lights the half facing away too, 0.5 is a plain diffuse falloff
|
||||
let glossiness = light.glossiness.clamp(*LightParameters::GLOSSINESS_RANGE.start(), *LightParameters::GLOSSINESS_RANGE.end());
|
||||
let threshold = 2.0 * glossiness - 1.0;
|
||||
let diffuse = ((normal.dot(direction) - threshold) / (1.0 - threshold)).clamp(0.0, 1.0);
|
||||
let highlight_level = light.highlight_level.clamp(0.0, 1.0);
|
||||
let diffuse = if highlight_level >= 1.0 { if diffuse > 0.0 { 1.0 } else { 0.0 } } else { (diffuse / (1.0 - highlight_level)).clamp(0.0, 1.0) };
|
||||
|
||||
// Depth from the tangent plane facing the light
|
||||
let depth = ATTENUATION_PLANE_OFFSET - (position - Vec3::splat(0.5)).dot(direction);
|
||||
let attenuation = light.attenuation.clamp(0.0, 1.0);
|
||||
let kept = if attenuation <= ATTENUATION_STEEPEST {
|
||||
(1.0 - 2.0 * attenuation * depth).clamp(0.0, 1.0)
|
||||
} else {
|
||||
(1.0 - depth).clamp(0.0, 1.0) * (2.0 - 2.0 * attenuation)
|
||||
};
|
||||
kept * if invert { 1.0 - diffuse } else { diffuse }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn axis(blend: AxisBlend, weight: f32) -> AxisLayer {
|
||||
AxisLayer { invert: false, blend, weight }
|
||||
}
|
||||
|
||||
fn defaults(kind: GeneratorKind) -> SectionParameters {
|
||||
SectionParameters::defaults(kind).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_axis_reads_its_own_channel() {
|
||||
let channels = [0.2, 0.5, 0.9];
|
||||
for (index, expected) in channels.iter().enumerate() {
|
||||
let mut axes = [axis(AxisBlend::Add, 0.0); 3];
|
||||
axes[index].weight = 1.0;
|
||||
assert!((axes_signal(channels, &axes) - expected).abs() < 1e-6, "axis {index}");
|
||||
}
|
||||
let mut inverted = [axis(AxisBlend::Add, 0.0); 3];
|
||||
inverted[SectionParameters::TOP_TO_BOTTOM] = AxisLayer { invert: true, ..axis(AxisBlend::Add, 1.0) };
|
||||
assert!((axes_signal(channels, &inverted) - 0.5).abs() < 1e-6);
|
||||
inverted[SectionParameters::RIGHT_TO_LEFT] = AxisLayer { invert: true, ..axis(AxisBlend::Normal, 1.0) };
|
||||
assert!((axes_signal(channels, &inverted) - 0.8).abs() < 1e-6, "inverted red replaces the base");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn right_to_left_blends_over_top_to_bottom_and_front_to_back_goes_last() {
|
||||
let channels = [0.3, 0.8, 0.6];
|
||||
let mut axes = [axis(AxisBlend::Add, 0.0), axis(AxisBlend::Add, 1.0), axis(AxisBlend::Add, 0.0)];
|
||||
for (blend, expected) in [
|
||||
(AxisBlend::Normal, 0.3),
|
||||
(AxisBlend::Add, 1.0),
|
||||
(AxisBlend::Subtract, 0.5),
|
||||
(AxisBlend::Multiply, 0.24),
|
||||
(AxisBlend::AddSub, 0.4),
|
||||
(AxisBlend::Max, 0.8),
|
||||
] {
|
||||
axes[SectionParameters::RIGHT_TO_LEFT] = axis(blend, 1.0);
|
||||
assert!((axes_signal(channels, &axes) - expected).abs() < 1e-6, "{blend:?}");
|
||||
}
|
||||
|
||||
axes[SectionParameters::RIGHT_TO_LEFT] = axis(AxisBlend::Normal, 1.0);
|
||||
axes[SectionParameters::FRONT_TO_BACK] = axis(AxisBlend::Normal, 1.0);
|
||||
assert!((axes_signal(channels, &axes) - 0.6).abs() < 1e-6, "front to back replaces both");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_weight_lerps_the_unclamped_blend_and_clamps_once() {
|
||||
let channels = [0.9, 0.8, 0.0];
|
||||
let axes = [axis(AxisBlend::Add, 0.5), axis(AxisBlend::Add, 1.0), axis(AxisBlend::Add, 0.0)];
|
||||
assert!((axes_signal(channels, &axes) - 1.0).abs() < 1e-6, "0.8 + 0.45 clamps to 1");
|
||||
let axes = [axis(AxisBlend::Subtract, 0.5), axis(AxisBlend::Add, 1.0), axis(AxisBlend::Add, 0.0)];
|
||||
assert!((axes_signal(channels, &axes) - 0.35).abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn position_balance_is_a_power_curve_and_occlusion_balance_is_linear() {
|
||||
let position = SectionParameters { balance: 0.25, ..defaults(GeneratorKind::Position) };
|
||||
assert!((adjusted(GeneratorKind::Position, &position, 0.5) - 0.5f32.powf(0.2)).abs() < 1e-5);
|
||||
let position = SectionParameters { balance: 0.75, ..position };
|
||||
assert!((adjusted(GeneratorKind::Position, &position, 0.5) - 0.5f32.powf(5.0)).abs() < 1e-5);
|
||||
|
||||
let occlusion = SectionParameters { balance: 0.25, ..defaults(GeneratorKind::AmbientOcclusion) };
|
||||
assert_eq!(adjusted(GeneratorKind::AmbientOcclusion, &occlusion, 0.4), 0.0, "the lower half goes black");
|
||||
assert!((adjusted(GeneratorKind::AmbientOcclusion, &occlusion, 0.75) - 0.5).abs() < 1e-6);
|
||||
|
||||
let curvature = SectionParameters { balance: 0.0, ..defaults(GeneratorKind::Curvature) };
|
||||
assert_eq!(adjusted(GeneratorKind::Curvature, &curvature, 0.4), 0.4, "curvature has no balance");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn contrast_narrows_around_the_middle_and_full_contrast_steps_just_above_it() {
|
||||
let half = SectionParameters { contrast: 0.5, ..defaults(GeneratorKind::Curvature) };
|
||||
assert_eq!(adjusted(GeneratorKind::Curvature, &half, 0.25), 0.0);
|
||||
assert!((adjusted(GeneratorKind::Curvature, &half, 0.6) - 0.7).abs() < 1e-5);
|
||||
|
||||
let full = SectionParameters { contrast: 1.0, ..half };
|
||||
assert_eq!(adjusted(GeneratorKind::Curvature, &full, 0.5), 0.0, "the middle itself stays black");
|
||||
assert_eq!(adjusted(GeneratorKind::Curvature, &full, 0.5001), 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn brightness_lerps_towards_white_or_black_then_invert_flips() {
|
||||
let brighter = SectionParameters { brightness: 0.5, ..defaults(GeneratorKind::WorldSpaceNormals) };
|
||||
assert!((adjusted(GeneratorKind::WorldSpaceNormals, &brighter, 0.4) - 0.7).abs() < 1e-6);
|
||||
let darker = SectionParameters { brightness: -0.5, ..brighter };
|
||||
assert!((adjusted(GeneratorKind::WorldSpaceNormals, &darker, 0.4) - 0.2).abs() < 1e-6);
|
||||
let inverted = SectionParameters { invert: true, ..darker };
|
||||
assert!((adjusted(GeneratorKind::WorldSpaceNormals, &inverted, 0.4) - 0.8).abs() < 1e-6);
|
||||
|
||||
let occlusion = SectionParameters { brightness: 0.5, ..defaults(GeneratorKind::AmbientOcclusion) };
|
||||
assert_eq!(adjusted(GeneratorKind::AmbientOcclusion, &occlusion, 0.4), 0.4, "ambient occlusion has no brightness");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_ambient_occlusion_and_world_space_normals_blur() {
|
||||
let section = SectionParameters { blur: 16.0, ..defaults(GeneratorKind::Position) };
|
||||
assert_eq!(blur_sigma(GeneratorKind::Position, §ion), 0.0);
|
||||
assert_eq!(blur_sigma(GeneratorKind::WorldSpaceNormals, §ion), 72.0);
|
||||
assert_eq!(blur_radius_at(GeneratorKind::AmbientOcclusion, &SectionParameters { blur: 0.0, ..section }, 2048), 0);
|
||||
|
||||
// Three boxes of radius 4 spread a texel with variance 4 × 5, the closest to sigma 4.5 squared
|
||||
assert_eq!(blur_radius_at(GeneratorKind::AmbientOcclusion, &SectionParameters { blur: 1.0, ..section }, 2048), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn light_angles_point_at_the_reference_axes() {
|
||||
let close = |a: Vec3, b: Vec3| (a - b).length() < 1e-5;
|
||||
assert!(close(light_direction(0.0, 0.0), Vec3::NEG_X));
|
||||
assert!(close(light_direction(90.0, 0.0), Vec3::Z));
|
||||
assert!(close(light_direction(180.0, 0.0), Vec3::X));
|
||||
assert!(close(light_direction(33.0, 90.0), Vec3::Y));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn light_lights_the_faces_towards_it() {
|
||||
let light = LightParameters { horizontal: 0.0, vertical: 0.0, attenuation: 0.0, ..LightParameters::defaults(GeneratorKind::Direction).unwrap() };
|
||||
let middle = Vec3::splat(0.5);
|
||||
assert_eq!(light_value(&light, Vec3::NEG_X, middle, false), 1.0);
|
||||
assert_eq!(light_value(&light, Vec3::X, middle, false), 0.0);
|
||||
assert!((light_value(&light, Vec3::new(-1.0, 1.0, 0.0), middle, false) - std::f32::consts::FRAC_1_SQRT_2).abs() < 1e-5, "a plain diffuse falloff");
|
||||
assert_eq!(light_value(&light, Vec3::X, middle, true), 1.0, "invert lights the far side");
|
||||
|
||||
let half_lambert = LightParameters { glossiness: 0.0, ..light };
|
||||
assert!((light_value(&half_lambert, Vec3::Y, middle, false) - 0.5).abs() < 1e-6, "glossiness 0 lights the side faces half");
|
||||
let highlighted = LightParameters { highlight_level: 0.5, ..light };
|
||||
assert!((light_value(&highlighted, Vec3::new(-1.0, 3.0, 0.0), middle, false) - 2.0 * 10f32.sqrt().recip()).abs() < 1e-5);
|
||||
let saturated = LightParameters { highlight_level: 1.0, ..light };
|
||||
assert_eq!(light_value(&saturated, Vec3::new(-0.01, 1.0, 0.0), middle, false), 1.0, "any lit texel is white");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attenuation_darkens_the_side_away_from_the_light() {
|
||||
let light = LightParameters { horizontal: 0.0, vertical: 0.0, glossiness: 0.0, ..LightParameters::defaults(GeneratorKind::Direction).unwrap() };
|
||||
let near = light_value(&light, Vec3::Y, Vec3::new(0.0, 0.5, 0.5), false);
|
||||
let far = light_value(&light, Vec3::Y, Vec3::new(1.0, 0.5, 0.5), false);
|
||||
assert!((near - 0.5).abs() < 1e-6, "the face of the bounds towards the light keeps its value");
|
||||
assert!((far - 0.25).abs() < 1e-6, "attenuation 0.25 halves it across the bounds");
|
||||
|
||||
let none = LightParameters { attenuation: 0.0, ..light };
|
||||
assert_eq!(light_value(&none, Vec3::Y, Vec3::new(1.0, 0.5, 0.5), false), near);
|
||||
let full = LightParameters { attenuation: 1.0, ..light };
|
||||
assert_eq!(light_value(&full, Vec3::Y, Vec3::new(0.0, 0.5, 0.5), false), 0.0, "attenuation 1 is black everywhere");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
/// Where a generator's image slot is read: `scale` times across the UV square (or the mesh's bounds, triplanar), plus `offset`
|
||||
pub(crate) struct SlotPlacement {
|
||||
pub scale: f32,
|
||||
pub offset: f32,
|
||||
/// How sharply the three projections meet, or None to read in UV
|
||||
pub triplanar_contrast: Option<f32>,
|
||||
/// The X projection's mirrored U turns about the bounds' centre, which a centred scale keeps fixed (Use Texture); else about 0, as custom grunge was fitted
|
||||
pub mirrored_about_centre: bool,
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
//! A generator's texture (Use Texture): where it is read, how it turns gray and how it blends over the signal; its custom grunge is read the same way
|
||||
|
||||
use texturecraft_core::{TextureBlend, TextureLayer};
|
||||
use texturecraft_geom::glam::{Vec2, Vec3};
|
||||
|
||||
pub(crate) use crate::slot_placement::SlotPlacement;
|
||||
|
||||
/// Exponent of the triplanar weights per unit of `1 / (1 − triplanar contrast)`: contrast 0 weighs the axes by the normal itself, 0.5 by its cube
|
||||
const TRIPLANAR_SHARPNESS_POWER: f32 = 1.58;
|
||||
|
||||
/// Smallest normal component still dividing the weights, so a zero normal weighs the axes evenly
|
||||
const MIN_NORMAL_COMPONENT: f32 = 1e-6;
|
||||
|
||||
/// The texture is scaled about the centre of the UV square (or of the mesh's bounds)
|
||||
pub(crate) fn texture_placement(texture: &TextureLayer) -> SlotPlacement {
|
||||
SlotPlacement {
|
||||
scale: texture.scale,
|
||||
offset: 0.5 * (1.0 - texture.scale),
|
||||
triplanar_contrast: texture.triplanar.then_some(texture.triplanar_contrast),
|
||||
mirrored_about_centre: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a slot is read in UV
|
||||
pub(crate) fn uv_coordinates(placement: &SlotPlacement, uv: Vec2) -> Vec2 {
|
||||
uv * placement.scale + Vec2::splat(placement.offset)
|
||||
}
|
||||
|
||||
/// Where a slot is read on each of the three projections (facing X, Y and Z) for `position` across the mesh's bounds (0..1)
|
||||
pub(crate) fn triplanar_coordinates(placement: &SlotPlacement, position: Vec3) -> [Vec2; 3] {
|
||||
let placed = |u: f32, v: f32| Vec2::new(u, v) * placement.scale + Vec2::splat(placement.offset);
|
||||
let mirrored_z = if placement.mirrored_about_centre { 1.0 - position.z } else { -position.z };
|
||||
[placed(mirrored_z, position.y), placed(position.x, position.z), placed(position.x, position.y)]
|
||||
}
|
||||
|
||||
/// How much each projection (facing X, Y and Z) counts for a surface facing `normal` at triplanar `contrast`, summing to 1
|
||||
pub(crate) fn triplanar_weights(contrast: f32, normal: Vec3) -> [f32; 3] {
|
||||
let contrast = contrast.clamp(*TextureLayer::TRIPLANAR_CONTRAST_RANGE.start(), *TextureLayer::TRIPLANAR_CONTRAST_RANGE.end());
|
||||
let sharpness = (1.0 - contrast).max(f32::EPSILON).powf(-TRIPLANAR_SHARPNESS_POWER);
|
||||
let facing = normal.abs();
|
||||
let largest = facing.max_element().max(MIN_NORMAL_COMPONENT);
|
||||
let weights = (facing / largest).powf(sharpness);
|
||||
let total = weights.x + weights.y + weights.z;
|
||||
if total > 0.0 { (weights / total).to_array() } else { [1.0 / 3.0; 3] }
|
||||
}
|
||||
|
||||
/// The texture's gray from its color: converted, inverted, contrasted, then brightened
|
||||
pub(crate) fn texture_gray(texture: &TextureLayer, rgb: [f32; 3]) -> f32 {
|
||||
let gray = texture.grayscale.gray(rgb).clamp(0.0, 1.0);
|
||||
let gray = if texture.invert { 1.0 - gray } else { gray };
|
||||
|
||||
let contrast = texture.contrast.clamp(-1.0, 1.0);
|
||||
let gray = if contrast > 0.0 {
|
||||
let range = (1.0 - contrast).max(f32::EPSILON);
|
||||
((gray - 0.5) / range + 0.5).clamp(0.0, 1.0)
|
||||
} else {
|
||||
(gray - 0.5) * (1.0 + contrast) + 0.5
|
||||
};
|
||||
|
||||
let brightness = texture.brightness.clamp(-1.0, 1.0);
|
||||
if brightness > 0.0 { gray + brightness * (1.0 - gray) } else { gray * (1.0 + brightness) }
|
||||
}
|
||||
|
||||
/// `gray` (the texture) blended over `signal` by the texture's blending mode and opacity
|
||||
pub(crate) fn blended_over(texture: &TextureLayer, signal: f32, gray: f32) -> f32 {
|
||||
let blend = match texture.blend {
|
||||
TextureBlend::Normal => gray,
|
||||
TextureBlend::Add => signal + gray,
|
||||
TextureBlend::Subtract => signal - gray,
|
||||
TextureBlend::Multiply => signal * gray,
|
||||
TextureBlend::AddSub => signal + 2.0 * gray - 1.0,
|
||||
TextureBlend::Max => signal.max(gray),
|
||||
TextureBlend::Min => signal.min(gray),
|
||||
TextureBlend::Overlay => {
|
||||
if signal < 0.5 {
|
||||
2.0 * signal * gray
|
||||
} else {
|
||||
1.0 - 2.0 * (1.0 - signal) * (1.0 - gray)
|
||||
}
|
||||
}
|
||||
TextureBlend::Screen => 1.0 - (1.0 - signal) * (1.0 - gray),
|
||||
TextureBlend::SoftLight => {
|
||||
if gray < 0.5 {
|
||||
2.0 * signal * gray + signal * signal * (1.0 - 2.0 * gray)
|
||||
} else {
|
||||
2.0 * signal * (1.0 - gray) + signal.max(0.0).sqrt() * (2.0 * gray - 1.0)
|
||||
}
|
||||
}
|
||||
};
|
||||
let opacity = texture.opacity.clamp(0.0, 1.0);
|
||||
(signal + (blend - signal) * opacity).clamp(0.0, 1.0)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use texturecraft_core::GeneratorGrayscale;
|
||||
|
||||
fn texture() -> TextureLayer {
|
||||
TextureLayer { enabled: true, opacity: 1.0, ..TextureLayer::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlay_at_full_opacity_darkens_darks_and_lightens_lights() {
|
||||
let texture = texture();
|
||||
assert!((blended_over(&texture, 0.25, 0.5) - 0.25).abs() < 1e-6, "mid gray leaves a dark signal unchanged");
|
||||
assert!(blended_over(&texture, 0.25, 0.2) < 0.25);
|
||||
assert!(blended_over(&texture, 0.75, 0.8) > 0.75);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opacity_zero_leaves_the_signal() {
|
||||
let texture = TextureLayer { opacity: 0.0, blend: TextureBlend::Normal, ..texture() };
|
||||
assert_eq!(blended_over(&texture, 0.3, 0.9), 0.3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_blend_stays_in_range() {
|
||||
for blend in TextureBlend::ALL {
|
||||
let texture = TextureLayer { blend, ..texture() };
|
||||
for signal in [0.0, 0.3, 0.5, 1.0] {
|
||||
for gray in [0.0, 0.4, 1.0] {
|
||||
let value = blended_over(&texture, signal, gray);
|
||||
assert!((0.0..=1.0).contains(&value), "{blend:?} {signal} {gray} -> {value}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gray_is_converted_then_inverted_contrasted_and_brightened() {
|
||||
let red = [1.0, 0.0, 0.0];
|
||||
assert_eq!(texture_gray(&TextureLayer { grayscale: GeneratorGrayscale::Red, ..texture() }, red), 1.0);
|
||||
assert_eq!(texture_gray(&TextureLayer { grayscale: GeneratorGrayscale::Green, ..texture() }, red), 0.0);
|
||||
assert!((texture_gray(&TextureLayer { grayscale: GeneratorGrayscale::Desaturation, ..texture() }, red) - 0.5).abs() < 1e-6);
|
||||
let inverted = TextureLayer { grayscale: GeneratorGrayscale::Red, invert: true, ..texture() };
|
||||
assert_eq!(texture_gray(&inverted, red), 0.0);
|
||||
let contrasted = TextureLayer { contrast: 0.5, ..texture() };
|
||||
assert!((texture_gray(&contrasted, [0.6; 3]) - 0.7).abs() < 1e-5, "contrast 0.5 doubles the distance from the middle");
|
||||
let flattened = TextureLayer { contrast: -1.0, ..texture() };
|
||||
assert!((texture_gray(&flattened, [0.9; 3]) - 0.5).abs() < 1e-6, "contrast −1 is flat gray");
|
||||
let brightened = TextureLayer { brightness: 0.5, ..texture() };
|
||||
assert!((texture_gray(&brightened, [0.4; 3]) - 0.7).abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn triplanar_weights_follow_the_normal_and_sharpen_with_contrast() {
|
||||
let along_y = triplanar_weights(texture().triplanar_contrast, Vec3::Y);
|
||||
assert!((along_y[1] - 1.0).abs() < 1e-6);
|
||||
let diagonal = Vec3::new(1.0, 0.5, 0.0).normalize();
|
||||
let (soft, hard) = (triplanar_weights(0.001, diagonal), triplanar_weights(0.9, diagonal));
|
||||
assert!(hard[0] > soft[0] && hard[1] < soft[1]);
|
||||
assert!((soft.iter().sum::<f32>() - 1.0).abs() < 1e-5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scale_is_about_the_centre() {
|
||||
let placement = texture_placement(&TextureLayer { scale: 2.0, ..texture() });
|
||||
assert_eq!(uv_coordinates(&placement, Vec2::splat(0.5)), Vec2::splat(0.5));
|
||||
assert_eq!(uv_coordinates(&placement, Vec2::new(0.75, 0.25)), Vec2::new(1.0, 0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_triplanar_projection_is_scaled_about_the_centre_of_the_bounds() {
|
||||
let placement = texture_placement(&TextureLayer { scale: 1.5, triplanar: true, ..texture() });
|
||||
for (axis, at) in triplanar_coordinates(&placement, Vec3::splat(0.5)).into_iter().enumerate() {
|
||||
assert!((at - Vec2::splat(0.5)).abs().max_element() < 1e-6, "projection {axis} reads {at} at the centre");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
//! The 3D Distance and 3D Linear Gradient generators: gradients around a point and between two points across the mesh's bounds
|
||||
|
||||
use texturecraft_core::{DistanceParameters, GeneratorGlobal, LinearGradientParameters};
|
||||
use texturecraft_geom::glam::Vec3;
|
||||
|
||||
use crate::histogram_scan::histogram_scan;
|
||||
|
||||
/// The value at `position` (0..1 across the bounds, the longest side spanning 0..1): 1 at the point, 0 at the radius, then scanned by the offset and contrast
|
||||
pub(crate) fn distance_value(distance: &DistanceParameters, position: Vec3) -> f32 {
|
||||
let from_point = position.distance(Vec3::from(distance.point));
|
||||
let gradient = if distance.radius > 0.0 { (1.0 - from_point / distance.radius).clamp(0.0, 1.0) } else { 0.0 };
|
||||
histogram_scan(gradient, distance.offset, distance.contrast)
|
||||
}
|
||||
|
||||
/// Smallest squared start-to-end span the gradient divides by
|
||||
const MIN_GRADIENT_LENGTH_SQUARED: f32 = 1e-12;
|
||||
|
||||
/// The value at `position`: how far along from the start to the end it lies (0 at the start, 1 at the end), balanced and contrasted like a generator's global controls
|
||||
pub(crate) fn linear_gradient_value(gradient: &LinearGradientParameters, position: Vec3) -> f32 {
|
||||
let (start, end) = (Vec3::from(gradient.start), Vec3::from(gradient.end));
|
||||
let span = end - start;
|
||||
let along = if span.length_squared() > MIN_GRADIENT_LENGTH_SQUARED { (position - start).dot(span) / span.length_squared() } else { 0.0 };
|
||||
GeneratorGlobal { balance: gradient.balance, contrast: gradient.contrast, ..GeneratorGlobal::default() }.apply(along.clamp(0.0, 1.0))
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
//! The UV Border Distance generator: how far each texel lies inside its UV island, as a gradient built once per UV layout and settings
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use rayon::prelude::*;
|
||||
use texturecraft_core::{BorderDistanceParameters, GeneratorGlobal};
|
||||
|
||||
use crate::eval::Inputs;
|
||||
use crate::field_cache::FieldCache;
|
||||
use crate::working_field::{REFERENCE_TILE_TEXELS, blur_blocks, box_radius};
|
||||
|
||||
/// How far in the gradient reaches at Distance 1, in UV units (fitted: about half a UV tile)
|
||||
const REACH_PER_DISTANCE: f32 = 0.4936;
|
||||
|
||||
/// The blur at Smoothness 1, as a gaussian sigma in texels of a 2K UV tile (fitted)
|
||||
const SMOOTHNESS_SIGMA_2K: f32 = 45.0;
|
||||
|
||||
static CACHE: FieldCache = FieldCache::new();
|
||||
|
||||
/// The gradient before balance, contrast and invert for every working texel of `inp` (0 outside the islands)
|
||||
pub(crate) fn border_gradient(inp: &Inputs, geometry: u64, border: &BorderDistanceParameters) -> Arc<Vec<f32>> {
|
||||
CACHE.get_or_build(inp, geometry, &[], vec![border.distance.to_bits(), border.smoothness.to_bits()], |block| build(inp, border, block))
|
||||
}
|
||||
|
||||
/// The value at a working texel: the gradient balanced, contrasted and inverted
|
||||
pub(crate) fn border_value(border: &BorderDistanceParameters, gradient: f32) -> f32 {
|
||||
GeneratorGlobal { balance: border.balance, contrast: border.contrast, ..GeneratorGlobal::default() }.apply(gradient)
|
||||
}
|
||||
|
||||
fn build(inp: &Inputs, border: &BorderDistanceParameters, block: (u32, u32)) -> Vec<f32> {
|
||||
let gbuf = inp.gbuf;
|
||||
let (width, height) = (gbuf.width, gbuf.height);
|
||||
|
||||
// Every covered texel's distance to the nearest uncovered one, within its UV tile
|
||||
let distances = border_distances(gbuf, (width, height), block);
|
||||
|
||||
let mut gradient: Vec<f32> = (0..width * height)
|
||||
.into_par_iter()
|
||||
.map(|texel| {
|
||||
if !gbuf.covered(texel as usize) {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
let (x, y) = (texel % width, texel / width);
|
||||
let tile_texels = block.0 as f32 * inp.block_scales.at(x, y);
|
||||
let to_border = distances.get(texel as usize).copied().unwrap_or(0.0);
|
||||
let reach = border.distance * REACH_PER_DISTANCE * tile_texels;
|
||||
if reach > 0.0 { (1.0 - to_border / reach).clamp(0.0, 1.0) } else { 0.0 }
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Smoothness blurs the gradient with the empty space around the islands, so their borders soften towards black
|
||||
if border.smoothness > 0.0 {
|
||||
let radius_at = |tile_texels: f32| box_radius(border.smoothness * SMOOTHNESS_SIGMA_2K * tile_texels / REFERENCE_TILE_TEXELS);
|
||||
blur_blocks(&mut gradient, (width, height), block, |left, top| radius_at(block.0 as f32 * inp.block_scales.at(left, top)));
|
||||
for (value, texel) in gradient.iter_mut().zip(0..) {
|
||||
if !gbuf.covered(texel) {
|
||||
*value = 0.0;
|
||||
}
|
||||
}
|
||||
}
|
||||
gradient
|
||||
}
|
||||
|
||||
/// Each texel's Euclidean distance in texels to the nearest uncovered texel of its UV tile block, the space past the block's edges counting as uncovered
|
||||
pub(crate) fn border_distances(gbuf: &texturecraft_geom::UvGBuffer, (width, height): (u32, u32), block: (u32, u32)) -> Vec<f32> {
|
||||
let mut squared = vec![0.0f32; (width * height) as usize];
|
||||
for top in (0..height).step_by(block.1 as usize) {
|
||||
for left in (0..width).step_by(block.0 as usize) {
|
||||
let (columns, rows) = (block.0.min(width - left) as usize, block.1.min(height - top) as usize);
|
||||
let index = |column: usize, row: usize| (top as usize + row) * width as usize + left as usize + column;
|
||||
|
||||
// A ring of uncovered texels around the block, then the exact transform along rows and columns
|
||||
let (padded_columns, padded_rows) = (columns + 2, rows + 2);
|
||||
let mut field: Vec<f32> = (0..padded_rows)
|
||||
.flat_map(|row| (0..padded_columns).map(move |column| (column, row)))
|
||||
.map(|(column, row)| {
|
||||
let inside = (1..=columns).contains(&column) && (1..=rows).contains(&row);
|
||||
if inside && gbuf.covered(index(column - 1, row - 1)) { f32::INFINITY } else { 0.0 }
|
||||
})
|
||||
.collect();
|
||||
field.par_chunks_mut(padded_columns).for_each(squared_distance_line);
|
||||
let mut transposed: Vec<f32> = (0..padded_columns * padded_rows)
|
||||
.map(|texel| field.get((texel % padded_rows) * padded_columns + texel / padded_rows).copied().unwrap_or(0.0))
|
||||
.collect();
|
||||
transposed.par_chunks_mut(padded_rows).for_each(squared_distance_line);
|
||||
|
||||
for row in 0..rows {
|
||||
for column in 0..columns {
|
||||
let value = transposed.get((column + 1) * padded_rows + row + 1).copied().unwrap_or(0.0);
|
||||
if let Some(target) = squared.get_mut(index(column, row)) {
|
||||
*target = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
squared.into_iter().map(f32::sqrt).collect()
|
||||
}
|
||||
|
||||
/// The squared distance transform of one line in place (Felzenszwalb and Huttenlocher's lower envelope of parabolas); `line` holds 0 at sources and infinity elsewhere
|
||||
fn squared_distance_line(line: &mut [f32]) {
|
||||
let length = line.len();
|
||||
let input = line.to_vec();
|
||||
let finite: Vec<usize> = (0..length).filter(|index| input.get(*index).is_some_and(|value| value.is_finite())).collect();
|
||||
if finite.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
// Parabola vertices and the boundaries between them
|
||||
let value_at = |index: usize| input.get(index).copied().unwrap_or(f32::INFINITY);
|
||||
let intersection = |a: usize, b: usize| ((value_at(b) + (b * b) as f32) - (value_at(a) + (a * a) as f32)) / (2.0 * (b as f32 - a as f32));
|
||||
let mut vertices: Vec<usize> = Vec::with_capacity(finite.len());
|
||||
let mut boundaries: Vec<f32> = Vec::with_capacity(finite.len() + 1);
|
||||
for &index in &finite {
|
||||
while let (Some(&last), Some(&start)) = (vertices.last(), boundaries.last()) {
|
||||
if intersection(last, index) <= start {
|
||||
vertices.pop();
|
||||
boundaries.pop();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let start = vertices.last().map_or(f32::NEG_INFINITY, |&last| intersection(last, index));
|
||||
vertices.push(index);
|
||||
boundaries.push(start);
|
||||
}
|
||||
|
||||
let mut current = 0;
|
||||
for (index, value) in line.iter_mut().enumerate() {
|
||||
while boundaries.get(current + 1).is_some_and(|next| *next < index as f32) {
|
||||
current += 1;
|
||||
}
|
||||
let vertex = vertices.get(current).copied().unwrap_or(index);
|
||||
let offset = index as f32 - vertex as f32;
|
||||
*value = offset * offset + value_at(vertex);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_line_reads_the_squared_distance_to_its_nearest_source() {
|
||||
let mut line = [0.0, f32::INFINITY, f32::INFINITY, f32::INFINITY, f32::INFINITY, 0.0, f32::INFINITY];
|
||||
squared_distance_line(&mut line);
|
||||
assert_eq!(line, [0.0, 1.0, 4.0, 4.0, 1.0, 0.0, 1.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_without_sources_stays_unreached() {
|
||||
let mut line = [f32::INFINITY; 3];
|
||||
squared_distance_line(&mut line);
|
||||
assert!(line.iter().all(|value| value.is_infinite()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
//! The UV island generators (UV Random Color, UV Checker) at every working texel, built once per layout and settings
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use rayon::prelude::*;
|
||||
use texturecraft_core::{GeneratorKind, UvCheckerParameters, UvRandomColorParameters};
|
||||
use texturecraft_geom::{NO_TRI, TrianglePartition};
|
||||
use texturecraft_texel::linear_to_srgb;
|
||||
use texturecraft_texel::noise::cell_hash;
|
||||
|
||||
use crate::eval::{Inputs, texel_coords};
|
||||
use crate::field_cache::FieldCache;
|
||||
use crate::uv_border_distance::border_distances;
|
||||
use crate::working_field::REFERENCE_TILE_TEXELS;
|
||||
|
||||
static CACHE: FieldCache = FieldCache::new();
|
||||
|
||||
/// UV Random Color at every working texel of `inp`: one value per UV island (0 outside the islands)
|
||||
pub(crate) fn random_color_field(inp: &Inputs, geometry: u64, random: &UvRandomColorParameters, seed: u32) -> Arc<Vec<f32>> {
|
||||
let mut settings = vec![GeneratorKind::UvRandomColor as u32, seed, u32::from(random.custom_gradient)];
|
||||
settings.push(random.used_colors().len() as u32);
|
||||
settings.extend(random.used_colors().iter().flat_map(|color| color.map(f32::to_bits)));
|
||||
settings.extend(random.positions.iter().map(|position| position.to_bits()));
|
||||
|
||||
CACHE.get_or_build(inp, geometry, &[], settings, |_| {
|
||||
let island_values = island_values(inp, |island| random_gray(random, seed, island));
|
||||
let gbuf = inp.gbuf;
|
||||
gbuf.tri.par_iter().map(|triangle| island_values.get(triangle).copied().unwrap_or(0.0)).collect()
|
||||
})
|
||||
}
|
||||
|
||||
/// The value `value_of` gives each UV island, by triangle
|
||||
fn island_values(inp: &Inputs, value_of: impl Fn(u32) -> f32) -> HashMap<u32, f32> {
|
||||
let material = inp.project.texture_set(inp.ts).map_or(0, |set| set.material);
|
||||
let islands = TrianglePartition::uv_islands(inp.mesh, material);
|
||||
islands
|
||||
.groups
|
||||
.iter()
|
||||
.enumerate()
|
||||
.flat_map(|(island, triangles)| {
|
||||
let value = value_of(island as u32);
|
||||
triangles.iter().map(move |triangle| (*triangle, value))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// An island's gray: the mean of a random color's channels, or of the gradient's color at a random point
|
||||
fn random_gray(random: &UvRandomColorParameters, seed: u32, island: u32) -> f32 {
|
||||
let island = island as i32;
|
||||
let color = if random.custom_gradient {
|
||||
random.at(cell_hash(island, 0, 0, seed)).unwrap_or([0.0; 3])
|
||||
} else {
|
||||
std::array::from_fn(|channel| cell_hash(island, channel as i32 + 1, 0, seed))
|
||||
};
|
||||
color.iter().sum::<f32>() / 3.0
|
||||
}
|
||||
|
||||
/// Checker squares across one grid tile, and grid lines across one square (fitted)
|
||||
const SQUARES_PER_GRID_TILE: f32 = 4.0;
|
||||
const MINOR_LINES_PER_SQUARE: f32 = 4.0;
|
||||
|
||||
/// The dark squares are the light color times this, on its sRGB-encoded values (fitted)
|
||||
const DARK_SQUARE_SHADE: f32 = 0.7128;
|
||||
|
||||
/// What a full-opacity minor and major grid line multiply the color by (fitted)
|
||||
const MINOR_LINE_SHADE: f32 = 0.8465;
|
||||
const MAJOR_LINE_SHADE: f32 = 0.4230;
|
||||
|
||||
/// Texels of a 2K UV tile a grid line lies within of its square's edge, and the border's width per unit of UV Borders Width (fitted: 0.2 is 3 texels)
|
||||
const LINE_HALF_WIDTH_2K: f32 = 1.0;
|
||||
const BORDER_TEXELS_PER_WIDTH_2K: f32 = 15.0;
|
||||
|
||||
/// The saturation and value random island colors are picked within (measured)
|
||||
const RANDOM_SATURATION: std::ops::RangeInclusive<f32> = 0.06..=0.57;
|
||||
const RANDOM_VALUE: std::ops::RangeInclusive<f32> = 0.42..=0.80;
|
||||
|
||||
/// UV Checker at every working texel of `inp`: the gray of its color, the mean of the sRGB-encoded channels as the reference reads it (0 outside the islands)
|
||||
pub(crate) fn checker_field(inp: &Inputs, geometry: u64, checker: &UvCheckerParameters, seed: u32) -> Arc<Vec<f32>> {
|
||||
let mut settings = vec![
|
||||
GeneratorKind::UvChecker as u32,
|
||||
seed,
|
||||
u32::from(checker.random_colors),
|
||||
checker.grid_tile,
|
||||
checker.grid_opacity.to_bits(),
|
||||
checker.border_width.to_bits(),
|
||||
];
|
||||
settings.extend(checker.checker_color.iter().chain(&checker.border_color).map(|value| value.to_bits()));
|
||||
|
||||
CACHE.get_or_build(inp, geometry, &[], settings, |block| {
|
||||
let gbuf = inp.gbuf;
|
||||
let (width, height) = (gbuf.width, gbuf.height);
|
||||
let island_colors = if checker.random_colors { island_colors(inp, seed) } else { HashMap::new() };
|
||||
let distances = (checker.border_width > 0.0).then(|| border_distances(gbuf, (width, height), block));
|
||||
let border_width_texels_2k = checker.border_width * BORDER_TEXELS_PER_WIDTH_2K;
|
||||
let light = checker.checker_color.map(linear_to_srgb);
|
||||
let border = checker.border_color.map(linear_to_srgb);
|
||||
|
||||
(0..width * height)
|
||||
.into_par_iter()
|
||||
.map(|texel| {
|
||||
let Some(triangle) = gbuf.tri.get(texel as usize).copied().filter(|triangle| *triangle != NO_TRI) else { return 0.0 };
|
||||
|
||||
let (x, y) = (texel % width, texel / width);
|
||||
let texels_2k = REFERENCE_TILE_TEXELS / (block.0 as f32 * inp.block_scales.at(x, y));
|
||||
|
||||
// Measure from the texel footprint so coarse texels still show the border they cover
|
||||
let on_border = distances.as_ref().is_some_and(|distances| {
|
||||
let distance = distances.get(texel as usize).copied().unwrap_or(0.0);
|
||||
distance * texels_2k - footprint_beyond_one(texels_2k) <= border_width_texels_2k
|
||||
});
|
||||
let color = if on_border {
|
||||
border
|
||||
} else {
|
||||
let uv = texel_coords(inp, x, y).uv;
|
||||
let light = island_colors.get(&triangle).copied().unwrap_or(light);
|
||||
let at = (uv.x.rem_euclid(1.0) * REFERENCE_TILE_TEXELS, uv.y.rem_euclid(1.0) * REFERENCE_TILE_TEXELS);
|
||||
checker_color(checker, light, at, texels_2k)
|
||||
};
|
||||
color.iter().sum::<f32>() / 3.0
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
}
|
||||
|
||||
/// How many 2K texels a working texel `texels_2k` of them wide covers beyond the one at its centre
|
||||
fn footprint_beyond_one(texels_2k: f32) -> f32 {
|
||||
(texels_2k - 1.0).max(0.0)
|
||||
}
|
||||
|
||||
/// The checker's sRGB-encoded color at (`x`, `y`) in texels of a 2K UV tile (row 0 at the top) for a texel `texels_2k` of them wide, with `light` its light squares
|
||||
fn checker_color(checker: &UvCheckerParameters, light: [f32; 3], (x, y): (f32, f32), texels_2k: f32) -> [f32; 3] {
|
||||
let square = REFERENCE_TILE_TEXELS / (SQUARES_PER_GRID_TILE * checker.grid_tile.max(1) as f32);
|
||||
let is_light = ((x / square).floor() + (y / square).floor()).rem_euclid(2.0) >= 1.0;
|
||||
let base = if is_light { light } else { light.map(|channel| channel * DARK_SQUARE_SHADE) };
|
||||
|
||||
// Line layers in the reference's order, each laid over the last at the grid's opacity
|
||||
let minor = square / MINOR_LINES_PER_SQUARE;
|
||||
|
||||
// Include the texel footprint so thin grid lines survive coarse sampling
|
||||
let reach = LINE_HALF_WIDTH_2K + footprint_beyond_one(texels_2k) / 2.0;
|
||||
let on_line = |position: f32, period: f32| (position - (position / period).round() * period).abs() < reach;
|
||||
let layers = [
|
||||
(on_line(y, minor) && !on_line(y, square), MINOR_LINE_SHADE),
|
||||
(on_line(x, minor) && !on_line(x, square), MINOR_LINE_SHADE),
|
||||
(on_line(y, square), MAJOR_LINE_SHADE),
|
||||
(on_line(x, square), MAJOR_LINE_SHADE),
|
||||
];
|
||||
let opacity = checker.grid_opacity.clamp(0.0, 1.0);
|
||||
let shade = layers.iter().filter(|(on, _)| *on).fold(1.0, |shade, (_, line)| shade + (line - shade) * opacity);
|
||||
base.map(|channel| channel * shade)
|
||||
}
|
||||
|
||||
/// A random light sRGB-encoded color per UV island, by triangle
|
||||
fn island_colors(inp: &Inputs, seed: u32) -> HashMap<u32, [f32; 3]> {
|
||||
let material = inp.project.texture_set(inp.ts).map_or(0, |set| set.material);
|
||||
let islands = TrianglePartition::uv_islands(inp.mesh, material);
|
||||
islands
|
||||
.groups
|
||||
.iter()
|
||||
.enumerate()
|
||||
.flat_map(|(island, triangles)| {
|
||||
let island = island as i32;
|
||||
let within = |range: &std::ops::RangeInclusive<f32>, random: f32| range.start() + (range.end() - range.start()) * random;
|
||||
let color = hsv_to_rgb(
|
||||
cell_hash(island, 0, 1, seed),
|
||||
within(&RANDOM_SATURATION, cell_hash(island, 1, 1, seed)),
|
||||
within(&RANDOM_VALUE, cell_hash(island, 2, 1, seed)),
|
||||
);
|
||||
triangles.iter().map(move |triangle| (*triangle, color))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A color from its hue (in turns), saturation and value
|
||||
fn hsv_to_rgb(hue: f32, saturation: f32, value: f32) -> [f32; 3] {
|
||||
let sector = hue.rem_euclid(1.0) * 6.0;
|
||||
let fraction = sector - sector.floor();
|
||||
let (low, falling, rising) = (value * (1.0 - saturation), value * (1.0 - saturation * fraction), value * (1.0 - saturation * (1.0 - fraction)));
|
||||
match sector.floor() as u32 {
|
||||
0 => [value, rising, low],
|
||||
1 => [falling, value, low],
|
||||
2 => [low, value, rising],
|
||||
3 => [low, falling, value],
|
||||
4 => [rising, low, value],
|
||||
_ => [value, low, falling],
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
//! The wear generators' value at a texel (Metal Edge Wear, Fiber Glass Edge Wear, Dirt), fitted to the reference app's observed results
|
||||
|
||||
use texturecraft_core::{GeneratorKind, Procedural, Projection, WearParameters};
|
||||
|
||||
use crate::curvature_sizes::LEVEL_RADII;
|
||||
use crate::grunge_pattern::grunge_pattern;
|
||||
use crate::pattern::{Coords, procedural};
|
||||
use crate::slot_placement::SlotPlacement;
|
||||
use crate::wear_inputs::WearInputs;
|
||||
use crate::wear_scan::{DIRT_SCAN, EDGE_WEAR_SCAN, FIBER_GLASS_SCAN};
|
||||
|
||||
/// The Gaussian sigma each blurred curvature level spreads like: three box blurs of radius r spread √(r(r+1)), radii from [`LEVEL_RADII`]
|
||||
const LEVEL_SIGMAS: [f32; LEVEL_RADII.len()] = [1.414, 2.449, 4.472, 8.485, 16.492, 32.496, 64.498, 128.499];
|
||||
|
||||
/// Gaussian sigma per unit of edges smoothness, in texels at 2K
|
||||
const EDGE_WEAR_SMOOTHNESS_SIGMA: f32 = 4.6;
|
||||
const FIBER_GLASS_SMOOTHNESS_SIGMA: f32 = 4.5;
|
||||
/// The share of the blurred curvature in the smoothed edges
|
||||
const SMOOTHED_SHARE: f32 = 0.5;
|
||||
/// Dirt reads its edges and cavities slightly softened, sigma in texels at 2K
|
||||
const DIRT_CURVATURE_SIGMA: f32 = 1.49;
|
||||
|
||||
/// How much a breakup pattern varies the grunge's strength (0 none, 1 down to nothing)
|
||||
const BREAKUP_DEPTH: f32 = 0.6;
|
||||
|
||||
/// The triplanar seams' sharpness at triplanar contrast 0 and 1
|
||||
const TRIPLANAR_SHARPNESS: std::ops::RangeInclusive<f32> = 1.0..=16.0;
|
||||
|
||||
/// The gray at which a custom grunge neither adds nor removes wear
|
||||
const CUSTOM_GRUNGE_MID_GRAY: f32 = 0.5;
|
||||
|
||||
/// Where the reference app reads a custom grunge at the UV square's origin: half way across the image (triplanar: at its origin)
|
||||
const CUSTOM_GRUNGE_UV_OFFSET: f32 = 0.5;
|
||||
|
||||
/// The Gaussian sigma (texels at 2K) the kind's blurred curvature is read at
|
||||
pub(crate) fn blur_sigma(kind: GeneratorKind, wear: &WearParameters) -> f32 {
|
||||
match kind {
|
||||
GeneratorKind::Dirt => DIRT_CURVATURE_SIGMA,
|
||||
GeneratorKind::FiberGlassEdgeWear => FIBER_GLASS_SMOOTHNESS_SIGMA * wear.edges_smoothness,
|
||||
_ => EDGE_WEAR_SMOOTHNESS_SIGMA * wear.edges_smoothness,
|
||||
}
|
||||
}
|
||||
|
||||
fn triplanar_sharpness(wear: &WearParameters) -> f32 {
|
||||
TRIPLANAR_SHARPNESS.start() + (TRIPLANAR_SHARPNESS.end() - TRIPLANAR_SHARPNESS.start()) * wear.triplanar_contrast
|
||||
}
|
||||
|
||||
/// The wear's own grunge at `coords`, normalised to mean 0 and spread 1
|
||||
pub(crate) fn grunge(kind: GeneratorKind, wear: &WearParameters, seed: u32, coords: &Coords) -> f32 {
|
||||
let grunge = grunge_pattern(kind);
|
||||
let pattern = Procedural { scale: grunge.repeats_per_scale * wear.grunge_scale, seed, ..Procedural::new(grunge.kind) };
|
||||
let projection = if wear.triplanar {
|
||||
Projection::Triplanar { scale: 1.0, sharpness: triplanar_sharpness(wear), offset: [0.0; 3], uv: Default::default(), projector: Default::default() }
|
||||
} else {
|
||||
Projection::Uv { scale: [1.0, 1.0], rotation: grunge.rotation, offset: [0.0, 0.0] }
|
||||
};
|
||||
let mut value = procedural(&pattern, &projection, coords);
|
||||
if let Some((breakup, repeats_per_scale)) = grunge.breakup {
|
||||
let breakup = Procedural { scale: repeats_per_scale * wear.grunge_scale, seed, ..Procedural::new(breakup) };
|
||||
value *= 1.0 - BREAKUP_DEPTH + BREAKUP_DEPTH * procedural(&breakup, &projection, coords);
|
||||
}
|
||||
(value - grunge.mean) / grunge.spread
|
||||
}
|
||||
|
||||
/// Where a custom grunge image is read: repeated grunge-scale times across the UV square (or the mesh's bounds, triplanar)
|
||||
pub(crate) fn custom_grunge_placement(wear: &WearParameters) -> SlotPlacement {
|
||||
if wear.triplanar {
|
||||
SlotPlacement { scale: wear.grunge_scale, offset: 0.0, triplanar_contrast: Some(wear.triplanar_contrast), mirrored_about_centre: false }
|
||||
} else {
|
||||
SlotPlacement { scale: wear.grunge_scale, offset: CUSTOM_GRUNGE_UV_OFFSET, triplanar_contrast: None, mirrored_about_centre: false }
|
||||
}
|
||||
}
|
||||
|
||||
/// A custom grunge's `gray` as the normalised grunge the fitted signals read; the reference app's seed leaves it where it is
|
||||
pub(crate) fn custom_grunge(kind: GeneratorKind, gray: f32) -> f32 {
|
||||
grunge_pattern(kind).custom_gain * (gray - CUSTOM_GRUNGE_MID_GRAY)
|
||||
}
|
||||
|
||||
/// The two blurred curvature levels around `sigma` and the weight of the wider one; level None is the map itself
|
||||
pub(crate) fn levels_around(sigma: f32) -> (Option<usize>, usize, f32) {
|
||||
let sigmas = LEVEL_SIGMAS;
|
||||
let wider = sigmas.iter().position(|level| *level >= sigma).unwrap_or(sigmas.len() - 1);
|
||||
let (narrower, narrower_sigma) = match wider.checked_sub(1) {
|
||||
Some(level) => (Some(level), sigmas[level]),
|
||||
None => (None, 0.0),
|
||||
};
|
||||
let span = sigmas[wider] - narrower_sigma;
|
||||
let weight = if span > 0.0 { ((sigma - narrower_sigma) / span).clamp(0.0, 1.0) } else { 1.0 };
|
||||
(narrower, wider, weight)
|
||||
}
|
||||
|
||||
/// Which blurred curvature levels a wear generator reads
|
||||
pub(crate) fn levels_in_use(kind: GeneratorKind, wear: &WearParameters) -> [bool; LEVEL_RADII.len()] {
|
||||
let sigma = blur_sigma(kind, wear);
|
||||
if sigma <= 0.0 {
|
||||
return [false; LEVEL_RADII.len()];
|
||||
}
|
||||
|
||||
let (narrower, wider, _) = levels_around(sigma);
|
||||
std::array::from_fn(|level| level == wider || Some(level) == narrower)
|
||||
}
|
||||
|
||||
/// The wear value (0..1) of `kind` at a texel
|
||||
pub(crate) fn wear_value(kind: GeneratorKind, wear: &WearParameters, inputs: &WearInputs) -> f32 {
|
||||
match kind {
|
||||
GeneratorKind::Dirt => DIRT_SCAN.apply(dirt_signal(wear, inputs), wear),
|
||||
GeneratorKind::FiberGlassEdgeWear => FIBER_GLASS_SCAN.apply(fiber_glass_signal(wear, inputs), wear),
|
||||
_ => EDGE_WEAR_SCAN.apply(edge_wear_signal(wear, inputs), wear),
|
||||
}
|
||||
}
|
||||
|
||||
/// Edges sharp and smoothed in equal parts
|
||||
fn smoothed_edges(inputs: &WearInputs) -> f32 {
|
||||
(1.0 - SMOOTHED_SHARE) * inputs.curvature + SMOOTHED_SHARE * inputs.blurred_curvature
|
||||
}
|
||||
|
||||
/// The masking at which the fitted cut-off is pinned, the controls' default
|
||||
const DEFAULT_MASKING: f32 = 0.5;
|
||||
|
||||
/// 1 where the area is open enough to wear, 0 where occluded: the cut-off sits at `offset + gain × masking`, softened over `width`
|
||||
fn open_area(occlusion: f32, masking: f32, (offset, gain, width): (f32, f32, f32)) -> f32 {
|
||||
// A cut-off below this leaves every occlusion fully open, so the low end eases from it to the default's cut-off instead of masking nothing
|
||||
let fully_open = -width * 0.5;
|
||||
let cut_off = if masking < DEFAULT_MASKING && offset < fully_open {
|
||||
fully_open + (offset + gain * DEFAULT_MASKING - fully_open) * masking / DEFAULT_MASKING
|
||||
} else {
|
||||
offset + gain * masking
|
||||
};
|
||||
((occlusion - cut_off) / width + 0.5).clamp(0.0, 1.0)
|
||||
}
|
||||
|
||||
// The signals' coefficients are fitted to the reference app's sweeps on a hard-surface bake
|
||||
fn edge_wear_signal(wear: &WearParameters, inputs: &WearInputs) -> f32 {
|
||||
let edges = smoothed_edges(inputs) * wear.curvature_weight;
|
||||
let open = open_area(inputs.occlusion, wear.ao_masking, (-0.779, 2.244, 0.935));
|
||||
let grunge = wear.grunge_amount;
|
||||
edges * open * (1.0 + 0.031 * grunge) - 0.009 * grunge + 0.057 * grunge.powf(0.731) * inputs.grunge
|
||||
}
|
||||
|
||||
fn fiber_glass_signal(wear: &WearParameters, inputs: &WearInputs) -> f32 {
|
||||
// The grunge takes over from the edges as it grows
|
||||
let edges = smoothed_edges(inputs) * wear.curvature_weight * 1.02;
|
||||
let open = open_area(inputs.occlusion, wear.ao_masking, (0.144, 0.726, 0.669));
|
||||
let grunge = wear.grunge_amount;
|
||||
(edges * (1.0 - 0.989 * grunge) + 0.167 * grunge + 0.094 * grunge.powf(1.64) * inputs.grunge) * open
|
||||
}
|
||||
|
||||
fn dirt_signal(wear: &WearParameters, inputs: &WearInputs) -> f32 {
|
||||
let edges = inputs.blurred_curvature;
|
||||
let grunge = wear.grunge_amount;
|
||||
0.486 * (0.869 - inputs.occlusion) - wear.edges_masking * 0.817 * edges.max(0.0)
|
||||
+ 0.203 * (-edges).max(0.0)
|
||||
+ 0.241 * grunge
|
||||
+ 0.0895 * grunge * inputs.grunge
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use texturecraft_geom::glam::{Vec2, Vec3};
|
||||
|
||||
use super::*;
|
||||
use crate::grunge_pattern::{DIRT_GRUNGE, EDGE_WEAR_GRUNGE, FIBER_GLASS_GRUNGE};
|
||||
|
||||
fn inputs(curvature: f32, occlusion: f32) -> WearInputs {
|
||||
WearInputs { curvature, blurred_curvature: curvature, occlusion, grunge: 0.0 }
|
||||
}
|
||||
|
||||
fn defaults(kind: GeneratorKind) -> WearParameters {
|
||||
WearParameters { grunge_amount: 0.0, ..WearParameters::defaults(kind).unwrap() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edge_wear_shows_on_open_convex_edges_only() {
|
||||
for kind in [GeneratorKind::EdgeWear, GeneratorKind::FiberGlassEdgeWear] {
|
||||
let wear = WearParameters { curvature_weight: 1.0, ..defaults(kind) };
|
||||
let value = |curvature, occlusion| wear_value(kind, &wear, &inputs(curvature, occlusion));
|
||||
assert!(value(0.4, 1.0) > 0.9, "{kind:?}: a sharp open edge wears");
|
||||
assert!(value(0.0, 1.0) < 0.1, "{kind:?}: a flat face does not");
|
||||
assert!(value(-0.4, 1.0) < 0.1, "{kind:?}: nor a cavity");
|
||||
assert!(value(0.4, 0.0) < value(0.4, 1.0), "{kind:?}: occlusion masks the wear");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dirt_gathers_in_occluded_cavities_and_spares_edges() {
|
||||
let wear = defaults(GeneratorKind::Dirt);
|
||||
let value = |curvature, occlusion| wear_value(GeneratorKind::Dirt, &wear, &inputs(curvature, occlusion));
|
||||
assert!(value(-0.3, 0.2) > value(0.0, 1.0), "occluded cavities collect dirt");
|
||||
assert!(value(0.3, 0.6) < value(0.0, 0.6), "edges are masked");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_ao_masking_above_0_masks_more_occluded_edges() {
|
||||
let wear = |ao_masking| WearParameters { ao_masking, ..defaults(GeneratorKind::EdgeWear) };
|
||||
let occluded_edge = inputs(0.1, 0.0);
|
||||
let values: Vec<f32> = [0.0, 0.05, 0.1, 0.3].iter().map(|masking| wear_value(GeneratorKind::EdgeWear, &wear(*masking), &occluded_edge)).collect();
|
||||
assert!(values.windows(2).all(|pair| pair[1] < pair[0]), "{values:?}");
|
||||
assert_eq!(wear_value(GeneratorKind::EdgeWear, &wear(1.0), &occluded_edge), 0.0, "full masking clears occluded areas");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_higher_level_spreads_the_wear_and_a_full_level_is_a_hard_step() {
|
||||
let low = WearParameters { level: 0.25, ..defaults(GeneratorKind::EdgeWear) };
|
||||
let high = WearParameters { level: 0.9, ..low };
|
||||
let mild = inputs(0.1, 1.0);
|
||||
assert!(wear_value(GeneratorKind::EdgeWear, &high, &mild) > wear_value(GeneratorKind::EdgeWear, &low, &mild));
|
||||
|
||||
let full = WearParameters { level: 1.0, ..low };
|
||||
for curvature in [-0.5, 0.0, 0.05, 0.5] {
|
||||
let value = wear_value(GeneratorKind::EdgeWear, &full, &inputs(curvature, 1.0));
|
||||
assert!(value == 0.0 || value == 1.0, "{curvature}: {value}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grunge_is_normalised() {
|
||||
for (kind, pattern) in
|
||||
[(GeneratorKind::EdgeWear, &EDGE_WEAR_GRUNGE), (GeneratorKind::FiberGlassEdgeWear, &FIBER_GLASS_GRUNGE), (GeneratorKind::Dirt, &DIRT_GRUNGE)]
|
||||
{
|
||||
let wear = WearParameters::defaults(kind).unwrap();
|
||||
let samples: Vec<f32> = (0..256 * 256)
|
||||
.map(|texel| {
|
||||
let uv = Vec2::new((texel % 256) as f32 / 256.0, (texel / 256) as f32 / 256.0);
|
||||
grunge(kind, &wear, 7, &Coords { uv, pos: uv.extend(0.0), nrm: Vec3::Z })
|
||||
})
|
||||
.collect();
|
||||
let mean = samples.iter().sum::<f32>() / samples.len() as f32;
|
||||
let spread = (samples.iter().map(|value| (value - mean).powi(2)).sum::<f32>() / samples.len() as f32).sqrt();
|
||||
let measured = (pattern.mean + mean * pattern.spread, spread * pattern.spread);
|
||||
assert!(mean.abs() < 0.1 && (spread - 1.0).abs() < 0.1, "{kind:?}: normalised mean {mean}, spread {spread}; the pattern's own {measured:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_kind_s_grunge_changes_with_the_seed() {
|
||||
for kind in [GeneratorKind::EdgeWear, GeneratorKind::FiberGlassEdgeWear, GeneratorKind::Dirt] {
|
||||
let wear = WearParameters::defaults(kind).unwrap();
|
||||
let sample = |seed| -> Vec<f32> {
|
||||
(0..64 * 64)
|
||||
.map(|texel| {
|
||||
let uv = Vec2::new((texel % 64) as f32 / 64.0, (texel / 64) as f32 / 64.0);
|
||||
grunge(kind, &wear, seed, &Coords { uv, pos: uv.extend(0.0), nrm: Vec3::Z })
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let (first, second) = (sample(1), sample(2));
|
||||
let difference = first.iter().zip(&second).map(|(a, b)| (a - b).abs()).sum::<f32>() / first.len() as f32;
|
||||
assert!(difference > 0.2, "{kind:?}: another seed barely changes the grunge ({difference})");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_blurred_levels_around_a_sigma_bracket_it() {
|
||||
assert_eq!(levels_around(0.5).0, None, "below the first level the map itself is the narrower one");
|
||||
let (narrower, wider, weight) = levels_around(4.6);
|
||||
assert_eq!((narrower, wider), (Some(2), 3));
|
||||
assert!((0.0..=0.1).contains(&weight), "4.6 sits just past radius 4's sigma: {weight}");
|
||||
assert_eq!(levels_around(500.0).1, LEVEL_RADII.len() - 1, "wider than every level reads the widest");
|
||||
for (radius, sigma) in LEVEL_RADII.iter().zip(LEVEL_SIGMAS) {
|
||||
assert!(((radius * (radius + 1.0)).sqrt() - sigma).abs() < 0.001, "{radius}: {sigma}");
|
||||
}
|
||||
let widest = super::blur_sigma(
|
||||
GeneratorKind::EdgeWear,
|
||||
&WearParameters { edges_smoothness: *WearParameters::EDGES_SMOOTHNESS_RANGE.end(), ..WearParameters::defaults(GeneratorKind::EdgeWear).unwrap() },
|
||||
);
|
||||
assert!(widest < LEVEL_SIGMAS[LEVEL_RADII.len() - 1], "the whole smoothness range lands between built levels: {widest}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
//! What a wear generator reads at a texel
|
||||
|
||||
/// What a wear generator reads at a texel
|
||||
pub(crate) struct WearInputs {
|
||||
/// The curvature map minus its flat 0.5 (above 0 convex, below 0 concave)
|
||||
pub curvature: f32,
|
||||
/// The curvature deviation blurred to the sigma the kind asks for ([`crate::wear::blur_sigma`])
|
||||
pub blurred_curvature: f32,
|
||||
/// Ambient occlusion (1 open, 0 occluded)
|
||||
pub occlusion: f32,
|
||||
/// The grunge pattern normalised to mean 0 and spread 1
|
||||
pub grunge: f32,
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
//! How a wear generator's level and contrast turn its signal into the mask (constants fitted to the reference app's sweeps)
|
||||
|
||||
use texturecraft_core::WearParameters;
|
||||
|
||||
/// Where a kind's level slides its edge and how wide the edge is
|
||||
pub(crate) struct WearScan {
|
||||
/// The edge at level 0, falling towards `floor` as the level rises
|
||||
pub travel: f32,
|
||||
pub floor: f32,
|
||||
/// The edge's width at contrast 0, narrowed by (1 − contrast) to the power `narrowing`
|
||||
pub width: f32,
|
||||
pub narrowing: f32,
|
||||
}
|
||||
|
||||
pub(crate) const EDGE_WEAR_SCAN: WearScan = WearScan { travel: 0.284, floor: -0.009, width: 0.504, narrowing: 0.95 };
|
||||
pub(crate) const FIBER_GLASS_SCAN: WearScan = WearScan { travel: 0.162, floor: 0.029, width: 0.358, narrowing: 0.872 };
|
||||
pub(crate) const DIRT_SCAN: WearScan = WearScan { travel: 0.593, floor: -0.088, width: 1.386, narrowing: 1.42 };
|
||||
|
||||
/// The narrowest edge, so a level or contrast of 1 is a hard step rather than a division by zero
|
||||
const MIN_EDGE_WIDTH: f32 = 1e-4;
|
||||
|
||||
impl WearScan {
|
||||
/// `signal` through the level and contrast: the level brings the edge down and narrows it, the contrast narrows it further
|
||||
pub(crate) fn apply(&self, signal: f32, wear: &WearParameters) -> f32 {
|
||||
let remaining = (1.0 - wear.level).max(0.0);
|
||||
let width = (remaining * self.width * (1.0 - wear.contrast).max(0.0).powf(self.narrowing)).max(MIN_EDGE_WIDTH);
|
||||
((signal - self.floor - remaining * self.travel) / width + 0.5).clamp(0.0, 1.0)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
//! Whole-map fields some generators precompute at the working resolution (UV Border Distance, Dripping Rust), built once per layout, mesh map and settings
|
||||
|
||||
use crate::eval::{Inputs, blur};
|
||||
|
||||
/// The resolution of a UV tile the generators' fitted sizes are measured at
|
||||
pub(crate) const REFERENCE_TILE_TEXELS: f32 = 2048.0;
|
||||
|
||||
/// The size of one UV tile's block in `inp`'s working atlas
|
||||
pub(crate) fn working_block(inp: &Inputs) -> (u32, u32) {
|
||||
let size = (inp.gbuf.width, inp.gbuf.height);
|
||||
let grid = inp.project.texture_set(inp.ts).ok().and_then(|set| set.tile_grid());
|
||||
let block = grid.map_or(size, |grid| (size.0 / grid.cols.max(1), size.1 / grid.rows.max(1)));
|
||||
(block.0.clamp(1, size.0.max(1)), block.1.clamp(1, size.1.max(1)))
|
||||
}
|
||||
|
||||
/// The radius of three box passes that blur like a gaussian of `sigma`: three boxes of radius r spread a texel with variance r (r + 1)
|
||||
pub(crate) fn box_radius(sigma: f32) -> usize {
|
||||
(((1.0 + 4.0 * sigma * sigma).sqrt() - 1.0) * 0.5).round() as usize
|
||||
}
|
||||
|
||||
/// `data` blurred one UV tile block at a time by the radius `radius_at` gives for the block's corner, reading black past each block's edges
|
||||
pub(crate) fn blur_blocks(data: &mut [f32], (width, height): (u32, u32), block: (u32, u32), radius_at: impl Fn(u32, u32) -> usize) {
|
||||
for top in (0..height).step_by(block.1 as usize) {
|
||||
for left in (0..width).step_by(block.0 as usize) {
|
||||
let radius = radius_at(left, top);
|
||||
if radius == 0 {
|
||||
continue;
|
||||
}
|
||||
|
||||
let (columns, rows) = (block.0.min(width - left) as usize, block.1.min(height - top) as usize);
|
||||
let index = |column: usize, row: usize| (top as usize + row) * width as usize + left as usize + column;
|
||||
let mut values: Vec<f32> = (0..rows)
|
||||
.flat_map(|row| (0..columns).map(move |column| (column, row)))
|
||||
.map(|(column, row)| data.get(index(column, row)).copied().unwrap_or(0.0))
|
||||
.collect();
|
||||
blur(&mut values, columns, rows, radius);
|
||||
for (offset, value) in values.into_iter().enumerate() {
|
||||
if let Some(target) = data.get_mut(index(offset % columns, offset / columns)) {
|
||||
*target = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1270,3 +1270,42 @@ fn a_folder_thumbnail_reads_compare_inputs_from_its_backdrop() {
|
||||
|
||||
assert!(thumbnail.rgba[center] > thumbnail.rgba[center + 2], "visible red child");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replacing_a_generator_texture_image_invalidates_the_cached_stack() {
|
||||
use std::sync::Arc;
|
||||
use texturecraft_compose::{ImageRes, ImageStore};
|
||||
use texturecraft_core::{TextureBlend, TextureLayer};
|
||||
|
||||
let mut fixture = fixture();
|
||||
let hot_layer = heavy_stack(&mut fixture);
|
||||
let texture = TextureLayer { enabled: true, source: Some(Source::image("grunge")), opacity: 1.0, blend: TextureBlend::Normal, ..TextureLayer::default() };
|
||||
let mut mask = Mask::new(MaskBackground::Black);
|
||||
mask.effects
|
||||
.push(effect(&mut fixture, EffectKind::Generator(Generator { texture: Some(Box::new(texture)), ..Generator::new(GeneratorKind::AmbientOcclusion) })));
|
||||
let textured = add(&mut fixture, 0, fill(&[(Channel::Roughness, procedural(ProceduralKind::Clouds, 0.0, 1.0))]), Some(mask));
|
||||
let stack = &mut fixture.project.texture_sets[0].stack;
|
||||
stack.retain(|id| *id != textured);
|
||||
stack.insert(0, textured);
|
||||
|
||||
let image_with_value = |value| Arc::new(ImageRes::new(4, 4, vec![[value, value, value, 1.0]; 16], false));
|
||||
let mut images = ImageStore::default();
|
||||
let baked = Default::default();
|
||||
let tiles = all_tiles(RES, RES);
|
||||
let mut cache = BelowCache::default();
|
||||
cache.set_hot(Some(hot_layer));
|
||||
let mut output = Composite::new(&fixture.project.texture_sets[0].channel_list(), RES);
|
||||
|
||||
for (stage, value) in [("dark", 0.1), ("light", 0.9)] {
|
||||
images.insert("grunge".into(), image_with_value(value));
|
||||
let input = inputs(&fixture, 0, &images, &baked);
|
||||
composite_tiles_cached(&input, &mut output, &tiles[..1], Some(&mut cache));
|
||||
let retained = cache.len() - 1;
|
||||
composite_tiles_cached(&input, &mut output, &tiles[1..], Some(&mut cache));
|
||||
assert_eq!(retained, 0, "{stage}: a new texture image drops the tiles cached below the hot layer");
|
||||
|
||||
let mut expected = Composite::new(&fixture.project.texture_sets[0].channel_list(), RES);
|
||||
composite_tiles(&input, &mut expected, &tiles);
|
||||
assert!(output == expected, "{stage}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
//! A wear generator's custom grunge on a sphere: read instead of the kind's own pattern, tiled by the grunge scale, the seed leaving it in place
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use texturecraft_compose::{BakedMaps, ImageRes};
|
||||
use texturecraft_core::{BakedMap, Generator, GeneratorKind, Source, WearParameters};
|
||||
use texturecraft_geom::primitives;
|
||||
|
||||
use super::generator_fixture::GeneratorFixture;
|
||||
|
||||
const RES: u32 = 128;
|
||||
|
||||
/// Width of the split image: its left half black, its right half white
|
||||
const SPLIT_WIDTH: u32 = 64;
|
||||
|
||||
const WEAR_KINDS: [GeneratorKind; 3] = [GeneratorKind::EdgeWear, GeneratorKind::FiberGlassEdgeWear, GeneratorKind::Dirt];
|
||||
|
||||
/// A unit sphere with a white fill layer, no occlusion anywhere, no curvature map, and the images `black`, `white` and `split`
|
||||
fn fixture() -> GeneratorFixture {
|
||||
let mesh = primitives::sphere(1.0, 32, 16);
|
||||
let mut fixture = GeneratorFixture::new(mesh, "builtin:sphere", RES);
|
||||
|
||||
let baked = BakedMaps { resolution: RES, maps: [(BakedMap::AmbientOcclusion, Arc::new(vec![1.0; (RES * RES) as usize]))].into() };
|
||||
|
||||
let flat = |value: f32| Arc::new(ImageRes::new(4, 4, vec![[value, value, value, 1.0]; 16], false));
|
||||
let split_texel = |index: u32| if index % SPLIT_WIDTH < SPLIT_WIDTH / 2 { [0.0, 0.0, 0.0, 1.0] } else { [1.0; 4] };
|
||||
let split = ImageRes::new(SPLIT_WIDTH, SPLIT_WIDTH, (0..SPLIT_WIDTH * SPLIT_WIDTH).map(split_texel).collect(), false);
|
||||
let images = [("black".to_string(), flat(0.0)), ("white".to_string(), flat(1.0)), ("split".to_string(), Arc::new(split))].into();
|
||||
fixture.baked = baked;
|
||||
fixture.images = images;
|
||||
fixture
|
||||
}
|
||||
|
||||
/// Every covered texel
|
||||
fn covered(fixture: &GeneratorFixture) -> Vec<(u32, u32)> {
|
||||
(0..RES * RES).filter(|index| fixture.gbuf.surface(&fixture.mesh, *index as usize).is_some()).map(|index| (index % RES, index / RES)).collect()
|
||||
}
|
||||
|
||||
/// `kind` on its wear controls at full grunge amount, reading `image` (None: an empty slot) as its grunge once `custom` is on
|
||||
fn wear(kind: GeneratorKind, image: Option<&str>, custom: bool, edit: impl Fn(&mut WearParameters)) -> Generator {
|
||||
let mut wear = WearParameters { grunge_amount: 1.0, custom_grunge: custom, ..WearParameters::defaults(kind).unwrap() };
|
||||
edit(&mut wear);
|
||||
Generator { wear: Some(wear), grunge: image.map(Source::image), ..Generator::new(kind) }
|
||||
}
|
||||
|
||||
fn mean(values: &[f32]) -> f32 {
|
||||
values.iter().sum::<f32>() / values.len() as f32
|
||||
}
|
||||
|
||||
/// The share of texels where `first` and `second` differ
|
||||
fn differing(first: &[f32], second: &[f32]) -> f32 {
|
||||
first.iter().zip(second).filter(|(a, b)| (*a - *b).abs() > 0.05).count() as f32 / first.len() as f32
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_grunge_image_changes_nothing_until_use_custom_grunge_is_on() {
|
||||
let mut fixture = fixture();
|
||||
let texels = covered(&fixture);
|
||||
for kind in WEAR_KINDS {
|
||||
let own = fixture.sample(wear(kind, None, false, |_| {}), &texels);
|
||||
assert_eq!(fixture.sample(wear(kind, Some("white"), false, |_| {}), &texels), own, "{kind:?}");
|
||||
assert!(differing(&fixture.sample(wear(kind, Some("white"), true, |_| {}), &texels), &own) > 0.1, "{kind:?}: on, the image replaces the pattern");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_brighter_custom_grunge_wears_edges_more_and_dirties_less_in_uv_and_triplanar() {
|
||||
let mut fixture = fixture();
|
||||
let texels = covered(&fixture);
|
||||
for kind in WEAR_KINDS {
|
||||
for triplanar in [false, true] {
|
||||
let read = |fixture: &mut GeneratorFixture, image| mean(&fixture.sample(wear(kind, Some(image), true, |wear| wear.triplanar = triplanar), &texels));
|
||||
let (white, black) = (read(&mut fixture, "white"), read(&mut fixture, "black"));
|
||||
let (more, less) = if kind == GeneratorKind::Dirt { (black, white) } else { (white, black) };
|
||||
assert!(more > less + 0.3, "{kind:?} triplanar {triplanar}: white {white}, black {black}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_grunge_slot_reads_black() {
|
||||
let mut fixture = fixture();
|
||||
let texels = covered(&fixture);
|
||||
for kind in WEAR_KINDS {
|
||||
assert_eq!(fixture.sample(wear(kind, None, true, |_| {}), &texels), fixture.sample(wear(kind, Some("black"), true, |_| {}), &texels), "{kind:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_grunge_scale_repeats_a_custom_grunge_across_the_uv_square() {
|
||||
let mut fixture = fixture();
|
||||
|
||||
// Texel pairs half the UV square apart, both covered
|
||||
let covered = covered(&fixture);
|
||||
let pairs: Vec<((u32, u32), (u32, u32))> =
|
||||
covered.iter().filter(|(x, _)| *x < RES / 2).map(|(x, y)| ((*x, *y), (x + RES / 2, *y))).filter(|(_, right)| covered.contains(right)).collect();
|
||||
let (left, right): (Vec<_>, Vec<_>) = pairs.into_iter().unzip();
|
||||
let halves = |fixture: &mut GeneratorFixture, scale: f32| {
|
||||
let generator = wear(GeneratorKind::EdgeWear, Some("split"), true, |wear| wear.grunge_scale = scale);
|
||||
(fixture.sample(generator.clone(), &left), fixture.sample(generator, &right))
|
||||
};
|
||||
|
||||
let (first, second) = halves(&mut fixture, 2.0);
|
||||
assert!(differing(&first, &second) < 0.02, "twice across the square, half of it apart reads the same");
|
||||
let (first, second) = halves(&mut fixture, 1.0);
|
||||
assert!(differing(&first, &second) > 0.5, "once across the square, half of it apart reads the other side of the image");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_seed_leaves_a_custom_grunge_in_place() {
|
||||
let mut fixture = fixture();
|
||||
let texels = covered(&fixture);
|
||||
for kind in WEAR_KINDS {
|
||||
for triplanar in [false, true] {
|
||||
let seeded = |seed| Generator { seed, ..wear(kind, Some("split"), true, |wear| wear.triplanar = triplanar) };
|
||||
assert_eq!(fixture.sample(seeded(1), &texels), fixture.sample(seeded(2), &texels), "{kind:?} triplanar {triplanar}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
//! The Dripping Rust generator on a sphere with an occluded band: rust grows in the occlusion, spreads from none to everywhere, and drips run down from it
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use texturecraft_compose::BakedMaps;
|
||||
use texturecraft_core::{BakedMap, DrippingRustParameters, Generator, GeneratorKind, KindControls};
|
||||
use texturecraft_geom::primitives;
|
||||
|
||||
use super::generator_fixture::GeneratorFixture;
|
||||
|
||||
const RES: u32 = 128;
|
||||
|
||||
/// The occluded band's heights on the unit sphere, and its occlusion
|
||||
const BAND: std::ops::Range<f32> = 0.2..0.5;
|
||||
const BAND_OCCLUSION: f32 = 0.2;
|
||||
|
||||
/// A unit sphere with a white fill layer, occluded only in [`BAND`]
|
||||
fn fixture() -> GeneratorFixture {
|
||||
let mesh = primitives::sphere(1.0, 48, 24);
|
||||
let mut fixture = GeneratorFixture::new(mesh, "builtin:sphere", RES);
|
||||
|
||||
let occlusion: Vec<f32> = (0..RES * RES)
|
||||
.map(|texel| {
|
||||
fixture.gbuf.surface(&fixture.mesh, texel as usize).map_or(1.0, |surface| if BAND.contains(&surface.pos.y) { BAND_OCCLUSION } else { 1.0 })
|
||||
})
|
||||
.collect();
|
||||
let baked = BakedMaps { resolution: RES, maps: [(BakedMap::AmbientOcclusion, Arc::new(occlusion))].into() };
|
||||
fixture.baked = baked;
|
||||
fixture
|
||||
}
|
||||
|
||||
/// Every covered texel and its height
|
||||
fn covered(fixture: &GeneratorFixture) -> Vec<((u32, u32), f32)> {
|
||||
(0..RES * RES).filter_map(|index| fixture.gbuf.surface(&fixture.mesh, index as usize).map(|surface| ((index % RES, index / RES), surface.pos.y))).collect()
|
||||
}
|
||||
|
||||
fn mask(fixture: &mut GeneratorFixture, rust: DrippingRustParameters, texels: &[(u32, u32)]) -> Vec<f32> {
|
||||
let generator = Generator { controls: Some(Box::new(KindControls::DrippingRust(rust))), ..Generator::new(GeneratorKind::DrippingRust) };
|
||||
fixture.sample(generator, texels)
|
||||
}
|
||||
|
||||
/// The mean of `values` over the texels whose height lies in `heights`
|
||||
fn mean_within(texels: &[((u32, u32), f32)], values: &[f32], heights: std::ops::Range<f32>) -> f32 {
|
||||
let picked: Vec<f32> = texels.iter().zip(values).filter(|((_, height), _)| heights.contains(height)).map(|(_, value)| *value).collect();
|
||||
picked.iter().sum::<f32>() / picked.len().max(1) as f32
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spreading_runs_from_none_to_everywhere() {
|
||||
let mut fixture = fixture();
|
||||
let at: Vec<(u32, u32)> = covered(&fixture).iter().map(|(texel, _)| *texel).collect();
|
||||
|
||||
let none = mask(&mut fixture, DrippingRustParameters { spreading: 0.0, ..DrippingRustParameters::default() }, &at);
|
||||
let all = mask(&mut fixture, DrippingRustParameters { spreading: 1.0, ..DrippingRustParameters::default() }, &at);
|
||||
assert!(none.iter().all(|value| *value == 0.0));
|
||||
assert!(all.iter().all(|value| *value == 1.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_occluded_band_rusts_most() {
|
||||
let mut fixture = fixture();
|
||||
let texels = covered(&fixture);
|
||||
let at: Vec<(u32, u32)> = texels.iter().map(|(texel, _)| *texel).collect();
|
||||
|
||||
let values = mask(&mut fixture, DrippingRustParameters { drips_intensity: 0.0, ..DrippingRustParameters::default() }, &at);
|
||||
assert!(mean_within(&texels, &values, BAND) > mean_within(&texels, &values, -1.0..-0.2) + 0.3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drips_only_add_rust_and_run_down_from_the_band() {
|
||||
let mut fixture = fixture();
|
||||
let texels = covered(&fixture);
|
||||
let at: Vec<(u32, u32)> = texels.iter().map(|(texel, _)| *texel).collect();
|
||||
let rust = DrippingRustParameters { contrast: 0.0, drips_smoothness: 0.0, ..DrippingRustParameters::default() };
|
||||
|
||||
let dry = mask(&mut fixture, DrippingRustParameters { drips_intensity: 0.0, ..rust }, &at);
|
||||
let dripping = mask(&mut fixture, DrippingRustParameters { drips_intensity: 1.0, ..rust }, &at);
|
||||
assert!(dripping.iter().zip(&dry).all(|(wet, dry)| wet >= dry), "a drip takes the most rust above, never less than its own");
|
||||
let gain = |heights: std::ops::Range<f32>| mean_within(&texels, &dripping, heights.clone()) - mean_within(&texels, &dry, heights);
|
||||
assert!(gain(0.05..0.2) > gain(0.5..0.65) + 0.05, "below the band {} above it {}", gain(0.05..0.2), gain(0.5..0.65));
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
use texturecraft_compose::{BakedMaps, ImageStore, Inputs, PixelStore, mask_at};
|
||||
use texturecraft_core::{Channel, Effect, EffectKind, Fill, Generator, Layer, LayerId, LayerKind, Mask, MaskBackground, Project, Source, TextureSet};
|
||||
use texturecraft_geom::{Mesh, UvGBuffer};
|
||||
|
||||
pub(super) struct GeneratorFixture {
|
||||
pub(super) project: Project,
|
||||
pub(super) mesh: Mesh,
|
||||
pub(super) gbuf: UvGBuffer,
|
||||
pub(super) layer: LayerId,
|
||||
pub(super) baked: BakedMaps,
|
||||
pub(super) images: ImageStore,
|
||||
}
|
||||
|
||||
impl GeneratorFixture {
|
||||
pub(super) fn new(mesh: Mesh, asset: &str, resolution: u32) -> Self {
|
||||
let gbuf = UvGBuffer::new(&mesh, 0, resolution, resolution);
|
||||
let mut project = Project::new("Generator test", asset);
|
||||
project.texture_sets.push(TextureSet::new("A", 0, resolution));
|
||||
|
||||
let id = project.alloc_id();
|
||||
let mut fill = Fill::default();
|
||||
fill.sources.insert(Channel::BaseColor, Source::Uniform([1.0; 3]));
|
||||
let layer = project.insert_layer(0, Layer::new(id, "Fill", LayerKind::Fill(fill), &[Channel::BaseColor]), None, false).unwrap();
|
||||
|
||||
Self { project, mesh, gbuf, layer, baked: BakedMaps::default(), images: ImageStore::default() }
|
||||
}
|
||||
|
||||
pub(super) fn sample(&mut self, generator: Generator, texels: &[(u32, u32)]) -> Vec<f32> {
|
||||
let mut mask = Mask::new(MaskBackground::Black);
|
||||
mask.effects.push(Effect::new(self.project.alloc_id(), EffectKind::Generator(generator)));
|
||||
self.project.layer_mut(self.layer).unwrap().mask = Some(mask);
|
||||
|
||||
let inputs = Inputs {
|
||||
project: &self.project,
|
||||
ts: 0,
|
||||
mesh: &self.mesh,
|
||||
gbuf: &self.gbuf,
|
||||
pixels: &PixelStore::default(),
|
||||
baked: &self.baked,
|
||||
block_scales: self.project.texture_sets[0].block_scales(),
|
||||
preview: None,
|
||||
images: &self.images,
|
||||
bounds: self.mesh.bounds(),
|
||||
};
|
||||
mask_at(&inputs, self.layer, texels).unwrap()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
//! The Grayscale Conversion generator on a plane filling its UV tile: its image turned gray by the chosen type, tiled, turned and balanced
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use texturecraft_compose::ImageRes;
|
||||
use texturecraft_core::{Generator, GeneratorGrayscale, GeneratorKind, GrayscaleConversionParameters, KindControls, Source};
|
||||
use texturecraft_geom::primitives;
|
||||
|
||||
use super::generator_fixture::GeneratorFixture;
|
||||
|
||||
const RES: u32 = 64;
|
||||
|
||||
/// Width of the image: its left half red, its right half blue
|
||||
const IMAGE_WIDTH: u32 = 16;
|
||||
|
||||
fn fixture() -> GeneratorFixture {
|
||||
let mesh = primitives::plane(2.0, 1);
|
||||
let mut fixture = GeneratorFixture::new(mesh, "builtin:plane", RES);
|
||||
|
||||
let texel = |index: u32| if index % IMAGE_WIDTH < IMAGE_WIDTH / 2 { [1.0, 0.0, 0.0, 1.0] } else { [0.0, 0.0, 1.0, 1.0] };
|
||||
let image = ImageRes::new(IMAGE_WIDTH, IMAGE_WIDTH, (0..IMAGE_WIDTH * IMAGE_WIDTH).map(texel).collect(), false);
|
||||
fixture.images.insert("split".to_owned(), Arc::new(image));
|
||||
fixture
|
||||
}
|
||||
|
||||
/// The values along a row a quarter of the way down, left to right
|
||||
fn row(fixture: &mut GeneratorFixture, grayscale: GrayscaleConversionParameters) -> Vec<f32> {
|
||||
let generator = Generator {
|
||||
controls: Some(Box::new(KindControls::Grayscale(GrayscaleConversionParameters { source: Some(Source::image("split")), ..grayscale }))),
|
||||
..Generator::new(GeneratorKind::GrayscaleConversion)
|
||||
};
|
||||
let texels: Vec<(u32, u32)> = (0..RES).map(|x| (x, RES / 4)).collect();
|
||||
fixture.sample(generator, &texels)
|
||||
}
|
||||
|
||||
fn red_channel() -> GrayscaleConversionParameters {
|
||||
GrayscaleConversionParameters { grayscale: GeneratorGrayscale::Red, ..GrayscaleConversionParameters::default() }
|
||||
}
|
||||
|
||||
/// How many times the row changes between dark and light
|
||||
fn edges(values: &[f32]) -> usize {
|
||||
values.windows(2).filter(|pair| (pair[0] > 0.5) != (pair[1] > 0.5)).count()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_type_picks_what_turns_white() {
|
||||
let mut fixture = fixture();
|
||||
let red = row(&mut fixture, red_channel());
|
||||
let blue = row(&mut fixture, GrayscaleConversionParameters { grayscale: GeneratorGrayscale::Blue, ..GrayscaleConversionParameters::default() });
|
||||
|
||||
assert!(red[2] > 0.9 && red[RES as usize - 3] < 0.1, "red on the left: {red:?}");
|
||||
assert!(blue[2] < 0.1 && blue[RES as usize - 3] > 0.9, "blue on the right");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tile_repeats_the_image_and_a_half_turn_mirrors_it() {
|
||||
let mut fixture = fixture();
|
||||
let once = row(&mut fixture, red_channel());
|
||||
let four = row(&mut fixture, GrayscaleConversionParameters { tile: 4.0, ..red_channel() });
|
||||
let turned = row(&mut fixture, GrayscaleConversionParameters { rotation: 180.0, ..red_channel() });
|
||||
|
||||
assert!(edges(&four) > edges(&once) + 4, "{} vs {}", edges(&four), edges(&once));
|
||||
assert!(turned[2] < 0.1 && turned[RES as usize - 3] > 0.9, "the red half swaps sides");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn safe_rotation_turns_by_quarter_turns_only() {
|
||||
let mut fixture = fixture();
|
||||
let snapped = row(&mut fixture, GrayscaleConversionParameters { rotation: 170.0, ..red_channel() });
|
||||
let half = row(&mut fixture, GrayscaleConversionParameters { rotation: 180.0, ..red_channel() });
|
||||
|
||||
assert_eq!(snapped, half);
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
//! A generator's micro details on a flat plane: a height bump reads as an edge on Curvature and occludes its foot on Ambient Occlusion; off or flat, they change nothing
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use texturecraft_compose::{BakedMaps, ImageRes};
|
||||
use texturecraft_core::{BakedMap, CurvatureDetail, CurvatureMode, Generator, GeneratorKind, MicroCurvatureType, MicroDetails, Source};
|
||||
use texturecraft_geom::primitives;
|
||||
|
||||
use super::generator_fixture::GeneratorFixture;
|
||||
|
||||
const RES: u32 = 128;
|
||||
|
||||
/// Size of the bump image, and the bump's spread in its texels
|
||||
const BUMP_SIZE: u32 = 64;
|
||||
const BUMP_SIGMA: f32 = 4.0;
|
||||
|
||||
/// How steep the bump's normal image is drawn
|
||||
const NORMAL_STRENGTH: f32 = 8.0;
|
||||
|
||||
/// The bump's height at texel (`x`, `y`) of the bump image: 1 at its center, 0 far away
|
||||
fn bump_height(x: f32, y: f32) -> f32 {
|
||||
let center = BUMP_SIZE as f32 / 2.0;
|
||||
let distance_squared = (x - center).powi(2) + (y - center).powi(2);
|
||||
(-distance_squared / (2.0 * BUMP_SIGMA * BUMP_SIGMA)).exp()
|
||||
}
|
||||
|
||||
/// A plane with a white fill layer, flat curvature and no occlusion, and the images `bump` (a height), `bump_normal` and `flat`
|
||||
fn fixture() -> GeneratorFixture {
|
||||
let mesh = primitives::plane(2.0, 1);
|
||||
let mut fixture = GeneratorFixture::new(mesh, "builtin:plane", RES);
|
||||
|
||||
let texels = (RES * RES) as usize;
|
||||
let maps = [(BakedMap::AmbientOcclusion, Arc::new(vec![1.0; texels])), (BakedMap::Curvature, Arc::new(vec![0.5; texels]))];
|
||||
let baked = BakedMaps { resolution: RES, maps: maps.into() };
|
||||
|
||||
let texel_xy = |index: u32| ((index % BUMP_SIZE) as f32 + 0.5, (index / BUMP_SIZE) as f32 + 0.5);
|
||||
let height = |index: u32| {
|
||||
let (x, y) = texel_xy(index);
|
||||
let height = bump_height(x, y);
|
||||
[height, height, height, 1.0]
|
||||
};
|
||||
let normal = |index: u32| {
|
||||
let (x, y) = texel_xy(index);
|
||||
let slope = ((bump_height(x + 0.5, y) - bump_height(x - 0.5, y)), (bump_height(x, y + 0.5) - bump_height(x, y - 0.5)));
|
||||
let (normal_x, normal_y) = (-NORMAL_STRENGTH * slope.0, -NORMAL_STRENGTH * slope.1);
|
||||
let length = (normal_x * normal_x + normal_y * normal_y + 1.0).sqrt();
|
||||
[normal_x / length * 0.5 + 0.5, normal_y / length * 0.5 + 0.5, 0.5 / length + 0.5, 1.0]
|
||||
};
|
||||
let image = |texel: &dyn Fn(u32) -> [f32; 4]| Arc::new(ImageRes::new(BUMP_SIZE, BUMP_SIZE, (0..BUMP_SIZE * BUMP_SIZE).map(texel).collect(), false));
|
||||
let flat = Arc::new(ImageRes::new(4, 4, vec![[0.3, 0.3, 0.3, 1.0]; 16], false));
|
||||
let images = [("bump".to_string(), image(&height)), ("bump_normal".to_string(), image(&normal)), ("flat".to_string(), flat)].into();
|
||||
fixture.baked = baked;
|
||||
fixture.images = images;
|
||||
fixture
|
||||
}
|
||||
|
||||
/// Every texel, row by row
|
||||
fn texels() -> Vec<(u32, u32)> {
|
||||
(0..RES * RES).map(|index| (index % RES, index / RES)).collect()
|
||||
}
|
||||
|
||||
/// The texel under the bump's center
|
||||
fn bump_center() -> usize {
|
||||
(RES / 2 * RES + RES / 2) as usize
|
||||
}
|
||||
|
||||
/// The mask of `generator` alone over black at every texel
|
||||
fn mask(fixture: &mut GeneratorFixture, generator: Generator) -> Vec<f32> {
|
||||
fixture.sample(generator, &texels())
|
||||
}
|
||||
|
||||
/// `kind` with micro details reading `height` (and `normal` when given), edited by `edit`
|
||||
fn with_micro(kind: GeneratorKind, height: Option<&str>, normal: Option<&str>, edit: impl Fn(&mut MicroDetails)) -> Generator {
|
||||
let mut micro = MicroDetails {
|
||||
enabled: true,
|
||||
height: height.is_some(),
|
||||
normal: normal.is_some(),
|
||||
height_source: height.map(Source::image),
|
||||
normal_source: normal.map(Source::image),
|
||||
..MicroDetails::defaults(kind).unwrap()
|
||||
};
|
||||
edit(&mut micro);
|
||||
let mut generator = Generator::new(kind);
|
||||
if generator.wear.is_none() && kind != GeneratorKind::FiberGlassEdgeWear && generator.section.is_none() {
|
||||
generator.wear = texturecraft_core::WearParameters::defaults(kind);
|
||||
}
|
||||
generator.micro = Some(Box::new(micro));
|
||||
generator
|
||||
}
|
||||
|
||||
/// Curvature in Raw mode, so a lift and a drop both show
|
||||
fn raw_curvature(mut generator: Generator) -> Generator {
|
||||
generator.detail = Some(CurvatureDetail { mode: CurvatureMode::Raw, ..CurvatureDetail::default() });
|
||||
generator
|
||||
}
|
||||
|
||||
fn strong(micro: &mut MicroDetails) {
|
||||
(micro.curvature_intensity, micro.height_intensity) = (5.0, 10.0);
|
||||
}
|
||||
|
||||
fn mean(values: &[f32]) -> f32 {
|
||||
values.iter().sum::<f32>() / values.len() as f32
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn micro_details_switched_off_change_nothing() {
|
||||
let mut fixture = fixture();
|
||||
for kind in [GeneratorKind::Curvature, GeneratorKind::AmbientOcclusion, GeneratorKind::EdgeWear, GeneratorKind::Dirt, GeneratorKind::FiberGlassEdgeWear] {
|
||||
let plain = mask(&mut fixture, with_micro(kind, None, None, |_| {}));
|
||||
|
||||
// Curvature and Ambient Occlusion switch them off whole, the wear kinds by both their images
|
||||
let switch = MicroDetails::has_switch(kind);
|
||||
let off = |micro: &mut MicroDetails| (micro.enabled, micro.height, micro.normal) = (!switch, switch, switch);
|
||||
|
||||
let switched_off = mask(&mut fixture, with_micro(kind, Some("bump"), Some("bump_normal"), off));
|
||||
assert_eq!(plain, switched_off, "{kind:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_micro_height_bump_reads_as_an_edge_on_curvature() {
|
||||
let mut fixture = fixture();
|
||||
let off = mask(&mut fixture, Generator::new(GeneratorKind::Curvature));
|
||||
|
||||
let on = mask(&mut fixture, with_micro(GeneratorKind::Curvature, Some("bump"), None, strong));
|
||||
assert!(on[bump_center()] > off[bump_center()] + 0.01, "the bump's top is convex: {} vs {}", on[bump_center()], off[bump_center()]);
|
||||
assert!((on[0] - off[0]).abs() < 1e-4, "far from the bump the surface stays flat");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_micro_normal_bump_reads_as_an_edge_on_curvature() {
|
||||
let mut fixture = fixture();
|
||||
let off = mask(&mut fixture, Generator::new(GeneratorKind::Curvature));
|
||||
|
||||
let on = mask(&mut fixture, with_micro(GeneratorKind::Curvature, None, Some("bump_normal"), strong));
|
||||
assert!(on[bump_center()] > off[bump_center()] + 0.01, "{} vs {}", on[bump_center()], off[bump_center()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn standard_lifts_a_flat_micro_height_and_smooth_lowers_it() {
|
||||
let mut fixture = fixture();
|
||||
let typed = |curvature_type| move |micro: &mut MicroDetails| micro.curvature_type = curvature_type;
|
||||
let sobel = mean(&mask(&mut fixture, raw_curvature(with_micro(GeneratorKind::Curvature, Some("flat"), None, typed(MicroCurvatureType::Sobel)))));
|
||||
let off = mean(&mask(&mut fixture, raw_curvature(Generator::new(GeneratorKind::Curvature))));
|
||||
|
||||
let standard = mean(&mask(&mut fixture, raw_curvature(with_micro(GeneratorKind::Curvature, Some("flat"), None, typed(MicroCurvatureType::Standard)))));
|
||||
let smooth = mean(&mask(&mut fixture, raw_curvature(with_micro(GeneratorKind::Curvature, Some("flat"), None, typed(MicroCurvatureType::Smooth)))));
|
||||
assert!((sobel - off).abs() < 1e-4, "Sobel adds nothing on a flat height");
|
||||
assert!(standard > off + 1e-3 && smooth < off - 1e-4, "standard {standard}, off {off}, smooth {smooth}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_micro_height_bump_occludes_around_it_on_ambient_occlusion() {
|
||||
let mut fixture = fixture();
|
||||
let deep = |micro: &mut MicroDetails| (micro.ao_radius, micro.ao_depth) = (1.0, 1.0);
|
||||
let off = mask(&mut fixture, Generator::new(GeneratorKind::AmbientOcclusion));
|
||||
let flat = mask(&mut fixture, with_micro(GeneratorKind::AmbientOcclusion, Some("flat"), None, deep));
|
||||
|
||||
let on = mask(&mut fixture, with_micro(GeneratorKind::AmbientOcclusion, Some("bump"), None, deep));
|
||||
assert_eq!(off, flat, "a flat micro height occludes nothing");
|
||||
assert!(on.iter().zip(&off).all(|(on, off)| on <= off), "micro occlusion only darkens");
|
||||
assert!(mean(&on) < mean(&off) - 1e-3, "{} vs {}", mean(&on), mean(&off));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tiny_ao_radius_occludes_nothing() {
|
||||
let mut fixture = fixture();
|
||||
let off = mask(&mut fixture, Generator::new(GeneratorKind::AmbientOcclusion));
|
||||
|
||||
let tiny = mask(&mut fixture, with_micro(GeneratorKind::AmbientOcclusion, Some("bump"), None, |micro| micro.ao_radius = 0.05));
|
||||
assert_eq!(off, tiny);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_micro_height_bump_moves_the_wear_kinds_around_it() {
|
||||
let mut fixture = fixture();
|
||||
for kind in [GeneratorKind::EdgeWear, GeneratorKind::Dirt, GeneratorKind::FiberGlassEdgeWear] {
|
||||
let off = mask(&mut fixture, with_micro(kind, None, None, |_| {}));
|
||||
|
||||
let on = mask(&mut fixture, with_micro(kind, Some("bump"), None, |micro| micro.curvature_intensity = 1.0));
|
||||
let changed = on.iter().zip(&off).filter(|(on, off)| (*on - *off).abs() > 1e-3).count();
|
||||
assert!(changed > 0, "{kind:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saved_micro_values_out_of_range_render_as_their_nearest_valid_ones() {
|
||||
let mut fixture = fixture();
|
||||
let hostile =
|
||||
mask(&mut fixture, with_micro(GeneratorKind::AmbientOcclusion, Some("bump"), None, |micro| (micro.ao_radius, micro.ao_depth) = (1e30, f32::NAN)));
|
||||
let valid = mask(&mut fixture, with_micro(GeneratorKind::AmbientOcclusion, Some("bump"), None, |micro| micro.ao_radius = 1.0));
|
||||
|
||||
assert_eq!(hostile, valid);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn micro_curvature_follows_the_layout_of_a_shared_bake() {
|
||||
let mut fixture = fixture();
|
||||
let curvature = Arc::new(vec![0.5; (2 * RES * RES) as usize]);
|
||||
fixture.baked.maps.insert(BakedMap::Curvature, curvature.clone());
|
||||
let generator = raw_curvature(with_micro(GeneratorKind::Curvature, Some("bump"), None, strong));
|
||||
|
||||
fixture.project.texture_sets[0].uv_tiles = vec![1001, 1002];
|
||||
fixture.baked.resolution = 2 * RES;
|
||||
let horizontal = mask(&mut fixture, generator.clone());
|
||||
fixture.project.texture_sets[0].uv_tiles = vec![1001, 1011];
|
||||
fixture.baked.resolution = RES;
|
||||
let vertical = mask(&mut fixture, generator.clone());
|
||||
|
||||
fixture.baked.maps.insert(BakedMap::Curvature, Arc::new(curvature.as_ref().clone()));
|
||||
let rebuilt = mask(&mut fixture, generator);
|
||||
assert!(horizontal != rebuilt, "the two layouts sample the height bump in different places");
|
||||
assert!(vertical == rebuilt, "a new atlas shape must sample like a fresh bake");
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
//! The section and light controls of the Curvature, Ambient Occlusion, Position, World Space Normals and Light generators on a sphere, beside their earlier model
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use texturecraft_compose::BakedMaps;
|
||||
use texturecraft_core::{AxisBlend, BakedMap, Generator, GeneratorKind, LightParameters, SectionParameters, Source};
|
||||
use texturecraft_geom::glam::Vec3;
|
||||
use texturecraft_geom::primitives;
|
||||
|
||||
use super::generator_fixture::GeneratorFixture;
|
||||
|
||||
const RES: u32 = 128;
|
||||
|
||||
/// How far a mask value may sit from the expected one
|
||||
const TOLERANCE: f32 = 1e-3;
|
||||
|
||||
/// A unit sphere with a white fill layer
|
||||
fn fixture() -> GeneratorFixture {
|
||||
let mesh = primitives::sphere(1.0, 32, 16);
|
||||
GeneratorFixture::new(mesh, "builtin:sphere", RES)
|
||||
}
|
||||
|
||||
/// A baked map of `map` holding `value` everywhere
|
||||
fn uniform_map(map: BakedMap, value: f32) -> BakedMaps {
|
||||
BakedMaps { resolution: RES, maps: [(map, Arc::new(vec![value; (RES * RES) as usize * map.components()]))].into() }
|
||||
}
|
||||
|
||||
/// Every covered texel with its world position and normal
|
||||
fn surface(fixture: &GeneratorFixture) -> Vec<((u32, u32), Vec3, Vec3)> {
|
||||
(0..RES * RES)
|
||||
.filter_map(|index| fixture.gbuf.surface(&fixture.mesh, index as usize).map(|surface| ((index % RES, index / RES), surface.pos, surface.nrm)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The earlier model's smooth step of `signal` at `generator`'s level and softness
|
||||
fn earlier_ramp(generator: &Generator, signal: f32) -> f32 {
|
||||
let threshold = 1.0 - generator.level;
|
||||
let ramp = ((signal - (threshold - generator.softness)) / (2.0 * generator.softness)).clamp(0.0, 1.0);
|
||||
ramp * ramp * (3.0 - 2.0 * ramp)
|
||||
}
|
||||
|
||||
fn earlier(kind: GeneratorKind) -> Generator {
|
||||
Generator { section: None, light: None, ..Generator::new(kind) }
|
||||
}
|
||||
|
||||
fn with_section(kind: GeneratorKind, change: impl FnOnce(&mut SectionParameters)) -> Generator {
|
||||
let mut generator = Generator::new(kind);
|
||||
let mut section = generator.section.unwrap();
|
||||
change(&mut section);
|
||||
generator.section = Some(section);
|
||||
generator
|
||||
}
|
||||
|
||||
/// `generator` with a uniform `value` plugged into its Position input
|
||||
fn plugged(mut generator: Generator, value: f32) -> Generator {
|
||||
generator.inputs.insert(BakedMap::Position, Source::Uniform([value; 3]));
|
||||
generator
|
||||
}
|
||||
|
||||
fn with_light(change: impl FnOnce(&mut LightParameters)) -> Generator {
|
||||
let mut generator = Generator::new(GeneratorKind::Direction);
|
||||
let mut light = generator.light.unwrap();
|
||||
change(&mut light);
|
||||
generator.light = Some(light);
|
||||
generator
|
||||
}
|
||||
|
||||
fn assert_close(actual: &[f32], expected: &[f32], what: &str) {
|
||||
assert_eq!(actual.len(), expected.len(), "{what}: texels read");
|
||||
for (index, (actual, expected)) in actual.iter().zip(expected).enumerate() {
|
||||
assert!((actual - expected).abs() < TOLERANCE, "{what}: texel {index} is {actual}, expected {expected}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generators_saved_before_their_new_controls_render_as_before() {
|
||||
let mut fixture = fixture();
|
||||
let points = surface(&fixture);
|
||||
let texels: Vec<_> = points.iter().map(|point| point.0).collect();
|
||||
let (low, high) = fixture.mesh.bounds();
|
||||
let (center, radius) = ((low + high) * 0.5, (high - low).length() * 0.5);
|
||||
|
||||
let position = earlier(GeneratorKind::Position);
|
||||
let expected: Vec<f32> = points.iter().map(|(_, pos, _)| earlier_ramp(&position, ((*pos - center) / radius).y * 0.5 + 0.5)).collect();
|
||||
assert_close(&fixture.sample(position, &texels), &expected, "position");
|
||||
|
||||
let direction = earlier(GeneratorKind::Direction);
|
||||
let expected: Vec<f32> = points.iter().map(|(_, _, nrm)| earlier_ramp(&direction, nrm.y * 0.5 + 0.5)).collect();
|
||||
assert_close(&fixture.sample(direction, &texels), &expected, "direction");
|
||||
|
||||
fixture.baked = uniform_map(BakedMap::AmbientOcclusion, 0.3);
|
||||
let occlusion = earlier(GeneratorKind::AmbientOcclusion);
|
||||
let expected = vec![earlier_ramp(&occlusion, 0.3); texels.len()];
|
||||
assert_close(&fixture.sample(occlusion, &texels), &expected, "ambient occlusion");
|
||||
assert_close(&fixture.sample(Generator::new(GeneratorKind::AmbientOcclusion), &texels), &vec![0.3; texels.len()], "new ambient occlusion");
|
||||
|
||||
fixture.baked = uniform_map(BakedMap::Curvature, 0.7);
|
||||
let curvature = Generator { detail: None, ..earlier(GeneratorKind::Curvature) };
|
||||
let expected = vec![earlier_ramp(&curvature, 0.7); texels.len()];
|
||||
assert_close(&fixture.sample(curvature, &texels), &expected, "curvature");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn world_space_normals_combine_the_axes_of_the_normal() {
|
||||
let mut fixture = fixture();
|
||||
let points = surface(&fixture);
|
||||
let texels: Vec<_> = points.iter().map(|point| point.0).collect();
|
||||
let channel = |axis: usize| -> Vec<f32> { points.iter().map(|(_, _, nrm)| nrm[axis] * 0.5 + 0.5).collect() };
|
||||
|
||||
assert_close(&fixture.sample(Generator::new(GeneratorKind::WorldSpaceNormals), &texels), &channel(1), "top to bottom by default");
|
||||
for (index, axis) in [(SectionParameters::RIGHT_TO_LEFT, 0), (SectionParameters::FRONT_TO_BACK, 2)] {
|
||||
let generator = with_section(GeneratorKind::WorldSpaceNormals, |section| {
|
||||
section.axes[SectionParameters::TOP_TO_BOTTOM].weight = 0.0;
|
||||
section.axes[index].weight = 1.0;
|
||||
});
|
||||
assert_close(&fixture.sample(generator, &texels), &channel(axis), "one axis alone");
|
||||
}
|
||||
|
||||
let multiplied = with_section(GeneratorKind::WorldSpaceNormals, |section| {
|
||||
section.axes[SectionParameters::RIGHT_TO_LEFT] = texturecraft_core::AxisLayer { invert: true, blend: AxisBlend::Multiply, weight: 1.0 };
|
||||
});
|
||||
let expected: Vec<f32> = channel(1).iter().zip(channel(0)).map(|(top, right)| top * (1.0 - right)).collect();
|
||||
assert_close(&fixture.sample(multiplied, &texels), &expected, "inverted right to left multiplies top to bottom");
|
||||
|
||||
// Without a baked map, the generator's own World Space Normal input reads instead of the mesh
|
||||
let mut uniform = Generator::new(GeneratorKind::WorldSpaceNormals);
|
||||
uniform.inputs.insert(BakedMap::WorldNormal, Source::Uniform([0.2, 0.9, 0.4]));
|
||||
assert_close(&fixture.sample(uniform, &texels), &vec![0.9; texels.len()], "a replaced input");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn position_reads_the_mesh_bounds_unless_an_image_is_plugged_in() {
|
||||
let mut fixture = fixture();
|
||||
let points = surface(&fixture);
|
||||
let texels: Vec<_> = points.iter().map(|point| point.0).collect();
|
||||
let (low, high) = fixture.mesh.bounds();
|
||||
let expected: Vec<f32> = points.iter().map(|(_, pos, _)| (pos.y - low.y) / (high.y - low.y)).collect();
|
||||
assert_close(&fixture.sample(Generator::new(GeneratorKind::Position), &texels), &expected, "bounds");
|
||||
|
||||
fixture.baked = uniform_map(BakedMap::Position, 0.25);
|
||||
assert_close(&fixture.sample(Generator::new(GeneratorKind::Position), &texels), &expected, "a baked Position map is not read");
|
||||
|
||||
let balanced = plugged(with_section(GeneratorKind::Position, |section| section.balance = 0.25), 0.25);
|
||||
assert_close(&fixture.sample(balanced, &texels), &vec![0.25f32.powf(0.2); texels.len()], "a power curve balance");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn occlusion_balance_is_linear_and_brightness_lerps() {
|
||||
let mut fixture = fixture();
|
||||
let texels: Vec<_> = surface(&fixture).iter().map(|point| point.0).collect();
|
||||
fixture.baked = uniform_map(BakedMap::AmbientOcclusion, 0.6);
|
||||
let balanced = with_section(GeneratorKind::AmbientOcclusion, |section| section.balance = 0.25);
|
||||
assert_close(&fixture.sample(balanced, &texels), &vec![0.2; texels.len()], "balance 0.25 stretches the upper half");
|
||||
|
||||
let inverted = with_section(GeneratorKind::AmbientOcclusion, |section| section.invert = true);
|
||||
assert_close(&fixture.sample(inverted, &texels), &vec![0.4; texels.len()], "section invert");
|
||||
|
||||
let brighter = plugged(with_section(GeneratorKind::Position, |section| section.brightness = 0.5), 0.4);
|
||||
assert_close(&fixture.sample(brighter, &texels), &vec![0.7; texels.len()], "brightness 0.5 halves the way to white");
|
||||
let darker = plugged(with_section(GeneratorKind::Position, |section| section.brightness = -0.5), 0.4);
|
||||
assert_close(&fixture.sample(darker, &texels), &vec![0.2; texels.len()], "brightness -0.5 halves the value");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn section_blur_spreads_occlusion_across_a_step() {
|
||||
let mut fixture = fixture();
|
||||
let step: Vec<f32> = (0..RES * RES).map(|index| if index % RES < RES / 2 { 0.0 } else { 1.0 }).collect();
|
||||
fixture.baked = BakedMaps { resolution: RES, maps: [(BakedMap::AmbientOcclusion, Arc::new(step))].into() };
|
||||
let row: Vec<(u32, u32)> = surface(&fixture).iter().map(|point| point.0).filter(|texel| texel.0.abs_diff(RES / 2) <= 2).collect();
|
||||
assert!(!row.is_empty());
|
||||
|
||||
let sharp = fixture.sample(Generator::new(GeneratorKind::AmbientOcclusion), &row);
|
||||
assert!(sharp.iter().all(|value| *value == 0.0 || *value == 1.0), "unblurred: {sharp:?}");
|
||||
let blurred = fixture.sample(with_section(GeneratorKind::AmbientOcclusion, |section| section.blur = 16.0), &row);
|
||||
assert!(blurred.iter().all(|value| *value > 0.05 && *value < 0.95), "blurred across the step: {blurred:?}");
|
||||
|
||||
let sharp_position = fixture.sample(Generator::new(GeneratorKind::Position), &row);
|
||||
let blurred_position = fixture.sample(with_section(GeneratorKind::Position, |section| section.blur = 16.0), &row);
|
||||
assert_close(&blurred_position, &sharp_position, "position has no section blur");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn light_angles_light_the_faces_towards_them() {
|
||||
let mut fixture = fixture();
|
||||
let points = surface(&fixture);
|
||||
let facing = |axis: Vec3| -> Vec<(u32, u32)> { points.iter().filter(|(_, _, nrm)| nrm.dot(axis) > 0.97).map(|point| point.0).collect() };
|
||||
|
||||
for (horizontal, vertical, towards) in [(0.0, 0.0, Vec3::NEG_X), (90.0, 0.0, Vec3::Z), (180.0, 0.0, Vec3::X), (0.0, 90.0, Vec3::Y)] {
|
||||
let light = with_light(|light| (light.horizontal, light.vertical, light.attenuation) = (horizontal, vertical, 0.0));
|
||||
let lit = fixture.sample(light.clone(), &facing(towards));
|
||||
let dark = fixture.sample(light, &facing(-towards));
|
||||
assert!(lit.iter().all(|value| *value > 0.95), "{horizontal}° {vertical}° lights {towards}: {lit:?}");
|
||||
assert!(dark.iter().all(|value| *value == 0.0), "{horizontal}° {vertical}° leaves {} dark: {dark:?}", -towards);
|
||||
}
|
||||
|
||||
let inverted = Generator { invert: true, ..with_light(|light| (light.horizontal, light.vertical, light.attenuation) = (0.0, 0.0, 0.0)) };
|
||||
assert!(fixture.sample(inverted, &facing(Vec3::X)).iter().all(|value| *value > 0.95), "invert lights the far side");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn light_attenuation_darkens_the_side_away_from_the_light() {
|
||||
let mut fixture = fixture();
|
||||
let sides: Vec<(u32, u32)> = surface(&fixture).iter().filter(|(_, _, nrm)| nrm.y > 0.97).map(|point| point.0).collect();
|
||||
let half_lit =
|
||||
|attenuation: f32| with_light(|light| (light.horizontal, light.vertical, light.glossiness, light.attenuation) = (0.0, 0.0, 0.0, attenuation));
|
||||
|
||||
let kept = fixture.sample(half_lit(0.0), &sides);
|
||||
let attenuated = fixture.sample(half_lit(0.5), &sides);
|
||||
for (kept, attenuated) in kept.iter().zip(&attenuated) {
|
||||
assert!((kept - 0.5).abs() < 0.15, "the top is about half lit from the side: {kept}");
|
||||
assert!(*attenuated < kept * 0.75, "halfway across the bounds, attenuation darkens it: {attenuated} vs {kept}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
//! A generator's texture (Use Texture) on a sphere: read in UV or triplanar, turned gray, blended over the signal before the global controls
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::surface_point::SurfacePoint;
|
||||
|
||||
use texturecraft_compose::{BakedMaps, ImageRes};
|
||||
use texturecraft_core::{BakedMap, Generator, GeneratorGrayscale, GeneratorKind, SectionParameters, Source, TextureBlend, TextureLayer};
|
||||
use texturecraft_geom::glam::Vec3;
|
||||
use texturecraft_geom::primitives;
|
||||
|
||||
use super::generator_fixture::GeneratorFixture;
|
||||
|
||||
const RES: u32 = 128;
|
||||
|
||||
/// How far a mask value may sit from the expected one
|
||||
const TOLERANCE: f32 = 1e-3;
|
||||
|
||||
/// The ambient occlusion every texel of the sphere reads
|
||||
const OCCLUSION: f32 = 0.3;
|
||||
|
||||
/// Width of the split image: its left half black, its right half white
|
||||
const SPLIT_WIDTH: u32 = 64;
|
||||
|
||||
/// How far from a split's edge (in UV) a texel must sit to read one side only
|
||||
const SPLIT_MARGIN: f32 = 0.05;
|
||||
|
||||
/// A unit sphere with a white fill layer, uniform occlusion and the images `flat` (one color) and `split` (black left, white right)
|
||||
fn fixture(flat: [f32; 3]) -> GeneratorFixture {
|
||||
let mesh = primitives::sphere(1.0, 32, 16);
|
||||
let mut fixture = GeneratorFixture::new(mesh, "builtin:sphere", RES);
|
||||
|
||||
let baked = BakedMaps { resolution: RES, maps: [(BakedMap::AmbientOcclusion, Arc::new(vec![OCCLUSION; (RES * RES) as usize]))].into() };
|
||||
|
||||
let [red, green, blue] = flat;
|
||||
let flat = ImageRes::new(4, 4, vec![[red, green, blue, 1.0]; 16], false);
|
||||
let split_texel = |index: u32| if index % SPLIT_WIDTH < SPLIT_WIDTH / 2 { [0.0, 0.0, 0.0, 1.0] } else { [1.0; 4] };
|
||||
let split = ImageRes::new(SPLIT_WIDTH, SPLIT_WIDTH, (0..SPLIT_WIDTH * SPLIT_WIDTH).map(split_texel).collect(), false);
|
||||
let images = [("flat".to_string(), Arc::new(flat)), ("split".to_string(), Arc::new(split))].into();
|
||||
fixture.baked = baked;
|
||||
fixture.images = images;
|
||||
fixture
|
||||
}
|
||||
|
||||
/// Every covered texel
|
||||
fn surface(fixture: &GeneratorFixture) -> Vec<SurfacePoint> {
|
||||
(0..RES * RES)
|
||||
.filter_map(|index| {
|
||||
let texel = (index % RES, index / RES);
|
||||
let uv = [(texel.0 as f32 + 0.5) / RES as f32, (texel.1 as f32 + 0.5) / RES as f32];
|
||||
fixture.gbuf.surface(&fixture.mesh, index as usize).map(|surface| SurfacePoint { texel, uv, position: surface.pos, normal: surface.nrm })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Ambient Occlusion on its section controls with `texture` reading image `image`
|
||||
fn occlusion_with(image: &str, texture: TextureLayer) -> Generator {
|
||||
Generator { texture: Some(Box::new(TextureLayer { source: Some(Source::image(image)), ..texture })), ..Generator::new(GeneratorKind::AmbientOcclusion) }
|
||||
}
|
||||
|
||||
/// A texture turned on at full opacity, replacing the signal
|
||||
fn replacing() -> TextureLayer {
|
||||
TextureLayer { enabled: true, opacity: 1.0, blend: TextureBlend::Normal, ..TextureLayer::default() }
|
||||
}
|
||||
|
||||
fn assert_all(actual: &[f32], expected: f32, what: &str) {
|
||||
assert!(!actual.is_empty(), "{what}: no texels read");
|
||||
for (index, actual) in actual.iter().enumerate() {
|
||||
assert!((actual - expected).abs() < TOLERANCE, "{what}: texel {index} is {actual}, expected {expected}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_texture_turned_off_or_at_opacity_zero_leaves_the_signal() {
|
||||
let mut fixture = fixture([0.6; 3]);
|
||||
let texels: Vec<_> = surface(&fixture).iter().map(|point| point.texel).collect();
|
||||
|
||||
assert_all(&fixture.sample(occlusion_with("flat", TextureLayer { enabled: false, ..replacing() }), &texels), OCCLUSION, "turned off");
|
||||
assert_all(&fixture.sample(occlusion_with("flat", TextureLayer { opacity: 0.0, ..replacing() }), &texels), OCCLUSION, "opacity 0");
|
||||
assert_all(&fixture.sample(occlusion_with("flat", TextureLayer::default()), &texels), OCCLUSION, "the reference's defaults");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_texture_slot_blends_black() {
|
||||
let mut fixture = fixture([0.6; 3]);
|
||||
let texels: Vec<_> = surface(&fixture).iter().map(|point| point.texel).collect();
|
||||
let empty = Generator { texture: Some(Box::new(TextureLayer { opacity: 0.5, ..replacing() })), ..Generator::new(GeneratorKind::AmbientOcclusion) };
|
||||
assert_all(&fixture.sample(empty, &texels), OCCLUSION * 0.5, "half way to black");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_texture_needs_the_section_controls() {
|
||||
let mut fixture = fixture([0.6; 3]);
|
||||
let texels: Vec<_> = surface(&fixture).iter().map(|point| point.texel).collect();
|
||||
let earlier = Generator { section: None, global: Default::default(), ..occlusion_with("flat", replacing()) };
|
||||
let without = Generator { texture: None, ..earlier.clone() };
|
||||
assert_eq!(fixture.sample(earlier, &texels), fixture.sample(without, &texels));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_texture_turns_gray_by_its_conversion() {
|
||||
let mut fixture = fixture([1.0, 0.25, 0.0]);
|
||||
let texels: Vec<_> = surface(&fixture).iter().map(|point| point.texel).collect();
|
||||
for (grayscale, expected) in [
|
||||
(GeneratorGrayscale::Average, 1.25 / 3.0),
|
||||
(GeneratorGrayscale::Red, 1.0),
|
||||
(GeneratorGrayscale::Green, 0.25),
|
||||
(GeneratorGrayscale::Desaturation, 0.5),
|
||||
(GeneratorGrayscale::Luma, 0.299 + 0.587 * 0.25),
|
||||
] {
|
||||
let generator = occlusion_with("flat", TextureLayer { grayscale, ..replacing() });
|
||||
assert_all(&fixture.sample(generator, &texels), expected, &format!("{grayscale:?}"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlay_with_a_mid_gray_texture_doubles_a_dark_signal_times_the_gray() {
|
||||
let mut fixture = fixture([0.4; 3]);
|
||||
let texels: Vec<_> = surface(&fixture).iter().map(|point| point.texel).collect();
|
||||
let generator = occlusion_with("flat", TextureLayer { blend: TextureBlend::Overlay, opacity: 0.5, ..replacing() });
|
||||
let overlay = 2.0 * OCCLUSION * 0.4;
|
||||
assert_all(&fixture.sample(generator, &texels), OCCLUSION + (overlay - OCCLUSION) * 0.5, "overlay at half opacity");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_image_not_loaded_blends_black_with_or_without_a_blur() {
|
||||
let mut fixture = fixture([0.6; 3]);
|
||||
let texels: Vec<_> = surface(&fixture).iter().map(|point| point.texel).collect();
|
||||
let loading = occlusion_with("not loaded yet", TextureLayer { opacity: 0.5, ..replacing() });
|
||||
assert_all(&fixture.sample(loading.clone(), &texels), OCCLUSION * 0.5, "per texel");
|
||||
|
||||
let mut blurred = loading;
|
||||
blurred.global.blur = 0.5;
|
||||
assert_all(&fixture.sample(blurred, &texels), OCCLUSION * 0.5, "over a region, as the blur computes it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_texture_blends_after_the_section_controls_and_before_the_global_ones() {
|
||||
let mut fixture = fixture([0.6; 3]);
|
||||
let texels: Vec<_> = surface(&fixture).iter().map(|point| point.texel).collect();
|
||||
|
||||
let mut section_inverted = occlusion_with("flat", replacing());
|
||||
section_inverted.section = Some(SectionParameters { invert: true, ..section_inverted.section.unwrap() });
|
||||
assert_all(&fixture.sample(section_inverted, &texels), 0.6, "the texture replaces the inverted section");
|
||||
|
||||
let globally_inverted = Generator { invert: true, ..occlusion_with("flat", replacing()) };
|
||||
assert_all(&fixture.sample(globally_inverted, &texels), 0.4, "the global invert flips the texture");
|
||||
|
||||
let mut blurred = occlusion_with("flat", replacing());
|
||||
blurred.section = Some(SectionParameters { blur: 2.0, ..blurred.section.unwrap() });
|
||||
assert_all(&fixture.sample(blurred, &texels), 0.6, "with the section blur (computed over a region)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uv_scale_repeats_the_texture_about_the_centre() {
|
||||
let mut fixture = fixture([0.0; 3]);
|
||||
let points = surface(&fixture);
|
||||
let side = |u: f32| (u.rem_euclid(1.0) >= 0.5) as u8 as f32;
|
||||
for scale in [1.0, 2.0, 3.0] {
|
||||
let read_at = |u: f32| (u - 0.5) * scale + 0.5;
|
||||
let clear: Vec<_> = points
|
||||
.iter()
|
||||
.filter(|point| {
|
||||
let u = read_at(point.uv[0]).rem_euclid(1.0);
|
||||
[0.0, 0.5, 1.0].iter().all(|edge| (u - edge).abs() > SPLIT_MARGIN * scale)
|
||||
})
|
||||
.collect();
|
||||
let texels: Vec<_> = clear.iter().map(|point| point.texel).collect();
|
||||
let values = fixture.sample(occlusion_with("split", TextureLayer { scale, ..replacing() }), &texels);
|
||||
for (point, value) in clear.iter().zip(values) {
|
||||
let expected = side(read_at(point.uv[0]));
|
||||
assert!((value - expected).abs() < TOLERANCE, "scale {scale} at u {}: {value}, expected {expected}", point.uv[0]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn triplanar_reads_the_top_from_the_plane_facing_up() {
|
||||
let mut fixture = fixture([0.0; 3]);
|
||||
let (low, high) = fixture.mesh.bounds();
|
||||
let across = |position: Vec3| (position.x - low.x) / (high.x - low.x);
|
||||
let top: Vec<_> = surface(&fixture).into_iter().filter(|point| point.normal.y > 0.95 && (across(point.position) - 0.5).abs() > SPLIT_MARGIN).collect();
|
||||
assert!(!top.is_empty());
|
||||
|
||||
let texels: Vec<_> = top.iter().map(|point| point.texel).collect();
|
||||
let sharp = TextureLayer { triplanar: true, triplanar_contrast: 1.0, ..replacing() };
|
||||
let values = fixture.sample(occlusion_with("split", sharp), &texels);
|
||||
for (point, value) in top.iter().zip(values) {
|
||||
let expected = if across(point.position) >= 0.5 { 1.0 } else { 0.0 };
|
||||
assert!((value - expected).abs() < TOLERANCE, "at x {}: {value}, expected {expected}", across(point.position));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
//! The 3D Distance and 3D Linear Gradient generators on a sphere: white at a point falling off over a radius, and a gradient between two points
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use texturecraft_compose::BakedMaps;
|
||||
use texturecraft_core::{BakedMap, DistanceParameters, Generator, GeneratorKind, KindControls, LinearGradientParameters};
|
||||
use texturecraft_geom::primitives;
|
||||
|
||||
use super::generator_fixture::GeneratorFixture;
|
||||
|
||||
const RES: u32 = 64;
|
||||
|
||||
/// A unit sphere with a white fill layer
|
||||
fn fixture() -> GeneratorFixture {
|
||||
let mesh = primitives::sphere(1.0, 32, 16);
|
||||
let mut fixture = GeneratorFixture::new(mesh, "builtin:sphere", RES);
|
||||
|
||||
let baked = BakedMaps { resolution: RES, maps: [(BakedMap::AmbientOcclusion, Arc::new(vec![1.0; (RES * RES) as usize]))].into() };
|
||||
fixture.baked = baked;
|
||||
fixture
|
||||
}
|
||||
|
||||
/// Every covered texel and its height on the sphere
|
||||
fn covered(fixture: &GeneratorFixture) -> Vec<((u32, u32), f32)> {
|
||||
(0..RES * RES).filter_map(|index| fixture.gbuf.surface(&fixture.mesh, index as usize).map(|surface| ((index % RES, index / RES), surface.pos.y))).collect()
|
||||
}
|
||||
|
||||
/// The mask of a 3D Distance generator with `distance` alone over black at `texels`
|
||||
fn mask(fixture: &mut GeneratorFixture, distance: DistanceParameters, texels: &[(u32, u32)]) -> Vec<f32> {
|
||||
fixture.sample(Generator { controls: Some(Box::new(KindControls::Distance(distance))), ..Generator::new(GeneratorKind::ThreeDDistance) }, texels)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_point_at_the_top_lights_the_top() {
|
||||
let mut fixture = fixture();
|
||||
let texels = covered(&fixture);
|
||||
let at: Vec<(u32, u32)> = texels.iter().map(|(texel, _)| *texel).collect();
|
||||
|
||||
let values = mask(&mut fixture, DistanceParameters { point: [0.5, 1.0, 0.5], radius: 0.8, contrast: 0.0, ..DistanceParameters::default() }, &at);
|
||||
let mean_where = |above: bool| {
|
||||
let picked: Vec<f32> = texels.iter().zip(&values).filter(|((_, height), _)| (*height > 0.5) == above).map(|(_, value)| *value).collect();
|
||||
picked.iter().sum::<f32>() / picked.len() as f32
|
||||
};
|
||||
assert!(mean_where(true) > mean_where(false) + 0.3, "top {} bottom {}", mean_where(true), mean_where(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_offset_slides_the_mask_from_black_to_white() {
|
||||
let mut fixture = fixture();
|
||||
let at: Vec<(u32, u32)> = covered(&fixture).iter().map(|(texel, _)| *texel).collect();
|
||||
|
||||
let black = mask(&mut fixture, DistanceParameters { offset: 0.0, ..DistanceParameters::default() }, &at);
|
||||
let white = mask(&mut fixture, DistanceParameters { offset: 1.0, ..DistanceParameters::default() }, &at);
|
||||
assert!(black.iter().all(|value| *value == 0.0));
|
||||
assert!(white.iter().all(|value| *value == 1.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_larger_radius_reaches_further() {
|
||||
let mut fixture = fixture();
|
||||
let at: Vec<(u32, u32)> = covered(&fixture).iter().map(|(texel, _)| *texel).collect();
|
||||
let total = |values: Vec<f32>| values.iter().sum::<f32>();
|
||||
|
||||
let small = total(mask(&mut fixture, DistanceParameters { radius: 0.3, ..DistanceParameters::default() }, &at));
|
||||
let large = total(mask(&mut fixture, DistanceParameters { radius: 1.2, ..DistanceParameters::default() }, &at));
|
||||
assert!(large > small);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_linear_gradient_runs_from_its_start_to_its_end() {
|
||||
let mut fixture = fixture();
|
||||
let texels = covered(&fixture);
|
||||
let at: Vec<(u32, u32)> = texels.iter().map(|(texel, _)| *texel).collect();
|
||||
let gradient = |gradient: LinearGradientParameters| Generator {
|
||||
controls: Some(Box::new(KindControls::LinearGradient(gradient))),
|
||||
..Generator::new(GeneratorKind::ThreeDLinearGradient)
|
||||
};
|
||||
|
||||
let upwards = fixture.sample(gradient(LinearGradientParameters::default()), &at);
|
||||
let downwards = fixture.sample(gradient(LinearGradientParameters { start: [0.5, 1.0, 0.5], end: [0.5, 0.0, 0.5], ..Default::default() }), &at);
|
||||
for (((_, height), up), down) in texels.iter().zip(&upwards).zip(&downwards) {
|
||||
assert!((up - (height * 0.5 + 0.5)).abs() < 0.02, "bottom to top across the sphere's height: {up} at {height}");
|
||||
assert!((up + down - 1.0).abs() < 1e-4, "swapping the points reverses it");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
//! The UV Border Distance generator on a plane filling its UV tile: white at the tile's edge, fading inwards over its distance, softened by its smoothness
|
||||
|
||||
use texturecraft_core::{BorderDistanceParameters, Generator, GeneratorKind, KindControls};
|
||||
use texturecraft_geom::primitives;
|
||||
|
||||
use super::generator_fixture::GeneratorFixture;
|
||||
|
||||
const RES: u32 = 64;
|
||||
|
||||
fn fixture() -> GeneratorFixture {
|
||||
let mesh = primitives::plane(2.0, 1);
|
||||
GeneratorFixture::new(mesh, "builtin:plane", RES)
|
||||
}
|
||||
|
||||
/// The middle row's values, left edge to centre
|
||||
fn row(fixture: &mut GeneratorFixture, border: BorderDistanceParameters) -> Vec<f32> {
|
||||
let generator = Generator { controls: Some(Box::new(KindControls::BorderDistance(border))), ..Generator::new(GeneratorKind::UvBorderDistance) };
|
||||
let texels: Vec<(u32, u32)> = (0..RES / 2).map(|x| (x, RES / 2)).collect();
|
||||
fixture.sample(generator, &texels)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_border_is_white_and_the_inside_fades_to_black() {
|
||||
let mut fixture = fixture();
|
||||
let values = row(&mut fixture, BorderDistanceParameters { distance: 0.5, ..BorderDistanceParameters::default() });
|
||||
|
||||
assert!(values[0] > 0.9, "the edge, a texel in: {}", values[0]);
|
||||
assert!(values.windows(2).all(|pair| pair[1] <= pair[0]), "falling inwards: {values:?}");
|
||||
assert!(*values.last().unwrap() < 0.05, "half a tile in is black at distance 0.5");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_larger_distance_reaches_further_in() {
|
||||
let mut fixture = fixture();
|
||||
let near = row(&mut fixture, BorderDistanceParameters { distance: 0.1, ..BorderDistanceParameters::default() });
|
||||
let far = row(&mut fixture, BorderDistanceParameters { distance: 0.6, ..BorderDistanceParameters::default() });
|
||||
|
||||
assert!(far.iter().sum::<f32>() > near.iter().sum::<f32>() + 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn smoothness_darkens_the_edge_with_the_space_around_the_island() {
|
||||
let mut fixture = fixture();
|
||||
let sharp = row(&mut fixture, BorderDistanceParameters::default());
|
||||
let smooth = row(&mut fixture, BorderDistanceParameters { smoothness: 1.0, ..BorderDistanceParameters::default() });
|
||||
|
||||
assert!(smooth[0] < sharp[0] - 0.2, "{} vs {}", smooth[0], sharp[0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saved_values_out_of_range_render_as_their_nearest_valid_ones() {
|
||||
let mut fixture = fixture();
|
||||
let hostile =
|
||||
row(&mut fixture, BorderDistanceParameters { distance: f32::NAN, smoothness: f32::INFINITY, contrast: 7.0, ..BorderDistanceParameters::default() });
|
||||
let valid = row(&mut fixture, BorderDistanceParameters { contrast: 1.0, ..BorderDistanceParameters::default() });
|
||||
|
||||
assert_eq!(hostile, valid, "non-finite values read their defaults, others their nearest valid value");
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
//! The UV Checker generator on a plane filling its UV tile: a checker with grid lines, its border along the tile's edge
|
||||
|
||||
use texturecraft_core::{Generator, GeneratorKind, KindControls, UvCheckerParameters, UvRandomColorParameters};
|
||||
use texturecraft_geom::primitives;
|
||||
|
||||
use super::generator_fixture::GeneratorFixture;
|
||||
|
||||
const RES: u32 = 256;
|
||||
|
||||
fn fixture() -> GeneratorFixture {
|
||||
let mesh = primitives::plane(2.0, 1);
|
||||
GeneratorFixture::new(mesh, "builtin:plane", RES)
|
||||
}
|
||||
|
||||
/// The middle row, left to right
|
||||
fn row(fixture: &mut GeneratorFixture, checker: UvCheckerParameters) -> Vec<f32> {
|
||||
let generator = Generator { controls: Some(Box::new(KindControls::UvChecker(checker))), ..Generator::new(GeneratorKind::UvChecker) };
|
||||
generator_row(fixture, generator)
|
||||
}
|
||||
|
||||
fn generator_row(fixture: &mut GeneratorFixture, generator: Generator) -> Vec<f32> {
|
||||
let texels: Vec<(u32, u32)> = (0..RES).map(|x| (x, RES / 2 + 3)).collect();
|
||||
fixture.sample(generator, &texels)
|
||||
}
|
||||
|
||||
/// The distinct values of `values`, to 0.01
|
||||
fn tones(values: &[f32]) -> std::collections::BTreeSet<u32> {
|
||||
values.iter().map(|value| (value * 100.0).round() as u32).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_grid_lines_the_checker_has_two_tones_and_a_border() {
|
||||
let mut fixture = fixture();
|
||||
let values = row(&mut fixture, UvCheckerParameters { grid_opacity: 0.0, grid_tile: 1, ..UvCheckerParameters::default() });
|
||||
|
||||
assert_eq!(tones(&values[8..RES as usize - 8]).len(), 2, "two checker tones inside: {:?}", tones(&values));
|
||||
assert!((values[0] - 1.0 / 3.0).abs() < 0.01, "the red border reads a third: {}", values[0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grid_lines_only_darken() {
|
||||
let mut fixture = fixture();
|
||||
let plain = row(&mut fixture, UvCheckerParameters { grid_opacity: 0.0, ..UvCheckerParameters::default() });
|
||||
let lined = row(&mut fixture, UvCheckerParameters::default());
|
||||
|
||||
assert!(lined.iter().zip(&plain).all(|(lined, plain)| lined <= plain));
|
||||
assert!(lined.iter().zip(&plain).any(|(lined, plain)| lined < plain));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checker_keeps_its_pattern_after_random_color_on_the_same_mesh() {
|
||||
let mut fixture = fixture();
|
||||
|
||||
// These controls encode to the same parameter bits when the kind is omitted
|
||||
let random = UvRandomColorParameters { custom_gradient: true, gradient: vec![[1.0, 0.0, 0.5], [0.5, 0.5, 0.0]], positions: vec![0.0, 1.0], quantity: None };
|
||||
let generator = Generator { controls: Some(Box::new(KindControls::UvRandomColor(random))), ..Generator::new(GeneratorKind::UvRandomColor) };
|
||||
let checker =
|
||||
UvCheckerParameters { random_colors: true, grid_tile: 2, grid_opacity: 1.0, border_width: 0.0, checker_color: [0.5; 3], border_color: [0.0, 0.0, 1.0] };
|
||||
|
||||
let island = generator_row(&mut fixture, generator);
|
||||
let pattern = row(&mut fixture, checker);
|
||||
|
||||
assert_eq!(tones(&island).len(), 1, "the plane is a single island");
|
||||
assert!(tones(&pattern).len() > 1, "the checker varies across that island");
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
//! The UV Random Color generator on a cube: one value per UV island, reshuffled by the seed, or picked along a gradient
|
||||
|
||||
use texturecraft_core::{Generator, GeneratorKind, KindControls, UvRandomColorParameters};
|
||||
use texturecraft_geom::{TrianglePartition, primitives};
|
||||
|
||||
use super::generator_fixture::GeneratorFixture;
|
||||
|
||||
const RES: u32 = 128;
|
||||
|
||||
fn fixture() -> GeneratorFixture {
|
||||
let mesh = primitives::cube(1.0);
|
||||
GeneratorFixture::new(mesh, "builtin:cube", RES)
|
||||
}
|
||||
|
||||
/// Every covered texel and its UV island
|
||||
fn covered(fixture: &GeneratorFixture) -> Vec<((u32, u32), usize)> {
|
||||
let islands = TrianglePartition::uv_islands(&fixture.mesh, 0);
|
||||
(0..RES * RES)
|
||||
.filter_map(|index| {
|
||||
let triangle = *fixture.gbuf.tri.get(index as usize)?;
|
||||
islands.index_of(triangle).map(|island| ((index % RES, index / RES), island))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn mask(fixture: &mut GeneratorFixture, random: UvRandomColorParameters, seed: u32, texels: &[(u32, u32)]) -> Vec<f32> {
|
||||
let generator = Generator { controls: Some(Box::new(KindControls::UvRandomColor(random))), seed, ..Generator::new(GeneratorKind::UvRandomColor) };
|
||||
fixture.sample(generator, texels)
|
||||
}
|
||||
|
||||
/// Each island's values, by island
|
||||
fn by_island(texels: &[((u32, u32), usize)], values: &[f32]) -> std::collections::BTreeMap<usize, Vec<f32>> {
|
||||
let mut islands = std::collections::BTreeMap::<usize, Vec<f32>>::new();
|
||||
for ((_, island), value) in texels.iter().zip(values) {
|
||||
islands.entry(*island).or_default().push(*value);
|
||||
}
|
||||
islands
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_island_is_one_value_and_the_islands_differ() {
|
||||
let mut fixture = fixture();
|
||||
let texels = covered(&fixture);
|
||||
let at: Vec<(u32, u32)> = texels.iter().map(|(texel, _)| *texel).collect();
|
||||
|
||||
let islands = by_island(&texels, &mask(&mut fixture, UvRandomColorParameters::default(), 0, &at));
|
||||
assert!(islands.len() > 1, "the cube has several UV islands");
|
||||
assert!(islands.values().all(|values| values.iter().all(|value| (value - values[0]).abs() < 1e-6)));
|
||||
let firsts: Vec<f32> = islands.values().map(|values| values[0]).collect();
|
||||
assert!(firsts.iter().any(|value| (value - firsts[0]).abs() > 0.01));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_seed_reshuffles_the_values() {
|
||||
let mut fixture = fixture();
|
||||
let at: Vec<(u32, u32)> = covered(&fixture).iter().map(|(texel, _)| *texel).collect();
|
||||
|
||||
let first = mask(&mut fixture, UvRandomColorParameters::default(), 0, &at);
|
||||
let second = mask(&mut fixture, UvRandomColorParameters::default(), 2, &at);
|
||||
assert_ne!(first, second);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_one_color_gradient_colors_every_island_alike() {
|
||||
let mut fixture = fixture();
|
||||
let at: Vec<(u32, u32)> = covered(&fixture).iter().map(|(texel, _)| *texel).collect();
|
||||
|
||||
let values =
|
||||
mask(&mut fixture, UvRandomColorParameters { custom_gradient: true, gradient: vec![[0.1, 0.2, 0.3]], ..UvRandomColorParameters::default() }, 0, &at);
|
||||
assert!(values.iter().all(|value| (value - 0.2).abs() < 1e-5), "the mean of its channels");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moving_a_gradient_stop_brightens_the_islands() {
|
||||
let mut fixture = fixture();
|
||||
let at: Vec<(u32, u32)> = covered(&fixture).iter().map(|(texel, _)| *texel).collect();
|
||||
let black_to_white = |positions: Vec<f32>| UvRandomColorParameters {
|
||||
custom_gradient: true,
|
||||
gradient: vec![[0.0; 3], [1.0; 3]],
|
||||
positions,
|
||||
..UvRandomColorParameters::default()
|
||||
};
|
||||
|
||||
let even = mask(&mut fixture, black_to_white(Vec::new()), 0, &at);
|
||||
let white_early = mask(&mut fixture, black_to_white(vec![0.0, 0.2]), 0, &at);
|
||||
let mean = |values: &[f32]| values.iter().sum::<f32>() / values.len().max(1) as f32;
|
||||
assert!(mean(&white_early) > mean(&even), "white reached sooner along the gradient: brighter islands");
|
||||
assert!(white_early.iter().zip(&even).all(|(early, even)| early >= even), "no island darker");
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
mod generator_custom_grunge;
|
||||
mod generator_dripping_rust;
|
||||
mod generator_fixture;
|
||||
mod generator_grayscale_conversion;
|
||||
mod generator_micro_details;
|
||||
mod generator_sections;
|
||||
mod generator_texture;
|
||||
mod generator_three_d_distance;
|
||||
mod generator_uv_border_distance;
|
||||
mod generator_uv_checker;
|
||||
mod generator_uv_random_color;
|
||||
mod surface_point;
|
||||
@@ -0,0 +1,9 @@
|
||||
use texturecraft_geom::glam::Vec3;
|
||||
|
||||
/// A covered texel with its UV, world position and normal
|
||||
pub(super) struct SurfacePoint {
|
||||
pub(super) texel: (u32, u32),
|
||||
pub(super) uv: [f32; 2],
|
||||
pub(super) position: Vec3,
|
||||
pub(super) normal: Vec3,
|
||||
}
|
||||
@@ -7,6 +7,8 @@ mod bake_antialiasing;
|
||||
mod bake_paint_target;
|
||||
mod bake_resolution;
|
||||
mod bake_settings;
|
||||
mod bake_sync;
|
||||
mod bake_sync_group;
|
||||
mod mesh_match_mode;
|
||||
mod skew_correction_method;
|
||||
pub use bake_paint_target::BakePaintTarget;
|
||||
@@ -45,6 +47,8 @@ pub use backface_mode::BackfaceMode;
|
||||
pub use bake_antialiasing::BakeAntialiasing;
|
||||
pub use bake_resolution::BakeResolution;
|
||||
pub use bake_settings::BakeSettings;
|
||||
pub use bake_sync::BakeSync;
|
||||
pub use bake_sync_group::BakeSyncGroup;
|
||||
pub use baked_map::BakedMap;
|
||||
pub use bent_normal_settings::BentNormalSettings;
|
||||
pub use cage_settings::CageSettings;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::{CageSettings, CageType, CommonBakeSettings, HighPolySettings, MeshMapSettings, SkewSettings};
|
||||
use super::{BakeSync, BakeSyncGroup, CageSettings, CageType, CommonBakeSettings, HighPolySettings, MeshMapSettings, SkewSettings};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Persisted clean-room bake settings, grouped by the controls they belong to
|
||||
@@ -10,6 +10,8 @@ pub struct BakeSettings {
|
||||
pub cage: CageSettings,
|
||||
pub skew: SkewSettings,
|
||||
pub maps: MeshMapSettings,
|
||||
/// What this texture set shares with the others
|
||||
pub sync: BakeSync,
|
||||
}
|
||||
|
||||
impl BakeSettings {
|
||||
@@ -17,4 +19,17 @@ impl BakeSettings {
|
||||
pub fn skew_applies(&self) -> bool {
|
||||
!self.high_poly.use_low_as_high && self.cage.kind == CageType::DistanceBased && self.cage.average_normals
|
||||
}
|
||||
|
||||
/// Take `group`'s settings from `source`, keeping whether this set is baked and which maps it bakes
|
||||
pub fn copy_group(&mut self, source: &BakeSettings, group: BakeSyncGroup) {
|
||||
match group {
|
||||
BakeSyncGroup::Common => {
|
||||
self.common = CommonBakeSettings { is_enabled: self.common.is_enabled, ..source.common };
|
||||
self.high_poly = source.high_poly.clone();
|
||||
self.cage = source.cage;
|
||||
self.skew = source.skew;
|
||||
}
|
||||
BakeSyncGroup::Map(map) => self.maps.copy_parameters(map, &source.maps),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
use super::{BakeSyncGroup, BakedMap};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
/// Which of a texture set's bake settings it shares with every other texture set sharing them; all are shared at first, as in the reference
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct BakeSync {
|
||||
/// Shares Common Settings: output, high poly, cage and skew correction
|
||||
pub common: bool,
|
||||
/// The map types whose settings it shares
|
||||
pub maps: BTreeSet<BakedMap>,
|
||||
}
|
||||
|
||||
impl Default for BakeSync {
|
||||
fn default() -> Self {
|
||||
Self { common: true, maps: BakedMap::ALL.into_iter().collect() }
|
||||
}
|
||||
}
|
||||
|
||||
impl BakeSync {
|
||||
pub fn shares(&self, group: BakeSyncGroup) -> bool {
|
||||
match group {
|
||||
BakeSyncGroup::Common => self.common,
|
||||
BakeSyncGroup::Map(map) => self.maps.contains(&map),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_shares(&mut self, group: BakeSyncGroup, shares: bool) {
|
||||
match group {
|
||||
BakeSyncGroup::Common => self.common = shares,
|
||||
BakeSyncGroup::Map(map) if shares => {
|
||||
self.maps.insert(map);
|
||||
}
|
||||
BakeSyncGroup::Map(map) => {
|
||||
self.maps.remove(&map);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
use super::BakedMap;
|
||||
|
||||
/// A part of the bake settings texture sets can share: Common Settings, or one map type's settings
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum BakeSyncGroup {
|
||||
Common,
|
||||
Map(BakedMap),
|
||||
}
|
||||
@@ -4,5 +4,7 @@ use serde::{Deserialize, Serialize};
|
||||
pub enum CageType {
|
||||
#[default]
|
||||
DistanceBased,
|
||||
/// Distances fitted to the high poly at every low-poly vertex
|
||||
Automatic,
|
||||
CustomFile,
|
||||
}
|
||||
@@ -21,8 +21,8 @@ impl Default for CommonBakeSettings {
|
||||
resolution: BakeResolution::R2048,
|
||||
resolution_height: None,
|
||||
antialiasing: BakeAntialiasing::None,
|
||||
dilation: 1,
|
||||
apply_diffusion: true,
|
||||
dilation: 32,
|
||||
apply_diffusion: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -68,6 +68,22 @@ impl MeshMapSettings {
|
||||
*enabled = is_enabled;
|
||||
}
|
||||
|
||||
/// Take `map`'s parameters from `source`, keeping whether it is checked
|
||||
pub fn copy_parameters(&mut self, map: BakedMap, source: &MeshMapSettings) {
|
||||
match map {
|
||||
BakedMap::Normal => self.normal.parameters = source.normal.parameters,
|
||||
BakedMap::WorldNormal => self.world_normal.parameters = source.world_normal.parameters,
|
||||
BakedMap::Id => self.id.parameters = source.id.parameters,
|
||||
BakedMap::AmbientOcclusion => self.ao.parameters = source.ao.parameters,
|
||||
BakedMap::Curvature => self.curvature.parameters = source.curvature.parameters,
|
||||
BakedMap::Position => self.position.parameters = source.position.parameters,
|
||||
BakedMap::Thickness => self.thickness.parameters = source.thickness.parameters,
|
||||
BakedMap::Height => self.height.parameters = source.height.parameters,
|
||||
BakedMap::BentNormal => self.bent_normal.parameters = source.bent_normal.parameters,
|
||||
BakedMap::Opacity => self.opacity.parameters = source.opacity.parameters,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn enabled(&self) -> impl Iterator<Item = BakedMap> {
|
||||
BakedMap::ALL.into_iter().filter(|map| self.is_enabled(*map))
|
||||
}
|
||||
|
||||
@@ -30,6 +30,24 @@ impl BlockScales {
|
||||
Some([(origin[0] + local[0]) * block / working_size.0.max(1) as f32, (origin[1] + local[1]) * block / working_size.1.max(1) as f32])
|
||||
}
|
||||
|
||||
/// Uniform bake atlas UV → working atlas UV, the inverse of [`BlockScales::bake_uv`]
|
||||
pub fn working_uv(&self, uv: [f32; 2], working_size: (u32, u32)) -> Option<[f32; 2]> {
|
||||
if working_size.0 == 0 || working_size.1 == 0 || uv.iter().any(|value| !value.is_finite() || !(0.0..1.0).contains(value)) {
|
||||
return None;
|
||||
}
|
||||
|
||||
if self.scales.is_empty() {
|
||||
return Some(uv);
|
||||
}
|
||||
|
||||
let block = self.block.max(1) as f32;
|
||||
let position = [uv[0] * working_size.0 as f32 / block, uv[1] * working_size.1 as f32 / block];
|
||||
let origin = position.map(f32::floor);
|
||||
let scale = self.at((origin[0] * block) as u32, (origin[1] * block) as u32);
|
||||
let local = [(position[0] - origin[0]) * scale, (position[1] - origin[1]) * scale];
|
||||
Some([(origin[0] + local[0]) * block / working_size.0 as f32, (origin[1] + local[1]) * block / working_size.1 as f32])
|
||||
}
|
||||
|
||||
/// The scale at atlas texel (x, y)
|
||||
pub fn at(&self, x: u32, y: u32) -> f32 {
|
||||
let (bx, by) = (x / self.block.max(1), y / self.block.max(1));
|
||||
|
||||
+402
-31
@@ -12,45 +12,81 @@ use crate::{
|
||||
ShapeCrop, SourceSlopeBlur, SourceWarp, StylizedLighting, SunAndSky, ThresholdMode, TileTransform, finite_unit, lum,
|
||||
};
|
||||
|
||||
mod anchored_micro_detail;
|
||||
mod axis_blend;
|
||||
mod axis_layer;
|
||||
mod border_distance_parameters;
|
||||
mod curvature_detail;
|
||||
mod curvature_mode;
|
||||
mod decal_flip;
|
||||
mod decal_symmetry;
|
||||
mod distance_parameters;
|
||||
mod dripping_rust_parameters;
|
||||
mod filtering;
|
||||
mod generator_global;
|
||||
mod micro_detail;
|
||||
mod generator_grayscale;
|
||||
mod grayscale_conversion_parameters;
|
||||
mod kind_controls;
|
||||
mod light_parameters;
|
||||
mod linear_gradient_parameters;
|
||||
mod micro_curvature_type;
|
||||
mod micro_details;
|
||||
mod output_resolution;
|
||||
mod resolution_mode;
|
||||
mod sampling;
|
||||
mod scale_mode;
|
||||
mod section_parameters;
|
||||
mod texture_blend;
|
||||
mod texture_layer;
|
||||
mod tile_blending;
|
||||
mod tile_generator;
|
||||
mod tile_input_distribution;
|
||||
mod tile_shape;
|
||||
mod tile_size_mode;
|
||||
mod tile_symmetry;
|
||||
mod uv_checker_parameters;
|
||||
mod uv_random_color_parameters;
|
||||
mod uv_transform;
|
||||
mod uv_wrap;
|
||||
mod wear_parameters;
|
||||
|
||||
use anchored_micro_detail::AnchoredMicroDetail;
|
||||
pub use axis_blend::AxisBlend;
|
||||
pub use axis_layer::AxisLayer;
|
||||
pub use border_distance_parameters::BorderDistanceParameters;
|
||||
pub use curvature_detail::CurvatureDetail;
|
||||
pub use curvature_mode::CurvatureMode;
|
||||
pub use decal_flip::DecalFlip;
|
||||
pub use decal_symmetry::DecalSymmetry;
|
||||
pub use distance_parameters::DistanceParameters;
|
||||
pub use dripping_rust_parameters::DrippingRustParameters;
|
||||
pub use filtering::Filtering;
|
||||
pub use generator_global::GeneratorGlobal;
|
||||
pub use micro_detail::MicroDetail;
|
||||
pub use generator_grayscale::GeneratorGrayscale;
|
||||
pub use grayscale_conversion_parameters::GrayscaleConversionParameters;
|
||||
pub use kind_controls::KindControls;
|
||||
pub use light_parameters::LightParameters;
|
||||
pub use linear_gradient_parameters::LinearGradientParameters;
|
||||
pub use micro_curvature_type::MicroCurvatureType;
|
||||
pub use micro_details::MicroDetails;
|
||||
pub use output_resolution::OutputResolution;
|
||||
pub use resolution_mode::ResolutionMode;
|
||||
pub use sampling::Sampling;
|
||||
pub use scale_mode::ScaleMode;
|
||||
pub use section_parameters::SectionParameters;
|
||||
pub use texture_blend::TextureBlend;
|
||||
pub use texture_layer::TextureLayer;
|
||||
pub use tile_blending::TileBlending;
|
||||
pub use tile_generator::TileGenerator;
|
||||
pub use tile_input_distribution::TileInputDistribution;
|
||||
pub use tile_shape::TileShape;
|
||||
pub use tile_size_mode::TileSizeMode;
|
||||
pub use tile_symmetry::TileSymmetry;
|
||||
pub use uv_checker_parameters::UvCheckerParameters;
|
||||
pub use uv_random_color_parameters::UvRandomColorParameters;
|
||||
pub use uv_transform::UvTransform;
|
||||
pub use uv_wrap::UvWrap;
|
||||
pub use wear_parameters::WearParameters;
|
||||
|
||||
/// Id of a layer or effect (one id space per project).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
@@ -926,10 +962,28 @@ pub enum GeneratorKind {
|
||||
Position,
|
||||
/// Surfaces facing a direction (e.g. up for dust).
|
||||
Direction,
|
||||
/// Worn edges of a fibreglass-like coating: the edges fade into its grunge
|
||||
FiberGlassEdgeWear,
|
||||
/// The world space normal's axes combined into one gray
|
||||
WorldSpaceNormals,
|
||||
/// White around a point across the mesh's bounds, fading with the distance from it
|
||||
ThreeDDistance,
|
||||
/// A gradient from a start point to an end point across the mesh's bounds
|
||||
ThreeDLinearGradient,
|
||||
/// White at the UV islands' borders, fading towards their insides
|
||||
UvBorderDistance,
|
||||
/// An image turned gray, tiled and rotated across the UV square
|
||||
GrayscaleConversion,
|
||||
/// Rust in the occluded areas, running down the mesh in drips
|
||||
DrippingRust,
|
||||
/// One random value per UV island
|
||||
UvRandomColor,
|
||||
/// A checker and grid over each UV tile with the UV islands' borders drawn in, for checking a layout
|
||||
UvChecker,
|
||||
}
|
||||
|
||||
impl GeneratorKind {
|
||||
pub const ALL: [GeneratorKind; 7] = [
|
||||
pub const ALL: [GeneratorKind; 16] = [
|
||||
GeneratorKind::EdgeWear,
|
||||
GeneratorKind::Dirt,
|
||||
GeneratorKind::ThinAreas,
|
||||
@@ -937,36 +991,135 @@ impl GeneratorKind {
|
||||
GeneratorKind::AmbientOcclusion,
|
||||
GeneratorKind::Position,
|
||||
GeneratorKind::Direction,
|
||||
GeneratorKind::FiberGlassEdgeWear,
|
||||
GeneratorKind::WorldSpaceNormals,
|
||||
GeneratorKind::ThreeDDistance,
|
||||
GeneratorKind::ThreeDLinearGradient,
|
||||
GeneratorKind::UvBorderDistance,
|
||||
GeneratorKind::GrayscaleConversion,
|
||||
GeneratorKind::DrippingRust,
|
||||
GeneratorKind::UvRandomColor,
|
||||
GeneratorKind::UvChecker,
|
||||
];
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
GeneratorKind::EdgeWear => "Mask Editor: Edge wear",
|
||||
GeneratorKind::EdgeWear => "Worn Metal Edges",
|
||||
GeneratorKind::Dirt => "Dirt",
|
||||
GeneratorKind::ThinAreas => "Thin areas",
|
||||
GeneratorKind::Curvature => "Curvature",
|
||||
GeneratorKind::AmbientOcclusion => "Ambient occlusion",
|
||||
GeneratorKind::Position => "Position gradient",
|
||||
GeneratorKind::Direction => "Light / direction",
|
||||
GeneratorKind::AmbientOcclusion => "Ambient Occlusion",
|
||||
GeneratorKind::Position => "Position",
|
||||
GeneratorKind::Direction => "Light",
|
||||
GeneratorKind::FiberGlassEdgeWear => "Exposed Glass Fibers",
|
||||
GeneratorKind::WorldSpaceNormals => "World Space Normals",
|
||||
GeneratorKind::ThreeDDistance => "3D Distance",
|
||||
GeneratorKind::ThreeDLinearGradient => "3D Linear Gradient",
|
||||
GeneratorKind::UvBorderDistance => "UV Border Distance",
|
||||
GeneratorKind::GrayscaleConversion => "Grayscale Conversion",
|
||||
GeneratorKind::DrippingRust => "Rust Runoff",
|
||||
GeneratorKind::UvRandomColor => "UV Random Color",
|
||||
GeneratorKind::UvChecker => "UV Checker",
|
||||
}
|
||||
}
|
||||
|
||||
/// The name commands and saved projects use for this kind
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
GeneratorKind::EdgeWear => "EdgeWear",
|
||||
GeneratorKind::Dirt => "Dirt",
|
||||
GeneratorKind::ThinAreas => "ThinAreas",
|
||||
GeneratorKind::Curvature => "Curvature",
|
||||
GeneratorKind::AmbientOcclusion => "AmbientOcclusion",
|
||||
GeneratorKind::Position => "Position",
|
||||
GeneratorKind::Direction => "Direction",
|
||||
GeneratorKind::FiberGlassEdgeWear => "FiberGlassEdgeWear",
|
||||
GeneratorKind::WorldSpaceNormals => "WorldSpaceNormals",
|
||||
GeneratorKind::ThreeDDistance => "ThreeDDistance",
|
||||
GeneratorKind::ThreeDLinearGradient => "ThreeDLinearGradient",
|
||||
GeneratorKind::UvBorderDistance => "UvBorderDistance",
|
||||
GeneratorKind::GrayscaleConversion => "GrayscaleConversion",
|
||||
GeneratorKind::DrippingRust => "DrippingRust",
|
||||
GeneratorKind::UvRandomColor => "UvRandomColor",
|
||||
GeneratorKind::UvChecker => "UvChecker",
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the generator picker offers this kind (Thin areas only loads from saved projects and smart masks)
|
||||
pub fn in_picker(self) -> bool {
|
||||
self != GeneratorKind::ThinAreas
|
||||
}
|
||||
|
||||
/// Whether the kind's result depends on its seed
|
||||
pub fn includes_randomness(self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
GeneratorKind::EdgeWear
|
||||
| GeneratorKind::Dirt
|
||||
| GeneratorKind::FiberGlassEdgeWear
|
||||
| GeneratorKind::DrippingRust
|
||||
| GeneratorKind::UvRandomColor
|
||||
| GeneratorKind::UvChecker
|
||||
)
|
||||
}
|
||||
|
||||
/// The mesh maps this kind reads, each an input that an image, a uniform value or an anchor can replace.
|
||||
pub fn inputs(self) -> &'static [BakedMap] {
|
||||
match self {
|
||||
GeneratorKind::EdgeWear | GeneratorKind::Curvature => &[BakedMap::Curvature],
|
||||
GeneratorKind::Dirt | GeneratorKind::AmbientOcclusion => &[BakedMap::AmbientOcclusion],
|
||||
GeneratorKind::EdgeWear | GeneratorKind::Dirt | GeneratorKind::FiberGlassEdgeWear => &[BakedMap::Curvature, BakedMap::AmbientOcclusion],
|
||||
GeneratorKind::Curvature => &[BakedMap::Curvature],
|
||||
GeneratorKind::AmbientOcclusion => &[BakedMap::AmbientOcclusion],
|
||||
GeneratorKind::ThinAreas => &[BakedMap::Thickness],
|
||||
GeneratorKind::Position | GeneratorKind::Direction => &[],
|
||||
GeneratorKind::Position | GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient => &[BakedMap::Position],
|
||||
GeneratorKind::WorldSpaceNormals => &[BakedMap::WorldNormal],
|
||||
GeneratorKind::Direction => &[BakedMap::WorldNormal, BakedMap::Position],
|
||||
// Dripping Rust reads the baked occlusion and the mesh's bounds whole, so no input replaces them yet
|
||||
GeneratorKind::UvBorderDistance
|
||||
| GeneratorKind::GrayscaleConversion
|
||||
| GeneratorKind::DrippingRust
|
||||
| GeneratorKind::UvRandomColor
|
||||
| GeneratorKind::UvChecker => &[],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse(s: &str) -> Option<GeneratorKind> {
|
||||
let norm = |x: &str| x.to_ascii_lowercase().replace([' ', '_', '-', ':'], "");
|
||||
GeneratorKind::ALL.into_iter().find(|k| norm(&format!("{k:?}")) == norm(s) || norm(k.label()) == norm(s))
|
||||
/// Whether the kind was added with the reference's controls only, so it never computes with level, softness and noise
|
||||
pub fn has_no_earlier_model(self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
GeneratorKind::FiberGlassEdgeWear
|
||||
| GeneratorKind::ThreeDDistance
|
||||
| GeneratorKind::ThreeDLinearGradient
|
||||
| GeneratorKind::UvBorderDistance
|
||||
| GeneratorKind::GrayscaleConversion
|
||||
| GeneratorKind::DrippingRust
|
||||
| GeneratorKind::UvRandomColor
|
||||
| GeneratorKind::UvChecker
|
||||
)
|
||||
}
|
||||
|
||||
pub fn parse(name: &str) -> Option<GeneratorKind> {
|
||||
let normalised = |text: &str| text.to_ascii_lowercase().replace([' ', '_', '-', ':'], "");
|
||||
let wanted = normalised(name);
|
||||
|
||||
GeneratorKind::ALL.into_iter().find(|kind| {
|
||||
normalised(kind.id()) == wanted || normalised(kind.label()) == wanted || kind.former_labels().iter().any(|label| normalised(label) == wanted)
|
||||
})
|
||||
}
|
||||
|
||||
/// Earlier names accepted by commands and picker search
|
||||
pub fn former_labels(self) -> &'static [&'static str] {
|
||||
match self {
|
||||
GeneratorKind::EdgeWear => &["Mask Editor: Edge wear", "Metal Edge Wear"],
|
||||
GeneratorKind::Position => &["Position gradient"],
|
||||
GeneratorKind::Direction => &["Light / direction"],
|
||||
GeneratorKind::FiberGlassEdgeWear => &["Fiber Glass Edge Wear"],
|
||||
GeneratorKind::DrippingRust => &["Dripping Rust"],
|
||||
_ => &[],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(remote = "Self")]
|
||||
pub struct Generator {
|
||||
pub kind: GeneratorKind,
|
||||
/// Where the mask starts (0..1, generator specific threshold).
|
||||
@@ -995,9 +1148,48 @@ pub struct Generator {
|
||||
/// What an input reads instead of its mesh map (an image, a uniform value or an anchor); inputs not listed read their mesh map.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub inputs: BTreeMap<BakedMap, Source>,
|
||||
/// Painted height read from an anchor point below, added as micro detail (None: baked maps only).
|
||||
/// The wear kinds' controls (None: the level, softness and noise above, as saved before they existed)
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub micro: Option<MicroDetail>,
|
||||
pub wear: Option<WearParameters>,
|
||||
/// The section controls of Curvature, Ambient Occlusion, Position and World Space Normals (None: the level, softness and noise above, as saved before they existed)
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub section: Option<SectionParameters>,
|
||||
/// The Light generator's controls (None: the level, softness and noise above, as saved before they existed)
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub light: Option<LightParameters>,
|
||||
/// The texture blended over the signal on the section controls (None: Use Texture never touched, as saved before it existed); boxed, so a generator effect stays small
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub texture: Option<Box<TextureLayer>>,
|
||||
/// The image a wear generator reads as its grunge once Use Custom Grunge is on (None: an empty slot)
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub grunge: Option<Source>,
|
||||
/// The micro details of Curvature, Ambient Occlusion and the wear kinds (None: never touched, their defaults: off); boxed, so a generator effect stays small
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub micro: Option<Box<MicroDetails>>,
|
||||
/// The controls of 3D Distance, 3D Linear Gradient, UV Border Distance or Grayscale Conversion (None on the other kinds); boxed, so a generator effect stays small
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub controls: Option<Box<KindControls>>,
|
||||
}
|
||||
|
||||
impl Serialize for Generator {
|
||||
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
Generator::serialize(self, serializer)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for Generator {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Generator, D::Error> {
|
||||
let mut saved = serde_json::Value::deserialize(deserializer)?;
|
||||
|
||||
// Micro detail saved before Micro Details: an anchor point's height and its amount
|
||||
let anchored = saved.get_mut("micro").filter(|micro| micro.get("anchor").is_some()).map(serde_json::Value::take);
|
||||
let mut generator = Generator::deserialize(saved).map_err(serde::de::Error::custom)?;
|
||||
if let Some(anchored) = anchored {
|
||||
let AnchoredMicroDetail { anchor, amount } = serde_json::from_value(anchored).map_err(serde::de::Error::custom)?;
|
||||
generator.micro = MicroDetails::of_anchor(generator.kind, anchor, amount).map(Box::new);
|
||||
}
|
||||
Ok(generator)
|
||||
}
|
||||
}
|
||||
|
||||
impl Generator {
|
||||
@@ -1008,6 +1200,104 @@ impl Generator {
|
||||
pub const MIN_NOISE_SCALE: f32 = 0.01;
|
||||
pub const MAX_NOISE_SCALE: f32 = 1000.0;
|
||||
|
||||
/// The global blur, balance and contrast the generator applies: none on the wear and light controls, which have no such controls
|
||||
pub fn applied_global(&self) -> GeneratorGlobal {
|
||||
if self.wear.is_some() || self.light.is_some() || self.kind.has_no_earlier_model() { GeneratorGlobal::default() } else { self.global }
|
||||
}
|
||||
|
||||
/// The section controls the generator computes with: its own, World Space Normals' defaults when it has none (it has no earlier model), else None
|
||||
pub fn section_controls(&self) -> Option<SectionParameters> {
|
||||
self.section.or_else(|| SectionParameters::defaults(self.kind).filter(|_| self.kind == GeneratorKind::WorldSpaceNormals))
|
||||
}
|
||||
|
||||
/// The 3D Distance controls the generator computes with: its own, else the defaults on a 3D Distance generator
|
||||
pub fn distance_controls(&self) -> Option<DistanceParameters> {
|
||||
match self.kind_controls() {
|
||||
Some(KindControls::Distance(distance)) => Some(distance),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The 3D Linear Gradient controls the generator computes with: its own, else the defaults on a 3D Linear Gradient generator
|
||||
pub fn linear_gradient_controls(&self) -> Option<LinearGradientParameters> {
|
||||
match self.kind_controls() {
|
||||
Some(KindControls::LinearGradient(gradient)) => Some(gradient),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The UV Border Distance controls the generator computes with: its own, else the defaults on a UV Border Distance generator
|
||||
pub fn border_distance_controls(&self) -> Option<BorderDistanceParameters> {
|
||||
match self.kind_controls() {
|
||||
Some(KindControls::BorderDistance(border)) => Some(border),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The Grayscale Conversion controls the generator computes with: its own, else the defaults on a Grayscale Conversion generator
|
||||
pub fn grayscale_controls(&self) -> Option<GrayscaleConversionParameters> {
|
||||
match self.kind_controls() {
|
||||
Some(KindControls::Grayscale(grayscale)) => Some(grayscale),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The controls of a kind with only its own controls: its saved ones (brought into range) when they are that kind's, else its defaults
|
||||
pub fn kind_controls(&self) -> Option<KindControls> {
|
||||
let saved = self.controls.as_deref().filter(|controls| controls.kind() == self.kind).cloned().map(KindControls::clamped);
|
||||
saved.or_else(|| KindControls::defaults(self.kind))
|
||||
}
|
||||
|
||||
/// The Grayscale Conversion controls as saved, without a copy
|
||||
fn grayscale_controls_ref(&self) -> Option<&GrayscaleConversionParameters> {
|
||||
match self.controls.as_deref() {
|
||||
Some(KindControls::Grayscale(grayscale)) if self.kind == GeneratorKind::GrayscaleConversion => Some(grayscale),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The mode and detail sizes the generator reads its curvature with: its own, the defaults on Curvature's section controls, else None
|
||||
pub fn detail_in_use(&self) -> Option<CurvatureDetail> {
|
||||
let on_section = self.kind == GeneratorKind::Curvature && self.section_controls().is_some();
|
||||
self.detail.clone().or_else(|| on_section.then(CurvatureDetail::default))
|
||||
}
|
||||
|
||||
/// The mesh maps the generator reads: none for Position and Light on the earlier model, which read the mesh itself
|
||||
pub fn inputs_in_use(&self) -> &'static [BakedMap] {
|
||||
let reads_geometry = self.on_earlier_model() && matches!(self.kind, GeneratorKind::Position | GeneratorKind::Direction);
|
||||
if reads_geometry { &[] } else { self.kind.inputs() }
|
||||
}
|
||||
|
||||
/// The texture the generator blends over its signal: only on the section controls, turned on with some opacity
|
||||
pub fn texture_in_use(&self) -> Option<&TextureLayer> {
|
||||
self.texture.as_deref().filter(|texture| texture.in_use() && self.section_controls().is_some())
|
||||
}
|
||||
|
||||
/// Everything the generator reads instead of its mesh maps: its inputs, then its texture, its custom grunge, its micro details and its Grayscale Conversion image
|
||||
pub fn sources(&self) -> impl Iterator<Item = &Source> {
|
||||
let micro = self.micro.iter().flat_map(|micro| micro.sources()).chain(self.grayscale_controls_ref().and_then(|grayscale| grayscale.source.as_ref()));
|
||||
self.inputs.values().chain(self.texture.as_ref().and_then(|texture| texture.source.as_ref())).chain(self.grunge.as_ref()).chain(micro)
|
||||
}
|
||||
|
||||
/// The micro details as saved, when the generator computes with them: with a slot switched on, except a micro detail saved before Micro Details on a generator still on the earlier model, which [`Generator::earlier_micro`] reads (bring them into range before use: saved files are not trusted)
|
||||
pub fn micro_in_use(&self) -> Option<&MicroDetails> {
|
||||
self.micro.as_deref().filter(|micro| micro.in_use(self.kind) && !(micro.earlier && self.on_earlier_model()))
|
||||
}
|
||||
|
||||
/// The anchor point and amount (0..1) of a micro detail saved before Micro Details, while the generator is still on the earlier model: its signal adds that anchor's height times the amount, as it did when saved
|
||||
pub fn earlier_micro(&self) -> Option<(LayerId, f32)> {
|
||||
let micro = self.micro.as_deref().filter(|micro| micro.earlier && micro.in_use(self.kind) && micro.height && self.on_earlier_model())?;
|
||||
let Some(Source::Anchor { anchor, .. }) = µ.height_source else { return None };
|
||||
|
||||
let amount = micro.height_intensity / MicroDetails::HEIGHT_INTENSITY_PER_AMOUNT;
|
||||
Some((*anchor, if amount.is_finite() { amount.clamp(0.0, 1.0) } else { 0.0 }))
|
||||
}
|
||||
|
||||
/// Whether the generator is on the level, softness and noise it had before the reference app's controls
|
||||
pub fn on_earlier_model(&self) -> bool {
|
||||
self.wear.is_none() && self.light.is_none() && self.section_controls().is_none() && !self.kind.has_no_earlier_model()
|
||||
}
|
||||
|
||||
pub fn new(kind: GeneratorKind) -> Generator {
|
||||
let (level, softness, noise_amount) = match kind {
|
||||
GeneratorKind::EdgeWear => (0.5, 0.25, 0.3),
|
||||
@@ -1035,7 +1325,13 @@ impl Generator {
|
||||
global: GeneratorGlobal::default(),
|
||||
resolution: OutputResolution::default(),
|
||||
inputs: BTreeMap::new(),
|
||||
wear: WearParameters::defaults(kind),
|
||||
section: SectionParameters::defaults(kind),
|
||||
light: LightParameters::defaults(kind),
|
||||
texture: None,
|
||||
grunge: None,
|
||||
micro: None,
|
||||
controls: KindControls::defaults(kind).map(Box::new),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2007,10 +2303,7 @@ impl EffectKind {
|
||||
match self {
|
||||
EffectKind::Fill { source, .. } => source.reads_anchor(anchor),
|
||||
EffectKind::Material(fill) => fill.sources.values().any(|source| source.reads_anchor(anchor)),
|
||||
EffectKind::Generator(generator) => {
|
||||
generator.micro.is_some_and(|micro| anchor.is_none_or(|wanted| wanted == micro.anchor))
|
||||
|| generator.inputs.values().any(|source| source.reads_anchor(anchor))
|
||||
}
|
||||
EffectKind::Generator(generator) => generator.sources().any(|source| source.reads_anchor(anchor)),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
@@ -2020,22 +2313,16 @@ impl EffectKind {
|
||||
let sources: Vec<&Source> = match self {
|
||||
EffectKind::Fill { source, .. } => vec![source],
|
||||
EffectKind::Material(fill) => fill.sources.values().collect(),
|
||||
EffectKind::Generator(generator) => generator.inputs.values().collect(),
|
||||
EffectKind::Generator(generator) => generator.sources().collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let mut anchors: Vec<_> = sources
|
||||
sources
|
||||
.into_iter()
|
||||
.filter_map(|source| match source {
|
||||
Source::Anchor { anchor, channel, .. } => Some((*anchor, *channel)),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
if let EffectKind::Generator(generator) = self
|
||||
&& let Some(micro) = generator.micro
|
||||
{
|
||||
anchors.push((micro.anchor, Channel::Height));
|
||||
}
|
||||
anchors
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The image resources this effect's sources read (a fill, its patterns, a material or a generator input, a colour selection's ID map)
|
||||
@@ -2043,7 +2330,7 @@ impl EffectKind {
|
||||
let sources: Vec<&Source> = match self {
|
||||
EffectKind::Fill { source, .. } => vec![source],
|
||||
EffectKind::Material(fill) => fill.sources.values().collect(),
|
||||
EffectKind::Generator(generator) => generator.inputs.values().collect(),
|
||||
EffectKind::Generator(generator) => generator.sources().collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let id_map = match self {
|
||||
@@ -2245,6 +2532,48 @@ mod tests {
|
||||
assert_eq!((not_finite.scale, not_finite.rotation), (1.0, 0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generator_ids_are_the_saved_names_and_parse_back() {
|
||||
for kind in GeneratorKind::ALL {
|
||||
assert_eq!(serde_json::to_value(kind).unwrap(), serde_json::json!(kind.id()));
|
||||
assert_eq!(GeneratorKind::parse(kind.id()), Some(kind));
|
||||
assert_eq!(GeneratorKind::parse(kind.label()), Some(kind));
|
||||
}
|
||||
assert!(!GeneratorKind::ThinAreas.in_picker(), "Thin areas only loads from saved projects and smart masks");
|
||||
assert_eq!(GeneratorKind::parse("Light / direction"), Some(GeneratorKind::Direction), "earlier labels still parse");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wear_generators_saved_before_their_wear_controls_load_on_the_earlier_model() {
|
||||
let mut saved = serde_json::to_value(Generator::new(GeneratorKind::EdgeWear)).unwrap();
|
||||
assert!(saved.get("wear").is_some(), "new wear generators have wear controls");
|
||||
|
||||
saved.as_object_mut().unwrap().remove("wear");
|
||||
let loaded: Generator = serde_json::from_value(saved).unwrap();
|
||||
assert_eq!(loaded.wear, None, "level, softness and noise keep driving it");
|
||||
let curvature = serde_json::to_value(Generator::new(GeneratorKind::Curvature)).unwrap();
|
||||
assert!(curvature.get("wear").is_none(), "other kinds save no wear controls");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generators_saved_before_their_section_or_light_controls_load_on_the_earlier_model() {
|
||||
for kind in [GeneratorKind::Curvature, GeneratorKind::AmbientOcclusion, GeneratorKind::Position, GeneratorKind::Direction] {
|
||||
let mut saved = serde_json::to_value(Generator::new(kind)).unwrap();
|
||||
let key = if kind == GeneratorKind::Direction { "light" } else { "section" };
|
||||
assert!(saved.get(key).is_some(), "new {kind:?} generators have the reference's controls");
|
||||
|
||||
saved.as_object_mut().unwrap().remove(key);
|
||||
let loaded: Generator = serde_json::from_value(saved).unwrap();
|
||||
assert!(loaded.on_earlier_model(), "{kind:?}: level, softness and noise keep driving it");
|
||||
assert_eq!(loaded.applied_global(), loaded.global, "{kind:?} keeps its global adjustments");
|
||||
}
|
||||
|
||||
let mut saved = serde_json::to_value(Generator::new(GeneratorKind::WorldSpaceNormals)).unwrap();
|
||||
saved.as_object_mut().unwrap().remove("section");
|
||||
let loaded: Generator = serde_json::from_value(saved).unwrap();
|
||||
assert_eq!(loaded.section_controls(), SectionParameters::defaults(GeneratorKind::WorldSpaceNormals), "it has no earlier model");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curvature_generators_saved_before_detail_sizes_load_without_them() {
|
||||
let mut saved = serde_json::to_value(Generator::new(GeneratorKind::Curvature)).unwrap();
|
||||
@@ -2481,10 +2810,10 @@ mod tests {
|
||||
let reader = fill_layer.mask.as_ref().map(|mask| &mask.effects[0].kind);
|
||||
assert!(reader.is_some_and(|reader| reader.reads(Some(LayerId(9))) && reader.reads(None) && !reader.reads(Some(LayerId(8)))));
|
||||
|
||||
// A generator with micro detail reads its anchor too
|
||||
// A generator whose Micro Height reads an anchor reads it too
|
||||
let mut generator_layer = Layer::new(LayerId(3), "g", LayerKind::Paint, &[Channel::BaseColor]);
|
||||
let mut generator = Generator::new(GeneratorKind::Dirt);
|
||||
generator.micro = Some(MicroDetail { anchor: LayerId(9), amount: 0.5 });
|
||||
generator.micro = MicroDetails::of_anchor(GeneratorKind::Dirt, LayerId(9), 0.5).map(Box::new);
|
||||
|
||||
assert_eq!(EffectKind::Generator(generator.clone()).anchors_read(), [(LayerId(9), Channel::Height)]);
|
||||
assert!(EffectKind::Generator(generator.clone()).reads(Some(LayerId(9))) && !EffectKind::Generator(generator.clone()).reads(Some(LayerId(8))));
|
||||
@@ -2494,6 +2823,48 @@ mod tests {
|
||||
assert!(generator_layer.reads_anchor());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn micro_detail_saved_on_an_anchor_loads_as_micro_details_reading_its_height() {
|
||||
let mut saved = serde_json::to_value(Generator::new(GeneratorKind::Curvature)).unwrap();
|
||||
saved["micro"] = serde_json::json!({"anchor": 9, "amount": 0.25});
|
||||
|
||||
let generator: Generator = serde_json::from_value(saved.clone()).unwrap();
|
||||
let micro = generator.micro.as_deref().unwrap();
|
||||
let defaults = MicroDetails::defaults(GeneratorKind::Curvature).unwrap();
|
||||
|
||||
assert!(micro.enabled && micro.height, "{micro:?}");
|
||||
assert_eq!(micro.height_source, Some(Source::Anchor { anchor: LayerId(9), channel: Channel::Height, ramp: Vec::new() }));
|
||||
assert!(micro.height_intensity < defaults.height_intensity, "a weaker amount reads a gentler height");
|
||||
assert_eq!((micro.curvature_type, micro.ao_radius, micro.normal_source.clone()), (defaults.curvature_type, defaults.ao_radius, None));
|
||||
assert!(EffectKind::Generator(generator.clone()).reads(Some(LayerId(9))));
|
||||
|
||||
let reloaded: Generator = serde_json::from_value(serde_json::to_value(&generator).unwrap()).unwrap();
|
||||
assert_eq!(reloaded, generator, "saved again as Micro Details");
|
||||
|
||||
saved["kind"] = serde_json::to_value(GeneratorKind::ThinAreas).unwrap();
|
||||
let without: Generator = serde_json::from_value(saved).unwrap();
|
||||
assert!(without.micro.is_none(), "a kind without micro details drops it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_micro_detail_saved_on_an_anchor_keeps_its_earlier_reading_until_the_generator_leaves_the_earlier_model() {
|
||||
// Saved before the reference's controls too: on the earlier model
|
||||
let earlier = Generator { section: None, ..Generator::new(GeneratorKind::Curvature) };
|
||||
let mut saved = serde_json::to_value(earlier).unwrap();
|
||||
saved["micro"] = serde_json::json!({"anchor": 9, "amount": 0.25});
|
||||
let generator: Generator = serde_json::from_value(saved).unwrap();
|
||||
|
||||
assert_eq!(generator.earlier_micro(), Some((LayerId(9), 0.25)));
|
||||
assert!(generator.micro_in_use().is_none(), "the earlier reading replaces the Micro Height's curvature");
|
||||
|
||||
let reloaded: Generator = serde_json::from_value(serde_json::to_value(&generator).unwrap()).unwrap();
|
||||
assert_eq!(reloaded.earlier_micro(), Some((LayerId(9), 0.25)), "saving again keeps the earlier reading");
|
||||
|
||||
let on_sections = Generator { section: SectionParameters::defaults(GeneratorKind::Curvature), ..generator };
|
||||
assert_eq!(on_sections.earlier_micro(), None);
|
||||
assert!(on_sections.micro_in_use().is_some(), "on the reference's controls the anchor reads as a Micro Height");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_masks_saved_before_sources_compare_the_mask_with_the_constant_hard() {
|
||||
let saved = r#"{"Compare":{"op":"GreaterThan","value":0.5,"tolerance":0.1}}"#;
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
use serde::Deserialize;
|
||||
|
||||
use super::LayerId;
|
||||
|
||||
/// Micro detail as saved before Micro Details: the anchor point whose painted height it read, and how strongly
|
||||
#[derive(Deserialize)]
|
||||
pub(crate) struct AnchoredMicroDetail {
|
||||
pub anchor: LayerId,
|
||||
/// 0..1, 0.5 by default
|
||||
#[serde(default = "AnchoredMicroDetail::default_amount")]
|
||||
pub amount: f32,
|
||||
}
|
||||
|
||||
impl AnchoredMicroDetail {
|
||||
fn default_amount() -> f32 {
|
||||
0.5
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// How an axis of a World Space Normals or Position generator combines with the axes before it
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AxisBlend {
|
||||
/// The axis replaces what is below it
|
||||
Normal,
|
||||
/// The axis adds to what is below it
|
||||
Add,
|
||||
/// The axis is taken from what is below it
|
||||
Subtract,
|
||||
/// The axis multiplies what is below it
|
||||
Multiply,
|
||||
/// The axis adds above its middle gray and subtracts below it
|
||||
AddSub,
|
||||
/// The brighter of the axis and what is below it
|
||||
Max,
|
||||
}
|
||||
|
||||
impl AxisBlend {
|
||||
pub const ALL: [AxisBlend; 6] = [AxisBlend::Normal, AxisBlend::Add, AxisBlend::Subtract, AxisBlend::Multiply, AxisBlend::AddSub, AxisBlend::Max];
|
||||
|
||||
/// The name the panel shows
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
AxisBlend::Normal => "Normal",
|
||||
AxisBlend::Add => "Linear Dodge (Add)",
|
||||
AxisBlend::Subtract => "Subtract",
|
||||
AxisBlend::Multiply => "Multiply",
|
||||
AxisBlend::AddSub => "Add/Sub",
|
||||
AxisBlend::Max => "Max (Lighten)",
|
||||
}
|
||||
}
|
||||
|
||||
/// The name commands and saved projects use
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
AxisBlend::Normal => "normal",
|
||||
AxisBlend::Add => "add",
|
||||
AxisBlend::Subtract => "subtract",
|
||||
AxisBlend::Multiply => "multiply",
|
||||
AxisBlend::AddSub => "addSub",
|
||||
AxisBlend::Max => "max",
|
||||
}
|
||||
}
|
||||
|
||||
/// The blend named by its id or its label, in any case
|
||||
pub fn parse(name: &str) -> Option<AxisBlend> {
|
||||
AxisBlend::ALL.into_iter().find(|blend| blend.id().eq_ignore_ascii_case(name) || blend.label().eq_ignore_ascii_case(name))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::axis_blend::AxisBlend;
|
||||
|
||||
/// One axis of a World Space Normals or Position generator: its channel, inverted or not, blended over the axes before it
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AxisLayer {
|
||||
/// The axis read from its far side
|
||||
pub invert: bool,
|
||||
pub blend: AxisBlend,
|
||||
/// How much of the blend shows (0..1)
|
||||
pub weight: f32,
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// The UV Border Distance generator's controls: white at the UV islands' borders, fading towards their insides
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct BorderDistanceParameters {
|
||||
/// How far in from the border the gradient reaches (0..1; 1 is half a UV tile)
|
||||
pub distance: f32,
|
||||
/// Softens the gradient, the empty space around the islands darkening their borders (0..1)
|
||||
pub smoothness: f32,
|
||||
/// Shifts the gradient darker (below 0.5) or brighter (above 0.5)
|
||||
pub balance: f32,
|
||||
/// Narrows the gradient around its middle (0..1; 1 a hard step)
|
||||
pub contrast: f32,
|
||||
}
|
||||
|
||||
impl BorderDistanceParameters {
|
||||
/// Every value brought into 0..1, non-finite ones to the defaults
|
||||
pub fn clamped(self) -> BorderDistanceParameters {
|
||||
let defaults = BorderDistanceParameters::default();
|
||||
let unit = |value: f32, default: f32| if value.is_finite() { value.clamp(0.0, 1.0) } else { default };
|
||||
|
||||
BorderDistanceParameters {
|
||||
distance: unit(self.distance, defaults.distance),
|
||||
smoothness: unit(self.smoothness, defaults.smoothness),
|
||||
balance: unit(self.balance, defaults.balance),
|
||||
contrast: unit(self.contrast, defaults.contrast),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for BorderDistanceParameters {
|
||||
/// The reference app's defaults
|
||||
fn default() -> BorderDistanceParameters {
|
||||
BorderDistanceParameters { distance: 0.1, smoothness: 0.0, balance: 0.5, contrast: 0.0 }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// The 3D Distance generator's controls: white around a point across the mesh's bounds, fading to black at the radius
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DistanceParameters {
|
||||
/// The point (Position X, Y and Z) in the mesh's bounds scaled evenly, as the reference's position map is: the longest side spans 0..1, the others are centred on 0.5
|
||||
pub point: [f32; 3],
|
||||
/// How far the gradient reaches, in units of the bounds' longest side ([`DistanceParameters::RADIUS_RANGE`])
|
||||
pub radius: f32,
|
||||
/// Slides the gradient through: 0 all black, 1 all white
|
||||
pub offset: f32,
|
||||
/// Narrows the gradient (0..1; 1 a hard edge)
|
||||
pub contrast: f32,
|
||||
}
|
||||
|
||||
impl DistanceParameters {
|
||||
pub const RADIUS_RANGE: std::ops::RangeInclusive<f32> = 0.0..=1.5;
|
||||
|
||||
/// Every value brought into its range, non-finite ones to the defaults
|
||||
pub fn clamped(self) -> DistanceParameters {
|
||||
let defaults = DistanceParameters::default();
|
||||
let within = |value: f32, default: f32, range: std::ops::RangeInclusive<f32>| {
|
||||
if value.is_finite() { value.clamp(*range.start(), *range.end()) } else { default }
|
||||
};
|
||||
|
||||
DistanceParameters {
|
||||
point: std::array::from_fn(|axis| within(self.point[axis], defaults.point[axis], 0.0..=1.0)),
|
||||
radius: within(self.radius, defaults.radius, DistanceParameters::RADIUS_RANGE),
|
||||
offset: within(self.offset, defaults.offset, 0.0..=1.0),
|
||||
contrast: within(self.contrast, defaults.contrast, 0.0..=1.0),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for DistanceParameters {
|
||||
/// The reference app's defaults: the bounds' centre, radius 1
|
||||
fn default() -> DistanceParameters {
|
||||
DistanceParameters { point: [0.5; 3], radius: 1.0, offset: 0.5, contrast: 0.5 }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// The Dripping Rust generator's controls: rust in the occluded areas, running down in drips
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DrippingRustParameters {
|
||||
/// How far the rust spreads: 0 none, 1 everywhere
|
||||
pub spreading: f32,
|
||||
/// How hard the rust's edge is (0..1; 1 a hard step)
|
||||
pub contrast: f32,
|
||||
/// Softens the rust before it drips (0..1)
|
||||
pub spreading_smoothness: f32,
|
||||
/// How far the drips run (0..1)
|
||||
pub drips_intensity: f32,
|
||||
/// Softens the drips (0..1)
|
||||
pub drips_smoothness: f32,
|
||||
/// How many steps each drip is drawn with ([`DrippingRustParameters::MAX_SAMPLES`] at most)
|
||||
pub drips_samples: u32,
|
||||
/// The axis of the mesh's bounds the drips run down: 0 X, 1 Y, 2 Z
|
||||
pub axis: u8,
|
||||
}
|
||||
|
||||
impl DrippingRustParameters {
|
||||
pub const MAX_SAMPLES: u32 = 32;
|
||||
|
||||
/// Every value brought into its range, non-finite ones to the defaults
|
||||
pub fn clamped(self) -> DrippingRustParameters {
|
||||
let defaults = DrippingRustParameters::default();
|
||||
let unit = |value: f32, default: f32| if value.is_finite() { value.clamp(0.0, 1.0) } else { default };
|
||||
|
||||
DrippingRustParameters {
|
||||
spreading: unit(self.spreading, defaults.spreading),
|
||||
contrast: unit(self.contrast, defaults.contrast),
|
||||
spreading_smoothness: unit(self.spreading_smoothness, defaults.spreading_smoothness),
|
||||
drips_intensity: unit(self.drips_intensity, defaults.drips_intensity),
|
||||
drips_smoothness: unit(self.drips_smoothness, defaults.drips_smoothness),
|
||||
drips_samples: self.drips_samples.min(DrippingRustParameters::MAX_SAMPLES),
|
||||
axis: self.axis.min(2),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for DrippingRustParameters {
|
||||
/// The reference app's defaults
|
||||
fn default() -> DrippingRustParameters {
|
||||
DrippingRustParameters {
|
||||
spreading: 0.5,
|
||||
contrast: 0.5,
|
||||
spreading_smoothness: 0.0,
|
||||
drips_intensity: 0.1,
|
||||
drips_smoothness: 0.05,
|
||||
drips_samples: 32,
|
||||
axis: 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,7 @@ pub struct GeneratorGlobal {
|
||||
|
||||
impl GeneratorGlobal {
|
||||
/// The widest blur, as a radius in texels at [`GeneratorGlobal::BLUR_RESOLUTION`].
|
||||
pub const MAX_BLUR: f32 = 64.0;
|
||||
pub const MAX_BLUR: f32 = 72.0;
|
||||
/// Narrower than this, the balanced range is a hard step.
|
||||
pub const MIN_RANGE: f32 = 1e-6;
|
||||
/// The texels per side the blur radius is measured at (2K).
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// How a color texture becomes one gray value
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum GeneratorGrayscale {
|
||||
/// Halfway between the brightest and the darkest channel
|
||||
Desaturation,
|
||||
/// The channels weighted by how bright the eye sees them
|
||||
Luma,
|
||||
/// The mean of the three channels
|
||||
#[default]
|
||||
Average,
|
||||
Max,
|
||||
Min,
|
||||
Red,
|
||||
Green,
|
||||
Blue,
|
||||
}
|
||||
|
||||
impl GeneratorGrayscale {
|
||||
pub const ALL: [GeneratorGrayscale; 8] = [
|
||||
GeneratorGrayscale::Desaturation,
|
||||
GeneratorGrayscale::Luma,
|
||||
GeneratorGrayscale::Average,
|
||||
GeneratorGrayscale::Max,
|
||||
GeneratorGrayscale::Min,
|
||||
GeneratorGrayscale::Red,
|
||||
GeneratorGrayscale::Green,
|
||||
GeneratorGrayscale::Blue,
|
||||
];
|
||||
|
||||
/// The name the panel shows
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
GeneratorGrayscale::Desaturation => "Desaturation",
|
||||
GeneratorGrayscale::Luma => "Luma",
|
||||
GeneratorGrayscale::Average => "Average",
|
||||
GeneratorGrayscale::Max => "Max",
|
||||
GeneratorGrayscale::Min => "Min",
|
||||
GeneratorGrayscale::Red => "Red channel",
|
||||
GeneratorGrayscale::Green => "Green channel",
|
||||
GeneratorGrayscale::Blue => "Blue channel",
|
||||
}
|
||||
}
|
||||
|
||||
/// The name commands and saved projects use
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
GeneratorGrayscale::Desaturation => "desaturation",
|
||||
GeneratorGrayscale::Luma => "luma",
|
||||
GeneratorGrayscale::Average => "average",
|
||||
GeneratorGrayscale::Max => "max",
|
||||
GeneratorGrayscale::Min => "min",
|
||||
GeneratorGrayscale::Red => "red",
|
||||
GeneratorGrayscale::Green => "green",
|
||||
GeneratorGrayscale::Blue => "blue",
|
||||
}
|
||||
}
|
||||
|
||||
/// The conversion named by its id or its label, in any case
|
||||
pub fn parse(name: &str) -> Option<GeneratorGrayscale> {
|
||||
GeneratorGrayscale::ALL.into_iter().find(|mode| mode.id().eq_ignore_ascii_case(name) || mode.label().eq_ignore_ascii_case(name))
|
||||
}
|
||||
|
||||
/// The gray of `rgb`
|
||||
pub fn gray(self, [red, green, blue]: [f32; 3]) -> f32 {
|
||||
// ITU-R BT.601 weights, the reference's Luma
|
||||
const LUMA: [f32; 3] = [0.299, 0.587, 0.114];
|
||||
match self {
|
||||
GeneratorGrayscale::Desaturation => (red.max(green).max(blue) + red.min(green).min(blue)) * 0.5,
|
||||
GeneratorGrayscale::Luma => red * LUMA[0] + green * LUMA[1] + blue * LUMA[2],
|
||||
GeneratorGrayscale::Average => (red + green + blue) / 3.0,
|
||||
GeneratorGrayscale::Max => red.max(green).max(blue),
|
||||
GeneratorGrayscale::Min => red.min(green).min(blue),
|
||||
GeneratorGrayscale::Red => red,
|
||||
GeneratorGrayscale::Green => green,
|
||||
GeneratorGrayscale::Blue => blue,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::Source;
|
||||
use super::generator_grayscale::GeneratorGrayscale;
|
||||
|
||||
/// The Grayscale Conversion generator's controls: an image turned gray, tiled and rotated across the UV square
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct GrayscaleConversionParameters {
|
||||
/// How the image's color becomes gray
|
||||
pub grayscale: GeneratorGrayscale,
|
||||
/// Shifts the gray darker (below 0.5) or brighter (above 0.5)
|
||||
pub balance: f32,
|
||||
/// Narrows the gray around its middle (0..1; 1 a hard step)
|
||||
pub contrast: f32,
|
||||
/// How many times the image repeats across the UV square ([`GrayscaleConversionParameters::TILE_RANGE`])
|
||||
pub tile: f32,
|
||||
/// Degrees the image turns about the UV square's centre (0..360)
|
||||
pub rotation: f32,
|
||||
/// Turn in quarter turns only, so the image keeps tiling seamlessly
|
||||
pub safe_rotation: bool,
|
||||
/// The image (None: an empty slot, read black)
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub source: Option<Source>,
|
||||
}
|
||||
|
||||
impl GrayscaleConversionParameters {
|
||||
pub const TILE_RANGE: std::ops::RangeInclusive<f32> = 1.0..=16.0;
|
||||
|
||||
/// Every value brought into its range, non-finite ones to the defaults
|
||||
pub fn clamped(self) -> GrayscaleConversionParameters {
|
||||
let defaults = GrayscaleConversionParameters::default();
|
||||
let within = |value: f32, default: f32, range: std::ops::RangeInclusive<f32>| {
|
||||
if value.is_finite() { value.clamp(*range.start(), *range.end()) } else { default }
|
||||
};
|
||||
|
||||
GrayscaleConversionParameters {
|
||||
balance: within(self.balance, defaults.balance, 0.0..=1.0),
|
||||
contrast: within(self.contrast, defaults.contrast, 0.0..=1.0),
|
||||
tile: within(self.tile, defaults.tile, GrayscaleConversionParameters::TILE_RANGE).round(),
|
||||
rotation: within(self.rotation, defaults.rotation, 0.0..=360.0),
|
||||
..self
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for GrayscaleConversionParameters {
|
||||
/// The reference app's defaults
|
||||
fn default() -> GrayscaleConversionParameters {
|
||||
GrayscaleConversionParameters {
|
||||
grayscale: GeneratorGrayscale::Desaturation,
|
||||
balance: 0.5,
|
||||
contrast: 0.0,
|
||||
tile: 1.0,
|
||||
rotation: 0.0,
|
||||
safe_rotation: true,
|
||||
source: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::{
|
||||
BorderDistanceParameters, DistanceParameters, DrippingRustParameters, GeneratorKind, GrayscaleConversionParameters, LinearGradientParameters,
|
||||
UvCheckerParameters, UvRandomColorParameters,
|
||||
};
|
||||
|
||||
/// The controls of a kind that has only the reference's own controls, no earlier model: one variant per kind
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum KindControls {
|
||||
Distance(DistanceParameters),
|
||||
LinearGradient(LinearGradientParameters),
|
||||
BorderDistance(BorderDistanceParameters),
|
||||
Grayscale(GrayscaleConversionParameters),
|
||||
DrippingRust(DrippingRustParameters),
|
||||
UvRandomColor(UvRandomColorParameters),
|
||||
UvChecker(UvCheckerParameters),
|
||||
}
|
||||
|
||||
impl KindControls {
|
||||
/// The reference app's defaults for `kind`, or None for kinds with an earlier model or section, wear or light controls
|
||||
pub fn defaults(kind: GeneratorKind) -> Option<KindControls> {
|
||||
match kind {
|
||||
GeneratorKind::ThreeDDistance => Some(KindControls::Distance(DistanceParameters::default())),
|
||||
GeneratorKind::ThreeDLinearGradient => Some(KindControls::LinearGradient(LinearGradientParameters::default())),
|
||||
GeneratorKind::UvBorderDistance => Some(KindControls::BorderDistance(BorderDistanceParameters::default())),
|
||||
GeneratorKind::GrayscaleConversion => Some(KindControls::Grayscale(GrayscaleConversionParameters::default())),
|
||||
GeneratorKind::DrippingRust => Some(KindControls::DrippingRust(DrippingRustParameters::default())),
|
||||
GeneratorKind::UvRandomColor => Some(KindControls::UvRandomColor(UvRandomColorParameters::default())),
|
||||
GeneratorKind::UvChecker => Some(KindControls::UvChecker(UvCheckerParameters::default())),
|
||||
GeneratorKind::EdgeWear
|
||||
| GeneratorKind::Dirt
|
||||
| GeneratorKind::ThinAreas
|
||||
| GeneratorKind::Curvature
|
||||
| GeneratorKind::AmbientOcclusion
|
||||
| GeneratorKind::Position
|
||||
| GeneratorKind::Direction
|
||||
| GeneratorKind::FiberGlassEdgeWear
|
||||
| GeneratorKind::WorldSpaceNormals => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Every value brought into its range, non-finite ones to the defaults (saved files are not trusted)
|
||||
pub fn clamped(self) -> KindControls {
|
||||
match self {
|
||||
KindControls::Distance(distance) => KindControls::Distance(distance.clamped()),
|
||||
KindControls::LinearGradient(gradient) => KindControls::LinearGradient(gradient.clamped()),
|
||||
KindControls::BorderDistance(border) => KindControls::BorderDistance(border.clamped()),
|
||||
KindControls::Grayscale(grayscale) => KindControls::Grayscale(grayscale.clamped()),
|
||||
KindControls::DrippingRust(rust) => KindControls::DrippingRust(rust.clamped()),
|
||||
KindControls::UvRandomColor(random) => KindControls::UvRandomColor(random.clamped()),
|
||||
KindControls::UvChecker(checker) => KindControls::UvChecker(checker.clamped()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The kind these controls belong to
|
||||
pub fn kind(&self) -> GeneratorKind {
|
||||
match self {
|
||||
KindControls::Distance(_) => GeneratorKind::ThreeDDistance,
|
||||
KindControls::LinearGradient(_) => GeneratorKind::ThreeDLinearGradient,
|
||||
KindControls::BorderDistance(_) => GeneratorKind::UvBorderDistance,
|
||||
KindControls::Grayscale(_) => GeneratorKind::GrayscaleConversion,
|
||||
KindControls::DrippingRust(_) => GeneratorKind::DrippingRust,
|
||||
KindControls::UvRandomColor(_) => GeneratorKind::UvRandomColor,
|
||||
KindControls::UvChecker(_) => GeneratorKind::UvChecker,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::GeneratorKind;
|
||||
|
||||
/// The Light generator's controls: where the light comes from, how its highlight spreads and how it fades across the mesh
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct LightParameters {
|
||||
/// Degrees around the up axis (0 from -X, 90 from +Z)
|
||||
pub horizontal: f32,
|
||||
/// Degrees above the horizon (90 from straight above)
|
||||
pub vertical: f32,
|
||||
/// How narrow the lit area is ([`LightParameters::GLOSSINESS_RANGE`]; 0.5 a plain diffuse falloff)
|
||||
pub glossiness: f32,
|
||||
/// How much the lit area is pushed to white (0..1; 1 every lit texel white)
|
||||
pub highlight_level: f32,
|
||||
/// How much the side away from the light darkens (0..1)
|
||||
pub attenuation: f32,
|
||||
}
|
||||
|
||||
impl LightParameters {
|
||||
pub const ANGLE_RANGE: std::ops::RangeInclusive<f32> = 0.0..=360.0;
|
||||
pub const GLOSSINESS_RANGE: std::ops::RangeInclusive<f32> = 0.0..=0.999;
|
||||
|
||||
/// The reference app's defaults for `kind`, or None for kinds other than Light
|
||||
pub fn defaults(kind: GeneratorKind) -> Option<LightParameters> {
|
||||
(kind == GeneratorKind::Direction).then_some(LightParameters {
|
||||
horizontal: 90.0,
|
||||
vertical: 45.0,
|
||||
glossiness: 0.5,
|
||||
highlight_level: 0.0,
|
||||
attenuation: 0.25,
|
||||
})
|
||||
}
|
||||
|
||||
/// Every value brought into its range, non-finite ones to the defaults
|
||||
pub fn clamped(self) -> LightParameters {
|
||||
let defaults = LightParameters::defaults(GeneratorKind::Direction).unwrap_or(self);
|
||||
let within = |value: f32, default: f32, range: std::ops::RangeInclusive<f32>| {
|
||||
if value.is_finite() { value.clamp(*range.start(), *range.end()) } else { default }
|
||||
};
|
||||
|
||||
LightParameters {
|
||||
horizontal: within(self.horizontal, defaults.horizontal, LightParameters::ANGLE_RANGE),
|
||||
vertical: within(self.vertical, defaults.vertical, LightParameters::ANGLE_RANGE),
|
||||
glossiness: within(self.glossiness, defaults.glossiness, LightParameters::GLOSSINESS_RANGE),
|
||||
highlight_level: within(self.highlight_level, defaults.highlight_level, 0.0..=1.0),
|
||||
attenuation: within(self.attenuation, defaults.attenuation, 0.0..=1.0),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// The 3D Linear Gradient generator's controls: black at the start point, white at the end point, across the mesh's bounds
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct LinearGradientParameters {
|
||||
/// Where the gradient is black, in the mesh's bounds scaled evenly like 3D Distance's point (the longest side spans 0..1, the others are centred on 0.5)
|
||||
pub start: [f32; 3],
|
||||
/// Where the gradient is white
|
||||
pub end: [f32; 3],
|
||||
/// Shifts the gradient darker (below 0.5) or brighter (above 0.5)
|
||||
pub balance: f32,
|
||||
/// Narrows the gradient around its middle (0..1; 1 a hard step)
|
||||
pub contrast: f32,
|
||||
}
|
||||
|
||||
impl LinearGradientParameters {
|
||||
/// Every value brought into its range, non-finite ones to the defaults
|
||||
pub fn clamped(self) -> LinearGradientParameters {
|
||||
let defaults = LinearGradientParameters::default();
|
||||
let unit = |value: f32, default: f32| if value.is_finite() { value.clamp(0.0, 1.0) } else { default };
|
||||
|
||||
LinearGradientParameters {
|
||||
start: std::array::from_fn(|axis| unit(self.start[axis], defaults.start[axis])),
|
||||
end: std::array::from_fn(|axis| unit(self.end[axis], defaults.end[axis])),
|
||||
balance: unit(self.balance, defaults.balance),
|
||||
contrast: unit(self.contrast, defaults.contrast),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for LinearGradientParameters {
|
||||
/// The reference app's defaults: from y 0 to y 1 through the bounds' centre, which spans the mesh when its longest side is vertical
|
||||
fn default() -> LinearGradientParameters {
|
||||
LinearGradientParameters { start: [0.5, 0.0, 0.5], end: [0.5, 1.0, 0.5], balance: 0.5, contrast: 0.0 }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// How a generator's micro details turn the micro height into curvature
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub enum MicroCurvatureType {
|
||||
/// The slope of the height, stronger than Sobel and lifting the whole surface slightly
|
||||
Standard,
|
||||
/// The slope of the height
|
||||
#[default]
|
||||
Sobel,
|
||||
/// The height against blurred copies of itself, softer and wider
|
||||
Smooth,
|
||||
}
|
||||
|
||||
impl MicroCurvatureType {
|
||||
pub const ALL: [MicroCurvatureType; 3] = [MicroCurvatureType::Standard, MicroCurvatureType::Sobel, MicroCurvatureType::Smooth];
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
MicroCurvatureType::Standard => "Standard",
|
||||
MicroCurvatureType::Sobel => "Sobel",
|
||||
MicroCurvatureType::Smooth => "Smooth",
|
||||
}
|
||||
}
|
||||
|
||||
/// The type named `name` (its label, any case)
|
||||
pub fn parse(name: &str) -> Option<MicroCurvatureType> {
|
||||
MicroCurvatureType::ALL.into_iter().find(|kind| kind.label().eq_ignore_ascii_case(name))
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::LayerId;
|
||||
|
||||
/// Painted height read from an anchor point below a generator
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct MicroDetail {
|
||||
/// The anchor point effect id
|
||||
pub anchor: LayerId,
|
||||
/// Strength of the height signal from 0 to 1
|
||||
pub amount: f32,
|
||||
}
|
||||
|
||||
impl MicroDetail {
|
||||
pub const DEFAULT_AMOUNT: f32 = 0.5;
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::micro_curvature_type::MicroCurvatureType;
|
||||
use super::{GeneratorKind, LayerId, Source};
|
||||
use crate::Channel;
|
||||
|
||||
/// A generator's micro details: a height or normal image adding fine curvature or occlusion to its mesh maps
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct MicroDetails {
|
||||
/// Use Micro Details (Curvature and Ambient Occlusion; the wear kinds use them once Micro Height or Micro Normal is on)
|
||||
pub enabled: bool,
|
||||
/// Read the micro height image
|
||||
pub height: bool,
|
||||
/// Read the micro normal image
|
||||
pub normal: bool,
|
||||
pub curvature_type: MicroCurvatureType,
|
||||
/// How strongly the micro details add to the curvature (0..5 on Curvature, 0..1 on the wear kinds)
|
||||
pub curvature_intensity: f32,
|
||||
/// How steep the micro height reads ([`MicroDetails::HEIGHT_INTENSITY_RANGE`])
|
||||
pub height_intensity: f32,
|
||||
/// How far the micro height occludes (0..1)
|
||||
pub ao_radius: f32,
|
||||
/// How deep the micro height reads for occlusion (0..1)
|
||||
pub ao_depth: f32,
|
||||
/// The micro height image (None: an empty slot)
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub height_source: Option<Source>,
|
||||
/// The micro normal image (None: an empty slot)
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub normal_source: Option<Source>,
|
||||
/// Saved as the micro detail before Micro Details (an anchor's height times an amount): a generator still on the earlier model adds it that way, see [`super::Generator::earlier_micro`]
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub earlier: bool,
|
||||
}
|
||||
|
||||
impl MicroDetails {
|
||||
pub const HEIGHT_INTENSITY_RANGE: std::ops::RangeInclusive<f32> = 0.0..=10.0;
|
||||
|
||||
/// Height Details Intensity per unit of an anchor's micro detail amount (0..1): the earlier default amount, 0.5, reads at the default intensity
|
||||
pub const HEIGHT_INTENSITY_PER_AMOUNT: f32 = 2.0;
|
||||
|
||||
/// The micro detail saved before Micro Details, anchor point `anchor`'s height at `amount` (0..1), as Micro Details on a `kind` generator (None for kinds without them): the anchor is the Micro Height, `amount` its intensity
|
||||
pub fn of_anchor(kind: GeneratorKind, anchor: LayerId, amount: f32) -> Option<MicroDetails> {
|
||||
let amount = if amount.is_finite() { amount.clamp(0.0, 1.0) } else { 0.0 };
|
||||
let source = Source::Anchor { anchor, channel: Channel::Height, ramp: Vec::new() };
|
||||
let micro = MicroDetails {
|
||||
enabled: true,
|
||||
height: true,
|
||||
height_intensity: amount * MicroDetails::HEIGHT_INTENSITY_PER_AMOUNT,
|
||||
height_source: Some(source),
|
||||
earlier: true,
|
||||
..MicroDetails::defaults(kind)?
|
||||
};
|
||||
Some(micro.clamped(kind))
|
||||
}
|
||||
|
||||
/// The reference app's defaults for `kind`, or None for kinds without micro details
|
||||
pub fn defaults(kind: GeneratorKind) -> Option<MicroDetails> {
|
||||
let shared = MicroDetails {
|
||||
enabled: false,
|
||||
height: true,
|
||||
normal: true,
|
||||
curvature_type: MicroCurvatureType::Sobel,
|
||||
curvature_intensity: 1.0,
|
||||
height_intensity: 1.0,
|
||||
ao_radius: 0.3,
|
||||
ao_depth: 0.05,
|
||||
height_source: None,
|
||||
normal_source: None,
|
||||
earlier: false,
|
||||
};
|
||||
match kind {
|
||||
GeneratorKind::Curvature | GeneratorKind::AmbientOcclusion => Some(shared),
|
||||
GeneratorKind::EdgeWear | GeneratorKind::Dirt | GeneratorKind::FiberGlassEdgeWear => {
|
||||
Some(MicroDetails { height: false, normal: false, curvature_intensity: 0.5, ..shared })
|
||||
}
|
||||
GeneratorKind::ThinAreas
|
||||
| GeneratorKind::Position
|
||||
| GeneratorKind::Direction
|
||||
| GeneratorKind::WorldSpaceNormals
|
||||
| GeneratorKind::ThreeDDistance
|
||||
| GeneratorKind::ThreeDLinearGradient
|
||||
| GeneratorKind::UvBorderDistance
|
||||
| GeneratorKind::GrayscaleConversion
|
||||
| GeneratorKind::DrippingRust
|
||||
| GeneratorKind::UvRandomColor
|
||||
| GeneratorKind::UvChecker => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a generator of `kind` has the Use Micro Details switch (the wear kinds have only Micro Height and Micro Normal)
|
||||
pub fn has_switch(kind: GeneratorKind) -> bool {
|
||||
matches!(kind, GeneratorKind::Curvature | GeneratorKind::AmbientOcclusion)
|
||||
}
|
||||
|
||||
/// Whether a generator of `kind` adds micro curvature
|
||||
pub fn has_curvature(kind: GeneratorKind) -> bool {
|
||||
MicroDetails::defaults(kind).is_some() && kind != GeneratorKind::AmbientOcclusion
|
||||
}
|
||||
|
||||
/// Whether a generator of `kind` adds micro occlusion
|
||||
pub fn has_occlusion(kind: GeneratorKind) -> bool {
|
||||
MicroDetails::defaults(kind).is_some() && kind != GeneratorKind::Curvature
|
||||
}
|
||||
|
||||
/// The range of the curvature intensity on `kind`
|
||||
pub fn curvature_intensity_range(kind: GeneratorKind) -> std::ops::RangeInclusive<f32> {
|
||||
if kind == GeneratorKind::Curvature { 0.0..=5.0 } else { 0.0..=1.0 }
|
||||
}
|
||||
|
||||
/// Whether the micro details change a generator of `kind`: switched on with a slot to read (an empty slot reads a flat black height, which some curvature types still lift)
|
||||
pub fn in_use(&self, kind: GeneratorKind) -> bool {
|
||||
(self.enabled || !MicroDetails::has_switch(kind)) && (self.height || self.normal)
|
||||
}
|
||||
|
||||
/// The images the micro details read: their height, then their normal
|
||||
pub fn sources(&self) -> impl Iterator<Item = &Source> {
|
||||
self.height_source.iter().chain(self.normal_source.as_ref())
|
||||
}
|
||||
|
||||
/// Every value brought into its range, non-finite ones to the defaults of `kind`
|
||||
pub fn clamped(self, kind: GeneratorKind) -> MicroDetails {
|
||||
let Some(defaults) = MicroDetails::defaults(kind) else { return self };
|
||||
let within = |value: f32, default: f32, range: std::ops::RangeInclusive<f32>| {
|
||||
if value.is_finite() { value.clamp(*range.start(), *range.end()) } else { default }
|
||||
};
|
||||
|
||||
MicroDetails {
|
||||
curvature_intensity: within(self.curvature_intensity, defaults.curvature_intensity, MicroDetails::curvature_intensity_range(kind)),
|
||||
height_intensity: within(self.height_intensity, defaults.height_intensity, MicroDetails::HEIGHT_INTENSITY_RANGE),
|
||||
ao_radius: within(self.ao_radius, defaults.ao_radius, 0.0..=1.0),
|
||||
ao_depth: within(self.ao_depth, defaults.ao_depth, 0.0..=1.0),
|
||||
..self
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::GeneratorKind;
|
||||
use super::axis_blend::AxisBlend;
|
||||
use super::axis_layer::AxisLayer;
|
||||
|
||||
/// The section controls of the Curvature, Ambient Occlusion, Position and World Space Normals generators, applied before the global ones
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SectionParameters {
|
||||
pub invert: bool,
|
||||
/// Blur of the signal ([`SectionParameters::BLUR_RANGE`]; Ambient Occlusion and World Space Normals)
|
||||
pub blur: f32,
|
||||
/// Shifts the signal darker (below 0.5) or brighter (above 0.5); 0.5 leaves it unchanged (not Curvature)
|
||||
pub balance: f32,
|
||||
/// Narrows the signal around its middle (0 unchanged, 1 a hard step)
|
||||
pub contrast: f32,
|
||||
/// Lifts the signal towards white (above 0) or black (below 0) ([`SectionParameters::BRIGHTNESS_RANGE`]; not Ambient Occlusion)
|
||||
pub brightness: f32,
|
||||
/// Right to left, top to bottom and front to back (Position and World Space Normals)
|
||||
pub axes: [AxisLayer; 3],
|
||||
}
|
||||
|
||||
impl SectionParameters {
|
||||
pub const BLUR_RANGE: std::ops::RangeInclusive<f32> = 0.0..=16.0;
|
||||
pub const BRIGHTNESS_RANGE: std::ops::RangeInclusive<f32> = -1.0..=1.0;
|
||||
/// Index in [`SectionParameters::axes`] of each axis
|
||||
pub const RIGHT_TO_LEFT: usize = 0;
|
||||
pub const TOP_TO_BOTTOM: usize = 1;
|
||||
pub const FRONT_TO_BACK: usize = 2;
|
||||
|
||||
/// The reference app's defaults for `kind`, or None for kinds without section controls
|
||||
pub fn defaults(kind: GeneratorKind) -> Option<SectionParameters> {
|
||||
let axis = |weight: f32| AxisLayer { invert: false, blend: AxisBlend::Add, weight };
|
||||
let defaults = SectionParameters { invert: false, blur: 0.0, balance: 0.5, contrast: 0.0, brightness: 0.0, axes: [axis(0.0), axis(1.0), axis(0.0)] };
|
||||
match kind {
|
||||
GeneratorKind::Curvature | GeneratorKind::AmbientOcclusion | GeneratorKind::Position | GeneratorKind::WorldSpaceNormals => Some(defaults),
|
||||
GeneratorKind::EdgeWear
|
||||
| GeneratorKind::Dirt
|
||||
| GeneratorKind::ThinAreas
|
||||
| GeneratorKind::Direction
|
||||
| GeneratorKind::FiberGlassEdgeWear
|
||||
| GeneratorKind::ThreeDDistance
|
||||
| GeneratorKind::ThreeDLinearGradient
|
||||
| GeneratorKind::UvBorderDistance
|
||||
| GeneratorKind::GrayscaleConversion
|
||||
| GeneratorKind::DrippingRust
|
||||
| GeneratorKind::UvRandomColor
|
||||
| GeneratorKind::UvChecker => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a generator of `kind` has the section blur
|
||||
pub fn has_blur(kind: GeneratorKind) -> bool {
|
||||
matches!(kind, GeneratorKind::AmbientOcclusion | GeneratorKind::WorldSpaceNormals)
|
||||
}
|
||||
|
||||
/// Whether a generator of `kind` has the section balance
|
||||
pub fn has_balance(kind: GeneratorKind) -> bool {
|
||||
matches!(kind, GeneratorKind::AmbientOcclusion | GeneratorKind::Position | GeneratorKind::WorldSpaceNormals)
|
||||
}
|
||||
|
||||
/// Whether a generator of `kind` has the section brightness
|
||||
pub fn has_brightness(kind: GeneratorKind) -> bool {
|
||||
matches!(kind, GeneratorKind::Curvature | GeneratorKind::Position | GeneratorKind::WorldSpaceNormals)
|
||||
}
|
||||
|
||||
/// Whether a generator of `kind` combines the three axes of a map
|
||||
pub fn has_axes(kind: GeneratorKind) -> bool {
|
||||
matches!(kind, GeneratorKind::Position | GeneratorKind::WorldSpaceNormals)
|
||||
}
|
||||
|
||||
/// Every value brought into its range, non-finite ones to the defaults of `kind`
|
||||
pub fn clamped(self, kind: GeneratorKind) -> SectionParameters {
|
||||
let defaults = SectionParameters::defaults(kind).unwrap_or(self);
|
||||
let within = |value: f32, default: f32, range: std::ops::RangeInclusive<f32>| {
|
||||
if value.is_finite() { value.clamp(*range.start(), *range.end()) } else { default }
|
||||
};
|
||||
let axes = std::array::from_fn(|index| {
|
||||
let (axis, default) = (self.axes[index], defaults.axes[index]);
|
||||
AxisLayer { weight: within(axis.weight, default.weight, 0.0..=1.0), ..axis }
|
||||
});
|
||||
|
||||
SectionParameters {
|
||||
invert: self.invert,
|
||||
blur: within(self.blur, defaults.blur, SectionParameters::BLUR_RANGE),
|
||||
balance: within(self.balance, defaults.balance, 0.0..=1.0),
|
||||
contrast: within(self.contrast, defaults.contrast, 0.0..=1.0),
|
||||
brightness: within(self.brightness, defaults.brightness, SectionParameters::BRIGHTNESS_RANGE),
|
||||
axes,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// How a generator's texture combines with its signal
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum TextureBlend {
|
||||
/// The texture replaces the signal
|
||||
Normal,
|
||||
/// The texture adds to the signal
|
||||
Add,
|
||||
/// The texture is taken from the signal
|
||||
Subtract,
|
||||
/// The texture multiplies the signal
|
||||
Multiply,
|
||||
/// The texture adds above its middle gray and subtracts below it
|
||||
AddSub,
|
||||
/// The brighter of the texture and the signal
|
||||
Max,
|
||||
/// The darker of the texture and the signal
|
||||
Min,
|
||||
/// The texture darkens the signal's darks and lightens its lights
|
||||
#[default]
|
||||
Overlay,
|
||||
/// The inverse of multiplying the inverses: always lighter
|
||||
Screen,
|
||||
/// A gentler overlay led by the texture
|
||||
SoftLight,
|
||||
}
|
||||
|
||||
impl TextureBlend {
|
||||
pub const ALL: [TextureBlend; 10] = [
|
||||
TextureBlend::Normal,
|
||||
TextureBlend::Add,
|
||||
TextureBlend::Subtract,
|
||||
TextureBlend::Multiply,
|
||||
TextureBlend::AddSub,
|
||||
TextureBlend::Max,
|
||||
TextureBlend::Min,
|
||||
TextureBlend::Overlay,
|
||||
TextureBlend::Screen,
|
||||
TextureBlend::SoftLight,
|
||||
];
|
||||
|
||||
/// The name the panel shows
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
TextureBlend::Normal => "Normal",
|
||||
TextureBlend::Add => "Linear Dodge (Add)",
|
||||
TextureBlend::Subtract => "Subtract",
|
||||
TextureBlend::Multiply => "Multiply",
|
||||
TextureBlend::AddSub => "Add/Sub",
|
||||
TextureBlend::Max => "Max (Lighten)",
|
||||
TextureBlend::Min => "Min (Darken)",
|
||||
TextureBlend::Overlay => "Overlay",
|
||||
TextureBlend::Screen => "Screen",
|
||||
TextureBlend::SoftLight => "Soft light",
|
||||
}
|
||||
}
|
||||
|
||||
/// The name commands and saved projects use
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
TextureBlend::Normal => "normal",
|
||||
TextureBlend::Add => "add",
|
||||
TextureBlend::Subtract => "subtract",
|
||||
TextureBlend::Multiply => "multiply",
|
||||
TextureBlend::AddSub => "addSub",
|
||||
TextureBlend::Max => "max",
|
||||
TextureBlend::Min => "min",
|
||||
TextureBlend::Overlay => "overlay",
|
||||
TextureBlend::Screen => "screen",
|
||||
TextureBlend::SoftLight => "softLight",
|
||||
}
|
||||
}
|
||||
|
||||
/// The blend named by its id or its label, in any case
|
||||
pub fn parse(name: &str) -> Option<TextureBlend> {
|
||||
TextureBlend::ALL.into_iter().find(|blend| blend.id().eq_ignore_ascii_case(name) || blend.label().eq_ignore_ascii_case(name))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::Source;
|
||||
use super::generator_grayscale::GeneratorGrayscale;
|
||||
use super::texture_blend::TextureBlend;
|
||||
|
||||
/// A texture a generator blends over its signal (the reference's Use Texture block): read as gray, adjusted, then blended before the global controls
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct TextureLayer {
|
||||
/// Use Texture: off keeps the settings but leaves the signal as it is
|
||||
pub enabled: bool,
|
||||
/// What the texture reads (None: an empty slot, uniform black)
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub source: Option<Source>,
|
||||
/// How much of the blend shows (0..1)
|
||||
pub opacity: f32,
|
||||
pub invert: bool,
|
||||
pub grayscale: GeneratorGrayscale,
|
||||
pub blend: TextureBlend,
|
||||
/// Repeats across the UV square, about its centre ([`TextureLayer::SCALE_RANGE`])
|
||||
pub scale: f32,
|
||||
/// Narrows the texture around its middle (above 0) or flattens it towards gray (below 0) (−1..1)
|
||||
pub contrast: f32,
|
||||
/// Lifts the texture towards white (above 0) or black (below 0) (−1..1)
|
||||
pub brightness: f32,
|
||||
/// Projected from the world's three axes rather than laid out in UV
|
||||
pub triplanar: bool,
|
||||
/// How sharply the three projections meet ([`TextureLayer::TRIPLANAR_CONTRAST_RANGE`])
|
||||
pub triplanar_contrast: f32,
|
||||
}
|
||||
|
||||
impl Default for TextureLayer {
|
||||
/// The reference app's defaults: off, and at opacity 0 even once turned on
|
||||
fn default() -> Self {
|
||||
TextureLayer {
|
||||
enabled: false,
|
||||
source: None,
|
||||
opacity: 0.0,
|
||||
invert: false,
|
||||
grayscale: GeneratorGrayscale::default(),
|
||||
blend: TextureBlend::default(),
|
||||
scale: 1.0,
|
||||
contrast: 0.0,
|
||||
brightness: 0.0,
|
||||
triplanar: false,
|
||||
triplanar_contrast: 0.5,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TextureLayer {
|
||||
pub const SCALE_RANGE: std::ops::RangeInclusive<f32> = 0.01..=10.0;
|
||||
pub const TRIPLANAR_CONTRAST_RANGE: std::ops::RangeInclusive<f32> = 0.001..=1.0;
|
||||
|
||||
/// Whether the texture changes the signal: turned on with some opacity (an empty slot blends black)
|
||||
pub fn in_use(&self) -> bool {
|
||||
self.enabled && self.opacity > 0.0
|
||||
}
|
||||
|
||||
/// Every value brought into its range, non-finite ones to the defaults
|
||||
pub fn clamped(self) -> TextureLayer {
|
||||
let defaults = TextureLayer::default();
|
||||
let within = |value: f32, default: f32, range: std::ops::RangeInclusive<f32>| {
|
||||
if value.is_finite() { value.clamp(*range.start(), *range.end()) } else { default }
|
||||
};
|
||||
|
||||
TextureLayer {
|
||||
opacity: within(self.opacity, defaults.opacity, 0.0..=1.0),
|
||||
scale: within(self.scale, defaults.scale, TextureLayer::SCALE_RANGE),
|
||||
contrast: within(self.contrast, defaults.contrast, -1.0..=1.0),
|
||||
brightness: within(self.brightness, defaults.brightness, -1.0..=1.0),
|
||||
triplanar_contrast: within(self.triplanar_contrast, defaults.triplanar_contrast, TextureLayer::TRIPLANAR_CONTRAST_RANGE),
|
||||
..self
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// The UV Checker generator's controls: a checker with a grid laid over each UV tile, the UV islands' borders drawn in a color
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct UvCheckerParameters {
|
||||
/// A random light color per UV island instead of the checker color
|
||||
pub random_colors: bool,
|
||||
/// The checker's light squares (linear RGB); the dark ones are a shade of it
|
||||
pub checker_color: [f32; 3],
|
||||
/// Grid tiles across the UV tile, each four checker squares wide ([`UvCheckerParameters::GRID_TILE_RANGE`])
|
||||
pub grid_tile: u32,
|
||||
/// How strongly the grid lines darken the checker (0..1)
|
||||
pub grid_opacity: f32,
|
||||
/// The color of the UV islands' borders (linear RGB)
|
||||
pub border_color: [f32; 3],
|
||||
/// How wide the borders are (0..1; 0.2 is 3 texels of a 2K UV tile)
|
||||
pub border_width: f32,
|
||||
}
|
||||
|
||||
impl UvCheckerParameters {
|
||||
pub const GRID_TILE_RANGE: std::ops::RangeInclusive<u32> = 1..=24;
|
||||
|
||||
/// Every value brought into its range, non-finite ones to the defaults
|
||||
pub fn clamped(self) -> UvCheckerParameters {
|
||||
let defaults = UvCheckerParameters::default();
|
||||
let unit = |value: f32, default: f32| if value.is_finite() { value.clamp(0.0, 1.0) } else { default };
|
||||
|
||||
UvCheckerParameters {
|
||||
checker_color: std::array::from_fn(|channel| unit(self.checker_color[channel], defaults.checker_color[channel])),
|
||||
grid_tile: self.grid_tile.clamp(*UvCheckerParameters::GRID_TILE_RANGE.start(), *UvCheckerParameters::GRID_TILE_RANGE.end()),
|
||||
grid_opacity: unit(self.grid_opacity, defaults.grid_opacity),
|
||||
border_color: std::array::from_fn(|channel| unit(self.border_color[channel], defaults.border_color[channel])),
|
||||
border_width: unit(self.border_width, defaults.border_width),
|
||||
..self
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for UvCheckerParameters {
|
||||
/// The reference app's defaults: a light cyan checker (#5BDDFF), red borders
|
||||
fn default() -> UvCheckerParameters {
|
||||
UvCheckerParameters {
|
||||
random_colors: false,
|
||||
checker_color: [0.104_616, 0.723_055, 1.0],
|
||||
grid_tile: 16,
|
||||
grid_opacity: 0.5,
|
||||
border_color: [1.0, 0.0, 0.0],
|
||||
border_width: 0.2,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// The UV Random Color generator's controls: one random value per UV island, picked at random or along a gradient
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct UvRandomColorParameters {
|
||||
/// Pick each island's color along [`UvRandomColorParameters::gradient`] instead of at random
|
||||
pub custom_gradient: bool,
|
||||
/// The gradient's colors (linear RGB, [`UvRandomColorParameters::MAX_GRADIENT_COLORS`] at most)
|
||||
pub gradient: Vec<[f32; 3]>,
|
||||
/// Each color's place on the gradient (0..1); colors past the end are evenly spaced (projects saved before have none)
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub positions: Vec<f32>,
|
||||
/// How many of the colors the gradient uses (all of them where None): the rest are kept for when the count grows again
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub quantity: Option<u8>,
|
||||
}
|
||||
|
||||
impl UvRandomColorParameters {
|
||||
pub const MAX_GRADIENT_COLORS: usize = 16;
|
||||
|
||||
/// The fewest colors the gradient's count goes down to
|
||||
pub const MIN_QUANTITY: u8 = 2;
|
||||
|
||||
/// Every color brought into 0..1 (non-finite components black), at most [`UvRandomColorParameters::MAX_GRADIENT_COLORS`] of them, and at least one; places into 0..1, one per color at most
|
||||
pub fn clamped(self) -> UvRandomColorParameters {
|
||||
let unit = |value: f32| if value.is_finite() { value.clamp(0.0, 1.0) } else { 0.0 };
|
||||
let gradient: Vec<[f32; 3]> = self.gradient.into_iter().take(UvRandomColorParameters::MAX_GRADIENT_COLORS).map(|color| color.map(unit)).collect();
|
||||
let gradient = if gradient.is_empty() { UvRandomColorParameters::default().gradient } else { gradient };
|
||||
let positions = self.positions.into_iter().take(gradient.len()).map(unit).collect();
|
||||
let quantity = self.quantity.map(|count| count.clamp(UvRandomColorParameters::MIN_QUANTITY, UvRandomColorParameters::MAX_GRADIENT_COLORS as u8));
|
||||
UvRandomColorParameters { gradient, positions, quantity, ..self }
|
||||
}
|
||||
|
||||
/// The colors the gradient uses: the first [`UvRandomColorParameters::quantity`] of them (all of them where it has none)
|
||||
pub fn used_colors(&self) -> &[[f32; 3]] {
|
||||
let used = self.quantity.map_or(self.gradient.len(), usize::from).min(self.gradient.len());
|
||||
self.gradient.get(..used).unwrap_or(&self.gradient)
|
||||
}
|
||||
|
||||
/// Each used color's place on the gradient, evenly spaced where it has none
|
||||
pub fn used_positions(&self) -> Vec<f32> {
|
||||
let used = self.used_colors().len();
|
||||
let last = used.saturating_sub(1).max(1) as f32;
|
||||
(0..used).map(|index| self.positions.get(index).copied().unwrap_or(index as f32 / last)).collect()
|
||||
}
|
||||
|
||||
/// The gradient's color at `t` (linear blend)
|
||||
pub fn at(&self, t: f32) -> Option<[f32; 3]> {
|
||||
let colors = self.used_colors();
|
||||
|
||||
// An evenly spaced gradient (projects saved before) takes the path it took then, so it renders bit for bit as before
|
||||
if self.positions.is_empty() { super::gradient(colors, t) } else { crate::gradient_input::ramp(colors, &self.positions, true, t) }
|
||||
}
|
||||
|
||||
/// Use the first `wanted` colors: an evenly spaced gradient keeps its places from now on, and each added color starts at 1 as the gradient's color there
|
||||
pub fn set_quantity(&mut self, wanted: u8) {
|
||||
let wanted = wanted.clamp(UvRandomColorParameters::MIN_QUANTITY, UvRandomColorParameters::MAX_GRADIENT_COLORS as u8);
|
||||
|
||||
// Preserve the implicit positions of visible stops and the stored positions of hidden stops
|
||||
let even = self.used_positions();
|
||||
let placed = self.positions.len();
|
||||
self.positions.extend(even.into_iter().skip(placed));
|
||||
let fill = self.at(1.0).unwrap_or([1.0; 3]);
|
||||
let wanted_len = usize::from(wanted);
|
||||
if self.gradient.len() < wanted_len {
|
||||
self.gradient.resize(wanted_len, fill);
|
||||
}
|
||||
if self.positions.len() < wanted_len {
|
||||
self.positions.resize(wanted_len, 1.0);
|
||||
}
|
||||
self.quantity = Some(wanted);
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for UvRandomColorParameters {
|
||||
fn default() -> UvRandomColorParameters {
|
||||
UvRandomColorParameters { custom_gradient: false, gradient: vec![[0.0; 3], [1.0; 3]], positions: Vec::new(), quantity: None }
|
||||
}
|
||||
}
|
||||
Loaded 100 of 254 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user