use ghast_physics::Keys;
use crate::Version;
use crate::class::{flag, table};
use crate::control::{Controller, ControllerConfig, Progress};
use crate::moves::MoveKind;
use crate::physics::{Observation, P16, P18, Physics, SourceView};
use crate::plan::Path;
use crate::world::BlockSource;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SimOutcome {
Arrived,
Stuck,
OffPath,
Hazard,
Timeout,
}
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct SimReport {
pub outcome: SimOutcome,
pub ticks: u32,
pub reached: usize,
pub end: [f64; 3],
pub collisions: u32,
pub first_collision: Option<u32>,
pub max_fall: f32,
pub trace: Vec<[f64; 3]>,
}
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct Turner {
yaw_budget: f64,
pitch_budget: f64,
}
impl Turner {
const MAX_YAW: f64 = 14.0;
const MAX_PITCH: f64 = 10.5;
const MULTIPLIER: f32 = 1.0;
fn counts(budget: &mut f64, delta: f32, per_tick_deg: f64) -> i64 {
let step = f64::from(Self::MULTIPLIER) * 0.15;
let per_tick = per_tick_deg / step;
*budget = (*budget + per_tick).min(per_tick + 1.0);
let wanted = (f64::from(delta) / step + 0.5).floor() as i64;
let lim = budget.trunc() as i64;
let count = wanted.clamp(-lim, lim);
*budget -= count.unsigned_abs() as f64;
if count == wanted {
*budget = 0.0;
}
count
}
pub(crate) fn step(&mut self, yaw: f32, pitch: f32, target: (f32, f32)) -> (f32, f32) {
let m = Self::MULTIPLIER;
let ty = target.0;
let tp = target.1.clamp(-89.5, 89.5);
let dx = Self::counts(
&mut self.yaw_budget,
crate::control::wrap(ty - yaw),
Self::MAX_YAW,
);
let dy = Self::counts(&mut self.pitch_budget, tp - pitch, Self::MAX_PITCH);
let fx = dx as f32 * m;
let fy = -(dy as f32) * m;
let new_yaw = (f64::from(yaw) + f64::from(fx) * 0.15) as f32;
let new_pitch = ((f64::from(pitch) - f64::from(fy) * 0.15) as f32).clamp(-90.0, 90.0);
(new_yaw, new_pitch)
}
}
#[must_use]
pub fn simulate<S: BlockSource + ?Sized>(
path: &Path,
world: &S,
cfg: &ControllerConfig,
) -> SimReport {
let mut sim = Simulation::new(path, cfg);
while sim.step(world, u32::MAX, None).is_none() {}
sim.into_report()
}
fn stone(version: Version) -> u32 {
match version {
Version::V1_8 => 1 << 4,
Version::V1_16_5 => u32::from(ghast_data::v1_16_5::Block::STONE.default_state().id()),
}
}
#[derive(Clone, Debug)]
enum Body {
V18(<P18 as Physics>::State),
V16(<P16 as Physics>::State),
}
#[derive(Clone, Debug)]
pub struct Simulation {
body: Body,
run: Run,
}
#[derive(Clone, Debug)]
struct Run {
version: Version,
turner: Turner,
ctrl: Controller,
overrides: Vec<([i32; 3], u32)>,
job: Option<([i32; 3], u32)>,
tick: u32,
max_ticks: u32,
report: SimReport,
done: bool,
}
impl Simulation {
#[must_use]
pub fn new(path: &Path, cfg: &ControllerConfig) -> Simulation {
let start = path.steps[0].target();
let yaw0 = path.steps.get(1).map_or(0.0, |s| {
let t = s.target();
(-(t[0] - start[0])).atan2(t[2] - start[2]).to_degrees() as f32
});
let body = match path.version {
Version::V1_8 => Body::V18(P18::new_state(start, yaw0, 0.0)),
Version::V1_16_5 => Body::V16(P16::new_state(start, yaw0, 0.0)),
};
let max_ticks = (path.cost * 4.0) as u32 + 20 * path.steps.len() as u32 + 200;
Simulation {
body,
run: Run {
version: path.version,
turner: Turner::default(),
ctrl: Controller::new(path.clone(), cfg.clone()),
overrides: Vec::new(),
job: None,
tick: 0,
max_ticks,
report: SimReport {
outcome: SimOutcome::Timeout,
ticks: 0,
reached: 0,
end: start,
collisions: 0,
first_collision: None,
max_fall: 0.0,
trace: Vec::with_capacity(max_ticks.min(4096) as usize),
},
done: false,
},
}
}
#[must_use]
pub fn path(&self) -> &Path {
self.run.ctrl.path()
}
pub fn step<S: BlockSource + ?Sized>(
&mut self,
world: &S,
ticks: u32,
time: Option<std::time::Duration>,
) -> Option<&SimReport> {
if !self.run.done {
let done = match &mut self.body {
Body::V18(s) => self.run.advance::<P18, S>(s, world, ticks, time),
Body::V16(s) => self.run.advance::<P16, S>(s, world, ticks, time),
};
self.run.done = done;
}
self.run.done.then_some(&self.run.report)
}
#[must_use]
pub fn report(&self) -> &SimReport {
&self.run.report
}
#[must_use]
pub fn into_report(self) -> SimReport {
self.run.report
}
}
impl Run {
fn advance<P: Physics, S: BlockSource + ?Sized>(
&mut self,
state: &mut P::State,
world: &S,
ticks: u32,
time: Option<std::time::Duration>,
) -> bool {
let tbl = table(self.version);
let started = time.map(|_| std::time::Instant::now());
let mut view =
SourceView::<P, S>::with_overrides(world, std::mem::take(&mut self.overrides));
let class = |v: &SourceView<'_, P, S>, x: i32, y: i32, z: i32| {
v.raw(x, y, z).map_or(crate::class::Class::UNKNOWN, |r| {
tbl.classes[tbl.index(r) as usize]
})
};
let report = &mut self.report;
let ctrl = &mut self.ctrl;
let mut done = false;
let mut n = 0u32;
while !done {
if self.tick >= self.max_ticks {
done = true;
break;
}
if n >= ticks
|| (n % 16 == 15
&& started
.zip(time)
.is_some_and(|(t0, max)| t0.elapsed() >= max))
{
break;
}
n += 1;
let tick = self.tick;
self.tick += 1;
let mut obs: Observation = P::observe(state);
obs.food = 20;
let want = ctrl.aim(&obs, &view);
let look = self.turner.step(obs.yaw, obs.pitch, want);
let cmd = ctrl.keys(&obs, look, &view);
report.reached = ctrl.reached();
match ctrl.progress() {
Progress::Arrived => {
report.outcome = SimOutcome::Arrived;
done = true;
break;
}
Progress::Stuck => {
report.outcome = SimOutcome::Stuck;
done = true;
break;
}
Progress::OffPath => {
report.outcome = SimOutcome::OffPath;
done = true;
break;
}
Progress::Moving | Progress::Working => {}
}
let target = cmd.dig.or(cmd.place.map(|p| p.pos));
match (target, self.job) {
(Some(p), Some((q, k))) if p == q => {
let need = match cmd.dig {
Some(d) => {
5 + (f64::from(class(&view, d[0], d[1], d[2]).hardness.max(0.0)) * 30.0)
as u32
}
None => 4,
};
if k + 1 >= need {
let raw = if cmd.dig.is_some() {
0
} else {
stone(self.version)
};
view.set(p, raw);
self.job = None;
} else {
self.job = Some((q, k + 1));
}
}
(Some(p), _) => self.job = Some((p, 0)),
(None, _) => self.job = None,
}
let keys = if target.is_some() {
Keys::NONE
} else {
cmd.keys
};
let kind = ctrl
.path()
.steps
.get(ctrl.reached() + 1)
.map_or(MoveKind::Start, |s| s.kind);
let fall_before = P::fall_distance(state);
P::tick(state, keys, look.0, look.1, &view);
let o = P::observe(state);
report.ticks = tick + 1;
report.end = o.pos;
report.trace.push(o.pos);
if o.on_ground {
report.max_fall = report.max_fall.max(fall_before);
}
if P::horizontal_collision(state)
&& matches!(
kind,
MoveKind::Walk
| MoveKind::Diagonal
| MoveKind::Descend
| MoveKind::Parkour { .. }
)
{
report.collisions += 1;
report.first_collision.get_or_insert(tick);
}
let (x, z) = (o.pos[0].floor() as i32, o.pos[2].floor() as i32);
let y0 = o.pos[1].floor() as i32;
let y1 = (o.pos[1] + 1.79).floor() as i32;
if (y0..=y1).any(|y| class(&view, x, y, z).has(flag::LAVA | flag::AVOID)) {
report.outcome = SimOutcome::Hazard;
done = true;
}
}
self.overrides = view.overrides;
done
}
}
#[cfg(all(test, feature = "client"))]
mod tests {
use super::Turner;
#[test]
fn turner_matches_the_client_rotation() {
let mut r = ghast_client::rotation::Rotation::new(0.5);
let mut t = Turner::default();
let (mut yaw, mut pitch) = (12.5_f32, 3.0_f32);
let targets = [
(100.0, 40.0),
(-170.0, -80.0),
(365.0, 0.0),
(12.3, 1.1),
(-45.0, 89.9),
];
let (mut y2, mut p2) = (yaw, pitch);
for (i, &(ty, tp)) in targets.iter().cycle().take(200).enumerate() {
if i % 7 == 0 {
r.set_target(ty, tp);
}
let target = r.target();
let a = r.step(yaw, pitch);
let b = t.step(y2, p2, target);
assert_eq!(a, b, "tick {i}");
(yaw, pitch) = a;
(y2, p2) = b;
}
}
}