use super::tests::{Script, engine, join, names};
use super::*;
use crate::sign::{SignCloseReason, SignEditor, SignError, SignEvent};
use crate::version::ClientVersion;
use ghast_protocol::frame::{FrameDecoder, FrameEncoder};
use ghast_protocol::{BlockPos, RawPacket};
fn versions() -> Vec<GameVersion> {
let mut v = vec![
GameVersion::V1_8_9,
GameVersion::V1_12_2,
GameVersion::V1_16_5,
GameVersion::V26_1,
GameVersion::V26_2,
];
#[cfg(feature = "v26_3")]
v.push(GameVersion::V26_3);
v
}
const SIGN: BlockPos = BlockPos::new(9, 64, 9);
fn raw<P: ghast_protocol::Packet>(p: &P) -> RawPacket {
RawPacket::from_packet(p).unwrap()
}
fn open_packet(v: GameVersion, pos: BlockPos, front: bool) -> RawPacket {
match v {
GameVersion::V1_8_9 => {
raw(&ghast_protocol::v1_8::play::clientbound::OpenSignEntity { location: pos })
}
GameVersion::V1_12_2 => {
raw(&ghast_protocol::v1_12_2::play::clientbound::OpenSignEntity { location: pos })
}
GameVersion::V1_16_5 => {
raw(&ghast_protocol::v1_16_5::play::clientbound::OpenSignEntity { location: pos })
}
GameVersion::V26_1 => raw(&ghast_protocol::v26_1::play::clientbound::OpenSignEntity {
location: pos,
is_front_text: front,
}),
#[cfg(feature = "v26_3")]
GameVersion::V26_3 => {
use ghast_protocol::v26_3::play::clientbound as cb;
raw(&cb::OpenSignEntity {
location: pos,
side: if front {
cb::OpenSignEntitySide::FRONT
} else {
cb::OpenSignEntitySide::BACK
},
})
}
_ => raw(&ghast_protocol::v26_2::play::clientbound::OpenSignEntity {
location: pos,
is_front_text: front,
}),
}
}
fn feed(e: &mut Engine<Box<dyn Sim>>, raw: &RawPacket) {
let v = e.core.opts.caps.version;
let i = Interests::default();
let (pass, p) = match v {
GameVersion::V1_8_9 => (
crate::version::V1_8::play_filter(i).contains(raw.id),
crate::version::V1_8::decode_play(raw, &mut ()),
),
GameVersion::V1_12_2 => (
crate::version::V1_12_2::play_filter(i).contains(raw.id),
crate::version::V1_12_2::decode_play(raw, &mut Default::default()),
),
GameVersion::V1_16_5 => (
crate::version::V1_16_5::play_filter(i).contains(raw.id),
crate::version::V1_16_5::decode_play(raw, &mut ()),
),
GameVersion::V26_1 => (
crate::version::V26_1::play_filter(i).contains(raw.id),
crate::version::V26_1::decode_play(raw, &mut Default::default()),
),
#[cfg(feature = "v26_3")]
GameVersion::V26_3 => (
crate::version::V26_3::play_filter(i).contains(raw.id),
crate::version::V26_3::decode_play(raw, &mut Default::default()),
),
_ => (
crate::version::V26_2::play_filter(i).contains(raw.id),
crate::version::V26_2::decode_play(raw, &mut Default::default()),
),
};
assert!(pass, "{v:?}: packet {} filtered", raw.id);
if let Some(p) = p.unwrap() {
e.handle(p);
}
}
fn put_block(e: &mut Engine<Box<dyn Sim>>, pos: BlockPos, sign: bool) {
let v = e.core.opts.caps.version;
let raw = match v {
GameVersion::V1_8_9 => raw(&ghast_protocol::v1_8::play::clientbound::BlockChange {
location: pos,
r#type: if sign { 63 << 4 } else { 1 << 4 },
}),
GameVersion::V1_12_2 => raw(&ghast_protocol::v1_12_2::play::clientbound::BlockChange {
location: pos,
r#type: if sign { 63 << 4 } else { 1 << 4 },
}),
GameVersion::V1_16_5 => {
let b = ghast_data::v1_16_5::Block::from_name(if sign { "oak_sign" } else { "stone" })
.unwrap();
raw(&ghast_protocol::v1_16_5::play::clientbound::BlockChange {
location: pos,
r#type: i32::from(b.default_state().id()),
})
}
_ => {
let name = if sign { "oak_sign" } else { "stone" };
let id = match v {
GameVersion::V26_1 => ghast_data::v26_1::Block::from_name(name)
.unwrap()
.default_state()
.id(),
#[cfg(feature = "v26_3")]
GameVersion::V26_3 => ghast_data::v26_3::Block::from_name(name)
.unwrap()
.default_state()
.id(),
_ => ghast_data::v26_2::Block::from_name(name)
.unwrap()
.default_state()
.id(),
};
raw(&ghast_protocol::v26_1::play::clientbound::BlockChange {
location: pos,
r#type: i32::from(id),
})
}
};
e.sim.world_packet(&raw).unwrap();
}
fn written<V: ClientVersion>(o: &Outbound) -> RawPacket
where
V::Wire: Default,
{
let mut enc = FrameEncoder::new();
V::write_play(&mut enc, o, &mut V::Wire::default()).unwrap();
let mut dec = FrameDecoder::new();
dec.push(&enc.take());
dec.next_packet().unwrap().unwrap()
}
fn sign_bytes(v: GameVersion, o: &Outbound) -> (BlockPos, Option<bool>, [String; 4]) {
let s = |b: &ghast_protocol::types::ByteString| b.to_string();
match v {
GameVersion::V1_8_9 => {
let p: ghast_protocol::v1_8::play::serverbound::UpdateSign =
written::<crate::version::V1_8>(o).decode_as().unwrap();
(
p.location,
None,
[s(&p.text1), s(&p.text2), s(&p.text3), s(&p.text4)],
)
}
GameVersion::V1_12_2 => {
let p: ghast_protocol::v1_12_2::play::serverbound::UpdateSign =
written::<crate::version::V1_12_2>(o).decode_as().unwrap();
(
p.location,
None,
[s(&p.text1), s(&p.text2), s(&p.text3), s(&p.text4)],
)
}
GameVersion::V1_16_5 => {
let p: ghast_protocol::v1_16_5::play::serverbound::UpdateSign =
written::<crate::version::V1_16_5>(o).decode_as().unwrap();
(
p.location,
None,
[s(&p.text1), s(&p.text2), s(&p.text3), s(&p.text4)],
)
}
GameVersion::V26_1 => {
let p: ghast_protocol::v26_1::play::serverbound::UpdateSign =
written::<crate::version::V26_1>(o).decode_as().unwrap();
(
p.location,
Some(p.is_front_text),
[s(&p.text1), s(&p.text2), s(&p.text3), s(&p.text4)],
)
}
#[cfg(feature = "v26_3")]
GameVersion::V26_3 => {
use ghast_protocol::v26_3::play::serverbound as sb;
let p: sb::UpdateSign = written::<crate::version::V26_3>(o).decode_as().unwrap();
(
p.location,
Some(p.side == sb::UpdateSignSide::FRONT),
[s(&p.text1), s(&p.text2), s(&p.text3), s(&p.text4)],
)
}
_ => {
let p: ghast_protocol::v26_2::play::serverbound::UpdateSign =
written::<crate::version::V26_2>(o).decode_as().unwrap();
(
p.location,
Some(p.is_front_text),
[s(&p.text1), s(&p.text2), s(&p.text3), s(&p.text4)],
)
}
}
}
fn sign_engine(v: GameVersion) -> Engine<Box<dyn Sim>> {
let mut e = engine(v);
join(&mut e);
e.note_inbound(Instant::now());
for _ in 0..3 {
e.tick(&mut Idle, Instant::now());
}
e.outbound().clear();
e
}
fn modern(v: GameVersion) -> bool {
v.caps().configuration_state
}
#[test]
fn write_sign_every_version() {
for v in versions() {
let mut e = sign_engine(v);
put_block(&mut e, SIGN, true);
let front = !modern(v);
feed(&mut e, &open_packet(v, SIGN, front));
let ed = SignEditor::new(SIGN, front);
let mut seen = (Vec::new(), None, None);
e.note_inbound(Instant::now());
e.tick(
&mut Script(|ctx: &mut TickContext<'_>| {
seen.0 = ctx.events().signs().to_vec();
seen.1 = ctx.sign_editor();
seen.2 = Some(ctx.write_sign(&["Hi§x", "a<b", "", "\u{7f}c\"d"]));
assert_eq!(ctx.close_sign(), Err(SignError::NotOpen));
}),
Instant::now(),
);
assert_eq!(seen.0, vec![SignEvent::Opened(ed)], "{v:?}");
assert_eq!(seen.1, Some(ed), "{v:?}");
assert_eq!(seen.2, Some(Ok(())), "{v:?}");
let out = e.outbound().clone();
let at = |f: fn(&Outbound) -> bool| out.iter().position(f);
let us = at(|o| matches!(o, Outbound::UpdateSign { .. })).expect("update_sign");
if let Some(mv) = at(|o| matches!(o, Outbound::Move(_))) {
assert!(us < mv, "{v:?}: the sign after the movement packet");
} else {
assert_ne!(v, GameVersion::V1_8_9);
}
let n = names(&mut out.clone());
assert_eq!(
n.iter().filter(|x| **x == "update_sign").count(),
1,
"{v:?}"
);
let o = out
.iter()
.find(|o| matches!(o, Outbound::UpdateSign { .. }))
.unwrap();
let (pos, side, lines) = sign_bytes(v, o);
assert_eq!(pos, SIGN, "{v:?}");
assert_eq!(side, modern(v).then_some(ed.front), "{v:?}");
if v == GameVersion::V1_8_9 {
assert_eq!(lines, ["\"Hix\"", "\"a\\u003cb\"", "\"\"", "\"c\\\"d\""]);
} else {
assert_eq!(lines, ["Hix", "a<b", "", "c\"d"].map(String::from), "{v:?}");
}
assert!(e.core.sign.is_none());
}
}
#[test]
fn editor_releases_the_keys() {
for v in versions() {
let mut e = sign_engine(v);
put_block(&mut e, SIGN, true);
feed(&mut e, &open_packet(v, SIGN, true));
let walk = Controls {
forward: true,
..Controls::NONE
};
let before = e.core.pose.pos;
for _ in 0..3 {
e.note_inbound(Instant::now());
e.tick(
&mut Script(|ctx: &mut TickContext<'_>| ctx.set_controls(walk)),
Instant::now(),
);
}
let flat = |p: Vec3| (p.x, p.z);
assert_eq!(
flat(e.core.pose.pos),
flat(before),
"{v:?}: walked with the editor open"
);
e.tick(
&mut Script(|ctx: &mut TickContext<'_>| {
ctx.close_sign().unwrap();
ctx.set_controls(walk);
}),
Instant::now(),
);
e.tick(
&mut Script(|ctx: &mut TickContext<'_>| ctx.set_controls(walk)),
Instant::now(),
);
assert_ne!(
flat(e.core.pose.pos),
flat(before),
"{v:?}: no walk after closing"
);
}
}
#[test]
fn close_and_replace() {
for v in versions() {
let mut e = sign_engine(v);
let other = BlockPos::new(10, 64, 9);
put_block(&mut e, SIGN, true);
put_block(&mut e, other, true);
feed(&mut e, &open_packet(v, SIGN, true));
feed(&mut e, &open_packet(v, other, true));
let mut ev = Vec::new();
e.note_inbound(Instant::now());
e.tick(
&mut Script(|ctx: &mut TickContext<'_>| {
ev = ctx.events().signs().to_vec();
ctx.close_sign().unwrap();
}),
Instant::now(),
);
let a = SignEditor::new(SIGN, true);
let b = SignEditor::new(other, true);
assert_eq!(
ev,
vec![
SignEvent::Opened(a),
SignEvent::Closed(a, SignCloseReason::Replaced),
SignEvent::Opened(b)
],
"{v:?}"
);
let sent: Vec<_> = e
.outbound()
.iter()
.filter_map(|o| match o {
Outbound::UpdateSign { pos, lines, .. } => Some((*pos, lines.clone())),
_ => None,
})
.collect();
assert_eq!(sent.len(), 2, "{v:?}");
assert_eq!((sent[0].0, sent[1].0), (SIGN, other));
assert!(sent.iter().all(|s| s.1.iter().all(String::is_empty)));
let empty = if v == GameVersion::V1_8_9 { "\"\"" } else { "" };
let o = e
.outbound()
.iter()
.find(|o| matches!(o, Outbound::UpdateSign { .. }))
.unwrap()
.clone();
assert_eq!(sign_bytes(v, &o).2, [empty; 4].map(String::from), "{v:?}");
}
}
#[test]
fn editor_without_a_sign() {
for v in versions() {
let mut e = sign_engine(v);
put_block(&mut e, SIGN, false);
feed(&mut e, &open_packet(v, SIGN, true));
let mut ev = Vec::new();
let mut open = None;
e.note_inbound(Instant::now());
e.tick(
&mut Script(|ctx: &mut TickContext<'_>| {
ev = ctx.events().signs().to_vec();
open = ctx.sign_editor();
}),
Instant::now(),
);
let ed = SignEditor::new(SIGN, true);
let sent = names(e.outbound()).contains(&"update_sign");
match v {
GameVersion::V1_8_9 | GameVersion::V1_12_2 => {
assert_eq!(ev, vec![SignEvent::Opened(ed)], "{v:?}");
assert_eq!(open, Some(ed));
assert!(!sent);
}
GameVersion::V1_16_5 => {
assert_eq!(
ev,
vec![
SignEvent::Opened(ed),
SignEvent::Closed(ed, SignCloseReason::BlockGone)
]
);
assert_eq!(open, None);
assert!(sent);
}
_ => {
assert_eq!(ev, vec![SignEvent::Ignored(ed)], "{v:?}");
assert_eq!(open, None);
assert!(!sent);
}
}
}
}
#[test]
fn v1_16_5_editor_before_its_block() {
let v = GameVersion::V1_16_5;
let mut e = sign_engine(v);
feed(&mut e, &open_packet(v, SIGN, true));
e.note_inbound(Instant::now());
e.tick(&mut Idle, Instant::now());
assert!(e.core.sign.is_some(), "closed over air");
put_block(&mut e, SIGN, true);
e.tick(&mut Idle, Instant::now());
assert!(e.core.sign.is_some());
assert!(!names(e.outbound()).contains(&"update_sign"));
}
#[test]
fn modern_editor_closes_itself() {
for v in versions() {
let mut e = sign_engine(v);
put_block(&mut e, SIGN, true);
feed(&mut e, &open_packet(v, SIGN, true));
put_block(&mut e, SIGN, false);
let mut ev = Vec::new();
e.note_inbound(Instant::now());
e.tick(
&mut Script(|ctx: &mut TickContext<'_>| ev = ctx.events().signs().to_vec()),
Instant::now(),
);
let ed = SignEditor::new(SIGN, true);
if modern(v) {
assert_eq!(
ev,
vec![
SignEvent::Opened(ed),
SignEvent::Closed(ed, SignCloseReason::BlockGone)
],
"{v:?}"
);
assert!(names(e.outbound()).contains(&"update_sign"));
} else {
assert_eq!(ev, vec![SignEvent::Opened(ed)], "{v:?}");
assert!(e.core.sign.is_some());
}
let mut e = sign_engine(v);
put_block(&mut e, SIGN, true);
feed(&mut e, &open_packet(v, SIGN, true));
for (z, closes) in [(18.4, false), (18.6, true)] {
e.handle(Inbound::Teleport(crate::common::Teleport {
x: 9.5,
y: 64.0,
z,
flags: 0,
..Default::default()
}));
let mut ev = Vec::new();
e.note_inbound(Instant::now());
e.tick(
&mut Script(|ctx: &mut TickContext<'_>| ev = ctx.events().signs().to_vec()),
Instant::now(),
);
let closed = ev.contains(&SignEvent::Closed(ed, SignCloseReason::TooFar));
assert_eq!(closed, closes && modern(v), "{v:?} z {z}: {ev:?}");
}
}
}
#[test]
fn too_many_lines() {
let mut e = sign_engine(GameVersion::V1_8_9);
feed(&mut e, &open_packet(GameVersion::V1_8_9, SIGN, true));
e.note_inbound(Instant::now());
e.tick(
&mut Script(|ctx: &mut TickContext<'_>| {
assert_eq!(
ctx.write_sign(&["1", "2", "3", "4", "5"]),
Err(SignError::TooManyLines)
);
assert!(ctx.sign_editor().is_some());
}),
Instant::now(),
);
assert!(!names(e.outbound()).contains(&"update_sign"));
}
#[derive(Debug, Default)]
struct BookSent {
channel: Option<String>,
slot: Option<i32>,
signing: Option<bool>,
stack: Option<ghast_inventory::Stack>,
pages: Option<Vec<String>>,
title: Option<Option<String>>,
}
fn book_sent(v: GameVersion, o: &Outbound) -> BookSent {
let legacy = |channel: &ghast_protocol::types::ByteString, data: &bytes::Bytes| {
let slot: ghast_protocol::types::slot::legacy::Slot =
ghast_protocol::Decode::decode(&mut ghast_protocol::Reader::new(data)).unwrap();
BookSent {
channel: Some(channel.to_string()),
stack: ghast_inventory::from_legacy_slot(slot),
..BookSent::default()
}
};
let pages = |p: &[ghast_protocol::types::ByteString]| p.iter().map(|s| s.to_string()).collect();
match v {
GameVersion::V1_8_9 => {
let p: ghast_protocol::v1_8::play::serverbound::CustomPayload =
written::<crate::version::V1_8>(o).decode_as().unwrap();
legacy(&p.channel, &p.data)
}
GameVersion::V1_12_2 => {
let p: ghast_protocol::v1_12_2::play::serverbound::CustomPayload =
written::<crate::version::V1_12_2>(o).decode_as().unwrap();
legacy(&p.channel, &p.data)
}
GameVersion::V1_16_5 => {
let p: ghast_protocol::v1_16_5::play::serverbound::EditBook =
written::<crate::version::V1_16_5>(o).decode_as().unwrap();
BookSent {
slot: Some(p.hand),
signing: Some(p.signing),
stack: ghast_inventory::from_modern_slot(p.new_book),
..BookSent::default()
}
}
GameVersion::V26_1 => {
let p: ghast_protocol::v26_1::play::serverbound::EditBook =
written::<crate::version::V26_1>(o).decode_as().unwrap();
BookSent {
slot: Some(p.hand),
pages: Some(pages(&p.pages)),
title: Some(p.title.map(|t| t.to_string())),
..BookSent::default()
}
}
#[cfg(feature = "v26_3")]
GameVersion::V26_3 => {
let p: ghast_protocol::v26_3::play::serverbound::EditBook =
written::<crate::version::V26_3>(o).decode_as().unwrap();
BookSent {
slot: Some(p.hand),
pages: Some(pages(&p.pages)),
title: Some(p.title.map(|t| t.to_string())),
..BookSent::default()
}
}
_ => {
let p: ghast_protocol::v26_2::play::serverbound::EditBook =
written::<crate::version::V26_2>(o).decode_as().unwrap();
BookSent {
slot: Some(p.hand),
pages: Some(pages(&p.pages)),
title: Some(p.title.map(|t| t.to_string())),
..BookSent::default()
}
}
}
}
fn book_nbt(s: &ghast_inventory::Stack) -> (Vec<String>, Option<String>, Option<String>) {
use ghast_protocol::nbt::Tag;
let root = s.nbt().unwrap().parse().unwrap().unwrap().tag;
let c = root.as_compound().unwrap();
let pages = match c.get("pages") {
Some(Tag::List(l)) => l
.items
.iter()
.map(|t| match t {
Tag::String(s) => s.clone(),
o => panic!("{o:?}"),
})
.collect(),
_ => Vec::new(),
};
let s = |k: &str| match c.get(k) {
Some(Tag::String(s)) => Some(s.clone()),
_ => None,
};
(pages, s("author"), s("title"))
}
fn the_edit(e: &mut Engine<Box<dyn Sim>>) -> Outbound {
let o = e
.outbound()
.iter()
.find(|o| matches!(o, Outbound::EditBook(_)))
.expect("edit_book")
.clone();
e.outbound().clear();
o
}
#[test]
fn edit_and_sign_a_book_every_version() {
for v in versions() {
let mut e = sign_engine(v);
let (writable, written_id) = crate::book::book_items(v.caps().data).unwrap();
e.core
.inv
.set_hand(false, Some(ghast_inventory::Stack::new(writable, 1, 0)));
let me = e.core.opts.name.to_string();
let mut r = None;
e.note_inbound(Instant::now());
e.tick(
&mut Script(|ctx: &mut TickContext<'_>| {
r = Some(ctx.edit_book(false, &["Hel§lo", "two\nlines", ""], None));
}),
Instant::now(),
);
assert_eq!(r, Some(Ok(())), "{v:?}");
let s = book_sent(v, &the_edit(&mut e));
let held = e.core.inv.held().cloned().unwrap();
let want = vec!["Hello".to_owned(), "two\nlines".to_owned()];
match v {
GameVersion::V1_8_9 | GameVersion::V1_12_2 => {
assert_eq!(s.channel.as_deref(), Some("MC|BEdit"), "{v:?}");
let st = s.stack.unwrap();
assert_eq!(st.id(), writable);
assert_eq!(book_nbt(&st), (want.clone(), None, None), "{v:?}");
assert_eq!(book_nbt(&held), (want.clone(), None, None), "{v:?}");
}
GameVersion::V1_16_5 => {
assert_eq!((s.slot, s.signing), (Some(0), Some(false)));
assert_eq!(book_nbt(&s.stack.unwrap()), (want.clone(), None, None));
assert_eq!(book_nbt(&held), (want.clone(), None, None));
}
_ => {
assert_eq!(s.slot, Some(0), "{v:?}");
assert_eq!(s.pages.as_ref(), Some(&want), "{v:?}");
assert_eq!(s.title, Some(None), "{v:?}");
let ty = if v.caps().protocol >= 777 { 56 } else { 54 };
let c = held.components().expect("components");
let b = c.get(ty).expect("writable_book_content");
let mut x = vec![2u8, 5];
x.extend_from_slice(b"Hello");
x.extend_from_slice(&[0, 9]);
x.extend_from_slice(b"two\nlines");
x.push(0);
assert_eq!(&b[..], &x[..], "{v:?}");
}
}
e.tick(
&mut Script(|ctx: &mut TickContext<'_>| {
r = Some(ctx.edit_book(false, &["A<", ""], Some(" T ")));
}),
Instant::now(),
);
assert_eq!(r, Some(Ok(())), "{v:?}");
let s = book_sent(v, &the_edit(&mut e));
let after = e.core.inv.held().cloned().unwrap();
let t = Some("T".to_owned());
match v {
GameVersion::V1_8_9 => {
assert_eq!(s.channel.as_deref(), Some("MC|BSign"));
let st = s.stack.unwrap();
assert_eq!(st.id(), written_id);
let n = (vec!["\"A\\u003c\"".to_owned()], Some(me.clone()), t.clone());
assert_eq!(book_nbt(&st), n);
assert_eq!((after.id(), book_nbt(&after)), (written_id, n));
}
GameVersion::V1_12_2 => {
assert_eq!(s.channel.as_deref(), Some("MC|BSign"));
let st = s.stack.unwrap();
assert_eq!(st.id(), writable);
let n = (vec!["A<".to_owned()], Some(me.clone()), t.clone());
assert_eq!(book_nbt(&st), n);
assert_eq!(book_nbt(&after), n);
}
GameVersion::V1_16_5 => {
assert_eq!((s.slot, s.signing), (Some(0), Some(true)));
let n = (vec!["A<".to_owned()], Some(me.clone()), t.clone());
assert_eq!(book_nbt(&s.stack.unwrap()), n);
assert_eq!(book_nbt(&after), n);
}
_ => {
assert_eq!(s.pages, Some(vec!["A<".to_owned(), String::new()]), "{v:?}");
assert_eq!(s.title, Some(t.clone()));
assert_eq!(after, held, "{v:?}");
}
}
}
}
#[test]
fn book_refusals_and_the_off_hand() {
for v in versions() {
let mut e = sign_engine(v);
let (writable, _) = crate::book::book_items(v.caps().data).unwrap();
let mut r = Vec::new();
e.note_inbound(Instant::now());
e.tick(
&mut Script(|ctx: &mut TickContext<'_>| {
r.push(ctx.edit_book(false, &["x"], None));
}),
Instant::now(),
);
assert_eq!(r, vec![Err(crate::book::BookError::NoBook)], "{v:?}");
assert!(!names(e.outbound()).contains(&"edit_book"));
e.core
.inv
.set_hand(true, Some(ghast_inventory::Stack::new(writable, 1, 0)));
let mut r = None;
e.tick(
&mut Script(|ctx: &mut TickContext<'_>| {
r = Some(ctx.edit_book(true, &["x"], None));
}),
Instant::now(),
);
if v == GameVersion::V1_8_9 {
assert_eq!(r, Some(Err(crate::book::BookError::OffHand)));
continue;
}
assert_eq!(r, Some(Ok(())), "{v:?}");
let s = book_sent(v, &the_edit(&mut e));
if v != GameVersion::V1_12_2 {
assert_eq!(s.slot, Some(40), "{v:?}");
}
}
}
#[test]
fn inbound_size_unchanged() {
assert!(
std::mem::size_of::<Inbound>() <= 104,
"{}",
std::mem::size_of::<Inbound>()
);
}
const BED: BlockPos = BlockPos::new(9, 64, 9);
const ME: i32 = 7;
fn put_bed(e: &mut Engine<Box<dyn Sim>>) {
let v = e.core.opts.caps.version;
let raw = match v {
GameVersion::V1_8_9 => raw(&ghast_protocol::v1_8::play::clientbound::BlockChange {
location: BED,
r#type: 26 << 4 | 8,
}),
GameVersion::V1_12_2 => raw(&ghast_protocol::v1_12_2::play::clientbound::BlockChange {
location: BED,
r#type: 26 << 4 | 8,
}),
GameVersion::V1_16_5 => raw(&ghast_protocol::v1_16_5::play::clientbound::BlockChange {
location: BED,
r#type: i32::from(
ghast_data::v1_16_5::Block::from_name("red_bed")
.unwrap()
.default_state()
.id(),
),
}),
_ => {
let id = match v {
GameVersion::V26_1 => ghast_data::v26_1::Block::from_name("red_bed")
.unwrap()
.default_state()
.id(),
#[cfg(feature = "v26_3")]
GameVersion::V26_3 => ghast_data::v26_3::Block::from_name("red_bed")
.unwrap()
.default_state()
.id(),
_ => ghast_data::v26_2::Block::from_name("red_bed")
.unwrap()
.default_state()
.id(),
};
raw(&ghast_protocol::v26_1::play::clientbound::BlockChange {
location: BED,
r#type: i32::from(id),
})
}
};
e.sim.world_packet(&raw).unwrap();
}
fn sleep_packet(v: GameVersion, bed: Option<BlockPos>) -> RawPacket {
use bytes::BufMut;
use ghast_protocol::codec::McWrite;
match v {
GameVersion::V1_8_9 => raw(&ghast_protocol::v1_8::play::clientbound::Bed {
entity_id: ME,
location: bed.unwrap(),
}),
GameVersion::V1_12_2 => raw(&ghast_protocol::v1_12_2::play::clientbound::Bed {
entity_id: ME,
location: bed.unwrap(),
}),
_ => {
let (index, ty, id) = match v {
GameVersion::V1_16_5 => (
13,
10,
ghast_protocol::v1_16_5::play::clientbound::id::ENTITY_METADATA,
),
GameVersion::V26_1 => (
14,
11,
ghast_protocol::v26_1::play::clientbound::id::ENTITY_METADATA,
),
#[cfg(feature = "v26_3")]
GameVersion::V26_3 => (
14,
11,
ghast_protocol::v26_3::play::clientbound::id::ENTITY_METADATA,
),
_ => (
14,
11,
ghast_protocol::v26_2::play::clientbound::id::ENTITY_METADATA,
),
};
let mut b = bytes::BytesMut::new();
b.put_varint(ME);
b.put_u8(index);
b.put_varint(ty);
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())
}
}
}
fn feed_sleep(e: &mut Engine<Box<dyn Sim>>, raw: &RawPacket) {
let v = e.core.opts.caps.version;
if matches!(v, GameVersion::V1_8_9 | GameVersion::V1_12_2) {
feed(e, raw);
} else {
e.sim.test_set_own_id(ME);
e.sim.world_packet(raw).unwrap();
}
}
fn animation(v: GameVersion, id: i32, anim: u8) -> RawPacket {
use bytes::BufMut;
use ghast_protocol::codec::McWrite;
let mut b = bytes::BytesMut::new();
b.put_varint(id);
b.put_u8(anim);
let pid = if v == GameVersion::V1_8_9 {
ghast_protocol::v1_8::play::clientbound::id::ANIMATION
} else {
ghast_protocol::v1_12_2::play::clientbound::id::ANIMATION
};
RawPacket::new(pid, b.freeze())
}
#[test]
fn sleeping_every_version() {
for v in versions() {
let mut e = sign_engine(v);
put_bed(&mut e);
e.core.pose.pitch = 30.0;
feed_sleep(&mut e, &sleep_packet(v, Some(BED)));
let mut seen = (Vec::new(), None, 0, false);
e.note_inbound(Instant::now());
e.tick(
&mut Script(|ctx: &mut TickContext<'_>| {
seen.0 = ctx.events().sleep().to_vec();
seen.1 = ctx.sleeping();
seen.2 = ctx.sleep_ticks();
ctx.set_controls(Controls {
forward: true,
jump: true,
..Controls::NONE
});
ctx.set_aim(90.0, 45.0);
}),
Instant::now(),
);
assert_eq!(
seen.0,
vec![crate::common::SleepEvent::FellAsleep(BED)],
"{v:?}"
);
assert_eq!((seen.1, seen.2), (Some(BED), 1), "{v:?}");
let p = e.core.pose.pos;
let (x, z) = match v {
GameVersion::V1_8_9 => (9.5, f64::from(9f32 + 0.9f32)),
GameVersion::V1_12_2 => (9.5, f64::from(9f32 + (0.5f32 + 0.4f32))),
_ => (9.5, 9.5),
};
assert_eq!((p.x, p.z), (x, z), "{v:?}");
assert!(p.y > 64.56 && p.y <= 64.6875, "{v:?} y {}", p.y);
let pitch = if v.caps().sleep_levels_pitch {
0.0
} else {
30.0
};
assert_eq!(e.core.pose.pitch, pitch, "{v:?}");
for _ in 0..30 {
e.note_inbound(Instant::now());
e.tick(&mut Idle, Instant::now());
}
let q = e.core.pose.pos;
assert_eq!((q.x, q.z), (x, z), "{v:?}: moved while asleep");
let mut r = (0, false, false);
e.tick(
&mut Script(|ctx: &mut TickContext<'_>| {
r = (ctx.sleep_ticks(), ctx.leave_bed(), false);
}),
Instant::now(),
);
assert_eq!((r.0, r.1), (32, true), "{v:?}");
let o = e
.outbound()
.iter()
.find(|o| matches!(o, Outbound::EntityAction { .. }))
.cloned()
.expect("entity_action");
let action = match v {
GameVersion::V1_8_9 => {
written::<crate::version::V1_8>(&o)
.decode_as::<ghast_protocol::v1_8::play::serverbound::EntityAction>()
.unwrap()
.action_id
.0
}
GameVersion::V1_12_2 => {
written::<crate::version::V1_12_2>(&o)
.decode_as::<ghast_protocol::v1_12_2::play::serverbound::EntityAction>()
.unwrap()
.action_id
.0
}
GameVersion::V1_16_5 => {
written::<crate::version::V1_16_5>(&o)
.decode_as::<ghast_protocol::v1_16_5::play::serverbound::EntityAction>()
.unwrap()
.action_id
.0
}
_ => {
written::<crate::version::V26_1>(&o)
.decode_as::<ghast_protocol::v26_1::play::serverbound::EntityAction>()
.unwrap()
.action_id
.0
}
};
assert_eq!(action, if modern(v) { 0 } else { 2 }, "{v:?}");
e.outbound().clear();
if !modern(v) && v != GameVersion::V1_16_5 {
feed(&mut e, &animation(v, ME, 0));
feed(&mut e, &animation(v, ME + 1, 2));
assert!(e.core.sleeping.is_some(), "{v:?}");
feed(&mut e, &animation(v, ME, 2));
} else {
feed_sleep(&mut e, &sleep_packet(v, None));
}
let mut seen = (Vec::new(), Some(BED), 9);
e.tick(
&mut Script(|ctx: &mut TickContext<'_>| {
seen = (
ctx.events().sleep().to_vec(),
ctx.sleeping(),
ctx.sleep_ticks(),
);
assert!(!ctx.leave_bed());
}),
Instant::now(),
);
assert_eq!(
seen,
(vec![crate::common::SleepEvent::WokeUp], None, 0),
"{v:?}"
);
}
}
#[test]
fn others_and_missing_beds() {
for v in versions() {
let mut e = sign_engine(v);
if !modern(v) && v != GameVersion::V1_16_5 {
let p = match v {
GameVersion::V1_8_9 => raw(&ghast_protocol::v1_8::play::clientbound::Bed {
entity_id: ME + 1,
location: BED,
}),
_ => raw(&ghast_protocol::v1_12_2::play::clientbound::Bed {
entity_id: ME + 1,
location: BED,
}),
};
feed(&mut e, &p);
assert!(e.core.sleeping.is_none(), "{v:?}");
continue;
}
let before = e.core.pose.pos;
feed_sleep(&mut e, &sleep_packet(v, Some(BED)));
e.note_inbound(Instant::now());
e.tick(&mut Idle, Instant::now());
assert_eq!(e.core.sleeping, Some(BED), "{v:?}");
let p = e.core.pose.pos;
if v == GameVersion::V26_3 {
assert_eq!(
(p.x, p.z),
(before.x, before.z),
"{v:?}: moved without a bed"
);
} else {
assert_eq!((p.x, p.z), (9.5, 9.5), "{v:?}");
}
}
}
#[test]
fn every_book_press_sends_its_use() {
for v in versions() {
let mut e = sign_engine(v);
let (writable, _) = crate::book::book_items(v.caps().data).unwrap();
e.core
.inv
.set_hand(false, Some(ghast_inventory::Stack::new(writable, 1, 0)));
let mut log = Vec::new();
for t in 0..30 {
e.note_inbound(Instant::now());
e.tick(
&mut Script(|ctx: &mut TickContext<'_>| {
let right = t == 1 || t == 16;
ctx.set_buttons(crate::hands::Buttons { left: false, right });
if t == 7 {
ctx.edit_book(false, &["a"], None).unwrap();
}
}),
Instant::now(),
);
for x in names(e.outbound()) {
if matches!(x, "block_place" | "edit_book") {
log.push((t, x));
}
}
}
assert_eq!(
log,
vec![(1, "block_place"), (7, "edit_book"), (16, "block_place")],
"{v:?}"
);
}
}