Merge remote-tracking branch 'origin/main' into fix/st-wind-charge

This commit is contained in:
Ludovic Marie
2026-10-23 21:43:45 +02:00
132 changed files with 2269 additions and 1140 deletions
@@ -121,6 +121,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
tick_frozen: false,
tick_steps: (0, 0),
collision: None,
border: &horizon_client::worldborder::WorldBorder::default(),
};
for event in hub.tick(&mut ctx) {
match event {
@@ -78,6 +78,7 @@ fn main() -> Result<()> {
let mut selected = collisions::EntityCollisions {
blocks: scene,
entities: &entities,
border: None,
};
let movement = world_movement::resolve_world_movement(
&mut selected,
+1 -7
View File
@@ -2,7 +2,7 @@
//! `banner_patterns` layers carried by banner items, shields and placed
//! banners, and the loom rules of `LoomMenu` (selectable patterns, the
//! six-layer limit and the result stack).
use crate::{block_entity_render::DYES, item_data, items::ItemStack, items::Items};
use crate::{block_entity_render::DYES, items::ItemStack, items::Items};
use horizon_world::nbt::Tag;
use serde_json::Value;
use std::{collections::HashMap, fs, path::Path, sync::Arc};
@@ -261,12 +261,6 @@ pub fn layers_from_nbt(tag: Option<&Tag>) -> Vec<BannerLayer> {
})
.collect()
}
/// Keeps `item_data` linked: the `StackData` fields the banner code reads.
pub fn set_layers(stack: &mut ItemStack, layers: Vec<BannerLayer>) {
let data: &mut item_data::StackData = stack.data_mut();
data.banner_patterns = layers;
stack.tidy();
}
#[cfg(test)]
mod tests {
@@ -144,9 +144,6 @@ impl BlockEntities {
pub fn set_states(&mut self, states: Vec<Ticking>) {
self.states = states;
}
pub fn take_states(&mut self) -> Vec<Ticking> {
std::mem::take(&mut self.states)
}
pub fn ticking(&self, state: u32) -> Ticking {
self.states.get(state as usize).copied().unwrap_or_default()
}
@@ -382,10 +382,6 @@ impl Shulker {
}
out
}
/// `getProgress(a)`: `Mth.lerp(a, progressOld, progress)`.
pub fn get_progress(&self, a: f32) -> f32 {
self.progress_old + a * (self.progress - self.progress_old)
}
/// `ShulkerBoxBlock.canOpen`: a closed box only opens when its lid has room
/// (`level.noCollision` of the half-block lid box, deflated by 1e-6).
pub fn lid_box(pos: [i32; 3], facing: u8) -> [f64; 6] {
@@ -668,14 +664,6 @@ impl Skull {
self.animating = false;
}
}
/// `getAnimation(a)`.
pub fn get_animation(&self, a: f32) -> f32 {
if self.animating {
self.tick_count as f32 + a
} else {
self.tick_count as f32
}
}
}
/// `DecoratedPotBlockEntity.WobbleStyle`.
@@ -875,13 +875,6 @@ impl BlockEntityRenderer {
visibility: None,
}
}
/// The standing banner's pole-and-bar and flag models (`BannerRenderer.submitSpecial`).
pub fn banner_models(&self) -> Option<(&ModelPart, &ModelPart)> {
Some((
self.models.get("standing_banner")?,
self.models.get("standing_banner_flag")?,
))
}
fn kind(&self, state: u32) -> &Kind {
self.kinds.get(state as usize).unwrap_or(&Kind::None)
}
+1 -1
View File
@@ -46,7 +46,7 @@ impl BossBar {
style: "progress".into(),
value: 0,
max: 100,
visible: false,
visible: true,
player: false,
}
}
-4
View File
@@ -169,10 +169,6 @@ impl TickRateManager {
self.frozen_ticks_to_run -= 1;
}
}
/// `isEntityFrozen` for an entity that is not (and does not carry) a player.
pub fn is_entity_frozen(&self, is_player_or_carries_player: bool) -> bool {
!self.runs_normally() && !is_player_or_carries_player
}
}
/// What `/tick sprint` reports when it ends.
+13 -2
View File
@@ -3,7 +3,7 @@
//! Entity-dependent rules use the defaults for players and the supported mobs.
use crate::{Result, world::World};
use horizon_core::{
geometry::{Aabb, Vec3, VoxelShape},
geometry::{Aabb, Vec3, VoxelShape, border::BorderGeometry},
position::{BlockPos, ChunkPos},
};
use horizon_world::{
@@ -64,6 +64,9 @@ pub struct SceneCollisions<'w, 'r> {
pub struct EntityCollisions<'a, W> {
pub blocks: W,
pub entities: &'a [Aabb],
/// The world border and the moving entity's x and z
/// (`CollisionGetter.borderCollision`); None: the blocks' answer.
pub border: Option<(&'a BorderGeometry, [f64; 2])>,
}
impl<W: BlockCollisionWorld> BlockCollisionWorld for EntityCollisions<'_, W> {
type Error = W::Error;
@@ -114,12 +117,20 @@ impl<W: EntityMovementWorld<Error = io::Error>> EntityMovementWorld for EntityCo
}
Ok(shapes)
}
/// `WorldBorder.isInsideCloseToBorder`: an entity inside the border and
/// near it collides with its walls.
fn movement_border(
&mut self,
entity: EntityIdentity,
bounds: Aabb,
) -> io::Result<Option<VoxelShape>> {
self.blocks.movement_border(entity, bounds)
let Some((border, [x, z])) = self.border else {
return self.blocks.movement_border(entity, bounds);
};
if !border.is_inside_close_to_border(x, z, bounds) {
return Ok(None);
}
border.collision_shape().map(Some).map_err(io::Error::other)
}
}
impl SceneCollisions<'_, '_> {
@@ -812,14 +812,6 @@ pub fn java_parse_int(s: &str) -> Option<i32> {
}
s.parse().ok()
}
/// Long.parseLong.
pub fn java_parse_long(s: &str) -> Option<i64> {
let digits = s.strip_prefix(['-', '+']).unwrap_or(s);
if digits.is_empty() || !digits.chars().all(|c| c.is_ascii_digit()) {
return None;
}
s.parse().ok()
}
/// Double.parseDouble over the characters StringReader reads as a number.
pub fn java_parse_double(s: &str) -> Option<f64> {
let t = s.trim_matches(|c: char| c <= ' ');
@@ -1,7 +1,7 @@
//! ComponentSerialization.CODEC and Style.Serializer.MAP_CODEC decoding of
//! SNBT text components, with the data-fixer-upper error messages
//! (ComponentArgument, StyleArgument and component-valued item data).
use super::codec::{get, no_key, not_list, not_map, snbt};
use super::codec::{get, no_key, not_list, not_map};
use horizon_world::nbt::{Compound, Tag};
/// A DataResult error: its message and whether it carries a partial result.
@@ -362,7 +362,3 @@ pub fn decode_style(t: &Tag) -> Result<(), String> {
_ => Err(not_map(t)),
}
}
#[allow(unused)]
fn _keep(t: &Tag) -> String {
snbt(t)
}
@@ -632,10 +632,6 @@ pub fn parse_predicate(reader: &mut Reader, reg: &Registries) -> CmdResult<ItemI
pub fn suggest_predicate(builder: &mut SuggestionsBuilder, reg: &Registries) {
PREDICATE.with(|g| g.parse_for_suggestions_with(builder, Some(reg)));
}
#[allow(unused)]
fn _unused(t: &Tag) -> String {
snbt(t)
}
#[cfg(test)]
mod tests {
-30
View File
@@ -183,9 +183,6 @@ impl<'a> Reader<'a> {
pub fn read_int(&mut self) -> CmdResult<i32> {
self.number("int")
}
pub fn read_long(&mut self) -> CmdResult<i64> {
self.number("long")
}
pub fn read_double(&mut self) -> CmdResult<f64> {
self.number("double")
}
@@ -222,21 +219,6 @@ impl<'a> Reader<'a> {
}
Err(CommandError::tr_at("parsing.quote.expected.end", &[], self))
}
pub fn read_quoted_string(&mut self) -> CmdResult<String> {
if !self.can_read() {
return Ok(String::new());
}
let next = self.peek();
if next != '"' && next != '\'' {
return Err(CommandError::tr_at(
"parsing.quote.expected.start",
&[],
self,
));
}
self.skip();
self.read_string_until(next)
}
pub fn read_string(&mut self) -> CmdResult<String> {
if !self.can_read() {
return Ok(String::new());
@@ -539,18 +521,6 @@ impl<'a> SuggestionsBuilder<'a> {
}
}
}
/// The same with a tooltip per candidate.
pub fn suggest_matching_tooltip<'b>(
&mut self,
candidates: impl IntoIterator<Item = (&'b str, String)>,
) {
let lower = self.remaining_lower();
for (c, tip) in candidates {
if args::matches_sub_str(&lower, &c.to_lowercase()) {
self.suggest_tooltip(c, tip);
}
}
}
}
/// String.compareToIgnoreCase.
pub fn compare_ignore_case(a: &str, b: &str) -> std::cmp::Ordering {
+1 -5
View File
@@ -1,8 +1,6 @@
//! SnbtGrammar and TagParser: vanilla's packrat SNBT grammar, with its
//! error messages and completion suggestions, producing NBT tags.
use super::packrat::{
Grammar, Reason, Rule, State, Sugg, Term, Value, alt, ch, chs, look, opt, seq,
};
use super::packrat::{Grammar, Reason, State, Sugg, Term, Value, alt, ch, chs, look, opt, seq};
use super::{CmdResult, CommandError, Reader, SuggestionsBuilder};
use horizon_world::nbt::{Compound, JavaString, Tag};
use std::rc::Rc;
@@ -981,5 +979,3 @@ pub fn rule_in<V: super::packrat::Value>(
}
}
}
#[allow(unused)]
fn _rule_kind(_: Rule<SV>) {}
+1 -7
View File
@@ -3,7 +3,7 @@
//! mode keywords are read back from the parsed literals.
use super::{
Dispatcher,
args::{ArgType, GameMode, Resource, integer},
args::{ArgType, Resource, integer},
};
use crate::gamerules::{RULES, Value};
@@ -509,10 +509,6 @@ fn clone_mode(d: &mut Dispatcher, node: usize) {
d.executes(l, "clone");
}
}
/// Game mode names for selector `gamemode=` and the argument.
pub fn game_modes() -> [&'static str; 4] {
GameMode::ALL.map(GameMode::name)
}
/// The shared vanilla tree.
/// Reorder node children as vanilla registers them (Brigadier keeps
/// children in registration order; smart usage lists them that way).
@@ -559,5 +555,3 @@ pub fn release_dispatcher() -> &'static Dispatcher {
static TREE: std::sync::OnceLock<Dispatcher> = std::sync::OnceLock::new();
TREE.get_or_init(|| build_with(false))
}
#[allow(unused)]
const _: (u8, u8) = (ALL, GAMEMASTERS);
-18
View File
@@ -252,24 +252,6 @@ impl BlockEntity {
};
Some(Self::Chest(vec![None; size]))
}
/// The vanilla block entity type id of a container block.
pub fn id_for_block(name: &str) -> Option<&'static str> {
Some(match name {
"minecraft:chest" => "minecraft:chest",
n if n.ends_with("copper_chest") => "minecraft:chest",
"minecraft:trapped_chest" => "minecraft:trapped_chest",
"minecraft:barrel" => "minecraft:barrel",
"minecraft:hopper" => "minecraft:hopper",
"minecraft:dispenser" => "minecraft:dispenser",
"minecraft:dropper" => "minecraft:dropper",
"minecraft:furnace" => "minecraft:furnace",
"minecraft:blast_furnace" => "minecraft:blast_furnace",
"minecraft:smoker" => "minecraft:smoker",
n if n.ends_with("shulker_box") => "minecraft:shulker_box",
"minecraft:crafter" => "minecraft:crafter",
_ => return None,
})
}
pub fn id(&self) -> &'static str {
match self {
Self::Chest(items) => match items.len() {
-6
View File
@@ -17,8 +17,6 @@ use std::{
pub const CAPACITY: usize = 240;
/// `AbstractDebugChart.CHART_HEIGHT`.
pub const CHART_HEIGHT: i32 = 60;
/// `TpsDebugDimensions`: a tick sample's values.
pub const FULL_TICK: usize = 0;
pub const TICK_SERVER_METHOD: usize = 1;
pub const SCHEDULED_TASKS: usize = 2;
pub const IDLE: usize = 3;
@@ -252,10 +250,6 @@ impl Chart {
pub fn width(max_width: i32) -> i32 {
(CAPACITY as i32 + 2).min(max_width)
}
/// `getFullHeight`: the box and the min/avg/max line above it.
pub fn full_height() -> i32 {
CHART_HEIGHT + 9
}
/// `AbstractDebugChart.extractRenderState`.
pub fn draw(
self,
-17
View File
@@ -359,10 +359,6 @@ impl Enchantments {
}
out
}
/// Whether a stack draws the enchantment glint.
pub fn has_glint(&self, stack: &ItemStack) -> bool {
stack.has_any_enchantments() || self.props(&stack.item).is_some_and(|p| p.glint)
}
// ---- Enchanting table (EnchantmentHelper) ----
@@ -514,19 +510,6 @@ impl Enchantments {
.is_some_and(|e| e.effects.get(component).is_some())
})
}
/// The highest level among enchantments on `stack` that have `component`.
pub fn component_level(&self, stack: &ItemStack, component: &str) -> u32 {
stack
.enchantments()
.iter()
.filter(|(id, _)| {
self.get(id)
.is_some_and(|e| e.effects.get(component).is_some())
})
.map(|(_, l)| *l)
.max()
.unwrap_or(0)
}
/// `minecraft:attributes` contributions of `stack`: (attribute, id, amount, operation).
pub fn attributes(&self, stack: &ItemStack) -> Vec<(String, String, f64, String)> {
let mut out = Vec::new();
@@ -289,15 +289,6 @@ impl Default for HandHeights {
}
}
}
/// What `FirstPersonHandsAndItems.tick` decides about a hand's visible item.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct HandChange {
/// The visible item is not the hand's item after the instant replacement
/// (`mainHandItem != nextMainHand`): the hand lowers.
pub changed: bool,
/// The visible item becomes the hand's item this tick.
pub replace: bool,
}
impl HandHeights {
/// `FirstPersonHandsAndItems.tick`'s heights. `changed` says per hand
/// whether the visible item differs from the held one once
+56 -37
View File
@@ -73,6 +73,7 @@ mod lan_crafting;
mod lan_entities;
mod lan_mobs;
mod lan_mount_menu;
mod lan_particles;
mod lan_pvp;
mod lan_screen;
mod lan_stations;
@@ -2609,6 +2610,17 @@ impl Game<'_> {
LevelEvent::LevelEvent { id: 2004, pos, .. } => {
self.spawner_burst([pos.x, pos.y, pos.z])
}
// LevelEventHandler 1505: the growth particles, then the sound.
LevelEvent::LevelEvent {
id: 1505,
pos,
data,
} => {
self.growth_particles(pos, data);
let at = [pos.x, pos.y, pos.z].map(|v| f64::from(v) + 0.5);
self.audio
.play("minecraft:item.bone_meal.use", Some(at), 1.0, 1.0);
}
LevelEvent::LevelEvent {
id: 2015,
pos,
@@ -2652,7 +2664,6 @@ impl Game<'_> {
1030 => Some(("minecraft:block.anvil.use", 1.0)),
1029 => Some(("minecraft:block.anvil.destroy", 1.0)),
1031 => Some(("minecraft:block.anvil.land", 0.3)),
1505 => Some(("minecraft:item.bone_meal.use", 1.0)),
1042 => Some(("minecraft:block.grindstone.use", 1.0)),
1044 => Some(("minecraft:block.smithing_table.use", 1.0)),
// LevelEvent.SOUND_PAGE_TURN (a lectern's page).
@@ -8114,13 +8125,15 @@ impl Game<'_> {
}
Ok(true)
}
/// `BlockTransformer.transformBlock` for a held axe, hoe or shovel.
fn use_block_transformer(
&mut self,
/// What `BlockTransformer.transformBlock` would do with a held axe, hoe
/// or shovel on the block at `pos`, without doing it: the new state, its
/// sound, loot table, the durability it costs and its particle.
pub(super) fn block_transform(
&self,
stack: &ItemStack,
pos: [i32; 3],
face: [i32; 3],
) -> Result<bool> {
) -> Option<(BlockStateId, String, Option<String>, u32, String)> {
use horizon_client::block_transform::Around;
struct Column<'w> {
world: &'w World,
@@ -8140,14 +8153,11 @@ impl Game<'_> {
})
}
}
let Some(id) = self
let id = self
.res
.items()
.get(&stack.item)
.and_then(|i| i.block_transformer.clone())
else {
return Ok(false);
};
.and_then(|i| i.block_transformer.clone())?;
// playerHasBlockingItemUseIntent: a shield in the off hand is raised
// instead, unless sneaking.
let shield = self
@@ -8156,7 +8166,7 @@ impl Game<'_> {
.and_then(|s| self.res.items().get(&s.item))
.is_some_and(|i| i.blocks_attacks.is_some());
if shield && !self.keys.contains(&KeyCode::ShiftLeft) {
return Ok(false);
return None;
}
let face_name = match face {
[0, -1, 0] => "down",
@@ -8167,38 +8177,47 @@ impl Game<'_> {
_ => "east",
};
let registry = self.pack.assets.registry;
let (state, sound, loot, damage, particle) = {
let around = Column {
world: &self.world,
registry,
pos,
};
let Some((_, t, state)) =
self.res
.transformers()
.apply(self.res.items(), registry, &id, face_name, &around)
else {
return Ok(false);
};
(
state,
t.sound.clone(),
t.loot.clone(),
t.damage,
t.particle.clone(),
)
let around = Column {
world: &self.world,
registry,
pos,
};
let Ok(new) = registry.resolve(&state) else {
return Ok(false);
};
self.level_set(pos, new)?;
// BlockTransformer.TransformParticle.send.
match particle.as_str() {
let (_, t, state) =
self.res
.transformers()
.apply(self.res.items(), registry, &id, face_name, &around)?;
let new = registry.resolve(&state).ok()?;
Some((
new,
t.sound.clone(),
t.loot.clone(),
t.damage,
t.particle.clone(),
))
}
/// `BlockTransformer.TransformParticle.send`: its level event.
pub(super) fn transform_particle(&mut self, particle: &str, pos: [i32; 3]) {
match particle {
"scrape" => self.level_event_at(3005, pos, 0),
"wax_on" => self.level_event_at(3003, pos, 0),
"wax_off" => self.level_event_at(3004, pos, 0),
_ => {}
}
}
/// `BlockTransformer.transformBlock` for a held axe, hoe or shovel.
fn use_block_transformer(
&mut self,
stack: &ItemStack,
pos: [i32; 3],
face: [i32; 3],
) -> Result<bool> {
let Some((new, sound, loot, damage, particle)) = self.block_transform(stack, pos, face)
else {
return Ok(false);
};
self.level_set(pos, new)?;
// BlockTransformer.TransformParticle.send.
self.transform_particle(&particle, pos);
if loot.as_deref() == Some("minecraft:till/rooted_dirt") {
self.pop_resource(
[pos[0] + face[0], pos[1] + face[1], pos[2] + face[2]],
+1 -5
View File
@@ -5,7 +5,7 @@ use horizon_client::{
chat::{Chat, ChatAction, ChatScreen, Commands, SYSTEM_INDICATOR},
command::Registries,
gamerules::GameRules,
hud::{HudBatch, rgba},
hud::HudBatch,
screen_draw::Measure,
text::{ClickEvent, Style, Text},
};
@@ -883,10 +883,6 @@ impl Game<'_> {
.chat
.add(&self.gui.atlas, message, None, self.ticks, focused);
}
#[allow(dead_code)]
fn chat_debug_fill(&self, batch: &mut HudBatch) {
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
/// approximated as UTC).
@@ -248,8 +248,32 @@ impl Game<'_> {
/// Every tick: the size change, the wall the player cannot pass and
/// damage outside the border.
/// `BorderChangeListener.DelegateBorderChangeListener`'s packets: what
/// changed on the border since the guests were last told of it.
pub(in crate::game) fn lan_sync_border(&mut self, host: &mut crate::game::lan::LanHost) {
let now = horizon_client::lan::border::Sent::of(&self.border);
if let Some(sent) = host.border_sent.replace(now) {
for packet in sent.changes(&self.border) {
host.hub.broadcast(&packet);
}
}
}
pub(in crate::game) fn tick_worldborder(&mut self) {
self.border.tick();
self.player_border();
self.border_damage();
}
/// The player's movement collides with the border as it is now
/// (`CollisionGetter.borderCollision`): from inside, its walls stop it.
pub(in crate::game) fn player_border(&mut self) {
if let Some(p) = self.player.as_mut() {
p.border = Some(self.border.geometry().clone());
}
}
/// `LivingEntity.baseTick`: a player outside the border, further than
/// its safe zone, is hurt by the blocks beyond it. The game's player, or
/// a guest's in their turn (`as_guest`).
pub(in crate::game) fn border_damage(&mut self) {
let Some((px, pz, half)) = self.player.as_ref().map(|p| {
(
p.position.x,
@@ -269,20 +293,6 @@ impl Game<'_> {
let amount = (-dist * self.border.damage_per_block).floor().max(1.0) as f32;
self.hurt_player_by("minecraft:outside_border", amount);
}
// From inside the border the wall stops movement.
if self.border.distance(px, pz) >= 0.0 {
let [x, z] = self.border.clamp(px, pz, half);
if let Some(p) = self.player.as_mut() {
if x != px {
p.velocity.x = 0.0;
}
if z != pz {
p.velocity.z = 0.0;
}
p.position.x = x;
p.position.z = z;
}
}
}
pub(super) fn cmd_worldborder(&mut self, id: &str, ctx: &Context) -> R<i32> {
let float2 = |v: f64| format!("{v:.2}");
@@ -8,6 +8,7 @@ use horizon_client::{
text::Text,
};
use horizon_core::random::RandomSource;
use horizon_protocol::packets::play::{self, Clientbound as C};
use horizon_world::attribute_map::ValueKind;
use horizon_world::nbt::Tag;
@@ -409,6 +410,8 @@ impl Game<'_> {
],
_ => [1.0, 0.0, 0.0],
};
// The block state of a block particle, for its packet.
let mut block_state = None;
let options = match ty {
ParticleType::Dust => ParticleOptions::dust(
rgb,
@@ -470,6 +473,7 @@ impl Game<'_> {
match block {
Ok(Arg::Block(b)) => {
let state = self.block_state(&b)?;
block_state = Some(state);
let at = self
.position_arg(ctx, "pos")
.unwrap_or_else(|| self.source_position())
@@ -487,10 +491,9 @@ impl Game<'_> {
let pos = self
.position_arg(ctx, "pos")
.unwrap_or_else(|| self.source_position());
let delta = self.position_arg(ctx, "delta").map_or([0.0; 3], |d| {
let s = self.source_position();
[d[0] - s[0], d[1] - s[1], d[2] - s[2]]
});
// Vec3Argument.getVec3: the spread as given (relative parts from the
// source), not a position to measure from the source.
let delta = self.position_arg(ctx, "delta").unwrap_or([0.0; 3]);
let speed = match ctx.get("speed") {
Some(Arg::Float(v)) => *v,
_ => 0.0,
@@ -501,27 +504,74 @@ impl Game<'_> {
};
// ParticleCommand.sendParticles: the viewers it reached, each within
// 32 blocks (512 with `force`) of the particle's block centre.
// Without viewers, every player (PlayerList.getPlayers).
let viewers = if ctx.get("viewers").is_some() {
self.entities(ctx, "viewers", true)?
} else {
vec![Target::Player]
let acting = self.lan_acting;
let guests = self.lan.iter().flat_map(|h| h.hub.guests.iter());
self.player
.as_ref()
.map(|_| Target::Player)
.into_iter()
.chain(
guests
.filter(|g| g.placed && Some(g.conn) != acting)
.map(|g| Target::Guest(g.conn)),
)
.collect()
};
let limit = if ctx.has("force") { 512.0 } else { 32.0 };
let reached = viewers
.iter()
.filter(|&&t| {
let force = ctx.has("force");
let limit = if force { 512.0 } else { 32.0 };
let reached: Vec<Target> = viewers
.into_iter()
.filter(|&t| {
self.target_position(t).is_some_and(|p| {
let c = p.map(|v| v.floor() + 0.5);
(c[0] - pos[0]).powi(2) + (c[1] - pos[1]).powi(2) + (c[2] - pos[2]).powi(2)
< limit * limit
})
})
.count() as i32;
if reached == 0 {
.collect();
if reached.is_empty() {
return Err(err("commands.particle.failed", &[]));
}
// `ServerLevel.sendParticles`: no count means one particle with the delta as velocity.
if count <= 0 {
// ServerLevel.sendParticles: each viewer a server serves is sent the
// particles (the player in place too when it is a guest); the
// window's own player draws them.
let packet = self
.network_particle(&options, block_state)
.map(|particle| {
C::LevelParticles(play::LevelParticles {
particle,
override_limiter: force,
always_show: false,
pos,
dist: delta.map(|d| d as f32),
max_speed: [speed; 3],
count: count.max(0),
randomization: 0,
})
});
let mut local = false;
for &t in &reached {
match (t, &packet) {
(Target::Player, Some(p)) if self.lan_acting.is_some() => {
self.guest_packets.push(p.clone());
}
(Target::Player, _) => local = true,
(Target::Guest(conn), Some(p)) => {
if let Some(host) = self.lan.as_ref() {
host.hub.send_to(conn, p);
}
}
_ => {}
}
}
let reached = reached.len() as i32;
if !local {
} else if count <= 0 {
// No count: one particle with the delta as velocity.
self.particles.create(&options, pos, delta);
} else {
for _ in 0..count {
+12
View File
@@ -845,6 +845,12 @@ impl Game<'_> {
"velocity": [p.velocity.x, p.velocity.y, p.velocity.z],
"on_ground": p.ground.on_ground,
"health": p.health.health(),
// The maximum the HUD's hearts last read (its cached value).
"max_health": p
.attributes
.lookup(p.attributes.key("minecraft:max_health").as_ref())
.and_then(|h| p.attributes.instance(&h).ok())
.map(|i| i.cached_value()),
"food": p.health.food.food,
})
});
@@ -982,6 +988,12 @@ impl Game<'_> {
"flashes": self.lightning_seen[1], "flash": self.flash});
// Primed TNT, falling blocks, projectiles, tridents and end crystals.
status["projectiles"] = json!(self.projectiles_status());
// The particles made so far, by type.
status["particles"] = json!(self.particles.made());
// The world border this side knows of.
status["border"] = json!({ "center": self.border.center(), "size": self.border.size() });
// The scoreboard sidebar the HUD shows.
status["sidebar"] = self.sidebar_status();
status
}
}
+51
View File
@@ -97,8 +97,58 @@ impl EndState {
}
}
impl EndState {
/// The eyes' entity ids, for a server to number them.
pub(super) fn eye_ids(&mut self) -> impl Iterator<Item = &mut u32> {
self.eyes.iter_mut().map(|e| &mut e.id)
}
/// The numbered eyes as a server's clients track them: (id, position, motion).
pub(super) fn eyes_tracked(&self) -> impl Iterator<Item = (u32, [f64; 3], [f64; 3])> {
self.eyes
.iter()
.filter(|e| e.id != 0)
.map(|e| (e.id, e.position.to_array(), e.velocity.to_array()))
}
/// `handleAddEntity` for an eye of ender on a server's client: it flies
/// where the server says.
pub(super) fn add_remote_eye(&mut self, id: u32, at: [f64; 3], velocity: [f64; 3]) {
self.eyes.retain(|e| e.id != id);
let at = glam::DVec3::from_array(at);
self.eyes.push(EyeOfEnder {
id,
position: at,
previous: at,
velocity: glam::DVec3::from_array(velocity),
target: at,
life: 0,
survive: false,
});
}
/// One tick of a server's client: `step` moves each toward where the
/// server put it.
pub(super) fn step_remote_eyes(&mut self, mut step: impl FnMut(u32, [f64; 3]) -> [f64; 3]) {
for e in &mut self.eyes {
e.previous = e.position;
e.life += 1;
e.position = glam::DVec3::from_array(step(e.id, e.position.to_array()));
}
}
pub(super) fn remove_remote_eye(&mut self, id: u32) {
self.eyes.retain(|e| e.id != id);
}
pub(super) fn clear_remote_eyes(&mut self) {
self.eyes.clear();
}
/// Where each eye is, for `status`.
pub(super) fn eye_positions(&self) -> impl Iterator<Item = (u32, [f64; 3])> {
self.eyes.iter().map(|e| (e.id, e.position.to_array()))
}
}
/// The EyeOfEnder entity.
struct EyeOfEnder {
/// Its entity id once a server's clients track it (0 until then).
id: u32,
position: glam::DVec3,
previous: glam::DVec3,
velocity: glam::DVec3,
@@ -1023,6 +1073,7 @@ impl Game<'_> {
};
let survive = self.world.random.next_int_bound(5).unwrap_or(0) > 0;
self.end.eyes.push(EyeOfEnder {
id: 0,
position: start,
previous: start,
velocity: glam::DVec3::ZERO,
@@ -580,6 +580,7 @@ impl Game<'_> {
self.particles.explosion(center, radius, block_count, &|b| {
facts.is_air(world.block(b[0], b[1], b[2]))
});
self.lan_explode(center, radius, block_count);
Ok(())
}
/// `BlockBehaviour.onExplosionHit` (TNT: `wasExploded` primes a short fuse).
+15 -2
View File
@@ -66,6 +66,8 @@ pub(super) struct LanHost {
/// whose respawn replaces their waypoint.
pub waypoints: std::collections::HashMap<String, lan::waypoints::Waypoints>,
pub waypoint_dead: std::collections::HashSet<u128>,
/// The world border as the guests were last told of it (lan/border.rs).
pub border_sent: Option<lan::border::Sent>,
/// 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>,
@@ -566,6 +568,7 @@ impl Game<'_> {
owner: None,
waypoints: Default::default(),
waypoint_dead: Default::default(),
border_sent: None,
commands: Vec::new(),
states: Default::default(),
});
@@ -896,6 +899,7 @@ impl Game<'_> {
tick_frozen: self.clock.frozen(),
tick_steps: self.clock.step_state(),
collision: Some(self.collision),
border: &self.border,
};
host.hub.movement_checks = (
self.ui.rules.bool("player_movement_check"),
@@ -1002,6 +1006,8 @@ impl Game<'_> {
self.lan_update_streaming(&host);
self.lan_update_models(&mut host);
self.lan_update_waypoints(&mut host, state.as_ref());
self.lan_sync_scoreboard(&mut host);
self.lan_sync_border(&mut host);
drop(holding);
lan::flush_all(host.hub.guests.iter().map(|g| &g.sender));
self.lan = Some(host);
@@ -1078,6 +1084,7 @@ impl Game<'_> {
tick_frozen: self.clock.frozen(),
tick_steps: self.clock.step_state(),
collision: Some(self.collision),
border: &self.border,
};
host.hub.place_new_player(conn, &mut ctx);
if elsewhere && let Err(e) = self.enter_level(Some(host), back) {
@@ -1092,8 +1099,14 @@ impl Game<'_> {
}
for e in events {
if let horizon_world::level::LevelEvent::LevelEvent { id, pos, data } = e {
// The acting guest does not predict the egg's teleport particles.
let except = if *id == 2015 { None } else { self.lan_acting };
// The acting guest does not predict the egg's teleport
// particles, nor bone meal's growth (BoneMealItem.useOn's
// levelEvent names no player).
let except = if matches!(*id, 2015 | 1505) {
None
} else {
self.lan_acting
};
self.lan_events
.push((*id, [pos.x, pos.y, pos.z], *data, except));
}
@@ -1609,6 +1609,7 @@ impl Game<'_> {
tick_frozen: self.clock.frozen(),
tick_steps: self.clock.step_state(),
collision: Some(self.collision),
border: &self.border,
};
host.hub.respawn(i, spawn, &ctx);
if let Some(config) = elsewhere {
@@ -1959,7 +1960,8 @@ impl Game<'_> {
for d in travelled {
game.movement_stats(Vec3::new(d[0], d[1], d[2]));
}
// LivingEntity.baseTick ends with tickEffects.
// LivingEntity.baseTick: outside the world border, then tickEffects.
game.border_damage();
game.tick_mob_effects();
let Some(player) = game.player.as_mut() else {
return Vec::new();
@@ -277,6 +277,8 @@ impl Game<'_> {
self.rockets.iter_mut().for_each(|r| give(&mut r.id));
self.crystals.iter_mut().for_each(|c| give(&mut c.id));
self.bolts.iter_mut().for_each(|b| give(&mut b.id));
self.potions.thrown_ids().for_each(&mut give);
self.end.eye_ids().for_each(&mut give);
}
/// Primed TNT, falling blocks, projectiles, tridents, firework rockets and
@@ -359,6 +361,26 @@ impl Game<'_> {
}
out.push(e);
}
// Thrown potions and bottles: ThrowableItemProjectile.DATA_ITEM_STACK
// (the potion's colour), which a plain bottle's type already has.
for (id, kind, stack, position, velocity) in self.potions.thrown_tracked() {
let mut e = state(id, kind, at(position), 0.0, false);
e.velocity = at(velocity);
if stack.extra.is_some() || stack.count != 1 {
e.meta.push((
8,
serializer::ITEM_STACK,
Value::Item(hub.stack(&Some(stack.clone()))),
));
}
out.push(e);
}
// EyeOfEnder: its item is the plain eye (DATA_ITEM_STACK's default).
for (id, position, velocity) in self.end.eyes_tracked() {
let mut e = state(id, "minecraft:eye_of_ender", position, 0.0, false);
e.velocity = velocity;
out.push(e);
}
for t in self.tridents.iter().filter(|t| t.id != 0) {
let mut e = state(t.id, "minecraft:trident", at(t.position), t.yaw, false);
e.pitch = t.pitch;
@@ -0,0 +1,228 @@
//! Particles a server sends its players and its clients draw:
//! `ClientboundLevelParticlesPacket` (`ServerLevel.sendParticles`, which
//! `/particle` uses) and `ClientboundExplodePacket` (`ServerLevel.explode`).
use super::Game;
use horizon_client::particles::{ParticleOptions, ParticleType};
use horizon_core::random::RandomSource;
use horizon_protocol::{
entity_data::{Particle, ParticleData},
packets::play::{self, Clientbound as C},
};
use horizon_world::registry::BlockStateId;
/// An ARGB colour as the options' RGBA.
fn rgba(argb: i32) -> [f32; 4] {
let c = |shift: i32| ((argb >> shift) & 255) as f32 / 255.0;
[c(16), c(8), c(0), c(24)]
}
/// The options' RGB as an RGB colour (`ARGB.colorFromFloat` without alpha).
fn rgb_int(c: [f32; 3]) -> i32 {
let b = |v: f32| ((v.clamp(0.0, 1.0) * 255.0).round() as i32) & 255;
(b(c[0]) << 16) | (b(c[1]) << 8) | b(c[2])
}
fn rgb(c: [f32; 4]) -> [f32; 3] {
[c[0], c[1], c[2]]
}
impl Game<'_> {
/// `ParticleTypes.STREAM_CODEC`'s value for `options`: the type's
/// network id and the data it carries (`state` for the block particles).
/// None while not serving, or for a particle whose data isn't sent from
/// here (items, vibrations, trails).
pub(super) fn network_particle(
&self,
options: &ParticleOptions,
state: Option<BlockStateId>,
) -> Option<Particle> {
let name = format!("minecraft:{}", options.ty.name());
let id = self
.lan
.as_ref()?
.hub
.registry_id("minecraft:particle_type", &name)?;
use ParticleType as T;
let c = options.color;
let data = match options.ty {
T::Block | T::BlockMarker | T::FallingDust | T::DustPillar | T::BlockCrumble => {
Some(ParticleData::State(state?.0 as i32))
}
T::Dust => Some(ParticleData::ColorScale(rgb_int(rgb(c)), options.scale)),
T::DustColorTransition => Some(ParticleData::ColorScale2(
rgb_int(rgb(c)),
rgb_int(options.to_color),
options.scale,
)),
T::Effect | T::InstantEffect => {
Some(ParticleData::ColorPower(rgb_int(rgb(c)), options.scale))
}
T::EntityEffect | T::TintedLeaves => Some(ParticleData::Color(
(((c[3].clamp(0.0, 1.0) * 255.0).round() as i32) << 24) | rgb_int(rgb(c)),
)),
T::DragonBreath | T::SculkCharge => Some(ParticleData::Scalar(options.scale)),
T::Shriek => Some(ParticleData::Delay(options.scale as i32)),
T::Item | T::Trail | T::Vibration => return None,
_ => None,
};
Some(Particle { id, data })
}
/// The options a server's particle stands for (None for a type or data
/// this client doesn't draw).
fn received_particle(&mut self, p: &Particle, at: [f64; 3]) -> Option<ParticleOptions> {
let name = self
.remote
.as_ref()?
.builtin
.get("minecraft:particle_type")?
.name(p.id)?
.to_owned();
let ty = ParticleType::from_name(&name)?;
Some(match &p.data {
None => ParticleOptions::simple(ty),
Some(ParticleData::State(s)) => {
let pos = at.map(|v| v.floor() as i32);
let (sprite, tint) = self
.particle_sprite(BlockStateId(*s as u32), pos)
.unwrap_or_else(|| ("block/stone".into(), 0xFFFFFF));
ParticleOptions::block(ty, sprite, tint)
}
Some(ParticleData::ColorScale(c, scale)) => {
ParticleOptions::dust(rgb(rgba(*c)), *scale)
}
Some(ParticleData::ColorScale2(from, to, scale)) => {
ParticleOptions::dust_transition(rgb(rgba(*from)), rgb(rgba(*to)), *scale)
}
Some(ParticleData::ColorPower(c, power)) => ParticleOptions {
scale: *power,
..ParticleOptions::colored(ty, [rgba(*c)[0], rgba(*c)[1], rgba(*c)[2], 1.0])
},
Some(ParticleData::Color(c)) => ParticleOptions::colored(ty, rgba(*c)),
Some(ParticleData::Scalar(v)) if ty == ParticleType::SculkCharge => {
ParticleOptions::sculk_charge(*v)
}
Some(ParticleData::Scalar(v)) => ParticleOptions {
scale: *v,
..ParticleOptions::simple(ty)
},
Some(ParticleData::Delay(d)) => ParticleOptions::shriek(*d),
Some(ParticleData::Trail(target, color, duration)) => {
ParticleOptions::trail(*target, *color as u32 & 0xFF_FFFF, *duration)
}
Some(_) => return None,
})
}
/// `ClientPacketListener.handleParticleEvent`: no count is one particle
/// moving by speed times spread; otherwise each is spread and sped up by
/// gaussians on each axis.
pub(super) fn remote_level_particles(&mut self, p: &play::LevelParticles) {
let Some(options) = self.received_particle(&p.particle, p.pos) else {
return;
};
let (d, s) = (p.dist.map(f64::from), p.max_speed.map(f64::from));
// ClientLevel.addParticle: the camera's 32 blocks unless the packet
// (`force`) or the type overrides the limiter.
let add = |particles: &mut horizon_client::particles::ParticleEngine, at, v| {
if p.override_limiter {
particles.create(&options, at, v);
} else {
particles.add(&options, at, v);
}
};
if p.count == 0 {
add(
&mut self.particles,
p.pos,
[s[0] * d[0], s[1] * d[1], s[2] * d[2]],
);
return;
}
for _ in 0..p.count {
let r = self.particles.random();
let at = [
p.pos[0] + r.next_gaussian() * d[0],
p.pos[1] + r.next_gaussian() * d[1],
p.pos[2] + r.next_gaussian() * d[2],
];
let v = [
r.next_gaussian() * s[0],
r.next_gaussian() * s[1],
r.next_gaussian() * s[2],
];
add(&mut self.particles, at, v);
}
}
/// `ClientPacketListener.handleExplosion`: the blast's particles (and its
/// sound, when the packet carries it).
pub(super) fn remote_explode(&mut self, p: &play::Explode) {
if p.play_sound {
let pitch = (1.0
+ (self.particles.random().next_float() - self.particles.random().next_float())
* 0.2)
* 0.7;
self.audio.play(
"minecraft:entity.generic.explode",
Some(p.center),
4.0,
pitch,
);
}
let (world, facts) = (&self.world, self.res.facts());
self.particles
.explosion(p.center, p.radius, p.block_count.max(0) as usize, &|b| {
facts.is_air(world.block(b[0], b[1], b[2]))
});
}
/// `ServerLevel.explode`'s packet to each player within 64 blocks. The
/// sound and the push reach them on their own (the level's sounds, the
/// players' motion), so the packet carries neither.
pub(super) fn lan_explode(&self, center: [f64; 3], radius: f32, block_count: usize) {
let Some(host) = self.lan.as_ref() else {
return;
};
let particle = |name: &str| {
Some(Particle {
id: host.hub.registry_id("minecraft:particle_type", name)?,
data: None,
})
};
let emitter = if radius < 2.0 {
"minecraft:explosion"
} else {
"minecraft:explosion_emitter"
};
let (Some(at_center), Some(poof), Some(smoke)) = (
particle(emitter),
particle("minecraft:poof"),
particle("minecraft:smoke"),
) else {
return;
};
// Level.DEFAULT_EXPLOSION_BLOCK_PARTICLES.
let info = |particle, scaling| play::ExplosionParticle {
particle,
scaling,
speed: 1.0,
weight: 1,
};
let packet = C::Explode(play::Explode {
center,
radius,
block_count: block_count as i32,
knockback: None,
particle: at_center,
sound: match host
.hub
.registry_id("minecraft:sound_event", "minecraft:entity.generic.explode")
{
Some(id) => (id, None),
None => (-1, Some(("minecraft:entity.generic.explode".into(), None))),
},
block_particles: vec![info(poof, 0.5), info(smoke, 1.0)],
play_sound: false,
});
host.hub.broadcast_near(center, 64.0, &packet, None);
}
}
@@ -129,23 +129,6 @@ impl Game<'_> {
}
/// The screen title: the custom name, else the profession (the client
/// adds the level itself).
#[allow(dead_code)]
fn merchant_title(&self, state: &MerchantState) -> String {
if let Some(name) = &state.name {
return name.clone();
}
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}"))
.unwrap_or(profession)
.to_owned()
} else {
e.translate("entity.minecraft.wandering_trader")
.unwrap_or("Wandering Trader")
.to_owned()
}
}
/// `ServerPlayer.sendMerchantOffers`, when the offers changed.
fn lan_send_offers(
&mut self,
@@ -1,10 +1,10 @@
//! Level events whose client handler (`LevelEventHandler`) spawns particles
//! on a block: dragon egg teleportation (2015), a consumable's teleport
//! (2017), electric sparks (3002), waxing (3003), wax off (3004) and
//! scraping (3005).
//! on a block: bone meal's growth (1505), 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;
use horizon_core::{position::BlockPos, random::RandomSource};
use horizon_world::level::LevelEvent;
impl Game<'_> {
@@ -42,6 +42,65 @@ impl Game<'_> {
self.particles.add(&options, p, v);
}
}
/// `BoneMealItem.addGrowthParticles` (event 1505, `count` the data):
/// happy villager sparks over a spreading block's neighbourhood (grass,
/// nylium, netherrack, moss) or water, or inside a growing block.
pub(super) fn growth_particles(&mut self, pos: BlockPos, count: i32) {
let p = [pos.x, pos.y, pos.z];
let state = self.world.block(p[0], p[1], p[2]);
let facts = self.res.facts();
// ParticleUtils.spawnParticles(level, pos, count, xzSpread, ySpread,
// allowFloatingParticles, particle).
let (at, count, xz, height, floating) = match self.res.behaviours().bone_meal_spreads(state)
{
Some(spreads) => {
// BonemealableBlock.getParticlePos: below for rooted dirt
// (its hanging roots) and mangrove leaves (their propagule).
let at = match &*facts.get(state).name {
"minecraft:rooted_dirt" | "minecraft:mangrove_leaves" => [p[0], p[1] - 1, p[2]],
_ => p,
};
if spreads {
(at, count * 3, 3.0, 1.0, false)
} else {
// ParticleUtils.spawnParticleInBlock: up to the
// block's shape (a full block when air).
let inside = self.world.block(at[0], at[1], at[2]);
let height = if facts.is_air(inside) {
1.0
} else {
facts
.get(inside)
.outline
.iter()
.map(|b| b[4])
.fold(0.0, f64::max)
};
(at, count, 0.5, height, true)
}
}
None if &*facts.get(state).name == "minecraft:water" => (p, count * 3, 3.0, 1.0, false),
None => return,
};
let options = ParticleOptions::simple(ParticleType::HappyVillager);
for _ in 0..count.max(0) {
let r = self.particles.level_random();
let v = [0.0; 3].map(|_: f64| r.next_gaussian() * 0.02);
let start = 0.5 - xz;
let x = f64::from(at[0]) + start + r.next_double() * xz * 2.0;
let y = f64::from(at[1]) + r.next_double() * height;
let z = f64::from(at[2]) + start + r.next_double() * xz * 2.0;
let below = [x.floor() as i32, y.floor() as i32 - 1, z.floor() as i32];
if floating
|| !self
.res
.facts()
.is_air(self.world.block(below[0], below[1], below[2]))
{
self.particles.add(&options, [x, y, z], v);
}
}
}
/// Queue and play level event `id` at `pos` (`Level.levelEvent`).
pub(super) fn level_event_at(&mut self, id: i32, pos: [i32; 3], data: i32) {
self.level_events.push(LevelEvent::LevelEvent {
+70 -8
View File
@@ -18,6 +18,8 @@ use horizon_core::{geometry::Vec3, random::RandomSource};
/// A thrown splash or lingering potion in flight.
#[derive(Clone, Debug)]
pub(super) struct ThrownPotion {
/// Its entity id once a server's clients track it (0 until then).
id: u32,
stack: ItemStack,
/// The position before the last tick, for drawing between ticks.
previous: Vec3,
@@ -47,6 +49,7 @@ impl Game<'_> {
/// player's throws and dispensers both end up here).
pub(super) fn launch_thrown(&mut self, stack: ItemStack, position: Vec3, velocity: Vec3) {
self.potions.thrown.push(ThrownPotion {
id: 0,
stack,
previous: position,
position,
@@ -90,19 +93,78 @@ impl PotionState {
pub(super) fn thrown_entities(&self) -> Vec<(&'static str, Vec3, Vec3)> {
self.thrown
.iter()
.map(|t| {
let kind = match &*t.stack.item {
"minecraft:lingering_potion" => "minecraft:lingering_potion",
"minecraft:experience_bottle" => "minecraft:experience_bottle",
_ => "minecraft:splash_potion",
};
(kind, t.position, t.velocity)
})
.map(|t| (thrown_kind(&t.stack), t.position, t.velocity))
.collect()
}
pub(super) fn clear_thrown(&mut self) {
self.thrown.clear();
}
/// Their entity ids, for a server to number them.
pub(super) fn thrown_ids(&mut self) -> impl Iterator<Item = &mut u32> {
self.thrown.iter_mut().map(|t| &mut t.id)
}
/// The numbered ones as a server's clients track them: (id, entity
/// type, item, position, motion).
pub(super) fn thrown_tracked(
&self,
) -> impl Iterator<Item = (u32, &'static str, &ItemStack, Vec3, Vec3)> {
self.thrown.iter().filter(|t| t.id != 0).map(|t| {
(
t.id,
thrown_kind(&t.stack),
&t.stack,
t.position,
t.velocity,
)
})
}
/// `handleAddEntity` for a thrown potion or bottle on a server's client:
/// drawn where the server says (its item comes in its entity data).
pub(super) fn add_remote_thrown(&mut self, id: u32, kind: &str, at: Vec3, velocity: Vec3) {
self.thrown.retain(|t| t.id != id);
let item = match kind {
"minecraft:lingering_potion" | "minecraft:experience_bottle" => kind,
_ => "minecraft:splash_potion",
};
self.thrown.push(ThrownPotion {
id,
stack: ItemStack::new(item, 1),
previous: at,
position: at,
velocity,
age: 0,
});
}
/// ThrowableItemProjectile.DATA_ITEM_STACK: the potion it shows.
pub(super) fn remote_thrown_item(&mut self, id: u32, stack: ItemStack) {
if let Some(t) = self.thrown.iter_mut().find(|t| t.id == id) {
t.stack = stack;
}
}
/// One tick of a server's client: `step` moves each toward where the
/// server put it.
pub(super) fn step_remote_thrown(&mut self, mut step: impl FnMut(u32, Vec3) -> Vec3) {
for t in &mut self.thrown {
t.previous = t.position;
t.age += 1;
t.position = step(t.id, t.position);
}
}
pub(super) fn remove_remote_thrown(&mut self, id: u32) {
self.thrown.retain(|t| t.id != id);
}
pub(super) fn has_thrown(&self, id: u32) -> bool {
self.thrown.iter().any(|t| t.id == id)
}
}
/// The entity type of a thrown potion or bottle.
fn thrown_kind(stack: &ItemStack) -> &'static str {
match &*stack.item {
"minecraft:lingering_potion" => "minecraft:lingering_potion",
"minecraft:experience_bottle" => "minecraft:experience_bottle",
_ => "minecraft:splash_potion",
}
}
impl Game<'_> {
+55 -24
View File
@@ -101,7 +101,7 @@ fn place_interpolated(m: &mut Mob, at: PosRot) {
pub(super) struct Remote {
pub session: Session,
pub brand: String,
builtin: Arc<Builtin>,
pub(super) builtin: Arc<Builtin>,
lang: Arc<Language>,
pub(super) registries: Arc<Dynamic>,
joined: bool,
@@ -164,6 +164,8 @@ pub(super) struct Remote {
level_players: HashMap<i32, u128>,
/// The local player's profile UUID (always in the level).
profile: u128,
/// The local player's profile name: its score holder and team member.
pub(super) profile_name: String,
destroying: Option<([i32; 3], u8, f32)>,
destroy_delay: u32,
input: horizon_client::interaction_input::InteractionInput,
@@ -411,6 +413,7 @@ impl Game<'_> {
online_mode: false,
level_players: HashMap::new(),
profile: 0,
profile_name: String::new(),
destroying: None,
destroy_delay: 0,
input: Default::default(),
@@ -811,6 +814,7 @@ impl Game<'_> {
if let Some(r) = self.remote.as_mut() {
r.joined = true;
r.profile = uuid;
r.profile_name = name.clone();
r.status = format!("Joined as {name}; loading terrain...");
}
}
@@ -1741,29 +1745,12 @@ impl Game<'_> {
self.block_entity_event(p.pos, i32::from(p.b0), i32::from(p.b1));
}
}
C::LevelEvent(p) if p.kind == 2015 => {
self.dragon_egg_particles(p.pos, p.data);
}
C::LevelEvent(p) if p.kind == 2017 => {
self.consume_teleport_particles(p.pos, p.data);
}
C::LevelEvent(p) if p.kind == 2001 => {
// LevelEvent.PARTICLES_DESTROY_BLOCK: someone else broke a block.
let state = BlockStateId(p.data.max(0) as u32);
let s = self.res.facts().get(state).sounds.clone();
let at = [
f64::from(p.pos[0]) + 0.5,
f64::from(p.pos[1]) + 0.5,
f64::from(p.pos[2]) + 0.5,
];
self.audio.play(
&s.break_sound,
Some(at),
(s.volume + 1.0) / 2.0,
s.pitch * 0.8,
);
self.destroy_particles(p.pos, state);
}
// ClientLevel.levelEvent: LevelEventHandler, as this client's own
// level plays them (particles and sounds: a spawner's burst, bone
// meal, waxing, a block broken by someone else).
C::LevelEvent(p) => self.level_event_at(p.kind, p.pos, p.data),
C::LevelParticles(p) => self.remote_level_particles(&p),
C::Explode(p) => self.remote_explode(&p),
C::Sound(p) => {
let name = match &p.sound.1 {
Some((location, _)) => Some(location.clone()),
@@ -2166,6 +2153,15 @@ impl Game<'_> {
m.swing();
}
}
// The player's own instances: its maximum health (the hearts the
// HUD draws and the health it may hold), reach, speed and so on.
// Then the received health again, which the old maximum clamped.
C::UpdateAttributes(p) if self.remote.as_ref().is_some_and(|r| r.entity_id == p.id) => {
if let Some(pl) = self.player.as_mut() {
horizon_client::lan::attributes::apply(&mut pl.attributes, &p.values);
}
self.apply_remote_health();
}
C::UpdateMobEffect(p) => self.remote_effect(&p),
C::RemoveMobEffect(p) => {
if self.remote.as_ref().is_some_and(|r| r.entity_id == p.id)
@@ -3070,6 +3066,7 @@ impl Game<'_> {
self.remote_handle_input();
// ClientLevel.tick: the border's size change.
self.border.tick();
self.player_border();
self.tick_remote_entities(running);
// ClientLevel.tickBlockEntities: chest lids, shulker boxes, bells.
self.tick_block_entity_anims();
@@ -3859,6 +3856,8 @@ impl Game<'_> {
}
if reacts {
self.predict_use(&changes, seq);
} else if let Some(stack) = held.as_ref() {
self.predict_item_on_block(stack, &hit);
}
if held_block {
if reacts
@@ -3877,6 +3876,38 @@ impl Game<'_> {
false
}
/// `Item.useOn` on this client's level for the items whose effects are
/// the clicker's own (`Level.levelEvent(player, ...)` and
/// `playSound(player, ...)`: the server sends them to the others only):
/// honeycomb waxing copper, and an axe, hoe or shovel transforming a
/// block (stripping, scraping, removing wax, tilling, making a path).
fn predict_item_on_block(&mut self, stack: &ItemStack, hit: &super::Hit) {
let at = [
f64::from(hit.pos[0]) + 0.5,
f64::from(hit.pos[1]) + 0.5,
f64::from(hit.pos[2]) + 0.5,
];
if &*stack.item == "minecraft:honeycomb" {
// HoneycombItem.useOn.
let registry = self.pack.assets.registry;
let clicked = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]);
let waxes = registry
.state(clicked)
.and_then(|old| self.res.transformers().waxed(registry, old))
.is_some();
if waxes {
self.level_event_at(3003, hit.pos, 0);
self.audio
.play("minecraft:item.honeycomb.wax_on", Some(at), 1.0, 1.0);
}
} else if let Some((_, sound, _, _, particle)) =
self.block_transform(stack, hit.pos, hit.face)
{
self.transform_particle(&particle, hit.pos);
self.audio.play(&sound, Some(at), 1.0, 1.0);
}
}
/// MultiPlayerGameMode.useItemOn inside startPrediction: the blocks the
/// use changed on this client's level at once, each kept as predicted
/// under the use's sequence until the server acknowledges it (a use the
@@ -79,6 +79,15 @@ impl Game<'_> {
self.rockets
.push(super::fireworks::Rocket::remote(id, at, velocity));
}
"minecraft:splash_potion"
| "minecraft:lingering_potion"
| "minecraft:experience_bottle" => {
self.potions.add_remote_thrown(id, kind, at, velocity);
}
"minecraft:eye_of_ender" => {
self.end
.add_remote_eye(id, position, [velocity.x, velocity.y, velocity.z])
}
"minecraft:end_crystal" => self.crystals.push(super::dragon::Crystal {
id,
position: at,
@@ -105,6 +114,17 @@ impl Game<'_> {
/// `handleSetEntityData` for these types: what changes how they look.
pub(super) fn remote_projectile_data(&mut self, id: i32, values: &[(u8, i32, Value)]) {
let id = id as u32;
if self.potions.has_thrown(id) {
// ThrowableItemProjectile.DATA_ITEM_STACK: the potion it is.
for (index, _, value) in values {
if let (8, Value::Item(stack)) = (index, value)
&& let Some(stack) = self.to_stack(stack)
{
self.potions.remote_thrown_item(id, stack);
}
}
return;
}
for (index, _, value) in values {
if let Some(t) = self.tnts.iter_mut().find(|t| t.id == id) {
// PrimedTnt.DATA_FUSE_ID.
@@ -184,6 +204,11 @@ impl Game<'_> {
c.time += 1;
c.position = step(c.id, c.position);
}
self.potions.step_remote_thrown(&mut step);
self.end.step_remote_eyes(|id, at| {
let at = step(id, Vec3::new(at[0], at[1], at[2]));
[at.x, at.y, at.z]
});
}
pub(super) fn remove_remote_projectile(&mut self, id: u32) {
@@ -193,6 +218,8 @@ impl Game<'_> {
self.tridents.retain(|t| t.id != id);
self.rockets.retain(|r| r.id != id);
self.crystals.retain(|c| c.id != id);
self.potions.remove_remote_thrown(id);
self.end.remove_remote_eye(id);
}
/// Every one a server sent (a new connection, level or dimension).
@@ -203,6 +230,8 @@ impl Game<'_> {
self.tridents.clear();
self.rockets.clear();
self.crystals.clear();
self.potions.clear_thrown();
self.end.clear_remote_eyes();
}
/// Their kind and place, for `status`.
@@ -225,6 +254,12 @@ impl Game<'_> {
for p in &self.creatures.projectiles {
out.push(json!({"id": p.id, "kind": format!("{:?}", p.kind).split([' ', '{']).next().unwrap_or(""), "position": at(p.position)}));
}
for (kind, p, _) in self.potions.thrown_entities() {
out.push(json!({"kind": kind, "position": at(p)}));
}
for (id, p) in self.end.eye_positions() {
out.push(json!({"id": id, "kind": "minecraft:eye_of_ender", "position": p}));
}
out
}
}
+45 -6
View File
@@ -324,6 +324,22 @@ impl Game<'_> {
}
}
}
/// `ServerScoreboard`'s packets: each placed player's client is sent
/// what changed on the board since it was last sent it (all of it on
/// joining), lan/scoreboard.rs.
pub(super) fn lan_sync_scoreboard(&mut self, host: &mut super::lan::LanHost) {
if host.hub.guests.iter().all(|g| !g.placed) {
return;
}
self.load_scoreboard();
let view = horizon_client::lan::scoreboard::View::of(&self.score.board);
for g in host.hub.guests.iter_mut().filter(|g| g.placed) {
if g.scoreboard != view {
g.send_all(&g.scoreboard.changes(&view));
g.scoreboard = view.clone();
}
}
}
/// `ServerPlayer.doTick` score updates and the statistic criteria.
pub(super) fn tick_scoreboard(&mut self) {
self.load_scoreboard();
@@ -563,19 +579,42 @@ impl Game<'_> {
// ---- the sidebar -----------------------------------------------------------
/// `Hud.extractScoreboardSidebar` / `displayScoreboardSidebar`.
pub(super) fn draw_scoreboard(&self, batch: &mut HudBatch) {
/// The objective in the player's team's sidebar slot, else the sidebar's.
fn sidebar_objective(&self) -> Option<&sb::Objective> {
let board = &self.score.board;
if board.display.is_empty() {
return;
return None;
}
// A server's client is in its team by its profile name.
let name = self
.remote
.as_ref()
.map_or(PLAYER_NAME, |r| r.profile_name.as_str());
let team_slot = board
.players_team(PLAYER_NAME)
.players_team(name)
.and_then(|t| t.color.as_ref())
.map(|c| format!("sidebar.team.{c}"))
.and_then(|slot| board.display_objective(&slot));
let Some(objective) = team_slot.or_else(|| board.display_objective(sb::SLOT_SIDEBAR))
else {
team_slot.or_else(|| board.display_objective(sb::SLOT_SIDEBAR))
}
/// The sidebar the HUD shows: its objective and its lines, for `status`.
pub(super) fn sidebar_status(&self) -> serde_json::Value {
let board = &self.score.board;
let Some(objective) = self.sidebar_objective() else {
return serde_json::Value::Null;
};
let scores: serde_json::Map<String, serde_json::Value> = board
.scores
.iter()
.filter_map(|(holder, s)| Some((holder.clone(), s.get(&objective.name)?.value.into())))
.collect();
serde_json::json!({ "objective": objective.name, "title": objective.display_text().plain(), "scores": scores })
}
/// `Hud.extractScoreboardSidebar` / `displayScoreboardSidebar`.
pub(super) fn draw_scoreboard(&self, batch: &mut HudBatch) {
let board = &self.score.board;
let Some(objective) = self.sidebar_objective() else {
return;
};
let draws = hud_overlays::sidebar(
@@ -455,6 +455,7 @@ impl Game<'_> {
tick_frozen: self.clock.frozen(),
tick_steps: self.clock.step_state(),
collision: Some(self.collision),
border: &self.border,
}
}
}
-4
View File
@@ -2463,10 +2463,6 @@ impl Renderer {
view_formats: &config.view_formats,
})
}
/// Rendering to a texture instead of the window (`--offscreen`).
pub fn is_offscreen(&self) -> bool {
self.surface.is_none()
}
/// Release the window surface before another renderer uses the same window.
pub fn release_surface(&mut self) {
self.surface = None;
-4
View File
@@ -119,10 +119,6 @@ impl Tile {
}
impl Renderer {
pub fn resident_lods(&self) -> usize {
self.lods.len()
}
pub fn upload_lod(&mut self, key: TileKey, mesh: &SectionMesh) {
self.remove_lod(key);
if let Some(bounds) = Bounds::mesh(mesh)
-1
View File
@@ -7,7 +7,6 @@ use std::collections::BTreeMap;
/// `ReputationEventType` amounts.
pub const REPUTATION_CHANGE_PER_EVENT: i32 = 25;
pub const REPUTATION_CHANGE_PER_EVERLASTING_MEMORY: i32 = 20;
pub const REPUTATION_CHANGE_PER_TRADE: i32 = 2;
/// `GossipContainer.DISCARD_THRESHOLD`: values below this are forgotten.
const DISCARD_THRESHOLD: i32 = 2;
-8
View File
@@ -486,14 +486,6 @@ impl Item {
_ => return None,
})
}
/// Caption and value text, split from the label ("Caption: Value").
pub fn caption_value(self, s: &Settings) -> (String, String) {
let label = self.label(s).plain();
match label.split_once(": ") {
Some((c, v)) => (c.to_owned(), v.to_owned()),
None => (label, String::new()),
}
}
pub fn slider(self, s: &Settings) -> Option<f32> {
match self {
Item::Vanilla(o) => o.slider_position(s),
-18
View File
@@ -861,24 +861,6 @@ impl HudBatch {
};
self.text_styled(atlas, &t, x, y, color, shadow)
}
/// `text_styled` under a pose: GUI positions scaled by `scale`, then
/// moved to `origin` (Matrix3x2fStack translate + scale).
pub fn text_posed(
&mut self,
atlas: &HudAtlas,
text: &crate::text::Text,
at: [f32; 2],
color: u32,
scale: f32,
origin: [f32; 2],
) -> f32 {
let start = self.vertices.len();
let advance = self.text_styled(atlas, text, at[0], at[1], color, true);
for v in &mut self.vertices[start..] {
v.pos = [origin[0] + v.pos[0] * scale, origin[1] + v.pos[1] * scale];
}
advance
}
/// Font.drawInternal: styled glyphs, shadows first, with bold, italic,
/// underline and strikethrough. `color` is the default colour and alpha.
pub fn text_styled(
-11
View File
@@ -124,17 +124,6 @@ impl ItemRenderState {
pub fn is_empty(&self) -> bool {
self.layers.is_empty()
}
/// `pickParticleMaterial`: a random layer's particle sprite.
pub fn pick_particle(
&self,
random: &mut impl horizon_core::random::RandomSource,
) -> Option<String> {
if self.layers.is_empty() {
return None;
}
let i = random.next_int_bound(self.layers.len() as i32).unwrap_or(0) as usize;
self.layers.get(i).map(|l| l.particle.clone())
}
/// `usesBlockLight` of the first layer (GUI lighting choice).
pub fn uses_block_light(&self) -> bool {
self.layers.first().is_some_and(|l| l.uses_block_light)
+22
View File
@@ -236,6 +236,24 @@ mod tests {
assert_eq!(vendor_name(0, "Apple M4 Pro"), "Apple");
}
/// wgpu is given the WGSL text: it must parse again.
fn reparse_error(pack: &JavaPasses) -> Option<String> {
let passes = pack
.folders
.iter()
.flat_map(|f| f.passes.iter().chain(&f.final_pass));
passes
.flat_map(|p| [(p, &p.vertex, "vsh"), (p, &p.fragment, "fsh")])
.find_map(|(p, t, ext)| {
let e = naga::front::wgsl::parse_str(&t.wgsl).err()?;
Some(format!(
"{}.{ext}: {}",
p.pass.program,
e.emit_to_string(&t.wgsl)
))
})
}
/// The packs in `HORIZON_TEST_SHADERPACKS` (folders or zips) load as the
/// game loads them, with their default options: the compatibility table
/// of docs/shader-packs.md. Skipped when the variable isn't set.
@@ -255,6 +273,10 @@ mod tests {
for path in entries {
let name = path.file_name().unwrap().to_string_lossy().into_owned();
match load(&path, &BTreeMap::new(), "Apple", "Apple M4 Pro") {
Ok(pack) if let Some(e) = reparse_error(&pack) => {
println!("{name}: {e}");
failures.push(name);
}
Ok(pack) => {
let folders: Vec<String> = pack
.folders
-9
View File
@@ -295,15 +295,6 @@ impl KeyBinds {
self.keys.insert(n, key.to_owned());
}
}
/// Load `key_<name>` from options.txt; false for unknown mappings.
pub fn set_saved(&mut self, name: &str, key: &str) -> bool {
if MAPPINGS.iter().any(|m| m.0 == name) {
self.set(name, key);
true
} else {
false
}
}
pub fn saved(&self) -> Vec<(&'static str, String)> {
MAPPINGS
.iter()
-2
View File
@@ -104,8 +104,6 @@ pub const SNEAK: usize = 0;
pub const SPRINT: usize = 1;
/// Attack (mouse).
pub const ATTACK: usize = 2;
/// Use (mouse).
pub const USE: usize = 3;
/// The `ToggleKeyMapping`s `Options` builds: sneak and sprint (keyboard,
/// restored after a screen), attack (mouse, restored) and use (mouse, not
+43 -1
View File
@@ -5,7 +5,7 @@
//! changed since (`getAttributesToSync`), to the trackers and the player itself.
use horizon_protocol::packets::play::{AttributeModifier, AttributeSnapshot};
use horizon_world::attributes::{
Instance, Operation,
Instance, Modifier, Operation,
entity::{AttributeId, EntityAttributes},
live::LiveAttributes,
};
@@ -70,6 +70,48 @@ pub fn take_dirty<G: FnMut() -> i32>(map: &mut LiveAttributes<G>) -> Vec<Attribu
.collect()
}
/// `ClientPacketListener.handleUpdateAttributes`: each instance the server
/// synced takes its base and exactly its modifiers (`removeModifiers`, then
/// `addTransientModifier` for each). An attribute the map doesn't know is
/// skipped, as vanilla warns and skips it.
pub fn apply<G: FnMut() -> i32>(map: &mut LiveAttributes<G>, values: &[AttributeSnapshot]) {
for s in values {
let Some(key) = map
.keys()
.iter()
.find(|k| k.attribute().registry_id() == s.attribute)
.cloned()
else {
continue;
};
let Ok(Some(handle)) = map.get_instance(Some(key)) else {
continue;
};
let modifiers: Vec<_> = s
.modifiers
.iter()
.filter_map(|m| Modifier::new(&m.id, m.amount, operation(m.operation)).ok())
.collect();
let _ = map.edit(&handle, |instance, observer| {
instance.set_base_value(s.base, observer)?;
instance.remove_all(observer)?;
for m in modifiers {
instance.add_transient(m, observer)?;
}
Ok(())
});
}
}
/// `AttributeModifier.Operation.BY_ID`.
fn operation(id: i32) -> Operation {
match id {
1 => Operation::AddMultipliedBase,
2 => Operation::AddMultipliedTotal,
_ => Operation::AddValue,
}
}
/// The client-syncable instances of a generic attribute map.
pub fn generic_syncable(map: &EntityAttributes) -> impl Iterator<Item = AttributeSnapshot> + '_ {
let catalog = map.catalog();
+130
View File
@@ -0,0 +1,130 @@
//! The world border a server's players see: all of it when they enter a
//! level (`PlayerList.sendLevelInfo`), then each change as
//! `BorderChangeListener` broadcasts it: a new centre, a new size, a size
//! change in progress, a new warning time or distance.
use crate::worldborder::WorldBorder;
use horizon_protocol::packets::play::{self, Clientbound as C};
/// `ClientboundInitializeBorderPacket`.
pub fn initialize(b: &WorldBorder) -> play::InitializeBorder {
let [center_x, center_z] = b.center();
play::InitializeBorder {
center_x,
center_z,
old_size: b.size(),
new_size: b.target_size(),
lerp_time: b.remaining_ticks(),
absolute_max_size: b.absolute_max_size(),
warning_blocks: b.warning_distance,
warning_time: b.warning_time,
}
}
/// The border as the players were last told of it.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Sent {
center: [f64; 2],
size: f64,
target: f64,
remaining: i64,
warning_distance: i32,
warning_time: i32,
}
impl Sent {
pub fn of(b: &WorldBorder) -> Self {
Self {
center: b.center(),
size: b.size(),
target: b.target_size(),
remaining: b.remaining_ticks(),
warning_distance: b.warning_distance,
warning_time: b.warning_time,
}
}
/// The packets that tell the players what changed since `self`, other
/// than a size change going on (which each client runs itself).
pub fn changes(&self, b: &WorldBorder) -> Vec<C> {
let now = Self::of(b);
let mut out = Vec::new();
if now.center != self.center {
out.push(C::SetBorderCenter(play::SetBorderCenter {
x: now.center[0],
z: now.center[1],
}));
}
// A change going on counts down a tick at a time (or not at all
// while the game is frozen), towards the same size.
let going_on = self.remaining > 0
&& now.target == self.target
&& (now.remaining == self.remaining || now.remaining == self.remaining - 1);
if now.remaining > 0 {
if !going_on {
out.push(C::SetBorderLerpSize(play::SetBorderLerpSize {
old_size: now.size,
new_size: now.target,
lerp_time: now.remaining,
}));
}
} else if now.size != self.size && !(self.remaining > 0 && now.size == self.target) {
out.push(C::SetBorderSize(play::SetBorderSize { size: now.size }));
}
if now.warning_time != self.warning_time {
out.push(C::SetBorderWarningDelay(play::SetBorderWarningDelay {
delay: now.warning_time,
}));
}
if now.warning_distance != self.warning_distance {
out.push(C::SetBorderWarningDistance(
play::SetBorderWarningDistance {
blocks: now.warning_distance,
},
));
}
out
}
}
#[cfg(test)]
mod tests {
use super::*;
fn kinds(packets: &[C]) -> Vec<&'static str> {
packets
.iter()
.map(|p| match p {
C::SetBorderCenter(_) => "center",
C::SetBorderSize(_) => "size",
C::SetBorderLerpSize(_) => "lerp",
C::SetBorderWarningDelay(_) => "delay",
C::SetBorderWarningDistance(_) => "distance",
_ => "other",
})
.collect()
}
#[test]
fn each_change_is_sent_once() {
let mut b = WorldBorder::default();
let mut sent = Sent::of(&b);
assert!(sent.changes(&b).is_empty());
b.set_center([4.0, -2.0]);
b.set_size(10.0);
b.warning_time = 30;
assert_eq!(kinds(&sent.changes(&b)), ["center", "size", "delay"]);
sent = Sent::of(&b);
// A change over 3 ticks: sent once, then each client runs it.
b.lerp_to(20.0, 3);
assert_eq!(kinds(&sent.changes(&b)), ["lerp"]);
for _ in 0..4 {
sent = Sent::of(&b);
b.tick();
assert!(sent.changes(&b).is_empty(), "{:?}", sent.changes(&b));
}
assert_eq!(b.size(), 20.0);
b.warning_distance = 1;
assert_eq!(kinds(&Sent::of(&b).changes(&b)), [] as [&str; 0]);
assert_eq!(kinds(&sent.changes(&b)), ["distance"]);
}
}
+3 -1
View File
@@ -15,7 +15,6 @@ use std::{
/// GameType ids.
pub const SURVIVAL: i32 = 0;
pub const CREATIVE: i32 = 1;
pub const ADVENTURE: i32 = 2;
pub const SPECTATOR: i32 = 3;
/// The body state a player's file keeps that lives on `PlayerMotion`.
@@ -243,6 +242,8 @@ pub struct Guest {
pub advancements_loaded: bool,
pub advancements_visible: Vec<bool>,
pub advancements_changed: std::collections::BTreeSet<usize>,
/// The server's scoreboard as this player's client has it (lan/scoreboard.rs).
pub scoreboard: super::scoreboard::View,
/// Recipes unlocked since the client was last told
/// (`ServerRecipeBook.addRecipes` sends them).
pub recipes_unlocked: Vec<String>,
@@ -355,6 +356,7 @@ impl Guest {
advancements_loaded: false,
advancements_visible: Vec::new(),
advancements_changed: Default::default(),
scoreboard: Default::default(),
recipes_unlocked: Vec::new(),
}
}
+3 -33
View File
@@ -111,6 +111,8 @@ pub struct TickCtx<'a> {
/// Block collisions, for ServerGamePacketListenerImpl's moved-wrongly
/// check (none: moves are not checked against blocks).
pub collision: Option<&'a BlockCollisionRegistry<'a>>,
/// The level's world border (PlayerList.sendLevelInfo sends it).
pub border: &'a crate::worldborder::WorldBorder,
}
/// What the gameplay code has to do for a guest.
@@ -172,13 +174,6 @@ pub struct Hub {
fn string(s: &str) -> Tag {
Tag::String(JavaString::from(s))
}
pub fn yellow_translation(key: &str, args: &[&str]) -> Tag {
let mut t = translatable(key, args);
if let Tag::Compound(map) = &mut t {
map.insert(JavaString::from("color"), string("yellow"));
}
t
}
/// Player.getDisplayName for a player in no team: the name, suggesting
/// `/tell NAME `, showing the player on hover and inserting the name.
@@ -898,17 +893,7 @@ impl Hub {
fn send_level_info(&mut self, i: usize, ctx: &TickCtx) {
let spawn = ctx.spawn;
let g = &self.guests[i];
g.send(&C::InitializeBorder(play::InitializeBorder {
center_x: 0.0,
center_z: 0.0,
old_size: 59_999_968.0,
new_size: 59_999_968.0,
lerp_time: 0,
absolute_max_size: 29_999_984,
warning_blocks: 5,
// WorldBorder.DEFAULT_WARNING_TIME, in ticks.
warning_time: 300,
}));
g.send(&C::InitializeBorder(super::border::initialize(ctx.border)));
g.send(&self.time_packet(ctx.world, ctx.clock_rate));
g.send(&self.default_spawn(spawn));
let w = &ctx.world.weather;
@@ -1360,21 +1345,6 @@ impl Hub {
(!batch.is_empty()).then_some(batch)
}
/// Resend a chunk to everyone who has it (a block entity changed, relight).
pub fn resend_chunk(&mut self, world: &World, x: i32, z: i32) {
let Some(chunk) = world.chunks.get(&(x, z)) else {
return;
};
let body = self.encoder.body_in(chunk, world);
for g in self
.guests
.iter()
.filter(|g| g.sent_chunks.contains(&(x, z)))
{
g.sender.send(body.clone());
}
}
/// `ChunkHolder.broadcastChanges`' light part: the light sections that
/// changed in a column go to the players for whom it is on the border of
/// what they track (`ChunkMap.isChunkOnTrackedBorder`); the others light
+2 -6
View File
@@ -6,6 +6,7 @@
//! world that is not open to the network pays nothing.
mod advancements;
pub mod attributes;
pub mod border;
pub mod chunks;
mod command_order;
pub mod command_suggestions;
@@ -20,6 +21,7 @@ pub mod hub;
pub mod menu;
pub mod playerdata;
mod recipes;
pub mod scoreboard;
pub mod tracking;
pub mod waypoints;
@@ -272,9 +274,6 @@ impl Shared {
pub fn max_players(&self) -> usize {
self.max_players.load(Ordering::Relaxed)
}
pub fn set_max_players(&self, n: usize) {
self.max_players.store(n, Ordering::Relaxed);
}
pub fn release(&self, uuid: u128) {
self.online.lock().unwrap().retain(|(u, _)| *u != uuid);
}
@@ -513,9 +512,6 @@ impl Lan {
pub fn reserve(&self, uuid: u128) {
self.shared.reserved.lock().unwrap().insert(uuid);
}
pub fn set_motd(&self, motd: &str) {
*self.shared.motd.lock().unwrap() = motd.to_owned();
}
pub fn stop(&mut self) {
self.shared.stop.store(true, Ordering::Relaxed);
self.stop_listening();
+308
View File
@@ -0,0 +1,308 @@
//! `ServerScoreboard`: what a player's client knows of the server's
//! scoreboard. Every team goes to every player; an objective goes once it
//! sits in a display slot (`startTrackingObjective`: its objective, its
//! slots, then its scores) and leaves when it sits in none
//! (`stopTrackingObjective`). A joining player gets it all
//! (`PlayerList.updateEntireScoreboard`).
//!
//! A server's commands change the board in place; each tick a player is
//! sent the packets that turn what it was last sent into what it should
//! have now, which are the ones `ServerScoreboard`'s callbacks send.
use crate::scoreboard::{NumberFormat, RenderType, Scoreboard, component_tag, display_slots};
use crate::text::COLORS;
use horizon_protocol::packets::play::{
self, Clientbound as C, ResetScore, SetDisplayObjective, SetObjective, SetPlayerTeam, SetScore,
TeamParameters,
};
use horizon_world::nbt::Tag;
use std::collections::{BTreeMap, BTreeSet};
type Format = Option<play::NumberFormat>;
/// The scoreboard as one player's client has it.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct View {
/// The tracked objectives: display name, render type (1 hearts), format.
objectives: BTreeMap<String, (Tag, i32, Format)>,
/// `DisplaySlot` id to objective.
display: BTreeMap<i32, String>,
/// The tracked objectives' scores, by holder and objective.
scores: BTreeMap<(String, String), (i32, Option<Tag>, Format)>,
/// Every team: its parameters and players, in the team's order.
teams: BTreeMap<String, (TeamParameters, Vec<String>)>,
}
fn format(f: Option<&NumberFormat>) -> Format {
f.map(|f| match f {
NumberFormat::Blank => play::NumberFormat::Blank,
NumberFormat::Styled(s) => play::NumberFormat::Styled(crate::scoreboard::json_to_tag(s)),
NumberFormat::Fixed(c) => play::NumberFormat::Fixed(component_tag(c)),
})
}
impl View {
/// What the board's state gives a client.
pub fn of(board: &Scoreboard) -> Self {
let slots = display_slots();
let display: BTreeMap<i32, String> = board
.display
.iter()
.filter_map(|(slot, o)| Some((slots.iter().position(|s| s == slot)? as i32, o.clone())))
.collect();
let tracked: BTreeSet<&String> = display.values().collect();
let objectives = board
.objectives
.iter()
.filter(|o| tracked.contains(&o.name))
.map(|o| {
let render = i32::from(o.render_type == RenderType::Hearts);
(
o.name.clone(),
(
component_tag(&o.display_name),
render,
format(o.number_format.as_ref()),
),
)
})
.collect();
let scores = board
.scores
.iter()
.flat_map(|(holder, scores)| {
scores
.iter()
.filter(|(o, _)| tracked.contains(o))
.map(move |(o, s)| {
(
(holder.clone(), o.clone()),
(
s.value,
s.display.as_ref().map(component_tag),
format(s.number_format.as_ref()),
),
)
})
})
.collect();
let teams = board
.teams
.iter()
.map(|t| {
let params = TeamParameters {
display_name: component_tag(&t.display_name),
prefix: component_tag(&t.prefix),
suffix: component_tag(&t.suffix),
name_tag_visibility: t.nametag_visibility as i32,
collision_rule: t.collision_rule as i32,
color: t
.color
.as_deref()
.and_then(|c| COLORS.iter().position(|(_, n, _)| *n == c))
.map(|i| i as i32),
options: i8::from(t.allow_friendly_fire)
| (i8::from(t.see_friendly_invisibles) << 1),
};
(
t.name.clone(),
(params, t.players.iter().cloned().collect()),
)
})
.collect();
Self {
objectives,
display,
scores,
teams,
}
}
/// The packets that take a client from `self` to `next`.
pub fn changes(&self, next: &View) -> Vec<C> {
let mut out = Vec::new();
let team = |name: &str, method, parameters, players| {
C::SetPlayerTeam(SetPlayerTeam {
name: name.to_owned(),
method,
parameters,
players,
})
};
for name in self.teams.keys().filter(|n| !next.teams.contains_key(*n)) {
out.push(team(name, 1, None, Vec::new()));
}
for (name, (params, players)) in &next.teams {
let Some((was, had)) = self.teams.get(name) else {
out.push(team(name, 0, Some(params.clone()), players.clone()));
continue;
};
if was != params {
out.push(team(name, 2, Some(params.clone()), Vec::new()));
}
let joined: Vec<_> = players
.iter()
.filter(|p| !had.contains(p))
.cloned()
.collect();
if !joined.is_empty() {
out.push(team(name, 3, None, joined));
}
let left: Vec<_> = had
.iter()
.filter(|p| !players.contains(p))
.cloned()
.collect();
if !left.is_empty() {
out.push(team(name, 4, None, left));
}
}
for (name, display) in &next.objectives {
let method = match self.objectives.get(name) {
None => 0,
Some(was) if was != display => 2,
Some(_) => continue,
};
out.push(C::SetObjective(SetObjective {
name: name.clone(),
method,
display: Some(display.clone()),
}));
}
let slots: BTreeSet<i32> = self
.display
.keys()
.chain(next.display.keys())
.copied()
.collect();
for slot in slots {
let objective = next.display.get(&slot);
if self.display.get(&slot) != objective {
out.push(C::SetDisplayObjective(SetDisplayObjective {
slot,
objective: objective.cloned().unwrap_or_default(),
}));
}
}
for ((holder, objective), (value, display, number_format)) in &next.scores {
let key = (holder.clone(), objective.clone());
if self.scores.get(&key) != Some(&(*value, display.clone(), number_format.clone())) {
out.push(C::SetScore(SetScore {
owner: holder.clone(),
objective: objective.clone(),
score: *value,
display: display.clone(),
number_format: number_format.clone(),
}));
}
}
for (holder, objective) in self.scores.keys() {
let key = (holder.clone(), objective.clone());
if !next.scores.contains_key(&key) && next.objectives.contains_key(objective) {
out.push(C::ResetScore(ResetScore {
owner: holder.clone(),
objective: Some(objective.clone()),
}));
}
}
for name in self
.objectives
.keys()
.filter(|n| !next.objectives.contains_key(*n))
{
out.push(C::SetObjective(SetObjective {
name: name.clone(),
method: 1,
display: None,
}));
}
out
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn methods(packets: &[C]) -> Vec<String> {
packets
.iter()
.map(|p| match p {
C::SetObjective(o) => format!("objective {} {}", o.name, o.method),
C::SetDisplayObjective(d) => format!("display {} {}", d.slot, d.objective),
C::SetScore(s) => format!("score {} {} {}", s.owner, s.objective, s.score),
C::ResetScore(r) => format!("reset {} {:?}", r.owner, r.objective),
C::SetPlayerTeam(t) => format!("team {} {} {:?}", t.name, t.method, t.players),
_ => "other".into(),
})
.collect()
}
#[test]
fn a_shown_objective_goes_with_its_scores_and_leaves_when_hidden() {
let mut board = Scoreboard::default();
board.add_objective(
"audit",
"dummy",
json!("Audit"),
RenderType::Integer,
false,
None,
);
board.score_mut("Alpha", "audit").value = 7;
let empty = View::default();
// Not displayed: not tracked, nothing sent.
let hidden = View::of(&board);
assert!(empty.changes(&hidden).is_empty());
board.set_display_objective("sidebar", Some("audit"));
let shown = View::of(&board);
assert_eq!(
methods(&hidden.changes(&shown)),
[
"objective audit 0",
"display 1 audit",
"score Alpha audit 7"
]
);
board.score_mut("Alpha", "audit").value = 12;
board.score_mut("Beta", "audit").value = 3;
board.reset_one("Beta", "audit");
let changed = View::of(&board);
assert_eq!(methods(&shown.changes(&changed)), ["score Alpha audit 12"]);
board.reset_one("Alpha", "audit");
let reset = View::of(&board);
assert_eq!(
methods(&changed.changes(&reset)),
["reset Alpha Some(\"audit\")"]
);
board.set_display_objective("sidebar", None);
assert_eq!(
methods(&reset.changes(&View::of(&board))),
["display 1 ", "objective audit 1"]
);
}
#[test]
fn teams_go_to_everyone_with_their_players() {
let mut board = Scoreboard::default();
board.add_team("red");
board.add_to_team("Alpha", "red");
let first = View::of(&board);
assert_eq!(
methods(&View::default().changes(&first)),
["team red 0 [\"Alpha\"]"]
);
board.add_to_team("Beta", "red");
board.remove_from_team("Alpha");
let second = View::of(&board);
assert_eq!(
methods(&first.changes(&second)),
["team red 3 [\"Beta\"]", "team red 4 [\"Alpha\"]"]
);
board.remove_team("red");
assert_eq!(
methods(&second.changes(&View::of(&board))),
["team red 1 []"]
);
}
}
-6
View File
@@ -77,12 +77,6 @@ pub fn apply_deprecated(map: &mut HashMap<String, String>, json: &[u8]) {
}
impl Language {
pub fn from_map(code: &str, map: HashMap<String, String>) -> Self {
Self {
code: code.to_owned(),
map,
}
}
/// ClientLanguage.loadFrom: en_us first, then the selected language, each
/// from every namespace and every source in priority order (later sources
/// override).
+1 -1
View File
@@ -203,7 +203,7 @@ impl LightTables {
Ok(tables)
}
/// Assembled tables (tests and benchmarks): derives the packed light cache.
#[allow(dead_code)]
#[cfg(test)]
fn from_parts(cells: Vec<Cell>, occludes: Vec<bool>, faces: usize) -> Self {
let mut tables = Self {
cells,
-4
View File
@@ -239,10 +239,6 @@ pub enum ArmPose {
/// Raising a trident to throw it (or to launch with Riptide).
ThrowTrident,
}
/// HumanoidModel.setupAnim for piglins: `PiglinModel` poses the arms itself.
pub fn humanoid_item(p: &mut Poses, s: &State, _holding: bool) {
humanoid(p, s, &Hum::new(ArmPose::Empty, ArmPose::Empty));
}
/// HumanoidModel.setupAnim with empty hands (endermen).
pub fn humanoid_pub(p: &mut Poses, s: &State, _m: &Mob) {
humanoid(p, s, &Hum::new(ArmPose::Empty, ArmPose::Empty));
@@ -152,10 +152,6 @@ pub fn protector(heart: &mut CreakingHeart, host: &impl HeartHost) -> Option<u32
}
None
}
/// `isProtector`.
pub fn is_protector(heart: &mut CreakingHeart, host: &impl HeartHost, id: u32) -> bool {
protector(heart, host) == Some(id)
}
fn distance_to_creaking(heart: &mut CreakingHeart, pos: [i32; 3], host: &impl HeartHost) -> f64 {
protector(heart, host)
.and_then(|id| host.mob(id))
-37
View File
@@ -76,9 +76,6 @@ pub struct GoalSelector {
locked: [Option<usize>; 4],
pub disabled: u8,
}
fn flag_index(f: u8) -> usize {
f.trailing_zeros() as usize
}
impl GoalSelector {
pub fn add(&mut self, priority: i32, goal: impl Goal + 'static) {
self.goals.push(Wrapped {
@@ -174,10 +171,6 @@ impl GoalSelector {
}
self.locked = [None; 4];
}
#[allow(dead_code)]
fn locked_by(&self, flag: u8) -> Option<usize> {
self.locked[flag_index(flag)]
}
}
// --- random positions (DefaultRandomPos / LandRandomPos / RandomPos) -------
@@ -565,36 +558,6 @@ impl Mob {
m.land_up_out_of_solid(w, p)
})
}
/// LandRandomPos.getPosTowards
pub fn land_random_pos_towards(
&mut self,
w: &MobWorld,
h: i32,
v: i32,
to: [f64; 3],
) -> Option<[f64; 3]> {
let (xd, zd) = (to[0] - self.position.x, to[2] - self.position.z);
self.pick_best(w, |m| {
let d = m.random_direction_within(
0.0,
f64::from(h),
v,
0,
xd,
zd,
std::f64::consts::FRAC_PI_2,
)?;
let p = m.toward(f64::from(h), d);
if p[1] < crate::chunk::MIN_Y
|| p[1] >= 320
|| m.restricted(f64::from(h), p)
|| !m.stable_destination(w, p)
{
return None;
}
m.land_up_out_of_solid(w, p)
})
}
pub fn target_info(&self, w: &MobWorld) -> Option<TargetInfo> {
self.ai.target.and_then(|t| w.target_info(t))
}
@@ -17,7 +17,6 @@ use horizon_core::{
// Happy ghast state: `head` the harness, `scratch[0]` 1 once set up as a
// baby and 2 as an adult, `ai.home` the restriction, `counter`
// the end tick of the follow-an-adult range pick.
pub const BABY_SCALE: f64 = 0.2375;
/// `Attributes.FLYING_SPEED` and the speed `travel` uses (`* 5 / 3`).
pub const FLYING_SPEED: f64 = 0.05;
pub const AIR_SPEED: f32 = 0.05 * 5.0 / 3.0;
@@ -250,10 +250,6 @@ pub fn nearest_players(m: &Mob) -> Vec<Who> {
.and_then(|b| b.mem.nearest_players.value())
.unwrap_or_default()
}
/// The damage the brain remembers (`HURT_BY`).
pub fn hurt_by_present(m: &Mob) -> bool {
brain(m).is_some_and(|b| b.mem.hurt_by.present())
}
/// `HURT_BY`'s damage source entity, if a living one.
fn hurt_by_entity(m: &Mob, w: &MobWorld) -> Option<Who> {
let t = brain(m)?.mem.hurt_by.value()?;
@@ -76,14 +76,6 @@ pub fn finalize(m: &mut Mob, warm_ocean: bool) {
m.extra.variant = u8::from(warm_ocean);
}
}
/// `checkNautilusSpawnRules`: 5 to 25 blocks below sea level, water below
/// and above.
pub fn spawn_rules_ok(w: &MobWorld, x: i32, y: i32, z: i32) -> bool {
let sea = 63;
(sea - 25..=sea - 5).contains(&y)
&& w.fluid(x, y - 1, z) == Fluid::Water
&& w.block_name(x, y + 1, z) == "minecraft:water"
}
/// `getControllingPassenger`: a player on a saddled nautilus.
pub fn controlled(m: &Mob) -> bool {
m.rider.is_some() && m.extra.saddled
-22
View File
@@ -582,26 +582,4 @@ impl Mob {
NavKind::Amphibious => !w.facts.is_air(w.world.block(p[0], p[1] - 1, p[2])),
}
}
pub fn should_recompute_path(&self, p: [i32; 3]) -> bool {
if self.ai.nav.delayed_recompute {
return false;
}
let Some(path) = &self.ai.nav.path else {
return false;
};
if path.is_done() || path.nodes.is_empty() {
return false;
}
let Some(end) = path.end() else { return false };
let mid = [
(f64::from(end.x) + self.position.x) / 2.0,
(f64::from(end.y) + self.position.y) / 2.0,
(f64::from(end.z) + self.position.z) / 2.0,
];
let d = (f64::from(p[0]) + 0.5 - mid[0]).powi(2)
+ (f64::from(p[1]) + 0.5 - mid[1]).powi(2)
+ (f64::from(p[2]) + 0.5 - mid[2]).powi(2);
let r = (path.nodes.len() - path.next) as f64;
d < r * r
}
}
@@ -769,19 +769,6 @@ pub fn weighted_pick(list: &[SpawnEntry], random: &mut impl RandomSource) -> Opt
None
}
/// `NaturalSpawner.getRandomSpawnMobAt`.
pub fn random_spawn_mob_at(
list: &[SpawnEntry],
category: &str,
reduced_water_ambient: bool,
random: &mut impl RandomSource,
) -> Option<SpawnEntry> {
if category == "water_ambient" && reduced_water_ambient && random.next_float() < 0.98 {
return None;
}
weighted_pick(list, random)
}
/// `SpawnerData.count().sample(random)`: a constant draws nothing.
pub fn sample_count(entry: &SpawnEntry, random: &mut impl RandomSource) -> u32 {
if entry.constant {
@@ -30,25 +30,6 @@ pub struct BiomeFacts {
pub fn placement_ok(species: Species, w: &MobWorld, x: i32, y: i32, z: i32) -> bool {
super::spawn_rules::is_spawn_position_ok(species, w, x, y, z)
}
/// `SpawnPlacements.checkSpawnRules` for a natural spawn.
pub fn spawn_rules_ok(
species: Species,
w: &MobWorld,
random: &mut impl RandomSource,
x: i32,
y: i32,
z: i32,
) -> bool {
super::spawn_rules::check_spawn_rules(
species,
w,
super::spawn_rules::Reason::Natural,
random,
x,
y,
z,
)
}
/// Mob.finalizeSpawn for natural, chunk-generation and summoned mobs.
/// `DifficultyInstance`: the local difficulty at a position.
#[derive(Clone, Copy, Debug)]
@@ -10,7 +10,7 @@
//! other `GateBehavior`s shuffle with a random of their own, seeded with
//! `Brain::shuffle_seed` when the brain is built.
use super::{
Mob, MobEvent, MobWorld, Seen, Species, Who,
Mob, MobEvent, MobWorld, Species, Who,
path::{Path, PathNode},
};
use horizon_core::{
@@ -4156,10 +4156,6 @@ pub fn woken(m: &mut Mob, now: i64) {
pub fn potential_job_site(m: &Mob) -> Option<[i32; 3]> {
mem_ref(m).and_then(|mm| mm.potential_job_site.value())
}
/// Whether a seen mob is a villager wanting to breed (`AgeableMob::canBreed`).
pub fn seen_can_breed(s: &Seen) -> bool {
s.species == Species::Villager && s.in_love
}
/// The memories other villagers read: the interaction target, the path's
/// nodes (while it is not done), whether a golem was seen lately and the
/// last sleep.
+1 -7
View File
@@ -1,7 +1,7 @@
//! What mobs read from the level: block solidity, ray clipping for line of
//! sight (`ClipContext.Block.COLLIDER`), sky visibility, light-dependent
//! values and the positions of other entities.
use super::{MobWorld, Seen, Species, Who, data};
use super::{MobWorld, Seen, Who, data};
use crate::{
blocks::{BlockFacts, Fluid},
collisions::SceneCollisions,
@@ -269,12 +269,6 @@ impl MobWorld<'_> {
});
v.into_iter()
}
pub fn count_species(&self, species: Species) -> usize {
self.others
.iter()
.filter(|s| s.species == species && s.alive)
.count()
}
}
/// Level.clip with VISUAL shapes and no fluids: the block the segment first
+6
View File
@@ -307,6 +307,9 @@ pub struct PlayerMotion {
pub hurt_log: Vec<crate::health::HurtRecord>,
/// The last melee attacks made on mobs, newest last.
pub attack_log: Vec<crate::health::AttackRecord>,
/// The level's world border, whose walls stop the player's movement
/// from inside (the game keeps it current; None: no border).
pub border: Option<horizon_core::geometry::border::BorderGeometry>,
}
fn attribute_error(error: impl std::fmt::Debug) -> io::Error {
io::Error::other(format!("movement attribute: {error:?}"))
@@ -461,6 +464,7 @@ impl PlayerMotion {
powder_snow_entered: Vec::new(),
hurt_log: Vec::new(),
attack_log: Vec::new(),
border: None,
})
}
/// `Entity.getTicksRequiredToFreeze`.
@@ -678,9 +682,11 @@ impl MotionWorld<'_, '_, '_> {
fn movement_collisions(
&self,
) -> crate::collisions::EntityCollisions<'_, SceneCollisions<'_, '_>> {
let at = [self.player.position.x, self.player.position.z];
crate::collisions::EntityCollisions {
blocks: self.collisions(),
entities: self.entities,
border: self.player.border.as_ref().map(|b| (b, at)),
}
}
/// `Level.noCollision(player, bounds)`: blocks and the host's entity boxes.
-5
View File
@@ -804,11 +804,6 @@ impl SelectionModel {
false
}
}
/// Whether activating the entry asks first (`handlePackSelection`'s
/// ConfirmScreen for an incompatible pack).
pub fn needs_confirmation(&self, selected: bool, i: usize) -> bool {
self.can_select(selected, i) && !self.unselected[i].compatible
}
/// `moveUp` / `moveDown` when allowed.
pub fn move_by(&mut self, selected: bool, i: usize, up: bool) -> bool {
let ok = if up {
+8
View File
@@ -1158,6 +1158,8 @@ pub struct ParticleEngine {
starters: Vec<Starter>,
/// Local sounds requested by particles (dripstone drips): (event, position, volume, pitch).
pub sounds: Vec<(&'static str, [f64; 3], f32, f32)>,
/// How many of each type were made, for `horizon-ctl status`.
made: std::collections::BTreeMap<&'static str, u64>,
/// The item particles' sprites (`BreakingItemParticle`'s slime ball, snowball
/// and cobweb models, resolved for the ground), one per model layer.
pub item_sprites: HashMap<ParticleType, Vec<String>>,
@@ -1183,6 +1185,7 @@ impl ParticleEngine {
starters: Vec::new(),
camera: [0.0; 3],
sounds: Vec::new(),
made: Default::default(),
item_sprites: HashMap::new(),
};
let dir = root.join("assets/minecraft/particles");
@@ -1449,9 +1452,14 @@ impl ParticleEngine {
pub fn create(&mut self, options: &ParticleOptions, p: [f64; 3], v: [f64; 3]) {
let seed = self.seeds.next_long();
if let Some(particle) = self.make(options, p, v, seed) {
*self.made.entry(options.ty.name()).or_default() += 1;
self.pending.push(particle);
}
}
/// How many particles of each type were made so far.
pub fn made(&self) -> &std::collections::BTreeMap<&'static str, u64> {
&self.made
}
/// Parity probes: seed the provider (`ParticleEngine.random`), level and
/// `SpellParticle.RANDOM` generators.
pub fn seed_randoms(&mut self, provider: i64, level: i64, spell: i64) {
-15
View File
@@ -384,21 +384,6 @@ impl Book {
order,
}
}
/// Which book a recipe id belongs to.
pub fn book_of(&self, id: &str) -> Option<BookType> {
let e = self.entries.iter().find(|e| e.id == id)?;
Some(match e.category {
Category::CraftingBuilding
| Category::CraftingRedstone
| Category::CraftingEquipment
| Category::CraftingMisc => BookType::Crafting,
Category::FurnaceFood | Category::FurnaceBlocks | Category::FurnaceMisc => {
BookType::Furnace
}
Category::BlastBlocks | Category::BlastMisc => BookType::BlastFurnace,
Category::SmokerFood => BookType::Smoker,
})
}
/// `RecipeDisplayEntry.canCraft`: the recipe's placement ingredients
/// (`craftingRequirements`) can all be found in `stock`.
pub fn can_craft(&self, entry: &Entry, stock: &crate::menu::place::Stacked) -> bool {
-6
View File
@@ -750,12 +750,6 @@ fn heightmaps(chunk: &Chunk, tables: &SaveTables) -> Tag {
)
}))
}
/// The heightmaps a ClientboundLevelChunkPacketData carries (the types with
/// sendToClient: WORLD_SURFACE, MOTION_BLOCKING, MOTION_BLOCKING_NO_LEAVES),
/// as (network id, packed longs) in Heightmap.Types order.
pub fn client_heightmaps(chunk: &Chunk, tables: &SaveTables) -> Vec<(i32, Vec<i64>)> {
client_heightmaps_in(&chunk.sections, tables, MIN_Y, SECTIONS as i32 * 16)
}
/// The client heightmaps of a column's sections, in a level from `min_y`,
/// `height` blocks high.
pub fn client_heightmaps_in(
-5
View File
@@ -78,7 +78,6 @@ pub const RESONANCE: [&str; 15] = [
];
pub const SHRIEK: &str = "minecraft:shriek";
pub const TENDRILS_CLICKING: &str = "minecraft:sculk_sensor_tendrils_clicking";
pub const NO_VIBRATION_FREQUENCY: i32 = 0;
/// `VibrationSystem.getGameEventFrequency`.
pub fn frequency(event: &str) -> i32 {
@@ -567,10 +566,6 @@ pub struct WardenSpawnTracker {
}
impl WardenSpawnTracker {
pub const MAX_WARNING_LEVEL: i32 = 4;
/// Blocks around a shrieker within which players are warned.
pub const PLAYER_SEARCH_RADIUS: f64 = 16.0;
/// `AABB.ofSize(centre, 48, 48, 48)` for an existing warden.
pub const WARNING_CHECK_DIAMETER: f64 = 48.0;
const DECREASE_EVERY: i32 = 12000;
const INCREASE_COOLDOWN: i32 = 200;
pub fn tick(&mut self) {
-4
View File
@@ -81,10 +81,6 @@ pub fn sound_source(event: &str) -> usize {
index("master")
}
}
/// Volume multiplier of an event's source (master applied separately).
pub fn event_volume(event: &str) -> f32 {
source_volume(sound_source(event))
}
/// Volume multiplier of a sound source by index.
pub fn source_volume(i: usize) -> f32 {
if i == 0 {
-3
View File
@@ -317,9 +317,6 @@ impl TabList {
self.visible = visible;
}
}
pub fn is_visible(&self) -> bool {
self.visible
}
/// `reset`.
pub fn reset(&mut self) {
self.header = None;
-3
View File
@@ -455,9 +455,6 @@ impl Text {
}
out
}
pub fn char_count(&self) -> usize {
self.spans.iter().map(|s| s.text.chars().count()).sum()
}
}
/// The style fields of a component's JSON.
-20
View File
@@ -1630,26 +1630,6 @@ fn caret_field<'a>(
_ => None,
}
}
/// `yyyy/MM/dd HH:mm` (UTC) for a modification time in Unix seconds.
pub fn date_label(secs: u64) -> String {
date_string(secs)
}
fn date_string(secs: u64) -> String {
// Civil date from Unix time (days-from-civil inverse), UTC.
let days = (secs / 86400) as i64;
let (h, m) = ((secs % 86400) / 3600, (secs % 3600) / 60);
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z - era * 146_097;
let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
let y = yoe + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let mo = if mp < 10 { mp + 3 } else { mp - 9 };
let y = if mo <= 2 { y + 1 } else { y };
format!("{y}-{mo:02}-{d:02} {h:02}:{m:02}")
}
#[cfg(test)]
mod classic_tests {
-4
View File
@@ -854,10 +854,6 @@ impl EditBox {
text_color: rgba(224, 224, 224, 255),
}
}
/// When the field gained focus, for the cursor's blink.
pub fn focused_since(&mut self, at: Instant) {
self.focused_at = at;
}
pub fn inner_width(&self) -> f32 {
if self.bordered {
self.width - 8.0
+4 -1
View File
@@ -7,7 +7,6 @@ pub use horizon_core::geometry::border::BorderStatus;
/// `WorldBorder.MAX_SIZE` (the float 5.999997E7 as a double).
pub const MAX_SIZE: f64 = 59_999_968.0;
pub const MAX_CENTER: f64 = 2.999_998_4e7;
/// `BorderStatus.getColor`: the wall colour.
pub fn status_color(status: BorderStatus) -> u32 {
@@ -81,6 +80,10 @@ impl PartialEq for WorldBorder {
}
}
impl WorldBorder {
/// Its extent, for collisions.
pub fn geometry(&self) -> &BorderGeometry {
&self.geometry
}
pub fn center(&self) -> [f64; 2] {
self.geometry.center()
}
+1
View File
@@ -200,6 +200,7 @@ impl Server {
tick_frozen: false,
tick_steps: (0, 0),
collision: None,
border: &horizon_client::worldborder::WorldBorder::default(),
};
let events = self.hub.tick(&mut ctx);
for event in events {
@@ -168,9 +168,6 @@ impl Beardifier {
self.kernel_junctions = junctions;
self
}
pub fn affected_bounds(&self) -> Option<StructureBounds> {
self.affected
}
fn sample_unchecked(&self, [x, y, z]: [i32; 3]) -> f32 {
let mut value = 0.;
// The kernel is a process-wide constant; resolving it once keeps the
@@ -13,8 +13,6 @@ impl ShapeOp {
pub const XOR: Self = Self(6);
pub const ONLY_FIRST: Self = Self(4);
pub const ONLY_SECOND: Self = Self(2);
pub const FIRST: Self = Self(12);
pub const SECOND: Self = Self(10);
pub const fn from_truth_table(bits: u8) -> Self {
Self(bits & 15)
}
-28
View File
@@ -466,34 +466,6 @@ impl PalettedContainer {
}
}
}
/// Block ids as 16-bit values (callers whose registry fits in 16 bits).
pub fn unpack_u16(&self, out: &mut [u16; 4096]) {
debug_assert_eq!(self.strategy.entries(), 4096);
match &self.palette {
Palette::Single(value) => out.fill(*value as u16),
Palette::List(list) => {
let bits = usize::from(self.bits);
let per = 64 / bits;
let m = mask(self.bits);
for (chunk, &word) in out.chunks_mut(per).zip(&self.words) {
for (slot, cell) in chunk.iter_mut().enumerate() {
let id = ((word >> (slot * bits)) & m) as usize;
*cell = list[id] as u16;
}
}
}
Palette::Global => {
let bits = usize::from(self.bits);
let per = 64 / bits;
let m = mask(self.bits);
for (chunk, &word) in out.chunks_mut(per).zip(&self.words) {
for (slot, cell) in chunk.iter_mut().enumerate() {
*cell = ((word >> (slot * bits)) & m) as u16;
}
}
}
}
}
/// A container holding `values` in the smallest configuration for their
/// distinct count, with palette ids in first-occurrence order, like a
/// container unpacked from disk.
@@ -91,9 +91,6 @@ impl<C: WorldGenTickContainers> WorldGenTickAccess<C> {
pub fn containers_mut(&mut self) -> &mut C {
&mut self.containers
}
pub fn into_containers(self) -> C {
self.containers
}
pub fn schedule(&mut self, tick: ScheduledTick) -> Result<bool, C::Error> {
Ok(self.containers.container_at(tick.pos)?.schedule(tick))
}
-3
View File
@@ -636,7 +636,4 @@ impl LevelTicks {
pub fn copy_area(&mut self, area: TickArea, offset: BlockPos) {
self.schedule_copy(self.area_ticks(area), offset);
}
pub fn copy_area_from(&mut self, source: &Self, area: TickArea, offset: BlockPos) {
self.schedule_copy(source.area_ticks(area), offset);
}
}
-10
View File
@@ -296,14 +296,4 @@ impl Tunnel {
})?;
Ok((port, thread))
}
/// The protected stream itself (tests, or a client that reads it
/// directly).
pub fn into_stream(
self,
) -> (
crypto::SecureReader<TcpStream>,
crypto::SecureWriter<TcpStream>,
) {
self.secure
}
}
+141 -1
View File
@@ -7,7 +7,7 @@ use crate::{
Vec3d, Writer,
},
chunk::{ChunkData, LightData},
entity_data::{EntityData, Value},
entity_data::{EntityData, Particle, Value},
item::{Hashed, HashedSlot, Slot, Stack},
packet, packet_enum,
packets::{
@@ -892,6 +892,116 @@ impl Codec<SetObjective> for SetObjective {
}
}
}
/// ClientboundLevelParticlesPacket: a particle, whether it ignores the
/// client's particle setting (`overrideLimiter`) and its distance limit
/// (`alwaysShow`), where, the spread and the speed on each axis, how many
/// (0: one, moving by speed times spread) and the randomization type
/// (0 default: gaussian spread and speed).
#[derive(Clone, Debug, PartialEq)]
pub struct LevelParticles {
pub particle: Particle,
pub override_limiter: bool,
pub always_show: bool,
pub pos: [f64; 3],
pub dist: [f32; 3],
pub max_speed: [f32; 3],
pub count: i32,
pub randomization: i32,
}
impl Codec<LevelParticles> for LevelParticles {
fn read(r: &mut Reader) -> Result<Self> {
Ok(Self {
particle: Particle::read(r)?,
override_limiter: r.bool()?,
always_show: r.bool()?,
pos: Vec3d::read(r)?,
dist: [r.f32()?, r.f32()?, r.f32()?],
max_speed: [r.f32()?, r.f32()?, r.f32()?],
count: r.varint()?,
randomization: r.varint()?,
})
}
fn write(v: &Self, w: &mut Writer) {
v.particle.write(w);
w.bool(v.override_limiter);
w.bool(v.always_show);
Vec3d::write(&v.pos, w);
for f in v.dist.iter().chain(&v.max_speed) {
w.f32(*f);
}
w.varint(v.count);
w.varint(v.randomization);
}
}
/// `ExplosionParticleInfo` in a `WeightedList`: a particle the blast
/// scatters, its scaling and speed, then its weight.
#[derive(Clone, Debug, PartialEq)]
pub struct ExplosionParticle {
pub particle: Particle,
pub scaling: f32,
pub speed: f32,
pub weight: i32,
}
/// ClientboundExplodePacket: the centre, radius and blocks destroyed, the
/// push the receiving player takes, the particle at the centre, the sound,
/// the particles the blast scatters, and whether the sound plays.
#[derive(Clone, Debug, PartialEq)]
pub struct Explode {
pub center: [f64; 3],
pub radius: f32,
pub block_count: i32,
pub knockback: Option<[f64; 3]>,
pub particle: Particle,
pub sound: (i32, Option<(String, Option<f32>)>),
pub block_particles: Vec<ExplosionParticle>,
pub play_sound: bool,
}
impl Codec<Explode> for Explode {
fn read(r: &mut Reader) -> Result<Self> {
let center = Vec3d::read(r)?;
let radius = r.f32()?;
let block_count = r.i32()?;
let knockback = <Opt<Vec3d>>::read(r)?;
let particle = Particle::read(r)?;
let sound = SoundHolder::read(r)?;
let n = r.varint()?;
let mut block_particles = Vec::new();
for _ in 0..n {
block_particles.push(ExplosionParticle {
particle: Particle::read(r)?,
scaling: r.f32()?,
speed: r.f32()?,
weight: r.varint()?,
});
}
Ok(Self {
center,
radius,
block_count,
knockback,
particle,
sound,
block_particles,
play_sound: r.bool()?,
})
}
fn write(v: &Self, w: &mut Writer) {
Vec3d::write(&v.center, w);
w.f32(v.radius);
w.i32(v.block_count);
<Opt<Vec3d>>::write(&v.knockback, w);
v.particle.write(w);
SoundHolder::write(&v.sound, w);
w.varint(v.block_particles.len() as i32);
for b in &v.block_particles {
b.particle.write(w);
w.f32(b.scaling);
w.f32(b.speed);
w.varint(b.weight);
}
w.bool(v.play_sound);
}
}
/// `ClientboundSetPlayerTeamPacket.Parameters`.
#[derive(Clone, Debug, PartialEq)]
pub struct TeamParameters {
@@ -1577,6 +1687,8 @@ packet_enum!(Clientbound, crate::ids::play::clientbound {
TickingStep(TickingStep) = TICKING_STEP,
UpdateAdvancements(UpdateAdvancements) = UPDATE_ADVANCEMENTS,
UpdateAttributes(UpdateAttributes) = UPDATE_ATTRIBUTES,
LevelParticles(LevelParticles) = LEVEL_PARTICLES,
Explode(Explode) = EXPLODE,
UpdateMobEffect(UpdateMobEffect) = UPDATE_MOB_EFFECT,
UpdateTags(UpdateTags) = UPDATE_TAGS,
TrackedWaypoint(TrackedWaypoint) = WAYPOINT,
@@ -2338,6 +2450,34 @@ mod tests {
passengers: vec![3, 300],
}),
Clientbound::SetEntityLink(SetEntityLink { source: 2, dest: 0 }),
Clientbound::LevelParticles(LevelParticles {
particle: Particle {
id: 21,
data: Some(crate::entity_data::ParticleData::ColorScale(0xFF0000, 1.5)),
},
override_limiter: true,
always_show: false,
pos: [0.5, 101.0, 3.0],
dist: [0.2, 0.0, 0.2],
max_speed: [0.0; 3],
count: 60,
randomization: 0,
}),
Clientbound::Explode(Explode {
center: [1.0, 2.0, 3.0],
radius: 4.0,
block_count: 12,
knockback: Some([0.5, 0.1, 0.0]),
particle: Particle { id: 29, data: None },
sound: (-1, Some(("minecraft:entity.generic.explode".into(), None))),
block_particles: vec![ExplosionParticle {
particle: Particle { id: 69, data: None },
scaling: 0.5,
speed: 1.0,
weight: 1,
}],
play_sound: true,
}),
Clientbound::ProjectilePower(ProjectilePower { id: 4, power: 0.1 }),
Clientbound::SetEquipment(SetEquipment {
id: 2,
@@ -190,14 +190,6 @@ impl UserCache {
result
}
/// `get(UUID)`: a cached player by id (expired or not).
pub fn get_by_id(&mut self, id: u128) -> Option<NameAndId> {
let index = *self.by_uuid.get(&id)?;
self.operations += 1;
self.infos[index].last_access = self.operations;
Some(self.infos[index].user.clone())
}
/// The file's text: the 1000 most recently used entries, most recent
/// first, as Gson writes them (compact, HTML-safe).
pub fn to_json(&self) -> String {
@@ -416,11 +416,6 @@ pub type WhiteList = UserList<WhiteEntry>;
pub type BanList = UserList<BanEntry<NameAndId>>;
pub type IpBanList = UserList<BanEntry<String>>;
/// IpBanList.getIpFromAddress.
pub fn ip_of(address: &std::net::SocketAddr) -> String {
address.ip().to_string()
}
#[cfg(test)]
mod tests {
use super::*;
+24 -2
View File
@@ -199,8 +199,11 @@ pub fn preprocess(
let (start, end) = (token.location.start, token.location.end);
let at = line_of(start);
if at > line {
// Lines the preprocessor left empty stay empty lines, so a value
// continued with `\` before an `#else` (Photon's
// `moon_phase_brightness`) ends there, as in Iris.
if line > 0 {
out.push('\n');
out.extend(std::iter::repeat_n('\n', at - line));
}
line = at;
} else if last_end != Some(start) {
@@ -799,7 +802,26 @@ b = 1
};
let values = OptionValues::default();
let out = preprocess(text, &env, &set, &values).unwrap();
assert_eq!(out, "a = 0.75\nb = 1\n");
let lines: Vec<&str> = out.lines().filter(|l| !l.is_empty()).collect();
assert_eq!(lines, ["a = 0.75", "b = 1"]);
// Photon ends an `#if`'d value with `) \` before `#else`: the value
// stops at the empty line the directive leaves.
let text = "\
#if FOG == 0
a = if( \\
moonPhase == 0, 1.0, \\
2.0 \\
) \\
#else
a = 1.0
#endif
b = 2
";
let out = preprocess(text, &env, &set, &values).unwrap();
let parsed = Properties::parse(&out);
assert_eq!(parsed.get("a"), Some("if( moonPhase == 0, 1.0, 2.0 ) "));
assert_eq!(parsed.get("b"), Some("2"));
assert_eq!(
jcpp_condition("#elif FOG == 0.75 && X > 2.5", &set, &values),
"#elif 0 == 0 && X > 2"
+236 -23
View File
@@ -17,8 +17,9 @@
//! (`vaPosition`, `modelViewMatrix`, ...) are declared;
//! - legacy texture calls are renamed, `shadow2D` returns a `vec4` again and a
//! swizzled shadow lookup is widened first (naga has no scalar swizzle);
//! - vertex and compute `texture(s, uv)` calls without an explicit LOD become
//! `textureLod(s, uv, 0.0)` so naga doesn't reject implicit derivatives;
//! - outside fragment programs, `texture`, `textureProj` and their `Offset`
//! forms become their `Lod` forms at level 0 (no derivatives there; naga
//! refuses the implicit ones), a bias dropped;
//! - global initialisers run at the start of `main` (drivers accept
//! non-constant ones), unsized global arrays are sized from them;
//! - `isnan`, `isinf` and `modf` are helper functions (WGSL has none);
@@ -380,9 +381,10 @@ pub fn translate(
stage: naga_stage,
defines: Default::default(),
};
let module = naga::front::glsl::Frontend::default()
let mut module = naga::front::glsl::Frontend::default()
.parse(&options, &glsl)
.map_err(|e| first_lines(&e.emit_to_string(&glsl)))?;
unpad_private_arrays(&mut module);
let info = naga::valid::Validator::new(
naga::valid::ValidationFlags::all(),
naga::valid::Capabilities::all(),
@@ -508,6 +510,79 @@ fn negative_constant(e: &ast::Expr) -> bool {
}
}
/// naga's GLSL front end lays every struct out as std140, so an array field
/// of a struct that never reaches a buffer (Photon's ACES spline parameters,
/// `float[6]`) gets a stride of 16, and constructing it from a `float[6](..)`
/// (stride 4) fails validation. Give such fields their natural stride.
fn unpad_private_arrays(module: &mut naga::Module) {
use naga::TypeInner as T;
let mut shared = HashSet::new();
let mut stack: Vec<_> = module
.global_variables
.iter()
.filter(|(_, v)| {
matches!(
v.space,
naga::AddressSpace::Uniform
| naga::AddressSpace::Storage { .. }
| naga::AddressSpace::Immediate
)
})
.map(|(_, v)| v.ty)
.collect();
while let Some(ty) = stack.pop() {
if !shared.insert(ty) {
continue;
}
match &module.types[ty].inner {
T::Struct { members, .. } => stack.extend(members.iter().map(|m| m.ty)),
T::Array { base, .. } | T::BindingArray { base, .. } => stack.push(*base),
_ => {}
}
}
let mut layouter = naga::proc::Layouter::default();
if layouter.update(module.to_ctx()).is_err() {
return;
}
let structs: Vec<_> = module
.types
.iter()
.filter(|(h, t)| !shared.contains(h) && matches!(t.inner, T::Struct { .. }))
.map(|(h, _)| h)
.collect();
for ty in structs {
let mut new = module.types[ty].clone();
let T::Struct { members, .. } = &mut new.inner else {
continue;
};
let mut changed = false;
for m in members.iter_mut() {
let T::Array { base, size, stride } = module.types[m.ty].inner else {
continue;
};
let natural = layouter[base].to_stride();
if stride != natural {
let span = module.types.get_span(m.ty);
m.ty = module.types.insert(
naga::Type {
name: None,
inner: T::Array {
base,
size,
stride: natural,
},
},
span,
);
changed = true;
}
}
if changed {
module.types.replace(ty, new);
}
}
}
fn first_lines(s: &str) -> String {
s.lines().take(8).collect::<Vec<_>>().join("\n")
}
@@ -554,6 +629,8 @@ struct Legaliser<'a> {
/// their helpers go in.
modulo: bool,
nan: bool,
/// `textureGather` was used: [`GATHER`] is added.
gather: bool,
mat2_ctor: bool,
/// Constants turned into globals ([`needs_runtime`]).
runtime_constants: HashSet<String>,
@@ -571,6 +648,94 @@ fn call(name: &str, args: Vec<ast::Expr>) -> ast::Expr {
.into_node()
}
/// `textureGather(sampler2D, uv, comp)`: component `comp` of the four texels
/// bilinear filtering at `uv` would blend, in GL's order, read with
/// `texelFetch` (edges clamped).
const GATHER: &str = "\
vec4 iris_gather(texture2D t, sampler s, vec2 uv, int c) {
ivec2 hi = textureSize(sampler2D(t, s), 0) - 1;
ivec2 i = ivec2(floor(uv * vec2(hi + 1) - 0.5));
vec4 a = texelFetch(sampler2D(t, s), clamp(i + ivec2(0, 1), ivec2(0), hi), 0);
vec4 b = texelFetch(sampler2D(t, s), clamp(i + ivec2(1, 1), ivec2(0), hi), 0);
vec4 d = texelFetch(sampler2D(t, s), clamp(i + ivec2(1, 0), ivec2(0), hi), 0);
vec4 e = texelFetch(sampler2D(t, s), clamp(i, ivec2(0), hi), 0);
return vec4(a[c], b[c], d[c], e[c]);
}
";
/// GL converts a `bool` given to a numeric constructor (`vec3(r < radius)`,
/// Photon's sun disc); naga refuses. A comparison or logical expression
/// passed to one becomes `(cond ? 1.0 : 0.0)` (or `1`/`1u`).
fn bool_to_number(e: &mut ast::Expr) {
use ast::BinaryOpData as B;
let ast::ExprData::FunCall(f, args) = &mut e.content else {
return;
};
let Some(name) = callee(f) else { return };
let base = name.trim_start_matches('d');
let (one, zero) = if base.starts_with("ivec") || name == "int" {
(ast::ExprData::IntConst(1), ast::ExprData::IntConst(0))
} else if base.starts_with("uvec") || name == "uint" {
(ast::ExprData::UIntConst(1), ast::ExprData::UIntConst(0))
} else if base.starts_with("vec") || base.starts_with("mat") || name == "float" {
(
ast::ExprData::FloatConst(1.0),
ast::ExprData::FloatConst(0.0),
)
} else {
return;
};
for a in args.iter_mut() {
let boolean = match &a.content {
ast::ExprData::Binary(op, ..) => matches!(
op.content,
B::Or | B::Xor | B::And | B::Equal | B::NonEqual | B::Lt | B::Gt | B::Lte | B::Gte
),
ast::ExprData::Unary(op, _) => op.content == ast::UnaryOpData::Not,
_ => false,
};
if boolean {
let cond = std::mem::replace(a, var("_"));
*a = ast::ExprData::Ternary(
Box::new(cond),
Box::new(one.clone().into_node()),
Box::new(zero.clone().into_node()),
)
.into_node();
}
}
}
/// Outside fragment shaders there are no derivatives, so GL samples level 0
/// where `texture` and its kin would pick one; naga refuses them there (the
/// vertex programs of Chocapic13', MakeUp and Bliss). Turn them into their
/// `Lod` forms at level 0 (a bias is dropped), also inside `vec4(..)` as
/// legacy shadow lookups are wrapped.
fn explicit_lod(e: &mut ast::Expr) {
let ast::ExprData::FunCall(f, args) = &mut e.content else {
return;
};
let Some(name) = callee(f) else { return };
if name == "vec4" && args.len() == 1 {
return explicit_lod(&mut args[0]);
}
// (implicit, explicit, where the level goes, how many arguments without a bias)
let (lod, at, plain) = match name.as_str() {
"texture" => ("textureLod", 2, 2),
"textureProj" => ("textureProjLod", 2, 2),
"textureOffset" => ("textureLodOffset", 2, 3),
"textureProjOffset" => ("textureProjLodOffset", 2, 3),
_ => return,
};
if args.len() < plain {
return;
}
args.truncate(plain);
let zero = ast::ExprData::FloatConst(0.0).into_node();
args.insert(at, zero);
*f = ast::FunIdentifierData::Expr(Box::new(var(lod))).into_node();
}
/// The name a call is made by: a function, or a constructor's type.
fn callee(f: &ast::FunIdentifier) -> Option<String> {
match &f.content {
@@ -784,6 +949,7 @@ impl<'a> Legaliser<'a> {
constant: false,
modulo: false,
nan: false,
gather: false,
mat2_ctor: false,
runtime_constants: HashSet::new(),
}
@@ -1253,7 +1419,23 @@ impl<'a> Legaliser<'a> {
}
let mut locals = Vec::new();
let mut params = Vec::with_capacity(p.parameters.len());
for param in std::mem::take(&mut p.parameters) {
for mut param in std::mem::take(&mut p.parameters) {
// `const in float x` (Bliss): naga's front end takes no `const`
// on parameters, and it changes nothing for the caller.
match &mut param.content {
ast::FunctionParameterDeclarationData::Named(q, _)
| ast::FunctionParameterDeclarationData::Unnamed(q, _) => {
if let Some(list) = q {
list.qualifiers.retain(|q| {
!matches!(&q.content, ast::TypeQualifierSpecData::Storage(s)
if s.content == ast::StorageQualifierData::Const)
});
if list.qualifiers.is_empty() {
*q = None;
}
}
}
}
let (ty, name) = match &param.content {
ast::FunctionParameterDeclarationData::Named(_, d) => {
(type_text(&d.ty), Some(d.ident.ident.as_str().to_owned()))
@@ -1713,32 +1895,60 @@ impl<'a> Legaliser<'a> {
self.nan = true;
return;
}
let mut target_name = name.as_str();
if name == "textureGather"
&& (2..=3).contains(&args.len())
&& let ast::ExprData::FunCall(g, inner) = &args[0].content
&& inner.len() == 2
&& callee(g).as_deref() == Some("sampler2D")
{
// naga's GLSL front end has no `textureGather`.
let mut call_args = inner.clone();
call_args.push(args[1].clone());
call_args.push(
args.get(2)
.cloned()
.unwrap_or_else(|| ast::ExprData::IntConst(0).into_node()),
);
*e = call("iris_gather", call_args);
self.gather = true;
return;
}
if name == "modf"
&& args.len() == 2
&& !matches!(args[1].content, ast::ExprData::Variable(_))
{
// `modf(x, v.y)` (Photon): WGSL can't point at a vector
// component, so no `out` parameter: `+(v.y = trunc(x), x - trunc(x))`
// (the unary `+` has the comma printed in brackets, also in an
// initialiser).
let (x, whole) = (args[0].clone(), args[1].clone());
let assign = ast::ExprData::Assignment(
Box::new(whole),
ast::AssignmentOpData::Equal.into_node(),
Box::new(call("trunc", vec![x.clone()])),
)
.into_node();
let fraction = ast::ExprData::Binary(
ast::BinaryOpData::Sub.into_node(),
Box::new(x.clone()),
Box::new(call("trunc", vec![x])),
)
.into_node();
let comma = ast::ExprData::Comma(Box::new(assign), Box::new(fraction)).into_node();
*e = ast::ExprData::Unary(ast::UnaryOpData::Add.into_node(), Box::new(comma))
.into_node();
return;
}
if let Some((_, new)) = LEGACY_CALLS.iter().find(|(old, _)| *old == name) {
*f = ast::FunIdentifierData::Expr(Box::new(var(new))).into_node();
target_name = new;
} else if let Some((_, new)) = SHADOW_CALLS.iter().find(|(old, _)| *old == name) {
let args = std::mem::take(args);
*e = call("vec4", vec![call(new, args)]);
return;
}
// In vertex and compute shaders, `texture(sampler, coord)` uses implicit
// derivatives that WGSL/naga forbid outside fragment shaders (Bliss):
// rewrite 2-argument non-shadow `texture(s, uv)` to `textureLod(s, uv, 0.0)`.
if self.stage != Stage::Fragment && target_name == "texture" && args.len() == 2 {
let is_shadow = match &args[0].content {
ast::ExprData::FunCall(g, _) => {
callee(g).and_then(|c| opaque(&c)).is_some_and(|o| o.3)
}
_ => false,
};
if !is_shadow {
if let ast::ExprData::FunCall(f, args) = &mut e.content {
*f = ast::FunIdentifierData::Expr(Box::new(var("textureLod"))).into_node();
args.push(ast::ExprData::FloatConst(0.0).into_node());
}
}
if self.stage != Stage::Fragment {
explicit_lod(e);
}
bool_to_number(e);
}
/// The legalised source: header, the rewritten program, then a `main`
@@ -1775,6 +1985,9 @@ impl<'a> Legaliser<'a> {
if self.modulo {
out.push_str(&modulo_helpers());
}
if self.gather {
out.push_str(GATHER);
}
if self.nan {
out.push_str("float iris_sqrt(float x) { return sqrt(x); }\n");
}
@@ -368,6 +368,78 @@ void main() {
reparse(&fs.wgsl).unwrap();
}
/// What Photon, Chocapic13', MakeUp Ultra Fast and Bliss write and GL takes:
/// lookups without a level in a vertex shader, a struct passed between
/// stages, `textureGather`, a `bool` given to `vec3(..)`, `const in`
/// parameters and an array field in a struct built by its constructor.
#[test]
fn legalises_what_photon_and_chocapic_write() {
let mut link = Link::default();
let header = "uniform sampler2D colortex0;
uniform sampler2DShadow shadowtex0;
struct Clouds { float coverage; vec2 wind; mat3 turn; int layers; };
";
let vs = run(
Stage::Vertex,
&format!(
"{header}flat varying Clouds clouds;
void main() {{
clouds.coverage = texture2D(colortex0, vec2(0.5)).r + shadow2D(shadowtex0, vec3(0.5)).r;
clouds.wind = textureOffset(colortex0, vec2(0.5), ivec2(1, 0), 2.0).rg;
clouds.turn = mat3(1.0);
clouds.layers = 2;
gl_Position = ftransform();
}}
"
),
&mut link,
)
.unwrap();
for wanted in [
"textureLod(sampler2D(colortex0_t",
"vec2(0.5), 0.)",
"textureLodOffset(sampler2D(colortex0_t",
"clouds_iriscoverage = clouds.coverage;",
"clouds_iristurn_iris1 = clouds.turn[1];",
] {
assert!(vs.glsl.contains(wanted), "{wanted}\n{}", vs.glsl);
}
reparse(&vs.wgsl).unwrap();
let fs = run(
Stage::Fragment,
&format!(
"{header}flat varying Clouds clouds;
struct Spline {{ float slope; float[3] coeffs; }};
float edge(const in float x, const float r) {{ return float(x < r); }}
void main() {{
const Spline spline = Spline(0.0, float[3](1.0, 2.0, 3.0));
vec4 four = textureGather(colortex0, vec2(0.5), 1);
vec3 disc = vec3(clouds.coverage < 0.5);
vec2 cell = vec2(0.0);
float part = modf(clouds.coverage * 4.0, cell.y);
gl_FragColor = vec4(disc * edge(four.x, spline.coeffs[1]), clouds.wind.x + float(clouds.layers) + part + cell.y);
}}
"
),
&mut link,
)
.unwrap();
for wanted in [
"iris_gather(colortex0_t",
"clouds.coverage = clouds_iriscoverage;",
"float edge(in float x, float r)",
"cell.y = trunc(",
] {
assert!(fs.glsl.contains(wanted), "{wanted}\n{}", fs.glsl);
}
reparse(&fs.wgsl).unwrap();
// The vertex program's outputs are the fragment program's inputs.
assert_eq!(
io(&vs, true).get("clouds_iriswind"),
io(&fs, false).get("clouds_iriswind")
);
}
/// A fragment output narrower than its four-channel target (Steadfast's
/// `final` writes `out vec3 color`) is written through a `vec4` with alpha 1:
/// GL fills the missing channels, wgpu refuses the pipeline.
@@ -62,9 +62,6 @@ impl<E> ProtoBlockEntities<E> {
pub fn active(&self, position: BlockPos) -> Option<&E> {
self.active.get(&position)
}
pub fn active_mut(&mut self, position: BlockPos) -> Option<&mut E> {
self.active.get_mut(&position)
}
pub fn pending(&self, position: BlockPos) -> Option<&Tag> {
self.pending.get(&position)
}
-12
View File
@@ -157,12 +157,6 @@ impl FaceVisibility {
}
}
}
/// Whether the state's occlusion face toward `direction` is the full square.
pub fn full_face(&self, state: BlockStateId, direction: Direction) -> bool {
self.states
.get(state.0 as usize)
.is_some_and(|s| s.faces[direction as usize] == 1)
}
/// The state's occlusion face toward `direction` (`getFaceOcclusionShape`) and
/// its shared ID: 0 is the empty singleton, 1 the full-block singleton.
pub fn occlusion_face(
@@ -173,12 +167,6 @@ impl FaceVisibility {
let id = self.states.get(state.0 as usize)?.faces[direction as usize];
Some((id, &self.faces[id as usize]))
}
/// Whether the state's occlusion face toward `direction` is empty.
pub fn empty_face(&self, state: BlockStateId, direction: Direction) -> bool {
self.states
.get(state.0 as usize)
.is_none_or(|s| s.faces[direction as usize] == 0)
}
pub fn skip_rendering(
&self,
state: BlockStateId,
-19
View File
@@ -186,25 +186,6 @@ impl<'r> BlockSupportRegistry<'r> {
pub fn registry(&self) -> &'r BlockRegistry {
self.cached.registry()
}
pub fn support_shape<W: DynamicSupportWorld>(
&self,
world: &mut W,
state: BlockStateId,
position: [i32; 3],
) -> Result<VoxelShape, SupportQueryError<W::Error>> {
if let Some(shape) = self
.cached
.cached_shape(state)
.map_err(SupportQueryError::Data)?
{
return Ok(shape.clone());
}
self.dynamic
.get(&state)
.ok_or(SupportQueryError::Unsupported(state))?
.shape(world, position)
.map_err(SupportQueryError::Dynamic)
}
pub fn is_face_sturdy<W: DynamicSupportWorld>(
&self,
world: &mut W,
@@ -524,14 +524,6 @@ impl<'r> BlockSurvivalRegistry<'r> {
bubble_down: tag_states("minecraft:enables_bubble_column_drag_down")?,
})
}
pub fn supported_states(&self) -> usize {
self.rules.iter().filter(|r| r.is_some()).count()
}
pub fn supports_state(&self, state: BlockStateId) -> bool {
self.rules
.get(state.0 as usize)
.is_some_and(Option::is_some)
}
fn read<W: SurvivalWorld>(
&self,
world: &mut W,
@@ -3,7 +3,6 @@
use crate::{
component_patch::{ComponentMap, MissingPrototype, Patch, Prototype},
item_durability::DurabilityStorage,
item_use_catalog::UseComponents,
};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Key {
@@ -52,13 +51,6 @@ impl DurabilityPrototype {
}
Self(Prototype::new(entries))
}
pub fn from_defaults(defaults: &UseComponents) -> Self {
Self::new([
Change::MaxDamage(defaults.max_damage),
Change::Damage(defaults.damage),
Change::Unbreakable(defaults.unbreakable),
])
}
}
#[derive(Clone, Debug)]
pub struct DurabilityPatch(Patch<Key, i32>);
@@ -157,12 +157,6 @@ pub fn map(tag: &Tag) -> Option<&Compound> {
_ => None,
}
}
pub fn map_mut(tag: &mut Tag) -> Option<&mut Compound> {
match tag {
Tag::Compound(c) => Some(c),
_ => None,
}
}
/// `Dynamic.set`: only maps change.
pub fn set(tag: &mut Tag, field: &str, value: Tag) {
if let Tag::End = tag {
@@ -193,12 +187,6 @@ pub fn update(tag: &mut Tag, field: &str, f: impl FnOnce(Tag) -> Tag) {
set(tag, field, f(v));
}
}
/// `Dynamic.update` in place.
pub fn update_mut(tag: &mut Tag, field: &str, f: impl FnOnce(&mut Tag)) {
if let Some(v) = tag.get_mut(field) {
f(v);
}
}
/// `Dynamic.renameAndFixField`: the fixed value under the new name, removed when
/// the fix gives nothing.
pub fn rename_and_fix(tag: &mut Tag, from: &str, to: &str, f: impl FnOnce(Tag) -> Option<Tag>) {
@@ -223,15 +211,6 @@ pub fn is_empty_map(tag: &Tag) -> bool {
pub fn or_empty_map(tag: Option<&Tag>) -> Tag {
tag.cloned().unwrap_or_else(empty_map)
}
/// Apply `f` to every element of a list field (`Dynamic.createList(asStream().map(f))`).
pub fn map_list(tag: &mut Tag, field: &str, mut f: impl FnMut(Tag) -> Tag) {
if let Some(v) = tag.get(field)
&& is_list(Some(v))
{
let list = stream(Some(v)).into_iter().map(&mut f).collect();
set(tag, field, Tag::List(list));
}
}
/// `NamespacedSchema.ensureNamespaced`.
pub fn namespaced(id: &str) -> String {
match crate::datafix::identifier(id) {
-3
View File
@@ -44,9 +44,6 @@ impl MovementHistory {
}
self.records.push_back(record);
}
pub fn remove_latest(&mut self) {
self.records.pop_back();
}
pub fn clear(&mut self) {
self.records.clear();
}
@@ -73,17 +73,3 @@ pub fn is_unobstructed<W: EntityObstructionWorld>(
}
Ok(true)
}
/// Entity obstruction for the unit cube used by the vanilla block predicate.
/// Translate the voxel shape in floating point: integer MAX + 1 must not wrap.
pub fn is_block_unobstructed<W: EntityObstructionWorld>(
world: &mut W,
position: [i32; 3],
) -> Result<bool, ObstructionError<W::Error>> {
let shape = VoxelShape::block().moved(horizon_core::geometry::Vec3::new(
f64::from(position[0]),
f64::from(position[1]),
f64::from(position[2]),
));
is_unobstructed(world, None, &shape)
}
-7
View File
@@ -272,13 +272,6 @@ impl FluidStateTable {
pub fn get(&self, state: BlockStateId) -> Option<FluidState> {
self.0.get(state.0 as usize).copied()
}
pub fn matching_states(&self, mask: u8) -> impl Iterator<Item = BlockStateId> + '_ {
self.0
.iter()
.enumerate()
.filter(move |(_, state)| state.kind.mask() & mask != 0)
.map(|(i, _)| BlockStateId(i as u32))
}
}
/// Bound identities for converting fluid states into their legacy liquid blocks.
@@ -15,9 +15,6 @@ macro_rules! classes {
pub fn from_java(name: &str) -> Option<Self> {
match name { $($java => Some(Class::$name),)* _ => None }
}
pub const fn java_name(self) -> &'static str {
match self { $(Class::$name => $java,)* }
}
}
};
}

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