enshwick 1.0.0-alpha.2

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
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
//! Recipes: a vanilla recipe copied for a new output, with its ingredients
//! scaled, or the recipes in the registry changed in place.

use std::sync::Arc;

use super::menu::{self, MenuEntry};
use super::workshops::WorkshopId;
use super::{Blob, DebugName, Guid, Id, types};
use crate::{Load, Off};

/// The most recipes the game itself takes at one workshop; more ends the game
/// with "`SmallDynamicArray` is out of elements" unless the loader lifts the
/// limit (see [`workshop_limit`]).
pub const WORKSHOP_RECIPES: usize = 512;

/// Places at each workshop derived recipes leave free for single ones,
/// which [`Load::add_recipe`] adds, while the game's limit holds.
pub const RESERVED_FOR_SINGLE: usize = 16;

/// The most recipes one workshop takes on the running game: [`usize::MAX`]
/// once the loader has lifted the game's limit, else [`WORKSHOP_RECIPES`],
/// also outside the game. The answer is final once
/// the hooks are armed, before the game first reads the recipe registry.
///
/// # Examples
///
/// ```
/// use enshwick::content::recipes::{WORKSHOP_RECIPES, workshop_limit};
///
/// // Outside the game the limit holds.
/// assert_eq!(workshop_limit(), WORKSHOP_RECIPES);
/// ```
#[must_use]
pub fn workshop_limit() -> usize {
    let Some(host) = crate::host() else {
        return WORKSHOP_RECIPES;
    };
    let api = host.api();
    match (api.workshop_recipes)() {
        u32::MAX => usize::MAX,
        limit => usize::try_from(limit).unwrap_or(WORKSHOP_RECIPES),
    }
}

/// The game's recipe registry resource.
pub const RECIPE_REGISTRY: Guid = Guid::parse("5e57de0f-280c-4559-8191-f02c1ba656e2");

/// A new recipe for [`Load::add_recipe`].
///
/// # Examples
///
/// See [`Load::add_recipe`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct NewRecipe {
    /// The new recipe's id; its game id is [`Id::id`].
    pub id: Id,
    /// The item whose recipe is copied: same workshop, unlock and duration.
    pub like: Guid,
    /// The item the recipe makes.
    pub output: Guid,
    /// How many it makes.
    pub output_count: u32,
    /// The copied recipe's ingredient counts times this.
    pub cost: u32,
    /// The workshop the recipe is made at, such as one from
    /// [`Load::add_workshop`]; `None` keeps the copied recipe's.
    pub workshop: Option<WorkshopId>,
}

/// Where the fields a recipe edit touches sit, from the game's reflection.
///
/// # Examples
///
/// See [`RecipeLayout::resolve`] and [`add_recipe_to`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct RecipeLayout {
    /// `RecipeRegistryResource.recipes`.
    pub recipes: usize,
    /// `RecipeInfo` size.
    pub recipe: usize,
    /// `RecipeInfo.recipeGuid`.
    pub guid: usize,
    /// `RecipeInfo.recipeId`.
    pub id: usize,
    /// `RecipeInfo.workshopGuid`.
    pub workshop_guid: usize,
    /// `RecipeInfo.workshopId`.
    pub workshop: usize,
    /// `RecipeInfo.input`.
    pub input: usize,
    /// `RecipeInfo.output`.
    pub output: usize,
    /// `RecipeInfo.completionRequirementQuery`, whose flag id comes first.
    pub completion: usize,
    /// The array and string headers inside a `RecipeInfo`.
    pub relative: [usize; 4],
    /// `RecipeInputResource` size.
    pub input_size: usize,
    /// `RecipeItemStackResource` size.
    pub stack_size: usize,
    /// `RecipeItemStackResource.item`.
    pub stack_item: usize,
    /// `RecipeItemStackResource.count`.
    pub stack_count: usize,
}

impl RecipeLayout {
    /// The layout on the running build.
    ///
    /// # Errors
    ///
    /// [`Off`] when a field or type is not reflected.
    ///
    /// # Examples
    ///
    /// ```
    /// fn init(load: &mut enshwick::Load<'_>) -> Result<(), enshwick::Off> {
    ///     let layout = enshwick::content::recipes::RecipeLayout::resolve(load)?;
    ///     assert_eq!(layout.recipe, 0xa8);
    ///     Ok(())
    /// }
    /// ```
    pub fn resolve(load: &Load<'_>) -> Result<Self, Off> {
        Self::with_lookup(
            |ty, name| {
                load.field_offset(ty, name)
                    .map(|o| usize::try_from(o).unwrap_or(usize::MAX))
            },
            |ty| load.type_size(ty).map(|s| s as usize),
        )
    }

    /// The layout of a game whose reflection `field` (a type's field offset)
    /// and `size` (a type's size) read, for the loader and for tools that
    /// read a game image rather than run in the game.
    ///
    /// # Errors
    ///
    /// The first [`Off`] a lookup returns.
    ///
    /// # Examples
    ///
    /// ```
    /// use enshwick::Off;
    /// use enshwick::content::recipes::RecipeLayout;
    ///
    /// let none = RecipeLayout::with_lookup(|ty, f| Err(Off::new(format!("{ty}.{f}"))), |_| Ok(0));
    /// assert!(none.is_err());
    /// ```
    pub fn with_lookup(
        field: impl Fn(&str, &str) -> Result<usize, Off>,
        size: impl Fn(&str) -> Result<usize, Off>,
    ) -> Result<Self, Off> {
        let recipe = |name: &str| field("keen::RecipeInfo", name);
        let stack = |name: &str| field("keen::RecipeItemStackResource", name);
        Ok(Self {
            recipes: field("keen::RecipeRegistryResource", "recipes")?,
            recipe: size("keen::RecipeInfo")?,
            guid: recipe("recipeGuid")?,
            id: recipe("recipeId")?,
            workshop_guid: recipe("workshopGuid")?,
            workshop: recipe("workshopId")?,
            input: recipe("input")?,
            output: recipe("output")?,
            completion: recipe("completionRequirementQuery")?,
            relative: [
                recipe("input")?,
                recipe("output")?,
                recipe("requiredProps")?,
                recipe("debugName")?,
            ],
            input_size: size("keen::RecipeInputResource")?,
            stack_size: size("keen::RecipeItemStackResource")?,
            stack_item: stack("item")?,
            stack_count: stack("count")?,
        })
    }
}

/// FNV-1a over `bytes`.
fn fnv1a(bytes: &[u8]) -> u32 {
    bytes.iter().fold(0x811c_9dc5_u32, |hash, &b| {
        (hash ^ u32::from(b)).wrapping_mul(0x0100_0193)
    })
}

/// The recipe registry with `recipe` after the others, unless its workshop
/// already holds `limit` recipes. [`Load::add_recipe`] serves it with
/// [`workshop_limit`]; call it from a [`Load::serve`] builder of your own to
/// combine it with other edits.
///
/// # Examples
///
/// ```
/// use enshwick::content::recipes::{
///     NewRecipe, RECIPE_REGISTRY, RecipeLayout, add_recipe_to, workshop_limit,
/// };
/// use enshwick::content::types;
///
/// fn init(
///     load: &mut enshwick::Load<'_>,
///     recipe: NewRecipe,
/// ) -> Result<(), enshwick::Off> {
///     let layout = RecipeLayout::resolve(load)?;
///     let registry = RECIPE_REGISTRY.key(types::RECIPE_REGISTRY);
///     load.serve(registry, registry, move |base| {
///         add_recipe_to(&layout, base, &recipe, workshop_limit())
///     })
/// }
/// ```
#[must_use]
pub fn add_recipe_to(
    layout: &RecipeLayout,
    registry: &[u8],
    recipe: &NewRecipe,
    limit: usize,
) -> Option<Vec<u8>> {
    let mut registry = Blob::new(registry);
    let (start, count) = registry.array(layout.recipes)?;
    let like = (0..usize::try_from(count).ok()?)
        .map(|i| start + i * layout.recipe)
        .find(|&at| makes(layout, &registry, at, recipe.like))?;
    let workshop = match recipe.workshop {
        Some(target) => target.id(),
        None => registry.read_u32(like + layout.workshop)?,
    };
    if workshop_counts(layout, &registry)?
        .get(&workshop)
        .copied()
        .unwrap_or(0)
        >= limit
    {
        crate::warn!("recipe skipped: workshop {workshop} holds {limit} recipes, the game's most");
        return Some(registry.into_bytes());
    }
    let template = registry.bytes().get(like..like + layout.recipe)?.to_vec();
    let inputs = scaled_inputs(layout, &registry, like, recipe.cost)?;
    let index = registry.grow_array(
        layout.recipes,
        layout.recipe,
        8,
        &layout.relative,
        &[(template, Some(like))],
    )?;
    let (start, _) = registry.array(layout.recipes)?;
    let at = start + usize::try_from(index).ok()? * layout.recipe;
    let id = recipe.id.id().to_le_bytes();
    let mut output = vec![0u8; layout.stack_size];
    output.get_mut(..16)?.copy_from_slice(&recipe.output.0);
    output
        .get_mut(layout.stack_item..layout.stack_item + 4)?
        .copy_from_slice(&recipe.output.id().to_le_bytes());
    output
        .get_mut(layout.stack_count..layout.stack_count + 4)?
        .copy_from_slice(&recipe.output_count.to_le_bytes());
    let input_count = u32::try_from(inputs.len() / layout.input_size.max(1)).ok()?;
    let inputs_at = registry.append(&inputs, 8);
    let output_at = registry.append(&output, 8);
    let written = registry.write(at + layout.guid, &recipe.id.guid().0)
        && registry.write(at + layout.id, &id)
        // The recipe's completion flag is its own id.
        && registry.write(at + layout.completion, &id)
        && registry.set_array(at + layout.input, inputs_at, input_count)
        && registry.set_array(at + layout.output, output_at, 1)
        && recipe
            .workshop
            .is_none_or(|target| retarget(layout, &mut registry, at, target));
    written.then(|| registry.into_bytes())
}

/// Moves the recipe at `at` to `workshop`.
fn retarget(layout: &RecipeLayout, blob: &mut Blob, at: usize, workshop: WorkshopId) -> bool {
    blob.write(at + layout.workshop_guid, &workshop.guid().0)
        && blob.write(at + layout.workshop, &workshop.id().to_le_bytes())
}

/// How many recipes each workshop has.
fn workshop_counts(
    layout: &RecipeLayout,
    blob: &Blob,
) -> Option<std::collections::HashMap<u32, usize>> {
    let (start, count) = blob.array(layout.recipes)?;
    let mut counts = std::collections::HashMap::new();
    for i in 0..usize::try_from(count).ok()? {
        let workshop = blob.read_u32(start + i * layout.recipe + layout.workshop)?;
        *counts.entry(workshop).or_insert(0) += 1;
    }
    Some(counts)
}

/// Whether the recipe at `at` makes `item`.
fn makes(layout: &RecipeLayout, registry: &Blob, at: usize, item: Guid) -> bool {
    let Some((outputs, count)) = registry.array(at + layout.output) else {
        return false;
    };
    (0..count as usize).any(|i| {
        let stack = outputs + i * layout.stack_size;
        registry.bytes().get(stack..stack + 16) == Some(&item.0[..])
    })
}

/// The vanilla recipe registry from the game's archive.
fn vanilla_registry() -> Option<Vec<u8>> {
    super::game_resource(RECIPE_REGISTRY.key(types::RECIPE_REGISTRY))
}

/// The GUIDs of the recipes in `registry`.
fn recipe_guids(layout: &RecipeLayout, registry: &[u8]) -> Option<std::collections::HashSet<Guid>> {
    let blob = Blob::new(registry);
    let (start, count) = blob.array(layout.recipes)?;
    Some(
        (0..usize::try_from(count).ok()?)
            .map(|i| {
                RecipeView {
                    blob: &blob,
                    at: start + i * layout.recipe,
                    layout,
                }
                .guid()
            })
            .collect(),
    )
}

/// The GUID of the first recipe in `registry` that makes `item`.
fn recipe_making(layout: &RecipeLayout, registry: &[u8], item: Guid) -> Option<Guid> {
    let registry = Blob::new(registry);
    let (start, count) = registry.array(layout.recipes)?;
    let at = (0..usize::try_from(count).ok()?)
        .map(|i| start + i * layout.recipe)
        .find(|&at| makes(layout, &registry, at, item))?;
    let view = RecipeView {
        blob: &registry,
        at,
        layout,
    };
    Some(view.guid())
}

/// Where the crafting menu lists `recipe`: after the vanilla recipe it
/// copies.
fn menu_entry(layout: &RecipeLayout, recipe: &NewRecipe) -> MenuEntry {
    MenuEntry {
        recipe: recipe.id.guid(),
        after: vanilla_registry()
            .and_then(|registry| recipe_making(layout, &registry, recipe.like)),
        workshop: recipe.workshop,
    }
}

/// Where the crafting menu lists the copies [`derive_recipes_in`] makes of
/// the recipes in `registry`: each after its original.
fn derived_entries(
    layout: &RecipeLayout,
    registry: &[u8],
    salt: u32,
    choose: &dyn Fn(&RecipeView<'_>) -> Option<Derived>,
) -> Option<Vec<MenuEntry>> {
    let blob = Blob::new(registry);
    let (start, count) = blob.array(layout.recipes)?;
    Some(
        (0..usize::try_from(count).ok()?)
            .filter_map(|i| {
                let view = RecipeView {
                    blob: &blob,
                    at: start + i * layout.recipe,
                    layout,
                };
                let derived = choose(&view)?;
                Some(MenuEntry {
                    recipe: derived_guid(view.guid(), salt),
                    after: Some(view.guid()),
                    workshop: derived.workshop,
                })
            })
            .collect(),
    )
}

/// The recipe's inputs with every count times `cost`; an input's item stack
/// comes first in it.
fn scaled_inputs(layout: &RecipeLayout, registry: &Blob, at: usize, cost: u32) -> Option<Vec<u8>> {
    let (inputs, count) = registry.array(at + layout.input)?;
    let mut bytes = registry
        .bytes()
        .get(inputs..inputs + usize::try_from(count).ok()? * layout.input_size)?
        .to_vec();
    for input in bytes.chunks_mut(layout.input_size.max(1)) {
        let field = input.get_mut(layout.stack_count..layout.stack_count + 4)?;
        let count = u32::from_le_bytes(field.try_into().ok()?);
        field.copy_from_slice(&count.saturating_mul(cost).to_le_bytes());
    }
    Some(bytes)
}

/// A vanilla recipe as [`Load::derive_recipes`] shows it.
///
/// # Examples
///
/// See [`Load::derive_recipes`].
#[derive(Clone, Copy, Debug)]
pub struct RecipeView<'a> {
    blob: &'a Blob,
    at: usize,
    layout: &'a RecipeLayout,
}

impl RecipeView<'_> {
    /// The recipe's GUID.
    ///
    /// # Examples
    ///
    /// See [`Load::derive_recipes`].
    #[must_use]
    pub fn guid(&self) -> Guid {
        let mut guid = [0u8; 16];
        if let Some(bytes) = self
            .blob
            .bytes()
            .get(self.at + self.layout.guid..self.at + self.layout.guid + 16)
        {
            guid.copy_from_slice(bytes);
        }
        Guid(guid)
    }

    /// The recipe's debug name, such as `Block_T2_Metal_Copper_CRAFTING`.
    ///
    /// # Examples
    ///
    /// See [`Load::derive_recipes`].
    #[must_use]
    pub fn debug_name(&self) -> String {
        self.blob
            .array(self.at + self.layout.relative[3])
            .and_then(|(start, len)| self.blob.bytes().get(start..start + len as usize))
            .map(|bytes| String::from_utf8_lossy(bytes).into_owned())
            .unwrap_or_default()
    }

    /// The item the recipe makes and how many.
    ///
    /// # Examples
    ///
    /// See [`Load::derive_recipes`].
    #[must_use]
    pub fn output(&self) -> Option<(Guid, u32)> {
        let (outputs, count) = self.blob.array(self.at + self.layout.output)?;
        if count == 0 {
            return None;
        }
        let mut guid = [0u8; 16];
        guid.copy_from_slice(self.blob.bytes().get(outputs..outputs + 16)?);
        let made = self.blob.read_u32(outputs + self.layout.stack_count)?;
        Some((Guid(guid), made))
    }
}

/// How a derived recipe differs from the vanilla one it copies.
///
/// # Examples
///
/// See [`Load::derive_recipes`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Derived {
    /// The vanilla output count times this.
    pub output: u32,
    /// The vanilla ingredient counts times this.
    pub cost: u32,
    /// The workshop the copy is made at, such as one from
    /// [`Load::add_workshop`]; `None` keeps the vanilla recipe's.
    pub workshop: Option<WorkshopId>,
}

/// A derived recipe's GUID: the vanilla one marked with the mod's salt, so it
/// stays the same across starts and differs between mods.
///
/// # Examples
///
/// ```
/// use enshwick::content::Guid;
/// use enshwick::content::recipes::derived_guid;
///
/// let vanilla = Guid::parse("5e57de0f-280c-4559-8191-f02c1ba656e2");
/// assert_eq!(derived_guid(vanilla, 7), derived_guid(vanilla, 7));
/// assert_ne!(derived_guid(vanilla, 7), derived_guid(vanilla, 8));
/// assert_ne!(derived_guid(vanilla, 7), vanilla);
/// ```
#[must_use]
pub fn derived_guid(base: Guid, salt: u32) -> Guid {
    let mut guid = base.0;
    for (byte, salt) in guid[..4].iter_mut().zip(salt.to_le_bytes()) {
        *byte ^= salt;
    }
    for (byte, salt) in guid[12..]
        .iter_mut()
        .zip(salt.rotate_left(16).to_le_bytes())
    {
        *byte ^= salt;
    }
    Guid(guid)
}

/// The recipe registry with a derived copy after the others for each vanilla
/// recipe `choose` picks. With a workshop `limit` other than [`usize::MAX`],
/// copies stop [`RESERVED_FOR_SINGLE`] short of it. [`Load::derive_recipes`]
/// serves it; `salt` marks the copies as in [`derived_guid`].
///
/// # Examples
///
/// ```
/// use enshwick::content::recipes::{
///     Derived, RECIPE_REGISTRY, RecipeLayout, derive_recipes_in, workshop_limit,
/// };
/// use enshwick::content::types;
///
/// fn init(load: &mut enshwick::Load<'_>) -> Result<(), enshwick::Off> {
///     let layout = RecipeLayout::resolve(load)?;
///     let registry = RECIPE_REGISTRY.key(types::RECIPE_REGISTRY);
///     load.serve(registry, registry, move |base| {
///         derive_recipes_in(&layout, base, 0x5afe, workshop_limit(), &|recipe| {
///             recipe.debug_name().starts_with("Block_").then_some(Derived {
///                 output: 2,
///                 cost: 1,
///                 workshop: None,
///             })
///         })
///     })
/// }
/// ```
#[must_use]
pub fn derive_recipes_in(
    layout: &RecipeLayout,
    registry: &[u8],
    salt: u32,
    limit: usize,
    choose: &dyn Fn(&RecipeView<'_>) -> Option<Derived>,
) -> Option<Vec<u8>> {
    let cap = if limit == usize::MAX {
        limit
    } else {
        limit.saturating_sub(RESERVED_FOR_SINGLE)
    };
    let mut blob = Blob::new(registry);
    let (start, count) = blob.array(layout.recipes)?;
    let mut counts = workshop_counts(layout, &blob)?;
    let mut skipped = 0usize;
    let mut picked: Vec<(usize, Derived, Guid)> = Vec::new();
    for at in (0..usize::try_from(count).ok()?).map(|i| start + i * layout.recipe) {
        let view = RecipeView {
            blob: &blob,
            at,
            layout,
        };
        let Some(derived) = choose(&view) else {
            continue;
        };
        let workshop = match derived.workshop {
            Some(target) => target.id(),
            None => blob.read_u32(at + layout.workshop)?,
        };
        let held = counts.entry(workshop).or_insert(0);
        if *held >= cap {
            skipped += 1;
            continue;
        }
        *held += 1;
        picked.push((at, derived, derived_guid(view.guid(), salt)));
    }
    if skipped > 0 {
        crate::warn!(
            "{skipped} derived recipes skipped: a workshop takes {limit} recipes at most, {RESERVED_FOR_SINGLE} kept for single ones; many recipes belong at a workshop or NPC of the mod's own"
        );
    }
    if picked.is_empty() {
        return Some(blob.into_bytes());
    }
    let extra: Vec<(Vec<u8>, Option<usize>)> = picked
        .iter()
        .map(|&(at, _, _)| Some((blob.bytes().get(at..at + layout.recipe)?.to_vec(), Some(at))))
        .collect::<Option<_>>()?;
    let mut changes = Vec::with_capacity(picked.len());
    for &(at, derived, _) in &picked {
        let inputs = scaled_inputs(layout, &blob, at, derived.cost)?;
        let (outputs, _) = blob.array(at + layout.output)?;
        let mut output = blob
            .bytes()
            .get(outputs..outputs + layout.stack_size)?
            .to_vec();
        let count_field = output.get_mut(layout.stack_count..layout.stack_count + 4)?;
        let made = u32::from_le_bytes(count_field.try_into().ok()?);
        count_field.copy_from_slice(&made.saturating_mul(derived.output).to_le_bytes());
        changes.push((inputs, output));
    }
    let first = blob.grow_array(layout.recipes, layout.recipe, 8, &layout.relative, &extra)?;
    let (start, _) = blob.array(layout.recipes)?;
    for (index, ((_, derived, guid), (inputs, output))) in picked.iter().zip(changes).enumerate() {
        let derived = *derived;
        let at = start + (usize::try_from(first).ok()? + index) * layout.recipe;
        let id = guid.id().to_le_bytes();
        let input_count = u32::try_from(inputs.len() / layout.input_size.max(1)).ok()?;
        let inputs_at = blob.append(&inputs, 8);
        let output_at = blob.append(&output, 8);
        let written = blob.write(at + layout.guid, &guid.0)
            && blob.write(at + layout.id, &id)
            && blob.write(at + layout.completion, &id)
            && blob.set_array(at + layout.input, inputs_at, input_count)
            && blob.set_array(at + layout.output, output_at, 1)
            && derived
                .workshop
                .is_none_or(|target| retarget(layout, &mut blob, at, target));
        if !written {
            return None;
        }
    }
    Some(blob.into_bytes())
}

/// A recipe in the registry as [`Load::modify_recipes`] shows it, with its
/// counts open to change in place.
///
/// # Examples
///
/// See [`Load::modify_recipes`].
#[derive(Debug)]
pub struct RecipeEdit<'a> {
    blob: &'a mut Blob,
    at: usize,
    layout: &'a RecipeLayout,
    changed: bool,
}

impl RecipeEdit<'_> {
    /// The recipe as it reads now: GUID, debug name and output.
    ///
    /// # Examples
    ///
    /// See [`Load::modify_recipes`].
    #[must_use]
    pub fn view(&self) -> RecipeView<'_> {
        RecipeView {
            blob: self.blob,
            at: self.at,
            layout: self.layout,
        }
    }

    /// Multiplies the count of each item the recipe makes by `by`.
    ///
    /// # Examples
    ///
    /// See [`Load::modify_recipes`].
    pub fn scale_output(&mut self, by: u32) {
        self.scale(self.layout.output, self.layout.stack_size, by);
    }

    /// Multiplies the count of each ingredient by `by`.
    ///
    /// # Examples
    ///
    /// See [`Load::modify_recipes`].
    pub fn scale_inputs(&mut self, by: u32) {
        self.scale(self.layout.input, self.layout.input_size, by);
    }

    /// Multiplies the stack counts of the array at `field`, whose elements
    /// are `size` bytes and start with an item stack.
    fn scale(&mut self, field: usize, size: usize, by: u32) {
        let Some((start, count)) = self.blob.array(self.at + field) else {
            return;
        };
        for i in 0..count as usize {
            let at = start + i * size + self.layout.stack_count;
            let Some(made) = self.blob.read_u32(at) else {
                return;
            };
            let scaled = made.saturating_mul(by);
            if scaled != made && self.blob.write(at, &scaled.to_le_bytes()) {
                self.changed = true;
            }
        }
    }
}

/// The recipe registry with `modify` called on each recipe in turn; the
/// second value is how many recipes it changed. [`Load::modify_recipes`]
/// serves it.
///
/// # Examples
///
/// ```
/// use enshwick::content::recipes::{RECIPE_REGISTRY, RecipeLayout, modify_recipes_in};
/// use enshwick::content::types;
///
/// fn init(load: &mut enshwick::Load<'_>) -> Result<(), enshwick::Off> {
///     let layout = RecipeLayout::resolve(load)?;
///     let registry = RECIPE_REGISTRY.key(types::RECIPE_REGISTRY);
///     load.serve(registry, registry, move |base| {
///         let (built, changed) = modify_recipes_in(&layout, base, &|recipe| recipe.scale_output(2))?;
///         enshwick::info!("{changed} recipes doubled");
///         Some(built)
///     })
/// }
/// ```
#[must_use]
pub fn modify_recipes_in(
    layout: &RecipeLayout,
    registry: &[u8],
    modify: &dyn Fn(&mut RecipeEdit<'_>),
) -> Option<(Vec<u8>, usize)> {
    let mut blob = Blob::new(registry);
    let (start, count) = blob.array(layout.recipes)?;
    let mut changed = 0;
    for at in (0..usize::try_from(count).ok()?).map(|i| start + i * layout.recipe) {
        let mut edit = RecipeEdit {
            blob: &mut blob,
            at,
            layout,
            changed: false,
        };
        modify(&mut edit);
        changed += usize::from(edit.changed);
    }
    Some((blob.into_bytes(), changed))
}

impl Load<'_> {
    /// Adds a recipe to the game, on the server and the client alike: a copy
    /// of the recipe that makes `like`, at the same workshop and unlocked with
    /// it, making `output` instead, beside recipes other mods add. The
    /// client's crafting menu lists it right after the copied recipe (see
    /// [`menu`](super::menu)).
    ///
    /// # Errors
    ///
    /// [`Off`] when the recipe layout is not reflected or the loader
    /// refuses the recipe's id (see
    /// [`Load::declare`]); a `like` with no recipe turns the mod off when the
    /// game first reads the registry.
    ///
    /// # Examples
    ///
    /// ```
    /// use enshwick::content::{Guid, Id};
    /// use enshwick::content::recipes::NewRecipe;
    ///
    /// fn init(load: &mut enshwick::Load<'_>) -> Result<(), enshwick::Off> {
    ///     load.add_recipe(NewRecipe {
    ///         id: Id::new("my-mod:safe.recipe"),
    ///         like: Guid::parse("6943053a-32c1-4718-ae22-e61427ddf54d"),
    ///         output: Guid::named("my-mod:safe"),
    ///         output_count: 1,
    ///         cost: 2,
    ///         workshop: None,
    ///     })
    /// }
    /// ```
    pub fn add_recipe(&mut self, recipe: NewRecipe) -> Result<(), Off> {
        self.declare(recipe.id)?;
        let layout = RecipeLayout::resolve(self)?;
        let registry = RECIPE_REGISTRY.key(types::RECIPE_REGISTRY);
        self.serve(registry, registry, move |base| {
            add_recipe_to(&layout, base, &recipe, workshop_limit())
        })?;
        menu::serve(self, move |menu, bundle| {
            menu::list_recipes(menu, bundle, &[menu_entry(&layout, &recipe)])
        })
    }

    /// Adds a recipe as [`add_recipe`](Self::add_recipe) does, asking
    /// `recipe` for it each time the registry is built, so a cost read from
    /// settings that change, such as a world's or a server's join values,
    /// applies through [`rebuild_recipes`]. Every answer keeps the id of the
    /// first.
    ///
    /// # Errors
    ///
    /// As for [`add_recipe`](Self::add_recipe).
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::atomic::{AtomicU32, Ordering};
    ///
    /// use enshwick::content::{Guid, Id};
    /// use enshwick::content::recipes::NewRecipe;
    ///
    /// static COST: AtomicU32 = AtomicU32::new(2);
    ///
    /// fn init(load: &mut enshwick::Load<'_>) -> Result<(), enshwick::Off> {
    ///     load.add_recipe_with(|| NewRecipe {
    ///         id: Id::new("my-mod:safe.recipe"),
    ///         like: Guid::parse("6943053a-32c1-4718-ae22-e61427ddf54d"),
    ///         output: Guid::named("my-mod:safe"),
    ///         output_count: 1,
    ///         cost: COST.load(Ordering::Relaxed),
    ///         workshop: None,
    ///     })
    /// }
    /// ```
    pub fn add_recipe_with(
        &mut self,
        recipe: impl Fn() -> NewRecipe + Send + Sync + 'static,
    ) -> Result<(), Off> {
        let id = recipe().id;
        self.declare(id)?;
        let layout = RecipeLayout::resolve(self)?;
        let registry = RECIPE_REGISTRY.key(types::RECIPE_REGISTRY);
        let recipe = Arc::new(recipe);
        let built = Arc::clone(&recipe);
        self.serve(registry, registry, move |base| {
            let recipe = NewRecipe { id, ..built() };
            add_recipe_to(&layout, base, &recipe, workshop_limit())
        })?;
        self.allow_rebuild(registry)?;
        menu::serve(self, move |menu, bundle| {
            let recipe = NewRecipe { id, ..recipe() };
            menu::list_recipes(menu, bundle, &[menu_entry(&layout, &recipe)])
        })
    }

    /// Adds a derived copy of each vanilla recipe `choose` picks: same
    /// workshop and unlock, its output and cost scaled as [`Derived`] says,
    /// beside the original, in the registry and in the client's crafting
    /// menu. `choose` sees only the game's own recipes, never those mods
    /// add. `salt` keeps the copies' GUIDs apart from other mods'; use the
    /// mod id.
    ///
    /// # Errors
    ///
    /// [`Off`] when the recipe layout is not reflected.
    ///
    /// # Examples
    ///
    /// ```
    /// use enshwick::content::recipes::Derived;
    ///
    /// fn init(load: &mut enshwick::Load<'_>) -> Result<(), enshwick::Off> {
    ///     load.derive_recipes("my-mod", |recipe| {
    ///         recipe
    ///             .debug_name()
    ///             .starts_with("Block_")
    ///             .then_some(Derived { output: 2, cost: 1, workshop: None })
    ///     })
    /// }
    /// ```
    pub fn derive_recipes(
        &mut self,
        salt: &str,
        choose: impl Fn(&RecipeView<'_>) -> Option<Derived> + Send + Sync + 'static,
    ) -> Result<(), Off> {
        let layout = RecipeLayout::resolve(self)?;
        let salt = fnv1a(salt.as_bytes());
        let registry = RECIPE_REGISTRY.key(types::RECIPE_REGISTRY);
        let choose = Arc::new(choose);
        let chosen = Arc::clone(&choose);
        self.serve(registry, registry, move |base| {
            let vanilla =
                vanilla_registry().and_then(|registry| recipe_guids(&layout, &registry));
            if vanilla.is_none() {
                crate::warn!(
                    "derived recipes may copy recipes of other mods: the game's recipe registry does not read"
                );
            }
            derive_recipes_in(&layout, base, salt, workshop_limit(), &|view| {
                let added = vanilla
                    .as_ref()
                    .is_some_and(|vanilla| !vanilla.contains(&view.guid()));
                if added { None } else { chosen(view) }
            })
        })?;
        menu::serve(self, move |menu, bundle| {
            let entries = vanilla_registry()
                .and_then(|registry| derived_entries(&layout, &registry, salt, &*choose));
            let Some(entries) = entries else {
                crate::warn!(
                    "derived recipes stay out of the crafting menu: the recipe registry does not read"
                );
                return Some(bundle.to_vec());
            };
            menu::list_recipes(menu, bundle, &entries)
        })
    }

    /// Changes recipes in the registry in place, on the server and the
    /// client alike, so the client's crafting menu shows the new counts:
    /// `modify` is called with each recipe and may scale its output and
    /// ingredient counts. It sees the registry as it reaches this patch,
    /// with the recipes and changes of mods that patched before, and the
    /// mods after see its changes. The mod's log says how many recipes
    /// changed. When values `modify` reads change later, such as a server's
    /// join values, [`rebuild_recipes`] applies them.
    ///
    /// # Errors
    ///
    /// [`Off`] when the recipe layout is not reflected.
    ///
    /// # Examples
    ///
    /// ```
    /// use enshwick::content::recipes::RecipeEdit;
    ///
    /// fn init(load: &mut enshwick::Load<'_>) -> Result<(), enshwick::Off> {
    ///     load.modify_recipes(|recipe: &mut RecipeEdit<'_>| {
    ///         if recipe.view().debug_name().starts_with("Block_") {
    ///             recipe.scale_output(2);
    ///         }
    ///     })
    /// }
    /// ```
    pub fn modify_recipes(
        &mut self,
        modify: impl Fn(&mut RecipeEdit<'_>) + Send + Sync + 'static,
    ) -> Result<(), Off> {
        let layout = RecipeLayout::resolve(self)?;
        let registry = RECIPE_REGISTRY.key(types::RECIPE_REGISTRY);
        self.serve(registry, registry, move |base| {
            let (built, changed) = modify_recipes_in(&layout, base, &modify)?;
            crate::info!("{changed} recipes changed");
            Some(built)
        })?;
        self.allow_rebuild(registry)
    }
}

/// Builds the recipe registry again with every mod's recipe changes, from
/// any thread, for a mod whose [`Load::modify_recipes`] or
/// [`Load::add_recipe_with`] reads values that changed, such as a server's
/// join values on a joined client: the counts the game holds change in place. Nothing is done while the game has not
/// built the registry yet. See [`rebuild`](crate::content::rebuild) for
/// what a rebuild can change.
///
/// # Errors
///
/// [`Off`] for a mod that neither modifies recipes nor adds them with
/// [`Load::add_recipe_with`], and when another mod's patch changed the
/// registry's length.
///
/// # Examples
///
/// ```
/// fn settings_changed() {
///     if let Err(off) = enshwick::content::recipes::rebuild_recipes() {
///         enshwick::warn!("recipe counts change at the next start: {off}");
///     }
/// }
/// ```
pub fn rebuild_recipes() -> Result<(), Off> {
    crate::content::rebuild(RECIPE_REGISTRY.key(types::RECIPE_REGISTRY))
}

/// A recipe, an item or a workshop item as a recipe rule names it: by GUID,
/// by content id, or by the debug name the loader resolves against the
/// registry.
///
/// # Examples
///
/// ```
/// use enshwick::content::recipes::Name;
/// use enshwick::content::{DebugName, Guid, Id};
///
/// let by_guid = Name::from(Guid::parse("7fa62007-a38e-4790-8591-873055fc3f34"));
/// let by_id = Name::from(Id::new("safes:safe.recipe"));
/// let by_debug = Name::from(DebugName("Tool_Torch01_T0_PK"));
/// assert_ne!(by_guid, by_id);
/// assert_ne!(by_id, by_debug);
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Name<'a> {
    /// A GUID, such as a vanilla recipe's.
    Guid(Guid),
    /// A mod's content id.
    Content(Id),
    /// A debug name, such as `Tool_Torch01_T0_PK`.
    Debug(DebugName<'a>),
}

impl From<Guid> for Name<'_> {
    fn from(guid: Guid) -> Self {
        Self::Guid(guid)
    }
}

impl From<Id> for Name<'_> {
    fn from(id: Id) -> Self {
        Self::Content(id)
    }
}

impl<'a> From<DebugName<'a>> for Name<'a> {
    fn from(name: DebugName<'a>) -> Self {
        Self::Debug(name)
    }
}

impl Name<'_> {
    /// The name as the loader's recipe file writes it.
    fn text(self) -> std::borrow::Cow<'static, str> {
        match self {
            Self::Guid(guid) => guid.to_string().into(),
            Self::Content(id) => id.name().into(),
            Self::Debug(name) => name.0.to_owned().into(),
        }
    }
}

/// What a recipe rule disables, in the forms the loader's recipe file
/// takes.
///
/// # Examples
///
/// See [`disable`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum RecipeRule<'a> {
    /// One recipe.
    Recipe(Name<'a>),
    /// Every recipe that makes this item.
    Output(Name<'a>),
    /// Every recipe made at the workshop of this item, such as
    /// `Craftingstation_Workbench` or a survivor's `NPC_Crafter_Blacksmith01`.
    Workshop(Name<'a>),
    /// Every recipe crafted by hand.
    Hand,
}

impl<'a> RecipeRule<'a> {
    /// The rule for one recipe.
    ///
    /// # Examples
    ///
    /// ```
    /// use enshwick::content::Id;
    /// use enshwick::content::recipes::{Name, RecipeRule};
    ///
    /// const SAFE_RECIPE: Id = Id::new("safes:safe.recipe");
    /// assert_eq!(RecipeRule::recipe(SAFE_RECIPE), RecipeRule::Recipe(Name::Content(SAFE_RECIPE)));
    /// ```
    #[must_use]
    pub fn recipe(name: impl Into<Name<'a>>) -> Self {
        Self::Recipe(name.into())
    }

    /// The rule for every recipe that makes an item.
    ///
    /// # Examples
    ///
    /// ```
    /// use enshwick::content::DebugName;
    /// use enshwick::content::recipes::RecipeRule;
    ///
    /// let torches = RecipeRule::output(DebugName("Tool_Torch01_T0"));
    /// # let _ = torches;
    /// ```
    #[must_use]
    pub fn output(item: impl Into<Name<'a>>) -> Self {
        Self::Output(item.into())
    }

    /// The rule for every recipe made at the workshop of an item.
    ///
    /// # Examples
    ///
    /// ```
    /// use enshwick::content::DebugName;
    /// use enshwick::content::recipes::RecipeRule;
    ///
    /// let workbench = RecipeRule::workshop(DebugName("Craftingstation_Workbench"));
    /// # let _ = workbench;
    /// ```
    #[must_use]
    pub fn workshop(item: impl Into<Name<'a>>) -> Self {
        Self::Workshop(item.into())
    }

    /// The rule's kind, its kind in words and the name it carries.
    fn parts(
        self,
    ) -> (
        crate::abi::RecipeRuleKind,
        &'static str,
        std::borrow::Cow<'static, str>,
    ) {
        use crate::abi::RecipeRuleKind;
        match self {
            Self::Recipe(name) => (RecipeRuleKind::RECIPE, "recipe", name.text()),
            Self::Output(name) => (RecipeRuleKind::OUTPUT, "output", name.text()),
            Self::Workshop(name) => (RecipeRuleKind::WORKSHOP, "workshop", name.text()),
            Self::Hand => (RecipeRuleKind::WORKSHOP, "workshop", "hand".into()),
        }
    }
}

fn rule(rule: RecipeRule<'_>, disable: bool) -> Result<(), Off> {
    let host = crate::host().ok_or_else(|| Off::new("recipe rules: no loader"))?;
    let api = host.api();
    let (kind, what, name) = rule.parts();
    if name.trim().is_empty() {
        return Err(Off::new(format!("recipe rule {what}: no name")));
    }
    let status = (api.recipe_rule)(
        host.handle(),
        kind,
        crate::abi::Str::new(&name),
        u32::from(disable),
    );
    crate::load::ok(status, (), || format!("recipe rule {what} {name:?}"))
}

/// Disables recipes in the whole game while the mod runs: they leave every
/// crafting menu, and the server refuses to craft them. On the server and in
/// single player, the server's rules sync to the players who join. The
/// loader resolves the name against the recipe registry and logs one it
/// cannot resolve in the mod's log; the server's recipe file
/// (`mod-configs/enshwick.recipes.toml`) wins over every mod's rules. Call it
/// at any time, from any thread; it applies within a second.
///
/// # Errors
///
/// [`Off`] outside the game, or for an empty debug name.
///
/// # Examples
///
/// ```
/// use enshwick::content::DebugName;
/// use enshwick::content::recipes::{RecipeRule, disable, enable};
///
/// fn init(_load: &mut enshwick::Load<'_>) -> Result<(), enshwick::Off> {
///     disable(RecipeRule::output(DebugName("Tool_Torch01_T0")))?;
///     disable(RecipeRule::Hand)?;
///     enable(RecipeRule::Hand)
/// }
/// ```
pub fn disable(rule: RecipeRule<'_>) -> Result<(), Off> {
    self::rule(rule, true)
}

/// Takes back the mod's own [`disable`] of `rule`; another mod's rules and
/// the server's recipe file stay as they are.
///
/// # Errors
///
/// As [`disable`].
///
/// # Examples
///
/// See [`disable`].
pub fn enable(rule: RecipeRule<'_>) -> Result<(), Off> {
    self::rule(rule, false)
}

/// Whether the recipe `recipe`, a GUID or a content id, is disabled in this
/// process now, by the server's recipe file or a mod's rule; on a client
/// joined to a server, by the server's. `false` outside the game.
///
/// # Examples
///
/// ```
/// use enshwick::content::{Guid, Id};
/// use enshwick::content::recipes::is_disabled;
///
/// let torch = Guid::parse("7fa62007-a38e-4790-8591-873055fc3f34");
/// assert!(!is_disabled(torch));
/// assert!(!is_disabled(Id::new("safes:safe.recipe")));
/// ```
#[must_use]
pub fn is_disabled(recipe: impl Into<Guid>) -> bool {
    let Some(host) = crate::host() else {
        return false;
    };
    let api = host.api();
    let mut out = 0u32;
    (api.recipe_disabled)(host.handle(), recipe.into().id(), &raw mut out).is_ok() && out != 0
}

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

    const LAYOUT: 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,
    };
    const CHEST: Guid = Guid::parse("6943053a-32c1-4718-ae22-e61427ddf54d");
    const SAFE: Guid = Guid::parse("8a3f6e21-5c4b-4d7e-9f10-2b7c5e6a9d31");
    const RECIPE_ID: Id = Id::new("test:recipe");
    const RECIPE: Guid = RECIPE_ID.guid();

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

    #[test]
    fn the_copy_costs_more_and_makes_the_new_output() {
        let mut blob = Blob::new(&[0u8; 16]);
        let recipe = blob.append(&[0; 0xa8], 8);
        let mut input = vec![0u8; 48];
        input[0x14..0x18].copy_from_slice(&5u32.to_le_bytes());
        let input_at = blob.append(&input, 8);
        let mut output = vec![0u8; 24];
        output[..16].copy_from_slice(&CHEST.0);
        let output_at = blob.append(&output, 8);
        let name_at = blob.append(b"Chest\0", 1);
        assert!(blob.set_array(recipe + 0x28, input_at, 1));
        assert!(blob.set_array(recipe + 0x30, output_at, 1));
        assert!(blob.set_array(recipe + 0x78, name_at, 5));
        assert!(blob.set_array(8, recipe, 1));

        let new = NewRecipe {
            id: RECIPE_ID,
            like: CHEST,
            output: SAFE,
            output_count: 1,
            cost: 2,
            workshop: None,
        };
        let built =
            Blob::new(&add_recipe_to(&LAYOUT, blob.bytes(), &new, WORKSHOP_RECIPES).unwrap());
        let (recipes, count) = built.array(8).unwrap();
        assert_eq!(count, 2);
        let copy = recipes + 0xa8;
        assert_eq!(&built.bytes()[copy..copy + 16], &RECIPE.0);
        assert_eq!(u32_at(built.bytes(), copy + 0x10), RECIPE.id());
        assert_eq!(u32_at(built.bytes(), copy + 0x5c), RECIPE.id());
        let (inputs, _) = built.array(copy + 0x28).unwrap();
        assert_eq!(u32_at(built.bytes(), inputs + 0x14), 10);
        let (outputs, _) = built.array(copy + 0x30).unwrap();
        assert_eq!(&built.bytes()[outputs..outputs + 16], &SAFE.0);
        assert_eq!(u32_at(built.bytes(), outputs + 0x10), SAFE.id());
        let (name, len) = built.array(copy + 0x78).unwrap();
        assert_eq!(&built.bytes()[name..name + len as usize], b"Chest");
        let (inputs, _) = built.array(recipes + 0x28).unwrap();
        assert_eq!(u32_at(built.bytes(), inputs + 0x14), 5);
    }

    #[test]
    fn derived_copies_double_the_output_of_the_chosen_recipes_only() {
        let mut blob = Blob::new(&[0u8; 16]);
        let first = blob.append(&[0; 0xa8 * 2], 8);
        for (i, (name, made)) in [(&b"Block_A\0"[..], 100u32), (&b"Prop_B\0"[..], 1)]
            .iter()
            .enumerate()
        {
            let at = first + i * 0xa8;
            let mut output = vec![0u8; 24];
            output[0x14..0x18].copy_from_slice(&made.to_le_bytes());
            let output_at = blob.append(&output, 8);
            let name_at = blob.append(name, 1);
            assert!(blob.set_array(at + 0x30, output_at, 1));
            assert!(blob.set_array(at + 0x78, name_at, u32::try_from(name.len() - 1).unwrap()));
        }
        assert!(blob.set_array(8, first, 2));
        let built = derive_recipes_in(&LAYOUT, blob.bytes(), 7, WORKSHOP_RECIPES, &|r| {
            r.debug_name().starts_with("Block_").then_some(Derived {
                output: 2,
                cost: 1,
                workshop: None,
            })
        })
        .unwrap();
        let built = Blob::new(&built);
        let (recipes, count) = built.array(8).unwrap();
        assert_eq!(count, 3);
        let copy = RecipeView {
            blob: &built,
            at: recipes + 2 * 0xa8,
            layout: &LAYOUT,
        };
        assert_eq!(copy.debug_name(), "Block_A");
        assert_eq!(copy.output().unwrap().1, 200);
        assert_eq!(copy.guid(), derived_guid(Guid([0; 16]), 7));
        let original = RecipeView {
            blob: &built,
            at: recipes,
            layout: &LAYOUT,
        };
        assert_eq!(original.output().unwrap().1, 100);
    }

    #[test]
    fn a_recipe_can_move_to_another_workshop() {
        let mut blob = Blob::new(&[0u8; 16]);
        let recipe = blob.append(&[0; 0xa8], 8);
        assert!(blob.write(recipe + 0x24, &7u32.to_le_bytes()));
        let mut output = vec![0u8; 24];
        output[..16].copy_from_slice(&CHEST.0);
        let output_at = blob.append(&output, 8);
        assert!(blob.set_array(recipe + 0x30, output_at, 1));
        assert!(blob.set_array(8, recipe, 1));
        let bench = WorkshopId::new(Guid::parse("5b828914-9b48-40f8-b541-72e9b942cee6"));
        let new = NewRecipe {
            id: RECIPE_ID,
            like: CHEST,
            output: SAFE,
            output_count: 1,
            cost: 1,
            workshop: Some(bench),
        };
        let built = add_recipe_to(&LAYOUT, blob.bytes(), &new, WORKSHOP_RECIPES).unwrap();
        let built = Blob::new(&built);
        let (recipes, _) = built.array(8).unwrap();
        let copy = recipes + 0xa8;
        assert_eq!(&built.bytes()[copy + 0x14..copy + 0x24], &bench.guid().0);
        assert_eq!(u32_at(built.bytes(), copy + 0x24), bench.id());
        assert_eq!(u32_at(built.bytes(), recipes + 0x24), 7);

        // Derived copies move too, and count against the new workshop.
        let derived = derive_recipes_in(&LAYOUT, blob.bytes(), 7, 1, &|_| {
            Some(Derived {
                output: 2,
                cost: 1,
                workshop: Some(bench),
            })
        })
        .unwrap();
        assert_eq!(
            Blob::new(&derived).array(8).unwrap().1,
            1,
            "limit 1, held 0"
        );
        let derived = derive_recipes_in(&LAYOUT, blob.bytes(), 7, RESERVED_FOR_SINGLE + 1, &|_| {
            Some(Derived {
                output: 2,
                cost: 1,
                workshop: Some(bench),
            })
        })
        .unwrap();
        let derived = Blob::new(&derived);
        let (recipes, count) = derived.array(8).unwrap();
        assert_eq!(count, 2);
        assert_eq!(u32_at(derived.bytes(), recipes + 0xa8 + 0x24), bench.id());
    }

    #[test]
    fn modified_recipes_change_in_place_and_stay_one_each() {
        let mut blob = Blob::new(&[0u8; 16]);
        let first = blob.append(&[0; 0xa8 * 2], 8);
        for (i, name) in [&b"Block_A"[..], &b"Prop_Decoration_Chest"[..]]
            .iter()
            .enumerate()
        {
            let at = first + i * 0xa8;
            let mut input = vec![0u8; 48 * 2];
            input[0x14..0x18].copy_from_slice(&3u32.to_le_bytes());
            input[48 + 0x14..48 + 0x18].copy_from_slice(&4u32.to_le_bytes());
            let input_at = blob.append(&input, 8);
            let mut output = vec![0u8; 24];
            output[0x14..0x18].copy_from_slice(&10u32.to_le_bytes());
            let output_at = blob.append(&output, 8);
            let name_at = blob.append(name, 1);
            assert!(blob.set_array(at + 0x28, input_at, 2));
            assert!(blob.set_array(at + 0x30, output_at, 1));
            assert!(blob.set_array(at + 0x78, name_at, u32::try_from(name.len()).unwrap()));
        }
        assert!(blob.set_array(8, first, 2));
        let (built, changed) = modify_recipes_in(&LAYOUT, blob.bytes(), &|recipe| {
            if recipe.view().debug_name().starts_with("Block_") {
                recipe.scale_output(3);
                recipe.scale_inputs(1);
            }
        })
        .unwrap();
        assert_eq!(changed, 1);
        assert_eq!(built.len(), blob.bytes().len(), "in place, nothing added");
        let built = Blob::new(&built);
        let (recipes, count) = built.array(8).unwrap();
        assert_eq!(count, 2);
        let view = |at| RecipeView {
            blob: &built,
            at,
            layout: &LAYOUT,
        };
        assert_eq!(view(recipes).output().unwrap().1, 30);
        assert_eq!(view(recipes + 0xa8).output().unwrap().1, 10);
        let (inputs, _) = built.array(recipes + 0x28).unwrap();
        assert_eq!(u32_at(built.bytes(), inputs + 0x14), 3);
        assert_eq!(u32_at(built.bytes(), inputs + 48 + 0x14), 4);

        // A second patch composes: it sees the first one's counts.
        let (again, _) =
            modify_recipes_in(&LAYOUT, built.bytes(), &|recipe| recipe.scale_inputs(2)).unwrap();
        let again = Blob::new(&again);
        let (inputs, _) = again.array(recipes + 0x28).unwrap();
        assert_eq!(u32_at(again.bytes(), inputs + 48 + 0x14), 8);
        assert_eq!(view(recipes).output().unwrap().1, 30);
    }

    #[test]
    fn an_item_without_a_recipe_builds_nothing() {
        let mut blob = Blob::new(&[0u8; 16]);
        assert!(blob.set_array(8, 16, 0));
        let new = NewRecipe {
            id: RECIPE_ID,
            like: CHEST,
            output: SAFE,
            output_count: 1,
            cost: 1,
            workshop: None,
        };
        assert!(add_recipe_to(&LAYOUT, blob.bytes(), &new, WORKSHOP_RECIPES).is_none());
    }
}