| ... | @@ -1,9 +1,11 @@ | ... | @@ -1,9 +1,11 @@ |
| 1 | //! Content-hashed GPU texture cache with hard VRAM budget, LRU eviction, | 1 | //! Content-hashed GPU texture cache with hard VRAM budget, LRU eviction, |
| 2 | //! and surgical cache-busting modes for profiling and playback verification. | 2 | //! VRAM-budgeted texture pooling, per-node profiling hooks, and surgical |
| | 3 | //! cache-busting modes for profiling and playback verification. |
| 3 | | 4 | |
| 4 | use model::{BitDepth, NodeId}; | 5 | use crate::profile::{FrameProfile, ProfileRecorder}; |
| 5 | use std::collections::{HashMap, HashSet}; | 6 | use model::{BitDepth, Comp, NodeId}; |
| 6 | use std::sync::Arc; | 7 | use std::collections::{HashMap, HashSet, VecDeque}; |
| | 8 | use std::sync::{Arc, Mutex}; |
| 7 | | 9 | |
| 8 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] | 10 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 9 | pub enum CacheMode { | 11 | pub enum CacheMode { |
| ... | @@ -35,6 +37,28 @@ pub struct CachedTexture { | ... | @@ -35,6 +37,28 @@ pub struct CachedTexture { |
| 35 | pub bytes: u64, | 37 | pub bytes: u64, |
| 36 | } | 38 | } |
| 37 | | 39 | |
| | 40 | fn depth_for_format(format: wgpu::TextureFormat) -> BitDepth { |
| | 41 | match format { |
| | 42 | wgpu::TextureFormat::Rgba16Float => BitDepth::Float16, |
| | 43 | wgpu::TextureFormat::Rgba32Float => BitDepth::Float32, |
| | 44 | _ => BitDepth::Int8, |
| | 45 | } |
| | 46 | } |
| | 47 | |
| | 48 | fn bytes_per_pixel(format: wgpu::TextureFormat) -> u64 { |
| | 49 | match format { |
| | 50 | wgpu::TextureFormat::Rgba32Float => 16, |
| | 51 | wgpu::TextureFormat::Rgba16Float => 8, |
| | 52 | _ => u64::from(format.block_copy_size(None).unwrap_or(4)), |
| | 53 | } |
| | 54 | } |
| | 55 | |
| | 56 | fn texture_bytes(size: [u32; 2], format: wgpu::TextureFormat) -> u64 { |
| | 57 | u64::from(size[0].max(1)) |
| | 58 | .saturating_mul(u64::from(size[1].max(1))) |
| | 59 | .saturating_mul(bytes_per_pixel(format)) |
| | 60 | } |
| | 61 | |
| 38 | impl CachedTexture { | 62 | impl CachedTexture { |
| 39 | pub fn from_texture(texture: wgpu::Texture, size: [u32; 2], content_hash: u64) -> Self { | 63 | pub fn from_texture(texture: wgpu::Texture, size: [u32; 2], content_hash: u64) -> Self { |
| 40 | Self::from_texture_dod(texture, size, [0, 0], size, content_hash) | 64 | Self::from_texture_dod(texture, size, [0, 0], size, content_hash) |
| ... | @@ -48,11 +72,7 @@ impl CachedTexture { | ... | @@ -48,11 +72,7 @@ impl CachedTexture { |
| 48 | content_hash: u64, | 72 | content_hash: u64, |
| 49 | ) -> Self { | 73 | ) -> Self { |
| 50 | let format = texture.format(); | 74 | let format = texture.format(); |
| 51 | let depth = match format { | 75 | let depth = depth_for_format(format); |
| 52 | wgpu::TextureFormat::Rgba16Float => BitDepth::Float16, | | |
| 53 | wgpu::TextureFormat::Rgba32Float => BitDepth::Float32, | | |
| 54 | _ => BitDepth::Int8, | | |
| 55 | }; | | |
| 56 | Self::from_texture_dod_depth(texture, size, origin, canvas_size, depth, content_hash) | 76 | Self::from_texture_dod_depth(texture, size, origin, canvas_size, depth, content_hash) |
| 57 | } | 77 | } |
| 58 | | 78 | |
| ... | @@ -65,13 +85,8 @@ impl CachedTexture { | ... | @@ -65,13 +85,8 @@ impl CachedTexture { |
| 65 | content_hash: u64, | 85 | content_hash: u64, |
| 66 | ) -> Self { | 86 | ) -> Self { |
| 67 | let format = texture.format(); | 87 | let format = texture.format(); |
| 68 | let bpp = match format { | | |
| 69 | wgpu::TextureFormat::Rgba32Float => 16u64, | | |
| 70 | wgpu::TextureFormat::Rgba16Float => 8u64, | | |
| 71 | _ => 4u64, | | |
| 72 | }; | | |
| 73 | let view = texture.create_view(&wgpu::TextureViewDescriptor::default()); | 88 | let view = texture.create_view(&wgpu::TextureViewDescriptor::default()); |
| 74 | let bytes = u64::from(size[0]) * u64::from(size[1]) * bpp; | 89 | let bytes = texture_bytes(size, format); |
| 75 | Self { | 90 | Self { |
| 76 | texture: Arc::new(texture), | 91 | texture: Arc::new(texture), |
| 77 | view: Arc::new(view), | 92 | view: Arc::new(view), |
| ... | @@ -87,6 +102,33 @@ impl CachedTexture { | ... | @@ -87,6 +102,33 @@ impl CachedTexture { |
| 87 | } | 102 | } |
| 88 | } | 103 | } |
| 89 | | 104 | |
| | 105 | #[allow(clippy::too_many_arguments)] |
| | 106 | pub(crate) fn from_parts( |
| | 107 | texture: Arc<wgpu::Texture>, |
| | 108 | view: Arc<wgpu::TextureView>, |
| | 109 | size: [u32; 2], |
| | 110 | origin: [i32; 2], |
| | 111 | canvas_size: [u32; 2], |
| | 112 | depth: BitDepth, |
| | 113 | format: wgpu::TextureFormat, |
| | 114 | content_hash: u64, |
| | 115 | bytes: u64, |
| | 116 | ) -> Self { |
| | 117 | Self { |
| | 118 | texture, |
| | 119 | view, |
| | 120 | size, |
| | 121 | origin, |
| | 122 | canvas_size, |
| | 123 | depth, |
| | 124 | format, |
| | 125 | tex_scale: 1.0, |
| | 126 | edge_mode: None, |
| | 127 | content_hash, |
| | 128 | bytes, |
| | 129 | } |
| | 130 | } |
| | 131 | |
| 90 | pub fn has_dod(&self) -> bool { | 132 | pub fn has_dod(&self) -> bool { |
| 91 | self.origin != [0, 0] || self.size != self.canvas_size | 133 | self.origin != [0, 0] || self.size != self.canvas_size |
| 92 | } | 134 | } |
| ... | @@ -107,6 +149,175 @@ pub struct EvalStats { | ... | @@ -107,6 +149,175 @@ pub struct EvalStats { |
| 107 | pub unsupported_nodes: Vec<String>, | 149 | pub unsupported_nodes: Vec<String>, |
| 108 | } | 150 | } |
| 109 | | 151 | |
| | 152 | /// Key identifying compatible GPU textures in `TexturePool`. |
| | 153 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] |
| | 154 | pub struct TexturePoolKey { |
| | 155 | pub width: u32, |
| | 156 | pub height: u32, |
| | 157 | pub format: wgpu::TextureFormat, |
| | 158 | pub usage: wgpu::TextureUsages, |
| | 159 | } |
| | 160 | |
| | 161 | /// Snapshot of `TexturePool` counters and resident VRAM. |
| | 162 | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] |
| | 163 | pub struct TexturePoolStats { |
| | 164 | pub pooled_count: usize, |
| | 165 | pub pooled_bytes: u64, |
| | 166 | pub hits: u64, |
| | 167 | pub misses: u64, |
| | 168 | pub evictions: u64, |
| | 169 | pub returns: u64, |
| | 170 | } |
| | 171 | |
| | 172 | struct PooledTexture { |
| | 173 | texture: Arc<wgpu::Texture>, |
| | 174 | view: Arc<wgpu::TextureView>, |
| | 175 | bytes: u64, |
| | 176 | last_returned: u64, |
| | 177 | } |
| | 178 | |
| | 179 | /// LRU pool of recycled `wgpu::Texture` allocations keyed by `(width, height, format, usage)`. |
| | 180 | pub struct TexturePool { |
| | 181 | buckets: HashMap<TexturePoolKey, VecDeque<PooledTexture>>, |
| | 182 | total_bytes: u64, |
| | 183 | pooled_count: usize, |
| | 184 | tick: u64, |
| | 185 | hits: u64, |
| | 186 | misses: u64, |
| | 187 | evictions: u64, |
| | 188 | returns: u64, |
| | 189 | } |
| | 190 | |
| | 191 | impl Default for TexturePool { |
| | 192 | fn default() -> Self { |
| | 193 | Self::new() |
| | 194 | } |
| | 195 | } |
| | 196 | |
| | 197 | impl TexturePool { |
| | 198 | pub fn new() -> Self { |
| | 199 | Self { |
| | 200 | buckets: HashMap::new(), |
| | 201 | total_bytes: 0, |
| | 202 | pooled_count: 0, |
| | 203 | tick: 0, |
| | 204 | hits: 0, |
| | 205 | misses: 0, |
| | 206 | evictions: 0, |
| | 207 | returns: 0, |
| | 208 | } |
| | 209 | } |
| | 210 | |
| | 211 | pub fn stats(&self) -> TexturePoolStats { |
| | 212 | TexturePoolStats { |
| | 213 | pooled_count: self.pooled_count, |
| | 214 | pooled_bytes: self.total_bytes, |
| | 215 | hits: self.hits, |
| | 216 | misses: self.misses, |
| | 217 | evictions: self.evictions, |
| | 218 | returns: self.returns, |
| | 219 | } |
| | 220 | } |
| | 221 | |
| | 222 | pub fn pooled_bytes(&self) -> u64 { |
| | 223 | self.total_bytes |
| | 224 | } |
| | 225 | |
| | 226 | pub fn pooled_count(&self) -> usize { |
| | 227 | self.pooled_count |
| | 228 | } |
| | 229 | |
| | 230 | pub fn hits(&self) -> u64 { |
| | 231 | self.hits |
| | 232 | } |
| | 233 | |
| | 234 | pub fn misses(&self) -> u64 { |
| | 235 | self.misses |
| | 236 | } |
| | 237 | |
| | 238 | pub fn evictions(&self) -> u64 { |
| | 239 | self.evictions |
| | 240 | } |
| | 241 | |
| | 242 | pub fn clear(&mut self) { |
| | 243 | self.buckets.clear(); |
| | 244 | self.total_bytes = 0; |
| | 245 | self.pooled_count = 0; |
| | 246 | } |
| | 247 | |
| | 248 | fn push(&mut self, tex: &CachedTexture) { |
| | 249 | if tex.bytes == 0 || tex.size[0] == 0 || tex.size[1] == 0 { |
| | 250 | return; |
| | 251 | } |
| | 252 | let key = TexturePoolKey { |
| | 253 | width: tex.size[0], |
| | 254 | height: tex.size[1], |
| | 255 | format: tex.format, |
| | 256 | usage: tex.texture.usage(), |
| | 257 | }; |
| | 258 | self.tick += 1; |
| | 259 | self.total_bytes = self.total_bytes.saturating_add(tex.bytes); |
| | 260 | self.pooled_count += 1; |
| | 261 | self.returns += 1; |
| | 262 | self.buckets.entry(key).or_default().push_back(PooledTexture { |
| | 263 | texture: Arc::clone(&tex.texture), |
| | 264 | view: Arc::clone(&tex.view), |
| | 265 | bytes: tex.bytes, |
| | 266 | last_returned: self.tick, |
| | 267 | }); |
| | 268 | } |
| | 269 | |
| | 270 | /// Pops an exclusively owned (`Arc::strong_count == 1`) texture matching `key`. |
| | 271 | /// Entries still referenced elsewhere (e.g. by `output_cache`) are dropped from the pool |
| | 272 | /// rather than aliased. |
| | 273 | fn pop(&mut self, key: TexturePoolKey) -> Option<(Arc<wgpu::Texture>, Arc<wgpu::TextureView>, u64)> { |
| | 274 | let mut found = None; |
| | 275 | let remove_bucket = if let Some(bucket) = self.buckets.get_mut(&key) { |
| | 276 | while let Some(item) = bucket.pop_back() { |
| | 277 | self.total_bytes = self.total_bytes.saturating_sub(item.bytes); |
| | 278 | self.pooled_count = self.pooled_count.saturating_sub(1); |
| | 279 | if Arc::strong_count(&item.texture) == 1 && Arc::strong_count(&item.view) == 1 { |
| | 280 | found = Some((item.texture, item.view, item.bytes)); |
| | 281 | break; |
| | 282 | } |
| | 283 | } |
| | 284 | bucket.is_empty() |
| | 285 | } else { |
| | 286 | false |
| | 287 | }; |
| | 288 | if remove_bucket { |
| | 289 | self.buckets.remove(&key); |
| | 290 | } |
| | 291 | found |
| | 292 | } |
| | 293 | |
| | 294 | /// Evicts the globally oldest pooled texture (FIFO/LRU by return order). |
| | 295 | fn evict_oldest(&mut self) -> bool { |
| | 296 | let oldest_key = self |
| | 297 | .buckets |
| | 298 | .iter() |
| | 299 | .filter_map(|(&k, q)| q.front().map(|front| (k, front.last_returned))) |
| | 300 | .min_by_key(|(_, tick)| *tick) |
| | 301 | .map(|(k, _)| k); |
| | 302 | let Some(key) = oldest_key else { |
| | 303 | return false; |
| | 304 | }; |
| | 305 | let mut remove_bucket = false; |
| | 306 | if let Some(bucket) = self.buckets.get_mut(&key) { |
| | 307 | if let Some(item) = bucket.pop_front() { |
| | 308 | self.total_bytes = self.total_bytes.saturating_sub(item.bytes); |
| | 309 | self.pooled_count = self.pooled_count.saturating_sub(1); |
| | 310 | self.evictions += 1; |
| | 311 | } |
| | 312 | remove_bucket = bucket.is_empty(); |
| | 313 | } |
| | 314 | if remove_bucket { |
| | 315 | self.buckets.remove(&key); |
| | 316 | } |
| | 317 | true |
| | 318 | } |
| | 319 | } |
| | 320 | |
| 110 | struct Entry { | 321 | struct Entry { |
| 111 | tex: CachedTexture, | 322 | tex: CachedTexture, |
| 112 | last_used: u64, | 323 | last_used: u64, |
| ... | @@ -117,6 +328,9 @@ struct Entry { | ... | @@ -117,6 +328,9 @@ struct Entry { |
| 117 | /// Default GPU texture cache VRAM budget (768 MiB keeps heavy 150+ node comps well below 1 GiB). | 328 | /// Default GPU texture cache VRAM budget (768 MiB keeps heavy 150+ node comps well below 1 GiB). |
| 118 | pub const DEFAULT_VRAM_BUDGET_MB: u64 = 768; | 329 | pub const DEFAULT_VRAM_BUDGET_MB: u64 = 768; |
| 119 | | 330 | |
| | 331 | /// Alias for `NodeCache` (GPU texture cache + VRAM-budgeted `TexturePool`). |
| | 332 | pub type GpuCache = NodeCache; |
| | 333 | |
| 120 | pub struct NodeCache { | 334 | pub struct NodeCache { |
| 121 | pub mode: CacheMode, | 335 | pub mode: CacheMode, |
| 122 | pub budget_bytes: u64, | 336 | pub budget_bytes: u64, |
| ... | @@ -128,6 +342,8 @@ pub struct NodeCache { | ... | @@ -128,6 +342,8 @@ pub struct NodeCache { |
| 128 | pub gpu_salt: u64, | 342 | pub gpu_salt: u64, |
| 129 | /// Per-node salt bumped when surgically busting a subtree. | 343 | /// Per-node salt bumped when surgically busting a subtree. |
| 130 | node_salts: HashMap<NodeId, u64>, | 344 | node_salts: HashMap<NodeId, u64>, |
| | 345 | pool: Mutex<TexturePool>, |
| | 346 | profiler: Option<ProfileRecorder>, |
| 131 | } | 347 | } |
| 132 | | 348 | |
| 133 | impl NodeCache { | 349 | impl NodeCache { |
| ... | @@ -141,12 +357,25 @@ impl NodeCache { | ... | @@ -141,12 +357,25 @@ impl NodeCache { |
| 141 | evictions: 0, | 357 | evictions: 0, |
| 142 | gpu_salt: 0, | 358 | gpu_salt: 0, |
| 143 | node_salts: HashMap::new(), | 359 | node_salts: HashMap::new(), |
| | 360 | pool: Mutex::new(TexturePool::new()), |
| | 361 | profiler: None, |
| 144 | } | 362 | } |
| 145 | } | 363 | } |
| 146 | | 364 | |
| | 365 | /// Standard compositor GPU texture usage flags used by `Evaluator`. |
| | 366 | pub fn default_texture_usage() -> wgpu::TextureUsages { |
| | 367 | wgpu::TextureUsages::TEXTURE_BINDING |
| | 368 | | wgpu::TextureUsages::STORAGE_BINDING |
| | 369 | | wgpu::TextureUsages::COPY_SRC |
| | 370 | | wgpu::TextureUsages::COPY_DST |
| | 371 | | wgpu::TextureUsages::RENDER_ATTACHMENT |
| | 372 | } |
| | 373 | |
| 147 | pub fn set_budget_mb(&mut self, budget_mb: u64) { | 374 | pub fn set_budget_mb(&mut self, budget_mb: u64) { |
| 148 | self.budget_bytes = budget_mb.saturating_mul(1024 * 1024); | 375 | self.budget_bytes = budget_mb.saturating_mul(1024 * 1024); |
| | 376 | self.trim_pool_to_budget(); |
| 149 | self.evict_over_budget(); | 377 | self.evict_over_budget(); |
| | 378 | self.trim_pool_to_budget(); |
| 150 | } | 379 | } |
| 151 | | 380 | |
| 152 | pub fn budget_mb(&self) -> u64 { | 381 | pub fn budget_mb(&self) -> u64 { |
| ... | @@ -161,6 +390,142 @@ impl NodeCache { | ... | @@ -161,6 +390,142 @@ impl NodeCache { |
| 161 | self.node_salts.get(&id).copied().unwrap_or(0) | 390 | self.node_salts.get(&id).copied().unwrap_or(0) |
| 162 | } | 391 | } |
| 163 | | 392 | |
| | 393 | pub fn pool_stats(&self) -> TexturePoolStats { |
| | 394 | self.pool.lock().expect("texture pool lock").stats() |
| | 395 | } |
| | 396 | |
| | 397 | pub fn pooled_bytes(&self) -> u64 { |
| | 398 | self.pool.lock().expect("texture pool lock").pooled_bytes() |
| | 399 | } |
| | 400 | |
| | 401 | pub fn pooled_mb(&self) -> f64 { |
| | 402 | self.pooled_bytes() as f64 / (1024.0 * 1024.0) |
| | 403 | } |
| | 404 | |
| | 405 | pub fn live_bytes(&self) -> u64 { |
| | 406 | self.total_bytes |
| | 407 | } |
| | 408 | |
| | 409 | pub fn live_mb(&self) -> f64 { |
| | 410 | self.total_bytes as f64 / (1024.0 * 1024.0) |
| | 411 | } |
| | 412 | |
| | 413 | pub fn total_vram_bytes(&self) -> u64 { |
| | 414 | self.total_bytes.saturating_add(self.pooled_bytes()) |
| | 415 | } |
| | 416 | |
| | 417 | /// Acquires a GPU texture matching `(width, height, format, usage)` from the pool if an |
| | 418 | /// exclusively-owned texture is available, otherwise allocates a fresh one on `device`. |
| | 419 | pub fn acquire_texture( |
| | 420 | &self, |
| | 421 | device: &wgpu::Device, |
| | 422 | width: u32, |
| | 423 | height: u32, |
| | 424 | format: wgpu::TextureFormat, |
| | 425 | usage: wgpu::TextureUsages, |
| | 426 | ) -> CachedTexture { |
| | 427 | let clamped = [width.max(1), height.max(1)]; |
| | 428 | let bytes = texture_bytes(clamped, format); |
| | 429 | let key = TexturePoolKey { |
| | 430 | width: clamped[0], |
| | 431 | height: clamped[1], |
| | 432 | format, |
| | 433 | usage, |
| | 434 | }; |
| | 435 | let depth = depth_for_format(format); |
| | 436 | |
| | 437 | { |
| | 438 | let mut pool = self.pool.lock().expect("texture pool lock"); |
| | 439 | if let Some((texture, view, pooled_bytes)) = pool.pop(key) { |
| | 440 | pool.hits += 1; |
| | 441 | return CachedTexture::from_parts( |
| | 442 | texture, |
| | 443 | view, |
| | 444 | clamped, |
| | 445 | [0, 0], |
| | 446 | clamped, |
| | 447 | depth, |
| | 448 | format, |
| | 449 | 0, |
| | 450 | pooled_bytes, |
| | 451 | ); |
| | 452 | } |
| | 453 | pool.misses += 1; |
| | 454 | // Evict oldest pooled textures upfront so live + pooled + new allocation stays within budget. |
| | 455 | while self |
| | 456 | .total_bytes |
| | 457 | .saturating_add(pool.total_bytes) |
| | 458 | .saturating_add(bytes) |
| | 459 | > self.budget_bytes |
| | 460 | { |
| | 461 | if !pool.evict_oldest() { |
| | 462 | break; |
| | 463 | } |
| | 464 | } |
| | 465 | } |
| | 466 | |
| | 467 | let texture = device.create_texture(&wgpu::TextureDescriptor { |
| | 468 | label: Some("comp-tex"), |
| | 469 | size: wgpu::Extent3d { |
| | 470 | width: clamped[0], |
| | 471 | height: clamped[1], |
| | 472 | depth_or_array_layers: 1, |
| | 473 | }, |
| | 474 | mip_level_count: 1, |
| | 475 | sample_count: 1, |
| | 476 | dimension: wgpu::TextureDimension::D2, |
| | 477 | format, |
| | 478 | usage, |
| | 479 | view_formats: &[], |
| | 480 | }); |
| | 481 | CachedTexture::from_texture_dod_depth(texture, clamped, [0, 0], clamped, depth, 0) |
| | 482 | } |
| | 483 | |
| | 484 | /// Pool-backed DoD texture allocation matching `create_texture_dod_fmt` semantics. |
| | 485 | #[allow(clippy::too_many_arguments)] |
| | 486 | pub fn acquire_texture_dod_fmt( |
| | 487 | &self, |
| | 488 | device: &wgpu::Device, |
| | 489 | size: [u32; 2], |
| | 490 | origin: [i32; 2], |
| | 491 | canvas_size: [u32; 2], |
| | 492 | depth: BitDepth, |
| | 493 | format: wgpu::TextureFormat, |
| | 494 | content_hash: u64, |
| | 495 | ) -> CachedTexture { |
| | 496 | let mut tex = self.acquire_texture( |
| | 497 | device, |
| | 498 | size[0], |
| | 499 | size[1], |
| | 500 | format, |
| | 501 | Self::default_texture_usage(), |
| | 502 | ); |
| | 503 | tex.origin = origin; |
| | 504 | tex.canvas_size = [canvas_size[0].max(1), canvas_size[1].max(1)]; |
| | 505 | tex.depth = depth; |
| | 506 | tex.content_hash = content_hash; |
| | 507 | tex |
| | 508 | } |
| | 509 | |
| | 510 | /// Starts per-node profiling for the upcoming frame evaluation. |
| | 511 | pub fn begin_frame_profile(&mut self) { |
| | 512 | let stats = self.pool_stats(); |
| | 513 | self.profiler = Some(ProfileRecorder::new(stats.hits, stats.misses)); |
| | 514 | } |
| | 515 | |
| | 516 | /// Starts per-node profiling with node names and kinds pre-populated from `comp`. |
| | 517 | pub fn begin_frame_profile_with_comp(&mut self, comp: &Comp) { |
| | 518 | let stats = self.pool_stats(); |
| | 519 | self.profiler = Some(ProfileRecorder::with_comp(comp, stats.hits, stats.misses)); |
| | 520 | } |
| | 521 | |
| | 522 | /// Stops profiling and returns the collected `FrameProfile`, if active. |
| | 523 | pub fn take_frame_profile(&mut self) -> Option<FrameProfile> { |
| | 524 | let rec = self.profiler.take()?; |
| | 525 | let stats = self.pool_stats(); |
| | 526 | Some(rec.finish(self.total_bytes, stats.pooled_bytes, stats.hits, stats.misses)) |
| | 527 | } |
| | 528 | |
| 164 | pub fn get(&mut self, key: u64, node: NodeId, frame: i64) -> Option<CachedTexture> { | 529 | pub fn get(&mut self, key: u64, node: NodeId, frame: i64) -> Option<CachedTexture> { |
| 165 | if self.mode == CacheMode::Bypass { | 530 | if self.mode == CacheMode::Bypass { |
| 166 | return None; | 531 | return None; |
| ... | @@ -170,18 +535,28 @@ impl NodeCache { | ... | @@ -170,18 +535,28 @@ impl NodeCache { |
| 170 | e.last_used = self.tick; | 535 | e.last_used = self.tick; |
| 171 | e.producers.insert(node); | 536 | e.producers.insert(node); |
| 172 | e.frames.insert(frame); | 537 | e.frames.insert(frame); |
| 173 | Some(e.tex.clone()) | 538 | let tex = e.tex.clone(); |
| | 539 | if let Some(prof) = &mut self.profiler { |
| | 540 | prof.record(node, true, tex.size, tex.bytes); |
| | 541 | } |
| | 542 | Some(tex) |
| 174 | } | 543 | } |
| 175 | | 544 | |
| 176 | pub fn insert(&mut self, key: u64, tex: CachedTexture, node: NodeId, frame: i64) { | 545 | pub fn insert(&mut self, key: u64, tex: CachedTexture, node: NodeId, frame: i64) { |
| | 546 | if let Some(prof) = &mut self.profiler { |
| | 547 | prof.record(node, false, tex.size, tex.bytes); |
| | 548 | } |
| 177 | if self.mode == CacheMode::Bypass { | 549 | if self.mode == CacheMode::Bypass { |
| 178 | return; | 550 | return; |
| 179 | } | 551 | } |
| 180 | self.tick += 1; | 552 | self.tick += 1; |
| 181 | if let Some(old) = self.entries.remove(&key) { | 553 | if let Some(old) = self.entries.remove(&key) { |
| 182 | self.total_bytes = self.total_bytes.saturating_sub(old.tex.bytes); | 554 | self.total_bytes = self.total_bytes.saturating_sub(old.tex.bytes); |
| | 555 | if !Arc::ptr_eq(&old.tex.texture, &tex.texture) { |
| | 556 | self.return_to_pool(&old.tex); |
| | 557 | } |
| 183 | } | 558 | } |
| 184 | self.total_bytes += tex.bytes; | 559 | self.total_bytes = self.total_bytes.saturating_add(tex.bytes); |
| 185 | let mut producers = HashSet::new(); | 560 | let mut producers = HashSet::new(); |
| 186 | producers.insert(node); | 561 | producers.insert(node); |
| 187 | let mut frames = HashSet::new(); | 562 | let mut frames = HashSet::new(); |
| ... | @@ -195,7 +570,32 @@ impl NodeCache { | ... | @@ -195,7 +570,32 @@ impl NodeCache { |
| 195 | frames, | 570 | frames, |
| 196 | }, | 571 | }, |
| 197 | ); | 572 | ); |
| | 573 | // Trim pooled textures before evicting live cached nodes so live working sets stay hot. |
| | 574 | self.trim_pool_to_budget(); |
| 198 | self.evict_over_budget(); | 575 | self.evict_over_budget(); |
| | 576 | self.trim_pool_to_budget(); |
| | 577 | } |
| | 578 | |
| | 579 | fn return_to_pool(&self, tex: &CachedTexture) { |
| | 580 | if tex.bytes == 0 || tex.bytes > self.budget_bytes { |
| | 581 | return; |
| | 582 | } |
| | 583 | let mut pool = self.pool.lock().expect("texture pool lock"); |
| | 584 | pool.push(tex); |
| | 585 | while self.total_bytes.saturating_add(pool.total_bytes) > self.budget_bytes { |
| | 586 | if !pool.evict_oldest() { |
| | 587 | break; |
| | 588 | } |
| | 589 | } |
| | 590 | } |
| | 591 | |
| | 592 | fn trim_pool_to_budget(&self) { |
| | 593 | let mut pool = self.pool.lock().expect("texture pool lock"); |
| | 594 | while self.total_bytes.saturating_add(pool.total_bytes) > self.budget_bytes { |
| | 595 | if !pool.evict_oldest() { |
| | 596 | break; |
| | 597 | } |
| | 598 | } |
| 199 | } | 599 | } |
| 200 | | 600 | |
| 201 | fn evict_over_budget(&mut self) { | 601 | fn evict_over_budget(&mut self) { |
| ... | @@ -207,18 +607,46 @@ impl NodeCache { | ... | @@ -207,18 +607,46 @@ impl NodeCache { |
| 207 | if let Some(removed) = self.entries.remove(&oldest_key) { | 607 | if let Some(removed) = self.entries.remove(&oldest_key) { |
| 208 | self.total_bytes = self.total_bytes.saturating_sub(removed.tex.bytes); | 608 | self.total_bytes = self.total_bytes.saturating_sub(removed.tex.bytes); |
| 209 | self.evictions += 1; | 609 | self.evictions += 1; |
| | 610 | if self |
| | 611 | .total_bytes |
| | 612 | .saturating_add(self.pooled_bytes()) |
| | 613 | .saturating_add(removed.tex.bytes) |
| | 614 | <= self.budget_bytes |
| | 615 | { |
| | 616 | self.return_to_pool(&removed.tex); |
| | 617 | } |
| 210 | } | 618 | } |
| 211 | } | 619 | } |
| 212 | } | 620 | } |
| 213 | | 621 | |
| 214 | /// Wipes every cached GPU node texture and bumps global salt. | 622 | /// Wipes every cached GPU node texture (returning eligible textures to the pool) and bumps global salt. |
| 215 | pub fn bust_all(&mut self) { | 623 | pub fn bust_all(&mut self) { |
| 216 | self.entries.clear(); | 624 | let _ = self.clear_dynamic(); |
| | 625 | } |
| | 626 | |
| | 627 | /// Clears all dynamic cached GPU node textures into the pool (within VRAM budget) and bumps global salt. |
| | 628 | pub fn clear_dynamic(&mut self) -> usize { |
| | 629 | let count = self.entries.len(); |
| | 630 | let drained: Vec<Entry> = self.entries.drain().map(|(_, e)| e).collect(); |
| 217 | self.total_bytes = 0; | 631 | self.total_bytes = 0; |
| 218 | self.gpu_salt += 1; | 632 | self.gpu_salt += 1; |
| | 633 | if !drained.is_empty() && self.budget_bytes > 0 { |
| | 634 | let mut pool = self.pool.lock().expect("texture pool lock"); |
| | 635 | for entry in drained { |
| | 636 | if entry.tex.bytes > 0 && entry.tex.bytes <= self.budget_bytes { |
| | 637 | pool.push(&entry.tex); |
| | 638 | } |
| | 639 | } |
| | 640 | while self.total_bytes.saturating_add(pool.total_bytes) > self.budget_bytes { |
| | 641 | if !pool.evict_oldest() { |
| | 642 | break; |
| | 643 | } |
| | 644 | } |
| | 645 | } |
| | 646 | count |
| 219 | } | 647 | } |
| 220 | | 648 | |
| 221 | /// Removes cached entries produced for a specific integer frame. | 649 | /// Removes cached entries produced for a specific integer frame, returning them to the pool. |
| 222 | pub fn bust_frame(&mut self, frame: i64) -> usize { | 650 | pub fn bust_frame(&mut self, frame: i64) -> usize { |
| 223 | let keys: Vec<u64> = self | 651 | let keys: Vec<u64> = self |
| 224 | .entries | 652 | .entries |
| ... | @@ -230,13 +658,14 @@ impl NodeCache { | ... | @@ -230,13 +658,14 @@ impl NodeCache { |
| 230 | for k in keys { | 658 | for k in keys { |
| 231 | if let Some(removed) = self.entries.remove(&k) { | 659 | if let Some(removed) = self.entries.remove(&k) { |
| 232 | self.total_bytes = self.total_bytes.saturating_sub(removed.tex.bytes); | 660 | self.total_bytes = self.total_bytes.saturating_sub(removed.tex.bytes); |
| | 661 | self.return_to_pool(&removed.tex); |
| 233 | } | 662 | } |
| 234 | } | 663 | } |
| 235 | count | 664 | count |
| 236 | } | 665 | } |
| 237 | | 666 | |
| 238 | /// Bumps the salt on `node` (automatically invalidating `node` AND everything downstream | 667 | /// Bumps the salt on `node` (automatically invalidating `node` AND everything downstream |
| 239 | /// via Merkle hashing!) and evicts its existing entries. | 668 | /// via Merkle hashing!) and evicts its existing entries back into the pool. |
| 240 | pub fn bust_subtree(&mut self, node: NodeId) -> usize { | 669 | pub fn bust_subtree(&mut self, node: NodeId) -> usize { |
| 241 | *self.node_salts.entry(node).or_insert(0) += 1; | 670 | *self.node_salts.entry(node).or_insert(0) += 1; |
| 242 | let keys: Vec<u64> = self | 671 | let keys: Vec<u64> = self |
| ... | @@ -249,6 +678,7 @@ impl NodeCache { | ... | @@ -249,6 +678,7 @@ impl NodeCache { |
| 249 | for k in keys { | 678 | for k in keys { |
| 250 | if let Some(removed) = self.entries.remove(&k) { | 679 | if let Some(removed) = self.entries.remove(&k) { |
| 251 | self.total_bytes = self.total_bytes.saturating_sub(removed.tex.bytes); | 680 | self.total_bytes = self.total_bytes.saturating_sub(removed.tex.bytes); |
| | 681 | self.return_to_pool(&removed.tex); |
| 252 | } | 682 | } |
| 253 | } | 683 | } |
| 254 | count | 684 | count |
| ... | @@ -259,6 +689,167 @@ impl NodeCache { | ... | @@ -259,6 +689,167 @@ impl NodeCache { |
| 259 | } | 689 | } |
| 260 | | 690 | |
| 261 | pub fn total_mb(&self) -> f64 { | 691 | pub fn total_mb(&self) -> f64 { |
| 262 | self.total_bytes as f64 / (1024.0 * 1024.0) | 692 | self.total_vram_bytes() as f64 / (1024.0 * 1024.0) |
| | 693 | } |
| | 694 | } |
| | 695 | |
| | 696 | #[cfg(test)] |
| | 697 | mod tests { |
| | 698 | use super::*; |
| | 699 | use crate::Engine; |
| | 700 | |
| | 701 | #[test] |
| | 702 | fn texture_pool_recycles_after_clear_dynamic_and_bust() { |
| | 703 | let eng = Engine::new_headless().expect("gpu"); |
| | 704 | let device = eng.device(); |
| | 705 | let usage = NodeCache::default_texture_usage(); |
| | 706 | let mut cache = NodeCache::new(DEFAULT_VRAM_BUDGET_MB); |
| | 707 | |
| | 708 | // Initial acquire misses pool and allocates a 512x512 RGBA8 texture (1 MiB). |
| | 709 | let t1 = cache.acquire_texture(device, 512, 512, wgpu::TextureFormat::Rgba8Unorm, usage); |
| | 710 | let ptr1 = Arc::as_ptr(&t1.texture); |
| | 711 | assert_eq!(t1.bytes, 1024 * 1024); |
| | 712 | assert_eq!(cache.pool_stats().misses, 1); |
| | 713 | assert_eq!(cache.pool_stats().hits, 0); |
| | 714 | |
| | 715 | cache.insert(101, t1, NodeId(1), 0); |
| | 716 | assert_eq!(cache.live_bytes(), 1024 * 1024); |
| | 717 | assert_eq!(cache.pooled_bytes(), 0); |
| | 718 | |
| | 719 | // clear_dynamic returns unshared texture to pool without freeing GPU allocation. |
| | 720 | let cleared = cache.clear_dynamic(); |
| | 721 | assert_eq!(cleared, 1); |
| | 722 | assert_eq!(cache.live_bytes(), 0); |
| | 723 | assert_eq!(cache.pooled_bytes(), 1024 * 1024); |
| | 724 | assert_eq!(cache.pool_stats().pooled_count, 1); |
| | 725 | |
| | 726 | // Acquiring same (w, h, format, usage) reuses the exact same wgpu::Texture allocation! |
| | 727 | let t2 = cache.acquire_texture(device, 512, 512, wgpu::TextureFormat::Rgba8Unorm, usage); |
| | 728 | assert_eq!(Arc::as_ptr(&t2.texture), ptr1); |
| | 729 | assert_eq!(cache.pool_stats().hits, 1); |
| | 730 | assert_eq!(cache.pool_stats().misses, 1); |
| | 731 | assert_eq!(cache.pooled_bytes(), 0); |
| | 732 | |
| | 733 | // Different format must miss pool and allocate separately. |
| | 734 | let t3 = cache.acquire_texture(device, 512, 512, wgpu::TextureFormat::Rgba16Float, usage); |
| | 735 | assert_ne!(Arc::as_ptr(&t3.texture), ptr1); |
| | 736 | assert_eq!(cache.pool_stats().misses, 2); |
| | 737 | |
| | 738 | // Insert both and bust_frame(5) -> returns only frame 5 texture to pool. |
| | 739 | cache.insert(201, t2, NodeId(1), 5); |
| | 740 | cache.insert(202, t3, NodeId(2), 6); |
| | 741 | assert_eq!(cache.bust_frame(5), 1); |
| | 742 | assert_eq!(cache.pooled_bytes(), 1024 * 1024); |
| | 743 | assert_eq!(cache.live_bytes(), 2 * 1024 * 1024); |
| | 744 | |
| | 745 | let t4 = cache.acquire_texture(device, 512, 512, wgpu::TextureFormat::Rgba8Unorm, usage); |
| | 746 | assert_eq!(Arc::as_ptr(&t4.texture), ptr1); |
| | 747 | assert_eq!(cache.pool_stats().hits, 2); |
| | 748 | } |
| | 749 | |
| | 750 | #[test] |
| | 751 | fn texture_pool_never_aliases_shared_arc() { |
| | 752 | let eng = Engine::new_headless().expect("gpu"); |
| | 753 | let device = eng.device(); |
| | 754 | let usage = NodeCache::default_texture_usage(); |
| | 755 | let mut cache = NodeCache::new(16); |
| | 756 | |
| | 757 | let t1 = cache.acquire_texture(device, 256, 256, wgpu::TextureFormat::Rgba8Unorm, usage); |
| | 758 | let pinned = t1.clone(); // External holder keeps strong_count > 1! |
| | 759 | let ptr1 = Arc::as_ptr(&t1.texture); |
| | 760 | cache.insert(1, t1, NodeId(0), 0); |
| | 761 | cache.bust_all(); |
| | 762 | |
| | 763 | // While `pinned` is still alive, acquire_texture must NOT alias `t1`. |
| | 764 | let t2 = cache.acquire_texture(device, 256, 256, wgpu::TextureFormat::Rgba8Unorm, usage); |
| | 765 | assert_ne!(Arc::as_ptr(&t2.texture), ptr1); |
| | 766 | assert_eq!(cache.pool_stats().hits, 0); |
| | 767 | drop(pinned); |
| | 768 | } |
| | 769 | |
| | 770 | #[test] |
| | 771 | fn vram_budget_enforces_live_plus_pooled_cap_and_lru_eviction() { |
| | 772 | let eng = Engine::new_headless().expect("gpu"); |
| | 773 | let device = eng.device(); |
| | 774 | let usage = NodeCache::default_texture_usage(); |
| | 775 | // 8 MiB budget; each 1024x1024 RGBA8 texture is 4 MiB. |
| | 776 | let mut cache = NodeCache::new(8); |
| | 777 | let budget = 8 * 1024 * 1024; |
| | 778 | |
| | 779 | let a = cache.acquire_texture(device, 1024, 1024, wgpu::TextureFormat::Rgba8Unorm, usage); |
| | 780 | let b = cache.acquire_texture(device, 1024, 1024, wgpu::TextureFormat::Rgba8Unorm, usage); |
| | 781 | cache.insert(1, a, NodeId(0), 0); |
| | 782 | cache.insert(2, b, NodeId(1), 0); |
| | 783 | assert_eq!(cache.total_vram_bytes(), 8 * 1024 * 1024); |
| | 784 | |
| | 785 | // Bust both into pool: live=0, pooled=8 MiB <= 8 MiB. |
| | 786 | cache.bust_all(); |
| | 787 | assert_eq!(cache.live_bytes(), 0); |
| | 788 | assert_eq!(cache.pooled_bytes(), 8 * 1024 * 1024); |
| | 789 | |
| | 790 | // Inserting a 1024x1024 RGBA16F (8 MiB) must evict ALL pooled RGBA8 textures so live + pooled <= 8 MiB. |
| | 791 | let c = cache.acquire_texture(device, 1024, 1024, wgpu::TextureFormat::Rgba16Float, usage); |
| | 792 | assert!(cache.total_vram_bytes() <= budget); |
| | 793 | cache.insert(3, c, NodeId(2), 1); |
| | 794 | assert!(cache.total_vram_bytes() <= budget); |
| | 795 | assert_eq!(cache.pooled_bytes(), 0); |
| | 796 | assert!(cache.pool_stats().evictions >= 2); |
| | 797 | |
| | 798 | // Verify deterministic LRU eviction order in pool within 8 MiB. |
| | 799 | let mut cache3 = NodeCache::new(8); |
| | 800 | let first = cache3.acquire_texture(device, 1024, 1024, wgpu::TextureFormat::Rgba8Unorm, usage); // 4 MiB |
| | 801 | let second = cache3.acquire_texture(device, 512, 1024, wgpu::TextureFormat::Rgba8Unorm, usage); // 2 MiB |
| | 802 | let third = cache3.acquire_texture(device, 512, 512, wgpu::TextureFormat::Rgba8Unorm, usage); // 1 MiB |
| | 803 | let ptr_second = Arc::as_ptr(&second.texture); |
| | 804 | cache3.insert(1, first, NodeId(0), 1); |
| | 805 | cache3.insert(2, second, NodeId(1), 2); |
| | 806 | cache3.insert(3, third, NodeId(2), 3); |
| | 807 | assert!(cache3.total_vram_bytes() <= budget); |
| | 808 | |
| | 809 | // Bust in deterministic order: frame 1 (4 MiB) oldest, then frame 2 (2 MiB), then frame 3 (1 MiB) => 7 MiB pooled. |
| | 810 | assert_eq!(cache3.bust_frame(1), 1); |
| | 811 | assert_eq!(cache3.bust_frame(2), 1); |
| | 812 | assert_eq!(cache3.bust_frame(3), 1); |
| | 813 | assert_eq!(cache3.pooled_bytes(), 7 * 1024 * 1024); |
| | 814 | |
| | 815 | // Acquiring a 4 MiB Rgba16Float (512x1024x8 = 4 MiB) misses pool and must evict oldest (frame 1's 4 MiB), |
| | 816 | // leaving frame 2 (2 MiB) + frame 3 (1 MiB) intact! |
| | 817 | let _new_f16 = cache3.acquire_texture(device, 512, 1024, wgpu::TextureFormat::Rgba16Float, usage); |
| | 818 | assert_eq!(cache3.pooled_bytes(), 3 * 1024 * 1024); |
| | 819 | let reused_second = cache3.acquire_texture(device, 512, 1024, wgpu::TextureFormat::Rgba8Unorm, usage); |
| | 820 | assert_eq!(Arc::as_ptr(&reused_second.texture), ptr_second); |
| | 821 | } |
| | 822 | |
| | 823 | #[test] |
| | 824 | fn default_budget_is_768_mb_and_profiler_records_hits_misses() { |
| | 825 | let eng = Engine::new_headless().expect("gpu"); |
| | 826 | let device = eng.device(); |
| | 827 | let usage = NodeCache::default_texture_usage(); |
| | 828 | let mut cache = NodeCache::new(DEFAULT_VRAM_BUDGET_MB); |
| | 829 | assert_eq!(cache.budget_mb(), 768); |
| | 830 | assert_eq!(cache.budget_bytes, 768 * 1024 * 1024); |
| | 831 | |
| | 832 | // Cold profile: 1 miss + insert |
| | 833 | cache.begin_frame_profile(); |
| | 834 | assert!(cache.get(42, NodeId(7), 10).is_none()); |
| | 835 | let t = cache.acquire_texture(device, 640, 360, wgpu::TextureFormat::Rgba8Unorm, usage); |
| | 836 | cache.insert(42, t, NodeId(7), 10); |
| | 837 | let p_cold = cache.take_frame_profile().expect("profile"); |
| | 838 | assert_eq!(p_cold.cache_hits, 0); |
| | 839 | assert_eq!(p_cold.cache_misses, 1); |
| | 840 | assert_eq!(p_cold.pool_misses, 1); |
| | 841 | assert_eq!(p_cold.pool_hits, 0); |
| | 842 | assert_eq!(p_cold.entries.len(), 1); |
| | 843 | assert_eq!(p_cold.entries[0].width, 640); |
| | 844 | assert_eq!(p_cold.entries[0].height, 360); |
| | 845 | |
| | 846 | // Warm profile: 1 hit |
| | 847 | cache.begin_frame_profile(); |
| | 848 | assert!(cache.get(42, NodeId(7), 10).is_some()); |
| | 849 | let p_warm = cache.take_frame_profile().expect("profile"); |
| | 850 | assert_eq!(p_warm.cache_hits, 1); |
| | 851 | assert_eq!(p_warm.cache_misses, 0); |
| | 852 | assert_eq!(p_warm.entries.len(), 1); |
| | 853 | assert!(p_warm.entries[0].cache_hit); |
| 263 | } | 854 | } |
| 264 | } | 855 | } |