ghast-client 0.5.3

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
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
//! The client's own share of the player's item actions: the held stacks' facts, item uses in the
//! air and their stack changes, attacks' effect on the player and the held stack, finished uses
//! (food, containers), the attack cooldown's held-item check, item-use bookkeeping, attributes
//! and enchantment levels.

use super::*;

/// The held stack's dig / use facts.
pub(super) fn held_item<W: Sim + ?Sized>(
    inv: &ghast_inventory::Inventory,
    sim: &W,
) -> Option<hands::HeldItem> {
    let s = inv.held()?;
    let id = u16::try_from(s.id()).ok()?;
    let count = u8::try_from(s.count().clamp(0, 255)).unwrap_or(0);
    Some(sim.item_use_facts(s, false, sim.held_item(id, count, efficiency(s))))
}

/// Whether a use of each hand's stack puts it on (armor, elytra): only with the right button
/// down, out of the key handling's hot path.
#[inline(never)]
pub(super) fn use_equips(
    c: &Core,
    creative: bool,
    held: &mut Option<hands::HeldItem>,
    off_held: &mut Option<hands::HeldItem>,
) {
    let swings = c.opts.caps.use_equip_swings;
    for (h, off) in [(held, false), (off_held, true)] {
        if let Some(h) = h.as_mut() {
            h.equips = c.inv.use_equips(off, creative);
            h.equip_swings = swings;
        }
    }
}

/// `interactItem`'s equip on the client (see [`ghast_inventory::Inventory::equip_from_hand`]).
#[cold]
#[inline(never)]
pub(super) fn equip_from_hand(
    inv: &mut ghast_inventory::Inventory,
    off_hand: bool,
    creative: bool,
) {
    inv.equip_from_hand(off_hand, creative);
}

/// Moves the hands' item use steps into the behaviour's events.
#[cold]
#[inline(never)]
pub(super) fn take_use_events(c: &mut Core) {
    c.current.more().item_use.append(&mut c.hands.use_events);
}

/// The off-hand stack's facts (1.9+).
pub(super) fn off_held_item<W: Sim + ?Sized>(
    inv: &ghast_inventory::Inventory,
    sim: &W,
) -> Option<hands::HeldItem> {
    let s = inv.offhand()?;
    let id = u16::try_from(s.id()).ok()?;
    let count = u8::try_from(s.count().clamp(0, 255)).unwrap_or(0);
    Some(sim.item_use_facts(s, true, sim.held_item(id, count, 0)))
}

/// What an item use in the air the version's rules decided changes on the client (no packet;
/// the server's block and slot updates follow): the blocks it set and the hand's stack. A stack
/// it gave that does not fit is dropped: vanilla's drop swings the main hand right after the
/// `use_item` packet.
#[cold]
#[inline(never)]
pub(super) fn air_used(c: &mut Core, sim: &mut (impl Sim + ?Sized)) {
    let used = std::mem::take(&mut c.hands.air_used);
    // (in order: the main hand's, then the off hand's; a later drop swing goes after an
    // earlier one)
    let mut shift = 0;
    for (off_hand, k, a) in used {
        shift += air_used_one(c, sim, off_hand, k as usize + shift, a);
    }
}

/// The swing packet of an attack or a dig click: the main-hand swing, 26.3's `punch`.
#[inline]
pub(super) fn attack_swing(caps: &crate::version::Capabilities) -> Outbound {
    if caps.sends_punch {
        Outbound::Punch
    } else {
        Outbound::Swing
    }
}

/// One hand's [`air_used`]; returns the packets it inserted.
fn air_used_one(
    c: &mut Core,
    sim: &mut (impl Sim + ?Sized),
    off_hand: bool,
    k: usize,
    a: crate::sim::predict::AirUse,
) -> usize {
    use crate::sim::predict::HandChange;
    if let Some(blocks) = a.blocks.as_deref()
        && !blocks.is_empty()
    {
        sim.air_use_sent(blocks);
    }
    match a.hand {
        HandChange::Keep => {}
        HandChange::UseOne => {
            if off_hand {
                c.inv.consume_offhand(1);
            } else {
                c.inv.consume_held(1);
            }
        }
        HandChange::Empty => c.inv.set_hand(off_hand, None),
        HandChange::Replace(s) => c.inv.set_hand(off_hand, Some(s)),
        HandChange::Exchange {
            output,
            creative_keeps,
        } => {
            let creative = c.abilities.creative_mode();
            if c.inv
                .exchange_hand(off_hand, output, creative, creative_keeps)
            {
                if !c.opts.caps.sends_swing {
                    // 26.3: the hand animation only
                    return 0;
                }
                let at = (k + 1).min(c.out.len());
                c.out.insert(at, Outbound::Swing);
                return 1;
            }
        }
        HandChange::ExchangeLegacy { output } => {
            // (a stack that does not fit is dropped without a swing)
            let _ = c.inv.exchange_hand(off_hand, output, false, false);
        }
    }
    0
}

/// `PlayerEntity.attack` on the client for this tick's attacks, in order: a hit the client
/// counts as landed ([`Sim::attack_hurts`]) with knockback slows the player
/// ([`Sim::attack_slow`]). The knockback is the held item's enchantment level (up to 1.16.5;
/// the client's is 0 on 26.x, see [`Capabilities::attack_knockback_enchantment`]) plus one
/// for a sprint attack, which 1.9+ grants only at full strength (cooldown above 0.9).
#[cold]
#[inline(never)]
pub(super) fn attack_effects(c: &mut Core, sim: &mut (impl Sim + ?Sized)) {
    let caps = c.opts.caps;
    let knockback = if caps.attack_knockback_enchantment {
        c.inv.held().map_or(0, |s| i32::from(knockback(s)))
    } else {
        0
    };
    let attacks = std::mem::take(&mut c.hands.attacks);
    for &(id, ticks) in &attacks {
        let hurts = sim
            .entities()
            .and_then(|t| t.get(id))
            .is_some_and(|e| sim.attack_hurts(e));
        if !hurts {
            continue;
        }
        let sprint_bonus =
            !caps.combat_1_9 || hands::attack_strength_at(ticks, c.attack_speed) > 0.9;
        sim.attack_slow(id, c.pose.yaw, knockback, sprint_bonus);
        // ItemStack.onEntityHit on a living target (another player on the client).
        let living = sim
            .entities()
            .and_then(|t| t.get(id))
            .is_some_and(ghast_entity::Entity::is_player);
        if living && c.game_mode != GameMode::Creative {
            hit_durability(c, id);
        }
    }
    // The list keeps its capacity for the next attacks.
    c.hands.attacks = attacks;
    c.hands.attacks.clear();
}

/// 1.8 / 1.12 `Item.postHit` of the held stack after a hit on a living entity: a sword loses 1,
/// an axe, pickaxe or shovel 2 (1.12: a hoe 1) on the client. Unbreaking rolls a random number:
/// then the server's slot update brings the damage.
#[cold]
#[inline(never)]
fn hit_durability(c: &mut Core, target: i32) {
    use ghast_inventory::ItemKind as K;
    let v = c.inv.version();
    let Some(s) = c.inv.held() else {
        return;
    };
    if !matches!(
        v,
        ghast_inventory::Version::V1_8 | ghast_inventory::Version::V1_12
    ) || enchant_level(s, 34, "minecraft:unbreaking") > 0
    {
        return;
    }
    let points = match s.kind(v) {
        K::Sword => 1,
        K::Axe | K::Pickaxe | K::Shovel => 2,
        K::Hoe if v == ghast_inventory::Version::V1_12 => 1,
        _ => return,
    };
    if !c.inv.damage_held(points) {
        return;
    }
    // A right click later in the same key handling sends the worn stack (1.8 block_place).
    let held = c.inv.held().cloned();
    let at = c.out.iter().position(|o| {
        matches!(o, Outbound::UseEntity { target: t, action: crate::common::EntityUse::Attack, .. } if *t == target)
    });
    if let Some(at) = at {
        for o in &mut c.out[at + 1..] {
            match o {
                Outbound::UseItem {
                    held: h,
                    off_hand: false,
                }
                | Outbound::Place {
                    held: h,
                    off_hand: false,
                    ..
                }
                | Outbound::PlaceInside {
                    held: h,
                    off_hand: false,
                    ..
                } => h.clone_from(&held),
                _ => {}
            }
        }
    }
}

/// Our finished use of a food (entity status 9): the client eats it itself
/// (`HungerManager.eat` in the item's finish), before the server's health update.
#[cold]
#[inline(never)]
pub(super) fn finish_food(c: &mut Core) {
    if let Some((false, item)) = c.hands.use_item()
        && let Some(p) = crate::sim::food_points(c.opts.caps.data, item)
    {
        c.health.food = (c.health.food + i32::from(p)).min(20);
    }
}

/// The client's own `onItemUseFinish` at the server's finish (1.8 – 1.16.5, not in creative
/// mode), on the used hand's stack before the server's `set_slot` (which can come a tick
/// later; a restarted use's 1.8 `block_place` carries the new stack): a food loses one item,
/// a potion, a milk bucket or a stew (1.16.5: also a honey bottle) becomes its container.
/// Not modelled: the second potion bottle a stack of several adds to the inventory.
pub(super) fn finish_consumes(c: &mut Core) {
    let Some((off_hand, item)) = c.hands.use_item() else {
        return;
    };
    let stack = if off_hand {
        c.inv.offhand()
    } else {
        c.inv.held()
    };
    if c.game_mode == GameMode::Creative
        || !stack.is_some_and(|s| u16::try_from(s.id()) == Ok(item))
    {
        return;
    }
    if let Some(container) = finish_container(c.opts.caps.data, item) {
        c.inv.finish_into(off_hand, container);
    } else if crate::sim::food_points(c.opts.caps.data, item).is_some() {
        if off_hand {
            c.inv.consume_offhand(1);
        } else {
            c.inv.consume_held(1);
        }
    }
}

/// The client's own stack changes of the key handling's clicks this tick (packets from
/// `first` on): item uses and releases, and an entity click's effect on its hand.
#[cold]
#[inline(never)]
pub(super) fn click_stack_effects(c: &mut Core, first: usize, entity: Option<hands::EntityHit>) {
    predict_use_effects(c, first);
    let Some(e) = entity else { return };
    // Each hand whose interact packet went out (1.9+ tries the off hand after a main hand
    // that was not handled).
    let mut clicked = [false; 2];
    for o in &c.out[first..] {
        if let Outbound::UseEntity {
            target,
            action: crate::common::EntityUse::Interact,
            off_hand,
            ..
        } = o
            && *target == e.id
        {
            clicked[usize::from(*off_hand)] = true;
        }
    }
    for (k, off_hand) in [(0, false), (1, true)] {
        let fx = e.interact[k].1;
        if clicked[k] && fx != hands::InteractEffect::None {
            interact_effect(c, off_hand, fx);
        }
    }
}

/// The client's own stack changes of this tick's item uses and releases (no packet; 1.8 –
/// 1.16.5, not in creative mode): a thrown snowball, egg, bottle o' enchanting or splash /
/// lingering potion (1.8: also an ender pearl) loses one item from its hand; a bow shot
/// released after at least 3 ticks of drawing takes one point of damage (1.8; 1.12 and
/// 1.16.5 damage it on the server only). Not modelled: the arrow taken from the inventory, ender
/// pearls on 1.12+ (their cooldown), Unbreaking.
pub(super) fn predict_use_effects(c: &mut Core, first: usize) {
    if c.game_mode == GameMode::Creative {
        return;
    }
    let data = c.opts.caps.data;
    for k in first..c.out.len() {
        let Outbound::UseItem {
            held: Some(s),
            off_hand,
        } = &c.out[k]
        else {
            continue;
        };
        if thrown(data, s) {
            let off = *off_hand;
            if off {
                c.inv.consume_offhand(1);
            } else {
                c.inv.consume_held(1);
            }
        }
    }
    if let Some((false, item, ticks)) = c.hands.released_use()
        && ticks >= 3
        && bow_damaged_on_client(data, item)
    {
        c.inv.damage_held(1);
    }
}

/// The client-side answer per hand to a right click on the entity `id`
/// ([`crate::interact::outcome`]). Out of line: it runs only on a tick that clicks an entity,
/// and inlined it makes the plain tick slower.
#[cold]
#[inline(never)]
pub(super) fn entity_click(
    c: &Core,
    ents: &ghast_entity::Entities,
    id: i32,
) -> [(hands::Interact, hands::InteractEffect); 2] {
    let item = |s: Option<&ghast_inventory::Stack>| {
        s.and_then(|s| Some((u16::try_from(s.id()).ok()?, s.damage())))
    };
    let inv_v = c.opts.inventory;
    let named =
        |s: Option<&ghast_inventory::Stack>| s.is_some_and(|s| s.custom_name(inv_v).is_some());
    crate::interact::outcome(
        ents,
        c.opts.caps.protocol,
        id,
        &c.opts.name,
        c.game_mode == GameMode::Spectator,
        c.pose.sneaking,
        c.game_mode == GameMode::Creative,
        [item(c.inv.held()), item(c.inv.offhand())],
        [named(c.inv.held()), named(c.inv.offhand())],
    )
}

/// An entity click's change of the clicking hand's stack (no packet).
#[cold]
#[inline(never)]
pub(super) fn interact_effect(c: &mut Core, off_hand: bool, fx: hands::InteractEffect) {
    use hands::InteractEffect as Fx;
    match fx {
        Fx::None => {}
        Fx::Take if off_hand => {
            c.inv.consume_offhand(1);
        }
        Fx::Take => {
            c.inv.consume_held(1);
        }
        Fx::Damage if !off_hand => {
            c.inv.damage_held(1);
        }
        Fx::Damage => {}
        Fx::IntoMilk => {
            if let Some(milk) = milk_bucket(c.opts.caps.data) {
                c.inv.finish_into(off_hand, milk);
            }
        }
        Fx::Into(item) => {
            c.inv.finish_into(off_hand, i32::from(item));
        }
    }
}

/// The milk bucket's raw item id.
pub(super) fn milk_bucket(data: crate::version::DataSet) -> Option<i32> {
    #[cfg(any(feature = "v1_8", feature = "v1_12_2", feature = "v1_16_5"))]
    use crate::version::DataSet;
    match data {
        #[cfg(feature = "v1_8")]
        DataSet::V1_8 => Some(335),
        #[cfg(feature = "v1_12_2")]
        DataSet::V1_12 => Some(335),
        #[cfg(feature = "v1_16_5")]
        DataSet::V1_16_5 => {
            ghast_data::v1_16_5::Item::from_name("milk_bucket").map(|i| i32::from(i.id()))
        }
        #[allow(unreachable_patterns)]
        _ => None,
    }
}

/// An item whose use throws it (and takes it from the stack on the client).
pub(super) fn thrown(data: crate::version::DataSet, s: &ghast_inventory::Stack) -> bool {
    #[cfg(any(feature = "v1_8", feature = "v1_12_2", feature = "v1_16_5"))]
    use crate::version::DataSet;
    let Ok(id) = u16::try_from(s.id()) else {
        return false;
    };
    match data {
        #[cfg(feature = "v1_8")]
        DataSet::V1_8 => {
            matches!(id, 332 | 344 | 368 | 384) || (id == 373 && s.damage() & 0x4000 != 0)
        }
        #[cfg(feature = "v1_12_2")]
        DataSet::V1_12 => matches!(id, 332 | 344 | 384 | 438 | 441),
        #[cfg(feature = "v1_16_5")]
        DataSet::V1_16_5 => ghast_data::v1_16_5::Item::from_id(id).is_some_and(|i| {
            matches!(
                i.info().name,
                "snowball" | "egg" | "experience_bottle" | "splash_potion" | "lingering_potion"
            )
        }),
        #[allow(unreachable_patterns)]
        _ => {
            let _ = id;
            false
        }
    }
}

/// A bow whose release damages it on the client (1.8 `ItemStack.damage`).
pub(super) fn bow_damaged_on_client(data: crate::version::DataSet, item: u16) -> bool {
    #[cfg(feature = "v1_8")]
    use crate::version::DataSet;
    match data {
        #[cfg(feature = "v1_8")]
        DataSet::V1_8 => item == 261,
        #[allow(unreachable_patterns)]
        _ => {
            let _ = item;
            false
        }
    }
}

/// The container a finished drink or stew leaves (raw item id), per version.
pub(super) fn finish_container(data: crate::version::DataSet, item: u16) -> Option<i32> {
    #[cfg(any(feature = "v1_8", feature = "v1_12_2", feature = "v1_16_5"))]
    use crate::version::DataSet;
    match data {
        #[cfg(feature = "v1_8")]
        DataSet::V1_8 => match item {
            373 => Some(374),
            335 => Some(325),
            282 => Some(281),
            _ => None,
        },
        #[cfg(feature = "v1_12_2")]
        DataSet::V1_12 => match item {
            373 => Some(374),
            335 => Some(325),
            282 | 413 | 436 => Some(281),
            _ => None,
        },
        #[cfg(feature = "v1_16_5")]
        DataSet::V1_16_5 => {
            use ghast_data::v1_16_5::Item;
            let to = match Item::from_id(item)?.info().name {
                "potion" | "honey_bottle" => "glass_bottle",
                "milk_bucket" => "bucket",
                "mushroom_stew" | "rabbit_stew" | "beetroot_soup" | "suspicious_stew" => "bowl",
                _ => return None,
            };
            Item::from_name(to).map(|i| i32::from(i.id()))
        }
        #[allow(unreachable_patterns)]
        _ => {
            let _ = item;
            None
        }
    }
}

/// 1.12 `PlayerEntity.tick`: when the held stack is not the last tick's item (1.12
/// `ItemStack.equals`: the same item, and for an item without durability the same damage
/// value), the attack cooldown resets after this tick's count (the next key handling reads
/// 0). Only a change of the raw (item, damage) pair is looked at further.
#[inline]
pub(super) fn cooldown_held_check(c: &mut Core) {
    let now = c.inv.held().map_or((-1, 0), |s| (s.id(), s.damage()));
    if now != c.cooldown_held {
        cooldown_held_changed(c, now);
    }
}

#[cold]
#[inline(never)]
fn cooldown_held_changed(c: &mut Core, now: (i32, i16)) {
    let old = c.cooldown_held;
    c.cooldown_held = now;
    let same = old.0 == now.0
        && (c.opts.caps.cooldown_reset == crate::version::CooldownReset::Item
            || old.1 == now.1
            || c.inv
                .held()
                .is_some_and(|s| s.is_damageable(c.inv.version())));
    if !same {
        c.hands.cooldown_reset_pending = true;
    }
}

/// 1.9+ `ClientPlayerEntity.onTrackedDataSet(LIVING_FLAGS)`: the server says we use an item
/// (bit 1, bit 2 the off hand) while we do not: the stack in that hand is in use now; it says
/// we do not while we do: the use ends (no packet).
#[cold]
#[inline(never)]
pub(super) fn living_flags_use(c: &mut Core, flags: u8) {
    let active = flags & 1 != 0;
    if active && !c.hands.using_item() {
        let off_hand = flags & 2 != 0;
        let stack = if off_hand {
            c.inv.offhand()
        } else {
            c.inv.held()
        };
        if let Some(id) = stack.and_then(|s| u16::try_from(s.id()).ok()) {
            c.hands.server_start_using(off_hand, id);
        }
    } else if !active && c.hands.using_item() {
        c.hands.stop_using();
    }
}

/// The food level the hands' eat test reads (`canConsume`): 1.8 / 1.12 eat nothing while
/// invulnerable (creative), 1.16.5 eats anything then.
#[inline]
pub(super) fn use_food_level(c: &Core) -> i32 {
    use_food_level_of(&c.abilities, c.opts.caps.invulnerable_eating, c.health.food)
}

/// The player's mining speed modifiers now, with `in_water` from the caller (the eyes' block),
/// for the behaviour's actions. The buttons' tick builds its own copy: sharing this one there
/// cost instructions per tick.
pub(super) fn dig_factors(c: &Core, in_water: bool) -> DigFactors {
    DigFactors {
        on_ground: c.pose.on_ground,
        in_water,
        aqua_affinity: c.aqua_affinity,
        haste: c.effects.get(&3).map_or(0, |a| (*a as u8).wrapping_add(1)),
        fatigue: c.effects.get(&4).map_or(0, |a| (*a as u8).wrapping_add(1)),
    }
}

/// [`use_food_level`] from its parts.
#[inline]
pub(super) fn use_food_level_of(
    abilities: &crate::common::Abilities,
    eating: crate::version::InvulnerableEating,
    food: i32,
) -> i32 {
    if abilities.invulnerable() {
        match eating {
            crate::version::InvulnerableEating::Never => return -1,
            crate::version::InvulnerableEating::Always => return 0,
            crate::version::InvulnerableEating::Hunger => {}
        }
    }
    food
}

/// 1.8 `PlayerEntity.tick`, 1.12 `updateActiveHand`, 1.16.5 `tickActiveItemStack`: the item
/// use goes on while the used hand holds the stack it started with (the same slot, no server
/// write of it since) or, on 1.16.5, the same item; else it ends without a packet.
#[inline(never)]
pub(super) fn held_use_check(c: &mut Core) {
    let off_hand = c.hands.use_item().is_some_and(|(off, _)| off);
    let stack = if off_hand {
        c.inv.offhand()
    } else {
        c.inv.held()
    };
    let now = if c.opts.caps.use_stop == crate::version::UseStop::HeldItemChanged {
        let id = stack.map_or(0, |s| u16::try_from(s.id()).unwrap_or(u16::MAX));
        (c.hands.use_serial, 0, id)
    } else if off_hand {
        (c.hands.use_serial, 255, c.inv.offhand_writes())
    } else {
        (c.hands.use_serial, c.held_slot, c.inv.held_writes())
    };
    match c.use_mark {
        Some(m) if m.0 != now.0 => c.use_mark = Some(now),
        None => c.use_mark = Some(now),
        Some(m) if m != now => {
            c.hands.stop_using();
            c.use_mark = None;
        }
        Some(_) => {}
    }
}

/// Our movement speed attribute from the server (the sim replaces its modifiers with it).
pub(super) fn movement_speed(
    c: &Core,
    sim: &mut (impl Sim + ?Sized),
    base: f64,
    modifiers: &[(uuid::Uuid, f64, i8)],
) {
    log::debug!(
        "[{}] t{} movement speed base {base:?} modifiers {modifiers:?}",
        c.opts.name,
        c.tick
    );
    let mods: Vec<(u128, f64, u8)> = modifiers
        .iter()
        .map(|&(id, amount, op)| (id.as_u128(), amount, op as u8))
        .collect();
    sim.movement_speed(base, &mods);
}

/// A 1.20.5+ attribute's value (`AttributeInstance.calculateValue`: additions, then
/// multiplied-base, then multiplied-total modifiers; clamped to the attack speed range).
pub(super) fn modern_attribute_value(a: &crate::common::AttributeUpdate) -> f64 {
    let ops = |op: i8| a.modifiers.iter().filter(move |m| m.2 == op).map(|m| m.1);
    let d = a.base + ops(0).sum::<f64>();
    let mut e = d;
    for v in ops(1) {
        e += d * v;
    }
    for v in ops(2) {
        e *= 1.0 + v;
    }
    e.clamp(0.0, 1024.0)
}

/// Knockback enchantment level of a stack (see [`enchant_level`]).
pub(super) fn knockback(s: &ghast_inventory::Stack) -> u8 {
    enchant_level(s, 19, "minecraft:knockback")
}

/// Efficiency level of a stack (see [`enchant_level`]).
pub(super) fn efficiency(s: &ghast_inventory::Stack) -> u8 {
    enchant_level(s, 32, "minecraft:efficiency")
}

/// An enchantment level from the stack NBT: the 1.8 `ench` list with numeric ids, or the 1.13+
/// `Enchantments` list with names. Parsed only when the stack has NBT.
pub(super) fn enchant_level(s: &ghast_inventory::Stack, id_1_8: i32, name: &str) -> u8 {
    use ghast_protocol::nbt::Tag;
    let Some(root) = s.nbt().and_then(|n| n.parse().ok().flatten()) else {
        return 0;
    };
    let Some(c) = root.tag.as_compound() else {
        return 0;
    };
    let num = |t: Option<&Tag>| match t {
        Some(Tag::Short(v)) => i32::from(*v),
        Some(Tag::Int(v)) => *v,
        Some(Tag::Byte(v)) => i32::from(*v),
        _ => -1,
    };
    for key in ["ench", "Enchantments"] {
        if let Some(Tag::List(l)) = c.get(key) {
            for e in l.items.iter().filter_map(Tag::as_compound) {
                let hit = match e.get("id") {
                    Some(Tag::String(n)) => n == name,
                    other => num(other) == id_1_8,
                };
                if hit {
                    return u8::try_from(num(e.get("lvl")).clamp(0, 255)).unwrap_or(0);
                }
            }
        }
    }
    0
}