use ghast_protocol::{BlockPos, RawPacket};
use super::*;
use crate::common::{Abilities, Controls, Outbound, Pose, Teleport, Vec3};
use crate::hands::{BlockQuery, HeldItem};
fn arr(b: &ghast_physics::math::Aabb) -> [f64; 6] {
[b.min_x, b.min_y, b.min_z, b.max_x, b.max_y, b.max_z]
}
fn ray_1_8(w: &ghast_world::v1_8::World, x: i32, y: i32, z: i32) -> RayBox {
use ghast_physics::v1_8::RayShape;
match ghast_physics::v1_8::ray_shape(w, x, y, z, false) {
RayShape::None => (None, None),
RayShape::Bounds(b) => (Some(arr(&b)), None),
RayShape::Stairs(p) => (None, Some(p.boxes().map(|b| b.as_ref().map(arr)))),
}
}
type RayBox = (Option<[f64; 6]>, Option<[Option<[f64; 6]>; 8]>);
pub(crate) struct Sim18 {
world: ghast_world::v1_8::World,
pub(super) player: ghast_physics::v1_8::PlayerState,
packets: ghast_physics::Packets,
rec: Option<crate::record::Recorder>,
force_step_position: ForceStepPosition,
entities: Option<ghast_entity::v1_8::Tracker>,
updates: BlockUpdates,
session: SessionPackets,
block_entities: bool,
ride: Option<Box<Ride18>>,
own_id: Option<i32>,
#[cfg(test)]
vaporizes: bool,
server_flags: Option<u8>,
absorption: f32,
absorption_dirty: bool,
pistons: ghast_physics::v1_8::Pistons,
piston_edits: ghast_physics::v1_8::Edits,
piston_uncertain_at: Option<i32>,
piston_phase: bool,
ray_missed: bool,
head_watch: bool,
heads: Vec<[i32; 3]>,
heads_center: Option<[i32; 3]>,
#[cfg(test)]
trig: Vec<(u64, f64, f64)>,
}
#[cfg(test)]
struct TableTrig<'a>(&'a [(u64, f64, f64)]);
#[cfg(test)]
impl ghast_physics::v1_8::JavaTrig for TableTrig<'_> {
fn sin(&self, x: f64) -> f64 {
self.0
.iter()
.find(|e| e.0 == x.to_bits())
.map_or_else(|| x.sin(), |e| e.1)
}
fn cos(&self, x: f64) -> f64 {
self.0
.iter()
.find(|e| e.0 == x.to_bits())
.map_or_else(|| x.cos(), |e| e.2)
}
}
#[derive(Debug)]
struct Ride18 {
id: i32,
seat: Seat18,
}
#[derive(Debug)]
enum Seat18 {
Boat(ghast_physics::v1_8::Boat),
Cart(ghast_physics::v1_8::Minecart),
}
impl std::fmt::Debug for Sim18 {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Sim18")
.field("world", &self.world)
.field("pos", &self.player.pos)
.finish_non_exhaustive()
}
}
#[cfg(test)]
impl Sim18 {
pub(crate) fn test_player(&self) -> &ghast_physics::v1_8::PlayerState {
&self.player
}
#[cfg(all(feature = "v1_12_2", feature = "v1_16_5", feature = "v26_1"))]
pub(crate) fn test_set_trig(&mut self, t: Vec<(u64, f64, f64)>) {
self.trig = t;
}
pub(crate) fn test_set_player(&mut self, pose: &mut Pose, p: ghast_physics::v1_8::PlayerState) {
self.player = p;
self.piston_uncertain_at = None;
sync_pose(pose, &self.player);
}
#[cfg(all(test, feature = "v1_12_2", feature = "v1_16_5"))]
pub(crate) fn test_set_block(
&mut self,
x: i32,
y: i32,
z: i32,
s: ghast_data::v1_8::BlockState,
) {
let old = self.world.block_state(x, y, z);
self.head_change(x, y, z, old, s.block().id() == 34);
self.world.set_block_state(x, y, z, s);
}
pub(crate) fn test_world(&self) -> &ghast_world::v1_8::World {
&self.world
}
}
impl Sim18 {
pub(crate) fn new() -> Self {
Sim18 {
world: ghast_world::v1_8::World::new(config()),
player: ghast_physics::v1_8::PlayerState::new([0.0; 3], 0.0, 0.0),
packets: ghast_physics::Packets::new(),
rec: None,
force_step_position: ForceStepPosition::Off,
entities: None,
updates: BlockUpdates::default(),
session: SessionPackets::default(),
block_entities: false,
ride: None,
own_id: None,
#[cfg(test)]
vaporizes: false,
server_flags: None,
absorption: 0.0,
absorption_dirty: false,
pistons: ghast_physics::v1_8::Pistons::new(),
piston_edits: ghast_physics::v1_8::Edits::new(),
piston_uncertain_at: None,
piston_phase: false,
ray_missed: false,
head_watch: false,
heads: Vec::new(),
heads_center: None,
#[cfg(test)]
trig: Vec::new(),
}
}
pub(crate) fn with(opts: &SimOptions) -> Self {
let mut s = Self::new();
s.force_step_position = opts.force_step_position;
s.entities = opts.entities.map(ghast_entity::v1_8::Tracker::new);
if let Some(c) = opts.world {
s.world = ghast_world::v1_8::World::new(c);
s.block_entities = c.block_entities;
}
if opts.shared_chunks.is_some() {
log::debug!("shared chunks are not used on 1.8.9; every section stays owned");
}
if let Some(p) = opts.record.as_deref() {
match crate::record::Recorder::create(p) {
Ok(r) => s.rec = Some(r),
Err(e) => log::warn!("cannot record to {}: {e}", p.display()),
}
}
s
}
}
impl Sim18 {
fn block_action(&mut self, raw: &RawPacket) -> Result<(), SimError> {
use ghast_protocol::v1_8::play::clientbound as cb;
let p: cb::BlockAction = raw.decode_as()?;
let block = p.block_id & 4095;
if block != 29 && block != 33 {
return Ok(());
}
self.piston_edits.clear();
self.pistons.block_event(
&self.world,
[p.location.x, p.location.y, p.location.z],
block as u8,
p.byte1,
p.byte2,
&mut self.piston_edits,
);
self.apply_piston_edits();
Ok(())
}
#[cold]
#[inline(never)]
fn step_pistons(&mut self, input: &ghast_physics::TickInput) {
if let Some(r) = &mut self.rec {
r.note_once("moving pistons not representable");
}
{
if std::mem::take(&mut self.ray_missed) {
self.pistons.forget_head_bounds(0x3f);
}
let p = &self.player;
let eye_h = if p.input.sneak {
1.62f32 - 0.08
} else {
1.62f32
};
let eye = ghast_physics::pick::legacy::eye_position(p.pos, eye_h);
let reach = f64::from(if p.abilities.creative { 5.0f32 } else { 4.5f32 });
self.pistons.crosshair(
&self.world,
eye,
ghast_physics::pick::legacy::look_vector(p.yaw, input.pitch),
reach,
);
}
let before = self.player.bb;
ghast_physics::v1_8::tick_player_among_pistons(
&mut self.player,
input,
&self.world,
&ghast_physics::v1_8::Options::default(),
&self.pistons,
&mut self.packets,
);
let head_unknown = self.pistons.head_unknown_touching(&before, &self.player.bb);
if self.entities.is_some() && !self.pistons.is_empty() {
self.piston_phase = true;
} else {
self.piston_edits.clear();
self.pistons.tick_after_entities(
&mut self.player,
&self.world,
&ghast_physics::v1_8::Options::default(),
&mut self.piston_edits,
);
self.apply_piston_edits();
self.flag_untracked();
}
if head_unknown {
self.piston_uncertain_at = Some(self.player.ticks_alive);
}
self.heads_near();
}
#[cold]
#[inline(never)]
fn heads_near(&mut self) -> bool {
const SCAN: i32 = 10;
let p = self.player.pos;
let eye = [p[0], p[1] + 1.62, p[2]];
let at = eye.map(|v| v.floor() as i32);
let far = |c: [i32; 3]| (0..3).any(|k| (at[k] - c[k]).abs() > SCAN - 7);
if self.heads_center.is_none_or(far) {
self.heads.clear();
scan_heads(&self.world, at, SCAN, &mut self.heads);
self.heads_center = Some(at);
}
let near = self.heads.iter().any(|h| {
let d = (0..3)
.map(|k| (f64::from(h[k]) + 0.5 - eye[k]).powi(2))
.sum::<f64>();
d <= 8.0 * 8.0
});
self.pistons.set_ray_needed(near);
near
}
#[cold]
#[inline(never)]
fn heads_out_of_reach(&mut self) -> bool {
self.pistons.watch_only() && !self.heads_near()
}
#[cold]
#[inline(never)]
fn watch_heads(&mut self) {
self.head_watch = true;
self.pistons.set_heads_loaded(true);
}
fn columns_loaded(&mut self, cols: impl Iterator<Item = (i32, i32)>) {
for (cx, cz) in cols {
if let Some(c) = self.heads_center {
const R: i32 = 10;
let meets = |v: i32, at: i32| v * 16 <= at + R && v * 16 + 15 >= at - R;
if meets(cx, c[0]) && meets(cz, c[2]) {
self.heads_center = None;
}
}
if self.head_watch {
continue;
}
let Some(col) = self.world.column(cx, cz) else {
continue;
};
if (0..16).any(|i| {
col.section(i)
.is_some_and(|s| s.any_state(|r| r >> 4 == 34))
}) {
self.watch_heads();
}
}
}
fn world_replaced(&mut self) {
self.heads.clear();
self.heads_center = None;
if self.world.columns().is_empty() {
self.head_watch = false;
self.pistons.set_heads_loaded(false);
self.pistons.set_ray_needed(false);
}
}
#[inline]
fn head_change(
&mut self,
x: i32,
y: i32,
z: i32,
old: Option<ghast_data::v1_8::BlockState>,
new_is_head: bool,
) {
if new_is_head && !self.head_watch {
self.watch_heads();
}
if head_facing(old) == 0 && !new_is_head {
return;
}
if self.heads_center.is_some() {
self.heads.retain(|h| *h != [x, y, z]);
if new_is_head {
self.heads.push([x, y, z]);
}
}
}
fn flag_untracked(&mut self) {
if self.pistons.take_unmodelled() | self.pistons.untracked_near(&self.player.bb) {
self.piston_uncertain_at = Some(self.player.ticks_alive);
}
}
#[cold]
#[inline(never)]
fn tick_piston_phase(&mut self, pose: &mut Pose) {
use ghast_entity::EntityType;
use ghast_physics::math::Aabb;
use ghast_physics::v1_8 as phys;
self.piston_phase = false;
let mut others: Vec<(i32, phys::PistonEntity)> = Vec::new();
let mut solids: Vec<(Aabb, [i32; 3])> = Vec::new();
if let Some(t) = self.entities.as_ref().filter(|t| t.tracks_client_motion()) {
let me = t.self_id();
for e in t.iter() {
if Some(e.id()) == me {
continue;
}
let (Some(b), Some(o)) = (e.drawn_bounding_box(), e.search_order()) else {
continue;
};
let bb = Aabb::new(b[0], b[1], b[2], b[3], b[4], b[5]);
let section = [o.0, o.2, o.1];
let ty = e.entity_type();
if ty == EntityType::LegacyObject(1) {
solids.push((bb, section));
}
let living = matches!(
ty,
EntityType::Player | EntityType::LegacyMob(_) | EntityType::LegacyObject(78)
);
let solid_object =
matches!(ty, EntityType::LegacyObject(1 | 10 | 50 | 51 | 63 | 70));
if !living && !solid_object {
continue;
}
let spectator = ty == EntityType::Player && t.tab_game_mode(&e.uuid()) == Some(3);
let step_height = match ty {
EntityType::Player => 0.0,
EntityType::LegacyMob(58) => 1.0,
EntityType::LegacyMob(100) => 0.5,
_ => phys::STEP_HEIGHT,
};
let p = e.drawn_position();
others.push((
e.id(),
phys::PistonEntity {
bb,
pos: p,
on_ground: e.drawn_on_ground(),
in_web: e.drawn_in_web(),
step_height,
sneaking: ty == EntityType::Player
&& ghast_entity::v1_8::flags(e) & 0x02 != 0,
moved: !spectator,
followed: living && e.vehicle().is_none() && e.passengers().is_empty(),
section,
},
));
}
}
let before: Vec<phys::PistonEntity> = others.iter().map(|o| o.1).collect();
let mut list: Vec<phys::PistonEntity> = others.iter().map(|o| o.1).collect();
self.piston_edits.clear();
if self.ride.is_some() {
self.pistons.tick_blocks_among(
&self.world,
&phys::Options::default(),
&mut list,
&solids,
&mut self.piston_edits,
);
} else {
self.pistons.tick_after_entities_among(
&mut self.player,
&self.world,
&phys::Options::default(),
&mut list,
&solids,
&mut self.piston_edits,
);
}
self.apply_piston_edits();
if let Some(t) = &mut self.entities {
for ((id, _), (a, b)) in others.iter().zip(list.iter().zip(&before)) {
if a != b {
let x = a.bb;
t.client_pushed(
*id,
a.pos,
[x.min_x, x.min_y, x.min_z, x.max_x, x.max_y, x.max_z],
a.on_ground,
a.in_web,
);
}
}
}
if self.ride.is_none() {
self.flag_untracked();
sync_pose(pose, &self.player);
} else if self.pistons.take_unmodelled() {
self.piston_uncertain_at = Some(self.player.ticks_alive);
}
}
#[cold]
#[inline(never)]
fn tick_piston_blocks(&mut self) {
self.piston_edits.clear();
self.pistons
.tick_blocks(&self.world, &mut self.piston_edits);
self.apply_piston_edits();
}
fn apply_piston_edits(&mut self) {
for k in 0..self.piston_edits.len() {
let ([x, y, z], s) = self.piston_edits[k];
let old = self.world.block_state(x, y, z);
self.head_change(x, y, z, old, s.block().id() == 34);
if self.world.set_block_state(x, y, z, s) {
self.updates
.push(BlockPos::new(x, y, z), u32::from(s.raw()));
}
}
}
#[inline]
fn prune_pistons(&mut self) {
if !self.pistons.is_empty() {
self.prune_pistons_slow();
}
}
#[cold]
#[inline(never)]
fn prune_pistons_slow(&mut self) {
let w = &self.world;
self.pistons.retain(|m| {
w.block_state(m.pos[0], m.pos[1], m.pos[2])
.is_some_and(|s| s.block().id() == ghast_physics::v1_8::MOVING_PISTON)
});
}
fn own_metadata(&mut self, raw: &RawPacket) -> Result<(), SimError> {
use ghast_protocol::defs::p47::types::EntityMetadataValue as V;
use ghast_protocol::v1_8::play::clientbound as cb;
let Some(own) = self.own_id else {
return Ok(());
};
if ghast_protocol::Reader::new(&raw.body).read_varint()? != own {
return Ok(());
}
let p: cb::EntityMetadata = raw.decode_as()?;
for e in &p.metadata {
if let (17, V::Float(a)) = (e.key, &e.value) {
self.absorption = *a;
self.absorption_dirty = true;
}
if let (0, V::Byte(b)) = (e.key, &e.value) {
let flags = *b as u8;
self.server_flags = Some(flags);
self.player.sprinting = flags & 0x08 != 0;
if let Some(r) = &mut self.rec {
r.note("own entity flags not representable");
}
}
}
Ok(())
}
#[cold]
#[inline(never)]
fn vehicle_packet(&mut self, raw: &RawPacket) -> Result<(), SimError> {
use ghast_protocol::v1_8::play::clientbound as cb;
let Some(t) = &self.entities else {
return Ok(());
};
if raw.id == cb::id::ATTACH_ENTITY {
let p: cb::AttachEntity = raw.decode_as()?;
if p.leash || t.self_id() != Some(p.entity_id) {
return Ok(());
}
if p.vehicle_id == -1 {
if let Some(r) = self.ride.take() {
log::debug!("left boat {}", r.id);
}
return Ok(());
}
let seat = t.get(p.vehicle_id).and_then(|e| {
let fixed = e.position().map(|v| (v * 32.0).round() as i32);
let yaw = (e.yaw() * 256.0 / 360.0).round() as i32 as i8;
let pitch = (e.pitch() * 256.0 / 360.0).round() as i32 as i8;
match e.entity_type() {
ghast_entity::EntityType::LegacyObject(1) => Some(Seat18::Boat(
ghast_physics::v1_8::Boat::spawned(fixed, yaw, pitch),
)),
ghast_entity::EntityType::LegacyObject(10) => Some(Seat18::Cart(
ghast_physics::v1_8::Minecart::spawned(fixed, yaw, pitch),
)),
_ => None,
}
});
match seat {
Some(seat) => {
log::debug!("riding {}", p.vehicle_id);
self.ride = Some(Box::new(Ride18 {
id: p.vehicle_id,
seat,
}));
}
None => {
self.ride = None;
log::debug!("riding {} (not simulated: not a boat)", p.vehicle_id);
}
}
return Ok(());
}
let Some(r) = self.ride.as_deref_mut() else {
return Ok(());
};
if let Seat18::Cart(c) = &mut r.seat {
let id = r.id;
match raw.id {
cb::id::ENTITY_TELEPORT => {
let p: cb::EntityTeleport = raw.decode_as()?;
if p.entity_id == id {
c.server_teleport([p.x, p.y, p.z], p.yaw, p.pitch);
}
}
cb::id::REL_ENTITY_MOVE => {
let p: cb::RelEntityMove = raw.decode_as()?;
if p.entity_id == id {
c.server_update([p.d_x, p.d_y, p.d_z], None);
}
}
cb::id::ENTITY_MOVE_LOOK => {
let p: cb::EntityMoveLook = raw.decode_as()?;
if p.entity_id == id {
c.server_update([p.d_x, p.d_y, p.d_z], Some((p.yaw, p.pitch)));
}
}
cb::id::ENTITY_LOOK => {
let p: cb::EntityLook = raw.decode_as()?;
if p.entity_id == id {
c.server_update([0; 3], Some((p.yaw, p.pitch)));
}
}
cb::id::ENTITY => {
let p: cb::Entity = raw.decode_as()?;
if p.entity_id == id {
c.server_update([0; 3], None);
}
}
cb::id::ENTITY_DESTROY => {
let p: cb::EntityDestroy = raw.decode_as()?;
if p.entity_ids.contains(&id) {
log::debug!("minecart {id} destroyed");
self.ride = None;
}
}
_ => {}
}
return Ok(());
}
let Seat18::Boat(b) = &mut r.seat else {
return Ok(());
};
match raw.id {
cb::id::ENTITY_TELEPORT => {
let p: cb::EntityTeleport = raw.decode_as()?;
if p.entity_id == r.id {
b.server_teleport([p.x, p.y, p.z], p.yaw, p.pitch, p.on_ground);
}
}
cb::id::REL_ENTITY_MOVE => {
let p: cb::RelEntityMove = raw.decode_as()?;
if p.entity_id == r.id {
b.server_move([p.d_x, p.d_y, p.d_z], p.on_ground);
}
}
cb::id::ENTITY_MOVE_LOOK => {
let p: cb::EntityMoveLook = raw.decode_as()?;
if p.entity_id == r.id {
b.server_move([p.d_x, p.d_y, p.d_z], p.on_ground);
}
}
cb::id::ENTITY_LOOK => {
let p: cb::EntityLook = raw.decode_as()?;
if p.entity_id == r.id {
b.server_move([0; 3], p.on_ground);
}
}
cb::id::ENTITY => {
let p: cb::Entity = raw.decode_as()?;
if p.entity_id == r.id {
b.server_move([0; 3], false);
}
}
cb::id::ENTITY_VELOCITY => {
let p: cb::EntityVelocity = raw.decode_as()?;
if p.entity_id == r.id {
let v = p.velocity;
let c = |x: i16| f64::from(x) / 8000.0;
b.server_velocity([c(v.x), c(v.y), c(v.z)]);
}
}
cb::id::ENTITY_DESTROY => {
let p: cb::EntityDestroy = raw.decode_as()?;
if p.entity_ids.contains(&r.id) {
log::debug!("boat {} destroyed", r.id);
self.ride = None;
}
}
_ => {}
}
Ok(())
}
#[cold]
#[inline(never)]
fn step_ride(&mut self, input: &ghast_physics::TickInput) {
if self.head_watch && self.heads_near() {
self.ray_missed = true;
}
let Some(r) = self.ride.as_deref_mut() else {
return;
};
let id = r.id;
let boat = match &mut r.seat {
Seat18::Boat(b) => b,
Seat18::Cart(c) => {
ghast_physics::v1_8::tick_minecart(
&mut self.player,
c,
input,
&self.world,
&ghast_physics::v1_8::Options::default(),
&mut self.packets,
);
return;
}
};
#[cfg(test)]
let still = ghast_physics::v1_8::tick_boat_with(
&mut self.player,
boat,
input,
&self.world,
&ghast_physics::v1_8::Options::default(),
&TableTrig(&self.trig),
&mut self.packets,
);
#[cfg(not(test))]
let still = ghast_physics::v1_8::tick_boat(
&mut self.player,
boat,
input,
&self.world,
&ghast_physics::v1_8::Options::default(),
&mut self.packets,
);
for &[x, y, z] in boat.broken_blocks() {
self.world
.set_block_state(x, y, z, ghast_data::v1_8::BlockState::AIR);
}
if !still {
log::debug!("boat {id} fell out of the world");
self.ride = None;
}
}
}
impl WorldView for Sim18 {
fn collisions(&self) -> (bool, bool) {
(
self.player.horizontal_collision,
self.player.vertical_collision,
)
}
fn piston_uncertain(&self) -> bool {
self.piston_uncertain_at == Some(self.player.ticks_alive)
}
fn column(&self, chunk_x: i32, chunk_z: i32) -> Option<&ghast_world::Column> {
self.world.column(chunk_x, chunk_z)
}
fn is_column_loaded(&self, chunk_x: i32, chunk_z: i32) -> bool {
self.world.is_column_loaded(chunk_x, chunk_z)
}
fn raw_block(&self, x: i32, y: i32, z: i32) -> Option<u32> {
self.world.block_state(x, y, z).map(|s| u32::from(s.raw()))
}
fn entities(&self) -> Option<&ghast_entity::Entities> {
self.entities.as_deref()
}
fn loaded_columns(&self) -> usize {
self.world.columns().len()
}
fn block_query(&self, x: i32, y: i32, z: i32) -> Option<BlockQuery> {
let s = self.world.block_state(x, y, z)?;
let b = s.block();
let info = b.info();
let ray = ray_1_8(&self.world, x, y, z);
Some(BlockQuery {
exact: Some(crate::hands::ExactDig::V1_8),
air: s.is_air(),
water: matches!(b.id(), 8 | 9),
block: u16::from(b.id()),
hardness: info.hardness.unwrap_or(-1.0),
dig_material: info.material,
harvest_tools: info.harvest_tools,
selection: ray.0,
stairs: ray.1,
activates: ACTIVATED_1_8.contains(&b.id()),
})
}
fn crosshair(
&self,
eyes: Vec3,
(yaw, pitch): (f32, f32),
_look: Vec3,
reach: f64,
) -> Option<crate::BlockHit> {
use ghast_physics::pick::v1_8 as pick;
let eye = [eyes.x, eyes.y, eyes.z];
let hit = pick::pick(&self.world, eye, pick::look_vector(yaw, pitch), reach)?;
block_hit(&hit, eye)
}
}
impl Sim for Sim18 {
fn crosshair_target(&self, q: &PickQuery<'_>) -> Crosshair {
use ghast_physics::pick::v1_8 as pick;
let eye = [q.eyes.x, q.eyes.y, q.eyes.z];
let look = pick::look_vector(q.rotation.0, q.rotation.1);
if q.entities.is_empty() {
let reach = if q.creative {
pick::CREATIVE_REACH
} else {
pick::REACH
};
return Crosshair::Block(
pick::pick(&self.world, eye, look, reach).and_then(|h| block_hit(&h, eye)),
);
}
let t = pick::pick_target(&self.world, eye, look, q.creative, &q.player_bb, q.entities);
legacy_crosshair(t, eye)
}
fn world_packet(&mut self, raw: &RawPacket) -> Result<(), SimError> {
{
use ghast_protocol::v1_8::play::clientbound::id;
self.session.note(raw, id::LOGIN, id::RESPAWN);
}
if let Some(t) = &mut self.entities
&& t.wants(raw.id)
{
t.apply(raw)?;
}
use ghast_protocol::v1_8::play::clientbound as cb;
if self.entities.is_some()
&& (raw.id == cb::id::ATTACH_ENTITY
|| (self.ride.is_some()
&& matches!(
raw.id,
cb::id::ENTITY_TELEPORT
| cb::id::REL_ENTITY_MOVE
| cb::id::ENTITY_MOVE_LOOK
| cb::id::ENTITY_LOOK
| cb::id::ENTITY
| cb::id::ENTITY_VELOCITY
| cb::id::ENTITY_DESTROY
)))
{
return self.vehicle_packet(raw);
}
let w = &mut self.world;
match raw.id {
cb::id::LOGIN => {
self.ride = None;
self.pistons.clear();
let p: cb::Login = raw.decode_as()?;
self.own_id = Some(p.entity_id);
w.apply_login(&p);
self.world_replaced();
}
cb::id::ENTITY_METADATA => return self.own_metadata(raw),
cb::id::RESPAWN => {
self.ride = None;
self.pistons.clear();
w.apply_respawn(&raw.decode_as()?);
self.world_replaced();
}
cb::id::MAP_CHUNK => {
let p: cb::MapChunk = raw.decode_as()?;
if p.ground_up && !self.pistons.is_empty() {
self.pistons.chunk_replaced(p.x, p.z);
}
let r = w.apply_map_chunk(&p);
self.columns_loaded(std::iter::once((p.x, p.z)));
r?;
}
cb::id::MAP_CHUNK_BULK => {
let p: cb::MapChunkBulk = raw.decode_as()?;
if !self.pistons.is_empty() {
for m in &p.meta {
self.pistons.chunk_replaced(m.x, m.z);
}
}
let r = w.apply_map_chunk_bulk(&p);
self.columns_loaded(p.meta.iter().map(|m| (m.x, m.z)));
r?;
}
cb::id::BLOCK_CHANGE => {
let p: cb::BlockChange = raw.decode_as()?;
let new_head = p.r#type >> 4 == 34;
if new_head || self.heads_center.is_some() {
let l = p.location;
let old = w.block_state(l.x, l.y, l.z);
self.head_change(l.x, l.y, l.z, old, new_head);
}
let w = &mut self.world;
self.updates.push(p.location, p.r#type as u32);
w.apply_block_change(&p);
self.prune_pistons();
}
cb::id::BLOCK_ACTION => return self.block_action(raw),
cb::id::MULTI_BLOCK_CHANGE => {
let p: cb::MultiBlockChange = raw.decode_as()?;
for r in &p.records {
let x = p.chunk_x * 16 + i32::from(r.horizontal_pos >> 4);
let z = p.chunk_z * 16 + i32::from(r.horizontal_pos & 15);
let new_head = r.block_id >> 4 == 34;
if new_head || self.heads_center.is_some() {
let old = self.world.block_state(x, i32::from(r.y), z);
self.head_change(x, i32::from(r.y), z, old, new_head);
}
self.updates
.push(BlockPos::new(x, i32::from(r.y), z), r.block_id as u32);
}
let w = &mut self.world;
w.apply_multi_block_change(&p);
self.prune_pistons();
}
cb::id::EXPLOSION => {
w.apply_explosion(&raw.decode_as()?);
self.prune_pistons();
}
cb::id::WORLD_BORDER => {
w.apply_world_border(&raw.decode_as()?);
}
cb::id::UPDATE_SIGN if self.block_entities => {
w.apply_update_sign(&raw.decode_as()?);
}
cb::id::TILE_ENTITY_DATA if self.block_entities => {
w.apply_tile_entity_data(&raw.decode_as()?);
}
_ => {}
}
Ok(())
}
fn reset_player(&mut self) {
let abilities = self.player.abilities;
let food = self.player.food_level;
self.player = ghast_physics::v1_8::PlayerState::new([0.0; 3], 0.0, 0.0);
self.piston_uncertain_at = None;
self.player.abilities = abilities;
self.player.food_level = food;
self.ride = None;
self.server_flags = None;
self.absorption_dirty |= self.absorption != 0.0;
self.absorption = 0.0;
}
fn mount_rules(&self, entity_id: i32) -> Option<ghast_inventory::MountRules> {
use ghast_inventory::{MountArmor, MountRules};
let t = self.entities.as_ref()?;
let e = t.get(entity_id)?;
if ghast_entity::v1_8::info(e.entity_type())?.name != "EntityHorse" || !t.config().metadata
{
return None;
}
let horse = e.metadata().byte(19).unwrap_or(0) == 0;
let armor = if horse {
MountArmor::HorseArmor
} else {
MountArmor::None
};
Some(MountRules::new(true, armor))
}
fn vehicle(&self) -> Option<crate::common::Vehicle> {
let r = self.ride.as_deref()?;
let b = match &r.seat {
Seat18::Boat(b) => b,
Seat18::Cart(c) => {
return Some(crate::common::Vehicle {
entity_id: r.id,
pos: Vec3::new(c.pos[0], c.pos[1], c.pos[2]),
yaw: c.yaw,
pitch: c.pitch,
on_ground: false,
controlled: false,
});
}
};
Some(crate::common::Vehicle {
entity_id: r.id,
pos: Vec3::new(b.pos[0], b.pos[1], b.pos[2]),
yaw: b.yaw,
pitch: b.pitch,
on_ground: b.on_ground,
controlled: true,
})
}
fn teleport(&mut self, pose: &mut Pose, t: &Teleport) {
use crate::common::teleport_flags as fl;
let rel = [
t.flags & fl::X != 0,
t.flags & fl::Y != 0,
t.flags & fl::Z != 0,
t.flags & fl::YAW != 0,
t.flags & fl::PITCH != 0,
];
self.player.yaw = pose.yaw;
self.player.pitch = pose.pitch;
let _reply = self
.player
.apply_teleport([t.x, t.y, t.z], t.yaw, t.pitch, rel);
if let Some(r) = &mut self.rec {
let p = &self.player;
r.teleport(
[t.x, t.y, t.z],
t.yaw,
t.pitch,
t.flags,
t.teleport_id,
[p.pos[0], p.bb.min_y, p.pos[2]],
p.yaw,
p.pitch,
);
}
sync_pose(pose, &self.player);
}
fn abilities(&mut self, a: Abilities) {
let a = ghast_physics::Abilities {
invulnerable: a.flags & 1 != 0,
flying: a.flags & 2 != 0,
allow_flying: a.flags & 4 != 0,
creative: a.flags & 8 != 0,
fly_speed: a.flying_speed,
walk_speed: a.walking_speed,
};
if let Some(r) = &mut self.rec {
r.abilities(&a);
}
self.player.apply_abilities(a);
}
fn food(&mut self, food: i32) {
self.player.food_level = food;
}
fn velocity(&mut self, v: Vec3, add: bool) {
if let Some(r) = &mut self.rec {
if add {
r.note("explosion push not representable");
} else {
r.velocity([
(v.x * 8000.0).round() as i32,
(v.y * 8000.0).round() as i32,
(v.z * 8000.0).round() as i32,
]);
}
}
let p = &mut self.player;
if add {
p.vel[0] += v.x;
p.vel[1] += v.y;
p.vel[2] += v.z;
} else {
p.vel = [v.x, v.y, v.z];
}
}
fn movement_speed(&mut self, base: f64, modifiers: &[(u128, f64, u8)]) {
if let Some(r) = &mut self.rec {
r.speed_attribute(base, modifiers);
}
self.player.apply_speed_attribute(base, modifiers);
}
fn status_effects(&mut self, effects: &std::collections::BTreeMap<i8, i8>) {
if let Some(r) = &mut self.rec {
r.effects(effects);
}
let e = &mut self.player.effects;
e.jump_boost = effects.get(&8).map(|a| i32::from(*a));
e.blindness = effects.contains_key(&15);
}
fn boots(&mut self, depth_strider: u8, _soul_speed: u8) {
self.player.depth_strider = depth_strider;
}
fn spectator(&mut self, on: bool) {
self.player.spectator = on;
}
fn set_flying(&mut self, flying: bool, out: &mut Vec<Outbound>) {
let a = &mut self.player.abilities;
if a.flying == flying || (flying && !a.allow_flying) {
return;
}
a.flying = flying;
let a = *a;
if let Some(r) = &mut self.rec {
r.abilities(&a);
}
out.push(Outbound::Abilities {
flags: abilities_flags(&a),
flying_speed: a.fly_speed,
walking_speed: a.walk_speed,
});
}
fn collect_block_updates(&mut self, on: bool) {
self.updates.on = on;
if !on {
self.updates.list.clear();
}
}
fn drain_block_updates(&mut self, out: &mut Vec<(BlockPos, u32)>) -> usize {
out.append(&mut self.updates.list);
std::mem::take(&mut self.updates.dropped)
}
fn world_packet_ids(&self) -> Vec<i32> {
let mut ids: Vec<i32> = self.world.packet_ids().collect();
ids.push(ghast_protocol::v1_8::play::clientbound::id::ENTITY_METADATA);
ids.push(ghast_protocol::v1_8::play::clientbound::id::BLOCK_ACTION);
ids
}
#[cfg(all(test, ghast_modern, feature = "v1_8", feature = "v1_16_5"))]
fn test_set_own_id(&mut self, id: i32) {
self.own_id = Some(id);
}
fn attack_hurts(&self, e: &ghast_entity::Entity) -> bool {
use ghast_entity::EntityType as T;
match e.entity_type() {
T::Player => true,
T::LegacyObject(t) => matches!(t, 1 | 10 | 51 | 63),
_ => false,
}
}
fn attack_slow(&mut self, target: i32, yaw: f32, knockback: i32, sprint_bonus: bool) {
let p = &mut self.player;
if super::attack_knockback_applies(knockback, p.sprinting, sprint_bonus) {
if let Some(t) = &mut self.entities {
let k = (knockback + i32::from(p.sprinting && sprint_bonus)) as f32;
let r = yaw * std::f32::consts::PI / 180.0;
t.add_velocity(
target,
[
f64::from(-ghast_physics::math::sin(r) * k * 0.5),
0.1,
f64::from(ghast_physics::math::cos(r) * k * 0.5),
],
);
}
p.vel[0] *= 0.6;
p.vel[2] *= 0.6;
p.set_sprinting(false);
if let Some(r) = &mut self.rec {
r.note("attack slow-down not representable");
}
}
}
fn server_flags(&self) -> Option<u8> {
self.server_flags
}
#[inline]
fn take_absorption(&mut self) -> Option<f32> {
std::mem::take(&mut self.absorption_dirty).then_some(self.absorption)
}
fn velocity_now(&self) -> Vec3 {
let v = self.player.vel;
Vec3::new(v[0], v[1], v[2])
}
fn entity_config(&self) -> Option<ghast_entity::Config> {
self.entities.as_ref().map(|t| t.config())
}
fn set_entities(&mut self, config: Option<ghast_entity::Config>) {
if self.entity_config() == config {
return;
}
self.entities = config.map(|c| {
let mut t = ghast_entity::v1_8::Tracker::new(c);
self.session.replay(|r| {
if let Err(e) = t.apply(r) {
log::debug!("entity tracker: session packet 0x{:02x}: {e}", r.id);
}
});
t
});
}
fn tick_entities(&mut self, pose: &mut Pose) {
if let Some(t) = &mut self.entities {
t.tick_client();
if self.piston_phase {
self.tick_piston_phase(pose);
}
}
}
fn entities_mut(&mut self) -> Option<&mut ghast_entity::Entities> {
self.entities.as_mut().map(|t| t.store_mut())
}
fn entity_packet_ids(&self) -> Vec<i32> {
self.entities
.as_ref()
.map(|t| t.packet_ids().collect())
.unwrap_or_default()
}
fn predict_air(&mut self, x: i32, y: i32, z: i32) {
self.world
.set_block_state(x, y, z, ghast_data::v1_8::BlockState::AIR);
}
fn place_sent(&mut self, p: &crate::sim::predict::PlaceSent<'_>) -> bool {
let player = self.player.bb;
let used = crate::sim::place18::sent(&mut self.world, &player, p);
log::debug!("place at {:?}: item used {used}", p.pos);
used
}
fn place_rules(
&self,
q: &crate::sim::predict::PlaceQuery<'_>,
) -> crate::sim::predict::PlaceRules {
crate::sim::place18::rules(&self.world, &self.player.bb, q)
}
fn air_use(&self, q: &crate::sim::predict::AirQuery<'_>) -> crate::sim::predict::AirAnswer {
#[cfg(test)]
let vaporizes = self.vaporizes || self.world.dimension() == -1;
#[cfg(not(test))]
let vaporizes = self.world.dimension() == -1;
let riding = self.ride.is_some()
|| self
.entities
.as_deref()
.zip(self.own_id)
.is_some_and(|(t, id)| t.iter().any(|e| e.id() == id && e.vehicle().is_some()));
crate::sim::use18::air_use(
&crate::sim::use18::Ctx {
world: &self.world,
bb: self.player.bb,
vaporizes,
entities: self.entities.as_deref(),
own_id: self.own_id,
riding,
},
q,
)
}
fn air_use_sent(&mut self, blocks: &[(BlockPos, u32)]) {
for &(p, raw) in blocks {
let s = ghast_data::v1_8::BlockState::from_raw_vanilla(raw as u16);
log::debug!("item use set {} at {p:?}", s.block().name());
if s.block().id() == 34 {
let old = self.world.block_state(p.x, p.y, p.z);
self.head_change(p.x, p.y, p.z, old, true);
}
self.world.set_block_state(p.x, p.y, p.z, s);
}
}
#[cfg(test)]
fn test_air_case(&mut self, case: &serde_json::Value) {
self.vaporizes = case["ultrawarm"].as_bool().unwrap_or(false);
}
fn place_suppressed(&self, pos: BlockPos, face: crate::common::Face, held: u16) -> bool {
use ghast_data::v1_8::{Block, BlockState};
const UNDECIDED: &[u16] = &[44, 126, 145, 182];
let w = &self.world;
let unit = ghast_data::Aabb {
min_x: 0.0,
min_y: 0.0,
min_z: 0.0,
max_x: 1.0,
max_y: 1.0,
max_z: 1.0,
};
crate::sim::predict::legacy_place_suppressed(
pos,
face,
held,
UNDECIDED,
|q| w.block_state(q.x, q.y, q.z).map(BlockState::raw),
|id| {
u8::try_from(id)
.ok()
.and_then(Block::from_id)
.is_some_and(|b| b.material().replaceable)
},
|id| {
let Some(b) = u8::try_from(id).ok().and_then(Block::from_id) else {
return false;
};
b.shape_dependency() == ghast_data::ShapeDependency::None
&& (0..16u8).all(|m| {
let s = BlockState::new(b, m);
!s.is_registered() || s.shape() == [unit]
})
},
&self.player.bb,
|_| false,
)
}
#[cfg(test)]
fn set_player_pos(&mut self, p: Vec3) {
self.player.set_position(p.x, p.y, p.z);
}
fn held_item(&self, id: u16, count: u8, efficiency: u8) -> HeldItem {
held_item_facts(DataSet::V1_8, id, count, efficiency)
}
fn step(
&mut self,
pose: &mut Pose,
controls: Controls,
using_item: bool,
entity_id: i32,
out: &mut Vec<Outbound>,
) {
let input = ghast_physics::TickInput {
keys: keys(controls),
yaw: pose.yaw,
pitch: pose.pitch,
using_item,
};
self.packets.clear();
if let Some(r) = &mut self.rec
&& !r.started()
{
r.start_1_8(&self.player);
}
if let Some(r) = &mut self.rec {
let w = &self.world;
r.observe(self.player.pos, |x, y, z| {
w.is_column_loaded(x >> 4, z >> 4)
.then(|| w.block_state(x, y, z).map_or(0, |s| u32::from(s.raw())))
});
}
let riding = self.ride.is_some();
if riding {
if let Some(r) = &mut self.rec {
r.note_once("riding not representable");
}
self.step_ride(&input);
} else if self.pistons.is_empty()
&& (!self.pistons.head_bounds_set() || self.heads_out_of_reach())
{
ghast_physics::v1_8::tick(&mut self.player, &input, &self.world, &mut self.packets);
} else {
self.step_pistons(&input);
}
if riding && !self.pistons.is_empty() {
if self.entities.is_some() {
self.piston_phase = true;
} else {
self.tick_piston_blocks();
}
}
if self.force_step_position != ForceStepPosition::Off && !riding {
let p = &mut self.player;
let cur = [p.pos[0], p.bb.min_y, p.pos[2]];
force_position(
&mut self.packets,
cur,
&mut p.sent.pos,
&mut p.sent.ticks_since_pos,
self.force_step_position,
);
}
if let Some(r) = &mut self.rec {
r.tick(
&input,
&crate::record::state_1_8(&self.player),
&self.packets,
);
}
push_packets(&self.packets, entity_id, out);
sync_pose(pose, &self.player);
self.world.advance_time(50);
}
}
#[cold]
#[inline(never)]
fn scan_heads(w: &ghast_world::v1_8::World, at: [i32; 3], r: i32, out: &mut Vec<[i32; 3]>) {
for x in at[0] - r..=at[0] + r {
for z in at[2] - r..=at[2] + r {
if !w.is_column_loaded(x >> 4, z >> 4) {
continue;
}
for y in (at[1] - r).max(0)..=(at[1] + r).min(255) {
if w.block_state(x, y, z).is_some_and(|s| s.block().id() == 34) {
out.push([x, y, z]);
}
}
}
}
}
#[inline]
fn head_facing(s: Option<ghast_data::v1_8::BlockState>) -> u8 {
match s {
Some(s) if s.block().id() == 34 && s.meta() & 7 <= 5 => 1 << (s.meta() & 7),
_ => 0,
}
}
fn sync_pose(pose: &mut Pose, p: &ghast_physics::v1_8::PlayerState) {
pose.pos = Vec3::new(p.pos[0], p.bb.min_y, p.pos[2]);
pose.motion = Vec3::new(p.vel[0], p.vel[1], p.vel[2]);
pose.yaw = p.yaw;
pose.pitch = p.pitch;
pose.on_ground = p.on_ground;
pose.flying = p.abilities.flying;
pose.sneaking = p.sneaking();
pose.sprinting = p.sprinting;
}