alice-sdf 6.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
//! Chunked incremental mesh cache (Deep Fried Edition)
//!
//! Provides spatial partitioning of SDF evaluation space into chunks.
//! Only dirty chunks are re-meshed when the SDF changes, enabling
//! incremental updates for real-time editing workflows.
//!
//! # Design
//! - Space is divided into a uniform grid of chunks
//! - Each chunk is independently meshable
//! - Dirty tracking: only modified chunks are re-generated
//! - Chunk meshes can be persisted individually as .abm files
//!
//! Author: Moroya Sakamoto

use crate::io::abm::{load_abm, save_abm};
use crate::io::IoError;
use crate::mesh::{Mesh, Vertex};
use glam::Vec3;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::{Arc, RwLock};

// ---------------------------------------------------------------------------
// ChunkCoord
// ---------------------------------------------------------------------------

/// 3D chunk coordinate in the spatial grid.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ChunkCoord {
    /// X index
    pub x: i32,
    /// Y index
    pub y: i32,
    /// Z index
    pub z: i32,
}

impl ChunkCoord {
    /// Create a new chunk coordinate.
    #[inline(always)]
    pub const fn new(x: i32, y: i32, z: i32) -> Self {
        Self { x, y, z }
    }
}

impl std::fmt::Display for ChunkCoord {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "({}, {}, {})", self.x, self.y, self.z)
    }
}

// ---------------------------------------------------------------------------
// ChunkedCacheConfig
// ---------------------------------------------------------------------------

/// Configuration for the chunked mesh cache.
#[derive(Debug, Clone)]
pub struct ChunkedCacheConfig {
    /// Size of each chunk in world units.
    pub chunk_size: f32,
    /// Resolution (voxels per axis) used when meshing a single chunk.
    pub chunk_resolution: usize,
    /// Optional disk persistence directory for `.abm` files.
    pub cache_dir: Option<PathBuf>,
    /// Maximum number of chunk meshes kept in memory.
    pub max_cached_chunks: usize,
}

impl Default for ChunkedCacheConfig {
    fn default() -> Self {
        Self {
            chunk_size: 1.0,
            chunk_resolution: 32,
            cache_dir: None,
            max_cached_chunks: 512,
        }
    }
}

// ---------------------------------------------------------------------------
// Internal: ChunkEntry
// ---------------------------------------------------------------------------

/// A single cached chunk entry.
struct ChunkEntry {
    /// The generated mesh for this chunk.
    mesh: Arc<Mesh>,
    /// Hash of the SDF at the time this mesh was generated.
    sdf_hash: u64,
    /// Whether this entry has been modified since last persist.
    dirty: bool,
}

/// Internal storage combining entries with insertion-order tracking for FIFO eviction.
struct ChunkedStore {
    entries: HashMap<ChunkCoord, ChunkEntry>,
    /// Insertion order: oldest at front, newest at back.
    order: Vec<ChunkCoord>,
}

// ---------------------------------------------------------------------------
// ChunkedMeshCache
// ---------------------------------------------------------------------------

/// Thread-safe chunked incremental mesh cache.
///
/// Divides the SDF evaluation space into a uniform grid of chunks. Each
/// chunk is independently cached and can be marked dirty when the underlying
/// SDF changes — either globally or within a specific region.
pub struct ChunkedMeshCache {
    config: ChunkedCacheConfig,
    chunks: RwLock<ChunkedStore>,
    /// Current global SDF hash used for invalidation.
    current_sdf_hash: RwLock<u64>,
}

impl ChunkedMeshCache {
    /// Create a new chunked mesh cache.
    pub fn new(config: ChunkedCacheConfig) -> Self {
        Self {
            config,
            chunks: RwLock::new(ChunkedStore {
                entries: HashMap::new(),
                order: Vec::new(),
            }),
            current_sdf_hash: RwLock::new(0),
        }
    }

    // -- Query ---------------------------------------------------------------

    /// Get the chunk mesh at the given coordinate, if cached and valid.
    pub fn get_chunk(&self, coord: &ChunkCoord) -> Option<Arc<Mesh>> {
        let chunks = self
            .chunks
            .read()
            .expect("ChunkedMeshCache: RwLock poisoned on chunks.read() in get_chunk()");
        chunks.entries.get(coord).map(|e| Arc::clone(&e.mesh))
    }

    /// Insert or update a chunk mesh.
    ///
    /// Uses FIFO eviction: when at capacity, the oldest-inserted chunk is
    /// removed first — deterministic and cache-friendly compared to random.
    pub fn set_chunk(&self, coord: ChunkCoord, mesh: Mesh, sdf_hash: u64) {
        let mut chunks = self
            .chunks
            .write()
            .expect("ChunkedMeshCache: RwLock poisoned on chunks.write() in set_chunk()");

        // FIFO eviction: remove the oldest entry when at capacity.
        if chunks.entries.len() >= self.config.max_cached_chunks
            && !chunks.entries.contains_key(&coord)
        {
            if let Some(evict_key) = chunks.order.first().copied() {
                chunks.entries.remove(&evict_key);
                chunks.order.remove(0);
            }
        }

        // If updating an existing entry, remove old position from order.
        if chunks.entries.contains_key(&coord) {
            if let Some(pos) = chunks.order.iter().position(|c| *c == coord) {
                chunks.order.remove(pos);
            }
        }

        chunks.entries.insert(
            coord,
            ChunkEntry {
                mesh: Arc::new(mesh),
                sdf_hash,
                dirty: true,
            },
        );
        chunks.order.push(coord);
    }

    // -- Invalidation --------------------------------------------------------

    /// Mark **all** chunks as dirty (e.g. the SDF changed globally).
    pub fn invalidate_all(&self) {
        let mut chunks = self
            .chunks
            .write()
            .expect("ChunkedMeshCache: RwLock poisoned on chunks.write() in invalidate_all()");
        for entry in chunks.entries.values_mut() {
            entry.dirty = true;
        }
    }

    /// Mark chunks overlapping a world-space bounding box as dirty.
    pub fn invalidate_region(&self, min: Vec3, max: Vec3) {
        let coords = self.chunks_in_bounds(min, max);
        let mut chunks = self
            .chunks
            .write()
            .expect("ChunkedMeshCache: RwLock poisoned on chunks.write() in invalidate_region()");
        for c in &coords {
            if let Some(entry) = chunks.entries.get_mut(c) {
                entry.dirty = true;
            }
        }
    }

    /// Get the coordinates of all currently dirty chunks.
    pub fn dirty_chunks(&self) -> Vec<ChunkCoord> {
        let chunks = self
            .chunks
            .read()
            .expect("ChunkedMeshCache: RwLock poisoned on chunks.read() in dirty_chunks()");
        chunks
            .entries
            .iter()
            .filter(|(_, e)| e.dirty)
            .map(|(&c, _)| c)
            .collect()
    }

    /// Update the global SDF hash. Returns the list of chunks that were
    /// invalidated (those whose stored hash differs from `new_hash`).
    #[allow(clippy::significant_drop_tightening)]
    pub fn update_sdf_hash(&self, new_hash: u64) -> Vec<ChunkCoord> {
        {
            let mut h = self.current_sdf_hash.write()
                .expect("ChunkedMeshCache: RwLock poisoned on current_sdf_hash.write() in update_sdf_hash()");
            *h = new_hash;
        }

        let mut invalidated = Vec::new();
        let mut chunks = self
            .chunks
            .write()
            .expect("ChunkedMeshCache: RwLock poisoned on chunks.write() in update_sdf_hash()");
        for (&coord, entry) in chunks.entries.iter_mut() {
            if entry.sdf_hash != new_hash {
                entry.dirty = true;
                invalidated.push(coord);
            }
        }
        invalidated
    }

    // -- Enumeration ---------------------------------------------------------

    /// Get all cached chunk coordinates.
    pub fn cached_chunks(&self) -> Vec<ChunkCoord> {
        let chunks = self
            .chunks
            .read()
            .expect("ChunkedMeshCache: RwLock poisoned on chunks.read() in cached_chunks()");
        chunks.entries.keys().copied().collect()
    }

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

    /// Total approximate memory usage of all cached chunk meshes (bytes).
    pub fn memory_usage(&self) -> usize {
        let chunks = self
            .chunks
            .read()
            .expect("ChunkedMeshCache: RwLock poisoned on chunks.read() in memory_usage()");
        chunks
            .entries
            .values()
            .map(|e| estimate_mesh_bytes(&e.mesh))
            .sum()
    }

    // -- Coordinate helpers --------------------------------------------------

    /// Convert a world-space position to its containing chunk coordinate.
    #[inline]
    pub fn world_to_chunk(&self, pos: Vec3) -> ChunkCoord {
        let s = self.config.chunk_size;
        ChunkCoord {
            x: pos.x.div_euclid(s).floor() as i32,
            y: pos.y.div_euclid(s).floor() as i32,
            z: pos.z.div_euclid(s).floor() as i32,
        }
    }

    /// Get the axis-aligned bounding box `(min, max)` for a chunk coordinate.
    #[inline]
    pub fn chunk_bounds(&self, coord: &ChunkCoord) -> (Vec3, Vec3) {
        let s = self.config.chunk_size;
        let min = Vec3::new(coord.x as f32 * s, coord.y as f32 * s, coord.z as f32 * s);
        let max = min + Vec3::splat(s);
        (min, max)
    }

    /// Compute all chunk coordinates required to cover the given bounding box.
    pub fn chunks_in_bounds(&self, min: Vec3, max: Vec3) -> Vec<ChunkCoord> {
        let lo = self.world_to_chunk(min);
        let hi = self.world_to_chunk(max);
        let mut coords = Vec::new();
        for x in lo.x..=hi.x {
            for y in lo.y..=hi.y {
                for z in lo.z..=hi.z {
                    coords.push(ChunkCoord::new(x, y, z));
                }
            }
        }
        coords
    }

    // -- Persistence ---------------------------------------------------------

    /// Persist all dirty chunks to disk as individual `.abm` files.
    ///
    /// Requires `cache_dir` to be set in the configuration. Returns the
    /// number of chunks written.
    #[allow(clippy::significant_drop_tightening)]
    pub fn persist_dirty(&self) -> Result<usize, IoError> {
        let dir = self.config.cache_dir.as_ref().ok_or_else(|| {
            IoError::Io(std::io::Error::new(
                std::io::ErrorKind::NotFound,
                "cache_dir not configured",
            ))
        })?;
        std::fs::create_dir_all(dir)?;

        let mut chunks = self
            .chunks
            .write()
            .expect("ChunkedMeshCache: RwLock poisoned on chunks.write() in persist_dirty()");
        let mut written = 0usize;
        for (&coord, entry) in chunks.entries.iter_mut() {
            if entry.dirty {
                let path = dir.join(format!("{}_{}_{}_.abm", coord.x, coord.y, coord.z));
                save_abm(&entry.mesh, &path)?;
                entry.dirty = false;
                written += 1;
            }
        }
        Ok(written)
    }

    /// Load a single chunk from the disk cache. Returns `None` if the file
    /// does not exist. A chunk that is not cached yet is added at the back of
    /// the FIFO order, evicting the oldest chunk when the cache is full.
    #[allow(clippy::significant_drop_tightening)]
    pub fn load_chunk(&self, coord: &ChunkCoord) -> Result<Option<Arc<Mesh>>, IoError> {
        let dir = self.config.cache_dir.as_ref().ok_or_else(|| {
            IoError::Io(std::io::Error::new(
                std::io::ErrorKind::NotFound,
                "cache_dir not configured",
            ))
        })?;
        let path = dir.join(format!("{}_{}_{}_.abm", coord.x, coord.y, coord.z));
        if !path.exists() {
            return Ok(None);
        }
        let mesh = load_abm(&path)?;
        let sdf_hash = *self
            .current_sdf_hash
            .read()
            .expect("ChunkedMeshCache: RwLock poisoned on current_sdf_hash.read() in load_chunk()");
        let arc = Arc::new(mesh);

        let mut chunks = self
            .chunks
            .write()
            .expect("ChunkedMeshCache: RwLock poisoned on chunks.write() in load_chunk()");
        let is_new = !chunks.entries.contains_key(coord);
        // Same FIFO eviction as `set_chunk`: a reloaded chunk must not push the
        // cache past `max_cached_chunks`.
        if is_new && chunks.entries.len() >= self.config.max_cached_chunks {
            if let Some(evict_key) = chunks.order.first().copied() {
                chunks.entries.remove(&evict_key);
                chunks.order.remove(0);
            }
        }
        chunks.entries.insert(
            *coord,
            ChunkEntry {
                mesh: Arc::clone(&arc),
                sdf_hash,
                dirty: false,
            },
        );
        if is_new {
            chunks.order.push(*coord);
        }
        Ok(Some(arc))
    }

    // -- Bulk operations -----------------------------------------------------

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

    /// Merge all cached chunk meshes into a single combined [`Mesh`].
    ///
    /// Vertex positions are preserved in world space. Index offsets are
    /// adjusted so the resulting mesh is self-consistent.
    ///
    /// Chunks are concatenated in ascending `(x, y, z)` order of their
    /// [`ChunkCoord`], so the same set of chunks always gives the same vertex
    /// and index order, whatever the insertion order and from one run to the
    /// next (until 5.0.0 the order was that of the internal `HashMap`, which
    /// changes between runs).
    #[allow(clippy::significant_drop_tightening)]
    pub fn merge_all(&self) -> Mesh {
        let chunks = self
            .chunks
            .read()
            .expect("ChunkedMeshCache: RwLock poisoned on chunks.read() in merge_all()");
        let mut ordered: Vec<(&ChunkCoord, &ChunkEntry)> = chunks.entries.iter().collect();
        ordered.sort_unstable_by_key(|(c, _)| (c.x, c.y, c.z));
        let mut vertices: Vec<Vertex> = Vec::new();
        let mut indices: Vec<u32> = Vec::new();
        for (_, entry) in ordered {
            let base = vertices.len() as u32;
            vertices.extend_from_slice(&entry.mesh.vertices);
            indices.extend(entry.mesh.indices.iter().map(|&i| i + base));
        }
        Mesh { vertices, indices }
    }
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

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

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    /// Helper: create a simple test mesh.
    fn make_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_world_to_chunk_positive() {
        let cache = ChunkedMeshCache::new(ChunkedCacheConfig {
            chunk_size: 2.0,
            ..Default::default()
        });
        let c = cache.world_to_chunk(Vec3::new(3.5, 1.0, 5.9));
        assert_eq!(c, ChunkCoord::new(1, 0, 2));
    }

    #[test]
    fn test_world_to_chunk_negative() {
        let cache = ChunkedMeshCache::new(ChunkedCacheConfig {
            chunk_size: 1.0,
            ..Default::default()
        });
        let c = cache.world_to_chunk(Vec3::new(-0.5, -1.5, -0.01));
        assert_eq!(c, ChunkCoord::new(-1, -2, -1));
    }

    #[test]
    fn test_world_to_chunk_on_boundary() {
        let cache = ChunkedMeshCache::new(ChunkedCacheConfig {
            chunk_size: 1.0,
            ..Default::default()
        });
        // Exactly on a boundary should map to the lower chunk.
        let c = cache.world_to_chunk(Vec3::new(1.0, 0.0, -1.0));
        assert_eq!(c, ChunkCoord::new(1, 0, -1));
    }

    #[test]
    fn test_chunk_bounds() {
        let cache = ChunkedMeshCache::new(ChunkedCacheConfig {
            chunk_size: 2.0,
            ..Default::default()
        });
        let (min, max) = cache.chunk_bounds(&ChunkCoord::new(1, -1, 0));
        assert!((min.x - 2.0).abs() < 1e-6);
        assert!((min.y - (-2.0)).abs() < 1e-6);
        assert!((min.z - 0.0).abs() < 1e-6);
        assert!((max.x - 4.0).abs() < 1e-6);
        assert!((max.y - 0.0).abs() < 1e-6);
        assert!((max.z - 2.0).abs() < 1e-6);
    }

    #[test]
    fn test_chunks_in_bounds() {
        let cache = ChunkedMeshCache::new(ChunkedCacheConfig {
            chunk_size: 1.0,
            ..Default::default()
        });
        let coords = cache.chunks_in_bounds(Vec3::new(0.0, 0.0, 0.0), Vec3::new(1.5, 0.5, 0.5));
        // Should cover (0,0,0) and (1,0,0)
        assert!(coords.contains(&ChunkCoord::new(0, 0, 0)));
        assert!(coords.contains(&ChunkCoord::new(1, 0, 0)));
    }

    #[test]
    fn test_insert_and_get() {
        let cache = ChunkedMeshCache::new(ChunkedCacheConfig::default());
        let coord = ChunkCoord::new(0, 0, 0);
        let mesh = make_mesh(4, 2);

        cache.set_chunk(coord, mesh, 42);
        let retrieved = cache.get_chunk(&coord);
        assert!(retrieved.is_some());
        assert_eq!(retrieved.unwrap().vertex_count(), 4);
    }

    #[test]
    fn test_get_missing_returns_none() {
        let cache = ChunkedMeshCache::new(ChunkedCacheConfig::default());
        assert!(cache.get_chunk(&ChunkCoord::new(99, 99, 99)).is_none());
    }

    #[test]
    fn test_invalidate_region() {
        let cache = ChunkedMeshCache::new(ChunkedCacheConfig {
            chunk_size: 1.0,
            ..Default::default()
        });

        // Insert several chunks and mark them clean.
        for x in 0..3 {
            for z in 0..3 {
                cache.set_chunk(ChunkCoord::new(x, 0, z), make_mesh(4, 2), 1);
            }
        }
        // Manually mark all clean first.
        {
            let mut chunks = cache.chunks.write().unwrap();
            for e in chunks.entries.values_mut() {
                e.dirty = false;
            }
        }

        // Invalidate a region covering chunk (1,0,1) only.
        cache.invalidate_region(Vec3::new(1.1, 0.0, 1.1), Vec3::new(1.9, 0.9, 1.9));

        let dirty = cache.dirty_chunks();
        assert_eq!(dirty.len(), 1);
        assert_eq!(dirty[0], ChunkCoord::new(1, 0, 1));
    }

    #[test]
    fn test_invalidate_all() {
        let cache = ChunkedMeshCache::new(ChunkedCacheConfig::default());
        cache.set_chunk(ChunkCoord::new(0, 0, 0), make_mesh(4, 2), 1);
        cache.set_chunk(ChunkCoord::new(1, 0, 0), make_mesh(4, 2), 1);
        // Mark clean.
        {
            let mut chunks = cache.chunks.write().unwrap();
            for e in chunks.entries.values_mut() {
                e.dirty = false;
            }
        }
        assert_eq!(cache.dirty_chunks().len(), 0);

        cache.invalidate_all();
        assert_eq!(cache.dirty_chunks().len(), 2);
    }

    #[test]
    fn test_merge_all() {
        let cache = ChunkedMeshCache::new(ChunkedCacheConfig::default());
        // Chunk A: 4 verts, indices [0,1,2, 1,2,3]
        let mut mesh_a = make_mesh(4, 0);
        mesh_a.indices = vec![0, 1, 2, 1, 2, 3];
        cache.set_chunk(ChunkCoord::new(0, 0, 0), mesh_a, 1);

        // Chunk B: 3 verts, indices [0,1,2]
        let mut mesh_b = make_mesh(3, 0);
        mesh_b.indices = vec![0, 1, 2];
        cache.set_chunk(ChunkCoord::new(1, 0, 0), mesh_b, 1);

        let merged = cache.merge_all();
        assert_eq!(merged.vertices.len(), 7); // 4 + 3
        assert_eq!(merged.indices.len(), 9); // 6 + 3

        // Indices from chunk B should be offset by 4 (or by the vertex count
        // of whatever chunk was iterated first -- HashMap order is unspecified).
        // Just verify all indices are in-bounds.
        for &idx in &merged.indices {
            assert!((idx as usize) < merged.vertices.len());
        }
    }

    #[test]
    fn test_memory_usage() {
        let cache = ChunkedMeshCache::new(ChunkedCacheConfig::default());
        assert_eq!(cache.memory_usage(), 0);

        let mesh = make_mesh(10, 4);
        let expected = 10 * std::mem::size_of::<Vertex>() + 12 * std::mem::size_of::<u32>();
        cache.set_chunk(ChunkCoord::new(0, 0, 0), mesh, 1);
        assert_eq!(cache.memory_usage(), expected);
    }

    #[test]
    fn test_update_sdf_hash_invalidation() {
        let cache = ChunkedMeshCache::new(ChunkedCacheConfig::default());
        cache.set_chunk(ChunkCoord::new(0, 0, 0), make_mesh(4, 2), 10);
        cache.set_chunk(ChunkCoord::new(1, 0, 0), make_mesh(4, 2), 10);
        cache.set_chunk(ChunkCoord::new(2, 0, 0), make_mesh(4, 2), 20);
        // Mark clean.
        {
            let mut chunks = cache.chunks.write().unwrap();
            for e in chunks.entries.values_mut() {
                e.dirty = false;
            }
        }

        // Update hash to 20 — chunks with hash 10 should be invalidated.
        let invalidated = cache.update_sdf_hash(20);
        assert_eq!(invalidated.len(), 2);
        // Chunk (2,0,0) already matches hash 20, so NOT invalidated.
        assert!(!invalidated.contains(&ChunkCoord::new(2, 0, 0)));
    }

    #[test]
    fn test_clear() {
        let cache = ChunkedMeshCache::new(ChunkedCacheConfig::default());
        cache.set_chunk(ChunkCoord::new(0, 0, 0), make_mesh(4, 2), 1);
        cache.set_chunk(ChunkCoord::new(1, 0, 0), make_mesh(4, 2), 1);
        assert_eq!(cache.chunk_count(), 2);

        cache.clear();
        assert_eq!(cache.chunk_count(), 0);
        assert!(cache.get_chunk(&ChunkCoord::new(0, 0, 0)).is_none());
    }

    #[test]
    fn test_cached_chunks() {
        let cache = ChunkedMeshCache::new(ChunkedCacheConfig::default());
        cache.set_chunk(ChunkCoord::new(0, 0, 0), make_mesh(4, 2), 1);
        cache.set_chunk(ChunkCoord::new(1, 2, 3), make_mesh(4, 2), 1);

        let cached = cache.cached_chunks();
        assert_eq!(cached.len(), 2);
        assert!(cached.contains(&ChunkCoord::new(0, 0, 0)));
        assert!(cached.contains(&ChunkCoord::new(1, 2, 3)));
    }

    #[test]
    fn test_persist_dirty_and_load_chunk() {
        let dir = std::env::temp_dir().join("alice_sdf_chunked_test");
        let _ = std::fs::remove_dir_all(&dir);

        let config = ChunkedCacheConfig {
            cache_dir: Some(dir.clone()),
            ..Default::default()
        };
        let cache = ChunkedMeshCache::new(config);

        // Insert a mesh and persist.
        let coord = ChunkCoord::new(1, -2, 3);
        cache.set_chunk(coord, make_mesh(6, 3), 42);
        let written = cache.persist_dirty().unwrap();
        assert_eq!(written, 1);

        // Dirty should now be empty.
        assert_eq!(cache.dirty_chunks().len(), 0);

        // Create a fresh cache and load from disk.
        let config2 = ChunkedCacheConfig {
            cache_dir: Some(dir.clone()),
            ..Default::default()
        };
        let cache2 = ChunkedMeshCache::new(config2);
        let loaded = cache2.load_chunk(&coord).unwrap();
        assert!(loaded.is_some());
        assert_eq!(loaded.unwrap().vertex_count(), 6);

        // Cleanup.
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn test_persist_without_cache_dir_errors() {
        let cache = ChunkedMeshCache::new(ChunkedCacheConfig {
            cache_dir: None,
            ..Default::default()
        });
        cache.set_chunk(ChunkCoord::new(0, 0, 0), make_mesh(4, 2), 1);
        assert!(cache.persist_dirty().is_err());
    }

    #[test]
    fn test_max_cached_chunks_eviction() {
        let cache = ChunkedMeshCache::new(ChunkedCacheConfig {
            max_cached_chunks: 3,
            ..Default::default()
        });
        for i in 0..5 {
            cache.set_chunk(ChunkCoord::new(i, 0, 0), make_mesh(4, 2), 1);
        }
        // Should never exceed max.
        assert!(cache.chunk_count() <= 3);
    }
}