Merge remote-tracking branch 'origin/main' into feat/terrain-lod

# Conflicts:
#	crates/horizon-client/src/gfx.rs
This commit is contained in:
Cosmic
2026-10-18 05:31:37 -04:00
174 changed files with 14659 additions and 1614 deletions
Generated
+2
View File
@@ -1539,6 +1539,7 @@ dependencies = [
"horizon-world",
"serde_json",
"sha1",
"sha2",
]
[[package]]
@@ -1569,6 +1570,7 @@ dependencies = [
name = "horizon-server-files"
version = "0.1.0"
dependencies = [
"base64",
"horizon-core",
"horizon-protocol",
"horizon-world",
+1 -1
View File
@@ -37,7 +37,7 @@ miniz_oxide = "0.8"
ab_glyph = "0.2.32"
log = "0.4"
chrono = { version = "0.4.42", default-features = false, features = ["clock", "std"] }
flate2 = { version = "1.1.10", default-features = false, features = ["rust_backend"] }
flate2 = { version = "1.1.10", default-features = false, features = ["zlib-rs", "runtime_detection"] }
horizon-theme = { path = "../horizon-theme" }
# Opt-in data collection: the game keeps, the launcher sends (docs/telemetry.md).
horizon-telemetry = { path = "../horizon-telemetry", default-features = false }
@@ -0,0 +1,99 @@
//! The Rust side of tools/test_block_entity_tickers_parity.py: the ops of
//! `VanillaBlockEntityTickerOracle` on `BlockEntities`, as `World` drives it
//! (a state write calls `state_changed`), printing the tick order.
use horizon_client::{
block_entities::{BlockEntities, Pos, Ticking},
containers::BlockEntity,
};
use std::collections::HashMap;
/// State ids of the fixture: 0 air, 1 a block whose block entity ticks, 2 a
/// jukebox without a record, 3 a block entity that never ticks (a chest).
fn state(name: &str) -> u32 {
match name {
"chest" | "barrel" => 3,
"jukebox" => 2,
_ => 1,
}
}
fn entity(name: &str) -> BlockEntity {
if name.starts_with("jukebox") {
// The game makes a jukebox's block entity when a record goes in.
return BlockEntity::Jukebox(Default::default());
}
BlockEntity::for_block(&format!("minecraft:{name}"))
.unwrap_or_else(|| panic!("no block entity for {name}"))
}
fn main() {
let args: Vec<String> = std::env::args().collect();
let input = std::fs::read_to_string(&args[1]).expect("input");
let mut out = String::new();
let mut entities = BlockEntities::default();
let mut states: HashMap<Pos, u32> = HashMap::new();
let mut kinds: HashMap<Pos, String> = HashMap::new();
let table = vec![Ticking::No, Ticking::Yes, Ticking::Idle, Ticking::No];
for line in input.lines() {
let w: Vec<&str> = line.split_whitespace().collect();
let pos = |i: usize| -> Pos {
let n = |j: usize| w[i + j].parse::<i32>().expect("coordinate");
(n(0), n(1), n(2))
};
match w[0] {
"reset" => {
entities = BlockEntities::default();
entities.set_states(table.clone());
states.clear();
kinds.clear();
}
"load" => {
let mut chunk = Vec::new();
for i in (3..w.len()).step_by(4) {
let p = pos(i + 1);
states.insert(p, state(w[i]));
kinds.insert(p, w[i].to_owned());
chunk.push((p, entity(w[i])));
}
entities.load_chunk(chunk);
}
"place" => {
let p = pos(2);
// World::set, then the game adds the block entity.
let old = states.insert(p, state(w[1])).unwrap_or(0);
kinds.insert(p, w[1].to_owned());
entities.state_changed(p, old, state(w[1]));
entities.insert(p, entity(w[1]));
}
"replace" => {
let p = pos(1);
entities.insert(p, entity(&kinds[&p]));
}
"remove" => {
let p = pos(1);
entities.remove(&p);
let old = states.insert(p, 0).unwrap_or(0);
entities.state_changed(p, old, 0);
}
"record" => {
let p = pos(1);
let s = if w[4] == "1" { 1 } else { 2 };
let old = states.insert(p, s).unwrap_or(0);
entities.state_changed(p, old, s);
}
"unload" => {
let c = (w[1].parse::<i32>().unwrap(), w[2].parse::<i32>().unwrap());
entities.retain(|p, _| (p.0 >> 4, p.2 >> 4) != c);
}
"tick" => {
out.push_str("tick");
for (p, _) in entities.tickers(|p| states.get(&p).copied().unwrap_or(0)) {
out.push_str(&format!(" {},{},{}", p.0, p.1, p.2));
}
out.push('\n');
}
other => panic!("unknown op {other}"),
}
}
std::fs::write(&args[2], out).expect("output");
}
+3 -1
View File
@@ -128,7 +128,9 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
eprintln!("[lan] {packet:?}");
}
}
HostEvent::Chat(line) | HostEvent::Warn(line) => println!("{line}"),
HostEvent::Chat { line, .. } | HostEvent::Warn(line) | HostEvent::Error(line) => {
println!("{line}")
}
HostEvent::Left(_) => {}
}
}
@@ -999,6 +999,7 @@ fn main() -> horizon_client::Result<()> {
hero: false,
uuid: PLAYER_UUID,
allies: Default::default(),
remote: false,
}
});
let mut scratch = LegacyRandom::new(0);
@@ -0,0 +1,263 @@
//! The `entity_portals` section scan only: `may_hold_portal` over synthetic
//! entity reaches, with the per-tick palette map against the resident cache.
//! Run with prepared client resources:
//! cargo run --profile fast -p horizon-client --example portal_scan_bench -- RESOURCES
use horizon_client::{
blocks::BlockFacts,
chunk::{Chunk, MIN_Y, SECTIONS, Section},
fast_hash::FxHashMap,
portal_sections::PortalSections,
};
use horizon_core::{
geometry::{Aabb, Vec3},
position::BlockPos,
};
use horizon_world::{level::Behaviours, registry::BlockStateId};
use std::{hint::black_box, path::Path, sync::Arc, time::Instant};
/// `Game::swept_portal`'s reach (`Entity.checkInsideBlocks`'s swept box).
fn reach(from: Vec3, to: Vec3, width: f32, height: f32) -> Aabb {
let half = f64::from(width) / 2.0;
let bounds = Aabb::new(
Vec3::new(to.x - half, to.y, to.z - half),
Vec3::new(to.x + half, to.y + f64::from(height), to.z + half),
)
.deflate(Vec3::new(1.0e-5, 1.0e-5, 1.0e-5));
bounds
.union_bounds(bounds.move_by(from.subtract(to)))
.inflate(Vec3::new(1.0, 1.0, 1.0))
}
fn sections(reach: Aabb) -> (i64, i32, i32, i32, i32, i32, i32) {
let (min, max) = (reach.min_position(), reach.max_position());
let (min, max) = (BlockPos::containing(min), BlockPos::containing(max));
let top = SECTIONS as i32 - 1;
let (x0, x1) = (min.x >> 4, max.x >> 4);
let (z0, z1) = (min.z >> 4, max.z >> 4);
let (y0, y1) = (
((min.y - MIN_Y) >> 4).clamp(0, top),
((max.y - MIN_Y) >> 4).clamp(0, top),
);
let count = (i64::from(x1) - i64::from(x0) + 1)
* (i64::from(y1) - i64::from(y0) + 1)
* (i64::from(z1) - i64::from(z0) + 1);
(count, x0, x1, y0, y1, z0, z1)
}
/// The original `Game::may_hold_portal`: per-tick `seen`, palette per section.
fn may_hold_portal_baseline(
reach: Aabb,
world: &FxHashMap<(i32, i32), Arc<Chunk>>,
seen: &mut FxHashMap<(i32, i32, i32), bool>,
behaviours: &Behaviours,
) -> bool {
let (count, x0, x1, y0, y1, z0, z1) = sections(reach);
if count > 64 {
return true;
}
(x0..=x1).any(|cx| {
(z0..=z1).any(|cz| {
(y0..=y1).any(|sy| {
*seen.entry((cx, sy, cz)).or_insert_with(|| {
world
.get(&(cx, cz))
.and_then(|c| c.sections.get(sy as usize))
.is_some_and(|s| {
s.blocks
.maybe_has(|v| behaviours.portal_axis(BlockStateId(v)).is_some())
})
})
})
})
})
}
/// The cached `Game::may_hold_portal`: one mask per resident chunk.
fn may_hold_portal_cached(
reach: Aabb,
world: &FxHashMap<(i32, i32), Arc<Chunk>>,
cache: &mut PortalSections,
behaviours: &Behaviours,
) -> bool {
let (count, x0, x1, y0, y1, z0, z1) = sections(reach);
if count > 64 {
return true;
}
let mut y_mask = 0u32;
for sy in y0..=y1 {
y_mask |= 1 << sy;
}
(x0..=x1).any(|cx| {
(z0..=z1).any(|cz| {
world.get(&(cx, cz)).is_some_and(|chunk| {
cache.get((cx, cz), chunk, |v| {
behaviours.portal_axis(BlockStateId(v)).is_some()
}) & y_mask
!= 0
})
})
})
}
fn main() -> horizon_client::Result<()> {
let root = std::env::args()
.nth(1)
.ok_or("expected prepared client resource directory")?;
let start = Instant::now();
let registry = horizon_world::level::data::load_registry(Path::new(&root))?;
let (facts, behaviours) = BlockFacts::load_pair(Path::new(&root), &registry)?;
println!(
"resource_load_ms={:.3}",
start.elapsed().as_secs_f64() * 1000.0
);
let len = registry.len() as u32;
let portal: Vec<u32> = (0..len)
.filter(|&id| behaviours.portal_axis(BlockStateId(id)).is_some())
.collect();
let inactive_states: Vec<u32> = (0..len)
.filter(|&id| behaviours.portal_axis(BlockStateId(id)).is_none())
.collect();
let _ = &facts;
let portal_state = *portal
.first()
.ok_or("no nether portal block state in the registry")?;
println!("portal_states={}", portal.len());
// 500 entities spread over a 17x17 chunk world. Their reaches touch 1-4
// sections, as an item or a mob standing in or stepping into a portal does.
let grid = 17;
let base = -(grid / 2) * 16;
let entities: Vec<(Vec3, Vec3, f32, f32)> = (0..500)
.map(|i| {
let x = base + (i % grid) * 16 + (i % 5);
let z = base + (i / grid % grid) * 16 + (i % 7);
let y = 64 + (i % 3) * 16;
let from = Vec3::new(f64::from(x), f64::from(y), f64::from(z));
let to = from.add_vector(Vec3::new(0.1, 0.0, 0.07));
(from, to, 0.25, 0.25)
})
.collect();
let reaches: Vec<Aabb> = entities
.iter()
.map(|&(from, to, w, h)| reach(from, to, w, h))
.collect();
for (name, palette, portals_every) in [
("sparse", 1usize, 0usize),
("dense", 128, 0),
("global", 300, 0),
("dense_portal", 128, 5),
] {
let start = Instant::now();
let mut world: FxHashMap<(i32, i32), Arc<Chunk>> = FxHashMap::default();
for czi in 0..grid {
for cxi in 0..grid {
let (cx, cz) = (-(grid / 2) + cxi, -(grid / 2) + czi);
let mut chunk = Chunk::empty(cx, cz);
for (i, section) in chunk.sections.iter_mut().enumerate() {
let values: [u32; 4096] = std::array::from_fn(|j| {
if portals_every > 0 && i % portals_every == 0 && j == 0 {
portal_state
} else {
inactive_states[(j * 7 + i) % palette.min(inactive_states.len())]
}
});
Arc::make_mut(section).blocks = Section::from_blocks(&values);
}
world.insert((cx, cz), Arc::new(chunk));
}
}
println!(
"{name} fixture_ms={:.3}",
start.elapsed().as_secs_f64() * 1000.0
);
let keys: Vec<_> = world.keys().copied().collect();
let portal_chunks: Vec<(i32, i32)> = keys
.iter()
.copied()
.filter(|&(cx, cz)| {
world[&(cx, cz)]
.sections
.iter()
.any(|s| s.blocks.maybe_has(|v| v == portal_state))
})
.collect();
println!("{name} portal_chunks={}", portal_chunks.len());
// The global palette's maybe_has walks the whole ID range, so rescanning
// every chunk each tick (cold/reload/edit_all) is intractable; those rows
// are only meaningful for the palettes whose scans are bounded.
let workloads: &[(&str, usize)] = if name == "global" {
&[("steady", 0), ("edit_1pct", 3)]
} else {
&[
("steady", 0),
("cold", 0),
("reload", 0),
("edit_1pct", 3),
("edit_all", 289),
]
};
for &(workload, changed) in workloads {
let mut baseline = Vec::new();
let mut candidate = Vec::new();
let mut cache = PortalSections::default();
let (mut base_hits, mut cand_hits) = (0u64, 0u64);
for sample in 0..8 {
for cached in if sample % 2 == 0 {
[false, true]
} else {
[true, false]
} {
let start = Instant::now();
let mut result = 0u64;
for tick in 0..300 {
if cached && workload == "cold" {
cache = PortalSections::default();
}
if cached && workload == "reload" {
cache.clear();
}
for key in keys.iter().take(changed) {
Arc::make_mut(world.get_mut(key).unwrap()).set(
0,
MIN_Y,
0,
inactive_states[tick % inactive_states.len()],
);
}
let mut seen = FxHashMap::default();
for reach in &reaches {
let hit = if cached {
may_hold_portal_cached(*reach, &world, &mut cache, &behaviours)
} else {
may_hold_portal_baseline(*reach, &world, &mut seen, &behaviours)
};
result += hit as u64;
}
}
if cached {
cache = PortalSections::default();
cand_hits += black_box(result);
} else {
base_hits += black_box(result);
}
if sample > 0 {
let us = start.elapsed().as_secs_f64() * 1e6 / 300.0;
if cached {
candidate.push(us);
} else {
baseline.push(us);
}
}
}
}
assert_eq!(
base_hits, cand_hits,
"{name} {workload}: cached may_hold_portal diverged"
);
println!("{name} {workload} baseline_us={baseline:.3?} candidate_us={candidate:.3?}");
}
}
println!("chunk_wrapper_bytes={}", std::mem::size_of::<Chunk>());
Ok(())
}
@@ -120,22 +120,8 @@ fn main() -> Result<()> {
step("mesh tables");
let collision = collisions::load(&root, assets.registry)?;
step("collision");
let motion = MotionResources::load(&root, &assets)?;
let motion = MotionResources::load_with_facts(&root, &assets, &facts)?;
step("motion");
for name in [
"worldgen/blocks/block-properties.nbt",
"worldgen/blocks/cached-collision.nbt",
"worldgen/blocks/cached-support.nbt",
"cached-collision.nbt",
"occlusion.nbt",
"movement-properties.nbt",
] {
let bytes = std::fs::read(root.join(name))?;
let tree = horizon_world::nbt::read_named(&bytes, horizon_world::nbt::Limits::tables())?;
step(&format!(" tree of {name}"));
drop((tree, bytes));
step(" dropped");
}
let terrain = VanillaTerrain::new(&root.join("worldgen"), assets.registry, &biomes, 1234)?;
step("worldgen");
println!(
@@ -0,0 +1,40 @@
//! Tooltip display visibility oracle companion for tools/test_tooltip_display_parity.py.
use horizon_client::{item_tooltip::TooltipDisplay, items::ItemStack};
use horizon_world::nbt::Tag;
use std::{error::Error, fmt::Write};
fn main() -> Result<(), Box<dyn Error>> {
let args: Vec<String> = std::env::args().collect();
let mut output = String::new();
for line in std::fs::read_to_string(&args[1])?.lines() {
let fields: Vec<&str> = line.split('\t').collect();
let hide_tooltip: bool = fields[0].parse()?;
let creative: bool = fields[1].parse()?;
let hide_attributes: bool = fields[2].parse()?;
let mut component = Vec::new();
if hide_tooltip {
component.push(("hide_tooltip", Tag::Byte(1)));
}
if hide_attributes {
component.push((
"hidden_components",
Tag::List(vec![Tag::String("minecraft:attribute_modifiers".into())]),
));
}
let mut stack = ItemStack::new("minecraft:diamond_sword", 1);
if !component.is_empty() {
stack
.data_mut()
.set_other("minecraft:tooltip_display", Some(Tag::compound(component)));
}
let display = TooltipDisplay::for_stack(&stack);
writeln!(
output,
"{}\t{}",
display.name_visible(creative),
display.shows("minecraft:attribute_modifiers")
)?;
}
std::fs::write(&args[2], output)?;
Ok(())
}
+16 -57
View File
@@ -2,14 +2,13 @@ use crate::Result;
use horizon_world::{
DATA_VERSION,
heightmap::HeightmapState,
nbt::Tag,
registry::{BlockRegistry, BlockStateId},
worldgen::{tags::TagDefinitions, terrain::TerrainBlockStates},
};
use serde_json::Value;
use std::{
collections::BTreeSet,
fs::{self, File},
fs::File,
io::{self, BufReader},
path::Path,
sync::Arc,
@@ -74,24 +73,6 @@ pub struct Assets {
fn invalid(message: &str) -> io::Error {
io::Error::new(io::ErrorKind::InvalidData, message)
}
fn tag(value: &Value) -> Result<Tag> {
Ok(match value {
Value::String(value) => Tag::String(value.as_str().into()),
Value::Number(value) => Tag::Int(i32::try_from(
value
.as_i64()
.ok_or_else(|| invalid("invalid registry number"))?,
)?),
Value::Array(values) => Tag::List(values.iter().map(tag).collect::<Result<_>>()?),
Value::Object(values) => Tag::Compound(
values
.iter()
.map(|(name, value)| Ok((name.as_str().into(), tag(value)?)))
.collect::<Result<_>>()?,
),
_ => return Err(invalid("unsupported registry value").into()),
})
}
impl Assets {
pub fn load(root: &Path) -> Result<Self> {
let manifest: Value = serde_json::from_reader(BufReader::new(File::open(
@@ -100,23 +81,8 @@ impl Assets {
if manifest["data_version"].as_i64() != Some(i64::from(DATA_VERSION)) {
return Err(invalid("resources do not match Horizon's pinned data version").into());
}
let facts: Value = serde_json::from_slice(&fs::read(root.join("facts.json"))?)?;
let states = facts["states"]
.as_array()
.ok_or_else(|| invalid("missing registry state facts"))?;
let registry = BlockRegistry::from_nbt(&Tag::compound([
("DataVersion", Tag::Int(DATA_VERSION)),
(
"states",
Tag::List(
states
.iter()
.map(|state| tag(&state[4]))
.collect::<Result<_>>()?,
),
),
("defaults", tag(&facts["defaults"])?),
]))?;
let (registry, flags) =
BlockRegistry::from_facts_json_with_flags(File::open(root.join("facts.json"))?)?;
let bundle: Value =
serde_json::from_reader(BufReader::new(File::open(root.join("block-tags.json"))?))?;
let mut definitions = TagDefinitions::default();
@@ -132,7 +98,7 @@ impl Assets {
)?;
}
let built =
definitions.build(|name, _| facts["defaults"].get(name).map(|_| name.to_owned()))?;
definitions.build(|name, _| registry.default_state(name).map(|_| name.to_owned()))?;
if !built.missing.is_empty() {
return Err(invalid("unresolved block tags").into());
}
@@ -158,27 +124,20 @@ impl Assets {
.cloned()
.collect();
let properties = Properties(Arc::new(
states
flags
.iter()
.map(|state| {
.enumerate()
.map(|(i, &(air, fluid))| {
let name = &registry
.state(BlockStateId(i as u32))
.ok_or_else(|| invalid("missing registry state"))?
.name;
Ok(StateFacts {
air: state[1]
.as_bool()
.ok_or_else(|| invalid("missing air fact"))?,
fluid: state[2]
.as_bool()
.ok_or_else(|| invalid("missing fluid fact"))?,
air_block: state[0].as_str() == Some("minecraft:air"),
motion: motion.contains(
state[0]
.as_str()
.ok_or_else(|| invalid("missing state name"))?,
),
no_leaves: no_leaves.contains(
state[0]
.as_str()
.ok_or_else(|| invalid("missing state name"))?,
),
air,
fluid,
air_block: name == "minecraft:air",
motion: motion.contains(name.as_str()),
no_leaves: no_leaves.contains(name.as_str()),
})
})
.collect::<Result<_>>()?,
@@ -187,6 +187,10 @@ pub const COMMANDS: &[Cmd] = &[
&[opt("radius", Ty::Num, "search radius in blocks (default 32)"), opt("type", Ty::Str, "entity type filter")], mcp: true, local: false),
cmd!("block", Observe, "block X Y Z", "the block state at a position", "",
["horizon-ctl block 10 64 -3"], &BLOCK_XYZ, mcp: true, local: false),
cmd!("light", Observe, "light X1 Y1 Z1 X2 Y2 Z2", "the stored sky and block light of a box",
"At most 32768 blocks per request. One hex digit per block in `sky` and `block`, x fastest, then z, then y; `.` where no chunk is loaded.",
["horizon-ctl light 0 64 0 15 70 15"],
&[p("x1", Ty::Int, "corner X"), p("y1", Ty::Int, "corner Y"), p("z1", Ty::Int, "corner Z"), p("x2", Ty::Int, "opposite X"), p("y2", Ty::Int, "opposite Y"), p("z2", Ty::Int, "opposite Z")], mcp: true, local: false),
cmd!("blocks", Observe, "blocks X1 Y1 Z1 X2 Y2 Z2", "the non-air blocks of a box, with counts per block",
"At most 32768 blocks per request.", ["horizon-ctl blocks 0 60 0 15 70 15"],
&[p("x1", Ty::Int, "corner X"), p("y1", Ty::Int, "corner Y"), p("z1", Ty::Int, "corner Z"), p("x2", Ty::Int, "opposite X"), p("y2", Ty::Int, "opposite Y"), p("z2", Ty::Int, "opposite Z")], mcp: true, local: false),
+395
View File
@@ -0,0 +1,395 @@
//! The world's block entities and the order they tick in: vanilla's
//! `Level.blockEntityTickers`, kept beside the block entity map so a tick
//! visits only the block entities that tick, in vanilla's order, instead of
//! scanning the whole map once per kind.
//!
//! The list follows `LevelChunk.updateBlockEntityTicker` and
//! `Level.tickBlockEntities`:
//! - a block entity whose block state has a ticker gets a slot at the end of
//! the list (through `pendingBlockEntityTickers`, so a slot made during a
//! tick first ticks on the next one);
//! - replacing the block entity at a position (`setBlockEntity`), or changing
//! its block state to another state with a ticker, keeps its slot
//! (`RebindableTickingBlockEntityWrapper.rebind`);
//! - removing it (`removeBlockEntity`), unloading its chunk
//! (`clearAllBlockEntities`) or changing its state to one without a ticker
//! (a jukebox losing its record) frees the slot; a later ticker there is
//! appended again;
//! - a loaded chunk's block entities are added in the iteration order of its
//! `Object2ObjectOpenHashMap<BlockPos, BlockEntity>`
//! (`registerAllBlockEntitiesAfterLevelLoad`), filled in the order the chunk
//! listed them.
//!
//! Which states tick is a table by state id, built by the game from the block
//! registry; whether a slot is made is decided when the slot is promoted at
//! the start of the next tick, from the block state then.
use crate::containers::BlockEntity;
use crate::fast_hash::{FxHashMap, FxHashSet};
use std::collections::HashMap;
pub type Pos = (i32, i32, i32);
/// What a block state's block entity does each tick (`BlockState.getTicker`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Ticking {
/// No ticker, and the block has no block entity that could have one.
#[default]
No,
/// A ticker.
Yes,
/// The block's block entity, but this state has no ticker (a jukebox
/// without a record): a state change to it frees the slot.
Idle,
}
#[derive(Default)]
pub struct BlockEntities {
map: HashMap<Pos, BlockEntity>,
/// `Level.blockEntityTickers`: positions and the slot each was given.
tickers: Vec<(Pos, u32)>,
/// `LevelChunk.tickersInLevel`: the live slot of each ticking position.
live: FxHashMap<Pos, u32>,
/// Positions that may need a slot, in the order vanilla would have made
/// it (`pendingBlockEntityTickers`), each with a token; decided at the
/// next promotion from the block state then.
added: Vec<(Pos, u32)>,
/// The token of each position's pending entry: an entry whose token is
/// not here any more was cancelled.
pending: FxHashMap<Pos, u32>,
next_slot: u32,
/// Whether a slot was freed since the list was last swept: otherwise
/// every slot in it is still live, unless its block entity is `out`.
freed: bool,
/// Positions whose block entity `take` took and `put` has not brought
/// back.
out: FxHashSet<Pos>,
/// `Ticking` by block state id; empty until the game builds it.
states: Vec<Ticking>,
}
impl std::ops::Deref for BlockEntities {
type Target = HashMap<Pos, BlockEntity>;
fn deref(&self) -> &Self::Target {
&self.map
}
}
impl<'a> IntoIterator for &'a BlockEntities {
type Item = (&'a Pos, &'a BlockEntity);
type IntoIter = std::collections::hash_map::Iter<'a, Pos, BlockEntity>;
fn into_iter(self) -> Self::IntoIter {
self.map.iter()
}
}
/// `Vec3i.hashCode`.
fn java_hash((x, y, z): Pos) -> i32 {
y.wrapping_add(z.wrapping_mul(31))
.wrapping_mul(31)
.wrapping_add(x)
}
/// `HashCommon.mix`.
fn mix(x: i32) -> usize {
let h = (x as u32).wrapping_mul(0x9E37_79B9);
(h ^ (h >> 16)) as usize
}
/// The order `values().forEach` visits a `new Object2ObjectOpenHashMap<>()`
/// keyed by these positions, put in this order (repeats keep their first
/// slot): open addressing with linear probing, a rehash to twice the size
/// past three quarters full, and iteration from the last slot down.
pub fn chunk_map_order(positions: impl IntoIterator<Item = Pos>) -> Vec<Pos> {
// HashCommon.arraySize(16, .75f), and maxFill of each size.
let mut slots: Vec<Option<Pos>> = vec![None; 32];
let max_fill = |n: usize| (n * 3).div_ceil(4).min(n - 1);
let mut size = 0;
for p in positions {
let mask = slots.len() - 1;
let mut at = mix(java_hash(p)) & mask;
let mut known = false;
while let Some(k) = slots[at] {
if k == p {
known = true;
break;
}
at = (at + 1) & mask;
}
if known {
continue;
}
slots[at] = Some(p);
// `if (size++ >= maxFill) rehash(arraySize(size + 1, f))`, which
// puts the keys back from the last slot down.
size += 1;
if size > max_fill(slots.len()) {
let n = ((size + 1) * 4).div_ceil(3).next_power_of_two();
let old = std::mem::replace(&mut slots, vec![None; n]);
for k in old.into_iter().rev().flatten() {
let mut at = mix(java_hash(k)) & (n - 1);
while slots[at].is_some() {
at = (at + 1) & (n - 1);
}
slots[at] = Some(k);
}
}
}
slots.into_iter().rev().flatten().collect()
}
impl BlockEntities {
/// Whether the ticking table has been built.
pub fn has_states(&self) -> bool {
!self.states.is_empty()
}
pub fn set_states(&mut self, states: Vec<Ticking>) {
self.states = states;
}
pub fn take_states(&mut self) -> Vec<Ticking> {
std::mem::take(&mut self.states)
}
pub fn ticking(&self, state: u32) -> Ticking {
self.states.get(state as usize).copied().unwrap_or_default()
}
fn next(&mut self) -> u32 {
let n = self.next_slot;
self.next_slot = n.wrapping_add(1);
n
}
/// A ticker may be made for `pos` now (`updateBlockEntityTicker`).
fn add(&mut self, pos: Pos) {
let token = self.next();
self.pending.insert(pos, token);
self.added.push((pos, token));
}
/// `removeBlockEntityTicker`: no slot, made or pending.
fn cancel(&mut self, pos: &Pos) {
self.freed |= self.live.remove(pos).is_some();
self.pending.remove(pos);
}
pub fn get_mut(&mut self, pos: &Pos) -> Option<&mut BlockEntity> {
self.map.get_mut(pos)
}
pub fn iter_mut(&mut self) -> impl Iterator<Item = (&Pos, &mut BlockEntity)> {
self.map.iter_mut()
}
pub fn values_mut(&mut self) -> impl Iterator<Item = &mut BlockEntity> {
self.map.values_mut()
}
/// `LevelChunk.setBlockEntity` (+ `addAndRegisterBlockEntity`): a new
/// block entity may get a slot; one replacing another keeps its slot.
pub fn insert(&mut self, pos: Pos, entity: BlockEntity) -> Option<BlockEntity> {
let old = self.map.insert(pos, entity);
if old.is_none() {
self.add(pos);
}
old
}
/// The block entity at `pos`, made by `make` when there is none.
pub fn get_or_insert_with(
&mut self,
pos: Pos,
make: impl FnOnce() -> BlockEntity,
) -> &mut BlockEntity {
if !self.map.contains_key(&pos) {
self.add(pos);
}
self.map.entry(pos).or_insert_with(make)
}
/// `LevelChunk.removeBlockEntity`: the block entity and its slot.
pub fn remove(&mut self, pos: &Pos) -> Option<BlockEntity> {
self.cancel(pos);
self.map.remove(pos)
}
/// The block entity at `pos`, out of the map for a while: its slot stays
/// for `put` to bring it back (a tick working on it).
pub fn take(&mut self, pos: &Pos) -> Option<BlockEntity> {
let taken = self.map.remove(pos);
if taken.is_some() {
self.out.insert(*pos);
}
taken
}
/// Brings back what `take` took, in its slot.
pub fn put(&mut self, pos: Pos, entity: BlockEntity) {
self.out.remove(&pos);
if self.map.insert(pos, entity).is_none()
&& !self.live.contains_key(&pos)
&& !self.pending.contains_key(&pos)
{
self.add(pos);
}
}
/// Removes the block entities `keep` refuses, and their slots
/// (`clearAllBlockEntities` of unloaded chunks).
pub fn retain(&mut self, mut keep: impl FnMut(&Pos, &mut BlockEntity) -> bool) {
let (live, pending, freed) = (&mut self.live, &mut self.pending, &mut self.freed);
self.map.retain(|p, e| {
let kept = keep(p, e);
if !kept {
*freed |= live.remove(p).is_some();
pending.remove(p);
}
kept
});
}
pub fn clear(&mut self) {
self.map.clear();
self.tickers.clear();
self.live.clear();
self.added.clear();
self.pending.clear();
self.out.clear();
self.freed = false;
}
/// A loaded or generated chunk's block entities, in the order the chunk
/// lists them; they tick in its block entity map's order
/// (`registerAllBlockEntitiesAfterLevelLoad`).
pub fn load_chunk(&mut self, entities: Vec<(Pos, BlockEntity)>) {
let order = chunk_map_order(entities.iter().map(|(p, _)| *p));
for (p, e) in entities {
self.map.insert(p, e);
}
for p in order {
self.add(p);
}
}
/// `LevelChunk.setBlockState` on a block entity's position, from state
/// `old` to `new`: a ticker made, kept or dropped.
pub fn state_changed(&mut self, pos: Pos, old: u32, new: u32) {
if self.states.is_empty() || !self.map.contains_key(&pos) {
return;
}
match self.ticking(new) {
// A new ticker, unless one was made or is pending (rebound).
Ticking::Yes => {
if self.ticking(old) != Ticking::Yes && !self.live.contains_key(&pos) {
self.add(pos);
}
}
Ticking::Idle => self.cancel(&pos),
// Another block: the game removes or replaces the block entity.
Ticking::No => {}
}
}
/// The start of `Level.tickBlockEntities`: pending slots join the list
/// and freed ones leave it. `state` reads the block state at a position.
/// Returns the slots to tick, in order; check each with `is_live` before
/// ticking it, as the ticks before it can free it.
pub fn tickers(&mut self, state: impl Fn(Pos) -> u32) -> Vec<(Pos, u32)> {
for (pos, token) in std::mem::take(&mut self.added) {
if self.pending.get(&pos) != Some(&token) {
continue;
}
self.pending.remove(&pos);
if self.live.contains_key(&pos)
|| !self.map.contains_key(&pos)
|| self.ticking(state(pos)) != Ticking::Yes
{
continue;
}
let slot = self.next();
self.live.insert(pos, slot);
self.tickers.push((pos, slot));
}
if !std::mem::take(&mut self.freed) && self.out.is_empty() {
return self.tickers.clone();
}
self.out.clear();
let (live, map) = (&mut self.live, &self.map);
self.tickers.retain(|(p, slot)| {
let mine = live.get(p) == Some(slot);
if mine && !map.contains_key(p) {
live.remove(p);
}
mine && map.contains_key(p)
});
self.tickers.clone()
}
/// Whether a slot from `tickers` still ticks.
pub fn is_live(&self, (pos, slot): (Pos, u32)) -> bool {
self.live.get(&pos) == Some(&slot) && self.map.contains_key(&pos)
}
/// Frees the slot at `pos` (the block entity stays).
pub fn forget(&mut self, pos: &Pos) {
self.cancel(pos);
}
}
#[cfg(test)]
mod tests {
use super::*;
fn hopper() -> BlockEntity {
BlockEntity::Chest(vec![None; 5])
}
/// States: 0 air, 1 ticks, 2 idle.
fn level() -> BlockEntities {
let mut b = BlockEntities::default();
b.set_states(vec![Ticking::No, Ticking::Yes, Ticking::Idle]);
b
}
fn order(b: &mut BlockEntities, states: &HashMap<Pos, u32>) -> Vec<Pos> {
b.tickers(|p| states.get(&p).copied().unwrap_or(0))
.into_iter()
.map(|(p, _)| p)
.collect()
}
#[test]
fn slots_follow_vanilla_lifecycle() {
let mut b = level();
let mut s = HashMap::new();
for p in [(0, 0, 0), (1, 0, 0), (2, 0, 0)] {
s.insert(p, 1);
b.insert(p, hopper());
}
assert_eq!(order(&mut b, &s), [(0, 0, 0), (1, 0, 0), (2, 0, 0)]);
// Replacing keeps the slot; removing and placing again appends.
b.insert((0, 0, 0), hopper());
b.remove(&(1, 0, 0));
b.insert((1, 0, 0), hopper());
assert_eq!(order(&mut b, &s), [(0, 0, 0), (2, 0, 0), (1, 0, 0)]);
// Take and put keep it; an idle state frees it, ticking again appends.
let e = b.take(&(0, 0, 0)).unwrap();
b.put((0, 0, 0), e);
assert_eq!(order(&mut b, &s), [(0, 0, 0), (2, 0, 0), (1, 0, 0)]);
s.insert((2, 0, 0), 2);
b.state_changed((2, 0, 0), 1, 2);
assert_eq!(order(&mut b, &s), [(0, 0, 0), (1, 0, 0)]);
s.insert((2, 0, 0), 1);
b.state_changed((2, 0, 0), 2, 1);
assert_eq!(order(&mut b, &s), [(0, 0, 0), (1, 0, 0), (2, 0, 0)]);
// A slot freed during a tick is not live any more.
let slots = b.tickers(|p| s.get(&p).copied().unwrap_or(0));
b.retain(|p, _| *p != (1, 0, 0));
assert!(b.is_live(slots[0]) && !b.is_live(slots[1]));
// A block entity taken and never brought back loses its slot.
b.take(&(0, 0, 0));
assert_eq!(order(&mut b, &s), [(2, 0, 0)]);
assert_eq!(order(&mut b, &s), [(2, 0, 0)]);
}
#[test]
fn chunk_loads_in_open_hash_map_order() {
// A few keys: their mixed hashes over 32 slots, read from the top.
let positions = [
(0, 64, 0),
(1, 64, 0),
(0, 64, 1),
(15, -64, 15),
(3, 70, 9),
];
let slot = |p: &Pos| mix(java_hash(*p)) & 31;
let mut expected = positions.to_vec();
expected.sort_by_key(|p| std::cmp::Reverse(slot(p)));
let distinct: std::collections::HashSet<usize> = positions.iter().map(slot).collect();
assert_eq!(distinct.len(), positions.len());
assert_eq!(chunk_map_order(positions), expected);
// Past 24 keys the table doubles; every key stays, once.
let many: Vec<Pos> = (0..100).map(|i| (i % 16, i / 16, 3)).collect();
let order = chunk_map_order(many.iter().copied().chain(many.iter().copied()));
assert_eq!(order.len(), 100);
}
}
+33 -22
View File
@@ -12,11 +12,11 @@
//! (blocks, entities, game time) as closures, so the parity fixture can drive
//! them with scripted inputs (`tools/test_block_entity_anim_parity.py`).
use crate::block_entity_render::BlockAnim;
use crate::fast_hash::FxHashMap;
use horizon_core::{
geometry::trig::{self, Mth},
random::{LegacyRandom, RandomSource},
};
use std::collections::HashMap;
/// `Direction` names by `get3DDataValue`.
pub const DIRECTIONS: [&str; 6] = ["down", "up", "north", "south", "west", "east"];
@@ -832,38 +832,44 @@ pub fn ticker(name: &str, prop: impl Fn(&str) -> Option<String>) -> Option<Ticke
/// The animated block entities of a level, by position.
#[derive(Clone, Debug)]
pub struct BlockEntityAnims {
pub chests: HashMap<[i32; 3], ChestLid>,
pub books: HashMap<[i32; 3], EnchantingBook>,
pub chests: FxHashMap<[i32; 3], ChestLid>,
pub books: FxHashMap<[i32; 3], EnchantingBook>,
/// `EnchantingTableBlockEntity.RANDOM`, shared by every table.
pub book_random: LegacyRandom,
pub shulkers: HashMap<[i32; 3], Shulker>,
pub bells: HashMap<[i32; 3], Bell>,
pub conduits: HashMap<[i32; 3], Conduit>,
pub skulls: HashMap<[i32; 3], Skull>,
pub pots: HashMap<[i32; 3], PotWobble>,
pub gateways: HashMap<[i32; 3], EndGateway>,
pub shulkers: FxHashMap<[i32; 3], Shulker>,
pub bells: FxHashMap<[i32; 3], Bell>,
pub conduits: FxHashMap<[i32; 3], Conduit>,
pub skulls: FxHashMap<[i32; 3], Skull>,
pub pots: FxHashMap<[i32; 3], PotWobble>,
pub gateways: FxHashMap<[i32; 3], EndGateway>,
/// The integrated server's copies of the gateways (`portalTick`).
pub gateway_servers: HashMap<[i32; 3], EndGateway>,
pub gateway_servers: FxHashMap<[i32; 3], EndGateway>,
/// The client level's random (conduit particles).
pub random: LegacyRandom,
/// [`Ticker`] by block state id (see [`BlockEntityAnims::classify`]).
pub kinds: Vec<Option<Ticker>>,
/// The drawn block entities with a ticker, sorted by position, and the
/// renderer's block entity revision they were read at.
pub present: Vec<([i32; 3], Ticker)>,
pub present_revision: Option<u64>,
}
impl Default for BlockEntityAnims {
fn default() -> Self {
Self {
chests: HashMap::new(),
books: HashMap::new(),
chests: FxHashMap::default(),
books: FxHashMap::default(),
book_random: LegacyRandom::new(0x626f6f6b),
shulkers: HashMap::new(),
bells: HashMap::new(),
conduits: HashMap::new(),
skulls: HashMap::new(),
pots: HashMap::new(),
gateways: HashMap::new(),
gateway_servers: HashMap::new(),
shulkers: FxHashMap::default(),
bells: FxHashMap::default(),
conduits: FxHashMap::default(),
skulls: FxHashMap::default(),
pots: FxHashMap::default(),
gateways: FxHashMap::default(),
gateway_servers: FxHashMap::default(),
random: LegacyRandom::new(0x6c6576656c),
kinds: Vec::new(),
present: Vec::new(),
present_revision: None,
}
}
}
@@ -877,15 +883,20 @@ impl BlockEntityAnims {
.and_then(|s| ticker(&s.name, |k| s.properties.get(k).cloned()))
})
.collect();
self.present_revision = None;
}
/// The ticker of a block state.
pub fn ticker(&self, state: u32) -> Option<Ticker> {
self.kinds.get(state as usize).copied().flatten()
}
/// Drops the state of block entities that are gone or changed kind:
/// `present` maps the loaded block entities to their tickers.
pub fn retain_present(&mut self, present: &HashMap<[i32; 3], Ticker>) {
let is = |p: &[i32; 3], f: fn(&Ticker) -> bool| present.get(p).is_some_and(f);
/// `present` holds the loaded block entities' tickers, sorted by position.
pub fn retain_present(&mut self, present: &[([i32; 3], Ticker)]) {
let is = |p: &[i32; 3], f: fn(&Ticker) -> bool| {
present
.binary_search_by_key(p, |(q, _)| *q)
.is_ok_and(|i| f(&present[i].1))
};
self.chests.retain(|p, _| is(p, |t| *t == Ticker::Lid));
self.books.retain(|p, _| is(p, |t| *t == Ticker::Book));
self.shulkers
+83 -5
View File
@@ -386,6 +386,12 @@ pub struct ChatScreen {
parse: Option<ParseResults>,
/// The completions at the cursor (`pendingSuggestions`): range start (bytes) and list.
pending: Option<(usize, Vec<Suggestion>)>,
/// Completions waiting for the server's (an `ask_server` node at the
/// cursor): `pendingSuggestions` is not done until they come.
awaiting: Option<Awaiting>,
/// The request to send (`ServerboundCommandSuggestionPacket`): id and
/// the command up to the cursor.
request: Option<(i32, String)>,
suggestions: Option<SuggestionList>,
usage: Vec<Text>,
usage_position: i32,
@@ -394,6 +400,16 @@ pub struct ChatScreen {
keep_suggestions: bool,
pub auto_suggestions: bool,
}
/// Local completions waiting for the server's reply to request `id`.
struct Awaiting {
id: i32,
/// The command up to the cursor, as sent.
truncated: String,
local: Vec<Suggestion>,
}
/// `ClientSuggestionProvider.pendingSuggestionsId`: one counter for the
/// connection, so a reply to an older request never matches.
static SUGGESTION_ID: std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(0);
/// `CommandSuggestions`' fill colour.
const FILL: i32 = -805306368;
fn byte_at(s: &str, chars: usize) -> usize {
@@ -442,6 +458,8 @@ impl ChatScreen {
history_pos: history_len,
parse: None,
pending: None,
awaiting: None,
request: None,
suggestions: None,
usage: Vec::new(),
usage_position: 0,
@@ -518,24 +536,84 @@ impl ChatScreen {
}
if cursor >= 1 && (self.suggestions.is_none() || !self.keep_suggestions) {
let parse = self.parse.as_ref().expect("parsed above");
let (range, list) = c
.dispatcher
.client_suggestions(parse, cursor_b, c.registries);
self.pending = Some((range.0, list));
self.update_usage_info(m, c);
let (range, list, ask) =
c.dispatcher
.client_suggestions_asking(parse, cursor_b, c.registries);
if ask {
// ClientSuggestionProvider.customSuggestion: the
// suggestions are done when the server answers.
let id = SUGGESTION_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
let truncated = command[..cursor_b].to_owned();
self.request = Some((id, truncated.clone()));
self.awaiting = Some(Awaiting {
id,
truncated,
local: list,
});
self.pending = None;
} else {
self.awaiting = None;
self.pending = Some((range.0, list));
self.update_usage_info(m, c);
}
}
} else if !command.chars().all(char::is_whitespace) {
let partial = &command[..cursor_b];
let mut builder = SuggestionsBuilder::new(partial, last_word_index(partial));
builder.suggest_matching(c.registries.players.iter().map(String::as_str));
let (range, list) = merge_suggestions(partial, builder.out);
self.awaiting = None;
self.pending = Some((range.0, list));
self.usage_width = 0;
self.usage_position = 0;
} else {
self.awaiting = None;
self.pending = None;
}
}
/// The completion request to send to the server, if one is waiting.
pub fn take_request(&mut self) -> Option<(i32, String)> {
self.request.take()
}
/// `ClientSuggestionProvider.completeCustomSuggestions`: the server's
/// completions for request `id`, with `range` in UTF-16 units of the
/// command sent. They join the local ones (`Suggestions.merge`) and the
/// pending suggestions are done.
pub fn server_suggestions(
&mut self,
m: &Measure,
c: &Commands,
id: i32,
range: (usize, usize),
list: Vec<(String, Option<String>)>,
) {
let Some(awaiting) = self.awaiting.take_if(|a| a.id == id) else {
return;
};
let input = &awaiting.truncated;
let byte = |units: usize| {
let mut n = 0;
input
.char_indices()
.find(|(_, ch)| {
let past = n >= units;
n += ch.len_utf16();
past
})
.map_or(input.len(), |(i, _)| i)
};
let range = (byte(range.0), byte(range.0 + range.1));
let mut all = awaiting.local;
all.extend(list.into_iter().map(|(text, tooltip)| Suggestion {
range,
text,
tooltip,
int_value: None,
}));
let (range, list) = merge_suggestions(input, all);
self.pending = Some((range.0, list));
self.update_usage_info(m, c);
}
/// `CommandSuggestions.updateUsageInfo`.
fn update_usage_info(&mut self, m: &Measure, c: &Commands) {
let Some(parse) = &self.parse else { return };
+55
View File
@@ -230,3 +230,58 @@ fn mod_commands_are_coloured_and_complete_like_vanilla_ones() {
screen.key(&m, &c, &[], winit::keyboard::KeyCode::Tab, false, false);
assert_eq!(screen.value(), "/coords");
}
#[test]
fn ask_server_nodes_wait_for_the_servers_completions() {
// ClientSuggestionProvider.customSuggestion: an `ask_server` node at the
// cursor sends the command so far, and the list is done with the reply.
let font = font();
let m = Measure(&font);
let registries = Registries {
permission: 4,
..Registries::default()
};
let mut d = crate::command::vanilla::game_dispatcher().clone();
let child = |d: &crate::command::Dispatcher, n: usize, name: &str| {
d.nodes[n]
.children
.iter()
.copied()
.find(|&c| d.nodes[c].name() == name)
.expect(name)
};
let id = child(&d, child(&d, child(&d, 0, "bossbar"), "get"), "id");
d.nodes[id].suggests = Some(crate::command::Suggests::AskServer);
let c = Commands {
dispatcher: &d,
registries: &registries,
};
let tab = |screen: &mut ChatScreen| {
screen.key(&m, &c, &[], winit::keyboard::KeyCode::Tab, false, false);
};
let mut screen = ChatScreen::new(&m, &c, "", 0, 640, 360);
screen.type_text(&m, &c, "/bossbar get pt");
let (request, sent) = screen.take_request().expect("the server is asked");
assert_eq!(sent, "/bossbar get pt");
assert_eq!(screen.take_request(), None);
// Nothing to complete until the reply.
tab(&mut screen);
assert_eq!(screen.value(), "/bossbar get pt");
// A reply to an older request is dropped; the range is in UTF-16 units.
let reply = |text: &str| vec![(text.to_owned(), None)];
screen.server_suggestions(&m, &c, request - 1, (13, 2), reply("pt6:old"));
tab(&mut screen);
assert_eq!(screen.value(), "/bossbar get pt");
screen.server_suggestions(&m, &c, request, (13, 2), reply("pt6:check"));
tab(&mut screen);
assert_eq!(screen.value(), "/bossbar get pt6:check");
// Without the server's provider the local list is done at once.
let local = crate::command::vanilla::game_dispatcher();
let c = Commands {
dispatcher: local,
registries: &registries,
};
let mut screen = ChatScreen::new(&m, &c, "", 0, 640, 360);
screen.type_text(&m, &c, "/bossbar get pt");
assert_eq!(screen.take_request(), None);
}
+18 -11
View File
@@ -15,24 +15,18 @@ use horizon_world::{
entity_obstruction::EntityIdentity,
fluid::{FluidKind, FluidState},
liquid_collision::LiquidCollisionWorld,
nbt::{self, Limits},
powder_snow_collision::{PowderSnowEntity, PowderSnowWorld},
registry::BlockRegistry,
registry::{BlockRegistry, BlockTableFile},
world_movement::{
CollisionCheckRequest, EntityMovementWorld, MovementRequest, no_world_collision,
resolve_world_movement,
},
};
use std::{fs, io, path::Path, sync::Arc};
use std::{io, path::Path, sync::Arc};
pub fn load<'r>(root: &Path, registry: &'r BlockRegistry) -> Result<BlockCollisionRegistry<'r>> {
let data = nbt::read_named(
&fs::read(root.join("cached-collision.nbt"))?,
Limits::tables(),
)?
.0
.tag;
let cached = CachedCollisionRegistry::from_nbt(&data, registry)?;
let file = BlockTableFile::open(&root.join("cached-collision.nbt"), registry)?;
let cached = CachedCollisionRegistry::from_table(file.table("collision")?)?;
if !cached.has_canonical_identities() {
return Err("scene collisions require canonical shape identities".into());
}
@@ -137,12 +131,25 @@ impl SceneCollisions<'_, '_> {
movement: Vec3,
max_step: f32,
on_ground: bool,
) -> Result<Vec3> {
self.resolve_with_context(bounds, movement, max_step, on_ground, self.context(bounds))
}
/// Resolve movement with the entity's captured collision context. Most
/// callers only need the position context; entities such as falling blocks
/// also affect contextual block shapes (for example powder snow).
pub fn resolve_with_context(
&mut self,
bounds: Aabb,
movement: Vec3,
max_step: f32,
on_ground: bool,
context: CollisionContext<'_>,
) -> Result<Vec3> {
Ok(resolve_world_movement(
self,
MovementRequest {
entity: EntityIdentity(0),
context: self.context(bounds),
context,
bounds,
movement,
max_step,
+23 -4
View File
@@ -312,6 +312,9 @@ pub enum Suggests {
/// ScoreboardCommand.suggestTriggers: trigger objectives some of the
/// parsed `targets` have no score in, or a locked one.
EnableTriggers,
/// SuggestionProviders.ASK_SERVER: the server completes the node
/// (ClientSuggestionProvider.customSuggestion); nothing locally.
AskServer,
}
impl Node {
pub fn name(&self) -> &str {
@@ -691,7 +694,7 @@ impl Suggests {
Suggests::Triggers => {
builder.suggest_matching(reg.trigger_objectives.iter().map(String::as_str))
}
Suggests::Nothing => {}
Suggests::Nothing | Suggests::AskServer => {}
}
}
}
@@ -955,7 +958,8 @@ impl Dispatcher {
cursor: usize,
reg: &Registries,
) -> (Range, Vec<Suggestion>) {
self.suggestions_within(parse, cursor, reg, u8::MAX)
let (range, list, _) = self.suggestions_within(parse, cursor, reg, u8::MAX);
(range, list)
}
/// The suggestions the player's chat shows: the client's tree only holds
/// the nodes the player may use (Commands.sendCommands prunes by canUse).
@@ -965,6 +969,18 @@ impl Dispatcher {
cursor: usize,
reg: &Registries,
) -> (Range, Vec<Suggestion>) {
let (range, list, _) = self.suggestions_within(parse, cursor, reg, reg.permission);
(range, list)
}
/// [`Self::client_suggestions`], and whether a node at the cursor asks
/// the server (`ask_server`): its completions come with the server's
/// reply, to be merged with these.
pub fn client_suggestions_asking(
&self,
parse: &ParseResults,
cursor: usize,
reg: &Registries,
) -> (Range, Vec<Suggestion>, bool) {
self.suggestions_within(parse, cursor, reg, reg.permission)
}
fn suggestions_within(
@@ -973,15 +989,17 @@ impl Dispatcher {
cursor: usize,
reg: &Registries,
permission: u8,
) -> (Range, Vec<Suggestion>) {
) -> (Range, Vec<Suggestion>, bool) {
let (parent, start, context) = parse.context.suggestion_context(cursor);
let start = start.min(cursor);
let truncated = &parse.input[..cursor.min(parse.input.len())];
let mut all = Vec::new();
let mut ask = false;
for &child in &self.nodes[parent].children {
if self.nodes[child].permission > permission {
continue;
}
ask |= matches!(self.nodes[child].suggests, Some(Suggests::AskServer));
let mut builder = SuggestionsBuilder::new(truncated, start);
match &self.nodes[child].kind {
NodeKind::Literal(l) => {
@@ -997,7 +1015,8 @@ impl Dispatcher {
}
all.extend(builder.out);
}
merge_suggestions(truncated, all)
let (range, list) = merge_suggestions(truncated, all);
(range, list, ask)
}
fn smart_usage_of(&self, node: usize, optional: bool, deep: bool, level: u8) -> Option<String> {
let n = &self.nodes[node];
+5 -6
View File
@@ -83,10 +83,9 @@ pub fn from_packet(packet: &Commands, local: &Dispatcher) -> Dispatcher {
}
_ => NodeKind::Root,
};
let suggests = match local_node {
Some(l) => l.suggests.clone(),
None => node.suggestions.as_deref().and_then(provider),
};
// The server's providers, as the client knows them
// (ArgumentNodeStub.build): its own custom ones arrive as `ask_server`.
let suggests = node.suggestions.as_deref().and_then(provider);
nodes[index(i)] = Some(Node {
kind: if i == root { NodeKind::Root } else { kind },
children: node.children.iter().filter_map(valid).map(index).collect(),
@@ -104,10 +103,10 @@ pub fn from_packet(packet: &Commands, local: &Dispatcher) -> Dispatcher {
d
}
/// SuggestionProviders by id (`ask_server` asks the server; the client's
/// own argument suggestions stand in for it).
/// SuggestionProviders by id (`SuggestionProviders.getProvider`).
fn provider(id: &str) -> Option<Suggests> {
match id {
"minecraft:ask_server" => Some(Suggests::AskServer),
"minecraft:summonable_entities" => Some(Suggests::SummonableEntities),
_ => None,
}
+31
View File
@@ -386,6 +386,12 @@ impl PlayerEffects {
4.0,
"add_value",
)),
"absorption" => Some((
"minecraft:max_absorption",
"minecraft:effect.absorption",
4.0,
"add_value",
)),
"luck" => Some(("minecraft:luck", "minecraft:effect.luck", 1.0, "add_value")),
"unluck" => Some((
"minecraft:luck",
@@ -538,4 +544,29 @@ mod tests {
assert!((fx.mining_speed_factor() - 1.4).abs() < 1e-6);
assert_eq!(fx.modifiers().len(), 1);
}
#[test]
fn absorption_modifier_scales_with_amplifier() {
let mut fx = PlayerEffects::default();
fx.add(EffectInstance::new("absorption", 2400, 0));
assert_eq!(
fx.modifiers(),
vec![(
"minecraft:max_absorption",
"minecraft:effect.absorption",
4.0,
"add_value",
)]
);
fx.add(EffectInstance::new("absorption", 2400, 3));
assert_eq!(
fx.modifiers(),
vec![(
"minecraft:max_absorption",
"minecraft:effect.absorption",
16.0,
"add_value",
)]
);
}
}
+12 -7
View File
@@ -179,6 +179,8 @@ impl ItemEntity {
/// ExperienceOrb: gravity 0.03, homing towards the player within 8 blocks.
#[derive(Clone, Debug)]
pub struct ExperienceOrb {
/// The entity id servers track it by.
pub id: u32,
pub position: Vec3,
pub previous: Vec3,
pub velocity: Vec3,
@@ -533,15 +535,16 @@ impl ArmorStand {
Vec3::new(p.x + w, p.y + h, p.z + w),
)
}
/// LivingEntity.travel with gravity 0.08 and 0.98 drag, falling until it
/// lands (armor stands have no other movement).
/// LivingEntity.travelInAir (armor stands have no other movement): move
/// by the velocity (a landing stops the fall,
/// `Block.updateEntityMovementAfterFallOn`), then gravity 0.08 and the
/// 0.98 drag, so a stand at rest on the ground keeps -0.0784 as vanilla's.
pub fn tick(&mut self, scene: &mut crate::collisions::SceneCollisions) {
if self.marker {
return;
}
let mut v = self.velocity;
v.y -= 0.08;
let wanted = v;
let wanted = self.velocity;
let mut y = wanted.y;
if let Ok(moved) = scene.resolve(self.bounds(), wanted, 0.0, self.on_ground) {
self.position = Vec3::new(
self.position.x + moved.x,
@@ -549,9 +552,11 @@ impl ArmorStand {
self.position.z + moved.z,
);
self.on_ground = wanted.y < 0.0 && moved.y > wanted.y;
v = Vec3::new(0.0, if moved.y != wanted.y { 0.0 } else { v.y * 0.98 }, 0.0);
if moved.y != wanted.y {
y = 0.0;
}
}
self.velocity = v;
self.velocity = Vec3::new(0.0, (y - 0.08) * f64::from(0.98f32), 0.0);
}
}
+2
View File
@@ -943,6 +943,7 @@ pub fn orbs_from_nbt(tag: &Tag) -> Vec<ExperienceOrb> {
};
let count = number(tag.get("Count")).unwrap_or(1).clamp(1, 64) as usize;
let orb = ExperienceOrb {
id: 0,
position,
previous: position,
velocity: motion(tag),
@@ -1587,6 +1588,7 @@ mod tests {
#[test]
fn orbs_expand_their_count() {
let o = ExperienceOrb {
id: 0,
position: Vec3::new(1.0, 2.0, 3.0),
previous: Vec3::ZERO,
velocity: Vec3::ZERO,
+391 -151
View File
@@ -10,6 +10,7 @@ mod banners;
mod beacon;
mod beehives;
mod block_entity_anims;
mod block_entity_ticks;
mod block_items;
mod blockctl;
mod boats;
@@ -63,7 +64,9 @@ mod item_particles;
mod jukebox;
mod lan;
mod lan_actions;
mod lan_chat;
mod lan_crafting;
mod lan_entities;
mod lan_mobs;
mod lan_pvp;
mod lan_screen;
@@ -107,6 +110,8 @@ mod powder_snow;
mod raids;
mod recipe_book;
mod remote;
mod remote_objects;
mod remote_projectiles;
mod render_control;
mod render_tick;
mod respawn_anchor;
@@ -188,6 +193,8 @@ use horizon_core::{
use horizon_core::{geometry::Vec3, random::RandomSource};
use horizon_world::{
block_collision::BlockCollisionRegistry,
collision_context::{CollisionContext, CollisionEntity, CollisionItem},
entity_obstruction::{EntityIdentity, EntityObstructionWorld, ObstructionEntity},
level::{
Behaviours, Dimension as LevelDimension, EntityQuery, Landing, LevelAccess, LevelEvent,
PlaceContext, PlaceOutcome, PlayerContext, PlayerEffect, Ticks, flags as level_flags,
@@ -446,12 +453,14 @@ struct Hit {
struct GameLevel<'w> {
world: &'w mut World,
facts: &'w BlockFacts,
collision: &'w BlockCollisionRegistry<'w>,
events: &'w mut Vec<LevelEvent>,
dimension: LevelDimension,
darken: i32,
raining: bool,
thundering: bool,
player_box: Option<([f64; 3], [f64; 3])>,
player_collision: Option<PlayerCollision>,
/// Minecart boxes (detector rails).
cart_boxes: Vec<([f64; 3], [f64; 3])>,
biomes: &'w Biomes,
@@ -467,6 +476,32 @@ struct GameLevel<'w> {
pending: &'w mut spill::Pending,
spill: &'w mut spill::Spill,
}
struct PlayerCollision {
y: f64,
descending: bool,
fall_distance: f64,
main_hand_item: Arc<str>,
main_hand_count: i32,
leather_boots: bool,
}
struct PlayerObstruction(Aabb);
impl EntityObstructionWorld for PlayerObstruction {
type Error = std::convert::Infallible;
fn obstruction_candidates(
&mut self,
_excluded: Option<EntityIdentity>,
_bounds: Aabb,
) -> std::result::Result<Vec<ObstructionEntity>, Self::Error> {
Ok(vec![ObstructionEntity {
identity: EntityIdentity(0),
root_vehicle: EntityIdentity(0),
bounds: self.0,
removed: false,
spectator: false,
blocks_building: true,
}])
}
}
impl LevelAccess for GameLevel<'_> {
fn precipitation(&self, pos: BlockPos) -> Option<horizon_world::level::Precipitation> {
self.behaviours.precipitation_info(self, pos)
@@ -579,21 +614,63 @@ impl LevelAccess for GameLevel<'_> {
fn dimension(&self) -> LevelDimension {
self.dimension
}
/// Level.isUnobstructed against the player for full-collision blocks.
/// `Level.isUnobstructed`: the placed state's collision shape against the player.
fn is_unobstructed(&self, pos: BlockPos, state: BlockStateId) -> bool {
let Some((lo, hi)) = self.player_box else {
return true;
};
if !self.facts.get(state).full_collision {
let player = self.player_collision.as_ref();
let context = player.map_or_else(
|| CollisionContext::position(lo[1]),
|player| {
CollisionContext::for_entity(
CollisionEntity {
identity: EntityIdentity(0),
y: player.y,
descending: player.descending,
main_hand: Some(CollisionItem {
item: &player.main_hand_item,
count: player.main_hand_count,
}),
},
false,
)
},
);
let mut scene = collisions::SceneCollisions {
world: &*self.world,
binding: self.collision,
subject: player.map(|player| horizon_client::collisions::PowderSnowSubject {
fall_distance: player.fall_distance,
falling_block: false,
leather_boots: player.leather_boots,
walkable_type: false,
lava_walker: false,
}),
};
let Ok(shape) = self
.collision
.collision_shape_with_context(&mut scene, state, pos, &context)
else {
return false;
};
if shape.is_empty() {
return true;
}
let (x, y, z) = (f64::from(pos.x), f64::from(pos.y), f64::from(pos.z));
!(x < hi[0] - 1e-7
&& x + 1.0 > lo[0] + 1e-7
&& y < hi[1] - 1e-7
&& y + 1.0 > lo[1] + 1e-7
&& z < hi[2] - 1e-7
&& z + 1.0 > lo[2] + 1e-7)
let shape = shape.moved(horizon_core::geometry::Vec3::new(
f64::from(pos.x),
f64::from(pos.y),
f64::from(pos.z),
));
horizon_world::entity_obstruction::is_unobstructed(
&mut PlayerObstruction(Aabb::new(
horizon_core::geometry::Vec3::new(lo[0], lo[1], lo[2]),
horizon_core::geometry::Vec3::new(hi[0], hi[1], hi[2]),
)),
None,
&shape,
)
.unwrap_or(false)
}
/// Entities that trigger pressure plates, tripwires and detector rails:
/// the player (a mob) and the minecarts.
@@ -647,6 +724,8 @@ impl LevelAccess for GameLevel<'_> {
/// FallingBlockEntity carrying a block state.
#[derive(Clone, Debug)]
struct FallingBlock {
/// The entity id a server tracks it by (0 until it is tracked).
id: u32,
state: BlockStateId,
/// `DATA_START_POS`: spawn position used to select weighted block models.
start_pos: BlockPos,
@@ -987,6 +1066,8 @@ struct Game<'a> {
/// A server's players on their way to another level, each waiting for
/// the destination to load around them.
server_trips: Vec<server_travel::Trip>,
/// Players a command sends to another level, once it has run.
level_teleports: Vec<server_travel::LevelTeleport>,
/// A server's levels other than the one in place (game/levels.rs).
levels: levels::Levels,
/// Which pass of a server tick runs (`tick_server`): the first one reads
@@ -1154,10 +1235,16 @@ struct Game<'a> {
lan_acting_uuid: Option<u128>,
/// Command feedback to forward to a guest.
chat_capture: Option<Vec<horizon_client::text::Text>>,
/// Packets for the guest acting now, sent once its action returns.
guest_packets: Vec<horizon_protocol::packets::play::Clientbound>,
/// `broadcastToAdmins` lines a guest's command queued, sent once it
/// returns: the line, whether operators get it and whether the console
/// logs it.
admin_feedback: Vec<(horizon_client::text::Text, bool, bool)>,
/// The server console is running a command: whether its feedback goes to
/// the operators (`DedicatedServer.shouldInformAdmins`,
/// `broadcast-console-to-ops`).
console_broadcast: Option<bool>,
/// State of `/spectate`, `/posteffect`, `/debug`, `/waypoint` and friends.
cmds: commands::extra::CommandExtras,
ui: chat::UiState,
@@ -1757,6 +1844,22 @@ impl Game<'_> {
],
)
});
let player_collision = self.player.as_ref().filter(|_| !spectator).map(|p| {
let main_hand = self.inventory.get(self.selected).and_then(Option::as_ref);
PlayerCollision {
y: p.position.y,
descending: p.velocity.y < 0.0,
fall_distance: p.fall_distance,
main_hand_item: main_hand.map_or_else(
|| Arc::from("minecraft:air"),
|stack| Arc::clone(&stack.item),
),
main_hand_count: main_hand.map_or(0, |stack| stack.count as i32),
leather_boots: self.armor[3]
.as_ref()
.is_some_and(|stack| stack.item.as_ref() == "minecraft:leather_boots"),
}
});
let cart_boxes = self
.carts
.iter()
@@ -1778,12 +1881,14 @@ impl Game<'_> {
cart_boxes,
world: &mut self.world,
facts: &self.res.facts,
collision: self.collision,
events: &mut self.level_events,
dimension,
darken,
raining: rain > 0.2,
thundering: thunder > 0.9,
player_box,
player_collision,
biomes: &self.res.biomes,
seed: self.level.seed,
behaviours: &self.res.behaviours,
@@ -1830,6 +1935,7 @@ impl Game<'_> {
}
for &key in self.tick_chunks.removed() {
self.random_tick_sections.remove(&key);
self.portals.sections.remove(&key);
self.block_ticks
.remove_chunk(horizon_core::position::ChunkPos::new(key.0, key.1));
}
@@ -2055,6 +2161,7 @@ impl Game<'_> {
f64::from(pos.z) + 0.5,
);
self.falling.push(FallingBlock {
id: 0,
state,
start_pos: pos,
position: p,
@@ -2204,13 +2311,13 @@ impl Game<'_> {
self.audio
.play("minecraft:block.ender_chest.open", Some(at), 0.5, pitch);
} else if &*name == "minecraft:beacon" && self.open_station(pos, &name) {
self.world.block_entities.entry(key).or_insert_with(|| {
self.world.block_entities.get_or_insert_with(key, || {
BlockEntity::for_block(&name).unwrap_or(BlockEntity::Chest(Vec::new()))
});
} else if storage::is_shulker_box(&name) && !self.shulker_can_open(pos) {
// ShulkerBoxBlock.canOpen: the lid has no room; nothing opens.
} else if let Some(entity) = BlockEntity::for_block(&name) {
self.world.block_entities.entry(key).or_insert(entity);
self.world.block_entities.get_or_insert_with(key, || entity);
let centre = [
f64::from(key.0) + 0.5,
f64::from(key.1) + 0.5,
@@ -2284,65 +2391,87 @@ impl Game<'_> {
let mut falling = std::mem::take(&mut self.falling);
let mut landed = Vec::new();
let mut dropped = Vec::new();
let mut collision_error = None;
let entity_drops = self.ui.rules.bool("entity_drops");
falling.retain_mut(|f| {
let original = f.clone();
f.previous = f.position;
f.age = f.age.wrapping_add(1);
if !f.no_gravity {
f.velocity.y -= 0.04;
}
let wanted = f.velocity;
let mut scene = collisions::SceneCollisions {
world: &self.world,
binding: self.collision,
subject: Some(collisions::PowderSnowSubject {
fall_distance: f.fall_distance,
falling_block: true,
..Default::default()
}),
};
let context = CollisionContext::for_entity(
CollisionEntity {
identity: EntityIdentity(0),
y: f.position.y,
descending: wanted.y < 0.0,
main_hand: None,
},
false,
);
let movement = match scene.resolve_with_context(
horizon_client::falling_block::bounds(f.position),
wanted,
0.0,
false,
context,
) {
Ok(movement) => movement,
Err(error) => {
*f = original;
collision_error.get_or_insert(error);
return true;
}
};
let next = Vec3::new(
f.position.x + f.velocity.x,
f.position.y + f.velocity.y,
f.position.z + f.velocity.z,
f.position.x + movement.x,
f.position.y + movement.y,
f.position.z + movement.z,
);
let below = self.world.block(
next.x.floor() as i32,
next.y.floor() as i32,
next.z.floor() as i32,
);
let below_facts = self.res.facts.get(below);
// PowderSnowBlock.getCollisionShape for a FallingBlockEntity: the
// whole block, or 0.9 high after a fall of more than 2.5 blocks,
// where the block it rests in is the snow itself.
let powder_snow = &*below_facts.name == "minecraft:powder_snow";
let sunk = powder_snow
&& f.fall_distance > 2.5
&& next.y - next.y.floor() < f64::from(0.9_f32);
let solid =
(below_facts.full_collision || powder_snow && f.fall_distance <= 2.5 || sunk)
&& f.velocity.y < 0.0;
let on_ground = wanted.y < 0.0 && movement.y != wanted.y;
// FallingBlockEntity.tick: off the ground, it gives up after 600
// ticks (100 outside the world) and drops itself as an item.
let y = next.y.floor() as i32;
let outside =
y <= horizon_client::chunk::MIN_Y || y >= horizon_client::chunk::MIN_Y + 384;
if !solid && (f.age > 100 && outside || f.age > 600) {
if !on_ground && (f.age > 100 && outside || f.age > 600) {
if f.drop_item && entity_drops {
dropped.push((f.state, next));
}
return false;
}
if solid {
let pos = [
next.x.floor() as i32,
next.y.floor() as i32 + i32::from(!sunk),
next.z.floor() as i32,
];
let landing_y = if sunk {
next.y.floor() + f64::from(0.9_f32)
} else {
f64::from(pos[1])
};
f.fall_distance += (f.position.y - landing_y).max(0.0);
f.position = Vec3::new(next.x, landing_y, next.z);
landed.push((f.clone(), pos));
return false;
}
if next.y < f.position.y {
f.fall_distance += f.position.y - next.y;
}
f.position = next;
if on_ground {
let pos = [
f.position.x.floor() as i32,
f.position.y.floor() as i32,
f.position.z.floor() as i32,
];
landed.push((f.clone(), pos));
return false;
}
if movement.x != wanted.x {
f.velocity.x = 0.0;
}
if movement.y != wanted.y {
f.velocity.y = 0.0;
}
if movement.z != wanted.z {
f.velocity.z = 0.0;
}
f.velocity = Vec3::new(
f.velocity.x * 0.98,
f.velocity.y * 0.98,
@@ -2373,7 +2502,11 @@ impl Game<'_> {
for (block, pos) in landed {
self.finish_falling_block(block, pos);
}
self.process_level_events()
self.process_level_events()?;
if let Some(error) = collision_error {
return Err(error);
}
Ok(())
}
fn break_block(&mut self, pos: [i32; 3]) -> Result<()> {
self.with_player_actor(|game| game.break_block_as_player(pos))
@@ -2767,7 +2900,7 @@ impl Game<'_> {
|| !self
.player
.as_ref()
.is_some_and(|p| p.health.food.food < 20 || self.creative)
.is_some_and(|p| info.can_always_eat || p.health.food.food < 20 || self.creative)
{
return false;
}
@@ -2776,6 +2909,56 @@ impl Game<'_> {
}
true
}
fn apply_consume_effect(
&mut self,
effect: &horizon_client::items::ConsumeEffect,
eye: [f64; 3],
) {
use horizon_client::items::ConsumeEffect;
match effect {
ConsumeEffect::ApplyEffects {
effects,
probability,
} => {
if *probability >= 1.0 || self.world.random.next_float() <= *probability {
for eff in effects {
if let Some(def) = horizon_client::brewing::effect(&eff.id) {
if def.instant {
if let Some(a) =
horizon_client::effects::instant(def.id, eff.amplifier, 1.0)
{
self.apply_effect_action(a);
}
} else {
self.add_player_effect(
horizon_client::effects::EffectInstance::new(
def.id,
eff.duration,
eff.amplifier,
),
);
}
}
}
}
}
ConsumeEffect::ClearAllEffects => {
self.potions.effects.clear();
self.apply_effect_status();
}
ConsumeEffect::RemoveEffects(to_remove) => {
for target in to_remove {
let id = target.trim_start_matches("minecraft:");
self.potions.effects.list.retain(|e| e.id != id);
}
self.apply_effect_status();
}
ConsumeEffect::TeleportRandomly => {}
ConsumeEffect::PlaySound(sound) => {
self.audio.play(sound, Some(eye), 1.0, 1.0);
}
}
}
fn consume_held(&mut self) {
if self.creative {
return;
@@ -2878,19 +3061,22 @@ impl Game<'_> {
self.eat_particles(&stack, 16);
// Consumable.onConsume.
self.post_entity_event("minecraft:eat", horizon_client::mobs::Who::Player);
if let Some((nutrition, saturation)) = info.food
&& let Some(p) = self.player.as_mut()
{
// FoodData.eat(nutrition, saturation)
let food = &mut p.health.food;
food.food = (food.food + nutrition as i32).clamp(0, 20);
food.saturation = (food.saturation + saturation).clamp(0.0, food.food as f32);
if let Some((nutrition, saturation)) = info.food {
if let Some(p) = self.player.as_mut() {
// FoodData.eat(nutrition, saturation)
let food = &mut p.health.food;
food.food = (food.food + nutrition as i32).clamp(0, 20);
food.saturation = (food.saturation + saturation).clamp(0.0, food.food as f32);
}
self.audio.play(
"minecraft:entity.player.burp",
Some(eye),
0.5,
self.world.random.next_float() * 0.1 + 0.9,
);
for effect in &info.consume_effects {
self.apply_consume_effect(effect, eye);
}
self.trigger_item("minecraft:consume_item", &stack);
self.consume_held();
}
@@ -3106,6 +3292,11 @@ impl Game<'_> {
player.may_fly = self.creative || spectator;
player.invulnerable = self.creative || spectator;
player.spectator = spectator;
if spectator {
player.flying = true;
} else if !player.may_fly {
player.flying = false;
}
player.respiration = self.armor[0]
.as_ref()
.map_or(0, |s| s.enchantment_level("minecraft:respiration") as i32);
@@ -3559,7 +3750,6 @@ impl Game<'_> {
horizon_client::spans::time("tick_block_entities", || self.tick_block_entities())?;
horizon_client::spans::time("tick_sculk_entities", || self.tick_sculk_entities());
horizon_client::spans::time("tick_sculk_blocks", || self.tick_sculk_blocks())?;
horizon_client::spans::time("tick_brewing_stands", || self.tick_brewing_stands())?;
}
if running {
// ClientLevel.tickBlockEntities (not while paused or frozen):
@@ -4549,6 +4739,10 @@ impl Game<'_> {
/// Several clicks on one menu instance (a quick craft drag is three).
fn menu_ops(&mut self, ops: &[(Option<usize>, i32, horizon_client::menu::Input)]) -> bool {
use horizon_client::menu::Input;
if self.remote.is_some() && self.screen == Screen::Inventory {
// On a server the clicks are the server's: predicted and sent.
return self.remote_menu_ops(ops);
}
if let [(Some(slot), button, input)] = ops {
self.crafter_slot_clicked(*slot, *button, *input);
}
@@ -4723,7 +4917,7 @@ impl Game<'_> {
plain: false,
};
(kind, map)
} else if self.station.is_none() && !self.mount_active() && self.remote.is_none() {
} else if self.station.is_none() && !self.mount_active() {
let table = self.craft_size == 3;
let map = Map {
container: 0,
@@ -4836,7 +5030,12 @@ impl Game<'_> {
Some(false) => return true,
Some(true) => {}
}
self.register_exploration_maps(made);
// On a server the clicks only predict: the server drops, crafts and
// makes maps itself.
let predicting = self.remote.is_some();
if !predicting {
self.register_exploration_maps(made);
}
if let Some(s) = menu.merchant.take() {
self.merchant_sync_out(s);
}
@@ -4854,10 +5053,12 @@ impl Game<'_> {
if !offhand_mapped {
self.offhand = menu.player_item(40).cloned();
}
for stack in dropped {
self.player_drop(stack);
if !predicting {
for stack in dropped {
self.player_drop(stack);
}
self.award_crafted(&crafted);
}
self.award_crafted(&crafted);
if kind == Kind::Loom {
if let Some(s) = self.station.as_mut() {
s.loom.selected = usize::try_from(menu.data[0]).ok();
@@ -4989,9 +5190,13 @@ impl Game<'_> {
return;
}
if let Some(moved) = self.last_quick_moved.clone() {
self.menu_session(|menu, env, to_menu| {
Some(menu.quick_move_all(env, to_menu(slot)?, &moved).is_ok())
});
if self.remote.is_some() {
self.remote_quick_move_all(slot, &moved);
} else {
self.menu_session(|menu, env, to_menu| {
Some(menu.quick_move_all(env, to_menu(slot)?, &moved).is_ok())
});
}
}
self.last_inv_click = None;
self.inv_clicks.skip_release();
@@ -6095,38 +6300,6 @@ impl Game<'_> {
false,
)
}
fn tick_block_entities(&mut self) -> Result<()> {
self.tick_hoppers()?;
self.tick_crafters();
self.tick_mount_menu();
self.tick_jukeboxes();
self.tick_beacons();
self.tick_creaking_hearts()?;
self.tick_spawners()?;
self.tick_trial_spawners()?;
self.tick_vaults()?;
self.tick_beehives();
let mut lit_changes = Vec::new();
for (pos, entity) in self.world.block_entities.iter_mut() {
if let BlockEntity::Furnace(f) = entity
&& let Some(lit) = f.tick(&self.res.recipes, &self.res.items, &self.res.providers)
{
lit_changes.push((*pos, lit));
}
}
for ((x, y, z), lit) in lit_changes {
let state = self.world.block(x, y, z);
if let Some(mut s) = self.pack.assets.registry.state(state).cloned()
&& s.properties.contains_key("lit")
{
s.properties.insert("lit".into(), lit.to_string());
if let Ok(id) = self.pack.assets.registry.resolve(&s) {
self.world.set(x, y, z, id)?;
}
}
}
Ok(())
}
/// Copies of a save batch carrying its live block entities and save data.
fn with_entities<'a>(
&self,
@@ -6506,7 +6679,10 @@ impl Game<'_> {
res.threads,
)
} else {
let inner = Arc::new(VanillaTerrain::for_dimension(&self.options.resources.join("worldgen"), pack.assets.registry, &res.biomes, seed, dim.id()).map_err(|e| {
// WorldOptions.generateStructures, from the world's settings.
let structures =
horizon_client::save::WorldGen::read(world_root).is_none_or(|w| w.structures);
let inner = Arc::new(VanillaTerrain::for_world(&self.options.resources.join("worldgen"), pack.assets.registry, &res.biomes, seed, dim.id(), structures).map_err(|e| {
format!("{e}\nPrepare the worldgen bundle with the launcher, or: horizon-prepare --prepare")
})?);
self.end.set_locator(Some(inner.clone()));
@@ -6529,8 +6705,9 @@ impl Game<'_> {
streaming.biome_zoom = BiomeZoom::new(obfuscate_seed(seed));
streaming.sky_light = dim != Dim::Nether;
streaming.nether_shading = dim == Dim::Nether;
// The integrated server draws nothing (the dedicated server keeps its behaviour).
streaming.mesh = !self.options.integrated;
// A server draws nothing: neither the integrated server nor the
// dedicated one meshes sections.
streaming.mesh = !self.options.integrated && self.options.dedicated.is_none();
Ok((streaming, save))
}
/// Change dimension through a portal (Entity.changeDimension with
@@ -6578,6 +6755,7 @@ impl Game<'_> {
world.weather = self.world.weather;
// An open hub keeps hearing the new level's block changes.
world.block_log = self.world.block_log.as_ref().map(|_| Vec::new());
world.light_log = self.world.light_log.as_ref().map(|_| Default::default());
// The sculk tables' watched blocks are built once per game.
world.watched = std::mem::take(&mut self.world.watched);
self.streaming = streaming;
@@ -7387,7 +7565,9 @@ impl Game<'_> {
let mut r = dispenser::entity_random();
let _yaw = r.next_float();
let p = Vec3::new(at[0], at[1], at[2]);
self.next_entity += 1;
self.orbs.push(ExperienceOrb {
id: self.next_entity,
position: p,
previous: p,
velocity: Vec3::new(
@@ -7451,13 +7631,29 @@ impl Game<'_> {
.player
.as_ref()
.filter(|p| !p.health.dead_or_dying() && !spectator);
let target = player.map(|p| {
[
p.position.x,
p.position.y + f64::from(p.dimensions.eye_height) / 2.0,
p.position.z,
]
});
// ExperienceOrb.followNearbyPlayer: each orb goes for the nearest
// living player within 8 blocks, the host's own or a guest.
let mut followed: Vec<([f64; 3], [f64; 3])> = player
.map(|p| {
let feet = [p.position.x, p.position.y, p.position.z];
let eye = f64::from(p.dimensions.eye_height);
(feet, [feet[0], feet[1] + eye / 2.0, feet[2]])
})
.into_iter()
.collect();
if let Some(host) = self.lan.as_ref() {
followed.extend(
host.hub
.guests
.iter()
.filter(|g| g.placed && g.loaded && !g.dead && g.health > 0.0)
.filter(|g| !g.spectator())
.map(|g| {
let p = g.position;
(p, [p[0], p[1] + g.eye_height() / 2.0, p[2]])
}),
);
}
let bounds = player.map(|p| {
let w = f64::from(p.dimensions.width) / 2.0;
(
@@ -7470,7 +7666,19 @@ impl Game<'_> {
)
});
let mut orbs = std::mem::take(&mut self.orbs);
orbs.retain_mut(|o| o.tick(&self.world, &self.res.facts, self.collision, target));
orbs.retain_mut(|o| {
let distance = |feet: &[f64; 3]| -> f64 {
(feet[0] - o.position.x).powi(2)
+ (feet[1] - o.position.y).powi(2)
+ (feet[2] - o.position.z).powi(2)
};
let target = followed
.iter()
.filter(|(feet, _)| distance(feet) < 64.0)
.min_by(|a, b| distance(&a.0).total_cmp(&distance(&b.0)))
.map(|(_, target)| *target);
o.tick(&self.world, &self.res.facts, self.collision, target)
});
let mut gained = 0;
let mut taken = Vec::new();
if let Some((min, max)) = bounds {
@@ -7504,19 +7712,25 @@ impl Game<'_> {
(self.world.random.next_float() - self.world.random.next_float()) * 0.35 + 0.9;
self.audio
.play("minecraft:entity.experience_orb.pickup", at, 0.1, pitch);
if self.experience.give(gained as i32)
&& self.experience.level % 5 == 0
&& self.ticks > self.last_level_up + 100
{
self.last_level_up = self.ticks;
let volume = if self.experience.level > 30 {
1.0
} else {
self.experience.level as f32 / 30.0
};
self.audio
.play("minecraft:entity.player.levelup", at, volume * 0.75, 1.0);
}
self.give_orb_points(gained);
}
}
/// `Player.giveExperiencePoints`, and `giveExperienceLevels`' level-up
/// sound every fifth level (at most every 100 ticks).
pub(super) fn give_orb_points(&mut self, gained: u32) {
let at = self.eye_position();
if self.experience.give(gained as i32)
&& self.experience.level % 5 == 0
&& self.ticks > self.last_level_up + 100
{
self.last_level_up = self.ticks;
let volume = if self.experience.level > 30 {
1.0
} else {
self.experience.level as f32 / 30.0
};
self.audio
.play("minecraft:entity.player.levelup", at, volume * 0.75, 1.0);
}
}
/// BowItem.releaseUsing: power from charge time, arrows at power * 3.
@@ -8078,40 +8292,48 @@ impl Game<'_> {
self.stats.reset("custom", "minecraft:time_since_rest");
}
fn wake_up(&mut self) {
if self.remote.is_some() {
// InBedChatScreen.sendWakeUp: the server wakes the player.
self.remote_stop_sleeping();
return;
}
self.sleeping = None;
self.sleep_timer = 100;
}
fn tick_sleep(&mut self) {
self.sleep_timer = tick_sleep_timer(self.sleep_timer, self.sleeping.is_some());
let Some(head) = self.sleeping else {
return;
};
if self.keys.contains(&KeyCode::ShiftLeft)
|| self
.player
.as_ref()
.is_none_or(|p| p.health.dead_or_dying())
{
self.wake_up();
return;
if let Some(head) = self.sleeping {
if self.keys.contains(&KeyCode::ShiftLeft)
|| self
.player
.as_ref()
.is_none_or(|p| p.health.dead_or_dying())
{
self.wake_up();
return;
}
if let Some(p) = self.player.as_mut() {
p.position = Vec3::new(
f64::from(head[0]) + 0.5,
f64::from(head[1]) + 0.5625,
f64::from(head[2]) + 0.5,
);
p.velocity = Vec3::ZERO;
}
}
if let Some(p) = self.player.as_mut() {
p.position = Vec3::new(
f64::from(head[0]) + 0.5,
f64::from(head[1]) + 0.5625,
f64::from(head[2]) + 0.5,
);
p.velocity = Vec3::ZERO;
}
// ServerLevel: once everyone has slept 100 ticks, skip to morning and clear weather.
if self.sleep_timer >= 100 {
// ServerLevel.tick: once enough of the players have slept 100 ticks,
// skip to morning, clear the weather and wake everyone.
if self.enough_slept() {
let t = self.world.day_time;
self.world.day_time = t + 24000 - t.rem_euclid(24000);
self.world.weather.raining = false;
self.world.weather.thundering = false;
self.world.weather.rain_time = 0;
self.world.weather.thunder_time = 0;
self.wake_up();
if self.sleeping.is_some() {
self.wake_up();
}
self.wake_guests();
}
}
fn creative_origin(batch: &HudBatch) -> (f32, f32) {
@@ -8414,6 +8636,7 @@ impl Game<'_> {
level.food = p.health.food.food;
level.saturation = p.health.food.saturation;
level.flying = p.flying;
}
level.inventory = self
.inventory
@@ -8540,6 +8763,22 @@ impl Game<'_> {
camera.y.floor() as i32,
camera.z.floor() as i32,
];
// The camera inside an opaque block sees nothing through it: disable.
let cave_culling = self.settings.horizon.cave_culling
&& !self
.res
.facts
.get(self.world.block(block[0], block[1], block[2]))
.solid_render;
// The cave culling search runs on its worker while the frame is prepared.
if cave_culling
&& self.title.is_none()
&& let Some(renderer) = self.renderer.as_mut()
{
horizon_client::spans::time("occlusion", || {
renderer.start_occlusion(camera, (self.streaming.radius * 16) as f32)
});
}
let biome = self
.world
.chunks
@@ -8730,13 +8969,7 @@ impl Game<'_> {
skybox: self.dim == Dim::Overworld && self.settings.horizon.sky,
end_sky: self.dim == Dim::End && self.settings.horizon.sky,
environment_fog: (self.dim == Dim::Nether).then_some((sky.fog_start, sky.fog_end)),
// The camera inside an opaque block sees nothing through it: disable.
cave_culling: self.settings.horizon.cave_culling
&& !self
.res
.facts
.get(self.world.block(block[0], block[1], block[2]))
.solid_render,
cave_culling,
water_fog,
fog: Some({
let mut fog = self.frame_fog(camera, &sky, biome);
@@ -9975,6 +10208,10 @@ impl ApplicationHandler for Game<'_> {
self.pause = self.pauses_game();
if let Some(server) = &self.integrated {
server.set_paused(self.pause);
server.set_distances(
self.settings.render_distance,
self.settings.simulation_distance,
);
}
self.clock.end_frame(self.pause);
let finished = self
@@ -10297,6 +10534,7 @@ impl<'a> Game<'a> {
world_root: PathBuf::new(),
travelling: None,
server_trips: Vec::new(),
level_teleports: Vec::new(),
levels: Default::default(),
level_pass: Default::default(),
portals: Default::default(),
@@ -10401,10 +10639,12 @@ impl<'a> Game<'a> {
lan_entity_events: Vec::new(),
lid_openers: HashMap::new(),
lan_acting: None,
guest_packets: Vec::new(),
lan_acting_name: None,
lan_acting_uuid: None,
chat_capture: None,
admin_feedback: Vec::new(),
console_broadcast: None,
cmds: Default::default(),
ui: Default::default(),
combat: Default::default(),
@@ -10551,7 +10791,7 @@ fn load_resources(
on_stage(5);
let registry_owner = assets.clone();
let collision = collisions::load(&root, registry_owner.registry)?;
let motion = MotionResources::load(&root, &registry_owner)?;
let motion = MotionResources::load_with_facts(&root, &registry_owner, &facts)?;
log::info!(
"load collision+motion: {:.2}s",
started.elapsed().as_secs_f32()
+41 -1
View File
@@ -4,7 +4,13 @@
//! take time run as a task advanced every frame and reply when they finish or
//! time out, so `horizon-ctl break 10 64 3` returns what the block dropped.
use super::{Game, Screen};
use horizon_client::{Result, block_entity_anim::Ticker, items::ItemStack, widgets};
use horizon_client::{
Result,
block_entity_anim::Ticker,
chunk::{MIN_Y, SECTIONS},
items::ItemStack,
widgets,
};
use horizon_core::geometry::Vec3;
use horizon_world::registry::BlockStateId;
use serde_json::{Value, json};
@@ -27,6 +33,7 @@ pub(super) const HELP: &[&str] = &[
"entities [RADIUS] [TYPE] mobs, dropped items and orbs near the player, nearest first",
"block X Y Z the block state at a position",
"blocks X1 Y1 Z1 X2 Y2 Z2 the non-air blocks of a box (at most 32768 blocks)",
"light X1 Y1 Z1 X2 Y2 Z2 the stored sky and block light of a box (at most 32768 blocks)",
"find-block BLOCK [RADIUS] the nearest loaded blocks of a kind (default radius 32)",
"inventory hotbar, main inventory, armor, offhand and carried stack",
"screen the open screen or menu, its slots and its buttons",
@@ -466,6 +473,10 @@ impl Game<'_> {
}),
"dimension": self.dim.id(),
"gamemode": format!("{:?}", self.mode).to_lowercase(),
// The bed (its head) the player sleeps in.
"sleeping": self.sleeping,
// The item in use: its slot and for how many ticks.
"using": self.using.map(|(slot, ticks)| json!({ "slot": slot, "ticks": ticks })),
"time": { "day_time": self.world.day_time, "day": self.world.day_time.div_euclid(24000), "time_of_day": self.world.day_time.rem_euclid(24000) },
"weather": { "raining": self.world.weather.raining, "thundering": self.world.weather.thundering },
"paused": self.pause,
@@ -958,6 +969,35 @@ impl Game<'_> {
}
ok(json!({ "from": lo, "to": hi, "counts": census, "blocks": list }))
}
"light" => {
self.need_world()?;
let (p, q) = (a.block_pos(0)?, a.block_pos(3)?);
let lo = [0, 1, 2].map(|i| p[i].min(q[i]));
let hi = [0, 1, 2].map(|i| p[i].max(q[i]));
let volume: i64 = (0..3).map(|i| i64::from(hi[i] - lo[i] + 1)).product();
if volume > 32768 {
return Err(format!("{volume} blocks; at most 32768 per request").into());
}
// One hex digit per block, x fastest, then z, then y; `.`
// outside the loaded chunks.
let (mut sky, mut block) = (String::new(), String::new());
for y in lo[1]..=hi[1] {
for z in lo[2]..=hi[2] {
for x in lo[0]..=hi[0] {
let packed = self
.world
.chunks
.get(&(x >> 4, z >> 4))
.filter(|_| (MIN_Y..MIN_Y + SECTIONS as i32 * 16).contains(&y))
.map(|c| c.light(x & 15, y, z & 15));
let digit = |v: u8| char::from_digit(u32::from(v), 16).unwrap_or('.');
sky.push(packed.map_or('.', |v| digit(v >> 4)));
block.push(packed.map_or('.', |v| digit(v & 15)));
}
}
}
ok(json!({ "from": lo, "to": hi, "sky": sky, "block": block }))
}
"find-block" => {
self.need_world()?;
let want = namespaced(a.get(0, "BLOCK")?);
@@ -413,6 +413,32 @@ impl Game<'_> {
if a.invisible {
continue;
}
// ArmorStand.shouldRenderAtSqrDistance: 256 times the box's mean
// edge (4 for a marker's empty box), whatever the entity distance.
// LivingEntityRenderer grows the culling box by 0.5 for a dragon head.
let (width, height) = match (a.marker, a.small) {
(true, _) => (0.0, 0.0),
(false, true) => (0.25, 0.9875),
(false, false) => (0.5, 1.975),
};
let edge = (width + height + width) / 3.0 * 4.0;
let range = if edge == 0.0 { 4.0 } else { edge } * 64.0;
let dragon = a.equipment[5]
.as_ref()
.is_some_and(|i| &*i.item == "minecraft:dragon_head");
let position = super::entity_culling::at(a.position);
if !self.standing_entity_in_view(
camera,
position,
position,
alpha,
width,
height,
range,
if dragon { 0.5 } else { 0.0 },
) {
continue;
}
let Some(model) = (if a.small { &assets.small } else { &assets.main }) else {
continue;
};
+7 -18
View File
@@ -105,24 +105,13 @@ impl Game<'_> {
.find(|&y| !self.res.facts.is_air(self.world.block(x, y, z)))
.map_or(min, |y| y + 1)
}
/// `BeaconBlockEntity.tick` for every beacon.
pub(super) fn tick_beacons(&mut self) {
let keys: Vec<(i32, i32, i32)> = self
.world
.block_entities
.iter()
.filter(|(_, e)| matches!(e, BlockEntity::Beacon(_)))
.map(|(k, _)| *k)
.collect();
for key in keys {
let Some(BlockEntity::Beacon(mut b)) = self.world.block_entities.remove(&key) else {
continue;
};
self.tick_beacon(key, &mut b);
self.world
.block_entities
.insert(key, BlockEntity::Beacon(b));
}
/// `BeaconBlockEntity.tick` of the beacon at `key`.
pub(super) fn tick_beacon_at(&mut self, key: (i32, i32, i32)) {
let Some(BlockEntity::Beacon(mut b)) = self.world.block_entities.take(&key) else {
return;
};
self.tick_beacon(key, &mut b);
self.world.block_entities.put(key, BlockEntity::Beacon(b));
}
fn tick_beacon(&mut self, (x, y, z): (i32, i32, i32), b: &mut Beacon) {
let mut check = if b.last_check_y < y {
+34 -45
View File
@@ -87,48 +87,37 @@ impl Game<'_> {
let facing = beehive::facing_step(props.get("facing").map(String::as_str));
Some((honey, facing))
}
/// `BeehiveBlockEntity.serverTick` for every hive, after an emergency
/// exit for those with fire beside them (`BeehiveBlock.updateShape`).
pub(super) fn tick_beehives(&mut self) {
let mut keys: Vec<(i32, i32, i32)> = self
.world
.block_entities
.iter()
.filter(|(_, e)| matches!(e, BlockEntity::Beehive(_)))
.map(|(k, _)| *k)
.collect();
keys.sort_unstable();
for key in keys {
let at = [key.0, key.1, key.2];
let Some((honey, facing)) = self.hive_state(at) else {
continue;
};
let Some(BlockEntity::Beehive(mut hive)) = self.world.block_entities.remove(&key)
else {
continue;
};
let fire = [
[1, 0, 0],
[-1, 0, 0],
[0, 1, 0],
[0, -1, 0],
[0, 0, 1],
[0, 0, -1],
]
.iter()
.any(|d| {
let state = self.world.block(at[0] + d[0], at[1] + d[1], at[2] + d[2]);
&*self.res.facts.get(state).name == "minecraft:fire"
});
let mut host = GameHive { game: self };
if fire && !hive.bees.is_empty() {
hive.release_all(at, facing, honey, Release::Emergency, &mut host);
}
hive.server_tick(at, facing, honey, &mut host);
self.world
.block_entities
.insert(key, BlockEntity::Beehive(hive));
/// `BeehiveBlockEntity.serverTick` of the hive at `key`, after an
/// emergency exit if fire is beside it (`BeehiveBlock.updateShape`).
pub(super) fn tick_beehive(&mut self, key: (i32, i32, i32)) {
let at = [key.0, key.1, key.2];
let Some((honey, facing)) = self.hive_state(at) else {
return;
};
let Some(BlockEntity::Beehive(mut hive)) = self.world.block_entities.take(&key) else {
return;
};
let fire = [
[1, 0, 0],
[-1, 0, 0],
[0, 1, 0],
[0, -1, 0],
[0, 0, 1],
[0, 0, -1],
]
.iter()
.any(|d| {
let state = self.world.block(at[0] + d[0], at[1] + d[1], at[2] + d[2]);
&*self.res.facts.get(state).name == "minecraft:fire"
});
let mut host = GameHive { game: self };
if fire && !hive.bees.is_empty() {
hive.release_all(at, facing, honey, Release::Emergency, &mut host);
}
hive.server_tick(at, facing, honey, &mut host);
self.world
.block_entities
.put(key, BlockEntity::Beehive(hive));
}
/// `BeehiveBlockEntity.addOccupant` for a bee its `BeeEnterHiveGoal`
/// sent in: off its lead, its tag stored, the bee gone.
@@ -152,13 +141,13 @@ impl Game<'_> {
self.mobs[i].extra.mount = None;
let tag = self.mob_tree_nbt(i);
let flower = bee::get(&self.mobs[i]).and_then(|b| b.flower);
let Some(BlockEntity::Beehive(mut hive)) = self.world.block_entities.remove(&key) else {
let Some(BlockEntity::Beehive(mut hive)) = self.world.block_entities.take(&key) else {
return;
};
let stored = hive.add_occupant(at, tag, flower, &mut GameHive { game: self });
self.world
.block_entities
.insert(key, BlockEntity::Beehive(hive));
.put(key, BlockEntity::Beehive(hive));
if stored && let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob) {
m.removed = true;
}
@@ -166,13 +155,13 @@ impl Game<'_> {
/// `BeehiveBlockEntity.emptyAllLivingFromHive` with no player about.
pub(super) fn empty_hive(&mut self, at: [i32; 3], facing: [i32; 2], status: Release) {
let key = (at[0], at[1], at[2]);
let Some(BlockEntity::Beehive(mut hive)) = self.world.block_entities.remove(&key) else {
let Some(BlockEntity::Beehive(mut hive)) = self.world.block_entities.take(&key) else {
return;
};
hive.release_all(at, facing, None, status, &mut GameHive { game: self });
self.world
.block_entities
.insert(key, BlockEntity::Beehive(hive));
.put(key, BlockEntity::Beehive(hive));
}
/// `BeehiveBlock.playerDestroy` without silk touch: the bees come out
/// angry at the player unless smoke calms them, then
@@ -13,7 +13,6 @@ use horizon_client::{
};
use horizon_core::geometry::{Aabb, Vec3};
use horizon_world::nbt::Tag;
use std::collections::HashMap;
/// The handle of the local player among a bell's gathered entities.
const PLAYER: u64 = u64::MAX;
@@ -174,11 +173,20 @@ impl Game<'_> {
let Some(r) = &self.renderer else {
return;
};
let present: HashMap<[i32; 3], Ticker> = r
.block_entities()
.filter_map(|(p, s)| Some((*p, self.be_anims.ticker(*s)?)))
.collect();
self.be_anims.retain_present(&present);
// Sorted by position: the order they tick in, and a quick lookup.
// Read again only when the drawn block entities changed.
let revision = r.block_entity_revision();
if self.be_anims.present_revision != Some(revision) {
let mut present: Vec<([i32; 3], Ticker)> = r
.block_entities()
.filter_map(|(p, s)| Some((*p, self.be_anims.ticker(*s)?)))
.collect();
present.sort_unstable_by_key(|(p, _)| *p);
self.be_anims.retain_present(&present);
self.be_anims.present = present;
self.be_anims.present_revision = Some(revision);
}
let positions = std::mem::take(&mut self.be_anims.present);
let players: Vec<[f64; 3]> = match &self.player {
Some(p) if !self.spectator() => vec![[p.position.x, p.position.y, p.position.z]],
_ => Vec::new(),
@@ -198,9 +206,7 @@ impl Game<'_> {
.get("minecraft:conduit_effect_block")
.cloned()
.unwrap_or_default();
let mut positions: Vec<([i32; 3], Ticker)> = present.into_iter().collect();
positions.sort_unstable_by_key(|(p, _)| *p);
for (pos, ticker) in positions {
for &(pos, ticker) in &positions {
match ticker {
Ticker::Lid => self.be_anims.chests.entry(pos).or_default().tick(),
Ticker::Book => {
@@ -322,6 +328,7 @@ impl Game<'_> {
}
}
}
self.be_anims.present = positions;
}
/// `EndGatewayBlock.entityInside` on the server: whether the gateway at
/// `pos` let the entity in (`triggerCooldown`, with its block event).
@@ -0,0 +1,146 @@
//! `Level.tickBlockEntities` for the block entities ticked together here
//! (hoppers, crafters, jukeboxes, beacons, creaking hearts, spawners, trial
//! spawners, vaults, beehives and furnaces): only those whose state has a
//! ticker, in vanilla's list order (`horizon_client::block_entities`), in
//! chunks that tick blocks. Sculk, brewing stands and pistons tick in their
//! own passes.
use super::Game;
use horizon_client::{
Result,
block_entities::{Pos, Ticking},
containers::{BlockEntity, FurnaceKind, HOPPER_SLOTS},
};
use horizon_world::registry::BlockStateId;
impl Game<'_> {
pub(super) fn tick_block_entities(&mut self) -> Result<()> {
self.tick_mount_menu();
self.load_entity_types();
if !self.world.block_entities.has_states() {
let states = self.ticking_states();
self.world.block_entities.set_states(states);
}
self.forget_gone_hoppers();
let ticking = self.block_ticking_area();
let mut spawners = Vec::new();
let mut trial_spawners = Vec::new();
for slot in self.world.block_entity_tickers() {
let pos = slot.0;
// Ticks before this one can remove it (`TickingBlockEntity.isRemoved`).
if !self.world.block_entities.is_live(slot)
|| !ticking(pos.0, pos.2)
|| !self.border.contains(f64::from(pos.0), f64::from(pos.2))
{
continue;
}
match self.world.block_entities.get(&pos) {
Some(BlockEntity::Chest(items)) if items.len() == HOPPER_SLOTS => {
self.tick_hopper(pos)
}
Some(BlockEntity::Crafter(_)) => self.tick_crafter(pos),
Some(BlockEntity::Jukebox(_)) => self.tick_jukebox(pos),
Some(BlockEntity::Beacon(_)) => self.tick_beacon_at(pos),
Some(BlockEntity::CreakingHeart(_)) => self.tick_creaking_heart(pos)?,
Some(BlockEntity::Spawner(_)) => {
self.tick_spawner(pos)?;
spawners.push(pos);
}
Some(BlockEntity::TrialSpawner(_)) => {
self.tick_trial_spawner(pos)?;
trial_spawners.push(pos);
}
Some(BlockEntity::Vault(_)) => self.tick_vault(pos)?,
Some(BlockEntity::Beehive(_)) => self.tick_beehive(pos),
Some(BlockEntity::Furnace(_)) => self.tick_furnace(pos)?,
Some(BlockEntity::Brewing(_)) => self.tick_brewing_stand(pos)?,
_ => {}
}
}
self.update_song_volumes();
self.scan_for_hearts();
// The client ticks (particles, sounds, the turning mob) are for a
// window; a dedicated or integrated server has none.
if self.options.dedicated.is_none() {
self.client_tick_spawners(&spawners);
for key in trial_spawners {
self.client_tick_trial_spawner(key);
}
}
Ok(())
}
/// `BlockState.getTicker` of every state, for the block entities ticked
/// here. A creaking heart keeps its slot while uprooted (see
/// `tick_creaking_heart`).
fn ticking_states(&self) -> Vec<Ticking> {
let registry = self.pack.assets.registry;
(0..registry.len())
.map(|i| {
let state = BlockStateId(i as u32);
let name: &str = &self.res.facts.get(state).name;
match name {
"minecraft:hopper"
| "minecraft:crafter"
| "minecraft:beacon"
| "minecraft:creaking_heart"
| "minecraft:spawner"
| "minecraft:trial_spawner"
| "minecraft:vault"
| "minecraft:beehive"
| "minecraft:bee_nest"
| "minecraft:brewing_stand" => Ticking::Yes,
"minecraft:jukebox" => {
let record = registry
.state(state)
.and_then(|s| s.properties.get("has_record"))
.is_some_and(|v| v == "true");
if record { Ticking::Yes } else { Ticking::Idle }
}
n if FurnaceKind::from_block(n).is_some() => Ticking::Yes,
_ => Ticking::No,
}
})
.collect()
}
/// `ServerLevel.shouldTickBlocksAt`: chunks within the simulation
/// distance plus one (`DistanceManager.inBlockTickingRange`, Chebyshev
/// in chunks) of the player or a guest. With nobody there, a dedicated
/// server ticks none; the game alone (no player yet, headless fixtures)
/// ticks every chunk.
fn block_ticking_area(&self) -> impl Fn(i32, i32) -> bool + use<> {
let d = self.settings.simulation_distance.max(2) + 1;
let mut centres: Vec<(i32, i32)> = self.streaming.extra.iter().map(|&(c, _)| c).collect();
if let Some(p) = &self.player {
centres.push((
(p.position.x.floor() as i32) >> 4,
(p.position.z.floor() as i32) >> 4,
));
}
let everywhere = centres.is_empty() && self.options.dedicated.is_none();
move |x, z| {
everywhere
|| centres
.iter()
.any(|&(cx, cz)| ((x >> 4) - cx).abs().max(((z >> 4) - cz).abs()) <= d)
}
}
/// `AbstractFurnaceBlockEntity.serverTick` of the furnace at `pos`, and
/// its block's `lit` following it.
fn tick_furnace(&mut self, pos: Pos) -> Result<()> {
let Some(BlockEntity::Furnace(f)) = self.world.block_entities.get_mut(&pos) else {
return Ok(());
};
let Some(lit) = f.tick(&self.res.recipes, &self.res.items, &self.res.providers) else {
return Ok(());
};
let state = self.world.block(pos.0, pos.1, pos.2);
if let Some(mut s) = self.pack.assets.registry.state(state).cloned()
&& s.properties.contains_key("lit")
{
s.properties.insert("lit".into(), lit.to_string());
if let Ok(id) = self.pack.assets.registry.resolve(&s) {
self.world.set(pos.0, pos.1, pos.2, id)?;
}
}
Ok(())
}
}
+12 -1
View File
@@ -2,7 +2,7 @@
//! paddling controls, collisions, riding (`positionRider`, `clampRotation`,
//! dismounting), `BoatItem` placement, `VehicleEntity.hurtServer` breaking,
//! saving and `AbstractBoatRenderer` with animated paddles.
use super::{Game, Keys, view_vector};
use super::{Game, Keys, entity_culling::at, view_vector};
use horizon_client::{
blocks::Fluid,
collisions::SceneCollisions,
@@ -700,8 +700,19 @@ impl Game<'_> {
/// AbstractBoatRenderer.
pub(super) fn boat_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec<Vertex>) {
let a = alpha as f32;
let range = super::entity_culling::default_range(
glam::DVec3::new(WIDTH, HEIGHT, WIDTH),
self.settings.entity_distance,
);
for b in &self.boats {
let entity_start = out.len();
// EntityRenderer.shouldRender.
let (previous, position) = (at(b.previous), at(b.position));
if !self.standing_entity_in_view(
camera, previous, position, alpha, WIDTH, HEIGHT, range, 0.0,
) {
continue;
}
let models = if b.chest {
&self.boat_models.chest_models
} else {
+17
View File
@@ -533,6 +533,23 @@ impl Game<'_> {
}
}
}
/// The server's completions for an `ask_server` request
/// (ClientPacketListener.handleCommandSuggestions).
pub(super) fn chat_server_suggestions(
&mut self,
id: i32,
range: (usize, usize),
list: Vec<(String, Option<String>)>,
) {
let m = Measure(&self.atlas.font);
let c = Commands {
dispatcher: chat_tree(&self.remote, &self.mods),
registries: &self.ui.registries,
};
if let Some(screen) = self.ui.chat_screen.as_mut() {
screen.server_suggestions(&m, &c, id, range, list);
}
}
/// Text typed into the chat box (control socket `chat`).
pub(super) fn chat_type(&mut self, text: &str) {
let m = Measure(&self.atlas.font);
@@ -357,6 +357,7 @@ impl Game<'_> {
silent: false,
store: None,
elsewhere: false,
level: None,
block: Some(pos),
};
// performPrefixedCommand: a leading slash is allowed.
@@ -598,13 +599,13 @@ impl Game<'_> {
if let Ok(id) = registry.resolve(&wanted)
&& wanted != *current
{
let entity = self.world.block_entities.remove(&pos);
let entity = self.world.block_entities.take(&pos);
let at = BlockPos::new(pos.0, pos.1, pos.2);
self.with_level(|b, level, ticks| {
b.set_block(level, ticks, at, id, flags::UPDATE_CLIENTS)
});
if let Some(entity) = entity {
self.world.block_entities.insert(pos, entity);
self.world.block_entities.put(pos, entity);
}
let _ = self.process_level_events();
}
+72 -16
View File
@@ -165,14 +165,20 @@ impl Game<'_> {
}
self.broadcast_to_admins(message);
}
/// CommandSourceStack.broadcastToAdmins, for a guest's command on a
/// dedicated server (`sendSuccess` with `broadcast`): `[name: message]`,
/// gray and italic, for the other operators when `send_command_feedback`
/// and the console when `log_admin_commands`. Queued while the guest acts;
/// `send_admin_feedback` sends it.
fn broadcast_to_admins(&mut self, message: Text) {
if self.lan_acting.is_none()
|| self.options.dedicated.is_none()
/// CommandSourceStack.broadcastToAdmins (`sendSuccess` with `broadcast`)
/// for a guest's command, the host's in a world open to LAN and the
/// dedicated server console's when `broadcast-console-to-ops` is on:
/// `[name: message]`, gray and italic, for the other operators when
/// `send_command_feedback`, and for a player's command on a dedicated
/// server the console when `log_admin_commands`. Queued while the
/// command runs; `send_admin_feedback` sends it.
pub(super) fn broadcast_to_admins(&mut self, message: Text) {
let informs = match self.console_broadcast {
Some(broadcast) => broadcast,
// While a guest acts the host's LanHost is out of `self.lan`.
None => self.lan_acting.is_some() || self.lan.is_some(),
};
if !informs
|| message
.translation_key()
.is_some_and(|k| admin::QUIET.contains(&k))
@@ -180,20 +186,46 @@ impl Game<'_> {
return;
}
let ops = self.ui.rules.bool("send_command_feedback");
let console = self.ui.rules.bool("log_admin_commands");
// MinecraftServer.sendSystemMessage, unless the server is the source.
let console = self.console_broadcast.is_none()
&& self.lan_acting.is_some()
&& self.options.dedicated.is_some()
&& self.ui.rules.bool("log_admin_commands");
if !ops && !console {
return;
}
// getDisplayName: the entity the command runs as (`execute as`).
let who = self
.command_source
.and_then(|s| s.entity)
.unwrap_or(Target::Player);
let line = Text::translate("chat.type.admin", &[self.target_name(who), message])
// getDisplayName: the entity the command runs as (`execute as`), or
// the server's own source, "Server".
let who = match self.command_source.and_then(|s| s.entity) {
Some(entity) => self.target_name(entity),
None if self.console_broadcast.is_some() => Text::literal("Server".to_owned()),
None => self.player_display_name(),
};
let line = Text::translate("chat.type.admin", &[who, message])
.with_color(text::GRAY)
.italic();
self.admin_feedback.push((line, ops, console));
}
/// Player.getDisplayName: the name (team-formatted), suggesting a
/// `/tell`, showing the player on hover, inserting the name.
fn player_display_name(&self) -> Text {
let name = self.acting_player_name().to_owned();
let Some(uuid) = self.lan_acting_uuid else {
return self.target_name(Target::Player);
};
self.target_name(Target::Player).with_component_fields(vec![
(
"click_event".into(),
serde_json::json!({"action": "suggest_command", "command": format!("/tell {name} ")}),
),
(
"hover_event".into(),
serde_json::json!({"action": "show_entity", "id": "minecraft:player",
"uuid": horizon_protocol::crypto::uuid_string(uuid), "name": name}),
),
("insertion".into(), name.into()),
])
}
fn source_position(&self) -> [f64; 3] {
if let Some(s) = &self.command_source {
return s.pos;
@@ -1124,7 +1156,23 @@ impl Game<'_> {
(-(dy.atan2(horizontal).to_degrees())) as f32,
]);
}
// `execute in` another dimension: a server's player moves to that
// level (ServerPlayer.teleport into another level), after the command.
let level = self
.command_source
.and_then(|s| s.level)
.filter(|d| *d != self.dim && self.options.dedicated.is_some());
for &t in &targets {
if let (Some(dim), Target::Player, Some(conn)) = (level, t, self.lan_acting) {
self.level_teleports
.push(super::server_travel::LevelTeleport {
conn,
dim,
at: pos,
rotation,
});
continue;
}
self.teleport_to(t, pos, rotation);
}
let [x, y, z] = pos.map(|v| Text::literal(format_double(v)));
@@ -1453,7 +1501,9 @@ impl Game<'_> {
return Err(err("commands.summon.failed", &[]));
}
"experience_orb" => {
self.next_entity += 1;
self.orbs.push(horizon_client::entities::ExperienceOrb {
id: self.next_entity,
position: Vec3::new(pos[0], pos[1], pos[2]),
previous: Vec3::new(pos[0], pos[1], pos[2]),
velocity: Vec3::new(0.0, 0.0, 0.0),
@@ -1479,7 +1529,13 @@ impl Game<'_> {
self.carts.push(cart);
name = Text::translate(&format!("entity.minecraft.{k}"), &[]);
}
_ => return Err(err("commands.summon.failed", &[])),
// SummonCommand.createEntity: any other type from an empty compound.
_ => {
let Some(target) = self.summon_with_nbt(&kind, pos, "{}")? else {
return Err(err("commands.summon.failed", &[]));
};
name = self.target_name(target);
}
}
}
self.feedback(Text::translate("commands.summon.success", &[name]));
@@ -86,7 +86,7 @@ impl Game<'_> {
Target::Player => {
let mut instance = EffectInstance::new(effect.id, duration, amplifier);
instance.visible = particles;
self.potions.effects.add(instance)
self.add_player_effect(instance)
}
Target::Mob(id) => match self.mobs.iter_mut().find(|m| m.id == id) {
Some(m) => {
@@ -134,11 +134,13 @@ impl Game<'_> {
(Target::Player, None) => {
let any = !self.potions.effects.list.is_empty();
self.potions.effects.clear();
self.apply_effect_status();
any
}
(Target::Player, Some(e)) => {
let before = self.potions.effects.list.len();
self.potions.effects.list.retain(|x| x.id != e.id);
self.apply_effect_status();
self.potions.effects.list.len() != before
}
(Target::Mob(id), e) => match self.mobs.iter_mut().find(|m| m.id == id) {
@@ -26,6 +26,9 @@ pub(in crate::game) struct Source {
/// `execute in` another dimension than the one Horizon has loaded: none
/// of its chunks are loaded.
pub elsewhere: bool,
/// The dimension `execute in` named, if any: a server teleports its
/// players there (`TeleportCommand` into the source's level).
pub level: Option<super::super::Dim>,
/// The command block whose output this source is
/// (`BaseCommandBlock.CloseableCommandBlockSource`).
pub block: Option<(i32, i32, i32)>,
@@ -77,6 +80,7 @@ impl Game<'_> {
silent: false,
store: None,
elsewhere: false,
level: None,
block: None,
}
}
@@ -90,6 +94,7 @@ impl Game<'_> {
silent: true,
store: None,
elsewhere: false,
level: None,
block: None,
}
}
@@ -441,6 +446,7 @@ impl Game<'_> {
pos: self.target_position(t)?,
rot: self.target_rotation(t),
elsewhere: false,
level: None,
..s
})
})
@@ -544,6 +550,7 @@ impl Game<'_> {
}
vec![Source {
elsewhere: dim != self.dim.id(),
level: Some(super::super::Dim::from_id(dim)),
..s
}]
}
@@ -1,6 +1,7 @@
//! `/tellraw` (TellRawCommand) and `/title` (TitleCommand).
use super::{Arg, Context, Game, R, Target, err};
use horizon_client::text::Text;
use horizon_client::{hud_overlays::Titles, lan::data::component_nbt, text::Text};
use horizon_protocol::packets::play::{self, Clientbound as C};
impl Game<'_> {
/// ComponentArgument with selectors resolved for the source
@@ -153,30 +154,45 @@ impl Game<'_> {
let name = self.target_name(Target::Player);
let single = n == 1;
let key = if ctx.has("clear") {
self.titles.clear();
self.titles_or_packet(Titles::clear, C::ClearTitles(play::Bool1 { value: false }));
"cleared"
} else if ctx.has("reset") {
self.titles.clear();
self.titles.reset_times();
self.titles_or_packet(
|t| {
t.clear();
t.reset_times();
},
C::ClearTitles(play::Bool1 { value: true }),
);
"reset"
} else if ctx.has("times") {
let get = |k: &str| match ctx.get(k) {
Some(Arg::Int(v)) => *v,
_ => -1,
};
self.titles
.set_times(get("fadeIn"), get("stay"), get("fadeOut"));
let (fade_in, stay, fade_out) = (get("fadeIn"), get("stay"), get("fadeOut"));
self.titles_or_packet(
|t| t.set_times(fade_in, stay, fade_out),
C::SetTitlesAnimation(play::TitlesAnimation {
fade_in,
stay,
fade_out,
}),
);
"times"
} else {
let text = self.component_arg(ctx, "title")?;
let sent = play::Text {
text: component_nbt(&text.component()),
};
if ctx.has("subtitle") {
self.titles.set_subtitle(text);
self.titles_or_packet(|t| t.set_subtitle(text), C::SetSubtitleText(sent));
"show.subtitle"
} else if ctx.has("actionbar") {
self.titles.set_overlay(text, false);
self.titles_or_packet(|t| t.set_overlay(text, false), C::SetActionBarText(sent));
"show.actionbar"
} else {
self.titles.set_title(text);
self.titles_or_packet(|t| t.set_title(text), C::SetTitleText(sent));
"show.title"
}
};
@@ -191,4 +207,13 @@ impl Game<'_> {
self.feedback(message);
Ok(n as i32)
}
/// The player the title is for: the guest acting now is sent the packet
/// (TitleCommand's `connection.send`), the window's own player shows it.
fn titles_or_packet(&mut self, local: impl FnOnce(&mut Titles), packet: C) {
if self.lan_acting.is_some() {
self.guest_packets.push(packet);
} else {
local(&mut self.titles);
}
}
}
@@ -783,6 +783,10 @@ impl Game<'_> {
status["lod"]["sampled_target_tiles"] = sampled.into();
status["pending_uploads"] = self.pending_uploads.len().into();
status["physical_keys"] = json!(physical_keys);
// Boats, minecarts, armor stands, item frames and paintings.
status["objects"] = json!(self.objects_status());
// Primed TNT, falling blocks, projectiles, tridents and end crystals.
status["projectiles"] = json!(self.projectiles_status());
status
}
}
+37 -43
View File
@@ -164,7 +164,7 @@ impl Game<'_> {
return;
}
let key = (home[0], home[1], home[2]);
let Some(BlockEntity::CreakingHeart(mut heart)) = self.world.block_entities.remove(&key)
let Some(BlockEntity::CreakingHeart(mut heart)) = self.world.block_entities.take(&key)
else {
return;
};
@@ -173,7 +173,7 @@ impl Game<'_> {
});
self.world
.block_entities
.insert(key, BlockEntity::CreakingHeart(heart));
.put(key, BlockEntity::CreakingHeart(heart));
}
/// `Creaking.tearDown`: the crumble particles.
pub(super) fn creaking_tear_down(&mut self, center: [f64; 3], spread: [f64; 3]) {
@@ -220,7 +220,7 @@ impl Game<'_> {
/// death and a natural heart drops experience.
pub(super) fn creaking_heart_broken(&mut self, pos: [i32; 3]) {
let key = (pos[0], pos[1], pos[2]);
let Some(BlockEntity::CreakingHeart(mut heart)) = self.world.block_entities.remove(&key)
let Some(BlockEntity::CreakingHeart(mut heart)) = self.world.block_entities.take(&key)
else {
return;
};
@@ -248,43 +248,35 @@ impl Game<'_> {
}
self.world
.block_entities
.insert(key, BlockEntity::CreakingHeart(heart));
.put(key, BlockEntity::CreakingHeart(heart));
}
/// `CreakingHeartBlockEntity.serverTick` for every heart.
pub(super) fn tick_creaking_hearts(&mut self) -> Result<()> {
let keys: Vec<Pos> = self
.world
.block_entities
.iter()
.filter(|(_, e)| matches!(e, BlockEntity::CreakingHeart(_)))
.map(|(k, _)| *k)
.collect();
for key in keys {
let Some(BlockEntity::CreakingHeart(mut heart)) =
self.world.block_entities.remove(&key)
else {
continue;
};
let state = self.world.block(key.0, key.1, key.2);
if &*self.res.facts.get(state).name != "minecraft:creaking_heart" {
// The block is gone: preRemoveSideEffects.
self.with_heart(key, &mut heart, |h, _, _, host, out| {
creaking_heart::remove_protector(h, host, false, out);
})?;
continue;
}
// getTicker: none once uprooted.
if self.heart_state_name(state) != "uprooted" {
let pos = [key.0, key.1, key.2];
self.with_heart(key, &mut heart, |h, w, lr, host, out| {
creaking_heart::server_tick(h, pos, w, lr, host, out);
})?;
}
self.world
.block_entities
.insert(key, BlockEntity::CreakingHeart(heart));
/// `CreakingHeartBlockEntity.serverTick` of the heart at `key`. Its slot
/// stays while uprooted, so that a heart whose block went away is still
/// found here and lets go of its protector.
pub(super) fn tick_creaking_heart(&mut self, key: Pos) -> Result<()> {
let Some(BlockEntity::CreakingHeart(mut heart)) = self.world.block_entities.take(&key)
else {
return Ok(());
};
let state = self.world.block(key.0, key.1, key.2);
if &*self.res.facts.get(state).name != "minecraft:creaking_heart" {
// The block is gone: preRemoveSideEffects.
self.world.block_entities.forget(&key);
self.with_heart(key, &mut heart, |h, _, _, host, out| {
creaking_heart::remove_protector(h, host, false, out);
})?;
return Ok(());
}
self.scan_for_hearts();
// getTicker: none once uprooted.
if self.heart_state_name(state) != "uprooted" {
let pos = [key.0, key.1, key.2];
self.with_heart(key, &mut heart, |h, w, lr, host, out| {
creaking_heart::server_tick(h, pos, w, lr, host, out);
})?;
}
self.world
.block_entities
.put(key, BlockEntity::CreakingHeart(heart));
Ok(())
}
/// `ServerLevel.isSpawningMonsters`.
@@ -295,7 +287,7 @@ impl Game<'_> {
}
/// Hearts that came with generated or loaded chunks get their block
/// entity (`newBlockEntity`) the first time their chunk is seen.
fn scan_for_hearts(&mut self) {
pub(super) fn scan_for_hearts(&mut self) {
let Some(heart) = self
.pack
.assets
@@ -327,13 +319,16 @@ impl Game<'_> {
}
let hearts = &self.creaking.hearts;
let _ = heart;
let is_heart = |id: u32| hearts.get(id as usize).copied().unwrap_or(false);
for (si, section) in chunk.sections.iter().enumerate() {
if section.is_uniform(0) {
// Only a section whose palette holds a heart state can have
// one: the others are skipped without reading their 4,096 blocks.
if !section.blocks.maybe_has(is_heart) {
continue;
}
for i in 0..4096 {
let id = section.get(i);
if !hearts.get(id as usize).copied().unwrap_or(false) {
if !is_heart(id) {
continue;
}
let (lx, lz, ly) = ((i & 15) as i32, ((i >> 4) & 15) as i32, (i >> 8) as i32);
@@ -344,8 +339,7 @@ impl Game<'_> {
);
self.world
.block_entities
.entry(pos)
.or_insert_with(|| BlockEntity::CreakingHeart(Box::default()));
.get_or_insert_with(pos, || BlockEntity::CreakingHeart(Box::default()));
}
}
}
@@ -196,6 +196,7 @@ impl Game<'_> {
hero: self.potions.effects.get("hero_of_the_village").is_some(),
uuid: self.level.player_uuid.unwrap_or_default(),
allies: std::sync::Arc::new(self.player_allies()),
remote: false,
})
}
/// Biome facts at a position for finalizeSpawn and variant rules.
+64 -6
View File
@@ -402,8 +402,32 @@ struct ServerState {
/// When the last passes of the loop ended, for the tick rate horizon-server shows.
ticks: std::collections::VecDeque<Instant>,
paused: bool,
/// `broadcast-console-to-ops`.
broadcast_console: bool,
}
/// The dedicated-only commands' replies vanilla sends with `broadcast`
/// (`sendSuccess(..., true)`): the operators hear of them.
const BROADCAST: &[&str] = &[
"commands.ban.success",
"commands.banip.info",
"commands.banip.success",
"commands.deop.success",
"commands.kick.success",
"commands.op.success",
"commands.pardon.success",
"commands.pardonip.success",
"commands.save.disabled",
"commands.save.enabled",
"commands.save.success",
"commands.stop.stopping",
"commands.whitelist.add.success",
"commands.whitelist.disabled",
"commands.whitelist.enabled",
"commands.whitelist.reloaded",
"commands.whitelist.remove.success",
];
impl Game<'_> {
/// DedicatedServer.initServer and MinecraftServer.runServer.
pub(super) fn run_dedicated(&mut self) -> Result<()> {
@@ -449,6 +473,18 @@ impl Game<'_> {
// DedicatedServer.initServer: names nobody has resolve offline only without authentication.
cache.resolve_offline_users = !props.online_mode;
*USER_CACHE.lock().unwrap() = Some(cache);
// Services.create: the services' public keys, fetched in the
// background (they check players' chat keys).
let secure_chat = Arc::new(horizon_client::lan::SecureChat::new(
props.enforce_secure_profile && props.online_mode,
|| {
let discovery = profiles::discovery_url();
profiles::fetch_profile_key_keys(&discovery).unwrap_or_else(|e| {
::log::error!("{e}");
Vec::new()
})
},
));
log("INFO", "Starting minecraft server version 26.3");
log("INFO", "Loading properties");
let game_mode = props.game_mode;
@@ -547,8 +583,7 @@ impl Game<'_> {
enable_status: props.enable_status,
hide_online_players: props.hide_online_players,
favicon,
// DedicatedServer.enforceSecureProfile needs online mode.
enforces_secure_chat: false,
secure_chat: Some(secure_chat),
accepts_transfers: props.accepts_transfers,
announce: false,
listen: true,
@@ -612,6 +647,7 @@ impl Game<'_> {
empty_ticks: 0,
ticks: Default::default(),
paused: false,
broadcast_console: props.broadcast_console_to_ops,
};
let pause_after = props.pause_when_empty_seconds * 20;
let idle_timeout = props.player_idle_timeout;
@@ -619,7 +655,7 @@ impl Game<'_> {
while !state.stop {
let tick_start = Instant::now();
while let Ok(line) = state.console.try_recv() {
self.console_command(&mut state, &line);
self.console_line(&mut state, &line);
}
self.poll_server_control(&mut state);
let players = self.lan.as_ref().map_or(0, |h| h.hub.guests.len());
@@ -767,14 +803,36 @@ impl Game<'_> {
})
});
if found.is_none() {
self.console_reply(Text::translate("argument.player.unknown", &[]));
let unknown = Text::translate("argument.player.unknown", &[]);
log("INFO", &format!("System chat: {}", unknown.plain()));
}
found
}
/// MinecraftServer.sendSystemMessage: what the console is told.
fn console_reply(&self, text: Text) {
/// MinecraftServer.sendSystemMessage: what the console is told; while
/// the console runs a command, the replies vanilla broadcasts go to the
/// operators too.
fn console_reply(&mut self, text: Text) {
log("INFO", &format!("System chat: {}", text.plain()));
if self.console_broadcast.is_some()
&& text
.translation_key()
.is_some_and(|k| BROADCAST.contains(&k))
{
self.broadcast_to_admins(text);
}
}
/// One console line, then the operators' share of its feedback.
fn console_line(&mut self, state: &mut ServerState, line: &str) {
self.console_broadcast = Some(state.broadcast_console);
self.console_command(state, line);
self.console_broadcast = None;
if let Some(mut host) = self.lan.take() {
self.send_admin_feedback(&mut host, None);
self.lan = Some(host);
}
self.admin_feedback.clear();
}
/// DedicatedServer.handleConsoleInputs: one console line, run as the
@@ -318,8 +318,18 @@ impl Game<'_> {
} else {
self.dispense_from(origin, state)?;
// CrafterBlockEntity.serverTick, the crafting animation running down.
let mut crafters: Vec<(i32, i32, i32)> = self
.world
.block_entities
.iter()
.filter(|(_, e)| matches!(e, BlockEntity::Crafter(_)))
.map(|(p, _)| *p)
.collect();
crafters.sort_unstable();
for _ in 0..case["ticks"].as_u64().unwrap_or(0) {
self.tick_crafters();
for &p in &crafters {
self.tick_crafter(p);
}
}
}
+6
View File
@@ -74,6 +74,8 @@ impl Respawn {
}
#[derive(Clone, Debug)]
pub(super) struct Crystal {
/// The entity id a server tracks it by (0 until it is tracked).
pub id: u32,
pub position: Vec3,
pub show_bottom: bool,
/// EndCrystal.time (the bob and spin), starting random.
@@ -553,6 +555,7 @@ impl Game<'_> {
}
let time = self.world.random.next_int_bound(100_000).unwrap_or(0);
self.crystals.push(Crystal {
id: 0,
position: at,
show_bottom: true,
time,
@@ -2301,6 +2304,7 @@ impl Crystal {
pub(super) fn from_nbt(tag: &Tag, time: i32) -> Option<Self> {
let (position, _, _) = horizon_client::entity_nbt::boat_from_nbt(tag)?;
Some(Self {
id: 0,
position,
show_bottom: !matches!(tag.get("ShowBottom"), Some(Tag::Byte(0))),
time,
@@ -2403,6 +2407,7 @@ impl Game<'_> {
}
let time = self.world.random.next_int_bound(100_000).unwrap_or(0);
self.crystals.push(Crystal {
id: 0,
position: Vec3::new(x + 0.5, y, z + 0.5),
show_bottom: false,
time,
@@ -2665,6 +2670,7 @@ impl Game<'_> {
.retain(|c| c.position.distance_squared(at) > 0.01);
let time = self.world.random.next_int_bound(100_000).unwrap_or(0);
self.crystals.push(Crystal {
id: 0,
position: at,
show_bottom: true,
time,
@@ -49,3 +49,64 @@ impl Game<'_> {
}
}
}
/// Entity.shouldRenderAtSqrDistance's default range: 64 times the bounding
/// box's mean edge, scaled by the entity distance option.
pub(super) fn default_range(size: glam::DVec3, view_scale: f32) -> f64 {
let edge = (size.x + size.y + size.z) / 3.0;
let edge = if edge.is_nan() { 1.0 } else { edge };
edge * 64.0 * f64::from(view_scale)
}
impl Game<'_> {
/// EntityRenderer.shouldRender: the entity within `range` blocks of the
/// camera, measured from its current `position`, and its culling box
/// (`lo`..`hi`, interpolated, in world space) grown by 0.5 in the view.
pub(super) fn entity_in_view(
&self,
camera: glam::DVec3,
position: glam::DVec3,
range: f64,
lo: glam::DVec3,
hi: glam::DVec3,
) -> bool {
if (position - camera).length_squared() >= range * range {
return false;
}
self.view_frustum.as_ref().is_none_or(|view| {
view.intersects(
(lo - camera - glam::DVec3::splat(0.5)).as_vec3(),
(hi - camera + glam::DVec3::splat(0.5)).as_vec3(),
)
})
}
}
/// An entity's position as a `DVec3`.
pub(super) fn at(p: horizon_core::geometry::Vec3) -> glam::DVec3 {
glam::DVec3::new(p.x, p.y, p.z)
}
impl Game<'_> {
/// `entity_in_view` for an entity whose box stands on its position,
/// `width` wide and `height` tall, interpolated by `alpha` and grown by
/// `grow` (a renderer's getBoundingBoxForCulling).
#[allow(clippy::too_many_arguments)]
pub(super) fn standing_entity_in_view(
&self,
camera: glam::DVec3,
previous: glam::DVec3,
position: glam::DVec3,
alpha: f64,
width: f64,
height: f64,
range: f64,
grow: f64,
) -> bool {
let p = previous.lerp(position, alpha);
let half = glam::DVec3::new(width / 2.0 + grow, grow, width / 2.0 + grow);
let lo = p - half;
let hi = p + glam::DVec3::new(half.x, height + grow, half.z);
self.entity_in_view(camera, position, range, lo, hi)
}
}
+45 -5
View File
@@ -18,21 +18,46 @@ use horizon_core::{
};
pub(super) struct Rocket {
position: Vec3,
/// The entity id a server tracks it by (0 until it is tracked).
pub id: u32,
pub(super) position: Vec3,
previous: Vec3,
velocity: Vec3,
pub(super) velocity: Vec3,
life: i32,
lifetime: i32,
explosions: Vec<FireworkExplosion>,
/// Boosting the player (attachedToEntity).
attached: bool,
pub(super) attached: bool,
/// `DATA_SHOT_AT_ANGLE` (dispensers): constant velocity, exploding on
/// the first block it hits.
angled: bool,
pub(super) angled: bool,
/// `DATA_ID_FIREWORKS_ITEM`: the stack it was launched from.
item: ItemStack,
pub(super) item: ItemStack,
}
impl Rocket {
/// A rocket a server sent (`handleAddEntity`): placed and moved by it.
pub(super) fn remote(id: u32, position: Vec3, velocity: Vec3) -> Self {
let item = ItemStack::new("minecraft:firework_rocket", 1);
let (_, explosions) = fireworks_of(&item);
Self {
id,
position,
previous: position,
velocity,
life: 0,
lifetime: i32::MAX,
explosions,
attached: false,
angled: false,
item,
}
}
/// One tick of a server's client: the previous position, then `step`.
pub(super) fn remote_step(&mut self, step: impl FnOnce(Vec3) -> Vec3) {
self.previous = self.position;
self.life += 1;
self.position = step(self.position);
}
/// Position and motion (the dispenser parity fixture).
pub(super) fn motion(&self) -> (Vec3, Vec3) {
(self.position, self.velocity)
@@ -56,6 +81,7 @@ impl Game<'_> {
+ r.next_int_bound(6).unwrap_or(0)
+ r.next_int_bound(7).unwrap_or(0);
Rocket {
id: 0,
position: at,
previous: at,
velocity,
@@ -253,6 +279,20 @@ impl Game<'_> {
pub(super) fn rocket_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec<Vertex>) {
let orientation = glam::Mat4::from_quat(self.camera_orientation());
for r in self.rockets.iter().filter(|r| !r.attached) {
// FireworkRocketEntity.shouldRenderAtSqrDistance: within 64 blocks;
// EntityRenderer.shouldRender: its 0.25 box in the view.
if !self.standing_entity_in_view(
camera,
super::entity_culling::at(r.previous),
super::entity_culling::at(r.position),
alpha,
0.25,
0.25,
64.0,
0.0,
) {
continue;
}
let p = glam::DVec3::new(
r.previous.x + (r.position.x - r.previous.x) * alpha,
r.previous.y + (r.position.y - r.previous.y) * alpha,
+18
View File
@@ -304,9 +304,27 @@ impl Game<'_> {
let sprites = &self.atlas.sprites;
let mut maps: Vec<(i32, glam::Mat4, u32)> = Vec::new();
let mut items: Vec<(ItemStack, u32, glam::Mat4, u8)> = Vec::new();
// ItemFrame.shouldRenderAtSqrDistance: 1024 blocks at 100%.
let range = 16.0 * 64.0 * f64::from(self.settings.entity_distance);
for f in &self.item_frames {
let entity_start = out.len();
let map = f.item.as_ref().and_then(super::maps::map_id);
// EntityRenderer.shouldRender: its box (a block wide with a map),
// measured from the box's centre.
let (lo, hi) = f.bounds();
let (mut lo, mut hi) = (glam::DVec3::from(lo), glam::DVec3::from(hi));
if map.is_some() {
let s = f.step();
for i in 0..3 {
if s[i] == 0 {
let c = (lo[i] + hi[i]) / 2.0;
(lo[i], hi[i]) = (c - 0.5, c + 0.5);
}
}
}
if !self.entity_in_view(camera, (lo + hi) / 2.0, range, lo, hi) {
continue;
}
let s = f.step();
// Pose: to the block centre, then X/Y rotation by facing.
let (x_rot, y_rot) = if s[1] == 0 {
+45 -3
View File
@@ -28,7 +28,7 @@ use std::{
path::Path,
sync::{
Arc,
atomic::{AtomicBool, AtomicU16, AtomicU32, Ordering},
atomic::{AtomicBool, AtomicI32, AtomicU16, AtomicU32, Ordering},
mpsc::{Receiver, Sender, channel, sync_channel},
},
thread::JoinHandle,
@@ -45,6 +45,10 @@ struct Flags {
/// while it is not.
published: AtomicU16,
smoothed_tick_ms: AtomicU32,
/// `options.renderDistance` and `options.simulationDistance`, which the
/// server follows while it runs (IntegratedServer.tickServer).
render_distance: AtomicI32,
simulation_distance: AtomicI32,
}
/// Work the window hands its server thread (`MinecraftServer.execute`).
@@ -66,6 +70,13 @@ impl Integrated {
pub fn set_paused(&self, paused: bool) {
self.flags.paused.store(paused, Ordering::Relaxed);
}
/// The window's render and simulation distances, for the server to follow.
pub fn set_distances(&self, render: i32, simulation: i32) {
self.flags.render_distance.store(render, Ordering::Relaxed);
self.flags
.simulation_distance
.store(simulation, Ordering::Relaxed);
}
/// `IntegratedServer.getPort` while `isPublished`.
pub fn published(&self) -> Option<u16> {
Some(self.flags.published.load(Ordering::Relaxed)).filter(|&p| p != 0)
@@ -192,6 +203,12 @@ impl Game<'_> {
options.dev_mods.clear();
let (res, pack, settings) = (self.res.clone(), self.pack.clone(), self.settings.clone());
let flags = Arc::new(Flags::default());
flags
.render_distance
.store(settings.render_distance, Ordering::Relaxed);
flags
.simulation_distance
.store(settings.simulation_distance, Ordering::Relaxed);
let (ready_tx, ready) = channel();
let (tasks, server_tasks) = channel();
let server_flags = flags.clone();
@@ -249,7 +266,9 @@ impl Game<'_> {
launch.create.as_ref(),
)?;
let saved = Box::new(self.level.clone());
let view_distance = self.settings.render_distance.clamp(2, 32);
// Math.max(2, options.renderDistance): past vanilla's 32 when the
// window's render distance is (Horizon's options go to 64).
let view_distance = self.settings.render_distance.max(2);
let config = HubConfig {
default_game_mode: self.level.mode(),
// Only the owner until it is opened to the LAN.
@@ -257,7 +276,7 @@ impl Game<'_> {
force_game_mode: false,
hardcore: self.level.hardcore,
view_distance,
simulation_distance: self.settings.simulation_distance.clamp(2, 32),
simulation_distance: self.settings.simulation_distance.max(2),
dimension: self.dim.id().to_owned(),
seed: self.level.seed,
max_players: MAX_PLAYERS,
@@ -318,6 +337,7 @@ impl Game<'_> {
// Only the connections run.
self.tick_server(true)?;
} else {
self.follow_distances(&flags);
let started = Instant::now();
self.tick_server(false)?;
self.debug_charts.log_tick(started, started.elapsed());
@@ -438,6 +458,28 @@ impl Game<'_> {
}
/// Publish or unpublish for real, once the hub is in its place (a
/// player's `/publish` runs while it is out).
/// IntegratedServer.tickServer: the server follows the window's render
/// and simulation distances when they change.
fn follow_distances(&mut self, flags: &Flags) {
let Some(host) = self.lan.as_mut() else {
return;
};
let view = flags.render_distance.load(Ordering::Relaxed).max(2);
let old = host.hub.config.view_distance;
if view != old {
log::info!("Changing view distance to {view}, from {old}");
host.hub.set_view_distance(view);
self.settings.render_distance = view;
}
let simulation = flags.simulation_distance.load(Ordering::Relaxed).max(2);
let old = host.hub.config.simulation_distance;
if simulation != old {
log::info!("Changing simulation distance to {simulation}, from {old}");
host.hub.set_simulation_distance(simulation);
self.settings.simulation_distance = simulation;
}
}
fn apply_publish(&mut self) {
if self.lan.is_none() {
return;
+42 -52
View File
@@ -140,63 +140,53 @@ impl Game<'_> {
pub(super) fn jukebox_removed(&mut self, pos: [i32; 3]) {
self.stop_song(pos);
}
/// `JukeboxSongPlayer.tick` for every playing jukebox.
pub(super) fn tick_jukeboxes(&mut self) {
let playing: Vec<((i32, i32, i32), String, i64)> = self
.world
.block_entities
.iter()
.filter_map(|(k, e)| match e {
BlockEntity::Jukebox(j) if j.playing => {
let song = self
.res
.items
.get(&j.record.as_ref()?.item)?
.jukebox_song
.clone()?;
Some((*k, song, j.ticks))
}
_ => None,
})
.collect();
for (key, song, ticks) in playing {
let pos = [key.0, key.1, key.2];
let Some(s) = self.res.items.songs.get(&song).cloned() else {
continue;
};
if s.finished(ticks) {
if let Some(BlockEntity::Jukebox(j)) = self.world.block_entities.get_mut(&key) {
j.playing = false;
j.ticks = 0;
}
self.stop_song(pos);
self.jukebox_changed(pos);
continue;
}
if !self.jukebox_sounds.contains_key(&key) && ticks == 0 {
self.start_song(pos, &song);
}
if ticks % 20 == 0 {
let color = f64::from(self.world.random.next_int_bound(4).unwrap_or(0)) / 24.0;
let at = [
f64::from(pos[0]) + 0.5,
f64::from(pos[1]) + 1.2,
f64::from(pos[2]) + 0.5,
];
self.particles.add(
&ParticleOptions::simple(ParticleType::Note),
at,
[color, 0.0, 0.0],
);
}
/// `JukeboxSongPlayer.tick` of the jukebox at `key`, while it plays.
pub(super) fn tick_jukebox(&mut self, key: (i32, i32, i32)) {
let playing = match self.world.block_entities.get(&key) {
Some(BlockEntity::Jukebox(j)) if j.playing => j.record.as_ref().and_then(|r| {
let song = self.res.items.get(&r.item)?.jukebox_song.clone()?;
Some((song, j.ticks))
}),
_ => None,
};
let Some((song, ticks)) = playing else {
return;
};
let pos = [key.0, key.1, key.2];
let Some(s) = self.res.items.songs.get(&song).cloned() else {
return;
};
if s.finished(ticks) {
if let Some(BlockEntity::Jukebox(j)) = self.world.block_entities.get_mut(&key) {
j.ticks += 1;
j.playing = false;
j.ticks = 0;
}
self.stop_song(pos);
self.jukebox_changed(pos);
return;
}
if !self.jukebox_sounds.contains_key(&key) && ticks == 0 {
self.start_song(pos, &song);
}
if ticks % 20 == 0 {
let color = f64::from(self.world.random.next_int_bound(4).unwrap_or(0)) / 24.0;
let at = [
f64::from(pos[0]) + 0.5,
f64::from(pos[1]) + 1.2,
f64::from(pos[2]) + 0.5,
];
self.particles.add(
&ParticleOptions::simple(ParticleType::Note),
at,
[color, 0.0, 0.0],
);
}
if let Some(BlockEntity::Jukebox(j)) = self.world.block_entities.get_mut(&key) {
j.ticks += 1;
}
self.update_song_volumes();
}
/// Let go of songs that ended or whose jukebox stopped.
fn update_song_volumes(&mut self) {
pub(super) fn update_song_volumes(&mut self) {
let sounds: Vec<_> = self
.jukebox_sounds
.iter()
+85 -22
View File
@@ -73,7 +73,7 @@ pub(super) struct Owner {
}
/// A stable UUID for an entity that has none.
fn entity_uuid(id: u32) -> u128 {
pub(super) fn entity_uuid(id: u32) -> u128 {
0x4856_5a4e_0000_0000_0000_0000_0000_0000u128 | u128::from(id)
}
@@ -144,11 +144,15 @@ fn mob_meta(m: &Mob, hub: &Hub) -> Vec<(u8, i32, Value)> {
meta.push((3, serializer::BOOLEAN, Value::Bool(true)));
}
}
if m.health < m.kind.max_health {
meta.push((9, serializer::FLOAT, Value::Float(m.health.max(0.0))));
// LivingEntity.DATA_HEALTH_ID: defined as 1, then set to the max health.
let health = m.health.max(0.0);
if health != 1.0 {
meta.push((9, serializer::FLOAT, Value::Float(health)));
}
if kind == "minecraft:rabbit" && m.no_ai {
meta.push((15, serializer::BYTE, Value::Byte(1)));
// Mob.DATA_MOB_FLAGS_ID: no AI 1, left-handed 2.
let flags = i8::from(m.no_ai) | i8::from(m.extra.left_handed) << 1;
if flags != 0 {
meta.push((15, serializer::BYTE, Value::Byte(flags)));
}
if m.is_baby()
&& let Some(index) = baby_index(kind)
@@ -363,6 +367,12 @@ impl Game<'_> {
"open": true,
"host": h.host_name,
"port": h.settings.port,
// The server's own world: its finished chunks and how many it
// has generated or loaded so far.
"world": {
"chunks": self.world.chunks.len(),
"generated": self.streaming.generated_total,
},
"guests": h.hub.guests.iter().map(|g| json!({
"name": g.name,
"position": g.position,
@@ -370,6 +380,7 @@ impl Game<'_> {
"loaded": g.loaded,
"game_mode": g.game_mode,
"sneaking": g.sneaking,
"sleeping": g.bed,
"health": g.health,
// FoodData: food level, saturation and exhaustion.
"food": [
@@ -493,6 +504,7 @@ impl Game<'_> {
let hub = Hub::new(lan, sync, encoder, config);
let port = hub.lan.port;
self.world.block_log = Some(Vec::new());
self.world.light_log = Some(Default::default());
self.lan = Some(LanHost {
hub,
settings: LanSettings { port, ..settings },
@@ -542,6 +554,7 @@ impl Game<'_> {
// Give the writer threads a moment to flush the disconnect packets.
std::thread::sleep(std::time::Duration::from_millis(100));
self.world.block_log = None;
self.world.light_log = None;
self.audio.capture = None;
self.lan_events.clear();
self.streaming.extra.clear();
@@ -712,9 +725,9 @@ impl Game<'_> {
})
}
/// Mobs and items as the entities guests track.
fn lan_entities(&self, hub: &mut Hub) -> Vec<EntityState> {
let mut out = Vec::with_capacity(self.mobs.len() + self.dropped.len());
/// The entities guests track: mobs, items and the rest (game/lan_entities.rs).
fn lan_entities(&self, host_entity: Option<i32>, hub: &mut Hub) -> Vec<EntityState> {
let mut out = Vec::with_capacity(self.mobs.len() + self.dropped.len() + self.orbs.len());
for m in self.mobs.iter().filter(|m| !m.removed) {
let kind = m.kind.id.as_str();
let meta = mob_meta(m, hub);
@@ -733,6 +746,7 @@ impl Game<'_> {
data: 0,
meta,
equipment,
precise: false,
});
}
for d in &self.dropped {
@@ -750,8 +764,28 @@ impl Game<'_> {
data: 0,
meta: vec![(8, serializer::ITEM_STACK, Value::Item(stack))],
equipment: Vec::new(),
precise: false,
});
}
for o in &self.orbs {
out.push(EntityState {
id: o.id as i32,
uuid: entity_uuid(o.id),
kind: "minecraft:experience_orb".to_owned(),
position: [o.position.x, o.position.y, o.position.z],
yaw: 0.0,
pitch: 0.0,
head_yaw: 0.0,
on_ground: o.on_ground,
velocity: [o.velocity.x, o.velocity.y, o.velocity.z],
data: 0,
// ExperienceOrb.DATA_VALUE.
meta: vec![(8, serializer::INT, Value::Int(o.value as i32))],
equipment: Vec::new(),
precise: false,
});
}
self.lan_object_states(host_entity, hub, &mut out);
out
}
@@ -762,12 +796,19 @@ impl Game<'_> {
};
// What the tick sends a guest goes to its connection at the end.
let holding = lan::Holding::start();
// The host's own commands' broadcastToAdmins lines.
if !self.admin_feedback.is_empty() {
self.send_admin_feedback(&mut host, None);
}
let state = self.lan_host_state(&host);
// A dedicated server runs the hub without a host player.
if state.is_some() || host.hub.config.dedicated {
let has_guests = !host.hub.guests.is_empty();
let entities = if has_guests {
self.lan_entities(&mut host.hub)
let host_entity = state.as_ref().map(|s| s.entity_id);
self.lan_assign_ids();
self.lan_riding(host_entity, &mut host.hub.riding);
self.lan_entities(host_entity, &mut host.hub)
} else {
Vec::new()
};
@@ -816,6 +857,9 @@ impl Game<'_> {
}
for event in events {
match event {
event @ (HostEvent::Chat { .. } | HostEvent::Warn(_) | HostEvent::Error(_)) => {
self.lan_log_event(event);
}
HostEvent::Joined(conn) => {
self.lan_guest_joined(&mut host, conn, state.as_ref(), &entities, spawn);
if self.options.dedicated.is_some()
@@ -872,15 +916,6 @@ impl Game<'_> {
);
}
}
// MinecraftServer.logChatMessage of an unsigned message.
HostEvent::Chat(line) if self.options.dedicated.is_some() => {
super::dedicated::log("INFO", &format!("[Not Secure] {line}"));
}
HostEvent::Chat(line) => self.system_message(Text::literal(line)),
HostEvent::Warn(line) if self.options.dedicated.is_some() => {
super::dedicated::log("WARN", &line);
}
HostEvent::Warn(line) => log::warn!("{line}"),
HostEvent::Packet(conn, packet) => {
self.lan_guest_packet(&mut host, conn, *packet);
}
@@ -950,7 +985,8 @@ impl Game<'_> {
log::error!("could not open {}: {e}", level.id());
return;
}
theirs = self.lan_entities(&mut host.hub);
// A dedicated server has no host player.
theirs = self.lan_entities(None, &mut host.hub);
&theirs[..]
} else {
entities
@@ -1045,14 +1081,20 @@ impl Game<'_> {
/// Keep the chunks around every guest loaded.
fn lan_update_streaming(&mut self, host: &LanHost) {
// DistanceManager.PlayerTicketTracker: every chunk within the server's
// view distance (Chebyshev) of a player holds a PLAYER_LOADING ticket
// at the entity-ticking level (31), whatever the player asked for;
// levels rise by one a chunk, so FULL (33) reaches two chunks past
// it. An extra area finishes its chunks out to its radius + 1. That
// covers what the player tracks (`ChunkTrackingView`, within its view
// distance + 1) and those chunks' lit neighbours.
let radius = host.hub.config.view_distance + 1;
self.streaming.extra = host
.hub
.guests
.iter()
.filter(|g| host.hub.here(g))
// The tracked square's corners and their lit neighbours lie
// within (view distance + 2) * √2 of the player's chunk.
.map(|g| (g.chunk(), (g.view_distance + 2) * 3 / 2 + 1))
.map(|g| (g.chunk(), radius))
.collect();
}
@@ -1163,3 +1205,24 @@ impl Game<'_> {
}
}
}
impl Game<'_> {
/// A hub's chat and log lines: a dedicated server logs them
/// (MinecraftServer.logChatMessage, `[Not Secure]` for unsigned or
/// expired messages); a LAN host shows the chat.
pub(super) fn lan_log_event(&mut self, event: HostEvent) {
let dedicated = self.options.dedicated.is_some();
match event {
HostEvent::Chat { line, secure } if dedicated => {
let tag = if secure { "" } else { "[Not Secure] " };
super::dedicated::log("INFO", &format!("{tag}{line}"));
}
HostEvent::Chat { line, .. } => self.system_message(Text::literal(line)),
HostEvent::Warn(line) if dedicated => super::dedicated::log("WARN", &line),
HostEvent::Warn(line) => log::warn!("{line}"),
HostEvent::Error(line) if dedicated => super::dedicated::log("ERROR", &line),
HostEvent::Error(line) => log::error!("{line}"),
_ => {}
}
}
}
+215 -15
View File
@@ -18,7 +18,7 @@ use horizon_client::{
},
motion::{MotionEvent, MotionWorld, PlayerMotion},
};
use horizon_core::geometry::Vec3;
use horizon_core::{geometry::Vec3, random::RandomSource};
use horizon_protocol::{
packets::play::{self, Clientbound as C, Serverbound as S},
text::literal,
@@ -56,6 +56,8 @@ pub(super) struct GuestPlay {
last_inventory: u64,
/// `Entity.portalProcess` and `portalCooldown` (game/server_travel.rs).
pub(super) portal: horizon_client::nether_portal::PortalState,
/// `Player.takeXpDelay`: ticks until the next orb can be taken.
xp_delay: u32,
}
struct ItemRules<'a>(&'a horizon_client::items::Items);
@@ -172,6 +174,16 @@ impl Game<'_> {
self.right = play.using.is_some() || self.using.is_some();
let riding = self.riding.take();
let host_station = self.station.take();
// The guest's bed, sleep counter and respawn point; the host's
// respawn point, anchor and action bar stay theirs.
let sleeping = std::mem::replace(&mut self.sleeping, g.bed);
let sleep_timer = std::mem::replace(&mut self.sleep_timer, g.sleep_timer);
let spawn = std::mem::replace(
&mut self.spawn,
g.spawn.map(|s| Vec3::new(s[0], s[1], s[2])),
);
let respawn = (self.respawn_config.take(), self.level.spawn);
let message = self.message.take();
// The guest's own ender inventory; one the host has open goes back
// into the host's while the guest acts.
let host_ender = self.ender_open;
@@ -191,6 +203,9 @@ impl Game<'_> {
self.lan_acting_uuid = Some(g.uuid);
let result = f(self);
for packet in std::mem::take(&mut self.guest_packets) {
host.hub.send_to(conn, &packet);
}
self.lan_acting = None;
self.lan_acting_name = None;
self.lan_acting_uuid = None;
@@ -203,6 +218,12 @@ impl Game<'_> {
let opened_table = std::mem::replace(&mut self.craft_size, craft_size) == 3;
self.craft_grid = craft_grid;
let opened_station = std::mem::replace(&mut self.station, host_station);
let bed = std::mem::replace(&mut self.sleeping, sleeping);
let guest_sleep_timer = std::mem::replace(&mut self.sleep_timer, sleep_timer);
let guest_spawn = std::mem::replace(&mut self.spawn, spawn).map(|s| [s.x, s.y, s.z]);
(self.respawn_config, self.level.spawn) = respawn;
// ServerPlayer.displayClientMessage(_, true): the guest's action bar.
let guest_message = std::mem::replace(&mut self.message, message);
self.riding = riding;
self.left = left;
self.right = right;
@@ -220,6 +241,15 @@ impl Game<'_> {
self.mount_menu = host_mount_menu;
self.keys = host_keys;
let g = &mut host.hub.guests[i];
let fell_asleep = bed.is_some() && g.bed.is_none();
(g.bed, g.sleep_timer, g.spawn) = (bed, guest_sleep_timer, guest_spawn);
g.sleeping = g.bed.is_some();
if let Some((text, _)) = guest_message {
g.send(&C::SystemChat(play::SystemChat {
content: literal(&text),
overlay: true,
}));
}
std::mem::swap(&mut self.ender_items, &mut g.ender_items);
std::mem::swap(&mut self.adv.progress, &mut g.advancements);
std::mem::swap(&mut self.adv.changed, &mut g.advancements_changed);
@@ -269,6 +299,19 @@ impl Game<'_> {
}
}
let g = &mut host.hub.guests[i];
if let Some(head) = g.bed.filter(|_| fell_asleep) {
// LivingEntity.startSleeping: in the bed, still.
let at = [
f64::from(head[0]) + 0.5,
f64::from(head[1]) + 0.5625,
f64::from(head[2]) + 0.5,
];
g.position = at;
if let Some(m) = g.motion.as_mut() {
m.position = Vec3::new(at[0], at[1], at[2]);
m.velocity = Vec3::ZERO;
}
}
if new_mode != g.game_mode {
let conn = g.conn;
host.hub.set_game_mode(conn, new_mode);
@@ -596,7 +639,8 @@ impl Game<'_> {
self.drop_guest_items(host, gi, vec![c]);
}
}
S::ChatCommand(c) => self.guest_command(host, conn, &c.command),
S::ChatCommand(c) => self.guest_chat_command(host, conn, &c.command),
S::ChatCommandSigned(p) => self.guest_signed_command(host, conn, p),
S::ChangeDifficulty(p) if host.hub.guests[gi].permission >= 2 => {
if !self.level.difficulty_locked && (0..=3).contains(&p.difficulty) {
self.ui.difficulty = if self.level.hardcore {
@@ -685,13 +729,7 @@ impl Game<'_> {
}),
);
}
self.send_admin_feedback(host, conn);
}
}
S::Unknown(8, payload) => {
// A signed command: the text comes first.
if let Ok(text) = horizon_protocol::buf::Reader::new(&payload).string(32767) {
self.guest_command(host, conn, &text);
self.send_admin_feedback(host, Some(conn));
}
}
S::Unknown(id, payload)
@@ -818,7 +856,18 @@ impl Game<'_> {
}
/// Commands.performCommand for a guest with command access.
fn guest_command(&mut self, host: &mut LanHost, conn: u32, command: &str) {
/// Commands.performCommand for a guest, with the message arguments it
/// signed (none after an unsigned command packet).
pub(super) fn guest_command(
&mut self,
host: &mut LanHost,
conn: u32,
command: &str,
signed: Option<Vec<(String, horizon_client::lan::hub::chat::ChatMessage)>>,
) {
if self.guest_message_command(host, conn, command, signed.as_ref()) {
return;
}
// ListPlayersCommand needs no permission and lists every player.
let words: Vec<&str> = command.trim_start_matches('/').split(' ').collect();
if words[0] == "list" && (words.len() == 1 || words[1..] == ["uuids"]) {
@@ -888,6 +937,8 @@ impl Game<'_> {
.map(|t| horizon_client::lan::data::component_nbt(&t.component()))
.collect::<Vec<_>>()
});
// A teleport into another level happens before its feedback is sent.
self.run_level_teleports(host);
for content in lines.unwrap_or_default() {
host.hub.send_to(
conn,
@@ -897,13 +948,19 @@ impl Game<'_> {
}),
);
}
self.send_admin_feedback(host, conn);
self.send_admin_feedback(host, Some(conn));
}
/// The `broadcastToAdmins` lines a guest's command queued: every other
/// The `broadcastToAdmins` lines a command queued (`source`: the guest
/// whose it was; none for the host's or the console's): every other
/// operator gets them, and the console logs them as the server's own
/// system messages (MinecraftServer.sendSystemMessage).
fn send_admin_feedback(&mut self, host: &mut LanHost, source: u32) {
pub(super) fn send_admin_feedback(&mut self, host: &mut LanHost, source: Option<u32>) {
// PlayerList.isOp for the host of a world open to LAN: the owner when
// the world allows commands, everyone when the LAN does.
let host_op = source.is_some()
&& !host.hub.config.dedicated
&& (self.allow_commands() || host.hub.config.guest_commands);
for (line, ops, console) in std::mem::take(&mut self.admin_feedback) {
if ops {
let content = horizon_client::lan::data::component_nbt(&line.component());
@@ -911,13 +968,16 @@ impl Game<'_> {
.hub
.guests
.iter()
.filter(|g| g.conn != source && g.permission > 0)
.filter(|g| Some(g.conn) != source && g.permission > 0)
{
g.send(&C::SystemChat(play::SystemChat {
content: content.clone(),
overlay: false,
}));
}
if host_op {
self.system_message(line.clone());
}
}
if console {
super::dedicated::log("INFO", &format!("System chat: {}", line.plain()));
@@ -966,10 +1026,19 @@ impl Game<'_> {
}
fn guest_respawn(&mut self, host: &mut LanHost, conn: u32) {
let spawn = self.spawn.map_or([0.5, 80.0, 0.5], |s| [s.x, s.y, s.z]);
let Some(i) = host.hub.guests.iter().position(|g| g.conn == conn) else {
return;
};
// The guest's own bed, else the world spawn: never the host's bed.
let world = self
.level
.world_spawn
.map(|[x, y, z]| [f64::from(x) + 0.5, f64::from(y), f64::from(z) + 0.5]);
let spawn = host.hub.guests[i]
.spawn
.or(world)
.or(self.spawn.map(|s| [s.x, s.y, s.z]))
.unwrap_or([0.5, 80.0, 0.5]);
if !host.hub.guests[i].dead {
return;
}
@@ -1041,6 +1110,7 @@ impl Game<'_> {
let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else {
continue;
};
self.guest_sleep_tick(host, gi);
if host.hub.guests[gi].dead || self.on_server_trip(conn) {
continue;
}
@@ -1083,6 +1153,7 @@ impl Game<'_> {
host.hub.flush_progress(conn);
self.guest_dig_feedback(host, conn);
self.guest_pickups(host, gi);
self.guest_orbs(host, gi);
let g = &mut host.hub.guests[gi];
if g.health <= 0.0 && !g.dead {
g.dead = true;
@@ -1106,6 +1177,62 @@ impl Game<'_> {
}
}
/// `Player.tick`'s sleep counter, and `LivingEntity.tick`'s wake-up of a
/// sleeper who died or whose bed is gone.
fn guest_sleep_tick(&mut self, host: &mut LanHost, gi: usize) {
let g = &mut host.hub.guests[gi];
g.sleep_timer = super::tick_sleep_timer(g.sleep_timer, g.bed.is_some());
if let Some(head) = g.bed {
let block = self.world.block(head[0], head[1], head[2]);
let bed = self.res.facts.get(block).name.ends_with("_bed");
if g.dead || g.health <= 0.0 || !bed {
host.hub.wake(gi);
}
}
}
/// `SleepStatus.areEnoughSleeping` and `areEnoughDeepSleeping` over the
/// host's player and the guests: of the players not in spectator mode,
/// players_sleeping_percentage of them (at least one) are in bed, and as
/// many have slept 100 ticks.
pub(super) fn enough_slept(&self) -> bool {
let (mut active, mut sleeping, mut deep) = (0i64, 0i64, 0i64);
let mut count = |in_bed: bool, timer: u32| {
active += 1;
if in_bed {
sleeping += 1;
if timer >= 100 {
deep += 1;
}
}
};
if self.player.is_some() && !self.spectator() {
count(self.sleeping.is_some(), self.sleep_timer);
}
if let Some(host) = self.lan.as_ref() {
for g in host
.hub
.guests
.iter()
.filter(|g| g.placed && !g.spectator())
{
count(g.bed.is_some(), g.sleep_timer);
}
}
let percent = i64::from(self.ui.rules.int("players_sleeping_percentage").max(0));
let needed = ((active * percent + 99) / 100).max(1);
sleeping >= needed && deep >= needed
}
/// `ServerLevel.wakeUpAllPlayers` for the guests.
pub(super) fn wake_guests(&mut self) {
if let Some(host) = self.lan.as_mut() {
for i in 0..host.hub.guests.len() {
host.hub.wake(i);
}
}
}
/// `PlayerList.broadcastSystemMessage` of the advancements guests made
/// (their own actions, commands and ticks).
fn announce_guest_advancements(&mut self, host: &mut LanHost) {
@@ -1384,6 +1511,79 @@ impl Game<'_> {
}
}
/// `Player.tick`'s takeXpDelay and `Player.aiStep`'s touch of the
/// experience orbs in the guest's box grown by 1, 0.5, 1: one of them at
/// random, at most every 2 ticks (`ExperienceOrb.playerTouch`), repairs
/// with Mending and gives the rest as points. Everyone near hears it.
fn guest_orbs(&mut self, host: &mut LanHost, gi: usize) {
let g = &host.hub.guests[gi];
// Player's standing and crouching boxes: 1.8 and 1.5 high.
let height = if g.sneaking { 1.5 } else { 1.8 };
let (conn, id, at) = (g.conn, g.entity_id, g.position);
let unable = g.spectator() || g.dead || g.health <= 0.0;
let play = host.play.entry(conn).or_default();
if play.xp_delay > 0 {
play.xp_delay -= 1;
}
if unable || play.xp_delay > 0 {
return;
}
let (min, max) = (
[at[0] - 1.3, at[1] - 0.5, at[2] - 1.3],
[at[0] + 1.3, at[1] + height + 0.5, at[2] + 1.3],
);
let touching: Vec<usize> = self
.orbs
.iter()
.enumerate()
.filter(|(_, o)| {
o.position.x + 0.25 > min[0]
&& o.position.x - 0.25 < max[0]
&& o.position.y + 0.5 > min[1]
&& o.position.y < max[1]
&& o.position.z + 0.25 > min[2]
&& o.position.z - 0.25 < max[2]
})
.map(|(i, _)| i)
.collect();
if touching.is_empty() {
return;
}
// Util.getRandom(orbs, random).
let pick = self
.world
.random
.next_int_bound(touching.len() as i32)
.unwrap_or(0) as usize;
let orb = self.orbs.remove(touching[pick]);
play.xp_delay = 2;
host.hub.take_item(orb.id as i32, id, 1, at);
// ClientPacketListener.handleTakeItemEntity's sound, at the orb.
let pitch = (self.world.random.next_float() - self.world.random.next_float()) * 0.35 + 0.9;
let p = orb.position;
self.audio.play(
"minecraft:entity.experience_orb.pickup",
Some([p.x, p.y, p.z]),
0.1,
pitch,
);
let value = orb.value;
if let Some(target) = super::pickups::guest_target(host, id as u32) {
use super::pickups::{Collector, Taken};
self.add_pickup_toward(
Taken::Orb(Box::new(orb)),
Collector::Guest(id as u32),
target,
);
}
self.as_guest(host, conn, |game| {
let rest = game.mending(value);
if rest > 0 {
game.give_orb_points(rest);
}
});
}
/// The host's own `ItemPickupParticle` toward the guest's model.
fn guest_pickup(
&mut self,
+194
View File
@@ -0,0 +1,194 @@
//! A guest's commands that carry chat: the unsigned and signed command
//! packets (ServerGamePacketListenerImpl.handleChatCommand and
//! handleSignedChatCommand), and the message commands whose text they sign
//! (SayCommand, EmoteCommands, MsgCommand), relayed by the hub as chat.
use super::{Game, lan::LanHost};
use horizon_client::{
command::{Arg, ArgType, NodeKind, ParseResults, vanilla},
lan::{
data::component_nbt,
hub::{HostEvent, chat::ChatMessage},
},
text::{self, Text},
};
use horizon_protocol::packets::play::{self, Clientbound as C};
/// The signing context of a command: each message argument as the chain
/// let it through, by argument name (CommandSigningContext.SignedArguments).
type Signed = Vec<(String, ChatMessage)>;
impl Game<'_> {
/// CommandDispatcher.parse with the guest's permission level.
fn parse_as(&mut self, permission: u8, command: &str) -> ParseResults {
let level = std::mem::replace(&mut self.ui.registries.permission, permission);
let parse = vanilla::game_dispatcher().parse(command, &self.ui.registries);
self.ui.registries.permission = level;
parse
}
/// SignableCommand.of: the command's message arguments, by name, with
/// their text, not past a redirect to the root (`execute ... run`).
fn signable_arguments(&mut self, permission: u8, command: &str) -> Vec<(String, String)> {
let parse = self.parse_as(permission, command);
let nodes = &vanilla::game_dispatcher().nodes;
let root = parse.context.root;
let mut out = Vec::new();
let mut context = Some(&parse.context);
while let Some(c) = context {
for &(node, (start, end)) in &c.nodes {
if let NodeKind::Argument {
ty: ArgType::Message,
name,
} = &nodes[node].kind
&& let Some(text) = command.get(start..end)
{
out.push((name.clone(), text.to_owned()));
}
}
context = c.child.as_deref().filter(|child| child.root != root);
}
out
}
/// handleChatCommand (performUnsignedChatCommand): refused when the
/// server enforces secure chat and the command has a message to sign.
pub(super) fn guest_chat_command(&mut self, host: &mut LanHost, conn: u32, command: &str) {
let Some(i) = host.hub.guests.iter().position(|g| g.conn == conn) else {
return;
};
if !host.hub.try_handle_chat(i, command, true) {
return;
}
let permission = host.hub.guests[i].permission;
if host.hub.enforces_secure_chat()
&& !self.signable_arguments(permission, command).is_empty()
{
let name = host.hub.guests[i].name.clone();
self.lan_log_event(HostEvent::Error(format!(
"Received unsigned command packet from {name}, but the command requires signable arguments: {command}"
)));
let failure = Text::translate("chat.disabled.invalid_command_signature", &[])
.with_color(text::RED);
host.hub.guests[i].send(&C::SystemChat(play::SystemChat {
content: component_nbt(&failure.component()),
overlay: false,
}));
return;
}
self.guest_command(host, conn, command, None);
}
/// handleSignedChatCommand: the acknowledgements, then each message
/// argument through the sender's chain, then the command with them.
pub(super) fn guest_signed_command(
&mut self,
host: &mut LanHost,
conn: u32,
p: play::ChatCommandSigned,
) {
let Some(i) = host.hub.guests.iter().position(|g| g.conn == conn) else {
return;
};
let mut events = Vec::new();
let mut signed = None;
if let Some(last_seen) = host.hub.apply_last_seen(i, &p.last_seen, &mut events)
&& host.hub.try_handle_chat(i, &p.command, true)
{
let permission = host.hub.guests[i].permission;
let parsed = self.signable_arguments(permission, &p.command);
match host
.hub
.signed_arguments(i, &p, &parsed, &last_seen, &mut events)
{
Ok(arguments) => signed = Some(arguments),
Err(e) => host.hub.decode_failure(i, e, &mut events),
}
}
for event in events {
self.lan_log_event(event);
}
if let Some(signed) = signed {
self.guest_command(host, conn, &p.command, Some(signed));
}
}
/// SayCommand, EmoteCommands and MsgCommand for a guest: chat to the
/// players, signed when the guest signed it (a disguised chat after an
/// unsigned command packet). False when the command is another one, or
/// one this can't run (selectors other than `@s` and `@a`), for the
/// game's dispatcher to handle.
pub(super) fn guest_message_command(
&mut self,
host: &mut LanHost,
conn: u32,
command: &str,
signed: Option<&Signed>,
) -> bool {
let Some(i) = host.hub.guests.iter().position(|g| g.conn == conn) else {
return false;
};
let parse = self.parse_as(host.hub.guests[i].permission, command);
let Ok((context, id)) = parse.executable() else {
return false;
};
let argument = if id == "me" { "action" } else { "message" };
let (Some(Arg::Str(text)), true) =
(context.get(argument), matches!(id, "say" | "me" | "msg"))
else {
return false;
};
let message = signed.and_then(|s| {
s.iter()
.find(|(n, _)| n == argument)
.map(|(_, m)| m.clone())
});
let mut events = Vec::new();
if id == "msg" {
let Some(Arg::Entity(selector)) = context.get("targets") else {
return false;
};
let raw = context
.args
.iter()
.rev()
.find(|a| a.name == "targets")
.and_then(|a| command.get(a.range.0..a.range.1));
let guests = &host.hub.guests;
let placed = |k: &usize| guests[*k].placed;
let targets: Vec<usize> = match (raw, &selector.player_name, selector.uuid) {
(Some("@s"), ..) => vec![i],
(Some("@a"), ..) => (0..guests.len()).filter(placed).collect(),
(_, Some(name), _) => (0..guests.len())
.filter(|&k| placed(&k) && guests[k].name.eq_ignore_ascii_case(name))
.collect(),
(_, None, Some(uuid)) => (0..guests.len())
.filter(|&k| placed(&k) && guests[k].uuid == uuid)
.collect(),
_ => return false,
};
if targets.is_empty() {
let failure = Text::empty()
.append(Text::translate("argument.entity.notfound.player", &[]))
.with_color(text::RED);
host.hub.guests[i].send(&C::SystemChat(play::SystemChat {
content: component_nbt(&failure.component()),
overlay: false,
}));
return true;
}
host.hub.whisper(i, &targets, message, text);
} else {
let chat_type = if id == "say" {
"say_command"
} else {
"emote_command"
};
host.hub
.broadcast_command_chat(i, chat_type, message, text, &mut events);
}
for event in events {
self.lan_log_event(event);
}
true
}
}
@@ -0,0 +1,449 @@
//! The entities beyond mobs and items that a server tracks to its clients
//! (`ChunkMap.TrackedEntity`, `ServerEntity`): boats, minecarts, armor
//! stands, item frames, paintings and the entities Horizon keeps without
//! simulating them, each as vanilla pairs it (`getAddEntityPacket` and the
//! synched data that differs from the defaults), and who rides what.
use super::Game;
use horizon_client::lan::{
entity::{EntityState, Riding},
hub::Hub,
};
use horizon_protocol::entity_data::{Value, serializer};
use horizon_world::nbt::Tag;
/// `ArmorStand`'s default poses (head, body, left arm, right arm, left leg,
/// right leg), DATA_HEAD_POSE to DATA_RIGHT_LEG_POSE (entries 16 to 21),
/// under their `Pose` keys.
const STAND_POSES: [(&str, [f32; 3]); 6] = [
("Head", [0.0, 0.0, 0.0]),
("Body", [0.0, 0.0, 0.0]),
("LeftArm", [-10.0, 0.0, -10.0]),
("RightArm", [-15.0, 0.0, 10.0]),
("LeftLeg", [-1.0, 0.0, -1.0]),
("RightLeg", [1.0, 0.0, 1.0]),
];
fn state(id: u32, kind: &str, position: [f64; 3], yaw: f32, on_ground: bool) -> EntityState {
EntityState {
id: id as i32,
uuid: super::lan::entity_uuid(id),
kind: kind.to_owned(),
position,
yaw,
pitch: 0.0,
head_yaw: 0.0,
on_ground,
velocity: [0.0; 3],
data: 0,
meta: Vec::new(),
equipment: Vec::new(),
precise: false,
}
}
/// `VehicleEntity`'s DATA_ID_HURT, DATA_ID_HURTDIR and DATA_ID_DAMAGE
/// (entries 8 to 10) when they differ from their defaults (0, 1, 0).
fn vehicle_meta(hurt_time: i32, hurt_dir: i32, damage: f32) -> Vec<(u8, i32, Value)> {
let mut meta = Vec::new();
if hurt_time != 0 {
meta.push((8, serializer::INT, Value::Int(hurt_time)));
}
if hurt_dir != 1 {
meta.push((9, serializer::INT, Value::Int(hurt_dir)));
}
if damage != 0.0 {
meta.push((10, serializer::FLOAT, Value::Float(damage)));
}
meta
}
/// An armor stand's pose from its compound (`ArmorStandPose`), each part
/// that differs from the default.
fn stand_poses(raw: Option<&Tag>) -> Vec<(u8, i32, Value)> {
let Some(pose) = raw.and_then(|t| t.get("Pose")) else {
return Vec::new();
};
let mut meta = Vec::new();
for (i, (key, default)) in STAND_POSES.iter().enumerate() {
let Some(Tag::List(values)) = pose.get(key) else {
continue;
};
let mut r = *default;
for (k, v) in values.iter().take(3).enumerate() {
if let Tag::Float(bits) = v {
r[k] = f32::from_bits(*bits);
}
}
if r != *default {
meta.push((
16 + i as u8,
serializer::ROTATIONS,
Value::Floats(r.to_vec()),
));
}
}
meta
}
impl Game<'_> {
/// Who rides what (`Entity.getPassengers`): mobs on mobs, and the
/// host in its boat or minecart.
pub(super) fn lan_riding(&self, host_entity: Option<i32>, riding: &mut Riding) {
riding.clear();
for m in self.mobs.iter().filter(|m| !m.removed) {
if let Some(vehicle) = m.extra.mount {
riding.add(vehicle as i32, m.id as i32);
}
}
if let (Some(host), Some(vehicle)) = (host_entity, self.riding) {
riding.add(vehicle as i32, host);
}
}
/// Boats, minecarts, armor stands, item frames, paintings and the
/// entities kept unsimulated, as guests track them.
pub(super) fn lan_object_states(
&self,
host_entity: Option<i32>,
hub: &mut Hub,
out: &mut Vec<EntityState>,
) {
for b in &self.boats {
let p = b.position;
let mut e = state(b.id, &b.entity_type(), [p.x, p.y, p.z], b.yaw, b.on_ground);
e.velocity = [b.velocity.x, b.velocity.y, b.velocity.z];
e.meta = vehicle_meta(b.hurt_time, b.hurt_dir, b.damage);
// AbstractBoat.DATA_ID_PADDLE_LEFT and DATA_ID_PADDLE_RIGHT.
for (k, paddling) in b.paddling.iter().enumerate() {
if *paddling {
e.meta
.push((11 + k as u8, serializer::BOOLEAN, Value::Bool(true)));
}
}
out.push(e);
}
for c in &self.carts {
let p = c.position;
let mut e = state(c.id, c.kind.id(), [p.x, p.y, p.z], c.yaw, c.on_ground());
e.velocity = [c.velocity.x, c.velocity.y, c.velocity.z];
e.meta = vehicle_meta(c.hurt_time, c.hurt_dir, c.damage);
match c.kind {
// MinecartFurnace.DATA_ID_FUEL.
super::minecarts::CartKind::Furnace if c.fuel > 0 => {
e.meta.push((13, serializer::BOOLEAN, Value::Bool(true)));
}
// MinecartCommandBlock.DATA_ID_COMMAND_NAME.
super::minecarts::CartKind::CommandBlock => {
if let Some(Tag::String(command)) =
self.persist.raw.get(&c.id).and_then(|t| t.get("Command"))
{
let command = command.to_string_lossy();
if !command.is_empty() {
e.meta
.push((13, serializer::STRING, Value::String(command)));
}
}
}
_ => {}
}
out.push(e);
}
for a in &self.armor_stands {
let p = a.position;
let mut e = state(
a.id,
"minecraft:armor_stand",
[p.x, p.y, p.z],
a.yaw,
a.on_ground,
);
e.head_yaw = a.yaw;
e.velocity = [a.velocity.x, a.velocity.y, a.velocity.z];
if a.fire_ticks > 0 {
e.meta.push((0, serializer::BYTE, Value::Byte(1)));
}
// LivingEntity.DATA_HEALTH_ID: 1 until the stand's max health is set.
e.meta.push((9, serializer::FLOAT, Value::Float(a.health)));
// ArmorStand.DATA_CLIENT_FLAGS: small 1, arms 4, no base plate 8, marker 16.
let flags = i8::from(a.small)
| i8::from(a.show_arms) << 2
| i8::from(a.no_base_plate) << 3
| i8::from(a.marker) << 4;
if flags != 0 {
e.meta.push((15, serializer::BYTE, Value::Byte(flags)));
}
e.meta.extend(stand_poses(self.persist.raw.get(&a.id)));
// Stored main hand, off hand, feet, legs, chest, head: the wire's slots 0 to 5.
for (slot, item) in a.equipment.iter().enumerate() {
if item.is_some() {
e.equipment.push((slot as u8, hub.stack(item)));
}
}
out.push(e);
}
for f in &self.item_frames {
// ItemFrame.getAddEntityPacket: the block it hangs in and its direction.
let mut e = state(f.id, f.kind(), f.pos.map(f64::from), 0.0, false);
e.pitch = match f.facing {
0 => 90.0,
1 => -90.0,
_ => 0.0,
};
e.yaw = match f.facing {
2 => 180.0,
4 => 90.0,
5 => 270.0,
_ => 0.0,
};
e.data = i32::from(f.facing);
// HangingEntity.DATA_DIRECTION, south by default.
if f.facing != 3 {
e.meta
.push((8, serializer::DIRECTION, Value::Id(i32::from(f.facing))));
}
if f.item.is_some() {
e.meta
.push((9, serializer::ITEM_STACK, Value::Item(hub.stack(&f.item))));
}
if f.rotation != 0 {
e.meta
.push((10, serializer::INT, Value::Int(i32::from(f.rotation))));
}
out.push(e);
}
for p in &self.paintings {
let mut e = state(p.id, "minecraft:painting", p.pos.map(f64::from), 0.0, false);
// Direction.get2DDataValue (south 0, west 1, north 2, east 3) to its
// 3D data value and yaw.
let facing = [3, 4, 2, 5][usize::from(p.facing & 3)];
e.yaw = f32::from(p.facing & 3) * 90.0;
e.data = facing;
if facing != 3 {
e.meta.push((8, serializer::DIRECTION, Value::Id(facing)));
}
// Painting.DATA_PAINTING_VARIANT_ID, a registry holder (id + 1),
// set unless it is the registry's first variant (VariantUtils.getAny).
if let Some(id) = hub.registry_id("minecraft:painting_variant", &p.variant)
&& id != 0
{
e.meta
.push((9, serializer::PAINTING_VARIANT, Value::Id(id + 1)));
}
out.push(e);
}
self.lan_projectile_states(host_entity, hub, out);
for o in &self.others {
let p = o.position;
let mut e = state(o.id, &o.kind, [p.x, p.y, p.z], o.yaw, false);
e.pitch = o.pitch;
e.head_yaw = o.yaw;
out.push(e);
}
}
}
impl Game<'_> {
/// Gives the entities Horizon keeps without an id one (`Entity.id`, from
/// the same counter as the rest) before they are first tracked.
pub(super) fn lan_assign_ids(&mut self) {
let next = &mut self.next_entity;
let mut give = |id: &mut u32| {
if *id == 0 {
*next += 1;
*id = *next;
}
};
self.tnts.iter_mut().for_each(|t| give(&mut t.id));
self.falling.iter_mut().for_each(|f| give(&mut f.id));
self.creatures
.projectiles
.iter_mut()
.for_each(|p| give(&mut p.id));
self.tridents.iter_mut().for_each(|t| give(&mut t.id));
self.rockets.iter_mut().for_each(|r| give(&mut r.id));
self.crystals.iter_mut().for_each(|c| give(&mut c.id));
}
/// Primed TNT, falling blocks, projectiles, tridents, firework rockets and
/// end crystals, as guests track them.
fn lan_projectile_states(
&self,
host_entity: Option<i32>,
hub: &mut Hub,
out: &mut Vec<EntityState>,
) {
let owner = |who: Option<horizon_client::mobs::Who>| match who {
Some(horizon_client::mobs::Who::Mob(id)) => id as i32,
Some(horizon_client::mobs::Who::Player) => host_entity.unwrap_or(0),
None => 0,
};
let at = |p: horizon_core::geometry::Vec3| [p.x, p.y, p.z];
for t in self.tnts.iter().filter(|t| t.id != 0) {
let mut e = state(t.id, "minecraft:tnt", at(t.position), 0.0, t.on_ground);
e.velocity = at(t.velocity);
// PrimedTnt.DATA_FUSE_ID, 80 by default; requiresPrecisePosition
// while it touches a block.
if t.fuse != 80 {
e.meta.push((8, serializer::INT, Value::Int(t.fuse)));
}
e.precise = t.on_ground;
out.push(e);
}
for f in self.falling.iter().filter(|f| f.id != 0) {
let mut e = state(f.id, "minecraft:falling_block", at(f.position), 0.0, false);
e.velocity = at(f.velocity);
// getAddEntityPacket: the block state; DATA_START_POS.
e.data = f.state.0 as i32;
if f.no_gravity {
e.meta.push((5, serializer::BOOLEAN, Value::Bool(true)));
}
let start = [f.start_pos.x, f.start_pos.y, f.start_pos.z];
if start != [0; 3] {
e.meta.push((8, serializer::BLOCK_POS, Value::Pos(start)));
}
out.push(e);
}
for p in self.creatures.projectiles.iter().filter(|p| p.id != 0) {
use horizon_client::projectiles::ProjectileKind as K;
let kind = match &p.kind {
K::Arrow { .. } => "minecraft:arrow",
K::Snowball => "minecraft:snowball",
K::Egg => "minecraft:egg",
K::EnderPearl => "minecraft:ender_pearl",
K::SmallFireball => "minecraft:small_fireball",
K::LargeFireball { .. } => "minecraft:fireball",
K::LlamaSpit => "minecraft:llama_spit",
K::WindCharge => "minecraft:wind_charge",
K::BreezeWindCharge => "minecraft:breeze_wind_charge",
K::ShulkerBullet { .. } => "minecraft:shulker_bullet",
K::WitherSkull { .. } => "minecraft:wither_skull",
K::Potion { .. } => "minecraft:splash_potion",
};
let mut e = state(p.id, kind, at(p.position), p.yaw, false);
e.pitch = p.pitch;
e.velocity = at(p.velocity);
e.data = owner(p.owner);
match &p.kind {
K::Arrow { critical, .. } => {
let a = p.arrow.as_deref();
e.meta.extend(arrow_meta(
*critical,
a.is_some_and(|a| a.no_physics),
a.map_or(0, |a| a.pierce),
a.is_some_and(|a| a.in_ground) || p.stuck,
));
}
// WitherSkull.DATA_DANGEROUS.
K::WitherSkull { dangerous: true } => {
e.meta.push((8, serializer::BOOLEAN, Value::Bool(true)));
}
_ => {}
}
out.push(e);
}
for t in self.tridents.iter().filter(|t| t.id != 0) {
let mut e = state(t.id, "minecraft:trident", at(t.position), t.yaw, false);
e.pitch = t.pitch;
e.velocity = at(t.velocity);
e.meta = arrow_meta(false, t.no_physics, 0, t.in_ground);
// ThrownTrident.ID_LOYALTY and ID_FOIL.
if t.loyalty != 0 {
e.meta
.push((11, serializer::BYTE, Value::Byte(t.loyalty as i8)));
}
if t.stack.has_any_enchantments() {
e.meta.push((12, serializer::BOOLEAN, Value::Bool(true)));
}
out.push(e);
}
for r in self.rockets.iter().filter(|r| r.id != 0) {
let mut e = state(
r.id,
"minecraft:firework_rocket",
at(r.position),
0.0,
false,
);
e.velocity = at(r.velocity);
// DATA_ID_FIREWORKS_ITEM once set from a stack, DATA_ATTACHED_TO_TARGET,
// DATA_SHOT_AT_ANGLE.
let plain = &*r.item.item == "minecraft:firework_rocket"
&& r.item.count == 1
&& r.item.extra.is_none();
if !plain {
e.meta.push((
8,
serializer::ITEM_STACK,
Value::Item(hub.stack(&Some(r.item.clone()))),
));
}
if r.attached
&& let Some(host) = host_entity
{
e.meta
.push((9, serializer::OPTIONAL_UNSIGNED_INT, Value::Id(host + 1)));
}
if r.angled {
e.meta.push((10, serializer::BOOLEAN, Value::Bool(true)));
}
out.push(e);
}
for c in self.crystals.iter().filter(|c| c.id != 0) {
let mut e = state(c.id, "minecraft:end_crystal", at(c.position), 0.0, false);
// EndCrystal.DATA_BEAM_TARGET and DATA_SHOW_BOTTOM (true by default).
if c.beam.is_some() {
e.meta
.push((8, serializer::OPTIONAL_BLOCK_POS, Value::OptPos(c.beam)));
}
if !c.show_bottom {
e.meta.push((9, serializer::BOOLEAN, Value::Bool(false)));
}
out.push(e);
}
}
}
/// `AbstractArrow`'s ID_FLAGS (critical 1, no physics 2), PIERCE_LEVEL and
/// IN_GROUND, when they differ from the defaults.
fn arrow_meta(
critical: bool,
no_physics: bool,
pierce: u8,
in_ground: bool,
) -> Vec<(u8, i32, Value)> {
let mut meta = Vec::new();
let flags = i8::from(critical) | i8::from(no_physics) << 1;
if flags != 0 {
meta.push((8, serializer::BYTE, Value::Byte(flags)));
}
if pierce != 0 {
meta.push((9, serializer::BYTE, Value::Byte(pierce as i8)));
}
if in_ground {
meta.push((10, serializer::BOOLEAN, Value::Bool(true)));
}
meta
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn armor_stand_poses_send_only_what_differs() {
let tag =
horizon_world::nbt::parse_snbt("{Pose:{Head:[10f,20f,0f],LeftArm:[-10f,0f,-10f]}}")
.unwrap()
.0;
let meta = stand_poses(Some(&tag));
assert_eq!(
meta,
vec![(
16,
serializer::ROTATIONS,
Value::Floats(vec![10.0, 20.0, 0.0])
)]
);
assert!(stand_poses(None).is_empty());
}
}
@@ -107,6 +107,7 @@ impl Game<'_> {
v.velocity = Vec3::new(moved[0], moved[1], moved[2]);
v.uuid = horizon_client::lan::playerdata::uuid_ints(uuid);
v.allies = Default::default();
v.remote = true;
views.push((conn, v));
}
}
@@ -274,6 +275,7 @@ mod tests {
hero: false,
uuid: [0; 4],
allies: Default::default(),
remote: false,
}
}
+27 -34
View File
@@ -497,42 +497,35 @@ impl Game<'_> {
}
}
}
/// Every hopper's `pushItemsTick`, in a stable position order.
pub(super) fn tick_hoppers(&mut self) -> Result<()> {
/// `HopperBlockEntity.pushItemsTick` of the hopper at `pos`, if its block
/// is still a hopper (`BlockEntityType.isValid`).
pub(super) fn tick_hopper(&mut self, pos: Pos) {
let hopper = self
.pack
.assets
.registry
.default_state("minecraft:hopper")
.map(|s| self.res.facts.get(s).name.clone());
let Some(hopper) = hopper else { return Ok(()) };
// A hopper's block entity is the plain container with five slots
// (`BlockEntity::for_block`; `BlockEntity::id` names it the hopper):
// only those need their block looked up (the ticker runs for a
// HopperBlockEntity whose block is still a hopper,
// `BlockEntityType.isValid`).
let mut positions: Vec<Pos> = self
.world
.block_entities
.iter()
.filter(|(_, e)| matches!(e, BlockEntity::Chest(items) if items.len() == HOPPER_SLOTS))
.map(|(p, _)| *p)
.filter(|p| self.res.facts.get(self.world.block(p.0, p.1, p.2)).name == hopper)
.collect();
positions.sort_unstable();
self.hoppers
.retain(|p, _| positions.binary_search(p).is_ok());
let time = self.world.game_time;
for pos in positions {
let state = self.hoppers.entry(pos).or_default();
state.cooldown -= 1;
state.ticked = time;
if state.cooldown <= 0 {
state.cooldown = 0;
self.hopper_try_move_items(pos);
}
.res
.facts
.get(self.world.block(pos.0, pos.1, pos.2))
.name
.as_ref()
== "minecraft:hopper";
if !hopper {
self.hoppers.remove(&pos);
return;
}
Ok(())
let time = self.world.game_time;
let state = self.hoppers.entry(pos).or_default();
state.cooldown -= 1;
state.ticked = time;
if state.cooldown <= 0 {
state.cooldown = 0;
self.hopper_try_move_items(pos);
}
}
/// Drops the cooldowns of hoppers whose block entity is gone.
pub(super) fn forget_gone_hoppers(&mut self) {
let entities = &self.world.block_entities;
self.hoppers.retain(|p, _| {
matches!(entities.get(p), Some(BlockEntity::Chest(items)) if items.len() == HOPPER_SLOTS)
});
}
/// `HopperBlockEntity.tryMoveItems` with `suckInItems`.
pub(super) fn hopper_try_move_items(&mut self, pos: Pos) {
@@ -56,44 +56,33 @@ impl Game<'_> {
_ => None,
}
}
/// `CrafterBlockEntity.serverTick` for every crafter, and the powered
/// flag following the block state.
pub(in crate::game) fn tick_crafters(&mut self) {
let positions: Vec<Pos> = self
.world
.block_entities
.iter()
.filter(|(_, e)| matches!(e, BlockEntity::Crafter(_)))
.map(|(p, _)| *p)
.collect();
let mut positions = positions;
positions.sort_unstable();
for pos in positions {
let state = self.world.block(pos.0, pos.1, pos.2);
let triggered = self.containers().prop(state, "triggered") == Some("true");
let mut finished = false;
if let Some(BlockEntity::Crafter(c)) = self.world.block_entities.get_mut(&pos) {
// CrafterBlock.neighborChanged sets the flag with the state; a
// loaded crafter keeps its saved flag until then.
if c.state_triggered.is_some_and(|t| t != triggered) {
c.triggered = triggered;
}
c.state_triggered = Some(triggered);
let remaining = c.crafting_ticks - 1;
if remaining >= 0 {
c.crafting_ticks = remaining;
finished = remaining == 0;
}
/// `CrafterBlockEntity.serverTick` of the crafter at `pos`, and the
/// powered flag following the block state.
pub(in crate::game) fn tick_crafter(&mut self, pos: Pos) {
let state = self.world.block(pos.0, pos.1, pos.2);
let triggered = self.containers().prop(state, "triggered") == Some("true");
let mut finished = false;
if let Some(BlockEntity::Crafter(c)) = self.world.block_entities.get_mut(&pos) {
// CrafterBlock.neighborChanged sets the flag with the state; a
// loaded crafter keeps its saved flag until then.
if c.state_triggered.is_some_and(|t| t != triggered) {
c.triggered = triggered;
}
if finished {
self.set_bool_prop(
pos,
"crafting",
false,
horizon_world::level::flags::UPDATE_ALL,
);
c.state_triggered = Some(triggered);
let remaining = c.crafting_ticks - 1;
if remaining >= 0 {
c.crafting_ticks = remaining;
finished = remaining == 0;
}
}
if finished {
self.set_bool_prop(
pos,
"crafting",
false,
horizon_world::level::flags::UPDATE_ALL,
);
}
}
/// `CrafterBlock.dispenseFrom` (the scheduled tick after a redstone pulse).
pub(super) fn crafter_dispense(&mut self, pos: BlockPos, state: BlockStateId) -> Result<()> {
+24 -1
View File
@@ -157,6 +157,10 @@ pub(super) struct Rail {
powered: bool,
}
impl Minecart {
/// `Entity.onGround`.
pub(super) fn on_ground(&self) -> bool {
self.on_ground
}
pub fn new(id: u32, kind: CartKind, position: Vec3) -> Self {
Self {
id,
@@ -1324,7 +1328,11 @@ impl Game<'_> {
if let Some(state) = self.display_state(c) {
let display = base
* glam::Mat4::from_scale(glam::Vec3::splat(0.75))
* glam::Mat4::from_translation(glam::Vec3::new(-0.5, (6.0 - 8.0) / 16.0, 0.5))
* glam::Mat4::from_translation(glam::Vec3::new(
-0.5,
(display_offset(c.kind) as f32 - 8.0) / 16.0,
0.5,
))
* glam::Mat4::from_rotation_y(90f32.to_radians());
if c.kind == CartKind::Chest {
self.cart_chest(state, display, l, out);
@@ -1460,3 +1468,18 @@ impl Minecart {
Some(c)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn display_offset_matches_vanilla_for_each_cart_kind() {
assert_eq!(display_offset(CartKind::Hopper), 1.0);
assert_eq!(display_offset(CartKind::Chest), 6.0);
assert_eq!(display_offset(CartKind::Furnace), 6.0);
assert_eq!(display_offset(CartKind::Tnt), 6.0);
assert_eq!(display_offset(CartKind::CommandBlock), 6.0);
assert_eq!(display_offset(CartKind::Rideable), 6.0);
}
}
+20 -18
View File
@@ -65,6 +65,8 @@ pub(super) struct Portals {
arrivals: Vec<Arrival>,
loaded: bool,
dirty: bool,
/// Per-chunk portal palette masks, kept across ticks (portal_sections).
pub(super) sections: horizon_client::portal_sections::PortalSections,
}
fn rotate_y(v: Vec3, degrees: f32) -> Vec3 {
@@ -486,13 +488,14 @@ impl Game<'_> {
.filter(|m| self.mob_can_use_portal(m))
.map(|m| (m.id, m.position, m.width(), m.height()))
.collect();
let mut portal_sections = horizon_client::fast_hash::FxHashMap::default();
let mut portal_sections = std::mem::take(&mut self.portals.sections);
for (id, to, width, height) in items.into_iter().chain(mobs) {
let from = self.portals.before.get(&id).copied().unwrap_or(to);
if let Some(pos) = self.swept_portal(from, to, width, height, &mut portal_sections) {
inside.push((id, pos));
}
}
self.portals.sections = portal_sections;
for (id, pos) in inside {
self.portals
.entities
@@ -509,7 +512,7 @@ impl Game<'_> {
to: Vec3,
width: f32,
height: f32,
portal_sections: &mut horizon_client::fast_hash::FxHashMap<(i32, i32, i32), bool>,
portal_sections: &mut horizon_client::portal_sections::PortalSections,
) -> Option<BlockPos> {
let half = f64::from(width) / 2.0;
let bounds = horizon_core::geometry::Aabb::new(
@@ -550,12 +553,13 @@ impl Game<'_> {
found
}
/// Whether a section `reach` touches has a nether portal state in its
/// palette: without one, no block there is a portal. Answers are kept
/// per section for the tick; a box over many sections is not checked.
/// palette: without one, no block there is a portal. Palette answers are
/// kept per chunk across ticks (`portal_sections`); a box over many
/// sections is not checked.
fn may_hold_portal(
&self,
reach: horizon_core::geometry::Aabb,
seen: &mut horizon_client::fast_hash::FxHashMap<(i32, i32, i32), bool>,
sections: &mut horizon_client::portal_sections::PortalSections,
) -> bool {
use horizon_client::chunk::{MIN_Y, SECTIONS};
let (min, max) = (reach.min_position(), reach.max_position());
@@ -576,23 +580,21 @@ impl Game<'_> {
if count > 64 {
return true;
}
let mut y_mask = 0u32;
for sy in y0..=y1 {
y_mask |= 1 << sy;
}
let behaviours = &self.res.behaviours;
let chunks = &self.world.chunks;
(x0..=x1).any(|cx| {
(z0..=z1).any(|cz| {
(y0..=y1).any(|sy| {
*seen.entry((cx, sy, cz)).or_insert_with(|| {
chunks
.get(&(cx, cz))
.and_then(|c| c.sections.get(sy as usize))
.is_some_and(|s| {
s.blocks.maybe_has(|v| {
behaviours
.portal_axis(horizon_world::registry::BlockStateId(v))
.is_some()
})
})
})
chunks.get(&(cx, cz)).is_some_and(|chunk| {
sections.get((cx, cz), chunk, |v| {
behaviours
.portal_axis(horizon_world::registry::BlockStateId(v))
.is_some()
}) & y_mask
!= 0
})
})
})
@@ -225,6 +225,11 @@ impl Game<'_> {
let _ = std::fs::create_dir_all(&dir);
super::packs::open_folder(&dir);
}
Event::OpenModFolder => {
let dir = Self::options_path().with_file_name(horizon_client::mod_list::DIR);
let _ = std::fs::create_dir_all(&dir);
super::packs::open_folder(&dir);
}
}
}
Ok(())
+1
View File
@@ -154,6 +154,7 @@ impl Game<'_> {
};
// Everything loaded: switch over.
self.random_tick_sections.clear();
self.portals.sections.clear();
self.options.resources = root.to_path_buf();
let context = pack.context.clone();
self.pack = pack;
@@ -255,6 +255,15 @@ impl Game<'_> {
};
for p in &self.paintings {
let entity_start = out.len();
// EntityRenderer.shouldRender: the default range and its box,
// measured from the box's centre (HangingEntity's position).
let (lo, hi) = p.bounds();
let (lo, hi) = (glam::DVec3::from(lo), glam::DVec3::from(hi));
let range =
super::entity_culling::default_range(hi - lo, self.settings.entity_distance);
if !self.entity_in_view(camera, (lo + hi) / 2.0, range, lo, hi) {
continue;
}
let Some(v) = self.painting_variants.get(&p.variant) else {
continue;
};
+25 -1
View File
@@ -176,7 +176,13 @@ impl Game<'_> {
self.dropped.push(e);
}
}
"minecraft:experience_orb" => self.orbs.extend(entity_nbt::orbs_from_nbt(&tag)),
"minecraft:experience_orb" => {
for mut orb in entity_nbt::orbs_from_nbt(&tag) {
self.next_entity += 1;
orb.id = self.next_entity;
self.orbs.push(orb);
}
}
"minecraft:arrow" => {
if let Some((mut p, in_block)) = entity_nbt::arrow_from_nbt(
&tag,
@@ -196,6 +202,7 @@ impl Game<'_> {
{
let (no_gravity, drop_item) = entity_nbt::falling_block_flags(&tag);
self.falling.push(FallingBlock {
id: 0,
state,
// DATA_START_POS is not persisted by vanilla.
start_pos: horizon_core::position::BlockPos::default(),
@@ -214,6 +221,23 @@ impl Game<'_> {
});
}
}
// PrimedTnt.readAdditionalSaveData: its fuse (80 when absent) and motion.
"minecraft:tnt" => {
if let Some(position) = entity_nbt::position(&tag) {
let fuse = match tag.get("fuse") {
Some(Tag::Short(f)) => i32::from(*f),
_ => 80,
};
self.tnts.push(super::tnt::PrimedTnt {
id: 0,
position,
previous: position,
velocity: entity_nbt::motion(&tag),
fuse,
on_ground: matches!(tag.get("OnGround"), Some(Tag::Byte(1))),
});
}
}
k if super::boats::any_boat_wood(k)
.is_some_and(|(wood, chest)| self.boat_models.has(wood, chest)) =>
{
@@ -148,6 +148,7 @@ mod tests {
fn orb_at(x: f64, y: f64, z: f64) -> Taken {
let at = horizon_core::geometry::Vec3::new(x, y, z);
Taken::Orb(Box::new(ExperienceOrb {
id: 0,
position: at,
previous: at,
velocity: horizon_core::geometry::Vec3::new(0.0, 0.0, 0.0),
+25 -4
View File
@@ -228,7 +228,7 @@ impl Game<'_> {
}
let (lasting, now) = PlayerEffects::potion_effects(stack.potion(), 1.0);
for e in lasting {
self.potions.effects.add(e);
self.add_player_effect(e);
}
for a in now {
self.apply_effect_action(a);
@@ -249,7 +249,7 @@ impl Game<'_> {
}
true
}
fn apply_effect_action(&mut self, action: EffectAction) {
pub(super) fn apply_effect_action(&mut self, action: EffectAction) {
let creative = self.creative;
let rules = self.world.health_rules;
let Some(p) = self.player.as_mut() else {
@@ -329,9 +329,24 @@ impl Game<'_> {
}
self.apply_effect_status();
}
/// Add an active effect to the player and update attributes / absorption.
pub(super) fn add_player_effect(&mut self, effect: EffectInstance) -> bool {
let id = effect.id;
let amp = effect.amplifier;
let changed = self.potions.effects.add(effect);
self.apply_effect_status();
if id == "absorption"
&& let Some(p) = self.player.as_mut()
{
let target = 4.0 * (amp + 1) as f32;
let current = p.health.absorption();
let _ = p.set_health(current.max(target), true);
}
changed
}
/// The effects' attribute modifiers, armor protection and status flags
/// on `self.player`.
fn apply_effect_status(&mut self) {
pub(super) fn apply_effect_status(&mut self) {
let modifiers = self.potions.effects.modifiers();
if modifiers != self.potions.applied
&& let Some(p) = self.player.as_mut()
@@ -344,6 +359,12 @@ impl Game<'_> {
}
self.potions.applied = modifiers;
}
if let Some(p) = self.player.as_mut()
&& self.potions.effects.amplifier("absorption").is_none()
&& p.health.absorption() > 0.0
{
let _ = p.set_health(0.0, true);
}
// EnchantmentHelper.getDamageProtection per damage type, recomputed on armor change.
let armor: Vec<Option<ItemStack>> = self.armor.to_vec();
if self.potions.protection_for.as_ref() != Some(&armor) {
@@ -495,7 +516,7 @@ impl Game<'_> {
if d > 20
&& let Some(e) = brewing::effect(id)
{
self.potions.effects.add(EffectInstance::new(e.id, d, *amp));
self.add_player_effect(EffectInstance::new(e.id, d, *amp));
}
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,270 @@
//! Boats, minecarts, armor stands, item frames and paintings on a server's
//! client (`ClientPacketListener.handleAddEntity`, `handleSetEntityData`,
//! `handleSetEquipment`): the server simulates them, the client places them
//! where it says and interpolates their moves like a mob's.
use super::Game;
use horizon_client::entities::{ArmorStand, ItemFrame, Painting};
use horizon_core::geometry::Vec3;
use horizon_protocol::entity_data::Value;
use std::sync::Arc;
impl Game<'_> {
/// `handleAddEntity` for an object type; false when `kind` isn't one.
/// Hanging entities come at their block, with their direction as the
/// spawn data (`Direction.from3DDataValue`).
pub(super) fn spawn_remote_object(
&mut self,
id: i32,
kind: &str,
position: [f64; 3],
yaw: f32,
data: i32,
) -> bool {
let id = id as u32;
let at = Vec3::new(position[0], position[1], position[2]);
let block = position.map(|v| v.floor() as i32);
self.remove_remote_object(id);
if let Some(cart) = super::minecarts::CartKind::from_id(kind) {
let mut c = super::minecarts::Minecart::new(id, cart, at);
c.yaw = yaw;
c.previous_yaw = yaw;
self.carts.push(c);
} else if let Some((wood, chest)) = super::boats::any_boat_wood(kind)
&& self.boat_models.has(wood, chest)
{
let mut b = super::boats::Boat::new(id, Arc::from(wood), at, yaw);
if chest {
b = b.with_chest();
}
self.boats.push(b);
} else if kind == "minecraft:armor_stand" {
self.armor_stands.push(ArmorStand::new(id, at, yaw));
} else if kind == "minecraft:item_frame" || kind == "minecraft:glow_item_frame" {
self.item_frames.push(ItemFrame {
id,
pos: block,
facing: data.clamp(0, 5) as u8,
glow: kind == "minecraft:glow_item_frame",
item: None,
rotation: 0,
drop_chance: 1.0,
fixed: false,
invisible: false,
check_interval: 0,
});
} else if kind == "minecraft:painting" {
// The variant comes with the entity data; until then the
// registry's first one (VariantUtils.getAny).
let (variant, width, height) = self
.remote_painting_variant(0)
.map_or((Arc::from("minecraft:kebab"), 1, 1), |v| {
(v.id, v.width, v.height)
});
// Direction 3D data value (north 2, south 3, west 4, east 5) to 2D.
let facing = match data {
2 => 2,
4 => 1,
5 => 3,
_ => 0,
};
self.paintings.push(Painting {
id,
pos: block,
facing,
variant,
width,
height,
check_interval: 0,
});
} else {
return false;
}
true
}
/// A `painting_variant` by its network id, from the server's registry.
fn remote_painting_variant(&self, id: i32) -> Option<super::paintings::Variant> {
let r = self.remote.as_ref()?;
let name = r.registries.name("minecraft:painting_variant", id)?;
self.painting_variants.get(name).cloned()
}
/// `handleSetEntityData` for an object: what changes how it looks.
pub(super) fn remote_object_data(&mut self, id: i32, values: &[(u8, i32, Value)]) {
let id = id as u32;
for (index, _, value) in values {
if self.item_frames.iter().any(|f| f.id == id) {
// HangingEntity.DATA_DIRECTION, ItemFrame.DATA_ITEM and DATA_ROTATION.
let item = match (index, value) {
(9, Value::Item(stack)) => Some(self.to_stack(stack)),
_ => None,
};
let Some(f) = self.item_frames.iter_mut().find(|f| f.id == id) else {
continue;
};
match (index, value) {
(8, Value::Id(d)) => f.facing = (*d).clamp(0, 5) as u8,
(10, Value::Int(r)) => f.rotation = r.rem_euclid(8) as u8,
_ => {}
}
if let Some(item) = item {
f.item = item;
}
} else if self.paintings.iter().any(|p| p.id == id) {
// Painting.DATA_PAINTING_VARIANT_ID: a registry holder (id + 1).
if let (9, Value::Id(holder)) = (index, value)
&& let Some(v) = self.remote_painting_variant(holder - 1)
&& let Some(p) = self.paintings.iter_mut().find(|p| p.id == id)
{
p.variant = v.id;
p.width = v.width;
p.height = v.height;
}
} else if let Some(a) = self.armor_stands.iter_mut().find(|a| a.id == id) {
match (index, value) {
(0, Value::Byte(flags)) => a.invisible = flags & 0x20 != 0,
(9, Value::Float(health)) => a.health = *health,
// ArmorStand.DATA_CLIENT_FLAGS.
(15, Value::Byte(flags)) => {
a.small = flags & 1 != 0;
a.show_arms = flags & 4 != 0;
a.no_base_plate = flags & 8 != 0;
a.marker = flags & 16 != 0;
}
_ => {}
}
} else if let Some(b) = self.boats.iter_mut().find(|b| b.id == id) {
// VehicleEntity's hurt, direction and damage; the paddles.
match (index, value) {
(8, Value::Int(v)) => b.hurt_time = *v,
(9, Value::Int(v)) => b.hurt_dir = *v,
(10, Value::Float(v)) => b.damage = *v,
(11, Value::Bool(v)) => b.paddling[0] = *v,
(12, Value::Bool(v)) => b.paddling[1] = *v,
_ => {}
}
} else if let Some(c) = self.carts.iter_mut().find(|c| c.id == id) {
match (index, value) {
(8, Value::Int(v)) => c.hurt_time = *v,
(9, Value::Int(v)) => c.hurt_dir = *v,
(10, Value::Float(v)) => c.damage = *v,
_ => {}
}
}
}
}
/// `handleSetEquipment` for an armor stand (EquipmentSlot ordinals 0 to
/// 5: main hand, off hand, feet, legs, chest, head, its storage order).
pub(super) fn remote_object_equipment(
&mut self,
id: i32,
slots: &[(u8, Option<horizon_protocol::item::Stack>)],
) {
if !self.armor_stands.iter().any(|a| a.id == id as u32) {
return;
}
let items: Vec<_> = slots
.iter()
.map(|(slot, stack)| (usize::from(*slot), self.to_stack(stack)))
.collect();
if let Some(a) = self.armor_stands.iter_mut().find(|a| a.id == id as u32) {
for (slot, item) in items {
if let Some(s) = a.equipment.get_mut(slot) {
*s = item;
}
}
}
}
/// A move's rotation and ground state for an object.
pub(super) fn turn_remote_object(&mut self, id: i32, yaw: Option<f32>, on_ground: bool) {
let id = id as u32;
if let Some(b) = self.boats.iter_mut().find(|b| b.id == id) {
if let Some(yaw) = yaw {
b.yaw = yaw;
}
b.on_ground = on_ground;
} else if let Some(c) = self.carts.iter_mut().find(|c| c.id == id) {
if let Some(yaw) = yaw {
c.yaw = yaw;
}
} else if let Some(a) = self.armor_stands.iter_mut().find(|a| a.id == id) {
if let Some(yaw) = yaw {
a.yaw = yaw;
}
a.on_ground = on_ground;
}
}
/// One tick of interpolation: `step` moves a position a step toward
/// the entity's last sent one, if it has a move in progress.
pub(super) fn tick_remote_objects(&mut self, mut step: impl FnMut(u32, Vec3) -> Vec3) {
for c in &mut self.carts {
c.previous = c.position;
c.previous_yaw = c.yaw;
c.position = step(c.id, c.position);
}
for b in &mut self.boats {
b.previous = b.position;
b.previous_yaw = b.yaw;
b.position = step(b.id, b.position);
}
for a in &mut self.armor_stands {
a.position = step(a.id, a.position);
}
}
/// The boats, minecarts, armor stands, item frames and paintings in the
/// level (a server's client: the ones it was sent), for `status`.
pub(super) fn objects_status(&self) -> Vec<serde_json::Value> {
use serde_json::json;
let at = |p: Vec3| [p.x, p.y, p.z];
let mut out = Vec::new();
for b in &self.boats {
out.push(json!({"id": b.id, "kind": b.entity_type(), "position": at(b.position), "yaw": b.yaw}));
}
for c in &self.carts {
out.push(
json!({"id": c.id, "kind": c.kind.id(), "position": at(c.position), "yaw": c.yaw}),
);
}
for a in &self.armor_stands {
let items: Vec<_> = a
.equipment
.iter()
.map(|i| i.as_ref().map(|i| &*i.item))
.collect();
out.push(json!({"id": a.id, "kind": "minecraft:armor_stand", "position": at(a.position), "yaw": a.yaw,
"small": a.small, "arms": a.show_arms, "no_base_plate": a.no_base_plate, "equipment": items}));
}
for f in &self.item_frames {
out.push(
json!({"id": f.id, "kind": f.kind(), "position": f.pos, "facing": f.facing,
"item": f.item.as_ref().map(|i| &*i.item), "rotation": f.rotation}),
);
}
for p in &self.paintings {
out.push(json!({"id": p.id, "kind": "minecraft:painting", "position": p.pos, "facing": p.facing,
"variant": &*p.variant}));
}
out
}
/// Every object a server sent (a new connection, level or dimension).
pub(super) fn clear_remote_objects(&mut self) {
self.carts.clear();
self.boats.clear();
self.armor_stands.clear();
self.item_frames.clear();
self.paintings.clear();
}
pub(super) fn remove_remote_object(&mut self, id: u32) {
self.carts.retain(|c| c.id != id);
self.boats.retain(|b| b.id != id);
self.armor_stands.retain(|a| a.id != id);
self.item_frames.retain(|f| f.id != id);
self.paintings.retain(|p| p.id != id);
}
}
@@ -0,0 +1,229 @@
//! Primed TNT, falling blocks, projectiles, tridents, firework rockets and
//! end crystals on a server's client (`ClientPacketListener.handleAddEntity`
//! and `handleSetEntityData`): the server simulates them, the client draws
//! them where it says and interpolates their moves.
use super::{FallingBlock, Game};
use horizon_client::projectiles::{Projectile, ProjectileKind};
use horizon_core::{geometry::Vec3, position::BlockPos};
use horizon_protocol::entity_data::Value;
use horizon_world::registry::BlockStateId;
/// The projectile a type id names, as Horizon models it.
fn projectile_kind(kind: &str) -> Option<ProjectileKind> {
Some(match kind {
"minecraft:arrow" | "minecraft:spectral_arrow" => ProjectileKind::Arrow {
base_damage: 2.0,
critical: false,
effect: None,
},
"minecraft:snowball" => ProjectileKind::Snowball,
"minecraft:egg" => ProjectileKind::Egg,
"minecraft:ender_pearl" => ProjectileKind::EnderPearl,
"minecraft:small_fireball" => ProjectileKind::SmallFireball,
"minecraft:fireball" => ProjectileKind::LargeFireball { power: 1 },
"minecraft:llama_spit" => ProjectileKind::LlamaSpit,
"minecraft:wind_charge" => ProjectileKind::WindCharge,
"minecraft:breeze_wind_charge" => ProjectileKind::BreezeWindCharge,
"minecraft:wither_skull" => ProjectileKind::WitherSkull { dangerous: false },
_ => return None,
})
}
impl Game<'_> {
/// `handleAddEntity` for these types; false when `kind` isn't one.
pub(super) fn spawn_remote_projectile(
&mut self,
id: i32,
kind: &str,
position: [f64; 3],
rotation: (f32, f32),
velocity: [f64; 3],
data: i32,
) -> bool {
let id = id as u32;
let at = Vec3::new(position[0], position[1], position[2]);
let velocity = Vec3::new(velocity[0], velocity[1], velocity[2]);
let (yaw, pitch) = rotation;
self.remove_remote_projectile(id);
match kind {
"minecraft:tnt" => self.tnts.push(super::tnt::PrimedTnt {
id,
position: at,
previous: at,
velocity,
fuse: 80,
on_ground: false,
}),
// FallingBlockEntity.recreateFromPacket: the block state is the data.
"minecraft:falling_block" => self.falling.push(FallingBlock {
id,
state: BlockStateId(data.max(0) as u32),
start_pos: BlockPos::default(),
position: at,
previous: at,
velocity,
age: 0,
no_gravity: false,
drop_item: false,
fall_distance: 0.0,
damage: Default::default(),
saved: None,
}),
"minecraft:trident" => {
let mut t = super::trident::ThrownTrident::remote(id, at, yaw, pitch);
t.velocity = velocity;
self.tridents.push(t);
}
"minecraft:firework_rocket" => {
self.rockets
.push(super::fireworks::Rocket::remote(id, at, velocity));
}
"minecraft:end_crystal" => self.crystals.push(super::dragon::Crystal {
id,
position: at,
show_bottom: true,
time: 0,
beam: None,
invulnerable: false,
}),
_ => {
let Some(k) = projectile_kind(kind) else {
return false;
};
let mut p = Projectile::new(k, at, None);
p.id = id;
p.velocity = velocity;
p.yaw = yaw;
p.pitch = pitch;
self.creatures.projectiles.push(p);
}
}
true
}
/// `handleSetEntityData` for these types: what changes how they look.
pub(super) fn remote_projectile_data(&mut self, id: i32, values: &[(u8, i32, Value)]) {
let id = id as u32;
for (index, _, value) in values {
if let Some(t) = self.tnts.iter_mut().find(|t| t.id == id) {
// PrimedTnt.DATA_FUSE_ID.
if let (8, Value::Int(fuse)) = (index, value) {
t.fuse = *fuse;
}
} else if let Some(f) = self.falling.iter_mut().find(|f| f.id == id) {
// FallingBlockEntity.DATA_START_POS (the model's seed).
if let (8, Value::Pos(p)) = (index, value) {
f.start_pos = BlockPos::new(p[0], p[1], p[2]);
}
} else if let Some(c) = self.crystals.iter_mut().find(|c| c.id == id) {
// EndCrystal.DATA_BEAM_TARGET and DATA_SHOW_BOTTOM.
match (index, value) {
(8, Value::OptPos(beam)) => c.beam = *beam,
(9, Value::Bool(show)) => c.show_bottom = *show,
_ => {}
}
} else if let Some(p) = self.creatures.projectiles.iter_mut().find(|p| p.id == id) {
match (&mut p.kind, index, value) {
// AbstractArrow.ID_FLAGS (critical) and IN_GROUND.
(ProjectileKind::Arrow { critical, .. }, 8, Value::Byte(flags)) => {
*critical = flags & 1 != 0;
}
(ProjectileKind::Arrow { .. }, 10, Value::Bool(in_ground)) => {
p.stuck = *in_ground;
}
// WitherSkull.DATA_DANGEROUS.
(ProjectileKind::WitherSkull { dangerous }, 8, Value::Bool(d)) => {
*dangerous = *d;
}
_ => {}
}
}
}
}
/// A move's rotation for a projectile or trident.
pub(super) fn turn_remote_projectile(&mut self, id: i32, rotation: Option<(f32, f32)>) {
let (id, Some((yaw, pitch))) = (id as u32, rotation) else {
return;
};
if let Some(p) = self.creatures.projectiles.iter_mut().find(|p| p.id == id) {
p.yaw = yaw;
p.pitch = pitch;
} else if let Some(t) = self.tridents.iter_mut().find(|t| t.id == id) {
t.yaw = yaw;
t.pitch = pitch;
}
}
/// One tick of interpolation, as `tick_remote_objects`.
pub(super) fn tick_remote_projectiles(&mut self, mut step: impl FnMut(u32, Vec3) -> Vec3) {
for t in &mut self.tnts {
t.previous = t.position;
t.position = step(t.id, t.position);
}
for f in &mut self.falling {
f.previous = f.position;
f.age += 1;
f.position = step(f.id, f.position);
}
for p in &mut self.creatures.projectiles {
p.previous = p.position;
p.age += 1;
p.position = step(p.id, p.position);
}
for t in &mut self.tridents {
let id = t.id;
t.remote_step(|at| step(id, at));
}
for r in &mut self.rockets {
let id = r.id;
r.remote_step(|at| step(id, at));
}
for c in &mut self.crystals {
c.time += 1;
c.position = step(c.id, c.position);
}
}
pub(super) fn remove_remote_projectile(&mut self, id: u32) {
self.tnts.retain(|t| t.id != id);
self.falling.retain(|f| f.id != id);
self.creatures.projectiles.retain(|p| p.id != id);
self.tridents.retain(|t| t.id != id);
self.rockets.retain(|r| r.id != id);
self.crystals.retain(|c| c.id != id);
}
/// Every one a server sent (a new connection, level or dimension).
pub(super) fn clear_remote_projectiles(&mut self) {
self.tnts.clear();
self.falling.clear();
self.creatures.projectiles.clear();
self.tridents.clear();
self.rockets.clear();
self.crystals.clear();
}
/// Their kind and place, for `status`.
pub(super) fn projectiles_status(&self) -> Vec<serde_json::Value> {
use serde_json::json;
let at = |p: Vec3| [p.x, p.y, p.z];
let mut out = Vec::new();
for t in &self.tnts {
out.push(json!({"id": t.id, "kind": "minecraft:tnt", "position": at(t.position), "fuse": t.fuse}));
}
for f in &self.falling {
out.push(json!({"id": f.id, "kind": "minecraft:falling_block", "position": at(f.position), "state": f.state.0}));
}
for c in &self.crystals {
out.push(json!({"id": c.id, "kind": "minecraft:end_crystal", "position": at(c.position), "show_bottom": c.show_bottom}));
}
for t in &self.tridents {
out.push(json!({"id": t.id, "kind": "minecraft:trident", "position": at(t.position)}));
}
for p in &self.creatures.projectiles {
out.push(json!({"id": p.id, "kind": format!("{:?}", p.kind).split([' ', '{']).next().unwrap_or(""), "position": at(p.position)}));
}
out
}
}
@@ -127,7 +127,7 @@ impl Game<'_> {
let entity = horizon_client::containers::BlockEntity::for_block(&name)
.filter(|e| matches!(e, horizon_client::containers::BlockEntity::Sign(_)))
.ok_or("no sign there")?;
self.world.block_entities.entry(key).or_insert(entity);
self.world.block_entities.get_or_insert_with(key, || entity);
self.open_sign_editor(key, words.get(4) != Some(&"back"));
Ok(Some(json!({ "ok": true })))
}
@@ -324,7 +324,7 @@ impl Game<'_> {
)
.unwrap_or_else(|_| VoxelShape::empty())
}
fn block_in_tag(&self, tag: &str, block: &str) -> bool {
pub(super) fn block_in_tag(&self, tag: &str, block: &str) -> bool {
self.res
.items
.block_tags
+6 -4
View File
@@ -6,13 +6,14 @@
use super::{Game, Result};
use horizon_client::{
containers::BlockEntity,
fast_hash::{FxHashMap, FxHashSet},
mobs::{Mob, Species, Who, warden},
particles::{ParticleOptions, ParticleType},
sculk::{self, Context, Info, SculkEntity, SculkKind, WardenSpawnTracker},
};
use horizon_core::{geometry::Direction, position::BlockPos, random::RandomSource};
use horizon_world::registry::BlockStateId;
use std::collections::{HashMap, HashSet};
use std::collections::HashSet;
use winit::keyboard::KeyCode;
pub const HELP: &[&str] = &[
@@ -70,8 +71,9 @@ pub(super) struct SculkState {
/// The sculk block entities in the order they were added.
index: Index,
pub known: HashSet<(i32, i32)>,
steps: HashMap<Who, Steps>,
damaged: HashMap<u32, i64>,
// Keyed by mob ids the server gives out: the fast hasher is safe.
steps: FxHashMap<Who, Steps>,
damaged: FxHashMap<u32, i64>,
last_health: Option<f32>,
/// The darkness effect's blend factor, previous and current tick.
darkness: (f32, f32),
@@ -1528,7 +1530,7 @@ impl Game<'_> {
}
}
}
let alive: HashSet<u32> = self.mobs.iter().map(|m| m.id).collect();
let alive: FxHashSet<u32> = self.mobs.iter().map(|m| m.id).collect();
self.sculk.damaged.retain(|id, _| alive.contains(id));
self.sculk.steps.retain(|who, _| match who {
Who::Player => true,
@@ -22,6 +22,17 @@ pub(super) struct Trip {
end: bool,
/// The Nether portal plan, whose exit is found or built on arrival.
plan: Option<Plan>,
/// Sent by a command: the player is already where it goes.
placed: bool,
}
/// `TeleportCommand` into another level for a server's player: where, and
/// the rotation it sets (none keeps the player's).
pub(super) struct LevelTeleport {
pub conn: u32,
pub dim: Dim,
pub at: [f64; 3],
pub rotation: Option<[f32; 2]>,
}
/// A player's box: Player's standing dimensions.
@@ -177,7 +188,8 @@ impl Game<'_> {
};
let at = [destination.x, destination.y, destination.z];
let ctx = self.server_ctx();
host.hub.change_level(i, at, yaw, &ctx);
// TeleportTransition.PLAY_PORTAL_SOUND.
host.hub.change_level(i, at, yaw, None, true, &ctx);
self.as_guest(host, conn, |g| g.trigger_dimension(source, target));
self.server_trips.push(Trip {
conn,
@@ -185,6 +197,7 @@ impl Game<'_> {
target: destination,
end,
plan,
placed: false,
});
if let Err(e) = self.enter_level(Some(host), source) {
log::error!("could not reopen {}: {e}", source.id());
@@ -214,6 +227,9 @@ impl Game<'_> {
continue;
}
let trip = self.server_trips.remove(k);
if trip.placed {
continue;
}
self.resolve_arrivals();
let yaw = host.hub.guests[i].yaw;
let (position, yaw) = if trip.end {
@@ -248,6 +264,43 @@ impl Game<'_> {
}
}
/// The players the command just run sends to another level
/// (`ServerPlayer.teleport` from TeleportCommand): a Respawn packet
/// keeping all data and the teleport, with no portal sound. The server
/// leaves the body alone until the level has loaded around it.
pub(super) fn run_level_teleports(&mut self, host: &mut LanHost) {
for t in std::mem::take(&mut self.level_teleports) {
let Some(i) = host.hub.guests.iter().position(|g| g.conn == t.conn) else {
continue;
};
let source = self.dim;
if let Err(e) = self.enter_level(Some(host), t.dim) {
log::error!("could not open {}: {e}", t.dim.id());
continue;
}
let g = &mut host.hub.guests[i];
let [yaw, pitch] = t.rotation.unwrap_or([g.yaw, g.pitch]);
// A new body there: no fall distance or motion carried over.
g.motion = None;
let ctx = self.server_ctx();
host.hub
.change_level(i, t.at, yaw, Some(pitch), false, &ctx);
self.as_guest(host, t.conn, |g| g.trigger_dimension(source, t.dim));
self.server_trips.retain(|trip| !trip.is(t.conn));
self.server_trips.push(Trip {
conn: t.conn,
dim: t.dim,
target: Vec3::new(t.at[0], t.at[1], t.at[2]),
end: false,
plan: None,
placed: true,
});
if let Err(e) = self.enter_level(Some(host), source) {
log::error!("could not reopen {}: {e}", source.id());
}
}
}
/// The hub's view of the server for packets sent outside its own tick.
pub(super) fn server_ctx(&mut self) -> TickCtx<'_> {
let spawn = self.spawn.map_or([0.5, 80.0, 0.5], |s| [s.x, s.y, s.z]);
+21 -27
View File
@@ -45,7 +45,7 @@ impl Game<'_> {
.as_ref()
.is_some_and(|t| t.contains(id))
}
fn load_entity_types(&mut self) {
pub(super) fn load_entity_types(&mut self) {
if self.spawners.entity_types.is_some() {
return;
}
@@ -63,32 +63,27 @@ impl Game<'_> {
.unwrap_or_default();
self.spawners.entity_types = Some(types);
}
/// Every spawner's server tick, then its client tick.
pub(super) fn tick_spawners(&mut self) -> Result<()> {
self.load_entity_types();
let keys: Vec<Pos> = self
.world
.block_entities
.iter()
.filter(|(_, e)| matches!(e, BlockEntity::Spawner(_)))
.map(|(k, _)| *k)
.collect();
for key in &keys {
let state = self.world.block(key.0, key.1, key.2);
if &*self.res.facts.get(state).name != "minecraft:spawner" {
continue;
}
let Some(BlockEntity::Spawner(mut spawner)) = self.world.block_entities.remove(key)
else {
continue;
};
let result = self.server_tick_spawner(*key, &mut spawner);
self.world
.block_entities
.insert(*key, BlockEntity::Spawner(spawner));
result?;
/// The server tick of the spawner at `key`, if its block is still a
/// spawner. Its client tick comes after every block entity's
/// (`client_tick_spawners`).
pub(super) fn tick_spawner(&mut self, key: Pos) -> Result<()> {
let state = self.world.block(key.0, key.1, key.2);
if &*self.res.facts.get(state).name != "minecraft:spawner" {
return Ok(());
}
for key in keys {
let Some(BlockEntity::Spawner(mut spawner)) = self.world.block_entities.take(&key) else {
return Ok(());
};
let result = self.server_tick_spawner(key, &mut spawner);
self.world
.block_entities
.put(key, BlockEntity::Spawner(spawner));
result
}
/// The client ticks of these spawners, then the shown mobs of spawners
/// that are gone go.
pub(super) fn client_tick_spawners(&mut self, keys: &[Pos]) {
for &key in keys {
self.client_tick_spawner(key);
}
let entities = &self.world.block_entities;
@@ -98,7 +93,6 @@ impl Game<'_> {
Some(BlockEntity::Spawner(_) | BlockEntity::TrialSpawner(_))
)
});
Ok(())
}
fn server_tick_spawner(&mut self, key: Pos, spawner: &mut Spawner) -> Result<()> {
let pos = [key.0, key.1, key.2];
+72 -43
View File
@@ -1885,17 +1885,27 @@ impl Game<'_> {
} else {
self.pack.names.item(&stack.item)
};
let mut lines = vec![(name, color)];
let display = horizon_client::item_tooltip::TooltipDisplay::for_stack(stack);
let mut lines = Vec::new();
if display.name_visible(self.screen == Screen::Creative) {
lines.push((name, color));
}
let translate = |k: &str| e.translate(k).map(str::to_owned);
// ItemContainerContents.addToTooltip.
let hover_name = |s: &ItemStack| {
s.custom_name()
.map_or_else(|| self.pack.names.item(&s.item), str::to_owned)
};
for line in horizon_client::item_tooltip::container_lines(stack, &hover_name, &translate) {
lines.push((line, u32::MAX));
if display.shows("minecraft:container") {
for line in
horizon_client::item_tooltip::container_lines(stack, &hover_name, &translate)
{
lines.push((line, u32::MAX));
}
}
if stack.item.ends_with("potion") || &*stack.item == "minecraft:tipped_arrow" {
if display.shows("minecraft:potion_contents")
&& (stack.item.ends_with("potion") || &*stack.item == "minecraft:tipped_arrow")
{
let scale = match &*stack.item {
"minecraft:lingering_potion" => 0.25,
"minecraft:tipped_arrow" => 0.125,
@@ -1912,7 +1922,9 @@ impl Game<'_> {
lines.push((line, c));
}
}
if let Some((material, pattern)) = stack.data().and_then(|d| d.trim.clone()) {
if display.shows("minecraft:trim")
&& let Some((material, pattern)) = stack.data().and_then(|d| d.trim.clone())
{
lines.push((
e.translate("item.minecraft.smithing_template.upgrade")
.unwrap_or("Upgrade:")
@@ -1929,30 +1941,44 @@ impl Game<'_> {
lines.push((format!(" {p}"), rgba(170, 170, 170, 255)));
lines.push((format!(" {m}"), rgba(170, 170, 170, 255)));
}
for (text, curse) in e
.tooltip(stack.stored_enchantments())
.into_iter()
.chain(e.tooltip(stack.enchantments()))
{
lines.push((
text,
if curse {
rgba(255, 85, 85, 255)
} else {
rgba(170, 170, 170, 255)
},
));
if display.shows("minecraft:stored_enchantments") {
for (text, curse) in e.tooltip(stack.stored_enchantments()) {
lines.push((
text,
if curse {
rgba(255, 85, 85, 255)
} else {
rgba(170, 170, 170, 255)
},
));
}
}
if display.shows("minecraft:enchantments") {
for (text, curse) in e.tooltip(stack.enchantments()) {
lines.push((
text,
if curse {
rgba(255, 85, 85, 255)
} else {
rgba(170, 170, 170, 255)
},
));
}
}
// BannerPatternLayers.addToTooltip: up to six layer names.
for layer in horizon_client::banner::tooltip_layers(stack).iter().take(6) {
let key = self.res.stations.banners.layer_key(layer);
lines.push((self.translate(&key, &key), rgba(170, 170, 170, 255)));
if display.shows("minecraft:banner_patterns") {
for layer in horizon_client::banner::tooltip_layers(stack).iter().take(6) {
let key = self.res.stations.banners.layer_key(layer);
lines.push((self.translate(&key, &key), rgba(170, 170, 170, 255)));
}
}
// Spawner.appendHoverText: what a spawner or trial spawner item spawns.
if matches!(
&*stack.item,
"minecraft:spawner" | "minecraft:trial_spawner"
) {
if display.shows("minecraft:block_entity_data")
&& matches!(
&*stack.item,
"minecraft:spawner" | "minecraft:trial_spawner"
)
{
let gray = rgba(170, 170, 170, 255);
match block_entity_item::spawner_entity(stack) {
Some(id) => {
@@ -1969,7 +1995,9 @@ impl Game<'_> {
}
}
}
if let Some(info) = self.res.items.get(&stack.item) {
if display.shows("minecraft:attribute_modifiers")
&& let Some(info) = self.res.items.get(&stack.item)
{
let base = |name: &str, default| {
self.player
.as_ref()
@@ -1997,7 +2025,8 @@ impl Game<'_> {
&translate,
));
}
if let Some(info) = self.res.items.get(&stack.item)
if display.shows("minecraft:damage")
&& let Some(info) = self.res.items.get(&stack.item)
&& info.max_damage > 0
&& stack.damage > 0
&& self.options_advanced_tooltips()
@@ -2144,22 +2173,22 @@ impl Game<'_> {
// ---------------------------------------------------------------- brewing stand
/// Ticks every brewing stand (`BrewingStandBlockEntity.serverTick`).
pub(super) fn tick_brewing_stands(&mut self) -> horizon_client::Result<()> {
let mut changes = Vec::new();
for (pos, entity) in self.world.block_entities.iter_mut() {
if let BlockEntity::Brewing(b) = entity {
let out = b.tick(
&self.res.stations.brewing,
&self.res.items,
&self.res.providers,
);
if out != brewing::BrewTick::default() {
changes.push((*pos, out));
}
}
}
for ((x, y, z), out) in changes {
/// `BrewingStandBlockEntity.serverTick` of the brewing stand at `pos`, in
/// its place among the level's block entity tickers.
pub(super) fn tick_brewing_stand(
&mut self,
pos: (i32, i32, i32),
) -> horizon_client::Result<()> {
let Some(BlockEntity::Brewing(b)) = self.world.block_entities.get_mut(&pos) else {
return Ok(());
};
let out = b.tick(
&self.res.stations.brewing,
&self.res.items,
&self.res.providers,
);
if out != brewing::BrewTick::default() {
let (x, y, z) = pos;
self.world.modified.insert((x >> 4, z >> 4));
if out.brewed {
self.play_at("minecraft:block.brewing_stand.brew", [x, y, z], 1.0, 1.0);
+21
View File
@@ -12,6 +12,8 @@ use horizon_world::level::flags as level_flags;
#[derive(Clone, Debug)]
pub(super) struct PrimedTnt {
/// The entity id a server tracks it by (0 until it is tracked).
pub id: u32,
pub position: Vec3,
pub previous: Vec3,
pub velocity: Vec3,
@@ -140,6 +142,7 @@ impl Game<'_> {
f64::from(pos.z) + 0.5,
);
self.tnts.push(PrimedTnt {
id: 0,
position,
previous: position,
velocity: Vec3::new(-rot.sin() * 0.02, f64::from(0.2f32), -rot.cos() * 0.02),
@@ -241,7 +244,24 @@ impl Game<'_> {
.and_then(|name| self.atlas.sprites.get(name).copied());
}
}
let range = super::entity_culling::default_range(
glam::DVec3::splat(PrimedTnt::SIZE),
self.settings.entity_distance,
);
for t in &self.tnts {
// EntityRenderer.shouldRender.
if !self.standing_entity_in_view(
camera,
super::entity_culling::at(t.previous),
super::entity_culling::at(t.position),
alpha,
PrimedTnt::SIZE,
PrimedTnt::SIZE,
range,
0.0,
) {
continue;
}
let fuse = t.fuse as f32 - alpha as f32 + 1.0;
let scale = if fuse < 10.0 {
let g = (1.0 - fuse / 10.0).clamp(0.0, 1.0);
@@ -484,6 +504,7 @@ mod tests {
world.set(21, 4, 20, flowing).unwrap();
let at = Vec3::new(20.5, 4.0, 20.5);
let mut tnt = PrimedTnt {
id: 0,
position: at,
previous: at,
velocity: Vec3::ZERO,
+1 -3
View File
@@ -53,9 +53,7 @@ impl Game<'_> {
("fire_resistance", 800, 0),
] {
if let Some(e) = horizon_client::brewing::effect(id) {
self.potions
.effects
.add(EffectInstance::new(e.id, ticks, amp));
self.add_player_effect(EffectInstance::new(e.id, ticks, amp));
}
}
self.audio
+14 -27
View File
@@ -106,34 +106,21 @@ impl TrialSpawnerLevel for GameLevel<'_, '_> {
}
impl Game<'_> {
/// Every trial spawner's server tick.
pub(super) fn tick_trial_spawners(&mut self) -> Result<()> {
let keys: Vec<Pos> = self
.world
/// The server tick of the trial spawner at `key`. Its client tick comes
/// after every block entity's.
pub(super) fn tick_trial_spawner(&mut self, key: Pos) -> Result<()> {
let Some((current, ominous)) = self.trial_spawner_block(key) else {
return Ok(());
};
let Some(BlockEntity::TrialSpawner(mut spawner)) = self.world.block_entities.take(&key)
else {
return Ok(());
};
let result = self.server_tick_trial_spawner(key, &mut spawner, current, ominous);
self.world
.block_entities
.iter()
.filter(|(_, e)| matches!(e, BlockEntity::TrialSpawner(_)))
.map(|(k, _)| *k)
.collect();
for &key in &keys {
let Some((current, ominous)) = self.trial_spawner_block(key) else {
continue;
};
let Some(BlockEntity::TrialSpawner(mut spawner)) =
self.world.block_entities.remove(&key)
else {
continue;
};
let result = self.server_tick_trial_spawner(key, &mut spawner, current, ominous);
self.world
.block_entities
.insert(key, BlockEntity::TrialSpawner(spawner));
result?;
}
for key in keys {
self.client_tick_trial_spawner(key);
}
Ok(())
.put(key, BlockEntity::TrialSpawner(spawner));
result
}
/// The trial spawner block at `key`: its state and ominous flag.
pub(super) fn trial_spawner_block(&self, key: Pos) -> Option<(TrialState, bool)> {
@@ -237,7 +237,7 @@ impl Game<'_> {
let shows = vault.display_item.is_some();
self.world
.block_entities
.insert(key, BlockEntity::Vault(vault));
.put(key, BlockEntity::Vault(vault));
let pos = [key.0, key.1, key.2];
if self.world.game_time % 20 == 0 {
self.vault_connection_particles(pos);
+56 -8
View File
@@ -15,20 +15,48 @@ use horizon_core::{
};
pub(super) struct ThrownTrident {
stack: ItemStack,
position: Vec3,
/// The entity id a server tracks it by (0 until it is tracked).
pub id: u32,
pub(super) stack: ItemStack,
pub(super) position: Vec3,
previous: Vec3,
velocity: Vec3,
yaw: f32,
pitch: f32,
in_ground: bool,
pub(super) velocity: Vec3,
pub(super) yaw: f32,
pub(super) pitch: f32,
pub(super) in_ground: bool,
in_ground_time: u32,
dealt_damage: bool,
loyalty: u32,
no_physics: bool,
pub(super) loyalty: u32,
pub(super) no_physics: bool,
returning: u32,
creative_only: bool,
}
impl ThrownTrident {
/// A trident a server sent (`handleAddEntity`): placed and moved by it.
pub(super) fn remote(id: u32, position: Vec3, yaw: f32, pitch: f32) -> Self {
Self {
id,
stack: ItemStack::new("minecraft:trident", 1),
position,
previous: position,
velocity: Vec3::ZERO,
yaw,
pitch,
in_ground: false,
in_ground_time: 0,
dealt_damage: false,
loyalty: 0,
no_physics: false,
returning: 0,
creative_only: false,
}
}
/// One tick of a server's client: the previous position, then `step`.
pub(super) fn remote_step(&mut self, step: impl FnOnce(Vec3) -> Vec3) {
self.previous = self.position;
self.position = step(self.position);
}
}
const HALF: f64 = 0.25;
fn bounds(p: Vec3) -> Aabb {
Aabb::new(
@@ -163,6 +191,7 @@ impl Game<'_> {
on_ground,
);
self.tridents.push(ThrownTrident {
id: 0,
loyalty: thrown.enchantment_level("minecraft:loyalty"),
stack: thrown,
position: start,
@@ -350,7 +379,26 @@ impl Game<'_> {
else {
return;
};
// AbstractArrow.shouldRenderAtSqrDistance: ten times the default.
let range = 10.0
* super::entity_culling::default_range(
glam::DVec3::splat(2.0 * HALF),
self.settings.entity_distance,
);
for t in &self.tridents {
// EntityRenderer.shouldRender; ThrownTridentRenderer grows the box by 1.5.
if !self.standing_entity_in_view(
camera,
super::entity_culling::at(t.previous),
super::entity_culling::at(t.position),
alpha,
2.0 * HALF,
2.0 * HALF,
range,
1.5,
) {
continue;
}
let p = glam::DVec3::new(
t.previous.x + (t.position.x - t.previous.x) * alpha,
t.previous.y + (t.position.y - t.previous.y) * alpha,
+1 -9
View File
@@ -70,15 +70,7 @@ impl Game<'_> {
/// One ordinary click on a game slot. False when nothing took it.
pub(super) fn tweak_click(&mut self, slot: usize, button: i32, input: Input) -> bool {
if self.remote.is_some() {
let ordinal = match input {
Input::Pickup => 0,
Input::QuickMove => 1,
Input::Swap => 2,
Input::Clone => 3,
Input::Throw => 4,
Input::QuickCraft => 5,
Input::PickupAll => 6,
};
let ordinal = super::remote::input_ordinal(input);
return self.remote_slot_click(slot, button as i8, ordinal);
}
if !self.menu_click(Some(slot), button, input) {
+13 -19
View File
@@ -61,7 +61,7 @@ impl Game<'_> {
.and_then(|s| VaultState::from_name(s))
.unwrap_or_default();
let ominous = block.properties.get("ominous").is_some_and(|v| v == "true");
let Some(BlockEntity::Vault(vault)) = self.world.block_entities.remove(&key) else {
let Some(BlockEntity::Vault(vault)) = self.world.block_entities.take(&key) else {
return None;
};
Some((vault, current, ominous))
@@ -118,26 +118,20 @@ impl Game<'_> {
self.rand_sequences = sequences;
self.world
.block_entities
.insert(key, BlockEntity::Vault(vault));
.put(key, BlockEntity::Vault(vault));
Some(self.vault_events(key, events).map(|()| out))
}
/// Every vault's server tick, then its client tick.
pub(super) fn tick_vaults(&mut self) -> Result<()> {
let keys: Vec<Pos> = self
.world
.block_entities
.iter()
.filter(|(_, e)| matches!(e, BlockEntity::Vault(_)))
.map(|(k, _)| *k)
.collect();
for key in keys {
let pos = [key.0, key.1, key.2];
let ticked = self.with_vault(key, |v, l, random, state, ominous, roll, events| {
v.server_tick(l, random, pos, state, ominous, roll, events);
});
if let Some(result) = ticked {
result?;
}
/// The server tick of the vault at `key`, then its client tick when there
/// is a window.
pub(super) fn tick_vault(&mut self, key: Pos) -> Result<()> {
let pos = [key.0, key.1, key.2];
let ticked = self.with_vault(key, |v, l, random, state, ominous, roll, events| {
v.server_tick(l, random, pos, state, ominous, roll, events);
});
if let Some(result) = ticked {
result?;
}
if self.options.dedicated.is_none() {
self.client_tick_vault(key);
}
Ok(())
+105 -19
View File
@@ -70,6 +70,12 @@ pub mod translucency;
pub(crate) mod upload;
mod world_post;
/// A new value for `Renderer::block_entity_revision`.
fn next_block_entity_revision() -> u64 {
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
}
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct Globals {
@@ -108,6 +114,12 @@ struct SectionGpu {
}
/// Line segments the hit outline can hold.
const MAX_OUTLINE_EDGES: u64 = 256;
/// Staging buffer size for section meshes: a frame of uploads while
/// exploring fits in a few.
const SECTION_UPLOAD_CHUNK: u64 = 4 << 20;
/// Section copies are submitted early past this many staged bytes, which
/// bounds the staging memory frames that are not drawn can hold.
const SECTION_COPY_LIMIT: u64 = 64 << 20;
pub struct Frame<'a> {
pub camera: DVec3,
pub yaw: f32,
@@ -322,6 +334,13 @@ pub struct Renderer {
lightmap_sampler: wgpu::Sampler,
animations: AnimatedSprites,
uploads: upload::Uploads,
/// Section meshes are staged through their own belt into
/// `section_copies`, which the next submission runs ahead of the frame:
/// `Queue::write_buffer` would make a staging buffer per write.
section_uploads: upload::Uploads,
section_copies: Option<wgpu::CommandEncoder>,
/// Bytes staged in `section_copies`.
section_copy_bytes: u64,
/// Whether `lightmap` holds `lightmap_pixels` yet.
lightmap_uploaded: bool,
sprite_minimum_size: u32,
@@ -355,6 +374,8 @@ pub struct Renderer {
draw_pages: Vec<(u32, Option<u32>)>,
/// Block-entity blocks per meshed section (world position, state id).
block_entities: HashMap<SectionKey, Vec<([i32; 3], u32)>>,
/// Changes whenever `block_entities` does (unique across renderers).
block_entity_revision: u64,
/// VisGraph face connectivity per meshed section (cave culling).
occlusion: occlusion::Occlusion,
/// Resolution scale and FXAA (Horizon settings).
@@ -1734,6 +1755,7 @@ impl Renderer {
.contains(wgpu::Features::INDIRECT_FIRST_INSTANCE);
let world_post = world_post::Post::new(&device, config.format.remove_srgb_suffix());
let uploads = upload::Uploads::new(&device);
let section_uploads = upload::Uploads::with_chunk(&device, SECTION_UPLOAD_CHUNK);
let panorama = panorama::Panorama::new(
&device,
&queue,
@@ -1808,6 +1830,9 @@ impl Renderer {
lightmap_sampler,
animations: AnimatedSprites::new(animations, sprite_size, sprite_mips),
uploads,
section_uploads,
section_copies: None,
section_copy_bytes: 0,
lightmap_uploaded: false,
sprite_minimum_size,
indices,
@@ -1833,6 +1858,7 @@ impl Renderer {
draws: Vec::new(),
draw_pages: Vec::new(),
block_entities: HashMap::new(),
block_entity_revision: next_block_entity_revision(),
occlusion: occlusion::Occlusion::new(crate::chunk::HEIGHT / 16),
world_post,
pack: None,
@@ -1990,12 +2016,23 @@ impl Renderer {
pub fn has_section(&self, key: SectionKey) -> bool {
self.sections.contains(key)
}
/// Bring the cave culling graph up to date for `camera` without waiting:
/// a search this starts runs on its worker while the frame is prepared,
/// and `render` takes it if it has finished.
pub fn start_occlusion(&mut self, camera: DVec3, distance: f32) {
self.occlusion
.update(camera_section(camera), (distance / 16.0) as i32 + 2);
}
pub fn upload(&mut self, key: SectionKey, mesh: &SectionMesh) {
self.occlusion.set(key, mesh.visibility);
if mesh.block_entities.is_empty() {
self.block_entities.remove(&key);
let changed = if mesh.block_entities.is_empty() {
self.block_entities.remove(&key).is_some()
} else {
self.block_entities.insert(key, mesh.block_entities.clone());
let old = self.block_entities.insert(key, mesh.block_entities.clone());
old.as_deref() != Some(&mesh.block_entities[..])
};
if changed {
self.block_entity_revision = next_block_entity_revision();
}
self.release_section(key);
let section = self.upload_mesh(mesh);
@@ -2020,12 +2057,18 @@ impl Renderer {
self.indices = Self::quad_indices(&self.device, self.index_quads);
}
let vertices = (mesh.solid.len() + mesh.translucent.len()) as u64;
let encoder = self.section_copies.get_or_insert_with(|| {
self.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("Section uploads"),
})
});
// With video and system memory both full, the section is not drawn.
let (page, start) = self.arena.alloc(&self.device, &self.queue, vertices)?;
let (page, start) = self.arena.alloc(&self.device, encoder, vertices)?;
let sorted_indices = if translucent > 0 {
let indices =
self.sorted_indices
.alloc(&self.device, &self.queue, u64::from(translucent) * 6);
.alloc(&self.device, encoder, u64::from(translucent) * 6);
if indices.is_none() {
self.arena.release(page, start, vertices);
return None;
@@ -2034,22 +2077,35 @@ impl Renderer {
} else {
None
};
let flat_id = self
.flat
.as_mut()
.map(|f| f.add(&self.device, &self.queue, page, start, vertices));
let flat_id = self.flat.as_mut().map(|f| {
f.add(
&self.device,
encoder,
&mut self.section_uploads,
page,
start,
vertices,
)
});
let stride = std::mem::size_of::<TerrainVertex>() as u64;
for (offset, part) in [(0, &mesh.solid), (mesh.solid.len(), &mesh.translucent)] {
if !part.is_empty() {
let bytes: &[u8] = bytemuck::cast_slice(part);
self.uploaded_bytes += bytes.len() as u64;
self.queue.write_buffer(
self.section_copy_bytes += bytes.len() as u64;
self.section_uploads.buffer(
encoder,
self.arena.buffer(page),
(start + offset as u64) * stride,
bytes,
);
}
}
if self.section_copy_bytes >= SECTION_COPY_LIMIT
&& let Some(copies) = self.take_section_copies()
{
self.queue.submit([copies]);
}
Some(SectionGpu {
page,
start,
@@ -2068,6 +2124,13 @@ impl Renderer {
flat_id,
})
}
/// The section copies recorded since the last submission, closed.
fn take_section_copies(&mut self) -> Option<wgpu::CommandBuffer> {
let encoder = self.section_copies.take()?;
self.section_copy_bytes = 0;
self.section_uploads.finish(&encoder);
Some(encoder.finish())
}
/// Draws `count` section draws from `first` with the arena and section
/// origins bound: one indirect multi-draw, or a loop without it.
/// Consecutive draws in one arena page share a vertex buffer binding,
@@ -2113,8 +2176,13 @@ impl Renderer {
pub fn block_entities(&self) -> impl Iterator<Item = &([i32; 3], u32)> {
self.block_entities.values().flatten()
}
/// A value that changes whenever `block_entities` gives something else.
pub fn block_entity_revision(&self) -> u64 {
self.block_entity_revision
}
pub fn clear_sections(&mut self) {
self.block_entities.clear();
self.block_entity_revision = next_block_entity_revision();
self.sections.clear();
self.lods.clear();
self.detail_columns.clear();
@@ -2139,7 +2207,9 @@ impl Renderer {
self.detail_columns.remove(&(key.0, key.2));
}
}
self.block_entities.remove(&key);
if self.block_entities.remove(&key).is_some() {
self.block_entity_revision = next_block_entity_revision();
}
self.occlusion.remove(key);
self.release_section(key);
}
@@ -2314,6 +2384,14 @@ impl Renderer {
);
}
pub fn render(&mut self, frame: &Frame) -> Result<bool> {
let rendered = self.draw_frame(frame);
// A frame that was not drawn still submits the section copies.
if let Some(copies) = self.take_section_copies() {
self.queue.submit([copies]);
}
rendered
}
fn draw_frame(&mut self, frame: &Frame) -> Result<bool> {
self.arena.trim();
self.sorted_indices.trim();
if let Some(flat) = &mut self.flat {
@@ -2501,16 +2579,11 @@ impl Renderer {
planes: frustum(view_proj),
};
let camera = frame.camera;
let camera_section = (
(camera.x.floor() as i32) >> 4,
(camera.y.floor() as i32 - crate::chunk::MIN_Y) >> 4,
(camera.z.floor() as i32) >> 4,
);
let camera_section = camera_section(camera);
let culling = !frame.title && frame.cave_culling;
if culling {
let radius = (frame.detail_distance / 16.0) as i32 + 2;
crate::spans::time("occlusion", || {
self.occlusion.update(camera_section, radius)
self.start_occlusion(camera, frame.detail_distance)
});
}
let reachable = &self.occlusion;
@@ -3268,7 +3341,11 @@ impl Renderer {
.map(|path| (path, self.copy_frame(&mut encoder, &target_texture)));
self.uploads.finish(&encoder);
let commands = crate::spans::time("encode", || encoder.finish());
let submission = crate::spans::time("submit", || self.queue.submit([commands]));
// The section copies run first: this frame draws what they write.
let copies = self.take_section_copies();
let submission = crate::spans::time("submit", || {
self.queue.submit(copies.into_iter().chain([commands]))
});
if let Some(timer) = &mut self.gpu_timer {
timer.submitted();
timer.collect(&self.device, &mut self.gpu_times);
@@ -3473,6 +3550,15 @@ enum Pack {
Java(java_stages::JavaStages),
}
/// The section the camera is in.
fn camera_section(camera: DVec3) -> SectionKey {
(
(camera.x.floor() as i32) >> 4,
(camera.y.floor() as i32 - crate::chunk::MIN_Y) >> 4,
(camera.z.floor() as i32) >> 4,
)
}
fn world_projection(fov_degrees: f32, aspect: f32, far: f32) -> Mat4 {
Mat4::perspective_rh(fov_degrees.to_radians(), aspect, far, 0.05)
}
+63 -21
View File
@@ -155,12 +155,14 @@ impl Arena {
.buffer
}
/// A range of `vertices`: (page, first vertex). Grows the newest page
/// (copying its contents on the GPU) or starts a new one when nothing
/// free is large enough; `None` when no memory is left for it.
/// (copying its contents on the GPU, in `encoder`) or starts a new one
/// when nothing free is large enough; `None` when no memory is left for
/// it. Writes to the arena belong in `encoder` too, so that those
/// recorded before a grow reach the grown page.
pub fn alloc(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
encoder: &mut wgpu::CommandEncoder,
vertices: u64,
) -> Option<(u32, u64)> {
let len = Self::span(vertices).min(self.page_limit);
@@ -178,7 +180,7 @@ impl Arena {
let current = page.capacity;
let grown = (current * 2).max(current + len).min(self.page_limit);
if (grown - current >= len || grown == self.page_limit)
&& self.grow(device, queue, last, grown)
&& self.grow(device, encoder, last, grown)
&& let Some(start) = self.pages[last].as_mut().unwrap().free.take(len)
{
return Some((last as u32, start));
@@ -228,7 +230,7 @@ impl Arena {
fn grow(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
encoder: &mut wgpu::CommandEncoder,
page: usize,
capacity: u64,
) -> bool {
@@ -237,12 +239,8 @@ impl Arena {
return false;
};
let old = self.pages[page].as_mut().expect("live arena page");
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("Grow section arena"),
});
// Copies recorded for the old buffer run before this one.
encoder.copy_buffer_to_buffer(&old.buffer, 0, &buffer, 0, old.capacity * self.stride);
// Writes queued for the old buffer run before this copy.
queue.submit([encoder.finish()]);
let previous = old.capacity;
old.buffer = buffer;
old.capacity = capacity;
@@ -304,6 +302,50 @@ mod tests {
.ok()
}
/// `Arena::alloc`, with the copies of a grow submitted at once.
fn alloc(
arena: &mut Arena,
device: &wgpu::Device,
queue: &wgpu::Queue,
vertices: u64,
) -> Option<(u32, u64)> {
let mut encoder = device.create_command_encoder(&Default::default());
let range = arena.alloc(device, &mut encoder, vertices);
queue.submit([encoder.finish()]);
range
}
#[test]
fn writes_recorded_before_a_grow_reach_the_grown_page() {
let Some((device, queue)) = device() else {
eprintln!("no GPU adapter: skipped");
return;
};
let mut arena = Arena::indices(&device, GRAIN, false);
let mut uploads = super::super::upload::Uploads::new(&device);
let mut encoder = device.create_command_encoder(&Default::default());
let (page, start) = arena.alloc(&device, &mut encoder, GRAIN).unwrap();
uploads.buffer(
&mut encoder,
arena.buffer(page),
start * 4,
&7u32.to_le_bytes(),
);
// The page is full: the next range grows it, in the same encoder.
let (grown, next) = arena.alloc(&device, &mut encoder, GRAIN).unwrap();
assert_eq!(grown, page);
uploads.buffer(
&mut encoder,
arena.buffer(grown),
next * 4,
&9u32.to_le_bytes(),
);
uploads.finish(&encoder);
queue.submit([encoder.finish()]);
assert_eq!(read(&device, &queue, arena.buffer(page), start * 4), 7);
assert_eq!(read(&device, &queue, arena.buffer(page), next * 4), 9);
}
#[test]
fn empty_pages_are_reclaimed_without_moving_live_ranges() {
let Some((device, queue)) = device() else {
@@ -313,9 +355,9 @@ mod tests {
let mut arena = Arena::new(&device, 4, GRAIN);
arena.page_limit = 2 * GRAIN;
assert_eq!(arena.bytes(), 0);
let (first, a) = arena.alloc(&device, &queue, GRAIN).unwrap();
let (_, b) = arena.alloc(&device, &queue, GRAIN).unwrap();
let (live, c) = arena.alloc(&device, &queue, 2 * GRAIN).unwrap();
let (first, a) = alloc(&mut arena, &device, &queue, GRAIN).unwrap();
let (_, b) = alloc(&mut arena, &device, &queue, GRAIN).unwrap();
let (live, c) = alloc(&mut arena, &device, &queue, 2 * GRAIN).unwrap();
let buffer = arena.buffer(live).clone();
let data = [1u8, 2, 3, 4];
queue.write_buffer(&buffer, c * 4, &data);
@@ -327,7 +369,7 @@ mod tests {
arena.trim();
assert_eq!(arena.bytes(), 2 * GRAIN * 4);
assert_eq!(arena.buffer(live), &buffer);
let (reused, d) = arena.alloc(&device, &queue, GRAIN).unwrap();
let (reused, d) = alloc(&mut arena, &device, &queue, GRAIN).unwrap();
assert_eq!(reused, first);
let (tx, rx) = std::sync::mpsc::channel();
@@ -356,11 +398,11 @@ mod tests {
Arena::new(&device, 28, GRAIN),
Arena::indices(&device, GRAIN, false),
] {
arena.alloc(&device, &queue, GRAIN).unwrap();
alloc(&mut arena, &device, &queue, GRAIN).unwrap();
assert_eq!(arena.bytes(), arena.stride * GRAIN);
arena.clear();
assert_eq!(arena.bytes(), 0);
assert_eq!(arena.alloc(&device, &queue, GRAIN), Some((0, 0)));
assert_eq!(alloc(&mut arena, &device, &queue, GRAIN), Some((0, 0)));
assert_eq!(arena.bytes(), arena.stride * GRAIN);
}
}
@@ -414,12 +456,12 @@ mod tests {
return;
}
let mut arena = Arena::indices(&device, GRAIN, false);
let (page, start) = arena.alloc(&device, &queue, GRAIN).unwrap();
let (page, start) = alloc(&mut arena, &device, &queue, GRAIN).unwrap();
queue.write_buffer(arena.buffer(page), start * 4, &7u32.to_le_bytes());
arena.video_memory_full = true;
// The full page can't grow in video memory: it moves to system
// memory with its contents, and new ranges come from there.
let (grown, next) = arena.alloc(&device, &queue, GRAIN).unwrap();
let (grown, next) = alloc(&mut arena, &device, &queue, GRAIN).unwrap();
assert!(arena.spilled);
assert_eq!(grown, page);
assert!(
@@ -439,13 +481,13 @@ mod tests {
return;
};
let mut arena = Arena::indices(&device, GRAIN, false);
arena.alloc(&device, &queue, GRAIN).unwrap();
alloc(&mut arena, &device, &queue, GRAIN).unwrap();
arena.video_memory_full = true;
// Without mappable primary buffers nothing can spill: the request
// fails, and the arena keeps what it has.
assert_eq!(arena.alloc(&device, &queue, GRAIN), None);
assert_eq!(alloc(&mut arena, &device, &queue, GRAIN), None);
assert_eq!(arena.bytes(), GRAIN * 4);
arena.release(0, 0, GRAIN);
assert_eq!(arena.alloc(&device, &queue, GRAIN), Some((0, 0)));
assert_eq!(alloc(&mut arena, &device, &queue, GRAIN), Some((0, 0)));
}
}
+9 -3
View File
@@ -262,11 +262,12 @@ impl Flat {
}
}
/// A section uploaded to `vertices` vertices from `start` of `page`: its
/// id, which its blocks now name.
/// id, which its blocks now name (written through `uploads` in `encoder`).
pub fn add(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
encoder: &mut wgpu::CommandEncoder,
uploads: &mut super::upload::Uploads,
page: u32,
start: u64,
vertices: u64,
@@ -290,7 +291,12 @@ impl Flat {
});
let first = start / GRAIN;
let ids = vec![id; vertices.div_ceil(GRAIN) as usize];
queue.write_buffer(&table.blocks, first * 4, bytemuck::cast_slice(&ids));
uploads.buffer(
encoder,
&table.blocks,
first * 4,
bytemuck::cast_slice(&ids),
);
id
}
pub fn remove(&mut self, id: u32) {
+514 -100
View File
@@ -2,11 +2,18 @@
//! faces. Breadth-first from the camera section through the faces each
//! section's VisGraph connects, never stepping back towards the camera.
//!
//! The search runs over dense arrays around the camera rather than hash sets,
//! so it stays cheap enough to redo whenever a section is meshed.
//! As in vanilla, the full search runs off the render thread: a worker keeps
//! its own copy of every section's connectivity and searches over dense
//! arrays around the camera. Frames use the last finished graph and never wait
//! for the next one. A section meshed in between propagates into the graph the
//! frame has (vanilla's partial update), so what it opens shows at once; what
//! it closes goes at the next full search.
use super::SectionKey;
use crate::mesher::ALL_VISIBLE;
use std::collections::{HashMap, VecDeque};
use std::sync::mpsc::{self, Receiver, Sender, TryRecvError};
/// Vanilla's `Direction` order: down, up, north, south, west, east.
const STEPS: [(i32, i32, i32); 6] = [
(0, -1, 0),
(0, 1, 0),
@@ -15,74 +22,92 @@ const STEPS: [(i32, i32, i32); 6] = [
(-1, 0, 0),
(1, 0, 0),
];
/// In `Graph::directions`: the cell has a node.
const REACHED: u8 = 1 << 7;
/// In `Graph::entered`: the camera's own section, entered through no face.
const NONE: u8 = 6;
pub struct Occlusion {
/// VisGraph connectivity per column, one entry per section (bottom first).
columns: HashMap<(i32, i32), Box<[u64]>>,
/// VisGraph connectivity per column, one entry per section (bottom first).
/// A missing column or section connects every face.
struct Columns {
sections: i32,
dirty: bool,
from: Option<SectionKey>,
map: HashMap<(i32, i32), Box<[u64]>>,
}
impl Columns {
fn new(sections: i32) -> Self {
Self {
sections,
map: HashMap::new(),
}
}
/// Whether the section's connectivity changed.
fn set(&mut self, key: SectionKey, vis: u64) -> bool {
if !(0..self.sections).contains(&key.1) {
return false;
}
let column = match self.map.get_mut(&(key.0, key.2)) {
Some(column) => column,
None if vis == ALL_VISIBLE => return false,
None => self
.map
.entry((key.0, key.2))
.or_insert_with(|| vec![ALL_VISIBLE; self.sections as usize].into()),
};
let slot = &mut column[key.1 as usize];
if *slot == vis {
return false;
}
*slot = vis;
if vis == ALL_VISIBLE && column.iter().all(|&v| v == ALL_VISIBLE) {
self.map.remove(&(key.0, key.2));
}
true
}
fn get(&self, key: SectionKey) -> u64 {
self.map
.get(&(key.0, key.2))
.and_then(|column| column.get(usize::try_from(key.1).ok()?))
.copied()
.unwrap_or(ALL_VISIBLE)
}
fn apply(&mut self, edit: Edit) {
match edit {
Edit::Set(key, vis) => {
self.set(key, vis);
}
Edit::Clear => self.map.clear(),
}
}
}
#[derive(Clone, Copy)]
enum Edit {
Set(SectionKey, u64),
Clear,
}
/// One search's result over the box around the camera: vanilla's
/// `GraphStorage.sectionToNodeMap`, as dense arrays.
#[derive(Default)]
struct Graph {
from: SectionKey,
radius: i32,
/// The searched box: lowest section y and its height in sections.
y0: i32,
height: i32,
reached: Vec<bool>,
vis: Vec<u64>,
queue: VecDeque<(u32, u8, u8)>,
/// Per cell: `REACHED`, and the directions travelled from the camera to
/// it (`Node.directions`).
directions: Vec<u8>,
/// Per cell: the face it was first entered through (`NONE` for the
/// camera's). Vanilla's `Node.sourceDirections` also keeps the faces it is
/// reached through later; Horizon keeps the first only.
entered: Vec<u8>,
}
impl Occlusion {
pub fn new(sections: i32) -> Self {
Self {
columns: HashMap::new(),
sections,
dirty: true,
from: None,
radius: 0,
y0: 0,
height: 0,
reached: Vec::new(),
vis: Vec::new(),
queue: VecDeque::new(),
}
}
pub fn set(&mut self, key: SectionKey, vis: u64) {
if !(0..self.sections).contains(&key.1) {
return;
}
let sections = self.sections as usize;
let column = self
.columns
.entry((key.0, key.2))
.or_insert_with(|| vec![crate::mesher::ALL_VISIBLE; sections].into());
let slot = &mut column[key.1 as usize];
if *slot != vis {
*slot = vis;
self.dirty = true;
}
}
pub fn remove(&mut self, key: SectionKey) {
let Some(column) = self.columns.get_mut(&(key.0, key.2)) else {
return;
};
if let Some(slot) = column.get_mut(key.1 as usize)
&& *slot != crate::mesher::ALL_VISIBLE
{
*slot = crate::mesher::ALL_VISIBLE;
self.dirty = true;
}
if column.iter().all(|&v| v == crate::mesher::ALL_VISIBLE) {
self.columns.remove(&(key.0, key.2));
}
}
pub fn clear(&mut self) {
self.columns.clear();
self.dirty = true;
}
impl Graph {
fn index(&self, key: SectionKey) -> Option<usize> {
let from = self.from?;
let (dx, dz, dy) = (key.0 - from.0, key.2 - from.2, key.1 - self.y0);
let (dx, dz, dy) = (key.0 - self.from.0, key.2 - self.from.2, key.1 - self.y0);
let side = 2 * self.radius + 1;
if dx.abs() > self.radius || dz.abs() > self.radius || !(0..self.height).contains(&dy) {
return None;
@@ -90,86 +115,331 @@ impl Occlusion {
Some((((dz + self.radius) * side + dx + self.radius) * self.height + dy) as usize)
}
fn key(&self, index: usize) -> SectionKey {
let from = self.from.expect("searched");
let side = 2 * self.radius + 1;
let i = index as i32;
let dy = i % self.height;
let column = i / self.height;
(
from.0 + column % side - self.radius,
self.y0 + dy,
from.2 + column / side - self.radius,
self.from.0 + column % side - self.radius,
self.y0 + i % self.height,
self.from.2 + column / side - self.radius,
)
}
pub fn contains(&self, key: SectionKey) -> bool {
self.index(key).is_some_and(|i| self.reached[i])
fn contains(&self, key: SectionKey) -> bool {
self.index(key)
.is_some_and(|i| self.directions[i] & REACHED != 0)
}
/// Search again when sections changed or the camera moved to another section.
pub fn update(&mut self, from: SectionKey, radius: i32) {
if !self.dirty && self.from == Some(from) && self.radius == radius {
return;
}
self.from = Some(from);
/// The full search from `from` (vanilla's `scheduleFullUpdate`).
fn search(
&mut self,
columns: &Columns,
from: SectionKey,
radius: i32,
vis: &mut Vec<u64>,
queue: &mut VecDeque<u32>,
) {
self.from = from;
self.radius = radius;
self.y0 = from.1.min(-1);
self.height = from.1.max(self.sections) - self.y0 + 1;
self.height = from.1.max(columns.sections) - self.y0 + 1;
let side = (2 * radius + 1) as usize;
let size = side * side * self.height as usize;
self.reached.clear();
self.reached.resize(size, false);
self.vis.clear();
self.vis.resize(size, crate::mesher::ALL_VISIBLE);
self.directions.clear();
self.directions.resize(size, 0);
self.entered.clear();
self.entered.resize(size, NONE);
vis.clear();
vis.resize(size, ALL_VISIBLE);
for dz in -radius..=radius {
for dx in -radius..=radius {
let Some(column) = self.columns.get(&(from.0 + dx, from.2 + dz)) else {
let Some(column) = columns.map.get(&(from.0 + dx, from.2 + dz)) else {
continue;
};
let base = self
.index((from.0 + dx, 0, from.2 + dz))
.expect("column inside the searched box");
self.vis[base..base + column.len()].copy_from_slice(column);
vis[base..base + column.len()].copy_from_slice(column);
}
}
let start = self.index(from).expect("camera inside the searched box");
self.reached[start] = true;
self.queue.clear();
self.queue.push_back((start as u32, NONE, 0));
while let Some((index, entered, travelled)) = self.queue.pop_front() {
let vis = self.vis[index as usize];
let key = self.key(index as usize);
self.directions[start] = REACHED;
queue.clear();
queue.push_back(start as u32);
self.propagate(queue, columns.sections, |i, _| vis[i]);
}
/// Vanilla's `runUpdates`: take nodes from the queue and step through
/// every face their entry face connects to, away from the camera.
fn propagate(
&mut self,
queue: &mut VecDeque<u32>,
sections: i32,
vis: impl Fn(usize, SectionKey) -> u64,
) {
while let Some(index) = queue.pop_front() {
let i = index as usize;
let key = self.key(i);
let directions = self.directions[i];
let entered = self.entered[i];
let exits = if entered == NONE {
0x3f
} else {
(vis(i, key) >> (u32::from(entered) * 6)) as u8 & 0x3f
};
for (d, step) in STEPS.iter().enumerate() {
let opposite = d ^ 1;
if travelled & (1 << opposite) != 0 {
continue;
}
if entered != NONE && vis & (1 << (usize::from(entered) * 6 + d)) == 0 {
if exits & (1 << d) == 0 || directions & (1 << (d ^ 1)) != 0 {
continue;
}
let next = (key.0 + step.0, key.1 + step.1, key.2 + step.2);
if next.1 < -1 || next.1 > self.sections {
if next.1 < -1 || next.1 > sections {
continue;
}
let Some(n) = self.index(next) else { continue };
if !self.reached[n] {
self.reached[n] = true;
self.queue
.push_back((n as u32, opposite as u8, travelled | (1 << d)));
if self.directions[n] & REACHED == 0 {
self.directions[n] = directions | 1 << d;
self.entered[n] = (d ^ 1) as u8;
queue.push_back(n as u32);
}
}
}
}
}
struct Job {
edits: Vec<Edit>,
from: SectionKey,
radius: i32,
/// Buffers to reuse.
graph: Graph,
}
/// The thread that runs full searches over its own copy of the columns.
struct Worker {
jobs: Sender<Job>,
done: Receiver<(Graph, Vec<Edit>)>,
}
impl Worker {
fn spawn(sections: i32) -> Option<Self> {
let (jobs, job_rx) = mpsc::channel::<Job>();
let (done_tx, done) = mpsc::channel();
std::thread::Builder::new()
.name("occlusion".into())
.spawn(move || {
let mut columns = Columns::new(sections);
let (mut vis, mut queue) = (Vec::new(), VecDeque::new());
while let Ok(mut job) = job_rx.recv() {
for edit in job.edits.drain(..) {
columns.apply(edit);
}
job.graph
.search(&columns, job.from, job.radius, &mut vis, &mut queue);
if done_tx.send((job.graph, job.edits)).is_err() {
break;
}
}
})
.ok()?;
Some(Self { jobs, done })
}
}
pub struct Occlusion {
/// The render thread's copy, for partial updates (and searches when the
/// worker is gone).
columns: Columns,
/// Edits the worker has not been sent yet.
edits: Vec<Edit>,
/// A full search is due: sections changed since the last one started.
dirty: bool,
/// The last finished search; `None` until one finishes, or after the
/// columns were cleared.
graph: Option<Graph>,
spare: Graph,
worker: Option<Worker>,
/// The camera section and radius of the running search.
running: Option<(SectionKey, i32)>,
/// The running search started before the columns were cleared: drop it.
discard: bool,
/// The camera section and radius `graph`'s search started from (or is
/// starting from).
searched: Option<(SectionKey, i32)>,
/// Sections changed since `graph`'s search started, to propagate from.
changed: Vec<SectionKey>,
/// Sections changed since the running search started: they propagate into
/// its graph when it lands.
changed_late: Vec<SectionKey>,
vis: Vec<u64>,
queue: VecDeque<u32>,
}
impl Occlusion {
pub fn new(sections: i32) -> Self {
Self {
columns: Columns::new(sections),
edits: Vec::new(),
dirty: true,
graph: None,
spare: Graph::default(),
worker: Worker::spawn(sections),
running: None,
discard: false,
searched: None,
changed: Vec::new(),
changed_late: Vec::new(),
vis: Vec::new(),
queue: VecDeque::new(),
}
}
pub fn set(&mut self, key: SectionKey, vis: u64) {
if self.columns.set(key, vis) {
self.edits.push(Edit::Set(key, vis));
self.dirty = true;
self.changed.push(key);
if self.running.is_some() {
self.changed_late.push(key);
}
}
}
pub fn remove(&mut self, key: SectionKey) {
self.set(key, ALL_VISIBLE);
}
pub fn clear(&mut self) {
self.columns.map.clear();
self.edits.clear();
self.edits.push(Edit::Clear);
self.dirty = true;
// Another world: the old graph says nothing about it.
if let Some(graph) = self.graph.take() {
self.spare = graph;
}
self.searched = None;
self.discard = self.running.is_some();
self.changed.clear();
self.changed_late.clear();
}
/// Whether `key` is visible from the camera. Without a usable graph
/// (before the first search lands, or with the camera somewhere the graph
/// never reached) every section is.
pub fn contains(&self, key: SectionKey) -> bool {
self.graph.as_ref().is_none_or(|g| g.contains(key))
}
/// Take a finished search, propagate changed sections into the graph,
/// and start a search when sections changed or the camera moved to
/// another section. Never waits for the worker.
pub fn update(&mut self, from: SectionKey, radius: i32) {
self.collect(false);
self.propagate_changes();
if self.running.is_none() && (self.dirty || self.searched != Some((from, radius))) {
self.start(from, radius);
}
// A graph that never reached the camera's section hides everything
// around it: until the new one lands, cull by the frustum alone.
if self
.graph
.as_ref()
.is_some_and(|g| g.from != from && !g.contains(from))
&& let Some(graph) = self.graph.take()
{
self.spare = graph;
}
}
fn start(&mut self, from: SectionKey, radius: i32) {
self.dirty = false;
self.searched = Some((from, radius));
let graph = std::mem::take(&mut self.spare);
if let Some(worker) = &self.worker {
let job = Job {
edits: std::mem::take(&mut self.edits),
from,
radius,
graph,
};
if worker.jobs.send(job).is_ok() {
self.running = Some((from, radius));
self.changed_late.clear();
return;
}
log::warn!("Horizon: the occlusion worker stopped; culling on the render thread");
self.worker = None;
}
self.edits.clear();
let mut graph = Graph::default();
graph.search(&self.columns, from, radius, &mut self.vis, &mut self.queue);
self.land(graph);
}
fn collect(&mut self, wait: bool) {
let Some(worker) = &self.worker else { return };
if self.running.is_none() {
return;
}
let result = if wait {
worker.done.recv().map_err(|_| TryRecvError::Disconnected)
} else {
worker.done.try_recv()
};
match result {
Ok((graph, edits)) => {
self.running = None;
if self.edits.is_empty() {
self.edits = edits;
}
if std::mem::take(&mut self.discard) {
self.spare = graph;
return;
}
self.land(graph);
self.changed.clear();
self.changed.append(&mut self.changed_late);
}
Err(TryRecvError::Empty) => {}
Err(TryRecvError::Disconnected) => {
// The edits it held are lost with it: search here from now on.
self.worker = None;
self.running = None;
self.discard = false;
self.dirty = true;
}
}
}
fn land(&mut self, graph: Graph) {
if let Some(old) = self.graph.replace(graph) {
self.spare = old;
}
}
/// Vanilla's `runPartialUpdate`: what changed sections now connect to.
fn propagate_changes(&mut self) {
let Some(graph) = &mut self.graph else {
self.changed.clear();
return;
};
self.queue.clear();
for key in self.changed.drain(..) {
if let Some(i) = graph.index(key)
&& graph.directions[i] & REACHED != 0
{
self.queue.push_back(i as u32);
}
}
let columns = &self.columns;
graph.propagate(&mut self.queue, columns.sections, |_, key| columns.get(key));
}
/// Wait for the running search: tests, and A/B timing of the old
/// blocking search.
#[cfg(test)]
fn settle(&mut self, from: SectionKey, radius: i32) {
self.update(from, radius);
self.collect(true);
self.propagate_changes();
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::mesher::ALL_VISIBLE;
#[test]
fn open_space_reaches_the_whole_box() {
let mut o = Occlusion::new(4);
o.update((0, 1, 0), 2);
o.settle((0, 1, 0), 2);
for x in -2..=2 {
for z in -2..=2 {
for y in -1..=4 {
@@ -186,11 +456,155 @@ mod tests {
for (dx, dy, dz) in STEPS {
o.set((dx, 1 + dy, dz), 0);
}
o.update((0, 1, 0), 3);
o.settle((0, 1, 0), 3);
assert!(o.contains((1, 1, 0)), "a neighbour is seen");
assert!(!o.contains((2, 1, 0)), "nothing shows through it");
o.set((1, 1, 0), ALL_VISIBLE);
o.update((0, 1, 0), 3);
o.settle((0, 1, 0), 3);
assert!(o.contains((2, 1, 0)));
}
#[test]
fn frames_never_wait_and_partial_updates_open_at_once() {
let mut o = Occlusion::new(4);
for (dx, dy, dz) in STEPS {
o.set((dx, 1 + dy, dz), 0);
}
o.settle((0, 1, 0), 3);
assert!(!o.contains((2, 1, 0)));
// Opening the wall shows what is behind it in the same frame, from the
// graph the frame has, whether or not the full search has finished.
o.set((1, 1, 0), ALL_VISIBLE);
o.update((0, 1, 0), 3);
assert!(o.contains((2, 1, 0)));
assert!(o.contains((3, 1, 0)));
// Closing it again lasts until the next full search lands.
o.set((1, 1, 0), 0);
o.settle((0, 1, 0), 3);
o.settle((0, 1, 0), 3);
assert!(!o.contains((2, 1, 0)));
}
#[test]
fn a_graph_that_lost_the_camera_culls_nothing() {
let mut o = Occlusion::new(4);
for (dx, dy, dz) in STEPS {
o.set((dx, 1 + dy, dz), 0);
}
o.settle((0, 1, 0), 3);
assert!(!o.contains((3, 1, 0)));
// The camera jumped past the wall; the next search is still running.
let o = &mut o;
o.update((3, 1, 0), 3);
if o.running.is_some() {
assert!(o.contains((3, 1, 0)));
}
o.settle((3, 1, 0), 3);
assert!(o.contains((3, 1, 0)));
assert!(
!o.contains((0, 1, 0)),
"the old camera section is walled in"
);
}
/// The search before it moved to the worker (main at ce38c8d7), over the
/// same box: whether each cell is reached.
fn reference(columns: &Columns, from: SectionKey, radius: i32) -> Vec<bool> {
let y0 = from.1.min(-1);
let height = from.1.max(columns.sections) - y0 + 1;
let side = 2 * radius + 1;
let index = |k: SectionKey| {
let (dx, dz, dy) = (k.0 - from.0, k.2 - from.2, k.1 - y0);
(dx.abs() <= radius && dz.abs() <= radius && (0..height).contains(&dy))
.then(|| (((dz + radius) * side + dx + radius) * height + dy) as usize)
};
let size = (side * side * height) as usize;
let mut reached = vec![false; size];
let start = index(from).unwrap();
reached[start] = true;
let mut queue = VecDeque::from([(from, NONE, 0u8)]);
while let Some((key, entered, travelled)) = queue.pop_front() {
let vis = columns.get(key);
for (d, step) in STEPS.iter().enumerate() {
let opposite = d ^ 1;
if travelled & (1 << opposite) != 0 {
continue;
}
if entered != NONE && vis & (1 << (usize::from(entered) * 6 + d)) == 0 {
continue;
}
let next = (key.0 + step.0, key.1 + step.1, key.2 + step.2);
if next.1 < -1 || next.1 > columns.sections {
continue;
}
let Some(n) = index(next) else { continue };
if !reached[n] {
reached[n] = true;
queue.push_back((next, opposite as u8, travelled | (1 << d)));
}
}
}
reached
}
fn random_world(o: &mut Occlusion, seed: u64, count: usize) {
let mut seed = seed;
let mut next = || {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
seed
};
for _ in 0..count {
let r = next();
let key = (
(r % 13) as i32 - 6,
((r >> 8) % 6) as i32,
((r >> 16) % 13) as i32 - 6,
);
// Open, half open or nearly closed sections.
let vis = match r >> 40 & 3 {
0 => next() & next() & next(),
1 => next(),
_ => next() | next(),
};
o.set(key, vis & ALL_VISIBLE);
}
}
/// The graph is the search the render thread did before, cell for cell.
#[test]
fn same_sections_as_before() {
let mut hidden = 0;
for seed in [0x9e37_79b9, 7, 0xdead_beef] {
let mut o = Occlusion::new(6);
random_world(&mut o, seed, 900);
for from in [(0, 2, 0), (3, 0, -2), (-5, 5, 4), (1, -1, 1), (0, 7, 0)] {
o.settle(from, 6);
o.settle(from, 6);
let graph = o.graph.as_ref().expect("searched");
let reached: Vec<bool> =
graph.directions.iter().map(|&d| d & REACHED != 0).collect();
assert_eq!(reached, reference(&o.columns, from, 6), "{seed} {from:?}");
hidden += reached.iter().filter(|&&r| !r).count();
}
}
assert!(hidden > 1000, "the worlds hide sections ({hidden})");
}
/// The worker's graph is the one the render thread would compute.
#[test]
fn the_worker_matches_a_search_on_the_render_thread() {
let mut o = Occlusion::new(6);
random_world(&mut o, 0x9e37_79b9, 800);
for from in [(0, 2, 0), (3, 0, -2), (-5, 5, 4)] {
o.settle(from, 6);
o.settle(from, 6);
let mut local = Graph::default();
local.search(&o.columns, from, 6, &mut Vec::new(), &mut VecDeque::new());
let graph = o.graph.as_ref().expect("searched");
assert_eq!(graph.directions, local.directions);
assert_eq!(graph.entered, local.entered);
}
}
}
+6 -1
View File
@@ -14,8 +14,13 @@ pub struct Uploads {
impl Uploads {
pub fn new(device: &wgpu::Device) -> Self {
Self::with_chunk(device, CHUNK)
}
/// A belt whose staging buffers hold `chunk` bytes (larger writes get
/// a buffer of their own).
pub fn with_chunk(device: &wgpu::Device, chunk: u64) -> Self {
Self {
belt: wgpu::util::StagingBelt::new(device.clone(), CHUNK),
belt: wgpu::util::StagingBelt::new(device.clone(), chunk),
}
}
/// Copy tightly packed RGBA8 `pixels` (`width` by `height`) into one mip
+28 -12
View File
@@ -110,6 +110,16 @@ pub const OMINOUS_LAYERS: [(&str, &str); 8] = [
("circle", "light_gray"),
("border", "black"),
];
/// The raid captain banner's default tooltip setting, stored by vanilla as a
/// component but represented by `StackData::ominous_banner` in Horizon.
fn ominous_tooltip_display() -> Tag {
Tag::compound([(
"hidden_components",
Tag::List(vec![Tag::String("minecraft:banner_patterns".into())]),
)])
}
/// `WrittenBookContent` with the pages as plain text.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct WrittenBook {
@@ -610,13 +620,9 @@ pub fn components_tag(damage: u32, data: Option<&StackData>) -> Option<Tag> {
"minecraft:banner_patterns",
Tag::List(OMINOUS_LAYERS.iter().map(|(p, c)| layer(p, c)).collect()),
));
entries.push((
"minecraft:tooltip_display",
Tag::compound([(
"hidden_components",
Tag::List(vec![Tag::String("minecraft:banner_patterns".into())]),
)]),
));
if d.other("minecraft:tooltip_display").is_none() {
entries.push(("minecraft:tooltip_display", ominous_tooltip_display()));
}
entries.push((
"minecraft:item_name",
Tag::compound([(
@@ -793,10 +799,8 @@ pub fn decode_components(components: Option<&Tag>) -> (u32, Option<Box<StackData
for (k, v) in map {
let key = k.to_string_lossy();
let ominous_part = data.ominous_banner
&& matches!(
key.as_str(),
"minecraft:item_name" | "minecraft:rarity" | "minecraft:tooltip_display"
);
&& (matches!(key.as_str(), "minecraft:item_name" | "minecraft:rarity")
|| (key == "minecraft:tooltip_display" && v == &ominous_tooltip_display()));
if !MODELLED.contains(&key.as_str()) && !ominous_part {
data.other.push((key, v.clone()));
}
@@ -882,7 +886,19 @@ mod tests {
let tag = encode_components(&banner).unwrap();
assert!(tag.get("minecraft:banner_patterns").is_some());
let (_, back) = decode_components(Some(&tag));
assert!(back.unwrap().ominous_banner);
let back = back.unwrap();
assert!(back.ominous_banner);
assert!(back.other("minecraft:tooltip_display").is_none());
banner.data_mut().set_other(
"minecraft:tooltip_display",
Some(Tag::Compound(Default::default())),
);
let (_, custom_display) = decode_components(encode_components(&banner).as_ref());
assert_eq!(
custom_display.unwrap().other("minecraft:tooltip_display"),
Some(&Tag::Compound(Default::default()))
);
let mut bottle = ItemStack::new("minecraft:ominous_bottle", 1);
bottle.data_mut().ominous_amplifier = Some(3);
let (_, back) = decode_components(encode_components(&bottle).as_ref());
+101
View File
@@ -4,6 +4,64 @@ use crate::{
hud::rgba,
items::{ItemInfo, ItemStack},
};
use horizon_world::nbt::Tag;
/// The `minecraft:tooltip_display` component applied by `ItemStack` while it
/// builds a hover tooltip.
pub struct TooltipDisplay<'a> {
component: Option<&'a Tag>,
ominous_banner: bool,
}
impl<'a> TooltipDisplay<'a> {
pub fn for_stack(stack: &'a ItemStack) -> Self {
Self {
component: stack
.data()
.and_then(|data| data.other("minecraft:tooltip_display")),
ominous_banner: stack.data().is_some_and(|data| data.ominous_banner),
}
}
fn hides_tooltip(&self) -> bool {
matches!(
self.component.and_then(|display| display.get("hide_tooltip")),
Some(Tag::Byte(value)) if *value != 0
)
}
/// `ItemStack.getTooltipLines`: `hide_tooltip` suppresses the name unless
/// the tooltip flag is creative.
pub fn name_visible(&self, creative: bool) -> bool {
creative || !self.hides_tooltip()
}
/// `TooltipDisplay.shows`: whether details for a data component are shown.
pub fn shows(&self, component: &str) -> bool {
if self.hides_tooltip() {
return false;
}
// `item_data::decode_components` models the raid captain banner's
// default hidden pattern tooltip as `ominous_banner` instead of
// retaining its redundant `tooltip_display` component.
if self.ominous_banner
&& self.component.is_none()
&& component == "minecraft:banner_patterns"
{
return false;
}
let Some(Tag::List(hidden)) = self
.component
.and_then(|display| display.get("hidden_components"))
else {
return true;
};
let component = horizon_world::nbt::JavaString::from(component);
!hidden
.iter()
.any(|tag| matches!(tag, Tag::String(id) if id == &component))
}
}
/// `EquipmentSlotGroup` in declaration order, the order tooltips list them in.
const SLOT_GROUPS: [&str; 11] = [
@@ -348,6 +406,49 @@ pub fn lines(
mod tests {
use super::*;
#[test]
fn tooltip_display_controls_name_and_component_visibility() {
let mut stack = ItemStack::new("minecraft:diamond_sword", 1);
let display = TooltipDisplay::for_stack(&stack);
assert!(display.name_visible(false));
assert!(display.shows("minecraft:attribute_modifiers"));
stack.data_mut().set_other(
"minecraft:tooltip_display",
Some(Tag::compound([(
"hidden_components",
Tag::List(vec![Tag::String("minecraft:attribute_modifiers".into())]),
)])),
);
let display = TooltipDisplay::for_stack(&stack);
assert!(display.name_visible(false));
assert!(!display.shows("minecraft:attribute_modifiers"));
assert!(display.shows("minecraft:enchantments"));
stack.data_mut().set_other(
"minecraft:tooltip_display",
Some(Tag::compound([("hide_tooltip", Tag::Byte(1))])),
);
let display = TooltipDisplay::for_stack(&stack);
assert!(!display.name_visible(false));
assert!(display.name_visible(true));
assert!(!display.shows("minecraft:attribute_modifiers"));
}
#[test]
fn ominous_banner_keeps_its_default_hidden_pattern_tooltip() {
let mut banner = crate::mobs::raider::ominous_banner();
let display = TooltipDisplay::for_stack(&banner);
assert!(!display.shows("minecraft:banner_patterns"));
banner.data_mut().set_other(
"minecraft:tooltip_display",
Some(Tag::Compound(Default::default())),
);
let display = TooltipDisplay::for_stack(&banner);
assert!(display.shows("minecraft:banner_patterns"));
}
#[test]
fn ominous_banner_name_and_rarity_use_the_stack() {
let translate = |key: &str| match key {
+124
View File
@@ -39,6 +39,25 @@ pub struct ToolRule {
pub speed: Option<f32>,
pub correct: Option<bool>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct ConsumeEffectSpec {
pub id: String,
pub duration: i32,
pub amplifier: i32,
}
#[derive(Clone, Debug, PartialEq)]
pub enum ConsumeEffect {
ApplyEffects {
effects: Vec<ConsumeEffectSpec>,
probability: f32,
},
ClearAllEffects,
RemoveEffects(Vec<String>),
TeleportRandomly,
PlaySound(String),
}
#[derive(Clone, Debug)]
pub struct ItemInfo {
pub fire_resistant: bool,
@@ -49,7 +68,9 @@ pub struct ItemInfo {
pub tool: Vec<ToolRule>,
pub tool_default_speed: f32,
pub food: Option<(u32, f32)>,
pub can_always_eat: bool,
pub consumable: bool,
pub consume_effects: Vec<ConsumeEffect>,
pub model: String,
/// Main-hand `attack_damage` / `attack_speed` modifier amounts.
pub attack_damage: f32,
@@ -421,6 +442,79 @@ impl Items {
f["saturation"].as_f64().unwrap_or(0.0) as f32,
)
});
let can_always_eat = c
.get("minecraft:food")
.and_then(|f| f.get("can_always_eat"))
.and_then(|v| v.as_bool())
.unwrap_or(false);
let mut consume_effects = Vec::new();
if let Some(effects) = c
.get("minecraft:consumable")
.and_then(|cons| cons.get("on_consume_effects"))
.and_then(|e| e.as_array())
{
for effect in effects {
match effect.get("type").and_then(|t| t.as_str()) {
Some("minecraft:apply_effects") => {
let probability = effect
.get("probability")
.and_then(|p| p.as_f64())
.map_or(1.0, |p| p as f32);
let mut specs = Vec::new();
if let Some(list) = effect.get("effects").and_then(|l| l.as_array()) {
for e in list {
if let Some(id) = e.get("id").and_then(|i| i.as_str()) {
let duration =
e.get("duration").and_then(|d| d.as_i64()).unwrap_or(0)
as i32;
let amplifier = e
.get("amplifier")
.and_then(|a| a.as_i64())
.unwrap_or(0)
as i32;
specs.push(ConsumeEffectSpec {
id: id.to_string(),
duration,
amplifier,
});
}
}
}
consume_effects.push(ConsumeEffect::ApplyEffects {
effects: specs,
probability,
});
}
Some("minecraft:clear_all_effects") => {
consume_effects.push(ConsumeEffect::ClearAllEffects);
}
Some("minecraft:remove_effects") => {
let mut targets = Vec::new();
if let Some(eff) = effect.get("effects") {
if let Some(s) = eff.as_str() {
targets.push(s.to_string());
} else if let Some(arr) = eff.as_array() {
for item in arr {
if let Some(s) = item.as_str() {
targets.push(s.to_string());
}
}
}
}
consume_effects.push(ConsumeEffect::RemoveEffects(targets));
}
Some("minecraft:teleport_randomly") => {
consume_effects.push(ConsumeEffect::TeleportRandomly);
}
Some("minecraft:play_sound") => {
if let Some(sound) = effect.get("sound").and_then(|s| s.as_str()) {
consume_effects.push(ConsumeEffect::PlaySound(sound.to_string()));
}
}
_ => {}
}
}
}
items.insert(
id.clone(),
ItemInfo {
@@ -435,7 +529,9 @@ impl Items {
.as_f64()
.unwrap_or(1.0) as f32,
food,
can_always_eat,
consumable: c.get("minecraft:consumable").is_some(),
consume_effects,
model: c["minecraft:item_model"]
.as_str()
.unwrap_or(name)
@@ -1496,6 +1592,34 @@ mod tests {
.is_empty()
);
}
#[test]
fn always_edible_and_consume_effects_loaded() {
let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../.local/horizon-client/26.3");
if !root.join("items.json").exists() {
return;
}
let assets = crate::assets::Assets::load(&root).unwrap();
let facts = crate::blocks::BlockFacts::load(&root, assets.registry).unwrap();
let items = Items::load(&root, assets.registry, &facts).unwrap();
let apple = items.get("minecraft:golden_apple").expect("golden apple");
assert!(apple.can_always_eat);
assert!(apple.food.is_some());
assert!(!apple.consume_effects.is_empty());
let enchanted = items
.get("minecraft:enchanted_golden_apple")
.expect("enchanted golden apple");
assert!(enchanted.can_always_eat);
assert!(enchanted.food.is_some());
assert!(!enchanted.consume_effects.is_empty());
let beef = items.get("minecraft:cooked_beef").expect("cooked beef");
assert!(!beef.can_always_eat);
assert!(beef.food.is_some());
}
}
pub fn take_held_drop(slot: &mut Option<ItemStack>, all: bool) -> Option<ItemStack> {
+27
View File
@@ -480,6 +480,33 @@ impl ChunkEncoder {
w.data
}
/// ClientboundLightUpdatePacket for the light sections over `changed` (a
/// bit per section of the column, `sectionLightChanged`), as vanilla's
/// `ClientboundLightUpdatePacketData` writes them, with both kinds of
/// each section (Horizon's light engine doesn't tell them apart; the
/// client keeps the same light either way). A section changed as its
/// last block went (light dimming around a removed block) is sent too:
/// a client not tracking the block would otherwise keep its old light.
pub fn light_update(&self, chunk: &Chunk, changed: u32) -> Vec<u8> {
let first = self.sections.start;
let lights: Vec<(usize, SectionLight)> = self
.light_sections(chunk, u64::MAX)
.into_iter()
.filter(|&(b, _)| {
// Light section b holds the column's section first + b - 1.
(1..=self.sections.len()).contains(&b) && changed >> (first + b - 1) & 1 != 0
})
.collect();
horizon_protocol::packets::play::Clientbound::LightUpdate(
horizon_protocol::packets::play::LightUpdate {
x: chunk.x,
z: chunk.z,
light: light_data_of(&lights, self.sky),
},
)
.encode()
}
pub fn encode(
&self,
chunk: &Chunk,
+229 -51
View File
@@ -11,7 +11,7 @@ use horizon_protocol::{
packets::play::{
self, AddEntity, EntityPositionSync, MoveEntity, MoveEntityPos, MoveEntityPosRot,
MoveEntityRot, PositionPath, RotateHead, SetEntityData, SetEntityMotion, SetEquipment,
VecDelta,
SetPassengers, VecDelta,
},
};
@@ -35,6 +35,30 @@ pub struct EntityState {
/// EquipmentSlot ordinals (0 main hand, 1 off hand, 2 feet, 3 legs,
/// 4 chest, 5 head, 6 body, 7 saddle) and their stacks.
pub equipment: Vec<(u8, Option<Stack>)>,
/// `Entity.getRequiresPrecisePosition` (primed TNT and falling blocks
/// touching a block): moves are sent as full position syncs.
pub precise: bool,
}
/// `AbstractArrow`: every update sends its position and rotation.
fn is_arrow(kind: &str) -> bool {
matches!(
kind,
"minecraft:arrow" | "minecraft:spectral_arrow" | "minecraft:trident"
)
}
/// `AbstractHurtingProjectile.accelerationPower` (0.1, none for wind
/// charges), sent with each velocity update.
fn acceleration_power(kind: &str) -> Option<f64> {
match kind {
"minecraft:fireball"
| "minecraft:small_fireball"
| "minecraft:dragon_fireball"
| "minecraft:wither_skull" => Some(0.1),
"minecraft:wind_charge" | "minecraft:breeze_wind_charge" => Some(0.0),
_ => None,
}
}
/// What a client was last told about one entity (ServerEntity's fields).
@@ -54,6 +78,40 @@ struct Sent {
/// The type's update interval (0: never) and whether velocity is tracked.
interval: u32,
track_deltas: bool,
/// lastPassengers, and wasRiding: a passenger's position isn't synced,
/// and the first update after it dismounts is a full position sync.
passengers: Vec<i32>,
was_riding: bool,
}
/// Who rides what this tick (`Entity.getPassengers`, `isPassenger`).
#[derive(Default)]
pub struct Riding {
/// Each vehicle's passengers, in order.
pub passengers: crate::fast_hash::FxHashMap<i32, Vec<i32>>,
/// Each passenger's vehicle.
pub vehicle: crate::fast_hash::FxHashMap<i32, i32>,
}
impl Riding {
pub fn clear(&mut self) {
self.passengers.clear();
self.vehicle.clear();
}
/// `passenger` rides `vehicle`, after the ones already riding it.
pub fn add(&mut self, vehicle: i32, passenger: i32) {
self.passengers.entry(vehicle).or_default().push(passenger);
self.vehicle.insert(passenger, vehicle);
}
pub fn passengers(&self, id: i32) -> &[i32] {
self.passengers.get(&id).map_or(&[], Vec::as_slice)
}
fn set_passengers(&self, vehicle: i32) -> play::Clientbound {
play::Clientbound::SetPassengers(SetPassengers {
vehicle,
passengers: self.passengers(vehicle).to_vec(),
})
}
}
#[derive(Default)]
@@ -94,7 +152,12 @@ impl Tracker {
}
/// The packets that introduce an entity (ServerEntity.sendPairingData).
pub fn spawn(&mut self, e: &EntityState, entity_type: i32) -> Vec<play::Clientbound> {
pub fn spawn(
&mut self,
e: &EntityState,
entity_type: i32,
riding: &Riding,
) -> Vec<play::Clientbound> {
let rotation = (pack_degrees(e.pitch), pack_degrees(e.yaw));
let head = pack_degrees(e.head_yaw);
let (_, interval, track_deltas) = tracking::settings(&e.kind);
@@ -121,6 +184,13 @@ impl Tracker {
slots: e.equipment.clone(),
}));
}
let passengers = riding.passengers(e.id).to_vec();
if !passengers.is_empty() {
out.push(riding.set_passengers(e.id));
}
if let Some(&vehicle) = riding.vehicle.get(&e.id) {
out.push(riding.set_passengers(vehicle));
}
self.sent.insert(
e.id,
Sent {
@@ -135,6 +205,8 @@ impl Tracker {
teleport_delay: 0,
interval,
track_deltas,
passengers,
was_riding: false,
},
);
out
@@ -144,20 +216,48 @@ impl Tracker {
/// rotation every update interval (positions at least every 60 ticks, a
/// full position sync every 400 or when the entity lands or leaves the
/// ground), velocity for types that track it, changed data at once.
pub fn update(&mut self, e: &EntityState) -> Vec<play::Clientbound> {
pub fn update(&mut self, e: &EntityState, riding: &Riding) -> Vec<play::Clientbound> {
let Some(s) = self.sent.get_mut(&e.id) else {
return Vec::new();
};
let mut out = Vec::new();
let passengers = riding.passengers(e.id);
if passengers != s.passengers.as_slice() {
out.push(riding.set_passengers(e.id));
s.passengers = passengers.to_vec();
}
let dirty = e.meta != s.meta;
let due = s.interval != 0 && s.tick.is_multiple_of(s.interval);
if due || dirty {
let rotation = (pack_degrees(e.pitch), pack_degrees(e.yaw));
let turned = |a: i8, b: i8| (i32::from(a) - i32::from(b)).abs() >= 1;
let rotate = turned(rotation.1, s.rotation.1) || turned(rotation.0, s.rotation.0);
let arrow = is_arrow(&e.kind);
let rotate =
arrow || turned(rotation.1, s.rotation.1) || turned(rotation.0, s.rotation.0);
if riding.vehicle.contains_key(&e.id) {
// A passenger: its rotation alone (its vehicle places it).
if rotate {
out.push(play::Clientbound::MoveEntityRot(MoveEntityRot(
MoveEntity {
id: e.id,
delta: None,
rotation: Some((rotation.1, rotation.0)),
on_ground: e.on_ground,
},
)));
s.rotation = rotation;
}
s.base = e.position;
s.was_riding = true;
Self::send_dirty(e, s, dirty, &mut out);
Self::send_head(e, s, &mut out);
s.tick += 1;
Self::send_equipment(e, s, &mut out);
return out;
}
s.teleport_delay += 1;
let d: f64 = (0..3).map(|k| (e.position[k] - s.base[k]).powi(2)).sum();
let send_position = d >= 7.629_394_5e-6 || s.tick.is_multiple_of(60);
let send_position = arrow || d >= 7.629_394_5e-6 || s.tick.is_multiple_of(60);
let sync = EntityPositionSync {
id: e.id,
path: PositionPath::Linear(e.position),
@@ -166,9 +266,14 @@ impl Tracker {
on_ground: e.on_ground,
};
// ServerEntity.createMovePacket.
let packet = if s.teleport_delay > 400 || s.was_on_ground != e.on_ground {
let packet = if e.precise
|| s.teleport_delay > 400
|| s.was_riding
|| s.was_on_ground != e.on_ground
{
s.was_on_ground = e.on_ground;
s.teleport_delay = 0;
s.was_riding = false;
Some(play::Clientbound::EntityPositionSync(sync))
} else if send_position {
let delta = [0, 1, 2].map(|k| encode(e.position[k]) - encode(s.base[k]));
@@ -206,10 +311,23 @@ impl Tracker {
let still = e.velocity.iter().all(|v| *v == 0.0);
if diff > 1.0e-7 || diff > 0.0 && still {
s.velocity = e.velocity;
out.push(play::Clientbound::SetEntityMotion(SetEntityMotion {
let motion = play::Clientbound::SetEntityMotion(SetEntityMotion {
id: e.id,
velocity: e.velocity,
}));
});
match acceleration_power(&e.kind) {
// A bundle: the motion and the projectile's power.
Some(power) => out.extend([
play::Clientbound::BundleDelimiter(horizon_protocol::packets::Empty),
motion,
play::Clientbound::ProjectilePower(play::ProjectilePower {
id: e.id,
power,
}),
play::Clientbound::BundleDelimiter(horizon_protocol::packets::Empty),
]),
None => out.push(motion),
}
}
}
if let Some(packet) = packet {
@@ -227,33 +345,47 @@ impl Tracker {
s.rotation = rotation;
}
}
// ServerEntity.sendDirtyEntityData.
if dirty {
let changed: Vec<_> = e
.meta
.iter()
.filter(|m| !s.meta.contains(m))
.cloned()
.collect();
if !changed.is_empty() {
out.push(play::Clientbound::SetEntityData(SetEntityData {
id: e.id,
values: changed,
}));
}
s.meta = e.meta.clone();
}
let head = pack_degrees(e.head_yaw);
if turned(head, s.head) {
out.push(play::Clientbound::RotateHead(RotateHead {
id: e.id,
head_yaw: head,
}));
s.head = head;
}
Self::send_dirty(e, s, dirty, &mut out);
Self::send_head(e, s, &mut out);
}
s.tick += 1;
// LivingEntity.detectEquipmentUpdates: changed slots every tick.
Self::send_equipment(e, s, &mut out);
out
}
/// ServerEntity.sendDirtyEntityData.
fn send_dirty(e: &EntityState, s: &mut Sent, dirty: bool, out: &mut Vec<play::Clientbound>) {
if !dirty {
return;
}
let changed: Vec<_> = e
.meta
.iter()
.filter(|m| !s.meta.contains(m))
.cloned()
.collect();
if !changed.is_empty() {
out.push(play::Clientbound::SetEntityData(SetEntityData {
id: e.id,
values: changed,
}));
}
s.meta = e.meta.clone();
}
fn send_head(e: &EntityState, s: &mut Sent, out: &mut Vec<play::Clientbound>) {
let head = pack_degrees(e.head_yaw);
if (i32::from(head) - i32::from(s.head)).abs() >= 1 {
out.push(play::Clientbound::RotateHead(RotateHead {
id: e.id,
head_yaw: head,
}));
s.head = head;
}
}
/// LivingEntity.detectEquipmentUpdates: changed slots every tick.
fn send_equipment(e: &EntityState, s: &mut Sent, out: &mut Vec<play::Clientbound>) {
if e.equipment != s.equipment {
// Cleared slots are sent as empty stacks.
let mut slots: Vec<(u8, Option<Stack>)> = e
@@ -275,7 +407,6 @@ impl Tracker {
}
s.equipment = e.equipment.clone();
}
out
}
}
@@ -297,44 +428,91 @@ mod tests {
data: 0,
meta: Vec::new(),
equipment: Vec::new(),
precise: false,
}
}
#[test]
fn moves_go_out_every_update_interval() {
let mut t = Tracker::default();
let spawn = t.spawn(&state(0.0), 100);
let spawn = t.spawn(&state(0.0), 100, &Riding::default());
assert!(matches!(spawn[0], play::Clientbound::AddEntity(_)));
// Tick 0 is due and a multiple of 60: the position goes out unchanged.
assert!(matches!(
t.update(&state(0.0))[..],
t.update(&state(0.0), &Riding::default())[..],
[play::Clientbound::MoveEntityPos(_)]
));
// A zombie updates every third tick.
assert!(t.update(&state(0.5)).is_empty());
assert!(t.update(&state(0.5)).is_empty());
assert!(t.update(&state(0.5), &Riding::default()).is_empty());
assert!(t.update(&state(0.5), &Riding::default()).is_empty());
assert!(matches!(
t.update(&state(0.5))[..],
t.update(&state(0.5), &Riding::default())[..],
[play::Clientbound::MoveEntityPos(_)]
));
for _ in 0..2 {
t.update(&state(40.0));
t.update(&state(40.0), &Riding::default());
}
let jump = t.update(&state(40.0));
let jump = t.update(&state(40.0), &Riding::default());
assert!(matches!(jump[0], play::Clientbound::EntityPositionSync(_)));
}
#[test]
fn fireballs_bundle_their_motion_with_their_power() {
let mut t = Tracker::default();
let mut e = state(0.0);
e.kind = "minecraft:fireball".into();
e.on_ground = false;
t.spawn(&e, 100, &Riding::default());
e.velocity = [0.0, 0.0, 0.5];
let out = t.update(&e, &Riding::default());
assert!(matches!(
out[..],
[
play::Clientbound::BundleDelimiter(_),
play::Clientbound::SetEntityMotion(_),
play::Clientbound::ProjectilePower(play::ProjectilePower { power, .. }),
play::Clientbound::BundleDelimiter(_),
play::Clientbound::MoveEntityPos(_),
] if power == 0.1
));
}
#[test]
fn arrows_send_position_and_rotation_every_update() {
let mut t = Tracker::default();
let mut e = state(0.0);
e.kind = "minecraft:arrow".into();
t.spawn(&e, 100, &Riding::default());
assert!(matches!(
t.update(&e, &Riding::default())[..],
[play::Clientbound::MoveEntityPosRot(_)]
));
}
#[test]
fn precise_entities_sync_their_position() {
let mut t = Tracker::default();
let mut e = state(0.0);
e.kind = "minecraft:tnt".into();
e.precise = true;
t.spawn(&e, 100, &Riding::default());
assert!(matches!(
t.update(&e, &Riding::default())[..],
[play::Clientbound::EntityPositionSync(_)]
));
}
#[test]
fn landing_sends_a_position_sync() {
let mut t = Tracker::default();
let mut e = state(0.0);
t.spawn(&e, 100);
t.update(&e);
t.spawn(&e, 100, &Riding::default());
t.update(&e, &Riding::default());
e.on_ground = false;
t.update(&e);
t.update(&e);
t.update(&e, &Riding::default());
t.update(&e, &Riding::default());
assert!(matches!(
t.update(&e)[..],
t.update(&e, &Riding::default())[..],
[play::Clientbound::EntityPositionSync(_)]
));
}
@@ -343,11 +521,11 @@ mod tests {
fn metadata_and_equipment_send_only_the_changes() {
let mut t = Tracker::default();
let mut e = state(0.0);
t.spawn(&e, 100);
t.update(&e);
t.spawn(&e, 100, &Riding::default());
t.update(&e, &Riding::default());
e.meta.push((0, 0, Value::Byte(1)));
e.equipment.push((0, Some(Stack::new(5, 1))));
let out = t.update(&e);
let out = t.update(&e, &Riding::default());
assert!(
out.iter()
.any(|p| matches!(p, play::Clientbound::SetEntityData(_)))
@@ -356,9 +534,9 @@ mod tests {
out.iter()
.any(|p| matches!(p, play::Clientbound::SetEquipment(_)))
);
assert!(t.update(&e).is_empty());
assert!(t.update(&e, &Riding::default()).is_empty());
e.equipment.clear();
let out = t.update(&e);
let out = t.update(&e, &Riding::default());
let Some(play::Clientbound::SetEquipment(eq)) = out.first() else {
panic!("expected equipment");
};
+23 -1
View File
@@ -37,6 +37,12 @@ pub struct Guest {
pub last_action_tick: u64,
/// The next ClientboundPlayerChatPacket.globalIndex for this connection.
pub chat_index: i32,
/// Secure chat (ServerGamePacketListenerImpl): the player's message
/// chain, keyed once it sends a chat session; the messages its
/// acknowledgements cover; the signatures its client caches.
pub chain: horizon_protocol::secure_chat::Chain,
pub last_seen: horizon_protocol::secure_chat::LastSeenValidator,
pub signatures: horizon_protocol::secure_chat::SignatureCache,
/// The hub tick the player was placed on: chunks go out from the tick
/// after next, behind the first doTick's packets, as vanilla's do.
pub placed_at: u64,
@@ -69,6 +75,14 @@ pub struct Guest {
pub fall_flying: bool,
pub flying: bool,
pub sleeping: bool,
/// The bed (its head) the player sleeps in (`LivingEntity.getSleepingPos`),
/// `Player.sleepCounter`, and the bed last told to the player itself.
pub bed: Option<[i32; 3]>,
pub sleep_timer: u32,
pub sent_bed: Option<[i32; 3]>,
/// Where the player respawns (a bed's spot; `ServerPlayer.respawnConfig`),
/// None for the world spawn.
pub spawn: Option<[f64; 3]>,
/// Pending ClientboundPlayerPositionPacket id; movement is ignored until
/// the client accepts it (ServerGamePacketListenerImpl.awaitingPositionFromClient).
pub awaiting_teleport: Option<(i32, [f64; 3])>,
@@ -129,7 +143,8 @@ pub struct Guest {
/// What the client believes the inventory menu holds (for change detection).
pub menu_sent: Vec<Option<ItemStack>>,
pub menu_state: i32,
pub sent_health: Option<(f32, i32, f32)>,
/// `lastSentHealth`, `lastSentFood` and `lastFoodSaturationZero`.
pub sent_health: Option<(f32, i32, bool)>,
pub sent_xp: Option<(f32, i32, i32)>,
/// Where the player last died (Player.lastDeathLocation), sent with the respawn.
pub last_death: Option<[i32; 3]>,
@@ -179,6 +194,9 @@ impl Guest {
address: j.address,
last_action_tick: 0,
chat_index: 0,
chain: Default::default(),
last_seen: Default::default(),
signatures: Default::default(),
placed_at: 0,
center_sent: None,
left_reason: String::new(),
@@ -204,6 +222,10 @@ impl Guest {
fall_flying: false,
flying: false,
sleeping: false,
bed: None,
sleep_timer: 0,
sent_bed: None,
spawn: None,
awaiting_teleport: None,
teleport_counter: 0,
teleport_tick: 0,
+153 -73
View File
@@ -33,6 +33,8 @@ use horizon_world::{
use std::sync::{Arc, atomic::Ordering};
/// GameEvent types (ClientboundGameEventPacket).
pub mod chat;
pub mod game_event {
pub const START_RAINING: u8 = 1;
pub const STOP_RAINING: u8 = 2;
@@ -108,10 +110,16 @@ pub enum HostEvent {
/// A guest left (state to save, entities to drop).
Left(Box<Guest>),
Packet(u32, Box<S>),
/// A chat line to show on the host (already broadcast to the guests).
Chat(String),
/// A chat line to show on the host (already broadcast to the guests);
/// a dedicated server logs it, `[Not Secure]` unless signed and fresh.
Chat {
line: String,
secure: bool,
},
/// A server log warning (ServerGamePacketListenerImpl's LOGGER.warn).
Warn(String),
/// A server log error (LOGGER.error).
Error(String),
}
pub struct Hub {
@@ -124,6 +132,8 @@ pub struct Hub {
/// The `player_movement_check` and `elytra_movement_check` game rules,
/// set by the game before each tick.
pub movement_checks: (bool, bool),
/// Who rides what, set by the game before each tick.
pub riding: super::entity::Riding,
last_clock: i64,
last_rate: f32,
ticking: (f32, bool),
@@ -237,6 +247,7 @@ impl Hub {
sync,
ticks: 0,
movement_checks: (true, true),
riding: Default::default(),
last_clock: i64::MIN,
last_rate: 0.0,
ticking: (20.0, false),
@@ -296,6 +307,22 @@ impl Hub {
g.sender.send(body.clone());
}
}
/// PlayerList.setViewDistance: every player is told the new radius,
/// and each one's chunks follow it, up to what they asked for
/// (ChunkMap.getPlayerViewDistance).
pub fn set_view_distance(&mut self, distance: i32) {
self.config.view_distance = distance;
self.broadcast(&C::SetChunkCacheRadius(play::Distance { distance }));
for g in &mut self.guests {
g.view_distance = i32::from(g.info.view_distance).clamp(2, distance);
g.center = None;
}
}
/// PlayerList.setSimulationDistance.
pub fn set_simulation_distance(&mut self, distance: i32) {
self.config.simulation_distance = distance;
self.broadcast(&C::SetSimulationDistance(play::Distance { distance }));
}
/// Whether a guest is placed in the level in place (`config.dimension`).
pub fn here(&self, g: &Guest) -> bool {
g.placed && g.dimension == self.config.dimension
@@ -408,56 +435,23 @@ impl Hub {
},
}));
}
/// PlayerList.broadcastChatMessage of a guest's unsigned message
/// (PlayerChatMessage.unsigned): a ClientboundPlayerChatPacket to every
/// player, each connection numbering its messages.
pub fn player_chat(&mut self, from: usize, text: &str) {
let (uuid, name) = (self.guests[from].uuid, self.guests[from].name.clone());
let timestamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_millis() as i64);
let bound = play::ChatTypeBound {
chat_type: self.chat_type,
name: display_name(uuid, &name),
target: None,
};
for g in self.guests.iter_mut().filter(|g| g.placed) {
let packet = C::PlayerChat(play::PlayerChat {
global_index: g.chat_index,
sender: uuid,
index: 0,
signature: None,
content: text.to_owned(),
timestamp,
salt: 0,
last_seen: Vec::new(),
unsigned_content: None,
filter: (0, Vec::new()),
chat_type: bound.clone(),
});
g.chat_index += 1;
g.send(&packet);
}
}
/// Disconnect a guest with a reason (ServerGamePacketListenerImpl.disconnect).
pub fn kick(&mut self, conn: u32, reason: Tag) {
if let Some(g) = self.guest(conn) {
// The log's "lost connection" line gives the reason, as vanilla's.
let text = self.english(&reason);
if let Some(g) = self.guest_mut(conn) {
g.left_reason = text;
g.sender.disconnect(reason);
}
}
fn player_info(&self, uuid: u128, name: &str, mode: i32, latency: i32) -> play::PlayerInfo {
let guest = self.guests.iter().find(|g| g.uuid == uuid);
play::PlayerInfo {
uuid,
name: Some(name.to_owned()),
properties: self
.guests
.iter()
.find(|g| g.uuid == uuid)
.map(|g| g.properties.clone())
.unwrap_or_default(),
chat_session: None,
properties: guest.map(|g| g.properties.clone()).unwrap_or_default(),
chat_session: guest.and_then(|g| g.chain.session()).map(|s| s.data()),
game_mode: Some(mode),
listed: Some(true),
latency: Some(latency),
@@ -550,8 +544,9 @@ impl Hub {
show_death_screen: true,
limited_crafting: false,
spawn: self.spawn_info(mode),
online_mode: false,
enforces_secure_chat: false,
// MinecraftServer.usesAuthentication, enforceSecureProfile.
online_mode: self.lan.shared.config.online.is_some(),
enforces_secure_chat: self.enforces_secure_chat(),
}));
g.send(&C::ChangeDifficulty(play::ChangeDifficulty {
difficulty: ctx.difficulty,
@@ -993,18 +988,23 @@ impl Hub {
.any(|g| g.dimension == self.config.dimension)
{
let _ = ctx.world.block_log.take();
let _ = ctx.world.light_log.take();
}
return events;
}
if ctx.world.block_log.is_none() {
ctx.world.block_log = Some(Vec::new());
}
if ctx.world.light_log.is_none() {
ctx.world.light_log = Some(Default::default());
}
self.sync_world(ctx);
for i in 0..self.guests.len() {
if self.here(&self.guests[i]) {
self.update_chunks(i, ctx);
}
}
self.broadcast_light_changes(ctx.world);
self.broadcast_block_changes(ctx.world);
// ServerGamePacketListenerImpl.tick: the actions handled since the last tick are
// acknowledged after the block changes they made were sent, so a client's predicted
@@ -1053,7 +1053,9 @@ impl Hub {
fn remove_guest(&mut self, i: usize, reason: &str) -> Guest {
let mut g = self.guests.remove(i);
g.left_reason = reason.to_owned();
if g.left_reason.is_empty() {
g.left_reason = reason.to_owned();
}
if std::env::var_os("HORIZON_NET_DEBUG").is_some() {
log::info!("[lan] {} left: {reason}", g.name);
}
@@ -1237,6 +1239,42 @@ impl Hub {
}
}
/// `ChunkHolder.broadcastChanges`' light part: the light sections that
/// changed in a column go to the players for whom it is on the border of
/// what they track (`ChunkMap.isChunkOnTrackedBorder`); the others light
/// the blocks they are sent themselves.
fn broadcast_light_changes(&mut self, world: &mut World) {
let Some(log) = world.light_log.as_mut() else {
return;
};
if log.is_empty() {
return;
}
let mut changes: Vec<((i32, i32), u32)> = log.drain().collect();
changes.sort_unstable();
for ((x, z), sections) in changes {
let tracked = |g: &Guest, x: i32, z: i32| g.sent_chunks.contains(&(x, z));
let viewers: Vec<usize> = (0..self.guests.len())
.filter(|&i| {
let g = &self.guests[i];
self.here(g)
&& tracked(g, x, z)
&& (-1..=1).any(|dz| (-1..=1).any(|dx| !tracked(g, x + dx, z + dz)))
})
.collect();
if viewers.is_empty() {
continue;
}
let Some(chunk) = world.chunks.get(&(x, z)) else {
continue;
};
let body = self.encoder.light_update(chunk, sections);
for &i in &viewers {
self.guests[i].sender.send(body.clone());
}
}
}
fn broadcast_block_changes(&mut self, world: &mut World) {
let Some(log) = world.block_log.as_mut() else {
return;
@@ -1375,6 +1413,7 @@ impl Hub {
data: 0,
meta,
equipment,
precise: false,
}
}
@@ -1501,24 +1540,58 @@ impl Hub {
continue;
}
if self.guests[gi].tracker.is_tracking(e.id) {
let packets = self.guests[gi].tracker.update(e);
let packets = self.guests[gi].tracker.update(e, &self.riding);
self.guests[gi].send_all(&packets);
} else if visible(&self.guests[gi], ei) {
let Some(kind) = self.entity_type(&e.kind) else {
continue;
};
// Players need their list entry first; guests got it at join.
let packets = self.guests[gi].tracker.spawn(e, kind);
let packets = self.guests[gi].tracker.spawn(e, kind, &self.riding);
self.guests[gi].send_all(&packets);
}
}
}
}
/// ServerPlayer.stopSleepInBed: the wake-up animation goes to the player
/// and those around, the pose is standing again and the sleep counter
/// starts the wake-up fade (100).
pub fn wake(&mut self, i: usize) {
let g = &mut self.guests[i];
if g.bed.take().is_none() && !g.sleeping {
return;
}
g.sleeping = false;
g.sleep_timer = 100;
let (id, at) = (g.entity_id, g.position);
// ClientboundAnimatePacket.WAKE_UP.
self.broadcast_near(
at,
128.0,
&C::Animate(play::Animate { id, action: 0 }),
None,
);
}
// ---- per-player state ------------------------------------------------
/// ServerPlayer.doTick: health, food, experience and the inventory menu.
fn sync_player_state(&mut self, i: usize) {
// LivingEntity.startSleeping / stopSleeping: the pose and the bed go
// to the player too (its client lies down in the bed from them).
let g = &mut self.guests[i];
if g.bed != g.sent_bed {
g.sent_bed = g.bed;
let pose = if g.bed.is_some() { 2 } else { 0 };
g.send(&C::SetEntityData(play::SetEntityData {
id: g.entity_id,
values: vec![
(6, serializer::POSE, Value::Id(pose)),
(14, serializer::OPTIONAL_BLOCK_POS, Value::OptPos(g.bed)),
],
}));
}
// ServerEntity.sendDirtyEntityData on the player's first tick: the
// health its creation set is still dirty, and goes to the player too.
if self.guests[i].sent_health.is_none() {
@@ -1551,17 +1624,15 @@ impl Hub {
self.flush_advancements(i, true);
}
}
let health = {
let g = &self.guests[i];
(g.health, g.food, g.saturation)
};
// A dead player's health isn't sent (the death screen shows from the combat kill).
if self.guests[i].sent_health != Some(health) && !self.guests[i].dead {
let g = &mut self.guests[i];
// Sent when the health or the food level changes, or the saturation
// reaches or leaves zero; a dead player's health of 0 too.
let g = &mut self.guests[i];
let health = (g.health, g.food, g.saturation == 0.0);
if g.sent_health != Some(health) {
g.send(&C::SetHealth(play::SetHealth {
health: health.0,
food: health.1,
saturation: health.2,
health: g.health,
food: g.food,
saturation: g.saturation,
}));
g.sent_health = Some(health);
}
@@ -1767,17 +1838,13 @@ impl Hub {
1 => self.guests[i].sprinting = true,
2 => self.guests[i].sprinting = false,
6 => self.guests[i].fall_flying = true,
0 => self.guests[i].sleeping = false,
// STOP_SLEEPING.
0 => self.wake(i),
_ => {}
},
S::Chat(c) => {
let text: String = c.message.chars().filter(|c| !c.is_control()).collect();
if !text.is_empty() {
let name = self.guests[i].name.clone();
self.player_chat(i, &text);
events.push(HostEvent::Chat(format!("<{name}> {text}")));
}
}
S::Chat(c) => self.handle_chat(i, c, events),
S::ChatAck(p) => self.chat_ack(i, p.offset, events),
S::ChatSessionUpdate(p) => self.chat_session_update(i, p, events),
other => events.push(HostEvent::Packet(conn, Box::new(other))),
}
}
@@ -2164,7 +2231,15 @@ impl Hub {
/// names (`set_dimension`): ClientboundRespawnPacket keeping all data,
/// then vanilla's packet order. Nothing tracked in the old level is
/// removed one by one: the client drops its whole level.
pub fn change_level(&mut self, i: usize, at: [f64; 3], yaw: f32, ctx: &TickCtx) {
pub fn change_level(
&mut self,
i: usize,
at: [f64; 3],
yaw: f32,
pitch: Option<f32>,
portal_sound: bool,
ctx: &TickCtx,
) {
let mode = self.guests[i].game_mode;
let info = self.spawn_info(mode);
self.close_container_for(i);
@@ -2175,6 +2250,9 @@ impl Hub {
g.chunk_queue.clear();
g.center = None;
g.yaw = yaw;
if let Some(pitch) = pitch {
g.pitch = pitch;
}
g.position = at;
g.previous_position = at;
g.send(&C::Respawn(play::Respawn {
@@ -2206,12 +2284,14 @@ impl Hub {
// ServerPlayer.sendPostEffects.
g.send(&raw(ids::POST_EFFECTS, vec![0]));
// TeleportTransition.PLAY_PORTAL_SOUND.
g.send(&C::LevelEvent(play::LevelEvent {
kind: 1032,
pos: [0, 0, 0],
data: 0,
global: false,
}));
if portal_sound {
g.send(&C::LevelEvent(play::LevelEvent {
kind: 1032,
pos: [0, 0, 0],
data: 0,
global: false,
}));
}
// lastSentExp, lastSentHealth and lastSentFood.
g.sent_health = None;
g.sent_xp = None;
+500
View File
@@ -0,0 +1,500 @@
//! Chat on the server side, as ServerGamePacketListenerImpl and PlayerList
//! handle it: chat sessions validated against the services' keys, signed
//! messages checked link by link, the acknowledged window, and messages
//! relayed with each connection's numbering and signature cache.
use super::{HostEvent, Hub, display_name};
use horizon_protocol::{
packets::play::{self, Clientbound as C},
secure_chat::{self, Body, Chain, ChatSession, DecodeError, ProfileKey, Signature, Unpacked},
text::{literal, translatable},
};
use horizon_world::nbt::{JavaString, Tag};
/// Now, in epoch milliseconds (Instant.now()).
pub fn now_millis() -> i64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_millis() as i64)
}
/// StringUtil.isAllowedChatCharacter.
fn allowed(c: char) -> bool {
c != '\u{a7}' && c >= ' ' && c != '\u{7f}'
}
/// A translatable message in red.
fn red(key: &str) -> Tag {
let mut t = translatable(key, &[]);
if let Tag::Compound(map) = &mut t {
map.insert(
JavaString::from("color"),
Tag::String(JavaString::from("red")),
);
}
t
}
/// PlayerChatMessage as the server relays it.
#[derive(Clone, Debug, PartialEq)]
pub struct ChatMessage {
pub sender: u128,
/// The link's index in the sender's chain (0 when unsigned).
pub index: i32,
pub signature: Option<Signature>,
pub content: String,
/// Epoch milliseconds.
pub timestamp: i64,
pub salt: i64,
pub last_seen: Vec<Signature>,
/// What clients show instead of the signed text (withUnsignedContent).
pub unsigned_content: Option<Tag>,
}
impl ChatMessage {
/// The message a chain let through: a signed one keeps its body;
/// PlayerChatMessage.unsigned takes the time now, no salt, nothing seen.
pub fn new(sender: u128, unpacked: Unpacked, body: &Body, now: i64) -> Self {
let (index, signature, timestamp, salt, last_seen) = match unpacked {
Unpacked::Unsigned => (0, None, now, 0, Vec::new()),
Unpacked::Signed { index, signature } => (
index,
Some(signature),
body.timestamp,
body.salt,
body.last_seen.to_vec(),
),
};
Self {
sender,
index,
signature,
content: body.content.to_owned(),
timestamp,
salt,
last_seen,
unsigned_content: None,
}
}
/// hasExpiredServer.
pub fn expired(&self, now: i64) -> bool {
now > self.timestamp + secure_chat::EXPIRES_AFTER_SERVER
}
/// PlayerList.verifyChatTrusted: signed and not expired.
pub fn trusted(&self, now: i64) -> bool {
self.signature.is_some() && !self.expired(now)
}
}
impl Hub {
/// MinecraftServer.enforceSecureProfile.
pub fn enforces_secure_chat(&self) -> bool {
self.lan.shared.config.enforces_secure_chat()
}
/// Component.getString in the server's language, for the log.
pub(crate) fn english(&self, tag: &Tag) -> String {
match &self.lan.shared.config.log {
Some(log) => horizon_protocol::text::plain(tag, &log.lang),
None => horizon_protocol::text::plain(tag, &Default::default()),
}
}
/// tryHandleChat: an illegal character disconnects; with chat hidden a
/// message (not a command) is refused. Whether to go on.
pub fn try_handle_chat(&mut self, i: usize, message: &str, command: bool) -> bool {
let conn = self.guests[i].conn;
if !message.chars().all(allowed) {
self.kick(
conn,
translatable("multiplayer.disconnect.illegal_characters", &[]),
);
return false;
}
// ChatVisiblity.HIDDEN.
if !command && self.guests[i].info.chat_visibility == 2 {
self.guests[i].send(&C::SystemChat(play::SystemChat {
content: red("chat.disabled.options"),
overlay: false,
}));
return false;
}
true
}
/// unpackAndApplyLastSeen: the acknowledged messages, or a disconnect.
pub fn apply_last_seen(
&mut self,
i: usize,
update: &play::LastSeenUpdate,
events: &mut Vec<HostEvent>,
) -> Option<Vec<Signature>> {
let g = &mut self.guests[i];
match g
.last_seen
.apply_update(update.offset, update.acknowledged, update.checksum)
{
Ok(seen) => Some(seen),
// Vanilla logs the ValidationException's stack trace after the line.
Err(_) => {
events.push(HostEvent::Error(format!(
"Failed to validate message acknowledgements from {}",
g.name
)));
let conn = g.conn;
self.kick(
conn,
translatable("multiplayer.disconnect.chat_validation_failed", &[]),
);
None
}
}
}
/// handleChatAck.
pub(super) fn chat_ack(&mut self, i: usize, offset: i32, events: &mut Vec<HostEvent>) {
let g = &mut self.guests[i];
if g.last_seen.apply_offset(offset).is_err() {
events.push(HostEvent::Error(format!(
"Failed to validate message acknowledgement offset from {}",
g.name
)));
let conn = g.conn;
self.kick(
conn,
translatable("multiplayer.disconnect.chat_validation_failed", &[]),
);
}
}
/// handleMessageDecodeFailure: logged, and the reason in red for the player.
pub fn decode_failure(&mut self, i: usize, e: DecodeError, events: &mut Vec<HostEvent>) {
let reason = red(e.key());
events.push(HostEvent::Warn(format!(
"Failed to update secure chat state for {}: '{}'",
self.guests[i].name,
self.english(&reason)
)));
self.guests[i].send(&C::SystemChat(play::SystemChat {
content: reason,
overlay: false,
}));
}
/// handleChat: the acknowledgements, then the message through the
/// sender's chain, then to everyone.
pub(super) fn handle_chat(&mut self, i: usize, c: play::Chat, events: &mut Vec<HostEvent>) {
let Some(last_seen) = self.apply_last_seen(i, &c.last_seen, events) else {
return;
};
if !self.try_handle_chat(i, &c.message, false) {
return;
}
let (enforce, now) = (self.enforces_secure_chat(), now_millis());
let body = Body {
content: &c.message,
timestamp: c.timestamp,
salt: c.salt,
last_seen: &last_seen,
};
let signature = c.signature.as_deref().and_then(secure_chat::signature);
let g = &mut self.guests[i];
let (uuid, name) = (g.uuid, g.name.clone());
let message = match g
.chain
.unpack(uuid, signature.as_ref(), &body, enforce, now)
{
Ok(unpacked) => ChatMessage::new(uuid, unpacked, &body, now),
Err(e) => return self.decode_failure(i, e, events),
};
if message.signature.is_some() && message.expired(now) {
events.push(HostEvent::Warn(format!(
"Received expired chat: '{}'. Is the client/server system time unsynchronized?",
message.content
)));
}
let bound = play::ChatTypeBound {
chat_type: self.chat_type,
name: display_name(uuid, &name),
target: None,
};
let line = format!("<{name}> {}", message.content);
self.broadcast_chat(&message, &bound, line, events);
}
/// handleChatSessionUpdate: a new profile key, validated against the
/// services' keys, starts a new chain and is announced to everyone.
pub(super) fn chat_session_update(
&mut self,
i: usize,
p: play::ChatSessionUpdate,
events: &mut Vec<HostEvent>,
) {
let key = ProfileKey {
expires_at: p.expires_at,
key: p.key,
signature: p.key_signature,
};
let g = &self.guests[i];
let (conn, uuid) = (g.conn, g.uuid);
let old = g.chain.session().map(|s| s.profile_key.expires_at);
if g.chain.session().is_some_and(|s| s.profile_key == key) {
return;
}
if old.is_some_and(|old| key.expires_at < old) {
self.kick(
conn,
translatable("multiplayer.disconnect.expired_public_key", &[]),
);
return;
}
let secure = self.lan.shared.config.secure_chat.clone();
let keys = secure.as_deref().map_or(&[][..], |s| s.keys());
if keys.is_empty() {
events.push(HostEvent::Warn(format!(
"Ignoring chat session from {} due to missing Services public key",
g.name
)));
return;
}
match ChatSession::validate(p.session, key, keys, uuid) {
Ok(session) => {
let data = session.data();
self.guests[i].chain = Chain::keyed(session);
// resetPlayerChatState: INITIALIZE_CHAT to every player.
self.broadcast(&C::PlayerInfoUpdate(play::PlayerInfoUpdate {
actions: 2,
entries: vec![play::PlayerInfo {
uuid,
chat_session: Some(data),
..Default::default()
}],
}));
}
Err(reason) => {
events.push(HostEvent::Error(
"Failed to validate profile key".to_owned(),
));
self.kick(conn, translatable(reason, &[]));
}
}
}
/// PlayerList.broadcastChatMessage: logged (`[Not Secure]` unless signed
/// and fresh), then sent to every player.
pub fn broadcast_chat(
&mut self,
message: &ChatMessage,
bound: &play::ChatTypeBound,
line: String,
events: &mut Vec<HostEvent>,
) {
let secure = message.trusted(now_millis());
events.push(HostEvent::Chat { line, secure });
for k in 0..self.guests.len() {
if self.guests[k].placed {
self.send_chat(k, message, bound);
}
}
}
/// ServerPlayer.sendChatMessage (players who show chat) and
/// sendPlayerChatMessage: numbered for the connection, the last seen
/// packed against its cache; a signed message joins the cache and the
/// messages the player must acknowledge.
pub fn send_chat(&mut self, k: usize, message: &ChatMessage, bound: &play::ChatTypeBound) {
let g = &mut self.guests[k];
if g.info.chat_visibility != 0 {
return;
}
let last_seen = message
.last_seen
.iter()
.map(|s| g.signatures.pack(s))
.collect();
g.send(&C::PlayerChat(play::PlayerChat {
global_index: g.chat_index,
sender: message.sender,
index: message.index,
signature: message.signature.map(|s| s.to_vec()),
content: message.content.clone(),
timestamp: message.timestamp,
salt: message.salt,
last_seen,
unsigned_content: message.unsigned_content.clone(),
filter: (0, Vec::new()),
chat_type: bound.clone(),
}));
g.chat_index += 1;
if let Some(signature) = &message.signature {
g.signatures.push(&message.last_seen, Some(signature));
g.last_seen.add_pending(signature);
if g.last_seen.tracked_count() > 4096 {
let conn = g.conn;
self.kick(
conn,
translatable("multiplayer.disconnect.too_many_pending_chats", &[]),
);
}
}
}
/// sendChatMessage of a system message: a disguised chat, to players
/// who show chat.
fn send_disguised(&self, k: usize, message: Tag, chat_type: play::ChatTypeBound) {
let g = &self.guests[k];
if g.info.chat_visibility == 0 {
g.send(&C::DisguisedChat(play::DisguisedChat {
message,
chat_type,
}));
}
}
/// collectSignedArguments, or collectUnsignedArguments when the client
/// signed none: each of the command's message arguments (`parsed`, by
/// name) through the sender's chain.
pub fn signed_arguments(
&mut self,
i: usize,
p: &play::ChatCommandSigned,
parsed: &[(String, String)],
last_seen: &[Signature],
events: &mut Vec<HostEvent>,
) -> Result<Vec<(String, ChatMessage)>, DecodeError> {
let (enforce, now) = (self.enforces_secure_chat(), now_millis());
let g = &mut self.guests[i];
let uuid = g.uuid;
let mut out = Vec::new();
if p.arguments.is_empty() {
for (name, value) in parsed {
// SignedMessageBody.unsigned.
let body = Body {
content: value,
timestamp: now,
salt: 0,
last_seen: &[],
};
let unpacked = g.chain.unpack(uuid, None, &body, enforce, now)?;
out.push((name.clone(), ChatMessage::new(uuid, unpacked, &body, now)));
}
return Ok(out);
}
let mismatch = |events: &mut Vec<HostEvent>| {
let names = |l: &mut dyn Iterator<Item = &String>| {
l.map(String::as_str).collect::<Vec<_>>().join(", ")
};
events.push(HostEvent::Error(format!(
"Signed command mismatch between server and client ('{}'): got [{}] from client, but expected [{}]",
p.command,
names(&mut p.arguments.iter().map(|a| &a.0)),
names(&mut parsed.iter().map(|a| &a.0)),
)));
DecodeError::InvalidCommandSignature
};
for (name, signature) in &p.arguments {
let Some((_, value)) = parsed.iter().find(|(n, _)| n == name) else {
g.chain.set_broken();
return Err(mismatch(events));
};
let body = Body {
content: value,
timestamp: p.timestamp,
salt: p.salt,
last_seen,
};
let signature = secure_chat::signature(signature);
let unpacked = g
.chain
.unpack(uuid, signature.as_ref(), &body, enforce, now)?;
out.push((name.clone(), ChatMessage::new(uuid, unpacked, &body, now)));
}
if parsed.iter().any(|(n, _)| !out.iter().any(|(o, _)| o == n)) {
return Err(mismatch(events));
}
Ok(out)
}
/// A message command's chat (SayCommand, EmoteCommands): to everyone,
/// bound to `chat_type` and the sender's name.
pub fn broadcast_command_chat(
&mut self,
i: usize,
chat_type: &str,
message: Option<ChatMessage>,
text: &str,
events: &mut Vec<HostEvent>,
) {
let (uuid, name) = (self.guests[i].uuid, self.guests[i].name.clone());
let bound = play::ChatTypeBound {
chat_type: self.chat_type_id(chat_type),
name: display_name(uuid, &name),
target: None,
};
let line = match chat_type {
"say_command" => format!("[{name}] {text}"),
_ => format!("* {name} {text}"),
};
match message {
Some(message) => self.broadcast_chat(&message, &bound, line, events),
// An unsigned command packet (no signing context):
// PlayerChatMessage.system, a disguised chat.
None => {
events.push(HostEvent::Chat {
line,
secure: false,
});
for k in 0..self.guests.len() {
if self.guests[k].placed {
self.send_disguised(k, literal(text), bound.clone());
}
}
}
}
}
/// MsgCommand.sendMessage to each target: the outgoing line for the
/// sender, the incoming one for the target. Nothing is logged.
pub fn whisper(
&mut self,
i: usize,
targets: &[usize],
message: Option<ChatMessage>,
text: &str,
) {
let (uuid, name) = (self.guests[i].uuid, self.guests[i].name.clone());
let (outgoing, incoming) = (
self.chat_type_id("msg_command_outgoing"),
self.chat_type_id("msg_command_incoming"),
);
for &t in targets {
let target = display_name(self.guests[t].uuid, &self.guests[t].name);
let out = play::ChatTypeBound {
chat_type: outgoing,
name: display_name(uuid, &name),
target: Some(target),
};
let inc = play::ChatTypeBound {
chat_type: incoming,
name: display_name(uuid, &name),
target: None,
};
match &message {
Some(m) => {
self.send_chat(i, m, &out);
self.send_chat(t, m, &inc);
}
None => {
self.send_disguised(i, literal(text), out);
self.send_disguised(t, literal(text), inc);
}
}
}
}
/// A chat type's registry id.
fn chat_type_id(&self, name: &str) -> i32 {
self.sync
.id("minecraft:chat_type", &format!("minecraft:{name}"))
.unwrap_or(self.chat_type)
}
}
+48 -4
View File
@@ -122,8 +122,8 @@ pub struct NetConfig {
pub hide_online_players: bool,
/// server-icon.png (64x64 PNG bytes).
pub favicon: Option<Vec<u8>>,
/// MinecraftServer.enforceSecureProfile.
pub enforces_secure_chat: bool,
/// Secure chat (a dedicated server; none on a LAN world).
pub secure_chat: Option<Arc<SecureChat>>,
pub accepts_transfers: bool,
/// LanServerPinger: announce the world on the local network.
pub announce: bool,
@@ -138,6 +138,10 @@ pub struct NetConfig {
pub log: Option<NetLog>,
}
impl NetConfig {
/// MinecraftServer.enforceSecureProfile.
pub fn enforces_secure_chat(&self) -> bool {
self.secure_chat.as_ref().is_some_and(|s| s.enforced())
}
/// IntegratedServer.publishServer.
pub fn lan(port: u16, motd: String, max_players: usize) -> Self {
Self {
@@ -149,7 +153,7 @@ impl NetConfig {
enable_status: true,
hide_online_players: false,
favicon: None,
enforces_secure_chat: false,
secure_chat: None,
accepts_transfers: false,
announce: true,
listen: true,
@@ -161,6 +165,46 @@ impl NetConfig {
}
}
/// A dedicated server's secure chat (DedicatedServer.enforceSecureProfile,
/// Services.profileKeySignatureValidator): the services' profile-key keys,
/// fetched in the background from startup and waited for by their first
/// use, as authlib's RetryableFetch does.
pub struct SecureChat {
/// enforce-secure-profile, in online mode.
pub enforce: bool,
keys: std::sync::OnceLock<Vec<horizon_protocol::rsa::RsaPublicKey>>,
fetch: Mutex<Option<JoinHandle<Vec<horizon_protocol::rsa::RsaPublicKey>>>>,
}
impl SecureChat {
pub fn new(
enforce: bool,
fetch: impl FnOnce() -> Vec<horizon_protocol::rsa::RsaPublicKey> + Send + 'static,
) -> Self {
let handle = std::thread::Builder::new()
.name("Services keys".into())
.spawn(fetch)
.ok();
Self {
enforce,
keys: std::sync::OnceLock::new(),
fetch: Mutex::new(handle),
}
}
/// The keys players' chat keys must be signed by (none when the
/// services couldn't be reached).
pub fn keys(&self) -> &[horizon_protocol::rsa::RsaPublicKey] {
self.keys.get_or_init(|| {
let handle = self.fetch.lock().ok().and_then(|mut h| h.take());
handle.and_then(|h| h.join().ok()).unwrap_or_default()
})
}
/// enforceSecureProfile: enforced, and able to check keys.
pub fn enforced(&self) -> bool {
self.enforce && !self.keys().is_empty()
}
}
/// State shared with the connection threads.
pub struct Shared {
pub sync: Arc<data::SyncData>,
@@ -301,7 +345,7 @@ impl Shared {
Json::String(format!("data:image/png;base64,{}", base64(icon))),
));
}
if self.config.enforces_secure_chat {
if self.config.enforces_secure_chat() {
status.push(("enforcesSecureChat".to_owned(), Json::Bool(true)));
}
Json::Object(status).compact()
@@ -68,7 +68,9 @@ pub fn apply(guest: &mut Guest, level: &Level) {
guest.xp_total = level.xp_total;
guest.effects = crate::effects::PlayerEffects::from_saved(&level.active_effects);
guest.game_mode = level.mode();
guest.flying = level.flying;
guest.selected = (level.selected_slot.max(0) as usize).min(8);
guest.spawn = level.spawn.map(|s| [s[0] + 0.5, s[1], s[2] + 0.5]);
guest.saved = level.player_extra.clone();
guest.recipe_book = level.recipe_book.clone();
guest.dimension = match level.dimension.as_str() {
@@ -128,7 +130,9 @@ pub fn store(guest: &Guest, level: &mut Level) {
level.active_effects = guest.effects.saved();
level.game_mode = guest.game_mode;
level.creative = guest.game_mode == 1;
level.flying = guest.flying;
level.selected_slot = guest.selected as i32;
level.spawn = guest.spawn.map(|s| [s[0] - 0.5, s[1], s[2] - 0.5]);
level.on_ground = guest.on_ground;
level.player_extra = guest.saved.clone();
level.recipe_book = guest.recipe_book.clone();
+2
View File
@@ -16,6 +16,7 @@ pub mod banner;
pub mod beehive;
pub mod benchmark;
pub mod biome;
pub mod block_entities;
pub mod block_entity_anim;
pub mod block_entity_item;
pub mod block_entity_nbt;
@@ -134,6 +135,7 @@ pub mod patrol;
pub mod perf_overlay;
pub mod pick_item;
pub mod poi_sections;
pub mod portal_sections;
pub mod pose;
pub mod post;
pub mod projectiles;
+116 -11
View File
@@ -65,17 +65,9 @@ impl LightTables {
}
/// Full tables with the vanilla occlusion shapes from `occlusion.nbt`.
pub fn load(root: &Path, registry: &BlockRegistry, facts: &BlockFacts) -> crate::Result<Self> {
use horizon_world::{
collision::CachedCollisionRegistry,
nbt::{self, Limits},
};
let data = nbt::read_named(
&std::fs::read(root.join("occlusion.nbt"))?,
Limits::tables(),
)?
.0
.tag;
let occlusion = CachedCollisionRegistry::from_nbt(&data, registry)?;
use horizon_world::{collision::CachedCollisionRegistry, registry::BlockTableFile};
let file = BlockTableFile::open(&root.join("occlusion.nbt"), registry)?;
let occlusion = CachedCollisionRegistry::from_table(file.table("occlusion")?)?;
let mut tables = Self::new(facts);
let block = VoxelShape::block();
let mut shapes: Vec<VoxelShape> = vec![VoxelShape::empty(), block.clone()];
@@ -389,6 +381,81 @@ pub fn apply_relighting(chunk: &mut Chunk, lights: Vec<Light>) -> Vec<(i32, i32,
changed
}
/// `DataLayer.get`: the nibble at index `i` (`y << 8 | z << 4 | x`), low first.
#[inline]
fn nibble(layer: &[u8], i: usize) -> u8 {
(layer[i >> 1] >> ((i & 1) * 4)) & 15
}
/// A column's light as vanilla stores it, two DataLayers per section (sky,
/// block; `layers[i]` for section `i`, `None` where no layer is stored), into
/// the sections' packed light, which then needs no light job. A missing sky
/// layer repeats the bottom layer of the nearest stored one above it, and
/// `above` (per `z << 4 | x`) above the highest
/// (`SkyLightSectionStorage.getLightValue`); a missing block layer is dark.
pub fn light_from_layers<L: AsRef<[u8]>>(
chunk: &mut Chunk,
layers: &[(Option<L>, Option<L>)],
mut above: [u8; 256],
sky_light: bool,
) {
for (si, (sky, block)) in layers.iter().enumerate().take(SECTIONS).rev() {
let sky = sky.as_ref().filter(|_| sky_light);
let section = Arc::make_mut(&mut chunk.sections[si]);
if sky.is_none() && block.is_none() && above.iter().all(|&v| v == above[0]) {
section.light = Light::Uniform(above[0] << 4);
section.compact();
continue;
}
let mut data = Box::new([0u8; 4096]);
for (i, packed) in data.iter_mut().enumerate() {
let s = sky.map_or(above[i & 255], |a| nibble(a.as_ref(), i));
let b = block.as_ref().map_or(0, |a| nibble(a.as_ref(), i));
*packed = s << 4 | b;
}
for (i, a) in above.iter_mut().enumerate() {
*a = data[i] >> 4;
}
section.light = Light::Full(data);
section.compact();
}
chunk.lit = true;
chunk.light_loaded = true;
}
/// A light update's layers (`LevelLightEngine.queueSectionData`): each one
/// given replaces that kind of light in its section, the other kind stays.
/// Returns the sections whose light changed.
pub fn update_light_layers<L: AsRef<[u8]>>(
chunk: &mut Chunk,
layers: &[(Option<L>, Option<L>)],
sky_light: bool,
) -> Vec<usize> {
let mut changed = Vec::new();
for (si, (sky, block)) in layers.iter().enumerate().take(SECTIONS) {
let sky = sky.as_ref().filter(|_| sky_light);
if sky.is_none() && block.is_none() {
continue;
}
let old = &chunk.sections[si].light;
let mut data = Box::new([0u8; 4096]);
for (i, packed) in data.iter_mut().enumerate() {
let was = old.get(i);
let s = sky.map_or(was >> 4, |a| nibble(a.as_ref(), i));
let b = block.as_ref().map_or(was & 15, |a| nibble(a.as_ref(), i));
*packed = s << 4 | b;
}
if (0..4096).all(|i| old.get(i) == data[i]) {
continue;
}
let section = Arc::make_mut(&mut chunk.sections[si]);
section.light = Light::Full(data);
section.compact();
changed.push(si);
}
changed
}
/// Resident chunks the incremental relighter reads and writes.
pub trait LightWorld {
fn state(&self, x: i32, y: i32, z: i32) -> Option<u32>;
@@ -817,6 +884,44 @@ mod tests {
assert!(copied <= 3, "{copied} sections copied");
}
#[test]
fn stored_layers_fill_the_column_as_vanilla_reads_them() {
// Section 10's sky layer is 7 on its bottom row and 3 above; no
// layers anywhere else; a block layer of 5 in section 2.
let mut sky = vec![0x33u8; 2048];
sky[..128].fill(0x77);
let mut layers: Vec<(Option<Vec<u8>>, Option<Vec<u8>>)> = vec![(None, None); SECTIONS];
layers[10].0 = Some(sky);
layers[2].1 = Some(vec![0x55; 2048]);
let mut chunk = Chunk::empty(0, 0);
light_from_layers(&mut chunk, &layers, [15; 256], true);
let at = |c: &Chunk, si: usize, i: usize| c.sections[si].light(i);
assert!(chunk.lit && chunk.light_loaded);
assert!(
matches!(chunk.sections[11].light, Light::Uniform(0xF0)),
"above: open sky"
);
assert_eq!((at(&chunk, 10, 0), at(&chunk, 10, 4095)), (0x70, 0x30));
// Below, each section repeats the bottom row of the stored one above.
assert!(matches!(chunk.sections[9].light, Light::Uniform(0x70)));
assert_eq!(at(&chunk, 2, 100), 0x75, "block light only where stored");
assert!(matches!(chunk.sections[0].light, Light::Uniform(0x70)));
// A light update replaces one kind of light in the sections it names.
let mut update: Vec<(Option<Vec<u8>>, Option<Vec<u8>>)> = vec![(None, None); SECTIONS];
update[2].1 = Some(vec![0; 2048]);
update[3].0 = Some(vec![0x77; 2048]);
let changed = update_light_layers(&mut chunk, &update, true);
assert_eq!(changed, vec![2]);
assert!(matches!(chunk.sections[2].light, Light::Uniform(0x70)));
update[3].0 = Some(vec![0xFF; 2048]);
assert_eq!(
update_light_layers(&mut chunk, &update, false),
Vec::<usize>::new(),
"no sky storage"
);
}
#[test]
fn empty_chunk_missing_neighbours_and_no_sky() {
let mut chunk = Chunk::empty(0, 0);
+13
View File
@@ -1668,6 +1668,18 @@ impl Menu {
env: &Env,
clicked: usize,
moved: &ItemStack,
) -> Result<(), &'static str> {
self.quick_move_all_each(env, clicked, moved, &mut |_, _| {})
}
/// `quick_move_all`, calling `each` with the menu and the slot after each
/// QUICK_MOVE (a server's client sends every one of them).
pub fn quick_move_all_each(
&mut self,
env: &Env,
clicked: usize,
moved: &ItemStack,
each: &mut dyn FnMut(&Self, usize),
) -> Result<(), &'static str> {
if clicked >= self.slots.len() || !self.can_take_for_pick_all(clicked) {
return Ok(());
@@ -1680,6 +1692,7 @@ impl Menu {
&& self.quick_replace(t, moved, env)
{
self.click(env, t as i32, 0, Input::QuickMove)?;
each(self, t);
}
}
Ok(())
+3
View File
@@ -1400,6 +1400,9 @@ pub struct PlayerView {
/// The mobs on the player's team (`isAlliedTo`): combat targeting
/// leaves the player alone.
pub allies: std::sync::Arc<std::collections::HashSet<u32>>,
/// A LAN guest: its own client moves it, and touching mobs push it there
/// (`EntitySelector.pushableBy` on the client).
pub remote: bool,
}
pub struct MobWorld<'a> {
pub world: &'a World,
+8 -4
View File
@@ -822,10 +822,14 @@ fn push_entities(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
za *= pow;
xa *= f64::from(0.05_f32);
za *= f64::from(0.05_f32);
events.push(MobEvent::Push {
target: who,
velocity: [-xa, 0.0, -za],
});
// A guest's server-side push never reaches its client (ServerPlayer
// motion is synced only when hurt): its client pushes it itself.
if who != Who::Player || w.player.as_ref().is_none_or(|p| !p.remote) {
events.push(MobEvent::Push {
target: who,
velocity: [-xa, 0.0, -za],
});
}
if self_pushable {
m.velocity = Vec3::new(m.velocity.x + xa, m.velocity.y, m.velocity.z + za);
}
+156 -4
View File
@@ -674,6 +674,28 @@ pub fn tag_namespaces(root: &Path) -> Vec<String> {
/// Bundles of block tag files (tag id → the tag file's text).
const TAG_BUNDLES: [&str; 2] = ["block-tags.json", "worldgen/block_tags.json"];
/// The worldgen loader's bundle of biome tags.
const BIOME_TAGS: &str = "worldgen/biome_tags.json";
/// Worldgen registries a content mod may add to, and the bundle the
/// worldgen loader reads each from (id → the file's text): what structure
/// mods hold. Biomes, noise and density functions change the terrain and
/// are not read from mods.
const WORLDGEN_BUNDLES: [(&str, &str); 6] = [
("structure", "worldgen/structures.json"),
("structure_set", "worldgen/structure_sets.json"),
("template_pool", "worldgen/template_pools.json"),
("processor_list", "worldgen/processor_lists.json"),
("configured_feature", "worldgen/features.json"),
("placed_feature", "worldgen/placed_features.json"),
];
/// A mod file that adds to a worldgen bundle: (bundle, id).
fn worldgen_entry(file: &str) -> Option<(&'static str, String)> {
let (ns, rest) = file.strip_prefix("data/")?.split_once("/worldgen/")?;
let (kind, path) = rest.split_once('/')?;
let (_, bundle) = WORLDGEN_BUNDLES.iter().find(|(k, _)| *k == kind)?;
Some((bundle, format!("{ns}:{}", path.strip_suffix(".json")?)))
}
/// The overlay being written: `out` mirrors `base` through links, and a
/// directory becomes real only when something inside it is written.
@@ -773,6 +795,9 @@ fn merge_tag(text: Option<&str>, more: &[J], what: &str) -> Result<String> {
struct Known {
blocks: std::collections::BTreeSet<String>,
items: std::collections::BTreeSet<String>,
/// The worldgen loader's biomes and biome tags.
biomes: std::collections::BTreeSet<String>,
biome_tags: std::collections::BTreeSet<String>,
/// `data/<ns>/tags/<kind>/<path>.json` files the mods add.
tag_files: std::collections::BTreeSet<String>,
}
@@ -786,14 +811,27 @@ impl Known {
items.extend(o.into_iter().map(|(k, _)| k));
}
items.extend(plan.items.iter().map(|i| i.rename.to.clone()));
let keys = |name: &str| -> Result<std::collections::BTreeSet<String>> {
Ok(match base.join(name).exists() {
true => match read_json(&base.join(name))? {
J::Obj(o) => o.into_iter().map(|(k, _)| k).collect(),
_ => Default::default(),
},
false => Default::default(),
})
};
Ok(Known {
blocks,
items,
biomes: keys("worldgen/biomes.json")?,
biome_tags: keys(BIOME_TAGS)?,
tag_files: tags.keys().cloned().collect(),
})
}
/// Whether tag `file` keeps entry `v`: a known id or an existing tag,
/// for block and item tags (other registries are kept as they are).
/// for block, item and biome tags (other registries are kept as they
/// are). The worldgen loader refuses a biome tag naming what it lacks
/// (another mod's biomes, a loader's tags), so those entries go.
fn keeps(&self, file: &str, v: &J) -> bool {
let id = match v {
J::Str(s) => s.as_str(),
@@ -803,23 +841,32 @@ impl Known {
},
_ => return true,
};
let Some(kind) = file
let Some(rest) = file
.strip_prefix("data/")
.and_then(|r| r.split_once("/tags/"))
.and_then(|(_, rest)| Some(rest.split_once('/')?.0))
.map(|(_, rest)| rest)
else {
return true;
};
let kind = match rest.strip_prefix("worldgen/biome/") {
Some(_) => "worldgen/biome",
None => rest.split_once('/').map_or("", |(k, _)| k),
};
let ids = match kind {
"block" => &self.blocks,
"item" => &self.items,
"worldgen/biome" => &self.biomes,
_ => return true,
};
match id.strip_prefix('#') {
Some(tag) => {
let (tns, path) = tag.split_once(':').unwrap_or(("minecraft", tag));
let rel = format!("data/{tns}/tags/{kind}/{path}.json");
self.tag_files.contains(&rel) || tns == "minecraft"
self.tag_files.contains(&rel)
|| match kind {
"worldgen/biome" => self.biome_tags.contains(&format!("{tns}:{path}")),
_ => tns == "minecraft",
}
}
None => ids.contains(id),
}
@@ -856,6 +903,7 @@ pub fn build(base: &Path, mods: &[ContentMod], out: &Path) -> Result<()> {
}
// Mod files, and every tag addition gathered per tag file.
let mut tags: BTreeMap<String, Vec<J>> = BTreeMap::new();
let mut worldgen: BTreeMap<&str, Vec<(String, String)>> = BTreeMap::new();
for m in mods {
let declarations = format!("data/{}/horizon/", m.id);
for file in &m.content.files {
@@ -878,6 +926,18 @@ pub fn build(base: &Path, mods: &[ContentMod], out: &Path) -> Result<()> {
.extend(values.iter().cloned());
} else if !file.starts_with(&declarations) {
overlay.write(file, &bytes)?;
if let Some((bundle, id)) = worldgen_entry(file) {
let text = String::from_utf8(bytes).map_err(|e| format!("{file}: {e}"))?;
worldgen.entry(bundle).or_default().push((id, text));
} else if let Some(template) = file
.strip_prefix("data/")
.and_then(|r| r.split_once("/structure/"))
.filter(|(_, path)| path.ends_with(".nbt"))
{
// The worldgen loader's templates: worldgen/structure/<ns>/<path>.nbt.
let (ns, path) = template;
overlay.write(&format!("worldgen/structure/{ns}/{path}"), &bytes)?;
}
}
}
}
@@ -921,6 +981,38 @@ pub fn build(base: &Path, mods: &[ContentMod], out: &Path) -> Result<()> {
for (name, doc) in &bundles {
overlay.write(name, &serde_json::to_vec(doc)?)?;
}
// Biome tags, merged into the worldgen loader's bundle as block tags are.
let biome_tags: Vec<(String, &Vec<J>)> = tags
.iter()
.filter_map(|(file, values)| {
let (ns, path) = file
.strip_prefix("data/")?
.split_once("/tags/worldgen/biome/")?;
Some((format!("{ns}:{}", path.strip_suffix(".json")?), values))
})
.collect();
if !biome_tags.is_empty() && base.join(BIOME_TAGS).exists() {
let mut doc = read_json(&base.join(BIOME_TAGS))?;
for (id, values) in biome_tags {
let text = match doc.get(&id) {
Some(J::Str(t)) => Some(t.clone()),
_ => None,
};
doc.set(&id, J::Str(merge_tag(text.as_deref(), values, BIOME_TAGS)?));
}
overlay.write(BIOME_TAGS, &serde_json::to_vec(&doc)?)?;
}
// Structures and the pools, sets, processors and features they use.
for (bundle, entries) in &worldgen {
if !base.join(bundle).exists() {
continue;
}
let mut doc = read_json(&base.join(bundle))?;
for (id, text) in entries {
doc.set(id, J::Str(text.clone()));
}
overlay.write(bundle, &serde_json::to_vec(&doc)?)?;
}
// A block without its own blockstate looks like its template, so every
// state still has a model.
for m in mods {
@@ -943,15 +1035,75 @@ pub fn build(base: &Path, mods: &[ContentMod], out: &Path) -> Result<()> {
/// The root to load: `base` itself with no content, else the mods' overlay
/// over it, built in `cache/mod-content`.
///
/// The root is built once and kept: later starts with the same build, base
/// and mod files reuse it. With ATM10's carried mods a build takes about
/// 25 s and peaks above 3 GB, more than everything the game keeps.
pub fn resource_root(base: &Path, mods: &[ContentMod], cache: &Path) -> Result<PathBuf> {
if mods.iter().all(|m| m.content.is_empty()) {
return Ok(base.to_owned());
}
let out = cache.join("mod-content");
let stamp = stamp(base, mods)?;
if fs::read(out.join(STAMP)).is_ok_and(|s| s == stamp.as_bytes()) {
return Ok(out);
}
build(base, mods, &out)?;
fs::write(out.join(STAMP), stamp)?;
Ok(out)
}
/// In a root built by [`resource_root`]: what it was built from.
const STAMP: &str = "horizon-mod-content.stamp";
/// What a content root is built from: this build of the game, the base's
/// manifest and the tables [`build`] rewrites, and every file of every mod
/// in order. Files count by size and modification time, as build tools do.
fn stamp(base: &Path, mods: &[ContentMod]) -> Result<String> {
use sha2::{Digest, Sha256};
let meta = |path: &Path| -> Result<String> {
let m = fs::metadata(path).map_err(|e| format!("{}: {e}", path.display()))?;
let modified = m
.modified()?
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default();
Ok(format!(
"{} {} {}",
path.display(),
m.len(),
modified.as_nanos()
))
};
let mut parts = vec!["horizon mod content 1".to_owned()];
parts.push(meta(&std::env::current_exe()?)?);
let base = std::path::absolute(base)?;
parts.push(
String::from_utf8_lossy(&fs::read(base.join("horizon-resources.json"))?).into_owned(),
);
for name in JSON_TABLES.iter().chain(&NBT_TABLES).chain(&TAG_BUNDLES) {
if base.join(name).exists() {
parts.push(meta(&base.join(name))?);
}
}
for m in mods {
parts.push(m.id.clone());
let source = m.content.source();
if source.is_dir() {
for file in &m.content.files {
parts.push(meta(&source.join(file))?);
}
} else {
parts.push(meta(source)?);
}
}
let mut hasher = Sha256::new();
for part in &parts {
hasher.update((part.len() as u64).to_le_bytes());
hasher.update(part.as_bytes());
}
Ok(format!("{:x}", hasher.finalize()))
}
#[cfg(test)]
#[path = "mod_content_tests.rs"]
mod tests;
@@ -502,3 +502,119 @@ fn independent_reloads_read_changed_behaviour_json_and_report_invalid_files() {
);
fs::remove_dir_all(&scratch).unwrap();
}
/// A built root is kept for later starts, and built again when a mod's
/// files change.
#[test]
fn content_root_is_reused_until_a_mod_changes() {
let Some(base) = prepared() else {
return;
};
let scratch = std::env::temp_dir().join(format!("horizon-mod-reuse-{}", std::process::id()));
let _ = fs::remove_dir_all(&scratch);
let m = ruby_mod(&scratch.join("ruby"));
let cache = scratch.join("cache");
let root = resource_root(&base, std::slice::from_ref(&m), &cache).unwrap();
// A rebuild starts from an empty folder: this file tells them apart.
let sentinel = root.join("sentinel");
fs::write(&sentinel, b"").unwrap();
assert_eq!(
resource_root(&base, std::slice::from_ref(&m), &cache).unwrap(),
root
);
assert!(sentinel.exists(), "an unchanged mod rebuilt the root");
let lang = scratch.join("ruby/assets/ruby/lang/en_us.json");
fs::write(&lang, r#"{"block.ruby.ruby_block": "Ruby Block"}"#).unwrap();
let file = fs::File::options().write(true).open(&lang).unwrap();
file.set_modified(std::time::SystemTime::now() + std::time::Duration::from_secs(5))
.unwrap();
resource_root(&base, std::slice::from_ref(&m), &cache).unwrap();
assert!(!sentinel.exists(), "a changed mod kept the old root");
assert!(
fs::read_to_string(root.join("assets/ruby/lang/en_us.json"))
.unwrap()
.contains("Ruby Block")
);
let _ = fs::remove_dir_all(&scratch);
}
/// A structure mod's worldgen reaches the worldgen loader: its structure,
/// set, pool and templates join the bundles, and its biome tag keeps only
/// what the loader knows.
#[test]
fn content_root_carries_a_structure_mod() {
let Some(base) = prepared() else {
return;
};
let scratch = std::env::temp_dir().join(format!("horizon-mod-worldgen-{}", std::process::id()));
let _ = fs::remove_dir_all(&scratch);
let dir = scratch.join("huts");
let files = [
(
"horizon-mod.toml",
"id = \"huts\"\nname = \"Huts\"\nversion = \"1.0\"\napi = \"0.2\"\nside = \"both\"\ncapabilities = [\"registries\"]\n",
),
(
"data/huts/worldgen/structure/hut.json",
r##"{"type": "minecraft:jigsaw", "biomes": "#huts:has_hut", "step": "surface_structures",
"spawn_overrides": {}, "terrain_adaptation": "beard_thin", "start_pool": "huts:hut/start",
"size": 1, "start_height": {"absolute": 0}, "project_start_to_heightmap": "WORLD_SURFACE_WG",
"max_distance_from_center": 80}"##,
),
(
"data/huts/worldgen/template_pool/hut/start.json",
r#"{"fallback": "minecraft:empty", "elements": [{"weight": 1, "element": {
"element_type": "minecraft:single_pool_element", "location": "huts:hut",
"projection": "rigid", "processors": "minecraft:empty"}}]}"#,
),
(
"data/huts/worldgen/structure_set/huts.json",
r#"{"structures": [{"structure": "huts:hut", "weight": 1}],
"placement": {"type": "minecraft:random_spread", "salt": 7, "spacing": 4, "separation": 2}}"#,
),
(
"data/huts/tags/worldgen/biome/has_hut.json",
r##"{"values": ["#minecraft:is_overworld", "#c:is_plains", "othermod:glade", "minecraft:plains"]}"##,
),
];
for (name, text) in files {
let path = dir.join(name);
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(path, text).unwrap();
}
// The template: vanilla's smallest plains house, as the mod's own file.
let house =
base.join("worldgen/structure/minecraft/village/plains/houses/plains_small_house_1.nbt");
fs::create_dir_all(dir.join("data/huts/structure")).unwrap();
fs::copy(&house, dir.join("data/huts/structure/hut.nbt")).unwrap();
let package = horizon_mods::Package::read(&dir).unwrap();
let m = ContentMod {
id: "huts".into(),
content: Content::read(&dir, &package.manifest).unwrap(),
};
let root = resource_root(&base, &[m], &scratch.join("cache")).unwrap();
assert!(root.join("worldgen/structure/huts/hut.nbt").exists());
let tags: BTreeMap<String, String> =
serde_json::from_slice(&fs::read(root.join("worldgen/biome_tags.json")).unwrap()).unwrap();
let hut: serde_json::Value = serde_json::from_str(&tags["huts:has_hut"]).unwrap();
assert_eq!(
hut["values"],
serde_json::json!(["#minecraft:is_overworld", "minecraft:plains"])
);
let assets = Assets::load(&root).unwrap();
let biomes = crate::biome::Biomes::load(&root).unwrap();
let terrain = crate::vanillagen::VanillaTerrain::new(
&root.join("worldgen"),
assets.registry,
&biomes,
1234,
)
.unwrap();
let (name, at) = terrain
.locate(&["huts:hut".to_owned()], [0, 64, 0], 16)
.expect("the mod's structure generates");
assert_eq!(name, "huts:hut");
assert!(at[0].abs() < 1024 && at[2].abs() < 1024, "{at:?}");
let _ = fs::remove_dir_all(&scratch);
}
+3 -5
View File
@@ -117,13 +117,11 @@ pub fn load_visibility(
use horizon_world::{
block_render::{FaceVisibility, RenderDefinition, SkipRendering},
collision::CachedCollisionRegistry,
nbt::{self, Limits},
registry::BlockTableFile,
};
use std::{collections::BTreeMap, fs};
let data = nbt::read_named(&fs::read(root.join("occlusion.nbt"))?, Limits::tables())?
.0
.tag;
let occlusion = CachedCollisionRegistry::from_nbt(&data, registry)?;
let file = BlockTableFile::open(&root.join("occlusion.nbt"), registry)?;
let occlusion = CachedCollisionRegistry::from_table(file.table("occlusion")?)?;
let raw: BTreeMap<String, Value> =
serde_json::from_slice(&fs::read(root.join("render-definitions.json"))?)?;
let definitions = raw
+23 -10
View File
@@ -31,8 +31,7 @@ use horizon_world::{
movement_restitution::{self, RestitutionInput, RestitutionWorld},
movement_statistics::{self, MovementStat, MovementStatisticsWorld},
movement_support::{self, MovementLocation},
nbt::{self, Limits},
registry::BlockStateId,
registry::{BlockStateId, BlockTableFile},
world_movement::{self, MovementRequest},
worldgen::tags::TagDefinitions,
};
@@ -57,17 +56,27 @@ pub struct MotionResources {
pub fluids: FluidResources,
}
impl MotionResources {
/// [`Self::load_with_facts`] with the block facts decoded here.
pub fn load(root: &Path, assets: &Assets) -> Result<Self> {
Self::load_with_facts(
root,
assets,
&crate::blocks::BlockFacts::load(root, assets.registry)?,
)
}
/// The motion tables, with the block facts the game already decoded
/// (decoding `gameplay-facts.json` again costs a second or more and, with
/// a big modpack, hundreds of megabytes while it runs).
pub fn load_with_facts(
root: &Path,
assets: &Assets,
facts: &crate::blocks::BlockFacts,
) -> Result<Self> {
let attributes = Arc::new(Catalog::from_json(&serde_json::from_slice(&fs::read(
root.join("attributes.json"),
)?)?)?);
let data = nbt::read_named(
&fs::read(root.join("movement-properties.nbt"))?,
Limits::tables(),
)?
.0
.tag;
let properties = MovementProperties::from_nbt(&data, assets.registry)?;
let file = BlockTableFile::open(&root.join("movement-properties.nbt"), assets.registry)?;
let properties = MovementProperties::from_table(file.table("movement")?)?;
let bundle: BTreeMap<String, String> =
serde_json::from_slice(&fs::read(root.join("block-tags.json"))?)?;
let mut definitions = TagDefinitions::default();
@@ -91,7 +100,7 @@ impl MotionResources {
Ok(Self {
landing: crate::landing::load(root, &properties)?,
health: crate::health::HealthResources::load(root)?,
fluids: FluidResources::load(root, assets)?,
fluids: FluidResources::new(assets, facts)?,
attributes,
blocks: properties.bind(&MovementTags {
fences: tag("minecraft:fences")?,
@@ -309,6 +318,7 @@ impl PlayerMotion {
self.set_health(level.health, false)?;
self.health.food.food = level.food;
self.health.food.saturation = level.saturation;
self.flying = level.flying;
}
Ok(())
}
@@ -2610,6 +2620,7 @@ mod tests {
food: 11,
saturation: 2.25,
player_extra: Some(extra),
flying: true,
..Default::default()
};
let mut pending = true;
@@ -2617,6 +2628,7 @@ mod tests {
.load_saved_state_once(&mut pending, &level)
.unwrap();
assert_eq!((w.player.fire_ticks, w.player.air), (160, 8));
assert!(w.player.flying);
assert_eq!(
(
w.player.health.health(),
@@ -2628,6 +2640,7 @@ mod tests {
let mut respawn = PlayerMotion::new(&resources, Vec3::new(20.5, 4.0, 20.5)).unwrap();
respawn.load_saved_state_once(&mut pending, &level).unwrap();
assert_eq!((respawn.fire_ticks, respawn.air), (-20, 300));
assert!(!respawn.flying);
assert_eq!(
(respawn.health.health(), respawn.health.food.food),
(20.0, 20)

Some files were not shown because too many files have changed in this diff Show More