ghast_entity/entity.rs
1//! Tracked entity state.
2
3use bytes::Bytes;
4use uuid::Uuid;
5
6/// What kind of entity this is, in the id space of the packet that spawned it.
7#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
8#[non_exhaustive]
9pub enum EntityType {
10 /// A player (`named_entity_spawn`).
11 Player,
12 /// 1.8 – 1.12 mob id (`spawn_entity_living`; the entity registry id), e.g. 54 = zombie. See
13 /// `ghast_data::v1_8::entity(EntityKind::Mob, id)` / `ghast_data::v1_12::entity(..)`.
14 LegacyMob(u8),
15 /// 1.8 – 1.12 object type (`spawn_entity`), e.g. 2 = item, 1 = boat. See
16 /// `ghast_data::v1_8::entity(EntityKind::Object, id)` / `ghast_data::v1_12::entity(..)`.
17 LegacyObject(u8),
18 /// 1.8 – 1.12 experience orb (`spawn_entity_experience_orb`; orb value in [`Entity::data`]).
19 ExperienceOrb,
20 /// 1.8 – 1.12 painting (`spawn_entity_painting`).
21 Painting,
22 /// 1.13+ entity registry id (1.16.5: every spawn packet except players), see
23 /// `ghast_data::v1_16_5::entity`.
24 Registry(u16),
25}
26
27/// Version-independent classification of an entity.
28#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
29#[non_exhaustive]
30pub enum EntityClass {
31 /// A player.
32 Player,
33 /// A dropped item (stack: [`Entity::item`]).
34 Item,
35 /// An experience orb (value: [`Entity::data`]).
36 ExperienceOrb,
37 /// A living non-player entity (spawned with the mob-spawn packet).
38 Mob,
39 /// Any other spawned object (boats, minecarts, arrows, falling blocks, armor stands in 1.8, ...).
40 Object,
41 /// Paintings.
42 Painting,
43}
44
45/// An item stack (equipment, item entities, metadata).
46///
47/// `damage` is the 1.8 damage/metadata value (always 0 in 1.13+, where damage lives in NBT).
48/// `nbt` is a private copy of the raw NBT bytes (never a view into a packet buffer).
49#[derive(Clone, Debug, PartialEq, Eq)]
50pub struct Item {
51 /// Item id.
52 pub id: i32,
53 /// Stack size.
54 pub count: i8,
55 /// 1.8 damage / metadata.
56 pub damage: i16,
57 /// Raw NBT (`None` = no tag).
58 pub nbt: Option<Bytes>,
59}
60
61/// An active status effect as the server reported it.
62#[derive(Clone, Copy, Debug, PartialEq, Eq)]
63pub struct Effect {
64 /// Effect id (1 = speed, 8 = jump boost, ...).
65 pub id: u8,
66 /// Amplifier (level - 1).
67 pub amplifier: i8,
68 /// Duration in ticks at the time of the packet (not counted down here).
69 pub duration: i32,
70 /// 1.8: bit 0 = hide particles. 1.12: bit 0 ambient, bit 1 show particles. 1.16: bit 0 ambient,
71 /// bit 1 show particles, bit 2 show icon.
72 pub flags: u8,
73}
74
75/// One entity metadata value (union of the 1.8, 1.12.2 and 1.16.5 serializer types; variants
76/// marked 1.16 also occur in 1.12 where 1.12 has that serializer).
77#[derive(Clone, Debug, PartialEq)]
78#[non_exhaustive]
79pub enum MetaValue {
80 /// Byte.
81 Byte(i8),
82 /// 1.8 short.
83 Short(i16),
84 /// 1.8 int.
85 Int(i32),
86 /// 1.16 VarInt.
87 VarInt(i32),
88 /// Float.
89 Float(f32),
90 /// String (1.8) / string (1.16).
91 String(Box<str>),
92 /// 1.16 chat component (raw JSON).
93 Chat(Box<str>),
94 /// 1.16 optional chat component (raw JSON).
95 OptChat(Option<Box<str>>),
96 /// Item stack (`None` = empty).
97 Item(Option<Item>),
98 /// 1.16 boolean.
99 Bool(bool),
100 /// Rotation (three floats).
101 Rotation([f32; 3]),
102 /// Block position.
103 BlockPos([i32; 3]),
104 /// 1.16 optional block position.
105 OptBlockPos(Option<[i32; 3]>),
106 /// 1.16 direction.
107 Direction(i32),
108 /// 1.16 optional UUID.
109 OptUuid(Option<Uuid>),
110 /// 1.16 optional block state (0 = none).
111 BlockState(i32),
112 /// 1.16 NBT (raw copy).
113 Nbt(Bytes),
114 /// 1.16 particle (only the particle type id is kept).
115 Particle(i32),
116 /// 1.16 villager data (type, profession, level).
117 VillagerData([i32; 3]),
118 /// 1.16 optional VarInt (0 = none, else value + 1).
119 OptVarInt(i32),
120 /// 1.16 / 26.1 pose.
121 Pose(i32),
122 /// 26.1 long (VarLong).
123 Long(i64),
124 /// 26.1 text component (the raw network NBT, copied).
125 Component(Bytes),
126 /// 26.1 optional text component (raw network NBT).
127 OptComponent(Option<Bytes>),
128 /// 26.1 item stack (`None` = empty; component patch copied out of the packet).
129 #[cfg(feature = "v26_1")]
130 Stack(Option<ghast_protocol::types::slot::v775::ItemStack>),
131 /// 26.1 registry or enum value: `(serializer id, value)` (cat / cow / wolf / frog / pig /
132 /// chicken / zombie nautilus variants and sound variants, sniffer / armadillo / copper golem
133 /// states, humanoid arm).
134 Enum(u8, i32),
135 /// 26.1 vector (three floats).
136 Vector3([f32; 3]),
137 /// 26.1 quaternion (four floats).
138 Quaternion([f32; 4]),
139 /// 26.1 value kept as its raw wire bytes, copied: `(serializer id, bytes)` (optional block
140 /// state, particle, particle list, optional global position, painting variant, resolvable
141 /// profile).
142 Raw(u8, Bytes),
143}
144
145/// The metadata of one entity: `(index, value)` pairs, at most one per index, in arrival order.
146///
147/// Scalar updates overwrite in place (no allocation).
148#[derive(Clone, Debug, Default, PartialEq)]
149pub struct Metadata {
150 entries: Vec<(u8, MetaValue)>,
151}
152
153impl Metadata {
154 /// The value at `index`.
155 #[must_use]
156 pub fn get(&self, index: u8) -> Option<&MetaValue> {
157 self.entries
158 .iter()
159 .find(|(i, _)| *i == index)
160 .map(|(_, v)| v)
161 }
162
163 /// Sets the value at `index`.
164 pub fn set(&mut self, index: u8, value: MetaValue) {
165 match self.entries.iter_mut().find(|(i, _)| *i == index) {
166 Some(slot) => slot.1 = value,
167 None => self.entries.push((index, value)),
168 }
169 }
170
171 /// All entries.
172 pub fn iter(&self) -> impl Iterator<Item = (u8, &MetaValue)> {
173 self.entries.iter().map(|(i, v)| (*i, v))
174 }
175
176 /// Number of entries.
177 #[must_use]
178 pub fn len(&self) -> usize {
179 self.entries.len()
180 }
181
182 /// `true` when nothing has been received.
183 #[must_use]
184 pub fn is_empty(&self) -> bool {
185 self.entries.is_empty()
186 }
187
188 /// Byte at `index` (`Byte` values only).
189 #[must_use]
190 pub fn byte(&self, index: u8) -> Option<i8> {
191 match self.get(index)? {
192 MetaValue::Byte(b) => Some(*b),
193 _ => None,
194 }
195 }
196
197 /// Float at `index`.
198 #[must_use]
199 pub fn float(&self, index: u8) -> Option<f32> {
200 match self.get(index)? {
201 MetaValue::Float(f) => Some(*f),
202 _ => None,
203 }
204 }
205
206 /// Item at `index` (`Some(None)` = an empty stack was sent).
207 #[must_use]
208 pub fn item(&self, index: u8) -> Option<Option<&Item>> {
209 match self.get(index)? {
210 MetaValue::Item(i) => Some(i.as_ref()),
211 _ => None,
212 }
213 }
214
215 pub(crate) fn clear(&mut self) {
216 self.entries.clear();
217 }
218
219 pub(crate) fn entries_mut(&mut self) -> impl Iterator<Item = &mut (u8, MetaValue)> {
220 self.entries.iter_mut()
221 }
222}
223
224/// The protocol family an entity was tracked with (selects metadata indices and size rules).
225#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
226pub(crate) enum Era {
227 /// 1.8.x.
228 #[default]
229 V1_8,
230 /// 1.9 – 1.12 (implemented: 1.12.2).
231 V1_12,
232 /// 1.16.5.
233 V1_16,
234 /// 26.1.
235 V26,
236}
237
238/// 1.16 registry ids used by [`Entity::class`].
239const ITEM_1_16: u16 = 37;
240const XP_ORB_1_16: u16 = 24;
241const PAINTING_1_16: u16 = 55;
242
243/// Number of equipment slots kept (1.16: main hand, off hand, feet, legs, chest, head;
244/// 1.8: held, boots, leggings, chestplate, helmet in slots 0..=4).
245pub const EQUIPMENT_SLOTS: usize = 6;
246
247/// A tracked entity, as the vanilla client knows it from the server's packets.
248#[derive(Clone, Debug)]
249pub struct Entity {
250 pub(crate) id: i32,
251 pub(crate) uuid: Uuid,
252 pub(crate) ty: EntityType,
253 pub(crate) living: bool,
254 /// The tracker's protocol family.
255 pub(crate) era: Era,
256 /// Vanilla size table entry (resolved at spawn).
257 pub(crate) sizer: Option<&'static ghast_data::VanillaEntitySize>,
258 pub(crate) pos: [f64; 3],
259 /// Per version: 1.8 the server position in 1/32 blocks (`serverPos`, i32 values); 1.9 – 1.12
260 /// the tracked position in 1/4096 blocks (`lfloor(x * 4096)`, plus moves); 26.1 the
261 /// `VecDeltaCodec` base (`f64` bits).
262 pub(crate) traced: [i64; 3],
263 pub(crate) yaw: f32,
264 pub(crate) pitch: f32,
265 pub(crate) head_yaw: f32,
266 pub(crate) velocity: [f64; 3],
267 pub(crate) on_ground: bool,
268 pub(crate) data: i32,
269 pub(crate) vehicle: Option<i32>,
270 pub(crate) passengers: Vec<i32>,
271 pub(crate) leash_holder: Option<i32>,
272 pub(crate) meta: Metadata,
273 pub(crate) equipment: Option<Box<[Option<Item>; EQUIPMENT_SLOTS]>>,
274 pub(crate) effects: Vec<Effect>,
275 /// 26.1 client state (codec base, interpolation, size keys), boxed: one pointer for the
276 /// other versions.
277 #[cfg(feature = "v26_1")]
278 pub(crate) m: crate::v26_1::Ext,
279}
280
281impl Entity {
282 pub(crate) fn new(id: i32, ty: EntityType) -> Self {
283 Entity {
284 id,
285 uuid: Uuid::nil(),
286 ty,
287 living: matches!(ty, EntityType::Player | EntityType::LegacyMob(_)),
288 era: Era::V1_8,
289 sizer: None,
290 pos: [0.0; 3],
291 traced: [0; 3],
292 yaw: 0.0,
293 pitch: 0.0,
294 head_yaw: 0.0,
295 velocity: [0.0; 3],
296 on_ground: false,
297 data: 0,
298 vehicle: None,
299 passengers: Vec::new(),
300 leash_holder: None,
301 meta: Metadata::default(),
302 equipment: None,
303 effects: Vec::new(),
304 #[cfg(feature = "v26_1")]
305 m: crate::v26_1::Ext::default(),
306 }
307 }
308
309 /// Network entity id.
310 #[must_use]
311 pub fn id(&self) -> i32 {
312 self.id
313 }
314
315 /// UUID (nil for 1.8 entities other than players).
316 #[must_use]
317 pub fn uuid(&self) -> Uuid {
318 self.uuid
319 }
320
321 /// Type.
322 #[must_use]
323 pub fn entity_type(&self) -> EntityType {
324 self.ty
325 }
326
327 /// Version-independent class.
328 #[must_use]
329 pub fn class(&self) -> EntityClass {
330 #[cfg(feature = "v26_1")]
331 if self.era == Era::V26 {
332 return crate::v26_1::class(self);
333 }
334 match self.ty {
335 EntityType::Player => EntityClass::Player,
336 EntityType::LegacyObject(2) | EntityType::Registry(ITEM_1_16) => EntityClass::Item,
337 EntityType::ExperienceOrb | EntityType::Registry(XP_ORB_1_16) => {
338 EntityClass::ExperienceOrb
339 }
340 EntityType::Painting | EntityType::Registry(PAINTING_1_16) => EntityClass::Painting,
341 _ if self.living => EntityClass::Mob,
342 _ => EntityClass::Object,
343 }
344 }
345
346 /// The stack of an item entity (from metadata; `None` before the server sent it or when
347 /// metadata is not tracked; 1.16 always keeps it for item entities). Always `None` on 26.1,
348 /// whose stacks carry data components: see `v26_1::item_stack` / `v26_1::item_count`.
349 #[must_use]
350 pub fn item(&self) -> Option<&Item> {
351 if self.era == Era::V26 {
352 return None;
353 }
354 let index = match self.ty {
355 EntityType::LegacyObject(2) if self.era == Era::V1_12 => 6,
356 EntityType::LegacyObject(2) => 10,
357 EntityType::Registry(ITEM_1_16) => 7,
358 _ => return None,
359 };
360 self.meta.item(index).flatten()
361 }
362
363 /// Vanilla client-side dimensions: the type's size from ghast-data (checked against the
364 /// oracle), with the variant the client applies from metadata (baby, slime size, wither
365 /// skeleton, elder guardian, small / marker armor stand, 1.16 player pose). `None` for
366 /// hanging entities (paintings, item frames, leash knots), whose box comes from facing.
367 ///
368 /// Variants vanilla applies on the entity's next client tick are applied immediately, and
369 /// the old-min-corner quirk after a resize is not modelled.
370 #[must_use]
371 pub fn dimensions(&self) -> Option<ghast_data::EntityDimensions> {
372 let vs = self.sizer?;
373 match self.era {
374 #[cfg(feature = "v1_8")]
375 Era::V1_8 => crate::v1_8::dimensions(self, vs),
376 #[cfg(feature = "v1_12")]
377 Era::V1_12 => crate::v1_12::dimensions(self, vs),
378 #[cfg(feature = "v1_16_5")]
379 Era::V1_16 => crate::v1_16_5::dimensions(self, vs),
380 #[cfg(feature = "v26_1")]
381 Era::V26 => {
382 let _ = vs;
383 crate::v26_1::dimensions(self)
384 }
385 // A tracker only stamps eras of versions compiled in.
386 #[allow(unreachable_patterns)]
387 _ => None,
388 }
389 }
390
391 /// How much the crosshair pick grows this entity's box (vanilla `getCollisionBorderSize` /
392 /// `getTargetingMargin`, from the type's size table: 0.1 for most 1.8 types, 0 since 1.9,
393 /// 1.0 for fireballs); 0 when the type has no size entry.
394 #[must_use]
395 pub fn targeting_margin(&self) -> f32 {
396 self.sizer.map_or(0.0, |s| s.targeting_margin)
397 }
398
399 /// `(width, height)` of [`Entity::dimensions`].
400 #[must_use]
401 pub fn size(&self) -> Option<(f32, f32)> {
402 self.dimensions().map(|d| (d.width, d.height))
403 }
404
405 /// Vanilla bounding box at the server position, `[min_x, min_y, min_z, max_x, max_y,
406 /// max_z]` (bit-exact `EntityDimensions::bounding_box`).
407 #[must_use]
408 pub fn bounding_box(&self) -> Option<[f64; 6]> {
409 let [x, y, z] = self.pos;
410 let b = self.dimensions()?.bounding_box(x, y, z);
411 Some([b.min_x, b.min_y, b.min_z, b.max_x, b.max_y, b.max_z])
412 }
413
414 /// `true` for players.
415 #[must_use]
416 pub fn is_player(&self) -> bool {
417 self.ty == EntityType::Player
418 }
419
420 /// The **server position**: exactly the coordinates the vanilla client tracks from the
421 /// packets (1.8: `serverPos / 32.0`; 1.12: spawn / teleport coordinates, after a relative
422 /// move the tracked 1/4096 position; 1.16: the packet coordinates, rel moves applied in
423 /// 1/4096 fixed point). The rendered position interpolates towards this over 3 ticks in
424 /// vanilla; a bot does not need that.
425 ///
426 /// **26.1** is different: this is the entity's *current* position as the client holds it
427 /// (`Entity.position()`): position packets of interpolated entities (living entities, boats,
428 /// minecarts) set a target the entity reaches over 3 calls of `v26_1::Tracker::tick`, others
429 /// move at once. That is the position vanilla's crosshair pick reads at tick time (with
430 /// [`Entity::bounding_box`]); the packet coordinates are `v26_1::server_position`.
431 #[must_use]
432 pub fn position(&self) -> [f64; 3] {
433 self.pos
434 }
435
436 /// 1.8 only: the raw server position in 1/32 blocks (`[0; 3]` in 1.12 and 1.16).
437 #[must_use]
438 pub fn fixed_position(&self) -> [i32; 3] {
439 if self.era == Era::V1_8 {
440 self.traced.map(|t| t as i32)
441 } else {
442 [0; 3]
443 }
444 }
445
446 /// Body yaw in degrees as vanilla computes it from the angle byte (`b * 360 / 256f`).
447 #[must_use]
448 pub fn yaw(&self) -> f32 {
449 self.yaw
450 }
451
452 /// Pitch in degrees.
453 #[must_use]
454 pub fn pitch(&self) -> f32 {
455 self.pitch
456 }
457
458 /// Head yaw in degrees (from `entity_head_rotation`; mobs also at spawn).
459 #[must_use]
460 pub fn head_yaw(&self) -> f32 {
461 self.head_yaw
462 }
463
464 /// Last velocity the server sent (blocks per tick), from the spawn packet or
465 /// `entity_velocity`. Not integrated over time.
466 #[must_use]
467 pub fn velocity(&self) -> [f64; 3] {
468 self.velocity
469 }
470
471 /// On-ground flag of the last movement packet.
472 #[must_use]
473 pub fn on_ground(&self) -> bool {
474 self.on_ground
475 }
476
477 /// Spawn data: object data (1.8 objects / 1.16 `spawn_entity`), experience orb value,
478 /// painting direction.
479 #[must_use]
480 pub fn data(&self) -> i32 {
481 self.data
482 }
483
484 /// Entity this one rides.
485 #[must_use]
486 pub fn vehicle(&self) -> Option<i32> {
487 self.vehicle
488 }
489
490 /// Entities riding this one (1.8: at most one).
491 #[must_use]
492 pub fn passengers(&self) -> &[i32] {
493 &self.passengers
494 }
495
496 /// Entity holding this one's leash.
497 #[must_use]
498 pub fn leash_holder(&self) -> Option<i32> {
499 self.leash_holder
500 }
501
502 /// Metadata (empty unless metadata tracking is enabled).
503 #[must_use]
504 pub fn metadata(&self) -> &Metadata {
505 &self.meta
506 }
507
508 /// Equipment slot (see [`EQUIPMENT_SLOTS`]); `None` if never sent or empty.
509 #[must_use]
510 pub fn equipment(&self, slot: usize) -> Option<&Item> {
511 self.equipment.as_ref()?.get(slot)?.as_ref()
512 }
513
514 /// Active effects as last reported.
515 #[must_use]
516 pub fn effects(&self) -> &[Effect] {
517 &self.effects
518 }
519
520 /// The effect with this id, if active.
521 #[must_use]
522 pub fn effect(&self, id: u8) -> Option<&Effect> {
523 self.effects.iter().find(|e| e.id == id)
524 }
525}