enshwick 1.0.0-alpha.11

The Enshwick Loader's modding API for Enshrouded: the one crate mods are written against
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
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
//! Vanilla content by the names the game gives it: items by their debug
//! names in the item registry, and crafting stations and their workshops by
//! the station's item, read from the game's archive.
//!
//! [`Vanilla::game`] reads the running game's data; [`Vanilla::new`] reads
//! any game's through a function of the caller's, as a tool outside the
//! game does.

use std::collections::BTreeMap;
use std::sync::OnceLock;

use crate::Off;
use crate::abi::ResourceKey;

use super::containers::{ContainerLayout, container_slots};
use super::items::{ITEM_REGISTRY, ItemLayout};
use super::loot_tables::{FillTableLayout, template_table};
use super::recipes::{RECIPE_REGISTRY, RecipeLayout};
use super::workshops::{
    Station, WORKSHOP_REGISTRY, WorkshopId, WorkshopLayout, clone_template, stations,
};
use super::{Blob, EngineFacts, Guid, types};

/// Reads one resource of the game's archive.
type Reader = Box<dyn Fn(ResourceKey) -> Option<Vec<u8>> + Send + Sync>;

/// Item debug names to the items that carry them.
type Names = BTreeMap<String, Vec<Guid>>;

/// The most near names a [`VanillaError::Unknown`] suggests.
const NEAR: usize = 5;

/// Why a vanilla name or station was not found.
///
/// # Examples
///
/// ```
/// use enshwick::content::vanilla::VanillaError;
///
/// let unknown = VanillaError::Unknown { name: "Tool_Torch1".into(), near: vec!["Tool_Torch01".into()] };
/// assert_eq!(unknown.to_string(), "no vanilla item \"Tool_Torch1\"; near: Tool_Torch01");
/// ```
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum VanillaError {
    /// The game's data does not read.
    #[error("the game's {0} does not read")]
    Unreadable(&'static str),
    /// No vanilla item has the name; `near` lists names that look like it.
    #[error("no vanilla item {name:?}{}", near_list(near))]
    Unknown {
        /// The name asked for.
        name: String,
        /// Names that look like it, at most five.
        near: Vec<String>,
    },
    /// Several vanilla items have the name.
    #[error("{} vanilla items are named {name:?}: {}; name one by its GUID", items.len(), guid_list(items))]
    Ambiguous {
        /// The name asked for.
        name: String,
        /// The items that carry it.
        items: Vec<Guid>,
    },
    /// No vanilla recipe has the debug name; `near` lists names that look
    /// like it.
    #[error("no vanilla recipe {name:?}{}", near_list(near))]
    UnknownRecipe {
        /// The name asked for.
        name: String,
        /// Names that look like it, at most five.
        near: Vec<String>,
    },
    /// Several vanilla recipes have the debug name.
    #[error("{} vanilla recipes are named {name:?}: {}; name one by its GUID", recipes.len(), guid_list(recipes))]
    AmbiguousRecipe {
        /// The name asked for.
        name: String,
        /// The recipes that carry it.
        recipes: Vec<Guid>,
    },
    /// No vanilla container template of the name rolls a fill table; `near`
    /// lists names that look like it.
    #[error("no vanilla container {name:?} rolls a loot table{}", near_list(near))]
    NoLootTable {
        /// The name asked for.
        name: String,
        /// Names that look like it, at most five.
        near: Vec<String>,
    },
    /// The item is no crafting station a mod can clone: the game lists no
    /// workshop for it, its workshop is a survivor's, or its template lacks
    /// the crafting components.
    #[error("{0} is no crafting station that can be cloned")]
    NotAStation(Guid),
}

fn near_list(near: &[String]) -> String {
    if near.is_empty() {
        String::new()
    } else {
        format!("; near: {}", near.join(", "))
    }
}

fn guid_list(items: &[Guid]) -> String {
    items
        .iter()
        .map(ToString::to_string)
        .collect::<Vec<_>>()
        .join(", ")
}

/// The game's vanilla content, read on demand.
///
/// # Examples
///
/// ```
/// use enshwick::content::vanilla::Vanilla;
///
/// if let Some(vanilla) = Vanilla::game() {
///     let forge = vanilla.item("Prop_Production_T1_Forge")?;
///     let station = vanilla.station(forge)?;
///     assert_eq!(station.item, forge);
/// }
/// # Ok::<(), enshwick::content::vanilla::VanillaError>(())
/// ```
pub struct Vanilla {
    items: ItemLayout,
    workshops: WorkshopLayout,
    hashes: Hashes,
    read: Reader,
    names: OnceLock<Option<Names>>,
    /// The recipe layout and the recipe registry's type hash, when the
    /// build reflects them.
    recipes: Option<(RecipeLayout, u32)>,
    recipe_list: OnceLock<Option<Recipes>>,
    /// The container layout, when the build reflects it.
    containers: Option<ContainerLayout>,
    /// Where templates name the fill table they roll, when the build
    /// reflects it.
    fill: Option<FillTableLayout>,
    fill_tables: OnceLock<Option<FillTables>>,
}

/// The fill tables containers roll: each container template's by its name,
/// and how many templates roll each table.
#[derive(Debug, Default)]
struct FillTables {
    by_name: Names,
    shared: BTreeMap<[u8; 16], usize>,
}

/// The fill table a vanilla container rolls, from
/// [`Vanilla::loot_table`].
///
/// # Examples
///
/// See [`Vanilla::loot_table`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct LootTable {
    /// The table's GUID, a `DefaultInventoryResource`.
    pub table: Guid,
    /// How many container templates roll it, this one among them.
    pub containers: usize,
}

/// The vanilla recipes: by debug name, and each with the item it makes.
#[derive(Debug, Default)]
struct Recipes {
    names: Names,
    made: Vec<(Guid, Option<Guid>)>,
}

impl core::fmt::Debug for Vanilla {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("Vanilla")
            .field("items", &self.items)
            .field("workshops", &self.workshops)
            .finish_non_exhaustive()
    }
}

/// The hashes of the resource types vanilla content is read from.
#[derive(Clone, Copy, Debug)]
struct Hashes {
    item: u32,
    item_registry: u32,
    template: u32,
    workshop_registry: u32,
    template_collection: u32,
}

impl Hashes {
    fn resolve(facts: &(impl EngineFacts + ?Sized)) -> Result<Self, Off> {
        Ok(Self {
            item: facts.hash(types::ITEM_INFO.id())?,
            item_registry: facts.hash(types::ITEM_REGISTRY_RESOURCE.id())?,
            template: facts.hash(types::TEMPLATE_RESOURCE.id())?,
            workshop_registry: facts.hash(types::WORKSHOP_REGISTRY_RESOURCE.id())?,
            template_collection: facts.hash(types::TEMPLATE_COLLECTION_RESOURCE.id())?,
        })
    }
}

impl Vanilla {
    /// Vanilla content read through `read`, which returns a resource of the
    /// game's archive by key, with the layouts and types `facts` give.
    ///
    /// # Errors
    ///
    /// The first [`Off`] a fact returns, when the build lacks it.
    ///
    /// # Examples
    ///
    /// ```
    /// use enshwick::content::EngineFacts;
    /// use enshwick::content::vanilla::Vanilla;
    ///
    /// fn offline(facts: &impl EngineFacts) -> Result<Vanilla, enshwick::Off> {
    ///     Vanilla::new(facts, |_key| None)
    /// }
    /// ```
    pub fn new(
        facts: &(impl EngineFacts + ?Sized),
        read: impl Fn(ResourceKey) -> Option<Vec<u8>> + Send + Sync + 'static,
    ) -> Result<Self, Off> {
        Ok(Self::with_parts(
            ItemLayout::resolve(facts)?,
            WorkshopLayout::resolve(facts)?,
            Hashes::resolve(facts)?,
            read,
        )
        .with_recipe_facts(facts)
        .with_containers(ContainerLayout::resolve(facts).ok())
        .with_fill_tables(FillTableLayout::resolve(facts).ok()))
    }

    fn with_parts(
        items: ItemLayout,
        workshops: WorkshopLayout,
        hashes: Hashes,
        read: impl Fn(ResourceKey) -> Option<Vec<u8>> + Send + Sync + 'static,
    ) -> Self {
        Self {
            items,
            workshops,
            hashes,
            read: Box::new(read),
            names: OnceLock::new(),
            recipes: None,
            recipe_list: OnceLock::new(),
            containers: None,
            fill: None,
            fill_tables: OnceLock::new(),
        }
    }

    /// The same, reading recipes through `layout` from the registry of type
    /// `hash`.
    fn with_recipes(mut self, layout: RecipeLayout, hash: u32) -> Self {
        self.recipes = Some((layout, hash));
        self
    }

    /// The same, reading containers through `layout`.
    fn with_containers(mut self, layout: Option<ContainerLayout>) -> Self {
        self.containers = layout;
        self
    }

    /// The same, reading the fill tables containers roll through `layout`.
    fn with_fill_tables(mut self, layout: Option<FillTableLayout>) -> Self {
        self.fill = layout;
        self
    }

    /// The fill table the vanilla container template named `name` rolls,
    /// such as `LootContainer_Enemy_Corpse_Vukah`, with how many templates
    /// share it: a change of the table reaches all of them. The first call
    /// reads every template once.
    ///
    /// # Errors
    ///
    /// [`VanillaError::NoLootTable`] with the names that look like it, and
    /// [`VanillaError::Unreadable`] when the templates do not read.
    ///
    /// # Examples
    ///
    /// ```
    /// use enshwick::content::vanilla::Vanilla;
    ///
    /// if let Some(vanilla) = Vanilla::game() {
    ///     let vukah = vanilla.loot_table("LootContainer_Enemy_Corpse_Vukah")?;
    ///     assert!(vukah.containers >= 1);
    /// }
    /// # Ok::<(), enshwick::content::vanilla::VanillaError>(())
    /// ```
    pub fn loot_table(&self, name: &str) -> Result<LootTable, VanillaError> {
        let tables = self
            .fill_tables
            .get_or_init(|| self.read_fill_tables())
            .as_ref()
            .ok_or(VanillaError::Unreadable("container templates"))?;
        match tables.by_name.get(name).and_then(|tables| tables.first()) {
            Some(table) => Ok(LootTable {
                table: *table,
                containers: tables.shared.get(&table.0).copied().unwrap_or(1),
            }),
            None => Err(VanillaError::NoLootTable {
                name: name.to_owned(),
                near: near(&tables.by_name, name),
            }),
        }
    }

    fn read_fill_tables(&self) -> Option<FillTables> {
        let layout = self.fill?;
        let collection = (self.read)(
            super::workshops::TEMPLATE_COLLECTION.key_by_hash(self.hashes.template_collection),
        )?;
        let blob = Blob::new(&collection);
        let (start, count) = blob.array(self.workshops.templates)?;
        let mut tables = FillTables::default();
        for at in (0..usize::try_from(count).ok()?).map(|i| start + i * 16) {
            let guid: [u8; 16] = collection.get(at..at + 16)?.try_into().ok()?;
            let Some(template) = (self.read)(Guid(guid).key_by_hash(self.hashes.template)) else {
                continue;
            };
            if let Some((name, table)) = template_table(&layout, &template) {
                *tables.shared.entry(table.0).or_default() += 1;
                tables.by_name.entry(name).or_default().push(table);
            }
        }
        Some(tables)
    }

    /// How many slots the container the vanilla item `item` places holds,
    /// or the backpack it is; `None` when it places or carries none.
    ///
    /// # Errors
    ///
    /// [`VanillaError::Unreadable`] when the item's data, the container
    /// layout or the template does not read.
    ///
    /// # Examples
    ///
    /// ```
    /// use enshwick::content::vanilla::Vanilla;
    ///
    /// if let Some(vanilla) = Vanilla::game() {
    ///     let chest = vanilla.item("Prop_Storage_24_T1_Box")?;
    ///     assert_eq!(vanilla.container_slots(chest)?, Some(24));
    /// }
    /// # Ok::<(), enshwick::content::vanilla::VanillaError>(())
    /// ```
    pub fn container_slots(&self, item: Guid) -> Result<Option<u8>, VanillaError> {
        let layout = self
            .containers
            .as_ref()
            .ok_or(VanillaError::Unreadable("container layout"))?;
        let info = (self.read)(item.key_by_hash(self.hashes.item))
            .ok_or(VanillaError::Unreadable("item data"))?;
        let slots = [self.workshops.placed_entity, self.items.pid_entity]
            .into_iter()
            .filter_map(|at| {
                info.get(at..at + 16)
                    .and_then(|bytes| <[u8; 16]>::try_from(bytes).ok())
                    .map(Guid)
                    .filter(|template| template.0 != [0; 16])
            })
            .find_map(|template| {
                let data = (self.read)(template.key_by_hash(self.hashes.template))?;
                container_slots(layout, &data)
            });
        Ok(slots)
    }

    /// The same, with the recipe layout `facts` give, when they give it.
    fn with_recipe_facts(self, facts: &(impl EngineFacts + ?Sized)) -> Self {
        match (
            RecipeLayout::resolve(facts),
            facts.hash(types::RECIPE_REGISTRY_RESOURCE.id()),
        ) {
            (Ok(layout), Ok(hash)) => self.with_recipes(layout, hash),
            _ => self,
        }
    }

    fn recipe_list(&self) -> Result<&Recipes, VanillaError> {
        self.recipe_list
            .get_or_init(|| {
                let (layout, hash) = self.recipes.as_ref()?;
                let registry = (self.read)(RECIPE_REGISTRY.key_by_hash(*hash))?;
                let mut recipes = Recipes::default();
                for (guid, name, output) in super::recipes::list(layout, &registry)? {
                    recipes.names.entry(name).or_default().push(guid);
                    recipes.made.push((guid, output));
                }
                Some(recipes)
            })
            .as_ref()
            .ok_or(VanillaError::Unreadable("recipe registry"))
    }

    /// The vanilla recipe with the debug name `name`, as the recipe registry
    /// lists it.
    ///
    /// # Errors
    ///
    /// [`VanillaError::UnknownRecipe`] with the names that look like it,
    /// [`VanillaError::AmbiguousRecipe`] when several recipes carry it, and
    /// [`VanillaError::Unreadable`] without the registry.
    ///
    /// # Examples
    ///
    /// ```
    /// use enshwick::content::vanilla::Vanilla;
    ///
    /// if let Some(vanilla) = Vanilla::game() {
    ///     let _recipe = vanilla.recipe("Tool_Torch01");
    /// }
    /// ```
    pub fn recipe(&self, name: &str) -> Result<Guid, VanillaError> {
        let names = &self.recipe_list()?.names;
        match names.get(name).map(Vec::as_slice) {
            Some([one]) => Ok(*one),
            Some(several) if !several.is_empty() => Err(VanillaError::AmbiguousRecipe {
                name: name.to_owned(),
                recipes: several.to_vec(),
            }),
            _ => Err(VanillaError::UnknownRecipe {
                name: name.to_owned(),
                near: near(names, name),
            }),
        }
    }

    /// The vanilla recipes that make `item`, in the registry's order; none
    /// when no recipe does.
    ///
    /// # Errors
    ///
    /// [`VanillaError::Unreadable`] without the registry.
    ///
    /// # Examples
    ///
    /// ```
    /// use enshwick::content::vanilla::Vanilla;
    ///
    /// if let Some(vanilla) = Vanilla::game() {
    ///     let torch = vanilla.item("Tool_Torch01")?;
    ///     let _recipes = vanilla.recipes_making(torch)?;
    /// }
    /// # Ok::<(), enshwick::content::vanilla::VanillaError>(())
    /// ```
    pub fn recipes_making(&self, item: Guid) -> Result<Vec<Guid>, VanillaError> {
        Ok(self
            .recipe_list()?
            .made
            .iter()
            .filter(|(_, output)| *output == Some(item))
            .map(|(recipe, _)| *recipe)
            .collect())
    }

    /// The running game's vanilla content, read from its archive through
    /// [`super::game_resource`]; `None` outside the game or when the build
    /// lacks a layout.
    ///
    /// # Examples
    ///
    /// See [`Vanilla`].
    #[must_use]
    pub fn game() -> Option<&'static Self> {
        static GAME: crate::fresh::Fresh<Option<Vanilla>> = crate::fresh::Fresh::new();
        GAME.get_or_init(|| Self::new(&crate::host()?, super::game_resource).ok())
            .as_ref()
    }

    fn names(&self) -> Result<&Names, VanillaError> {
        self.names
            .get_or_init(|| {
                let registry = (self.read)(ITEM_REGISTRY.key_by_hash(self.hashes.item_registry))?;
                registry_names(&self.items, &registry)
            })
            .as_ref()
            .ok_or(VanillaError::Unreadable("item registry"))
    }

    /// The vanilla item with the debug name `name`, as the item registry
    /// lists it, such as `Craftingstation_Workbench`.
    ///
    /// # Errors
    ///
    /// [`VanillaError::Unknown`] with the names that look like it,
    /// [`VanillaError::Ambiguous`] when several items carry it, and
    /// [`VanillaError::Unreadable`] without the registry.
    ///
    /// # Examples
    ///
    /// See [`Vanilla`].
    pub fn item(&self, name: &str) -> Result<Guid, VanillaError> {
        let names = self.names()?;
        match names.get(name).map(Vec::as_slice) {
            Some([one]) => Ok(*one),
            Some(several) if !several.is_empty() => Err(VanillaError::Ambiguous {
                name: name.to_owned(),
                items: several.to_vec(),
            }),
            _ => Err(VanillaError::Unknown {
                name: name.to_owned(),
                near: near(names, name),
            }),
        }
    }

    /// The vanilla crafting station whose item is `item`, to clone with
    /// [`crate::Load::add_workshop`].
    ///
    /// # Errors
    ///
    /// [`VanillaError::NotAStation`] when the game lists no workshop for the
    /// item, the workshop is a survivor's, or the template the item places
    /// lacks the crafting components; [`VanillaError::Unreadable`] when the
    /// game's data does not read.
    ///
    /// # Examples
    ///
    /// See [`Vanilla`].
    pub fn station(&self, item: Guid) -> Result<Station, VanillaError> {
        if item == stations::WORKBENCH.item {
            return Ok(stations::WORKBENCH);
        }
        self.workshop_entry(item)?;
        let info = (self.read)(item.key_by_hash(self.hashes.item))
            .ok_or(VanillaError::Unreadable("item data"))?;
        let at = self.workshops.placed_entity;
        let template = info
            .get(at..at + 16)
            .and_then(|bytes| bytes.try_into().ok())
            .map(Guid)
            .ok_or(VanillaError::NotAStation(item))?;
        let data = (self.read)(template.key_by_hash(self.hashes.template))
            .ok_or(VanillaError::NotAStation(item))?;
        clone_template(&self.workshops, &data, Guid([0xee; 16]))
            .map(|_| Station { item, template })
            .ok_or(VanillaError::NotAStation(item))
    }

    /// The workshop of the vanilla crafting station whose item is `item`,
    /// for recipes made at it.
    ///
    /// # Errors
    ///
    /// As [`Vanilla::station`] for an item without a workshop of its own.
    ///
    /// # Examples
    ///
    /// ```
    /// use enshwick::content::vanilla::Vanilla;
    ///
    /// if let Some(vanilla) = Vanilla::game() {
    ///     let forge = vanilla.item("Prop_Production_T1_Forge")?;
    ///     let _workshop = vanilla.workshop(forge)?;
    /// }
    /// # Ok::<(), enshwick::content::vanilla::VanillaError>(())
    /// ```
    pub fn workshop(&self, item: Guid) -> Result<WorkshopId, VanillaError> {
        let entry = self.workshop_entry(item)?;
        let at = self.workshops.entry_guid;
        entry
            .get(at..at + 16)
            .and_then(|bytes| bytes.try_into().ok())
            .map(|guid| WorkshopId::new(Guid(guid)))
            .ok_or(VanillaError::NotAStation(item))
    }

    /// The workshop registry's entry for the station item `item`, when it is
    /// no survivor's.
    fn workshop_entry(&self, item: Guid) -> Result<Vec<u8>, VanillaError> {
        let registry = (self.read)(WORKSHOP_REGISTRY.key_by_hash(self.hashes.workshop_registry))
            .ok_or(VanillaError::Unreadable("workshop registry"))?;
        let layout = &self.workshops;
        let blob = Blob::new(&registry);
        let (start, count) = blob
            .array(layout.workshops)
            .ok_or(VanillaError::Unreadable("workshop registry"))?;
        (0..usize::try_from(count).unwrap_or(0))
            .map(|i| start + i * layout.entry)
            .find(|&at| {
                blob.read_u32(at + layout.entry_item) == Some(item.fnv1a())
                    && registry.get(at + layout.entry_npc) == Some(&0)
            })
            .and_then(|at| registry.get(at..at + layout.entry))
            .map(<[u8]>::to_vec)
            .ok_or(VanillaError::NotAStation(item))
    }
}

/// The debug names of the item registry `registry`, beside its references.
fn registry_names(layout: &ItemLayout, registry: &[u8]) -> Option<Names> {
    let blob = Blob::new(registry);
    let (refs, count) = blob.array(layout.refs)?;
    let (names, names_count) = blob.array(layout.names)?;
    if names_count != count {
        return None;
    }
    let mut out = Names::new();
    for i in 0..usize::try_from(count).ok()? {
        let guid: [u8; 16] = registry
            .get(refs + i * 16..refs + i * 16 + 16)?
            .try_into()
            .ok()?;
        let (text, len) = blob.array(names + i * 8)?;
        let name = registry.get(text..text + usize::try_from(len).ok()?)?;
        let name = core::str::from_utf8(name).ok()?;
        out.entry(name.to_owned()).or_default().push(Guid(guid));
    }
    Some(out)
}

/// Names in `names` that look like `name`: the same but for case first,
/// then those that hold it, then those a few edits away, ignoring case.
fn near(names: &Names, name: &str) -> Vec<String> {
    let wanted = name.to_ascii_lowercase();
    let mut scored: Vec<(usize, &String)> = names
        .keys()
        .filter_map(|n| {
            let lower = n.to_ascii_lowercase();
            let score = if lower == wanted {
                0
            } else if !wanted.is_empty() && lower.contains(&wanted) {
                1
            } else {
                let edits = strsim::levenshtein(&lower, &wanted);
                if edits > 2 {
                    return None;
                }
                1 + edits
            };
            Some((score, n))
        })
        .collect();
    scored.sort();
    scored
        .into_iter()
        .take(NEAR)
        .map(|(_, n)| n.clone())
        .collect()
}

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

    const HASHES: Hashes = Hashes {
        item: 1,
        item_registry: 2,
        template: 3,
        workshop_registry: 4,
        template_collection: 5,
    };

    /// The item layout of build 1269579, as far as the registry goes.
    pub(crate) const ITEMS: ItemLayout = ItemLayout {
        id: 0,
        object: 4,
        name: 0x48,
        description: 0x68,
        flags: 0x78,
        pid_entity: 0x80,
        ui_values: 0x90,
        icon_image: 0x58,
        ui_value: [0x28, 0, 4, 8, 0x24],
        refs: 0,
        names: 8,
    };

    /// A registry listing `items` with their names.
    pub(crate) fn registry(items: &[(Guid, &str)]) -> Vec<u8> {
        let mut blob = Blob::new(&[0u8; 16]);
        let refs: Vec<(Vec<u8>, Option<usize>)> =
            items.iter().map(|(g, _)| (g.0.to_vec(), None)).collect();
        blob.grow_array(0, 16, 4, &[], &refs).unwrap();
        for (_, name) in items {
            let at = blob.append(name.as_bytes(), 1);
            let first = blob
                .grow_array(8, 8, 4, &[0], &[(vec![0; 8], None)])
                .unwrap();
            let (start, _) = blob.array(8).unwrap();
            let element = start + usize::try_from(first).unwrap() * 8;
            assert!(blob.set_array(element, at, u32::try_from(name.len()).unwrap()));
        }
        blob.into_bytes()
    }

    #[test]
    fn items_are_found_by_name_and_near_names_suggested() {
        let torch = Guid([1; 16]);
        let (one, two) = (Guid([2; 16]), Guid([3; 16]));
        let data = registry(&[
            (torch, "Tool_Torch01"),
            (one, "Twin"),
            (two, "Twin"),
            (Guid([4; 16]), "Material_T2_Wood_Planks"),
            (Guid([5; 16]), "Material_T1_Wood_Logs"),
        ]);
        let names = registry_names(&ITEMS, &data).unwrap();
        assert_eq!(names.get("Tool_Torch01"), Some(&vec![torch]));
        assert_eq!(near(&names, "tool_torch01"), ["Tool_Torch01"]);
        assert_eq!(
            near(&names, "wood"),
            ["Material_T1_Wood_Logs", "Material_T2_Wood_Planks"]
        );
        assert!(near(&names, "nothing").is_empty());
    }

    /// A game with the items `named`, a forge station of its own workshop,
    /// a survivor's workshop and an item that places a plain template.
    pub(crate) fn game(named: &[(Guid, &str)]) -> Vanilla {
        let data = game_data(named);
        Vanilla::with_parts(
            ITEMS,
            super::super::workshops::tests::LAYOUT,
            HASHES,
            move |key| data.get(&key).cloned(),
        )
    }

    /// The recipe registry's type hash in these tests.
    const RECIPE_REGISTRY_HASH: u32 = 5;

    /// The recipe layout of build 1269579, as far as these tests read it.
    const RECIPES: RecipeLayout = RecipeLayout {
        recipes: 8,
        recipe: 0xa8,
        guid: 0,
        id: 0x10,
        workshop_guid: 0x14,
        workshop: 0x24,
        input: 0x28,
        output: 0x30,
        completion: 0x5c,
        relative: [0x28, 0x30, 0x40, 0x78],
        input_size: 48,
        stack_size: 24,
        stack_item: 0x10,
        stack_count: 0x14,
    };

    /// [`game`] with a recipe registry: each recipe's GUID, debug name and
    /// the item it makes.
    pub(crate) fn game_with_recipes(
        named: &[(Guid, &str)],
        recipes: &[(Guid, &str, Guid)],
    ) -> Vanilla {
        let mut blob = Blob::new(&[0u8; 16]);
        let at = blob.append(&vec![0u8; 0xa8 * recipes.len()], 8);
        for (i, (guid, name, output)) in recipes.iter().enumerate() {
            let recipe = at + i * 0xa8;
            let mut stack = vec![0u8; 24];
            stack[..16].copy_from_slice(&output.0);
            let output_at = blob.append(&stack, 8);
            let name_at = blob.append(name.as_bytes(), 1);
            assert!(blob.write(recipe, &guid.0));
            assert!(blob.set_array(recipe + 0x30, output_at, 1));
            assert!(blob.set_array(recipe + 0x78, name_at, u32::try_from(name.len()).unwrap()));
        }
        assert!(blob.set_array(8, at, u32::try_from(recipes.len()).unwrap()));
        let mut data = game_data(named);
        data.insert(
            RECIPE_REGISTRY.key_by_hash(RECIPE_REGISTRY_HASH),
            blob.into_bytes(),
        );
        Vanilla::with_parts(
            ITEMS,
            super::super::workshops::tests::LAYOUT,
            HASHES,
            move |key| data.get(&key).cloned(),
        )
        .with_recipes(RECIPES, RECIPE_REGISTRY_HASH)
    }

    /// [`game`] with the item `chest`, named `name`, which places a
    /// container of `slots` slots.
    pub(crate) fn game_with_chest(chest: Guid, name: &str, slots: u8) -> Vanilla {
        game_with_container(chest, name, slots, 0x3c0)
    }

    /// A game with the backpack `backpack`, named `name`, of `slots` slots
    /// in the template of its own entity.
    pub(crate) fn game_with_backpack(backpack: Guid, name: &str, slots: u8) -> Vanilla {
        game_with_container(backpack, name, slots, ITEMS.pid_entity)
    }

    /// A game with `item`, named `name`, whose template at `at` in its data
    /// holds a container of `slots` slots.
    fn game_with_container(chest: Guid, name: &str, slots: u8, at: usize) -> Vanilla {
        use super::super::containers::tests::{LAYOUT as CONTAINERS, chest as template};

        let placed = Guid([0x77; 16]);
        let mut data = game_data(&[(chest, name)]);
        let mut info = vec![0u8; 0x400];
        info[at..at + 16].copy_from_slice(&placed.0);
        data.insert(chest.key_by_hash(HASHES.item), info);
        data.insert(placed.key_by_hash(HASHES.template), template(slots));
        Vanilla::with_parts(
            ITEMS,
            super::super::workshops::tests::LAYOUT,
            HASHES,
            move |key| data.get(&key).cloned(),
        )
        .with_containers(Some(CONTAINERS))
    }

    /// A game whose templates are the containers `containers`: name and
    /// fill table each.
    pub(crate) fn game_with_tables(containers: &[(&str, Guid)]) -> Vanilla {
        use super::super::loot_tables::tests::{FILL, container};

        let mut data = game_data(&[]);
        let mut guids = Vec::new();
        for (i, (name, table)) in containers.iter().enumerate() {
            let template = Guid([0x40 + u8::try_from(i).unwrap(); 16]);
            data.insert(
                template.key_by_hash(HASHES.template),
                container(name, *table),
            );
            guids.extend_from_slice(&template.0);
        }
        let mut collection = Blob::new(&[0u8; 8]);
        let at = collection.append(&guids, 8);
        assert!(collection.set_array(0, at, u32::try_from(containers.len()).unwrap()));
        data.insert(
            super::super::workshops::TEMPLATE_COLLECTION.key_by_hash(HASHES.template_collection),
            collection.into_bytes(),
        );
        Vanilla::with_parts(
            ITEMS,
            super::super::workshops::tests::LAYOUT,
            HASHES,
            move |key| data.get(&key).cloned(),
        )
        .with_fill_tables(Some(FILL))
    }

    #[test]
    fn a_container_s_loot_table_is_found_by_its_name_with_its_sharers() {
        let (corpses, chest) = (Guid([1; 16]), Guid([2; 16]));
        let vanilla = game_with_tables(&[
            ("LootContainer_Enemy_Corpse_Vukah", corpses),
            ("LootContainer_Enemy_Wildlife_Vuka_Melee", corpses),
            ("LootChest_Gold", chest),
        ]);
        assert_eq!(
            vanilla.loot_table("LootContainer_Enemy_Corpse_Vukah"),
            Ok(LootTable {
                table: corpses,
                containers: 2
            })
        );
        assert_eq!(vanilla.loot_table("LootChest_Gold").unwrap().containers, 1);
        assert!(
            vanilla
                .loot_table("LootChest_Gld")
                .unwrap_err()
                .to_string()
                .contains("near: LootChest_Gold")
        );
    }

    /// The archive of [`game`], by key.
    fn game_data(named: &[(Guid, &str)]) -> std::collections::HashMap<ResourceKey, Vec<u8>> {
        use super::super::workshops::tests::{CLIENT, CRAFTING, INTERACTION, station};

        let (forge, survivor, prop) = (Guid([5; 16]), Guid([6; 16]), Guid([7; 16]));
        let (template, plain, workshop) = (Guid([8; 16]), Guid([9; 16]), Guid([10; 16]));
        let mut workshops = Blob::new(&[0u8; 24]);
        let mut entries = Vec::new();
        for (item, npc) in [(forge, 0u8), (survivor, 1), (prop, 0)] {
            let mut entry = vec![0u8; 56];
            entry[0] = npc;
            entry[4..20].copy_from_slice(&workshop.0);
            entry[28..32].copy_from_slice(&item.fnv1a().to_le_bytes());
            entries.extend_from_slice(&entry);
        }
        let at = workshops.append(&entries, 4);
        assert!(workshops.set_array(8, at, 3));
        let placing = |template: Guid| {
            let mut info = vec![0u8; 0x400];
            info[0x3c0..0x3d0].copy_from_slice(&template.0);
            info
        };
        let (crafting, _) = station(&[(CRAFTING, 20), (INTERACTION, 32), (CLIENT, 16)]);
        let (other, _) = station(&[(0x1234_5678, 24)]);
        let mut data = std::collections::HashMap::new();
        data.insert(
            ITEM_REGISTRY.key_by_hash(HASHES.item_registry),
            registry(named),
        );
        data.insert(
            WORKSHOP_REGISTRY.key_by_hash(HASHES.workshop_registry),
            workshops.into_bytes(),
        );
        for (item, places) in [(forge, template), (survivor, template), (prop, plain)] {
            data.insert(item.key_by_hash(HASHES.item), placing(places));
        }
        data.insert(template.key_by_hash(HASHES.template), crafting.into_bytes());
        data.insert(plain.key_by_hash(HASHES.template), other.into_bytes());
        data
    }

    #[test]
    fn a_chest_s_slots_are_read_from_the_template_it_places() {
        let chest = Guid([1; 16]);
        let vanilla = game_with_chest(chest, "Prop_Storage_24_T1_Box", 24);
        assert_eq!(vanilla.container_slots(chest), Ok(Some(24)));
        assert_eq!(vanilla.container_slots(Guid([7; 16])), Ok(None));
        assert_eq!(
            game(&[]).container_slots(chest),
            Err(VanillaError::Unreadable("container layout"))
        );
    }

    #[test]
    fn a_backpack_s_slots_are_read_from_its_own_entity() {
        let backpack = Guid([2; 16]);
        let vanilla = game_with_backpack(backpack, "Equipment_Backpack_T1", 16);
        assert_eq!(vanilla.container_slots(backpack), Ok(Some(16)));
    }

    #[test]
    fn a_recipe_is_found_by_its_name_and_by_what_it_makes() {
        let (torch, recipe) = (Guid([1; 16]), Guid([3; 16]));
        let vanilla = game_with_recipes(
            &[(torch, "Tool_Torch01")],
            &[(recipe, "Tool_Torch01_T0_PK", torch)],
        );
        assert_eq!(vanilla.recipe("Tool_Torch01_T0_PK"), Ok(recipe));
        assert_eq!(
            vanilla
                .recipe("tool_torch01_t0_pk")
                .unwrap_err()
                .to_string(),
            "no vanilla recipe \"tool_torch01_t0_pk\"; near: Tool_Torch01_T0_PK"
        );
        assert_eq!(vanilla.recipes_making(torch), Ok(vec![recipe]));
        assert_eq!(vanilla.recipes_making(Guid([9; 16])), Ok(Vec::new()));
        assert_eq!(
            game(&[]).recipe("Tool_Torch01_T0_PK"),
            Err(VanillaError::Unreadable("recipe registry"))
        );
    }

    #[test]
    fn a_name_finds_its_item_or_explains_why_not() {
        let torch = Guid([1; 16]);
        let vanilla = game(&[
            (torch, "Tool_Torch01"),
            (Guid([2; 16]), "Twin"),
            (Guid([3; 16]), "Twin"),
        ]);
        assert_eq!(vanilla.item("Tool_Torch01"), Ok(torch));
        let unknown = vanilla.item("torch").unwrap_err();
        assert_eq!(
            unknown.to_string(),
            "no vanilla item \"torch\"; near: Tool_Torch01"
        );
        let ambiguous = vanilla.item("Twin").unwrap_err().to_string();
        assert!(
            ambiguous.starts_with("2 vanilla items are named \"Twin\""),
            "{ambiguous}"
        );
        let empty = Vanilla::with_parts(
            ITEMS,
            super::super::workshops::tests::LAYOUT,
            HASHES,
            |_| None,
        );
        assert_eq!(
            empty.item("Tool_Torch01"),
            Err(VanillaError::Unreadable("item registry"))
        );
    }

    #[test]
    fn only_a_crafting_station_of_its_own_can_be_cloned() {
        let vanilla = game(&[]);
        let station = vanilla.station(Guid([5; 16])).unwrap();
        assert_eq!(station.template, Guid([8; 16]));
        assert_eq!(
            vanilla.workshop(Guid([5; 16])).map(WorkshopId::guid),
            Ok(Guid([10; 16]))
        );
        for (item, why) in [
            (6, "a survivor's"),
            (7, "no crafting components"),
            (11, "no workshop"),
        ] {
            assert_eq!(
                vanilla.station(Guid([item; 16])),
                Err(VanillaError::NotAStation(Guid([item; 16]))),
                "{why}"
            );
        }
        assert_eq!(
            vanilla.station(stations::WORKBENCH.item),
            Ok(stations::WORKBENCH)
        );
    }
}