use ghast_data::v1_16_5::item_use::{UseClass, arrow, crossbow_held_ammo, use_class};
use ghast_data::v1_16_5::place::{Held, Mode, Use, inert, lily_pad};
use ghast_data::v1_16_5::{Block, BlockState, Item};
use ghast_physics::math::Aabb;
use ghast_physics::pick::v1_16_5::{self as pick, Fluids};
use ghast_protocol::BlockPos;
use ghast_protocol::nbt::{Compound, NamedTag, RawNbt, Tag};
use super::predict::{AirAnswer, AirQuery, AirResult, AirUse, HandChange};
use crate::common::GameMode;
pub(crate) struct Ctx<'a> {
pub world: &'a ghast_world::v1_16_5::World,
pub bb: Aabb,
pub climbing: bool,
pub eye_y: f64,
pub ultrawarm: bool,
pub fall_flying: bool,
pub entities: Option<&'a ghast_entity::Entities>,
pub own_id: i32,
}
fn item_name(id: i32) -> Option<&'static str> {
Item::from_id(u16::try_from(id).ok()?).map(|i| i.info().name)
}
fn item_id(name: &str) -> i32 {
Item::from_name(name).map_or(0, |i| i32::from(i.id()))
}
fn with_tag(name: &str, key: &str, value: Tag) -> ghast_inventory::Stack {
let nbt = RawNbt::from_named(&NamedTag {
name: String::new(),
tag: Tag::Compound(Compound(vec![(key.to_owned(), value)])),
})
.ok();
ghast_inventory::Stack::new(item_id(name), 1, 0).with_nbt(nbt)
}
fn tag_of(s: &ghast_inventory::Stack) -> Option<Compound> {
match s.nbt()?.parse().ok()??.tag {
Tag::Compound(c) => Some(c),
_ => None,
}
}
fn known(result: AirResult, starts: bool) -> AirAnswer {
AirAnswer::Known(AirUse {
result,
starts,
blocks: Some(Vec::new()),
hand: HandChange::Keep,
})
}
const PASS: AirResult = AirResult::Pass;
fn offset(p: BlockPos, face: u8) -> BlockPos {
let [x, y, z] = [p.x, p.y, p.z];
match face {
0 => BlockPos::new(x, y - 1, z),
1 => BlockPos::new(x, y + 1, z),
2 => BlockPos::new(x, y, z - 1),
3 => BlockPos::new(x, y, z + 1),
4 => BlockPos::new(x - 1, y, z),
_ => BlockPos::new(x + 1, y, z),
}
}
fn state(w: &ghast_world::v1_16_5::World, p: BlockPos) -> BlockState {
if !(0..256).contains(&p.y) {
return Block::VOID_AIR.default_state();
}
w.block_state(p.x, p.y, p.z).unwrap_or(BlockState::AIR)
}
fn set(
w: &ghast_world::v1_16_5::World,
p: BlockPos,
s: BlockState,
) -> Option<Vec<(BlockPos, u32)>> {
(0..6)
.all(|d| inert(state(w, offset(p, d))))
.then(|| vec![(p, u32::from(s.id()))])
}
fn waterlogged(s: BlockState) -> Option<bool> {
let p = ghast_data::v1_16_5::Property::from_name("waterlogged")?;
s.get(p).map(|v| v == "true")
}
fn with_waterlogged(s: BlockState, on: bool) -> Option<BlockState> {
let p = ghast_data::v1_16_5::Property::from_name("waterlogged")?;
s.with(p, if on { "true" } else { "false" })
}
pub(crate) fn air_use(cx: &Ctx<'_>, q: &AirQuery<'_>) -> AirAnswer {
let Some(class) = u16::try_from(q.stack.id()).ok().and_then(use_class) else {
return AirAnswer::Unknown;
};
let eye = [q.eyes.x, cx.eye_y, q.eyes.z];
let held_block = q
.inv
.held()
.and_then(|s| item_name(s.id()))
.and_then(Block::from_name);
let ray = |f: Fluids| pick::item_ray(cx.world, eye, q.yaw, q.pitch, f, held_block);
let creative = q.creative;
match class {
UseClass::Plain
| UseClass::Armor
| UseClass::Elytra
| UseClass::Trident
| UseClass::Thrown
| UseClass::FishingRod => AirAnswer::Flags,
UseClass::EnderPearl => AirAnswer::Known(AirUse {
result: AirResult::Success,
starts: false,
blocks: Some(Vec::new()),
hand: if creative {
HandChange::Keep
} else {
HandChange::UseOne
},
}),
UseClass::MilkBucket | UseClass::Drink | UseClass::Shield => {
known(AirResult::Consume, true)
}
UseClass::Firework => known(
if cx.fall_flying {
AirResult::Success
} else {
PASS
},
false,
),
UseClass::OnAStick => known(PASS, false),
UseClass::WritableBook | UseClass::WrittenBook => known(AirResult::Success, false),
UseClass::KnowledgeBook => {
let recipes =
tag_of(q.stack).is_some_and(|t| matches!(t.get("Recipes"), Some(Tag::List(_))));
AirAnswer::Known(AirUse {
result: if recipes { AirResult::Success } else { PASS },
starts: false,
blocks: Some(Vec::new()),
hand: if creative {
HandChange::Keep
} else {
HandChange::Empty
},
})
}
UseClass::EmptyMap => AirAnswer::Known(AirUse {
result: AirResult::Success,
starts: false,
blocks: Some(Vec::new()),
hand: HandChange::Exchange {
output: with_tag("filled_map", "map", Tag::Int(0)),
creative_keeps: false,
},
}),
UseClass::Bow => {
let ammo = creative || has_arrow(q.inv);
known(if ammo { AirResult::Consume } else { PASS }, ammo)
}
UseClass::Crossbow => {
let charged = tag_of(q.stack).filter(|t| match t.get("Charged") {
Some(Tag::Byte(b)) => *b != 0,
Some(Tag::Short(v)) => *v as i8 != 0,
Some(Tag::Int(v)) => *v as i8 != 0,
_ => false,
});
if let Some(t) = charged {
return AirAnswer::Known(AirUse {
result: AirResult::Consume,
starts: false,
blocks: Some(Vec::new()),
hand: HandChange::Replace(fired(q.stack, t)),
});
}
let held = [q.inv.offhand(), q.inv.held()]
.into_iter()
.flatten()
.any(|s| u16::try_from(s.id()).is_ok_and(crossbow_held_ammo));
let ammo = held || has_arrow(q.inv) || creative;
known(if ammo { AirResult::Consume } else { PASS }, ammo)
}
UseClass::EnderEye => {
let hit = ray(Fluids::None);
let frame = hit.is_block()
&& state(cx.world, pos_of(hit.pos)).block() == Block::END_PORTAL_FRAME;
if frame {
known(PASS, false)
} else {
known(AirResult::Consume, true)
}
}
UseClass::SpawnEgg => {
let hit = ray(Fluids::SourceOnly);
known(
if hit.is_block() {
AirResult::Success
} else {
PASS
},
false,
)
}
UseClass::GlassBottle => {
let hit = ray(Fluids::SourceOnly);
let water = hit.is_block()
&& state(cx.world, pos_of(hit.pos))
.fluid()
.is_some_and(|f| f.kind == ghast_data::FluidKind::Water);
if !water {
return known(PASS, false);
}
AirAnswer::Known(AirUse {
result: AirResult::Success,
starts: false,
blocks: Some(Vec::new()),
hand: HandChange::Exchange {
output: with_tag("potion", "Potion", Tag::String("minecraft:water".into())),
creative_keeps: true,
},
})
}
UseClass::LilyPad => {
let hit = ray(Fluids::SourceOnly);
let above = [hit.pos[0], hit.pos[1] + 1, hit.pos[2]];
let held = Held {
id: u16::try_from(q.stack.id()).unwrap_or(0),
count: q.stack.count(),
nbt: q.stack.nbt().is_some(),
};
let mode = match q.game_mode {
GameMode::Creative => Mode::Creative,
GameMode::Adventure => Mode::Adventure,
GameMode::Spectator => Mode::Spectator,
_ => Mode::Survival,
};
let player = ghast_data::Aabb {
min_x: cx.bb.min_x,
min_y: cx.bb.min_y,
min_z: cx.bb.min_z,
max_x: cx.bb.max_x,
max_y: cx.bb.max_y,
max_z: cx.bb.max_z,
};
let o = lily_pad(above, hit.face as u8, held, mode, &player, &|[x, y, z]| {
state(cx.world, BlockPos::new(x, y, z)).id()
});
match o.result {
Some(Use::Success) => AirAnswer::Known(AirUse {
result: AirResult::Success,
starts: false,
blocks: o.placed.map(|v| {
v.into_iter()
.map(|([x, y, z], s)| (BlockPos::new(x, y, z), u32::from(s)))
.collect()
}),
hand: if o.count_after.is_some_and(|n| n < held.count) {
HandChange::UseOne
} else {
HandChange::Keep
},
}),
Some(_) => known(PASS, false),
None => AirAnswer::Unknown,
}
}
UseClass::Boat => boat(cx, q, eye, &ray(Fluids::Any)),
UseClass::Bucket => bucket(cx, q, &ray),
_ => AirAnswer::Unknown,
}
}
fn fired(s: &ghast_inventory::Stack, mut t: Compound) -> ghast_inventory::Stack {
let mut put = |key: &str, v: Tag| match t.0.iter_mut().find(|(k, _)| k == key) {
Some(e) => e.1 = v,
None => t.0.push((key.to_owned(), v)),
};
put(
"ChargedProjectiles",
Tag::List(ghast_protocol::nbt::List::default()),
);
put("Charged", Tag::Byte(0));
let nbt = RawNbt::from_named(&NamedTag {
name: String::new(),
tag: Tag::Compound(t),
})
.ok();
s.clone().with_nbt(nbt)
}
pub(crate) fn climbing(w: &ghast_world::v1_16_5::World, pos: [f64; 3]) -> bool {
use ghast_data::PhysicsFlags;
use ghast_data::v1_16_5::Property;
let p = BlockPos::new(
pos[0].floor() as i32,
pos[1].floor() as i32,
pos[2].floor() as i32,
);
let s = state(w, p);
let f = s.block().physics().flags;
if f.contains(PhysicsFlags::CLIMBABLE) {
return true;
}
if f.contains(PhysicsFlags::TRAPDOOR) && s.get(Property::Open) == Some("true") {
let below = state(w, offset(p, 0));
return below.block() == Block::LADDER
&& below.get(Property::Facing) == s.get(Property::Facing);
}
false
}
fn pos_of(p: [i32; 3]) -> BlockPos {
BlockPos::new(p[0], p[1], p[2])
}
fn has_arrow(inv: &ghast_inventory::Inventory) -> bool {
(0..41).any(|k| {
inv.player(k)
.is_some_and(|s| u16::try_from(s.id()).is_ok_and(arrow))
})
}
fn boat(
cx: &Ctx<'_>,
q: &AirQuery<'_>,
eye: [f64; 3],
hit: &ghast_physics::pick::BlockHit,
) -> AirAnswer {
if !hit.is_block() {
return known(PASS, false);
}
let _ = q;
if let Some(ents) = cx.entities {
let reach = Aabb::new(
eye[0] - 7.0,
eye[1] - 7.0,
eye[2] - 7.0,
eye[0] + 7.0,
eye[1] + 7.0,
eye[2] + 7.0,
);
let near = ents.iter().any(|e| {
e.id() != cx.own_id
&& e.bounding_box().is_none_or(|b| {
b[3] > reach.min_x
&& b[0] < reach.max_x
&& b[4] > reach.min_y
&& b[1] < reach.max_y
&& b[5] > reach.min_z
&& b[2] < reach.max_z
})
});
if near {
return AirAnswer::Unknown;
}
}
let me: &[Aabb] = if cx.climbing {
&[]
} else {
std::slice::from_ref(&cx.bb)
};
let fits = ghast_physics::v1_16_5::boat_item_fits(cx.world, hit.location, me);
known(if fits { AirResult::Success } else { PASS }, false)
}
enum Pour {
NoRoom,
Fail,
Done(Option<Vec<(BlockPos, u32)>>),
}
fn bucket(
cx: &Ctx<'_>,
q: &AirQuery<'_>,
ray: &dyn Fn(Fluids) -> ghast_physics::pick::BlockHit,
) -> AirAnswer {
let name = item_name(q.stack.id()).unwrap_or("");
let fluid = match name {
"bucket" => None,
"lava_bucket" => Some(Block::LAVA),
_ => Some(Block::WATER),
};
let hit = ray(if fluid.is_none() {
Fluids::SourceOnly
} else {
Fluids::None
});
if !hit.is_block() {
return known(PASS, false);
}
let pos = pos_of(hit.pos);
let face = hit.face as u8;
if !matches!(q.game_mode, GameMode::Survival | GameMode::Creative) {
return known(PASS, false);
}
let w = cx.world;
let at = state(w, pos);
let Some(fluid) = fluid else {
let (left, filled) = match at.block().name() {
"water" | "lava" if at.fluid().is_some_and(|f| f.still()) => (
Some(BlockState::AIR),
if at.block() == Block::LAVA {
"lava_bucket"
} else {
"water_bucket"
},
),
"bubble_column" => (Some(BlockState::AIR), "water_bucket"),
_ if waterlogged(at) == Some(true) => (with_waterlogged(at, false), "water_bucket"),
_ => (None, ""),
};
let Some(left) = left else {
return known(PASS, false);
};
return AirAnswer::Known(AirUse {
result: AirResult::Success,
starts: false,
blocks: set(w, pos, left),
hand: HandChange::Exchange {
output: ghast_inventory::Stack::new(item_id(filled), 1, 0),
creative_keeps: true,
},
});
};
let water = fluid == Block::WATER;
let fillable = |s: BlockState| {
waterlogged(s).is_some()
|| matches!(
s.block().name(),
"kelp" | "kelp_plant" | "seagrass" | "tall_seagrass"
)
};
let target = if fillable(at) && water {
pos
} else {
offset(pos, face)
};
let place = |p: BlockPos| -> Pour {
let s = state(w, p);
let n = s.block().name();
let bucket_place = !matches!(n, "end_gateway" | "end_portal")
&& (s.material_replaceable() || !s.material_solid());
let fill = waterlogged(s) == Some(false) && water;
if !(s.is_air() || bucket_place || fill) {
return Pour::NoRoom;
}
if (cx.ultrawarm && water) || (fillable(s) && water) {
return Pour::Done(Some(Vec::new()));
}
let new = fluid.default_state();
if !(0..256).contains(&p.y) {
return Pour::Fail;
}
if s == new {
return if s.fluid().is_some_and(|f| f.still()) {
Pour::Done(Some(Vec::new()))
} else {
Pour::Fail
};
}
Pour::Done(set(w, p, new))
};
let blocks = match place(target) {
Pour::NoRoom => match place(offset(pos, face)) {
Pour::Done(b) => b,
Pour::NoRoom | Pour::Fail => return known(PASS, false),
},
Pour::Fail => return known(PASS, false),
Pour::Done(b) => b,
};
AirAnswer::Known(AirUse {
result: AirResult::Success,
starts: false,
blocks,
hand: if q.creative {
HandChange::Keep
} else {
HandChange::Replace(ghast_inventory::Stack::new(item_id("bucket"), 1, 0))
},
})
}