Skip to main content

ghast_data/
common.rs

1//! Version-independent data types shared by every version module.
2//!
3//! The generated per-version tables (`crate::v1_8`, `crate::v1_16_5`) are built from these types.
4//! Everything here is plain `Copy` data or `&'static` slices so the tables can live in `static`
5//! memory with no runtime initialisation.
6
7/// Axis-aligned box in block-local coordinates (`0.0..=1.0` for a full cube; some shapes such as
8/// fences or piston arms extend outside that range).
9///
10/// Field names follow Yarn's `Box` (`minX` .. `maxZ`). Values are exact `f64` copies of the source
11/// data; every value in the shipped tables is a dyadic fraction, so it is also exactly the `f64`
12/// produced by vanilla's `(double)someFloat` bounds.
13#[derive(Clone, Copy, Debug, PartialEq)]
14pub struct Aabb {
15    /// Minimum X (west edge).
16    pub min_x: f64,
17    /// Minimum Y (bottom).
18    pub min_y: f64,
19    /// Minimum Z (north edge).
20    pub min_z: f64,
21    /// Maximum X (east edge).
22    pub max_x: f64,
23    /// Maximum Y (top).
24    pub max_y: f64,
25    /// Maximum Z (south edge).
26    pub max_z: f64,
27}
28
29impl Aabb {
30    /// The full unit cube `[0, 1]³`.
31    pub const FULL: Aabb = Aabb::new(0.0, 0.0, 0.0, 1.0, 1.0, 1.0);
32
33    /// Creates a box from its six bounds.
34    #[must_use]
35    pub const fn new(
36        min_x: f64,
37        min_y: f64,
38        min_z: f64,
39        max_x: f64,
40        max_y: f64,
41        max_z: f64,
42    ) -> Self {
43        Aabb {
44            min_x,
45            min_y,
46            min_z,
47            max_x,
48            max_y,
49            max_z,
50        }
51    }
52
53    /// The box translated by a block position (`x`, `y`, `z` are the block's integer coordinates),
54    /// in `double` arithmetic. Use [`Collision::world_box`] for vanilla-exact placement.
55    #[must_use]
56    pub fn at(&self, x: i32, y: i32, z: i32) -> Aabb {
57        let (x, y, z) = (f64::from(x), f64::from(y), f64::from(z));
58        Aabb::new(
59            self.min_x + x,
60            self.min_y + y,
61            self.min_z + z,
62            self.max_x + x,
63            self.max_y + y,
64            self.max_z + z,
65        )
66    }
67}
68
69/// A block's outline (selection) or interaction `VoxelShape`, block-local, as the crosshair ray
70/// tests it (1.14+ versions; oracle `selection_shapes.jsonl.gz`).
71///
72/// The ray uses two views of a shape: the filled-cell grid (is the ray's first test point inside
73/// the shape?) and the box list (`toAabbs()` / `getBoundingBoxes()` in vanilla's order, which
74/// decides ties between equally near faces).
75#[derive(Clone, Copy, Debug, PartialEq)]
76pub struct SelectionShape {
77    /// Vanilla's cube shape class (`CubeVoxelShape` / `SimpleVoxelShape`): a coordinate's cell is
78    /// `floor(c * n)` clamped to `-1..=n`; otherwise (array shapes) it is found by binary search
79    /// over the points.
80    pub cube: bool,
81    /// Cell counts `[nx, ny, nz]` (`0, 0, 0` for the empty shape).
82    pub sizes: [u8; 3],
83    /// Cell boundaries along X (`nx + 1` values; the empty shape has `[0.0]`).
84    pub xs: &'static [f64],
85    /// Cell boundaries along Y.
86    pub ys: &'static [f64],
87    /// Cell boundaries along Z.
88    pub zs: &'static [f64],
89    /// Filled-cell bitset, bit index `(x * ny + y) * nz + z`, 64 bits per word.
90    pub cells: &'static [u64],
91    /// `VoxelShape.isEmpty()`.
92    pub empty: bool,
93    /// The shape's boxes in vanilla's order.
94    pub boxes: &'static [Aabb],
95}
96
97impl SelectionShape {
98    /// `true` when cell (`x`, `y`, `z`) is filled; `false` outside the grid.
99    #[must_use]
100    pub fn filled(&self, x: i32, y: i32, z: i32) -> bool {
101        let [nx, ny, nz] = self.sizes.map(i32::from);
102        if x < 0 || y < 0 || z < 0 || x >= nx || y >= ny || z >= nz {
103            return false;
104        }
105        let i = ((x * ny + y) * nz + z) as usize;
106        self.cells[i / 64] & (1 << (i % 64)) != 0
107    }
108}
109
110/// What a block's collision shape depends on besides its own block state.
111///
112/// When this is not [`ShapeDependency::None`], [`Collision::boxes`] is only the shape for the
113/// "default" situation described on each variant and the caller (world / physics crate) must
114/// compute the real shape. The tables never pretend such shapes are static.
115#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
116#[non_exhaustive]
117pub enum ShapeDependency {
118    /// The shape is fully determined by the block state.
119    None,
120    /// The shape depends on neighbouring blocks (1.8 "actual state" blocks). `boxes` is the
121    /// shape with no connecting neighbours, as given by minecraft-data.
122    Neighbours(NeighbourShape),
123    /// The shape depends on the colliding entity (1.16 scaffolding: sneaking / standing above).
124    /// `boxes` is the shape minecraft-data reports.
125    EntityContext,
126    /// The shape depends on a block entity (1.16 shulker box lid, moving piston). `boxes` is the
127    /// shape minecraft-data reports.
128    BlockEntity,
129    /// The shape is shifted by a per-position pseudo-random XZ offset (1.16 bamboo). `boxes` is the
130    /// un-offset shape.
131    PositionOffset,
132}
133
134/// Family of a neighbour-dependent shape. The world/physics crate implements the vanilla
135/// connection rules per family.
136#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
137#[non_exhaustive]
138pub enum NeighbourShape {
139    /// Fences: centre post plus arms towards connecting neighbours, 1.5 high.
140    Fence,
141    /// Glass panes and iron bars.
142    Pane,
143    /// Cobblestone walls (1.5 high, post omitted on straight runs).
144    Wall,
145    /// Stairs: straight / inner / outer corner shapes from adjacent stairs.
146    Stairs,
147    /// Doors: the shape combines the lower half (facing, open) with the upper half (hinge).
148    Door,
149    /// Chests: the box extends to the block edge towards an adjacent chest of the same kind.
150    Chest,
151    /// 1.12 chorus plants: a centre box plus an arm towards each connecting neighbour (chorus
152    /// plant / flower, end stone below).
153    ChorusPlant,
154}
155
156/// How vanilla turns one bound of a collision box into an absolute world coordinate.
157///
158/// Most 1.8 blocks compute `blockPos + localBound` in `double` ([`WorldCoord::Double`]), which is
159/// exact. A few (cactus, cake, fence gate, soul sand, snow layer) do the addition in `float`:
160/// `(float) (blockPos + int_offset) + term`, widened to `double`. That rounds once
161/// `|blockPos|` is large (from 2^20 ≈ 1M blocks for 1/16 steps), and the rounded value is what
162/// vanilla collides with.
163#[derive(Clone, Copy, Debug, PartialEq)]
164pub enum WorldCoord {
165    /// `f64::from(pos) + local` (the matching [`Aabb`] bound).
166    Double,
167    /// `f64::from((pos + int_offset) as f32 + term)`: Java `i2f`, `fadd`, `f2d`.
168    Float {
169        /// Integer added to the block coordinate before the `float` conversion (`pos.getX() + 1`).
170        int_offset: i8,
171        /// `float` term added afterwards (negative for `pos.getX() + 1 - f`).
172        term: f32,
173    },
174}
175
176/// Per-bound world-coordinate rules of one box, in [`Aabb`] field order
177/// (`min_x, min_y, min_z, max_x, max_y, max_z`).
178pub type WorldCoords = [WorldCoord; 6];
179
180impl WorldCoord {
181    /// The absolute coordinate for block coordinate `pos` and local bound `local`.
182    #[inline]
183    #[must_use]
184    pub fn apply(self, pos: i32, local: f64) -> f64 {
185        match self {
186            WorldCoord::Double => f64::from(pos) + local,
187            #[allow(clippy::cast_precision_loss)]
188            WorldCoord::Float { int_offset, term } => {
189                f64::from(pos.wrapping_add(i32::from(int_offset)) as f32 + term)
190            }
191        }
192    }
193}
194
195/// `(min, max)` of two coordinates (never NaN here).
196fn ordered(a: f64, b: f64) -> (f64, f64) {
197    if a <= b { (a, b) } else { (b, a) }
198}
199
200/// The collision of one block state.
201#[derive(Clone, Copy, Debug, PartialEq)]
202#[non_exhaustive]
203pub struct Collision {
204    /// Boxes in block-local coordinates; empty means no collision.
205    pub boxes: &'static [Aabb],
206    /// Whether `boxes` is the final shape or needs more context.
207    pub dependency: ShapeDependency,
208    /// `Some` when vanilla builds these boxes with `float` world coordinates (one rule set per
209    /// box, parallel to `boxes`); `None` = plain `double` addition, i.e. [`Aabb::at`].
210    pub world_coords: Option<&'static [WorldCoords]>,
211}
212
213impl Collision {
214    /// `true` when at least one bound is computed in `float` world coordinates.
215    #[must_use]
216    pub fn uses_float_world_coords(&self) -> bool {
217        self.world_coords.is_some()
218    }
219
220    /// Box `i` placed at block position (`x`, `y`, `z`), bit-exact as vanilla computes it.
221    ///
222    /// # Panics
223    /// If `i >= self.boxes.len()`.
224    #[inline]
225    #[must_use]
226    pub fn world_box(&self, i: usize, x: i32, y: i32, z: i32) -> Aabb {
227        let b = &self.boxes[i];
228        match self.world_coords {
229            None => b.at(x, y, z),
230            Some(rules) => {
231                let r = &rules[i];
232                // Vanilla's Box constructor orders each axis (Math.min / Math.max); float rounding
233                // can invert a thin bound pair far from the origin (cake below x = -2^24).
234                let (x0, x1) = ordered(r[0].apply(x, b.min_x), r[3].apply(x, b.max_x));
235                let (y0, y1) = ordered(r[1].apply(y, b.min_y), r[4].apply(y, b.max_y));
236                let (z0, z1) = ordered(r[2].apply(z, b.min_z), r[5].apply(z, b.max_z));
237                Aabb::new(x0, y0, z0, x1, y1, z1)
238            }
239        }
240    }
241
242    /// All boxes placed at block position (`x`, `y`, `z`), bit-exact as vanilla computes them.
243    pub fn world_boxes(&self, x: i32, y: i32, z: i32) -> impl ExactSizeIterator<Item = Aabb> + '_ {
244        (0..self.boxes.len()).map(move |i| self.world_box(i, x, y, z))
245    }
246    /// `true` when the block state has no collision boxes and nothing else can add one.
247    #[must_use]
248    pub fn is_empty(&self) -> bool {
249        self.boxes.is_empty() && self.dependency == ShapeDependency::None
250    }
251
252    /// `true` when the shape is exactly one full unit cube and does not depend on anything else.
253    #[must_use]
254    pub fn is_full_cube(&self) -> bool {
255        self.dependency == ShapeDependency::None && self.boxes == [Aabb::FULL]
256    }
257}
258
259/// minecraft-data's coarse bounding-box classification.
260#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
261pub enum BoundingBox {
262    /// No collision ("empty").
263    Empty,
264    /// Has some collision ("block"); see the block state's [`Collision`] for the real shape.
265    Block,
266}
267
268/// minecraft-data's harvest "material" group: selects the tool speed multipliers
269/// (see the per-version `tool_multiplier`). This is NOT vanilla's `Material` class.
270#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
271#[non_exhaustive]
272pub enum DigMaterial {
273    /// Pickaxe group.
274    Rock,
275    /// Axe group.
276    Wood,
277    /// Axe/sword group (plants).
278    Plant,
279    /// Sword-only group (melons, pumpkins).
280    Melon,
281    /// Leaves (sword, shears).
282    Leaves,
283    /// Shovel group.
284    Dirt,
285    /// Cobweb (sword, shears).
286    Web,
287    /// Wool (shears).
288    Wool,
289    /// 1.16 data's explicit "default" group (no tool bonus).
290    Default,
291}
292
293/// A block's item drop as listed by minecraft-data (no loot-table logic, no fortune).
294#[derive(Clone, Copy, Debug, PartialEq, Eq)]
295pub struct Drop {
296    /// Item id.
297    pub item: u16,
298    /// Item metadata / damage (1.8 only); `None` = 0 / unspecified.
299    pub meta: Option<u8>,
300    /// Minimum count.
301    pub min: u8,
302    /// Maximum count.
303    pub max: u8,
304}
305
306/// Bit set of physics-relevant block flags.
307#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
308pub struct PhysicsFlags(pub u16);
309
310impl PhysicsFlags {
311    /// No flags.
312    pub const NONE: PhysicsFlags = PhysicsFlags(0);
313    /// The entity can climb while inside this block (ladder, vine, ...).
314    pub const CLIMBABLE: PhysicsFlags = PhysicsFlags(1 << 0);
315    /// The block is a water block (still / flowing). In 1.16 waterlogged states are reported by the
316    /// per-state fluid table instead.
317    pub const WATER: PhysicsFlags = PhysicsFlags(1 << 1);
318    /// The block is a lava block (still / flowing).
319    pub const LAVA: PhysicsFlags = PhysicsFlags(1 << 2);
320    /// Entities inside are slowed by the block's `stuck_multiplier` (cobweb, sweet berry bush).
321    pub const STUCK: PhysicsFlags = PhysicsFlags(1 << 3);
322    /// Slime block: bounces on landing and slows walking.
323    pub const SLIME: PhysicsFlags = PhysicsFlags(1 << 4);
324    /// Bed: bounces on landing (1.12+ behaviour; never set for 1.8).
325    pub const BED_BOUNCE: PhysicsFlags = PhysicsFlags(1 << 5);
326    /// Honey block: wall sliding (1.15+).
327    pub const HONEY: PhysicsFlags = PhysicsFlags(1 << 6);
328    /// Bubble column (1.13+): pushes entities up or down.
329    pub const BUBBLE_COLUMN: PhysicsFlags = PhysicsFlags(1 << 7);
330    /// 1.8 soul sand: `speed_factor` is applied to horizontal motion when the entity's box
331    /// intersects the block (vanilla `Block.onEntityCollision`), not as a ground speed factor.
332    pub const COLLIDE_SLOWDOWN: PhysicsFlags = PhysicsFlags(1 << 8);
333    /// Fence: 1.16 `#minecraft:fences` tag; 1.8 `FenceBlock` (wooden + nether brick fences).
334    pub const FENCE: PhysicsFlags = PhysicsFlags(1 << 9);
335    /// Wall: 1.16 `#minecraft:walls` tag; 1.8 `WallBlock` (cobblestone wall).
336    pub const WALL: PhysicsFlags = PhysicsFlags(1 << 10);
337    /// Fence gate: 1.16 `#minecraft:fence_gates` tag; 1.8 `FenceGateBlock`.
338    pub const FENCE_GATE: PhysicsFlags = PhysicsFlags(1 << 11);
339    /// Trapdoor: 1.16 `#minecraft:trapdoors` tag; 1.8 `TrapdoorBlock`.
340    pub const TRAPDOOR: PhysicsFlags = PhysicsFlags(1 << 12);
341    /// 1.16 `#minecraft:soul_speed_blocks` (soul sand, soul soil); never set for 1.8.
342    pub const SOUL_SPEED: PhysicsFlags = PhysicsFlags(1 << 13);
343    /// 1.16 `#minecraft:fire` (fire, soul fire); never set for 1.8.
344    pub const FIRE: PhysicsFlags = PhysicsFlags(1 << 14);
345
346    /// `true` when every flag of `other` is set in `self`.
347    #[must_use]
348    pub const fn contains(self, other: PhysicsFlags) -> bool {
349        self.0 & other.0 == other.0
350    }
351
352    /// Union of two flag sets.
353    #[must_use]
354    pub const fn union(self, other: PhysicsFlags) -> PhysicsFlags {
355        PhysicsFlags(self.0 | other.0)
356    }
357}
358
359/// Physics properties of a block (vanilla facts that minecraft-data does not carry; maintained in
360/// `codegen/data/src/facts.rs`).
361#[derive(Clone, Copy, Debug, PartialEq)]
362#[non_exhaustive]
363pub struct BlockPhysics {
364    /// Ground friction ("slipperiness"), vanilla `float`: default 0.6, ice 0.98, slime 0.8.
365    pub slipperiness: f32,
366    /// Horizontal speed multiplier. The exact `f64` vanilla multiplies by: `0.4` (a `double`
367    /// literal) for 1.8 soul sand, `0.4f32 as f64` for 1.16 speed factors. `1.0` = none.
368    pub speed_factor: f64,
369    /// Jump velocity multiplier (vanilla `float`; 1.16 honey block 0.5). `1.0` = none.
370    pub jump_factor: f32,
371    /// Motion multiplier `[x, y, z]` while inside the block (when [`PhysicsFlags::STUCK`]).
372    pub stuck_multiplier: [f64; 3],
373    /// Flag bits.
374    pub flags: PhysicsFlags,
375}
376
377impl BlockPhysics {
378    /// Properties of an ordinary block.
379    pub const DEFAULT: BlockPhysics = BlockPhysics {
380        slipperiness: 0.6,
381        speed_factor: 1.0,
382        jump_factor: 1.0,
383        stuck_multiplier: [1.0, 1.0, 1.0],
384        flags: PhysicsFlags::NONE,
385    };
386
387    /// The speed factor as the `float` 1.16 `Block.getVelocityMultiplier()` returns (exact: the
388    /// 1.16 tables store `f64::from(f32)`). For 1.8 use [`BlockPhysics::speed_factor`] directly.
389    #[allow(clippy::cast_possible_truncation)]
390    #[must_use]
391    pub const fn velocity_multiplier(&self) -> f32 {
392        self.speed_factor as f32
393    }
394
395    /// Shorthand for `self.flags.contains(flag)`.
396    #[must_use]
397    pub const fn has(&self, flag: PhysicsFlags) -> bool {
398        self.flags.contains(flag)
399    }
400}
401
402/// Static description of a block (cold data: names, digging, light, drops).
403#[derive(Clone, Copy, Debug, PartialEq)]
404#[non_exhaustive]
405pub struct BlockInfo {
406    /// Registry id (1.8: 0..=255, 1.16: 0..763).
407    pub id: u16,
408    /// Registry name without namespace (`"stone"`).
409    pub name: &'static str,
410    /// English display name.
411    #[cfg(feature = "display-names")]
412    pub display_name: &'static str,
413    /// Hardness (vanilla "strength"); `None` when minecraft-data lists `null` (unbreakable in 1.8).
414    /// Note: 1.16 data lists unbreakable blocks (bedrock, barrier, ...) with hardness `0` and
415    /// `diggable == false`; always check [`BlockInfo::diggable`].
416    pub hardness: Option<f32>,
417    /// Blast resistance.
418    pub resistance: f32,
419    /// Max stack size of the block's item.
420    pub stack_size: u8,
421    /// Whether the block can be dug at all.
422    pub diggable: bool,
423    /// minecraft-data "transparent" flag (light passes / not an opaque cube).
424    pub transparent: bool,
425    /// Emitted light level 0..=15.
426    pub emit_light: u8,
427    /// Light absorbed 0..=15.
428    pub filter_light: u8,
429    /// Coarse bounding-box class.
430    pub bounding_box: BoundingBox,
431    /// Tool-speed group; `None` = no tool bonus.
432    pub material: Option<DigMaterial>,
433    /// Item ids that can harvest this block (get drops). Empty = any tool / hand.
434    pub harvest_tools: &'static [u16],
435    /// Item drops (basic list, no loot tables).
436    pub drops: &'static [Drop],
437    /// Physics properties.
438    pub physics: BlockPhysics,
439}
440
441impl BlockInfo {
442    /// `true` when the block needs a specific tool to drop anything.
443    #[must_use]
444    pub fn requires_tool(&self) -> bool {
445        !self.harvest_tools.is_empty()
446    }
447
448    /// `true` when `item` (an item id, or `None` for the empty hand) harvests the block.
449    #[must_use]
450    pub fn can_harvest_with(&self, item: Option<u16>) -> bool {
451        self.harvest_tools.is_empty() || item.is_some_and(|i| self.harvest_tools.contains(&i))
452    }
453}
454
455/// Fluid kind of a block state.
456#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
457pub enum FluidKind {
458    /// Water (incl. 1.16 waterlogged states and always-wet plants / bubble columns).
459    Water,
460    /// Lava.
461    Lava,
462}
463
464/// A fluid occupying a block state.
465#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
466pub struct Fluid {
467    /// Kind of fluid.
468    pub kind: FluidKind,
469    /// Vanilla `level` value (0 = source, 1..=7 flowing, 8..=15 falling). Waterlogged / always-wet
470    /// blocks report 0.
471    pub level: u8,
472}
473
474impl Fluid {
475    /// Vanilla `FluidState` amount 1..=8: source 8, flowing `8 - level`, falling 8
476    /// (`FluidBlock.getFluidState` maps `level >= 8` to falling with amount 8).
477    #[must_use]
478    pub const fn amount(self) -> u8 {
479        if self.level == 0 || self.level >= 8 {
480            8
481        } else {
482            8 - self.level
483        }
484    }
485
486    /// `true` for falling fluid (`level >= 8`).
487    #[must_use]
488    pub const fn falling(self) -> bool {
489        self.level >= 8
490    }
491
492    /// Vanilla `FlowableFluid.getHeight(state)` = `amount / 9F`: the surface height when the block
493    /// above holds no fluid of the same kind (then vanilla uses 1.0).
494    #[must_use]
495    pub fn height(self) -> f32 {
496        f32::from(self.amount()) / 9.0
497    }
498
499    /// `true` for a source / still fluid (`level == 0`, also waterlogged states).
500    #[must_use]
501    pub const fn still(self) -> bool {
502        self.level == 0
503    }
504}
505
506/// An item.
507#[derive(Clone, Copy, Debug, PartialEq, Eq)]
508#[non_exhaustive]
509pub struct ItemInfo {
510    /// Item id.
511    pub id: u16,
512    /// Registry name without namespace.
513    pub name: &'static str,
514    /// English display name.
515    #[cfg(feature = "display-names")]
516    pub display_name: &'static str,
517    /// Max stack size.
518    pub stack_size: u8,
519    /// Durability for damageable items.
520    pub max_durability: Option<u16>,
521    /// 1.8 metadata variants `(meta, display name)`; empty for 1.16.
522    #[cfg(feature = "display-names")]
523    pub variations: &'static [(u8, &'static str)],
524}
525
526/// Broad entity kind from minecraft-data.
527#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
528pub enum EntityKind {
529    /// Living entity ("mob"). In 1.8 these use the mob-spawn packet's id space.
530    Mob,
531    /// Non-living "object" (1.8 spawn-object packet id space: boats, items, arrows, ...).
532    Object,
533    /// Anything else minecraft-data reports (`"UNKNOWN"`, `"player"`, ...).
534    Other,
535}
536
537/// An entity type.
538#[derive(Clone, Copy, Debug, PartialEq)]
539#[non_exhaustive]
540pub struct EntityInfo {
541    /// Network type id (in 1.8 mob and object ids are separate spaces, see [`EntityKind`]).
542    pub id: u16,
543    /// Name as listed by minecraft-data (1.8: legacy CamelCase names such as `"PigZombie"`).
544    pub name: &'static str,
545    /// English display name.
546    #[cfg(feature = "display-names")]
547    pub display_name: &'static str,
548    /// Mob / object.
549    pub kind: EntityKind,
550    /// minecraft-data category (`"Hostile mobs"`, ...).
551    pub category: &'static str,
552    /// Box width; `None` when unknown. From minecraft-data, NOT verified float-exact.
553    pub width: Option<f32>,
554    /// Box height; `None` when unknown. From minecraft-data, NOT verified float-exact.
555    pub height: Option<f32>,
556}
557
558/// Vanilla entity dimensions (`float`s, as the game stores them).
559#[derive(Clone, Copy, Debug, PartialEq)]
560pub struct EntityDimensions {
561    /// Box width (x and z).
562    pub width: f32,
563    /// Box height.
564    pub height: f32,
565    /// Eye height above the feet.
566    pub eye_height: f32,
567}
568
569impl EntityDimensions {
570    /// The bounding box with its feet centre at (`x`, `y`), `z`, bit-exact as vanilla builds it:
571    /// half width in `float`, then `x - (double) halfWidth`, `y + (double) height`, ...
572    #[must_use]
573    pub fn bounding_box(&self, x: f64, y: f64, z: f64) -> Aabb {
574        let half = f64::from(self.width / 2.0);
575        Aabb::new(
576            x - half,
577            y,
578            z - half,
579            x + half,
580            y + f64::from(self.height),
581            z + half,
582        )
583    }
584}
585
586/// When the vanilla client applies a size variant.
587#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
588#[non_exhaustive]
589pub enum VariantApplied {
590    /// The size right after the spawn packet (the `"default"` variant).
591    Spawn,
592    /// Immediately when the entity metadata packet arrives.
593    Metadata,
594    /// In the entity's next client tick (passive babies, 1.8 wither skeleton, armor stand marker).
595    NextTick,
596    /// From the client player's own input (1.8 sneaking eye height).
597    Input,
598    /// Only on the server: the client never applies it (e.g. 1.8 baby zombie's 0.3 x 0.975); listed
599    /// for reference.
600    Server,
601}
602
603/// One measured size variant of an entity type.
604#[derive(Clone, Copy, Debug, PartialEq)]
605pub struct EntityVariant {
606    /// `"default"`, `"baby"`, `"baby_server"`, `"wither"`, `"elder"`, `"size_1"`..`"size_4"`,
607    /// `"small"`, `"marker"`, `"small_marker"`, `"sneaking"`, `"villager"`.
608    pub name: &'static str,
609    /// The dimensions.
610    pub dimensions: EntityDimensions,
611    /// When the client applies them.
612    pub applied: VariantApplied,
613}
614
615/// Vanilla sizes of one entity type, measured by the oracle on the client, spawned the way the
616/// client spawns it from its packet, then metadata-dependent variants applied like the client does
617/// (`oracle/README.md`, "entity_sizes.jsonl.gz").
618///
619/// Boxes: [`EntityDimensions::bounding_box`] is the centred box vanilla builds on spawn and every
620/// position update. Hanging entities (paintings, item frames) build their box from facing and motive
621/// instead, and vanilla's resize keeps the old min corner until the next position update.
622#[derive(Clone, Copy, Debug, PartialEq)]
623pub struct VanillaEntitySize {
624    /// Name: 1.8 legacy registry name (`"Zombie"`, `"PigZombie"`, `"Player"`), 1.16 registry path
625    /// (`"zombie"`, `"player"`).
626    pub name: &'static str,
627    /// Vanilla registry id (1.8 `EntityType` id = the spawn-mob type for mobs; 1.16 registry id);
628    /// `-1` when the type has none (1.8 players, lightning, fishing bobber) or no client instance.
629    pub registry_id: i32,
630    /// 1.8 spawn packet kind: `"mob"`, `"object"`, `"xp_orb"`, `"painting"`, `"global"`,
631    /// `"player"`; empty for 1.16.
632    pub spawn: &'static str,
633    /// 1.8 spawn-object packet `(type, data)` pairs that create this entity (minecart kinds share
634    /// type 10 with different data).
635    pub object_types: &'static [(i32, i32)],
636    /// Extra growth of the box when picking entities with the crosshair (`getTargetingMargin`).
637    pub targeting_margin: f32,
638    /// 1.16 `EntityDimensions.fixed` (not scaled for babies); `false` in 1.8.
639    pub fixed: bool,
640    /// 1.16 registered type dimensions `(width, height)`; `None` in 1.8.
641    pub registered: Option<(f32, f32)>,
642    /// Measured variants, `"default"` first.
643    pub variants: &'static [EntityVariant],
644    /// 1.16 player: dimensions per pose (`"standing"`, `"crouching"`, `"swimming"`, ...).
645    pub poses: &'static [(&'static str, EntityDimensions)],
646}
647
648impl VanillaEntitySize {
649    /// A measured variant by name.
650    #[must_use]
651    pub fn variant(&self, name: &str) -> Option<&'static EntityVariant> {
652        self.variants.iter().find(|v| v.name == name)
653    }
654
655    /// The size right after spawning (`None` for 1.16 types without a client instance; use
656    /// [`VanillaEntitySize::registered`]).
657    #[must_use]
658    pub fn default_dimensions(&self) -> Option<EntityDimensions> {
659        self.variant("default").map(|v| v.dimensions)
660    }
661
662    /// The `"baby"` variant as the client applies it, for types that have one.
663    #[must_use]
664    pub fn baby(&self) -> Option<EntityDimensions> {
665        self.variant("baby").map(|v| v.dimensions)
666    }
667
668    /// 1.16 player dimensions for a pose.
669    #[must_use]
670    pub fn pose(&self, name: &str) -> Option<EntityDimensions> {
671        self.poses.iter().find(|(n, _)| *n == name).map(|(_, d)| *d)
672    }
673}
674
675/// A biome.
676#[derive(Clone, Copy, Debug, PartialEq)]
677#[non_exhaustive]
678pub struct BiomeInfo {
679    /// Biome id.
680    pub id: u16,
681    /// Registry name.
682    pub name: &'static str,
683    /// English display name.
684    #[cfg(feature = "display-names")]
685    pub display_name: &'static str,
686    /// Category (`"ocean"`, `"plains"`, ...).
687    pub category: &'static str,
688    /// Temperature.
689    pub temperature: f32,
690    /// Rainfall / downfall.
691    pub rainfall: f32,
692    /// Precipitation (`"rain"`, `"snow"`, `"none"`).
693    pub precipitation: &'static str,
694    /// Dimension (`"overworld"`, `"nether"`, `"end"`).
695    pub dimension: &'static str,
696}
697
698/// Linear enchanting cost `a * level + b`.
699#[derive(Clone, Copy, Debug, PartialEq, Eq)]
700pub struct EnchantCost {
701    /// Per-level factor.
702    pub a: i16,
703    /// Offset.
704    pub b: i16,
705}
706
707/// An enchantment.
708#[derive(Clone, Copy, Debug, PartialEq, Eq)]
709#[non_exhaustive]
710pub struct EnchantmentInfo {
711    /// Enchantment id (1.8: the NBT `id` short; 1.16: registry id).
712    pub id: u16,
713    /// Registry name.
714    pub name: &'static str,
715    /// English display name.
716    #[cfg(feature = "display-names")]
717    pub display_name: &'static str,
718    /// Highest level.
719    pub max_level: u8,
720    /// Minimum enchanting cost.
721    pub min_cost: EnchantCost,
722    /// Maximum enchanting cost.
723    pub max_cost: EnchantCost,
724    /// Names of incompatible enchantments.
725    pub exclude: &'static [&'static str],
726    /// Applicable item category (`"armor"`, `"digger"`, ...).
727    pub category: &'static str,
728    /// Random-selection weight.
729    pub weight: u8,
730    /// Only from loot / trades.
731    pub treasure_only: bool,
732    /// Curse.
733    pub curse: bool,
734}
735
736/// A food item.
737#[derive(Clone, Copy, Debug, PartialEq)]
738#[non_exhaustive]
739pub struct FoodInfo {
740    /// Item id (resolved by name against this version's item table).
741    pub item: u16,
742    /// Item name.
743    pub name: &'static str,
744    /// Hunger points restored.
745    pub food_points: u8,
746    /// Saturation restored.
747    pub saturation: f32,
748}
749
750/// A status effect.
751#[derive(Clone, Copy, Debug, PartialEq, Eq)]
752#[non_exhaustive]
753pub struct EffectInfo {
754    /// Effect id.
755    pub id: u8,
756    /// Name as listed by minecraft-data (`"Speed"`).
757    pub name: &'static str,
758    /// English display name.
759    #[cfg(feature = "display-names")]
760    pub display_name: &'static str,
761    /// `true` for beneficial effects.
762    pub good: bool,
763}
764
765/// Binary search in a name-sorted `(name, id)` index.
766#[cfg_attr(not(any(feature = "v1_8", feature = "v1_16_5")), allow(dead_code))]
767pub(crate) fn lookup_name<T: Copy>(index: &[(&'static str, T)], name: &str) -> Option<T> {
768    index
769        .binary_search_by(|(n, _)| (*n).cmp(name))
770        .ok()
771        .map(|i| index[i].1)
772}
773
774/// Binary search in an id-sorted slice by a key function.
775#[cfg_attr(not(any(feature = "v1_8", feature = "v1_16_5")), allow(dead_code))]
776pub(crate) fn lookup_id<T, K: Ord>(
777    items: &'static [T],
778    key: K,
779    f: impl Fn(&T) -> K,
780) -> Option<&'static T> {
781    items
782        .binary_search_by(|x| f(x).cmp(&key))
783        .ok()
784        .map(|i| &items[i])
785}
786
787/// Looks a tool's multiplier up in a generated `TOOL_MULTIPLIERS` table.
788#[cfg_attr(not(any(feature = "v1_8", feature = "v1_16_5")), allow(dead_code))]
789pub(crate) fn tool_multiplier(
790    table: &[(DigMaterial, &[(u16, f32)])],
791    material: DigMaterial,
792    tool: u16,
793) -> f32 {
794    table
795        .iter()
796        .find(|(m, _)| *m == material)
797        .and_then(|(_, tools)| tools.iter().find(|(t, _)| *t == tool))
798        .map_or(1.0, |(_, x)| *x)
799}
800
801/// When a survival dig with a constant per-tick progress finishes.
802#[derive(Clone, Copy, Debug, PartialEq, Eq)]
803pub enum BreakTime {
804    /// Broken by the start packet itself (`START_DESTROY_BLOCK` / 1.8 `attackBlock`, progress ≥ 1
805    /// in one tick).
806    Instant,
807    /// Broken on the `n`-th `continueDestroyBlock` call, counting the one in the start tick:
808    /// the client sends `STOP_DESTROY_BLOCK` on that tick (`n` = 1 is the start tick itself).
809    Ticks(u32),
810    /// Never (progress 0: unbreakable, or a speed of 0).
811    Never,
812}
813
814/// The tick the client finishes the block, accumulating `progress` in `f32` as
815/// `MultiPlayerGameMode` does: the start tick runs `startDestroyBlock` and then
816/// `continueDestroyBlock`, every later tick `continueDestroyBlock`. The first `destroy_delay`
817/// continue calls only count the delay down (5 after the client finished a block, else 0).
818/// `limit` bounds the search (vanilla has none).
819#[must_use]
820pub fn break_time(progress: f32, destroy_delay: u32, limit: u32) -> BreakTime {
821    if progress >= 1.0 {
822        return BreakTime::Instant;
823    }
824    if progress.is_nan() || progress <= 0.0 {
825        return BreakTime::Never;
826    }
827    let mut acc = 0.0f32;
828    for n in 1..=limit {
829        if n <= destroy_delay {
830            continue;
831        }
832        acc += progress;
833        if acc >= 1.0 {
834            return BreakTime::Ticks(n);
835        }
836    }
837    BreakTime::Never
838}
839
840/// One row of a version's generated `ITEM_DIG` table: item id, `(block, speed multiplier)` sorted
841/// by block, effective blocks sorted.
842#[cfg(any(feature = "v1_8", feature = "v1_12", feature = "v1_16_5"))]
843pub(crate) type ItemDig = (u16, &'static [(u16, f32)], &'static [u16]);