use bevy::math::{IVec3, Vec3};
use crate::chunk::CHUNK_SIZE;
use crate::chunk::Chunk;
use crate::noise::{fbm, hash3};
use crate::voxel::{DefaultVoxel, VoxelType};
use super::ChunkGenerator;
#[derive(Clone, Debug)]
pub struct MineralFrequencies {
pub rare_mineral: f32,
pub silicon_crystal: f32,
pub iron_ore: f32,
pub rock: f32,
}
impl Default for MineralFrequencies {
fn default() -> Self {
Self {
rare_mineral: 0.05,
silicon_crystal: 0.15,
iron_ore: 0.25,
rock: 0.55,
}
}
}
#[derive(Clone, Debug)]
pub struct AsteroidConfig {
pub seed: u32,
pub asteroid_count: usize,
pub min_radius: f32,
pub max_radius: f32,
pub noise_octaves: u32,
pub noise_frequency: f32,
pub noise_amplitude: f32,
pub mineral_frequencies: MineralFrequencies,
}
impl Default for AsteroidConfig {
fn default() -> Self {
Self {
seed: 12345,
asteroid_count: 8,
min_radius: 20.0,
max_radius: 60.0,
noise_octaves: 4,
noise_frequency: 2.5,
noise_amplitude: 0.34,
mineral_frequencies: MineralFrequencies::default(),
}
}
}
const MINERAL_OCTAVES: u32 = 3;
const MINERAL_LACUNARITY: f32 = 2.0;
const MINERAL_GAIN: f32 = 0.5;
pub const DEFAULT_MINERAL_NOISE_FREQUENCY: f32 = 5.0;
#[derive(Clone, Copy, Debug, PartialEq, Default)]
pub enum MineralPlacement {
#[default]
Anywhere,
RadialBand {
min: f32,
max: f32,
},
}
impl MineralPlacement {
#[inline]
pub fn allows(&self, radial_fraction: f32) -> bool {
match *self {
MineralPlacement::Anywhere => true,
MineralPlacement::RadialBand { min, max } => {
radial_fraction >= min && radial_fraction <= max
}
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct AsteroidMineral<V: VoxelType> {
pub voxel: V,
pub threshold: f32,
pub seed_offset: u32,
pub noise_frequency: f32,
pub placement: MineralPlacement,
}
impl<V: VoxelType> AsteroidMineral<V> {
pub fn new(voxel: V, threshold: f32, seed_offset: u32) -> Self {
Self {
voxel,
threshold,
seed_offset,
noise_frequency: DEFAULT_MINERAL_NOISE_FREQUENCY,
placement: MineralPlacement::Anywhere,
}
}
pub fn with_placement(mut self, placement: MineralPlacement) -> Self {
self.placement = placement;
self
}
pub fn with_noise_frequency(mut self, noise_frequency: f32) -> Self {
self.noise_frequency = noise_frequency;
self
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct AsteroidClass<V: VoxelType> {
pub weight: f32,
pub base: V,
pub minerals: Vec<AsteroidMineral<V>>,
pub radius_range: Option<(f32, f32)>,
}
impl<V: VoxelType> AsteroidClass<V> {
pub fn new(base: V) -> Self {
Self {
weight: 1.0,
base,
minerals: Vec::new(),
radius_range: None,
}
}
pub fn with_weight(mut self, weight: f32) -> Self {
self.weight = weight;
self
}
pub fn with_mineral(mut self, mineral: AsteroidMineral<V>) -> Self {
self.minerals.push(mineral);
self
}
pub fn with_radius_range(mut self, min: f32, max: f32) -> Self {
self.radius_range = Some((min, max));
self
}
}
impl Default for AsteroidClass<DefaultVoxel> {
fn default() -> Self {
Self {
weight: 1.0,
base: DefaultVoxel::Rock,
minerals: vec![
AsteroidMineral::new(DefaultVoxel::RareMineral, 0.55, 100),
AsteroidMineral::new(DefaultVoxel::SiliconCrystal, 0.30, 200),
AsteroidMineral::new(DefaultVoxel::IronOre, 0.20, 300),
],
radius_range: None,
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct AsteroidMaterials<V: VoxelType> {
pub classes: Vec<AsteroidClass<V>>,
pub origin_class: Option<usize>,
}
impl<V: VoxelType> AsteroidMaterials<V> {
pub fn new(classes: Vec<AsteroidClass<V>>) -> Self {
Self {
classes,
origin_class: None,
}
}
pub fn single(class: AsteroidClass<V>) -> Self {
Self::new(vec![class])
}
pub fn with_origin_class(mut self, index: usize) -> Self {
self.origin_class = Some(index);
self
}
}
impl Default for AsteroidMaterials<DefaultVoxel> {
fn default() -> Self {
Self::single(AsteroidClass::default())
}
}
#[inline]
fn usable_weight(weight: f32) -> f32 {
if weight.is_finite() && weight > 0.0 {
weight
} else {
0.0
}
}
fn pick_class<V: VoxelType>(classes: &[AsteroidClass<V>], roll: f32) -> usize {
let total: f32 = classes
.iter()
.map(|class| usable_weight(class.weight))
.sum();
if !total.is_finite() || total <= 0.0 {
return 0;
}
let target = roll * total;
let mut accumulated = 0.0_f32;
let mut last_usable = 0;
for (index, class) in classes.iter().enumerate() {
let weight = usable_weight(class.weight);
if weight <= 0.0 {
continue;
}
accumulated += weight;
last_usable = index;
if target < accumulated {
return index;
}
}
last_usable
}
fn class_radius_range(config: &AsteroidConfig, range: Option<(f32, f32)>) -> (f32, f32) {
match range {
Some((a, b)) if a.is_finite() && b.is_finite() && a > 0.0 && b > 0.0 => {
(a.min(b), a.max(b))
}
_ => (config.min_radius, config.max_radius),
}
}
#[derive(Clone, Debug)]
struct Asteroid {
center: Vec3,
radius: f32,
seed: u32,
flatten_y: f32,
class: usize,
}
pub struct AsteroidGenerator<V: VoxelType = DefaultVoxel> {
config: AsteroidConfig,
materials: AsteroidMaterials<V>,
asteroids: Vec<Asteroid>,
}
impl AsteroidGenerator<DefaultVoxel> {
pub fn new(config: AsteroidConfig) -> Self {
Self::with_materials(config, AsteroidMaterials::default())
}
}
impl<V: VoxelType> AsteroidGenerator<V> {
pub fn with_materials(config: AsteroidConfig, materials: AsteroidMaterials<V>) -> Self {
let asteroids = Self::build_asteroids(&config, &materials);
Self {
config,
materials,
asteroids,
}
}
pub fn config(&self) -> &AsteroidConfig {
&self.config
}
pub fn materials(&self) -> &AsteroidMaterials<V> {
&self.materials
}
pub fn asteroid_count(&self) -> usize {
self.asteroids.len()
}
pub fn asteroid_class(&self, asteroid: usize) -> Option<usize> {
self.asteroids.get(asteroid).map(|entry| entry.class)
}
fn build_asteroids(config: &AsteroidConfig, materials: &AsteroidMaterials<V>) -> Vec<Asteroid> {
if materials.classes.is_empty() {
return Vec::new();
}
let mut asteroids = Vec::with_capacity(config.asteroid_count);
for i in 0..config.asteroid_count {
let per_seed = config.seed.wrapping_add(i as u32 * 97 + 1);
let forced = if i == 0 {
materials
.origin_class
.filter(|&index| index < materials.classes.len())
} else {
None
};
let class = match forced {
Some(index) => index,
None => pick_class(&materials.classes, hash3(i as i32, 4, 0, per_seed)),
};
let (min_radius, max_radius) =
class_radius_range(config, materials.classes[class].radius_range);
let (center, radius, flatten_y) = if i == 0 {
let r = (min_radius + max_radius) * 0.5;
(Vec3::ZERO, r, 1.0)
} else {
let hx = hash3(i as i32, 0, 0, per_seed);
let hy = hash3(i as i32, 1, 0, per_seed);
let hz = hash3(i as i32, 2, 0, per_seed);
let hr = hash3(i as i32, 3, 0, per_seed);
let spread_xz = config.max_radius * 10.0;
let spread_y = config.max_radius * 5.0;
let x = (hx * 2.0 - 1.0) * spread_xz;
let y = (hy * 2.0 - 1.0) * spread_y;
let z = (hz * 2.0 - 1.0) * spread_xz;
let r = min_radius + hr * (max_radius - min_radius);
(Vec3::new(x, y, z), r, 1.0_f32)
};
asteroids.push(Asteroid {
center,
radius,
seed: per_seed,
flatten_y,
class,
});
}
asteroids
}
#[inline]
fn determine_voxel(
class: &AsteroidClass<V>,
world_pos: Vec3,
asteroid_seed: u32,
radial_fraction: f32,
) -> V {
for mineral in &class.minerals {
if !mineral.placement.allows(radial_fraction) {
continue;
}
let noise = fbm(
world_pos.x,
world_pos.y,
world_pos.z,
asteroid_seed.wrapping_add(mineral.seed_offset),
MINERAL_OCTAVES,
mineral.noise_frequency,
MINERAL_LACUNARITY,
MINERAL_GAIN,
);
if noise > mineral.threshold {
return mineral.voxel;
}
}
class.base
}
}
impl<V: VoxelType> ChunkGenerator<V> for AsteroidGenerator<V> {
fn generate(&self, coord: IVec3, chunk: &mut Chunk<V>) {
let chunk_world = coord.as_vec3() * CHUNK_SIZE as f32;
for lx in 0..CHUNK_SIZE {
for ly in 0..CHUNK_SIZE {
for lz in 0..CHUNK_SIZE {
let world_pos =
chunk_world + Vec3::new(lx as f32 + 0.5, ly as f32 + 0.5, lz as f32 + 0.5);
for asteroid in &self.asteroids {
let dx = world_pos.x - asteroid.center.x;
let dy = (world_pos.y - asteroid.center.y) / asteroid.flatten_y;
let dz = world_pos.z - asteroid.center.z;
let dist = (dx * dx + dy * dy + dz * dz).sqrt();
let max_extent =
asteroid.radius + asteroid.radius * self.config.noise_amplitude;
if dist > max_extent + 1.0 {
continue;
}
let inner_solid_radius =
asteroid.radius * (1.0 - self.config.noise_amplitude);
let solid = if dist < inner_solid_radius {
true
} else {
let norm = world_pos / (asteroid.radius * 2.0);
let surface_noise = fbm(
norm.x,
norm.y,
norm.z,
asteroid.seed,
self.config.noise_octaves,
self.config.noise_frequency,
2.0, 0.5, ) * asteroid.radius
* self.config.noise_amplitude;
let density = asteroid.radius - dist + surface_noise;
density > 0.0
};
if solid {
let voxel = Self::determine_voxel(
&self.materials.classes[asteroid.class],
world_pos,
asteroid.seed,
dist / asteroid.radius,
);
chunk.set(lx, ly, lz, voxel);
break;
}
}
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn deterministic_generation() {
let config = AsteroidConfig::default();
let generator = AsteroidGenerator::new(config.clone());
let coord = 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 empty_space_produces_air() {
let config = AsteroidConfig {
asteroid_count: 1,
min_radius: 10.0,
max_radius: 10.0,
..AsteroidConfig::default()
};
let generator = AsteroidGenerator::new(config);
let coord = IVec3::new(1000, 1000, 1000);
let mut chunk = Chunk::<DefaultVoxel>::new();
generator.generate(coord, &mut chunk);
assert!(
chunk.is_empty(),
"Chunk far from any asteroid should be entirely air"
);
}
#[test]
fn asteroid_interior_has_solid_voxels() {
let config = AsteroidConfig {
asteroid_count: 1,
min_radius: 30.0,
max_radius: 30.0,
..AsteroidConfig::default()
};
let generator = AsteroidGenerator::new(config);
let coord = IVec3::new(0, 0, 0);
let mut chunk = Chunk::<DefaultVoxel>::new();
generator.generate(coord, &mut chunk);
let solid_count = (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();
assert!(
solid_count > 0,
"Chunk at asteroid center should contain solid voxels, but found none"
);
assert!(
solid_count > CHUNK_SIZE * CHUNK_SIZE,
"Expected substantial solid voxels at asteroid center, got only {solid_count}"
);
}
#[test]
fn mineral_distribution_has_variety() {
let config = AsteroidConfig {
asteroid_count: 1,
min_radius: 40.0,
max_radius: 40.0,
..AsteroidConfig::default()
};
let generator = AsteroidGenerator::new(config);
let mut has_rock = false;
let mut has_iron = false;
let mut has_silicon = false;
let mut has_rare = false;
for cx in -1..=1 {
for cy in -1..=1 {
for cz in -1..=1 {
let coord = IVec3::new(cx, cy, cz);
let mut chunk = Chunk::<DefaultVoxel>::new();
generator.generate(coord, &mut chunk);
for x in 0..CHUNK_SIZE {
for y in 0..CHUNK_SIZE {
for z in 0..CHUNK_SIZE {
match chunk.get(x, y, z) {
DefaultVoxel::Rock => has_rock = true,
DefaultVoxel::IronOre => has_iron = true,
DefaultVoxel::SiliconCrystal => has_silicon = true,
DefaultVoxel::RareMineral => has_rare = true,
DefaultVoxel::Air => {}
}
}
}
}
}
}
}
assert!(has_rock, "Should contain Rock voxels");
assert!(has_iron, "Should contain IronOre voxels");
assert!(has_silicon, "Should contain SiliconCrystal voxels");
assert!(has_rare, "Should contain RareMineral voxels");
}
}
#[cfg(test)]
mod material_tests {
use super::*;
struct LegacyAsteroid {
center: Vec3,
radius: f32,
seed: u32,
flatten_y: f32,
}
fn legacy_build_asteroids(config: &AsteroidConfig) -> Vec<LegacyAsteroid> {
let mut asteroids = Vec::with_capacity(config.asteroid_count);
for i in 0..config.asteroid_count {
let per_seed = config.seed.wrapping_add(i as u32 * 97 + 1);
let (center, radius, flatten_y) = if i == 0 {
let r = (config.min_radius + config.max_radius) * 0.5;
(Vec3::ZERO, r, 1.0)
} else {
let hx = hash3(i as i32, 0, 0, per_seed);
let hy = hash3(i as i32, 1, 0, per_seed);
let hz = hash3(i as i32, 2, 0, per_seed);
let hr = hash3(i as i32, 3, 0, per_seed);
let spread_xz = config.max_radius * 10.0;
let spread_y = config.max_radius * 5.0;
let x = (hx * 2.0 - 1.0) * spread_xz;
let y = (hy * 2.0 - 1.0) * spread_y;
let z = (hz * 2.0 - 1.0) * spread_xz;
let r = config.min_radius + hr * (config.max_radius - config.min_radius);
(Vec3::new(x, y, z), r, 1.0_f32)
};
asteroids.push(LegacyAsteroid {
center,
radius,
seed: per_seed,
flatten_y,
});
}
asteroids
}
fn legacy_determine_mineral(world_pos: Vec3, asteroid_seed: u32) -> DefaultVoxel {
let mineral_octaves = 3;
let mineral_freq = 5.0;
let lacunarity = 2.0;
let gain = 0.5;
let rare_noise = fbm(
world_pos.x,
world_pos.y,
world_pos.z,
asteroid_seed.wrapping_add(100),
mineral_octaves,
mineral_freq,
lacunarity,
gain,
);
let crystal_noise = fbm(
world_pos.x,
world_pos.y,
world_pos.z,
asteroid_seed.wrapping_add(200),
mineral_octaves,
mineral_freq,
lacunarity,
gain,
);
let iron_noise = fbm(
world_pos.x,
world_pos.y,
world_pos.z,
asteroid_seed.wrapping_add(300),
mineral_octaves,
mineral_freq,
lacunarity,
gain,
);
if rare_noise > 0.55 {
DefaultVoxel::RareMineral
} else if crystal_noise > 0.30 {
DefaultVoxel::SiliconCrystal
} else if iron_noise > 0.20 {
DefaultVoxel::IronOre
} else {
DefaultVoxel::Rock
}
}
fn legacy_generate(
config: &AsteroidConfig,
asteroids: &[LegacyAsteroid],
coord: IVec3,
chunk: &mut Chunk<DefaultVoxel>,
) {
let chunk_world = coord.as_vec3() * CHUNK_SIZE as f32;
for lx in 0..CHUNK_SIZE {
for ly in 0..CHUNK_SIZE {
for lz in 0..CHUNK_SIZE {
let world_pos =
chunk_world + Vec3::new(lx as f32 + 0.5, ly as f32 + 0.5, lz as f32 + 0.5);
for asteroid in asteroids {
let dx = world_pos.x - asteroid.center.x;
let dy = (world_pos.y - asteroid.center.y) / asteroid.flatten_y;
let dz = world_pos.z - asteroid.center.z;
let dist = (dx * dx + dy * dy + dz * dz).sqrt();
let max_extent = asteroid.radius + asteroid.radius * config.noise_amplitude;
if dist > max_extent + 1.0 {
continue;
}
let inner_solid_radius = asteroid.radius * (1.0 - config.noise_amplitude);
if dist < inner_solid_radius {
let voxel = legacy_determine_mineral(world_pos, asteroid.seed);
chunk.set(lx, ly, lz, voxel);
break;
}
let norm = world_pos / (asteroid.radius * 2.0);
let surface_noise = fbm(
norm.x,
norm.y,
norm.z,
asteroid.seed,
config.noise_octaves,
config.noise_frequency,
2.0,
0.5,
) * asteroid.radius
* config.noise_amplitude;
let density = asteroid.radius - dist + surface_noise;
if density > 0.0 {
let voxel = legacy_determine_mineral(world_pos, asteroid.seed);
chunk.set(lx, ly, lz, voxel);
break;
}
}
}
}
}
}
fn chunk_of(world: Vec3) -> IVec3 {
(world / CHUNK_SIZE as f32).floor().as_ivec3()
}
fn pinned_coords(asteroids: &[LegacyAsteroid]) -> Vec<IVec3> {
let mut coords = vec![
IVec3::new(0, 0, 0),
IVec3::new(-1, 0, 0),
IVec3::new(0, -1, 0),
IVec3::new(1, 1, 1),
IVec3::new(2, 0, -1),
IVec3::new(-3, 1, 2),
IVec3::new(1000, 1000, 1000),
IVec3::new(-40, 7, 13),
];
for asteroid in asteroids {
coords.push(chunk_of(asteroid.center));
for axis in [Vec3::X, Vec3::Y, Vec3::Z] {
coords.push(chunk_of(asteroid.center + axis * asteroid.radius));
coords.push(chunk_of(asteroid.center - axis * asteroid.radius));
}
}
coords
}
fn for_each_voxel(mut f: impl FnMut(usize, usize, usize)) {
for x in 0..CHUNK_SIZE {
for y in 0..CHUNK_SIZE {
for z in 0..CHUNK_SIZE {
f(x, y, z);
}
}
}
}
fn assert_matches_legacy(config: &AsteroidConfig, generator: &AsteroidGenerator) -> usize {
let legacy_asteroids = legacy_build_asteroids(config);
assert_eq!(generator.asteroids.len(), legacy_asteroids.len());
for (index, (new, old)) in generator
.asteroids
.iter()
.zip(legacy_asteroids.iter())
.enumerate()
{
assert_eq!(new.center, old.center, "center of asteroid {index}");
assert_eq!(
new.radius.to_bits(),
old.radius.to_bits(),
"radius of asteroid {index}"
);
assert_eq!(new.seed, old.seed, "seed of asteroid {index}");
assert_eq!(
new.flatten_y.to_bits(),
old.flatten_y.to_bits(),
"flatten of asteroid {index}"
);
assert_eq!(new.class, 0, "class of asteroid {index}");
}
let mut solid = 0;
for coord in pinned_coords(&legacy_asteroids) {
let mut expected = Chunk::<DefaultVoxel>::new();
legacy_generate(config, &legacy_asteroids, coord, &mut expected);
let mut actual = Chunk::<DefaultVoxel>::new();
generator.generate(coord, &mut actual);
for_each_voxel(|x, y, z| {
let want = expected.get(x, y, z);
let got = actual.get(x, y, z);
assert_eq!(
got.to_byte(),
want.to_byte(),
"seed {} chunk {coord} voxel ({x}, {y}, {z}): default generation \
must stay byte-identical to the pre-material-set generator",
config.seed
);
if want.is_solid() {
solid += 1;
}
});
}
solid
}
#[test]
fn default_config_is_byte_identical_to_legacy_generator() {
let config = AsteroidConfig::default();
let generator = AsteroidGenerator::new(config.clone());
let solid = assert_matches_legacy(&config, &generator);
assert!(
solid > 10_000,
"the pinned chunks must cover real asteroid volume, got {solid} solid voxels"
);
}
#[test]
fn other_configs_are_byte_identical_to_legacy_generator() {
let configs = [
AsteroidConfig {
seed: 99,
asteroid_count: 12,
..AsteroidConfig::default()
},
AsteroidConfig {
seed: 7,
asteroid_count: 5,
min_radius: 15.0,
max_radius: 80.0,
..AsteroidConfig::default()
},
AsteroidConfig {
seed: u32::MAX - 3,
asteroid_count: 3,
min_radius: 10.0,
max_radius: 10.0,
noise_octaves: 2,
noise_frequency: 1.5,
noise_amplitude: 0.2,
..AsteroidConfig::default()
},
];
for config in configs {
let generator = AsteroidGenerator::new(config.clone());
let solid = assert_matches_legacy(&config, &generator);
assert!(solid > 0, "seed {} compared no solid voxels", config.seed);
}
}
#[test]
fn explicit_default_materials_are_byte_identical_to_legacy_generator() {
let config = AsteroidConfig::default();
let generator = AsteroidGenerator::with_materials(
config.clone(),
AsteroidMaterials::single(AsteroidClass::<DefaultVoxel>::default()),
);
assert_matches_legacy(&config, &generator);
}
#[test]
fn default_class_matches_documented_distribution() {
let class = AsteroidClass::<DefaultVoxel>::default();
assert_eq!(class.weight, 1.0);
assert_eq!(class.base, DefaultVoxel::Rock);
assert_eq!(class.radius_range, None);
assert_eq!(
class.minerals,
vec![
AsteroidMineral {
voxel: DefaultVoxel::RareMineral,
threshold: 0.55,
seed_offset: 100,
noise_frequency: 5.0,
placement: MineralPlacement::Anywhere,
},
AsteroidMineral {
voxel: DefaultVoxel::SiliconCrystal,
threshold: 0.30,
seed_offset: 200,
noise_frequency: 5.0,
placement: MineralPlacement::Anywhere,
},
AsteroidMineral {
voxel: DefaultVoxel::IronOre,
threshold: 0.20,
seed_offset: 300,
noise_frequency: 5.0,
placement: MineralPlacement::Anywhere,
},
]
);
let materials = AsteroidMaterials::<DefaultVoxel>::default();
assert_eq!(materials.classes, vec![class]);
assert_eq!(materials.origin_class, None);
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
enum TestVoxel {
#[default]
Air,
Stone,
Ice,
Metal,
}
impl VoxelType for TestVoxel {
fn name(&self) -> &'static str {
match self {
TestVoxel::Air => "Air",
TestVoxel::Stone => "Stone",
TestVoxel::Ice => "Ice",
TestVoxel::Metal => "Metal",
}
}
fn is_solid(&self) -> bool {
!matches!(self, TestVoxel::Air)
}
fn color(&self) -> [f32; 4] {
[1.0, 1.0, 1.0, 1.0]
}
fn to_byte(&self) -> u8 {
match self {
TestVoxel::Air => 0,
TestVoxel::Stone => 1,
TestVoxel::Ice => 2,
TestVoxel::Metal => 3,
}
}
fn from_byte(byte: u8) -> Self {
match byte {
1 => TestVoxel::Stone,
2 => TestVoxel::Ice,
3 => TestVoxel::Metal,
_ => TestVoxel::Air,
}
}
}
fn single_asteroid_config(radius: f32) -> AsteroidConfig {
AsteroidConfig {
asteroid_count: 1,
min_radius: radius,
max_radius: radius,
..AsteroidConfig::default()
}
}
fn weighted(weights: &[f32]) -> Vec<AsteroidClass<TestVoxel>> {
weights
.iter()
.map(|&weight| AsteroidClass::new(TestVoxel::Stone).with_weight(weight))
.collect()
}
#[test]
fn generator_is_send_sync_for_custom_palettes() {
fn assert_generator<V: VoxelType, G: ChunkGenerator<V>>() {}
assert_generator::<TestVoxel, AsteroidGenerator<TestVoxel>>();
assert_generator::<DefaultVoxel, AsteroidGenerator>();
}
#[test]
fn mineral_placement_bands() {
assert!(MineralPlacement::Anywhere.allows(0.0));
assert!(MineralPlacement::Anywhere.allows(f32::NAN));
assert_eq!(MineralPlacement::default(), MineralPlacement::Anywhere);
let band = MineralPlacement::RadialBand {
min: 0.25,
max: 0.5,
};
assert!(band.allows(0.25));
assert!(band.allows(0.5));
assert!(band.allows(0.3));
assert!(!band.allows(0.2));
assert!(!band.allows(0.6));
assert!(!band.allows(f32::NAN));
let crust = MineralPlacement::RadialBand {
min: 0.9,
max: f32::INFINITY,
};
assert!(crust.allows(1.3));
assert!(!crust.allows(0.5));
let inverted = MineralPlacement::RadialBand { min: 0.8, max: 0.2 };
assert!(!inverted.allows(0.5));
}
#[test]
fn pick_class_follows_weights() {
let classes = weighted(&[1.0, 3.0]);
assert_eq!(pick_class(&classes, 0.0), 0);
assert_eq!(pick_class(&classes, 0.2), 0);
assert_eq!(pick_class(&classes, 0.3), 1);
assert_eq!(pick_class(&classes, 0.99), 1);
assert_eq!(pick_class(&classes, 1.0), 1);
}
#[test]
fn pick_class_skips_unusable_weights() {
let classes = weighted(&[0.0, 2.0, -1.0, f32::NAN, 2.0, f32::INFINITY]);
assert_eq!(pick_class(&classes, 0.0), 1);
assert_eq!(pick_class(&classes, 0.4), 1);
assert_eq!(pick_class(&classes, 0.6), 4);
assert_eq!(pick_class(&classes, 1.0), 4);
}
#[test]
fn pick_class_without_usable_weights_uses_first_class() {
assert_eq!(pick_class(&weighted(&[0.0, 0.0]), 0.7), 0);
assert_eq!(pick_class(&weighted(&[f32::NAN, -2.0]), 0.7), 0);
assert_eq!(pick_class(&weighted(&[]), 0.7), 0);
assert_eq!(pick_class(&weighted(&[5.0]), 0.7), 0);
}
#[test]
fn class_radius_range_falls_back_to_config() {
let config = AsteroidConfig {
min_radius: 20.0,
max_radius: 60.0,
..AsteroidConfig::default()
};
assert_eq!(class_radius_range(&config, None), (20.0, 60.0));
assert_eq!(class_radius_range(&config, Some((5.0, 9.0))), (5.0, 9.0));
assert_eq!(class_radius_range(&config, Some((9.0, 5.0))), (5.0, 9.0));
assert_eq!(class_radius_range(&config, Some((0.0, 9.0))), (20.0, 60.0));
assert_eq!(class_radius_range(&config, Some((-1.0, 9.0))), (20.0, 60.0));
assert_eq!(
class_radius_range(&config, Some((5.0, f32::NAN))),
(20.0, 60.0)
);
assert_eq!(
class_radius_range(&config, Some((5.0, f32::INFINITY))),
(20.0, 60.0)
);
}
#[test]
fn empty_material_set_generates_nothing() {
let generator = AsteroidGenerator::with_materials(
AsteroidConfig::default(),
AsteroidMaterials::<TestVoxel>::new(Vec::new()),
);
assert_eq!(generator.asteroid_count(), 0);
assert_eq!(generator.asteroid_class(0), None);
let mut chunk = Chunk::<TestVoxel>::new();
generator.generate(IVec3::ZERO, &mut chunk);
assert!(chunk.is_empty());
}
#[test]
fn class_without_minerals_is_made_of_its_base() {
let generator = AsteroidGenerator::with_materials(
single_asteroid_config(30.0),
AsteroidMaterials::single(AsteroidClass::new(TestVoxel::Ice)),
);
let mut chunk = Chunk::<TestVoxel>::new();
generator.generate(IVec3::ZERO, &mut chunk);
let mut solid = 0;
for_each_voxel(|x, y, z| {
let voxel = chunk.get(x, y, z);
assert!(
voxel == TestVoxel::Ice || voxel == TestVoxel::Air,
"unexpected {voxel:?} at ({x}, {y}, {z})"
);
if voxel == TestVoxel::Ice {
solid += 1;
}
});
assert!(solid > 0);
}
#[test]
fn materials_do_not_change_asteroid_shape() {
let config = AsteroidConfig::default();
let default_generator = AsteroidGenerator::new(config.clone());
let custom_generator = AsteroidGenerator::with_materials(
config,
AsteroidMaterials::new(vec![
AsteroidClass::new(TestVoxel::Stone).with_mineral(AsteroidMineral::new(
TestVoxel::Metal,
0.1,
7,
)),
AsteroidClass::new(TestVoxel::Ice).with_weight(2.0),
]),
);
for (default_asteroid, custom_asteroid) in default_generator
.asteroids
.iter()
.zip(custom_generator.asteroids.iter())
{
assert_eq!(default_asteroid.center, custom_asteroid.center);
assert_eq!(default_asteroid.radius, custom_asteroid.radius);
assert_eq!(default_asteroid.seed, custom_asteroid.seed);
}
for coord in [
IVec3::new(0, 0, 0),
IVec3::new(2, 0, 0),
IVec3::new(0, -3, 0),
IVec3::new(-2, 1, 1),
] {
let mut default_chunk = Chunk::<DefaultVoxel>::new();
default_generator.generate(coord, &mut default_chunk);
let mut custom_chunk = Chunk::<TestVoxel>::new();
custom_generator.generate(coord, &mut custom_chunk);
for_each_voxel(|x, y, z| {
assert_eq!(
default_chunk.is_solid_at(x, y, z),
custom_chunk.is_solid_at(x, y, z),
"solidity differs in chunk {coord} at ({x}, {y}, {z})"
);
});
}
}
#[test]
fn always_matching_mineral_replaces_the_base() {
let generator = AsteroidGenerator::with_materials(
single_asteroid_config(30.0),
AsteroidMaterials::single(
AsteroidClass::new(TestVoxel::Stone)
.with_mineral(AsteroidMineral::new(TestVoxel::Metal, -2.0, 1))
.with_mineral(AsteroidMineral::new(TestVoxel::Ice, -2.0, 2)),
),
);
let mut chunk = Chunk::<TestVoxel>::new();
generator.generate(IVec3::ZERO, &mut chunk);
let mut solid = 0;
for_each_voxel(|x, y, z| {
let voxel = chunk.get(x, y, z);
assert!(voxel == TestVoxel::Metal || voxel == TestVoxel::Air);
if voxel == TestVoxel::Metal {
solid += 1;
}
});
assert!(solid > 0);
}
#[test]
fn unreachable_threshold_disables_a_mineral() {
let generator = AsteroidGenerator::with_materials(
single_asteroid_config(30.0),
AsteroidMaterials::single(
AsteroidClass::new(TestVoxel::Stone).with_mineral(AsteroidMineral::new(
TestVoxel::Metal,
1.0,
1,
)),
),
);
let mut chunk = Chunk::<TestVoxel>::new();
generator.generate(IVec3::ZERO, &mut chunk);
for_each_voxel(|x, y, z| {
assert_ne!(chunk.get(x, y, z), TestVoxel::Metal);
});
}
#[test]
fn radial_band_confines_a_mineral_to_its_depth() {
let radius = 40.0_f32;
let band_max = 0.3_f32;
let generator = AsteroidGenerator::with_materials(
single_asteroid_config(radius),
AsteroidMaterials::single(AsteroidClass::new(TestVoxel::Stone).with_mineral(
AsteroidMineral::new(TestVoxel::Metal, -2.0, 1).with_placement(
MineralPlacement::RadialBand {
min: 0.0,
max: band_max,
},
),
)),
);
let mut chunk = Chunk::<TestVoxel>::new();
generator.generate(IVec3::ZERO, &mut chunk);
let mut metal = 0;
let mut stone = 0;
for_each_voxel(|x, y, z| {
let pos = Vec3::new(x as f32 + 0.5, y as f32 + 0.5, z as f32 + 0.5);
let fraction = pos.length() / radius;
if (fraction - band_max).abs() < 1e-3 {
return; }
let voxel = chunk.get(x, y, z);
if fraction < band_max {
assert_eq!(
voxel,
TestVoxel::Metal,
"inside the band at ({x}, {y}, {z})"
);
metal += 1;
} else {
assert_ne!(
voxel,
TestVoxel::Metal,
"outside the band at ({x}, {y}, {z})"
);
if voxel == TestVoxel::Stone {
stone += 1;
}
}
});
assert!(metal > 0, "the band must contain voxels");
assert!(
stone > 0,
"voxels outside the band must fall back to the base"
);
}
#[test]
fn classes_are_assigned_per_asteroid_and_deterministically() {
let config = AsteroidConfig {
asteroid_count: 64,
..AsteroidConfig::default()
};
let materials = AsteroidMaterials::new(vec![
AsteroidClass::new(TestVoxel::Stone),
AsteroidClass::new(TestVoxel::Ice),
AsteroidClass::new(TestVoxel::Metal).with_weight(0.0),
]);
let first = AsteroidGenerator::with_materials(config.clone(), materials.clone());
let second = AsteroidGenerator::with_materials(config.clone(), materials.clone());
assert_eq!(first.asteroid_count(), 64);
assert_eq!(first.materials(), &materials);
let mut counts = [0usize; 3];
for index in 0..64 {
let class = first.asteroid_class(index).expect("asteroid exists");
assert_eq!(Some(class), second.asteroid_class(index));
counts[class] += 1;
}
assert_eq!(first.asteroid_class(64), None);
assert!(
counts[0] > 0,
"equal weights should both be drawn: {counts:?}"
);
assert!(
counts[1] > 0,
"equal weights should both be drawn: {counts:?}"
);
assert_eq!(counts[2], 0, "a zero-weight class is never drawn");
let other = AsteroidGenerator::with_materials(
AsteroidConfig {
seed: config.seed.wrapping_add(1),
..config
},
materials,
);
assert!(
(0..64).any(|index| other.asteroid_class(index) != first.asteroid_class(index)),
"class assignment must depend on the seed"
);
}
#[test]
fn each_asteroid_uses_only_its_class_composition() {
let config = AsteroidConfig {
asteroid_count: 24,
..AsteroidConfig::default()
};
let generator = AsteroidGenerator::with_materials(
config,
AsteroidMaterials::new(vec![
AsteroidClass::new(TestVoxel::Stone),
AsteroidClass::new(TestVoxel::Ice),
]),
);
let mut checked = [false; 2];
for (index, asteroid) in generator.asteroids.iter().enumerate() {
let overlapped = generator
.asteroids
.iter()
.enumerate()
.any(|(other_index, other)| {
other_index != index
&& other.center.distance(asteroid.center)
< other.radius * 1.4 + asteroid.radius * 1.4 + 32.0
});
if overlapped {
continue;
}
let expected = [TestVoxel::Stone, TestVoxel::Ice][asteroid.class];
let mut chunk = Chunk::<TestVoxel>::new();
generator.generate(chunk_of(asteroid.center), &mut chunk);
let mut solid = 0;
for_each_voxel(|x, y, z| {
let voxel = chunk.get(x, y, z);
if voxel != TestVoxel::Air {
assert_eq!(voxel, expected, "asteroid {index}");
solid += 1;
}
});
assert!(solid > 0, "asteroid {index} center chunk should be solid");
checked[asteroid.class] = true;
}
assert!(
checked[0] && checked[1],
"both classes should have been checked: {checked:?}"
);
}
#[test]
fn origin_class_is_forced_only_when_valid() {
let classes = vec![
AsteroidClass::new(TestVoxel::Stone),
AsteroidClass::new(TestVoxel::Ice).with_weight(0.0),
];
let config = AsteroidConfig {
asteroid_count: 16,
..AsteroidConfig::default()
};
let forced = AsteroidGenerator::with_materials(
config.clone(),
AsteroidMaterials::new(classes.clone()).with_origin_class(1),
);
assert_eq!(forced.asteroid_class(0), Some(1));
for index in 1..16 {
assert_eq!(forced.asteroid_class(index), Some(0));
}
let mut chunk = Chunk::<TestVoxel>::new();
forced.generate(IVec3::ZERO, &mut chunk);
assert_eq!(chunk.get(0, 0, 0), TestVoxel::Ice);
let out_of_range = AsteroidGenerator::with_materials(
config,
AsteroidMaterials::new(classes).with_origin_class(9),
);
assert_eq!(out_of_range.asteroid_class(0), Some(0));
}
#[test]
fn class_radius_range_sizes_asteroids_without_moving_them() {
let config = AsteroidConfig {
asteroid_count: 16,
..AsteroidConfig::default()
};
let reference = AsteroidGenerator::new(config.clone());
let small = AsteroidGenerator::with_materials(
config,
AsteroidMaterials::single(
AsteroidClass::new(TestVoxel::Stone).with_radius_range(5.0, 6.0),
),
);
assert_eq!(small.asteroids[0].radius, 5.5);
for (index, (asteroid, original)) in small
.asteroids
.iter()
.zip(reference.asteroids.iter())
.enumerate()
{
assert!(
(5.0..=6.0).contains(&asteroid.radius),
"asteroid {index} radius {}",
asteroid.radius
);
assert_eq!(asteroid.center, original.center, "asteroid {index} moved");
}
}
}