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
//! New workshops: a crafting station cloned from a vanilla one, with a
//! workshop of its own that recipes can target.
//!
//! A workshop is only an id. A placed station crafts at it because its
//! template's crafting components (the station's own, the server's and the
//! client's side of its menu) carry the id, and recipes name it.
//! The workshop registry maps the id to a name and the station item.

use crate::engine_ids as ids;
use crate::{Load, Off};

use super::items::{self, ItemLayout, NewItem};
use super::recipes::NewRecipe;
use super::{Blob, EngineFacts, Guid, Id, types};

/// The game's workshop registry resource.
pub const WORKSHOP_REGISTRY: Guid = Guid::parse("3baba1c2-bc82-4ab7-b20e-16dec28208af");

/// The game's list of every template.
pub const TEMPLATE_COLLECTION: Guid = Guid::parse("377f61dc-c7b8-4e4f-830f-7d2c3e8b7fd8");

/// Vanilla stations to clone: the station item and the template it places.
pub mod stations {
    use super::{Guid, Station};

    /// The Workbench (`Craftingstation_Workbench`).
    pub const WORKBENCH: Station = Station {
        item: Guid::parse("2f04a05f-697d-489b-a32f-76bb3439f5bc"),
        template: Guid::parse("ebf450c3-fb96-4240-a3be-8ebe0713eccd"),
    };
}

/// A vanilla crafting station: its item and the template the item places.
///
/// # Examples
///
/// ```
/// use enshwick::content::workshops::stations;
///
/// let workbench = stations::WORKBENCH;
/// assert_ne!(workbench.item, workbench.template);
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Station {
    /// The station item.
    pub item: Guid,
    /// The template the item places.
    pub template: Guid,
}

/// A workshop: recipes made at it name its id.
///
/// # Examples
///
/// ```
/// use enshwick::content::Guid;
/// use enshwick::content::workshops::WorkshopId;
///
/// let workbench = WorkshopId::new(Guid::parse("965d3192-0287-49a2-ad51-a716139571a6"));
/// assert_eq!(workbench.id(), 1_302_892_403);
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct WorkshopId(Guid);

impl WorkshopId {
    /// The workshop with GUID `guid`.
    ///
    /// # Examples
    ///
    /// See [`WorkshopId`].
    #[must_use]
    pub const fn new(guid: Guid) -> Self {
        Self(guid)
    }

    /// The workshop's GUID.
    ///
    /// # Examples
    ///
    /// See [`WorkshopId`].
    #[must_use]
    pub const fn guid(self) -> Guid {
        self.0
    }

    /// The game's id for the workshop: [`Guid::fnv1a`] of its GUID.
    ///
    /// # Examples
    ///
    /// See [`WorkshopId`].
    #[must_use]
    pub const fn id(self) -> u32 {
        self.0.fnv1a()
    }
}

/// How the new station is crafted: a copy of the vanilla station's recipe.
///
/// # Examples
///
/// See [`Load::add_workshop`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct StationRecipe {
    /// The recipe's id.
    pub id: Id,
    /// The vanilla recipe's ingredient counts times this.
    pub cost: u32,
}

/// A new workshop for [`Load::add_workshop`].
///
/// Every id is the mod's own and never changes: saves keep the template
/// GUID of each placed station and the item id of each stack.
///
/// # Examples
///
/// See [`Load::add_workshop`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct NewWorkshop {
    /// The vanilla station cloned: what the new one looks like and does.
    pub like: Station,
    /// The new station item.
    pub item: Id,
    /// The new station's template.
    pub template: Id,
    /// The new workshop.
    pub workshop: Id,
    /// The tag of the station's name, which also names the workshop; `None`
    /// keeps the vanilla names.
    pub name: Option<Guid>,
    /// The tag of the station item's description; `None` keeps the vanilla one.
    pub description: Option<Guid>,
    /// How the station is crafted; `None` adds no recipe.
    pub station_recipe: Option<StationRecipe>,
    /// The item's name in the registry's debug list.
    pub debug_name: String,
}

/// Where the fields a workshop edit touches sit on the running build,
/// resolved by the loader.
///
/// # Examples
///
/// See [`clone_template`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct WorkshopLayout {
    /// A template's components.
    pub components: usize,
    /// The hashes of the three crafting component types: the workshop the
    /// entity crafts at, then the server and the client side of its menu.
    pub crafting_types: [u32; 3],
    /// The crafting component's workshop GUID, its id and its size.
    pub crafting: [usize; 3],
    /// The menu's server side: workshop GUID, id and size.
    pub interaction: [usize; 3],
    /// The menu's client side: workshop id and size.
    pub client: [usize; 2],
    /// The template an item places, inside the item data.
    pub placed_entity: usize,
    /// The template collection's list of templates.
    pub templates: usize,
    /// The workshop registry's list of workshops.
    pub workshops: usize,
    /// One workshop entry's size.
    pub entry: usize,
    /// The entry's workshop GUID.
    pub entry_guid: usize,
    /// The entry's workshop id.
    pub entry_id: usize,
    /// The entry's name tag.
    pub entry_name: usize,
    /// The entry's station item id.
    pub entry_item: usize,
    /// The entry's station item GUID.
    pub entry_item_ref: usize,
    /// The entry's flag set for a survivor's workshop.
    pub entry_npc: usize,
}

impl WorkshopLayout {
    /// The layout `facts` give: the running game's through [`Load`], a game
    /// image's in a tool.
    ///
    /// # Errors
    ///
    /// The first [`Off`] a fact returns, when the build lacks it.
    ///
    /// # Examples
    ///
    /// ```
    /// fn init(load: &mut enshwick::Load<'_>) -> Result<(), enshwick::Off> {
    ///     let layout = enshwick::content::workshops::WorkshopLayout::resolve(load)?;
    ///     assert_eq!(layout.entry, 56);
    ///     Ok(())
    /// }
    /// ```
    pub fn resolve(facts: &(impl EngineFacts + ?Sized)) -> Result<Self, Off> {
        let at = |id: &str| facts.offset(id);
        Ok(Self {
            components: at(ids::TEMPLATE_COMPONENTS)?,
            crafting_types: [
                facts.hash(ids::CRAFTING)?,
                facts.hash(ids::CRAFTING_INTERACTION)?,
                facts.hash(ids::CLIENT_CRAFTING_INTERACTION)?,
            ],
            crafting: [
                at(ids::CRAFTING_WORKSHOP)?,
                at(ids::CRAFTING_WORKSHOP_ID)?,
                facts.size(ids::CRAFTING)?,
            ],
            interaction: [
                at(ids::CRAFTING_INTERACTION_WORKSHOP)?,
                at(ids::CRAFTING_INTERACTION_WORKSHOP_ID)?,
                facts.size(ids::CRAFTING_INTERACTION)?,
            ],
            client: [
                at(ids::CLIENT_CRAFTING_INTERACTION_WORKSHOP_ID)?,
                facts.size(ids::CLIENT_CRAFTING_INTERACTION)?,
            ],
            placed_entity: at(ids::ITEM_INFO_PLACED_ENTITY)?,
            templates: at(ids::TEMPLATE_COLLECTION_TEMPLATES)?,
            workshops: at(ids::WORKSHOP_REGISTRY_WORKSHOPS)?,
            entry: facts.size(ids::WORKSHOP)?,
            entry_guid: at(ids::WORKSHOP_GUID)?,
            entry_id: at(ids::WORKSHOP_ID)?,
            entry_name: at(ids::WORKSHOP_NAME)?,
            entry_item: at(ids::WORKSHOP_ITEM)?,
            entry_item_ref: at(ids::WORKSHOP_ITEM_REF)?,
            entry_npc: at(ids::WORKSHOP_NPC)?,
        })
    }
}

/// A `BlobVariant`: type hash, offset from its second word, size.
const VARIANT: usize = 12;
/// A GUID reference in a blob.
const REFERENCE: usize = 16;

/// The station template with its crafting components moved to `workshop`;
/// `None` unless it has all three, each of the reflected size.
///
/// [`Load::add_workshop`] serves it, with [`clone_station`], [`list_template`]
/// and [`list_workshop`]; call them from [`Load::serve`] builders of your own
/// for a station it does not make.
///
/// # Examples
///
/// ```
/// use enshwick::content::types;
/// use enshwick::content::workshops::{NewWorkshop, WorkshopLayout, clone_template};
///
/// fn init(
///     load: &mut enshwick::Load<'_>,
///     new: NewWorkshop,
/// ) -> Result<(), enshwick::Off> {
///     let layout = WorkshopLayout::resolve(load)?;
///     let (template, like, workshop) = (new.template, new.like.template, new.workshop.guid());
///     load.serve(template.key(types::TEMPLATE_RESOURCE)?, like.key(types::TEMPLATE_RESOURCE)?, move |base| {
///         clone_template(&layout, base, workshop)
///     })
/// }
/// ```
#[must_use]
pub fn clone_template(layout: &WorkshopLayout, template: &[u8], workshop: Guid) -> Option<Vec<u8>> {
    let mut blob = Blob::new(template);
    let (start, count) = blob.array(layout.components)?;
    let id = workshop.fnv1a().to_le_bytes();
    let mut patched = [false; 3];
    for variant in (0..usize::try_from(count).ok()?).map(|i| start + i * VARIANT) {
        let hash = blob.read_u32(variant)?;
        let data = (variant + 4).checked_add(usize::try_from(blob.read_u32(variant + 4)?).ok()?)?;
        let size = usize::try_from(blob.read_u32(variant + 8)?).ok()?;
        let Some(slot) = layout.crafting_types.iter().position(|&ty| ty == hash) else {
            continue;
        };
        let [guid_at, id_at, expected] = match slot {
            0 => layout.crafting,
            1 => layout.interaction,
            _ => [usize::MAX, layout.client[0], layout.client[1]],
        };
        if size != expected {
            return None;
        }
        let written = (guid_at == usize::MAX || blob.write(data + guid_at, &workshop.0))
            && blob.write(data + id_at, &id);
        if !written {
            return None;
        }
        patched[slot] = true;
    }
    patched.iter().all(|&p| p).then(|| blob.into_bytes())
}

/// The new station item, cloned from the vanilla station in `like`, placing
/// the new template; `None` when the vanilla item does not place
/// `new.like.template`.
///
/// # Examples
///
/// ```
/// use enshwick::content::items::ItemLayout;
/// use enshwick::content::types;
/// use enshwick::content::workshops::{NewWorkshop, WorkshopLayout, clone_station};
///
/// fn init(
///     load: &mut enshwick::Load<'_>,
///     new: NewWorkshop,
/// ) -> Result<(), enshwick::Off> {
///     let layout = WorkshopLayout::resolve(load)?;
///     let items = ItemLayout::resolve(load)?;
///     let (item, like) = (new.item.key(types::ITEM_INFO)?, new.like.item.key(types::ITEM_INFO)?);
///     load.serve(item, like, move |base| clone_station(&items, &layout, base, &new))
/// }
/// ```
#[must_use]
pub fn clone_station(
    items: &ItemLayout,
    layout: &WorkshopLayout,
    like: &[u8],
    new: &NewWorkshop,
) -> Option<Vec<u8>> {
    let placed = like.get(layout.placed_entity..layout.placed_entity + REFERENCE)?;
    if placed != new.like.template.0 {
        return None;
    }
    let mut item = Blob::new(&items::clone_item(
        items,
        like,
        &item_of(new),
        new.item.guid(),
    )?);
    item.write(layout.placed_entity, &new.template.guid().0)
        .then(|| item.into_bytes())
}

/// The template collection with `template` listed after the others.
///
/// # Examples
///
/// ```
/// use enshwick::content::types;
/// use enshwick::content::workshops::{
///     NewWorkshop, TEMPLATE_COLLECTION, WorkshopLayout, list_template,
/// };
///
/// fn init(
///     load: &mut enshwick::Load<'_>,
///     new: NewWorkshop,
/// ) -> Result<(), enshwick::Off> {
///     let layout = WorkshopLayout::resolve(load)?;
///     let collection = TEMPLATE_COLLECTION.key(types::TEMPLATE_COLLECTION_RESOURCE)?;
///     load.serve(collection, collection, move |base| list_template(&layout, base, new.template.guid()))
/// }
/// ```
#[must_use]
pub fn list_template(
    layout: &WorkshopLayout,
    collection: &[u8],
    template: Guid,
) -> Option<Vec<u8>> {
    let mut blob = Blob::new(collection);
    blob.grow_array(
        layout.templates,
        REFERENCE,
        4,
        &[],
        &[(template.0.to_vec(), None)],
    )?;
    Some(blob.into_bytes())
}

/// The workshop registry with the new workshop after the others: a copy of
/// the vanilla station's entry with the new workshop, item and name.
///
/// # Examples
///
/// ```
/// use enshwick::content::types;
/// use enshwick::content::workshops::{
///     NewWorkshop, WORKSHOP_REGISTRY, WorkshopLayout, list_workshop,
/// };
///
/// fn init(
///     load: &mut enshwick::Load<'_>,
///     new: NewWorkshop,
/// ) -> Result<(), enshwick::Off> {
///     let layout = WorkshopLayout::resolve(load)?;
///     let registry = WORKSHOP_REGISTRY.key(types::WORKSHOP_REGISTRY_RESOURCE)?;
///     load.serve(registry, registry, move |base| list_workshop(&layout, base, &new))
/// }
/// ```
#[must_use]
pub fn list_workshop(
    layout: &WorkshopLayout,
    registry: &[u8],
    new: &NewWorkshop,
) -> Option<Vec<u8>> {
    let mut blob = Blob::new(registry);
    let (start, count) = blob.array(layout.workshops)?;
    let like = new.like.item.fnv1a();
    let vanilla = (0..usize::try_from(count).ok()?)
        .map(|i| start + i * layout.entry)
        .find(|&at| blob.read_u32(at + layout.entry_item) == Some(like))?;
    let mut entry = blob.bytes().get(vanilla..vanilla + layout.entry)?.to_vec();
    let mut put = |at: usize, bytes: &[u8]| {
        entry
            .get_mut(at..at + bytes.len())
            .map(|target| target.copy_from_slice(bytes))
    };
    put(layout.entry_guid, &new.workshop.guid().0)?;
    put(layout.entry_id, &new.workshop.guid().fnv1a().to_le_bytes())?;
    put(
        layout.entry_item,
        &crate::ItemId::from_guid(new.item.guid())
            .get()
            .to_le_bytes(),
    )?;
    put(layout.entry_item_ref, &new.item.guid().0)?;
    if let Some(name) = new.name {
        put(layout.entry_name, &name.fnv1a().to_le_bytes())?;
    }
    blob.grow_array(layout.workshops, layout.entry, 4, &[], &[(entry, None)])?;
    Some(blob.into_bytes())
}

/// The station item as a plain new item.
fn item_of(new: &NewWorkshop) -> NewItem {
    NewItem {
        name: new.name,
        description: new.description,
        debug_name: new.debug_name.clone(),
        ..NewItem::new(new.item, new.like.item)
    }
}

impl Load<'_> {
    /// Adds a crafting station with a workshop of its own, on the server and
    /// the client alike: the vanilla station's template and item cloned, the
    /// template crafting at the new workshop, the item placing the new
    /// template, both listed beside what other mods add, a crafting menu
    /// for the workshop on the client, and optionally a copy of the vanilla
    /// station's recipe that makes the new one. Recipes
    /// target the workshop with [`NewRecipe::workshop`] or
    /// [`Derived::workshop`](super::recipes::Derived::workshop).
    ///
    /// When the mod is removed, the loader serves the vanilla template under
    /// the new one's GUID, so placed stations load as the vanilla station.
    ///
    /// # Errors
    ///
    /// [`Off`] when a layout is not reflected or the loader refuses one of
    /// its ids (see [`Load::declare`]); a station whose
    /// components or item do not match turns the mod off when the game first
    /// reads them.
    ///
    /// # Examples
    ///
    /// ```
    /// use enshwick::content::{Guid, Id};
    /// use enshwick::content::workshops::{NewWorkshop, StationRecipe, stations};
    ///
    /// fn init(load: &mut enshwick::Load<'_>) -> Result<(), enshwick::Off> {
    ///     let bench = load.add_workshop(NewWorkshop {
    ///         like: stations::WORKBENCH,
    ///         item: Id::new("my-mod:bench"),
    ///         template: Id::new("my-mod:bench.template"),
    ///         workshop: Id::new("my-mod:bench.workshop"),
    ///         name: None,
    ///         description: None,
    ///         station_recipe: Some(StationRecipe { id: Id::new("my-mod:bench.recipe"), cost: 1 }),
    ///         debug_name: "Bulk Workbench".into(),
    ///     })?;
    ///     assert_eq!(bench.guid(), Guid::named("my-mod:bench.workshop"));
    ///     Ok(())
    /// }
    /// ```
    pub fn add_workshop(&mut self, new: NewWorkshop) -> Result<WorkshopId, Off> {
        for id in [new.item, new.template, new.workshop] {
            self.declare(id)?;
        }
        let layout = WorkshopLayout::resolve(self)?;
        let item_layout = ItemLayout::resolve(self)?;
        let workshop = WorkshopId::new(new.workshop.guid());
        let (like, template) = (new.like, new.template);
        self.serve(
            template.key(types::TEMPLATE_RESOURCE)?,
            like.template.key(types::TEMPLATE_RESOURCE)?,
            move |base| clone_template(&layout, base, workshop.guid()),
        )?;
        let collection = TEMPLATE_COLLECTION.key(types::TEMPLATE_COLLECTION_RESOURCE)?;
        self.serve(collection, collection, move |base| {
            list_template(&layout, base, template.guid())
        })?;
        let station = new.clone();
        self.serve(
            new.item.key(types::ITEM_INFO)?,
            like.item.key(types::ITEM_INFO)?,
            move |base| clone_station(&item_layout, &layout, base, &station),
        )?;
        let (item, debug_name) = (new.item.guid(), new.debug_name.clone());
        let registry = items::ITEM_REGISTRY.key(types::ITEM_REGISTRY_RESOURCE)?;
        self.serve(registry, registry, move |base| {
            items::list_item(&item_layout, base, item, &debug_name)
        })?;
        let recipe = new.station_recipe;
        let registry = WORKSHOP_REGISTRY.key(types::WORKSHOP_REGISTRY_RESOURCE)?;
        self.serve(registry, registry, move |base| {
            list_workshop(&layout, base, &new)
        })?;
        super::menu::serve(self, move |menu, bundle| {
            super::menu::list_workshop(menu, bundle, workshop)
        })?;
        if let Some(recipe) = recipe {
            self.push_recipe(NewRecipe {
                id: recipe.id,
                like: like.item,
                output: item,
                output_count: 1,
                cost: recipe.cost,
                workshop: None,
            })?;
        }
        Ok(workshop)
    }
}

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

    pub(crate) const LAYOUT: WorkshopLayout = WorkshopLayout {
        components: 16,
        crafting_types: [CRAFTING, INTERACTION, CLIENT],
        crafting: [0, 16, 20],
        interaction: [12, 28, 32],
        client: [12, 16],
        placed_entity: 0x3c0,
        templates: 0,
        workshops: 8,
        entry: 56,
        entry_guid: 4,
        entry_id: 20,
        entry_name: 24,
        entry_item: 28,
        entry_item_ref: 32,
        entry_npc: 0,
    };
    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: 0x38,
    };
    pub(crate) const CRAFTING: u32 = 0xc1;
    pub(crate) const INTERACTION: u32 = 0xc2;
    pub(crate) const CLIENT: u32 = 0xc3;
    const WORKSHOP_ID: Id = Id::new("test:bench.workshop");
    const ITEM_ID: Id = Id::new("test:bench");
    const TEMPLATE_ID: Id = Id::new("test:bench.template");
    const WORKSHOP: Guid = WORKSHOP_ID.guid();
    const ITEM: Guid = ITEM_ID.guid();
    const TEMPLATE: Guid = TEMPLATE_ID.guid();
    const NAME: Guid = Guid::parse("41b222ea-cefa-4774-a040-c43aa9f0b227");
    const OLD: Guid = Guid::parse("965d3192-0287-49a2-ad51-a716139571a6");

    fn new() -> NewWorkshop {
        NewWorkshop {
            like: stations::WORKBENCH,
            item: ITEM_ID,
            template: TEMPLATE_ID,
            workshop: WORKSHOP_ID,
            name: Some(NAME),
            description: None,
            station_recipe: None,
            debug_name: "Bench".into(),
        }
    }

    fn u32_at(bytes: &[u8], at: usize) -> u32 {
        u32::from_le_bytes(bytes[at..at + 4].try_into().unwrap())
    }

    /// A template with a transform-like component and the three crafting
    /// ones, all at the old workshop; returns the blob and each data offset.
    pub(crate) fn station(components: &[(u32, usize)]) -> (Blob, Vec<usize>) {
        let mut blob = Blob::new(&[0u8; 24]);
        let variants = blob.append(&vec![0; components.len() * VARIANT], 4);
        let mut data = Vec::new();
        for (i, &(hash, size)) in components.iter().enumerate() {
            let mut bytes = vec![0xee; size];
            if size >= 20 {
                bytes[..16].copy_from_slice(&OLD.0);
            }
            let at = blob.append(&bytes, 4);
            let variant = variants + i * VARIANT;
            let relative = u32::try_from(at - (variant + 4)).unwrap();
            assert!(blob.write(variant, &hash.to_le_bytes()));
            assert!(blob.write(variant + 4, &relative.to_le_bytes()));
            assert!(blob.write(variant + 8, &u32::try_from(size).unwrap().to_le_bytes()));
            data.push(at);
        }
        let count = u32::try_from(components.len()).unwrap();
        assert!(blob.set_array(16, variants, count));
        (blob, data)
    }

    #[test]
    fn the_template_clone_crafts_at_the_new_workshop_only() {
        let (blob, data) = station(&[
            (0x1234_5678, 24),
            (CRAFTING, 20),
            (INTERACTION, 32),
            (CLIENT, 16),
        ]);
        let clone = clone_template(&LAYOUT, blob.bytes(), WORKSHOP).unwrap();
        let id = WORKSHOP.fnv1a();
        assert_eq!(&clone[data[0]..data[0] + 16], &OLD.0, "others stay");
        assert_eq!(&clone[data[1]..data[1] + 16], &WORKSHOP.0);
        assert_eq!(u32_at(&clone, data[1] + 16), id);
        assert_eq!(&clone[data[2] + 12..data[2] + 28], &WORKSHOP.0);
        assert_eq!(u32_at(&clone, data[2] + 28), id);
        assert_eq!(
            &clone[data[2]..data[2] + 12],
            &blob.bytes()[data[2]..data[2] + 12],
            "props in range and comfort stay"
        );
        assert_eq!(u32_at(&clone, data[3] + 12), id);
        assert_eq!(clone.len(), blob.bytes().len());
    }

    #[test]
    fn a_template_missing_a_component_or_of_another_size_is_refused() {
        let (blob, _) = station(&[(CRAFTING, 20), (INTERACTION, 32)]);
        assert!(clone_template(&LAYOUT, blob.bytes(), WORKSHOP).is_none());
        let (blob, _) = station(&[(CRAFTING, 24), (INTERACTION, 32), (CLIENT, 16)]);
        assert!(clone_template(&LAYOUT, blob.bytes(), WORKSHOP).is_none());
    }

    #[test]
    fn the_station_item_places_the_new_template() {
        let mut bench = vec![0u8; 0x400];
        bench[0x3c0..0x3d0].copy_from_slice(&stations::WORKBENCH.template.0);
        let clone = clone_station(&ITEMS, &LAYOUT, &bench, &new()).unwrap();
        assert_eq!(&clone[..4], &ITEM.fnv1a().to_le_bytes());
        assert_eq!(&clone[0x3c0..0x3d0], &TEMPLATE.0);
        assert_eq!(&clone[0x48..0x58], &NAME.0);
        // An item placing something else is not the station named.
        bench[0x3c0] ^= 1;
        assert!(clone_station(&ITEMS, &LAYOUT, &bench, &new()).is_none());
    }

    #[test]
    fn the_registries_list_the_new_workshop_and_template_after_the_others() {
        let mut blob = Blob::new(&[0u8; 24]);
        let mut entry = vec![0u8; 56];
        entry[4..20].copy_from_slice(&OLD.0);
        entry[20..24].copy_from_slice(&OLD.fnv1a().to_le_bytes());
        entry[24..28].copy_from_slice(&7u32.to_le_bytes());
        entry[28..32].copy_from_slice(&stations::WORKBENCH.item.fnv1a().to_le_bytes());
        entry[48..52].copy_from_slice(&3u32.to_le_bytes());
        let at = blob.append(&entry, 4);
        assert!(blob.set_array(8, at, 1));
        let built = Blob::new(&list_workshop(&LAYOUT, blob.bytes(), &new()).unwrap());
        let (start, count) = built.array(8).unwrap();
        assert_eq!(count, 2);
        let added = &built.bytes()[start + 56..start + 112];
        assert_eq!(&added[4..20], &WORKSHOP.0);
        assert_eq!(u32_at(added, 20), WORKSHOP.fnv1a());
        assert_eq!(u32_at(added, 24), NAME.fnv1a());
        assert_eq!(u32_at(added, 28), ITEM.fnv1a());
        assert_eq!(&added[32..48], &ITEM.0);
        assert_eq!(u32_at(added, 48), 3, "upgrade masks stay");
        assert_eq!(&built.bytes()[start + 4..start + 20], &OLD.0);

        let mut collection = Blob::new(&[0u8; 8]);
        let first = collection.append(&OLD.0, 4);
        assert!(collection.set_array(0, first, 1));
        let listed = Blob::new(&list_template(&LAYOUT, collection.bytes(), TEMPLATE).unwrap());
        let (start, count) = listed.array(0).unwrap();
        assert_eq!(count, 2);
        assert_eq!(&listed.bytes()[start + 16..start + 32], &TEMPLATE.0);
    }

    #[test]
    fn a_registry_without_the_vanilla_station_builds_nothing() {
        let mut blob = Blob::new(&[0u8; 24]);
        assert!(blob.set_array(8, 24, 0));
        assert!(list_workshop(&LAYOUT, blob.bytes(), &new()).is_none());
    }
}