use bytes::Bytes;
use ghast_protocol::types::ByteString;
use uuid::Uuid;
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct Vec3 {
pub x: f64,
pub y: f64,
pub z: f64,
}
impl Vec3 {
#[must_use]
pub const fn new(x: f64, y: f64, z: f64) -> Self {
Vec3 { x, y, z }
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct Pose {
pub pos: Vec3,
pub yaw: f32,
pub pitch: f32,
pub motion: Vec3,
pub on_ground: bool,
pub flying: bool,
pub sneaking: bool,
pub sprinting: bool,
}
impl Pose {
#[must_use]
pub fn eyes(&self, eye_height: f64) -> Vec3 {
Vec3::new(self.pos.x, self.pos.y + eye_height, self.pos.z)
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub struct Controls {
pub forward: bool,
pub back: bool,
pub left: bool,
pub right: bool,
pub jump: bool,
pub sneak: bool,
pub sprint: bool,
}
impl Controls {
pub const NONE: Controls = Controls {
forward: false,
back: false,
left: false,
right: false,
jump: false,
sneak: false,
sprint: false,
};
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ChatPosition {
Chat,
System,
ActionBar,
Other(i8),
}
impl ChatPosition {
#[must_use]
pub fn from_wire(v: i8) -> Self {
match v {
0 => Self::Chat,
1 => Self::System,
2 => Self::ActionBar,
v => Self::Other(v),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ChatMessage {
pub json: ByteString,
pub position: ChatPosition,
pub sender: Option<Uuid>,
pub(crate) rendered: Option<String>,
}
impl ChatMessage {
#[must_use]
pub fn from_json(json: ByteString, position: ChatPosition, sender: Option<Uuid>) -> Self {
ChatMessage {
json,
position,
sender,
rendered: None,
}
}
#[must_use]
pub fn from_text(text: String, position: ChatPosition, sender: Option<Uuid>) -> Self {
ChatMessage {
json: ByteString::from_static(""),
position,
sender,
rendered: Some(text),
}
}
#[must_use]
pub fn text(&self) -> String {
match &self.rendered {
Some(t) => t.clone(),
None => ghast_protocol::chat::to_plain_text(&self.json),
}
}
#[must_use]
pub fn plain(&self) -> String {
ghast_protocol::chat::strip_formatting(&self.text())
}
}
#[must_use]
pub fn chat_to_plain(json: &str) -> String {
ghast_protocol::chat::strip_formatting(&ghast_protocol::chat::to_plain_text(json))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum GameMode {
#[default]
Survival,
Creative,
Adventure,
Spectator,
Other(u8),
}
impl GameMode {
#[must_use]
pub fn from_wire(v: u8) -> Self {
match v & 0x07 {
0 => Self::Survival,
1 => Self::Creative,
2 => Self::Adventure,
3 => Self::Spectator,
_ => Self::Other(v),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct Abilities {
pub flags: i8,
pub flying_speed: f32,
pub walking_speed: f32,
}
impl Default for Abilities {
fn default() -> Self {
Abilities {
flags: 0,
flying_speed: 0.05,
walking_speed: 0.1,
}
}
}
impl Abilities {
#[must_use]
pub fn may_fly(&self) -> bool {
self.flags & 4 != 0
}
#[must_use]
pub fn flying(&self) -> bool {
self.flags & 2 != 0
}
#[must_use]
pub fn invulnerable(&self) -> bool {
self.flags & 1 != 0
}
#[must_use]
pub(crate) fn creative_mode(&self) -> bool {
self.flags & 8 != 0
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct Health {
pub health: f32,
pub food: i32,
pub saturation: f32,
pub absorption: f32,
}
impl Default for Health {
fn default() -> Self {
Health {
health: 20.0,
food: 20,
saturation: 5.0,
absorption: 0.0,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct WorldTime {
pub age: i64,
pub day_time: Option<i64>,
pub day_rate: f32,
}
impl WorldTime {
#[must_use]
pub fn time_of_day(&self) -> Option<i64> {
self.day_time.map(|t| t.rem_euclid(24000))
}
#[must_use]
pub fn day(&self) -> Option<i64> {
self.day_time.map(|t| t.div_euclid(24000))
}
#[must_use]
pub fn day_frozen(&self) -> bool {
self.day_rate == 0.0
}
}
#[derive(Debug, Clone, Copy, PartialEq, Default)]
#[non_exhaustive]
pub struct ClockUpdate {
pub id: i32,
pub total_ticks: i64,
pub partial_tick: f32,
pub rate: f32,
}
impl ClockUpdate {
pub const LEGACY_DAY: i32 = -1;
}
#[derive(Debug, Clone, Copy, PartialEq, Default)]
#[non_exhaustive]
pub struct TimeUpdate {
pub age: i64,
pub clocks: [ClockUpdate; TimeUpdate::MAX_CLOCKS],
pub len: u8,
}
impl TimeUpdate {
pub const MAX_CLOCKS: usize = 3;
#[must_use]
pub fn legacy(age: i64, time: i64) -> TimeUpdate {
let mut u = TimeUpdate {
age,
..TimeUpdate::default()
};
u.push(ClockUpdate {
id: ClockUpdate::LEGACY_DAY,
total_ticks: time.wrapping_abs(),
partial_tick: 0.0,
rate: if time < 0 { 0.0 } else { 1.0 },
});
u
}
pub fn push(&mut self, c: ClockUpdate) {
if let Some(slot) = self.clocks.get_mut(usize::from(self.len)) {
*slot = c;
self.len += 1;
}
}
pub fn decode_modern(body: &bytes::Bytes) -> Result<TimeUpdate, ghast_protocol::DecodeError> {
let mut r = ghast_protocol::Reader::new(body);
let mut u = TimeUpdate {
age: r.read_i64()?,
..TimeUpdate::default()
};
let n = r.read_varint()?;
for _ in 0..n.max(0) {
let c = ClockUpdate {
id: r.read_varint()?,
total_ticks: r.read_varlong()?,
partial_tick: r.read_f32()?,
rate: r.read_f32()?,
};
u.push(c);
}
Ok(u)
}
#[must_use]
pub fn clocks(&self) -> &[ClockUpdate] {
&self.clocks[..usize::from(self.len)]
}
}
#[derive(Debug, Clone, Copy, Default)]
pub(crate) struct Clocks {
known: bool,
age: i64,
last: i64,
len: u8,
c: [ClockUpdate; Clocks::CAP],
}
impl Clocks {
const CAP: usize = 4;
#[inline]
pub(crate) fn tick(&mut self) {
if self.known {
self.age = self.age.wrapping_add(1);
self.advance();
}
}
fn advance(&mut self) {
let d = self.age.wrapping_sub(self.last);
self.last = self.age;
for c in &mut self.c[..usize::from(self.len)] {
let t = f64::from(c.partial_tick) + d as f64 * f64::from(c.rate);
let i = t as i32;
let whole = if t < f64::from(i) { i - 1 } else { i };
c.partial_tick = (t - f64::from(whole)) as f32;
c.total_ticks = c.total_ticks.wrapping_add(i64::from(whole));
}
}
pub(crate) fn apply(&mut self, u: &TimeUpdate) {
if !self.known {
self.known = true;
self.last = u.age;
}
self.age = u.age;
self.advance();
for s in u.clocks() {
let n = usize::from(self.len);
match self.c[..n].iter_mut().find(|c| c.id == s.id) {
Some(c) => *c = *s,
None if n < Clocks::CAP => {
self.c[n] = *s;
self.len += 1;
}
None => {}
}
}
}
pub(crate) fn world_time(&self, day: Option<i32>) -> Option<WorldTime> {
if !self.known {
return None;
}
let c = day.and_then(|id| self.c[..usize::from(self.len)].iter().find(|c| c.id == id));
Some(WorldTime {
age: self.age,
day_time: c.map(|c| c.total_ticks),
day_rate: c.map_or(0.0, |c| c.rate),
})
}
}
pub mod teleport_flags {
pub const X: i8 = 0x01;
pub const Y: i8 = 0x02;
pub const Z: i8 = 0x04;
pub const YAW: i8 = 0x08;
pub const PITCH: i8 = 0x10;
}
#[derive(Debug, Clone, Copy, PartialEq, Default)]
#[non_exhaustive]
pub struct Teleport {
pub x: f64,
pub y: f64,
pub z: f64,
pub yaw: f32,
pub pitch: f32,
pub flags: i8,
pub teleport_id: Option<i32>,
pub relative: u32,
pub delta: Vec3,
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum LoginInbound {
Disconnect(ByteString),
EncryptionRequest {
server_id: ByteString,
public_key: Bytes,
verify_token: Bytes,
},
EncryptionRequestUnauthenticated {
server_id: ByteString,
public_key: Bytes,
verify_token: Bytes,
},
Compress(i32),
Success {
uuid: Option<Uuid>,
username: ByteString,
},
PluginRequest {
message_id: i32,
channel: ByteString,
},
CookieRequest(ByteString),
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct KnownPack {
pub namespace: ByteString,
pub id: ByteString,
pub version: ByteString,
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum ConfigInbound {
KeepAlive(i64),
Ping(i32),
Finish,
Disconnect(String),
SelectKnownPacks(Vec<KnownPack>),
RegistryData(ghast_protocol::RawPacket),
ResourcePackPush {
id: Uuid,
required: bool,
},
CookieRequest(ByteString),
CodeOfConduct(String),
Transfer(String),
ShowDialog(Box<crate::dialog::Dialog>),
ClearDialog,
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum ConfigOutbound {
KeepAlive(i64),
Pong(i32),
Finish,
SelectKnownPacks(Vec<KnownPack>),
ResourcePackStatus {
id: Uuid,
result: i32,
},
CookieResponse {
key: ByteString,
},
AcceptCodeOfConduct,
Brand(String),
Settings(ClientSettings),
CustomClickAction {
id: String,
payload: Option<ghast_protocol::nbt::AnonNbt>,
},
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct JoinGame {
pub entity_id: i32,
pub game_mode: GameMode,
pub dimension: String,
pub hardcore: bool,
pub dimension_nbt: Option<(ghast_protocol::nbt::RawNbt, ghast_protocol::nbt::RawNbt)>,
pub respawn_screen: bool,
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum Inbound {
KeepAlive(i64),
JoinGame(JoinGame),
Respawn {
dimension: String,
game_mode: GameMode,
keep: u8,
},
Teleport(Teleport),
Chat(ChatMessage),
Disconnect(ByteString),
Health(Health),
Time(TimeUpdate),
Abilities(Abilities),
HeldSlot(i8),
GameState {
reason: u8,
value: f32,
},
Transaction {
window_id: i8,
action: i16,
accepted: bool,
},
OpenWindow(i32),
CloseWindow(i32),
SetCompression(i32),
Velocity {
entity_id: i32,
motion: Vec3,
},
ExplosionPush(Vec3),
MovementSpeed {
entity_id: i32,
base: f64,
modifiers: Vec<(Uuid, f64, i8)>,
},
LegacyAttributes {
entity_id: i32,
movement_speed: Option<LegacyAttribute>,
attack_speed: Option<LegacyAttribute>,
},
Effect {
entity_id: i32,
id: i8,
amplifier: i8,
},
EffectApplied(StatusEffect),
SpawnPoint(SpawnPoint),
Death(Death),
Damage(Hurt),
Teams(crate::teams::TeamsPacket),
EffectRemoved {
entity_id: i32,
id: i8,
},
EntityStatus {
entity_id: i32,
status: i8,
},
ItemCooldown {
key: crate::cooldown::CooldownKey,
ticks: i32,
},
Died {
entity_id: i32,
},
Attributes {
entity_id: i32,
attributes: Vec<AttributeUpdate>,
},
Ping(i32),
ChunkBatchStart,
ChunkBatchFinished(i32),
StartConfiguration,
ResourcePackPush {
id: Uuid,
required: bool,
},
CookieRequest(ByteString),
Transfer {
host: String,
port: u16,
},
StoreCookie {
key: ByteString,
value: Bytes,
},
Rotate {
yaw: f32,
pitch: f32,
relative_yaw: bool,
relative_pitch: bool,
},
ShowDialog(std::sync::Arc<crate::dialog::Dialog>),
ClearDialog,
BossBar(crate::hud::BossBarOp),
Title(crate::hud::TitleOp),
ActionBar(crate::hud::Text),
TabList {
header: Option<crate::hud::Text>,
footer: Option<crate::hud::Text>,
},
TabComplete(crate::hud::TabCompleteResponse),
OpenSign(crate::sign::SignEditor),
UseBed {
entity_id: i32,
bed: ghast_protocol::BlockPos,
},
WakeUp(i32),
}
pub type LegacyAttribute = (f64, Vec<(Uuid, f64, i8)>);
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct AttributeUpdate {
pub name: &'static str,
pub base: f64,
pub modifiers: Vec<(ByteString, f64, i8)>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SleepEvent {
FellAsleep(ghast_protocol::BlockPos),
WokeUp,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum EntityAction {
StartSneaking,
StopSneaking,
StartSprinting,
StopSprinting,
StartFallFlying,
StopRidingJump,
LeaveBed,
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub enum MovePacket {
Flying {
on_ground: bool,
horizontal_collision: bool,
},
Position {
pos: Vec3,
on_ground: bool,
horizontal_collision: bool,
},
Look {
yaw: f32,
pitch: f32,
on_ground: bool,
horizontal_collision: bool,
},
PositionLook {
pos: Vec3,
yaw: f32,
pitch: f32,
on_ground: bool,
horizontal_collision: bool,
},
}
impl MovePacket {
#[must_use]
pub fn trace_id(&self) -> &'static str {
match self {
Self::Flying { .. } => "C03",
Self::Position { .. } => "C04",
Self::Look { .. } => "C05",
Self::PositionLook { .. } => "C06",
}
}
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct ClientSettings {
pub locale: String,
pub view_distance: i8,
pub chat_mode: i8,
pub chat_colors: bool,
pub skin_parts: u8,
pub main_hand: i32,
}
impl ClientSettings {
#[must_use]
pub fn with_locale(mut self, locale: impl Into<String>) -> Self {
self.locale = locale.into();
self
}
#[must_use]
pub const fn with_view_distance(mut self, chunks: i8) -> Self {
self.view_distance = chunks;
self
}
#[must_use]
pub const fn with_chat_mode(mut self, mode: i8) -> Self {
self.chat_mode = mode;
self
}
#[must_use]
pub const fn with_chat_colors(mut self, on: bool) -> Self {
self.chat_colors = on;
self
}
#[must_use]
pub const fn with_skin_parts(mut self, mask: u8) -> Self {
self.skin_parts = mask;
self
}
#[must_use]
pub const fn with_main_hand(mut self, hand: i32) -> Self {
self.main_hand = hand;
self
}
}
impl Default for ClientSettings {
fn default() -> Self {
ClientSettings {
locale: "en_US".to_owned(),
view_distance: 8,
chat_mode: 0,
chat_colors: true,
skin_parts: 0x7f,
main_hand: 1,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Face {
Down,
Up,
North,
South,
West,
East,
}
impl Face {
#[must_use]
pub const fn id(self) -> i8 {
match self {
Face::Down => 0,
Face::Up => 1,
Face::North => 2,
Face::South => 3,
Face::West => 4,
Face::East => 5,
}
}
#[must_use]
pub const fn from_id(id: i8) -> Option<Face> {
Some(match id {
0 => Face::Down,
1 => Face::Up,
2 => Face::North,
3 => Face::South,
4 => Face::West,
5 => Face::East,
_ => return None,
})
}
#[must_use]
pub const fn offset(self, p: ghast_protocol::BlockPos) -> ghast_protocol::BlockPos {
let (x, y, z) = match self {
Face::Down => (0, -1, 0),
Face::Up => (0, 1, 0),
Face::North => (0, 0, -1),
Face::South => (0, 0, 1),
Face::West => (-1, 0, 0),
Face::East => (1, 0, 0),
};
ghast_protocol::BlockPos::new(p.x + x, p.y + y, p.z + z)
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub enum EntityUse {
Interact,
Attack,
InteractAt(Vec3),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum DigStatus {
Start,
Abort,
Finish,
ReleaseUseItem,
DropStack,
DropItem,
SwapHands,
ChangeDirection,
}
impl DigStatus {
#[must_use]
pub const fn id(self) -> i32 {
match self {
DigStatus::Start => 0,
DigStatus::Abort => 1,
DigStatus::Finish => 2,
DigStatus::ReleaseUseItem => 5,
DigStatus::DropStack => 3,
DigStatus::DropItem => 4,
DigStatus::SwapHands => 6,
DigStatus::ChangeDirection => 1,
}
}
#[cfg_attr(not(feature = "v26_3"), allow(dead_code))]
pub(crate) const fn id_777(self) -> i32 {
match self {
DigStatus::Start => 0,
DigStatus::ChangeDirection => 1,
DigStatus::Abort => 2,
DigStatus::Finish => 3,
DigStatus::DropStack => 4,
DigStatus::DropItem => 5,
DigStatus::ReleaseUseItem => 6,
DigStatus::SwapHands => 7,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct Vehicle {
pub entity_id: i32,
pub pos: Vec3,
pub yaw: f32,
pub pitch: f32,
pub on_ground: bool,
pub controlled: bool,
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum Outbound {
KeepAlive(i64),
TeleportConfirm(i32),
TeleportConfirmPose {
id: i32,
pos: Vec3,
yaw: f32,
pitch: f32,
},
Move(MovePacket),
EntityAction {
entity_id: i32,
action: EntityAction,
},
RidingJump {
entity_id: i32,
strength: i32,
},
Chat(String),
Respawn,
Transaction {
window_id: i8,
action: i16,
accepted: bool,
},
Abilities {
flags: i8,
flying_speed: f32,
walking_speed: f32,
},
HeldSlot(i16),
Swing,
Punch,
Dig {
status: DigStatus,
pos: ghast_protocol::BlockPos,
face: Face,
},
Place {
pos: ghast_protocol::BlockPos,
face: Face,
cursor: Vec3,
held: Option<ghast_inventory::Stack>,
off_hand: bool,
},
PlaceInside {
pos: ghast_protocol::BlockPos,
face: Face,
cursor: Vec3,
held: Option<ghast_inventory::Stack>,
off_hand: bool,
},
UseItem {
held: Option<ghast_inventory::Stack>,
off_hand: bool,
},
SwingOffHand,
UseEntity {
target: i32,
action: EntityUse,
off_hand: bool,
sneaking: bool,
},
Settings(ClientSettings),
Inventory(ghast_inventory::Outgoing),
Brand(String),
PlayerInput(Controls),
TickEnd,
PlayerLoaded,
ChatSessionUpdate,
ChunkBatchReceived(f32),
Pong(i32),
ResourcePackStatus {
id: Uuid,
result: i32,
},
CookieResponse {
key: ByteString,
value: Option<Bytes>,
},
LookAnswer {
yaw: f32,
pitch: f32,
},
VehicleMove {
pos: Vec3,
yaw: f32,
pitch: f32,
on_ground: bool,
},
SteerVehicle {
sideways: f32,
forward: f32,
jump: bool,
sneak: bool,
},
SteerBoat {
left: bool,
right: bool,
},
CustomClickAction {
id: String,
payload: Option<ghast_protocol::nbt::AnonNbt>,
},
DialogCommand(String),
TabComplete {
id: i32,
text: String,
assume_command: bool,
block: Option<ghast_protocol::BlockPos>,
},
UpdateSign {
pos: ghast_protocol::BlockPos,
front: bool,
lines: Box<[String; 4]>,
},
EditBook(Box<crate::book::BookEdit>),
Raw(ghast_protocol::RawPacket),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct ActiveEffect {
pub id: i8,
pub amplifier: i8,
pub duration: i32,
pub flags: u8,
pub received_tick: u64,
}
impl ActiveEffect {
#[must_use]
pub fn remaining(&self, now: u64) -> Option<i32> {
if self.is_infinite() {
return None;
}
let gone = i64::try_from(now.saturating_sub(self.received_tick)).unwrap_or(i64::MAX);
Some((i64::from(self.duration) - gone).max(0) as i32)
}
#[must_use]
pub fn is_infinite(&self) -> bool {
self.duration == -1
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum EffectEvent {
Applied(ActiveEffect),
Removed(i8),
Cleared,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct StatusEffect {
pub entity_id: i32,
pub id: i8,
pub amplifier: i8,
pub duration: i32,
pub flags: u8,
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct SpawnPoint {
pub pos: ghast_protocol::BlockPos,
pub yaw: f32,
pub pitch: f32,
pub dimension: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Death {
pub entity_id: i32,
pub killer_id: Option<i32>,
pub message: ChatMessage,
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct Knockback {
pub motion: Vec3,
pub explosion: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Hurt {
pub entity_id: i32,
pub status: Option<i8>,
pub source_type: Option<i32>,
pub attacker: Option<i32>,
pub direct: Option<i32>,
}
impl Hurt {
#[must_use]
pub fn from_status(entity_id: i32, status: i8) -> Self {
Hurt {
entity_id,
status: Some(status),
source_type: None,
attacker: None,
direct: None,
}
}
#[must_use]
pub fn from_damage(
entity_id: i32,
source_type: i32,
cause: Option<i32>,
direct: Option<i32>,
) -> Self {
Hurt {
entity_id,
status: None,
source_type: Some(source_type),
attacker: cause,
direct,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum UseEvent {
Started {
item: i32,
off_hand: bool,
},
Finished {
item: i32,
off_hand: bool,
ticks: u32,
},
Released {
item: i32,
off_hand: bool,
ticks: u32,
},
Interrupted {
item: i32,
off_hand: bool,
ticks: u32,
},
}