use std::collections::HashMap;
use super::*;
use crate::sim::shared::PlayerFacts;
use ghast_entity::EntityType;
use ghast_physics::v1_12::Side;
use ghast_physics::v1_12::drop::{self, Drop, DropKind, OrbPlayer};
use ghast_physics::v1_12::projectile::{self, HookedEntity, Projectile, ProjectileKind};
#[derive(Debug)]
enum State {
Projectile(Projectile),
Drop(Drop),
}
#[derive(Debug)]
struct Entry {
state: State,
hook: Option<i32>,
seq: u64,
}
type Update = (i32, [f64; 3], [f64; 3], [f32; 2], bool);
#[derive(Debug, Default)]
pub(super) struct NonLiving12 {
map: HashMap<i32, Entry>,
updates: Vec<Update>,
discards: Vec<i32>,
seq: u64,
flags: HashMap<i32, (u8, u64, f32)>,
idents: crate::sim::shared::PlayerIdents,
pre: Vec<(i32, [f64; 3])>,
players: Vec<(OrbPlayer, OrbPlayer, u64)>,
seen: Vec<OrbPlayer>,
}
impl NonLiving12 {
pub(super) fn clear(&mut self) {
self.map.clear();
self.flags.clear();
self.idents.clear();
}
fn has_orbs(&self) -> bool {
self.map
.values()
.any(|en| matches!(&en.state, State::Drop(d) if d.kind() == DropKind::ExperienceOrb))
}
}
pub(super) fn eye_height(asleep: bool, sneaking: bool, gliding: bool, height: f32) -> f32 {
if asleep {
0.2
} else if sneaking || height == 1.65 {
1.62 - 0.08
} else if gliding || height == 0.6 {
0.4
} else {
1.62
}
}
fn size_height(flags: u8) -> f32 {
if flags & 0x80 != 0 {
0.6
} else if flags & 0x02 != 0 {
1.65
} else {
1.8
}
}
fn resize<W: ghast_physics::BlockView<State = ghast_physics::v1_12::BlockState>>(
world: &W,
pos: [f64; 3],
height: f32,
flags: u8,
) -> f32 {
let h = size_height(flags);
if h == height {
return h;
}
let half = f64::from(0.6f32 / 2.0);
let (x, z) = (pos[0] - half, pos[2] - half);
let w = f64::from(0.6f32);
let b = ghast_physics::math::Aabb::new(x, pos[1], z, x + w, pos[1] + f64::from(h), z + w);
if ghast_physics::v1_12::collides_with_any_block(world, &b) {
height
} else {
h
}
}
mod data_index {
pub(super) const NO_GRAVITY: u8 = 5;
pub(super) const FIRST: u8 = 6;
pub(super) const ARROW_COLOR: u8 = 7;
}
fn kind_of(t: EntityType) -> Option<State> {
let pos = [0.0; 3];
Some(match t {
EntityType::ExperienceOrb => State::Drop(Drop::new(DropKind::ExperienceOrb, pos, pos)),
EntityType::LegacyObject(o) => {
let p = |k| Some(State::Projectile(Projectile::new(k, pos, pos)));
let d = |k| Some(State::Drop(Drop::new(k, pos, pos)));
return match o {
2 => d(DropKind::Item),
50 => d(DropKind::PrimedTnt),
70 => d(DropKind::FallingBlock),
60 => p(ProjectileKind::Arrow),
91 => p(ProjectileKind::SpectralArrow),
61 => p(ProjectileKind::Snowball),
62 => p(ProjectileKind::Egg),
65 => p(ProjectileKind::EnderPearl),
73 => p(ProjectileKind::SplashPotion),
75 => p(ProjectileKind::ExperienceBottle),
63 => p(ProjectileKind::LargeFireball),
64 => p(ProjectileKind::SmallFireball),
66 => p(ProjectileKind::WitherSkull),
93 => p(ProjectileKind::DragonFireball),
90 => p(ProjectileKind::FishingBobber),
_ => None,
};
}
_ => return None,
})
}
fn data_reset(t: u8) -> bool {
matches!(t, 63 | 64 | 66 | 67 | 70 | 71 | 73 | 75 | 77 | 90 | 93)
}
impl Sim12 {
pub(super) fn set_nonliving(&mut self, on: bool) {
if on == self.nonliving.is_some() {
return;
}
self.nonliving = on.then(Box::default);
self.glide.filter_dirty = true;
}
#[cold]
#[inline(never)]
pub(super) fn nonliving_packet(&mut self, raw: &RawPacket) -> Result<(), SimError> {
use ghast_protocol::defs::p340::types::EntityMetadataValue as V;
use ghast_protocol::v1_12_2::play::clientbound as cb;
let (Some(n), Some(t)) = (&mut self.nonliving, &mut self.entities) else {
return Ok(());
};
let mut r = ghast_protocol::Reader::new(&raw.body);
let id = match raw.id {
cb::id::LOGIN => {
n.clear();
return Ok(());
}
cb::id::NAMED_ENTITY_SPAWN => {
let p: cb::NamedEntitySpawn = raw.decode_as()?;
let id = p.entity_id;
if !t.get(id).is_some_and(ghast_entity::Entity::is_player) {
return Ok(());
}
let flags = p
.metadata
.iter()
.find_map(|m| match (m.key, &m.value) {
(0, V::Byte(b)) => Some(*b as u8),
_ => None,
})
.unwrap_or(0);
n.seq += 1;
n.flags.insert(id, (flags, n.seq, 1.8));
n.idents.spawned(id);
return Ok(());
}
cb::id::SPAWN_ENTITY | cb::id::SPAWN_ENTITY_EXPERIENCE_ORB => {
let id = r.read_varint()?;
n.map.remove(&id);
n.flags.remove(&id);
let packet_vel = if raw.id == cb::id::SPAWN_ENTITY {
r.skip(16 + 1 + 24 + 2 + 4)?;
[r.read_i16()?, r.read_i16()?, r.read_i16()?].map(|c| f64::from(c) / 8000.0)
} else {
[0.0; 3]
};
let Some(e) = t.get(id) else {
return Ok(());
};
let Some(state) = spawned(e, packet_vel) else {
return Ok(());
};
n.seq += 1;
let seq = n.seq;
n.map.insert(
id,
Entry {
state,
hook: None,
seq,
},
);
id
}
cb::id::ENTITY_VELOCITY => {
let id = r.read_varint()?;
let (Some(en), Some(e)) = (n.map.get_mut(&id), t.get(id)) else {
return Ok(());
};
match &mut en.state {
State::Projectile(p) => p.set_velocity_client(e.velocity()),
State::Drop(d) => d.set_vel(e.velocity()),
}
id
}
cb::id::REL_ENTITY_MOVE
| cb::id::ENTITY_MOVE_LOOK
| cb::id::ENTITY_LOOK
| cb::id::ENTITY
| cb::id::ENTITY_TELEPORT => {
let id = r.read_varint()?;
let (Some(en), Some(e)) = (n.map.get_mut(&id), t.get(id)) else {
return Ok(());
};
let target = e.position();
let to = |at: [f64; 3]| {
if raw.id == cb::id::ENTITY_TELEPORT
&& (at[0] - target[0]).abs() < 0.03125
&& (at[1] - target[1]).abs() < 0.015625
&& (at[2] - target[2]).abs() < 0.03125
{
at
} else {
target
}
};
match &mut en.state {
State::Projectile(p) if p.kind() == ProjectileKind::FishingBobber => {}
State::Projectile(p) => {
p.set_pos(to(p.pos()));
p.set_rotation(e.yaw() % 360.0, e.pitch() % 360.0);
}
State::Drop(d) => d.set_pos(to(d.pos())),
}
match &mut en.state {
State::Projectile(p) => p.set_on_ground(e.on_ground()),
State::Drop(d) => d.set_on_ground(e.on_ground()),
}
id
}
cb::id::ENTITY_METADATA => {
let id = r.read_varint()?;
if let Some(e) = t.get(id).filter(|e| e.is_player()) {
let orbs = n.has_orbs();
let f = n.flags.entry(id).or_insert((0, 0, 1.8));
let m: cb::EntityMetadata = raw.decode_as()?;
for m in &m.metadata {
if let (0, V::Byte(b)) = (m.key, &m.value) {
f.0 = *b as u8;
}
}
if !orbs {
f.2 = resize(&self.world, e.drawn_position(), f.2, f.0);
}
let eye = eye_height(false, f.0 & 0x02 != 0, f.0 & 0x80 != 0, f.2);
n.idents.eye_changed(id, eye);
return Ok(());
}
let Some(en) = n.map.get_mut(&id) else {
return Ok(());
};
let p: cb::EntityMetadata = raw.decode_as()?;
for m in &p.metadata {
match (&mut en.state, m.key, &m.value) {
(State::Projectile(p), data_index::NO_GRAVITY, V::Boolean(b)) => {
p.set_no_gravity(*b);
}
(State::Drop(d), data_index::NO_GRAVITY, V::Boolean(b)) => {
d.set_no_gravity(*b);
}
(State::Projectile(p), data_index::ARROW_COLOR, V::VarInt(c))
if p.kind() == ProjectileKind::Arrow =>
{
p.set_tipped(*c != -1);
}
(State::Projectile(p), data_index::FIRST, V::Boolean(b))
if p.kind() == ProjectileKind::WitherSkull =>
{
p.set_dangerous(*b);
}
(State::Projectile(p), data_index::FIRST, V::VarInt(h))
if p.kind() == ProjectileKind::FishingBobber =>
{
en.hook = (*h > 0).then(|| *h - 1).filter(|&i| t.get(i).is_some());
if en.hook.is_none() {
p.set_hooked(None);
}
}
(State::Drop(d), data_index::FIRST, V::VarInt(f))
if d.kind() == DropKind::PrimedTnt =>
{
d.set_fuse(*f);
}
_ => {}
}
}
return Ok(());
}
_ => return Ok(()),
};
if let Some(en) = n.map.get(&id) {
let (pos, vel, rot, g) = copy_of(&en.state, t.get(id));
t.client_simulated(id, pos, vel, rot, g);
}
Ok(())
}
#[cold]
#[inline(never)]
pub(super) fn nonliving_before_tick(n: &mut NonLiving12, t: &ghast_entity::v1_12::Tracker) {
n.pre.clear();
if !n.has_orbs() {
return;
}
n.pre.extend(
t.iter()
.filter(|e| e.is_player())
.map(|e| (e.id(), e.drawn_position())),
);
}
fn orb_players(&mut self) {
let (Some(n), Some(t)) = (&mut self.nonliving, &self.entities) else {
return;
};
n.players.clear();
if !n.has_orbs() {
return;
}
let NonLiving12 {
map,
flags,
idents,
pre,
players,
..
} = &mut **n;
let p = &self.player;
let me = t.self_id().unwrap_or(self.glide.own_id);
let eye = eye_height(
self.ext.sleeping,
p.sneaking(),
self.ext.fall_flying,
p.height,
);
let own = OrbPlayer::new(me, p.pos, eye).with_spectator(p.spectator);
players.push((own, own, 0));
flags.retain(|&id, _| t.get(id).is_some_and(ghast_entity::Entity::is_player));
for e in t.iter().filter(|e| e.is_player() && e.id() != me) {
let id = e.id();
let f = flags.entry(id).or_insert((0, 0, 1.8));
let (bits, seq, height) = *f;
let (sneak, glide) = (bits & 0x02 != 0, bits & 0x80 != 0);
let now_pos = e.drawn_position();
f.2 = resize(&self.world, now_pos, height, bits);
let before_pos = pre.iter().find(|q| q.0 == id).map_or(now_pos, |q| q.1);
let ident = idents.of(id);
let uuid = e.uuid();
let spectator = t.tab_game_mode(&uuid) == Some(3);
let now_eye = eye_height(false, sneak, glide, f.2);
idents.seen(
ident,
PlayerFacts {
uuid,
#[cfg(ghast_modern)]
generation: 0,
spectator,
pos: now_pos,
eye_height: now_eye,
},
);
let now = OrbPlayer::new(ident, now_pos, now_eye).with_spectator(spectator);
let before = OrbPlayer::new(ident, before_pos, eye_height(false, sneak, glide, height))
.with_spectator(spectator);
players.push((now, before, seq));
}
players[1..].sort_by_key(|q| q.2);
for en in map.values() {
let State::Drop(d) = &en.state else { continue };
let Some(ident) = d.following() else { continue };
if players.iter().any(|q| q.0.id == ident) {
continue;
}
let Some(mut f) = idents.facts(ident) else {
continue;
};
f.spectator = t.tab_game_mode(&f.uuid) == Some(3);
idents.seen(ident, f);
let gone = OrbPlayer::new(ident, f.pos, f.eye_height)
.with_spectator(f.spectator)
.with_removed(true);
players.push((gone, gone, u64::MAX));
}
idents.retain(|k| players.iter().any(|q| q.0.id == k));
}
#[cold]
#[inline(never)]
pub(super) fn tick_nonliving(&mut self) {
if self.nonliving.as_ref().is_none_or(|n| n.map.is_empty()) {
return;
}
self.orb_players();
let (Some(n), Some(t)) = (&mut self.nonliving, &mut self.entities) else {
return;
};
let world = &self.world;
let me = self.glide.own_id;
let NonLiving12 {
map,
updates,
discards,
players,
seen,
..
} = &mut **n;
updates.clear();
discards.clear();
map.retain(|&id, en| {
let Some(e) = t.get(id) else {
return false;
};
if e.vehicle().is_some() {
return true;
}
match &mut en.state {
State::Projectile(p) => {
if p.kind() == ProjectileKind::FishingBobber {
let owner = e.data();
let pos = if owner == me || t.self_id() == Some(owner) {
Some([0.0; 3])
} else {
t.get(owner)
.filter(|o| o.is_player())
.map(ghast_entity::Entity::position)
};
p.set_owner_pos(pos);
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())
}));
}
projectile::tick_projectile(p, Side::Client, world);
if p.hooked().is_none() {
en.hook = None;
}
if p.removed() {
discards.push(id);
return false;
}
}
State::Drop(d) => {
seen.clear();
if d.kind() == DropKind::ExperienceOrb {
seen.extend(
players
.iter()
.map(|&(now, before, seq)| if seq > en.seq { before } else { now }),
);
}
drop::tick_drop_near(d, Side::Client, world, seen);
if d.removed() {
discards.push(id);
return false;
}
}
}
let (pos, vel, rot, g) = copy_of(&en.state, Some(e));
updates.push((id, pos, vel, rot, g));
true
});
for &(id, pos, vel, rot, g) in updates.iter() {
t.client_simulated(id, pos, vel, rot, g);
}
for &id in discards.iter() {
t.client_discarded(id);
}
}
}
fn copy_of(s: &State, e: Option<&ghast_entity::Entity>) -> ([f64; 3], [f64; 3], [f32; 2], bool) {
match s {
State::Projectile(p) => (p.pos(), p.vel(), [p.yaw(), p.pitch()], p.on_ground()),
State::Drop(d) => (
d.pos(),
d.vel(),
e.map_or([0.0; 2], |e| [e.yaw(), e.pitch()]),
d.on_ground(),
),
}
}
fn spawned(e: &ghast_entity::Entity, packet_vel: [f64; 3]) -> Option<State> {
let ty = e.entity_type();
let pos = e.position();
let seed = i64::from(e.id());
let applies = match ty {
EntityType::LegacyObject(o) => !data_reset(o) && e.data() > 0,
_ => false,
};
Some(match kind_of(ty)? {
State::Projectile(k) => {
let k = k.kind();
let mut p = Projectile::new(k, pos, packet_vel).with_random_seed(seed);
p.set_vel([0.0; 3]);
p.set_rotation(e.yaw(), e.pitch());
if applies {
p.set_velocity_client(packet_vel);
}
State::Projectile(p)
}
State::Drop(k) => {
let k = k.kind();
let mut d = Drop::new(k, pos, e.velocity())
.with_id(e.id())
.with_random_seed(seed);
if k == DropKind::FallingBlock {
let raw = e.data() & 0xFFFF;
let block = ghast_data::v1_12::BlockState::from_raw_vanilla(
(((raw & 4095) as u16) << 4) | ((raw >> 12) & 15) as u16,
);
d = Drop::new(
k,
[
pos[0],
pos[1] + f64::from((1.0f32 - 0.98f32) / 2.0f32),
pos[2],
],
[0.0; 3],
)
.with_id(e.id())
.with_random_seed(seed)
.with_block(block);
} else if applies {
d.set_vel(packet_vel);
}
State::Drop(d)
}
})
}