use super::tests::opts;
use super::*;
use crate::common::{EntityAction, JoinGame};
use crate::version::ClientVersion;
use ghast_protocol::{PacketFilter, RawPacket};
use serde_json::Value;
use std::io::BufRead;
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())
}
fn i(v: &Value) -> i32 {
v.as_i64().unwrap() as i32
}
fn pos(v: &Value) -> ghast_protocol::BlockPos {
ghast_protocol::BlockPos::new(i(&v[0]), i(&v[1]), i(&v[2]))
}
const ME: i32 = 1;
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::TeleportConfirm(id) | Outbound::TeleportConfirmPose { id, .. } => {
serde_json::json!(["teleport_confirm", id])
}
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",
EntityAction::LeaveBed => "stop_sleeping",
_ => "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"];
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]),
"teleport_confirm" => serde_json::json!(["teleport_confirm", p["teleport_id"]]),
"entity_action" => serde_json::json!(["entity_action", p["action_name"]]),
_ => return None,
})
}
struct Keys {
controls: Controls,
leave: bool,
}
impl Behavior for Keys {
fn name(&self) -> &str {
"sleep-replay"
}
fn tick(&mut self, ctx: &mut TickContext<'_>) {
ctx.set_controls(self.controls);
if self.leave {
assert!(ctx.leave_bed(), "leave_bed refused");
}
}
}
trait Fixture {
type V: ClientVersion;
type S: Sim;
const TELEPORT_IDS: bool = true;
fn sim() -> Self::S;
fn login() -> Option<RawPacket> {
None
}
fn join(s: &mut Self::S) {
match Self::login() {
Some(raw) => s.world_packet(&raw).unwrap(),
None => s.test_set_own_id(ME),
}
}
fn chunk(x: i32, z: i32) -> RawPacket;
fn set_block(s: &mut Self::S, x: i32, y: i32, z: i32, fill: &Value);
fn fill_world(e: &mut Engine<Self::S>, sc: &Value, filter: &PacketFilter) {
let _ = filter;
for fill in sc["fills"].as_array().unwrap() {
let v: Vec<i32> = (0..6).map(|k| i(&fill[k])).collect();
for x in v[0]..=v[3] {
for y in v[1]..=v[4] {
for z in v[2]..=v[5] {
Self::set_block(&mut e.sim, x, y, z, fill);
}
}
}
}
}
fn set_player(e: &mut Engine<Self::S>, sc: &Value, t0: &Value);
fn packet(ev: &Value) -> RawPacket;
fn state(s: &Self::S) -> ([f64; 3], [f64; 6], [f64; 3], f32, f32);
}
fn feed<F: Fixture>(e: &mut Engine<F::S>, filter: &PacketFilter, raw: &RawPacket) {
if !filter.contains(raw.id) {
return;
}
e.sim.world_packet(raw).unwrap();
if let Some(o) = F::V::inventory_packet(e.inventory_mut(), raw).unwrap() {
e.outbound().push(Outbound::Inventory(o));
}
let mut wire = <F::V as ClientVersion>::Wire::default();
if let Some(p) = F::V::decode_play(raw, &mut wire).unwrap() {
e.handle(p);
}
}
fn replay<F: Fixture>(path: &str) -> (usize, usize, Vec<String>) {
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_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);
}
if let Ok(only) = std::env::var("GHAST_SLEEP_CASES")
&& !only.split(',').any(|n| n == name)
{
continue;
}
cases += 1;
let setup = &sc["setup"];
let mut e = Engine::new(opts(F::V::GAME), F::sim());
e.handle(Inbound::JoinGame(JoinGame {
entity_id: ME,
game_mode: GameMode::Survival,
dimension: "0".into(),
hardcore: false,
dimension_nbt: None,
respawn_screen: true,
}));
F::join(&mut e.sim);
let mut filter = F::V::play_filter(Interests::default());
for id in e.sim.entity_packet_ids() {
filter.insert(id);
}
for id in e.sim.world_packet_ids() {
filter.insert(id);
}
for &id in F::V::inventory_packet_ids(e.inventory_mut()) {
filter.insert(id);
}
for r in sc["loaded_chunks"].as_array().unwrap() {
let r: Vec<i32> = (0..4).map(|k| i(&r[k])).collect();
for x in r[0]..=r[2] {
for z in r[1]..=r[3] {
e.sim.world_packet(&F::chunk(x, z)).unwrap();
}
}
}
F::fill_world(&mut e, &sc, &filter);
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()
}));
F::set_player(&mut e, &sc, &ticks[0]);
e.core.ready = true;
e.outbound().clear();
let t0 = Instant::now();
let mut teleport_id = 0;
for (k, rec) in ticks.iter().enumerate().skip(1) {
let input = &rec["input"];
let mut leave = false;
for ev in input["events"].as_array().into_iter().flatten() {
match ev["type"].as_str().unwrap() {
"teleport" => {
teleport_id += 1;
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"]),
teleport_id: F::TELEPORT_IDS.then_some(teleport_id),
..Default::default()
}));
}
"leave_bed" => leave = true,
_ => feed::<F>(&mut e, &filter, &F::packet(ev)),
}
}
let keys = input["keys"].as_str().unwrap();
let has = |k: &str| keys.split(',').any(|n| n == k);
let mut b = Keys {
controls: Controls {
forward: has("forward"),
back: has("back"),
left: has("left"),
right: has("right"),
jump: has("jump"),
sneak: has("sneak"),
sprint: has("sprint"),
},
leave,
};
let sleep = &rec["sleep"];
let asleep = sleep["sleeping"].as_bool().unwrap();
if !asleep {
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();
let st = &rec["state"];
let (p, bb, vel, yaw, pitch) = F::state(&e.sim);
let want_p = [0, 1, 2].map(|j| f64v(&st["pos"][j]));
let want_bb = [0, 1, 2, 3, 4, 5].map(|j| f64v(&st["bb"][j]));
let want_v = [0, 1, 2].map(|j| f64v(&st["vel"][j]));
let want_look = (f32v(&st["yaw"]), f32v(&st["pitch"]));
let eye = f64::from(f32v(&sleep["eye_height"]));
let mut diffs = Vec::new();
if got != want {
diffs.push(format!("packets {got:?} want {want:?}"));
}
if p != want_p {
diffs.push(format!("pos {p:?} want {want_p:?}"));
}
if bb != want_bb {
diffs.push(format!("box {bb:?} want {want_bb:?}"));
}
if vel != want_v {
diffs.push(format!("vel {vel:?} want {want_v:?}"));
}
if (yaw, pitch) != want_look {
diffs.push(format!("look {:?} want {want_look:?}", (yaw, pitch)));
}
if e.core.sleeping.is_some() != asleep {
diffs.push(format!("sleeping {:?} want {asleep}", e.core.sleeping));
}
if asleep {
let timer = i(&sleep["timer"]);
if i32::from(e.core.sleep_ticks) != timer {
diffs.push(format!("timer {} want {timer}", e.core.sleep_ticks));
}
if e.sim.eye_height() != Some(eye) {
diffs.push(format!("eye height {:?} want {eye}", e.sim.eye_height()));
}
} else if e.sim.eye_height().is_some_and(|h| h != eye) {
diffs.push(format!("eye height {:?} want {eye}", e.sim.eye_height()));
}
if !diffs.is_empty() {
failed.push(format!("{name} tick {k}: {}", diffs.join("; ")));
break;
}
ticks_done += 1;
}
}
eprintln!(
"{path}: {cases} cases, {ticks_done} ticks identical, {} cases differ",
failed.len()
);
(cases, ticks_done, failed)
}
fn check<F: Fixture>(version: &str) {
let path = format!(
"{}/../../tests/golden/{version}/sleep.jsonl.gz",
env!("CARGO_MANIFEST_DIR")
);
let (cases, ticks, failed) = replay::<F>(&path);
assert!(
failed.is_empty(),
"{} of {cases} cases differ:\n{}",
failed.len(),
failed.join("\n")
);
assert!(cases >= 10 && ticks > 300, "{cases} cases, {ticks} ticks");
}
struct F18;
impl Fixture for F18 {
type V = crate::version::V1_8;
type S = crate::sim::Sim18;
const TELEPORT_IDS: bool = false;
fn sim() -> Self::S {
crate::sim::Sim18::new()
}
fn login() -> 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),
})
}
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 st = ghast_data::v1_8::BlockState::from_raw_vanilla(
((i(&fill[6]) as u16) << 4) | (i(&fill[7]) as u16 & 15),
);
s.test_set_block(x, y, z, st);
}
fn set_player(e: &mut Engine<Self::S>, sc: &Value, t0: &Value) {
let p = crate::phys_golden::player_of(sc, t0);
let mut pose = e.core.pose;
e.sim.test_set_player(&mut pose, p);
e.core.pose = pose;
}
fn packet(ev: &Value) -> RawPacket {
use ghast_protocol::v1_8::play::clientbound as cb;
match ev["type"].as_str().unwrap() {
"bed" => RawPacket::from_packet(&cb::Bed {
entity_id: ME,
location: pos(&ev["pos"]),
}),
"wake" => RawPacket::from_packet(&cb::Animation {
entity_id: ME,
animation: 2,
}),
"block" => RawPacket::from_packet(&cb::BlockChange {
location: pos(&ev["pos"]),
r#type: i(&ev["id"]) << 4 | i(&ev["meta"]),
}),
"velocity" => RawPacket::from_packet(&cb::EntityVelocity {
entity_id: ME,
velocity: ghast_protocol::v1_8::types::Vec3i16 {
x: i(&ev["x"]) as i16,
y: i(&ev["y"]) as i16,
z: i(&ev["z"]) as i16,
},
}),
other => panic!("event {other}"),
}
.unwrap()
}
fn state(s: &Self::S) -> ([f64; 3], [f64; 6], [f64; 3], f32, f32) {
let p = s.test_player();
let b = p.bb;
(
p.pos,
[b.min_x, b.min_y, b.min_z, b.max_x, b.max_y, b.max_z],
p.vel,
p.yaw,
p.pitch,
)
}
}
struct F112;
impl Fixture for F112 {
type V = crate::version::V1_12_2;
type S = crate::sim::Sim12;
fn sim() -> Self::S {
crate::sim::Sim12::new()
}
fn login() -> 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),
})
}
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 st = ghast_data::v1_12::BlockState::from_raw_vanilla(
((i(&fill[6]) as u16) << 4) | (i(&fill[7]) as u16 & 15),
);
s.test_set_block(x, y, z, st);
}
fn set_player(e: &mut Engine<Self::S>, sc: &Value, t0: &Value) {
let mut p = crate::phys_golden::v112::player_of(sc, t0);
p.added_to_chunk = true;
e.sim.test_set_player(p);
e.core.pose.pos = Vec3::new(p.pos[0], p.bb.min_y, p.pos[2]);
e.core.pose.yaw = p.yaw;
e.core.pose.pitch = p.pitch;
}
fn packet(ev: &Value) -> RawPacket {
use ghast_protocol::v1_12_2::play::clientbound as cb;
match ev["type"].as_str().unwrap() {
"bed" => RawPacket::from_packet(&cb::Bed {
entity_id: ME,
location: pos(&ev["pos"]),
}),
"wake" => RawPacket::from_packet(&cb::Animation {
entity_id: ME,
animation: 2,
}),
"block" => RawPacket::from_packet(&cb::BlockChange {
location: pos(&ev["pos"]),
r#type: i(&ev["id"]) << 4 | i(&ev["meta"]),
}),
"velocity" => RawPacket::from_packet(&cb::EntityVelocity {
entity_id: ME,
velocity: ghast_protocol::v1_12_2::types::Vec3i16 {
x: i(&ev["x"]) as i16,
y: i(&ev["y"]) as i16,
z: i(&ev["z"]) as i16,
},
}),
other => panic!("event {other}"),
}
.unwrap()
}
fn state(s: &Self::S) -> ([f64; 3], [f64; 6], [f64; 3], f32, f32) {
let p = s.test_player();
let b = p.bb;
(
p.pos,
[b.min_x, b.min_y, b.min_z, b.max_x, b.max_y, b.max_z],
p.vel,
p.yaw,
p.pitch,
)
}
}
#[test]
fn sleep_matches_the_oracle_1_12_2() {
check::<F112>("1.12.2");
}
fn sleep_data(
id: i32,
pos_index: u8,
pos_type: i32,
pose_type: i32,
bed: Option<ghast_protocol::BlockPos>,
) -> RawPacket {
use bytes::BufMut;
use ghast_protocol::codec::McWrite;
let mut b = bytes::BytesMut::new();
b.put_varint(ME);
b.put_u8(6);
b.put_varint(pose_type);
b.put_varint(if bed.is_some() { 2 } else { 0 });
b.put_u8(pos_index);
b.put_varint(pos_type);
match bed {
Some(p) => {
b.put_u8(1);
let x = (i64::from(p.x) & 0x3ff_ffff) << 38;
let z = (i64::from(p.z) & 0x3ff_ffff) << 12;
b.put_i64(x | z | (i64::from(p.y) & 0xfff));
}
None => b.put_u8(0),
}
b.put_u8(0xff);
RawPacket::new(id, b.freeze())
}
struct F116;
impl Fixture for F116 {
type V = crate::version::V1_16_5;
type S = crate::sim::Sim16;
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(i(&fill[6]) as u16).unwrap();
s.test_set_block(x, y, z, st);
}
fn set_player(e: &mut Engine<Self::S>, sc: &Value, t0: &Value) {
let p = crate::phys_golden::v116::player_of(sc, t0);
e.sim.test_set_player(p);
e.core.pose.pos = Vec3::new(p.pos[0], p.pos[1], p.pos[2]);
e.core.pose.yaw = p.yaw;
e.core.pose.pitch = p.pitch;
}
fn packet(ev: &Value) -> RawPacket {
use ghast_protocol::v1_16_5::play::clientbound as cb;
match ev["type"].as_str().unwrap() {
"bed" => sleep_data(cb::id::ENTITY_METADATA, 13, 10, 18, Some(pos(&ev["pos"]))),
"wake" => sleep_data(cb::id::ENTITY_METADATA, 13, 10, 18, None),
"block" => RawPacket::from_packet(&cb::BlockChange {
location: pos(&ev["pos"]),
r#type: i(&ev["state"]),
})
.unwrap(),
"velocity" => RawPacket::from_packet(&cb::EntityVelocity {
entity_id: ME,
velocity: ghast_protocol::v1_16_5::types::Vec3i16 {
x: i(&ev["x"]) as i16,
y: i(&ev["y"]) as i16,
z: i(&ev["z"]) as i16,
},
})
.unwrap(),
other => panic!("event {other}"),
}
}
fn state(s: &Self::S) -> ([f64; 3], [f64; 6], [f64; 3], f32, f32) {
let p = s.test_player();
let b = p.bb;
(
p.pos,
[b.min_x, b.min_y, b.min_z, b.max_x, b.max_y, b.max_z],
p.vel,
p.yaw,
p.pitch,
)
}
}
#[test]
fn sleep_matches_the_oracle_1_16_5() {
check::<F116>("1.16.5");
}
macro_rules! modern_fixture {
($f:ident, $v:ty, $s:ty, $proto:ident, $data:ident, $chunk:ident) => {
struct $f;
impl Fixture for $f {
type V = $v;
type S = $s;
fn sim() -> Self::S {
<$s>::test_overworld()
}
fn chunk(x: i32, z: i32) -> RawPacket {
crate::sim::test_chunks::$chunk(x, z)
}
fn set_block(_: &mut Self::S, _: i32, _: i32, _: i32, _: &Value) {
unreachable!("26.x blocks arrive as block updates")
}
fn set_player(e: &mut Engine<Self::S>, sc: &Value, t0: &Value) {
let p = crate::phys_golden::v261::player_of(sc, t0);
e.sim
.test_set_modern(p, crate::phys_golden::v261::ext_of(sc, t0));
e.core.pose.pos = Vec3::new(p.pos[0], p.pos[1], p.pos[2]);
e.core.pose.yaw = p.yaw;
e.core.pose.pitch = p.pitch;
e.core.level_load_started = true;
e.core.client_loaded = true;
}
fn packet(ev: &Value) -> RawPacket {
use ghast_protocol::$proto::play::clientbound as cb;
match ev["type"].as_str().unwrap() {
"bed" => sleep_data(cb::id::ENTITY_METADATA, 14, 11, 20, Some(pos(&ev["pos"]))),
"wake" => sleep_data(cb::id::ENTITY_METADATA, 14, 11, 20, None),
"block" => RawPacket::from_packet(&cb::BlockChange {
location: pos(&ev["pos"]),
r#type: i(&ev["state"]),
})
.unwrap(),
"velocity" => RawPacket::from_packet(&cb::EntityVelocity {
entity_id: ME,
velocity: ghast_protocol::types::LpVec3::from_vec3(
["x", "y", "z"].map(|k| f64::from(i(&ev[k])) / 8000.0),
),
})
.unwrap(),
other => panic!("event {other}"),
}
}
fn state(s: &Self::S) -> ([f64; 3], [f64; 6], [f64; 3], f32, f32) {
let p = s.modern_player().unwrap();
let b = p.bb;
(
p.pos,
[b.min_x, b.min_y, b.min_z, b.max_x, b.max_y, b.max_z],
p.vel,
p.yaw,
p.pitch,
)
}
fn fill_world(e: &mut Engine<Self::S>, sc: &Value, filter: &PacketFilter) {
for fill in sc["fills"].as_array().unwrap() {
let v: Vec<i32> = (0..7).map(|k| i(&fill[k])).collect();
let state = sc["states"][v[6].to_string()].as_str().unwrap();
if state == "minecraft:stone" && v[1] == 63 && v[4] == 63 {
continue;
}
let id = ghast_data::$data::BlockState::parse(
state.strip_prefix("minecraft:").unwrap_or(state),
)
.or_else(|| ghast_data::$data::BlockState::parse(state))
.unwrap()
.id();
for x in v[0]..=v[3] {
for y in v[1]..=v[4] {
for z in v[2]..=v[5] {
let ev = serde_json::json!({
"type": "block", "pos": [x, y, z], "state": id
});
feed::<Self>(e, filter, &Self::packet(&ev));
}
}
}
}
}
}
};
}
modern_fixture!(
F261,
crate::version::V26_1,
crate::sim::Sim26,
v26_1,
v26_1,
v26_1
);
modern_fixture!(
F262,
crate::version::V26_2,
crate::sim::Sim262,
v26_2,
v26_2,
v26_2
);
modern_fixture!(
F263,
crate::version::V26_3,
crate::sim::Sim263,
v26_3,
v26_3,
v26_3
);
#[test]
fn sleep_matches_the_oracle_26_1() {
check::<F261>("26.1");
}
#[test]
fn sleep_matches_the_oracle_26_2() {
check::<F262>("26.2");
}
#[test]
fn sleep_matches_the_oracle_26_3() {
check::<F263>("26.3");
}
#[test]
fn sleep_matches_the_oracle_1_8_9() {
check::<F18>("1.8.9");
}