use super::tests::opts;
use super::*;
use ghast_protocol::RawPacket;
use serde_json::Value;
use std::io::BufRead;
fn hex64(v: &Value) -> f64 {
f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap())
}
fn hex32(v: &Value) -> f32 {
f32::from_bits(u32::from_str_radix(v.as_str().unwrap(), 16).unwrap())
}
fn unhex(s: &str) -> bytes::Bytes {
(0..s.len() / 2)
.map(|i| u8::from_str_radix(&s[2 * i..2 * i + 2], 16).unwrap())
.collect::<Vec<u8>>()
.into()
}
trait Fixture {
type S: Sim;
const GAME: GameVersion;
const GOLDEN: &'static str;
fn sim() -> Self::S;
fn chunk(x: i32, z: i32) -> RawPacket;
fn set_block(s: &mut Self::S, x: i32, y: i32, z: i32, fill: &Value);
fn packet_id(name: &str) -> i32;
const KINDS: usize;
fn snowball() -> RawPacket;
fn login(me: i32) -> Option<RawPacket> {
let _ = me;
None
}
}
fn legacy_snowball(id: i32, uuid: bool, fixed: bool) -> RawPacket {
let mut b = Body::default().varint(50);
if uuid {
b = b.bytes(&[9; 16]);
}
b = b.bytes(&[61]);
for v in [4.5f64, 66.0, 4.5] {
b = if fixed {
b.bytes(&((v * 32.0) as i32).to_be_bytes())
} else {
b.bytes(&v.to_be_bytes())
};
}
b = b.bytes(&[0, 0]).bytes(&0i32.to_be_bytes());
if uuid {
b = b.bytes(&[0; 6]);
}
b.raw(id)
}
struct V18;
impl Fixture for V18 {
type S = crate::sim::Sim18;
const GAME: GameVersion = GameVersion::V1_8_9;
const GOLDEN: &'static str = "1.8.9";
const KINDS: usize = 12;
fn sim() -> Self::S {
crate::sim::Sim18::new()
}
fn chunk(x: i32, z: i32) -> RawPacket {
crate::sim::test_chunks::v1_8(x, z)
}
fn set_block(s: &mut Self::S, x: i32, y: i32, z: i32, fill: &Value) {
let id = fill[6].as_u64().unwrap() as u16;
let meta = fill[7].as_u64().unwrap() as u16;
s.test_set_block(
x,
y,
z,
ghast_data::v1_8::BlockState::from_raw_vanilla(id << 4 | (meta & 15)),
);
}
fn packet_id(name: &str) -> i32 {
use ghast_protocol::v1_8::play::clientbound::id;
legacy_id(
name,
[
id::SPAWN_ENTITY,
id::SPAWN_ENTITY_EXPERIENCE_ORB,
id::ENTITY_VELOCITY,
id::REL_ENTITY_MOVE,
id::ENTITY_LOOK,
id::ENTITY_MOVE_LOOK,
id::ENTITY,
id::ENTITY_TELEPORT,
id::ENTITY_METADATA,
id::ENTITY_DESTROY,
],
)
}
fn snowball() -> RawPacket {
legacy_snowball(
ghast_protocol::v1_8::play::clientbound::id::SPAWN_ENTITY,
false,
true,
)
}
fn login(me: i32) -> Option<RawPacket> {
let mut b = me.to_be_bytes().to_vec();
b.extend_from_slice(&[0, 0, 1, 20, 4]);
b.extend_from_slice(b"flat");
b.push(0);
Some(RawPacket {
id: ghast_protocol::v1_8::play::clientbound::id::LOGIN,
body: bytes::Bytes::from(b),
})
}
}
struct V112;
impl Fixture for V112 {
type S = crate::sim::Sim12;
const GAME: GameVersion = GameVersion::V1_12_2;
const GOLDEN: &'static str = "1.12.2";
const KINDS: usize = 13;
fn sim() -> Self::S {
crate::sim::Sim12::new()
}
fn chunk(x: i32, z: i32) -> RawPacket {
crate::sim::test_chunks::v1_12_2(x, z)
}
fn set_block(s: &mut Self::S, x: i32, y: i32, z: i32, fill: &Value) {
let id = fill[6].as_u64().unwrap() as u16;
let meta = fill[7].as_u64().unwrap() as u16;
s.test_set_block(
x,
y,
z,
ghast_data::v1_12::BlockState::from_raw_vanilla(id << 4 | (meta & 15)),
);
}
fn packet_id(name: &str) -> i32 {
use ghast_protocol::v1_12_2::play::clientbound::id;
legacy_id(
name,
[
id::SPAWN_ENTITY,
id::SPAWN_ENTITY_EXPERIENCE_ORB,
id::ENTITY_VELOCITY,
id::REL_ENTITY_MOVE,
id::ENTITY_LOOK,
id::ENTITY_MOVE_LOOK,
id::ENTITY,
id::ENTITY_TELEPORT,
id::ENTITY_METADATA,
id::ENTITY_DESTROY,
],
)
}
fn snowball() -> RawPacket {
legacy_snowball(
ghast_protocol::v1_12_2::play::clientbound::id::SPAWN_ENTITY,
true,
false,
)
}
fn login(me: i32) -> Option<RawPacket> {
let mut b = me.to_be_bytes().to_vec();
b.push(0);
b.extend_from_slice(&0i32.to_be_bytes());
b.extend_from_slice(&[1, 20, 4]);
b.extend_from_slice(b"flat");
b.push(0);
Some(RawPacket {
id: ghast_protocol::v1_12_2::play::clientbound::id::LOGIN,
body: bytes::Bytes::from(b),
})
}
}
#[derive(Default)]
struct Body(Vec<u8>);
impl Body {
fn varint(mut self, v: i32) -> Self {
let mut u = v as u32;
loop {
let b = (u & 0x7f) as u8;
u >>= 7;
if u == 0 {
self.0.push(b);
return self;
}
self.0.push(b | 0x80);
}
}
fn bytes(mut self, b: &[u8]) -> Self {
self.0.extend_from_slice(b);
self
}
fn raw(self, id: i32) -> RawPacket {
RawPacket {
id,
body: self.0.into(),
}
}
}
fn only_with_the_interest<F: Fixture>() {
let run = |physics: bool| {
let mut e = Engine::new(opts(F::GAME), F::sim());
e.sim.set_entities(crate::client::entity_config(
crate::Interests::ENTITY_TRACKING,
F::GAME.caps(),
));
e.sim.set_entity_physics(physics);
e.sim.world_packet(&F::chunk(0, 0)).unwrap();
e.sim.world_packet(&F::snowball()).unwrap();
let mut pose = e.core.pose;
for _ in 0..5 {
e.sim.tick_entities(&mut pose);
}
e.sim.entities().unwrap().get(50).unwrap().position()
};
assert_eq!(run(false), [4.5, 66.0, 4.5]);
let p = run(true);
assert!(p[1] < 66.0 && p[0] == 4.5 && p[2] == 4.5, "{p:?}");
}
struct V116;
impl Fixture for V116 {
type S = crate::sim::Sim16;
const GAME: GameVersion = GameVersion::V1_16_5;
const GOLDEN: &'static str = "1.16.5";
const KINDS: usize = 15;
fn snowball() -> RawPacket {
let ty = ghast_data::v1_16_5::entities()
.iter()
.find(|e| e.name == "snowball")
.unwrap()
.id;
let mut b = Body::default()
.varint(50)
.bytes(&[9; 16])
.varint(i32::from(ty));
for v in [4.5f64, 66.0, 4.5] {
b = b.bytes(&v.to_be_bytes());
}
b.bytes(&[0; 2 + 4 + 6])
.raw(ghast_protocol::v1_16_5::play::clientbound::id::SPAWN_ENTITY)
}
fn sim() -> Self::S {
crate::sim::Sim16::new()
}
fn chunk(x: i32, z: i32) -> RawPacket {
crate::sim::test_chunks::v1_16_5(x, z)
}
fn set_block(s: &mut Self::S, x: i32, y: i32, z: i32, fill: &Value) {
let st =
ghast_data::v1_16_5::BlockState::from_id(fill[6].as_u64().unwrap() as u16).unwrap();
s.test_set_block(x, y, z, st);
}
fn packet_id(name: &str) -> i32 {
use ghast_protocol::v1_16_5::play::clientbound::id;
legacy_id(
name,
[
id::SPAWN_ENTITY,
id::SPAWN_ENTITY_EXPERIENCE_ORB,
id::ENTITY_VELOCITY,
id::REL_ENTITY_MOVE,
id::ENTITY_LOOK,
id::ENTITY_MOVE_LOOK,
id::ENTITY,
id::ENTITY_TELEPORT,
id::ENTITY_METADATA,
id::ENTITY_DESTROY,
],
)
}
}
fn legacy_id(name: &str, ids: [i32; 10]) -> i32 {
let i = match name {
"spawn_entity" => 0,
"spawn_entity_experience_orb" => 1,
"entity_velocity" => 2,
"rel_entity_move" => 3,
"entity_look" => 4,
"entity_move_look" => 5,
"entity" => 6,
"entity_teleport" => 7,
"entity_metadata" => 8,
"entity_destroy" => 9,
n => panic!("unknown packet {n}"),
};
ids[i]
}
fn compare<S: Sim>(e: &Engine<S>, rec: &Value, at: &str) -> usize {
let t = e.sim.entities().unwrap();
let want = rec["entities"].as_array().unwrap();
let mut got: Vec<i32> = t.iter().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();
let vel: Vec<f64> = (0..3).map(|k| hex64(&w["vel"][k])).collect();
let bits = |a: &[f64]| a.iter().map(|v| v.to_bits()).collect::<Vec<_>>();
assert_eq!(
bits(&x.position()),
bits(&pos),
"{at}: {ty} {id} pos {:?} want {pos:?}",
x.position()
);
assert_eq!(
bits(&x.velocity()),
bits(&vel),
"{at}: {ty} {id} vel {:?} want {vel:?}",
x.velocity()
);
let rot = [hex32(&w["rot"][0]), hex32(&w["rot"][1])];
assert_eq!(
[x.yaw().to_bits(), x.pitch().to_bits()],
[rot[0].to_bits(), rot[1].to_bits()],
"{at}: {ty} {id} rot {:?} want {rot:?}",
[x.yaw(), x.pitch()]
);
assert_eq!(
x.on_ground(),
w["ground"].as_bool().unwrap(),
"{at}: {ty} {id} ground"
);
}
want.len()
}
fn replay<F: Fixture>() {
let var = format!("GHAST_NONLIVING_{}", F::GOLDEN.replace('.', "_"));
let path = std::env::var(&var).unwrap_or_else(|_| {
format!(
"{}/../../tests/golden/{}/nonliving_tracking.jsonl.gz",
env!("CARGO_MANIFEST_DIR"),
F::GOLDEN
)
});
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 cases, mut ticks, mut compared) = (0, 0, 0);
let mut kinds = std::collections::BTreeSet::new();
while let Some(sc) = lines.next() {
assert_eq!(sc["type"], "scenario");
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(
crate::Interests::ENTITY_TRACKING,
F::GAME.caps(),
));
e.sim.set_entity_physics(true);
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();
}
}
}
for fill in sc["fills"].as_array().unwrap() {
let v: Vec<i32> = (0..6).map(|k| fill[k].as_i64().unwrap() as i32).collect();
for x in v[0]..=v[3] {
for y in v[1]..=v[4] {
for z in v[2]..=v[5] {
F::set_block(&mut e.sim, x, y, z, fill);
}
}
}
}
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::packet_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() {
kinds.insert(w["type"].as_str().unwrap().to_owned());
}
compared += compare(&e, &rec, &format!("{name} tick {k}"));
e.sim.tick_entities(&mut pose);
ticks += 1;
}
}
eprintln!(
"{} non-living physics: {cases} cases, {ticks} ticks, {compared} entity states identical, kinds {kinds:?}",
F::GOLDEN
);
assert!(
cases >= 10 && ticks >= 400 && compared >= 2000,
"{cases} {ticks} {compared}"
);
assert!(kinds.len() >= F::KINDS, "{kinds:?}");
}
#[test]
fn nonliving_physics_matches_the_oracle_1_16_5() {
replay::<V116>();
}
#[test]
fn nonliving_physics_only_with_the_interest_1_16_5() {
only_with_the_interest::<V116>();
}
#[test]
fn nonliving_physics_matches_the_oracle_1_12_2() {
replay::<V112>();
}
#[test]
fn nonliving_physics_only_with_the_interest_1_12_2() {
only_with_the_interest::<V112>();
}
#[test]
fn nonliving_physics_matches_the_oracle_1_8_9() {
replay::<V18>();
}
#[test]
fn nonliving_physics_only_with_the_interest_1_8_9() {
only_with_the_interest::<V18>();
}