enshwick 1.0.0-alpha.3

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
//! Typed game events: a struct per event with its fields read for the
//! running build, for [`Load::on_game`](crate::Load::on_game).

use crate::ecs::Entity;
use crate::game_events::{EventType, Field, RawGameEvent};
use crate::raw::read_at;
use crate::world::{ComponentType, World};
use crate::{Load, Off};

mod sealed {
    pub trait Sealed {}
}

/// A game event with a typed form; implemented by the types in this
/// module only.
///
/// # Examples
///
/// ```
/// use enshwick::game_events::{Died, Kind};
///
/// fn watch<E: Kind + core::fmt::Debug>(load: &mut enshwick::Load<'_>) -> Result<(), enshwick::Off> {
///     load.on_game::<E>(|event| enshwick::debug!("{event:?}"))
/// }
///
/// fn init(load: &mut enshwick::Load<'_>) -> Result<(), enshwick::Off> {
///     watch::<Died>(load)
/// }
/// ```
pub trait Kind: sealed::Sealed + Sized + 'static {
    /// The reflected engine type the event comes from.
    const TYPE_NAME: &'static str;

    /// Resolves the event's fields and subscribes `handler`.
    #[doc(hidden)]
    fn subscribe<F>(load: &mut Load<'_>, handler: F) -> Result<(), Off>
    where
        F: Fn(&Self) + Send + Sync + 'static;
}

/// `Some(entity)` unless it is [`Entity::NONE`].
fn some(entity: Entity) -> Option<Entity> {
    (!entity.is_none()).then_some(entity)
}

/// Subscribes `handler` to the events `decode` turns into an `E`.
fn on<E, D, F>(load: &mut Load<'_>, ty: EventType, decode: D, handler: F) -> Result<(), Off>
where
    D: Fn(&RawGameEvent<'_>) -> Option<E> + Send + Sync + 'static,
    F: Fn(&E) + Send + Sync + 'static,
{
    load.on_raw_game_event(ty, move |event| {
        if let Some(typed) = decode(event) {
            handler(&typed);
        }
    })
}

/// Bits of the damage types of a hit, the engine's `DamageTypeNew` mask.
///
/// # Examples
///
/// ```
/// use enshwick::game_events::DamageTypes;
///
/// let types = DamageTypes(DamageTypes::FIRE.0 | DamageTypes::CUT.0);
/// assert!(types.contains(DamageTypes::FIRE));
/// assert!(!types.contains(DamageTypes::ICE));
/// ```
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct DamageTypes(pub u16);

impl DamageTypes {
    /// Physical cut.
    pub const CUT: Self = Self(1);
    /// Physical pierce.
    pub const PIERCE: Self = Self(1 << 1);
    /// Physical blunt.
    pub const BLUNT: Self = Self(1 << 2);
    /// Fire.
    pub const FIRE: Self = Self(1 << 3);
    /// Ice.
    pub const ICE: Self = Self(1 << 4);
    /// Shroud.
    pub const SHROUD: Self = Self(1 << 5);
    /// Lightning.
    pub const LIGHTNING: Self = Self(1 << 6);
    /// Healing.
    pub const HEALING: Self = Self(1 << 7);
    /// Poison.
    pub const POISON: Self = Self(1 << 8);
    /// Wood, against trees and wooden things.
    pub const WOOD: Self = Self(1 << 9);
    /// Stone, against rock.
    pub const STONE: Self = Self(1 << 10);
    /// Metal, against ore.
    pub const METAL: Self = Self(1 << 11);
    /// Explosion.
    pub const EXPLOSION: Self = Self(1 << 12);

    /// Whether every bit of `other` is set.
    ///
    /// # Examples
    ///
    /// See [`DamageTypes`].
    #[must_use]
    pub const fn contains(self, other: Self) -> bool {
        self.0 & other.0 == other.0
    }
}

/// Bits of the attack categories of a hit, the engine's `AttackCategory`
/// mask.
///
/// # Examples
///
/// ```
/// use enshwick::game_events::AttackCategories;
///
/// assert!(AttackCategories(1).contains(AttackCategories::MELEE));
/// ```
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct AttackCategories(pub u8);

impl AttackCategories {
    /// Melee.
    pub const MELEE: Self = Self(1);
    /// Ranged.
    pub const RANGED: Self = Self(1 << 1);
    /// Magic.
    pub const MAGIC: Self = Self(1 << 2);
    /// A tool, such as a pickaxe.
    pub const TOOL: Self = Self(1 << 3);
    /// Anything else.
    pub const OTHER: Self = Self(1 << 4);
    /// Area of effect.
    pub const AREA: Self = Self(1 << 5);
    /// A skill shot.
    pub const SKILL_SHOT: Self = Self(1 << 6);

    /// Whether every bit of `other` is set.
    ///
    /// # Examples
    ///
    /// See [`AttackCategories`].
    #[must_use]
    pub const fn contains(self, other: Self) -> bool {
        self.0 & other.0 == other.0
    }
}

/// A hit the server resolved, damage or healing: `HitEvent`, written where
/// health changes. Fall and shroud damage change health without a hit.
///
/// # Examples
///
/// ```
/// use enshwick::game_events::Hit;
///
/// fn init(load: &mut enshwick::Load<'_>) -> Result<(), enshwick::Off> {
///     load.on_game::<Hit>(|hit| {
///         if hit.health_change < 0 {
///             enshwick::debug!("{:?} took {} from {:?}", hit.target, -hit.health_change, hit.attacker);
///         }
///     })
/// }
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Hit {
    /// Who the hit is credited to: a character or enemy, not its arrow.
    pub attacker: Option<Entity>,
    /// What dealt it: the attacker itself, a projectile or an effect.
    pub source: Option<Entity>,
    /// The entity hit.
    pub target: Entity,
    /// The root of what was hit: the actor a hit body part belongs to.
    pub root_target: Option<Entity>,
    /// The weapon's item entity.
    pub weapon: Option<Entity>,
    /// The change of the target's health: below 0 for damage.
    pub health_change: i32,
    /// The change of the target's stamina.
    pub stamina_change: i32,
    /// The damage types.
    pub damage_types: DamageTypes,
    /// The attack categories.
    pub attack: AttackCategories,
    /// The target's faction, the engine's `FactionType`.
    pub target_faction: u8,
}

impl sealed::Sealed for Hit {}

impl Kind for Hit {
    const TYPE_NAME: &'static str = "keen::ecs::HitEvent";

    fn subscribe<F>(load: &mut Load<'_>, handler: F) -> Result<(), Off>
    where
        F: Fn(&Self) + Send + Sync + 'static,
    {
        const BASE: &str = "keen::ecs::BaseHitEvent";
        let ty = load.event_type(Self::TYPE_NAME)?;
        let attacker: Field<Entity> = ty.inherited_field(load, BASE, "rootSourceId")?;
        let target: Field<Entity> = ty.inherited_field(load, BASE, "targetId")?;
        let source: Field<Entity> = ty.field(load, "sourceId")?;
        let root_target: Field<Entity> = ty.field(load, "rootTargetId")?;
        let weapon: Field<Entity> = ty.field(load, "weaponPideId")?;
        let health: Field<i32> = ty.field(load, "healthChange")?;
        let stamina: Field<i32> = ty.field(load, "staminaChange")?;
        let damage: Field<u16> = ty.field(load, "damageTypes")?;
        let attack: Field<u8> = ty.field(load, "attackCategory")?;
        let faction: Field<u8> = ty.field(load, "targetFaction")?;
        on(
            load,
            ty,
            move |e| {
                Some(Self {
                    attacker: some(e.get(attacker)?),
                    source: some(e.get(source)?),
                    target: e.get(target)?,
                    root_target: some(e.get(root_target)?),
                    weapon: some(e.get(weapon)?),
                    health_change: e.get(health)?,
                    stamina_change: e.get(stamina)?,
                    damage_types: DamageTypes(e.get(damage)?),
                    attack: AttackCategories(e.get(attack)?),
                    target_faction: e.get(faction)?,
                })
            },
            handler,
        )
    }
}

/// An entity died: `EntityDiedEvent`, with who killed it as far as the
/// engine kept track, read while the dead entity is still in the world.
///
/// # Examples
///
/// ```
/// use enshwick::game_events::Died;
///
/// fn init(load: &mut enshwick::Load<'_>) -> Result<(), enshwick::Off> {
///     let world = load.world()?;
///     load.on_game::<Died>(move |died| {
///         if let Some(player) = died.killer_player.and_then(|p| world.player(p)) {
///             enshwick::info!("{} killed entity {}", player.name, died.entity.0);
///         }
///     })
/// }
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Died {
    /// The entity that died.
    pub entity: Entity,
    /// The attacker of the last hit it took, from its `HitHistory`.
    pub killer: Option<Entity>,
    /// The last player character that hit it, from its `ExperienceSource`:
    /// the one the game credits with the experience.
    pub killer_player: Option<Entity>,
}

impl sealed::Sealed for Died {}

/// Where the kill credit lives on a dying entity.
#[derive(Clone, Copy, Debug)]
struct Credit {
    world: World,
    history: ComponentType,
    last_index: usize,
    entries: usize,
    slots: usize,
    entry_size: usize,
    entry_attacker: usize,
    experience: ComponentType,
    last_player: usize,
}

impl Credit {
    fn resolve(load: &mut Load<'_>) -> Result<Self, Off> {
        let world = load.world()?;
        let offset = |ty: &str, field: &str| {
            load.field_offset(ty, field).and_then(|o| {
                usize::try_from(o).map_err(|_| Off::new(format!("{ty}.{field}: out of range")))
            })
        };
        let history = "keen::ecs::HitHistory";
        let source = "keen::ecs::ExperienceSource";
        let size = usize::try_from(load.type_size(history)?).unwrap_or(0);
        let source_size = usize::try_from(load.type_size(source)?).unwrap_or(0);
        let entries = offset(history, "history")?;
        let entry_size = usize::try_from(load.type_size(Hit::TYPE_NAME)?)
            .unwrap_or(0)
            .max(1);
        // The ring of hits ends where `targetTransform` starts.
        let slots = offset(history, "targetTransform")?.saturating_sub(entries) / entry_size;
        Ok(Self {
            history: world.component_type(load, history)?,
            last_index: offset(history, "lastIndex")?,
            entries,
            slots,
            entry_size,
            entry_attacker: offset("keen::ecs::BaseHitEvent", "rootSourceId")?,
            experience: world.component_type(load, source)?,
            last_player: offset(source, "lastHitPlayerId")?,
            world,
        })
        .and_then(|credit: Self| {
            let id = size_of::<u32>();
            (credit.last_index + id <= size
                && credit.entries + credit.slots * credit.entry_size <= size
                && credit.entry_attacker + id <= credit.entry_size
                && credit.last_player + id <= source_size)
                .then_some(credit)
                .ok_or_else(|| Off::new("kill credit: an unexpected layout"))
        })
    }

    /// The attacker of the last hit `entity` took.
    fn killer(&self, entity: Entity) -> Option<Entity> {
        let history = self.world.component(entity, self.history)?.cast::<u8>();
        // SAFETY: `component` returned the entity's live HitHistory, valid
        // until the game thread moves on; `resolve` checked that the u32 at
        // `lastIndex` lies inside its reflected size.
        let last: u32 = unsafe { read_at(history, self.last_index) };
        let last = usize::try_from(last).ok().filter(|&i| i < self.slots)?;
        let at = self.entries + last * self.entry_size + self.entry_attacker;
        // SAFETY: `history` is the entity's live HitHistory; `last < slots`
        // was checked above, and `resolve` checked that every slot, and the
        // u32 attacker inside it, lies inside its reflected size.
        some(Entity(unsafe { read_at(history, at) }))
    }

    /// The last player character that hit `entity`.
    fn killer_player(&self, entity: Entity) -> Option<Entity> {
        let source = self.world.component(entity, self.experience)?.cast::<u8>();
        // SAFETY: `component` returned the entity's live ExperienceSource,
        // valid until the game thread moves on; `resolve` checked that the u32
        // at `lastHitPlayerId` lies inside its reflected size.
        some(Entity(unsafe { read_at(source, self.last_player) }))
    }
}

impl Kind for Died {
    const TYPE_NAME: &'static str = "keen::ecs::EntityDiedEvent";

    fn subscribe<F>(load: &mut Load<'_>, handler: F) -> Result<(), Off>
    where
        F: Fn(&Self) + Send + Sync + 'static,
    {
        let ty = load.event_type(Self::TYPE_NAME)?;
        let dead: Field<Entity> = ty.field(load, "deadEntityId")?;
        let credit = Credit::resolve(load)
            .inspect_err(|off| crate::debug!("kill credit off: {off}"))
            .ok();
        on(
            load,
            ty,
            move |e| {
                let entity = e.get(dead)?;
                Some(Self {
                    entity,
                    killer: credit.as_ref().and_then(|c| c.killer(entity)),
                    killer_player: credit.as_ref().and_then(|c| c.killer_player(entity)),
                })
            },
            handler,
        )
    }
}

/// A character reached a new level: `LevelUpEvent`.
///
/// # Examples
///
/// ```
/// use enshwick::game_events::LevelGained;
///
/// fn init(load: &mut enshwick::Load<'_>) -> Result<(), enshwick::Off> {
///     load.on_game::<LevelGained>(|up| enshwick::info!("entity {} reached level {}", up.player.0, up.level))
/// }
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct LevelGained {
    /// The player's character.
    pub player: Entity,
    /// The level reached.
    pub level: u32,
}

impl sealed::Sealed for LevelGained {}

impl Kind for LevelGained {
    const TYPE_NAME: &'static str = "keen::ecs::LevelUpEvent";

    fn subscribe<F>(load: &mut Load<'_>, handler: F) -> Result<(), Off>
    where
        F: Fn(&Self) + Send + Sync + 'static,
    {
        let ty = load.event_type(Self::TYPE_NAME)?;
        let player: Field<Entity> = ty.field(load, "playerEntityId")?;
        let level: Field<i32> = ty.field(load, "level")?;
        on(
            load,
            ty,
            move |e| {
                Some(Self {
                    player: e.get(player)?,
                    level: u32::try_from(e.get(level)?).ok()?,
                })
            },
            handler,
        )
    }
}

/// Where experience came from, the engine's `ExperienceSourceType`.
///
/// # Examples
///
/// ```
/// use enshwick::game_events::ExperienceSource;
///
/// assert_eq!(ExperienceSource::from_raw(4), ExperienceSource::Combat);
/// assert_eq!(ExperienceSource::from_raw(40), ExperienceSource::Other(40));
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ExperienceSource {
    /// No source given.
    None,
    /// Exploring.
    Exploration,
    /// Reading lore.
    Lore,
    /// A quest.
    Quest,
    /// A kill.
    Combat,
    /// Mining.
    Mining,
    /// A completed item set.
    ItemSetCompleted,
    /// A value this crate does not name.
    Other(u8),
}

impl ExperienceSource {
    /// The source the engine's value names.
    ///
    /// # Examples
    ///
    /// See [`ExperienceSource`].
    #[must_use]
    pub const fn from_raw(value: u8) -> Self {
        match value {
            0 => Self::None,
            1 => Self::Exploration,
            2 => Self::Lore,
            3 => Self::Quest,
            4 => Self::Combat,
            5 => Self::Mining,
            6 => Self::ItemSetCompleted,
            other => Self::Other(other),
        }
    }
}

/// A character gained experience: `XPGainedEvent`.
///
/// # Examples
///
/// ```
/// use enshwick::game_events::{ExperienceGained, ExperienceSource};
///
/// fn init(load: &mut enshwick::Load<'_>) -> Result<(), enshwick::Off> {
///     load.on_game::<ExperienceGained>(|gained| {
///         if gained.source == ExperienceSource::Combat {
///             enshwick::debug!("{} experience for a kill", gained.amount);
///         }
///     })
/// }
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct ExperienceGained {
    /// The player's character.
    pub player: Entity,
    /// How much.
    pub amount: u32,
    /// Where from.
    pub source: ExperienceSource,
}

impl sealed::Sealed for ExperienceGained {}

impl Kind for ExperienceGained {
    const TYPE_NAME: &'static str = "keen::ecs::XPGainedEvent";

    fn subscribe<F>(load: &mut Load<'_>, handler: F) -> Result<(), Off>
    where
        F: Fn(&Self) + Send + Sync + 'static,
    {
        let ty = load.event_type(Self::TYPE_NAME)?;
        let player: Field<Entity> = ty.field(load, "playerEntityId")?;
        let amount: Field<u32> = ty.field(load, "amount")?;
        let source: Field<u8> = ty.field(load, "source")?;
        on(
            load,
            ty,
            move |e| {
                Some(Self {
                    player: e.get(player)?,
                    amount: e.get(amount)?,
                    source: ExperienceSource::from_raw(e.get(source)?),
                })
            },
            handler,
        )
    }
}

/// A player asked a station to craft: `CraftRecipeEvent`, before the
/// server checks ingredients.
///
/// # Examples
///
/// ```
/// use enshwick::game_events::CraftRequested;
///
/// fn init(load: &mut enshwick::Load<'_>) -> Result<(), enshwick::Off> {
///     load.on_game::<CraftRequested>(|craft| enshwick::debug!("recipe {:#x} x{}", craft.recipe, craft.amount))
/// }
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct CraftRequested {
    /// The crafting player's character.
    pub player: Entity,
    /// The station, or none for crafting by hand.
    pub station: Option<Entity>,
    /// The recipe id.
    pub recipe: u32,
    /// How many.
    pub amount: u16,
}

impl sealed::Sealed for CraftRequested {}

impl Kind for CraftRequested {
    const TYPE_NAME: &'static str = "keen::ecs::CraftRecipeEvent";

    fn subscribe<F>(load: &mut Load<'_>, handler: F) -> Result<(), Off>
    where
        F: Fn(&Self) + Send + Sync + 'static,
    {
        let ty = load.event_type(Self::TYPE_NAME)?;
        let player: Field<Entity> = ty.field(load, "craftingOperatorId")?;
        let station: Field<Entity> = ty.field(load, "craftingStationId")?;
        let recipe: Field<u32> = ty.field(load, "recipeId")?;
        let amount: Field<u16> = ty.field(load, "recipeAmount")?;
        on(
            load,
            ty,
            move |e| {
                Some(Self {
                    player: e.get(player)?,
                    station: some(e.get(station)?),
                    recipe: e.get(recipe)?,
                    amount: e.get(amount)?,
                })
            },
            handler,
        )
    }
}

/// A workshop finished a recipe: `CraftRecipeSuccessEvent`.
///
/// # Examples
///
/// ```
/// use enshwick::game_events::Crafted;
///
/// fn init(load: &mut enshwick::Load<'_>) -> Result<(), enshwick::Off> {
///     load.on_game::<Crafted>(|done| enshwick::debug!("workshop {:#x} made {:#x}", done.workshop, done.recipe))
/// }
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Crafted {
    /// The workshop id.
    pub workshop: u32,
    /// The recipe id.
    pub recipe: u32,
}

impl sealed::Sealed for Crafted {}

impl Kind for Crafted {
    const TYPE_NAME: &'static str = "keen::ecs::CraftRecipeSuccessEvent";

    fn subscribe<F>(load: &mut Load<'_>, handler: F) -> Result<(), Off>
    where
        F: Fn(&Self) + Send + Sync + 'static,
    {
        let ty = load.event_type(Self::TYPE_NAME)?;
        let workshop: Field<u32> = ty.field(load, "workshopId")?;
        let recipe: Field<u32> = ty.field(load, "recipeId")?;
        on(
            load,
            ty,
            move |e| {
                Some(Self {
                    workshop: e.get(workshop)?,
                    recipe: e.get(recipe)?,
                })
            },
            handler,
        )
    }
}

/// A player accepted an interaction an entity offered, such as opening a
/// door or talking to a survivor: `AcceptOfferedInteractionEvent`.
///
/// # Examples
///
/// ```
/// use enshwick::game_events::Interacted;
///
/// fn init(load: &mut enshwick::Load<'_>) -> Result<(), enshwick::Off> {
///     load.on_game::<Interacted>(|used| enshwick::debug!("{:?} used {:?}", used.player, used.target))
/// }
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Interacted {
    /// The player's character.
    pub player: Entity,
    /// The entity that offered the interaction.
    pub target: Entity,
    /// Which of the target's offers.
    pub offer: u32,
}

impl sealed::Sealed for Interacted {}

impl Kind for Interacted {
    const TYPE_NAME: &'static str = "keen::ecs::AcceptOfferedInteractionEvent";

    fn subscribe<F>(load: &mut Load<'_>, handler: F) -> Result<(), Off>
    where
        F: Fn(&Self) + Send + Sync + 'static,
    {
        let ty = load.event_type(Self::TYPE_NAME)?;
        let player: Field<Entity> = ty.field(load, "guestEntityId")?;
        let target: Field<Entity> = ty.field(load, "hostEntityId")?;
        let offer: Field<u32> = ty.field(load, "offerId")?;
        on(
            load,
            ty,
            move |e| {
                Some(Self {
                    player: e.get(player)?,
                    target: e.get(target)?,
                    offer: e.get(offer)?,
                })
            },
            handler,
        )
    }
}

/// What a player did to a building block, from the engine's building
/// events.
///
/// # Examples
///
/// See [`Built`].
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub struct Block {
    /// The player's character.
    pub player: Entity,
    /// Where, in metres, as the engine records it.
    pub position: [f32; 3],
    /// The block's volume, its lower corner, in metres.
    pub volume_min: [f32; 3],
    /// The block's volume, its upper corner, in metres.
    pub volume_max: [f32; 3],
    /// The material's feedback id.
    pub material: u32,
}

/// The fields every building event shares.
#[derive(Clone, Copy, Debug)]
struct BlockFields {
    player: Field<Entity>,
    position: [Field<f32>; 3],
    min: [Field<f32>; 3],
    max: [Field<f32>; 3],
    material: Field<u32>,
}

impl BlockFields {
    fn resolve(load: &Load<'_>, ty: EventType) -> Result<Self, Off> {
        let vector = |name: &str| -> Result<[Field<f32>; 3], Off> {
            let at: Field<f32> = ty.field(load, name)?;
            let next = |step: u64| {
                let offset = u64::from(at.offset()) + step;
                ty.field_at::<f32>(offset)
                    .ok_or_else(|| Off::new(format!("{}.{name}: past the end", ty.name())))
            };
            Ok([at, next(4)?, next(8)?])
        };
        Ok(Self {
            player: ty.field(load, "ownerId")?,
            position: vector("position")?,
            min: vector("volumeMin")?,
            max: vector("volumeMax")?,
            material: ty.field(load, "material")?,
        })
    }

    fn read(&self, e: &RawGameEvent<'_>) -> Option<Block> {
        let vector = |fields: [Field<f32>; 3]| -> Option<[f32; 3]> {
            Some([e.get(fields[0])?, e.get(fields[1])?, e.get(fields[2])?])
        };
        Some(Block {
            player: e.get(self.player)?,
            position: vector(self.position)?,
            volume_min: vector(self.min)?,
            volume_max: vector(self.max)?,
            material: e.get(self.material)?,
        })
    }
}

/// A player placed a building block: `BuildingPlaceEvent`. Props and
/// furniture come as [`BuildingPlaced`](crate::events::BuildingPlaced) too.
///
/// # Examples
///
/// ```
/// use enshwick::game_events::Built;
///
/// fn init(load: &mut enshwick::Load<'_>) -> Result<(), enshwick::Off> {
///     load.on_game::<Built>(|built| enshwick::debug!("{:?} built at {:?}", built.block.player, built.block.position))
/// }
/// ```
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub struct Built {
    /// The block.
    pub block: Block,
    /// The item the block was built from.
    pub item: u32,
}

impl sealed::Sealed for Built {}

impl Kind for Built {
    const TYPE_NAME: &'static str = "keen::ecs::BuildingPlaceEvent";

    fn subscribe<F>(load: &mut Load<'_>, handler: F) -> Result<(), Off>
    where
        F: Fn(&Self) + Send + Sync + 'static,
    {
        let ty = load.event_type(Self::TYPE_NAME)?;
        let block = BlockFields::resolve(load, ty)?;
        let item: Field<u32> = ty.field(load, "trackingItemId")?;
        on(
            load,
            ty,
            move |e| {
                Some(Self {
                    block: block.read(e)?,
                    item: e.get(item)?,
                })
            },
            handler,
        )
    }
}

/// A player tore down building blocks: `BuildingTearDownEvent`.
///
/// # Examples
///
/// ```
/// use enshwick::game_events::TornDown;
///
/// fn init(load: &mut enshwick::Load<'_>) -> Result<(), enshwick::Off> {
///     load.on_game::<TornDown>(|torn| enshwick::debug!("torn down at {:?}", torn.block.position))
/// }
/// ```
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub struct TornDown {
    /// The block.
    pub block: Block,
}

impl sealed::Sealed for TornDown {}

impl Kind for TornDown {
    const TYPE_NAME: &'static str = "keen::ecs::BuildingTearDownEvent";

    fn subscribe<F>(load: &mut Load<'_>, handler: F) -> Result<(), Off>
    where
        F: Fn(&Self) + Send + Sync + 'static,
    {
        let ty = load.event_type(Self::TYPE_NAME)?;
        let block = BlockFields::resolve(load, ty)?;
        on(
            load,
            ty,
            move |e| {
                Some(Self {
                    block: block.read(e)?,
                })
            },
            handler,
        )
    }
}

/// A player picked up a placed piece: `BuildingPickUpEvent`.
///
/// # Examples
///
/// ```
/// use enshwick::game_events::PickedUp;
///
/// fn init(load: &mut enshwick::Load<'_>) -> Result<(), enshwick::Off> {
///     load.on_game::<PickedUp>(|picked| enshwick::debug!("picked up {:?}", picked.entity))
/// }
/// ```
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub struct PickedUp {
    /// The block.
    pub block: Block,
    /// The entity picked up.
    pub entity: Option<Entity>,
}

impl sealed::Sealed for PickedUp {}

impl Kind for PickedUp {
    const TYPE_NAME: &'static str = "keen::ecs::BuildingPickUpEvent";

    fn subscribe<F>(load: &mut Load<'_>, handler: F) -> Result<(), Off>
    where
        F: Fn(&Self) + Send + Sync + 'static,
    {
        let ty = load.event_type(Self::TYPE_NAME)?;
        let block = BlockFields::resolve(load, ty)?;
        let picked: Field<Entity> = ty.field(load, "pickedEntityId")?;
        on(
            load,
            ty,
            move |e| {
                Some(Self {
                    block: block.read(e)?,
                    entity: some(e.get(picked)?),
                })
            },
            handler,
        )
    }
}

/// What a player did at a Flame Altar, the engine's `FlameAltarActionType`.
///
/// # Examples
///
/// ```
/// use enshwick::game_events::AltarAction;
///
/// assert_eq!(AltarAction::from_raw(1), AltarAction::Reclaim);
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum AltarAction {
    /// Abandoned the base.
    Abandon,
    /// Reclaimed an abandoned base.
    Reclaim,
    /// Removed the water.
    RemoveWater,
    /// Made it the preferred respawn altar.
    SetSpawn,
    /// A value this crate does not name.
    Other(u8),
}

impl AltarAction {
    /// The action the engine's value names.
    ///
    /// # Examples
    ///
    /// See [`AltarAction`].
    #[must_use]
    pub const fn from_raw(value: u8) -> Self {
        match value {
            0 => Self::Abandon,
            1 => Self::Reclaim,
            2 => Self::RemoveWater,
            3 => Self::SetSpawn,
            other => Self::Other(other),
        }
    }
}

/// A player acted at a Flame Altar: `FlameAltarEvent`.
///
/// # Examples
///
/// ```
/// use enshwick::game_events::AltarUsed;
///
/// fn init(load: &mut enshwick::Load<'_>) -> Result<(), enshwick::Off> {
///     load.on_game::<AltarUsed>(|used| enshwick::info!("{:?} at altar {:?}", used.action, used.altar))
/// }
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct AltarUsed {
    /// The player's character.
    pub player: Entity,
    /// The altar's base entity.
    pub altar: Entity,
    /// What was done.
    pub action: AltarAction,
}

impl sealed::Sealed for AltarUsed {}

impl Kind for AltarUsed {
    const TYPE_NAME: &'static str = "keen::ecs::FlameAltarEvent";

    fn subscribe<F>(load: &mut Load<'_>, handler: F) -> Result<(), Off>
    where
        F: Fn(&Self) + Send + Sync + 'static,
    {
        let ty = load.event_type(Self::TYPE_NAME)?;
        let player: Field<Entity> = ty.field(load, "playerEntityId")?;
        let altar: Field<Entity> = ty.field(load, "baseEntityId")?;
        let kind: Field<u8> = ty.field(load, "type")?;
        on(
            load,
            ty,
            move |e| {
                Some(Self {
                    player: e.get(player)?,
                    altar: e.get(altar)?,
                    action: AltarAction::from_raw(e.get(kind)?),
                })
            },
            handler,
        )
    }
}

/// A player opened loot, a chest or a container: `LootInteractionEvent`.
///
/// # Examples
///
/// ```
/// use enshwick::game_events::LootOpened;
///
/// fn init(load: &mut enshwick::Load<'_>) -> Result<(), enshwick::Off> {
///     load.on_game::<LootOpened>(|loot| enshwick::debug!("{:?} looted {:?}", loot.player, loot.container))
/// }
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct LootOpened {
    /// The player's character.
    pub player: Entity,
    /// The container.
    pub container: Entity,
    /// Whether the player took everything at once.
    pub take_all: bool,
}

impl sealed::Sealed for LootOpened {}

impl Kind for LootOpened {
    const TYPE_NAME: &'static str = "keen::ecs::LootInteractionEvent";

    fn subscribe<F>(load: &mut Load<'_>, handler: F) -> Result<(), Off>
    where
        F: Fn(&Self) + Send + Sync + 'static,
    {
        let ty = load.event_type(Self::TYPE_NAME)?;
        let player: Field<Entity> = ty.field(load, "guestId")?;
        let container: Field<Entity> = ty.field(load, "hostId")?;
        let all: Field<bool> = ty.field(load, "lootAll")?;
        on(
            load,
            ty,
            move |e| {
                Some(Self {
                    player: e.get(player)?,
                    container: e.get(container)?,
                    take_all: e.get(all)?,
                })
            },
            handler,
        )
    }
}

/// A player's equipment slot changed: `HandleEquipmentSlotChangedEvent`.
///
/// # Examples
///
/// ```
/// use enshwick::game_events::EquipmentChanged;
///
/// fn init(load: &mut enshwick::Load<'_>) -> Result<(), enshwick::Off> {
///     load.on_game::<EquipmentChanged>(|changed| enshwick::debug!("slot {} of {:?}", changed.slot, changed.player))
/// }
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct EquipmentChanged {
    /// The player's character.
    pub player: Entity,
    /// The slot, the engine's `EquipmentSlot`: 5 to 9 armour from head to
    /// feet, 10 and 11 rings, 12 the ranged weapon, 13 the shield.
    pub slot: u8,
}

impl sealed::Sealed for EquipmentChanged {}

impl Kind for EquipmentChanged {
    const TYPE_NAME: &'static str = "keen::ecs::HandleEquipmentSlotChangedEvent";

    fn subscribe<F>(load: &mut Load<'_>, handler: F) -> Result<(), Off>
    where
        F: Fn(&Self) + Send + Sync + 'static,
    {
        let ty = load.event_type(Self::TYPE_NAME)?;
        let player: Field<Entity> = ty.field(load, "playerEntityId")?;
        let slot: Field<u8> = ty.field(load, "equipmentSlot")?;
        on(
            load,
            ty,
            move |e| {
                Some(Self {
                    player: e.get(player)?,
                    slot: e.get(slot)?,
                })
            },
            handler,
        )
    }
}

/// A downed player was revived: `RevivedPlayerEvent`.
///
/// # Examples
///
/// ```
/// use enshwick::game_events::Revived;
///
/// fn init(load: &mut enshwick::Load<'_>) -> Result<(), enshwick::Off> {
///     load.on_game::<Revived>(|revived| enshwick::info!("{:?} revived by {:?}", revived.player, revived.by))
/// }
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Revived {
    /// The revived player's character.
    pub player: Entity,
    /// Who revived them.
    pub by: Option<Entity>,
}

impl sealed::Sealed for Revived {}

impl Kind for Revived {
    const TYPE_NAME: &'static str = "keen::ecs::RevivedPlayerEvent";

    fn subscribe<F>(load: &mut Load<'_>, handler: F) -> Result<(), Off>
    where
        F: Fn(&Self) + Send + Sync + 'static,
    {
        let ty = load.event_type(Self::TYPE_NAME)?;
        let player: Field<Entity> = ty.field(load, "targetEntityId")?;
        let by: Field<Entity> = ty.field(load, "sourceEntityId")?;
        on(
            load,
            ty,
            move |e| {
                Some(Self {
                    player: e.get(player)?,
                    by: some(e.get(by)?),
                })
            },
            handler,
        )
    }
}