Generators: whole-map fields keyed by a coverage hash taken once per evaluation and by each mesh map's bake size

The field cache read every 31st texel's triangle on each lookup (once
per tile plan) and could miss an edit between samples; the evaluation
now hashes every texel once, on first use. A mesh map's bake size joins
its key (one allocation read as another layout), and a hit moves to the
most recently used end.
This commit is contained in:
Rebornim committed 2026-11-25 07:12:15 +00:00
1 parent eaf3ad1c2a
commit 44b1bc0273
8 files changed
+140 -32

No files matched your search

+2 -3
View File
@@ -36,8 +36,7 @@ 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, rust: &DrippingRustParameters, seed: u32) -> Arc<Vec<f32>> {
let occlusion = inp.baked.maps.get(&BakedMap::AmbientOcclusion);
pub(crate) fn rust_field(inp: &Inputs, coverage: u64, rust: &DrippingRustParameters, seed: u32) -> Arc<Vec<f32>> {
let settings = vec![
rust.spreading_smoothness.to_bits(),
rust.drips_intensity.to_bits(),
@@ -46,7 +45,7 @@ pub(crate) fn rust_field(inp: &Inputs, rust: &DrippingRustParameters, seed: u32)
u32::from(rust.axis),
seed,
];
CACHE.get_or_build(inp, &occlusion.into_iter().collect::<Vec<_>>(), settings, |block| build(inp, rust, seed, block))
CACHE.get_or_build(inp, coverage, &[BakedMap::AmbientOcclusion], settings, |block| build(inp, rust, seed, block))
}
/// The value at a working texel: the rust spread and contrasted
+75 -4
View File
@@ -2419,7 +2419,7 @@ fn compares_this_layer(kind: &EffectKind) -> bool {
}
/// Build the curvature detail sizes every visible generator of `layers` reads, once, before tiles composite in parallel.
fn prepare_curvature_sizes(inp: &Inputs, layers: &[LayerId]) {
fn prepare_curvature_sizes(inp: &EvaluationInputs, layers: &[LayerId]) {
let visible = layers.iter().filter(|id| inp.project.layers.get(id).is_some_and(|layer| layer.visible));
let masks = visible.filter_map(|id| layer_mask(inp.project, *id)).filter(|mask| mask.enabled);
prepare_mask_curvature_sizes(inp, masks);
@@ -2506,7 +2506,7 @@ fn wear_parameters(generator: &Generator) -> Option<WearParameters> {
}
/// Build the curvature detail sizes the visible generators of `masks` read, once, before tiles composite in parallel.
fn prepare_mask_curvature_sizes<'a>(inp: &Inputs, masks: impl Iterator<Item = &'a Mask>) {
fn prepare_mask_curvature_sizes<'a>(inp: &EvaluationInputs, masks: impl Iterator<Item = &'a Mask>) {
let mut needed = [false; LEVEL_RADII.len()];
for effect in masks.flat_map(|mask| &mask.effects).filter(|effect| effect.visible) {
if let EffectKind::Generator(generator) = &effect.kind {
@@ -2516,7 +2516,7 @@ fn prepare_mask_curvature_sizes<'a>(inp: &Inputs, masks: impl Iterator<Item = &'
Some(KindControls::BorderDistance(_) | KindControls::DrippingRust(_) | KindControls::UvRandomColor(_) | KindControls::UvChecker(_))
);
if generator.micro_in_use().is_some() || whole_map {
GeneratorMaps::of(inp, generator, &curvature_sizes_in_use(generator));
GeneratorMaps::of(inp, generator, &curvature_sizes_in_use(generator), || inp.coverage_identity());
continue;
}
for (slot, in_use) in needed.iter_mut().zip(curvature_sizes_in_use(generator)) {
@@ -2562,7 +2562,7 @@ fn effect_plans<'a>(
None => (inp.pixels.masks.get(&effect.id), PaintTarget::Mask(effect.id)),
};
let maps = match &effect.kind {
EffectKind::Generator(generator) => GeneratorMaps::of(inp, generator, &curvature_sizes_in_use(generator)),
EffectKind::Generator(generator) => GeneratorMaps::of(inp, generator, &curvature_sizes_in_use(generator), || inp.coverage_identity()),
_ => GeneratorMaps::default(),
};
let (depth, covers_all, projection) = match &effect.kind {
@@ -7368,6 +7368,77 @@ soft {soft:?}"
assert_eq!(builds.get(), 2, "a smaller working atlas builds them again");
}
/// Builds a field cache made: the counter goes up with each build
fn counted_build(builds: &std::cell::Cell<usize>) -> impl FnOnce((u32, u32)) -> Vec<f32> + '_ {
move |_| {
builds.set(builds.get() + 1);
vec![0.0; 4]
}
}
#[test]
fn a_whole_map_field_is_built_again_when_its_mesh_map_is_read_at_another_bake_size() {
let cache = crate::field_cache::FieldCache::new();
let builds = std::cell::Cell::new(0);
let mut fixture = fixture();
let occlusion = Arc::new(vec![0.5; 16]);
let images = ImageStore::default();
for resolution in [4, 4, 8] {
fixture.baked = BakedMaps { resolution, maps: [(BakedMap::AmbientOcclusion, occlusion.clone())].into() };
let inputs = inputs(&fixture, &images, None);
cache.get_or_build(
&inputs,
crate::field_cache::coverage_identity(&fixture.gbuf),
&[BakedMap::AmbientOcclusion],
Vec::new(),
counted_build(&builds),
);
}
assert_eq!(builds.get(), 2, "4 × 4 reuses its field; the same map read as 8 × 2 builds another");
}
#[test]
fn a_whole_map_field_is_built_again_after_any_texel_of_its_coverage_changes() {
let cache = crate::field_cache::FieldCache::new();
let builds = std::cell::Cell::new(0);
let mut fixture = fixture();
let images = ImageStore::default();
let build_on = |fixture: &Fixture| {
let inputs = inputs(fixture, &images, None);
cache.get_or_build(&inputs, crate::field_cache::coverage_identity(&fixture.gbuf), &[], Vec::new(), counted_build(&builds));
};
build_on(&fixture);
build_on(&fixture);
// The second texel, in place: the same allocation, one triangle different
fixture.gbuf.tri[1] = if fixture.gbuf.tri[1] == NO_TRI { 0 } else { NO_TRI };
build_on(&fixture);
assert_eq!(builds.get(), 2);
}
#[test]
fn a_whole_map_field_read_again_outlives_fields_built_before_it() {
const FIELDS_KEPT: u32 = 8;
let cache = crate::field_cache::FieldCache::new();
let builds = std::cell::Cell::new(0);
let fixture = fixture();
let images = ImageStore::default();
let inputs = inputs(&fixture, &images, None);
let coverage = crate::field_cache::coverage_identity(&fixture.gbuf);
let field = |settings: u32| {
cache.get_or_build(&inputs, coverage, &[], vec![settings], counted_build(&builds));
};
(0..FIELDS_KEPT).for_each(field);
field(0);
field(FIELDS_KEPT);
let built = builds.get();
field(0);
assert_eq!(builds.get(), built, "the field read again stays when a newer one pushes the oldest out");
}
#[test]
fn a_micro_detail_saved_before_micro_details_renders_as_saved_on_the_earlier_model() {
const SAVED_AMOUNT: f32 = 0.25;
@@ -22,6 +22,7 @@ pub(super) struct EvaluationInputs<'a> {
instance_draws: OnceLock<HashMap<(usize, LayerId), usize>>,
depth_maps: Mutex<Vec<ViewDepth>>,
gradients: Mutex<HashMap<usize, Arc<PreparedGradient>>>,
coverage: OnceLock<u64>,
}
impl<'a> EvaluationInputs<'a> {
@@ -33,9 +34,15 @@ impl<'a> EvaluationInputs<'a> {
instance_draws: OnceLock::new(),
depth_maps: Mutex::new(Vec::new()),
gradients: Mutex::default(),
coverage: OnceLock::new(),
}
}
/// The working layout's coverage identity, hashed on first use only: the whole-map generator fields' cache reads it ([`crate::field_cache::coverage_identity`])
pub(super) fn coverage_identity(&self) -> u64 {
*self.coverage.get_or_init(|| crate::field_cache::coverage_identity(self.inputs.gbuf))
}
pub(super) fn environment(&self) -> EnvironmentSh {
if let Some(environment) = self.environment.get() {
return *environment;
+36 -8
View File
@@ -1,5 +1,9 @@
use std::sync::{Arc, Mutex};
use rayon::prelude::*;
use texturecraft_core::BakedMap;
use texturecraft_geom::UvGBuffer;
use crate::eval::Inputs;
use crate::field_cache_key::FieldCacheKey;
use crate::working_field::working_block;
@@ -8,8 +12,19 @@ use crate::working_field::working_block;
const CACHE_ENTRIES: usize = 8;
const CACHE_BYTES: usize = 256 << 20;
/// Texels between the samples a layout's fingerprint reads: dense enough to tell UV edits apart, sparse enough to read once per tile
const FINGERPRINT_STRIDE: usize = 31;
/// Texels hashed together before their hashes are combined, so the coverage hashes in parallel
const COVERAGE_CHUNK_TEXELS: usize = 1 << 16;
/// The 64-bit FNV prime, spreading each step of the coverage hash over every bit
const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;
/// The identity of `gbuf`'s coverage: its size and the triangle under every texel, hashed (read once per evaluation, as it reads every texel)
pub(crate) fn coverage_identity(gbuf: &UvGBuffer) -> u64 {
let chunk_hash =
|chunk: &[u32]| chunk.iter().fold(chunk.len() as u64, |hash, triangle| (hash.rotate_left(5) ^ u64::from(*triangle)).wrapping_mul(FNV_PRIME));
let chunks: Vec<u64> = gbuf.tri.par_chunks(COVERAGE_CHUNK_TEXELS).map(chunk_hash).collect();
chunks.iter().fold((u64::from(gbuf.width) << 32) | u64::from(gbuf.height), |hash, chunk| (hash.rotate_left(7) ^ chunk).wrapping_mul(FNV_PRIME))
}
/// Built fields by what they were built from, most recently used last
pub(crate) struct FieldCache {
@@ -21,26 +36,39 @@ impl FieldCache {
FieldCache { entries: Mutex::new(Vec::new()) }
}
/// The field of `inp`'s working layout reading `maps` with `settings`, built by `build` (given the UV tile block) when missing, outside the lock: the build runs parallel work
pub(crate) fn get_or_build(&self, inp: &Inputs, maps: &[&Arc<Vec<f32>>], settings: Vec<u32>, build: impl FnOnce((u32, u32)) -> Vec<f32>) -> Arc<Vec<f32>> {
/// The field of `inp`'s working layout (its coverage: [`coverage_identity`]) reading the baked `maps` with `settings`, built by `build` (given the UV tile block) when missing, outside the lock: the build runs parallel work
pub(crate) fn get_or_build(
&self,
inp: &Inputs,
coverage: u64,
maps: &[BakedMap],
settings: Vec<u32>,
build: impl FnOnce((u32, u32)) -> Vec<f32>,
) -> Arc<Vec<f32>> {
let gbuf = inp.gbuf;
let block = working_block(inp);
let read = maps.iter().filter_map(|map| inp.baked.maps.get(map).map(|data| (Arc::downgrade(data), (inp.baked.resolution, inp.baked.height(*map)))));
let key = FieldCacheKey {
layout: gbuf.tri.as_ptr() as usize,
size: (gbuf.width, gbuf.height),
fingerprint: gbuf.tri.iter().step_by(FINGERPRINT_STRIDE).fold(gbuf.tri.len() as u64, |hash, tri| hash.rotate_left(5) ^ u64::from(*tri)),
coverage,
block,
scales: inp.block_scales.clone(),
positions: (inp.mesh.positions.as_ptr() as usize, inp.mesh.positions.len()),
uvs: (inp.mesh.uvs.as_ptr() as usize, inp.mesh.uvs.len()),
maps: maps.iter().map(|map| Arc::downgrade(map)).collect(),
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.strong_count() > 0));
entries.iter().find(|(cached, _)| *cached == key).map(|(_, field)| field.clone())
entries.retain(|(key, _)| key.maps.iter().all(|(map, _)| map.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;
+8 -5
View File
@@ -2,28 +2,31 @@ use std::sync::Weak;
use texturecraft_core::BlockScales;
/// What a field was built from: the working layout (the g-buffer's address, size, coverage fingerprint, UV tile block and tile scales), the mesh's positions and UVs, the mesh maps it reads and its settings' bits
/// What a field was built from: the working layout (the g-buffer's address, size, coverage, UV tile block and tile scales), the mesh's positions and UVs, the mesh maps it reads and its settings' bits
#[derive(Clone)]
pub(crate) struct FieldCacheKey {
pub(crate) layout: usize,
pub(crate) size: (u32, u32),
pub(crate) fingerprint: u64,
/// Every texel's triangle, hashed: [`crate::field_cache::coverage_identity`]
pub(crate) coverage: u64,
pub(crate) block: (u32, u32),
pub(crate) scales: BlockScales,
/// The mesh's positions and UVs, each by address and length: a UV edit changes island fields
pub(crate) positions: (usize, usize),
pub(crate) uvs: (usize, usize),
pub(crate) maps: Vec<Weak<Vec<f32>>>,
/// The mesh maps it samples, each with the size it was baked at: one allocation read as another layout reads other texels
pub(crate) maps: Vec<(Weak<Vec<f32>>, (u32, u32))>,
pub(crate) settings: Vec<u32>,
}
impl PartialEq for FieldCacheKey {
fn eq(&self, other: &FieldCacheKey) -> bool {
let same_maps = self.maps.len() == other.maps.len() && self.maps.iter().zip(&other.maps).all(|(a, b)| a.strong_count() > 0 && a.ptr_eq(b));
let same_maps = self.maps.len() == other.maps.len()
&& self.maps.iter().zip(&other.maps).all(|((a, a_size), (b, b_size))| a.strong_count() > 0 && a.ptr_eq(b) && a_size == b_size);
same_maps
&& self.layout == other.layout
&& self.size == other.size
&& self.fingerprint == other.fingerprint
&& self.coverage == other.coverage
&& self.block == other.block
&& self.scales == other.scales
&& self.positions == other.positions
+6 -6
View File
@@ -27,8 +27,8 @@ pub(crate) struct GeneratorMaps {
}
impl GeneratorMaps {
/// The maps `generator` reads, with the detail sizes `needed` marks (one flag per blurred size)
pub fn of(inp: &Inputs, generator: &Generator, needed: &[bool]) -> GeneratorMaps {
/// The maps `generator` reads, with the detail sizes `needed` marks (one flag per blurred size); `coverage` gives the working layout's coverage identity for whole-map fields
pub fn of(inp: &Inputs, generator: &Generator, needed: &[bool], coverage: impl Fn() -> 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));
@@ -39,10 +39,10 @@ impl GeneratorMaps {
};
let controls = generator.kind_controls();
let field = match &controls {
Some(KindControls::BorderDistance(border)) => Some(border_gradient(inp, border)),
Some(KindControls::DrippingRust(rust)) => Some(rust_field(inp, rust, generator.seed)),
Some(KindControls::UvRandomColor(random)) => Some(random_color_field(inp, random, generator.seed)),
Some(KindControls::UvChecker(checker)) => Some(checker_field(inp, checker, generator.seed)),
Some(KindControls::BorderDistance(border)) => Some(border_gradient(inp, coverage(), border)),
Some(KindControls::DrippingRust(rust)) => Some(rust_field(inp, coverage(), rust, generator.seed)),
Some(KindControls::UvRandomColor(random)) => Some(random_color_field(inp, coverage(), random, generator.seed)),
Some(KindControls::UvChecker(checker)) => Some(checker_field(inp, coverage(), checker, generator.seed)),
_ => None,
};
GeneratorMaps { sizes, micro_curvature, micro_occlusion, field, controls: controls.map(Arc::new) }
+2 -2
View File
@@ -18,8 +18,8 @@ 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, border: &BorderDistanceParameters) -> Arc<Vec<f32>> {
CACHE.get_or_build(inp, &[], vec![border.distance.to_bits(), border.smoothness.to_bits()], |block| build(inp, border, block))
pub(crate) fn border_gradient(inp: &Inputs, coverage: u64, border: &BorderDistanceParameters) -> Arc<Vec<f32>> {
CACHE.get_or_build(inp, coverage, &[], 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
+4 -4
View File
@@ -17,12 +17,12 @@ 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, random: &UvRandomColorParameters, seed: u32) -> Arc<Vec<f32>> {
pub(crate) fn random_color_field(inp: &Inputs, coverage: u64, random: &UvRandomColorParameters, seed: u32) -> Arc<Vec<f32>> {
let mut settings = vec![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, &[], settings, |_| {
CACHE.get_or_build(inp, coverage, &[], 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()
@@ -73,10 +73,10 @@ 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, checker: &UvCheckerParameters, seed: u32) -> Arc<Vec<f32>> {
pub(crate) fn checker_field(inp: &Inputs, coverage: u64, checker: &UvCheckerParameters, seed: u32) -> Arc<Vec<f32>> {
let mut settings = vec![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, &[], settings, |block| {
CACHE.get_or_build(inp, coverage, &[], 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() };