ghast-physics 0.5.3

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
//! Item entities, experience orbs, primed TNT and falling blocks of the modern versions (26.1,
//! 26.2, 26.3): `Entity.move` with full block collision, ground friction (slippery blocks),
//! water and lava buoyancy, flowing water, the inside-block effects — each ticked as the server
//! and as a client tick it, checked bit for bit against the vanilla oracle
//! (`tests/golden/<v>/projectiles.jsonl.gz`).
//!
//! Not modelled: merging, pickup, an orb following a player, a TNT explosion (the entity is
//! removed when the fuse runs out), a falling block's landing (the server places the block; only
//! the client's tick is modelled for falling blocks), burning in lava (a server destroys an item
//! that is not fire resistant and an orb within a few ticks; the tick here keeps them).
//!
//! What the sides do differently (all from the vanilla tick):
//!
//! * only the server pushes an item or an orb out of a block it is stuck in
//!   (`moveTowardsClosestSpace`, one random draw) and counts the fall distance (which decides
//!   whether powder snow carries a falling item);
//! * a client updates the ground and vertical-collision flags only when the entity moved
//!   vertically, and does not run the collision response (26.1: the bounce on slime and beds;
//!   26.2: the whole restitution, so a client's item keeps its speed into a wall) — except in
//!   26.3, where these entities are simulated on both sides ([`Rules::SIMULATED_ON_CLIENT`]);
//! * a client skips an orb's first tick.

pub use super::body::Side;
use super::body::{self, Body, InsideRules, LegacyRandom, MoveRules, with_env};
use super::fluid::kind;
use super::math::{V3, deflate, java_min, mv};
use super::rules::Rules;
use crate::math::Aabb;
use crate::world::BlockView;

/// The kinds.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum DropKind {
    /// `item` (an item entity; gravity 0.04).
    Item,
    /// `experience_orb` (gravity 0.03).
    ExperienceOrb,
    /// `tnt` (primed TNT; gravity 0.04).
    PrimedTnt,
    /// `falling_block` (gravity 0.04; client tick only).
    FallingBlock,
}

impl DropKind {
    /// The entity type id without namespace.
    #[must_use]
    pub const fn entity_name(self) -> &'static str {
        match self {
            DropKind::Item => "item",
            DropKind::ExperienceOrb => "experience_orb",
            DropKind::PrimedTnt => "tnt",
            DropKind::FallingBlock => "falling_block",
        }
    }

    /// The kind of an entity type id (with or without the `minecraft:` namespace).
    #[must_use]
    pub fn from_entity_name(name: &str) -> Option<DropKind> {
        let name = name.strip_prefix("minecraft:").unwrap_or(name);
        [
            DropKind::Item,
            DropKind::ExperienceOrb,
            DropKind::PrimedTnt,
            DropKind::FallingBlock,
        ]
        .into_iter()
        .find(|k| k.entity_name() == name)
    }

    /// Box width and height.
    #[must_use]
    pub const fn dimensions(self) -> (f32, f32) {
        match self {
            DropKind::Item => (0.25, 0.25),
            DropKind::ExperienceOrb => (0.5, 0.5),
            DropKind::PrimedTnt | DropKind::FallingBlock => (0.98, 0.98),
        }
    }

    fn eye_height(self) -> f32 {
        match self {
            DropKind::Item => 0.2125,
            DropKind::PrimedTnt => 0.15,
            _ => self.dimensions().1 * 0.85,
        }
    }

    /// The gravity added each tick.
    #[must_use]
    pub const fn gravity(self) -> f64 {
        match self {
            DropKind::ExperienceOrb => 0.03,
            _ => 0.04,
        }
    }
}

/// The state of an item entity, orb, primed TNT or falling block.
#[derive(Clone, Debug)]
pub struct Drop {
    kind: DropKind,
    b: Body,
    id: i32,
    age: i32,
    fuse: i32,
    time: i32,
}

impl Drop {
    /// An entity at `pos` moving by `vel` per tick, as freshly spawned (first tick pending, not on
    /// the ground, entity id 0, random seed 0, a TNT fuse of 80).
    #[must_use]
    pub fn new(kind: DropKind, pos: [f64; 3], vel: [f64; 3]) -> Drop {
        let (w, h) = kind.dimensions();
        let mut b = Body::new(V3::of(pos), V3::of(vel), w, h, kind.eye_height());
        if matches!(kind, DropKind::Item | DropKind::ExperienceOrb) {
            b.below_offset = 0.999_999;
        }
        Drop {
            kind,
            b,
            id: 0,
            age: 0,
            fuse: 80,
            time: 0,
        }
    }

    /// The entity id (an item resting on the ground moves every fourth tick, counted with it).
    #[must_use]
    pub fn with_id(mut self, id: i32) -> Drop {
        self.id = id;
        self
    }

    /// The seed of the entity's random (`RandomSource.create(seed)`; the server's push out of
    /// blocks, an orb's jumps in lava and the water splash draw from it).
    #[must_use]
    pub fn with_random_seed(mut self, seed: i64) -> Drop {
        self.b.rng = LegacyRandom::new(seed);
        self
    }

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

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

    /// A primed TNT's fuse in ticks.
    #[must_use]
    pub fn with_fuse(mut self, fuse: i32) -> Drop {
        self.fuse = fuse;
        self
    }

    /// Sets the position (the box follows), keeping the rest of the state: what a client copy
    /// does when a server packet moves the entity between its ticks.
    pub fn set_pos(&mut self, pos: [f64; 3]) {
        self.b.set_pos(V3::of(pos));
    }

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

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

    /// The position and rotation before this tick's interpolation step (an experience orb: see
    /// [`super::projectile::Projectile::set_interpolation_start`]); the next tick starts from
    /// them (once).
    pub fn set_interpolation_start(&mut self, pos: [f64; 3], yaw: f32, pitch: f32) {
        self.b.pending_old = Some((V3::of(pos), yaw, pitch));
    }

    /// The movements `Entity.move` made in the last tick, in order (see
    /// [`super::projectile::Projectile::moved_last_tick`]).
    #[must_use]
    pub fn moved_last_tick(&self) -> &[[f64; 3]] {
        &self.b.moved[..usize::from(self.b.moved_n)]
    }

    /// Sets a primed TNT's fuse (its entity data).
    pub fn set_fuse(&mut self, fuse: i32) {
        self.fuse = fuse;
    }

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

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

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

    /// 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
    }

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

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

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

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

    /// An item's or orb's age in ticks.
    #[must_use]
    pub fn age(&self) -> i32 {
        self.age
    }

    /// A primed TNT's remaining fuse.
    #[must_use]
    pub fn fuse(&self) -> i32 {
        self.fuse
    }

    /// A falling block's ticks.
    #[must_use]
    pub fn time(&self) -> i32 {
        self.time
    }

    /// The server found an item inside a block this tick (`noPhysics`: it moves without collision
    /// while it is pushed out).
    #[must_use]
    pub fn no_physics(&self) -> bool {
        self.b.no_physics
    }

    /// The entity was removed (a fuse ran out, an age limit).
    #[must_use]
    pub fn removed(&self) -> bool {
        self.b.removed
    }

    /// At rest: on the ground and not moving (an item or orb that stays put until something
    /// changes around it).
    #[must_use]
    pub fn at_rest(&self) -> bool {
        self.b.on_ground && self.b.vel.horizontal_sqr() < 1.0e-12 && self.b.vel.y.abs() < 1.0e-12
    }
}

const ENTITY_INSIDE: InsideRules = InsideRules {
    projectile_bubbles: false,
    no_bubbles: false,
};

/// One tick (`tickNonPassenger` then the kind's `tick`). A removed entity does not tick.
pub fn tick_drop<R: Rules, W: BlockView<State = R::State>>(d: &mut Drop, side: Side, world: &W) {
    if d.b.removed {
        return;
    }
    let server = side == Side::Server;
    let mr = MoveRules {
        authoritative: server,
        simulate: server || R::SIMULATED_ON_CLIENT,
        gravity: d.kind.gravity(),
        air_drag: 0.98,
    };
    with_env::<R, W, _>(world, |w| match d.kind {
        DropKind::Item => item::<R, W>(d, server, mr, w),
        DropKind::ExperienceOrb => orb::<R, W>(d, server, mr, w),
        DropKind::PrimedTnt => tnt::<R, W>(d, mr, w),
        DropKind::FallingBlock => falling::<R, W>(d, mr, w),
    });
}

/// Ticks until the entity rests on the ground with no motion ([`Drop::at_rest`]), is removed, or
/// `max_ticks` ticks ran; returns the ticks run.
pub fn run_drop<R: Rules, W: BlockView<State = R::State>>(
    d: &mut Drop,
    side: Side,
    world: &W,
    max_ticks: u32,
) -> u32 {
    for t in 1..=max_ticks {
        tick_drop::<R, W>(d, side, world);
        if d.b.removed || d.at_rest() {
            return t;
        }
    }
    max_ticks
}

/// The drag of items, TNT and falling blocks: the double 0.98, from 26.2 the float `getAirDrag()`.
fn air_drag<R: Rules>() -> f64 {
    if R::FLOAT_AIR_DRAG {
        f64::from(0.98f32)
    } else {
        0.98
    }
}

/// `ItemEntity.tick`.
fn item<R: Rules, W: BlockView<State = R::State>>(
    d: &mut Drop,
    server: bool,
    mr: MoveRules,
    w: &body::Env<'_, R, W>,
) {
    let b = &mut d.b;
    b.start_tick();
    body::base_tick::<R, W>(b, w, true, true);
    b.old = b.pos;
    if b.in_water && b.water_height > f64::from(0.1f32) {
        fluid_movement(b, 0.99);
    } else if b.in_lava() && b.lava_height > f64::from(0.1f32) {
        fluid_movement(b, 0.95);
    } else {
        b.apply_gravity(0.04);
    }
    if server {
        let probe = deflate(&b.bb, 1.0e-7);
        let ctx = b.ctx();
        b.no_physics = !w.no_collision(b.pos.arr(), &probe, &ctx);
        if b.no_physics {
            let y = (b.bb.min_y + b.bb.max_y) / 2.0;
            let (x, z) = (b.pos.x, b.pos.z);
            body::move_towards_closest_space::<R, W>(b, w, x, y, z);
        }
    } else {
        b.no_physics = false;
    }
    let resting = b.on_ground
        // `!(h > 1e-5F)`: a NaN speed counts as resting, as in vanilla.
        && (b.vel.horizontal_sqr() <= f64::from(1.0e-5f32) || b.vel.horizontal_sqr().is_nan())
        && (b.tick_count.wrapping_add(d.id)) % 4 != 0;
    if resting {
        body::apply_effects_last::<R, W>(b, w, ENTITY_INSIDE);
    } else {
        let v = b.vel;
        body::entity_move::<R, W>(b, w, v, mr);
        body::apply_effects_from_blocks::<R, W>(b, w, ENTITY_INSIDE);
        let drag = 0.98f32;
        let ground = if b.on_ground {
            let p = body::on_pos::<R, W>(b, w, b.below_offset);
            drag * R::friction(w.state(p[0], p[1], p[2]))
        } else {
            drag
        };
        b.vel = b
            .vel
            .mul(f64::from(ground), air_drag::<R>(), f64::from(ground));
        if b.on_ground && b.vel.y < 0.0 {
            b.vel = b.vel.mul(1.0, -0.5, 1.0);
        }
    }
    if d.age != -32768 {
        d.age += 1;
    }
    body::update_fluids::<R, W>(b, w, true, true);
    if server && d.age >= 6000 {
        b.removed = true;
    }
}

/// `ItemEntity.setFluidMovement(multiplier)`.
fn fluid_movement(b: &mut Body, k: f32) {
    let v = b.vel;
    let k = f64::from(k);
    let up = if v.y < f64::from(0.06f32) {
        f64::from(5.0e-4f32)
    } else {
        0.0
    };
    b.vel = V3::new(v.x * k, v.y + up, v.z * k);
}

/// `ExperienceOrb.tick`.
fn orb<R: Rules, W: BlockView<State = R::State>>(
    d: &mut Drop,
    server: bool,
    mr: MoveRules,
    w: &body::Env<'_, R, W>,
) {
    let b = &mut d.b;
    b.start_tick();
    if b.first_tick && !server {
        b.first_tick = false;
        return;
    }
    body::base_tick::<R, W>(b, w, true, false);
    let colliding = !body::no_collision_empty::<R, W>(w, &b.bb);
    if b.eye_in_water {
        let v = b.vel;
        b.vel = V3::new(
            v.x * f64::from(0.99f32),
            java_min(v.y + f64::from(5.0e-4f32), f64::from(0.06f32)),
            v.z * f64::from(0.99f32),
        );
    } else if !colliding {
        b.apply_gravity(0.03);
    }
    let bp = b.block_pos();
    if kind(w.fluid(bp[0], bp[1], bp[2])) == 2 {
        let x = (b.rng.next_float() - b.rng.next_float()) * 0.2;
        let z = (b.rng.next_float() - b.rng.next_float()) * 0.2;
        b.vel = V3::new(f64::from(x), f64::from(0.2f32), f64::from(z));
    }
    if server && colliding {
        let next = mv(&b.bb, b.vel.x, b.vel.y, b.vel.z);
        if !body::no_collision_empty::<R, W>(w, &next) {
            let y = (b.bb.min_y + b.bb.max_y) / 2.0;
            let (x, z) = (b.pos.x, b.pos.z);
            body::move_towards_closest_space::<R, W>(b, w, x, y, z);
        }
    }
    let fall_speed = b.vel.y;
    let v = b.vel;
    body::entity_move::<R, W>(b, w, v, mr);
    body::apply_effects_from_blocks::<R, W>(b, w, ENTITY_INSIDE);
    let friction = if b.on_ground {
        let p = body::on_pos::<R, W>(b, w, b.below_offset);
        R::friction(w.state(p[0], p[1], p[2])) * 0.98f32
    } else {
        0.98f32
    };
    b.vel = b.vel.scale(f64::from(friction));
    if b.vcol_below && fall_speed < -0.03 {
        b.vel = V3::new(b.vel.x, -fall_speed * 0.4, b.vel.z);
    }
    d.age += 1;
    if d.age >= 6000 {
        b.removed = true;
    }
}

/// `PrimedTnt.tick` (no base tick: only the fluid update after the fuse).
fn tnt<R: Rules, W: BlockView<State = R::State>>(
    d: &mut Drop,
    mr: MoveRules,
    w: &body::Env<'_, R, W>,
) {
    let b = &mut d.b;
    b.start_tick();
    b.apply_gravity(0.04);
    let v = b.vel;
    body::entity_move::<R, W>(b, w, v, mr);
    body::apply_effects_from_blocks::<R, W>(b, w, ENTITY_INSIDE);
    b.vel = b.vel.scale(air_drag::<R>());
    if b.on_ground {
        b.vel = b.vel.mul(0.7, -0.5, 0.7);
    }
    d.fuse -= 1;
    if d.fuse <= 0 {
        b.removed = true;
    } else {
        body::update_fluids::<R, W>(b, w, true, true);
    }
}

/// `FallingBlockEntity.tick` as a client runs it (no base tick, no fluids; the landing is the
/// server's).
fn falling<R: Rules, W: BlockView<State = R::State>>(
    d: &mut Drop,
    mr: MoveRules,
    w: &body::Env<'_, R, W>,
) {
    let b = &mut d.b;
    b.start_tick();
    d.time += 1;
    b.apply_gravity(0.04);
    let v = b.vel;
    body::entity_move::<R, W>(b, w, v, mr);
    body::apply_effects_from_blocks::<R, W>(b, w, ENTITY_INSIDE);
    b.vel = b.vel.scale(air_drag::<R>());
}