use crate::common::{Face, Vec3};
use crate::sim::WorldView;
use crate::version::GameVersion;
use ghast_protocol::BlockPos;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Throw {
Snowball,
Egg,
EnderPearl,
SplashPotion,
LingeringPotion,
ExperienceBottle,
WindCharge,
Trident,
Bow {
ticks_held: i32,
},
CrossbowArrow,
}
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub struct ThrowHit {
pub block: BlockPos,
pub face: Face,
pub point: Vec3,
pub tick: u32,
}
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct ThrowPrediction {
pub path: Vec<Vec3>,
pub velocity: Vec3,
pub hit: Option<ThrowHit>,
pub max_spread: f64,
}
#[derive(Clone, Copy, Debug)]
pub(crate) struct Shooter {
pub pos: Vec3,
pub eye_height: f64,
pub yaw: f32,
pub pitch: f32,
#[cfg_attr(
not(any(
feature = "v1_12_2",
feature = "v1_16_5",
feature = "v26_1",
feature = "v26_2",
feature = "v26_3"
)),
allow(dead_code)
)]
pub motion: Vec3,
#[cfg_attr(
not(any(
feature = "v1_12_2",
feature = "v1_16_5",
feature = "v26_1",
feature = "v26_2",
feature = "v26_3"
)),
allow(dead_code)
)]
pub on_ground: bool,
}
struct Raw<'a, S> {
world: &'a dyn WorldView,
decode: fn(Option<u32>) -> S,
}
impl<S: Copy> ghast_physics::BlockView for Raw<'_, S> {
type State = S;
fn block(&self, x: i32, y: i32, z: i32) -> S {
(self.decode)(self.world.raw_block(x, y, z))
}
fn is_chunk_loaded(&self, chunk_x: i32, chunk_z: i32) -> bool {
self.world.is_column_loaded(chunk_x, chunk_z)
}
}
fn face(d: ghast_physics::pick::Direction) -> Face {
use ghast_physics::pick::Direction;
match d {
Direction::Down => Face::Down,
Direction::Up => Face::Up,
Direction::North => Face::North,
Direction::South => Face::South,
Direction::West => Face::West,
Direction::East => Face::East,
}
}
fn v3(a: [f64; 3]) -> Vec3 {
Vec3::new(a[0], a[1], a[2])
}
fn fly(
start: [f64; 3],
vel: [f64; 3],
max_spread: f64,
max_ticks: u32,
mut tick: impl FnMut() -> Option<(Option<([i32; 3], Face, [f64; 3])>, [f64; 3])>,
) -> ThrowPrediction {
let mut path = vec![v3(start)];
let mut hit = None;
for t in 1..=max_ticks {
let Some((h, pos)) = tick() else { break };
path.push(v3(pos));
if let Some((b, face, p)) = h {
hit = Some(ThrowHit {
block: BlockPos::new(b[0], b[1], b[2]),
face,
point: v3(p),
tick: t,
});
break;
}
}
ThrowPrediction {
path,
velocity: v3(vel),
hit,
max_spread,
}
}
pub(crate) fn predict(
world: &dyn WorldView,
version: GameVersion,
throw: Throw,
shooter: &Shooter,
max_ticks: u32,
) -> Option<ThrowPrediction> {
match version.instance() {
#[cfg(feature = "v1_8")]
GameVersion::V1_8_9 => v1_8(world, throw, shooter, max_ticks),
#[cfg(feature = "v1_12_2")]
GameVersion::V1_12_2 => v1_12(world, throw, shooter, max_ticks),
#[cfg(feature = "v1_16_5")]
GameVersion::V1_16_5 => v1_16_5(world, throw, shooter, max_ticks),
#[cfg(feature = "v26_1")]
GameVersion::V26_1 => {
modern::<ghast_physics::modern::V26_1>(world, throw, shooter, max_ticks, |r| {
r.and_then(|id| ghast_data::v26_1::BlockState::from_id(id as u16))
.unwrap_or(ghast_data::v26_1::Block::VOID_AIR.default_state())
})
}
#[cfg(feature = "v26_2")]
GameVersion::V26_2 => {
modern::<ghast_physics::modern::V26_2>(world, throw, shooter, max_ticks, |r| {
r.and_then(|id| ghast_data::v26_2::BlockState::from_id(id as u16))
.unwrap_or(ghast_data::v26_2::Block::VOID_AIR.default_state())
})
}
#[cfg(feature = "v26_3")]
GameVersion::V26_3 => {
modern::<ghast_physics::modern::V26_3>(world, throw, shooter, max_ticks, |r| {
r.and_then(|id| ghast_data::v26_3::BlockState::from_id(id as u16))
.unwrap_or(ghast_data::v26_3::Block::VOID_AIR.default_state())
})
}
_ => {
let _ = (world, throw, shooter, max_ticks);
None
}
}
}
#[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
fn modern<R: ghast_physics::modern::Rules>(
world: &dyn WorldView,
throw: Throw,
s: &Shooter,
max_ticks: u32,
decode: fn(Option<u32>) -> R::State,
) -> Option<ThrowPrediction> {
use ghast_physics::modern::launch::{self, LaunchSpec, Noise};
use ghast_physics::modern::projectile::{self as p, Projectile, ProjectileKind as K};
let (kind, spec) = match throw {
Throw::Snowball => (K::Snowball, LaunchSpec::THROWN),
Throw::Egg => (K::Egg, LaunchSpec::THROWN),
Throw::EnderPearl => (K::EnderPearl, LaunchSpec::THROWN),
Throw::SplashPotion => (K::SplashPotion, LaunchSpec::POTION),
Throw::LingeringPotion => (K::LingeringPotion, LaunchSpec::POTION),
Throw::ExperienceBottle => (K::ExperienceBottle, LaunchSpec::EXPERIENCE_BOTTLE),
Throw::WindCharge => (K::WindCharge, LaunchSpec::WIND_CHARGE),
Throw::Trident => (K::Trident, LaunchSpec::TRIDENT),
Throw::Bow { ticks_held } => (K::Arrow, LaunchSpec::bow(ticks_held)?),
Throw::CrossbowArrow => (K::Arrow, LaunchSpec::CROSSBOW_ARROW),
};
let eye_y = s.pos.y + s.eye_height;
let y = if kind == K::WindCharge {
eye_y
} else {
eye_y - f64::from(0.1f32)
};
let start = [s.pos.x, y, s.pos.z];
let l = launch::shoot(
s.yaw,
s.pitch,
&spec,
Noise::NONE,
[s.motion.x, s.motion.y, s.motion.z],
s.on_ground,
);
let w = Raw { world, decode };
let mut pr = Projectile::new(kind, start, l.vel).with_rotation(l.yaw, l.pitch);
Some(fly(
start,
l.vel,
launch::max_spread(&spec),
max_ticks,
|| {
if pr.removed() {
return None;
}
let h = p::tick_projectile::<R, _>(&mut pr, p::Side::Server, &w);
Some((h.map(|h| (h.pos, face(h.face), h.location)), pr.pos()))
},
))
}
#[cfg(feature = "v1_16_5")]
fn v1_16_5(
world: &dyn WorldView,
throw: Throw,
s: &Shooter,
max_ticks: u32,
) -> Option<ThrowPrediction> {
use ghast_data::v1_16_5::BlockState;
use ghast_physics::v1_16_5::launch::{self, LaunchSpec, Noise};
use ghast_physics::v1_16_5::projectile::{self as p, Projectile, ProjectileKind as K};
let (kind, spec) = match throw {
Throw::Snowball => (K::Snowball, LaunchSpec::THROWN),
Throw::Egg => (K::Egg, LaunchSpec::THROWN),
Throw::EnderPearl => (K::EnderPearl, LaunchSpec::THROWN),
Throw::SplashPotion => (K::SplashPotion, LaunchSpec::POTION),
Throw::LingeringPotion => (K::LingeringPotion, LaunchSpec::POTION),
Throw::ExperienceBottle => (K::ExperienceBottle, LaunchSpec::EXPERIENCE_BOTTLE),
Throw::Trident => (K::Trident, LaunchSpec::TRIDENT),
Throw::Bow { ticks_held } => (K::Arrow, LaunchSpec::bow(ticks_held)?),
Throw::WindCharge | Throw::CrossbowArrow => return None,
};
let start = [s.pos.x, launch::launch_y(s.pos.y + s.eye_height), s.pos.z];
let l = launch::shoot(
s.yaw,
s.pitch,
&spec,
Noise::NONE,
[s.motion.x, s.motion.y, s.motion.z],
s.on_ground,
);
let w = Raw {
world,
decode: |r| {
r.and_then(|id| BlockState::from_id(id as u16))
.unwrap_or(BlockState::AIR)
},
};
let mut pr = Projectile::new(kind, start, l.vel).with_rotation(l.yaw, l.pitch);
let spread = f64::from(spec.power) * launch::SPREAD * f64::from(spec.uncertainty);
Some(fly(start, l.vel, spread, max_ticks, || {
if pr.removed() {
return None;
}
let h = p::tick_projectile(&mut pr, p::Side::Server, &w);
Some((h.map(|h| (h.pos, face(h.face), h.location)), pr.pos()))
}))
}
#[cfg(feature = "v1_12_2")]
fn v1_12(
world: &dyn WorldView,
throw: Throw,
s: &Shooter,
max_ticks: u32,
) -> Option<ThrowPrediction> {
use ghast_data::v1_12::BlockState;
use ghast_physics::v1_12::launch::{self, LaunchSpec, Noise};
use ghast_physics::v1_12::projectile::{self as p, Projectile, ProjectileKind as K};
let (kind, spec) = match throw {
Throw::Snowball => (K::Snowball, LaunchSpec::THROWN),
Throw::Egg => (K::Egg, LaunchSpec::THROWN),
Throw::EnderPearl => (K::EnderPearl, LaunchSpec::THROWN),
Throw::SplashPotion => (K::SplashPotion, LaunchSpec::POTION),
Throw::LingeringPotion => (K::LingeringPotion, LaunchSpec::POTION),
Throw::ExperienceBottle => (K::ExperienceBottle, LaunchSpec::EXPERIENCE_BOTTLE),
Throw::Bow { ticks_held } => (K::Arrow, LaunchSpec::bow(ticks_held)?),
Throw::WindCharge | Throw::Trident | Throw::CrossbowArrow => return None,
};
let start = [s.pos.x, launch::launch_y(s.pos.y + s.eye_height), s.pos.z];
let motion = [s.motion.x, s.motion.y, s.motion.z];
let l = if kind == K::Arrow {
launch::shoot_arrow(s.yaw, s.pitch, &spec, Noise::NONE, motion, s.on_ground)
} else {
launch::shoot(s.yaw, s.pitch, &spec, Noise::NONE, motion, s.on_ground)
};
let w = Raw {
world,
decode: |r| {
r.and_then(|id| BlockState::from_raw(id as u16))
.unwrap_or(BlockState::AIR)
},
};
let mut pr = Projectile::new(kind, start, l.vel).with_rotation(l.yaw, l.pitch);
let spread = f64::from(spec.power) * launch::SPREAD * f64::from(spec.uncertainty);
Some(fly(start, l.vel, spread, max_ticks, || {
if pr.removed() {
return None;
}
let h = p::tick_projectile(&mut pr, p::Side::Server, &w);
Some((h.map(|h| (h.pos, face(h.face), h.location)), pr.pos()))
}))
}
#[cfg(feature = "v1_8")]
fn v1_8(
world: &dyn WorldView,
throw: Throw,
s: &Shooter,
max_ticks: u32,
) -> Option<ThrowPrediction> {
use ghast_data::v1_8::BlockState;
use ghast_physics::v1_8::launch::{self, LaunchSpec, Noise, Shooter as From};
use ghast_physics::v1_8::projectile::{self as p, Projectile, ProjectileKind as K};
let (kind, spec, from) = match throw {
Throw::Snowball => (K::Snowball, LaunchSpec::THROWN, From::Thrown),
Throw::Egg => (K::Egg, LaunchSpec::THROWN, From::Thrown),
Throw::EnderPearl => (K::EnderPearl, LaunchSpec::THROWN, From::Thrown),
Throw::SplashPotion => (K::SplashPotion, LaunchSpec::POTION, From::Thrown),
Throw::ExperienceBottle => (
K::ExperienceBottle,
LaunchSpec::EXPERIENCE_BOTTLE,
From::Thrown,
),
Throw::Bow { ticks_held } => (K::Arrow, LaunchSpec::bow(ticks_held)?, From::Arrow),
_ => return None,
};
let l = launch::shoot(
from,
s.yaw,
s.pitch,
[s.pos.x, s.pos.y, s.pos.z],
s.eye_height as f32,
&spec,
Noise::NONE,
);
let w = Raw {
world,
decode: |r| {
r.and_then(|id| BlockState::from_raw(id as u16))
.unwrap_or(BlockState::AIR)
},
};
let mut pr = Projectile::new(kind, l.pos, l.vel).with_rotation(l.yaw, l.pitch);
let spread = f64::from(spec.power) * launch::SPREAD * f64::from(spec.uncertainty);
Some(fly(l.pos, l.vel, spread, max_ticks, || {
if pr.removed() {
return None;
}
let h = p::tick_projectile(&mut pr, p::Side::Server, &w);
Some((h.map(|h| (h.pos, face(h.face), h.location)), pr.pos()))
}))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::sim::Sim;
fn shooter(yaw: f32, pitch: f32) -> Shooter {
Shooter {
pos: Vec3::new(8.5, 64.0, 8.5),
eye_height: f64::from(1.62f32),
yaw,
pitch,
motion: Vec3::new(0.0, 0.0, 0.0),
on_ground: true,
}
}
fn check(
mut sim: impl Sim,
version: GameVersion,
chunk: Option<fn(i32, i32) -> ghast_protocol::RawPacket>,
) {
for x in -1..=1 {
for z in -1..=5 {
if let Some(chunk) = chunk {
sim.world_packet(&chunk(x, z)).unwrap();
}
}
}
let w: &dyn WorldView = ∼
let s = predict(w, version, Throw::Snowball, &shooter(0.0, 0.0), 100).unwrap();
let hit = s
.hit
.unwrap_or_else(|| panic!("{version:?} {:?} {:?}", s.path, w.raw_block(8, 63, 12)));
assert_eq!(
(hit.block.y, hit.face),
(63, Face::Up),
"{version:?} {hit:?}"
);
assert!(
hit.block.z > 9 && (hit.point.x - 8.5).abs() < 0.3,
"{version:?} {hit:?}"
);
assert_eq!(s.path.len(), hit.tick as usize + 1);
assert!(
s.path[0].y > 65.0 && s.path[0].y < 65.6,
"{version:?} {:?}",
s.path[0]
);
assert!(s.max_spread > 0.0);
let a = predict(
w,
version,
Throw::Bow { ticks_held: 20 },
&shooter(0.0, 0.0),
100,
)
.unwrap()
.hit
.unwrap();
assert!(a.block.z > hit.block.z, "{version:?} {a:?} {hit:?}");
let up = predict(w, version, Throw::EnderPearl, &shooter(0.0, -90.0), 200).unwrap();
let top = up.path.iter().map(|p| p.y).fold(f64::MIN, f64::max);
assert!(top > 70.0, "{version:?} {top}");
assert_eq!(up.hit.unwrap().block.y, 63);
assert_eq!(
predict(
w,
version,
Throw::Bow { ticks_held: 1 },
&shooter(0.0, 0.0),
10
),
None
);
}
#[cfg(feature = "v1_8")]
#[test]
fn throws_on_1_8() {
check(
crate::sim::Sim18::new(),
GameVersion::V1_8_9,
Some(crate::sim::test_chunks::v1_8),
);
let w = crate::sim::Sim18::new();
assert_eq!(
predict(
&w,
GameVersion::V1_8_9,
Throw::Trident,
&shooter(0.0, 0.0),
5
),
None
);
}
#[cfg(feature = "v1_12_2")]
#[test]
fn throws_on_1_12() {
check(
crate::sim::Sim12::new(),
GameVersion::V1_12_2,
Some(crate::sim::test_chunks::v1_12_2),
);
}
#[cfg(feature = "v1_16_5")]
#[test]
fn throws_on_1_16_5() {
let mut sim = crate::sim::Sim16::new();
for x in -1..=1 {
for z in -1..=5 {
sim.world_packet(&crate::sim::test_chunks::v1_16_5(x, z))
.unwrap();
}
}
for x in 0..16 {
for z in -16..96 {
let p = ghast_protocol::v1_16_5::play::clientbound::BlockChange {
location: BlockPos::new(x, 63, z),
r#type: 1, };
sim.world_packet(&ghast_protocol::RawPacket::from_packet(&p).unwrap())
.unwrap();
}
}
check(sim, GameVersion::V1_16_5, None);
}
#[cfg(feature = "v26_1")]
#[test]
fn throws_on_26_1() {
check(
crate::sim::Sim26::test_overworld(),
GameVersion::V26_1,
Some(crate::sim::test_chunks::v26_1),
);
}
#[cfg(feature = "v26_2")]
#[test]
fn throws_on_26_2() {
check(
crate::sim::Sim262::test_overworld(),
GameVersion::V26_2,
Some(crate::sim::test_chunks::v26_2),
);
}
#[cfg(feature = "v26_3")]
#[test]
fn throws_on_26_3() {
check(
crate::sim::Sim263::test_overworld(),
GameVersion::V26_3,
Some(crate::sim::test_chunks::v26_3),
);
let mut sim = crate::sim::Sim263::test_overworld();
sim.world_packet(&crate::sim::test_chunks::v26_3(0, 0))
.unwrap();
let s = predict(
&sim,
GameVersion::V26_3,
Throw::Trident,
&shooter(10.0, -5.0),
60,
)
.unwrap();
use ghast_physics::modern::launch::{self, LaunchSpec, Noise};
let l = launch::shoot(
10.0,
-5.0,
&LaunchSpec::TRIDENT,
Noise::NONE,
[0.0; 3],
true,
);
assert_eq!(s.velocity, v3(l.vel));
}
}