use super::tests::opts;
use super::*;
use crate::common::{EntityAction, JoinGame};
use crate::phys_golden as golden;
use crate::sim::Sim18;
use ghast_protocol::RawPacket;
use ghast_protocol::v1_8::play::clientbound as cb;
use serde_json::Value;
use std::io::BufRead;
#[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 i8(mut self, v: i8) -> Self {
self.0.push(v as u8);
self
}
fn i16(mut self, v: i16) -> Self {
self.0.extend_from_slice(&v.to_be_bytes());
self
}
fn i32(mut self, v: i32) -> Self {
self.0.extend_from_slice(&v.to_be_bytes());
self
}
fn bool(mut self, v: bool) -> Self {
self.0.push(u8::from(v));
self
}
fn string(self, s: &str) -> Self {
let mut b = self.varint(s.len() as i32);
b.0.extend_from_slice(s.as_bytes());
b
}
fn flags(self, pig: bool, flags: i32) -> Self {
if pig {
self.i8(16).i8(flags as i8)
} else {
self.i8(2 << 5 | 16).i32(flags)
}
}
fn raw(self, id: i32) -> RawPacket {
RawPacket {
id,
body: bytes::Bytes::from(self.0),
}
}
}
fn f64v(v: &Value) -> f64 {
f64::from_bits(u64::from_str_radix(v[1].as_str().unwrap(), 16).unwrap())
}
fn f32v(v: &Value) -> f32 {
f32::from_bits(u32::from_str_radix(v[1].as_str().unwrap(), 16).unwrap())
}
const MOUNT: i32 = 100;
fn packet(ev: &Value, pig: bool) -> RawPacket {
let n = |k: &str| ev[k].as_i64().unwrap() as i32;
let og = || ev["on_ground"].as_bool().unwrap();
match ev["type"].as_str().unwrap() {
"ride" => Body::default()
.i32(1)
.i32(if ev["on"].as_bool().unwrap() {
MOUNT
} else {
-1
})
.bool(false)
.raw(cb::id::ATTACH_ENTITY),
"mount_teleport" => Body::default()
.varint(MOUNT)
.i32(n("x"))
.i32(n("y"))
.i32(n("z"))
.i8(n("yaw") as i8)
.i8(n("pitch") as i8)
.bool(og())
.raw(cb::id::ENTITY_TELEPORT),
"mount_move" => Body::default()
.varint(MOUNT)
.i8(n("dx") as i8)
.i8(n("dy") as i8)
.i8(n("dz") as i8)
.bool(og())
.raw(cb::id::REL_ENTITY_MOVE),
"mount_move_look" => Body::default()
.varint(MOUNT)
.i8(n("dx") as i8)
.i8(n("dy") as i8)
.i8(n("dz") as i8)
.i8(n("yaw") as i8)
.i8(n("pitch") as i8)
.bool(og())
.raw(cb::id::ENTITY_MOVE_LOOK),
"mount_look" => Body::default()
.varint(MOUNT)
.i8(n("yaw") as i8)
.i8(n("pitch") as i8)
.bool(og())
.raw(cb::id::ENTITY_LOOK),
"mount_idle" => Body::default().varint(MOUNT).raw(cb::id::ENTITY),
"mount_head_yaw" => Body::default()
.varint(MOUNT)
.i8(n("yaw") as i8)
.raw(cb::id::ENTITY_HEAD_ROTATION),
"mount_velocity" => Body::default()
.varint(MOUNT)
.i16(n("x") as i16)
.i16(n("y") as i16)
.i16(n("z") as i16)
.raw(cb::id::ENTITY_VELOCITY),
"mount_flags" => Body::default()
.varint(MOUNT)
.flags(pig, n("flags"))
.i8(127)
.raw(cb::id::ENTITY_METADATA),
other => panic!("event {other}"),
}
}
fn spawn_packet(m: &Value) -> RawPacket {
let p = &m["pos"];
let fixed = |k: usize| (f64v(&p[k]) * 32.0).floor() as i32;
let byte = |k: &str| (f32v(&m[k]) * 256.0 / 360.0).floor() as i32 as i8;
let pig = m["kind"] == "pig";
let b = Body::default()
.varint(MOUNT)
.i8(if pig { 90 } else { 100_u8 as i8 })
.i32(fixed(0))
.i32(fixed(1))
.i32(fixed(2))
.i8(byte("yaw"))
.i8(0)
.i8(byte("head_yaw"))
.i16(0)
.i16(0)
.i16(0)
.flags(pig, m["flags"].as_i64().unwrap() as i32);
let b = if pig {
b
} else {
b.i8(16 + 3).i8(m["horse_type"].as_i64().unwrap() as i8)
};
b.i8(127).raw(cb::id::SPAWN_ENTITY_LIVING)
}
fn login_packet() -> RawPacket {
Body::default()
.i32(1)
.i8(0)
.i8(0)
.i8(1)
.i8(20)
.string("flat")
.bool(false)
.raw(cb::id::LOGIN)
}
fn ours(o: &Outbound) -> Option<Value> {
let bits = |p: Vec3| [p.x.to_bits(), p.y.to_bits(), p.z.to_bits()];
Some(match *o {
Outbound::Move(MovePacket::Position { pos, on_ground, .. }) => {
serde_json::json!(["position", bits(pos), on_ground])
}
Outbound::Move(MovePacket::PositionLook {
pos,
yaw,
pitch,
on_ground,
..
}) => serde_json::json!([
"position_look",
bits(pos),
yaw.to_bits(),
pitch.to_bits(),
on_ground
]),
Outbound::Move(MovePacket::Look {
yaw,
pitch,
on_ground,
..
}) => serde_json::json!(["look", yaw.to_bits(), pitch.to_bits(), on_ground]),
Outbound::Move(MovePacket::Flying { on_ground, .. }) => {
serde_json::json!(["flying", on_ground])
}
Outbound::SteerVehicle {
sideways,
forward,
jump,
sneak,
} => serde_json::json!([
"steer_vehicle",
sideways.to_bits(),
forward.to_bits(),
jump,
sneak
]),
Outbound::Abilities { flags, .. } => serde_json::json!(["abilities", flags]),
Outbound::RidingJump { strength, .. } => {
serde_json::json!(["entity_action", "riding_jump", strength])
}
Outbound::EntityAction { action, .. } => serde_json::json!([
"entity_action",
match action {
EntityAction::StartSprinting => "start_sprinting",
EntityAction::StopSprinting => "stop_sprinting",
EntityAction::StartSneaking => "start_sneaking",
EntityAction::StopSneaking => "stop_sneaking",
_ => "other",
}
]),
_ => return None,
})
}
fn theirs(p: &Value) -> Option<Value> {
let bits = |v: &Value| {
[
f64v(&v[0]).to_bits(),
f64v(&v[1]).to_bits(),
f64v(&v[2]).to_bits(),
]
};
let og = &p["on_ground"];
let flag = |k: &str, f: i8| if p[k].as_bool().unwrap() { f } else { 0 };
Some(match p["name"].as_str().unwrap() {
"position" => serde_json::json!(["position", bits(&p["pos"]), og]),
"position_look" => serde_json::json!([
"position_look",
bits(&p["pos"]),
f32v(&p["yaw"]).to_bits(),
f32v(&p["pitch"]).to_bits(),
og
]),
"look" => serde_json::json!([
"look",
f32v(&p["yaw"]).to_bits(),
f32v(&p["pitch"]).to_bits(),
og
]),
"flying" => serde_json::json!(["flying", og]),
"steer_vehicle" => serde_json::json!([
"steer_vehicle",
f32v(&p["sideways"]).to_bits(),
f32v(&p["forward"]).to_bits(),
p["jump"],
p["sneak"]
]),
"abilities" => serde_json::json!([
"abilities",
flag("invulnerable", 1)
| flag("flying", 2)
| flag("allow_flying", 4)
| flag("creative", 8)
]),
"entity_action" if p["action_name"] == "riding_jump" => {
serde_json::json!(["entity_action", "riding_jump", p["jump_boost"]])
}
"entity_action" => serde_json::json!(["entity_action", p["action_name"]]),
_ => return None,
})
}
struct Keys(Controls);
impl Behavior for Keys {
fn name(&self) -> &str {
"mounts-replay-1.8"
}
fn tick(&mut self, ctx: &mut TickContext<'_>) {
ctx.set_controls(self.0);
}
}
fn replay_file(path: &std::path::Path, metadata: bool) -> (usize, usize, Vec<String>) {
let f = std::fs::File::open(path).unwrap();
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_done) = (0, 0);
let mut failed = Vec::new();
while let Some(sc) = lines.next() {
let name = sc["name"].as_str().unwrap().to_owned();
let mut ticks = Vec::new();
while let Some(t) = lines.next_if(|l| l["type"] == "tick") {
ticks.push(t);
}
cases += 1;
let setup = &sc["setup"];
let mount = &setup["ext"]["mount"];
let pig = mount["kind"] == "pig";
let mut e = Engine::new(opts(GameVersion::V1_8_9), Sim18::new());
e.handle(Inbound::JoinGame(JoinGame {
entity_id: 1,
game_mode: GameMode::Survival,
dimension: "0".into(),
hardcore: false,
dimension_nbt: None,
respawn_screen: true,
}));
e.sim.set_entities(Some(
ghast_entity::Config::default()
.with_metadata(metadata)
.with_equipment(false)
.with_effects(false)
.with_player_list(false)
.with_player_names(false)
.with_events(false)
.with_client_motion(true),
));
e.sim.world_packet(&login_packet()).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(&crate::sim::test_chunks::v1_8(x, z))
.unwrap();
}
}
for x in r[0] * 16..r[2] * 16 + 16 {
for z in r[1] * 16..r[3] * 16 + 16 {
e.sim.predict_air(x, 63, z);
}
}
}
for fill in sc["fills"].as_array().unwrap() {
let v: Vec<i64> = (0..8).map(|k| fill[k].as_i64().unwrap()).collect();
let st = ghast_data::v1_8::BlockState::from_raw_vanilla(
((v[6] as u16) << 4) | (v[7] as u16 & 15),
);
for x in v[0]..=v[3] {
for y in v[1]..=v[4] {
for z in v[2]..=v[5] {
e.sim.test_set_block(x as i32, y as i32, z as i32, st);
}
}
}
}
e.handle(Inbound::Teleport(crate::common::Teleport {
x: f64v(&setup["pos"][0]),
y: f64v(&setup["pos"][1]),
z: f64v(&setup["pos"][2]),
yaw: f32v(&setup["yaw"]),
pitch: f32v(&setup["pitch"]),
teleport_id: None,
..Default::default()
}));
let p = golden::player_of(&sc, &ticks[0]);
let mut pose = e.core.pose;
e.sim.test_set_player(&mut pose, p);
e.core.pose = pose;
e.sim.world_packet(&spawn_packet(mount)).unwrap();
e.core.ready = true;
e.outbound().clear();
let t0 = Instant::now();
for (k, rec) in ticks.iter().enumerate().skip(1) {
let input = &rec["input"];
for ev in input["events"].as_array().into_iter().flatten() {
if ev["type"] == "teleport" {
let flags = ev.get("flags").and_then(Value::as_i64).unwrap_or(0);
e.handle(Inbound::Teleport(crate::common::Teleport {
x: f64v(&ev["pos"][0]),
y: f64v(&ev["pos"][1]),
z: f64v(&ev["pos"][2]),
yaw: f32v(&ev["yaw"]),
pitch: f32v(&ev["pitch"]),
flags: flags as i8,
relative: flags as u32,
teleport_id: None,
..Default::default()
}));
continue;
}
e.sim.world_packet(&packet(ev, pig)).unwrap();
}
let keys = input["keys"].as_str().unwrap();
let has = |k: &str| keys.split(',').any(|n| n == k);
let mut b = Keys(Controls {
forward: has("forward"),
back: has("back"),
left: has("left"),
right: has("right"),
jump: has("jump"),
sneak: has("sneak"),
sprint: has("sprint"),
});
e.core.forced_look = Some((f32v(&input["yaw"]), f32v(&input["pitch"])));
e.note_inbound(t0);
e.tick(&mut b, t0);
let out = std::mem::take(e.outbound());
let got: Vec<Value> = out.iter().filter_map(ours).collect();
let want: Vec<Value> = rec["packets"]
.as_array()
.unwrap()
.iter()
.filter_map(theirs)
.collect();
if got != want {
failed.push(format!("{name} tick {k}: got {got:?} want {want:?}"));
break;
}
let want_pos = [0, 1, 2].map(|i| f64v(&rec["state"]["pos"][i]));
if e.sim.test_player().pos != want_pos {
failed.push(format!(
"{name} tick {k}: player at {:?} want {want_pos:?}",
e.sim.test_player().pos
));
break;
}
ticks_done += 1;
}
}
eprintln!(
"1.8.9 {} through the engine (metadata {metadata}): {cases} cases, {ticks_done} ticks, \
{} cases differ",
path.display(),
failed.len()
);
(cases, ticks_done, failed)
}
fn cache_files() -> Vec<std::path::PathBuf> {
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../oracle/cache/1.8.9/fuzz-mounts");
let Ok(rd) = std::fs::read_dir(&dir) else {
eprintln!("skipped: {} not found", dir.display());
return Vec::new();
};
let mut files: Vec<_> = rd
.filter_map(|e| e.ok().map(|e| e.path()))
.filter(|p| p.to_string_lossy().ends_with(".jsonl.gz"))
.collect();
files.sort();
files
}
#[test]
fn mounts_match_the_oracle_1_8_9() {
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../tests/golden/1.8.9/mounts.jsonl.gz");
let (cases, ticks, failed) = replay_file(&path, true);
assert!(
failed.is_empty(),
"{} cases differ:\n{}",
failed.len(),
failed.join("\n")
);
assert!(cases >= 75 && ticks > 4500, "{cases} cases, {ticks} ticks");
}
#[test]
fn mounts_without_metadata_take_a_saddled_mount_1_8_9() {
use std::io::BufRead;
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../tests/golden/1.8.9/mounts.jsonl.gz");
let f = std::fs::File::open(&path).unwrap();
let mut assumed: std::collections::HashMap<String, bool> = Default::default();
let (mut name, mut pig) = (String::new(), false);
let fits = |pig: bool, flags: i64| {
if pig {
flags & 1 != 0
} else {
flags & (4 | 64) == 4
}
};
for l in std::io::BufReader::new(flate2::read::GzDecoder::new(f)).lines() {
let v: Value = serde_json::from_str(&l.unwrap()).unwrap();
if v["type"] == "scenario" {
let m = &v["setup"]["ext"]["mount"];
name = v["name"].as_str().unwrap().to_owned();
pig = m["kind"] == "pig";
assumed.insert(name.clone(), fits(pig, m["flags"].as_i64().unwrap()));
} else {
for e in v["input"]["events"].as_array().into_iter().flatten() {
if e["type"] == "mount_flags" && !fits(pig, e["flags"].as_i64().unwrap()) {
assumed.insert(name.clone(), false);
}
}
}
}
let (cases, ticks, failed) = replay_file(&path, false);
assert!(cases >= 75 && ticks > 4000, "{cases} cases, {ticks} ticks");
for f in &failed {
let name = f.split(" tick ").next().unwrap();
assert!(
!assumed[name],
"a saddled mount differs without metadata: {f}"
);
}
let other = assumed.values().filter(|&&ok| !ok).count();
eprintln!(
"without metadata: {} of {other} cases with other flags differ",
failed.len()
);
}
#[test]
fn dismounts_match_the_oracle_1_8_9() {
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../tests/golden/1.8.9/dismounts.jsonl.gz");
let (cases, ticks, failed) = replay_file(&path, true);
assert!(
failed.is_empty(),
"{} cases differ:\n{}",
failed.len(),
failed.join("\n")
);
assert!(cases >= 20 && ticks > 700, "{cases} cases, {ticks} ticks");
}
#[test]
fn mounts_board_match_the_oracle_1_8_9() {
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../tests/golden/1.8.9/mounts_board.jsonl.gz");
for metadata in [true, false] {
let (cases, ticks, failed) = replay_file(&path, metadata);
assert!(
failed.is_empty(),
"metadata {metadata}: {} cases differ:\n{}",
failed.len(),
failed.join("\n")
);
assert!(cases >= 24 && ticks >= 1200, "{cases} cases, {ticks} ticks");
}
}
#[test]
#[ignore = "needs the oracle cache"]
fn mounts_board_cache_match_the_oracle_1_8_9() {
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../oracle/cache/1.8.9/fuzz-mount-boards");
let mut files: Vec<_> = std::fs::read_dir(&dir)
.unwrap()
.filter_map(|e| e.ok().map(|e| e.path()))
.filter(|p| p.to_string_lossy().ends_with(".jsonl.gz"))
.collect();
files.sort();
assert!(!files.is_empty());
let (mut cases, mut ticks, mut failed) = (0, 0, Vec::new());
for f in &files {
let (c, t, x) = replay_file(f, true);
cases += c;
ticks += t;
failed.extend(x);
}
eprintln!("1.8.9 boarding cache through the engine: {cases} cases, {ticks} ticks");
assert!(
failed.is_empty(),
"{} cases differ:\n{}",
failed.len(),
failed.join("\n")
);
}
#[test]
#[ignore = "needs the oracle cache"]
fn mounts_cache_match_the_oracle_1_8_9() {
let (mut cases, mut ticks, mut failed) = (0, 0, Vec::new());
for f in &cache_files() {
let (c, t, x) = replay_file(f, true);
cases += c;
ticks += t;
failed.extend(x);
}
eprintln!("1.8.9 mount fuzz cache through the engine: {cases} cases, {ticks} ticks");
assert!(
failed.is_empty(),
"{} cases differ:\n{}",
failed.len(),
failed.join("\n")
);
}