ghast-physics 0.5.4

Vanilla-exact, pure and deterministic player movement for the ghast Minecraft Java Edition client library (1.8.9, 1.12.2, 1.16.5, 26.1, 26.2 and 26.3), verified bit for bit against the real game
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
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
//! Projectiles of 1.8.9: thrown items, arrows, hurting projectiles (fireballs, wither skulls) and
//! the fishing bobber, each ticked as the server and as a client tick it, checked bit for bit
//! against the vanilla oracle (`tests/golden/1.8.9/projectiles.jsonl.gz`).
//!
//! A [`Projectile`] is the entity's state; [`tick_projectile`] runs one tick of it in a world for
//! a [`Side`] and returns the block hit of that tick (vanilla `World.rayTrace`'s result: the block,
//! face and exact point); [`run_projectile`] ticks until the first block hit (or removal). No
//! entity is hit: which entity a projectile hits is the server's decision and needs the other
//! entities, which this module does not see.
//!
//! What the sides do differently (all from the vanilla tick):
//!
//! * thrown items and hurting projectiles: the server removes them on their first block hit; a
//!   client keeps ticking its copy, which moves on by its whole motion every tick;
//! * hurting projectiles: the server removes one outside the build height or in a chunk that is
//!   not loaded;
//! * the fishing bobber: the server removes it when the owner does not hold a rod or is more than
//!   32 blocks away; in water only the client's tick is modelled (the server's bite timers draw
//!   from the same random). 1.8's bobber has no flying / bobbing states: it moves by
//!   `Entity.move`, floats by the part of its box in water, and a block in its path sticks it for
//!   one tick only (the block is never stored, so the next tick lets it fall, three draws).

use ghast_data::v1_8::BlockState;

use super::blocks::{HistoryShapes, is_air, is_valid_pos, is_water, state_at};
use super::body::{self, Body};
use crate::math::{Aabb, sqrt_f64_as_f32};
pub use crate::nonliving::Side;
use crate::nonliving::{LegacyRandom, atan2, degrees_1_8 as degrees, lerp_rotation};
use crate::pick::{BlockHit, Direction};
use crate::world::BlockView;

/// The kinds of projectile.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ProjectileKind {
    /// `snowball` (gravity 0.03).
    Snowball,
    /// `egg` (gravity 0.03).
    Egg,
    /// `ender_pearl` (gravity 0.03).
    EnderPearl,
    /// `experience_bottle` (gravity 0.07).
    ExperienceBottle,
    /// `potion` (a splash potion; gravity 0.05).
    SplashPotion,
    /// `arrow` (gravity 0.05, water inertia 0.6).
    Arrow,
    /// `small_fireball` (inertia 0.95).
    SmallFireball,
    /// `fireball` (the ghast's large fireball).
    LargeFireball,
    /// `wither_skull` (a dangerous one: inertia 0.73).
    WitherSkull,
    /// `fishing_bobber`.
    FishingBobber,
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum Family {
    Thrown,
    Hurting,
    Arrow,
    Bobber,
}

impl ProjectileKind {
    /// Every kind.
    pub const ALL: [ProjectileKind; 10] = [
        ProjectileKind::Snowball,
        ProjectileKind::Egg,
        ProjectileKind::EnderPearl,
        ProjectileKind::ExperienceBottle,
        ProjectileKind::SplashPotion,
        ProjectileKind::Arrow,
        ProjectileKind::SmallFireball,
        ProjectileKind::LargeFireball,
        ProjectileKind::WitherSkull,
        ProjectileKind::FishingBobber,
    ];

    /// The name used for the kind (the modern entity type id).
    #[must_use]
    pub const fn entity_name(self) -> &'static str {
        match self {
            ProjectileKind::Snowball => "snowball",
            ProjectileKind::Egg => "egg",
            ProjectileKind::EnderPearl => "ender_pearl",
            ProjectileKind::ExperienceBottle => "experience_bottle",
            ProjectileKind::SplashPotion => "splash_potion",
            ProjectileKind::Arrow => "arrow",
            ProjectileKind::SmallFireball => "small_fireball",
            ProjectileKind::LargeFireball => "fireball",
            ProjectileKind::WitherSkull => "wither_skull",
            ProjectileKind::FishingBobber => "fishing_bobber",
        }
    }

    /// The kind of a name (with or without the `minecraft:` namespace).
    #[must_use]
    pub fn from_entity_name(name: &str) -> Option<ProjectileKind> {
        let name = name.strip_prefix("minecraft:").unwrap_or(name);
        ProjectileKind::ALL
            .into_iter()
            .find(|k| k.entity_name() == name)
    }

    fn family(self) -> Family {
        match self {
            ProjectileKind::Snowball
            | ProjectileKind::Egg
            | ProjectileKind::EnderPearl
            | ProjectileKind::ExperienceBottle
            | ProjectileKind::SplashPotion => Family::Thrown,
            ProjectileKind::SmallFireball
            | ProjectileKind::LargeFireball
            | ProjectileKind::WitherSkull => Family::Hurting,
            ProjectileKind::Arrow => Family::Arrow,
            ProjectileKind::FishingBobber => Family::Bobber,
        }
    }

    /// Box width and height of the entity type.
    #[must_use]
    pub const fn dimensions(self) -> (f32, f32) {
        match self {
            ProjectileKind::SmallFireball | ProjectileKind::WitherSkull => (0.3125, 0.3125),
            ProjectileKind::Arrow => (0.5, 0.5),
            ProjectileKind::LargeFireball => (1.0, 1.0),
            _ => (0.25, 0.25),
        }
    }

    /// The gravity taken off the vertical motion each tick (the float constant as vanilla
    /// widens it).
    #[must_use]
    pub fn gravity(self) -> f64 {
        f64::from(match self {
            ProjectileKind::Snowball | ProjectileKind::Egg | ProjectileKind::EnderPearl => 0.03f32,
            ProjectileKind::ExperienceBottle => 0.07,
            ProjectileKind::SplashPotion => 0.05,
            ProjectileKind::Arrow => 0.05,
            _ => 0.0,
        })
    }
}

/// A projectile's state. Create it with [`Projectile::new`] from the spawn packet's position and
/// motion (or a launch, [`super::launch`]); tick it with [`tick_projectile`].
#[derive(Clone, Debug)]
pub struct Projectile {
    kind: ProjectileKind,
    b: Body,
    power: [f64; 3],
    dangerous: bool,
    in_ground: bool,
    life: i32,
    /// The arrow's stored block position, block id and metadata.
    stuck: [i32; 3],
    stuck_block: Option<(u8, u8)>,
    owner: Option<[f64; 3]>,
    owner_holds_rod: bool,
    /// A client bobber's interpolation (`field_4053` steps left, the target position, yaw and
    /// pitch) and the motion of the last velocity packet (`field_4059 – field_4061`).
    lerp: Option<Box<BobberLerp>>,
}

/// A 1.8 client bobber's interpolation toward the server's position.
#[derive(Clone, Debug, Default)]
struct BobberLerp {
    steps: i32,
    to: [f64; 5],
    packet_vel: [f64; 3],
}

/// `MathHelper.wrapDegrees(double)`.
fn wrap_degrees(mut d: f64) -> f64 {
    d %= 360.0;
    if d >= 180.0 {
        d -= 360.0;
    }
    if d < -180.0 {
        d += 360.0;
    }
    d
}

/// One tick's block hit (vanilla `MovingObjectPosition` of the projectile's ray).
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub struct ProjectileHit {
    /// The block.
    pub pos: [i32; 3],
    /// The face hit.
    pub face: Direction,
    /// The exact point.
    pub location: [f64; 3],
    /// Always `false`: a 1.8 hit has no "started inside" flag (kept for the shape the other
    /// version modules share).
    pub inside: bool,
}

/// The first block hit of [`run_projectile`] and the tick it happened (1 = the first tick run).
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub struct Impact {
    /// Tick number of the hit, counted from 1.
    pub tick: u32,
    /// The hit.
    pub hit: ProjectileHit,
}

impl Projectile {
    /// A projectile at `pos` moving by `vel` per tick, rotation 0, as freshly spawned (first
    /// update pending, not on the ground, entity random seed 0). A hurting projectile gets the
    /// acceleration a client gives it from its spawn motion (`vel` normalised, times 0.1).
    #[must_use]
    pub fn new(kind: ProjectileKind, pos: [f64; 3], vel: [f64; 3]) -> Projectile {
        let (w, h) = kind.dimensions();
        let mut b = Body::new(pos, vel, w, h);
        b.climbs = kind == ProjectileKind::FishingBobber;
        b.history = HistoryShapes::Constructor;
        let power = if kind.family() == Family::Hurting {
            let d = f64::from(sqrt_f64_as_f32(
                vel[0] * vel[0] + vel[1] * vel[1] + vel[2] * vel[2],
            ));
            if d == 0.0 {
                [0.0; 3]
            } else {
                [vel[0] / d * 0.1, vel[1] / d * 0.1, vel[2] / d * 0.1]
            }
        } else {
            [0.0; 3]
        };
        Projectile {
            kind,
            b,
            power,
            dangerous: false,
            in_ground: false,
            life: 0,
            stuck: [-1, -1, -1],
            stuck_block: None,
            owner: None,
            owner_holds_rod: true,
            lerp: None,
        }
    }

    /// The rotation (yaw, pitch in degrees).
    #[must_use]
    pub fn with_rotation(mut self, yaw: f32, pitch: f32) -> Projectile {
        self.b.yaw = yaw;
        self.b.pitch = pitch;
        self.b.yaw_o = yaw;
        self.b.pitch_o = pitch;
        self
    }

    /// A hurting projectile's acceleration (`accelerationX/Y/Z`).
    #[must_use]
    pub fn with_power(mut self, power: [f64; 3]) -> Projectile {
        self.power = power;
        self
    }

    /// A dangerous (blue) wither skull (inertia 0.73).
    #[must_use]
    pub fn with_dangerous(mut self, dangerous: bool) -> Projectile {
        self.dangerous = dangerous;
        self
    }

    /// Accepted for the shape the version modules share: 1.8 has no tipped arrows.
    #[must_use]
    pub fn with_tipped(self, _tipped: bool) -> Projectile {
        self
    }

    /// The seed of the entity's random (an arrow's sounds and fall, the bobber's swim sounds,
    /// the water splash).
    #[must_use]
    pub fn with_random_seed(mut self, seed: i64) -> Projectile {
        self.b.rng = LegacyRandom::new(seed);
        self
    }

    /// The on-ground flag.
    #[must_use]
    pub fn with_on_ground(mut self, on_ground: bool) -> Projectile {
        self.b.on_ground = on_ground;
        self
    }

    /// The fall distance.
    #[must_use]
    pub fn with_fall_distance(mut self, fall: f32) -> Projectile {
        self.b.fall = fall;
        self
    }

    /// Accepted for the shape the version modules share: 1.8 has no no-gravity flag.
    #[must_use]
    pub fn with_no_gravity(self, _no_gravity: bool) -> Projectile {
        self
    }

    /// A bobber's owner (its position and whether it holds a fishing rod); the server removes a
    /// bobber without one (a client ticks it on).
    #[must_use]
    pub fn with_owner(mut self, pos: Option<[f64; 3]>, holds_rod: bool) -> Projectile {
        self.owner = pos;
        self.owner_holds_rod = holds_rod;
        self
    }

    /// Moves the bobber's owner (call before each tick when the owner moves).
    pub fn set_owner_pos(&mut self, pos: Option<[f64; 3]>) {
        self.owner = pos;
    }

    /// Sets the position (`updatePosition`: the box is made there), keeping the rest of the
    /// state.
    pub fn set_pos(&mut self, pos: [f64; 3]) {
        self.b.set_position(pos);
    }

    /// Sets the motion, keeping the rest of the state.
    pub fn set_vel(&mut self, vel: [f64; 3]) {
        self.b.vel = vel;
    }

    /// Sets the rotation (`yaw`, `pitch`; the previous rotation is taken when the next tick
    /// starts).
    pub fn set_rotation(&mut self, yaw: f32, pitch: f32) {
        self.b.yaw = yaw;
        self.b.pitch = pitch;
    }

    /// Sets the on-ground flag.
    pub fn set_on_ground(&mut self, on_ground: bool) {
        self.b.on_ground = on_ground;
    }

    /// A position packet on a client (`updateTrackedPositionAndAngles`): thrown items and
    /// hurting projectiles move there (`updatePosition`), take the rotation (`% 360`) and are
    /// pushed up onto the highest block box their box (less 1/32 on each side) runs into; an
    /// arrow moves and turns without the push; a fishing bobber starts a 3-step interpolation
    /// toward it and takes the last velocity packet's motion again.
    pub fn set_tracked_position<W: BlockView<State = BlockState>>(
        &mut self,
        pos: [f64; 3],
        yaw: f32,
        pitch: f32,
        world: &W,
    ) {
        match self.kind.family() {
            Family::Bobber => {
                let l = self.lerp.get_or_insert_with(Box::default);
                l.steps = 3;
                l.to = [pos[0], pos[1], pos[2], f64::from(yaw), f64::from(pitch)];
                self.b.vel = l.packet_vel;
            }
            Family::Arrow => {
                self.b.set_position(pos);
                self.b.yaw = yaw % 360.0;
                self.b.pitch = pitch % 360.0;
            }
            Family::Thrown | Family::Hurting => {
                self.b.yaw = yaw % 360.0;
                self.b.pitch = pitch % 360.0;
                body::tracked_position(&mut self.b, world, pos);
            }
        }
    }

    /// A velocity packet on a client (`setVelocityClient`): the motion; a thrown item or an arrow
    /// whose previous rotation is still 0 / 0 (a fresh spawn) also turns to the motion's
    /// direction (an arrow also rebuilds its box and restarts its timer); a bobber keeps the
    /// motion for its next position packet.
    pub fn set_velocity_client(&mut self, vel: [f64; 3]) {
        let family = self.kind.family();
        let b = &mut self.b;
        b.vel = vel;
        match family {
            Family::Thrown | Family::Arrow if b.pitch_o == 0.0 && b.yaw_o == 0.0 => {
                let f = sqrt_f64_as_f32(vel[0] * vel[0] + vel[2] * vel[2]);
                b.yaw = degrees(atan2(vel[0], vel[2]));
                b.pitch = degrees(atan2(vel[1], f64::from(f)));
                b.yaw_o = b.yaw;
                b.pitch_o = b.pitch;
                if family == Family::Arrow {
                    // refreshPositionAndAngles
                    let p = b.pos;
                    b.set_position(p);
                    self.life = 0;
                }
            }
            Family::Bobber => {
                self.lerp.get_or_insert_with(Box::default).packet_vel = vel;
            }
            _ => {}
        }
    }

    /// The world's entity update without the entity's own tick: the previous position and
    /// rotation become the current ones.
    pub fn skip_tick(&mut self) {
        let b = &mut self.b;
        b.old = b.pos;
        b.tick_start = b.pos;
        b.yaw_o = b.yaw;
        b.pitch_o = b.pitch;
    }

    /// Sets whether a wither skull is dangerous (its entity data).
    pub fn set_dangerous(&mut self, dangerous: bool) {
        self.dangerous = dangerous;
    }

    /// The kind.
    #[must_use]
    pub fn kind(&self) -> ProjectileKind {
        self.kind
    }

    /// Position.
    #[must_use]
    pub fn pos(&self) -> [f64; 3] {
        self.b.pos
    }

    /// Motion per tick.
    #[must_use]
    pub fn vel(&self) -> [f64; 3] {
        self.b.vel
    }

    /// Yaw in degrees.
    #[must_use]
    pub fn yaw(&self) -> f32 {
        self.b.yaw
    }

    /// Pitch in degrees.
    #[must_use]
    pub fn pitch(&self) -> f32 {
        self.b.pitch
    }

    /// The bounding box.
    #[must_use]
    pub fn bounding_box(&self) -> Aabb {
        self.b.bb
    }

    /// The on-ground flag.
    #[must_use]
    pub fn on_ground(&self) -> bool {
        self.b.on_ground
    }

    /// `isTouchingWater()`.
    #[must_use]
    pub fn in_water(&self) -> bool {
        self.b.in_water
    }

    /// The last move collided horizontally (the bobber).
    #[must_use]
    pub fn horizontal_collision(&self) -> bool {
        self.b.hcol
    }

    /// The last move collided vertically (the bobber).
    #[must_use]
    pub fn vertical_collision(&self) -> bool {
        self.b.vcol
    }

    /// The fall distance.
    #[must_use]
    pub fn fall_distance(&self) -> f32 {
        self.b.fall
    }

    /// An arrow (or the bobber, for one tick) stuck in a block.
    #[must_use]
    pub fn in_ground(&self) -> bool {
        self.in_ground
    }

    /// An arrow's despawn timer in the ground / the bobber's removal timer.
    #[must_use]
    pub fn life(&self) -> i32 {
        self.life
    }

    /// A hurting projectile's acceleration.
    #[must_use]
    pub fn power(&self) -> [f64; 3] {
        self.power
    }

    /// The entity was removed (by the side that ticked it).
    #[must_use]
    pub fn removed(&self) -> bool {
        self.b.removed
    }

    /// The entity's tick counter (`ticksAlive`).
    #[must_use]
    pub fn age(&self) -> i32 {
        self.b.age
    }
}

/// The block at `pos` is water (still or flowing). The 1.8.9 bobber has no flying / bobbing
/// state (it measures the water in its box every tick); ghast's fishing state uses this.
#[must_use]
pub fn water_at<W: BlockView<State = BlockState>>(w: &W, pos: [f64; 3]) -> bool {
    is_water(state_at(
        w,
        crate::math::floor(pos[0]),
        crate::math::floor(pos[1]),
        crate::math::floor(pos[2]),
    ))
}

/// One tick of a projectile (the world's entity update, then the kind's `tick`). Returns this
/// tick's block hit, if any. A removed projectile does not tick.
pub fn tick_projectile<W: BlockView<State = BlockState>>(
    p: &mut Projectile,
    side: Side,
    world: &W,
) -> Option<ProjectileHit> {
    if p.b.removed {
        return None;
    }
    let hit = match p.kind.family() {
        Family::Thrown => thrown(p, side, world),
        Family::Hurting => hurting(p, side, world),
        Family::Arrow => arrow(p, side, world),
        Family::Bobber => bobber(p, side, world),
    };
    p.b.end_tick();
    hit
}

/// Ticks until the first block hit, the removal of the projectile, or `max_ticks` ticks; returns
/// the first hit and its tick.
pub fn run_projectile<W: BlockView<State = BlockState>>(
    p: &mut Projectile,
    side: Side,
    world: &W,
    max_ticks: u32,
) -> Option<Impact> {
    for t in 1..=max_ticks {
        if p.b.removed {
            return None;
        }
        if let Some(hit) = tick_projectile(p, side, world) {
            return Some(Impact { tick: t, hit });
        }
    }
    None
}

fn to_hit(h: BlockHit) -> ProjectileHit {
    ProjectileHit {
        pos: h.pos,
        face: h.face,
        location: h.location,
        inside: false,
    }
}

/// `new Vec3(..)`: `-0.0` becomes `0.0`.
#[inline]
fn v3(v: [f64; 3]) -> [f64; 3] {
    v.map(|c| if c == 0.0 { 0.0 } else { c })
}

/// `World.rayTrace(from, to, false, ignoreNoBox, false)`; `touched` is [`Body::touched`].
fn ray<W: BlockView<State = BlockState>>(
    w: &W,
    from: [f64; 3],
    to: [f64; 3],
    ignore_no_box: bool,
    touched: u8,
) -> Option<BlockHit> {
    crate::pick::legacy::trace(v3(from), v3(to), false, |p| {
        let s = state_at(w, p[0], p[1], p[2]);
        if ignore_no_box && !s.selection().has_collision_box {
            return crate::pick::legacy::Shape::Skip;
        }
        // Brewing stands and end portal frames ray-test their shared block bounds: the full cube
        // until a collision scan sets them to the item-render box.
        match s.block().id() {
            body::nid::BREWING_STAND if touched & 1 == 0 => {
                crate::pick::legacy::Shape::One(Aabb::FULL)
            }
            body::nid::BREWING_STAND => {
                crate::pick::legacy::Shape::One(Aabb::new(0.0, 0.0, 0.0, 1.0, 0.125, 1.0))
            }
            body::nid::END_PORTAL_FRAME if touched & 2 == 0 => {
                crate::pick::legacy::Shape::One(Aabb::FULL)
            }
            body::nid::END_PORTAL_FRAME => {
                crate::pick::legacy::Shape::One(Aabb::new(0.0, 0.0, 0.0, 1.0, 0.8125, 1.0))
            }
            _ => crate::pick::v1_8::shape(w, p, false),
        }
    })
}

fn add(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
    [a[0] + b[0], a[1] + b[1], a[2] + b[2]]
}

/// The rotation turned towards the motion (a fifth of the way from the old angles brought
/// within 180 of the new ones).
fn update_rotation(b: &mut Body) {
    let v = b.vel;
    let f = f64::from(sqrt_f64_as_f32(v[0] * v[0] + v[2] * v[2]));
    b.pitch = lerp_rotation(b.pitch_o, degrees(atan2(v[1], f)));
    b.yaw = lerp_rotation(b.yaw_o, degrees(atan2(v[0], v[2])));
}

/// `ThrowableEntity.tick`.
fn thrown<W: BlockView<State = BlockState>>(
    p: &mut Projectile,
    side: Side,
    w: &W,
) -> Option<ProjectileHit> {
    let gravity = p.kind.gravity();
    let b = &mut p.b;
    b.start_tick();
    body::base_tick(b, w, side);
    let hit = ray(w, b.pos, add(b.pos, b.vel), false, b.touched);
    if hit.is_some() && side == Side::Server {
        b.removed = true;
    }
    let next = add(b.pos, b.vel);
    update_rotation(b);
    let g: f32 = if b.in_water { 0.8 } else { 0.99 };
    for v in &mut b.vel {
        *v *= f64::from(g);
    }
    b.vel[1] -= gravity;
    b.set_position(next);
    hit.map(to_hit)
}

/// `ExplosiveProjectileEntity.tick`.
fn hurting<W: BlockView<State = BlockState>>(
    p: &mut Projectile,
    side: Side,
    w: &W,
) -> Option<ProjectileHit> {
    let drag: f32 = if p.kind == ProjectileKind::WitherSkull && p.dangerous {
        0.73
    } else {
        0.95
    };
    let power = p.power;
    let b = &mut p.b;
    b.start_tick();
    let bp = b.block_pos();
    if side == Side::Server
        && !(is_valid_pos(bp[0], bp[1], bp[2]) && w.is_chunk_loaded(bp[0] >> 4, bp[2] >> 4))
    {
        b.removed = true;
        return None;
    }
    body::base_tick(b, w, side);
    let hit = ray(w, b.pos, add(b.pos, b.vel), false, b.touched);
    if hit.is_some() && side == Side::Server {
        b.removed = true;
    }
    let next = add(b.pos, b.vel);
    let v = b.vel;
    let g = f64::from(sqrt_f64_as_f32(v[0] * v[0] + v[2] * v[2]));
    let yaw = degrees(atan2(v[2], v[0])) + 90.0;
    let pitch = degrees(atan2(g, v[1])) - 90.0;
    b.pitch = lerp_rotation(b.pitch_o, pitch);
    b.yaw = lerp_rotation(b.yaw_o, yaw);
    let f = if b.in_water { 0.8 } else { drag };
    for a in 0..3 {
        b.vel[a] = (b.vel[a] + power[a]) * f64::from(f);
    }
    b.set_position(next);
    hit.map(to_hit)
}

/// `AbstractArrowEntity.tick`.
fn arrow<W: BlockView<State = BlockState>>(
    p: &mut Projectile,
    side: Side,
    w: &W,
) -> Option<ProjectileHit> {
    let b = &mut p.b;
    b.start_tick();
    body::base_tick(b, w, side);
    if b.pitch_o == 0.0 && b.yaw_o == 0.0 {
        let v = b.vel;
        let f = f64::from(sqrt_f64_as_f32(v[0] * v[0] + v[2] * v[2]));
        b.yaw = degrees(atan2(v[0], v[2]));
        b.pitch = degrees(atan2(v[1], f));
        b.yaw_o = b.yaw;
        b.pitch_o = b.pitch;
    }
    let sp = p.stuck;
    let here = state_at(w, sp[0], sp[1], sp[2]);
    if !is_air(here)
        && let Some(bx) = body::collision_bounds(w, b.history, sp[0], sp[1], sp[2])
    {
        let q = b.pos;
        if q[0] > bx.min_x
            && q[0] < bx.max_x
            && q[1] > bx.min_y
            && q[1] < bx.max_y
            && q[2] > bx.min_z
            && q[2] < bx.max_z
        {
            p.in_ground = true;
        }
    }
    let mut result = None;
    if p.in_ground {
        if p.stuck_block == Some((here.block().id(), here.meta())) {
            p.life += 1;
            if p.life >= 1200 {
                b.removed = true;
            }
        } else {
            p.in_ground = false;
            for a in 0..3 {
                b.vel[a] *= f64::from(b.rng.next_float() * 0.2);
            }
            p.life = 0;
        }
    } else {
        let hit = ray(w, b.pos, add(b.pos, b.vel), true, b.touched);
        if let Some(h) = hit {
            // onHit (a block)
            p.stuck = h.pos;
            let s = state_at(w, h.pos[0], h.pos[1], h.pos[2]);
            p.stuck_block = Some((s.block().id(), s.meta()));
            for a in 0..3 {
                b.vel[a] = f64::from((h.location[a] - b.pos[a]) as f32);
            }
            let v = b.vel;
            let len = f64::from(sqrt_f64_as_f32(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]));
            for a in 0..3 {
                b.pos[a] -= v[a] / len * f64::from(0.05f32);
            }
            b.rng.next_float();
            p.in_ground = true;
            if !is_air(s) {
                body::block_touch(b, s);
            }
            result = Some(to_hit(h));
        }
        b.pos = add(b.pos, b.vel);
        update_rotation(b);
        let h: f32 = if b.in_water { 0.6 } else { 0.99 };
        for v in &mut b.vel {
            *v *= f64::from(h);
        }
        b.vel[1] -= f64::from(0.05f32);
        let pos = b.pos;
        b.set_position(pos);
        body::check_block_collision(b, w);
    }
    result
}

/// `FishingBobberEntity.tick` (no hooked entity, no bite).
fn bobber<W: BlockView<State = BlockState>>(
    p: &mut Projectile,
    side: Side,
    w: &W,
) -> Option<ProjectileHit> {
    let b = &mut p.b;
    b.start_tick();
    body::base_tick(b, w, side);
    // A client copy interpolating toward a position packet does only that.
    if let Some(l) = p.lerp.as_deref_mut()
        && l.steps > 0
    {
        let n = f64::from(l.steps);
        let d = [
            b.pos[0] + (l.to[0] - b.pos[0]) / n,
            b.pos[1] + (l.to[1] - b.pos[1]) / n,
            b.pos[2] + (l.to[2] - b.pos[2]) / n,
        ];
        let g = wrap_degrees(l.to[3] - f64::from(b.yaw));
        let yaw = (f64::from(b.yaw) + g / n) as f32;
        let pitch = (f64::from(b.pitch) + (l.to[4] - f64::from(b.pitch)) / n) as f32;
        l.steps -= 1;
        b.set_position(d);
        b.yaw = yaw % 360.0;
        b.pitch = pitch % 360.0;
        return None;
    }
    if side == Side::Server {
        let gone = match p.owner {
            None => true,
            Some(o) => {
                let (dx, dy, dz) = (b.pos[0] - o[0], b.pos[1] - o[1], b.pos[2] - o[2]);
                !p.owner_holds_rod || dx * dx + dy * dy + dz * dz > 1024.0
            }
        };
        if gone {
            b.removed = true;
            return None;
        }
    }
    if p.in_ground {
        // The block it stuck in is never stored: the next tick lets it go.
        p.in_ground = false;
        for a in 0..3 {
            b.vel[a] *= f64::from(b.rng.next_float() * 0.2);
        }
        p.life = 0;
    }
    let hit = ray(w, b.pos, add(b.pos, b.vel), false, b.touched);
    if hit.is_some() {
        p.in_ground = true;
    }
    if !p.in_ground {
        let v = b.vel;
        body::entity_move(b, w, v);
        update_rotation(b);
        let mut m: f32 = if b.on_ground || b.hcol { 0.5 } else { 0.92 };
        let mut o = 0.0;
        let bb = b.bb;
        for i in 0..5 {
            let q = bb.max_y - bb.min_y;
            let r = bb.min_y + q * f64::from(i) / 5.0;
            let s = bb.min_y + q * f64::from(i + 1) / 5.0;
            if contains_water(w, &Aabb::new(bb.min_x, r, bb.min_z, bb.max_x, s, bb.max_z)) {
                o += 1.0 / 5.0;
            }
        }
        let aj = o * 2.0 - 1.0;
        b.vel[1] += f64::from(0.04f32) * aj;
        if o > 0.0 {
            m = (f64::from(m) * 0.9) as f32;
            b.vel[1] *= 0.8;
        }
        for v in &mut b.vel {
            *v *= f64::from(m);
        }
        let pos = b.pos;
        b.set_position(pos);
    }
    hit.map(to_hit)
}

/// Water whose surface reaches the box's bottom in the box's block range
/// (`World.containsBlockWithMaterial`, 1.8's `floor(max + 1)` end).
fn contains_water<W: BlockView<State = BlockState>>(w: &W, bb: &Aabb) -> bool {
    use crate::math::floor;
    let end = |v: f64| floor(v + 1.0);
    for x in floor(bb.min_x)..end(bb.max_x) {
        for y in floor(bb.min_y)..end(bb.max_y) {
            for z in floor(bb.min_z)..end(bb.max_z) {
                let s = state_at(w, x, y, z);
                if is_water(s) {
                    // The surface: a level below 8 lowers it by an eighth per level.
                    let level = i32::from(s.meta());
                    let top = if level < 8 {
                        f64::from(y + 1) - f64::from(level) / 8.0
                    } else {
                        f64::from(y + 1)
                    };
                    if top >= bb.min_y {
                        return true;
                    }
                }
            }
        }
    }
    false
}