Merge remote-tracking branch 'origin/main' into pr854

# Conflicts:
#	crates/horizon-client/src/game/remote.rs
This commit is contained in:
Ludovic Marie
2026-10-19 06:40:04 +02:00
294 changed files with 22390 additions and 3361 deletions
+18 -25
View File
@@ -48,11 +48,20 @@ impl TerrainBlockStates for Properties {
self.0[id.0 as usize]
}
}
/// The block registry and the facts read from `facts.json` and the block tags:
/// everything world generation and collisions need, with none of the block
/// models or baked sprites.
pub struct Assets {
/// Leaked once per process: shared by world generation threads.
pub registry: &'static BlockRegistry,
pub properties: Properties,
pub material_states: [BlockStateId; 6],
/// Block names in `#minecraft:blocks_fluid_flow` (fluid flow vectors).
pub blocks_fluid_flow: BTreeSet<String>,
}
/// The block models and their baked sprites, read from the pack at `root` over
/// an existing block registry: everything the mesher and renderer need.
pub struct RenderAssets {
pub sprite_size: u32,
pub sprite_minimum_size: u32,
pub pixels: Vec<u8>,
@@ -67,8 +76,6 @@ pub struct Assets {
pub translucent_layers: Vec<bool>,
/// Each layer's `MipmapGenerator` settings.
pub sprite_mips: Vec<crate::mipmap::Settings>,
/// Block names in `#minecraft:blocks_fluid_flow` (fluid flow vectors).
pub blocks_fluid_flow: BTreeSet<String>,
}
fn invalid(message: &str) -> io::Error {
io::Error::new(io::ErrorKind::InvalidData, message)
@@ -152,33 +159,23 @@ impl Assets {
// past vanilla's 16-bit global palette.
crate::chunk::set_block_states(registry.len());
let registry: &'static BlockRegistry = Box::leak(Box::new(registry));
Self::with_models(
root,
Ok(Self {
registry,
properties,
material_states,
blocks_fluid_flow,
)
})
}
/// The same blocks with the models and sprites of another resource root
/// The models and sprites of another resource root over these blocks
/// (resource packs changed): the registry and block facts come from the
/// game data, which resource packs do not touch.
pub fn reload(&self, root: &Path) -> Result<Self> {
Self::with_models(
root,
self.registry,
self.properties.clone(),
self.material_states,
self.blocks_fluid_flow.clone(),
)
pub fn reload(&self, root: &Path) -> Result<RenderAssets> {
RenderAssets::load(root, self)
}
fn with_models(
root: &Path,
registry: &'static BlockRegistry,
properties: Properties,
material_states: [BlockStateId; 6],
blocks_fluid_flow: BTreeSet<String>,
) -> Result<Self> {
}
impl RenderAssets {
pub fn load(root: &Path, assets: &Assets) -> Result<Self> {
let registry = assets.registry;
let mut sprites = crate::sprites::Sprites::default();
for name in MATERIALS {
sprites.insert(root, &format!("minecraft:block/{name}"))?;
@@ -202,9 +199,6 @@ impl Assets {
}
sprites.finish();
Ok(Self {
registry,
properties,
material_states,
sprite_size: sprites.size,
sprite_minimum_size: sprites.minimum_size,
texture_layers: u32::try_from(sprites.count())?,
@@ -217,7 +211,6 @@ impl Assets {
sprite_layers: sprites.layers,
translucent_layers: sprites.translucent,
sprite_mips: sprites.mips,
blocks_fluid_flow,
})
}
}
+19 -2
View File
@@ -9,6 +9,7 @@ use crate::sound_engine::{
Sounds, TickContext,
};
use crate::sound_events::{Sound, SoundRegistry};
#[cfg(feature = "audio")]
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
use horizon_core::random::{LegacyRandom, RandomSource};
use std::{
@@ -134,8 +135,14 @@ fn attach(mixer: &Mutex<Mixer>, channel: ChannelId, samples: Samples, looping: b
c.looping |= looping;
}
}
/// The open output stream. A build without the `audio` feature (the server build, which must not
/// need libasound) never has one.
#[cfg(feature = "audio")]
type Stream = cpal::Stream;
#[cfg(not(feature = "audio"))]
type Stream = std::convert::Infallible;
pub struct Audio {
_stream: Option<cpal::Stream>,
_stream: Option<Stream>,
pub engine: SoundEngine,
backend: MixerBackend,
/// Record `Heard` sounds (the subtitle overlay is listening).
@@ -333,6 +340,8 @@ fn distance_gain(linear: Option<f32>, distance: f32) -> f32 {
Some(_) => 0.0,
}
}
// Only the output stream mixes; a build without one (no `audio` feature) never does.
#[cfg_attr(not(feature = "audio"), allow(dead_code))]
fn mix(mixer: &mut Mixer, data: &mut [f32], channels: usize, rate: u32) {
data.fill(0.0);
let listener = mixer.listener;
@@ -415,6 +424,7 @@ fn mix(mixer: &mut Mixer, data: &mut [f32], channels: usize, rate: u32) {
/// `HORIZON_NO_AUDIO`, or a virtual screen (`vscreen`), where agents and
/// harnesses run the game and must stay off the user's speakers.
/// `HORIZON_AUDIO=1` opens the output anyway (testing into a null sink).
#[cfg(any(feature = "audio", test))]
fn output_disabled(var: impl Fn(&str) -> Option<std::ffi::OsString>) -> Option<String> {
if var("HORIZON_NO_AUDIO").is_some() {
return Some("audio off: HORIZON_NO_AUDIO is set".into());
@@ -430,6 +440,7 @@ fn output_disabled(var: impl Fn(&str) -> Option<std::ffi::OsString>) -> Option<S
}
/// An output stream on `device` in its default configuration, whatever its
/// sample format: the mixer works in f32 and converts.
#[cfg(feature = "audio")]
fn open_device(
device: &cpal::Device,
mixer: Arc<Mutex<Mixer>>,
@@ -450,6 +461,7 @@ fn open_device(
stream.play()?;
Ok((stream, config))
}
#[cfg(feature = "audio")]
fn build_stream<T: cpal::SizedSample + cpal::FromSample<f32>>(
device: &cpal::Device,
config: &cpal::SupportedStreamConfig,
@@ -523,7 +535,12 @@ impl Audio {
capture: None,
}
}
fn open(mixer: Arc<Mutex<Mixer>>) -> Result<cpal::Stream> {
#[cfg(not(feature = "audio"))]
fn open(_: Arc<Mutex<Mixer>>) -> Result<Stream> {
Err("this build has no sound output (built without the `audio` feature)".into())
}
#[cfg(feature = "audio")]
fn open(mixer: Arc<Mutex<Mixer>>) -> Result<Stream> {
if let Some(reason) = output_disabled(|name| std::env::var_os(name)) {
return Err(reason.into());
}
@@ -343,7 +343,7 @@ pub const COMMANDS: &[Cmd] = &[
cmd!("bench", Scripting, "bench SECONDS", "reset frame stats, wait, reply with the summary", "", ["horizon-ctl bench 10"], &[], mcp: false, local: false),
cmd!("stats", Scripting, "stats [reset]", "frame-time summary since the last reset", "", ["horizon-ctl stats"], &[], mcp: false, local: false),
cmd!("fly", Scripting, "fly X1 Y1 Z1 X2 Y2 Z2 SECONDS [PITCH [raw]]", "fly the camera along a line, then reply with the frame summary",
"With raw, the reply also lists every frame time in milliseconds (frame_ms).",
"The reply's tick_ms and tick_ms_max are the world's smoothed tick time over the flight (the server thread's when single player runs on one). With raw, the reply also lists every frame time in milliseconds (frame_ms).",
["horizon-ctl fly 0 100 0 500 100 0 20"], &[], mcp: false, local: false),
];
@@ -215,7 +215,12 @@ impl Session {
let deadline = Instant::now() + Duration::from_secs_f64(limit.max(0.0));
loop {
let status = self.game("status")?;
if !status["player"].is_null() && status["pending_chunks"] == 0 {
// On a server (single player's server thread too), also the
// level around the player.
if !status["player"].is_null()
&& status["pending_chunks"] == 0
&& status["server"]["loaded"] != false
{
return Ok(status);
}
if Instant::now() > deadline {
+102 -5
View File
@@ -3,7 +3,7 @@
//! (copy-on-write through `Arc::make_mut`).
use horizon_core::paletted::{PalettedContainer, Strategy};
use horizon_world::registry::BlockStateId;
use std::sync::Arc;
use std::sync::{Arc, OnceLock};
pub const MIN_Y: i32 = -64;
pub const HEIGHT: i32 = 384;
@@ -45,6 +45,10 @@ impl Light {
}
}
#[inline]
fn column(x: i32, z: i32) -> usize {
((z & 15) << 4 | (x & 15)) as usize
}
#[inline]
pub fn index(x: i32, y: i32, z: i32) -> usize {
((y & 15) << 8 | (z & 15) << 4 | (x & 15)) as usize
}
@@ -118,8 +122,10 @@ pub struct Chunk {
pub x: i32,
pub z: i32,
pub sections: Vec<Arc<Section>>,
/// Highest non-air, light-blocking-or-fluid Y per column (MOTION_BLOCKING-like), for rain/sky.
pub heights: Arc<[i16; 256]>,
/// `Heightmap.Types.WORLD_SURFACE` per column (`z << 4 | x`): one above
/// the highest non-air block, or `MIN_Y`. Built on the first read; a
/// `set` that can move a column's surface drops it.
surface: OnceLock<Box<[i16; 256]>>,
pub lit: bool,
/// Light read from a save with `isLightOn`: no light job is needed.
pub light_loaded: bool,
@@ -148,7 +154,7 @@ impl Chunk {
sections: (0..SECTIONS)
.map(|_| Arc::new(Section::default()))
.collect(),
heights: Arc::new([MIN_Y as i16; 256]),
surface: OnceLock::new(),
lit: false,
light_loaded: false,
fresh: false,
@@ -190,7 +196,52 @@ impl Chunk {
if !(0..SECTIONS as i32).contains(&s) {
return v;
}
Arc::make_mut(&mut self.sections[s as usize]).set(index(x, y, z), v)
let previous = Arc::make_mut(&mut self.sections[s as usize]).set(index(x, y, z), v);
// `Heightmap.update`: a write two or more below the surface can't
// move it. Any other change rebuilds the map on the next read.
if previous != v
&& let Some(surface) = self.surface.get()
&& y >= i32::from(surface[column(x, z)]) - 1
{
self.surface = OnceLock::new();
}
previous
}
/// `getHeight(Heightmap.Types.WORLD_SURFACE, x, z)` (`x`, `z` within the
/// chunk): one above the highest block that isn't `air`, or `MIN_Y`.
/// Sections must change only through `set` once this has been read.
pub fn world_surface(&self, x: i32, z: i32, air: impl Fn(u32) -> bool) -> i32 {
let surface = self.surface.get_or_init(|| self.prime_surface(air));
i32::from(surface[column(x, z)])
}
/// `Heightmap.primeHeightmaps` for WORLD_SURFACE: each section from the
/// top, skipping those of one air state, until every column is found.
fn prime_surface(&self, air: impl Fn(u32) -> bool) -> Box<[i16; 256]> {
let mut surface = Box::new([MIN_Y as i16; 256]);
let mut found = [false; 256];
let mut left = 256;
let mut values = [0u32; 4096];
for (s, section) in self.sections.iter().enumerate().rev() {
if left == 0 {
break;
}
if section.blocks.uniform().is_some_and(&air) {
continue;
}
section.unpack(&mut values);
let base = MIN_Y + s as i32 * 16;
for i in 0..256 {
if found[i] {
continue;
}
if let Some(dy) = (0..16).rev().find(|&dy| !air(values[dy << 8 | i])) {
surface[i] = (base + dy as i32 + 1) as i16;
found[i] = true;
left -= 1;
}
}
}
surface
}
#[inline]
pub fn light(&self, x: i32, y: i32, z: i32) -> u8 {
@@ -261,4 +312,50 @@ mod tests {
);
assert_eq!(Chunk::empty(0, 0).highest(air, |_| unreachable!()), None);
}
/// The kept WORLD_SURFACE heights match a scan of every column after
/// each of a few thousand writes (air, cave air, stone, whole sections).
#[test]
fn world_surface_follows_writes() {
let (air, cave_air, stone) = (0, 7, 1);
let is_air = |v: u32| v == air || v == cave_air;
let scan = |c: &Chunk, x: i32, z: i32| {
(MIN_Y..MIN_Y + HEIGHT)
.rev()
.find(|&y| !is_air(c.get(x, y, z)))
.map_or(MIN_Y, |y| y + 1)
};
let mut chunk = Chunk::empty(0, 0);
assert_eq!(chunk.world_surface(5, 5, is_air), MIN_Y);
for y in MIN_Y..MIN_Y + 70 {
for i in 0..256 {
chunk.set(i & 15, y, i >> 4, stone);
}
}
for i in 0..4096 {
Arc::make_mut(&mut chunk.sections[8]).set(i, cave_air);
}
let mut random = horizon_core::random::LegacyRandom::new(9);
use horizon_core::random::RandomSource;
for step in 0..4000 {
let x = random.next_int_bound(16).unwrap();
let z = random.next_int_bound(16).unwrap();
let y = MIN_Y + 40 + random.next_int_bound(120).unwrap();
let v = [air, cave_air, stone][random.next_int_bound(3).unwrap() as usize];
chunk.set(x, y, z, v);
if step % 7 == 0 {
for i in 0..256 {
assert_eq!(
chunk.world_surface(i & 15, i >> 4, is_air),
scan(&chunk, i & 15, i >> 4)
);
}
}
}
// Out-of-range writes and unchanged states keep the map.
let before = chunk.world_surface(3, 3, is_air);
chunk.set(3, MIN_Y + HEIGHT, 3, stone);
chunk.set(3, before - 1, 3, chunk.get(3, before - 1, 3));
assert!(chunk.surface.get().is_some());
assert_eq!(chunk.world_surface(3, 3, |_| unreachable!()), before);
}
}
+72 -67
View File
@@ -336,73 +336,8 @@ impl PlayerEffects {
pub fn modifiers(&self) -> Vec<(&'static str, &'static str, f64, &'static str)> {
let mut out = Vec::new();
for e in &self.list {
let level = f64::from(e.amplifier + 1);
let m = match e.id {
"speed" => Some((
"minecraft:movement_speed",
"minecraft:effect.speed",
0.2,
"add_multiplied_total",
)),
"slowness" => Some((
"minecraft:movement_speed",
"minecraft:effect.slowness",
-0.15,
"add_multiplied_total",
)),
"haste" => Some((
"minecraft:attack_speed",
"minecraft:effect.haste",
0.1,
"add_multiplied_total",
)),
"mining_fatigue" => Some((
"minecraft:attack_speed",
"minecraft:effect.mining_fatigue",
-0.1,
"add_multiplied_total",
)),
"strength" => Some((
"minecraft:attack_damage",
"minecraft:effect.strength",
3.0,
"add_value",
)),
"weakness" => Some((
"minecraft:attack_damage",
"minecraft:effect.weakness",
-4.0,
"add_value",
)),
"jump_boost" => Some((
"minecraft:safe_fall_distance",
"minecraft:effect.jump_boost",
1.0,
"add_value",
)),
"health_boost" => Some((
"minecraft:max_health",
"minecraft:effect.health_boost",
4.0,
"add_value",
)),
"absorption" => Some((
"minecraft:max_absorption",
"minecraft:effect.absorption",
4.0,
"add_value",
)),
"luck" => Some(("minecraft:luck", "minecraft:effect.luck", 1.0, "add_value")),
"unluck" => Some((
"minecraft:luck",
"minecraft:effect.unluck",
-1.0,
"add_value",
)),
_ => None,
};
if let Some((a, id, amount, op)) = m {
out.push((a, id, amount * level, op));
if let Some((a, id, amount, op)) = effect_modifier(e.id) {
out.push((a, id, amount * f64::from(e.amplifier + 1), op));
}
}
out
@@ -445,6 +380,76 @@ impl StatusFlags {
}
}
/// The attribute modifier an effect adds at amplifier 0
/// (`MobEffect.addAttributeModifier`): (attribute, id, amount, operation).
/// Each level multiplies the amount (`amplifier + 1`).
pub fn effect_modifier(effect: &str) -> Option<(&'static str, &'static str, f64, &'static str)> {
match effect {
"speed" => Some((
"minecraft:movement_speed",
"minecraft:effect.speed",
0.2,
"add_multiplied_total",
)),
"slowness" => Some((
"minecraft:movement_speed",
"minecraft:effect.slowness",
-0.15,
"add_multiplied_total",
)),
"haste" => Some((
"minecraft:attack_speed",
"minecraft:effect.haste",
0.1,
"add_multiplied_total",
)),
"mining_fatigue" => Some((
"minecraft:attack_speed",
"minecraft:effect.mining_fatigue",
-0.1,
"add_multiplied_total",
)),
"strength" => Some((
"minecraft:attack_damage",
"minecraft:effect.strength",
3.0,
"add_value",
)),
"weakness" => Some((
"minecraft:attack_damage",
"minecraft:effect.weakness",
-4.0,
"add_value",
)),
"jump_boost" => Some((
"minecraft:safe_fall_distance",
"minecraft:effect.jump_boost",
1.0,
"add_value",
)),
"health_boost" => Some((
"minecraft:max_health",
"minecraft:effect.health_boost",
4.0,
"add_value",
)),
"absorption" => Some((
"minecraft:max_absorption",
"minecraft:effect.absorption",
4.0,
"add_value",
)),
"luck" => Some(("minecraft:luck", "minecraft:effect.luck", 1.0, "add_value")),
"unluck" => Some((
"minecraft:luck",
"minecraft:effect.unluck",
-1.0,
"add_value",
)),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
+2 -1
View File
@@ -602,9 +602,10 @@ mod fire_environment_tests {
return;
}
let assets = crate::assets::Assets::load(&root).unwrap();
let render = assets.reload(&root).unwrap();
let facts = BlockFacts::load(&root, assets.registry).unwrap();
let items = crate::items::Items::load(&root, assets.registry, &facts).unwrap();
let mut world = World::test_scene(&assets, 3).unwrap();
let mut world = World::test_scene(&assets, &render, 3).unwrap();
let at = Vec3::new(20.5, 4.0, 20.5);
world
.set(
+5 -2
View File
@@ -840,9 +840,12 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
m.species(),
crate::mobs::Species::Slime | crate::mobs::Species::MagmaCube
) {
let health = m.health;
// AbstractCubeMob.readAdditionalSaveData: the size's attributes, then
// the saved health, the max health when there is none.
crate::mobs::cube::set_size(&mut m, number(tag.get("Size")).unwrap_or(0) as i32 + 1);
m.health = health;
if let Some(h) = float(tag.get("Health")) {
m.health = h as f32;
}
m.extra.flag2 = flag(tag, "wasOnGround");
}
// Zombie, Piglin and Zoglin.readAdditionalSaveData: IsBaby (the baby
+1
View File
@@ -32,6 +32,7 @@ pub struct FogData {
}
/// Per-biome water fog end multipliers (`visual/water_fog_end_distance`).
#[derive(Default)]
pub struct FogTables {
water_fog_end: Vec<f32>,
}
File diff suppressed because it is too large Load Diff
+39 -26
View File
@@ -106,7 +106,7 @@ impl adv::World for View<'_, '_> {
.map(|c| {
self.0
.res
.biomes
.biomes()
.get(c.biome(p[0], p[1], p[2]))
.name
.clone()
@@ -118,7 +118,7 @@ impl adv::World for View<'_, '_> {
}
fn block(&self, p: [i32; 3]) -> (String, BTreeMap<String, String>) {
let state = self.0.world.block(p[0], p[1], p[2]);
let name = self.0.res.facts.get(state).name.to_string();
let name = self.0.res.facts().get(state).name.to_string();
let props = self
.0
.pack
@@ -138,7 +138,7 @@ impl adv::World for View<'_, '_> {
match self
.0
.res
.facts
.facts()
.get(self.0.world.block(p[0], p[1], p[2]))
.fluid
{
@@ -152,7 +152,7 @@ impl adv::World for View<'_, '_> {
!self
.0
.res
.facts
.facts()
.get(self.0.world.block(p[0], y, p[2]))
.full_collision
})
@@ -165,19 +165,19 @@ impl adv::World for View<'_, '_> {
(1..=5).any(|d| {
self.0
.res
.facts
.facts()
.get(self.0.world.block(p[0], p[1] - d, p[2]))
.name
.ends_with("campfire")
})
}
fn in_tag(&self, registry: &str, tag: &str, id: &str) -> bool {
let items = &self.0.res.items;
let items = &self.0.res.items();
match registry {
"item" => items.item_tags.get(tag).is_some_and(|t| t.contains(id)),
"block" => items.block_tags.get(tag).is_some_and(|t| t.contains(id)),
"entity_type" => self.0.res.mob_data.entity_has(tag, id),
"worldgen/biome" => self.0.res.mob_data.biome_has(tag, id),
"entity_type" => self.0.res.mob_data().entity_has(tag, id),
"worldgen/biome" => self.0.res.mob_data().biome_has(tag, id),
_ => false,
}
}
@@ -408,6 +408,9 @@ impl Game<'_> {
}
}
}
if hits.is_empty() {
return;
}
let date = now_text();
for (ai, ci) in hits {
let a = &tree.list[ai];
@@ -454,17 +457,17 @@ impl Game<'_> {
.rewards
.recipes
.iter()
.filter(|r| self.res.stations.recipe_index.contains(r))
.filter(|r| self.res.stations().recipe_index.contains(r))
.cloned()
.collect();
let (_, unlocked) = self
.level
.recipe_book
.add_recipes(&self.res.stations.recipe_index, &rewards);
.add_recipes(&self.res.stations().recipe_index, &rewards);
for table in &a.rewards.loot {
let items = self
.res
.items
.items()
.loot_table(table, false, None, &mut self.world.random);
for s in items {
if let Some(rest) = self.give(s)
@@ -497,10 +500,13 @@ impl Game<'_> {
// PlayerList.broadcastSystemMessage: everyone hears of a
// network player's advancement.
match self.lan_acting_name.clone() {
Some(player) => self
.adv
.announced
.push(Text::translate(key, &[Text::literal(&player), name])),
// Player.getDisplayName.
Some(_) => {
let player = self.target_name(super::commands::Target::Player);
self.adv
.announced
.push(Text::translate(key, &[player, name]));
}
None => self.system_message(Text::translate(
key,
&[Text::literal(super::chat::PLAYER_NAME), name],
@@ -549,7 +555,7 @@ impl Game<'_> {
.filter_map(|s| s.as_ref())
.filter(|s| {
self.res
.items
.items()
.get(&s.item)
.is_some_and(|i| s.count >= i.max_stack)
})
@@ -790,11 +796,11 @@ impl Game<'_> {
if let Some((station, item)) = recipe {
// RecipeToast: black description under a purple title, the
// station at 0.6 scale in the corner over the cycling result.
let atlas = &self.atlas;
let atlas = &self.gui.atlas;
batch.sprite(atlas, "gui/sprites/toast/recipe", x, 0.0);
let title = self.translate("recipe.toast.title", "New Recipe(s) Unlocked!");
let description = self.translate("recipe.toast.description", "Check your recipe book");
let atlas = &self.atlas;
let atlas = &self.gui.atlas;
batch.text(atlas, &title, x + 30.0, 7.0, 0xFF50_0050, false);
batch.text(atlas, &description, x + 30.0, 18.0, 0xFF00_0000, false);
let start = batch.vertices.len();
@@ -803,7 +809,7 @@ impl Game<'_> {
self.draw_item_model(batch, &item, x + 8.0, 8.0);
return;
}
let atlas = &self.atlas;
let atlas = &self.gui.atlas;
batch.sprite(atlas, "gui/sprites/toast/advancement", x, 0.0);
let (key, color) = match frame {
Frame::Task => ("advancements.toast.task", 0xFF00_FFFF),
@@ -832,18 +838,25 @@ pub(super) fn adv_name(a: &adv::Advancement) -> Text {
Frame::Challenge => text::DARK_PURPLE,
_ => text::GREEN,
};
let tooltip = text_of(&d.title)
.with_color(color)
// Advancement.decorateName: the title in the frame's colour (styles
// merged into it), a new line and the description.
let coloured = text_of(&d.title).with_color(color);
let mut component = coloured.component();
if let Some(o) = component.as_object_mut() {
o.insert(
"extra".into(),
serde_json::json!(["\n", text_of(&d.description).component()]),
);
}
let tooltip = coloured
.append("\n")
.append(text_of(&d.description));
.append(text_of(&d.description))
.with_component(component);
let title = text_of(&d.title).with_style(&Style {
hover: Some(Box::new(tooltip)),
..Style::default()
});
Text::literal("[")
.append(title)
.append("]")
.with_color(color)
Text::translate("chat.square_brackets", &[title]).with_color(color)
}
impl Game<'_> {
/// `AdvancementCommands.Action.GRANT` on one advancement (or one of
@@ -269,7 +269,7 @@ impl Game<'_> {
}
/// `AdvancementWidget`'s title lines, description lines and width.
fn adv_widget_text(&self, i: usize) -> (Vec<Text>, Vec<Text>, f32) {
let font = &self.atlas.font;
let font = &self.gui.atlas.font;
let a = &self.adv.tree.list[i];
let Some(d) = &a.display else {
return (Vec::new(), Vec::new(), 0.0);
@@ -332,7 +332,7 @@ impl Game<'_> {
let (sx, sy) = self.adv_ui.scroll.unwrap_or_default();
let (sx, sy) = (sx.floor() as i32, sy.floor() as i32);
self.adv_tick_hover(&view, sx, sy, left, top);
let atlas = &self.atlas;
let atlas = &self.gui.atlas;
ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true);
let title = Text::translate("gui.advancements", &[]);
let tw = atlas.font.width_text(&title);
@@ -444,7 +444,7 @@ impl Game<'_> {
}
let (x, y) = pos(i);
let (x, y) = ((ox + x) as f32, (oy + y) as f32);
let atlas = &self.atlas;
let atlas = &self.gui.atlas;
batch.sprite_scaled(
atlas,
frame_sprite(d.frame, done),
@@ -461,7 +461,7 @@ impl Game<'_> {
}
}
// The window, tabs and title.
let atlas = &self.atlas;
let atlas = &self.gui.atlas;
batch.sprite_region(
atlas,
"gui/advancements/window",
@@ -475,7 +475,7 @@ impl Game<'_> {
let (x, y) = tab_pos(ty, i);
let sprite = tab_sprite(ty, i, ty.3, Some(t) == tab);
batch.sprite_scaled(
&self.atlas,
&self.gui.atlas,
&sprite,
left + x,
top + y,
@@ -494,7 +494,7 @@ impl Game<'_> {
}
}
}
let atlas = &self.atlas;
let atlas = &self.gui.atlas;
let title = tab.and_then(|t| tree.list[t].display.as_ref()).map_or_else(
|| Text::translate("gui.advancements", &[]),
|d| text_of(&d.title),
@@ -509,7 +509,7 @@ impl Game<'_> {
}
}
// Done.
let atlas = &self.atlas;
let atlas = &self.gui.atlas;
let (bx, by) = ((w / 2.0 - 100.0).floor(), h - FOOTER + 6.0);
let hover = ui::hovered(self.cursor, bx, by, 200.0, 20.0);
ui::button(
@@ -532,7 +532,7 @@ impl Game<'_> {
let (cx, cy) = self.cursor;
if cx > x && cx < x + ty.1 && cy > y && cy < y + ty.2 {
if let Some(d) = &tree.list[t].display {
ui::tooltip(batch, &self.atlas, &[text_of(&d.title)], self.cursor);
ui::tooltip(batch, &self.gui.atlas, &[text_of(&d.title)], self.cursor);
}
break;
}
@@ -616,7 +616,7 @@ impl Game<'_> {
],
)
});
let atlas = &self.atlas;
let atlas = &self.gui.atlas;
let progress_w = progress.as_ref().map_or(0.0, |t| atlas.font.width_text(t)) as i32;
let top_side = title_bottom + desc_h >= INSIDE_H;
let amount = if a.criteria.is_empty() || total == 0 {
+41 -17
View File
@@ -325,7 +325,7 @@ impl Game<'_> {
let state = self.world.block(pos[0], pos[1], pos[2]);
let mut v = json!({
"pos": pos,
"block": &*self.res.facts.get(state).name,
"block": &*self.res.facts().get(state).name,
"state": self.state_string(state),
"loaded": self.world.chunks.contains_key(&(pos[0] >> 4, pos[2] >> 4)),
});
@@ -477,6 +477,8 @@ impl Game<'_> {
"sleeping": self.sleeping,
// The item in use: its slot and for how many ticks.
"using": self.using.map(|(slot, ticks)| json!({ "slot": slot, "ticks": ticks })),
// The arm swings started (LivingEntity.swing).
"swings": self.swings_started,
"time": { "day_time": self.world.day_time, "day": self.world.day_time.div_euclid(24000), "time_of_day": self.world.day_time.rem_euclid(24000) },
"weather": { "raining": self.world.weather.raining, "thundering": self.world.weather.thundering },
"paused": self.pause,
@@ -579,7 +581,7 @@ impl Game<'_> {
push(
[m.position.x, m.position.y, m.position.z],
m.kind.id.as_ref(),
json!({ "id": m.id, "kind": "mob", "health": m.health, "baby": m.is_baby() }),
json!({ "id": m.id, "kind": "mob", "health": m.health, "baby": m.is_baby(), "hurt_time": m.hurt_time }),
);
}
for item in &self.dropped {
@@ -677,17 +679,25 @@ impl Game<'_> {
/// Whether a block stops movement, for the path finder.
fn blocks_motion(&self, pos: [i32; 3]) -> bool {
let f = self.res.facts.get(self.world.block(pos[0], pos[1], pos[2]));
let f = self
.res
.facts()
.get(self.world.block(pos[0], pos[1], pos[2]));
f.full_collision || f.legacy_solid
}
fn walkable(&self, n: Node) -> bool {
let below = self.world.block(n[0], n[1] - 1, n[2]);
let lava = |p: [i32; 3]| {
&*self.res.facts.get(self.world.block(p[0], p[1], p[2])).name == "minecraft:lava"
&*self
.res
.facts()
.get(self.world.block(p[0], p[1], p[2]))
.name
== "minecraft:lava"
};
self.world.chunks.contains_key(&(n[0] >> 4, n[2] >> 4))
&& (self.blocks_motion([n[0], n[1] - 1, n[2]])
|| self.res.facts.get(below).fluid != horizon_client::blocks::Fluid::None)
|| self.res.facts().get(below).fluid != horizon_client::blocks::Fluid::None)
&& !self.blocks_motion(n)
&& !self.blocks_motion([n[0], n[1] + 1, n[2]])
&& !lava(n)
@@ -748,7 +758,11 @@ impl Game<'_> {
if !clear || !self.walkable(m) {
continue;
}
let water = self.res.facts.get(self.world.block(m[0], m[1], m[2])).fluid
let water = self
.res
.facts()
.get(self.world.block(m[0], m[1], m[2]))
.fluid
!= horizon_client::blocks::Fluid::None;
let step = 10 + if dy != 0 { 5 } else { 0 } + if water { 30 } else { 0 };
let c = base + step;
@@ -958,10 +972,10 @@ impl Game<'_> {
for z in lo[2]..=hi[2] {
for x in lo[0]..=hi[0] {
let state = self.world.block(x, y, z);
if self.res.facts.is_air(state) {
if self.res.facts().is_air(state) {
continue;
}
let name = self.res.facts.get(state).name.to_string();
let name = self.res.facts().get(state).name.to_string();
*census.entry(name).or_insert(0) += 1;
list.push(json!([x, y, z, self.state_string(state)]));
}
@@ -1013,7 +1027,7 @@ impl Game<'_> {
for z in c[2] - radius..=c[2] + radius {
for x in c[0] - radius..=c[0] + radius {
let state = self.world.block(x, y, z);
if *self.res.facts.get(state).name == *want {
if *self.res.facts().get(state).name == *want {
let d = dist(eye, [x, y, z].map(|v| f64::from(v) + 0.5));
found.push((d, [x, y, z]));
}
@@ -1221,7 +1235,7 @@ impl Game<'_> {
self.playing()?;
let pos = a.block_pos(0)?;
let before = self.world.block(pos[0], pos[1], pos[2]);
if self.res.facts.is_air(before) {
if self.res.facts().is_air(before) {
return Err(format!("there is no block at {pos:?}").into());
}
self.aim_block(pos, None)?;
@@ -1250,24 +1264,24 @@ impl Game<'_> {
.ok_or("nothing in hand to place; select an item")?;
let held = held.item.clone();
let before = self.world.block(pos[0], pos[1], pos[2]);
if !self.res.facts.get(before).replaceable && !self.res.facts.is_air(before) {
if !self.res.facts().get(before).replaceable && !self.res.facts().is_air(before) {
return Err(format!(
"{pos:?} holds {}; break it first",
self.res.facts.get(before).name
self.res.facts().get(before).name
)
.into());
}
// A replaceable block there (grass, snow) is clicked itself, as
// a player would; otherwise the face of a neighbour touching it.
let mut aimed = !self.res.facts.is_air(before)
&& !self.res.facts.get(before).outline.is_empty()
let mut aimed = !self.res.facts().is_air(before)
&& !self.res.facts().get(before).outline.is_empty()
&& self.aim_block(pos, None).is_ok();
for (_, d) in FACES.iter().filter(|_| !aimed) {
let d = *d;
let support = add(pos, d);
let state = self.world.block(support[0], support[1], support[2]);
let f = self.res.facts.get(state);
if self.res.facts.is_air(state)
let f = self.res.facts().get(state);
if self.res.facts().is_air(state)
|| f.replaceable
|| f.fluid != horizon_client::blocks::Fluid::None && !f.waterlogged
{
@@ -1534,6 +1548,13 @@ impl Game<'_> {
return Err("command TEXT".into());
}
let command = format!("/{text}");
// Single player's console is its server thread's.
if let Some(server) = &self.integrated {
let chat = server
.call(move |g| g.owner_console_command(&command))
.ok_or("the integrated server stopped")?;
return ok(json!({ "ok": true, "chat": chat }));
}
if self.remote.is_some() {
self.send_chat(&command);
return ok(json!({ "ok": true }));
@@ -1933,7 +1954,10 @@ impl Game<'_> {
// Step up onto the next block, or out of water.
let in_water = {
let b = p.map(|v| v.floor() as i32);
self.res.facts.get(self.world.block(b[0], b[1], b[2])).fluid
self.res
.facts()
.get(self.world.block(b[0], b[1], b[2]))
.fluid
!= horizon_client::blocks::Fluid::None
};
if aim[1] > p[1] + 0.5 && horizontal(p, aim) < 1.6 && on_ground {
+5 -1
View File
@@ -29,7 +29,11 @@ impl Game<'_> {
continue;
};
let carried = self.mobs[i].extra.ints[1];
let max = self.res.items.get(&held).map_or(64, |i| i.max_stack as i32);
let max = self
.res
.items()
.get(&held)
.map_or(64, |i| i.max_stack as i32);
// GoToWantedItem / wantsToPickUp: the same item within 32.
let wanted = if griefing && carried < max && self.mobs[i].extra.ints[3] <= 0 {
self.dropped
+20 -10
View File
@@ -111,7 +111,12 @@ impl Game<'_> {
let Some(item) = item else {
continue;
};
let Some(asset) = self.res.items.get(item).and_then(|i| i.equip_asset.clone()) else {
let Some(asset) = self
.res
.items()
.get(item)
.and_then(|i| i.equip_asset.clone())
else {
continue;
};
let kind = if layer == "leggings" {
@@ -124,7 +129,7 @@ impl Game<'_> {
continue;
};
let (Some(r), Some(part)) = (
self.atlas.sprites.get(texture.as_str()),
self.gui.atlas.sprites.get(texture.as_str()),
assets.player.get(layer),
) else {
continue;
@@ -144,7 +149,7 @@ impl Game<'_> {
// BlockPlaceContext: a replaceable clicked block is replaced.
let clicked = self
.res
.facts
.facts()
.get(self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]));
let pos = if clicked.replaceable {
hit.pos
@@ -230,7 +235,7 @@ impl Game<'_> {
fn equipment_slot(&self, stack: &ItemStack) -> usize {
match self
.res
.items
.items()
.get(&stack.item)
.and_then(|i| i.equip_slot.as_deref())
{
@@ -377,9 +382,14 @@ impl Game<'_> {
subject: None,
};
let mut dead = Vec::new();
// ServerLevel.tick: only entities in entity-ticking chunks tick.
let ticking = self.entity_ticking_area();
for (i, a) in self.armor_stands.iter_mut().enumerate() {
if !ticking(a.position.x.floor() as i32, a.position.z.floor() as i32) {
continue;
}
a.tick(&mut scene);
if !a.environment_tick(&self.world, &self.res.facts, self.pack.assets.registry) {
if !a.environment_tick(&self.world, self.res.facts(), self.pack.assets.registry) {
dead.push(i);
}
}
@@ -403,7 +413,7 @@ impl Game<'_> {
out: &mut Vec<Vertex>,
) {
let assets = &self.armor_stand_assets;
let sprites = &self.atlas.sprites;
let sprites = &self.gui.atlas.sprites;
let uv_of = |name: &str| sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]);
let Some(wood) = uv_of("entity/armorstand/armorstand") else {
return;
@@ -516,7 +526,7 @@ impl Game<'_> {
};
let Some(asset) = self
.res
.items
.items()
.get(&stack.item)
.and_then(|i| i.equip_asset.clone())
else {
@@ -568,7 +578,7 @@ impl Game<'_> {
/// `Equippable.swapWithEquipmentSlot`: right-clicking armor swaps it into
/// its slot (the worn piece comes back to the hand).
pub(super) fn equip_from_hand(&mut self, stack: &ItemStack) -> bool {
let Some(info) = self.res.items.get(&stack.item) else {
let Some(info) = self.res.items().get(&stack.item) else {
return false;
};
let index = match info.equip_slot.as_deref() {
@@ -699,7 +709,7 @@ impl Game<'_> {
&serde_json::Value::Null,
false,
pose,
&self.atlas.sprites,
&self.gui.atlas.sprites,
&self.item_host(),
&mut sink,
);
@@ -709,7 +719,7 @@ impl Game<'_> {
if let Some(stack) = &a.equipment[5]
&& self
.res
.items
.items()
.get(&stack.item)
.is_none_or(|i| i.equip_asset.is_none())
&& let Some(head) = part_matrix(model, base, poses, "head", 0.0)
+17 -7
View File
@@ -71,8 +71,10 @@ impl Game<'_> {
}
/// Called every frame while the title is up.
pub(super) fn update_backdrop(&mut self) -> Result<()> {
let wanted = self.title.is_some()
let wanted = self.pending_entry.is_none()
&& self.title.is_some()
&& horizon_client::ui_theme::horizon()
&& self.world_renderer_ready
&& self.renderer.is_some()
&& self.options.frames.is_none();
if !wanted {
@@ -127,6 +129,10 @@ impl Game<'_> {
.is_some_and(|r| r.section_count() > 40)
{
self.backdrop.ready = Some(Instant::now());
log::info!(
"Horizon: title backdrop ready; world rest ready: {}",
self.res.rest.get().is_some()
);
}
Ok(())
}
@@ -139,10 +145,14 @@ impl Game<'_> {
}
}
fn surface_y(&self, x: i32, z: i32) -> Option<i32> {
let air = self.res.facts.air;
let air = self.res.facts().air;
(-60..320).rev().find(|&y| self.world.block(x, y, z) != air)
}
fn start_backdrop(&mut self) -> Result<()> {
log::info!(
"Horizon: starting title backdrop after {} ms",
self.started.elapsed().as_millis()
);
let seed = seed();
let root = std::env::current_dir()?
.join("saves")
@@ -155,7 +165,7 @@ impl Game<'_> {
VanillaTerrain::new(
&self.options.resources.join("worldgen"),
pack.assets.registry,
&res.biomes,
res.biomes(),
seed,
)
.map_err(|e| format!("title backdrop: {e}"))?,
@@ -165,10 +175,10 @@ impl Game<'_> {
inner: inner.clone(),
save: save.clone(),
registry: pack.assets.clone(),
biomes: res.biomes.clone(),
biomes: res.biomes().clone(),
}),
pack.context.clone(),
res.threads.min(6),
res.threads().min(6),
);
streaming.radius = self.settings.render_distance.clamp(4, 10);
streaming.biome_blend = self.settings.biome_blend;
@@ -179,7 +189,7 @@ impl Game<'_> {
streaming.paused = true;
self.streaming = streaming;
self.save = save;
let mut world = World::new(self.res.facts.air, seed);
let mut world = World::new(self.res.facts().air, seed);
world.day_time = DAY_TIME;
world.game_time = 6000;
// Light snow: the weather renders as snow in frozen biomes.
@@ -237,7 +247,7 @@ impl Game<'_> {
}
fn stop_backdrop(&mut self) {
self.streaming.paused = true;
self.world = World::new(self.res.facts.air, 0);
self.world = World::new(self.res.facts().air, 0);
if let Some(r) = self.renderer.as_mut() {
r.clear_sections();
}
+1 -1
View File
@@ -14,7 +14,7 @@ impl Game<'_> {
else {
return Vec::new();
};
layer_textures(&self.res.stations.banners, &b.layers)
layer_textures(&self.res.stations().banners, &b.layers)
}
}
+16 -13
View File
@@ -99,11 +99,8 @@ impl Game<'_> {
}
/// `getHeight(WORLD_SURFACE)`: above the highest non-air block.
pub(super) fn world_surface(&self, x: i32, z: i32) -> i32 {
let (min, max) = (super::MIN_Y, super::MIN_Y + super::HEIGHT);
(min..max)
.rev()
.find(|&y| !self.res.facts.is_air(self.world.block(x, y, z)))
.map_or(min, |y| y + 1)
self.world
.world_surface(x, z, |id| self.res.facts().is_air(id))
}
/// `BeaconBlockEntity.tick` of the beacon at `key`.
pub(super) fn tick_beacon_at(&mut self, key: (i32, i32, i32)) {
@@ -125,7 +122,7 @@ impl Game<'_> {
let mut i = 0;
while i < 10 && check <= surface {
let state = self.world.block(x, check, z);
let f = self.res.facts.get(state);
let f = self.res.facts().get(state);
if let Some(color) = self.beam_color(&f.name) {
if b.checking.len() <= 1 {
b.checking.push((color, 1));
@@ -186,7 +183,7 @@ impl Game<'_> {
fn beacon_base(&self, x: i32, y: i32, z: i32) -> i32 {
let base = self
.res
.items
.items()
.block_tags
.get("minecraft:beacon_base_blocks");
let mut levels = 0;
@@ -197,7 +194,7 @@ impl Game<'_> {
}
let ok = (x - step..=x + step).all(|lx| {
(z - step..=z + step).all(|lz| {
let name = &self.res.facts.get(self.world.block(lx, ly, lz)).name;
let name = &self.res.facts().get(self.world.block(lx, ly, lz)).name;
base.is_some_and(|t| t.contains(&**name))
})
});
@@ -378,7 +375,7 @@ impl Game<'_> {
let levels = self.beacon_levels();
let sel = self.station.as_ref().map_or([None; 2], |s| s.beacon);
let paid = self.station.as_ref().is_some_and(|s| s.inputs[0].is_some());
let atlas = &self.atlas;
let atlas = &self.gui.atlas;
batch.fill(
atlas,
0.0,
@@ -399,7 +396,7 @@ impl Game<'_> {
("block.minecraft.beacon.secondary", "Secondary Power", 169.0),
] {
let text = self.translate(key, fallback);
let atlas = &self.atlas;
let atlas = &self.gui.atlas;
let w = HudBatch::text_width(atlas, &text);
batch.text(
atlas,
@@ -414,7 +411,7 @@ impl Game<'_> {
let x = [20.0, 41.0, 63.0, 86.0, 108.0][i];
self.draw_item(batch, &ItemStack::new(item, 1), bx + x, by + 109.0);
}
let atlas = &self.atlas;
let atlas = &self.gui.atlas;
let mut tooltip = None;
let button =
|batch: &mut HudBatch, x: f32, y: f32, active: bool, selected: bool, icon: &str| {
@@ -496,7 +493,7 @@ impl Game<'_> {
if let Some(slot) = self.slot_at(batch, self.cursor.0, self.cursor.1) {
let (sx, sy) = self.slot_position(slot);
batch.fill(
&self.atlas,
&self.gui.atlas,
ox + sx,
oy + sy,
16.0,
@@ -517,7 +514,13 @@ impl Game<'_> {
}
/// `BeaconRenderer`: each section's rotating solid beam and its glow.
pub(super) fn beacon_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec<Vertex>) {
let Some(s) = self.atlas.sprites.get("entity/beacon/beacon_beam").copied() else {
let Some(s) = self
.gui
.atlas
.sprites
.get("entity/beacon/beacon_beam")
.copied()
else {
return;
};
let time = (self.world.game_time.rem_euclid(40)) as f32 + alpha as f32;
+4 -4
View File
@@ -41,7 +41,7 @@ impl HiveHost for GameHive<'_, '_> {
if !self
.game
.res
.mob_data
.mob_data()
.entity_has("minecraft:beehive_inhabitors", &kind)
{
return None;
@@ -72,10 +72,10 @@ impl Game<'_> {
/// The hive's honey level and front, from its block state.
pub(super) fn hive_state(&self, at: [i32; 3]) -> Option<(Option<i32>, [i32; 2])> {
let state = self.world.block(at[0], at[1], at[2]);
let name = &self.res.facts.get(state).name;
let name = &self.res.facts().get(state).name;
if !self
.res
.items
.items()
.block_tags
.get("minecraft:beehives")
.is_some_and(|t| t.contains(&**name))
@@ -108,7 +108,7 @@ impl Game<'_> {
.iter()
.any(|d| {
let state = self.world.block(at[0] + d[0], at[1] + d[1], at[2] + d[2]);
&*self.res.facts.get(state).name == "minecraft:fire"
&*self.res.facts().get(state).name == "minecraft:fire"
});
let mut host = GameHive { game: self };
if fire && !hive.bees.is_empty() {
@@ -193,7 +193,7 @@ impl Game<'_> {
};
let raiders = self
.res
.stations
.stations()
.enchantments
.entity_tags
.get("minecraft:raiders")
@@ -201,7 +201,7 @@ impl Game<'_> {
.unwrap_or_default();
let frames = self
.res
.items
.items()
.block_tags
.get("minecraft:conduit_effect_block")
.cloned()
@@ -285,7 +285,7 @@ impl Game<'_> {
}
Ticker::Conduit => {
let world = &self.world;
let facts = &self.res.facts;
let facts = self.res.facts();
let registry = self.pack.assets.registry;
let is_water = |p: [i32; 3]| {
facts.get(world.block(p[0], p[1], p[2])).fluid
@@ -372,7 +372,7 @@ impl Game<'_> {
/// pot's saved `sherds` (back, left, right, front).
pub(super) fn block_anim(&self, pos: [i32; 3], partial: f32) -> BlockAnim {
let state = self.world.block(pos[0], pos[1], pos[2]);
let sherds = if &*self.res.facts.get(state).name == "minecraft:decorated_pot" {
let sherds = if &*self.res.facts().get(state).name == "minecraft:decorated_pot" {
let sherds = self.saved_tag(pos).and_then(|t| t.get("sherds"));
["back", "left", "right", "front"].map(|side| match sherds.and_then(|s| s.get(side)) {
// An item id, or the item stack the processed templates hold.
@@ -76,7 +76,7 @@ impl Game<'_> {
(0..registry.len())
.map(|i| {
let state = BlockStateId(i as u32);
let name: &str = &self.res.facts.get(state).name;
let name: &str = &self.res.facts().get(state).name;
match name {
"minecraft:hopper"
| "minecraft:crafter"
@@ -101,27 +101,12 @@ impl Game<'_> {
})
.collect()
}
/// `ServerLevel.shouldTickBlocksAt`: chunks within the simulation
/// distance plus one (`DistanceManager.inBlockTickingRange`, Chebyshev
/// in chunks) of the player or a guest. With nobody there, a dedicated
/// server ticks none; the game alone (no player yet, headless fixtures)
/// ticks every chunk.
/// `ServerLevel.shouldTickBlocksAt` in a block-ticking chunk
/// (`LevelChunk.isTicking`, block coordinates), from every player's
/// tickets (`update_chunk_tickets`).
fn block_ticking_area(&self) -> impl Fn(i32, i32) -> bool + use<> {
let d = self.settings.simulation_distance.max(2) + 1;
let mut centres: Vec<(i32, i32)> = self.streaming.extra.iter().map(|&(c, _)| c).collect();
if let Some(p) = &self.player {
centres.push((
(p.position.x.floor() as i32) >> 4,
(p.position.z.floor() as i32) >> 4,
));
}
let everywhere = centres.is_empty() && self.options.dedicated.is_none();
move |x, z| {
everywhere
|| centres
.iter()
.any(|&(cx, cz)| ((x >> 4) - cx).abs().max(((z >> 4) - cz).abs()) <= d)
}
let levels = self.tickets.levels();
move |x, z| levels.block_ticking_at(x, z)
}
/// `AbstractFurnaceBlockEntity.serverTick` of the furnace at `pos`, and
/// its block's `lit` following it.
@@ -129,7 +114,7 @@ impl Game<'_> {
let Some(BlockEntity::Furnace(f)) = self.world.block_entities.get_mut(&pos) else {
return Ok(());
};
let Some(lit) = f.tick(&self.res.recipes, &self.res.items, &self.res.providers) else {
let Some(lit) = f.tick(self.res.recipes(), self.res.items(), self.res.providers()) else {
return Ok(());
};
let state = self.world.block(pos.0, pos.1, pos.2);
@@ -22,7 +22,7 @@ impl Game<'_> {
let entity = self.world.block_entities.get(&key)?;
let block = &self
.res
.facts
.facts()
.get(self.world.block(key.0, key.1, key.2))
.name;
let mut tag = save::encode_block_entity(key, entity, block);
@@ -37,7 +37,7 @@ impl Game<'_> {
pub(super) fn picked_stack(&self, pos: [i32; 3], include_data: bool) -> Option<ItemStack> {
let key = (pos[0], pos[1], pos[2]);
let state = self.world.block(pos[0], pos[1], pos[2]);
let facts = self.res.facts.get(state);
let facts = self.res.facts().get(state);
if &*facts.item == "minecraft:air" {
return None;
}
+1 -1
View File
@@ -47,7 +47,7 @@ impl Game<'_> {
format!("{}[{}]", s.name, props.join(","))
}
fn put_block(&mut self, pos: [i32; 3], state: BlockStateId) -> Result<()> {
let name = self.res.facts.get(state).name.clone();
let name = self.res.facts().get(state).name.clone();
self.world.block_entities.remove(&(pos[0], pos[1], pos[2]));
self.level_set(pos, state)?;
if let Some(entity) = BlockEntity::for_block(&name) {
+12 -6
View File
@@ -180,11 +180,11 @@ impl BoatModels {
}
impl Game<'_> {
fn fluid_height(&self, x: i32, y: i32, z: i32) -> Option<(f32, bool)> {
let f = self.res.facts.get(self.world.block(x, y, z));
let f = self.res.facts().get(self.world.block(x, y, z));
if f.fluid != Fluid::Water {
return None;
}
let above = self.res.facts.get(self.world.block(x, y + 1, z));
let above = self.res.facts().get(self.world.block(x, y + 1, z));
// FluidState.getHeight: 1 under the same fluid, else amount / 9.
let height = if above.fluid == Fluid::Water {
1.0
@@ -277,7 +277,7 @@ impl Game<'_> {
&& f64::from(x + 1) > lo.x
&& f64::from(z) < hi.z
&& f64::from(z + 1) > lo.z;
let f = self.res.facts.get(self.world.block(x, y0, z));
let f = self.res.facts().get(self.world.block(x, y0, z));
if inside && (f.full_collision || f.legacy_solid) && !f.has_class("LilyPadBlock") {
friction += f.friction;
count += 1;
@@ -443,8 +443,13 @@ impl Game<'_> {
}
/// Every boat but the ridden one (which ticks with its rider).
pub(super) fn tick_boats(&mut self) {
// ServerLevel.tick: only entities in entity-ticking chunks tick.
let ticking = self.entity_ticking_area();
for i in 0..self.boats.len() {
if Some(self.boats[i].id) == self.riding {
let p = self.boats[i].position;
if Some(self.boats[i].id) == self.riding
|| !ticking(p.x.floor() as i32, p.z.floor() as i32)
{
continue;
}
let b = self.boats[i].clone();
@@ -495,8 +500,8 @@ impl Game<'_> {
);
let top = b.bounds().max_position().y;
let (bx, by, bz) = (x.floor() as i32, top.floor() as i32, z.floor() as i32);
let below = self.res.facts.get(self.world.block(bx, by - 1, bz));
let here = self.res.facts.get(self.world.block(bx, by, bz));
let below = self.res.facts().get(self.world.block(bx, by - 1, bz));
let here = self.res.facts().get(self.world.block(bx, by, bz));
let target = if below.fluid != Fluid::Water
&& !here.full_collision
&& (below.full_collision || below.legacy_solid)
@@ -723,6 +728,7 @@ impl Game<'_> {
};
let folder = if b.chest { "chest_boat" } else { "boat" };
let Some(uv) = self
.gui
.atlas
.sprites
.get(&format!("entity/{folder}/{}", b.wood))
+4 -4
View File
@@ -45,7 +45,7 @@ pub(super) enum BookScreen {
}
impl Game<'_> {
fn book_lines(&self, page: &str) -> Vec<Text> {
self.atlas.font.split(&Text::literal(page), 114.0)
self.gui.atlas.font.split(&Text::literal(page), 114.0)
}
/// `WritableBookItem.use` / `WrittenBookItem.use`.
pub(super) fn use_book(&mut self, stack: &ItemStack) -> bool {
@@ -242,7 +242,7 @@ impl Game<'_> {
/// the page (`MultilineTextField.insertText`: line breaks kept, cut to
/// the 1024 characters left, rejected when it overflows the 14 lines).
fn book_shortcut(&mut self, shortcut: horizon_client::clipboard::EditShortcut) {
let font = &self.atlas.font;
let font = &self.gui.atlas.font;
match self.book.as_mut() {
Some(BookScreen::Edit {
signing: true,
@@ -397,7 +397,7 @@ impl Game<'_> {
let key = (pos[0], pos[1], pos[2]);
if &*self
.res
.facts
.facts()
.get(self.world.block(pos[0], pos[1], pos[2]))
.name
!= "minecraft:lectern"
@@ -549,7 +549,7 @@ impl Game<'_> {
}
pub(super) fn draw_book(&self, batch: &mut HudBatch) {
let Some(book) = &self.book else { return };
let atlas = &self.atlas;
let atlas = &self.gui.atlas;
let (w, h) = (batch.width, batch.height);
let (mx, my) = self.cursor;
let hover =
+1 -1
View File
@@ -40,7 +40,7 @@ impl Game<'_> {
m.position.z.floor() as i32,
);
let mut state = self.world.block(x, y, z);
if self.res.facts.is_air(state) {
if self.res.facts().is_air(state) {
state = self.world.block(x, (m.position.y - 0.2).floor() as i32, z);
}
let Some((sprite, tint)) = self.particle_sprite(state) else {
@@ -89,17 +89,17 @@ impl Game<'_> {
if is_locked {
locked = true;
if scaling || locking {
batch.sprite(&self.atlas, error, ox + 35.0, oy + 31.0);
batch.sprite(&self.gui.atlas, error, ox + 35.0, oy + 31.0);
}
}
if scaling && scale >= 4 {
locked = true;
batch.sprite(&self.atlas, error, ox + 35.0, oy + 31.0);
batch.sprite(&self.gui.atlas, error, ox + 35.0, oy + 31.0);
}
}
let sprite = |batch: &mut HudBatch, game: &Self, name: &str, x: f32, y: f32| {
batch.sprite(
&game.atlas,
&game.gui.atlas,
&format!("gui/sprites/container/cartography_table/{name}"),
ox + x,
oy + y,
+36 -18
View File
@@ -219,12 +219,18 @@ impl Game<'_> {
.map(|a| format!("minecraft:{a}"))
.collect();
let reg = &mut self.ui.registries;
let mut items: Vec<String> = self.res.items.order.iter().map(|s| s.to_string()).collect();
let mut items: Vec<String> = self
.res
.items()
.order
.iter()
.map(|s| s.to_string())
.collect();
items.sort();
reg.items = items;
reg.item_tags = self
.res
.items
.items()
.item_tags
.keys()
.map(|k| horizon_client::command::args::normalize(k))
@@ -232,7 +238,7 @@ impl Game<'_> {
reg.item_tags.sort();
reg.block_tags = self
.res
.items
.items()
.block_tags
.keys()
.map(|k| horizon_client::command::args::normalize(k))
@@ -259,7 +265,7 @@ impl Game<'_> {
.collect();
let mut summonable: Vec<String> = self
.res
.mob_types
.mob_types()
.keys()
.map(|k| horizon_client::command::args::normalize(k))
.collect();
@@ -405,7 +411,7 @@ impl Game<'_> {
.as_ref()
.map_or([1280, 720], |r| [r.config.width, r.config.height]);
let b = HudBatch::new(size);
let m = Measure(&self.atlas.font);
let m = Measure(&self.gui.atlas.font);
let c = Commands {
dispatcher: chat_tree(&self.remote, &self.mods),
registries: &self.ui.registries,
@@ -450,7 +456,7 @@ impl Game<'_> {
let focused = self.screen == Screen::Chat;
let heard = self.mods.mods.is_running().then(|| text.plain());
self.ui.chat.add(
&self.atlas,
&self.gui.atlas,
text,
Some(SYSTEM_INDICATOR),
self.ticks,
@@ -463,7 +469,7 @@ impl Game<'_> {
/// Keys while the chat screen is open.
pub(super) fn chat_key(&mut self, event: &KeyEvent) {
if let Some(shortcut) = self.edit_shortcut(event) {
let m = Measure(&self.atlas.font);
let m = Measure(&self.gui.atlas.font);
let c = Commands {
dispatcher: chat_tree(&self.remote, &self.mods),
registries: &self.ui.registries,
@@ -509,7 +515,7 @@ impl Game<'_> {
let Some(mut screen) = self.ui.chat_screen.take() else {
return;
};
let m = Measure(&self.atlas.font);
let m = Measure(&self.gui.atlas.font);
let c = Commands {
dispatcher: chat_tree(&self.remote, &self.mods),
registries: &self.ui.registries,
@@ -541,7 +547,7 @@ impl Game<'_> {
range: (usize, usize),
list: Vec<(String, Option<String>)>,
) {
let m = Measure(&self.atlas.font);
let m = Measure(&self.gui.atlas.font);
let c = Commands {
dispatcher: chat_tree(&self.remote, &self.mods),
registries: &self.ui.registries,
@@ -552,7 +558,7 @@ impl Game<'_> {
}
/// Text typed into the chat box (control socket `chat`).
pub(super) fn chat_type(&mut self, text: &str) {
let m = Measure(&self.atlas.font);
let m = Measure(&self.gui.atlas.font);
let c = Commands {
dispatcher: chat_tree(&self.remote, &self.mods),
registries: &self.ui.registries,
@@ -580,7 +586,7 @@ impl Game<'_> {
let heard = self.mods.mods.is_running().then(|| line.plain());
self.ui
.chat
.add(&self.atlas, line, None, self.ticks, focused);
.add(&self.gui.atlas, line, None, self.ticks, focused);
if let Some(line) = heard {
self.mods_chat(&line);
}
@@ -608,7 +614,7 @@ impl Game<'_> {
let height = self.renderer.as_ref().map_or(720.0, |r| {
HudBatch::new([r.config.width, r.config.height]).height
});
let m = Measure(&self.atlas.font);
let m = Measure(&self.gui.atlas.font);
let c = Commands {
dispatcher: chat_tree(&self.remote, &self.mods),
registries: &self.ui.registries,
@@ -621,7 +627,7 @@ impl Game<'_> {
return;
}
match self.ui.chat.click_at(
&self.atlas.font,
&self.gui.atlas.font,
height as i32,
cursor.0 as f64,
cursor.1 as f64,
@@ -647,13 +653,15 @@ impl Game<'_> {
if self.ui.hide_gui && !focused {
return;
}
self.ui.chat.draw(batch, &self.atlas, self.ticks, focused);
self.ui
.chat
.draw(batch, &self.gui.atlas, self.ticks, focused);
}
pub(super) fn draw_chat_screen(&mut self, batch: &mut HudBatch) {
let Some(mut screen) = self.ui.chat_screen.take() else {
return;
};
let m = Measure(&self.atlas.font);
let m = Measure(&self.gui.atlas.font);
let c = Commands {
dispatcher: chat_tree(&self.remote, &self.mods),
registries: &self.ui.registries,
@@ -671,7 +679,7 @@ impl Game<'_> {
.chat_opened
.map_or(0, |t| t.elapsed().as_millis() as u64);
let draws = screen.draw(&m, mouse, blink, background);
horizon_client::screen_draw::paint(batch, &self.atlas, &draws);
horizon_client::screen_draw::paint(batch, &self.gui.atlas, &draws);
self.ui.chat_screen = Some(screen);
}
/// Advance the overworld clock (ServerClockManager.tick) when
@@ -689,6 +697,16 @@ impl Game<'_> {
c.partial -= whole;
self.world.day_time += whole as i64;
}
/// `ServerClockInstance.packNetworkState`: the rate players' clients
/// advance the overworld clock at, 0 while it is paused (`/time pause`)
/// or `advance_time` is off.
pub(super) fn network_clock_rate(&self) -> f32 {
if self.ui.rules.bool("advance_time") && !self.ui.clock.paused {
self.ui.clock.rate
} else {
0.0
}
}
/// The engine-side rule values (block behaviour and health).
pub(super) fn level_rules(&self) -> horizon_world::level::GameRules {
let r = &self.ui.rules;
@@ -863,11 +881,11 @@ impl Game<'_> {
let focused = self.screen == Screen::Chat;
self.ui
.chat
.add(&self.atlas, message, None, self.ticks, focused);
.add(&self.gui.atlas, message, None, self.ticks, focused);
}
#[allow(dead_code)]
fn chat_debug_fill(&self, batch: &mut HudBatch) {
batch.fill(&self.atlas, 0.0, 0.0, 1.0, 1.0, rgba(0, 0, 0, 0));
batch.fill(&self.gui.atlas, 0.0, 0.0, 1.0, 1.0, rgba(0, 0, 0, 0));
}
}
/// `yyyy-MM-dd_HH.mm.ss[_n].png` (Util.getFilenameFormattedDateTime, local time
+2 -2
View File
@@ -114,7 +114,7 @@ impl Game<'_> {
let location = if let Some(c) = p.last_climbable {
let name = self
.res
.facts
.facts()
.get(self.world.block(c.x, c.y, c.z))
.name
.clone();
@@ -127,7 +127,7 @@ impl Game<'_> {
_ => "other_climbable",
})
} else {
let f = self.res.facts.get(self.world.block(
let f = self.res.facts().get(self.world.block(
p.position.x.floor() as i32,
(p.position.y + 0.1).floor() as i32,
p.position.z.floor() as i32,
@@ -356,7 +356,7 @@ impl Game<'_> {
eyes: false,
silent: false,
store: None,
elsewhere: false,
dimension: self.dim,
level: None,
block: Some(pos),
};
@@ -459,7 +459,7 @@ impl Game<'_> {
self.close_command_block();
return;
}
let atlas = &self.atlas;
let atlas = &self.gui.atlas;
let (w, h) = (batch.width, batch.height);
let mid = (w / 2.0).floor();
ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true);
@@ -4,7 +4,8 @@
//! command as the player (Commands.performPrefixedCommand) and records every
//! system message it produced, as styled spans, with the results reported to
//! the player's `CommandResultCallback`; `tick` advances the game; `settle`
//! waits until the terrain around the player is loaded.
//! waits until the terrain and entities around the player are loaded;
//! `portal` sends the player through the nether portal it stands in.
use super::Game;
use horizon_client::{Result, text::Text};
use serde_json::{Value, json};
@@ -40,6 +41,19 @@ pub(super) fn spans(text: &Text) -> Value {
}
impl Game<'_> {
/// The player's portal process finished in the nether portal it stands
/// in (the oracle's player is not ticked, so neither is the wait).
fn harness_portal(&mut self) -> Result<()> {
let Some(p) = &self.player else {
return Err("command harness: portal without a player".into());
};
let entry = horizon_core::position::BlockPos::containing(p.position);
let block = self.world.block(entry.x, entry.y, entry.z);
if &*self.res.facts().get(block).name != "minecraft:nether_portal" {
return Err("command harness: the player is not in a nether portal".into());
}
self.player_through_nether_portal(entry)
}
/// Load terrain until the player stands in lit chunks.
fn harness_settle(&mut self, deadline: Instant) -> Result<()> {
loop {
@@ -51,6 +65,10 @@ impl Game<'_> {
(p.position.z.floor() as i32) >> 4,
);
if (-1..=1).all(|dz| (-1..=1).all(|dx| self.streaming.is_lit(cx + dx, cz + dz))) {
// The oracle's settle also waits for the entities saved
// in those chunks (areEntitiesActuallyLoadedAndTicking):
// after a dimension change they come back from the save.
self.spawn_loaded_entities();
return Ok(());
}
}
@@ -130,6 +148,7 @@ impl Game<'_> {
}
}
"settle" => self.harness_settle(deadline)?,
"portal" => self.harness_portal()?,
other => return Err(format!("command harness: unknown op {other}").into()),
}
}
+241 -103
View File
@@ -9,6 +9,7 @@ pub(super) mod extra;
mod items;
mod misc;
mod place;
mod players;
mod raid;
mod terrain_cmds;
mod text_commands;
@@ -33,7 +34,11 @@ pub(super) type R<T> = Result<T, CommandError>;
/// An entity a selector found.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub(super) enum Target {
/// The player in place: the host's, or the guest whose turn it is.
Player,
/// Another player of a hosted world or server: a guest by connection
/// (game/commands/players.rs).
Guest(u32),
Mob(u32),
Item(u32),
Orb(usize),
@@ -232,9 +237,16 @@ impl Game<'_> {
}
match &self.player {
Some(p) => [p.position.x, p.position.y, p.position.z],
None => self.spawn.map_or([0.0, 64.0, 0.0], |s| [s.x, s.y, s.z]),
None => self.server_position(),
}
}
/// MinecraftServer.createCommandSourceStack's position: the corner of
/// the respawn block (`Vec3.atLowerCornerOf`).
pub(super) fn server_position(&self) -> [f64; 3] {
self.spawn.map_or([0.0, 64.0, 0.0], |s| {
[s.x.floor(), s.y.floor(), s.z.floor()]
})
}
fn source_rotation(&self) -> [f32; 2] {
self.command_source
.map_or([self.yaw, self.pitch], |s| s.rot)
@@ -263,8 +275,8 @@ impl Game<'_> {
.ok_or_else(|| err("argument.pos.missing.int", &[]))?;
// BlockPos.containing(getPosition)
let p = self.resolve_coords(&c).map(|v| v.floor() as i32);
let elsewhere = self.command_source.is_some_and(|s| s.elsewhere);
if elsewhere || !self.world.chunks.contains_key(&(p[0] >> 4, p[2] >> 4)) {
let dimension = self.command_source.map_or(self.dim, |s| s.dimension);
if dimension != self.dim || !self.world.chunks.contains_key(&(p[0] >> 4, p[2] >> 4)) {
return Err(err("argument.pos.unloaded", &[]));
}
if p[1] < horizon_client::chunk::MIN_Y
@@ -288,6 +300,7 @@ impl Game<'_> {
.player
.as_ref()
.map(|p| [p.position.x, p.position.y, p.position.z]),
Target::Guest(conn) => self.command_guest(conn).map(|g| g.position),
Target::Mob(id) => self
.mobs
.iter()
@@ -347,7 +360,7 @@ impl Game<'_> {
}
pub(super) fn target_type(&self, t: Target) -> String {
match t {
Target::Player => "minecraft:player".into(),
Target::Player | Target::Guest(_) => "minecraft:player".into(),
Target::Mob(id) => self
.mobs
.iter()
@@ -394,12 +407,19 @@ impl Game<'_> {
match t {
Target::Player => {
let name = self.acting_player_name();
if let Some(uuid) = self.lan_acting_uuid {
return self.player_text(name, uuid);
}
match self.score.board.players_team(name) {
// PlayerTeam.formatNameForTeam.
Some(team) => team.formatted_name(Text::literal(name)),
None => Text::literal(name),
}
}
Target::Guest(conn) => match self.command_guest(conn) {
Some(g) => self.player_text(&g.name, g.uuid),
None => Text::empty(),
},
Target::Item(id) => {
let item = self
.dropped
@@ -446,11 +466,10 @@ impl Game<'_> {
/// EntitySelector.findEntities.
pub(super) fn select(&mut self, s: &Selector) -> Vec<Target> {
if let Some(name) = &s.player_name {
return if name.eq_ignore_ascii_case(PLAYER_NAME) && self.player.is_some() {
vec![Target::Player]
} else {
Vec::new()
};
return self.player_named(name).into_iter().collect();
}
if let Some(uuid) = s.uuid {
return self.target_by_uuid(uuid).into_iter().collect();
}
let origin = {
let p = self.source_position();
@@ -464,10 +483,15 @@ impl Game<'_> {
match (s.kind, self.command_source) {
// @s: the executing entity (none for a server source).
('s', Some(source)) => candidates.extend(source.entity),
_ if self.player.is_some() => candidates.push(Target::Player),
('s', None) => candidates.extend(self.source_entity()),
// A guest in place is among the players, in join order.
_ if self.player.is_some() && self.lan_acting.is_none() => {
candidates.push(Target::Player);
}
_ => {}
}
if s.kind != 's' {
candidates.extend(self.player_candidates(s));
candidates.extend(
self.mobs
.iter()
@@ -511,7 +535,7 @@ impl Game<'_> {
}
}
if !s.include_entities
&& t != Target::Player
&& !t.is_player()
&& s.types.iter().all(|(w, n)| *n || w != &ty)
&& s.kind != 'e'
&& s.kind != 'n'
@@ -527,16 +551,20 @@ impl Game<'_> {
if !passing.contains(&t) {
return None;
}
let player = match t {
Target::Player => Some((level, if creative { "creative" } else { "survival" })),
Target::Guest(conn) => self.guest_level_and_mode(conn),
_ => None,
};
if let Some((lo, hi)) = s.level
&& (t != Target::Player
|| lo.is_some_and(|l| level < l)
|| hi.is_some_and(|h| level > h))
&& player.is_none_or(|(level, _)| {
lo.is_some_and(|l| level < l) || hi.is_some_and(|h| level > h)
})
{
return None;
}
for (mode, neg) in &s.gamemodes {
let current = if creative { "creative" } else { "survival" };
if t != Target::Player || (current == mode) == *neg {
if player.is_none_or(|(_, current)| (current == mode) == *neg) {
return None;
}
}
@@ -595,12 +623,12 @@ impl Game<'_> {
/// EntityArgument.getEntities / getPlayers / getEntity / getPlayer.
pub(super) fn entities(&mut self, ctx: &Context, name: &str, players: bool) -> R<Vec<Target>> {
let Some(Arg::Entity(s)) = ctx.get(name).cloned() else {
return Ok(vec![Target::Player]);
return Ok(vec![self.implied_player()]);
};
let found: Vec<Target> = self
.select(&s)
.into_iter()
.filter(|t| !players || *t == Target::Player)
.filter(|t| !players || t.is_player())
.collect();
if found.is_empty() {
return Err(err(
@@ -806,63 +834,63 @@ impl Game<'_> {
let targets = if ctx.get("target").is_some() {
self.entities(ctx, "target", true)?
} else {
vec![Target::Player]
vec![self.implied_player()]
};
let mut count = 0;
for t in targets {
if t != Target::Player || !self.set_game_mode(mode) {
let mode_name = Text::translate(&format!("gameMode.{}", mode.name()), &[]);
// GameModeCommand.logGamemodeChange: the source's own entity.
let own = self.source_entity() == Some(t);
let told = !own && self.ui.rules.bool("send_command_feedback");
let changed = self.for_player(t, |g| {
if !g.set_game_mode(mode) {
return false;
}
if told {
g.system_message(Text::translate(
"gameMode.changed",
std::slice::from_ref(&mode_name),
));
}
true
});
if changed != Some(true) {
continue;
}
count += 1;
let mode_name = Text::translate(&format!("gameMode.{}", mode.name()), &[]);
// GameModeCommand.logGamemodeChange: the source's own entity.
let own = match self.command_source {
None => true,
Some(s) => s.entity == Some(t),
};
if own {
self.feedback(Text::translate(
"commands.gamemode.success.self",
&[mode_name],
));
} else {
if self.ui.rules.bool("send_command_feedback") {
self.system_message(Text::translate(
"gameMode.changed",
std::slice::from_ref(&mode_name),
));
}
self.feedback(Text::translate(
"commands.gamemode.success.other",
&[Text::literal(self.acting_player_name()), mode_name],
&[self.target_name(t), mode_name],
));
}
}
Ok(count)
}
/// ItemStack.getDisplayName: "[Name]" in the rarity colour.
/// ItemStack.getDisplayName of one `item` with no components.
pub(super) fn item_display_name(&self, item: &str) -> Text {
let rarity = self.item_rarity(item);
let color = match rarity.as_str() {
"uncommon" => text::YELLOW,
"rare" => text::AQUA,
"epic" => text::LIGHT_PURPLE,
_ => text::WHITE,
};
Text::literal("[")
.append(Text::literal(self.pack.names.item(item)))
.append("]")
.with_color(color)
self.stack_display_name(&ItemStack {
item: item.into(),
count: 1,
damage: 0,
extra: None,
})
}
/// `ItemStack.getDisplayName`: the hover name (custom name in italics,
/// a written book's title, a potion's effect name...) in brackets, in the
/// rarity colour unless the stack is empty.
/// a written book's title, a potion's effect name, else the item's
/// translated name) in brackets, in the rarity colour and showing the
/// stack on hover unless it is empty.
pub(super) fn stack_display_name(&self, s: &ItemStack) -> Text {
let item = &*s.item;
let empty = item == "minecraft:air" || s.count == 0;
let custom = s.custom_name();
let hover = if let Some(c) = custom {
Text::literal(c).italic()
Text::literal(c)
} else if let Some(title) = s
.data()
.and_then(|d| d.written.as_ref())
@@ -883,9 +911,22 @@ impl Game<'_> {
&[],
)
} else {
Text::literal(self.pack.names.item(item))
// Item.getDescriptionId: a block item's is the block's.
let (namespace, path) = item.split_once(':').unwrap_or(("minecraft", item));
let key = format!("item.{namespace}.{path}");
let key = if self.pack.names.get(&key).is_some() {
key
} else {
format!("block.{namespace}.{path}")
};
Text::translate(&key, &[])
};
let wrapped = Text::translate("chat.square_brackets", &[hover]);
// Component.empty().append(getHoverName()), italic for a custom name.
let mut name = Text::empty().append(hover);
if custom.is_some() {
name = name.italic();
}
let wrapped = Text::translate("chat.square_brackets", &[name]);
if empty {
return wrapped;
}
@@ -903,7 +944,14 @@ impl Game<'_> {
"epic" => text::LIGHT_PURPLE,
_ => text::WHITE,
};
wrapped.with_color(color)
// HoverEvent.ShowItem: the count only when it is not one.
let mut shown = serde_json::json!({"action": "show_item", "id": item});
if s.count != 1 {
shown["count"] = s.count.into();
}
wrapped
.with_color(color)
.with_component_fields(vec![("hover_event".into(), shown)])
}
pub(super) fn item_rarity(&self, item: &str) -> String {
static RARITY: std::sync::OnceLock<std::collections::HashMap<String, String>> =
@@ -941,7 +989,7 @@ impl Game<'_> {
};
let count = Self::int(ctx, "count").unwrap_or(1);
let targets = self.entities(ctx, "targets", true)?;
let max_stack = self.res.items.get(&id).map_or(64, |i| i.max_stack) as i32;
let max_stack = self.res.items().get(&id).map_or(64, |i| i.max_stack) as i32;
if count > max_stack * 100 {
return Err(CommandError::new(Text::translate(
"commands.give.failed.toomanyitems",
@@ -953,33 +1001,38 @@ impl Game<'_> {
}
// An air stack is empty: nothing is given (but the message still is).
let empty = id == "minecraft:air";
for _ in targets.iter().filter(|_| !empty) {
let mut remaining = count;
while remaining > 0 {
let size = remaining.min(max_stack);
remaining -= size;
let left = self.give(ItemStack {
item: id.as_str().into(),
count: size as u32,
damage,
extra: extra.clone(),
});
if let Some(rest) = left {
// Inventory full: drop the rest at the player's feet without pickup delay.
let p = self.source_position();
self.spawn_item(rest, [p[0], p[1] + 1.32, p[2]], [0.0, 0.0, 0.0], 0);
} else {
let r = &mut self.world.random;
let pitch = ((r.next_float() - r.next_float()) * 0.7 + 1.0) * 2.0;
let p = self.source_position();
self.audio
.play("minecraft:entity.item.pickup", Some(p), 0.2, pitch);
for &t in targets.iter().filter(|_| !empty) {
self.for_player(t, |g| {
let mut remaining = count;
while remaining > 0 {
let size = remaining.min(max_stack);
remaining -= size;
let left = g.give(ItemStack {
item: id.as_str().into(),
count: size as u32,
damage,
extra: extra.clone(),
});
// At the player who gets them.
let p = g
.target_position(Target::Player)
.unwrap_or(g.source_position());
if let Some(rest) = left {
// Inventory full: drop the rest at the player's feet without pickup delay.
g.spawn_item(rest, [p[0], p[1] + 1.32, p[2]], [0.0, 0.0, 0.0], 0);
} else {
let r = &mut g.world.random;
let pitch = ((r.next_float() - r.next_float()) * 0.7 + 1.0) * 2.0;
g.audio
.play("minecraft:entity.item.pickup", Some(p), 0.2, pitch);
}
}
}
});
}
// The prototype stack: one item.
let name = self.stack_display_name(&ItemStack {
item: id.as_str().into(),
count: count.max(1) as u32,
count: 1,
damage,
extra: extra.clone(),
});
@@ -989,7 +1042,7 @@ impl Game<'_> {
&[
Text::literal(count.to_string()),
name,
Text::literal(self.acting_player_name()),
self.target_name(targets[0]),
],
)
} else {
@@ -1008,6 +1061,9 @@ impl Game<'_> {
fn teleport_to(&mut self, t: Target, pos: [f64; 3], rotation: Option<[f32; 2]>) {
let v = Vec3::new(pos[0], pos[1], pos[2]);
match t {
Target::Guest(_) => {
self.for_player(t, |g| g.teleport_to(Target::Player, pos, rotation));
}
Target::Player => {
if let Some(p) = self.player.as_mut() {
p.position = v;
@@ -1088,17 +1144,96 @@ impl Game<'_> {
Target::Frame(_) | Target::Painting(_) => {}
}
}
/// Teleport the local player into the command source's dimension. Unlike
/// portal travel, `/tp` keeps the coordinates given by the command.
fn teleport_player_to_dimension(
&mut self,
dimension: Dim,
pos: [f64; 3],
rotation: Option<[f32; 2]>,
) -> R<()> {
let Some(mut player) = self.player.take() else {
return Ok(());
};
let from = self.dim;
if self.switch_level(dimension, player.position).is_err() {
self.player = Some(player);
return Err(err("command.failed", &[]));
}
self.trigger_dimension(from, dimension);
let target = Vec3::new(pos[0], pos[1], pos[2]);
player.position = target;
player.velocity = Vec3::ZERO;
player.fall_distance = 0.0;
player.ground.on_ground = false;
if let Some([yaw, pitch]) = rotation {
let pitch = pitch.clamp(-90.0, 90.0);
self.yaw = yaw;
self.pitch = pitch;
player.yaw = yaw;
player.head_yaw = yaw;
player.pitch = pitch;
}
self.travelling = Some((player, target));
self.portals.travel = None;
self.end_travel = false;
self.end_portal_travel = false;
Ok(())
}
/// A server's player teleported into another level than theirs
/// (ServerPlayer.teleport): queued to move after the command. False
/// when `t` is not a player in another level.
fn teleport_across(
&mut self,
t: Target,
level: super::Dim,
pos: [f64; 3],
rotation: Option<[f32; 2]>,
) -> bool {
let (conn, at) = match t {
Target::Player => (self.lan_acting, self.dim),
Target::Guest(conn) => (
Some(conn),
self.command_guest(conn)
.map_or(self.dim, |g| super::Dim::from_id(&g.dimension)),
),
_ => (None, self.dim),
};
let Some(conn) = conn.filter(|_| at != level && self.options.dedicated.is_some()) else {
return false;
};
self.level_teleports
.push(super::server_travel::LevelTeleport {
conn,
dim: level,
at: pos,
rotation,
});
true
}
fn cmd_teleport(&mut self, id: &str, ctx: &Context) -> R<i32> {
let targets = if id.starts_with("teleport.targets") {
self.entities(ctx, "targets", false)?
} else {
vec![Target::Player]
vec![self.implied_player()]
};
if id.ends_with("destination") {
let dest = self.entities(ctx, "destination", false)?[0];
let pos = self.target_position(dest).unwrap_or(self.source_position());
// Into the destination's level.
let level = match dest {
Target::Guest(conn) => self
.command_guest(conn)
.map_or(self.dim, |g| super::Dim::from_id(&g.dimension)),
_ => self.dim,
};
// TeleportCommand.teleportToEntity: the destination's rotation too.
let rotation = Some(self.target_rotation(dest));
for &t in &targets {
self.teleport_to(t, pos, None);
if !self.teleport_across(t, level, pos, rotation) {
self.teleport_to(t, pos, rotation);
}
}
let message = if targets.len() == 1 {
Text::translate(
@@ -1156,24 +1291,24 @@ impl Game<'_> {
(-(dy.atan2(horizontal).to_degrees())) as f32,
]);
}
// `execute in` another dimension: a server's player moves to that
// level (ServerPlayer.teleport into another level), after the command.
let level = self
.command_source
.and_then(|s| s.level)
.filter(|d| *d != self.dim && self.options.dedicated.is_some());
// A server's player in another level than the source's (`execute
// in`, the console's Overworld) moves there (ServerPlayer.teleport
// into another level), after the command.
let source_level = match self.command_source.and_then(|s| s.level) {
Some(level) => level,
None if self.source_entity().is_none() => super::Dim::Overworld,
None => self.dim,
};
for &t in &targets {
if let (Some(dim), Target::Player, Some(conn)) = (level, t, self.lan_acting) {
self.level_teleports
.push(super::server_travel::LevelTeleport {
conn,
dim,
at: pos,
rotation,
});
if self.teleport_across(t, source_level, pos, rotation) {
continue;
}
self.teleport_to(t, pos, rotation);
let dimension = self.command_source.map_or(self.dim, |s| s.dimension);
if t == Target::Player && dimension != self.dim {
self.teleport_player_to_dimension(dimension, pos, rotation)?;
} else {
self.teleport_to(t, pos, rotation);
}
}
let [x, y, z] = pos.map(|v| Text::literal(format_double(v)));
let message = if targets.len() == 1 {
@@ -1373,6 +1508,9 @@ impl Game<'_> {
}
fn kill_target(&mut self, t: Target) {
match t {
Target::Guest(_) => {
self.for_player(t, |g| g.kill_target(Target::Player));
}
Target::Player => {
if let Some(p) = self.player.as_mut() {
let _ = p.set_health(0.0, false);
@@ -1415,7 +1553,7 @@ impl Game<'_> {
let targets = if ctx.get("targets").is_some() {
self.entities(ctx, "targets", false)?
} else {
vec![Target::Player]
vec![self.implied_player()]
};
let names: Vec<Text> = targets.iter().map(|&t| self.target_name(t)).collect();
// Remove indexed entities from the back so earlier indices stay valid.
@@ -1468,7 +1606,7 @@ impl Game<'_> {
if self.ui.difficulty == 0
&& self
.res
.mob_types
.mob_types()
.get(&format!("minecraft:{short}"))
.is_some_and(|t| t.category == "monster")
{
@@ -1485,7 +1623,7 @@ impl Game<'_> {
let name;
if let Some(t) = self
.res
.mob_types
.mob_types()
.get(&format!("minecraft:{short}"))
.cloned()
{
@@ -1561,10 +1699,10 @@ impl Game<'_> {
let name_ok = if b.tag {
let tag = b.id.trim_start_matches("minecraft:");
self.res
.items
.items()
.block_tags
.get(tag)
.or_else(|| self.res.items.block_tags.get(&b.id))
.or_else(|| self.res.items().block_tags.get(&b.id))
.is_some_and(|set| {
set.contains(&s.name) || set.contains(s.name.trim_start_matches("minecraft:"))
})
@@ -1589,8 +1727,8 @@ impl Game<'_> {
}
// A different block replaces the block entity (Level.setBlock).
let (old, new) = (
self.res.facts.get(previous).name.clone(),
self.res.facts.get(state).name.clone(),
self.res.facts().get(previous).name.clone(),
self.res.facts().get(state).name.clone(),
);
// The command clears the old block entity without its side effects
// (UPDATE_SKIP_BLOCK_ENTITY_SIDEEFFECTS); the new block gets a fresh one.
@@ -2184,10 +2322,10 @@ impl Game<'_> {
let tag = predicate.id.trim_start_matches("minecraft:");
return self
.res
.items
.items()
.item_tags
.get(tag)
.or_else(|| self.res.items.item_tags.get(&predicate.id))
.or_else(|| self.res.items().item_tags.get(&predicate.id))
.is_some_and(|s| {
s.contains(item) || s.contains(item.trim_start_matches("minecraft:"))
});
@@ -2633,7 +2771,7 @@ impl Game<'_> {
let focused = self.screen == Screen::Chat;
self.ui
.chat
.add(&self.atlas, line, None, self.ticks, focused);
.add(&self.gui.atlas, line, None, self.ticks, focused);
Ok(1)
}
/// MessageArgument: `@p`-style selectors in a message become names.
@@ -502,7 +502,7 @@ impl Game<'_> {
Some(Value::String(b)) => match b.strip_prefix('#') {
Some(tag) => self
.res
.items
.items()
.block_tags
.get(tag.trim_start_matches("minecraft:"))
.is_some_and(|set| {
@@ -35,6 +35,11 @@ impl Game<'_> {
pub(in crate::game) fn entity_nbt(&mut self, t: Target) -> Option<Tag> {
let player_uuid = self.level.player_uuid;
Some(match t {
Target::Guest(_) => {
return self
.for_player(t, |g| g.entity_nbt(Target::Player))
.flatten();
}
Target::Player => {
self.player.as_ref()?;
self.sync_level();
@@ -142,7 +147,7 @@ impl Game<'_> {
set_key(&mut tag, "id", Tag::String(k.as_str().into()));
}
let new =
entity_nbt::mob_from_nbt(&tag, &self.res.mob_types, id).ok_or_else(stale)?;
entity_nbt::mob_from_nbt(&tag, self.res.mob_types(), id).ok_or_else(stale)?;
if let Some(slot) = self.mobs.iter_mut().find(|m| m.id == id) {
// Runtime-only state (AI, animation) carries over.
let old = std::mem::replace(slot, new);
@@ -661,13 +666,20 @@ impl Game<'_> {
/// Spawn an entity from its compound (`EntityType.loadEntityRecursive`);
/// returns what was created.
pub(super) fn spawn_entity_from_nbt(&mut self, tag: Tag) -> Option<Target> {
let before = self.next_entity;
let key = {
let p = entity_nbt::position(&tag)?;
((p.x.floor() as i32) >> 4, (p.z.floor() as i32) >> 4)
};
// Only this stack spawns now: the entities of chunks that finished
// loading wait for the level's entity tick, as in vanilla
// (PersistentEntitySectionManager.processPendingLoads), and must not
// take the ids counted as this stack's.
let mut waiting = std::mem::take(&mut self.world.loaded_entities);
let before = self.next_entity;
self.world.loaded_entities.push((key, vec![tag]));
self.spawn_loaded_entities();
waiting.append(&mut self.world.loaded_entities);
self.world.loaded_entities = waiting;
if self.next_entity == before {
return None;
}
@@ -59,7 +59,7 @@ impl Game<'_> {
if ctx.get("targets").is_some() {
self.entities(ctx, "targets", false)
} else {
Ok(vec![Target::Player])
Ok(vec![self.implied_player()])
}
}
/// `EffectCommands.giveEffect`.
@@ -83,10 +83,11 @@ impl Game<'_> {
let mut tracker = Tracker::default();
for t in self.living_targets(ctx)? {
let changed = match t {
Target::Player => {
Target::Player | Target::Guest(_) => {
let mut instance = EffectInstance::new(effect.id, duration, amplifier);
instance.visible = particles;
self.add_player_effect(instance)
self.for_player(t, |g| g.add_player_effect(instance))
.unwrap_or(false)
}
Target::Mob(id) => match self.mobs.iter_mut().find(|m| m.id == id) {
Some(m) => {
@@ -131,18 +132,22 @@ impl Game<'_> {
let mut tracker = Tracker::default();
for t in self.living_targets(ctx)? {
let changed = match (t, effect) {
(Target::Player, None) => {
let any = !self.potions.effects.list.is_empty();
self.potions.effects.clear();
self.apply_effect_status();
any
}
(Target::Player, Some(e)) => {
let before = self.potions.effects.list.len();
self.potions.effects.list.retain(|x| x.id != e.id);
self.apply_effect_status();
self.potions.effects.list.len() != before
}
(Target::Player | Target::Guest(_), None) => self
.for_player(t, |g| {
let any = !g.potions.effects.list.is_empty();
g.potions.effects.clear();
g.apply_effect_status();
any
})
.unwrap_or(false),
(Target::Player | Target::Guest(_), Some(e)) => self
.for_player(t, |g| {
let before = g.potions.effects.list.len();
g.potions.effects.list.retain(|x| x.id != e.id);
g.apply_effect_status();
g.potions.effects.list.len() != before
})
.unwrap_or(false),
(Target::Mob(id), e) => match self.mobs.iter_mut().find(|m| m.id == id) {
Some(m) => {
let before = m.extra.effects.len();
@@ -187,7 +192,7 @@ impl Game<'_> {
return Ok(0);
};
let level = Self::int(ctx, "level").unwrap_or(1);
let enchantments = &self.res.stations.enchantments;
let enchantments = &self.res.stations().enchantments;
let Some(def) = enchantments.get(&id) else {
return Err(err(
"argument.resource.not_found",
@@ -213,8 +218,8 @@ impl Game<'_> {
}
continue;
};
let e = &self.res.stations.enchantments;
let compatible = e.can_enchant(&self.res.items, &id, &stack.item)
let e = &self.res.stations().enchantments;
let compatible = e.can_enchant(self.res.items(), &id, &stack.item)
&& stack
.crafting_enchantments()
.iter()
@@ -265,7 +270,7 @@ impl Game<'_> {
}
let (name, curse) = self
.res
.stations
.stations()
.enchantments
.full_name(&id, level.max(0) as u32);
let style = Style {
@@ -1,7 +1,7 @@
//! `/execute` (ExecuteCommand): walk the parsed redirect chain, forking and
//! filtering command sources, then run the final command once per source,
//! reporting each result to the `store` callbacks of its source.
use super::{Arg, Context, Game, R, Target, data::DataRef, err};
use super::{Arg, Context, Dim, Game, R, Target, data::DataRef, err};
use horizon_client::{
command::{CommandError, vanilla},
nbt_path::NbtPath,
@@ -23,9 +23,9 @@ pub(in crate::game) struct Source {
pub silent: bool,
/// Index of the newest `store` in `ExecState::stores`.
pub store: Option<u32>,
/// `execute in` another dimension than the one Horizon has loaded: none
/// of its chunks are loaded.
pub elsewhere: bool,
/// The level this command source uses. Horizon has only this dimension's
/// chunks loaded in the single-player client.
pub dimension: Dim,
/// The dimension `execute in` named, if any: a server teleports its
/// players there (`TeleportCommand` into the source's level).
pub level: Option<super::super::Dim>,
@@ -73,13 +73,14 @@ impl Game<'_> {
/// The source a command typed by the player starts from.
pub(in crate::game) fn player_source(&self) -> Source {
Source {
entity: Some(Target::Player),
// The server console has no entity (CommandSourceStack of the server).
entity: self.player.is_some().then_some(Target::Player),
pos: self.source_position(),
rot: self.source_rotation(),
eyes: false,
silent: false,
store: None,
elsewhere: false,
dimension: self.dim,
level: None,
block: None,
}
@@ -88,12 +89,12 @@ impl Game<'_> {
pub(in crate::game) fn server_source(&self) -> Source {
Source {
entity: None,
pos: self.spawn.map_or([0.0, 64.0, 0.0], |s| [s.x, s.y, s.z]),
pos: self.server_position(),
rot: [0.0, 0.0],
eyes: false,
silent: true,
store: None,
elsewhere: false,
dimension: self.dim,
level: None,
block: None,
}
@@ -101,6 +102,9 @@ impl Game<'_> {
pub(super) fn target_rotation(&self, t: Target) -> [f32; 2] {
match t {
Target::Player => [self.yaw, self.pitch],
Target::Guest(conn) => self
.command_guest(conn)
.map_or([0.0; 2], |g| [g.yaw, g.pitch]),
Target::Mob(id) => self
.mobs
.iter()
@@ -135,6 +139,7 @@ impl Game<'_> {
.player
.as_ref()
.map_or(1.62, |p| f64::from(p.dimensions.eye_height)),
Target::Guest(conn) => self.command_guest(conn).map_or(1.62, |g| g.eye_height()),
Target::Mob(id) => self
.mobs
.iter()
@@ -445,7 +450,7 @@ impl Game<'_> {
Some(Source {
pos: self.target_position(t)?,
rot: self.target_rotation(t),
elsewhere: false,
dimension: self.dim,
level: None,
..s
})
@@ -537,8 +542,8 @@ impl Game<'_> {
..s
}],
"in" => {
// Horizon keeps one dimension loaded: in another one, no
// chunk is loaded (as in vanilla without a player there).
// CommandSourceStack.withLevel scales the source position;
// absolute coordinates passed to /tp are unaffected.
let Some(Arg::Resource(dim)) = c.get("dimension") else {
return Ok(vec![s]);
};
@@ -548,8 +553,12 @@ impl Game<'_> {
) {
return Err(err("argument.dimension.invalid", &[dim]));
}
let dimension = Dim::from_id(dim);
let coordinate_scale = |dim| if dim == Dim::Nether { 8.0 } else { 1.0 };
let scale = coordinate_scale(s.dimension) / coordinate_scale(dimension);
vec![Source {
elsewhere: dim != self.dim.id(),
pos: [s.pos[0] * scale, s.pos[1], s.pos[2] * scale],
dimension,
level: Some(super::super::Dim::from_id(dim)),
..s
}]
@@ -633,7 +642,7 @@ impl Game<'_> {
})
.collect()
}
fn target_with_uuid(&self, uuid: [i32; 4]) -> Option<Target> {
pub(super) fn target_with_uuid(&self, uuid: [i32; 4]) -> Option<Target> {
if Some(uuid) == self.level.player_uuid {
return Some(Target::Player);
}
@@ -656,7 +665,7 @@ impl Game<'_> {
if state == self.world.air {
continue;
}
let facts = self.res.facts.get(state);
let facts = self.res.facts().get(state);
let blocks = facts.legacy_solid || facts.fluid != horizon_client::blocks::Fluid::None;
let leaves = self
.pack
@@ -792,14 +801,16 @@ impl Game<'_> {
let p = self
.coords(c, "pos")
.map(|co| co.block(self.source_position(), self.source_rotation()));
return Ok(flag(p.is_some_and(|p| {
self.world.chunks.contains_key(&(p[0] >> 4, p[2] >> 4))
})));
let dimension = self.command_source.map_or(self.dim, |s| s.dimension);
return Ok(flag(
dimension == self.dim
&& p.is_some_and(|p| self.world.chunks.contains_key(&(p[0] >> 4, p[2] >> 4))),
));
}
if c.has("dimension") {
return Ok(flag(
matches!(c.get("dimension"), Some(Arg::Resource(d)) if d == self.dim.id()),
));
let dimension = self.command_source.map_or(self.dim, |s| s.dimension);
return Ok(flag(matches!(c.get("dimension"), Some(Arg::Resource(d))
if d.as_str() == dimension.id())));
}
if c.has("block") {
let p = self.block_pos_arg(c, "pos")?;
@@ -948,7 +959,7 @@ impl Game<'_> {
let chunk = self.world.chunks.get(&(p[0] >> 4, p[2] >> 4))?;
Some(
self.res
.biomes
.biomes()
.get(chunk.biome(p[0], p[1], p[2]))
.name
.clone(),
@@ -971,7 +982,7 @@ impl Game<'_> {
.resources
.join(format!("data/{ns}/tags/worldgen/biome/{path}.json"));
let Ok(bytes) = std::fs::read(file) else {
return self.res.mob_data.biome_has(tag, biome);
return self.res.mob_data().biome_has(tag, biome);
};
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap_or_default();
v["values"].as_array().is_some_and(|a| {
@@ -586,7 +586,7 @@ impl Game<'_> {
);
let hit = traverse_blocks(eye, end, 256, |b: BlockPos| {
let state = self.world.block(b.x, b.y, b.z);
(!self.res.facts.is_air(state)).then_some([b.x, b.y, b.z])
(!self.res.facts().is_air(state)).then_some([b.x, b.y, b.z])
});
hit.ok().flatten().unwrap_or([
end.x.floor() as i32,
@@ -375,7 +375,11 @@ impl Game<'_> {
} else {
0
};
let max = self.res.items.get(&stack.item).map_or(64, |i| i.max_stack);
let max = self
.res
.items()
.get(&stack.item)
.map_or(64, |i| i.max_stack);
stack.count = (base + n).clamp(0, max as i32) as u32;
}
"minecraft:limit_count" => {
@@ -389,7 +393,11 @@ impl Game<'_> {
}
}
"minecraft:set_damage" => {
let max = self.res.items.get(&stack.item).map_or(0, |i| i.max_damage);
let max = self
.res
.items()
.get(&stack.item)
.map_or(0, |i| i.max_damage);
if max > 0 {
let f = match m["damage"].as_f64() {
Some(f) => f as f32,
@@ -587,7 +595,7 @@ impl Game<'_> {
if let Some(Tag::Int(n)) = s.data().and_then(|d| d.other("minecraft:max_stack_size")) {
return (*n).clamp(1, 99) as u32;
}
self.res.items.get(&s.item).map_or(64, |i| i.max_stack)
self.res.items().get(&s.item).map_or(64, |i| i.max_stack)
}
/// `ResourceOrIdArgument.getItemModifier`: an inline modifier (SNBT) or
/// a registered one.
@@ -53,13 +53,7 @@ impl Game<'_> {
let Ok(raw) = Compression::Gzip.decode(&bytes, 1 << 28) else {
continue;
};
let Ok((named, _)) = nbt::read_named(
&raw,
Limits {
max_bytes: 1 << 28,
..Limits::default()
},
) else {
let Ok((named, _)) = nbt::read_named(&raw, Limits::templates()) else {
continue;
};
return Some(Arc::new(StructureTemplate::from_nbt(
@@ -79,10 +73,10 @@ impl Game<'_> {
}
/// `PlaceCommand.checkLoaded`: every chunk of the inclusive range.
fn place_check_loaded(&self, min: [i32; 2], max: [i32; 2]) -> R<()> {
let elsewhere = self.command_source.is_some_and(|s| s.elsewhere);
let dimension = self.command_source.map_or(self.dim, |s| s.dimension);
for cx in min[0]..=max[0] {
for cz in min[1]..=max[1] {
if elsewhere || !self.world.chunks.contains_key(&(cx, cz)) {
if dimension != self.dim || !self.world.chunks.contains_key(&(cx, cz)) {
return Err(err("argument.pos.unloaded", &[]));
}
}
@@ -0,0 +1,210 @@
//! Commands acting on the other players of a hosted world or a server
//! (EntitySelector.findPlayers and EntityArgument's player targets). The
//! player in place (the host's, or the guest whose turn it is) is
//! `Target::Player`; every other guest is `Target::Guest`, found by name,
//! UUID or selector, and what a command does to them runs with their state
//! swapped in (`for_player`), as their own turn, what it tells them going to
//! their chat.
use super::{Game, Target};
use horizon_client::{command::args::Selector, lan::guest::Guest, text::Text};
use horizon_protocol::packets::play::{self, Clientbound as C};
impl Target {
/// A player, in place or not (`instanceof ServerPlayer`).
pub(in crate::game) fn is_player(self) -> bool {
matches!(self, Target::Player | Target::Guest(_))
}
}
/// GameType.getName for a guest's game mode id.
fn mode_name(id: i32) -> &'static str {
match id {
1 => "creative",
2 => "adventure",
3 => "spectator",
_ => "survival",
}
}
impl Game<'_> {
/// The guest `conn`, while the hub is in `self.lan`.
pub(in crate::game) fn command_guest(&self, conn: u32) -> Option<&Guest> {
self.lan.as_ref()?.hub.guest(conn)
}
/// `PlayerList.getPlayers` but the player in place: the guests who
/// joined the world.
fn command_players(&self) -> impl Iterator<Item = &Guest> {
let acting = self.lan_acting;
self.lan
.iter()
.flat_map(|h| h.hub.guests.iter())
.filter(move |g| g.placed && Some(g.conn) != acting)
}
/// The entity the command runs as (`CommandSourceStack.getEntity`): a
/// command typed by the player in place runs as them, the server
/// console's as nobody.
pub(in crate::game) fn source_entity(&self) -> Option<Target> {
match self.command_source {
Some(s) => s.entity,
None => self.player.is_some().then_some(Target::Player),
}
}
/// `CommandSourceStack.getPlayerOrException` for the commands whose
/// player argument is optional: the source's player (the player in
/// place when it has none, as before).
pub(in crate::game) fn implied_player(&self) -> Target {
self.source_entity()
.filter(|t| t.is_player())
.unwrap_or(Target::Player)
}
/// `PlayerList.getPlayerByName`: names are not case sensitive.
pub(super) fn player_named(&self, name: &str) -> Option<Target> {
if self.player.is_some() && name.eq_ignore_ascii_case(self.acting_player_name()) {
return Some(Target::Player);
}
self.command_players()
.find(|g| g.name.eq_ignore_ascii_case(name))
.map(|g| Target::Guest(g.conn))
}
/// `EntitySelector.findEntities` with a UUID: the player with it, else
/// the entity.
pub(super) fn target_by_uuid(&self, uuid: u128) -> Option<Target> {
let own = self.lan_acting_uuid.or_else(|| {
self.level.player_uuid.map(|[a, b, c, d]| {
(u128::from(a as u32) << 96)
| (u128::from(b as u32) << 64)
| (u128::from(c as u32) << 32)
| u128::from(d as u32)
})
});
if self.player.is_some() && own == Some(uuid) {
return Some(Target::Player);
}
if let Some(g) = self.command_players().find(|g| g.uuid == uuid) {
return Some(Target::Guest(g.conn));
}
let words = [96, 64, 32, 0].map(|shift| (uuid >> shift) as u32 as i32);
self.target_with_uuid(words)
}
/// The guests a selector looks at, in join order (`PlayerList.getPlayers`),
/// the one in place as `Target::Player`: all of them, or those in the
/// source's level when it limits the search to a place
/// (`isWorldLimited`); `@e` and `@n` skip the dead (`Entity::isAlive`).
pub(super) fn player_candidates(&self, s: &Selector) -> Vec<Target> {
let limited = s.distance.is_some()
|| s.pos.iter().any(Option::is_some)
|| s.delta.iter().any(Option::is_some);
let alive = matches!(s.kind, 'e' | 'n');
let here = self.dim.id();
let in_place = self.lan_acting.filter(|_| self.player.is_some());
self.lan
.iter()
.flat_map(|h| h.hub.guests.iter())
.filter(|g| g.placed)
.filter(|g| !limited || g.dimension == here || Some(g.conn) == in_place)
.filter(|g| !alive || (!g.dead && g.health > 0.0))
.map(|g| {
if Some(g.conn) == in_place {
Target::Player
} else {
Target::Guest(g.conn)
}
})
.collect()
}
/// A guest's experience level and game mode, for `level=` and `gamemode=`.
pub(super) fn guest_level_and_mode(&self, conn: u32) -> Option<(i32, &'static str)> {
self.command_guest(conn)
.map(|g| (g.xp_level, mode_name(g.game_mode)))
}
/// `Player.getDisplayName`: the name as its team shows it, suggesting a
/// `/tell`, showing the player on hover, inserting the name.
pub(in crate::game) fn player_text(&self, name: &str, uuid: u128) -> Text {
let shown = match self.score.board.players_team(name) {
Some(team) => team.formatted_name(Text::literal(name)),
None => Text::literal(name),
};
shown.with_component_fields(vec![
(
"click_event".into(),
serde_json::json!({"action": "suggest_command", "command": format!("/tell {name} ")}),
),
(
"hover_event".into(),
serde_json::json!({"action": "show_entity", "id": "minecraft:player",
"uuid": horizon_protocol::crypto::uuid_string(uuid), "name": name}),
),
("insertion".into(), name.into()),
])
}
/// Run `f` for the player `t` (None for anything else): in place, or
/// with the guest's state swapped in, in their level, as their own turn.
/// What `f` tells the player (`system_message`) goes to their chat; the
/// command's own feedback is the caller's to send.
pub(in crate::game) fn for_player<T>(
&mut self,
t: Target,
f: impl FnOnce(&mut Self) -> T,
) -> Option<T> {
let conn = match t {
Target::Player => return Some(f(self)),
Target::Guest(conn) if self.lan_acting == Some(conn) => return Some(f(self)),
Target::Guest(conn) => conn,
_ => return None,
};
let mut host = self.lan.take()?;
let back = self.dim;
let theirs = host
.hub
.guest(conn)
.map(|g| super::super::Dim::from_id(&g.dimension));
if let Some(dim) = theirs.filter(|d| *d != back)
&& let Err(e) = self.enter_level(Some(&mut host), dim)
{
log::error!("could not open {}: {e}", dim.id());
}
let Some(swap) = self.enter_guest(&mut host, conn) else {
if self.dim != back
&& let Err(e) = self.enter_level(Some(&mut host), back)
{
log::error!("could not reopen {}: {e}", back.id());
}
self.lan = Some(host);
return None;
};
self.lan = Some(host);
let source = self.chat_capture.replace(Vec::new());
let out = f(self);
let told = std::mem::replace(&mut self.chat_capture, source).unwrap_or_default();
let mut host = self
.lan
.take()
.expect("the hub is back after a player's turn");
self.leave_guest(&mut host, swap);
for line in told {
host.hub.send_to(
conn,
&C::SystemChat(play::SystemChat {
content: horizon_client::lan::data::component_nbt(&line.component()),
overlay: false,
}),
);
}
if self.dim != back
&& let Err(e) = self.enter_level(Some(&mut host), back)
{
log::error!("could not reopen {}: {e}", back.id());
}
self.lan = Some(host);
Some(out)
}
}
@@ -174,7 +174,7 @@ impl Game<'_> {
if volume > i64::from(limit) {
return Err(err("commands.fillbiome.toobig", &[&limit, &volume]));
}
let Some(target) = self.res.biomes.list.iter().position(|b| b.name == biome) else {
let Some(target) = self.res.biomes().list.iter().position(|b| b.name == biome) else {
return Err(err(
"argument.resource.not_found",
&[&biome, &"minecraft:worldgen/biome"],
@@ -201,7 +201,7 @@ impl Game<'_> {
continue;
};
let current = chunk.biome(x, y, z);
let current_name = &self.res.biomes.list[usize::from(current)].name;
let current_name = &self.res.biomes().list[usize::from(current)].name;
if let Some(f) = &filter
&& !self.biome_matches(f, current_name)
{
@@ -474,11 +474,11 @@ impl Game<'_> {
let json = horizon_client::scoreboard::tag_to_json(&tag);
let drops = self
.res
.items
.items()
.inline_loot_table(&json, &mut self.world.random);
(drops, None)
} else {
if !self.res.items.has_loot_table(&table) {
if !self.res.items().has_loot_table(&table) {
return Err(err("argument.resource_or_id.failed_to_parse", &[&table]));
}
let held = if id == "loot.fish" {
@@ -486,14 +486,14 @@ impl Game<'_> {
} else {
None
};
let drops = match self.res.items.loot_sequence(&table) {
let drops = match self.res.items().loot_sequence(&table) {
Some(seq) => {
let random = self.rand_sequences.get(&seq, self.level.seed);
self.res
.items
.items()
.loot_table(&table, false, held.as_ref(), random)
}
None => self.res.items.loot_table(
None => self.res.items().loot_table(
&table,
false,
held.as_ref(),
@@ -510,7 +510,7 @@ impl Game<'_> {
};
let ty = self.target_type(t);
let table = format!("minecraft:entities/{}", ty.trim_start_matches("minecraft:"));
if t == Target::Player || !self.res.items.has_loot_table(&table) {
if t == Target::Player || !self.res.items().has_loot_table(&table) {
return Err(err(
"commands.drop.no_loot_table.entity",
&[&self.target_name(t).plain()],
@@ -521,14 +521,14 @@ impl Game<'_> {
None | Some(Some(Target::Player))
);
let held = self.slot_get(&super::items::Slot::Inv(self.selected));
let drops = match self.res.items.loot_sequence(&table) {
let drops = match self.res.items().loot_sequence(&table) {
Some(seq) => {
let random = self.rand_sequences.get(&seq, self.level.seed);
self.res
.items
.items()
.entity_drops(&ty, by_player, held.as_ref(), random)
}
None => self.res.items.entity_drops(
None => self.res.items().entity_drops(
&ty,
by_player,
held.as_ref(),
@@ -543,21 +543,21 @@ impl Game<'_> {
let state = self.world.block(p[0], p[1], p[2]);
let name = self.data_block_name(p);
let table = format!("minecraft:blocks/{}", name.trim_start_matches("minecraft:"));
if !self.res.items.has_loot_table(&table) {
if !self.res.items().has_loot_table(&table) {
return Err(err("commands.drop.no_loot_table.block", &[&name]));
}
let tool = self.tool_stack(ctx)?;
let drops = match self.res.items.loot_sequence(&table) {
let drops = match self.res.items().loot_sequence(&table) {
Some(seq) => {
let random = self.rand_sequences.get(&seq, self.level.seed);
self.res.items.block_drops(
self.res.items().block_drops(
self.pack.assets.registry,
state,
tool.as_ref(),
random,
)
}
None => self.res.items.block_drops(
None => self.res.items().block_drops(
self.pack.assets.registry,
state,
tool.as_ref(),
@@ -624,7 +624,7 @@ impl Game<'_> {
&& cur.damage == left.damage
&& cur.extra == left.extra =>
{
let max = self.res.items.get(&cur.item).map_or(64, |i| i.max_stack);
let max = self.res.items().get(&cur.item).map_or(64, |i| i.max_stack);
let take = left.count.min(max.saturating_sub(cur.count));
if take > 0 {
cur.count += take;
@@ -31,7 +31,7 @@ impl Game<'_> {
/// Every recipe id of the recipe manager (what `/recipe` resolves and suggests).
pub(super) fn learnable_recipes(&self) -> Vec<String> {
self.res.stations.recipe_index.ids().cloned().collect()
self.res.stations().recipe_index.ids().cloned().collect()
}
pub(super) fn cmd_recipe(&mut self, id: &str, ctx: &Context) -> R<i32> {
let targets = self.entities(ctx, "targets", true)?;
@@ -52,7 +52,7 @@ impl Game<'_> {
// displays (a transmute recipe has one per material count).
let mut n = 0;
// ServerPlayer.awardRecipes / resetRecipes: the displays changed.
let index = &self.res.stations.recipe_index;
let index = &self.res.stations().recipe_index;
n += if give {
let (count, unlocked) = self.level.recipe_book.add_recipes(index, &recipes);
self.recipe_unlocked(&unlocked);
@@ -1267,7 +1267,7 @@ impl Game<'_> {
fn spread_spawn_y(&self, p: [f64; 2], max_y: i32) -> i32 {
let (x, z) = (p[0].floor() as i32, p[1].floor() as i32);
let air = |y: i32| {
let name: &str = &self.res.facts.get(self.world.block(x, y, z)).name;
let name: &str = &self.res.facts().get(self.world.block(x, y, z)).name;
matches!(
name,
"minecraft:air" | "minecraft:cave_air" | "minecraft:void_air"
@@ -1292,16 +1292,16 @@ impl Game<'_> {
fn spread_safe(&self, p: [f64; 2], max_y: i32) -> bool {
let y = self.spread_spawn_y(p, max_y) - 1;
let (x, z) = (p[0].floor() as i32, p[1].floor() as i32);
let name = self.res.facts.get(self.world.block(x, y, z)).name.clone();
let name = self.res.facts().get(self.world.block(x, y, z)).name.clone();
let liquid = matches!(&*name, "minecraft:water" | "minecraft:lava");
let teleportable = self
.res
.items
.items()
.block_tags
.get("entities_can_teleport_to")
.or_else(|| {
self.res
.items
.items()
.block_tags
.get("minecraft:entities_can_teleport_to")
})
+1 -1
View File
@@ -21,7 +21,7 @@ impl Game<'_> {
}
/// The item's `compostable` layers provider.
fn compostable(&self, stack: &ItemStack) -> Option<serde_json::Value> {
self.res.items.get(&stack.item)?.compostable.clone()
self.res.items().get(&stack.item)?.compostable.clone()
}
/// `ComposterBlock.addLayer` and level event 1500: the provider is
/// evaluated in the composter's block-interaction loot context (its
+330
View File
@@ -0,0 +1,330 @@
//! Finishing a consumable (`Consumable.onConsume` and the use remainder),
//! its particles and sounds, and `TeleportRandomlyConsumeEffect` (chorus
//! fruit) for the local player. The level random stands in for the player's
//! own, as for every other player draw.
use super::{Dim, Game};
use horizon_client::{
items::{ConsumeEffect, ItemInfo, ItemStack},
mobs::Who,
particles::{ParticleOptions, ParticleType},
};
use horizon_core::{
geometry::Vec3, position::BlockPos, random::LegacyRandom, random::RandomSource,
};
use horizon_world::{
consumable::{Consumable, EmissionWorld, UseAnimation},
teleport_consume::{TeleportConsume, TeleportConsumeWorld},
};
use std::convert::Infallible;
type ItemConsumable = Consumable<String, ConsumeEffect>;
impl Game<'_> {
/// `Consumable.emitParticlesAndSounds(user.getRandom(), user, stack, count)`.
pub(super) fn emit_consume(
&mut self,
consumable: &ItemConsumable,
stack: &ItemStack,
count: i32,
) {
let Ok(()) = consumable.emit(&mut Emitter(self), (), stack.clone(), count);
}
/// `LivingEntity.completeUsingItem` for a consumable: `Consumable.onConsume`,
/// then `ItemStack.applyAfterUseComponentSideEffects`' use remainder.
pub(super) fn finish_consuming(
&mut self,
info: &ItemInfo,
consumable: &ItemConsumable,
stack: &ItemStack,
) {
self.emit_consume(consumable, stack, 16);
// ServerPlayer: the used statistic and the consume_item trigger.
self.stats.add("used", &stack.item, 1);
self.trigger_item("minecraft:consume_item", stack);
// FoodProperties.onConsume, the player's one ConsumableListener.
if let Some((nutrition, saturation)) = info.food {
let at = self.feet();
let pitch = self.world.random.triangle_float(1.0, 0.4);
self.audio.play(&consumable.sound, at, 1.0, pitch);
if let Some(p) = self.player.as_mut() {
// FoodData.eat(nutrition, saturation)
let food = &mut p.health.food;
food.food = (food.food + nutrition as i32).clamp(0, 20);
food.saturation = (food.saturation + saturation).clamp(0.0, food.food as f32);
}
// Mth.randomBetween(random, 0.9, 1.0)
let pitch = self.world.random.next_float() * (1.0f32 - 0.9f32) + 0.9;
self.audio
.play("minecraft:entity.player.burp", self.feet(), 0.5, pitch);
}
for effect in &consumable.effects {
self.apply_consume_effect(effect);
}
let event = if consumable.animation == UseAnimation::Drink {
"minecraft:drink"
} else {
"minecraft:eat"
};
self.post_entity_event(event, Who::Player);
// ItemStack.consume, then UseRemainder.convertIntoRemainder: nothing
// with infinite materials, the hand when emptied, else the inventory
// (ServerPlayer.handleExtraItemsCreatedOnUse) or a drop.
self.consume_held();
if let Some(remainder) = &info.use_remainder
&& !self.creative
{
let remainder = ItemStack::new(remainder, 1);
if self.held().is_none() {
*self.held_mut() = Some(remainder);
} else if let Some(rest) = self.give(remainder) {
self.player_drop(rest);
}
}
}
fn feet(&self) -> Option<[f64; 3]> {
self.player
.as_ref()
.map(|p| [p.position.x, p.position.y, p.position.z])
}
/// `TeleportRandomlyConsumeEffect.apply` for the local player.
pub(super) fn teleport_randomly(&mut self, teleport: &TeleportConsume) {
if self.player.is_none() {
return;
}
let dim = self.dim;
let Ok(_) = teleport.apply(&mut Teleporter(self), dim);
}
/// `LivingEntity.randomTeleport(x, y, z, true, avoid)`: down to the first
/// block entities can teleport onto, inside the border, in a loaded chunk.
fn random_teleport(&mut self, target: Vec3, avoid: &str) -> bool {
let [min_x, min_z, max_x, max_z] = self.border.bounds();
// WorldBorder.clampVec3ToBound (Mth.clamp, 1.0E-5F inside the far edge).
let clamp = |v: f64, low: f64, high: f64| if v < low { low } else { v.min(high) };
let x = clamp(target.x, min_x, max_x - f64::from(1.0e-5_f32));
let z = clamp(target.z, min_z, max_z - f64::from(1.0e-5_f32));
let mut y = target.y;
let mut pos = BlockPos::containing(Vec3::new(x, y, z));
if !self.world.loaded(pos.x, pos.z) {
return false;
}
while pos.y > self.dim.min_y() {
pos.y -= 1;
let state = self.world.block(pos.x, pos.y, pos.z);
if self.state_in_tag("minecraft:entities_can_teleport_to", state) {
return self.check_position_and_teleport(Vec3::new(x, y, z), state, avoid);
}
y -= 1.0;
}
false
}
/// `LivingEntity.checkPositionAndTeleport`, then `ServerPlayer.teleportTo`
/// (the motion and rotation kept) and entity event 46.
fn check_position_and_teleport(
&mut self,
at: Vec3,
ground: horizon_world::registry::BlockStateId,
avoid: &str,
) -> bool {
if self.state_in_tag(avoid, ground) {
return false;
}
let entities = self.happy_ghast_player_collisions();
let Some(player) = self.player.as_mut() else {
return false;
};
let bounds = player.dimensions.bounds(at);
let free = horizon_client::motion::MotionWorld {
entities: &entities,
player,
scene: &mut self.world,
assets: &self.pack.assets,
collision_binding: self.collision,
resources: self.motion,
}
.no_player_collision(bounds)
.unwrap_or(false);
// LevelReader.containsAnyLiquid and findBlocksIn: the blocks from the
// box's minimum corner to the one holding its maximum corner.
let (lo, hi) = (
BlockPos::containing(bounds.min_position()),
BlockPos::containing(bounds.max_position()),
);
let blocks = (lo.x..=hi.x)
.flat_map(|x| (lo.y..=hi.y).flat_map(move |y| (lo.z..=hi.z).map(move |z| (x, y, z))));
let states: Vec<_> = blocks.map(|(x, y, z)| self.world.block(x, y, z)).collect();
let liquid = states
.iter()
.any(|&s| self.res.facts().get(s).fluid != horizon_client::blocks::Fluid::None);
if !free || liquid || states.iter().any(|&s| self.state_in_tag(avoid, s)) {
return false;
}
if let Some(p) = self.player.as_mut() {
p.position = at;
}
// The position packet moves the old position along (absolute xyz).
self.previous_position = at;
self.portal_particles();
true
}
fn state_in_tag(&self, tag: &str, state: horizon_world::registry::BlockStateId) -> bool {
let name = &self.res.facts().get(state).name;
self.res
.items()
.block_tags
.get(tag)
.is_some_and(|s| s.contains(&**name))
}
/// `LivingEntity.handleEntityEvent(46)`: 128 portal particles from the old
/// to the new position, from the client player's random (the particle
/// engine's here).
fn portal_particles(&mut self) {
let Some(p) = self.player.as_ref() else {
return;
};
let (from, to) = (self.previous_position, p.position);
let (width, height) = (
f64::from(p.dimensions.width),
f64::from(p.dimensions.height),
);
let options = ParticleOptions::simple(ParticleType::Portal);
for i in 0..128 {
let d = f64::from(i) / 127.0;
let r = self.particles.random();
let v = [0; 3].map(|_| f64::from((r.next_float() - 0.5) * 0.2));
let x = from.x + d * (to.x - from.x) + (r.next_double() - 0.5) * width * 2.0;
let y = from.y + d * (to.y - from.y) + r.next_double() * height;
let z = from.z + d * (to.z - from.z) + (r.next_double() - 0.5) * width * 2.0;
self.particles.add(&options, [x, y, z], v);
}
}
/// `LivingEntity.stopRiding`.
pub(super) fn stop_riding(&mut self) {
let Some(id) = self.riding else {
return;
};
if let Some(i) = self.boats.iter().position(|b| b.id == id) {
self.dismount(i);
} else if let Some(i) = self.carts.iter().position(|c| c.id == id) {
self.dismount_cart(i);
} else {
self.dismount_mount();
}
}
}
/// `Consumable.emitParticlesAndSounds` against the local player.
struct Emitter<'a, 'g>(&'a mut Game<'g>);
impl EmissionWorld for Emitter<'_, '_> {
type Error = Infallible;
type Stack = ItemStack;
type Sound = String;
type Random = ();
type Source = LegacyRandom;
fn random_source(&mut self, (): ()) -> &mut LegacyRandom {
&mut self.0.world.random
}
/// `LivingEntity.spawnItemParticles`.
fn spawn_item_particles(&mut self, stack: ItemStack, count: i32) -> Result<(), Infallible> {
self.0.eat_particles(&stack, count.max(0) as u32);
Ok(())
}
fn overrides_consume_sound(&self) -> bool {
false
}
fn consume_sound(&mut self, _: ItemStack) -> Result<String, Infallible> {
unreachable!("players play the consumable's own sound")
}
/// `Entity.playSound`: at the player's position.
fn play_sound(&mut self, sound: String, volume: f32, pitch: f32) -> Result<(), Infallible> {
let at = self.0.feet();
self.0.audio.play(&sound, at, volume, pitch);
Ok(())
}
}
/// The local player as `TeleportRandomlyConsumeEffect`'s user.
struct Teleporter<'a, 'g>(&'a mut Game<'g>);
impl Teleporter<'_, '_> {
fn at(&self) -> Vec3 {
self.0.player.as_ref().map_or(Vec3::ZERO, |p| p.position)
}
}
impl TeleportConsumeWorld for Teleporter<'_, '_> {
type Error = Infallible;
type Level = Dim;
type Random = ();
type Source = LegacyRandom;
fn position_field(&self) -> Vec3 {
self.at()
}
fn get_random(&mut self) -> Result<(), Infallible> {
Ok(())
}
fn random_source(&mut self, (): ()) -> &mut LegacyRandom {
&mut self.0.world.random
}
fn min_y(&mut self, level: Dim) -> Result<i32, Infallible> {
Ok(level.min_y())
}
fn logical_height(&mut self, level: Dim) -> Result<i32, Infallible> {
Ok(level.logical_height())
}
fn is_passenger(&mut self) -> Result<bool, Infallible> {
Ok(self.0.riding.is_some())
}
fn stop_riding(&mut self) -> Result<(), Infallible> {
self.0.stop_riding();
Ok(())
}
fn position(&mut self) -> Result<Vec3, Infallible> {
Ok(self.at())
}
fn random_teleport(&mut self, target: Vec3) -> Result<bool, Infallible> {
Ok(self
.0
.random_teleport(target, "minecraft:consumable_does_not_teleport_to"))
}
fn teleport_event(&mut self, _: Dim, old: Vec3) -> Result<(), Infallible> {
let ctx = self.0.who_context(Some(Who::Player), None);
self.0
.post_game_event("minecraft:teleport", [old.x, old.y, old.z], ctx);
Ok(())
}
fn is_fox(&self) -> bool {
false
}
fn teleport_sound(&mut self, _: Dim, at: Vec3, _: bool) -> Result<(), Infallible> {
self.0.audio.play(
"minecraft:item.chorus_fruit.teleport",
Some([at.x, at.y, at.z]),
1.0,
1.0,
);
Ok(())
}
fn block_position(&mut self) -> Result<BlockPos, Infallible> {
Ok(BlockPos::containing(self.at()))
}
fn directional_particles(
&mut self,
_: Dim,
origin: BlockPos,
offset: i32,
) -> Result<(), Infallible> {
self.0
.level_event_at(2017, [origin.x, origin.y, origin.z], offset);
Ok(())
}
fn reset_fall_distance(&mut self) -> Result<(), Infallible> {
if let Some(p) = self.0.player.as_mut() {
p.fall_distance = 0.0;
}
Ok(())
}
fn reset_impulse(&mut self) -> Result<(), Infallible> {
if let Some(p) = self.0.player.as_mut() {
p.impulse.reset();
}
Ok(())
}
}
+46 -5
View File
@@ -54,12 +54,23 @@ pub struct Flight {
/// Reply with every frame time too (`fly ... PITCH raw`).
raw: bool,
reply: Sender<String>,
/// The world's smoothed tick time each frame (the F3 server line): the
/// server thread's when single player runs on one.
tick_ms: Vec<f32>,
}
impl Game<'_> {
/// Move the camera along the running flight; reply when it ends.
pub(super) fn advance_flight(&mut self) {
let Some(flight) = &self.flight else { return };
let tick_ms = self
.integrated
.as_ref()
.map_or(self.debug_charts.smoothed_tick_ms, |s| s.smoothed_tick_ms());
let Some(flight) = self.flight.as_mut() else {
return;
};
flight.tick_ms.push(tick_ms);
let flight = &*flight;
let t = (flight.started.elapsed().as_secs_f64() / flight.seconds).min(1.0);
let (a, b) = (flight.from, flight.to);
let d = [b.x - a.x, b.y - a.y, b.z - a.z];
@@ -79,6 +90,9 @@ impl Game<'_> {
&& let Some(flight) = self.flight.take()
{
let mut summary = self.frame_stats.summary();
let n = flight.tick_ms.len().max(1) as f32;
summary["tick_ms"] = (flight.tick_ms.iter().sum::<f32>() / n).into();
summary["tick_ms_max"] = flight.tick_ms.iter().copied().fold(0.0, f32::max).into();
if flight.raw {
summary["frame_ms"] = self.frame_stats.frame_millis().into();
summary["cpu_ms"] = self.frame_stats.cpu_millis().into();
@@ -183,6 +197,16 @@ impl Game<'_> {
}
Ok(Some(json!({ "ok": true, "flat": r.flat_draws() })))
}
"section-cull" => {
let r = self.renderer.as_mut().ok_or("no renderer")?;
match words.get(1).copied() {
None => {}
Some("on") => r.set_section_cull(true)?,
Some("off") => r.set_section_cull(false)?,
Some(other) => return Err(format!("unknown section cull mode {other}").into()),
}
Ok(Some(json!({ "ok": true, "cull": r.section_cull() })))
}
"sculk" => Ok(Some(self.sculk_command(&words)?)),
"status" => Ok(Some(self.control_status())),
"pad" => Ok(Some(self.pad_command(&words)?)),
@@ -345,10 +369,18 @@ impl Game<'_> {
};
let info = self
.res
.items
.items()
.get(&item)
.ok_or_else(|| format!("unknown item {item}"))?;
let count: u32 = words.get(2).map_or(Ok(1), |c| c.parse())?;
// Single player's inventory is its server thread's player's.
if let Some(server) = &self.integrated {
let command = format!("give @s {item} {count}");
server
.call(move |g| g.owner_console_command(&command))
.ok_or("the integrated server stopped")?;
return Ok(Some(json!({ "ok": true, "given": count })));
}
let max = info.max_stack;
let mut given = 0;
// Stop once the inventory is full.
@@ -379,7 +411,14 @@ impl Game<'_> {
ok()
}
"time" => {
self.world.day_time = arg(1)?.parse()?;
let time: i64 = arg(1)?.parse()?;
self.world.day_time = time;
// Single player's clock is its server thread's.
if let Some(server) = &self.integrated {
server
.call(move |g| g.world.day_time = time)
.ok_or("the integrated server stopped")?;
}
ok()
}
"summon" => {
@@ -437,7 +476,7 @@ impl Game<'_> {
match self.screen {
Screen::Chat => self.chat_type(text),
Screen::CommandBlock => self.command_block_type(text),
Screen::Options => self.ui.options.type_text(&self.atlas, text),
Screen::Options => self.ui.options.type_text(&self.gui.atlas, text),
// The port, or the game rules' search and number boxes.
Screen::WorldOptions if text == "\\b" => self.world_options_text(None),
Screen::WorldOptions => self.world_options_text(Some(text)),
@@ -527,6 +566,7 @@ impl Game<'_> {
seconds: n(7)?.max(0.1),
raw: words.get(9) == Some(&"raw"),
reply: reply.clone(),
tick_ms: Vec::new(),
});
Ok(None)
}
@@ -661,7 +701,7 @@ impl Game<'_> {
});
let target = self.pick().map(|hit| {
let state = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]);
json!({ "pos": hit.pos, "block": &*self.res.facts.get(state).name })
json!({ "pos": hit.pos, "block": &*self.res.facts().get(state).name })
});
let renderer = self.renderer.as_ref().map(|r| {
let [arena_bytes, section_vertex_bytes] = r.section_vertex_bytes();
@@ -684,6 +724,7 @@ impl Game<'_> {
"drawn_sections": r.drawn_sections,
"section_draws": r.section_draws,
"section_draw_calls": r.section_draw_calls,
"culled_sections": r.culled_sections(),
"uploaded_bytes": r.uploaded_bytes,
"resident_sections": r.resident_sections(),
"arena_bytes": arena_bytes,
@@ -106,7 +106,7 @@ impl Game<'_> {
fn golem_chest_sound(&mut self, p: [i32; 3], open: bool) {
let name = self
.res
.facts
.facts()
.get(self.world.block(p[0], p[1], p[2]))
.name
.clone();
@@ -292,7 +292,7 @@ impl Game<'_> {
pub(super) fn golem_shearable(&self, index: usize) -> bool {
self.mobs[index].saddle_item().is_some_and(|a| {
self.res
.items
.items()
.item_tags
.get("minecraft:shearable_from_copper_golem")
.is_some_and(|t| t.contains(&*a.item))
+9 -3
View File
@@ -110,7 +110,7 @@ impl Game<'_> {
let mut next_entity = self.next_entity;
let mut random = self.world.random.clone();
let spawning = self.spawning_monsters();
let creaking = self.res.mob_types.get("minecraft:creaking").cloned();
let creaking = self.res.mob_types().get("minecraft:creaking").cloned();
let player_uuid = self.level.player_uuid;
let snapshot: Vec<_> = mobs.iter().map(|m| seen(m, player_uuid)).collect();
let mut events = Vec::new();
@@ -220,6 +220,12 @@ impl Game<'_> {
/// death and a natural heart drops experience.
pub(super) fn creaking_heart_broken(&mut self, pos: [i32; 3]) {
let key = (pos[0], pos[1], pos[2]);
if !matches!(
self.world.block_entities.get(&key),
Some(BlockEntity::CreakingHeart(_))
) {
return;
}
let Some(BlockEntity::CreakingHeart(mut heart)) = self.world.block_entities.take(&key)
else {
return;
@@ -259,7 +265,7 @@ impl Game<'_> {
return Ok(());
};
let state = self.world.block(key.0, key.1, key.2);
if &*self.res.facts.get(state).name != "minecraft:creaking_heart" {
if &*self.res.facts().get(state).name != "minecraft:creaking_heart" {
// The block is gone: preRemoveSideEffects.
self.world.block_entities.forget(&key);
self.with_heart(key, &mut heart, |h, _, _, host, out| {
@@ -311,7 +317,7 @@ impl Game<'_> {
if self.creaking.hearts.is_empty() {
self.creaking.hearts = self
.res
.facts
.facts()
.states
.iter()
.map(|f| &*f.name == "minecraft:creaking_heart")
+44 -63
View File
@@ -204,8 +204,8 @@ impl Game<'_> {
let Some(chunk) = self.world.chunks.get(&(x >> 4, z >> 4)) else {
return BiomeFacts::default();
};
let b = self.res.biomes.get(chunk.biome(x, y, z));
let tags = &self.res.mob_data;
let b = self.res.biomes().get(chunk.biome(x, y, z));
let tags = self.res.mob_data();
let has = |t: &str| tags.biome_has(t, &b.name);
let climate = if has("minecraft:spawns_warm_variant_farm_animals") {
Climate::Warm
@@ -255,7 +255,7 @@ impl Game<'_> {
} else {
format!("minecraft:{kind}")
};
let t = self.res.mob_types.get(&kind).cloned()?;
let t = self.res.mob_types().get(&kind).cloned()?;
self.next_entity += 1;
let yaw = self.world.random.next_float() * 360.0;
let mut mob = Mob::new(self.next_entity, t, Vec3::new(at[0], at[1], at[2]), yaw);
@@ -368,7 +368,7 @@ impl Game<'_> {
pub(super) fn motion_top(&self, x: i32, z: i32) -> i32 {
let top = if self.dim == Dim::Nether { 127 } else { 319 };
for y in (horizon_client::chunk::MIN_Y..=top).rev() {
let f = self.res.facts.get(self.world.block(x, y, z));
let f = self.res.facts().get(self.world.block(x, y, z));
if (f.full_collision || f.fluid != Fluid::None) && !f.name.ends_with("leaves") {
return y + 1;
}
@@ -377,14 +377,16 @@ impl Game<'_> {
}
pub(super) fn mob_world_base<'s>(&'s self, others: &'s [Seen]) -> MobWorld<'s> {
let (rain, thunder) = self.world.weather.levels(1.0);
let player = self.player_view();
MobWorld {
world: &self.world,
registry: self.pack.assets.registry,
facts: &self.res.facts,
facts: self.res.facts(),
movement: &self.motion.blocks,
collision: self.collision,
data: &self.res.mob_data,
player: self.player_view(),
data: self.res.mob_data(),
nearest_player: player.as_ref().filter(|p| !p.spectator).map(|p| p.position),
player,
others,
others_grid: None,
daylight: self.dim != Dim::Nether && self.sky_darken() < 4,
@@ -393,14 +395,14 @@ impl Game<'_> {
raining: rain > 0.2,
thundering: thunder > 0.9,
nether: self.dim == Dim::Nether,
block_tags: &self.res.items.block_tags,
biomes: &self.res.biomes,
block_tags: &self.res.items().block_tags,
biomes: self.res.biomes(),
mob_griefing: self.ui.rules.bool("mob_griefing"),
end: self.dim == Dim::End,
world_seed: self.level.seed,
sea_level: if self.dim == Dim::Nether { 32 } else { 63 },
teams: self.mob_teams(),
items: Some(&self.res.items),
items: Some(self.res.items()),
difficulty: self.local_difficulty(
self.player
.as_ref()
@@ -429,25 +431,6 @@ impl Game<'_> {
};
spawning::LocalDifficulty::new(base, self.world.day_time, inhabited, moon)
}
/// `ServerChunkCache.tickSpawningChunk`: chunks whose centre is within
/// 128 blocks of the player gain inhabited time.
fn tick_inhabited(&mut self) {
let Some(p) = self.player.as_ref().map(|p| p.position) else {
return;
};
let (pcx, pcz) = (p.x.floor() as i32 >> 4, p.z.floor() as i32 >> 4);
for dx in -8..=8 {
for dz in -8..=8 {
let key = (pcx + dx, pcz + dz);
let (cx, cz) = (f64::from(key.0 * 16 + 8), f64::from(key.1 * 16 + 8));
if (cx - p.x).powi(2) + (cz - p.z).powi(2) < 128.0 * 128.0
&& self.world.chunks.contains_key(&key)
{
*self.world.inhabited.entry(key).or_insert(0) += 1;
}
}
}
}
/// Advance every mob one tick, then apply their events.
pub(super) fn tick_creatures(&mut self) -> Result<()> {
self.attack_ticks = self.attack_ticks.saturating_add(1);
@@ -464,7 +447,6 @@ impl Game<'_> {
}
self.spawn_generation_creatures(key.0, key.1);
}
self.tick_inhabited();
self.tick_leads();
self.spawn_natural();
// ServerChunkCache.tickChunks: the custom spawners tick only with spawn_mobs.
@@ -475,24 +457,11 @@ impl Game<'_> {
self.tick_raids();
self.tick_creature_entities()
}
/// `DistanceManager.inEntityTickingRange`: chunks within the simulation
/// distance (Chebyshev, in chunks) of the player or of a guest.
/// `DistanceManager.inEntityTickingRange` in an entity-ticking chunk
/// (block coordinates), from every player's tickets (`update_chunk_tickets`).
pub(super) fn entity_ticking_area(&self) -> impl Fn(i32, i32) -> bool + use<> {
let d = self.settings.simulation_distance.max(2);
let mut centres: Vec<(i32, i32)> = self.streaming.extra.iter().map(|&(c, _)| c).collect();
if let Some(p) = &self.player {
centres.push((
(p.position.x.floor() as i32) >> 4,
(p.position.z.floor() as i32) >> 4,
));
}
let everywhere = centres.is_empty();
move |x, z| {
everywhere
|| centres
.iter()
.any(|&(cx, cz)| ((x >> 4) - cx).abs().max(((z >> 4) - cz).abs()) <= d)
}
let levels = self.tickets.levels();
move |x, z| levels.entity_ticking_at(x, z)
}
/// The entity phase of `tick_creatures`: every mob's tick, deaths, and the
/// projectiles and effects that follow from them.
@@ -518,6 +487,7 @@ impl Game<'_> {
let ticking = self.entity_ticking_area();
// With guests on, each mob sees its nearest player (game/lan_mobs.rs).
let guests = self.lan_guest_views();
let players = self.level_players();
let mut bindings = match self.lan.as_mut() {
Some(host) if !guests.is_empty() => std::mem::take(&mut host.mob_players),
_ => Default::default(),
@@ -536,6 +506,13 @@ impl Game<'_> {
let mut w = self.mob_world_base(&snapshot);
w.others_grid = Some(&grid);
let m = &mut mobs[i];
w.nearest_player = super::natural_spawning::nearest_player(
&players,
m.position.x,
m.position.y,
m.position.z,
)
.map(|p| p.position);
let seen_guest = if guests.is_empty() {
None
} else {
@@ -984,7 +961,7 @@ impl Game<'_> {
if effect {
let old = self.world.block(pos[0], pos[1], pos[2]);
self.destroy_particles(pos, old);
let s = self.res.facts.get(old).sounds.break_sound.clone();
let s = self.res.facts().get(old).sounds.break_sound.clone();
self.audio.play(
&s,
Some([
@@ -1004,7 +981,7 @@ impl Game<'_> {
let old = self.world.block(pos[0], pos[1], pos[2]);
self.destroy_particles(pos, old);
if drop {
let drops = self.res.items.block_drops_in(
let drops = self.res.items().block_drops_in(
self.pack.assets.registry,
old,
None,
@@ -1158,7 +1135,7 @@ impl Game<'_> {
MobEvent::GiftLoot { table, at } => {
let drops =
self.res
.items
.items()
.loot_table(table, false, None, &mut self.world.random);
for d in drops {
self.spawn_item(d, at, [0.0, 0.2, 0.0], 10);
@@ -1421,7 +1398,7 @@ impl Game<'_> {
}
let projectile = self
.res
.stations
.stations()
.enchantments
.damage_tags
.get("minecraft:is_projectile")
@@ -1781,7 +1758,7 @@ impl Game<'_> {
horizon_client::arrows::ArrowScene {
world: &self.world,
registry: self.pack.assets.registry,
facts: &self.res.facts,
facts: self.res.facts(),
collision: self.collision,
fluids: &self.motion.fluids,
raining: rain,
@@ -2033,7 +2010,7 @@ impl Game<'_> {
let fire = [pos[0] + face[0], pos[1] + face[1], pos[2] + face[2]];
if self
.res
.facts
.facts()
.is_air(self.world.block(fire[0], fire[1], fire[2]))
&& let Some(state) =
self.pack.assets.registry.default_state("minecraft:fire")
@@ -2359,7 +2336,7 @@ impl Game<'_> {
Species::Sheep if item == "minecraft:shears" && !m.extra.sheared && !m.is_baby() => {
m.extra.sheared = true;
let color = horizon_client::mobs::render::DYE_NAMES[m.extra.color as usize & 15];
let stacks = self.res.items.loot_table(
let stacks = self.res.items().loot_table(
&format!("minecraft:shearing/sheep/{color}"),
false,
None,
@@ -2391,7 +2368,7 @@ impl Game<'_> {
Species::Wolf if m.extra.tame && is_food && m.health < m.attrs.max_health => {
let heal = self
.res
.items
.items()
.get(&item)
.and_then(|i| i.food.as_ref())
.map_or(2.0, |f| f.0 as f32);
@@ -2495,7 +2472,7 @@ impl Game<'_> {
Species::Cat if m.extra.tame && is_food && m.health < m.attrs.max_health => {
let heal = self
.res
.items
.items()
.get(&item)
.and_then(|i| i.food.as_ref())
.map_or(1.0, |f| f.0 as f32);
@@ -2662,7 +2639,7 @@ impl Game<'_> {
return;
}
if let Some(stack) = self.inventory[self.selected].as_mut()
&& let Some(info) = self.res.items.get(&stack.item)
&& let Some(info) = self.res.items().get(&stack.item)
&& info.max_damage > 0
{
stack.damage += 1;
@@ -2735,7 +2712,7 @@ impl Game<'_> {
// EntityType.canSpawn: no monsters in peaceful (FAIL ends the click).
let id = format!("minecraft:{}", kind.trim_start_matches("minecraft:"));
if self.ui.difficulty == 0
&& let Some(t) = self.res.mob_types.get(&id)
&& let Some(t) = self.res.mob_types().get(&id)
&& !horizon_client::mobs::spawn_rules::allowed_in_peaceful(t.species)
{
return Ok(true);
@@ -2799,7 +2776,7 @@ impl Game<'_> {
}
/// Mob models and projectiles for the entity pass.
pub(super) fn mob_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec<Vertex>) {
let atlas = &self.atlas;
let atlas = &self.gui.atlas;
let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]);
let scale = f64::from(self.settings.entity_distance);
for mob in &self.mobs {
@@ -2857,7 +2834,7 @@ impl Game<'_> {
camera,
&lookup,
packed,
&self.res.mob_data,
self.res.mob_data(),
&armor,
out,
);
@@ -3016,7 +2993,7 @@ impl Game<'_> {
}
/// Mob.getBaseExperienceReward
/// The damage type id of a Horizon damage kind.
fn damage_type(kind: horizon_client::mobs::DamageKind, player: bool) -> &'static str {
pub(super) fn damage_type(kind: horizon_client::mobs::DamageKind, player: bool) -> &'static str {
use horizon_client::mobs::DamageKind as K;
match kind {
K::PlayerAttack => "minecraft:player_attack",
@@ -3101,13 +3078,17 @@ impl Game<'_> {
return;
}
let mut y = pos[1];
while &*self.res.facts.get(self.world.block(pos[0], y, pos[2])).name
while &*self
.res
.facts()
.get(self.world.block(pos[0], y, pos[2]))
.name
== "minecraft:nether_portal"
{
y -= 1;
}
// isValidSpawn: a sturdy top face (portal frames emit no light).
let below = self.res.facts.get(self.world.block(pos[0], y, pos[2]));
let below = self.res.facts().get(self.world.block(pos[0], y, pos[2]));
if below.sturdy_full & (1 << 1) == 0 {
return;
}
+4 -1
View File
@@ -51,6 +51,9 @@ impl DebugHost for Host<'_, '_> {
impl Game<'_> {
fn open_screen(&self) -> OpenScreen {
if self.title.is_some() {
return OpenScreen::Other;
}
match self.screen {
Screen::GameModeSwitcher => OpenScreen::GameModeSwitcher,
Screen::Playing if self.book.is_none() && self.sign_edit.is_none() => OpenScreen::None,
@@ -437,7 +440,7 @@ impl Game<'_> {
}
}
let (left, right) = d.columns(&self.debug_chart_lines());
let atlas = &self.atlas;
let atlas = &self.gui.atlas;
let mut draws = debug_overlay::draw(&atlas.font, [&left, &right], scale, width);
let charts = self.debug_charts.draw(
&atlas.font,
@@ -63,7 +63,7 @@ impl Game<'_> {
/// pot without), or None when no pot is there.
fn pot_tag(&mut self, pos: [i32; 3]) -> Option<Tag> {
let state = self.world.block(pos[0], pos[1], pos[2]);
if &*self.res.facts.get(state).name != "minecraft:decorated_pot" {
if &*self.res.facts().get(state).name != "minecraft:decorated_pot" {
return None;
}
let mut tag = spill::saved_entity(&self.world, pos).unwrap_or_else(|| {
+9 -11
View File
@@ -11,9 +11,7 @@ use horizon_client::{
Result,
lan::{LoginGate, NetConfig, NetLog, OnlineMode, hub::HubConfig},
server::{
eula,
java_properties::now_millis,
profiles,
eula, profiles,
properties::{GAME_MODES, ServerProperties, SystemEntropy},
user_cache::UserCache,
user_lists::{
@@ -84,18 +82,16 @@ fn log_from(thread: &str, level: &str, message: &str) {
"ERROR" => ::log::Level::Error,
_ => ::log::Level::Info,
};
horizon_client::logging::write_only(file_level, message);
horizon_client::logging::write_as(thread, file_level, message);
CAPTURE.with_borrow_mut(|lines| {
if let Some(lines) = lines {
lines.push(message.to_owned());
}
});
let secs = now_millis().div_euclid(1000).rem_euclid(86_400);
// Log4j's %d{HH:mm:ss}: the local time, as in logs/latest.log.
println!(
"[{:02}:{:02}:{:02}] [{thread}/{level}]: {message}",
secs / 3600,
secs / 60 % 60,
secs % 60
"[{}] [{thread}/{level}]: {message}",
chrono::Local::now().format("%H:%M:%S")
);
}
@@ -340,7 +336,7 @@ impl Game<'_> {
);
}
let settings = if flat {
let biomes = &self.res.biomes;
let biomes = self.res.biomes();
let (settings, errors) = horizon_client::flatgen::settings_from_json(
&props.generator_settings,
|b| self.pack.assets.registry.default_state(b).is_some(),
@@ -431,6 +427,7 @@ const BROADCAST: &[&str] = &[
impl Game<'_> {
/// DedicatedServer.initServer and MinecraftServer.runServer.
pub(super) fn run_dedicated(&mut self) -> Result<()> {
self.join_world_rest()?;
let Setup {
props,
universe,
@@ -683,7 +680,7 @@ impl Game<'_> {
self.ticks = self.ticks.max(1);
}
// MinecraftServer.tickServer: while paused only the connections run.
self.tick_server(paused)?;
self.tick_server_timed(paused)?;
if idle_timeout > 0 {
self.kick_idle(idle_timeout);
}
@@ -829,6 +826,7 @@ impl Game<'_> {
self.console_command(state, line);
self.console_broadcast = None;
if let Some(mut host) = self.lan.take() {
self.run_level_teleports(&mut host);
self.send_admin_feedback(&mut host, None);
self.lan = Some(host);
}
@@ -114,9 +114,9 @@ impl Game<'_> {
}
fn fixture_reset(&mut self, seed: i64) {
self.world = World::new(self.res.facts.air, seed);
self.world = World::new(self.res.facts().air, seed);
// The oracle level is plains everywhere (bone meal's flowers, freezing).
let plains = u32::from(self.res.biomes.id("minecraft:plains"));
let plains = u32::from(self.res.biomes().id("minecraft:plains"));
for cx in -2..=2 {
for cz in -2..=2 {
let mut chunk = Chunk::empty(cx, cz);
@@ -198,7 +198,7 @@ impl Game<'_> {
let state = BlockStateId(cell[3].as_u64().unwrap_or(0) as u32);
self.world.set(p.0, p.1, p.2, state)?;
before.insert(p, state.0);
if let Some(entity) = BlockEntity::for_block(&self.res.facts.get(state).name) {
if let Some(entity) = BlockEntity::for_block(&self.res.facts().get(state).name) {
self.world.block_entities.insert(p, entity);
}
}
@@ -284,7 +284,7 @@ impl Game<'_> {
let state = self.world.block(origin.x, origin.y, origin.z);
let mut used = Vec::new();
if let Some(op) = case.get("remove") {
self.fixture_remove(origin, op)?;
used = self.fixture_remove(origin, op)?;
} else if let Some(op) = case.get("use") {
used = self.fixture_use(origin, op)?;
} else if let Some(op) = case.get("use_item") {
@@ -339,7 +339,7 @@ impl Game<'_> {
changed.dedup();
for p in changed {
let now = self.world.block(p.0, p.1, p.2).0;
if before.get(&p).copied().unwrap_or(self.res.facts.air.0) != now {
if before.get(&p).copied().unwrap_or(self.res.facts().air.0) != now {
out.push(format!("set {},{},{} {now}", p.0, p.1, p.2));
}
}
@@ -706,7 +706,7 @@ impl Game<'_> {
/// lectern's book, or the items of a block entity Horizon keeps as saved.
fn fixture_fill(&mut self, p: (i32, i32, i32), slot: usize, stack: Option<ItemStack>) {
let jukebox =
&*self.res.facts.get(self.world.block(p.0, p.1, p.2)).name == "minecraft:jukebox";
&*self.res.facts().get(self.world.block(p.0, p.1, p.2)).name == "minecraft:jukebox";
match self.world.block_entities.get_mut(&p) {
Some(BlockEntity::Jukebox(j)) => j.record = stack,
Some(BlockEntity::Lectern(l)) => l.book = stack,
@@ -735,7 +735,7 @@ impl Game<'_> {
use horizon_world::nbt::Tag;
let name = self
.res
.facts
.facts()
.get(self.world.block(p.0, p.1, p.2))
.name
.clone();
@@ -788,8 +788,9 @@ impl Game<'_> {
other => *other = Tag::List(vec![item]),
}
}
/// `Level.setBlock`, `destroyBlock` or `removeBlock` on the case's block.
fn fixture_remove(&mut self, origin: BlockPos, op: &Value) -> Result<()> {
/// `Level.setBlock`, `destroyBlock` or `removeBlock` on the case's block, or
/// a player mining it (`fixture_mine`).
fn fixture_remove(&mut self, origin: BlockPos, op: &Value) -> Result<Vec<String>> {
match op["op"].as_str().unwrap_or("") {
"set" => {
let state = BlockStateId(op["state"].as_u64().unwrap_or(0) as u32);
@@ -803,9 +804,61 @@ impl Game<'_> {
"remove" => {
self.with_level(|b, level, ticks| b.remove_block(level, ticks, origin, false));
}
"mine" => return self.fixture_mine(origin, op),
other => return Err(format!("unknown removal {other}").into()),
}
self.process_level_events()
self.process_level_events()?;
Ok(Vec::new())
}
/// A survival player three blocks south of `pos` mines it holding the
/// case's item (`break_block`, which every player's mining goes through):
/// the statistics and the held stack, as `VanillaDispenserOracle.mine`
/// prints them.
fn fixture_mine(&mut self, pos: BlockPos, op: &Value) -> Result<Vec<String>> {
let stack = parse_stack(op["item"].as_str().unwrap_or("-"))?;
self.mode = GameMode::Survival;
self.creative = false;
self.player = Some(PlayerMotion::new(
self.motion,
horizon_core::geometry::Vec3::new(
f64::from(pos.x) + 0.5,
f64::from(pos.y) + 1.0,
f64::from(pos.z) + 3.5,
),
)?);
self.yaw = 0.0;
self.pitch = 90.0;
self.keys.clear();
self.inventory[self.selected] = stack.clone();
self.offhand = None;
let state = self.world.block(pos.x, pos.y, pos.z);
let block = self.res.facts().get(state).name.clone();
let item = stack.as_ref().map(|s| s.item.clone());
let before = |game: &Self| {
let used = item.as_ref().map_or(0, |i| game.stats.get("used", i));
(used, game.stats.get("mined", &block))
};
let (used, mined) = before(self);
self.break_block([pos.x, pos.y, pos.z])?;
let (used_after, mined_after) = before(self);
let mut out = Vec::new();
if let Some(item) = &item
&& used_after != used
{
out.push(format!("stat {item} minecraft:used {}", used_after - used));
}
if mined_after != mined {
out.push(format!(
"stat {block} minecraft:mined {}",
mined_after - mined
));
}
out.push(format!(
"mine held {}",
canon_stack(self.inventory[self.selected].as_ref())
));
Ok(out)
}
/// `EntityType.create` and `snapTo` for one target: no spawn finalization.
@@ -829,7 +882,7 @@ impl Game<'_> {
}
let t = self
.res
.mob_types
.mob_types()
.get(kind)
.cloned()
.ok_or_else(|| format!("no mob type {kind}"))?;
+24 -20
View File
@@ -328,18 +328,18 @@ impl Game<'_> {
self.world.block(p.0, p.1, p.2)
}
fn dispenser_block_name(&self, p: Pos) -> std::sync::Arc<str> {
self.res.facts.get(self.block_at(p)).name.clone()
self.res.facts().get(self.block_at(p)).name.clone()
}
fn in_block_tag(&self, tag: &str, block: &str) -> bool {
self.res
.items
.items()
.block_tags
.get(tag)
.is_some_and(|s| s.contains(block))
}
fn water_at(&self, p: Pos) -> bool {
matches!(
self.res.behaviours.fluid_kind(self.block_at(p)),
self.res.behaviours().fluid_kind(self.block_at(p)),
FluidKind::Water | FluidKind::FlowingWater
)
}
@@ -520,7 +520,7 @@ impl Game<'_> {
if let Some(entity) = self.world.block_entities.get_mut(&pos) {
let max = self
.res
.items
.items()
.get(&rest.item)
.map_or(64, |i| i.max_stack)
.max(1);
@@ -555,7 +555,11 @@ impl Game<'_> {
}
/// `ItemStack.hurtAndBreak(amount)` without an entity.
fn hurt_and_break(&mut self, mut stack: ItemStack, amount: u32) -> Option<ItemStack> {
let max = self.res.items.get(&stack.item).map_or(0, |i| i.max_damage);
let max = self
.res
.items()
.get(&stack.item)
.map_or(0, |i| i.max_damage);
if max == 0 {
return Some(stack);
}
@@ -637,7 +641,7 @@ impl Game<'_> {
) -> Result<Dispensed> {
let equippable = self
.res
.items
.items()
.get(&stack.item)
.is_some_and(|i| i.equip_slot.is_some());
if equippable {
@@ -649,7 +653,7 @@ impl Game<'_> {
}
let swallowable = self
.res
.items
.items()
.item_tags
.get("minecraft:sulfur_cube_swallowable")
.is_some_and(|t| t.contains(&*stack.item));
@@ -748,7 +752,7 @@ impl Game<'_> {
} else {
format!("minecraft:{kind}")
};
let t = self.res.mob_types.get(&name)?.clone();
let t = self.res.mob_types().get(&name)?.clone();
let y_off = if try_move_down {
self.drop_offset(t.width, t.height, p)
} else {
@@ -768,7 +772,7 @@ impl Game<'_> {
/// `EquipmentDispenseItemBehavior.dispenseEquipment`: the first living
/// entity in front that `canEquipWithDispenser` gets one of the item.
fn dispense_equipment(&mut self, pos: Pos, facing: Direction, stack: &mut ItemStack) -> bool {
let Some(info) = self.res.items.get(&stack.item) else {
let Some(info) = self.res.items().get(&stack.item) else {
return false;
};
let (Some(slot), true) = (
@@ -1078,7 +1082,7 @@ impl Game<'_> {
let below = (front.0, front.1 - 1, front.2);
let y_offset = if self.water_at(front) {
1.0
} else if self.res.facts.is_air(self.block_at(front)) && self.water_at(below) {
} else if self.res.facts().is_air(self.block_at(front)) && self.water_at(below) {
0.0
} else {
return (self.dispense_default(pos, facing, stack), CLICK);
@@ -1116,7 +1120,7 @@ impl Game<'_> {
let y_offset = if let Some(rail) = self.rail(front.0, front.1, front.2) {
if rail.shape.is_slope() { 0.6 } else { 0.1 }
} else {
if !self.res.facts.is_air(self.block_at(front)) {
if !self.res.facts().is_air(self.block_at(front)) {
return (self.dispense_default(pos, facing, stack), CLICK);
}
let below = (front.0, front.1 - 1, front.2);
@@ -1389,7 +1393,7 @@ impl Game<'_> {
stack: ItemStack,
) -> Result<Dispensed> {
let target = offset(pos, facing);
let free = self.res.facts.is_air(self.block_at(target))
let free = self.res.facts().is_air(self.block_at(target))
&& target.1 >= horizon_client::chunk::MIN_Y + 2
&& self.ui.difficulty != 0
&& self.can_build_wither(target);
@@ -1443,7 +1447,7 @@ impl Game<'_> {
"minecraft:soul_sand" | "minecraft:soul_soil"
)
};
let air = |p: Pos| self.res.facts.is_air(self.block_at(p));
let air = |p: Pos| self.res.facts().is_air(self.block_at(p));
for (ax, az) in [(1, 0), (0, 1)] {
for col in 0..3 {
let left = (head.0 - ax * col, head.1, head.2 - az * col);
@@ -1466,7 +1470,7 @@ impl Game<'_> {
stack: ItemStack,
) -> Result<Dispensed> {
let target = offset(pos, facing);
if self.res.facts.is_air(self.block_at(target))
if self.res.facts().is_air(self.block_at(target))
&& self.can_spawn_golem([target.0, target.1, target.2])
{
if let Some(pumpkin) = self
@@ -1511,7 +1515,7 @@ impl Game<'_> {
let front = offset(pos, facing);
let below_empty = self
.res
.facts
.facts()
.is_air(self.block_at((front.0, front.1 - 1, front.2)));
let clicked_face = if below_empty { facing } else { Direction::Up };
let ctx = PlaceContext {
@@ -1539,7 +1543,7 @@ impl Game<'_> {
return Ok((Some(stack), FAIL));
};
let target = (placed.x, placed.y, placed.z);
if let Some(entity) = BlockEntity::for_block(&self.res.facts.get(state).name) {
if let Some(entity) = BlockEntity::for_block(&self.res.facts().get(state).name) {
self.world.block_entities.insert(target, entity);
self.apply_placed_item([target.0, target.1, target.2], &stack, false);
}
@@ -1689,14 +1693,14 @@ impl Game<'_> {
table: &str,
held: Option<&ItemStack>,
) -> Vec<ItemStack> {
match self.res.items.loot_sequence(parent) {
match self.res.items().loot_sequence(parent) {
Some(sequence) => {
let random = self.rand_sequences.get(&sequence, self.level.seed);
self.res.items.loot_table_from(table, false, held, random)
self.res.items().loot_table_from(table, false, held, random)
}
None => self
.res
.items
.items()
.loot_table(table, false, held, &mut self.world.random),
}
}
@@ -1717,7 +1721,7 @@ impl Game<'_> {
/// random draws) keeps the name, flags, persistence and age; the old one
/// is discarded.
pub(super) fn convert_mob(&mut self, index: usize, kind: &str) -> Option<u32> {
let t = self.res.mob_types.get(kind).cloned()?;
let t = self.res.mob_types().get(kind).cloned()?;
let old = &self.mobs[index];
self.next_entity += 1;
let mut mob = Mob::new(self.next_entity, t, old.position, old.yaw);
+28 -20
View File
@@ -447,9 +447,9 @@ impl Game<'_> {
}
fn end_portal_active(&self) -> bool {
(0..256).any(|y| {
&*self.res.facts.get(self.world.block(0, y, 0)).name == "minecraft:bedrock"
&*self.res.facts().get(self.world.block(0, y, 0)).name == "minecraft:bedrock"
&& (-3..=3).any(|d| {
&*self.res.facts.get(self.world.block(d, y, 0)).name == "minecraft:end_portal"
&*self.res.facts().get(self.world.block(d, y, 0)).name == "minecraft:end_portal"
})
})
}
@@ -591,7 +591,7 @@ impl Game<'_> {
let p = self.crystals[i].position;
let b = [p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32];
if let Some(fire) = fire
&& self.res.facts.is_air(self.world.block(b[0], b[1], b[2]))
&& self.res.facts().is_air(self.world.block(b[0], b[1], b[2]))
&& self.world.loaded(b[0], b[2])
{
let _ = self.level_set(b, fire);
@@ -764,7 +764,7 @@ impl Game<'_> {
let held = self.held().cloned();
let modifiers = held
.as_ref()
.and_then(|h| self.res.items.get(&h.item))
.and_then(|h| self.res.items().get(&h.item))
.map(|i| (i.attack_damage, i.attack_speed))
.unwrap_or((0.0, 0.0));
let speed = (4.0 + modifiers.1).max(0.1);
@@ -813,7 +813,7 @@ impl Game<'_> {
(0..256)
.rev()
.find(|&y| {
let f = self.res.facts.get(self.world.block(x, y, z));
let f = self.res.facts().get(self.world.block(x, y, z));
(f.full_collision
|| f.legacy_solid
|| f.fluid != horizon_client::blocks::Fluid::None)
@@ -1257,7 +1257,7 @@ impl Game<'_> {
let (x, z) = (head.x + look.x * 2.5, head.z + look.y * 2.5);
let mut y = head.y + 0.5;
while y > 0.0
&& self.res.facts.is_air(self.world.block(
&& self.res.facts().is_air(self.world.block(
x.floor() as i32,
y.floor() as i32,
z.floor() as i32,
@@ -1594,7 +1594,7 @@ impl Game<'_> {
return;
};
let boxes = [d.part_box(0), d.part_box(1), d.part_box(2)];
let tags = &self.res.items.block_tags;
let tags = &self.res.items().block_tags;
let transparent = tags
.get("minecraft:dragon_transparent")
.cloned()
@@ -1610,8 +1610,8 @@ impl Game<'_> {
for y in lo.y.floor() as i32..=hi.y.floor() as i32 {
for z in lo.z.floor() as i32..=hi.z.floor() as i32 {
let state = self.world.block(x, y, z);
let name = &self.res.facts.get(state).name;
if self.res.facts.is_air(state) || transparent.contains(&**name) {
let name = &self.res.facts().get(state).name;
if self.res.facts().is_air(state) || transparent.contains(&**name) {
continue;
}
if griefing && !immune.contains(&**name) {
@@ -1713,7 +1713,7 @@ impl Game<'_> {
let y = (0..256)
.rev()
.find(|&y| {
let f = self.res.facts.get(self.world.block(0, y, 0));
let f = self.res.facts().get(self.world.block(0, y, 0));
f.full_collision || f.legacy_solid
})
.map_or(64, |y| y + 1);
@@ -1767,7 +1767,7 @@ impl Game<'_> {
next.y.floor() as i32,
next.z.floor() as i32,
];
let f = self.res.facts.get(self.world.block(p[0], p[1], p[2]));
let f = self.res.facts().get(self.world.block(p[0], p[1], p[2]));
f.full_collision || f.legacy_solid
};
let hit_player = player.is_some_and(|pb| {
@@ -1869,9 +1869,9 @@ impl Game<'_> {
batch.width as i32,
batch.height as i32,
&bars,
&self.atlas.font,
&self.gui.atlas.font,
);
hud_layout::paint(batch, &self.atlas, &draws);
hud_layout::paint(batch, &self.gui.atlas, &draws);
}
/// The dragon fight's boss bar shows (`EnderDragonFight.dragonEvent`,
/// with `setCreateWorldFog`).
@@ -1909,7 +1909,13 @@ impl Game<'_> {
return;
};
let a = alpha as f32;
let sprite = |n: &str| self.atlas.sprites.get(n).map(|r| [r.u0, r.v0, r.u1, r.v1]);
let sprite = |n: &str| {
self.gui
.atlas
.sprites
.get(n)
.map(|r| [r.u0, r.v0, r.u1, r.v1])
};
let (Some(skin), Some(eyes)) = (
sprite("entity/enderdragon/dragon"),
sprite("entity/enderdragon/dragon_eyes"),
@@ -2075,7 +2081,7 @@ impl Game<'_> {
}
/// `submitRays`: the death rays from a fixed seed, fading in white to magenta.
fn dragon_rays(&self, base: glam::Mat4, t: f32, out: &mut Vec<Vertex>) {
let white = self.atlas.font.white();
let white = self.gui.atlas.font.white();
let uv = [white.u0, white.v0];
let over = if t > 0.8 {
((t - 0.8) / 0.2).min(1.0)
@@ -2131,6 +2137,7 @@ impl Game<'_> {
out: &mut Vec<Vertex>,
) {
let Some(s) = self
.gui
.atlas
.sprites
.get("entity/end_crystal/end_crystal_beam")
@@ -2192,6 +2199,7 @@ impl Game<'_> {
out: &mut Vec<Vertex>,
) {
let Some(s) = self
.gui
.atlas
.sprites
.get("entity/enderdragon/dragon_fireball")
@@ -2381,7 +2389,7 @@ impl Game<'_> {
}
let name = self
.res
.facts
.facts()
.get(self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]))
.name
.clone();
@@ -2391,7 +2399,7 @@ impl Game<'_> {
let above = [hit.pos[0], hit.pos[1] + 1, hit.pos[2]];
if !self
.res
.facts
.facts()
.is_air(self.world.block(above[0], above[1], above[2]))
{
return false;
@@ -2512,7 +2520,7 @@ impl Game<'_> {
}
fn block_name_at(&self, p: [i32; 3]) -> std::sync::Arc<str> {
self.res
.facts
.facts()
.get(self.world.block(p[0], p[1], p[2]))
.name
.clone()
@@ -2614,7 +2622,7 @@ impl Game<'_> {
for y in h - 10..=h + 10 {
for z in cz - 10..=cz + 10 {
for x in cx - 10..=cx + 10 {
if !self.res.facts.is_air(self.world.block(x, y, z)) {
if !self.res.facts().is_air(self.world.block(x, y, z)) {
let _ = self.level_set([x, y, z], air);
}
}
@@ -2636,7 +2644,7 @@ impl Game<'_> {
if &*self.block_name_at([x, y, z]) != "minecraft:obsidian" {
let _ = self.set_state_named([x, y, z], "minecraft:obsidian", &[]);
}
} else if y > 65 && !self.res.facts.is_air(self.world.block(x, y, z)) {
} else if y > 65 && !self.res.facts().is_air(self.world.block(x, y, z)) {
let _ = self.level_set([x, y, z], air);
}
}
@@ -16,7 +16,7 @@ impl Game<'_> {
let held = self.inventory[self.selected].as_ref();
speed += self
.res
.stations
.stations()
.enchantments
.attribute_add(held, "minecraft:mining_efficiency") as f32;
}
@@ -26,7 +26,7 @@ impl Game<'_> {
pub(super) fn submerged_mining_speed(&self) -> f32 {
let mut total = 0.0;
for stack in self.armor.iter().flatten() {
for (attr, _, amount, op) in self.res.stations.enchantments.attributes(stack) {
for (attr, _, amount, op) in self.res.stations().enchantments.attributes(stack) {
if attr == "minecraft:submerged_mining_speed" && op == "add_multiplied_total" {
total += amount;
}
@@ -36,13 +36,13 @@ impl Game<'_> {
}
/// `EnchantmentHelper.processDurabilityChange` (unbreaking) for `amount` points.
pub(super) fn durability_loss(&mut self, stack: &ItemStack, amount: u32) -> u32 {
let e = &self.res.stations.enchantments;
let e = &self.res.stations().enchantments;
if !e.has_component(stack, "minecraft:item_damage") {
return amount;
}
let ctx = EffectContext {
tool: Some(&stack.item),
items: Some(&self.res.items),
items: Some(self.res.items()),
..Default::default()
};
e.modify_value(
@@ -65,10 +65,10 @@ impl Game<'_> {
direct_attacker: Some("minecraft:player"),
is_direct: true,
damage_type: Some("minecraft:player_attack"),
items: Some(&self.res.items),
items: Some(self.res.items()),
..Default::default()
};
self.res.stations.enchantments.modify_value(
self.res.stations().enchantments.modify_value(
Some(&held),
"minecraft:damage",
&ctx,
@@ -96,10 +96,10 @@ impl Game<'_> {
attacker: Some("minecraft:player"),
direct_attacker: Some("minecraft:player"),
is_direct: true,
items: Some(&self.res.items),
items: Some(self.res.items()),
..Default::default()
};
let knockback = self.res.stations.enchantments.modify_value(
let knockback = self.res.stations().enchantments.modify_value(
Some(&held),
"minecraft:knockback",
&ctx,
@@ -130,7 +130,7 @@ impl Game<'_> {
// minecraft:post_attack ignite effects of the attacker's weapon (fire aspect).
let mut ignite = 0.0f32;
for (id, level) in held.enchantments() {
let Some(def) = self.res.stations.enchantments.get(id) else {
let Some(def) = self.res.stations().enchantments.get(id) else {
continue;
};
for effect in def.effects["minecraft:post_attack"]
@@ -145,7 +145,7 @@ impl Game<'_> {
let mut random = self.world.random.clone();
let ok = effect.get("requirements").is_none_or(|r| {
self.res
.stations
.stations()
.enchantments
.condition(r, *level, &ctx, &mut random)
});
@@ -182,13 +182,13 @@ impl Game<'_> {
attacker: Some("minecraft:player"),
direct_attacker: Some("minecraft:player"),
is_direct: true,
items: Some(&self.res.items),
items: Some(self.res.items()),
direct_motion: Some(motion),
..Default::default()
};
let mut bursts = Vec::new();
for (id, level) in held.enchantments() {
let Some(def) = self.res.stations.enchantments.get(id) else {
let Some(def) = self.res.stations().enchantments.get(id) else {
continue;
};
for effect in def.effects["minecraft:post_attack"]
@@ -205,7 +205,7 @@ impl Game<'_> {
continue;
}
let ok = effect.get("requirements").is_none_or(|r| {
self.res.stations.enchantments.condition(
self.res.stations().enchantments.condition(
r,
*level,
&ctx,
@@ -254,16 +254,16 @@ impl Game<'_> {
if level == 0 {
continue;
}
let Some(def) = self.res.stations.enchantments.get("minecraft:thorns") else {
let Some(def) = self.res.stations().enchantments.get("minecraft:thorns") else {
continue;
};
let effect = def.effects["minecraft:post_attack"][0].clone();
let ctx = EffectContext {
items: Some(&self.res.items),
items: Some(self.res.items()),
..Default::default()
};
let mut random = self.world.random.clone();
let ok = self.res.stations.enchantments.condition(
let ok = self.res.stations().enchantments.condition(
&effect["requirements"],
level,
&ctx,
@@ -286,7 +286,7 @@ impl Game<'_> {
s.damage += 2;
if self
.res
.items
.items()
.get(&s.item)
.is_some_and(|i| s.damage >= i.max_damage)
{
@@ -330,10 +330,10 @@ impl Game<'_> {
};
let Some(stack) = stack else { return amount };
let ctx = EffectContext {
items: Some(&self.res.items),
items: Some(self.res.items()),
..Default::default()
};
let to_repair_xp = self.res.stations.enchantments.modify_value(
let to_repair_xp = self.res.stations().enchantments.modify_value(
Some(&stack),
"minecraft:repair_with_xp",
&ctx,
@@ -364,11 +364,11 @@ impl Game<'_> {
let Some(bow) = self.inventory[self.selected].clone() else {
return (0.0, false);
};
let e = &self.res.stations.enchantments;
let e = &self.res.stations().enchantments;
let ctx = EffectContext {
direct_attacker: Some("minecraft:arrow"),
attacker: Some("minecraft:player"),
items: Some(&self.res.items),
items: Some(self.res.items()),
..Default::default()
};
let power = e.modify_value(
@@ -380,7 +380,7 @@ impl Game<'_> {
);
let ammo_ctx = EffectContext {
tool: Some("minecraft:arrow"),
items: Some(&self.res.items),
items: Some(self.res.items()),
..Default::default()
};
let infinity = e.has_component(&bow, "minecraft:ammo_use")
@@ -399,12 +399,12 @@ impl Game<'_> {
let bow = self.inventory[self.selected].clone()?;
let ctx = EffectContext {
this: Some("minecraft:arrow"),
items: Some(&self.res.items),
items: Some(self.res.items()),
..Default::default()
};
let mut ignite: Option<f32> = None;
for (id, level) in bow.enchantments() {
let Some(def) = self.res.stations.enchantments.get(id) else {
let Some(def) = self.res.stations().enchantments.get(id) else {
continue;
};
for effect in def.effects["minecraft:projectile_spawned"]
@@ -416,7 +416,7 @@ impl Game<'_> {
continue;
}
let ok = effect.get("requirements").is_none_or(|r| {
self.res.stations.enchantments.condition(
self.res.stations().enchantments.condition(
r,
*level,
&ctx,
@@ -436,7 +436,7 @@ impl Game<'_> {
pub(super) fn apply_enchantment_attributes(&mut self) {
let mut wanted: Vec<(String, String, f64, String)> = Vec::new();
for stack in self.armor.iter().flatten() {
wanted.extend(self.res.stations.enchantments.attributes(stack));
wanted.extend(self.res.stations().enchantments.attributes(stack));
}
let Some(p) = self.player.as_mut() else {
return;
+13 -11
View File
@@ -132,9 +132,9 @@ impl Game<'_> {
/// The environment attributes of the current dimension.
pub(super) fn dim_environment(&self) -> &Environment {
match self.dim {
Dim::Overworld => &self.res.environment,
Dim::Nether => &self.res.nether_environment,
Dim::End => &self.res.end_environment,
Dim::Overworld => self.res.environment(),
Dim::Nether => self.res.nether_environment(),
Dim::End => self.res.end_environment(),
}
}
@@ -142,7 +142,7 @@ impl Game<'_> {
/// tinted 0x282828. The atlas does not wrap, so each face is 16×16 quads.
pub(super) fn end_sky_geometry(&self) -> Vec<Vertex> {
let mut out = Vec::with_capacity(6 * 256 * 4);
let Some(r) = self.atlas.sprites.get("environment/end_sky").copied() else {
let Some(r) = self.gui.atlas.sprites.get("environment/end_sky").copied() else {
return out;
};
use std::f32::consts::FRAC_PI_2;
@@ -184,6 +184,7 @@ impl Game<'_> {
let intensity = self.end.flash.intensity(self.clock.fraction() as f32);
if intensity > 1e-5
&& let Some(r) = self
.gui
.atlas
.sprites
.get("environment/celestial/end_flash")
@@ -224,7 +225,7 @@ impl Game<'_> {
pub(super) fn block_name(&self, p: [i32; 3]) -> std::sync::Arc<str> {
self.res
.facts
.facts()
.get(self.world.block(p[0], p[1], p[2]))
.name
.clone()
@@ -561,7 +562,7 @@ impl Game<'_> {
let mut y = (0..256)
.rev()
.find(|&y| {
let f = self.res.facts.get(self.world.block(0, y, 0));
let f = self.res.facts().get(self.world.block(0, y, 0));
(f.full_collision || f.fluid != horizon_client::blocks::Fluid::None)
&& !f.name.ends_with("_leaves")
})
@@ -783,7 +784,7 @@ impl Game<'_> {
let mut y = 255;
while y > floor {
let p = [around[0] + xd, y, around[2] + zd];
let f = self.res.facts.get(self.world.block(p[0], p[1], p[2]));
let f = self.res.facts().get(self.world.block(p[0], p[1], p[2]));
if f.full_collision && (allow_bedrock || &*f.name != "minecraft:bedrock") {
tallest = Some(p);
break;
@@ -839,12 +840,12 @@ impl Game<'_> {
if &*self.block_name([x, y, z]) != "minecraft:end_stone"
|| self
.res
.facts
.facts()
.get(self.world.block(x, y + 1, z))
.full_collision
|| self
.res
.facts
.facts()
.get(self.world.block(x, y + 2, z))
.full_collision
{
@@ -920,7 +921,8 @@ impl Game<'_> {
fn end_crystal_geometry(&self, camera: glam::DVec3, out: &mut Vec<Vertex>) {
let (Some(model), Some(r)) = (
self.crystal_model.as_ref(),
self.atlas
self.gui
.atlas
.sprites
.get("entity/end_crystal/end_crystal")
.copied(),
@@ -1073,7 +1075,7 @@ impl Game<'_> {
/// ThrownItemRenderer: the ender eye item facing the camera.
fn eye_geometry(&self, camera: glam::DVec3, out: &mut Vec<Vertex>) {
let Some(r) = self.atlas.sprites.get("item/ender_eye").copied() else {
let Some(r) = self.gui.atlas.sprites.get("item/ender_eye").copied() else {
return;
};
let alpha = self.clock.fraction();
@@ -21,7 +21,7 @@ impl Game<'_> {
&& self.settings.resource_packs.iter().all(|id| id == "vanilla")
&& self.player.is_some()
&& !self.spectator()
&& !opaque(self.res.facts.get(self.world.block(at[0], at[1], at[2]))))
&& !opaque(self.res.facts().get(self.world.block(at[0], at[1], at[2]))))
.then(|| Culler::new(camera.to_array(), 8_192));
}
@@ -31,7 +31,7 @@ impl Game<'_> {
if let Some(culler) = &self.entity_culler {
culler.cull_vertices(vertices, start, |pos| {
let state = self.world.block(pos[0], pos[1], pos[2]);
if !opaque(self.res.facts.get(state)) {
if !opaque(self.res.facts().get(state)) {
return false;
}
let Some(y) = pos[1].checked_sub(MIN_Y) else {
+18 -3
View File
@@ -167,7 +167,11 @@ impl Game<'_> {
Snapshot {
screen: self.screen_label(),
dimension: self.dim.id().to_string(),
chat: self.ui.chat.received,
// A remote client counts the server's lines itself.
chat: self
.remote
.as_ref()
.map_or(self.ui.chat.received, |r| r.chat_received),
counts: if world.is_some() {
self.inventory_counts()
} else {
@@ -189,8 +193,19 @@ impl Game<'_> {
if let Some(before) = &self.events.last
&& *before != now
{
let new_chat = (now.chat - before.chat).min(100) as usize;
let lines = self.ui.chat.recent_lines(new_chat);
// Joining or leaving a server starts another count.
let new_chat = now.chat.saturating_sub(before.chat).min(100) as usize;
// Newest first; the remote client keeps its lines oldest first.
let lines = match &self.remote {
Some(r) => r
.chat
.iter()
.rev()
.take(new_chat)
.map(|(t, _)| t.clone())
.collect(),
None => self.ui.chat.recent_lines(new_chat),
};
for event in diff(before, &now, &lines) {
self.events.push(self.ticks, event);
}
+8 -8
View File
@@ -196,7 +196,7 @@ impl Game<'_> {
break;
}
let state = self.world.block(pos[0], pos[1], pos[2]);
let f = self.res.facts.get(state);
let f = self.res.facts().get(state);
let fluid = if f.fluid != Fluid::None {
100.0f32
} else {
@@ -206,7 +206,7 @@ impl Game<'_> {
Some((at, resistance)) if at == pos => {
power -= (resistance + 0.3) * 0.3;
}
_ if !self.res.facts.is_air(state) || f.fluid != Fluid::None => {
_ if !self.res.facts().is_air(state) || f.fluid != Fluid::None => {
power -= (f.explosion_resistance.max(fluid) + 0.3) * 0.3;
}
_ => {}
@@ -450,11 +450,11 @@ impl Game<'_> {
if self.world.random.next_int_bound(3).unwrap_or(1) == 0
&& self
.res
.facts
.facts()
.is_air(self.world.block(pos[0], pos[1], pos[2]))
&& self
.res
.facts
.facts()
.get(self.world.block(pos[0], pos[1] - 1, pos[2]))
.solid_render
{
@@ -475,7 +475,7 @@ impl Game<'_> {
} else {
targets.len()
};
let (world, facts) = (&self.world, &self.res.facts);
let (world, facts) = (&self.world, self.res.facts());
self.particles.explosion(center, radius, block_count, &|b| {
facts.is_air(world.block(b[0], b[1], b[2]))
});
@@ -490,10 +490,10 @@ impl Game<'_> {
stacks: &mut Vec<([i32; 3], ItemStack)>,
) -> Result<()> {
let state = self.world.block(pos[0], pos[1], pos[2]);
if self.res.facts.is_air(state) {
if self.res.facts().is_air(state) {
return Ok(());
}
let name = self.res.facts.get(state).name.clone();
let name = self.res.facts().get(state).name.clone();
let is_tnt = &*name == "minecraft:tnt";
// Block.onExplosionHit: the drops copy from the block entity, which
// then spills its contents as the block turns to air.
@@ -510,7 +510,7 @@ impl Game<'_> {
// tables' survives_explosion and explosion_decay draw from their
// random sequence.
let decay = (interaction == BlockInteraction::DestroyWithDecay).then_some(radius);
let drops = self.res.items.block_drops_exploded(
let drops = self.res.items().block_drops_exploded(
self.pack.assets.registry,
state,
None,
+5 -5
View File
@@ -188,7 +188,7 @@ impl Game<'_> {
let radius = ((reach / 16.0).ceil() as i32 + 1).min(self.settings.render_distance.max(2));
self.extras.minimap.update(
&self.world,
&self.res.facts,
self.res.facts(),
(bx >> 4, bz >> 4),
radius,
layer,
@@ -197,10 +197,10 @@ impl Game<'_> {
if !self.extras.minimap.compose(view) {
return;
}
let Some(rect) = self.atlas.sprites.get(MINIMAP_SPRITE).copied() else {
let Some(rect) = self.gui.atlas.sprites.get(MINIMAP_SPRITE).copied() else {
return;
};
let (w, h) = (self.atlas.width as f32, self.atlas.height as f32);
let (w, h) = (self.gui.atlas.width as f32, self.gui.atlas.height as f32);
self.map_patches.push(horizon_client::font::Patch {
x: (rect.u0 * w).round() as u32,
y: (rect.v0 * h).round() as u32,
@@ -246,7 +246,7 @@ impl Game<'_> {
let (map_corner, map_size) = (e.minimap_corner, f32::from(e.minimap_size));
let visible = |corner| !(self.debug && corner == Corner::TopLeft);
let mut corners = Corners::new(batch.width, batch.height, self.effect_rows_height());
let atlas = &self.atlas;
let atlas = &self.gui.atlas;
if let Some(view) = self.minimap_view()
&& visible(map_corner)
&& !self.extras.minimap.image.is_empty()
@@ -290,7 +290,7 @@ impl Game<'_> {
use_: self.extras.mouse[1],
cps,
};
extras_hud::draw_keystrokes(batch, &self.atlas, &mut corners, keys_corner, &k);
extras_hud::draw_keystrokes(batch, &self.gui.atlas, &mut corners, keys_corner, &k);
}
if mod_panels {
self.draw_mod_panels(batch, &mut corners);
@@ -6,7 +6,7 @@ use horizon_world::level::LevelEvent;
impl Game<'_> {
pub(super) fn finish_falling_block(&mut self, mut block: FallingBlock, pos: [i32; 3]) {
let anvil = self.res.facts.get(block.state).name.ends_with("anvil");
let anvil = self.res.facts().get(block.state).name.ends_with("anvil");
if let Some(impact) = block.damage.impact(block.fall_distance) {
if impact.amount > 0.0 {
falling_block::hurt_mobs(&mut self.mobs, block.position, impact.amount);
@@ -80,7 +80,7 @@ impl Game<'_> {
&& block.drop_item
&& self.ui.rules.bool("entity_drops")
{
let item = self.res.facts.get(block.state).item.clone();
let item = self.res.facts().get(block.state).item.clone();
if &*item != "minecraft:air" {
self.pop_resource(
pos,
+1
View File
@@ -108,6 +108,7 @@ impl Game<'_> {
return;
};
let Some(r) = self
.gui
.atlas
.sprites
.get("entity/illager/evoker_fangs")
+10 -5
View File
@@ -226,14 +226,18 @@ impl Game<'_> {
fn biome_name_at(&self, p: Vec3) -> Option<String> {
let (x, y, z) = (p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32);
let c = self.world.chunks.get(&(x >> 4, z >> 4))?;
Some(self.res.biomes.list[c.biome(x, y, z) as usize].name.clone())
Some(
self.res.biomes().list[c.biome(x, y, z) as usize]
.name
.clone(),
)
}
fn water_height(&self, x: i32, y: i32, z: i32) -> Option<(f32, bool)> {
let f = self.res.facts.get(self.world.block(x, y, z));
let f = self.res.facts().get(self.world.block(x, y, z));
if f.fluid != Fluid::Water {
return None;
}
let above = self.res.facts.get(self.world.block(x, y + 1, z));
let above = self.res.facts().get(self.world.block(x, y + 1, z));
let h = if above.fluid == Fluid::Water {
1.0
} else {
@@ -243,7 +247,7 @@ impl Game<'_> {
}
/// getOpenWaterTypeForBlock: 0 above water, 1 inside water, 2 invalid.
fn open_water_type(&self, x: i32, y: i32, z: i32) -> u8 {
let f = self.res.facts.get(self.world.block(x, y, z));
let f = self.res.facts().get(self.world.block(x, y, z));
if self.world.is_air(self.world.block(x, y, z)) || &*f.name == "minecraft:lily_pad" {
return 0;
}
@@ -390,7 +394,7 @@ impl Game<'_> {
(fish[1] - 1.0).floor() as i32,
fish[2].floor() as i32,
);
&*self.res.facts.get(state).name == "minecraft:water"
&*self.res.facts().get(state).name == "minecraft:water"
}
/// `ServerLevel.sendParticles` of a simple particle.
fn send_particles(
@@ -565,6 +569,7 @@ impl Game<'_> {
return;
};
let Some(r) = self
.gui
.atlas
.sprites
.get("entity/fishing/fishing_hook")
+2 -2
View File
@@ -75,7 +75,7 @@ impl Game<'_> {
}
/// The fluid at the camera, as `Camera.getFluidInCamera` reports it.
fn camera_fluid(&self, camera: [f64; 3]) -> CameraFluid {
match fog_type(&self.world, &self.res.facts, camera, self.forward()) {
match fog_type(&self.world, self.res.facts(), camera, self.forward()) {
FogType::Water => CameraFluid::Water,
FogType::Lava => CameraFluid::Lava,
FogType::PowderSnow => CameraFluid::PowderSnow,
@@ -177,6 +177,6 @@ impl Game<'_> {
}
let draws =
hud_overlays::spyglass(batch.width as i32, batch.height as i32, self.scope_scale);
hud_layout::paint(batch, &self.atlas, &draws);
hud_layout::paint(batch, &self.gui.atlas, &draws);
}
}
+9 -2
View File
@@ -110,7 +110,7 @@ impl Game<'_> {
return false;
}
let s = f.step();
let behind = self.res.facts.get(self.world.block(
let behind = self.res.facts().get(self.world.block(
f.pos[0] - s[0],
f.pos[1] - s[1],
f.pos[2] - s[2],
@@ -282,8 +282,15 @@ impl Game<'_> {
}
/// BlockAttachedEntity.tick for frames.
pub(super) fn tick_item_frames(&mut self) {
// ServerLevel.tick: only entities in entity-ticking chunks tick.
let ticking = self.entity_ticking_area();
let mut i = 0;
while i < self.item_frames.len() {
let at = center(&self.item_frames[i]);
if !ticking(at[0].floor() as i32, at[2].floor() as i32) {
i += 1;
continue;
}
self.item_frames[i].check_interval += 1;
if self.item_frames[i].check_interval >= 100 {
self.item_frames[i].check_interval = 0;
@@ -301,7 +308,7 @@ impl Game<'_> {
}
/// ItemFrameRenderer: the frame model, then the item half size on its face.
pub(super) fn frame_geometry(&mut self, camera: glam::DVec3, out: &mut Vec<Vertex>) {
let sprites = &self.atlas.sprites;
let sprites = &self.gui.atlas.sprites;
let mut maps: Vec<(i32, glam::Mat4, u32)> = Vec::new();
let mut items: Vec<(ItemStack, u32, glam::Mat4, u8)> = Vec::new();
// ItemFrame.shouldRenderAtSqrDistance: 1024 blocks at 100%.
@@ -39,7 +39,7 @@ impl Game<'_> {
};
switcher.hover(w, h, (self.cursor.0 as i32, self.cursor.1 as i32));
let selected = switcher.selected;
let atlas = &self.atlas;
let atlas = &self.gui.atlas;
batch.sprite_region(
atlas,
"gui/container/gamemode_switcher",
@@ -62,14 +62,14 @@ impl Game<'_> {
for (index, mode) in MODES.into_iter().enumerate() {
let (x, y) = slot_origin(w, h, index);
batch.sprite(
&self.atlas,
&self.gui.atlas,
"gui/sprites/gamemode_switcher/slot",
x as f32,
y as f32,
);
if mode == selected {
batch.sprite(
&self.atlas,
&self.gui.atlas,
"gui/sprites/gamemode_switcher/selection",
x as f32,
y as f32,
+7 -7
View File
@@ -8,7 +8,7 @@ use horizon_client::Result;
impl Game<'_> {
fn golem_block(&self, p: [i32; 3]) -> &str {
let state = self.world.block(p[0], p[1], p[2]);
&self.res.facts.get(state).name
&self.res.facts().get(state).name
}
fn is_golem_head(&self, p: [i32; 3]) -> bool {
matches!(
@@ -33,7 +33,7 @@ impl Game<'_> {
for (ax, az) in [(1, 0), (0, 1)] {
let side = |s: i32, row: i32| [head[0] + ax * s, head[1] - row, head[2] + az * s];
let arms = (-1..=1).all(|s| self.golem_block(side(s, 1)) == "minecraft:iron_block");
let air = |p: [i32; 3]| self.res.facts.is_air(self.world.block(p[0], p[1], p[2]));
let air = |p: [i32; 3]| self.res.facts().is_air(self.world.block(p[0], p[1], p[2]));
if arms
&& self.golem_block(side(0, 2)) == "minecraft:iron_block"
&& [-1, 1].iter().all(|&s| air(side(s, 0)) && air(side(s, 2)))
@@ -58,7 +58,7 @@ impl Game<'_> {
let below = [head[0], head[1] - 1, head[2]];
let name = self.golem_block(below);
self.res
.items
.items()
.block_tags
.get("minecraft:copper")
.is_some_and(|t| t.contains(name))
@@ -88,7 +88,7 @@ impl Game<'_> {
/// `EntityType.create(level, TRIGGERED)` and `snapTo`: a built golem or
/// wither has no spawn finalization and draws nothing from the level.
pub(super) fn create_triggered(&mut self, kind: &str, at: [f64; 3], yaw: f32) -> Option<u32> {
let t = self.res.mob_types.get(kind).cloned()?;
let t = self.res.mob_types().get(kind).cloned()?;
self.next_entity += 1;
let mut mob = horizon_client::mobs::Mob::new(
self.next_entity,
@@ -181,9 +181,9 @@ impl Game<'_> {
});
if let Some(chest) = chest {
self.with_level(|b, level, ticks| b.set_block(level, ticks, pos, chest, 2));
if let Some(entity) =
horizon_client::containers::BlockEntity::for_block(&self.res.facts.get(chest).name)
{
if let Some(entity) = horizon_client::containers::BlockEntity::for_block(
&self.res.facts().get(chest).name,
) {
self.world
.block_entities
.insert((below[0], below[1], below[2]), entity);
+2 -2
View File
@@ -10,7 +10,7 @@ impl Game<'_> {
/// Load the configured/placed feature registry used by saplings, fungi
/// and bone meal (once per process; shares the generator's bundle).
pub(super) fn install_live_features(&self) {
if self.res.behaviours.live_features().is_some() {
if self.res.behaviours().live_features().is_some() {
return;
}
let dir = self.options.resources.join("worldgen");
@@ -20,7 +20,7 @@ impl Game<'_> {
.and_then(|data| LiveFeatures::new(&data).map_err(|e| e.to_string()));
match features {
Ok(Some(features)) => {
self.res.behaviours.set_live_features(Arc::new(features));
self.res.behaviours().set_live_features(Arc::new(features));
log::info!("Horizon: live features ready in {:?}", started.elapsed());
}
Ok(None) => {
+8 -8
View File
@@ -39,7 +39,7 @@ impl Game<'_> {
});
self.clicks.destroying = destroying;
self.attack_clicks = 0;
self.stop_remote_mining();
self.request_remote_mining_stop();
self.mining = None;
}
/// `LivingEntity.swing` with `getModifiedSwingDuration`.
@@ -90,7 +90,7 @@ impl Game<'_> {
let (pos, first) = (d.pos, (d.ticks as u32 - 1).is_multiple_of(4));
let state = self.world.block(pos[0], pos[1], pos[2]);
if first {
let sounds = self.res.facts.get(state).sounds.clone();
let sounds = self.res.facts().get(state).sounds.clone();
self.audio.play(
&sounds.hit,
Some(pos.map(|v| f64::from(v) + 0.5)),
@@ -117,17 +117,17 @@ impl Game<'_> {
/// `BlockBehaviour.getDestroyProgress` with `Player.getDestroySpeed`.
pub(super) fn destroy_progress(&self, pos: [i32; 3]) -> f32 {
let state = self.world.block(pos[0], pos[1], pos[2]);
let facts = self.res.facts.get(state);
let facts = self.res.facts().get(state);
if facts.hardness == -1.0 {
return 0.0;
}
let held = self.held();
let mut speed = self.res.items.mining_speed(held, &facts.name);
let mut speed = self.res.items().mining_speed(held, &facts.name);
speed = self.modify_destroy_speed(speed);
if let Some(eye) = self.eye_position()
&& self
.res
.facts
.facts()
.get(self.world.block(
eye[0].floor() as i32,
eye[1].floor() as i32,
@@ -141,7 +141,7 @@ impl Game<'_> {
if self.player.as_ref().is_some_and(|p| !p.ground.on_ground) {
speed /= 5.0;
}
let harvest = !facts.requires_tool || self.res.items.correct_for_drops(held, &facts.name);
let harvest = !facts.requires_tool || self.res.items().correct_for_drops(held, &facts.name);
speed / facts.hardness / if harvest { 30.0 } else { 100.0 }
}
/// Whether an attack would hit an entity rather than the block behind
@@ -287,7 +287,7 @@ impl Game<'_> {
horizon_client::attack_strength::BASE_ATTACK_SPEED
+ self
.held()
.and_then(|h| self.res.items.get(&h.item))
.and_then(|h| self.res.items().get(&h.item))
.map_or(0.0, |i| f64::from(i.attack_speed))
}
/// `evaluateWhichHandsToRender`: which of the main and off hand show.
@@ -351,7 +351,7 @@ impl HandWorld for GameHands<'_, '_> {
}
fn is_air(&mut self, pos: [i32; 3]) -> bool {
let state = self.game.world.block(pos[0], pos[1], pos[2]);
self.game.res.facts.get(state).name.ends_with("air")
self.game.res.facts().get(state).name.ends_with("air")
}
fn creative(&self) -> bool {
self.game.creative
@@ -83,7 +83,7 @@ impl Game<'_> {
horizon_client::flatgen::FlatTerrain::from_settings(
&s,
self.pack.assets.registry,
&self.res.biomes,
self.res.biomes(),
)
})
{
+67 -4
View File
@@ -10,7 +10,7 @@
//! player joins as a network player, and the server side of a network player
//! does not do everything single player does yet.
use super::{
Game, Options, PackResources, Resources,
Game, Options, PackResources, Resources, UiResources,
lan::{LanSettings, Owner},
};
use horizon_client::{
@@ -201,6 +201,7 @@ impl Game<'_> {
options.server = None;
options.world = None;
options.dev_mods.clear();
self.join_world_rest()?;
let (res, pack, settings) = (self.res.clone(), self.pack.clone(), self.settings.clone());
let flags = Arc::new(Flags::default());
flags
@@ -316,6 +317,7 @@ impl Game<'_> {
// The owner is an operator when the world allows commands
// (`IntegratedPlayerList`, `MinecraftServer.getProfilePermissions`).
host.hub.ops.insert(owner, if commands { 4 } else { 0 });
host.hub.singleplayer_owner = Some(owner);
host.owner = Some(Owner {
uuid: owner,
saved: Some(saved),
@@ -335,11 +337,11 @@ impl Game<'_> {
self.run_tasks();
if flags.paused.load(Ordering::Relaxed) {
// Only the connections run.
self.tick_server(true)?;
self.tick_server_timed(true)?;
} else {
self.follow_distances(&flags);
let started = Instant::now();
self.tick_server(false)?;
self.tick_server_timed(false)?;
self.debug_charts.log_tick(started, started.elapsed());
flags.smoothed_tick_ms.store(
self.debug_charts.smoothed_tick_ms.to_bits(),
@@ -409,6 +411,60 @@ impl Game<'_> {
pub(super) fn serving(&self) -> bool {
self.serving.is_some()
}
/// The window's agent runs a command as single player's console does
/// (`as_console`, as without a server thread): as the world's owner, in
/// the owner's level, at the owner permission level. The feedback goes to
/// the owner's chat and is returned.
pub(super) fn owner_console_command(&mut self, command: &str) -> Vec<String> {
let Some(owner) = self.serving.as_ref().map(|s| s.owner) else {
return Vec::new();
};
let Some(mut host) = self.lan.take() else {
return Vec::new();
};
let mut out = Vec::new();
if let Some(g) = host.hub.guests.iter().find(|g| g.uuid == owner && g.placed) {
let conn = g.conn;
// Commands.performCommand runs in the player's level.
let (back, theirs) = (self.dim, super::Dim::from_id(&g.dimension));
let entered = theirs == back || self.enter_level(Some(&mut host), theirs).is_ok();
if entered {
let command = command.trim_start_matches('/').to_owned();
let lines = self.as_guest(&mut host, conn, |g| {
g.as_console(|g| {
g.chat_capture = Some(Vec::new());
g.run_command(&command);
g.chat_capture.take().unwrap_or_default()
})
});
// A teleport into another level happens before its feedback is sent.
self.run_level_teleports(&mut host);
for line in lines.unwrap_or_default() {
out.push(line.plain());
host.hub.send_to(
conn,
&horizon_protocol::packets::play::Clientbound::SystemChat(
horizon_protocol::packets::play::SystemChat {
content: horizon_client::lan::data::component_nbt(
&line.component(),
),
overlay: false,
},
),
);
}
self.send_admin_feedback(&mut host, Some(conn));
}
if theirs != back
&& let Err(e) = self.enter_level(Some(&mut host), back)
{
log::error!("could not reopen {}: {e}", back.id());
}
}
self.lan = Some(host);
out
}
/// The window's requests, between two ticks.
fn run_tasks(&mut self) {
let tasks: Vec<Task> = match &self.serving {
@@ -594,7 +650,14 @@ fn serve(
) -> Result<()> {
// It draws nothing: only the font, which books and chat measure with.
let atlas = HudAtlas::fonts(&options.resources)?;
let gui = UiResources {
atlas,
panorama: Arc::new(horizon_client::gfx::panorama::Faces {
size: 1,
pixels: [0u8; 4].repeat(6),
}),
};
let audio = Audio::silent(&options.resources);
let mut server = Game::new(res, pack, atlas, options, settings, audio)?;
let mut server = Game::new(res, pack, gui, options, settings, audio)?;
server.run_integrated(launch, flags, tasks, ready)
}
+4 -4
View File
@@ -176,7 +176,7 @@ impl Game<'_> {
}
pub(super) fn item_host(&self) -> Host<'_> {
Host {
banners: &self.res.stations.banners,
banners: &self.res.stations().banners,
}
}
/// The client level as item models read it.
@@ -255,7 +255,7 @@ impl Game<'_> {
item_render::gui::draw(
&state,
&self.pack.item_renderer,
&self.atlas.sprites,
&self.gui.atlas.sprites,
&self.item_host(),
batch,
x,
@@ -279,7 +279,7 @@ impl Game<'_> {
};
state.submit(
&self.pack.item_renderer,
&self.atlas.sprites,
&self.gui.atlas.sprites,
&self.item_host(),
pose,
&mut sink,
@@ -300,7 +300,7 @@ impl Game<'_> {
};
state.submit(
&self.pack.item_renderer,
&self.atlas.sprites,
&self.gui.atlas.sprites,
&self.item_host(),
pose,
&mut sink,
+5 -5
View File
@@ -51,7 +51,7 @@ impl Game<'_> {
pub(super) fn use_jukebox(&mut self, pos: [i32; 3], held: Option<&ItemStack>) -> bool {
if &*self
.res
.facts
.facts()
.get(self.world.block(pos[0], pos[1], pos[2]))
.name
!= "minecraft:jukebox"
@@ -65,7 +65,7 @@ impl Game<'_> {
let Some(stack) = held else { return false };
let Some(song) = self
.res
.items
.items()
.get(&stack.item)
.and_then(|i| i.jukebox_song.clone())
else {
@@ -95,7 +95,7 @@ impl Game<'_> {
/// Level event 1010: the song from the jukebox, and the "Now Playing" overlay.
fn start_song(&mut self, pos: [i32; 3], song: &str) {
self.stop_song(pos);
let Some(s) = self.res.items.songs.get(song).cloned() else {
let Some(s) = self.res.items().songs.get(song).cloned() else {
return;
};
// LevelRenderer.playJukeboxSong: SimpleSoundInstance.forJukeboxSong.
@@ -144,7 +144,7 @@ impl Game<'_> {
pub(super) fn tick_jukebox(&mut self, key: (i32, i32, i32)) {
let playing = match self.world.block_entities.get(&key) {
Some(BlockEntity::Jukebox(j)) if j.playing => j.record.as_ref().and_then(|r| {
let song = self.res.items.get(&r.item)?.jukebox_song.clone()?;
let song = self.res.items().get(&r.item)?.jukebox_song.clone()?;
Some((song, j.ticks))
}),
_ => None,
@@ -153,7 +153,7 @@ impl Game<'_> {
return;
};
let pos = [key.0, key.1, key.2];
let Some(s) = self.res.items.songs.get(&song).cloned() else {
let Some(s) = self.res.items().songs.get(&song).cloned() else {
return;
};
if s.finished(ticks) {
+76 -15
View File
@@ -2,7 +2,7 @@
//! server threads and the play-state hub, feeds it the world's entities each
//! tick and turns what the guests do into gameplay. A world that is not open
//! costs one `Option` check per tick.
use super::Game;
use super::{Game, shield::OFFHAND_SLOT};
use horizon_client::{
Result,
items::ItemStack,
@@ -42,6 +42,8 @@ pub(super) struct LanHost {
pub hub: Hub,
pub settings: LanSettings,
pub host_entity: i32,
/// The host's swings the guests were told of (`Game::swings_started`).
pub host_swings: u32,
pub host_uuid: u128,
/// The host's profile name (the account's, or the offline name).
pub host_name: String,
@@ -61,6 +63,9 @@ pub(super) struct LanHost {
/// are dead, whose respawn replaces their waypoint.
pub waypoints: lan::waypoints::Waypoints,
pub waypoint_dead: std::collections::HashSet<u128>,
/// Guests' commands waiting for the hub to be back in `self.lan`, where
/// a command can reach every player (game/lan_actions.rs).
pub commands: Vec<super::lan_actions::GuestCommand>,
}
/// The player who owns an integrated server's world: a guest whose state is
@@ -395,6 +400,10 @@ impl Game<'_> {
[&m.extra.head, &m.extra.chest, &m.extra.legs, &m.extra.feet]
.map(|s| s.as_deref())
}),
// The host draws this guest's arm swinging.
"model_swinging": h.models.get(&g.conn).map(|m| m.ai.swinging),
// For how many ticks the host draws this guest using an item.
"model_using": h.models.get(&g.conn).map(|m| m.extra.using_item),
})).collect::<Vec<_>>(),
}),
_ => json!({ "open": false }),
@@ -467,7 +476,7 @@ impl Game<'_> {
.clone()?;
let biome_names: Vec<String> = self
.res
.biomes
.biomes()
.list
.iter()
.map(|b| b.name.clone())
@@ -480,7 +489,7 @@ impl Game<'_> {
.unwrap_or_default();
let mut encoder = ChunkEncoder::new(
self.res
.facts
.facts()
.states
.iter()
.map(|s| (s.name.clone(), s.fluid_level > 0 || s.waterlogged)),
@@ -509,6 +518,7 @@ impl Game<'_> {
hub,
settings: LanSettings { port, ..settings },
host_entity,
host_swings: self.swings_started,
host_uuid,
host_name: self.options.player_name(),
models: HashMap::new(),
@@ -520,6 +530,7 @@ impl Game<'_> {
owner: None,
waypoints: Default::default(),
waypoint_dead: Default::default(),
commands: Vec::new(),
});
self.audio.capture = Some(Vec::new());
Ok(())
@@ -722,6 +733,8 @@ impl Game<'_> {
sprinting: p.sprinting,
equipment,
health: p.health.health(),
attributes: horizon_client::lan::attributes::syncable(&p.attributes),
living_flags: living_flags(self.using),
})
}
@@ -732,6 +745,7 @@ impl Game<'_> {
let kind = m.kind.id.as_str();
let meta = mob_meta(m, hub);
let equipment = mob_equipment(m, hub);
let attributes = self.mob_attributes(m);
let (yaw, pitch) = (m.yaw, m.head_pitch);
out.push(EntityState {
id: m.id as i32,
@@ -746,6 +760,7 @@ impl Game<'_> {
data: 0,
meta,
equipment,
attributes,
precise: false,
});
}
@@ -764,6 +779,7 @@ impl Game<'_> {
data: 0,
meta: vec![(8, serializer::ITEM_STACK, Value::Item(stack))],
equipment: Vec::new(),
attributes: Vec::new(),
precise: false,
});
}
@@ -782,6 +798,7 @@ impl Game<'_> {
// ExperienceOrb.DATA_VALUE.
meta: vec![(8, serializer::INT, Value::Int(o.value as i32))],
equipment: Vec::new(),
attributes: Vec::new(),
precise: false,
});
}
@@ -796,7 +813,11 @@ impl Game<'_> {
};
// What the tick sends a guest goes to its connection at the end.
let holding = lan::Holding::start();
// The host's own commands' broadcastToAdmins lines.
// The host's own commands' (and command blocks') players moving
// to another level, and their broadcastToAdmins lines.
if !self.level_teleports.is_empty() {
self.run_level_teleports(&mut host);
}
if !self.admin_feedback.is_empty() {
self.send_admin_feedback(&mut host, None);
}
@@ -814,6 +835,7 @@ impl Game<'_> {
};
let spawn = self.spawn.map_or([0.5, 80.0, 0.5], |s| [s.x, s.y, s.z]);
let events = {
let clock_rate = self.network_clock_rate();
let mut ctx = TickCtx {
world: &mut self.world,
host: state.as_ref(),
@@ -822,11 +844,7 @@ impl Game<'_> {
spawn,
difficulty: i32::from(self.ui.difficulty),
difficulty_locked: self.level.difficulty_locked,
clock_rate: if self.ui.rules.bool("advance_time") {
self.ui.clock.rate
} else {
0.0
},
clock_rate,
tick_rate: self.clock.rate(),
tick_frozen: self.clock.frozen(),
collision: Some(self.collision),
@@ -918,12 +936,18 @@ impl Game<'_> {
}
HostEvent::Packet(conn, packet) => {
self.lan_guest_packet(&mut host, conn, *packet);
if !host.commands.is_empty() {
self.lan = Some(host);
self.run_guest_commands();
host = self.lan.take().expect("the hub is back after the commands");
}
}
}
}
}
self.lan_flush_effects(&mut host);
self.tick_guests(&mut host);
self.lan_living_flags(&mut host);
self.tick_server_travel(&mut host);
self.lan_swings(&mut host);
self.lan_update_streaming(&host);
@@ -991,6 +1015,7 @@ impl Game<'_> {
} else {
entities
};
let clock_rate = self.network_clock_rate();
let mut ctx = TickCtx {
world: &mut self.world,
host: state,
@@ -999,7 +1024,7 @@ impl Game<'_> {
spawn,
difficulty: i32::from(self.ui.difficulty),
difficulty_locked: self.level.difficulty_locked,
clock_rate: self.ui.clock.rate,
clock_rate,
tick_rate: self.clock.rate(),
tick_frozen: self.clock.frozen(),
collision: Some(self.collision),
@@ -1068,8 +1093,30 @@ impl Game<'_> {
.and_then(|s| s.get(&m.id))
.copied();
let at = [m.position.x, m.position.y, m.position.z];
if m.hurt_time > old.map_or(0, |o| o.0) && !dead {
host.hub.entity_event(m.id as i32, 2, at);
// LivingEntity.hurtServer: a hurt that restarted the hurt time.
if m.hurt_time > old.map_or(0, |o| o.0)
&& !dead
&& let Some((source, _)) = m.last_damage
{
use horizon_client::mobs::{DamageKind as K, Who};
let player = source.attacker == Some(Who::Player);
let kind = super::creatures::damage_type(source.kind, player);
// The player a mob sees is the guest acting, else the host.
let cause = source.attacker.map(|who| match who {
Who::Player => host
.mob_players
.get(&m.id)
.and_then(|conn| host.hub.guest(*conn))
.map_or(host.host_entity, |g| g.entity_id),
Who::Mob(id) => id as i32,
});
// A projectile is the direct entity of its hit: not tracked here.
let melee = matches!(
source.kind,
K::PlayerAttack | K::MaceSmash | K::MobAttack | K::Sting | K::SonicBoom
);
let direct = cause.filter(|_| melee);
host.hub.damage_event(m.id as i32, kind, cause, direct, at);
}
if dead && !old.is_some_and(|o| o.1) {
host.hub.entity_event(m.id as i32, 3, at);
@@ -1100,7 +1147,7 @@ impl Game<'_> {
/// The guests' models, for the host to see them.
fn lan_update_models(&mut self, host: &mut LanHost) {
let Some(kind) = self.res.player_type.clone() else {
let Some(kind) = self.res.player_type().clone() else {
return;
};
host.models
@@ -1158,6 +1205,14 @@ impl Game<'_> {
.each_ref()
.map(|s| s.as_ref().map(|s| s.item.clone()));
m.extra.crouching = g.sneaking;
// LivingEntity.updateSwingTime: the arm swing lan_swings started.
m.anim.attack_anim_o = m.anim.attack_anim;
horizon_client::mobs::ai::tick_swing(m);
// LivingEntity.onSyncedDataUpdated(DATA_LIVING_ENTITY_FLAGS): the
// item in use and its hand (the arm poses of a bow, a shield...).
let using = host.play.get(&g.conn).and_then(|p| p.using());
m.extra.using_item = using.map_or(0, |(_, ticks)| ticks as i32 + 1);
m.extra.using_off_hand = using.is_some_and(|(slot, _)| slot == OFFHAND_SLOT);
}
}
@@ -1171,7 +1226,7 @@ impl Game<'_> {
let Some(host) = &self.lan else {
return;
};
let atlas = &self.atlas;
let atlas = &self.gui.atlas;
let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]);
for m in host.models.values() {
let entity_start = out.len();
@@ -1187,7 +1242,7 @@ impl Game<'_> {
camera,
&lookup,
packed,
&self.res.mob_data,
self.res.mob_data(),
&self.worn_armor_layers(m),
out,
);
@@ -1226,3 +1281,9 @@ impl Game<'_> {
}
}
}
/// `LivingEntity.DATA_LIVING_ENTITY_FLAGS` for an item in use: 1, and 2 when
/// it is the off hand's.
pub(super) fn living_flags(using: Option<(usize, u32)>) -> i8 {
using.map_or(0, |(slot, _)| if slot == OFFHAND_SLOT { 3 } else { 1 })
}
+389 -91
View File
@@ -10,6 +10,7 @@ use horizon_client::{
command::vanilla,
containers::BlockEntity,
entities::Experience,
first_person::{Hand, SwingAnimation},
items::ItemStack,
lan::{
guest::SPECTATOR,
@@ -43,8 +44,9 @@ pub(super) struct GuestPlay {
/// its progress since `dig_start` is complete (ServerPlayerGameMode.hasDelayedDestroy).
delayed: Option<([i32; 3], u64)>,
last_progress: i32,
/// Hand movements the client announced and the host animated.
swung: bool,
/// Swings the guest's actions started this tick, for the players around
/// (`LivingEntity.swing` sends ClientboundSwingAnimationPacket).
swings: u32,
/// The trading screen the guest has open.
pub(super) merchant: Option<super::lan_trading::GuestMerchant>,
/// The inventory menu and the crafting table the guest crafts in.
@@ -58,6 +60,78 @@ pub(super) struct GuestPlay {
pub(super) portal: horizon_client::nether_portal::PortalState,
/// `Player.takeXpDelay`: ticks until the next orb can be taken.
xp_delay: u32,
/// What last killed the guest outright (`/kill`): the death message's key.
death_cause: Option<String>,
}
/// A guest's command waiting for the hub (`LanHost::commands`).
pub(super) struct GuestCommand {
conn: u32,
command: String,
permission: u8,
/// An integrated server's: no admin feedback or level teleports (yet).
integrated: bool,
}
/// The game's own state while a guest's is swapped in (`enter_guest`), and
/// the guest's records that live outside `Guest`.
pub(super) struct GuestSwap {
conn: u32,
i: usize,
play: GuestPlay,
player: Option<PlayerMotion>,
/// The guest's eye height and the game's.
eye: (f32, f32),
yaw: f32,
pitch: f32,
selected: usize,
mode: horizon_client::command::args::GameMode,
creative: bool,
xp: Experience,
host_keys: std::collections::HashSet<KeyCode>,
screen: Screen,
host_sign: Option<super::sign_edit::SignEditor>,
host_book: Option<super::books::BookScreen>,
host_command_block: Option<super::command_blocks::CommandBlockScreen>,
host_mount_menu: super::mount_menu::MountMenu,
craft_size: usize,
craft_grid: Vec<Option<ItemStack>>,
container: Option<(i32, i32, i32)>,
mining: Option<Mining>,
destroy_delay: u32,
using: Option<(usize, u32)>,
use_delay: u32,
attack_ticks: u32,
swing: horizon_client::first_person::SwingState,
left: bool,
right: bool,
riding: Option<u32>,
host_station: Option<super::stations::Station>,
sleeping: Option<[i32; 3]>,
sleep_timer: u32,
spawn: Option<Vec3>,
respawn: (
Option<super::respawn_anchor::RespawnConfig>,
Option<[f64; 3]>,
),
message: Option<(String, std::time::Instant)>,
host_ender: Option<(i32, i32, i32)>,
adv_loaded: bool,
last_inventory: u64,
death_cause: Option<String>,
/// The guest whose turn this one nests in, if any.
acting: (Option<u32>, Option<String>, Option<u128>),
/// The packets queued for that guest.
packets: Vec<play::Clientbound>,
/// The host's count of swings started, kept while the guest acts.
swings: u32,
}
impl GuestPlay {
/// The item in use: its slot and for how many ticks.
pub(super) fn using(&self) -> Option<(usize, u32)> {
self.using
}
}
struct ItemRules<'a>(&'a horizon_client::items::Items);
@@ -95,6 +169,24 @@ impl Game<'_> {
conn: u32,
f: impl FnOnce(&mut Self) -> R,
) -> Option<R> {
let swap = self.enter_guest(host, conn)?;
let result = f(self);
self.leave_guest(host, swap);
Some(result)
}
/// The first half of `as_guest`: the guest's state in place of the
/// game's, which the returned swap keeps until `leave_guest`. Between the
/// two the host may go back into `self.lan`, so that what the guest does
/// can reach the other players (their commands, `for_player`), and a
/// guest's turn can nest in another's: the acting guest and the packets
/// queued for them are kept and restored too.
pub(super) fn enter_guest(&mut self, host: &mut LanHost, conn: u32) -> Option<GuestSwap> {
// The guest whose turn it is is in place already (their record holds
// the game's state until their turn ends).
if self.lan_acting == Some(conn) {
return None;
}
let i = host.hub.guests.iter().position(|g| g.conn == conn)?;
if host.hub.guests[i].motion.is_none() {
let p = Vec3::new(
@@ -198,17 +290,115 @@ impl Game<'_> {
std::mem::swap(&mut self.stats, &mut play.stats);
let adv_loaded = std::mem::replace(&mut self.adv.loaded, true);
let last_inventory = std::mem::replace(&mut self.adv.last_inventory, play.last_inventory);
self.lan_acting = Some(conn);
self.lan_acting_name = Some(g.name.clone());
self.lan_acting_uuid = Some(g.uuid);
let death_cause = std::mem::replace(&mut self.ui.death_cause, play.death_cause.take());
let acting = (
self.lan_acting.replace(conn),
self.lan_acting_name.replace(g.name.clone()),
self.lan_acting_uuid.replace(g.uuid),
);
let packets = std::mem::take(&mut self.guest_packets);
let swings = self.swings_started;
Some(GuestSwap {
conn,
i,
play,
player,
eye,
yaw,
pitch,
selected,
mode,
creative,
xp,
host_keys,
screen,
host_sign,
host_book,
host_command_block,
host_mount_menu,
craft_size,
craft_grid,
container,
mining,
destroy_delay,
using,
use_delay,
attack_ticks,
swing,
left,
right,
riding,
host_station,
sleeping,
sleep_timer,
spawn,
respawn,
message,
host_ender,
adv_loaded,
last_inventory,
death_cause,
acting,
packets,
swings,
})
}
let result = f(self);
for packet in std::mem::take(&mut self.guest_packets) {
/// The second half of `as_guest`: the guest's state back into their
/// record, the game's back in place, and what the turn changed sent.
pub(super) fn leave_guest(&mut self, host: &mut LanHost, swap: GuestSwap) {
let GuestSwap {
conn,
i,
mut play,
mut player,
eye,
yaw,
pitch,
selected,
mode,
creative,
xp,
host_keys,
screen,
host_sign,
host_book,
host_command_block,
host_mount_menu,
craft_size,
craft_grid,
container,
mining,
destroy_delay,
using,
use_delay,
attack_ticks,
swing,
left,
right,
riding,
host_station,
sleeping,
sleep_timer,
spawn,
respawn,
message,
host_ender,
adv_loaded,
last_inventory,
death_cause,
acting,
packets,
swings,
} = swap;
// The guest's swings are theirs: the host's own count stays the host's.
play.swings += self.swings_started.wrapping_sub(swings);
self.swings_started = swings;
for packet in std::mem::replace(&mut self.guest_packets, packets) {
host.hub.send_to(conn, &packet);
}
self.lan_acting = None;
self.lan_acting_name = None;
self.lan_acting_uuid = None;
(self.lan_acting, self.lan_acting_name, self.lan_acting_uuid) = acting;
play.death_cause = std::mem::replace(&mut self.ui.death_cause, death_cause);
// An ender chest the guest opened: the menu shows their inventory
// itself (lan_open_container), not a stand-in block entity.
self.close_ender_chest();
@@ -281,6 +471,9 @@ impl Game<'_> {
std::mem::swap(&mut self.armor, &mut g.armor);
std::mem::swap(&mut self.offhand, &mut g.offhand);
std::mem::swap(&mut self.carried, &mut g.carried);
// A teleport with a rotation (commands) turns the guest.
let turned = [self.yaw, self.pitch] != [g.yaw, g.pitch];
[g.yaw, g.pitch] = [self.yaw, self.pitch];
self.yaw = yaw;
self.pitch = pitch;
self.eye = eye.1;
@@ -294,7 +487,7 @@ impl Game<'_> {
m.sprinting = false;
let moved: f64 = (0..3).map(|k| (at[k] - g.position[k]).powi(2)).sum();
g.motion = Some(Box::new(m));
if moved > 0.0001 {
if moved > 0.0001 || turned {
host.hub.teleport(i, Some(at));
}
}
@@ -331,7 +524,6 @@ impl Game<'_> {
if opened_table {
self.lan_open_crafting(host, conn);
}
Some(result)
}
/// `ServerLevel.players()` in turn: the host's own player, then each
@@ -377,7 +569,7 @@ impl Game<'_> {
fn lan_open_container(&mut self, host: &mut LanHost, conn: u32, pos: (i32, i32, i32)) -> bool {
let name = &self
.res
.facts
.facts()
.get(self.world.block(pos.0, pos.1, pos.2))
.name;
let (menu, title, slots) = if &**name == "minecraft:ender_chest" {
@@ -395,6 +587,13 @@ impl Game<'_> {
_ => ("minecraft:furnace", "container.furnace"),
};
(menu, title, Slots::Block(pos))
} else if let Some(BlockEntity::Brewing(_)) = self.world.block_entities.get(&pos) {
// BrewingStandBlock.useWithoutItem: BrewingStandMenu.
(
"minecraft:brewing_stand",
"container.brewing",
Slots::Block(pos),
)
} else if let Some((other, right)) = self.chest_partner(pos) {
// ChestBlock.combine: the right half's slots come first.
let halves = if right {
@@ -542,6 +741,16 @@ impl Game<'_> {
}
}
}
// ServerGamePacketListenerImpl.handlePunch: the main hand swings
// with the held item's attack animation (mining, attacking, a
// click on nothing), seen by the players around, and the attack
// strength starts again.
S::Punch(_) => {
self.as_guest(host, conn, |g| {
g.swing_hand(Hand::Main, SwingAnimation::DEFAULT);
g.reset_attack_strength();
});
}
S::UseItemOn(p) => {
host.hub.ack(conn, p.sequence);
if spectator {
@@ -557,11 +766,14 @@ impl Game<'_> {
f64::from(p.pos[2]) + f64::from(p.cursor[2]),
],
};
self.as_guest(host, conn, |g| {
let swung = self.as_guest(host, conn, |g| {
g.forced_hit = Some(hit);
let swings = g.swings_started;
let _ = g.use_item();
g.forced_hit = None;
g.swings_started != swings
});
self.lan_swing_back(host, conn, swung);
// The client predicted a result: correct it with what really is.
for pos in [
p.pos,
@@ -579,20 +791,26 @@ impl Game<'_> {
}
// handleUseItem: the client's rotation, then the item alone. What it
// looked at a moment ago (a block, a mob) is UseItemOn's or Interact's.
self.as_guest(host, conn, |g| {
let swung = self.as_guest(host, conn, |g| {
(g.yaw, g.pitch) = (p.yaw, p.pitch);
g.lan_item_only = true;
let swings = g.swings_started;
let _ = g.use_item();
g.lan_item_only = false;
g.swings_started != swings
});
self.lan_swing_back(host, conn, swung);
}
S::Attack(p) => self.guest_attack(host, conn, p.id),
S::Interact(p) => {
if let Some((position, eye)) = self.look_at_entity(host, gi, p.id) {
let _ = (position, eye);
self.as_guest(host, conn, |g| {
let swung = self.as_guest(host, conn, |g| {
let swings = g.swings_started;
let _ = g.use_item();
g.swings_started != swings
});
self.lan_swing_back(host, conn, swung);
}
}
S::SetCreativeModeSlot(p) => {
@@ -606,7 +824,7 @@ impl Game<'_> {
S::ContainerClick(p) if self.lan_merchant_click(host, conn, &p) => {}
S::ContainerClick(p) if self.lan_inventory_click(host, conn, &p) => {}
S::ContainerClick(p) if self.lan_crafting_click(host, conn, &p) => {}
S::ContainerClick(p) if self.lan_furnace_click(host, conn, &p) => {}
S::ContainerClick(p) if self.lan_machine_click(host, conn, &p) => {}
S::SelectTrade(p) => self.lan_select_trade(host, conn, p.item),
S::ContainerClose(p) if self.lan_merchant_closed(host, conn, Some(p.container)) => {
let g = &mut host.hub.guests[gi];
@@ -621,7 +839,7 @@ impl Game<'_> {
}
}
S::ContainerClick(p) => {
let rules = ItemRules(&self.res.items);
let rules = ItemRules(self.res.items());
let drops = host.hub.container_click(conn, &p, &mut self.world, &rules);
self.drop_guest_items(host, gi, drops);
}
@@ -750,7 +968,7 @@ impl Game<'_> {
}
S::PickItemFromBlock(p) => {
let state = self.world.block(p.pos[0], p.pos[1], p.pos[2]);
let item = self.res.facts.get(state).item.clone();
let item = self.res.facts().get(state).item.clone();
let g = &mut host.hub.guests[gi];
if g.creative() && &*item != "minecraft:air" {
let slot = g.selected;
@@ -884,34 +1102,12 @@ impl Game<'_> {
return;
}
// An integrated server runs every player's commands at their own
// permission level (`CommandSourceStack.permissions`).
if host.hub.config.integrated {
let Some(level) = host.hub.guest(conn).map(|g| g.permission) else {
return;
};
let command = command.trim_start_matches('/').to_owned();
let lines = self.as_guest(host, conn, |g| {
let console = std::mem::replace(&mut g.ui.registries.permission, level);
g.chat_capture = Some(Vec::new());
g.run_command(&command);
g.ui.registries.permission = console;
g.chat_capture.take().unwrap_or_default()
});
for line in lines.unwrap_or_default() {
host.hub.send_to(
conn,
&C::SystemChat(play::SystemChat {
content: horizon_client::lan::data::component_nbt(&line.component()),
overlay: false,
}),
);
}
return;
}
// A LAN world follows its Allow Commands; a dedicated server leaves
// it to the ops list (the guest's permission level).
// permission level (`CommandSourceStack.permissions`); a LAN world
// follows its Allow Commands, and a dedicated server leaves it to
// the ops list (the guest's permission level).
let integrated = host.hub.config.integrated;
let allowed = self.options.dedicated.is_some() || self.allow_commands();
if !host.settings.guest_commands || !allowed {
if !integrated && (!host.settings.guest_commands || !allowed) {
host.hub.send_to(
conn,
&C::SystemChat(play::SystemChat {
@@ -921,34 +1117,62 @@ impl Game<'_> {
);
return;
}
let command = command.trim_start_matches('/').to_owned();
// The guest's own level (Commands.performCommand with the player's source): an
// operator's on a dedicated server, never the host's.
let permission = host.hub.guest(conn).map_or(0, |g| g.permission);
let lines = self.as_guest(host, conn, |g| {
g.chat_capture = Some(Vec::new());
let level = std::mem::replace(&mut g.ui.registries.permission, permission);
g.run_command(&command);
g.ui.registries.permission = level;
g.chat_capture
.take()
.unwrap_or_default()
.iter()
.map(|t| horizon_client::lan::data::component_nbt(&t.component()))
.collect::<Vec<_>>()
// The guest's own level (Commands.performCommand with the player's
// source): an operator's on a dedicated server, never the host's.
let Some(permission) = host.hub.guest(conn).map(|g| g.permission) else {
return;
};
host.commands.push(GuestCommand {
conn,
command: command.trim_start_matches('/').to_owned(),
permission,
integrated,
});
// A teleport into another level happens before its feedback is sent.
self.run_level_teleports(host);
for content in lines.unwrap_or_default() {
host.hub.send_to(
conn,
&C::SystemChat(play::SystemChat {
content,
overlay: false,
}),
);
}
/// The guests' queued commands, run with the hub in `self.lan` so that
/// they reach the other players too (`/give Bob`, `/tp Bob`, `/kick`).
pub(super) fn run_guest_commands(&mut self) {
loop {
let Some(host) = self.lan.as_mut() else {
return;
};
if host.commands.is_empty() {
return;
}
let c = host.commands.remove(0);
let mut host = self.lan.take().expect("checked above");
let Some(swap) = self.enter_guest(&mut host, c.conn) else {
self.lan = Some(host);
continue;
};
self.lan = Some(host);
self.chat_capture = Some(Vec::new());
let level = std::mem::replace(&mut self.ui.registries.permission, c.permission);
self.run_command(&c.command);
self.ui.registries.permission = level;
let lines = self.chat_capture.take().unwrap_or_default();
let mut host = self.lan.take().expect("a command puts the hub back");
self.leave_guest(&mut host, swap);
host.hub.sync_all_effects();
if !c.integrated {
// A teleport into another level happens before its feedback is sent.
self.run_level_teleports(&mut host);
}
for line in lines {
host.hub.send_to(
c.conn,
&C::SystemChat(play::SystemChat {
content: horizon_client::lan::data::component_nbt(&line.component()),
overlay: false,
}),
);
}
if !c.integrated {
self.send_admin_feedback(&mut host, Some(c.conn));
}
self.lan = Some(host);
}
self.send_admin_feedback(host, Some(conn));
}
/// The `broadcastToAdmins` lines a command queued (`source`: the guest
@@ -1072,6 +1296,7 @@ impl Game<'_> {
if let Some(play) = host.play.get_mut(&conn) {
play.potions = Default::default();
}
let clock_rate = self.network_clock_rate();
let ctx = TickCtx {
world: &mut self.world,
host: None,
@@ -1080,11 +1305,7 @@ impl Game<'_> {
spawn,
difficulty: i32::from(self.ui.difficulty),
difficulty_locked: self.level.difficulty_locked,
clock_rate: if self.ui.rules.bool("advance_time") {
self.ui.clock.rate
} else {
0.0
},
clock_rate,
tick_rate: self.clock.rate(),
tick_frozen: self.clock.frozen(),
collision: Some(self.collision),
@@ -1149,6 +1370,7 @@ impl Game<'_> {
self.as_guest(host, conn, |g| {
g.count_tick_stats(sleeping);
g.tick_advancements();
g.update_player_attributes();
});
host.hub.flush_progress(conn);
self.guest_dig_feedback(host, conn);
@@ -1165,7 +1387,34 @@ impl Game<'_> {
total: g.xp_total,
}
.death_reward(self.ui.rules.bool("keep_inventory") || g.game_mode == SPECTATOR);
let message = literal(&format!("{} died", g.name));
let (name, uuid) = (g.name.clone(), g.uuid);
let cause = host.play.get_mut(&conn).and_then(|p| p.death_cause.take());
let message = match cause {
// ServerPlayer.die: the death message, to everyone unless
// the player's team hides it.
Some(key) if self.ui.rules.bool("show_death_messages") => {
let text = horizon_client::text::Text::translate(
&key,
&[self.player_text(&name, uuid)],
);
let message = horizon_client::lan::data::component_nbt(&text.component());
let team = self.score.board.players_team(&name);
if horizon_client::scoreboard::own_death_message_shown(team) {
host.hub.system_message(message.clone());
if self.options.dedicated.is_some() {
super::dedicated::log(
"INFO",
&format!("System chat: {}", text.plain()),
);
} else if self.player.is_some() {
self.system_message(text);
}
}
message
}
Some(_) => literal(""),
None => literal(&format!("{name} died")),
};
host.hub.send_to(
conn,
&C::PlayerCombatKill(play::PlayerCombatKill { id, message }),
@@ -1184,7 +1433,7 @@ impl Game<'_> {
g.sleep_timer = super::tick_sleep_timer(g.sleep_timer, g.bed.is_some());
if let Some(head) = g.bed {
let block = self.world.block(head[0], head[1], head[2]);
let bed = self.res.facts.get(block).name.ends_with("_bed");
let bed = self.res.facts().get(block).name.ends_with("_bed");
if g.dead || g.health <= 0.0 || !bed {
host.hub.wake(gi);
}
@@ -1352,7 +1601,7 @@ impl Game<'_> {
let range = |v: f64| (v - half).floor() as i32..=(v + half).floor() as i32;
range(at[0]).any(|x| {
range(at[2]).any(|z| {
let f = self.res.facts.get(self.world.block(x, y, z));
let f = self.res.facts().get(self.world.block(x, y, z));
f.full_collision && f.solid_render
})
})
@@ -1370,7 +1619,7 @@ impl Game<'_> {
play.mining = None;
let start = play.dig_start;
let state = self.world.block(pos[0], pos[1], pos[2]);
if !dug || self.res.facts.is_air(state) {
if !dug || self.res.facts().is_air(state) {
return;
}
let progress = self
@@ -1394,7 +1643,7 @@ impl Game<'_> {
};
let ticks = host.hub.ticks;
let state = self.world.block(pos[0], pos[1], pos[2]);
let progress = if self.res.facts.is_air(state) {
let progress = if self.res.facts().is_air(state) {
None
} else {
self.as_guest(host, conn, |g| g.destroy_progress(pos))
@@ -1619,23 +1868,72 @@ impl Game<'_> {
}
}
/// Guests' arm swings for everyone else.
/// The guests' items in use, for the players around (`LivingEntity.startUsingItem`
/// and `stopUsingItem` set DATA_LIVING_ENTITY_FLAGS).
pub(super) fn lan_living_flags(&mut self, host: &mut LanHost) {
for g in &mut host.hub.guests {
let using = host.play.get(&g.conn).and_then(GuestPlay::using);
g.living_flags = super::lan::living_flags(using);
}
}
/// A use the server ran swung the guest's hand: their own client is told
/// too (`swing(hand, true)` for a SwingSource.SERVER result). Horizon's
/// client does not run uses itself, so it does not predict the swing; a
/// client that did (a block placed) is still in the first half of its
/// swing and ignores it (`SwingState.startIfAble`).
fn lan_swing_back(&mut self, host: &mut LanHost, conn: u32, swung: Option<bool>) {
if swung != Some(true) {
return;
}
let (Some(g), Some(play)) = (host.hub.guest(conn), host.play.get(&conn)) else {
return;
};
if let Some(c) = play.swing.current {
host.hub
.send_to(conn, &swing_packet(g.entity_id, c.hand, c.animation));
}
}
/// The tick's arm swings for the players around (the guests' to everyone
/// else, the host's to the guests), and `LivingEntity.updateSwingTime`
/// for the guests' bodies here.
pub(super) fn lan_swings(&mut self, host: &mut LanHost) {
let conns: Vec<u32> = host.play.keys().copied().collect();
for conn in conns {
let Some(g) = host.hub.guests.iter().find(|g| g.conn == conn) else {
continue;
};
if !host.hub.here(g) {
continue;
}
let (id, at) = (g.entity_id, g.position);
let (id, at, here) = (g.entity_id, g.position, host.hub.here(g));
let play = host.play.get_mut(&conn).expect("play");
let swinging = play.swing.swinging() && play.swing.ticks == 0;
if swinging && !play.swung {
host.hub.swing(id, 0, at, Some(conn));
let swung = std::mem::take(&mut play.swings) > 0;
if let (true, true, Some(c)) = (swung, here, play.swing.current) {
let packet = swing_packet(id, c.hand, c.animation);
host.hub.broadcast_near(at, 128.0, &packet, Some(conn));
if let Some(m) = host.models.get_mut(&conn) {
m.swing();
}
}
play.swing.tick();
}
if self.swings_started != host.host_swings {
host.host_swings = self.swings_started;
if let (Some(p), Some(c)) = (self.player.as_ref(), self.swing.current) {
let at = [p.position.x, p.position.y, p.position.z];
let packet = swing_packet(host.host_entity, c.hand, c.animation);
host.hub.broadcast_near(at, 128.0, &packet, None);
}
play.swung = swinging;
}
}
}
/// ClientboundSwingAnimationPacket: the hand and the animation (its type and
/// base duration; each client applies the swinger's haste and fatigue).
fn swing_packet(id: i32, hand: Hand, animation: SwingAnimation) -> C {
C::SwingAnimation(play::SwingAnimation {
id,
hand: i32::from(hand == Hand::Off),
kind: i32::from(animation.kind),
duration: animation.duration,
})
}
@@ -0,0 +1,274 @@
//! The attribute instances a server syncs for the living entities it tracks
//! (`ClientboundUpdateAttributesPacket`, lan/attributes.rs): the ones
//! vanilla's `AttributeMap` would have created by then, since only those are
//! sent, never the type's other defaults.
use super::Game;
use super::commands::Target;
use horizon_client::{
effects,
lan::attributes::{add_modifier, generic_syncable, instance, operation_named},
mobs::{
Mob,
finalize::{self, Attr, Op},
},
};
use horizon_protocol::packets::play::{AttributeModifier, AttributeSnapshot};
use std::sync::Arc;
/// `EquipmentSlotGroup.test`: whether a modifier's slot group covers a slot.
fn slot_in_group(group: &str, slot: &str) -> bool {
group == slot
|| group == "any"
|| (group == "hand" && matches!(slot, "mainhand" | "offhand"))
|| (group == "armor" && matches!(slot, "feet" | "legs" | "chest" | "head" | "body"))
}
impl Game<'_> {
/// The registry id of a client-syncable attribute the entity type has
/// (`AttributeMap.getInstance` is null for the others), by name.
fn synced_attribute(&self, entity: &str, name: &str) -> Option<i32> {
let catalog = &self.motion.attributes;
let id = catalog.id(name)?;
(catalog.attribute(id).syncable && catalog.default_base(entity, id).is_some())
.then(|| id.registry_id())
}
/// The type's base value of an attribute, as the instance starts.
fn attribute_default(&self, entity: &str, name: &str) -> f64 {
let catalog = &self.motion.attributes;
catalog
.id(name)
.and_then(|id| catalog.default_base(entity, id))
.unwrap_or(0.0)
}
/// `LivingEntity.collectEquipmentChanges`: each worn or held item's
/// attribute modifiers, slot by slot in `EquipmentSlot` order, create
/// their instances (an instance without a modifier keeps its base).
fn equipment_attributes<'a>(
&self,
entity: &str,
base: impl Fn(&str) -> Option<f64>,
slots: impl IntoIterator<Item = (&'static str, Option<&'a Arc<str>>)>,
out: &mut Vec<AttributeSnapshot>,
) {
for (slot, item) in slots {
let Some(info) = item.and_then(|i| self.res.items().get(i)) else {
continue;
};
for (attribute, id, amount, op, group) in &info.modifiers {
if !slot_in_group(group, slot) {
continue;
}
let Some(a) = self.synced_attribute(entity, attribute) else {
continue;
};
let start =
base(attribute).unwrap_or_else(|| self.attribute_default(entity, attribute));
add_modifier(
out,
a,
start,
AttributeModifier {
id: id.clone(),
amount: *amount,
operation: operation_named(op),
},
);
}
}
}
/// A mob's synced instances: movement speed (its first `aiStep` reads it,
/// `LivingEntity.removeFrost`), what finalizeSpawn set, the baby speed
/// modifier, its effects' modifiers, its equipment's, and what
/// `/attribute` changed.
pub(super) fn mob_attributes(&self, m: &Mob) -> Vec<AttributeSnapshot> {
let kind = m.kind.id.as_str();
let mut out = Vec::new();
if let Some(a) = self.synced_attribute(kind, "minecraft:movement_speed") {
instance(&mut out, a, finalize::base_value(m, Attr::MovementSpeed));
}
if let Some(s) = m.extra.attributes.as_deref() {
for (attr, v) in &s.bases {
if let Some(a) = self.synced_attribute(kind, &format!("minecraft:{}", attr.name()))
{
instance(&mut out, a, *v).base = *v;
}
}
for x in &s.modifiers {
if let Some(a) =
self.synced_attribute(kind, &format!("minecraft:{}", x.attr.name()))
{
add_modifier(
&mut out,
a,
finalize::base_value(m, x.attr),
AttributeModifier {
id: x.id.to_owned(),
amount: x.amount,
operation: match x.op {
Op::AddValue => 0,
Op::AddMultipliedBase => 1,
Op::AddMultipliedTotal => 2,
},
},
);
}
}
}
if let (Some(a), Some((amount, Op::AddMultipliedBase))) = (
self.synced_attribute(kind, "minecraft:movement_speed"),
finalize::transient(m, Attr::MovementSpeed),
) {
add_modifier(
&mut out,
a,
finalize::base_value(m, Attr::MovementSpeed),
AttributeModifier {
id: "minecraft:baby".into(),
amount,
operation: 1,
},
);
}
let base = |name: &str| {
Attr::ALL
.into_iter()
.find(|a| name.strip_prefix("minecraft:") == Some(a.name()))
.map(|a| finalize::base_value(m, a))
};
// LivingEntity.onEffectAdded: MobEffect.addAttributeModifiers.
for &(effect, _, amplifier) in &m.extra.effects {
let Some((attribute, id, amount, op)) =
effects::effect_modifier(effect.trim_start_matches("minecraft:"))
else {
continue;
};
let Some(a) = self.synced_attribute(kind, attribute) else {
continue;
};
let start = base(attribute).unwrap_or_else(|| self.attribute_default(kind, attribute));
add_modifier(
&mut out,
a,
start,
AttributeModifier {
id: id.to_owned(),
amount: amount * f64::from(amplifier + 1),
operation: operation_named(op),
},
);
}
let e = &m.extra;
self.equipment_attributes(
kind,
base,
[
("mainhand", e.main_hand.as_ref()),
("offhand", e.off_hand.as_ref()),
("feet", e.feet.as_ref()),
("legs", e.legs.as_ref()),
("chest", e.chest.as_ref()),
("head", e.head.as_ref()),
],
&mut out,
);
self.generic_attributes_of(Target::Mob(m.id), &mut out);
out
}
/// An armor stand's synced instances: movement speed (its first
/// `aiStep`), its equipment's modifiers and what `/attribute` changed.
pub(super) fn stand_attributes(
&self,
id: u32,
equipment: &[Option<horizon_client::items::ItemStack>; 6],
) -> Vec<AttributeSnapshot> {
const KIND: &str = "minecraft:armor_stand";
let mut out = Vec::new();
if let Some(a) = self.synced_attribute(KIND, "minecraft:movement_speed") {
instance(
&mut out,
a,
self.attribute_default(KIND, "minecraft:movement_speed"),
);
}
let slots = horizon_client::entities::ArmorStand::SLOTS
.into_iter()
.zip(equipment.iter().map(|s| s.as_ref().map(|s| &s.item)));
self.equipment_attributes(KIND, |_| None, slots, &mut out);
self.generic_attributes_of(Target::Stand(id), &mut out);
out
}
/// The instances a server player's tick creates, and
/// `ServerPlayer.updatePlayerAttributes`: a creative player reaches 0.5
/// further to blocks and 2 to entities. Its client reads the reach from
/// these synced modifiers. (The crouching player's waypoint range is
/// server-side only: lan_waypoints.rs hides it.)
pub(super) fn update_player_attributes(&mut self) {
let creative = self.mode_id() == 1;
let Some(p) = self.player.as_mut() else {
return;
};
// LivingEntity.aiStep's removeFrost reads the movement speed instance
// every tick, which creates it (and its first sync).
if let Some(key) = p.attributes.key("minecraft:movement_speed") {
let _ = p.attributes.get_instance(Some(key));
}
for (attribute, id, amount) in [
(
"minecraft:block_interaction_range",
"minecraft:creative_mode_block_range",
0.5,
),
(
"minecraft:entity_interaction_range",
"minecraft:creative_mode_entity_range",
2.0,
),
] {
let Some(key) = p.attributes.key(attribute) else {
continue;
};
// getAttribute creates the instance, a creative player's or not.
if !matches!(p.attributes.get_instance(Some(key.clone())), Ok(Some(_))) {
continue;
}
// addOrUpdateTransientModifier with the same modifier and
// removeModifier of a missing one leave the instance clean.
let has = p.attributes.has_modifier(Some(key), id).unwrap_or(false);
if has != creative {
let _ = p.set_modifier(attribute, id, amount, "add_value", creative);
}
}
}
/// The instances `/attribute` created in an entity's generic map
/// replace the ones derived from its state.
fn generic_attributes_of(&self, t: Target, out: &mut Vec<AttributeSnapshot>) {
let Some(map) = self.cmds.attributes.get(&t) else {
return;
};
for s in generic_syncable(map) {
let (attribute, base) = (s.attribute, s.base);
*instance(out, attribute, base) = s;
}
}
}
#[cfg(test)]
mod tests {
use super::slot_in_group;
#[test]
fn slot_groups_cover_their_slots() {
assert!(slot_in_group("head", "head"));
assert!(slot_in_group("armor", "chest"));
assert!(!slot_in_group("armor", "mainhand"));
assert!(slot_in_group("hand", "offhand"));
assert!(slot_in_group("any", "feet"));
assert!(!slot_in_group("mainhand", "offhand"));
}
}
+43 -29
View File
@@ -21,9 +21,10 @@ pub(super) struct GuestCrafting {
inventory: Option<Box<Menu>>,
/// The open crafting table: its window, state id and menu.
table: Option<(i32, i32, Box<Menu>)>,
/// The open furnace's window and menu (`AbstractFurnaceMenu`); its slots live in
/// the furnace block entity and the hub's container menu keeps the client in sync.
furnace: Option<(i32, Box<Menu>)>,
/// The open furnace's or brewing stand's window and menu (`AbstractFurnaceMenu`,
/// `BrewingStandMenu`); its slots live in the block entity and the hub's
/// container menu keeps the client in sync.
machine: Option<(i32, Box<Menu>)>,
}
/// ServerboundContainerClickPacket's input.
@@ -84,10 +85,10 @@ fn place_back(menu: &mut Menu, env: &Env, stacks: Vec<ItemStack>) {
impl Game<'_> {
fn menu_env(&self) -> Env<'_> {
Env {
items: &self.res.items,
recipes: &self.res.recipes,
brewing: &self.res.stations.brewing,
banners: &self.res.stations.banners,
items: self.res.items(),
recipes: self.res.recipes(),
brewing: &self.res.stations().brewing,
banners: &self.res.stations().banners,
trade: None,
}
}
@@ -157,10 +158,11 @@ impl Game<'_> {
true
}
/// A click on the guest's open furnace, blast furnace or smoker: the host's
/// `AbstractFurnaceMenu` (fuel slot, take-only result, quick moves by recipe and
/// fuel) over the block entity's slots. False for other windows.
pub(super) fn lan_furnace_click(
/// A click on the guest's open furnace, blast furnace, smoker or brewing stand:
/// the host's `AbstractFurnaceMenu` (fuel slot, take-only result, quick moves by
/// recipe and fuel) or `BrewingStandMenu` (one bottle per slot, ingredient and
/// blaze powder slots) over the block entity's slots. False for other windows.
pub(super) fn lan_machine_click(
&mut self,
host: &mut LanHost,
conn: u32,
@@ -180,15 +182,18 @@ impl Game<'_> {
else {
return false;
};
let Some(BlockEntity::Furnace(f)) = self.world.block_entities.get(&pos) else {
return false;
let (kind, items) = match self.world.block_entities.get(&pos) {
Some(BlockEntity::Furnace(f)) => {
let recipe = match f.kind.recipe_type() {
"minecraft:blasting" => "blasting",
"minecraft:smoking" => "smoking",
_ => "smelting",
};
(Kind::Furnace(recipe), f.items.to_vec())
}
Some(BlockEntity::Brewing(b)) => (Kind::Brewing, b.items.to_vec()),
_ => return false,
};
let recipe = match f.kind.recipe_type() {
"minecraft:blasting" => "blasting",
"minecraft:smoking" => "smoking",
_ => "smelting",
};
let items = f.items.clone();
if host.hub.guests[gi].spectator() {
return true;
}
@@ -197,10 +202,10 @@ impl Game<'_> {
.entry(conn)
.or_default()
.crafting
.furnace
.machine
.take()
.filter(|(window, _)| *window == p.container)
.map_or_else(|| Box::new(Menu::new(Kind::Furnace(recipe))), |(_, m)| m);
.map_or_else(|| Box::new(Menu::new(kind)), |(_, m)| m);
let changed = self.guest_menu_op(host, gi, &mut menu, |menu, env| {
for (k, s) in items.iter().enumerate() {
menu.set_slot(env, k, s.clone());
@@ -213,14 +218,23 @@ impl Game<'_> {
.filter(|&s| menu.slot(s) != before[s].as_ref())
.collect::<Vec<_>>()
});
if let Some(BlockEntity::Furnace(f)) = self.world.block_entities.get_mut(&pos) {
for k in 0..3 {
f.items[k] = menu.slot(k).cloned();
match self.world.block_entities.get_mut(&pos) {
Some(BlockEntity::Furnace(f)) => {
for k in 0..3 {
f.items[k] = menu.slot(k).cloned();
}
// AbstractFurnaceBlockEntity.setItem: only a new input restarts cooking.
f.input_clicked(self.res.recipes(), items[0].clone());
}
// AbstractFurnaceBlockEntity.setItem: only a new input restarts cooking.
f.input_clicked(&self.res.recipes, items[0].clone());
// BrewingStandBlockEntity.serverTick notices a new ingredient itself.
Some(BlockEntity::Brewing(b)) => {
for k in 0..5 {
b.items[k] = menu.slot(k).cloned();
}
}
_ => {}
}
host.play.entry(conn).or_default().crafting.furnace = Some((p.container, menu));
host.play.entry(conn).or_default().crafting.machine = Some((p.container, menu));
host.hub.inventory_clicked(conn, p, &self.world, &changed);
true
}
@@ -245,7 +259,7 @@ impl Game<'_> {
}
let Some(id) = self
.res
.stations
.stations()
.recipe_index
.recipe_of_display(p.recipe)
.map(str::to_owned)
@@ -256,7 +270,7 @@ impl Game<'_> {
if !g.recipe_book.knows(&id)
|| self
.res
.recipes
.recipes()
.placement(&id)
.is_none_or(|placement| placement.impossible())
{
@@ -37,6 +37,7 @@ fn state(id: u32, kind: &str, position: [f64; 3], yaw: f32, on_ground: bool) ->
data: 0,
meta: Vec::new(),
equipment: Vec::new(),
attributes: Vec::new(),
precise: false,
}
}
@@ -179,6 +180,7 @@ impl Game<'_> {
e.equipment.push((slot as u8, hub.stack(item)));
}
}
e.attributes = self.stand_attributes(a.id, &a.equipment);
out.push(e);
}
for f in &self.item_frames {
@@ -131,6 +131,26 @@ impl Game<'_> {
self.lan = Some(host);
}
/// The guests' boxes for the blocks entities trigger (pressure plates,
/// tripwires, detector rails): `Entity.checkInsideBlocks` and
/// `Level.getEntities` see every player in the level, but not spectators
/// (`Entity.isIgnoringBlockTriggers`).
pub(super) fn lan_block_trigger_boxes(&self) -> Vec<([f64; 3], [f64; 3])> {
let Some(host) = self.lan.as_ref() else {
return Vec::new();
};
host.hub
.guests
.iter()
.filter(|g| host.hub.here(g) && g.loaded && !g.dead && !g.spectator())
.map(|g| {
let [x, y, z] = g.position;
let height = if g.sneaking { 1.5 } else { 1.8 };
([x - 0.3, y, z - 0.3], [x + 0.3, y + height, z + 0.3])
})
.collect()
}
/// The guests a projectile can hit, under their entity ids.
pub(super) fn lan_projectile_targets(&self) -> Vec<(Who, Aabb)> {
let Some(host) = self.lan.as_ref() else {
+9 -8
View File
@@ -596,11 +596,11 @@ impl Game<'_> {
View::Restrictions => self.draw_restrictions(batch),
View::GameRules => {
if let Some(rules) = o.rules.as_mut() {
rules.draw(batch, &self.atlas, self.cursor);
rules.draw(batch, &self.gui.atlas, self.cursor);
} else {
ui::menu_background(
batch,
&self.atlas,
&self.gui.atlas,
0.0,
0.0,
batch.width,
@@ -614,7 +614,7 @@ impl Game<'_> {
}
fn draw_lock_question(&self, o: &WorldOptions, batch: &mut HudBatch) {
let atlas = &self.atlas;
let atlas = &self.gui.atlas;
let (w, h) = (batch.width, batch.height);
// Screen.extractTransparentBackground.
batch.fill_gradient(
@@ -656,7 +656,7 @@ impl Game<'_> {
}
fn draw_restrictions(&self, batch: &mut HudBatch) {
let atlas = &self.atlas;
let atlas = &self.gui.atlas;
let (w, h) = (batch.width, batch.height);
ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true);
let title = Text::translate("restrictions_screen.title", &[]);
@@ -687,7 +687,7 @@ impl Game<'_> {
}
fn draw_options_view(&self, o: &mut WorldOptions, batch: &mut HudBatch, cursor: (f32, f32)) {
let atlas = &self.atlas;
let atlas = &self.gui.atlas;
let (w, h) = (batch.width, batch.height);
o.scroll = o.scroll.clamp(0.0, o.scroll_limit(h));
// extractMenuBackground: the in-world background, the list
@@ -810,7 +810,7 @@ impl Game<'_> {
match o.view {
View::Options => {}
View::GameRules => {
let atlas = &self.atlas;
let atlas = &self.gui.atlas;
let exit = o.rules.as_mut().and_then(|rules| {
if rules.clicks_button(atlas, self.cursor, (w, h)) {
self.audio.play_button_click();
@@ -824,7 +824,7 @@ impl Game<'_> {
return;
}
View::LockQuestion => {
let p = Popup::lock_question(&self.atlas.font, o.difficulty, (w, h));
let p = Popup::lock_question(&self.gui.atlas.font, o.difficulty, (w, h));
let hit = p
.buttons
.iter()
@@ -842,7 +842,8 @@ impl Game<'_> {
return;
}
View::Restrictions => {
let r = Restrictions::new(&self.atlas.font, self.settings.chat_visibility, (w, h));
let r =
Restrictions::new(&self.gui.atlas.font, self.settings.chat_visibility, (w, h));
let in_body = self.cursor.1 >= r.area.0 && self.cursor.1 < r.area.1;
let action = r.action.is_some_and(|(ax, ay)| {
in_body && ui::hovered(self.cursor, ax, ay, 200.0, 20.0)
@@ -133,7 +133,7 @@ impl Game<'_> {
if let Some(name) = &state.name {
return name.clone();
}
let e = &self.res.stations.enchantments;
let e = &self.res.stations().enchantments;
let profession = state.session.profession.trim_start_matches("minecraft:");
if state.session.villager {
e.translate(&format!("entity.minecraft.villager.{profession}"))
@@ -245,15 +245,15 @@ impl Game<'_> {
next_id: std::cell::Cell::new(next_map),
};
let trade_env = merchant::TradeEnv {
trades: &self.res.stations.trades,
enchantments: &self.res.stations.enchantments,
trades: &self.res.stations().trades,
enchantments: &self.res.stations().enchantments,
maps: Some(&maps),
};
let env = Env {
items: &self.res.items,
recipes: &self.res.recipes,
brewing: &self.res.stations.brewing,
banners: &self.res.stations.banners,
items: self.res.items(),
recipes: self.res.recipes(),
brewing: &self.res.stations().brewing,
banners: &self.res.stations().banners,
trade: Some(&trade_env),
};
let mut menu = Menu::new(Kind::Merchant);
+3 -3
View File
@@ -220,11 +220,11 @@ impl Game<'_> {
};
let name = self
.res
.facts
.facts()
.get(self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]));
if !self
.res
.items
.items()
.block_tags
.get("minecraft:fences")
.is_some_and(|s| s.contains(&*name.name))
@@ -283,7 +283,7 @@ impl Game<'_> {
}
/// `LeashFeatureRenderer` for every lead and `LeashKnotRenderer` for the knots.
pub(super) fn leash_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec<Vertex>) {
let atlas = &self.atlas;
let atlas = &self.gui.atlas;
let white = atlas.font.white();
let uv = [
[white.u0, white.v1],
@@ -1,6 +1,7 @@
//! Level events whose client handler (`LevelEventHandler`) spawns particles
//! on a block: dragon egg teleportation (2015), electric sparks (3002),
//! waxing (3003), wax off (3004) and scraping (3005).
//! on a block: dragon egg teleportation (2015), a consumable's teleport
//! (2017), electric sparks (3002), waxing (3003), wax off (3004) and
//! scraping (3005).
use super::Game;
use horizon_client::particles::{self, ParticleOptions, ParticleType};
use horizon_core::position::BlockPos;
@@ -9,7 +10,12 @@ use horizon_world::level::LevelEvent;
impl Game<'_> {
pub(super) fn dragon_egg_particles(&mut self, pos: [i32; 3], data: i32) {
self.particles
.block_teleportation(pos, data, self.settings.particles);
.block_teleportation(pos, data, [16, 8, 16], self.settings.particles);
}
/// Event 2017: `TeleportRandomlyConsumeEffect`'s directional particles.
pub(super) fn consume_teleport_particles(&mut self, pos: [i32; 3], data: i32) {
self.particles
.block_teleportation(pos, data, [127, 127, 127], self.settings.particles);
}
/// `LevelEventHandler.levelEvent` 3002 to 3005, drawing from the client
/// level's random.
+38 -3
View File
@@ -20,10 +20,11 @@ use super::{
};
use horizon_client::{
Result, block_entity_anim::BlockEntityAnims, random_tick_sections::RandomTickSections,
save::SaveDir, streaming::Streaming, tick_chunk_membership::TickChunkMembership, world::World,
save::SaveDir, streaming::Streaming, tick_chunk_membership::TickChunkMembership,
ticket_levels::ChunkTickets, world::World,
};
use horizon_world::level::{LevelEvent, Ticks};
use std::{collections::HashMap, sync::Arc};
use std::{collections::HashMap, sync::Arc, time::Instant};
/// Server ticks a level other than the Overworld stays loaded with no player
/// in it, before it is saved and closed (vanilla unloads a level's chunks
@@ -37,6 +38,7 @@ pub(super) struct Parked {
save: Arc<SaveDir>,
block_ticks: Ticks,
tick_chunks: TickChunkMembership,
tickets: ChunkTickets,
random_tick_sections: RandomTickSections,
level_events: Vec<LevelEvent>,
falling: Vec<FallingBlock>,
@@ -105,7 +107,7 @@ impl Game<'_> {
fn open_level(&self, dim: Dim) -> Result<Parked> {
let (streaming, save) =
self.make_streaming(&self.world_root.clone(), dim, self.level.seed)?;
let mut world = World::new(self.res.facts.air, self.level.seed);
let mut world = World::new(self.res.facts().air, self.level.seed);
world.fast_lava = dim == Dim::Nether;
Ok(Parked {
world,
@@ -113,6 +115,7 @@ impl Game<'_> {
save,
block_ticks: Ticks::new(self.level.seed as i32),
tick_chunks: Default::default(),
tickets: Default::default(),
random_tick_sections: Default::default(),
level_events: Vec::new(),
falling: Vec::new(),
@@ -159,6 +162,7 @@ impl Game<'_> {
swap(&mut self.save, &mut p.save);
swap(&mut self.block_ticks, &mut p.block_ticks);
swap(&mut self.tick_chunks, &mut p.tick_chunks);
swap(&mut self.tickets, &mut p.tickets);
swap(&mut self.random_tick_sections, &mut p.random_tick_sections);
swap(&mut self.level_events, &mut p.level_events);
swap(&mut self.falling, &mut p.falling);
@@ -287,6 +291,37 @@ impl Game<'_> {
self.close_idle_levels()
}
/// `tick_server` as a server thread runs it. With `HORIZON_SPIKES=MS`, a
/// tick longer than MS is logged with its thread CPU time and spans.
pub(super) fn tick_server_timed(&mut self, paused: bool) -> Result<()> {
let Some(threshold) = self.options.spikes else {
return self.tick_server(paused);
};
let (started, cpu) = (Instant::now(), horizon_client::spans::thread_cpu());
let result = self.tick_server(paused);
let wall = started.elapsed().as_secs_f32() * 1000.0;
// Taken every tick: nothing else takes this thread's spans.
let spans = horizon_client::spans::take();
if wall > threshold {
let cpu = horizon_client::spans::thread_cpu()
.zip(cpu)
.map_or_else(String::new, |(end, start)| {
format!(", cpu {:.1} ms", (end - start).as_secs_f32() * 1000.0)
});
let list: Vec<String> = spans
.iter()
.filter(|(_, ms)| *ms >= 0.5)
.map(|(n, ms)| format!("{n} {ms:.1}"))
.collect();
log::info!(
"Horizon: slow tick {wall:.1} ms{cpu} ({} mobs): {}",
self.mobs.len(),
list.join(", ")
);
}
result
}
/// The levels this server tick runs, in `MinecraftServer.levels` order
/// (the Overworld, the Nether, the End): every level with a player in
/// it, or the Overworld while nobody is online.
+11 -7
View File
@@ -24,14 +24,18 @@ pub(super) struct Bolt {
converted: Vec<u32>,
}
impl Game<'_> {
/// One `tickThunder` roll per loaded chunk.
/// `ServerChunkCache.tickSpawningChunk`: one `tickThunder` roll per
/// spawning chunk (within 128 blocks of a player) that is in entity
/// ticking range.
pub(super) fn tick_thunder(&mut self) {
// isRaining (rain level > 0.2) and isThundering (> 0.9, sky light, no ceiling).
let (rain, thunder) = self.world.weather.levels(1.0);
if rain <= 0.2 || thunder <= 0.9 || self.dim != super::Dim::Overworld {
return;
}
let chunks: Vec<(i32, i32)> = self.world.chunks.keys().copied().collect();
let (_, mut chunks) = self.spawning_chunks(&self.level_players());
let levels = self.tickets.levels();
chunks.retain(|&(x, z)| levels.random_ticking(x, z));
for (cx, cz) in chunks {
if self.world.random.next_int_bound(100_000).unwrap_or(1) != 0 {
continue;
@@ -50,7 +54,7 @@ impl Game<'_> {
let difficulty = f64::from(self.ui.difficulty) * 0.75;
let below = &self
.res
.facts
.facts()
.get(self.world.block(pos[0], pos[1] - 1, pos[2]))
.name;
let trap = self.ui.rules.bool("spawn_mobs")
@@ -160,11 +164,11 @@ impl Game<'_> {
}
for p in spots {
let state = self.world.block(p[0], p[1], p[2]);
if !self.res.facts.is_air(state) {
if !self.res.facts().is_air(state) {
continue;
}
// BaseFireBlock.getState: soul fire on soul soil and sand.
let below = self.res.facts.get(self.world.block(p[0], p[1] - 1, p[2]));
let below = self.res.facts().get(self.world.block(p[0], p[1] - 1, p[2]));
let name = if matches!(&*below.name, "minecraft:soul_soil" | "minecraft:soul_sand") {
"minecraft:soul_fire"
} else {
@@ -236,7 +240,7 @@ impl Game<'_> {
at[2].floor() as i32,
];
let state = self.world.block(p[0], p[1], p[2]);
if !self.res.facts.get(state).name.ends_with("lightning_rod") {
if !self.res.facts().get(state).name.ends_with("lightning_rod") {
return;
}
let registry = self.pack.assets.registry;
@@ -348,7 +352,7 @@ impl Game<'_> {
/// `LightningBoltRenderer`: 4 layers of a trunk and two branches, 8
/// segments of 16 blocks, from the bolt's seed.
pub(super) fn bolt_geometry(&self, camera: glam::DVec3, out: &mut Vec<Vertex>) {
let white = self.atlas.font.white();
let white = self.gui.atlas.font.white();
let uv = [white.u0, white.v0];
// ARGB 0.45, 0.45, 0.5 at 0.3 alpha, packed RGBA.
let color = (76u32 << 24) | (127 << 16) | (114 << 8) | 114;
+5 -5
View File
@@ -192,14 +192,14 @@ impl Game<'_> {
base: &str,
layers: &[BannerLayer],
) {
let banners = &self.res.stations.banners;
let banners = &self.res.stations().banners;
let layers: Vec<(String, String)> = layers
.iter()
.map(|l| (banners.banner_texture(&l.pattern), l.color.to_string()))
.collect();
horizon_client::item_render::gui::draw_banner_result(
&self.pack.item_renderer,
&self.atlas.sprites,
&self.gui.atlas.sprites,
batch,
x,
y,
@@ -217,7 +217,7 @@ impl Game<'_> {
draws: &[ScreenDraw],
background: bool,
) -> Option<Vec<(String, u32)>> {
let atlas = &self.atlas;
let atlas = &self.gui.atlas;
let mut tooltip = None;
let mut sheet: Option<String> = None;
for d in draws {
@@ -317,7 +317,7 @@ impl Game<'_> {
let l = &s.loom;
let dye = s.inputs[1]
.as_ref()
.and_then(|d| self.res.items.get(&d.item))
.and_then(|d| self.res.items().get(&d.item))
.and_then(|i| i.dye.clone())
.unwrap_or_else(|| "white".to_owned());
let result = s
@@ -342,7 +342,7 @@ impl Game<'_> {
dye: &dye,
mouse: local,
};
let draws = screen_layout::loom(&view, &self.res.stations.banners);
let draws = screen_layout::loom(&view, &self.res.stations().banners);
self.paint_screen(batch, ox, oy, &draws, false)
}
}
+5 -5
View File
@@ -84,11 +84,11 @@ impl Game<'_> {
direct_attacker: Some("minecraft:player"),
is_direct: true,
damage_type: Some("minecraft:mace_smash"),
items: Some(&self.res.items),
items: Some(self.res.items()),
..Default::default()
};
// EnchantmentHelper.modifyFallBasedDamage(..., 0)
let per_block = self.res.stations.enchantments.modify_value(
let per_block = self.res.stations().enchantments.modify_value(
held.as_ref(),
"minecraft:smash_damage_per_fallen_block",
&ctx,
@@ -111,10 +111,10 @@ impl Game<'_> {
horizon_client::mobs::DamageKind::MaceSmash => "minecraft:mace_smash",
_ => "minecraft:player_attack",
}),
items: Some(&self.res.items),
items: Some(self.res.items()),
..Default::default()
};
let enchantments = &self.res.stations.enchantments;
let enchantments = &self.res.stations().enchantments;
let random = &mut self.world.random;
// CombatRules.getDamageAfterAbsorb: EnchantmentHelper.modifyArmorEffectiveness.
let mut breach = |fraction: f32| {
@@ -143,7 +143,7 @@ impl Game<'_> {
};
let weapon = self
.res
.items
.items()
.get(&stack.item)
.and_then(|i| i.weapon_damage.map(|d| (d, i.max_damage)));
let smash = self.smash_attack();
+21 -11
View File
@@ -361,10 +361,10 @@ impl Game<'_> {
fn containers(&self) -> Containers<'_> {
Containers {
world: &self.world,
behaviours: &self.res.behaviours,
items: &self.res.items,
behaviours: self.res.behaviours(),
items: self.res.items(),
registry: self.pack.assets.registry,
brewing: Some(&self.res.stations.brewing),
brewing: Some(&self.res.stations().brewing),
bone_meal: bone_meal(),
}
}
@@ -502,7 +502,7 @@ impl Game<'_> {
pub(super) fn tick_hopper(&mut self, pos: Pos) {
let hopper = self
.res
.facts
.facts()
.get(self.world.block(pos.0, pos.1, pos.2))
.name
.as_ref()
@@ -626,12 +626,12 @@ impl Game<'_> {
return false;
}
let above_state = self.world.block(above.0, above.1, above.2);
let blocked = self.res.facts.get(above_state).full_collision
let blocked = self.res.facts().get(above_state).full_collision
&& !self
.res
.behaviours
.behaviours()
.tag("minecraft:does_not_block_hoppers")
.is_some_and(|t| t.contains(self.res.behaviours.block(above_state)));
.is_some_and(|t| t.contains(self.res.behaviours().block(above_state)));
if blocked {
return false;
}
@@ -678,7 +678,7 @@ impl Game<'_> {
/// `DispenserBlock.dispenseFrom` / `DropperBlock.dispenseFrom`.
pub(super) fn dispense_from(&mut self, pos: BlockPos, state: BlockStateId) -> Result<()> {
let key = (pos.x, pos.y, pos.z);
let name = self.res.facts.get(state).name.clone();
let name = self.res.facts().get(state).name.clone();
if &*name == "minecraft:crafter" {
return self.crafter_dispense(pos, state);
}
@@ -770,12 +770,20 @@ enum Screen {
impl Game<'_> {
fn machine_screen(&self) -> Option<Screen> {
let key = self.container?;
// A server's menu shows by its type, whatever block (or minecart) holds it.
if let Some(menu) = self.remote_menu_type() {
return match menu {
"minecraft:hopper" => Some(Screen::Hopper),
"minecraft:generic_3x3" => Some(Screen::Dispenser),
_ => None,
};
}
if key.1 == super::minecarts::CART_KEY_Y {
return (self.open_cart_kind() == Some(super::minecarts::CartKind::Hopper))
.then_some(Screen::Hopper);
}
let state = self.world.block(key.0, key.1, key.2);
match &*self.res.facts.get(state).name {
match &*self.res.facts().get(state).name {
"minecraft:hopper" => Some(Screen::Hopper),
"minecraft:dispenser" => Some(Screen::Dispenser),
"minecraft:dropper" => Some(Screen::Dropper),
@@ -832,7 +840,7 @@ impl Game<'_> {
let Some(screen) = self.machine_screen() else {
return false;
};
let atlas = &self.atlas;
let atlas = &self.gui.atlas;
let key_is_cart = self
.container
.is_some_and(|k| k.1 == super::minecarts::CART_KEY_Y);
@@ -852,7 +860,9 @@ impl Game<'_> {
batch.rect_uv(ox, oy, 176.0, height, r, u32::MAX);
}
let grey = horizon_client::hud::rgba(64, 64, 64, 255);
let title = &self.container_title(title.to_owned());
let title = &self
.remote_menu_title()
.unwrap_or_else(|| self.container_title(title.to_owned()));
let title_x = if screen == Screen::Hopper {
8.0
} else {
@@ -94,7 +94,7 @@ impl Game<'_> {
// RecipeCache.get: the first crafting recipe that matches, assembled.
let found = self
.res
.recipes
.recipes()
.find(&grid, 3)
.map(|(name, result)| (name.to_owned(), result))
.filter(|(_, result)| result.count > 0);
@@ -120,7 +120,7 @@ impl Game<'_> {
horizon_world::level::flags::UPDATE_CLIENTS,
);
// The remainders come from the grid as it was before anything moved.
let remainders = self.res.recipes.remainders(&recipe, &grid, 3);
let remainders = self.res.recipes().remainders(&recipe, &grid, 3);
self.crafter_eject(key, facing, result, &recipe);
for rest in remainders.into_iter().flatten() {
self.crafter_eject(key, facing, rest, &recipe);
@@ -202,7 +202,7 @@ impl Game<'_> {
pub(in crate::game) fn crafter_result(&self) -> Option<ItemStack> {
let key = self.container?;
let c = self.crafter_at(key)?;
self.res.recipes.craft(&c.items, 3)
self.res.recipes().craft(&c.items, 3)
}
fn crafter_open(&self) -> bool {
matches!(self.container_kind(), Some(BlockEntity::Crafter(_)))
@@ -243,7 +243,7 @@ impl Game<'_> {
// The background goes first, then the labels, then the slot decorations.
let (background, rest) = draws.split_at(2.min(draws.len()));
self.paint_screen(batch, ox, oy, background, true);
let atlas = &self.atlas;
let atlas = &self.gui.atlas;
let grey = rgba(64, 64, 64, 255);
let title = self.container_title(self.translate("container.crafter", "Crafter"));
let tw = HudBatch::text_width(atlas, &title);
+8 -6
View File
@@ -673,17 +673,18 @@ impl Game<'_> {
} else {
loop {
y -= 1;
color = self.res.facts.get(self.world.block(x, y, z)).map_color;
color =
self.res.facts().get(self.world.block(x, y, z)).map_color;
if color != 0 || y <= min_y {
break;
}
}
let f = self.res.facts.get(self.world.block(x, y, z));
let f = self.res.facts().get(self.world.block(x, y, z));
if y > min_y && f.fluid != Fluid::None {
let mut solid = y - 1;
loop {
let below =
self.res.facts.get(self.world.block(x, solid, z));
self.res.facts().get(self.world.block(x, solid, z));
solid -= 1;
water_depth += 1;
if solid <= min_y || below.fluid == Fluid::None {
@@ -789,6 +790,7 @@ impl Game<'_> {
}
let slot = self.maps.slots.last()?.1;
let rect = self
.gui
.atlas
.sprites
.get(&format!("horizon/map{slot}"))
@@ -797,7 +799,7 @@ impl Game<'_> {
if m.texture_dirty {
m.texture_dirty = false;
let rgba: Vec<u8> = m.colors.iter().flat_map(|&c| packed_rgba(c)).collect();
let (w, h) = (self.atlas.width as f32, self.atlas.height as f32);
let (w, h) = (self.gui.atlas.width as f32, self.gui.atlas.height as f32);
self.map_patches.push(horizon_client::font::Patch {
x: (rect.u0 * w).round() as u32,
y: (rect.v0 * h).round() as u32,
@@ -855,7 +857,7 @@ impl Game<'_> {
.map(|m| m.decorations.clone())
.unwrap_or_default();
for (i, d) in decorations.iter().enumerate() {
let Some(s) = self.atlas.sprites.get(d.sprite).copied() else {
let Some(s) = self.gui.atlas.sprites.get(d.sprite).copied() else {
continue;
};
let dm = glam::Mat4::from_translation(glam::Vec3::new(
@@ -931,7 +933,7 @@ impl Game<'_> {
} else {
"map/map_background"
};
if let Some(r) = self.atlas.sprites.get(background).copied() {
if let Some(r) = self.gui.atlas.sprites.get(background).copied() {
for (c, uv) in [
([-7.0, 135.0, 0.0], [r.u0, r.v1]),
([135.0, 135.0, 0.0], [r.u1, r.v1]),
+16 -12
View File
@@ -218,7 +218,7 @@ impl CartModels {
impl Game<'_> {
pub(super) fn rail(&self, x: i32, y: i32, z: i32) -> Option<Rail> {
let state = self.world.block(x, y, z);
let name = self.res.facts.get(state).name.clone();
let name = self.res.facts().get(state).name.clone();
if !matches!(
&*name,
"minecraft:rail"
@@ -247,11 +247,14 @@ impl Game<'_> {
}
}
fn conductor(&self, x: i32, y: i32, z: i32) -> bool {
self.res.facts.get(self.world.block(x, y, z)).full_collision
self.res
.facts()
.get(self.world.block(x, y, z))
.full_collision
}
fn cart_in_water(&self, c: &Minecart) -> bool {
let p = c.position;
let f = self.res.facts.get(self.world.block(
let f = self.res.facts().get(self.world.block(
p.x.floor() as i32,
(p.y + 0.1).floor() as i32,
p.z.floor() as i32,
@@ -661,7 +664,7 @@ impl Game<'_> {
stack.count = 0;
}
Some(s) if s.same_item_same_components(&stack) => {
let max = self.res.items.get(&s.item).map_or(64, |i| i.max_stack);
let max = self.res.items().get(&s.item).map_or(64, |i| i.max_stack);
let moved = stack.count.min(max.saturating_sub(s.count));
s.count += moved;
stack.count -= moved;
@@ -889,9 +892,9 @@ impl Game<'_> {
(-1, 1),
] {
let (x, y, z) = (bx + dx, by + dy, bz + dz);
let below = self.res.facts.get(self.world.block(x, y - 1, z));
let here = self.res.facts.get(self.world.block(x, y, z));
let head = self.res.facts.get(self.world.block(x, y + 1, z));
let below = self.res.facts().get(self.world.block(x, y - 1, z));
let here = self.res.facts().get(self.world.block(x, y, z));
let head = self.res.facts().get(self.world.block(x, y + 1, z));
if (below.full_collision || below.legacy_solid)
&& !here.full_collision
&& !head.full_collision
@@ -1156,7 +1159,7 @@ impl Game<'_> {
diffuse: bool,
out: &mut Vec<Vertex>,
) {
let Ok(models) = self.pack.assets.model_catalog.collect_seeded(state, seed) else {
let Ok(models) = self.pack.render.model_catalog.collect_seeded(state, seed) else {
return;
};
for (_, model) in &models {
@@ -1165,7 +1168,7 @@ impl Game<'_> {
.pack
.layer_names
.get(&face.layer)
.and_then(|n| self.atlas.sprites.get(n))
.and_then(|n| self.gui.atlas.sprites.get(n))
else {
continue;
};
@@ -1239,6 +1242,7 @@ impl Game<'_> {
pub(super) fn cart_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec<Vertex>) {
let a = alpha as f32;
let Some(uv) = self
.gui
.atlas
.sprites
.get("entity/minecart/minecart")
@@ -1382,15 +1386,15 @@ impl Game<'_> {
game_time: self.world.game_time,
max_y: self.dim.max_y(),
world: &self.world,
sprites: &self.atlas.sprites,
sprites: &self.gui.atlas.sprites,
nether: self.dim == super::Dim::Nether,
lid: &lid,
sign: &|_| None,
banner: &|_| Vec::new(),
glyph: &|c| self.atlas.glyph_cell(c),
glyph: &|c| self.gui.atlas.glyph_cell(c),
};
self.res
.block_entity_render
.block_entity_render()
.render_state(&scene, state.0, m, light, out);
}
}
+6 -6
View File
@@ -75,10 +75,10 @@ impl Game<'_> {
if left <= 0 {
return;
}
let Some(kind) = self.res.mob_types.get("minecraft:elder_guardian") else {
let Some(kind) = self.res.mob_types().get("minecraft:elder_guardian") else {
return;
};
let Some(r) = self.atlas.sprites.get("entity/guardian_elder").copied() else {
let Some(r) = self.gui.atlas.sprites.get("entity/guardian_elder").copied() else {
return;
};
let age = (APPARITION_TICKS - left) as f32 + alpha as f32;
@@ -142,12 +142,12 @@ impl Game<'_> {
return;
};
let Some(head) =
render::part_transform(mob, alpha as f32, camera, &self.res.mob_data, "head")
render::part_transform(mob, alpha as f32, camera, self.res.mob_data(), "head")
else {
return;
};
let m = banner_matrix(head);
let atlas = &self.atlas;
let atlas = &self.gui.atlas;
let uv = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]);
// BannerRenderer: the flag sways with a per-banner phase.
let phase =
@@ -187,7 +187,7 @@ impl Game<'_> {
) {
for (corners, shade, side) in FACES {
let name = cube.sprites[usize::from(side)];
let Some(r) = self.atlas.sprites.get(name).copied() else {
let Some(r) = self.gui.atlas.sprites.get(name).copied() else {
continue;
};
let tint = if side == 0 { cube.tint } else { 0xFF_FFFF };
@@ -261,7 +261,7 @@ impl Game<'_> {
let Some(item) = item else { continue };
let left = off_hand != mob.extra.main_hand_left;
let Some(t) =
render::held_item_transform(mob, alpha as f32, camera, &self.res.mob_data, left)
render::held_item_transform(mob, alpha as f32, camera, self.res.mob_data(), left)
else {
continue;
};
+2 -2
View File
@@ -91,9 +91,9 @@ impl Game<'_> {
let cost = random
.next_int_between_inclusive(MIN_COST, top)
.unwrap_or(MIN_COST);
let e = &self.res.stations.enchantments;
let e = &self.res.stations().enchantments;
let pool = e.tag("minecraft:on_mob_spawn_equipment");
let picked = e.select(&self.res.items, random, item, cost, pool);
let picked = e.select(self.res.items(), random, item, cost, pool);
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) {
for (enchantment, level) in picked {
gear::upgrade(m, slot, &enchantment, level);
+2 -2
View File
@@ -284,7 +284,7 @@ impl Game<'_> {
let focused = self.screen == Screen::Chat;
self.ui
.chat
.add(&self.atlas, line, None, self.ticks, focused);
.add(&self.gui.atlas, line, None, self.ticks, focused);
}
}
/// The mods' HUD panels, stacked with the extras in their corners.
@@ -305,7 +305,7 @@ impl Game<'_> {
.iter()
.map(|l| (l.text.as_str(), l.color))
.collect();
extras_hud::draw_lines(batch, &self.atlas, corners, corner, &lines);
extras_hud::draw_lines(batch, &self.gui.atlas, corners, corner, &lines);
}
}
}
+3 -3
View File
@@ -283,7 +283,7 @@ impl Game<'_> {
let Some(open) = self.mount_menu.open.as_ref() else {
return;
};
let atlas = &self.atlas;
let atlas = &self.gui.atlas;
batch.sprite_region(
atlas,
"gui/container/horse",
@@ -376,7 +376,7 @@ impl Game<'_> {
m.hurt_time = 0;
m.death_time = 0;
let camera = glam::DVec3::new(m.position.x, m.position.y, m.position.z);
let atlas = &self.atlas;
let atlas = &self.gui.atlas;
let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]);
let mut verts = Vec::new();
horizon_client::mobs::render::render_with(
@@ -385,7 +385,7 @@ impl Game<'_> {
camera,
&lookup,
240 | 240 << 8,
&self.res.mob_data,
self.res.mob_data(),
&[],
&mut verts,
);
+7 -3
View File
@@ -90,7 +90,11 @@ impl Game<'_> {
&& let Some(stack) = self.inventory[self.selected].as_mut()
{
stack.damage += wear;
let max = self.res.items.get(&stack.item).map_or(25, |i| i.max_damage);
let max = self
.res
.items()
.get(&stack.item)
.map_or(25, |i| i.max_damage);
if stack.damage >= max {
self.inventory[self.selected] = Some(ItemStack::new("minecraft:fishing_rod", 1));
}
@@ -406,7 +410,7 @@ impl Game<'_> {
.find(|c| {
let f = |dy: i32| {
self.res
.facts
.facts()
.get(self.world.block(
c.x.floor() as i32,
c.y.floor() as i32 + dy,
@@ -457,7 +461,7 @@ impl Game<'_> {
return (0, false);
};
let m = &self.mobs[i];
let atlas = &self.atlas;
let atlas = &self.gui.atlas;
let hearts = horizon_client::hud_layout::vehicle_max_hearts(m.attrs.max_health);
let draws = horizon_client::hud_layout::vehicle_health(w, h, hearts, m.health);
horizon_client::hud_layout::paint(batch, atlas, &draws);
+6 -6
View File
@@ -50,7 +50,7 @@ impl Game<'_> {
let (background, probe_volume) = match eye {
Some(eye) => {
let (dimension, biome) = (self.dim.id(), self.biome_at(eye));
let tables = &self.res.music;
let tables = self.res.music();
(
tables.background(dimension, biome),
tables.volume(dimension, biome),
@@ -81,7 +81,7 @@ impl Game<'_> {
.chunks
.get(&(x >> 4, z >> 4))
.map_or("minecraft:plains", |c| {
self.res.biomes.list[c.biome(x, y, z) as usize]
self.res.biomes().list[c.biome(x, y, z) as usize]
.name
.as_str()
})
@@ -89,11 +89,11 @@ impl Game<'_> {
/// `isEyeInFluid(WATER)`: the eye inside the water of its block column.
fn eye_in_water(&self, x: f64, eye_y: f64, z: f64) -> bool {
let (bx, by, bz) = (x.floor() as i32, eye_y.floor() as i32, z.floor() as i32);
let f = self.res.facts.get(self.world.block(bx, by, bz));
let f = self.res.facts().get(self.world.block(bx, by, bz));
if f.fluid != Fluid::Water {
return false;
}
let above = self.res.facts.get(self.world.block(bx, by + 1, bz));
let above = self.res.facts().get(self.world.block(bx, by + 1, bz));
let height = if above.fluid == Fluid::Water {
1.0
} else {
@@ -111,7 +111,7 @@ impl Game<'_> {
};
let feet = [p.position.x, p.position.y, p.position.z];
let eye_y = feet[1] + f64::from(p.dimensions.eye_height);
let sounds = self.res.ambient.get(self.dim.id(), self.biome_at(feet));
let sounds = self.res.ambient().get(self.dim.id(), self.biome_at(feet));
let underwater = self.eye_in_water(feet[0], eye_y, feet[2]);
let world = &self.world;
let light = |b: [i32; 3]| {
@@ -123,7 +123,7 @@ impl Game<'_> {
f64::from(p.dimensions.height),
);
let registry = &self.pack.assets.registry;
let facts = &self.res.facts;
let facts = self.res.facts();
let bubble_column = horizon_client::ambience::bubble_column_in(
[
feet[0] - half,
+3 -3
View File
@@ -218,7 +218,7 @@ impl Game<'_> {
let forward = glam::DVec3::from_array(view_vector(self.yaw, self.pitch));
let right = forward.cross(glam::DVec3::Y).normalize_or_zero();
let up = right.cross(forward).normalize_or_zero();
let white = self.atlas.font.white();
let white = self.gui.atlas.font.white();
let away = forward.as_vec3() * 0.002;
for (text, lift) in lines {
let o = (o + glam::DVec3::new(0.0, *lift, 0.0)).as_vec3();
@@ -240,7 +240,7 @@ impl Game<'_> {
.collect();
let width: f32 = chars
.iter()
.map(|(c, _)| self.atlas.glyph(*c).map_or(6.0, |g| g.1))
.map(|(c, _)| self.gui.atlas.glyph(*c).map_or(6.0, |g| g.1))
.sum();
let x0 = -(width / 2.0).trunc();
let y0 = if text.plain() == "deadmau5" {
@@ -278,7 +278,7 @@ impl Game<'_> {
}
let mut x = x0;
for (ch, color) in chars {
let Some((g, advance)) = self.atlas.glyph(ch) else {
let Some((g, advance)) = self.gui.atlas.glyph(ch) else {
x += 6.0;
continue;
};
@@ -23,10 +23,54 @@ use horizon_core::{
use horizon_world::registry::BlockStateId;
use std::collections::HashMap;
/// A player in the level in place, as spawning and despawning see it.
pub(super) struct LevelPlayer {
pub(super) position: Vec3,
pub(super) bounds: Aabb,
pub(super) alive: bool,
pub(super) creative: bool,
pub(super) spectator: bool,
}
impl LevelPlayer {
fn distance_sqr(&self, x: f64, y: f64, z: f64) -> f64 {
(self.position.x - x).powi(2)
+ (self.position.y - y).powi(2)
+ (self.position.z - z).powi(2)
}
}
/// `ChunkMap.euclideanDistanceSquared` below 128 blocks
/// (`playerIsCloseEnoughForSpawning`).
fn close_enough_for_spawning(p: &LevelPlayer, (cx, cz): (i32, i32)) -> bool {
let (x, z) = (
f64::from(cx * 16 + 8) - p.position.x,
f64::from(cz * 16 + 8) - p.position.z,
);
!p.spectator && x * x + z * z < 16384.0
}
/// `EntityGetter.getNearestPlayer(x, y, z, -1, false)`: the nearest
/// non-spectator, alive or not.
pub(super) fn nearest_player(
players: &[LevelPlayer],
x: f64,
y: f64,
z: f64,
) -> Option<&LevelPlayer> {
let mut best: Option<(&LevelPlayer, f64)> = None;
for p in players.iter().filter(|p| !p.spectator) {
let d = p.distance_sqr(x, y, z);
if best.is_none_or(|(_, b)| d < b) {
best = Some((p, d));
}
}
best.map(|(p, _)| p)
}
/// The game level as natural spawning reads it.
pub(super) struct GameLevel<'g, 'a> {
pub(super) game: &'g Game<'a>,
pub(super) w: MobWorld<'g>,
/// Every player in the level ([`Game::level_players`]).
pub(super) players: Vec<LevelPlayer>,
/// Boxes of the mobs this pass created, not yet in the game's list.
pub(super) pending: std::cell::RefCell<Vec<Aabb>>,
/// The types and boxes of what a spawner created this tick.
@@ -35,7 +79,7 @@ pub(super) struct GameLevel<'g, 'a> {
impl GameLevel<'_, '_> {
fn biome(&self, x: i32, y: i32, z: i32) -> Option<&BiomeInfo> {
let chunk = self.game.world.chunks.get(&(x >> 4, z >> 4))?;
Some(self.game.res.biomes.get(chunk.biome(x, y, z)))
Some(self.game.res.biomes().get(chunk.biome(x, y, z)))
}
}
impl SpawnLevel for GameLevel<'_, '_> {
@@ -84,8 +128,11 @@ impl SpawnLevel for GameLevel<'_, '_> {
fn world_seed(&self) -> i64 {
self.w.world_seed
}
/// `getNearestPlayer(x, y, z, distance, true)`, over every player.
fn player_near(&self, x: f64, y: f64, z: f64, distance: f64) -> bool {
self.w.player_near(x, y, z, distance)
self.players.iter().any(|p| {
p.alive && !p.creative && !p.spectator && p.distance_sqr(x, y, z) < distance * distance
})
}
}
impl NaturalLevel for GameLevel<'_, '_> {
@@ -106,7 +153,7 @@ impl NaturalLevel for GameLevel<'_, '_> {
self.game.dim == Dim::Nether
}
fn mob_type(&self, entity: &str) -> Option<(Species, f32, f32, Category)> {
let t = self.game.res.mob_types.get(entity)?;
let t = self.game.res.mob_types().get(entity)?;
Some((
t.species,
t.width as f32,
@@ -138,12 +185,7 @@ impl NaturalLevel for GameLevel<'_, '_> {
StructureSpawns::shared(&self.game.options.resources)
}
fn nearest_player_distance_sqr(&self, x: f64, y: f64, z: f64) -> Option<f64> {
let p = self.game.player.as_ref()?;
if self.game.spectator() {
return None;
}
let d = [p.position.x - x, p.position.y - y, p.position.z - z];
Some(d[0] * d[0] + d[1] * d[1] + d[2] * d[2])
nearest_player(&self.players, x, y, z).map(|p| p.distance_sqr(x, y, z))
}
fn respawn(&self) -> Option<[i32; 3]> {
// The world spawn point lives in the overworld.
@@ -184,9 +226,9 @@ impl NaturalLevel for GameLevel<'_, '_> {
}
fn unobstructed(&self, bounds: Aabb) -> bool {
let player = self
.game
.player_view()
.is_some_and(|p| p.alive && !p.spectator && p.bounds.intersects(bounds));
.players
.iter()
.any(|p| p.alive && !p.spectator && p.bounds.intersects(bounds));
!player
&& !self.pending.borrow().iter().any(|b| b.intersects(bounds))
&& !self
@@ -198,10 +240,14 @@ impl NaturalLevel for GameLevel<'_, '_> {
fn spawn_mobs(&self) -> bool {
self.game.ui.rules.bool("spawn_mobs")
}
/// Scanned down the column: sections of air alone are skipped (air counts
/// for no heightmap), and an unloaded column reads as air.
/// WORLD_SURFACE (every spawn attempt's) is the chunk's kept heightmap.
/// The others are scanned down the column: sections of air alone are
/// skipped (air counts for no heightmap). An unloaded column reads as air.
fn heightmap(&self, kind: Heightmap, x: i32, z: i32) -> i32 {
let world = self.w.world;
if kind == Heightmap::WorldSurface {
return self.w.world_surface(x, z);
}
world
.chunks
.get(&(x >> 4, z >> 4))
@@ -217,24 +263,17 @@ impl NaturalLevel for GameLevel<'_, '_> {
}
}
impl horizon_client::mobs::spawner::SpawnerLevel for GameLevel<'_, '_> {
/// `Level.hasNearbyAlivePlayer`, over every player.
fn alive_player_near(&self, x: f64, y: f64, z: f64, range: f64) -> bool {
let Some(p) = self.game.player_view() else {
return false;
};
if !p.alive || p.spectator {
return false;
}
let at = self.game.player.as_ref().map(|p| p.position);
at.is_some_and(|a| {
let d = (a.x - x).powi(2) + (a.y - y).powi(2) + (a.z - z).powi(2);
range < 0.0 || d < range * range
self.players.iter().any(|p| {
p.alive && !p.spectator && (range < 0.0 || p.distance_sqr(x, y, z) < range * range)
})
}
fn spawner_blocks_work(&self) -> bool {
self.game.ui.rules.bool("spawner_blocks_work")
}
fn entity_exists(&self, id: &str) -> bool {
self.game.res.mob_types.contains_key(id) || self.game.entity_type_exists(id)
self.game.res.mob_types().contains_key(id) || self.game.entity_type_exists(id)
}
fn count_entities(&self, id: &str, bounds: Aabb) -> usize {
let mobs = self
@@ -257,6 +296,7 @@ impl<'a> Game<'a> {
GameLevel {
game: self,
w: self.mob_world_base(&[]),
players: self.level_players(),
pending: Default::default(),
pending_ids: Default::default(),
}
@@ -264,7 +304,7 @@ impl<'a> Game<'a> {
/// Creates a mob the spawner accepted, finalized the game's way; the
/// caller adds it with [`Game::add_spawned`].
fn finalize_spawned(&self, r: &SpawnRequest, pending: &mut Vec<Mob>) -> Option<Spawned> {
let kind = self.res.mob_types.get(r.entity)?.clone();
let kind = self.res.mob_types().get(r.entity)?.clone();
let [x, y, z] = r.position;
let mut mob = Mob::new(0, kind, Vec3::new(x, y, z), r.yaw);
let facts = self.biome_facts(x.floor() as i32, y.floor() as i32, z.floor() as i32);
@@ -295,25 +335,82 @@ impl<'a> Game<'a> {
}
}
}
/// Every player in the level in place: the local player, and the LAN
/// guests or server players in it.
pub(super) fn level_players(&self) -> Vec<LevelPlayer> {
let mut players: Vec<LevelPlayer> = self.lan.as_ref().map_or_else(Vec::new, |h| {
h.hub
.guests
.iter()
.filter(|g| h.hub.here(g))
.map(|g| LevelPlayer {
position: Vec3::new(g.position[0], g.position[1], g.position[2]),
bounds: super::lan_mobs::guest_bounds(g),
alive: !g.dead,
creative: g.creative(),
spectator: g.spectator(),
})
.collect()
});
if let Some(p) = self.player_view() {
players.insert(
0,
LevelPlayer {
position: p.position,
bounds: p.bounds,
alive: p.alive,
creative: p.creative,
spectator: p.spectator,
},
);
}
players
}
/// `ChunkMap.collectSpawningChunks`: the natural spawn chunk tracker's
/// chunks (within 8 chunks of a player, `getSpawnCandidateChunks`) that
/// are ticking and within 128 blocks of a non-spectator. Also returns how
/// many chunks the tracker holds (`getNaturalSpawnChunkCount`).
pub(super) fn spawning_chunks(&self, players: &[LevelPlayer]) -> (i32, Vec<(i32, i32)>) {
let mut candidates: Vec<(i32, i32)> = Vec::with_capacity(289 * players.len());
let mut seen = horizon_client::fast_hash::FxHashSet::default();
for p in players {
let (pcx, pcz) = (
p.position.x.floor() as i32 >> 4,
p.position.z.floor() as i32 >> 4,
);
for dx in -8..=8 {
for dz in -8..=8 {
let key = (pcx + dx, pcz + dz);
if seen.insert(key) {
candidates.push(key);
}
}
}
}
let count = candidates.len() as i32;
let levels = self.tickets.levels();
candidates.retain(|&(cx, cz)| {
levels.loaded_ticking(cx, cz)
&& super::ticking_chunk(&self.world, cx, cz)
&& players
.iter()
.any(|p| close_enough_for_spawning(p, (cx, cz)))
});
(count, candidates)
}
/// `ServerChunkCache.tickChunks`: the spawn state over the loaded mobs,
/// the categories under their global caps (creatures every 400 ticks),
/// then `spawnForChunk` in the shuffled chunks within 128 blocks of the
/// player.
/// then `tickSpawningChunk` in the shuffled spawning chunks of every
/// player: inhabited time, then `spawnForChunk`.
pub(super) fn spawn_natural(&mut self) {
let Some(p) = self.player.as_ref().map(|p| p.position) else {
let players = self.level_players();
if players.is_empty() {
return;
};
let (pcx, pcz) = (p.x.floor() as i32 >> 4, p.z.floor() as i32 >> 4);
// ChunkMap.collectSpawningChunks: tracked chunks whose centre is
// within 128 blocks of a non-spectator.
let spectator = self.spectator();
let mut chunks: Vec<(i32, i32)> = (-8..=8)
.flat_map(|dx| (-8..=8).map(move |dz| (pcx + dx, pcz + dz)))
.filter(|&(cx, cz)| {
let (x, z) = (f64::from(cx * 16 + 8) - p.x, f64::from(cz * 16 + 8) - p.z);
!spectator && x * x + z * z < 16384.0 && self.world.chunks.contains_key(&(cx, cz))
})
.collect();
}
let (spawnable, mut chunks) = self.spawning_chunks(&players);
for &key in &chunks {
*self.world.inhabited.entry(key).or_insert(0) += 1;
}
let spawn_mobs = self.ui.rules.bool("spawn_mobs");
let spawn_enemies = self.ui.rules.bool("spawn_monsters");
let mut random = std::mem::replace(&mut self.world.random, LegacyRandom::new(0));
@@ -335,12 +432,14 @@ impl<'a> Game<'a> {
persistent: m.persistent,
})
.collect();
let players = vec![SpawnPlayer {
position: [p.x, p.y, p.z],
spectator,
}];
// A single player's natural spawn chunk tracker covers 17 x 17 chunks.
let mut state = SpawnState::new(&level, 289, players, &counted, |cx, cz| {
let players = players
.iter()
.map(|p| SpawnPlayer {
position: [p.position.x, p.position.y, p.position.z],
spectator: p.spectator,
})
.collect();
let mut state = SpawnState::new(&level, spawnable, players, &counted, |cx, cz| {
self.world.chunks.contains_key(&(cx, cz))
});
let categories = if spawn_mobs {
+2 -2
View File
@@ -11,7 +11,7 @@ use horizon_core::random::RandomSource;
impl Game<'_> {
fn item_tagged(&self, tag: &str, item: &str) -> bool {
self.res
.items
.items()
.item_tags
.get(tag)
.is_some_and(|t| t.contains(item))
@@ -43,7 +43,7 @@ impl Game<'_> {
}
let taming: Vec<String> = self
.res
.items
.items()
.item_tags
.get("minecraft:nautilus_taming_items")
.map(|t| t.iter().cloned().collect())

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