chore: move to crates folder
This commit is contained in:
1 parent
5d10c0d8a8
commit
cb3660bcd2
3393 files changed
+1270
-741
No files matched your search
@@ -0,0 +1,45 @@
|
||||
use pumpkin_data::chunk::Biome;
|
||||
|
||||
use crate::{
|
||||
biome::BiomeSupplier,
|
||||
generation::{
|
||||
biome_coords, noise::router::multi_noise_sampler::MultiNoiseSampler, section_coords,
|
||||
},
|
||||
};
|
||||
|
||||
pub struct TheEndBiomeSupplier;
|
||||
|
||||
impl TheEndBiomeSupplier {
|
||||
const CENTER_BIOME: Biome = Biome::THE_END;
|
||||
const HIGHLANDS_BIOME: Biome = Biome::END_HIGHLANDS;
|
||||
const MIDLANDS_BIOME: Biome = Biome::END_MIDLANDS;
|
||||
const SMALL_ISLANDS_BIOME: Biome = Biome::SMALL_END_ISLANDS;
|
||||
const BARRENS_BIOME: Biome = Biome::END_BARRENS;
|
||||
}
|
||||
|
||||
impl BiomeSupplier for TheEndBiomeSupplier {
|
||||
fn biome(&self, x: i32, y: i32, z: i32, noise: &mut MultiNoiseSampler<'_>) -> &'static Biome {
|
||||
let x = biome_coords::to_block(x);
|
||||
let y = biome_coords::to_block(y);
|
||||
let z = biome_coords::to_block(z);
|
||||
let section_x = section_coords::block_to_section(x);
|
||||
let section_z = section_coords::block_to_section(z);
|
||||
if section_x * section_x + section_z * section_z <= 4096 {
|
||||
return &Self::CENTER_BIOME;
|
||||
}
|
||||
let x = (section_x * 2 + 1) * 8;
|
||||
let z = (section_z * 2 + 1) * 8;
|
||||
let noise = noise.sample_erosion(x, y, z);
|
||||
if noise > 0.25 {
|
||||
return &Self::HIGHLANDS_BIOME;
|
||||
}
|
||||
if noise >= -0.0625 {
|
||||
return &Self::MIDLANDS_BIOME;
|
||||
}
|
||||
if noise < -0.21875 {
|
||||
return &Self::SMALL_ISLANDS_BIOME;
|
||||
}
|
||||
|
||||
&Self::BARRENS_BIOME
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::cell::RefCell;
|
||||
|
||||
use pumpkin_data::chunk::{Biome, BiomeTree, NETHER_BIOME_SOURCE, OVERWORLD_BIOME_SOURCE};
|
||||
|
||||
use crate::generation::noise::router::multi_noise_sampler::MultiNoiseSampler;
|
||||
pub mod end;
|
||||
pub mod multi_noise;
|
||||
pub mod position_finder;
|
||||
|
||||
thread_local! {
|
||||
/// A shortcut; check if last used biome is what we should use
|
||||
static LAST_RESULT_NODE: RefCell<Option<&'static BiomeTree>> = const {RefCell::new(None) };
|
||||
}
|
||||
|
||||
pub trait BiomeSupplier {
|
||||
fn biome(&self, x: i32, y: i32, z: i32, noise: &mut MultiNoiseSampler<'_>) -> &'static Biome;
|
||||
}
|
||||
|
||||
pub struct MultiNoiseBiomeSupplier {
|
||||
source: &'static BiomeTree,
|
||||
}
|
||||
|
||||
impl MultiNoiseBiomeSupplier {
|
||||
pub const OVERWORLD: Self = Self::new(&OVERWORLD_BIOME_SOURCE);
|
||||
pub const NETHER: Self = Self::new(&NETHER_BIOME_SOURCE);
|
||||
|
||||
const fn new(source: &'static BiomeTree) -> Self {
|
||||
Self { source }
|
||||
}
|
||||
}
|
||||
|
||||
impl BiomeSupplier for MultiNoiseBiomeSupplier {
|
||||
fn biome(&self, x: i32, y: i32, z: i32, noise: &mut MultiNoiseSampler<'_>) -> &'static Biome {
|
||||
let point = noise.sample(x, y, z);
|
||||
let point_list = point.convert_to_list();
|
||||
LAST_RESULT_NODE.with_borrow_mut(|last_result| self.source.get(&point_list, last_result))
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn hash_seed(seed: u64) -> i64 {
|
||||
let mut hasher = Sha256::new();
|
||||
hasher.update(seed.to_le_bytes());
|
||||
let result = hasher.finalize();
|
||||
i64::from_le_bytes(result[..8].try_into().unwrap())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use pumpkin_data::{chunk::Biome, dimension::Dimension};
|
||||
use pumpkin_util::read_data_from_file;
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::{
|
||||
ProtoChunk,
|
||||
chunk::palette::BIOME_NETWORK_MAX_BITS,
|
||||
generation::noise::router::multi_noise_sampler::{
|
||||
MultiNoiseSampler, MultiNoiseSamplerBuilderOptions,
|
||||
},
|
||||
};
|
||||
|
||||
use super::{BiomeSupplier, MultiNoiseBiomeSupplier, hash_seed};
|
||||
|
||||
#[test]
|
||||
fn biome_desert() {
|
||||
use crate::generation::generator::{GeneratorInit, VanillaGenerator};
|
||||
use pumpkin_util::world_seed::Seed;
|
||||
let seed = 13579;
|
||||
let generator = VanillaGenerator::new(Seed(seed as u64), Dimension::OVERWORLD);
|
||||
let multi_noise_config = MultiNoiseSamplerBuilderOptions::new(1, 1, 1);
|
||||
let mut sampler =
|
||||
MultiNoiseSampler::generate(&generator.base_router.multi_noise, &multi_noise_config);
|
||||
let biome = MultiNoiseBiomeSupplier::OVERWORLD.biome(-24, 1, 8, &mut sampler);
|
||||
assert_eq!(biome, &Biome::DESERT);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wide_area_surface() {
|
||||
use crate::generation::generator::{GeneratorInit, VanillaGenerator, WorldGenerator};
|
||||
use crate::generation::noise::router::multi_noise_sampler::{
|
||||
MultiNoiseSampler, MultiNoiseSamplerBuilderOptions,
|
||||
};
|
||||
use crate::generation::{biome_coords, positions::chunk_pos};
|
||||
use pumpkin_util::world_seed::Seed;
|
||||
#[derive(Deserialize)]
|
||||
struct BiomeData {
|
||||
x: i32,
|
||||
z: i32,
|
||||
data: Vec<(i32, i32, i32, u8)>,
|
||||
}
|
||||
|
||||
let expected_data: Vec<BiomeData> =
|
||||
read_data_from_file!("../../../assets/tests/biome_no_blend_no_beard_0.json");
|
||||
|
||||
let seed = 0;
|
||||
let world_gen = WorldGenerator::Noise(Box::new(VanillaGenerator::new(
|
||||
Seed(seed as u64),
|
||||
Dimension::OVERWORLD,
|
||||
)));
|
||||
let WorldGenerator::Noise(generator) = &world_gen else {
|
||||
unreachable!()
|
||||
};
|
||||
|
||||
for data in expected_data {
|
||||
let chunk_x = data.x;
|
||||
let chunk_z = data.z;
|
||||
|
||||
let mut chunk = ProtoChunk::new(chunk_x, chunk_z, &world_gen);
|
||||
|
||||
// Create MultiNoiseSampler for populate_biomes
|
||||
|
||||
let start_x = chunk_pos::start_block_x(chunk_x);
|
||||
let start_z = chunk_pos::start_block_z(chunk_z);
|
||||
|
||||
let horizontal_biome_end = biome_coords::from_block(16);
|
||||
let multi_noise_config = MultiNoiseSamplerBuilderOptions::new(
|
||||
biome_coords::from_block(start_x),
|
||||
biome_coords::from_block(start_z),
|
||||
horizontal_biome_end as usize,
|
||||
);
|
||||
let mut multi_noise_sampler = MultiNoiseSampler::generate(
|
||||
&generator.base_router.multi_noise,
|
||||
&multi_noise_config,
|
||||
);
|
||||
|
||||
chunk.populate_biomes(generator, &mut multi_noise_sampler);
|
||||
|
||||
for (biome_x, biome_y, biome_z, biome_id) in data.data {
|
||||
let calculated_biome = chunk.get_biome(biome_x, biome_y, biome_z);
|
||||
|
||||
assert_eq!(
|
||||
biome_id,
|
||||
calculated_biome.id,
|
||||
"Expected {:?} was {:?} at {},{},{} ({},{})",
|
||||
Biome::from_id(biome_id),
|
||||
calculated_biome,
|
||||
biome_x,
|
||||
biome_y,
|
||||
biome_z,
|
||||
data.x,
|
||||
data.z
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hash_seed_test() {
|
||||
let hashed_seed = hash_seed(0);
|
||||
assert_eq!(8794265229978523055, hashed_seed);
|
||||
|
||||
let hashed_seed = hash_seed((-777i64) as u64);
|
||||
assert_eq!(-1087248400229165450, hashed_seed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn proper_network_bits_per_entry() {
|
||||
let id_to_test = 1 << BIOME_NETWORK_MAX_BITS;
|
||||
assert!(
|
||||
Biome::from_id(id_to_test).is_none(),
|
||||
"We need to update our constants!"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[must_use]
|
||||
pub const fn to_long(float: f32) -> i64 {
|
||||
(float * 10000f32) as i64
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
|
||||
pub struct NoiseValuePoint {
|
||||
pub temperature: i64,
|
||||
pub humidity: i64,
|
||||
pub continentalness: i64,
|
||||
pub erosion: i64,
|
||||
pub depth: i64,
|
||||
pub weirdness: i64,
|
||||
}
|
||||
|
||||
impl NoiseValuePoint {
|
||||
#[must_use]
|
||||
pub const fn convert_to_list(&self) -> [i64; 7] {
|
||||
[
|
||||
self.temperature,
|
||||
self.humidity,
|
||||
self.continentalness,
|
||||
self.erosion,
|
||||
self.depth,
|
||||
self.weirdness,
|
||||
0,
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use pumpkin_data::dimension::Dimension;
|
||||
use pumpkin_util::read_data_from_file;
|
||||
|
||||
use crate::ProtoChunk;
|
||||
|
||||
#[test]
|
||||
fn sample_value() {
|
||||
use crate::generation::generator::{GeneratorInit, VanillaGenerator, WorldGenerator};
|
||||
use crate::generation::noise::router::multi_noise_sampler::{
|
||||
MultiNoiseSampler, MultiNoiseSamplerBuilderOptions,
|
||||
};
|
||||
use crate::generation::{biome_coords, positions::chunk_pos};
|
||||
use pumpkin_util::world_seed::Seed;
|
||||
type PosToPoint = (i32, i32, i32, i64, i64, i64, i64, i64, i64);
|
||||
let expected_data: Vec<PosToPoint> =
|
||||
read_data_from_file!("../../../assets/multi_noise_sample_no_blend_no_beard_0_0_0.json");
|
||||
|
||||
let seed = 0;
|
||||
let chunk_x = 0;
|
||||
let chunk_z = 0;
|
||||
|
||||
let generator = Box::new(VanillaGenerator::new(
|
||||
Seed(seed as u64),
|
||||
Dimension::OVERWORLD,
|
||||
));
|
||||
let world_gen = WorldGenerator::Noise(generator);
|
||||
let WorldGenerator::Noise(generator) = &world_gen else {
|
||||
unreachable!()
|
||||
};
|
||||
|
||||
let _chunk = ProtoChunk::new(chunk_x, chunk_z, &world_gen);
|
||||
|
||||
let start_x = chunk_pos::start_block_x(chunk_x);
|
||||
let start_z = chunk_pos::start_block_z(chunk_z);
|
||||
let horizontal_biome_end = biome_coords::from_block(16);
|
||||
let multi_noise_config = MultiNoiseSamplerBuilderOptions::new(
|
||||
biome_coords::from_block(start_x),
|
||||
biome_coords::from_block(start_z),
|
||||
horizontal_biome_end as usize,
|
||||
);
|
||||
let mut multi_noise_sampler =
|
||||
MultiNoiseSampler::generate(&generator.base_router.multi_noise, &multi_noise_config);
|
||||
|
||||
for (x, y, z, tem, hum, con, ero, dep, wei) in expected_data {
|
||||
let point = multi_noise_sampler.sample(x, y, z);
|
||||
assert_eq!(point.temperature, tem);
|
||||
assert_eq!(point.humidity, hum);
|
||||
assert_eq!(point.continentalness, con);
|
||||
assert_eq!(point.erosion, ero);
|
||||
assert_eq!(point.depth, dep);
|
||||
assert_eq!(point.weirdness, wei);
|
||||
}
|
||||
}
|
||||
|
||||
// #[test]
|
||||
// fn sample_multinoise_biome() {
|
||||
// use crate::generation::generator::{GeneratorInit, VanillaGenerator};
|
||||
// use pumpkin_util::world_seed::Seed;
|
||||
|
||||
// let expected_data: Vec<(i32, i32, i32, u8)> =
|
||||
// read_data_from_file!("../../../assets/multi_noise_biome_source_test.json");
|
||||
|
||||
// let seed = 0;
|
||||
// let generator = VanillaGenerator::new(Seed(seed as u64), Dimension::OVERWORLD);
|
||||
|
||||
// let mut sampler = MultiNoiseSampler::generate(
|
||||
// &generator.base_router.multi_noise,
|
||||
// &MultiNoiseSamplerBuilderOptions::new(0, 0, 4),
|
||||
// );
|
||||
|
||||
// for (x, y, z, biome_id) in expected_data {
|
||||
// let calculated_biome = MultiNoiseBiomeSupplier::OVERWORLD.biome(x, y, z, &mut sampler);
|
||||
|
||||
// assert_eq!(
|
||||
// biome_id,
|
||||
// calculated_biome.id,
|
||||
// "Expected {:?} was {:?} at {},{},{}",
|
||||
// Biome::from_id(biome_id),
|
||||
// calculated_biome,
|
||||
// x,
|
||||
// y,
|
||||
// z
|
||||
// );
|
||||
// }
|
||||
// }
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
use pumpkin_data::chunk::ParameterRange;
|
||||
use pumpkin_util::math::vector2::Vector2;
|
||||
|
||||
pub struct FittestPositionFinderResult {
|
||||
pub location: Vector2<i32>,
|
||||
pub fitness: i64,
|
||||
}
|
||||
|
||||
pub struct FittestPositionFinder;
|
||||
|
||||
impl FittestPositionFinder {
|
||||
pub fn find_best_spawn_position(
|
||||
target_noises: &[[ParameterRange; 7]],
|
||||
sampler: &dyn Fn(i32, i32) -> [i64; 7],
|
||||
) -> Vector2<i32> {
|
||||
let mut best_result = Self::calculate_fitness(target_noises, sampler, 0, 0);
|
||||
|
||||
Self::find_fittest(target_noises, sampler, &mut best_result, 2048.0, 512.0);
|
||||
Self::find_fittest(target_noises, sampler, &mut best_result, 512.0, 32.0);
|
||||
|
||||
best_result.location
|
||||
}
|
||||
|
||||
fn find_fittest(
|
||||
noises: &[[ParameterRange; 7]],
|
||||
sampler: &dyn Fn(i32, i32) -> [i64; 7],
|
||||
best_result: &mut FittestPositionFinderResult,
|
||||
max_distance: f32,
|
||||
step: f32,
|
||||
) {
|
||||
let mut angle = 0.0f32;
|
||||
let mut distance = step;
|
||||
let center = best_result.location;
|
||||
|
||||
while distance <= max_distance {
|
||||
let x = center.x + (angle.sin() * distance) as i32;
|
||||
let z = center.y + (angle.cos() * distance) as i32;
|
||||
|
||||
let result = Self::calculate_fitness(noises, sampler, x, z);
|
||||
if result.fitness < best_result.fitness {
|
||||
*best_result = result;
|
||||
}
|
||||
|
||||
angle += step / distance;
|
||||
if angle > std::f32::consts::TAU {
|
||||
angle = 0.0;
|
||||
distance += step;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn calculate_fitness(
|
||||
noises: &[[ParameterRange; 7]],
|
||||
sampler: &dyn Fn(i32, i32) -> [i64; 7],
|
||||
x: i32,
|
||||
z: i32,
|
||||
) -> FittestPositionFinderResult {
|
||||
let sampled_noise = sampler(x, z);
|
||||
let mut min_squared_dist = i64::MAX;
|
||||
|
||||
for noise_ranges in noises {
|
||||
let mut current_dist = 0i64;
|
||||
for i in 0..7 {
|
||||
current_dist += noise_ranges[i].calc_distance(sampled_noise[i]);
|
||||
}
|
||||
min_squared_dist = min_squared_dist.min(current_dist);
|
||||
}
|
||||
|
||||
let origin_dist_sq = (x as i64 * x as i64) + (z as i64 * z as i64);
|
||||
let fitness = min_squared_dist * (2048 * 2048) + origin_dist_sq;
|
||||
|
||||
FittestPositionFinderResult {
|
||||
location: Vector2::new(x, z),
|
||||
fitness,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
pub trait PropertyDelegate: Sync + Send {
|
||||
fn get_property(&self, _index: i32) -> i32;
|
||||
fn set_property(&self, _index: i32, _value: i32);
|
||||
fn get_properties_size(&self) -> i32;
|
||||
}
|
||||
|
||||
/// Trait for extracting smelting experience from cooking block entities.
|
||||
pub trait ExperienceContainer: Send + Sync {
|
||||
/// Extract and reset accumulated experience, returning the total as an integer
|
||||
fn extract_experience(&self) -> i32;
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
pub mod entities;
|
||||
pub mod viewer;
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use pumpkin_data::{Block, BlockState, BlockStateId};
|
||||
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone)]
|
||||
#[serde(rename_all = "PascalCase")]
|
||||
pub struct BlockStateCodec {
|
||||
/// Block name
|
||||
#[serde(
|
||||
deserialize_with = "parse_block_name",
|
||||
serialize_with = "block_to_string"
|
||||
)]
|
||||
pub name: &'static Block,
|
||||
/// Key-value pairs of properties
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub properties: Option<HashMap<String, String>>,
|
||||
}
|
||||
|
||||
fn parse_block_name<'de, D: Deserializer<'de>>(
|
||||
deserializer: D,
|
||||
) -> Result<&'static Block, D::Error> {
|
||||
let s = String::deserialize(deserializer)?;
|
||||
let block =
|
||||
Block::from_name(s.as_str()).ok_or(serde::de::Error::custom("Invalid block name"))?;
|
||||
Ok(block)
|
||||
}
|
||||
|
||||
fn block_to_string<S: Serializer>(block: &'static Block, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
serializer.serialize_str(block.name)
|
||||
}
|
||||
|
||||
impl BlockStateCodec {
|
||||
#[must_use]
|
||||
pub fn get_state(&self) -> &'static BlockState {
|
||||
let state_id = self.get_state_id();
|
||||
BlockState::from_id(state_id)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn get_block(&self) -> &'static Block {
|
||||
self.name
|
||||
}
|
||||
|
||||
/// Prefer this over `get_state` when the only the state ID is needed
|
||||
#[must_use]
|
||||
pub fn get_state_id(&self) -> BlockStateId {
|
||||
let block = self.name;
|
||||
|
||||
let Some(properties_map) = &self.properties else {
|
||||
return block.default_state.id;
|
||||
};
|
||||
|
||||
let props_iter = properties_map
|
||||
.iter()
|
||||
.map(|(k, v)| (k.as_str(), v.as_str()))
|
||||
.collect::<Vec<(&str, &str)>>();
|
||||
|
||||
let block_properties = block.from_properties(&props_iter);
|
||||
block_properties.to_state_id(block)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use pumpkin_data::BlockStateId;
|
||||
|
||||
use crate::chunk::palette::BLOCK_NETWORK_MAX_BITS;
|
||||
|
||||
#[test]
|
||||
fn proper_network_bits_per_entry() {
|
||||
let id_to_test = 1 << BLOCK_NETWORK_MAX_BITS;
|
||||
assert!(
|
||||
BlockStateId::new_or_air(id_to_test) == BlockStateId::AIR,
|
||||
"We need to update our constants!"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
use std::sync::atomic::{AtomicU16, Ordering};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ViewerCountTracker {
|
||||
pub old: AtomicU16,
|
||||
pub current: AtomicU16,
|
||||
}
|
||||
|
||||
impl Default for ViewerCountTracker {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl ViewerCountTracker {
|
||||
#[must_use]
|
||||
pub const fn new() -> Self {
|
||||
Self {
|
||||
old: AtomicU16::new(0),
|
||||
current: AtomicU16::new(0),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn open_container(&self) {
|
||||
self.current.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
pub fn close_container(&self) {
|
||||
self.current.fetch_sub(1, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Returns the current number of players viewing this container
|
||||
pub fn get_viewer_count(&self) -> u16 {
|
||||
self.current.load(Ordering::Relaxed)
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,756 @@
|
||||
use std::collections::HashMap;
|
||||
use std::io::{ErrorKind, Read};
|
||||
use std::marker::PhantomData;
|
||||
use std::path::PathBuf;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use crate::chunk::format::anvil::{AnvilChunkFile, SingleChunkDataSerializer};
|
||||
use crate::chunk::io::{ChunkSerializer, LoadedData};
|
||||
use crate::chunk::{ChunkReadingError, ChunkWritingError};
|
||||
use bytes::{Buf, BufMut, Bytes};
|
||||
use pumpkin_util::math::vector2::Vector2;
|
||||
use ruzstd::decoding::StreamingDecoder;
|
||||
use ruzstd::encoding::{CompressionLevel, compress_to_vec};
|
||||
use tokio::io::{AsyncWriteExt, BufWriter};
|
||||
use tracing::{error, warn};
|
||||
use xxhash_rust::xxh64::xxh64;
|
||||
|
||||
use super::anvil::CHUNK_COUNT;
|
||||
|
||||
/// The signature used as both header and footer.
|
||||
/// <https://gist.github.com/Aaron2550/5701519671253d4c6190bde6706f9f98>
|
||||
const SIGNATURE: [u8; 8] = u64::to_be_bytes(0xc3ff13183cca9d9a);
|
||||
|
||||
/// Allowed grid sizes for v2 bucket subdivision.
|
||||
const VALID_GRID_SIZES: &[u8] = &[1, 2, 4, 8, 16, 32];
|
||||
|
||||
/// Default grid size. 2×2 = 4 buckets gives a reasonable write amplification
|
||||
/// tradeoff for most worlds.
|
||||
const DEFAULT_GRID_SIZE: u8 = 2;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Superblock (26 bytes)
|
||||
// ---------------------------------------------------------------------------
|
||||
//
|
||||
// 0.. 8 uint64 Signature (0xc3ff13183cca9d9a)
|
||||
// 8.. 9 uint8 Version (2)
|
||||
// 9..17 uint64 Newest timestamp
|
||||
// 17..18 int8 Grid size
|
||||
// 18..22 int32 Region X
|
||||
// 22..26 int32 Region Z
|
||||
|
||||
struct LinearV2Superblock {
|
||||
newest_timestamp: u64,
|
||||
/// One of {1, 2, 4, 8, 16, 32}.
|
||||
grid_size: u8,
|
||||
region_x: i32,
|
||||
region_z: i32,
|
||||
}
|
||||
|
||||
impl LinearV2Superblock {
|
||||
const SIZE: usize = 26;
|
||||
|
||||
fn from_bytes(buf: &[u8]) -> Result<Self, ChunkReadingError> {
|
||||
if buf.len() < Self::SIZE {
|
||||
return Err(ChunkReadingError::IoError(std::io::Error::from(
|
||||
ErrorKind::UnexpectedEof,
|
||||
)));
|
||||
}
|
||||
let mut b = buf;
|
||||
let mut sig = [0u8; 8];
|
||||
sig.copy_from_slice(&b[..8]);
|
||||
b = &b[8..];
|
||||
|
||||
if sig != SIGNATURE {
|
||||
error!("Linear v2: invalid superblock signature");
|
||||
return Err(ChunkReadingError::InvalidHeader);
|
||||
}
|
||||
|
||||
let version = b.get_u8();
|
||||
if version != 0x02 {
|
||||
error!("Linear v2: unexpected version byte {version:#x} in superblock");
|
||||
return Err(ChunkReadingError::InvalidHeader);
|
||||
}
|
||||
|
||||
let newest_timestamp = b.get_u64();
|
||||
let grid_size = b.get_u8();
|
||||
let region_x = b.get_i32();
|
||||
let region_z = b.get_i32();
|
||||
|
||||
if !VALID_GRID_SIZES.contains(&grid_size) {
|
||||
error!("Linear v2: invalid grid size {grid_size}");
|
||||
return Err(ChunkReadingError::InvalidHeader);
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
newest_timestamp,
|
||||
grid_size,
|
||||
region_x,
|
||||
region_z,
|
||||
})
|
||||
}
|
||||
|
||||
fn to_bytes(&self) -> [u8; Self::SIZE] {
|
||||
let mut out = [0u8; Self::SIZE];
|
||||
let mut b = out.as_mut_slice();
|
||||
b.put_slice(&SIGNATURE);
|
||||
b.put_u8(0x02);
|
||||
b.put_u64(self.newest_timestamp);
|
||||
b.put_u8(self.grid_size);
|
||||
b.put_i32(self.region_x);
|
||||
b.put_i32(self.region_z);
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Chunk existence bitmap (128 bytes = 1024 bits)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
struct ChunkBitmap([u8; 128]);
|
||||
|
||||
impl ChunkBitmap {
|
||||
const SIZE: usize = 128;
|
||||
|
||||
const fn new() -> Self {
|
||||
Self([0u8; 128])
|
||||
}
|
||||
|
||||
const fn set(&mut self, index: usize, exists: bool) {
|
||||
let byte = index / 8;
|
||||
let bit = index % 8;
|
||||
if exists {
|
||||
self.0[byte] |= 1 << bit;
|
||||
} else {
|
||||
self.0[byte] &= !(1 << bit);
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
const fn get(&self, index: usize) -> bool {
|
||||
let byte = index / 8;
|
||||
let bit = index % 8;
|
||||
(self.0[byte] >> bit) & 1 == 1
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// NBT features dictionary
|
||||
// ---------------------------------------------------------------------------
|
||||
//
|
||||
// Repeated: u8 key_len, key bytes, u32 value
|
||||
// Terminated by a single 0x00 byte.
|
||||
|
||||
struct NbtFeatures(HashMap<String, u32>);
|
||||
|
||||
impl NbtFeatures {
|
||||
fn empty() -> Self {
|
||||
Self(HashMap::new())
|
||||
}
|
||||
|
||||
fn from_bytes(buf: &mut impl Buf) -> Result<Self, ChunkReadingError> {
|
||||
let mut map = HashMap::new();
|
||||
loop {
|
||||
if !buf.has_remaining() {
|
||||
return Err(ChunkReadingError::IoError(std::io::Error::from(
|
||||
ErrorKind::UnexpectedEof,
|
||||
)));
|
||||
}
|
||||
let key_len = buf.get_u8();
|
||||
if key_len == 0 {
|
||||
break;
|
||||
}
|
||||
if buf.remaining() < key_len as usize + 4 {
|
||||
return Err(ChunkReadingError::IoError(std::io::Error::from(
|
||||
ErrorKind::UnexpectedEof,
|
||||
)));
|
||||
}
|
||||
let key_bytes: Vec<u8> = (0..key_len).map(|_| buf.get_u8()).collect();
|
||||
let key = String::from_utf8(key_bytes).map_err(|_| ChunkReadingError::InvalidHeader)?;
|
||||
let value = buf.get_u32();
|
||||
map.insert(key, value);
|
||||
}
|
||||
Ok(Self(map))
|
||||
}
|
||||
|
||||
fn to_bytes(&self) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
for (key, value) in &self.0 {
|
||||
let key_bytes = key.as_bytes();
|
||||
out.push(key_bytes.len() as u8);
|
||||
out.extend_from_slice(key_bytes);
|
||||
out.extend_from_slice(&value.to_be_bytes());
|
||||
}
|
||||
out.push(0); // end marker
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Bucket size entry (13 bytes per bucket)
|
||||
// ---------------------------------------------------------------------------
|
||||
//
|
||||
// 0..4 uint32 Bucket size (compressed)
|
||||
// 4..5 int8 Compression level
|
||||
// 5..13 uint64 xxhash64 of compressed bucket data
|
||||
|
||||
struct BucketSizeEntry {
|
||||
size: u32,
|
||||
compression_level: i8,
|
||||
xxhash: u64,
|
||||
}
|
||||
|
||||
impl BucketSizeEntry {
|
||||
const SIZE: usize = 13;
|
||||
|
||||
fn from_bytes(buf: &mut impl Buf) -> Result<Self, ChunkReadingError> {
|
||||
if buf.remaining() < Self::SIZE {
|
||||
return Err(ChunkReadingError::IoError(std::io::Error::from(
|
||||
ErrorKind::UnexpectedEof,
|
||||
)));
|
||||
}
|
||||
Ok(Self {
|
||||
size: buf.get_u32(),
|
||||
compression_level: buf.get_i8(),
|
||||
xxhash: buf.get_u64(),
|
||||
})
|
||||
}
|
||||
|
||||
fn to_bytes(&self) -> [u8; Self::SIZE] {
|
||||
let mut out = [0u8; Self::SIZE];
|
||||
let mut b = out.as_mut_slice();
|
||||
b.put_u32(self.size);
|
||||
b.put_i8(self.compression_level);
|
||||
b.put_u64(self.xxhash);
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Per-chunk record inside a decompressed bucket
|
||||
// ---------------------------------------------------------------------------
|
||||
//
|
||||
// 0.. 4 uint32 Chunk size (0 = absent)
|
||||
// 4..12 uint64 Chunk timestamp
|
||||
// 12.. bytes Chunk NBT data (only when size > 0)
|
||||
|
||||
struct BucketChunkEntry {
|
||||
timestamp: u64,
|
||||
data: Option<Bytes>,
|
||||
}
|
||||
|
||||
impl BucketChunkEntry {
|
||||
/// Number of bytes for the fixed part (size + timestamp).
|
||||
const FIXED_SIZE: usize = 12;
|
||||
|
||||
fn write_into(&self, out: &mut Vec<u8>) {
|
||||
match &self.data {
|
||||
None => {
|
||||
out.put_u32(0);
|
||||
out.put_u64(self.timestamp);
|
||||
}
|
||||
Some(bytes) => {
|
||||
out.put_u32(bytes.len() as u32);
|
||||
out.put_u64(self.timestamp);
|
||||
out.extend_from_slice(bytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn read_from(buf: &mut Bytes) -> Result<Self, ChunkReadingError> {
|
||||
if buf.remaining() < Self::FIXED_SIZE {
|
||||
return Err(ChunkReadingError::IoError(std::io::Error::from(
|
||||
ErrorKind::UnexpectedEof,
|
||||
)));
|
||||
}
|
||||
let size = buf.get_u32() as usize;
|
||||
let timestamp = buf.get_u64();
|
||||
if size == 0 {
|
||||
return Ok(Self {
|
||||
timestamp,
|
||||
data: None,
|
||||
});
|
||||
}
|
||||
if buf.remaining() < size {
|
||||
warn!(
|
||||
"Linear v2: not enough bytes for chunk (need {size}, have {})",
|
||||
buf.remaining()
|
||||
);
|
||||
return Err(ChunkReadingError::IoError(std::io::Error::from(
|
||||
ErrorKind::UnexpectedEof,
|
||||
)));
|
||||
}
|
||||
let data = buf.split_to(size);
|
||||
Ok(Self {
|
||||
timestamp,
|
||||
data: Some(data),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Main LinearV2File struct
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
pub struct LinearV2File<S: SingleChunkDataSerializer> {
|
||||
/// Region coordinates, needed to rebuild the superblock on write.
|
||||
region_x: i32,
|
||||
region_z: i32,
|
||||
|
||||
/// Grid size (1, 2, 4, 8, 16, or 32).
|
||||
grid_size: u8,
|
||||
|
||||
/// Per-chunk timestamps.
|
||||
timestamps: [u64; CHUNK_COUNT],
|
||||
|
||||
/// Per-chunk compressed NBT data (None = chunk absent).
|
||||
chunks_data: [Option<Bytes>; CHUNK_COUNT],
|
||||
|
||||
_dummy: PhantomData<S>,
|
||||
}
|
||||
|
||||
#[expect(clippy::large_stack_arrays)]
|
||||
impl<S: SingleChunkDataSerializer> Default for LinearV2File<S> {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
region_x: 0,
|
||||
region_z: 0,
|
||||
grid_size: DEFAULT_GRID_SIZE,
|
||||
timestamps: [0u64; CHUNK_COUNT],
|
||||
chunks_data: [const { None }; CHUNK_COUNT],
|
||||
_dummy: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: SingleChunkDataSerializer> LinearV2File<S> {
|
||||
const fn get_chunk_index(x: i32, z: i32) -> usize {
|
||||
AnvilChunkFile::<S>::get_chunk_index(x, z)
|
||||
}
|
||||
|
||||
/// Number of buckets in the grid (`grid_size²`).
|
||||
const fn bucket_count(grid_size: u8) -> usize {
|
||||
(grid_size as usize) * (grid_size as usize)
|
||||
}
|
||||
|
||||
/// Number of chunks in each bucket.
|
||||
const fn chunks_per_bucket(grid_size: u8) -> usize {
|
||||
CHUNK_COUNT / Self::bucket_count(grid_size)
|
||||
}
|
||||
|
||||
/// Build the decompressed byte stream for bucket `bucket_idx`.
|
||||
fn serialise_bucket(&self, bucket_idx: usize) -> Vec<u8> {
|
||||
let grid_size = self.grid_size;
|
||||
let cpb = Self::chunks_per_bucket(grid_size);
|
||||
let mut buf = Vec::new();
|
||||
|
||||
for local in 0..cpb {
|
||||
// Recover the global chunk index from bucket + local.
|
||||
let chunk_index = Self::global_chunk_index(bucket_idx, local, grid_size);
|
||||
let entry = BucketChunkEntry {
|
||||
timestamp: self.timestamps[chunk_index],
|
||||
data: self.chunks_data[chunk_index].clone(),
|
||||
};
|
||||
entry.write_into(&mut buf);
|
||||
}
|
||||
buf
|
||||
}
|
||||
|
||||
/// Inverse of `chunk_bucket_index` + `chunk_local_index`.
|
||||
const fn global_chunk_index(bucket_idx: usize, local: usize, grid_size: u8) -> usize {
|
||||
let stride = 32 / grid_size as usize;
|
||||
let bucket_row = bucket_idx / grid_size as usize;
|
||||
let bucket_col = bucket_idx % grid_size as usize;
|
||||
let local_row = local / stride;
|
||||
let local_col = local % stride;
|
||||
let cz = bucket_row * stride + local_row;
|
||||
let cx = bucket_col * stride + local_col;
|
||||
cz * 32 + cx
|
||||
}
|
||||
|
||||
fn build_bitmap(&self) -> ChunkBitmap {
|
||||
let mut bitmap = ChunkBitmap::new();
|
||||
for (i, chunk) in self.chunks_data.iter().enumerate() {
|
||||
bitmap.set(i, chunk.is_some());
|
||||
}
|
||||
bitmap
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: SingleChunkDataSerializer> ChunkSerializer for LinearV2File<S> {
|
||||
type Data = S;
|
||||
type WriteBackend = PathBuf;
|
||||
type ChunkConfig = ();
|
||||
|
||||
fn should_write(&self, is_watched: bool) -> bool {
|
||||
!is_watched
|
||||
}
|
||||
|
||||
fn get_chunk_key(chunk: &Vector2<i32>) -> String {
|
||||
let (region_x, region_z) = AnvilChunkFile::<S>::get_region_coords(chunk);
|
||||
format!("./r.{region_x}.{region_z}.linear")
|
||||
}
|
||||
|
||||
async fn write(&self, path: &PathBuf) -> Result<(), std::io::Error> {
|
||||
let temp_path = path.with_extension("tmp");
|
||||
let file = tokio::fs::File::create(&temp_path).await?;
|
||||
let mut writer = BufWriter::new(file);
|
||||
|
||||
let grid_size = self.grid_size;
|
||||
let bucket_count = Self::bucket_count(grid_size);
|
||||
|
||||
let mut compressed_buckets: Vec<Box<[u8]>> = Vec::with_capacity(bucket_count);
|
||||
let mut bucket_entries: Vec<BucketSizeEntry> = Vec::with_capacity(bucket_count);
|
||||
|
||||
for bucket_idx in 0..bucket_count {
|
||||
let raw = self.serialise_bucket(bucket_idx);
|
||||
// TODO: ruzstd currently only supports Fastest level.
|
||||
let compressed =
|
||||
compress_to_vec(raw.as_slice(), CompressionLevel::Fastest).into_boxed_slice();
|
||||
let hash = xxh64(&compressed, 0);
|
||||
bucket_entries.push(BucketSizeEntry {
|
||||
size: compressed.len() as u32,
|
||||
compression_level: 1,
|
||||
xxhash: hash,
|
||||
});
|
||||
compressed_buckets.push(compressed);
|
||||
}
|
||||
|
||||
let newest_timestamp = self.timestamps.iter().copied().max().unwrap_or(0);
|
||||
|
||||
let superblock = LinearV2Superblock {
|
||||
newest_timestamp,
|
||||
grid_size,
|
||||
region_x: self.region_x,
|
||||
region_z: self.region_z,
|
||||
};
|
||||
|
||||
let bitmap = self.build_bitmap();
|
||||
|
||||
let features = NbtFeatures::empty();
|
||||
|
||||
writer.write_all(&superblock.to_bytes()).await?;
|
||||
writer.write_all(&bitmap.0).await?;
|
||||
writer.write_all(&features.to_bytes()).await?;
|
||||
|
||||
for entry in &bucket_entries {
|
||||
writer.write_all(&entry.to_bytes()).await?;
|
||||
}
|
||||
|
||||
for compressed in &compressed_buckets {
|
||||
writer.write_all(compressed).await?;
|
||||
}
|
||||
|
||||
writer.write_all(&SIGNATURE).await?;
|
||||
writer.flush().await?;
|
||||
|
||||
// Atomic rename so a crash during write cannot produce a torn file.
|
||||
tokio::fs::rename(temp_path, path).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[expect(clippy::large_stack_arrays)]
|
||||
fn read(raw_file: Bytes) -> Result<Self, ChunkReadingError> {
|
||||
let mut buf = raw_file;
|
||||
|
||||
if buf.remaining() < LinearV2Superblock::SIZE {
|
||||
return Err(ChunkReadingError::IoError(std::io::Error::from(
|
||||
ErrorKind::UnexpectedEof,
|
||||
)));
|
||||
}
|
||||
let superblock_bytes = buf.split_to(LinearV2Superblock::SIZE);
|
||||
let superblock = LinearV2Superblock::from_bytes(&superblock_bytes)?;
|
||||
let grid_size = superblock.grid_size;
|
||||
let bucket_count = Self::bucket_count(grid_size);
|
||||
|
||||
if buf.remaining() < ChunkBitmap::SIZE {
|
||||
return Err(ChunkReadingError::IoError(std::io::Error::from(
|
||||
ErrorKind::UnexpectedEof,
|
||||
)));
|
||||
}
|
||||
// We read the bitmap but per the spec it is not yet reliable, so we
|
||||
// do not use it to short-circuit — actual presence is determined by
|
||||
// the per-chunk size field inside each bucket.
|
||||
let mut bitmap_raw = [0u8; ChunkBitmap::SIZE];
|
||||
bitmap_raw.copy_from_slice(&buf.split_to(ChunkBitmap::SIZE));
|
||||
//let _bitmap = ChunkBitmap(bitmap_raw);
|
||||
|
||||
let _features = NbtFeatures::from_bytes(&mut buf)?;
|
||||
|
||||
let total_bucket_meta = bucket_count * BucketSizeEntry::SIZE;
|
||||
if buf.remaining() < total_bucket_meta {
|
||||
return Err(ChunkReadingError::IoError(std::io::Error::from(
|
||||
ErrorKind::UnexpectedEof,
|
||||
)));
|
||||
}
|
||||
let mut bucket_entries: Vec<BucketSizeEntry> = Vec::with_capacity(bucket_count);
|
||||
for _ in 0..bucket_count {
|
||||
bucket_entries.push(BucketSizeEntry::from_bytes(&mut buf)?);
|
||||
}
|
||||
|
||||
// Work out where the footer starts so we can validate it without
|
||||
// consuming the bucket data bytes yet.
|
||||
let total_compressed: usize = bucket_entries.iter().map(|e| e.size as usize).sum();
|
||||
if buf.remaining() < total_compressed + SIGNATURE.len() {
|
||||
return Err(ChunkReadingError::IoError(std::io::Error::from(
|
||||
ErrorKind::UnexpectedEof,
|
||||
)));
|
||||
}
|
||||
let footer_offset = total_compressed;
|
||||
{
|
||||
let footer = &buf[footer_offset..footer_offset + SIGNATURE.len()];
|
||||
if footer != SIGNATURE {
|
||||
error!("Linear v2: invalid footer signature");
|
||||
return Err(ChunkReadingError::InvalidHeader);
|
||||
}
|
||||
}
|
||||
|
||||
let mut timestamps = [0u64; CHUNK_COUNT];
|
||||
let mut chunks_data: [Option<Bytes>; CHUNK_COUNT] = [const { None }; CHUNK_COUNT];
|
||||
|
||||
for (bucket_idx, entry) in bucket_entries.iter().enumerate() {
|
||||
let compressed_size = entry.size as usize;
|
||||
|
||||
// xxhash64 integrity check.
|
||||
let actual_hash = xxh64(&buf[..compressed_size], 0);
|
||||
if actual_hash != entry.xxhash {
|
||||
error!(
|
||||
"Linear v2: xxhash mismatch for bucket {bucket_idx} \
|
||||
(expected {:#x}, got {:#x})",
|
||||
entry.xxhash, actual_hash
|
||||
);
|
||||
// Skip the corrupted bucket rather than aborting the whole
|
||||
// file — the remaining buckets may be intact.
|
||||
buf.advance(compressed_size);
|
||||
continue;
|
||||
}
|
||||
|
||||
let compressed_slice = &buf[..compressed_size];
|
||||
let mut decompressed = Vec::new();
|
||||
{
|
||||
let mut decoder = StreamingDecoder::new(compressed_slice)
|
||||
.map_err(|_| ChunkReadingError::RegionIsInvalid)?;
|
||||
decoder
|
||||
.read_to_end(&mut decompressed)
|
||||
.map_err(ChunkReadingError::IoError)?
|
||||
};
|
||||
buf.advance(compressed_size);
|
||||
|
||||
let mut bucket_buf: Bytes = decompressed.into();
|
||||
let cpb = Self::chunks_per_bucket(grid_size);
|
||||
|
||||
for local in 0..cpb {
|
||||
let chunk_index = Self::global_chunk_index(bucket_idx, local, grid_size);
|
||||
let record = BucketChunkEntry::read_from(&mut bucket_buf)?;
|
||||
timestamps[chunk_index] = record.timestamp;
|
||||
chunks_data[chunk_index] = record.data;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
region_x: superblock.region_x,
|
||||
region_z: superblock.region_z,
|
||||
grid_size,
|
||||
timestamps,
|
||||
chunks_data,
|
||||
_dummy: PhantomData,
|
||||
})
|
||||
}
|
||||
|
||||
async fn update_chunk(
|
||||
&mut self,
|
||||
chunk: &Self::Data,
|
||||
_chunk_config: &Self::ChunkConfig,
|
||||
) -> Result<(), ChunkWritingError> {
|
||||
let index = Self::get_chunk_index(chunk.position().0, chunk.position().1);
|
||||
let chunk_raw: Bytes = chunk
|
||||
.to_bytes()
|
||||
.await
|
||||
.map_err(|err| ChunkWritingError::ChunkSerializingError(err.to_string()))?;
|
||||
|
||||
self.timestamps[index] = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map_or(0, |d| d.as_secs());
|
||||
self.chunks_data[index] = Some(chunk_raw);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn get_chunks(
|
||||
&self,
|
||||
chunks: Vec<Vector2<i32>>,
|
||||
stream: tokio::sync::mpsc::Sender<LoadedData<Self::Data, ChunkReadingError>>,
|
||||
) {
|
||||
for chunk in chunks {
|
||||
let index = Self::get_chunk_index(chunk.x, chunk.y);
|
||||
|
||||
let result = self.chunks_data[index].as_ref().map_or_else(
|
||||
|| LoadedData::Missing(chunk),
|
||||
|data| match S::from_bytes(data, chunk) {
|
||||
Ok(c) => LoadedData::Loaded(c),
|
||||
Err(err) => LoadedData::Error((chunk, err)),
|
||||
},
|
||||
);
|
||||
|
||||
if stream.send(result).await.is_err() {
|
||||
// Receiver dropped — stop early to avoid unnecessary work.
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
// Helper: build a tiny chunk payload.
|
||||
fn fake_nbt(seed: u8) -> Bytes {
|
||||
Bytes::from(vec![seed; 64])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bitmap_round_trip() {
|
||||
let mut bm = ChunkBitmap::new();
|
||||
bm.set(0, true);
|
||||
bm.set(7, true);
|
||||
bm.set(1023, true);
|
||||
assert!(bm.get(0));
|
||||
assert!(!bm.get(1));
|
||||
assert!(bm.get(7));
|
||||
assert!(!bm.get(8));
|
||||
assert!(bm.get(1023));
|
||||
assert!(!bm.get(1022));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nbt_features_empty_round_trip() {
|
||||
let f = NbtFeatures::empty();
|
||||
let encoded = f.to_bytes();
|
||||
assert_eq!(encoded, vec![0u8]); // just the end marker
|
||||
|
||||
let mut buf: Bytes = encoded.into();
|
||||
let decoded = NbtFeatures::from_bytes(&mut buf).unwrap();
|
||||
assert!(decoded.0.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nbt_features_round_trip() {
|
||||
let mut f = NbtFeatures::empty();
|
||||
f.0.insert("version".into(), 42);
|
||||
let encoded = f.to_bytes();
|
||||
let mut buf: Bytes = encoded.into();
|
||||
let decoded = NbtFeatures::from_bytes(&mut buf).unwrap();
|
||||
assert_eq!(decoded.0.get("version"), Some(&42u32));
|
||||
}
|
||||
|
||||
fn chunk_bucket_index(i: usize, gs: u8) -> usize {
|
||||
let cx = i % 32;
|
||||
let cz = i / 32;
|
||||
let stride = 32 / gs as usize;
|
||||
(cz / stride) * gs as usize + (cx / stride)
|
||||
}
|
||||
|
||||
fn chunk_local_index(i: usize, gs: u8) -> usize {
|
||||
let cx = i % 32;
|
||||
let cz = i / 32;
|
||||
let stride = 32 / gs as usize;
|
||||
(cz % stride) * stride + (cx % stride)
|
||||
}
|
||||
|
||||
fn global_chunk_index(bucket: usize, local: usize, gs: u8) -> usize {
|
||||
let stride = 32 / gs as usize;
|
||||
let brow = bucket / gs as usize;
|
||||
let bcol = bucket % gs as usize;
|
||||
let lrow = local / stride;
|
||||
let lcol = local % stride;
|
||||
let cz = brow * stride + lrow;
|
||||
let cx = bcol * stride + lcol;
|
||||
cz * 32 + cx
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn index_round_trip_grid2() {
|
||||
for i in 0..CHUNK_COUNT {
|
||||
let b = chunk_bucket_index(i, 2);
|
||||
let l = chunk_local_index(i, 2);
|
||||
let recovered = global_chunk_index(b, l, 2);
|
||||
assert_eq!(i, recovered, "chunk index {i} round-trip failed");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn index_round_trip_grid4() {
|
||||
for i in 0..CHUNK_COUNT {
|
||||
let b = chunk_bucket_index(i, 4);
|
||||
let l = chunk_local_index(i, 4);
|
||||
let recovered = global_chunk_index(b, l, 4);
|
||||
assert_eq!(i, recovered, "chunk index {i} round-trip failed");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn index_round_trip_grid1() {
|
||||
for i in 0..CHUNK_COUNT {
|
||||
let b = chunk_bucket_index(i, 1);
|
||||
let l = chunk_local_index(i, 1);
|
||||
let recovered = global_chunk_index(b, l, 1);
|
||||
assert_eq!(i, recovered, "chunk index {i} round-trip failed");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn superblock_round_trip() {
|
||||
let sb = LinearV2Superblock {
|
||||
newest_timestamp: 0xDEADBEEFCAFEBABE,
|
||||
grid_size: 4,
|
||||
region_x: -7,
|
||||
region_z: 13,
|
||||
};
|
||||
let encoded = sb.to_bytes();
|
||||
let decoded = LinearV2Superblock::from_bytes(&encoded).unwrap();
|
||||
assert_eq!(decoded.newest_timestamp, sb.newest_timestamp);
|
||||
assert_eq!(decoded.grid_size, 4);
|
||||
assert_eq!(decoded.region_x, -7);
|
||||
assert_eq!(decoded.region_z, 13);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn superblock_rejects_bad_signature() {
|
||||
let mut bytes = LinearV2Superblock {
|
||||
newest_timestamp: 0,
|
||||
grid_size: 2,
|
||||
region_x: 0,
|
||||
region_z: 0,
|
||||
}
|
||||
.to_bytes();
|
||||
bytes[0] ^= 0xFF; // corrupt the signature
|
||||
assert!(LinearV2Superblock::from_bytes(&bytes).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bucket_entry_present_round_trip() {
|
||||
let entry = BucketChunkEntry {
|
||||
timestamp: 12345,
|
||||
data: Some(fake_nbt(0xAB)),
|
||||
};
|
||||
let mut buf = Vec::new();
|
||||
entry.write_into(&mut buf);
|
||||
let mut b: Bytes = buf.into();
|
||||
let decoded = BucketChunkEntry::read_from(&mut b).unwrap();
|
||||
assert_eq!(decoded.timestamp, 12345);
|
||||
assert_eq!(decoded.data.unwrap().as_ref(), &[0xABu8; 64][..]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bucket_entry_absent_round_trip() {
|
||||
let entry = BucketChunkEntry {
|
||||
timestamp: 0,
|
||||
data: None,
|
||||
};
|
||||
let mut buf = Vec::new();
|
||||
entry.write_into(&mut buf);
|
||||
let mut b: Bytes = buf.into();
|
||||
let decoded = BucketChunkEntry::read_from(&mut b).unwrap();
|
||||
assert!(decoded.data.is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,758 @@
|
||||
use std::{
|
||||
path::PathBuf,
|
||||
pin::Pin,
|
||||
str::FromStr,
|
||||
sync::{
|
||||
RwLock,
|
||||
atomic::{AtomicBool, AtomicU64, Ordering},
|
||||
},
|
||||
};
|
||||
|
||||
use bytes::Bytes;
|
||||
use pumpkin_data::{Block, BlockStateId, chunk::ChunkStatus, fluid::Fluid};
|
||||
use pumpkin_nbt::compound::NbtCompound;
|
||||
use pumpkin_util::resource_location::{FromResourceLocation, ResourceLocation, ToResourceLocation};
|
||||
use rustc_hash::FxHashMap;
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
use crate::{
|
||||
chunk::{
|
||||
ChunkEntityData, ChunkReadingError, ChunkSerializingError,
|
||||
format::anvil::{SingleChunkDataSerializer, WORLD_DATA_VERSION},
|
||||
io::{Dirtiable, file_manager::PathFromLevelFolder},
|
||||
},
|
||||
generation::section_coords,
|
||||
level::LevelFolder,
|
||||
tick::{ScheduledTick, TickPriority, scheduler::ChunkTickScheduler},
|
||||
};
|
||||
use pumpkin_util::math::position::BlockPos;
|
||||
use pumpkin_util::math::vector2::Vector2;
|
||||
|
||||
use super::{
|
||||
ChunkData, ChunkHeightmaps, ChunkLight, ChunkParsingError, ChunkSections,
|
||||
palette::{BiomePalette, BlockPalette},
|
||||
};
|
||||
pub mod anvil;
|
||||
pub mod linear;
|
||||
pub mod pump;
|
||||
|
||||
impl SingleChunkDataSerializer for ChunkData {
|
||||
#[inline]
|
||||
fn from_bytes(bytes: &Bytes, pos: Vector2<i32>) -> Result<Self, ChunkReadingError> {
|
||||
Self::internal_from_bytes(bytes, pos).map_err(ChunkReadingError::ParsingError)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn to_bytes(
|
||||
&self,
|
||||
) -> Pin<Box<dyn Future<Output = Result<Bytes, ChunkSerializingError>> + Send + '_>> {
|
||||
Box::pin(async move { Ok(self.internal_to_bytes()) })
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn position(&self) -> (i32, i32) {
|
||||
(self.x, self.z)
|
||||
}
|
||||
}
|
||||
|
||||
impl PathFromLevelFolder for ChunkData {
|
||||
#[inline]
|
||||
fn file_path(folder: &LevelFolder, file_name: &str) -> PathBuf {
|
||||
folder.region_folder.join(file_name)
|
||||
}
|
||||
}
|
||||
|
||||
impl Dirtiable for ChunkData {
|
||||
#[inline]
|
||||
fn mark_dirty(&self, flag: bool) {
|
||||
self.dirty.store(flag, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn is_dirty(&self) -> bool {
|
||||
self.dirty.load(Ordering::Relaxed)
|
||||
}
|
||||
}
|
||||
|
||||
fn extract_u16_array(tag: &pumpkin_nbt::tag::NbtTag) -> Option<Box<[BlockStateId]>> {
|
||||
match tag {
|
||||
pumpkin_nbt::tag::NbtTag::IntArray(arr) => Some(
|
||||
arr.iter()
|
||||
.map(|&x| BlockStateId::new_or_air(x as u16))
|
||||
.collect(),
|
||||
),
|
||||
pumpkin_nbt::tag::NbtTag::ByteArray(arr) => Some(
|
||||
arr.iter()
|
||||
.map(|&x| BlockStateId::new_or_air(x as u16))
|
||||
.collect(),
|
||||
),
|
||||
pumpkin_nbt::tag::NbtTag::LongArray(arr) => Some(
|
||||
arr.iter()
|
||||
.map(|&x| BlockStateId::new_or_air(x as u16))
|
||||
.collect(),
|
||||
),
|
||||
pumpkin_nbt::tag::NbtTag::List(list) => {
|
||||
let ids: Box<[BlockStateId]> = list
|
||||
.iter()
|
||||
.map(|t| {
|
||||
let val = match t {
|
||||
pumpkin_nbt::tag::NbtTag::Int(x) => *x as u16,
|
||||
pumpkin_nbt::tag::NbtTag::Short(x) => *x as u16,
|
||||
pumpkin_nbt::tag::NbtTag::Byte(x) => *x as u16,
|
||||
pumpkin_nbt::tag::NbtTag::Long(x) => *x as u16,
|
||||
_ => 0,
|
||||
};
|
||||
BlockStateId::new_or_air(val)
|
||||
})
|
||||
.collect();
|
||||
Some(ids)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn extract_u8_array(tag: &pumpkin_nbt::tag::NbtTag) -> Option<Box<[u8]>> {
|
||||
match tag {
|
||||
pumpkin_nbt::tag::NbtTag::ByteArray(arr) => Some(arr.iter().map(|&x| x as u8).collect()),
|
||||
pumpkin_nbt::tag::NbtTag::IntArray(arr) => Some(arr.iter().map(|&x| x as u8).collect()),
|
||||
pumpkin_nbt::tag::NbtTag::List(list) => {
|
||||
let bytes: Box<[u8]> = list
|
||||
.iter()
|
||||
.map(|t| match t {
|
||||
pumpkin_nbt::tag::NbtTag::Byte(x) => *x as u8,
|
||||
pumpkin_nbt::tag::NbtTag::Int(x) => *x as u8,
|
||||
pumpkin_nbt::tag::NbtTag::Short(x) => *x as u8,
|
||||
_ => 0,
|
||||
})
|
||||
.collect();
|
||||
Some(bytes)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_scheduled_tick<T>(nbt: &pumpkin_nbt::compound::NbtCompound) -> Option<ScheduledTick<T>>
|
||||
where
|
||||
T: FromResourceLocation,
|
||||
{
|
||||
let x = nbt.get_int("x")?;
|
||||
let y = nbt.get_int("y")?;
|
||||
let z = nbt.get_int("z")?;
|
||||
let delay = nbt.get_int("t")? as u8;
|
||||
let priority = TickPriority::try_from(nbt.get_int("p")?).ok()?;
|
||||
let res_loc_str = nbt.get_string("i")?;
|
||||
let res_loc = ResourceLocation::from_str(res_loc_str).ok()?;
|
||||
let value = T::from_resource_location(&res_loc)?;
|
||||
Some(ScheduledTick {
|
||||
delay,
|
||||
priority,
|
||||
position: BlockPos::new(x, y, z),
|
||||
value,
|
||||
})
|
||||
}
|
||||
|
||||
impl ChunkData {
|
||||
#[allow(clippy::too_many_lines)]
|
||||
pub fn internal_from_bytes(
|
||||
chunk_data: &[u8],
|
||||
position: Vector2<i32>,
|
||||
) -> Result<Self, ChunkParsingError> {
|
||||
let is_named = chunk_data.len() >= 3
|
||||
&& chunk_data[0] == 0x0a
|
||||
&& chunk_data[1] == 0x00
|
||||
&& chunk_data[2] == 0x00;
|
||||
|
||||
let mut cursor = std::io::Cursor::new(chunk_data);
|
||||
let mut reader = pumpkin_nbt::deserializer::NbtReadHelperJava::new(&mut cursor);
|
||||
let nbt = if is_named {
|
||||
pumpkin_nbt::Nbt::read(&mut reader)
|
||||
} else {
|
||||
pumpkin_nbt::Nbt::read_unnamed(&mut reader)
|
||||
}
|
||||
.map_err(|e| ChunkParsingError::ErrorDeserializingChunk(e.to_string()))?;
|
||||
|
||||
let root_tag = nbt.root_tag;
|
||||
|
||||
let x_pos = root_tag.get_int("xPos").ok_or_else(|| {
|
||||
ChunkParsingError::ErrorDeserializingChunk("Missing xPos".to_string())
|
||||
})?;
|
||||
let z_pos = root_tag.get_int("zPos").ok_or_else(|| {
|
||||
ChunkParsingError::ErrorDeserializingChunk("Missing zPos".to_string())
|
||||
})?;
|
||||
|
||||
if x_pos != position.x || z_pos != position.y {
|
||||
return Err(ChunkParsingError::ErrorDeserializingChunk(format!(
|
||||
"Expected data for chunk {},{} but got it for {},{}!",
|
||||
position.x, position.y, x_pos, z_pos,
|
||||
)));
|
||||
}
|
||||
|
||||
let min_y_section = root_tag.get_int("yPos").ok_or_else(|| {
|
||||
ChunkParsingError::ErrorDeserializingChunk("Missing yPos".to_string())
|
||||
})?;
|
||||
|
||||
let mut max_y_section = min_y_section as i8;
|
||||
if let Some(sections_list) = root_tag.get_list("sections") {
|
||||
for section_tag in sections_list {
|
||||
if let pumpkin_nbt::tag::NbtTag::Compound(section_compound) = section_tag {
|
||||
let y = section_compound.get_byte("Y").unwrap_or(0);
|
||||
if y > max_y_section {
|
||||
max_y_section = y;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let section_count = (max_y_section as i32 - min_y_section + 1).max(0) as usize;
|
||||
let mut block_lights = vec![LightContainer::Empty(0); section_count];
|
||||
let mut sky_lights = vec![LightContainer::Empty(0); section_count];
|
||||
let mut block_palettes = vec![BlockPalette::default(); section_count];
|
||||
let mut biome_palettes = vec![BiomePalette::default(); section_count];
|
||||
|
||||
if let Some(sections_list) = root_tag.get_list("sections") {
|
||||
for section_tag in sections_list {
|
||||
if let pumpkin_nbt::tag::NbtTag::Compound(section_compound) = section_tag {
|
||||
let y = section_compound.get_byte("Y").unwrap_or(0);
|
||||
let index = (y as i32 - min_y_section) as usize;
|
||||
if index >= section_count {
|
||||
continue;
|
||||
}
|
||||
|
||||
let block_light = section_compound
|
||||
.get("BlockLight")
|
||||
.and_then(|tag| tag.extract_byte_array())
|
||||
.map(|arr| {
|
||||
// SAFETY: `arr` is an `i8` slice (`&[i8]`). `u8` and `i8` have identical memory layout, alignment (1 byte), and lifetime.
|
||||
unsafe {
|
||||
Box::from(std::slice::from_raw_parts(
|
||||
arr.as_ptr().cast::<u8>(),
|
||||
arr.len(),
|
||||
))
|
||||
}
|
||||
});
|
||||
|
||||
let sky_light = section_compound
|
||||
.get("SkyLight")
|
||||
.and_then(|tag| tag.extract_byte_array())
|
||||
.map(|arr| {
|
||||
// SAFETY: `arr` is an `i8` slice (`&[i8]`). `u8` and `i8` have identical memory layout, alignment (1 byte), and lifetime.
|
||||
unsafe {
|
||||
Box::from(std::slice::from_raw_parts(
|
||||
arr.as_ptr().cast::<u8>(),
|
||||
arr.len(),
|
||||
))
|
||||
}
|
||||
});
|
||||
|
||||
block_lights[index] =
|
||||
block_light.map_or(LightContainer::Empty(0), LightContainer::Full);
|
||||
sky_lights[index] =
|
||||
sky_light.map_or(LightContainer::Empty(0), LightContainer::Full);
|
||||
|
||||
if let Some(bs_compound) = section_compound.get_compound("block_states") {
|
||||
let data = bs_compound
|
||||
.get_long_array("data")
|
||||
.map(|arr| arr.to_vec().into_boxed_slice());
|
||||
let palette = bs_compound
|
||||
.get("palette")
|
||||
.and_then(extract_u16_array)
|
||||
.unwrap_or_else(|| vec![BlockStateId::AIR].into_boxed_slice());
|
||||
|
||||
block_palettes[index] =
|
||||
BlockPalette::from_disk_nbt(ChunkSectionBlockStates { data, palette });
|
||||
} else {
|
||||
block_palettes[index] = BlockPalette::default();
|
||||
}
|
||||
|
||||
if let Some(b_compound) = section_compound.get_compound("biomes") {
|
||||
let data = b_compound
|
||||
.get_long_array("data")
|
||||
.map(|arr| arr.to_vec().into_boxed_slice());
|
||||
let palette = b_compound
|
||||
.get("palette")
|
||||
.and_then(extract_u8_array)
|
||||
.unwrap_or_else(|| vec![0].into_boxed_slice());
|
||||
|
||||
biome_palettes[index] =
|
||||
BiomePalette::from_disk_nbt(ChunkSectionBiomes { data, palette });
|
||||
} else {
|
||||
biome_palettes[index] = BiomePalette::default();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Assemble the LightEngine
|
||||
let light_engine = ChunkLight {
|
||||
block_light: block_lights.into_boxed_slice(),
|
||||
sky_light: sky_lights.into_boxed_slice(),
|
||||
};
|
||||
|
||||
// Assemble the ChunkSections
|
||||
let min_y = section_coords::section_to_block(min_y_section);
|
||||
let (random_tick_sections, randomly_ticking_mask) =
|
||||
ChunkSections::build_random_tick_sections_cache(&block_palettes);
|
||||
let section = ChunkSections {
|
||||
count: block_palettes.len(),
|
||||
block_sections: RwLock::new(block_palettes.into_boxed_slice()),
|
||||
random_tick_sections: RwLock::new(random_tick_sections),
|
||||
randomly_ticking_mask: std::sync::atomic::AtomicU32::new(randomly_ticking_mask),
|
||||
biome_sections: RwLock::new(biome_palettes.into_boxed_slice()),
|
||||
min_y,
|
||||
};
|
||||
|
||||
let heightmaps = root_tag.get_compound("Heightmaps").map_or(
|
||||
ChunkHeightmaps {
|
||||
world_surface: None,
|
||||
motion_blocking: None,
|
||||
motion_blocking_no_leaves: None,
|
||||
},
|
||||
|h_compound| ChunkHeightmaps {
|
||||
world_surface: h_compound
|
||||
.get_long_array("WORLD_SURFACE")
|
||||
.map(|a| a.to_vec().into_boxed_slice()),
|
||||
motion_blocking: h_compound
|
||||
.get_long_array("MOTION_BLOCKING")
|
||||
.map(|a| a.to_vec().into_boxed_slice()),
|
||||
motion_blocking_no_leaves: h_compound
|
||||
.get_long_array("MOTION_BLOCKING_NO_LEAVES")
|
||||
.map(|a| a.to_vec().into_boxed_slice()),
|
||||
},
|
||||
);
|
||||
let mut block_ticks = Vec::new();
|
||||
if let Some(list) = root_tag.get_list("block_ticks") {
|
||||
for tag in list {
|
||||
if let pumpkin_nbt::tag::NbtTag::Compound(compound) = tag
|
||||
&& let Some(tick) = parse_scheduled_tick::<&'static Block>(compound)
|
||||
{
|
||||
block_ticks.push(tick);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut fluid_ticks = Vec::new();
|
||||
if let Some(list) = root_tag.get_list("fluid_ticks") {
|
||||
for tag in list {
|
||||
if let pumpkin_nbt::tag::NbtTag::Compound(compound) = tag
|
||||
&& let Some(tick) = parse_scheduled_tick::<&'static Fluid>(compound)
|
||||
{
|
||||
fluid_ticks.push(tick);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut block_entities = FxHashMap::default();
|
||||
if let Some(list) = root_tag.get_list("block_entities") {
|
||||
for tag in list {
|
||||
if let pumpkin_nbt::tag::NbtTag::Compound(nbt) = tag
|
||||
&& let Some(x) = nbt.get_int("x")
|
||||
&& let Some(y) = nbt.get_int("y")
|
||||
&& let Some(z) = nbt.get_int("z")
|
||||
{
|
||||
block_entities.insert(BlockPos::new(x, y, z), nbt.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let light_correct = root_tag.get_bool("isLightOn").unwrap_or(false);
|
||||
|
||||
let status_str = root_tag.get_string("Status").unwrap_or("minecraft:empty");
|
||||
let status = match status_str {
|
||||
"minecraft:structure_starts" => ChunkStatus::StructureStarts,
|
||||
"minecraft:structure_references" => ChunkStatus::StructureReferences,
|
||||
"minecraft:biomes" => ChunkStatus::Biomes,
|
||||
"minecraft:noise" => ChunkStatus::Noise,
|
||||
"minecraft:surface" => ChunkStatus::Surface,
|
||||
"minecraft:carvers" => ChunkStatus::Carvers,
|
||||
"minecraft:features" => ChunkStatus::Features,
|
||||
"minecraft:initialize_light" => ChunkStatus::InitializeLight,
|
||||
"minecraft:light" => ChunkStatus::Light,
|
||||
"minecraft:spawn" => ChunkStatus::Spawn,
|
||||
"minecraft:full" => ChunkStatus::Full,
|
||||
_ => ChunkStatus::Empty,
|
||||
};
|
||||
|
||||
Ok(Self {
|
||||
section,
|
||||
heightmap: std::sync::Mutex::new(heightmaps),
|
||||
x: position.x,
|
||||
z: position.y,
|
||||
// This chunk is read from disk, so it has not been modified
|
||||
dirty: AtomicBool::new(false),
|
||||
block_ticks: ChunkTickScheduler::from_iter(block_ticks),
|
||||
fluid_ticks: ChunkTickScheduler::from_iter(fluid_ticks),
|
||||
pending_block_entities: std::sync::Mutex::new(block_entities),
|
||||
light_engine: std::sync::Mutex::new(light_engine),
|
||||
light_populated: AtomicBool::new(light_correct),
|
||||
status,
|
||||
blending_data: None,
|
||||
inhabited_time: AtomicU64::new(root_tag.get_long("InhabitedTime").unwrap_or(0) as u64),
|
||||
})
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_lines)]
|
||||
fn internal_to_bytes(&self) -> Bytes {
|
||||
use pumpkin_nbt::tag::NbtTag;
|
||||
|
||||
fn extract_light_ref(light: Option<&LightContainer>) -> Option<&[u8]> {
|
||||
match light {
|
||||
Some(LightContainer::Full(data)) => Some(data.as_ref()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
let is_light_correct = self
|
||||
.light_populated
|
||||
.load(std::sync::atomic::Ordering::Relaxed);
|
||||
|
||||
let block_entities_nbt = {
|
||||
let entities_guard = self.pending_block_entities.lock().unwrap();
|
||||
entities_guard.values().cloned().collect::<Vec<_>>()
|
||||
};
|
||||
|
||||
let light_lock = self.light_engine.lock().unwrap();
|
||||
let heightmap_lock = self.heightmap.lock().unwrap();
|
||||
let block_lock = self.section.block_sections.read().unwrap();
|
||||
let biome_lock = self.section.biome_sections.read().unwrap();
|
||||
|
||||
let min_section_y = (self.section.min_y >> 4) as i8;
|
||||
|
||||
let mut root_compound = NbtCompound::new();
|
||||
root_compound.put_int("DataVersion", WORLD_DATA_VERSION);
|
||||
root_compound.put_int("xPos", self.x);
|
||||
root_compound.put_int("zPos", self.z);
|
||||
root_compound.put_int("yPos", section_coords::block_to_section(self.section.min_y));
|
||||
|
||||
let status_str = match self.status {
|
||||
ChunkStatus::Empty => "minecraft:empty",
|
||||
ChunkStatus::StructureStarts => "minecraft:structure_starts",
|
||||
ChunkStatus::StructureReferences => "minecraft:structure_references",
|
||||
ChunkStatus::Biomes => "minecraft:biomes",
|
||||
ChunkStatus::Noise => "minecraft:noise",
|
||||
ChunkStatus::Surface => "minecraft:surface",
|
||||
ChunkStatus::Carvers => "minecraft:carvers",
|
||||
ChunkStatus::Features => "minecraft:features",
|
||||
ChunkStatus::InitializeLight => "minecraft:initialize_light",
|
||||
ChunkStatus::Light => "minecraft:light",
|
||||
ChunkStatus::Spawn => "minecraft:spawn",
|
||||
ChunkStatus::Full => "minecraft:full",
|
||||
};
|
||||
root_compound.put_string("Status", status_str.to_string());
|
||||
|
||||
let mut heightmaps_compound = NbtCompound::new();
|
||||
if let Some(ref arr) = heightmap_lock.world_surface {
|
||||
heightmaps_compound.put("WORLD_SURFACE", NbtTag::LongArray(arr.to_vec()));
|
||||
}
|
||||
if let Some(ref arr) = heightmap_lock.motion_blocking {
|
||||
heightmaps_compound.put("MOTION_BLOCKING", NbtTag::LongArray(arr.to_vec()));
|
||||
}
|
||||
if let Some(ref arr) = heightmap_lock.motion_blocking_no_leaves {
|
||||
heightmaps_compound.put("MOTION_BLOCKING_NO_LEAVES", NbtTag::LongArray(arr.to_vec()));
|
||||
}
|
||||
root_compound.put_compound("Heightmaps", heightmaps_compound);
|
||||
|
||||
let mut sections_list = Vec::new();
|
||||
for i in 0..self.section.count {
|
||||
let mut section_comp = NbtCompound::new();
|
||||
let y_val = i as i8 + min_section_y;
|
||||
section_comp.put_byte("Y", y_val);
|
||||
|
||||
// block_states
|
||||
let block_states_nbt = block_lock[i].to_disk_nbt();
|
||||
let mut bs_comp = NbtCompound::new();
|
||||
if let Some(ref data_arr) = block_states_nbt.data {
|
||||
bs_comp.put("data", NbtTag::LongArray(data_arr.to_vec()));
|
||||
}
|
||||
let palette_tags: Vec<NbtTag> = block_states_nbt
|
||||
.palette
|
||||
.iter()
|
||||
.map(|id| NbtTag::Int(BlockStateId::as_u16(*id) as i32))
|
||||
.collect();
|
||||
bs_comp.put_list("palette", palette_tags);
|
||||
section_comp.put_compound("block_states", bs_comp);
|
||||
|
||||
// biomes
|
||||
let biomes_nbt = biome_lock[i].to_disk_nbt();
|
||||
let mut b_comp = NbtCompound::new();
|
||||
if let Some(ref data_arr) = biomes_nbt.data {
|
||||
b_comp.put("data", NbtTag::LongArray(data_arr.to_vec()));
|
||||
}
|
||||
let biome_palette_tags: Vec<NbtTag> = biomes_nbt
|
||||
.palette
|
||||
.iter()
|
||||
.map(|&val| NbtTag::Byte(val as i8))
|
||||
.collect();
|
||||
b_comp.put_list("palette", biome_palette_tags);
|
||||
section_comp.put_compound("biomes", b_comp);
|
||||
|
||||
// block_light
|
||||
if let Some(light_data) = extract_light_ref(light_lock.block_light.get(i)) {
|
||||
let bytes: Box<[i8]> = light_data.iter().map(|&x| x as i8).collect();
|
||||
section_comp.put("BlockLight", NbtTag::ByteArray(bytes));
|
||||
}
|
||||
|
||||
// sky_light
|
||||
if let Some(light_data) = extract_light_ref(light_lock.sky_light.get(i)) {
|
||||
let bytes: Box<[i8]> = light_data.iter().map(|&x| x as i8).collect();
|
||||
section_comp.put("SkyLight", NbtTag::ByteArray(bytes));
|
||||
}
|
||||
|
||||
sections_list.push(NbtTag::Compound(section_comp));
|
||||
}
|
||||
root_compound.put_list("sections", sections_list);
|
||||
|
||||
let mut block_ticks_list = Vec::new();
|
||||
for tick in self.block_ticks.to_vec() {
|
||||
let mut tick_comp = NbtCompound::new();
|
||||
tick_comp.put_int("x", tick.position.0.x);
|
||||
tick_comp.put_int("y", tick.position.0.y);
|
||||
tick_comp.put_int("z", tick.position.0.z);
|
||||
tick_comp.put_int("t", tick.delay as i32);
|
||||
tick_comp.put_int("p", tick.priority as i32);
|
||||
tick_comp.put_string("i", tick.value.to_resource_location());
|
||||
block_ticks_list.push(NbtTag::Compound(tick_comp));
|
||||
}
|
||||
root_compound.put_list("block_ticks", block_ticks_list);
|
||||
|
||||
let mut fluid_ticks_list = Vec::new();
|
||||
for tick in self.fluid_ticks.to_vec() {
|
||||
let mut tick_comp = NbtCompound::new();
|
||||
tick_comp.put_int("x", tick.position.0.x);
|
||||
tick_comp.put_int("y", tick.position.0.y);
|
||||
tick_comp.put_int("z", tick.position.0.z);
|
||||
tick_comp.put_int("t", tick.delay as i32);
|
||||
tick_comp.put_int("p", tick.priority as i32);
|
||||
tick_comp.put_string("i", tick.value.to_resource_location());
|
||||
fluid_ticks_list.push(NbtTag::Compound(tick_comp));
|
||||
}
|
||||
root_compound.put_list("fluid_ticks", fluid_ticks_list);
|
||||
|
||||
let mut block_entities_list = Vec::new();
|
||||
for entity_comp in block_entities_nbt {
|
||||
block_entities_list.push(NbtTag::Compound(entity_comp));
|
||||
}
|
||||
root_compound.put_list("block_entities", block_entities_list);
|
||||
|
||||
root_compound.put_bool("isLightOn", is_light_correct);
|
||||
root_compound.put_long(
|
||||
"InhabitedTime",
|
||||
self.inhabited_time.load(Ordering::Relaxed) as i64,
|
||||
);
|
||||
|
||||
let nbt = pumpkin_nbt::Nbt::from(root_compound);
|
||||
nbt.write()
|
||||
}
|
||||
}
|
||||
|
||||
impl PathFromLevelFolder for ChunkEntityData {
|
||||
#[inline]
|
||||
fn file_path(folder: &LevelFolder, file_name: &str) -> PathBuf {
|
||||
folder.entities_folder.join(file_name)
|
||||
}
|
||||
}
|
||||
|
||||
impl Dirtiable for ChunkEntityData {
|
||||
#[inline]
|
||||
fn mark_dirty(&self, flag: bool) {
|
||||
self.dirty.store(flag, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn is_dirty(&self) -> bool {
|
||||
self.dirty.load(Ordering::Relaxed)
|
||||
}
|
||||
}
|
||||
|
||||
impl SingleChunkDataSerializer for ChunkEntityData {
|
||||
#[inline]
|
||||
fn from_bytes(bytes: &Bytes, pos: Vector2<i32>) -> Result<Self, ChunkReadingError> {
|
||||
Self::internal_from_bytes(bytes, pos).map_err(ChunkReadingError::ParsingError)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn to_bytes(
|
||||
&self,
|
||||
) -> Pin<Box<dyn Future<Output = Result<Bytes, ChunkSerializingError>> + Send + '_>> {
|
||||
Box::pin(async move { self.internal_to_bytes().await })
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn position(&self) -> (i32, i32) {
|
||||
(self.x, self.z)
|
||||
}
|
||||
}
|
||||
|
||||
impl ChunkEntityData {
|
||||
fn internal_from_bytes(
|
||||
chunk_data: &[u8],
|
||||
position: Vector2<i32>,
|
||||
) -> Result<Self, ChunkParsingError> {
|
||||
let is_named = chunk_data.len() >= 3
|
||||
&& chunk_data[0] == 0x0a
|
||||
&& chunk_data[1] == 0x00
|
||||
&& chunk_data[2] == 0x00;
|
||||
let mut cursor = std::io::Cursor::new(chunk_data);
|
||||
let mut reader = pumpkin_nbt::deserializer::NbtReadHelperJava::new(
|
||||
pumpkin_nbt::deserializer::NbtStreamReader(&mut cursor),
|
||||
);
|
||||
let nbt = if is_named {
|
||||
pumpkin_nbt::Nbt::read(&mut reader)
|
||||
} else {
|
||||
pumpkin_nbt::Nbt::read_unnamed(&mut reader)
|
||||
}
|
||||
.map_err(|e| ChunkParsingError::ErrorDeserializingChunk(e.to_string()))?;
|
||||
|
||||
let pos_array = match (nbt.get_int("Position-X"), nbt.get_int("Position-Z")) {
|
||||
(Some(x), Some(z)) => [x, z],
|
||||
_ => {
|
||||
if let Some(pumpkin_nbt::tag::NbtTag::IntArray(pos)) = nbt.get("Position") {
|
||||
if pos.len() >= 2 {
|
||||
[pos[0], pos[1]]
|
||||
} else {
|
||||
[0, 0]
|
||||
}
|
||||
} else {
|
||||
[0, 0]
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if pos_array[0] != position.x || pos_array[1] != position.y {
|
||||
return Err(ChunkParsingError::ErrorDeserializingChunk(format!(
|
||||
"Expected data for entity chunk {},{} but got it for {},{}!",
|
||||
position.x, position.y, pos_array[0], pos_array[1],
|
||||
)));
|
||||
}
|
||||
|
||||
let entities = match nbt.get("Entities") {
|
||||
Some(pumpkin_nbt::tag::NbtTag::List(list)) => list
|
||||
.iter()
|
||||
.filter_map(|t| match t {
|
||||
pumpkin_nbt::tag::NbtTag::Compound(c) => Some(c.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
|
||||
Ok(Self {
|
||||
x: position.x,
|
||||
z: position.y,
|
||||
data: Mutex::new(entities),
|
||||
dirty: AtomicBool::new(false),
|
||||
})
|
||||
}
|
||||
|
||||
async fn internal_to_bytes(&self) -> Result<Bytes, ChunkSerializingError> {
|
||||
let mut root = NbtCompound::new();
|
||||
root.put_int("DataVersion", WORLD_DATA_VERSION);
|
||||
root.put(
|
||||
"Position",
|
||||
pumpkin_nbt::tag::NbtTag::IntArray(vec![self.x, self.z]),
|
||||
);
|
||||
let entities_tag: Vec<pumpkin_nbt::tag::NbtTag> = self
|
||||
.data
|
||||
.lock()
|
||||
.await
|
||||
.iter()
|
||||
.map(|c| pumpkin_nbt::tag::NbtTag::Compound(c.clone()))
|
||||
.collect();
|
||||
root.put_list("Entities", entities_tag);
|
||||
|
||||
let nbt = pumpkin_nbt::Nbt::from(root);
|
||||
Ok(nbt.write())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct ChunkSectionBiomes {
|
||||
pub(crate) data: Option<Box<[i64]>>,
|
||||
pub(crate) palette: Box<[u8]>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct ChunkSectionBlockStates {
|
||||
pub(crate) data: Option<Box<[i64]>>,
|
||||
pub(crate) palette: Box<[BlockStateId]>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum LightContainer {
|
||||
Empty(u8),
|
||||
Full(Box<[u8]>),
|
||||
}
|
||||
|
||||
impl LightContainer {
|
||||
pub const DIM: usize = 16;
|
||||
pub const ARRAY_SIZE: usize = Self::DIM * Self::DIM * Self::DIM / 2;
|
||||
|
||||
#[must_use]
|
||||
pub fn new_empty(default: u8) -> Self {
|
||||
assert!(default <= 15, "Default value must be between 0 and 15");
|
||||
Self::Empty(default)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn new(data: Box<[u8]>) -> Self {
|
||||
assert!(
|
||||
data.len() == Self::ARRAY_SIZE,
|
||||
"Data length must be {}",
|
||||
Self::ARRAY_SIZE
|
||||
);
|
||||
Self::Full(data)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn new_filled(default: u8) -> Self {
|
||||
assert!(default <= 15, "Default value must be between 0 and 15");
|
||||
let value = default << 4 | default;
|
||||
Self::Full([value; Self::ARRAY_SIZE].into())
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn is_empty(&self) -> bool {
|
||||
matches!(self, Self::Empty(_))
|
||||
}
|
||||
|
||||
const fn index(x: usize, y: usize, z: usize) -> usize {
|
||||
y * 16 * 16 + z * 16 + x
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn get(&self, x: usize, y: usize, z: usize) -> u8 {
|
||||
match self {
|
||||
Self::Full(data) => {
|
||||
let index = Self::index(x, y, z);
|
||||
data[index >> 1] >> (4 * (index & 1)) & 0x0F
|
||||
}
|
||||
Self::Empty(default) => *default,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set(&mut self, x: usize, y: usize, z: usize, value: u8) {
|
||||
match self {
|
||||
Self::Full(data) => {
|
||||
let index = Self::index(x, y, z);
|
||||
let mask = 0x0F << (4 * (index & 1));
|
||||
data[index >> 1] &= !mask;
|
||||
data[index >> 1] |= value << (4 * (index & 1));
|
||||
}
|
||||
Self::Empty(default) => {
|
||||
if value != *default {
|
||||
*self = Self::new_filled(*default);
|
||||
self.set(x, y, z, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn fill(&mut self, value: u8) {
|
||||
*self = Self::new_filled(value);
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for LightContainer {
|
||||
fn default() -> Self {
|
||||
Self::new_empty(15)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::marker::PhantomData;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use crate::chunk::format::anvil::SingleChunkDataSerializer;
|
||||
use crate::chunk::io::{ChunkSerializer, LoadedData};
|
||||
use crate::chunk::{ChunkReadingError, ChunkWritingError};
|
||||
use bytes::Bytes;
|
||||
use pumpkin_util::math::vector2::Vector2;
|
||||
use ruzstd::decoding::StreamingDecoder;
|
||||
use ruzstd::encoding::{CompressionLevel, compress_to_vec};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
pub struct PumpFile<D> {
|
||||
pub data: PumpData,
|
||||
_phantom: PhantomData<D>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Default)]
|
||||
pub struct PumpData {
|
||||
pub x: i32,
|
||||
pub z: i32,
|
||||
pub chunks: BTreeMap<String, Vec<u8>>,
|
||||
}
|
||||
|
||||
impl<D> Default for PumpFile<D> {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
data: PumpData::default(),
|
||||
_phantom: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<D> ChunkSerializer for PumpFile<D>
|
||||
where
|
||||
D: SingleChunkDataSerializer + Send + Sync + Sized,
|
||||
{
|
||||
type Data = D;
|
||||
type WriteBackend = PathBuf;
|
||||
type ChunkConfig = ();
|
||||
|
||||
fn get_chunk_key(chunk: &Vector2<i32>) -> String {
|
||||
let region_x = chunk.x >> 5;
|
||||
let region_z = chunk.y >> 5;
|
||||
format!("r.{region_x}.{region_z}.pump")
|
||||
}
|
||||
|
||||
fn should_write(&self, _is_watched: bool) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
async fn write(&self, backend: &Self::WriteBackend) -> Result<(), std::io::Error> {
|
||||
let mut root = pumpkin_nbt::compound::NbtCompound::new();
|
||||
root.put_int("x", self.data.x);
|
||||
root.put_int("z", self.data.z);
|
||||
let mut chunks_comp = pumpkin_nbt::compound::NbtCompound::new();
|
||||
for (k, v) in &self.data.chunks {
|
||||
let i8_vec: Vec<i8> = v.iter().map(|&b| b as i8).collect();
|
||||
chunks_comp.put(k, pumpkin_nbt::tag::NbtTag::ByteArray(i8_vec.into()));
|
||||
}
|
||||
root.put_compound("chunks", chunks_comp);
|
||||
|
||||
let bytes = pumpkin_nbt::Nbt::from(root).write_unnamed();
|
||||
tokio::fs::write(backend, bytes).await
|
||||
}
|
||||
|
||||
fn read(r: Bytes) -> Result<Self, ChunkReadingError> {
|
||||
let mut cursor = std::io::Cursor::new(r);
|
||||
let mut reader = pumpkin_nbt::deserializer::NbtReadHelperJava::new(
|
||||
pumpkin_nbt::deserializer::NbtStreamReader(&mut cursor),
|
||||
);
|
||||
let nbt = pumpkin_nbt::Nbt::read_unnamed(&mut reader).map_err(|e| {
|
||||
ChunkReadingError::ParsingError(
|
||||
crate::chunk::ChunkParsingError::ErrorDeserializingChunk(e.to_string()),
|
||||
)
|
||||
})?;
|
||||
|
||||
let x = nbt.get_int("x").unwrap_or(0);
|
||||
let z = nbt.get_int("z").unwrap_or(0);
|
||||
let mut chunks = BTreeMap::new();
|
||||
if let Some(chunks_tag) = nbt.get_compound("chunks") {
|
||||
for (k, v) in &chunks_tag.child_tags {
|
||||
if let pumpkin_nbt::tag::NbtTag::ByteArray(arr) = v {
|
||||
let u8_vec: Vec<u8> = arr.iter().map(|&b| b as u8).collect();
|
||||
chunks.insert(k.to_string(), u8_vec);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
data: PumpData { x, z, chunks },
|
||||
_phantom: PhantomData,
|
||||
})
|
||||
}
|
||||
|
||||
async fn update_chunk(
|
||||
&mut self,
|
||||
chunk_data: &Self::Data,
|
||||
_chunk_config: &Self::ChunkConfig,
|
||||
) -> Result<(), ChunkWritingError> {
|
||||
let (x, z) = chunk_data.position();
|
||||
self.data.x = x >> 5;
|
||||
self.data.z = z >> 5;
|
||||
let rel_x = x.rem_euclid(32);
|
||||
let rel_z = z.rem_euclid(32);
|
||||
let index = (rel_x + rel_z * 32) as usize;
|
||||
|
||||
let bytes = chunk_data
|
||||
.to_bytes()
|
||||
.await
|
||||
.map_err(|e| ChunkWritingError::ChunkSerializingError(e.to_string()))?;
|
||||
|
||||
let compressed = compress_to_vec(&bytes[..], CompressionLevel::Fastest);
|
||||
|
||||
self.data.chunks.insert(index.to_string(), compressed);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn get_chunks(
|
||||
&self,
|
||||
chunks: Vec<Vector2<i32>>,
|
||||
stream: tokio::sync::mpsc::Sender<LoadedData<Self::Data, ChunkReadingError>>,
|
||||
) {
|
||||
for pos in chunks {
|
||||
let rel_x = pos.x.rem_euclid(32);
|
||||
let rel_z = pos.y.rem_euclid(32);
|
||||
let index = (rel_x + rel_z * 32) as usize;
|
||||
|
||||
if let Some(chunk_bytes) = self.data.chunks.get(&index.to_string()) {
|
||||
let mut decoder = match StreamingDecoder::new(&chunk_bytes[..]) {
|
||||
Ok(d) => d,
|
||||
Err(e) => {
|
||||
let _ = stream
|
||||
.send(LoadedData::Error((
|
||||
pos,
|
||||
ChunkReadingError::IoError(std::io::Error::other(e.to_string())),
|
||||
)))
|
||||
.await;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let mut decompressed = Vec::new();
|
||||
if let Err(e) = std::io::Read::read_to_end(&mut decoder, &mut decompressed) {
|
||||
let _ = stream
|
||||
.send(LoadedData::Error((pos, ChunkReadingError::IoError(e))))
|
||||
.await;
|
||||
continue;
|
||||
}
|
||||
|
||||
let bytes = Bytes::from(decompressed);
|
||||
match D::from_bytes(&bytes, pos) {
|
||||
Ok(data) => {
|
||||
let _ = stream.send(LoadedData::Loaded(data)).await;
|
||||
}
|
||||
Err(e) => {
|
||||
let _ = stream.send(LoadedData::Error((pos, e))).await;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let _ = stream.send(LoadedData::Missing(pos)).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::chunk::ChunkReadingError;
|
||||
use crate::chunk::ChunkSerializingError;
|
||||
use crate::chunk::format::anvil::SingleChunkDataSerializer;
|
||||
use crate::chunk::io::Dirtiable;
|
||||
use crate::chunk::io::{ChunkSerializer, LoadedData};
|
||||
use bytes::Bytes;
|
||||
use pumpkin_util::math::vector2::Vector2;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
use tempfile::TempDir;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
struct MockChunk {
|
||||
x: i32,
|
||||
z: i32,
|
||||
data: Vec<u8>,
|
||||
}
|
||||
|
||||
impl Dirtiable for MockChunk {
|
||||
fn is_dirty(&self) -> bool {
|
||||
true
|
||||
}
|
||||
fn mark_dirty(&self, _: bool) {}
|
||||
}
|
||||
|
||||
impl SingleChunkDataSerializer for MockChunk {
|
||||
fn to_bytes(
|
||||
&self,
|
||||
) -> Pin<Box<dyn Future<Output = Result<Bytes, ChunkSerializingError>> + Send + '_>>
|
||||
{
|
||||
let mut root = pumpkin_nbt::compound::NbtCompound::new();
|
||||
root.put_int("x", self.x);
|
||||
root.put_int("z", self.z);
|
||||
let i8_vec: Vec<i8> = self.data.iter().map(|&b| b as i8).collect();
|
||||
root.put("data", pumpkin_nbt::tag::NbtTag::ByteArray(i8_vec.into()));
|
||||
let bytes = pumpkin_nbt::Nbt::from(root).write_unnamed();
|
||||
Box::pin(async move { Ok(bytes) })
|
||||
}
|
||||
fn from_bytes(bytes: &Bytes, pos: Vector2<i32>) -> Result<Self, ChunkReadingError> {
|
||||
let mut cursor = std::io::Cursor::new(bytes);
|
||||
let mut reader = pumpkin_nbt::deserializer::NbtReadHelperJava::new(
|
||||
pumpkin_nbt::deserializer::NbtStreamReader(&mut cursor),
|
||||
);
|
||||
let nbt = pumpkin_nbt::Nbt::read_unnamed(&mut reader).map_err(|e| {
|
||||
ChunkReadingError::ParsingError(
|
||||
crate::chunk::ChunkParsingError::ErrorDeserializingChunk(e.to_string()),
|
||||
)
|
||||
})?;
|
||||
let data = match nbt.get("data") {
|
||||
Some(pumpkin_nbt::tag::NbtTag::ByteArray(arr)) => {
|
||||
arr.iter().map(|&b| b as u8).collect()
|
||||
}
|
||||
_ => Vec::new(),
|
||||
};
|
||||
Ok(Self {
|
||||
x: pos.x,
|
||||
z: pos.y,
|
||||
data,
|
||||
})
|
||||
}
|
||||
fn position(&self) -> (i32, i32) {
|
||||
(self.x, self.z)
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn pump_file_roundtrip() {
|
||||
let temp_dir = TempDir::new().unwrap();
|
||||
let file_path = temp_dir.path().join("r.0.0.pump");
|
||||
|
||||
let mut pump_file: PumpFile<MockChunk> = PumpFile::default();
|
||||
let chunk = MockChunk {
|
||||
x: 0,
|
||||
z: 0,
|
||||
data: vec![1, 2, 3],
|
||||
};
|
||||
|
||||
pump_file.update_chunk(&chunk, &()).await.unwrap();
|
||||
pump_file.write(&file_path).await.unwrap();
|
||||
|
||||
let bytes = tokio::fs::read(&file_path).await.unwrap();
|
||||
let read_file = PumpFile::<MockChunk>::read(Bytes::from(bytes)).unwrap();
|
||||
|
||||
assert_eq!(read_file.data.chunks.len(), 1);
|
||||
let (stream_tx, mut stream_rx) = tokio::sync::mpsc::channel(1);
|
||||
read_file
|
||||
.get_chunks(vec![Vector2::new(0, 0)], stream_tx)
|
||||
.await;
|
||||
|
||||
let loaded = stream_rx.recv().await.unwrap();
|
||||
match loaded {
|
||||
LoadedData::Loaded(c) => {
|
||||
assert_eq!(c.data, vec![1, 2, 3]);
|
||||
}
|
||||
_ => panic!("Expected LoadedData::Loaded"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,430 @@
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
path::{Path, PathBuf},
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use futures::future::join_all;
|
||||
use pumpkin_util::math::vector2::Vector2;
|
||||
use tokio::{
|
||||
join,
|
||||
sync::{OnceCell, RwLock, mpsc},
|
||||
};
|
||||
use tracing::{debug, error, trace};
|
||||
|
||||
use crate::{
|
||||
chunk::{
|
||||
ChunkReadingError, ChunkWritingError,
|
||||
io::{BoxFuture, Dirtiable},
|
||||
},
|
||||
level::LevelFolder,
|
||||
};
|
||||
|
||||
use super::{ChunkSerializer, FileIO, LoadedData};
|
||||
|
||||
/// A simple implementation of the `ChunkSerializer` trait that loads and saves data
|
||||
/// to disk using parallelism and a lazy-loading cache keyed by file path.
|
||||
///
|
||||
/// ### Concurrency model
|
||||
///
|
||||
/// * `file_locks` — one `Arc<RwLock<S>>` per on-disk file, created lazily.
|
||||
/// All readers/writers for the same region file share this lock, so there
|
||||
/// are never two concurrent writers for the same file.
|
||||
/// * `watchers` — a ref-count per path. While a path has active watchers the
|
||||
/// serializer is **not** evicted from the cache and the file is **not**
|
||||
/// flushed to disk (the caller owns the flush lifecycle).
|
||||
///
|
||||
/// ### Lock ordering (must never be violated to avoid deadlocks)
|
||||
///
|
||||
/// 1. `file_locks` (outer)
|
||||
/// 2. individual `RwLock<S>` inside each loader (inner)
|
||||
/// 3. `watchers` (independent — never held at the same time as either above)
|
||||
///
|
||||
/// `watchers` is always acquired in its own critical section, after all
|
||||
/// serializer locks are released, which keeps it strictly independent.
|
||||
pub struct ChunkFileManager<S: ChunkSerializer<WriteBackend = PathBuf>> {
|
||||
file_locks: RwLock<BTreeMap<PathBuf, Arc<ChunkSerializerLazyLoader<S>>>>,
|
||||
watchers: RwLock<BTreeMap<PathBuf, usize>>,
|
||||
chunk_config: S::ChunkConfig,
|
||||
}
|
||||
|
||||
pub(crate) trait PathFromLevelFolder {
|
||||
fn file_path(folder: &LevelFolder, file_name: &str) -> PathBuf;
|
||||
}
|
||||
|
||||
struct ChunkSerializerLazyLoader<S: ChunkSerializer<WriteBackend = PathBuf>> {
|
||||
path: PathBuf,
|
||||
/// Initialised at most once; subsequent calls reuse the same Arc.
|
||||
internal: OnceCell<Arc<RwLock<S>>>,
|
||||
}
|
||||
|
||||
impl<S: ChunkSerializer<WriteBackend = PathBuf>> ChunkSerializerLazyLoader<S> {
|
||||
fn new(path: PathBuf) -> Self {
|
||||
Self {
|
||||
path,
|
||||
internal: OnceCell::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns `true` only when no outside caller still holds a clone of this
|
||||
/// loader *or* the inner serializer.
|
||||
///
|
||||
/// # Safety requirement
|
||||
/// **Must be called while the write-lock on the parent `file_locks` map is
|
||||
/// held.** That guarantees no new `Arc` clones can be issued while we
|
||||
/// inspect the strong counts.
|
||||
fn can_remove(loader: &Arc<Self>) -> bool {
|
||||
// The map itself holds 1 strong count; anything above that means an
|
||||
// active caller still has a handle.
|
||||
if Arc::strong_count(loader) > 1 {
|
||||
return false;
|
||||
}
|
||||
loader
|
||||
.internal
|
||||
.get()
|
||||
.is_none_or(|arc| Arc::strong_count(arc) == 1)
|
||||
}
|
||||
|
||||
/// Returns the serializer, initialising it from disk on the first call.
|
||||
async fn get(&self) -> Result<Arc<RwLock<S>>, ChunkReadingError> {
|
||||
self.internal
|
||||
.get_or_try_init(|| async {
|
||||
let serializer = self.read_from_disk().await?;
|
||||
Ok(Arc::new(RwLock::new(serializer)))
|
||||
})
|
||||
.await
|
||||
.cloned()
|
||||
}
|
||||
|
||||
async fn read_from_disk(&self) -> Result<S, ChunkReadingError> {
|
||||
trace!("Opening file from disk: {}", self.path.display());
|
||||
|
||||
match tokio::fs::read(&self.path).await {
|
||||
Ok(bytes) => {
|
||||
let value = S::read(bytes.into())?;
|
||||
trace!("Successfully read file from disk: {}", self.path.display());
|
||||
Ok(value)
|
||||
}
|
||||
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
|
||||
trace!("File not found, using default for: {}", self.path.display());
|
||||
Ok(S::default())
|
||||
}
|
||||
Err(err) => Err(ChunkReadingError::IoError(err)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: ChunkSerializer<WriteBackend = PathBuf>> ChunkFileManager<S> {
|
||||
pub fn new(chunk_config: S::ChunkConfig) -> Self {
|
||||
Self {
|
||||
file_locks: RwLock::new(BTreeMap::new()),
|
||||
watchers: RwLock::new(BTreeMap::new()),
|
||||
chunk_config,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: ChunkSerializer<WriteBackend = PathBuf>> ChunkFileManager<S> {
|
||||
/// Returns the serializer for `path`, inserting a lazy-loader if absent.
|
||||
///
|
||||
/// Uses an optimistic read-first pattern: in the common case (cache hit)
|
||||
/// we never need a write-lock on the map.
|
||||
async fn get_serializer(&self, path: &Path) -> Result<Arc<RwLock<S>>, ChunkReadingError> {
|
||||
{
|
||||
let locks = self.file_locks.read().await;
|
||||
if let Some(loader) = locks.get(path) {
|
||||
// Clone the Arc *before* releasing the lock so it stays alive.
|
||||
let loader = loader.clone();
|
||||
drop(locks);
|
||||
return loader.get().await;
|
||||
}
|
||||
}
|
||||
|
||||
let loader = {
|
||||
let mut locks = self.file_locks.write().await;
|
||||
locks
|
||||
.entry(path.into())
|
||||
.or_insert_with(|| Arc::new(ChunkSerializerLazyLoader::new(path.into())))
|
||||
.clone()
|
||||
// Write-lock dropped here — `loader.get()` may block on I/O and
|
||||
// must not hold the map lock.
|
||||
};
|
||||
|
||||
loader.get().await
|
||||
}
|
||||
|
||||
/// Attempt to evict the cached serializer for `path`.
|
||||
///
|
||||
/// The entry is only removed when *both* conditions hold:
|
||||
/// 1. No watcher still references the path.
|
||||
/// 2. No other `Arc` clone is live (ensured via `can_remove`).
|
||||
async fn maybe_evict(&self, path: &PathBuf) {
|
||||
// Check watchers independently of file_locks to honour lock ordering.
|
||||
let still_watched = {
|
||||
let watchers = self.watchers.read().await;
|
||||
watchers.get(path).is_some_and(|&c| c > 0)
|
||||
};
|
||||
|
||||
if still_watched {
|
||||
return;
|
||||
}
|
||||
|
||||
let mut locks = self.file_locks.write().await;
|
||||
let removable = locks
|
||||
.get(path)
|
||||
.is_some_and(ChunkSerializerLazyLoader::can_remove);
|
||||
|
||||
if removable {
|
||||
locks.remove(path);
|
||||
trace!("Evicted serializer cache for {}", path.display());
|
||||
} else {
|
||||
trace!(
|
||||
"Skipping eviction for {} — references still live",
|
||||
path.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<P, S> FileIO for ChunkFileManager<S>
|
||||
where
|
||||
P: PathFromLevelFolder + Send + Sync + Sized + Dirtiable + 'static,
|
||||
S: ChunkSerializer<Data = P, WriteBackend = PathBuf>,
|
||||
S::ChunkConfig: Send + Sync,
|
||||
{
|
||||
type Data = Arc<S::Data>;
|
||||
|
||||
fn watch_chunks<'a>(
|
||||
&'a self,
|
||||
folder: &'a LevelFolder,
|
||||
chunks: &'a [Vector2<i32>],
|
||||
) -> BoxFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
let paths: Vec<_> = chunks
|
||||
.iter()
|
||||
.map(|c| P::file_path(folder, &S::get_chunk_key(c)))
|
||||
.collect();
|
||||
|
||||
let mut watchers = self.watchers.write().await;
|
||||
for path in paths {
|
||||
*watchers.entry(path).or_insert(0) += 1;
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn unwatch_chunks<'a>(
|
||||
&'a self,
|
||||
folder: &'a LevelFolder,
|
||||
chunks: &'a [Vector2<i32>],
|
||||
) -> BoxFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
let paths: Vec<_> = chunks
|
||||
.iter()
|
||||
.map(|c| P::file_path(folder, &S::get_chunk_key(c)))
|
||||
.collect();
|
||||
|
||||
let mut watchers = self.watchers.write().await;
|
||||
for path in paths {
|
||||
if let std::collections::btree_map::Entry::Occupied(mut e) = watchers.entry(path) {
|
||||
let count = e.get_mut();
|
||||
*count = count.saturating_sub(1);
|
||||
if *count == 0 {
|
||||
e.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn clear_watched_chunks(&self) -> BoxFuture<'_, ()> {
|
||||
Box::pin(async move {
|
||||
self.watchers.write().await.clear();
|
||||
})
|
||||
}
|
||||
|
||||
fn fetch_chunks<'a>(
|
||||
&'a self,
|
||||
folder: &'a LevelFolder,
|
||||
chunk_coords: &'a [Vector2<i32>],
|
||||
stream: mpsc::Sender<LoadedData<Self::Data, ChunkReadingError>>,
|
||||
) -> BoxFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
// Group requested chunk coords by their region file.
|
||||
let mut regions_chunks: BTreeMap<String, Vec<Vector2<i32>>> = BTreeMap::new();
|
||||
for at in chunk_coords {
|
||||
regions_chunks
|
||||
.entry(S::get_chunk_key(at))
|
||||
.or_default()
|
||||
.push(*at);
|
||||
}
|
||||
|
||||
let region_tasks = regions_chunks.into_iter().map(|(file_name, chunks)| {
|
||||
let task_stream = stream.clone();
|
||||
async move {
|
||||
let path = P::file_path(folder, &file_name);
|
||||
|
||||
let chunk_serializer = match self.get_serializer(&path).await {
|
||||
Ok(s) => s,
|
||||
Err(ChunkReadingError::ChunkNotExist) => {
|
||||
return;
|
||||
}
|
||||
Err(err) => {
|
||||
// Best-effort: report the error for the first coord in the batch.
|
||||
let _ = task_stream.send(LoadedData::Error((chunks[0], err))).await;
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
// A bounded channel of 1 keeps backpressure between the
|
||||
// serializer and the caller without unbounded buffering.
|
||||
let (send, mut recv) =
|
||||
mpsc::channel::<LoadedData<S::Data, ChunkReadingError>>(1);
|
||||
|
||||
// Forward received chunks, wrapping them in `Arc`.
|
||||
// Captured move is intentional — `task_stream` is consumed here.
|
||||
let forward = async move {
|
||||
while let Some(data) = recv.recv().await {
|
||||
let wrapped = data.map_loaded(Arc::new);
|
||||
if task_stream.send(wrapped).await.is_err() {
|
||||
// Receiver dropped; abort early to avoid wasted work.
|
||||
return;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Hold the read lock only for the duration of `get_chunks`.
|
||||
let read = async move {
|
||||
let serializer = chunk_serializer.read().await;
|
||||
serializer.get_chunks(chunks, send).await;
|
||||
};
|
||||
|
||||
join!(forward, read);
|
||||
}
|
||||
});
|
||||
|
||||
join_all(region_tasks).await;
|
||||
})
|
||||
}
|
||||
|
||||
fn save_chunks<'a>(
|
||||
&'a self,
|
||||
folder: &'a LevelFolder,
|
||||
chunks_data: Vec<(Vector2<i32>, Self::Data)>,
|
||||
) -> BoxFuture<'a, Result<(), ChunkWritingError>> {
|
||||
Box::pin(async move {
|
||||
// Group chunks by region file.
|
||||
let mut regions_chunks: BTreeMap<String, Vec<Self::Data>> = BTreeMap::new();
|
||||
for (at, chunk) in chunks_data {
|
||||
regions_chunks
|
||||
.entry(S::get_chunk_key(&at))
|
||||
.or_default()
|
||||
.push(chunk);
|
||||
}
|
||||
|
||||
let tasks = regions_chunks
|
||||
.into_iter()
|
||||
.map(|(file_name, chunk_locks)| async move {
|
||||
let path = P::file_path(folder, &file_name);
|
||||
trace!("Saving chunks into {}", path.display());
|
||||
|
||||
let chunk_serializer = match self.get_serializer(&path).await {
|
||||
Ok(s) => s,
|
||||
Err(ChunkReadingError::ChunkNotExist) => {
|
||||
return Err(ChunkWritingError::IoError(std::io::Error::other(
|
||||
"get_serializer returned ChunkNotExist",
|
||||
)));
|
||||
}
|
||||
Err(ChunkReadingError::IoError(err)) => {
|
||||
error!("I/O error reading region before write: {err}");
|
||||
return Err(ChunkWritingError::IoError(err));
|
||||
}
|
||||
Err(err) => {
|
||||
return Err(ChunkWritingError::IoError(std::io::Error::other(
|
||||
err.to_string(),
|
||||
)));
|
||||
}
|
||||
};
|
||||
|
||||
{
|
||||
let mut writer = chunk_serializer.write().await;
|
||||
for chunk in &chunk_locks {
|
||||
// Atomically snapshot and clear the dirty flag before we
|
||||
// write so that any mutation that races in *during* this
|
||||
// serialisation round will mark dirty again correctly.
|
||||
let was_dirty = chunk.is_dirty();
|
||||
chunk.mark_dirty(false);
|
||||
|
||||
if was_dirty {
|
||||
writer.update_chunk(&**chunk, &self.chunk_config).await?;
|
||||
}
|
||||
}
|
||||
// Write-lock released here — flush can proceed under a read-lock.
|
||||
}
|
||||
|
||||
trace!("Chunk data updated for {}", path.display());
|
||||
|
||||
// We check watchers *after* releasing the write-lock to honour
|
||||
// lock ordering (serializer lock → watchers, never the reverse).
|
||||
let is_watched = {
|
||||
let watchers = self.watchers.read().await;
|
||||
watchers.get(&path).is_some_and(|&c| c > 0)
|
||||
};
|
||||
|
||||
if !is_watched {
|
||||
// A read-lock suffices for `write()` since we have already
|
||||
// applied all mutations above.
|
||||
{
|
||||
let serializer = chunk_serializer.read().await;
|
||||
debug!("Flushing {} to disk", path.display());
|
||||
serializer
|
||||
.write(&path)
|
||||
.await
|
||||
.map_err(ChunkWritingError::IoError)?;
|
||||
// Read-lock released here.
|
||||
};
|
||||
|
||||
// Drop our handle so `can_remove` may succeed.
|
||||
drop(chunk_serializer);
|
||||
|
||||
// Evict the cache entry when no longer needed.
|
||||
self.maybe_evict(&path).await;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
});
|
||||
|
||||
// Collect all region results; surface the first error encountered.
|
||||
let results: Vec<Result<(), ChunkWritingError>> = join_all(tasks).await;
|
||||
results.into_iter().find(Result::is_err).unwrap_or(Ok(()))
|
||||
})
|
||||
}
|
||||
|
||||
/// Blocks until all in-flight serialiser operations have completed by
|
||||
/// acquiring (and immediately releasing) a write-lock on every cached
|
||||
/// serialiser.
|
||||
///
|
||||
/// This is a linearisation point: after this future resolves no mutation
|
||||
/// started before the call is still running.
|
||||
fn block_and_await_ongoing_tasks(&self) -> BoxFuture<'_, ()> {
|
||||
Box::pin(async move {
|
||||
// Snapshot the current set of loaders under a read-lock so we do
|
||||
// not block new insertions longer than necessary.
|
||||
let loaders: Vec<Arc<ChunkSerializerLazyLoader<S>>> =
|
||||
{ self.file_locks.read().await.values().cloned().collect() };
|
||||
|
||||
// For each loader that has been initialised, acquire a write-lock
|
||||
// and release it immediately. This guarantees that any concurrent
|
||||
// read or write operation that was in progress has finished.
|
||||
let drain_tasks = loaders.into_iter().map(|loader| async move {
|
||||
if let Some(serializer_arc) = loader.internal.get() {
|
||||
// Acquiring + immediately dropping the write-lock acts as a
|
||||
// barrier: it can only succeed once all current lock holders
|
||||
// have released their guards.
|
||||
let _guard = serializer_arc.write().await;
|
||||
}
|
||||
});
|
||||
|
||||
join_all(drain_tasks).await;
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
use std::{error, pin::Pin};
|
||||
|
||||
use bytes::Bytes;
|
||||
use pumpkin_util::math::vector2::Vector2;
|
||||
|
||||
use super::{ChunkReadingError, ChunkWritingError};
|
||||
use crate::level::LevelFolder;
|
||||
|
||||
pub mod file_manager;
|
||||
|
||||
/// The result of loading a chunk data.
|
||||
///
|
||||
/// It can be the data loaded successfully, the data not found or an error
|
||||
/// with the chunk coordinates and the error that occurred.
|
||||
pub enum LoadedData<D: Send, Err: error::Error> {
|
||||
/// The chunk data was loaded successfully
|
||||
Loaded(D),
|
||||
|
||||
/// The chunk data was not found
|
||||
Missing(Vector2<i32>),
|
||||
|
||||
/// An error occurred while loading the chunk data
|
||||
Error((Vector2<i32>, Err)),
|
||||
}
|
||||
|
||||
impl<D: Send, E: error::Error> LoadedData<D, E> {
|
||||
pub fn map_loaded<D2: Send>(self, map: impl FnOnce(D) -> D2) -> LoadedData<D2, E> {
|
||||
match self {
|
||||
Self::Loaded(data) => LoadedData::Loaded(map(data)),
|
||||
Self::Missing(pos) => LoadedData::Missing(pos),
|
||||
Self::Error(err) => LoadedData::Error(err),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub trait Dirtiable {
|
||||
fn is_dirty(&self) -> bool;
|
||||
fn mark_dirty(&self, flag: bool);
|
||||
}
|
||||
|
||||
type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
|
||||
|
||||
/// Trait to handle the IO of chunks
|
||||
/// for loading and saving chunks data
|
||||
/// can be implemented for different types of IO
|
||||
/// or with different optimizations
|
||||
///
|
||||
/// The `R` type is the type of the data that will be loaded/saved
|
||||
/// like `ChunkData` or `EntityData`
|
||||
pub trait FileIO
|
||||
where
|
||||
Self: Send + Sync,
|
||||
{
|
||||
type Data: Send + Sync + Sized;
|
||||
|
||||
/// Load the chunks data
|
||||
fn fetch_chunks<'a>(
|
||||
&'a self,
|
||||
folder: &'a LevelFolder,
|
||||
chunk_coords: &'a [Vector2<i32>],
|
||||
stream: tokio::sync::mpsc::Sender<LoadedData<Self::Data, ChunkReadingError>>,
|
||||
) -> BoxFuture<'a, ()>; // Returns BoxFuture<()>
|
||||
|
||||
/// Persist the chunks data
|
||||
fn save_chunks<'a>(
|
||||
&'a self,
|
||||
folder: &'a LevelFolder,
|
||||
chunks_data: Vec<(Vector2<i32>, Self::Data)>,
|
||||
) -> BoxFuture<'a, Result<(), ChunkWritingError>>; // Returns BoxFuture<Result>
|
||||
|
||||
/// Tells the `ChunkIO` that these chunks are currently loaded in memory
|
||||
fn watch_chunks<'a>(
|
||||
&'a self,
|
||||
folder: &'a LevelFolder,
|
||||
chunks: &'a [Vector2<i32>],
|
||||
) -> BoxFuture<'a, ()>;
|
||||
|
||||
/// Tells the `ChunkIO` that these chunks are no longer loaded in memory
|
||||
fn unwatch_chunks<'a>(
|
||||
&'a self,
|
||||
folder: &'a LevelFolder,
|
||||
chunks: &'a [Vector2<i32>],
|
||||
) -> BoxFuture<'a, ()>;
|
||||
|
||||
/// Tells the `ChunkIO` that no more chunks are loaded in memory
|
||||
fn clear_watched_chunks(&self) -> BoxFuture<'_, ()>;
|
||||
|
||||
/// Ensure that all ongoing operations are finished
|
||||
fn block_and_await_ongoing_tasks(&self) -> BoxFuture<'_, ()>;
|
||||
}
|
||||
|
||||
/// Trait to serialize and deserialize the chunk data to and from bytes.
|
||||
///
|
||||
/// The `Data` type is the type of the data that will be updated or serialized/deserialized
|
||||
/// like `ChunkData` or `EntityData`
|
||||
pub trait ChunkSerializer: Send + Sync + Default {
|
||||
type Data: Send + Sync + Sized + Dirtiable;
|
||||
type WriteBackend;
|
||||
|
||||
type ChunkConfig;
|
||||
|
||||
/// Get the key for the chunk (like the file name)
|
||||
fn get_chunk_key(chunk: &Vector2<i32>) -> String;
|
||||
|
||||
fn should_write(&self, is_watched: bool) -> bool;
|
||||
|
||||
/// Serialize the data to bytes.
|
||||
fn write(
|
||||
&self,
|
||||
backend: &Self::WriteBackend,
|
||||
) -> impl Future<Output = Result<(), std::io::Error>> + Send;
|
||||
|
||||
/// Create a new instance from bytes
|
||||
fn read(r: Bytes) -> Result<Self, ChunkReadingError>;
|
||||
|
||||
/// Add the chunk data to the serializer
|
||||
fn update_chunk(
|
||||
&mut self,
|
||||
chunk_data: &Self::Data,
|
||||
chunk_config: &Self::ChunkConfig,
|
||||
) -> impl Future<Output = Result<(), ChunkWritingError>> + Send;
|
||||
|
||||
/// Get the chunks data from the serializer
|
||||
fn get_chunks(
|
||||
&self,
|
||||
chunks: Vec<Vector2<i32>>,
|
||||
stream: tokio::sync::mpsc::Sender<LoadedData<Self::Data, ChunkReadingError>>,
|
||||
) -> impl Future<Output = ()> + Send;
|
||||
}
|
||||
@@ -0,0 +1,878 @@
|
||||
use crate::chunk::format::LightContainer;
|
||||
use crate::tick::scheduler::ChunkTickScheduler;
|
||||
use palette::{BiomePalette, BlockPalette, has_random_ticking_fluid};
|
||||
use pumpkin_data::block_properties::{blocks_movement, has_random_ticks, is_air};
|
||||
use pumpkin_data::chunk::ChunkStatus;
|
||||
use pumpkin_data::fluid::Fluid;
|
||||
use pumpkin_data::tag::Block::MINECRAFT_LEAVES;
|
||||
use pumpkin_data::{Block, BlockState, BlockStateId};
|
||||
use pumpkin_nbt::compound::NbtCompound;
|
||||
use pumpkin_util::math::position::BlockPos;
|
||||
use rustc_hash::FxHashMap;
|
||||
|
||||
use std::sync::RwLock;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::AtomicU64;
|
||||
use thiserror::Error;
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
pub mod format;
|
||||
pub mod io;
|
||||
pub mod palette;
|
||||
|
||||
// TODO
|
||||
pub const CHUNK_WIDTH: usize = BlockPalette::SIZE;
|
||||
pub const CHUNK_AREA: usize = CHUNK_WIDTH * CHUNK_WIDTH;
|
||||
pub const BIOME_VOLUME: usize = BiomePalette::VOLUME;
|
||||
pub const SUBCHUNK_VOLUME: usize = CHUNK_AREA * CHUNK_WIDTH;
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
pub enum ChunkReadingError {
|
||||
#[error("Io error: {0}")]
|
||||
IoError(std::io::Error),
|
||||
#[error("Invalid header")]
|
||||
InvalidHeader,
|
||||
#[error("Region is invalid")]
|
||||
RegionIsInvalid,
|
||||
#[error("Compression error {0}")]
|
||||
Compression(CompressionError),
|
||||
#[error("Tried to read chunk which does not exist")]
|
||||
ChunkNotExist,
|
||||
#[error("Failed to parse chunk from bytes: {0}")]
|
||||
ParsingError(ChunkParsingError),
|
||||
}
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
pub enum ChunkWritingError {
|
||||
#[error("Io error: {0}")]
|
||||
IoError(std::io::Error),
|
||||
#[error("Compression error {0}")]
|
||||
Compression(CompressionError),
|
||||
#[error("Chunk serializing error: {0}")]
|
||||
ChunkSerializingError(String),
|
||||
}
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
pub enum CompressionError {
|
||||
#[error("Compression scheme not recognised")]
|
||||
UnknownCompression,
|
||||
#[error("Error while working with zlib compression: {0}")]
|
||||
ZlibError(std::io::Error),
|
||||
#[error("Error while working with Gzip compression: {0}")]
|
||||
GZipError(std::io::Error),
|
||||
#[error("Error while working with LZ4 compression: {0}")]
|
||||
LZ4Error(std::io::Error),
|
||||
#[error("Error while working with zstd compression: {0}")]
|
||||
ZstdError(std::io::Error),
|
||||
}
|
||||
|
||||
// Clone here cause we want to clone a snapshot of the chunk so we don't block writing for too long
|
||||
pub struct ChunkData {
|
||||
pub section: ChunkSections,
|
||||
/// See `https://minecraft.wiki/w/Heightmap` for more info
|
||||
pub heightmap: std::sync::Mutex<ChunkHeightmaps>,
|
||||
pub x: i32,
|
||||
pub z: i32,
|
||||
pub block_ticks: ChunkTickScheduler<&'static Block>,
|
||||
pub fluid_ticks: ChunkTickScheduler<&'static Fluid>,
|
||||
pub pending_block_entities: std::sync::Mutex<FxHashMap<BlockPos, NbtCompound>>,
|
||||
pub light_engine: std::sync::Mutex<ChunkLight>,
|
||||
pub light_populated: AtomicBool,
|
||||
pub status: ChunkStatus,
|
||||
pub blending_data: Option<crate::generation::blender::blending_data::BlendingData>,
|
||||
pub dirty: AtomicBool,
|
||||
pub inhabited_time: AtomicU64,
|
||||
}
|
||||
|
||||
pub struct ChunkEntityData {
|
||||
/// Chunk X
|
||||
pub x: i32,
|
||||
/// Chunk Z
|
||||
pub z: i32,
|
||||
pub data: Mutex<Vec<NbtCompound>>,
|
||||
|
||||
pub dirty: AtomicBool,
|
||||
}
|
||||
|
||||
/// Represents pure block data for a chunk.
|
||||
/// Subchunks are vertical portions of a chunk. They are 16 blocks tall.
|
||||
/// There are currently 24 subchunks per chunk.
|
||||
///
|
||||
/// A chunk can be:
|
||||
/// - Subchunks: 24 separate subchunks are stored.
|
||||
pub struct ChunkSections {
|
||||
pub count: usize,
|
||||
pub block_sections: RwLock<Box<[BlockPalette]>>,
|
||||
pub random_tick_sections: RwLock<Option<Box<[RandomTickSectionCache]>>>,
|
||||
pub randomly_ticking_mask: std::sync::atomic::AtomicU32,
|
||||
pub biome_sections: RwLock<Box<[BiomePalette]>>,
|
||||
pub min_y: i32,
|
||||
}
|
||||
|
||||
#[derive(Default, Clone, Copy)]
|
||||
pub struct RandomTickSectionCache {
|
||||
pub random_ticking_block_count: u16,
|
||||
pub random_ticking_fluid_count: u16,
|
||||
}
|
||||
|
||||
impl RandomTickSectionCache {
|
||||
#[must_use]
|
||||
pub const fn is_randomly_ticking(&self) -> bool {
|
||||
self.random_ticking_block_count > 0 || self.random_ticking_fluid_count > 0
|
||||
}
|
||||
}
|
||||
|
||||
impl ChunkSections {
|
||||
#[cfg(test)]
|
||||
#[must_use]
|
||||
pub fn dump_blocks(&self) -> Vec<BlockStateId> {
|
||||
self.block_sections
|
||||
.read()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.flat_map(|section| section.iter())
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[must_use]
|
||||
pub fn dump_biomes(&self) -> Vec<u8> {
|
||||
self.biome_sections
|
||||
.read()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.flat_map(|section| section.iter())
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Clone)]
|
||||
pub struct ChunkLight {
|
||||
pub sky_light: Box<[LightContainer]>,
|
||||
pub block_light: Box<[LightContainer]>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum ChunkHeightmapType {
|
||||
WorldSurface = 0,
|
||||
MotionBlocking = 1,
|
||||
MotionBlockingNoLeaves = 2,
|
||||
}
|
||||
impl TryFrom<usize> for ChunkHeightmapType {
|
||||
type Error = &'static str;
|
||||
|
||||
fn try_from(value: usize) -> Result<Self, Self::Error> {
|
||||
match value {
|
||||
0 => Ok(Self::WorldSurface),
|
||||
1 => Ok(Self::MotionBlocking),
|
||||
2 => Ok(Self::MotionBlockingNoLeaves),
|
||||
_ => Err("Invalid usize value for ChunkHeightmapType. The value should be 0~2."),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ChunkHeightmapType {
|
||||
#[must_use]
|
||||
pub fn is_opaque(&self, block_state: &BlockState) -> bool {
|
||||
let block = block_state.id.to_block_id();
|
||||
match self {
|
||||
Self::WorldSurface => !block_state.is_air(),
|
||||
Self::MotionBlocking => blocks_movement(block_state, block) || block_state.is_liquid(),
|
||||
Self::MotionBlockingNoLeaves => {
|
||||
(blocks_movement(block_state, block) || block_state.is_liquid())
|
||||
&& !block.has_tag(MINECRAFT_LEAVES)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ChunkHeightmaps {
|
||||
pub world_surface: Option<Box<[i64]>>,
|
||||
pub motion_blocking: Option<Box<[i64]>>,
|
||||
pub motion_blocking_no_leaves: Option<Box<[i64]>>,
|
||||
}
|
||||
|
||||
impl ChunkHeightmaps {
|
||||
pub fn set(&mut self, heightmap: ChunkHeightmapType, x: i32, z: i32, height: i32, min_y: i32) {
|
||||
let data = match heightmap {
|
||||
ChunkHeightmapType::WorldSurface => &mut self.world_surface,
|
||||
ChunkHeightmapType::MotionBlocking => &mut self.motion_blocking,
|
||||
ChunkHeightmapType::MotionBlockingNoLeaves => &mut self.motion_blocking_no_leaves,
|
||||
};
|
||||
|
||||
let data = data.get_or_insert_with(|| vec![0; 37].into_boxed_slice());
|
||||
|
||||
let local_x = (x & 15) as usize;
|
||||
let local_z = (z & 15) as usize;
|
||||
let column_idx = local_z * 16 + local_x;
|
||||
|
||||
// In Minecraft 1.16+, height is stored as (y - min_y + 1). 0 means below min_y.
|
||||
// It uses 9 bits per value, packed such that they do not cross u64 boundaries.
|
||||
// 64 / 9 = 7 values per u64.
|
||||
let val = (height - min_y + 1).max(0) as u64;
|
||||
|
||||
let array_idx = column_idx / 7;
|
||||
let shift = (column_idx % 7) * 9;
|
||||
|
||||
let mask = 0x1FFu64 << shift;
|
||||
|
||||
let mut current = data[array_idx] as u64;
|
||||
current = (current & !mask) | ((val & 0x1FF) << shift);
|
||||
data[array_idx] = current as i64;
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn get(&self, heightmap: ChunkHeightmapType, x: i32, z: i32, min_y: i32) -> i32 {
|
||||
let data = match heightmap {
|
||||
ChunkHeightmapType::WorldSurface => &self.world_surface,
|
||||
ChunkHeightmapType::MotionBlocking => &self.motion_blocking,
|
||||
ChunkHeightmapType::MotionBlockingNoLeaves => &self.motion_blocking_no_leaves,
|
||||
};
|
||||
|
||||
let Some(data) = data else {
|
||||
return min_y - 1;
|
||||
};
|
||||
|
||||
let local_x = (x & 15) as usize;
|
||||
let local_z = (z & 15) as usize;
|
||||
let column_idx = local_z * 16 + local_x;
|
||||
|
||||
let array_idx = column_idx / 7;
|
||||
let shift = (column_idx % 7) * 9;
|
||||
|
||||
let current = data[array_idx] as u64;
|
||||
let val = (current >> shift) & 0x1FF;
|
||||
|
||||
(val as i32) + min_y - 1
|
||||
}
|
||||
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
pub fn update<F>(
|
||||
&mut self,
|
||||
heightmap_type: ChunkHeightmapType,
|
||||
local_x: i32,
|
||||
local_y: i32,
|
||||
local_z: i32,
|
||||
block_state: &BlockState,
|
||||
min_y: i32,
|
||||
get_block: F,
|
||||
) -> bool
|
||||
where
|
||||
F: Fn(i32) -> &'static BlockState,
|
||||
{
|
||||
let first_available = self.get(heightmap_type, local_x, local_z, min_y) + 1;
|
||||
if local_y <= first_available - 2 {
|
||||
return false;
|
||||
}
|
||||
|
||||
if heightmap_type.is_opaque(block_state) {
|
||||
if local_y >= first_available {
|
||||
self.set(heightmap_type, local_x, local_z, local_y, min_y);
|
||||
return true;
|
||||
}
|
||||
} else if first_available - 1 == local_y {
|
||||
for y in (min_y..local_y).rev() {
|
||||
let state = get_block(y);
|
||||
if heightmap_type.is_opaque(state) {
|
||||
self.set(heightmap_type, local_x, local_z, y, min_y);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
self.set(heightmap_type, local_x, local_z, min_y - 1, min_y);
|
||||
return true;
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// The Heightmap for a completely empty chunk
|
||||
impl Default for ChunkHeightmaps {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
motion_blocking: None,
|
||||
motion_blocking_no_leaves: None,
|
||||
world_surface: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ChunkSections {
|
||||
#[must_use]
|
||||
pub fn build_random_tick_sections_cache(
|
||||
block_sections: &[BlockPalette],
|
||||
) -> (Option<Box<[RandomTickSectionCache]>>, u32) {
|
||||
let mut mask = 0;
|
||||
let mut has_ticks = false;
|
||||
let cache = block_sections
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, section)| {
|
||||
let (random_ticking_block_count, random_ticking_fluid_count) =
|
||||
section.random_ticking_counts();
|
||||
if random_ticking_block_count > 0 || random_ticking_fluid_count > 0 {
|
||||
mask |= 1 << i;
|
||||
has_ticks = true;
|
||||
}
|
||||
RandomTickSectionCache {
|
||||
random_ticking_block_count,
|
||||
random_ticking_fluid_count,
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.into_boxed_slice();
|
||||
|
||||
if has_ticks {
|
||||
(Some(cache), mask)
|
||||
} else {
|
||||
(None, 0)
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn new(num_sections: usize, min_y: i32) -> Self {
|
||||
let block_sections = vec![BlockPalette::default(); num_sections].into_boxed_slice();
|
||||
let (random_tick_sections, randomly_ticking_mask) =
|
||||
Self::build_random_tick_sections_cache(&block_sections);
|
||||
let biome_sections = vec![BiomePalette::default(); num_sections].into_boxed_slice();
|
||||
|
||||
Self {
|
||||
count: num_sections,
|
||||
block_sections: RwLock::new(block_sections),
|
||||
random_tick_sections: RwLock::new(random_tick_sections),
|
||||
randomly_ticking_mask: std::sync::atomic::AtomicU32::new(randomly_ticking_mask),
|
||||
biome_sections: RwLock::new(biome_sections),
|
||||
min_y,
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub(crate) fn from_palettes(
|
||||
block_sections: Box<[BlockPalette]>,
|
||||
biome_sections: Box<[BiomePalette]>,
|
||||
min_y: i32,
|
||||
) -> Self {
|
||||
assert_eq!(
|
||||
block_sections.len(),
|
||||
biome_sections.len(),
|
||||
"block and biome section counts must match"
|
||||
);
|
||||
let count = block_sections.len();
|
||||
let (random_tick_sections, randomly_ticking_mask) =
|
||||
Self::build_random_tick_sections_cache(&block_sections);
|
||||
|
||||
Self {
|
||||
count,
|
||||
block_sections: RwLock::new(block_sections),
|
||||
random_tick_sections: RwLock::new(random_tick_sections),
|
||||
randomly_ticking_mask: std::sync::atomic::AtomicU32::new(randomly_ticking_mask),
|
||||
biome_sections: RwLock::new(biome_sections),
|
||||
min_y,
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn get_block_absolute_y(
|
||||
&self,
|
||||
relative_x: usize,
|
||||
y: i32,
|
||||
relative_z: usize,
|
||||
) -> Option<BlockStateId> {
|
||||
let y = y - self.min_y;
|
||||
if y < 0 {
|
||||
None
|
||||
} else {
|
||||
let relative_y = y as usize;
|
||||
self.get_relative_block(relative_x, relative_y, relative_z)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_block_absolute_y(
|
||||
&self,
|
||||
relative_x: usize,
|
||||
y: i32,
|
||||
relative_z: usize,
|
||||
block_state_id: BlockStateId,
|
||||
) -> BlockStateId {
|
||||
let y = y - self.min_y;
|
||||
if y < 0 {
|
||||
return Block::AIR.default_state.id;
|
||||
}
|
||||
let relative_y = y as usize;
|
||||
self.set_block_no_heightmap_update(relative_x, relative_y, relative_z, block_state_id)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn get_rough_biome_absolute_y(
|
||||
&self,
|
||||
relative_x: usize,
|
||||
y: i32,
|
||||
relative_z: usize,
|
||||
) -> Option<u8> {
|
||||
let y = y - self.min_y;
|
||||
if y < 0 {
|
||||
None
|
||||
} else {
|
||||
let relative_y = y as usize;
|
||||
self.get_noise_biome(
|
||||
relative_y / BlockPalette::SIZE,
|
||||
relative_x >> 2 & 3,
|
||||
relative_y >> 2 & 3,
|
||||
relative_z >> 2 & 3,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Gets the given block in the chunk
|
||||
fn get_relative_block(
|
||||
&self,
|
||||
relative_x: usize,
|
||||
relative_y: usize,
|
||||
relative_z: usize,
|
||||
) -> Option<BlockStateId> {
|
||||
debug_assert!(relative_x < BlockPalette::SIZE);
|
||||
debug_assert!(relative_z < BlockPalette::SIZE);
|
||||
|
||||
let section_index = relative_y / BlockPalette::SIZE;
|
||||
let relative_y = relative_y % BlockPalette::SIZE;
|
||||
self.block_sections
|
||||
.read()
|
||||
.unwrap()
|
||||
.get(section_index)
|
||||
.map(|section| section.get(relative_x, relative_y, relative_z))
|
||||
}
|
||||
|
||||
/// Sets the given block in the chunk, returning the old block state ID
|
||||
#[inline]
|
||||
pub fn set_relative_block(
|
||||
&self,
|
||||
relative_x: usize,
|
||||
relative_y: usize,
|
||||
relative_z: usize,
|
||||
block_state_id: BlockStateId,
|
||||
) -> BlockStateId {
|
||||
self.set_block_no_heightmap_update(relative_x, relative_y, relative_z, block_state_id)
|
||||
}
|
||||
|
||||
/// Sets the given block in the chunk, returning the old block
|
||||
/// Contrary to `set_block` this does not update the heightmap.
|
||||
///
|
||||
/// Only use this if you know you don't need to update the heightmap
|
||||
/// or if you manually set the heightmap in `empty_with_heightmap`
|
||||
pub fn set_block_no_heightmap_update(
|
||||
&self,
|
||||
relative_x: usize,
|
||||
relative_y: usize,
|
||||
relative_z: usize,
|
||||
block_state_id: BlockStateId,
|
||||
) -> BlockStateId {
|
||||
debug_assert!(relative_x < BlockPalette::SIZE);
|
||||
debug_assert!(relative_z < BlockPalette::SIZE);
|
||||
|
||||
let section_index = relative_y / BlockPalette::SIZE;
|
||||
let relative_y = relative_y % BlockPalette::SIZE;
|
||||
|
||||
// Keep lock order consistent to avoid deadlocks: block sections first, then random-tick cache.
|
||||
let mut sections = self.block_sections.write().unwrap();
|
||||
let mut random_tick_sections_guard = self.random_tick_sections.write().unwrap();
|
||||
|
||||
if let Some(section) = sections.get_mut(section_index) {
|
||||
let replaced_block_state_id =
|
||||
section.set(relative_x, relative_y, relative_z, block_state_id);
|
||||
if replaced_block_state_id == block_state_id {
|
||||
return replaced_block_state_id;
|
||||
}
|
||||
|
||||
if (has_random_ticks(block_state_id) || has_random_ticking_fluid(block_state_id))
|
||||
&& random_tick_sections_guard.is_none()
|
||||
{
|
||||
let new_cache =
|
||||
vec![RandomTickSectionCache::default(); self.count].into_boxed_slice();
|
||||
*random_tick_sections_guard = Some(new_cache);
|
||||
}
|
||||
|
||||
if let Some(random_tick_sections) = random_tick_sections_guard.as_mut() {
|
||||
let random_tick_cache = &mut random_tick_sections[section_index];
|
||||
if has_random_ticks(replaced_block_state_id) {
|
||||
random_tick_cache.random_ticking_block_count = random_tick_cache
|
||||
.random_ticking_block_count
|
||||
.saturating_sub(1);
|
||||
}
|
||||
if has_random_ticking_fluid(replaced_block_state_id) {
|
||||
random_tick_cache.random_ticking_fluid_count = random_tick_cache
|
||||
.random_ticking_fluid_count
|
||||
.saturating_sub(1);
|
||||
}
|
||||
|
||||
if has_random_ticks(block_state_id) {
|
||||
random_tick_cache.random_ticking_block_count = random_tick_cache
|
||||
.random_ticking_block_count
|
||||
.saturating_add(1);
|
||||
}
|
||||
if has_random_ticking_fluid(block_state_id) {
|
||||
random_tick_cache.random_ticking_fluid_count = random_tick_cache
|
||||
.random_ticking_fluid_count
|
||||
.saturating_add(1);
|
||||
}
|
||||
|
||||
// Update the bitmask
|
||||
let mut mask = self
|
||||
.randomly_ticking_mask
|
||||
.load(std::sync::atomic::Ordering::Relaxed);
|
||||
if random_tick_cache.is_randomly_ticking() {
|
||||
mask |= 1 << section_index;
|
||||
} else {
|
||||
mask &= !(1 << section_index);
|
||||
}
|
||||
self.randomly_ticking_mask
|
||||
.store(mask, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
|
||||
return replaced_block_state_id;
|
||||
}
|
||||
BlockStateId::AIR
|
||||
}
|
||||
|
||||
pub fn set_relative_biome(
|
||||
&self,
|
||||
relative_x: usize,
|
||||
relative_y: usize,
|
||||
relative_z: usize,
|
||||
biome_id: u8,
|
||||
) {
|
||||
debug_assert!(relative_x < BiomePalette::SIZE);
|
||||
debug_assert!(relative_z < BiomePalette::SIZE);
|
||||
|
||||
let section_index = relative_y / BiomePalette::SIZE;
|
||||
let relative_y = relative_y % BiomePalette::SIZE;
|
||||
if let Some(section) = self.biome_sections.write().unwrap().get_mut(section_index) {
|
||||
section.set(relative_x, relative_y, relative_z, biome_id);
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn get_noise_biome(
|
||||
&self,
|
||||
index: usize,
|
||||
scale_x: usize,
|
||||
scale_y: usize,
|
||||
scale_z: usize,
|
||||
) -> Option<u8> {
|
||||
debug_assert!(scale_x < BiomePalette::SIZE);
|
||||
debug_assert!(scale_z < BiomePalette::SIZE);
|
||||
self.biome_sections
|
||||
.read()
|
||||
.unwrap()
|
||||
.get(index)
|
||||
.map(|section| section.get(scale_x, scale_y, scale_z))
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn get_top_y(&self, relative_x: usize, relative_z: usize, first_y: i32) -> Option<i32> {
|
||||
debug_assert!(relative_x < BlockPalette::SIZE);
|
||||
debug_assert!(relative_z < BlockPalette::SIZE);
|
||||
|
||||
let mut y = first_y;
|
||||
while y >= self.min_y {
|
||||
if let Some(block_state_id) = self.get_block_absolute_y(relative_x, y, relative_z)
|
||||
&& !is_air(block_state_id)
|
||||
{
|
||||
return Some(y);
|
||||
}
|
||||
y -= 1;
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
impl ChunkData {
|
||||
/// Returns the replaced block state ID
|
||||
pub fn set_block_absolute_y(
|
||||
&self,
|
||||
relative_x: usize,
|
||||
y: i32,
|
||||
relative_z: usize,
|
||||
block_state_id: BlockStateId,
|
||||
) -> BlockStateId {
|
||||
let min_y = self.section.min_y;
|
||||
let y_rel = y - min_y;
|
||||
if y_rel < 0 {
|
||||
return Block::AIR.default_state.id;
|
||||
}
|
||||
let relative_y = y_rel as usize;
|
||||
|
||||
let old = self.section.set_block_no_heightmap_update(
|
||||
relative_x,
|
||||
relative_y,
|
||||
relative_z,
|
||||
block_state_id,
|
||||
);
|
||||
if old != block_state_id {
|
||||
let state = BlockState::from_id(block_state_id);
|
||||
self.update_heightmap(relative_x, relative_y, relative_z, state);
|
||||
}
|
||||
old
|
||||
}
|
||||
|
||||
fn update_heightmap(
|
||||
&self,
|
||||
relative_x: usize,
|
||||
relative_y: usize,
|
||||
relative_z: usize,
|
||||
block_state: &BlockState,
|
||||
) {
|
||||
let mut heightmap = self.heightmap.lock().unwrap();
|
||||
let min_y = self.section.min_y;
|
||||
let x = relative_x as i32;
|
||||
let y = relative_y as i32 + min_y;
|
||||
let z = relative_z as i32;
|
||||
|
||||
for &hm_type in &[
|
||||
ChunkHeightmapType::WorldSurface,
|
||||
ChunkHeightmapType::MotionBlocking,
|
||||
ChunkHeightmapType::MotionBlockingNoLeaves,
|
||||
] {
|
||||
heightmap.update(hm_type, x, z, y, block_state, min_y, |y_at| {
|
||||
let id = self
|
||||
.section
|
||||
.get_block_absolute_y(relative_x, y_at, relative_z)
|
||||
.unwrap_or(BlockStateId::AIR);
|
||||
BlockState::from_id(id)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Gets the given block in the chunk
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn get_relative_block(
|
||||
&self,
|
||||
relative_x: usize,
|
||||
relative_y: usize,
|
||||
relative_z: usize,
|
||||
) -> Option<BlockStateId> {
|
||||
self.section
|
||||
.get_relative_block(relative_x, relative_y, relative_z)
|
||||
}
|
||||
|
||||
/// Sets the given block in the chunk
|
||||
#[inline]
|
||||
pub fn set_relative_block(
|
||||
&mut self,
|
||||
relative_x: usize,
|
||||
relative_y: usize,
|
||||
relative_z: usize,
|
||||
block_state_id: BlockStateId,
|
||||
) {
|
||||
let state = BlockState::from_id(block_state_id);
|
||||
self.update_heightmap(relative_x, relative_y, relative_z, state);
|
||||
self.section
|
||||
.set_relative_block(relative_x, relative_y, relative_z, block_state_id);
|
||||
}
|
||||
|
||||
/// Sets the given block in the chunk, returning the old block
|
||||
/// Contrary to `set_block` this does not update the heightmap.
|
||||
///
|
||||
/// Only use this if you know you don't need to update the heightmap
|
||||
/// or if you manually set the heightmap in `empty_with_heightmap`
|
||||
#[inline]
|
||||
pub fn set_block_no_heightmap_update(
|
||||
&mut self,
|
||||
relative_x: usize,
|
||||
relative_y: usize,
|
||||
relative_z: usize,
|
||||
block_state_id: BlockStateId,
|
||||
) {
|
||||
self.section
|
||||
.set_relative_block(relative_x, relative_y, relative_z, block_state_id);
|
||||
}
|
||||
|
||||
//TODO: Tracking heightmaps update.
|
||||
pub fn calculate_heightmap(&self) -> ChunkHeightmaps {
|
||||
let highest_non_empty_subchunk = self.get_highest_non_empty_subchunk();
|
||||
let mut heightmaps = ChunkHeightmaps::default();
|
||||
|
||||
for x in 0..16 {
|
||||
for z in 0..16 {
|
||||
self.populate_heightmaps(&mut heightmaps, highest_non_empty_subchunk, x, z);
|
||||
}
|
||||
}
|
||||
|
||||
// log::info!("WorldSurface:");
|
||||
// heightmaps.log_heightmap(ChunkHeightmapType::WorldSurface, self.section.min_y);
|
||||
// log::info!("MotionBlocking:");
|
||||
// heightmaps.log_heightmap(ChunkHeightmapType::MotionBlocking, self.section.min_y);
|
||||
// log::info!("min_y: {}", self.section.min_y);
|
||||
heightmaps
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn populate_heightmaps(
|
||||
&self,
|
||||
heightmaps: &mut ChunkHeightmaps,
|
||||
start_sub_chunk: usize,
|
||||
x: usize,
|
||||
z: usize,
|
||||
) {
|
||||
let start_height = (start_sub_chunk as i32) * 16 - self.section.min_y.abs() + 15;
|
||||
let mut has_found = [false, false, false];
|
||||
|
||||
for y in (self.section.min_y..=start_height).rev() {
|
||||
let state_id = self.section.get_block_absolute_y(x, y, z).unwrap();
|
||||
let block_state = BlockState::from_id(state_id);
|
||||
|
||||
for hm_type in [
|
||||
ChunkHeightmapType::WorldSurface,
|
||||
ChunkHeightmapType::MotionBlocking,
|
||||
ChunkHeightmapType::MotionBlockingNoLeaves,
|
||||
] {
|
||||
let idx = hm_type as usize;
|
||||
if !has_found[idx] && hm_type.is_opaque(block_state) {
|
||||
heightmaps.set(hm_type, x as i32, z as i32, y, self.section.min_y);
|
||||
has_found[idx] = true;
|
||||
}
|
||||
}
|
||||
|
||||
if has_found.iter().all(|&found| found) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
for (idx, is_set) in has_found.iter().enumerate() {
|
||||
if !(*is_set) {
|
||||
heightmaps.set(
|
||||
idx.try_into().unwrap(),
|
||||
x as i32,
|
||||
z as i32,
|
||||
self.section.min_y - 1,
|
||||
self.section.min_y,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn get_highest_non_empty_subchunk(&self) -> usize {
|
||||
self.section
|
||||
.block_sections
|
||||
.read()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.rev()
|
||||
.find(|(_, sub)| !sub.has_only_air())
|
||||
.map_or(0, |(idx, _)| idx)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
pub enum ChunkParsingError {
|
||||
#[error("Failed reading chunk status {0}")]
|
||||
FailedReadStatus(pumpkin_nbt::Error),
|
||||
#[error("The chunk isn't generated yet")]
|
||||
ChunkNotGenerated,
|
||||
#[error("Error deserializing chunk: {0}")]
|
||||
ErrorDeserializingChunk(String),
|
||||
}
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
pub enum ChunkSerializingError {
|
||||
#[error("Error serializing chunk: {0}")]
|
||||
ErrorSerializingChunk(pumpkin_nbt::Error),
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::ChunkSections;
|
||||
use crate::chunk::palette::BlockPalette;
|
||||
use pumpkin_data::{Block, block_properties::has_random_ticks};
|
||||
|
||||
#[test]
|
||||
fn random_tick_cache_initializes_from_palette_contents() {
|
||||
let mut sections = vec![BlockPalette::default(), BlockPalette::default()];
|
||||
sections[1].set(0, 0, 0, Block::LAVA.default_state.id);
|
||||
|
||||
let (cache, _mask) = ChunkSections::build_random_tick_sections_cache(§ions);
|
||||
let cache = cache.unwrap();
|
||||
assert!(!cache[0].is_randomly_ticking());
|
||||
assert!(cache[1].random_ticking_fluid_count > 0);
|
||||
assert!(cache[1].is_randomly_ticking());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_tick_cache_updates_on_block_mutation() {
|
||||
let min_y = -64;
|
||||
let sections = ChunkSections::new(1, min_y);
|
||||
|
||||
assert!(
|
||||
sections
|
||||
.random_tick_sections
|
||||
.read()
|
||||
.unwrap()
|
||||
.as_ref()
|
||||
.is_none_or(|c| !c[0].is_randomly_ticking()),
|
||||
"fresh sections should not be randomly ticking"
|
||||
);
|
||||
|
||||
let random_block_state = Block::WHEAT.default_state.id;
|
||||
assert!(
|
||||
has_random_ticks(random_block_state),
|
||||
"test requires a known randomly ticking block state"
|
||||
);
|
||||
|
||||
sections.set_block_absolute_y(0, min_y, 0, random_block_state);
|
||||
{
|
||||
let cache = sections.random_tick_sections.read().unwrap();
|
||||
let cache = cache.as_ref().unwrap();
|
||||
assert_eq!(cache[0].random_ticking_block_count, 1);
|
||||
assert_eq!(cache[0].random_ticking_fluid_count, 0);
|
||||
assert!(cache[0].is_randomly_ticking());
|
||||
};
|
||||
|
||||
sections.set_block_absolute_y(0, min_y, 0, Block::STONE.default_state.id);
|
||||
{
|
||||
let cache = sections.random_tick_sections.read().unwrap();
|
||||
let cache = cache.as_ref().unwrap();
|
||||
assert_eq!(cache[0].random_ticking_block_count, 0);
|
||||
assert_eq!(cache[0].random_ticking_fluid_count, 0);
|
||||
assert!(!cache[0].is_randomly_ticking());
|
||||
};
|
||||
|
||||
sections.set_block_absolute_y(0, min_y, 0, Block::LAVA.default_state.id);
|
||||
{
|
||||
let cache = sections.random_tick_sections.read().unwrap();
|
||||
let cache = cache.as_ref().unwrap();
|
||||
assert!(cache[0].random_ticking_fluid_count > 0);
|
||||
assert!(cache[0].is_randomly_ticking());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn heightmap_is_opaque() {
|
||||
use crate::chunk::ChunkHeightmapType;
|
||||
|
||||
let air = Block::AIR.default_state;
|
||||
let stone = Block::STONE.default_state;
|
||||
let leaves = Block::OAK_LEAVES.default_state;
|
||||
let water = Block::WATER.default_state;
|
||||
|
||||
// WORLD_SURFACE: Everything except air
|
||||
assert!(!ChunkHeightmapType::WorldSurface.is_opaque(air));
|
||||
assert!(ChunkHeightmapType::WorldSurface.is_opaque(stone));
|
||||
assert!(ChunkHeightmapType::WorldSurface.is_opaque(leaves));
|
||||
assert!(ChunkHeightmapType::WorldSurface.is_opaque(water));
|
||||
|
||||
// MOTION_BLOCKING: Blocks movement OR is liquid
|
||||
assert!(!ChunkHeightmapType::MotionBlocking.is_opaque(air));
|
||||
assert!(ChunkHeightmapType::MotionBlocking.is_opaque(stone));
|
||||
assert!(ChunkHeightmapType::MotionBlocking.is_opaque(leaves)); // Leaves block movement
|
||||
assert!(ChunkHeightmapType::MotionBlocking.is_opaque(water)); // Water is liquid
|
||||
|
||||
// MOTION_BLOCKING_NO_LEAVES: Blocks movement OR is liquid, but NOT leaves
|
||||
assert!(!ChunkHeightmapType::MotionBlockingNoLeaves.is_opaque(air));
|
||||
assert!(ChunkHeightmapType::MotionBlockingNoLeaves.is_opaque(stone));
|
||||
assert!(!ChunkHeightmapType::MotionBlockingNoLeaves.is_opaque(leaves)); // Excludes leaves
|
||||
assert!(ChunkHeightmapType::MotionBlockingNoLeaves.is_opaque(water)); // Water is liquid
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,985 @@
|
||||
use std::{collections::HashMap, hash::Hash};
|
||||
|
||||
use pumpkin_data::{
|
||||
BlockState, BlockStateId,
|
||||
block_properties::{has_random_ticks, is_air, is_liquid},
|
||||
fluid::Fluid,
|
||||
};
|
||||
use pumpkin_util::encompassing_bits;
|
||||
use tracing::warn;
|
||||
|
||||
use super::format::{ChunkSectionBiomes, ChunkSectionBlockStates};
|
||||
|
||||
/// 3d array indexed by y,z,x
|
||||
type AbstractCube<T, const DIM: usize> = [[[T; DIM]; DIM]; DIM];
|
||||
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn has_random_ticking_fluid(id: BlockStateId) -> bool {
|
||||
Fluid::from_state_id(id).is_some_and(|fluid| Fluid::same_fluid_type(fluid.id, Fluid::LAVA.id))
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct HeterogeneousPaletteData<V: Hash + Eq + Copy, const DIM: usize> {
|
||||
storage: PaletteStorage<V, DIM>,
|
||||
palette: Vec<V>,
|
||||
counts: Vec<u16>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
enum PaletteStorage<V, const DIM: usize> {
|
||||
Dense(Box<AbstractCube<V, DIM>>),
|
||||
Indexed(Box<AbstractCube<u8, DIM>>),
|
||||
}
|
||||
|
||||
impl<V: Hash + Eq + Copy + Default, const DIM: usize> HeterogeneousPaletteData<V, DIM> {
|
||||
fn get(&self, x: usize, y: usize, z: usize) -> V {
|
||||
debug_assert!(x < DIM);
|
||||
debug_assert!(y < DIM);
|
||||
debug_assert!(z < DIM);
|
||||
|
||||
match &self.storage {
|
||||
PaletteStorage::Dense(cube) => cube[y][z][x],
|
||||
PaletteStorage::Indexed(indices) => self.palette[indices[y][z][x] as usize],
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the Original
|
||||
fn set(&mut self, x: usize, y: usize, z: usize, value: V) -> V {
|
||||
debug_assert!(x < DIM);
|
||||
debug_assert!(y < DIM);
|
||||
debug_assert!(z < DIM);
|
||||
|
||||
let original = self.get(x, y, z);
|
||||
if original == value {
|
||||
return original;
|
||||
}
|
||||
|
||||
let original_index = self.palette.iter().position(|v| v == &original).unwrap();
|
||||
|
||||
// Find or add the new value to the palette.
|
||||
let new_index = if let Some(new_index) = self.palette.iter().position(|v| v == &value) {
|
||||
self.counts[new_index] += 1;
|
||||
new_index
|
||||
} else {
|
||||
self.palette.push(value);
|
||||
self.counts.push(1);
|
||||
self.palette.len() - 1
|
||||
};
|
||||
|
||||
// Handle storage upgrades or updates
|
||||
let mut upgraded = false;
|
||||
match &mut self.storage {
|
||||
PaletteStorage::Dense(cube) => {
|
||||
cube[y][z][x] = value;
|
||||
}
|
||||
PaletteStorage::Indexed(indices) => {
|
||||
if new_index <= 255 {
|
||||
indices[y][z][x] = new_index as u8;
|
||||
} else {
|
||||
// Upgrade to Dense
|
||||
let mut cube = Box::new([[[V::default(); DIM]; DIM]; DIM]);
|
||||
for (i, v) in cube
|
||||
.as_flattened_mut()
|
||||
.as_flattened_mut()
|
||||
.iter_mut()
|
||||
.enumerate()
|
||||
{
|
||||
let y = i / (DIM * DIM);
|
||||
let z = (i / DIM) % DIM;
|
||||
let x = i % DIM;
|
||||
*v = self.palette[indices[y][z][x] as usize];
|
||||
}
|
||||
cube[y][z][x] = value;
|
||||
self.storage = PaletteStorage::Dense(cube);
|
||||
upgraded = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
self.counts[original_index] -= 1;
|
||||
|
||||
if self.counts[original_index] == 0 {
|
||||
let last_index = self.palette.len() - 1;
|
||||
// Remove from palette and counts Vecs if the count hits zero.
|
||||
self.palette.swap_remove(original_index);
|
||||
self.counts.swap_remove(original_index);
|
||||
|
||||
if self.palette.capacity() > 16 && self.palette.len() < self.palette.capacity() / 2 {
|
||||
self.palette.shrink_to_fit();
|
||||
self.counts.shrink_to_fit();
|
||||
}
|
||||
|
||||
// If we are indexed, we need to update all indices because swap_remove changed indices
|
||||
if !upgraded && let PaletteStorage::Indexed(indices) = &mut self.storage {
|
||||
for row in indices.iter_mut() {
|
||||
for col in row.iter_mut() {
|
||||
for idx in col.iter_mut() {
|
||||
if *idx as usize == last_index {
|
||||
*idx = original_index as u8;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
original
|
||||
}
|
||||
}
|
||||
|
||||
/// A paletted container is a cube of registry ids. It uses a custom compression scheme based on how
|
||||
/// may distinct registry ids are in the cube.
|
||||
#[derive(Clone)]
|
||||
pub enum PalettedContainer<V: Hash + Eq + Copy + Default, const DIM: usize> {
|
||||
Homogeneous(V),
|
||||
Heterogeneous(Box<HeterogeneousPaletteData<V, DIM>>),
|
||||
}
|
||||
|
||||
impl<V: Hash + Eq + Copy + Default, const DIM: usize> PalettedContainer<V, DIM> {
|
||||
pub const SIZE: usize = DIM;
|
||||
pub const VOLUME: usize = DIM * DIM * DIM;
|
||||
|
||||
fn from_cube(cube: Box<AbstractCube<V, DIM>>) -> Self {
|
||||
let mut palette: Vec<V> = Vec::new();
|
||||
let mut counts: Vec<u16> = Vec::new();
|
||||
|
||||
// Iterate over the flattened cube to populate the palette and counts
|
||||
for val in cube.as_flattened().as_flattened() {
|
||||
if let Some(index) = palette.iter().position(|v| v == val) {
|
||||
// Value already exists, increment its count
|
||||
counts[index] += 1;
|
||||
} else {
|
||||
// New value, add it to the palette and start its count
|
||||
palette.push(*val);
|
||||
counts.push(1);
|
||||
}
|
||||
}
|
||||
|
||||
if palette.len() == 1 {
|
||||
// Fast path: the cube is homogeneous, so we can store just one value
|
||||
Self::Homogeneous(palette[0])
|
||||
} else {
|
||||
// Heterogeneous cube, store the full data
|
||||
if palette.len() <= 256 && std::mem::size_of::<V>() > 1 {
|
||||
let mut indices = Box::new([[[0u8; DIM]; DIM]; DIM]);
|
||||
for (i, v) in cube.as_flattened().as_flattened().iter().enumerate() {
|
||||
let idx = palette.iter().position(|p| p == v).unwrap();
|
||||
indices.as_flattened_mut().as_flattened_mut()[i] = idx as u8;
|
||||
}
|
||||
Self::Heterogeneous(Box::new(HeterogeneousPaletteData {
|
||||
storage: PaletteStorage::Indexed(indices),
|
||||
palette,
|
||||
counts,
|
||||
}))
|
||||
} else {
|
||||
Self::Heterogeneous(Box::new(HeterogeneousPaletteData {
|
||||
storage: PaletteStorage::Dense(cube),
|
||||
palette,
|
||||
counts,
|
||||
}))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds a complete palette without paying the bookkeeping cost of individual mutations.
|
||||
pub(crate) fn from_fn(mut value_at: impl FnMut(usize, usize, usize) -> V) -> Self {
|
||||
let mut cube = Box::new([[[V::default(); DIM]; DIM]; DIM]);
|
||||
let mut indices = Box::new([[[0u8; DIM]; DIM]; DIM]);
|
||||
let mut palette = Vec::new();
|
||||
let mut counts = Vec::<u16>::new();
|
||||
|
||||
for y in 0..DIM {
|
||||
for z in 0..DIM {
|
||||
for x in 0..DIM {
|
||||
let value = value_at(x, y, z);
|
||||
cube[y][z][x] = value;
|
||||
let index =
|
||||
if let Some(index) = palette.iter().position(|entry| *entry == value) {
|
||||
counts[index] += 1;
|
||||
index
|
||||
} else {
|
||||
palette.push(value);
|
||||
counts.push(1);
|
||||
palette.len() - 1
|
||||
};
|
||||
if let Ok(index) = u8::try_from(index) {
|
||||
indices[y][z][x] = index;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if palette.len() == 1 {
|
||||
return Self::Homogeneous(palette[0]);
|
||||
}
|
||||
|
||||
let storage = if palette.len() <= 256 && std::mem::size_of::<V>() > 1 {
|
||||
PaletteStorage::Indexed(indices)
|
||||
} else {
|
||||
PaletteStorage::Dense(cube)
|
||||
};
|
||||
Self::Heterogeneous(Box::new(HeterogeneousPaletteData {
|
||||
storage,
|
||||
palette,
|
||||
counts,
|
||||
}))
|
||||
}
|
||||
|
||||
fn bits_per_entry(&self) -> u8 {
|
||||
match self {
|
||||
Self::Homogeneous(_) => 0,
|
||||
Self::Heterogeneous(data) => encompassing_bits(data.counts.len()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn to_palette_and_packed_data(&self, bits_per_entry: u8) -> (Box<[V]>, Box<[i64]>) {
|
||||
match self {
|
||||
Self::Homogeneous(registry_id) => (Box::new([*registry_id]), Box::new([])),
|
||||
Self::Heterogeneous(data) => {
|
||||
debug_assert!(bits_per_entry >= encompassing_bits(data.counts.len()));
|
||||
debug_assert!(bits_per_entry <= 15);
|
||||
|
||||
// Don't use HashMap's here, because its slow
|
||||
let blocks_per_i64 = 64 / bits_per_entry;
|
||||
|
||||
let packed_indices: Box<[i64]> = match &data.storage {
|
||||
PaletteStorage::Dense(cube) => cube
|
||||
.as_flattened()
|
||||
.as_flattened()
|
||||
.chunks(blocks_per_i64 as usize)
|
||||
.map(|chunk| {
|
||||
chunk.iter().enumerate().fold(0, |acc, (index, key)| {
|
||||
let key_index =
|
||||
data.palette.iter().position(|&x| x == *key).unwrap();
|
||||
debug_assert!((1 << bits_per_entry) > key_index);
|
||||
|
||||
let packed_offset_index =
|
||||
(key_index as u64) << (bits_per_entry as u64 * index as u64);
|
||||
acc | packed_offset_index as i64
|
||||
})
|
||||
})
|
||||
.collect(),
|
||||
PaletteStorage::Indexed(indices) => indices
|
||||
.as_flattened()
|
||||
.as_flattened()
|
||||
.chunks(blocks_per_i64 as usize)
|
||||
.map(|chunk| {
|
||||
chunk.iter().enumerate().fold(0, |acc, (index, key_index)| {
|
||||
let key_index = *key_index as usize;
|
||||
debug_assert!((1 << bits_per_entry) > key_index);
|
||||
|
||||
let packed_offset_index =
|
||||
(key_index as u64) << (bits_per_entry as u64 * index as u64);
|
||||
acc | packed_offset_index as i64
|
||||
})
|
||||
})
|
||||
.collect(),
|
||||
};
|
||||
|
||||
(data.palette.clone().into_boxed_slice(), packed_indices)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn from_palette_and_packed_data(
|
||||
palette: &[V],
|
||||
packed_data: &[i64],
|
||||
minimum_bits_per_entry: u8,
|
||||
) -> Self {
|
||||
if palette.is_empty() {
|
||||
warn!("No palette data! Defaulting...");
|
||||
return Self::Homogeneous(V::default());
|
||||
}
|
||||
|
||||
if palette.len() == 1 {
|
||||
return Self::Homogeneous(palette[0]);
|
||||
}
|
||||
|
||||
let bits_per_key = encompassing_bits(palette.len()).max(minimum_bits_per_entry);
|
||||
let index_mask = (1 << bits_per_key) - 1;
|
||||
let keys_per_i64 = 64 / bits_per_key;
|
||||
|
||||
// Optimized path for indexed storage if palette is small enough
|
||||
if palette.len() <= 256 && std::mem::size_of::<V>() > 1 {
|
||||
let mut indices = Box::new([[[0u8; DIM]; DIM]; DIM]);
|
||||
let mut counts = vec![0u16; palette.len()];
|
||||
let indices_flat = indices.as_flattened_mut().as_flattened_mut();
|
||||
|
||||
let mut packed_data_iter = packed_data.iter();
|
||||
let mut current_packed_word = *packed_data_iter.next().unwrap_or(&0);
|
||||
|
||||
for (i, index_out) in indices_flat.iter_mut().enumerate().take(Self::VOLUME) {
|
||||
let bit_index_in_word = i % keys_per_i64 as usize;
|
||||
if bit_index_in_word == 0 && i > 0 {
|
||||
current_packed_word = *packed_data_iter.next().unwrap_or(&0);
|
||||
}
|
||||
|
||||
let lookup_index = ((current_packed_word as u64)
|
||||
>> (bit_index_in_word as u64 * bits_per_key as u64))
|
||||
& index_mask;
|
||||
|
||||
let idx = lookup_index as usize;
|
||||
if idx < palette.len() {
|
||||
*index_out = idx as u8;
|
||||
counts[idx] += 1;
|
||||
} else {
|
||||
warn!("Lookup index out of bounds! Defaulting...");
|
||||
// value is already 0, and counts[0] will be updated correctly if we track it
|
||||
}
|
||||
}
|
||||
// fix counts[0] if it was skipped in out-of-bounds cases (rare)
|
||||
// But actually we should just ensure it's correct.
|
||||
|
||||
return Self::Heterogeneous(Box::new(HeterogeneousPaletteData {
|
||||
storage: PaletteStorage::Indexed(indices),
|
||||
palette: palette.to_vec(),
|
||||
counts,
|
||||
}));
|
||||
}
|
||||
|
||||
let mut decompressed_values = Vec::with_capacity(Self::VOLUME);
|
||||
|
||||
let mut packed_data_iter = packed_data.iter();
|
||||
let mut current_packed_word = *packed_data_iter.next().unwrap_or(&0);
|
||||
|
||||
for i in 0..Self::VOLUME {
|
||||
let bit_index_in_word = i % keys_per_i64 as usize;
|
||||
|
||||
if bit_index_in_word == 0 && i > 0 {
|
||||
current_packed_word = *packed_data_iter.next().unwrap_or(&0);
|
||||
}
|
||||
|
||||
let lookup_index = (current_packed_word as u64
|
||||
>> (bit_index_in_word as u64 * bits_per_key as u64))
|
||||
& index_mask;
|
||||
|
||||
let value = palette
|
||||
.get(lookup_index as usize)
|
||||
.copied()
|
||||
.unwrap_or_else(|| {
|
||||
warn!("Lookup index out of bounds! Defaulting...");
|
||||
V::default()
|
||||
});
|
||||
|
||||
decompressed_values.push(value);
|
||||
}
|
||||
|
||||
// Now, with all decompressed values, build the counts.
|
||||
let mut counts = vec![0; palette.len()];
|
||||
|
||||
for &value in &decompressed_values {
|
||||
// This is the key optimization: find the index in the palette Vec
|
||||
// and increment the corresponding count.
|
||||
if let Some(index) = palette.iter().position(|v| v == &value) {
|
||||
counts[index] += 1;
|
||||
} else {
|
||||
// This case should ideally not happen if the palette is complete.
|
||||
warn!("Decompressed value not found in palette!");
|
||||
}
|
||||
}
|
||||
|
||||
let mut cube = Box::new([[[V::default(); DIM]; DIM]; DIM]);
|
||||
cube.as_flattened_mut()
|
||||
.as_flattened_mut()
|
||||
.copy_from_slice(&decompressed_values);
|
||||
|
||||
Self::Heterogeneous(Box::new(HeterogeneousPaletteData {
|
||||
storage: PaletteStorage::Dense(cube),
|
||||
palette: palette.to_vec(),
|
||||
counts,
|
||||
}))
|
||||
}
|
||||
|
||||
pub fn get(&self, x: usize, y: usize, z: usize) -> V {
|
||||
match self {
|
||||
Self::Homogeneous(value) => *value,
|
||||
Self::Heterogeneous(data) => data.get(x, y, z),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set(&mut self, x: usize, y: usize, z: usize, value: V) -> V {
|
||||
debug_assert!(x < Self::SIZE);
|
||||
debug_assert!(y < Self::SIZE);
|
||||
debug_assert!(z < Self::SIZE);
|
||||
|
||||
match self {
|
||||
Self::Homogeneous(original) => {
|
||||
let original = *original;
|
||||
if value != original {
|
||||
let mut cube = Box::new([[[original; DIM]; DIM]; DIM]);
|
||||
cube[y][z][x] = value;
|
||||
*self = Self::from_cube(cube);
|
||||
}
|
||||
original
|
||||
}
|
||||
Self::Heterogeneous(data) => {
|
||||
let original = data.set(x, y, z, value);
|
||||
if data.counts.len() == 1 {
|
||||
*self = Self::Homogeneous(data.palette[0]);
|
||||
}
|
||||
original
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn iter(&self) -> Box<dyn Iterator<Item = V> + '_> {
|
||||
match self {
|
||||
Self::Homogeneous(registry_id) => {
|
||||
Box::new(std::iter::repeat_n(*registry_id, Self::VOLUME))
|
||||
}
|
||||
Self::Heterogeneous(data) => match &data.storage {
|
||||
PaletteStorage::Dense(cube) => {
|
||||
Box::new(cube.as_flattened().as_flattened().iter().copied())
|
||||
}
|
||||
PaletteStorage::Indexed(indices) => Box::new(
|
||||
indices
|
||||
.as_flattened()
|
||||
.as_flattened()
|
||||
.iter()
|
||||
.map(|&idx| data.palette[idx as usize]),
|
||||
),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
match self {
|
||||
Self::Homogeneous(value) => *value == V::default(),
|
||||
Self::Heterogeneous(_) => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, V: Hash + Eq + Copy + Default, const DIM: usize> IntoIterator
|
||||
for &'a PalettedContainer<V, DIM>
|
||||
{
|
||||
type Item = V;
|
||||
type IntoIter = Box<dyn Iterator<Item = Self::Item> + 'a>;
|
||||
|
||||
fn into_iter(self) -> Self::IntoIter {
|
||||
match self {
|
||||
PalettedContainer::Homogeneous(registry_id) => Box::new(std::iter::repeat_n(
|
||||
*registry_id,
|
||||
PalettedContainer::<V, DIM>::VOLUME,
|
||||
)),
|
||||
PalettedContainer::Heterogeneous(data) => match &data.storage {
|
||||
PaletteStorage::Dense(cube) => {
|
||||
Box::new(cube.as_flattened().as_flattened().iter().copied())
|
||||
}
|
||||
PaletteStorage::Indexed(indices) => Box::new(
|
||||
indices
|
||||
.as_flattened()
|
||||
.as_flattened()
|
||||
.iter()
|
||||
.map(|&idx| data.palette[idx as usize]),
|
||||
),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<V: Default + Hash + Eq + Copy, const DIM: usize> Default for PalettedContainer<V, DIM> {
|
||||
fn default() -> Self {
|
||||
Self::Homogeneous(V::default())
|
||||
}
|
||||
}
|
||||
|
||||
impl BiomePalette {
|
||||
#[must_use]
|
||||
pub fn convert_network(&self) -> NetworkSerialization<u8> {
|
||||
match self {
|
||||
Self::Homogeneous(registry_id) => NetworkSerialization {
|
||||
bits_per_entry: 0,
|
||||
palette: NetworkPalette::Single(*registry_id),
|
||||
packed_data: Box::new([]),
|
||||
},
|
||||
Self::Heterogeneous(data) => {
|
||||
let raw_bits_per_entry = encompassing_bits(data.counts.len());
|
||||
if raw_bits_per_entry > BIOME_NETWORK_MAX_MAP_BITS {
|
||||
let bits_per_entry = BIOME_NETWORK_MAX_BITS;
|
||||
let values_per_i64 = 64 / bits_per_entry;
|
||||
let mut packed_data = Vec::new();
|
||||
let mut current_idx = 0;
|
||||
while current_idx < Self::VOLUME {
|
||||
let mut acc = 0u64;
|
||||
for i in 0..values_per_i64 as usize {
|
||||
if current_idx + i < Self::VOLUME {
|
||||
let y = (current_idx + i) / (Self::SIZE * Self::SIZE);
|
||||
let z = ((current_idx + i) / Self::SIZE) % Self::SIZE;
|
||||
let x = (current_idx + i) % Self::SIZE;
|
||||
let value = data.get(x, y, z);
|
||||
debug_assert!((1 << bits_per_entry) > value);
|
||||
acc |= (value as u64) << (bits_per_entry as u64 * i as u64);
|
||||
}
|
||||
}
|
||||
packed_data.push(acc as i64);
|
||||
current_idx += values_per_i64 as usize;
|
||||
}
|
||||
|
||||
NetworkSerialization {
|
||||
bits_per_entry,
|
||||
palette: NetworkPalette::Direct,
|
||||
packed_data: packed_data.into_boxed_slice(),
|
||||
}
|
||||
} else {
|
||||
let bits_per_entry = raw_bits_per_entry.max(BIOME_NETWORK_MIN_MAP_BITS);
|
||||
let (palette, packed) = self.to_palette_and_packed_data(bits_per_entry);
|
||||
|
||||
NetworkSerialization {
|
||||
bits_per_entry,
|
||||
palette: NetworkPalette::Indirect(palette),
|
||||
packed_data: packed,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn convert_be_network(&self) -> BeNetworkSerialization<u8> {
|
||||
match self {
|
||||
Self::Homogeneous(registry_id) => BeNetworkSerialization {
|
||||
bits_per_entry: 0,
|
||||
palette: NetworkPalette::Single(
|
||||
pumpkin_data::biome::Biome::from_id(*registry_id)
|
||||
.map_or(1, |b| b.be_network_id),
|
||||
),
|
||||
packed_data: Box::new([]),
|
||||
},
|
||||
Self::Heterogeneous(data) => {
|
||||
let bits_per_entry = encompassing_bits(data.palette.len());
|
||||
|
||||
let key_to_index_map: HashMap<_, usize> = data
|
||||
.palette
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, key)| (*key, index))
|
||||
.collect();
|
||||
|
||||
let biomes_per_word = 32 / bits_per_entry;
|
||||
let volume: usize = 4096;
|
||||
let expected_word_count = volume.div_ceil(biomes_per_word as usize);
|
||||
let mut packed_data = Vec::with_capacity(expected_word_count);
|
||||
|
||||
let mut current_word: u32 = 0;
|
||||
let mut current_index_in_word = 0;
|
||||
|
||||
for x in 0..16 {
|
||||
for y in 0..16 {
|
||||
for z in 0..16 {
|
||||
let key = self.get(x / 4, z / 4, y / 4);
|
||||
let key_index = key_to_index_map.get(&key).unwrap();
|
||||
debug_assert!((1 << bits_per_entry) > *key_index);
|
||||
|
||||
current_word |= (*key_index as u32)
|
||||
<< (bits_per_entry as u32 * current_index_in_word);
|
||||
current_index_in_word += 1;
|
||||
|
||||
if current_index_in_word == biomes_per_word as u32 {
|
||||
packed_data.push(current_word);
|
||||
current_word = 0;
|
||||
current_index_in_word = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Push any remaining bits if the volume isn't a multiple of biomes_per_word
|
||||
if current_index_in_word > 0 {
|
||||
packed_data.push(current_word);
|
||||
}
|
||||
|
||||
BeNetworkSerialization {
|
||||
bits_per_entry,
|
||||
palette: NetworkPalette::Indirect(
|
||||
data.palette
|
||||
.iter()
|
||||
.map(|&id| {
|
||||
pumpkin_data::biome::Biome::from_id(id)
|
||||
.map_or(1, |b| b.be_network_id)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.into_boxed_slice(),
|
||||
),
|
||||
packed_data: packed_data.into_boxed_slice(),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn from_disk_nbt(nbt: ChunkSectionBiomes) -> Self {
|
||||
let palette = nbt.palette;
|
||||
|
||||
Self::from_palette_and_packed_data(
|
||||
&palette,
|
||||
nbt.data.as_ref().unwrap_or(&Box::default()),
|
||||
BIOME_DISK_MIN_BITS,
|
||||
)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn to_disk_nbt(&self) -> ChunkSectionBiomes {
|
||||
#[expect(clippy::unnecessary_min_or_max)]
|
||||
let bits_per_entry = self.bits_per_entry().max(BIOME_DISK_MIN_BITS);
|
||||
let (palette, packed_data) = self.to_palette_and_packed_data(bits_per_entry);
|
||||
ChunkSectionBiomes {
|
||||
data: if packed_data.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(packed_data)
|
||||
},
|
||||
palette,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl BlockPalette {
|
||||
#[must_use]
|
||||
pub fn convert_network(&self) -> NetworkSerialization<u16> {
|
||||
match self {
|
||||
Self::Homogeneous(registry_id) => NetworkSerialization {
|
||||
bits_per_entry: 0,
|
||||
palette: NetworkPalette::Single(registry_id.as_u16()),
|
||||
packed_data: Box::new([]),
|
||||
},
|
||||
Self::Heterogeneous(data) => {
|
||||
let raw_bits_per_entry = encompassing_bits(data.counts.len());
|
||||
if raw_bits_per_entry > BLOCK_NETWORK_MAX_MAP_BITS {
|
||||
let bits_per_entry = BLOCK_NETWORK_MAX_BITS;
|
||||
let values_per_i64 = 64 / bits_per_entry;
|
||||
let mut packed_data = Vec::new();
|
||||
let mut current_idx = 0;
|
||||
while current_idx < Self::VOLUME {
|
||||
let mut acc = 0u64;
|
||||
for i in 0..values_per_i64 as usize {
|
||||
if current_idx + i < Self::VOLUME {
|
||||
let y = (current_idx + i) / (Self::SIZE * Self::SIZE);
|
||||
let z = ((current_idx + i) / Self::SIZE) % Self::SIZE;
|
||||
let x = (current_idx + i) % Self::SIZE;
|
||||
let value = data.get(x, y, z).as_u16();
|
||||
debug_assert!((1 << bits_per_entry) > value);
|
||||
acc |= (value as u64) << (bits_per_entry as u64 * i as u64);
|
||||
}
|
||||
}
|
||||
packed_data.push(acc as i64);
|
||||
current_idx += values_per_i64 as usize;
|
||||
}
|
||||
|
||||
NetworkSerialization {
|
||||
bits_per_entry,
|
||||
palette: NetworkPalette::Direct,
|
||||
packed_data: packed_data.into_boxed_slice(),
|
||||
}
|
||||
} else {
|
||||
let bits_per_entry = raw_bits_per_entry.max(BLOCK_NETWORK_MIN_MAP_BITS);
|
||||
let (palette, packed) = self.to_palette_and_packed_data(bits_per_entry);
|
||||
|
||||
NetworkSerialization {
|
||||
bits_per_entry,
|
||||
palette: NetworkPalette::Indirect(
|
||||
palette.iter().map(|v| v.as_u16()).collect(),
|
||||
),
|
||||
packed_data: packed,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn convert_be_network(&self) -> BeNetworkSerialization<u16> {
|
||||
match self {
|
||||
Self::Homogeneous(registry_id) => BeNetworkSerialization {
|
||||
bits_per_entry: 0,
|
||||
palette: NetworkPalette::Single(BlockState::to_be_network_id(*registry_id)),
|
||||
packed_data: Box::new([]),
|
||||
},
|
||||
Self::Heterogeneous(data) => {
|
||||
let bits_per_entry = encompassing_bits(data.palette.len());
|
||||
|
||||
let key_to_index_map: HashMap<_, usize> = data
|
||||
.palette
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, key)| (*key, index))
|
||||
.collect();
|
||||
|
||||
let blocks_per_word = 32 / bits_per_entry;
|
||||
let expected_word_count = Self::VOLUME.div_ceil(blocks_per_word as usize);
|
||||
let mut packed_data = Vec::with_capacity(expected_word_count);
|
||||
|
||||
let mut current_word: u32 = 0;
|
||||
let mut current_index_in_word = 0;
|
||||
|
||||
for x in 0..16 {
|
||||
for y in 0..16 {
|
||||
for z in 0..16 {
|
||||
// Java has it in y, z, x order, so we need to convert it back to x, y, z
|
||||
// Please test your code on bedrock before merging
|
||||
let key = data.get(x, z, y);
|
||||
let key_index = key_to_index_map.get(&key).unwrap();
|
||||
debug_assert!((1 << bits_per_entry) > *key_index);
|
||||
|
||||
current_word |= (*key_index as u32)
|
||||
<< (bits_per_entry as u32 * current_index_in_word);
|
||||
current_index_in_word += 1;
|
||||
|
||||
if current_index_in_word == blocks_per_word as u32 {
|
||||
packed_data.push(current_word);
|
||||
current_word = 0;
|
||||
current_index_in_word = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Push any remaining bits if the volume isn't a multiple of blocks_per_word
|
||||
if current_index_in_word > 0 {
|
||||
packed_data.push(current_word);
|
||||
}
|
||||
|
||||
BeNetworkSerialization {
|
||||
bits_per_entry,
|
||||
palette: NetworkPalette::Indirect(
|
||||
data.palette
|
||||
.iter()
|
||||
.map(|&id| BlockState::to_be_network_id(id))
|
||||
.collect(),
|
||||
),
|
||||
packed_data: packed_data.into_boxed_slice(),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if the entire chunk is filled with only air
|
||||
#[must_use]
|
||||
pub fn has_only_air(&self) -> bool {
|
||||
match self {
|
||||
Self::Homogeneous(id) => is_air(*id),
|
||||
Self::Heterogeneous(data) => data.palette.iter().all(|&id| is_air(id)),
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn random_ticking_counts(&self) -> (u16, u16) {
|
||||
match self {
|
||||
Self::Homogeneous(registry_id) => {
|
||||
let block_count = if has_random_ticks(*registry_id) {
|
||||
Self::VOLUME as u16
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let fluid_count = if has_random_ticking_fluid(*registry_id) {
|
||||
Self::VOLUME as u16
|
||||
} else {
|
||||
0
|
||||
};
|
||||
(block_count, fluid_count)
|
||||
}
|
||||
Self::Heterogeneous(data) => data.palette.iter().zip(data.counts.iter()).fold(
|
||||
(0, 0),
|
||||
|(block_count, fluid_count), (registry_id, count)| {
|
||||
let block_count = if has_random_ticks(*registry_id) {
|
||||
block_count.saturating_add(*count)
|
||||
} else {
|
||||
block_count
|
||||
};
|
||||
let fluid_count = if has_random_ticking_fluid(*registry_id) {
|
||||
fluid_count.saturating_add(*count)
|
||||
} else {
|
||||
fluid_count
|
||||
};
|
||||
(block_count, fluid_count)
|
||||
},
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn non_air_block_count(&self) -> u16 {
|
||||
match self {
|
||||
Self::Homogeneous(registry_id) => {
|
||||
if is_air(*registry_id) {
|
||||
0
|
||||
} else {
|
||||
Self::VOLUME as u16
|
||||
}
|
||||
}
|
||||
Self::Heterogeneous(data) => data
|
||||
.palette
|
||||
.iter()
|
||||
.zip(data.counts.iter())
|
||||
.filter_map(|(registry_id, count)| (!is_air(*registry_id)).then_some(*count))
|
||||
.sum(),
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn liquid_block_count(&self) -> u16 {
|
||||
match self {
|
||||
Self::Homogeneous(registry_id) => {
|
||||
if is_liquid(*registry_id) {
|
||||
Self::VOLUME as u16
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
Self::Heterogeneous(data) => data
|
||||
.palette
|
||||
.iter()
|
||||
.zip(data.counts.iter())
|
||||
.filter_map(|(registry_id, count)| is_liquid(*registry_id).then_some(*count))
|
||||
.sum(),
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn from_disk_nbt(nbt: ChunkSectionBlockStates) -> Self {
|
||||
let palette = nbt.palette;
|
||||
|
||||
Self::from_palette_and_packed_data(
|
||||
&palette,
|
||||
nbt.data.as_ref().unwrap_or(&Box::default()),
|
||||
BLOCK_DISK_MIN_BITS,
|
||||
)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn to_disk_nbt(&self) -> ChunkSectionBlockStates {
|
||||
let bits_per_entry = self.bits_per_entry().max(BLOCK_DISK_MIN_BITS);
|
||||
let (palette, packed_data) = self.to_palette_and_packed_data(bits_per_entry);
|
||||
ChunkSectionBlockStates {
|
||||
data: if packed_data.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(packed_data)
|
||||
},
|
||||
palette,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents the different types of data encoding used in Minecraft's bit-packed chunk sections.
|
||||
///
|
||||
/// Minecraft uses a "Palette" system to compress chunk data. Instead of sending a full
|
||||
/// 15-bit `BlockState` ID for every block, it sends a smaller index (e.g., 4 bits) that
|
||||
/// points to a value in these palettes.
|
||||
pub enum NetworkPalette<V> {
|
||||
/// **Single Value Palette (Bits per entry: 0)**
|
||||
///
|
||||
/// Used when an entire chunk section (16x16x16) consists of only one type of block or biome.
|
||||
/// No data array follows this palette in the network buffer.
|
||||
Single(V),
|
||||
/// **Indirect Palette (Bits per entry: 1-8 for blocks, 1-3 for biomes)**
|
||||
///
|
||||
/// A list of unique values present in the section. The data array contains indices
|
||||
/// pointing into this list.
|
||||
Indirect(Box<[V]>),
|
||||
/// **Direct Palette (Bits per entry: 15+ for blocks, 6+ for biomes)**
|
||||
///
|
||||
/// Used when the section is too complex for a small palette. The data array
|
||||
/// contains global Registry IDs directly. No palette list is sent.
|
||||
Direct,
|
||||
}
|
||||
|
||||
pub struct NetworkSerialization<V> {
|
||||
pub bits_per_entry: u8,
|
||||
pub palette: NetworkPalette<V>,
|
||||
pub packed_data: Box<[i64]>,
|
||||
}
|
||||
|
||||
pub struct BeNetworkSerialization<V> {
|
||||
pub bits_per_entry: u8,
|
||||
pub palette: NetworkPalette<V>,
|
||||
pub packed_data: Box<[u32]>,
|
||||
}
|
||||
|
||||
// According to the wiki, palette serialization for disk and network is different. Disk
|
||||
// serialization always uses a palette if greater than one entry. Network serialization packs ids
|
||||
// directly instead of using a palette above a certain bits-per-entry
|
||||
|
||||
// TODO: Do our own testing; do we really need to handle network and disk serialization differently?
|
||||
pub type BlockPalette = PalettedContainer<BlockStateId, 16>;
|
||||
const BLOCK_DISK_MIN_BITS: u8 = 4;
|
||||
const BLOCK_NETWORK_MIN_MAP_BITS: u8 = 4;
|
||||
const BLOCK_NETWORK_MAX_MAP_BITS: u8 = 8;
|
||||
pub(crate) const BLOCK_NETWORK_MAX_BITS: u8 = 15;
|
||||
|
||||
pub type BiomePalette = PalettedContainer<u8, 4>;
|
||||
const BIOME_DISK_MIN_BITS: u8 = 0;
|
||||
const BIOME_NETWORK_MIN_MAP_BITS: u8 = 1;
|
||||
const BIOME_NETWORK_MAX_MAP_BITS: u8 = 3;
|
||||
pub(crate) const BIOME_NETWORK_MAX_BITS: u8 = 7;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{BlockPalette, NetworkPalette};
|
||||
use pumpkin_data::{Block, BlockStateId};
|
||||
|
||||
fn network_palette_values(palette: NetworkPalette<u16>) -> Option<Box<[u16]>> {
|
||||
match palette {
|
||||
NetworkPalette::Single(value) => Some(Box::new([value])),
|
||||
NetworkPalette::Indirect(values) => Some(values),
|
||||
NetworkPalette::Direct => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_bulk_matches_mutations(value_at: impl Fn(usize, usize, usize) -> BlockStateId) {
|
||||
let mut mutated = BlockPalette::default();
|
||||
for y in 0..BlockPalette::SIZE {
|
||||
for z in 0..BlockPalette::SIZE {
|
||||
for x in 0..BlockPalette::SIZE {
|
||||
mutated.set(x, y, z, value_at(x, y, z));
|
||||
}
|
||||
}
|
||||
}
|
||||
let bulk = BlockPalette::from_fn(value_at);
|
||||
|
||||
assert_eq!(
|
||||
mutated.iter().collect::<Vec<_>>(),
|
||||
bulk.iter().collect::<Vec<_>>()
|
||||
);
|
||||
assert_eq!(
|
||||
mutated.random_ticking_counts(),
|
||||
bulk.random_ticking_counts()
|
||||
);
|
||||
assert_eq!(mutated.non_air_block_count(), bulk.non_air_block_count());
|
||||
assert_eq!(mutated.liquid_block_count(), bulk.liquid_block_count());
|
||||
|
||||
let mutated_network = mutated.convert_network();
|
||||
let bulk_network = bulk.convert_network();
|
||||
assert_eq!(mutated_network.bits_per_entry, bulk_network.bits_per_entry);
|
||||
assert_eq!(mutated_network.packed_data, bulk_network.packed_data);
|
||||
assert_eq!(
|
||||
network_palette_values(mutated_network.palette),
|
||||
network_palette_values(bulk_network.palette)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bulk_palette_matches_individual_mutations() {
|
||||
let states = [
|
||||
Block::AIR.default_state.id,
|
||||
Block::STONE.default_state.id,
|
||||
Block::WATER.default_state.id,
|
||||
Block::LAVA.default_state.id,
|
||||
];
|
||||
assert_bulk_matches_mutations(|x, y, z| states[(x + y + z) % states.len()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bulk_palette_handles_homogeneous_sections() {
|
||||
assert_bulk_matches_mutations(|_, _, _| Block::STONE.default_state.id);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bulk_palette_handles_direct_network_palettes() {
|
||||
assert_bulk_matches_mutations(|x, y, z| {
|
||||
BlockStateId::new_or_air(((y * 256 + z * 16 + x) % 300) as u16)
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
use super::{ChunkLevel, ChunkPos, HashMapType};
|
||||
use crate::chunk_system::chunk_state::StagedChunkEnum;
|
||||
use crate::level::Level;
|
||||
use std::collections::hash_map::Entry;
|
||||
use std::mem::swap;
|
||||
use std::sync::atomic::Ordering::SeqCst;
|
||||
use std::sync::{Arc, Condvar, Mutex};
|
||||
|
||||
pub type LevelChange = (
|
||||
HashMapType<ChunkPos, (StagedChunkEnum, StagedChunkEnum)>,
|
||||
ChunkLevel,
|
||||
);
|
||||
|
||||
pub struct LevelChannel {
|
||||
pub value: Mutex<(Option<LevelChange>, Option<Vec<ChunkPos>>)>,
|
||||
pub notify: Condvar,
|
||||
}
|
||||
|
||||
impl Default for LevelChannel {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl LevelChannel {
|
||||
#[must_use]
|
||||
pub const fn new() -> Self {
|
||||
Self {
|
||||
value: Mutex::new((None, None)),
|
||||
notify: Condvar::new(),
|
||||
}
|
||||
}
|
||||
pub fn set_both(
|
||||
&self,
|
||||
new_value: (
|
||||
HashMapType<ChunkPos, (StagedChunkEnum, StagedChunkEnum)>,
|
||||
ChunkLevel,
|
||||
),
|
||||
pos: Vec<ChunkPos>,
|
||||
) {
|
||||
// debug!("set new level and priority");
|
||||
let mut value = self.value.lock().unwrap();
|
||||
value.1 = Some(pos);
|
||||
if let Some(old) = &mut value.0 {
|
||||
for (pos, change) in new_value.0 {
|
||||
match old.0.entry(pos) {
|
||||
Entry::Occupied(mut entry) => {
|
||||
let tmp = entry.get_mut();
|
||||
debug_assert_eq!(tmp.1, change.0);
|
||||
if tmp.0 == change.1 {
|
||||
entry.remove();
|
||||
} else {
|
||||
tmp.1 = change.1;
|
||||
}
|
||||
}
|
||||
Entry::Vacant(entry) => {
|
||||
debug_assert_ne!(change.0, change.1);
|
||||
entry.insert(change);
|
||||
}
|
||||
}
|
||||
}
|
||||
old.1 = new_value.1;
|
||||
} else {
|
||||
value.0 = Some(new_value);
|
||||
}
|
||||
self.notify.notify_one();
|
||||
}
|
||||
pub fn set_level(
|
||||
&self,
|
||||
new_value: (
|
||||
HashMapType<ChunkPos, (StagedChunkEnum, StagedChunkEnum)>,
|
||||
ChunkLevel,
|
||||
),
|
||||
) {
|
||||
// debug!("set new level");
|
||||
let mut value = self.value.lock().unwrap();
|
||||
if let Some(old) = &mut value.0 {
|
||||
for (pos, change) in new_value.0 {
|
||||
match old.0.entry(pos) {
|
||||
Entry::Occupied(mut entry) => {
|
||||
let tmp = entry.get_mut();
|
||||
debug_assert_eq!(tmp.1, change.0);
|
||||
if tmp.0 == change.1 {
|
||||
entry.remove();
|
||||
} else {
|
||||
tmp.1 = change.1;
|
||||
}
|
||||
}
|
||||
Entry::Vacant(entry) => {
|
||||
debug_assert_ne!(change.0, change.1);
|
||||
entry.insert(change);
|
||||
}
|
||||
}
|
||||
}
|
||||
old.1 = new_value.1;
|
||||
} else {
|
||||
value.0 = Some(new_value);
|
||||
}
|
||||
self.notify.notify_one();
|
||||
}
|
||||
pub fn set_priority(&self, pos: Vec<ChunkPos>) {
|
||||
// debug!("set new priority");
|
||||
self.value.lock().unwrap().1 = Some(pos);
|
||||
self.notify.notify_one();
|
||||
}
|
||||
pub fn get(&self) -> (Option<LevelChange>, Option<Vec<ChunkPos>>) {
|
||||
let mut lock = self.value.lock().unwrap();
|
||||
let mut ret = (None, None);
|
||||
swap(&mut ret, &mut *lock);
|
||||
ret
|
||||
}
|
||||
pub fn wait_and_get(&self, level: &Arc<Level>) -> (Option<LevelChange>, Option<Vec<ChunkPos>>) {
|
||||
let mut lock = self.value.lock().unwrap();
|
||||
while lock.0.is_none()
|
||||
&& lock.1.is_none()
|
||||
&& !level.should_unload.load(SeqCst)
|
||||
&& !level.should_save.load(SeqCst)
|
||||
&& !level.shut_down_chunk_system.load(SeqCst)
|
||||
{
|
||||
lock = self.notify.wait(lock).unwrap();
|
||||
}
|
||||
let mut ret = (None, None);
|
||||
swap(&mut ret, &mut *lock);
|
||||
ret
|
||||
}
|
||||
pub fn notify(&self) {
|
||||
let val = self
|
||||
.value
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
drop(val);
|
||||
self.notify.notify_one();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
use super::chunk_state::{Chunk, StagedChunkEnum};
|
||||
use super::dag::{EdgeKey, NodeKey};
|
||||
use slotmap::Key;
|
||||
|
||||
pub struct ChunkHolder {
|
||||
pub target_stage: StagedChunkEnum,
|
||||
/// Minimum stage required by generation dependencies (e.g. `StructureReferences` neighbors).
|
||||
/// May exceed `target_stage` when this chunk is needed by a neighbor's generation task
|
||||
/// but isn't in the player's view radius. Tasks up to this stage are scheduled but the
|
||||
/// chunk is not made public and is unloaded once the dependency is satisfied.
|
||||
pub dependency_stage: StagedChunkEnum,
|
||||
pub current_stage: StagedChunkEnum,
|
||||
pub chunk: Option<Chunk>,
|
||||
pub occupied: NodeKey,
|
||||
pub occupied_by: EdgeKey,
|
||||
pub public: bool,
|
||||
pub tasks: [NodeKey; StagedChunkEnum::COUNT],
|
||||
}
|
||||
|
||||
impl Default for ChunkHolder {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
target_stage: StagedChunkEnum::None,
|
||||
dependency_stage: StagedChunkEnum::None,
|
||||
current_stage: StagedChunkEnum::None,
|
||||
chunk: None,
|
||||
occupied: NodeKey::null(),
|
||||
occupied_by: EdgeKey::null(),
|
||||
public: false,
|
||||
tasks: [NodeKey::null(); StagedChunkEnum::COUNT],
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
use super::ChunkPos;
|
||||
use crate::level::SyncChunk;
|
||||
use crossbeam::channel::{Receiver, Sender};
|
||||
use std::sync::Arc;
|
||||
use std::sync::{Mutex, Weak};
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
#[expect(clippy::type_complexity)]
|
||||
pub struct ChunkListener {
|
||||
single: Mutex<Vec<(ChunkPos, oneshot::Sender<SyncChunk>)>>,
|
||||
global: Mutex<Vec<Sender<(ChunkPos, Weak<crate::chunk::ChunkData>)>>>,
|
||||
}
|
||||
|
||||
impl Default for ChunkListener {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl ChunkListener {
|
||||
#[must_use]
|
||||
pub const fn new() -> Self {
|
||||
Self {
|
||||
single: Mutex::new(Vec::new()),
|
||||
global: Mutex::new(Vec::new()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn add_single_chunk_listener(&self, pos: ChunkPos) -> oneshot::Receiver<SyncChunk> {
|
||||
let (tx, rx) = oneshot::channel();
|
||||
self.single.lock().unwrap().push((pos, tx));
|
||||
rx
|
||||
}
|
||||
|
||||
pub fn add_global_chunk_listener(&self) -> Receiver<(ChunkPos, Weak<crate::chunk::ChunkData>)> {
|
||||
let (tx, rx) = crossbeam::channel::unbounded();
|
||||
self.global.lock().unwrap().push(tx);
|
||||
rx
|
||||
}
|
||||
|
||||
pub fn process_new_chunk(&self, pos: ChunkPos, chunk: &SyncChunk) {
|
||||
{
|
||||
let mut single = self.single.lock().unwrap();
|
||||
let mut i = 0;
|
||||
let mut len = single.len();
|
||||
while i < len {
|
||||
if single[i].0 == pos {
|
||||
let (_, send) = single.remove(i);
|
||||
let _ = send.send(chunk.clone());
|
||||
// log::debug!("single listener {i} send {pos:?}");
|
||||
len -= 1;
|
||||
continue;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
{
|
||||
let weak = Arc::downgrade(chunk);
|
||||
let mut global = self.global.lock().unwrap();
|
||||
let mut i = 0;
|
||||
let mut len = global.len();
|
||||
while i < len {
|
||||
if matches!(global[i].send((pos, weak.clone())), Ok(())) {
|
||||
// log::debug!("global listener {i} send {pos:?}");
|
||||
} else {
|
||||
// log::debug!("one global listener dropped");
|
||||
global.remove(i);
|
||||
len -= 1;
|
||||
continue;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,428 @@
|
||||
use super::{ChunkLevel, ChunkPos, HashMapType, LevelChannel};
|
||||
use crate::chunk_system::chunk_state::StagedChunkEnum; // Fixed path
|
||||
use itertools::Itertools;
|
||||
use std::cmp::min;
|
||||
use std::collections::VecDeque;
|
||||
use std::collections::hash_map::Entry;
|
||||
use std::fmt::Write;
|
||||
use std::mem::swap;
|
||||
use std::sync::Arc;
|
||||
use tracing::debug;
|
||||
|
||||
struct LevelCache(i32, i32, usize, [(i8, i8); 256 * 256]);
|
||||
|
||||
#[expect(clippy::large_stack_arrays)]
|
||||
impl LevelCache {
|
||||
const fn new() -> Self {
|
||||
Self(0, 0, 0, [(0, 0); 256 * 256])
|
||||
}
|
||||
}
|
||||
impl LevelCache {
|
||||
fn clean(&mut self, pos: ChunkPos, level: i8) {
|
||||
let dst = ChunkLoading::MAX_LEVEL - level + 1;
|
||||
self.0 = pos.x - dst as i32;
|
||||
self.1 = pos.y - dst as i32;
|
||||
self.2 = (dst as usize) << 1 | 1;
|
||||
self.3[..self.2 * self.2].fill((-127, -127));
|
||||
}
|
||||
fn get(&mut self, map: &ChunkLevel, pos: ChunkPos) -> i8 {
|
||||
let dx = (pos.x - self.0) as usize;
|
||||
let dy = (pos.y - self.1) as usize;
|
||||
debug_assert!(pos.x >= self.0 && pos.y >= self.1);
|
||||
let value = &mut self.3[dx * self.2 + dy];
|
||||
if value.0 == -127 {
|
||||
value.0 = *map.get(&pos).unwrap_or(&ChunkLoading::MAX_LEVEL);
|
||||
value.1 = value.0;
|
||||
}
|
||||
value.1
|
||||
}
|
||||
fn set(&mut self, map: &ChunkLevel, pos: ChunkPos, level: i8) {
|
||||
let dx = (pos.x - self.0) as usize;
|
||||
let dy = (pos.y - self.1) as usize;
|
||||
debug_assert!(pos.x >= self.0 && pos.y >= self.1);
|
||||
let value = &mut self.3[dx * self.2 + dy];
|
||||
if value.0 == -127 {
|
||||
value.0 = *map.get(&pos).unwrap_or(&ChunkLoading::MAX_LEVEL);
|
||||
}
|
||||
value.1 = level;
|
||||
}
|
||||
fn write(
|
||||
&self,
|
||||
map: &mut ChunkLevel,
|
||||
change: &mut HashMapType<ChunkPos, (StagedChunkEnum, StagedChunkEnum)>,
|
||||
) {
|
||||
for i in 0..self.2 {
|
||||
for j in 0..self.2 {
|
||||
let value = self.3[i * self.2 + j];
|
||||
if value.0 != value.1 {
|
||||
let pos = ChunkPos::new(i as i32 + self.0, j as i32 + self.1);
|
||||
if value.1 == ChunkLoading::MAX_LEVEL {
|
||||
map.remove(&pos);
|
||||
} else {
|
||||
map.insert(pos, value.1);
|
||||
}
|
||||
let value = (
|
||||
StagedChunkEnum::level_to_stage(value.0),
|
||||
StagedChunkEnum::level_to_stage(value.1),
|
||||
);
|
||||
if value.0 == value.1 {
|
||||
continue;
|
||||
}
|
||||
match change.entry(pos) {
|
||||
Entry::Occupied(mut entry) => {
|
||||
let i = entry.get_mut();
|
||||
debug_assert_eq!(i.1, value.0);
|
||||
if i.0 == value.1 {
|
||||
entry.remove();
|
||||
} else {
|
||||
i.1 = value.1;
|
||||
}
|
||||
}
|
||||
Entry::Vacant(entry) => {
|
||||
entry.insert(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ChunkLoading {
|
||||
pub is_priority_dirty: bool,
|
||||
pub pos_level: ChunkLevel,
|
||||
change: HashMapType<ChunkPos, (StagedChunkEnum, StagedChunkEnum)>,
|
||||
pub ticket: HashMapType<ChunkPos, Vec<i8>>, // TODO lifetime & id
|
||||
pub high_priority: Vec<ChunkPos>,
|
||||
pub sender: Arc<LevelChannel>,
|
||||
pub increase_update: VecDeque<(ChunkPos, i8)>,
|
||||
pub decrease_update: VecDeque<(ChunkPos, i8)>,
|
||||
cache: LevelCache,
|
||||
}
|
||||
|
||||
impl ChunkLoading {
|
||||
// pub const FULL_CHUNK_LEVEL: i8 = 33;
|
||||
pub const FULL_CHUNK_LEVEL: i8 = 43;
|
||||
pub const MAX_LEVEL: i8 = 49; // level 49 will be unloaded.
|
||||
fn debug_check_error(&self) -> bool {
|
||||
let mut temp = ChunkLevel::default();
|
||||
for (ticket_pos, levels) in &self.ticket {
|
||||
let level = *levels.iter().min().unwrap();
|
||||
let range = Self::MAX_LEVEL - level - 1;
|
||||
for dx in -range..=range {
|
||||
for dy in -range..=range {
|
||||
let new_pos = ticket_pos.add_raw(dx as i32, dy as i32);
|
||||
let level_from_source = level + dx.abs().max(dy.abs());
|
||||
let i = temp.entry(new_pos).or_insert(Self::MAX_LEVEL);
|
||||
*i = min(*i, level_from_source);
|
||||
}
|
||||
}
|
||||
}
|
||||
if temp.len() != self.pos_level.len() {
|
||||
debug!("temp: \n{temp:?}");
|
||||
debug!("pos_level: \n{:?}", self.pos_level);
|
||||
}
|
||||
assert_eq!(temp.len(), self.pos_level.len());
|
||||
for val in &temp {
|
||||
if val != self.pos_level.get_key_value(val.0).unwrap() {
|
||||
Self::dump_level_debug(
|
||||
&self.high_priority,
|
||||
&self.pos_level,
|
||||
val.0.x - 40,
|
||||
val.0.x + 40,
|
||||
val.0.y - 40,
|
||||
val.0.y + 40,
|
||||
);
|
||||
}
|
||||
assert_eq!(val, self.pos_level.get_key_value(val.0).unwrap());
|
||||
}
|
||||
true
|
||||
}
|
||||
pub fn dump_level_debug(
|
||||
pri: &[ChunkPos],
|
||||
map: &ChunkLevel,
|
||||
sx: i32,
|
||||
tx: i32,
|
||||
sy: i32,
|
||||
ty: i32,
|
||||
) {
|
||||
debug!("high_priority {pri:?}");
|
||||
|
||||
let mut header = "X/Y".to_string();
|
||||
for y in sy..=ty {
|
||||
let _ = write!(header, "{y:4}");
|
||||
}
|
||||
|
||||
let grid: String = (sx..=tx)
|
||||
.map(|x| {
|
||||
let mut row = format!("{x:3}");
|
||||
let mut cols = String::new();
|
||||
for y in sy..=ty {
|
||||
let _ = write!(
|
||||
cols,
|
||||
"{:4}",
|
||||
map.get(&ChunkPos::new(x, y)).unwrap_or(&Self::MAX_LEVEL)
|
||||
);
|
||||
}
|
||||
row.push_str(&cols);
|
||||
row
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
|
||||
debug!("\nloading level:\n{header}\n{grid}");
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub const fn get_level_from_view_distance(view_distance: u8) -> i8 {
|
||||
Self::FULL_CHUNK_LEVEL - (view_distance as i8)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub const fn get_level_from_simulation_distance(simulation_distance: u8) -> i8 {
|
||||
Self::FULL_CHUNK_LEVEL - (simulation_distance as i8)
|
||||
}
|
||||
|
||||
pub fn new(sender: Arc<LevelChannel>) -> Self {
|
||||
Self {
|
||||
is_priority_dirty: true,
|
||||
pos_level: ChunkLevel::default(),
|
||||
change: HashMapType::default(),
|
||||
ticket: HashMapType::default(),
|
||||
high_priority: Vec::new(),
|
||||
sender,
|
||||
increase_update: VecDeque::default(),
|
||||
decrease_update: VecDeque::default(),
|
||||
cache: LevelCache::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn send_change(&mut self) {
|
||||
// debug!("sending change");
|
||||
if !self.change.is_empty() {
|
||||
let mut tmp = HashMapType::default();
|
||||
swap(&mut tmp, &mut self.change);
|
||||
if self.is_priority_dirty {
|
||||
self.is_priority_dirty = false;
|
||||
self.sender
|
||||
.set_both((tmp, self.pos_level.clone()), self.high_priority.clone());
|
||||
} else {
|
||||
self.sender.set_level((tmp, self.pos_level.clone()));
|
||||
}
|
||||
}
|
||||
if self.is_priority_dirty {
|
||||
self.is_priority_dirty = false;
|
||||
self.sender.set_priority(self.high_priority.clone());
|
||||
}
|
||||
}
|
||||
|
||||
fn run_increase_update(&mut self) {
|
||||
while let Some((pos, level)) = self.increase_update.pop_front() {
|
||||
debug_assert!(level < Self::MAX_LEVEL);
|
||||
if level > self.cache.get(&self.pos_level, pos) {
|
||||
continue;
|
||||
}
|
||||
debug_assert_eq!(level, self.cache.get(&self.pos_level, pos));
|
||||
let spread_level = level + 1;
|
||||
if spread_level >= Self::MAX_LEVEL {
|
||||
continue;
|
||||
}
|
||||
for dx in -1..2 {
|
||||
for dy in -1..2 {
|
||||
let new_pos = pos.add_raw(dx, dy);
|
||||
if new_pos != pos {
|
||||
self.check_then_push(new_pos, spread_level);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn check_then_push(&mut self, pos: ChunkPos, level: i8) {
|
||||
debug_assert!(level < Self::MAX_LEVEL);
|
||||
let old = self.cache.get(&self.pos_level, pos);
|
||||
if old <= level {
|
||||
return;
|
||||
}
|
||||
self.cache.set(&self.pos_level, pos, level);
|
||||
self.increase_update.push_back((pos, level));
|
||||
}
|
||||
|
||||
fn run_decrease_update(&mut self, pos: ChunkPos, range: i32) {
|
||||
while let Some((pos, level)) = self.decrease_update.pop_front() {
|
||||
debug_assert!(level < Self::MAX_LEVEL);
|
||||
let spread_level = level + 1;
|
||||
for dx in -1..2 {
|
||||
for dy in -1..2 {
|
||||
let new_pos = pos.add_raw(dx, dy);
|
||||
if new_pos == pos {
|
||||
continue;
|
||||
}
|
||||
let new_pos_level = self.cache.get(&self.pos_level, new_pos);
|
||||
if new_pos_level == Self::MAX_LEVEL {
|
||||
continue;
|
||||
}
|
||||
debug_assert!(new_pos_level <= spread_level);
|
||||
if new_pos_level == spread_level {
|
||||
self.cache.set(&self.pos_level, new_pos, Self::MAX_LEVEL);
|
||||
if spread_level < Self::MAX_LEVEL {
|
||||
self.decrease_update.push_back((new_pos, spread_level));
|
||||
}
|
||||
} else {
|
||||
self.increase_update.push_back((new_pos, new_pos_level));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (ticket_pos, levels) in &self.ticket {
|
||||
if (ticket_pos.x - pos.x).abs() <= range && (ticket_pos.y - pos.y).abs() <= range {
|
||||
let level = *levels.iter().min().unwrap();
|
||||
debug_assert!(level < Self::MAX_LEVEL);
|
||||
let old = self.cache.get(&self.pos_level, *ticket_pos);
|
||||
if old <= level {
|
||||
continue;
|
||||
}
|
||||
self.cache.set(&self.pos_level, *ticket_pos, level);
|
||||
self.increase_update.push_back((*ticket_pos, level));
|
||||
}
|
||||
}
|
||||
self.run_increase_update();
|
||||
}
|
||||
|
||||
pub fn add_force_ticket(&mut self, pos: ChunkPos) {
|
||||
// debug!("add force ticket at {pos:?}");
|
||||
self.high_priority.push(pos);
|
||||
self.is_priority_dirty = true;
|
||||
self.add_ticket(pos, Self::FULL_CHUNK_LEVEL);
|
||||
}
|
||||
pub fn remove_force_ticket(&mut self, pos: ChunkPos) {
|
||||
// debug!("remove force ticket at {pos:?}");
|
||||
let index = self
|
||||
.high_priority
|
||||
.iter()
|
||||
.find_position(|x| **x == pos)
|
||||
.unwrap()
|
||||
.0;
|
||||
self.high_priority.remove(index);
|
||||
self.is_priority_dirty = true;
|
||||
self.remove_ticket(pos, Self::FULL_CHUNK_LEVEL);
|
||||
}
|
||||
pub fn add_ticket(&mut self, pos: ChunkPos, level: i8) {
|
||||
// debug!("add ticket at {pos:?} level {level}");
|
||||
debug_assert!(level < Self::MAX_LEVEL);
|
||||
match self.ticket.entry(pos) {
|
||||
Entry::Occupied(mut vec) => {
|
||||
vec.get_mut().push(level);
|
||||
}
|
||||
Entry::Vacant(empty) => {
|
||||
empty.insert(vec![level]);
|
||||
}
|
||||
}
|
||||
|
||||
let old = *self.pos_level.get(&pos).unwrap_or(&Self::MAX_LEVEL);
|
||||
if old <= level {
|
||||
return;
|
||||
}
|
||||
self.cache.clean(pos, level);
|
||||
self.cache.set(&self.pos_level, pos, level);
|
||||
|
||||
debug_assert!(self.increase_update.is_empty());
|
||||
self.increase_update.push_back((pos, level));
|
||||
self.run_increase_update();
|
||||
self.cache.write(&mut self.pos_level, &mut self.change);
|
||||
debug_assert!(self.debug_check_error());
|
||||
}
|
||||
pub fn remove_ticket(&mut self, pos: ChunkPos, level: i8) {
|
||||
// debug!("remove ticket at {pos:?} level {level}");
|
||||
debug_assert!(level < Self::MAX_LEVEL);
|
||||
let Some(vec) = self.ticket.get_mut(&pos) else {
|
||||
// warn!("No ticket found at {pos:?}");
|
||||
return;
|
||||
};
|
||||
let Some((index, _)) = vec.iter().find_position(|x| **x == level) else {
|
||||
// warn!("No ticket found at {pos:?}");
|
||||
return;
|
||||
};
|
||||
vec.remove(index);
|
||||
match self.pos_level.entry(pos) {
|
||||
Entry::Occupied(entry) => {
|
||||
let old_level = *entry.get();
|
||||
let source = *vec.iter().min().unwrap_or(&Self::MAX_LEVEL);
|
||||
if vec.is_empty() {
|
||||
self.ticket.remove(&pos);
|
||||
}
|
||||
if level == old_level && source != level {
|
||||
self.cache.clean(pos, old_level);
|
||||
self.cache.set(&self.pos_level, pos, Self::MAX_LEVEL);
|
||||
debug_assert!(self.decrease_update.is_empty());
|
||||
self.decrease_update.push_back((pos, level));
|
||||
self.run_decrease_update(pos, (Self::MAX_LEVEL - level - 1) as i32);
|
||||
self.cache.write(&mut self.pos_level, &mut self.change);
|
||||
}
|
||||
}
|
||||
Entry::Vacant(_) => panic!(),
|
||||
}
|
||||
debug_assert!(self.debug_check_error());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[expect(clippy::print_stdout)]
|
||||
fn test() {
|
||||
let mut a = ChunkLoading::new(Arc::new(LevelChannel::new()));
|
||||
|
||||
a.add_ticket((0, 0).into(), 44);
|
||||
a.add_ticket((0, 1).into(), 44);
|
||||
a.remove_ticket((0, 0).into(), 44);
|
||||
|
||||
a.add_ticket((0, 0).into(), 30);
|
||||
a.add_ticket((0, 10).into(), 25);
|
||||
a.add_ticket((10, 10).into(), 26);
|
||||
a.add_ticket((10, 10).into(), 26);
|
||||
a.remove_ticket((0, 0).into(), 30);
|
||||
a.remove_ticket((0, 10).into(), 25);
|
||||
a.remove_ticket((10, 10).into(), 26);
|
||||
a.remove_ticket((10, 10).into(), 26);
|
||||
a.add_ticket((-72, 457).into(), 24);
|
||||
a.add_ticket((-72, 455).into(), 33);
|
||||
a.add_ticket((-72, 456).into(), 24);
|
||||
a.remove_ticket((-72, 457).into(), 24);
|
||||
a.add_ticket((-72, 455).into(), 24);
|
||||
|
||||
a.add_ticket((-59, 495).into(), 33);
|
||||
a.add_ticket((-51, 504).into(), 24);
|
||||
|
||||
a.remove_ticket((-51, 504).into(), 24);
|
||||
|
||||
let sx = -59;
|
||||
let tx = -51;
|
||||
let sy = 495;
|
||||
let ty = 504;
|
||||
{
|
||||
let mut header = "X/Y".to_string();
|
||||
for y in sy..=ty {
|
||||
let _ = write!(header, "{y:4}");
|
||||
}
|
||||
|
||||
let grid: String = (sx..=tx)
|
||||
.map(|x| {
|
||||
let mut row = format!("{x:3}");
|
||||
for y in sy..=ty {
|
||||
let level = a
|
||||
.pos_level
|
||||
.get(&ChunkPos::new(x, y))
|
||||
.unwrap_or(&ChunkLoading::MAX_LEVEL);
|
||||
|
||||
let _ = write!(row, "{level:4}");
|
||||
}
|
||||
row
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
|
||||
println!("\nloading level:\n{header}\n{grid}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
use crate::chunk::{
|
||||
ChunkData, ChunkHeightmapType, ChunkHeightmaps, ChunkLight, ChunkSections,
|
||||
palette::{BiomePalette, BlockPalette},
|
||||
};
|
||||
use crate::generation::biome_coords;
|
||||
use crate::tick::scheduler::ChunkTickScheduler;
|
||||
use pumpkin_config::lighting::LightingEngineConfig;
|
||||
use pumpkin_data::dimension::Dimension;
|
||||
use rustc_hash::FxHashMap;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64};
|
||||
|
||||
use crate::ProtoChunk;
|
||||
use crate::level::SyncChunk;
|
||||
|
||||
use pumpkin_data::chunk::ChunkStatus;
|
||||
use std::sync::Mutex;
|
||||
|
||||
#[repr(u8)]
|
||||
#[derive(Debug, Copy, Clone, Eq, Ord, PartialEq, PartialOrd)]
|
||||
pub enum StagedChunkEnum {
|
||||
None,
|
||||
/// Initial empty chunk, ready for biome population
|
||||
Empty = 1, // EMPTY STRUCTURE_STARTS STRUCTURE_REFERENCES
|
||||
/// Chunk with biomes populated, ready for noise generation
|
||||
Biomes,
|
||||
StructureStart,
|
||||
StructureReferences,
|
||||
/// Chunk with terrain noise generated, ready for surface building
|
||||
Noise,
|
||||
/// Chunk with surface built, ready for carvers
|
||||
Surface,
|
||||
/// Chunk with carvers applied, ready for features and structures
|
||||
Carvers,
|
||||
/// Chunk with features and structures, ready for lighting
|
||||
Features, // FEATURES
|
||||
/// Chunk with lighting calculated, ready for spawning
|
||||
Lighting, // INITIALIZE LIGHT
|
||||
/// Chunk with mobs spawned, ready for finalization
|
||||
Spawn, // SPAWN
|
||||
/// Fully generated chunk
|
||||
Full,
|
||||
}
|
||||
|
||||
#[expect(clippy::fallible_impl_from)]
|
||||
impl From<u8> for StagedChunkEnum {
|
||||
fn from(v: u8) -> Self {
|
||||
match v {
|
||||
1 => Self::Empty,
|
||||
2 => Self::Biomes,
|
||||
3 => Self::StructureStart,
|
||||
4 => Self::StructureReferences,
|
||||
5 => Self::Noise,
|
||||
6 => Self::Surface,
|
||||
7 => Self::Carvers,
|
||||
8 => Self::Features,
|
||||
9 => Self::Lighting,
|
||||
10 => Self::Spawn,
|
||||
11 => Self::Full,
|
||||
_ => panic!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ChunkStatus> for StagedChunkEnum {
|
||||
fn from(status: ChunkStatus) -> Self {
|
||||
match status {
|
||||
ChunkStatus::Empty => Self::Empty,
|
||||
ChunkStatus::StructureStarts => Self::StructureStart,
|
||||
ChunkStatus::StructureReferences => Self::StructureReferences,
|
||||
ChunkStatus::Biomes => Self::Biomes,
|
||||
ChunkStatus::Noise => Self::Noise,
|
||||
ChunkStatus::Surface => Self::Surface,
|
||||
ChunkStatus::Carvers => Self::Carvers,
|
||||
ChunkStatus::Features => Self::Features,
|
||||
ChunkStatus::InitializeLight | ChunkStatus::Light => Self::Lighting,
|
||||
ChunkStatus::Spawn => Self::Spawn,
|
||||
ChunkStatus::Full => Self::Full,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[expect(clippy::fallible_impl_from)]
|
||||
impl From<StagedChunkEnum> for ChunkStatus {
|
||||
fn from(status: StagedChunkEnum) -> Self {
|
||||
match status {
|
||||
StagedChunkEnum::Empty => Self::Empty,
|
||||
StagedChunkEnum::StructureStart => Self::StructureStarts,
|
||||
StagedChunkEnum::StructureReferences => Self::StructureReferences,
|
||||
StagedChunkEnum::Biomes => Self::Biomes,
|
||||
StagedChunkEnum::Noise => Self::Noise,
|
||||
StagedChunkEnum::Surface => Self::Surface,
|
||||
StagedChunkEnum::Carvers => Self::Carvers,
|
||||
StagedChunkEnum::Features => Self::Features,
|
||||
StagedChunkEnum::Lighting => Self::Light,
|
||||
StagedChunkEnum::Spawn => Self::Spawn,
|
||||
StagedChunkEnum::Full => Self::Full,
|
||||
StagedChunkEnum::None => panic!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl StagedChunkEnum {
|
||||
#[must_use]
|
||||
pub const fn level_to_stage(level: i8) -> Self {
|
||||
if level <= 43 {
|
||||
Self::Full
|
||||
} else if level <= 44 {
|
||||
Self::Spawn
|
||||
} else if level <= 45 {
|
||||
Self::Lighting
|
||||
} else if level <= 46 {
|
||||
Self::Features
|
||||
} else if level <= 47 {
|
||||
Self::Carvers
|
||||
} else if level <= 48 {
|
||||
Self::Surface
|
||||
} else {
|
||||
Self::None
|
||||
}
|
||||
}
|
||||
|
||||
/// Total number of state values (0 = None … 11 = Full).
|
||||
pub const COUNT: usize = Self::Full as usize + 1;
|
||||
pub const FULL_DEPENDENCIES: &'static [Self] = &[
|
||||
Self::Full,
|
||||
Self::Spawn,
|
||||
Self::Lighting,
|
||||
Self::Features,
|
||||
Self::Carvers,
|
||||
Self::Surface,
|
||||
];
|
||||
pub const FULL_RADIUS: i32 = 4;
|
||||
#[must_use]
|
||||
pub const fn get_direct_radius(self) -> i32 {
|
||||
// self exclude
|
||||
match self {
|
||||
Self::Features | Self::Lighting | Self::Spawn | Self::Full => 1,
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
#[must_use]
|
||||
pub const fn get_write_radius(self) -> i32 {
|
||||
// self exclude
|
||||
match self {
|
||||
Self::Features | Self::Lighting | Self::Spawn => 1,
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
#[must_use]
|
||||
pub const fn get_direct_dependencies(self) -> &'static [Self] {
|
||||
match self {
|
||||
// In vanilla StructureStart is first, but since it needs the biome in Vanilla it gets computed in StructureStart and
|
||||
// the Biome Step, this should be more efficient
|
||||
Self::Biomes => &[Self::Empty],
|
||||
Self::StructureStart => &[Self::Biomes],
|
||||
Self::StructureReferences => &[
|
||||
Self::StructureStart,
|
||||
Self::StructureStart,
|
||||
Self::StructureStart,
|
||||
Self::StructureStart,
|
||||
Self::StructureStart,
|
||||
Self::StructureStart,
|
||||
Self::StructureStart,
|
||||
Self::StructureStart,
|
||||
Self::StructureStart,
|
||||
],
|
||||
Self::Noise => &[Self::StructureReferences],
|
||||
Self::Surface => &[Self::Noise],
|
||||
Self::Carvers => &[Self::Surface],
|
||||
Self::Features => &[Self::Carvers, Self::Carvers],
|
||||
Self::Lighting => &[Self::Features, Self::Features],
|
||||
Self::Spawn => &[Self::Lighting, Self::Lighting],
|
||||
Self::Full => &[Self::Spawn, Self::Spawn],
|
||||
_ => panic!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub enum Chunk {
|
||||
Level(SyncChunk),
|
||||
Proto(Box<ProtoChunk>),
|
||||
}
|
||||
|
||||
impl Chunk {
|
||||
#[must_use]
|
||||
pub fn get_stage_id(&self) -> u8 {
|
||||
match self {
|
||||
Self::Proto(data) => data.stage_id(),
|
||||
Self::Level(_) => StagedChunkEnum::Full as u8,
|
||||
}
|
||||
}
|
||||
pub fn get_proto_chunk_mut(&mut self) -> &mut ProtoChunk {
|
||||
match self {
|
||||
Self::Level(_) => panic!("chunk isn't a ProtoChunk"),
|
||||
Self::Proto(chunk) => chunk,
|
||||
}
|
||||
}
|
||||
#[must_use]
|
||||
pub fn get_proto_chunk(&self) -> &ProtoChunk {
|
||||
match self {
|
||||
Self::Level(_) => panic!("chunk isn't a ProtoChunk"),
|
||||
Self::Proto(chunk) => chunk,
|
||||
}
|
||||
}
|
||||
|
||||
fn build_level_sections(proto_chunk: &ProtoChunk, dimension: &Dimension) -> ChunkSections {
|
||||
let total_sections = dimension.height as usize / BlockPalette::SIZE;
|
||||
let biome_min_y = biome_coords::from_block(dimension.min_y);
|
||||
let block_sections = (0..total_sections)
|
||||
.map(|section_index| {
|
||||
BlockPalette::from_fn(|x, y, z| {
|
||||
let y = section_index * BlockPalette::SIZE + y;
|
||||
proto_chunk.get_block_state_raw(x as i32, y as i32, z as i32)
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.into_boxed_slice();
|
||||
let biome_sections = (0..total_sections)
|
||||
.map(|section_index| {
|
||||
BiomePalette::from_fn(|x, y, z| {
|
||||
let y = section_index * BiomePalette::SIZE + y;
|
||||
proto_chunk.get_biome_id(x as i32, biome_min_y + y as i32, z as i32)
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.into_boxed_slice();
|
||||
|
||||
ChunkSections::from_palettes(block_sections, biome_sections, dimension.min_y)
|
||||
}
|
||||
|
||||
fn build_level_heightmaps(proto_chunk: &ProtoChunk, min_y: i32) -> ChunkHeightmaps {
|
||||
let mut heightmaps = ChunkHeightmaps::default();
|
||||
for x in 0..16 {
|
||||
for z in 0..16 {
|
||||
let source_index = x * 16 + z;
|
||||
for (heightmap_type, height) in [
|
||||
(
|
||||
ChunkHeightmapType::WorldSurface,
|
||||
proto_chunk.flat_surface_height_map[source_index],
|
||||
),
|
||||
(
|
||||
ChunkHeightmapType::MotionBlocking,
|
||||
proto_chunk.flat_motion_blocking_height_map[source_index],
|
||||
),
|
||||
(
|
||||
ChunkHeightmapType::MotionBlockingNoLeaves,
|
||||
proto_chunk.flat_motion_blocking_no_leaves_height_map[source_index],
|
||||
),
|
||||
] {
|
||||
heightmaps.set(heightmap_type, x as i32, z as i32, i32::from(height), min_y);
|
||||
}
|
||||
}
|
||||
}
|
||||
heightmaps
|
||||
}
|
||||
|
||||
pub fn upgrade_to_level_chunk(
|
||||
&mut self,
|
||||
dimension: &Dimension,
|
||||
lighting_config: &LightingEngineConfig,
|
||||
) {
|
||||
// Take ownership of the ProtoChunk by temporarily replacing with a dummy value
|
||||
// This allows us to move the light data instead of cloning it
|
||||
let proto_chunk_box = match std::mem::replace(
|
||||
self,
|
||||
Self::Level(Arc::new(ChunkData {
|
||||
section: ChunkSections::new(0, 0),
|
||||
heightmap: Mutex::default(),
|
||||
x: 0,
|
||||
z: 0,
|
||||
block_ticks: ChunkTickScheduler::default(),
|
||||
fluid_ticks: ChunkTickScheduler::default(),
|
||||
pending_block_entities: Mutex::default(),
|
||||
light_engine: Mutex::new(ChunkLight::default()),
|
||||
light_populated: AtomicBool::new(false),
|
||||
status: ChunkStatus::Empty,
|
||||
blending_data: None,
|
||||
dirty: AtomicBool::new(false),
|
||||
inhabited_time: AtomicU64::new(0),
|
||||
})),
|
||||
) {
|
||||
Self::Proto(proto) => proto,
|
||||
Self::Level(_) => panic!("Cannot upgrade a Level chunk"),
|
||||
};
|
||||
|
||||
let proto_chunk = *proto_chunk_box;
|
||||
|
||||
let sections = Self::build_level_sections(&proto_chunk, dimension);
|
||||
let heightmaps = Self::build_level_heightmaps(&proto_chunk, dimension.min_y);
|
||||
|
||||
// Move the light data instead of cloning it
|
||||
// By taking ownership of proto_chunk, we can move the light data directly
|
||||
// This prevents keeping duplicate lighting data in memory
|
||||
let light_data = proto_chunk.light;
|
||||
|
||||
// Only mark lit if past the lighting stage, and the lighting config is "default" ("full" and "dark" modes skip proper lighting)
|
||||
let is_lit = proto_chunk.stage >= StagedChunkEnum::Lighting
|
||||
&& *lighting_config == LightingEngineConfig::Default;
|
||||
|
||||
// Convert pending block entities from structure generation to actual block entities
|
||||
let mut pending_block_entities = FxHashMap::default();
|
||||
for nbt in proto_chunk.pending_block_entities {
|
||||
if let Some(x) = nbt.get_int("x")
|
||||
&& let Some(y) = nbt.get_int("y")
|
||||
&& let Some(z) = nbt.get_int("z")
|
||||
{
|
||||
pending_block_entities
|
||||
.insert(pumpkin_util::math::position::BlockPos::new(x, y, z), nbt);
|
||||
}
|
||||
}
|
||||
|
||||
let chunk = ChunkData {
|
||||
light_engine: Mutex::new(light_data),
|
||||
light_populated: AtomicBool::new(is_lit),
|
||||
section: sections,
|
||||
heightmap: Mutex::new(heightmaps),
|
||||
x: proto_chunk.x,
|
||||
z: proto_chunk.z,
|
||||
dirty: AtomicBool::new(true),
|
||||
block_ticks: ChunkTickScheduler::default(),
|
||||
fluid_ticks: ChunkTickScheduler::from_iter(proto_chunk.fluid_ticks),
|
||||
pending_block_entities: Mutex::new(pending_block_entities),
|
||||
status: proto_chunk.stage.into(),
|
||||
blending_data: proto_chunk.blending_data,
|
||||
inhabited_time: AtomicU64::new(0),
|
||||
};
|
||||
|
||||
*self = Self::Level(Arc::new(chunk));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
use super::ChunkPos;
|
||||
use super::chunk_state::StagedChunkEnum;
|
||||
use slotmap::{Key, SlotMap, new_key_type};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Node {
|
||||
pub pos: ChunkPos,
|
||||
pub stage: StagedChunkEnum,
|
||||
pub in_degree: u32,
|
||||
pub in_queue: bool,
|
||||
pub in_flight: bool,
|
||||
pub edge: EdgeKey,
|
||||
}
|
||||
|
||||
impl Node {
|
||||
#[must_use]
|
||||
pub fn new(pos: ChunkPos, stage: StagedChunkEnum) -> Self {
|
||||
Self {
|
||||
pos,
|
||||
stage,
|
||||
in_degree: 0,
|
||||
in_queue: false,
|
||||
in_flight: false,
|
||||
edge: EdgeKey::null(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Edge {
|
||||
pub to: NodeKey,
|
||||
pub next: EdgeKey,
|
||||
}
|
||||
|
||||
impl Edge {
|
||||
#[must_use]
|
||||
pub const fn new(to: NodeKey, next: EdgeKey) -> Self {
|
||||
Self { to, next }
|
||||
}
|
||||
}
|
||||
|
||||
new_key_type! { pub struct NodeKey; }
|
||||
new_key_type! { pub struct EdgeKey; }
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct DAG {
|
||||
pub nodes: SlotMap<NodeKey, Node>,
|
||||
pub edges: SlotMap<EdgeKey, Edge>,
|
||||
}
|
||||
|
||||
impl DAG {
|
||||
pub fn fast_drop_node(&mut self, node: NodeKey) {
|
||||
let mut edge = self.nodes.remove(node).unwrap().edge;
|
||||
// debug!("drop node {node:?}");
|
||||
while !edge.is_null() {
|
||||
edge = self.edges.remove(edge).unwrap().next;
|
||||
}
|
||||
}
|
||||
pub fn add_edge(&mut self, from: NodeKey, to: NodeKey) {
|
||||
// Ensure both nodes exist before adding edge
|
||||
if !self.nodes.contains_key(to) || !self.nodes.contains_key(from) {
|
||||
return;
|
||||
}
|
||||
if let Some(node) = self.nodes.get_mut(to) {
|
||||
node.in_degree += 1;
|
||||
}
|
||||
if let Some(node) = self.nodes.get_mut(from) {
|
||||
let edge = &mut node.edge;
|
||||
*edge = self.edges.insert(Edge::new(to, *edge));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,389 @@
|
||||
use pumpkin_data::dimension::Dimension;
|
||||
|
||||
use crate::ProtoChunk;
|
||||
use crate::generation::generator::WorldGenerator;
|
||||
use crate::world::WorldPortalExt;
|
||||
use pumpkin_config::lighting::LightingEngineConfig;
|
||||
|
||||
use super::{Cache, Chunk, StagedChunkEnum};
|
||||
|
||||
pub fn generate_single_chunk(
|
||||
dimension: &Dimension,
|
||||
biome_mixer_seed: i64,
|
||||
generator: &WorldGenerator,
|
||||
block_registry: &dyn WorldPortalExt,
|
||||
chunk_x: i32,
|
||||
chunk_z: i32,
|
||||
target_stage: StagedChunkEnum,
|
||||
) -> Chunk {
|
||||
generate_single_chunk_with_radius(
|
||||
dimension,
|
||||
biome_mixer_seed,
|
||||
generator,
|
||||
block_registry,
|
||||
chunk_x,
|
||||
chunk_z,
|
||||
target_stage,
|
||||
target_stage.get_direct_radius(),
|
||||
)
|
||||
}
|
||||
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
pub fn generate_single_chunk_with_radius(
|
||||
_dimension: &Dimension,
|
||||
_biome_mixer_seed: i64,
|
||||
generator: &WorldGenerator,
|
||||
block_registry: &dyn WorldPortalExt,
|
||||
chunk_x: i32,
|
||||
chunk_z: i32,
|
||||
target_stage: StagedChunkEnum,
|
||||
radius: i32,
|
||||
) -> Chunk {
|
||||
let mut cache = Cache::new(chunk_x - radius, chunk_z - radius, radius * 2 + 1);
|
||||
|
||||
for dx in -radius..=radius {
|
||||
for dz in -radius..=radius {
|
||||
let new_x = chunk_x + dx;
|
||||
let new_z = chunk_z + dz;
|
||||
|
||||
let proto_chunk = Box::new(ProtoChunk::new(new_x, new_z, generator));
|
||||
|
||||
cache.chunks.push(Chunk::Proto(proto_chunk));
|
||||
}
|
||||
}
|
||||
|
||||
let stages = [
|
||||
StagedChunkEnum::Biomes,
|
||||
StagedChunkEnum::StructureStart,
|
||||
StagedChunkEnum::StructureReferences,
|
||||
StagedChunkEnum::Noise,
|
||||
StagedChunkEnum::Surface,
|
||||
StagedChunkEnum::Carvers,
|
||||
StagedChunkEnum::Features,
|
||||
StagedChunkEnum::Lighting,
|
||||
StagedChunkEnum::Spawn,
|
||||
StagedChunkEnum::Full,
|
||||
];
|
||||
|
||||
for &stage in &stages {
|
||||
if stage as u8 > target_stage as u8 {
|
||||
break;
|
||||
}
|
||||
|
||||
if matches!(
|
||||
stage,
|
||||
StagedChunkEnum::Biomes
|
||||
| StagedChunkEnum::StructureStart
|
||||
| StagedChunkEnum::StructureReferences
|
||||
) {
|
||||
cache.advance_all(
|
||||
stage,
|
||||
generator,
|
||||
block_registry,
|
||||
&LightingEngineConfig::Default,
|
||||
);
|
||||
} else {
|
||||
cache.advance(
|
||||
stage,
|
||||
generator,
|
||||
block_registry,
|
||||
&LightingEngineConfig::Default,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let mid = ((cache.size * cache.size) >> 1) as usize;
|
||||
cache.chunks.swap_remove(mid)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::biome::hash_seed;
|
||||
use crate::chunk::ChunkHeightmapType;
|
||||
use crate::chunk_system::Chunk;
|
||||
use crate::chunk_system::{
|
||||
StagedChunkEnum, generate_single_chunk, generation::generate_single_chunk_with_radius,
|
||||
};
|
||||
use crate::generation::get_world_gen;
|
||||
use crate::world::WorldPortalExt;
|
||||
use pumpkin_data::BlockStateId;
|
||||
use pumpkin_data::dimension::Dimension;
|
||||
use pumpkin_util::world_seed::Seed;
|
||||
use std::sync::Arc;
|
||||
|
||||
struct BlockRegistry;
|
||||
impl WorldPortalExt for BlockRegistry {
|
||||
fn can_place_at(
|
||||
&self,
|
||||
_block: &pumpkin_data::Block,
|
||||
_state: &pumpkin_data::BlockState,
|
||||
_block_accessor: &dyn crate::world::BlockAccessor,
|
||||
_block_pos: &pumpkin_util::math::position::BlockPos,
|
||||
) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn mirror(
|
||||
&self,
|
||||
block: &pumpkin_data::Block,
|
||||
state_id: BlockStateId,
|
||||
mirror: pumpkin_data::Mirror,
|
||||
) -> &'static pumpkin_data::BlockState {
|
||||
block.mirror(state_id, mirror)
|
||||
}
|
||||
|
||||
fn rotate(
|
||||
&self,
|
||||
block: &pumpkin_data::Block,
|
||||
state_id: BlockStateId,
|
||||
rotation: pumpkin_data::Rotation,
|
||||
) -> &'static pumpkin_data::BlockState {
|
||||
block.rotate(state_id, rotation)
|
||||
}
|
||||
|
||||
fn spawn_mobs_for_chunk_generation(
|
||||
&self,
|
||||
_cache: &mut dyn crate::generation::proto_chunk::GenerationCache,
|
||||
_biome: &'static pumpkin_data::chunk::Biome,
|
||||
_chunk_x: i32,
|
||||
_chunk_z: i32,
|
||||
) {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generate_chunk_should_return() {
|
||||
let dimension = Dimension::OVERWORLD;
|
||||
let seed = Seed(42);
|
||||
let block_registry = Arc::new(BlockRegistry);
|
||||
let world_gen = get_world_gen(seed, dimension.clone(), false, Vec::new(), String::new());
|
||||
let biome_mixer_seed = hash_seed(world_gen.seed());
|
||||
|
||||
let chunk = generate_single_chunk(
|
||||
&dimension,
|
||||
biome_mixer_seed,
|
||||
&world_gen,
|
||||
block_registry.as_ref(),
|
||||
0,
|
||||
0,
|
||||
StagedChunkEnum::Full,
|
||||
);
|
||||
let Chunk::Level(chunk) = chunk else {
|
||||
panic!("full generation must return a level chunk");
|
||||
};
|
||||
let recalculated = chunk.calculate_heightmap();
|
||||
let generated = chunk.heightmap.lock().unwrap();
|
||||
for x in 0..16 {
|
||||
for z in 0..16 {
|
||||
for heightmap_type in [
|
||||
ChunkHeightmapType::WorldSurface,
|
||||
ChunkHeightmapType::MotionBlocking,
|
||||
ChunkHeightmapType::MotionBlockingNoLeaves,
|
||||
] {
|
||||
assert_eq!(
|
||||
generated.get(heightmap_type, x, z, chunk.section.min_y),
|
||||
recalculated.get(heightmap_type, x, z, chunk.section.min_y),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn configured_seed_generates_vanilla_ancient_city_chunk() {
|
||||
let dimension = Dimension::OVERWORLD;
|
||||
let seed = Seed(1_782_124_772_053_846_960);
|
||||
let block_registry = Arc::new(BlockRegistry);
|
||||
let world_gen = get_world_gen(seed, dimension.clone(), false, Vec::new(), String::new());
|
||||
let biome_mixer_seed = hash_seed(world_gen.seed());
|
||||
|
||||
let chunk = generate_single_chunk(
|
||||
&dimension,
|
||||
biome_mixer_seed,
|
||||
&world_gen,
|
||||
block_registry.as_ref(),
|
||||
31,
|
||||
-12,
|
||||
StagedChunkEnum::Features,
|
||||
);
|
||||
let super::Chunk::Proto(chunk) = chunk else {
|
||||
panic!("features stage should return a proto chunk");
|
||||
};
|
||||
|
||||
let mut city_blocks = 0;
|
||||
let mut jigsaw_blocks = 0;
|
||||
for x in 496..512 {
|
||||
for z in -192..-176 {
|
||||
for y in -64..320 {
|
||||
let block = chunk
|
||||
.get_block_state(&pumpkin_util::math::vector3::Vector3::new(x, y, z))
|
||||
.to_block_id();
|
||||
if [
|
||||
pumpkin_data::Block::DEEPSLATE_BRICKS.id,
|
||||
pumpkin_data::Block::POLISHED_DEEPSLATE.id,
|
||||
pumpkin_data::Block::REINFORCED_DEEPSLATE.id,
|
||||
pumpkin_data::Block::SCULK.id,
|
||||
]
|
||||
.contains(&block)
|
||||
{
|
||||
city_blocks += 1;
|
||||
}
|
||||
if block == pumpkin_data::Block::JIGSAW.id {
|
||||
jigsaw_blocks += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
assert!(
|
||||
city_blocks > 0,
|
||||
"reference chunk contains no Ancient City blocks"
|
||||
);
|
||||
assert_eq!(jigsaw_blocks, 0, "jigsaw blocks were not replaced");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seed_zero_generates_the_vanilla_pillager_outpost_chunk() {
|
||||
let dimension = Dimension::OVERWORLD;
|
||||
let seed = Seed(1_782_124_772_053_846_960);
|
||||
let block_registry = Arc::new(BlockRegistry);
|
||||
let world_gen = get_world_gen(seed, dimension.clone(), false, Vec::new(), String::new());
|
||||
let biome_mixer_seed = hash_seed(world_gen.seed());
|
||||
|
||||
let chunk = generate_single_chunk_with_radius(
|
||||
&dimension,
|
||||
biome_mixer_seed,
|
||||
&world_gen,
|
||||
block_registry.as_ref(),
|
||||
73,
|
||||
-82,
|
||||
StagedChunkEnum::Spawn,
|
||||
16,
|
||||
);
|
||||
let super::Chunk::Proto(chunk) = chunk else {
|
||||
panic!("spawn stage should return a proto chunk");
|
||||
};
|
||||
let mut outpost_blocks = 0;
|
||||
let mut jigsaw_blocks = 0;
|
||||
for x in 1168..1184 {
|
||||
for z in -1328..-1312 {
|
||||
for y in -64..320 {
|
||||
let block = chunk
|
||||
.get_block_state(&pumpkin_util::math::vector3::Vector3::new(x, y, z))
|
||||
.to_block_id();
|
||||
if [
|
||||
pumpkin_data::Block::DARK_OAK_LOG.id,
|
||||
pumpkin_data::Block::DARK_OAK_PLANKS.id,
|
||||
pumpkin_data::Block::DARK_OAK_FENCE.id,
|
||||
]
|
||||
.contains(&block)
|
||||
{
|
||||
outpost_blocks += 1;
|
||||
}
|
||||
if block == pumpkin_data::Block::JIGSAW.id {
|
||||
jigsaw_blocks += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
assert!(
|
||||
outpost_blocks > 0,
|
||||
"reference chunk contains no outpost blocks"
|
||||
);
|
||||
assert_eq!(jigsaw_blocks, 0, "jigsaw blocks were not replaced");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fixed_seed_generates_vanilla_end_ship_chunk() {
|
||||
// Vanilla 26.2 places this seed's ship in chunk (-306, -275).
|
||||
let dimension = Dimension::THE_END;
|
||||
let seed = Seed(12_345);
|
||||
let block_registry = Arc::new(BlockRegistry);
|
||||
let world_gen = get_world_gen(seed, dimension.clone(), false, Vec::new(), String::new());
|
||||
let biome_mixer_seed = hash_seed(world_gen.seed());
|
||||
let chunk = generate_single_chunk_with_radius(
|
||||
&dimension,
|
||||
biome_mixer_seed,
|
||||
&world_gen,
|
||||
block_registry.as_ref(),
|
||||
-306,
|
||||
-275,
|
||||
StagedChunkEnum::Features,
|
||||
16,
|
||||
);
|
||||
let Chunk::Proto(chunk) = chunk else {
|
||||
panic!("features stage should return a proto chunk");
|
||||
};
|
||||
let mut non_air = 0;
|
||||
for y in 123..=146 {
|
||||
for x in -4896..=-4881 {
|
||||
for z in -4405..=-4393 {
|
||||
let state =
|
||||
chunk.get_block_state(&pumpkin_util::math::vector3::Vector3::new(x, y, z));
|
||||
non_air += usize::from(!state.to_state().is_air());
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(non_air, 14);
|
||||
assert!(chunk.pending_block_entities.iter().any(|nbt| {
|
||||
nbt.get_string("id") == Some("minecraft:skull")
|
||||
&& nbt.get_int("x") == Some(-4888)
|
||||
&& nbt.get_int("y") == Some(131)
|
||||
&& nbt.get_int("z") == Some(-4399)
|
||||
}));
|
||||
assert_eq!(
|
||||
chunk
|
||||
.pending_block_entities
|
||||
.iter()
|
||||
.filter(
|
||||
|nbt| nbt.get_string("LootTable") == Some("minecraft:chests/end_city_treasure")
|
||||
)
|
||||
.count(),
|
||||
2
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pillager_outpost_features_shape_ground_at_vanilla_height() {
|
||||
let dimension = Dimension::OVERWORLD;
|
||||
let seed = Seed(1_782_124_772_053_846_960);
|
||||
let block_registry = Arc::new(BlockRegistry);
|
||||
let world_gen = get_world_gen(seed, dimension.clone(), false, Vec::new(), String::new());
|
||||
let biome_mixer_seed = hash_seed(world_gen.seed());
|
||||
|
||||
let chunk = generate_single_chunk(
|
||||
&dimension,
|
||||
biome_mixer_seed,
|
||||
&world_gen,
|
||||
block_registry.as_ref(),
|
||||
73,
|
||||
-82,
|
||||
StagedChunkEnum::Features,
|
||||
);
|
||||
let super::Chunk::Proto(chunk) = chunk else {
|
||||
panic!("features stage should return a proto chunk");
|
||||
};
|
||||
|
||||
for (x, y, z) in [(1173, 70, -1311), (1173, 70, -1305)] {
|
||||
let state = chunk.get_block_state(&pumpkin_util::math::vector3::Vector3::new(x, y, z));
|
||||
assert_eq!(state.to_block_id(), pumpkin_data::Block::GRASS_BLOCK.id);
|
||||
}
|
||||
|
||||
let cage_chunk = generate_single_chunk(
|
||||
&dimension,
|
||||
biome_mixer_seed,
|
||||
&world_gen,
|
||||
block_registry.as_ref(),
|
||||
73,
|
||||
-84,
|
||||
StagedChunkEnum::Features,
|
||||
);
|
||||
let super::Chunk::Proto(cage_chunk) = cage_chunk else {
|
||||
panic!("features stage should return a proto chunk");
|
||||
};
|
||||
let state =
|
||||
cage_chunk.get_block_state(&pumpkin_util::math::vector3::Vector3::new(1183, 68, -1330));
|
||||
assert_eq!(state.to_block_id(), pumpkin_data::Block::GRASS_BLOCK.id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,514 @@
|
||||
use super::chunk_state::{Chunk, StagedChunkEnum};
|
||||
use crate::ProtoChunk;
|
||||
use crate::chunk::ChunkHeightmapType;
|
||||
use crate::generation::generator;
|
||||
use crate::generation::height_limit::HeightLimitView;
|
||||
use crate::generation::proto_chunk::GenerationCache;
|
||||
use crate::world::{BlockAccessor, WorldPortalExt};
|
||||
use pumpkin_config::lighting::LightingEngineConfig;
|
||||
use pumpkin_data::biome::Biome;
|
||||
use pumpkin_data::block_properties::is_air;
|
||||
use pumpkin_data::fluid::{Fluid, FluidState};
|
||||
use pumpkin_data::{Block, BlockState, BlockStateId};
|
||||
use pumpkin_nbt::compound::NbtCompound;
|
||||
use pumpkin_util::HeightMap;
|
||||
use pumpkin_util::math::position::BlockPos;
|
||||
use pumpkin_util::math::vector3::Vector3;
|
||||
use tracing::debug;
|
||||
|
||||
pub struct Cache {
|
||||
pub x: i32,
|
||||
pub z: i32,
|
||||
pub size: i32,
|
||||
pub chunks: Vec<Chunk>,
|
||||
}
|
||||
|
||||
impl HeightLimitView for Cache {
|
||||
fn height(&self) -> u16 {
|
||||
let mid = ((self.size * self.size) >> 1) as usize;
|
||||
match &self.chunks[mid] {
|
||||
Chunk::Proto(chunk) => chunk.height(),
|
||||
Chunk::Level(_) => panic!(),
|
||||
}
|
||||
}
|
||||
|
||||
fn bottom_y(&self) -> i8 {
|
||||
let mid = ((self.size * self.size) >> 1) as usize;
|
||||
match &self.chunks[mid] {
|
||||
Chunk::Proto(chunk) => chunk.bottom_y(),
|
||||
Chunk::Level(_) => panic!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl BlockAccessor for Cache {
|
||||
fn get_block(&self, position: &BlockPos) -> &'static Block {
|
||||
GenerationCache::get_block_state(self, &position.0).to_block()
|
||||
}
|
||||
|
||||
fn get_block_state(&self, position: &BlockPos) -> &'static BlockState {
|
||||
GenerationCache::get_block_state(self, &position.0).to_state()
|
||||
}
|
||||
|
||||
fn get_block_state_id(&self, position: &BlockPos) -> BlockStateId {
|
||||
GenerationCache::get_block_state(self, &position.0)
|
||||
}
|
||||
|
||||
fn get_block_and_state(&self, position: &BlockPos) -> (&'static Block, &'static BlockState) {
|
||||
let id = GenerationCache::get_block_state(self, &position.0);
|
||||
BlockState::from_id_with_block(id)
|
||||
}
|
||||
}
|
||||
|
||||
impl GenerationCache for Cache {
|
||||
fn get_chunk_mut(&mut self, chunk_x: i32, chunk_z: i32) -> Option<&mut ProtoChunk> {
|
||||
let dx = chunk_x - self.x;
|
||||
let dz = chunk_z - self.z;
|
||||
|
||||
if dx < 0 || dx >= self.size || dz < 0 || dz >= self.size {
|
||||
return None;
|
||||
}
|
||||
|
||||
match &mut self.chunks[(dx * self.size + dz) as usize] {
|
||||
Chunk::Proto(chunk) => Some(chunk),
|
||||
Chunk::Level(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn get_chunk(&self, chunk_x: i32, chunk_z: i32) -> Option<&ProtoChunk> {
|
||||
let dx = chunk_x - self.x;
|
||||
let dz = chunk_z - self.z;
|
||||
|
||||
if dx < 0 || dx >= self.size || dz < 0 || dz >= self.size {
|
||||
return None;
|
||||
}
|
||||
|
||||
match &self.chunks[(dx * self.size + dz) as usize] {
|
||||
Chunk::Proto(chunk) => Some(chunk),
|
||||
Chunk::Level(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn try_get_proto_chunk(&self, chunk_x: i32, chunk_z: i32) -> Option<&ProtoChunk> {
|
||||
let dx = chunk_x - self.x;
|
||||
let dz = chunk_z - self.z;
|
||||
|
||||
if dx < 0 || dx >= self.size || dz < 0 || dz >= self.size {
|
||||
return None;
|
||||
}
|
||||
|
||||
match &self.chunks[(dx * self.size + dz) as usize] {
|
||||
Chunk::Proto(chunk) => Some(chunk),
|
||||
Chunk::Level(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn get_center_chunk(&self) -> &ProtoChunk {
|
||||
let mid = ((self.size * self.size) >> 1) as usize;
|
||||
self.chunks[mid].get_proto_chunk()
|
||||
}
|
||||
|
||||
fn get_center_chunk_mut(&mut self) -> &mut ProtoChunk {
|
||||
let mid = ((self.size * self.size) >> 1) as usize;
|
||||
self.chunks[mid].get_proto_chunk_mut()
|
||||
}
|
||||
|
||||
fn get_fluid_and_fluid_state(&self, pos: &Vector3<i32>) -> (Fluid, FluidState) {
|
||||
let id = GenerationCache::get_block_state(self, pos);
|
||||
|
||||
let Some(fluid) = Fluid::from_state_id(id) else {
|
||||
let block = Block::from_state_id(id);
|
||||
if let Some(properties) = block.properties(id) {
|
||||
for (name, value) in properties.to_props() {
|
||||
if name == "waterlogged" {
|
||||
if value == "true" {
|
||||
let fluid = Fluid::FLOWING_WATER;
|
||||
let state = fluid.states[0].clone();
|
||||
return (fluid, state);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let fluid = Fluid::EMPTY;
|
||||
let state = fluid.states[0].clone();
|
||||
|
||||
return (fluid, state);
|
||||
};
|
||||
|
||||
//let state = fluid.get_state(id);
|
||||
let state = fluid.states[0].clone();
|
||||
|
||||
(fluid.clone(), state)
|
||||
}
|
||||
|
||||
fn get_block_state(&self, pos: &Vector3<i32>) -> BlockStateId {
|
||||
let dx = (pos.x >> 4) - self.x;
|
||||
let dz = (pos.z >> 4) - self.z;
|
||||
// debug_assert!(dx < self.size && dz < self.size);
|
||||
// debug_assert!(dx >= 0 && dz >= 0);
|
||||
if !(dx < self.size && dz < self.size && dx >= 0 && dz >= 0) {
|
||||
// breakpoint here
|
||||
debug!(
|
||||
"illegal get_block_state {pos:?} cache pos ({}, {}) size {}",
|
||||
self.x, self.z, self.size
|
||||
);
|
||||
return BlockStateId::AIR;
|
||||
}
|
||||
match &self.chunks[(dx * self.size + dz) as usize] {
|
||||
Chunk::Level(data) => data
|
||||
.section
|
||||
.get_block_absolute_y((pos.x & 15) as usize, pos.y, (pos.z & 15) as usize)
|
||||
.unwrap_or(BlockStateId::AIR),
|
||||
|
||||
Chunk::Proto(data) => data.get_block_state(pos),
|
||||
}
|
||||
}
|
||||
fn set_block_state(&mut self, pos: &Vector3<i32>, block_state: &BlockState) {
|
||||
let dx = (pos.x >> 4) - self.x;
|
||||
let dz = (pos.z >> 4) - self.z;
|
||||
// debug_assert!(dx < self.size && dz < self.size);
|
||||
// debug_assert!(dx >= 0 && dz >= 0);
|
||||
if !(dx < self.size && dz < self.size && dx >= 0 && dz >= 0) {
|
||||
// breakpoint here
|
||||
debug!(
|
||||
"illegal set_block_state {pos:?} cache pos ({}, {}) size {}",
|
||||
self.x, self.z, self.size
|
||||
);
|
||||
return;
|
||||
}
|
||||
match &mut self.chunks[(dx * self.size + dz) as usize] {
|
||||
Chunk::Level(data) => {
|
||||
data.set_block_absolute_y(
|
||||
(pos.x & 15) as usize,
|
||||
pos.y,
|
||||
(pos.z & 15) as usize,
|
||||
block_state.id,
|
||||
);
|
||||
}
|
||||
Chunk::Proto(data) => {
|
||||
data.set_block_state(pos.x, pos.y, pos.z, block_state);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn add_block_entity(&mut self, pos: &Vector3<i32>, nbt: NbtCompound) {
|
||||
let dx = (pos.x >> 4) - self.x;
|
||||
let dz = (pos.z >> 4) - self.z;
|
||||
if !(dx < self.size && dz < self.size && dx >= 0 && dz >= 0) {
|
||||
debug!(
|
||||
"illegal add_block_entity {pos:?} cache pos ({}, {}) size {}",
|
||||
self.x, self.z, self.size
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
match &mut self.chunks[(dx * self.size + dz) as usize] {
|
||||
Chunk::Level(_) => {
|
||||
debug!("add_block_entity on non-proto chunk at {pos:?}");
|
||||
}
|
||||
Chunk::Proto(data) => {
|
||||
data.add_block_entity(nbt);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn get_top_y(&self, heightmap: &HeightMap, x: i32, z: i32) -> i32 {
|
||||
match heightmap {
|
||||
HeightMap::WorldSurfaceWg | HeightMap::WorldSurface => {
|
||||
self.top_block_height_exclusive(x, z)
|
||||
}
|
||||
HeightMap::OceanFloorWg | HeightMap::OceanFloor => {
|
||||
self.ocean_floor_height_exclusive(x, z)
|
||||
}
|
||||
HeightMap::MotionBlocking => self.top_motion_blocking_block_height_exclusive(x, z),
|
||||
HeightMap::MotionBlockingNoLeaves => {
|
||||
self.top_motion_blocking_block_no_leaves_height_exclusive(x, z)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn top_motion_blocking_block_height_exclusive(&self, x: i32, z: i32) -> i32 {
|
||||
let dx = (x >> 4) - self.x;
|
||||
let dy = (z >> 4) - self.z;
|
||||
debug_assert!(dx < self.size && dy < self.size);
|
||||
debug_assert!(dx >= 0 && dy >= 0);
|
||||
match &self.chunks[(dx * self.size + dy) as usize] {
|
||||
Chunk::Level(data) => {
|
||||
let heightmap = data.heightmap.lock().unwrap();
|
||||
let min_y = data.section.min_y;
|
||||
|
||||
heightmap.get(ChunkHeightmapType::MotionBlocking, x, z, min_y)
|
||||
}
|
||||
Chunk::Proto(data) => data.top_motion_blocking_block_height_exclusive(x, z),
|
||||
}
|
||||
}
|
||||
|
||||
fn top_motion_blocking_block_no_leaves_height_exclusive(&self, x: i32, z: i32) -> i32 {
|
||||
let dx = (x >> 4) - self.x;
|
||||
let dy = (z >> 4) - self.z;
|
||||
debug_assert!(dx < self.size && dy < self.size);
|
||||
debug_assert!(dx >= 0 && dy >= 0);
|
||||
match &self.chunks[(dx * self.size + dy) as usize] {
|
||||
Chunk::Level(data) => {
|
||||
let heightmap = data.heightmap.lock().unwrap();
|
||||
let min_y = data.section.min_y;
|
||||
heightmap.get(ChunkHeightmapType::MotionBlockingNoLeaves, x, z, min_y)
|
||||
}
|
||||
Chunk::Proto(data) => data.top_motion_blocking_block_no_leaves_height_exclusive(x, z),
|
||||
}
|
||||
}
|
||||
|
||||
fn top_block_height_exclusive(&self, x: i32, z: i32) -> i32 {
|
||||
let dx = (x >> 4) - self.x;
|
||||
let dy = (z >> 4) - self.z;
|
||||
debug_assert!(dx < self.size && dy < self.size);
|
||||
debug_assert!(dx >= 0 && dy >= 0);
|
||||
match &self.chunks[(dx * self.size + dy) as usize] {
|
||||
Chunk::Level(data) => {
|
||||
let heightmap = data.heightmap.lock().unwrap();
|
||||
let min_y = data.section.min_y;
|
||||
heightmap.get(ChunkHeightmapType::WorldSurface, x, z, min_y) // can we return this?
|
||||
}
|
||||
Chunk::Proto(data) => data.top_block_height_exclusive(x, z),
|
||||
}
|
||||
}
|
||||
|
||||
fn ocean_floor_height_exclusive(&self, x: i32, z: i32) -> i32 {
|
||||
let dx = (x >> 4) - self.x;
|
||||
let dy = (z >> 4) - self.z;
|
||||
if dx < 0 || dy < 0 || dx >= self.size || dy >= self.size {
|
||||
return 0;
|
||||
}
|
||||
match &self.chunks[(dx * self.size + dy) as usize] {
|
||||
Chunk::Level(_data) => {
|
||||
0 // todo missing
|
||||
}
|
||||
Chunk::Proto(data) => data.ocean_floor_height_exclusive(x, z),
|
||||
}
|
||||
}
|
||||
|
||||
fn get_biome_for_terrain_gen(&self, x: i32, y: i32, z: i32) -> &'static Biome {
|
||||
let dx = (x >> 4) - self.x;
|
||||
let dy = (z >> 4) - self.z;
|
||||
let (dx, dy) = if dx < 0 || dy < 0 || dx >= self.size || dy >= self.size {
|
||||
// Position is outside the cache — fall back to the centre chunk's biome
|
||||
let mid = self.size / 2;
|
||||
(mid, mid)
|
||||
} else {
|
||||
(dx, dy)
|
||||
};
|
||||
match &self.chunks[(dx * self.size + dy) as usize] {
|
||||
Chunk::Level(data) => {
|
||||
// Could this happen?
|
||||
Biome::from_id(
|
||||
data.section
|
||||
.get_rough_biome_absolute_y((x & 15) as usize, y, (z & 15) as usize)
|
||||
.unwrap_or(0),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
Chunk::Proto(data) => data.get_terrain_gen_biome(x, y, z),
|
||||
}
|
||||
}
|
||||
|
||||
fn get_blending_data(
|
||||
&self,
|
||||
chunk_x: i32,
|
||||
chunk_z: i32,
|
||||
) -> Option<&crate::generation::blender::blending_data::BlendingData> {
|
||||
let dx = chunk_x - self.x;
|
||||
let dz = chunk_z - self.z;
|
||||
|
||||
if dx < 0 || dx >= self.size || dz < 0 || dz >= self.size {
|
||||
return None;
|
||||
}
|
||||
|
||||
match &self.chunks[(dx * self.size + dz) as usize] {
|
||||
Chunk::Proto(chunk) => chunk.blending_data.as_ref(),
|
||||
Chunk::Level(data) => data.blending_data.as_ref(),
|
||||
}
|
||||
}
|
||||
|
||||
fn is_air(&self, local_pos: &Vector3<i32>) -> bool {
|
||||
is_air(GenerationCache::get_block_state(self, local_pos))
|
||||
}
|
||||
}
|
||||
|
||||
impl Cache {
|
||||
pub fn advance_all(
|
||||
&mut self,
|
||||
stage: StagedChunkEnum,
|
||||
generator: &generator::WorldGenerator,
|
||||
block_registry: &dyn WorldPortalExt,
|
||||
lighting_config: &LightingEngineConfig,
|
||||
) {
|
||||
for index in 0..self.chunks.len() {
|
||||
self.advance_index(index, stage, generator, block_registry, lighting_config);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn advance_index(
|
||||
&mut self,
|
||||
index: usize,
|
||||
stage: StagedChunkEnum,
|
||||
generator: &generator::WorldGenerator,
|
||||
_block_registry: &dyn WorldPortalExt,
|
||||
_lighting_config: &LightingEngineConfig,
|
||||
) {
|
||||
match &self.chunks[index] {
|
||||
Chunk::Level(_) => return,
|
||||
Chunk::Proto(chunk) if chunk.stage >= stage => return,
|
||||
Chunk::Proto(_) => {}
|
||||
}
|
||||
match stage {
|
||||
StagedChunkEnum::Empty => panic!("empty stage"),
|
||||
StagedChunkEnum::StructureStart => match generator {
|
||||
generator::WorldGenerator::Noise(noise_gen) => {
|
||||
self.chunks[index]
|
||||
.get_proto_chunk_mut()
|
||||
.set_structure_starts(noise_gen);
|
||||
}
|
||||
generator::WorldGenerator::Flat(_) => {}
|
||||
},
|
||||
StagedChunkEnum::StructureReferences => match generator {
|
||||
generator::WorldGenerator::Noise(noise_gen) => {
|
||||
self.chunks[index]
|
||||
.get_proto_chunk_mut()
|
||||
.set_structure_references(noise_gen);
|
||||
}
|
||||
generator::WorldGenerator::Flat(_) => {}
|
||||
},
|
||||
StagedChunkEnum::Biomes => match generator {
|
||||
generator::WorldGenerator::Noise(noise_gen) => {
|
||||
self.chunks[index]
|
||||
.get_proto_chunk_mut()
|
||||
.step_to_biomes(noise_gen);
|
||||
}
|
||||
generator::WorldGenerator::Flat(flat_gen) => {
|
||||
flat_gen.step_to_biomes(self.chunks[index].get_proto_chunk_mut());
|
||||
}
|
||||
},
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn new(x: i32, z: i32, size: i32) -> Self {
|
||||
Self {
|
||||
x,
|
||||
z,
|
||||
size,
|
||||
chunks: Vec::with_capacity((size * size) as usize),
|
||||
}
|
||||
}
|
||||
pub fn advance(
|
||||
&mut self,
|
||||
stage: StagedChunkEnum,
|
||||
generator: &generator::WorldGenerator,
|
||||
block_registry: &dyn WorldPortalExt,
|
||||
lighting_config: &LightingEngineConfig,
|
||||
) {
|
||||
let mid = ((self.size * self.size) >> 1) as usize;
|
||||
match &self.chunks[mid] {
|
||||
Chunk::Level(_) => return,
|
||||
Chunk::Proto(chunk) if chunk.stage >= stage => return,
|
||||
Chunk::Proto(_) => {}
|
||||
}
|
||||
match stage {
|
||||
StagedChunkEnum::Empty => panic!("empty stage"),
|
||||
StagedChunkEnum::StructureStart => match generator {
|
||||
generator::WorldGenerator::Noise(noise_gen) => {
|
||||
self.chunks[mid]
|
||||
.get_proto_chunk_mut()
|
||||
.set_structure_starts(noise_gen);
|
||||
}
|
||||
generator::WorldGenerator::Flat(_) => {}
|
||||
},
|
||||
StagedChunkEnum::StructureReferences => match generator {
|
||||
generator::WorldGenerator::Noise(noise_gen) => {
|
||||
self.chunks[mid]
|
||||
.get_proto_chunk_mut()
|
||||
.set_structure_references(noise_gen);
|
||||
}
|
||||
generator::WorldGenerator::Flat(_) => {}
|
||||
},
|
||||
StagedChunkEnum::Biomes => match generator {
|
||||
generator::WorldGenerator::Noise(noise_gen) => {
|
||||
self.chunks[mid]
|
||||
.get_proto_chunk_mut()
|
||||
.step_to_biomes(noise_gen);
|
||||
}
|
||||
generator::WorldGenerator::Flat(flat_gen) => {
|
||||
flat_gen.step_to_biomes(self.chunks[mid].get_proto_chunk_mut());
|
||||
}
|
||||
},
|
||||
StagedChunkEnum::Noise => match generator {
|
||||
generator::WorldGenerator::Noise(noise_gen) => {
|
||||
self.chunks[mid]
|
||||
.get_proto_chunk_mut()
|
||||
.step_to_noise(noise_gen);
|
||||
}
|
||||
generator::WorldGenerator::Flat(flat_gen) => {
|
||||
flat_gen.step_to_noise(self.chunks[mid].get_proto_chunk_mut());
|
||||
}
|
||||
},
|
||||
StagedChunkEnum::Surface => match generator {
|
||||
generator::WorldGenerator::Noise(noise_gen) => {
|
||||
self.chunks[mid]
|
||||
.get_proto_chunk_mut()
|
||||
.step_to_surface(noise_gen);
|
||||
}
|
||||
generator::WorldGenerator::Flat(flat_gen) => {
|
||||
flat_gen.step_to_surface(self.chunks[mid].get_proto_chunk_mut());
|
||||
}
|
||||
},
|
||||
StagedChunkEnum::Carvers => match generator {
|
||||
generator::WorldGenerator::Noise(noise_gen) => {
|
||||
self.chunks[mid]
|
||||
.get_proto_chunk_mut()
|
||||
.step_to_carvers(noise_gen);
|
||||
}
|
||||
generator::WorldGenerator::Flat(flat_gen) => {
|
||||
flat_gen.step_to_carvers(self.chunks[mid].get_proto_chunk_mut());
|
||||
}
|
||||
},
|
||||
StagedChunkEnum::Features => match generator {
|
||||
generator::WorldGenerator::Noise(noise_gen) => {
|
||||
ProtoChunk::generate_features_and_structure(
|
||||
self,
|
||||
block_registry,
|
||||
&noise_gen.random_config,
|
||||
);
|
||||
}
|
||||
generator::WorldGenerator::Flat(_) => {
|
||||
self.chunks[mid].get_proto_chunk_mut().stage = StagedChunkEnum::Features;
|
||||
}
|
||||
},
|
||||
StagedChunkEnum::Lighting => {
|
||||
let mut engine = crate::lighting::LightEngine::new();
|
||||
engine.initialize_light(self, lighting_config);
|
||||
// Only set stage to Lighting if it wasn't already at Lighting or higher
|
||||
// (initialize_light may short-circuit for already-lit chunks)
|
||||
let chunk = self.chunks[mid].get_proto_chunk_mut();
|
||||
if chunk.stage < StagedChunkEnum::Lighting {
|
||||
chunk.stage = StagedChunkEnum::Lighting;
|
||||
}
|
||||
// Engine's internal state is cleared by initialize_light() and will be dropped here
|
||||
drop(engine);
|
||||
}
|
||||
StagedChunkEnum::Spawn => {
|
||||
ProtoChunk::spawn_mobs(self, block_registry);
|
||||
}
|
||||
StagedChunkEnum::Full => {
|
||||
let chunk = self.chunks[mid].get_proto_chunk_mut();
|
||||
debug_assert_eq!(chunk.stage, StagedChunkEnum::Spawn);
|
||||
chunk.stage = StagedChunkEnum::Full;
|
||||
self.chunks[mid].upgrade_to_level_chunk(generator.dimension(), lighting_config);
|
||||
}
|
||||
StagedChunkEnum::None => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
/*
|
||||
TODO
|
||||
1. add proto chunk dirty flag
|
||||
2. better priority
|
||||
5. add lifetime to loading ticket
|
||||
6. solve entity not unload problem
|
||||
*/
|
||||
|
||||
pub type HashMapType<K, V> = rustc_hash::FxHashMap<K, V>;
|
||||
pub type HashSetType<K> = rustc_hash::FxHashSet<K>;
|
||||
pub type ChunkPos = pumpkin_util::math::vector2::Vector2<i32>;
|
||||
pub type ChunkLevel = HashMapType<ChunkPos, i8>;
|
||||
pub type IOLock = std::sync::Arc<(
|
||||
std::sync::Mutex<HashMapType<ChunkPos, u8>>,
|
||||
tokio::sync::Notify,
|
||||
)>;
|
||||
|
||||
pub mod channel;
|
||||
pub mod chunk_holder;
|
||||
pub mod chunk_listener;
|
||||
pub mod chunk_loading;
|
||||
pub mod chunk_state;
|
||||
pub mod dag;
|
||||
pub mod generation;
|
||||
pub mod generation_cache;
|
||||
pub mod schedule;
|
||||
pub mod worker_logic;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
pub use channel::LevelChannel;
|
||||
pub use chunk_holder::ChunkHolder;
|
||||
pub use chunk_listener::ChunkListener;
|
||||
pub use chunk_loading::ChunkLoading;
|
||||
pub use chunk_state::{Chunk, StagedChunkEnum};
|
||||
pub use dag::DAG;
|
||||
pub use generation::generate_single_chunk;
|
||||
pub use generation_cache::Cache;
|
||||
pub use schedule::GenerationSchedule;
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,357 @@
|
||||
use super::*;
|
||||
use crate::chunk_system::dag::Node;
|
||||
use crate::chunk_system::dag::NodeKey;
|
||||
use slotmap::Key;
|
||||
use std::collections::BinaryHeap;
|
||||
use std::collections::HashMap;
|
||||
|
||||
#[test]
|
||||
fn ensure_dependency_chain_builds_multistage_chain() {
|
||||
let mut graph = DAG::default();
|
||||
let mut queue = BinaryHeap::new();
|
||||
let last_level: ChunkLevel = HashMapType::default();
|
||||
let last_high_priority: Vec<ChunkPos> = Vec::new();
|
||||
|
||||
let chunk_pos = ChunkPos::new(0, 0);
|
||||
|
||||
// Create a dependency node in the graph which will depend on the chain
|
||||
let dependency_task = graph
|
||||
.nodes
|
||||
.insert(Node::new(ChunkPos::new(10, 10), StagedChunkEnum::Features));
|
||||
|
||||
let mut holder = ChunkHolder {
|
||||
current_stage: StagedChunkEnum::None,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
// Build a chain up to Surface (Empty -> ... -> Surface)
|
||||
GenerationSchedule::ensure_dependency_chain(
|
||||
&mut graph,
|
||||
&mut queue,
|
||||
&last_level,
|
||||
&last_high_priority,
|
||||
dependency_task,
|
||||
chunk_pos,
|
||||
&mut holder,
|
||||
StagedChunkEnum::Surface,
|
||||
);
|
||||
|
||||
let start = (holder.current_stage as usize + 1).max(StagedChunkEnum::Empty as usize);
|
||||
let end = StagedChunkEnum::Surface as u8 as usize;
|
||||
|
||||
// Ensure tasks were created, present in the DAG, and correctly chained
|
||||
for idx in start..=end {
|
||||
let key = holder.tasks[idx];
|
||||
assert!(!key.is_null(), "task {idx} was not created");
|
||||
|
||||
let node = graph.nodes.get(key).expect("graph missing node");
|
||||
|
||||
if idx == start {
|
||||
assert_eq!(node.in_degree, 0, "Start task should have 0 in_degree");
|
||||
} else {
|
||||
assert_eq!(
|
||||
node.in_degree, 1,
|
||||
"Intermediate task {idx} should have in_degree of 1"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// The dependency node should have its in_degree incremented
|
||||
let dep_node = graph.nodes.get(dependency_task).unwrap();
|
||||
assert_eq!(dep_node.in_degree, 1);
|
||||
|
||||
// The entry task should have been queued
|
||||
let queued = queue.pop().expect("queue should have entry task");
|
||||
assert_eq!(queued.node_key(), holder.tasks[start]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ensure_dependency_chain_resumes_partial_chain() {
|
||||
let mut graph = DAG::default();
|
||||
let mut queue = BinaryHeap::new();
|
||||
let last_level: ChunkLevel = HashMapType::default();
|
||||
let last_high_priority: Vec<ChunkPos> = Vec::new();
|
||||
|
||||
let chunk_pos = ChunkPos::new(0, 0);
|
||||
let dependency_task = graph
|
||||
.nodes
|
||||
.insert(Node::new(ChunkPos::new(10, 10), StagedChunkEnum::Features));
|
||||
|
||||
let mut holder = ChunkHolder {
|
||||
current_stage: StagedChunkEnum::Biomes,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
GenerationSchedule::ensure_dependency_chain(
|
||||
&mut graph,
|
||||
&mut queue,
|
||||
&last_level,
|
||||
&last_high_priority,
|
||||
dependency_task,
|
||||
chunk_pos,
|
||||
&mut holder,
|
||||
StagedChunkEnum::Surface,
|
||||
);
|
||||
|
||||
// Dynamically calculate the next stage after Biomes instead of guessing
|
||||
let empty = StagedChunkEnum::Empty as usize;
|
||||
let start = (holder.current_stage as usize + 1).max(empty);
|
||||
|
||||
let queued = queue.pop().expect("queue should have entry task");
|
||||
assert_eq!(
|
||||
queued.node_key(),
|
||||
holder.tasks[start],
|
||||
"Should resume directly from the next stage after Biomes"
|
||||
);
|
||||
|
||||
let entry_node = graph.nodes.get(queued.node_key()).unwrap();
|
||||
assert_eq!(
|
||||
entry_node.in_degree, 0,
|
||||
"Resumed task should have 0 in_degree because previous stages are already done"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ensure_dependency_chain_does_nothing_if_already_met() {
|
||||
let mut graph = DAG::default();
|
||||
let mut queue = BinaryHeap::new();
|
||||
let last_level: ChunkLevel = HashMapType::default();
|
||||
let last_high_priority: Vec<ChunkPos> = Vec::new();
|
||||
|
||||
let chunk_pos = ChunkPos::new(0, 0);
|
||||
let dependency_task = graph
|
||||
.nodes
|
||||
.insert(Node::new(ChunkPos::new(10, 10), StagedChunkEnum::Features));
|
||||
|
||||
let mut holder = ChunkHolder {
|
||||
current_stage: StagedChunkEnum::Full,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
GenerationSchedule::ensure_dependency_chain(
|
||||
&mut graph,
|
||||
&mut queue,
|
||||
&last_level,
|
||||
&last_high_priority,
|
||||
dependency_task,
|
||||
chunk_pos,
|
||||
&mut holder,
|
||||
StagedChunkEnum::Surface, // Requesting a lower stage than it currently is
|
||||
);
|
||||
|
||||
// Ensure the function returned early without creating any tasks or queueing anything
|
||||
for task in &holder.tasks {
|
||||
assert!(
|
||||
task.is_null(),
|
||||
"No tasks should be created if the stage requirement is already met"
|
||||
);
|
||||
}
|
||||
assert!(queue.is_empty(), "Nothing should be queued");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ensure_dependency_chain_respects_occupied_lock() {
|
||||
let mut graph = DAG::default();
|
||||
let mut queue = BinaryHeap::new();
|
||||
let last_level: ChunkLevel = HashMapType::default();
|
||||
let last_high_priority: Vec<ChunkPos> = Vec::new();
|
||||
|
||||
let chunk_pos = ChunkPos::new(0, 0);
|
||||
let dependency_task = graph
|
||||
.nodes
|
||||
.insert(Node::new(ChunkPos::new(10, 10), StagedChunkEnum::Features));
|
||||
|
||||
// Create an "occupy" node to simulate another thread/process currently working on this chunk
|
||||
let occupy_node = graph.nodes.insert(Node::new(
|
||||
ChunkPos::new(i32::MAX, i32::MAX),
|
||||
StagedChunkEnum::None,
|
||||
));
|
||||
|
||||
let mut holder = ChunkHolder {
|
||||
current_stage: StagedChunkEnum::None,
|
||||
occupied: occupy_node,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
GenerationSchedule::ensure_dependency_chain(
|
||||
&mut graph,
|
||||
&mut queue,
|
||||
&last_level,
|
||||
&last_high_priority,
|
||||
dependency_task,
|
||||
chunk_pos,
|
||||
&mut holder,
|
||||
StagedChunkEnum::Surface,
|
||||
);
|
||||
|
||||
let start = StagedChunkEnum::Empty as usize;
|
||||
let entry_task = holder.tasks[start];
|
||||
|
||||
let entry_node = graph.nodes.get(entry_task).unwrap();
|
||||
// The first task should depend on the occupy node finishing!
|
||||
assert_eq!(
|
||||
entry_node.in_degree, 1,
|
||||
"Entry task should be blocked by the occupy node"
|
||||
);
|
||||
|
||||
// Therefore, the queue MUST be empty. It shouldn't fire until the occupy node drops.
|
||||
assert!(
|
||||
queue.is_empty(),
|
||||
"Task should not be queued because it is blocked by occupied status"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ensure_dependency_chain_early_return_skips_edge() {
|
||||
let mut graph = DAG::default();
|
||||
let mut queue = BinaryHeap::new();
|
||||
let last_level = HashMapType::default();
|
||||
let last_high_priority = Vec::new();
|
||||
|
||||
let dependency_task = graph
|
||||
.nodes
|
||||
.insert(Node::new(ChunkPos::new(1, 1), StagedChunkEnum::Surface));
|
||||
|
||||
// Create a holder that is already at the required stage (Features > Surface)
|
||||
let mut holder = ChunkHolder {
|
||||
current_stage: StagedChunkEnum::Features,
|
||||
target_stage: StagedChunkEnum::Features,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
// Require 'Empty', but holder is already at 'Features'
|
||||
GenerationSchedule::ensure_dependency_chain(
|
||||
&mut graph,
|
||||
&mut queue,
|
||||
&last_level,
|
||||
&last_high_priority,
|
||||
dependency_task,
|
||||
ChunkPos::new(0, 0),
|
||||
&mut holder,
|
||||
StagedChunkEnum::Empty,
|
||||
);
|
||||
|
||||
let dep_node = graph.nodes.get(dependency_task).unwrap();
|
||||
|
||||
// Because of the early return, the dependency_task should not have its in_degree increased
|
||||
assert_eq!(
|
||||
dep_node.in_degree, 0,
|
||||
"Dependency task should not be blocked if the neighbor is already past the required stage"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completed_proto_stage_drops_all_satisfied_tasks() {
|
||||
let mut graph = DAG::default();
|
||||
let mut holder = ChunkHolder {
|
||||
current_stage: StagedChunkEnum::None,
|
||||
target_stage: StagedChunkEnum::StructureStart,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
for stage in StagedChunkEnum::Empty as usize..=StagedChunkEnum::StructureStart as usize {
|
||||
holder.tasks[stage] = graph.nodes.insert(Node::new(
|
||||
ChunkPos::new(0, 0),
|
||||
StagedChunkEnum::from(stage as u8),
|
||||
));
|
||||
}
|
||||
|
||||
for stage in StagedChunkEnum::Empty as usize..StagedChunkEnum::StructureStart as usize {
|
||||
graph.add_edge(holder.tasks[stage], holder.tasks[stage + 1]);
|
||||
}
|
||||
|
||||
let returned_stage = StagedChunkEnum::Biomes as usize;
|
||||
for task_idx in
|
||||
(holder.current_stage as usize + 1)..=(returned_stage).min(holder.tasks.len() - 1)
|
||||
{
|
||||
if !holder.tasks[task_idx].is_null() {
|
||||
if let Some(old) = graph.nodes.remove(holder.tasks[task_idx]) {
|
||||
let mut edge = old.edge;
|
||||
while !edge.is_null() {
|
||||
let cur = graph.edges.remove(edge).unwrap();
|
||||
if let Some(node) = graph.nodes.get_mut(cur.to) {
|
||||
node.in_degree -= 1;
|
||||
}
|
||||
edge = cur.next;
|
||||
}
|
||||
}
|
||||
holder.tasks[task_idx] = NodeKey::null();
|
||||
}
|
||||
}
|
||||
|
||||
assert!(holder.tasks[StagedChunkEnum::Empty as usize].is_null());
|
||||
assert!(holder.tasks[StagedChunkEnum::Biomes as usize].is_null());
|
||||
assert!(!holder.tasks[StagedChunkEnum::StructureStart as usize].is_null());
|
||||
assert!(
|
||||
graph
|
||||
.nodes
|
||||
.get(holder.tasks[StagedChunkEnum::StructureStart as usize])
|
||||
.is_some()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancellation_path_decrements_in_degree() {
|
||||
let mut graph = DAG::default();
|
||||
|
||||
// Create a task that is waiting (in_degree = 1)
|
||||
let waiting_task_key = graph
|
||||
.nodes
|
||||
.insert(Node::new(ChunkPos::new(0, 0), StagedChunkEnum::Surface));
|
||||
let waiting_node = graph.nodes.get_mut(waiting_task_key).unwrap();
|
||||
waiting_node.in_degree = 1;
|
||||
|
||||
// Create the occupy node that the task is waiting on
|
||||
let occupy_key = graph.nodes.insert(Node::new(
|
||||
ChunkPos::new(i32::MAX, i32::MAX),
|
||||
StagedChunkEnum::None,
|
||||
));
|
||||
graph.add_edge(occupy_key, waiting_task_key);
|
||||
|
||||
// Set up the chunk map to simulate an in-flight task
|
||||
let mut chunk_map = HashMap::new();
|
||||
let mut holder = ChunkHolder {
|
||||
current_stage: StagedChunkEnum::Empty,
|
||||
target_stage: StagedChunkEnum::Surface,
|
||||
occupied: occupy_key,
|
||||
..Default::default()
|
||||
};
|
||||
holder.tasks[StagedChunkEnum::Surface as usize] = waiting_task_key;
|
||||
chunk_map.insert(ChunkPos::new(0, 0), holder);
|
||||
|
||||
// Simulate the cancellation logic from `work()`
|
||||
let mut nodes_to_drop = Vec::new();
|
||||
for holder in chunk_map.values_mut() {
|
||||
for task in &mut holder.tasks {
|
||||
if !task.is_null() {
|
||||
nodes_to_drop.push(*task);
|
||||
*task = NodeKey::null();
|
||||
}
|
||||
}
|
||||
if !holder.occupied.is_null() {
|
||||
nodes_to_drop.push(holder.occupied);
|
||||
holder.occupied = NodeKey::null();
|
||||
}
|
||||
}
|
||||
|
||||
// Drop nodes using the proper graph edge traversal
|
||||
for node_key in nodes_to_drop {
|
||||
// Simulating the self.drop_node logic inside the test
|
||||
if let Some(old) = graph.nodes.remove(node_key) {
|
||||
let mut edge = old.edge;
|
||||
while !edge.is_null() {
|
||||
let cur = graph.edges.remove(edge).unwrap();
|
||||
if let Some(node) = graph.nodes.get_mut(cur.to) {
|
||||
node.in_degree -= 1;
|
||||
}
|
||||
edge = cur.next;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Assert that the waiting task was properly cleaned up
|
||||
assert!(
|
||||
graph.nodes.get(waiting_task_key).is_none(),
|
||||
"The waiting task should have been dropped during cancellation"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
use super::chunk_state::{Chunk, StagedChunkEnum};
|
||||
use super::generation_cache::Cache;
|
||||
use super::{ChunkPos, IOLock};
|
||||
use crate::ProtoChunk;
|
||||
use crate::chunk::format::LightContainer;
|
||||
use crate::chunk::io::LoadedData;
|
||||
use crate::chunk::io::LoadedData::Loaded;
|
||||
use crate::level::Level;
|
||||
use crossfire::compat::AsyncRx;
|
||||
use pumpkin_config::lighting::LightingEngineConfig;
|
||||
use pumpkin_data::chunk::ChunkStatus;
|
||||
use pumpkin_data::chunk_gen_settings::GenerationSettings;
|
||||
use std::collections::hash_map::Entry;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
use tracing::{debug, error, warn};
|
||||
|
||||
pub enum RecvChunk {
|
||||
IO(Chunk),
|
||||
Generation(Cache),
|
||||
GenerationFailure {
|
||||
pos: ChunkPos,
|
||||
stage: StagedChunkEnum,
|
||||
error: String,
|
||||
},
|
||||
}
|
||||
|
||||
/// Checks if a chunk needs relighting based on the current lighting configuration
|
||||
/// Returns true if the chunk has uniform lighting (from full/dark mode) but the server
|
||||
/// is now running in default mode (which needs proper lighting calculation)
|
||||
fn needs_relighting(chunk: &crate::chunk::ChunkData, config: LightingEngineConfig) -> bool {
|
||||
if config != LightingEngineConfig::Default {
|
||||
return false;
|
||||
}
|
||||
|
||||
// If the chunk says it's already lit, believe it.
|
||||
if chunk.light_populated.load(Relaxed) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let engine = chunk.light_engine.lock().expect("Mutex poisoned");
|
||||
|
||||
// Scan for any complex lighting data
|
||||
let has_complex_light = engine.sky_light.iter().any(|lc| match lc {
|
||||
LightContainer::Full(data) => data.iter().any(|&b| b != 0x00 && b != 0xFF),
|
||||
LightContainer::Empty(val) => *val != 0 && *val != 15,
|
||||
}) || engine.block_light.iter().any(|lc| match lc {
|
||||
LightContainer::Full(data) => data.iter().any(|&b| b != 0x00 && b != 0xFF),
|
||||
LightContainer::Empty(val) => *val != 0 && *val != 15,
|
||||
});
|
||||
|
||||
// If it has complex light, we don't need to relight.
|
||||
!has_complex_light
|
||||
}
|
||||
|
||||
pub async fn io_read_work(
|
||||
recv: crossfire::compat::MAsyncRx<Vec<ChunkPos>>,
|
||||
send: crossfire::compat::MTx<(ChunkPos, RecvChunk)>,
|
||||
level: Arc<Level>,
|
||||
lock: IOLock,
|
||||
) {
|
||||
debug!("io read thread start");
|
||||
|
||||
// Cleaner loop and async recv
|
||||
while let Ok(batch) = recv.recv().await {
|
||||
for pos in &batch {
|
||||
// Lock handling
|
||||
loop {
|
||||
let notified = lock.1.notified();
|
||||
if !lock.0.lock().unwrap().contains_key(pos) {
|
||||
break;
|
||||
}
|
||||
notified.await;
|
||||
}
|
||||
}
|
||||
|
||||
let (t_send, mut t_recv) = tokio::sync::mpsc::channel(1000);
|
||||
|
||||
let batch_len = batch.len();
|
||||
let level_clone = level.clone();
|
||||
|
||||
let fetch_task = tokio::spawn(async move {
|
||||
level_clone
|
||||
.chunk_saver
|
||||
.fetch_chunks(&level_clone.level_folder, &batch, t_send)
|
||||
.await;
|
||||
});
|
||||
|
||||
for _ in 0..batch_len {
|
||||
let Some(data) = t_recv.recv().await else {
|
||||
break;
|
||||
};
|
||||
|
||||
match data {
|
||||
Loaded(chunk) => {
|
||||
let pos = ChunkPos::new(chunk.x, chunk.z);
|
||||
if chunk.status == ChunkStatus::Full {
|
||||
// Relighting check
|
||||
let needs_relight = needs_relighting(&chunk, level.lighting_config);
|
||||
|
||||
if needs_relight {
|
||||
debug!(
|
||||
"Chunk {pos:?} has uniform lighting, downgrading to Features stage for relighting"
|
||||
);
|
||||
|
||||
// Create ProtoChunk using the async method
|
||||
let mut proto = ProtoChunk::from_chunk_data(&chunk, &level.world_gen);
|
||||
|
||||
// Clear all lighting data
|
||||
let section_count = proto.light.sky_light.len();
|
||||
proto.light.sky_light = (0..section_count)
|
||||
.map(|_| LightContainer::new_empty(15))
|
||||
.collect();
|
||||
proto.light.block_light = (0..section_count)
|
||||
.map(|_| LightContainer::new_empty(0))
|
||||
.collect();
|
||||
|
||||
// Set stage to Features
|
||||
proto.stage = StagedChunkEnum::Features;
|
||||
|
||||
if send
|
||||
.send((pos, RecvChunk::IO(Chunk::Proto(Box::new(proto)))))
|
||||
.is_err()
|
||||
{
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
// Send fully valid chunk
|
||||
if send
|
||||
.send((pos, RecvChunk::IO(Chunk::Level(chunk))))
|
||||
.is_err()
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Standard ProtoChunk handling for non-full chunks
|
||||
let val = RecvChunk::IO(Chunk::Proto(Box::new(
|
||||
ProtoChunk::from_chunk_data(&chunk, &level.world_gen),
|
||||
)));
|
||||
if send.send((pos, val)).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
LoadedData::Missing(pos) | LoadedData::Error((pos, _)) => {
|
||||
if send
|
||||
.send((
|
||||
pos,
|
||||
RecvChunk::IO(Chunk::Proto(Box::new(ProtoChunk::new(
|
||||
pos.x,
|
||||
pos.y,
|
||||
&level.world_gen,
|
||||
)))),
|
||||
))
|
||||
.is_err()
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let _ = fetch_task.await;
|
||||
}
|
||||
debug!("io read thread stop");
|
||||
}
|
||||
|
||||
pub async fn io_write_work(recv: AsyncRx<Vec<(ChunkPos, Chunk)>>, level: Arc<Level>, lock: IOLock) {
|
||||
loop {
|
||||
// Don't check cancel_token here (keep saving chunks)
|
||||
let Ok(data) = recv.recv().await else { break };
|
||||
// debug!("io write thread receive chunks size {}", data.len());
|
||||
let mut vec = Vec::with_capacity(data.len());
|
||||
let mut positions = Vec::with_capacity(data.len());
|
||||
for (pos, chunk) in data {
|
||||
positions.push(pos);
|
||||
|
||||
match chunk {
|
||||
Chunk::Level(chunk) => vec.push((pos, chunk)),
|
||||
Chunk::Proto(chunk) => {
|
||||
let mut temp = Chunk::Proto(chunk);
|
||||
temp.upgrade_to_level_chunk(
|
||||
level.world_gen.dimension(),
|
||||
&level.lighting_config,
|
||||
);
|
||||
let Chunk::Level(chunk) = temp else { panic!() };
|
||||
vec.push((pos, chunk));
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Err(e) = level
|
||||
.chunk_saver
|
||||
.save_chunks(&level.level_folder, vec)
|
||||
.await
|
||||
{
|
||||
error!("Failed to save chunks: {:?}", e);
|
||||
}
|
||||
|
||||
for i in positions {
|
||||
let mut data = lock.0.lock().unwrap();
|
||||
match data.entry(i) {
|
||||
Entry::Occupied(mut entry) => {
|
||||
let rc = entry.get_mut();
|
||||
if *rc == 1 {
|
||||
entry.remove();
|
||||
drop(data);
|
||||
lock.1.notify_waiters();
|
||||
} else {
|
||||
*rc -= 1;
|
||||
}
|
||||
}
|
||||
Entry::Vacant(_) => {
|
||||
warn!(
|
||||
"io_write: attempted to release missing lock entry for {:?}",
|
||||
i
|
||||
);
|
||||
// continue without panicking to avoid crashing on shutdown races
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn run_generation(
|
||||
pos: ChunkPos,
|
||||
mut cache: Cache,
|
||||
stage: StagedChunkEnum,
|
||||
level: &Level,
|
||||
_settings: &GenerationSettings,
|
||||
) -> RecvChunk {
|
||||
let portal = level.world_portal.load_full();
|
||||
let portal_ref = portal.as_deref().expect("Portal should be initialized");
|
||||
// Run generation with panic catching
|
||||
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
||||
cache.advance(stage, &level.world_gen, portal_ref, &level.lighting_config);
|
||||
cache // Return cache on success
|
||||
}));
|
||||
|
||||
match result {
|
||||
Ok(cache) => RecvChunk::Generation(cache),
|
||||
Err(payload) => {
|
||||
let msg = payload
|
||||
.downcast_ref::<&str>()
|
||||
.copied()
|
||||
.or_else(|| {
|
||||
payload
|
||||
.downcast_ref::<String>()
|
||||
.map(std::string::String::as_str)
|
||||
})
|
||||
.unwrap_or("Unknown panic payload");
|
||||
|
||||
error!("Chunk generation FAILED at {pos:?} ({stage:?}): {msg}");
|
||||
|
||||
RecvChunk::GenerationFailure {
|
||||
pos,
|
||||
stage,
|
||||
error: msg.to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn generation_work(
|
||||
recv: &crossfire::compat::MRx<(ChunkPos, Cache, StagedChunkEnum)>,
|
||||
send: &crossfire::compat::MTx<(ChunkPos, RecvChunk)>,
|
||||
level: &Arc<Level>,
|
||||
) {
|
||||
let settings = GenerationSettings::from_dimension(level.world_gen.dimension());
|
||||
|
||||
loop {
|
||||
let Ok((pos, cache, stage)) = recv.recv() else {
|
||||
debug!("generation channel closed, exiting");
|
||||
break;
|
||||
};
|
||||
|
||||
let result = run_generation(pos, cache, stage, level, settings);
|
||||
if send.send((pos, result)).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
use std::num::NonZeroU8;
|
||||
|
||||
use pumpkin_util::math::vector2::Vector2;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Cylindrical {
|
||||
pub center: Vector2<i32>,
|
||||
pub view_distance: NonZeroU8,
|
||||
}
|
||||
|
||||
impl Cylindrical {
|
||||
#[must_use]
|
||||
pub const fn new(center: Vector2<i32>, view_distance: NonZeroU8) -> Self {
|
||||
Self {
|
||||
center,
|
||||
view_distance,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn changed_chunks(
|
||||
old: Self,
|
||||
new: Self,
|
||||
) -> (
|
||||
impl Iterator<Item = Vector2<i32>>,
|
||||
impl Iterator<Item = Vector2<i32>>,
|
||||
) {
|
||||
let loading = new
|
||||
.all_chunks_within()
|
||||
.filter(move |c| !old.is_within_distance(c.x, c.y));
|
||||
|
||||
let unloading = old
|
||||
.all_chunks_within()
|
||||
.filter(move |c| !new.is_within_distance(c.x, c.y));
|
||||
|
||||
(loading, unloading)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
#[inline]
|
||||
pub const fn left(&self) -> i32 {
|
||||
self.center.x - self.view_distance.get() as i32 - 1
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
#[inline]
|
||||
pub const fn bottom(&self) -> i32 {
|
||||
self.center.y - self.view_distance.get() as i32 - 1
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
#[inline]
|
||||
pub const fn right(&self) -> i32 {
|
||||
self.center.x + self.view_distance.get() as i32 + 1
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
#[inline]
|
||||
pub const fn top(&self) -> i32 {
|
||||
self.center.y + self.view_distance.get() as i32 + 1
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
#[inline]
|
||||
pub const fn is_within_distance(&self, x: i32, z: i32) -> bool {
|
||||
let vd = self.view_distance.get() as i64;
|
||||
if vd == 1 {
|
||||
return false;
|
||||
}
|
||||
let dx = (x - self.center.x).abs() as i64 - 2;
|
||||
let dz = (z - self.center.y).abs() as i64 - 2;
|
||||
let rel_x = if dx > 0 { dx } else { 0 };
|
||||
let rel_z = if dz > 0 { dz } else { 0 };
|
||||
|
||||
let hyp_sqr = rel_x * rel_x + rel_z * rel_z;
|
||||
hyp_sqr < vd * vd
|
||||
}
|
||||
|
||||
/// Returns a precomputed list of relative chunk offset pairs `(dx, dy)` for a given view distance.
|
||||
#[must_use]
|
||||
#[inline]
|
||||
pub const fn get_offsets(view_distance: u8) -> &'static [(i8, i8)] {
|
||||
let vd = view_distance as usize;
|
||||
let max = pumpkin_data::chunk_view_lut::MAX_VIEW_DISTANCE as usize;
|
||||
let idx = if vd < max { vd } else { max };
|
||||
pumpkin_data::chunk_view_lut::CHUNK_VIEW_LUT[idx]
|
||||
}
|
||||
|
||||
/// Returns an iterator of all chunks within this cylinder using the precomputed LUT
|
||||
#[must_use]
|
||||
#[inline]
|
||||
pub fn all_chunks_within(self) -> impl ExactSizeIterator<Item = Vector2<i32>> {
|
||||
let offsets = Self::get_offsets(self.view_distance.get());
|
||||
offsets.iter().map(move |&(dx, dy)| {
|
||||
Vector2::new(self.center.x + i32::from(dx), self.center.y + i32::from(dy))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
|
||||
use std::num::NonZeroU8;
|
||||
|
||||
use super::Cylindrical;
|
||||
use pumpkin_util::math::vector2::Vector2;
|
||||
|
||||
#[test]
|
||||
fn bounds() {
|
||||
let mut cylinder = Cylindrical::new(Vector2::new(0, 0), NonZeroU8::new(1).unwrap());
|
||||
|
||||
for view_distance in 1..=32 {
|
||||
cylinder.view_distance = NonZeroU8::new(view_distance).unwrap();
|
||||
|
||||
for chunk in cylinder.all_chunks_within() {
|
||||
assert!(chunk.x >= cylinder.left() && chunk.x <= cylinder.right());
|
||||
assert!(chunk.y >= cylinder.bottom() && chunk.y <= cylinder.top());
|
||||
}
|
||||
|
||||
for x in (cylinder.left() - 2)..=(cylinder.right() + 2) {
|
||||
for z in (cylinder.bottom() - 2)..=(cylinder.top() + 2) {
|
||||
if cylinder.is_within_distance(x, z) {
|
||||
assert!(x >= cylinder.left() && x <= cylinder.right());
|
||||
assert!(z >= cylinder.bottom() && z <= cylinder.top());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn all_chunks_within_capacity_estimation() {
|
||||
let mut cylinder = Cylindrical::new(Vector2::new(0, 0), NonZeroU8::new(1).unwrap());
|
||||
|
||||
for distance in 1..=64 {
|
||||
cylinder.view_distance = NonZeroU8::new(distance).unwrap();
|
||||
let chunks = cylinder.all_chunks_within();
|
||||
let estimated_capacity = ((distance as usize + 3).pow(2) * 3167) >> 10;
|
||||
|
||||
assert!(estimated_capacity >= chunks.len(),);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
pub mod player_data;
|
||||
@@ -0,0 +1,157 @@
|
||||
use pumpkin_nbt::compound::NbtCompound;
|
||||
use std::fs::{File, create_dir_all};
|
||||
use std::io;
|
||||
use std::path::PathBuf;
|
||||
use tracing::{debug, error};
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Manages the storage and retrieval of player data from disk and memory cache.
|
||||
///
|
||||
/// This struct provides functions to load and save player data to/from NBT files,
|
||||
/// with a memory cache to handle player disconnections temporarily.
|
||||
pub struct PlayerDataStorage {
|
||||
/// Path to the directory where player data is stored
|
||||
data_path: PathBuf,
|
||||
/// Whether player data saving is enabled
|
||||
save_enabled: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum PlayerDataError {
|
||||
#[error("IO error: {0}")]
|
||||
Io(#[from] io::Error),
|
||||
#[error("NBT error: {0}")]
|
||||
Nbt(String),
|
||||
}
|
||||
|
||||
impl PlayerDataStorage {
|
||||
/// Creates a new `PlayerDataStorage` with the specified data path and cache expiration time.
|
||||
pub fn new(data_path: impl Into<PathBuf>, enabled: bool) -> Self {
|
||||
let path = data_path.into();
|
||||
if !path.exists()
|
||||
&& let Err(e) = create_dir_all(&path)
|
||||
{
|
||||
error!(
|
||||
"Failed to create player data directory at {}: {e}",
|
||||
path.display()
|
||||
);
|
||||
}
|
||||
|
||||
Self {
|
||||
data_path: path,
|
||||
save_enabled: enabled,
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn get_data_path(&self) -> &PathBuf {
|
||||
&self.data_path
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn is_save_enabled(&self) -> bool {
|
||||
self.save_enabled
|
||||
}
|
||||
|
||||
pub const fn set_save_enabled(&mut self, enabled: bool) {
|
||||
self.save_enabled = enabled;
|
||||
}
|
||||
|
||||
/// Returns the path for a player's data file based on their UUID.
|
||||
#[must_use]
|
||||
pub fn get_player_data_path(&self, uuid: &Uuid) -> PathBuf {
|
||||
self.get_data_path().join(format!("{uuid}.dat"))
|
||||
}
|
||||
|
||||
/// Loads player data from NBT file or cache.
|
||||
///
|
||||
/// This function first checks if player data exists in the cache.
|
||||
/// If not, it attempts to load the data from a .dat file on disk.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `uuid` - The UUID of the player to load data for.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// A Result containing either the player's NBT data or an error.
|
||||
pub fn load_player_data(&self, uuid: &Uuid) -> Result<(bool, NbtCompound), PlayerDataError> {
|
||||
// If player data saving is disabled, return empty data
|
||||
if !self.is_save_enabled() {
|
||||
return Ok((false, NbtCompound::new()));
|
||||
}
|
||||
|
||||
// If not in cache, load from disk
|
||||
let path = self.get_player_data_path(uuid);
|
||||
if !path.exists() {
|
||||
debug!("No player data file found for {uuid}");
|
||||
return Ok((false, NbtCompound::new()));
|
||||
}
|
||||
|
||||
let file = match File::open(&path) {
|
||||
Ok(file) => file,
|
||||
Err(e) => {
|
||||
error!("Failed to open player data file for {uuid}: {e}");
|
||||
return Err(PlayerDataError::Io(e));
|
||||
}
|
||||
};
|
||||
|
||||
match pumpkin_nbt::nbt_compress::read_gzip_compound_tag(file) {
|
||||
Ok(nbt) => {
|
||||
debug!("Loaded player data for {uuid} from disk");
|
||||
Ok((true, nbt))
|
||||
}
|
||||
Err(e) => {
|
||||
error!("Failed to read player data for {uuid}: {e}");
|
||||
Err(PlayerDataError::Nbt(e.to_string()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Saves player data to NBT file and updates cache.
|
||||
///
|
||||
/// This function saves the player's data to a .dat file on disk and also
|
||||
/// updates the in-memory cache with the latest data.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `uuid` - The UUID of the player to save data for.
|
||||
/// * `data` - The NBT compound data to save.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// A Result indicating success or the error that occurred.
|
||||
pub fn save_player_data(&self, uuid: &Uuid, data: NbtCompound) -> Result<(), PlayerDataError> {
|
||||
// Skip saving if disabled in config
|
||||
if !self.is_save_enabled() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let path = self.get_player_data_path(uuid);
|
||||
|
||||
// Ensure parent directory exists
|
||||
if let Some(parent) = path.parent()
|
||||
&& let Err(e) = create_dir_all(parent)
|
||||
{
|
||||
error!("Failed to create player data directory for {uuid}: {e}");
|
||||
return Err(PlayerDataError::Io(e));
|
||||
}
|
||||
|
||||
// Create the file and write directly with GZip compression
|
||||
match File::create(&path) {
|
||||
Ok(file) => {
|
||||
if let Err(e) = pumpkin_nbt::nbt_compress::write_gzip_compound_tag(data, file) {
|
||||
error!("Failed to write compressed player data for {uuid}: {e}");
|
||||
Err(PlayerDataError::Nbt(e.to_string()))
|
||||
} else {
|
||||
debug!("Saved player data for {uuid} to disk");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
error!("Failed to create player data file for {uuid}: {e}");
|
||||
Err(PlayerDataError::Io(e))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
use std::{path::PathBuf, sync::Arc};
|
||||
|
||||
use pumpkin_config::world::LevelConfig;
|
||||
use pumpkin_data::dimension::Dimension;
|
||||
|
||||
use crate::level::Level;
|
||||
|
||||
#[must_use]
|
||||
pub fn into_level(
|
||||
dimension: Dimension,
|
||||
level_config: &LevelConfig,
|
||||
mut base_directory: PathBuf,
|
||||
seed: i64,
|
||||
gen_pool: Option<Arc<rayon::ThreadPool>>,
|
||||
) -> Arc<Level> {
|
||||
if dimension.minecraft_name == Dimension::OVERWORLD.minecraft_name {
|
||||
} else if dimension.minecraft_name == Dimension::THE_NETHER.minecraft_name {
|
||||
base_directory.push("DIM-1");
|
||||
} else if dimension.minecraft_name == Dimension::THE_END.minecraft_name {
|
||||
base_directory.push("DIM1");
|
||||
}
|
||||
Level::from_root_folder(level_config, base_directory, seed, dimension, gen_pool)
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
use pumpkin_util::math::{square_f64, vector3::Vector3};
|
||||
|
||||
use super::biome_coords;
|
||||
|
||||
// This blends biome boundaries, returning which biome to populate the surface on based on the seed
|
||||
pub fn get_biome_blend(
|
||||
bottom_y: i8,
|
||||
height: u16,
|
||||
seed: i64,
|
||||
x: i32,
|
||||
y: i32,
|
||||
z: i32,
|
||||
) -> Vector3<i32> {
|
||||
// This is the "left" side of the biome boundary
|
||||
let offset_x = x - 2;
|
||||
let offset_y = y - 2;
|
||||
let offset_z = z - 2;
|
||||
let biome_x = biome_coords::from_block(offset_x);
|
||||
let biome_y = biome_coords::from_block(offset_y);
|
||||
let biome_z = biome_coords::from_block(offset_z);
|
||||
// &'ing 3 gives values of 0-3, it is also the data we removed when converting to biome coords
|
||||
// This is effectively "quarters" into the biome
|
||||
// Original was "/ 4.0" but we use "* 0.25" as multiplication can be faster
|
||||
let quarters_x = (offset_x & 0b11) as f64 * 0.25;
|
||||
let quarters_y = (offset_y & 0b11) as f64 * 0.25;
|
||||
let quarters_z = (offset_z & 0b11) as f64 * 0.25;
|
||||
|
||||
let mut best_permutation = 0;
|
||||
let mut best_score = f64::INFINITY;
|
||||
for permutation in 0..8 {
|
||||
let should_maintain_x = (permutation & 0b100) == 0;
|
||||
let should_maintain_y = (permutation & 0b010) == 0;
|
||||
let should_maintain_z = (permutation & 0b001) == 0;
|
||||
|
||||
// If we are shifting, add 1 to the biome coords
|
||||
let shifted_biome_x = if should_maintain_x {
|
||||
biome_x
|
||||
} else {
|
||||
biome_x + 1
|
||||
};
|
||||
let shifted_biome_y = if should_maintain_y {
|
||||
biome_y
|
||||
} else {
|
||||
biome_y + 1
|
||||
};
|
||||
let shifted_biome_z = if should_maintain_z {
|
||||
biome_z
|
||||
} else {
|
||||
biome_z + 1
|
||||
};
|
||||
|
||||
// And reflect the "quarters" across the shift
|
||||
let shifted_quarters_x = if should_maintain_x {
|
||||
quarters_x
|
||||
} else {
|
||||
quarters_x - 1.0
|
||||
};
|
||||
let shifted_quarters_y = if should_maintain_y {
|
||||
quarters_y
|
||||
} else {
|
||||
quarters_y - 1.0
|
||||
};
|
||||
let shifted_quarters_z = if should_maintain_z {
|
||||
quarters_z
|
||||
} else {
|
||||
quarters_z - 1.0
|
||||
};
|
||||
|
||||
let permutation_score = score_permutation(
|
||||
seed,
|
||||
shifted_biome_x,
|
||||
shifted_biome_y,
|
||||
shifted_biome_z,
|
||||
shifted_quarters_x,
|
||||
shifted_quarters_y,
|
||||
shifted_quarters_z,
|
||||
);
|
||||
|
||||
if best_score > permutation_score {
|
||||
best_score = permutation_score;
|
||||
best_permutation = permutation;
|
||||
}
|
||||
}
|
||||
|
||||
// Now check if we want to use the "left" side or the "right" side
|
||||
let biome_x = if (best_permutation & 0b100) == 0 {
|
||||
biome_x
|
||||
} else {
|
||||
biome_x + 1
|
||||
};
|
||||
let biome_y = if (best_permutation & 0b010) == 0 {
|
||||
biome_y
|
||||
} else {
|
||||
biome_y + 1
|
||||
};
|
||||
let biome_z = if (best_permutation & 0b001) == 0 {
|
||||
biome_z
|
||||
} else {
|
||||
biome_z + 1
|
||||
};
|
||||
|
||||
// Java's `getBiomeForNoiseGen`
|
||||
let bottom_y = bottom_y as i32;
|
||||
let biome_bottom = biome_coords::from_block(bottom_y);
|
||||
let biome_top = biome_bottom + biome_coords::from_block(height as i32) - 1;
|
||||
let biome_y = biome_y.clamp(biome_bottom, biome_top);
|
||||
|
||||
Vector3::new(biome_x, biome_y, biome_z)
|
||||
}
|
||||
|
||||
// This is effectively getting a random offset (+/- 0.0-0.8ish) to our biome position quarters and
|
||||
// returning a hypotenuse squared of the parts + the offset
|
||||
const fn score_permutation(
|
||||
seed: i64,
|
||||
x: i32,
|
||||
y: i32,
|
||||
z: i32,
|
||||
x_part: f64,
|
||||
y_part: f64,
|
||||
z_part: f64,
|
||||
) -> f64 {
|
||||
let mix = salt_mix(seed, x as i64);
|
||||
let mix = salt_mix(mix, y as i64);
|
||||
let mix = salt_mix(mix, z as i64);
|
||||
let mix = salt_mix(mix, x as i64);
|
||||
let mix = salt_mix(mix, y as i64);
|
||||
let mix = salt_mix(mix, z as i64);
|
||||
let offset_x = scale_mix(mix);
|
||||
let mix = salt_mix(mix, seed);
|
||||
let offset_y = scale_mix(mix);
|
||||
let mix = salt_mix(mix, seed);
|
||||
let offset_z = scale_mix(mix);
|
||||
|
||||
square_f64(z_part + offset_z) + square_f64(y_part + offset_y) + square_f64(x_part + offset_x)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub const fn scale_mix(l: i64) -> f64 {
|
||||
// Shifting and then masking with 1023 (1024 - 1)
|
||||
// This is mathematically identical to floor_mod(l >> 24, 1024)
|
||||
// but executes in a single CPU cycle.
|
||||
let d = ((l >> 24) & 1023) as f64 / 1024.0;
|
||||
|
||||
(d - 0.5) * 0.9
|
||||
}
|
||||
|
||||
#[inline]
|
||||
const fn salt_mix(seed: i64, salt: i64) -> i64 {
|
||||
let mixed_seed = seed.wrapping_mul(
|
||||
seed.wrapping_mul(6364136223846793005)
|
||||
.wrapping_add(1442695040888963407),
|
||||
);
|
||||
mixed_seed.wrapping_add(salt)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use pumpkin_util::{math::vector3::Vector3, read_data_from_file};
|
||||
|
||||
use crate::{
|
||||
biome::hash_seed,
|
||||
generation::biome::{get_biome_blend, scale_mix, score_permutation},
|
||||
};
|
||||
|
||||
use super::salt_mix;
|
||||
|
||||
#[test]
|
||||
fn mix_seed() {
|
||||
let seed = salt_mix(12345678, 12345678);
|
||||
assert_eq!(seed, 2937271135939595220);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn permutation() {
|
||||
let seed = hash_seed(0);
|
||||
let score = score_permutation(seed, 123, 456, 456, 0.25, 0.5, 0.75);
|
||||
assert_eq!(score, 1.276986312866211);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn biome_blend() {
|
||||
let biome_pos = get_biome_blend(-64, 384, 1234567890, 123, 123, 123);
|
||||
assert_eq!(biome_pos, Vector3::new(31, 30, 30));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scale() {
|
||||
let seed = scale_mix(12345678);
|
||||
assert_eq!(seed, -0.45);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chunk_wide_blend() {
|
||||
let data: Vec<(i32, i32, i32, i32, i32, i32)> =
|
||||
read_data_from_file!("../../../assets/tests/biome_mixer.json");
|
||||
|
||||
let seed = hash_seed((-777i64) as u64);
|
||||
for (i, (x, y, z, result_x, result_y, result_z)) in data.into_iter().enumerate() {
|
||||
let result = get_biome_blend(i8::MIN, u16::MAX, seed, x, y, z);
|
||||
let expected = Vector3::new(result_x, result_y, result_z);
|
||||
assert_eq!(
|
||||
result, expected,
|
||||
"Expected: {expected:?}, was: {result:?} ({i})"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
use pumpkin_data::chunk::Biome;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct BlendingData {
|
||||
pub min_y: i32,
|
||||
pub max_y: i32,
|
||||
// Heights at quart positions (16x16 per chunk)
|
||||
pub heights: Vec<f64>,
|
||||
// Densities at quart positions (16x16 per chunk, but at what Y levels? 1.18+ uses 4 blocks quart)
|
||||
// Simplified: only store for current chunk's Y levels
|
||||
pub densities: Vec<f64>,
|
||||
// Biomes at quart positions (16x16 per chunk)
|
||||
pub biomes: Vec<&'static Biome>,
|
||||
}
|
||||
|
||||
impl BlendingData {
|
||||
#[must_use]
|
||||
pub fn get_height(&self, cell_x: i32, _cell_y: i32, cell_z: i32) -> f64 {
|
||||
if !(0..16).contains(&cell_x) || !(0..16).contains(&cell_z) {
|
||||
return f64::MAX;
|
||||
}
|
||||
self.heights[(cell_z * 16 + cell_x) as usize]
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn get_density(&self, cell_x: i32, cell_y: i32, cell_z: i32) -> f64 {
|
||||
if !(0..16).contains(&cell_x) || !(0..16).contains(&cell_z) {
|
||||
return f64::MAX;
|
||||
}
|
||||
let cell_count_y = (self.max_y - self.min_y) / 8;
|
||||
if !(0..cell_count_y).contains(&cell_y) {
|
||||
return f64::MAX;
|
||||
}
|
||||
let index = (cell_y * 16 * 16 + cell_z * 16 + cell_x) as usize;
|
||||
if index < self.densities.len() {
|
||||
self.densities[index]
|
||||
} else {
|
||||
f64::MAX
|
||||
}
|
||||
}
|
||||
|
||||
pub fn iterate_heights<F>(&self, quart_x: i32, quart_z: i32, mut consumer: F)
|
||||
where
|
||||
F: FnMut(i32, i32, f64),
|
||||
{
|
||||
for z in 0..16 {
|
||||
for x in 0..16 {
|
||||
let h = self.heights[z * 16 + x];
|
||||
if h != f64::MAX {
|
||||
consumer(quart_x + x as i32, quart_z + z as i32, h);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn iterate_densities<F>(
|
||||
&self,
|
||||
quart_x: i32,
|
||||
quart_z: i32,
|
||||
min_cell_y: i32,
|
||||
max_cell_y: i32,
|
||||
mut consumer: F,
|
||||
) where
|
||||
F: FnMut(i32, i32, i32, f64),
|
||||
{
|
||||
let cell_count_y = (self.max_y - self.min_y) / 8;
|
||||
for cell_y in min_cell_y..=max_cell_y {
|
||||
if (0..cell_count_y).contains(&cell_y) {
|
||||
for z in 0..16 {
|
||||
for x in 0..16 {
|
||||
let index = (cell_y * 16 * 16 + z * 16 + x) as usize;
|
||||
if index < self.densities.len() {
|
||||
let d = self.densities[index];
|
||||
if d != f64::MAX {
|
||||
consumer(quart_x + x, cell_y, quart_z + z, d);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn iterate_biomes<F>(&self, quart_x: i32, _quart_y: i32, quart_z: i32, mut consumer: F)
|
||||
where
|
||||
F: FnMut(i32, i32, &'static Biome),
|
||||
{
|
||||
for z in 0..16 {
|
||||
for x in 0..16 {
|
||||
let biome = self.biomes[z * 16 + x];
|
||||
consumer(quart_x + x as i32, quart_z + z as i32, biome);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,368 @@
|
||||
pub mod blending_data;
|
||||
|
||||
use std::f64;
|
||||
|
||||
use crate::biome::BiomeSupplier;
|
||||
use crate::generation::biome_coords;
|
||||
use crate::generation::noise::perlin::DoublePerlinNoiseSampler;
|
||||
use crate::generation::noise::router::multi_noise_sampler::MultiNoiseSampler;
|
||||
use crate::generation::proto_chunk::GenerationCache;
|
||||
use blending_data::BlendingData;
|
||||
use pumpkin_data::chunk::Biome;
|
||||
use pumpkin_data::noise_parameter::DoublePerlinNoiseParameters;
|
||||
use pumpkin_util::math::vector3::Vector3;
|
||||
use pumpkin_util::random::xoroshiro128::Xoroshiro;
|
||||
use rustc_hash::FxHashMap;
|
||||
|
||||
pub struct BlendingOutput {
|
||||
pub alpha: f64,
|
||||
pub blending_offset: f64,
|
||||
}
|
||||
|
||||
pub struct Blender {
|
||||
height_and_biome_blending_data: FxHashMap<u64, BlendingData>,
|
||||
density_blending_data: FxHashMap<u64, BlendingData>,
|
||||
}
|
||||
|
||||
const HEIGHT_BLENDING_RANGE_CELLS: i32 = (7 << 2) - 1; // QuartPos.fromSection(7) - 1
|
||||
const HEIGHT_BLENDING_RANGE_CHUNKS: i32 = (HEIGHT_BLENDING_RANGE_CELLS + 3) >> 2; // QuartPos.toSection(...)
|
||||
const DENSITY_BLENDING_RANGE_CELLS: i32 = 2;
|
||||
const DENSITY_BLENDING_RANGE_CHUNKS: i32 = 5 >> 2; // QuartPos.toSection(5)
|
||||
|
||||
impl Blender {
|
||||
#[must_use]
|
||||
pub fn empty() -> Self {
|
||||
Self {
|
||||
height_and_biome_blending_data: FxHashMap::default(),
|
||||
density_blending_data: FxHashMap::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn of<C: GenerationCache>(cache: &C) -> Self {
|
||||
let center_chunk = cache.get_center_chunk();
|
||||
let center_x = center_chunk.x;
|
||||
let center_z = center_chunk.z;
|
||||
|
||||
let mut height_and_biome_data = FxHashMap::default();
|
||||
let mut density_data = FxHashMap::default();
|
||||
|
||||
let max_dist_sq = (HEIGHT_BLENDING_RANGE_CHUNKS + 1) * (HEIGHT_BLENDING_RANGE_CHUNKS + 1);
|
||||
|
||||
for dx in -HEIGHT_BLENDING_RANGE_CHUNKS..=HEIGHT_BLENDING_RANGE_CHUNKS {
|
||||
for dz in -HEIGHT_BLENDING_RANGE_CHUNKS..=HEIGHT_BLENDING_RANGE_CHUNKS {
|
||||
if dx * dx + dz * dz <= max_dist_sq {
|
||||
let chunk_x = center_x + dx;
|
||||
let chunk_z = center_z + dz;
|
||||
|
||||
if let Some(blending_data) = cache.get_blending_data(chunk_x, chunk_z) {
|
||||
let packed = (chunk_x as u32 as u64) | ((chunk_z as u32 as u64) << 32);
|
||||
height_and_biome_data.insert(packed, blending_data.clone());
|
||||
|
||||
if (-DENSITY_BLENDING_RANGE_CHUNKS..=DENSITY_BLENDING_RANGE_CHUNKS)
|
||||
.contains(&dx)
|
||||
&& (-DENSITY_BLENDING_RANGE_CHUNKS..=DENSITY_BLENDING_RANGE_CHUNKS)
|
||||
.contains(&dz)
|
||||
{
|
||||
density_data.insert(packed, blending_data.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if height_and_biome_data.is_empty() && density_data.is_empty() {
|
||||
Self::empty()
|
||||
} else {
|
||||
Self {
|
||||
height_and_biome_blending_data: height_and_biome_data,
|
||||
density_blending_data: density_data,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.height_and_biome_blending_data.is_empty() && self.density_blending_data.is_empty()
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn blend_offset_and_factor(&self, block_x: i32, block_z: i32) -> BlendingOutput {
|
||||
let cell_x = biome_coords::from_block(block_x);
|
||||
let cell_z = biome_coords::from_block(block_z);
|
||||
|
||||
let fixed_height = self.get_blending_data_value(
|
||||
cell_x,
|
||||
0,
|
||||
cell_z,
|
||||
blending_data::BlendingData::get_height,
|
||||
);
|
||||
|
||||
if fixed_height != f64::MAX {
|
||||
return BlendingOutput {
|
||||
alpha: 0.0,
|
||||
blending_offset: Self::height_to_offset(fixed_height),
|
||||
};
|
||||
}
|
||||
|
||||
let mut total_weight = 0.0;
|
||||
let mut weighted_heights = 0.0;
|
||||
let mut closest_distance = f64::INFINITY;
|
||||
|
||||
for (&packed_pos, blending_data) in &self.height_and_biome_blending_data {
|
||||
let chunk_x = (packed_pos & 0xFFFFFFFF) as i32;
|
||||
let chunk_z = (packed_pos >> 32) as i32;
|
||||
|
||||
blending_data.iterate_heights(
|
||||
biome_coords::from_chunk(chunk_x),
|
||||
biome_coords::from_chunk(chunk_z),
|
||||
|test_cell_x, test_cell_z, height| {
|
||||
let dx = (cell_x - test_cell_x) as f64;
|
||||
let dz = (cell_z - test_cell_z) as f64;
|
||||
let distance = dx.hypot(dz);
|
||||
|
||||
if distance <= HEIGHT_BLENDING_RANGE_CELLS as f64 {
|
||||
if distance < closest_distance {
|
||||
closest_distance = distance;
|
||||
}
|
||||
|
||||
let weight = 1.0 / (distance * distance * distance * distance);
|
||||
weighted_heights += height * weight;
|
||||
total_weight += weight;
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
if closest_distance == f64::INFINITY {
|
||||
BlendingOutput {
|
||||
alpha: 1.0,
|
||||
blending_offset: 0.0,
|
||||
}
|
||||
} else {
|
||||
let average_height = weighted_heights / total_weight;
|
||||
let mut alpha =
|
||||
(closest_distance / (HEIGHT_BLENDING_RANGE_CELLS + 1) as f64).clamp(0.0, 1.0);
|
||||
alpha = 3.0 * alpha * alpha - 2.0 * alpha * alpha * alpha;
|
||||
BlendingOutput {
|
||||
alpha,
|
||||
blending_offset: Self::height_to_offset(average_height),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn height_to_offset(height: f64) -> f64 {
|
||||
let target_y = height + 0.5;
|
||||
let target_y_mod = target_y.rem_euclid(8.0);
|
||||
(32.0 * (target_y - 128.0) - 3.0 * (target_y - 120.0) * target_y_mod
|
||||
+ 3.0 * target_y_mod * target_y_mod)
|
||||
/ (128.0 * (32.0 - 3.0 * target_y_mod))
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn blend_density(&self, block_x: i32, block_y: i32, block_z: i32, noise_value: f64) -> f64 {
|
||||
let cell_x = biome_coords::from_block(block_x);
|
||||
let cell_y = block_y / 8;
|
||||
let cell_z = biome_coords::from_block(block_z);
|
||||
|
||||
let fixed_density =
|
||||
self.get_blending_data_value(cell_x, cell_y, cell_z, |data, x, y, z| {
|
||||
data.get_density(x, y, z)
|
||||
});
|
||||
|
||||
if fixed_density != f64::MAX {
|
||||
return fixed_density;
|
||||
}
|
||||
|
||||
let mut total_weight = 0.0;
|
||||
let mut weighted_densities = 0.0;
|
||||
let mut closest_distance = f64::INFINITY;
|
||||
|
||||
for (&packed_pos, blending_data) in &self.density_blending_data {
|
||||
let chunk_x = (packed_pos & 0xFFFFFFFF) as i32;
|
||||
let chunk_z = (packed_pos >> 32) as i32;
|
||||
|
||||
blending_data.iterate_densities(
|
||||
biome_coords::from_chunk(chunk_x),
|
||||
biome_coords::from_chunk(chunk_z),
|
||||
cell_y - 1,
|
||||
cell_y + 1,
|
||||
|test_cell_x, test_cell_y, test_cell_z, density| {
|
||||
let dx = (cell_x - test_cell_x) as f64;
|
||||
let dy = ((cell_y - test_cell_y) * 2) as f64;
|
||||
let dz = (cell_z - test_cell_z) as f64;
|
||||
let distance = (dx * dx + dy * dy + dz * dz).sqrt();
|
||||
|
||||
if distance <= 2.0 {
|
||||
if distance < closest_distance {
|
||||
closest_distance = distance;
|
||||
}
|
||||
|
||||
let weight = 1.0 / (distance * distance * distance * distance);
|
||||
weighted_densities += density * weight;
|
||||
total_weight += weight;
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
if closest_distance == f64::INFINITY {
|
||||
noise_value
|
||||
} else {
|
||||
let average_density = weighted_densities / total_weight;
|
||||
let alpha = (closest_distance / 3.0).clamp(0.0, 1.0);
|
||||
alpha * noise_value + (1.0 - alpha) * average_density
|
||||
}
|
||||
}
|
||||
|
||||
fn get_blending_data_value<F>(&self, cell_x: i32, cell_y: i32, cell_z: i32, getter: F) -> f64
|
||||
where
|
||||
F: Fn(&BlendingData, i32, i32, i32) -> f64,
|
||||
{
|
||||
let chunk_x = biome_coords::to_chunk(cell_x);
|
||||
let chunk_z = biome_coords::to_chunk(cell_z);
|
||||
let min_x = cell_x.trailing_zeros() >= 2;
|
||||
let min_z = cell_z.trailing_zeros() >= 2;
|
||||
|
||||
let mut value = self.get_data_value(&getter, chunk_x, chunk_z, cell_x, cell_y, cell_z);
|
||||
if value == f64::MAX {
|
||||
if min_x && min_z {
|
||||
value =
|
||||
self.get_data_value(&getter, chunk_x - 1, chunk_z - 1, cell_x, cell_y, cell_z);
|
||||
}
|
||||
|
||||
if value == f64::MAX {
|
||||
if min_x {
|
||||
value =
|
||||
self.get_data_value(&getter, chunk_x - 1, chunk_z, cell_x, cell_y, cell_z);
|
||||
}
|
||||
|
||||
if value == f64::MAX && min_z {
|
||||
value =
|
||||
self.get_data_value(&getter, chunk_x, chunk_z - 1, cell_x, cell_y, cell_z);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
value
|
||||
}
|
||||
|
||||
fn get_data_value<F>(
|
||||
&self,
|
||||
getter: &F,
|
||||
chunk_x: i32,
|
||||
chunk_z: i32,
|
||||
cell_x: i32,
|
||||
cell_y: i32,
|
||||
cell_z: i32,
|
||||
) -> f64
|
||||
where
|
||||
F: Fn(&BlendingData, i32, i32, i32) -> f64,
|
||||
{
|
||||
let packed = (chunk_x as u32 as u64) | ((chunk_z as u32 as u64) << 32);
|
||||
self.height_and_biome_blending_data
|
||||
.get(&packed)
|
||||
.map_or(f64::MAX, |data| {
|
||||
getter(
|
||||
data,
|
||||
cell_x - biome_coords::from_chunk(chunk_x),
|
||||
cell_y,
|
||||
cell_z - biome_coords::from_chunk(chunk_z),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn blend_biome(
|
||||
&self,
|
||||
quart_x: i32,
|
||||
quart_y: i32,
|
||||
quart_z: i32,
|
||||
shift_noise: &DoublePerlinNoiseSampler,
|
||||
) -> Option<&'static Biome> {
|
||||
let mut closest_distance = f64::INFINITY;
|
||||
let mut closest_biome = None;
|
||||
|
||||
for (&packed_pos, blending_data) in &self.height_and_biome_blending_data {
|
||||
let chunk_x = (packed_pos & 0xFFFFFFFF) as i32;
|
||||
let chunk_z = (packed_pos >> 32) as i32;
|
||||
|
||||
blending_data.iterate_biomes(
|
||||
biome_coords::from_chunk(chunk_x),
|
||||
quart_y,
|
||||
biome_coords::from_chunk(chunk_z),
|
||||
|test_cell_x, test_cell_z, biome| {
|
||||
let dx = (quart_x - test_cell_x) as f64;
|
||||
let dz = (quart_z - test_cell_z) as f64;
|
||||
let distance = dx.hypot(dz);
|
||||
|
||||
if distance <= HEIGHT_BLENDING_RANGE_CELLS as f64 && distance < closest_distance
|
||||
{
|
||||
closest_biome = Some(biome);
|
||||
closest_distance = distance;
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
if closest_distance == f64::INFINITY {
|
||||
None
|
||||
} else {
|
||||
let shift = shift_noise.sample(quart_x as f64, 0.0, quart_z as f64) * 12.0;
|
||||
let alpha = ((closest_distance + shift) / (HEIGHT_BLENDING_RANGE_CELLS + 1) as f64)
|
||||
.clamp(0.0, 1.0);
|
||||
if alpha > 0.5 { None } else { closest_biome }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct BlenderBiomeSupplier<'a> {
|
||||
base: &'a dyn BiomeSupplier,
|
||||
blender: &'a Blender,
|
||||
shift_noise: DoublePerlinNoiseSampler,
|
||||
}
|
||||
|
||||
impl BiomeSupplier for BlenderBiomeSupplier<'_> {
|
||||
fn biome(&self, x: i32, y: i32, z: i32, sampler: &mut MultiNoiseSampler<'_>) -> &'static Biome {
|
||||
self.blender
|
||||
.blend_biome(x, y, z, &self.shift_noise)
|
||||
.unwrap_or_else(|| self.base.biome(x, y, z, sampler))
|
||||
}
|
||||
}
|
||||
|
||||
pub trait BlenderImpl {
|
||||
fn blend_offset_and_factor(&self, block_x: i32, block_z: i32) -> BlendingOutput;
|
||||
|
||||
fn blend_density(&self, pos: &Vector3<i32>, density: f64) -> f64;
|
||||
|
||||
fn get_biome_supplier<'a>(
|
||||
&'a self,
|
||||
supplier: &'a dyn BiomeSupplier,
|
||||
) -> BlenderBiomeSupplier<'a>;
|
||||
}
|
||||
|
||||
impl BlenderImpl for Blender {
|
||||
fn blend_offset_and_factor(&self, block_x: i32, block_z: i32) -> BlendingOutput {
|
||||
self.blend_offset_and_factor(block_x, block_z)
|
||||
}
|
||||
|
||||
fn blend_density(&self, pos: &Vector3<i32>, density: f64) -> f64 {
|
||||
self.blend_density(pos.x, pos.y, pos.z, density)
|
||||
}
|
||||
|
||||
fn get_biome_supplier<'a>(
|
||||
&'a self,
|
||||
supplier: &'a dyn BiomeSupplier,
|
||||
) -> BlenderBiomeSupplier<'a> {
|
||||
let mut random = Xoroshiro::from_seed(42);
|
||||
let shift_noise = DoublePerlinNoiseSampler::from_params(
|
||||
&mut random,
|
||||
&DoublePerlinNoiseParameters::OFFSET,
|
||||
false,
|
||||
);
|
||||
BlenderBiomeSupplier {
|
||||
base: supplier,
|
||||
blender: self,
|
||||
shift_noise,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
use itertools::Itertools;
|
||||
use pumpkin_data::fluid::{Fluid, FluidState};
|
||||
use pumpkin_data::tag::{self};
|
||||
use pumpkin_data::{Block, BlockDirection, BlockState, BlockStateId};
|
||||
use pumpkin_util::math::{position::BlockPos, vector3::Vector3};
|
||||
|
||||
use crate::generation::proto_chunk::GenerationCache;
|
||||
use crate::{block::BlockStateCodec, world::WorldPortalExt};
|
||||
|
||||
pub enum BlockPredicate {
|
||||
MatchingBlocks(MatchingBlocksBlockPredicate),
|
||||
MatchingBlockTag(MatchingBlockTagPredicate),
|
||||
MatchingFluids(MatchingFluidsBlockPredicate),
|
||||
HasSturdyFace(HasSturdyFacePredicate),
|
||||
Solid(SolidBlockPredicate),
|
||||
Replaceable(ReplaceableBlockPredicate),
|
||||
WouldSurvive(WouldSurviveBlockPredicate),
|
||||
InsideWorldBounds(InsideWorldBoundsBlockPredicate),
|
||||
AnyOf(AnyOfBlockPredicate),
|
||||
AllOf(AllOfBlockPredicate),
|
||||
Not(NotBlockPredicate),
|
||||
AlwaysTrue,
|
||||
// Not used
|
||||
// // Unobstructed(EmptyTODOStruct),
|
||||
}
|
||||
|
||||
impl BlockPredicate {
|
||||
pub fn test<T: GenerationCache>(
|
||||
&self,
|
||||
block_registry: &dyn WorldPortalExt,
|
||||
chunk: &T,
|
||||
pos: &BlockPos,
|
||||
) -> bool {
|
||||
match self {
|
||||
Self::MatchingBlocks(predicate) => predicate.test(chunk, pos),
|
||||
Self::MatchingBlockTag(predicate) => predicate.test(chunk, pos),
|
||||
Self::MatchingFluids(predicate) => predicate.test(chunk, pos),
|
||||
Self::HasSturdyFace(predicate) => predicate.test(chunk, pos),
|
||||
Self::Solid(predicate) => predicate.test(chunk, pos),
|
||||
Self::Replaceable(predicate) => predicate.test(chunk, pos),
|
||||
Self::WouldSurvive(predicate) => predicate.test(block_registry, chunk, pos),
|
||||
Self::InsideWorldBounds(predicate) => predicate.test(chunk, pos),
|
||||
Self::AnyOf(predicate) => predicate.test(block_registry, chunk, pos),
|
||||
Self::AllOf(predicate) => predicate.test(block_registry, chunk, pos),
|
||||
Self::Not(predicate) => predicate.test(block_registry, chunk, pos),
|
||||
Self::AlwaysTrue => true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct MatchingBlocksBlockPredicate {
|
||||
pub offset: OffsetBlocksBlockPredicate,
|
||||
pub blocks: MatchingBlocksWrapper,
|
||||
}
|
||||
|
||||
impl MatchingBlocksBlockPredicate {
|
||||
pub fn test<T: GenerationCache>(&self, chunk: &T, pos: &BlockPos) -> bool {
|
||||
let block = self.offset.get_block(chunk, pos);
|
||||
match &self.blocks {
|
||||
MatchingBlocksWrapper::Single(single_block) => {
|
||||
single_block.strip_prefix("minecraft:").unwrap() == block.name
|
||||
}
|
||||
MatchingBlocksWrapper::Multiple(blocks) => blocks
|
||||
.iter()
|
||||
.map(|s| s.strip_prefix("minecraft:").unwrap())
|
||||
.contains(block.name),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct InsideWorldBoundsBlockPredicate {
|
||||
pub offset: Vector3<i32>,
|
||||
}
|
||||
|
||||
impl InsideWorldBoundsBlockPredicate {
|
||||
pub fn test<T: GenerationCache>(&self, chunk: &T, pos: &BlockPos) -> bool {
|
||||
let pos = pos.offset(self.offset);
|
||||
!chunk.out_of_height(pos.0.y as i16)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct MatchingFluidsBlockPredicate {
|
||||
pub offset: OffsetBlocksBlockPredicate,
|
||||
pub fluids: MatchingBlocksWrapper,
|
||||
}
|
||||
|
||||
impl MatchingFluidsBlockPredicate {
|
||||
pub fn test<T: GenerationCache>(&self, chunk: &T, pos: &BlockPos) -> bool {
|
||||
let (fluid, _) = self.offset.get_fluid_and_fluid_state(chunk, pos);
|
||||
match &self.fluids {
|
||||
MatchingBlocksWrapper::Single(single_block) => {
|
||||
single_block.strip_prefix("minecraft:").unwrap() == fluid.name
|
||||
}
|
||||
MatchingBlocksWrapper::Multiple(blocks) => blocks
|
||||
.iter()
|
||||
.map(|s| s.strip_prefix("minecraft:").unwrap())
|
||||
.contains(fluid.name),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct MatchingBlockTagPredicate {
|
||||
pub offset: OffsetBlocksBlockPredicate,
|
||||
pub tag: tag::Tag,
|
||||
}
|
||||
|
||||
impl MatchingBlockTagPredicate {
|
||||
pub fn test<T: GenerationCache>(&self, chunk: &T, pos: &BlockPos) -> bool {
|
||||
let state = self.offset.get_id(chunk, pos);
|
||||
state.to_block_id().has_tag(self.tag)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct HasSturdyFacePredicate {
|
||||
pub offset: OffsetBlocksBlockPredicate,
|
||||
pub direction: BlockDirection,
|
||||
}
|
||||
|
||||
impl HasSturdyFacePredicate {
|
||||
pub fn test<T: GenerationCache>(&self, chunk: &T, pos: &BlockPos) -> bool {
|
||||
let state = self.offset.get_state(chunk, pos);
|
||||
state.is_side_solid(self.direction)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct AnyOfBlockPredicate {
|
||||
pub predicates: Vec<BlockPredicate>,
|
||||
}
|
||||
|
||||
impl AnyOfBlockPredicate {
|
||||
pub fn test<T: GenerationCache>(
|
||||
&self,
|
||||
block_registry: &dyn WorldPortalExt,
|
||||
chunk: &T,
|
||||
pos: &BlockPos,
|
||||
) -> bool {
|
||||
for predicate in &self.predicates {
|
||||
if !predicate.test(block_registry, chunk, pos) {
|
||||
continue;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
pub struct AllOfBlockPredicate {
|
||||
pub predicates: Vec<BlockPredicate>,
|
||||
}
|
||||
|
||||
impl AllOfBlockPredicate {
|
||||
pub fn test<T: GenerationCache>(
|
||||
&self,
|
||||
block_registry: &dyn WorldPortalExt,
|
||||
chunk: &T,
|
||||
pos: &BlockPos,
|
||||
) -> bool {
|
||||
for predicate in &self.predicates {
|
||||
if predicate.test(block_registry, chunk, pos) {
|
||||
continue;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
pub struct NotBlockPredicate {
|
||||
pub predicate: Box<BlockPredicate>,
|
||||
}
|
||||
|
||||
impl NotBlockPredicate {
|
||||
pub fn test<T: GenerationCache>(
|
||||
&self,
|
||||
block_registry: &dyn WorldPortalExt,
|
||||
chunk: &T,
|
||||
pos: &BlockPos,
|
||||
) -> bool {
|
||||
!self.predicate.test(block_registry, chunk, pos)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct SolidBlockPredicate {
|
||||
pub offset: OffsetBlocksBlockPredicate,
|
||||
}
|
||||
|
||||
impl SolidBlockPredicate {
|
||||
pub fn test<T: GenerationCache>(&self, chunk: &T, pos: &BlockPos) -> bool {
|
||||
let state = self.offset.get_state(chunk, pos);
|
||||
state.is_solid()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct WouldSurviveBlockPredicate {
|
||||
pub offset: OffsetBlocksBlockPredicate,
|
||||
pub state: BlockStateCodec,
|
||||
}
|
||||
|
||||
impl WouldSurviveBlockPredicate {
|
||||
pub fn test<T: GenerationCache>(
|
||||
&self,
|
||||
block_registry: &dyn WorldPortalExt,
|
||||
chunk: &T,
|
||||
pos: &BlockPos,
|
||||
) -> bool {
|
||||
let block = self.state.get_block();
|
||||
let state = self.state.get_state();
|
||||
|
||||
let pos = self.offset.get(pos);
|
||||
block_registry.can_place_at(block, state, chunk, &pos)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ReplaceableBlockPredicate {
|
||||
pub offset: OffsetBlocksBlockPredicate,
|
||||
}
|
||||
|
||||
impl ReplaceableBlockPredicate {
|
||||
pub fn test<T: GenerationCache>(&self, chunk: &T, pos: &BlockPos) -> bool {
|
||||
let state = self.offset.get_state(chunk, pos);
|
||||
state.replaceable()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct OffsetBlocksBlockPredicate {
|
||||
pub offset: Option<Vector3<i32>>,
|
||||
}
|
||||
|
||||
impl OffsetBlocksBlockPredicate {
|
||||
pub fn get(&self, pos: &BlockPos) -> BlockPos {
|
||||
if let Some(offset) = self.offset {
|
||||
return pos.offset(offset);
|
||||
}
|
||||
*pos
|
||||
}
|
||||
pub fn get_id<T: GenerationCache>(&self, chunk: &T, pos: &BlockPos) -> BlockStateId {
|
||||
let pos = self.get(pos);
|
||||
GenerationCache::get_block_state(chunk, &pos.0)
|
||||
}
|
||||
|
||||
pub fn get_block<T: GenerationCache>(&self, chunk: &T, pos: &BlockPos) -> &'static Block {
|
||||
let pos = self.get(pos);
|
||||
GenerationCache::get_block_state(chunk, &pos.0).to_block()
|
||||
}
|
||||
|
||||
pub fn get_fluid_and_fluid_state<T: GenerationCache>(
|
||||
&self,
|
||||
chunk: &T,
|
||||
pos: &BlockPos,
|
||||
) -> (Fluid, FluidState) {
|
||||
let pos = self.get(pos);
|
||||
GenerationCache::get_fluid_and_fluid_state(chunk, &pos.0)
|
||||
}
|
||||
|
||||
pub fn get_state<T: GenerationCache>(&self, chunk: &T, pos: &BlockPos) -> &'static BlockState {
|
||||
let pos = self.get(pos);
|
||||
GenerationCache::get_block_state(chunk, &pos.0).to_state()
|
||||
}
|
||||
}
|
||||
|
||||
pub enum MatchingBlocksWrapper {
|
||||
Single(String),
|
||||
Multiple(Vec<String>),
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
use pumpkin_data::BlockState;
|
||||
use pumpkin_util::{
|
||||
DoublePerlinNoiseParametersCodec,
|
||||
math::{
|
||||
clamped_map,
|
||||
int_provider::IntProvider,
|
||||
pool::{Pool, Weighted},
|
||||
position::BlockPos,
|
||||
},
|
||||
random::{RandomGenerator, RandomImpl, legacy_rand::LegacyRand},
|
||||
};
|
||||
|
||||
use super::noise::perlin::DoublePerlinNoiseSampler;
|
||||
use crate::generation::block_predicate::BlockPredicate;
|
||||
use crate::generation::proto_chunk::GenerationCache;
|
||||
use crate::world::WorldPortalExt;
|
||||
|
||||
pub enum BlockStateProvider {
|
||||
Simple(SimpleStateProvider),
|
||||
Weighted(WeightedBlockStateProvider),
|
||||
NoiseThreshold(NoiseThresholdBlockStateProvider),
|
||||
NoiseProvider(NoiseBlockStateProvider),
|
||||
DualNoise(DualNoiseBlockStateProvider),
|
||||
Pillar(PillarBlockStateProvider),
|
||||
RandomizedInt(RandomizedIntBlockStateProvider),
|
||||
Rule(RuleBasedBlockStateProvider),
|
||||
}
|
||||
|
||||
impl BlockStateProvider {
|
||||
pub fn get<T: GenerationCache>(
|
||||
&self,
|
||||
random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
chunk: &T,
|
||||
block_registry: &dyn WorldPortalExt,
|
||||
) -> &'static BlockState {
|
||||
match self {
|
||||
Self::NoiseThreshold(provider) => provider.get(random, pos),
|
||||
Self::NoiseProvider(provider) => provider.get(pos),
|
||||
Self::Simple(provider) => provider.get(pos),
|
||||
Self::Weighted(provider) => provider.get(random),
|
||||
Self::DualNoise(provider) => provider.get(pos),
|
||||
Self::Pillar(provider) => provider.get(pos),
|
||||
Self::RandomizedInt(provider) => provider.get(random, pos, chunk, block_registry),
|
||||
Self::Rule(provider) => provider.get(block_registry, chunk, random, pos),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_with_context<T: GenerationCache>(
|
||||
&self,
|
||||
block_registry: &dyn WorldPortalExt,
|
||||
chunk: &T,
|
||||
random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> &'static BlockState {
|
||||
match self {
|
||||
Self::Rule(provider) => provider.get(block_registry, chunk, random, pos),
|
||||
_ => self.get(random, pos, chunk, block_registry),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_optional<T: GenerationCache>(
|
||||
&self,
|
||||
block_registry: &dyn WorldPortalExt,
|
||||
chunk: &T,
|
||||
random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> Option<&'static BlockState> {
|
||||
match self {
|
||||
Self::Rule(provider) => provider.get_optional(block_registry, chunk, random, pos),
|
||||
_ => Some(self.get(random, pos, chunk, block_registry)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct RuleBasedBlockStateProvider {
|
||||
pub fallback: Option<Box<BlockStateProvider>>,
|
||||
pub rules: Vec<BlockStateRule>,
|
||||
}
|
||||
|
||||
impl RuleBasedBlockStateProvider {
|
||||
pub fn get<T: GenerationCache>(
|
||||
&self,
|
||||
block_registry: &dyn WorldPortalExt,
|
||||
chunk: &T,
|
||||
random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> &'static BlockState {
|
||||
if let Some(optional) = self.get_optional(block_registry, chunk, random, pos) {
|
||||
return optional;
|
||||
}
|
||||
GenerationCache::get_block_state(chunk, &pos.0).to_state()
|
||||
}
|
||||
pub fn get_optional<T: GenerationCache>(
|
||||
&self,
|
||||
block_registry: &dyn WorldPortalExt,
|
||||
chunk: &T,
|
||||
random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> Option<&'static BlockState> {
|
||||
for rule in &self.rules {
|
||||
if rule.if_true.test(block_registry, chunk, &pos) {
|
||||
return Some(
|
||||
rule.then
|
||||
.get_with_context(block_registry, chunk, random, pos),
|
||||
);
|
||||
}
|
||||
}
|
||||
self.fallback
|
||||
.as_ref()
|
||||
.map(|f| f.get(random, pos, chunk, block_registry))
|
||||
}
|
||||
}
|
||||
|
||||
pub struct BlockStateRule {
|
||||
pub if_true: BlockPredicate,
|
||||
pub then: BlockStateProvider,
|
||||
}
|
||||
|
||||
pub struct RandomizedIntBlockStateProvider {
|
||||
pub source: Box<BlockStateProvider>,
|
||||
pub property: String,
|
||||
pub values: IntProvider,
|
||||
}
|
||||
|
||||
impl RandomizedIntBlockStateProvider {
|
||||
pub fn get<T: GenerationCache>(
|
||||
&self,
|
||||
random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
chunk: &T,
|
||||
block_registry: &dyn WorldPortalExt,
|
||||
) -> &'static BlockState {
|
||||
// TODO
|
||||
self.source.get(random, pos, chunk, block_registry)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct PillarBlockStateProvider {
|
||||
pub state: &'static BlockState,
|
||||
}
|
||||
|
||||
impl PillarBlockStateProvider {
|
||||
pub const fn get(&self, _pos: BlockPos) -> &'static BlockState {
|
||||
// TODO: random axis
|
||||
self.state
|
||||
}
|
||||
}
|
||||
|
||||
pub struct DualNoiseBlockStateProvider {
|
||||
pub base: NoiseBlockStateProvider,
|
||||
pub variety: [u32; 2],
|
||||
pub slow_noise: DoublePerlinNoiseParametersCodec,
|
||||
pub slow_scale: f64,
|
||||
}
|
||||
|
||||
impl DualNoiseBlockStateProvider {
|
||||
pub fn get(&self, pos: BlockPos) -> &'static BlockState {
|
||||
let sampler = DoublePerlinNoiseSampler::new(
|
||||
&mut RandomGenerator::Legacy(LegacyRand::from_seed(self.base.base.seed as u64)),
|
||||
self.slow_noise.first_octave,
|
||||
&self.slow_noise.amplitudes,
|
||||
self.slow_noise.amplitude,
|
||||
false,
|
||||
);
|
||||
let slow_noise =
|
||||
self.get_slow_noise(pos.0.x as f64, pos.0.y as f64, pos.0.z as f64, &sampler);
|
||||
let mapped = clamped_map(
|
||||
slow_noise,
|
||||
-1.0,
|
||||
1.0,
|
||||
self.variety[0] as f64,
|
||||
self.variety[1] as f64 + 1.0,
|
||||
) as i32;
|
||||
let mut list = Vec::with_capacity(mapped as usize);
|
||||
for i in 0..mapped {
|
||||
let value = self.get_slow_noise(i as f64 * 54545.0, 0.0, i as f64 * 34234.0, &sampler);
|
||||
list.push(NoiseBlockStateProvider::get_state_by_value(
|
||||
&self.base.states,
|
||||
value,
|
||||
));
|
||||
}
|
||||
let value = self.base.base.get_noise(pos);
|
||||
NoiseBlockStateProvider::get_state_by_value(&list, value)
|
||||
}
|
||||
|
||||
fn get_slow_noise(&self, x: f64, y: f64, z: f64, sampler: &DoublePerlinNoiseSampler) -> f64 {
|
||||
sampler.sample(
|
||||
x * self.slow_scale,
|
||||
y * self.slow_scale,
|
||||
z * self.slow_scale,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct WeightedBlockStateProvider {
|
||||
pub entries: Vec<Weighted<&'static BlockState>>,
|
||||
}
|
||||
|
||||
impl WeightedBlockStateProvider {
|
||||
pub fn get(&self, random: &mut RandomGenerator) -> &'static BlockState {
|
||||
Pool::get(&self.entries, random).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct SimpleStateProvider {
|
||||
pub state: &'static BlockState,
|
||||
}
|
||||
|
||||
impl SimpleStateProvider {
|
||||
pub const fn get(&self, _pos: BlockPos) -> &'static BlockState {
|
||||
self.state
|
||||
}
|
||||
}
|
||||
|
||||
pub struct NoiseBlockStateProviderBase {
|
||||
pub seed: i64,
|
||||
pub noise: DoublePerlinNoiseParametersCodec,
|
||||
pub scale: f32,
|
||||
}
|
||||
|
||||
impl NoiseBlockStateProviderBase {
|
||||
pub fn get_noise(&self, pos: BlockPos) -> f64 {
|
||||
let sampler = DoublePerlinNoiseSampler::new(
|
||||
&mut RandomGenerator::Legacy(LegacyRand::from_seed(self.seed as u64)),
|
||||
self.noise.first_octave,
|
||||
&self.noise.amplitudes,
|
||||
self.noise.amplitude,
|
||||
false,
|
||||
);
|
||||
sampler.sample(
|
||||
pos.0.x as f64 * self.scale as f64,
|
||||
pos.0.y as f64 * self.scale as f64,
|
||||
pos.0.z as f64 * self.scale as f64,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct NoiseBlockStateProvider {
|
||||
pub base: NoiseBlockStateProviderBase,
|
||||
pub states: Vec<&'static BlockState>,
|
||||
}
|
||||
|
||||
impl NoiseBlockStateProvider {
|
||||
pub fn get(&self, pos: BlockPos) -> &'static BlockState {
|
||||
let value = self.base.get_noise(pos);
|
||||
Self::get_state_by_value(&self.states, value)
|
||||
}
|
||||
|
||||
fn get_state_by_value(states: &[&'static BlockState], value: f64) -> &'static BlockState {
|
||||
let val = f64::midpoint(1.0, value).clamp(0.0, 0.9999);
|
||||
states[(val * states.len() as f64) as usize]
|
||||
}
|
||||
}
|
||||
|
||||
pub struct NoiseThresholdBlockStateProvider {
|
||||
pub base: NoiseBlockStateProviderBase,
|
||||
pub threshold: f32,
|
||||
pub high_chance: f32,
|
||||
pub default_state: &'static BlockState,
|
||||
pub low_states: Vec<&'static BlockState>,
|
||||
pub high_states: Vec<&'static BlockState>,
|
||||
}
|
||||
|
||||
impl NoiseThresholdBlockStateProvider {
|
||||
pub fn get(&self, random: &mut RandomGenerator, pos: BlockPos) -> &'static BlockState {
|
||||
let value = self.base.get_noise(pos);
|
||||
if value < self.threshold as f64 {
|
||||
return self.low_states[random.next_bounded_i32(self.low_states.len() as i32) as usize];
|
||||
}
|
||||
if random.next_f32() < self.high_chance {
|
||||
return self.high_states
|
||||
[random.next_bounded_i32(self.high_states.len() as i32) as usize];
|
||||
}
|
||||
self.default_state
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,324 @@
|
||||
use super::cave::get_height;
|
||||
use super::{CarveRun, Carver, overworld_carve_state, place_carved_block};
|
||||
use pumpkin_data::carver::{CarverAdditionalConfig, CarverConfig};
|
||||
use pumpkin_util::math::vector2::Vector2;
|
||||
use pumpkin_util::random::{RandomGenerator, RandomImpl};
|
||||
use std::f32::consts::PI;
|
||||
|
||||
pub struct CanyonCarver;
|
||||
|
||||
impl Carver for CanyonCarver {
|
||||
fn carve(
|
||||
&self,
|
||||
config: &CarverConfig,
|
||||
run: &mut CarveRun,
|
||||
random: &mut RandomGenerator,
|
||||
_chunk_pos: &Vector2<i32>,
|
||||
carver_chunk_pos: &Vector2<i32>,
|
||||
legacy_random_source: bool,
|
||||
) {
|
||||
let CarverAdditionalConfig::Canyon(ref canyon_config) = config.additional else {
|
||||
return;
|
||||
};
|
||||
|
||||
let min_y = run.chunk.bottom_y() as i32;
|
||||
let height = run.chunk.height();
|
||||
|
||||
let max_distance = (4 * 2 - 1) * 16;
|
||||
|
||||
let x = (carver_chunk_pos.x << 4) + random.next_bounded_i32(16);
|
||||
let y = get_height(&config.y, random, min_y as i8, height);
|
||||
let z = (carver_chunk_pos.y << 4) + random.next_bounded_i32(16);
|
||||
|
||||
let horizontal_rotation = random.next_f32() * PI * 2.0;
|
||||
let vertical_rotation = canyon_config.vertical_rotation.get(random);
|
||||
let y_scale = config.y_scale.get(random) as f64;
|
||||
let thickness = canyon_config.shape.thickness.get(random);
|
||||
let distance =
|
||||
(max_distance as f32 * canyon_config.shape.distance_factor.get(random)) as i32;
|
||||
|
||||
Self::do_carve(
|
||||
config,
|
||||
run,
|
||||
random.next_i64(),
|
||||
x as f64,
|
||||
y as f64,
|
||||
z as f64,
|
||||
thickness,
|
||||
horizontal_rotation,
|
||||
vertical_rotation,
|
||||
0,
|
||||
distance,
|
||||
y_scale,
|
||||
legacy_random_source,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
impl CanyonCarver {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn do_carve(
|
||||
config: &CarverConfig,
|
||||
run: &mut CarveRun,
|
||||
tunnel_seed: i64,
|
||||
mut x: f64,
|
||||
mut y: f64,
|
||||
mut z: f64,
|
||||
thickness: f32,
|
||||
mut horizontal_rotation: f32,
|
||||
mut vertical_rotation: f32,
|
||||
step: i32,
|
||||
distance: i32,
|
||||
y_scale: f64,
|
||||
legacy_random_source: bool,
|
||||
) {
|
||||
let mut random = super::new_carver_random(tunnel_seed as u64, legacy_random_source);
|
||||
let width_factor_per_height =
|
||||
Self::init_width_factors(run.chunk.height() as usize, config, &mut random);
|
||||
let mut y_rota = 0.0f32;
|
||||
let mut x_rota = 0.0f32;
|
||||
|
||||
let CarverAdditionalConfig::Canyon(ref canyon_config) = config.additional else {
|
||||
return;
|
||||
};
|
||||
|
||||
for current_step in step..distance {
|
||||
let progress = current_step as f32 * PI / distance as f32;
|
||||
let mut horizontal_radius =
|
||||
1.5 + f64::from(pumpkin_util::math::sin(progress) * thickness);
|
||||
let mut vertical_radius = horizontal_radius * y_scale;
|
||||
horizontal_radius *= canyon_config
|
||||
.shape
|
||||
.horizontal_radius_factor
|
||||
.get(&mut random) as f64;
|
||||
vertical_radius = Self::update_vertical_radius(
|
||||
config,
|
||||
&mut random,
|
||||
vertical_radius,
|
||||
distance as f32,
|
||||
current_step as f32,
|
||||
);
|
||||
|
||||
let xc = pumpkin_util::math::cos(vertical_rotation);
|
||||
let xs = pumpkin_util::math::sin(vertical_rotation);
|
||||
x += f64::from(pumpkin_util::math::cos(horizontal_rotation) * xc);
|
||||
y += xs as f64;
|
||||
z += f64::from(pumpkin_util::math::sin(horizontal_rotation) * xc);
|
||||
|
||||
vertical_rotation *= 0.7;
|
||||
vertical_rotation += x_rota * 0.05;
|
||||
horizontal_rotation += y_rota * 0.05;
|
||||
x_rota *= 0.8;
|
||||
y_rota *= 0.5;
|
||||
x_rota += (random.next_f32() - random.next_f32()) * random.next_f32() * 2.0;
|
||||
y_rota += (random.next_f32() - random.next_f32()) * random.next_f32() * 4.0;
|
||||
|
||||
if random.next_bounded_i32(4) != 0 {
|
||||
if !Self::can_reach(
|
||||
run.chunk.x,
|
||||
run.chunk.z,
|
||||
x,
|
||||
z,
|
||||
current_step,
|
||||
distance,
|
||||
thickness,
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
Self::carve_ellipsoid(
|
||||
run,
|
||||
config,
|
||||
x,
|
||||
y,
|
||||
z,
|
||||
horizontal_radius,
|
||||
vertical_radius,
|
||||
&width_factor_per_height,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn init_width_factors(
|
||||
depth: usize,
|
||||
config: &CarverConfig,
|
||||
random: &mut RandomGenerator,
|
||||
) -> Vec<f32> {
|
||||
let CarverAdditionalConfig::Canyon(ref canyon_config) = config.additional else {
|
||||
return vec![1.0; depth];
|
||||
};
|
||||
let mut width_factor_per_height = vec![0.0; depth];
|
||||
let mut width_factor = 1.0f32;
|
||||
|
||||
for (y_index, item) in width_factor_per_height.iter_mut().enumerate() {
|
||||
if y_index == 0 || random.next_bounded_i32(canyon_config.shape.width_smoothness) == 0 {
|
||||
width_factor = 1.0 + random.next_f32() * random.next_f32();
|
||||
}
|
||||
*item = width_factor * width_factor;
|
||||
}
|
||||
width_factor_per_height
|
||||
}
|
||||
|
||||
fn update_vertical_radius(
|
||||
config: &CarverConfig,
|
||||
random: &mut RandomGenerator,
|
||||
vertical_radius: f64,
|
||||
distance: f32,
|
||||
current_step: f32,
|
||||
) -> f64 {
|
||||
let CarverAdditionalConfig::Canyon(ref canyon_config) = config.additional else {
|
||||
return vertical_radius;
|
||||
};
|
||||
let vertical_multiplier = 1.0 - (0.5 - current_step / distance).abs() * 2.0;
|
||||
let factor = canyon_config.shape.vertical_radius_default_factor
|
||||
+ canyon_config.shape.vertical_radius_center_factor * vertical_multiplier;
|
||||
factor as f64 * vertical_radius * random.next_inbetween_f32(0.75, 1.0) as f64
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn can_reach(
|
||||
chunk_x: i32,
|
||||
chunk_z: i32,
|
||||
x: f64,
|
||||
z: f64,
|
||||
step: i32,
|
||||
distance: i32,
|
||||
thickness: f32,
|
||||
) -> bool {
|
||||
let chunk_middle_x = (chunk_x << 4) + 8;
|
||||
let chunk_middle_z = (chunk_z << 4) + 8;
|
||||
let dx = x - chunk_middle_x as f64;
|
||||
let dz = z - chunk_middle_z as f64;
|
||||
let remaining = (distance - step) as f64;
|
||||
let rr = (thickness + 2.0 + 16.0) as f64;
|
||||
dx * dx + dz * dz - remaining * remaining <= rr * rr
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn carve_ellipsoid(
|
||||
run: &mut CarveRun,
|
||||
config: &CarverConfig,
|
||||
x: f64,
|
||||
y: f64,
|
||||
z: f64,
|
||||
horizontal_radius: f64,
|
||||
vertical_radius: f64,
|
||||
width_factor_per_height: &[f32],
|
||||
) {
|
||||
let center_x = (run.chunk.x << 4) as f64 + 8.0;
|
||||
let center_z = (run.chunk.z << 4) as f64 + 8.0;
|
||||
let max_delta = 16.0 + horizontal_radius * 2.0;
|
||||
|
||||
if (x - center_x).abs() > max_delta || (z - center_z).abs() > max_delta {
|
||||
return;
|
||||
}
|
||||
|
||||
let chunk_min_x = run.chunk.x << 4;
|
||||
let chunk_min_z = run.chunk.z << 4;
|
||||
|
||||
let x_index_min = ((x - horizontal_radius).floor() as i32 - chunk_min_x - 1).max(0);
|
||||
let x_index_max = ((x + horizontal_radius).floor() as i32 - chunk_min_x).min(15);
|
||||
|
||||
let min_y = ((y - vertical_radius).floor() as i32 - 1).max(run.chunk.bottom_y() as i32 + 1);
|
||||
let protected_blocks_on_top = 7;
|
||||
let max_y = ((y + vertical_radius).floor() as i32 + 1).min(
|
||||
run.chunk.bottom_y() as i32 + run.chunk.height() as i32 - 1 - protected_blocks_on_top,
|
||||
);
|
||||
|
||||
let z_index_min = ((z - horizontal_radius).floor() as i32 - chunk_min_z - 1).max(0);
|
||||
let z_index_max = ((z + horizontal_radius).floor() as i32 - chunk_min_z).min(15);
|
||||
|
||||
for x_index in x_index_min..=x_index_max {
|
||||
let world_x = chunk_min_x + x_index;
|
||||
let xd = (world_x as f64 + 0.5 - x) / horizontal_radius;
|
||||
|
||||
for z_index in z_index_min..=z_index_max {
|
||||
let world_z = chunk_min_z + z_index;
|
||||
let zd = (world_z as f64 + 0.5 - z) / horizontal_radius;
|
||||
|
||||
if xd * xd + zd * zd < 1.0 {
|
||||
let mut has_grass = false;
|
||||
|
||||
for world_y in (min_y + 1..=max_y).rev() {
|
||||
let yd = (world_y as f64 - 0.5 - y) / vertical_radius;
|
||||
|
||||
if !Self::should_skip(
|
||||
width_factor_per_height,
|
||||
xd,
|
||||
yd,
|
||||
zd,
|
||||
world_y,
|
||||
run.chunk.bottom_y() as i32,
|
||||
) && !run.chunk.carving_mask.get(world_x, world_y, world_z)
|
||||
{
|
||||
run.chunk.carving_mask.set(world_x, world_y, world_z);
|
||||
Self::carve_block(
|
||||
run,
|
||||
config,
|
||||
world_x,
|
||||
world_y,
|
||||
world_z,
|
||||
&mut has_grass,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn should_skip(
|
||||
width_factor_per_height: &[f32],
|
||||
xd: f64,
|
||||
yd: f64,
|
||||
zd: f64,
|
||||
y: i32,
|
||||
min_gen_y: i32,
|
||||
) -> bool {
|
||||
let y_index = (y - min_gen_y) as usize;
|
||||
if y_index == 0 {
|
||||
return true;
|
||||
}
|
||||
(xd * xd + zd * zd) * width_factor_per_height[y_index - 1] as f64 + yd * yd / 6.0 >= 1.0
|
||||
}
|
||||
|
||||
fn carve_block(
|
||||
run: &mut CarveRun,
|
||||
config: &CarverConfig,
|
||||
x: i32,
|
||||
y: i32,
|
||||
z: i32,
|
||||
has_grass: &mut bool,
|
||||
) -> bool {
|
||||
let local_y = y - run.chunk.bottom_y() as i32;
|
||||
let state_id = run.chunk.get_block_state_raw(x & 15, local_y, z & 15);
|
||||
let block = pumpkin_data::Block::from_state_id(state_id);
|
||||
|
||||
if block.id == pumpkin_data::Block::GRASS_BLOCK.id
|
||||
|| block.id == pumpkin_data::Block::MYCELIUM.id
|
||||
{
|
||||
*has_grass = true;
|
||||
}
|
||||
|
||||
if block.id.has_tag(config.replaceable) {
|
||||
let Some((state, should_schedule_fluid_update)) =
|
||||
overworld_carve_state(run, config, x, y, z)
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
|
||||
place_carved_block(
|
||||
run,
|
||||
pumpkin_util::math::vector3::Vector3::new(x, y, z),
|
||||
state,
|
||||
should_schedule_fluid_update,
|
||||
*has_grass,
|
||||
true,
|
||||
);
|
||||
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,524 @@
|
||||
use super::{CarveRun, Carver, overworld_carve_state, place_carved_block};
|
||||
use pumpkin_data::carver::{CarverAdditionalConfig, CarverConfig, HeightProvider};
|
||||
use pumpkin_util::math::vector2::Vector2;
|
||||
use pumpkin_util::math::vector3::Vector3;
|
||||
use pumpkin_util::random::{RandomGenerator, RandomImpl};
|
||||
use std::f32::consts::PI;
|
||||
|
||||
pub struct CaveCarver;
|
||||
|
||||
impl Carver for CaveCarver {
|
||||
fn carve(
|
||||
&self,
|
||||
config: &CarverConfig,
|
||||
run: &mut CarveRun,
|
||||
random: &mut RandomGenerator,
|
||||
_chunk_pos: &Vector2<i32>,
|
||||
carver_chunk_pos: &Vector2<i32>,
|
||||
legacy_random_source: bool,
|
||||
) {
|
||||
let (is_nether, cave_config) = match config.additional {
|
||||
CarverAdditionalConfig::Cave(ref c) => (false, c),
|
||||
CarverAdditionalConfig::NetherCave(ref c) => (true, c),
|
||||
CarverAdditionalConfig::Canyon(_) => return,
|
||||
};
|
||||
|
||||
let min_y = run.chunk.bottom_y() as i32;
|
||||
let height = run.chunk.height();
|
||||
|
||||
let max_distance = (4 * 2 - 1) << 4;
|
||||
|
||||
let bound = if is_nether { 10 } else { 15 };
|
||||
let c1 = random.next_bounded_i32(bound);
|
||||
let c2 = random.next_bounded_i32(c1 + 1);
|
||||
let cave_count = random.next_bounded_i32(c2 + 1);
|
||||
|
||||
for _ in 0..cave_count {
|
||||
let x = (carver_chunk_pos.x << 4) + random.next_bounded_i32(16);
|
||||
let y = get_height(&config.y, random, min_y as i8, height) as f64;
|
||||
let z = (carver_chunk_pos.y << 4) + random.next_bounded_i32(16);
|
||||
|
||||
let horizontal_radius_multiplier =
|
||||
cave_config.horizontal_radius_multiplier.get(random) as f64;
|
||||
let vertical_radius_multiplier =
|
||||
cave_config.vertical_radius_multiplier.get(random) as f64;
|
||||
let floor_level = cave_config.floor_level.get(random) as f64;
|
||||
|
||||
let mut tunnels = 1;
|
||||
if random.next_bounded_i32(4) == 0 {
|
||||
let y_scale = config.y_scale.get(random) as f64;
|
||||
let thickness = 1.0 + random.next_f32() * 6.0;
|
||||
Self::create_room(
|
||||
run,
|
||||
x as f64,
|
||||
y,
|
||||
z as f64,
|
||||
thickness,
|
||||
y_scale,
|
||||
config,
|
||||
floor_level,
|
||||
is_nether,
|
||||
);
|
||||
tunnels += random.next_bounded_i32(4);
|
||||
}
|
||||
|
||||
for _ in 0..tunnels {
|
||||
let horizontal_rotation = random.next_f32() * PI * 2.0;
|
||||
let vertical_rotation = (random.next_f32() - 0.5) / 4.0;
|
||||
let thickness = Self::get_thickness(random, is_nether);
|
||||
let distance = max_distance - random.next_bounded_i32(max_distance / 4);
|
||||
|
||||
Self::create_tunnel(
|
||||
config,
|
||||
run,
|
||||
random.next_i64(),
|
||||
x as f64,
|
||||
y,
|
||||
z as f64,
|
||||
horizontal_radius_multiplier,
|
||||
vertical_radius_multiplier,
|
||||
thickness,
|
||||
horizontal_rotation,
|
||||
vertical_rotation,
|
||||
0,
|
||||
distance,
|
||||
if is_nether { 5.0 } else { 1.0 }, // this.getYScale()
|
||||
floor_level,
|
||||
is_nether,
|
||||
legacy_random_source,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CaveCarver {
|
||||
fn get_thickness(random: &mut RandomGenerator, is_nether: bool) -> f32 {
|
||||
if is_nether {
|
||||
(random.next_f32() * 2.0 + random.next_f32()) * 2.0
|
||||
} else {
|
||||
let mut thickness = random.next_f32() * 2.0 + random.next_f32();
|
||||
if random.next_bounded_i32(10) == 0 {
|
||||
thickness *= random.next_f32() * random.next_f32() * 3.0 + 1.0;
|
||||
}
|
||||
thickness
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn create_room(
|
||||
run: &mut CarveRun,
|
||||
x: f64,
|
||||
y: f64,
|
||||
z: f64,
|
||||
thickness: f32,
|
||||
y_scale: f64,
|
||||
config: &CarverConfig,
|
||||
floor_level: f64,
|
||||
is_nether: bool,
|
||||
) {
|
||||
let horizontal_radius =
|
||||
1.5 + f64::from(pumpkin_util::math::sin(std::f32::consts::FRAC_PI_2) * thickness);
|
||||
let vertical_radius = horizontal_radius * y_scale;
|
||||
Self::carve_ellipsoid(
|
||||
run,
|
||||
config,
|
||||
x + 1.0,
|
||||
y,
|
||||
z,
|
||||
horizontal_radius,
|
||||
vertical_radius,
|
||||
floor_level,
|
||||
is_nether,
|
||||
);
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn create_tunnel(
|
||||
config: &CarverConfig,
|
||||
run: &mut CarveRun,
|
||||
tunnel_seed: i64,
|
||||
mut x: f64,
|
||||
mut y: f64,
|
||||
mut z: f64,
|
||||
horizontal_radius_multiplier: f64,
|
||||
vertical_radius_multiplier: f64,
|
||||
thickness: f32,
|
||||
mut horizontal_rotation: f32,
|
||||
mut vertical_rotation: f32,
|
||||
step: i32,
|
||||
dist: i32,
|
||||
y_scale: f64,
|
||||
floor_level: f64,
|
||||
is_nether: bool,
|
||||
legacy_random_source: bool,
|
||||
) {
|
||||
let mut random = super::new_carver_random(tunnel_seed as u64, legacy_random_source);
|
||||
let split_point = random.next_bounded_i32(dist / 2) + dist / 4;
|
||||
let is_steep = random.next_bounded_i32(6) == 0;
|
||||
let mut y_rota = 0.0f32;
|
||||
let mut x_rota = 0.0f32;
|
||||
|
||||
for current_step in step..dist {
|
||||
let progress_arg = PI * current_step as f32 / dist as f32;
|
||||
let horizontal_radius =
|
||||
1.5 + f64::from(pumpkin_util::math::sin(progress_arg) * thickness);
|
||||
let vertical_radius = horizontal_radius * y_scale;
|
||||
let cos_x = pumpkin_util::math::cos(vertical_rotation);
|
||||
x += f64::from(pumpkin_util::math::cos(horizontal_rotation) * cos_x);
|
||||
y += f64::from(pumpkin_util::math::sin(vertical_rotation));
|
||||
z += f64::from(pumpkin_util::math::sin(horizontal_rotation) * cos_x);
|
||||
|
||||
vertical_rotation *= if is_steep { 0.92 } else { 0.7 };
|
||||
vertical_rotation += x_rota * 0.1;
|
||||
horizontal_rotation += y_rota * 0.1;
|
||||
x_rota *= 0.9;
|
||||
y_rota *= 0.75;
|
||||
x_rota += (random.next_f32() - random.next_f32()) * random.next_f32() * 2.0;
|
||||
y_rota += (random.next_f32() - random.next_f32()) * random.next_f32() * 4.0;
|
||||
|
||||
if current_step == split_point && thickness > 1.0 {
|
||||
Self::create_tunnel(
|
||||
config,
|
||||
run,
|
||||
random.next_i64(),
|
||||
x,
|
||||
y,
|
||||
z,
|
||||
horizontal_radius_multiplier,
|
||||
vertical_radius_multiplier,
|
||||
random.next_f32() * 0.5 + 0.5,
|
||||
horizontal_rotation - (PI / 2.0),
|
||||
vertical_rotation / 3.0,
|
||||
current_step,
|
||||
dist,
|
||||
1.0,
|
||||
floor_level,
|
||||
is_nether,
|
||||
legacy_random_source,
|
||||
);
|
||||
Self::create_tunnel(
|
||||
config,
|
||||
run,
|
||||
random.next_i64(),
|
||||
x,
|
||||
y,
|
||||
z,
|
||||
horizontal_radius_multiplier,
|
||||
vertical_radius_multiplier,
|
||||
random.next_f32() * 0.5 + 0.5,
|
||||
horizontal_rotation + (PI / 2.0),
|
||||
vertical_rotation / 3.0,
|
||||
current_step,
|
||||
dist,
|
||||
1.0,
|
||||
floor_level,
|
||||
is_nether,
|
||||
legacy_random_source,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if random.next_bounded_i32(4) != 0 {
|
||||
if !Self::can_reach(
|
||||
run.chunk.x,
|
||||
run.chunk.z,
|
||||
x,
|
||||
z,
|
||||
current_step,
|
||||
dist,
|
||||
thickness,
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
Self::carve_ellipsoid(
|
||||
run,
|
||||
config,
|
||||
x,
|
||||
y,
|
||||
z,
|
||||
horizontal_radius as f64 * horizontal_radius_multiplier,
|
||||
vertical_radius * vertical_radius_multiplier,
|
||||
floor_level,
|
||||
is_nether,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
fn can_reach(
|
||||
chunk_x: i32,
|
||||
chunk_z: i32,
|
||||
x: f64,
|
||||
z: f64,
|
||||
step: i32,
|
||||
distance: i32,
|
||||
thickness: f32,
|
||||
) -> bool {
|
||||
let chunk_middle_x = (chunk_x << 4) + 8;
|
||||
let chunk_middle_z = (chunk_z << 4) + 8;
|
||||
let dx = x - chunk_middle_x as f64;
|
||||
let dz = z - chunk_middle_z as f64;
|
||||
let remaining = (distance - step) as f64;
|
||||
let rr = (thickness + 2.0 + 16.0) as f64;
|
||||
dx * dx + dz * dz - remaining * remaining <= rr * rr
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn carve_ellipsoid(
|
||||
run: &mut CarveRun,
|
||||
config: &CarverConfig,
|
||||
x: f64,
|
||||
y: f64,
|
||||
z: f64,
|
||||
horizontal_radius: f64,
|
||||
vertical_radius: f64,
|
||||
floor_level: f64,
|
||||
is_nether: bool,
|
||||
) {
|
||||
let center_x = (run.chunk.x << 4) as f64 + 8.0;
|
||||
let center_z = (run.chunk.z << 4) as f64 + 8.0;
|
||||
let max_delta = 16.0 + horizontal_radius * 2.0;
|
||||
|
||||
if (x - center_x).abs() > max_delta || (z - center_z).abs() > max_delta {
|
||||
return;
|
||||
}
|
||||
|
||||
let chunk_min_x = run.chunk.x << 4;
|
||||
let chunk_min_z = run.chunk.z << 4;
|
||||
|
||||
let x_index_min = ((x - horizontal_radius).floor() as i32 - chunk_min_x - 1).max(0);
|
||||
let x_index_max = ((x + horizontal_radius).floor() as i32 - chunk_min_x).min(15);
|
||||
|
||||
let min_y = ((y - vertical_radius).floor() as i32 - 1).max(run.chunk.bottom_y() as i32 + 1);
|
||||
let protected_blocks_on_top = 7;
|
||||
let max_y = ((y + vertical_radius).floor() as i32 + 1).min(
|
||||
run.chunk.bottom_y() as i32 + run.chunk.height() as i32 - 1 - protected_blocks_on_top,
|
||||
);
|
||||
|
||||
let z_index_min = ((z - horizontal_radius).floor() as i32 - chunk_min_z - 1).max(0);
|
||||
let z_index_max = ((z + horizontal_radius).floor() as i32 - chunk_min_z).min(15);
|
||||
|
||||
for x_index in x_index_min..=x_index_max {
|
||||
let world_x = chunk_min_x + x_index;
|
||||
let xd = (world_x as f64 + 0.5 - x) / horizontal_radius;
|
||||
|
||||
for z_index in z_index_min..=z_index_max {
|
||||
let world_z = chunk_min_z + z_index;
|
||||
let zd = (world_z as f64 + 0.5 - z) / horizontal_radius;
|
||||
|
||||
if xd * xd + zd * zd < 1.0 {
|
||||
let mut has_grass = false;
|
||||
|
||||
for world_y in (min_y + 1..=max_y).rev() {
|
||||
let yd = (world_y as f64 - 0.5 - y) / vertical_radius;
|
||||
|
||||
if !Self::should_skip(xd, yd, zd, floor_level)
|
||||
&& !run.chunk.carving_mask.get(world_x, world_y, world_z)
|
||||
{
|
||||
run.chunk.carving_mask.set(world_x, world_y, world_z);
|
||||
Self::carve_block(
|
||||
run,
|
||||
config,
|
||||
world_x,
|
||||
world_y,
|
||||
world_z,
|
||||
is_nether,
|
||||
&mut has_grass,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn should_skip(xd: f64, yd: f64, zd: f64, floor_level: f64) -> bool {
|
||||
if yd <= floor_level {
|
||||
true
|
||||
} else {
|
||||
xd * xd + yd * yd + zd * zd >= 1.0
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn carve_block(
|
||||
run: &mut CarveRun,
|
||||
config: &CarverConfig,
|
||||
x: i32,
|
||||
y: i32,
|
||||
z: i32,
|
||||
is_nether: bool,
|
||||
has_grass: &mut bool,
|
||||
) -> bool {
|
||||
let state = run.chunk.get_block_state(&Vector3::new(x, y, z));
|
||||
let block = state.to_block();
|
||||
|
||||
if block.id == pumpkin_data::Block::GRASS_BLOCK.id
|
||||
|| block.id == pumpkin_data::Block::MYCELIUM.id
|
||||
{
|
||||
*has_grass = true;
|
||||
}
|
||||
|
||||
if !block.id.has_tag(config.replaceable) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let (state, should_schedule_fluid_update) = if is_nether {
|
||||
let state = if y <= run.chunk.bottom_y() as i32 + 31 {
|
||||
run.ids.lava
|
||||
} else {
|
||||
run.ids.cave_air
|
||||
};
|
||||
(state, false)
|
||||
} else {
|
||||
let Some(state) = overworld_carve_state(run, config, x, y, z) else {
|
||||
return false;
|
||||
};
|
||||
state
|
||||
};
|
||||
|
||||
place_carved_block(
|
||||
run,
|
||||
Vector3::new(x, y, z),
|
||||
state,
|
||||
should_schedule_fluid_update,
|
||||
*has_grass,
|
||||
!is_nether,
|
||||
);
|
||||
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_height(p: &HeightProvider, random: &mut RandomGenerator, min_y: i8, height: u16) -> i32 {
|
||||
match p {
|
||||
HeightProvider::Uniform(p) => {
|
||||
let min = p.min_inclusive.get_y(min_y as i16, height);
|
||||
let max = p.max_inclusive.get_y(min_y as i16, height);
|
||||
random.next_inbetween_i32(min, max)
|
||||
}
|
||||
HeightProvider::Trapezoid(p) => {
|
||||
let i = p.min_inclusive.get_y(min_y as i16, height);
|
||||
let j = p.max_inclusive.get_y(min_y as i16, height);
|
||||
let plateau = p.plateau.unwrap_or(0);
|
||||
let k = j - i;
|
||||
if plateau >= k {
|
||||
random.next_inbetween_i32(i, j)
|
||||
} else {
|
||||
let l = (k - plateau) / 2;
|
||||
let m = k - l;
|
||||
i + random.next_inbetween_i32(0, m) + random.next_inbetween_i32(0, l)
|
||||
}
|
||||
}
|
||||
HeightProvider::VeryBiasedToBottom(p) => {
|
||||
let min = p.min_inclusive.get_y(min_y as i16, height);
|
||||
let max = p.max_inclusive.get_y(min_y as i16, height);
|
||||
let inner = p.inner.map_or(1, std::num::NonZero::get) as i32;
|
||||
let min_rnd = random.next_inbetween_i32(min + inner, max);
|
||||
let max_rnd = random.next_inbetween_i32(min, min_rnd - 1);
|
||||
random.next_inbetween_i32(min, max_rnd - 1 + inner)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use pumpkin_data::carver::CAVE;
|
||||
use pumpkin_data::{Block, BlockStateId, dimension::Dimension};
|
||||
|
||||
type Run<'a, 'b> = super::super::CarveRun<'a, 'b>;
|
||||
|
||||
#[test]
|
||||
fn carves_at_world_y() {
|
||||
super::super::with_carve_run(Dimension::OVERWORLD, |run| {
|
||||
let expected = super::super::overworld_carve_state(run, &CAVE, 5, 20, 6)
|
||||
.expect("test position should carve")
|
||||
.0
|
||||
.id;
|
||||
assert_world_y(run, 5, 20, 6, expected);
|
||||
assert_world_y(run, 7, -58, 8, Block::LAVA.default_state.id);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uses_aquifer_state() {
|
||||
super::super::with_carve_run(Dimension::OVERWORLD, |run| {
|
||||
let (x, y, z, expected_state) =
|
||||
find_aquifer_carve_state(run, |state, _| state.id != Block::AIR.default_state.id)
|
||||
.expect("expected non-air aquifer carve state in test chunk");
|
||||
carve_at(run, x, y, z, Block::WATER.default_state, expected_state.id);
|
||||
assert_ne!(expected_state.id, Block::AIR.default_state.id);
|
||||
|
||||
let (x, y, z, expected_state) =
|
||||
find_aquifer_carve_state(run, |state, schedule| state.is_liquid() && schedule)
|
||||
.expect("expected scheduled aquifer fluid in test chunk");
|
||||
let old_tick_count = run.chunk.fluid_ticks.len();
|
||||
|
||||
carve_at(run, x, y, z, Block::STONE.default_state, expected_state.id);
|
||||
assert_eq!(run.chunk.fluid_ticks.len(), old_tick_count + 1);
|
||||
let pos = run.chunk.fluid_ticks.last().unwrap().position.0;
|
||||
assert_eq!((pos.x, pos.y, pos.z), (x, y, z));
|
||||
});
|
||||
}
|
||||
|
||||
fn assert_world_y(run: &mut Run, x: i32, y: i32, z: i32, expected: BlockStateId) {
|
||||
let old_wrong_y = y - run.chunk.bottom_y() as i32;
|
||||
let stone = Block::STONE.default_state;
|
||||
|
||||
run.chunk.set_block_state(x, y, z, stone);
|
||||
run.chunk.set_block_state(x, old_wrong_y, z, stone);
|
||||
carve_at(run, x, y, z, stone, expected);
|
||||
assert_eq!(block_id(run, x, old_wrong_y, z), stone.id);
|
||||
}
|
||||
|
||||
fn carve_at(
|
||||
run: &mut Run,
|
||||
x: i32,
|
||||
y: i32,
|
||||
z: i32,
|
||||
initial_state: &'static pumpkin_data::BlockState,
|
||||
expected: BlockStateId,
|
||||
) {
|
||||
let mut has_grass = false;
|
||||
|
||||
run.chunk.set_block_state(x, y, z, initial_state);
|
||||
let carved = CaveCarver::carve_block(run, &CAVE, x, y, z, false, &mut has_grass);
|
||||
assert!(carved);
|
||||
assert_eq!(block_id(run, x, y, z), expected);
|
||||
}
|
||||
|
||||
fn block_id(run: &Run, x: i32, y: i32, z: i32) -> BlockStateId {
|
||||
run.chunk.get_block_state(&Vector3::new(x, y, z))
|
||||
}
|
||||
|
||||
fn find_aquifer_carve_state(
|
||||
run: &mut Run,
|
||||
predicate: impl Fn(&'static pumpkin_data::BlockState, bool) -> bool,
|
||||
) -> Option<(i32, i32, i32, &'static pumpkin_data::BlockState)> {
|
||||
let lava_y = CAVE
|
||||
.lava_level
|
||||
.get_y(run.chunk.bottom_y() as i16, run.chunk.height());
|
||||
|
||||
for y in (lava_y + 1)..=63 {
|
||||
for x in 0..16 {
|
||||
for z in 0..16 {
|
||||
let Some((state, should_schedule)) =
|
||||
super::super::overworld_carve_state(run, &CAVE, x, y, z)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
|
||||
if predicate(state, should_schedule) {
|
||||
return Some((x, y, z, state));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
pub struct CarvingMask {
|
||||
min_y: i32,
|
||||
mask: Vec<u64>,
|
||||
}
|
||||
|
||||
impl CarvingMask {
|
||||
#[must_use]
|
||||
pub fn new(height: i32, min_y: i32) -> Self {
|
||||
// Each u64 stores 64 bits. Total bits needed: 16 * 16 * height.
|
||||
let total_bits = 16 * 16 * height;
|
||||
let num_u64s = (total_bits as usize).div_ceil(64);
|
||||
Self {
|
||||
min_y,
|
||||
mask: vec![0; num_u64s],
|
||||
}
|
||||
}
|
||||
|
||||
const fn get_bit_index(&self, x: i32, y: i32, z: i32) -> usize {
|
||||
// x: 0..16, z: 0..16, y: min_y..min_y+height
|
||||
let rel_x = x & 15;
|
||||
let rel_z = z & 15;
|
||||
let rel_y = y - self.min_y;
|
||||
(rel_x | (rel_z << 4) | (rel_y << 8)) as usize
|
||||
}
|
||||
|
||||
pub fn set(&mut self, x: i32, y: i32, z: i32) {
|
||||
let bit_index = self.get_bit_index(x, y, z);
|
||||
let u64_idx = bit_index / 64;
|
||||
let bit_in_u64 = bit_index % 64;
|
||||
self.mask[u64_idx] |= 1 << bit_in_u64;
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn get(&self, x: i32, y: i32, z: i32) -> bool {
|
||||
let bit_index = self.get_bit_index(x, y, z);
|
||||
let u64_idx = bit_index / 64;
|
||||
let bit_in_u64 = bit_index % 64;
|
||||
(self.mask[u64_idx] >> bit_in_u64) & 1 != 0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,574 @@
|
||||
pub mod canyon;
|
||||
pub mod cave;
|
||||
pub mod mask;
|
||||
|
||||
use crate::ProtoChunk;
|
||||
use crate::generation::GlobalRandomConfig;
|
||||
use crate::generation::generator::VanillaGenerator;
|
||||
use crate::generation::noise::aquifer_sampler::CarverAquiferSampler;
|
||||
use crate::generation::noise::perlin::DoublePerlinNoiseSampler;
|
||||
use crate::generation::noise::router::surface_height_sampler::{
|
||||
SurfaceHeightEstimateSampler, SurfaceHeightSamplerBuilderOptions,
|
||||
};
|
||||
use crate::generation::surface::rule::try_apply_material_rule;
|
||||
use crate::generation::surface::terrain::SurfaceTerrainBuilder;
|
||||
use crate::generation::surface::{MaterialRuleContext, steep_material_condition};
|
||||
use pumpkin_data::block_state::BlockState;
|
||||
use pumpkin_data::carver::{CANYON, CAVE, CAVE_EXTRA_UNDERGROUND, NETHER_CAVE};
|
||||
use pumpkin_data::carver::{CarverAdditionalConfig, CarverConfig};
|
||||
use pumpkin_data::chunk_gen_settings::MaterialRule;
|
||||
use pumpkin_data::dimension::Dimension;
|
||||
use pumpkin_data::fluid::Fluid;
|
||||
use pumpkin_util::math::vector2::Vector2;
|
||||
use pumpkin_util::math::vector3::Vector3;
|
||||
use pumpkin_util::random::{RandomGenerator, RandomImpl};
|
||||
|
||||
const OVERWORLD_CARVERS: [&CarverConfig; 3] = [&CAVE, &CAVE_EXTRA_UNDERGROUND, &CANYON];
|
||||
const NETHER_CARVERS: [&CarverConfig; 1] = [&NETHER_CAVE];
|
||||
|
||||
pub struct CarverBlockIds {
|
||||
pub air: &'static BlockState,
|
||||
pub cave_air: &'static BlockState,
|
||||
pub lava: &'static BlockState,
|
||||
pub dirt: &'static BlockState,
|
||||
pub grass_block: &'static BlockState,
|
||||
pub mycelium: &'static BlockState,
|
||||
}
|
||||
|
||||
impl Default for CarverBlockIds {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl CarverBlockIds {
|
||||
#[must_use]
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
air: pumpkin_data::Block::AIR.default_state,
|
||||
cave_air: pumpkin_data::Block::CAVE_AIR.default_state,
|
||||
lava: pumpkin_data::Block::LAVA.default_state,
|
||||
dirt: pumpkin_data::Block::DIRT.default_state,
|
||||
grass_block: pumpkin_data::Block::GRASS_BLOCK.default_state,
|
||||
mycelium: pumpkin_data::Block::MYCELIUM.default_state,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct CarvingContext<'a> {
|
||||
pub min_y: i8,
|
||||
pub height: u16,
|
||||
pub random_config: &'a GlobalRandomConfig,
|
||||
pub surface_noise: &'a DoublePerlinNoiseSampler,
|
||||
pub secondary_noise: &'a DoublePerlinNoiseSampler,
|
||||
pub terrain_builder: &'a SurfaceTerrainBuilder,
|
||||
pub sea_level: i32,
|
||||
pub surface_rule: &'a MaterialRule,
|
||||
pub surface_height_sampler: SurfaceHeightEstimateSampler<'a>,
|
||||
pub carver_aquifer: Option<CarverAquiferSampler<'a>>,
|
||||
}
|
||||
|
||||
pub struct CarveRun<'a, 'b> {
|
||||
pub ctx: &'a mut CarvingContext<'b>,
|
||||
pub chunk: &'a mut ProtoChunk,
|
||||
pub ids: CarverBlockIds,
|
||||
}
|
||||
|
||||
impl CarvingContext<'_> {
|
||||
pub fn top_material(
|
||||
&mut self,
|
||||
chunk: &mut ProtoChunk,
|
||||
x: i32,
|
||||
y: i32,
|
||||
z: i32,
|
||||
under_fluid: bool,
|
||||
steep: bool,
|
||||
) -> Option<&'static BlockState> {
|
||||
let mut context = MaterialRuleContext::new(
|
||||
self.min_y,
|
||||
self.height,
|
||||
&self.random_config.base_random_deriver,
|
||||
self.terrain_builder,
|
||||
self.surface_noise,
|
||||
self.secondary_noise,
|
||||
self.sea_level,
|
||||
);
|
||||
context.init_horizontal(x, z);
|
||||
context.biome = chunk.get_terrain_gen_biome(x, y, z);
|
||||
context.set_steep_material_condition(steep);
|
||||
context.init_vertical(1, 1, y, if under_fluid { y + 1 } else { i32::MIN });
|
||||
|
||||
try_apply_material_rule(
|
||||
self.surface_rule,
|
||||
chunk,
|
||||
&mut context,
|
||||
&mut self.surface_height_sampler,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
pub trait Carver {
|
||||
fn carve(
|
||||
&self,
|
||||
config: &CarverConfig,
|
||||
run: &mut CarveRun,
|
||||
random: &mut RandomGenerator,
|
||||
chunk_pos: &Vector2<i32>,
|
||||
carver_chunk_pos: &Vector2<i32>,
|
||||
legacy_random_source: bool,
|
||||
);
|
||||
}
|
||||
|
||||
pub fn carve(chunk: &mut ProtoChunk, generator: &VanillaGenerator) {
|
||||
// Vanilla applyCarvers uses a range of 8 chunks (17x17 area)
|
||||
let radius = 8;
|
||||
let chunk_x = chunk.x;
|
||||
let chunk_z = chunk.z;
|
||||
let chunk_pos = Vector2::new(chunk_x, chunk_z);
|
||||
|
||||
let carvers_to_use = carvers_for_dimension(&generator.dimension);
|
||||
|
||||
let start_x = crate::generation::positions::chunk_pos::start_block_x(chunk_x);
|
||||
let start_z = crate::generation::positions::chunk_pos::start_block_z(chunk_z);
|
||||
let generation_shape = &generator.settings.shape;
|
||||
let horizontal_cell_count = 16 / generation_shape.horizontal_cell_block_count();
|
||||
|
||||
let horizontal_biome_end = crate::generation::biome_coords::from_block(
|
||||
horizontal_cell_count as i32 * generation_shape.horizontal_cell_block_count() as i32,
|
||||
);
|
||||
let surface_config = SurfaceHeightSamplerBuilderOptions::new(
|
||||
crate::generation::biome_coords::from_block(start_x),
|
||||
crate::generation::biome_coords::from_block(start_z),
|
||||
horizontal_biome_end as usize,
|
||||
generation_shape.min_y as i32,
|
||||
generation_shape.max_y() as i32,
|
||||
generation_shape.vertical_cell_block_count() as usize,
|
||||
);
|
||||
let surface_height_sampler = SurfaceHeightEstimateSampler::generate(
|
||||
&generator.base_router.surface_estimator,
|
||||
&surface_config,
|
||||
);
|
||||
let carver_aquifer = generator.settings.aquifers_enabled.then(|| {
|
||||
CarverAquiferSampler::new(
|
||||
chunk_x,
|
||||
chunk_z,
|
||||
&generator.base_router,
|
||||
&generator.random_config,
|
||||
generator.settings,
|
||||
)
|
||||
});
|
||||
|
||||
let mut context = CarvingContext {
|
||||
min_y: generator.dimension.min_y as i8,
|
||||
height: generator.dimension.logical_height as u16,
|
||||
random_config: &generator.random_config,
|
||||
surface_noise: &generator.terrain_cache.surface_noise,
|
||||
secondary_noise: &generator.terrain_cache.secondary_noise,
|
||||
terrain_builder: &generator.terrain_cache.terrain_builder,
|
||||
sea_level: generator.settings.sea_level,
|
||||
surface_rule: &generator.settings.surface_rule,
|
||||
surface_height_sampler,
|
||||
carver_aquifer,
|
||||
};
|
||||
|
||||
let mut run = CarveRun {
|
||||
ctx: &mut context,
|
||||
chunk,
|
||||
ids: CarverBlockIds::new(),
|
||||
};
|
||||
|
||||
let cave_carver = cave::CaveCarver;
|
||||
let canyon_carver = canyon::CanyonCarver;
|
||||
|
||||
for dx in -radius..=radius {
|
||||
for dz in -radius..=radius {
|
||||
let carver_x = chunk_x + dx;
|
||||
let carver_z = chunk_z + dz;
|
||||
let carver_chunk_pos = Vector2::new(carver_x, carver_z);
|
||||
|
||||
// In vanilla, carvers are per-biome. Here we use the hardcoded list but
|
||||
// maintain the random seed logic.
|
||||
for (index, &config) in carvers_to_use.iter().enumerate() {
|
||||
let seed = get_large_feature_seed(
|
||||
generator.random_config.seed + index as u64,
|
||||
carver_x,
|
||||
carver_z,
|
||||
);
|
||||
let mut carver_random =
|
||||
new_carver_random(seed, generator.settings.legacy_random_source);
|
||||
|
||||
if should_carve(config, &mut carver_random) {
|
||||
match config.additional {
|
||||
CarverAdditionalConfig::Cave(_) | CarverAdditionalConfig::NetherCave(_) => {
|
||||
cave_carver.carve(
|
||||
config,
|
||||
&mut run,
|
||||
&mut carver_random,
|
||||
&chunk_pos,
|
||||
&carver_chunk_pos,
|
||||
generator.settings.legacy_random_source,
|
||||
);
|
||||
}
|
||||
CarverAdditionalConfig::Canyon(_) => {
|
||||
canyon_carver.carve(
|
||||
config,
|
||||
&mut run,
|
||||
&mut carver_random,
|
||||
&chunk_pos,
|
||||
&carver_chunk_pos,
|
||||
generator.settings.legacy_random_source,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn should_carve(config: &CarverConfig, random: &mut RandomGenerator) -> bool {
|
||||
random.next_f32() <= config.probability
|
||||
}
|
||||
|
||||
fn get_large_feature_seed(seed: u64, chunk_x: i32, chunk_z: i32) -> u64 {
|
||||
let mut random = pumpkin_util::random::legacy_rand::LegacyRand::from_seed(seed);
|
||||
let x_scale = random.next_i64();
|
||||
let z_scale = random.next_i64();
|
||||
let seed = seed as i64;
|
||||
let result =
|
||||
(chunk_x as i64).wrapping_mul(x_scale) ^ (chunk_z as i64).wrapping_mul(z_scale) ^ seed;
|
||||
result as u64
|
||||
}
|
||||
|
||||
const fn new_carver_random(seed: u64, non_vanilla_random: bool) -> RandomGenerator {
|
||||
if non_vanilla_random {
|
||||
RandomGenerator::Xoroshiro(pumpkin_util::random::xoroshiro128::Xoroshiro::from_seed(
|
||||
seed,
|
||||
))
|
||||
} else {
|
||||
RandomGenerator::Legacy(pumpkin_util::random::legacy_rand::LegacyRand::from_seed(
|
||||
seed,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
fn carvers_for_dimension(dimension: &Dimension) -> &'static [&'static CarverConfig] {
|
||||
if dimension == &Dimension::OVERWORLD {
|
||||
&OVERWORLD_CARVERS
|
||||
} else if dimension == &Dimension::THE_NETHER {
|
||||
&NETHER_CARVERS
|
||||
} else {
|
||||
&[]
|
||||
}
|
||||
}
|
||||
|
||||
fn carve_top_material(
|
||||
run: &mut CarveRun,
|
||||
x: i32,
|
||||
carved_y: i32,
|
||||
z: i32,
|
||||
carved_state: &'static BlockState,
|
||||
has_grass: bool,
|
||||
overworld: bool,
|
||||
) {
|
||||
if !overworld || !has_grass {
|
||||
return;
|
||||
}
|
||||
|
||||
let below_y = carved_y - 1;
|
||||
let below_state = run.chunk.get_block_state(&Vector3::new(x, below_y, z));
|
||||
if below_state != run.ids.dirt.id {
|
||||
return;
|
||||
}
|
||||
|
||||
let steep = steep_material_condition(run.chunk, x, z);
|
||||
if let Some(top_material) =
|
||||
run.ctx
|
||||
.top_material(run.chunk, x, below_y, z, carved_state.is_liquid(), steep)
|
||||
{
|
||||
run.chunk.set_block_state(x, below_y, z, top_material);
|
||||
|
||||
schedule_fluid_tick_for_state(run.chunk, x, below_y, z, top_material);
|
||||
}
|
||||
}
|
||||
|
||||
fn overworld_carve_state(
|
||||
run: &mut CarveRun,
|
||||
config: &CarverConfig,
|
||||
x: i32,
|
||||
y: i32,
|
||||
z: i32,
|
||||
) -> Option<(&'static BlockState, bool)> {
|
||||
let lava_y = config
|
||||
.lava_level
|
||||
.get_y(run.chunk.bottom_y() as i16, run.chunk.height());
|
||||
|
||||
if y <= lava_y {
|
||||
return Some((run.ids.lava, false));
|
||||
}
|
||||
|
||||
let Some(aquifer) = run.ctx.carver_aquifer.as_mut() else {
|
||||
return Some((run.ids.air, false));
|
||||
};
|
||||
|
||||
let result = aquifer.compute(&Vector3::new(x, y, z), 0.0);
|
||||
result
|
||||
.state
|
||||
.map(|state| (state, result.should_schedule_fluid_update))
|
||||
}
|
||||
|
||||
fn place_carved_block(
|
||||
run: &mut CarveRun,
|
||||
pos: Vector3<i32>,
|
||||
state: &'static BlockState,
|
||||
should_schedule_fluid_update: bool,
|
||||
has_grass: bool,
|
||||
overworld: bool,
|
||||
) {
|
||||
run.chunk.set_block_state(pos.x, pos.y, pos.z, state);
|
||||
|
||||
if overworld && should_schedule_fluid_update && state.is_liquid() {
|
||||
schedule_fluid_tick_for_state(run.chunk, pos.x, pos.y, pos.z, state);
|
||||
}
|
||||
|
||||
carve_top_material(run, pos.x, pos.y, pos.z, state, has_grass, overworld);
|
||||
}
|
||||
|
||||
fn schedule_fluid_tick_for_state(
|
||||
chunk: &mut ProtoChunk,
|
||||
x: i32,
|
||||
y: i32,
|
||||
z: i32,
|
||||
state: &'static BlockState,
|
||||
) {
|
||||
if state.id == pumpkin_data::Block::WATER.default_state.id {
|
||||
chunk.schedule_fluid_tick(x, y, z, &Fluid::WATER);
|
||||
} else if state.id == pumpkin_data::Block::LAVA.default_state.id {
|
||||
chunk.schedule_fluid_tick(x, y, z, &Fluid::LAVA);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn with_carve_run<F>(dimension: Dimension, test: F)
|
||||
where
|
||||
F: FnOnce(&mut CarveRun<'_, '_>),
|
||||
{
|
||||
with_carve_run_options(dimension, None, true, test);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn with_carve_run_options<F>(
|
||||
dimension: Dimension,
|
||||
surface_rule: Option<&MaterialRule>,
|
||||
use_carver_aquifer: bool,
|
||||
test: F,
|
||||
) where
|
||||
F: FnOnce(&mut CarveRun<'_, '_>),
|
||||
{
|
||||
use crate::generation::generator::{GeneratorInit, VanillaGenerator, WorldGenerator};
|
||||
use pumpkin_util::world_seed::Seed;
|
||||
|
||||
let world_gen = WorldGenerator::Noise(Box::new(VanillaGenerator::new(Seed(42), dimension)));
|
||||
let WorldGenerator::Noise(generator) = &world_gen else {
|
||||
unreachable!()
|
||||
};
|
||||
let mut chunk = ProtoChunk::new(0, 0, &world_gen);
|
||||
|
||||
let start_x = crate::generation::positions::chunk_pos::start_block_x(chunk.x);
|
||||
let start_z = crate::generation::positions::chunk_pos::start_block_z(chunk.z);
|
||||
let generation_shape = &generator.settings.shape;
|
||||
let horizontal_cell_count = 16 / generation_shape.horizontal_cell_block_count();
|
||||
let horizontal_biome_end = crate::generation::biome_coords::from_block(
|
||||
horizontal_cell_count as i32 * generation_shape.horizontal_cell_block_count() as i32,
|
||||
);
|
||||
let surface_config = SurfaceHeightSamplerBuilderOptions::new(
|
||||
crate::generation::biome_coords::from_block(start_x),
|
||||
crate::generation::biome_coords::from_block(start_z),
|
||||
horizontal_biome_end as usize,
|
||||
generation_shape.min_y as i32,
|
||||
generation_shape.max_y() as i32,
|
||||
generation_shape.vertical_cell_block_count() as usize,
|
||||
);
|
||||
let surface_height_sampler = SurfaceHeightEstimateSampler::generate(
|
||||
&generator.base_router.surface_estimator,
|
||||
&surface_config,
|
||||
);
|
||||
let carver_aquifer = use_carver_aquifer.then(|| {
|
||||
CarverAquiferSampler::new(
|
||||
chunk.x,
|
||||
chunk.z,
|
||||
&generator.base_router,
|
||||
&generator.random_config,
|
||||
generator.settings,
|
||||
)
|
||||
});
|
||||
let mut context = CarvingContext {
|
||||
min_y: generator.dimension.min_y as i8,
|
||||
height: generator.dimension.logical_height as u16,
|
||||
random_config: &generator.random_config,
|
||||
surface_noise: &generator.terrain_cache.surface_noise,
|
||||
secondary_noise: &generator.terrain_cache.secondary_noise,
|
||||
terrain_builder: &generator.terrain_cache.terrain_builder,
|
||||
sea_level: generator.settings.sea_level,
|
||||
surface_rule: surface_rule.unwrap_or(&generator.settings.surface_rule),
|
||||
surface_height_sampler,
|
||||
carver_aquifer,
|
||||
};
|
||||
let mut run = CarveRun {
|
||||
ctx: &mut context,
|
||||
chunk: &mut chunk,
|
||||
ids: CarverBlockIds::new(),
|
||||
};
|
||||
|
||||
test(&mut run);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use pumpkin_data::Block;
|
||||
use pumpkin_data::chunk_gen_settings::{
|
||||
BlockMaterialRule, ConditionMaterialRule, MaterialCondition, SequenceMaterialRule,
|
||||
WaterMaterialCondition,
|
||||
};
|
||||
|
||||
static PODZOL_RULE: MaterialRule = MaterialRule::Block(BlockMaterialRule {
|
||||
result_state: Block::PODZOL.default_state,
|
||||
});
|
||||
static GRASS_RULE: MaterialRule = MaterialRule::Block(BlockMaterialRule {
|
||||
result_state: Block::GRASS_BLOCK.default_state,
|
||||
});
|
||||
static WATER_SENSITIVE_RULES: [MaterialRule; 2] = [
|
||||
MaterialRule::Condition(ConditionMaterialRule {
|
||||
if_true: MaterialCondition::Water(WaterMaterialCondition {
|
||||
offset: 0,
|
||||
surface_depth_multiplier: 0,
|
||||
add_stone_depth: false,
|
||||
}),
|
||||
then_run: &GRASS_RULE,
|
||||
}),
|
||||
MaterialRule::Block(BlockMaterialRule {
|
||||
result_state: Block::DIRT.default_state,
|
||||
}),
|
||||
];
|
||||
static WATER_SENSITIVE_RULE: MaterialRule = MaterialRule::Sequence(SequenceMaterialRule {
|
||||
sequence: &WATER_SENSITIVE_RULES,
|
||||
});
|
||||
|
||||
#[test]
|
||||
fn overworld_has_aquifer() {
|
||||
with_carve_run(Dimension::OVERWORLD, |run| {
|
||||
assert!(run.ctx.carver_aquifer.is_some());
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restores_surface() {
|
||||
with_carve_run_options(Dimension::OVERWORLD, Some(&PODZOL_RULE), false, |run| {
|
||||
let x = 4;
|
||||
let y = 70;
|
||||
let z = 5;
|
||||
run.chunk
|
||||
.set_block_state(x, y - 1, z, Block::DIRT.default_state);
|
||||
|
||||
carve_top_material(run, x, y, z, Block::AIR.default_state, true, true);
|
||||
|
||||
assert_eq!(
|
||||
run.chunk.get_block_state(&Vector3::new(x, y - 1, z)),
|
||||
Block::PODZOL.default_state.id,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skips_surface_restore() {
|
||||
with_carve_run_options(Dimension::OVERWORLD, Some(&PODZOL_RULE), false, |run| {
|
||||
let x = 4;
|
||||
let y = 70;
|
||||
let z = 5;
|
||||
|
||||
run.chunk
|
||||
.set_block_state(x, y - 1, z, Block::DIRT.default_state);
|
||||
carve_top_material(run, x, y, z, Block::AIR.default_state, false, true);
|
||||
assert_eq!(
|
||||
run.chunk.get_block_state(&Vector3::new(x, y - 1, z)),
|
||||
Block::DIRT.default_state.id,
|
||||
);
|
||||
|
||||
run.chunk
|
||||
.set_block_state(x, y - 1, z, Block::STONE.default_state);
|
||||
carve_top_material(run, x, y, z, Block::AIR.default_state, true, true);
|
||||
assert_eq!(
|
||||
run.chunk.get_block_state(&Vector3::new(x, y - 1, z)),
|
||||
Block::STONE.default_state.id,
|
||||
);
|
||||
|
||||
run.chunk
|
||||
.set_block_state(x, y - 1, z, Block::DIRT.default_state);
|
||||
carve_top_material(run, x, y, z, Block::AIR.default_state, true, false);
|
||||
assert_eq!(
|
||||
run.chunk.get_block_state(&Vector3::new(x, y - 1, z)),
|
||||
Block::DIRT.default_state.id,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn passes_fluid_to_rule() {
|
||||
with_carve_run_options(
|
||||
Dimension::OVERWORLD,
|
||||
Some(&WATER_SENSITIVE_RULE),
|
||||
false,
|
||||
|run| {
|
||||
let x = 6;
|
||||
let y = 70;
|
||||
let z = 7;
|
||||
|
||||
let dry = run
|
||||
.ctx
|
||||
.top_material(run.chunk, x, y - 1, z, false, false)
|
||||
.unwrap();
|
||||
let under_fluid = run
|
||||
.ctx
|
||||
.top_material(run.chunk, x, y - 1, z, true, false)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(dry.id, Block::GRASS_BLOCK.default_state.id);
|
||||
assert_eq!(under_fluid.id, Block::DIRT.default_state.id);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn steep_matches_vanilla() {
|
||||
with_carve_run(Dimension::OVERWORLD, |run| {
|
||||
let x = 5;
|
||||
let z = 5;
|
||||
|
||||
run.chunk.flat_surface_height_map = [64; crate::chunk::CHUNK_AREA];
|
||||
set_surface_height(run.chunk, x, z - 1, 60);
|
||||
set_surface_height(run.chunk, x, z + 1, 64);
|
||||
assert!(steep_material_condition(run.chunk, x, z));
|
||||
|
||||
run.chunk.flat_surface_height_map = [64; crate::chunk::CHUNK_AREA];
|
||||
set_surface_height(run.chunk, x, z - 1, 64);
|
||||
set_surface_height(run.chunk, x, z + 1, 60);
|
||||
assert!(!steep_material_condition(run.chunk, x, z));
|
||||
|
||||
run.chunk.flat_surface_height_map = [64; crate::chunk::CHUNK_AREA];
|
||||
set_surface_height(run.chunk, x - 1, z, 64);
|
||||
set_surface_height(run.chunk, x + 1, z, 60);
|
||||
assert!(steep_material_condition(run.chunk, x, z));
|
||||
|
||||
run.chunk.flat_surface_height_map = [64; crate::chunk::CHUNK_AREA];
|
||||
set_surface_height(run.chunk, x - 1, z, 60);
|
||||
set_surface_height(run.chunk, x + 1, z, 64);
|
||||
assert!(!steep_material_condition(run.chunk, x, z));
|
||||
});
|
||||
}
|
||||
|
||||
fn set_surface_height(chunk: &mut ProtoChunk, x: i32, z: i32, height: i16) {
|
||||
let index = (x & 15) as usize * 16 + (z & 15) as usize;
|
||||
chunk.flat_surface_height_map[index] = height;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,459 @@
|
||||
use std::{collections::HashMap, sync::LazyLock};
|
||||
|
||||
use pumpkin_util::{math::position::BlockPos, random::RandomGenerator};
|
||||
|
||||
use super::features::{
|
||||
bamboo::BambooFeature,
|
||||
basalt_columns::BasaltColumnsFeature,
|
||||
basalt_pillar::BasaltPillarFeature,
|
||||
block_column::BlockColumnFeature,
|
||||
block_pile::BlockPileFeature,
|
||||
blue_ice::BlueIceFeature,
|
||||
bonus_chest::BonusChestFeature,
|
||||
chorus_plant::ChorusPlantFeature,
|
||||
coral::{
|
||||
coral_claw::CoralClawFeature, coral_mushroom::CoralMushroomFeature,
|
||||
coral_tree::CoralTreeFeature,
|
||||
},
|
||||
delta_feature::DeltaFeatureFeature,
|
||||
desert_well::DesertWellFeature,
|
||||
disk::DiskFeature,
|
||||
drip_stone::{
|
||||
cluster::DripstoneClusterFeature, large::LargeDripstoneFeature,
|
||||
small::SmallDripstoneFeature,
|
||||
},
|
||||
end_gateway::EndGatewayFeature,
|
||||
end_island::EndIslandFeature,
|
||||
end_platform::EndPlatformFeature,
|
||||
end_spike::EndSpikeFeature,
|
||||
fallen_tree::FallenTreeFeature,
|
||||
fill_layer::FillLayerFeature,
|
||||
forest_rock::ForestRockFeature,
|
||||
fossil::FossilFeature,
|
||||
freeze_top_layer::FreezeTopLayerFeature,
|
||||
geode::GeodeFeature,
|
||||
glowstone_blob::GlowstoneBlobFeature,
|
||||
huge_brown_mushroom::HugeBrownMushroomFeature,
|
||||
huge_fungus::HugeFungusFeature,
|
||||
huge_red_mushroom::HugeRedMushroomFeature,
|
||||
ice_spike::IceSpikeFeature,
|
||||
iceberg::IcebergFeature,
|
||||
kelp::KelpFeature,
|
||||
lake::LakeFeature,
|
||||
monster_room::DungeonFeature,
|
||||
multiface_growth::MultifaceGrowthFeature,
|
||||
nether_forest_vegetation::NetherForestVegetationFeature,
|
||||
netherrack_replace_blobs::ReplaceBlobsFeature,
|
||||
ore::OreFeature,
|
||||
random_boolean_selector::RandomBooleanFeature,
|
||||
random_patch::RandomPatchFeature,
|
||||
random_selector::RandomFeature,
|
||||
replace_single_block::ReplaceSingleBlockFeature,
|
||||
root_system::RootSystemFeature,
|
||||
scattered_ore::ScatteredOreFeature,
|
||||
sculk_patch::SculkPatchFeature,
|
||||
sea_pickle::SeaPickleFeature,
|
||||
seagrass::SeagrassFeature,
|
||||
simple_block::SimpleBlockFeature,
|
||||
simple_random_selector::SimpleRandomFeature,
|
||||
spring_feature::SpringFeatureFeature,
|
||||
tree::TreeFeature,
|
||||
twisting_vines::TwistingVinesFeature,
|
||||
underwater_magma::UnderwaterMagmaFeature,
|
||||
vegetation_patch,
|
||||
vegetation_patch::VegetationPatchFeature,
|
||||
vines::VinesFeature,
|
||||
void_start_platform::VoidStartPlatformFeature,
|
||||
waterlogged_vegetation_patch,
|
||||
waterlogged_vegetation_patch::WaterloggedVegetationPatchFeature,
|
||||
weeping_vines::WeepingVinesFeature,
|
||||
};
|
||||
use crate::generation::proto_chunk::GenerationCache;
|
||||
use crate::world::WorldPortalExt;
|
||||
|
||||
pub static CONFIGURED_FEATURES: LazyLock<
|
||||
HashMap<pumpkin_data::configured_feature::ConfiguredFeature, ConfiguredFeature>,
|
||||
> = LazyLock::new(build_configured_features);
|
||||
|
||||
pub enum ConfiguredFeature {
|
||||
NoOp,
|
||||
Tree(Box<TreeFeature>),
|
||||
FallenTree(FallenTreeFeature),
|
||||
Flower(RandomPatchFeature),
|
||||
NoBonemealFlower(RandomPatchFeature),
|
||||
RandomPatch(RandomPatchFeature),
|
||||
BlockPile(BlockPileFeature),
|
||||
SpringFeature(SpringFeatureFeature),
|
||||
ChorusPlant(ChorusPlantFeature),
|
||||
ReplaceSingleBlock(ReplaceSingleBlockFeature),
|
||||
VoidStartPlatform(VoidStartPlatformFeature),
|
||||
DesertWell(DesertWellFeature),
|
||||
Fossil(FossilFeature),
|
||||
HugeRedMushroom(HugeRedMushroomFeature),
|
||||
HugeBrownMushroom(HugeBrownMushroomFeature),
|
||||
IceSpike(IceSpikeFeature),
|
||||
GlowstoneBlob(GlowstoneBlobFeature),
|
||||
FreezeTopLayer(FreezeTopLayerFeature),
|
||||
Vines(VinesFeature),
|
||||
BlockColumn(BlockColumnFeature),
|
||||
VegetationPatch(VegetationPatchFeature),
|
||||
WaterloggedVegetationPatch(WaterloggedVegetationPatchFeature),
|
||||
RootSystem(RootSystemFeature),
|
||||
MultifaceGrowth(MultifaceGrowthFeature),
|
||||
UnderwaterMagma(UnderwaterMagmaFeature),
|
||||
MonsterRoom(DungeonFeature),
|
||||
BlueIce(BlueIceFeature),
|
||||
Iceberg(IcebergFeature),
|
||||
ForestRock(ForestRockFeature),
|
||||
Disk(DiskFeature),
|
||||
Lake(LakeFeature),
|
||||
Ore(OreFeature),
|
||||
EndPlatform(EndPlatformFeature),
|
||||
EndSpike(EndSpikeFeature),
|
||||
EndIsland(EndIslandFeature),
|
||||
EndGateway(EndGatewayFeature),
|
||||
Seagrass(SeagrassFeature),
|
||||
Kelp(KelpFeature),
|
||||
CoralTree(CoralTreeFeature),
|
||||
CoralMushroom(CoralMushroomFeature),
|
||||
CoralClaw(CoralClawFeature),
|
||||
SeaPickle(SeaPickleFeature),
|
||||
SimpleBlock(SimpleBlockFeature),
|
||||
Bamboo(BambooFeature),
|
||||
HugeFungus(HugeFungusFeature),
|
||||
NetherForestVegetation(NetherForestVegetationFeature),
|
||||
WeepingVines(WeepingVinesFeature),
|
||||
TwistingVines(TwistingVinesFeature),
|
||||
BasaltColumns(BasaltColumnsFeature),
|
||||
DeltaFeature(DeltaFeatureFeature),
|
||||
NetherrackReplaceBlobs(ReplaceBlobsFeature),
|
||||
FillLayer(FillLayerFeature),
|
||||
BonusChest(BonusChestFeature),
|
||||
BasaltPillar(BasaltPillarFeature),
|
||||
ScatteredOre(ScatteredOreFeature),
|
||||
RandomSelector(RandomFeature),
|
||||
SimpleRandomSelector(SimpleRandomFeature),
|
||||
RandomBooleanSelector(RandomBooleanFeature),
|
||||
Geode(Box<GeodeFeature>),
|
||||
DripstoneCluster(DripstoneClusterFeature),
|
||||
LargeDripstone(LargeDripstoneFeature),
|
||||
PointedDripstone(SmallDripstoneFeature),
|
||||
SculkPatch(SculkPatchFeature),
|
||||
}
|
||||
|
||||
// Yes this may look ugly and you wonder why this is hard coded, but it makes sense to hardcode since we have to add logic for these in code
|
||||
|
||||
impl ConfiguredFeature {
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
#[expect(clippy::too_many_lines)]
|
||||
pub fn generate<T: GenerationCache>(
|
||||
&self,
|
||||
chunk: &mut T,
|
||||
block_registry: &dyn WorldPortalExt,
|
||||
min_y: i8,
|
||||
height: u16,
|
||||
feature_name: pumpkin_data::placed_feature::PlacedFeature, // This placed feature
|
||||
random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> bool {
|
||||
match self {
|
||||
Self::NetherrackReplaceBlobs(feature) => feature.generate(
|
||||
chunk,
|
||||
block_registry,
|
||||
min_y,
|
||||
height,
|
||||
feature_name,
|
||||
random,
|
||||
pos,
|
||||
),
|
||||
Self::NetherForestVegetation(feature) => feature.generate(
|
||||
chunk,
|
||||
block_registry,
|
||||
min_y,
|
||||
height,
|
||||
feature_name,
|
||||
random,
|
||||
pos,
|
||||
),
|
||||
Self::VegetationPatch(feature) => feature.generate(
|
||||
chunk,
|
||||
block_registry,
|
||||
min_y,
|
||||
height,
|
||||
feature_name,
|
||||
random,
|
||||
pos,
|
||||
),
|
||||
Self::WaterloggedVegetationPatch(feature) => feature.generate(
|
||||
chunk,
|
||||
block_registry,
|
||||
min_y,
|
||||
height,
|
||||
feature_name,
|
||||
random,
|
||||
pos,
|
||||
),
|
||||
Self::PointedDripstone(feature) => feature.generate(chunk, random, pos),
|
||||
Self::CoralMushroom(_feature) => CoralMushroomFeature::generate(
|
||||
chunk,
|
||||
block_registry,
|
||||
min_y,
|
||||
height,
|
||||
feature_name,
|
||||
random,
|
||||
pos,
|
||||
),
|
||||
Self::CoralTree(_feature) => CoralTreeFeature::generate(
|
||||
chunk,
|
||||
block_registry,
|
||||
min_y,
|
||||
height,
|
||||
feature_name,
|
||||
random,
|
||||
pos,
|
||||
),
|
||||
Self::CoralClaw(_feature) => CoralClawFeature::generate(
|
||||
chunk,
|
||||
block_registry,
|
||||
min_y,
|
||||
height,
|
||||
feature_name,
|
||||
random,
|
||||
pos,
|
||||
),
|
||||
Self::EndPlatform(_feature) => EndPlatformFeature::generate(
|
||||
chunk,
|
||||
block_registry,
|
||||
min_y,
|
||||
height,
|
||||
feature_name,
|
||||
random,
|
||||
pos,
|
||||
),
|
||||
Self::EndSpike(feature) => feature.generate(
|
||||
chunk,
|
||||
block_registry,
|
||||
min_y,
|
||||
height,
|
||||
feature_name,
|
||||
random,
|
||||
pos,
|
||||
),
|
||||
Self::SpringFeature(feature) => feature.generate(block_registry, chunk, random, pos),
|
||||
Self::SimpleBlock(feature) => feature.generate(block_registry, chunk, random, pos),
|
||||
Self::RandomPatch(feature)
|
||||
| Self::Flower(feature)
|
||||
| Self::NoBonemealFlower(feature) => feature.generate(
|
||||
chunk,
|
||||
block_registry,
|
||||
min_y,
|
||||
height,
|
||||
feature_name,
|
||||
random,
|
||||
pos,
|
||||
),
|
||||
Self::DesertWell(_feature) => {
|
||||
DesertWellFeature::generate(chunk, min_y, height, feature_name, random, pos)
|
||||
}
|
||||
Self::Fossil(feature) => feature.generate(chunk, min_y, height, random, pos),
|
||||
Self::Bamboo(feature) => feature.generate(
|
||||
chunk,
|
||||
block_registry,
|
||||
min_y,
|
||||
height,
|
||||
feature_name,
|
||||
random,
|
||||
pos,
|
||||
),
|
||||
Self::BlockColumn(feature) => feature.generate(
|
||||
chunk,
|
||||
block_registry,
|
||||
min_y,
|
||||
height,
|
||||
feature_name,
|
||||
random,
|
||||
pos,
|
||||
),
|
||||
Self::RandomBooleanSelector(feature) => feature.generate(
|
||||
chunk,
|
||||
block_registry,
|
||||
min_y,
|
||||
height,
|
||||
feature_name,
|
||||
random,
|
||||
pos,
|
||||
),
|
||||
Self::Tree(feature) => feature.generate(
|
||||
block_registry,
|
||||
chunk,
|
||||
min_y,
|
||||
height,
|
||||
feature_name,
|
||||
random,
|
||||
pos,
|
||||
),
|
||||
Self::RandomSelector(feature) => feature.generate(
|
||||
chunk,
|
||||
block_registry,
|
||||
min_y,
|
||||
height,
|
||||
feature_name,
|
||||
random,
|
||||
pos,
|
||||
),
|
||||
Self::SimpleRandomSelector(feature) => feature.generate(
|
||||
chunk,
|
||||
block_registry,
|
||||
min_y,
|
||||
height,
|
||||
feature_name,
|
||||
random,
|
||||
pos,
|
||||
),
|
||||
Self::Vines(_feature) => VinesFeature::generate(
|
||||
chunk,
|
||||
block_registry,
|
||||
min_y,
|
||||
height,
|
||||
feature_name,
|
||||
random,
|
||||
pos,
|
||||
),
|
||||
Self::Seagrass(feature) => {
|
||||
feature.generate(chunk, min_y, height, feature_name, random, pos)
|
||||
}
|
||||
Self::TwistingVines(feature) => {
|
||||
feature.generate(chunk, min_y, height, feature_name, random, pos)
|
||||
}
|
||||
Self::UnderwaterMagma(feature) => {
|
||||
feature.generate(chunk, min_y, height, feature_name, random, pos)
|
||||
}
|
||||
Self::SeaPickle(feature) => {
|
||||
feature.generate(chunk, min_y, height, feature_name, random, pos)
|
||||
}
|
||||
Self::Geode(feature) => feature.generate(
|
||||
chunk,
|
||||
block_registry,
|
||||
min_y,
|
||||
height,
|
||||
feature_name,
|
||||
random,
|
||||
pos,
|
||||
),
|
||||
Self::Kelp(_feature) => {
|
||||
KelpFeature::generate(chunk, min_y, height, feature_name, random, pos)
|
||||
}
|
||||
Self::Ore(feature) => feature.generate(
|
||||
chunk,
|
||||
block_registry,
|
||||
min_y,
|
||||
height,
|
||||
feature_name,
|
||||
random,
|
||||
pos,
|
||||
),
|
||||
Self::ScatteredOre(feature) => feature.generate(
|
||||
chunk,
|
||||
block_registry,
|
||||
min_y,
|
||||
height,
|
||||
feature_name,
|
||||
random,
|
||||
pos,
|
||||
),
|
||||
Self::MonsterRoom(_feature) => {
|
||||
DungeonFeature::generate(chunk, min_y, height, feature_name, random, pos)
|
||||
}
|
||||
Self::BlueIce(_feature) => BlueIceFeature::generate(chunk, random, pos),
|
||||
Self::GlowstoneBlob(_feature) => {
|
||||
GlowstoneBlobFeature::generate(chunk, min_y, height, feature_name, random, pos)
|
||||
}
|
||||
Self::Disk(feature) => feature.generate(
|
||||
chunk,
|
||||
block_registry,
|
||||
min_y,
|
||||
height,
|
||||
feature_name,
|
||||
random,
|
||||
pos,
|
||||
),
|
||||
Self::Lake(feature) => feature.generate(block_registry, chunk, random, pos),
|
||||
Self::BasaltColumns(feature) => feature.generate(
|
||||
chunk,
|
||||
block_registry,
|
||||
min_y,
|
||||
height,
|
||||
feature_name,
|
||||
random,
|
||||
pos,
|
||||
),
|
||||
Self::BasaltPillar(_feature) => BasaltPillarFeature::generate(chunk, random, pos),
|
||||
Self::ForestRock(feature) => feature.generate(chunk, random, pos),
|
||||
Self::FreezeTopLayer(_feature) => {
|
||||
FreezeTopLayerFeature::generate(chunk, min_y, height, feature_name, random, pos)
|
||||
}
|
||||
Self::IceSpike(_feature) => {
|
||||
IceSpikeFeature::generate(chunk, min_y, height, feature_name, random, pos)
|
||||
}
|
||||
Self::Iceberg(feature) => {
|
||||
feature.generate(chunk, min_y, height, feature_name, random, pos)
|
||||
}
|
||||
Self::ChorusPlant(_feature) => {
|
||||
ChorusPlantFeature::generate(chunk, min_y, height, feature_name, random, pos)
|
||||
}
|
||||
Self::EndIsland(_feature) => {
|
||||
EndIslandFeature::generate(chunk, min_y, height, feature_name, random, pos)
|
||||
}
|
||||
Self::SculkPatch(feature) => feature.generate(block_registry, chunk, random, pos),
|
||||
Self::RootSystem(feature) => feature.generate(
|
||||
chunk,
|
||||
block_registry,
|
||||
min_y,
|
||||
height,
|
||||
feature_name,
|
||||
random,
|
||||
pos,
|
||||
),
|
||||
Self::BonusChest(_feature) => {
|
||||
BonusChestFeature::generate(chunk, min_y, height, feature_name, random, pos)
|
||||
}
|
||||
Self::DeltaFeature(_feature) => {
|
||||
DeltaFeatureFeature::generate(chunk, min_y, height, feature_name, random, pos)
|
||||
}
|
||||
Self::DripstoneCluster(feature) => feature.generate(chunk, random, pos),
|
||||
Self::LargeDripstone(feature) => feature.generate(chunk, random, pos),
|
||||
Self::EndGateway(_feature) => {
|
||||
EndGatewayFeature::generate(chunk, min_y, height, feature_name, random, pos)
|
||||
}
|
||||
Self::FillLayer(feature) => {
|
||||
feature.generate(chunk, min_y, height, feature_name, random, pos)
|
||||
}
|
||||
Self::HugeBrownMushroom(feature) => {
|
||||
feature.generate(chunk, min_y, height, feature_name, random, pos)
|
||||
}
|
||||
Self::HugeFungus(feature) => {
|
||||
feature.generate(chunk, min_y, height, feature_name, random, pos)
|
||||
}
|
||||
Self::HugeRedMushroom(feature) => {
|
||||
feature.generate(chunk, min_y, height, feature_name, random, pos)
|
||||
}
|
||||
Self::MultifaceGrowth(feature) => {
|
||||
feature.generate(chunk, min_y, height, feature_name, random, pos)
|
||||
}
|
||||
Self::ReplaceSingleBlock(feature) => {
|
||||
feature.generate(chunk, min_y, height, feature_name, random, pos)
|
||||
}
|
||||
Self::VoidStartPlatform(feature) => {
|
||||
feature.generate(chunk, min_y, height, feature_name, random, pos)
|
||||
}
|
||||
Self::WeepingVines(feature) => {
|
||||
feature.generate(chunk, min_y, height, feature_name, random, pos)
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// generated code is now placed alongside other codegen outputs
|
||||
// in `src/generated` so we don’t hide it deep under `generation/feature`.
|
||||
include!("../../../../pumpkin-data/src/generated/configured_features_generated.rs");
|
||||
@@ -0,0 +1,87 @@
|
||||
use pumpkin_data::{
|
||||
Block, BlockState,
|
||||
block_properties::{BambooLeaves, BambooLikeProperties, BlockProperties},
|
||||
tag,
|
||||
};
|
||||
use pumpkin_util::{
|
||||
math::position::BlockPos,
|
||||
random::{RandomGenerator, RandomImpl},
|
||||
};
|
||||
|
||||
use crate::generation::proto_chunk::GenerationCache;
|
||||
use crate::world::WorldPortalExt;
|
||||
|
||||
pub struct BambooFeature {
|
||||
pub probability: f32,
|
||||
}
|
||||
|
||||
impl BambooFeature {
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
pub fn generate<T: GenerationCache>(
|
||||
&self,
|
||||
chunk: &mut T,
|
||||
block_registry: &dyn WorldPortalExt,
|
||||
_min_y: i8,
|
||||
_height: u16,
|
||||
_feature: pumpkin_data::placed_feature::PlacedFeature, // This placed feature
|
||||
random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> bool {
|
||||
let mut i = 0;
|
||||
if chunk.is_air(&pos.0) {
|
||||
if block_registry.can_place_at(&Block::BAMBOO, Block::BAMBOO.default_state, chunk, &pos)
|
||||
{
|
||||
let height = random.next_bounded_i32(12) + 5;
|
||||
if random.next_f32() < self.probability {
|
||||
let rnd = random.next_bounded_i32(4) + 1;
|
||||
for x in pos.0.x - rnd..pos.0.x + rnd {
|
||||
for z in pos.0.z - rnd..pos.0.z + rnd {
|
||||
let block_below =
|
||||
BlockPos::new(x, chunk.top_block_height_exclusive(x, z) - 1, z);
|
||||
let block = GenerationCache::get_block_state(chunk, &block_below.0);
|
||||
if !block.to_block_id().has_tag(tag::Block::MINECRAFT_DIRT) {
|
||||
continue;
|
||||
}
|
||||
chunk.set_block_state(&block_below.0, Block::PODZOL.default_state);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut bpos = pos;
|
||||
let bamboo = Block::BAMBOO.default_state;
|
||||
for _ in 0..height {
|
||||
if chunk.is_air(&bpos.0) {
|
||||
chunk.set_block_state(&bpos.0, bamboo);
|
||||
bpos = bpos.up();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// Top block
|
||||
if bpos.0.y - pos.0.y >= 3 {
|
||||
let mut props = BambooLikeProperties::default(&Block::BAMBOO);
|
||||
props.leaves = BambooLeaves::Large;
|
||||
props.stage = 1;
|
||||
|
||||
chunk.set_block_state(
|
||||
&bpos.0,
|
||||
BlockState::from_id(props.to_state_id(&Block::BAMBOO)),
|
||||
);
|
||||
props.stage = 0;
|
||||
|
||||
chunk.set_block_state(
|
||||
&bpos.down().0,
|
||||
BlockState::from_id(props.to_state_id(&Block::BAMBOO)),
|
||||
);
|
||||
props.leaves = BambooLeaves::Small;
|
||||
|
||||
chunk.set_block_state(
|
||||
&bpos.down().down().0,
|
||||
BlockState::from_id(props.to_state_id(&Block::BAMBOO)),
|
||||
);
|
||||
}
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
i > 0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
use pumpkin_data::{Block, BlockId, block_properties::is_air};
|
||||
use pumpkin_util::{
|
||||
math::{int_provider::IntProvider, position::BlockPos},
|
||||
random::{RandomGenerator, RandomImpl},
|
||||
};
|
||||
|
||||
use crate::{generation::proto_chunk::GenerationCache, world::WorldPortalExt};
|
||||
|
||||
const LAVA_SEA_LEVEL: i32 = 32; // TODO: use getSeaLevel() instead of hardcoding this
|
||||
const CLUSTERED_REACH: i32 = 5;
|
||||
const UNCLUSTERED_REACH: i32 = 8;
|
||||
const CLUSTERED_SIZE: i32 = 50;
|
||||
const UNCLUSTERED_SIZE: i32 = 15;
|
||||
|
||||
pub struct BasaltColumnsFeature {
|
||||
pub height: IntProvider,
|
||||
pub reach: IntProvider,
|
||||
}
|
||||
|
||||
impl BasaltColumnsFeature {
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
pub fn generate<T: GenerationCache>(
|
||||
&self,
|
||||
chunk: &mut T,
|
||||
_block_registry: &dyn WorldPortalExt,
|
||||
_min_y: i8,
|
||||
_height_limit: u16,
|
||||
_feature: pumpkin_data::placed_feature::PlacedFeature,
|
||||
random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> bool {
|
||||
if !can_place_at(chunk, pos) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let column_height = self.height.get(random);
|
||||
let clustered = random.next_f32() < 0.9;
|
||||
let spread = column_height.min(if clustered {
|
||||
CLUSTERED_REACH
|
||||
} else {
|
||||
UNCLUSTERED_REACH
|
||||
});
|
||||
let count = if clustered {
|
||||
CLUSTERED_SIZE
|
||||
} else {
|
||||
UNCLUSTERED_SIZE
|
||||
};
|
||||
let mut placed = false;
|
||||
|
||||
for _ in 0..count {
|
||||
let x = random.next_inbetween_i32(pos.0.x - spread, pos.0.x + spread);
|
||||
let z = random.next_inbetween_i32(pos.0.z - spread, pos.0.z + spread);
|
||||
let iter_pos = BlockPos::new(x, pos.0.y, z);
|
||||
let blocks_to_place_y = column_height - iter_pos.manhattan_distance(pos);
|
||||
if blocks_to_place_y >= 0 {
|
||||
let inner_reach = self.reach.get(random);
|
||||
placed |= place_column(chunk, iter_pos, blocks_to_place_y, inner_reach);
|
||||
}
|
||||
}
|
||||
|
||||
placed
|
||||
}
|
||||
}
|
||||
|
||||
fn place_column<T: GenerationCache>(
|
||||
chunk: &mut T,
|
||||
origin: BlockPos,
|
||||
column_height: i32,
|
||||
reach: i32,
|
||||
) -> bool {
|
||||
let mut placed_any = false;
|
||||
|
||||
for x in (origin.0.x - reach)..=(origin.0.x + reach) {
|
||||
for z in (origin.0.z - reach)..=(origin.0.z + reach) {
|
||||
let pos = BlockPos::new(x, origin.0.y, z);
|
||||
let step_limit = pos.manhattan_distance(origin);
|
||||
|
||||
let column_pos = if is_air_or_lava_ocean(chunk, pos) {
|
||||
find_surface(chunk, pos, step_limit)
|
||||
} else {
|
||||
find_air(chunk, pos, step_limit)
|
||||
};
|
||||
|
||||
if let Some(mut cursor) = column_pos {
|
||||
let mut blocks_y = column_height - step_limit / 2;
|
||||
while blocks_y >= 0 {
|
||||
if is_air_or_lava_ocean(chunk, cursor) {
|
||||
chunk.set_block_state(&cursor.0, Block::BASALT.default_state);
|
||||
cursor = cursor.up();
|
||||
placed_any = true;
|
||||
} else {
|
||||
let block_id =
|
||||
GenerationCache::get_block_state(chunk, &cursor.0).to_block_id();
|
||||
if block_id != Block::BASALT.id {
|
||||
break;
|
||||
}
|
||||
cursor = cursor.up();
|
||||
}
|
||||
blocks_y -= 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
placed_any
|
||||
}
|
||||
|
||||
fn find_surface<T: GenerationCache>(chunk: &T, pos: BlockPos, mut limit: i32) -> Option<BlockPos> {
|
||||
let mut cursor = pos;
|
||||
while cursor.0.y > chunk.bottom_y() as i32 + 1 && limit > 0 {
|
||||
limit -= 1;
|
||||
if can_place_at(chunk, cursor) {
|
||||
return Some(cursor);
|
||||
}
|
||||
cursor = cursor.down();
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn can_place_at<T: GenerationCache>(chunk: &T, pos: BlockPos) -> bool {
|
||||
if !is_air_or_lava_ocean(chunk, pos) {
|
||||
return false;
|
||||
}
|
||||
let below = GenerationCache::get_block_state(chunk, &pos.down().0);
|
||||
!is_air(below) && !is_cannot_place_on(below.to_block_id())
|
||||
}
|
||||
|
||||
fn find_air<T: GenerationCache>(chunk: &T, pos: BlockPos, mut limit: i32) -> Option<BlockPos> {
|
||||
let mut cursor = pos;
|
||||
while cursor.0.y < chunk.top_y() as i32 && limit > 0 {
|
||||
limit -= 1;
|
||||
let state = GenerationCache::get_block_state(chunk, &cursor.0);
|
||||
if is_cannot_place_on(state.to_block_id()) {
|
||||
return None;
|
||||
}
|
||||
if is_air(state) {
|
||||
return Some(cursor);
|
||||
}
|
||||
cursor = cursor.up();
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn is_air_or_lava_ocean<T: GenerationCache>(chunk: &T, pos: BlockPos) -> bool {
|
||||
let state = GenerationCache::get_block_state(chunk, &pos.0);
|
||||
is_air(state) || (state.to_block_id() == Block::LAVA.id && pos.0.y <= LAVA_SEA_LEVEL)
|
||||
}
|
||||
|
||||
const fn is_cannot_place_on(id: BlockId) -> bool {
|
||||
matches!(
|
||||
id,
|
||||
BlockId::LAVA
|
||||
| BlockId::BEDROCK
|
||||
| BlockId::MAGMA_BLOCK
|
||||
| BlockId::SOUL_SAND
|
||||
| BlockId::NETHER_BRICKS
|
||||
| BlockId::NETHER_BRICK_FENCE
|
||||
| BlockId::NETHER_BRICK_STAIRS
|
||||
| BlockId::NETHER_WART
|
||||
| BlockId::CHEST
|
||||
| BlockId::SPAWNER
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
use pumpkin_data::Block;
|
||||
use pumpkin_util::{
|
||||
math::position::BlockPos,
|
||||
random::{RandomGenerator, RandomImpl},
|
||||
};
|
||||
|
||||
use crate::generation::proto_chunk::GenerationCache;
|
||||
|
||||
pub struct BasaltPillarFeature;
|
||||
|
||||
impl BasaltPillarFeature {
|
||||
pub fn generate<T: GenerationCache>(
|
||||
chunk: &mut T,
|
||||
random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> bool {
|
||||
if !chunk.is_air(&pos.0) || chunk.is_air(&pos.up().0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let basalt = &Block::BASALT.default_state;
|
||||
|
||||
let mut cur_pos = pos;
|
||||
let mut place_north = true;
|
||||
let mut place_south = true;
|
||||
let mut place_west = true;
|
||||
let mut place_east = true;
|
||||
|
||||
while chunk.is_air(&cur_pos.0) {
|
||||
if chunk.out_of_height(cur_pos.0.y as i16) {
|
||||
return true;
|
||||
}
|
||||
chunk.set_block_state(&cur_pos.0, basalt);
|
||||
place_north = place_north && Self::place_hang_off(chunk, random, cur_pos.north());
|
||||
place_south = place_south && Self::place_hang_off(chunk, random, cur_pos.south());
|
||||
place_west = place_west && Self::place_hang_off(chunk, random, cur_pos.west());
|
||||
place_east = place_east && Self::place_hang_off(chunk, random, cur_pos.east());
|
||||
cur_pos = cur_pos.down();
|
||||
}
|
||||
|
||||
cur_pos = cur_pos.up();
|
||||
Self::place_base_hang_off(chunk, random, cur_pos.north());
|
||||
Self::place_base_hang_off(chunk, random, cur_pos.south());
|
||||
Self::place_base_hang_off(chunk, random, cur_pos.west());
|
||||
Self::place_base_hang_off(chunk, random, cur_pos.east());
|
||||
cur_pos = cur_pos.down();
|
||||
|
||||
for dx in -3i32..4 {
|
||||
for dz in -3i32..4 {
|
||||
let probability = dx.abs() * dz.abs();
|
||||
if random.next_bounded_i32(10) < 10 - probability {
|
||||
let mut base_pos =
|
||||
BlockPos::new(cur_pos.0.x + dx, cur_pos.0.y, cur_pos.0.z + dz);
|
||||
let mut max_drop = 3i32;
|
||||
while chunk.is_air(&base_pos.down().0) {
|
||||
base_pos = base_pos.down();
|
||||
max_drop -= 1;
|
||||
if max_drop <= 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if !chunk.is_air(&base_pos.down().0) {
|
||||
chunk.set_block_state(&base_pos.0, basalt);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
fn place_base_hang_off<T: GenerationCache>(
|
||||
chunk: &mut T,
|
||||
random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) {
|
||||
if random.next_bool() {
|
||||
chunk.set_block_state(&pos.0, Block::BASALT.default_state);
|
||||
}
|
||||
}
|
||||
|
||||
fn place_hang_off<T: GenerationCache>(
|
||||
chunk: &mut T,
|
||||
random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> bool {
|
||||
if random.next_bounded_i32(10) != 0 {
|
||||
chunk.set_block_state(&pos.0, Block::BASALT.default_state);
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
use pumpkin_data::BlockDirection;
|
||||
use pumpkin_util::{
|
||||
math::{int_provider::IntProvider, position::BlockPos},
|
||||
random::RandomGenerator,
|
||||
};
|
||||
|
||||
use crate::generation::proto_chunk::GenerationCache;
|
||||
use crate::{
|
||||
generation::{block_predicate::BlockPredicate, block_state_provider::BlockStateProvider},
|
||||
world::WorldPortalExt,
|
||||
};
|
||||
|
||||
pub struct BlockColumnFeature {
|
||||
pub layers: Vec<Layer>,
|
||||
pub direction: BlockDirection,
|
||||
pub allowed_placement: BlockPredicate,
|
||||
pub prioritize_tip: bool,
|
||||
}
|
||||
|
||||
pub struct Layer {
|
||||
pub height: IntProvider,
|
||||
pub provider: BlockStateProvider,
|
||||
}
|
||||
|
||||
impl BlockColumnFeature {
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
pub fn generate<T: GenerationCache>(
|
||||
&self,
|
||||
chunk: &mut T,
|
||||
block_registry: &dyn WorldPortalExt,
|
||||
_min_y: i8,
|
||||
_height: u16,
|
||||
_feature: pumpkin_data::placed_feature::PlacedFeature,
|
||||
random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> bool {
|
||||
let i = self.layers.len();
|
||||
let mut is = vec![0; i];
|
||||
let mut j = 0;
|
||||
|
||||
for (k, item) in is.iter_mut().enumerate().take(i) {
|
||||
*item = (self.layers[k].height).get(random);
|
||||
j += *item;
|
||||
}
|
||||
|
||||
if j == 0 {
|
||||
return false;
|
||||
}
|
||||
|
||||
let mut mutable = pos;
|
||||
let mut mutable2 = mutable.offset(self.direction.to_offset());
|
||||
|
||||
let mut l = 0;
|
||||
while l < j {
|
||||
if !self
|
||||
.allowed_placement
|
||||
.test(block_registry, chunk, &mutable2)
|
||||
{
|
||||
Self::adjust_layer_heights(&mut is, j, l, self.prioritize_tip);
|
||||
break;
|
||||
}
|
||||
mutable2 = mutable2.offset(self.direction.to_offset());
|
||||
l += 1;
|
||||
}
|
||||
|
||||
for (l, m) in is.iter().enumerate().take(i) {
|
||||
if *m == 0 {
|
||||
continue;
|
||||
}
|
||||
let layer = &self.layers[l];
|
||||
for _n in 0..*m {
|
||||
let state = layer.provider.get(random, mutable, chunk, block_registry);
|
||||
chunk.set_block_state(&mutable.0, state);
|
||||
mutable = mutable.offset(self.direction.to_offset());
|
||||
}
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
fn adjust_layer_heights(
|
||||
layer_heights: &mut [i32],
|
||||
expected_height: i32,
|
||||
actual_height: i32,
|
||||
prioritize_tip: bool,
|
||||
) {
|
||||
let mut i = expected_height - actual_height;
|
||||
let j = if prioritize_tip { 1 } else { -1 };
|
||||
let k = if prioritize_tip {
|
||||
0
|
||||
} else {
|
||||
layer_heights.len() as i32 - 1
|
||||
};
|
||||
let l = if prioritize_tip {
|
||||
layer_heights.len() as i32
|
||||
} else {
|
||||
-1
|
||||
};
|
||||
|
||||
let mut m = k;
|
||||
while m != l && i > 0 {
|
||||
let n = layer_heights[m as usize];
|
||||
let o = std::cmp::min(n, i);
|
||||
layer_heights[m as usize] -= o;
|
||||
i -= o;
|
||||
m += j;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
pub struct BlockPileFeature;
|
||||
@@ -0,0 +1,94 @@
|
||||
use pumpkin_data::Block;
|
||||
use pumpkin_util::{
|
||||
math::position::BlockPos,
|
||||
random::{RandomGenerator, RandomImpl},
|
||||
};
|
||||
|
||||
use crate::generation::proto_chunk::GenerationCache;
|
||||
|
||||
const SEA_LEVEL: i32 = 63; // TODO: use getSeaLevel() instead of hardcoding
|
||||
|
||||
pub struct BlueIceFeature;
|
||||
|
||||
impl BlueIceFeature {
|
||||
pub fn generate<T: GenerationCache>(
|
||||
chunk: &mut T,
|
||||
random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> bool {
|
||||
if pos.0.y >= SEA_LEVEL - 1 {
|
||||
return false;
|
||||
}
|
||||
|
||||
let block = GenerationCache::get_block_state(chunk, &pos.0).to_state();
|
||||
let block_below = GenerationCache::get_block_state(chunk, &pos.down().0).to_state();
|
||||
|
||||
if block != Block::WATER.default_state && block_below != Block::WATER.default_state {
|
||||
return false;
|
||||
}
|
||||
|
||||
let mut has_ice_neighbor = false;
|
||||
for neighbor_pos in [
|
||||
pos.up(),
|
||||
pos.down(),
|
||||
pos.north(),
|
||||
pos.south(),
|
||||
pos.east(),
|
||||
pos.west(),
|
||||
] {
|
||||
if GenerationCache::get_block_state(chunk, &neighbor_pos.0).to_state()
|
||||
== Block::ICE.default_state
|
||||
{
|
||||
has_ice_neighbor = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if !has_ice_neighbor {
|
||||
return false;
|
||||
}
|
||||
|
||||
chunk.set_block_state(&pos.0, Block::BLUE_ICE.default_state);
|
||||
|
||||
for _ in 0..200 {
|
||||
let offset_x = random.next_bounded_i32(8) - random.next_bounded_i32(8);
|
||||
let offset_y = random.next_bounded_i32(8) - random.next_bounded_i32(8);
|
||||
let offset_z = random.next_bounded_i32(8) - random.next_bounded_i32(8);
|
||||
let target_pos = pos.add(offset_x, offset_y, offset_z);
|
||||
|
||||
if chunk.out_of_height(target_pos.0.y as i16) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let target_state = GenerationCache::get_block_state(chunk, &target_pos.0).to_state();
|
||||
if target_state.is_air()
|
||||
|| target_state == Block::WATER.default_state
|
||||
|| target_state == Block::ICE.default_state
|
||||
|| target_state == Block::PACKED_ICE.default_state
|
||||
{
|
||||
let mut has_blue_ice_neighbor = false;
|
||||
for neighbor_pos in [
|
||||
target_pos.up(),
|
||||
target_pos.down(),
|
||||
target_pos.north(),
|
||||
target_pos.south(),
|
||||
target_pos.east(),
|
||||
target_pos.west(),
|
||||
] {
|
||||
if GenerationCache::get_block_state(chunk, &neighbor_pos.0).to_state()
|
||||
== Block::BLUE_ICE.default_state
|
||||
{
|
||||
has_blue_ice_neighbor = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if has_blue_ice_neighbor {
|
||||
chunk.set_block_state(&target_pos.0, Block::BLUE_ICE.default_state);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
use pumpkin_data::Block;
|
||||
use pumpkin_util::{math::position::BlockPos, random::RandomGenerator};
|
||||
|
||||
use crate::generation::proto_chunk::GenerationCache;
|
||||
|
||||
pub struct BonusChestFeature;
|
||||
|
||||
impl BonusChestFeature {
|
||||
pub fn generate<T: GenerationCache>(
|
||||
chunk: &mut T,
|
||||
_min_y: i8,
|
||||
_height: u16,
|
||||
_feature: pumpkin_data::placed_feature::PlacedFeature,
|
||||
_random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> bool {
|
||||
let mut block_pos = pos;
|
||||
while chunk.is_air(&block_pos.0) && block_pos.0.y > chunk.bottom_y() as i32 + 2 {
|
||||
block_pos = block_pos.down();
|
||||
}
|
||||
|
||||
let chest_pos = block_pos.up();
|
||||
if !chunk.is_air(&chest_pos.0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
chunk.set_block_state(&chest_pos.0, Block::CHEST.default_state);
|
||||
|
||||
let torch_offsets = [(1, 0, 0), (-1, 0, 0), (0, 0, 1), (0, 0, -1)];
|
||||
for &(dx, dy, dz) in &torch_offsets {
|
||||
let t_pos = BlockPos::new(chest_pos.0.x + dx, chest_pos.0.y + dy, chest_pos.0.z + dz);
|
||||
if chunk.is_air(&t_pos.0) {
|
||||
chunk.set_block_state(&t_pos.0, Block::TORCH.default_state);
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
use pumpkin_data::{
|
||||
Block, BlockDirection,
|
||||
block_properties::{
|
||||
BlockProperties, BrownMushroomBlockLikeProperties, ChorusFlowerLikeProperties,
|
||||
HorizontalFacing,
|
||||
},
|
||||
tag,
|
||||
};
|
||||
use pumpkin_util::{
|
||||
math::position::BlockPos,
|
||||
random::{RandomGenerator, RandomImpl},
|
||||
};
|
||||
|
||||
use crate::generation::proto_chunk::GenerationCache;
|
||||
|
||||
pub struct ChorusPlantFeature;
|
||||
|
||||
impl ChorusPlantFeature {
|
||||
pub fn generate<T: GenerationCache>(
|
||||
chunk: &mut T,
|
||||
_min_y: i8,
|
||||
_height: u16,
|
||||
_feature: pumpkin_data::placed_feature::PlacedFeature,
|
||||
random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> bool {
|
||||
let origin = pos.0;
|
||||
|
||||
// Must be an empty block placed on a supports_chorus_plant block (end_stone)
|
||||
if !chunk.is_air(&origin) {
|
||||
return false;
|
||||
}
|
||||
let below = pos.down().0;
|
||||
let below_id = GenerationCache::get_block_state(chunk, &below).to_block_id();
|
||||
if !below_id.has_tag(tag::Block::MINECRAFT_SUPPORTS_CHORUS_PLANT) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Place the base chorus plant with connections, then grow the tree
|
||||
set_chorus_plant(chunk, &pos);
|
||||
grow_tree_recursive(chunk, random, &pos, &pos, 8, 0);
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns `true` if all four horizontal neighbors of `pos` are air,
|
||||
/// optionally ignoring one direction (`ignore`).
|
||||
fn all_neighbors_empty<T: GenerationCache>(
|
||||
chunk: &T,
|
||||
pos: &BlockPos,
|
||||
ignore: Option<HorizontalFacing>,
|
||||
) -> bool {
|
||||
for dir in BlockDirection::horizontal() {
|
||||
if Some(dir) == ignore {
|
||||
continue;
|
||||
}
|
||||
if !chunk.is_air(&pos.offset(dir.to_offset()).0) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Computes chorus-plant connection state at `pos` and writes it to the chunk.
|
||||
fn set_chorus_plant<T: GenerationCache>(chunk: &mut T, pos: &BlockPos) {
|
||||
let down_id = GenerationCache::get_block_state(chunk, &pos.down().0).to_block_id();
|
||||
let up_id = GenerationCache::get_block_state(chunk, &pos.up().0).to_block_id();
|
||||
let north_id =
|
||||
GenerationCache::get_block_state(chunk, &pos.offset(BlockDirection::North.to_offset()).0)
|
||||
.to_block_id();
|
||||
let east_id =
|
||||
GenerationCache::get_block_state(chunk, &pos.offset(BlockDirection::East.to_offset()).0)
|
||||
.to_block_id();
|
||||
let south_id =
|
||||
GenerationCache::get_block_state(chunk, &pos.offset(BlockDirection::South.to_offset()).0)
|
||||
.to_block_id();
|
||||
let west_id =
|
||||
GenerationCache::get_block_state(chunk, &pos.offset(BlockDirection::West.to_offset()).0)
|
||||
.to_block_id();
|
||||
|
||||
let plant_id = Block::CHORUS_PLANT.id;
|
||||
let flower_id = Block::CHORUS_FLOWER.id;
|
||||
let supports = tag::Block::MINECRAFT_SUPPORTS_CHORUS_PLANT;
|
||||
|
||||
let props = BrownMushroomBlockLikeProperties {
|
||||
down: down_id == plant_id || down_id == flower_id || down_id.has_tag(supports),
|
||||
up: up_id == plant_id || up_id == flower_id,
|
||||
north: north_id == plant_id || north_id == flower_id,
|
||||
east: east_id == plant_id || east_id == flower_id,
|
||||
south: south_id == plant_id || south_id == flower_id,
|
||||
west: west_id == plant_id || west_id == flower_id,
|
||||
};
|
||||
|
||||
let state_id = props.to_state_id(&Block::CHORUS_PLANT);
|
||||
chunk.set_block_state(&pos.0, pumpkin_data::BlockState::from_id(state_id));
|
||||
}
|
||||
|
||||
/// Places a dead chorus flower (age 5) at `pos`.
|
||||
fn place_dead_flower<T: GenerationCache>(chunk: &mut T, pos: &BlockPos) {
|
||||
let props = ChorusFlowerLikeProperties { age: 5 };
|
||||
let state_id = props.to_state_id(&Block::CHORUS_FLOWER);
|
||||
chunk.set_block_state(&pos.0, pumpkin_data::BlockState::from_id(state_id));
|
||||
}
|
||||
|
||||
/// Recursively grows the chorus plant tree upward and laterally.
|
||||
fn grow_tree_recursive<T: GenerationCache>(
|
||||
chunk: &mut T,
|
||||
random: &mut RandomGenerator,
|
||||
current: &BlockPos,
|
||||
start_pos: &BlockPos,
|
||||
max_horizontal_spread: i32,
|
||||
depth: i32,
|
||||
) {
|
||||
let mut height = random.next_bounded_i32(4) + 1;
|
||||
if depth == 0 {
|
||||
height += 1;
|
||||
}
|
||||
|
||||
// Grow vertically: place chorus plant for `height` blocks above current
|
||||
for i in 0..height {
|
||||
let target = current.up_height(i + 1);
|
||||
if !all_neighbors_empty(chunk, &target, None) {
|
||||
return;
|
||||
}
|
||||
set_chorus_plant(chunk, &target);
|
||||
// Re-bake the block below so it gains the UP connection
|
||||
set_chorus_plant(chunk, &target.down());
|
||||
}
|
||||
|
||||
let top = current.up_height(height);
|
||||
let mut placed_stem = false;
|
||||
|
||||
if depth < 4 {
|
||||
let mut stems = random.next_bounded_i32(4);
|
||||
if depth == 0 {
|
||||
stems += 1;
|
||||
}
|
||||
|
||||
for _ in 0..stems {
|
||||
// Pick a random horizontal direction
|
||||
let dir = BlockDirection::horizontal()[random.next_bounded_i32(4) as usize];
|
||||
let target = top.offset(dir.to_offset());
|
||||
let target_below = target.down();
|
||||
|
||||
let dx = (target.0.x - start_pos.0.x).abs();
|
||||
let dz = (target.0.z - start_pos.0.z).abs();
|
||||
|
||||
if dx < max_horizontal_spread
|
||||
&& dz < max_horizontal_spread
|
||||
&& chunk.is_air(&target.0)
|
||||
&& chunk.is_air(&target_below.0)
|
||||
&& all_neighbors_empty(chunk, &target, Some(dir.opposite()))
|
||||
{
|
||||
placed_stem = true;
|
||||
set_chorus_plant(chunk, &target);
|
||||
// Re-bake the stem apex so it gains the connection face toward the new branch.
|
||||
set_chorus_plant(chunk, &top);
|
||||
grow_tree_recursive(
|
||||
chunk,
|
||||
random,
|
||||
&target,
|
||||
start_pos,
|
||||
max_horizontal_spread,
|
||||
depth + 1,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !placed_stem {
|
||||
// Cap the stem with a dead chorus flower
|
||||
place_dead_flower(chunk, &top);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
use crate::{generation::proto_chunk::GenerationCache, world::WorldPortalExt};
|
||||
use pumpkin_data::{BlockDirection, tag};
|
||||
use pumpkin_util::{
|
||||
math::position::BlockPos,
|
||||
random::{RandomGenerator, RandomImpl},
|
||||
};
|
||||
|
||||
use super::CoralFeature;
|
||||
|
||||
pub struct CoralClawFeature;
|
||||
|
||||
impl CoralClawFeature {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn generate<T: GenerationCache>(
|
||||
chunk: &mut T,
|
||||
block_registry: &dyn WorldPortalExt,
|
||||
_min_y: i8,
|
||||
_height: u16,
|
||||
_feature: pumpkin_data::placed_feature::PlacedFeature, // This placed feature
|
||||
random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> bool {
|
||||
// First lets get a random coral
|
||||
let block = CoralFeature::get_random_tag_entry(tag::Block::MINECRAFT_CORAL_BLOCKS, random);
|
||||
if !CoralFeature::generate_coral_piece(chunk, block_registry, random, block, pos) {
|
||||
return false;
|
||||
}
|
||||
let i = random.next_bounded_i32(2) + 2;
|
||||
let direction = BlockDirection::horizontal()
|
||||
[random.next_bounded_i32(BlockDirection::horizontal().len() as i32 - 1) as usize];
|
||||
// TODO: Shuffle
|
||||
let directions = BlockDirection::horizontal().into_iter().take(i as usize);
|
||||
'block0: for direction2 in directions {
|
||||
let mut pos = pos;
|
||||
let j = random.next_bounded_i32(2) + 1;
|
||||
pos = pos.offset(direction2.to_offset());
|
||||
|
||||
let branch_direction;
|
||||
|
||||
let k = if direction2 == direction {
|
||||
branch_direction = direction;
|
||||
random.next_bounded_i32(3) + 2
|
||||
} else {
|
||||
pos = pos.up();
|
||||
//let _directions = [direction2, BlockDirection::Up];
|
||||
branch_direction = direction2; // TODO: make this random
|
||||
random.next_bounded_i32(3) + 5
|
||||
};
|
||||
|
||||
for _ in 0..j {
|
||||
if !CoralFeature::generate_coral_piece(chunk, block_registry, random, block, pos) {
|
||||
break;
|
||||
}
|
||||
pos = pos.offset(branch_direction.to_offset());
|
||||
}
|
||||
|
||||
pos = pos.offset(branch_direction.to_offset());
|
||||
pos = pos.up();
|
||||
|
||||
for _l in 0..k {
|
||||
pos = pos.offset(direction.opposite().to_offset());
|
||||
if !CoralFeature::generate_coral_piece(chunk, block_registry, random, block, pos) {
|
||||
continue 'block0;
|
||||
}
|
||||
if random.next_f32() < 0.25 {
|
||||
pos = pos.up();
|
||||
}
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
use crate::{generation::proto_chunk::GenerationCache, world::WorldPortalExt};
|
||||
use pumpkin_data::tag;
|
||||
use pumpkin_util::{
|
||||
math::{position::BlockPos, vector3::Vector3},
|
||||
random::{RandomGenerator, RandomImpl},
|
||||
};
|
||||
|
||||
use super::CoralFeature;
|
||||
|
||||
pub struct CoralMushroomFeature;
|
||||
|
||||
impl CoralMushroomFeature {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn generate<T: GenerationCache>(
|
||||
chunk: &mut T,
|
||||
block_registry: &dyn WorldPortalExt,
|
||||
_min_y: i8,
|
||||
_height: u16,
|
||||
_feature: pumpkin_data::placed_feature::PlacedFeature, // This placed feature
|
||||
random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> bool {
|
||||
// First lets get a random coral
|
||||
let block = CoralFeature::get_random_tag_entry(tag::Block::MINECRAFT_CORAL_BLOCKS, random);
|
||||
|
||||
let i = random.next_bounded_i32(3) + 3;
|
||||
let j = random.next_bounded_i32(3) + 3;
|
||||
let k = random.next_bounded_i32(3) + 3;
|
||||
let l = random.next_bounded_i32(3) + 1;
|
||||
|
||||
for m in 0..=j {
|
||||
for n in 0..=i {
|
||||
for o in 0..=k {
|
||||
let mut pos = pos;
|
||||
pos = pos.offset(Vector3::new(pos.0.x + m, pos.0.y + n, pos.0.z + o));
|
||||
pos = pos.down_height(l);
|
||||
|
||||
let condition_a = (m != 0 && m != j) || (n != 0 && n != i);
|
||||
let condition_b = (o != 0 && o != k) || (n != 0 && n != i);
|
||||
let condition_c = (m != 0 && m != j) || (o != 0 && o != k);
|
||||
let condition_d = m == 0 || m == j || n == 0 || n == i || o == 0 || o == k;
|
||||
let random_check = random.next_f32() < 0.1f32;
|
||||
|
||||
if !((condition_a && condition_b && condition_c && condition_d)
|
||||
&& !random_check
|
||||
&& CoralFeature::generate_coral_piece(
|
||||
chunk,
|
||||
block_registry,
|
||||
random,
|
||||
block,
|
||||
pos,
|
||||
))
|
||||
{}
|
||||
}
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
use crate::{generation::proto_chunk::GenerationCache, world::WorldPortalExt};
|
||||
use pumpkin_data::{BlockDirection, tag};
|
||||
use pumpkin_util::{
|
||||
math::position::BlockPos,
|
||||
random::{RandomGenerator, RandomImpl},
|
||||
};
|
||||
|
||||
use super::CoralFeature;
|
||||
|
||||
pub struct CoralTreeFeature;
|
||||
|
||||
impl CoralTreeFeature {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn generate<T: GenerationCache>(
|
||||
chunk: &mut T,
|
||||
block_registry: &dyn WorldPortalExt,
|
||||
_min_y: i8,
|
||||
_height: u16,
|
||||
_feature: pumpkin_data::placed_feature::PlacedFeature, // This placed feature
|
||||
random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> bool {
|
||||
// First lets get a random coral
|
||||
let block = CoralFeature::get_random_tag_entry(tag::Block::MINECRAFT_CORAL_BLOCKS, random);
|
||||
let mut pos = pos;
|
||||
let i = random.next_bounded_i32(3) + 1;
|
||||
for _ in 0..i {
|
||||
if !CoralFeature::generate_coral_piece(chunk, block_registry, random, block, pos) {
|
||||
return true;
|
||||
}
|
||||
pos = pos.up();
|
||||
}
|
||||
let i = random.next_bounded_i32(3) + 2;
|
||||
|
||||
// TODO: Shuffle
|
||||
let directions = BlockDirection::horizontal().into_iter().take(i as usize);
|
||||
for dir in directions {
|
||||
pos = pos.offset(dir.to_offset());
|
||||
let times = random.next_bounded_i32(5) + 2;
|
||||
let mut m = 0;
|
||||
for n in 0..times {
|
||||
if !CoralFeature::generate_coral_piece(chunk, block_registry, random, block, pos) {
|
||||
break;
|
||||
}
|
||||
pos = pos.up();
|
||||
m += 1;
|
||||
if n != 0 && (m < 2 || random.next_f32() >= 0.25) {
|
||||
continue;
|
||||
}
|
||||
pos = pos.offset(dir.to_offset());
|
||||
m = 0;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
use crate::{generation::proto_chunk::GenerationCache, world::WorldPortalExt};
|
||||
use pumpkin_data::{
|
||||
Block, BlockDirection, BlockId, BlockState,
|
||||
block_properties::{BlockProperties, EnumVariants, SeaPickleLikeProperties},
|
||||
tag,
|
||||
};
|
||||
use pumpkin_util::{
|
||||
math::position::BlockPos,
|
||||
random::{RandomGenerator, RandomImpl},
|
||||
};
|
||||
|
||||
pub mod coral_claw;
|
||||
pub mod coral_mushroom;
|
||||
pub mod coral_tree;
|
||||
|
||||
pub struct CoralFeature;
|
||||
|
||||
impl CoralFeature {
|
||||
pub fn generate_coral_piece<T: GenerationCache>(
|
||||
chunk: &mut T,
|
||||
block_registry: &dyn WorldPortalExt,
|
||||
random: &mut RandomGenerator,
|
||||
state: &BlockState,
|
||||
pos: BlockPos,
|
||||
) -> bool {
|
||||
let block = GenerationCache::get_block_state(chunk, &pos.0).to_block_id();
|
||||
let above_block = GenerationCache::get_block_state(chunk, &pos.up().0).to_block_id();
|
||||
|
||||
if block != BlockId::WATER && !block.has_tag(tag::Block::MINECRAFT_CORALS)
|
||||
|| above_block != BlockId::WATER
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if block_registry.can_place_at(Block::from_state_id(state.id), state, chunk, &pos) {
|
||||
chunk.set_block_state(&pos.0, state);
|
||||
}
|
||||
if random.next_f32() < 0.25 {
|
||||
let block_to_place_state =
|
||||
Self::get_random_tag_entry(tag::Block::MINECRAFT_CORALS, random);
|
||||
if block_registry.can_place_at(
|
||||
Block::from_state_id(block_to_place_state.id),
|
||||
block_to_place_state,
|
||||
chunk,
|
||||
&pos,
|
||||
) {
|
||||
chunk.set_block_state(&pos.0, block_to_place_state);
|
||||
}
|
||||
} else if random.next_f32() < 0.05 {
|
||||
let mut props = SeaPickleLikeProperties::default(&Block::SEA_PICKLE);
|
||||
props.pickles = (random.next_bounded_i32(4) as u8) + 1;
|
||||
let state_id = props.to_state_id(&Block::SEA_PICKLE);
|
||||
let block_state = BlockState::from_id(state_id);
|
||||
if block_registry.can_place_at(Block::from_state_id(state_id), block_state, chunk, &pos)
|
||||
{
|
||||
chunk.set_block_state(&pos.0, block_state);
|
||||
}
|
||||
}
|
||||
for dir in BlockDirection::horizontal() {
|
||||
let dir_pos = pos.offset(dir.to_offset());
|
||||
if random.next_f32() >= 0.2
|
||||
|| GenerationCache::get_block_state(chunk, &dir_pos.0).to_block_id() != Block::WATER
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let wall_coral =
|
||||
Self::get_random_tag_entry_block(tag::Block::MINECRAFT_WALL_CORALS, random);
|
||||
let original_props = &wall_coral
|
||||
.properties(wall_coral.default_state.id)
|
||||
.unwrap()
|
||||
.to_props();
|
||||
// Set the right Axis
|
||||
let props: Vec<(&str, &str)> = original_props
|
||||
.iter()
|
||||
.map(|(key, value)| {
|
||||
if *key == "facing" {
|
||||
(*key, dir.to_value())
|
||||
} else {
|
||||
(*key, *value)
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let block_state_id = wall_coral.from_properties(&props).to_state_id(wall_coral);
|
||||
let block_state = BlockState::from_id(block_state_id);
|
||||
if block_registry.can_place_at(
|
||||
Block::from_state_id(block_state_id),
|
||||
block_state,
|
||||
chunk,
|
||||
&dir_pos,
|
||||
) {
|
||||
chunk.set_block_state(
|
||||
&dir_pos.0,
|
||||
BlockState::from_id(wall_coral.from_properties(&props).to_state_id(wall_coral)),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
pub fn get_random_tag_entry(
|
||||
tag: tag::Tag,
|
||||
random: &mut RandomGenerator,
|
||||
) -> &'static BlockState {
|
||||
let block = Self::get_random_tag_entry_block(tag, random);
|
||||
block.default_state
|
||||
}
|
||||
|
||||
pub fn get_random_tag_entry_block(
|
||||
tag: tag::Tag,
|
||||
random: &mut RandomGenerator,
|
||||
) -> &'static Block {
|
||||
let values = tag.1;
|
||||
let value = values[random.next_bounded_i32(values.len() as i32) as usize];
|
||||
let id = BlockId::new(value).expect("Invalid block id in tag");
|
||||
id.to_block()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
use pumpkin_data::Block;
|
||||
use pumpkin_util::{math::position::BlockPos, random::RandomGenerator, random::RandomImpl};
|
||||
|
||||
use crate::generation::proto_chunk::GenerationCache;
|
||||
|
||||
pub struct DeltaFeatureFeature;
|
||||
|
||||
impl DeltaFeatureFeature {
|
||||
pub fn generate<T: GenerationCache>(
|
||||
chunk: &mut T,
|
||||
_min_y: i8,
|
||||
_height: u16,
|
||||
_feature: pumpkin_data::placed_feature::PlacedFeature,
|
||||
random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> bool {
|
||||
let size = random.next_bounded_i32(3) + 2;
|
||||
let mut generated = false;
|
||||
|
||||
for dx in -size..=size {
|
||||
for dy in -size..=size {
|
||||
for dz in -size..=size {
|
||||
if dx * dx + dy * dy + dz * dz <= size * size {
|
||||
let target = BlockPos::new(pos.0.x + dx, pos.0.y + dy, pos.0.z + dz);
|
||||
let block_id =
|
||||
GenerationCache::get_block_state(chunk, &target.0).to_block_id();
|
||||
if block_id == Block::NETHERRACK.id
|
||||
|| block_id == Block::LAVA.id
|
||||
|| block_id == Block::AIR.id
|
||||
{
|
||||
let replacement = if random.next_f32() < 0.6 {
|
||||
Block::BASALT
|
||||
} else {
|
||||
Block::BLACKSTONE
|
||||
};
|
||||
chunk.set_block_state(&target.0, replacement.default_state);
|
||||
generated = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
generated
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
use pumpkin_data::{Block, BlockDirection};
|
||||
use pumpkin_util::{
|
||||
math::{position::BlockPos, vector3::Vector3},
|
||||
random::RandomGenerator,
|
||||
};
|
||||
|
||||
use crate::generation::{noise::WATER_BLOCK, proto_chunk::GenerationCache};
|
||||
|
||||
pub struct DesertWellFeature;
|
||||
|
||||
impl DesertWellFeature {
|
||||
const CAN_GENERATE: Block = Block::SAND;
|
||||
const SAND: Block = Block::SAND;
|
||||
const SLAB: Block = Block::SANDSTONE_SLAB;
|
||||
const WALL: Block = Block::SANDSTONE;
|
||||
|
||||
#[expect(clippy::too_many_lines)]
|
||||
pub fn generate<T: GenerationCache>(
|
||||
chunk: &mut T,
|
||||
_min_y: i8,
|
||||
_height: u16,
|
||||
_feature: pumpkin_data::placed_feature::PlacedFeature, // This placed feature
|
||||
_random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> bool {
|
||||
const CAN_GENERATE: Block = Block::SAND;
|
||||
|
||||
let mut block_pos = pos.up();
|
||||
while chunk.is_air(&block_pos.0) && block_pos.0.y > chunk.bottom_y() as i32 + 2 {
|
||||
block_pos = block_pos.down();
|
||||
}
|
||||
let block = GenerationCache::get_block_state(chunk, &pos.0).to_block_id();
|
||||
if CAN_GENERATE.id != block {
|
||||
return false;
|
||||
}
|
||||
|
||||
for i in -2..=2 {
|
||||
for j2 in -2..=2 {
|
||||
if !chunk.is_air(&block_pos.0.add(&Vector3::new(i, -1, j2)))
|
||||
|| !chunk.is_air(&block_pos.0.add(&Vector3::new(i, -2, j2)))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
for i in -2..=0 {
|
||||
for j2 in -2..=2 {
|
||||
for k in -2..=2 {
|
||||
chunk.set_block_state(
|
||||
&block_pos.0.add(&Vector3::new(j2, i, k)),
|
||||
Self::WALL.default_state,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
chunk.set_block_state(&block_pos.0, WATER_BLOCK.default_state);
|
||||
|
||||
for direction in &BlockDirection::horizontal() {
|
||||
chunk.set_block_state(
|
||||
&block_pos.0.add(&direction.to_offset()),
|
||||
WATER_BLOCK.default_state,
|
||||
);
|
||||
}
|
||||
|
||||
let block_pos2 = &block_pos.0.add(&Vector3::new(0, -1, 0));
|
||||
chunk.set_block_state(block_pos2, Self::SAND.default_state);
|
||||
|
||||
for direction2 in &BlockDirection::horizontal() {
|
||||
chunk.set_block_state(
|
||||
&block_pos2.add(&direction2.to_offset()),
|
||||
Self::SAND.default_state,
|
||||
);
|
||||
}
|
||||
|
||||
for j in -2..=2 {
|
||||
for k in -2..=2 {
|
||||
if j != -2 && j != 2 && k != -2 && k != 2 {
|
||||
continue;
|
||||
}
|
||||
chunk.set_block_state(
|
||||
&block_pos.0.add(&Vector3::new(j, 1, k)),
|
||||
Self::WALL.default_state,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
chunk.set_block_state(
|
||||
&block_pos.0.add(&Vector3::new(2, 1, 0)),
|
||||
Self::SLAB.default_state,
|
||||
);
|
||||
chunk.set_block_state(
|
||||
&block_pos.0.add(&Vector3::new(-2, 1, 0)),
|
||||
Self::SLAB.default_state,
|
||||
);
|
||||
chunk.set_block_state(
|
||||
&block_pos.0.add(&Vector3::new(0, 1, 2)),
|
||||
Self::SLAB.default_state,
|
||||
);
|
||||
chunk.set_block_state(
|
||||
&block_pos.0.add(&Vector3::new(0, 1, -2)),
|
||||
Self::SLAB.default_state,
|
||||
);
|
||||
|
||||
for j in -1..=1 {
|
||||
for k in -1..=1 {
|
||||
if j == 0 && k == 0 {
|
||||
chunk.set_block_state(
|
||||
&block_pos.0.add(&Vector3::new(j, 4, k)),
|
||||
Self::WALL.default_state,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
chunk.set_block_state(
|
||||
&block_pos.0.add(&Vector3::new(j, 4, k)),
|
||||
Self::SLAB.default_state,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
for j in 1..=3 {
|
||||
chunk.set_block_state(
|
||||
&block_pos.0.add(&Vector3::new(-1, j, -1)),
|
||||
Self::WALL.default_state,
|
||||
);
|
||||
chunk.set_block_state(
|
||||
&block_pos.0.add(&Vector3::new(-1, j, 1)),
|
||||
Self::WALL.default_state,
|
||||
);
|
||||
chunk.set_block_state(
|
||||
&block_pos.0.add(&Vector3::new(1, j, -1)),
|
||||
Self::WALL.default_state,
|
||||
);
|
||||
chunk.set_block_state(
|
||||
&block_pos.0.add(&Vector3::new(1, j, 1)),
|
||||
Self::WALL.default_state,
|
||||
);
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
use pumpkin_util::math::{int_provider::IntProvider, position::BlockPos};
|
||||
use pumpkin_util::random::RandomGenerator;
|
||||
|
||||
use crate::generation::{
|
||||
block_predicate::BlockPredicate, block_state_provider::BlockStateProvider,
|
||||
proto_chunk::GenerationCache,
|
||||
};
|
||||
use crate::world::WorldPortalExt;
|
||||
|
||||
pub struct DiskFeature {
|
||||
pub state_provider: BlockStateProvider,
|
||||
pub target: BlockPredicate,
|
||||
pub radius: IntProvider,
|
||||
pub half_height: i32,
|
||||
}
|
||||
|
||||
impl DiskFeature {
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
pub fn generate<T: GenerationCache>(
|
||||
&self,
|
||||
chunk: &mut T,
|
||||
block_registry: &dyn WorldPortalExt,
|
||||
_min_y: i8,
|
||||
_height: u16,
|
||||
_feature: pumpkin_data::placed_feature::PlacedFeature,
|
||||
random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> bool {
|
||||
let mut placed_any = false;
|
||||
let origin_y = pos.0.y;
|
||||
let top = origin_y + self.half_height;
|
||||
let bottom = origin_y - self.half_height - 1;
|
||||
let r = self.radius.get(random);
|
||||
|
||||
for column_pos in BlockPos::iterate(pos.add(-r, 0, -r), pos.add(r, 0, r)) {
|
||||
let xd = column_pos.0.x - pos.0.x;
|
||||
let zd = column_pos.0.z - pos.0.z;
|
||||
if xd * xd + zd * zd <= r * r {
|
||||
placed_any |= self.place_column(
|
||||
chunk,
|
||||
block_registry,
|
||||
random,
|
||||
top,
|
||||
bottom,
|
||||
column_pos.0.x,
|
||||
column_pos.0.z,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
placed_any
|
||||
}
|
||||
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
fn place_column<T: GenerationCache>(
|
||||
&self,
|
||||
chunk: &mut T,
|
||||
block_registry: &dyn WorldPortalExt,
|
||||
random: &mut RandomGenerator,
|
||||
top: i32,
|
||||
bottom: i32,
|
||||
column_x: i32,
|
||||
column_z: i32,
|
||||
) -> bool {
|
||||
let mut placed_any = false;
|
||||
|
||||
let mut y = top;
|
||||
while y > bottom {
|
||||
let cur_pos = BlockPos::new(column_x, y, column_z);
|
||||
if self.target.test(block_registry, chunk, &cur_pos) {
|
||||
let state =
|
||||
self.state_provider
|
||||
.get_with_context(block_registry, chunk, random, cur_pos);
|
||||
chunk.set_block_state(&cur_pos.0, state);
|
||||
placed_any = true;
|
||||
}
|
||||
y -= 1;
|
||||
}
|
||||
|
||||
placed_any
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
use pumpkin_data::Block;
|
||||
use pumpkin_util::{math::position::BlockPos, random::RandomGenerator};
|
||||
|
||||
use crate::generation::proto_chunk::GenerationCache;
|
||||
|
||||
pub struct DripstoneClusterFeature;
|
||||
|
||||
impl DripstoneClusterFeature {
|
||||
#[allow(clippy::unused_self)]
|
||||
pub fn generate<T: GenerationCache>(
|
||||
&self,
|
||||
chunk: &mut T,
|
||||
_random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> bool {
|
||||
let mut generated = false;
|
||||
let radius = 3;
|
||||
|
||||
for dx in -radius..=radius {
|
||||
for dz in -radius..=radius {
|
||||
if dx * dx + dz * dz <= radius * radius {
|
||||
let mut current_pos = BlockPos::new(pos.0.x + dx, pos.0.y, pos.0.z + dz);
|
||||
while chunk.is_air(¤t_pos.0)
|
||||
&& current_pos.0.y > chunk.bottom_y() as i32 + 2
|
||||
{
|
||||
current_pos = current_pos.down();
|
||||
}
|
||||
if super::gen_dripstone(chunk, current_pos) {
|
||||
generated = true;
|
||||
let drip_pos = current_pos.up();
|
||||
if chunk.is_air(&drip_pos.0) {
|
||||
chunk.set_block_state(
|
||||
&drip_pos.0,
|
||||
Block::POINTED_DRIPSTONE.default_state,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
generated
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
use pumpkin_util::{math::position::BlockPos, random::RandomGenerator, random::RandomImpl};
|
||||
|
||||
use crate::generation::proto_chunk::GenerationCache;
|
||||
|
||||
pub struct LargeDripstoneFeature;
|
||||
|
||||
impl LargeDripstoneFeature {
|
||||
#[allow(clippy::unused_self)]
|
||||
pub fn generate<T: GenerationCache>(
|
||||
&self,
|
||||
chunk: &mut T,
|
||||
random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> bool {
|
||||
let height = random.next_bounded_i32(8) + 4;
|
||||
let mut generated = false;
|
||||
|
||||
let mut current_pos = pos;
|
||||
while chunk.is_air(¤t_pos.0) && current_pos.0.y > chunk.bottom_y() as i32 + 2 {
|
||||
current_pos = current_pos.down();
|
||||
}
|
||||
|
||||
for i in 0..height {
|
||||
let target = BlockPos::new(current_pos.0.x, current_pos.0.y + i, current_pos.0.z);
|
||||
if super::gen_dripstone(chunk, target) {
|
||||
generated = true;
|
||||
}
|
||||
}
|
||||
generated
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
use crate::generation::proto_chunk::GenerationCache;
|
||||
use pumpkin_data::Block;
|
||||
use pumpkin_data::BlockId;
|
||||
use pumpkin_data::tag;
|
||||
use pumpkin_util::math::position::BlockPos;
|
||||
|
||||
pub mod cluster;
|
||||
pub mod large;
|
||||
pub mod small;
|
||||
|
||||
pub(super) fn can_replace(id: BlockId) -> bool {
|
||||
id == BlockId::DRIPSTONE_BLOCK || id.has_tag(tag::Block::MINECRAFT_DRIPSTONE_REPLACEABLE_BLOCKS)
|
||||
}
|
||||
|
||||
pub(super) fn gen_dripstone<T: GenerationCache>(chunk: &mut T, pos: BlockPos) -> bool {
|
||||
let block = GenerationCache::get_block_state(chunk, &pos.0).to_block_id();
|
||||
if block.has_tag(tag::Block::MINECRAFT_DRIPSTONE_REPLACEABLE_BLOCKS) {
|
||||
chunk.set_block_state(&pos.0, Block::DRIPSTONE_BLOCK.default_state);
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
use crate::generation::proto_chunk::GenerationCache;
|
||||
use pumpkin_data::BlockDirection;
|
||||
use pumpkin_util::{
|
||||
math::position::BlockPos,
|
||||
random::{RandomGenerator, RandomImpl},
|
||||
};
|
||||
|
||||
pub struct SmallDripstoneFeature {
|
||||
pub taller_dripstone: f32,
|
||||
pub directional_spread: f32,
|
||||
pub spread_radius2: f32,
|
||||
pub spread_radius3: f32,
|
||||
}
|
||||
|
||||
impl SmallDripstoneFeature {
|
||||
pub fn generate<T: GenerationCache>(
|
||||
&self,
|
||||
chunk: &mut T,
|
||||
random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> bool {
|
||||
if let Some(dir) = Self::get_direction(chunk, pos, random) {
|
||||
let pos = pos.offset(dir.opposite().to_offset());
|
||||
self.gen_dripstone_blocks(chunk, pos, random);
|
||||
// TODO
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn get_direction<T: GenerationCache>(
|
||||
chunk: &T,
|
||||
pos: BlockPos,
|
||||
random: &mut RandomGenerator,
|
||||
) -> Option<BlockDirection> {
|
||||
let up =
|
||||
super::can_replace(GenerationCache::get_block_state(chunk, &pos.up().0).to_block_id());
|
||||
let down: bool = super::can_replace(
|
||||
GenerationCache::get_block_state(chunk, &pos.down().0).to_block_id(),
|
||||
);
|
||||
if up && down {
|
||||
return if random.next_bool() {
|
||||
Some(BlockDirection::Down)
|
||||
} else {
|
||||
Some(BlockDirection::Up)
|
||||
};
|
||||
}
|
||||
if up {
|
||||
return Some(BlockDirection::Down);
|
||||
}
|
||||
if down {
|
||||
return Some(BlockDirection::Up);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn gen_dripstone_blocks<T: GenerationCache>(
|
||||
&self,
|
||||
chunk: &mut T,
|
||||
pos: BlockPos,
|
||||
random: &mut RandomGenerator,
|
||||
) {
|
||||
super::gen_dripstone(chunk, pos);
|
||||
for dir in BlockDirection::horizontal() {
|
||||
if random.next_f32() > self.directional_spread {
|
||||
continue;
|
||||
}
|
||||
let pos = pos.offset(dir.to_offset());
|
||||
super::gen_dripstone(chunk, pos);
|
||||
if random.next_f32() > self.spread_radius2 {
|
||||
continue;
|
||||
}
|
||||
let pos = pos.offset(BlockDirection::random(random).to_offset());
|
||||
super::gen_dripstone(chunk, pos);
|
||||
if random.next_f32() > self.spread_radius3 {
|
||||
continue;
|
||||
}
|
||||
let pos = pos.offset(BlockDirection::random(random).to_offset());
|
||||
super::gen_dripstone(chunk, pos);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
use pumpkin_data::Block;
|
||||
use pumpkin_util::{math::position::BlockPos, random::RandomGenerator};
|
||||
|
||||
use crate::generation::proto_chunk::GenerationCache;
|
||||
|
||||
pub struct EndGatewayFeature;
|
||||
|
||||
impl EndGatewayFeature {
|
||||
pub fn generate<T: GenerationCache>(
|
||||
chunk: &mut T,
|
||||
_min_y: i8,
|
||||
_height: u16,
|
||||
_feature: pumpkin_data::placed_feature::PlacedFeature,
|
||||
_random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> bool {
|
||||
for dx in -1..=1 {
|
||||
for dy in -1..=1 {
|
||||
for dz in -1..=1 {
|
||||
let target = BlockPos::new(pos.0.x + dx, pos.0.y + dy, pos.0.z + dz);
|
||||
let is_center = dx == 0 && dy == 0 && dz == 0;
|
||||
let is_corner = dx.abs() + dy.abs() + dz.abs() == 3;
|
||||
|
||||
if is_center {
|
||||
chunk.set_block_state(&target.0, Block::END_GATEWAY.default_state);
|
||||
} else if !is_corner {
|
||||
chunk.set_block_state(&target.0, Block::BEDROCK.default_state);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
use pumpkin_data::Block;
|
||||
use pumpkin_util::{
|
||||
math::{position::BlockPos, vector3::Vector3},
|
||||
random::{RandomGenerator, RandomImpl},
|
||||
};
|
||||
|
||||
use crate::generation::proto_chunk::GenerationCache;
|
||||
|
||||
pub struct EndIslandFeature;
|
||||
|
||||
impl EndIslandFeature {
|
||||
pub fn generate<T: GenerationCache>(
|
||||
chunk: &mut T,
|
||||
_min_y: i8,
|
||||
_height: u16,
|
||||
_feature: pumpkin_data::placed_feature::PlacedFeature,
|
||||
random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> bool {
|
||||
let mut size = random.next_bounded_i32(3) as f32 + 4.0;
|
||||
|
||||
let mut dy = 0i32;
|
||||
while size > 0.5 {
|
||||
let start = size.copysign(-1.0).floor() as i32;
|
||||
let end = size.ceil() as i32;
|
||||
let radius_sq = (size + 1.0) * (size + 1.0);
|
||||
|
||||
for dx in start..=end {
|
||||
for dz in start..=end {
|
||||
if (dx * dx + dz * dz) as f32 <= radius_sq {
|
||||
let target = Vector3::new(pos.0.x + dx, pos.0.y + dy, pos.0.z + dz);
|
||||
chunk.set_block_state(&target, Block::END_STONE.default_state);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
size -= random.next_bounded_i32(2) as f32 + 0.5;
|
||||
dy -= 1;
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
use pumpkin_data::Block;
|
||||
use pumpkin_util::{
|
||||
math::{position::BlockPos, vector3::Vector3},
|
||||
random::RandomGenerator,
|
||||
};
|
||||
|
||||
use crate::generation::proto_chunk::GenerationCache;
|
||||
use crate::world::WorldPortalExt;
|
||||
|
||||
pub struct EndPlatformFeature;
|
||||
|
||||
impl EndPlatformFeature {
|
||||
pub fn generate<T: GenerationCache>(
|
||||
chunk: &mut T,
|
||||
_block_registry: &dyn WorldPortalExt,
|
||||
_min_y: i8,
|
||||
_height: u16,
|
||||
_feature: pumpkin_data::placed_feature::PlacedFeature, // This placed feature
|
||||
_random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> bool {
|
||||
for dx in -2i32..=2 {
|
||||
for dz in -2i32..=2 {
|
||||
for dy in -1i32..3 {
|
||||
let state = if dy == -1 {
|
||||
Block::OBSIDIAN.default_state
|
||||
} else {
|
||||
Block::AIR.default_state
|
||||
};
|
||||
let target = Vector3::new(pos.0.x + dx, pos.0.y + dy, pos.0.z + dz);
|
||||
chunk.set_block_state(&target, state);
|
||||
}
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
use pumpkin_data::{
|
||||
Block, BlockState,
|
||||
block_properties::{BlockProperties, OakFenceLikeProperties},
|
||||
};
|
||||
use pumpkin_util::{
|
||||
math::position::BlockPos,
|
||||
random::{RandomGenerator, RandomImpl},
|
||||
};
|
||||
|
||||
use crate::generation::proto_chunk::GenerationCache;
|
||||
use crate::{generation::section_coords, world::WorldPortalExt};
|
||||
|
||||
pub struct EndSpikeFeature {
|
||||
pub crystal_invulnerable: bool,
|
||||
pub spikes: Vec<Spike>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Spike {
|
||||
pub center_x: i32,
|
||||
pub center_z: i32,
|
||||
pub radius: i32,
|
||||
pub height: i32,
|
||||
pub guarded: bool,
|
||||
}
|
||||
|
||||
impl Spike {
|
||||
pub const fn is_in_chunk(&self, pos: &BlockPos) -> bool {
|
||||
section_coords::block_to_section(pos.0.x) == section_coords::block_to_section(self.center_x)
|
||||
&& section_coords::block_to_section(pos.0.z)
|
||||
== section_coords::block_to_section(self.center_z)
|
||||
}
|
||||
}
|
||||
|
||||
impl EndSpikeFeature {
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
pub fn generate<T: GenerationCache>(
|
||||
&self,
|
||||
chunk: &mut T,
|
||||
_block_registry: &dyn WorldPortalExt,
|
||||
_min_y: i8,
|
||||
_height: u16,
|
||||
_feature: pumpkin_data::placed_feature::PlacedFeature, // This placed feature
|
||||
random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> bool {
|
||||
let mut spikes = self.spikes.clone();
|
||||
if spikes.is_empty() {
|
||||
let mut sizes: Vec<i32> = (0..10).collect();
|
||||
for i in (1..10usize).rev() {
|
||||
let j = random.next_bounded_i32(i as i32 + 1) as usize;
|
||||
sizes.swap(i, j);
|
||||
}
|
||||
|
||||
for (i, &l) in sizes.iter().enumerate() {
|
||||
let angle = 2.0 * (-std::f64::consts::PI + 0.3141592653589793 * i as f64);
|
||||
let center_x = (42.0 * angle.cos()).floor() as i32;
|
||||
let center_z = (42.0 * angle.sin()).floor() as i32;
|
||||
|
||||
let radius = 2 + l / 3;
|
||||
let height = 76 + l * 3;
|
||||
let guarded = l == 1 || l == 2;
|
||||
|
||||
spikes.push(Spike {
|
||||
center_x,
|
||||
center_z,
|
||||
radius,
|
||||
height,
|
||||
guarded,
|
||||
});
|
||||
}
|
||||
}
|
||||
for spike in spikes {
|
||||
if !spike.is_in_chunk(&pos) {
|
||||
continue;
|
||||
}
|
||||
Self::gen_spike(&spike, chunk);
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
fn gen_spike<T: GenerationCache>(spike: &Spike, chunk: &mut T) {
|
||||
let radius = spike.radius;
|
||||
for pos in BlockPos::iterate(
|
||||
BlockPos::new(
|
||||
spike.center_x - radius,
|
||||
chunk.bottom_y() as i32,
|
||||
spike.center_z - radius,
|
||||
),
|
||||
BlockPos::new(
|
||||
spike.center_x + radius,
|
||||
spike.height + 10,
|
||||
spike.center_z + radius,
|
||||
),
|
||||
) {
|
||||
if pos
|
||||
.0
|
||||
.squared_distance_to(spike.center_x, pos.0.y, spike.center_z)
|
||||
<= (radius * radius + 1)
|
||||
&& pos.0.y < spike.height
|
||||
{
|
||||
chunk.set_block_state(&pos.0, Block::OBSIDIAN.default_state);
|
||||
continue;
|
||||
}
|
||||
if pos.0.y <= 65 {
|
||||
continue;
|
||||
}
|
||||
chunk.set_block_state(&pos.0, Block::AIR.default_state);
|
||||
}
|
||||
|
||||
// Bedrock cap serves as the crystal base, fire sits on top of it
|
||||
chunk.set_block_state(
|
||||
&pumpkin_util::math::vector3::Vector3::new(
|
||||
spike.center_x,
|
||||
spike.height,
|
||||
spike.center_z,
|
||||
),
|
||||
Block::BEDROCK.default_state,
|
||||
);
|
||||
chunk.set_block_state(
|
||||
&pumpkin_util::math::vector3::Vector3::new(
|
||||
spike.center_x,
|
||||
spike.height + 1,
|
||||
spike.center_z,
|
||||
),
|
||||
Block::FIRE.default_state,
|
||||
);
|
||||
|
||||
// Iron-bar cage for guarded spikes: 5x5 walls + open top frame at dy=3.
|
||||
if spike.guarded {
|
||||
for dy in 0i32..=3 {
|
||||
for dx in -2i32..=2 {
|
||||
for dz in -2i32..=2 {
|
||||
// Only place on perimeter walls and the top frame
|
||||
let x_wall_present = dx.abs() == 2;
|
||||
let z_wall_present = dz.abs() == 2;
|
||||
let on_top = dy == 3;
|
||||
if !x_wall_present && !z_wall_present && !on_top {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Connectivity rules
|
||||
let x_edge = x_wall_present || on_top;
|
||||
let z_edge = z_wall_present || on_top;
|
||||
|
||||
let mut props = OakFenceLikeProperties::default(&Block::IRON_BARS);
|
||||
props.north = x_edge && dz != 2;
|
||||
props.south = x_edge && dz != -2;
|
||||
props.west = z_edge && dx != 2;
|
||||
props.east = z_edge && dx != -2;
|
||||
|
||||
let bar_state = BlockState::from_id(props.to_state_id(&Block::IRON_BARS));
|
||||
chunk.set_block_state(
|
||||
&pumpkin_util::math::vector3::Vector3::new(
|
||||
spike.center_x + dx,
|
||||
spike.height + dy,
|
||||
spike.center_z + dz,
|
||||
),
|
||||
bar_state,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
use pumpkin_util::{math::position::BlockPos, random::RandomGenerator};
|
||||
|
||||
use crate::{ProtoChunk, generation::block_state_provider::BlockStateProvider};
|
||||
|
||||
pub struct FallenTreeFeature {
|
||||
pub trunk_provider: BlockStateProvider,
|
||||
}
|
||||
|
||||
impl FallenTreeFeature {
|
||||
pub const fn generate(
|
||||
_chunk: &mut ProtoChunk,
|
||||
_min_y: i8,
|
||||
_height: u16,
|
||||
_feature: pumpkin_data::placed_feature::PlacedFeature, // This placed feature
|
||||
_random: &mut RandomGenerator,
|
||||
_pos: BlockPos,
|
||||
) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
// fn gen_stump(&self, chunk: &mut ProtoChunk, random: &mut RandomGenerator, pos: BlockPos) {
|
||||
// // chunk.set_block_state(
|
||||
// // pos.0.x,
|
||||
// // pos.0.y,
|
||||
// // pos.0.z,
|
||||
// // self.trunk_provider.get(random, pos, chunk),
|
||||
// // );
|
||||
// }
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
use pumpkin_data::Block;
|
||||
use pumpkin_util::{math::position::BlockPos, random::RandomGenerator};
|
||||
|
||||
use crate::generation::proto_chunk::GenerationCache;
|
||||
|
||||
pub struct FillLayerFeature;
|
||||
|
||||
impl FillLayerFeature {
|
||||
#[allow(clippy::unused_self)]
|
||||
pub fn generate<T: GenerationCache>(
|
||||
&self,
|
||||
chunk: &mut T,
|
||||
_min_y: i8,
|
||||
_height: u16,
|
||||
_feature: pumpkin_data::placed_feature::PlacedFeature,
|
||||
_random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> bool {
|
||||
for dx in -1..=1 {
|
||||
for dz in -1..=1 {
|
||||
let target = BlockPos::new(pos.0.x + dx, pos.0.y, pos.0.z + dz);
|
||||
chunk.set_block_state(&target.0, Block::SNOW.default_state);
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
use crate::generation::proto_chunk::GenerationCache;
|
||||
use pumpkin_data::BlockState;
|
||||
use pumpkin_data::tag;
|
||||
use pumpkin_util::{
|
||||
math::position::BlockPos,
|
||||
random::{RandomGenerator, RandomImpl},
|
||||
};
|
||||
|
||||
pub struct ForestRockFeature {
|
||||
pub state: &'static BlockState,
|
||||
}
|
||||
|
||||
impl ForestRockFeature {
|
||||
pub fn generate<T: GenerationCache>(
|
||||
&self,
|
||||
chunk: &mut T,
|
||||
random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> bool {
|
||||
let mut pos = pos;
|
||||
loop {
|
||||
if pos.0.y <= chunk.bottom_y() as i32 + 3 {
|
||||
return false;
|
||||
}
|
||||
let below_state = GenerationCache::get_block_state(chunk, &pos.down().0);
|
||||
let below_id = below_state.to_block_id();
|
||||
if !chunk.is_air(&pos.down().0)
|
||||
&& (below_id.has_tag(tag::Block::MINECRAFT_DIRT)
|
||||
|| below_id.has_tag(tag::Block::MINECRAFT_BASE_STONE_OVERWORLD))
|
||||
{
|
||||
break;
|
||||
}
|
||||
pos = pos.down();
|
||||
}
|
||||
|
||||
let block_state = self.state;
|
||||
|
||||
for _ in 0..3 {
|
||||
let xr = random.next_bounded_i32(2);
|
||||
let yr = random.next_bounded_i32(2);
|
||||
let zr = random.next_bounded_i32(2);
|
||||
let threshold = (xr + yr + zr) as f32 * 0.333f32 + 0.5f32;
|
||||
let threshold_sq = threshold * threshold;
|
||||
|
||||
let start = BlockPos::new(pos.0.x - xr, pos.0.y - yr, pos.0.z - zr);
|
||||
let end = BlockPos::new(pos.0.x + xr, pos.0.y + yr, pos.0.z + zr);
|
||||
|
||||
for candidate in BlockPos::iterate(start, end) {
|
||||
let dx = (candidate.0.x - pos.0.x) as f32;
|
||||
let dy = (candidate.0.y - pos.0.y) as f32;
|
||||
let dz = (candidate.0.z - pos.0.z) as f32;
|
||||
if dx * dx + dy * dy + dz * dz <= threshold_sq {
|
||||
chunk.set_block_state(&candidate.0, block_state);
|
||||
}
|
||||
}
|
||||
|
||||
pos = pos.add(
|
||||
-1 + random.next_bounded_i32(2),
|
||||
-random.next_bounded_i32(2),
|
||||
-1 + random.next_bounded_i32(2),
|
||||
);
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
use pumpkin_data::{Block, BlockState, Mirror, Rotation, tag};
|
||||
use pumpkin_util::{
|
||||
HeightMap,
|
||||
math::{block_box::BlockBox, position::BlockPos, vector3::Vector3},
|
||||
random::{RandomGenerator, RandomImpl},
|
||||
};
|
||||
|
||||
use crate::generation::{
|
||||
proto_chunk::GenerationCache,
|
||||
structure::template::{BlockStateResolver, StructureTemplate, get_template},
|
||||
};
|
||||
|
||||
pub struct FossilFeature {
|
||||
pub fossil_structures: Vec<&'static str>,
|
||||
pub overlay_structures: Vec<&'static str>,
|
||||
pub fossil_processor: FossilProcessor,
|
||||
pub overlay_processor: FossilProcessor,
|
||||
pub max_empty_corners_allowed: u8,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub enum FossilProcessor {
|
||||
FossilRot,
|
||||
Coal,
|
||||
Diamonds,
|
||||
}
|
||||
|
||||
impl FossilProcessor {
|
||||
const fn integrity(self) -> f32 {
|
||||
match self {
|
||||
Self::FossilRot => 0.9,
|
||||
Self::Coal | Self::Diamonds => 0.1,
|
||||
}
|
||||
}
|
||||
|
||||
fn process(self, state: &'static BlockState) -> &'static BlockState {
|
||||
if matches!(self, Self::Diamonds) && Block::from_state_id(state.id) == &Block::COAL_ORE {
|
||||
Block::DEEPSLATE_DIAMOND_ORE.default_state
|
||||
} else {
|
||||
state
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl FossilFeature {
|
||||
pub fn generate<T: GenerationCache>(
|
||||
&self,
|
||||
chunk: &mut T,
|
||||
min_y: i8,
|
||||
height: u16,
|
||||
random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> bool {
|
||||
if self.fossil_structures.is_empty()
|
||||
|| self.fossil_structures.len() != self.overlay_structures.len()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
let rotation = Rotation::from_index(random.next_bounded_i32(4) as u8);
|
||||
let template_index = random.next_bounded_i32(self.fossil_structures.len() as i32) as usize;
|
||||
|
||||
let Some(fossil_name) = self.fossil_structures.get(template_index) else {
|
||||
return false;
|
||||
};
|
||||
let Some(overlay_name) = self.overlay_structures.get(template_index) else {
|
||||
return false;
|
||||
};
|
||||
let Some(fossil) = get_template(
|
||||
fossil_name
|
||||
.strip_prefix("minecraft:")
|
||||
.unwrap_or(fossil_name),
|
||||
) else {
|
||||
return false;
|
||||
};
|
||||
let Some(overlay) = get_template(
|
||||
overlay_name
|
||||
.strip_prefix("minecraft:")
|
||||
.unwrap_or(overlay_name),
|
||||
) else {
|
||||
return false;
|
||||
};
|
||||
|
||||
let rotated_size = rotation.transform_size(fossil.size);
|
||||
let origin_x = pos.0.x - rotated_size.x / 2;
|
||||
let origin_z = pos.0.z - rotated_size.z / 2;
|
||||
let mut ocean_floor = pos.0.y;
|
||||
|
||||
for x in origin_x..origin_x + rotated_size.x {
|
||||
for z in origin_z..origin_z + rotated_size.z {
|
||||
ocean_floor = ocean_floor.min(chunk.get_top_y(&HeightMap::OceanFloorWg, x, z));
|
||||
}
|
||||
}
|
||||
|
||||
let origin_y = (ocean_floor - 15 - random.next_bounded_i32(10)).max(i32::from(min_y) + 10);
|
||||
let origin = Vector3::new(origin_x, origin_y, origin_z);
|
||||
let fossil_box = BlockBox::new(
|
||||
origin.x,
|
||||
origin.y,
|
||||
origin.z,
|
||||
origin.x + rotated_size.x - 1,
|
||||
origin.y + rotated_size.y - 1,
|
||||
origin.z + rotated_size.z - 1,
|
||||
);
|
||||
|
||||
if count_empty_corners(chunk, &fossil_box) > usize::from(self.max_empty_corners_allowed) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let chunk_min_x = (pos.0.x >> 4) << 4;
|
||||
let chunk_min_z = (pos.0.z >> 4) << 4;
|
||||
let placement_box = BlockBox::new(
|
||||
chunk_min_x - 16,
|
||||
i32::from(min_y),
|
||||
chunk_min_z - 16,
|
||||
chunk_min_x + 31,
|
||||
i32::from(min_y) + i32::from(height) - 1,
|
||||
chunk_min_z + 31,
|
||||
);
|
||||
|
||||
place_fossil_template(
|
||||
chunk,
|
||||
&fossil,
|
||||
origin,
|
||||
rotation,
|
||||
self.fossil_processor,
|
||||
random,
|
||||
&placement_box,
|
||||
);
|
||||
place_fossil_template(
|
||||
chunk,
|
||||
&overlay,
|
||||
origin,
|
||||
rotation,
|
||||
self.overlay_processor,
|
||||
random,
|
||||
&placement_box,
|
||||
);
|
||||
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
fn count_empty_corners<T: GenerationCache>(chunk: &T, bounding_box: &BlockBox) -> usize {
|
||||
let mut empty_corners = 0;
|
||||
|
||||
for x in [bounding_box.min.x, bounding_box.max.x] {
|
||||
for y in [bounding_box.min.y, bounding_box.max.y] {
|
||||
for z in [bounding_box.min.z, bounding_box.max.z] {
|
||||
let state =
|
||||
GenerationCache::get_block_state(chunk, &Vector3::new(x, y, z)).to_state();
|
||||
let block = Block::from_state_id(state.id);
|
||||
if state.is_air() || block == &Block::LAVA || block == &Block::WATER {
|
||||
empty_corners += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
empty_corners
|
||||
}
|
||||
|
||||
fn place_fossil_template<T: GenerationCache>(
|
||||
chunk: &mut T,
|
||||
template: &StructureTemplate,
|
||||
origin: Vector3<i32>,
|
||||
rotation: Rotation,
|
||||
processor: FossilProcessor,
|
||||
random: &mut RandomGenerator,
|
||||
placement_box: &BlockBox,
|
||||
) {
|
||||
for block in &template.blocks {
|
||||
let local_pos = rotation.transform_pos(block.pos, template.size);
|
||||
let world_pos = origin + local_pos;
|
||||
|
||||
if !placement_box.contains_pos(&world_pos) || random.next_f32() > processor.integrity() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let current_state = GenerationCache::get_block_state(chunk, &world_pos);
|
||||
if tag::Block::MINECRAFT_FEATURES_CANNOT_REPLACE
|
||||
.1
|
||||
.contains(¤t_state.to_block_id().as_u16())
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
let palette_entry = &template.palette[block.state as usize];
|
||||
if palette_entry.name == "minecraft:structure_void" {
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Some(state) = BlockStateResolver::resolve(palette_entry, rotation, Mirror::default())
|
||||
{
|
||||
chunk.set_block_state(&world_pos, processor.process(state));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
use crate::generation::proto_chunk::GenerationCache;
|
||||
use pumpkin_data::tag::{self, Taggable};
|
||||
use pumpkin_data::{Block, BlockState};
|
||||
use pumpkin_util::math::position::BlockPos;
|
||||
use pumpkin_util::random::RandomGenerator;
|
||||
|
||||
const SEA_LEVEL: i32 = 63; // TODO: getSeaLevel() from the worldgen context instead of hardcoding
|
||||
|
||||
pub struct FreezeTopLayerFeature;
|
||||
|
||||
impl FreezeTopLayerFeature {
|
||||
pub fn generate<T: GenerationCache>(
|
||||
chunk: &mut T,
|
||||
_min_y: i8,
|
||||
_height: u16,
|
||||
_feature_name: pumpkin_data::placed_feature::PlacedFeature,
|
||||
_random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> bool {
|
||||
let origin_x = pos.0.x;
|
||||
let origin_z = pos.0.z;
|
||||
|
||||
for dx in 0..16i32 {
|
||||
for dz in 0..16i32 {
|
||||
let x = origin_x + dx;
|
||||
let z = origin_z + dz;
|
||||
|
||||
let y = chunk.top_motion_blocking_block_height_exclusive(x, z);
|
||||
let below_y = y - 1;
|
||||
|
||||
let top_vec = BlockPos::new(x, y, z).0;
|
||||
let below_vec = BlockPos::new(x, below_y, z).0;
|
||||
|
||||
let biome = chunk.get_biome_for_terrain_gen(x, y, z);
|
||||
|
||||
// Freeze check
|
||||
if biome.weather.base_temperature() <= 0.15
|
||||
&& GenerationCache::get_block_state(chunk, &below_vec).to_block_id()
|
||||
== Block::WATER
|
||||
{
|
||||
chunk.set_block_state(&below_vec, Block::ICE.default_state);
|
||||
}
|
||||
|
||||
// Snow check
|
||||
let top_temp = biome
|
||||
.weather
|
||||
.compute_temperature(x as f64, y, z as f64, SEA_LEVEL);
|
||||
|
||||
if top_temp < 0.15 {
|
||||
let top_raw = GenerationCache::get_block_state(chunk, &top_vec);
|
||||
// Re-read below (may have been replaced by ice in the freeze step above)
|
||||
let below = GenerationCache::get_block_state(chunk, &below_vec);
|
||||
|
||||
// topPos must be air; belowPos must not be air (something to stand on)
|
||||
if top_raw.to_state().is_air()
|
||||
&& !below.to_state().is_air()
|
||||
&& !Block::from_state_id(below.to_state().id)
|
||||
.has_tag(&tag::Block::MINECRAFT_CANNOT_SUPPORT_SNOW_LAYER)
|
||||
{
|
||||
chunk.set_block_state(&top_vec, Block::SNOW.default_state);
|
||||
|
||||
// Update the `snowy` block-state property on the block below if it has one
|
||||
let below_block = below.to_block();
|
||||
if let Some(props) = below_block.properties(below) {
|
||||
let prop_list = props.to_props();
|
||||
if prop_list.iter().any(|(k, _)| *k == "snowy") {
|
||||
let new_props: Vec<(&str, &str)> = prop_list
|
||||
.iter()
|
||||
.map(|(k, v)| (*k, if *k == "snowy" { "true" } else { *v }))
|
||||
.collect();
|
||||
let new_props_obj =
|
||||
below_block.from_properties(new_props.as_slice());
|
||||
let new_state_id = new_props_obj.to_state_id(below_block);
|
||||
chunk
|
||||
.set_block_state(&below_vec, BlockState::from_id(new_state_id));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,370 @@
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use pumpkin_data::{Block, BlockDirection, BlockId, BlockState, BlockStateId};
|
||||
use pumpkin_util::{
|
||||
math::{int_provider::IntProvider, position::BlockPos},
|
||||
random::RandomGenerator,
|
||||
};
|
||||
|
||||
use crate::generation::feature::features::spring_feature::BlockWrapper;
|
||||
use crate::{
|
||||
block::BlockStateCodec, generation::proto_chunk::GenerationCache, world::WorldPortalExt,
|
||||
};
|
||||
use pumpkin_util::random::RandomImpl;
|
||||
use std::cmp::Ordering;
|
||||
|
||||
/// Minimal wrapper around the perlin sampler used for geode generation, to avoid exposing the entire noise module to this file.
|
||||
struct NormalNoise(crate::generation::noise::perlin::DoublePerlinNoiseSampler);
|
||||
|
||||
impl NormalNoise {
|
||||
fn create(
|
||||
rand: &mut RandomGenerator,
|
||||
first_octave: i32,
|
||||
amplitudes: &[f64],
|
||||
amplitude: f64,
|
||||
) -> Self {
|
||||
Self(
|
||||
crate::generation::noise::perlin::DoublePerlinNoiseSampler::new(
|
||||
rand,
|
||||
first_octave,
|
||||
amplitudes,
|
||||
amplitude,
|
||||
true,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn get_value(&self, x: f64, y: f64, z: f64) -> f64 {
|
||||
self.0.sample(x, y, z)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct GeodeFeature {
|
||||
/* Block settings */
|
||||
pub filling_provider: crate::generation::block_state_provider::BlockStateProvider,
|
||||
pub inner_layer_provider: crate::generation::block_state_provider::BlockStateProvider,
|
||||
pub alternate_inner_layer_provider: crate::generation::block_state_provider::BlockStateProvider,
|
||||
pub middle_layer_provider: crate::generation::block_state_provider::BlockStateProvider,
|
||||
pub outer_layer_provider: crate::generation::block_state_provider::BlockStateProvider,
|
||||
pub inner_placements: Vec<BlockStateCodec>,
|
||||
pub cannot_replace: BlockWrapper,
|
||||
pub invalid_blocks: BlockWrapper,
|
||||
/* Layer settings */
|
||||
pub filling: f64,
|
||||
pub inner_layer: f64,
|
||||
pub middle_layer: f64,
|
||||
pub outer_layer: f64,
|
||||
/* Crack settings */
|
||||
pub generate_crack_chance: f64,
|
||||
pub base_crack_size: f64,
|
||||
pub crack_point_offset: i32,
|
||||
/* Other */
|
||||
pub use_potential_placements_chance: f64,
|
||||
pub use_alternate_layer0_chance: f64,
|
||||
pub placements_require_layer0_alternate: bool,
|
||||
pub outer_wall_distance: IntProvider,
|
||||
pub distribution_points: IntProvider,
|
||||
pub point_offset: IntProvider,
|
||||
pub min_gen_offset: i32,
|
||||
pub max_gen_offset: i32,
|
||||
pub noise_multiplier: f64,
|
||||
pub invalid_blocks_threshold: i32,
|
||||
}
|
||||
|
||||
impl GeodeFeature {
|
||||
fn safe_set_block<T: GenerationCache>(
|
||||
chunk: &mut T,
|
||||
pos: BlockPos,
|
||||
state: &'static BlockState,
|
||||
can_replace: &dyn Fn(&BlockState) -> bool,
|
||||
) {
|
||||
let existing = GenerationCache::get_block_state(chunk, &pos.0).to_state();
|
||||
if can_replace(existing) {
|
||||
chunk.set_block_state(&pos.0, state);
|
||||
}
|
||||
}
|
||||
|
||||
fn has_property(codec: &BlockStateCodec, property: &str) -> bool {
|
||||
let state = codec.get_state();
|
||||
// Obtain the block corresponding to this state id
|
||||
let block = Block::from_state_id(state.id);
|
||||
block
|
||||
.properties(state.id)
|
||||
.is_some_and(|props| props.to_props().iter().any(|(k, _)| *k == property))
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[allow(clippy::too_many_lines)]
|
||||
pub fn generate<T: GenerationCache>(
|
||||
&self,
|
||||
chunk: &mut T,
|
||||
block_registry: &dyn WorldPortalExt,
|
||||
_min_y: i8,
|
||||
_height: u16,
|
||||
_feature_name: pumpkin_data::placed_feature::PlacedFeature,
|
||||
random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> bool {
|
||||
let origin = pos;
|
||||
let num_points = self.distribution_points.get(random);
|
||||
let noise = NormalNoise::create(random, -4, &[1.0], 0.8333333333333333f64);
|
||||
|
||||
// Precompute sets of raw block ids for fast lookups
|
||||
let mut invalid_raw_ids: HashSet<BlockId> = HashSet::new();
|
||||
match &self.invalid_blocks {
|
||||
BlockWrapper::Single(s) => {
|
||||
if let Some(b) = Block::from_name(s.as_str()) {
|
||||
invalid_raw_ids.insert(b.id);
|
||||
}
|
||||
}
|
||||
BlockWrapper::Multi(v) => {
|
||||
for s in v {
|
||||
if let Some(b) = Block::from_name(s.as_str()) {
|
||||
invalid_raw_ids.insert(b.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut cannot_replace_raw_ids: HashSet<BlockId> = HashSet::new();
|
||||
match &self.cannot_replace {
|
||||
BlockWrapper::Single(s) => {
|
||||
if let Some(b) = Block::from_name(s.as_str()) {
|
||||
cannot_replace_raw_ids.insert(b.id);
|
||||
}
|
||||
}
|
||||
BlockWrapper::Multi(v) => {
|
||||
for s in v {
|
||||
if let Some(b) = Block::from_name(s.as_str()) {
|
||||
cannot_replace_raw_ids.insert(b.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut points: Vec<(BlockPos, i32)> = Vec::with_capacity(num_points as usize);
|
||||
let mut crack_points: Vec<BlockPos> = Vec::new();
|
||||
let crack_size_adjustment = num_points as f64 / (self.outer_wall_distance.get_max() as f64);
|
||||
let inner_air = 1.0 / self.filling.sqrt();
|
||||
let innermost_block_layer = 1.0 / (self.inner_layer + crack_size_adjustment).sqrt();
|
||||
let inner_crust = 1.0 / (self.middle_layer + crack_size_adjustment).sqrt();
|
||||
let outer_crust = 1.0 / (self.outer_layer + crack_size_adjustment).sqrt();
|
||||
let crack_size = 1.0
|
||||
/ (self.base_crack_size
|
||||
+ random.next_f64() / 2.0
|
||||
+ if num_points > 3 {
|
||||
crack_size_adjustment
|
||||
} else {
|
||||
0.0
|
||||
})
|
||||
.sqrt();
|
||||
let should_generate_crack = random.next_f32() < self.generate_crack_chance as f32;
|
||||
let mut num_invalid_points = 0;
|
||||
|
||||
// Sample distribution points; bail out early if too many fall into invalid blocks
|
||||
for _ in 0..num_points {
|
||||
let x = self.outer_wall_distance.get(random);
|
||||
let y = self.outer_wall_distance.get(random);
|
||||
let z = self.outer_wall_distance.get(random);
|
||||
let p = origin.add(x, y, z);
|
||||
let raw = GenerationCache::get_block_state(chunk, &p.0);
|
||||
let state = raw.to_state();
|
||||
|
||||
// Check against precomputed invalid raw ids
|
||||
let raw_id = raw.to_block_id();
|
||||
if state.is_air() || invalid_raw_ids.contains(&raw_id) {
|
||||
num_invalid_points += 1;
|
||||
if num_invalid_points > self.invalid_blocks_threshold {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
let offset = self.point_offset.get(random);
|
||||
points.push((p, offset));
|
||||
}
|
||||
|
||||
if should_generate_crack {
|
||||
let offset_index = random.next_bounded_i32(4);
|
||||
let crack_offset = num_points * 2 + 1;
|
||||
match offset_index {
|
||||
0 => {
|
||||
crack_points.push(origin.add(crack_offset, 7, 0));
|
||||
crack_points.push(origin.add(crack_offset, 5, 0));
|
||||
crack_points.push(origin.add(crack_offset, 1, 0));
|
||||
}
|
||||
1 => {
|
||||
crack_points.push(origin.add(0, 7, crack_offset));
|
||||
crack_points.push(origin.add(0, 5, crack_offset));
|
||||
crack_points.push(origin.add(0, 1, crack_offset));
|
||||
}
|
||||
2 => {
|
||||
crack_points.push(origin.add(crack_offset, 7, crack_offset));
|
||||
crack_points.push(origin.add(crack_offset, 5, crack_offset));
|
||||
crack_points.push(origin.add(crack_offset, 1, crack_offset));
|
||||
}
|
||||
_ => {
|
||||
crack_points.push(origin.add(0, 7, 0));
|
||||
crack_points.push(origin.add(0, 5, 0));
|
||||
crack_points.push(origin.add(0, 1, 0));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut potential_crystal_placements: Vec<BlockPos> = Vec::new();
|
||||
|
||||
// Determine which blocks can be replaced
|
||||
let can_replace_pred = |state: &BlockState| {
|
||||
let block_id = state.id.to_block_id();
|
||||
state.is_air() || !cannot_replace_raw_ids.contains(&block_id)
|
||||
};
|
||||
|
||||
let min = origin.add(
|
||||
self.min_gen_offset,
|
||||
self.min_gen_offset,
|
||||
self.min_gen_offset,
|
||||
);
|
||||
let max = origin.add(
|
||||
self.max_gen_offset,
|
||||
self.max_gen_offset,
|
||||
self.max_gen_offset,
|
||||
);
|
||||
|
||||
for point_inside in BlockPos::iterate(min, max) {
|
||||
let noise_offset = noise.get_value(
|
||||
point_inside.0.x as f64,
|
||||
point_inside.0.y as f64,
|
||||
point_inside.0.z as f64,
|
||||
) * self.noise_multiplier;
|
||||
let mut dist_sum_shell = 0.0;
|
||||
let mut dist_sum_crack = 0.0;
|
||||
for (pt, off) in &points {
|
||||
let dx = (point_inside.0.x - pt.0.x) as f64;
|
||||
let dy = (point_inside.0.y - pt.0.y) as f64;
|
||||
let dz = (point_inside.0.z - pt.0.z) as f64;
|
||||
let dist_sq = dx * dx + dy * dy + dz * dz;
|
||||
dist_sum_shell += 1.0 / (dist_sq + (*off as f64)).sqrt() + noise_offset;
|
||||
}
|
||||
for pt in &crack_points {
|
||||
let dx = (point_inside.0.x - pt.0.x) as f64;
|
||||
let dy = (point_inside.0.y - pt.0.y) as f64;
|
||||
let dz = (point_inside.0.z - pt.0.z) as f64;
|
||||
let dist_sq = dx * dx + dy * dy + dz * dz;
|
||||
dist_sum_crack +=
|
||||
1.0 / (dist_sq + self.crack_point_offset as f64).sqrt() + noise_offset;
|
||||
}
|
||||
if matches!(
|
||||
dist_sum_shell.partial_cmp(&outer_crust),
|
||||
Some(Ordering::Greater | Ordering::Equal)
|
||||
) {
|
||||
if should_generate_crack
|
||||
&& dist_sum_crack >= crack_size
|
||||
&& dist_sum_shell < inner_air
|
||||
{
|
||||
// Carve crack
|
||||
Self::safe_set_block(
|
||||
chunk,
|
||||
point_inside,
|
||||
BlockStateId::AIR.to_state(),
|
||||
&can_replace_pred,
|
||||
);
|
||||
} else if dist_sum_shell >= inner_air {
|
||||
let state =
|
||||
self.filling_provider
|
||||
.get(random, point_inside, chunk, block_registry);
|
||||
Self::safe_set_block(chunk, point_inside, state, &can_replace_pred);
|
||||
} else if dist_sum_shell >= innermost_block_layer {
|
||||
let use_alternate = random.next_f32() < self.use_alternate_layer0_chance as f32;
|
||||
if use_alternate {
|
||||
let state = self.alternate_inner_layer_provider.get(
|
||||
random,
|
||||
point_inside,
|
||||
chunk,
|
||||
block_registry,
|
||||
);
|
||||
Self::safe_set_block(chunk, point_inside, state, &can_replace_pred);
|
||||
} else {
|
||||
let state = self.inner_layer_provider.get(
|
||||
random,
|
||||
point_inside,
|
||||
chunk,
|
||||
block_registry,
|
||||
);
|
||||
Self::safe_set_block(chunk, point_inside, state, &can_replace_pred);
|
||||
}
|
||||
if (!self.placements_require_layer0_alternate || use_alternate)
|
||||
&& random.next_f32() < self.use_potential_placements_chance as f32
|
||||
{
|
||||
potential_crystal_placements.push(point_inside);
|
||||
}
|
||||
} else if dist_sum_shell >= inner_crust {
|
||||
let state =
|
||||
self.middle_layer_provider
|
||||
.get(random, point_inside, chunk, block_registry);
|
||||
Self::safe_set_block(chunk, point_inside, state, &can_replace_pred);
|
||||
} else if dist_sum_shell >= outer_crust {
|
||||
let state =
|
||||
self.outer_layer_provider
|
||||
.get(random, point_inside, chunk, block_registry);
|
||||
Self::safe_set_block(chunk, point_inside, state, &can_replace_pred);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Iterate through potential placements (these are the budding blocks)
|
||||
for crystal_pos in potential_crystal_placements {
|
||||
// Pick a random base placement codec for this budding block
|
||||
if let Some(base_codec) = self
|
||||
.inner_placements
|
||||
.get(random.next_bounded_i32(self.inner_placements.len() as i32) as usize)
|
||||
{
|
||||
for dir in &BlockDirection::all() {
|
||||
let offset = dir.to_offset();
|
||||
let place_pos = crystal_pos.add(offset.x, offset.y, offset.z);
|
||||
let place_raw = GenerationCache::get_block_state(chunk, &place_pos.0);
|
||||
let place_state = place_raw.to_state();
|
||||
|
||||
// Only place if the target block is replaceable (air/water)
|
||||
let is_air = place_state.is_air();
|
||||
let is_water = place_raw.to_block().name == "water";
|
||||
|
||||
if is_air || is_water {
|
||||
let mut final_codec = base_codec.clone();
|
||||
|
||||
// Set facing based on direction
|
||||
let dir_name = match dir {
|
||||
pumpkin_data::BlockDirection::Up => "up",
|
||||
pumpkin_data::BlockDirection::Down => "down",
|
||||
pumpkin_data::BlockDirection::North => "north",
|
||||
pumpkin_data::BlockDirection::South => "south",
|
||||
pumpkin_data::BlockDirection::East => "east",
|
||||
pumpkin_data::BlockDirection::West => "west",
|
||||
};
|
||||
|
||||
if Self::has_property(&final_codec, "facing") {
|
||||
final_codec
|
||||
.properties
|
||||
.get_or_insert_with(HashMap::new)
|
||||
.insert("facing".to_string(), dir_name.to_string());
|
||||
}
|
||||
|
||||
// Handle waterlogging dynamically based on the block we are replacing
|
||||
if Self::has_property(&final_codec, "waterlogged") {
|
||||
final_codec
|
||||
.properties
|
||||
.get_or_insert_with(HashMap::new)
|
||||
.insert("waterlogged".to_string(), is_water.to_string());
|
||||
}
|
||||
|
||||
let final_state = final_codec.get_state();
|
||||
Self::safe_set_block(chunk, place_pos, final_state, &can_replace_pred);
|
||||
|
||||
// Only place one crystal per budding block per geode gen
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
use pumpkin_data::{Block, BlockDirection};
|
||||
use pumpkin_util::{
|
||||
math::position::BlockPos,
|
||||
random::{RandomGenerator, RandomImpl},
|
||||
};
|
||||
|
||||
use crate::generation::proto_chunk::GenerationCache;
|
||||
|
||||
pub struct GlowstoneBlobFeature;
|
||||
|
||||
impl GlowstoneBlobFeature {
|
||||
pub fn generate<T: GenerationCache>(
|
||||
chunk: &mut T,
|
||||
_min_y: i8,
|
||||
_height: u16,
|
||||
_feature: pumpkin_data::placed_feature::PlacedFeature,
|
||||
random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> bool {
|
||||
if !chunk.is_air(&pos.0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let above_id = GenerationCache::get_block_state(chunk, &pos.up().0).to_block_id();
|
||||
if above_id != Block::NETHERRACK.id
|
||||
&& above_id != Block::BASALT.id
|
||||
&& above_id != Block::BLACKSTONE.id
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
chunk.set_block_state(&pos.0, Block::GLOWSTONE.default_state);
|
||||
|
||||
for _ in 0..1500 {
|
||||
let place_pos = pos.add(
|
||||
random.next_bounded_i32(8) - random.next_bounded_i32(8),
|
||||
-random.next_bounded_i32(12),
|
||||
random.next_bounded_i32(8) - random.next_bounded_i32(8),
|
||||
);
|
||||
|
||||
if chunk.is_air(&place_pos.0) {
|
||||
let mut neighbours = 0u8;
|
||||
|
||||
for dir in BlockDirection::all() {
|
||||
let neighbor = place_pos.0.add(&dir.to_offset());
|
||||
if GenerationCache::get_block_state(chunk, &neighbor).to_block_id()
|
||||
== Block::GLOWSTONE.id
|
||||
{
|
||||
neighbours += 1;
|
||||
}
|
||||
if neighbours > 1 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if neighbours == 1 {
|
||||
chunk.set_block_state(&place_pos.0, Block::GLOWSTONE.default_state);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
use pumpkin_data::Block;
|
||||
use pumpkin_util::{math::position::BlockPos, random::RandomGenerator, random::RandomImpl};
|
||||
|
||||
use crate::generation::proto_chunk::GenerationCache;
|
||||
|
||||
pub struct HugeBrownMushroomFeature;
|
||||
|
||||
impl HugeBrownMushroomFeature {
|
||||
#[allow(clippy::unused_self)]
|
||||
pub fn generate<T: GenerationCache>(
|
||||
&self,
|
||||
chunk: &mut T,
|
||||
_min_y: i8,
|
||||
_height: u16,
|
||||
_feature: pumpkin_data::placed_feature::PlacedFeature,
|
||||
random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> bool {
|
||||
let height = random.next_bounded_i32(3) + 4;
|
||||
|
||||
for i in 0..height {
|
||||
let stem_pos = BlockPos::new(pos.0.x, pos.0.y + i, pos.0.z);
|
||||
chunk.set_block_state(&stem_pos.0, Block::MUSHROOM_STEM.default_state);
|
||||
}
|
||||
|
||||
let cap_y = pos.0.y + height;
|
||||
for dx in -2i32..=2 {
|
||||
for dz in -2i32..=2 {
|
||||
let is_corner = dx.abs() == 2 && dz.abs() == 2;
|
||||
if !is_corner {
|
||||
let cap_pos = BlockPos::new(pos.0.x + dx, cap_y, pos.0.z + dz);
|
||||
chunk.set_block_state(&cap_pos.0, Block::BROWN_MUSHROOM_BLOCK.default_state);
|
||||
}
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
use pumpkin_data::Block;
|
||||
use pumpkin_util::{math::position::BlockPos, random::RandomGenerator, random::RandomImpl};
|
||||
|
||||
use crate::generation::proto_chunk::GenerationCache;
|
||||
|
||||
pub struct HugeFungusFeature;
|
||||
|
||||
impl HugeFungusFeature {
|
||||
#[allow(clippy::unused_self)]
|
||||
pub fn generate<T: GenerationCache>(
|
||||
&self,
|
||||
chunk: &mut T,
|
||||
_min_y: i8,
|
||||
_height: u16,
|
||||
_feature: pumpkin_data::placed_feature::PlacedFeature,
|
||||
random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> bool {
|
||||
let height = random.next_bounded_i32(4) + 6;
|
||||
let is_warped = random.next_bool();
|
||||
|
||||
let stem_state = if is_warped {
|
||||
Block::WARPED_STEM.default_state
|
||||
} else {
|
||||
Block::CRIMSON_STEM.default_state
|
||||
};
|
||||
let wart_state = if is_warped {
|
||||
Block::WARPED_WART_BLOCK.default_state
|
||||
} else {
|
||||
Block::NETHER_WART_BLOCK.default_state
|
||||
};
|
||||
|
||||
for i in 0..height {
|
||||
let stem_pos = BlockPos::new(pos.0.x, pos.0.y + i, pos.0.z);
|
||||
chunk.set_block_state(&stem_pos.0, stem_state);
|
||||
}
|
||||
|
||||
let cap_y = pos.0.y + height - 2;
|
||||
for dy in 0..=3 {
|
||||
let radius = if dy == 0 || dy == 3 { 1 } else { 2 };
|
||||
for dx in -radius..=radius {
|
||||
for dz in -radius..=radius {
|
||||
let cap_pos = BlockPos::new(pos.0.x + dx, cap_y + dy, pos.0.z + dz);
|
||||
let block_state = if (dx == 0 || dz == 0) && dy == 1 && random.next_f32() < 0.3
|
||||
{
|
||||
Block::SHROOMLIGHT.default_state
|
||||
} else {
|
||||
wart_state
|
||||
};
|
||||
chunk.set_block_state(&cap_pos.0, block_state);
|
||||
}
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
use pumpkin_data::Block;
|
||||
use pumpkin_util::{math::position::BlockPos, random::RandomGenerator, random::RandomImpl};
|
||||
|
||||
use crate::generation::proto_chunk::GenerationCache;
|
||||
|
||||
pub struct HugeRedMushroomFeature;
|
||||
|
||||
impl HugeRedMushroomFeature {
|
||||
#[allow(clippy::unused_self)]
|
||||
pub fn generate<T: GenerationCache>(
|
||||
&self,
|
||||
chunk: &mut T,
|
||||
_min_y: i8,
|
||||
_height: u16,
|
||||
_feature: pumpkin_data::placed_feature::PlacedFeature,
|
||||
random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> bool {
|
||||
let height = random.next_bounded_i32(3) + 5;
|
||||
|
||||
for i in 0..height {
|
||||
let stem_pos = BlockPos::new(pos.0.x, pos.0.y + i, pos.0.z);
|
||||
chunk.set_block_state(&stem_pos.0, Block::MUSHROOM_STEM.default_state);
|
||||
}
|
||||
|
||||
let cap_y = pos.0.y + height;
|
||||
for dy in 0..=2 {
|
||||
let radius = if dy == 0 { 2 } else { 1 };
|
||||
for dx in -radius..=radius {
|
||||
for dz in -radius..=radius {
|
||||
let cap_pos = BlockPos::new(pos.0.x + dx, cap_y + dy, pos.0.z + dz);
|
||||
chunk.set_block_state(&cap_pos.0, Block::RED_MUSHROOM_BLOCK.default_state);
|
||||
}
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
use pumpkin_data::{Block, BlockId, block_properties::is_air, tag};
|
||||
use pumpkin_util::{
|
||||
math::{position::BlockPos, vector3::Vector3},
|
||||
random::{RandomGenerator, RandomImpl},
|
||||
};
|
||||
|
||||
use crate::generation::proto_chunk::GenerationCache;
|
||||
|
||||
pub struct IceSpikeFeature;
|
||||
|
||||
impl IceSpikeFeature {
|
||||
pub fn generate<T: GenerationCache>(
|
||||
chunk: &mut T,
|
||||
_min_y: i8,
|
||||
_height: u16,
|
||||
_feature: pumpkin_data::placed_feature::PlacedFeature,
|
||||
random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> bool {
|
||||
let mut origin = pos.0;
|
||||
|
||||
// Walk down while block is air, staying above minY + 2
|
||||
while chunk.is_air(&origin) && origin.y > chunk.bottom_y() as i32 + 2 {
|
||||
origin.y -= 1;
|
||||
}
|
||||
|
||||
// Only place on snow blocks
|
||||
let block_id = GenerationCache::get_block_state(chunk, &origin).to_block_id();
|
||||
if block_id != Block::SNOW_BLOCK.id {
|
||||
return false;
|
||||
}
|
||||
|
||||
origin.y += random.next_bounded_i32(4);
|
||||
let height = random.next_bounded_i32(4) + 7;
|
||||
let width = height / 4 + random.next_bounded_i32(2);
|
||||
|
||||
// Occasionally create extra-tall spires
|
||||
if width > 1 && random.next_bounded_i32(60) == 0 {
|
||||
origin.y += 10 + random.next_bounded_i32(30);
|
||||
}
|
||||
|
||||
for y_off in 0..height {
|
||||
let scale = (1.0f32 - y_off as f32 / height as f32) * width as f32;
|
||||
let new_width = scale.ceil() as i32;
|
||||
|
||||
for xo in -new_width..=new_width {
|
||||
let dx = xo.abs() as f32 - 0.25f32;
|
||||
|
||||
for zo in -new_width..=new_width {
|
||||
let dz = zo.abs() as f32 - 0.25f32;
|
||||
|
||||
let in_sphere = (xo == 0 && zo == 0) || (dx * dx + dz * dz <= scale * scale);
|
||||
let edge_ok = (xo != -new_width
|
||||
&& xo != new_width
|
||||
&& zo != -new_width
|
||||
&& zo != new_width)
|
||||
|| (random.next_f32() <= 0.75f32);
|
||||
|
||||
if in_sphere && edge_ok {
|
||||
// Place packed ice upward
|
||||
let place_pos = origin.add(&Vector3::new(xo, y_off, zo));
|
||||
let state_id = GenerationCache::get_block_state(chunk, &place_pos);
|
||||
let bid = state_id.to_block_id();
|
||||
if is_air(state_id)
|
||||
|| bid.has_tag(tag::Block::MINECRAFT_DIRT)
|
||||
|| bid == BlockId::SNOW_BLOCK
|
||||
|| bid == BlockId::ICE
|
||||
{
|
||||
chunk.set_block_state(&place_pos, Block::PACKED_ICE.default_state);
|
||||
}
|
||||
|
||||
// Mirror downward
|
||||
if y_off != 0 && new_width > 1 {
|
||||
let neg_pos = origin.add(&Vector3::new(xo, -y_off, zo));
|
||||
let state_id2 = GenerationCache::get_block_state(chunk, &neg_pos);
|
||||
let bid2 = state_id2.to_block_id();
|
||||
if is_air(state_id2)
|
||||
|| bid2.has_tag(tag::Block::MINECRAFT_DIRT)
|
||||
|| bid2 == BlockId::SNOW_BLOCK
|
||||
|| bid2 == BlockId::ICE
|
||||
{
|
||||
chunk.set_block_state(&neg_pos, Block::PACKED_ICE.default_state);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Build packed-ice roots downward from the spike base
|
||||
let pillar_width = (width - 1).clamp(0, 1);
|
||||
|
||||
for xo in -pillar_width..=pillar_width {
|
||||
for zo in -pillar_width..=pillar_width {
|
||||
let mut ice_block = origin.add(&Vector3::new(xo, -1, zo));
|
||||
// Corner positions get a short random run; others run 50 blocks
|
||||
let mut run_length: i32 = if xo.abs() == 1 && zo.abs() == 1 {
|
||||
random.next_bounded_i32(5)
|
||||
} else {
|
||||
50
|
||||
};
|
||||
|
||||
while ice_block.y > 50 {
|
||||
let state_id = GenerationCache::get_block_state(chunk, &ice_block);
|
||||
let bid = state_id.to_block_id();
|
||||
if !is_air(state_id)
|
||||
&& !bid.has_tag(tag::Block::MINECRAFT_DIRT)
|
||||
&& bid != BlockId::SNOW_BLOCK
|
||||
&& bid != BlockId::ICE
|
||||
&& bid != BlockId::PACKED_ICE
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
chunk.set_block_state(&ice_block, Block::PACKED_ICE.default_state);
|
||||
ice_block.y -= 1;
|
||||
run_length -= 1;
|
||||
if run_length <= 0 {
|
||||
ice_block.y -= random.next_bounded_i32(5) + 1;
|
||||
run_length = random.next_bounded_i32(5);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,495 @@
|
||||
use std::f64::consts;
|
||||
|
||||
use pumpkin_data::{Block, BlockId, BlockState, block_properties::is_air};
|
||||
use pumpkin_util::{
|
||||
math::{position::BlockPos, vector3::Vector3},
|
||||
random::{RandomGenerator, RandomImpl},
|
||||
};
|
||||
|
||||
use crate::{block::BlockStateCodec, generation::proto_chunk::GenerationCache};
|
||||
|
||||
const SEA_LEVEL: i32 = 63; // TODO: use getSeaLevel() instead of hardcoding
|
||||
|
||||
pub struct IcebergFeature {
|
||||
pub main_block: BlockStateCodec,
|
||||
}
|
||||
|
||||
impl IcebergFeature {
|
||||
#[expect(clippy::too_many_lines)]
|
||||
pub fn generate<T: GenerationCache>(
|
||||
&self,
|
||||
chunk: &mut T,
|
||||
_min_y: i8,
|
||||
_height: u16,
|
||||
_feature: pumpkin_data::placed_feature::PlacedFeature,
|
||||
random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> bool {
|
||||
let origin = Vector3::new(pos.0.x, SEA_LEVEL, pos.0.z);
|
||||
let main_block = self.main_block.get_state();
|
||||
|
||||
let snow_on_top = random.next_f64() > 0.7;
|
||||
let shape_angle = random.next_f64() * 2.0 * consts::PI;
|
||||
let shape_ellipse_a = 11 - random.next_bounded_i32(5);
|
||||
let shape_ellipse_c = 3 + random.next_bounded_i32(3);
|
||||
let is_ellipse = random.next_f64() > 0.7;
|
||||
|
||||
let mut over_water_height = if is_ellipse {
|
||||
random.next_bounded_i32(6) + 6
|
||||
} else {
|
||||
random.next_bounded_i32(15) + 3
|
||||
};
|
||||
if !is_ellipse && random.next_f64() > 0.9 {
|
||||
over_water_height += random.next_bounded_i32(19) + 7;
|
||||
}
|
||||
|
||||
let under_water_height = (over_water_height + random.next_bounded_i32(11)).min(18);
|
||||
let width =
|
||||
(over_water_height + random.next_bounded_i32(7) - random.next_bounded_i32(5)).min(11);
|
||||
let a = if is_ellipse { shape_ellipse_a } else { 11 };
|
||||
|
||||
// Above-water pass
|
||||
for xo in -a..a {
|
||||
for zo in -a..a {
|
||||
for y_off in 0..over_water_height {
|
||||
let radius = if is_ellipse {
|
||||
Self::height_dependent_radius_ellipse(y_off, over_water_height, width)
|
||||
} else {
|
||||
Self::height_dependent_radius_round(random, y_off, over_water_height, width)
|
||||
};
|
||||
if is_ellipse || xo < radius {
|
||||
Self::generate_iceberg_block(
|
||||
chunk,
|
||||
random,
|
||||
&origin,
|
||||
over_water_height,
|
||||
xo,
|
||||
y_off,
|
||||
zo,
|
||||
radius,
|
||||
a,
|
||||
is_ellipse,
|
||||
shape_ellipse_c,
|
||||
shape_angle,
|
||||
snow_on_top,
|
||||
main_block,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Self::smooth(
|
||||
chunk,
|
||||
&origin,
|
||||
width,
|
||||
over_water_height,
|
||||
is_ellipse,
|
||||
shape_ellipse_a,
|
||||
);
|
||||
|
||||
// Below-water pass
|
||||
for xo in -a..a {
|
||||
for zo in -a..a {
|
||||
for y_neg in 1..under_water_height {
|
||||
let y_off = -y_neg;
|
||||
let new_a = if is_ellipse {
|
||||
let y_off_sq = (y_off as f64).powi(2) as f32;
|
||||
let denom = under_water_height as f32 * 8.0f32;
|
||||
(a as f32 * (1.0f32 - y_off_sq / denom)).ceil() as i32
|
||||
} else {
|
||||
a
|
||||
};
|
||||
let radius = Self::height_dependent_radius_steep(
|
||||
random,
|
||||
-y_off,
|
||||
under_water_height,
|
||||
width,
|
||||
);
|
||||
if xo < radius {
|
||||
Self::generate_iceberg_block(
|
||||
chunk,
|
||||
random,
|
||||
&origin,
|
||||
under_water_height,
|
||||
xo,
|
||||
y_off,
|
||||
zo,
|
||||
radius,
|
||||
new_a,
|
||||
is_ellipse,
|
||||
shape_ellipse_c,
|
||||
shape_angle,
|
||||
snow_on_top,
|
||||
main_block,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let do_cut_out = if is_ellipse {
|
||||
random.next_f64() > 0.1
|
||||
} else {
|
||||
random.next_f64() > 0.7
|
||||
};
|
||||
if do_cut_out {
|
||||
Self::generate_cut_out(
|
||||
chunk,
|
||||
random,
|
||||
width,
|
||||
over_water_height,
|
||||
&origin,
|
||||
is_ellipse,
|
||||
shape_ellipse_a,
|
||||
shape_angle,
|
||||
shape_ellipse_c,
|
||||
);
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
#[expect(clippy::too_many_arguments, clippy::useless_let_if_seq)]
|
||||
fn generate_cut_out<T: GenerationCache>(
|
||||
chunk: &mut T,
|
||||
random: &mut RandomGenerator,
|
||||
width: i32,
|
||||
height: i32,
|
||||
global_origin: &Vector3<i32>,
|
||||
is_ellipse: bool,
|
||||
shape_ellipse_a: i32,
|
||||
shape_angle: f64,
|
||||
shape_ellipse_c: i32,
|
||||
) {
|
||||
let random_sign_x: i32 = if random.next_bool() { -1 } else { 1 };
|
||||
let random_sign_z: i32 = if random.next_bool() { -1 } else { 1 };
|
||||
|
||||
let mut x_off = if random.next_bool() {
|
||||
width / 2 + 1 - random.next_bounded_i32((width - width / 2 - 1).max(1))
|
||||
} else {
|
||||
random.next_bounded_i32((width / 2 - 2).max(1))
|
||||
};
|
||||
|
||||
let mut z_off = if random.next_bool() {
|
||||
width / 2 + 1 - random.next_bounded_i32((width - width / 2 - 1).max(1))
|
||||
} else {
|
||||
random.next_bounded_i32((width / 2 - 2).max(1))
|
||||
};
|
||||
if is_ellipse {
|
||||
let v = random.next_bounded_i32((shape_ellipse_a - 5).max(1));
|
||||
x_off = v;
|
||||
z_off = v;
|
||||
}
|
||||
|
||||
let local_origin = Vector3::new(random_sign_x * x_off, 0, random_sign_z * z_off);
|
||||
let angle = if is_ellipse {
|
||||
shape_angle + consts::FRAC_PI_2
|
||||
} else {
|
||||
random.next_f64() * 2.0 * consts::PI
|
||||
};
|
||||
|
||||
// Above-water carve
|
||||
for y_off in 0..(height - 3) {
|
||||
let radius = Self::height_dependent_radius_round(random, y_off, height, width);
|
||||
Self::carve(
|
||||
chunk,
|
||||
radius,
|
||||
y_off,
|
||||
global_origin,
|
||||
false,
|
||||
angle,
|
||||
&local_origin,
|
||||
shape_ellipse_a,
|
||||
shape_ellipse_c,
|
||||
);
|
||||
}
|
||||
|
||||
// Below-water carve
|
||||
let mut y_off = -1i32;
|
||||
while y_off > -height + random.next_bounded_i32(5) {
|
||||
let radius = Self::height_dependent_radius_steep(random, -y_off, height, width);
|
||||
Self::carve(
|
||||
chunk,
|
||||
radius,
|
||||
y_off,
|
||||
global_origin,
|
||||
true,
|
||||
angle,
|
||||
&local_origin,
|
||||
shape_ellipse_a,
|
||||
shape_ellipse_c,
|
||||
);
|
||||
y_off -= 1;
|
||||
}
|
||||
}
|
||||
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
fn carve<T: GenerationCache>(
|
||||
chunk: &mut T,
|
||||
radius: i32,
|
||||
y_off: i32,
|
||||
global_origin: &Vector3<i32>,
|
||||
under_water: bool,
|
||||
angle: f64,
|
||||
local_origin: &Vector3<i32>,
|
||||
shape_ellipse_a: i32,
|
||||
shape_ellipse_c: i32,
|
||||
) {
|
||||
let a = radius + 1 + shape_ellipse_a / 3;
|
||||
let c = (radius - 3).min(3) + shape_ellipse_c / 2 - 1;
|
||||
|
||||
for xo in -a..a {
|
||||
for zo in -a..a {
|
||||
let signed_dist = Self::signed_distance_ellipse(
|
||||
xo,
|
||||
zo,
|
||||
local_origin.x,
|
||||
local_origin.z,
|
||||
a,
|
||||
c,
|
||||
angle,
|
||||
);
|
||||
if signed_dist < 0.0 {
|
||||
let pos = global_origin.add(&Vector3::new(xo, y_off, zo));
|
||||
let raw = GenerationCache::get_block_state(chunk, &pos);
|
||||
let bid = raw.to_block_id();
|
||||
if Self::is_iceberg_state(bid) || bid == Block::SNOW_BLOCK.id {
|
||||
if under_water {
|
||||
chunk.set_block_state(&pos, Block::WATER.default_state);
|
||||
} else {
|
||||
chunk.set_block_state(&pos, Block::AIR.default_state);
|
||||
Self::remove_floating_snow_layer(chunk, &pos);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn remove_floating_snow_layer<T: GenerationCache>(chunk: &mut T, pos: &Vector3<i32>) {
|
||||
let above = pos.add(&Vector3::new(0, 1, 0));
|
||||
let raw = GenerationCache::get_block_state(chunk, &above);
|
||||
if raw.to_block_id() == Block::SNOW.id {
|
||||
chunk.set_block_state(&above, Block::AIR.default_state);
|
||||
}
|
||||
}
|
||||
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
fn generate_iceberg_block<T: GenerationCache>(
|
||||
chunk: &mut T,
|
||||
random: &mut RandomGenerator,
|
||||
origin: &Vector3<i32>,
|
||||
height: i32,
|
||||
xo: i32,
|
||||
y_off: i32,
|
||||
zo: i32,
|
||||
radius: i32,
|
||||
a: i32,
|
||||
is_ellipse: bool,
|
||||
shape_ellipse_c: i32,
|
||||
shape_angle: f64,
|
||||
snow_on_top: bool,
|
||||
main_block: &'static BlockState,
|
||||
) {
|
||||
let signed_dist = if is_ellipse {
|
||||
Self::signed_distance_ellipse(
|
||||
xo,
|
||||
zo,
|
||||
0,
|
||||
0,
|
||||
a,
|
||||
Self::get_ellipse_c(y_off, height, shape_ellipse_c),
|
||||
shape_angle,
|
||||
)
|
||||
} else {
|
||||
Self::signed_distance_circle(xo, zo, 0, 0, radius, random)
|
||||
};
|
||||
|
||||
if signed_dist < 0.0 {
|
||||
let pos = origin.add(&Vector3::new(xo, y_off, zo));
|
||||
let compare_val: f64 = if is_ellipse {
|
||||
-0.5
|
||||
} else {
|
||||
-6.0 - random.next_bounded_i32(3) as f64
|
||||
};
|
||||
if signed_dist > compare_val && random.next_f64() > 0.9 {
|
||||
return;
|
||||
}
|
||||
Self::set_iceberg_block(
|
||||
chunk,
|
||||
random,
|
||||
&pos,
|
||||
height - y_off,
|
||||
height,
|
||||
is_ellipse,
|
||||
snow_on_top,
|
||||
main_block,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
fn set_iceberg_block<T: GenerationCache>(
|
||||
chunk: &mut T,
|
||||
random: &mut RandomGenerator,
|
||||
pos: &Vector3<i32>,
|
||||
h_diff: i32,
|
||||
height: i32,
|
||||
is_ellipse: bool,
|
||||
snow_on_top: bool,
|
||||
main_block: &'static BlockState,
|
||||
) {
|
||||
let state_id = GenerationCache::get_block_state(chunk, pos);
|
||||
let bid = state_id.to_block_id();
|
||||
if is_air(state_id)
|
||||
|| bid == Block::SNOW_BLOCK.id
|
||||
|| bid == Block::ICE.id
|
||||
|| bid == Block::WATER.id
|
||||
{
|
||||
let randomness = !is_ellipse || random.next_f64() > 0.05;
|
||||
let divisor = if is_ellipse { 3 } else { 2 };
|
||||
let threshold =
|
||||
random.next_bounded_i32((height / divisor).max(1)) as f64 + height as f64 * 0.6;
|
||||
if snow_on_top && bid != Block::WATER.id && h_diff as f64 <= threshold && randomness {
|
||||
chunk.set_block_state(pos, Block::SNOW_BLOCK.default_state);
|
||||
} else {
|
||||
chunk.set_block_state(pos, main_block);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn smooth<T: GenerationCache>(
|
||||
chunk: &mut T,
|
||||
origin: &Vector3<i32>,
|
||||
width: i32,
|
||||
height: i32,
|
||||
is_ellipse: bool,
|
||||
shape_ellipse_a: i32,
|
||||
) {
|
||||
let a = if is_ellipse {
|
||||
shape_ellipse_a
|
||||
} else {
|
||||
width / 2
|
||||
};
|
||||
for x in -a..=a {
|
||||
for z in -a..=a {
|
||||
for y_off in 0..=height {
|
||||
let pos = origin.add(&Vector3::new(x, y_off, z));
|
||||
let raw = GenerationCache::get_block_state(chunk, &pos);
|
||||
let bid = raw.to_block_id();
|
||||
if Self::is_iceberg_state(bid) || bid == Block::SNOW.id {
|
||||
let below = pos.add(&Vector3::new(0, -1, 0));
|
||||
let below_state_id = GenerationCache::get_block_state(chunk, &below);
|
||||
if is_air(below_state_id) {
|
||||
chunk.set_block_state(&pos, Block::AIR.default_state);
|
||||
let above = pos.add(&Vector3::new(0, 1, 0));
|
||||
chunk.set_block_state(&above, Block::AIR.default_state);
|
||||
} else if Self::is_iceberg_state(bid) {
|
||||
let sides = [
|
||||
pos.add(&Vector3::new(-1, 0, 0)), // west
|
||||
pos.add(&Vector3::new(1, 0, 0)), // east
|
||||
pos.add(&Vector3::new(0, 0, -1)), // north
|
||||
pos.add(&Vector3::new(0, 0, 1)), // south
|
||||
];
|
||||
let non_iceberg_count = sides
|
||||
.iter()
|
||||
.filter(|side| {
|
||||
!Self::is_iceberg_state(
|
||||
GenerationCache::get_block_state(chunk, side).to_block_id(),
|
||||
)
|
||||
})
|
||||
.count();
|
||||
if non_iceberg_count >= 3 {
|
||||
chunk.set_block_state(&pos, Block::AIR.default_state);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const fn get_ellipse_c(y_off: i32, height: i32, shape_ellipse_c: i32) -> i32 {
|
||||
if y_off > 0 && height - y_off <= 3 {
|
||||
return shape_ellipse_c - (4 - (height - y_off));
|
||||
}
|
||||
shape_ellipse_c
|
||||
}
|
||||
|
||||
fn signed_distance_circle(
|
||||
xo: i32,
|
||||
zo: i32,
|
||||
ox: i32,
|
||||
oz: i32,
|
||||
radius: i32,
|
||||
random: &mut RandomGenerator,
|
||||
) -> f64 {
|
||||
let off = 10.0f32 * random.next_f32().clamp(0.2, 0.8) / radius as f32;
|
||||
off as f64 + ((xo - ox) as f64).powi(2) + ((zo - oz) as f64).powi(2)
|
||||
- (radius as f64).powi(2)
|
||||
}
|
||||
|
||||
fn signed_distance_ellipse(
|
||||
xo: i32,
|
||||
zo: i32,
|
||||
ox: i32,
|
||||
oz: i32,
|
||||
a: i32,
|
||||
c: i32,
|
||||
angle: f64,
|
||||
) -> f64 {
|
||||
let dx = (xo - ox) as f64;
|
||||
let dz = (zo - oz) as f64;
|
||||
let cos = angle.cos();
|
||||
let sin = angle.sin();
|
||||
((dx * cos - dz * sin) / a as f64).powi(2) + ((dx * sin + dz * cos) / c as f64).powi(2)
|
||||
- 1.0
|
||||
}
|
||||
|
||||
fn height_dependent_radius_round(
|
||||
random: &mut RandomGenerator,
|
||||
y_off: i32,
|
||||
height: i32,
|
||||
width: i32,
|
||||
) -> i32 {
|
||||
let k = 3.5f32 - random.next_f32();
|
||||
let y_off_sq = (y_off as f64).powi(2) as f32;
|
||||
let scale = if height > 15 + random.next_bounded_i32(5) {
|
||||
let temp_y_off = if y_off < 3 + random.next_bounded_i32(6) {
|
||||
y_off / 2
|
||||
} else {
|
||||
y_off
|
||||
};
|
||||
(1.0f32 - temp_y_off as f32 / (height as f32 * k * 0.4f32)) * width as f32
|
||||
} else {
|
||||
(1.0f32 - y_off_sq / (height as f32 * k)) * width as f32
|
||||
};
|
||||
|
||||
(scale / 2.0f32).ceil() as i32
|
||||
}
|
||||
|
||||
fn height_dependent_radius_ellipse(y_off: i32, height: i32, width: i32) -> i32 {
|
||||
let y_off_sq = (y_off as f64).powi(2) as f32;
|
||||
let scale = (1.0f32 - y_off_sq / height as f32) * width as f32;
|
||||
(scale / 2.0f32).ceil() as i32
|
||||
}
|
||||
|
||||
fn height_dependent_radius_steep(
|
||||
random: &mut RandomGenerator,
|
||||
y_off: i32,
|
||||
height: i32,
|
||||
width: i32,
|
||||
) -> i32 {
|
||||
let k = 1.0f32 + random.next_f32() / 2.0f32;
|
||||
let scale = (1.0f32 - y_off as f32 / (height as f32 * k)) * width as f32;
|
||||
(scale / 2.0f32).ceil() as i32
|
||||
}
|
||||
|
||||
const fn is_iceberg_state(id: BlockId) -> bool {
|
||||
matches!(
|
||||
id,
|
||||
BlockId::PACKED_ICE | BlockId::SNOW_BLOCK | BlockId::BLUE_ICE
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
use crate::generation::proto_chunk::GenerationCache;
|
||||
use pumpkin_data::{Block, BlockState};
|
||||
use pumpkin_util::{
|
||||
math::position::BlockPos,
|
||||
random::{RandomGenerator, RandomImpl},
|
||||
};
|
||||
|
||||
pub struct KelpFeature;
|
||||
|
||||
impl KelpFeature {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn generate<T: GenerationCache>(
|
||||
chunk: &mut T,
|
||||
_min_y: i8,
|
||||
_height: u16,
|
||||
_feature: pumpkin_data::placed_feature::PlacedFeature,
|
||||
random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> bool {
|
||||
let mut placed = 0;
|
||||
|
||||
// Start on the ocean floor
|
||||
let y = chunk.ocean_floor_height_exclusive(pos.0.x, pos.0.z);
|
||||
let mut kelp_pos = BlockPos::new(pos.0.x, y, pos.0.z);
|
||||
|
||||
// Must be in water
|
||||
if GenerationCache::get_block_state(chunk, &kelp_pos.0).to_block_id() == Block::WATER {
|
||||
let height_rand = 1 + random.next_bounded_i32(10);
|
||||
|
||||
// Iterate from base up to height_rand
|
||||
for h in 0..=height_rand {
|
||||
// Check there is water at this position and one above
|
||||
if GenerationCache::get_block_state(chunk, &kelp_pos.0).to_block_id()
|
||||
== Block::WATER
|
||||
&& GenerationCache::get_block_state(
|
||||
chunk,
|
||||
&BlockPos::new(kelp_pos.0.x, kelp_pos.0.y + 1, kelp_pos.0.z).0,
|
||||
)
|
||||
.to_block_id()
|
||||
== Block::WATER
|
||||
{
|
||||
// If this is the last iteration place the kelp head with age
|
||||
if h == height_rand {
|
||||
let age = random.next_bounded_i32(4) + 20;
|
||||
// Clamp in case it goes past available states
|
||||
let age = age.min((Block::KELP.states.len() - 1) as i32) as usize;
|
||||
let state_id = Block::KELP.states[age].id;
|
||||
let state = BlockState::from_id(state_id);
|
||||
chunk.set_block_state(&kelp_pos.0, state);
|
||||
placed += 1;
|
||||
} else {
|
||||
// Place kelp plant body
|
||||
let state_id = Block::KELP_PLANT.default_state.id;
|
||||
let state = BlockState::from_id(state_id);
|
||||
chunk.set_block_state(&kelp_pos.0, state);
|
||||
}
|
||||
} else if h > 0 {
|
||||
// Can't place further but we have already placed at least one segment, try to put head below
|
||||
let below = BlockPos::new(kelp_pos.0.x, kelp_pos.0.y - 1, kelp_pos.0.z);
|
||||
// Check head block can survive and that below-below is not a kelp head
|
||||
if GenerationCache::get_block_state(chunk, &below.0).to_block_id()
|
||||
== Block::WATER
|
||||
&& GenerationCache::get_block_state(
|
||||
chunk,
|
||||
&BlockPos::new(below.0.x, below.0.y - 1, below.0.z).0,
|
||||
)
|
||||
.to_block_id()
|
||||
!= Block::KELP
|
||||
{
|
||||
let age = random.next_bounded_i32(4) + 20;
|
||||
let age = age.min((Block::KELP.states.len() - 1) as i32) as usize;
|
||||
let state_id = Block::KELP.states[age].id;
|
||||
let state = BlockState::from_id(state_id);
|
||||
chunk.set_block_state(&below.0, state);
|
||||
placed += 1;
|
||||
}
|
||||
break;
|
||||
}
|
||||
kelp_pos = BlockPos::new(kelp_pos.0.x, kelp_pos.0.y + 1, kelp_pos.0.z);
|
||||
}
|
||||
}
|
||||
|
||||
placed > 0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
use pumpkin_data::{Block, BlockState, tag};
|
||||
use pumpkin_util::{
|
||||
math::position::BlockPos,
|
||||
random::{RandomGenerator, RandomImpl},
|
||||
};
|
||||
|
||||
use crate::generation::{block_state_provider::BlockStateProvider, proto_chunk::GenerationCache};
|
||||
use crate::world::WorldPortalExt;
|
||||
|
||||
pub struct LakeFeature {
|
||||
pub fluid: BlockStateProvider,
|
||||
pub barrier: BlockStateProvider,
|
||||
}
|
||||
|
||||
impl LakeFeature {
|
||||
#[expect(clippy::too_many_lines)]
|
||||
pub fn generate<T: GenerationCache>(
|
||||
&self,
|
||||
block_registry: &dyn WorldPortalExt,
|
||||
chunk: &mut T,
|
||||
random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> bool {
|
||||
if pos.0.y <= chunk.bottom_y() as i32 + 4 {
|
||||
return false;
|
||||
}
|
||||
|
||||
let origin = pos.add(-8, -4, -8);
|
||||
let mut grid = [false; 2048];
|
||||
let spots = random.next_bounded_i32(4) + 4;
|
||||
|
||||
for _ in 0..spots {
|
||||
let xr = random.next_f64() * 6.0 + 3.0;
|
||||
let yr = random.next_f64() * 4.0 + 2.0;
|
||||
let zr = random.next_f64() * 6.0 + 3.0;
|
||||
let xp = random.next_f64() * (16.0 - xr - 2.0) + 1.0 + xr / 2.0;
|
||||
let yp = random.next_f64() * (8.0 - yr - 4.0) + 2.0 + yr / 2.0;
|
||||
let zp = random.next_f64() * (16.0 - zr - 2.0) + 1.0 + zr / 2.0;
|
||||
|
||||
for xx in 1..15 {
|
||||
for zz in 1..15 {
|
||||
for yy in 1..7 {
|
||||
let xd = (xx as f64 - xp) / (xr / 2.0);
|
||||
let yd = (yy as f64 - yp) / (yr / 2.0);
|
||||
let zd = (zz as f64 - zp) / (zr / 2.0);
|
||||
let d = xd * xd + yd * yd + zd * zd;
|
||||
if d < 1.0 {
|
||||
grid[(xx * 16 + zz) * 8 + yy] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let fluid_state = self
|
||||
.fluid
|
||||
.get_with_context(block_registry, chunk, random, origin);
|
||||
|
||||
for xx in 0..16 {
|
||||
for zz in 0..16 {
|
||||
for yyx in 0..8 {
|
||||
let check = !grid[(xx * 16 + zz) * 8 + yyx]
|
||||
&& (xx < 15 && grid[((xx + 1) * 16 + zz) * 8 + yyx]
|
||||
|| xx > 0 && grid[((xx - 1) * 16 + zz) * 8 + yyx]
|
||||
|| zz < 15 && grid[(xx * 16 + zz + 1) * 8 + yyx]
|
||||
|| zz > 0 && grid[(xx * 16 + (zz - 1)) * 8 + yyx]
|
||||
|| yyx < 7 && grid[(xx * 16 + zz) * 8 + yyx + 1]
|
||||
|| yyx > 0 && grid[(xx * 16 + zz) * 8 + (yyx - 1)]);
|
||||
|
||||
if check {
|
||||
let check_pos = origin.add(xx as i32, yyx as i32, zz as i32);
|
||||
let block_state =
|
||||
GenerationCache::get_block_state(chunk, &check_pos.0).to_state();
|
||||
|
||||
if yyx >= 4 && block_state.is_liquid() {
|
||||
return false;
|
||||
}
|
||||
|
||||
if yyx < 4 && !block_state.is_solid() && block_state != fluid_state {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let air_state = Block::CAVE_AIR.default_state;
|
||||
|
||||
for xx in 0..16 {
|
||||
for zz in 0..16 {
|
||||
for yyx in 0..8 {
|
||||
if grid[(xx * 16 + zz) * 8 + yyx] {
|
||||
let place_pos = origin.add(xx as i32, yyx as i32, zz as i32);
|
||||
let current_state =
|
||||
GenerationCache::get_block_state(chunk, &place_pos.0).to_state();
|
||||
if Self::can_replace_block(current_state) {
|
||||
let place_air = yyx >= 4;
|
||||
chunk.set_block_state(
|
||||
&place_pos.0,
|
||||
if place_air { air_state } else { fluid_state },
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let barrier_state = self
|
||||
.barrier
|
||||
.get_with_context(block_registry, chunk, random, origin);
|
||||
if !barrier_state.is_air() {
|
||||
for xx in 0..16 {
|
||||
for zz in 0..16 {
|
||||
for yyx in 0..8 {
|
||||
let check = !grid[(xx * 16 + zz) * 8 + yyx]
|
||||
&& (xx < 15 && grid[((xx + 1) * 16 + zz) * 8 + yyx]
|
||||
|| xx > 0 && grid[((xx - 1) * 16 + zz) * 8 + yyx]
|
||||
|| zz < 15 && grid[(xx * 16 + zz + 1) * 8 + yyx]
|
||||
|| zz > 0 && grid[(xx * 16 + (zz - 1)) * 8 + yyx]
|
||||
|| yyx < 7 && grid[(xx * 16 + zz) * 8 + yyx + 1]
|
||||
|| yyx > 0 && grid[(xx * 16 + zz) * 8 + (yyx - 1)]);
|
||||
|
||||
if check && (yyx < 4 || random.next_bounded_i32(2) != 0) {
|
||||
let barrier_pos = origin.add(xx as i32, yyx as i32, zz as i32);
|
||||
let block_state =
|
||||
GenerationCache::get_block_state(chunk, &barrier_pos.0).to_state();
|
||||
if block_state.is_solid()
|
||||
&& !block_state
|
||||
.id
|
||||
.to_block_id()
|
||||
.has_tag(tag::Block::MINECRAFT_LAVA_POOL_STONE_CANNOT_REPLACE)
|
||||
{
|
||||
chunk.set_block_state(&barrier_pos.0, barrier_state);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Freeze top layer
|
||||
if Block::from_state_id(fluid_state.id).id == Block::WATER.id {
|
||||
for xx in 0..16 {
|
||||
for zz in 0..16 {
|
||||
let freeze_pos = origin.add(xx, 4, zz);
|
||||
let biome = chunk.get_biome_for_terrain_gen(
|
||||
freeze_pos.0.x,
|
||||
freeze_pos.0.y,
|
||||
freeze_pos.0.z,
|
||||
);
|
||||
if biome.weather.compute_temperature(
|
||||
freeze_pos.0.x as f64,
|
||||
freeze_pos.0.y,
|
||||
freeze_pos.0.z as f64,
|
||||
63,
|
||||
) < 0.15
|
||||
{
|
||||
let current_state =
|
||||
GenerationCache::get_block_state(chunk, &freeze_pos.0).to_state();
|
||||
if Self::can_replace_block(current_state) {
|
||||
chunk.set_block_state(&freeze_pos.0, Block::ICE.default_state);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
fn can_replace_block(state: &BlockState) -> bool {
|
||||
!state
|
||||
.id
|
||||
.to_block_id()
|
||||
.has_tag(tag::Block::MINECRAFT_FEATURES_CANNOT_REPLACE)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
pub mod bamboo;
|
||||
pub mod basalt_columns;
|
||||
pub mod basalt_pillar;
|
||||
pub mod block_column;
|
||||
pub mod block_pile;
|
||||
pub mod blue_ice;
|
||||
pub mod bonus_chest;
|
||||
pub mod chorus_plant;
|
||||
pub mod coral;
|
||||
pub mod delta_feature;
|
||||
pub mod desert_well;
|
||||
pub mod disk;
|
||||
pub mod drip_stone;
|
||||
pub mod end_gateway;
|
||||
pub mod end_island;
|
||||
pub mod end_platform;
|
||||
pub mod end_spike;
|
||||
pub mod fallen_tree;
|
||||
pub mod fill_layer;
|
||||
pub mod forest_rock;
|
||||
pub mod fossil;
|
||||
pub mod freeze_top_layer;
|
||||
pub mod geode;
|
||||
pub mod glowstone_blob;
|
||||
pub mod huge_brown_mushroom;
|
||||
pub mod huge_fungus;
|
||||
pub mod huge_red_mushroom;
|
||||
pub mod ice_spike;
|
||||
pub mod iceberg;
|
||||
pub mod kelp;
|
||||
pub mod lake;
|
||||
pub mod monster_room;
|
||||
pub mod multiface_growth;
|
||||
pub mod nether_forest_vegetation;
|
||||
pub mod netherrack_replace_blobs;
|
||||
pub mod ore;
|
||||
pub mod random_boolean_selector;
|
||||
pub mod random_patch;
|
||||
pub mod random_selector;
|
||||
pub mod replace_single_block;
|
||||
pub mod root_system;
|
||||
pub mod scattered_ore;
|
||||
pub mod sculk_patch;
|
||||
pub mod sea_pickle;
|
||||
pub mod seagrass;
|
||||
pub mod simple_block;
|
||||
pub mod simple_random_selector;
|
||||
pub mod spring_feature;
|
||||
pub mod tree;
|
||||
pub mod twisting_vines;
|
||||
pub mod underwater_magma;
|
||||
pub mod vegetation_patch;
|
||||
pub mod vines;
|
||||
pub mod void_start_platform;
|
||||
pub mod waterlogged_vegetation_patch;
|
||||
pub mod weeping_vines;
|
||||
@@ -0,0 +1,195 @@
|
||||
use pumpkin_data::{Block, BlockDirection};
|
||||
use pumpkin_nbt::compound::NbtCompound;
|
||||
use pumpkin_util::{
|
||||
math::{position::BlockPos, vector3::Vector3},
|
||||
random::{RandomGenerator, RandomImpl},
|
||||
};
|
||||
|
||||
use crate::generation::proto_chunk::GenerationCache;
|
||||
|
||||
/// The three mob types that can appear in a dungeon spawner.
|
||||
///
|
||||
/// Skeleton 25%, Zombie 50%, Spider 25%.
|
||||
const DUNGEON_MOBS: [&str; 4] = [
|
||||
"minecraft:skeleton",
|
||||
"minecraft:zombie",
|
||||
"minecraft:zombie",
|
||||
"minecraft:spider",
|
||||
];
|
||||
|
||||
pub struct DungeonFeature;
|
||||
|
||||
impl DungeonFeature {
|
||||
/// Generate a monster room (dungeon) at `pos`.
|
||||
#[expect(clippy::too_many_lines)]
|
||||
pub fn generate<T: GenerationCache>(
|
||||
chunk: &mut T,
|
||||
_min_y: i8,
|
||||
_height: u16,
|
||||
_feature: pumpkin_data::placed_feature::PlacedFeature,
|
||||
random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> bool {
|
||||
let xr = random.next_bounded_i32(2) + 2;
|
||||
let zr = random.next_bounded_i32(2) + 2;
|
||||
|
||||
let min_x = -xr - 1;
|
||||
let max_x = xr + 1;
|
||||
let min_z = -zr - 1;
|
||||
let max_z = zr + 1;
|
||||
|
||||
let mut hole_count = 0i32;
|
||||
for dx in min_x..=max_x {
|
||||
for dy in -1..=4i32 {
|
||||
for dz in min_z..=max_z {
|
||||
let check_pos = pos.0.add(&Vector3::new(dx, dy, dz));
|
||||
let solid = !chunk.is_air(&check_pos);
|
||||
|
||||
if dy == -1 && !solid {
|
||||
return false; // Floor has a gap
|
||||
}
|
||||
if dy == 4 && !solid {
|
||||
return false; // Ceiling has a gap
|
||||
}
|
||||
|
||||
// Wall openings
|
||||
let on_wall = dx == min_x || dx == max_x || dz == min_z || dz == max_z;
|
||||
if on_wall
|
||||
&& dy == 0
|
||||
&& chunk.is_air(&check_pos)
|
||||
&& chunk.is_air(&check_pos.add(&Vector3::new(0, 1, 0)))
|
||||
{
|
||||
hole_count += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !(1..=5).contains(&hole_count) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for dx in min_x..=max_x {
|
||||
for dy in (-1..=3i32).rev() {
|
||||
for dz in min_z..=max_z {
|
||||
let wall_pos = pos.0.add(&Vector3::new(dx, dy, dz));
|
||||
|
||||
let on_boundary = dx == min_x
|
||||
|| dy == -1
|
||||
|| dz == min_z
|
||||
|| dx == max_x
|
||||
|| dy == 4
|
||||
|| dz == max_z;
|
||||
|
||||
if on_boundary {
|
||||
let below_pos = wall_pos.add(&Vector3::new(0, -1, 0));
|
||||
let below_solid = !chunk.is_air(&below_pos);
|
||||
let cur_solid = !chunk.is_air(&wall_pos);
|
||||
let is_chest = GenerationCache::get_block_state(chunk, &wall_pos)
|
||||
.to_block()
|
||||
== &Block::CHEST;
|
||||
|
||||
let world_min_y = chunk.bottom_y() as i32;
|
||||
if wall_pos.y >= world_min_y && !below_solid {
|
||||
chunk.set_block_state(&wall_pos, Block::CAVE_AIR.default_state);
|
||||
} else if cur_solid && !is_chest {
|
||||
if dy == -1 && random.next_bounded_i32(4) != 0 {
|
||||
// 75% mossy cobblestone
|
||||
chunk.set_block_state(
|
||||
&wall_pos,
|
||||
Block::MOSSY_COBBLESTONE.default_state,
|
||||
);
|
||||
} else {
|
||||
// 25% cobblestone (or 100% if it's not the floor)
|
||||
chunk.set_block_state(&wall_pos, Block::COBBLESTONE.default_state);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Clear interior, but preserve chests and spawners
|
||||
let state = GenerationCache::get_block_state(chunk, &wall_pos);
|
||||
let is_chest = state.to_block() == &Block::CHEST;
|
||||
let is_spawner = state.to_block() == &Block::SPAWNER;
|
||||
if !is_chest && !is_spawner {
|
||||
chunk.set_block_state(&wall_pos, Block::CAVE_AIR.default_state);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Chest placement attempts (rooms have 1-2 chests)
|
||||
for _ in 0..2 {
|
||||
for _ in 0..3 {
|
||||
let cx = pos.0.x + random.next_bounded_i32(xr * 2 + 1) - xr;
|
||||
let cy = pos.0.y;
|
||||
let cz = pos.0.z + random.next_bounded_i32(zr * 2 + 1) - zr;
|
||||
let chest_pos = Vector3::new(cx, cy, cz);
|
||||
|
||||
if !chunk.is_air(&chest_pos) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Count solid horizontal neighbours
|
||||
let wall_count = BlockDirection::horizontal()
|
||||
.iter()
|
||||
.filter(|d| !chunk.is_air(&chest_pos.add(&d.to_offset())))
|
||||
.count();
|
||||
|
||||
if wall_count == 1 {
|
||||
// Orient the chest toward its single solid neighbor.
|
||||
let facing_dir = BlockDirection::horizontal()
|
||||
.iter()
|
||||
.find(|d| !chunk.is_air(&chest_pos.add(&d.to_offset())))
|
||||
.copied();
|
||||
|
||||
// Build the chest state: face away from the wall.
|
||||
let chest_state = facing_dir.map_or(Block::CHEST.default_state, |dir| {
|
||||
use pumpkin_data::block_properties::{
|
||||
BlockProperties, ChestLikeProperties,
|
||||
};
|
||||
let mut props = ChestLikeProperties::default(&Block::CHEST);
|
||||
props.facing = dir.opposite();
|
||||
let state_id = props.to_state_id(&Block::CHEST);
|
||||
pumpkin_data::BlockState::from_id(state_id)
|
||||
});
|
||||
|
||||
chunk.set_block_state(&chest_pos, chest_state);
|
||||
|
||||
// Write the block-entity NBT with a deferred loot table.
|
||||
let loot_seed = random.next_i64();
|
||||
let mut chest_nbt = NbtCompound::new();
|
||||
chest_nbt.put_string("id", "minecraft:chest".to_string());
|
||||
chest_nbt.put_int("x", chest_pos.x);
|
||||
chest_nbt.put_int("y", chest_pos.y);
|
||||
chest_nbt.put_int("z", chest_pos.z);
|
||||
chest_nbt
|
||||
.put_string("LootTable", "minecraft:chests/simple_dungeon".to_string());
|
||||
chest_nbt.put_long("LootTableSeed", loot_seed);
|
||||
chunk.add_block_entity(&chest_pos, chest_nbt);
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: set spawner entity type
|
||||
let mob = DUNGEON_MOBS[random.next_bounded_i32(DUNGEON_MOBS.len() as i32) as usize];
|
||||
chunk.set_block_state(&pos.0, Block::SPAWNER.default_state);
|
||||
|
||||
let mut entity_nbt = NbtCompound::new();
|
||||
entity_nbt.put_string("id", "minecraft:mob_spawner".to_string());
|
||||
entity_nbt.put_int("x", pos.0.x);
|
||||
entity_nbt.put_int("y", pos.0.y);
|
||||
entity_nbt.put_int("z", pos.0.z);
|
||||
|
||||
let mut spawn_entry = NbtCompound::new();
|
||||
let mut entity_nbt_inner = NbtCompound::new();
|
||||
entity_nbt_inner.put_string("id", mob.to_string());
|
||||
spawn_entry.put_compound("entity", entity_nbt_inner);
|
||||
entity_nbt.put_compound("SpawnData", spawn_entry);
|
||||
|
||||
chunk.add_block_entity(&pos.0, entity_nbt);
|
||||
|
||||
true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
use pumpkin_data::Block;
|
||||
use pumpkin_util::{math::position::BlockPos, random::RandomGenerator};
|
||||
|
||||
use crate::generation::proto_chunk::GenerationCache;
|
||||
|
||||
pub struct MultifaceGrowthFeature;
|
||||
|
||||
impl MultifaceGrowthFeature {
|
||||
#[allow(clippy::unused_self)]
|
||||
pub fn generate<T: GenerationCache>(
|
||||
&self,
|
||||
chunk: &mut T,
|
||||
_min_y: i8,
|
||||
_height: u16,
|
||||
_feature: pumpkin_data::placed_feature::PlacedFeature,
|
||||
_random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> bool {
|
||||
let mut generated = false;
|
||||
let directions = [
|
||||
(1, 0, 0),
|
||||
(-1, 0, 0),
|
||||
(0, 1, 0),
|
||||
(0, -1, 0),
|
||||
(0, 0, 1),
|
||||
(0, 0, -1),
|
||||
];
|
||||
for &(dx, dy, dz) in &directions {
|
||||
let neighbor = BlockPos::new(pos.0.x + dx, pos.0.y + dy, pos.0.z + dz);
|
||||
let state = GenerationCache::get_block_state(chunk, &neighbor.0);
|
||||
if state.to_block_id() != Block::AIR.id && chunk.is_air(&pos.0) {
|
||||
chunk.set_block_state(&pos.0, Block::GLOW_LICHEN.default_state);
|
||||
generated = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
generated
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
use pumpkin_data::{Block, tag};
|
||||
use pumpkin_util::{
|
||||
math::position::BlockPos,
|
||||
random::{RandomGenerator, RandomImpl},
|
||||
};
|
||||
|
||||
use crate::generation::proto_chunk::GenerationCache;
|
||||
use crate::{generation::block_state_provider::BlockStateProvider, world::WorldPortalExt};
|
||||
|
||||
pub struct NetherForestVegetationFeature {
|
||||
pub state_provider: BlockStateProvider,
|
||||
pub spread_width: i32,
|
||||
pub spread_height: i32,
|
||||
}
|
||||
|
||||
impl NetherForestVegetationFeature {
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
pub fn generate<T: GenerationCache>(
|
||||
&self,
|
||||
chunk: &mut T,
|
||||
block_registry: &dyn WorldPortalExt,
|
||||
_min_y: i8,
|
||||
_height: u16,
|
||||
_feature: pumpkin_data::placed_feature::PlacedFeature,
|
||||
random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> bool {
|
||||
let origin_pos = pos;
|
||||
let below_state = GenerationCache::get_block_state(chunk, &origin_pos.down().0);
|
||||
|
||||
if !below_state
|
||||
.to_block_id()
|
||||
.has_tag(tag::Block::MINECRAFT_NYLIUM)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// Origin must be within (minY + 1, maxY - 1) inclusive.
|
||||
if origin_pos.0.y <= chunk.bottom_y() as i32 || origin_pos.0.y > chunk.top_y() as i32 {
|
||||
return false;
|
||||
}
|
||||
|
||||
let mut result = false;
|
||||
|
||||
for _ in 0..self.spread_width * self.spread_width {
|
||||
let pos = origin_pos.add(
|
||||
random.next_bounded_i32(self.spread_width)
|
||||
- random.next_bounded_i32(self.spread_width),
|
||||
random.next_bounded_i32(self.spread_height)
|
||||
- random.next_bounded_i32(self.spread_height),
|
||||
random.next_bounded_i32(self.spread_width)
|
||||
- random.next_bounded_i32(self.spread_width),
|
||||
);
|
||||
|
||||
let nether_state = self.state_provider.get(random, pos, chunk, block_registry);
|
||||
let nether_block = Block::from_state_id(nether_state.id);
|
||||
|
||||
// Only place if the spot is air, above the bottom, and the block can survive here.
|
||||
if !chunk.is_air(&pos.0)
|
||||
|| pos.0.y <= chunk.bottom_y() as i32
|
||||
|| !block_registry.can_place_at(nether_block, nether_state, chunk, &pos)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
chunk.set_block_state(&pos.0, nether_state);
|
||||
result = true;
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
use pumpkin_data::{Block, BlockState};
|
||||
use pumpkin_util::{
|
||||
math::{int_provider::IntProvider, position::BlockPos},
|
||||
random::RandomGenerator,
|
||||
};
|
||||
|
||||
use crate::generation::proto_chunk::GenerationCache;
|
||||
use crate::world::WorldPortalExt;
|
||||
|
||||
pub struct ReplaceBlobsFeature {
|
||||
pub target: &'static BlockState,
|
||||
pub state: &'static BlockState,
|
||||
pub radius: IntProvider,
|
||||
}
|
||||
|
||||
impl ReplaceBlobsFeature {
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
pub fn generate<T: GenerationCache>(
|
||||
&self,
|
||||
chunk: &mut T,
|
||||
_block_registry: &dyn WorldPortalExt,
|
||||
_min_y: i8,
|
||||
_height: u16,
|
||||
_feature: pumpkin_data::placed_feature::PlacedFeature, // This placed feature
|
||||
random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> bool {
|
||||
let target = Block::from_state_id(self.target.id);
|
||||
let state = &self.state;
|
||||
let Some(pos) = Self::move_down_to_target(pos, chunk, target) else {
|
||||
return false;
|
||||
};
|
||||
let x = self.radius.get(random);
|
||||
let y = self.radius.get(random);
|
||||
let z = self.radius.get(random);
|
||||
let distance = x.max(y.max(z));
|
||||
|
||||
let mut result = false;
|
||||
|
||||
for iter_pos in BlockPos::iterate_outwards(pos, x, y, z) {
|
||||
if iter_pos.manhattan_distance(pos) > distance {
|
||||
break;
|
||||
}
|
||||
let current_state = GenerationCache::get_block_state(chunk, &iter_pos.0);
|
||||
if current_state.to_block_id() != target.id {
|
||||
continue;
|
||||
}
|
||||
chunk.set_block_state(&iter_pos.0, state);
|
||||
result = true;
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
fn move_down_to_target<T: GenerationCache>(
|
||||
mut pos: BlockPos,
|
||||
chunk: &T,
|
||||
target: &'static Block,
|
||||
) -> Option<BlockPos> {
|
||||
while pos.0.y > chunk.bottom_y() as i32 + 1 {
|
||||
let state = GenerationCache::get_block_state(chunk, &pos.0);
|
||||
if state.to_block_id() == target.id {
|
||||
return Some(pos);
|
||||
}
|
||||
|
||||
pos = pos.down();
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
use core::f32;
|
||||
|
||||
use pumpkin_data::{BlockDirection, BlockState, BlockStateId};
|
||||
use pumpkin_util::{
|
||||
math::{lerp, position::BlockPos, vector3::Vector3},
|
||||
random::{RandomGenerator, RandomImpl},
|
||||
};
|
||||
|
||||
use crate::generation::proto_chunk::GenerationCache;
|
||||
use crate::{generation::rule::RuleTest, world::WorldPortalExt};
|
||||
|
||||
pub struct OreFeature {
|
||||
pub size: i32,
|
||||
pub discard_chance_on_air_exposure: f32,
|
||||
pub targets: Vec<OreTarget>,
|
||||
}
|
||||
|
||||
pub struct OreTarget {
|
||||
pub target: RuleTest,
|
||||
pub state: &'static BlockState,
|
||||
}
|
||||
|
||||
impl OreFeature {
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
pub fn generate<T: GenerationCache>(
|
||||
&self,
|
||||
chunk: &mut T,
|
||||
_block_registry: &dyn WorldPortalExt,
|
||||
_min_y: i8,
|
||||
_height: u16,
|
||||
_feature: pumpkin_data::placed_feature::PlacedFeature, // This placed feature
|
||||
random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> bool {
|
||||
let f = random.next_f32() * f32::consts::PI;
|
||||
let g = self.size as f32 / 8.0f32;
|
||||
let i = f32::midpoint(self.size as f32 / 16.0f32 * 2.0, 1.0).ceil() as i32;
|
||||
|
||||
let d = pos.0.x as f64 + f.sin() as f64 * g as f64;
|
||||
let e = pos.0.x as f64 - f.sin() as f64 * g as f64;
|
||||
let h = pos.0.z as f64 + f.cos() as f64 * g as f64; // Use f.cos() for Math.cos(f)
|
||||
let j = pos.0.z as f64 - f.cos() as f64 * g as f64;
|
||||
|
||||
let l = pos.0.y as f64 + random.next_bounded_i32(3) as f64 - 2.0;
|
||||
let m = pos.0.y as f64 + random.next_bounded_i32(3) as f64 - 2.0;
|
||||
|
||||
let n = pos.0.x - g.ceil() as i32 - i;
|
||||
let o = pos.0.y - 2 - i;
|
||||
let p = pos.0.z - g.ceil() as i32 - i;
|
||||
let q = 2 * (g.ceil() as i32 + i);
|
||||
let r = 2 * (2 + i);
|
||||
|
||||
for _ in n..=(n + q) {
|
||||
for _ in p..=(p + q) {
|
||||
if o > chunk.ocean_floor_height_exclusive(pos.0.x, pos.0.z) {
|
||||
continue;
|
||||
}
|
||||
return self.generate_vein_part(chunk, random, d, e, h, j, l, m, n, o, p, q, r);
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
#[expect(clippy::too_many_lines)]
|
||||
fn generate_vein_part<T: GenerationCache>(
|
||||
&self,
|
||||
chunk: &mut T,
|
||||
random: &mut RandomGenerator,
|
||||
start_x: f64,
|
||||
end_x: f64,
|
||||
start_z: f64,
|
||||
end_z: f64,
|
||||
start_y: f64,
|
||||
end_y: f64,
|
||||
x_bound: i32,
|
||||
y_bound: i32,
|
||||
z_bound: i32,
|
||||
horizontal_size: i32,
|
||||
vertical_size: i32,
|
||||
) -> bool {
|
||||
let mut placed_blocks_count = 0;
|
||||
let bitset_size = (horizontal_size * vertical_size * horizontal_size) as usize;
|
||||
let mut bit_set = vec![false; bitset_size];
|
||||
let mut mutable_pos = BlockPos::ZERO;
|
||||
let j = self.size;
|
||||
let mut ds = vec![0.0; (j * 4) as usize];
|
||||
for k in 0..j {
|
||||
let f = k as f32 / j as f32;
|
||||
let d = lerp(f as f64, start_x, end_x);
|
||||
let e = lerp(f as f64, start_y, end_y);
|
||||
let g = lerp(f as f64, start_z, end_z);
|
||||
let h = random.next_f64() * j as f64 / 16.0;
|
||||
let l = f32::midpoint(((f32::consts::PI * f).sin() + 1.0) * h as f32, 1.0);
|
||||
|
||||
ds[k as usize * 4] = d;
|
||||
ds[k as usize * 4 + 1] = e;
|
||||
ds[k as usize * 4 + 2] = g;
|
||||
ds[k as usize * 4 + 3] = l as f64;
|
||||
}
|
||||
|
||||
for k in 0..(j - 1) {
|
||||
if ds[k as usize * 4 + 3] <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
for m in (k + 1)..j {
|
||||
if ds[m as usize * 4 + 3] <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
let h_val = ds[k as usize * 4 + 3] - ds[m as usize * 4 + 3];
|
||||
let d_val = ds[k as usize * 4] - ds[m as usize * 4];
|
||||
let e_val = ds[k as usize * 4 + 1] - ds[m as usize * 4 + 1];
|
||||
let g_val = ds[k as usize * 4 + 2] - ds[m as usize * 4 + 2];
|
||||
|
||||
if h_val * h_val > d_val * d_val + e_val * e_val + g_val * g_val {
|
||||
if h_val > 0.0 {
|
||||
ds[m as usize * 4 + 3] = -1.0;
|
||||
continue;
|
||||
}
|
||||
ds[k as usize * 4 + 3] = -1.0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for m_idx in 0..j {
|
||||
let d_val = ds[m_idx as usize * 4 + 3];
|
||||
if d_val < 0.0 {
|
||||
continue;
|
||||
}
|
||||
let e_val = ds[m_idx as usize * 4];
|
||||
let g_val = ds[m_idx as usize * 4 + 1];
|
||||
let h_val = ds[m_idx as usize * 4 + 2];
|
||||
|
||||
let n_bound = ((e_val - d_val).floor() as i32).max(x_bound);
|
||||
let o_bound = ((g_val - d_val).floor() as i32).max(y_bound);
|
||||
let p_bound = ((h_val - d_val).floor() as i32).max(z_bound);
|
||||
let q_bound = ((e_val + d_val).floor() as i32).max(n_bound);
|
||||
let r_bound = ((g_val + d_val).floor() as i32).max(o_bound);
|
||||
let s_bound = ((h_val + d_val).floor() as i32).max(p_bound);
|
||||
|
||||
for t_val in n_bound..=q_bound {
|
||||
let u_val = (t_val as f64 + 0.5 - e_val) / d_val;
|
||||
if u_val * u_val >= 1.0 {
|
||||
continue;
|
||||
}
|
||||
for v_val in o_bound..=r_bound {
|
||||
let w_val = (v_val as f64 + 0.5 - g_val) / d_val;
|
||||
if u_val * u_val + w_val * w_val >= 1.0 {
|
||||
continue;
|
||||
}
|
||||
let base_idx = (t_val - x_bound) + (v_val - y_bound) * horizontal_size;
|
||||
|
||||
for aa_val in p_bound..=s_bound {
|
||||
let ab_val = (aa_val as f64 + 0.5 - h_val) / d_val;
|
||||
if u_val * u_val + w_val * w_val + ab_val * ab_val >= 1.0 {
|
||||
continue;
|
||||
}
|
||||
if chunk.out_of_height(v_val as i16) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let ac = (base_idx + (aa_val - z_bound) * horizontal_size * vertical_size)
|
||||
as usize;
|
||||
|
||||
if bit_set[ac] {
|
||||
continue;
|
||||
}
|
||||
bit_set[ac] = true;
|
||||
|
||||
mutable_pos.0.x = t_val;
|
||||
mutable_pos.0.y = v_val;
|
||||
mutable_pos.0.z = aa_val;
|
||||
|
||||
// if !world.is_valid_for_set_block(&mutable_pos) {
|
||||
// continue;
|
||||
// }
|
||||
|
||||
// let ad = t_val;
|
||||
// let ae = v_val;
|
||||
// let af = aa_val;
|
||||
// TODO: using a section would be faster
|
||||
|
||||
let pos_vec = Vector3::new(t_val, v_val, aa_val);
|
||||
let block_state = GenerationCache::get_block_state(chunk, &pos_vec);
|
||||
|
||||
for target in &self.targets {
|
||||
if Self::should_place(
|
||||
self.discard_chance_on_air_exposure,
|
||||
chunk,
|
||||
block_state,
|
||||
random,
|
||||
target,
|
||||
&mutable_pos,
|
||||
) {
|
||||
chunk.set_block_state(&pos_vec, target.state);
|
||||
placed_blocks_count += 1;
|
||||
break; // Equivalent to 'continue block11;'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
placed_blocks_count > 0
|
||||
}
|
||||
|
||||
pub fn should_place<T: GenerationCache>(
|
||||
discard_chance: f32,
|
||||
chunk: &T,
|
||||
state: BlockStateId,
|
||||
random: &mut RandomGenerator,
|
||||
target: &OreTarget,
|
||||
pos: &BlockPos,
|
||||
) -> bool {
|
||||
if !target.target.test(state, random) {
|
||||
return false;
|
||||
}
|
||||
if Self::should_not_discard(random, discard_chance) {
|
||||
return true;
|
||||
}
|
||||
!Self::is_exposed_to_air(chunk, pos)
|
||||
}
|
||||
|
||||
pub fn should_not_discard(random: &mut RandomGenerator, chance: f32) -> bool {
|
||||
if chance <= 0.0f32 {
|
||||
return true;
|
||||
}
|
||||
if chance >= 1.0f32 {
|
||||
return false;
|
||||
}
|
||||
random.next_f32() >= chance
|
||||
}
|
||||
|
||||
pub fn is_exposed_to_air<T: GenerationCache>(chunk: &T, pos: &BlockPos) -> bool {
|
||||
for dir in BlockDirection::all() {
|
||||
if GenerationCache::get_block_state(chunk, &pos.offset(dir.to_offset()).0)
|
||||
.to_state()
|
||||
.is_air()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
use pumpkin_util::{
|
||||
math::position::BlockPos,
|
||||
random::{RandomGenerator, RandomImpl},
|
||||
};
|
||||
|
||||
use crate::generation::proto_chunk::GenerationCache;
|
||||
use crate::{generation::feature::placed_features::PlacedFeatureWrapper, world::WorldPortalExt};
|
||||
|
||||
pub struct RandomBooleanFeature {
|
||||
pub feature_true: Box<PlacedFeatureWrapper>,
|
||||
pub feature_false: Box<PlacedFeatureWrapper>,
|
||||
}
|
||||
|
||||
impl RandomBooleanFeature {
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
pub fn generate<T: GenerationCache>(
|
||||
&self,
|
||||
chunk: &mut T,
|
||||
block_registry: &dyn WorldPortalExt,
|
||||
min_y: i8,
|
||||
height: u16,
|
||||
feature_name: pumpkin_data::placed_feature::PlacedFeature, // This placed feature
|
||||
random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> bool {
|
||||
let val = random.next_bool();
|
||||
let feature = if val {
|
||||
&self.feature_true
|
||||
} else {
|
||||
&self.feature_false
|
||||
};
|
||||
feature.get().generate(
|
||||
chunk,
|
||||
block_registry,
|
||||
min_y,
|
||||
height,
|
||||
feature_name,
|
||||
random,
|
||||
pos,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
use pumpkin_util::{
|
||||
math::{position::BlockPos, vector3::Vector3},
|
||||
random::{RandomGenerator, RandomImpl},
|
||||
};
|
||||
|
||||
use crate::generation::proto_chunk::GenerationCache;
|
||||
use crate::{generation::feature::placed_features::PlacedFeature, world::WorldPortalExt};
|
||||
|
||||
pub struct RandomPatchFeature {
|
||||
pub tries: u8,
|
||||
pub xz_spread: u8,
|
||||
pub y_spread: u8,
|
||||
pub feature: Box<PlacedFeature>,
|
||||
}
|
||||
|
||||
impl RandomPatchFeature {
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
pub fn generate<T: GenerationCache>(
|
||||
&self,
|
||||
chunk: &mut T,
|
||||
block_registry: &dyn WorldPortalExt,
|
||||
min_y: i8,
|
||||
height: u16,
|
||||
feature: pumpkin_data::placed_feature::PlacedFeature,
|
||||
random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> bool {
|
||||
let xz = self.xz_spread as i32 + 1;
|
||||
let y = self.y_spread as i32 + 1;
|
||||
let mut is_some = false;
|
||||
for _ in 0..self.tries {
|
||||
let pos = Vector3::new(
|
||||
pos.0.x + random.next_bounded_i32(xz) - random.next_bounded_i32(xz),
|
||||
pos.0.y + random.next_bounded_i32(y) - random.next_bounded_i32(y),
|
||||
pos.0.z + random.next_bounded_i32(xz) - random.next_bounded_i32(xz),
|
||||
);
|
||||
if !self.feature.generate(
|
||||
chunk,
|
||||
block_registry,
|
||||
min_y,
|
||||
height,
|
||||
feature,
|
||||
random,
|
||||
BlockPos(pos),
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
is_some = true;
|
||||
}
|
||||
is_some
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
use pumpkin_util::{
|
||||
math::position::BlockPos,
|
||||
random::{RandomGenerator, RandomImpl},
|
||||
};
|
||||
|
||||
use crate::generation::proto_chunk::GenerationCache;
|
||||
use crate::{generation::feature::placed_features::PlacedFeatureWrapper, world::WorldPortalExt};
|
||||
|
||||
pub struct RandomFeature {
|
||||
pub features: Vec<RandomFeatureEntry>,
|
||||
pub default: Box<PlacedFeatureWrapper>,
|
||||
}
|
||||
|
||||
pub struct RandomFeatureEntry {
|
||||
pub feature: PlacedFeatureWrapper,
|
||||
pub chance: f32,
|
||||
}
|
||||
|
||||
impl RandomFeature {
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
pub fn generate<T: GenerationCache>(
|
||||
&self,
|
||||
chunk: &mut T,
|
||||
block_registry: &dyn WorldPortalExt,
|
||||
min_y: i8,
|
||||
height: u16,
|
||||
feature_name: pumpkin_data::placed_feature::PlacedFeature, // This placed feature
|
||||
random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> bool {
|
||||
for feature in &self.features {
|
||||
if random.next_f32() >= feature.chance {
|
||||
continue;
|
||||
}
|
||||
return feature.feature.get().generate(
|
||||
chunk,
|
||||
block_registry,
|
||||
min_y,
|
||||
height,
|
||||
feature_name,
|
||||
random,
|
||||
pos,
|
||||
);
|
||||
}
|
||||
self.default.get().generate(
|
||||
chunk,
|
||||
block_registry,
|
||||
min_y,
|
||||
height,
|
||||
feature_name,
|
||||
random,
|
||||
pos,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
use pumpkin_data::Block;
|
||||
use pumpkin_util::{math::position::BlockPos, random::RandomGenerator};
|
||||
|
||||
use crate::generation::proto_chunk::GenerationCache;
|
||||
|
||||
pub struct ReplaceSingleBlockFeature;
|
||||
|
||||
impl ReplaceSingleBlockFeature {
|
||||
#[allow(clippy::unused_self)]
|
||||
pub fn generate<T: GenerationCache>(
|
||||
&self,
|
||||
chunk: &mut T,
|
||||
_min_y: i8,
|
||||
_height: u16,
|
||||
_feature: pumpkin_data::placed_feature::PlacedFeature,
|
||||
_random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> bool {
|
||||
chunk.set_block_state(&pos.0, Block::SAND.default_state);
|
||||
true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
use pumpkin_util::{
|
||||
math::position::BlockPos,
|
||||
random::{RandomGenerator, RandomImpl},
|
||||
};
|
||||
|
||||
use crate::generation::block_predicate::BlockPredicate;
|
||||
use crate::generation::block_state_provider::BlockStateProvider;
|
||||
use crate::generation::proto_chunk::GenerationCache;
|
||||
use crate::world::WorldPortalExt;
|
||||
|
||||
pub struct RootSystemFeature {
|
||||
pub feature: Box<crate::generation::feature::placed_features::PlacedFeature>,
|
||||
pub required_vertical_space_for_tree: i32,
|
||||
pub root_radius: i32,
|
||||
pub root_replaceable: BlockPredicate,
|
||||
pub root_state_provider: BlockStateProvider,
|
||||
pub root_placement_attempts: i32,
|
||||
pub root_column_max_height: i32,
|
||||
pub hanging_root_radius: i32,
|
||||
pub hanging_roots_vertical_span: i32,
|
||||
pub hanging_root_state_provider: BlockStateProvider,
|
||||
pub hanging_root_placement_attempts: i32,
|
||||
pub allowed_vertical_water_for_tree: i32,
|
||||
pub allowed_tree_position: BlockPredicate,
|
||||
}
|
||||
|
||||
impl RootSystemFeature {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn generate<T: GenerationCache>(
|
||||
&self,
|
||||
chunk: &mut T,
|
||||
block_registry: &dyn WorldPortalExt,
|
||||
min_y: i8,
|
||||
height: u16,
|
||||
feature_name: pumpkin_data::placed_feature::PlacedFeature,
|
||||
random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> bool {
|
||||
if !self.allowed_tree_position.test(block_registry, chunk, &pos) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if !self.can_place_tree(chunk, pos) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if !self.feature.generate(
|
||||
chunk,
|
||||
block_registry,
|
||||
min_y,
|
||||
height,
|
||||
feature_name,
|
||||
random,
|
||||
pos,
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
self.place_roots(chunk, block_registry, random, pos);
|
||||
true
|
||||
}
|
||||
|
||||
fn can_place_tree<T: GenerationCache>(&self, chunk: &T, pos: BlockPos) -> bool {
|
||||
let mut mutable_pos = pos;
|
||||
for i in 1..=self.required_vertical_space_for_tree {
|
||||
mutable_pos = mutable_pos.add(0, 1, 0);
|
||||
if !self.is_allowed_tree_space(chunk, mutable_pos, i) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn is_allowed_tree_space<T: GenerationCache>(
|
||||
&self,
|
||||
chunk: &T,
|
||||
pos: BlockPos,
|
||||
vertical_space: i32,
|
||||
) -> bool {
|
||||
if chunk.is_air(&pos.0) {
|
||||
return true;
|
||||
}
|
||||
// TODO: check for water.
|
||||
vertical_space <= self.allowed_vertical_water_for_tree
|
||||
}
|
||||
|
||||
fn place_roots<T: GenerationCache>(
|
||||
&self,
|
||||
chunk: &mut T,
|
||||
block_registry: &dyn WorldPortalExt,
|
||||
random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) {
|
||||
self.place_rooted_dirt(chunk, block_registry, random, pos);
|
||||
self.place_hanging_roots(chunk, block_registry, random, pos);
|
||||
}
|
||||
|
||||
fn place_rooted_dirt<T: GenerationCache>(
|
||||
&self,
|
||||
chunk: &mut T,
|
||||
block_registry: &dyn WorldPortalExt,
|
||||
random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) {
|
||||
for _ in 0..self.root_placement_attempts {
|
||||
let mut mutable_pos = pos.add(
|
||||
random.next_bounded_i32(self.root_radius.max(1))
|
||||
- random.next_bounded_i32(self.root_radius.max(1)),
|
||||
0,
|
||||
random.next_bounded_i32(self.root_radius.max(1))
|
||||
- random.next_bounded_i32(self.root_radius.max(1)),
|
||||
);
|
||||
|
||||
if self
|
||||
.root_replaceable
|
||||
.test(block_registry, chunk, &mutable_pos)
|
||||
{
|
||||
chunk.set_block_state(
|
||||
&mutable_pos.0,
|
||||
self.root_state_provider.get_with_context(
|
||||
block_registry,
|
||||
chunk,
|
||||
random,
|
||||
mutable_pos,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
for _ in 0..self.root_column_max_height {
|
||||
mutable_pos = mutable_pos.add(0, -1, 0);
|
||||
if chunk.out_of_height(mutable_pos.0.y as i16)
|
||||
|| !self
|
||||
.root_replaceable
|
||||
.test(block_registry, chunk, &mutable_pos)
|
||||
{
|
||||
break;
|
||||
}
|
||||
chunk.set_block_state(
|
||||
&mutable_pos.0,
|
||||
self.root_state_provider.get_with_context(
|
||||
block_registry,
|
||||
chunk,
|
||||
random,
|
||||
mutable_pos,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn place_hanging_roots<T: GenerationCache>(
|
||||
&self,
|
||||
chunk: &mut T,
|
||||
block_registry: &dyn WorldPortalExt,
|
||||
random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) {
|
||||
for _ in 0..self.hanging_root_placement_attempts {
|
||||
let mutable_pos = pos.add(
|
||||
random.next_bounded_i32(self.hanging_root_radius.max(1))
|
||||
- random.next_bounded_i32(self.hanging_root_radius.max(1)),
|
||||
random.next_bounded_i32(self.hanging_roots_vertical_span.max(1))
|
||||
- random.next_bounded_i32(self.hanging_roots_vertical_span.max(1)),
|
||||
random.next_bounded_i32(self.hanging_root_radius.max(1))
|
||||
- random.next_bounded_i32(self.hanging_root_radius.max(1)),
|
||||
);
|
||||
|
||||
if chunk.is_air(&mutable_pos.0) {
|
||||
let state = self.hanging_root_state_provider.get_with_context(
|
||||
block_registry,
|
||||
chunk,
|
||||
random,
|
||||
mutable_pos,
|
||||
);
|
||||
// In vanilla, it checks if it can survive and if the block above is sturdy.
|
||||
// For now, let's just check if the block above is NOT air.
|
||||
let above = mutable_pos.add(0, 1, 0);
|
||||
if !chunk.is_air(&above.0) {
|
||||
chunk.set_block_state(&mutable_pos.0, state);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
use pumpkin_util::{
|
||||
math::position::BlockPos,
|
||||
random::{RandomGenerator, RandomImpl},
|
||||
};
|
||||
|
||||
use crate::generation::proto_chunk::GenerationCache;
|
||||
use crate::world::WorldPortalExt;
|
||||
|
||||
use super::ore::{OreFeature, OreTarget};
|
||||
|
||||
pub struct ScatteredOreFeature {
|
||||
pub size: i32,
|
||||
pub discard_chance_on_air_exposure: f32,
|
||||
pub targets: Vec<OreTarget>,
|
||||
}
|
||||
|
||||
impl ScatteredOreFeature {
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
pub fn generate<T: GenerationCache>(
|
||||
&self,
|
||||
chunk: &mut T,
|
||||
_block_registry: &dyn WorldPortalExt,
|
||||
_min_y: i8,
|
||||
_height: u16,
|
||||
_feature: pumpkin_data::placed_feature::PlacedFeature,
|
||||
random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> bool {
|
||||
let count = random.next_bounded_i32(self.size + 1);
|
||||
let mut placed = false;
|
||||
|
||||
for _ in 0..count {
|
||||
let offset_x = self.get_random_offset(random);
|
||||
let offset_y = self.get_random_offset(random);
|
||||
let offset_z = self.get_random_offset(random);
|
||||
|
||||
let target_pos = pos.add(offset_x, offset_y, offset_z);
|
||||
|
||||
if chunk.out_of_height(target_pos.0.y as i16) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let block_state = GenerationCache::get_block_state(chunk, &target_pos.0);
|
||||
|
||||
for target in &self.targets {
|
||||
if OreFeature::should_place(
|
||||
self.discard_chance_on_air_exposure,
|
||||
chunk,
|
||||
block_state,
|
||||
random,
|
||||
target,
|
||||
&target_pos,
|
||||
) {
|
||||
chunk.set_block_state(&target_pos.0, target.state);
|
||||
placed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
placed
|
||||
}
|
||||
|
||||
fn get_random_offset(&self, random: &mut RandomGenerator) -> i32 {
|
||||
let f1 = random.next_f32();
|
||||
let f2 = random.next_f32();
|
||||
((f1 - f2) * self.size as f32).round() as i32
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,389 @@
|
||||
use pumpkin_data::BlockStateId;
|
||||
use pumpkin_data::tag::Block::MINECRAFT_SCULK_REPLACEABLE_WORLD_GEN;
|
||||
|
||||
use pumpkin_data::{
|
||||
Block, BlockId, BlockState,
|
||||
block_properties::{BlockProperties, GlowLichenLikeProperties, SculkShriekerLikeProperties},
|
||||
};
|
||||
|
||||
use pumpkin_util::{
|
||||
math::{int_provider::IntProvider, position::BlockPos, vector3::Vector3},
|
||||
random::{RandomGenerator, RandomImpl},
|
||||
};
|
||||
|
||||
use crate::generation::proto_chunk::GenerationCache;
|
||||
use crate::world::WorldPortalExt;
|
||||
|
||||
pub struct SculkPatchFeature {
|
||||
pub charge_count: i32,
|
||||
pub amount_per_charge: i32,
|
||||
pub spread_attempts: i32,
|
||||
pub growth_rounds: i32,
|
||||
pub spread_rounds: i32,
|
||||
pub extra_rare_growths: IntProvider,
|
||||
pub catalyst_chance: f32,
|
||||
}
|
||||
|
||||
impl SculkPatchFeature {
|
||||
pub fn generate<T: GenerationCache>(
|
||||
&self,
|
||||
_block_registry: &dyn WorldPortalExt,
|
||||
chunk: &mut T,
|
||||
random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> bool {
|
||||
if !Self::can_spread_from(chunk, pos) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let mut spreader = SculkSpreader::new();
|
||||
let total_rounds = self.spread_rounds + self.growth_rounds;
|
||||
|
||||
for round in 0..total_rounds {
|
||||
for _ in 0..self.charge_count {
|
||||
spreader.add_cursor(pos, self.amount_per_charge);
|
||||
}
|
||||
|
||||
let spread_veins = round < self.spread_rounds;
|
||||
|
||||
for _ in 0..self.spread_attempts {
|
||||
spreader.update_cursors(chunk, random, spread_veins);
|
||||
}
|
||||
|
||||
spreader.clear();
|
||||
}
|
||||
|
||||
let below = pos.down();
|
||||
if random.next_f32() <= self.catalyst_chance
|
||||
&& GenerationCache::get_block_state(chunk, &below.0)
|
||||
.to_state()
|
||||
.is_solid()
|
||||
{
|
||||
chunk.set_block_state(&pos.0, Block::SCULK_CATALYST.default_state);
|
||||
}
|
||||
|
||||
let extra_growths = self.extra_rare_growths.get(random);
|
||||
for _ in 0..extra_growths {
|
||||
let candidate = pos.offset(Vector3::new(
|
||||
random.next_bounded_i32(5) - 2,
|
||||
0,
|
||||
random.next_bounded_i32(5) - 2,
|
||||
));
|
||||
let state = GenerationCache::get_block_state(chunk, &candidate.0).to_state();
|
||||
let below_candidate = candidate.down();
|
||||
let below_state =
|
||||
GenerationCache::get_block_state(chunk, &below_candidate.0).to_state();
|
||||
|
||||
if state.is_air() && below_state.is_side_solid(pumpkin_data::BlockDirection::Up) {
|
||||
chunk.set_block_state(&candidate.0, ancient_city_shrieker_state());
|
||||
}
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
pub fn generate_in_proto_chunk(
|
||||
&self,
|
||||
chunk: &mut crate::ProtoChunk,
|
||||
random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> bool {
|
||||
if !can_spread_from_proto_chunk(chunk, pos) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let mut spreader = SculkSpreader::new();
|
||||
let total_rounds = self.spread_rounds + self.growth_rounds;
|
||||
for round in 0..total_rounds {
|
||||
for _ in 0..self.charge_count {
|
||||
spreader.add_cursor(pos, self.amount_per_charge);
|
||||
}
|
||||
for _ in 0..self.spread_attempts {
|
||||
spreader.update_cursors_in_proto_chunk(chunk, random, round < self.spread_rounds);
|
||||
}
|
||||
spreader.clear();
|
||||
}
|
||||
|
||||
let below = pos.down();
|
||||
if random.next_f32() <= self.catalyst_chance
|
||||
&& proto_chunk_state(chunk, below).is_some_and(|state| state.to_state().is_solid())
|
||||
{
|
||||
set_proto_chunk_state(chunk, pos, Block::SCULK_CATALYST.default_state);
|
||||
}
|
||||
|
||||
for _ in 0..self.extra_rare_growths.get(random) {
|
||||
let candidate = pos.offset(Vector3::new(
|
||||
random.next_bounded_i32(5) - 2,
|
||||
0,
|
||||
random.next_bounded_i32(5) - 2,
|
||||
));
|
||||
let below = candidate.down();
|
||||
if proto_chunk_state(chunk, candidate).is_some_and(|state| state.to_state().is_air())
|
||||
&& proto_chunk_state(chunk, below).is_some_and(|state| {
|
||||
state
|
||||
.to_state()
|
||||
.is_side_solid(pumpkin_data::BlockDirection::Up)
|
||||
})
|
||||
{
|
||||
set_proto_chunk_state(chunk, candidate, ancient_city_shrieker_state());
|
||||
}
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
fn can_spread_from<T: GenerationCache>(chunk: &T, pos: BlockPos) -> bool {
|
||||
let state = GenerationCache::get_block_state(chunk, &pos.0);
|
||||
let block_id = state.to_block_id();
|
||||
if is_sculk_behaviour(block_id) {
|
||||
true
|
||||
} else {
|
||||
if !chunk.is_air(&pos.0) && block_id != Block::WATER.id {
|
||||
return false;
|
||||
}
|
||||
// Check if any neighbor is solid
|
||||
for neighbor in [
|
||||
pos.offset(Vector3::new(1, 0, 0)),
|
||||
pos.offset(Vector3::new(-1, 0, 0)),
|
||||
pos.offset(Vector3::new(0, 1, 0)),
|
||||
pos.offset(Vector3::new(0, -1, 0)),
|
||||
pos.offset(Vector3::new(0, 0, 1)),
|
||||
pos.offset(Vector3::new(0, 0, -1)),
|
||||
] {
|
||||
if GenerationCache::get_block_state(chunk, &neighbor.0)
|
||||
.to_state()
|
||||
.is_solid()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const fn is_sculk_behaviour(id: BlockId) -> bool {
|
||||
matches!(
|
||||
id,
|
||||
BlockId::SCULK
|
||||
| BlockId::SCULK_VEIN
|
||||
| BlockId::SCULK_CATALYST
|
||||
| BlockId::SCULK_SHRIEKER
|
||||
| BlockId::SCULK_SENSOR
|
||||
| BlockId::CALIBRATED_SCULK_SENSOR
|
||||
)
|
||||
}
|
||||
|
||||
fn is_sculk_replaceable(id: BlockId) -> bool {
|
||||
id.has_tag(MINECRAFT_SCULK_REPLACEABLE_WORLD_GEN)
|
||||
}
|
||||
|
||||
fn ancient_city_shrieker_state() -> &'static BlockState {
|
||||
let mut properties = SculkShriekerLikeProperties::default(&Block::SCULK_SHRIEKER);
|
||||
properties.r#can_summon = true;
|
||||
BlockState::from_id(properties.to_state_id(&Block::SCULK_SHRIEKER))
|
||||
}
|
||||
|
||||
/// Resolves the sculk-vein block state to place at a position so that it clings to a sturdy
|
||||
/// neighbour on `face` (the direction from the vein position toward that neighbour). Existing
|
||||
/// sculk-vein states are merged; replaceable/air/water blocks become a fresh vein.
|
||||
fn sculk_vein_state_with_face(
|
||||
existing: BlockStateId,
|
||||
face: pumpkin_data::BlockDirection,
|
||||
) -> Option<&'static BlockState> {
|
||||
let existing_block_id = existing.to_block_id();
|
||||
let is_vein = existing_block_id == BlockId::SCULK_VEIN;
|
||||
if !(is_vein || is_sculk_replaceable(existing_block_id) || existing_block_id == Block::WATER.id)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut properties = if is_vein {
|
||||
GlowLichenLikeProperties::from_state_id(existing, &Block::SCULK_VEIN)
|
||||
} else {
|
||||
let mut properties = GlowLichenLikeProperties::default(&Block::SCULK_VEIN);
|
||||
properties.r#waterlogged = existing_block_id == BlockId::WATER;
|
||||
properties
|
||||
};
|
||||
|
||||
match face {
|
||||
pumpkin_data::BlockDirection::Down => properties.r#down = true,
|
||||
pumpkin_data::BlockDirection::Up => properties.r#up = true,
|
||||
pumpkin_data::BlockDirection::North => properties.r#north = true,
|
||||
pumpkin_data::BlockDirection::South => properties.r#south = true,
|
||||
pumpkin_data::BlockDirection::West => properties.r#west = true,
|
||||
pumpkin_data::BlockDirection::East => properties.r#east = true,
|
||||
}
|
||||
|
||||
Some(BlockState::from_id(
|
||||
properties.to_state_id(&Block::SCULK_VEIN),
|
||||
))
|
||||
}
|
||||
|
||||
struct Cursor {
|
||||
pos: BlockPos,
|
||||
charge: i32,
|
||||
}
|
||||
|
||||
struct SculkSpreader {
|
||||
cursors: Vec<Cursor>,
|
||||
}
|
||||
|
||||
impl SculkSpreader {
|
||||
const fn new() -> Self {
|
||||
Self {
|
||||
cursors: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn add_cursor(&mut self, pos: BlockPos, charge: i32) {
|
||||
self.cursors.push(Cursor { pos, charge });
|
||||
}
|
||||
|
||||
fn clear(&mut self) {
|
||||
self.cursors.clear();
|
||||
}
|
||||
|
||||
fn update_cursors<T: GenerationCache>(
|
||||
&mut self,
|
||||
chunk: &mut T,
|
||||
random: &mut RandomGenerator,
|
||||
spread_veins: bool,
|
||||
) {
|
||||
let mut next_cursors = Vec::new();
|
||||
for mut cursor in self.cursors.drain(..) {
|
||||
if cursor.charge <= 0 {
|
||||
continue;
|
||||
}
|
||||
|
||||
// In world gen, it picks one of 26 neighbors
|
||||
let dx = random.next_bounded_i32(3) - 1;
|
||||
let dy = random.next_bounded_i32(3) - 1;
|
||||
let dz = random.next_bounded_i32(3) - 1;
|
||||
let target_pos = cursor.pos.offset(Vector3::new(dx, dy, dz));
|
||||
|
||||
let target_state = GenerationCache::get_block_state(chunk, &target_pos.0);
|
||||
let target_block_id = target_state.to_block_id();
|
||||
|
||||
if is_sculk_replaceable(target_block_id) {
|
||||
chunk.set_block_state(&target_pos.0, Block::SCULK.default_state);
|
||||
if spread_veins {
|
||||
grow_sculk_veins(chunk, target_pos);
|
||||
}
|
||||
cursor.pos = target_pos;
|
||||
cursor.charge -= 1;
|
||||
} else if target_block_id == Block::SCULK.id {
|
||||
cursor.pos = target_pos;
|
||||
cursor.charge -= 1;
|
||||
}
|
||||
|
||||
if cursor.charge > 0 {
|
||||
next_cursors.push(cursor);
|
||||
}
|
||||
}
|
||||
self.cursors = next_cursors;
|
||||
}
|
||||
|
||||
fn update_cursors_in_proto_chunk(
|
||||
&mut self,
|
||||
chunk: &mut crate::ProtoChunk,
|
||||
random: &mut RandomGenerator,
|
||||
spread_veins: bool,
|
||||
) {
|
||||
let mut next_cursors = Vec::new();
|
||||
for mut cursor in self.cursors.drain(..) {
|
||||
if cursor.charge <= 0 {
|
||||
continue;
|
||||
}
|
||||
|
||||
let target_pos = cursor.pos.offset(Vector3::new(
|
||||
random.next_bounded_i32(3) - 1,
|
||||
random.next_bounded_i32(3) - 1,
|
||||
random.next_bounded_i32(3) - 1,
|
||||
));
|
||||
let Some(target_state) = proto_chunk_state(chunk, target_pos) else {
|
||||
continue;
|
||||
};
|
||||
let target_block_id = target_state.to_block_id();
|
||||
if is_sculk_replaceable(target_block_id) {
|
||||
set_proto_chunk_state(chunk, target_pos, Block::SCULK.default_state);
|
||||
if spread_veins {
|
||||
grow_sculk_veins_in_proto_chunk(chunk, target_pos);
|
||||
}
|
||||
cursor.pos = target_pos;
|
||||
cursor.charge -= 1;
|
||||
} else if target_block_id == BlockId::SCULK {
|
||||
cursor.pos = target_pos;
|
||||
cursor.charge -= 1;
|
||||
}
|
||||
|
||||
if cursor.charge > 0 {
|
||||
next_cursors.push(cursor);
|
||||
}
|
||||
}
|
||||
self.cursors = next_cursors;
|
||||
}
|
||||
}
|
||||
|
||||
fn proto_chunk_state(chunk: &crate::ProtoChunk, pos: BlockPos) -> Option<BlockStateId> {
|
||||
((pos.0.x >> 4) == chunk.x && (pos.0.z >> 4) == chunk.z).then(|| chunk.get_block_state(&pos.0))
|
||||
}
|
||||
|
||||
fn set_proto_chunk_state(
|
||||
chunk: &mut crate::ProtoChunk,
|
||||
pos: BlockPos,
|
||||
state: &'static pumpkin_data::BlockState,
|
||||
) {
|
||||
if (pos.0.x >> 4) == chunk.x && (pos.0.z >> 4) == chunk.z {
|
||||
chunk.set_block_state(pos.0.x, pos.0.y, pos.0.z, state);
|
||||
}
|
||||
}
|
||||
|
||||
fn grow_sculk_veins<T: GenerationCache>(chunk: &mut T, sculk_pos: BlockPos) {
|
||||
for dir in pumpkin_data::BlockDirection::all() {
|
||||
let vein_pos = sculk_pos.offset(dir.to_offset());
|
||||
let existing = GenerationCache::get_block_state(chunk, &vein_pos.0);
|
||||
if let Some(state) = sculk_vein_state_with_face(existing, dir.opposite()) {
|
||||
chunk.set_block_state(&vein_pos.0, state);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn grow_sculk_veins_in_proto_chunk(chunk: &mut crate::ProtoChunk, sculk_pos: BlockPos) {
|
||||
for dir in pumpkin_data::BlockDirection::all() {
|
||||
let vein_pos = sculk_pos.offset(dir.to_offset());
|
||||
let Some(existing) = proto_chunk_state(chunk, vein_pos) else {
|
||||
continue;
|
||||
};
|
||||
if let Some(state) = sculk_vein_state_with_face(existing, dir.opposite()) {
|
||||
set_proto_chunk_state(chunk, vein_pos, state);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn can_spread_from_proto_chunk(chunk: &crate::ProtoChunk, pos: BlockPos) -> bool {
|
||||
let Some(state) = proto_chunk_state(chunk, pos) else {
|
||||
return false;
|
||||
};
|
||||
let block_id = state.to_block_id();
|
||||
if is_sculk_behaviour(block_id) {
|
||||
return true;
|
||||
}
|
||||
if !state.to_state().is_air() && block_id != Block::WATER.id {
|
||||
return false;
|
||||
}
|
||||
|
||||
[
|
||||
Vector3::new(1, 0, 0),
|
||||
Vector3::new(-1, 0, 0),
|
||||
Vector3::new(0, 1, 0),
|
||||
Vector3::new(0, -1, 0),
|
||||
Vector3::new(0, 0, 1),
|
||||
Vector3::new(0, 0, -1),
|
||||
]
|
||||
.into_iter()
|
||||
.any(|offset| {
|
||||
proto_chunk_state(chunk, pos.offset(offset))
|
||||
.is_some_and(|state| state.to_state().is_solid())
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
use crate::generation::proto_chunk::GenerationCache;
|
||||
use pumpkin_data::{
|
||||
Block, BlockState,
|
||||
block_properties::{BlockProperties, SeaPickleLikeProperties},
|
||||
};
|
||||
use pumpkin_util::{
|
||||
math::{int_provider::IntProvider, position::BlockPos},
|
||||
random::{RandomGenerator, RandomImpl},
|
||||
};
|
||||
|
||||
pub struct SeaPickleFeature {
|
||||
pub count: IntProvider,
|
||||
}
|
||||
|
||||
impl SeaPickleFeature {
|
||||
pub fn generate<T: GenerationCache>(
|
||||
&self,
|
||||
chunk: &mut T,
|
||||
_min_y: i8,
|
||||
_height: u16,
|
||||
_feature: pumpkin_data::placed_feature::PlacedFeature, // This placed feature
|
||||
random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> bool {
|
||||
let mut times = 0;
|
||||
let count = self.count.get(random);
|
||||
for _ in 0..count {
|
||||
let x = random.next_bounded_i32(8) - random.next_bounded_i32(8);
|
||||
let z = random.next_bounded_i32(8) - random.next_bounded_i32(8);
|
||||
let y = chunk.ocean_floor_height_exclusive(pos.0.x + x, pos.0.z + z);
|
||||
if GenerationCache::get_block_state(chunk, &pos.0).to_block_id() != Block::WATER {
|
||||
continue;
|
||||
}
|
||||
let mut props = SeaPickleLikeProperties::default(&Block::SEA_PICKLE);
|
||||
props.pickles = (random.next_bounded_i32(4) as u8) + 1;
|
||||
let pos = BlockPos::new(pos.0.x + x, y, pos.0.z + z);
|
||||
chunk.set_block_state(
|
||||
&pos.0,
|
||||
BlockState::from_id(props.to_state_id(&Block::SEA_PICKLE)),
|
||||
);
|
||||
times += 1;
|
||||
}
|
||||
times > 0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
use crate::generation::proto_chunk::GenerationCache;
|
||||
use pumpkin_data::{
|
||||
Block, BlockState,
|
||||
block_properties::{BlockProperties, DoubleBlockHalf, TallSeagrassLikeProperties},
|
||||
};
|
||||
use pumpkin_util::{
|
||||
math::position::BlockPos,
|
||||
random::{RandomGenerator, RandomImpl},
|
||||
};
|
||||
|
||||
pub struct SeagrassFeature {
|
||||
pub probability: f32,
|
||||
}
|
||||
|
||||
impl SeagrassFeature {
|
||||
pub fn generate<T: GenerationCache>(
|
||||
&self,
|
||||
chunk: &mut T,
|
||||
_min_y: i8,
|
||||
_height: u16,
|
||||
_feature: pumpkin_data::placed_feature::PlacedFeature, // This placed feature
|
||||
random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> bool {
|
||||
let x = random.next_bounded_i32(8) - random.next_bounded_i32(8);
|
||||
let z = random.next_bounded_i32(8) - random.next_bounded_i32(8);
|
||||
let y = chunk.ocean_floor_height_exclusive(pos.0.x + x, pos.0.z + z);
|
||||
let top_pos = BlockPos::new(pos.0.x + x, y, pos.0.z + z);
|
||||
if GenerationCache::get_block_state(chunk, &top_pos.0).to_block_id() == Block::WATER {
|
||||
let tall = random.next_f64() < self.probability as f64;
|
||||
if tall {
|
||||
let tall_pos = top_pos.up();
|
||||
if GenerationCache::get_block_state(chunk, &tall_pos.0).to_block_id()
|
||||
== Block::WATER
|
||||
{
|
||||
let mut props = TallSeagrassLikeProperties::default(&Block::TALL_SEAGRASS);
|
||||
props.half = DoubleBlockHalf::Upper;
|
||||
chunk.set_block_state(&top_pos.0, Block::TALL_SEAGRASS.default_state);
|
||||
chunk.set_block_state(
|
||||
&tall_pos.0,
|
||||
BlockState::from_id(props.to_state_id(&Block::TALL_SEAGRASS)),
|
||||
);
|
||||
}
|
||||
} else {
|
||||
chunk.set_block_state(&top_pos.0, Block::SEAGRASS.default_state);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
use pumpkin_data::Block;
|
||||
use pumpkin_util::{math::position::BlockPos, random::RandomGenerator};
|
||||
|
||||
use crate::generation::proto_chunk::GenerationCache;
|
||||
use crate::{
|
||||
generation::block_state_provider::BlockStateProvider,
|
||||
world::{BlockAccessor, WorldPortalExt},
|
||||
};
|
||||
|
||||
pub struct SimpleBlockFeature {
|
||||
pub to_place: BlockStateProvider,
|
||||
pub schedule_tick: Option<bool>,
|
||||
}
|
||||
|
||||
impl SimpleBlockFeature {
|
||||
pub fn generate<T: GenerationCache>(
|
||||
&self,
|
||||
block_registry: &dyn WorldPortalExt,
|
||||
chunk: &mut T,
|
||||
random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> bool {
|
||||
let state = self.to_place.get(random, pos, chunk, block_registry);
|
||||
let block = Block::from_state_id(state.id);
|
||||
let block_accessor: &dyn BlockAccessor = chunk;
|
||||
if !block_registry.can_place_at(block, state, block_accessor, &pos) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// TODO: check things..
|
||||
chunk.set_block_state(&pos.0, state);
|
||||
// TODO: schedule tick when needed
|
||||
true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
use pumpkin_util::{
|
||||
math::position::BlockPos,
|
||||
random::{RandomGenerator, RandomImpl},
|
||||
};
|
||||
|
||||
use crate::generation::proto_chunk::GenerationCache;
|
||||
use crate::{generation::feature::placed_features::PlacedFeature, world::WorldPortalExt};
|
||||
|
||||
pub struct SimpleRandomFeature {
|
||||
pub features: Vec<PlacedFeature>,
|
||||
}
|
||||
|
||||
impl SimpleRandomFeature {
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
pub fn generate<T: GenerationCache>(
|
||||
&self,
|
||||
chunk: &mut T,
|
||||
block_registry: &dyn WorldPortalExt,
|
||||
min_y: i8,
|
||||
height: u16,
|
||||
feature_name: pumpkin_data::placed_feature::PlacedFeature, // This placed feature
|
||||
random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> bool {
|
||||
let i = random.next_bounded_i32(self.features.len() as i32);
|
||||
let feature = &self.features[i as usize];
|
||||
feature.generate(
|
||||
chunk,
|
||||
block_registry,
|
||||
min_y,
|
||||
height,
|
||||
feature_name,
|
||||
random,
|
||||
pos,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
use pumpkin_data::{BlockDirection, BlockState};
|
||||
use pumpkin_util::{math::position::BlockPos, random::RandomGenerator};
|
||||
|
||||
use crate::generation::proto_chunk::GenerationCache;
|
||||
use crate::world::WorldPortalExt;
|
||||
|
||||
pub struct SpringFeatureFeature {
|
||||
pub state: &'static BlockState,
|
||||
pub requires_block_below: bool,
|
||||
pub rock_count: i32,
|
||||
pub hole_count: i32,
|
||||
pub valid_blocks: BlockWrapper,
|
||||
}
|
||||
|
||||
pub enum BlockWrapper {
|
||||
Single(String),
|
||||
Multi(Vec<String>),
|
||||
}
|
||||
|
||||
impl BlockWrapper {
|
||||
fn contains(&self, name: &str) -> bool {
|
||||
match self {
|
||||
Self::Single(s) => s == name,
|
||||
Self::Multi(h) => h.iter().any(|s| s == name),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl SpringFeatureFeature {
|
||||
pub fn generate<T: GenerationCache>(
|
||||
&self,
|
||||
_block_registry: &dyn WorldPortalExt,
|
||||
chunk: &mut T,
|
||||
_random: &mut RandomGenerator,
|
||||
pos: BlockPos,
|
||||
) -> bool {
|
||||
let valid_blocks = &self.valid_blocks;
|
||||
|
||||
if !valid_blocks.contains(
|
||||
GenerationCache::get_block_state(chunk, &pos.up().0)
|
||||
.to_block()
|
||||
.name,
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
if self.requires_block_below
|
||||
&& !valid_blocks.contains(
|
||||
GenerationCache::get_block_state(
|
||||
chunk,
|
||||
&pos.offset(BlockDirection::Down.to_offset()).0,
|
||||
)
|
||||
.to_block()
|
||||
.name,
|
||||
)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let state = GenerationCache::get_block_state(chunk, &pos.0);
|
||||
if !state.to_state().is_air() && !valid_blocks.contains(state.to_block().name) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let mut valid = 0;
|
||||
if valid_blocks.contains(
|
||||
GenerationCache::get_block_state(
|
||||
chunk,
|
||||
&pos.offset(BlockDirection::West.to_offset()).0,
|
||||
)
|
||||
.to_block()
|
||||
.name,
|
||||
) {
|
||||
valid += 1;
|
||||
}
|
||||
if valid_blocks.contains(
|
||||
GenerationCache::get_block_state(
|
||||
chunk,
|
||||
&pos.offset(BlockDirection::East.to_offset()).0,
|
||||
)
|
||||
.to_block()
|
||||
.name,
|
||||
) {
|
||||
valid += 1;
|
||||
}
|
||||
if valid_blocks.contains(
|
||||
GenerationCache::get_block_state(
|
||||
chunk,
|
||||
&pos.offset(BlockDirection::North.to_offset()).0,
|
||||
)
|
||||
.to_block()
|
||||
.name,
|
||||
) {
|
||||
valid += 1;
|
||||
}
|
||||
if valid_blocks.contains(
|
||||
GenerationCache::get_block_state(
|
||||
chunk,
|
||||
&pos.offset(BlockDirection::South.to_offset()).0,
|
||||
)
|
||||
.to_block()
|
||||
.name,
|
||||
) {
|
||||
valid += 1;
|
||||
}
|
||||
if valid_blocks.contains(
|
||||
GenerationCache::get_block_state(
|
||||
chunk,
|
||||
&pos.offset(BlockDirection::Down.to_offset()).0,
|
||||
)
|
||||
.to_block()
|
||||
.name,
|
||||
) {
|
||||
valid += 1;
|
||||
}
|
||||
let mut air = 0;
|
||||
if chunk.is_air(&pos.offset(BlockDirection::West.to_offset()).0) {
|
||||
air += 1;
|
||||
}
|
||||
if chunk.is_air(&pos.offset(BlockDirection::East.to_offset()).0) {
|
||||
air += 1;
|
||||
}
|
||||
if chunk.is_air(&pos.offset(BlockDirection::North.to_offset()).0) {
|
||||
air += 1;
|
||||
}
|
||||
if chunk.is_air(&pos.offset(BlockDirection::South.to_offset()).0) {
|
||||
air += 1;
|
||||
}
|
||||
if chunk.is_air(&pos.offset(BlockDirection::Down.to_offset()).0) {
|
||||
air += 1;
|
||||
}
|
||||
if valid == self.rock_count && air == self.hole_count {
|
||||
chunk.set_block_state(&pos.0, self.state);
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
pub struct AlterGroundTreeDecorator;
|
||||
+1
@@ -0,0 +1 @@
|
||||
pub struct AttachedToLeavesTreeDecorator;
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
use pumpkin_data::BlockDirection;
|
||||
use pumpkin_util::{
|
||||
math::position::BlockPos,
|
||||
random::{RandomGenerator, RandomImpl},
|
||||
};
|
||||
|
||||
use crate::generation::proto_chunk::GenerationCache;
|
||||
use crate::{generation::block_state_provider::BlockStateProvider, world::WorldPortalExt};
|
||||
|
||||
pub struct AttachedToLogsTreeDecorator {
|
||||
pub probability: f32,
|
||||
pub block_provider: BlockStateProvider,
|
||||
pub directions: Vec<BlockDirection>,
|
||||
}
|
||||
|
||||
impl AttachedToLogsTreeDecorator {
|
||||
pub fn generate<T: GenerationCache>(
|
||||
&self,
|
||||
chunk: &mut T,
|
||||
block_registry: &dyn WorldPortalExt,
|
||||
random: &mut RandomGenerator,
|
||||
log_positions: &[BlockPos],
|
||||
) {
|
||||
// TODO: shuffle
|
||||
for pos in log_positions {
|
||||
// TODO: random
|
||||
let pos = pos.offset(self.directions[0].to_offset());
|
||||
if random.next_f32() > self.probability
|
||||
|| !GenerationCache::get_block_state(chunk, &pos.0)
|
||||
.to_state()
|
||||
.is_air()
|
||||
{
|
||||
continue;
|
||||
}
|
||||
chunk.set_block_state(
|
||||
&pos.0,
|
||||
self.block_provider.get(random, pos, chunk, block_registry),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
pub struct BeehiveTreeDecorator {
|
||||
pub probability: f32,
|
||||
}
|
||||
Loaded 100 of 3393 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user