use ghast_data::v1_16_5::{Block, BlockState, Property, Side};
use super::piston::{Facing, offset};
use crate::voxel::{EPSILON, VoxelShape};
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) enum Kind {
Inert,
Fence,
Pane,
Wall,
Stairs,
Gate,
Snowy,
Carpet,
DeadCoral,
DeadWallFan,
Chest,
Mushroom,
AttachedStem,
Campfire,
ChorusPlant,
ConcretePowder,
Other,
}
#[must_use]
pub(crate) fn kind(b: Block) -> Kind {
let n = b.name();
if n.ends_with("_fence_gate") {
Kind::Gate
} else if n.ends_with("_fence") {
Kind::Fence
} else if n == "iron_bars" || n == "glass_pane" || n.ends_with("_stained_glass_pane") {
Kind::Pane
} else if n.ends_with("_wall") {
Kind::Wall
} else if n.ends_with("_stairs") {
Kind::Stairs
} else if matches!(n, "grass_block" | "podzol" | "mycelium") {
Kind::Snowy
} else if n.ends_with("_carpet") {
Kind::Carpet
} else if n.starts_with("dead_") && n.ends_with("_coral_wall_fan") {
Kind::DeadWallFan
} else if n.starts_with("dead_") && (n.ends_with("_coral") || n.ends_with("_coral_fan")) {
Kind::DeadCoral
} else if n == "chest" || n == "trapped_chest" {
Kind::Chest
} else if n.ends_with("_mushroom_block") || n == "mushroom_stem" {
Kind::Mushroom
} else if n.starts_with("attached_") {
Kind::AttachedStem
} else if n == "campfire" || n == "soul_campfire" {
Kind::Campfire
} else if n == "chorus_plant" {
Kind::ChorusPlant
} else if n.ends_with("_concrete_powder") {
Kind::ConcretePowder
} else if matches!(
n,
"kelp"
| "kelp_plant"
| "weeping_vines"
| "weeping_vines_plant"
| "twisting_vines"
| "twisting_vines_plant"
| "bamboo"
| "bamboo_sapling"
| "bell"
| "note_block"
| "bubble_column"
| "fire"
| "redstone_wire"
| "tripwire"
| "tripwire_hook"
| "vine"
) {
Kind::Other
} else {
Kind::Inert
}
}
fn wooden_fence(b: Block) -> bool {
b.name() != "nether_brick_fence"
}
#[must_use]
pub(crate) fn cannot_connect(b: Block) -> bool {
let n = b.name();
n.ends_with("_leaves")
|| n == "shulker_box"
|| n.ends_with("_shulker_box")
|| matches!(
n,
"barrier" | "carved_pumpkin" | "jack_o_lantern" | "melon" | "pumpkin"
)
}
#[must_use]
pub(crate) fn wall_post_override(b: Block) -> bool {
let n = b.name();
n.ends_with("_sign")
|| n.ends_with("_banner")
|| n.ends_with("_pressure_plate")
|| matches!(n, "torch" | "soul_torch" | "redstone_torch" | "tripwire")
}
pub(super) trait UpdateView {
fn state(&self, p: [i32; 3]) -> BlockState;
fn side_solid(&self, p: [i32; 3], s: BlockState, face: Facing) -> Option<bool>;
fn down_face_covers(&self, p: [i32; 3], s: BlockState, rect: [f64; 4]) -> Option<bool>;
}
const NAMES: [&str; 6] = ["down", "up", "north", "south", "west", "east"];
fn prop(name: &str) -> Property {
Property::from_name(name).expect("1.16.5 property")
}
fn with(s: BlockState, p: &str, v: &str) -> BlockState {
s.with(prop(p), v).expect("1.16.5 state property")
}
fn facing_of(s: BlockState) -> Option<Facing> {
let v = s.get(prop("facing"))?;
NAMES.iter().position(|n| *n == v).map(|i| i as Facing)
}
#[inline]
const fn opposite(f: Facing) -> Facing {
f ^ 1
}
#[inline]
const fn axis(f: Facing) -> u8 {
f >> 1
}
const fn clockwise(f: Facing) -> Facing {
match f {
2 => 5,
5 => 3,
3 => 4,
_ => 2,
}
}
const fn counter_clockwise(f: Facing) -> Facing {
match f {
2 => 4,
4 => 3,
3 => 5,
_ => 2,
}
}
fn step(p: [i32; 3], f: Facing) -> [i32; 3] {
let o = offset(f);
[p[0] + o[0], p[1] + o[1], p[2] + o[2]]
}
pub(super) fn side(f: Facing) -> Side {
match f {
0 => Side::Down,
1 => Side::Up,
2 => Side::North,
3 => Side::South,
4 => Side::West,
_ => Side::East,
}
}
pub(super) fn neighbor_update<V: UpdateView>(
v: &V,
s: BlockState,
dir: Facing,
n: BlockState,
pos: [i32; 3],
npos: [i32; 3],
) -> Result<BlockState, BlockState> {
let horizontal = dir >= 2;
match kind(s.block()) {
Kind::Inert => Ok(s),
Kind::Other => Err(s),
Kind::Fence if horizontal => {
let solid = v.side_solid(npos, n, opposite(dir)).ok_or(s)?;
let c = fence_connects(s.block(), n, solid, opposite(dir));
Ok(with(s, NAMES[dir as usize], bool_str(c)))
}
Kind::Pane if horizontal => {
let solid = v.side_solid(npos, n, opposite(dir)).ok_or(s)?;
let c = pane_connects(n, solid);
Ok(with(s, NAMES[dir as usize], bool_str(c)))
}
Kind::Gate => {
let f = facing_of(s).ok_or(s)?;
if axis(clockwise(f)) != axis(dir) {
return Ok(s);
}
let w = is_wall(n.block()) || is_wall(v.state(step(pos, opposite(dir))).block());
Ok(with(s, "in_wall", bool_str(w)))
}
Kind::Snowy if dir == 1 => {
let b = n.block();
let snowy = b == Block::SNOW_BLOCK || b == Block::SNOW;
Ok(with(s, "snowy", bool_str(snowy)))
}
Kind::Stairs if horizontal => Ok(with(s, "shape", stair_shape(v, s, pos))),
Kind::Carpet => Ok(if v.state(step(pos, 0)).is_air() {
BlockState::AIR
} else {
s
}),
Kind::DeadCoral if dir == 0 => {
let below = step(pos, 0);
let solid = v.side_solid(below, v.state(below), 1).ok_or(s)?;
Ok(if solid { s } else { BlockState::AIR })
}
Kind::DeadWallFan => {
let f = facing_of(s).ok_or(s)?;
if opposite(dir) != f {
return Ok(s);
}
let behind = step(pos, opposite(f));
let solid = v.side_solid(behind, v.state(behind), f).ok_or(s)?;
Ok(if solid { s } else { BlockState::AIR })
}
Kind::Chest => Ok(chest_update(s, dir, n)),
Kind::Mushroom if n.block() == s.block() => Ok(with(s, NAMES[dir as usize], "false")),
Kind::AttachedStem => {
let f = facing_of(s).ok_or(s)?;
let (gourd, stem) = if s.block() == Block::ATTACHED_PUMPKIN_STEM {
(Block::PUMPKIN, Block::PUMPKIN_STEM)
} else {
(Block::MELON, Block::MELON_STEM)
};
Ok(if dir == f && n.block() != gourd {
with(stem.default_state(), "age", "7")
} else {
s
})
}
Kind::Campfire if dir == 0 => Ok(with(
s,
"signal_fire",
bool_str(n.block() == Block::HAY_BLOCK),
)),
Kind::ChorusPlant => {
if !chorus_can_stay(v, pos) {
return Ok(s);
}
let b = n.block();
let c = b == Block::CHORUS_PLANT
|| b == Block::CHORUS_FLOWER
|| (dir == 0 && b == Block::END_STONE);
Ok(with(s, NAMES[dir as usize], bool_str(c)))
}
Kind::ConcretePowder => {
let wet = |d: Facing| {
let q = step(pos, d);
let ns = v.state(q);
if !ns
.fluid()
.is_some_and(|f| f.kind == ghast_data::FluidKind::Water)
{
return Some(false);
}
v.side_solid(pos, ns, opposite(d)).map(|solid| !solid)
};
let mut hardens = false;
for d in 1..6 {
if wet(d).ok_or(s)? {
hardens = true;
break;
}
}
Ok(if hardens { concrete_of(s.block()) } else { s })
}
Kind::Wall if dir != 0 => {
let mut c = [false; 4];
for (k, side) in WALL_SIDES.iter().enumerate() {
c[k] = s.get(prop(side)) != Some("none");
}
let above = if dir == 1 {
(npos, n)
} else {
let k = WALL_SIDES
.iter()
.position(|w| *w == NAMES[dir as usize])
.expect("horizontal");
let solid = v.side_solid(npos, n, opposite(dir)).ok_or(s)?;
c[k] = wall_connects(n, solid, opposite(dir));
let up = step(pos, 1);
(up, v.state(up))
};
wall_state(v, s, above.0, above.1, c).ok_or(s)
}
_ => Ok(s),
}
}
fn chest_partner(s: BlockState) -> Option<Facing> {
let f = facing_of(s)?;
Some(if s.get(prop("type")) == Some("left") {
clockwise(f)
} else {
counter_clockwise(f)
})
}
fn chest_update(s: BlockState, dir: Facing, n: BlockState) -> BlockState {
if n.block() == s.block() && dir >= 2 {
let t = n.get(prop("type"));
if s.get(prop("type")) == Some("single")
&& t != Some("single")
&& facing_of(s) == facing_of(n)
&& chest_partner(n) == Some(opposite(dir))
{
let other = if t == Some("left") { "right" } else { "left" };
return with(s, "type", other);
}
s
} else if chest_partner(s) == Some(dir) {
with(s, "type", "single")
} else {
s
}
}
fn chorus_can_stay<V: UpdateView>(v: &V, pos: [i32; 3]) -> bool {
let below = v.state(step(pos, 0));
let vertical = !v.state(step(pos, 1)).is_air() && !below.is_air();
for d in 2..6 {
let q = step(pos, d);
if v.state(q).block() == Block::CHORUS_PLANT {
if vertical {
return false;
}
let b = v.state(step(q, 0)).block();
if b == Block::CHORUS_PLANT || b == Block::END_STONE {
return true;
}
}
}
let b = below.block();
b == Block::CHORUS_PLANT || b == Block::END_STONE
}
fn concrete_of(b: Block) -> BlockState {
let name = b.name().trim_end_matches("_powder");
Block::from_name(name).map_or(BlockState::AIR, Block::default_state)
}
const fn bool_str(b: bool) -> &'static str {
if b { "true" } else { "false" }
}
fn is_wall(b: Block) -> bool {
kind(b) == Kind::Wall
}
fn gate_connects(n: BlockState, side: Facing) -> bool {
kind(n.block()) == Kind::Gate && facing_of(n).is_some_and(|f| axis(f) == axis(clockwise(side)))
}
fn fence_connects(fence: Block, n: BlockState, solid: bool, side: Facing) -> bool {
let b = n.block();
let same_fence = kind(b) == Kind::Fence && wooden_fence(b) == wooden_fence(fence);
(!cannot_connect(b) && solid) || same_fence || gate_connects(n, side)
}
fn pane_connects(n: BlockState, solid: bool) -> bool {
let b = n.block();
(!cannot_connect(b) && solid) || kind(b) == Kind::Pane || is_wall(b)
}
fn wall_connects(n: BlockState, solid: bool, side: Facing) -> bool {
let b = n.block();
is_wall(b) || (!cannot_connect(b) && solid) || kind(b) == Kind::Pane || gate_connects(n, side)
}
const WALL_SIDES: [&str; 4] = ["north", "east", "south", "west"];
const TALL_SIDES: [[f64; 4]; 4] = [
[7.0, 0.0, 9.0, 9.0],
[7.0, 7.0, 16.0, 9.0],
[7.0, 7.0, 9.0, 16.0],
[0.0, 7.0, 9.0, 9.0],
];
const TALL_POST: [f64; 4] = [7.0, 7.0, 9.0, 9.0];
fn sixteenths(r: [f64; 4]) -> [f64; 4] {
r.map(|v| v / 16.0)
}
fn wall_state<V: UpdateView>(
v: &V,
s: BlockState,
above_pos: [i32; 3],
above: BlockState,
c: [bool; 4],
) -> Option<BlockState> {
let mut out = s;
let mut tall = [false; 4];
for k in 0..4 {
let value = if c[k] {
tall[k] = v.down_face_covers(above_pos, above, sixteenths(TALL_SIDES[k]))?;
if tall[k] { "tall" } else { "low" }
} else {
"none"
};
out = with(out, WALL_SIDES[k], value);
}
let up = if is_wall(above.block()) && above.get(prop("up")) == Some("true") {
true
} else {
let [n, e, so, w] = c.map(|x| !x);
if (n && so && w && e) || n != so || w != e {
true
} else if (tall[0] && tall[2]) || (tall[1] && tall[3]) {
false
} else {
wall_post_override(above.block())
|| v.down_face_covers(above_pos, above, sixteenths(TALL_POST))?
}
};
Some(with(out, "up", bool_str(up)))
}
fn is_stairs(s: BlockState) -> bool {
kind(s.block()) == Kind::Stairs
}
fn stair_shape<V: UpdateView>(v: &V, s: BlockState, pos: [i32; 3]) -> &'static str {
let half = s.get(prop("half"));
let Some(f) = facing_of(s) else {
return "straight";
};
let different = |d: Facing| {
let o = v.state(step(pos, d));
!is_stairs(o) || facing_of(o) != Some(f) || o.get(prop("half")) != half
};
let front = v.state(step(pos, f));
if is_stairs(front)
&& front.get(prop("half")) == half
&& let Some(d2) = facing_of(front)
&& axis(d2) != axis(f)
&& different(opposite(d2))
{
return if d2 == counter_clockwise(f) {
"outer_left"
} else {
"outer_right"
};
}
let back = v.state(step(pos, opposite(f)));
if is_stairs(back)
&& back.get(prop("half")) == half
&& let Some(d3) = facing_of(back)
&& axis(d3) != axis(f)
&& different(d3)
{
return if d3 == counter_clockwise(f) {
"inner_left"
} else {
"inner_right"
};
}
"straight"
}
fn cell_index(shape: &VoxelShape<'_>, axis: usize, coord: f64) -> isize {
let p = shape.axes[axis];
let n = p.cells();
if shape
.axes
.iter()
.all(|q| matches!(q, crate::voxel::Points::Fractional(_)))
{
let v = crate::math::floor(coord * n as f64);
return (v as isize).clamp(-1, n as isize);
}
(0..=n).find(|&k| coord < p.get(k)).unwrap_or(n + 1) as isize - 1
}
pub(super) fn face_covers(
shape: &VoxelShape<'_>,
dir: Facing,
rect: [f64; 4],
exact: bool,
) -> bool {
let a = [1usize, 2, 0][(dir >> 1) as usize];
let (b, c) = match a {
0 => (1, 2),
1 => (0, 2),
_ => (0, 1),
};
if shape.is_empty() {
return false;
}
let layer = cell_index(shape, a, if dir & 1 == 1 { 0.999_999_9 } else { EPSILON });
let pts = |k: usize| -> Vec<f64> {
let p = shape.axes[k];
(0..=p.cells()).map(|i| p.get(i)).collect()
};
let merged = |p: &[f64], lo: f64, hi: f64| -> Vec<f64> {
let mut all: Vec<f64> = p.iter().copied().chain([lo, hi]).collect();
all.sort_by(f64::total_cmp);
let mut kept: Vec<f64> = Vec::with_capacity(all.len());
for v in all {
if kept.last().is_none_or(|&l| l < v - EPSILON) {
kept.push(v);
}
}
kept
};
let cell = |p: &[f64], x: f64| -> Option<usize> {
let k = p.iter().rposition(|&q| q <= x)?;
(k + 1 < p.len()).then_some(k)
};
let (pb, pc) = (pts(b), pts(c));
let (mb, mc) = (merged(&pb, rect[0], rect[2]), merged(&pc, rect[1], rect[3]));
let n = [
shape.axes[0].cells(),
shape.axes[1].cells(),
shape.axes[2].cells(),
];
let in_layer = layer >= 0 && (layer as usize) < n[a];
for u in mb.windows(2) {
let inside_b = u[0] >= rect[0] - EPSILON && u[1] <= rect[2] + EPSILON;
let jb = cell(&pb, f64::midpoint(u[0], u[1]));
for w in mc.windows(2) {
let inside = inside_b && w[0] >= rect[1] - EPSILON && w[1] <= rect[3] + EPSILON;
let jc = cell(&pc, f64::midpoint(w[0], w[1]));
let filled = in_layer
&& match (jb, jc) {
(Some(jb), Some(jc)) => {
let mut q = [0isize; 3];
q[a] = layer;
q[b] = jb as isize;
q[c] = jc as isize;
shape.filled(q[0], q[1], q[2])
}
_ => false,
};
if inside != filled && (inside || exact) {
return false;
}
}
}
true
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Read;
#[test]
fn kinds_match_oracle_dump() {
let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../tests/golden/1.16.5/piston_facts.jsonl.gz");
let mut text = String::new();
flate2::read::GzDecoder::new(std::fs::File::open(path).expect("facts"))
.read_to_string(&mut text)
.expect("gzip");
let mut n = 0;
for line in text.lines() {
let v: serde_json::Value = serde_json::from_str(line).unwrap();
let b = Block::from_id(v["block"].as_u64().unwrap() as u16).unwrap();
let class = v["shape_update"].as_str().unwrap();
let want = match class {
"FenceBlock" => Kind::Fence,
"PaneBlock" => Kind::Pane,
"WallBlock" => Kind::Wall,
"StairsBlock" => Kind::Stairs,
"FenceGateBlock" => Kind::Gate,
"SnowyBlock" => Kind::Snowy,
"CarpetBlock" => Kind::Carpet,
"CoralParentBlock" => Kind::DeadCoral,
"DeadCoralWallFanBlock" => Kind::DeadWallFan,
"ChestBlock" => Kind::Chest,
"MushroomBlock" => Kind::Mushroom,
"AttachedStemBlock" => Kind::AttachedStem,
"CampfireBlock" => Kind::Campfire,
"ChorusPlantBlock" => Kind::ChorusPlant,
"ConcretePowderBlock" => Kind::ConcretePowder,
"AbstractPlantBlock"
| "AbstractPlantStemBlock"
| "BambooBlock"
| "BambooSaplingBlock"
| "BellBlock"
| "BubbleColumnBlock"
| "FireBlock"
| "NoteBlock"
| "RedstoneWireBlock"
| "TripwireBlock"
| "TripwireHookBlock"
| "VineBlock" => Kind::Other,
"AbstractBlock"
| "AbstractPressurePlateBlock"
| "BannerBlock"
| "BedBlock"
| "DoorBlock"
| "BeehiveBlock"
| "CactusBlock"
| "CakeBlock"
| "ChainBlock"
| "ChorusFlowerBlock"
| "CocoaBlock"
| "ConduitBlock"
| "CoralBlock"
| "CoralBlockBlock"
| "CoralFanBlock"
| "CoralWallFanBlock"
| "EnderChestBlock"
| "FallingBlock"
| "FarmlandBlock"
| "FlowerPotBlock"
| "FluidBlock"
| "GrassPathBlock"
| "LadderBlock"
| "LanternBlock"
| "LeavesBlock"
| "MagmaBlock"
| "NetherPortalBlock"
| "ObserverBlock"
| "PistonHeadBlock"
| "PlantBlock"
| "RepeaterBlock"
| "ScaffoldingBlock"
| "SeaPickleBlock"
| "SeagrassBlock"
| "SignBlock"
| "SlabBlock"
| "SnowBlock"
| "SoulFireBlock"
| "SoulSandBlock"
| "SugarCaneBlock"
| "TallPlantBlock"
| "TorchBlock"
| "TrapdoorBlock"
| "WallBannerBlock"
| "WallMountedBlock"
| "WallRedstoneTorchBlock"
| "WallSignBlock"
| "WallTorchBlock" => Kind::Inert,
other => panic!("{other}: read its getStateForNeighborUpdate and classify it"),
};
assert_eq!(kind(b), want, "{} ({class})", b.name());
let flag = |k: &str| v[k].as_bool().unwrap();
assert_eq!(is_wall(b), flag("walls"), "walls {}", b.name());
assert_eq!(is_wall(b), flag("wall_block"), "wall {}", b.name());
assert_eq!(
kind(b) == Kind::Fence,
flag("fences"),
"fences {}",
b.name()
);
assert_eq!(
kind(b) == Kind::Fence && wooden_fence(b),
flag("wooden_fences"),
"wooden {}",
b.name()
);
assert_eq!(kind(b) == Kind::Pane, flag("pane"), "pane {}", b.name());
assert_eq!(
kind(b) == Kind::Gate,
flag("fence_gate"),
"gate {}",
b.name()
);
assert_eq!(
is_stairs(b.default_state()),
flag("stairs_block"),
"{}",
b.name()
);
assert_eq!(cannot_connect(b), flag("cannot_connect"), "{}", b.name());
assert_eq!(
wall_post_override(b),
flag("wall_post_override"),
"post override {}",
b.name()
);
assert_eq!(
b.default_state().has_dynamic_bounds(),
flag("dynamic_bounds"),
"dynamic {}",
b.name()
);
n += 1;
}
assert!(n > 700);
}
}