use std::collections::HashMap;
use std::hash::{BuildHasherDefault, Hasher};
use super::*;
use ghast_physics::modern::Side;
use ghast_physics::modern::drop::{self, Drop, DropKind};
use ghast_physics::modern::projectile::{self, HookedEntity, Projectile, ProjectileKind};
mod data_index {
pub(super) const NO_GRAVITY: u8 = 5;
pub(super) const FIRST: u8 = 8;
pub(super) const BITING: u8 = 9;
pub(super) const ARROW_IN_GROUND: u8 = 10;
}
#[derive(Default)]
pub(super) struct IdHasher(u64);
impl Hasher for IdHasher {
fn finish(&self) -> u64 {
self.0
}
fn write(&mut self, bytes: &[u8]) {
for &b in bytes {
self.0 = self.0.rotate_left(8) ^ u64::from(b);
}
}
fn write_i32(&mut self, i: i32) {
self.0 = u64::from(i as u32).wrapping_mul(0x9E37_79B9_7F4A_7C15);
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Kind {
Projectile(ProjectileKind),
Drop(DropKind),
}
impl Kind {
fn of(name: &str) -> Option<Kind> {
ProjectileKind::from_entity_name(name)
.map(Kind::Projectile)
.or_else(|| DropKind::from_entity_name(name).map(Kind::Drop))
}
fn arrow(self) -> bool {
matches!(
self,
Kind::Projectile(
ProjectileKind::Arrow | ProjectileKind::SpectralArrow | ProjectileKind::Trident
)
)
}
}
#[derive(Debug)]
enum State {
Projectile(Projectile),
Drop(Drop),
}
#[derive(Debug)]
struct Entry {
kind: Kind,
state: Option<State>,
no_gravity: bool,
no_physics: bool,
in_ground: Option<bool>,
dangerous: Option<bool>,
fuse: Option<i32>,
power: Option<f64>,
pre: Option<([f64; 3], [f32; 2])>,
hook: Option<i32>,
biting: Option<bool>,
}
impl Entry {
fn new(kind: Kind) -> Entry {
Entry {
kind,
state: None,
no_gravity: false,
no_physics: false,
in_ground: None,
dangerous: None,
fuse: None,
power: None,
pre: None,
hook: None,
biting: None,
}
}
fn projectile(&mut self) -> Option<&mut Projectile> {
match &mut self.state {
Some(State::Projectile(p)) => Some(p),
_ => None,
}
}
}
const PREDICTED: bool = <Rules as modern::Rules>::SIMULATED_ON_CLIENT;
type Update = (i32, [f64; 3], [f64; 3], [f32; 2], bool);
#[derive(Debug, Default)]
pub(super) struct NonLiving {
map: HashMap<i32, Entry, BuildHasherDefault<IdHasher>>,
updates: Vec<Update>,
moves: Vec<(i32, [f64; 3])>,
discards: Vec<i32>,
}
impl NonLiving {
pub(super) fn clear(&mut self) {
self.map.clear();
}
}
impl ModernSim {
pub(super) fn set_nonliving(&mut self, on: bool) {
if on == self.nonliving.is_some() {
return;
}
self.nonliving = on.then(Box::default);
self.filter_dirty = true;
}
pub(super) fn nonliving_packet_ids(&self) -> &'static [i32] {
use super::proto::play::clientbound as cb;
if self.nonliving.is_some() && self.entities.is_some() {
&[cb::id::SET_PROJECTILE_POWER]
} else {
&[]
}
}
#[cold]
#[inline(never)]
pub(super) fn nonliving_packet(&mut self, raw: &RawPacket) -> Result<(), SimError> {
use super::proto::play::clientbound as cb;
use super::proto::types::EntityMetadataEntryValue as V;
let (Some(n), Some(t)) = (&mut self.nonliving, &self.entities) else {
return Ok(());
};
let mut r = ghast_protocol::Reader::new(&raw.body);
match raw.id {
cb::id::LOGIN | cb::id::RESPAWN => n.clear(),
cb::id::SPAWN_ENTITY => {
let id = r.read_varint()?;
r.skip(16)?; let ty = r.read_varint()?;
let kind = u16::try_from(ty)
.ok()
.and_then(super::data::entity_type)
.and_then(|t| Kind::of(t.name));
match kind {
Some(k) if t.get(id).is_some() => {
n.map.insert(id, Entry::new(k));
}
_ => {
n.map.remove(&id);
}
}
}
cb::id::ENTITY_METADATA => {
let id = r.read_varint()?;
let Some(en) = n.map.get_mut(&id) else {
return Ok(());
};
let p: cb::EntityMetadata = raw.decode_as()?;
let mut bitten = None;
for m in &p.metadata {
match (&m.value, m.key, en.kind) {
(V::Boolean(b), data_index::NO_GRAVITY, _) => en.no_gravity = *b,
(V::Byte(f), data_index::FIRST, k) if k.arrow() => {
en.no_physics = *f as u8 & 0x02 != 0;
}
(V::Boolean(b), data_index::ARROW_IN_GROUND, k) if k.arrow() => {
match en.projectile() {
Some(p) => p.set_in_ground(*b),
None => en.in_ground = Some(*b),
}
}
(
V::Boolean(b),
data_index::FIRST,
Kind::Projectile(ProjectileKind::WitherSkull),
) => match en.projectile() {
Some(p) => p.set_dangerous(*b),
None => en.dangerous = Some(*b),
},
(V::Int(f), data_index::FIRST, Kind::Drop(DropKind::PrimedTnt)) => {
match &mut en.state {
Some(State::Drop(d)) => d.set_fuse(*f),
_ => en.fuse = Some(*f),
}
}
(
V::Int(h),
data_index::FIRST,
Kind::Projectile(ProjectileKind::FishingBobber),
) => {
en.hook = (*h > 0).then(|| *h - 1).filter(|&i| t.get(i).is_some());
if en.hook.is_none()
&& let Some(p) = en.projectile()
{
p.set_hooked(None);
}
}
(
V::Boolean(b),
data_index::BITING,
Kind::Projectile(ProjectileKind::FishingBobber),
) => match en.projectile() {
Some(p) => {
p.set_biting(*b);
let (pos, vel, rot, g) =
(p.pos(), p.vel(), [p.yaw(), p.pitch()], p.on_ground());
bitten = Some((id, pos, vel, rot, g));
}
None => en.biting = Some(*b),
},
_ => {}
}
}
if let Some((id, pos, vel, rot, g)) = bitten
&& let Some(t) = &mut self.entities
{
t.client_simulated(id, pos, vel, rot, g);
}
}
cb::id::ENTITY_VELOCITY => {
let id = r.read_varint()?;
let Some(en) = n.map.get_mut(&id).filter(|en| en.kind.arrow()) else {
return Ok(());
};
let moving = t.get(id).is_some_and(|e| {
let v = e.velocity();
v[0] * v[0] + v[1] * v[1] + v[2] * v[2] > 0.0
});
if moving {
match en.projectile() {
Some(p) => {
if p.in_ground() {
p.set_in_ground(false);
}
}
None => {
if en.in_ground == Some(true) {
en.in_ground = Some(false);
}
}
}
}
}
cb::id::SET_PROJECTILE_POWER => {
let p: cb::SetProjectilePower = raw.decode_as()?;
if let Some(en) = n.map.get_mut(&p.id) {
match en.projectile() {
Some(s) => s.set_acceleration_power(p.acceleration_power),
None => en.power = Some(p.acceleration_power),
}
}
}
_ => {}
}
Ok(())
}
#[cold]
#[inline(never)]
pub(super) fn nonliving_before_tick(&mut self) {
let (Some(n), Some(t)) = (&mut self.nonliving, &self.entities) else {
return;
};
for (&id, en) in &mut n.map {
en.pre = t
.get(id)
.filter(|e| super::entity::interpolation_target(e).is_some())
.map(|e| (e.position(), [e.yaw(), e.pitch()]));
}
}
#[cold]
#[inline(never)]
pub(super) fn tick_nonliving(&mut self) {
let game_time = self.game_time();
let (Some(n), Some(t)) = (&mut self.nonliving, &mut self.entities) else {
return;
};
if n.map.is_empty() {
return;
}
let world = &self.world;
let me = self.own.id;
let NonLiving {
map,
updates,
moves,
discards,
} = &mut **n;
updates.clear();
moves.clear();
discards.clear();
map.retain(|&id, en| {
let Some(e) = t.get(id) else {
return false;
};
if !t.is_ticking(e) || en.no_gravity || en.no_physics || e.vehicle().is_some() {
return true;
}
let st = en.state.get_or_insert_with(|| build(en.kind, e));
match st {
State::Projectile(p) => {
if let Some(g) = en.in_ground.take() {
p.set_in_ground(g);
}
if let Some(d) = en.dangerous.take() {
p.set_dangerous(d);
}
if let Some(a) = en.power.take() {
p.set_acceleration_power(a);
}
let bobber = p.kind() == ProjectileKind::FishingBobber;
if bobber {
let owner = e.data();
let pos = if owner == me {
Some([0.0; 3])
} else {
t.get(owner)
.filter(|o| o.is_player())
.map(ghast_entity::Entity::position)
};
p.set_owner_pos(pos);
}
take_packets_p(p, e);
if bobber {
if let Some(b) = en.biting.take() {
p.set_biting(b);
}
p.set_game_time(game_time);
p.set_hooked(en.hook.map(|h| {
t.get(h)
.and_then(|he| {
he.size().map(|(_, height)| {
HookedEntity::new(he.drawn_position(), height)
})
})
.unwrap_or(HookedEntity::removed())
}));
}
if let Some((pos, r)) = en.pre.take() {
p.set_interpolation_start(pos, r[0], r[1]);
}
projectile::tick_projectile::<Rules, _>(p, Side::Client, world);
if bobber && p.hooked().is_none() {
en.hook = None;
}
if p.removed() {
discards.push(id);
return false;
}
updates.push((id, p.pos(), p.vel(), [p.yaw(), p.pitch()], p.on_ground()));
if PREDICTED {
moves.extend(p.moved_last_tick().iter().map(|&m| (id, m)));
}
}
State::Drop(d) => {
if d.kind() == DropKind::FallingBlock && e.data() == 0 {
discards.push(id);
return false;
}
if let Some(f) = en.fuse.take() {
d.set_fuse(f);
}
take_packets_d(d, e);
if let Some((pos, r)) = en.pre.take() {
d.set_interpolation_start(pos, r[0], r[1]);
}
drop::tick_drop::<Rules, _>(d, Side::Client, world);
if d.removed() {
discards.push(id);
return false;
}
updates.push((id, d.pos(), d.vel(), [e.yaw(), e.pitch()], d.on_ground()));
if PREDICTED {
moves.extend(d.moved_last_tick().iter().map(|&m| (id, m)));
}
}
}
true
});
for &(id, pos, vel, rot, g) in updates.iter() {
t.client_simulated(id, pos, vel, rot, g);
}
let level = &self.player.level;
for &(id, m) in moves.iter() {
t.client_predicted_move(id, m, |e, bb| block_free(world, level, e, bb));
}
for &id in discards.iter() {
t.client_discarded(id);
}
}
}
fn build(kind: Kind, e: &ghast_entity::Entity) -> State {
let (pos, vel) = (e.position(), e.velocity());
let seed = i64::from(e.id());
match kind {
Kind::Projectile(k) => {
let p = Projectile::new(k, pos, vel)
.with_rotation(e.yaw(), e.pitch())
.with_on_ground(e.on_ground())
.with_random_seed(seed);
State::Projectile(if k == ProjectileKind::FishingBobber {
p.with_uuid_lsb(e.uuid().as_u64_pair().1 as i64)
} else {
p
})
}
Kind::Drop(k) => State::Drop(
Drop::new(k, pos, vel)
.with_id(e.id())
.with_on_ground(e.on_ground())
.with_random_seed(seed),
),
}
}
fn same(a: [f64; 3], b: [f64; 3]) -> bool {
(0..3).all(|i| a[i].to_bits() == b[i].to_bits())
}
fn take_packets_p(p: &mut Projectile, e: &ghast_entity::Entity) {
if !same(p.pos(), e.position()) {
p.set_pos(e.position());
}
if !same(p.vel(), e.velocity()) {
p.set_vel(e.velocity());
}
if p.yaw().to_bits() != e.yaw().to_bits() || p.pitch().to_bits() != e.pitch().to_bits() {
p.set_rotation(e.yaw(), e.pitch());
}
if p.on_ground() != e.on_ground() {
p.set_on_ground(e.on_ground());
}
}
fn take_packets_d(d: &mut Drop, e: &ghast_entity::Entity) {
if !same(d.pos(), e.position()) {
d.set_pos(e.position());
}
if !same(d.vel(), e.velocity()) {
d.set_vel(e.velocity());
}
if d.on_ground() != e.on_ground() {
d.set_on_ground(e.on_ground());
}
}