ghast-client 0.5.5

Headless Minecraft Java Edition client for the ghast library: connection, login, fixed 50 ms tick loop and a version-agnostic bot API (1.8.9, 1.12.2, 1.16.5, 26.1, 26.2 and 26.3)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
//! 1.12.2: the client-side physics of the tracked non-living entities
//! ([`crate::Interests::ENTITY_PHYSICS`]): projectiles, item entities, experience orbs, primed
//! TNT and falling blocks run their own tick on the client every client tick
//! (`World.checkChunk`), with the client's side of the rules
//! (`ghast_physics::v1_12::{projectile, drop}`, oracle-proven per kind).
//!
//! The physics state is the client's copy of the entity. Each packet the tracker applied is
//! handed to the copy the way `ClientPlayNetworkHandler` does it, and the copy is written back
//! to the tracker ([`ghast_entity::v1_12::Tracker::client_simulated`]):
//!
//! * spawn (`onEntitySpawn`): the entity the client constructs (a falling block 0.01 higher than
//!   the packet's position, a hurting projectile's acceleration from the packet's motion), the
//!   packet's rotation, then `setVelocityClient` with the packet's motion when the object data
//!   is above 0 after the client's resets; an item's, orb's and TNT's constructor motion comes
//!   from an unseeded random — here the packet's motion (0 without one), which the velocity
//!   packet a server sends after a spawn replaces;
//! * relative moves and the bare `entity` packet (`onEntityUpdate`): the copy moves to the
//!   tracked position (`updatePosition`) with the packet's rotation or its own (`% 360`);
//!   teleports (`onEntityPosition`) keep the copy's position when it is within 1/32 (1/64
//!   vertically) of the packet's; a fishing bobber ignores both; the ground flag is the
//!   packet's;
//! * velocity (`setVelocityClient`): a thrown item or an arrow with a previous rotation of 0 / 0
//!   also turns to the motion;
//! * entity data: no gravity, a TNT's fuse, a dangerous wither skull, a tipped arrow's colour,
//!   a bobber's hooked entity (it follows the entity's drawn position at 0.8 of its height; the
//!   order of the entity's own tick against the bobber's is not modelled). A 1.12 server sends
//!   no bite flag: a bite reaches the client as the server's velocity packet.
//!
//! A 1.12 client ticks every entity it holds, loaded column or not; an entity spawned in an
//! unloaded column waits for its chunk (not simulated here). The client discards a TNT whose
//! fuse ran out, a falling block of air, a bobber without its player owner and an entity below
//! y −64.
//!
//! An orb follows the nearest player within 8 blocks (as 1.8.9, pulled towards half the eye
//! height): the eye height from the entity flags (sneaking 1.54, gliding 0.4) or the box height
//! the player's last `updateSize` left (1.65, 0.6: a box that cannot grow keeps its height).
//!
//! Not simulated: entity hits, pickup, merging (the client runs none of them), passengers,
//! the falling block's removal of its own block from the client world, a hurting
//! projectile spawned without motion (its acceleration is NaN in vanilla), and the random
//! draws of a client entity (unseeded in vanilla; seeded with the entity id here).

use std::collections::HashMap;

use super::*;
use crate::sim::shared::PlayerFacts;
use ghast_entity::EntityType;
use ghast_physics::v1_12::Side;
use ghast_physics::v1_12::drop::{self, Drop, DropKind, OrbPlayer};
use ghast_physics::v1_12::projectile::{self, HookedEntity, Projectile, ProjectileKind};

#[derive(Debug)]
enum State {
    Projectile(Projectile),
    Drop(Drop),
}

/// One simulated entity.
#[derive(Debug)]
struct Entry {
    state: State,
    /// A bobber's hooked entity (`caughtEntity`: the tracked id named an entity the client has).
    hook: Option<i32>,
    /// Its place in `World.loadedEntityList`.
    seq: u64,
}

/// A position / motion / rotation / ground update for the tracker.
type Update = (i32, [f64; 3], [f64; 3], [f32; 2], bool);

/// The simulated entities (a side table: only while [`crate::Interests::ENTITY_PHYSICS`] is on).
#[derive(Debug, Default)]
pub(super) struct NonLiving12 {
    map: HashMap<i32, Entry>,
    updates: Vec<Update>,
    discards: Vec<i32>,
    /// The order of `World.loadedEntityList` (spawn order) for the entries and the players.
    seq: u64,
    /// Player entities: entity flags (index 0: 0x02 sneaking, 0x80 gliding), place in the list
    /// and box height (`updateSize` at the player's tick: 1.65 sneaking, 0.6 gliding).
    flags: HashMap<i32, (u8, u64, f32)>,
    idents: crate::sim::shared::PlayerIdents,
    /// Orbs are simulated: the other players' drawn positions before this tick's entity ticks.
    pre: Vec<(i32, [f64; 3])>,
    /// `World.playerEntities` after the entity ticks: each player, the same player as an
    /// entity that ticks later reads it (position, box height before its tick) and its place.
    players: Vec<(OrbPlayer, OrbPlayer, u64)>,
    /// The players one orb reads.
    seen: Vec<OrbPlayer>,
}

impl NonLiving12 {
    /// Forgets every entity (a new world, a new tracker).
    pub(super) fn clear(&mut self) {
        self.map.clear();
        self.flags.clear();
        self.idents.clear();
    }

    fn has_orbs(&self) -> bool {
        self.map
            .values()
            .any(|en| matches!(&en.state, State::Drop(d) if d.kind() == DropKind::ExperienceOrb))
    }
}

/// `PlayerEntity.getEyeHeight` of 1.12.2: 0.2 asleep, 1.54 sneaking or 1.65 high, 0.4 gliding
/// or 0.6 high, else 1.62.
pub(super) fn eye_height(asleep: bool, sneaking: bool, gliding: bool, height: f32) -> f32 {
    if asleep {
        0.2
    } else if sneaking || height == 1.65 {
        1.62 - 0.08
    } else if gliding || height == 0.6 {
        0.4
    } else {
        1.62
    }
}

/// The box height a player's `updateSize` picks from its flags (gliding 0.6, sneaking 1.65,
/// else 1.8).
fn size_height(flags: u8) -> f32 {
    if flags & 0x80 != 0 {
        0.6
    } else if flags & 0x02 != 0 {
        1.65
    } else {
        1.8
    }
}

/// Another player's `updateSize` at its tick (after its interpolation step, at `pos`): the
/// height its flags ask for when the box of that height, grown from the box's minimum corner,
/// is free of blocks; else the old `height`.
fn resize<W: ghast_physics::BlockView<State = ghast_physics::v1_12::BlockState>>(
    world: &W,
    pos: [f64; 3],
    height: f32,
    flags: u8,
) -> f32 {
    let h = size_height(flags);
    if h == height {
        return h;
    }
    let half = f64::from(0.6f32 / 2.0);
    let (x, z) = (pos[0] - half, pos[2] - half);
    let w = f64::from(0.6f32);
    let b = ghast_physics::math::Aabb::new(x, pos[1], z, x + w, pos[1] + f64::from(h), z + w);
    if ghast_physics::v1_12::collides_with_any_block(world, &b) {
        height
    } else {
        h
    }
}

/// Entity data indices (1.12.2: `Entity` defines 0 – 5, a subclass starts at 6).
mod data_index {
    pub(super) const NO_GRAVITY: u8 = 5;
    /// `WitherSkullEntity.CHARGED`, `TntEntity.FUSE`, `FishingBobberEntity.HOOK_ENTITY_ID`.
    pub(super) const FIRST: u8 = 6;
    /// `ArrowEntity.COLOR`.
    pub(super) const ARROW_COLOR: u8 = 7;
}

/// The kind of a 1.12 object type (`onEntitySpawn`'s type byte).
fn kind_of(t: EntityType) -> Option<State> {
    let pos = [0.0; 3];
    Some(match t {
        EntityType::ExperienceOrb => State::Drop(Drop::new(DropKind::ExperienceOrb, pos, pos)),
        EntityType::LegacyObject(o) => {
            let p = |k| Some(State::Projectile(Projectile::new(k, pos, pos)));
            let d = |k| Some(State::Drop(Drop::new(k, pos, pos)));
            return match o {
                2 => d(DropKind::Item),
                50 => d(DropKind::PrimedTnt),
                70 => d(DropKind::FallingBlock),
                60 => p(ProjectileKind::Arrow),
                91 => p(ProjectileKind::SpectralArrow),
                61 => p(ProjectileKind::Snowball),
                62 => p(ProjectileKind::Egg),
                65 => p(ProjectileKind::EnderPearl),
                // one `potion` object (splash or lingering by its stack; the same physics)
                73 => p(ProjectileKind::SplashPotion),
                75 => p(ProjectileKind::ExperienceBottle),
                63 => p(ProjectileKind::LargeFireball),
                64 => p(ProjectileKind::SmallFireball),
                66 => p(ProjectileKind::WitherSkull),
                93 => p(ProjectileKind::DragonFireball),
                90 => p(ProjectileKind::FishingBobber),
                _ => None,
            };
        }
        _ => return None,
    })
}

/// Object types whose object data the client resets to 0 before it applies the motion.
fn data_reset(t: u8) -> bool {
    matches!(t, 63 | 64 | 66 | 67 | 70 | 71 | 73 | 75 | 77 | 90 | 93)
}

impl Sim12 {
    /// Switches the client-side physics of the non-living entities on or off.
    pub(super) fn set_nonliving(&mut self, on: bool) {
        if on == self.nonliving.is_some() {
            return;
        }
        // Entities spawned before are known again once the server sends them again.
        self.nonliving = on.then(Box::default);
        // entity data packets (entity_packet_ids)
        self.glide.filter_dirty = true;
    }

    /// A packet the simulated entities care about, after the tracker applied it.
    #[cold]
    #[inline(never)]
    pub(super) fn nonliving_packet(&mut self, raw: &RawPacket) -> Result<(), SimError> {
        use ghast_protocol::defs::p340::types::EntityMetadataValue as V;
        use ghast_protocol::v1_12_2::play::clientbound as cb;
        let (Some(n), Some(t)) = (&mut self.nonliving, &mut self.entities) else {
            return Ok(());
        };
        let mut r = ghast_protocol::Reader::new(&raw.body);
        let id = match raw.id {
            cb::id::LOGIN => {
                n.clear();
                return Ok(());
            }
            cb::id::NAMED_ENTITY_SPAWN => {
                // Another player: a new object at the end of the lists, with its entity flags.
                let p: cb::NamedEntitySpawn = raw.decode_as()?;
                let id = p.entity_id;
                if !t.get(id).is_some_and(ghast_entity::Entity::is_player) {
                    return Ok(());
                }
                let flags = p
                    .metadata
                    .iter()
                    .find_map(|m| match (m.key, &m.value) {
                        (0, V::Byte(b)) => Some(*b as u8),
                        _ => None,
                    })
                    .unwrap_or(0);
                n.seq += 1;
                // the constructor's 0.6 x 1.8 until its first tick
                n.flags.insert(id, (flags, n.seq, 1.8));
                n.idents.spawned(id);
                return Ok(());
            }
            cb::id::SPAWN_ENTITY | cb::id::SPAWN_ENTITY_EXPERIENCE_ORB => {
                let id = r.read_varint()?;
                n.map.remove(&id);
                n.flags.remove(&id);
                // The spawn packet's motion (the tracker keeps it only when the client applies
                // it): uuid, type, x, y, z, pitch, yaw, data, then the motion.
                let packet_vel = if raw.id == cb::id::SPAWN_ENTITY {
                    r.skip(16 + 1 + 24 + 2 + 4)?;
                    [r.read_i16()?, r.read_i16()?, r.read_i16()?].map(|c| f64::from(c) / 8000.0)
                } else {
                    [0.0; 3]
                };
                let Some(e) = t.get(id) else {
                    return Ok(());
                };
                let Some(state) = spawned(e, packet_vel) else {
                    return Ok(());
                };
                n.seq += 1;
                let seq = n.seq;
                n.map.insert(
                    id,
                    Entry {
                        state,
                        hook: None,
                        seq,
                    },
                );
                id
            }
            cb::id::ENTITY_VELOCITY => {
                let id = r.read_varint()?;
                let (Some(en), Some(e)) = (n.map.get_mut(&id), t.get(id)) else {
                    return Ok(());
                };
                match &mut en.state {
                    State::Projectile(p) => p.set_velocity_client(e.velocity()),
                    State::Drop(d) => d.set_vel(e.velocity()),
                }
                id
            }
            cb::id::REL_ENTITY_MOVE
            | cb::id::ENTITY_MOVE_LOOK
            | cb::id::ENTITY_LOOK
            | cb::id::ENTITY
            | cb::id::ENTITY_TELEPORT => {
                let id = r.read_varint()?;
                let (Some(en), Some(e)) = (n.map.get_mut(&id), t.get(id)) else {
                    return Ok(());
                };
                let target = e.position();
                // onEntityPosition: a copy within 1/32 (1/64 vertically) of the packet's
                // position stays where it is.
                let to = |at: [f64; 3]| {
                    if raw.id == cb::id::ENTITY_TELEPORT
                        && (at[0] - target[0]).abs() < 0.03125
                        && (at[1] - target[1]).abs() < 0.015625
                        && (at[2] - target[2]).abs() < 0.03125
                    {
                        at
                    } else {
                        target
                    }
                };
                match &mut en.state {
                    // FishingBobberEntity.updateTrackedPositionAndAngles does nothing.
                    State::Projectile(p) if p.kind() == ProjectileKind::FishingBobber => {}
                    State::Projectile(p) => {
                        p.set_pos(to(p.pos()));
                        p.set_rotation(e.yaw() % 360.0, e.pitch() % 360.0);
                    }
                    State::Drop(d) => d.set_pos(to(d.pos())),
                }
                match &mut en.state {
                    State::Projectile(p) => p.set_on_ground(e.on_ground()),
                    State::Drop(d) => d.set_on_ground(e.on_ground()),
                }
                id
            }
            cb::id::ENTITY_METADATA => {
                let id = r.read_varint()?;
                if let Some(e) = t.get(id).filter(|e| e.is_player()) {
                    let orbs = n.has_orbs();
                    // A player's entity flags (sneaking, gliding; one spawned before the
                    // physics was on counts as first in the list).
                    let f = n.flags.entry(id).or_insert((0, 0, 1.8));
                    let m: cb::EntityMetadata = raw.decode_as()?;
                    for m in &m.metadata {
                        if let (0, V::Byte(b)) = (m.key, &m.value) {
                            f.0 = *b as u8;
                        }
                    }
                    // No orb reads the player's box height before its next tick: no need to
                    // wait for that tick.
                    if !orbs {
                        f.2 = resize(&self.world, e.drawn_position(), f.2, f.0);
                    }
                    // a followed player's eye height reads the flags at once
                    let eye = eye_height(false, f.0 & 0x02 != 0, f.0 & 0x80 != 0, f.2);
                    n.idents.eye_changed(id, eye);
                    return Ok(());
                }
                let Some(en) = n.map.get_mut(&id) else {
                    return Ok(());
                };
                let p: cb::EntityMetadata = raw.decode_as()?;
                for m in &p.metadata {
                    match (&mut en.state, m.key, &m.value) {
                        (State::Projectile(p), data_index::NO_GRAVITY, V::Boolean(b)) => {
                            p.set_no_gravity(*b);
                        }
                        (State::Drop(d), data_index::NO_GRAVITY, V::Boolean(b)) => {
                            d.set_no_gravity(*b);
                        }
                        (State::Projectile(p), data_index::ARROW_COLOR, V::VarInt(c))
                            if p.kind() == ProjectileKind::Arrow =>
                        {
                            p.set_tipped(*c != -1);
                        }
                        (State::Projectile(p), data_index::FIRST, V::Boolean(b))
                            if p.kind() == ProjectileKind::WitherSkull =>
                        {
                            p.set_dangerous(*b);
                        }
                        (State::Projectile(p), data_index::FIRST, V::VarInt(h))
                            if p.kind() == ProjectileKind::FishingBobber =>
                        {
                            // onTrackedDataSet: caughtEntity = world.getEntityById(id - 1)
                            en.hook = (*h > 0).then(|| *h - 1).filter(|&i| t.get(i).is_some());
                            if en.hook.is_none() {
                                p.set_hooked(None);
                            }
                        }
                        (State::Drop(d), data_index::FIRST, V::VarInt(f))
                            if d.kind() == DropKind::PrimedTnt =>
                        {
                            d.set_fuse(*f);
                        }
                        _ => {}
                    }
                }
                return Ok(());
            }
            _ => return Ok(()),
        };
        // The copy as the handler left it.
        if let Some(en) = n.map.get(&id) {
            let (pos, vel, rot, g) = copy_of(&en.state, t.get(id));
            t.client_simulated(id, pos, vel, rot, g);
        }
        Ok(())
    }

    /// Before the other entities' interpolation steps: where the other players are, when an
    /// orb may read them before their own tick. Called only with a tracker and simulated
    /// entities (the plain tick tests neither).
    #[cold]
    #[inline(never)]
    pub(super) fn nonliving_before_tick(n: &mut NonLiving12, t: &ghast_entity::v1_12::Tracker) {
        n.pre.clear();
        if !n.has_orbs() {
            return;
        }
        n.pre.extend(
            t.iter()
                .filter(|e| e.is_player())
                .map(|e| (e.id(), e.drawn_position())),
        );
    }

    /// `World.playerEntities` for the orbs: ours first (where this tick's movement left it),
    /// then the others in spawn order, after the entity ticks and as an orb before them reads
    /// them; then the followed players that left the world. Each other player's box height
    /// follows its flags at its tick.
    fn orb_players(&mut self) {
        let (Some(n), Some(t)) = (&mut self.nonliving, &self.entities) else {
            return;
        };
        n.players.clear();
        if !n.has_orbs() {
            return;
        }
        let NonLiving12 {
            map,
            flags,
            idents,
            pre,
            players,
            ..
        } = &mut **n;
        let p = &self.player;
        let me = t.self_id().unwrap_or(self.glide.own_id);
        let eye = eye_height(
            self.ext.sleeping,
            p.sneaking(),
            self.ext.fall_flying,
            p.height,
        );
        let own = OrbPlayer::new(me, p.pos, eye).with_spectator(p.spectator);
        players.push((own, own, 0));
        flags.retain(|&id, _| t.get(id).is_some_and(ghast_entity::Entity::is_player));
        for e in t.iter().filter(|e| e.is_player() && e.id() != me) {
            let id = e.id();
            // A player spawned before the physics was on: first in the list, flags unknown.
            let f = flags.entry(id).or_insert((0, 0, 1.8));
            let (bits, seq, height) = *f;
            let (sneak, glide) = (bits & 0x02 != 0, bits & 0x80 != 0);
            let now_pos = e.drawn_position();
            f.2 = resize(&self.world, now_pos, height, bits);
            let before_pos = pre.iter().find(|q| q.0 == id).map_or(now_pos, |q| q.1);
            let ident = idents.of(id);
            let uuid = e.uuid();
            // AbstractClientPlayerEntity.isSpectator: the tab-list entry, looked up each time.
            let spectator = t.tab_game_mode(&uuid) == Some(3);
            let now_eye = eye_height(false, sneak, glide, f.2);
            idents.seen(
                ident,
                PlayerFacts {
                    uuid,
                    #[cfg(ghast_modern)]
                    generation: 0,
                    spectator,
                    pos: now_pos,
                    eye_height: now_eye,
                },
            );
            let now = OrbPlayer::new(ident, now_pos, now_eye).with_spectator(spectator);
            let before = OrbPlayer::new(ident, before_pos, eye_height(false, sneak, glide, height))
                .with_spectator(spectator);
            players.push((now, before, seq));
        }
        players[1..].sort_by_key(|q| q.2);
        for en in map.values() {
            let State::Drop(d) = &en.state else { continue };
            let Some(ident) = d.following() else { continue };
            if players.iter().any(|q| q.0.id == ident) {
                continue;
            }
            let Some(mut f) = idents.facts(ident) else {
                continue;
            };
            f.spectator = t.tab_game_mode(&f.uuid) == Some(3);
            idents.seen(ident, f);
            let gone = OrbPlayer::new(ident, f.pos, f.eye_height)
                .with_spectator(f.spectator)
                .with_removed(true);
            players.push((gone, gone, u64::MAX));
        }
        idents.retain(|k| players.iter().any(|q| q.0.id == k));
    }

    /// One client tick of the simulated entities (`World.checkChunk` of each one that is not
    /// riding: a 1.12 client ticks every entity it holds).
    #[cold]
    #[inline(never)]
    pub(super) fn tick_nonliving(&mut self) {
        if self.nonliving.as_ref().is_none_or(|n| n.map.is_empty()) {
            return;
        }
        self.orb_players();
        let (Some(n), Some(t)) = (&mut self.nonliving, &mut self.entities) else {
            return;
        };
        let world = &self.world;
        let me = self.glide.own_id;
        let NonLiving12 {
            map,
            updates,
            discards,
            players,
            seen,
            ..
        } = &mut **n;
        updates.clear();
        discards.clear();
        map.retain(|&id, en| {
            let Some(e) = t.get(id) else {
                return false;
            };
            if e.vehicle().is_some() {
                return true;
            }
            match &mut en.state {
                State::Projectile(p) => {
                    if p.kind() == ProjectileKind::FishingBobber {
                        // getOwner: the spawn's owner, a player.
                        let owner = e.data();
                        let pos = if owner == me || t.self_id() == Some(owner) {
                            Some([0.0; 3])
                        } else {
                            t.get(owner)
                                .filter(|o| o.is_player())
                                .map(ghast_entity::Entity::position)
                        };
                        p.set_owner_pos(pos);
                        // caughtEntity: the bottom of its box now; gone, the bobber lets go
                        p.set_hooked(en.hook.map(|h| {
                            t.get(h)
                                .and_then(|he| {
                                    he.size().map(|(_, height)| {
                                        HookedEntity::new(he.drawn_position(), height)
                                    })
                                })
                                .unwrap_or(HookedEntity::removed())
                        }));
                    }
                    projectile::tick_projectile(p, Side::Client, world);
                    if p.hooked().is_none() {
                        en.hook = None;
                    }
                    if p.removed() {
                        discards.push(id);
                        return false;
                    }
                }
                State::Drop(d) => {
                    seen.clear();
                    if d.kind() == DropKind::ExperienceOrb {
                        // A player before the orb in the list has ticked already.
                        seen.extend(
                            players
                                .iter()
                                .map(|&(now, before, seq)| if seq > en.seq { before } else { now }),
                        );
                    }
                    drop::tick_drop_near(d, Side::Client, world, seen);
                    if d.removed() {
                        discards.push(id);
                        return false;
                    }
                }
            }
            let (pos, vel, rot, g) = copy_of(&en.state, Some(e));
            updates.push((id, pos, vel, rot, g));
            true
        });
        for &(id, pos, vel, rot, g) in updates.iter() {
            t.client_simulated(id, pos, vel, rot, g);
        }
        for &id in discards.iter() {
            t.client_discarded(id);
        }
    }
}

/// Position, motion, rotation and ground flag of the client copy (a drop keeps the tracker's
/// rotation: its tick never turns it).
fn copy_of(s: &State, e: Option<&ghast_entity::Entity>) -> ([f64; 3], [f64; 3], [f32; 2], bool) {
    match s {
        State::Projectile(p) => (p.pos(), p.vel(), [p.yaw(), p.pitch()], p.on_ground()),
        State::Drop(d) => (
            d.pos(),
            d.vel(),
            e.map_or([0.0; 2], |e| [e.yaw(), e.pitch()]),
            d.on_ground(),
        ),
    }
}

/// The client's copy of a freshly spawned entity (`onEntitySpawn` / `onExperienceOrbSpawn`): the
/// constructor at the packet's position, the packet's rotation, then the packet's motion through
/// `setVelocityClient` when the object data (after the client's resets) is above 0. `None` for
/// other types. Its random is seeded with the entity id.
fn spawned(e: &ghast_entity::Entity, packet_vel: [f64; 3]) -> Option<State> {
    let ty = e.entity_type();
    let pos = e.position();
    let seed = i64::from(e.id());
    let applies = match ty {
        EntityType::LegacyObject(o) => !data_reset(o) && e.data() > 0,
        _ => false,
    };
    Some(match kind_of(ty)? {
        State::Projectile(k) => {
            let k = k.kind();
            // Only a hurting projectile's constructor reads the motion (its acceleration).
            let mut p = Projectile::new(k, pos, packet_vel).with_random_seed(seed);
            p.set_vel([0.0; 3]);
            p.set_rotation(e.yaw(), e.pitch());
            if applies {
                p.set_velocity_client(packet_vel);
            }
            State::Projectile(p)
        }
        State::Drop(k) => {
            let k = k.kind();
            let mut d = Drop::new(k, pos, e.velocity())
                .with_id(e.id())
                .with_random_seed(seed);
            if k == DropKind::FallingBlock {
                // FallingBlockEntity: the block from the data (id | meta << 12), the position
                // raised by half the missing height.
                let raw = e.data() & 0xFFFF;
                let block = ghast_data::v1_12::BlockState::from_raw_vanilla(
                    (((raw & 4095) as u16) << 4) | ((raw >> 12) & 15) as u16,
                );
                d = Drop::new(
                    k,
                    [
                        pos[0],
                        pos[1] + f64::from((1.0f32 - 0.98f32) / 2.0f32),
                        pos[2],
                    ],
                    [0.0; 3],
                )
                .with_id(e.id())
                .with_random_seed(seed)
                .with_block(block);
            } else if applies {
                d.set_vel(packet_vel);
            }
            State::Drop(d)
        }
    })
}