perf(paint): key the pattern cache on normalised levels, make the eviction test independent

The key now uses the brightness and contrast values Texture::level uses (clamped, non-finite as 0, -0.0 as 0.0), so equal levels share one entry. The cache logic moves into a PatternCache struct so the eviction test runs on its own instance instead of the shared static.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
vangel76andClaude Sonnet 5.5 committed 2026-11-04 01:51:30 +01:00
1 parent 640006e794
commit 0d69d40c6b
1 file changed
+80 -32
+80 -32
View File
@@ -31,41 +31,65 @@ struct PatternEntry {
image: Arc<PatternImage>,
}
static PATTERNS: Mutex<Vec<PatternEntry>> = Mutex::new(Vec::new());
/// The entries, least recently used first.
struct PatternCache(Vec<PatternEntry>);
impl PatternCache {
const fn new() -> Self {
Self(Vec::new())
}
/// The image cached for `key`, which is then the most recently used entry.
fn get(&mut self, key: &PatternKey) -> Option<Arc<PatternImage>> {
let i = self.0.iter().position(|e| e.key == *key)?;
let e = self.0.remove(i);
let image = Arc::clone(&e.image);
self.0.push(e);
Some(image)
}
/// Caches `image` for `key` (unless it is too big) and evicts the oldest entries past the limits.
fn insert(&mut self, key: PatternKey, image: &Arc<PatternImage>) {
if image.data.len() * 4 > PATTERN_MAX_BYTES / 2 {
return;
}
// Another thread may have built the same key meanwhile: keep its image, but it was just asked for.
match self.0.iter().position(|e| e.key == key) {
Some(i) => {
let e = self.0.remove(i);
self.0.push(e);
}
None => self.0.push(PatternEntry { key, image: Arc::clone(image) }),
}
let bytes = |e: &PatternEntry| e.image.data.len() * 4;
while self.0.len() > PATTERN_MAX_ENTRIES || self.0.iter().map(bytes).sum::<usize>() > PATTERN_MAX_BYTES {
self.0.remove(0);
}
}
}
static PATTERNS: Mutex<PatternCache> = Mutex::new(PatternCache::new());
/// The key of `(style, size, seed)` with `t`'s levels. Brightness and contrast are keyed on the values
/// [`Texture::level`] uses (clamped, non-finite as 0, `-0.0` as `0.0`), so equal levels share an entry.
fn pattern_key(style: PatternStyle, size: u32, seed: u32, t: &Texture) -> PatternKey {
let level_bits = |v: f32| (if v.is_finite() { v.clamp(-1.0, 1.0) + 0.0 } else { 0.0 }).to_bits();
PatternKey { style, size: size.clamp(8, 1024), seed, brightness: level_bits(t.brightness), contrast: level_bits(t.contrast), invert: t.invert }
}
/// The procedural pattern `(style, size, seed)` with `t`'s levels applied, from the cache when it
/// was built recently.
pub fn procedural_pattern(style: PatternStyle, size: u32, seed: u32, t: &Texture) -> Arc<PatternImage> {
let key = PatternKey { style, size: size.clamp(8, 1024), seed, brightness: t.brightness.to_bits(), contrast: t.contrast.to_bits(), invert: t.invert };
{
let mut cache = PATTERNS.lock().unwrap_or_else(PoisonError::into_inner);
if let Some(i) = cache.iter().position(|e| e.key == key) {
let e = cache.remove(i);
let image = Arc::clone(&e.image);
cache.push(e);
return image;
}
let key = pattern_key(style, size, seed, t);
if let Some(image) = PATTERNS.lock().unwrap_or_else(PoisonError::into_inner).get(&key) {
return image;
}
let mut img = crate::procedural::pattern(style, size, seed);
for v in &mut img.data {
*v = t.level(*v);
}
let image = Arc::new(img);
let bytes = |e: &PatternEntry| e.image.data.len() * 4;
if image.data.len() * 4 <= PATTERN_MAX_BYTES / 2 {
let mut cache = PATTERNS.lock().unwrap_or_else(PoisonError::into_inner);
// Another thread may have built the same key meanwhile: keep its image, but it was just asked for.
match cache.iter().position(|e| e.key == key) {
Some(i) => {
let e = cache.remove(i);
cache.push(e);
}
None => cache.push(PatternEntry { key, image: Arc::clone(&image) }),
}
while cache.len() > PATTERN_MAX_ENTRIES || cache.iter().map(bytes).sum::<usize>() > PATTERN_MAX_BYTES {
cache.remove(0);
}
}
PATTERNS.lock().unwrap_or_else(PoisonError::into_inner).insert(key, &image);
image
}
@@ -98,16 +122,40 @@ mod tests {
}
}
/// The cache holds a few entries: the oldest one goes first. Seeds are used by no other test, so
/// no hit can refresh `first`.
/// The cache holds a few entries: the oldest one goes first. Runs on a cache this test owns, so
/// no other test can evict or refresh an entry.
#[test]
fn pattern_cache_evicts_the_oldest_entry_past_its_limit() {
let base = Texture::default();
let first = procedural_pattern(PatternStyle::Noise, 16, 90_001, &base);
assert!(Arc::ptr_eq(&first, &procedural_pattern(PatternStyle::Noise, 16, 90_001, &base)));
for seed in 90_002..90_002 + PATTERN_MAX_ENTRIES as u32 {
procedural_pattern(PatternStyle::Noise, 16, seed, &base);
let mut cache = PatternCache::new();
let key = |seed| pattern_key(PatternStyle::Noise, 16, seed, &base);
let image = |seed| Arc::new(crate::procedural::pattern(PatternStyle::Noise, 16, seed));
let first = image(0);
cache.insert(key(0), &first);
assert!(Arc::ptr_eq(&first, &cache.get(&key(0)).unwrap()));
for seed in 1..=PATTERN_MAX_ENTRIES as u32 {
cache.insert(key(seed), &image(seed));
}
assert!(!Arc::ptr_eq(&first, &procedural_pattern(PatternStyle::Noise, 16, 90_001, &base)));
assert!(cache.get(&key(0)).is_none());
assert!(cache.get(&key(1)).is_some());
}
#[test]
fn pattern_cache_shares_an_entry_between_equal_levels() {
let tex = |brightness, contrast| Texture { brightness, contrast, ..Texture::default() };
let pairs = [
(tex(2.0, 0.0), tex(1.0, 0.0)),
(tex(-7.5, 0.0), tex(-1.0, 0.0)),
(tex(0.0, 3.0), tex(0.0, 1.0)),
(tex(f32::NAN, 0.0), tex(0.0, 0.0)),
(tex(0.0, f32::INFINITY), tex(0.0, 0.0)),
(tex(-0.0, -0.0), tex(0.0, 0.0)),
];
for (a, b) in pairs {
assert!(pattern_key(PatternStyle::Noise, 64, 5, &a) == pattern_key(PatternStyle::Noise, 64, 5, &b));
let (ia, ib) = (procedural_pattern(PatternStyle::Noise, 64, 5, &a), procedural_pattern(PatternStyle::Noise, 64, 5, &b));
assert_eq!(ia.data, ib.data);
}
assert!(pattern_key(PatternStyle::Noise, 64, 5, &tex(0.5, 0.0)) != pattern_key(PatternStyle::Noise, 64, 5, &tex(1.0, 0.0)));
}
}