o-centored-attack 0.1.0

Deterministic vertical-strike geometry and impulse resolution for 2D games
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
//! Checked, deterministic vertical-strike resolution for 2D games.
//!
//! Positive Y points upward. A downward attack therefore produces a negative
//! Y impulse, while an upward attack produces a positive Y impulse. Horizontal
//! impulse is always zero.
//!
//! ```
//! use o_centored_attack::{
//!     AttackOutcome, AxisPoint, TargetBox, VerticalAttack, VerticalDirection,
//! };
//!
//! let attack = VerticalAttack::new(
//!     AxisPoint::new(0, 100),
//!     VerticalDirection::Down,
//!     100,
//!     10,
//!     1_000,
//! )?;
//! let target = TargetBox::new(AxisPoint::new(0, 20), 10, 10);
//! assert!(matches!(attack.resolve(&target)?, AttackOutcome::Hit(_)));
//! # Ok::<(), o_centored_attack::AttackError>(())
//! ```

use std::error::Error;
use std::fmt::{self, Display, Formatter};

/// Integer point in an axis-aligned 2D world.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct AxisPoint {
    x: i64,
    y: i64,
}

impl AxisPoint {
    /// Creates a point.
    pub const fn new(x: i64, y: i64) -> Self {
        Self { x, y }
    }

    /// Horizontal coordinate.
    pub const fn x(self) -> i64 {
        self.x
    }

    /// Vertical coordinate.
    pub const fn y(self) -> i64 {
        self.y
    }
}

/// Axis-aligned target bounds described by a center and half extents.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct TargetBox {
    center: AxisPoint,
    half_width: u64,
    half_height: u64,
}

impl TargetBox {
    /// Creates target bounds. Zero-sized extents are valid.
    pub const fn new(center: AxisPoint, half_width: u64, half_height: u64) -> Self {
        Self {
            center,
            half_width,
            half_height,
        }
    }

    /// Target center.
    pub const fn center(self) -> AxisPoint {
        self.center
    }

    /// Horizontal half extent.
    pub const fn half_width(self) -> u64 {
        self.half_width
    }

    /// Vertical half extent.
    pub const fn half_height(self) -> u64 {
        self.half_height
    }
}

/// Vertical direction of travel and impulse.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum VerticalDirection {
    /// Decreasing Y.
    Down,
    /// Increasing Y.
    Up,
}

/// A vertical attack column originating at one point.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct VerticalAttack {
    origin: AxisPoint,
    direction: VerticalDirection,
    reach: u64,
    half_width: u64,
    force: u64,
}

impl VerticalAttack {
    /// Creates an attack with positive reach and force.
    pub fn new(
        origin: AxisPoint,
        direction: VerticalDirection,
        reach: u64,
        half_width: u64,
        force: u64,
    ) -> Result<Self, AttackError> {
        if reach == 0 {
            return Err(AttackError::ZeroReach);
        }
        if force == 0 {
            return Err(AttackError::ZeroForce);
        }
        Ok(Self {
            origin,
            direction,
            reach,
            half_width,
            force,
        })
    }

    /// Attack origin.
    pub const fn origin(self) -> AxisPoint {
        self.origin
    }

    /// Attack direction.
    pub const fn direction(self) -> VerticalDirection {
        self.direction
    }

    /// Maximum distance to the target's facing surface.
    pub const fn reach(self) -> u64 {
        self.reach
    }

    /// Horizontal half width around the attack axis.
    pub const fn half_width(self) -> u64 {
        self.half_width
    }

    /// Force before horizontal-centering falloff.
    pub const fn force(self) -> u64 {
        self.force
    }

    /// Resolves this attack against one target without mutating either value.
    pub fn resolve(self, target: &TargetBox) -> Result<AttackOutcome, AttackError> {
        let horizontal_span = self
            .half_width
            .checked_add(target.half_width)
            .ok_or(AttackError::HorizontalSpanOverflow)?;
        let horizontal_offset = self.origin.x.abs_diff(target.center.x);
        let centering_basis_points = if horizontal_span == 0 {
            if horizontal_offset != 0 {
                return Ok(AttackOutcome::Miss(MissReason::HorizontalOutside));
            }
            10_000
        } else {
            if horizontal_offset >= horizontal_span {
                return Ok(AttackOutcome::Miss(MissReason::HorizontalOutside));
            }
            let remaining = horizontal_span - horizontal_offset;
            u16::try_from(u128::from(remaining) * 10_000 / u128::from(horizontal_span))
                .map_err(|_| AttackError::ForceOverflow)?
        };

        let surface_y = facing_surface(*target, self.direction)?;
        let distance = match self.direction {
            VerticalDirection::Down => {
                if self.origin.y < surface_y {
                    return Ok(AttackOutcome::Miss(MissReason::TargetBehind));
                }
                self.origin.y.abs_diff(surface_y)
            }
            VerticalDirection::Up => {
                if self.origin.y > surface_y {
                    return Ok(AttackOutcome::Miss(MissReason::TargetBehind));
                }
                self.origin.y.abs_diff(surface_y)
            }
        };
        if distance > self.reach {
            return Ok(AttackOutcome::Miss(MissReason::BeyondReach));
        }

        let transmitted_force =
            u128::from(self.force) * u128::from(centering_basis_points) / 10_000;
        let transmitted_force =
            u64::try_from(transmitted_force).map_err(|_| AttackError::ForceOverflow)?;
        let impulse_y = match self.direction {
            VerticalDirection::Down => -i128::from(transmitted_force),
            VerticalDirection::Up => i128::from(transmitted_force),
        };

        Ok(AttackOutcome::Hit(Impact {
            axis_x: self.origin.x,
            contact_y: surface_y,
            distance,
            centering_basis_points,
            transmitted_force,
            impulse_y,
        }))
    }
}

fn facing_surface(target: TargetBox, direction: VerticalDirection) -> Result<i64, AttackError> {
    let center = i128::from(target.center.y);
    let offset = i128::from(target.half_height);
    let surface = match direction {
        VerticalDirection::Down => center + offset,
        VerticalDirection::Up => center - offset,
    };
    i64::try_from(surface).map_err(|_| AttackError::SurfaceOverflow)
}

/// Result of resolving one attack against one target.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum AttackOutcome {
    /// The target was contacted.
    Hit(Impact),
    /// The target was not contacted for this reason.
    Miss(MissReason),
}

impl AttackOutcome {
    /// Returns whether this outcome is a hit.
    pub const fn is_hit(self) -> bool {
        matches!(self, Self::Hit(_))
    }

    /// Returns hit details, if present.
    pub const fn impact(self) -> Option<Impact> {
        match self {
            Self::Hit(impact) => Some(impact),
            Self::Miss(_) => None,
        }
    }
}

/// Why a geometrically valid resolution did not hit.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum MissReason {
    /// Horizontal separation was outside the combined half widths.
    HorizontalOutside,
    /// Target surface was opposite the attack direction.
    TargetBehind,
    /// Target surface was farther away than attack reach.
    BeyondReach,
}

/// Contact and impulse details for a hit.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Impact {
    axis_x: i64,
    contact_y: i64,
    distance: u64,
    centering_basis_points: u16,
    transmitted_force: u64,
    impulse_y: i128,
}

impl Impact {
    /// X coordinate of the vertical attack axis.
    pub const fn axis_x(self) -> i64 {
        self.axis_x
    }

    /// Y coordinate of the target's facing surface.
    pub const fn contact_y(self) -> i64 {
        self.contact_y
    }

    /// Distance traveled to the facing surface.
    pub const fn distance(self) -> u64 {
        self.distance
    }

    /// Horizontal centeredness from 0 through 10,000 basis points.
    pub const fn centering_basis_points(self) -> u16 {
        self.centering_basis_points
    }

    /// Force after centeredness falloff.
    pub const fn transmitted_force(self) -> u64 {
        self.transmitted_force
    }

    /// Horizontal impulse, always zero by the vertical-strike principle.
    pub const fn impulse_x(self) -> i128 {
        0
    }

    /// Signed vertical impulse.
    pub const fn impulse_y(self) -> i128 {
        self.impulse_y
    }
}

/// Invalid attack configuration or checked-arithmetic failure.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum AttackError {
    /// Attack reach was zero.
    ZeroReach,
    /// Attack force was zero.
    ZeroForce,
    /// Combined horizontal half widths overflowed.
    HorizontalSpanOverflow,
    /// Target facing-surface coordinate overflowed.
    SurfaceOverflow,
    /// Centering or force conversion overflowed.
    ForceOverflow,
}

impl Display for AttackError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::ZeroReach => "vertical attack reach must be greater than zero",
            Self::ZeroForce => "vertical attack force must be greater than zero",
            Self::HorizontalSpanOverflow => "combined horizontal span overflowed",
            Self::SurfaceOverflow => "target facing-surface coordinate overflowed",
            Self::ForceOverflow => "centered force arithmetic overflowed",
        })
    }
}

impl Error for AttackError {}

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

    fn downward(x: i64) -> VerticalAttack {
        VerticalAttack::new(
            AxisPoint::new(x, 100),
            VerticalDirection::Down,
            100,
            10,
            1_000,
        )
        .unwrap()
    }

    fn target(x: i64) -> TargetBox {
        TargetBox::new(AxisPoint::new(x, 20), 10, 10)
    }

    #[test]
    fn centered_downward_hit_transfers_full_vertical_force() {
        let impact = downward(0).resolve(&target(0)).unwrap().impact().unwrap();
        assert_eq!(impact.distance(), 70);
        assert_eq!(impact.centering_basis_points(), 10_000);
        assert_eq!(impact.transmitted_force(), 1_000);
        assert_eq!(impact.impulse_x(), 0);
        assert_eq!(impact.impulse_y(), -1_000);
    }

    #[test]
    fn horizontal_offset_reduces_force() {
        let impact = downward(10).resolve(&target(0)).unwrap().impact().unwrap();
        assert_eq!(impact.centering_basis_points(), 5_000);
        assert_eq!(impact.transmitted_force(), 500);
    }

    #[test]
    fn horizontal_boundary_is_a_miss() {
        assert_eq!(
            downward(20).resolve(&target(0)).unwrap(),
            AttackOutcome::Miss(MissReason::HorizontalOutside)
        );
    }

    #[test]
    fn target_beyond_reach_is_a_miss() {
        let far = TargetBox::new(AxisPoint::new(0, -20), 10, 10);
        assert_eq!(
            downward(0).resolve(&far).unwrap(),
            AttackOutcome::Miss(MissReason::BeyondReach)
        );
    }

    #[test]
    fn target_on_wrong_side_is_a_miss() {
        let above = TargetBox::new(AxisPoint::new(0, 120), 10, 10);
        assert_eq!(
            downward(0).resolve(&above).unwrap(),
            AttackOutcome::Miss(MissReason::TargetBehind)
        );
    }

    #[test]
    fn upward_hit_has_positive_impulse() {
        let attack =
            VerticalAttack::new(AxisPoint::new(0, -100), VerticalDirection::Up, 100, 5, 200)
                .unwrap();
        let target = TargetBox::new(AxisPoint::new(0, -20), 5, 10);
        let impact = attack.resolve(&target).unwrap().impact().unwrap();
        assert_eq!(impact.distance(), 70);
        assert_eq!(impact.impulse_y(), 200);
    }

    #[test]
    fn invalid_and_overflowing_geometry_is_rejected() {
        assert_eq!(
            VerticalAttack::new(AxisPoint::default(), VerticalDirection::Down, 0, 1, 1)
                .unwrap_err(),
            AttackError::ZeroReach
        );
        let attack = VerticalAttack::new(
            AxisPoint::new(0, i64::MAX),
            VerticalDirection::Down,
            1,
            u64::MAX,
            1,
        )
        .unwrap();
        let target = TargetBox::new(AxisPoint::new(0, i64::MAX), 1, 1);
        assert_eq!(
            attack.resolve(&target).unwrap_err(),
            AttackError::HorizontalSpanOverflow
        );

        let attack = VerticalAttack::new(
            AxisPoint::new(0, i64::MAX),
            VerticalDirection::Down,
            1,
            0,
            1,
        )
        .unwrap();
        let target = TargetBox::new(AxisPoint::new(0, i64::MAX), 0, 1);
        assert_eq!(
            attack.resolve(&target).unwrap_err(),
            AttackError::SurfaceOverflow
        );
    }
}