use ghast_data::v1_8::{Block, BlockState};
use super::blocks::{fence_links, is_valid_pos, pane_links, shape_kind, state_at, wall_links};
use super::player::{Options, PlayerState, other_push_move, push_move, tick_with_moving};
use crate::input::{Packets, TickInput};
use crate::math::{Aabb, BoxOps, sorted_box};
use crate::world::{BlockView, WorldBorder};
pub const MOVING_PISTON: u8 = 36;
const STICKY_PISTON: u8 = 29;
const PISTON: u8 = 33;
const PISTON_HEAD: u8 = 34;
const OBSIDIAN: u8 = 49;
const SLIME: u8 = 165;
const PUSH_LIMIT: usize = 12;
pub type Facing = u8;
#[inline]
#[must_use]
pub const fn offset(f: Facing) -> [i32; 3] {
match f {
0 => [0, -1, 0],
1 => [0, 1, 0],
2 => [0, 0, -1],
3 => [0, 0, 1],
4 => [-1, 0, 0],
_ => [1, 0, 0],
}
}
#[inline]
const fn opposite(f: Facing) -> Facing {
f ^ 1
}
#[inline]
const fn axis(f: Facing) -> u8 {
f >> 1
}
#[inline]
fn step(p: [i32; 3], f: Facing, n: i32) -> [i32; 3] {
let o = offset(f);
[p[0] + o[0] * n, p[1] + o[1] * n, p[2] + o[2] * n]
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct MovingBlock {
pub pos: [i32; 3],
pub pushed: BlockState,
pub facing: Facing,
pub extending: bool,
pub source: bool,
pub progress: f32,
pub last_progress: f32,
removed: bool,
stale: bool,
}
impl MovingBlock {
#[must_use]
pub fn collision_box(&self) -> Option<Aabb> {
self.collision_box_with(FULL)
}
#[must_use]
pub fn collision_box_with(&self, head: [f64; 6]) -> Option<Aabb> {
let f = if self.extending {
1.0 - self.last_progress
} else {
self.last_progress
};
shrunk_box(self.pushed, self.pos, f, self.facing, head)
}
}
fn base_box(s: BlockState, head: [f64; 6]) -> Option<[f64; 6]> {
match s.block().id() {
PISTON | STICKY_PISTON => Some(FULL),
PISTON_HEAD => Some(head),
_ => s
.collision()
.boxes
.first()
.map(|b| [b.min_x, b.min_y, b.min_z, b.max_x, b.max_y, b.max_z]),
}
}
#[must_use]
pub fn box_is_tracked(s: BlockState) -> bool {
match s.block().id() {
PISTON | STICKY_PISTON | PISTON_HEAD | WALL => true,
78 | 88 | 60 | 171 => true,
id if shared_kind(id).is_some() => true,
_ => {
let c = s.collision();
c.boxes.is_empty() || c.is_full_cube()
}
}
}
const WALL: u8 = 139;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum SharedKind {
Own,
Stairs,
Fence,
Pane,
}
const fn shared_kind(id: u8) -> Option<(usize, SharedKind)> {
use SharedKind::{Fence, Own, Pane, Stairs};
Some(match id {
44 => (0, Own),
126 => (1, Own),
182 => (2, Own),
96 => (3, Own),
167 => (4, Own),
53 => (5, Stairs),
67 => (6, Stairs),
108 => (7, Stairs),
109 => (8, Stairs),
114 => (9, Stairs),
128 => (10, Stairs),
134 => (11, Stairs),
135 => (12, Stairs),
136 => (13, Stairs),
156 => (14, Stairs),
163 => (15, Stairs),
164 => (16, Stairs),
180 => (17, Stairs),
85 => (18, Fence),
113 => (19, Fence),
188 => (20, Fence),
189 => (21, Fence),
190 => (22, Fence),
191 => (23, Fence),
192 => (24, Fence),
101 => (25, Pane),
102 => (26, Pane),
160 => (27, Pane),
_ => return None,
})
}
const SHARED_SLOTS: usize = 28;
fn own_box(s: BlockState) -> Option<[f64; 6]> {
s.collision()
.boxes
.first()
.map(|b| [b.min_x, b.min_y, b.min_z, b.max_x, b.max_y, b.max_z])
}
fn fence_union([n, s, w, e]: [bool; 4]) -> [f64; 6] {
[
if w { 0.0 } else { 0.375 },
0.0,
if n { 0.0 } else { 0.375 },
if e { 1.0 } else { 0.625 },
1.0,
if s { 1.0 } else { 0.625 },
]
}
fn pane_bars([n, s, w, e]: [bool; 4]) -> (Option<[f64; 6]>, Option<[f64; 6]>) {
let any = n || s || w || e;
let (lo, hi) = (0.4375, 0.5625);
let x = if w && e || !any {
Some([0.0, 0.0, lo, 1.0, 1.0, hi])
} else if w {
Some([0.0, 0.0, lo, 0.5, 1.0, hi])
} else if e {
Some([0.5, 0.0, lo, 1.0, 1.0, hi])
} else {
None
};
let z = if n && s || !any {
Some([lo, 0.0, 0.0, hi, 1.0, 1.0])
} else if n {
Some([lo, 0.0, 0.0, hi, 1.0, 0.5])
} else if s {
Some([lo, 0.0, 0.5, hi, 1.0, 1.0])
} else {
None
};
(x, z)
}
fn pane_union([n, s, w, e]: [bool; 4]) -> [f64; 6] {
let any = n || s || w || e;
let (lo, hi) = (0.4375, 0.5625);
let span = |a: bool, b: bool| {
if (!a || !b) && any {
if a {
(0.0, hi)
} else if b {
(lo, 1.0)
} else {
(lo, hi)
}
} else {
(0.0, 1.0)
}
};
let (x0, x1) = span(w, e);
let (z0, z1) = span(n, s);
[x0, 0.0, z0, x1, 1.0, z1]
}
fn stairs_ray_bounds(meta: u8) -> [f64; 6] {
let last = if meta & 4 != 0 {
7
} else {
[7, 6, 7, 5][usize::from(meta & 3)]
};
let h = |bit: u8| if last & bit != 0 { 0.5 } else { 0.0 };
let (x, y, z) = (h(1), h(4), h(2));
[x, y, z, x + 0.5, y + 0.5, z + 0.5]
}
fn wall_bounds<W: BlockView<State = BlockState>>(w: &W, pos: [i32; 3]) -> [f64; 6] {
let [n, s, we, e] = wall_links(w, pos[0], pos[1], pos[2]);
let mut b = [
if we { 0.0 } else { 0.25 },
0.0,
if n { 0.0 } else { 0.25 },
if e { 1.0 } else { 0.75 },
1.5,
if s { 1.0 } else { 0.75 },
];
if n && s && !we && !e {
b[0] = 0.3125;
b[3] = 0.6875;
} else if we && e && !n && !s {
b[2] = 0.3125;
b[5] = 0.6875;
}
b
}
#[derive(Clone, Copy, Debug)]
enum Shape {
Exact(Aabb),
Unknown(Aabb),
}
fn shrink(b: [f64; 6], pos: [i32; 3], progress: f32, facing: Facing) -> Aabb {
let (x, y, z) = (f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2]));
let mut v = [x + b[0], y + b[1], z + b[2], x + b[3], y + b[4], z + b[5]];
let o = offset(facing);
for axis in 0..3 {
let d = f64::from(o[axis] as f32 * progress);
if o[axis] < 0 {
v[axis] -= d;
} else {
v[axis + 3] -= d;
}
}
sorted_box(v[0], v[1], v[2], v[3], v[4], v[5])
}
fn shrink_hull(pos: [i32; 3], progress: f32, facing: Facing) -> Aabb {
let p = [f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])];
let o = offset(facing);
let mut lo = p;
let mut hi = [p[0] + 1.0, p[1] + 1.0, p[2] + 1.0];
for axis in 0..3 {
if o[axis] != 0 {
let d = f64::from(o[axis] as f32 * progress);
let (a, b) = (p[axis] - d, (p[axis] + 1.0) - d);
lo[axis] = lo[axis].min(a).min(b);
hi[axis] = hi[axis].max(a).max(b);
}
}
Aabb::new(lo[0], lo[1], lo[2], hi[0], hi[1], hi[2])
}
fn shrunk_box(
s: BlockState,
pos: [i32; 3],
progress: f32,
facing: Facing,
head: [f64; 6],
) -> Option<Aabb> {
if s.block().id() == MOVING_PISTON || s.is_air() {
return None;
}
let b = base_box(s, head)?;
Some(shrink(b, pos, progress, facing))
}
pub type Edits = Vec<([i32; 3], BlockState)>;
#[derive(Clone, Debug, PartialEq)]
pub struct Pistons {
blocks: Vec<MovingBlock>,
head: std::cell::Cell<u8>,
unmodelled: bool,
head_unknown: std::cell::Cell<u8>,
ray_needed: std::cell::Cell<bool>,
heads_loaded: std::cell::Cell<bool>,
shared: [std::cell::Cell<Option<[f64; 6]>>; SHARED_SLOTS],
bounds_tick: std::cell::Cell<Option<i32>>,
bounds_missed: std::cell::Cell<bool>,
use_ray: std::cell::Cell<bool>,
}
impl Default for Pistons {
fn default() -> Pistons {
Pistons::new()
}
}
const FULL: [f64; 6] = [0.0, 0.0, 0.0, 1.0, 1.0, 1.0];
const HEAD_FULL: u8 = 6;
const HEAD_FULL_RAY: u8 = 7;
const HEAD_FULL_WATCH: u8 = 8;
const HEAD_PLATE: [[f64; 6]; 6] = [
[0.0, 0.0, 0.0, 1.0, 0.25, 1.0],
[0.0, 0.75, 0.0, 1.0, 1.0, 1.0],
[0.0, 0.0, 0.0, 1.0, 1.0, 0.25],
[0.0, 0.0, 0.75, 1.0, 1.0, 1.0],
[0.0, 0.0, 0.0, 0.25, 1.0, 1.0],
[0.75, 0.0, 0.0, 1.0, 1.0, 1.0],
];
impl Pistons {
#[must_use]
pub const fn new() -> Pistons {
Pistons {
blocks: Vec::new(),
head: std::cell::Cell::new(HEAD_FULL),
unmodelled: false,
head_unknown: std::cell::Cell::new(0),
ray_needed: std::cell::Cell::new(false),
heads_loaded: std::cell::Cell::new(false),
shared: [const { std::cell::Cell::new(None) }; SHARED_SLOTS],
bounds_tick: std::cell::Cell::new(None),
bounds_missed: std::cell::Cell::new(false),
use_ray: std::cell::Cell::new(false),
}
}
#[must_use]
pub fn head_bounds(&self) -> [f64; 6] {
match self.head.get() {
f @ 0..=5 => HEAD_PLATE[f as usize],
_ => FULL,
}
}
#[inline]
#[must_use]
pub fn head_bounds_set(&self) -> bool {
self.head.get() != HEAD_FULL
}
pub fn set_ray_needed(&self, on: bool) {
self.ray_needed.set(on);
if self.head.get() >= HEAD_FULL {
self.head.set(self.full_code());
}
}
pub fn set_heads_loaded(&self, on: bool) {
self.heads_loaded.set(on);
if self.head.get() >= HEAD_FULL {
self.head.set(self.full_code());
}
}
#[inline]
#[must_use]
pub fn watch_only(&self) -> bool {
self.head.get() == HEAD_FULL_WATCH
}
fn full_code(&self) -> u8 {
if self.ray_needed.get() {
HEAD_FULL_RAY
} else if self.heads_loaded.get() {
HEAD_FULL_WATCH
} else {
HEAD_FULL
}
}
pub fn crosshair<W: BlockView<State = BlockState>>(
&self,
world: &W,
eye: [f64; 3],
look: [f64; 3],
reach: f64,
) {
let end = crate::pick::legacy::ray_end(eye, look, reach);
let mut last = None;
crate::pick::legacy::trace(eye, end, true, |p| {
let s = state_at(world, p[0], p[1], p[2]);
if s.block().id() == PISTON_HEAD && s.meta() & 7 <= 5 {
last = Some(s.meta() & 7);
}
self.rayed(world, p, s);
crate::pick::v1_8::shape(world, p, false)
});
if let Some(f) = last {
self.head.set(f);
self.head_unknown.set(0);
}
if self.use_ray.take() {
self.forget_shared_bounds();
}
}
pub fn note_use_ray(&self) {
self.use_ray.set(true);
}
pub fn forget_head_bounds(&self, facings: u8) {
let full = u8::from(self.head.get() < HEAD_FULL) << 6;
self.head_unknown
.set(self.head_unknown.get() | (facings & 0x3f) | full);
}
#[must_use]
pub fn untracked_near(&self, bb: &Aabb) -> bool {
let area = bb.grow(1.0, 1.0, 1.0);
self.iter().any(|m| {
!box_is_tracked(m.pushed)
&& area.intersects(&Aabb::new(
f64::from(m.pos[0]) - 1.0,
f64::from(m.pos[1]) - 1.0,
f64::from(m.pos[2]) - 1.0,
f64::from(m.pos[0]) + 2.0,
f64::from(m.pos[1]) + 2.0,
f64::from(m.pos[2]) + 2.0,
))
})
}
pub fn take_unmodelled(&mut self) -> bool {
std::mem::take(&mut self.unmodelled) | self.bounds_missed.take()
}
pub fn begin_bounds_tick(&self, ticks_alive: i32) {
if self.bounds_tick.get() != Some(ticks_alive) {
self.forget_shared_bounds();
}
}
pub fn end_bounds_tick(&self, ticks_alive: i32) {
self.bounds_tick.set(Some(ticks_alive));
}
pub fn forget_shared_bounds(&self) {
for b in &self.shared {
b.set(None);
}
self.bounds_tick.set(None);
}
#[inline]
pub(super) fn block_queried<W: BlockView<State = BlockState>>(
&self,
w: &W,
x: i32,
y: i32,
z: i32,
s: BlockState,
) {
let id = s.block().id();
let Some((slot, kind)) = shared_kind(id) else {
return;
};
let b = match kind {
SharedKind::Own => own_box(s),
SharedKind::Stairs => Some(FULL),
SharedKind::Fence => Some(fence_union(fence_links(w, x, y, z, shape_kind(id)))),
SharedKind::Pane => {
let (bx, bz) = pane_bars(pane_links(w, x, y, z));
bz.or(bx)
}
};
if b.is_some() {
self.shared[slot].set(b);
}
}
fn rayed<W: BlockView<State = BlockState>>(&self, w: &W, p: [i32; 3], s: BlockState) {
let id = s.block().id();
let Some((slot, kind)) = shared_kind(id) else {
return;
};
let b = match kind {
SharedKind::Own => own_box(s),
SharedKind::Stairs => Some(stairs_ray_bounds(s.meta())),
SharedKind::Fence => Some(fence_union(fence_links(
w,
p[0],
p[1],
p[2],
shape_kind(id),
))),
SharedKind::Pane => Some(pane_union(pane_links(w, p[0], p[1], p[2]))),
};
if b.is_some() {
self.shared[slot].set(b);
}
}
fn shape<W: BlockView<State = BlockState>>(
&self,
w: &W,
s: BlockState,
pos: [i32; 3],
progress: f32,
facing: Facing,
) -> Option<Shape> {
let id = s.block().id();
if id == MOVING_PISTON || s.is_air() {
return None;
}
let b = if id == WALL {
wall_bounds(w, pos)
} else if let Some((slot, _)) = shared_kind(id) {
match self.shared[slot].get() {
Some(b) => b,
None => return Some(Shape::Unknown(shrink_hull(pos, progress, facing))),
}
} else {
base_box(s, self.head_bounds())?
};
Some(Shape::Exact(shrink(b, pos, progress, facing)))
}
#[inline]
pub(super) fn moving_box_in<W: BlockView<State = BlockState>>(
&self,
w: &W,
x: i32,
y: i32,
z: i32,
query: &Aabb,
) -> Option<Aabb> {
let m = self.at([x, y, z])?;
let f = if m.extending {
1.0 - m.last_progress
} else {
m.last_progress
};
match self.shape(w, m.pushed, m.pos, f, m.facing)? {
Shape::Exact(b) => Some(b),
Shape::Unknown(hull) => {
if hull.intersects(query) {
self.bounds_missed.set(true);
}
None
}
}
}
#[must_use]
pub fn head_unknown_touching(&self, before: &Aabb, after: &Aabb) -> bool {
if self.head_unknown.get() == 0 {
return false;
}
let swept = Aabb::new(
before.min_x.min(after.min_x) - 0.01,
before.min_y.min(after.min_y) - 0.01,
before.min_z.min(after.min_z) - 0.01,
before.max_x.max(after.max_x) + 0.01,
before.max_y.max(after.max_y) + 0.61,
before.max_z.max(after.max_z) + 0.01,
);
self.iter().any(|m| {
m.pushed.block().id() == PISTON_HEAD
&& m.collision_box_with(FULL)
.is_some_and(|b| b.intersects(&swept))
})
}
#[inline]
pub(super) fn head_queried(&self) {
self.head.set(self.full_code());
self.head_unknown.set(0);
}
#[inline]
#[must_use]
pub fn is_empty(&self) -> bool {
self.blocks.is_empty()
}
pub fn iter(&self) -> impl Iterator<Item = &MovingBlock> {
self.blocks.iter().filter(|b| !b.removed)
}
#[must_use]
pub fn at(&self, pos: [i32; 3]) -> Option<&MovingBlock> {
self.blocks.iter().find(|b| !b.removed && b.pos == pos)
}
fn index_at(&self, pos: [i32; 3]) -> Option<usize> {
self.blocks.iter().position(|b| !b.removed && b.pos == pos)
}
pub fn clear(&mut self) {
self.blocks.clear();
}
pub fn block_changed(&mut self, pos: [i32; 3], old: BlockState, new: BlockState) {
if old.block().id() == MOVING_PISTON
&& new.block().id() != MOVING_PISTON
&& let Some(i) = self.index_at(pos)
{
self.blocks.remove(i);
}
}
pub fn chunk_replaced(&mut self, cx: i32, cz: i32) {
self.blocks
.retain(|b| !(b.pos[0] >> 4 == cx && b.pos[2] >> 4 == cz));
}
fn add(&mut self, mut b: MovingBlock) {
if let Some(i) = self.index_at(b.pos) {
self.blocks[i].removed = true;
self.blocks[i].stale = true;
}
b.removed = false;
self.blocks.push(b);
}
pub fn tick_blocks<W: BlockView<State = BlockState>>(&mut self, world: &W, edits: &mut Edits) {
if !self.is_empty() {
tick_moving(None, world, &Options::default(), self, &mut [], &[], edits);
}
}
pub fn tick_blocks_among<W: BlockView<State = BlockState>>(
&mut self,
world: &W,
options: &Options,
others: &mut [PistonEntity],
solids: &[(Aabb, [i32; 3])],
edits: &mut Edits,
) {
if !self.is_empty() {
tick_moving(None, world, options, self, others, solids, edits);
}
}
pub fn tick_after_entities<W: BlockView<State = BlockState>>(
&mut self,
p: &mut PlayerState,
world: &W,
options: &Options,
edits: &mut Edits,
) {
if !self.is_empty() {
tick_moving(Some(p), world, options, self, &mut [], &[], edits);
}
}
pub fn tick_after_entities_among<W: BlockView<State = BlockState>>(
&mut self,
p: &mut PlayerState,
world: &W,
options: &Options,
others: &mut [PistonEntity],
solids: &[(Aabb, [i32; 3])],
edits: &mut Edits,
) {
if !self.is_empty() {
tick_moving(Some(p), world, options, self, others, solids, edits);
}
}
pub fn retain(&mut self, mut keep: impl FnMut(&MovingBlock) -> bool) {
self.blocks.retain(|b| b.stale || (!b.removed && keep(b)));
}
fn drop_removed(&mut self) {
self.blocks.retain(|b| b.stale || !b.removed);
}
pub fn block_event<W: BlockView<State = BlockState>>(
&mut self,
world: &W,
pos: [i32; 3],
block: u8,
action: u8,
data: u8,
edits: &mut Edits,
) -> bool {
let start = edits.len();
let mut ov = Overlay {
w: world,
edits,
start,
pistons: self,
};
let r = ov.on_event(pos, block, action, data);
self.drop_removed();
r
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PistonEntity {
pub bb: Aabb,
pub pos: [f64; 3],
pub on_ground: bool,
pub in_web: bool,
pub step_height: f32,
pub sneaking: bool,
pub moved: bool,
pub followed: bool,
pub section: [i32; 3],
}
#[must_use]
pub fn search_finds(section: [i32; 3], q: &Aabb) -> bool {
let f = |v: f64| crate::math::floor(v / 16.0);
let (x0, x1) = (f(q.min_x - 2.0), f(q.max_x + 2.0));
let (z0, z1) = (f(q.min_z - 2.0), f(q.max_z + 2.0));
let (y0, y1) = (f(q.min_y - 2.0).clamp(0, 15), f(q.max_y + 2.0).clamp(0, 15));
(x0..=x1).contains(§ion[0])
&& (y0..=y1).contains(§ion[1])
&& (z0..=z1).contains(§ion[2])
}
struct Layered<'a, W> {
w: &'a W,
edits: &'a [([i32; 3], BlockState)],
}
impl<W: BlockView<State = BlockState>> BlockView for Layered<'_, W> {
type State = BlockState;
#[inline]
fn block(&self, x: i32, y: i32, z: i32) -> BlockState {
for (p, s) in self.edits.iter().rev() {
if *p == [x, y, z] {
return *s;
}
}
self.w.block(x, y, z)
}
#[inline]
fn is_chunk_loaded(&self, cx: i32, cz: i32) -> bool {
self.w.is_chunk_loaded(cx, cz)
}
#[inline]
fn world_border(&self) -> WorldBorder {
self.w.world_border()
}
}
struct Overlay<'a, W> {
w: &'a W,
edits: &'a mut Edits,
start: usize,
pistons: &'a mut Pistons,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Behaviour {
Normal,
Destroy,
Block,
}
fn behaviour(id: u8) -> Behaviour {
match id {
6
| 8..=11
| 18
| 26
| 30..=32
| 37..=40
| 50
| 51
| 55
| 59
| 64
| 65
| 69..=72
| 75..=78
| 81
| 83
| 86
| 91..=94
| 103..=106
| 111
| 115
| 122
| 127
| 131
| 132
| 140..=144
| 147..=150
| 161
| 175
| 193..=197 => Behaviour::Destroy,
29 | 33 | 34 | 36 | 90 | 119 | 145 | 166 => Behaviour::Block,
_ => Behaviour::Normal,
}
}
fn unbreakable(id: u8) -> bool {
matches!(id, 7 | 36 | 90 | 119 | 120 | 137 | 166)
}
fn has_block_entity(id: u8) -> bool {
matches!(
id,
23 | 25
| 36
| 52
| 54
| 61..=63
| 68
| 84
| 116
| 117
| 119
| 130
| 137
| 138
| 140
| 144
| 146
| 149
| 150
| 151
| 154
| 158
| 176..=178
)
}
#[inline]
fn is_piston(id: u8) -> bool {
id == PISTON || id == STICKY_PISTON
}
fn facing_of(s: BlockState) -> Option<Facing> {
match s.block().id() {
PISTON | STICKY_PISTON | PISTON_HEAD | MOVING_PISTON => {
let f = s.meta() & 7;
(f <= 5).then_some(f)
}
_ => None,
}
}
impl<W: BlockView<State = BlockState>> Overlay<'_, W> {
#[inline]
fn get(&self, p: [i32; 3]) -> BlockState {
let v = Layered {
w: self.w,
edits: &self.edits[self.start..],
};
state_at(&v, p[0], p[1], p[2])
}
fn set(&mut self, p: [i32; 3], s: BlockState) {
if !is_valid_pos(p[0], p[1], p[2]) || !self.w.is_chunk_loaded(p[0] >> 4, p[2] >> 4) {
return;
}
let old = self.get(p);
if old == s {
return;
}
if old.block().id() == MOVING_PISTON
&& s.block().id() != MOVING_PISTON
&& let Some(i) = self.pistons.index_at(p)
{
self.pistons.blocks[i].removed = true;
}
self.edits.push((p, s));
}
fn add_moving(
&mut self,
pos: [i32; 3],
pushed: BlockState,
facing: Facing,
extending: bool,
source: bool,
) {
if !is_valid_pos(pos[0], pos[1], pos[2])
|| !self.w.is_chunk_loaded(pos[0] >> 4, pos[2] >> 4)
{
return;
}
self.pistons.add(MovingBlock {
pos,
pushed,
facing,
extending,
source,
progress: 0.0,
last_progress: 0.0,
removed: false,
stale: false,
});
}
fn finish(&mut self, i: usize) {
let b = self.pistons.blocks[i];
if b.last_progress < 1.0 {
let m = &mut self.pistons.blocks[i];
m.progress = 1.0;
m.last_progress = 1.0;
m.removed = true;
if self.get(b.pos).block().id() == MOVING_PISTON {
self.set(b.pos, b.pushed);
}
}
}
fn on_event(&mut self, pos: [i32; 3], block: u8, action: u8, data: u8) -> bool {
let state = self.get(pos);
let Some(facing) = facing_of(state) else {
return false;
};
let sticky = block == STICKY_PISTON;
match action {
0 => {
if !self.move_blocks(pos, facing, true, sticky) {
return true;
}
if is_piston(state.block().id()) {
self.set(pos, BlockState::new(state.block(), state.meta() | 8));
}
}
1 => {
if let Some(i) = self.pistons.index_at(step(pos, facing, 1)) {
self.finish(i);
}
let moving = Block::from_id(MOVING_PISTON).expect("moving piston");
self.set(
pos,
BlockState::new(moving, facing | if sticky { 8 } else { 0 }),
);
let base = Block::from_id(block).unwrap_or(state.block());
self.add_moving(pos, BlockState::new(base, data & 15), facing, false, true);
if sticky {
let p2 = step(pos, facing, 2);
let b = self.get(p2);
let mut finished = false;
if b.block().id() == MOVING_PISTON
&& let Some(i) = self.pistons.index_at(p2)
&& self.pistons.blocks[i].facing == facing
&& self.pistons.blocks[i].extending
{
self.finish(i);
finished = true;
}
let id = b.block().id();
if !finished
&& !b.is_air()
&& self.movable(b, p2, opposite(facing), false)
&& (behaviour(id) == Behaviour::Normal || is_piston(id))
{
self.move_blocks(pos, facing, false, sticky);
}
} else {
self.set(step(pos, facing, 1), BlockState::AIR);
}
}
_ => {}
}
true
}
fn movable(&self, b: BlockState, p: [i32; 3], dir: Facing, can_break: bool) -> bool {
let id = b.block().id();
if id == OBSIDIAN {
return false;
}
if !self.w.world_border().contains_block(p[0], p[2]) {
return false;
}
if p[1] < 0 || (dir == 0 && p[1] == 0) || p[1] > 255 || (dir == 1 && p[1] == 255) {
return false;
}
if is_piston(id) {
if self.get(p).meta() & 8 != 0 {
return false;
}
} else {
if unbreakable(id) {
return false;
}
match behaviour(id) {
Behaviour::Block => return false,
Behaviour::Destroy => return can_break,
Behaviour::Normal => {}
}
}
!has_block_entity(id)
}
fn move_blocks(&mut self, pos: [i32; 3], facing: Facing, extend: bool, sticky: bool) -> bool {
if !extend {
self.set(step(pos, facing, 1), BlockState::AIR);
}
let mut h = Handler::new(pos, facing, extend);
if !h.calculate(self) {
return false;
}
let push = if extend { facing } else { opposite(facing) };
for &b in h.broken.iter().rev() {
self.set(b, BlockState::AIR);
}
let moving = Block::from_id(MOVING_PISTON).expect("moving piston");
for &m in h.moved.iter().rev() {
let s = self.get(m);
self.set(m, BlockState::AIR);
let dst = step(m, push, 1);
self.set(dst, BlockState::new(moving, facing));
self.add_moving(dst, s, facing, extend, false);
}
if extend {
let head_pos = step(pos, facing, 1);
let t = if sticky { 8 } else { 0 };
let head = Block::from_id(PISTON_HEAD).expect("piston head");
self.set(head_pos, BlockState::new(moving, facing | t));
self.add_moving(
head_pos,
BlockState::new(head, facing | t),
facing,
true,
false,
);
}
true
}
}
struct Handler {
from: [i32; 3],
to: [i32; 3],
dir: Facing,
moved: Vec<[i32; 3]>,
broken: Vec<[i32; 3]>,
}
impl Handler {
fn new(pos: [i32; 3], facing: Facing, extend: bool) -> Handler {
let (dir, to) = if extend {
(facing, step(pos, facing, 1))
} else {
(opposite(facing), step(pos, facing, 2))
};
Handler {
from: pos,
to,
dir,
moved: Vec::new(),
broken: Vec::new(),
}
}
fn calculate<W: BlockView<State = BlockState>>(&mut self, ov: &Overlay<'_, W>) -> bool {
self.moved.clear();
self.broken.clear();
let b = ov.get(self.to);
if !ov.movable(b, self.to, self.dir, false) {
if behaviour(b.block().id()) != Behaviour::Destroy {
return false;
}
self.broken.push(self.to);
return true;
}
if !self.try_move(ov, self.to) {
return false;
}
let mut i = 0;
while i < self.moved.len() {
let p = self.moved[i];
if ov.get(p).block().id() == SLIME && !self.move_adjacent(ov, p) {
return false;
}
i += 1;
}
true
}
fn try_move<W: BlockView<State = BlockState>>(
&mut self,
ov: &Overlay<'_, W>,
pos: [i32; 3],
) -> bool {
let mut b = ov.get(pos);
if b.is_air()
|| !ov.movable(b, pos, self.dir, false)
|| pos == self.from
|| self.moved.contains(&pos)
{
return true;
}
let back = opposite(self.dir);
let mut i = 1usize;
if i + self.moved.len() > PUSH_LIMIT {
return false;
}
while b.block().id() == SLIME {
let bp = step(pos, back, i as i32);
b = ov.get(bp);
if b.is_air() || !ov.movable(b, bp, self.dir, false) || bp == self.from {
break;
}
i += 1;
if i + self.moved.len() > PUSH_LIMIT {
return false;
}
}
let mut j = 0usize;
for k in (0..i).rev() {
self.moved.push(step(pos, back, k as i32));
j += 1;
}
let mut l = 1;
loop {
let bp = step(pos, self.dir, l);
if let Some(m) = self.moved.iter().position(|&p| p == bp) {
self.reorder(j, m);
for n in 0..=m + j {
let p = self.moved[n];
if ov.get(p).block().id() == SLIME && !self.move_adjacent(ov, p) {
return false;
}
}
return true;
}
let b = ov.get(bp);
if b.is_air() {
return true;
}
if !ov.movable(b, bp, self.dir, true) || bp == self.from {
return false;
}
if behaviour(b.block().id()) == Behaviour::Destroy {
self.broken.push(bp);
return true;
}
if self.moved.len() >= PUSH_LIMIT {
return false;
}
self.moved.push(bp);
j += 1;
l += 1;
}
}
fn reorder(&mut self, from: usize, to: usize) {
let n = self.moved.len();
let mut v = Vec::with_capacity(n);
v.extend_from_slice(&self.moved[..to]);
v.extend_from_slice(&self.moved[n - from..]);
v.extend_from_slice(&self.moved[to..n - from]);
self.moved = v;
}
fn move_adjacent<W: BlockView<State = BlockState>>(
&mut self,
ov: &Overlay<'_, W>,
pos: [i32; 3],
) -> bool {
for d in 0..6 {
if axis(d) != axis(self.dir) && !self.try_move(ov, step(pos, d, 1)) {
return false;
}
}
true
}
}
pub fn tick_with_pistons<W: BlockView<State = BlockState>>(
p: &mut PlayerState,
input: &TickInput,
world: &W,
options: &Options,
pistons: &mut Pistons,
out: &mut Packets,
edits: &mut Edits,
) {
let view = Distinct(world);
tick_with_moving(p, input, &view, options, pistons, out);
tick_moving(Some(p), world, options, pistons, &mut [], &[], edits);
}
pub fn tick_player_among_pistons<W: BlockView<State = BlockState>>(
p: &mut PlayerState,
input: &TickInput,
world: &W,
options: &Options,
pistons: &Pistons,
out: &mut Packets,
) {
let view = Distinct(world);
tick_with_moving(p, input, &view, options, pistons, out);
}
struct Distinct<'a, W>(&'a W);
impl<W: BlockView<State = BlockState>> BlockView for Distinct<'_, W> {
type State = BlockState;
#[inline(always)]
fn block(&self, x: i32, y: i32, z: i32) -> BlockState {
self.0.block(x, y, z)
}
#[inline(always)]
fn is_chunk_loaded(&self, cx: i32, cz: i32) -> bool {
self.0.is_chunk_loaded(cx, cz)
}
#[inline(always)]
fn world_border(&self) -> WorldBorder {
self.0.world_border()
}
}
fn tick_moving<W: BlockView<State = BlockState>>(
mut p: Option<&mut PlayerState>,
world: &W,
options: &Options,
pistons: &mut Pistons,
others: &mut [PistonEntity],
solids: &[(Aabb, [i32; 3])],
edits: &mut Edits,
) {
let border = world.world_border();
let start = edits.len();
let mut i = 0;
while i < pistons.blocks.len() {
let b = pistons.blocks[i];
i += 1;
if b.stale {
pistons.blocks[i - 1].stale = false;
if let Some(j) = pistons.index_at(b.pos) {
pistons.blocks[j].removed = true;
}
continue;
}
if b.removed || !(0..256).contains(&b.pos[1]) || !border.contains_block(b.pos[0], b.pos[2])
{
continue;
}
let m = &mut pistons.blocks[i - 1];
m.last_progress = m.progress;
if m.last_progress >= 1.0 {
let m = *m;
if p.is_some() || !others.is_empty() {
let mut a = Pushes {
p: p.as_deref_mut(),
others,
solids,
};
push(
&mut a,
world,
options,
pistons,
&edits[start..],
&m,
1.0,
0.25,
);
}
pistons.blocks[i - 1].removed = true;
let mut ov = Overlay {
w: world,
edits,
start,
pistons,
};
if ov.get(m.pos).block().id() == MOVING_PISTON {
ov.set(m.pos, m.pushed);
}
} else {
m.progress += 0.5;
if m.progress >= 1.0 {
m.progress = 1.0;
}
let m = *m;
if m.extending && (p.is_some() || !others.is_empty()) {
let distance = m.progress - m.last_progress + 0.0625;
let mut a = Pushes {
p: p.as_deref_mut(),
others,
solids,
};
push(
&mut a,
world,
options,
pistons,
&edits[start..],
&m,
m.progress,
distance,
);
}
}
}
pistons.drop_removed();
}
struct Pushes<'a, 'b, 'c> {
p: Option<&'a mut PlayerState>,
others: &'b mut [PistonEntity],
solids: &'c [(Aabb, [i32; 3])],
}
#[allow(clippy::too_many_arguments)]
fn push<W: BlockView<State = BlockState>>(
a: &mut Pushes<'_, '_, '_>,
world: &W,
options: &Options,
pistons: &mut Pistons,
edits: &[([i32; 3], BlockState)],
m: &MovingBlock,
progress: f32,
distance: f32,
) {
let progress = if m.extending {
1.0 - progress
} else {
progress - 1.0
};
let view = Layered { w: world, edits };
let bx = match pistons.shape(&view, m.pushed, m.pos, progress, m.facing) {
None => return,
Some(Shape::Exact(b)) => b,
Some(Shape::Unknown(hull)) => {
unknown_push(a, pistons, &hull);
return;
}
};
let o = offset(m.facing);
let slime = m.pushed.block().id() == SLIME && m.extending;
let d = [
f64::from(distance * o[0] as f32),
f64::from(distance * o[1] as f32),
f64::from(distance * o[2] as f32),
];
if m.pushed.block().id() == PISTON_HEAD && pistons.head_unknown.get() != 0 {
plate_check(a, pistons, m, progress, &bx);
}
if let Some(p) = a.p.as_deref_mut()
&& !p.spectator
&& p.bb.intersects(&bx)
{
if slime {
let axis = axis(m.facing) as usize;
let i = [1, 2, 0][axis];
p.vel[i] = f64::from(o[i]);
} else {
push_move(p, &view, options, pistons, d);
}
}
if a.others.is_empty() {
return;
}
push_others(a, &view, options, pistons, &bx, slime, d);
}
#[cold]
#[inline(never)]
fn unknown_push(a: &Pushes<'_, '_, '_>, pistons: &mut Pistons, hull: &Aabb) {
let player =
a.p.as_deref()
.is_some_and(|p| !p.spectator && p.bb.intersects(hull));
let other = a
.others
.iter()
.any(|e| e.moved && search_finds(e.section, hull) && e.bb.intersects(hull));
if player || other {
pistons.unmodelled = true;
}
}
#[cold]
#[inline(never)]
fn plate_check(
a: &Pushes<'_, '_, '_>,
pistons: &mut Pistons,
m: &MovingBlock,
progress: f32,
bx: &Aabb,
) {
let mask = pistons.head_unknown.get();
for (f, plate) in HEAD_PLATE.into_iter().chain([FULL]).enumerate() {
if mask & (1 << f) == 0 {
continue;
}
let alt = shrunk_box(m.pushed, m.pos, progress, m.facing, plate);
let differs = |bb: &Aabb| bb.intersects(bx) != alt.is_some_and(|b| bb.intersects(&b));
let player =
a.p.as_deref()
.is_some_and(|p| !p.spectator && differs(&p.bb));
let other = a
.others
.iter()
.any(|e| e.moved && search_finds(e.section, bx) && differs(&e.bb));
if player || other {
pistons.unmodelled = true;
return;
}
}
}
#[cold]
#[inline(never)]
fn push_others<W: BlockView<State = BlockState>>(
a: &mut Pushes<'_, '_, '_>,
world: &W,
options: &Options,
pistons: &mut Pistons,
bx: &Aabb,
slime: bool,
d: [f64; 3],
) {
let mut solids: Vec<Aabb> = Vec::new();
for e in a.others.iter_mut() {
if !e.moved || !search_finds(e.section, bx) || !e.bb.intersects(bx) {
continue;
}
if !e.followed {
pistons.unmodelled = true;
continue;
}
if slime {
continue;
}
let q = e.bb.stretch(d[0], d[1], d[2]).grow(0.25, 0.25, 0.25);
solids.clear();
solids.extend(
a.solids
.iter()
.filter(|s| search_finds(s.1, &q))
.map(|s| s.0),
);
other_push_move(
&mut e.bb,
&mut e.pos,
&mut e.on_ground,
&mut e.in_web,
e.sneaking,
e.step_height,
&solids,
world,
options,
pistons,
d,
);
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Read;
#[test]
fn facts_match_oracle_dump() {
let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../tests/golden/1.8.9/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 id = v["id"].as_u64().unwrap() as u8;
let b = match v["piston"].as_u64().unwrap() {
0 => Behaviour::Normal,
1 => Behaviour::Destroy,
_ => Behaviour::Block,
};
assert!(behaviour(id) == b, "behaviour of {id}");
assert_eq!(
unbreakable(id),
v["unbreakable"].as_bool().unwrap(),
"strength of {id}"
);
assert_eq!(
has_block_entity(id),
v["block_entity"].as_bool().unwrap(),
"block entity of {id}"
);
let air = Block::from_id(id).is_some_and(|b| b.default_state().is_air());
assert_eq!(air, v["air"].as_bool().unwrap(), "air of {id}");
n += 1;
}
assert_eq!(n, 198);
}
#[test]
fn shrink_hull_holds_every_shared_box() {
let mut cands = vec![
FULL,
[0.0, 0.0, 0.0, 1.0, 0.5, 1.0],
[0.0, 0.5, 0.0, 1.0, 1.0, 1.0],
[0.0, 0.40625, 0.0, 1.0, 0.59375, 1.0],
];
for t in 0..16u16 {
cands.extend(own_box(BlockState::from_raw_vanilla(96 << 4 | t)));
}
cands.extend((0..8).map(stairs_ray_bounds));
for c in 0..16u8 {
let l = [c & 1 != 0, c & 2 != 0, c & 4 != 0, c & 8 != 0];
cands.push(fence_union(l));
cands.push(pane_union(l));
let (x, z) = pane_bars(l);
cands.extend(x);
cands.extend(z);
}
for pos in [[0, 64, 0], [-3, 70, 5], [7, 1, -9]] {
for facing in 0..6 {
for p in [-1.0f32, -0.75, -0.5, -0.25, 0.0, 0.25, 0.5, 0.75, 1.0] {
let h = shrink_hull(pos, p, facing);
for c in &cands {
let b = shrink(*c, pos, p, facing);
assert!(
h.min_x <= b.min_x
&& h.min_y <= b.min_y
&& h.min_z <= b.min_z
&& b.max_x <= h.max_x
&& b.max_y <= h.max_y
&& b.max_z <= h.max_z,
"{c:?} at {pos:?} facing {facing} progress {p}: {b:?} outside {h:?}"
);
}
}
}
}
}
#[test]
fn empty_pistons_take_the_plain_tick() {
let mut w = super::super::memory_world();
w.load_chunks(-1, -1, 0, 0);
w.fill_raw([-4, 63, -4], [4, 63, 4], 1 << 4);
let mut a = PlayerState::new([0.5, 64.0, 0.5], 0.0, 0.0);
let mut b = a;
let input = TickInput::default();
let (mut oa, mut ob) = (Packets::new(), Packets::new());
let mut edits = Edits::new();
for _ in 0..20 {
oa.clear();
ob.clear();
super::super::tick_with(&mut a, &input, &w, &Options::default(), &mut oa);
tick_with_pistons(
&mut b,
&input,
&w,
&Options::default(),
&mut Pistons::new(),
&mut ob,
&mut edits,
);
assert_eq!(a, b);
assert_eq!(oa.as_slice(), ob.as_slice());
}
assert!(edits.is_empty());
}
}