use ghast_data::v1_16_5::{Block, BlockState, Property};
use super::blocks::ShapeCtx;
use super::blocks::{Shape, collision_shape};
use super::collide::{BorderShape, Collider, WithMoving};
use super::fluid::V3;
use super::piston_shapes::SOURCE_SHAPES;
use super::piston_updates::{UpdateView, face_covers, neighbor_update, side};
use super::player::{PlayerState, PlayerStepCtx, piston_move, tick_with_moving};
use super::{PlayerExt, Surroundings};
use crate::input::{Packets, TickInput};
use crate::math::{Aabb, BoxOps, sorted_box};
use crate::voxel::{Points, VoxelShape};
use crate::world::{BlockView, WorldBorder};
pub type Facing = u8;
const PUSH_LIMIT: usize = 12;
const CLIENT_HOLD: u8 = 5;
const MAX_DEPTH: u32 = 512;
#[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]
const fn axis_index(f: Facing) -> usize {
[1, 2, 0][(f >> 1) as usize]
}
#[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]
}
const FACING_NAMES: [&str; 6] = ["down", "up", "north", "south", "west", "east"];
#[deprecated(
since = "0.4.9",
note = "the client's shape updates are modelled; see `Pistons::take_unmodelled`"
)]
#[must_use]
pub fn follows_neighbours(b: Block) -> bool {
const SHAPED: [&str; 10] = [
"north", "east", "south", "west", "up", "down", "shape", "in_wall", "snowy", "type",
];
let name = b.name();
name.ends_with("_carpet")
|| name == "snow"
|| name.ends_with("rail")
|| b.properties().any(|d| {
let n = d.property.name();
SHAPED.contains(&n) && (n != "type" || d.values.contains(&"left"))
})
}
#[deprecated(
since = "0.4.9",
note = "the edits include the client's shape updates; use `Pistons::take_unmodelled`"
)]
#[allow(deprecated)]
#[must_use]
pub fn edits_need_shape_updates<W: BlockView<State = BlockState>>(
world: &W,
edits: &[([i32; 3], BlockState)],
) -> bool {
let v = Layered { w: world, edits };
edits.iter().any(|&(p, s)| {
follows_neighbours(s.block())
|| (0..6).any(|f| {
let q = step(p, f, 1);
follows_neighbours(v.block(q[0], q[1], q[2]).block())
})
})
}
fn prop(name: &str) -> Property {
Property::from_name(name).expect("1.16.5 property")
}
fn facing_of(s: BlockState) -> Option<Facing> {
let v = s.get(prop("facing"))?;
FACING_NAMES
.iter()
.position(|n| *n == v)
.map(|i| i as Facing)
}
fn with(s: BlockState, p: &str, v: &str) -> BlockState {
s.with(prop(p), v).expect("1.16.5 state property")
}
fn is_piston(b: Block) -> bool {
b == Block::PISTON || b == Block::STICKY_PISTON
}
fn is_sticky_block(b: Block) -> bool {
b == Block::SLIME_BLOCK || b == Block::HONEY_BLOCK
}
fn stuck(a: Block, b: Block) -> bool {
if (a == Block::HONEY_BLOCK && b == Block::SLIME_BLOCK)
|| (a == Block::SLIME_BLOCK && b == Block::HONEY_BLOCK)
{
return false;
}
is_sticky_block(a) || is_sticky_block(b)
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Behaviour {
Normal,
Destroy,
Block,
PushOnly,
}
fn behaviour(id: u16) -> Behaviour {
match id {
19..=24
| 26..=27
| 59..=64
| 75..=90
| 94..=99
| 119..=133
| 141..=144
| 148
| 152
| 161..=162
| 171..=179
| 181..=184
| 187
| 189
| 192
| 198..=199
| 202..=205
| 244..=249
| 254
| 258
| 265
| 267
| 271..=272
| 281..=325
| 330..=332
| 410..=415
| 485..=489
| 491..=492
| 497
| 507
| 509..=525
| 574..=575
| 577
| 593..=597
| 603..=607
| 613..=618
| 621..=623
| 626
| 666
| 677..=679
| 682
| 688
| 690..=691
| 697
| 699..=703
| 708..=709
| 718..=721
| 738..=741
| 757..=758 => Behaviour::Destroy,
93 | 100..=101 | 118 | 201 | 262 | 326..=328 | 378 | 499 | 673 | 742 => Behaviour::Block,
526..=541 => Behaviour::PushOnly,
_ => Behaviour::Normal,
}
}
fn unbreakable(id: u16) -> bool {
matches!(
id,
25 | 118 | 201 | 262..=263 | 277 | 378 | 499..=501 | 726..=727
)
}
fn has_block_entity(id: u16) -> bool {
matches!(
id,
70 | 75..=90
| 118
| 145
| 147
| 154..=160
| 165..=170
| 190
| 259..=260
| 262
| 270
| 277..=278
| 314..=325
| 329
| 332..=333
| 336
| 342
| 416..=447
| 499..=501
| 509..=525
| 620
| 668..=670
| 674
| 677
| 680..=681
| 722..=727
| 730..=731
)
}
#[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,
pub hold: u8,
removed: bool,
}
impl MovingBlock {
fn moves(&self) -> Facing {
if self.extending {
self.facing
} else {
opposite(self.facing)
}
}
fn shift(&self, p: f32) -> f32 {
if self.extending { p - 1.0 } else { 1.0 - p }
}
fn head_state(&self) -> BlockState {
if !self.extending && self.source && is_piston(self.pushed.block()) {
let f = facing_of(self.pushed).unwrap_or(self.facing);
let mut h = with(
Block::PISTON_HEAD.default_state(),
"facing",
FACING_NAMES[f as usize],
);
h = with(
h,
"short",
if self.progress > 0.25 {
"true"
} else {
"false"
},
);
if self.pushed.block() == Block::STICKY_PISTON {
h = with(h, "type", "sticky");
}
h
} else {
self.pushed
}
}
}
pub type Edits = Vec<([i32; 3], BlockState)>;
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Pistons {
blocks: Vec<MovingBlock>,
delta: [f64; 3],
delta_time: i64,
unmodelled: bool,
}
impl Pistons {
#[must_use]
pub const fn new() -> Pistons {
Pistons {
blocks: Vec::new(),
delta: [0.0; 3],
delta_time: 0,
unmodelled: false,
}
}
#[inline]
#[must_use]
pub fn is_empty(&self) -> bool {
self.blocks.is_empty()
}
pub fn take_unmodelled(&mut self) -> bool {
std::mem::take(&mut self.unmodelled)
}
pub fn iter(&self) -> impl Iterator<Item = &MovingBlock> {
self.blocks.iter().filter(|b| !b.removed)
}
#[must_use]
pub fn touches(&self, bb: &Aabb) -> bool {
self.iter().any(|m| {
bb.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,
))
})
}
#[deprecated(
since = "0.4.9",
note = "moving multi-box blocks are modelled; always false"
)]
#[must_use]
pub fn untracked_near(&self, _bb: &Aabb) -> bool {
false
}
#[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 reset_player(&mut self) {
self.delta = [0.0; 3];
self.delta_time = 0;
}
pub fn retain(&mut self, mut keep: impl FnMut(&MovingBlock) -> bool) {
self.blocks.retain(|b| !b.removed && keep(b));
}
pub fn block_changed(&mut self, pos: [i32; 3], old: BlockState, new: BlockState) {
if old.block() == Block::MOVING_PISTON
&& new.block() != Block::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;
}
b.removed = false;
self.blocks.push(b);
}
fn drop_removed(&mut self) {
self.blocks.retain(|b| !b.removed);
}
pub fn block_event<W: BlockView<State = BlockState>>(
&mut self,
world: &W,
pos: [i32; 3],
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, action, data);
self.drop_removed();
r
}
pub fn tick_blocks<W: BlockView<State = BlockState>>(
&mut self,
world: &W,
time: i64,
edits: &mut Edits,
) {
if !self.is_empty() {
let mut cx = Actors {
p: None,
others: &mut [],
player_rank: 0,
player_section: None,
};
tick_moving(&mut cx, world, time, self, edits);
}
}
}
#[derive(Default)]
pub(crate) struct MovingShapes {
shapes: Vec<([i32; 3], Placed)>,
unions: Vec<UnionShape>,
}
#[derive(Clone, Copy)]
enum Placed {
Owned(OwnedShape),
Static(VoxelShape<'static>, bool),
Union(usize),
}
#[derive(Clone, Debug, Default, PartialEq)]
struct UnionShape {
pts: [Vec<f64>; 3],
cells: Vec<u64>,
}
impl UnionShape {
fn of(boxes: impl Iterator<Item = Aabb> + Clone) -> Option<UnionShape> {
const EPS: f64 = 1.0e-7;
let lo = |b: &Aabb, a: usize| [b.min_x, b.min_y, b.min_z][a];
let hi = |b: &Aabb, a: usize| [b.max_x, b.max_y, b.max_z][a];
let res = |l: f64, h: f64| -> Option<u32> {
if l < -EPS || h > 1.000_000_1 {
return None;
}
(0..=3).find(|&i| {
let k = f64::from(1u32 << i);
let (d, e) = (l * k, h * k);
(d - d.floor()).abs() < EPS && (e - e.floor()).abs() < EPS
})
};
let mut pts: [Vec<f64>; 3] = Default::default();
let mut used: Vec<Aabb> = Vec::new();
for b in boxes {
let r = [
res(b.min_x, b.max_x),
res(b.min_y, b.max_y),
res(b.min_z, b.max_z),
];
match r {
[Some(0), Some(0), Some(0)] => {
let inside = (0..3).all(|a| 0.5 >= lo(&b, a) && 0.5 < hi(&b, a));
if !inside {
continue;
}
for p in &mut pts {
p.extend([0.0, 1.0]);
}
}
[Some(i), Some(j), Some(k)] => {
for (a, n) in [i, j, k].into_iter().enumerate() {
let n = 1u32 << n;
pts[a].extend((0..=n).map(|q| f64::from(q) / f64::from(n)));
}
}
_ => {
for (a, p) in pts.iter_mut().enumerate() {
p.extend([lo(&b, a), hi(&b, a)]);
}
}
}
used.push(b);
}
if used.is_empty() {
return None;
}
for p in &mut pts {
p.sort_by(f64::total_cmp);
let mut kept: Vec<f64> = Vec::with_capacity(p.len());
for &v in p.iter() {
if kept.last().is_none_or(|&l| l < v - EPS) {
kept.push(v);
}
}
*p = kept;
}
let index = |a: usize, v: f64, p: &[Vec<f64>; 3]| {
p[a].iter().rposition(|&q| q <= v + EPS).unwrap_or(0)
};
let n = [pts[0].len() - 1, pts[1].len() - 1, pts[2].len() - 1];
let mut cells = vec![0u64; (n[0] * n[1] * n[2]).div_ceil(64)];
for b in &used {
let r: [(usize, usize); 3] =
std::array::from_fn(|a| (index(a, lo(b, a), &pts), index(a, hi(b, a), &pts)));
for x in r[0].0..r[0].1 {
for y in r[1].0..r[1].1 {
for z in r[2].0..r[2].1 {
let i = (x * n[1] + y) * n[2] + z;
cells[i / 64] |= 1 << (i % 64);
}
}
}
}
Some(UnionShape { pts, cells })
}
fn view(&self) -> VoxelShape<'_> {
VoxelShape {
axes: [
Points::Explicit(&self.pts[0]),
Points::Explicit(&self.pts[1]),
Points::Explicit(&self.pts[2]),
],
cells: &self.cells,
}
}
}
#[derive(Clone, Copy)]
struct OwnedShape {
simple: Option<[u32; 3]>,
pts: [[f64; 2]; 3],
cells: [u64; 8],
full: bool,
}
impl OwnedShape {
fn view(&self) -> VoxelShape<'_> {
let axes = match self.simple {
Some(n) => [
Points::Fractional(n[0]),
Points::Fractional(n[1]),
Points::Fractional(n[2]),
],
None => [
Points::Explicit(&self.pts[0]),
Points::Explicit(&self.pts[1]),
Points::Explicit(&self.pts[2]),
],
};
VoxelShape {
axes,
cells: &self.cells,
}
}
fn cuboid(b: &Aabb) -> Option<OwnedShape> {
let (x0, y0, z0, x1, y1, z1) = (b.min_x, b.min_y, b.min_z, b.max_x, b.max_y, b.max_z);
let res = |lo: f64, hi: f64| -> Option<u32> {
if lo < -1.0e-7 || hi > 1.000_000_1 {
return None;
}
(0..=3).find(|&i| {
let k = f64::from(1u32 << i);
let (d, e) = (lo * k, hi * k);
(d - d.floor()).abs() < 1.0e-7 && (e - e.floor()).abs() < 1.0e-7
})
};
let mut s = OwnedShape {
simple: None,
pts: [[x0, x1], [y0, y1], [z0, z1]],
cells: [0; 8],
full: false,
};
match (res(x0, x1), res(y0, y1), res(z0, z1)) {
(Some(0), Some(0), Some(0)) => {
let inside =
0.5 >= x0 && 0.5 < x1 && 0.5 >= y0 && 0.5 < y1 && 0.5 >= z0 && 0.5 < z1;
if !inside {
return None;
}
s.simple = Some([1, 1, 1]);
s.cells[0] = 1;
s.full = true;
}
(Some(i), Some(j), Some(k)) => {
let (l, m, n) = (1u32 << i, 1u32 << j, 1u32 << k);
let r = |v: f64, k: u32| (v * f64::from(k)).round() as i64;
let (o, p) = (r(x0, l), r(x1, l));
let (q, rr) = (r(y0, m), r(y1, m));
let (t, u) = (r(z0, n), r(z1, n));
s.simple = Some([l, m, n]);
for x in o..p {
for y in q..rr {
for z in t..u {
let idx = ((x as u32 * m + y as u32) * n + z as u32) as usize;
s.cells[idx / 64] |= 1 << (idx % 64);
}
}
}
}
_ => s.cells[0] = 1,
}
Some(s)
}
}
impl MovingShapes {
pub(crate) fn of(pistons: &Pistons, pushing: Option<Facing>) -> MovingShapes {
let mut out = MovingShapes::default();
for m in pistons.iter() {
out.add_block(m, pushing);
}
out
}
fn add_block(&mut self, m: &MovingBlock, pushing: Option<Facing>) {
let excluded = m.progress < 1.0 && pushing == Some(m.moves());
if excluded {
if !m.extending
&& m.source
&& let Shape::Grid { shape, full_cube } = collision_shape(
with(m.pushed, "extended", "true"),
m.pos[0],
m.pos[1],
m.pos[2],
None,
)
{
self.shapes.push((m.pos, Placed::Static(shape, full_cube)));
}
return;
}
if m.source {
let k = if m.extending {
0
} else if m.pushed.block() == Block::STICKY_PISTON {
2
} else {
1
};
let pi = if m.progress == 0.0 {
Some(0)
} else if m.progress == 0.5 {
Some(1)
} else if m.progress == 1.0 {
Some(2)
} else {
None
};
if let Some(pi) = pi {
let t = &SOURCE_SHAPES[m.facing as usize][k][pi];
let axes = if t.simple {
[
Points::Fractional(t.sizes[0] as u32),
Points::Fractional(t.sizes[1] as u32),
Points::Fractional(t.sizes[2] as u32),
]
} else {
[
Points::Explicit(t.xs),
Points::Explicit(t.ys),
Points::Explicit(t.zs),
]
};
let full = t.simple && t.sizes == [1, 1, 1];
let shape = VoxelShape {
axes,
cells: t.cells,
};
self.shapes.push((m.pos, Placed::Static(shape, full)));
return;
}
}
let state = if m.source {
let mut h = with(
Block::PISTON_HEAD.default_state(),
"facing",
FACING_NAMES[m.facing as usize],
);
let short = m.extending != (1.0 - m.progress < 0.25);
h = with(h, "short", if short { "true" } else { "false" });
h
} else {
m.pushed
};
let f = m.shift(m.progress);
let o = offset(m.facing);
let (d, e, g) = (
f64::from(o[0] as f32 * f),
f64::from(o[1] as f32 * f),
f64::from(o[2] as f32 * f),
);
let boxes = state.collision().boxes;
let shift = |b: &Aabb| {
Aabb::new(
b.min_x + d,
b.min_y + e,
b.min_z + g,
b.max_x + d,
b.max_y + e,
b.max_z + g,
)
};
if let [b] = boxes {
if let Some(s) = OwnedShape::cuboid(&shift(b)) {
self.shapes.push((m.pos, Placed::Owned(s)));
}
} else if let Some(u) = UnionShape::of(boxes.iter().map(shift)) {
self.unions.push(u);
self.shapes
.push((m.pos, Placed::Union(self.unions.len() - 1)));
}
}
pub(crate) fn at(&self, pos: [i32; 3]) -> impl Iterator<Item = (VoxelShape<'_>, bool)> {
self.shapes
.iter()
.filter(move |(p, _)| *p == pos)
.map(|(_, s)| match s {
Placed::Owned(o) => (o.view(), o.full),
Placed::Static(v, full) => (*v, *full),
Placed::Union(i) => (self.unions[*i].view(), false),
})
}
}
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,
}
#[inline]
fn valid(p: [i32; 3]) -> bool {
(0..256).contains(&p[1])
}
impl<W: BlockView<State = BlockState>> Overlay<'_, W> {
fn get(&self, p: [i32; 3]) -> BlockState {
if !valid(p) {
return BlockState::AIR;
}
let v = Layered {
w: self.w,
edits: &self.edits[self.start..],
};
v.block(p[0], p[1], p[2])
}
fn set(&mut self, p: [i32; 3], s: BlockState, flags: u32, depth: u32) {
if !valid(p) || !self.w.is_chunk_loaded(p[0] >> 4, p[2] >> 4) {
return;
}
let old = self.get(p);
if old == s {
return;
}
if old.block() == Block::MOVING_PISTON
&& s.block() != Block::MOVING_PISTON
&& let Some(i) = self.pistons.index_at(p)
{
self.pistons.blocks[i].removed = true;
}
self.edits.push((p, s));
if flags & 16 == 0 && depth > 0 {
if old.block() == Block::REDSTONE_WIRE || s.block() == Block::REDSTONE_WIRE {
self.pistons.unmodelled = true;
}
self.update_neighbors(p, s, flags & !33, depth - 1);
}
}
fn update_neighbors(&mut self, p: [i32; 3], s: BlockState, flags: u32, depth: u32) {
for d in 0..6 {
let q = step(p, d, 1);
let n = self.get(q);
let new = match neighbor_update(self, n, opposite(d), s, q, p) {
Ok(v) => v,
Err(v) => {
self.pistons.unmodelled = true;
v
}
};
if new != n && !new.is_air() {
self.set(q, new, flags & !32, depth);
}
}
}
fn post_process(&mut self, s: BlockState, p: [i32; 3]) -> BlockState {
let mut out = s;
for d in 0..6 {
let q = step(p, d, 1);
let n = self.get(q);
out = match neighbor_update(self, out, d, n, p, q) {
Ok(v) => v,
Err(v) => {
self.pistons.unmodelled = true;
v
}
};
}
out
}
fn remove(&mut self, p: [i32; 3]) {
let s = self.get(p);
if s.fluid().is_some() {
self.pistons.unmodelled = true;
}
self.set(p, BlockState::AIR, 3, MAX_DEPTH);
}
fn with_moving_shape<T>(&self, p: [i32; 3], f: impl FnOnce(Option<&VoxelShape<'_>>) -> T) -> T {
let Some(m) = self.pistons.at(p) else {
return f(None);
};
let mut shapes = MovingShapes::default();
shapes.add_block(m, None);
let first = shapes.at(p).next().map(|v| v.0);
f(first.as_ref())
}
fn add_moving(
&mut self,
pos: [i32; 3],
pushed: BlockState,
facing: Facing,
extending: bool,
source: bool,
) {
if !valid(pos) || !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,
hold: 0,
removed: false,
});
}
fn finish(&mut self, i: usize) {
let b = self.pistons.blocks[i];
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() == Block::MOVING_PISTON {
let s = if b.source {
BlockState::AIR
} else {
self.post_process(b.pushed, b.pos)
};
self.set(b.pos, s, 3, MAX_DEPTH);
}
}
fn moving_state(facing: Facing, sticky: bool) -> BlockState {
let s = with(
Block::MOVING_PISTON.default_state(),
"facing",
FACING_NAMES[facing as usize],
);
if sticky { with(s, "type", "sticky") } else { s }
}
fn on_event(&mut self, pos: [i32; 3], action: u8, data: u8) -> bool {
let state = self.get(pos);
if !is_piston(state.block()) {
return false;
}
let Some(facing) = facing_of(state) else {
return false;
};
let sticky = state.block() == Block::STICKY_PISTON;
match action {
0 => {
if !self.move_blocks(pos, facing, true, sticky) {
return true;
}
self.set(pos, with(state, "extended", "true"), 67, MAX_DEPTH);
}
1 | 2 => {
if let Some(i) = self.pistons.index_at(step(pos, facing, 1)) {
self.finish(i);
}
let moving = Self::moving_state(facing, sticky);
self.set(pos, moving, 20, MAX_DEPTH);
let base = with(
state.block().default_state(),
"facing",
FACING_NAMES[(data & 7) as usize % 6],
);
self.add_moving(pos, base, facing, false, true);
self.update_neighbors(pos, moving, 2, MAX_DEPTH);
if sticky {
let p2 = step(pos, facing, 2);
let b = self.get(p2);
let mut finished = false;
if b.block() == Block::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;
}
if !finished {
let id = b.block().id();
if action != 1
|| b.is_air()
|| !self.movable(b, p2, opposite(facing), false, facing)
|| (behaviour(id) != Behaviour::Normal && !is_piston(b.block()))
{
self.remove(step(pos, facing, 1));
} else {
self.move_blocks(pos, facing, false, sticky);
}
}
} else {
self.remove(step(pos, facing, 1));
}
}
_ => {}
}
true
}
fn movable(
&self,
b: BlockState,
p: [i32; 3],
dir: Facing,
can_break: bool,
piston: Facing,
) -> bool {
if !valid(p) || !self.w.world_border().contains_block(p[0], p[2]) {
return false;
}
if b.is_air() {
return true;
}
let blk = b.block();
if blk == Block::OBSIDIAN || blk == Block::CRYING_OBSIDIAN || blk == Block::RESPAWN_ANCHOR {
return false;
}
if (dir == 0 && p[1] == 0) || (dir == 1 && p[1] == 255) {
return false;
}
if is_piston(blk) {
if b.get(prop("extended")) == Some("true") {
return false;
}
} else {
let id = blk.id();
if unbreakable(id) {
return false;
}
match behaviour(id) {
Behaviour::Block => return false,
Behaviour::Destroy => return can_break,
Behaviour::PushOnly => return dir == piston,
Behaviour::Normal => {}
}
}
!has_block_entity(blk.id())
}
fn move_blocks(&mut self, pos: [i32; 3], facing: Facing, extend: bool, sticky: bool) -> bool {
let head_pos = step(pos, facing, 1);
if !extend && self.get(head_pos).block() == Block::PISTON_HEAD {
self.set(head_pos, BlockState::AIR, 20, MAX_DEPTH);
}
let mut h = Handler::new(pos, facing, extend);
if !h.calculate(self) {
return false;
}
let states: Vec<BlockState> = h.moved.iter().map(|&m| self.get(m)).collect();
let mut vacated: Vec<([i32; 3], BlockState)> = h
.moved
.iter()
.copied()
.zip(states.iter().copied())
.collect();
let push = if extend { facing } else { opposite(facing) };
for &b in h.broken.iter().rev() {
if self.get(b).block() == Block::REDSTONE_WIRE {
self.pistons.unmodelled = true;
}
self.set(b, BlockState::AIR, 18, MAX_DEPTH);
}
for (k, &m) in h.moved.iter().enumerate().rev() {
let dst = step(m, push, 1);
vacated.retain(|v| v.0 != dst);
self.set(dst, Self::moving_state(facing, false), 68, MAX_DEPTH);
self.add_moving(dst, states[k], facing, extend, false);
}
if extend {
vacated.retain(|v| v.0 != head_pos);
self.set(head_pos, Self::moving_state(facing, sticky), 68, MAX_DEPTH);
let mut head = with(
Block::PISTON_HEAD.default_state(),
"facing",
FACING_NAMES[facing as usize],
);
if sticky {
head = with(head, "type", "sticky");
}
self.add_moving(head_pos, head, facing, true, true);
}
let order = hash_map_order(&h.moved, &vacated).unwrap_or_else(|| {
self.pistons.unmodelled = true;
(0..vacated.len()).collect()
});
for &k in &order {
self.set(vacated[k].0, BlockState::AIR, 82, MAX_DEPTH);
}
for &k in &order {
if vacated[k].1.block() == Block::REDSTONE_WIRE {
self.pistons.unmodelled = true;
}
self.update_neighbors(vacated[k].0, BlockState::AIR, 2, MAX_DEPTH);
}
true
}
}
impl<W: BlockView<State = BlockState>> UpdateView for Overlay<'_, W> {
fn state(&self, p: [i32; 3]) -> BlockState {
self.get(p)
}
fn side_solid(&self, p: [i32; 3], s: BlockState, face: Facing) -> Option<bool> {
if s.block() == Block::MOVING_PISTON {
return Some(self.with_moving_shape(p, |sh| {
sh.is_some_and(|sh| face_covers(sh, face, [0.0, 0.0, 1.0, 1.0], true))
}));
}
if s.has_dynamic_bounds() {
return None;
}
Some(s.side_solid_full_square(side(face)))
}
fn down_face_covers(&self, p: [i32; 3], s: BlockState, rect: [f64; 4]) -> Option<bool> {
if s.block() == Block::MOVING_PISTON {
return Some(
self.with_moving_shape(p, |sh| {
sh.is_some_and(|sh| face_covers(sh, 0, rect, false))
}),
);
}
if s.has_dynamic_bounds() {
return None;
}
Some(match collision_shape(s, p[0], p[1], p[2], None) {
Shape::Grid { shape, .. } => face_covers(&shape, 0, rect, false),
Shape::Empty => false,
})
}
}
fn hash_map_order(moved: &[[i32; 3]], left: &[([i32; 3], BlockState)]) -> Option<Vec<usize>> {
let bucket = |p: [i32; 3]| {
let h = (p[1].wrapping_add(p[2].wrapping_mul(31)))
.wrapping_mul(31)
.wrapping_add(p[0]);
let spread = h ^ ((h as u32) >> 16) as i32;
(spread & 15) as usize
};
let mut counts = [0usize; 16];
for &p in moved {
counts[bucket(p)] += 1;
}
if counts.iter().any(|&c| c >= 8) {
return None;
}
let mut out = Vec::with_capacity(left.len());
for b in 0..16 {
for &p in moved {
if bucket(p) == b
&& let Some(k) = left.iter().position(|v| v.0 == p)
{
out.push(k);
}
}
}
Some(out)
}
struct Handler {
from: [i32; 3],
to: [i32; 3],
motion: Facing,
piston: Facing,
extend: bool,
moved: Vec<[i32; 3]>,
broken: Vec<[i32; 3]>,
}
impl Handler {
fn new(pos: [i32; 3], facing: Facing, extend: bool) -> Handler {
let (motion, to) = if extend {
(facing, step(pos, facing, 1))
} else {
(opposite(facing), step(pos, facing, 2))
};
Handler {
from: pos,
to,
motion,
piston: facing,
extend,
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.motion, false, self.piston) {
if self.extend && behaviour(b.block().id()) == Behaviour::Destroy {
self.broken.push(self.to);
return true;
}
return false;
}
if !self.try_move(ov, self.to, self.motion) {
return false;
}
let mut i = 0;
while i < self.moved.len() {
let p = self.moved[i];
if is_sticky_block(ov.get(p).block()) && !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],
dir: Facing,
) -> bool {
let mut b = ov.get(pos);
if b.is_air()
|| !ov.movable(b, pos, self.motion, false, dir)
|| pos == self.from
|| self.moved.contains(&pos)
{
return true;
}
let back = opposite(self.motion);
let mut i = 1usize;
if i + self.moved.len() > PUSH_LIMIT {
return false;
}
while is_sticky_block(b.block()) {
let bp = step(pos, back, i as i32);
let prev = b.block();
b = ov.get(bp);
if b.is_air()
|| !stuck(prev, b.block())
|| !ov.movable(b, bp, self.motion, false, back)
|| 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.motion, 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 is_sticky_block(ov.get(p).block()) && !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.motion, true, self.motion) || 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 {
let s = ov.get(pos).block();
for d in 0..6 {
if axis(d) != axis(self.motion) {
let q = step(pos, d, 1);
if stuck(ov.get(q).block(), s) && !self.try_move(ov, q, d) {
return false;
}
}
}
true
}
}
pub(super) struct Distinct<'a, W>(pub(super) &'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()
}
}
#[allow(clippy::too_many_arguments)]
pub fn tick_with_pistons<W: BlockView<State = BlockState>>(
p: &mut PlayerState,
x: &mut PlayerExt,
around: &Surroundings<'_>,
input: &TickInput,
world: &W,
pistons: &mut Pistons,
time: i64,
out: &mut Packets,
edits: &mut Edits,
) {
tick_player_among_pistons(p, x, around, input, world, pistons, out);
pistons.tick_after_entities(p, x, around, world, time, edits);
}
pub fn tick_player_among_pistons<W: BlockView<State = BlockState>>(
p: &mut PlayerState,
x: &mut PlayerExt,
around: &Surroundings<'_>,
input: &TickInput,
world: &W,
pistons: &Pistons,
out: &mut Packets,
) {
let view = Distinct(world);
let shapes = MovingShapes::of(pistons, None);
tick_with_moving(p, x, around, input, &view, &shapes, out);
}
impl Pistons {
pub fn tick_after_entities<W: BlockView<State = BlockState>>(
&mut self,
p: &mut PlayerState,
x: &mut PlayerExt,
around: &Surroundings<'_>,
world: &W,
time: i64,
edits: &mut Edits,
) {
if !self.is_empty() {
let mut cx = Actors {
p: Some((p, x, around)),
others: &mut [],
player_rank: 0,
player_section: None,
};
tick_moving(&mut cx, world, time, self, edits);
}
}
#[allow(clippy::too_many_arguments)]
pub fn tick_after_entities_among<W: BlockView<State = BlockState>>(
&mut self,
p: &mut PlayerState,
x: &mut PlayerExt,
around: &Surroundings<'_>,
others: &mut [PistonEntity],
player: PlayerPlace,
world: &W,
time: i64,
edits: &mut Edits,
) {
if !self.is_empty() {
let mut cx = Actors {
p: Some((p, x, around)),
others,
player_rank: player.rank,
player_section: Some(player.section),
};
tick_moving(&mut cx, world, time, self, edits);
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PistonEntity {
pub bb: Aabb,
pub pos: [f64; 3],
pub on_ground: bool,
pub step_height: f32,
pub moved: bool,
pub collidable: bool,
pub pushable: bool,
pub hits_pushable: bool,
pub living: bool,
pub section: [i32; 3],
pub carry: PistonCarry,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct PlayerPlace {
pub rank: usize,
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])
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct PistonCarry {
delta: [f64; 3],
delta_time: i64,
multiplier: [f64; 3],
}
struct Actors<'a, 'b, 'c> {
p: Option<PlayerRef<'a, 'b>>,
others: &'c mut [PistonEntity],
player_rank: usize,
player_section: Option<[i32; 3]>,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Actor {
Player,
Other(usize),
}
impl Actors<'_, '_, '_> {
fn order(&self) -> impl Iterator<Item = Actor> + use<> {
let n = self.others.len();
let rank = if self.p.is_some() {
Some(self.player_rank.min(n))
} else {
None
};
(0..=n).filter_map(move |k| match rank {
Some(r) if k == r => Some(Actor::Player),
Some(r) if k > r => Some(Actor::Other(k - 1)),
_ if k < n => Some(Actor::Other(k)),
_ => None,
})
}
fn bb(&self, a: Actor) -> Aabb {
match a {
Actor::Player => self.p.as_ref().expect("player").0.bb,
Actor::Other(k) => self.others[k].bb,
}
}
fn found(&self, a: Actor, q: &Aabb) -> bool {
match a {
Actor::Player => self.player_section.is_none_or(|s| search_finds(s, q)),
Actor::Other(k) => search_finds(self.others[k].section, q),
}
}
}
type PlayerRef<'a, 'b> = (&'a mut PlayerState, &'a mut PlayerExt, &'a Surroundings<'b>);
fn tick_moving<W: BlockView<State = BlockState>>(
actors: &mut Actors<'_, '_, '_>,
world: &W,
time: i64,
pistons: &mut Pistons,
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.removed || !valid(b.pos) || !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 {
if m.hold < CLIENT_HOLD {
m.hold += 1;
continue;
}
m.removed = true;
let m = *m;
let mut ov = Overlay {
w: world,
edits,
start,
pistons,
};
if ov.get(m.pos).block() == Block::MOVING_PISTON {
let s = ov.post_process(m.pushed, m.pos);
if s.is_air() {
ov.set(m.pos, m.pushed, 84, MAX_DEPTH);
} else {
let s = s.with(prop("waterlogged"), "false").unwrap_or(s);
ov.set(m.pos, s, 67, MAX_DEPTH);
}
}
} else {
let f = m.progress + 0.5;
let m = *m;
if actors.p.is_some() {
let view = Layered {
w: world,
edits: &edits[start..],
};
let view = Distinct(&view);
let mut cx = PushCx {
a: actors,
world: &view,
time,
pistons,
};
cx.push(&m, f);
cx.honey(&m, f);
}
let m = &mut pistons.blocks[i - 1];
m.progress = f;
if m.progress >= 1.0 {
m.progress = 1.0;
}
}
}
pistons.drop_removed();
}
fn stretch(b: &Aabb, dir: Facing, d: f64) -> Aabb {
let e = if dir & 1 == 1 { d } else { -d };
let (f, g) = (e.min(0.0), e.max(0.0));
match dir {
4 => sorted_box(b.min_x + f, b.min_y, b.min_z, b.min_x + g, b.max_y, b.max_z),
5 => sorted_box(b.max_x + f, b.min_y, b.min_z, b.max_x + g, b.max_y, b.max_z),
0 => sorted_box(b.min_x, b.min_y + f, b.min_z, b.max_x, b.min_y + g, b.max_z),
2 => sorted_box(b.min_x, b.min_y, b.min_z + f, b.max_x, b.max_y, b.min_z + g),
3 => sorted_box(b.min_x, b.min_y, b.max_z + f, b.max_x, b.max_y, b.max_z + g),
_ => sorted_box(b.min_x, b.max_y + f, b.min_z, b.max_x, b.max_y + g, b.max_z),
}
}
fn reach(b: &Aabb, dir: Facing, e: &Aabb) -> f64 {
match dir {
5 => b.max_x - e.min_x,
4 => e.max_x - b.min_x,
0 => e.max_y - b.min_y,
3 => b.max_z - e.min_z,
2 => e.max_z - b.min_z,
_ => b.max_y - e.min_y,
}
}
fn union(a: &Aabb, b: &Aabb) -> Aabb {
Aabb::new(
a.min_x.min(b.min_x),
a.min_y.min(b.min_y),
a.min_z.min(b.min_z),
a.max_x.max(b.max_x),
a.max_y.max(b.max_y),
a.max_z.max(b.max_z),
)
}
fn piston_budget(
delta: &mut [f64; 3],
delta_time: &mut i64,
time: i64,
d: [f64; 3],
) -> Option<[f64; 3]> {
if d[0] * d[0] + d[1] * d[1] + d[2] * d[2] <= 1.0e-7 {
return Some(d);
}
if time != *delta_time {
*delta = [0.0; 3];
*delta_time = time;
}
let k = [0, 1, 2].into_iter().find(|&k| d[k] != 0.0)?;
let v = (d[k] + delta[k]).clamp(-0.51, 0.51);
let mv = v - delta[k];
delta[k] = v;
if mv.abs() <= f64::from(1.0e-5f32) {
return None;
}
let mut out = [0.0; 3];
out[k] = mv;
Some(out)
}
struct PushCx<'a, 'b, 'c, 'd, W> {
a: &'a mut Actors<'b, 'c, 'd>,
world: &'a W,
time: i64,
pistons: &'a mut Pistons,
}
impl<W: BlockView<State = BlockState>> PushCx<'_, '_, '_, '_, W> {
fn place(m: &MovingBlock, b: &Aabb) -> Aabb {
let d = f64::from(m.shift(m.progress));
let o = offset(m.facing);
b.offset(
f64::from(m.pos[0]) + d * f64::from(o[0]),
f64::from(m.pos[1]) + d * f64::from(o[1]),
f64::from(m.pos[2]) + d * f64::from(o[2]),
)
}
fn movable(&self, a: Actor) -> bool {
match a {
Actor::Player => !self.a.p.as_ref().expect("player").0.spectator,
Actor::Other(k) => self.a.others[k].moved,
}
}
fn push(&mut self, m: &MovingBlock, f: f32) {
let dir = m.moves();
let d = f64::from(f - m.progress);
let boxes = m.head_state().collision().boxes;
if boxes.is_empty() {
return;
}
let mut hull = boxes[0];
for b in &boxes[1..] {
hull = union(&hull, b);
}
let bx = Self::place(m, &hull);
let query = union(&stretch(&bx, dir, d), &bx);
let list: Vec<Actor> = self
.a
.order()
.filter(|&a| {
self.movable(a) && self.a.found(a, &query) && self.a.bb(a).intersects(&query)
})
.collect();
for a in list {
if m.pushed.block() == Block::SLIME_BLOCK
&& let Actor::Player = a
{
let k = axis_index(dir);
self.a.p.as_mut().expect("player").0.vel[k] = f64::from(offset(dir)[k]);
}
let mut h: f64 = 0.0;
for b in boxes {
let b3 = stretch(&Self::place(m, b), dir, d);
let bb = self.a.bb(a);
if b3.intersects(&bb) {
h = h.max(reach(&b3, dir, &bb));
if h >= d {
break;
}
}
}
#[allow(clippy::neg_cmp_op_on_partial_ord)]
if !(h <= 0.0) {
let h = h.min(d) + 0.01;
self.move_by_piston(a, dir, dir, h);
if !m.extending && m.source {
self.pull_back(a, m, dir, d);
}
}
}
}
fn pull_back(&mut self, a: Actor, m: &MovingBlock, dir: Facing, amount: f64) {
let bb = self.a.bb(a);
let cell = Aabb::FULL.offset(
f64::from(m.pos[0]),
f64::from(m.pos[1]),
f64::from(m.pos[2]),
);
if !bb.intersects(&cell) {
return;
}
let back = opposite(dir);
let d = reach(&cell, back, &bb) + 0.01;
let inter = sorted_box(
bb.min_x.max(cell.min_x),
bb.min_y.max(cell.min_y),
bb.min_z.max(cell.min_z),
bb.max_x.min(cell.max_x),
bb.max_y.min(cell.max_y),
bb.max_z.min(cell.max_z),
);
let e = reach(&cell, back, &inter) + 0.01;
if (d - e).abs() < 0.01 {
let d = d.min(amount) + 0.01;
self.move_by_piston(a, dir, back, d);
}
}
fn honey(&mut self, m: &MovingBlock, f: f32) {
if m.pushed.block() != Block::HONEY_BLOCK {
return;
}
let dir = m.moves();
if axis(dir) == 0 {
return;
}
let top = m
.pushed
.collision()
.boxes
.iter()
.map(|b| b.max_y)
.fold(f64::NEG_INFINITY, f64::max);
let bx = Self::place(
m,
&Aabb::new(0.0, top, 0.0, 1.0, 1.500_000_099_999_999_8, 1.0),
);
let e = f64::from(f - m.progress);
let stands = |bb: &Aabb, pos: [f64; 3], on_ground: bool| {
on_ground
&& bb.intersects(&bx)
&& pos[0] >= bx.min_x
&& pos[0] <= bx.max_x
&& pos[2] >= bx.min_z
&& pos[2] <= bx.max_z
};
let list: Vec<Actor> = self
.a
.order()
.filter(|&a| {
self.movable(a)
&& self.a.found(a, &bx)
&& match a {
Actor::Player => {
let p = &*self.a.p.as_ref().expect("player").0;
stands(&p.bb, p.pos, p.on_ground)
}
Actor::Other(k) => {
let o = &self.a.others[k];
stands(&o.bb, o.pos, o.on_ground)
}
}
})
.collect();
for a in list {
self.move_by_piston(a, dir, dir, e);
}
}
fn move_by_piston(&mut self, a: Actor, pushing: Facing, dir: Facing, e: f64) {
let o = offset(dir);
let d = [
e * f64::from(o[0]),
e * f64::from(o[1]),
e * f64::from(o[2]),
];
match a {
Actor::Player => self.move_player(pushing, d),
Actor::Other(k) => self.move_other(k, pushing, d),
}
}
fn move_player(&mut self, pushing: Facing, d: [f64; 3]) {
let time = self.time;
let pistons = &mut *self.pistons;
let (p, x, around) = self.a.p.as_mut().expect("player");
if p.no_clip {
return;
}
let Some(d) = piston_budget(&mut pistons.delta, &mut pistons.delta_time, time, d) else {
return;
};
let shapes = MovingShapes::of(pistons, Some(pushing));
let mut boxes: Vec<Aabb>;
let around = if self.a.others.iter().any(|o| o.collidable) {
let q = super::collide::stretch(&p.bb, V3::new(d[0], d[1], d[2]))
.grow(1.0e-7, 1.0e-7, 1.0e-7);
boxes = around.entities.to_vec();
boxes.extend(
self.a
.others
.iter()
.filter(|o| o.collidable && search_finds(o.section, &q))
.map(|o| o.bb),
);
Surroundings::new()
.with_entities(&boxes)
.with_others(around.others)
} else {
**around
};
let cx = PlayerStepCtx {
x,
around: &around,
shapes: &shapes,
};
piston_move(p, cx, self.world, d);
}
fn move_other(&mut self, k: usize, pushing: Facing, d: [f64; 3]) {
let time = self.time;
let o = self.a.others[k];
let mut carry = o.carry;
let Some(mut m) = piston_budget(&mut carry.delta, &mut carry.delta_time, time, d) else {
self.a.others[k].carry = carry;
return;
};
let mm = carry.multiplier;
if mm[0] * mm[0] + mm[1] * mm[1] + mm[2] * mm[2] > 1.0e-7 {
m = [m[0] * mm[0], m[1] * mm[1], m[2] * mm[2]];
carry.multiplier = [0.0; 3];
}
let player_pushable = self.a.p.as_ref().is_some_and(|(p, _, _)| {
!p.spectator
&& !super::blocks::is_climbable_at(
self.world,
crate::math::floor(p.pos[0]),
crate::math::floor(p.pos[1]),
crate::math::floor(p.pos[2]),
)
});
let q =
super::collide::stretch(&o.bb, V3::new(m[0], m[1], m[2])).grow(1.0e-7, 1.0e-7, 1.0e-7);
let boxes: Vec<Aabb> = self
.a
.order()
.filter(|&b| self.a.found(b, &q))
.filter(|&b| match b {
Actor::Player => o.hits_pushable && player_pushable,
Actor::Other(j) => {
j != k && {
let t = &self.a.others[j];
t.collidable || (o.hits_pushable && t.pushable)
}
}
})
.map(|b| self.a.bb(b))
.collect();
let shapes = MovingShapes::of(self.pistons, Some(pushing));
let border = BorderShape::new(&self.world.world_border());
let col = Collider {
w: self.world,
border: &border,
ctx: ShapeCtx {
min_y: o.pos[1],
descending: false,
},
entities: WithMoving {
ents: &boxes,
shapes: &shapes,
},
};
let mv = V3::new(m[0], m[1], m[2]);
let v = col.adjust(mv, &o.bb, o.on_ground, o.step_height);
let t = &mut self.a.others[k];
if v.length_sq() > 1.0e-7 {
t.bb = t.bb.offset(v.x, v.y, v.z);
t.pos = [
(t.bb.min_x + t.bb.max_x) / 2.0,
t.bb.min_y,
(t.bb.min_z + t.bb.max_z) / 2.0,
];
}
t.on_ground = mv.y != v.y && mv.y < 0.0;
let c = t.bb;
let lo = |v: f64| crate::math::floor(v + 0.001);
let hi = |v: f64| crate::math::floor(v - 0.001);
for x in lo(c.min_x)..=hi(c.max_x) {
for y in lo(c.min_y)..=hi(c.max_y) {
for z in lo(c.min_z)..=hi(c.max_z) {
let b = self.world.block(x, y, z).block();
if b == Block::COBWEB {
carry.multiplier = [0.25, f64::from(0.05f32), 0.25];
} else if b == Block::SWEET_BERRY_BUSH && t.living {
carry.multiplier = [f64::from(0.8f32), 0.75, f64::from(0.8f32)];
}
}
}
}
t.carry = carry;
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Read;
#[test]
fn source_shapes_match_oracle_dump() {
let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../tests/golden/1.16.5/piston_shapes.jsonl.gz");
let mut text = String::new();
flate2::read::GzDecoder::new(std::fs::File::open(path).expect("shapes"))
.read_to_string(&mut text)
.expect("gzip");
let bits = |v: &serde_json::Value| {
f64::from_bits(u64::from_str_radix(v[1].as_str().unwrap(), 16).unwrap())
};
let mut n = 0;
for line in text.lines() {
let v: serde_json::Value = serde_json::from_str(line).unwrap();
let f = v["facing"].as_u64().unwrap() as usize;
let k = match v["kind"].as_str().unwrap() {
"head" => 0,
"base" => 1,
_ => 2,
};
let p = match v["progress"][1].as_str().unwrap() {
"00000000" => 0,
"3f000000" => 1,
_ => 2,
};
let t = &SOURCE_SHAPES[f][k][p];
assert_eq!(t.simple, v["class"] == "simple");
for (axis, pts) in [("x", t.xs), ("y", t.ys), ("z", t.zs)] {
let want: Vec<u64> = v[format!("points_{axis}")]
.as_array()
.unwrap()
.iter()
.map(|x| bits(x).to_bits())
.collect();
let got: Vec<u64> = pts.iter().map(|x| x.to_bits()).collect();
assert_eq!(got, want, "{line}");
}
for (i, c) in v["filled"].as_str().unwrap().chars().enumerate() {
assert_eq!(t.cells[i / 64] >> (i % 64) & 1 == 1, c == '1', "{line}");
}
n += 1;
}
assert_eq!(n, 54);
}
#[test]
fn moving_shapes_match_oracle_dump() {
let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../tests/golden/1.16.5/moving_shapes.jsonl.gz");
let mut text = String::new();
flate2::read::GzDecoder::new(std::fs::File::open(path).expect("moving shapes"))
.read_to_string(&mut text)
.expect("gzip");
let bits = |v: &serde_json::Value| u64::from_str_radix(v[1].as_str().unwrap(), 16).unwrap();
let mut n = 0;
for line in text.lines() {
let v: serde_json::Value = serde_json::from_str(line).unwrap();
let progress = f32::from_bits(bits(&v["progress"]) as u32);
let m = MovingBlock {
pos: [0, 0, 0],
pushed: BlockState::from_id(v["state"].as_u64().unwrap() as u16).unwrap(),
facing: v["facing"].as_u64().unwrap() as Facing,
extending: v["extending"].as_bool().unwrap(),
source: false,
progress,
last_progress: progress,
hold: 0,
removed: false,
};
let mut shapes = MovingShapes::default();
shapes.add_block(&m, None);
let got: Vec<_> = shapes.at([0, 0, 0]).collect();
assert_eq!(got.len(), 1, "{line}");
let shape = got[0].0;
for (a, axis) in ["x", "y", "z"].into_iter().enumerate() {
let want: Vec<u64> = v[format!("points_{axis}")]
.as_array()
.unwrap()
.iter()
.map(bits)
.collect();
let p = shape.axes[a];
let got: Vec<u64> = (0..=p.cells()).map(|i| p.get(i).to_bits()).collect();
assert_eq!(got, want, "{axis}: {line}");
}
for (i, c) in v["filled"].as_str().unwrap().chars().enumerate() {
assert_eq!(shape.cells[i / 64] >> (i % 64) & 1 == 1, c == '1', "{line}");
}
n += 1;
}
assert!(n > 2000);
}
#[test]
fn facts_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 id = v["block"].as_u64().unwrap() as u16;
let b = match v["piston"].as_u64().unwrap() {
0 => Behaviour::Normal,
1 => Behaviour::Destroy,
2 => Behaviour::Block,
_ => Behaviour::PushOnly,
};
assert_eq!(behaviour(id), b, "behaviour of {id}");
assert_eq!(
unbreakable(id),
v["unbreakable"].as_bool().unwrap(),
"hardness of {id}"
);
assert_eq!(
has_block_entity(id),
v["block_entity"].as_bool().unwrap(),
"block entity of {id}"
);
assert!(v["same_for_all_states"].as_bool().unwrap());
let blk = Block::from_id(id).expect("block");
assert_eq!(blk.name(), v["name"].as_str().unwrap());
n += 1;
}
assert!(n > 700);
}
}