ghast-inventory 0.4.2

Inventory and container windows for the ghast Minecraft Java Edition client library: vanilla client-side click prediction, the window confirm protocol, hashed 26.1 clicks and lazy NBT / data-component item stacks (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
//! 26.1 configuration data some menus read (the anvil, grindstone, loom and mount screens):
//! the tags of `update_tags` and the enchantment definitions of `registry_data`. Both arrive at
//! every join and are kept as their raw bytes; they are parsed only when a click in such a menu
//! first needs them (a bot that never opens one pays a copy of the bytes, nothing more).
//! Enchantments the server sends without data (the client knows the vanilla data pack) take
//! their vanilla definitions from `src/generated/enchantments_26_1.rs`.

use std::collections::HashMap;

use bytes::Bytes;
use ghast_protocol::codec::Reader;
use ghast_protocol::nbt::{AnonNbt, Tag};

/// A holder set as data components and definitions write it: a tag or listed registry ids.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Holders {
    Tag(String),
    Ids(Vec<i32>),
}

/// What the anvil (and the trident spin) reads off an enchantment.
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct Ench {
    pub max_level: i32,
    pub anvil_cost: i32,
    pub supported: Holders,
    pub exclusive: Option<Holders>,
    /// The `minecraft:trident_spin_attack_strength` effect: `None` without one, `Some(None)`
    /// when it does not read.
    pub spin: Option<Option<crate::ench_value::Fx>>,
}

/// The tag registries the menus read.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) enum Reg {
    Item,
    Enchantment,
    BannerPattern,
    EntityType,
}

#[derive(Debug, Clone, Default)]
pub(crate) struct Data26 {
    tags_raw: Option<Bytes>,
    tags: Option<HashMap<(Reg, String), Vec<i32>>>,
    ench_raw: Option<Bytes>,
    /// By enchantment registry id (`None`: no definition known).
    ench: Option<Vec<Option<Ench>>>,
    /// Enchantment names by registry id (from `registry_data`, else the hash registries).
    ench_names: Vec<String>,
}

fn reg_of(name: &str) -> Option<Reg> {
    Some(match name.strip_prefix("minecraft:").unwrap_or(name) {
        "item" => Reg::Item,
        "enchantment" => Reg::Enchantment,
        "banner_pattern" => Reg::BannerPattern,
        "entity_type" => Reg::EntityType,
        _ => return None,
    })
}

/// A `Holders` from its definition / report text: `#tag`, one name or a list of names.
pub(crate) fn holders_from_names(spec: &str, id: impl Fn(&str) -> Option<i32>) -> Option<Holders> {
    if let Some(t) = spec.strip_prefix('#') {
        return Some(Holders::Tag(t.to_string()));
    }
    let mut ids = Vec::new();
    for n in spec.split(',').filter(|n| !n.is_empty()) {
        ids.push(id(n)?);
    }
    Some(Holders::Ids(ids))
}

fn names_spec(t: &Tag) -> Option<String> {
    match t {
        Tag::String(s) => Some(s.clone()),
        Tag::List(l) => {
            let mut out = Vec::new();
            for e in &l.items {
                match e {
                    Tag::String(s) => out.push(s.clone()),
                    _ => return None,
                }
            }
            Some(out.join(","))
        }
        _ => None,
    }
}

/// One enchantment entry: name and, when sent with data, `(max_level, anvil_cost,
/// supported_items, exclusive_set, trident_spin_attack_strength)` (the effect in the text form
/// of `ench_value::Fx`, `""` without one, `"?"` when it does not read).
pub type EnchantmentSpec = (String, Option<(i32, i32, String, String, String)>);

/// `(name, max_level, anvil_cost, supported_items, exclusive_set)` of every enchantment entry
/// with data in a `registry_data` body (holder sets as `#tag` or comma-separated names).
pub(crate) fn enchantment_specs(body: &[u8]) -> Option<Vec<EnchantmentSpec>> {
    let b = Bytes::copy_from_slice(body);
    let mut r = Reader::new(&b);
    let registry = r.read_string().ok()?;
    if reg_of(&registry) != Some(Reg::Enchantment) {
        return None;
    }
    let n = r.read_varint().ok()?;
    let mut out = Vec::new();
    for _ in 0..n.max(0) {
        let key = r.read_string().ok()?.to_string();
        let def = if r.read_bool().ok()? {
            let nbt = AnonNbt::read(&mut r).ok()?;
            let tag = nbt.parse().ok()??;
            let c = tag.as_compound()?;
            let get = |k: &str| c.0.iter().rev().find(|(n, _)| n == k).map(|(_, v)| v);
            let int = |k: &str| match get(k) {
                Some(Tag::Int(v)) => Some(*v),
                _ => None,
            };
            Some((
                int("max_level")?,
                int("anvil_cost")?,
                names_spec(get("supported_items")?)?,
                get("exclusive_set")
                    .and_then(names_spec)
                    .unwrap_or_default(),
                spin_spec(get("effects")),
            ))
        } else {
            None
        };
        out.push((key, def));
    }
    Some(out)
}

/// The text form of an `effects` compound's `minecraft:trident_spin_attack_strength`.
fn spin_spec(effects: Option<&Tag>) -> String {
    let Some(c) = effects.and_then(Tag::as_compound) else {
        return String::new();
    };
    match c
        .0
        .iter()
        .rev()
        .find(|(n, _)| n == "minecraft:trident_spin_attack_strength")
    {
        None => String::new(),
        Some((_, t)) => {
            crate::ench_value::Fx::from_tag(t).map_or_else(|| "?".into(), |fx| fx.to_string())
        }
    }
}

impl Data26 {
    /// `update_tags` (configuration or play): replaces the tags.
    pub(crate) fn set_tags_raw(&mut self, body: Bytes) {
        // Only the registries `parse_tags` reads are kept (a vanilla body is ~32 KB, these ~4).
        self.tags_raw = Some(kept_tags(&body).unwrap_or(body));
        self.tags = None;
    }

    /// A `registry_data` body; kept when it is the enchantment registry.
    pub(crate) fn set_registry_raw(&mut self, body: Bytes) {
        let mut r = Reader::new(&body);
        if r.read_string().ok().as_deref().and_then(reg_of) == Some(Reg::Enchantment) {
            self.ench_raw = Some(body);
            self.ench = None;
        }
    }

    /// Bytes kept unparsed (for measurements).
    #[allow(dead_code)]
    pub(crate) fn raw_len(&self) -> usize {
        self.tags_raw.as_ref().map_or(0, Bytes::len) + self.ench_raw.as_ref().map_or(0, Bytes::len)
    }

    /// Parses what is still raw (the first click in a menu that reads tags or enchantments).
    pub(crate) fn ensure(&mut self, mv: crate::tables::Mv, ench_names: &[String]) {
        if let Some(raw) = self.tags_raw.take() {
            self.tags = parse_tags(&raw);
        }
        if self.ench.is_none() || (self.ench_names.is_empty() && !ench_names.is_empty()) {
            self.parse_enchantments(mv, ench_names);
        }
    }

    fn parse_enchantments(&mut self, mv: crate::tables::Mv, hash_names: &[String]) {
        let from_packet = self.ench_raw.take().and_then(|b| enchantment_specs(&b));
        let mut names: Vec<String> = match &from_packet {
            Some(v) => v.iter().map(|(n, _)| n.clone()).collect(),
            None => hash_names.to_vec(),
        };
        if names.is_empty() {
            names = hash_names.to_vec();
        }
        let id_of = |n: &str| names.iter().position(|x| x == n).map(|i| i as i32);
        let item_id = |n: &str| crate::item26::item_id(mv, n);
        let mut defs = Vec::with_capacity(names.len());
        for (i, name) in names.iter().enumerate() {
            let spec = from_packet
                .as_ref()
                .and_then(|v| v.get(i))
                .and_then(|(_, d)| d.clone())
                .or_else(|| {
                    builtin(name)
                        .map(|(m, a, s, e, x)| (m, a, s.to_string(), e.to_string(), x.to_string()))
                });
            defs.push(spec.and_then(|(max_level, anvil_cost, s, e, x)| {
                Some(Ench {
                    max_level,
                    anvil_cost,
                    supported: holders_from_names(&s, item_id)?,
                    exclusive: if e.is_empty() {
                        None
                    } else {
                        Some(holders_from_names(&e, id_of)?)
                    },
                    spin: (!x.is_empty()).then(|| crate::ench_value::Fx::parse(&x)),
                })
            }));
        }
        self.ench = Some(defs);
        self.ench_names = names;
    }

    /// The definition of enchantment `id`.
    pub(crate) fn enchantment(&self, id: i32) -> Option<&Ench> {
        self.ench.as_ref()?.get(usize::try_from(id).ok()?)?.as_ref()
    }

    /// The ids of a tag (`None` when no tags were received or the tag is unknown).
    pub(crate) fn tag(&self, reg: Reg, name: &str) -> Option<&[i32]> {
        let name = name.strip_prefix('#').unwrap_or(name);
        let full = if name.contains(':') {
            name.to_string()
        } else {
            format!("minecraft:{name}")
        };
        self.tags.as_ref()?.get(&(reg, full)).map(Vec::as_slice)
    }

    /// Whether `id` is in a holder set (`None` when a tag is not known).
    pub(crate) fn contains(&self, reg: Reg, set: &Holders, id: i32) -> Option<bool> {
        match set {
            Holders::Ids(v) => Some(v.contains(&id)),
            Holders::Tag(t) => self.tag(reg, t).map(|v| v.contains(&id)),
        }
    }

    /// The ids of a holder set, in order.
    pub(crate) fn resolve(&self, reg: Reg, set: &Holders) -> Option<Vec<i32>> {
        match set {
            Holders::Ids(v) => Some(v.clone()),
            Holders::Tag(t) => self.tag(reg, t).map(<[i32]>::to_vec),
        }
    }
}

/// The registries of an `update_tags` body that [`parse_tags`] keeps, re-framed as one
/// exact-size body (`None` when the body does not parse).
fn kept_tags(body: &Bytes) -> Option<Bytes> {
    let mut r = Reader::new(body);
    let n = r.read_varint().ok()?;
    let mut kept: Vec<&[u8]> = Vec::new();
    for _ in 0..n.max(0) {
        let start = r.position();
        let keep = reg_of(&r.read_string().ok()?).is_some();
        let k = r.read_varint().ok()?;
        for _ in 0..k.max(0) {
            r.read_string().ok()?;
            let c = r.read_varint().ok()?;
            for _ in 0..c.max(0) {
                r.read_varint().ok()?;
            }
        }
        if keep {
            kept.push(&body[start..r.position()]);
        }
    }
    let count = i32::try_from(kept.len()).ok()?;
    let len: usize = kept.iter().map(|k| k.len()).sum();
    let mut out = Vec::with_capacity(len + 5);
    let mut v = count as u32;
    loop {
        if v < 0x80 {
            out.push(v as u8);
            break;
        }
        out.push((v as u8 & 0x7f) | 0x80);
        v >>= 7;
    }
    for k in kept {
        out.extend_from_slice(k);
    }
    Some(Bytes::from(out))
}

fn parse_tags(raw: &Bytes) -> Option<HashMap<(Reg, String), Vec<i32>>> {
    let mut r = Reader::new(raw);
    let mut out = HashMap::new();
    let n = r.read_varint().ok()?;
    for _ in 0..n.max(0) {
        let reg = r.read_string().ok()?;
        let keep = reg_of(&reg);
        let k = r.read_varint().ok()?;
        for _ in 0..k.max(0) {
            let name = r.read_string().ok()?;
            let c = r.read_varint().ok()?;
            let c = r.check_count(i64::from(c), 1).ok()?;
            let mut ids = Vec::with_capacity(if keep.is_some() { c } else { 0 });
            for _ in 0..c {
                let v = r.read_varint().ok()?;
                if keep.is_some() {
                    ids.push(v);
                }
            }
            if let Some(reg) = keep {
                out.insert((reg, name.to_string()), ids);
            }
        }
    }
    Some(out)
}

mod builtin_table {
    /// `(offset, len)` in [`ENCHANTMENT_TEXT`].
    type Span = (u32, u16);
    include!("generated/enchantments_26_1.rs");

    pub(super) fn text((o, l): Span) -> &'static str {
        let o = o as usize;
        ENCHANTMENT_TEXT.get(o..o + usize::from(l)).unwrap_or("")
    }
}

/// The vanilla definition of an enchantment (`max_level`, `anvil_cost`, supported items,
/// exclusive set, trident spin attack strength effect).
fn builtin(name: &str) -> Option<(i32, i32, &'static str, &'static str, &'static str)> {
    use builtin_table::text;
    builtin_table::ENCHANTMENTS
        .iter()
        .find(|e| text(e.0) == name)
        .map(|e| (e.1, e.2, text(e.3), text(e.4), text(e.5)))
}

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

    /// `update_tags` body: registries of (tag name, ids).
    /// (registry, [(tag, ids)]).
    type Reg<'a> = (&'a str, &'a [(&'a str, &'a [i32])]);

    fn body(regs: &[Reg<'_>]) -> Vec<u8> {
        fn varint(o: &mut Vec<u8>, v: i32) {
            let mut v = v as u32;
            loop {
                if v < 0x80 {
                    o.push(v as u8);
                    return;
                }
                o.push((v as u8 & 0x7f) | 0x80);
                v >>= 7;
            }
        }
        fn string(o: &mut Vec<u8>, s: &str) {
            varint(o, s.len() as i32);
            o.extend_from_slice(s.as_bytes());
        }
        let mut o = Vec::new();
        varint(&mut o, regs.len() as i32);
        for (reg, tags) in regs {
            string(&mut o, reg);
            varint(&mut o, tags.len() as i32);
            for (name, ids) in *tags {
                string(&mut o, name);
                varint(&mut o, ids.len() as i32);
                for &i in *ids {
                    varint(&mut o, i);
                }
            }
        }
        o
    }

    #[test]
    fn kept_tags_keep_what_parse_tags_reads() {
        let many: Vec<i32> = (0..300).collect();
        let full = body(&[
            (
                "minecraft:block",
                &[("minecraft:logs", &many[..]), ("minecraft:dirt", &[1, 2])],
            ),
            (
                "minecraft:item",
                &[
                    ("minecraft:swords", &[800, 801, 1000]),
                    ("minecraft:empty", &[]),
                ],
            ),
            ("minecraft:fluid", &[("minecraft:water", &[1, 2])]),
            (
                "minecraft:enchantment",
                &[("minecraft:exclusive_set/armor", &[3, 4])],
            ),
            (
                "minecraft:banner_pattern",
                &[("minecraft:no_item_required", &[0, 1, 2])],
            ),
            ("minecraft:entity_type", &[("minecraft:skeletons", &[5])]),
        ]);
        let full = Bytes::from(full);
        let kept = kept_tags(&full).unwrap();
        assert!(
            kept.len() < full.len() / 3,
            "{} of {}",
            kept.len(),
            full.len()
        );
        assert_eq!(parse_tags(&kept), parse_tags(&full));
        assert_eq!(parse_tags(&kept).unwrap().len(), 5);
        // Truncated: not parsed, the caller keeps the body as it is.
        assert!(kept_tags(&full.slice(..full.len() - 1)).is_none());
    }
}