Skip to main content

o_centored_attack/
lib.rs

1//! Checked, deterministic vertical-strike resolution for 2D games.
2//!
3//! Positive Y points upward. A downward attack therefore produces a negative
4//! Y impulse, while an upward attack produces a positive Y impulse. Horizontal
5//! impulse is always zero.
6//!
7//! ```
8//! use o_centored_attack::{
9//!     AttackOutcome, AxisPoint, TargetBox, VerticalAttack, VerticalDirection,
10//! };
11//!
12//! let attack = VerticalAttack::new(
13//!     AxisPoint::new(0, 100),
14//!     VerticalDirection::Down,
15//!     100,
16//!     10,
17//!     1_000,
18//! )?;
19//! let target = TargetBox::new(AxisPoint::new(0, 20), 10, 10);
20//! assert!(matches!(attack.resolve(&target)?, AttackOutcome::Hit(_)));
21//! # Ok::<(), o_centored_attack::AttackError>(())
22//! ```
23
24use std::error::Error;
25use std::fmt::{self, Display, Formatter};
26
27/// Integer point in an axis-aligned 2D world.
28#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
29pub struct AxisPoint {
30    x: i64,
31    y: i64,
32}
33
34impl AxisPoint {
35    /// Creates a point.
36    pub const fn new(x: i64, y: i64) -> Self {
37        Self { x, y }
38    }
39
40    /// Horizontal coordinate.
41    pub const fn x(self) -> i64 {
42        self.x
43    }
44
45    /// Vertical coordinate.
46    pub const fn y(self) -> i64 {
47        self.y
48    }
49}
50
51/// Axis-aligned target bounds described by a center and half extents.
52#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
53pub struct TargetBox {
54    center: AxisPoint,
55    half_width: u64,
56    half_height: u64,
57}
58
59impl TargetBox {
60    /// Creates target bounds. Zero-sized extents are valid.
61    pub const fn new(center: AxisPoint, half_width: u64, half_height: u64) -> Self {
62        Self {
63            center,
64            half_width,
65            half_height,
66        }
67    }
68
69    /// Target center.
70    pub const fn center(self) -> AxisPoint {
71        self.center
72    }
73
74    /// Horizontal half extent.
75    pub const fn half_width(self) -> u64 {
76        self.half_width
77    }
78
79    /// Vertical half extent.
80    pub const fn half_height(self) -> u64 {
81        self.half_height
82    }
83}
84
85/// Vertical direction of travel and impulse.
86#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
87pub enum VerticalDirection {
88    /// Decreasing Y.
89    Down,
90    /// Increasing Y.
91    Up,
92}
93
94/// A vertical attack column originating at one point.
95#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
96pub struct VerticalAttack {
97    origin: AxisPoint,
98    direction: VerticalDirection,
99    reach: u64,
100    half_width: u64,
101    force: u64,
102}
103
104impl VerticalAttack {
105    /// Creates an attack with positive reach and force.
106    pub fn new(
107        origin: AxisPoint,
108        direction: VerticalDirection,
109        reach: u64,
110        half_width: u64,
111        force: u64,
112    ) -> Result<Self, AttackError> {
113        if reach == 0 {
114            return Err(AttackError::ZeroReach);
115        }
116        if force == 0 {
117            return Err(AttackError::ZeroForce);
118        }
119        Ok(Self {
120            origin,
121            direction,
122            reach,
123            half_width,
124            force,
125        })
126    }
127
128    /// Attack origin.
129    pub const fn origin(self) -> AxisPoint {
130        self.origin
131    }
132
133    /// Attack direction.
134    pub const fn direction(self) -> VerticalDirection {
135        self.direction
136    }
137
138    /// Maximum distance to the target's facing surface.
139    pub const fn reach(self) -> u64 {
140        self.reach
141    }
142
143    /// Horizontal half width around the attack axis.
144    pub const fn half_width(self) -> u64 {
145        self.half_width
146    }
147
148    /// Force before horizontal-centering falloff.
149    pub const fn force(self) -> u64 {
150        self.force
151    }
152
153    /// Resolves this attack against one target without mutating either value.
154    pub fn resolve(self, target: &TargetBox) -> Result<AttackOutcome, AttackError> {
155        let horizontal_span = self
156            .half_width
157            .checked_add(target.half_width)
158            .ok_or(AttackError::HorizontalSpanOverflow)?;
159        let horizontal_offset = self.origin.x.abs_diff(target.center.x);
160        let centering_basis_points = if horizontal_span == 0 {
161            if horizontal_offset != 0 {
162                return Ok(AttackOutcome::Miss(MissReason::HorizontalOutside));
163            }
164            10_000
165        } else {
166            if horizontal_offset >= horizontal_span {
167                return Ok(AttackOutcome::Miss(MissReason::HorizontalOutside));
168            }
169            let remaining = horizontal_span - horizontal_offset;
170            u16::try_from(u128::from(remaining) * 10_000 / u128::from(horizontal_span))
171                .map_err(|_| AttackError::ForceOverflow)?
172        };
173
174        let surface_y = facing_surface(*target, self.direction)?;
175        let distance = match self.direction {
176            VerticalDirection::Down => {
177                if self.origin.y < surface_y {
178                    return Ok(AttackOutcome::Miss(MissReason::TargetBehind));
179                }
180                self.origin.y.abs_diff(surface_y)
181            }
182            VerticalDirection::Up => {
183                if self.origin.y > surface_y {
184                    return Ok(AttackOutcome::Miss(MissReason::TargetBehind));
185                }
186                self.origin.y.abs_diff(surface_y)
187            }
188        };
189        if distance > self.reach {
190            return Ok(AttackOutcome::Miss(MissReason::BeyondReach));
191        }
192
193        let transmitted_force =
194            u128::from(self.force) * u128::from(centering_basis_points) / 10_000;
195        let transmitted_force =
196            u64::try_from(transmitted_force).map_err(|_| AttackError::ForceOverflow)?;
197        let impulse_y = match self.direction {
198            VerticalDirection::Down => -i128::from(transmitted_force),
199            VerticalDirection::Up => i128::from(transmitted_force),
200        };
201
202        Ok(AttackOutcome::Hit(Impact {
203            axis_x: self.origin.x,
204            contact_y: surface_y,
205            distance,
206            centering_basis_points,
207            transmitted_force,
208            impulse_y,
209        }))
210    }
211}
212
213fn facing_surface(target: TargetBox, direction: VerticalDirection) -> Result<i64, AttackError> {
214    let center = i128::from(target.center.y);
215    let offset = i128::from(target.half_height);
216    let surface = match direction {
217        VerticalDirection::Down => center + offset,
218        VerticalDirection::Up => center - offset,
219    };
220    i64::try_from(surface).map_err(|_| AttackError::SurfaceOverflow)
221}
222
223/// Result of resolving one attack against one target.
224#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
225pub enum AttackOutcome {
226    /// The target was contacted.
227    Hit(Impact),
228    /// The target was not contacted for this reason.
229    Miss(MissReason),
230}
231
232impl AttackOutcome {
233    /// Returns whether this outcome is a hit.
234    pub const fn is_hit(self) -> bool {
235        matches!(self, Self::Hit(_))
236    }
237
238    /// Returns hit details, if present.
239    pub const fn impact(self) -> Option<Impact> {
240        match self {
241            Self::Hit(impact) => Some(impact),
242            Self::Miss(_) => None,
243        }
244    }
245}
246
247/// Why a geometrically valid resolution did not hit.
248#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
249pub enum MissReason {
250    /// Horizontal separation was outside the combined half widths.
251    HorizontalOutside,
252    /// Target surface was opposite the attack direction.
253    TargetBehind,
254    /// Target surface was farther away than attack reach.
255    BeyondReach,
256}
257
258/// Contact and impulse details for a hit.
259#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
260pub struct Impact {
261    axis_x: i64,
262    contact_y: i64,
263    distance: u64,
264    centering_basis_points: u16,
265    transmitted_force: u64,
266    impulse_y: i128,
267}
268
269impl Impact {
270    /// X coordinate of the vertical attack axis.
271    pub const fn axis_x(self) -> i64 {
272        self.axis_x
273    }
274
275    /// Y coordinate of the target's facing surface.
276    pub const fn contact_y(self) -> i64 {
277        self.contact_y
278    }
279
280    /// Distance traveled to the facing surface.
281    pub const fn distance(self) -> u64 {
282        self.distance
283    }
284
285    /// Horizontal centeredness from 0 through 10,000 basis points.
286    pub const fn centering_basis_points(self) -> u16 {
287        self.centering_basis_points
288    }
289
290    /// Force after centeredness falloff.
291    pub const fn transmitted_force(self) -> u64 {
292        self.transmitted_force
293    }
294
295    /// Horizontal impulse, always zero by the vertical-strike principle.
296    pub const fn impulse_x(self) -> i128 {
297        0
298    }
299
300    /// Signed vertical impulse.
301    pub const fn impulse_y(self) -> i128 {
302        self.impulse_y
303    }
304}
305
306/// Invalid attack configuration or checked-arithmetic failure.
307#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
308#[non_exhaustive]
309pub enum AttackError {
310    /// Attack reach was zero.
311    ZeroReach,
312    /// Attack force was zero.
313    ZeroForce,
314    /// Combined horizontal half widths overflowed.
315    HorizontalSpanOverflow,
316    /// Target facing-surface coordinate overflowed.
317    SurfaceOverflow,
318    /// Centering or force conversion overflowed.
319    ForceOverflow,
320}
321
322impl Display for AttackError {
323    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
324        f.write_str(match self {
325            Self::ZeroReach => "vertical attack reach must be greater than zero",
326            Self::ZeroForce => "vertical attack force must be greater than zero",
327            Self::HorizontalSpanOverflow => "combined horizontal span overflowed",
328            Self::SurfaceOverflow => "target facing-surface coordinate overflowed",
329            Self::ForceOverflow => "centered force arithmetic overflowed",
330        })
331    }
332}
333
334impl Error for AttackError {}
335
336#[cfg(test)]
337mod tests {
338    use super::*;
339
340    fn downward(x: i64) -> VerticalAttack {
341        VerticalAttack::new(
342            AxisPoint::new(x, 100),
343            VerticalDirection::Down,
344            100,
345            10,
346            1_000,
347        )
348        .unwrap()
349    }
350
351    fn target(x: i64) -> TargetBox {
352        TargetBox::new(AxisPoint::new(x, 20), 10, 10)
353    }
354
355    #[test]
356    fn centered_downward_hit_transfers_full_vertical_force() {
357        let impact = downward(0).resolve(&target(0)).unwrap().impact().unwrap();
358        assert_eq!(impact.distance(), 70);
359        assert_eq!(impact.centering_basis_points(), 10_000);
360        assert_eq!(impact.transmitted_force(), 1_000);
361        assert_eq!(impact.impulse_x(), 0);
362        assert_eq!(impact.impulse_y(), -1_000);
363    }
364
365    #[test]
366    fn horizontal_offset_reduces_force() {
367        let impact = downward(10).resolve(&target(0)).unwrap().impact().unwrap();
368        assert_eq!(impact.centering_basis_points(), 5_000);
369        assert_eq!(impact.transmitted_force(), 500);
370    }
371
372    #[test]
373    fn horizontal_boundary_is_a_miss() {
374        assert_eq!(
375            downward(20).resolve(&target(0)).unwrap(),
376            AttackOutcome::Miss(MissReason::HorizontalOutside)
377        );
378    }
379
380    #[test]
381    fn target_beyond_reach_is_a_miss() {
382        let far = TargetBox::new(AxisPoint::new(0, -20), 10, 10);
383        assert_eq!(
384            downward(0).resolve(&far).unwrap(),
385            AttackOutcome::Miss(MissReason::BeyondReach)
386        );
387    }
388
389    #[test]
390    fn target_on_wrong_side_is_a_miss() {
391        let above = TargetBox::new(AxisPoint::new(0, 120), 10, 10);
392        assert_eq!(
393            downward(0).resolve(&above).unwrap(),
394            AttackOutcome::Miss(MissReason::TargetBehind)
395        );
396    }
397
398    #[test]
399    fn upward_hit_has_positive_impulse() {
400        let attack =
401            VerticalAttack::new(AxisPoint::new(0, -100), VerticalDirection::Up, 100, 5, 200)
402                .unwrap();
403        let target = TargetBox::new(AxisPoint::new(0, -20), 5, 10);
404        let impact = attack.resolve(&target).unwrap().impact().unwrap();
405        assert_eq!(impact.distance(), 70);
406        assert_eq!(impact.impulse_y(), 200);
407    }
408
409    #[test]
410    fn invalid_and_overflowing_geometry_is_rejected() {
411        assert_eq!(
412            VerticalAttack::new(AxisPoint::default(), VerticalDirection::Down, 0, 1, 1)
413                .unwrap_err(),
414            AttackError::ZeroReach
415        );
416        let attack = VerticalAttack::new(
417            AxisPoint::new(0, i64::MAX),
418            VerticalDirection::Down,
419            1,
420            u64::MAX,
421            1,
422        )
423        .unwrap();
424        let target = TargetBox::new(AxisPoint::new(0, i64::MAX), 1, 1);
425        assert_eq!(
426            attack.resolve(&target).unwrap_err(),
427            AttackError::HorizontalSpanOverflow
428        );
429
430        let attack = VerticalAttack::new(
431            AxisPoint::new(0, i64::MAX),
432            VerticalDirection::Down,
433            1,
434            0,
435            1,
436        )
437        .unwrap();
438        let target = TargetBox::new(AxisPoint::new(0, i64::MAX), 0, 1);
439        assert_eq!(
440            attack.resolve(&target).unwrap_err(),
441            AttackError::SurfaceOverflow
442        );
443    }
444}