Build distant terrain from sparse seed samples and layered voxel columns
This commit is contained in:
@@ -180,6 +180,8 @@ pub struct FogInputs<'a> {
|
||||
pub water_fog_color: [f32; 3],
|
||||
pub biome: u16,
|
||||
pub render_distance_chunks: i32,
|
||||
/// Extend ordinary Overworld atmosphere for terrain beyond vanilla's range.
|
||||
pub distant_terrain: bool,
|
||||
/// The Cloud Distance option, in chunks.
|
||||
pub cloud_range_chunks: i32,
|
||||
pub camera_y: f64,
|
||||
@@ -336,6 +338,18 @@ pub fn setup_fog(tables: &FogTables, state: &FogState, input: &FogInputs) -> Fog
|
||||
let span = (rd / 10.0).clamp(4.0, 64.0);
|
||||
fog.render_distance_start = rd - span;
|
||||
fog.render_distance_end = rd;
|
||||
if input.distant_terrain
|
||||
&& input.skybox
|
||||
&& input.fog_type == FogType::Atmospheric
|
||||
&& input.blindness.is_none()
|
||||
&& input.darkness.is_none()
|
||||
&& !input.boss_world_fog
|
||||
&& sky.fog_end >= 1024.0
|
||||
{
|
||||
let scale = (rd / 1024.0).max(1.0);
|
||||
fog.environmental_start *= scale;
|
||||
fog.environmental_end *= scale;
|
||||
}
|
||||
fog
|
||||
}
|
||||
/// `AtmosphericFogEnvironment.updateRainFogState`.
|
||||
@@ -368,6 +382,7 @@ mod tests {
|
||||
water_fog_color: [0.0, 0.0, 0.2],
|
||||
biome: 0,
|
||||
render_distance_chunks: 12,
|
||||
distant_terrain: false,
|
||||
cloud_range_chunks: 128,
|
||||
camera_y: 70.0,
|
||||
min_y: -64,
|
||||
@@ -446,6 +461,38 @@ mod tests {
|
||||
assert_eq!(fog.sky_end, 192.0);
|
||||
}
|
||||
#[test]
|
||||
fn distant_atmosphere_extends_without_extending_environmental_overrides() {
|
||||
let sky = Sky {
|
||||
fog_end: 1024.,
|
||||
..Sky::default()
|
||||
};
|
||||
let tables = FogTables {
|
||||
water_fog_end: vec![1.],
|
||||
};
|
||||
let mut input = inputs(&sky);
|
||||
input.render_distance_chunks = 1024;
|
||||
input.distant_terrain = true;
|
||||
let fog = setup_fog(&tables, &FogState::default(), &input);
|
||||
assert_eq!(fog.environmental_end, 16384.);
|
||||
input.fog_type = FogType::Water;
|
||||
assert_eq!(
|
||||
setup_fog(&tables, &FogState::default(), &input).environmental_end,
|
||||
24.
|
||||
);
|
||||
input.fog_type = FogType::Atmospheric;
|
||||
input.darkness = Some(1.);
|
||||
assert_eq!(
|
||||
setup_fog(&tables, &FogState::default(), &input).environmental_end,
|
||||
15.
|
||||
);
|
||||
input.darkness = None;
|
||||
input.boss_world_fog = true;
|
||||
assert_eq!(
|
||||
setup_fog(&tables, &FogState::default(), &input).environmental_end,
|
||||
96.
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn cloud_fog_ends_at_the_cloud_distance() {
|
||||
let sky = Sky {
|
||||
fog_end: 1024.0,
|
||||
|
||||
@@ -6446,6 +6446,7 @@ impl Game<'_> {
|
||||
self.screen = Screen::Playing;
|
||||
self.title = None;
|
||||
self.clear_lod();
|
||||
self.pending_uploads.clear();
|
||||
if let Some(r) = self.renderer.as_mut() {
|
||||
r.clear_sections();
|
||||
}
|
||||
@@ -6596,6 +6597,7 @@ impl Game<'_> {
|
||||
self.orbs.clear();
|
||||
self.mining = None;
|
||||
self.clear_lod();
|
||||
self.pending_uploads.clear();
|
||||
if let Some(r) = self.renderer.as_mut() {
|
||||
r.clear_sections();
|
||||
}
|
||||
@@ -6775,6 +6777,7 @@ impl Game<'_> {
|
||||
self.clear_entities();
|
||||
self.screen = Screen::Playing;
|
||||
self.clear_lod();
|
||||
self.pending_uploads.clear();
|
||||
if let Some(r) = self.renderer.as_mut() {
|
||||
r.clear_sections();
|
||||
}
|
||||
@@ -8738,7 +8741,13 @@ impl Game<'_> {
|
||||
fog: Some({
|
||||
let mut fog = self.frame_fog(camera, &sky, biome);
|
||||
// Horizon's fog setting: no distance fog (fluids keep theirs).
|
||||
if !self.settings.horizon.fog && !underwater && fog.environmental_end >= distance {
|
||||
if !self.settings.horizon.fog
|
||||
&& !underwater
|
||||
&& self.darkness_fog().is_none()
|
||||
&& !self.dragon_bar_shown()
|
||||
&& self.potions.effects.get("blindness").is_none()
|
||||
&& fog.environmental_end >= (self.streaming.radius * 16) as f32
|
||||
{
|
||||
(fog.render_distance_start, fog.render_distance_end) = (1e9, 2e9);
|
||||
(fog.environmental_start, fog.environmental_end) = (1e9, 2e9);
|
||||
}
|
||||
@@ -9112,9 +9121,9 @@ impl Game<'_> {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Only surface LOD worlds extend the renderer's range, never simulation.
|
||||
/// Only enabled LOD worlds extend the renderer's range, never simulation.
|
||||
fn terrain_distance(&self) -> i32 {
|
||||
if self.lod.is_some() && self.dim != Dim::Nether {
|
||||
if self.lod.is_some() {
|
||||
self.streaming
|
||||
.radius
|
||||
.max(self.settings.horizon.lod_distance.min(1024) as i32)
|
||||
@@ -9132,7 +9141,6 @@ impl Game<'_> {
|
||||
}
|
||||
fn prepare_lod(&mut self) {
|
||||
let enabled = self.settings.horizon.lod_distance > 0
|
||||
&& self.dim != Dim::Nether
|
||||
&& self.renderer.is_some()
|
||||
&& self.player.is_some()
|
||||
&& self.title.is_none()
|
||||
@@ -9181,14 +9189,16 @@ impl Game<'_> {
|
||||
self.lod_observe
|
||||
.extend(uploads.iter().map(|(key, _)| (key.0, key.2)));
|
||||
for chunk in &unloaded {
|
||||
lod.observe(chunk, &self.res.facts);
|
||||
horizon_client::spans::time("lod_observe", || lod.observe(chunk, &self.res.facts));
|
||||
self.lod_observe.remove(&(chunk.x, chunk.z));
|
||||
}
|
||||
let observe: Vec<_> = self.lod_observe.iter().copied().take(2).collect();
|
||||
for key in observe {
|
||||
self.lod_observe.remove(&key);
|
||||
if let Some(chunk) = self.world.chunks.get(&key) {
|
||||
lod.observe(chunk, &self.res.facts);
|
||||
horizon_client::spans::time("lod_observe", || {
|
||||
lod.observe(chunk, &self.res.facts)
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9219,39 +9229,37 @@ impl Game<'_> {
|
||||
}
|
||||
if let Some(renderer) = self.renderer.as_mut() {
|
||||
let g = &self.settings.horizon;
|
||||
let budgeted = g.chunk_updates > 0 || g.upload_budget_kib > 0;
|
||||
if !budgeted && self.pending_uploads.is_empty() {
|
||||
horizon_client::spans::time("upload", || {
|
||||
for (key, mesh) in uploads {
|
||||
renderer.upload(key, &mesh);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
// Even unlimited count/byte settings must yield during a join's
|
||||
// upload burst; draining it all blocked input/rendering for seconds.
|
||||
horizon_client::spans::time("upload", || {
|
||||
// Horizon's chunk-update and upload budgets: the nearest
|
||||
// sections go first, the rest wait for later frames; a newer
|
||||
// mesh of a waiting section replaces it.
|
||||
let pending = &mut self.pending_uploads;
|
||||
let fresh: horizon_client::fast_hash::FxHashSet<(i32, i32, i32)> =
|
||||
uploads.iter().map(|(k, _)| *k).collect();
|
||||
let gone: horizon_client::fast_hash::FxHashSet<(i32, i32)> =
|
||||
unloaded.iter().map(|c| (c.x, c.z)).collect();
|
||||
pending.retain(|(k, _)| !fresh.contains(k) && !gone.contains(&(k.0, k.2)));
|
||||
pending.extend(uploads);
|
||||
let chunks = &self.world.chunks;
|
||||
pending.retain(|(k, _)| !fresh.contains(k) && chunks.contains_key(&(k.0, k.2)));
|
||||
pending.extend(
|
||||
uploads
|
||||
.into_iter()
|
||||
.filter(|(k, _)| chunks.contains_key(&(k.0, k.2))),
|
||||
);
|
||||
let centre = self.streaming.center;
|
||||
let far = |k: &(i32, i32, i32)| (k.0 - centre.0).pow(2) + (k.2 - centre.1).pow(2);
|
||||
pending.sort_unstable_by_key(|(k, _)| std::cmp::Reverse(far(k)));
|
||||
let (limit, budget) = if budgeted {
|
||||
(
|
||||
g.chunk_updates as usize,
|
||||
u64::from(g.upload_budget_kib) * 1024,
|
||||
)
|
||||
} else {
|
||||
(0, 0)
|
||||
};
|
||||
let (limit, budget) = (
|
||||
g.chunk_updates as usize,
|
||||
u64::from(g.upload_budget_kib) * 1024,
|
||||
);
|
||||
let (mut count, mut bytes) = (0, 0u64);
|
||||
let upload_started = Instant::now();
|
||||
while let Some((_, mesh)) = pending.last() {
|
||||
let size = ((mesh.solid.len() + mesh.translucent.len()) * 32) as u64;
|
||||
if (limit > 0 && count >= limit)
|
||||
let size = ((mesh.solid.len() + mesh.translucent.len())
|
||||
* std::mem::size_of::<horizon_client::mesher::TerrainVertex>())
|
||||
as u64;
|
||||
if (count > 0 && upload_started.elapsed() >= Duration::from_millis(4))
|
||||
|| (limit > 0 && count >= limit)
|
||||
|| (budget > 0 && bytes > 0 && bytes + size > budget)
|
||||
{
|
||||
break;
|
||||
@@ -9261,7 +9269,7 @@ impl Game<'_> {
|
||||
count += 1;
|
||||
bytes += size;
|
||||
}
|
||||
}
|
||||
});
|
||||
for c in unloaded {
|
||||
for sy in 0..(HEIGHT / 16) {
|
||||
renderer.remove((c.x, sy, c.z));
|
||||
@@ -9279,13 +9287,16 @@ impl Game<'_> {
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
for (key, mesh) in lod.update(
|
||||
[player.position.x, player.position.y, player.position.z],
|
||||
self.streaming.radius,
|
||||
self.settings.horizon.lod_distance,
|
||||
covered,
|
||||
) {
|
||||
renderer.upload_lod(key, &mesh);
|
||||
for (key, mesh) in horizon_client::spans::time("lod_update", || {
|
||||
lod.update(
|
||||
[player.position.x, player.position.y, player.position.z],
|
||||
self.yaw,
|
||||
self.streaming.radius,
|
||||
self.settings.horizon.lod_distance,
|
||||
covered,
|
||||
)
|
||||
}) {
|
||||
horizon_client::spans::time("lod_upload", || renderer.upload_lod(key, &mesh));
|
||||
}
|
||||
for key in lod.removed() {
|
||||
renderer.remove_lod(key);
|
||||
|
||||
@@ -717,6 +717,7 @@ impl Game<'_> {
|
||||
"active_tiles": self.lod.as_ref().map_or(0, |lod| lod.stats().0),
|
||||
"cached_tiles": self.lod.as_ref().map_or(0, |lod| lod.stats().1),
|
||||
"pending_observations": self.lod_observe.len(),
|
||||
"refined_samples": self.lod.as_ref().map_or(0, |lod| lod.refined_samples()),
|
||||
});
|
||||
let mut status = json!({
|
||||
"screen": self.screen_name(),
|
||||
@@ -777,6 +778,10 @@ impl Game<'_> {
|
||||
.map(|e| self.shown_name_tags(glam::DVec3::from_array(e))),
|
||||
});
|
||||
status["lod"] = lod;
|
||||
let (target, sampled) = self.lod.as_ref().map_or((0, 0), |lod| lod.progress());
|
||||
status["lod"]["target_tiles"] = target.into();
|
||||
status["lod"]["sampled_target_tiles"] = sampled.into();
|
||||
status["pending_uploads"] = self.pending_uploads.len().into();
|
||||
status["physical_keys"] = json!(physical_keys);
|
||||
status
|
||||
}
|
||||
|
||||
@@ -260,6 +260,7 @@ impl Game<'_> {
|
||||
self.title = None;
|
||||
self.dim = Dim::Overworld;
|
||||
self.clear_lod();
|
||||
self.pending_uploads.clear();
|
||||
if let Some(r) = self.renderer.as_mut() {
|
||||
r.clear_sections();
|
||||
}
|
||||
@@ -365,6 +366,7 @@ impl Game<'_> {
|
||||
self.screen = Screen::Playing;
|
||||
self.container = None;
|
||||
self.clear_lod();
|
||||
self.pending_uploads.clear();
|
||||
if let Some(r) = self.renderer.as_mut() {
|
||||
r.clear_sections();
|
||||
}
|
||||
@@ -613,6 +615,7 @@ impl Game<'_> {
|
||||
r.chunk_center = (0, 0);
|
||||
}
|
||||
self.clear_lod();
|
||||
self.pending_uploads.clear();
|
||||
if let Some(renderer) = self.renderer.as_mut() {
|
||||
renderer.clear_sections();
|
||||
}
|
||||
|
||||
@@ -86,6 +86,7 @@ impl Game<'_> {
|
||||
],
|
||||
biome,
|
||||
render_distance_chunks: self.terrain_distance(),
|
||||
distant_terrain: self.lod.is_some(),
|
||||
cloud_range_chunks: self.settings.cloud_range,
|
||||
camera_y: camera.y,
|
||||
// level.getMinY(): the Nether and the End start at y 0.
|
||||
|
||||
+1238
-384
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -2783,44 +2783,110 @@ pub struct Persistent<G> {
|
||||
pub registry: Arc<crate::assets::Assets>,
|
||||
pub biomes: Arc<Biomes>,
|
||||
}
|
||||
type LodSurfaces = [Option<crate::lod::Surface>; 16];
|
||||
type LodSurfaces = Arc<[crate::lod::Column; 256]>;
|
||||
struct SavedLodSampler<G: ChunkGenerator> {
|
||||
generator: Arc<Persistent<G>>,
|
||||
inner: Box<dyn crate::streaming::LodSampler>,
|
||||
cache: std::collections::VecDeque<((i32, i32), Option<LodSurfaces>)>,
|
||||
details: Vec<crate::streaming::LodDetail>,
|
||||
}
|
||||
impl<G: ChunkGenerator> crate::streaming::LodSampler for SavedLodSampler<G> {
|
||||
fn sample(&mut self, x: i32, z: i32) -> Option<crate::lod::Surface> {
|
||||
let key = (x >> 4, z >> 4);
|
||||
impl<G: ChunkGenerator> SavedLodSampler<G> {
|
||||
fn saved_columns(&mut self, key: (i32, i32)) -> Option<LodSurfaces> {
|
||||
let cached = match self.cache.iter().position(|(at, _)| *at == key) {
|
||||
Some(index) => self.cache.remove(index).unwrap(),
|
||||
None => {
|
||||
let surfaces = self.generator.save.lod_surfaces(
|
||||
None => (
|
||||
key,
|
||||
self.generator.save.lod_surfaces(
|
||||
key.0,
|
||||
key.1,
|
||||
&self.generator.registry,
|
||||
&self.generator.biomes,
|
||||
);
|
||||
(key, surfaces)
|
||||
}
|
||||
),
|
||||
),
|
||||
};
|
||||
let surfaces = cached.1;
|
||||
let columns = cached.1.clone();
|
||||
self.cache.push_front(cached);
|
||||
self.cache.truncate(128);
|
||||
match surfaces {
|
||||
Some(surfaces) => surfaces[((z & 15) / 4 * 4 + (x & 15) / 4) as usize],
|
||||
None => self.inner.sample(x, z),
|
||||
columns
|
||||
}
|
||||
}
|
||||
impl<G: ChunkGenerator> crate::streaming::LodSampler for SavedLodSampler<G> {
|
||||
fn fork(&self) -> Option<Box<dyn crate::streaming::LodSampler>> {
|
||||
Some(Box::new(Self {
|
||||
generator: self.generator.clone(),
|
||||
inner: self.inner.fork()?,
|
||||
cache: Default::default(),
|
||||
details: Vec::new(),
|
||||
}))
|
||||
}
|
||||
fn request_detail(&mut self, chunks: &[(i32, i32)], center: [i32; 2]) {
|
||||
let mut missing = Vec::new();
|
||||
for &key in chunks {
|
||||
if let Some(columns) = self.saved_columns(key) {
|
||||
self.details.push((key, columns));
|
||||
} else {
|
||||
missing.push(key);
|
||||
}
|
||||
}
|
||||
self.inner.request_detail(&missing, center);
|
||||
}
|
||||
fn drain_details(&mut self) -> Vec<crate::streaming::LodDetail> {
|
||||
let mut details = std::mem::take(&mut self.details);
|
||||
for (key, generated) in self.inner.drain_details() {
|
||||
// A generation batch also returns neighbouring, unrequested chunks.
|
||||
// Their saved builds must take precedence too.
|
||||
details.push((key, self.saved_columns(key).unwrap_or(generated)));
|
||||
}
|
||||
details
|
||||
}
|
||||
fn grid(&mut self, x: i32, z: i32, stride: i32, side: usize) -> Vec<crate::lod::Column> {
|
||||
let mut columns = self.inner.grid(x, z, stride, side);
|
||||
if stride <= 16 {
|
||||
for (index, column) in columns.iter_mut().enumerate() {
|
||||
let (wx, wz) = (
|
||||
x + (index % side) as i32 * stride,
|
||||
z + (index / side) as i32 * stride,
|
||||
);
|
||||
if let Some(saved) = self.saved_columns((wx >> 4, wz >> 4)) {
|
||||
*column = crate::lod::Column::reduced(
|
||||
&saved,
|
||||
(wx & 15) as usize,
|
||||
(wz & 15) as usize,
|
||||
stride as usize,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
columns
|
||||
}
|
||||
fn sample(&mut self, x: i32, z: i32) -> Option<crate::lod::Surface> {
|
||||
self.column(x, z).surface
|
||||
}
|
||||
fn column(&mut self, x: i32, z: i32) -> crate::lod::Column {
|
||||
self.reduced_column(x, z, 1)
|
||||
}
|
||||
fn reduced_column(&mut self, x: i32, z: i32, width: i32) -> crate::lod::Column {
|
||||
if width <= 16
|
||||
&& let Some(columns) = self.saved_columns((x >> 4, z >> 4))
|
||||
{
|
||||
return crate::lod::Column::reduced(
|
||||
&columns,
|
||||
(x & 15) as usize,
|
||||
(z & 15) as usize,
|
||||
width as usize,
|
||||
);
|
||||
}
|
||||
self.inner.reduced_column(x, z, width)
|
||||
}
|
||||
}
|
||||
|
||||
/// Read one palette entry without expanding the other entries in the section.
|
||||
fn lod_palette_entry(
|
||||
/// Read one palette index without expanding the other entries in the section.
|
||||
fn lod_palette_index(
|
||||
container: &Tag,
|
||||
index: usize,
|
||||
entries: usize,
|
||||
minimum_bits: u32,
|
||||
) -> Option<&Tag> {
|
||||
) -> Option<usize> {
|
||||
let Tag::List(palette) = container.get("palette")? else {
|
||||
return None;
|
||||
};
|
||||
@@ -2828,7 +2894,7 @@ fn lod_palette_entry(
|
||||
return None;
|
||||
}
|
||||
if palette.len() == 1 {
|
||||
return palette.first();
|
||||
return Some(0);
|
||||
}
|
||||
let bits = (usize::BITS - (palette.len() - 1).leading_zeros()).max(minimum_bits);
|
||||
let per_word = 64 / bits as usize;
|
||||
@@ -2840,12 +2906,61 @@ fn lod_palette_entry(
|
||||
}
|
||||
let value = ((data[index / per_word] as u64 >> ((index % per_word) * bits as usize))
|
||||
& ((1 << bits) - 1)) as usize;
|
||||
palette.get(value)
|
||||
(value < palette.len()).then_some(value)
|
||||
}
|
||||
fn lod_light_layers(sections: &[(i32, &Tag)], sky_light: bool) -> Box<[u8]> {
|
||||
let mut layers = [(None, None); SECTIONS];
|
||||
for &(y, section) in sections {
|
||||
let layer = |name: &str| match section.get(name) {
|
||||
Some(Tag::ByteArray(data)) if data.len() == 2048 => Some(&data[..]),
|
||||
_ => None,
|
||||
};
|
||||
layers[(y - (MIN_Y >> 4)) as usize] = (
|
||||
if sky_light { layer("SkyLight") } else { None },
|
||||
layer("BlockLight"),
|
||||
);
|
||||
}
|
||||
let mut light = vec![0u8; SECTIONS * 4096].into_boxed_slice();
|
||||
let mut above = [if sky_light { 15u8 } else { 0 }; 256];
|
||||
let nibble = |data: &[u8], index: usize| (data[index / 2] >> ((index & 1) * 4)) & 15;
|
||||
for si in (0..SECTIONS).rev() {
|
||||
let (sky, block) = layers[si];
|
||||
let section = &mut light[si * 4096..(si + 1) * 4096];
|
||||
for (index, value) in section.iter_mut().enumerate() {
|
||||
*value = sky.map_or(above[index & 255], |data| nibble(data, index)) << 4
|
||||
| block.map_or(0, |data| nibble(data, index));
|
||||
}
|
||||
// Missing sky layers inherit the bottom layer above, as load_light does.
|
||||
for (index, value) in above.iter_mut().enumerate() {
|
||||
*value = section[index] >> 4;
|
||||
}
|
||||
}
|
||||
light
|
||||
}
|
||||
fn lod_face_light(light: &[u8], x: usize, y: usize, z: usize) -> u16 {
|
||||
let index = y * 256 + z * 16 + x;
|
||||
let mut sky = light[index] >> 4;
|
||||
let mut block = light[index] & 15;
|
||||
for (valid, index) in [
|
||||
(x > 0, index.wrapping_sub(1)),
|
||||
(x < 15, index + 1),
|
||||
(z > 0, index.wrapping_sub(16)),
|
||||
(z < 15, index + 16),
|
||||
(y > 0, index.wrapping_sub(256)),
|
||||
(y + 1 < SECTIONS * 16, index + 256),
|
||||
] {
|
||||
if valid {
|
||||
sky = sky.max(light[index] >> 4);
|
||||
block = block.max(light[index] & 15);
|
||||
}
|
||||
}
|
||||
u16::from(sky) << 4 | u16::from(block) << 12
|
||||
}
|
||||
fn decode_lod_surfaces(
|
||||
root: &NamedTag,
|
||||
assets: &crate::assets::Assets,
|
||||
biomes: &Biomes,
|
||||
sky_light: bool,
|
||||
) -> Option<LodSurfaces> {
|
||||
let Tag::List(sections) = root.tag.get("sections")? else {
|
||||
return None;
|
||||
@@ -2860,21 +2975,23 @@ fn decode_lod_surfaces(
|
||||
})
|
||||
.collect();
|
||||
sections.sort_unstable_by_key(|(y, _)| std::cmp::Reverse(*y));
|
||||
let mut surfaces = [None; 16];
|
||||
let mut water = [None; 16];
|
||||
let mut columns: Box<[crate::lod::Column; 256]> =
|
||||
Box::new(std::array::from_fn(|_| crate::lod::Column {
|
||||
surface: None,
|
||||
spans: Vec::new(),
|
||||
}));
|
||||
let mut water = [None; 256];
|
||||
let light = lod_light_layers(§ions, sky_light);
|
||||
let mut states = BTreeMap::new();
|
||||
for (section_y, section) in sections {
|
||||
let Some(blocks) = section.get("block_states") else {
|
||||
continue;
|
||||
};
|
||||
for z in (0..16).step_by(4) {
|
||||
for x in (0..16).step_by(4) {
|
||||
let cell = z / 4 * 4 + x / 4;
|
||||
if surfaces[cell].is_some() {
|
||||
continue;
|
||||
}
|
||||
for y in (0..16).rev() {
|
||||
let entry = lod_palette_entry(blocks, y * 256 + z * 16 + x, 4096, 4)?;
|
||||
if let Some(blocks) = section.get("block_states") {
|
||||
let Tag::List(palette) = blocks.get("palette")? else {
|
||||
return None;
|
||||
};
|
||||
// Resolve each state once per palette, rather than parsing NBT for every block.
|
||||
let palette: Vec<_> = palette
|
||||
.iter()
|
||||
.map(|entry| {
|
||||
let descriptor = BlockState::from_nbt(entry).ok()?;
|
||||
let state = *states.entry(descriptor.clone()).or_insert_with(|| {
|
||||
assets
|
||||
@@ -2882,47 +2999,97 @@ fn decode_lod_surfaces(
|
||||
.id(&descriptor)
|
||||
.or_else(|| assets.registry.default_state(&descriptor.name))
|
||||
});
|
||||
let Some(state) = state else {
|
||||
continue;
|
||||
};
|
||||
let properties = assets.properties.heightmap_state(state);
|
||||
if properties.is_air() {
|
||||
continue;
|
||||
Some(state.map(|state| {
|
||||
let properties = assets.properties.heightmap_state(state);
|
||||
let fluid = matches!(
|
||||
descriptor.name.as_str(),
|
||||
"minecraft:water" | "minecraft:lava"
|
||||
);
|
||||
(state, fluid, properties.blocks_motion_in_heightmap())
|
||||
}))
|
||||
})
|
||||
.collect::<Option<_>>()?;
|
||||
let biome_palette: Vec<_> = section
|
||||
.get("biomes")
|
||||
.and_then(|container| match container.get("palette")? {
|
||||
Tag::List(palette) => Some(palette),
|
||||
_ => None,
|
||||
})
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|entry| match entry {
|
||||
Tag::String(name) => biomes.id(&name.to_string_lossy()),
|
||||
_ => 0,
|
||||
})
|
||||
.collect();
|
||||
for z in 0..16 {
|
||||
for x in 0..16 {
|
||||
let cell = z * 16 + x;
|
||||
let column = &mut columns[cell];
|
||||
for y in (0..16).rev() {
|
||||
let index = y * 256 + cell;
|
||||
let palette_index = lod_palette_index(blocks, index, 4096, 4)?;
|
||||
let Some((state, fluid, solid)) = palette[palette_index] else {
|
||||
continue;
|
||||
};
|
||||
if !solid && !fluid {
|
||||
continue;
|
||||
}
|
||||
let biome = section
|
||||
.get("biomes")
|
||||
.and_then(|container| {
|
||||
lod_palette_index(
|
||||
container,
|
||||
(y / 4) * 16 + (z / 4) * 4 + x / 4,
|
||||
64,
|
||||
1,
|
||||
)
|
||||
})
|
||||
.and_then(|index| biome_palette.get(index))
|
||||
.copied()
|
||||
.unwrap_or(0);
|
||||
let height = section_y * 16 + y as i32 + 1;
|
||||
if column.surface.is_none() {
|
||||
if fluid {
|
||||
water[cell].get_or_insert((height, state));
|
||||
} else {
|
||||
column.surface = Some(crate::lod::Surface {
|
||||
height,
|
||||
state,
|
||||
water: water[cell],
|
||||
biome,
|
||||
});
|
||||
}
|
||||
}
|
||||
let light = lod_face_light(&light, x, (height - 1 - MIN_Y) as usize, z);
|
||||
let min = (height - 1) as i16;
|
||||
let max = height as i16;
|
||||
if let Some(previous) = column.spans.last_mut()
|
||||
&& previous.min == max
|
||||
&& (previous.state, previous.biome, previous.light)
|
||||
== (state, biome, light)
|
||||
{
|
||||
previous.min = min;
|
||||
} else {
|
||||
column.spans.push(crate::lod::Span {
|
||||
min,
|
||||
max,
|
||||
state,
|
||||
biome,
|
||||
light,
|
||||
});
|
||||
}
|
||||
}
|
||||
let height = section_y * 16 + y as i32 + 1;
|
||||
if matches!(
|
||||
descriptor.name.as_str(),
|
||||
"minecraft:water" | "minecraft:lava"
|
||||
) {
|
||||
water[cell].get_or_insert((height, state));
|
||||
continue;
|
||||
}
|
||||
if !properties.blocks_motion_in_heightmap() {
|
||||
continue;
|
||||
}
|
||||
let biome = section
|
||||
.get("biomes")
|
||||
.and_then(|container| {
|
||||
lod_palette_entry(container, (y / 4) * 16 + (z / 4) * 4 + x / 4, 64, 1)
|
||||
})
|
||||
.and_then(|tag| match tag {
|
||||
Tag::String(name) => Some(biomes.id(&name.to_string_lossy())),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or(0);
|
||||
surfaces[cell] = Some(crate::lod::Surface {
|
||||
height,
|
||||
state,
|
||||
water: water[cell],
|
||||
biome,
|
||||
});
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(surfaces)
|
||||
for column in &mut *columns {
|
||||
column.spans.reverse();
|
||||
}
|
||||
Some(Arc::from(columns))
|
||||
}
|
||||
|
||||
impl SaveDir {
|
||||
fn lod_surfaces(
|
||||
&self,
|
||||
@@ -2948,7 +3115,13 @@ impl SaveDir {
|
||||
.nbt(Limits::default())
|
||||
.ok()?
|
||||
};
|
||||
decode_lod_surfaces(&root, assets, biomes)
|
||||
// Proto saves may still be missing decoration from their neighbors.
|
||||
if text(root.tag.get("Status"))
|
||||
.is_some_and(|status| status != "minecraft:full" && status != "full")
|
||||
{
|
||||
return None;
|
||||
}
|
||||
decode_lod_surfaces(&root, assets, biomes, self.sky_light)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2963,6 +3136,7 @@ impl<G: ChunkGenerator> ChunkGenerator for Persistent<G> {
|
||||
generator: self,
|
||||
inner,
|
||||
cache: Default::default(),
|
||||
details: Vec::new(),
|
||||
})
|
||||
}
|
||||
fn load(&self, x: i32, z: i32) -> Option<Chunk> {
|
||||
@@ -3049,8 +3223,33 @@ mod tests {
|
||||
let stone = assets.registry.default_state("minecraft:stone").unwrap();
|
||||
let water = assets.registry.default_state("minecraft:water").unwrap();
|
||||
let sand = assets.registry.default_state("minecraft:sand").unwrap();
|
||||
let dirt = assets.registry.default_state("minecraft:dirt").unwrap();
|
||||
let leaves = assets
|
||||
.registry
|
||||
.default_state("minecraft:oak_leaves")
|
||||
.unwrap();
|
||||
let mut chunk = Chunk::empty(-2, 3);
|
||||
chunk.set(0, 109, 0, stone.0);
|
||||
chunk.set(3, 121, 5, stone.0);
|
||||
chunk.set(3, 122, 5, stone.0);
|
||||
chunk.set(3, 120, 5, dirt.0);
|
||||
chunk.set(3, 119, 5, dirt.0);
|
||||
chunk.set(3, 115, 5, stone.0);
|
||||
chunk.set(11, 125, 11, stone.0);
|
||||
chunk.set(14, 127, 14, stone.0);
|
||||
chunk.set(14, 112, 14, stone.0);
|
||||
for y in 95..98 {
|
||||
chunk.set(2, y, 6, stone.0);
|
||||
}
|
||||
chunk.lit = true;
|
||||
let mut cave_light = Box::new([0x03; 4096]);
|
||||
cave_light[crate::chunk::index(12, 125, 11)] = 0xa7;
|
||||
Arc::make_mut(&mut chunk.sections[((121 - MIN_Y) >> 4) as usize]).light =
|
||||
Light::Full(cave_light);
|
||||
chunk.set(7, 90, 9, sand.0);
|
||||
chunk.set(7, 98, 9, leaves.0);
|
||||
let forest = biomes.id("minecraft:forest");
|
||||
chunk.set_biome_cell(7 / 4, (98 - MIN_Y) / 4, 9 / 4, forest);
|
||||
chunk.set(4, 54, 4, sand.0);
|
||||
for y in 55..64 {
|
||||
chunk.set(4, y, 4, water.0);
|
||||
@@ -3070,20 +3269,152 @@ mod tests {
|
||||
let surfaces = reopened
|
||||
.lod_surfaces(-2, 3, &assets, &biomes)
|
||||
.expect("saved summary");
|
||||
assert_eq!(surfaces[0].unwrap().height, 110);
|
||||
assert_eq!(surfaces[0].unwrap().state, stone);
|
||||
let underwater = surfaces[5].unwrap();
|
||||
assert_eq!(surfaces[0].surface.unwrap().height, 110);
|
||||
assert_eq!(surfaces[0].surface.unwrap().state, stone);
|
||||
let narrow_build = surfaces[5 * 16 + 3].surface.unwrap();
|
||||
assert_eq!((narrow_build.height, narrow_build.state), (123, stone));
|
||||
assert!(
|
||||
surfaces[5 * 16 + 2].surface.is_none(),
|
||||
"adjacent columns stay distinct"
|
||||
);
|
||||
let strata = &surfaces[5 * 16 + 3].spans;
|
||||
assert_eq!(
|
||||
strata
|
||||
.iter()
|
||||
.map(|span| (span.min, span.max, span.state))
|
||||
.collect::<Vec<_>>(),
|
||||
vec![(115, 116, stone), (119, 121, dirt), (121, 123, stone)]
|
||||
);
|
||||
assert!(
|
||||
strata.iter().all(|span| span.light == 0x3000),
|
||||
"saved cave darkness and block light survive"
|
||||
);
|
||||
assert_eq!(
|
||||
surfaces[11 * 16 + 11].spans[0].light,
|
||||
0x70a0,
|
||||
"neighbor face light uses separate sky/block channels"
|
||||
);
|
||||
let boundaries = &surfaces[14 * 16 + 14].spans;
|
||||
assert_eq!(boundaries.len(), 2);
|
||||
assert!(
|
||||
boundaries.iter().all(|span| span.light == 0x30f0),
|
||||
"face light crosses section boundaries above and below"
|
||||
);
|
||||
let across_sections = &surfaces[6 * 16 + 2].spans;
|
||||
assert_eq!(across_sections.len(), 1);
|
||||
assert_eq!((across_sections[0].min, across_sections[0].max), (95, 98));
|
||||
let canopy = surfaces[9 * 16 + 7].surface.unwrap();
|
||||
assert_eq!(
|
||||
(canopy.height, canopy.state, canopy.biome),
|
||||
(99, leaves, forest)
|
||||
);
|
||||
let underwater = surfaces[4 * 16 + 4].surface.unwrap();
|
||||
assert_eq!((underwater.height, underwater.state), (55, sand));
|
||||
assert_eq!(underwater.water, Some((64, water)));
|
||||
assert!(surfaces[15].is_none(), "saved void stays empty");
|
||||
assert!(surfaces[15].surface.is_none(), "saved void stays empty");
|
||||
assert!(
|
||||
reopened.regions.lock().unwrap().is_empty(),
|
||||
"far reads do not grow gameplay region cache"
|
||||
);
|
||||
drop((save, reopened));
|
||||
let mut proto = encode(&chunk, assets.registry, &biomes);
|
||||
put(
|
||||
&mut proto.tag,
|
||||
"Status",
|
||||
string(ChunkStatus::Terrain.name()),
|
||||
);
|
||||
put(&mut proto.tag, "xPos", Tag::Int(-3));
|
||||
save.write_records("region", vec![((-3, 3), Some(proto))], true)
|
||||
.unwrap();
|
||||
assert!(
|
||||
reopened.lod_surfaces(-3, 3, &assets, &biomes).is_none(),
|
||||
"unfinished proto saves must not suppress complete decoration"
|
||||
);
|
||||
let mut nether = SaveDir::new(dir.clone());
|
||||
nether.sky_light = false;
|
||||
let dark = nether.lod_surfaces(-2, 3, &assets, &biomes).unwrap();
|
||||
assert!(
|
||||
dark.iter()
|
||||
.flat_map(|c| &c.spans)
|
||||
.all(|s| s.light & 0xf0 == 0),
|
||||
"no invented skylight in Nether saves"
|
||||
);
|
||||
struct SavedOnly(Vec<crate::streaming::LodDetail>);
|
||||
impl crate::streaming::LodSampler for SavedOnly {
|
||||
fn sample(&mut self, _: i32, _: i32) -> Option<crate::lod::Surface> {
|
||||
panic!("saved data must win")
|
||||
}
|
||||
fn request_detail(&mut self, chunks: &[(i32, i32)], _: [i32; 2]) {
|
||||
assert!(
|
||||
chunks.is_empty(),
|
||||
"saved builds must not request speculative generation"
|
||||
);
|
||||
}
|
||||
fn drain_details(&mut self) -> Vec<crate::streaming::LodDetail> {
|
||||
std::mem::take(&mut self.0)
|
||||
}
|
||||
}
|
||||
let inner = Arc::new(crate::testgen::TestTerrain::new(assets.registry, &biomes).unwrap());
|
||||
let generator = Arc::new(Persistent {
|
||||
inner,
|
||||
save: Arc::new(reopened),
|
||||
registry: Arc::new(assets),
|
||||
biomes: Arc::new(biomes),
|
||||
});
|
||||
let mut sampler = SavedLodSampler {
|
||||
generator,
|
||||
inner: Box::new(SavedOnly(Vec::new())),
|
||||
cache: Default::default(),
|
||||
details: Vec::new(),
|
||||
};
|
||||
use crate::streaming::LodSampler;
|
||||
sampler.request_detail(&[(-2, 3)], [-32, 48]);
|
||||
let details = sampler.drain_details();
|
||||
assert_eq!(details.len(), 1);
|
||||
assert_eq!(&details[0].1[..], &surfaces[..]);
|
||||
sampler.cache.clear();
|
||||
let generated: LodSurfaces =
|
||||
Arc::new(std::array::from_fn(|_| crate::lod::Column::default()));
|
||||
sampler.inner = Box::new(SavedOnly(vec![
|
||||
((-2, 3), generated.clone()),
|
||||
((-9, 9), generated.clone()),
|
||||
]));
|
||||
let details = sampler.drain_details();
|
||||
assert_eq!(
|
||||
&details[0].1[..],
|
||||
&surfaces[..],
|
||||
"unrequested batch neighbours must preserve saved builds"
|
||||
);
|
||||
assert!(Arc::ptr_eq(&details[1].1, &generated));
|
||||
sampler.inner =
|
||||
crate::streaming::ChunkGenerator::lod_sampler(sampler.generator.inner.clone());
|
||||
let grid = sampler.grid(-32, 48, 2, 16);
|
||||
for z in 0..8 {
|
||||
for x in 0..8 {
|
||||
assert_eq!(
|
||||
grid[z * 16 + x],
|
||||
crate::lod::Column::reduced(&surfaces, x * 2, z * 2, 2),
|
||||
"saved builds must override a batched direct grid"
|
||||
);
|
||||
}
|
||||
}
|
||||
drop((save, sampler, nether));
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saved_far_surface_rejects_invalid_packed_palettes() {
|
||||
let mut states = Tag::compound([
|
||||
("palette", Tag::List(vec![Tag::Byte(0), Tag::Byte(1)])),
|
||||
("data", Tag::LongArray(vec![0; 256])),
|
||||
]);
|
||||
assert_eq!(lod_palette_index(&states, 4095, 4096, 4), Some(0));
|
||||
assert_eq!(lod_palette_index(&states, 4096, 4096, 4), None);
|
||||
put(&mut states, "data", Tag::LongArray(vec![15; 256]));
|
||||
assert_eq!(lod_palette_index(&states, 0, 4096, 4), None);
|
||||
put(&mut states, "data", Tag::LongArray(vec![0; 255]));
|
||||
assert_eq!(lod_palette_index(&states, 0, 4096, 4), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_batch_preserves_order_coordinates_and_ownership() {
|
||||
use crate::containers::BlockEntity;
|
||||
|
||||
@@ -82,9 +82,38 @@ pub trait ChunkGenerator: Send + Sync + 'static {
|
||||
/// neighbours' decoration is done, so it can't be generated again.
|
||||
fn save_finished(&self, _chunk: Chunk) {}
|
||||
}
|
||||
pub type LodDetail = ((i32, i32), Arc<[crate::lod::Column; 256]>);
|
||||
|
||||
/// Independent, thread-owned far-terrain sampling state.
|
||||
pub trait LodSampler: Send {
|
||||
/// Independent sampling state; native detail generation stays with the owner.
|
||||
fn fork(&self) -> Option<Box<dyn LodSampler>> {
|
||||
None
|
||||
}
|
||||
fn request_detail(&mut self, _chunks: &[(i32, i32)], _center: [i32; 2]) {}
|
||||
fn drain_details(&mut self) -> Vec<LodDetail> {
|
||||
Vec::new()
|
||||
}
|
||||
fn sample(&mut self, x: i32, z: i32) -> Option<crate::lod::Surface>;
|
||||
fn column(&mut self, x: i32, z: i32) -> crate::lod::Column {
|
||||
crate::lod::Column::from_surface(self.sample(x, z))
|
||||
}
|
||||
fn reduced_column(&mut self, x: i32, z: i32, _width: i32) -> crate::lod::Column {
|
||||
self.column(x, z)
|
||||
}
|
||||
fn grid(&mut self, x: i32, z: i32, stride: i32, side: usize) -> Vec<crate::lod::Column> {
|
||||
let mut columns = Vec::with_capacity(side * side);
|
||||
for dz in 0..side {
|
||||
for dx in 0..side {
|
||||
columns.push(self.reduced_column(
|
||||
x + dx as i32 * stride,
|
||||
z + dz as i32 * stride,
|
||||
stride,
|
||||
));
|
||||
}
|
||||
}
|
||||
columns
|
||||
}
|
||||
}
|
||||
pub trait LodSource: Send + Sync {
|
||||
fn sampler(self: Arc<Self>) -> Box<dyn LodSampler>;
|
||||
|
||||
@@ -4,7 +4,7 @@ use crate::{
|
||||
biome::Biomes,
|
||||
chunk::{BIOME_STRATEGY, Chunk, HEIGHT, MIN_Y, SECTIONS, Section},
|
||||
save::SavedProto,
|
||||
streaming::{ChunkGenerator, Proto},
|
||||
streaming::{ChunkGenerator, LodSampler, Proto},
|
||||
};
|
||||
use horizon_core::{
|
||||
paletted::PalettedContainer,
|
||||
@@ -16,11 +16,15 @@ use horizon_world::{
|
||||
nbt::Tag,
|
||||
registry::BlockRegistry,
|
||||
worldgen::{
|
||||
generator::{GeneratorData, GeneratorWorker, OverworldGenerator, ProtoChunk},
|
||||
generator::{
|
||||
GeneratorData, GeneratorWorker, OverworldGenerator, ProtoChunk, SurfaceSample,
|
||||
},
|
||||
terrain::PreLightChunkStage,
|
||||
},
|
||||
};
|
||||
use std::{path::Path, sync::Arc};
|
||||
mod lod;
|
||||
use lod::VanillaLodSampler;
|
||||
|
||||
pub struct VanillaTerrain {
|
||||
generator: OverworldGenerator,
|
||||
@@ -35,7 +39,8 @@ pub struct VanillaTerrain {
|
||||
tick_blocks: Vec<u32>,
|
||||
/// Block index -> default state id: `tick_blocks` the other way.
|
||||
tick_states: Vec<u32>,
|
||||
lod_supported: bool,
|
||||
seed: i64,
|
||||
dimension: String,
|
||||
}
|
||||
/// A proto chunk, or the position of one whose generation failed.
|
||||
enum VanillaProto {
|
||||
@@ -43,6 +48,18 @@ enum VanillaProto {
|
||||
Failed(i32, i32),
|
||||
}
|
||||
impl VanillaTerrain {
|
||||
fn client_surface(&self, surface: SurfaceSample) -> crate::lod::Surface {
|
||||
crate::lod::Surface {
|
||||
height: surface.height,
|
||||
state: surface.state,
|
||||
water: surface.water,
|
||||
biome: self
|
||||
.biome_map
|
||||
.get(surface.biome.0 as usize)
|
||||
.copied()
|
||||
.unwrap_or(0),
|
||||
}
|
||||
}
|
||||
pub fn new(
|
||||
dir: &Path,
|
||||
registry: &'static BlockRegistry,
|
||||
@@ -107,7 +124,8 @@ impl VanillaTerrain {
|
||||
query: std::sync::Mutex::new(None),
|
||||
tick_blocks,
|
||||
tick_states,
|
||||
lod_supported: dimension != "minecraft:the_nether",
|
||||
seed,
|
||||
dimension: dimension.to_owned(),
|
||||
})
|
||||
}
|
||||
/// A proto chunk's blocks, biomes, scheduled ticks and post-processing
|
||||
@@ -267,26 +285,16 @@ impl ChunkGenerator for VanillaTerrain {
|
||||
fn worker(&self) -> GeneratorWorker {
|
||||
self.generator.worker()
|
||||
}
|
||||
fn lod_sampler(self: Arc<Self>) -> Box<dyn LodSampler> {
|
||||
Box::new(VanillaLodSampler::new(self))
|
||||
}
|
||||
fn lod_surface(
|
||||
&self,
|
||||
worker: &mut GeneratorWorker,
|
||||
x: i32,
|
||||
z: i32,
|
||||
) -> Option<crate::lod::Surface> {
|
||||
if !self.lod_supported {
|
||||
return None;
|
||||
}
|
||||
let surface = worker.surface_sample(x, z)?;
|
||||
Some(crate::lod::Surface {
|
||||
height: surface.height,
|
||||
state: surface.state,
|
||||
water: surface.water,
|
||||
biome: self
|
||||
.biome_map
|
||||
.get(surface.biome.0 as usize)
|
||||
.copied()
|
||||
.unwrap_or(0),
|
||||
})
|
||||
Some(self.client_surface(worker.surface_sample(x, z)?))
|
||||
}
|
||||
/// The structure starts a saved chunk references, as vanilla reads them
|
||||
/// with the chunk: built here, on the loading worker, into the
|
||||
|
||||
@@ -0,0 +1,700 @@
|
||||
//! Speculative decoration is isolated from gameplay and never writes normal saves.
|
||||
use super::*;
|
||||
use crate::{
|
||||
fast_hash::{FxHashMap, FxHashSet},
|
||||
lod::{Column, Span, Surface},
|
||||
streaming::LodDetail,
|
||||
};
|
||||
use horizon_world::{
|
||||
heightmap::HeightmapState,
|
||||
registry::BlockStateId,
|
||||
worldgen::{decoration_order::vanilla_order, generator::GeneratorError},
|
||||
};
|
||||
use std::{
|
||||
collections::VecDeque,
|
||||
sync::{
|
||||
Condvar, Mutex,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
mpsc,
|
||||
},
|
||||
thread,
|
||||
};
|
||||
|
||||
mod vegetation;
|
||||
use vegetation::Vegetation;
|
||||
const CACHE: usize = 1024;
|
||||
const REQUESTS: usize = 64;
|
||||
const BATCH: i32 = 4;
|
||||
fn batch_origin((x, z): (i32, i32)) -> (i32, i32) {
|
||||
(x.div_euclid(BATCH) * BATCH, z.div_euclid(BATCH) * BATCH)
|
||||
}
|
||||
#[derive(Default)]
|
||||
struct Requests {
|
||||
chunks: FxHashSet<(i32, i32)>,
|
||||
center: [i32; 2],
|
||||
current: Option<(i32, i32)>,
|
||||
finished: FxHashSet<(i32, i32)>,
|
||||
}
|
||||
struct Shared {
|
||||
requests: Mutex<Requests>,
|
||||
wake: Condvar,
|
||||
stop: AtomicBool,
|
||||
}
|
||||
fn distance((x, z): (i32, i32), center: [i32; 2]) -> i64 {
|
||||
let dx = i64::from(x * 16 + 8 - center[0]);
|
||||
let dz = i64::from(z * 16 + 8 - center[1]);
|
||||
dx * dx + dz * dz
|
||||
}
|
||||
struct Builder {
|
||||
shared: Arc<Shared>,
|
||||
results: mpsc::Receiver<LodDetail>,
|
||||
thread: Option<thread::JoinHandle<()>>,
|
||||
}
|
||||
impl Builder {
|
||||
fn new(terrain: Arc<VanillaTerrain>) -> Self {
|
||||
let shared = Arc::new(Shared {
|
||||
requests: Mutex::new(Requests::default()),
|
||||
wake: Condvar::new(),
|
||||
stop: AtomicBool::new(false),
|
||||
});
|
||||
let worker = shared.clone();
|
||||
let (tx, results) = mpsc::channel();
|
||||
let thread = thread::Builder::new()
|
||||
.name("Far decoration".into())
|
||||
.spawn(move || {
|
||||
// Structure pieces have mutable one-shot placement flags. Sharing
|
||||
// gameplay's seeded pipeline would consume its chests/spawners.
|
||||
let generator = match OverworldGenerator::for_dimension(
|
||||
terrain.generator.data().clone(),
|
||||
terrain.seed,
|
||||
"minecraft:normal",
|
||||
&terrain.dimension,
|
||||
) {
|
||||
Ok(generator) => generator,
|
||||
Err(error) => {
|
||||
log::warn!("Horizon: far decoration unavailable: {error}");
|
||||
worker.stop.store(true, Ordering::Relaxed);
|
||||
return;
|
||||
}
|
||||
};
|
||||
let mut state = generator.worker();
|
||||
loop {
|
||||
let key = {
|
||||
let mut requests = worker.requests.lock().unwrap();
|
||||
while requests.chunks.is_empty() && !worker.stop.load(Ordering::Relaxed) {
|
||||
requests = worker.wake.wait(requests).unwrap();
|
||||
}
|
||||
if worker.stop.load(Ordering::Relaxed) {
|
||||
break;
|
||||
}
|
||||
let key = *requests
|
||||
.chunks
|
||||
.iter()
|
||||
.min_by_key(|&&key| (distance(key, requests.center), key))
|
||||
.unwrap();
|
||||
let origin = batch_origin(key);
|
||||
requests.chunks.retain(|&key| batch_origin(key) != origin);
|
||||
requests.current = Some(origin);
|
||||
origin
|
||||
};
|
||||
let result = decorated_batch(&mut state, key, BATCH, &worker.stop, |chunk| {
|
||||
let pos = chunk.position();
|
||||
let key = (pos.x, pos.z);
|
||||
worker.requests.lock().unwrap().finished.insert(key);
|
||||
let columns = columns(chunk, &terrain.biome_map, &terrain.dimension);
|
||||
if tx.send((key, columns)).is_err() {
|
||||
worker.stop.store(true, Ordering::Relaxed);
|
||||
}
|
||||
});
|
||||
worker.requests.lock().unwrap().current = None;
|
||||
match result {
|
||||
Ok(_) => {}
|
||||
Err(error) => {
|
||||
log::warn!(
|
||||
"Horizon: far decoration failed at {} {}: {error}",
|
||||
key.0,
|
||||
key.1
|
||||
);
|
||||
worker.stop.store(true, Ordering::Relaxed);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
.expect("far decoration worker");
|
||||
Self {
|
||||
shared,
|
||||
results,
|
||||
thread: Some(thread),
|
||||
}
|
||||
}
|
||||
fn request(&self, chunks: &[(i32, i32)], center: [i32; 2]) {
|
||||
if self.shared.stop.load(Ordering::Relaxed) {
|
||||
return;
|
||||
}
|
||||
let mut requests = self.shared.requests.lock().unwrap();
|
||||
requests.center = center;
|
||||
for &key in chunks {
|
||||
if requests.current != Some(batch_origin(key)) && !requests.finished.contains(&key) {
|
||||
requests.chunks.insert(key);
|
||||
}
|
||||
}
|
||||
if requests.chunks.len() > REQUESTS {
|
||||
let mut sorted: Vec<_> = requests.chunks.iter().copied().collect();
|
||||
sorted.sort_unstable_by_key(|&key| (distance(key, center), key));
|
||||
requests.chunks = sorted.into_iter().take(REQUESTS).collect();
|
||||
}
|
||||
self.shared.wake.notify_one();
|
||||
}
|
||||
}
|
||||
impl Drop for Builder {
|
||||
fn drop(&mut self) {
|
||||
self.shared.stop.store(true, Ordering::Relaxed);
|
||||
self.shared.wake.notify_one();
|
||||
if let Some(thread) = self.thread.take() {
|
||||
let _ = thread.join();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Share the two-chunk terrain halo and one-chunk feature halo across adjacent
|
||||
/// targets. Emit each target only after all nine feature centers have run.
|
||||
/// These proto chunks never enter World, lighting or normal save queues.
|
||||
fn decorated_batch(
|
||||
worker: &mut GeneratorWorker,
|
||||
origin: (i32, i32),
|
||||
size: i32,
|
||||
stop: &AtomicBool,
|
||||
mut emit: impl FnMut(&ProtoChunk),
|
||||
) -> Result<FxHashMap<(i32, i32), ProtoChunk>, GeneratorError> {
|
||||
// Each region starts afresh; flags from a previous speculative structure
|
||||
// placement must not suppress blocks in this region.
|
||||
worker.forget_structure_starts();
|
||||
let mut chunks = FxHashMap::default();
|
||||
for dx in -2..size + 2 {
|
||||
for dz in -2..size + 2 {
|
||||
if stop.load(Ordering::Relaxed) {
|
||||
return Ok(FxHashMap::default());
|
||||
}
|
||||
let key = (origin.0 + dx, origin.1 + dz);
|
||||
chunks.insert(key, worker.generate_proto(ChunkPos::new(key.0, key.1))?);
|
||||
}
|
||||
}
|
||||
let mut remaining: FxHashMap<_, u8> = (0..size)
|
||||
.flat_map(|x| (0..size).map(move |z| ((origin.0 + x, origin.1 + z), 9)))
|
||||
.collect();
|
||||
let center = (origin.0 + size / 2, origin.1 + size / 2);
|
||||
for (x, z) in vanilla_order(center, size / 2)
|
||||
.into_iter()
|
||||
.filter(|&(x, z)| {
|
||||
x >= origin.0 - 1 && x <= origin.0 + size && z >= origin.1 - 1 && z <= origin.1 + size
|
||||
})
|
||||
{
|
||||
if stop.load(Ordering::Relaxed) {
|
||||
return Ok(FxHashMap::default());
|
||||
}
|
||||
let mut region: [ProtoChunk; 9] = std::array::from_fn(|i| {
|
||||
chunks
|
||||
.remove(&(x + i as i32 % 3 - 1, z + i as i32 / 3 - 1))
|
||||
.expect("generated neighborhood")
|
||||
});
|
||||
worker.decorate(&mut region)?;
|
||||
for chunk in region {
|
||||
let pos = chunk.position();
|
||||
chunks.insert((pos.x, pos.z), chunk);
|
||||
}
|
||||
for dx in -1..=1 {
|
||||
for dz in -1..=1 {
|
||||
let key = (x + dx, z + dz);
|
||||
if let Some(left) = remaining.get_mut(&key) {
|
||||
*left -= 1;
|
||||
if *left == 0 {
|
||||
emit(&chunks[&key]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
remaining.values().all(|&left| left == 0),
|
||||
"incomplete far decoration halo"
|
||||
);
|
||||
Ok(chunks)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn decorated_region(
|
||||
worker: &mut GeneratorWorker,
|
||||
center: (i32, i32),
|
||||
stop: &AtomicBool,
|
||||
) -> Result<Option<ProtoChunk>, GeneratorError> {
|
||||
Ok(decorated_batch(worker, center, 1, stop, |_| {})?.remove(¢er))
|
||||
}
|
||||
fn columns(chunk: &ProtoChunk, biome_map: &[u16], dimension: &str) -> Arc<[Column; 256]> {
|
||||
let states = chunk.data().block_states();
|
||||
let registry = chunk.data().registry();
|
||||
let min = chunk.terrain.min_y().max(MIN_Y);
|
||||
let max = (chunk.terrain.min_y() + chunk.terrain.height()).min(MIN_Y + HEIGHT);
|
||||
Arc::new(std::array::from_fn(|index| {
|
||||
let x = (index & 15) as i32;
|
||||
let z = (index >> 4) as i32;
|
||||
let mut column = Column::default();
|
||||
for y in min..max {
|
||||
let state = chunk.block(x, y, z);
|
||||
let properties = states.get(state);
|
||||
if properties.is_air()
|
||||
|| (!properties.blocks_motion_in_heightmap() && !properties.has_fluid())
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let name = registry.state(state).map_or("", |s| s.name.as_str());
|
||||
let fluid = matches!(name, "minecraft:water" | "minecraft:lava");
|
||||
let biome = biome_map
|
||||
.get(chunk.biome_id_at(x, y, z).0 as usize)
|
||||
.copied()
|
||||
.unwrap_or(0);
|
||||
// shortcut: no propagated far lighting, use the normal lighting
|
||||
// engine if accurate distant block-light propagation is required.
|
||||
let light = if dimension == "minecraft:the_nether" {
|
||||
0
|
||||
} else {
|
||||
240
|
||||
} | if name == "minecraft:lava" {
|
||||
15 << 12
|
||||
} else {
|
||||
0
|
||||
};
|
||||
column.push(Span {
|
||||
min: y as i16,
|
||||
max: (y + 1) as i16,
|
||||
state,
|
||||
biome,
|
||||
light,
|
||||
});
|
||||
if fluid {
|
||||
let surface = column.surface.get_or_insert(Surface {
|
||||
height: MIN_Y,
|
||||
state: BlockStateId(0),
|
||||
water: None,
|
||||
biome,
|
||||
});
|
||||
surface.water = Some((y + 1, state));
|
||||
} else {
|
||||
column.surface = Some(Surface {
|
||||
height: y + 1,
|
||||
state,
|
||||
water: None,
|
||||
biome,
|
||||
});
|
||||
}
|
||||
}
|
||||
column
|
||||
}))
|
||||
}
|
||||
|
||||
pub(super) struct VanillaLodSampler {
|
||||
generator: Arc<VanillaTerrain>,
|
||||
worker: GeneratorWorker,
|
||||
builder: Option<Builder>,
|
||||
vegetation: Arc<Vegetation>,
|
||||
cache: FxHashMap<(i32, i32), Arc<[Column; 256]>>,
|
||||
order: VecDeque<(i32, i32)>,
|
||||
details: Vec<LodDetail>,
|
||||
}
|
||||
impl VanillaLodSampler {
|
||||
pub(super) fn new(generator: Arc<VanillaTerrain>) -> Self {
|
||||
let worker = generator.generator.worker();
|
||||
let builder = Some(Builder::new(generator.clone()));
|
||||
let vegetation = Arc::new(Vegetation::new(
|
||||
generator.generator.data(),
|
||||
&generator.biome_map,
|
||||
generator.seed,
|
||||
));
|
||||
Self {
|
||||
generator,
|
||||
worker,
|
||||
builder,
|
||||
vegetation,
|
||||
cache: FxHashMap::default(),
|
||||
order: VecDeque::new(),
|
||||
details: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl LodSampler for VanillaLodSampler {
|
||||
fn fork(&self) -> Option<Box<dyn LodSampler>> {
|
||||
Some(Box::new(Self {
|
||||
generator: self.generator.clone(),
|
||||
worker: self.generator.generator.worker(),
|
||||
builder: None,
|
||||
vegetation: self.vegetation.clone(),
|
||||
cache: FxHashMap::default(),
|
||||
order: VecDeque::new(),
|
||||
details: Vec::new(),
|
||||
}))
|
||||
}
|
||||
fn request_detail(&mut self, chunks: &[(i32, i32)], center: [i32; 2]) {
|
||||
let mut missing = Vec::new();
|
||||
for &key in chunks {
|
||||
if let Some(columns) = self.cache.get(&key) {
|
||||
self.details.push((key, columns.clone()));
|
||||
} else {
|
||||
missing.push(key);
|
||||
}
|
||||
}
|
||||
if let Some(builder) = &self.builder {
|
||||
builder.request(&missing, center);
|
||||
}
|
||||
}
|
||||
fn drain_details(&mut self) -> Vec<LodDetail> {
|
||||
let Some(builder) = &self.builder else {
|
||||
return std::mem::take(&mut self.details);
|
||||
};
|
||||
while let Ok((key, columns)) = builder.results.try_recv() {
|
||||
if !self.cache.contains_key(&key) {
|
||||
self.order.push_back(key);
|
||||
}
|
||||
self.cache.insert(key, columns.clone());
|
||||
while self.cache.len() > CACHE {
|
||||
if let Some(old) = self.order.pop_front() {
|
||||
self.cache.remove(&old);
|
||||
builder
|
||||
.shared
|
||||
.requests
|
||||
.lock()
|
||||
.unwrap()
|
||||
.finished
|
||||
.remove(&old);
|
||||
}
|
||||
}
|
||||
self.details.push((key, columns));
|
||||
}
|
||||
std::mem::take(&mut self.details)
|
||||
}
|
||||
fn sample(&mut self, x: i32, z: i32) -> Option<Surface> {
|
||||
self.column(x, z).surface
|
||||
}
|
||||
fn column(&mut self, x: i32, z: i32) -> Column {
|
||||
self.reduced_column(x, z, 1)
|
||||
}
|
||||
fn reduced_column(&mut self, x: i32, z: i32, width: i32) -> Column {
|
||||
if width <= 16
|
||||
&& let Some(columns) = self.cache.get(&(x >> 4, z >> 4))
|
||||
{
|
||||
return Column::reduced(
|
||||
columns,
|
||||
(x & 15) as usize,
|
||||
(z & 15) as usize,
|
||||
width as usize,
|
||||
);
|
||||
}
|
||||
self.grid(x, z, width, 1).pop().unwrap_or_default()
|
||||
}
|
||||
fn grid(&mut self, x: i32, z: i32, width: i32, side: usize) -> Vec<Column> {
|
||||
let samples = match self
|
||||
.worker
|
||||
.lod_grid(x + width / 2, z + width / 2, width, side)
|
||||
{
|
||||
Ok(samples) => samples,
|
||||
Err(error) => {
|
||||
log::warn!("Horizon: direct far sampling failed: {error}");
|
||||
return vec![Column::default(); side * side];
|
||||
}
|
||||
};
|
||||
samples
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(index, (surface, spans))| {
|
||||
let (wx, wz) = (
|
||||
x + (index % side) as i32 * width,
|
||||
z + (index / side) as i32 * width,
|
||||
);
|
||||
if width <= 16
|
||||
&& let Some(columns) = self.cache.get(&(wx >> 4, wz >> 4))
|
||||
{
|
||||
return Column::reduced(
|
||||
columns,
|
||||
(wx & 15) as usize,
|
||||
(wz & 15) as usize,
|
||||
width as usize,
|
||||
);
|
||||
}
|
||||
self.preview_column(wx + width / 2, wz + width / 2, width, surface, spans)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
impl VanillaLodSampler {
|
||||
fn preview_column(
|
||||
&self,
|
||||
x: i32,
|
||||
z: i32,
|
||||
width: i32,
|
||||
surface: Option<SurfaceSample>,
|
||||
spans: Vec<(i32, i32, BlockStateId)>,
|
||||
) -> Column {
|
||||
let surface = surface.map(|sample| self.generator.client_surface(sample));
|
||||
let biome = surface.map_or(0, |surface| surface.biome);
|
||||
let registry = self.generator.generator.data().registry();
|
||||
let mut column = Column {
|
||||
surface,
|
||||
spans: Vec::new(),
|
||||
};
|
||||
for (min, max, state) in spans.into_iter().rev() {
|
||||
column.push(Span {
|
||||
min: min as i16,
|
||||
max: max as i16,
|
||||
state,
|
||||
biome,
|
||||
light: if self.generator.dimension == "minecraft:the_nether" {
|
||||
0
|
||||
} else {
|
||||
240
|
||||
} | if registry
|
||||
.state(state)
|
||||
.is_some_and(|s| s.name == "minecraft:lava")
|
||||
{
|
||||
15 << 12
|
||||
} else {
|
||||
0
|
||||
},
|
||||
});
|
||||
}
|
||||
let light = if self.generator.dimension == "minecraft:the_nether" {
|
||||
0
|
||||
} else {
|
||||
240
|
||||
};
|
||||
self.vegetation.apply(&mut column, x, z, width, light);
|
||||
column
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
#[ignore = "requires prepared worldgen data in HORIZON_TEST_RESOURCES"]
|
||||
fn decorated_lod_refines_real_seed_canopies_and_all_dimensions() -> crate::Result<()> {
|
||||
let root = std::path::PathBuf::from(
|
||||
std::env::var_os("HORIZON_TEST_RESOURCES").expect("resources"),
|
||||
);
|
||||
let assets = crate::assets::Assets::load(&root)?;
|
||||
let biomes = crate::biome::Biomes::load(&root)?;
|
||||
let terrain = Arc::new(VanillaTerrain::new(
|
||||
&root.join("worldgen"),
|
||||
assets.registry,
|
||||
&biomes,
|
||||
1234,
|
||||
)?);
|
||||
let mut sampler = VanillaLodSampler::new(terrain.clone());
|
||||
let mut fork = sampler.fork().expect("independent far sampler");
|
||||
let direct = sampler.grid(-1024, 0, 32, 16);
|
||||
assert_eq!(
|
||||
direct,
|
||||
fork.grid(-1024, 0, 32, 16),
|
||||
"sampling workers must agree on seed/biome vegetation"
|
||||
);
|
||||
let grass = assets
|
||||
.registry
|
||||
.default_state("minecraft:grass_block")
|
||||
.unwrap();
|
||||
let planted = |biome, width, x, z| {
|
||||
let mut column = Column::from_surface(Some(Surface {
|
||||
height: 80,
|
||||
state: grass,
|
||||
water: None,
|
||||
biome,
|
||||
}));
|
||||
sampler.vegetation.apply(&mut column, x, z, width, 240);
|
||||
column
|
||||
};
|
||||
let forest = biomes.id("minecraft:forest");
|
||||
let plains = biomes.id("minecraft:plains");
|
||||
let leaves = |column: &Column| {
|
||||
column.spans.iter().any(|span| {
|
||||
assets
|
||||
.registry
|
||||
.state(span.state)
|
||||
.unwrap()
|
||||
.name
|
||||
.ends_with("_leaves")
|
||||
})
|
||||
};
|
||||
let mut forest_count = 0;
|
||||
let mut plains_count = 0;
|
||||
for z in 0..64 {
|
||||
for x in 0..64 {
|
||||
forest_count += usize::from(leaves(&planted(forest, 1, x, z)));
|
||||
plains_count += usize::from(leaves(&planted(plains, 1, x, z)));
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
forest_count > 1000 && forest_count > plains_count * 4,
|
||||
"feature-derived vegetation density: forest={forest_count}, plains={plains_count}"
|
||||
);
|
||||
for width in [16, 32, 128, 512, 1024] {
|
||||
assert!(
|
||||
leaves(&planted(forest, width, 0, 0)),
|
||||
"forest canopy missing at scale {width}"
|
||||
);
|
||||
}
|
||||
let key = (-64, 0);
|
||||
sampler.request_detail(&[key], [-1024, 0]);
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
|
||||
let generated = loop {
|
||||
if let Some((_, columns)) = sampler.drain_details().into_iter().find(|(k, _)| *k == key)
|
||||
{
|
||||
break columns;
|
||||
}
|
||||
assert!(
|
||||
std::time::Instant::now() < deadline,
|
||||
"decoration worker stalled"
|
||||
);
|
||||
std::thread::sleep(std::time::Duration::from_millis(5));
|
||||
};
|
||||
let count = |suffix: &str| {
|
||||
generated
|
||||
.iter()
|
||||
.flat_map(|column| &column.spans)
|
||||
.filter(|span| {
|
||||
assets
|
||||
.registry
|
||||
.state(span.state)
|
||||
.unwrap()
|
||||
.name
|
||||
.ends_with(suffix)
|
||||
})
|
||||
.map(|span| i32::from(span.max - span.min))
|
||||
.sum::<i32>()
|
||||
};
|
||||
assert!(count("_leaves") > 0, "unexplored forest has a real canopy");
|
||||
assert!(count("_log") > 0, "canopy retains its trunks");
|
||||
assert!(generated.iter().all(|column| {
|
||||
column
|
||||
.spans
|
||||
.windows(2)
|
||||
.all(|pair| pair[0].max <= pair[1].min)
|
||||
}));
|
||||
for z in 0..16 {
|
||||
for x in 0..16 {
|
||||
assert_eq!(
|
||||
sampler.column(key.0 * 16 + x, key.1 * 16 + z),
|
||||
generated[(z * 16 + x) as usize]
|
||||
);
|
||||
}
|
||||
}
|
||||
sampler.request_detail(&[key], [-1024, 0]);
|
||||
let cached = sampler.drain_details();
|
||||
assert!(
|
||||
Arc::ptr_eq(&cached[0].1, &generated),
|
||||
"reuses completed compact data"
|
||||
);
|
||||
drop(sampler);
|
||||
let mut worker = terrain.generator.worker();
|
||||
let started = std::time::Instant::now();
|
||||
for x in 0..BATCH {
|
||||
for z in 0..BATCH {
|
||||
decorated_region(&mut worker, (key.0 + x, key.1 + z), &AtomicBool::new(false))?
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
let separate = started.elapsed();
|
||||
let started = std::time::Instant::now();
|
||||
let mut emitted = FxHashMap::default();
|
||||
let region = decorated_batch(&mut worker, key, BATCH, &AtomicBool::new(false), |chunk| {
|
||||
let pos = chunk.position();
|
||||
assert!(
|
||||
emitted
|
||||
.insert(
|
||||
(pos.x, pos.z),
|
||||
columns(chunk, &terrain.biome_map, "minecraft:overworld")
|
||||
)
|
||||
.is_none()
|
||||
);
|
||||
})?;
|
||||
eprintln!(
|
||||
"far generation: {} separate targets={separate:?}, shared targets={:?}",
|
||||
emitted.len(),
|
||||
started.elapsed()
|
||||
);
|
||||
assert_eq!(emitted.len(), (BATCH * BATCH) as usize);
|
||||
for (key, data) in emitted {
|
||||
assert_eq!(
|
||||
data,
|
||||
columns(®ion[&key], &terrain.biome_map, "minecraft:overworld"),
|
||||
"emitted before all neighbouring features completed"
|
||||
);
|
||||
}
|
||||
assert_eq!(batch_origin((-1, -5)), (-4, -8));
|
||||
let stop = AtomicBool::new(true);
|
||||
assert!(decorated_region(&mut terrain.generator.worker(), key, &stop)?.is_none());
|
||||
for (dimension, center) in [
|
||||
("minecraft:the_nether", (0, 0)),
|
||||
("minecraft:the_end", (16, 0)),
|
||||
] {
|
||||
let generator = OverworldGenerator::for_dimension(
|
||||
terrain.generator.data().clone(),
|
||||
1234,
|
||||
"minecraft:normal",
|
||||
dimension,
|
||||
)?;
|
||||
let mut emitted = 0;
|
||||
let mut region = decorated_batch(
|
||||
&mut generator.worker(),
|
||||
center,
|
||||
BATCH,
|
||||
&AtomicBool::new(false),
|
||||
|_| emitted += 1,
|
||||
)?;
|
||||
assert_eq!(emitted, (BATCH * BATCH) as usize);
|
||||
let chunk = region.remove(¢er).unwrap();
|
||||
let data = columns(&chunk, &terrain.biome_map, dimension);
|
||||
if dimension == "minecraft:the_nether" {
|
||||
assert!(
|
||||
data.iter()
|
||||
.flat_map(|c| &c.spans)
|
||||
.all(|s| s.light & 0xf0 == 0)
|
||||
);
|
||||
assert!(data.iter().flat_map(|c| &c.spans).any(|s| {
|
||||
assets.registry.state(s.state).unwrap().name == "minecraft:lava"
|
||||
&& s.light >> 12 == 15
|
||||
}));
|
||||
} else {
|
||||
assert!(
|
||||
data.iter().all(|c| c.spans.is_empty()),
|
||||
"End void stays empty"
|
||||
);
|
||||
}
|
||||
}
|
||||
// Reuse the saved-proto bastion fixture. Repeated speculative regions
|
||||
// must reconstruct structures after their one-shot placement flags ran.
|
||||
let generator = OverworldGenerator::for_dimension(
|
||||
terrain.generator.data().clone(),
|
||||
-1860902098141295193,
|
||||
"minecraft:normal",
|
||||
"minecraft:the_nether",
|
||||
)?;
|
||||
let mut worker = generator.worker();
|
||||
let mut previous = None;
|
||||
for _ in 0..2 {
|
||||
let chunk = decorated_region(&mut worker, (3, 7), &AtomicBool::new(false))?.unwrap();
|
||||
assert!(
|
||||
chunk
|
||||
.structures()
|
||||
.iter()
|
||||
.any(|(name, _, _, _)| name.contains("bastion"))
|
||||
);
|
||||
let data = columns(&chunk, &terrain.biome_map, "minecraft:the_nether");
|
||||
let snapshot = (data, chunk.block_entities);
|
||||
if let Some(previous) = &previous {
|
||||
assert_eq!(
|
||||
&snapshot, previous,
|
||||
"speculative structure state leaked between regions"
|
||||
);
|
||||
}
|
||||
previous = Some(snapshot);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,309 @@
|
||||
//! Seed-stable visual vegetation from the world's own feature data.
|
||||
//! shortcut: these positions approximate native placement; saved/visited and
|
||||
//! completed native chunks replace them rather than changing gameplay worldgen.
|
||||
use crate::{
|
||||
fast_hash::FxHashMap,
|
||||
lod::{Column, Span, Surface},
|
||||
};
|
||||
use horizon_world::{
|
||||
registry::{BlockRegistry, BlockStateId},
|
||||
worldgen::generator::GeneratorData,
|
||||
};
|
||||
use serde_json::Value;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Tree {
|
||||
leaves: BlockStateId,
|
||||
log: BlockStateId,
|
||||
height: i32,
|
||||
variation: i32,
|
||||
radius: i32,
|
||||
count: f64,
|
||||
}
|
||||
pub(super) struct Vegetation {
|
||||
trees: FxHashMap<u16, Vec<Tree>>,
|
||||
seed: u64,
|
||||
registry: &'static BlockRegistry,
|
||||
}
|
||||
fn mean(v: &Value) -> f64 {
|
||||
if let Some(n) = v.as_f64() {
|
||||
return n;
|
||||
}
|
||||
let distribution = v["distribution"].as_array();
|
||||
if let Some(entries) = distribution {
|
||||
let total: f64 = entries
|
||||
.iter()
|
||||
.map(|e| e["weight"].as_f64().unwrap_or(0.))
|
||||
.sum();
|
||||
if total > 0. {
|
||||
return entries
|
||||
.iter()
|
||||
.map(|e| mean(&e["data"]) * e["weight"].as_f64().unwrap_or(0.))
|
||||
.sum::<f64>()
|
||||
/ total;
|
||||
}
|
||||
}
|
||||
(v["min_inclusive"].as_f64().unwrap_or(0.) + v["max_inclusive"].as_f64().unwrap_or(0.)) * 0.5
|
||||
}
|
||||
fn block(v: &Value, registry: &BlockRegistry) -> Option<BlockStateId> {
|
||||
let name = v
|
||||
.as_str()
|
||||
.or_else(|| v["id"].as_str())
|
||||
.or_else(|| v["Name"].as_str())?;
|
||||
registry.default_state(name)
|
||||
}
|
||||
fn gather(
|
||||
data: &GeneratorData,
|
||||
value: &Value,
|
||||
placed: bool,
|
||||
count: f64,
|
||||
depth: usize,
|
||||
out: &mut Vec<Tree>,
|
||||
) {
|
||||
if depth > 12 || count <= 0. {
|
||||
return;
|
||||
}
|
||||
if let Some(name) = value.as_str() {
|
||||
let json = if placed {
|
||||
data.placed_feature_json(name)
|
||||
} else {
|
||||
data.configured_feature_json(name)
|
||||
};
|
||||
if let Some(json) = json.and_then(|s| serde_json::from_str::<Value>(s).ok()) {
|
||||
gather(data, &json, placed, count, depth + 1, out);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if placed {
|
||||
let mut count = count;
|
||||
if let Some(modifiers) = value["placement"].as_array() {
|
||||
for modifier in modifiers {
|
||||
match modifier["type"]
|
||||
.as_str()
|
||||
.unwrap_or("")
|
||||
.strip_prefix("minecraft:")
|
||||
.unwrap_or("")
|
||||
{
|
||||
"count" | "count_on_every_layer" => count *= mean(&modifier["count"]),
|
||||
"rarity_filter" => count /= modifier["chance"].as_f64().unwrap_or(1.).max(1.),
|
||||
"count_extra" => {
|
||||
count *= modifier["count"].as_f64().unwrap_or(0.)
|
||||
+ modifier["extra_count"].as_f64().unwrap_or(0.)
|
||||
* modifier["extra_chance"].as_f64().unwrap_or(0.)
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
gather(data, &value["feature"], false, count, depth + 1, out);
|
||||
return;
|
||||
}
|
||||
let config = if value["config"].is_object() {
|
||||
&value["config"]
|
||||
} else {
|
||||
value
|
||||
};
|
||||
match value["type"].as_str().unwrap_or("") {
|
||||
"minecraft:tree" => {
|
||||
let (Some(leaves), Some(log)) = (
|
||||
block(&config["foliage_provider"], data.registry()),
|
||||
block(&config["trunk_provider"], data.registry()),
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
let trunk = &config["trunk_placer"];
|
||||
out.push(Tree {
|
||||
leaves,
|
||||
log,
|
||||
height: trunk["base_height"].as_i64().unwrap_or(5) as i32,
|
||||
variation: (trunk["height_rand_a"].as_i64().unwrap_or(0)
|
||||
+ trunk["height_rand_b"].as_i64().unwrap_or(0))
|
||||
as i32,
|
||||
radius: mean(&config["foliage_placer"]["radius"])
|
||||
.round()
|
||||
.clamp(2., 6.) as i32,
|
||||
count,
|
||||
});
|
||||
}
|
||||
"minecraft:random_selector" => {
|
||||
let mut remaining = count;
|
||||
if let Some(features) = config["features"].as_array() {
|
||||
for entry in features {
|
||||
let chance = entry["chance"].as_f64().unwrap_or(0.).clamp(0., 1.);
|
||||
gather(
|
||||
data,
|
||||
&entry["feature"],
|
||||
true,
|
||||
remaining * chance,
|
||||
depth + 1,
|
||||
out,
|
||||
);
|
||||
remaining *= 1. - chance;
|
||||
}
|
||||
}
|
||||
gather(data, &config["default"], true, remaining, depth + 1, out);
|
||||
}
|
||||
"minecraft:random_boolean_selector" => {
|
||||
for key in ["feature_true", "feature_false"] {
|
||||
gather(data, &config[key], true, count * 0.5, depth + 1, out);
|
||||
}
|
||||
}
|
||||
"minecraft:simple_random_selector" => {
|
||||
if let Some(features) = config["features"].as_array() {
|
||||
for feature in features {
|
||||
gather(
|
||||
data,
|
||||
feature,
|
||||
true,
|
||||
count / features.len().max(1) as f64,
|
||||
depth + 1,
|
||||
out,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
fn hash(seed: u64, x: i32, z: i32) -> u64 {
|
||||
let mut n = seed
|
||||
^ (x as u64).wrapping_mul(0x9e3779b97f4a7c15)
|
||||
^ (z as u64).wrapping_mul(0xd1b54a32d192ed03);
|
||||
n = (n ^ n >> 30).wrapping_mul(0xbf58476d1ce4e5b9);
|
||||
n = (n ^ n >> 27).wrapping_mul(0x94d049bb133111eb);
|
||||
n ^ n >> 31
|
||||
}
|
||||
impl Vegetation {
|
||||
pub(super) fn new(data: &GeneratorData, map: &[u16], seed: i64) -> Self {
|
||||
let mut trees = FxHashMap::default();
|
||||
for (index, &biome) in map.iter().enumerate() {
|
||||
let Ok(json) = serde_json::from_str::<Value>(
|
||||
data.biome_json(horizon_world::worldgen::biome::BiomeId(index as u32)),
|
||||
) else {
|
||||
continue;
|
||||
};
|
||||
let mut list = Vec::new();
|
||||
if let Some(steps) = json["features"].as_array() {
|
||||
for step in steps {
|
||||
if let Some(features) = step.as_array() {
|
||||
for feature in features {
|
||||
gather(data, feature, true, 1., 0, &mut list);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !list.is_empty() {
|
||||
trees.insert(biome, list);
|
||||
}
|
||||
}
|
||||
Self {
|
||||
trees,
|
||||
seed: seed as u64,
|
||||
registry: data.registry(),
|
||||
}
|
||||
}
|
||||
pub(super) fn apply(&self, column: &mut Column, x: i32, z: i32, width: i32, light: u16) {
|
||||
let Some(surface) = column.surface else {
|
||||
return;
|
||||
};
|
||||
if surface.water.is_some_and(|(y, _)| y >= surface.height) {
|
||||
return;
|
||||
}
|
||||
let ground = self
|
||||
.registry
|
||||
.state(surface.state)
|
||||
.map_or("", |s| s.name.as_str());
|
||||
if !matches!(
|
||||
ground,
|
||||
"minecraft:grass_block"
|
||||
| "minecraft:dirt"
|
||||
| "minecraft:coarse_dirt"
|
||||
| "minecraft:podzol"
|
||||
| "minecraft:mycelium"
|
||||
| "minecraft:rooted_dirt"
|
||||
| "minecraft:moss_block"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
let Some(trees) = self.trees.get(&surface.biome) else {
|
||||
return;
|
||||
};
|
||||
let total: f64 = trees.iter().map(|tree| tree.count).sum();
|
||||
let choose = |n: u64| {
|
||||
let mut value = (n as u32 as f64 / u32::MAX as f64) * total;
|
||||
for tree in trees {
|
||||
value -= tree.count;
|
||||
if value <= 0. {
|
||||
return tree;
|
||||
}
|
||||
}
|
||||
&trees[trees.len() - 1]
|
||||
};
|
||||
let mut best = None;
|
||||
if width >= 16 {
|
||||
let n = hash(self.seed, x.div_euclid(4), z.div_euclid(4));
|
||||
let tree = choose(n);
|
||||
let coverage = 1.
|
||||
- (-total * f64::from(tree.radius * tree.radius) * std::f64::consts::PI / 256.)
|
||||
.exp();
|
||||
if coverage >= 0.25 {
|
||||
let height = tree.height + ((n >> 32) & 1) as i32;
|
||||
best = Some((
|
||||
surface.height + height.max(4),
|
||||
surface.height + height.max(4) - tree.radius * 2,
|
||||
*tree,
|
||||
false,
|
||||
));
|
||||
}
|
||||
} else {
|
||||
let radius = trees.iter().map(|t| t.radius).max().unwrap_or(2);
|
||||
for cz in (z - radius).div_euclid(4)..=(z + radius).div_euclid(4) {
|
||||
for cx in (x - radius).div_euclid(4)..=(x + radius).div_euclid(4) {
|
||||
let n = hash(self.seed, cx, cz);
|
||||
if (n as u32 as f64 / u32::MAX as f64) >= (total / 16.).min(1.) {
|
||||
continue;
|
||||
}
|
||||
let tree = *choose(n.rotate_left(21));
|
||||
let tx = cx * 4 + ((n >> 32) & 3) as i32;
|
||||
let tz = cz * 4 + ((n >> 34) & 3) as i32;
|
||||
let d2 = (x - tx).pow(2) + (z - tz).pow(2);
|
||||
if d2 > tree.radius.pow(2) {
|
||||
continue;
|
||||
}
|
||||
let height =
|
||||
tree.height + ((n >> 40) % (tree.variation.max(0) + 1) as u64) as i32;
|
||||
let cap = ((tree.radius.pow(2) - d2) as f32).sqrt().ceil() as i32;
|
||||
let top = surface.height + height + cap.min(2);
|
||||
let bottom = surface.height + height - tree.radius;
|
||||
if best.as_ref().is_none_or(|&(y, _, _, _)| top > y) {
|
||||
best = Some((top, bottom, tree, x == tx && z == tz));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some((top, bottom, tree, trunk)) = best {
|
||||
let bottom = bottom.max(surface.height + 1);
|
||||
if trunk {
|
||||
column.push(Span {
|
||||
min: surface.height as i16,
|
||||
max: bottom as i16,
|
||||
state: tree.log,
|
||||
biome: surface.biome,
|
||||
light,
|
||||
});
|
||||
}
|
||||
column.push(Span {
|
||||
min: bottom as i16,
|
||||
max: top.max(bottom + 1) as i16,
|
||||
state: tree.leaves,
|
||||
biome: surface.biome,
|
||||
light,
|
||||
});
|
||||
column.surface = Some(Surface {
|
||||
height: top.max(bottom + 1),
|
||||
state: tree.leaves,
|
||||
..surface
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,14 @@ impl SamplerContext {
|
||||
..Self::default()
|
||||
}
|
||||
}
|
||||
/// Far previews evaluate only the supplied lattice. Ordinary generation
|
||||
/// retains vanilla's dense strided-volume evaluation and rounding.
|
||||
pub fn sparse() -> Self {
|
||||
Self {
|
||||
sparse: true,
|
||||
..Self::cached()
|
||||
}
|
||||
}
|
||||
pub fn clear_caches(&mut self) {
|
||||
if let Some(caches) = &mut self.caches {
|
||||
caches.clear();
|
||||
|
||||
@@ -172,6 +172,18 @@ impl DensitySampler for InterpolatedSampler {
|
||||
volume: DensityVolume,
|
||||
) -> Result<(), SampleError> {
|
||||
check_buffer(output, volume)?;
|
||||
if context.sparse {
|
||||
if (0..3).all(|i| {
|
||||
volume.steps()[i] % self.cell_size[i] == 0
|
||||
&& volume.minimum()[i].rem_euclid(self.cell_size[i]) == 0
|
||||
}) {
|
||||
return self.input.sample_volume(context, output, volume);
|
||||
}
|
||||
return visit(volume, |index, position| {
|
||||
output[index] = self.sample_value(context, position)?;
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
if (0..3).all(|i| {
|
||||
(volume.steps()[i] == self.cell_size[i] || volume.sizes()[i] == 1)
|
||||
&& volume.minimum()[i].rem_euclid(self.cell_size[i]) == 0
|
||||
|
||||
@@ -90,6 +90,7 @@ pub struct SamplerContext {
|
||||
scratch: Vec<Vec<f32>>,
|
||||
caches: Option<Vec<cache::CacheCell>>,
|
||||
fields: WorldFields,
|
||||
sparse: bool,
|
||||
}
|
||||
impl SamplerContext {
|
||||
fn with_buffer<T>(
|
||||
|
||||
@@ -501,6 +501,28 @@ fn grid_interpolation_uses_child_bulk_corners_and_preserves_aligned_delegation()
|
||||
.unwrap();
|
||||
assert!(output.iter().all(|v| v.to_bits() == (-0.0_f32).to_bits()));
|
||||
assert_eq!(traced.volumes.lock().unwrap()[1], volume);
|
||||
let distant = DensityVolume::new([16, 49, 16], [-8192, -64, -8192], [1024, 8, 1024]).unwrap();
|
||||
let mut output = vec![19.; distant.size()];
|
||||
sampler
|
||||
.sample_volume(&mut SamplerContext::sparse(), &mut output, distant)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
traced.volumes.lock().unwrap()[2],
|
||||
distant,
|
||||
"far samples must not expand to a block-resolution bounding box"
|
||||
);
|
||||
let unaligned = DensityVolume::new([2; 3], [-5, -9, -7], [1024, 8, 1024]).unwrap();
|
||||
let mut output = [19.; 8];
|
||||
sampler
|
||||
.sample_volume(&mut SamplerContext::sparse(), &mut output, unaligned)
|
||||
.unwrap();
|
||||
assert!(output.iter().all(|&v| v == 0.));
|
||||
assert!(
|
||||
traced.volumes.lock().unwrap()[3..]
|
||||
.iter()
|
||||
.all(|v| v.size() == 8),
|
||||
"unaligned far points use bounded corner queries"
|
||||
);
|
||||
assert!(InterpolatedSampler::new(traced.clone(), 0, 8).is_err());
|
||||
assert!(InterpolatedSampler::new(traced, 4, -1).is_err());
|
||||
}
|
||||
|
||||
@@ -495,6 +495,20 @@ impl GeneratorData {
|
||||
&self.states
|
||||
}
|
||||
/// Biome identifiers in registry (identifier-sorted) order.
|
||||
pub fn configured_feature_json(&self, name: &str) -> Option<&str> {
|
||||
self.feature_resources
|
||||
.as_ref()?
|
||||
.features
|
||||
.get(name)
|
||||
.map(String::as_str)
|
||||
}
|
||||
pub fn placed_feature_json(&self, name: &str) -> Option<&str> {
|
||||
self.feature_resources
|
||||
.as_ref()?
|
||||
.placed
|
||||
.get(name)
|
||||
.map(String::as_str)
|
||||
}
|
||||
pub fn biome_names(&self) -> &[Arc<str>] {
|
||||
&self.biome_names
|
||||
}
|
||||
@@ -1412,7 +1426,21 @@ trait SeededPipeline: Send + Sync {
|
||||
) -> Result<DecorateStats, GeneratorError>;
|
||||
fn data(&self) -> &Arc<GeneratorData>;
|
||||
fn sea_level(&self) -> i32;
|
||||
fn surface_sample(&self, worker: &mut WorkerState, x: i32, z: i32) -> Option<SurfaceSample>;
|
||||
fn surface_sample(
|
||||
&self,
|
||||
worker: &mut WorkerState,
|
||||
x: i32,
|
||||
z: i32,
|
||||
spans: Option<&mut Vec<(i32, i32, BlockStateId)>>,
|
||||
) -> Option<SurfaceSample>;
|
||||
fn lod_grid(
|
||||
&self,
|
||||
worker: &mut WorkerState,
|
||||
x: i32,
|
||||
z: i32,
|
||||
width: i32,
|
||||
side: usize,
|
||||
) -> Result<Vec<LodColumn>, GeneratorError>;
|
||||
fn structure_starts(
|
||||
&self,
|
||||
worker: &mut WorkerState,
|
||||
@@ -1595,15 +1623,38 @@ where
|
||||
}
|
||||
None
|
||||
}
|
||||
fn surface_sample(&self, worker: &mut WorkerState, x: i32, z: i32) -> Option<SurfaceSample> {
|
||||
fn surface_sample(
|
||||
&self,
|
||||
worker: &mut WorkerState,
|
||||
x: i32,
|
||||
z: i32,
|
||||
mut spans: Option<&mut Vec<(i32, i32, BlockStateId)>>,
|
||||
) -> Option<SurfaceSample> {
|
||||
let mut top = None;
|
||||
let mut water = None;
|
||||
let mut below = 0;
|
||||
self.noise_column(x, z, &mut |y, state| {
|
||||
let mut surface_complete = false;
|
||||
let mut visit = |y, state| {
|
||||
let properties = self.data.states.get(state);
|
||||
if let Some(spans) = spans.as_mut()
|
||||
&& !properties.is_air()
|
||||
{
|
||||
if let Some((min, _, previous)) = spans.last_mut()
|
||||
&& *min == y + 1
|
||||
&& *previous == state
|
||||
{
|
||||
*min = y;
|
||||
} else {
|
||||
spans.push((y, y + 1, state));
|
||||
}
|
||||
}
|
||||
if surface_complete {
|
||||
return false;
|
||||
}
|
||||
if properties.is_air() || properties.has_fluid() {
|
||||
if top.is_some() {
|
||||
return true;
|
||||
surface_complete = true;
|
||||
return spans.is_none();
|
||||
}
|
||||
if properties.has_fluid() {
|
||||
water.get_or_insert((y + 1, state));
|
||||
@@ -1616,7 +1667,8 @@ where
|
||||
below += 1;
|
||||
}
|
||||
false
|
||||
});
|
||||
};
|
||||
self.noise_column(x, z, &mut visit);
|
||||
let (height, state) = top?;
|
||||
let y = height - 1;
|
||||
let position = BlockPos::new(x, y, z);
|
||||
@@ -1651,6 +1703,18 @@ where
|
||||
material.update_xz(x, z, 0, 0);
|
||||
material.update_y(1, below, water.map_or(i32::MIN, |(height, _)| height), y);
|
||||
let state = material.try_apply(rule, position).ok()?.unwrap_or(state);
|
||||
if let Some(spans) = spans
|
||||
&& let Some(index) = spans.iter().position(|&(min, max, _)| min <= y && y < max)
|
||||
&& spans[index].2 != state
|
||||
{
|
||||
let (min, max, _) = spans[index];
|
||||
if min == y {
|
||||
spans[index].2 = state;
|
||||
} else {
|
||||
spans[index].1 = y;
|
||||
spans.insert(index, (y, max, state));
|
||||
}
|
||||
}
|
||||
Some(SurfaceSample {
|
||||
height,
|
||||
state,
|
||||
@@ -1658,6 +1722,207 @@ where
|
||||
biome,
|
||||
})
|
||||
}
|
||||
fn lod_grid(
|
||||
&self,
|
||||
worker: &mut WorkerState,
|
||||
x: i32,
|
||||
z: i32,
|
||||
width: i32,
|
||||
side: usize,
|
||||
) -> Result<Vec<LodColumn>, GeneratorError> {
|
||||
if width <= 0 || side == 0 || side > 64 {
|
||||
return Err(resource("far sample dimensions"));
|
||||
}
|
||||
let mut geometry = Vec::with_capacity(side * side);
|
||||
let mut context = SamplerContext::sparse();
|
||||
let (min, height) = (self.settings.noise_min_y, self.settings.noise_height);
|
||||
let step_xz = width.max(4);
|
||||
let ox = x.div_euclid(4) * 4;
|
||||
let oz = z.div_euclid(4) * 4;
|
||||
let nx = ((x - ox + (side as i32 - 1) * width + step_xz - 1) / step_xz) + 1;
|
||||
let nz = ((z - oz + (side as i32 - 1) * width + step_xz - 1) / step_xz) + 1;
|
||||
let ny = (height + 7) / 8 + 1;
|
||||
let volume = DensityVolume::new([nx, ny, nz], [ox, min, oz], [step_xz, 8, step_xz])
|
||||
.map_err(stage("far density"))?;
|
||||
let mut densities = vec![0.; volume.size()];
|
||||
self.router
|
||||
.get(RouterField::FinalDensity)
|
||||
.sample_volume(&mut context, &mut densities, volume)
|
||||
.map_err(stage("far density"))?;
|
||||
let aquifer = DisabledAquifer::new(
|
||||
self.picker,
|
||||
self.data.registry.default_state("minecraft:air").unwrap(),
|
||||
);
|
||||
// Interpolate the supplied lattice, never the physical bounding volume.
|
||||
let value = |wx: i32, iy: usize, wz: i32| {
|
||||
let rx = (wx - ox) as f32 / step_xz as f32;
|
||||
let rz = (wz - oz) as f32 / step_xz as f32;
|
||||
let ix = rx.floor() as usize;
|
||||
let iz = rz.floor() as usize;
|
||||
let at = |dx: usize, dz: usize| {
|
||||
densities[volume
|
||||
.index([
|
||||
(ix + dx).min(nx as usize - 1),
|
||||
iy,
|
||||
(iz + dz).min(nz as usize - 1),
|
||||
])
|
||||
.unwrap()]
|
||||
};
|
||||
let mix = |a: f32, b: f32, t: f32| a + (b - a) * t;
|
||||
mix(
|
||||
mix(at(0, 0), at(1, 0), rx - ix as f32),
|
||||
mix(at(0, 1), at(1, 1), rx - ix as f32),
|
||||
rz - iz as f32,
|
||||
)
|
||||
};
|
||||
let mut profile = vec![0.; ny as usize];
|
||||
let mut resolver = self.source.resolver(
|
||||
&self.climate,
|
||||
self.router.get(RouterField::Erosion).as_ref(),
|
||||
);
|
||||
let mut biome_context = SamplerContext::cached();
|
||||
for dz in 0..side {
|
||||
for dx in 0..side {
|
||||
let (wx, wz) = (x + dx as i32 * width, z + dz as i32 * width);
|
||||
let mut top = None;
|
||||
let mut water = None;
|
||||
let mut below = 0;
|
||||
let mut complete = false;
|
||||
let mut spans: Vec<(i32, i32, BlockStateId)> = Vec::new();
|
||||
for (iy, density) in profile.iter_mut().enumerate() {
|
||||
*density = value(wx, iy, wz);
|
||||
}
|
||||
for y in (min..min + height).rev() {
|
||||
let iy = (y - min) as usize / 8;
|
||||
let alpha = ((y - min) % 8) as f32 / 8.;
|
||||
let density = profile[iy] + (profile[iy + 1] - profile[iy]) * alpha;
|
||||
let state = aquifer
|
||||
.compute_substance([wx, y, wz], f64::from(density))
|
||||
.unwrap_or(self.settings.default_block);
|
||||
let properties = self.data.states.get(state);
|
||||
if !properties.is_air() {
|
||||
if let Some((min, _, old)) = spans.last_mut()
|
||||
&& *min == y + 1
|
||||
&& *old == state
|
||||
{
|
||||
*min = y;
|
||||
} else {
|
||||
spans.push((y, y + 1, state));
|
||||
}
|
||||
}
|
||||
if !complete {
|
||||
if properties.is_air() || properties.has_fluid() {
|
||||
if top.is_some() {
|
||||
complete = true;
|
||||
} else if properties.has_fluid() {
|
||||
water.get_or_insert((y + 1, state));
|
||||
} else {
|
||||
water = None;
|
||||
}
|
||||
} else {
|
||||
top.get_or_insert((y + 1, state));
|
||||
below += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let biome = if let Some((height, _)) = top {
|
||||
let name = resolver
|
||||
.sample(
|
||||
&mut biome_context,
|
||||
self.zoom.quart_at_block(BlockPos::new(wx, height - 1, wz)),
|
||||
)
|
||||
.map_err(stage("far biome"))?;
|
||||
self.data
|
||||
.biome_id(name)
|
||||
.ok_or_else(|| resource("far biome"))?
|
||||
} else {
|
||||
BiomeId(0)
|
||||
};
|
||||
geometry.push((top, water, below, spans, biome));
|
||||
}
|
||||
}
|
||||
if geometry.iter().all(|column| column.0.is_none()) {
|
||||
return Ok(geometry
|
||||
.into_iter()
|
||||
.map(|(_, _, _, spans, _)| (None, spans))
|
||||
.collect());
|
||||
}
|
||||
let volume =
|
||||
DensityVolume::new([1; 3], [x, 0, z], [1; 3]).map_err(stage("far material"))?;
|
||||
let queries = SurfaceQueries {
|
||||
pipeline: self,
|
||||
temperatures: &mut worker.temperatures,
|
||||
biome: Biomes::Resolver(&mut resolver, &mut biome_context),
|
||||
possible: None,
|
||||
};
|
||||
let sources = MaterialDensitySources::new(
|
||||
queries,
|
||||
volume,
|
||||
self.preliminary.clone(),
|
||||
SamplerContext::cached(),
|
||||
)
|
||||
.map_err(stage("far material"))?;
|
||||
let mut material =
|
||||
MaterialConditions::<R, _>::new(self.generation(), self.root.clone(), sources);
|
||||
let rule = material
|
||||
.add_rule(self.rule.clone())
|
||||
.map_err(stage("far material"))?;
|
||||
let mut result = Vec::with_capacity(side * side);
|
||||
for (index, (top, water, below, mut spans, biome)) in geometry.into_iter().enumerate() {
|
||||
let (wx, wz) = (
|
||||
x + (index % side) as i32 * width,
|
||||
z + (index / side) as i32 * width,
|
||||
);
|
||||
let Some((height, mut state)) = top else {
|
||||
result.push((None, spans));
|
||||
continue;
|
||||
};
|
||||
material.update_xz(wx, wz, 0, 0);
|
||||
for depth in 1..=below.min(8) {
|
||||
let y = height - depth;
|
||||
material.update_y(
|
||||
depth,
|
||||
below - depth + 1,
|
||||
water.map_or(i32::MIN, |(height, _)| height),
|
||||
y,
|
||||
);
|
||||
let Some(index) = spans.iter().position(|&(min, max, _)| min <= y && y < max)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let (min, max, old) = spans[index];
|
||||
let painted = material
|
||||
.try_apply(rule, BlockPos::new(wx, y, wz))
|
||||
.map_err(stage("far material"))?
|
||||
.unwrap_or(old);
|
||||
if depth == 1 {
|
||||
state = painted;
|
||||
}
|
||||
if old == painted {
|
||||
continue;
|
||||
}
|
||||
let mut replacement = Vec::with_capacity(3);
|
||||
if y + 1 < max {
|
||||
replacement.push((y + 1, max, old));
|
||||
}
|
||||
replacement.push((y, y + 1, painted));
|
||||
if min < y {
|
||||
replacement.push((min, y, old));
|
||||
}
|
||||
spans.splice(index..=index, replacement);
|
||||
}
|
||||
result.push((
|
||||
Some(SurfaceSample {
|
||||
height,
|
||||
state,
|
||||
water,
|
||||
biome,
|
||||
}),
|
||||
spans,
|
||||
));
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
fn noise_biomes(&self, worker: &mut WorkerState, quarts: &[[i32; 3]]) -> Vec<Option<String>> {
|
||||
let mut resolver = self.source.resolver(
|
||||
&self.climate,
|
||||
@@ -1937,6 +2202,8 @@ pub struct SurfaceSample {
|
||||
pub biome: BiomeId,
|
||||
}
|
||||
|
||||
pub type LodColumn = (Option<SurfaceSample>, Vec<(i32, i32, BlockStateId)>);
|
||||
|
||||
/// Per-thread generation state.
|
||||
pub struct GeneratorWorker {
|
||||
pipeline: Arc<dyn SeededPipeline>,
|
||||
@@ -1952,7 +2219,20 @@ impl GeneratorWorker {
|
||||
}
|
||||
/// Noise/aquifer surface and its material rule, without chunks, structures or features.
|
||||
pub fn surface_sample(&mut self, x: i32, z: i32) -> Option<SurfaceSample> {
|
||||
self.pipeline.surface_sample(&mut self.state, x, z)
|
||||
self.pipeline.surface_sample(&mut self.state, x, z, None)
|
||||
}
|
||||
/// Noise/aquifer material runs, excluding air; bounds are half-open.
|
||||
/// Features and carvers still require generated chunks.
|
||||
pub fn surface_column(
|
||||
&mut self,
|
||||
x: i32,
|
||||
z: i32,
|
||||
) -> (Option<SurfaceSample>, Vec<(i32, i32, BlockStateId)>) {
|
||||
let mut spans = Vec::new();
|
||||
let surface = self
|
||||
.pipeline
|
||||
.surface_sample(&mut self.state, x, z, Some(&mut spans));
|
||||
(surface, spans)
|
||||
}
|
||||
/// `/locate structure`: the nearest start of one of `names`.
|
||||
pub fn locate(
|
||||
@@ -1963,11 +2243,22 @@ impl GeneratorWorker {
|
||||
) -> Option<(String, [i32; 3])> {
|
||||
self.pipeline.locate(&mut self.state, names, from, radius)
|
||||
}
|
||||
/// `BiomeSource.findClosestBiome3d`: the first sampled position whose
|
||||
/// noise biome passes `allowed`, spiralling out from the origin.
|
||||
/// Direct far sampling: work scales with rendered vertical resolution,
|
||||
/// without allocating chunks, carving masks or propagated aquifers.
|
||||
pub fn lod_grid(
|
||||
&mut self,
|
||||
x: i32,
|
||||
z: i32,
|
||||
width: i32,
|
||||
side: usize,
|
||||
) -> Result<Vec<LodColumn>, GeneratorError> {
|
||||
self.pipeline.lod_grid(&mut self.state, x, z, width, side)
|
||||
}
|
||||
pub fn noise_biomes(&mut self, quarts: &[[i32; 3]]) -> Vec<Option<String>> {
|
||||
self.pipeline.noise_biomes(&mut self.state, quarts)
|
||||
}
|
||||
/// `BiomeSource.findClosestBiome3d`: the first sampled position whose
|
||||
/// noise biome passes `allowed`, spiralling out from the origin.
|
||||
pub fn find_closest_biome(&mut self, search: &BiomeSearch<'_>) -> Option<(String, [i32; 3])> {
|
||||
self.pipeline.find_closest_biome(&mut self.state, search)
|
||||
}
|
||||
@@ -2032,6 +2323,26 @@ mod tests {
|
||||
OverworldGenerator::without_structures(data.clone(), 1234).expect("generator");
|
||||
let mut worker = generator.worker();
|
||||
let sample = worker.surface_sample(0, 0).expect("land");
|
||||
let (column_surface, spans) = worker.surface_column(0, 0);
|
||||
let column_surface = column_surface.expect("column land");
|
||||
assert_eq!(column_surface.height, sample.height);
|
||||
assert_eq!(column_surface.state, sample.state);
|
||||
assert_eq!(column_surface.water, sample.water);
|
||||
assert_eq!(column_surface.biome, sample.biome);
|
||||
assert!(spans.iter().all(|&(min, max, state)| {
|
||||
min < max && !generator.data().block_states().get(state).is_air()
|
||||
}));
|
||||
assert!(spans.windows(2).all(|pair| {
|
||||
pair[1].1 <= pair[0].0 && (pair[1].1 != pair[0].0 || pair[1].2 != pair[0].2)
|
||||
}));
|
||||
assert!(spans.iter().any(|&(min, max, state)| {
|
||||
min < sample.height && sample.height - 1 < max && state == sample.state
|
||||
}));
|
||||
assert!(sample.water.is_some_and(|(height, state)| {
|
||||
spans
|
||||
.iter()
|
||||
.any(|&(min, max, block)| min < height && height - 1 < max && block == state)
|
||||
}));
|
||||
let chunk = worker.generate_proto(ChunkPos::new(0, 0)).expect("terrain");
|
||||
assert_eq!(
|
||||
sample.water.map_or(sample.height, |(height, _)| height),
|
||||
@@ -2042,12 +2353,55 @@ mod tests {
|
||||
sample.water.is_some(),
|
||||
"fixture includes underwater terrain"
|
||||
);
|
||||
let started = std::time::Instant::now();
|
||||
let mut exact = Vec::new();
|
||||
for z in 0..8 {
|
||||
for x in 0..8 {
|
||||
exact.push(worker.surface_column(-1024 + x * 32, z * 32));
|
||||
}
|
||||
}
|
||||
let dense_time = started.elapsed();
|
||||
let started = std::time::Instant::now();
|
||||
let direct = worker.lod_grid(-1024, 0, 32, 8).unwrap();
|
||||
for z in 0..8 {
|
||||
for x in 0..8 {
|
||||
let wx = -1024 + x * 32;
|
||||
let wz = z * 32;
|
||||
let (surface, spans) = &direct[(z * 8 + x) as usize];
|
||||
let expected = exact[(z * 8 + x) as usize].0;
|
||||
if let (Some(surface), Some(expected)) = (surface, expected) {
|
||||
assert!(
|
||||
(surface.height - expected.height).abs() <= 32,
|
||||
"coarse height exceeds its vertical resolution at {wx} {wz}: {} vs {}",
|
||||
surface.height,
|
||||
expected.height
|
||||
);
|
||||
assert!(spans.iter().any(|&(min, max, state)| min < surface.height
|
||||
&& surface.height - 1 < max
|
||||
&& state == surface.state));
|
||||
}
|
||||
assert!(spans.iter().all(|&(min, max, _)| min < max));
|
||||
assert!(spans.windows(2).all(|pair| pair[1].1 <= pair[0].0));
|
||||
}
|
||||
}
|
||||
eprintln!(
|
||||
"64 far columns: dense={dense_time:?}, direct32={:?}",
|
||||
started.elapsed()
|
||||
);
|
||||
let end =
|
||||
OverworldGenerator::for_dimension(data, 1234, "minecraft:normal", "minecraft:the_end")
|
||||
.expect("End generator");
|
||||
let mut worker = end.worker();
|
||||
assert!(worker.surface_sample(0, 0).is_some());
|
||||
assert!(worker.surface_sample(256, 0).is_none());
|
||||
let (surface, spans) = worker.surface_column(256, 0);
|
||||
assert!(surface.is_none());
|
||||
assert!(spans.is_empty());
|
||||
let (surface, spans) = worker.lod_grid(256, 0, 32, 1).unwrap().pop().unwrap();
|
||||
assert!(
|
||||
surface.is_none() && spans.is_empty(),
|
||||
"direct sampling retains End void"
|
||||
);
|
||||
}
|
||||
|
||||
/// Generators of one seed and dimension share their ring positions;
|
||||
|
||||
+10
-2
@@ -25,7 +25,7 @@ Every row has a one-line description and its cost in frame time (none, low, medi
|
||||
| Performance | battery mode, worker threads, upload budget per frame | `horizon-graphics.txt` |
|
||||
| Overlay | performance overlay: FPS, frame/CPU/GPU times, frame-time graph | `horizon-graphics.txt` |
|
||||
|
||||
`options.txt` keeps exactly vanilla's keys and values, so the options harness still compares it with vanilla; Horizon's settings live in `horizon-graphics.txt` beside it. Their defaults render as vanilla does: cave culling on, no upload budgets, sky, fog and weather on, 100% resolution, no FXAA, the present mode following VSync. VSync on always waits for the display (Fifo), in a window and in fullscreen, as in vanilla; the present mode setting chooses how frames are shown only while VSync is off. Frame pacing defaults to Efficient: the limiter sleeps through the last half millisecond where vanilla spins, which changes timing, not pixels.
|
||||
`options.txt` keeps exactly vanilla's keys and values, so the options harness still compares it with vanilla; Horizon's settings live in `horizon-graphics.txt` beside it. Their defaults render as vanilla does: cave culling on, no explicit upload count/byte limits, sky, fog and weather on, 100% resolution, no FXAA, the present mode following VSync. VSync on always waits for the display (Fifo), in a window and in fullscreen, as in vanilla; the present mode setting chooses how frames are shown only while VSync is off. Chunk mesh uploads yield after roughly 4 ms per frame, even with count and byte limits set to Unlimited; a single upload can exceed that soft limit. Frame pacing defaults to Efficient: the limiter sleeps through the last half millisecond where vanilla spins, which changes timing, not pixels.
|
||||
|
||||
**Battery mode** (Performance, off by default) is for laptops and handhelds: at most 60 frames per second in a world, 30 in menus without a world or while another window has focus, and half the automatic worker threads (chunks load slower). It changes only when frames are drawn: what they show and the game's 20 ticks per second stay as they are.
|
||||
|
||||
@@ -35,7 +35,15 @@ Which settings each level shows, their descriptions and costs are in `crates/hor
|
||||
|
||||
**LOD Distance** is off by default. Enable it in Simple or Advanced graphics settings and choose 64, 128, 256, 512 or 1024 chunks. With LODs enabled, **Full Detail Distance** controls the nearby normal chunks; LOD Distance controls the outer view. Keep the nearby range modest, for example 12 chunks with a 256-chunk LOD distance. Increasing the distant range does not increase simulation distance.
|
||||
|
||||
Distant terrain uses progressively coarser surface meshes, streamed in bounded background work instead of loading full chunks out to the distant range. It is available in local Overworld and End worlds; surface LODs are disabled in the Nether. Unknown terrain samples use noise/aquifer heights and surface materials, omitting caves, decorations, structures and slope-dependent extensions. Loaded and saved terrain supplies bounded surface summaries, including player edits; small details can disappear between samples. This is a surface approximation, not full block geometry. Procedural distant terrain requires a local world's generator; remote servers do not supply their world-generation seed.
|
||||
Distant terrain uses progressively coarser voxel columns. Columns retain separate material layers and air gaps; matching exposed faces are merged, with block-scale texture repeats. Complete chunk data is reduced once on the terrain worker and cached at each supported scale, across each cell’s area instead of enlarging its corner column. Material votes combine different light levels of the same block; reduced cells retain the brightest sampled sky and block light separately. Finer tiles replace only their own footprints in a loading fallback, and a movement margin limits rapid resolution changes at tile boundaries. Local Overworld, Nether and End worlds and a LAN world you host can supply their generator. Remote servers do not supply the client's world-generation seed or generator configuration.
|
||||
|
||||
Unknown areas are sampled directly from the dimension's seed-bound density and surface rules, with shared per-tile scratch and material evaluation. A small pool samples tiles independently of meshing. Refinement prioritizes visible screen error; high aerial views use the distance to the world height range to avoid unnecessary close detail below the camera. Initial vegetation uses the world's configured tree types, placement densities and biome assignments at every distance level. Tree positions, shapes and large-cell coverage are visual approximations, not a replay of native feature placement.
|
||||
|
||||
A separate bounded worker refines the nearest LOD levels with disposable ordinary chunk generation, including supported carvers, structures and decoration. Groups of 4×4 chunks share their generation halos, and each chunk is published once every neighbouring feature center has completed. Farther tiles use direct sampling rather than waiting for every intervening ordinary chunk. Saved and visited blocks take precedence over both paths. These temporary chunks never enter gameplay, simulation or normal save queues. Generated-column caches and request queues are bounded; far data is regenerated after reopening a world.
|
||||
|
||||
Coverage and detail improve progressively; a large selected radius does not mean all its target detail is already resident. The control status reports target and sampled target tile counts separately. Direct far sampling approximates vertical noise interpolation, fluid boundaries and lighting; surface slopes and column extensions, small features and partial block shapes can differ. Unexplored distant structures are not synthesized by the direct path, and native decoration order can differ from subsequent gameplay generation. Horizon-supported data-driven noise and tree configurations can be reused; this does not execute arbitrary Fabric/NeoForge worldgen or structure mods.
|
||||
|
||||
Ordinary Overworld atmospheric fog extends with the selected LOD distance. Fog Off disables distance haze at large ranges too; fluid, darkness and boss fog retain their limits.
|
||||
|
||||
LOD terrain enters the existing world colour and depth passes, so supported shader-pack postprocessing can see it. This does not add Iris material passes or shadow maps: Java packs still have the [existing fullscreen-pass limitations](shader-packs.md). Shader appearance and transitions need testing with the selected pack.
|
||||
|
||||
|
||||
@@ -258,7 +258,7 @@ A `shaders/` folder of GLSL programs, named by where Iris (and OptiFine before i
|
||||
| Custom textures, `noisetex` | easy | image loads |
|
||||
| Custom uniforms (`uniform.*` expressions) | medium | a small expression evaluator per frame |
|
||||
| Compute (`.csh`), `image2D` load/store | medium | wgpu has compute; storage formats are more limited than OpenGL's |
|
||||
| Distant Horizons, Voxy hooks, `DH_*` | not planned | Horizon has no LOD terrain yet |
|
||||
| Distant Horizons, Voxy hooks, `DH_*` | not planned | Horizon's native LOD terrain shares world colour/depth; it does not expose these mods' APIs |
|
||||
|
||||
Order: preprocessor and legaliser until the three test packs parse; then `composite`/`final`/`deferred` with the
|
||||
uniforms; then `gbuffers_terrain`, `gbuffers_water` and `gbuffers_skybasic`/`skytextured` (the packs' look comes
|
||||
|
||||
Reference in New Issue
Block a user