Merge branch 'parity-base' into parity/old-saves

This commit is contained in:
Ludovic Marie
2026-10-13 03:27:26 +02:00
41 changed files with 7919 additions and 530 deletions
+16 -2
View File
@@ -329,12 +329,26 @@ fn mix(mixer: &mut Mixer, data: &mut [f32], channels: usize, rate: u32) {
}
impl Audio {
pub fn new(root: &Path) -> Self {
Self::with_output(root, true)
}
/// No output device: the dedicated server.
pub fn silent(root: &Path) -> Self {
Self::with_output(root, false)
}
fn with_output(root: &Path, output: bool) -> Self {
let registry = SoundRegistry::load(root);
let mixer = Arc::new(Mutex::new(Mixer::default()));
let (stream, live) = match Self::open(mixer.clone()) {
let opened = if output {
Self::open(mixer.clone())
} else {
Err("no output on a dedicated server".into())
};
let (stream, live) = match opened {
Ok(v) => (Some(v), true),
Err(e) => {
eprintln!("Horizon: audio unavailable: {e}");
if output {
eprintln!("Horizon: audio unavailable: {e}");
}
(None, false)
}
};
+1 -1
View File
@@ -140,7 +140,7 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
for (key, value) in [
("AbsorptionAmount", Tag::Float(0)),
("FallFlying", Tag::Byte(0)),
("CanPickUpLoot", Tag::Byte(i8::from(m.extra.pick_up_loot))),
("CanPickUpLoot", Tag::Byte(i8::from(m.can_pick_up_loot()))),
("LeftHanded", Tag::Byte(0)),
(
"Brain",
+33 -1
View File
@@ -22,6 +22,7 @@ mod copper_golems;
mod creaking;
mod creatures;
mod crossbow;
mod dedicated;
mod dispense_fixture;
mod dispenser;
mod dragon;
@@ -58,6 +59,7 @@ mod music;
mod names;
mod natural_spawning;
mod nautili;
mod net_harness;
mod options;
mod packs;
mod paintings;
@@ -184,6 +186,9 @@ struct Options {
/// Multiplayer: `--server HOST[:PORT]` joins at start; `--name` is the offline player name.
server: Option<String>,
player_name: String,
/// `--dedicated`: run as a dedicated server; vanilla's server arguments
/// (`--nogui`, `--port`, `--world`, `--universe`, `--initSettings`) follow.
dedicated: Option<Vec<String>>,
}
impl Options {
fn read() -> Result<Option<Self>> {
@@ -215,6 +220,7 @@ impl Options {
control: None,
server: None,
player_name: std::env::var("HORIZON_PLAYER_NAME").unwrap_or_else(|_| "Player".into()),
dedicated: None,
};
let mut args = std::env::args().skip(1);
while let Some(arg) = args.next() {
@@ -225,6 +231,10 @@ impl Options {
);
return Ok(None);
}
"--dedicated" => {
o.dedicated = Some(args.by_ref().collect());
break;
}
"--creative" => o.creative = true,
"--test-terrain" => o.test_terrain = true,
"--no-pause" => o.no_pause = true,
@@ -2573,6 +2583,10 @@ impl Game<'_> {
}
let riding = self.riding.is_some();
let Some(player) = self.player.as_mut() else {
// A dedicated server has no local player: the world still runs.
if self.options.dedicated.is_some() {
return self.tick_world(running);
}
return Ok(());
};
// Hold position until the surrounding terrain exists.
@@ -2760,6 +2774,11 @@ impl Game<'_> {
self.screen = Screen::Dead;
self.capture(false);
}
self.tick_world(running)
}
/// What the tick runs after the local player's own update: effects, the
/// world's entities and blocks, and the network hub.
fn tick_world(&mut self, running: bool) -> Result<()> {
self.tick_effects();
self.tick_burning();
self.tick_using();
@@ -8053,6 +8072,9 @@ pub fn run() -> Result<()> {
let Some(mut options) = Options::read()? else {
return Ok(());
};
if options.dedicated.is_some() && !dedicated::preflight(&mut options)? {
return Ok(());
}
let started = Instant::now();
let vanilla_root = options.resources.clone();
let early_settings = Settings::load(&std::env::current_dir()?.join("options.txt"));
@@ -8127,7 +8149,11 @@ pub fn run() -> Result<()> {
.join("saves")
.join(".horizon-title"),
));
let audio = Audio::new(&root);
let audio = if options.dedicated.is_some() {
Audio::silent(&root)
} else {
Audio::new(&root)
};
let world = World::new(facts.air, 0);
let creative = options.creative;
let stations = horizon_client::stations::StationData::load(&root, &items);
@@ -8417,6 +8443,9 @@ pub fn run() -> Result<()> {
if let Ok(spec) = std::env::var("HORIZON_SCULK_FIXTURE") {
return game.sculk_fixture(&spec);
}
if game.options.dedicated.is_some() {
return game.run_dedicated();
}
match game.options.world.clone() {
_ if game.options.server.is_some() => {
let (address, name) = (
@@ -8424,6 +8453,9 @@ pub fn run() -> Result<()> {
game.options.player_name.clone(),
);
game.connect_server(&address, &name)?;
if let Some(report) = std::env::var_os("HORIZON_NET_REPORT") {
return game.run_net_harness(report.as_ref());
}
}
Some(folder) => {
let (seed, creative) = (game.options.seed, game.options.creative);
+6 -55
View File
@@ -87,60 +87,7 @@ impl ProjectileWorld for ProjWorld<'_, '_> {
}
}
pub(super) fn seen(m: &Mob, player: Option<[i32; 4]>) -> Seen {
let villager = m.species() == Species::Villager;
Seen {
id: m.id,
species: m.species(),
position: m.position,
bounds: m.bounds(),
eye_y: m.eye_y(),
alive: m.alive(),
baby: m.is_baby(),
// A villager is "in love" when it is willing to breed (`canBreed`).
in_love: if villager {
horizon_client::mobs::villager::can_breed(m)
} else {
m.extra.in_love > 0
},
tame: m.extra.tame,
hostile: m.hostile(),
target: m.ai.target,
health: m.health,
variant: m.extra.variant,
color: m.extra.color,
job: (m.species() == Species::Villager)
.then_some(m.extra.home)
.flatten(),
bed: (m.species() == Species::Villager)
.then_some(m.extra.bed)
.flatten(),
yaw: m.yaw,
velocity: m.velocity,
leash: m.extra.leash,
caravan: horizon_client::mobs::caravan::head_of(m),
delay: m.extra.ints[5],
hurt_by: m.ai.last_hurt_by.map(|w| (w, m.ai.last_hurt_by_time)),
active_raid: horizon_client::mobs::raider::has_active_raid(m),
player_rep: match (villager, player) {
(true, Some(uuid)) => {
horizon_client::mobs::villager::ext(m).map_or(0, |e| e.gossips.reputation(uuid))
}
_ => 0,
},
pushable: m.pushable(),
category: m.category(),
potential_job: horizon_client::mobs::villager_brain::potential_job_site(m),
meeting: (m.species() == Species::Villager)
.then_some(m.extra.meeting)
.flatten(),
profession: m.extra.variant2,
xp: horizon_client::mobs::villager::xp(m),
stats: [
f64::from(m.attrs.max_health),
m.extra.vector[0],
m.attrs.speed,
],
}
m.seen(player)
}
impl Game<'_> {
pub(super) fn player_view(&self) -> Option<PlayerView> {
@@ -967,7 +914,11 @@ impl Game<'_> {
}
MobEvent::CureZombieVillager { mob } => self.cure_zombie_villager(mob),
MobEvent::VillagerMeet { mob, other } => self.villager_meet(mob, other),
MobEvent::VillagerBirth { parent, partner } => self.villager_birth(parent, partner),
MobEvent::VillagerBirth {
parent,
partner,
child,
} => self.villager_birth(parent, partner, child),
MobEvent::GolemCheck { mob, needed } => self.villager_golem_check(mob, needed),
MobEvent::Firework { at, color, flight } => {
self.villager_firework(at, color, flight)
File diff suppressed because it is too large Load Diff
+96 -37
View File
@@ -7,7 +7,7 @@ use horizon_client::{
Result,
items::ItemStack,
lan::{
self, Lan, MAX_PLAYERS,
self, Lan, MAX_PLAYERS, NetConfig,
chunks::ChunkEncoder,
data::SyncData,
entity::EntityState,
@@ -345,6 +345,40 @@ impl Game<'_> {
if self.lan.is_some() || self.remote.is_some() || self.title.is_some() {
return Err("already open".into());
}
let motd = format!("{PLAYER_NAME} - {}", self.level.name);
let host_uuid = self.level.player_uuid.map_or_else(
|| offline_uuid(PLAYER_NAME),
|u| {
u128::from(u[0] as u32) << 96
| u128::from(u[1] as u32) << 64
| u128::from(u[2] as u32) << 32
| u128::from(u[3] as u32)
},
);
let config = HubConfig {
default_game_mode: self.level.mode(),
guest_commands: settings.guest_commands,
force_game_mode: settings.force_game_mode,
hardcore: self.level.hardcore,
view_distance: self.settings.render_distance.clamp(2, 32),
simulation_distance: self.settings.render_distance.clamp(2, 32),
dimension: self.dim.id().to_owned(),
seed: self.level.seed,
max_players: MAX_PLAYERS,
dedicated: false,
};
let net = NetConfig::lan(settings.port, motd, MAX_PLAYERS);
self.lan_host(settings, net, config, Some(host_uuid))
}
/// Start the network side and the play-state hub: for the LAN (with the
/// host's own profile reserved) or for a dedicated server (no host).
pub(super) fn lan_host(
&mut self,
settings: LanSettings,
net: NetConfig,
config: HubConfig,
host: Option<u128>,
) -> Result<()> {
let root = self.options.resources.clone();
let sync = SYNC
.get_or_init(|| SyncData::load(&root).map(Arc::new))
@@ -362,7 +396,7 @@ impl Game<'_> {
.get("minecraft:worldgen/biome")
.map(|v| v.iter().map(|(n, _)| n.clone()).collect())
.unwrap_or_default();
let encoder = ChunkEncoder::new(
let mut encoder = ChunkEncoder::new(
self.res
.facts
.states
@@ -372,37 +406,20 @@ impl Game<'_> {
&biome_names,
&registry,
);
let motd = format!("{PLAYER_NAME} - {}", self.level.name);
let lan = Lan::start(sync.clone(), settings.port, motd, MAX_PLAYERS)?;
let host_uuid = self.level.player_uuid.map_or_else(
|| offline_uuid(PLAYER_NAME),
|u| {
u128::from(u[0] as u32) << 96
| u128::from(u[1] as u32) << 64
| u128::from(u[2] as u32) << 32
| u128::from(u[3] as u32)
},
encoder.tables = Some(
self.save
.tables
.get_or_init(|| Arc::new(horizon_client::save::SaveTables::new(&self.res.assets)))
.clone(),
);
lan.reserve(host_uuid);
let lan = Lan::start_with(sync.clone(), net)?;
if let Some(uuid) = host {
lan.reserve(uuid);
}
let host_uuid = host.unwrap_or(0);
self.next_entity += 1;
let host_entity = self.next_entity as i32;
let hub = Hub::new(
lan,
sync,
encoder,
HubConfig {
default_game_mode: self.level.mode(),
guest_commands: settings.guest_commands,
force_game_mode: settings.force_game_mode,
hardcore: self.level.hardcore,
view_distance: self.settings.render_distance.clamp(2, 32),
simulation_distance: self.settings.render_distance.clamp(2, 32),
dimension: self.dim.id().to_owned(),
seed: self.level.seed,
max_players: MAX_PLAYERS,
dedicated: false,
},
);
let hub = Hub::new(lan, sync, encoder, config);
let port = hub.lan.port;
self.world.block_log = Some(Vec::new());
self.lan = Some(LanHost {
@@ -543,7 +560,9 @@ impl Game<'_> {
let Some(mut host) = self.lan.take() else {
return;
};
if let Some(state) = self.lan_host_state(&host) {
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)
@@ -554,7 +573,7 @@ impl Game<'_> {
let events = {
let mut ctx = TickCtx {
world: &mut self.world,
host: Some(&state),
host: state.as_ref(),
entities: &entities,
next_entity: &mut self.next_entity,
spawn,
@@ -570,18 +589,56 @@ impl Game<'_> {
};
host.hub.tick(&mut ctx)
};
if host.host_mode != state.game_mode {
if let Some(state) = &state
&& host.host_mode != state.game_mode
{
host.host_mode = state.game_mode;
host.hub.set_host_game_mode(state.uuid, state.game_mode);
}
for event in events {
match event {
HostEvent::Joined(conn) => {
self.lan_guest_joined(&mut host, conn, &state, &entities, spawn)
self.lan_guest_joined(&mut host, conn, state.as_ref(), &entities, spawn);
if self.options.dedicated.is_some()
&& let Some(g) = host.hub.guest(conn)
{
// PlayerList.placeNewPlayer, then the broadcast join message.
let [x, y, z] = g.position;
super::dedicated::log(
"INFO",
&format!(
"{}[/{}] logged in with entity id {} at ({}, {}, {})",
g.name,
g.address,
g.entity_id,
super::dedicated::java_double(x),
super::dedicated::java_double(y),
super::dedicated::java_double(z)
),
);
super::dedicated::log(
"INFO",
&format!("System chat: {} joined the game", g.name),
);
}
}
HostEvent::Left(guest) => {
playerdata::save(&guest, &self.world_root);
host.models.remove(&guest.conn);
if self.options.dedicated.is_some() && guest.placed {
super::dedicated::log(
"INFO",
&format!("{} lost connection: {}", guest.name, guest.left_reason),
);
super::dedicated::log(
"INFO",
&format!("System chat: {} left the game", guest.name),
);
}
}
// 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::Packet(conn, packet) => {
@@ -602,7 +659,7 @@ impl Game<'_> {
&mut self,
host: &mut LanHost,
conn: u32,
state: &HostState,
state: Option<&HostState>,
entities: &[EntityState],
spawn: [f64; 3],
) {
@@ -624,7 +681,7 @@ impl Game<'_> {
}
let mut ctx = TickCtx {
world: &mut self.world,
host: Some(state),
host: state,
entities,
next_entity: &mut self.next_entity,
spawn,
@@ -688,7 +745,9 @@ impl Game<'_> {
.guests
.iter()
.filter(|g| g.placed)
.map(|g| (g.chunk(), g.view_distance + 1))
// 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))
.collect();
}
@@ -511,6 +511,21 @@ impl Game<'_> {
/// Commands.performCommand for a guest with command access.
fn guest_command(&mut self, host: &mut LanHost, conn: u32, command: &str) {
// 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"]) {
let me = (self.options.dedicated.is_none() && self.player.is_some())
.then_some((host.host_uuid, super::chat::PLAYER_NAME));
let content = host.hub.list_reply(me, words.len() == 2);
host.hub.send_to(
conn,
&C::SystemChat(play::SystemChat {
content,
overlay: false,
}),
);
return;
}
if !host.settings.guest_commands || !self.cheats {
host.hub.send_to(
conn,
@@ -0,0 +1,93 @@
//! Headless multiplayer client for `tools/test_dedicated_server_parity.py`:
//! with `--server` and `HORIZON_NET_REPORT` set, the client joins without a
//! window, waits until it stands in the world with the chunks around it,
//! sends a chat message and `/list`, collects the chat it is shown, leaves
//! and writes a JSON report (position, chunks, chat lines, whether the
//! server kept it connected throughout).
use super::Game;
use horizon_client::Result;
use serde_json::json;
use std::{
path::Path,
time::{Duration, Instant},
};
impl Game<'_> {
pub(super) fn run_net_harness(&mut self, report: &Path) -> Result<()> {
let deadline = Instant::now() + Duration::from_secs(120);
let mut next = Instant::now();
let mut spawned_at: Option<Instant> = None;
let mut last_chunks = 0;
let mut quiet_since = Instant::now();
let mut step = 0;
let mut step_at = Instant::now();
let mut position = None;
let mut chunks = 0;
let mut error = None;
while Instant::now() < deadline {
self.update_world();
if self.remote.is_none() {
error = Some("disconnected".to_owned());
break;
}
if Instant::now() >= next {
next += Duration::from_millis(50);
self.tick()?;
}
let now = Instant::now();
if let Some(p) = &self.player {
spawned_at.get_or_insert(now);
position.get_or_insert([p.position.x, p.position.y, p.position.z]);
}
let count = self.world.chunks.len();
if count != last_chunks {
last_chunks = count;
quiet_since = now;
}
match step {
0 if spawned_at.is_some()
&& count > 0
&& now - quiet_since > Duration::from_secs(3) =>
{
chunks = count;
self.send_chat("hello from the horizon client");
step = 1;
step_at = now;
}
1 if now - step_at > Duration::from_millis(1500) => {
self.send_chat("/list");
step = 2;
step_at = now;
}
2 if now - step_at > Duration::from_millis(1500) => {
step = 3;
break;
}
_ => {}
}
std::thread::sleep(Duration::from_millis(5));
}
if step < 3 && error.is_none() {
error = Some(format!("timed out at step {step}"));
}
let chat: Vec<String> = self
.remote
.as_ref()
.map(|r| r.chat.iter().map(|(t, _)| t.clone()).collect())
.unwrap_or_default();
if self.remote.is_some() {
self.leave_server(None)?;
}
std::fs::write(
report,
json!({
"position": position,
"chunks": chunks,
"chat": chat,
"error": error,
})
.to_string(),
)?;
Ok(())
}
}
@@ -144,6 +144,7 @@ pub(super) fn player_type(root: &Path) -> Option<Arc<MobType>> {
armor_toughness: 0.0,
knockback_resistance: 0.0,
jump_strength: 0.42,
attributes: Default::default(),
gravity: 0.08,
safe_fall_distance: 3.0,
fall_damage_multiplier: 1.0,
+23 -124
View File
@@ -8,7 +8,6 @@ use horizon_client::{
mobs::{Mob, Species, spawning, villager},
};
use horizon_core::{geometry::Vec3, random::RandomSource};
use std::collections::HashMap;
fn block_of(p: Vec3) -> [i32; 3] {
[p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32]
@@ -59,68 +58,13 @@ impl Game<'_> {
};
let now = self.world.game_time;
let items = &self.res.items;
let max = |item: &str| items.get(item).map_or(64, |i| i.max_stack);
// Villager.gossip: both must be past their cool-down.
let ready = {
let ea = villager::ext(&self.mobs[ia]);
let eb = villager::ext(&self.mobs[ib]);
ea.is_none_or(|e| e.can_gossip(now)) && eb.is_none_or(|e| e.can_gossip(now))
};
let mut golem = false;
if ready {
let source = villager::ext(&self.mobs[ib]).cloned().unwrap_or_default();
let me = &mut self.mobs[ia];
let mut random = me.random.clone();
let e = villager::ext_mut(me);
e.gossips.transfer_from(&source.gossips, &mut random, 10);
e.last_gossip_time = now;
me.random = random;
villager::ext_mut(&mut self.mobs[ib]).last_gossip_time = now;
golem = true;
let meeting = villager::meet(&mut self.mobs, ia, ib, now, |item| {
items.get(item).map_or(64, |i| i.max_stack)
});
for stack in meeting.thrown {
self.villager_throw(meeting.from, meeting.eye, meeting.to, stack);
}
// Surplus food goes to a hungry neighbour (farmers hand it to anyone).
let farmer = villager::is_farmer(&self.mobs[ia]);
let (from, eye, to) = (
self.mobs[ia].position,
self.mobs[ia].eye_y(),
self.mobs[ib].position,
);
let wants_more = villager::ext(&self.mobs[ib]).is_none_or(|e| e.wants_more_food());
let excess = villager::ext(&self.mobs[ia]).is_some_and(|e| e.has_excess_food());
let mut thrown = Vec::new();
if excess
&& (farmer || wants_more)
&& let Some(s) = villager::ext_mut(&mut self.mobs[ia])
.take_half_stack(|s| villager::food_points(&s.item) > 0, max)
{
thrown.push(s);
}
// A farmer's wheat.
if farmer
&& villager::ext(&self.mobs[ia]).is_some_and(|e| e.count_item("minecraft:wheat") > 32)
&& let Some(s) = villager::ext_mut(&mut self.mobs[ia])
.take_half_stack(|s| &*s.item == "minecraft:wheat", max)
{
thrown.push(s);
}
// Wares the neighbour's profession asks for and ours does not.
let theirs = villager::requested_items(&self.mobs[ib]);
let mine = villager::requested_items(&self.mobs[ia]);
let wanted: Vec<&str> = theirs
.iter()
.copied()
.filter(|i| !mine.contains(i))
.collect();
if !wanted.is_empty()
&& let Some(s) = villager::ext_mut(&mut self.mobs[ia])
.take_half_stack(|s| wanted.contains(&&*s.item), max)
{
thrown.push(s);
}
for stack in thrown {
self.villager_throw(from, eye, to, stack);
}
if golem {
if meeting.gossiped {
self.villager_golem_check(a, 5);
}
}
@@ -219,46 +163,39 @@ impl Game<'_> {
/// `VillagerMakeLove.tryToGiveBirth`: both eat, a free bed within 48
/// blocks is taken for the child, who is a baby villager of one of
/// three villager types.
pub(super) fn villager_birth(&mut self, parent: u32, partner: u32) {
pub(super) fn villager_birth(
&mut self,
parent: u32,
partner: u32,
child: Option<([i32; 3], Option<u8>)>,
) {
let (Some(ia), Some(ib)) = (self.villager_index(parent), self.villager_index(partner))
else {
return;
};
villager::ext_mut(&mut self.mobs[ia]).eat_and_digest();
villager::ext_mut(&mut self.mobs[ib]).eat_and_digest();
let from = self.mobs[ia].position;
let angry = |g: &mut Self| {
let Some((bed, variant)) = child else {
for i in [ia, ib] {
let p = g.mobs[i].position;
g.particles_at("angry_villager", [p.x, p.y + 1.8, p.z]);
let p = self.mobs[i].position;
self.particles_at("angry_villager", [p.x, p.y + 1.8, p.z]);
}
};
let Some(bed) = self.take_vacant_bed(block_of(from)) else {
angry(self);
return;
};
// Villager.getBreedOffspring: half the biome's type, a quarter each parent's.
let roll = self.mobs[ia].random.next_double();
let kind_of = |m: &Mob| m.extra.variant;
let facts = self.biome_facts(
from.x.floor() as i32,
from.y.floor() as i32,
from.z.floor() as i32,
);
let variant = if roll < 0.5 {
let variant = variant.unwrap_or_else(|| {
let facts = self.biome_facts(
from.x.floor() as i32,
from.y.floor() as i32,
from.z.floor() as i32,
);
spawning::villager_type(&facts)
} else if roll < 0.75 {
kind_of(&self.mobs[ia])
} else {
kind_of(&self.mobs[ib])
};
});
self.mobs[ib].extra.age = 6000;
let Some(id) =
self.spawn_mob_for("minecraft:villager", [from.x, from.y, from.z], true, true)
else {
return;
};
self.mobs[ia].extra.age = 6000;
self.mobs[ib].extra.age = 6000;
if let Some(child) = self.mobs.iter_mut().find(|m| m.id == id) {
child.extra.variant = variant;
child.extra.variant2 = villager::NONE;
@@ -267,44 +204,6 @@ impl Game<'_> {
}
self.particles_at("heart", [from.x, from.y + 1.8, from.z]);
}
/// `PoiManager.take(HOME, ..., 48)`: the nearest unclaimed bed head.
fn take_vacant_bed(&self, from: [i32; 3]) -> Option<[i32; 3]> {
let claimed: Vec<[i32; 3]> = self
.mobs
.iter()
.filter(|m| m.species() == Species::Villager)
.filter_map(|m| m.extra.bed)
.collect();
let mut known: HashMap<u32, bool> = HashMap::new();
let mut best: Option<(i32, [i32; 3])> = None;
for y in from[1] - 8..=from[1] + 8 {
for z in from[2] - 48..=from[2] + 48 {
for x in from[0] - 48..=from[0] + 48 {
let state = self.world.block(x, y, z);
if self.res.facts.is_air(state) {
continue;
}
let free_head = *known.entry(state.0).or_insert_with(|| {
self.res.facts.get(state).name.ends_with("_bed")
&& self.res.assets.registry.state(state).is_some_and(|s| {
s.properties.get("part").map(String::as_str) == Some("head")
&& s.properties.get("occupied").map(String::as_str)
!= Some("true")
})
});
let d = (x - from[0]).pow(2) + (y - from[1]).pow(2) + (z - from[2]).pow(2);
if free_head
&& d <= 48 * 48
&& !claimed.contains(&[x, y, z])
&& best.is_none_or(|(b, _)| d < b)
{
best = Some((d, [x, y, z]));
}
}
}
}
best.map(|(_, p)| p)
}
fn particles_at(&mut self, kind: &'static str, at: [f64; 3]) {
if let Some(ty) = horizon_client::particles::ParticleType::from_name(kind) {
let options = horizon_client::particles::ParticleOptions::simple(ty);
+9
View File
@@ -110,6 +110,15 @@ impl Gossips {
pub fn clear(&mut self) {
self.map.clear();
}
/// Every (target, type, value) held.
pub fn entries(&self) -> impl Iterator<Item = (Target, GossipType, i32)> + '_ {
self.map.iter().flat_map(|(t, e)| {
GossipType::ALL
.into_iter()
.filter(move |k| e[k.index()] != 0)
.map(move |k| (*t, k, e[k.index()]))
})
}
pub fn get(&self, target: Target, kind: GossipType) -> i32 {
self.map.get(&target).map_or(0, |e| e[kind.index()])
}
+168 -21
View File
@@ -88,6 +88,8 @@ pub struct ChunkEncoder {
biome_bits: u8,
/// The block registry id of each state's block, for BlockEvent.
pub block_ids: Vec<i32>,
/// The save's tables, for the heightmaps.
pub tables: Option<Arc<crate::save::SaveTables>>,
}
impl ChunkEncoder {
/// `biome_names`: the internal biome list in order; `biome_registry`:
@@ -140,6 +142,7 @@ impl ChunkEncoder {
biome_ids,
biome_bits: ceil_log2(biome_registry.len()),
block_ids,
tables: None,
}
}
pub fn entity_type(&self, state: u16) -> Option<i32> {
@@ -194,6 +197,38 @@ impl ChunkEncoder {
}
/// The chunk column with its light and block entities.
/// The non-air sections of a column as bits (LevelChunkSection.hasOnlyAir).
fn occupied(&self, chunk: &Chunk) -> u64 {
let mut bits = 0u64;
for (i, s) in chunk.sections.iter().enumerate() {
let mut unpacked = [0u16; BLOCKS];
s.unpack(&mut unpacked);
let any = unpacked
.iter()
.any(|&v| self.flags.get(usize::from(v)).copied().unwrap_or(0) & NON_AIR != 0);
if any {
bits |= 1 << i;
}
}
bits
}
/// The chunk column with its light and block entities. `world` gives the
/// neighbouring columns, whose sections decide which light layers exist.
pub fn encode_in(&self, chunk: &Chunk, world: &crate::world::World) -> LevelChunkWithLight {
let mut around = 0u64;
for dz in -1..=1 {
for dx in -1..=1 {
if let Some(c) = world.chunks.get(&(chunk.x + dx, chunk.z + dz)) {
around |= self.occupied(c);
}
}
}
let mut packet = self.encode(chunk, &world.block_entities);
packet.light = light_data(chunk, around);
packet
}
pub fn encode(
&self,
chunk: &Chunk,
@@ -215,12 +250,12 @@ impl ChunkEncoder {
packed_xz: ((x << 4) | z) as i8,
y: wy as i16,
kind,
// BlockEntityInfo.create: an empty update tag is not sent.
tag: block_entities
.get(&pos)
.and_then(entity_tag)
.unwrap_or_else(
|| Tag::compound(Vec::<(&str, Tag)>::new()),
),
.or_else(|| saved_update_tag(chunk, pos))
.unwrap_or(Tag::End),
});
}
}
@@ -229,19 +264,118 @@ impl ChunkEncoder {
}
sections.push(encoded);
}
java_hash_order(&mut entity_infos, |e| {
(
chunk.x * 16 + i32::from(e.packed_xz as u8 >> 4),
i32::from(e.y),
chunk.z * 16 + i32::from(e.packed_xz as u8 & 15),
)
});
LevelChunkWithLight {
x: chunk.x,
z: chunk.z,
chunk: ChunkData {
heightmaps: Vec::new(),
heightmaps: self
.tables
.as_ref()
.map(|t| crate::save::client_heightmaps(chunk, t))
.unwrap_or_default(),
buffer: ChunkData::from_sections(&sections),
block_entities: entity_infos,
},
light: light_data(chunk),
light: light_data(chunk, u64::MAX),
}
}
}
/// The order LevelChunk.getBlockEntities() iterates in: a fastutil
/// Object2ObjectOpenHashMap keyed by BlockPos (linear probing from
/// HashCommon.mix(hashCode), grown at 3/4 by reinserting from the top of
/// the table, iterated from the top down), filled in the order of the
/// java.util.HashMap of pending block entities that the loaded chunk's list
/// (`items` in section order) went through.
fn java_hash_order<T>(items: &mut Vec<T>, pos: impl Fn(&T) -> (i32, i32, i32)) {
// Vec3i.hashCode.
let hash = |&(x, y, z): &(i32, i32, i32)| {
y.wrapping_add(z.wrapping_mul(31))
.wrapping_mul(31)
.wrapping_add(x)
};
let keys: Vec<i32> = items.iter().map(|i| hash(&pos(i))).collect();
// java.util.HashMap: buckets in index order, insertion order within one.
let mut capacity = 16usize;
while keys.len() * 4 > capacity * 3 {
capacity *= 2;
}
let mut order: Vec<usize> = (0..keys.len()).collect();
order.sort_by_key(|&i| {
((keys[i] ^ ((keys[i] as u32) >> 16) as i32) as u32 as usize) & (capacity - 1)
});
// Object2ObjectOpenHashMap.
let mix = |h: i32| {
let h = h.wrapping_mul(0x9E37_79B9_u32 as i32) as u32;
(h ^ (h >> 16)) as usize
};
let put = |table: &mut Vec<Option<usize>>, i: usize| {
let mask = table.len() - 1;
let mut at = mix(keys[i]) & mask;
while table[at].is_some() {
at = (at + 1) & mask;
}
table[at] = Some(i);
};
// Default expected size 16: HashCommon.arraySize(16, 0.75) = 32 slots.
let mut table: Vec<Option<usize>> = vec![None; 32];
for (size, &i) in order.iter().enumerate() {
put(&mut table, i);
// insert: `if (size++ >= maxFill) rehash(arraySize(size + 1, f))`.
let max_fill = (table.len() * 3).div_ceil(4).min(table.len() - 1);
if size >= max_fill {
let grown = ((size + 2) * 4).div_ceil(3).next_power_of_two().max(2);
let old = std::mem::replace(&mut table, vec![None; grown]);
for &j in old.iter().rev().flatten() {
put(&mut table, j);
}
}
}
let iteration: Vec<usize> = table.iter().rev().flatten().copied().collect();
let mut slots: Vec<Option<T>> = items.drain(..).map(Some).collect();
items.extend(iteration.into_iter().filter_map(|i| slots[i].take()));
}
/// The update tag of a block entity Horizon keeps only as loaded NBT:
/// SpawnerBlockEntity.getUpdateTag is its saved fields without
/// SpawnPotentials (saveCustomOnly, so no id or position).
fn saved_update_tag(chunk: &Chunk, pos: (i32, i32, i32)) -> Option<Tag> {
let saved = chunk.saved.as_ref()?;
let tag = saved.block_entities.iter().find(|t| {
let Tag::Compound(c) = t else { return false };
let at = |k: &str| match c.get(&k.into()) {
Some(Tag::Int(v)) => Some(*v),
_ => None,
};
(at("x"), at("y"), at("z")) == (Some(pos.0), Some(pos.1), Some(pos.2))
})?;
if crate::block_entity_nbt::id(tag).as_deref() != Some("minecraft:mob_spawner") {
return None;
}
let Tag::Compound(mut c) = crate::block_entity_nbt::canonical(tag)? else {
return None;
};
for key in [
"id",
"x",
"y",
"z",
"keepPacked",
"SpawnPotentials",
"components",
] {
c.remove(&key.into());
}
Some(Tag::Compound(c))
}
/// The update tag of a block entity (getUpdateTag) for what the client shows.
pub fn entity_tag(entity: &BlockEntity) -> Option<Tag> {
match entity {
@@ -251,8 +385,12 @@ pub fn entity_tag(entity: &BlockEntity) -> Option<Tag> {
}
}
/// Light sections run from one below the world to one above it.
fn light_data(chunk: &Chunk) -> LightData {
/// Light sections run from one below the world to one above it. A layer
/// exists where vanilla's light storage keeps one: within one section of a
/// non-air section of this column or a neighbouring one (`around`, bit i for
/// section i; LayerLightSectionStorage.updateSectionStatus). An existing
/// layer is sent, or marked empty when all dark; the others are left out.
fn light_data(chunk: &Chunk, around: u64) -> LightData {
let mut data = LightData {
sky_mask: Vec::new(),
block_mask: Vec::new(),
@@ -261,14 +399,24 @@ fn light_data(chunk: &Chunk) -> LightData {
sky: Vec::new(),
block: Vec::new(),
};
// The section below the world has no sky light; the one above is full.
set_bit(&mut data.empty_sky_mask, 0);
set_bit(&mut data.empty_block_mask, 0);
for (i, s) in chunk.sections.iter().enumerate() {
let bit = i + 1;
// Light section b holds chunk section b - 1.
let exists = |b: usize| {
(b.saturating_sub(2)..=b.min(SECTIONS - 1)).any(|s| s + 2 >= b && around >> s & 1 != 0)
};
let full_sky = Light::Uniform(0xF0);
for b in 0..SECTIONS + 2 {
if !exists(b) {
continue;
}
let light = match b {
// Below the world nothing is lit; above it the sky is full.
0 => &Light::Uniform(0),
_ if b == SECTIONS + 1 => &full_sky,
_ => &chunk.sections[b - 1].light,
};
let (mut sky, mut block) = (vec![0u8; 2048], vec![0u8; 2048]);
let (mut sky_any, mut block_any) = (false, false);
match &s.light {
match light {
Light::Uniform(v) => {
let (sk, bl) = (v >> 4, v & 15);
sky_any = sk != 0;
@@ -293,21 +441,18 @@ fn light_data(chunk: &Chunk) -> LightData {
}
}
if sky_any {
set_bit(&mut data.sky_mask, bit);
set_bit(&mut data.sky_mask, b);
data.sky.push(sky);
} else {
set_bit(&mut data.empty_sky_mask, bit);
set_bit(&mut data.empty_sky_mask, b);
}
if block_any {
set_bit(&mut data.block_mask, bit);
set_bit(&mut data.block_mask, b);
data.block.push(block);
} else {
set_bit(&mut data.empty_block_mask, bit);
set_bit(&mut data.empty_block_mask, b);
}
}
set_bit(&mut data.sky_mask, SECTIONS + 1);
data.sky.push(vec![0xFF; 2048]);
set_bit(&mut data.empty_block_mask, SECTIONS + 1);
data
}
@@ -335,7 +480,9 @@ mod tests {
#[test]
fn light_masks_cover_the_world_plus_borders() {
let chunk = Chunk::empty(0, 0);
let data = light_data(&chunk);
// A column with nothing around it has no light layers at all.
assert!(light_data(&chunk, 0).sky.is_empty());
let data = light_data(&chunk, u64::MAX);
// Default sections are full sky light and no block light.
assert_eq!(data.sky.len(), SECTIONS + 1);
assert_eq!(data.block.len(), 0);
+205 -23
View File
@@ -35,16 +35,88 @@ const KEEP_ALIVE_EVERY: Duration = Duration::from_secs(15);
const KEEP_ALIVE_TIMEOUT: Duration = Duration::from_secs(30);
/// Packets queued for one client beyond this many bytes disconnect it.
const MAX_PENDING: usize = 96 << 20;
/// Connection.setupCompression threshold of the integrated server.
const COMPRESSION_THRESHOLD: i32 = 256;
/// Vanilla's server-side disconnect during login is a JSON component.
fn login_disconnect(c: &mut Connection, key: &str) {
let json = format!("{{\"translate\":\"{key}\"}}");
fn login_disconnect(c: &mut Connection, reason: &horizon_world::nbt::Tag) {
let json = component_json(reason);
let _ =
c.send(&login::Clientbound::Disconnect(login::Disconnect { reason_json: json }).encode());
}
/// A component as ComponentSerialization.CODEC writes it with JsonOps (and
/// Gson without HTML escaping): plain text collapses to a string, the
/// content fields come first, then `extra`, then the style.
pub fn component_json(tag: &horizon_world::nbt::Tag) -> String {
component_value(tag).compact()
}
fn component_value(tag: &horizon_world::nbt::Tag) -> crate::server::json::Json {
use crate::server::json::Json;
use horizon_world::nbt::Tag;
const ORDER: &[&str] = &[
"type",
"text",
"translate",
"fallback",
"with",
"score",
"selector",
"separator",
"keybind",
"nbt",
"interpret",
"block",
"entity",
"storage",
"source",
"object",
"sprite",
"atlas",
"player",
"hat",
"extra",
"color",
"shadow_color",
"bold",
"italic",
"underlined",
"strikethrough",
"obfuscated",
"click_event",
"hover_event",
"insertion",
"font",
];
match tag {
Tag::String(s) => Json::String(s.to_string_lossy()),
Tag::List(items) => Json::Array(items.iter().map(component_value).collect()),
Tag::Compound(map) => {
if map.len() == 1
&& let Some(Tag::String(t)) = map.get(&horizon_world::nbt::JavaString::from("text"))
{
return Json::String(t.to_string_lossy());
}
let mut keys: Vec<String> = map.keys().map(|k| k.to_string_lossy()).collect();
keys.sort_by_key(|k| ORDER.iter().position(|o| o == k).unwrap_or(ORDER.len()));
Json::Object(
keys.into_iter()
.map(|k| {
let v = &map[&horizon_world::nbt::JavaString::from(k.as_str())];
let value = match v {
Tag::Byte(b) => Json::Bool(*b != 0),
Tag::Int(i) => Json::Number(i.to_string()),
other => component_value(other),
};
(k, value)
})
.collect(),
)
}
Tag::Byte(b) => Json::Bool(*b != 0),
Tag::Int(i) => Json::Number(i.to_string()),
Tag::Long(i) => Json::Number(i.to_string()),
_ => Json::Null,
}
}
/// StringUtil.isValidPlayerName.
pub fn valid_name(name: &str) -> bool {
(1..=16).contains(&name.len()) && name.chars().all(|c| c as u32 > 32 && (c as u32) < 127)
@@ -63,8 +135,88 @@ impl PlayerSender {
}
}
pub fn serve(stream: TcpStream, shared: Arc<Shared>) -> Result<(), String> {
/// LegacyQueryHandler: the pre-1.7 server list ping. What the first read
/// holds decides the reply (1.3 and older: no more bytes; 1.4 and 1.5: 0x01;
/// 1.6: 0x01 then the MC|PingHost payload); anything else gets no reply.
fn serve_legacy(mut stream: TcpStream, shared: &Shared) -> Result<(), String> {
use std::io::{Read, Write};
let _ = stream.set_read_timeout(Some(Duration::from_millis(100)));
let mut data = Vec::new();
let mut chunk = [0u8; 1024];
// The bytes of the first read: what arrived together.
if let Ok(n) = stream.read(&mut chunk) {
data.extend_from_slice(&chunk[..n]);
}
let in_string = |d: &[u8], at: &mut usize| -> Option<String> {
let len = usize::from(u16::from_be_bytes([*d.get(*at)?, *d.get(*at + 1)?]));
let bytes = d.get(*at + 2..*at + 2 + len * 2)?;
*at += 2 + len * 2;
Some(String::from_utf16_lossy(
&bytes
.chunks(2)
.map(|c| u16::from_be_bytes([c[0], c[1]]))
.collect::<Vec<_>>(),
))
};
let motd = shared.motd();
let (online, max) = (shared.online(), shared.max_players());
let body = if data.len() == 1 {
format!("{motd}\u{a7}{online}\u{a7}{max}")
} else {
if data[1] != 1 {
return Ok(());
}
if data.len() > 2 {
// readCustomPayloadPacket.
let mut at = 3;
let valid = data[2] == 0xFA
&& in_string(&data, &mut at).as_deref() == Some("MC|PingHost")
&& data
.get(at..at + 2)
.map(|b| usize::from(u16::from_be_bytes([b[0], b[1]])))
== Some(data.len().saturating_sub(at + 2))
&& {
at += 2;
data.get(at).is_some_and(|v| *v >= 73)
}
&& {
at += 1;
in_string(&data, &mut at).is_some()
}
&& data
.get(at..at + 4)
.is_some_and(|b| i32::from_be_bytes([b[0], b[1], b[2], b[3]]) <= 65535);
if !valid {
return Ok(());
}
}
format!("\u{a7}1\0127\026.3\0{motd}\0{online}\0{max}")
};
let units: Vec<u16> = body.encode_utf16().collect();
let mut out = vec![0xFF];
out.extend_from_slice(&(units.len() as u16).to_be_bytes());
for u in units {
out.extend_from_slice(&u.to_be_bytes());
}
stream.write_all(&out).map_err(|e| e.to_string())?;
let _ = stream.shutdown(std::net::Shutdown::Both);
Ok(())
}
pub fn serve(
stream: TcpStream,
address: std::net::SocketAddr,
shared: Arc<Shared>,
) -> Result<(), String> {
let e = |e: horizon_protocol::Error| e.to_string();
// LegacyQueryHandler, ahead of the frame decoder while status is on.
let mut first = [0u8; 1];
if shared.config.enable_status
&& stream.peek(&mut first).is_ok_and(|n| n == 1)
&& first[0] == 0xFE
{
return serve_legacy(stream, &shared);
}
let mut c = Connection::from_stream(stream).map_err(e)?;
c.reader
.set_read_timeout(Some(Duration::from_secs(30)))
@@ -75,10 +227,20 @@ pub fn serve(stream: TcpStream, shared: Arc<Shared>) -> Result<(), String> {
_ => return Err("expected a handshake".into()),
};
match intention.intent {
// ServerHandshakePacketListenerImpl: a server that does not reply
// to status requests closes the connection.
handshake::STATUS if !shared.config.enable_status => Ok(()),
handshake::STATUS => serve_status(&mut c, &shared),
handshake::TRANSFER if !shared.config.accepts_transfers => {
login_disconnect(
&mut c,
&translatable("multiplayer.disconnect.transfers_disabled", &[]),
);
Ok(())
}
handshake::LOGIN | handshake::TRANSFER => {
if intention.protocol != PROTOCOL_VERSION {
let key = if intention.protocol < PROTOCOL_VERSION {
let key = if intention.protocol < 754 {
"multiplayer.disconnect.outdated_client"
} else {
"multiplayer.disconnect.incompatible"
@@ -93,7 +255,7 @@ pub fn serve(stream: TcpStream, shared: Arc<Shared>) -> Result<(), String> {
);
return Ok(());
}
serve_login(c, &shared)
serve_login(c, address, &shared)
}
other => Err(format!("unknown intent {other}")),
}
@@ -101,10 +263,14 @@ pub fn serve(stream: TcpStream, shared: Arc<Shared>) -> Result<(), String> {
fn serve_status(c: &mut Connection, shared: &Shared) -> Result<(), String> {
let e = |e: horizon_protocol::Error| e.to_string();
let mut requested = false;
loop {
let (id, payload) = c.recv().map_err(e)?;
match status::Serverbound::decode(id, &payload).map_err(e)? {
// ServerStatusPacketListenerImpl: a second request disconnects.
status::Serverbound::StatusRequest(_) if requested => return Ok(()),
status::Serverbound::StatusRequest(_) => {
requested = true;
let json = shared.status_json();
c.send(
&status::Clientbound::StatusResponse(status::StatusResponse { json }).encode(),
@@ -121,7 +287,11 @@ fn serve_status(c: &mut Connection, shared: &Shared) -> Result<(), String> {
}
}
fn serve_login(mut c: Connection, shared: &Arc<Shared>) -> Result<(), String> {
fn serve_login(
mut c: Connection,
address: std::net::SocketAddr,
shared: &Arc<Shared>,
) -> Result<(), String> {
let e = |e: horizon_protocol::Error| e.to_string();
let (id, payload) = c.recv().map_err(e)?;
let hello = match login::Serverbound::decode(id, &payload).map_err(e)? {
@@ -129,20 +299,23 @@ fn serve_login(mut c: Connection, shared: &Arc<Shared>) -> Result<(), String> {
_ => return Err("expected a login hello".into()),
};
if !valid_name(&hello.name) {
login_disconnect(&mut c, "multiplayer.disconnect.invalid_name");
login_disconnect(
&mut c,
&translatable("multiplayer.disconnect.invalid_name", &[]),
);
return Ok(());
}
// Offline mode: the profile is derived from the name (PlayerList.canPlayerLogin
// then rejects duplicates and a full server).
let uuid = offline_uuid(&hello.name);
if let Some(reason) = shared.try_admit(uuid, &hello.name) {
login_disconnect(&mut c, reason);
if let Some(reason) = shared.try_admit(address, uuid, &hello.name) {
login_disconnect(&mut c, &reason);
return Ok(());
}
let result = login_and_configure(&mut c, shared, uuid, &hello.name);
match result {
Ok(Some(parts)) => {
play(c, shared, parts);
play(c, shared, parts, address);
Ok(())
}
Ok(None) => {
@@ -170,14 +343,12 @@ fn login_and_configure(
name: &str,
) -> Result<Option<Parts>, String> {
let e = |e: horizon_protocol::Error| e.to_string();
c.send(
&login::Clientbound::Compression(login::Compression {
threshold: COMPRESSION_THRESHOLD,
})
.encode(),
)
.map_err(e)?;
c.set_compression(COMPRESSION_THRESHOLD);
let threshold = shared.config.compression_threshold;
if threshold >= 0 {
c.send(&login::Clientbound::Compression(login::Compression { threshold }).encode())
.map_err(e)?;
c.set_compression(threshold);
}
c.send(
&login::Clientbound::LoginFinished(login::LoginFinished {
profile: login::GameProfile {
@@ -208,7 +379,8 @@ fn login_and_configure(
channel: "minecraft:brand".into(),
data: {
let mut w = horizon_protocol::buf::Writer::new();
w.string("horizon");
// MinecraftServer.getServerModName.
w.string("vanilla");
w.data
},
}),
@@ -266,7 +438,7 @@ fn login_and_configure(
}))
}
fn play(c: Connection, shared: &Arc<Shared>, parts: Parts) {
fn play(c: Connection, shared: &Arc<Shared>, parts: Parts, address: std::net::SocketAddr) {
let conn_id = shared.next_id();
let events = shared.events.clone();
let _ = c.reader.set_read_timeout(Some(KEEP_ALIVE_TIMEOUT));
@@ -294,6 +466,7 @@ fn play(c: Connection, shared: &Arc<Shared>, parts: Parts) {
brand: parts.brand,
sender,
latency,
address,
};
let reason = if events.send(NetEvent::Joined(Box::new(joined))).is_ok() {
read_loop(&mut reader, conn_id, &events, &alive)
@@ -317,6 +490,15 @@ fn read_loop(
loop {
let (id, payload) = match reader.recv() {
Ok(p) => p,
// The client closed the connection: Connection.channelInactive
// without details, multiplayer.disconnect.generic.
Err(e)
if e.0 == "Connection closed by the server"
|| e.0.contains("reset by peer")
|| e.0.contains("aborted") =>
{
return "Disconnected".to_owned();
}
Err(e) => return e.to_string(),
};
match play::Serverbound::decode(id, &payload) {
+58 -35
View File
@@ -10,34 +10,61 @@ use std::{
atomic::{AtomicBool, Ordering},
},
thread::JoinHandle,
time::{Duration, Instant},
time::Duration,
};
pub const GROUP: Ipv4Addr = Ipv4Addr::new(224, 0, 2, 60);
pub const PORT: u16 = 4445;
/// LanServerPinger sleeps 1500 ms between announcements.
const INTERVAL: Duration = Duration::from_millis(1500);
/// LanServerDetection.LanServerList drops entries not refreshed for 5 s.
const EXPIRY: Duration = Duration::from_secs(5);
/// LanServerPinger.createPingString.
pub fn ping_string(motd: &str, port: u16) -> String {
format!("[MOTD]{motd}[/MOTD][AD]{port}[/AD]")
ping_string_text(motd, &port.to_string())
}
fn between<'a>(s: &'a str, open: &str, close: &str) -> Option<&'a str> {
let start = s.find(open)? + open.len();
let end = s[start..].find(close)? + start;
Some(&s[start..end])
/// LanServerPinger.createPingString with the address as text.
pub fn ping_string_text(motd: &str, address: &str) -> String {
format!("[MOTD]{motd}[/MOTD][AD]{address}[/AD]")
}
/// LanServerPinger.parseMotd; vanilla shows "missing no" when absent.
/// String.indexOf(needle, from) on a Rust string (byte offsets).
fn index_of(s: &str, needle: &str, from: usize) -> Option<usize> {
s.get(from..)?.find(needle).map(|i| i + from)
}
/// LanServerPinger.parseMotd; "missing no" when there is none.
pub fn parse_motd(s: &str) -> String {
between(s, "[MOTD]", "[/MOTD]")
.unwrap_or("missing no")
.to_owned()
let Some(start) = s.find("[MOTD]") else {
return "missing no".to_owned();
};
match index_of(s, "[/MOTD]", start + "[MOTD]".len()) {
Some(end) => s[start + "[MOTD]".len()..end].to_owned(),
None => "missing no".to_owned(),
}
}
/// LanServerPinger.parseAddress: the announced port, if present and valid.
pub fn parse_port(s: &str) -> Option<u16> {
between(s, "[AD]", "[/AD]")?.parse().ok().filter(|p| *p > 0)
/// LanServerPinger.parseAddress: the text between [AD] and [/AD] after the
/// only [/MOTD], as announced (vanilla does not check it is a port).
pub fn parse_address(s: &str) -> Option<String> {
let end_motd = s.find("[/MOTD]")?;
if index_of(s, "[/MOTD]", end_motd + "[/MOTD]".len()).is_some() {
return None;
}
let start = index_of(s, "[AD]", end_motd + "[/MOTD]".len())?;
let end = index_of(s, "[/AD]", start + "[AD]".len())?;
Some(s[start + "[AD]".len()..end].to_owned())
}
/// LanServerDetection.LanServerList.addServer: an announcement from `ip`.
/// A new address joins the list; a known one keeps its first MOTD. True
/// when the list changed.
pub fn add_server(games: &mut Vec<LanGame>, ping: &str, ip: &str) -> bool {
let motd = parse_motd(ping);
let Some(address) = parse_address(ping) else {
return false;
};
let address = format!("{ip}:{address}");
if games.iter().any(|g| g.address == address) {
return false;
}
games.push(LanGame { motd, address });
true
}
/// Announces one hosted world until dropped.
@@ -48,7 +75,6 @@ pub struct Pinger {
impl Pinger {
pub fn start(motd: String, port: u16) -> io::Result<Self> {
let socket = UdpSocket::bind(("0.0.0.0", 0))?;
let _ = socket.set_multicast_ttl_v4(4);
let stop = Arc::new(AtomicBool::new(false));
let flag = stop.clone();
let message = ping_string(&motd, port);
@@ -86,7 +112,7 @@ pub struct LanGame {
pub motd: String,
pub address: String,
}
type Games = Arc<Mutex<Vec<(LanGame, Instant)>>>;
type Games = Arc<Mutex<Vec<LanGame>>>;
/// Listens for announcements until the last clone is dropped.
#[derive(Clone, Debug)]
@@ -118,11 +144,10 @@ impl Scanner {
inner: Arc::new(ScanInner { games, stop }),
}
}
/// The live announcements, oldest first.
/// The worlds announced since the scan started, in order (vanilla's
/// list keeps them while the multiplayer screen is open).
pub fn games(&self) -> Vec<LanGame> {
let mut games = self.inner.games.lock().unwrap();
games.retain(|(_, seen)| seen.elapsed() < EXPIRY);
games.iter().map(|(g, _)| g.clone()).collect()
self.inner.games.lock().unwrap().clone()
}
}
fn bind_listener() -> io::Result<UdpSocket> {
@@ -138,18 +163,7 @@ fn listen(socket: UdpSocket, games: Games, stop: Arc<AtomicBool>) {
continue;
};
let text = String::from_utf8_lossy(&buf[..n]);
let Some(port) = parse_port(&text) else {
continue;
};
let game = LanGame {
motd: parse_motd(&text),
address: format!("{}:{port}", from.ip()),
};
let mut games = games.lock().unwrap();
match games.iter_mut().find(|(g, _)| g.address == game.address) {
Some(entry) => *entry = (game, Instant::now()),
None => games.push((game, Instant::now())),
}
add_server(&mut games.lock().unwrap(), &text, &from.ip().to_string());
}
}
@@ -162,8 +176,17 @@ mod tests {
let s = ping_string("Steve - World", 25565);
assert_eq!(s, "[MOTD]Steve - World[/MOTD][AD]25565[/AD]");
assert_eq!(parse_motd(&s), "Steve - World");
assert_eq!(parse_port(&s), Some(25565));
assert_eq!(parse_port("[AD]0[/AD]"), None);
assert_eq!(parse_address(&s).as_deref(), Some("25565"));
assert_eq!(parse_address("[AD]1[/AD]"), None);
assert_eq!(parse_address("[/MOTD][AD]x[/AD][/MOTD]"), None);
assert_eq!(parse_motd("junk"), "missing no");
let mut games = Vec::new();
assert!(add_server(&mut games, &s, "10.0.0.2"));
assert!(!add_server(
&mut games,
&ping_string("Other", 25565),
"10.0.0.2"
));
assert_eq!(games[0].motd, "Steve - World");
}
}
+20
View File
@@ -20,6 +20,20 @@ pub const SPECTATOR: i32 = 3;
pub struct Guest {
pub conn: u32,
/// The client's address (IP bans, `list`).
pub address: std::net::SocketAddr,
/// The hub tick of the player's last action (ServerPlayer.lastActionTime),
/// for player-idle-timeout.
pub last_action_tick: u64,
/// The next ClientboundPlayerChatPacket.globalIndex for this connection.
pub chat_index: i32,
/// 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,
/// The chunk cache centre placeNewPlayer already sent.
pub center_sent: Option<(i32, i32)>,
/// Why the connection closed (the console's "lost connection").
pub left_reason: String,
pub uuid: u128,
pub name: String,
pub entity_id: i32,
@@ -97,6 +111,12 @@ impl Guest {
pub fn new(j: Joined, entity_id: i32, position: [f64; 3], view_distance: i32) -> Self {
Self {
conn: j.conn,
address: j.address,
last_action_tick: 0,
chat_index: 0,
placed_at: 0,
center_sent: None,
left_reason: String::new(),
uuid: j.uuid,
name: j.name,
entity_id,
+248 -27
View File
@@ -126,6 +126,54 @@ pub fn yellow_translation(key: &str, args: &[&str]) -> Tag {
t
}
/// Player.getDisplayName for a player in no team: the name, suggesting
/// `/tell NAME `, showing the player on hover and inserting the name.
pub fn display_name(uuid: u128, name: &str) -> Tag {
let words = [
(uuid >> 96) as i32,
(uuid >> 64) as i32,
(uuid >> 32) as i32,
uuid as i32,
];
Tag::compound([
("text", string(name)),
(
"click_event",
Tag::compound([
("action", string("suggest_command")),
("command", string(&format!("/tell {name} "))),
]),
),
(
"hover_event",
Tag::compound([
("action", string("show_entity")),
("id", string("minecraft:player")),
("uuid", Tag::IntArray(words.to_vec())),
("name", string(name)),
]),
),
("insertion", string(name)),
])
}
/// A yellow translation of player names (`multiplayer.player.joined`).
fn yellow_names(key: &str, names: Vec<Tag>) -> Tag {
Tag::compound([
("translate", string(key)),
("with", Tag::List(names)),
("color", string("yellow")),
])
}
/// ChunkTrackingView.contains: the chunks a player at (cx, cz) with view
/// distance `r` is sent (isWithinDistance with the neighbours' buffer).
fn tracked(cx: i32, cz: i32, r: i32, x: i32, z: i32) -> bool {
let dx = i64::from(((x - cx).abs() - 2).max(0));
let dz = i64::from(((z - cz).abs() - 2).max(0));
dx * dx + dz * dz < i64::from(r) * i64::from(r)
}
impl Hub {
pub fn new(lan: Lan, sync: Arc<SyncData>, encoder: ChunkEncoder, config: HubConfig) -> Self {
let chat_type = sync
@@ -214,19 +262,123 @@ impl Hub {
overlay: false,
}));
}
/// A chat message from `sender` (PlayerChatMessage as a disguised chat).
/// A chat message from the host (a disguised chat: the host has no
/// connection to sign with).
pub fn chat(&self, sender: &str, text: &str) {
self.broadcast(&self.chat_packet(sender, text));
}
fn chat_packet(&self, sender: &str, text: &str) -> C {
C::DisguisedChat(play::DisguisedChat {
self.broadcast(&C::DisguisedChat(play::DisguisedChat {
message: literal(text),
chat_type: play::ChatTypeBound {
chat_type: self.chat_type,
name: literal(sender),
target: None,
},
})
}));
}
/// ListPlayersCommand's reply: the players in join order (the host of a
/// LAN world first), as display names or names with ids, joined by
/// gray commas (ComponentUtils.formatList).
pub fn list_reply(&self, host: Option<(u128, &str)>, uuids: bool) -> Tag {
let players: Vec<(u128, &str)> = host
.into_iter()
.chain(
self.guests
.iter()
.filter(|g| g.placed)
.map(|g| (g.uuid, g.name.as_str())),
)
.collect();
let format = |(uuid, name): (u128, &str)| {
if uuids {
Tag::compound([
("translate", string("commands.list.nameAndId")),
(
"with",
Tag::List(vec![
string(name),
string(&horizon_protocol::crypto::uuid_string(uuid)),
]),
),
])
} else {
display_name(uuid, name)
}
};
let names = match players.len() {
0 => string(""),
1 => format(players[0]),
_ => {
let mut extra = Vec::new();
for (k, p) in players.iter().enumerate() {
if k > 0 {
extra.push(Tag::compound([
("text", string(", ")),
("color", string("gray")),
]));
}
extra.push(format(*p));
}
Tag::compound([("text", string("")), ("extra", Tag::List(extra))])
}
};
Tag::compound([
("translate", string("commands.list.players")),
(
"with",
Tag::List(vec![
Tag::Int(players.len() as i32),
Tag::Int(self.lan.shared.max_players() as i32),
names,
]),
),
])
}
/// SayCommand from a source without a player: a disguised chat of type
/// say_command named after the source.
pub fn say(&self, source: &str, text: &str) {
let chat_type = self
.sync
.id("minecraft:chat_type", "minecraft:say_command")
.unwrap_or(self.chat_type);
self.broadcast(&C::DisguisedChat(play::DisguisedChat {
message: literal(text),
chat_type: play::ChatTypeBound {
chat_type,
name: literal(source),
target: None,
},
}));
}
/// 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).
@@ -275,6 +427,7 @@ impl Hub {
*ctx.next_entity += 1;
let conn = j.conn;
let mut guest = Guest::new(j, entity_id, ctx.spawn, self.config.view_distance);
guest.last_action_tick = self.ticks;
guest.game_mode = self.config.default_game_mode;
guest.permission = self.default_permission(guest.uuid);
guest.joined_tick = self.ticks;
@@ -356,7 +509,10 @@ impl Hub {
self.broadcast_except(
conn,
&C::SystemChat(play::SystemChat {
content: yellow_translation("multiplayer.player.joined", &[&name]),
content: yellow_names(
"multiplayer.player.joined",
vec![display_name(self.guests[i].uuid, &name)],
),
overlay: false,
}),
);
@@ -365,7 +521,7 @@ impl Hub {
let g = &self.guests[i];
g.send(&C::ServerData(play::ServerData {
motd: literal(&self.lan.shared.motd()),
icon: None,
icon: self.lan.shared.config.favicon.clone(),
}));
// The player list: everyone already here, then the newcomer to all.
let mut entries = Vec::new();
@@ -390,6 +546,15 @@ impl Hub {
};
self.broadcast(&C::PlayerInfoUpdate(newcomer));
self.send_level_info(i, ctx);
// ServerLevel.addNewPlayer: the chunk tracking starts at the player.
let g = &mut self.guests[i];
let (cx, cz) = g.chunk();
g.send(&C::SetChunkCacheCenter(play::SetChunkCacheCenter {
x: cx,
z: cz,
}));
g.center_sent = Some((cx, cz));
g.placed_at = self.ticks;
// ServerPlayer.sendPostEffects and initInventoryMenu.
self.guests[i].send(&raw(ids::POST_EFFECTS, vec![0]));
self.send_inventory(i);
@@ -409,9 +574,7 @@ impl Hub {
/// The permissions changed: tell everyone their level and commands again.
pub fn resend_commands(&mut self) {
for i in 0..self.guests.len() {
if !self.config.dedicated {
self.guests[i].permission = self.default_permission(self.guests[i].uuid);
}
self.guests[i].permission = self.default_permission(self.guests[i].uuid);
if self.guests[i].placed {
self.send_permission_level(i);
}
@@ -586,6 +749,20 @@ impl Hub {
g.inbox.push_back(*packet);
}
}
NetEvent::Duplicate(uuid) => {
let conns: Vec<u32> = self
.guests
.iter()
.filter(|g| g.uuid == uuid)
.map(|g| g.conn)
.collect();
for conn in conns {
self.kick(
conn,
translatable("multiplayer.disconnect.duplicate_login", &[]),
);
}
}
}
}
for i in 0..self.guests.len() {
@@ -639,7 +816,8 @@ impl Hub {
}
fn remove_guest(&mut self, i: usize, reason: &str) -> Guest {
let g = self.guests.remove(i);
let mut g = self.guests.remove(i);
g.left_reason = reason.to_owned();
if std::env::var_os("HORIZON_NET_DEBUG").is_some() {
eprintln!("[lan] {} left: {reason}", g.name);
}
@@ -652,7 +830,10 @@ impl Hub {
self.broadcast(&C::RemoveEntities(play::RemoveEntities {
ids: vec![g.entity_id],
}));
self.system_message(yellow_translation("multiplayer.player.left", &[&g.name]));
self.system_message(yellow_names(
"multiplayer.player.left",
vec![display_name(g.uuid, &g.name)],
));
g
}
@@ -729,27 +910,31 @@ impl Hub {
let g = &mut self.guests[i];
if g.center != Some((cx, cz)) {
g.center = Some((cx, cz));
g.send(&C::SetChunkCacheCenter(play::SetChunkCacheCenter {
x: cx,
z: cz,
}));
if g.center_sent.take() != Some((cx, cz)) {
g.send(&C::SetChunkCacheCenter(play::SetChunkCacheCenter {
x: cx,
z: cz,
}));
}
// Chunks that left the view.
let forget: Vec<_> = g
.sent_chunks
.iter()
.copied()
.filter(|&(x, z)| (x - cx).abs().max((z - cz).abs()) > r)
.filter(|&(x, z)| !tracked(cx, cz, r, x, z))
.collect();
for (x, z) in forget {
g.sent_chunks.remove(&(x, z));
g.send(&C::ForgetLevelChunk(play::ForgetLevelChunk { pos: [x, z] }));
}
g.chunk_queue
.retain(|&(x, z)| (x - cx).abs().max((z - cz).abs()) <= r);
for dz in -r..=r {
for dx in -r..=r {
g.chunk_queue.retain(|&(x, z)| tracked(cx, cz, r, x, z));
for dz in -r - 2..=r + 2 {
for dx in -r - 2..=r + 2 {
let key = (cx + dx, cz + dz);
if !g.sent_chunks.contains(&key) && !g.chunk_queue.contains(&key) {
if tracked(cx, cz, r, key.0, key.1)
&& !g.sent_chunks.contains(&key)
&& !g.chunk_queue.contains(&key)
{
g.chunk_queue.push(key);
}
}
@@ -758,7 +943,7 @@ impl Hub {
.sort_by_key(|&(x, z)| i64::from(x - cx).pow(2) + i64::from(z - cz).pow(2));
}
// Send ready chunks, closest first, in batches.
if g.chunk_queue.is_empty() || g.unacknowledged >= 10 {
if g.chunk_queue.is_empty() || g.unacknowledged >= 10 || self.ticks <= g.placed_at + 1 {
return;
}
g.chunk_credit = (g.chunk_credit + g.chunks_per_tick).min(g.chunks_per_tick.max(1.0) * 2.0);
@@ -779,7 +964,7 @@ impl Hub {
continue;
}
packets.push(C::LevelChunkWithLight(
self.encoder.encode(chunk, &ctx.world.block_entities),
self.encoder.encode_in(chunk, ctx.world),
));
taken.push(idx);
}
@@ -806,7 +991,7 @@ impl Hub {
let Some(chunk) = world.chunks.get(&(x, z)) else {
return;
};
let packet = C::LevelChunkWithLight(self.encoder.encode(chunk, &world.block_entities));
let packet = C::LevelChunkWithLight(self.encoder.encode_in(chunk, world));
let body = packet.encode();
for g in self
.guests
@@ -1092,6 +1277,15 @@ impl Hub {
/// ServerPlayer.doTick: health, food, experience and the inventory menu.
fn sync_player_state(&mut self, i: usize) {
// 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() {
let g = &self.guests[i];
g.send(&C::SetEntityData(play::SetEntityData {
id: g.entity_id,
values: vec![(9, serializer::FLOAT, Value::Float(g.health))],
}));
}
let health = {
let g = &self.guests[i];
(g.health, g.food, g.saturation)
@@ -1142,6 +1336,13 @@ impl Hub {
// ---- incoming ------------------------------------------------------
/// The squared movement past 1.0E-5F (handlePlayerKnownMovement).
fn moved_far(&self, i: usize, to: [f64; 3]) -> bool {
let from = self.guests[i].position;
let d: f64 = (0..3).map(|k| (to[k] - from[k]).powi(2)).sum();
d > f64::from(1.0E-5_f32)
}
fn process_inbox(&mut self, i: usize, ctx: &mut TickCtx, events: &mut Vec<HostEvent>) {
let mut budget = 400;
while budget > 0 {
@@ -1150,6 +1351,26 @@ impl Hub {
};
budget -= 1;
let conn = self.guests[i].conn;
// ServerPlayer.resetLastActionTime: every handler of a player's
// own action resets it, movement only when it moved
// (handlePlayerKnownMovement), PlayerInput once loaded.
let acted = match &packet {
S::AcceptTeleportation(_)
| S::MovePlayerStatus(_)
| S::MovePlayerRot(_)
| S::PlayerLoaded(_)
| S::ChunkBatchReceived(_)
| S::ClientInformation(_)
| S::ClientTickEnd(_)
| S::KeepAlive(_) => false,
S::MovePlayerPos(p) => self.moved_far(i, [p.x, p.y, p.z]),
S::MovePlayerPosRot(p) => self.moved_far(i, [p.x, p.y, p.z]),
S::PlayerInput(_) => self.guests[i].loaded,
_ => true,
};
if acted {
self.guests[i].last_action_tick = self.ticks;
}
match packet {
S::AcceptTeleportation(p) => {
let g = &mut self.guests[i];
@@ -1202,7 +1423,7 @@ impl Hub {
let text: String = c.message.chars().filter(|c| !c.is_control()).collect();
if !text.is_empty() {
let name = self.guests[i].name.clone();
self.chat(&name, &text);
self.player_chat(i, &text);
events.push(HostEvent::Chat(format!("<{name}> {text}")));
}
}
+228 -29
View File
@@ -20,14 +20,17 @@ pub mod tracking;
pub use conn::PlayerSender;
use horizon_protocol::packets::play;
use horizon_protocol::{GAME_VERSION, PROTOCOL_VERSION, packets::configuration::ClientInformation};
use horizon_protocol::{
GAME_VERSION, PROTOCOL_VERSION, crypto::uuid_string, packets::configuration::ClientInformation,
text::translatable,
};
use std::{
collections::HashSet,
io,
net::{SocketAddr, TcpListener, TcpStream},
sync::{
Arc, Mutex,
atomic::{AtomicBool, AtomicI32, AtomicU32, Ordering},
atomic::{AtomicBool, AtomicI32, AtomicU32, AtomicUsize, Ordering},
mpsc::{Receiver, Sender, channel},
},
thread::JoinHandle,
@@ -44,6 +47,9 @@ pub enum NetEvent {
Packet(u32, Box<play::Serverbound>),
/// The connection ended (reason for the log).
Left(u32, String),
/// PlayerList.disconnectAllPlayersWithProfile: a new login of this
/// profile replaces the player already in the world.
Duplicate(u128),
}
pub struct Joined {
pub conn: u32,
@@ -54,6 +60,7 @@ pub struct Joined {
pub sender: PlayerSender,
/// Smoothed keep-alive round trip in milliseconds.
pub latency: Arc<AtomicI32>,
pub address: SocketAddr,
}
/// Queued for a connection's writer thread.
pub enum Out {
@@ -64,54 +71,232 @@ pub enum Out {
Close,
}
/// PlayerList.canPlayerLogin for a dedicated server: the disconnect reason
/// (bans, whitelist) for a profile connecting from an address, if refused.
pub type LoginGate =
Arc<dyn Fn(SocketAddr, u128, &str) -> Option<horizon_world::nbt::Tag> + Send + Sync>;
/// How the server side of the network behaves: an integrated server's LAN
/// uses the defaults, a dedicated server takes them from server.properties.
#[derive(Clone)]
pub struct NetConfig {
/// server-ip (all interfaces when absent).
pub bind: Option<std::net::IpAddr>,
/// 0 picks a free port.
pub port: u16,
pub motd: String,
pub max_players: usize,
/// network-compression-threshold; negative disables compression.
pub compression_threshold: i32,
/// enable-status: answer status pings.
pub enable_status: bool,
pub hide_online_players: bool,
/// server-icon.png (64x64 PNG bytes).
pub favicon: Option<Vec<u8>>,
/// MinecraftServer.enforceSecureProfile.
pub enforces_secure_chat: bool,
pub accepts_transfers: bool,
/// LanServerPinger: announce the world on the local network.
pub announce: bool,
/// Ops bypass a full server (ServerOpList.canBypassPlayerLimit).
pub bypasses_limit: Option<Arc<dyn Fn(u128) -> bool + Send + Sync>>,
pub gate: Option<LoginGate>,
}
impl NetConfig {
/// IntegratedServer.publishServer.
pub fn lan(port: u16, motd: String, max_players: usize) -> Self {
Self {
bind: None,
port,
motd,
max_players,
compression_threshold: 256,
enable_status: true,
hide_online_players: false,
favicon: None,
enforces_secure_chat: false,
accepts_transfers: false,
announce: true,
bypasses_limit: None,
gate: None,
}
}
}
/// State shared with the connection threads.
pub struct Shared {
pub sync: Arc<data::SyncData>,
pub events: Sender<NetEvent>,
pub config: NetConfig,
motd: Mutex<String>,
online: Mutex<HashSet<u128>>,
max_players: usize,
max_players: AtomicUsize,
/// PlayerList.players in join order: profile id and name.
online: Mutex<Vec<(u128, String)>>,
/// Profiles held by the host (the LAN host's own name).
reserved: Mutex<HashSet<u128>>,
next: AtomicU32,
stop: AtomicBool,
random: Mutex<u64>,
}
impl Shared {
pub fn next_id(&self) -> u32 {
self.next.fetch_add(1, Ordering::Relaxed)
}
/// PlayerList.canPlayerLogin: duplicates and a full server are refused.
pub fn try_admit(&self, uuid: u128, _name: &str) -> Option<&'static str> {
let mut online = self.online.lock().unwrap();
if online.contains(&uuid) {
return Some("multiplayer.disconnect.duplicate_login");
/// PlayerList.canPlayerLogin then disconnectAllPlayersWithProfile: the
/// refusal reason, or None once the profile holds a place. A profile
/// already playing is kicked and its place awaited.
pub fn try_admit(
&self,
address: SocketAddr,
uuid: u128,
name: &str,
) -> Option<horizon_world::nbt::Tag> {
if let Some(gate) = &self.config.gate
&& let Some(reason) = gate(address, uuid, name)
{
return Some(reason);
}
if online.len() >= self.max_players {
return Some("multiplayer.disconnect.server_full");
if self.reserved.lock().unwrap().contains(&uuid) {
return Some(translatable("multiplayer.disconnect.duplicate_login", &[]));
}
online.insert(uuid);
{
let online = self.online.lock().unwrap();
let bypass = self.config.bypasses_limit.as_ref().is_some_and(|b| b(uuid));
let taken = online.len() + self.reserved.lock().unwrap().len();
if taken >= self.max_players() && !bypass {
return Some(translatable("multiplayer.disconnect.server_full", &[]));
}
}
if self.is_online(uuid) {
let _ = self.events.send(NetEvent::Duplicate(uuid));
let deadline = std::time::Instant::now() + Duration::from_secs(30);
while self.is_online(uuid) {
if std::time::Instant::now() > deadline {
return Some(translatable("multiplayer.disconnect.slow_login", &[]));
}
std::thread::sleep(Duration::from_millis(10));
}
}
self.online.lock().unwrap().push((uuid, name.to_owned()));
None
}
fn is_online(&self, uuid: u128) -> bool {
self.online.lock().unwrap().iter().any(|(u, _)| *u == uuid)
}
pub fn motd(&self) -> String {
self.motd.lock().unwrap().clone()
}
pub fn max_players(&self) -> usize {
self.max_players.load(Ordering::Relaxed)
}
pub fn set_max_players(&self, n: usize) {
self.max_players.store(n, Ordering::Relaxed);
}
pub fn release(&self, uuid: u128) {
self.online.lock().unwrap().remove(&uuid);
self.online.lock().unwrap().retain(|(u, _)| *u != uuid);
}
pub fn online(&self) -> usize {
self.online.lock().unwrap().len()
self.online.lock().unwrap().len() + self.reserved.lock().unwrap().len()
}
/// The status response (ServerStatus): version, players and the MOTD.
fn next_random(&self, bound: usize) -> usize {
let mut r = self.random.lock().unwrap();
*r = r
.wrapping_mul(6_364_136_223_846_793_005)
.wrapping_add(1_442_695_040_888_963_407);
((*r >> 33) as usize) % bound.max(1)
}
/// The status response (MinecraftServer.buildServerStatus encoded with
/// ServerStatus.CODEC): description, players with up to 12 shuffled
/// names, version, favicon and enforcesSecureChat when true.
pub fn status_json(&self) -> String {
use crate::server::json::Json;
let motd = self.motd.lock().unwrap().clone();
serde_json::json!({
"version": { "name": GAME_VERSION, "protocol": PROTOCOL_VERSION },
"players": { "max": self.max_players, "online": self.online() },
"description": { "text": motd },
"enforcesSecureChat": false,
})
.to_string()
let online: Vec<(u128, String)> = self.online.lock().unwrap().clone();
let count = self.online();
let mut players = vec![
(
"max".to_owned(),
Json::Number(self.max_players().to_string()),
),
("online".to_owned(), Json::Number(count.to_string())),
];
if !self.config.hide_online_players && !online.is_empty() {
let size = online.len().min(12);
let offset = self.next_random(online.len() - size + 1);
let mut sample: Vec<(u128, String)> = online[offset..offset + size].to_vec();
for i in (1..sample.len()).rev() {
let j = self.next_random(i + 1);
sample.swap(i, j);
}
players.push((
"sample".to_owned(),
Json::Array(
sample
.into_iter()
.map(|(u, n)| {
Json::Object(vec![
("id".to_owned(), Json::String(uuid_string(u))),
("name".to_owned(), Json::String(n)),
])
})
.collect(),
),
));
}
let mut status = vec![
("description".to_owned(), Json::String(motd)),
("players".to_owned(), Json::Object(players)),
(
"version".to_owned(),
Json::Object(vec![
("name".to_owned(), Json::String(GAME_VERSION.to_owned())),
(
"protocol".to_owned(),
Json::Number(PROTOCOL_VERSION.to_string()),
),
]),
),
];
if let Some(icon) = &self.config.favicon {
status.push((
"favicon".to_owned(),
Json::String(format!("data:image/png;base64,{}", base64(icon))),
));
}
if self.config.enforces_secure_chat {
status.push(("enforcesSecureChat".to_owned(), Json::Bool(true)));
}
Json::Object(status).compact()
}
}
/// java.util.Base64.getEncoder (padded, no line breaks).
pub fn base64(data: &[u8]) -> String {
const A: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
for chunk in data.chunks(3) {
let b = [
chunk[0],
*chunk.get(1).unwrap_or(&0),
*chunk.get(2).unwrap_or(&0),
];
let n = u32::from(b[0]) << 16 | u32::from(b[1]) << 8 | u32::from(b[2]);
out.push(char::from(A[(n >> 18) as usize & 63]));
out.push(char::from(A[(n >> 12) as usize & 63]));
out.push(if chunk.len() > 1 {
char::from(A[(n >> 6) as usize & 63])
} else {
'='
});
out.push(if chunk.len() > 2 {
char::from(A[n as usize & 63])
} else {
'='
});
}
out
}
/// A running LAN server.
pub struct Lan {
pub shared: Arc<Shared>,
@@ -129,19 +314,33 @@ impl Lan {
motd: String,
max_players: usize,
) -> io::Result<Self> {
let listener = TcpListener::bind(("0.0.0.0", port))?;
Self::start_with(sync, NetConfig::lan(port, motd, max_players))
}
/// ServerConnectionListener.startTcpServerListener with a configuration.
pub fn start_with(sync: Arc<data::SyncData>, config: NetConfig) -> io::Result<Self> {
let bind = config
.bind
.unwrap_or(std::net::IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED));
let listener = TcpListener::bind((bind, config.port))?;
listener.set_nonblocking(true)?;
let port = listener.local_addr()?.port();
let _pinger = discovery::Pinger::start(motd.clone(), port).ok();
let _pinger = if config.announce {
discovery::Pinger::start(config.motd.clone(), port).ok()
} else {
None
};
let (tx, events) = channel();
let shared = Arc::new(Shared {
sync,
events: tx,
motd: Mutex::new(motd),
online: Mutex::new(HashSet::new()),
max_players,
motd: Mutex::new(config.motd.clone()),
max_players: AtomicUsize::new(config.max_players),
online: Mutex::new(Vec::new()),
reserved: Mutex::new(HashSet::new()),
next: AtomicU32::new(1),
stop: AtomicBool::new(false),
random: Mutex::new(crate::server::java_properties::now_millis() as u64 | 1),
config,
});
let accept_shared = shared.clone();
let listener = std::thread::Builder::new()
@@ -161,7 +360,7 @@ impl Lan {
}
/// Reserve a uuid for the host so a guest cannot take the name.
pub fn reserve(&self, uuid: u128) {
self.shared.online.lock().unwrap().insert(uuid);
self.shared.reserved.lock().unwrap().insert(uuid);
}
pub fn set_motd(&self, motd: &str) {
*self.shared.motd.lock().unwrap() = motd.to_owned();
@@ -198,7 +397,7 @@ fn accept_loop(listener: TcpListener, shared: Arc<Shared>) {
}
fn handle(stream: TcpStream, addr: SocketAddr, shared: Arc<Shared>) {
let _ = stream.set_nonblocking(false);
if let Err(e) = conn::serve(stream, shared)
if let Err(e) = conn::serve(stream, addr, shared)
&& std::env::var_os("HORIZON_NET_DEBUG").is_some()
{
eprintln!("[lan] {addr}: {e}");
+130 -6
View File
@@ -25,6 +25,7 @@ pub mod drops;
pub mod enderman;
pub mod equine;
pub mod farm;
pub mod finalize;
pub mod gear;
pub mod goals;
pub mod golem;
@@ -205,6 +206,8 @@ pub struct MobType {
pub armor_toughness: f32,
pub knockback_resistance: f64,
pub jump_strength: f64,
/// Every default attribute value of the type (`entity-types.json`).
pub attributes: Arc<HashMap<String, f64>>,
pub gravity: f64,
pub safe_fall_distance: f64,
pub fall_damage_multiplier: f64,
@@ -238,12 +241,35 @@ impl MobType {
self.layers.get(key)
}
}
/// Each type's default attribute values, parsed exactly (serde_json's
/// default float parsing can miss the nearest double by one ulp).
fn exact_attributes(bytes: &[u8]) -> HashMap<String, HashMap<String, f64>> {
use serde_json::value::RawValue;
type Raw = HashMap<String, Box<RawValue>>;
let Ok(types) = serde_json::from_slice::<Raw>(bytes) else {
return HashMap::new();
};
types
.into_iter()
.filter_map(|(id, t)| {
let t: Raw = serde_json::from_str(t.get()).ok()?;
let attrs: Raw = serde_json::from_str(t.get("attributes")?.get()).ok()?;
let values = attrs
.into_iter()
.filter_map(|(k, v)| v.get().trim().parse::<f64>().ok().map(|v| (k, v)))
.collect();
Some((id, values))
})
.collect()
}
pub struct MobTypes {
pub types: HashMap<String, MobType>,
}
impl MobTypes {
pub fn load(root: &Path) -> crate::Result<Self> {
let types: Value = serde_json::from_slice(&fs::read(root.join("entity-types.json"))?)?;
let bytes = fs::read(root.join("entity-types.json"))?;
let types: Value = serde_json::from_slice(&bytes)?;
let exact = exact_attributes(&bytes);
let models: Value = serde_json::from_slice(&fs::read(root.join("entity-models.json"))?)?;
let item_tags = crate::items::load_tags(root, "item").unwrap_or_default();
sulfur_cube::load_archetype_items(&item_tags);
@@ -268,7 +294,8 @@ impl MobTypes {
let Some(model) = models.get(&model_key) else {
continue;
};
let attr = |k: &str| t["attributes"][format!("minecraft:{k}")].as_f64();
let defaults = exact.get(&id).cloned().unwrap_or_default();
let attr = |k: &str| defaults.get(&format!("minecraft:{k}")).copied();
let mut layers = HashMap::new();
if let Some(all) = models.as_object() {
for prefix in def.layer_prefixes() {
@@ -302,6 +329,7 @@ impl MobTypes {
armor_toughness: attr("armor_toughness").unwrap_or(0.0) as f32,
knockback_resistance: attr("knockback_resistance").unwrap_or(0.0),
jump_strength: attr("jump_strength").unwrap_or(0.42),
attributes: Arc::new(defaults.clone()),
gravity: attr("gravity").unwrap_or(0.08),
safe_fall_distance: attr("safe_fall_distance").unwrap_or(3.0),
fall_damage_multiplier: attr("fall_damage_multiplier").unwrap_or(1.0),
@@ -461,6 +489,9 @@ pub struct Attrs {
pub attack_damage: f32,
pub max_health: f32,
pub follow_range: f64,
pub knockback_resistance: f64,
pub spawn_reinforcements: f64,
pub jump_strength: f64,
}
/// Species-specific persistent state (variants, colours, taming, ageing...).
#[derive(Clone, Debug, Default)]
@@ -561,6 +592,24 @@ pub struct Extra {
/// `Mob.dropChances` by `EquipmentSlot` (`drops::SLOTS` order) when set
/// explicitly; None uses the defaults of `drops::drop_chance`.
pub drop_chances: Option<Box<[f32; 8]>>,
/// `Mob.leftHanded`.
pub left_handed: bool,
/// The sound variant: index in the species' `*_sound_variant` registry.
pub sound_variant: u8,
/// `Zombie.canBreakDoors`.
pub can_break_doors: bool,
/// A goat's `IsScreamingGoat` and the horns it lost (left, right).
pub screaming: bool,
pub lost_horns: [bool; 2],
/// Attribute bases and permanent modifiers set by `finalizeSpawn`.
pub attributes: Option<Box<finalize::Attributes>>,
/// Brain memories `finalizeSpawn` sets: (memory, value, ticks to expiry).
pub memories: Vec<(&'static str, i64, i64)>,
/// A camel's `LAST_POSE_CHANGE_TICK`.
pub pose_change_tick: i64,
/// The school leader a fish follows, and a tropical fish that swims alone.
pub leader: Option<u32>,
pub lone: bool,
/// A breeze's or creaking's brain (`monster_brain`).
pub brain: Option<Box<monster_brain::Brain>>,
}
@@ -798,10 +847,14 @@ pub enum MobEvent {
mob: u32,
other: u32,
},
/// Two villagers make a baby.
/// Two villagers make a baby (`VillagerMakeLove.tryToGiveBirth`): the
/// parent has eaten and, with a bed for the child, rests; the partner
/// eats, and rests too if `child` holds the child's bed and type
/// (`None`: the biome's).
VillagerBirth {
parent: u32,
partner: u32,
child: Option<([i32; 3], Option<u8>)>,
},
/// A villager asks whether enough neighbours want an iron golem.
GolemCheck {
@@ -936,11 +989,65 @@ pub struct Seen {
/// `render::PROFESSIONS`), a llama's strength. And a villager's experience.
pub profession: u8,
pub xp: i32,
/// What other villagers read of a villager's state and brain.
pub villager: Option<Arc<villager::Seen>>,
/// `MAX_HEALTH`, `JUMP_STRENGTH` and `MOVEMENT_SPEED` base values (a
/// horse's breeding stock).
pub stats: [f64; 3],
}
impl Mob {
/// What other mobs see of this one this tick (`player`: the player's
/// UUID, which villagers' reputation is keyed by).
pub fn seen(&self, player: Option<[i32; 4]>) -> Seen {
let m = self;
let villager = m.species() == Species::Villager;
Seen {
id: m.id,
species: m.species(),
position: m.position,
bounds: m.bounds(),
eye_y: m.eye_y(),
alive: m.alive(),
baby: m.is_baby(),
// A villager is "in love" when it is willing to breed (`canBreed`).
in_love: if villager {
villager::can_breed(m)
} else {
m.extra.in_love > 0
},
tame: m.extra.tame,
hostile: m.hostile(),
target: m.ai.target,
health: m.health,
variant: m.extra.variant,
color: m.extra.color,
job: villager.then_some(m.extra.home).flatten(),
bed: villager.then_some(m.extra.bed).flatten(),
yaw: m.yaw,
velocity: m.velocity,
leash: m.extra.leash,
caravan: caravan::head_of(m),
delay: m.extra.ints[5],
hurt_by: m.ai.last_hurt_by.map(|w| (w, m.ai.last_hurt_by_time)),
active_raid: raider::has_active_raid(m),
player_rep: match (villager, player) {
(true, Some(uuid)) => villager::ext(m).map_or(0, |e| e.gossips.reputation(uuid)),
_ => 0,
},
pushable: m.pushable(),
category: m.category(),
potential_job: villager_brain::potential_job_site(m),
meeting: villager.then_some(m.extra.meeting).flatten(),
profession: m.extra.variant2,
xp: villager::xp(m),
villager: villager.then(|| Arc::new(villager::seen(m))),
stats: [
f64::from(m.attrs.max_health),
m.extra.vector[0],
m.attrs.speed,
],
}
}
/// `EntityType.getCategory`'s name.
pub fn category(&self) -> &'static str {
match self.kind.category.as_str() {
@@ -1000,6 +1107,7 @@ pub fn apply_brain_events(mobs: &mut [Mob], events: &mut Vec<MobEvent>, from: us
MobEvent::LockGaze { mob, partner } => {
if let Some(m) = mobs.iter_mut().find(|m| m.id == mob) {
animal_brain::lock_gaze(m, partner);
villager_brain::lock_gaze_half(m, Who::Mob(partner));
}
events.remove(i);
}
@@ -1156,17 +1264,24 @@ impl Mob {
attack_damage: kind.attack_damage,
max_health: kind.max_health,
follow_range: kind.follow_range,
knockback_resistance: kind.knockback_resistance,
spawn_reinforcements: kind
.attributes
.get("minecraft:spawn_reinforcements")
.copied()
.unwrap_or(0.0),
jump_strength: kind.jump_strength,
},
kind,
};
// setCanPickUpLoot(true) in the Villager, AbstractPiglin, Allay,
// Dolphin, Fox and Panda constructors.
// setCanPickUpLoot(true) in the Villager, AbstractPiglin, Dolphin,
// Fox and Panda constructors (an allay's is false until it holds
// something: it overrides canPickUpLoot).
mob.extra.pick_up_loot = matches!(
mob.species(),
Species::Villager
| Species::Piglin
| Species::PiglinBrute
| Species::Allay
| Species::Dolphin
| Species::Fox
| Species::Panda
@@ -1174,6 +1289,15 @@ impl Mob {
ai::register(&mut mob);
mob
}
/// `Mob.canPickUpLoot`, with the overrides: an allay that holds
/// something off its pickup cooldown, a sulfur cube with no block.
pub fn can_pick_up_loot(&self) -> bool {
match self.species() {
Species::Allay => self.extra.main_hand.is_some() && self.extra.ints[3] <= 0,
Species::SulfurCube => !sulfur_cube::has_body(self),
_ => self.extra.pick_up_loot,
}
}
pub fn bounds(&self) -> Aabb {
let w = f64::from(self.width()) / 2.0;
Aabb::new(
+7 -4
View File
@@ -895,11 +895,14 @@ fn check_despawn(m: &mut Mob, w: &MobWorld) -> bool {
|| super::nautilus::is_nautilus(m.species()) && m.extra.tame
|| m.species() == Species::SulfurCube
&& (super::sulfur_cube::has_body(m) || m.extra.scratch[3] != 0);
// removeWhenFarAway: animals, wardens, patrols and raiders, zombie
// villagers being cured and ridden mobs stay.
// removeWhenFarAway: animals, wardens, allays, patrols and raiders,
// zombie villagers being cured and ridden mobs stay; the wither's
// checkDespawn never removes it for distance.
let creature = m.kind.category == "creature";
let removable = !(m.species() == Species::Warden
|| creature && m.kind.flags.animal && !m.extra.jockey
let removable = !(matches!(
m.species(),
Species::Warden | Species::Allay | Species::Wither
) || creature && m.kind.flags.animal && !m.extra.jockey
|| super::raider::keeps_alive(m, d)
|| super::zombie_villager::keeps_alive(m)
|| super::riders::keeps_alive(m));
-1
View File
@@ -27,7 +27,6 @@ pub fn register(m: &mut Mob) {
m.ai.nav.kind = NavKind::Flying;
// FlyingPathNavigation.setRequiredPathLength(48).
m.ai.nav.required_path_length = 48.0;
m.persistent = true;
let g = &mut m.ai.goals;
g.add(0, Panic::new(2.5));
g.add(1, Fetch);
+29 -26
View File
@@ -445,35 +445,38 @@ impl Goal for PufferfishPuff {
}
}
/// finalizeSpawn variants (tropical fish patterns and colours).
/// TropicalFish.COMMON_VARIANTS: (pattern index, base colour, pattern colour).
pub const COMMON_TROPICAL: [(u8, u8, u8); 22] = [
(7, 1, 7),
(6, 7, 7),
(6, 7, 11),
(11, 0, 7),
(1, 11, 7),
(0, 1, 0),
(5, 6, 3),
(9, 10, 4),
(11, 0, 14),
(5, 0, 4),
(8, 0, 7),
(11, 0, 1),
(3, 9, 6),
(4, 5, 3),
(10, 14, 0),
(2, 7, 14),
(9, 14, 0),
(6, 0, 4),
(0, 14, 0),
(1, 7, 0),
(3, 9, 4),
(6, 4, 4),
];
pub fn finalize(m: &mut Mob) {
if m.species() == Species::TropicalFish {
// TropicalFish.COMMON_VARIANTS: (pattern index, base colour, pattern colour).
const COMMON: [(u8, u8, u8); 22] = [
(7, 1, 7),
(6, 7, 7),
(6, 7, 11),
(11, 0, 7),
(1, 11, 7),
(0, 1, 0),
(5, 6, 3),
(9, 10, 4),
(11, 0, 14),
(5, 0, 4),
(8, 0, 7),
(11, 0, 1),
(3, 9, 6),
(4, 5, 3),
(10, 14, 0),
(2, 7, 14),
(9, 14, 0),
(6, 0, 4),
(0, 14, 0),
(1, 7, 0),
(3, 9, 4),
(6, 4, 4),
];
let (p, b, c) = if m.random.next_float() < 0.9 {
COMMON[m.random.next_int_bound(COMMON.len() as i32).unwrap_or(0) as usize]
COMMON_TROPICAL[m
.random
.next_int_bound(COMMON_TROPICAL.len() as i32)
.unwrap_or(0) as usize]
} else {
(
m.random.next_int_bound(12).unwrap_or(0) as u8,
File diff suppressed because it is too large Load Diff
+97 -2
View File
@@ -132,6 +132,38 @@ impl MobWorld<'_> {
.map(|shape| shape.boxes().iter().map(|b| b.move_by(offset)).collect())
.unwrap_or_default()
}
/// `Level.findSupportingBlock`: of the blocks whose collision shape
/// meets `area`, the one whose centre is nearest `from` (ties: the
/// greatest by `Vec3i.compareTo`, y then z then x).
pub fn supporting_block(&self, area: Aabb, from: Vec3) -> Option<[i32; 3]> {
use horizon_core::geometry::Axis;
let range = |axis| {
(area.min(axis) - 1.0e-7).floor() as i32 - 1
..=(area.max(axis) + 1.0e-7).floor() as i32 + 1
};
let mut best: Option<(f64, [i32; 3])> = None;
for y in range(Axis::Y) {
for z in range(Axis::Z) {
for x in range(Axis::X) {
if !self
.block_collision_boxes(x, y, z)
.iter()
.any(|b| b.intersects(area))
{
continue;
}
let d = (f64::from(x) + 0.5 - from.x).powi(2)
+ (f64::from(y) + 0.5 - from.y).powi(2)
+ (f64::from(z) + 0.5 - from.z).powi(2);
let greater = |b: [i32; 3]| (y, z, x) > (b[1], b[2], b[0]);
if best.is_none_or(|(bd, b)| d < bd || d == bd && greater(b)) {
best = Some((d, [x, y, z]));
}
}
}
}
best.map(|(_, p)| p)
}
pub fn no_collision(&self, b: Aabb) -> bool {
let mut scene = SceneCollisions {
world: self.world,
@@ -346,7 +378,8 @@ impl Mob {
let full = (moved.length() * f64::from(0.6_f32)) as f32;
let horizontal =
((moved.x * moved.x + moved.z * moved.z).sqrt() * f64::from(0.6_f32)) as f32;
let on = self.on_pos(1.0e-5);
let supporting = self.supporting_block(w, moved);
let on = self.supported_on_pos(w, supporting, 1.0e-5);
let state = w.world.block(on[0], on[1], on[2]);
let climbable = w.facts.get(state).name.as_ref() == "minecraft:powder_snow"
|| w.has_tag("minecraft:climbable", &w.facts.get(state).name);
@@ -354,7 +387,7 @@ impl Mob {
steps.move_dist += if climbable { full } else { horizontal };
steps.fly_dist += full;
if steps.move_dist > steps.next_step && !w.facts.is_air(state) {
let legacy = self.on_pos(0.2);
let legacy = self.supported_on_pos(w, supporting, 0.2);
let legacy_state = w.world.block(legacy[0], legacy[1], legacy[2]);
let produced = !w.facts.is_air(legacy_state)
&& (self.on_ground || climbable)
@@ -397,6 +430,68 @@ impl Mob {
fn fluids_swimming(&self) -> bool {
false
}
/// `Entity.checkSupportingBlock` after a move: on the ground, the block
/// under the feet (`mainSupportingBlockPos`), looked for again where
/// the mob came from if none is under it now.
fn supporting_block(&self, w: &MobWorld, moved: Vec3) -> Option<[i32; 3]> {
if !self.on_ground {
return None;
}
let b = self.bounds();
use horizon_core::geometry::Axis;
let area = Aabb::new(
Vec3::new(b.min(Axis::X), b.min(Axis::Y) - 1.0e-6, b.min(Axis::Z)),
Vec3::new(b.max(Axis::X), b.min(Axis::Y), b.max(Axis::Z)),
);
w.supporting_block(area, self.position).or_else(|| {
let back = Vec3::new(-moved.x, 0.0, -moved.z);
let shifted = Aabb::new(
Vec3::new(
area.min(Axis::X) + back.x,
area.min(Axis::Y),
area.min(Axis::Z) + back.z,
),
Vec3::new(
area.max(Axis::X) + back.x,
area.max(Axis::Y),
area.max(Axis::Z) + back.z,
),
);
w.supporting_block(shifted, self.position)
})
}
/// `Entity.getOnPos(offset)` with a supporting block: its column (its
/// own position for fences, walls and gates up to half a block down).
fn supported_on_pos(
&self,
w: &MobWorld,
supporting: Option<[i32; 3]>,
offset: f32,
) -> [i32; 3] {
let Some(p) = supporting else {
return self.on_pos(offset);
};
if offset <= 1.0e-5 {
return p;
}
let name = &w.facts.get(w.world.block(p[0], p[1], p[2])).name;
let tall = [
"minecraft:fences",
"minecraft:walls",
"minecraft:fence_gates",
]
.iter()
.any(|t| w.has_tag(t, name));
if offset <= 0.5 && tall {
p
} else {
[
p[0],
(self.position.y - f64::from(offset)).floor() as i32,
p[2],
]
}
}
/// Entity.getOnPos(offset) without a supporting block record.
pub fn on_pos(&self, offset: f32) -> [i32; 3] {
[
+138
View File
@@ -496,6 +496,144 @@ impl Ext {
now < self.last_gossip_time || now >= self.last_gossip_time + 1200
}
}
/// What a villager ticking later reads of another one this tick (vanilla
/// reads the other villager itself).
#[derive(Clone, Debug, Default)]
pub struct Seen {
pub gossips: crate::gossip::Gossips,
pub last_gossip_time: i64,
/// `countFoodPointsInInventory`.
pub food_points: i32,
/// The `INTERACTION_TARGET` memory (play tag's chases).
pub interaction_target: Option<super::Who>,
/// The `PATH` memory, when not done: its previous and next nodes.
pub path_nodes: Option<(Option<[i32; 3]>, [i32; 3])>,
/// `LAST_SLEPT` and whether `GOLEM_DETECTED_RECENTLY` is remembered.
pub last_slept: Option<i64>,
pub golem_detected: bool,
}
impl Seen {
/// `Villager.wantsToSpawnGolem`.
pub fn wants_golem(&self, now: i64) -> bool {
self.last_slept.is_some_and(|t| now - t < 24000) && !self.golem_detected
}
/// `Villager.wantsMoreFood`.
pub fn wants_more_food(&self) -> bool {
self.food_points < 12
}
}
pub fn seen(m: &Mob) -> Seen {
let e = ext(m);
let (interaction_target, path_nodes, golem_detected, last_slept) =
super::villager_brain::seen_memories(m);
Seen {
gossips: e.map(|e| e.gossips.clone()).unwrap_or_default(),
last_gossip_time: e.map_or(0, |e| e.last_gossip_time),
food_points: e.map_or(0, Ext::food_in_inventory),
interaction_target,
path_nodes,
last_slept: last_slept.or(e.and_then(|e| e.last_slept)),
golem_detected,
}
}
/// What `TradeWithVillager.tick` hands over: stacks tossed from the first
/// villager's hand (`from`, its eye height) toward the second (`to`), and
/// whether the gossip happened (`spawnGolemIfNeeded` follows).
pub struct Meeting {
pub thrown: Vec<ItemStack>,
pub from: horizon_core::geometry::Vec3,
pub eye: f64,
pub to: horizon_core::geometry::Vec3,
pub gossiped: bool,
}
/// `TradeWithVillager.tick` for villagers `a` and `b` (indices into `mobs`):
/// `Villager.gossip` (at most once in 1200 ticks for both), then surplus
/// food and wanted wares taken out of `a`'s inventory.
pub fn meet(
mobs: &mut [Mob],
a: usize,
b: usize,
now: i64,
max_stack: impl Fn(&str) -> u32,
) -> Meeting {
let ready = ext(&mobs[a]).is_none_or(|e| e.can_gossip(now))
&& ext(&mobs[b]).is_none_or(|e| e.can_gossip(now));
if ready {
let source = ext(&mobs[b]).map(|e| e.gossips.clone()).unwrap_or_default();
let me = &mut mobs[a];
let mut random = me.random.clone();
let e = ext_mut(me);
e.gossips.transfer_from(&source, &mut random, 10);
e.last_gossip_time = now;
me.random = random;
ext_mut(&mut mobs[b]).last_gossip_time = now;
}
// Surplus food goes to a hungry neighbour (farmers hand it to anyone).
let farmer = is_farmer(&mobs[a]);
let wants_more = ext(&mobs[b]).is_none_or(Ext::wants_more_food);
let excess = ext(&mobs[a]).is_some_and(Ext::has_excess_food);
let mut thrown = Vec::new();
if excess
&& (farmer || wants_more)
&& let Some(s) =
ext_mut(&mut mobs[a]).take_half_stack(|s| food_points(&s.item) > 0, &max_stack)
{
thrown.push(s);
}
// A farmer's wheat.
if farmer
&& ext(&mobs[a]).is_some_and(|e| e.count_item("minecraft:wheat") > 32)
&& let Some(s) =
ext_mut(&mut mobs[a]).take_half_stack(|s| &*s.item == "minecraft:wheat", &max_stack)
{
thrown.push(s);
}
// Wares the neighbour's profession asks for and ours does not.
let theirs = requested_items(&mobs[b]);
let mine = requested_items(&mobs[a]);
let wanted: Vec<&str> = theirs
.iter()
.copied()
.filter(|i| !mine.contains(i))
.collect();
if !wanted.is_empty()
&& let Some(s) =
ext_mut(&mut mobs[a]).take_half_stack(|s| wanted.contains(&&*s.item), &max_stack)
{
thrown.push(s);
}
Meeting {
thrown,
from: mobs[a].position,
eye: mobs[a].eye_y(),
to: mobs[b].position,
gossiped: ready,
}
}
/// `PoiManager.take(HOME, ..., 48)`: the nearest bed head not `claimed`
/// (`free_head`: a bed head that is not occupied).
pub fn take_vacant_bed(
claimed: &[[i32; 3]],
from: [i32; 3],
mut free_head: impl FnMut(i32, i32, i32) -> bool,
) -> Option<[i32; 3]> {
let mut best: Option<(i32, [i32; 3])> = None;
for y in from[1] - 8..=from[1] + 8 {
for z in from[2] - 48..=from[2] + 48 {
for x in from[0] - 48..=from[0] + 48 {
let d = (x - from[0]).pow(2) + (y - from[1]).pow(2) + (z - from[2]).pow(2);
if d <= 48 * 48
&& best.is_none_or(|(b, _)| d < b)
&& free_head(x, y, z)
&& !claimed.contains(&[x, y, z])
{
best = Some((d, [x, y, z]));
}
}
}
}
best.map(|(_, p)| p)
}
/// `Villager.canBreed`: enough food, awake and an adult.
pub fn can_breed(m: &Mob) -> bool {
m.species() == Species::Villager
@@ -663,7 +663,7 @@ fn sense_bed(m: &mut Mob, w: &MobWorld, lr: &mut LegacyRandom) {
let mut cache = std::mem::take(&mut brain_mut(m).bed_cache);
let mut tried = 0;
let mut targets = Vec::new();
for p in homes {
for &p in &homes {
if cache.iter().any(|(q, _)| *q == p) {
continue;
}
@@ -679,8 +679,12 @@ fn sense_bed(m: &mut Mob, w: &MobWorld, lr: &mut LegacyRandom) {
} else {
m.create_path_to_any(w, &targets, 1)
};
// createPath hands back the current path when it still heads for a
// target position it was asked: only a bed (a POI) counts.
if let Some(path) = path.filter(|p| p.reached) {
mem(m).nearest_bed.set(path.target);
if homes.contains(&path.target) {
mem(m).nearest_bed.set(path.target);
}
} else if tried < 5 {
cache.retain(|(_, until)| *until >= last_update);
}
@@ -1609,13 +1613,7 @@ impl B {
}
t.begin(cx);
let target = mem(m).interaction_target.value().unwrap();
let mm = mem(m);
mm.look_target.set(Tracker::Entity(target, true));
mm.walk_target.set(WalkTarget {
target: Tracker::Entity(target, true),
speed: 0.5,
close: 2,
});
lock_gaze(m, target, cx);
true
}
B::MakeLove { t, birth } => {
@@ -1628,7 +1626,7 @@ impl B {
}
t.begin(cx);
let target = mem(m).breed_target.value().unwrap();
lock_gaze(m, target);
lock_gaze(m, target, cx);
*birth = now + 275 + i64::from(m.random.next_int_bound(50).unwrap_or(0));
true
}
@@ -2853,6 +2851,7 @@ impl B {
&& i.position.distance_squared(m.position) <= 5.0
{
let Who::Mob(other) = target else { return };
lock_gaze(m, target, cx);
cx.events.push(MobEvent::VillagerMeet { mob: m.id, other });
}
}
@@ -2870,11 +2869,29 @@ impl B {
.target_info(target)
.is_some_and(|t| t.position.distance_squared(m.position) <= 5.0)
{
lock_gaze(m, target);
lock_gaze(m, target, cx);
if now >= *birth {
// The parent's half happens in its own tick: it eats,
// takes a bed for the child, picks its type and rests.
super::villager::ext_mut(m).eat_and_digest();
let child = take_bed_for_child(m, cx.w).map(|bed| {
// Villager.getBreedOffspring: half the biome's type,
// a quarter each parent's.
let roll = m.random.next_double();
let variant = if roll < 0.5 {
None
} else if roll < 0.75 {
Some(m.extra.variant)
} else {
Some(cx.w.seen(partner).map_or(m.extra.variant, |s| s.variant))
};
m.extra.age = 6000;
(bed, variant)
});
cx.events.push(MobEvent::VillagerBirth {
parent: m.id,
partner,
child,
});
} else if m.random.next_int_bound(35).unwrap_or(1) == 0 {
let mut p = vec![m.position];
@@ -3366,8 +3383,38 @@ fn breeding_possible(m: &mut Mob, w: &MobWorld) -> bool {
&& super::villager::can_breed(m)
&& w.seen(id).is_some_and(|s| s.in_love)
}
/// `BehaviorUtils.lockGazeAndWalkToEachOther`, this villager's half.
fn lock_gaze(m: &mut Mob, target: Who) {
/// `VillagerMakeLove.takeVacantBed`: a bed head no villager has claimed.
fn take_bed_for_child(m: &Mob, w: &MobWorld) -> Option<[i32; 3]> {
let claimed: Vec<[i32; 3]> = w
.others
.iter()
.filter(|s| s.species == Species::Villager && s.id != m.id)
.filter_map(|s| s.bed)
.chain(m.extra.bed)
.collect();
let p = m.position;
let from = [p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32];
super::villager::take_vacant_bed(&claimed, from, |x, y, z| {
w.prop(x, y, z, "part") == Some("head") && w.prop(x, y, z, "occupied") != Some("true")
})
}
/// `BehaviorUtils.lockGazeAndWalkToEachOther`: this villager's half, and
/// the other villager's through a `LockGaze` event.
fn lock_gaze(m: &mut Mob, target: Who, cx: &mut Bx) {
lock_gaze_half(m, target);
if let Who::Mob(other) = target {
cx.events.push(MobEvent::LockGaze {
mob: other,
partner: m.id,
});
}
}
/// One villager's half of `lockGazeAndWalkToEachOther`: look at the other
/// and walk to it.
pub fn lock_gaze_half(m: &mut Mob, target: Who) {
if super::villager::ext(m).is_none_or(|e| e.brain.is_none()) {
return;
}
let mm = mem(m);
mm.look_target.set(Tracker::Entity(target, true));
mm.walk_target.set(WalkTarget {
@@ -4080,3 +4127,34 @@ pub fn potential_job_site(m: &Mob) -> Option<[i32; 3]> {
pub fn seen_can_breed(s: &Seen) -> bool {
s.species == Species::Villager && s.in_love
}
/// The memories other villagers read: the interaction target, the path's
/// nodes (while it is not done), whether a golem was seen lately and the
/// last sleep.
#[allow(clippy::type_complexity)]
pub fn seen_memories(
m: &Mob,
) -> (
Option<Who>,
Option<(Option<[i32; 3]>, [i32; 3])>,
bool,
Option<i64>,
) {
let Some(mm) = mem_ref(m) else {
return (None, None, false, None);
};
let path = mm
.path
.present()
.then_some(m.ai.nav.path.as_ref())
.flatten();
let nodes = path.filter(|p| !p.is_done()).map(|p| {
let n = |i: usize| [p.nodes[i].x, p.nodes[i].y, p.nodes[i].z];
((p.next > 0).then(|| n(p.next - 1)), n(p.next))
});
(
mm.interaction_target.value(),
nodes,
mm.golem_detected_recently.present(),
mm.last_slept.value(),
)
}
-1
View File
@@ -28,7 +28,6 @@ pub fn register(m: &mut Mob) {
hovers: false,
};
m.ai.nav.kind = NavKind::Flying;
m.persistent = true;
let g = &mut m.ai.goals;
g.add(0, DoNothing);
g.add(
+26
View File
@@ -639,6 +639,32 @@ fn heightmaps(chunk: &Chunk, tables: &SaveTables) -> Tag {
)
}))
}
/// The heightmaps a ClientboundLevelChunkPacketData carries (the types with
/// sendToClient: WORLD_SURFACE, MOTION_BLOCKING, MOTION_BLOCKING_NO_LEAVES),
/// as (network id, packed longs) in Heightmap.Types order.
pub fn client_heightmaps(chunk: &Chunk, tables: &SaveTables) -> Vec<(i32, Vec<i64>)> {
let kinds = [
(1, HeightmapType::WorldSurface),
(4, HeightmapType::MotionBlocking),
(5, HeightmapType::MotionBlockingNoLeaves),
];
let mut maps: Vec<(i32, Heightmap)> = kinds
.iter()
.filter_map(|(id, k)| {
Heightmap::new(*k, MIN_Y, SECTIONS as i32 * 16)
.ok()
.map(|m| (*id, m))
})
.collect();
let view = HeightmapView { chunk, tables };
let mut refs: Vec<&mut Heightmap> = maps.iter_mut().map(|(_, m)| m).collect();
if Heightmap::prime(&view, &mut refs).is_err() {
return Vec::new();
}
maps.iter()
.map(|(id, m)| (*id, m.raw_data().iter().map(|&w| w as i64).collect()))
.collect()
}
/// Vanilla light layer (nibbles, index y<<8|z<<4|x, low nibble first).
fn nibbles(light: &Light, sky: bool) -> Vec<u8> {
let mut out = vec![0u8; 2048];
+112 -6
View File
@@ -341,7 +341,7 @@ impl Streaming {
match done {
Done::Proto(x, z, proto) => {
self.generating.remove(&(x, z));
if self.in_range(x, z, 4) {
if self.in_range(x, z, 4) || self.near_finished(x, z, 2) {
self.protos.insert((x, z), Some(proto));
if !self.decorates {
self.decorated.insert((x, z));
@@ -371,7 +371,7 @@ impl Streaming {
self.generating.remove(&key);
self.finishing.remove(&key);
self.decorated.insert(key);
if self.in_range(key.0, key.1, 2) {
if self.in_range(key.0, key.1, 2) || self.near_finished(key.0, key.1, 1) {
self.generated_total += 1;
// A chunk saved with its light needs no light job; its
// unlit neighbours still light themselves from it.
@@ -435,7 +435,9 @@ impl Streaming {
.chunks
.keys()
.copied()
.filter(|&(x, z)| !self.remote && !self.in_range(x, z, 3))
.filter(|&(x, z)| {
!self.remote && !self.in_range(x, z, 3) && !self.near_finished(x, z, 1)
})
.collect();
for key in &far {
self.decorated.remove(key);
@@ -499,7 +501,9 @@ impl Streaming {
.protos
.iter()
.filter(|(k, p)| {
p.is_some() && !self.decorated.contains(k) && self.in_range(k.0, k.1, 2)
p.is_some()
&& !self.decorated.contains(k)
&& (self.in_range(k.0, k.1, 2) || self.near_finished(k.0, k.1, 1))
})
.map(|(k, _)| (self.distance(k.0, k.1), k.0, k.1))
.collect();
@@ -540,17 +544,19 @@ impl Streaming {
}
// Generation (load or proto), closest first, bounded in flight.
let margin = if self.decorates { 3 } else { 1 };
// Neighbours a finished chunk needs generated: decorated ones need theirs.
let reach = if self.decorates { 2 } else { 1 };
if !self.remote && self.generating.len() < workers * 3 {
let mut wanted = Vec::new();
let areas: Vec<((i32, i32), i32)> = std::iter::once((self.center, self.radius))
.chain(self.extra.iter().copied())
.collect();
for (center, radius) in areas {
let r = radius + margin;
let r = radius + margin.max(reach + 1);
for dz in -r..=r {
for dx in -r..=r {
let (x, z) = (center.0 + dx, center.1 + dz);
if !self.in_range(x, z, margin)
if !(self.in_range(x, z, margin) || self.near_finished(x, z, reach))
|| world.chunks.contains_key(&(x, z))
|| self.generating.contains(&(x, z))
|| self.protos.contains_key(&(x, z))
@@ -728,6 +734,46 @@ impl Streaming {
}
}
}
fn ranges(&self) -> Ranges<'_> {
Ranges {
center: self.center,
radius: self.radius,
extra: &self.extra,
forced: &self.forced,
}
}
fn near_finished(&self, x: i32, z: i32, reach: i32) -> bool {
self.ranges().near_finished(x, z, reach)
}
fn in_range(&self, x: i32, z: i32, margin: i32) -> bool {
self.ranges().in_range(x, z, margin)
}
fn in_main_range(&self, x: i32, z: i32, margin: i32) -> bool {
self.ranges().in_main_range(x, z, margin)
}
}
/// The areas kept loaded: circles around the player and `extra`, and forced chunks.
struct Ranges<'a> {
center: (i32, i32),
radius: i32,
extra: &'a [((i32, i32), i32)],
forced: &'a HashSet<(i32, i32)>,
}
impl Ranges<'_> {
/// Whether a chunk finished here (`in_range(_, _, 1)`) lies within `reach`
/// chunks of (x, z) on both axes: its decoration needs its 3x3 neighbours
/// decorated, which need their own 3x3 neighbours generated. The ranges are
/// circles, so a fixed margin alone misses the corners of those squares
/// (render distance 2 never finished the chunks next to the player).
fn near_finished(&self, x: i32, z: i32, reach: i32) -> bool {
let near = |c: (i32, i32), radius: i32| {
let gap = |d: i32| i64::from((d.abs() - reach).max(0));
let (dx, dz) = (gap(x - c.0), gap(z - c.1));
let r = i64::from(radius + 1);
dx * dx + dz * dz <= r * r
};
near(self.center, self.radius) || self.extra.iter().any(|&(c, r)| near(c, r))
}
fn in_range(&self, x: i32, z: i32, margin: i32) -> bool {
self.in_main_range(x, z, margin)
|| self.extra.iter().any(|&(c, radius)| {
@@ -757,3 +803,63 @@ impl Drop for Streaming {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
/// The ranges `Streaming::update` checks at each step, from generation to
/// light, must let every chunk the player spawns on finish and light: the
/// 3x3 columns around the player need their own 3x3 neighbours finished,
/// each of those its 3x3 neighbours decorated, and each of those its 3x3
/// neighbours generated and kept. Render distance 2 once stopped short.
#[test]
fn spawn_neighbourhood_completes_at_every_distance() {
let forced = HashSet::new();
for decorates in [true, false] {
let (margin, reach) = if decorates { (3, 2) } else { (1, 1) };
for radius in 2..=32 {
let r = Ranges {
center: (5, -7),
radius,
extra: &[],
forced: &forced,
};
let square = |x: i32, z: i32, n: i32| {
(-n..=n).flat_map(move |dz| (-n..=n).map(move |dx| (x + dx, z + dz)))
};
let generated = |x, z| {
(r.in_range(x, z, margin) || r.near_finished(x, z, reach))
&& (x - r.center.0).abs() <= radius + margin.max(reach + 1)
&& (z - r.center.1).abs() <= radius + margin.max(reach + 1)
};
let proto_kept = |x, z| r.in_range(x, z, 4) || r.near_finished(x, z, 2);
let decorated =
|x, z| !decorates || r.in_range(x, z, 2) || r.near_finished(x, z, 1);
let chunk_kept = |x, z| r.in_range(x, z, 2) || r.near_finished(x, z, 1);
let unloaded = |x, z| !r.in_range(x, z, 3) && !r.near_finished(x, z, 1);
let finishes = |x: i32, z: i32| {
r.in_range(x, z, 1)
&& chunk_kept(x, z)
&& !unloaded(x, z)
&& square(x, z, 1).all(|(nx, nz)| {
decorated(nx, nz)
&& (!decorates
|| square(nx, nz, 1)
.all(|(gx, gz)| generated(gx, gz) && proto_kept(gx, gz)))
&& generated(nx, nz)
&& proto_kept(nx, nz)
})
};
let (cx, cz) = r.center;
for (x, z) in square(cx, cz, 1) {
for (nx, nz) in square(x, z, 1) {
assert!(
finishes(nx, nz),
"radius {radius} (decorates: {decorates}): ({nx}, {nz}) never finishes"
);
}
}
}
}
}
}