enshwick 1.0.0-alpha.11

The Enshwick Loader's modding API for Enshrouded: the one crate mods are written against
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
//! Typed game events: a struct per event with its fields read for the
//! running build, for [`Load::on`](crate::Load::on).

#[cfg(feature = "unstable")]
use crate::Host;
#[cfg(feature = "unstable")]
use crate::ecs::ComponentType;
use crate::engine_enum::{Bits, Values};
use crate::engine_ids as ids;
use crate::game_events::values::{
    AttackCategoryMask, DamageTypeMask, EquipmentSlot, ExperienceSourceType, FlameAltarActionType,
};
use crate::game_events::{EventType, Field, RawGameEvent};
#[cfg(feature = "unstable")]
use crate::raw::read_at;
use crate::{Entity, ItemId, RecipeId};
use crate::{Load, Off};

/// `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);
        }
    })
}

/// A hit the server resolved, damage or healing, written where health
/// changes. Fall and shroud damage change health without a hit.
///
/// # Examples
///
/// ```
/// use enshwick::game_events::HitEvent;
///
/// fn init(load: &mut enshwick::Load<'_>) -> Result<(), enshwick::Off> {
///     load.on::<HitEvent>(|hit| {
///         if hit.health_change < 0 {
///             enshwick::debug!("{:?} took {} from {:?}", hit.target_id, -hit.health_change, hit.root_source_id);
///         }
///     })
/// }
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq, crate::Script)]
#[non_exhaustive]
pub struct HitEvent {
    /// Who the hit is credited to: a character or enemy, not its arrow.
    pub root_source_id: Option<Entity>,
    /// What dealt it: the attacker itself, a projectile or an effect.
    pub source_id: Option<Entity>,
    /// The entity hit.
    pub target_id: Entity,
    /// The root of what was hit: the actor a hit body part belongs to.
    pub root_target_id: Option<Entity>,
    /// The weapon's item entity.
    pub weapon_pide_id: 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: DamageTypeMask,
    /// The attack categories.
    pub attack_category: AttackCategoryMask,
    /// The target's faction, the engine's `FactionType`.
    pub target_faction: u8,
}

impl crate::events::Kind for HitEvent {
    type Data = Self;

    fn subscribe<F>(load: &mut Load<'_>, handler: F) -> Result<(), Off>
    where
        F: Fn(&Self) + Send + Sync + 'static,
    {
        let ty = load.game_event_type(ids::HIT_EVENT)?;
        let attacker: Field<Entity> = ty.field_by_id(load, ids::HIT_EVENT_ROOT_SOURCE_ID)?;
        let target: Field<Entity> = ty.field_by_id(load, ids::HIT_EVENT_TARGET_ID)?;
        let source: Field<Entity> = ty.field_by_id(load, ids::HIT_EVENT_SOURCE_ID)?;
        let root_target: Field<Entity> = ty.field_by_id(load, ids::HIT_EVENT_ROOT_TARGET_ID)?;
        let weapon: Field<Entity> = ty.field_by_id(load, ids::HIT_EVENT_WEAPON_PIDE_ID)?;
        let health: Field<i32> = ty.field_by_id(load, ids::HIT_HEALTH_CHANGE)?;
        let stamina: Field<i32> = ty.field_by_id(load, ids::HIT_STAMINA_CHANGE)?;
        let damage: Field<u16> = ty.field_by_id(load, ids::HIT_DAMAGE_TYPES)?;
        let attack: Field<u8> = ty.field_by_id(load, ids::HIT_EVENT_ATTACK_CATEGORY)?;
        let faction: Field<u8> = ty.field_by_id(load, ids::HIT_TARGET_FACTION)?;
        let damage_bits = Bits::resolve(load, DamageTypeMask::IDS.map(|(t, id)| (t.bits(), id)));
        let attack_bits = Bits::resolve(
            load,
            AttackCategoryMask::IDS.map(|(c, id)| (u16::from(c.bits()), id)),
        );
        on(
            load,
            ty,
            move |e| {
                Some(Self {
                    root_source_id: some(e.get(attacker)?),
                    source_id: some(e.get(source)?),
                    target_id: e.get(target)?,
                    root_target_id: some(e.get(root_target)?),
                    weapon_pide_id: some(e.get(weapon)?),
                    health_change: e.get(health)?,
                    stamina_change: e.get(stamina)?,
                    damage_types: DamageTypeMask::from_bits(damage_bits.map(e.get(damage)?)),
                    attack_category: AttackCategoryMask::from_bits(
                        u8::try_from(attack_bits.map(u16::from(e.get(attack)?))).ok()?,
                    ),
                    target_faction: e.get(faction)?,
                })
            },
            handler,
        )
    }
}

/// An entity died, 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::EntityDiedEvent;
///
/// fn init(load: &mut enshwick::Load<'_>) -> Result<(), enshwick::Off> {
///     load.on::<EntityDiedEvent>(|died| {
///         enshwick::debug!("entity {} died", died.dead_entity_id);
///     })
/// }
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq, crate::Script)]
#[non_exhaustive]
pub struct EntityDiedEvent {
    /// The entity that died.
    pub dead_entity_id: Entity,
    /// The attacker of the last hit it took, from the hits it keeps; the
    /// name is enshwick's, not the game's. Unstable: needs the `unstable`
    /// feature and may change in any release.
    #[cfg(feature = "unstable")]
    pub killer: Option<Entity>,
    /// The last player character that hit it, from its kill credit:
    /// the one the game credits with the experience; the name is
    /// enshwick's, not the game's. Unstable: needs the `unstable` feature
    /// and may change in any release.
    #[cfg(feature = "unstable")]
    pub killer_player: Option<Entity>,
}

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

#[cfg(feature = "unstable")]
impl Credit {
    fn resolve(load: &mut Load<'_>) -> Result<Self, Off> {
        let offset = |id: &str| {
            load.constant(id).and_then(|o| {
                usize::try_from(o).map_err(|_| Off::new(format!("{id}: out of range")))
            })
        };
        let size = usize::try_from(load.type_size(ids::HIT_HISTORY)?).unwrap_or(0);
        let source_size = usize::try_from(load.type_size(ids::EXPERIENCE_CREDIT)?).unwrap_or(0);
        let entries = offset(ids::HIT_HISTORY_ENTRIES)?;
        let entry_size = usize::try_from(load.type_size(ids::HIT_EVENT)?)
            .unwrap_or(0)
            .max(1);
        let slots = offset(ids::HIT_HISTORY_END)?.saturating_sub(entries) / entry_size;
        Ok(Self {
            history: ComponentType::resolve(load, ids::HIT_HISTORY)?,
            last_index: offset(ids::HIT_HISTORY_LAST_INDEX)?,
            entries,
            slots,
            entry_size,
            entry_attacker: offset(ids::HIT_EVENT_ROOT_SOURCE_ID)?,
            experience: ComponentType::resolve(load, ids::EXPERIENCE_CREDIT)?,
            last_player: offset(ids::EXPERIENCE_CREDIT_LAST_PLAYER)?,
            host: load.host(),
        })
        .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.history.read(self.host, entity)?.cast::<u8>();
        // SAFETY: `read` 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.experience.read(self.host, entity)?.cast::<u8>();
        // SAFETY: `read` returned the entity's live ExperienceSource component,
        // 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 crate::events::Kind for EntityDiedEvent {
    type Data = Self;

    fn subscribe<F>(load: &mut Load<'_>, handler: F) -> Result<(), Off>
    where
        F: Fn(&Self) + Send + Sync + 'static,
    {
        let ty = load.game_event_type(ids::ENTITY_DIED_EVENT)?;
        let dead: Field<Entity> = ty.field_by_id(load, ids::ENTITY_DIED_EVENT_DEAD_ENTITY_ID)?;
        #[cfg(feature = "unstable")]
        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 {
                    dead_entity_id: entity,
                    #[cfg(feature = "unstable")]
                    killer: credit.as_ref().and_then(|c| c.killer(entity)),
                    #[cfg(feature = "unstable")]
                    killer_player: credit.as_ref().and_then(|c| c.killer_player(entity)),
                })
            },
            handler,
        )
    }
}

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

impl crate::events::Kind for LevelUpEvent {
    type Data = Self;

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

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

impl crate::events::Kind for XpGainedEvent {
    type Data = Self;

    fn subscribe<F>(load: &mut Load<'_>, handler: F) -> Result<(), Off>
    where
        F: Fn(&Self) + Send + Sync + 'static,
    {
        let ty = load.game_event_type(ids::XP_GAINED_EVENT)?;
        let player: Field<Entity> = ty.field_by_id(load, ids::XP_GAINED_EVENT_PLAYER_ENTITY_ID)?;
        let amount: Field<u32> = ty.field_by_id(load, ids::XP_GAINED_EVENT_AMOUNT)?;
        let source: Field<u8> = ty.field_by_id(load, ids::XP_GAINED_EVENT_SOURCE)?;
        let sources = Values::resolve(load, ExperienceSourceType::IDS);
        on(
            load,
            ty,
            move |e| {
                Some(Self {
                    player_entity_id: e.get(player)?,
                    amount: e.get(amount)?,
                    source: {
                        let raw = e.get(source)?;
                        sources
                            .variant(u64::from(raw))
                            .unwrap_or(ExperienceSourceType::Other(raw))
                    },
                })
            },
            handler,
        )
    }
}

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

impl crate::events::Kind for CraftRecipeEvent {
    type Data = Self;

    fn subscribe<F>(load: &mut Load<'_>, handler: F) -> Result<(), Off>
    where
        F: Fn(&Self) + Send + Sync + 'static,
    {
        let ty = load.game_event_type(ids::CRAFT_RECIPE_EVENT)?;
        let player: Field<Entity> =
            ty.field_by_id(load, ids::CRAFT_RECIPE_EVENT_CRAFTING_OPERATOR_ID)?;
        let station: Field<Entity> =
            ty.field_by_id(load, ids::CRAFT_RECIPE_EVENT_CRAFTING_STATION_ID)?;
        let recipe: Field<RecipeId> = ty.field_by_id(load, ids::CRAFT_RECIPE_EVENT_RECIPE_ID)?;
        let amount: Field<u16> = ty.field_by_id(load, ids::CRAFT_RECIPE_EVENT_RECIPE_AMOUNT)?;
        on(
            load,
            ty,
            move |e| {
                Some(Self {
                    crafting_operator_id: e.get(player)?,
                    crafting_station_id: some(e.get(station)?),
                    recipe_id: e.get(recipe)?,
                    recipe_amount: e.get(amount)?,
                })
            },
            handler,
        )
    }
}

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

impl crate::events::Kind for CraftRecipeSuccessEvent {
    type Data = Self;

    fn subscribe<F>(load: &mut Load<'_>, handler: F) -> Result<(), Off>
    where
        F: Fn(&Self) + Send + Sync + 'static,
    {
        let ty = load.game_event_type(ids::CRAFT_RECIPE_SUCCESS_EVENT)?;
        let workshop: Field<u32> =
            ty.field_by_id(load, ids::CRAFT_RECIPE_SUCCESS_EVENT_WORKSHOP_ID)?;
        let recipe: Field<RecipeId> =
            ty.field_by_id(load, ids::CRAFT_RECIPE_SUCCESS_EVENT_RECIPE_ID)?;
        on(
            load,
            ty,
            move |e| {
                Some(Self {
                    workshop_id: e.get(workshop)?,
                    recipe_id: e.get(recipe)?,
                })
            },
            handler,
        )
    }
}

/// A player accepted an interaction an entity offered, such as opening a
/// door or talking to a survivor.
///
/// # Examples
///
/// ```
/// use enshwick::game_events::AcceptOfferedInteractionEvent;
///
/// fn init(load: &mut enshwick::Load<'_>) -> Result<(), enshwick::Off> {
///     load.on::<AcceptOfferedInteractionEvent>(|used| enshwick::debug!("{:?} used {:?}", used.guest_entity_id, used.host_entity_id))
/// }
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq, crate::Script)]
#[non_exhaustive]
#[expect(
    clippy::struct_field_names,
    reason = "the fields take the game's names, which all end in Id"
)]
pub struct AcceptOfferedInteractionEvent {
    /// The player's character.
    pub guest_entity_id: Entity,
    /// The entity that offered the interaction.
    pub host_entity_id: Entity,
    /// Which of the target's offers.
    pub offer_id: u32,
}

impl crate::events::Kind for AcceptOfferedInteractionEvent {
    type Data = Self;

    fn subscribe<F>(load: &mut Load<'_>, handler: F) -> Result<(), Off>
    where
        F: Fn(&Self) + Send + Sync + 'static,
    {
        let ty = load.game_event_type(ids::ACCEPT_OFFERED_INTERACTION_EVENT)?;
        let player: Field<Entity> =
            ty.field_by_id(load, ids::ACCEPT_OFFERED_INTERACTION_EVENT_GUEST_ENTITY_ID)?;
        let target: Field<Entity> =
            ty.field_by_id(load, ids::ACCEPT_OFFERED_INTERACTION_EVENT_HOST_ENTITY_ID)?;
        let offer: Field<u32> =
            ty.field_by_id(load, ids::ACCEPT_OFFERED_INTERACTION_EVENT_OFFER_ID)?;
        on(
            load,
            ty,
            move |e| {
                Some(Self {
                    guest_entity_id: e.get(player)?,
                    host_entity_id: e.get(target)?,
                    offer_id: e.get(offer)?,
                })
            },
            handler,
        )
    }
}

/// What a player did to a building block, the fields the engine's building
/// events share; the name is enshwick's, not the game's.
///
/// # Examples
///
/// See [`BuildingPlaceEvent`].
#[derive(Clone, Copy, Debug, PartialEq, crate::Script)]
#[non_exhaustive]
pub struct Block {
    /// The player's character.
    pub owner_id: 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 ids of the fields every building event shares, one set per event.
#[derive(Clone, Copy, Debug)]
struct BlockIds {
    owner_id: &'static str,
    position: &'static str,
    min: &'static str,
    max: &'static str,
    material: &'static str,
}

/// The fields every building event shares.
#[derive(Clone, Copy, Debug)]
struct BlockFields {
    owner_id: 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, ids: BlockIds) -> Result<Self, Off> {
        let vector = |id: &str| -> Result<[Field<f32>; 3], Off> {
            let at: Field<f32> = ty.field_by_id(load, id)?;
            let next = |step: u64| {
                let offset = u64::from(at.offset()) + step;
                ty.field_at::<f32>(offset)
                    .ok_or_else(|| Off::new(format!("{id}: past the end of {}", ty.name())))
            };
            Ok([at, next(4)?, next(8)?])
        };
        Ok(Self {
            owner_id: ty.field_by_id(load, ids.owner_id)?,
            position: vector(ids.position)?,
            min: vector(ids.min)?,
            max: vector(ids.max)?,
            material: ty.field_by_id(load, ids.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 {
            owner_id: e.get(self.owner_id)?,
            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. Props and
/// furniture come as [`BuildingPlaced`](crate::events::BuildingPlaced) too.
///
/// # Examples
///
/// ```
/// use enshwick::game_events::BuildingPlaceEvent;
///
/// fn init(load: &mut enshwick::Load<'_>) -> Result<(), enshwick::Off> {
///     load.on::<BuildingPlaceEvent>(|built| enshwick::debug!("{:?} built at {:?}", built.block.owner_id, built.block.position))
/// }
/// ```
#[derive(Clone, Copy, Debug, PartialEq, crate::Script)]
#[non_exhaustive]
pub struct BuildingPlaceEvent {
    /// The block.
    pub block: Block,
    /// The item the block was built from.
    pub tracking_item_id: ItemId,
}

impl crate::events::Kind for BuildingPlaceEvent {
    type Data = Self;

    fn subscribe<F>(load: &mut Load<'_>, handler: F) -> Result<(), Off>
    where
        F: Fn(&Self) + Send + Sync + 'static,
    {
        let ty = load.game_event_type(ids::BUILDING_PLACE_EVENT)?;
        let block = BlockFields::resolve(
            load,
            ty,
            BlockIds {
                owner_id: ids::BUILDING_PLACE_EVENT_OWNER_ID,
                position: ids::BUILDING_PLACE_EVENT_POSITION,
                min: ids::BUILDING_PLACE_EVENT_VOLUME_MIN,
                max: ids::BUILDING_PLACE_EVENT_VOLUME_MAX,
                material: ids::BUILDING_PLACE_EVENT_MATERIAL,
            },
        )?;
        let item: Field<ItemId> =
            ty.field_by_id(load, ids::BUILDING_PLACE_EVENT_TRACKING_ITEM_ID)?;
        on(
            load,
            ty,
            move |e| {
                Some(Self {
                    block: block.read(e)?,
                    tracking_item_id: e.get(item)?,
                })
            },
            handler,
        )
    }
}

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

impl crate::events::Kind for BuildingTearDownEvent {
    type Data = Self;

    fn subscribe<F>(load: &mut Load<'_>, handler: F) -> Result<(), Off>
    where
        F: Fn(&Self) + Send + Sync + 'static,
    {
        let ty = load.game_event_type(ids::BUILDING_TEAR_DOWN_EVENT)?;
        let block = BlockFields::resolve(
            load,
            ty,
            BlockIds {
                owner_id: ids::BUILDING_TEAR_DOWN_EVENT_OWNER_ID,
                position: ids::BUILDING_TEAR_DOWN_EVENT_POSITION,
                min: ids::BUILDING_TEAR_DOWN_EVENT_VOLUME_MIN,
                max: ids::BUILDING_TEAR_DOWN_EVENT_VOLUME_MAX,
                material: ids::BUILDING_TEAR_DOWN_EVENT_MATERIAL,
            },
        )?;
        on(
            load,
            ty,
            move |e| {
                Some(Self {
                    block: block.read(e)?,
                })
            },
            handler,
        )
    }
}

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

impl crate::events::Kind for BuildingPickUpEvent {
    type Data = Self;

    fn subscribe<F>(load: &mut Load<'_>, handler: F) -> Result<(), Off>
    where
        F: Fn(&Self) + Send + Sync + 'static,
    {
        let ty = load.game_event_type(ids::BUILDING_PICK_UP_EVENT)?;
        let block = BlockFields::resolve(
            load,
            ty,
            BlockIds {
                owner_id: ids::BUILDING_PICK_UP_EVENT_OWNER_ID,
                position: ids::BUILDING_PICK_UP_EVENT_POSITION,
                min: ids::BUILDING_PICK_UP_EVENT_VOLUME_MIN,
                max: ids::BUILDING_PICK_UP_EVENT_VOLUME_MAX,
                material: ids::BUILDING_PICK_UP_EVENT_MATERIAL,
            },
        )?;
        let picked: Field<Entity> =
            ty.field_by_id(load, ids::BUILDING_PICK_UP_EVENT_PICKED_ENTITY_ID)?;
        on(
            load,
            ty,
            move |e| {
                Some(Self {
                    block: block.read(e)?,
                    picked_entity_id: some(e.get(picked)?),
                })
            },
            handler,
        )
    }
}

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

impl crate::events::Kind for FlameAltarEvent {
    type Data = Self;

    fn subscribe<F>(load: &mut Load<'_>, handler: F) -> Result<(), Off>
    where
        F: Fn(&Self) + Send + Sync + 'static,
    {
        let ty = load.game_event_type(ids::FLAME_ALTAR_EVENT)?;
        let player: Field<Entity> =
            ty.field_by_id(load, ids::FLAME_ALTAR_EVENT_PLAYER_ENTITY_ID)?;
        let altar: Field<Entity> = ty.field_by_id(load, ids::FLAME_ALTAR_EVENT_BASE_ENTITY_ID)?;
        let kind: Field<u8> = ty.field_by_id(load, ids::FLAME_ALTAR_EVENT_TYPE)?;
        let actions = Values::resolve(load, FlameAltarActionType::IDS);
        on(
            load,
            ty,
            move |e| {
                Some(Self {
                    player_entity_id: e.get(player)?,
                    base_entity_id: e.get(altar)?,
                    r#type: {
                        let raw = e.get(kind)?;
                        actions
                            .variant(u64::from(raw))
                            .unwrap_or(FlameAltarActionType::Other(raw))
                    },
                })
            },
            handler,
        )
    }
}

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

impl crate::events::Kind for LootInteractionEvent {
    type Data = Self;

    fn subscribe<F>(load: &mut Load<'_>, handler: F) -> Result<(), Off>
    where
        F: Fn(&Self) + Send + Sync + 'static,
    {
        let ty = load.game_event_type(ids::LOOT_INTERACTION_EVENT)?;
        let player: Field<Entity> = ty.field_by_id(load, ids::LOOT_INTERACTION_EVENT_GUEST_ID)?;
        let container: Field<Entity> = ty.field_by_id(load, ids::LOOT_INTERACTION_EVENT_HOST_ID)?;
        let all: Field<bool> = ty.field_by_id(load, ids::LOOT_INTERACTION_EVENT_LOOT_ALL)?;
        on(
            load,
            ty,
            move |e| {
                Some(Self {
                    guest_id: e.get(player)?,
                    host_id: e.get(container)?,
                    loot_all: e.get(all)?,
                })
            },
            handler,
        )
    }
}

/// A player's equipment slot changed.
///
/// # Examples
///
/// ```
/// use enshwick::game_events::HandleEquipmentSlotChangedEvent;
///
/// fn init(load: &mut enshwick::Load<'_>) -> Result<(), enshwick::Off> {
///     load.on::<HandleEquipmentSlotChangedEvent>(|changed| enshwick::debug!("{:?} of {:?}", changed.equipment_slot, changed.player_entity_id))
/// }
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq, crate::Script)]
#[non_exhaustive]
pub struct HandleEquipmentSlotChangedEvent {
    /// The player's character.
    pub player_entity_id: Entity,
    /// The slot.
    pub equipment_slot: EquipmentSlot,
}

impl crate::events::Kind for HandleEquipmentSlotChangedEvent {
    type Data = Self;

    fn subscribe<F>(load: &mut Load<'_>, handler: F) -> Result<(), Off>
    where
        F: Fn(&Self) + Send + Sync + 'static,
    {
        let ty = load.game_event_type(ids::HANDLE_EQUIPMENT_SLOT_CHANGED_EVENT)?;
        let player: Field<Entity> = ty.field_by_id(
            load,
            ids::HANDLE_EQUIPMENT_SLOT_CHANGED_EVENT_PLAYER_ENTITY_ID,
        )?;
        let slot: Field<u8> = ty.field_by_id(
            load,
            ids::HANDLE_EQUIPMENT_SLOT_CHANGED_EVENT_EQUIPMENT_SLOT,
        )?;
        let slots = Values::resolve(load, EquipmentSlot::IDS);
        on(
            load,
            ty,
            move |e| {
                Some(Self {
                    player_entity_id: e.get(player)?,
                    equipment_slot: {
                        let raw = e.get(slot)?;
                        slots
                            .variant(u64::from(raw))
                            .unwrap_or(EquipmentSlot::Other(raw))
                    },
                })
            },
            handler,
        )
    }
}

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

impl crate::events::Kind for RevivedPlayerEvent {
    type Data = Self;

    fn subscribe<F>(load: &mut Load<'_>, handler: F) -> Result<(), Off>
    where
        F: Fn(&Self) + Send + Sync + 'static,
    {
        let ty = load.game_event_type(ids::REVIVED_PLAYER_EVENT)?;
        let player: Field<Entity> =
            ty.field_by_id(load, ids::REVIVED_PLAYER_EVENT_TARGET_ENTITY_ID)?;
        let by: Field<Entity> = ty.field_by_id(load, ids::REVIVED_PLAYER_EVENT_SOURCE_ENTITY_ID)?;
        on(
            load,
            ty,
            move |e| {
                Some(Self {
                    target_entity_id: e.get(player)?,
                    source_entity_id: some(e.get(by)?),
                })
            },
            handler,
        )
    }
}