alice-sdf 5.0.0

ALICE-SDF: 3D/Spatial Data Specialist — Store laws, not polygons. GLSL/WGSL/HLSL transpile, SVO, GPU marching cubes, texture-fit, procedural CSG. Optional bridges to alice-physics / alice-codec / libasp / alice-cache behind features.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
//! SDF hash-based mesh cache with LRU eviction
//!
//! Maps SDF tree hashes to cached meshes for fast retrieval when the same
//! SDF is meshed repeatedly (e.g. editor preview, LOD regeneration).
//!
//! Also provides chunked incremental mesh caching via [`chunked`].
//!
//! # Features
//!
//! - **LRU eviction**: Oldest entries are evicted when the cache is full.
//! - **Thread-safe**: Uses `RwLock` for concurrent reads, exclusive writes.
//! - **Deterministic hashing**: Same SDF tree + bounds + resolution = same key.
//! - **Zero-copy sharing**: Cached meshes are returned as `Arc<Mesh>`.
//! - **`get_or_generate`**: Atomic check-and-insert to avoid redundant work.
//!
//! # Example
//!
//! ```rust
//! use alice_sdf::cache::{MeshCache, CacheConfig, compute_cache_key};
//! use alice_sdf::prelude::*;
//!
//! let cache = MeshCache::new(CacheConfig::default());
//! let sphere = SdfNode::sphere(1.0);
//! let min = Vec3::splat(-2.0);
//! let max = Vec3::splat(2.0);
//! let config = MarchingCubesConfig { resolution: 32, ..Default::default() };
//!
//! let key = compute_cache_key(&sphere, min, max, config.resolution);
//! let mesh = cache.get_or_generate(key, || {
//!     sdf_to_mesh(&sphere, min, max, &config)
//! });
//! ```
//!
//! Author: Moroya Sakamoto

pub mod chunked;
pub use chunked::{ChunkCoord, ChunkedCacheConfig, ChunkedMeshCache};

use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::path::PathBuf;
use std::sync::{Arc, RwLock};

use crate::mesh::Mesh;
use crate::types::SdfNode;

/// Configuration for the mesh cache.
///
/// Build it with `..Default::default()` for the fields you do not set, so the
/// deprecated fields below are not named:
///
/// ```
/// use alice_sdf::cache::CacheConfig;
/// let config = CacheConfig { max_entries: 16, ..Default::default() };
/// assert_eq!(config.max_entries, 16);
/// ```
#[derive(Debug, Clone)]
pub struct CacheConfig {
    /// Maximum number of cached meshes in memory.
    ///
    /// When an insert of a new key finds `max_entries` entries, the least
    /// recently used one is evicted first. **`0` means unbounded**: nothing is
    /// ever evicted and the cache grows with every distinct key.
    pub max_entries: usize,
    /// Not implemented: [`MeshCache`] never reads or writes this directory.
    ///
    /// Deprecated since 5.0.0. For `.abm` persistence use
    /// [`ChunkedMeshCache::persist_dirty`] / [`ChunkedMeshCache::load_chunk`]
    /// or [`crate::io::save_abm`] directly.
    #[deprecated(
        since = "5.0.0",
        note = "not implemented: MeshCache never touches the disk; persist with crate::io::save_abm or ChunkedMeshCache"
    )]
    pub disk_cache_dir: Option<PathBuf>,
    /// Not implemented: evicted meshes are dropped whatever this is set to.
    ///
    /// Deprecated since 5.0.0, see [`Self::disk_cache_dir`].
    #[deprecated(
        since = "5.0.0",
        note = "not implemented: evicted meshes are dropped; persist with crate::io::save_abm or ChunkedMeshCache"
    )]
    pub persist_on_evict: bool,
}

#[allow(deprecated)] // the deprecated fields still have to be initialised
impl Default for CacheConfig {
    fn default() -> Self {
        Self {
            max_entries: 64,
            disk_cache_dir: None,
            persist_on_evict: false,
        }
    }
}

/// Cache key computed from SDF tree + generation parameters.
///
/// Two identical SDF trees with the same bounds and resolution will produce
/// the same `MeshCacheKey`, enabling cache hits across frames or sessions.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct MeshCacheKey {
    /// Hash of the SDF node tree.
    pub sdf_hash: u64,
    /// Resolution used for mesh generation.
    pub resolution: u32,
    /// Quantized bounds hash (to avoid float comparison issues).
    pub bounds_hash: u64,
}

/// Internal cache entry holding the mesh and its approximate memory footprint.
struct CacheEntry {
    mesh: Arc<Mesh>,
    /// Approximate size in bytes (vertices * vertex_size + indices * 4).
    size_bytes: usize,
}

/// Internal LRU-ordered map.
///
/// `order` tracks access recency: front = oldest, back = newest.
struct LruMap {
    map: HashMap<MeshCacheKey, CacheEntry>,
    /// LRU order: front = oldest, back = newest.
    order: Vec<MeshCacheKey>,
}

impl LruMap {
    fn new() -> Self {
        Self {
            map: HashMap::new(),
            order: Vec::new(),
        }
    }

    /// Move `key` to the back (most-recently-used position).
    #[inline(always)]
    fn touch(&mut self, key: &MeshCacheKey) {
        if let Some(pos) = self.order.iter().position(|k| k == key) {
            self.order.remove(pos);
            self.order.push(key.clone());
        }
    }

    /// Insert a new entry, returning the evicted key (if any) when over capacity.
    fn insert(
        &mut self,
        key: MeshCacheKey,
        entry: CacheEntry,
        max_entries: usize,
    ) -> Option<MeshCacheKey> {
        // If key already exists, update in-place and touch.
        if self.map.contains_key(&key) {
            self.map.insert(key.clone(), entry);
            self.touch(&key);
            return None;
        }

        // Evict oldest if at capacity.
        let evicted = if self.map.len() >= max_entries && max_entries > 0 {
            if let Some(oldest_key) = self.order.first().cloned() {
                self.map.remove(&oldest_key);
                self.order.remove(0);
                Some(oldest_key)
            } else {
                None
            }
        } else {
            None
        };

        self.map.insert(key.clone(), entry);
        self.order.push(key);
        evicted
    }

    /// Remove an entry by key.
    fn remove(&mut self, key: &MeshCacheKey) -> Option<Arc<Mesh>> {
        if let Some(entry) = self.map.remove(key) {
            if let Some(pos) = self.order.iter().position(|k| k == key) {
                self.order.remove(pos);
            }
            Some(entry.mesh)
        } else {
            None
        }
    }

    /// Get a reference to a cached mesh, touching it for LRU.
    fn get(&mut self, key: &MeshCacheKey) -> Option<Arc<Mesh>> {
        if self.map.contains_key(key) {
            self.touch(key);
            Some(Arc::clone(&self.map[key].mesh))
        } else {
            None
        }
    }

    /// Clear all entries.
    fn clear(&mut self) {
        self.map.clear();
        self.order.clear();
    }

    /// Number of entries.
    #[inline(always)]
    fn len(&self) -> usize {
        self.map.len()
    }

    /// Total memory usage across all cached meshes.
    fn memory_usage(&self) -> usize {
        self.map.values().map(|e| e.size_bytes).sum()
    }
}

/// Thread-safe LRU mesh cache.
///
/// Stores generated meshes keyed by SDF tree hash, bounds, and resolution.
/// Uses `RwLock` internally so multiple readers can access the cache
/// concurrently, while writes (insert/evict) take exclusive access.
pub struct MeshCache {
    config: CacheConfig,
    entries: RwLock<LruMap>,
}

impl MeshCache {
    /// Create a new mesh cache with the given configuration.
    pub fn new(config: CacheConfig) -> Self {
        Self {
            config,
            entries: RwLock::new(LruMap::new()),
        }
    }

    /// Get a cached mesh by key. Returns `None` if not cached.
    ///
    /// This promotes the entry to most-recently-used position.
    pub fn get(&self, key: &MeshCacheKey) -> Option<Arc<Mesh>> {
        // We need write access because `get` updates LRU order.
        let mut entries = self
            .entries
            .write()
            .expect("MeshCache: RwLock poisoned on entries.write() in get()");
        entries.get(key)
    }

    /// Insert a mesh into the cache, evicting the oldest entry if full.
    ///
    /// Returns an `Arc<Mesh>` pointing to the cached copy.
    pub fn insert(&self, key: MeshCacheKey, mesh: Mesh) -> Arc<Mesh> {
        let size_bytes = estimate_mesh_size(&mesh);
        let arc_mesh = Arc::new(mesh);
        let entry = CacheEntry {
            mesh: Arc::clone(&arc_mesh),
            size_bytes,
        };

        let mut entries = self
            .entries
            .write()
            .expect("MeshCache: RwLock poisoned on entries.write() in insert()");
        let _evicted = entries.insert(key, entry, self.config.max_entries);

        arc_mesh
    }

    /// Remove an entry from the cache.
    pub fn remove(&self, key: &MeshCacheKey) -> Option<Arc<Mesh>> {
        let mut entries = self
            .entries
            .write()
            .expect("MeshCache: RwLock poisoned on entries.write() in remove()");
        entries.remove(key)
    }

    /// Clear all cached meshes.
    pub fn clear(&self) {
        let mut entries = self
            .entries
            .write()
            .expect("MeshCache: RwLock poisoned on entries.write() in clear()");
        entries.clear();
    }

    /// Number of cached entries.
    #[inline(always)]
    pub fn len(&self) -> usize {
        let entries = self
            .entries
            .read()
            .expect("MeshCache: RwLock poisoned on entries.read() in len()");
        entries.len()
    }

    /// Check if the cache is empty.
    #[inline(always)]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Total approximate memory usage of all cached meshes in bytes.
    pub fn memory_usage(&self) -> usize {
        let entries = self
            .entries
            .read()
            .expect("MeshCache: RwLock poisoned on entries.read() in memory_usage()");
        entries.memory_usage()
    }

    /// Get a cached mesh or generate it using the provided closure.
    ///
    /// If the key is found in the cache, returns the cached `Arc<Mesh>`.
    /// Otherwise, calls `generator()` to produce a new mesh, inserts it
    /// into the cache, and returns it.
    ///
    /// **Note**: The generator is called outside the lock to avoid holding
    /// the lock during potentially expensive mesh generation.
    pub fn get_or_generate<F>(&self, key: MeshCacheKey, generator: F) -> Arc<Mesh>
    where
        F: FnOnce() -> Mesh,
    {
        // Fast path: check if already cached.
        {
            let mut entries = self
                .entries
                .write()
                .expect("MeshCache: RwLock poisoned on entries.write() in get_or_generate()");
            if let Some(mesh) = entries.get(&key) {
                return mesh;
            }
        }

        // Slow path: generate mesh outside the lock.
        let mesh = generator();

        // Insert into cache (another thread may have inserted in the meantime).
        let size_bytes = estimate_mesh_size(&mesh);
        let arc_mesh = Arc::new(mesh);
        let entry = CacheEntry {
            mesh: Arc::clone(&arc_mesh),
            size_bytes,
        };

        let mut entries = self
            .entries
            .write()
            .expect("MeshCache: RwLock poisoned on entries.write() in get_or_generate()");
        // Double-check: if another thread inserted while we were generating,
        // return the existing entry instead.
        if let Some(existing) = entries.get(&key) {
            return existing;
        }
        entries.insert(key, entry, self.config.max_entries);

        arc_mesh
    }
}

/// Compute a deterministic hash of an SDF node tree.
///
/// Uses JSON serialization of the node for a stable, content-based hash.
/// The same logical SDF tree will always produce the same hash.
pub fn hash_sdf_node(node: &SdfNode) -> u64 {
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    serde_json::to_string(node)
        .unwrap_or_default()
        .hash(&mut hasher);
    hasher.finish()
}

/// Compute a cache key from an SDF node, bounds, and resolution.
///
/// Bounds are quantized to fixed-point (multiply by 1000, cast to i32) to
/// avoid floating-point comparison issues.
pub fn compute_cache_key(
    node: &SdfNode,
    min_bounds: glam::Vec3,
    max_bounds: glam::Vec3,
    resolution: usize,
) -> MeshCacheKey {
    let sdf_hash = hash_sdf_node(node);
    let bounds_hash = hash_bounds(min_bounds, max_bounds);
    MeshCacheKey {
        sdf_hash,
        resolution: resolution as u32,
        bounds_hash,
    }
}

/// Hash bounds by quantizing floats to fixed-point integers.
#[inline(always)]
fn hash_bounds(min_bounds: glam::Vec3, max_bounds: glam::Vec3) -> u64 {
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    quantize_f32(min_bounds.x).hash(&mut hasher);
    quantize_f32(min_bounds.y).hash(&mut hasher);
    quantize_f32(min_bounds.z).hash(&mut hasher);
    quantize_f32(max_bounds.x).hash(&mut hasher);
    quantize_f32(max_bounds.y).hash(&mut hasher);
    quantize_f32(max_bounds.z).hash(&mut hasher);
    hasher.finish()
}

/// Quantize a float to fixed-point (multiply by 1000, cast to i32).
#[inline(always)]
fn quantize_f32(value: f32) -> i32 {
    (value * 1000.0) as i32
}

/// Estimate the memory footprint of a mesh in bytes.
#[inline(always)]
fn estimate_mesh_size(mesh: &Mesh) -> usize {
    let vertex_size = std::mem::size_of::<crate::mesh::Vertex>();
    mesh.vertices.len() * vertex_size + mesh.indices.len() * std::mem::size_of::<u32>()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::mesh::Vertex;
    use glam::Vec3;

    /// Helper: create a simple test mesh with the given number of vertices and triangles.
    fn make_test_mesh(num_verts: usize, num_tris: usize) -> Mesh {
        let vertices: Vec<Vertex> = (0..num_verts)
            .map(|i| {
                let f = i as f32;
                Vertex::new(Vec3::new(f, f, f), Vec3::Y)
            })
            .collect();
        let indices: Vec<u32> = (0..num_tris * 3).map(|i| (i % num_verts) as u32).collect();
        Mesh { vertices, indices }
    }

    #[test]
    fn test_insert_and_retrieve() {
        let cache = MeshCache::new(CacheConfig {
            max_entries: 4,
            ..Default::default()
        });

        let key = MeshCacheKey {
            sdf_hash: 42,
            resolution: 32,
            bounds_hash: 100,
        };
        let mesh = make_test_mesh(8, 4);
        let expected_verts = mesh.vertices.len();

        cache.insert(key.clone(), mesh);

        let retrieved = cache.get(&key);
        assert!(retrieved.is_some());
        assert_eq!(retrieved.unwrap().vertex_count(), expected_verts);
    }

    #[test]
    fn test_lru_eviction() {
        let cache = MeshCache::new(CacheConfig {
            max_entries: 3,
            ..Default::default()
        });

        // Insert 3 entries (fills cache).
        for i in 0..3u64 {
            let key = MeshCacheKey {
                sdf_hash: i,
                resolution: 16,
                bounds_hash: 0,
            };
            cache.insert(key, make_test_mesh(4, 2));
        }
        assert_eq!(cache.len(), 3);

        // Insert a 4th entry -- should evict key with sdf_hash=0 (oldest).
        let key4 = MeshCacheKey {
            sdf_hash: 99,
            resolution: 16,
            bounds_hash: 0,
        };
        cache.insert(key4, make_test_mesh(4, 2));
        assert_eq!(cache.len(), 3);

        // The oldest (sdf_hash=0) should be evicted.
        let evicted_key = MeshCacheKey {
            sdf_hash: 0,
            resolution: 16,
            bounds_hash: 0,
        };
        assert!(cache.get(&evicted_key).is_none());

        // The rest should still be present.
        for i in 1..3u64 {
            let key = MeshCacheKey {
                sdf_hash: i,
                resolution: 16,
                bounds_hash: 0,
            };
            assert!(cache.get(&key).is_some());
        }
        let key99 = MeshCacheKey {
            sdf_hash: 99,
            resolution: 16,
            bounds_hash: 0,
        };
        assert!(cache.get(&key99).is_some());
    }

    #[test]
    fn test_lru_access_updates_order() {
        let cache = MeshCache::new(CacheConfig {
            max_entries: 3,
            ..Default::default()
        });

        // Insert keys 0, 1, 2.
        for i in 0..3u64 {
            let key = MeshCacheKey {
                sdf_hash: i,
                resolution: 16,
                bounds_hash: 0,
            };
            cache.insert(key, make_test_mesh(4, 2));
        }

        // Access key 0 to make it most-recently-used.
        let key0 = MeshCacheKey {
            sdf_hash: 0,
            resolution: 16,
            bounds_hash: 0,
        };
        assert!(cache.get(&key0).is_some());

        // Insert key 3 -- should evict key 1 (now the oldest).
        let key3 = MeshCacheKey {
            sdf_hash: 3,
            resolution: 16,
            bounds_hash: 0,
        };
        cache.insert(key3, make_test_mesh(4, 2));

        let evicted_key = MeshCacheKey {
            sdf_hash: 1,
            resolution: 16,
            bounds_hash: 0,
        };
        assert!(cache.get(&evicted_key).is_none());

        // Key 0 should still be present (was touched).
        assert!(cache.get(&key0).is_some());
    }

    #[test]
    fn test_get_or_generate_caches() {
        let cache = MeshCache::new(CacheConfig::default());
        let key = MeshCacheKey {
            sdf_hash: 1,
            resolution: 16,
            bounds_hash: 0,
        };

        let call_count = std::sync::atomic::AtomicU32::new(0);

        // First call: generator runs.
        let mesh1 = cache.get_or_generate(key.clone(), || {
            call_count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            make_test_mesh(10, 5)
        });
        assert_eq!(call_count.load(std::sync::atomic::Ordering::SeqCst), 1);
        assert_eq!(mesh1.vertex_count(), 10);

        // Second call: generator should NOT run.
        let mesh2 = cache.get_or_generate(key, || {
            call_count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            make_test_mesh(20, 10)
        });
        assert_eq!(call_count.load(std::sync::atomic::Ordering::SeqCst), 1);
        assert_eq!(mesh2.vertex_count(), 10); // Same mesh as first call.
    }

    #[test]
    fn test_cache_key_determinism() {
        let node = SdfNode::sphere(1.0);
        let hash1 = hash_sdf_node(&node);
        let hash2 = hash_sdf_node(&node);
        assert_eq!(hash1, hash2, "Same SDF tree must produce the same hash");

        // Different tree should (very likely) produce different hash.
        let node2 = SdfNode::sphere(2.0);
        let hash3 = hash_sdf_node(&node2);
        assert_ne!(
            hash1, hash3,
            "Different SDF trees should produce different hashes"
        );
    }

    #[test]
    fn test_compute_cache_key_determinism() {
        let node = SdfNode::sphere(1.0).subtract(SdfNode::box3d(0.5, 0.5, 0.5));
        let min = Vec3::splat(-2.0);
        let max = Vec3::splat(2.0);

        let key1 = compute_cache_key(&node, min, max, 32);
        let key2 = compute_cache_key(&node, min, max, 32);
        assert_eq!(key1, key2);

        // Different resolution => different key.
        let key3 = compute_cache_key(&node, min, max, 64);
        assert_ne!(key1, key3);

        // Different bounds => different key.
        let key4 = compute_cache_key(&node, Vec3::splat(-3.0), max, 32);
        assert_ne!(key1, key4);
    }

    #[test]
    fn test_thread_safety_concurrent_reads() {
        use std::sync::Arc as StdArc;

        let cache = StdArc::new(MeshCache::new(CacheConfig {
            max_entries: 16,
            ..Default::default()
        }));

        // Pre-populate.
        for i in 0..8u64 {
            let key = MeshCacheKey {
                sdf_hash: i,
                resolution: 16,
                bounds_hash: 0,
            };
            cache.insert(key, make_test_mesh(4, 2));
        }

        // Spawn threads that all read concurrently.
        let mut handles = Vec::new();
        for i in 0..8u64 {
            let cache_clone = StdArc::clone(&cache);
            handles.push(std::thread::spawn(move || {
                let key = MeshCacheKey {
                    sdf_hash: i,
                    resolution: 16,
                    bounds_hash: 0,
                };
                let result = cache_clone.get(&key);
                assert!(result.is_some(), "Key {} should be in cache", i);
                result.unwrap().vertex_count()
            }));
        }

        for handle in handles {
            let count = handle.join().unwrap();
            assert_eq!(count, 4);
        }
    }

    #[test]
    fn test_clear() {
        let cache = MeshCache::new(CacheConfig::default());
        let key = MeshCacheKey {
            sdf_hash: 1,
            resolution: 16,
            bounds_hash: 0,
        };
        cache.insert(key.clone(), make_test_mesh(4, 2));
        assert_eq!(cache.len(), 1);

        cache.clear();
        assert_eq!(cache.len(), 0);
        assert!(cache.is_empty());
        assert!(cache.get(&key).is_none());
    }

    #[test]
    fn test_remove() {
        let cache = MeshCache::new(CacheConfig::default());

        let key1 = MeshCacheKey {
            sdf_hash: 1,
            resolution: 16,
            bounds_hash: 0,
        };
        let key2 = MeshCacheKey {
            sdf_hash: 2,
            resolution: 16,
            bounds_hash: 0,
        };
        cache.insert(key1.clone(), make_test_mesh(4, 2));
        cache.insert(key2.clone(), make_test_mesh(8, 4));
        assert_eq!(cache.len(), 2);

        let removed = cache.remove(&key1);
        assert!(removed.is_some());
        assert_eq!(removed.unwrap().vertex_count(), 4);
        assert_eq!(cache.len(), 1);
        assert!(cache.get(&key1).is_none());
        assert!(cache.get(&key2).is_some());

        // Remove non-existent key.
        let removed_none = cache.remove(&key1);
        assert!(removed_none.is_none());
    }

    #[test]
    fn test_memory_usage() {
        let cache = MeshCache::new(CacheConfig::default());

        let key = MeshCacheKey {
            sdf_hash: 1,
            resolution: 16,
            bounds_hash: 0,
        };
        let mesh = make_test_mesh(100, 50);
        let expected_size = mesh.vertices.len() * std::mem::size_of::<Vertex>()
            + mesh.indices.len() * std::mem::size_of::<u32>();

        cache.insert(key, mesh);

        assert_eq!(cache.memory_usage(), expected_size);
    }

    #[test]
    fn test_empty_cache() {
        let cache = MeshCache::new(CacheConfig::default());
        assert!(cache.is_empty());
        assert_eq!(cache.len(), 0);
        assert_eq!(cache.memory_usage(), 0);
    }

    #[test]
    fn test_insert_duplicate_key_updates() {
        let cache = MeshCache::new(CacheConfig {
            max_entries: 4,
            ..Default::default()
        });

        let key = MeshCacheKey {
            sdf_hash: 42,
            resolution: 32,
            bounds_hash: 100,
        };

        cache.insert(key.clone(), make_test_mesh(4, 2));
        assert_eq!(cache.len(), 1);

        // Insert with same key but different mesh.
        cache.insert(key.clone(), make_test_mesh(16, 8));
        assert_eq!(cache.len(), 1); // Should not increase count.

        let retrieved = cache.get(&key).unwrap();
        assert_eq!(retrieved.vertex_count(), 16); // Should be the updated mesh.
    }
}