Skip to main content

ghast_data/v1_16_5/
mod.rs

1//! Minecraft 1.16.5 (protocol 754) data: global block-state palette with properties.
2//!
3//! A [`BlockState`] is the global palette id used on the wire and in chunk sections
4//! (`0..STATE_COUNT`). Each [`Block`] owns a contiguous id range; the state's properties are a
5//! mixed-radix number over that range with the first property most significant (vanilla order).
6//! In 1.16 neighbour connections (fences, panes, walls, stairs, doors, chests) are part of the
7//! state, so their collision shapes are static per state; the few that are not are flagged with a
8//! [`ShapeDependency`].
9
10use crate::common::{
11    Aabb, BiomeInfo, BlockInfo, BlockPhysics, Collision, DigMaterial, EffectInfo, EnchantmentInfo,
12    EntityInfo, EntityKind, Fluid, FluidKind, FoodInfo, ItemInfo, SelectionShape, ShapeDependency,
13    lookup_id, lookup_name,
14};
15use crate::generated::v1_16_5 as g;
16
17pub mod dig;
18use core::fmt;
19
20pub use g::blocks::{Material, Property};
21
22/// Number of blocks (ids `0..BLOCK_COUNT`).
23pub const BLOCK_COUNT: usize = g::blocks::BLOCKS.len();
24/// Number of block states (ids `0..STATE_COUNT`).
25pub const STATE_COUNT: usize = g::blocks::STATE_BLOCK.len();
26
27impl Property {
28    /// Looks a property up by name (`"facing"`).
29    #[must_use]
30    pub fn from_name(name: &str) -> Option<Property> {
31        lookup_name(
32            g::blocks::PROPERTY_NAMES_TEXT,
33            &g::blocks::PROPERTY_NAMES,
34            name,
35        )
36    }
37}
38
39/// One property of a block with its possible values, in palette order.
40#[derive(Clone, Copy, Debug, PartialEq, Eq)]
41pub struct PropertyDef {
42    /// Which property.
43    pub property: Property,
44    /// Values in palette order (booleans are `["true", "false"]`, integers `"0"`, `"1"`, ...).
45    pub values: &'static [&'static str],
46}
47
48/// The state-id layout of one block.
49#[derive(Clone, Copy, Debug, PartialEq, Eq)]
50pub struct StateLayout {
51    /// First state id.
52    pub min_state: u16,
53    /// Number of states.
54    pub state_count: u16,
55    /// Default state id.
56    pub default_state: u16,
57    /// Indices into the property definition table, most significant first: `(start, len)` in
58    /// the generated `LAYOUT_PROPERTIES` (plain data, no pointer).
59    pub(crate) properties: (u16, u8),
60}
61
62impl StateLayout {
63    /// Indices into the property definition table, most significant first.
64    #[inline]
65    pub(crate) fn property_ids(&self) -> &'static [u8] {
66        let (start, len) = (
67            usize::from(self.properties.0),
68            usize::from(self.properties.1),
69        );
70        g::blocks::LAYOUT_PROPERTIES
71            .get(start..start + len)
72            .unwrap_or(&[])
73    }
74}
75
76/// Vanilla model offset type (`AbstractBlock.OffsetType`): bamboo and plants are shifted by a
77/// per-position pseudo-random offset.
78#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
79pub enum OffsetType {
80    /// No offset.
81    None,
82    /// Horizontal offset (bamboo's collision shape follows it).
83    Xz,
84    /// Horizontal and vertical offset.
85    Xyz,
86}
87
88/// Vanilla 1.16.5 per-block facts dumped by the oracle.
89#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
90pub struct VanillaBlock {
91    /// `AbstractBlock.collidable` (false for plants, cobweb, fluids, ...).
92    pub collidable: bool,
93    /// Model / shape offset type.
94    pub offset: OffsetType,
95}
96
97/// Scaffolding's context-dependent collision shapes; pick one with [`ScaffoldingShapes::select`].
98///
99/// Vanilla (`ScaffoldingBlock.getCollisionShape`), confirmed by the oracle's feet-height sweep:
100/// `stable` when the entity's feet `minY > y + 1 - 1.0E-5F` and it is not descending (sneaking);
101/// otherwise `bottom` when the state has `bottom=true`, `distance != 0` and `minY > y + 0 - 1.0E-5F`
102/// (`OUTLINE_SHAPE` is the full cube offset down by one, max Y 0); otherwise empty.
103#[derive(Clone, Copy, Debug, PartialEq)]
104pub struct ScaffoldingShapes {
105    /// The full (stable) shape, also [`BlockState::shape`].
106    pub stable: &'static [Aabb],
107    /// The bottom "collision" shape.
108    pub bottom: &'static [Aabb],
109    /// `stable` as a VoxelShape.
110    pub stable_voxel: &'static VoxelShapeRef,
111    /// `bottom` as a VoxelShape (the empty shape when there is none).
112    pub bottom_voxel: &'static VoxelShapeRef,
113    /// The state has a bottom shape (`bottom=true`, `distance != 0`).
114    pub has_bottom: bool,
115}
116
117impl ScaffoldingShapes {
118    /// The collision shape vanilla uses for an entity whose box bottom is `feet_min_y`, against
119    /// the scaffolding block at height `block_y`. Returns the boxes and the VoxelShape.
120    #[must_use]
121    pub fn select(
122        &self,
123        feet_min_y: f64,
124        block_y: i32,
125        descending: bool,
126    ) -> (&'static [Aabb], &'static VoxelShapeRef) {
127        let eps = f64::from(1.0e-5_f32);
128        if feet_min_y > f64::from(block_y) + 1.0 - eps && !descending {
129            (self.stable, self.stable_voxel)
130        } else if self.has_bottom && feet_min_y > f64::from(block_y) + 0.0 - eps {
131            (self.bottom, self.bottom_voxel)
132        } else {
133            (&[], &g::blocks::VOXEL_SHAPES[0])
134        }
135    }
136}
137
138/// VoxelShape implementation class (decides how a coordinate maps to a cell index in vanilla).
139#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
140pub enum VoxelClass {
141    /// `SimpleVoxelShape`: points are `i / n`; vanilla indexes with `floor(c * n)`, clamped.
142    Simple,
143    /// `ArrayVoxelShape`: explicit point lists; vanilla binary-searches them.
144    Array,
145}
146
147/// A vanilla 1.16.5 collision `VoxelShape` (block-local), exactly as the oracle dumped it.
148#[derive(Clone, Copy, Debug, PartialEq)]
149pub struct VoxelShapeRef {
150    /// Implementation class.
151    pub class: VoxelClass,
152    /// Cell counts `[nx, ny, nz]` (`0, 0, 0` for the empty shape).
153    pub sizes: [u8; 3],
154    /// `getPointPositions(X)` (`nx + 1` values; the empty shape has `[0.0]`).
155    pub xs: &'static [f64],
156    /// `getPointPositions(Y)`.
157    pub ys: &'static [f64],
158    /// `getPointPositions(Z)`.
159    pub zs: &'static [f64],
160    /// Filled-cell bitset, bit index `(x * ny + y) * nz + z`, 64 bits per word.
161    pub cells: &'static [u64],
162    /// `VoxelShape.isEmpty()`.
163    pub empty: bool,
164}
165
166impl VoxelShapeRef {
167    /// `true` when cell (`x`, `y`, `z`) is filled; `false` outside the grid.
168    #[must_use]
169    pub fn filled(&self, x: usize, y: usize, z: usize) -> bool {
170        let [nx, ny, nz] = self.sizes.map(usize::from);
171        if x >= nx || y >= ny || z >= nz {
172            return false;
173        }
174        let i = (x * ny + y) * nz + z;
175        self.cells[i / 64] & (1 << (i % 64)) != 0
176    }
177}
178
179/// Block side for [`BlockState::side_solid_full_square`].
180#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
181pub enum Side {
182    /// -Z.
183    North = 0,
184    /// +X.
185    East = 1,
186    /// +Z.
187    South = 2,
188    /// -X.
189    West = 3,
190    /// +Y.
191    Up = 4,
192    /// -Y.
193    Down = 5,
194}
195
196/// A 1.16.5 block type (registry id).
197#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
198pub struct Block(pub(crate) u16);
199
200impl Block {
201    /// The block with this registry id.
202    #[must_use]
203    pub const fn from_id(id: u16) -> Option<Block> {
204        if (id as usize) < BLOCK_COUNT {
205            Some(Block(id))
206        } else {
207            None
208        }
209    }
210
211    /// Looks a block up by registry name (`"oak_stairs"`, no namespace).
212    #[must_use]
213    pub fn from_name(name: &str) -> Option<Block> {
214        lookup_name(g::blocks::BLOCK_NAMES_TEXT, &g::blocks::BLOCK_NAMES, name).map(Block)
215    }
216
217    /// Registry id.
218    #[must_use]
219    pub const fn id(self) -> u16 {
220        self.0
221    }
222
223    /// Static information (names, hardness, drops, physics).
224    #[must_use]
225    pub fn info(self) -> &'static BlockInfo {
226        &g::blocks::BLOCKS[self.0 as usize]
227    }
228
229    /// Registry name.
230    #[must_use]
231    pub fn name(self) -> &'static str {
232        self.info().name
233    }
234
235    /// Physics properties.
236    #[must_use]
237    pub fn physics(self) -> &'static BlockPhysics {
238        &g::blocks::BLOCKS[self.0 as usize].physics
239    }
240
241    /// What the collision shape depends on besides the state.
242    #[must_use]
243    pub fn shape_dependency(self) -> ShapeDependency {
244        g::blocks::BLOCK_SHAPE_DEPENDENCY[self.0 as usize]
245    }
246
247    /// `true` for `air`, `cave_air` and `void_air` (vanilla `BlockState.isAir`).
248    #[must_use]
249    pub const fn is_air(self) -> bool {
250        matches!(self, Block::AIR | Block::CAVE_AIR | Block::VOID_AIR)
251    }
252
253    /// `true` for the 16 coloured beds (contiguous ids `WHITE_BED..=BLACK_BED`).
254    #[must_use]
255    pub const fn is_bed(self) -> bool {
256        self.0 >= Block::WHITE_BED.0 && self.0 <= Block::BLACK_BED.0
257    }
258
259    /// Vanilla material (Yarn `Material` field), per block as in vanilla.
260    #[must_use]
261    pub fn material(self) -> Material {
262        g::blocks::BLOCK_MATERIAL[self.0 as usize]
263    }
264
265    /// Vanilla per-block facts (oracle).
266    #[must_use]
267    pub fn vanilla(self) -> &'static VanillaBlock {
268        &g::blocks::VANILLA_BLOCKS[self.0 as usize]
269    }
270
271    /// State-id layout.
272    #[must_use]
273    pub fn layout(self) -> &'static StateLayout {
274        &g::blocks::LAYOUTS[self.0 as usize]
275    }
276
277    /// The default state.
278    #[must_use]
279    pub fn default_state(self) -> BlockState {
280        BlockState(self.layout().default_state)
281    }
282
283    /// All states of this block in id order.
284    pub fn states(self) -> impl ExactSizeIterator<Item = BlockState> {
285        let l = self.layout();
286        (l.min_state..l.min_state + l.state_count).map(BlockState)
287    }
288
289    /// The block's properties, most significant first.
290    pub fn properties(self) -> impl ExactSizeIterator<Item = &'static PropertyDef> {
291        self.layout()
292            .property_ids()
293            .iter()
294            .map(|&i| &g::blocks::PROPERTY_DEFS[i as usize])
295    }
296
297    /// The default state with the given properties changed; `None` if a property or value does not
298    /// exist for this block.
299    #[must_use]
300    pub fn state_with(self, props: &[(Property, &str)]) -> Option<BlockState> {
301        props
302            .iter()
303            .try_fold(self.default_state(), |s, &(p, v)| s.with(p, v))
304    }
305
306    /// All blocks in id order.
307    pub fn all() -> impl ExactSizeIterator<Item = Block> {
308        (0..BLOCK_COUNT as u16).map(Block)
309    }
310}
311
312/// A 1.16.5 block state (global palette id).
313#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
314pub struct BlockState(u16);
315
316impl BlockState {
317    /// `minecraft:air` (id 0).
318    pub const AIR: BlockState = BlockState(0);
319
320    /// Wraps a palette id; `None` if out of range.
321    #[must_use]
322    pub const fn from_id(id: u16) -> Option<BlockState> {
323        if (id as usize) < STATE_COUNT {
324            Some(BlockState(id))
325        } else {
326            None
327        }
328    }
329
330    /// Palette id.
331    #[must_use]
332    pub const fn id(self) -> u16 {
333        self.0
334    }
335
336    /// The block type.
337    #[must_use]
338    pub fn block(self) -> Block {
339        Block(g::blocks::STATE_BLOCK[self.0 as usize])
340    }
341
342    /// `true` for `air`, `cave_air` and `void_air`.
343    #[must_use]
344    pub fn is_air(self) -> bool {
345        self.block().is_air()
346    }
347
348    /// Collision boxes and what else they depend on. Hot path: three table lookups.
349    #[must_use]
350    pub fn collision(self) -> Collision {
351        Collision {
352            boxes: self.shape(),
353            dependency: g::blocks::BLOCK_SHAPE_DEPENDENCY
354                [g::blocks::STATE_BLOCK[self.0 as usize] as usize],
355            // 1.16 places shapes with double arithmetic (VoxelShape offset).
356            world_coords: None,
357        }
358    }
359
360    /// `true` when the collision shape is exactly a full cube (oracle `full_cube`).
361    #[must_use]
362    pub fn full_cube(self) -> bool {
363        g::blocks::STATE_VANILLA_FLAGS[self.0 as usize] & 1 != 0
364    }
365
366    /// `AbstractBlockState.isSolidBlock` (oracle `solid_block`).
367    #[must_use]
368    pub fn solid_block(self) -> bool {
369        g::blocks::STATE_VANILLA_FLAGS[self.0 as usize] & 2 != 0
370    }
371
372    /// `AbstractBlockState.shouldSuffocate` (oracle `suffocates`).
373    #[must_use]
374    pub fn should_suffocate(self) -> bool {
375        g::blocks::STATE_VANILLA_FLAGS[self.0 as usize] & 4 != 0
376    }
377
378    /// The collision `VoxelShape` (context-free; see [`BlockState::scaffolding_shapes`]).
379    #[must_use]
380    pub fn voxel_shape(self) -> &'static VoxelShapeRef {
381        &g::blocks::VOXEL_SHAPES[g::blocks::STATE_VOXEL[self.0 as usize] as usize]
382    }
383
384    /// The crosshair outline shape (`getShape` / `getOutlineShape` with the player's context,
385    /// empty hand). For states with [`BlockState::outline_offset`] this is the unshifted shape: the
386    /// block moves it by its per-position model offset.
387    #[must_use]
388    pub fn outline_shape(self) -> &'static SelectionShape {
389        &g::selection::SELECTION_SHAPES[g::selection::STATE_OUTLINE[self.0 as usize] as usize]
390    }
391
392    /// The outline while the player holds this block's own item (scaffolding and, where it
393    /// exists, the light block show a full cube then); otherwise [`BlockState::outline_shape`].
394    #[must_use]
395    pub fn outline_shape_holding_own_item(self) -> &'static SelectionShape {
396        let t = &g::selection::OUTLINE_HOLDING_OWN_ITEM;
397        match t.binary_search_by_key(&self.0, |e| e.0) {
398            Ok(i) => &g::selection::SELECTION_SHAPES[t[i].1 as usize],
399            Err(_) => self.outline_shape(),
400        }
401    }
402
403    /// `true` when the outline is moved by the block's model offset (flowers, bamboo, ...).
404    #[must_use]
405    pub fn outline_offset(self) -> bool {
406        g::selection::STATE_OUTLINE_OFFSET[self.0 as usize / 64] & (1 << (self.0 % 64)) != 0
407    }
408
409    /// The raycast shape (`getRaycastShape`): when the ray hits it nearer than the outline, the
410    /// hit keeps the outline's position but takes this shape's side (cauldrons, composters,
411    /// hoppers, scaffolding).
412    #[must_use]
413    pub fn raycast_shape(self) -> &'static SelectionShape {
414        &g::selection::SELECTION_SHAPES[g::selection::STATE_INTERACTION[self.0 as usize] as usize]
415    }
416
417    fn voxel_flag(self, bit: u16) -> bool {
418        g::blocks::STATE_VOXEL_FLAGS[self.0 as usize] & bit != 0
419    }
420
421    /// The collision shape *is* `VoxelShapes.fullCube()` (identity, as vanilla's fast paths test).
422    #[must_use]
423    pub fn full_cube_identity(self) -> bool {
424        self.voxel_flag(1)
425    }
426
427    /// The collision shape *is* `VoxelShapes.empty()` (identity).
428    #[must_use]
429    pub fn empty_identity(self) -> bool {
430        self.voxel_flag(1 << 12)
431    }
432
433    /// `Material.isLiquid()` of the state's material.
434    #[must_use]
435    pub fn material_liquid(self) -> bool {
436        self.voxel_flag(1 << 13)
437    }
438
439    /// `Material.isSolid()` of the state's material.
440    #[must_use]
441    pub fn material_solid(self) -> bool {
442        self.voxel_flag(1 << 14)
443    }
444
445    /// `Material.isReplaceable()` of the state's material.
446    #[must_use]
447    pub fn material_replaceable(self) -> bool {
448        self.voxel_flag(1 << 15)
449    }
450
451    /// `AbstractBlockState.exceedsCube()`.
452    #[must_use]
453    pub fn exceeds_cube(self) -> bool {
454        self.voxel_flag(2)
455    }
456
457    /// `AbstractBlock.dynamicBounds` (no shape cache; shapes recomputed per query).
458    #[must_use]
459    pub fn has_dynamic_bounds(self) -> bool {
460        self.voxel_flag(16)
461    }
462
463    /// `Material.blocksMovement()` of the state's material.
464    #[must_use]
465    pub fn material_blocks_movement(self) -> bool {
466        self.voxel_flag(32)
467    }
468
469    /// `isSideSolidFullSquare(world, pos, side)` in an otherwise empty world.
470    #[must_use]
471    pub fn side_solid_full_square(self, side: Side) -> bool {
472        self.voxel_flag(64 << side as u16)
473    }
474
475    /// Scaffolding context shapes; `None` for other blocks.
476    #[must_use]
477    pub fn scaffolding_shapes(self) -> Option<ScaffoldingShapes> {
478        if self.block() != Block::SCAFFOLDING {
479            return None;
480        }
481        let has_bottom =
482            self.get(Property::Bottom) == Some("true") && self.get(Property::Distance) != Some("0");
483        Some(ScaffoldingShapes {
484            stable: self.shape(),
485            bottom: if has_bottom {
486                g::blocks::SCAFFOLDING_BOTTOM
487            } else {
488                &[]
489            },
490            stable_voxel: self.voxel_shape(),
491            has_bottom,
492            bottom_voxel: &g::blocks::VOXEL_SHAPES[if has_bottom {
493                g::blocks::SCAFFOLDING_BOTTOM_VOXEL as usize
494            } else {
495                0
496            }],
497        })
498    }
499
500    /// Collision boxes from the table.
501    #[must_use]
502    pub fn shape(self) -> &'static [Aabb] {
503        crate::common::shape_boxes(
504            &g::blocks::SHAPE_BOXES,
505            g::blocks::SHAPES[g::blocks::STATE_SHAPE[self.0 as usize] as usize],
506        )
507    }
508
509    /// Fluid in this state: water / lava blocks with their `level`, waterlogged states and
510    /// always-wet blocks (kelp, seagrass, bubble column) as water level 0.
511    #[must_use]
512    pub fn fluid(self) -> Option<Fluid> {
513        let f = g::blocks::STATE_FLUID[self.0 as usize];
514        let kind = match f >> 4 {
515            1 => FluidKind::Water,
516            2 => FluidKind::Lava,
517            _ => return None,
518        };
519        Some(Fluid {
520            kind,
521            level: f & 15,
522        })
523    }
524
525    /// Index of `prop`'s value in [`PropertyDef::values`], if the block has that property.
526    #[must_use]
527    pub fn get_index(self, prop: Property) -> Option<usize> {
528        let layout = self.block().layout();
529        let mut rem = usize::from(self.0 - layout.min_state);
530        for &d in layout.property_ids().iter().rev() {
531            let def = &g::blocks::PROPERTY_DEFS[d as usize];
532            let n = def.values.len();
533            if def.property == prop {
534                return Some(rem % n);
535            }
536            rem /= n;
537        }
538        None
539    }
540
541    /// The value of `prop` (`"north"`, `"true"`, `"3"`), if the block has that property.
542    #[must_use]
543    pub fn get(self, prop: Property) -> Option<&'static str> {
544        let def = self.property_def(prop)?;
545        self.get_index(prop).map(|i| def.values[i])
546    }
547
548    /// This state with `prop` set to `value`; `None` if the block lacks the property or value.
549    #[must_use]
550    pub fn with(self, prop: Property, value: &str) -> Option<BlockState> {
551        let layout = self.block().layout();
552        let mut stride = 1usize;
553        for &d in layout.property_ids().iter().rev() {
554            let def = &g::blocks::PROPERTY_DEFS[d as usize];
555            let n = def.values.len();
556            if def.property == prop {
557                let new = def.values.iter().position(|v| *v == value)?;
558                let base = usize::from(self.0 - layout.min_state);
559                let old = base / stride % n;
560                let id = base - old * stride + new * stride + usize::from(layout.min_state);
561                return Some(BlockState(id as u16));
562            }
563            stride *= n;
564        }
565        None
566    }
567
568    /// `(property, value)` pairs of this state, most significant property first.
569    pub fn properties(self) -> impl Iterator<Item = (Property, &'static str)> {
570        let block = self.block();
571        block
572            .properties()
573            .filter_map(move |d| self.get(d.property).map(|v| (d.property, v)))
574    }
575
576    fn property_def(self, prop: Property) -> Option<&'static PropertyDef> {
577        self.block().properties().find(|d| d.property == prop)
578    }
579}
580
581/// `minecraft:oak_stairs[facing=north,half=bottom,...]`, the vanilla block-state string form.
582impl fmt::Display for BlockState {
583    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
584        write!(f, "minecraft:{}", self.block().name())?;
585        let mut first = true;
586        for (p, v) in self.properties() {
587            f.write_str(if first { "[" } else { "," })?;
588            write!(f, "{}={v}", p.name())?;
589            first = false;
590        }
591        if !first {
592            f.write_str("]")?;
593        }
594        Ok(())
595    }
596}
597
598/// 1.16.5 slime / magma cube dimensions for metadata size `n` (vanilla: the type's 2.04 x 2.04
599/// `scaled(0.255F * n)`, eye height `0.625F * height`).
600#[must_use]
601#[allow(clippy::cast_precision_loss)]
602pub fn slime_dimensions(n: i32) -> crate::common::EntityDimensions {
603    let ratio = 0.255_f32 * n as f32;
604    let s = 2.04_f32 * ratio;
605    crate::common::EntityDimensions {
606        width: s,
607        height: s,
608        eye_height: 0.625 * s,
609    }
610}
611
612crate::macros::common_api!();