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;
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 varint(b: &mut Vec<u8>, v: i32) {
let mut u = v as u32;
loop {
let x = (u & 0x7f) as u8;
u >>= 7;
if u == 0 {
b.push(x);
return;
}
b.push(x | 0x80);
}
}
fn position(b: &mut Vec<u8>, p: &Value) {
let c = |k: usize| p[k].as_i64().unwrap();
let v = ((c(0) & 0x3FF_FFFF) << 38) | ((c(1) & 0xFFF) << 26) | (c(2) & 0x3FF_FFFF);
b.extend_from_slice(&v.to_be_bytes());
}
fn packet(ev: &Value) -> RawPacket {
let mut b = Vec::new();
let n = |k: &str| ev[k].as_i64().unwrap() as i32;
let id = match ev["type"].as_str().unwrap() {
"block_action" => {
position(&mut b, &ev["pos"]);
b.push(n("action") as u8);
b.push(n("data") as u8);
varint(&mut b, n("block"));
cb::id::BLOCK_ACTION
}
"block_change" => {
position(&mut b, &ev["pos"]);
varint(&mut b, n("raw"));
cb::id::BLOCK_CHANGE
}
other => panic!("event {other}"),
};
RawPacket {
id,
body: bytes::Bytes::from(b),
}
}
fn login_packet() -> RawPacket {
let mut b = Vec::new();
b.extend_from_slice(&1i32.to_be_bytes());
b.extend_from_slice(&[0, 0, 1, 20]);
varint(&mut b, 4);
b.extend_from_slice(b"flat");
b.push(0);
RawPacket {
id: cb::id::LOGIN,
body: bytes::Bytes::from(b),
}
}
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::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::StartFallFlying => "start_fall_flying",
}
]),
_ => 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]),
"entity_action" => serde_json::json!(["entity_action", p["action_name"]]),
_ => return None,
})
}
struct Keys(Controls);
impl Behavior for Keys {
fn name(&self) -> &str {
"pistons-replay-1.8"
}
fn tick(&mut self, ctx: &mut TickContext<'_>) {
ctx.set_controls(self.0);
}
}
fn snapshot(w: &ghast_world::v1_8::World, r: &[i32]) -> Vec<u16> {
let mut v = Vec::new();
for x in r[0]..=r[3] {
for y in r[1]..=r[4] {
for z in r[2]..=r[5] {
v.push(w.block_state(x, y, z).map_or(0, |s| s.raw()));
}
}
}
v
}
fn replay_file(path: &std::path::Path) -> (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 watch: Vec<i32> = setup["ext"]["pistons"]["watch"]
.as_array()
.unwrap()
.iter()
.map(|v| v.as_i64().unwrap() as i32)
.collect();
let mut e = Engine::new(opts(GameVersion::V1_8_9), Sim18::new());
e.handle(Inbound::JoinGame(JoinGame {
entity_id: 1,
game_mode: if setup["game_mode"] == "spectator" {
GameMode::Spectator
} else {
GameMode::Survival
},
dimension: "0".into(),
hardcore: false,
dimension_nbt: None,
respawn_screen: 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.core.ready = true;
e.outbound().clear();
let mut prev = snapshot(e.sim.test_world(), &watch);
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() {
e.sim.world_packet(&packet(ev)).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);
if e.sim.piston_uncertain() {
eprintln!("{name}: ends at tick {k} (flagged piston_uncertain)");
break;
}
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 now = snapshot(e.sim.test_world(), &watch);
let mut changes = Vec::new();
let mut i = 0;
for x in watch[0]..=watch[3] {
for y in watch[1]..=watch[4] {
for z in watch[2]..=watch[5] {
if now[i] != prev[i] {
changes.push(serde_json::json!([x, y, z, now[i]]));
}
i += 1;
}
}
}
prev = now;
if Value::Array(changes.clone()) != rec["pistons"]["changes"] {
failed.push(format!(
"{name} tick {k}: world changes {changes:?} want {}",
rec["pistons"]["changes"]
));
break;
}
ticks_done += 1;
}
}
eprintln!(
"1.8.9 {} through the engine: {cases} cases, {ticks_done} ticks, {} cases differ",
path.display(),
failed.len()
);
(cases, ticks_done, failed)
}
#[test]
fn pistons_match_the_oracle_1_8_9() {
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../tests/golden/1.8.9/pistons.jsonl.gz");
let (cases, ticks, failed) = replay_file(&path);
assert!(
failed.is_empty(),
"{} cases differ:\n{}",
failed.len(),
failed.join("\n")
);
assert!(cases >= 146 && ticks > 5000, "{cases} cases, {ticks} ticks");
}
#[test]
#[ignore = "needs the oracle cache"]
fn pistons_cache_match_the_oracle_1_8_9() {
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../oracle/cache/1.8.9/fuzz-pistons");
let mut files: Vec<_> = std::fs::read_dir(&dir)
.expect("oracle/cache/1.8.9/fuzz-pistons")
.map(|e| e.unwrap().path())
.filter(|p| p.extension().is_some_and(|x| x == "gz"))
.collect();
files.sort();
let (mut cases, mut ticks) = (0, 0);
let mut failed = Vec::new();
for f in &files {
let (c, t, mut fl) = replay_file(f);
cases += c;
ticks += t;
failed.append(&mut fl);
}
eprintln!(
"piston cache: {cases} cases, {ticks} ticks, {} differ",
failed.len()
);
assert!(failed.is_empty(), "{}", failed.join("\n"));
assert!(cases > 0);
}
#[cfg(feature = "v26_1")]
mod v1_12 {
use super::super::tests::opts;
use super::super::*;
use crate::common::{EntityAction, JoinGame};
use crate::phys_golden::v112 as golden;
use crate::sim::Sim12;
use ghast_protocol::RawPacket;
use ghast_protocol::v1_12_2::play::clientbound as cb;
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 varint(b: &mut Vec<u8>, v: i32) {
let mut u = v as u32;
loop {
let x = (u & 0x7f) as u8;
u >>= 7;
if u == 0 {
b.push(x);
return;
}
b.push(x | 0x80);
}
}
fn position(b: &mut Vec<u8>, p: &Value) {
let c = |k: usize| p[k].as_i64().unwrap();
let v = ((c(0) & 0x3FF_FFFF) << 38) | ((c(1) & 0xFFF) << 26) | (c(2) & 0x3FF_FFFF);
b.extend_from_slice(&v.to_be_bytes());
}
fn packet(ev: &Value) -> RawPacket {
let mut b = Vec::new();
let n = |k: &str| ev[k].as_i64().unwrap() as i32;
let id = match ev["type"].as_str().unwrap() {
"block_action" => {
position(&mut b, &ev["pos"]);
b.push(n("action") as u8);
b.push(n("data") as u8);
varint(&mut b, n("block"));
cb::id::BLOCK_ACTION
}
"block_change" => {
position(&mut b, &ev["pos"]);
varint(&mut b, n("raw"));
cb::id::BLOCK_CHANGE
}
"world_time" => {
let t = ev["time"].as_i64().unwrap();
b.extend_from_slice(&t.to_be_bytes());
b.extend_from_slice(&t.to_be_bytes());
cb::id::UPDATE_TIME
}
other => panic!("event {other}"),
};
RawPacket {
id,
body: bytes::Bytes::from(b),
}
}
fn login_packet() -> RawPacket {
let mut b = Vec::new();
b.extend_from_slice(&1i32.to_be_bytes());
b.push(0);
b.extend_from_slice(&0i32.to_be_bytes());
b.extend_from_slice(&[1, 20]);
varint(&mut b, 4);
b.extend_from_slice(b"flat");
b.push(0);
RawPacket {
id: cb::id::LOGIN,
body: bytes::Bytes::from(b),
}
}
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::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::StartFallFlying => "start_fall_flying",
}
]),
_ => 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]),
"entity_action" => serde_json::json!(["entity_action", p["action_name"]]),
_ => return None,
})
}
struct Keys(Controls);
impl Behavior for Keys {
fn name(&self) -> &str {
"pistons-replay-1.12"
}
fn tick(&mut self, ctx: &mut TickContext<'_>) {
ctx.set_controls(self.0);
}
}
fn snapshot(w: &ghast_world::v1_12::World, r: &[i32]) -> Vec<u16> {
let mut v = Vec::new();
for x in r[0]..=r[3] {
for y in r[1]..=r[4] {
for z in r[2]..=r[5] {
v.push(w.block_state(x, y, z).map_or(0, |s| s.raw()));
}
}
}
v
}
fn replay_file(path: &std::path::Path) -> (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);
}
let setup = &sc["setup"];
if setup
.get("entities")
.is_some_and(|e| !e.as_array().unwrap().is_empty())
{
continue;
}
cases += 1;
let watch: Vec<i32> = setup["ext"]["pistons"]["watch"]
.as_array()
.unwrap()
.iter()
.map(|v| v.as_i64().unwrap() as i32)
.collect();
let mut e = Engine::new(opts(GameVersion::V1_12_2), Sim12::new());
e.handle(Inbound::JoinGame(JoinGame {
entity_id: 1,
game_mode: if setup["game_mode"] == "spectator" {
GameMode::Spectator
} else {
GameMode::Survival
},
dimension: "0".into(),
hardcore: false,
dimension_nbt: None,
respawn_screen: 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_12_2(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_12::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 mut p = golden::player_of(&sc, &ticks[0]);
p.added_to_chunk = true;
e.sim.test_set_player(p);
e.core.ready = true;
e.outbound().clear();
let mut prev = snapshot(e.sim.test_world(), &watch);
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() {
e.sim.world_packet(&packet(ev)).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 now = snapshot(e.sim.test_world(), &watch);
let mut changes = Vec::new();
let mut i = 0;
for x in watch[0]..=watch[3] {
for y in watch[1]..=watch[4] {
for z in watch[2]..=watch[5] {
if now[i] != prev[i] {
changes.push(serde_json::json!([x, y, z, now[i]]));
}
i += 1;
}
}
}
prev = now;
if Value::Array(changes.clone()) != rec["pistons"]["changes"] {
failed.push(format!(
"{name} tick {k}: world changes {changes:?} want {}",
rec["pistons"]["changes"]
));
break;
}
ticks_done += 1;
}
}
eprintln!(
"1.12.2 {} through the engine: {cases} cases, {ticks_done} ticks, {} cases differ",
path.display(),
failed.len()
);
(cases, ticks_done, failed)
}
#[test]
fn pistons_match_the_oracle_1_12_2() {
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../tests/golden/1.12.2/pistons.jsonl.gz");
let (cases, ticks, failed) = replay_file(&path);
assert!(
failed.is_empty(),
"{} cases differ:\n{}",
failed.len(),
failed.join("\n")
);
assert!(cases >= 80 && ticks > 4000, "{cases} cases, {ticks} ticks");
}
#[test]
#[ignore = "needs the oracle cache"]
fn pistons_cache_match_the_oracle_1_12_2() {
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../oracle/cache/1.12.2/fuzz-pistons");
let mut files: Vec<_> = std::fs::read_dir(&dir)
.expect("oracle/cache/1.12.2/fuzz-pistons")
.map(|e| e.unwrap().path())
.filter(|p| p.extension().is_some_and(|x| x == "gz"))
.collect();
files.sort();
let (mut cases, mut ticks) = (0, 0);
let mut failed = Vec::new();
for f in &files {
let (c, t, mut fl) = replay_file(f);
cases += c;
ticks += t;
failed.append(&mut fl);
}
eprintln!(
"piston cache: {cases} cases, {ticks} ticks, {} differ",
failed.len()
);
assert!(failed.is_empty(), "{}", failed.join("\n"));
assert!(cases > 0);
}
}
#[cfg(feature = "v26_1")]
mod v1_16 {
use super::super::tests::opts;
use super::super::*;
use crate::common::{EntityAction, JoinGame};
use crate::phys_golden::v116 as golden;
use crate::sim::Sim16;
use ghast_protocol::RawPacket;
use ghast_protocol::v1_16_5::play::clientbound as cb;
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 varint(b: &mut Vec<u8>, v: i32) {
let mut u = v as u32;
loop {
let x = (u & 0x7f) as u8;
u >>= 7;
if u == 0 {
b.push(x);
return;
}
b.push(x | 0x80);
}
}
fn position(b: &mut Vec<u8>, p: &Value) {
let c = |k: usize| p[k].as_i64().unwrap();
let v = ((c(0) & 0x3FF_FFFF) << 38) | ((c(2) & 0x3FF_FFFF) << 12) | (c(1) & 0xFFF);
b.extend_from_slice(&v.to_be_bytes());
}
fn packet(ev: &Value) -> RawPacket {
let mut b = Vec::new();
let n = |k: &str| ev[k].as_i64().unwrap() as i32;
let id = match ev["type"].as_str().unwrap() {
"block_action" => {
position(&mut b, &ev["pos"]);
b.push(n("action") as u8);
b.push(n("data") as u8);
varint(&mut b, n("block"));
cb::id::BLOCK_ACTION
}
"block_change" => {
position(&mut b, &ev["pos"]);
varint(&mut b, n("raw"));
cb::id::BLOCK_CHANGE
}
"world_time" => {
let t = ev["time"].as_i64().unwrap();
b.extend_from_slice(&t.to_be_bytes());
b.extend_from_slice(&t.to_be_bytes());
cb::id::UPDATE_TIME
}
other => panic!("event {other}"),
};
RawPacket {
id,
body: bytes::Bytes::from(b),
}
}
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::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::StartFallFlying => "start_fall_flying",
}
]),
_ => 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]),
"entity_action" => serde_json::json!([
"entity_action",
match p["action_name"].as_str().unwrap() {
"press_shift_key" => "start_sneaking",
"release_shift_key" => "stop_sneaking",
n => n,
}
]),
_ => return None,
})
}
struct Keys(Controls);
impl Behavior for Keys {
fn name(&self) -> &str {
"pistons-replay-1.16"
}
fn tick(&mut self, ctx: &mut TickContext<'_>) {
ctx.set_controls(self.0);
}
}
fn snapshot(w: &ghast_world::v1_16_5::World, r: &[i32]) -> Vec<u16> {
let mut v = Vec::new();
for x in r[0]..=r[3] {
for y in r[1]..=r[4] {
for z in r[2]..=r[5] {
v.push(w.block_state(x, y, z).map_or(0, |s| s.id()));
}
}
}
v
}
fn replay_file(path: &std::path::Path) -> (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);
}
let setup = &sc["setup"];
if setup["ext"]["entities"]
.as_array()
.is_some_and(|e| !e.is_empty())
{
continue;
}
cases += 1;
let watch: Vec<i32> = setup["ext"]["pistons"]["watch"]
.as_array()
.unwrap()
.iter()
.map(|v| v.as_i64().unwrap() as i32)
.collect();
let mut e = Engine::new(opts(GameVersion::V1_16_5), Sim16::new());
e.handle(Inbound::JoinGame(JoinGame {
entity_id: 1,
game_mode: if setup["game_mode"] == "spectator" {
GameMode::Spectator
} else {
GameMode::Survival
},
dimension: "0".into(),
hardcore: false,
dimension_nbt: None,
respawn_screen: true,
}));
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_16_5(x, z))
.unwrap();
}
}
}
for fill in sc["fills"].as_array().unwrap() {
let v: Vec<i64> = (0..7).map(|k| fill[k].as_i64().unwrap()).collect();
let st = ghast_data::v1_16_5::BlockState::from_id(v[6] as u16).unwrap();
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]);
e.sim.test_set_player(p);
e.core.ready = true;
e.outbound().clear();
let mut prev = snapshot(e.sim.test_world(), &watch);
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() {
e.sim.world_packet(&packet(ev)).unwrap();
}
if e.sim.piston_uncertain() {
eprintln!("{name}: ends at tick {k} (flagged piston_uncertain)");
break;
}
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);
if e.sim.piston_uncertain() {
eprintln!("{name}: ends at tick {k} (flagged piston_uncertain)");
break;
}
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 now = snapshot(e.sim.test_world(), &watch);
let mut changes = Vec::new();
let mut i = 0;
for x in watch[0]..=watch[3] {
for y in watch[1]..=watch[4] {
for z in watch[2]..=watch[5] {
if now[i] != prev[i] {
changes.push(serde_json::json!([x, y, z, now[i]]));
}
i += 1;
}
}
}
prev = now;
if Value::Array(changes.clone()) != rec["pistons"]["changes"] {
failed.push(format!(
"{name} tick {k}: world changes {changes:?} want {}",
rec["pistons"]["changes"]
));
break;
}
ticks_done += 1;
}
}
eprintln!(
"1.16.5 {} through the engine: {cases} cases, {ticks_done} ticks, {} cases differ",
path.display(),
failed.len()
);
(cases, ticks_done, failed)
}
#[test]
fn pistons_match_the_oracle_1_16_5() {
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../tests/golden/1.16.5/pistons.jsonl.gz");
let (cases, ticks, failed) = replay_file(&path);
assert!(
failed.is_empty(),
"{} cases differ:\n{}",
failed.len(),
failed.join("\n")
);
assert!(cases >= 80 && ticks > 4000, "{cases} cases, {ticks} ticks");
}
#[test]
#[ignore = "needs the oracle cache"]
fn pistons_cache_match_the_oracle_1_16_5() {
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../oracle/cache/1.16.5/fuzz-pistons");
let mut files: Vec<_> = std::fs::read_dir(&dir)
.expect("oracle/cache/1.16.5/fuzz-pistons")
.map(|e| e.unwrap().path())
.filter(|p| p.extension().is_some_and(|x| x == "gz"))
.collect();
files.sort();
let (mut cases, mut ticks) = (0, 0);
let mut failed = Vec::new();
for f in &files {
let (c, t, mut fl) = replay_file(f);
cases += c;
ticks += t;
failed.append(&mut fl);
}
eprintln!(
"piston cache: {cases} cases, {ticks} ticks, {} differ",
failed.len()
);
assert!(failed.is_empty(), "{}", failed.join("\n"));
assert!(cases > 0);
}
}