voxel-framework 0.10.0

A reusable voxel engine framework built on Bevy
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
//! Integration tests for voxel-framework.
//!
//! Tests pure logic without spinning up a Bevy App (no display required).

use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};

use bevy::ecs::message::{MessageReader, MessageWriter};
use bevy::math::{IVec3, Vec3};
use bevy::mesh::VertexAttributeValues;
use bevy::mesh::{Indices, Mesh};
use bevy::prelude::{
    App, IntoScheduleConfigs, MinimalPlugins, Query, Res, ResMut, Resource, Update,
};

use voxel_framework::chunk::persistence::{chunk_filename, save_chunk};
use voxel_framework::chunk::{CHUNK_SIZE, Chunk};
use voxel_framework::generator::asteroid::{AsteroidConfig, AsteroidGenerator};
use voxel_framework::generator::{ChunkGenerator, GeneratorPlugin};
use voxel_framework::mesh::lod::{compute_lod, lod_to_step};
use voxel_framework::mesh::{
    ChunkNeighbors, generate_chunk_mesh, generate_chunk_mesh_with_neighbors,
};
use voxel_framework::noise::fbm;
use voxel_framework::voxel::{DefaultVoxel, VoxelType};
use voxel_framework::world::{
    ChunkLoadRequest, ChunkManager, ChunkModified, MiningConfig, MiningPlugin, MiningProgress,
    MiningState, PersistenceConfig, ViewerPosition, VoxelBroken, WorldPlugin, tick_mining,
};

// ── Helpers ──────────────────────────────────────────────────────────────────

fn vertex_count(mesh: &Mesh) -> usize {
    match mesh
        .attribute(Mesh::ATTRIBUTE_POSITION)
        .expect("mesh has no ATTRIBUTE_POSITION")
    {
        VertexAttributeValues::Float32x3(v) => v.len(),
        _ => panic!("unexpected position attribute type"),
    }
}

fn index_count(mesh: &Mesh) -> usize {
    match mesh.indices().expect("mesh has no indices") {
        Indices::U32(idx) => idx.len(),
        _ => panic!("expected U32 indices"),
    }
}

fn fill_chunk(voxel: DefaultVoxel) -> Chunk<DefaultVoxel> {
    let mut chunk = Chunk::<DefaultVoxel>::new();
    for x in 0..CHUNK_SIZE {
        for y in 0..CHUNK_SIZE {
            for z in 0..CHUNK_SIZE {
                chunk.set(x, y, z, voxel);
            }
        }
    }
    chunk
}

fn solid_count(chunk: &Chunk<DefaultVoxel>) -> usize {
    (0..CHUNK_SIZE)
        .flat_map(|x| (0..CHUNK_SIZE).flat_map(move |y| (0..CHUNK_SIZE).map(move |z| (x, y, z))))
        .filter(|&(x, y, z)| chunk.is_solid_at(x, y, z))
        .count()
}

#[derive(Resource, Default)]
struct ObservedLoadRequests(Vec<IVec3>);

fn record_load_requests(
    mut reader: MessageReader<ChunkLoadRequest>,
    mut observed: ResMut<ObservedLoadRequests>,
) {
    observed.0.extend(reader.read().map(|request| request.0));
}

#[derive(Resource, Default)]
struct ObservedBrokenBytes(Vec<u8>);

fn mine_origin_once(
    mut state: ResMut<MiningState>,
    config: Res<MiningConfig>,
    manager: Res<ChunkManager>,
    mut chunks: Query<&mut Chunk<DefaultVoxel>>,
    mut broken: MessageWriter<VoxelBroken>,
    mut progress: MessageWriter<MiningProgress>,
    mut modified: MessageWriter<ChunkModified>,
) {
    tick_mining(
        IVec3::ZERO,
        (0, 0, 0),
        99.0,
        &mut state,
        &config,
        &manager,
        &mut chunks,
        &mut broken,
        &mut progress,
        &mut modified,
    );
}

fn record_broken_bytes(
    mut reader: MessageReader<VoxelBroken>,
    mut observed: ResMut<ObservedBrokenBytes>,
) {
    observed
        .0
        .extend(reader.read().map(|event| event.voxel_byte));
}

struct CountingGenerator {
    calls: Arc<AtomicUsize>,
}

impl ChunkGenerator<DefaultVoxel> for CountingGenerator {
    fn generate(&self, _coord: IVec3, chunk: &mut Chunk<DefaultVoxel>) {
        self.calls.fetch_add(1, Ordering::SeqCst);
        chunk.set(0, 0, 0, DefaultVoxel::IronOre);
    }
}

fn unique_temp_chunk_dir(test_name: &str) -> PathBuf {
    std::env::temp_dir().join(format!(
        "voxel_framework_{test_name}_{}",
        std::process::id()
    ))
}

// ── 1. Chunk + Voxel roundtrip ────────────────────────────────────────────────

#[test]
fn chunk_fill_and_read() {
    let chunk = fill_chunk(DefaultVoxel::Rock);
    for x in 0..CHUNK_SIZE {
        for y in 0..CHUNK_SIZE {
            for z in 0..CHUNK_SIZE {
                assert_eq!(
                    chunk.get(x, y, z),
                    DefaultVoxel::Rock,
                    "expected Rock at ({x}, {y}, {z})"
                );
            }
        }
    }
}

#[test]
fn chunk_is_fully_solid_after_fill() {
    let chunk = fill_chunk(DefaultVoxel::Rock);
    assert!(
        chunk.is_fully_solid(),
        "fully filled chunk must report is_fully_solid"
    );
    assert!(
        !chunk.is_empty(),
        "fully filled chunk must not report is_empty"
    );
}

#[test]
fn chunk_is_empty_on_new() {
    let chunk = Chunk::<DefaultVoxel>::new();
    assert!(chunk.is_empty(), "new chunk must be empty");
    assert!(!chunk.is_fully_solid(), "new chunk must not be fully solid");
}

// ── 2. Mesh generation ────────────────────────────────────────────────────────

#[test]
fn empty_chunk_produces_no_geometry() {
    let chunk = Chunk::<DefaultVoxel>::new();
    let mesh = generate_chunk_mesh(&chunk, 1);
    assert_eq!(
        vertex_count(&mesh),
        0,
        "air-only chunk should produce 0 vertices"
    );
}

#[test]
fn single_voxel_produces_6_faces() {
    let mut chunk = Chunk::<DefaultVoxel>::new();
    chunk.set(0, 0, 0, DefaultVoxel::Rock);
    let mesh = generate_chunk_mesh(&chunk, 1);

    // 4 vertices per face × 6 faces = 24 vertices
    assert_eq!(
        vertex_count(&mesh),
        24,
        "single voxel should produce 24 vertices (4 per face × 6 faces)"
    );
    // 6 indices per face × 6 faces = 36 indices
    assert_eq!(
        index_count(&mesh),
        36,
        "single voxel should produce 36 indices (6 per face × 6 faces)"
    );
}

#[test]
fn full_chunk_only_has_outer_faces() {
    // Greedy meshing merges the entire surface of a uniform solid chunk into
    // one quad per face direction — 6 quads total.
    let chunk = fill_chunk(DefaultVoxel::Rock);
    let mesh = generate_chunk_mesh(&chunk, 1);

    assert_eq!(
        vertex_count(&mesh),
        24,
        "fully solid chunk should produce 24 vertices (4 per face × 6 outer faces)"
    );
    assert_eq!(
        index_count(&mesh),
        36,
        "fully solid chunk should produce 36 indices (6 per face × 6 outer faces)"
    );
}

#[test]
fn lod_1_produces_coarser_mesh_than_lod_0() {
    // Checkerboard of two solid voxel types: LOD 0 cannot merge across type
    // boundaries (many small quads), LOD 1 collapses 2×2×2 super-voxels so
    // much more merging is possible.
    let mut chunk = Chunk::<DefaultVoxel>::new();
    for x in 0..CHUNK_SIZE {
        for y in 0..CHUNK_SIZE {
            for z in 0..CHUNK_SIZE {
                let voxel = if (x + y + z) % 2 == 0 {
                    DefaultVoxel::Rock
                } else {
                    DefaultVoxel::IronOre
                };
                chunk.set(x, y, z, voxel);
            }
        }
    }

    let mesh_lod0 = generate_chunk_mesh(&chunk, lod_to_step(0)); // step = 1
    let mesh_lod1 = generate_chunk_mesh(&chunk, lod_to_step(1)); // step = 2

    let verts_lod0 = vertex_count(&mesh_lod0);
    let verts_lod1 = vertex_count(&mesh_lod1);

    assert!(
        verts_lod1 <= verts_lod0,
        "LOD 1 ({verts_lod1} vertices) should be <= LOD 0 ({verts_lod0} vertices)"
    );
}

// ── 3. Generator determinism ──────────────────────────────────────────────────

#[test]
fn asteroid_generator_is_deterministic() {
    let generator = AsteroidGenerator::new(AsteroidConfig::default());
    let coord = bevy::math::IVec3::new(0, 0, 0);

    let mut chunk_a = Chunk::<DefaultVoxel>::new();
    generator.generate(coord, &mut chunk_a);

    let mut chunk_b = Chunk::<DefaultVoxel>::new();
    generator.generate(coord, &mut chunk_b);

    for x in 0..CHUNK_SIZE {
        for y in 0..CHUNK_SIZE {
            for z in 0..CHUNK_SIZE {
                assert_eq!(
                    chunk_a.get(x, y, z),
                    chunk_b.get(x, y, z),
                    "voxel mismatch at ({x}, {y}, {z}): generation must be deterministic"
                );
            }
        }
    }
}

#[test]
fn asteroid_generator_different_coords_can_differ() {
    // The first asteroid is always at the origin, so chunks at different
    // positions within the asteroid may differ. We generate coord (0,0,0) and
    // a far-away coord and expect at least one pair of voxels to differ (the
    // far one should be all-air, which differs from the near one).
    let generator = AsteroidGenerator::new(AsteroidConfig::default());

    let mut chunk_near = Chunk::<DefaultVoxel>::new();
    generator.generate(bevy::math::IVec3::new(0, 0, 0), &mut chunk_near);

    let mut chunk_far = Chunk::<DefaultVoxel>::new();
    generator.generate(bevy::math::IVec3::new(1000, 1000, 1000), &mut chunk_far);

    let near_has_solid = solid_count(&chunk_near) > 0;
    let far_is_empty = chunk_far.is_empty();

    // If the near chunk has any solid content and the far one is empty,
    // they are provably different.
    assert!(
        near_has_solid || far_is_empty,
        "expected the two chunks to differ in content"
    );

    // They should not be identical — at least one voxel must differ.
    let identical = (0..CHUNK_SIZE).all(|x| {
        (0..CHUNK_SIZE)
            .all(|y| (0..CHUNK_SIZE).all(|z| chunk_near.get(x, y, z) == chunk_far.get(x, y, z)))
    });
    assert!(
        !identical,
        "chunk at (0,0,0) and chunk at (1000,1000,1000) should not be identical"
    );
}

#[test]
fn asteroid_generator_produces_solid_voxels() {
    // The first asteroid is always centered at the world origin. A config with
    // a large enough radius guarantees solid voxels in the origin chunk.
    let config = AsteroidConfig {
        asteroid_count: 1,
        min_radius: 30.0,
        max_radius: 30.0,
        ..AsteroidConfig::default()
    };
    let generator = AsteroidGenerator::new(config);

    let mut chunk = Chunk::<DefaultVoxel>::new();
    generator.generate(bevy::math::IVec3::new(0, 0, 0), &mut chunk);

    assert!(
        solid_count(&chunk) > 0,
        "chunks near the asteroid center must contain at least one solid voxel"
    );
}

// ── 4. Noise ──────────────────────────────────────────────────────────────────

#[test]
fn fbm_noise_is_bounded() {
    // fbm is documented to return values in approximately [-1.0, 1.0].
    // We allow a tiny epsilon for floating-point accumulation.
    for i in 0..500 {
        let x = (i as f32) * 0.37 - 92.5;
        let y = (i as f32) * 0.23 + 3.0;
        let z = (i as f32) * 0.53 - 60.0;
        let v = fbm(x, y, z, 42, 4, 2.5, 2.0, 0.5);
        assert!(
            (-1.01..=1.01).contains(&v),
            "fbm({x}, {y}, {z}) = {v} is out of the expected [-1, 1] range"
        );
    }
}

#[test]
fn fbm_noise_varies_spatially() {
    // Sampling at a stride of 1.0 should not produce identical values.
    let values: Vec<f32> = (0..20)
        .map(|i| fbm(i as f32, 0.0, 0.0, 1234, 4, 2.5, 2.0, 0.5))
        .collect();

    let all_identical = values.windows(2).all(|w| w[0] == w[1]);
    assert!(
        !all_identical,
        "fbm must produce varying values across spatial samples, but all 20 were identical"
    );
}

// ── 5. LOD thresholds ─────────────────────────────────────────────────────────

#[test]
fn lod_0_within_200_units() {
    let lod = compute_lod(Vec3::new(25.0, 0.0, 0.0), Vec3::ZERO);
    assert_eq!(lod, 0, "distance 25 should map to LOD 0");

    let lod_mid = compute_lod(Vec3::new(100.0, 0.0, 0.0), Vec3::ZERO);
    assert_eq!(lod_mid, 0, "distance 100 should map to LOD 0");

    // Boundary: just under 200 is still LOD 0
    let lod_boundary = compute_lod(Vec3::new(199.9, 0.0, 0.0), Vec3::ZERO);
    assert_eq!(lod_boundary, 0, "distance 199.9 should still be LOD 0");
}

#[test]
fn lod_1_at_and_beyond_200_units() {
    // Exactly 200.0 is NOT < 200.0, so it maps to LOD 1.
    let lod_at_200 = compute_lod(Vec3::new(200.0, 0.0, 0.0), Vec3::ZERO);
    assert_eq!(lod_at_200, 1, "distance exactly 200 should map to LOD 1");

    let lod_far = compute_lod(Vec3::new(500.0, 0.0, 0.0), Vec3::ZERO);
    assert_eq!(lod_far, 1, "distance 500 should map to LOD 1");
}

// ── 6. Runtime plugin contracts ──────────────────────────────────────────────

#[test]
fn world_and_generator_plugins_can_run_in_minimal_app_without_panic() {
    let mut app = App::new();
    app.add_plugins(MinimalPlugins);
    app.add_plugins(WorldPlugin);
    app.add_plugins(GeneratorPlugin::<DefaultVoxel>::new());

    // No renderer, window, audio, GPU, or real-time plugins are involved here.
    // This verifies the base runtime systems can be registered and ticked in a
    // headless ECS app.
    app.update();
}

#[test]
fn mining_emits_real_destroyed_voxel_byte_for_drop_mapping() {
    let mut app = App::new();
    app.add_plugins(MinimalPlugins);
    app.add_plugins(WorldPlugin);
    app.add_plugins(MiningPlugin);
    app.init_resource::<ObservedBrokenBytes>();
    app.add_systems(Update, (mine_origin_once, record_broken_bytes).chain());

    let mut chunk = Chunk::<DefaultVoxel>::new();
    chunk.set(0, 0, 0, DefaultVoxel::IronOre);
    let entity = app.world_mut().spawn(chunk).id();
    app.world_mut()
        .resource_mut::<ChunkManager>()
        .register(IVec3::ZERO, entity);

    app.update();

    let observed = app.world().resource::<ObservedBrokenBytes>();
    assert_eq!(
        observed.0,
        vec![DefaultVoxel::IronOre.to_byte()],
        "VoxelBroken must carry the destroyed voxel byte so drops map from real block content"
    );
}

#[test]
fn streaming_requests_new_viewer_region_once_and_marks_pending() {
    let mut app = App::new();
    app.insert_resource(ChunkManager::new(14.0, 32.0));
    app.init_resource::<ObservedLoadRequests>();
    app.add_plugins(WorldPlugin);
    app.add_systems(
        Update,
        record_load_requests.after(voxel_framework::world::systems::streaming_system),
    );

    app.update();
    {
        let observed = app.world().resource::<ObservedLoadRequests>();
        assert!(
            observed.0.contains(&IVec3::ZERO),
            "initial stream around origin should include origin chunk; observed {:?}",
            observed.0
        );
    }
    assert!(
        app.world()
            .resource::<ChunkManager>()
            .is_pending(IVec3::ZERO)
    );

    // Running the same frame again must not duplicate the pending request.
    let initial_request_count = app.world().resource::<ObservedLoadRequests>().0.len();
    app.update();
    assert_eq!(
        app.world().resource::<ObservedLoadRequests>().0.len(),
        initial_request_count,
        "a second update at the same viewer position must not duplicate pending requests"
    );

    app.world_mut().resource_mut::<ViewerPosition>().position = Vec3::new(16.0, 0.0, 0.0);
    app.update();

    let observed = &app.world().resource::<ObservedLoadRequests>().0;
    assert!(
        observed.iter().any(|coord| coord.x == 1),
        "moving the viewer one chunk over should request at least one +X chunk; observed {observed:?}"
    );
    assert_eq!(
        observed
            .iter()
            .filter(|&&coord| coord == IVec3::ZERO)
            .count(),
        1,
        "pending origin chunk must not be requested twice"
    );
}

#[test]
fn generator_plugin_loads_persisted_chunk_before_calling_generator() {
    let coord = IVec3::new(7, -2, 3);
    let save_dir = unique_temp_chunk_dir("persisted_chunk_wins");
    let _ = std::fs::remove_dir_all(&save_dir);
    std::fs::create_dir_all(&save_dir).expect("create temp chunk dir");

    let mut saved_chunk = Chunk::<DefaultVoxel>::new();
    saved_chunk.set(0, 0, 0, DefaultVoxel::RareMineral);
    save_chunk(&saved_chunk, save_dir.join(chunk_filename(coord))).expect("save test chunk");

    let generator_calls = Arc::new(AtomicUsize::new(0));
    let mut app = App::new();
    app.add_plugins(MinimalPlugins);
    app.add_plugins(WorldPlugin);
    app.insert_resource(PersistenceConfig {
        save_dir: save_dir.to_string_lossy().into_owned(),
        auto_save: false,
    });
    app.insert_resource(
        voxel_framework::generator::GeneratorResource::<DefaultVoxel> {
            generator: Arc::new(CountingGenerator {
                calls: generator_calls.clone(),
            }),
        },
    );
    app.add_plugins(GeneratorPlugin::<DefaultVoxel>::new());

    app.world_mut().write_message(ChunkLoadRequest(coord));
    app.update();

    assert_eq!(
        generator_calls.load(Ordering::SeqCst),
        0,
        "disk-backed chunks should be loaded synchronously before generator fallback"
    );

    let manager = app.world().resource::<ChunkManager>();
    let entity = manager
        .get_entity(coord)
        .expect("persisted chunk should be registered as loaded");
    let loaded = app
        .world()
        .entity(entity)
        .get::<Chunk<DefaultVoxel>>()
        .expect("loaded entity should contain chunk data");
    assert_eq!(loaded.get(0, 0, 0), DefaultVoxel::RareMineral);

    let modified = app
        .world()
        .resource::<bevy::ecs::message::Messages<ChunkModified>>();
    assert_eq!(
        modified.len(),
        1,
        "loading a persisted chunk should notify mesh/persistence consumers"
    );

    let _ = std::fs::remove_dir_all(&save_dir);
}

#[test]
fn neighbor_mesh_culls_border_face_against_solid_adjacent_chunk() {
    let mut chunk = Chunk::<DefaultVoxel>::new();
    chunk.set(CHUNK_SIZE - 1, 0, 0, DefaultVoxel::Rock);

    let mut right_neighbor = Chunk::<DefaultVoxel>::new();
    right_neighbor.set(0, 0, 0, DefaultVoxel::Rock);

    let mut neighbors = ChunkNeighbors::<DefaultVoxel>::default();
    // Current +X face sees the right neighbor's -X border.
    neighbors.faces[2] = Some(right_neighbor.border_slice(3));

    let isolated_mesh = generate_chunk_mesh(&chunk, 1);
    let seam_free_mesh = generate_chunk_mesh_with_neighbors(&chunk, &neighbors, 1);

    assert_eq!(vertex_count(&isolated_mesh), 24);
    assert_eq!(index_count(&isolated_mesh), 36);
    assert_eq!(
        vertex_count(&seam_free_mesh),
        20,
        "one solid neighbor should cull exactly one single-voxel border face"
    );
    assert_eq!(index_count(&seam_free_mesh), 30);
}