use super::tests::opts;
use super::tests_nonliving_legacy::{Fixture, V18, V112, V116, hex32, hex64, unhex};
use super::*;
use ghast_protocol::RawPacket;
use serde_json::Value;
use std::io::BufRead;
trait Boxes: Fixture {
const LIVING: i32;
const PAINTING: i32;
fn id(name: &str) -> i32 {
match name {
"spawn_entity_living" => Self::LIVING,
"spawn_entity_painting" => Self::PAINTING,
n => Self::packet_id(n),
}
}
}
impl Boxes for V18 {
const LIVING: i32 = ghast_protocol::v1_8::play::clientbound::id::SPAWN_ENTITY_LIVING;
const PAINTING: i32 = ghast_protocol::v1_8::play::clientbound::id::SPAWN_ENTITY_PAINTING;
}
impl Boxes for V112 {
const LIVING: i32 = ghast_protocol::v1_12_2::play::clientbound::id::SPAWN_ENTITY_LIVING;
const PAINTING: i32 = ghast_protocol::v1_12_2::play::clientbound::id::SPAWN_ENTITY_PAINTING;
}
impl Boxes for V116 {
const LIVING: i32 = ghast_protocol::v1_16_5::play::clientbound::id::SPAWN_ENTITY_LIVING;
const PAINTING: i32 = ghast_protocol::v1_16_5::play::clientbound::id::SPAWN_ENTITY_PAINTING;
}
#[derive(Default)]
struct Totals {
cases: usize,
ticks: usize,
compared: usize,
kinds: std::collections::BTreeSet<String>,
diffs: std::collections::BTreeMap<String, usize>,
first: Vec<String>,
}
impl Totals {
fn diff(&mut self, ty: &str, field: &str, text: String) {
*self.diffs.entry(format!("{ty} {field}")).or_default() += 1;
if self.first.len() < 12 {
self.first.push(text);
}
}
}
fn bits(a: &[f64]) -> Vec<u64> {
a.iter().map(|v| v.to_bits()).collect()
}
fn compare<S: Sim>(e: &Engine<S>, rec: &Value, at: &str, d: &mut Totals) -> usize {
let t = e.sim.entities().unwrap();
let want = rec["entities"].as_array().unwrap();
let mut got: Vec<i32> = t
.iter()
.filter(|e| !e.is_player())
.map(ghast_entity::Entity::id)
.collect();
got.sort_unstable();
let ids: Vec<i32> = want
.iter()
.map(|w| w["id"].as_i64().unwrap() as i32)
.collect();
assert_eq!(got, ids, "{at}: entity ids");
for w in want {
let id = w["id"].as_i64().unwrap() as i32;
let x = t.get(id).unwrap();
let ty = w["type"].as_str().unwrap();
let pos: Vec<f64> = (0..3).map(|k| hex64(&w["pos"][k])).collect();
if bits(&x.drawn_position()) != bits(&pos) {
d.diff(
ty,
"pos",
format!("{at}: {ty} {id} pos {:?} want {pos:?}", x.drawn_position()),
);
}
let bx: Vec<f64> = (0..6).map(|k| hex64(&w["box"][k])).collect();
let got = x.drawn_bounding_box();
if got.map(|b| bits(&b)) != Some(bits(&bx)) {
d.diff(
ty,
"box",
format!(
"{at}: {ty} {id} box {got:?} want {bx:?} (pos {:?} server box {:?})",
x.position(),
x.bounding_box()
),
);
}
let margin = hex32(&w["margin"]);
if x.targeting_margin().to_bits() != margin.to_bits() {
d.diff(
ty,
"margin",
format!(
"{at}: {ty} {id} margin {} want {margin}",
x.targeting_margin()
),
);
}
let rot = [hex32(&w["rot"][0]), hex32(&w["rot"][1])];
let (yaw, pitch) = x.drawn_rotation();
if [yaw.to_bits(), pitch.to_bits()] != [rot[0].to_bits(), rot[1].to_bits()] {
d.diff(
ty,
"rot",
format!("{at}: {ty} {id} rot {:?} want {rot:?}", [yaw, pitch]),
);
}
}
want.len()
}
fn replay_file<F: Boxes>(path: &str, metadata: bool) -> Totals {
let f = std::fs::File::open(path).unwrap_or_else(|e| panic!("{path}: {e}"));
let mut lines = std::io::BufReader::new(flate2::read::GzDecoder::new(f))
.lines()
.map(|l| serde_json::from_str::<Value>(&l.unwrap()).unwrap())
.peekable();
let mut t = Totals::default();
let interests = if metadata {
crate::Interests::ENTITY_TRACKING | crate::Interests::ENTITIES
} else {
crate::Interests::ENTITY_TRACKING
};
while let Some(sc) = lines.next() {
assert_eq!(sc["type"], "scenario");
assert_eq!(sc["tracking"]["boxes"], true);
t.cases += 1;
let name = sc["name"].as_str().unwrap().to_owned();
let me = sc["tracking"]["player_id"].as_i64().unwrap() as i32;
let mut e = Engine::new(opts(F::GAME), F::sim());
e.sim
.set_entities(crate::client::entity_config(interests, F::GAME.caps()));
e.sim.test_set_own_id(me);
if let Some(login) = F::login(me) {
e.sim.world_packet(&login).unwrap();
}
for r in sc["loaded_chunks"].as_array().unwrap() {
let r: Vec<i32> = (0..4).map(|k| r[k].as_i64().unwrap() as i32).collect();
for x in r[0]..=r[2] {
for z in r[1]..=r[3] {
e.sim.world_packet(&F::chunk(x, z)).unwrap();
}
}
}
let mut pose = e.core.pose;
while let Some(rec) = lines.next_if(|l| l["type"] == "tick") {
let k = rec["tick"].as_i64().unwrap();
for p in rec["packets"].as_array().unwrap() {
let raw = RawPacket {
id: F::id(p[0].as_str().unwrap()),
body: unhex(p[1].as_str().unwrap()),
};
e.sim.world_packet(&raw).unwrap();
}
for w in rec["entities"].as_array().unwrap() {
t.kinds.insert(w["type"].as_str().unwrap().to_owned());
}
let at = format!("{name} tick {k} (metadata {metadata})");
let n = compare(&e, &rec, &at, &mut t);
t.compared += n;
e.sim.tick_entities(&mut pose);
t.ticks += 1;
}
}
t
}
fn replay<F: Boxes>(kinds: usize) {
let var = format!("GHAST_BOXES_{}", F::GOLDEN.replace('.', "_"));
let path = std::env::var(&var).unwrap_or_else(|_| {
format!(
"{}/../../tests/golden/{}/entity_boxes.jsonl.gz",
env!("CARGO_MANIFEST_DIR"),
F::GOLDEN
)
});
for metadata in [false, true] {
let t = replay_file::<F>(&path, metadata);
eprintln!(
"{} entity boxes (metadata {metadata}): {} cases, {} ticks, {} entity states identical, kinds {:?}",
F::GOLDEN,
t.cases,
t.ticks,
t.compared,
t.kinds
);
assert!(
t.cases >= 10 && t.ticks >= 400 && t.compared >= 2000,
"{} {} {}",
t.cases,
t.ticks,
t.compared
);
assert_eq!(t.kinds.len(), kinds, "{:?}", t.kinds);
assert!(
t.diffs.is_empty(),
"{} differences {:?}, first:\n{}",
F::GOLDEN,
t.diffs,
t.first.join("\n")
);
}
}
#[test]
fn entity_boxes_match_the_oracle_1_16_5() {
replay::<V116>(4);
}
#[test]
fn entity_boxes_match_the_oracle_1_12_2() {
replay::<V112>(4);
}
#[test]
fn entity_boxes_match_the_oracle_1_8_9() {
replay::<V18>(3);
}