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
//! Damage filters: see and change damage before it reaches an entity's
//! health in the server's world, by cause and, for hits, by damage type.
//!
//! A hit's damage comes by type, after the target's resistances and before
//! its armour: the armour, a block and the hit the game raises all follow
//! what the filters leave. Falls, the shroud, drowning and freezing take
//! health without a hit and come as one amount; an administrator's kill
//! comes as an amount of 1 that a filter can only let through or cancel. A
//! filter scales, sets or cancels; filters of several mods run in load
//! order, each on what the one before left. Executions are hits; heals and
//! health set by the game's scripts are not filtered.
//!
//! Filters run on the game's worker threads, in parallel, inside the
//! systems that deal damage: they must not allocate, lock or log, and read
//! only what they hold themselves, such as settings in atomics.
//!
//! The filters need the `unstable` feature and may change in any release:
//! the order of health, stamina and mana in the game's attributes, and who
//! the game records as a killer, are not yet seen in the running game. The
//! damage types are stable.
//!
//! # Examples
//!
//! ```
//! use enshwick::damage::DamageTypeNew;
//!
//! assert_eq!(DamageTypeNew::ALL[DamageTypeNew::MagicalFire.index()], DamageTypeNew::MagicalFire);
//! ```

#[cfg(feature = "unstable")]
use core::ffi::c_void;

#[cfg(feature = "unstable")]
use crate::Entity;
#[cfg(feature = "unstable")]
use crate::abi::DamageCheck;
#[cfg(feature = "unstable")]
use crate::{Load, Off};

/// A damage type, as the game sorts a hit's damage.
///
/// # Examples
///
/// See the [module](self).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum DamageTypeNew {
    /// Blades.
    PhysicalCut,
    /// Arrows and spears.
    PhysicalPierce,
    /// Clubs and hammers.
    PhysicalBlunt,
    /// Fire.
    MagicalFire,
    /// Ice.
    MagicalIce,
    /// The shroud.
    MagicalFog,
    /// Lightning.
    MagicalLightning,
    /// Healing: what the hit heals, not what it hurts.
    Healing,
    /// Poison.
    Poison,
    /// Damage to wood.
    Wood,
    /// Damage to stone.
    Stone,
    /// Damage to metal.
    Metal,
    /// Explosions.
    Explosion,
}

impl DamageTypeNew {
    /// Every type, in the game's order.
    pub const ALL: [Self; crate::abi::DAMAGE_TYPES] = [
        Self::PhysicalCut,
        Self::PhysicalPierce,
        Self::PhysicalBlunt,
        Self::MagicalFire,
        Self::MagicalIce,
        Self::MagicalFog,
        Self::MagicalLightning,
        Self::Healing,
        Self::Poison,
        Self::Wood,
        Self::Stone,
        Self::Metal,
        Self::Explosion,
    ];

    /// The type's place in a hit's damage amounts,
    /// [`DamageCheck::amounts`](crate::abi::DamageCheck::amounts), the game's
    /// order of its damage types.
    ///
    /// # Examples
    ///
    /// ```
    /// use enshwick::damage::DamageTypeNew;
    ///
    /// assert_eq!(DamageTypeNew::ALL[DamageTypeNew::Healing.index()], DamageTypeNew::Healing);
    /// ```
    #[must_use]
    pub const fn index(self) -> usize {
        self as usize
    }
}

/// What deals damage.
///
/// Unstable: needs the `unstable` feature and may change in any release.
///
/// The name is enshwick's: the loader's hook points, not a game type. A
/// cause the game names among its death causes (`DeathCause`) takes that
/// name; the others are enshwick's and say so.
///
/// # Examples
///
/// See the [module](self).
#[cfg(feature = "unstable")]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum DamageCause {
    /// A hit from a weapon, a spell, a creature or an explosion, by type.
    Impact,
    /// A fall.
    FallDamage,
    /// The shroud draining a character whose time in it ran out.
    Fog,
    /// The deadly shroud, which kills at once.
    DeadlyFog,
    /// A character out of breath under water.
    Suffocated,
    /// A creature out of breath under water, which dies at once. The name
    /// is enshwick's, not the game's.
    DrowningDeath,
    /// A character frozen through, out of body heat. The name is
    /// enshwick's, not the game's.
    Freezing,
    /// An administrator's kill command: [`Damage::total`] is 1, and the kill
    /// goes ahead unless a filter [cancels](Damage::cancel) it. The name is
    /// enshwick's, not the game's.
    AdminKill,
    /// A cause this API does not name.
    Other(u32),
}

#[cfg(feature = "unstable")]
impl DamageCause {
    /// Every cause this API names, without [`Other`](Self::Other): the set
    /// a tally by cause iterates, so a newly named cause joins it.
    ///
    /// # Examples
    ///
    /// ```
    /// use enshwick::damage::DamageCause;
    ///
    /// assert!(DamageCause::NAMED.contains(&DamageCause::FallDamage));
    /// ```
    pub const NAMED: &[Self] = &[
        Self::Impact,
        Self::FallDamage,
        Self::Fog,
        Self::DeadlyFog,
        Self::Suffocated,
        Self::DrowningDeath,
        Self::Freezing,
        Self::AdminKill,
    ];

    /// The cause of the ABI's code, as [`DamageCheck`] numbers them.
    const fn from_code(code: u32) -> Self {
        match code {
            DamageCheck::IMPACT => Self::Impact,
            DamageCheck::FALL_DAMAGE => Self::FallDamage,
            DamageCheck::FOG => Self::Fog,
            DamageCheck::DEADLY_FOG => Self::DeadlyFog,
            DamageCheck::SUFFOCATED => Self::Suffocated,
            DamageCheck::DROWNING_DEATH => Self::DrowningDeath,
            DamageCheck::FREEZING => Self::Freezing,
            DamageCheck::ADMIN_KILL => Self::AdminKill,
            other => Self::Other(other),
        }
    }
}

/// Damage about to reach an entity's health, for a filter registered with
/// [`Load::on_damage`] to see and change.
///
/// Unstable: needs the `unstable` feature and may change in any release.
///
/// # Examples
///
/// See the [module](self).
#[cfg(feature = "unstable")]
#[derive(Debug)]
pub struct Damage<'a> {
    check: &'a mut DamageCheck,
}

#[cfg(feature = "unstable")]
impl Damage<'_> {
    /// What deals it.
    ///
    /// # Examples
    ///
    /// See the [module](self).
    #[must_use]
    pub const fn cause(&self) -> DamageCause {
        DamageCause::from_code(self.check.cause)
    }

    /// The entity that takes it.
    ///
    /// # Examples
    ///
    /// ```
    /// fn init(load: &mut enshwick::Load<'_>) -> Result<(), enshwick::Off> {
    ///     // Entity 2 takes no damage at all.
    ///     load.on_damage(|damage| {
    ///         if damage.target().0 == 2 {
    ///             damage.cancel();
    ///         }
    ///     })
    /// }
    /// ```
    #[must_use]
    pub const fn target(&self) -> Entity {
        self.check.target
    }

    /// What dealt a hit: the attacker, or its projectile; `None` for other
    /// causes.
    ///
    /// # Examples
    ///
    /// ```
    /// fn init(load: &mut enshwick::Load<'_>) -> Result<(), enshwick::Off> {
    ///     // Nothing hurts itself.
    ///     load.on_damage(|damage| {
    ///         if damage.source() == Some(damage.target()) {
    ///             damage.cancel();
    ///         }
    ///     })
    /// }
    /// ```
    #[must_use]
    pub const fn source(&self) -> Option<Entity> {
        if self.check.source.is_none() {
            None
        } else {
            Some(self.check.source)
        }
    }

    /// Who dealt a hit: the attacker, also for its arrows and spells; `None`
    /// for other causes.
    ///
    /// # Examples
    ///
    /// ```
    /// fn init(load: &mut enshwick::Load<'_>) -> Result<(), enshwick::Off> {
    ///     // Entity 7 deals double damage, by hand or by bow.
    ///     load.on_damage(|damage| {
    ///         if damage.attacker().is_some_and(|a| a.0 == 7) {
    ///             damage.scale(2.0);
    ///         }
    ///     })
    /// }
    /// ```
    #[must_use]
    pub const fn attacker(&self) -> Option<Entity> {
        if self.check.attacker.is_none() {
            self.source()
        } else {
            Some(self.check.attacker)
        }
    }

    /// A hit's damage of type `ty`; 0 for other causes.
    ///
    /// # Examples
    ///
    /// ```
    /// use enshwick::damage::DamageTypeNew;
    ///
    /// fn init(load: &mut enshwick::Load<'_>) -> Result<(), enshwick::Off> {
    ///     // Fire never deals more than 50 at once.
    ///     load.on_damage(|damage| {
    ///         let fire = damage.amount(DamageTypeNew::MagicalFire);
    ///         damage.set(DamageTypeNew::MagicalFire, fire.min(50.0));
    ///     })
    /// }
    /// ```
    #[must_use]
    pub const fn amount(&self, ty: DamageTypeNew) -> f32 {
        self.check.amounts[ty.index()]
    }

    /// Sets a hit's damage of type `ty`; does nothing for other causes. A
    /// negative or not finite amount counts as none.
    ///
    /// # Examples
    ///
    /// See [`Damage::amount`].
    pub const fn set(&mut self, ty: DamageTypeNew, amount: f32) {
        if self.check.cause == DamageCheck::IMPACT {
            self.check.amounts[ty.index()] = amount;
        }
    }

    /// The damage the health takes: for a hit, the sum of its types but
    /// healing, before the target's armour.
    ///
    /// # Examples
    ///
    /// ```
    /// fn init(load: &mut enshwick::Load<'_>) -> Result<(), enshwick::Off> {
    ///     // No single blow deals more than 200.
    ///     load.on_damage(|damage| {
    ///         let total = damage.total();
    ///         if total > 200.0 {
    ///             damage.scale(200.0 / total);
    ///         }
    ///     })
    /// }
    /// ```
    #[must_use]
    pub fn total(&self) -> f32 {
        if self.check.cause == DamageCheck::IMPACT {
            DamageTypeNew::ALL
                .iter()
                .filter(|&&ty| ty != DamageTypeNew::Healing)
                .map(|&ty| self.amount(ty))
                .sum()
        } else {
            self.check.total
        }
    }

    /// Scales the damage by `factor`: every type of a hit but healing, or
    /// the amount of another cause.
    ///
    /// # Examples
    ///
    /// See the [module](self).
    pub fn scale(&mut self, factor: f32) {
        if self.check.cause == DamageCheck::IMPACT {
            for ty in DamageTypeNew::ALL {
                if ty != DamageTypeNew::Healing {
                    self.check.amounts[ty.index()] *= factor;
                }
            }
        } else {
            self.check.total *= factor;
        }
    }

    /// Scales a hit's damage of type `ty` by `factor`; does nothing for
    /// other causes.
    ///
    /// # Examples
    ///
    /// See the [module](self).
    pub fn scale_type(&mut self, ty: DamageTypeNew, factor: f32) {
        if self.check.cause == DamageCheck::IMPACT {
            self.check.amounts[ty.index()] *= factor;
        }
    }

    /// Takes all damage away: the health stays as it is. A hit still lands,
    /// with no damage, as against an immune target.
    ///
    /// # Examples
    ///
    /// See [`Damage::target`].
    pub fn cancel(&mut self) {
        self.scale(0.0);
    }
}

#[cfg(feature = "unstable")]
unsafe extern "system" fn run_damage<F>(check: *mut DamageCheck, user: *mut c_void)
where
    F: Fn(&mut Damage<'_>),
{
    // SAFETY: the loader passes a valid check for the duration of this call.
    let Some(check) = (unsafe { check.as_mut() }) else {
        return;
    };
    let mut working = *check;
    // SAFETY: `user` is the leaked `F` this function was registered with.
    let filter = unsafe { &*user.cast::<F>() };
    let done = crate::host::guard(
        "panic in a damage filter",
        || false,
        || {
            filter(&mut Damage {
                check: &mut working,
            });
            true
        },
    );
    if done {
        *check = working;
    }
}

#[cfg(feature = "unstable")]
impl Load<'_> {
    /// Runs `filter` on damage about to reach an entity's health in the
    /// server's world: hits by type, falls and the shroud. What it leaves is
    /// what the game applies. It runs on the game's worker threads, inside
    /// the systems that deal damage, in the dedicated server or a hosting
    /// client: it must not allocate, lock or log.
    ///
    /// Unstable: needs the `unstable` feature and may change in any release.
    ///
    /// # Errors
    ///
    /// [`Off`] after init or on a build without the damage sites.
    ///
    /// # Examples
    ///
    /// ```
    /// use enshwick::damage::{DamageCause, DamageTypeNew};
    ///
    /// fn init(load: &mut enshwick::Load<'_>) -> Result<(), enshwick::Off> {
    ///     load.on_damage(|damage| match damage.cause() {
    ///         // Falls hurt half as much, fire twice as much.
    ///         DamageCause::FallDamage => damage.scale(0.5),
    ///         DamageCause::Impact => damage.scale_type(DamageTypeNew::MagicalFire, 2.0),
    ///         _ => {}
    ///     })
    /// }
    /// ```
    pub fn on_damage<F>(&mut self, filter: F) -> Result<(), Off>
    where
        F: Fn(&mut Damage<'_>) + Send + Sync + 'static,
    {
        let host = self.host();
        crate::load::hand_over(
            filter,
            |user| (host.api().damage_filter)(host.handle(), run_damage::<F>, user),
            "damage filter",
        )
    }
}

#[cfg(test)]
#[cfg(feature = "unstable")]
mod tests {
    use super::*;

    #[test]
    fn every_cause_the_api_names_is_in_named() {
        let named: Vec<DamageCause> = (0..=u32::from(u8::MAX))
            .map(DamageCause::from_code)
            .filter(|cause| !matches!(cause, DamageCause::Other(_)))
            .collect();
        assert_eq!(named, DamageCause::NAMED);
    }
}