Merge origin/main into feat/server-dialogs

Conflicts: lib.rs (dialog + discord_presence modules), packets/play.rs tests
(boss_event_round_trips + dialogs_round_trip), both kept.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-25 14:24:45 +01:00
211 changed files with 19473 additions and 2927 deletions
+82 -10
View File
@@ -6,7 +6,7 @@
use crate::{Error, Result, buf::Reader, crypto::Cfb8, frame};
use std::{
io::{Read, Write},
net::{Shutdown, TcpStream, ToSocketAddrs},
net::{Shutdown, SocketAddr, TcpStream, ToSocketAddrs},
sync::{
Arc, Condvar, Mutex,
atomic::{AtomicI64, Ordering},
@@ -180,6 +180,13 @@ pub struct ConnWriter {
pub threshold: Option<usize>,
counters: Arc<Counters>,
}
/// `InetAddress.getByName` under Java's default `java.net.preferIPv6Addresses=false`: IPv4
/// addresses first, whatever order the system resolver gives (macOS lists IPv6 first). Vanilla
/// connects to that first address only; the rest stay here as fallbacks.
fn ipv4_first(mut addrs: Vec<SocketAddr>) -> Vec<SocketAddr> {
addrs.sort_by_key(SocketAddr::is_ipv6);
addrs
}
/// Both halves before the split.
pub struct Connection {
pub reader: ConnReader,
@@ -199,19 +206,19 @@ impl Connection {
let addrs = crate::resolver::resolve(host, port)?;
Self::connect_addresses(host, addrs, timeout)
}
fn connect_addresses(
host: &str,
addrs: Vec<std::net::SocketAddr>,
timeout: Duration,
) -> Result<Self> {
let mut last = Error::new(format!("Unknown host {host}"));
for addr in addrs {
fn connect_addresses(host: &str, addrs: Vec<SocketAddr>, timeout: Duration) -> Result<Self> {
// Report the first address's failure: it is the one vanilla tries, and the IPv6
// fallbacks after it often fail only because the client has no IPv6 route.
let mut first = None;
for addr in ipv4_first(addrs) {
match TcpStream::connect_timeout(&addr, timeout) {
Ok(stream) => return Self::from_stream(stream),
Err(e) => last = Error::new(format!("Connection refused: {e}")),
Err(e) => {
first.get_or_insert_with(|| Error::new(format!("Connection refused: {e}")));
}
}
}
Err(last)
Err(first.unwrap_or_else(|| Error::new(format!("Unknown host {host}"))))
}
pub fn from_stream(stream: TcpStream) -> Result<Self> {
stream.set_nodelay(true)?;
@@ -328,6 +335,71 @@ mod tests {
use super::*;
use std::net::TcpListener;
#[test]
fn ipv4_first_keeps_each_familys_order() {
let a = |s: &str| s.parse::<SocketAddr>().unwrap();
let resolved = vec![
a("[2001:db8::1]:25565"),
a("192.0.2.1:25565"),
a("[2001:db8::2]:25565"),
a("10.0.0.1:25565"),
];
assert_eq!(
ipv4_first(resolved),
[
a("192.0.2.1:25565"),
a("10.0.0.1:25565"),
a("[2001:db8::1]:25565"),
a("[2001:db8::2]:25565"),
]
);
}
fn peer(c: &Connection) -> SocketAddr {
match &c.reader.stream {
Stream::Tcp(s) => s.peer_addr().unwrap(),
Stream::Memory(_) => panic!("not a socket"),
}
}
/// Binds `[::1]`, or `None` where the machine has no IPv6 loopback.
fn ipv6_loopback() -> Option<TcpListener> {
let listener = TcpListener::bind("[::1]:0");
if listener.is_err() {
eprintln!("skipped: no IPv6 loopback");
}
listener.ok()
}
#[test]
fn connects_to_ipv4_although_the_resolver_lists_ipv6_first() {
// Both listen, as with a server whose IPv6 address accepts and then resets.
let Some(v6_listener) = ipv6_loopback() else {
return;
};
let v4_listener = TcpListener::bind("127.0.0.1:0").unwrap();
let v6 = v6_listener.local_addr().unwrap();
let v4 = v4_listener.local_addr().unwrap();
let c =
Connection::connect_addresses("test", vec![v6, v4], Duration::from_secs(5)).unwrap();
assert_eq!(peer(&c), v4);
}
#[test]
fn falls_back_to_ipv6_when_ipv4_refuses() {
let Some(v6_listener) = ipv6_loopback() else {
return;
};
let v6 = v6_listener.local_addr().unwrap();
let closed = TcpListener::bind("127.0.0.1:0")
.unwrap()
.local_addr()
.unwrap();
let c = Connection::connect_addresses("test", vec![v6, closed], Duration::from_secs(5))
.unwrap();
assert_eq!(peer(&c), v6);
}
#[test]
fn loopback_with_compression_and_encryption() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
+80 -3
View File
@@ -2,11 +2,13 @@
//! item's registry id and a data component patch, plus the hashed form the
//! client sends back in container clicks (HashedStack).
use crate::{
Error, Result,
Result,
buf::{Codec, Reader, Writer},
};
use horizon_world::nbt::Tag;
mod skip;
/// minecraft:data_component_type registry ids (26.3).
pub mod component {
pub const CUSTOM_DATA: i32 = 0;
@@ -35,6 +37,7 @@ pub mod component {
pub const CHARGED_PROJECTILES: i32 = 51;
pub const WRITABLE_BOOK_CONTENT: i32 = 56;
pub const WRITTEN_BOOK_CONTENT: i32 = 57;
pub const TRIM: i32 = 58;
}
/// A written book's content (`WrittenBookContent.STREAM_CODEC`): the
@@ -78,6 +81,15 @@ pub enum Component {
WrittenBook(WrittenBook),
/// `ChargedProjectiles`: a loaded crossbow's ammunition, as templates.
Stacks(Vec<Stack>),
/// `ArmorTrim` naming its material and pattern by registry id (`trim_material`,
/// `trim_pattern`); a trim with a direct holder stays [`Component::Raw`].
Trim {
material: i32,
pattern: i32,
},
/// A component Horizon reads past without interpreting it: its encoded
/// bytes, written back as they came.
Raw(Vec<u8>),
}
/// `Filterable.streamCodec`: the raw value, then an optional filtered one
@@ -224,11 +236,35 @@ impl Component {
hidden: (0..n).map(|_| r.varint()).collect::<Result<_>>()?,
}
}
other => return Err(Error::new(format!("unsupported item component {other}"))),
// ArmorTrim.STREAM_CODEC: two holders, each a reference's id plus
// one. A direct material or pattern has no registry name: read past.
TRIM => {
let start = r.position();
skip::component(TRIM, r)?;
let bytes = r.since(start);
let mut ids = Reader::new(bytes);
match (ids.varint(), ids.varint()) {
(Ok(material @ 1..), Ok(pattern @ 1..)) if ids.remaining() == 0 => Self::Trim {
material: material - 1,
pattern: pattern - 1,
},
_ => Self::Raw(bytes.to_vec()),
}
}
other => {
let start = r.position();
skip::component(other, r)?;
Self::Raw(r.since(start).to_vec())
}
})
}
fn write(&self, kind: i32, w: &mut Writer) {
match self {
Self::Raw(bytes) => w.bytes(bytes),
Self::Trim { material, pattern } => {
w.varint(material + 1);
w.varint(pattern + 1);
}
Self::Int(v) if kind == component::DYED_COLOR => w.i32(*v),
Self::Int(v) => w.varint(*v),
Self::Unit => {}
@@ -582,7 +618,8 @@ mod tests {
#[test]
fn unknown_components_are_errors() {
let bytes = [1, 5, 1, 0, 99];
// 122 is past DataComponents' last id (cushion_color, 121).
let bytes = [1, 5, 1, 0, 122];
assert!(Slot::read(&mut Reader::new(&bytes)).is_err());
}
@@ -631,4 +668,44 @@ mod tests {
[("textures".to_owned(), "x".to_owned(), None)]
);
}
#[test]
fn components_read_past_keep_their_bytes() {
// Vanilla 26.3's encoding (tools/test_item_wire_parity.py) of a chestplate's
// armour trim (decoded: both holders are references), a banner's patterns
// (one direct), a pot's sherds and a stew's effects: one server's
// inventory, recipe book and advancements had them.
for (hex, kind) in [
("01bd0801003a0502", 58),
("01890b01004a02200e000b6d696e6563726166743a7801790b", 74),
("01880301004c01f60801000001be0c0100000001d30c010000", 76),
("01a408010037020f6412a001", 55),
] {
let bytes: Vec<u8> = (0..hex.len())
.step_by(2)
.map(|i| u8::from_str_radix(&hex[i..i + 2], 16).unwrap())
.collect();
let mut r = Reader::new(&bytes);
let stack = Slot::read(&mut r).unwrap();
assert_eq!(r.remaining(), 0, "component {kind}");
let expected = |c: &Component| match kind {
58 => {
*c == Component::Trim {
material: 4,
pattern: 1,
}
}
_ => matches!(c, Component::Raw(_)),
};
assert!(
stack
.as_ref()
.and_then(|s| s.component(kind))
.is_some_and(expected)
);
let mut w = Writer::new();
Slot::write(&stack, &mut w);
assert_eq!(w.data, bytes, "component {kind}");
}
}
}
+427
View File
@@ -0,0 +1,427 @@
//! Reading past the data components Horizon doesn't interpret: each
//! function consumes exactly what its vanilla StreamCodec writes
//! (DataComponents' `networkSynchronized` codecs; a component without one
//! goes as its persistent Codec's NBT, `ByteBufCodecs.fromCodecWithRegistries`).
//! Item data has no length prefix, so a component read short or long makes
//! everything after it unreadable.
use super::{Component, Template};
use crate::{
Error, Result,
buf::{Codec, Reader},
};
type Read = fn(&mut Reader) -> Result<()>;
/// DataComponents' registry order (26.3) for the ids `Component::read`
/// doesn't decode itself.
pub(super) fn component(kind: i32, r: &mut Reader) -> Result<()> {
match kind {
// Unit.STREAM_CODEC: glider, waxed.
34 | 120 => Ok(()),
// Components without a network codec go as their NBT: intangible_projectile,
// map_decorations, debug_stick_state, recipes, lock, container_loot.
22 | 49 | 59 | 68 | 81 | 82 => nbt(r),
// A VarInt (VAR_INT, an idMapper, a registry or holderRegistry id): damage_type,
// enchantable, additional_trade_cost, block_transformer, villager_food, dye,
// ominous_bottle_amplifier, base_color, the mob variants and colours, the pottery
// pattern and cushion_color.
8 | 31 | 42 | 43 | 44 | 46 | 65 | 75 | 88..=108 | 110..=117 | 121 => varint(r),
// FLOAT: minimum_attack_charge, potion_duration_scale.
7 | 54 => f32(r),
// Identifier.STREAM_CODEC: tooltip_style, note_block_sound.
35 | 73 => ident(r),
// UseEffects: canSprint, interactVibrations, speedMultiplier.
5 => {
r.bool()?;
r.bool()?;
f32(r)
}
// AdventureModePredicate: can_place_on, can_break.
14 | 15 => list(r, block_predicate),
16 => list(r, attribute_modifier),
// FoodProperties.DIRECT_STREAM_CODEC: nutrition, saturation, canAlwaysEat.
23 => {
varint(r)?;
f32(r)?;
boolean(r)
}
// Consumable: consumeSeconds, animation, sound, hasConsumeParticles, onConsumeEffects.
24 => {
f32(r)?;
varint(r)?;
sound(r)?;
boolean(r)?;
list(r, consume_effect)
}
// UseRemainder, SulfurCubeContent: one template.
25 | 80 => template(r),
// UseCooldown: seconds, cooldownGroup.
26 => {
f32(r)?;
optional(r, ident)
}
// DamageResistant, Repairable, provides_banner_patterns: a holder set.
27 | 33 | 67 => holder_set(r),
28 => tool(r),
// Weapon: itemDamagePerAttack, disableBlockingForSeconds.
29 => {
varint(r)?;
f32(r)
}
32 => equippable(r),
// DeathProtection: deathEffects.
36 => list(r, consume_effect),
37 => blocks_attacks(r),
// PiercingWeapon: dealsKnockback, dismounts, sound, hitSound.
38 => {
boolean(r)?;
boolean(r)?;
optional(r, sound)?;
optional(r, sound)
}
39 => kinetic_weapon(r),
// SwingAnimation: type, duration.
40 | 41 => {
varint(r)?;
varint(r)
}
// BundleContents: templates.
52 => list(r, template),
53 => potion_contents(r),
// SuspiciousStewEffects: effect, duration.
55 => list(r, |r| {
varint(r)?;
varint(r)
}),
// ArmorTrim: material, then Holder<TrimPattern> (assetId, description, decal).
58 => {
trim_material(r)?;
holder(r, |r| {
ident(r)?;
nbt(r)?;
boolean(r)
})
}
// TypedEntityData (entity_data, block_entity_data): the type id, then a compound.
60 | 62 => {
varint(r)?;
nbt(r)
}
// CustomData: bucket_entity_data.
61 => nbt(r),
// InstrumentComponent: Holder<Instrument> (soundEvent, useDuration, range,
// durabilityDamage, description).
63 => holder(r, |r| {
sound(r)?;
f32(r)?;
f32(r)?;
varint(r)?;
nbt(r)
}),
64 => trim_material(r),
// JukeboxPlayable: Holder<JukeboxSong> (soundEvent, description, lengthInSeconds,
// comparatorOutput).
66 => holder(r, |r| {
sound(r)?;
nbt(r)?;
f32(r)?;
varint(r)
}),
// LodestoneTracker: target (GlobalPos: dimension, BlockPos), tracked.
69 => {
optional(r, |r| {
ident(r)?;
r.i64().map(drop)
})?;
boolean(r)
}
70 => firework_explosion(r),
// Fireworks: flightDuration, explosions.
71 => {
varint(r)?;
list(r, firework_explosion)
}
// BannerPatternLayers: Holder<BannerPattern> (assetId, translationKey), colour.
74 => list(r, |r| {
holder(r, |r| {
ident(r)?;
string(r)
})?;
varint(r)
}),
// PotDecorations: back, left, right, front.
76 => (0..4).try_for_each(|_| optional(r, template)),
// ItemContainerContents: optional templates.
77 => list(r, |r| optional(r, template)),
// BlockItemStateProperties: a string to string map.
78 => list(r, |r| {
string(r)?;
string(r)
}),
// Bees: Occupant (entity type and data, ticksInHive, minTicksInHive).
79 => list(r, |r| {
varint(r)?;
nbt(r)?;
varint(r)?;
varint(r)
}),
83 => sound(r),
// Compostable: layers.
84 => resolvable(r, i32),
// CookingFuel (burnTime, speedMultiplier), BrewingFuel (uses, speedMultiplier).
85 | 86 => {
resolvable(r, i32)?;
resolvable(r, f32)
}
// MobVisibility: targetingEntityTypes, visibility.
87 => {
holder_set(r)?;
f32(r)
}
// Holder<PaintingVariant>: width, height, assetId, title, author.
109 => holder(r, |r| {
varint(r)?;
varint(r)?;
ident(r)?;
optional(r, nbt)?;
optional(r, nbt)
}),
// SignText: four messages, four optional filtered ones, colour, hasGlowingText.
118 | 119 => {
(0..4).try_for_each(|_| nbt(r))?;
optional(r, |r| (0..4).try_for_each(|_| nbt(r)))?;
varint(r)?;
boolean(r)
}
other => Err(Error::new(format!("unsupported item component {other}"))),
}
}
fn boolean(r: &mut Reader) -> Result<()> {
r.bool().map(drop)
}
fn varint(r: &mut Reader) -> Result<()> {
r.varint().map(drop)
}
fn f32(r: &mut Reader) -> Result<()> {
r.f32().map(drop)
}
fn i32(r: &mut Reader) -> Result<()> {
r.i32().map(drop)
}
/// ByteBufCodecs.STRING_UTF8.
fn string(r: &mut Reader) -> Result<()> {
r.string(32767).map(drop)
}
/// Identifier.STREAM_CODEC, ResourceKey.streamCodec.
fn ident(r: &mut Reader) -> Result<()> {
string(r)
}
/// A text component or compound (fromCodecWithRegistries, COMPOUND_TAG).
fn nbt(r: &mut Reader) -> Result<()> {
r.nbt().map(drop)
}
fn template(r: &mut Reader) -> Result<()> {
Template::read(r).map(drop)
}
/// ByteBufCodecs.optional: a flag, then the value.
fn optional(r: &mut Reader, value: Read) -> Result<()> {
if r.bool()? { value(r) } else { Ok(()) }
}
/// ByteBufCodecs.list and map: a VarInt count, then the elements (a map's
/// key and value each). Every element is at least a byte, so the count
/// can't pass what is left.
fn list(r: &mut Reader, element: Read) -> Result<()> {
let n = r.count(r.remaining())?;
(0..n).try_for_each(|_| element(r))
}
/// ByteBufCodecs.holder: 0 and the value itself, or the registry id plus one.
fn holder(r: &mut Reader, direct: Read) -> Result<()> {
if r.varint()? == 0 { direct(r) } else { Ok(()) }
}
/// ByteBufCodecs.holderSet: 0 and a tag id, or the size plus one and the ids.
fn holder_set(r: &mut Reader) -> Result<()> {
match r.varint()? {
0 => ident(r),
n => {
let n = usize::try_from(n - 1).map_err(|_| Error::new("negative holder set size"))?;
if n > r.remaining() {
return Err(Error::new("holder set past the end"));
}
(0..n).try_for_each(|_| varint(r))
}
}
}
/// SoundEvent.STREAM_CODEC: a holder of a location and an optional fixed range.
fn sound(r: &mut Reader) -> Result<()> {
holder(r, |r| {
ident(r)?;
optional(r, f32)
})
}
/// ResolvableInt, ResolvableFloat: Either a constant (true) or a context provider's key.
fn resolvable(r: &mut Reader, constant: Read) -> Result<()> {
if r.bool()? { constant(r) } else { ident(r) }
}
/// TrimMaterial.STREAM_CODEC: a holder of a palette id and a description.
fn trim_material(r: &mut Reader) -> Result<()> {
holder(r, |r| {
ident(r)?;
nbt(r)
})
}
/// MobEffectInstance: the effect id, then its Details.
fn mob_effect(r: &mut Reader) -> Result<()> {
varint(r)?;
effect_details(r)
}
/// MobEffectInstance.Details: amplifier, duration, ambient, showParticles, showIcon, then the
/// hidden effect's Details, recursively.
fn effect_details(r: &mut Reader) -> Result<()> {
varint(r)?;
varint(r)?;
boolean(r)?;
boolean(r)?;
boolean(r)?;
optional(r, effect_details)
}
/// ConsumeEffect.STREAM_CODEC: the consume_effect_type id, then that type's fields.
fn consume_effect(r: &mut Reader) -> Result<()> {
match r.varint()? {
// apply_effects: effects, probability.
0 => {
list(r, mob_effect)?;
f32(r)
}
// remove_effects: a mob effect holder set.
1 => holder_set(r),
// clear_all_effects.
2 => Ok(()),
// teleport_randomly: diameter, directionalParticles.
3 => {
f32(r)?;
boolean(r)
}
// play_sound.
4 => sound(r),
other => Err(Error::new(format!("unknown consume effect type {other}"))),
}
}
/// BlockPredicate: blocks, properties, nbt, then DataComponentMatchers (exact, partial).
fn block_predicate(r: &mut Reader) -> Result<()> {
optional(r, holder_set)?;
// StatePropertiesPredicate: PropertyMatchers, each a name and an
// Either<ExactMatcher (value), RangedMatcher (min, max)>.
optional(r, |r| {
list(r, |r| {
string(r)?;
if r.bool()? {
string(r)
} else {
optional(r, string)?;
optional(r, string)
}
})
})?;
optional(r, nbt)?;
// DataComponentExactPredicate: TypedDataComponents, a component type id and its value.
list(r, |r| {
let kind = r.varint()?;
Component::read(kind, r).map(drop)
})?;
// DataComponentPredicate.STREAM_CODEC: an Either of a predicate type id or a component
// type id, then the predicate as NBT (fromCodecWithRegistries).
list(r, |r| {
boolean(r)?;
varint(r)?;
nbt(r)
})
}
/// ItemAttributeModifiers.Entry: attribute, modifier (id, amount, operation), slot, display.
fn attribute_modifier(r: &mut Reader) -> Result<()> {
varint(r)?;
ident(r)?;
r.f64()?;
varint(r)?;
varint(r)?;
// Display.Type: default, hidden, or override and its text.
match r.varint()? {
0 | 1 => Ok(()),
2 => nbt(r),
other => Err(Error::new(format!(
"unknown attribute modifier display {other}"
))),
}
}
/// Tool: rules (blocks, speed, correctForDrops), defaultMiningSpeed, damagePerBlock,
/// canDestroyBlocksInCreative.
fn tool(r: &mut Reader) -> Result<()> {
list(r, |r| {
holder_set(r)?;
optional(r, f32)?;
optional(r, boolean)
})?;
f32(r)?;
varint(r)?;
boolean(r)
}
/// Equippable: slot, equipSound, assetId, cameraOverlay, allowedEntities, dispensable,
/// swappable, damageOnHurt, equipOnInteract, canBeSheared, shearingSound.
fn equippable(r: &mut Reader) -> Result<()> {
varint(r)?;
sound(r)?;
optional(r, ident)?;
optional(r, ident)?;
optional(r, holder_set)?;
(0..5).try_for_each(|_| boolean(r))?;
sound(r)
}
/// BlocksAttacks: blockDelaySeconds, disableCooldownScale, damageReductions (angle, type,
/// base, factor), itemDamage (threshold, base, factor), bypassedBy, blockSound, disableSound.
fn blocks_attacks(r: &mut Reader) -> Result<()> {
f32(r)?;
f32(r)?;
list(r, |r| {
f32(r)?;
optional(r, holder_set)?;
f32(r)?;
f32(r)
})?;
(0..3).try_for_each(|_| f32(r))?;
optional(r, holder_set)?;
optional(r, sound)?;
optional(r, sound)
}
/// KineticWeapon: contactCooldownTicks, delayTicks, the dismount, knockback and damage
/// conditions (maxDurationTicks, minSpeed, minRelativeSpeed), forwardMovement,
/// damageMultiplier, sound, hitSound.
fn kinetic_weapon(r: &mut Reader) -> Result<()> {
varint(r)?;
varint(r)?;
(0..3).try_for_each(|_| {
optional(r, |r| {
varint(r)?;
f32(r)?;
f32(r)
})
})?;
f32(r)?;
f32(r)?;
optional(r, sound)?;
optional(r, sound)
}
/// PotionContents: potion, customColor, customEffects, customName.
fn potion_contents(r: &mut Reader) -> Result<()> {
optional(r, varint)?;
optional(r, i32)?;
list(r, mob_effect)?;
optional(r, string)
}
/// FireworkExplosion: shape, colors, fadeColors, hasTrail, hasTwinkle.
fn firework_explosion(r: &mut Reader) -> Result<()> {
varint(r)?;
list(r, i32)?;
list(r, i32)?;
boolean(r)?;
boolean(r)
}
+198 -2
View File
@@ -1147,6 +1147,42 @@ packet!(SoundEntity {
pitch: f32 => Float,
seed: i64 => Long,
});
/// ClientboundStopSoundPacket: bit 0 selects a source, bit 1 an event id.
#[derive(Clone, Debug, PartialEq)]
pub struct StopSound {
pub source: Option<i32>,
pub sound: Option<String>,
}
impl Codec<StopSound> for StopSound {
fn read(r: &mut Reader) -> crate::Result<Self> {
let flags = r.u8()?;
let source = if flags & 1 != 0 {
let value = r.varint()?;
if !(0..11).contains(&value) {
return Err(crate::Error::new("invalid sound source"));
}
Some(value)
} else {
None
};
let sound = if flags & 2 != 0 {
Some(r.string(32767)?)
} else {
None
};
Ok(Self { source, sound })
}
fn write(p: &Self, w: &mut Writer) {
w.u8(u8::from(p.source.is_some()) | (u8::from(p.sound.is_some()) << 1));
if let Some(source) = p.source {
w.varint(source);
}
if let Some(sound) = &p.sound {
w.string(sound);
}
}
}
/// One entry of ClientboundCommandsPacket: a literal or an argument node.
#[derive(Clone, Debug, PartialEq)]
pub struct CommandNode {
@@ -1609,6 +1645,125 @@ impl Codec<Vec<(i32, i32, i32)>> for StatList {
}
}
/// `ClientboundBossEventPacket` (`boss_event`).
#[derive(Clone, Debug, PartialEq)]
pub enum BossAction {
Add {
name: Tag,
progress: f32,
/// `BossBarColor` ordinal.
color: i32,
/// `BossBarOverlay` ordinal.
overlay: i32,
darken: bool,
music: bool,
fog: bool,
},
Remove,
UpdateProgress {
progress: f32,
},
UpdateName {
name: Tag,
},
UpdateStyle {
color: i32,
overlay: i32,
},
UpdateProperties {
darken: bool,
music: bool,
fog: bool,
},
}
#[derive(Clone, Debug, PartialEq)]
pub struct BossEvent {
pub id: u128,
pub action: BossAction,
}
fn boss_flags(darken: bool, music: bool, fog: bool) -> u8 {
u8::from(darken) | (u8::from(music) << 1) | (u8::from(fog) << 2)
}
fn split_flags(flags: u8) -> (bool, bool, bool) {
(flags & 1 != 0, flags & 2 != 0, flags & 4 != 0)
}
impl Codec<BossEvent> for BossEvent {
fn read(r: &mut Reader) -> Result<BossEvent> {
let id = r.uuid()?;
let action = match r.varint()? {
0 => {
let name = r.nbt()?;
let progress = r.f32()?;
let color = r.varint()?;
let overlay = r.varint()?;
let (darken, music, fog) = split_flags(r.u8()?);
BossAction::Add {
name,
progress,
color,
overlay,
darken,
music,
fog,
}
}
1 => BossAction::Remove,
2 => BossAction::UpdateProgress { progress: r.f32()? },
3 => BossAction::UpdateName { name: r.nbt()? },
4 => BossAction::UpdateStyle {
color: r.varint()?,
overlay: r.varint()?,
},
5 => {
let (darken, music, fog) = split_flags(r.u8()?);
BossAction::UpdateProperties { darken, music, fog }
}
op => return Err(Error::new(format!("unknown boss event operation {op}"))),
};
Ok(BossEvent { id, action })
}
fn write(v: &BossEvent, w: &mut Writer) {
w.uuid(v.id);
match &v.action {
BossAction::Add {
name,
progress,
color,
overlay,
darken,
music,
fog,
} => {
w.varint(0);
w.nbt(name);
w.f32(*progress);
w.varint(*color);
w.varint(*overlay);
w.u8(boss_flags(*darken, *music, *fog));
}
BossAction::Remove => w.varint(1),
BossAction::UpdateProgress { progress } => {
w.varint(2);
w.f32(*progress);
}
BossAction::UpdateName { name } => {
w.varint(3);
w.nbt(name);
}
BossAction::UpdateStyle { color, overlay } => {
w.varint(4);
w.varint(*color);
w.varint(*overlay);
}
BossAction::UpdateProperties { darken, music, fog } => {
w.varint(5);
w.u8(boss_flags(*darken, *music, *fog));
}
}
}
}
packet_enum!(Clientbound, crate::ids::play::clientbound {
BundleDelimiter(Empty) = BUNDLE_DELIMITER,
AddEntity(AddEntity) = ADD_ENTITY,
@@ -1619,6 +1774,7 @@ packet_enum!(Clientbound, crate::ids::play::clientbound {
BlockEntityData(BlockEntityData) = BLOCK_ENTITY_DATA,
BlockEvent(BlockEvent) = BLOCK_EVENT,
BlockUpdate(BlockUpdate) = BLOCK_UPDATE,
BossEvent(BossEvent) = BOSS_EVENT,
ChangeDifficulty(ChangeDifficulty) = CHANGE_DIFFICULTY,
ChunkBatchFinished(ChunkBatchFinished) = CHUNK_BATCH_FINISHED,
ChunkBatchStart(Empty) = CHUNK_BATCH_START,
@@ -1707,6 +1863,7 @@ packet_enum!(Clientbound, crate::ids::play::clientbound {
SetTitlesAnimation(TitlesAnimation) = SET_TITLES_ANIMATION,
Sound(Sound) = SOUND,
SoundEntity(SoundEntity) = SOUND_ENTITY,
StopSound(StopSound) = STOP_SOUND,
StartConfiguration(Empty) = START_CONFIGURATION,
SwingAnimation(SwingAnimation) = SWING_ANIMATION,
SystemChat(SystemChat) = SYSTEM_CHAT,
@@ -2793,10 +2950,11 @@ mod tests {
#[test]
fn unknown_packets_keep_their_payload() {
let p = Clientbound::decode(crate::ids::play::clientbound::BOSS_EVENT, &[1, 2, 3]).unwrap();
let p =
Clientbound::decode(crate::ids::play::clientbound::PLAYER_LOOK_AT, &[1, 2, 3]).unwrap();
assert_eq!(
p,
Clientbound::Unknown(crate::ids::play::clientbound::BOSS_EVENT, vec![1, 2, 3])
Clientbound::Unknown(crate::ids::play::clientbound::PLAYER_LOOK_AT, vec![1, 2, 3])
);
assert_eq!(p.encode()[1..], [1, 2, 3]);
}
@@ -2894,6 +3052,44 @@ mod tests {
assert!(BookPages::read(&mut Reader::new(&w.data)).is_err());
}
#[test]
fn boss_event_round_trips() {
let add = Clientbound::BossEvent(BossEvent {
id: 0x0123_4567_89ab_cdef_fedc_ba98_7654_3210,
action: BossAction::Add {
name: Tag::String("Wither".into()),
progress: 0.5,
color: 5,
overlay: 0,
darken: true,
music: false,
fog: true,
},
});
let body = add.encode();
// Packet id 9, then the uuid, operation 0, and the property byte
// (darken 1, fog 4).
assert_eq!(body[0], 9);
assert_eq!(*body.last().unwrap(), 5);
round_trip(add, Clientbound::encode, Clientbound::decode);
round_trip(
Clientbound::BossEvent(BossEvent {
id: 7,
action: BossAction::UpdateProgress { progress: 0.25 },
}),
Clientbound::encode,
Clientbound::decode,
);
round_trip(
Clientbound::BossEvent(BossEvent {
id: 7,
action: BossAction::Remove,
}),
Clientbound::encode,
Clientbound::decode,
);
}
/// A registry entry is its id + 1, the dialog itself a 0 then its NBT.
#[test]
fn dialogs_round_trip() {