ghast-client 0.4.10

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 and 26.2)
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
//! The client's own records of the blocks it changed ahead of the server, and how the server's
//! answers settle them.
//!
//! - 1.19+ (26.x), `BlockStatePredictionHandler`: every block the client changes while it predicts
//!   (`startPredicting`, one sequence number per predicting packet) remembers the server's state
//!   from before. Block updates for such a position only replace the remembered state; the
//!   server's `block_changed_ack(sequence)` ends every prediction up to that number and puts the
//!   remembered state back into the world (a refused break is restored even when the server sends
//!   no block update, which it often does not).
//! - 1.16.5, `ClientPlayerInteractionManager.unacknowledgedPlayerActions`: every dig action
//!   packet remembers the player's position; the server's `acknowledge_player_digging` answers
//!   each one with the block's state and whether it was approved.
//!
//! Both are empty almost always (the server answers within a round trip): the callers test
//! [`Sequenced::is_empty`] / nothing at all on the hot path.

use ghast_protocol::BlockPos;

/// A `block_place` (use item on block) of this tick that used the held block item (the clicked
/// block was not activated), in packet order: the input of the versions' placed-block
/// prediction ([`super::Sim::place_sent`]).
///
/// Predicted (exactly, on every version): a block whose placement is its only state with a full
/// collision cube (stone, planks, ores, wool on 1.13+, …: the per-version `plain` rules)
/// placed from a stack without block state data, on the face of a block with a full collision
/// cube that the click does not activate, into air or a fluid, inside the build height and the
/// world border, not into the player's own box, in survival or creative. Everything else is
/// left to the server's block updates (vanilla runs the item's own placement logic there:
/// facing, waterlogging, half / axis / shape properties, replaceable clicked blocks, multi-block
/// items, neighbour shape updates).
#[derive(Clone, Copy, Debug)]
pub(crate) struct PlaceSent<'a> {
    /// The clicked block.
    pub pos: BlockPos,
    /// The clicked face.
    pub face: crate::common::Face,
    /// The stack in the hand that placed.
    pub held: Option<&'a ghast_inventory::Stack>,
    /// Sneaking (`isSecondaryUseActive`): the clicked block is not activated when a hand holds
    /// something.
    pub sneaking: bool,
    /// Either hand holds something.
    #[cfg_attr(
        not(any(feature = "v1_12_2", feature = "v1_16_5", ghast_modern)),
        allow(dead_code)
    )]
    pub any_item: bool,
    /// The local game mode.
    pub game_mode: crate::common::GameMode,
    /// The packet's 1.19+ prediction sequence.
    #[cfg_attr(not(ghast_modern), allow(dead_code))]
    pub sequence: i32,
    /// The player's position when the packet was sent (26.x: where an ack may move it back).
    #[cfg_attr(not(ghast_modern), allow(dead_code))]
    pub player: crate::common::Vec3,
    /// The hit point relative to `pos` as the packet carries it (`(float) (hit - pos)`).
    #[allow(dead_code)]
    pub cursor: [f32; 3],
    /// The player's yaw (the facing of placed stairs, furnaces, doors, ...).
    #[allow(dead_code)]
    pub yaw: f32,
}

/// A right click on a block before it is sent ([`super::Sim::place_rules`]).
#[derive(Clone, Copy, Debug)]
// read by the versions with right-click rules (1.8.9, 1.12.2, 1.16.5)
#[cfg_attr(
    not(any(feature = "v1_8", feature = "v1_12_2", feature = "v1_16_5")),
    allow(dead_code)
)]
pub(crate) struct PlaceQuery<'a> {
    /// The clicked block.
    pub pos: BlockPos,
    /// The clicked face.
    pub face: crate::common::Face,
    /// The hit point relative to `pos` (`(float) (hit - pos)`).
    pub cursor: [f32; 3],
    /// The clicking hand's stack (1.8: the main hand).
    pub held: Option<&'a ghast_inventory::Stack>,
    /// Sneaking.
    pub sneaking: bool,
    /// Either hand holds something (1.12: sneaking skips the block's activation then).
    #[cfg_attr(not(feature = "v1_12_2"), allow(dead_code))]
    pub any_item: bool,
    /// The local game mode.
    pub game_mode: crate::common::GameMode,
    /// The player's yaw (1.8.9, 1.12.2: the facing of placed blocks).
    #[cfg_attr(not(any(feature = "v1_8", feature = "v1_12_2")), allow(dead_code))]
    pub yaw: f32,
    /// The food level as the hands read it (-1: nothing can be eaten; 0 while invulnerable on
    /// 1.9+): 1.16.5 food block items eat when their placement fails.
    #[cfg_attr(not(feature = "v1_16_5"), allow(dead_code))]
    pub food: i32,
}

/// What the version's rules say about a right click on a block before it is sent
/// ([`super::Sim::place_rules`]): `None` where they do not decide it (the caller keeps its own
/// behaviour).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct PlaceRules {
    /// The hand's use in the air after a click that did not succeed is not modelled (1.12+:
    /// nothing after it, the off hand's turn, is predicted).
    pub air_use_unknown: bool,
    /// The `block_place` packet for the block is written.
    pub block_packet: Option<bool>,
    /// The click is taken (the client swings; otherwise the held item is used in the air).
    pub used: Option<bool>,
    /// A taken click without the swing (1.16+ `CONSUME`).
    pub no_swing: bool,
    /// A click not taken that still ends the use key (1.16+ `FAIL`: no item use, no off hand).
    pub ends: bool,
    /// The taken click starts the hand's item use (1.16.5: a food block item that could not be
    /// placed is eaten, `BlockItem.useOnBlock`).
    pub starts_use: bool,
}

/// A hand's item use in the air ([`super::Sim::air_use`]): `interactItem` after its packet, the
/// stack's `use` on the client.
#[derive(Clone, Copy, Debug)]
#[cfg_attr(not(any(feature = "v1_12_2", feature = "v1_16_5")), allow(dead_code))]
pub(crate) struct AirQuery<'a> {
    /// The off hand's turn.
    #[allow(dead_code)]
    pub off_hand: bool,
    /// The hand's stack.
    pub stack: &'a ghast_inventory::Stack,
    /// The inventory (ammunition; where a filled bucket goes).
    pub inv: &'a ghast_inventory::Inventory,
    /// The eyes.
    pub eyes: crate::common::Vec3,
    /// The look (the player's yaw / pitch at the key handling).
    pub yaw: f32,
    /// The look's pitch.
    pub pitch: f32,
    /// The local game mode.
    pub game_mode: crate::common::GameMode,
    /// The abilities' creative mode (`abilities.creativeMode`).
    pub creative: bool,
}

/// What a version knows of a hand's item use in the air.
#[derive(Clone, Debug, Default)]
pub(crate) enum AirAnswer {
    /// The held-item flags decide it (proven per class elsewhere).
    #[default]
    Flags,
    /// Not modelled: the flags guess; nothing after it (the off hand's turn) is predicted.
    #[cfg_attr(not(any(feature = "v1_12_2", feature = "v1_16_5")), allow(dead_code))]
    Unknown,
    /// The version's rules decide it.
    #[cfg_attr(not(any(feature = "v1_12_2", feature = "v1_16_5")), allow(dead_code))]
    Known(AirUse),
}

/// The result of an item use in the air (`TypedActionResult` of `Item.use` on the client).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(not(any(feature = "v1_12_2", feature = "v1_16_5")), allow(dead_code))]
pub(crate) enum AirResult {
    /// Accepted with the arm swing: the click ends.
    Success,
    /// Accepted without a swing: the click ends.
    Consume,
    /// Not accepted: the off hand's turn follows.
    Pass,
}

/// An item use in the air the version's rules decide.
#[derive(Clone, Debug)]
#[cfg_attr(not(any(feature = "v1_12_2", feature = "v1_16_5")), allow(dead_code))]
pub(crate) struct AirUse {
    /// The result.
    pub result: AirResult,
    /// The hand starts using the item (`setCurrentHand`).
    pub starts: bool,
    /// The blocks the client sets (the version's state ids); `None`: left to the server.
    pub blocks: Option<Vec<(BlockPos, u32)>>,
    /// What happens to the hand's stack on the client.
    pub hand: HandChange,
}

/// The client's change of the used hand's stack (no packet; the server's slot updates follow).
#[derive(Clone, Debug, Default)]
#[cfg_attr(not(any(feature = "v1_12_2", feature = "v1_16_5")), allow(dead_code))]
pub(crate) enum HandChange {
    /// Unchanged.
    #[default]
    Keep,
    /// One item used up.
    UseOne,
    /// The hand empties.
    Empty,
    /// The stack becomes this one.
    Replace(ghast_inventory::Stack),
    /// `ItemUsage.exchangeStack` (Yarn `method_30270`): one item becomes `output`, which goes
    /// into the inventory (dropped when it does not fit) unless it was the last; in creative
    /// with `creative_keeps` the hand keeps its stack and `output` goes in only when the
    /// inventory holds none of its item.
    #[cfg_attr(not(feature = "v1_16_5"), allow(dead_code))]
    Exchange {
        /// The new stack.
        output: ghast_inventory::Stack,
        /// Creative keeps the hand's stack.
        creative_keeps: bool,
    },
    /// 1.8 – 1.12 (`BucketItem.fill`, `GlassBottleItem`, `EmptyMapItem`): one item used up
    /// (creative too), the last one becomes `output`, else `output` goes into the inventory
    /// (`insertStack`; what does not fit is dropped or, in creative, gone: no packet, no swing).
    #[cfg_attr(not(any(feature = "v1_8", feature = "v1_12_2")), allow(dead_code))]
    ExchangeLegacy {
        /// The new stack.
        output: ghast_inventory::Stack,
    },
}

/// Whether a block placed on the client uses up one item of the stack there too
/// (`BlockItem.place`, 1.8 `ItemBlock.onItemUse`): not in creative (`hasInfiniteMaterials`;
/// 1.8 – 1.16.5 restore the count after the use).
pub(crate) fn placing_uses_item(mode: crate::common::GameMode) -> bool {
    mode != crate::common::GameMode::Creative
}

/// `WorldBorder.isWithinBounds(BlockPos)` (1.16.5 `contains`) of a static border.
pub(crate) fn border_contains(b: &ghast_physics::WorldBorder, pos: BlockPos) -> bool {
    let h = b.size / 2.0;
    let (x, z) = (f64::from(pos.x), f64::from(pos.z));
    x + 1.0 > b.center_x - h && x < b.center_x + h && z + 1.0 > b.center_z - h && z < b.center_z + h
}

/// 1.8.9 / 1.12.2 `BlockItem.canPlaceItemBlock`, which the client's right click checks before it
/// writes the `block_place` packet (`onRightClick` / `interactBlock`: no packet when it fails),
/// decided where the data decides it exactly: `true` = vanilla sends no block packet for this
/// click. `false` also for every case this cannot decide (the packet is sent as before).
///
/// Decided: the block next to the clicked face (or the clicked block itself when it is
/// replaceable: air, tall grass, dead bush, vines, any snow layer) is not of a replaceable
/// material (`World.canBlockBePlaced` needs one, whatever the block's own rules add), and the
/// held block's collision box, a full cube on every data value, would overlap the player's own
/// box or a box `entity_in` knows (`World.hasEntityIn`; 1.12.2 with entity tracking: the
/// entities whose client position the sim keeps). Not decided: anvils (they go on decorations) and slab items (their
/// own check), double plants as the clicked block, the block's own placement rules
/// (`canBePlacedAdjacent`: torches, flowers, ...), partial collision boxes, the other entities.
#[cfg(any(feature = "v1_8", feature = "v1_12_2"))]
#[allow(clippy::too_many_arguments)]
pub(crate) fn legacy_place_suppressed(
    pos: BlockPos,
    face: crate::common::Face,
    held: u16,
    undecided_items: &[u16],
    raw_at: impl Fn(BlockPos) -> Option<u16>,
    replaceable: impl Fn(u16) -> bool,
    full_cube_block: impl Fn(u16) -> bool,
    player: &ghast_physics::math::Aabb,
    entity_in: impl Fn(&ghast_physics::math::Aabb) -> bool,
) -> bool {
    // Block items: ids below 256, and the banner (its item is a block item too).
    if !(held < 256 || held == 425) || undecided_items.contains(&held) {
        return false;
    }
    let Some(clicked) = raw_at(pos) else {
        return false;
    };
    let target = match clicked >> 4 {
        // Snow layers: the face is taken as up, the layer itself is the spot.
        0 | 31 | 32 | 78 | 106 => pos,
        // DoublePlantBlock.isReplaceable reads the plant's kind from the other half.
        175 => return false,
        _ => face.offset(pos),
    };
    // getBlockState of an unloaded or out-of-height position is air (replaceable).
    let Some(there) = raw_at(target) else {
        return false;
    };
    if !replaceable(there >> 4) {
        return true;
    }
    if held < 256 && full_cube_block(held) {
        let (x, y, z) = (
            f64::from(target.x),
            f64::from(target.y),
            f64::from(target.z),
        );
        let cube = ghast_physics::math::Aabb::new(x, y, z, x + 1.0, y + 1.0, z + 1.0);
        return boxes_intersect(player, &cube) || entity_in(&cube);
    }
    false
}

/// `Box.intersects` (open intervals).
#[cfg(any(feature = "v1_8", feature = "v1_12_2"))]
#[inline]
pub(crate) fn boxes_intersect(
    a: &ghast_physics::math::Aabb,
    b: &ghast_physics::math::Aabb,
) -> bool {
    a.max_x > b.min_x
        && a.min_x < b.max_x
        && a.max_y > b.min_y
        && a.min_y < b.max_y
        && a.max_z > b.min_z
        && a.min_z < b.max_z
}

/// One prediction of [`Sequenced`] (`ServerVerifiedState`).
#[cfg(ghast_modern)]
#[derive(Clone, Copy, Debug)]
struct Verified<S> {
    pos: BlockPos,
    /// The sequence of the last prediction that changed this block.
    sequence: i32,
    /// The server's state as far as the client knows it.
    state: S,
    /// The player's position when the block was first predicted.
    player: [f64; 3],
}

/// `BlockStatePredictionHandler` of one client level (26.x).
#[cfg(ghast_modern)]
#[derive(Clone, Debug)]
pub(crate) struct Sequenced<S> {
    /// Vanilla keeps a hash map; the list is short (one entry per block broken in the last
    /// round trip).
    entries: Vec<Verified<S>>,
    /// `lastTeleportSequence`: the sequence when the last server teleport arrived.
    last_teleport: i32,
}

#[cfg(ghast_modern)]
impl<S> Default for Sequenced<S> {
    fn default() -> Self {
        Sequenced {
            entries: Vec::new(),
            last_teleport: -1,
        }
    }
}

#[cfg(ghast_modern)]
impl<S: Copy> Sequenced<S> {
    /// No prediction is waiting for the server.
    #[inline]
    pub(crate) fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// `retainKnownServerState`: the client changed `pos` (from `old`) in prediction
    /// `sequence`. A block predicted before keeps its first server state and player position
    /// and takes the new sequence.
    pub(crate) fn retain(&mut self, pos: BlockPos, old: S, sequence: i32, player: [f64; 3]) {
        if let Some(e) = self.entries.iter_mut().find(|e| e.pos == pos) {
            e.sequence = sequence;
        } else {
            self.entries.push(Verified {
                pos,
                sequence,
                state: old,
                player,
            });
        }
    }

    /// `updateKnownServerState`: a server block update for a predicted position replaces the
    /// remembered state (`true`: the world must not take it now).
    pub(crate) fn update(&mut self, pos: BlockPos, state: S) -> bool {
        match self.entries.iter_mut().find(|e| e.pos == pos) {
            Some(e) => {
                e.state = state;
                true
            }
            None => false,
        }
    }

    /// `onTeleport`: a server teleport arrived while `current` was the last sequence sent.
    pub(crate) fn on_teleport(&mut self, current: i32) {
        self.last_teleport = current;
    }

    /// `endPredictionsUpTo(ack)`: removes every prediction with a sequence up to `ack` and
    /// hands each to `sync` (`ClientLevel.syncBlockState`) with its remembered state and, unless
    /// a teleport arrived after `ack` was sent, the player position to return to.
    pub(crate) fn end_up_to(
        &mut self,
        ack: i32,
        mut sync: impl FnMut(BlockPos, S, Option<[f64; 3]>),
    ) {
        let reset = self.last_teleport < ack;
        self.entries.retain(|e| {
            if e.sequence <= ack {
                sync(e.pos, e.state, reset.then_some(e.player));
                false
            } else {
                true
            }
        });
    }

    /// A new client level (a new handler).
    pub(crate) fn clear(&mut self) {
        self.entries.clear();
        self.last_teleport = -1;
    }
}

/// `ClientPlayerInteractionManager.unacknowledgedPlayerActions` (1.16.5): (position, dig
/// action) → the player's position when the action was sent, in sending order.
#[cfg(feature = "v1_16_5")]
#[derive(Clone, Debug, Default)]
pub(crate) struct Unacked {
    entries: Vec<(BlockPos, u8, [f64; 3])>,
}

#[cfg(feature = "v1_16_5")]
impl Unacked {
    /// Vanilla drops the oldest entries from this size on (after each answer).
    const LIMIT: usize = 50;

    /// `sendPlayerAction`: `put` (an entry for the same position and action keeps its place and
    /// takes the new player position).
    pub(crate) fn put(&mut self, pos: BlockPos, action: u8, player: [f64; 3]) {
        if let Some(e) = self
            .entries
            .iter_mut()
            .find(|e| e.0 == pos && e.1 == action)
        {
            e.2 = player;
        } else {
            self.entries.push((pos, action, player));
        }
    }

    /// The answer's `remove(Pair.of(pos, action))`.
    pub(crate) fn remove(&mut self, pos: BlockPos, action: u8) -> Option<[f64; 3]> {
        let i = self
            .entries
            .iter()
            .position(|e| e.0 == pos && e.1 == action)?;
        Some(self.entries.remove(i).2)
    }

    /// The size limit after an answer ("Too many unacked block actions").
    pub(crate) fn trim(&mut self) {
        if self.entries.len() >= Self::LIMIT {
            let n = self.entries.len() + 1 - Self::LIMIT;
            log::debug!("too many unacknowledged block actions: dropping {n}");
            self.entries.drain(..n);
        }
    }

    /// A new interaction manager (join game).
    pub(crate) fn clear(&mut self) {
        self.entries.clear();
    }

    #[cfg(test)]
    fn len(&self) -> usize {
        self.entries.len()
    }
}

#[cfg(all(test, feature = "v1_16_5"))]
mod tests_unacked {
    use super::*;

    /// `put` keeps the first place of a (position, action) pair; `trim` leaves 49.
    #[test]
    fn unacked_order_and_limit() {
        let mut u = Unacked::default();
        let p = |i| BlockPos::new(i, 0, 0);
        u.put(p(1), 0, [1.0; 3]);
        u.put(p(1), 2, [2.0; 3]);
        u.put(p(1), 0, [3.0; 3]);
        assert_eq!(u.len(), 2);
        assert_eq!(u.remove(p(1), 0), Some([3.0; 3]));
        assert_eq!(u.remove(p(1), 0), None);
        for i in 0..60 {
            u.put(p(i), 1, [f64::from(i); 3]);
        }
        u.trim();
        assert_eq!(u.len(), 49);
        // The oldest went first.
        assert_eq!(u.remove(p(1), 2), None);
        assert_eq!(u.remove(p(10), 1), None);
        assert_eq!(u.remove(p(11), 1), Some([11.0; 3]));
    }
}

#[cfg(all(test, ghast_modern))]
mod tests {
    use super::*;

    #[test]
    fn sequenced_ends_up_to_the_ack() {
        let mut s = Sequenced::<u16>::default();
        let (a, b) = (BlockPos::new(1, 2, 3), BlockPos::new(4, 5, 6));
        s.retain(a, 1, 1, [0.0; 3]);
        s.retain(b, 1, 2, [0.0; 3]);
        // Predicted again: the first server state stays, the sequence moves.
        s.retain(a, 9, 3, [1.0; 3]);
        assert!(s.update(b, 7));
        assert!(!s.update(BlockPos::new(0, 0, 0), 7));
        let mut got = Vec::new();
        s.end_up_to(2, |p, st, pl| got.push((p, st, pl)));
        assert_eq!(got, [(b, 7, Some([0.0; 3]))]);
        s.on_teleport(3);
        got.clear();
        s.end_up_to(3, |p, st, pl| got.push((p, st, pl)));
        // A teleport at sequence 3: no position reset for acks up to 3.
        assert_eq!(got, [(a, 1, None)]);
        assert!(s.is_empty());
    }
}