2095590807
Preserve AirDef replay lighting and acoustic commands while retaining upstream shadow and HDR fixes. Give the two entity shadow shaders distinct entry points. Co-Authored-By: Codex <noreply@openai.com>
673 lines
28 KiB
Rust
673 lines
28 KiB
Rust
//! Resident client world: streamed chunk columns plus the bookkeeping the game
|
|
//! loop needs to relight and remesh after edits.
|
|
use crate::chunk::{Chunk, MIN_Y, SECTIONS};
|
|
use horizon_core::random::LegacyRandom;
|
|
use horizon_world::registry::BlockStateId;
|
|
use std::{
|
|
collections::{HashMap, HashSet},
|
|
sync::Arc,
|
|
};
|
|
|
|
/// Sections (x, section index, z) waiting to be remeshed, kept by column
|
|
/// (a bit per section index), so the mesh scheduler looks at each column once
|
|
/// rather than at every section of it.
|
|
#[derive(Clone, Debug, Default)]
|
|
pub struct DirtySections {
|
|
columns: crate::fast_hash::FxHashMap<(i32, i32), u32>,
|
|
}
|
|
const _: () = assert!(SECTIONS <= 32);
|
|
impl DirtySections {
|
|
pub fn insert(&mut self, (x, sy, z): (i32, i32, i32)) {
|
|
debug_assert!((0..SECTIONS as i32).contains(&sy));
|
|
*self.columns.entry((x, z)).or_default() |= 1 << sy;
|
|
}
|
|
pub fn contains(&self, &(x, sy, z): &(i32, i32, i32)) -> bool {
|
|
(0..SECTIONS as i32).contains(&sy)
|
|
&& self.columns.get(&(x, z)).is_some_and(|m| m & 1 << sy != 0)
|
|
}
|
|
/// The dirty section indexes of column (x, z), as bits, removed.
|
|
pub fn take_column(&mut self, x: i32, z: i32) -> u32 {
|
|
self.columns.remove(&(x, z)).unwrap_or(0)
|
|
}
|
|
/// Keep the columns `keep` accepts.
|
|
pub fn retain_columns(&mut self, mut keep: impl FnMut(i32, i32) -> bool) {
|
|
self.columns.retain(|&(x, z), _| keep(x, z));
|
|
}
|
|
/// The columns holding dirty sections, with their section bits.
|
|
pub fn columns(&self) -> impl Iterator<Item = ((i32, i32), u32)> + '_ {
|
|
self.columns.iter().map(|(&c, &m)| (c, m))
|
|
}
|
|
pub fn clear(&mut self) {
|
|
self.columns.clear();
|
|
}
|
|
pub fn is_empty(&self) -> bool {
|
|
self.columns.is_empty()
|
|
}
|
|
/// How many sections are dirty.
|
|
pub fn len(&self) -> usize {
|
|
self.columns.values().map(|m| m.count_ones() as usize).sum()
|
|
}
|
|
}
|
|
pub struct World {
|
|
pub fast_lava: bool,
|
|
pub chunks: crate::chunk_map::ChunkMap,
|
|
pub random: LegacyRandom,
|
|
/// The revision of the blocks shown: a real change, and a view of an earlier time that
|
|
/// changes the picture (the renderer and the acoustics follow it). Mods cache on
|
|
/// `live_revision`: a film's view is no change of the world they simulate.
|
|
pub revision: u64,
|
|
/// The revision of the real blocks, which a view of an earlier time leaves alone.
|
|
pub live_revision: u64,
|
|
pub health_rules: HealthRules,
|
|
pub air: BlockStateId,
|
|
/// Sections whose geometry changed and need remeshing.
|
|
pub dirty_sections: DirtySections,
|
|
/// Chunks whose light must be recomputed.
|
|
pub dirty_light: crate::fast_hash::FxHashSet<(i32, i32)>,
|
|
/// Edits on lit chunks (position, old state, new state), relit
|
|
/// incrementally by streaming.
|
|
pub light_edits: Vec<((i32, i32, i32), u32, u32)>,
|
|
/// Saved entities of chunks that just loaded, spawned by the game.
|
|
pub loaded_entities: Vec<((i32, i32), Vec<horizon_world::nbt::Tag>)>,
|
|
/// Chunks changed since the last save.
|
|
pub modified: HashSet<(i32, i32)>,
|
|
/// Block entities, and the order they tick in.
|
|
pub block_entities: crate::block_entities::BlockEntities,
|
|
/// Each chest's `ContainerOpenersCounter`: opener count and largest
|
|
/// interaction range.
|
|
pub chest_openers: HashMap<(i32, i32, i32), (i32, f64)>,
|
|
/// `BaseContainerBlockEntity.name`: custom names of container block entities.
|
|
pub block_names: HashMap<(i32, i32, i32), String>,
|
|
/// States (by id) whose writes are recorded in `watched_writes` (sculk
|
|
/// blocks, which need a block entity).
|
|
pub watched: Vec<bool>,
|
|
/// Writes of watched states: position, previous and new state.
|
|
pub watched_writes: Vec<((i32, i32, i32), u32, u32)>,
|
|
/// `ChunkAccess.inhabitedTime` of resident chunks: ticks a player spent
|
|
/// within spawning range (local difficulty).
|
|
pub inhabited: HashMap<(i32, i32), i64>,
|
|
pub game_time: i64,
|
|
pub day_time: i64,
|
|
pub weather: Weather,
|
|
/// Every block position written since the log was last drained, kept
|
|
/// only while the world is open to the network (see `lan`).
|
|
pub block_log: Option<Vec<(i32, i32, i32)>>,
|
|
/// The sections whose light changed since the log was last drained, as
|
|
/// a bit per section of each column, kept while `block_log` is
|
|
/// (`ChunkHolder.sectionLightChanged`).
|
|
pub light_log: Option<crate::fast_hash::FxHashMap<(i32, i32), u32>>,
|
|
/// The villager POIs of each section (`PoiManager`'s sections).
|
|
pub pois: crate::poi_sections::PoiSections<crate::poi_sections::Poi>,
|
|
/// Moving-piston states removed during the last tick; retained until the
|
|
/// final block mesh is visible.
|
|
pub moving_piston_fallback: Vec<([i32; 3], horizon_world::piston_shape::MovingPistonState)>,
|
|
/// The moving-piston block entities of the level, by position, copied
|
|
/// from the block ticks after each tick: collision and rendering read them.
|
|
pub moving_pistons: Vec<([i32; 3], horizon_world::piston_shape::MovingPistonState)>,
|
|
/// A number of this world alone (a new one for every level opened): what
|
|
/// mods cache about the blocks is void when it changes.
|
|
pub epoch: u32,
|
|
/// The sections whose blocks changed since a mod last asked, kept only
|
|
/// while a mod watches (`render.world-changes`).
|
|
pub mod_changes: ModChanges,
|
|
/// The same for the acoustics (AirDef fork, #96): their cache is dropped where a block changed.
|
|
pub sound_changes: ModChanges,
|
|
/// AirDef fork: the log of block changes a mod asked for (`render.world-log-start`) and the
|
|
/// game tick the changes are stamped with.
|
|
pub log: Option<crate::world_log::WorldLog>,
|
|
pub log_tick: u64,
|
|
}
|
|
/// The block changes a mod's cache of the world must hear of.
|
|
#[derive(Default)]
|
|
pub struct ModChanges {
|
|
pub watching: bool,
|
|
pub sections: crate::fast_hash::FxHashSet<(i32, i32, i32)>,
|
|
/// More sections changed than [`ModChanges::MAX`]: all count as changed.
|
|
pub overflow: bool,
|
|
}
|
|
impl ModChanges {
|
|
/// Sections kept between two reads.
|
|
pub const MAX: usize = 256;
|
|
fn note(&mut self, x: i32, y: i32, z: i32) {
|
|
if self.sections.len() >= Self::MAX {
|
|
self.overflow = true;
|
|
} else {
|
|
self.sections.insert((x >> 4, y >> 4, z >> 4));
|
|
}
|
|
}
|
|
/// A column's residency changed (a chunk loaded, was replaced by a reload
|
|
/// or is gone): every section of the column counts as changed, for caches
|
|
/// keyed to sections. Bounded like `note` is.
|
|
pub fn column(&mut self, x: i32, z: i32) {
|
|
if self.sections.len() < Self::MAX {
|
|
for sy in (MIN_Y >> 4)..(MIN_Y >> 4) + SECTIONS as i32 {
|
|
self.sections.insert((x, sy, z));
|
|
}
|
|
}
|
|
if self.sections.len() >= Self::MAX {
|
|
self.overflow = true;
|
|
}
|
|
}
|
|
/// The change log overflowed or the resident columns were cleared: every cached section may be stale.
|
|
pub fn overflow(&mut self) {
|
|
self.overflow = true;
|
|
}
|
|
/// What changed since the last call, as the mod reads it.
|
|
pub fn take(&mut self) -> (Vec<(i32, i32, i32)>, bool) {
|
|
(
|
|
self.sections.drain().collect(),
|
|
std::mem::take(&mut self.overflow),
|
|
)
|
|
}
|
|
}
|
|
static NEXT_EPOCH: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(1);
|
|
#[derive(Clone, Copy, Debug, Default)]
|
|
pub struct Weather {
|
|
pub clear_time: i32,
|
|
pub rain_time: i32,
|
|
pub thunder_time: i32,
|
|
pub raining: bool,
|
|
pub thundering: bool,
|
|
pub rain_level: (f32, f32),
|
|
pub thunder_level: (f32, f32),
|
|
}
|
|
impl Weather {
|
|
/// The timers of `advanceWeatherCycle`, which run only while
|
|
/// `advance_weather` is on.
|
|
pub fn tick_timers(&mut self, random: &mut horizon_core::random::LegacyRandom) {
|
|
use horizon_core::random::RandomSource;
|
|
let mut uniform =
|
|
|min: i32, max: i32| min + random.next_int_bound(max - min + 1).unwrap_or(0);
|
|
if self.clear_time > 0 {
|
|
self.clear_time -= 1;
|
|
self.thunder_time = if self.thundering { 0 } else { 1 };
|
|
self.rain_time = if self.raining { 0 } else { 1 };
|
|
self.thundering = false;
|
|
self.raining = false;
|
|
} else {
|
|
if self.thunder_time > 0 {
|
|
self.thunder_time -= 1;
|
|
if self.thunder_time == 0 {
|
|
self.thundering = !self.thundering;
|
|
}
|
|
} else if self.thundering {
|
|
self.thunder_time = uniform(3600, 15600);
|
|
} else {
|
|
self.thunder_time = uniform(12000, 180000);
|
|
}
|
|
if self.rain_time > 0 {
|
|
self.rain_time -= 1;
|
|
if self.rain_time == 0 {
|
|
self.raining = !self.raining;
|
|
}
|
|
} else if self.raining {
|
|
self.rain_time = uniform(12000, 24000);
|
|
} else {
|
|
self.rain_time = uniform(12000, 180000);
|
|
}
|
|
}
|
|
}
|
|
/// The rain and thunder level fade at the end of `advanceWeatherCycle`,
|
|
/// which runs whatever `advance_weather` says, so `/weather` still shows.
|
|
pub fn tick_levels(&mut self) {
|
|
self.thunder_level.0 = self.thunder_level.1;
|
|
self.thunder_level.1 =
|
|
(self.thunder_level.1 + if self.thundering { 0.01 } else { -0.01 }).clamp(0.0, 1.0);
|
|
self.rain_level.0 = self.rain_level.1;
|
|
self.rain_level.1 =
|
|
(self.rain_level.1 + if self.raining { 0.01 } else { -0.01 }).clamp(0.0, 1.0);
|
|
}
|
|
/// Level.getRainLevel / getThunderLevel (thunder scales with rain).
|
|
pub fn levels(&self, partial: f32) -> (f32, f32) {
|
|
let rain = self.rain_level.0 + (self.rain_level.1 - self.rain_level.0) * partial;
|
|
let thunder =
|
|
self.thunder_level.0 + (self.thunder_level.1 - self.thunder_level.0) * partial;
|
|
(rain, thunder * rain)
|
|
}
|
|
}
|
|
impl World {
|
|
pub fn new(air: BlockStateId, seed: i64) -> Self {
|
|
Self {
|
|
chunks: Default::default(),
|
|
random: LegacyRandom::new(seed),
|
|
revision: 0,
|
|
live_revision: 0,
|
|
health_rules: HealthRules::default(),
|
|
air,
|
|
fast_lava: false,
|
|
dirty_sections: Default::default(),
|
|
dirty_light: Default::default(),
|
|
light_edits: Vec::new(),
|
|
loaded_entities: Vec::new(),
|
|
modified: HashSet::new(),
|
|
block_entities: Default::default(),
|
|
chest_openers: HashMap::new(),
|
|
block_names: HashMap::new(),
|
|
watched: Vec::new(),
|
|
watched_writes: Vec::new(),
|
|
inhabited: HashMap::new(),
|
|
game_time: 0,
|
|
day_time: 1000,
|
|
weather: Weather::default(),
|
|
block_log: None,
|
|
light_log: None,
|
|
moving_piston_fallback: Vec::new(),
|
|
moving_pistons: Vec::new(),
|
|
pois: Default::default(),
|
|
epoch: NEXT_EPOCH.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
|
|
mod_changes: ModChanges::default(),
|
|
sound_changes: ModChanges::default(),
|
|
log: None,
|
|
log_tick: 0,
|
|
}
|
|
}
|
|
/// A controlled blockstate scene for the native scene probes: material
|
|
/// layers, a stepped pyramid and the model gallery. Not generated terrain.
|
|
pub fn test_scene(
|
|
assets: &crate::assets::Assets,
|
|
render: &crate::assets::RenderAssets,
|
|
radius: i32,
|
|
) -> crate::Result<Self> {
|
|
let air = assets
|
|
.registry
|
|
.default_state("minecraft:air")
|
|
.ok_or("missing air state")?;
|
|
let mut world = Self::new(air, 0);
|
|
for cz in -radius..=radius {
|
|
for cx in -radius..=radius {
|
|
world
|
|
.chunks
|
|
.insert((cx, cz), Arc::new(Chunk::empty(cx, cz)));
|
|
for z in 0..16 {
|
|
for x in 0..16 {
|
|
for y in 0..4 {
|
|
let layer = match y {
|
|
0 => 0,
|
|
1 | 2 => 1,
|
|
_ if (cx + cz) & 1 == 0 => 2,
|
|
_ => 3,
|
|
};
|
|
world.set(
|
|
cx * 16 + x,
|
|
y,
|
|
cz * 16 + z,
|
|
assets.material_states[layer],
|
|
)?;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
for y in 4..11 {
|
|
for z in -10_i32..=10 {
|
|
for x in -10_i32..=10 {
|
|
if x.abs().max(z.abs()) <= 10 - (y - 4) {
|
|
world.set(
|
|
x,
|
|
y,
|
|
z,
|
|
assets.material_states[if y & 1 == 0 { 4 } else { 5 }],
|
|
)?;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
for (position, state) in &render.model_placements {
|
|
world.set(position.x, position.y, position.z, *state)?;
|
|
}
|
|
world.revision = 0;
|
|
Ok(world)
|
|
}
|
|
/// Resident storage write; marks the touched sections (and neighbours on
|
|
/// section borders) for remeshing and the surrounding chunks for relighting.
|
|
/// Neighbour updates, drops and block entities belong to the gameplay layer.
|
|
pub fn set(&mut self, x: i32, y: i32, z: i32, state: BlockStateId) -> crate::Result<()> {
|
|
if self.chunks.get(&(x >> 4, z >> 4)).is_none() {
|
|
return Err("write outside resident chunks".into());
|
|
}
|
|
if y < MIN_Y || y >= MIN_Y + (SECTIONS as i32) * 16 {
|
|
return Err("write outside world height".into());
|
|
}
|
|
// A mod's view of an earlier time keeps the blocks it shows: a real change is logged and
|
|
// held back (the state before it is the real one) until the view moves past it.
|
|
let deferred = self
|
|
.log
|
|
.as_ref()
|
|
.and_then(|l| l.deferred([x, y, z], self.block(x, y, z).0));
|
|
let previous = match deferred {
|
|
Some(real) => real,
|
|
None => {
|
|
let chunk = self.chunks.get_mut(&(x >> 4, z >> 4)).expect("checked");
|
|
Arc::make_mut(chunk).set(x & 15, y, z & 15, state.0)
|
|
}
|
|
};
|
|
if previous != state.0 {
|
|
if let Some(log) = &mut self.log {
|
|
log.record(
|
|
self.log_tick,
|
|
[x, y, z],
|
|
previous,
|
|
state.0,
|
|
deferred.is_some(),
|
|
);
|
|
}
|
|
self.block_entities
|
|
.state_changed((x, y, z), previous, state.0);
|
|
let watches = |id: u32| self.watched.get(id as usize).copied().unwrap_or(false);
|
|
if watches(previous) || watches(state.0) {
|
|
self.watched_writes.push(((x, y, z), previous, state.0));
|
|
}
|
|
self.revision = self.revision.wrapping_add(1);
|
|
self.live_revision = self.live_revision.wrapping_add(1);
|
|
if self.mod_changes.watching {
|
|
self.mod_changes.note(x, y, z);
|
|
}
|
|
if self.sound_changes.watching {
|
|
self.sound_changes.note(x, y, z);
|
|
}
|
|
if let Some(log) = &mut self.block_log {
|
|
log.push((x, y, z));
|
|
}
|
|
self.modified.insert((x >> 4, z >> 4));
|
|
if deferred.is_none() {
|
|
self.touched(x, y, z, previous, state.0);
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
/// Marks what a written block changes: the sections to remesh (and their neighbours on a
|
|
/// border) and the light.
|
|
fn touched(&mut self, x: i32, y: i32, z: i32, previous: u32, state: u32) {
|
|
for dz in -1..=1 {
|
|
for dy in -1..=1 {
|
|
for dx in -1..=1 {
|
|
let (bx, by, bz) = (x + dx, y + dy, z + dz);
|
|
let s = (by - MIN_Y) >> 4;
|
|
if !(0..SECTIONS as i32).contains(&s) {
|
|
continue;
|
|
}
|
|
self.dirty_sections.insert((bx >> 4, s, bz >> 4));
|
|
}
|
|
}
|
|
}
|
|
if self.chunks.get(&(x >> 4, z >> 4)).is_some_and(|c| c.lit) {
|
|
self.light_edits.push(((x, y, z), previous, state));
|
|
} else {
|
|
for dz in -1..=1 {
|
|
for dx in -1..=1 {
|
|
self.dirty_light.insert(((x >> 4) + dx, (z >> 4) + dz));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
/// A mod's view of the world at an earlier tick (`render.set-world-time-view`): moves it
|
|
/// toward `target` by at most `budget` changes, leaving alone the blocks around `protect`
|
|
/// (a block position whose neighbourhood stays as it is: the player's). Only the picture
|
|
/// changes: the renderer meshes these chunks, while a simulation reads the real blocks
|
|
/// ([`Self::live_block`]). True when it has got there.
|
|
pub fn view_log(
|
|
&mut self,
|
|
target: Option<u64>,
|
|
budget: usize,
|
|
protect: Option<[i32; 3]>,
|
|
) -> bool {
|
|
let Some(mut log) = self.log.take() else {
|
|
return true;
|
|
};
|
|
let keep = |p: [i32; 3]| {
|
|
protect.is_none_or(|c| {
|
|
!((p[0] - c[0]).abs() <= 2
|
|
&& (p[2] - c[2]).abs() <= 2
|
|
&& (-3..=3).contains(&(p[1] - c[1])))
|
|
})
|
|
};
|
|
let done = log.view(&mut ShownBlocks(self), target, budget, keep);
|
|
self.log = Some(log);
|
|
done
|
|
}
|
|
}
|
|
/// The world as a log's view writes it: the picture the renderer meshes changes, and nothing
|
|
/// else. The real state of every block written stays in the log (`WorldLog::real`), which is
|
|
/// what a simulation reads; the world's own change signals stay the real ones.
|
|
struct ShownBlocks<'a>(&'a mut World);
|
|
impl crate::world_log::Blocks for ShownBlocks<'_> {
|
|
fn get(&self, pos: [i32; 3]) -> Option<u32> {
|
|
let w = &*self.0;
|
|
(w.chunks.get(&(pos[0] >> 4, pos[2] >> 4)).is_some()
|
|
&& (MIN_Y..MIN_Y + (SECTIONS as i32) * 16).contains(&pos[1]))
|
|
.then(|| w.block(pos[0], pos[1], pos[2]).0)
|
|
}
|
|
fn put(&mut self, [x, y, z]: [i32; 3], state: u32) -> bool {
|
|
let w = &mut *self.0;
|
|
if !(MIN_Y..MIN_Y + (SECTIONS as i32) * 16).contains(&y) {
|
|
return false;
|
|
}
|
|
let Some(chunk) = w.chunks.get_mut(&(x >> 4, z >> 4)) else {
|
|
return false;
|
|
};
|
|
let previous = Arc::make_mut(chunk).set(x & 15, y, z & 15, state);
|
|
if previous != state {
|
|
// The picture changed, so the renderer and the acoustics look at it again; the
|
|
// blocks did not, so `live_revision` and `mod_changes` — what mods cache and
|
|
// simulate by — stay as they are.
|
|
w.revision = w.revision.wrapping_add(1);
|
|
if w.sound_changes.watching {
|
|
w.sound_changes.note(x, y, z);
|
|
}
|
|
w.touched(x, y, z, previous, state);
|
|
}
|
|
true
|
|
}
|
|
}
|
|
impl World {
|
|
/// `getHeight(Heightmap.Types.WORLD_SURFACE, x, z)`: one above the highest
|
|
/// block that isn't `air`, or `MIN_Y` (also where the chunk isn't loaded).
|
|
pub fn world_surface(&self, x: i32, z: i32, air: impl Fn(BlockStateId) -> bool) -> i32 {
|
|
self.chunks.get(&(x >> 4, z >> 4)).map_or(MIN_Y, |chunk| {
|
|
chunk.world_surface(x, z, |v| air(BlockStateId(v)))
|
|
})
|
|
}
|
|
/// `getHeight(Heightmap.Types.MOTION_BLOCKING, x, z)`: one above the
|
|
/// highest block where `blocks` (motion blocking or holding a fluid),
|
|
/// or `MIN_Y` (also where the chunk isn't loaded).
|
|
pub fn motion_blocking(&self, x: i32, z: i32, blocks: impl Fn(BlockStateId) -> bool) -> i32 {
|
|
self.chunks.get(&(x >> 4, z >> 4)).map_or(MIN_Y, |chunk| {
|
|
chunk.motion_blocking(x & 15, z & 15, |v| blocks(BlockStateId(v)))
|
|
})
|
|
}
|
|
pub fn block(&self, x: i32, y: i32, z: i32) -> BlockStateId {
|
|
self.chunks
|
|
.get(&(x >> 4, z >> 4))
|
|
.map_or(self.air, |chunk| chunk.block(x & 15, y, z & 15))
|
|
}
|
|
/// Inserts a whole current column. A replay keeps its picture, but the real states behind it
|
|
/// are refreshed from this column and simulations hear the change.
|
|
pub fn insert_chunk(&mut self, key: (i32, i32), mut chunk: Arc<crate::chunk::Chunk>) -> Option<Arc<crate::chunk::Chunk>> {
|
|
if let Some(log) = &mut self.log {
|
|
let current = self.chunks.get(&key).cloned();
|
|
log.reload_column(key.0, key.1, current.as_deref(), Arc::make_mut(&mut chunk));
|
|
}
|
|
self.live_revision = self.live_revision.wrapping_add(1);
|
|
if self.mod_changes.watching {
|
|
self.mod_changes.column(key.0, key.1);
|
|
}
|
|
self.chunks.insert(key, chunk)
|
|
}
|
|
/// The real block at `(x, y, z)`: what a simulation reads, where a view of an earlier
|
|
/// time shows something else for a film ([`Self::view_log`]). [`Self::block`] stays the
|
|
/// picture, which is what the renderer meshes.
|
|
pub fn live_block(&self, x: i32, y: i32, z: i32) -> BlockStateId {
|
|
match self.log.as_ref().and_then(|log| log.real([x, y, z])) {
|
|
Some(real) => BlockStateId(real),
|
|
None => self.block(x, y, z),
|
|
}
|
|
}
|
|
/// Whether a view of an earlier time shows a block of the column `(x >> 4, z >> 4)`
|
|
/// otherwise: until it does, the column reads as the real one.
|
|
pub fn view_shows_in_column(&self, cx: i32, cz: i32) -> bool {
|
|
self.log
|
|
.as_ref()
|
|
.is_some_and(|log| log.shows_in_column(cx, cz))
|
|
}
|
|
/// The blocks of section `(cx, sy, cz)` (vanilla section coordinates, `sy = y >> 4`), in
|
|
/// `chunk::index` order, with every block a view of an earlier time shows otherwise put
|
|
/// back to its real state.
|
|
pub fn live_section_states(&self, cx: i32, sy: i32, cz: i32, states: &mut [u32; 4096]) {
|
|
let Some(log) = &self.log else {
|
|
return;
|
|
};
|
|
if !log.shows_in_section(cx, sy, cz) {
|
|
return;
|
|
}
|
|
for ([x, y, z], real) in log.real_in_section(cx, sy, cz) {
|
|
states[crate::chunk::index(x, y, z)] = real;
|
|
}
|
|
}
|
|
/// [`Self::motion_blocking`] over the real blocks: a mod's ground query, whatever a view
|
|
/// of an earlier time shows.
|
|
pub fn live_motion_blocking(
|
|
&self,
|
|
x: i32,
|
|
z: i32,
|
|
blocks: impl Fn(BlockStateId) -> bool,
|
|
) -> i32 {
|
|
if !self.view_shows_in_column(x >> 4, z >> 4) {
|
|
return self.motion_blocking(x, z, blocks);
|
|
}
|
|
(MIN_Y..MIN_Y + (SECTIONS as i32) * 16)
|
|
.rev()
|
|
.find(|&y| blocks(self.live_block(x, y, z)))
|
|
.map_or(MIN_Y, |y| y + 1)
|
|
}
|
|
/// Whether a block of the box `lo..=hi` may match, from the palettes of
|
|
/// the sections it reaches (a palette of the whole registry may hold
|
|
/// anything): `false` means [`Self::block`] matches in none of its cells,
|
|
/// so a scan over them can stop before reading one.
|
|
pub fn may_hold(
|
|
&self,
|
|
lo: [i32; 3],
|
|
hi: [i32; 3],
|
|
mut matches: impl FnMut(BlockStateId) -> bool,
|
|
) -> bool {
|
|
let top = MIN_Y + SECTIONS as i32 * 16 - 1;
|
|
// Heights outside the sections read as state 0.
|
|
if (lo[1] < MIN_Y || hi[1] > top) && matches(BlockStateId(0)) {
|
|
return true;
|
|
}
|
|
let sections = (lo[1].max(MIN_Y) - MIN_Y) >> 4..=(hi[1].min(top) - MIN_Y) >> 4;
|
|
for cx in lo[0] >> 4..=hi[0] >> 4 {
|
|
for cz in lo[2] >> 4..=hi[2] >> 4 {
|
|
let Some(chunk) = self.chunks.get(&(cx, cz)) else {
|
|
if matches(self.air) {
|
|
return true;
|
|
}
|
|
continue;
|
|
};
|
|
for s in sections.clone() {
|
|
let blocks = &chunk.sections[s as usize].blocks;
|
|
if blocks.is_global() || blocks.maybe_has(|v| matches(BlockStateId(v))) {
|
|
return true;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
false
|
|
}
|
|
/// The block entities to tick this tick, in order (`BlockEntities::tickers`).
|
|
pub fn block_entity_tickers(
|
|
&mut self,
|
|
) -> std::sync::Arc<Vec<(crate::block_entities::Pos, u32)>> {
|
|
let (chunks, air) = (&self.chunks, self.air);
|
|
self.block_entities.tickers(|(x, y, z)| {
|
|
chunks
|
|
.get(&(x >> 4, z >> 4))
|
|
.map_or(air, |chunk| chunk.block(x & 15, y, z & 15))
|
|
.0
|
|
})
|
|
}
|
|
pub fn light(&self, x: i32, y: i32, z: i32) -> u8 {
|
|
self.chunks
|
|
.get(&(x >> 4, z >> 4))
|
|
.map_or(0xF0, |chunk| chunk.light(x & 15, y, z & 15))
|
|
}
|
|
pub fn is_air(&self, state: BlockStateId) -> bool {
|
|
state == self.air
|
|
}
|
|
pub fn loaded(&self, x: i32, z: i32) -> bool {
|
|
self.chunks.contains_key(&(x >> 4, z >> 4))
|
|
}
|
|
}
|
|
|
|
/// The game rules and difficulty a player's health reads (`Player.isInvulnerableTo`,
|
|
/// natural regeneration), kept with the world they belong to.
|
|
#[derive(Clone, Copy, Debug)]
|
|
pub struct HealthRules {
|
|
pub difficulty: horizon_world::food::Difficulty,
|
|
pub natural_regeneration: bool,
|
|
/// The `drowning_damage`, `fall_damage`, `fire_damage` and
|
|
/// `freeze_damage` rules `Player.isInvulnerableTo` reads.
|
|
pub drowning_damage: bool,
|
|
pub fall_damage: bool,
|
|
pub fire_damage: bool,
|
|
pub freeze_damage: bool,
|
|
}
|
|
impl Default for HealthRules {
|
|
fn default() -> Self {
|
|
Self {
|
|
difficulty: horizon_world::food::Difficulty::Normal,
|
|
natural_regeneration: true,
|
|
drowning_damage: true,
|
|
fall_damage: true,
|
|
fire_damage: true,
|
|
freeze_damage: true,
|
|
}
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::World;
|
|
use crate::chunk::Chunk;
|
|
use horizon_world::registry::BlockStateId;
|
|
use std::sync::Arc;
|
|
|
|
#[test]
|
|
fn changed_column_uses_world_section_coordinates_and_stays_bounded() {
|
|
let mut changes = super::ModChanges::default();
|
|
changes.column(2, -3);
|
|
let (sections, overflow) = changes.take();
|
|
assert!(!overflow);
|
|
assert_eq!(sections.len(), crate::chunk::SECTIONS);
|
|
for sy in
|
|
(crate::chunk::MIN_Y >> 4)..(crate::chunk::MIN_Y >> 4) + crate::chunk::SECTIONS as i32
|
|
{
|
|
assert!(sections.contains(&(2, sy, -3)));
|
|
}
|
|
for x in 0..12 {
|
|
changes.column(x, 0);
|
|
}
|
|
assert!(changes.take().1);
|
|
}
|
|
|
|
/// A box misses a state only where no section it reaches lists it, and
|
|
/// unloaded columns or heights past the world count as their air.
|
|
#[test]
|
|
fn may_hold_reads_the_palettes_of_the_reached_sections() {
|
|
let mut world = World::new(BlockStateId(0), 0);
|
|
let mut chunk = Chunk::empty(0, 0);
|
|
chunk.set(3, 70, 3, 9);
|
|
world.chunks.insert((0, 0), Arc::new(chunk));
|
|
let nine = |s: BlockStateId| s.0 == 9;
|
|
// The section of y 64..80 holds 9, the one below does not.
|
|
assert!(world.may_hold([0, 64, 0], [1, 65, 1], nine));
|
|
assert!(world.may_hold([10, 79, 10], [12, 80, 12], nine));
|
|
assert!(!world.may_hold([0, 50, 0], [15, 63, 15], nine));
|
|
// A box over the unloaded column next door sees only air.
|
|
assert!(!world.may_hold([16, 70, 0], [17, 71, 1], nine));
|
|
assert!(world.may_hold([16, 70, 0], [17, 71, 1], |s| s.0 == 0));
|
|
// Past the top, and the palette of air below it.
|
|
assert!(!world.may_hold([0, 400, 0], [0, 401, 0], nine));
|
|
assert!(world.may_hold([0, 400, 0], [0, 401, 0], |s| s.0 == 0));
|
|
}
|
|
}
|