use ghast_protocol::{BlockPos, RawPacket};
use super::*;
use crate::common::{Abilities, Controls, Outbound, Pose, Teleport, Vec3};
use crate::hands::{BlockQuery, HeldItem};
pub(crate) struct Sim16 {
world: ghast_world::v1_16_5::World,
player: ghast_physics::v1_16_5::PlayerState,
packets: ghast_physics::Packets,
rec: Option<crate::record::Recorder>,
force_step_position: ForceStepPosition,
entities: Option<ghast_entity::v1_16_5::Tracker>,
updates: BlockUpdates,
session: SessionPackets,
block_entities: bool,
entity_push: bool,
teams: Option<Box<super::teams::Teams>>,
profile_name: Box<str>,
around: Around16,
filed_pos: [f64; 3],
ext: ghast_physics::v1_16_5::PlayerExt,
slow: bool,
rt: Riptide16,
unacked: crate::sim::predict::Unacked,
snapped: bool,
}
#[derive(Debug, Default)]
struct HeldCells {
hands: std::cell::Cell<[(u8, bool, i32); 2]>,
watch: std::cell::Cell<bool>,
filter_dirty: std::cell::Cell<bool>,
}
#[derive(Debug)]
struct Riptide16 {
held: Box<HeldCells>,
using: Option<u8>,
use_ticks: u32,
rain_level: f32,
sky: bool,
seed: i64,
own_id: i32,
}
impl Default for Riptide16 {
fn default() -> Self {
Riptide16 {
held: Box::default(),
using: None,
use_ticks: 0,
rain_level: 0.0,
sky: true,
seed: 0,
own_id: i32::MIN,
}
}
}
fn voronoi_cell(seed: i64, x: i32, y: i32, z: i32) -> [i32; 3] {
let mix = |s: i64, salt: i64| {
s.wrapping_mul(
s.wrapping_mul(6_364_136_223_846_793_005)
.wrapping_add(1_442_695_040_888_963_407),
)
.wrapping_add(salt)
};
let distribute = |s: i64| (f64::from((s >> 24).rem_euclid(1024) as i32) / 1024.0 - 0.5) * 0.9;
let (x, y, z) = (x - 2, y - 2, z - 2);
let base = [x >> 2, y >> 2, z >> 2];
let frac = [
f64::from(x & 3) / 4.0,
f64::from(y & 3) / 4.0,
f64::from(z & 3) / 4.0,
];
let mut best = 0;
let mut dist = 0.0;
for o in 0..8 {
let hi = [o & 4 != 0, o & 2 != 0, o & 1 != 0];
let c: [i64; 3] = std::array::from_fn(|i| i64::from(base[i] + i32::from(hi[i])));
let f: [f64; 3] = std::array::from_fn(|i| if hi[i] { frac[i] - 1.0 } else { frac[i] });
let mut l = mix(seed, c[0]);
l = mix(l, c[1]);
l = mix(l, c[2]);
l = mix(l, c[0]);
l = mix(l, c[1]);
l = mix(l, c[2]);
let d = distribute(l);
l = mix(l, seed);
let e = distribute(l);
l = mix(l, seed);
let g = distribute(l);
let sq = |v: f64| v * v;
let v = sq(f[2] + g) + sq(f[1] + e) + sq(f[0] + d);
if o == 0 || dist > v {
best = o;
dist = v;
}
}
[
base[0] + i32::from(best & 4 != 0),
base[1] + i32::from(best & 2 != 0),
base[2] + i32::from(best & 1 != 0),
]
}
fn dimension_flag(dimension: &ghast_protocol::nbt::RawNbt, name: &str) -> Option<bool> {
use ghast_protocol::nbt::Tag;
let Ok(Some(t)) = dimension.parse() else {
return None;
};
match t.tag.as_compound().and_then(|c| c.get(name)) {
Some(Tag::Byte(b)) => Some(*b != 0),
_ => None,
}
}
fn trident_nbt(s: &ghast_inventory::Stack) -> (u8, i32) {
use ghast_protocol::nbt::Tag;
let Some(root) = s.nbt().and_then(|n| n.parse().ok().flatten()) else {
return (0, 0);
};
let Some(c) = root.tag.as_compound() else {
return (0, 0);
};
let num = |t: Option<&Tag>| match t {
Some(Tag::Short(v)) => i32::from(*v),
Some(Tag::Int(v)) => *v,
Some(Tag::Byte(v)) => i32::from(*v),
_ => 0,
};
let mut level = 0;
if let Some(Tag::List(l)) = c.get("Enchantments") {
for e in l.items.iter().filter_map(Tag::as_compound) {
if matches!(e.get("id"), Some(Tag::String(n)) if n == "minecraft:riptide") {
level = u8::try_from(num(e.get("lvl")).clamp(0, 255)).unwrap_or(0);
break;
}
}
}
(level, num(c.get("Damage")))
}
#[derive(Debug, Default)]
struct Around16 {
boxes: Vec<ghast_physics::math::Aabb>,
after: Vec<(u32, ghast_physics::v1_16_5::Pusher)>,
before: Vec<(u32, ghast_physics::v1_16_5::Pusher)>,
ticked: bool,
others: Vec<ghast_physics::v1_16_5::OtherEntity>,
}
const COLLIDES: u8 = 1;
const PUSH_LIVING: u8 = 2;
const PUSH_BOAT: u8 = 4;
fn entity_bits(e: &ghast_entity::Entity) -> u8 {
use ghast_physics::v1_16_5 as phys;
static BITS: std::sync::OnceLock<Box<[u8]>> = std::sync::OnceLock::new();
let bits = BITS.get_or_init(|| {
let types = ghast_data::v1_16_5::entities();
let mut v = vec![
0u8;
types
.iter()
.map(|t| usize::from(t.id) + 1)
.max()
.unwrap_or(0)
];
for t in types {
let mut b = 0;
if phys::collides(t.name) {
b |= COLLIDES;
}
match phys::push_kind(t.name, true) {
Some(phys::PushKind::Boat) => b |= PUSH_BOAT,
Some(phys::PushKind::Living) => b |= PUSH_LIVING,
_ => {}
}
v[usize::from(t.id)] = b;
}
v.into_boxed_slice()
});
match e.entity_type() {
ghast_entity::EntityType::Player => PUSH_LIVING,
ghast_entity::EntityType::Registry(id) => {
let b = bits.get(usize::from(id)).copied().unwrap_or(0);
if e.class() == ghast_entity::EntityClass::Mob {
b
} else {
b & !PUSH_LIVING
}
}
_ => 0,
}
}
fn aabb(b: [f64; 6]) -> ghast_physics::math::Aabb {
ghast_physics::math::Aabb::new(b[0], b[1], b[2], b[3], b[4], b[5])
}
fn near(b: &[f64; 6], p: &ghast_physics::math::Aabb, m: [f64; 3]) -> bool {
!(b[3] < p.min_x - m[0]
|| b[0] > p.max_x + m[0]
|| b[4] < p.min_y - m[1]
|| b[1] > p.max_y + m[1]
|| b[5] < p.min_z - m[2]
|| b[2] > p.max_z + m[2])
}
impl std::fmt::Debug for Sim16 {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Sim16")
.field("world", &self.world)
.finish_non_exhaustive()
}
}
impl Sim16 {
#[cfg(all(test, feature = "v1_8", feature = "v1_12_2", feature = "v1_16_5"))]
pub(crate) fn test_set_block(
&mut self,
x: i32,
y: i32,
z: i32,
st: ghast_data::v1_16_5::BlockState,
) {
self.world.set_block_state(x, y, z, st);
}
pub(crate) fn new() -> Self {
Sim16 {
world: ghast_world::v1_16_5::World::new(config()),
player: ghast_physics::v1_16_5::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,
entity_push: true,
teams: None,
profile_name: "".into(),
around: Around16::default(),
filed_pos: [0.0; 3],
ext: ghast_physics::v1_16_5::PlayerExt::new(),
slow: false,
rt: Riptide16::default(),
unacked: Default::default(),
snapped: false,
}
}
fn update_slow(&mut self) {
self.slow = self.entities.is_some() || !self.ext.is_inert() || self.rt.using.is_some();
}
fn new_world(&mut self, dimension: &ghast_protocol::nbt::RawNbt, seed: i64) {
self.ext.ultrawarm = dimension_flag(dimension, "ultrawarm").unwrap_or(false);
self.rt.sky = dimension_flag(dimension, "has_skylight").unwrap_or(true);
self.rt.seed = seed;
self.update_slow();
}
fn rains_at(&self, x: i32, y: i32, z: i32) -> bool {
let raining = self.rt.rain_level.partial_cmp(&0.2) == Some(std::cmp::Ordering::Greater);
if !raining || !self.rt.sky {
return false;
}
let [qx, qy, qz] = voronoi_cell(self.rt.seed, x, y, z);
let id = match self.world.column(qx >> 2, qz >> 2) {
None => Some(1),
Some(c) => match c.biomes() {
ghast_world::Biomes::Cells(b) => {
let i = (qy.clamp(0, 63) << 4 | (qz & 3) << 2 | (qx & 3)) as usize;
Some(b[i])
}
_ => None,
},
};
let Some(id) = id else {
return true;
};
ghast_data::v1_16_5::biome(id)
.is_none_or(|b| b.precipitation == "rain" && b.temperature >= 0.15)
}
fn wet(&self) -> bool {
use ghast_physics::v1_16_5 as phys;
let p = &self.player;
if p.touching_water {
return true;
}
let (bx, bz) = (p.pos[0].floor() as i32, p.pos[2].floor() as i32);
let (feet, head) = (p.pos[1].floor() as i32, p.bb.max_y.floor() as i32);
let mut q = *p;
match (self.rains_at(bx, feet, bz), self.rains_at(bx, head, bz)) {
(false, false) => return false,
(true, true) => {}
(true, false) => q.bb.max_y = q.pos[1],
(false, true) => q.pos[1] = q.bb.max_y,
}
phys::in_water_or_rain(&q, &self.world, true)
}
fn riptide_use(&mut self, input: &ghast_physics::TickInput, out: &[Outbound]) {
let age = self.player.age;
let hands = self
.rt
.held
.hands
.get()
.map(|h| if h.2 == age { (h.0, h.1) } else { (0, false) });
match (self.rt.using, input.using_item) {
(None, true) => {
let hand = if hands[0].1 { hands[0] } else { hands[1] };
self.rt.using = Some(hand.0);
self.rt.use_ticks = 0;
}
(Some(level), false) => {
self.rt.using = None;
let released = out.iter().rev().any(|o| {
matches!(
o,
Outbound::Dig {
status: crate::common::DigStatus::ReleaseUseItem,
..
}
)
});
if released && level > 0 && self.rt.use_ticks >= 10 && self.wet() {
let boxes = self.launch_boxes();
let around = ghast_physics::v1_16_5::Surroundings::new().with_entities(&boxes);
ghast_physics::v1_16_5::riptide(
&mut self.player,
&mut self.ext,
&around,
&self.world,
level,
input.yaw,
input.pitch,
);
}
}
_ => {}
}
}
fn launch_boxes(&self) -> Vec<ghast_physics::math::Aabb> {
let Some(t) = self.entities.as_ref() else {
return Vec::new();
};
let w = &self.world;
t.iter()
.filter(|e| entity_bits(e) & COLLIDES != 0 && t.client_alive(e.id()))
.filter_map(|e| {
let pos = t.client_position(e.id())?;
w.is_column_loaded((pos[0].floor() as i32) >> 4, (pos[2].floor() as i32) >> 4)
.then(|| t.client_box(e.id()).map(aabb))
.flatten()
})
.collect()
}
#[cfg(all(
test,
feature = "v1_8",
feature = "v1_12_2",
feature = "v1_16_5",
feature = "v26_1"
))]
pub(crate) fn test_ext(&self) -> ghast_physics::v1_16_5::PlayerExt {
self.ext
}
fn tracker(c: ghast_entity::Config) -> ghast_entity::v1_16_5::Tracker {
let mut t = ghast_entity::v1_16_5::Tracker::new(c);
t.track_client_motion(true);
t
}
#[cfg(all(
test,
feature = "v1_8",
feature = "v1_12_2",
feature = "v1_16_5",
feature = "v26_1"
))]
pub(crate) fn test_set_player(&mut self, p: ghast_physics::v1_16_5::PlayerState) {
self.player = p;
self.filed_pos = p.pos;
}
#[cfg(all(
test,
feature = "v1_8",
feature = "v1_12_2",
feature = "v1_16_5",
feature = "v26_1"
))]
pub(crate) fn test_set_profile_name(&mut self, name: &str) {
self.profile_name = name.into();
}
#[cfg(all(
test,
feature = "v1_8",
feature = "v1_12_2",
feature = "v1_16_5",
feature = "v26_1"
))]
pub(crate) fn test_tracker_login(&mut self, own_id: i32) {
use ghast_protocol::v1_16_5::play::clientbound::id;
let Some(t) = &mut self.entities else { return };
let mut b = Vec::new();
b.extend_from_slice(&own_id.to_be_bytes());
b.extend_from_slice(&[0, 0, 0xFF, 1]);
let name = b"minecraft:overworld";
b.push(name.len() as u8);
b.extend_from_slice(name);
b.extend_from_slice(&[10, 0, 0, 0, 10, 0, 0, 0]);
b.push(name.len() as u8);
b.extend_from_slice(name);
b.extend_from_slice(&0i64.to_be_bytes());
b.extend_from_slice(&[20, 10, 0, 1, 0, 0]);
let raw = RawPacket {
id: id::LOGIN,
body: bytes::Bytes::from(b),
};
t.apply(&raw).unwrap();
}
#[cfg(all(
test,
feature = "v1_8",
feature = "v1_12_2",
feature = "v1_16_5",
feature = "v26_1"
))]
pub(crate) fn test_client_box(&self, id: i32) -> Option<([f64; 3], [f64; 6])> {
let t = self.entities.as_ref()?;
Some((t.client_position(id)?, t.client_box(id)?))
}
#[cfg(all(
test,
feature = "v1_8",
feature = "v1_12_2",
feature = "v1_16_5",
feature = "v26_1"
))]
pub(crate) fn test_player(&self) -> &ghast_physics::v1_16_5::PlayerState {
&self.player
}
#[cfg(all(
test,
feature = "v1_8",
feature = "v1_12_2",
feature = "v1_16_5",
feature = "v26_1"
))]
pub(crate) fn test_tick_order(&self) -> Vec<i32> {
self.entities
.as_ref()
.map(|t| t.client_tick_order().collect())
.unwrap_or_default()
}
#[inline(never)]
fn tick_tracked(&mut self, pose: &mut Pose) {
if !std::mem::take(&mut self.around.ticked) {
let w = &self.world;
if let Some(t) = &mut self.entities {
t.tick_client(|x, z| w.is_column_loaded(x, z));
}
return;
}
if self.around.after.is_empty() {
return;
}
let p = &mut self.player;
for (_, pusher) in &self.around.after {
ghast_physics::v1_16_5::push_by(p, self.filed_pos, &self.world, pusher);
}
self.around.after.clear();
pose.motion = Vec3::new(p.vel[0], p.vel[1], p.vel[2]);
}
fn entities_around(&mut self) {
let a = &mut self.around;
a.boxes.clear();
a.after.clear();
a.before.clear();
let Some(t) = self.entities.as_mut() else {
return;
};
let w = &self.world;
let loaded = |x: i32, z: i32| w.is_column_loaded(x, z);
let p = &self.player;
let reach = |v: f64| v.abs() + 3.0;
let m = [reach(p.vel[0]), reach(p.vel[1]), reach(p.vel[2])];
let mut any = false;
for e in t.iter() {
let bits = entity_bits(e);
if bits == 0 {
continue;
}
any = true;
if bits & COLLIDES == 0 || t.ticks_before_self(e.id()) {
continue;
}
if let Some(b) = t.client_box(e.id())
&& near(&b, &p.bb, m)
&& t.client_alive(e.id())
&& t.client_position(e.id())
.is_some_and(|q| loaded((q[0].floor() as i32) >> 4, (q[2].floor() as i32) >> 4))
{
a.boxes.push(aabb(b));
}
}
t.tick_client(loaded);
a.ticked = true;
if !any {
return;
}
if let Some(me) = t.self_id()
&& t.iter().any(|e| e.passengers().contains(&me))
{
a.boxes.clear();
return;
}
let own: &str = &self.profile_name;
let teams = self.teams.as_deref().filter(|t| t.any_rule());
for e in t.iter() {
let bits = entity_bits(e);
if bits == 0 {
continue;
}
let id = e.id();
let before = t.ticks_before_self(id);
let (Some(b), Some(pos)) = (t.client_box(id), t.client_position(id)) else {
continue;
};
if bits & COLLIDES != 0
&& before
&& near(&b, &p.bb, m)
&& t.client_alive(id)
&& loaded((pos[0].floor() as i32) >> 4, (pos[2].floor() as i32) >> 4)
{
a.boxes.push(aabb(b));
}
if !self.entity_push || bits & (PUSH_LIVING | PUSH_BOAT) == 0 {
continue;
}
let margin = if before { [0.25; 3] } else { m };
if !near(&b, &p.bb, margin) || !t.client_ticks(e, loaded) {
continue;
}
if t.is_spectator(e) {
continue;
}
if let Some(teams) = teams {
let mut buf = [0u8; 36];
let name = match t.scoreboard_name(e) {
Some(n) => n,
None => e.uuid().hyphenated().encode_lower(&mut buf),
};
if !teams.may_push(name, own) {
continue;
}
}
let kind = if bits & PUSH_BOAT != 0 {
ghast_physics::v1_16_5::PushKind::Boat
} else {
ghast_physics::v1_16_5::PushKind::Living
};
let rank = t.client_tick_rank(id).unwrap_or(u32::MAX);
let pusher = ghast_physics::v1_16_5::Pusher::new(pos, aabb(b), kind);
if before {
a.before.push((rank, pusher));
} else {
a.after.push((rank, pusher));
}
}
a.before.sort_by_key(|x| x.0);
a.after.sort_by_key(|x| x.0);
let p = &mut self.player;
for (_, pusher) in &a.before {
ghast_physics::v1_16_5::push_by(p, self.filed_pos, &self.world, pusher);
}
}
fn own_metadata(&mut self, raw: &RawPacket) -> Result<(), SimError> {
use ghast_protocol::defs::p754::types::EntityMetadataValue as V;
use ghast_protocol::v1_16_5::play::clientbound as cb;
let mut r = ghast_protocol::Reader::new(&raw.body);
if r.read_varint()? != self.rt.own_id {
return Ok(());
}
let p: cb::EntityMetadata = raw.decode_as()?;
for e in &p.metadata {
if let (7, V::Byte(b)) = (e.key, &e.value) {
self.ext.apply_living_flags(*b as u8);
}
}
self.update_slow();
Ok(())
}
fn spin_contacts(&mut self, before: bool) {
let Some(t) = self.entities.as_ref() else {
return;
};
let w = &self.world;
for e in t.iter() {
let id = e.id();
if t.ticks_before_self(id) != before || t.is_spectator(e) {
continue;
}
let (Some(b), Some(pos)) = (t.client_box(id), t.client_position(id)) else {
continue;
};
if !w.is_column_loaded((pos[0].floor() as i32) >> 4, (pos[2].floor() as i32) >> 4) {
continue;
}
let living = matches!(e.entity_type(), ghast_entity::EntityType::Player)
|| e.class() == ghast_entity::EntityClass::Mob;
self.around
.others
.push(ghast_physics::v1_16_5::OtherEntity::new(aabb(b), living));
}
}
#[inline(never)]
fn slow_tick(&mut self, input: &ghast_physics::TickInput, out: &[Outbound]) {
if self.rt.using.is_some() || input.using_item {
self.riptide_use(input, out);
}
self.around.others.clear();
let spinning = self.ext.riptide_ticks > 0;
if spinning {
self.spin_contacts(false);
}
if self.entities.is_some() {
self.entities_around();
}
if spinning {
self.spin_contacts(true);
}
let around = ghast_physics::v1_16_5::Surroundings::new()
.with_entities(&self.around.boxes)
.with_others(&self.around.others);
if self.ext.is_inert() {
ghast_physics::v1_16_5::tick_in(
&mut self.player,
&around,
input,
&self.world,
&mut self.packets,
);
} else {
ghast_physics::v1_16_5::tick_ext(
&mut self.player,
&mut self.ext,
&around,
input,
&self.world,
&mut self.packets,
);
}
if self.rt.using.is_some() {
self.rt.use_ticks += 1;
}
self.update_slow();
}
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(Self::tracker);
s.teams = s.entities.is_some().then(Box::default);
if let Some(n) = &opts.profile_name {
s.profile_name = n.as_str().into();
}
if let Some(c) = opts.world {
s.world = ghast_world::v1_16_5::World::new(c);
s.block_entities = c.block_entities;
}
if opts.shared_chunks.is_some() {
log::debug!("shared chunks are not used on 1.16.5; every section stays owned");
}
s.update_slow();
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 WorldView for Sim16 {
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.id()))
}
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 info = s.block().info();
let air = s.block().is_air();
let passable = matches!(
info.name,
"water" | "lava" | "fire" | "nether_portal" | "end_portal"
);
Some(BlockQuery {
exact: Some(crate::hands::ExactDig::V1_16_5),
air,
water: info.name == "water",
block: s.block().id(),
hardness: if info.diggable {
info.hardness.unwrap_or(-1.0)
} else {
-1.0
},
dig_material: info.material,
harvest_tools: info.harvest_tools,
selection: if air || passable {
None
} else {
Some(union(s.shape()).unwrap_or([0.0, 0.0, 0.0, 1.0, 1.0, 1.0]))
},
stairs: None,
activates: activates_1_16(info.name),
})
}
fn crosshair(
&self,
eyes: Vec3,
(yaw, pitch): (f32, f32),
_look: Vec3,
reach: f64,
) -> Option<crate::BlockHit> {
use ghast_physics::pick::v1_16_5 as pick;
let eye = [eyes.x, eyes.y, eyes.z];
let hit = pick::pick(
&self.world,
eye,
pick::rotation_vector(yaw, pitch),
reach,
None,
);
block_hit(&hit, eye)
}
}
impl Sim for Sim16 {
fn crosshair_target(&self, q: &PickQuery<'_>) -> Crosshair {
use ghast_physics::pick::v1_16_5 as pick;
let held_block = q
.held
.and_then(ghast_data::v1_16_5::Item::from_id)
.and_then(|i| ghast_data::v1_16_5::Block::from_name(i.info().name));
let eye = [q.eyes.x, q.eyes.y, q.eyes.z];
let look = pick::rotation_vector(q.rotation.0, q.rotation.1);
if q.entities.is_empty() {
let reach = if q.creative {
pick::CREATIVE_REACH
} else {
pick::REACH
};
let hit = pick::pick(&self.world, eye, look, reach, held_block);
return Crosshair::Block(block_hit(&hit, eye));
}
let t = pick::pick_target(
&self.world,
&q.player_bb,
eye,
look,
q.creative,
held_block,
q.entities,
);
modern_crosshair(t, eye)
}
fn crosshair_now(
&self,
eyes: Vec3,
(yaw, pitch): (f32, f32),
_look: Vec3,
held: Option<u16>,
) -> Option<crate::BlockHit> {
use ghast_physics::pick::v1_16_5 as pick;
let held_block = held
.and_then(ghast_data::v1_16_5::Item::from_id)
.and_then(|i| ghast_data::v1_16_5::Block::from_name(i.info().name));
let eye = [eyes.x, eyes.y, eyes.z];
let hit = pick::pick(
&self.world,
eye,
pick::rotation_vector(yaw, pitch),
crate::hands::REACH,
held_block,
);
block_hit(&hit, eye)
}
fn world_packet(&mut self, raw: &RawPacket) -> Result<(), SimError> {
{
use ghast_protocol::v1_16_5::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_16_5::play::clientbound as cb;
if raw.id == cb::id::TEAMS {
if let Some(t) = &mut self.teams
&& !t.apply(&raw.body, super::teams::TeamLayout::Legacy1_16)
{
log::debug!("bad teams packet ({} B)", raw.body.len());
}
return Ok(());
}
if raw.id == cb::id::ENTITY_METADATA {
return self.own_metadata(raw);
}
let w = &mut self.world;
match raw.id {
cb::id::LOGIN => {
let p: cb::Login = raw.decode_as()?;
w.apply_login(&p);
self.rt.own_id = p.entity_id;
self.rt.rain_level = 0.0;
self.new_world(&p.dimension, p.hashed_seed);
if let Some(t) = &mut self.teams {
t.clear();
}
self.unacked.clear();
}
cb::id::RESPAWN => {
let p: cb::Respawn = raw.decode_as()?;
let new = *p.world_name != *w.world_name();
w.apply_respawn(&p);
if new {
self.rt.rain_level = 0.0;
self.new_world(&p.dimension, p.hashed_seed);
}
}
cb::id::MAP_CHUNK => {
w.apply_map_chunk(&raw.decode_as()?)?;
}
cb::id::UNLOAD_CHUNK => {
w.apply_unload_chunk(&raw.decode_as()?);
}
cb::id::UPDATE_VIEW_POSITION => {
w.apply_view_position(&raw.decode_as()?);
}
cb::id::UPDATE_VIEW_DISTANCE => {
w.apply_view_distance(&raw.decode_as()?);
}
cb::id::BLOCK_CHANGE => {
let p: cb::BlockChange = raw.decode_as()?;
self.updates.push(p.location, p.r#type as u32);
w.apply_block_change(&p);
}
cb::id::MULTI_BLOCK_CHANGE => {
let p: cb::MultiBlockChange = raw.decode_as()?;
let c = &p.chunk_coordinates;
let sy = ((c.y << 12) as i32) >> 12;
for &r in &p.records {
let local = (r & 0xFFF) as i32;
let pos = BlockPos::new(
c.x * 16 + ((local >> 8) & 15),
sy.wrapping_mul(16).wrapping_add(local & 15),
c.z * 16 + ((local >> 4) & 15),
);
self.updates.push(pos, ((r as u64) >> 12) as u32);
}
w.apply_multi_block_change(&p);
}
cb::id::EXPLOSION => {
w.apply_explosion(&raw.decode_as()?);
}
cb::id::ACKNOWLEDGE_PLAYER_DIGGING => {
self.action_answer(&raw.decode_as()?);
}
cb::id::WORLD_BORDER => {
w.apply_world_border(&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_16_5::PlayerState::new([0.0; 3], 0.0, 0.0);
self.filed_pos = [0.0; 3];
self.player.abilities = abilities;
self.player.food_level = food;
self.ext.spin_attack = false;
self.ext.riptide_ticks = 0;
self.rt.using = None;
self.rt.held.hands.set([(0, false, -1); 2]);
self.update_slow();
}
fn teleport(&mut self, pose: &mut Pose, t: &Teleport) {
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_flags(t.flags));
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,
p.yaw,
p.pitch,
);
}
sync_pose_16(pose, &self.player);
}
fn abilities(&mut self, a: Abilities) {
let a = physics_abilities(a);
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);
e.levitation = effects.get(&25).map(|a| i32::from(*a));
e.slow_falling = effects.contains_key(&28);
e.dolphins_grace = effects.contains_key(&30);
}
fn boots(&mut self, depth_strider: u8, soul_speed: u8) {
self.player.enchantments.depth_strider = depth_strider;
self.player.enchantments.soul_speed = soul_speed;
}
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> {
use ghast_protocol::v1_16_5::play::clientbound as cb;
let mut ids: Vec<i32> = self.world.packet_ids().collect();
ids.push(cb::id::ACKNOWLEDGE_PLAYER_DIGGING);
if self.rt.held.watch.get() {
ids.push(cb::id::ENTITY_METADATA);
}
ids
}
fn take_filter_dirty(&mut self) -> bool {
self.rt.held.filter_dirty.replace(false)
}
#[inline(never)]
fn weather(&mut self, reason: u8, value: f32) {
self.rt.rain_level = match reason {
1 => 0.0,
2 => 1.0,
_ => value.clamp(0.0, 1.0),
};
}
#[inline(never)]
fn item_use_facts(
&self,
stack: &ghast_inventory::Stack,
off_hand: bool,
mut held: HeldItem,
) -> HeldItem {
let trident = u16::try_from(stack.id())
.ok()
.and_then(ghast_data::v1_16_5::Item::from_id)
.is_some_and(|i| i.info().name == "trident");
let mut level = 0;
if trident {
let (lvl, damage) = trident_nbt(stack);
level = lvl;
held.usable = held.usable && damage < 250 - 1 && (lvl == 0 || self.wet());
if lvl > 0 && !self.rt.held.watch.replace(true) {
self.rt.held.filter_dirty.set(true);
}
}
let starts =
held.usable && (!held.food || held.always_edible || self.player.food_level < 20);
let mut h = self.rt.held.hands.get();
h[usize::from(off_hand)] = (level, starts, self.player.age);
self.rt.held.hands.set(h);
held
}
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.teams = config.is_some().then(Box::default);
self.entities = config.map(|c| {
let mut t = Self::tracker(c);
self.session.replay(|r| {
if let Err(e) = t.apply(r) {
log::debug!("entity tracker: session packet 0x{:02x}: {e}", r.id);
}
});
t
});
self.update_slow();
}
fn entity_packet_ids(&self) -> Vec<i32> {
use ghast_protocol::v1_16_5::play::clientbound as cb;
self.entities
.as_ref()
.map(|t| t.packet_ids().chain([cb::id::TEAMS]).collect())
.unwrap_or_default()
}
#[inline(always)]
fn tick_entities(&mut self, pose: &mut Pose) {
if self.entities.is_some() {
self.tick_tracked(pose);
}
}
fn set_entity_push(&mut self, on: bool) {
self.entity_push = on;
}
fn predict_air(&mut self, x: i32, y: i32, z: i32) {
self.world
.set_block_state(x, y, z, ghast_data::v1_16_5::BlockState::AIR);
}
fn dig_sent(
&mut self,
pos: BlockPos,
status: crate::common::DigStatus,
broken: bool,
_sequence: i32,
player: Vec3,
) {
use crate::common::DigStatus;
if matches!(
status,
DigStatus::Start | DigStatus::Abort | DigStatus::Finish
) {
self.unacked
.put(pos, status.id() as u8, [player.x, player.y, player.z]);
}
if broken {
self.predict_air(pos.x, pos.y, pos.z);
}
}
#[inline(always)]
fn records_digs(&self) -> bool {
true
}
fn take_snap(&mut self) -> Option<Vec3> {
if !std::mem::take(&mut self.snapped) {
return None;
}
let p = self.player.pos;
Some(Vec3::new(p[0], p[1], p[2]))
}
fn held_item(&self, id: u16, count: u8, efficiency: u8) -> HeldItem {
held_item_facts(DataSet::V1_16_5, 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_16(&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.id())))
});
}
if self.slow || using_item {
self.slow_tick(&input, out);
} else {
ghast_physics::v1_16_5::tick(&mut self.player, &input, &self.world, &mut self.packets);
}
self.filed_pos = self.player.pos;
if self.force_step_position != ForceStepPosition::Off {
let p = &mut self.player;
let cur = p.pos;
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_16(&self.player),
&self.packets,
);
}
push_packets(&self.packets, entity_id, out);
sync_pose_16(pose, &self.player);
self.world.advance_time(50);
}
}
impl Sim16 {
#[cold]
#[inline(never)]
fn action_answer(
&mut self,
p: &ghast_protocol::v1_16_5::play::clientbound::AcknowledgePlayerDigging,
) {
use ghast_data::v1_16_5::BlockState;
let pos = p.location;
let at = u8::try_from(p.status)
.ok()
.and_then(|a| self.unacked.remove(pos, a));
let state = u16::try_from(p.block)
.ok()
.and_then(BlockState::from_id)
.unwrap_or(BlockState::AIR);
let now = self
.world
.block_state(pos.x, pos.y, pos.z)
.unwrap_or(BlockState::AIR);
let start = p.status == crate::common::DigStatus::Start.id();
if now != state && (at.is_none() || !p.successful || !start) {
self.world.set_block_state(pos.x, pos.y, pos.z, state);
if let Some(at) = at
&& holds_player(state, pos, &self.player.bb)
{
self.player.set_position(at[0], at[1], at[2]);
self.snapped = true;
}
}
self.unacked.trim();
}
}
fn holds_player(
state: ghast_data::v1_16_5::BlockState,
pos: BlockPos,
bb: &ghast_physics::math::Aabb,
) -> bool {
use ghast_data::v1_16_5::VoxelClass;
use ghast_physics::voxel::{Points, VoxelShape};
let r = state.voxel_shape();
let axis = |n: u8, pts: &'static [f64]| match r.class {
VoxelClass::Simple => Points::Fractional(u32::from(n)),
VoxelClass::Array => Points::Explicit(pts),
};
let shape = VoxelShape {
axes: [
axis(r.sizes[0], r.xs),
axis(r.sizes[1], r.ys),
axis(r.sizes[2], r.zs),
],
cells: r.cells,
};
crate::sim::predict::shape_overlaps(shape, pos, bb)
}
fn sync_pose_16(pose: &mut Pose, p: &ghast_physics::v1_16_5::PlayerState) {
pose.pos = Vec3::new(p.pos[0], p.pos[1], 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;
}
#[cfg(all(test, ghast_modern))]
mod tests {
#[test]
fn voronoi_cell_is_the_modern_zoom() {
let mut r: u64 = 0x9E37_79B9_7F4A_7C15;
let mut next = || {
r ^= r << 13;
r ^= r >> 7;
r ^= r << 17;
r
};
for _ in 0..20_000 {
let seed = next() as i64;
let p = [next(), next(), next()].map(|v| (v as i32) >> 8);
assert_eq!(
super::voronoi_cell(seed, p[0], p[1], p[2]),
ghast_world::climate::zoom_cell(seed, p[0], p[1], p[2]),
"seed {seed} at {p:?}"
);
}
}
}