use super::{Fx, Interact};
use ghast_entity::{Entities, Entity, EntityType, MetaValue};
#[cfg(feature = "v26_1")]
#[rustfmt::skip]
pub(super) mod v26_1;
#[cfg(feature = "v26_2")]
#[rustfmt::skip]
pub(super) mod v26_2;
#[cfg(feature = "v26_3")]
#[rustfmt::skip]
pub(super) mod v26_3;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Dim {
Hand,
Sneak,
OtherHand(u16),
Flag { idx: u8, mask: u8, def: u8 },
Int { idx: u8, n: u8, def: u8 },
Present(u8),
Owner(u8),
SameColorByte { idx: u8, def: u8 },
SameColorInt { idx: u8, def: u8 },
Health(u8),
#[cfg(any(feature = "v26_2", feature = "v26_3"))]
NonNegative(u8),
Equip(u8),
Passengers,
Leash,
Effect(u8),
}
impl Dim {
fn n(self) -> usize {
match self {
Dim::Int { n, .. } => usize::from(n),
Dim::Owner(_) | Dim::Health(_) | Dim::Passengers => 3,
Dim::Leash => 4,
_ => 2,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum StackFx {
None,
Take,
Into(u16),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Outcome {
pub kind: Interact,
pub fx: StackFx,
}
#[derive(Debug)]
pub(crate) struct TypeRule {
pub ty: u16,
pub max_health: f32,
pub dims: &'static [Dim],
pub states: &'static [u8],
pub rows: &'static [u16],
}
#[derive(Debug)]
pub(crate) struct Table {
pub outcomes: &'static [Outcome],
pub item_class: &'static [u8],
pub named_class: u8,
pub empty_class: u8,
pub name_tag: u16,
pub dyes: &'static [(u16, u8)],
pub rows: &'static [u8],
pub classes: usize,
pub types: &'static [TypeRule],
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Held {
pub id: u16,
pub named: bool,
}
pub(crate) fn table(protocol: i32) -> Option<&'static Table> {
match protocol {
#[cfg(feature = "v26_1")]
775 => Some(&v26_1::TABLE),
#[cfg(feature = "v26_2")]
776 => Some(&v26_2::TABLE),
#[cfg(feature = "v26_3")]
777 => Some(&v26_3::TABLE),
_ => None,
}
}
pub(crate) fn kept_types(protocol: i32) -> &'static [u16] {
use std::sync::OnceLock;
fn of(t: &'static Table, k: &'static OnceLock<Box<[u16]>>) -> &'static [u16] {
k.get_or_init(|| t.kept_types())
}
match protocol {
#[cfg(feature = "v26_1")]
775 => {
static K: OnceLock<Box<[u16]>> = OnceLock::new();
of(&v26_1::TABLE, &K)
}
#[cfg(feature = "v26_2")]
776 => {
static K: OnceLock<Box<[u16]>> = OnceLock::new();
of(&v26_2::TABLE, &K)
}
#[cfg(feature = "v26_3")]
777 => {
static K: OnceLock<Box<[u16]>> = OnceLock::new();
of(&v26_3::TABLE, &K)
}
_ => &[],
}
}
impl Table {
fn kept_types(&self) -> Box<[u16]> {
self.types
.iter()
.filter(|t| {
t.dims
.iter()
.any(|d| matches!(d, Dim::Equip(_) | Dim::Effect(_)))
})
.map(|t| t.ty)
.collect()
}
fn class(&self, h: Option<Held>) -> Option<u8> {
match h {
None => Some(self.empty_class),
Some(h) if h.id == self.name_tag && h.named => Some(self.named_class),
Some(h) => self.item_class.get(usize::from(h.id)).copied(),
}
}
fn dye(&self, h: Option<Held>) -> Option<u8> {
let id = h?.id;
self.dyes.iter().find(|d| d.0 == id).map(|d| d.1)
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn outcome(
&self,
ents: &Entities,
e: &Entity,
me: Option<uuid::Uuid>,
hand: usize,
sneaking: bool,
hands: [Option<Held>; 2],
) -> Outcome {
const PASS: Outcome = Outcome {
kind: Interact::NotHandled,
fx: StackFx::None,
};
let EntityType::Registry(ty) = e.entity_type() else {
return PASS;
};
let Ok(k) = self.types.binary_search_by_key(&ty, |t| t.ty) else {
return PASS;
};
let rule = &self.types[k];
let held = hands[hand];
let other = hands[1 - hand];
let Some(class) = self.class(held) else {
return PASS;
};
let mut state = 0usize;
let mut mul = 1usize;
for &d in rule.dims {
let v = read(
d,
ents,
e,
me,
hand,
sneaking,
held,
other,
self,
rule.max_health,
);
state += v.min(d.n() - 1) * mul;
mul *= d.n();
}
let Some(&row) = rule.states.get(state) else {
return PASS;
};
let row = usize::from(rule.rows[usize::from(row)]);
let o = self.rows[row * self.classes + usize::from(class)];
self.outcomes[usize::from(o)]
}
}
#[allow(clippy::too_many_arguments)]
fn read(
d: Dim,
ents: &Entities,
e: &Entity,
me: Option<uuid::Uuid>,
hand: usize,
sneaking: bool,
held: Option<Held>,
other: Option<Held>,
t: &Table,
max_health: f32,
) -> usize {
let m = e.metadata();
let int = |idx: u8| match m.get(idx) {
Some(MetaValue::VarInt(v) | MetaValue::Int(v) | MetaValue::Enum(_, v)) => Some(*v),
Some(MetaValue::Byte(b)) => Some(i32::from(*b)),
_ => None,
};
match d {
Dim::Hand => hand,
Dim::Sneak => usize::from(sneaking),
Dim::OtherHand(id) => usize::from(other.is_some_and(|h| h.id == id)),
Dim::Flag { idx, mask, def } => match m.get(idx) {
Some(MetaValue::Bool(b)) => usize::from(*b),
Some(MetaValue::Byte(b)) if mask == 0 => usize::from(*b != 0),
Some(MetaValue::Byte(b)) => usize::from((*b as u8) & mask != 0),
_ => usize::from(def),
},
Dim::Int { idx, def, .. } => int(idx).map_or(usize::from(def), |v| v.max(0) as usize),
Dim::Present(idx) => usize::from(match m.get(idx) {
Some(MetaValue::Stack(s)) => s.is_some(),
Some(MetaValue::Item(s)) => s.is_some(),
Some(MetaValue::OptBlockPos(p)) => p.is_some(),
Some(MetaValue::OptUuid(u)) => u.is_some(),
_ => false,
}),
Dim::Owner(idx) => match m.get(idx) {
Some(MetaValue::OptUuid(Some(u))) if Some(*u) == me => 1,
Some(MetaValue::OptUuid(Some(_))) => 2,
_ => 0,
},
Dim::SameColorByte { idx, def } => {
let color = int(idx).map_or(def, |b| (b & 15) as u8);
usize::from(t.dye(held) == Some(color))
}
Dim::SameColorInt { idx, def } => {
let color = int(idx).unwrap_or(i32::from(def));
usize::from(t.dye(held).map(i32::from) == Some(color))
}
Dim::Health(idx) => match m.get(idx) {
Some(MetaValue::Float(h)) if *h <= 0.0 => 2,
Some(MetaValue::Float(h)) if *h < max_health => 1,
_ => 0,
},
#[cfg(any(feature = "v26_2", feature = "v26_3"))]
Dim::NonNegative(idx) => usize::from(int(idx).is_some_and(|v| v >= 0)),
Dim::Equip(slot) => usize::from(e.equipment(usize::from(slot)).is_some()),
Dim::Passengers => e.passengers().len(),
Dim::Leash => match e.leash_holder() {
None => 0,
Some(h) if Some(h) == ents.self_id() => 1,
Some(h) => match ents.get(h) {
None => 0,
Some(x) if x.is_player() => 3,
Some(_) => 2,
},
},
Dim::Effect(id) => usize::from(e.effect(id).is_some()),
}
}
#[allow(clippy::too_many_arguments)]
pub(super) fn outcome(
t: &Table,
ents: &Entities,
e: &Entity,
name: &str,
spectator: bool,
sneaking: bool,
creative: bool,
hands: [Option<Held>; 2],
) -> [(Interact, Fx); 2] {
if spectator {
return [(Interact::NotHandled, Fx::None); 2];
}
let me = ents.tab_uuid(name);
let one = |hand: usize| {
let o = t.outcome(ents, e, me, hand, sneaking, hands);
let fx = match o.fx {
_ if creative => Fx::None,
StackFx::None => Fx::None,
StackFx::Take => Fx::Take,
StackFx::Into(id) => Fx::Into(id),
};
(o.kind, fx)
};
[one(0), one(1)]
}
#[cfg(test)]
mod generate {
use serde_json::Value;
use std::collections::{BTreeMap, HashMap};
use std::fmt::Write as _;
use std::io::BufRead;
fn lines(version: &str) -> Vec<Value> {
let path = format!(
"{}/../../tests/golden/{version}/entity_click_table.jsonl.gz",
env!("CARGO_MANIFEST_DIR")
);
let f = std::fs::File::open(&path).unwrap_or_else(|e| panic!("{path}: {e}"));
std::io::BufReader::new(flate2::read::GzDecoder::new(f))
.lines()
.map(|l| serde_json::from_str(&l.unwrap()).unwrap())
.collect()
}
fn outcome(s: &str, ids: &HashMap<&str, u64>) -> String {
let (kind, fx) = s.split_once('|').unwrap();
let kind = match kind {
"pass" | "fail" => "NotHandled",
"consume" => "Handled",
"swing" => "HandledSwing",
k => panic!("result {k}"),
};
let fx = match fx {
"none" => "StackFx::None".to_owned(),
"take" => "StackFx::Take".to_owned(),
f => match f.strip_prefix("into:") {
Some(item) => format!("StackFx::Into({})", ids[item]),
None => panic!("stack change {f}"),
},
};
format!("Outcome {{ kind: Interact::{kind}, fx: {fx} }}")
}
fn dim(d: &Value, ids: &HashMap<&str, u64>) -> String {
let u = |k: &str| d[k].as_i64().unwrap();
match d["kind"].as_str().unwrap() {
"hand" => "Dim::Hand".into(),
"sneak" => "Dim::Sneak".into(),
"other_hand" => format!("Dim::OtherHand({})", ids[d["item"].as_str().unwrap()]),
"flag" => format!(
"Dim::Flag {{ idx: {}, mask: {}, def: {} }}",
u("idx"),
u("mask"),
u("def")
),
"int" => format!(
"Dim::Int {{ idx: {}, n: {}, def: {} }}",
u("idx"),
u("n"),
u("def").max(0)
),
"present" => format!("Dim::Present({})", u("idx")),
"owner" => format!("Dim::Owner({})", u("idx")),
"same_color_byte" => format!(
"Dim::SameColorByte {{ idx: {}, def: {} }}",
u("idx"),
u("def")
),
"same_color_int" => format!(
"Dim::SameColorInt {{ idx: {}, def: {} }}",
u("idx"),
u("def")
),
"health" => format!("Dim::Health({})", u("idx")),
"non_negative" => format!("Dim::NonNegative({})", u("idx")),
"equip" => format!("Dim::Equip({})", u("slot")),
"passengers" => "Dim::Passengers".into(),
"leash" => "Dim::Leash".into(),
"effect" => format!("Dim::Effect({})", u("id")),
k => panic!("dim {k}"),
}
}
pub(super) fn render(version: &str) -> String {
let all = lines(version);
let h = &all[0];
let n_items = h["items"].as_u64().unwrap() as usize;
let item_ids: Vec<u64> = h["item_ids"]
.as_array()
.unwrap()
.iter()
.map(|v| v.as_u64().unwrap())
.collect();
let names: Vec<&str> = h["item_names"]
.as_array()
.unwrap()
.iter()
.map(|v| v.as_str().unwrap())
.collect();
let ids: HashMap<&str, u64> = names
.iter()
.copied()
.zip(item_ids.iter().copied())
.collect();
let outcomes: Vec<&str> = h["outcomes"]
.as_array()
.unwrap()
.iter()
.map(|v| v.as_str().unwrap())
.collect();
let width = n_items + 2;
let mut rows: Vec<Vec<u8>> = Vec::new();
let mut type_rows: Vec<Vec<usize>> = Vec::new();
for t in &all[1..] {
let mut mine = Vec::new();
for r in t["rows"].as_array().unwrap() {
let mut v = vec![r["default"].as_u64().unwrap() as u8; width];
for e in r["except"].as_array().unwrap() {
v[e[0].as_u64().unwrap() as usize] = e[1].as_u64().unwrap() as u8;
}
v[width - 1] = r["empty"].as_u64().unwrap() as u8;
mine.push(rows.len());
rows.push(v);
}
type_rows.push(mine);
}
let mut class_of = vec![0u8; width];
let mut classes: BTreeMap<Vec<u8>, u8> = BTreeMap::new();
let mut order: Vec<usize> = Vec::new();
for (it, c) in class_of.iter_mut().enumerate() {
let sig: Vec<u8> = rows.iter().map(|r| r[it]).collect();
let next = classes.len() as u8;
let id = *classes.entry(sig).or_insert_with(|| {
order.push(it);
next
});
*c = id;
}
assert!(classes.len() < 256, "{} classes", classes.len());
let mut distinct: Vec<Vec<u8>> = Vec::new();
let mut index: HashMap<Vec<u8>, usize> = HashMap::new();
let row_of: Vec<usize> = rows
.iter()
.map(|r| {
let v: Vec<u8> = order.iter().map(|&it| r[it]).collect();
let n = distinct.len();
*index.entry(v.clone()).or_insert_with(|| {
distinct.push(v);
n
})
})
.collect();
let max_id = item_ids.iter().copied().max().unwrap() as usize;
let mut item_class = vec![class_of[width - 1]; max_id + 1];
for (k, &id) in item_ids.iter().enumerate() {
item_class[id as usize] = class_of[k];
}
let mut s = String::new();
let _ = writeln!(
s,
"//! {version} entity click table: `tests/golden/{version}/entity_click_table.jsonl.gz` (oracle\n\
//! `EntityClicks`) rendered by `interact::modern::generate`.\n//!\n\
//! @generated by `GHAST_BLESS=1 cargo test -p ghast-client --lib interact::modern` — do not edit.\n\n\
use super::{{Dim, Outcome, StackFx, Table, TypeRule}};\nuse crate::hands::Interact;\n"
);
let _ = writeln!(s, "pub(crate) static TABLE: Table = Table {{");
let _ = writeln!(s, " outcomes: &[");
for o in &outcomes {
let _ = writeln!(s, " {},", outcome(o, &ids));
}
let _ = writeln!(s, " ],");
let _ = writeln!(s, " item_class: &[");
for chunk in item_class.chunks(32) {
let v: Vec<String> = chunk.iter().map(u8::to_string).collect();
let _ = writeln!(s, " {},", v.join(", "));
}
let _ = writeln!(s, " ],");
let _ = writeln!(s, " named_class: {},", class_of[n_items]);
let _ = writeln!(s, " empty_class: {},", class_of[width - 1]);
let _ = writeln!(s, " name_tag: {},", h["name_tag"].as_u64().unwrap());
let dyes: Vec<String> = h["dyes"]
.as_array()
.unwrap()
.iter()
.map(|d| format!("({}, {})", d[0], d[1]))
.collect();
let _ = writeln!(s, " dyes: &[{}],", dyes.join(", "));
let _ = writeln!(s, " rows: &[");
for r in &distinct {
let v: Vec<String> = r.iter().map(u8::to_string).collect();
let _ = writeln!(s, " {},", v.join(", "));
}
let _ = writeln!(s, " ],");
let _ = writeln!(s, " classes: {},", classes.len());
let _ = writeln!(s, " types: &[");
let mut types: Vec<(u64, String)> = Vec::new();
for (t, mine) in all[1..].iter().zip(&type_rows) {
let dims: Vec<String> = t["dims"]
.as_array()
.unwrap()
.iter()
.map(|d| dim(d, &ids))
.collect();
let states: Vec<String> = t["states"]
.as_array()
.unwrap()
.iter()
.map(|v| {
let k = v.as_u64().unwrap();
assert!(k < 256);
k.to_string()
})
.collect();
let rows: Vec<String> = mine.iter().map(|r| row_of[*r].to_string()).collect();
let max_health = t["max_health"]
.as_array()
.map_or(0.0, |v| v[0].as_f64().unwrap());
let id = t["id"].as_u64().unwrap();
types.push((
id,
format!(
" // {}\n TypeRule {{ ty: {id}, max_health: {max_health:?}, dims: &[{}], states: &[{}], rows: &[{}] }},",
t["name"].as_str().unwrap(),
dims.join(", "),
states.join(", "),
rows.join(", ")
),
));
}
types.sort_by_key(|t| t.0);
for (_, t) in types {
let _ = writeln!(s, "{t}");
}
let _ = writeln!(s, " ],\n}};");
s
}
fn check(version: &str, file: &str) {
let want = render(version);
let path = format!("{}/src/interact/modern/{file}", env!("CARGO_MANIFEST_DIR"));
if std::env::var_os("GHAST_BLESS").is_some() {
std::fs::write(&path, &want).unwrap();
return;
}
let have = std::fs::read_to_string(&path).unwrap_or_default();
assert!(
have == want,
"{path} is stale: GHAST_BLESS=1 cargo test -p ghast-client --lib interact::modern"
);
}
#[cfg(feature = "v26_1")]
#[test]
fn table_26_1_is_current() {
check("26.1", "v26_1.rs");
}
#[cfg(feature = "v26_2")]
#[test]
fn table_26_2_is_current() {
check("26.2", "v26_2.rs");
}
#[cfg(feature = "v26_3")]
#[test]
fn table_26_3_is_current() {
check("26.3", "v26_3.rs");
}
}